solutions
listlengths
2
791
task_name
stringlengths
2
86
[ { "code": "---\ncategory:\n- Handicap\nfrom: http://rosettacode.org/wiki/Calendar_-_for_\"REAL\"_programmers\nnote: Date and time\n", "language": "00-META" }, { "code": ";Task:\nProvide an algorithm as per the [[Calendar]] task, except the entire code for the algorithm must be presented &nbsp; ''entirely without lowercase''. \n\nAlso - as per many 1969 era [[wp:line printer#Paper (forms) handling|line printer]]s - format the calendar to nicely fill a page that is 132 characters wide.\n\n(Hint: manually convert the code from the [[Calendar]] task to all UPPERCASE)\n\nThis task also is inspired by [http://www.ee.ryerson.ca/~elf/hack/realmen.html Real Programmers Don't Use PASCAL] by Ed Post, Datamation, volume 29 number 7, July 1983.\n THE REAL PROGRAMMER'S NATURAL HABITAT\n \"Taped to the wall is a line-printer Snoopy calender for the year 1969.\"\n\nMoreover this task is further inspired by the ''long lost'' corollary article titled:\n \"Real programmers think in UPPERCASE\"!\n\nNote: Whereas today we ''only'' need to worry about [[wp:ASCII|ASCII]], [[wp:UTF-8|UTF-8]], [[wp:UTF-16/UCS-2|UTF-16]], [[wp:UTF-32/UCS-4|UTF-32]], [[wp:UTF-7|UTF-7]] and [[wp:UTF-EBCDIC|UTF-EBCDIC]] encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into [[wp:36-bit|36-bit]] words as 6 lots of [[wp:6-bit|6-bit]] characters. More extreme words sizes include [[wp:60-bit|60-bit]] words of the [[wp:CDC 6000 series|CDC 6000 series]] computers. The Soviets even had a national character set that was inclusive of all\n[[wp:GOST_10859#4-bit code: Binary coded decimal|4-bit]],\n[[wp:GOST_10859#5-bit code: with BCD & mathematical operators|5-bit]],\n[[wp:GOST_10859#6-bit code: with only Cyrillic upper case letters|6-bit]] &\n[[wp:GOST_10859#7-bit code: Cyrillic & Latin upper case letters|7-bit]] depending on how the file was opened... '''And''' one rogue Soviet university went further and built a [http://www.computer-museum.ru/english/setun.htm 1.5-bit] based computer.\n\nOf course... as us [[wp:Baby-Boom Generation|Boomers]] have turned into [[wp:Geezer|Geezer]]s we have become [[wp:All_caps#Computing|HARD OF HEARING]], \nand suffer from chronic [[wp:Presbyopia|Presbyopia]], hence programming in UPPERCASE \nis less to do with computer architecture and more to do with practically. :-)\n\nFor economy of size, do not actually include Snoopy generation \nin either the code or the output, instead just output a place-holder. \n\nFYI: a nice ASCII art file of Snoopy can be found at [http://www.textfiles.com/artscene/asciiart/cursepic.art textfiles.com]. Save with a .txt extension.\n\n'''Trivia:''' The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed ''minuscule'' letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, ''majuscule'' letters, ended up in the harder to reach upper cases.\n<br><br>\n", "language": "00-TASK" }, { "code": "* CALENDAR FOR REAL PROGRAMMERS 05/03/2017\nCALENDAR CSECT\n USING CALENDAR,R13 BASE REGISTER\n B 72(R15) SKIP MY SAVEAREA\n DC 17F'0' MY SAVEAREA\n STM R14,R12,12(R13) SAVE CALLER'S REGISTERS\n ST R13,4(R15) LINK BACKWARD\n ST R15,8(R13) LINK FORWARD\n LR R13,R15 SET ADDRESSABILITY\n L R4,YEAR YEAR\n SRDA R4,32 .\n D R4,=F'4' YEAR//4\n LTR R4,R4 IF YEAR//4=0\n BNZ LYNOT\n L R4,YEAR YEAR\n SRDA R4,32 .\n D R4,=F'100' YEAR//100\n LTR R4,R4 IF YEAR//100=0\n BNZ LY\n L R4,YEAR YEAR\n SRDA R4,32 .\n D R4,=F'400' IF YEAR//400\n LTR R4,R4 IF YEAR//400=0\n BNZ LYNOT\nLY MVC ML+2,=H'29' ML(2)=29 LEAPYEAR\nLYNOT SR R10,R10 LTD1=0\n LA R6,1 I=1\nLOOPI1 C R6,=F'31' DO I=1 TO 31\n BH ELOOPI1\n XDECO R6,XDEC EDIT I\n LA R14,TD1 TD1\n AR R14,R10 TD1+LTD1\n MVC 0(3,R14),XDEC+9 SUB(TD1,LTD1+1,3)=PIC(I,3)\n LA R10,3(R10) LTD1+3\n LA R6,1(R6) I=I+1\n B LOOPI1\nELOOPI1 LA R6,1 I=1\nLOOPI2 C R6,=F'12' DO I=1 TO 12\n BH ELOOPI2\n ST R6,M M=I\n MVC D,=F'1' D=1\n MVC YY,YEAR YY=YEAR\n L R4,M M\n C R4,=F'3' IF M<3\n BNL GE3\n L R2,M M\n LA R2,12(R2) M+12\n ST R2,M M=M+12\n L R2,YY YY\n BCTR R2,0 YY-1\n ST R2,YY YY=YY-1\nGE3 L R2,YY YY\n LR R1,R2 YY\n SRA R1,2 YY/4\n AR R2,R1 YY+(YY/4)\n L R4,YY YY\n SRDA R4,32 .\n D R4,=F'100' YY/100\n SR R2,R5 YY+(YY/4)-(YY/100)\n L R4,YY YY\n SRDA R4,32 .\n D R4,=F'400' YY/400\n AR R2,R5 YY+(YY/4)-(YY/100)+(YY/400)\n A R2,D R2=YY+(YY/4)-(YY/100)+(YY/400)+D\n LA R5,153 153\n M R4,M 153*M\n LA R5,8(R5) 153*M+8\n D R4,=F'5' (153*M+8)/5\n AR R5,R2 ((153*M+8)/5+R2\n LA R4,0 .\n D R4,=F'7' R4=MOD(R5,7) 0=SUN 1=MON ... 6=SAT\n LTR R4,R4 IF J=0\n BNZ JNE0\n LA R4,7 J=7\nJNE0 BCTR R4,0 J-1\n MH R4,=H'3' J*3\n LR R10,R4 J1=J*3\n LR R1,R6 I\n SLA R1,1 *2\n LH R11,ML-2(R1) ML(I)\n MH R11,=H'3' J2=ML(I)*3\n MVC TD2,BLANK TD2=' '\n LA R4,TD1 @TD1\n LR R5,R11 J2\n LA R2,TD2 @TD2\n AR R2,R10 @TD2+J1\n LR R3,R5 J2\n MVCL R2,R4 SUB(TD2,J1+1,J2)=SUB(TD1,1,J2)\n LR R1,R6 I\n MH R1,=H'144' *144\n LA R14,DA-144(R1) @DA(I)\n MVC 0(144,R14),TD2 DA(I)=TD2\n LA R6,1(R6) I=I+1\n B LOOPI2\nELOOPI2 XPRNT SNOOPY,132 PRINT SNOOPY\n L R1,YEAR YEAR\n XDECO R1,PG+56 EDIT YEAR\n XPRNT PG,L'PG PRINT YEAR\n MVC WDLINE,BLANK WDLINE=' '\n LA R10,1 LWDLINE=1\n LA R8,1 K=1\nLOOPK3 C R8,=F'6' DO K=1 TO 6\n BH ELOOPK3\n LA R4,WDLINE @WDLINE\n AR R4,R10 +LWDLINE\n MVC 0(20,R4),WDNA SUB(WDLINE,LWDLINE+1,20)=WDNA\n LA R10,20(R10) LWDLINE=LWDLINE+20\n C R8,=F'6' IF K<6\n BNL ITERK3\n LA R10,2(R10) LWDLINE=LWDLINE+2\nITERK3 LA R8,1(R8) K=K+1\n B LOOPK3\nELOOPK3 LA R6,1 I=1\nLOOPI4 C R6,=F'12' DO I=1 TO 12 BY 6\n BH ELOOPI4\n MVC MOLINE,BLANK MOLINE=' '\n LA R10,6 LMOLINE=6\n LR R8,R6 K=I\nLOOPK4 LA R2,5(R6) I+5\n CR R8,R2 DO K=I TO I+5\n BH ELOOPK4\n LR R1,R8 K\n MH R1,=H'10' *10\n LA R3,MO-10(R1) MO(K)\n LA R4,MOLINE @MOLINE\n AR R4,R10 +LMOLINE\n MVC 0(10,R4),0(R3) SUB(MOLINE,LMOLINE+1,10)=MO(K)\n LA R10,22(R10) LMOLINE=LMOLINE+22\n LA R8,1(R8) K=K+1\n B LOOPK4\nELOOPK4 XPRNT MOLINE,L'MOLINE PRINT MONTHS\n XPRNT WDLINE,L'WDLINE PRINT DAYS OF WEEK\n LA R7,1 J=1\nLOOPJ4 C R7,=F'106' DO J=1 TO 106 BY 21\n BH ELOOPJ4\n MVC PG,BLANK CLEAR BUFFER\n LA R9,PG PGI=0\n LR R8,R6 K=I\nLOOPK5 LA R2,5(R6) I+5\n CR R8,R2 DO K=I TO I+5\n BH ELOOPK5\n LR R1,R8 K\n MH R1,=H'144' *144\n LA R4,DA-144(R1) DA(K)\n BCTR R4,0 -1\n AR R4,R7 +J\n MVC 0(21,R9),0(R4) SUBSTR(DA(K),J,21)\n LA R9,22(R9) PGI=PGI+22\n LA R8,1(R8) K=K+1\n B LOOPK5\nELOOPK5 XPRNT PG,L'PG PRINT BUFFER\n LA R7,21(R7) J=J+21\n B LOOPJ4\nELOOPJ4 LA R6,6(R6) I=I+6\n B LOOPI4\nELOOPI4 L R13,4(0,R13) RESTORE PREVIOUS SAVEAREA POINTER\n LM R14,R12,12(R13) RESTORE CALLER'S REGISTERS\n XR R15,R15 SET RETURN CODE TO 0\n BR R14 RETURN TO CALLER\nSNOOPY DC CL57' ',CL18'INSERT SNOOPY HERE',CL57' '\nYEAR DC F'1969' <== 1969\nMO DC CL10' JANUARY ',CL10' FEBRUARY ',CL10' MARCH '\n DC CL10' APRIL ',CL10' MAY ',CL10' JUNE '\n DC CL10' JULY ',CL10' AUGUST ',CL10'SEPTEMBER '\n DC CL10' OCTOBER ',CL10' NOVEMBER ',CL10' DECEMBER '\nML DC H'31',H'28',H'31',H'30',H'31',H'30'\n DC H'31',H'31',H'30',H'31',H'30',H'31'\nWDNA DC CL20'MO TU WE TH FR SA SU'\nM DS F\nD DS F\nYY DS F\nTD1 DS CL93\nTD2 DS CL144\nMOLINE DS CL132\nWDLINE DS CL132\nPG DC CL132' ' BUFFER FOR THE LINE PRINTER\nXDEC DS CL12\nBLANK DC CL144' '\nDA DS 12CL144\n YREGS\n END CALENDAR\n", "language": "360-Assembly" }, { "code": "WITH PRINTABLE_CALENDAR;\n\nPROCEDURE REAL_CAL IS\n\n C: PRINTABLE_CALENDAR.CALENDAR := PRINTABLE_CALENDAR.INIT_132\n ((WEEKDAY_REP =>\n \"MO TU WE TH FR SA SO\",\n MONTH_REP =>\n (\" JANUARY \", \" FEBRUARY \",\n \" MARCH \", \" APRIL \",\n \" MAY \", \" JUNE \",\n \" JULY \", \" AUGUST \",\n \" SEPTEMBER \", \" OCTOBER \",\n \" NOVEMBER \", \" DECEMBER \")\n ));\n\nBEGIN\n C.PRINT_LINE_CENTERED(\"[SNOOPY]\");\n C.NEW_LINE;\n C.PRINT(1969, \"NINETEEN-SIXTY-NINE\");\nEND REAL_CAL;\n", "language": "Ada" }, { "code": "'PR' QUOTE 'PR'\n\n'PROC' PRINT CALENDAR = ('INT' YEAR, PAGE WIDTH)'VOID': 'BEGIN'\n\n ()'STRING' MONTH NAMES = (\n \"JANUARY\",\"FEBRUARY\",\"MARCH\",\"APRIL\",\"MAY\",\"JUNE\",\n \"JULY\",\"AUGUST\",\"SEPTEMBER\",\"OCTOBER\",\"NOVEMBER\",\"DECEMBER\"),\n WEEKDAY NAMES = (\"SU\",\"MO\",\"TU\",\"WE\",\"TH\",\"FR\",\"SA\");\n 'FORMAT' WEEKDAY FMT = $G,N('UPB' WEEKDAY NAMES - 'LWB' WEEKDAY NAMES)(\" \"G)$;\n\n # 'JUGGLE' THE CALENDAR FORMAT TO FIT THE PRINTER/SCREEN WIDTH #\n 'INT' DAY WIDTH = 'UPB' WEEKDAY NAMES(1), DAY GAP=1;\n 'INT' MONTH WIDTH = (DAY WIDTH+DAY GAP) * 'UPB' WEEKDAY NAMES-1;\n 'INT' MONTH HEADING LINES = 2;\n 'INT' MONTH LINES = (31 'OVER' 'UPB' WEEKDAY NAMES+MONTH HEADING LINES+2); # +2 FOR HEAD/TAIL WEEKS #\n 'INT' YEAR COLS = (PAGE WIDTH+1) 'OVER' (MONTH WIDTH+1);\n 'INT' YEAR ROWS = ('UPB' MONTH NAMES-1)'OVER' YEAR COLS + 1;\n 'INT' MONTH GAP = (PAGE WIDTH - YEAR COLS*MONTH WIDTH + 1)'OVER' YEAR COLS;\n 'INT' YEAR WIDTH = YEAR COLS*(MONTH WIDTH+MONTH GAP)-MONTH GAP;\n 'INT' YEAR LINES = YEAR ROWS*MONTH LINES;\n\n 'MODE' 'MONTHBOX' = (MONTH LINES, MONTH WIDTH)'CHAR';\n 'MODE' 'YEARBOX' = (YEAR LINES, YEAR WIDTH)'CHAR';\n\n 'INT' WEEK START = 1; # 'SUNDAY' #\n\n 'PROC' DAYS IN MONTH = ('INT' YEAR, MONTH)'INT':\n 'CASE' MONTH 'IN' 31,\n 'IF' YEAR 'MOD' 4 'EQ' 0 'AND' YEAR 'MOD' 100 'NE' 0 'OR' YEAR 'MOD' 400 'EQ' 0 'THEN' 29 'ELSE' 28 'FI',\n 31, 30, 31, 30, 31, 31, 30, 31, 30, 31\n 'ESAC';\n\n 'PROC' DAY OF WEEK = ('INT' YEAR, MONTH, DAY)'INT': 'BEGIN'\n # 'DAY' OF THE WEEK BY 'ZELLER'’S 'CONGRUENCE' ALGORITHM FROM 1887 #\n 'INT' Y := YEAR, M := MONTH, D := DAY, C;\n 'IF' M <= 2 'THEN' M +:= 12; Y -:= 1 'FI';\n C := Y 'OVER' 100;\n Y 'MODAB' 100;\n (D - 1 + ((M + 1) * 26) 'OVER' 10 + Y + Y 'OVER' 4 + C 'OVER' 4 - 2 * C) 'MOD' 7\n 'END';\n\n 'MODE' 'SIMPLEOUT' = 'UNION'('STRING', ()'STRING', 'INT');\n\n 'PROC' CPUTF = ('REF'()'CHAR' OUT, 'FORMAT' FMT, 'SIMPLEOUT' ARGV)'VOID':'BEGIN'\n 'FILE' F; 'STRING' S; ASSOCIATE(F,S);\n PUTF(F, (FMT, ARGV));\n OUT(:'UPB' S):=S;\n CLOSE(F)\n 'END';\n\n 'PROC' MONTH REPR = ('INT' YEAR, MONTH)'MONTHBOX':'BEGIN'\n 'MONTHBOX' MONTH BOX; 'FOR' LINE 'TO' 'UPB' MONTH BOX 'DO' MONTH BOX(LINE,):=\" \"* 2 'UPB' MONTH BOX 'OD';\n 'STRING' MONTH NAME = MONTH NAMES(MONTH);\n\n # CENTER THE TITLE #\n CPUTF(MONTH BOX(1,(MONTH WIDTH - 'UPB' MONTH NAME ) 'OVER' 2+1:), $G$, MONTH NAME);\n CPUTF(MONTH BOX(2,), WEEKDAY FMT, WEEKDAY NAMES);\n\n 'INT' FIRST DAY := DAY OF WEEK(YEAR, MONTH, 1);\n 'FOR' DAY 'TO' DAYS IN MONTH(YEAR, MONTH) 'DO'\n 'INT' LINE = (DAY+FIRST DAY-WEEK START) 'OVER' 'UPB' WEEKDAY NAMES + MONTH HEADING LINES + 1;\n 'INT' CHAR =((DAY+FIRST DAY-WEEK START) 'MOD' 'UPB' WEEKDAY NAMES)*(DAY WIDTH+DAY GAP) + 1;\n CPUTF(MONTH BOX(LINE,CHAR:CHAR+DAY WIDTH-1),$G(-DAY WIDTH)$, DAY)\n 'OD';\n MONTH BOX\n 'END';\n\n 'PROC' YEAR REPR = ('INT' YEAR)'YEARBOX':'BEGIN'\n 'YEARBOX' YEAR BOX;\n 'FOR' LINE 'TO' 'UPB' YEAR BOX 'DO' YEAR BOX(LINE,):=\" \"* 2 'UPB' YEAR BOX 'OD';\n 'FOR' MONTH ROW 'FROM' 0 'TO' YEAR ROWS-1 'DO'\n 'FOR' MONTH COL 'FROM' 0 'TO' YEAR COLS-1 'DO'\n 'INT' MONTH = MONTH ROW * YEAR COLS + MONTH COL + 1;\n 'IF' MONTH > 'UPB' MONTH NAMES 'THEN'\n DONE\n 'ELSE'\n 'INT' MONTH COL WIDTH = MONTH WIDTH+MONTH GAP;\n YEAR BOX(\n MONTH ROW*MONTH LINES+1 : (MONTH ROW+1)*MONTH LINES,\n MONTH COL*MONTH COL WIDTH+1 : (MONTH COL+1)*MONTH COL WIDTH-MONTH GAP\n ) := MONTH REPR(YEAR, MONTH)\n 'FI'\n 'OD'\n 'OD';\n DONE: YEAR BOX\n 'END';\n\n 'INT' CENTER = (YEAR COLS*(MONTH WIDTH+MONTH GAP) - MONTH GAP - 1) 'OVER' 2;\n 'INT' INDENT = (PAGE WIDTH - YEAR WIDTH) 'OVER' 2;\n\n PRINTF((\n $N(INDENT + CENTER - 9)K G L$, \"(INSERT SNOOPY HERE)\",\n $N(INDENT + CENTER - 1)K 4D L$, YEAR, $L$,\n $N(INDENT)K N(YEAR WIDTH)(G) L$, YEAR REPR(YEAR)\n ))\n'END';\n\nMAIN: 'BEGIN'\n'CO' INSPIRED BY HTTP://WWW.EE.RYERSON.CA/~ELF/hack/realmen.html\n REAL PROGRAMMERS DONT USE PASCAL - ED POST\n DATAMATION, VOLUME 29 NUMBER 7, JULY 1983\n THE REAL PROGRAMMERS NATURAL HABITAT\n\"TAPED TO THE WALL IS A LINE-PRINTER SNOOPY CALENDER FOR THE YEAR 1969\"\n'CO'\n 'INT' MANKIND STEPPED ON THE MOON = 1969,\n LINE PRINTER WIDTH = 132; # AS AT 1969! #\n PRINT CALENDAR(MANKIND STEPPED ON THE MOON, LINE PRINTER WIDTH)\n'END'\n", "language": "ALGOL-68" }, { "code": "CALENDAR(YR){\n\tLASTDAY := [], DAY := []\n\tTITLES =\n\t(LTRIM\n\t______JANUARY_________________FEBRUARY_________________MARCH_______\n\t_______APRIL____________________MAY____________________JUNE________\n\t________JULY___________________AUGUST_________________SEPTEMBER_____\n\t______OCTOBER_________________NOVEMBER________________DECEMBER______\n\t)\n\tSTRINGSPLIT, TITLE, TITLES, % CHR(10)\n\tRES := \"________________________________\" YR CHR(13) CHR(10)\n\n\tLOOP 4 {\t\t\t\t\t\t\t\t\t\t\t\t; 4 VERTICAL SECTIONS\n\t\tDAY[1]:=YR SUBSTR(\"0\" A_INDEX*3 -2, -1) 01\n\t\tDAY[2]:=YR SUBSTR(\"0\" A_INDEX*3 -1, -1) 01\n\t\tDAY[3]:=YR SUBSTR(\"0\" A_INDEX*3 , -1) 01\n\t\tRES .= CHR(13) CHR(10) TITLE%A_INDEX% CHR(13) CHR(10) \"SU MO TU WE TH FR SA SU MO TU WE TH FR SA SU MO TU WE TH FR SA\"\n\t\tLOOP , 6 {\t\t\t\t\t\t\t\t\t\t\t; 6 WEEKS MAX PER MONTH\n\t\t\tWEEK := A_INDEX, RES .= CHR(13) CHR(10)\n\t\t\tLOOP, 21 {\t\t\t\t\t\t\t\t\t\t; 3 WEEKS TIMES 7 DAYS\n\t\t\t\tMON := CEIL(A_INDEX/7), THISWD := MOD(A_INDEX-1,7)+1\n\t\t\t\tFORMATTIME, WD, % DAY[MON], WDAY\n\t\t\t\t;~ MSGBOX % WD\n\t\t\t\tFORMATTIME, DD, % DAY[MON], % CHR(100) CHR(100)\n\t\t\t\tIF (WD>THISWD) {\n\t\t\t\t\tRES .= \"__ \"\n\t\t\t\t\tCONTINUE\n\t\t\t\t}\n\t\t\t\tDD := ((WEEK>3) && DD <10) ? \"__\" : DD, RES .= DD \" \", LASTDAY[MON] := DAY[MON], DAY[MON] +=1, D\n\t\t\t\tRES .= ((WD=7) && A_INDEX < 21) ? \"___\" : \"\"\n\t\t\t\tFORMATTIME, DD, % DAY[MON], % CHR(100) CHR(100)\n\t\t\t}\n\t\t}\n\t\tRES .= CHR(13) CHR(10)\n\t}\n\tSTRINGREPLACE, RES, RES,_,%A_SPACE%, ALL\n\tSTRINGREPLACE, RES, RES,%A_SPACE%0,%A_SPACE%%A_SPACE%, ALL\n\tRETURN RES\n}\n", "language": "AutoHotkey" }, { "code": "EXAMPLES:\nGUI, FONT,S8, COURIER\nGUI, ADD, EDIT, VYR W40 R1 LIMIT4 NUMBER, 1969\nGUI, ADD, EDIT, VEDIT2 W580 R38\nGUI, ADD, BUTTON, DEFAULT HIDDEN GSUBMIT\nGUI, SHOW\n\nSUBMIT:\nGUI, SUBMIT, NOHIDE\nGUICONTROL,, EDIT2, % CALENDAR(YR)\nRETURN\n\nGUIESCAPE:\nGUICLOSE:\nEXITAPP\nRETURN\n", "language": "AutoHotkey" }, { "code": "DECLARE MON$[] = { \"JANUARY\", \"FEBRUARY\", \"MARCH\", \"APRIL\", \"MAY\", \"JUNE\", \"JULY\", \"AUGUST\", \"SEPTEMBER\", \"OCTOBER\", \"NOVEMBER\", \"DECEMBER\" }\nDECLARE MON[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }\nY$ = \"1969\"\n' Leap year\nINCR MON[1], IIF(MOD(VAL(Y$), 4) = 0 OR MOD(VAL(Y$), 100) = 0 AND MOD(VAL(Y$), 400) <> 0, 1, 0)\nPRINT ALIGN$(\"[SNOOPY HERE]\", 132, 2)\nPRINT ALIGN$(Y$, 132, 2)\nFOR NR = 0 TO 11\n ROW = 3\n GOTOXY 1+(NR %6)*22, ROW+(NR/6)*9\n PRINT ALIGN$(MON$[NR], 21, 2);\n INCR ROW\n GOTOXY 1+(NR %6)*22, ROW+(NR/6)*9\n PRINT ALIGN$(\"MO TU WE TH FR SA SU\", 21, 2);\n INCR ROW\n ' Each day\n FOR D = 1 TO MON[NR]\n ' Zeller\n J = VAL(LEFT$(Y$, 2))\n K = VAL(MID$(Y$, 3, 2))\n M = NR+1\n IF NR < 2 THEN\n INCR M, 12\n DECR K\n END IF\n H = (D + ((M+1)*26)/10 + K + (K/4) + (J/4) + 5*J)\n DAYNR = MOD(H, 7) - 2\n IF DAYNR < 0 THEN INCR DAYNR, 7\n IF DAYNR = 0 AND D > 1 THEN INCR ROW\n GOTOXY 1+(NR %6)*22+DAYNR*3, ROW+(NR/6)*9\n PRINT D;\n NEXT\nNEXT\n", "language": "BaCon" }, { "code": " VDU 23,22,1056;336;8,16,16,128\n\n YEAR = 1969\n PRINT TAB(62) \"[SNOOPY]\" TAB(64); YEAR\n DIM DOM(5), MJD(5), DM(5), MONTH$(11)\n DAYS$ = \"SU MO TU WE TH FR SA\"\n MONTH$() = \"JANUARY\", \"FEBRUARY\", \"MARCH\", \"APRIL\", \"MAY\", \"JUNE\", \\\n \\ \"JULY\", \"AUGUST\", \"SEPTEMBER\", \"OCTOBER\", \"NOVEMBER\", \"DECEMBER\"\n\n FOR MONTH = 1 TO 7 STEP 6\n PRINT\n FOR COL = 0 TO 5\n MJD(COL) = FNMJD(1, MONTH + COL, YEAR)\n MONTH$ = MONTH$(MONTH + COL - 1)\n PRINT TAB(COL*22 + 11 - LEN(MONTH$)/2) MONTH$;\n NEXT\n FOR COL = 0 TO 5\n PRINT TAB(COL*22 + 1) DAYS$;\n DM(COL) = FNDIM(MONTH + COL, YEAR)\n NEXT\n DOM() = 1\n COL = 0\n REPEAT\n DOW = FNDOW(MJD(COL))\n IF DOM(COL)<=DM(COL) THEN\n PRINT TAB(COL*22 + DOW*3 + 1); DOM(COL);\n DOM(COL) += 1\n MJD(COL) += 1\n ENDIF\n IF DOW=6 OR DOM(COL)>DM(COL) COL = (COL + 1) MOD 6\n UNTIL DOM(0)>DM(0) AND DOM(1)>DM(1) AND DOM(2)>DM(2) AND \\\n \\ DOM(3)>DM(3) AND DOM(4)>DM(4) AND DOM(5)>DM(5)\n PRINT\n NEXT\n END\n\n DEF FNMJD(D%,M%,Y%) : M% -= 3 : IF M% < 0 M% += 12 : Y% -= 1\n = D% + (153*M%+2)DIV5 + Y%*365 + Y%DIV4 - Y%DIV100 + Y%DIV400 - 678882\n\n DEF FNDOW(J%) = (J%+2400002) MOD 7\n\n DEF FNDIM(M%,Y%)\n CASE M% OF\n WHEN 2: = 28 + (Y%MOD4=0) - (Y%MOD100=0) + (Y%MOD400=0)\n WHEN 4,6,9,11: = 30\n OTHERWISE = 31\n ENDCASE\n", "language": "BBC-BASIC" }, { "code": "/* UPPER CASE ONLY VERSION OF THE ORIGINAL CALENDAR.C, CHANGES MOSTLY TO AVOID NEEDING #INCLUDES */\n/* ERROR MESSAGES GO TO STDOUT TO SLIGHTLY SIMPLIFY THE I/O HANDLING */\n/* WHEN COMPILING THIS, THE COMMAND LINE SHOULD SPECIFY -D OPTIONS FOR THE FOLLOWING WORDS: */\n/* STRUCT, VOID, INT, CHAR, CONST, MAIN, IF, ELSE, WHILE, FOR, DO, BREAK, RETURN, PUTCHAR */\n/* THE VALUE OF EACH MACRO SHOULD BE THE WORD IN LOWER-CASE */\n\nINT PUTCHAR(INT);\n\nINT WIDTH = 80, YEAR = 1969;\nINT COLS, LEAD, GAP;\n\nCONST CHAR *WDAYS[] = { \"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\" };\nSTRUCT MONTHS {\n CONST CHAR *NAME;\n INT DAYS, START_WDAY, AT;\n} MONTHS[12] = {\n { \"JANUARY\", 31, 0, 0 },\n { \"FEBRUARY\", 28, 0, 0 },\n { \"MARCH\", 31, 0, 0 },\n { \"APRIL\", 30, 0, 0 },\n { \"MAY\", 31, 0, 0 },\n { \"JUNE\", 30, 0, 0 },\n { \"JULY\", 31, 0, 0 },\n { \"AUGUST\", 31, 0, 0 },\n { \"SEPTEMBER\", 30, 0, 0 },\n { \"OCTOBER\", 31, 0, 0 },\n { \"NOVEMBER\", 30, 0, 0 },\n { \"DECEMBER\", 31, 0, 0 }\n};\n\nVOID SPACE(INT N) { WHILE (N-- > 0) PUTCHAR(' '); }\nVOID PRINT(CONST CHAR * S){ WHILE (*S != '\\0') { PUTCHAR(*S++); } }\nINT STRLEN(CONST CHAR * S)\n{\n INT L = 0;\n WHILE (*S++ != '\\0') { L ++; };\nRETURN L;\n}\nINT ATOI(CONST CHAR * S)\n{\n INT I = 0;\n INT SIGN = 1;\n CHAR C;\n WHILE ((C = *S++) != '\\0') {\n IF (C == '-')\n SIGN *= -1;\n ELSE {\n I *= 10;\n I += (C - '0');\n }\n }\nRETURN I * SIGN;\n}\n\nVOID INIT_MONTHS(VOID)\n{\n INT I;\n\n IF ((!(YEAR % 4) && (YEAR % 100)) || !(YEAR % 400))\n MONTHS[1].DAYS = 29;\n\n YEAR--;\n MONTHS[0].START_WDAY\n = (YEAR * 365 + YEAR/4 - YEAR/100 + YEAR/400 + 1) % 7;\n\n FOR (I = 1; I < 12; I++)\n MONTHS[I].START_WDAY =\n (MONTHS[I-1].START_WDAY + MONTHS[I-1].DAYS) % 7;\n\n COLS = (WIDTH + 2) / 22;\n WHILE (12 % COLS) COLS--;\n GAP = COLS - 1 ? (WIDTH - 20 * COLS) / (COLS - 1) : 0;\n IF (GAP > 4) GAP = 4;\n LEAD = (WIDTH - (20 + GAP) * COLS + GAP + 1) / 2;\n YEAR++;\n}\n\nVOID PRINT_ROW(INT ROW)\n{\n INT C, I, FROM = ROW * COLS, TO = FROM + COLS;\n SPACE(LEAD);\n FOR (C = FROM; C < TO; C++) {\n I = STRLEN(MONTHS[C].NAME);\n SPACE((20 - I)/2);\n PRINT(MONTHS[C].NAME);\n SPACE(20 - I - (20 - I)/2 + ((C == TO - 1) ? 0 : GAP));\n }\n PUTCHAR('\\012');\n\n SPACE(LEAD);\n FOR (C = FROM; C < TO; C++) {\n FOR (I = 0; I < 7; I++) {\n PRINT(WDAYS[I]);\n PRINT(I == 6 ? \"\" : \" \");\n }\n IF (C < TO - 1) SPACE(GAP);\n ELSE PUTCHAR('\\012');\n }\n\n WHILE (1) {\n FOR (C = FROM; C < TO; C++)\n IF (MONTHS[C].AT < MONTHS[C].DAYS) BREAK;\n IF (C == TO) BREAK;\n\n SPACE(LEAD);\n FOR (C = FROM; C < TO; C++) {\n FOR (I = 0; I < MONTHS[C].START_WDAY; I++) SPACE(3);\n WHILE(I++ < 7 && MONTHS[C].AT < MONTHS[C].DAYS) {\n INT MM = ++MONTHS[C].AT;\n PUTCHAR((MM < 10) ? ' ' : '0' + (MM /10));\n PUTCHAR('0' + (MM %10));\n IF (I < 7 || C < TO - 1) PUTCHAR(' ');\n }\n WHILE (I++ <= 7 && C < TO - 1) SPACE(3);\n IF (C < TO - 1) SPACE(GAP - 1);\n MONTHS[C].START_WDAY = 0;\n }\n PUTCHAR('\\012');\n }\n PUTCHAR('\\012');\n}\n\nVOID PRINT_YEAR(VOID)\n{\n INT Y = YEAR;\n INT ROW;\n CHAR BUF[32];\n CHAR * B = &(BUF[31]);\n *B-- = '\\0';\n DO {\n *B-- = '0' + (Y % 10);\n Y /= 10;\n } WHILE (Y > 0);\n B++;\n SPACE((WIDTH - STRLEN(B)) / 2);\n PRINT(B);PUTCHAR('\\012');PUTCHAR('\\012');\n FOR (ROW = 0; ROW * COLS < 12; ROW++)\n PRINT_ROW(ROW);\n}\n\nINT MAIN(INT C, CHAR **V)\n{\n INT I, YEAR_SET = 0, RESULT = 0;\n FOR (I = 1; I < C && RESULT == 0; I++) {\n IF (V[I][0] == '-' && V[I][1] == 'W' && V[I][2] == '\\0') {\n IF (++I == C || (WIDTH = ATOI(V[I])) < 20)\n RESULT = 1;\n } ELSE IF (!YEAR_SET) {\n YEAR = ATOI(V[I]);\n IF (YEAR <= 0)\n YEAR = 1969;\n YEAR_SET = 1;\n } ELSE\n RESULT = 1;\n }\n\n IF (RESULT == 0) {\n INIT_MONTHS();\n PRINT_YEAR();\n } ELSE {\n PRINT(\"BAD ARGS\\012USAGE: \");\n PRINT(V[0]);\n PRINT(\" YEAR [-W WIDTH (>= 20)]\\012\");\n }\nRETURN RESULT;\n}\n", "language": "C" }, { "code": "(QL:QUICKLOAD '(DATE-CALC))\n\n(DEFPARAMETER *DAY-ROW* \"SU MO TU WE TH FR SA\")\n(DEFPARAMETER *CALENDAR-MARGIN* 3)\n\n(DEFUN MONTH-TO-WORD (MONTH)\n \"TRANSLATE A MONTH FROM 1 TO 12 INTO ITS WORD REPRESENTATION.\"\n (SVREF #(\"JANUARY\" \"FEBRUARY\" \"MARCH\" \"APRIL\"\n \"MAY\" \"JUNE\" \"JULY\" \"AUGUST\"\n \"SEPTEMBER\" \"OCTOBER\" \"NOVEMBER\" \"DECEMBER\")\n (1- MONTH)))\n\n(DEFUN MONTH-STRINGS (YEAR MONTH)\n \"COLLECT ALL OF THE STRINGS THAT MAKE UP A CALENDAR FOR A GIVEN\nMONTH AND YEAR.\"\n `(,(DATE-CALC:CENTER (MONTH-TO-WORD MONTH) (LENGTH *DAY-ROW*))\n ,*DAY-ROW*\n ;; WE CAN ASSUME THAT A MONTH CALENDAR WILL ALWAYS FIT INTO A 7 BY 6 BLOCK\n ;; OF VALUES. THIS MAKES IT EASY TO FORMAT THE RESULTING STRINGS.\n ,@ (LET ((DAYS (MAKE-ARRAY (* 7 6) :INITIAL-ELEMENT NIL)))\n (LOOP :FOR I :FROM (DATE-CALC:DAY-OF-WEEK YEAR MONTH 1)\n :FOR DAY :FROM 1 :TO (DATE-CALC:DAYS-IN-MONTH YEAR MONTH)\n :DO (SETF (AREF DAYS I) DAY))\n (LOOP :FOR I :FROM 0 :TO 5\n :COLLECT\n (FORMAT NIL \"~{~:[ ~;~2,D~]~^ ~}\"\n (LOOP :FOR DAY :ACROSS (SUBSEQ DAYS (* I 7) (+ 7 (* I 7)))\n :APPEND (IF DAY (LIST DAY DAY) (LIST DAY))))))))\n\n(DEFUN CALC-COLUMNS (CHARACTERS MARGIN-SIZE)\n \"CALCULATE THE NUMBER OF COLUMNS GIVEN THE NUMBER OF CHARACTERS PER\nCOLUMN AND THE MARGIN-SIZE BETWEEN THEM.\"\n (MULTIPLE-VALUE-BIND (COLS EXCESS)\n (TRUNCATE CHARACTERS (+ MARGIN-SIZE (LENGTH *DAY-ROW*)))\n (INCF EXCESS MARGIN-SIZE)\n (IF (>= EXCESS (LENGTH *DAY-ROW*))\n (1+ COLS)\n COLS)))\n\n(DEFUN TAKE (N LIST)\n \"TAKE THE FIRST N ELEMENTS OF A LIST.\"\n (LOOP :REPEAT N :FOR X :IN LIST :COLLECT X))\n\n(DEFUN DROP (N LIST)\n \"DROP THE FIRST N ELEMENTS OF A LIST.\"\n (COND ((OR (<= N 0) (NULL LIST)) LIST)\n (T (DROP (1- N) (CDR LIST)))))\n\n(DEFUN CHUNKS-OF (N LIST)\n \"SPLIT THE LIST INTO CHUNKS OF SIZE N.\"\n (ASSERT (> N 0))\n (LOOP :FOR X := LIST :THEN (DROP N X)\n :WHILE X\n :COLLECT (TAKE N X)))\n\n(DEFUN PRINT-CALENDAR (YEAR &KEY (CHARACTERS 80) (MARGIN-SIZE 3))\n \"PRINT OUT THE CALENDAR FOR A GIVEN YEAR, OPTIONALLY SPECIFYING\nA WIDTH LIMIT IN CHARACTERS AND MARGIN-SIZE BETWEEN MONTHS.\"\n (ASSERT (>= CHARACTERS (LENGTH *DAY-ROW*)))\n (ASSERT (>= MARGIN-SIZE 0))\n (LET* ((CALENDARS (LOOP :FOR MONTH :FROM 1 :TO 12\n :COLLECT (MONTH-STRINGS YEAR MONTH)))\n (COLUMN-COUNT (CALC-COLUMNS CHARACTERS MARGIN-SIZE))\n (TOTAL-SIZE (+ (* COLUMN-COUNT (LENGTH *DAY-ROW*))\n (* (1- COLUMN-COUNT) MARGIN-SIZE)))\n (FORMAT-STRING (CONCATENATE 'STRING\n \"~{~A~^~\" (WRITE-TO-STRING MARGIN-SIZE) \",0@T~}~%\")))\n (FORMAT T \"~A~%~A~%~%\"\n (DATE-CALC:CENTER \"[SNOOPY]\" TOTAL-SIZE)\n (DATE-CALC:CENTER (WRITE-TO-STRING YEAR) TOTAL-SIZE))\n (LOOP :FOR ROW :IN (CHUNKS-OF COLUMN-COUNT CALENDARS)\n :DO (APPLY 'MAPCAR\n (LAMBDA (&REST HEADS)\n (FORMAT T FORMAT-STRING HEADS))\n ROW))))\n", "language": "Common-Lisp" }, { "code": "import std.string;mixin(import(\"CALENDAR\").toLower);void main(){}\n", "language": "D" }, { "code": "import system'text;\nimport system'routines;\nimport system'calendar;\nimport extensions;\nimport extensions'routines;\n\nconst MonthNames = new string[]{\"JANUARY\",\"FEBRUARY\",\"MARCH\",\"APRIL\",\"MAY\",\"JUNE\",\"JULY\",\"AUGUST\",\"SEPTEMBER\",\"OCTOBER\",\"NOVEMBER\",\"DECEMBER\"};\nconst DayNames = new string[]{\"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\", \"SU\"};\n\nclass CalendarMonthPrinter\n{\n Date _date;\n TextBuilder _line;\n int _month;\n int _year;\n Reference<int> _row;\n\n constructor(year, month)\n {\n _month := month;\n _year := year;\n _line := new TextBuilder();\n _row := 0;\n }\n\n writeTitle()\n {\n _row.Value := 0;\n _date := Date.new(_year, _month, 1);\n\n DayNames.forEach::(name)\n { _line.print(\" \",name) }\n }\n\n writeLine()\n {\n _line.clear();\n\n if (_date.Month == _month)\n {\n var dw := _date.DayOfWeek;\n\n _line.writeCopies(\" \",_date.DayOfWeek == 0 ? 6 : (_date.DayOfWeek - 1));\n\n do\n {\n _line.writePaddingLeft(_date.Day.toPrintable(), $32, 3);\n\n _date := _date.addDays(1)\n }\n until(_date.Month != _month || _date.DayOfWeek == 1)\n };\n\n int length := _line.Length;\n if (length < 21)\n { _line.writeCopies(\" \", 21 - length) };\n\n _row.append(1)\n }\n\n indexer() = new Indexer\n {\n bool Available = _row < 7;\n\n int Index\n {\n get() = _row.Value;\n\n set(int index)\n {\n if (index <= _row)\n { self.writeTitle() };\n\n while (index > _row)\n { self.writeLine() }\n }\n }\n\n appendIndex(int index)\n {\n this self.Index := _row.Value + index\n }\n\n get int Length() { ^ 7 }\n\n get Value() = self;\n\n set Value(o) { NotSupportedException.raise() }\n };\n\n printTitleTo(output)\n {\n output.writePadding(MonthNames[_month - 1], $32, 21)\n }\n\n printTo(output)\n {\n output.write(_line.Value)\n }\n}\n\nclass Calendar\n{\n int _year;\n int _rowLength;\n\n constructor new(int year)\n {\n _year := year;\n _rowLength := 3\n }\n\n printTo(output)\n {\n output.writePadding(\"[SNOOPY]\", $32, _rowLength * 25);\n output.writeLine();\n output.writePadding(_year.toPrintable(), $32, _rowLength * 25);\n output.writeLine().writeLine();\n\n var rowCount := 12 / _rowLength;\n var months := Array.allocate(rowCount).populate::(i =>\n Array.allocate(_rowLength)\n .populate::(j =>\n new CalendarMonthPrinter(_year, i * _rowLength + j + 1)));\n\n months.forEach::(row)\n {\n var r := row;\n\n row.forEach::(month)\n {\n month.printTitleTo(output);\n\n output.write(\" \")\n };\n\n output.writeLine();\n\n ParallelEnumerator.new(row).forEach::(line)\n {\n line.forEach::(printer)\n {\n printer.printTo(output);\n\n output.write(\" \")\n };\n\n output.writeLine()\n }\n }\n }\n}\n\npublic program()\n{\n var calender := Calendar.new(console.write(\"ENTER THE YEAR:\").readLine().toInt());\n\n calender.printTo(console);\n\n console.readChar()\n}\n", "language": "Elena" }, { "code": ": WEEKDAY ( D M Y -- U )\n OVER 3 < IF SWAP 12 + SWAP 1- THEN\n DUP 4 / OVER 100 / - OVER 400 / + + SWAP 1+ 13 * 5 / + + 2 - 7 MOD ;\n\n: MDAYS ( M Y -- MSIZE MDAY )\n OVER 12 = IF 31 1 2SWAP WEEKDAY NEGATE EXIT THEN\n 2>R 1 2R@ WEEKDAY 1 2R> SWAP 1+ SWAP WEEKDAY OVER -\n 7 + 7 MOD 28 + SWAP NEGATE ;\n\n: .WEEK ( MSIZE MDAY -- MSIZE MDAY' )\n 7 0 DO DUP 0< IF 1+ 3 SPACES ELSE\n 2DUP > IF 1+ DUP 2 .R SPACE ELSE 3 SPACES THEN THEN LOOP ;\n\n: .3MONTHS ( Y M -- )\n 3 0 DO .\" MO TU WE TH FR SA SU \" LOOP CR\n 3 OVER + SWAP DO I OVER MDAYS ROT LOOP DROP\n 6 0 DO 2ROT .WEEK 2 SPACES 2ROT .WEEK 2 SPACES 2ROT .WEEK CR LOOP\n 2DROP 2DROP 2DROP ;\n\n: CAL ( Y -- )\n 30 SPACES .\" [SNOOPY]\" CR\n 32 SPACES DUP . CR\n .\" JANUARY FEBRUARY MARCH\" CR\n DUP 1 .3MONTHS\n .\" APRIL MAY JUNE\" CR\n DUP 4 .3MONTHS\n .\" JULY AUGUST SEPTEMBER\" CR\n DUP 7 .3MONTHS\n .\" OCTOBER NOVEMBER DECEMBER\" CR\n 10 .3MONTHS ;\n\n1969 CAL\n", "language": "Forth" }, { "code": " MODULE DATEGNASH\n\n TYPE DATEBAG\n INTEGER DAY,MONTH,YEAR\n END TYPE DATEBAG\n\n CHARACTER*9 MONTHNAME(12),DAYNAME(0:6)\n PARAMETER (MONTHNAME = (/\"JANUARY\",\"FEBRUARY\",\"MARCH\",\"APRIL\",\n 1 \"MAY\",\"JUNE\",\"JULY\",\"AUGUST\",\"SEPTEMBER\",\"OCTOBER\",\"NOVEMBER\",\n 2 \"DECEMBER\"/))\n PARAMETER (DAYNAME = (/\"SUNDAY\",\"MONDAY\",\"TUESDAY\",\"WEDNESDAY\",\n 1 \"THURSDAY\",\"FRIDAY\",\"SATURDAY\"/))\n\n INTEGER*4 JDAYSHIFT\n PARAMETER (JDAYSHIFT = 2415020)\n CONTAINS\n INTEGER FUNCTION LSTNB(TEXT)\n CHARACTER*(*),INTENT(IN):: TEXT\n INTEGER L\n L = LEN(TEXT)\n 1 IF (L.LE.0) GO TO 2\n IF (ICHAR(TEXT(L:L)).GT.ICHAR(\" \")) GO TO 2\n L = L - 1\n GO TO 1\n 2 LSTNB = L\n RETURN\n END FUNCTION LSTNB\n CHARACTER*2 FUNCTION I2FMT(N)\n INTEGER*4 N\n IF (N.LT.0) THEN\n IF (N.LT.-9) THEN\n I2FMT = \"-!\"\n ELSE\n I2FMT = \"-\"//CHAR(ICHAR(\"0\") - N)\n END IF\n ELSE IF (N.LT.10) THEN\n I2FMT = \" \" //CHAR(ICHAR(\"0\") + N)\n ELSE IF (N.LT.100) THEN\n I2FMT = CHAR(N/10 + ICHAR(\"0\"))\n 1 //CHAR(MOD(N,10) + ICHAR(\"0\"))\n ELSE\n I2FMT = \"+!\"\n END IF\n END FUNCTION I2FMT\n CHARACTER*8 FUNCTION I8FMT(N)\n INTEGER*4 N\n CHARACTER*8 HIC\n WRITE (HIC,1) N\n 1 FORMAT (I8)\n I8FMT = HIC\n END FUNCTION I8FMT\n\n SUBROUTINE SAY(OUT,TEXT)\n INTEGER OUT\n CHARACTER*(*) TEXT\n WRITE (6,1) TEXT(1:LSTNB(TEXT))\n 1 FORMAT (A)\n END SUBROUTINE SAY\n\n INTEGER*4 FUNCTION DAYNUM(YY,M,D)\n INTEGER*4 JDAYN\n INTEGER YY,Y,M,MM,D\n Y = YY\n IF (Y.LT.1) Y = Y + 1\n MM = (M - 14)/12\n JDAYN = D - 32075\n A + 1461*(Y + 4800 + MM)/4\n B + 367*(M - 2 - MM*12)/12\n C - 3*((Y + 4900 + MM)/100)/4\n DAYNUM = JDAYN - JDAYSHIFT\n END FUNCTION DAYNUM\n\n TYPE(DATEBAG) FUNCTION MUNYAD(DAYNUM)\n INTEGER*4 DAYNUM,JDAYN\n INTEGER Y,M,D,L,N\n JDAYN = DAYNUM + JDAYSHIFT\n L = JDAYN + 68569\n N = 4*L/146097\n L = L - (146097*N + 3)/4\n Y = 4000*(L + 1)/1461001\n L = L - 1461*Y/4 + 31\n M = 80*L/2447\n D = L - 2447*M/80\n L = M/11\n M = M + 2 - 12*L\n Y = 100*(N - 49) + Y + L\n IF (Y.LT.1) Y = Y - 1\n MUNYAD%YEAR = Y\n MUNYAD%MONTH = M\n MUNYAD%DAY = D\n END FUNCTION MUNYAD\n\n INTEGER FUNCTION PMOD(N,M)\n INTEGER N,M\n PMOD = MOD(MOD(N,M) + M,M)\n END FUNCTION PMOD\n\n SUBROUTINE CALENDAR(Y1,Y2,COLUMNS)\n\n INTEGER Y1,Y2,YEAR\n INTEGER M,M1,M2,MONTH\n INTEGER*4 DN1,DN2,DN,D\n INTEGER W,G\n INTEGER L,LINE\n INTEGER COL,COLUMNS,COLWIDTH\n CHARACTER*200 STRIPE(6),SPECIAL(6),MLINE,DLINE\n W = 3\n G = 1\n COLWIDTH = 7*W + G\n Y:DO YEAR = Y1,Y2\n CALL SAY(MSG,\"\")\n IF (YEAR.EQ.0) THEN\n CALL SAY(MSG,\"THERE IS NO YEAR ZERO.\")\n CYCLE Y\n END IF\n MLINE = \"\"\n L = (COLUMNS*COLWIDTH - G - 8)/2\n IF (YEAR.GT.0) THEN\n MLINE(L:) = I8FMT(YEAR)\n ELSE\n MLINE(L - 1:) = I8FMT(-YEAR)//\"BC\"\n END IF\n CALL SAY(MSG,MLINE)\n DO MONTH = 1,12,COLUMNS\n M1 = MONTH\n M2 = MIN(12,M1 + COLUMNS - 1)\n MLINE = \"\"\n DLINE = \"\"\n STRIPE = \"\"\n SPECIAL = \"\"\n L0 = 1\n DO M = M1,M2\n L = (COLWIDTH - G - LSTNB(MONTHNAME(M)))/2 - 1\n MLINE(L0 + L:) = MONTHNAME(M)\n DO D = 0,6\n L = L0 + (3 - W) + D*W\n DLINE(L:L + 2) = DAYNAME(D)(1:W - 1)\n END DO\n DN1 = DAYNUM(YEAR,M,1)\n DN2 = DAYNUM(YEAR,M + 1,0)\n COL = MOD(PMOD(DN1,7) + 7,7)\n LINE = 1\n D = 1\n DO DN = DN1,DN2\n L = L0 + COL*W\n STRIPE(LINE)(L:L + 1) = I2FMT(D)\n D = D + 1\n COL = COL + 1\n IF (COL.GT.6) THEN\n LINE = LINE + 1\n COL = 0\n END IF\n END DO\n L0 = L0 + 7*W + G\n END DO\n CALL SAY(MSG,MLINE)\n CALL SAY(MSG,DLINE)\n DO LINE = 1,6\n IF (STRIPE(LINE).NE.\"\") THEN\n CALL SAY(MSG,STRIPE(LINE))\n END IF\n END DO\n END DO\n END DO Y\n CALL SAY(MSG,\"\")\n END SUBROUTINE CALENDAR\n END MODULE DATEGNASH\n\n PROGRAM SHOW1968\n USE DATEGNASH\n INTEGER NCOL\n DO NCOL = 1,6\n CALL CALENDAR(1969,1969,NCOL)\n END DO\n END\n", "language": "Fortran" }, { "code": "' VERSION 16-03-2016\n' COMPILE WITH: FBC -S CONSOLE\n\n' TRUE/FALSE ARE BUILT-IN CONSTANTS SINCE FREEBASIC 1.04\n' BUT WE HAVE TO DEFINE THEM FOR OLDER VERSIONS.\n#IFNDEF TRUE\n #DEFINE FALSE 0\n #DEFINE TRUE NOT FALSE\n#ENDIF\n\nFUNCTION WD(M AS INTEGER, D AS INTEGER, Y AS INTEGER) AS INTEGER\n ' ZELLERISH\n ' 0 = SUNDAY, 1 = MONDAY, 2 = TUESDAY, 3 = WEDNESDAY\n ' 4 = THURSDAY, 5 = FRIDAY, 6 = SATURDAY\n\n IF M < 3 THEN ' IF M = 1 OR M = 2 THEN\n M += 12\n Y -= 1\n END IF\n RETURN (Y + (Y \\ 4) - (Y \\ 100) + (Y \\ 400) + D + ((153 * M + 8) \\ 5)) MOD 7\nEND FUNCTION\n\nFUNCTION LEAPYEAR(Y AS INTEGER) AS INTEGER\n\n IF (Y MOD 4) <> 0 THEN RETURN FALSE\n IF (Y MOD 100) = 0 ANDALSO (Y MOD 400) <> 0 THEN RETURN FALSE\n RETURN TRUE\nEND FUNCTION\n\n' ------=< MAIN >=------\n' HARD CODED FOR 132 CHARACTERS PER LINE\n\nDIM AS STRING WDN = \"MO TU WE TH FR SA SU\" ' WEEKDAY NAMES\nDIM AS STRING MO(1 TO 12) => {\"JANUARY\", \"FEBRUARY\", \"MARCH\", \"APRIL\", _\n \"MAY\", \"JUNE\", \"JULY\", \"AUGUST\", \"SEPTEMBER\", _\n \"OCTOBER\", \"NOVEMBER\", \"DECEMBER\"}\nDIM AS STRING TMP1, TMP2, D(1 TO 12)\n\nDIM AS UINTEGER ML(1 TO 12) => {31,28,31,30,31,30,31,31,30,31,30,31}\nDIM AS UINTEGER I, I1, J, K, Y = 1969\n\n'SCREENRES 1080,600,8\n\nIF LEAPYEAR(Y) = TRUE THEN ML(2) = 29\n\nTMP1 = \"\"\nFOR I = 1 TO 31\n TMP1 = TMP1 + RIGHT((\" \" + STR(I)), 3)\nNEXT I\n\n\nFOR I = 1 TO 12\n TMP2 = \"\"\n J = WD(I,1, Y)\n IF J = 0 THEN J = 7\n J = J - 1\n TMP2 = SPACE(J * 3) + LEFT(TMP1, ML(I) * 3) + SPACE(21)\n D(I) = TMP2\nNEXT I\n\nPRINT\nTMP1 = \"INSERT YOUR SNOOPY PICTURE HERE\"\nPRINT SPACE((132 - LEN(TMP1)) \\ 2); TMP1\nPRINT\nTMP1 = STR(Y)\nPRINT SPACE((132 - LEN(TMP1)) \\ 2); TMP1\nPRINT\n\n' 6 MONTH ON A ROW\nTMP2 = \" \"\nFOR I = 1 TO 6\n TMP2 = TMP2 + WDN\n IF I < 6 THEN TMP2 = TMP2 + \" \"\nNEXT I\n\nFOR I = 1 TO 12 STEP 6\n TMP1 = \"\"\n FOR J = I TO I + 4\n TMP1 = TMP1 + LEFT(SPACE((22 - LEN(MO(J))) \\ 2) + MO(J) + SPACE(11), 22)\n NEXT J\n TMP1 = TMP1 + SPACE((22 - LEN(MO(I + 5))) \\ 2) + MO(I + 5)\n PRINT TMP1\n PRINT TMP2\n FOR J = 1 TO 85 STEP 21\n FOR K = I TO I + 4\n PRINT MID(D(K), J ,21); \" \";\n NEXT K\n PRINT MID(D(I + 5), J ,21)\n NEXT J\n PRINT\nNEXT I\n\n' EMPTY KEYBOARD BUFFER\nWHILE INKEY <> \"\" : WEND\nPRINT : PRINT \"HIT ANY KEY TO END PROGRAM\"\nSLEEP\nEND\n", "language": "FreeBASIC" }, { "code": "INCLUDE \"NSLOG.INCL\"\n\nLOCAL FN RUNTERMINALCOMMAND( CMD AS CFSTRINGREF ) AS CFSTRINGREF\n CFSTRINGREF OUTPUTSTR = NULL\n\n TASKREF TASK = FN TASKINIT\n TASKSETEXECUTABLEURL( TASK, FN URLFILEURLWITHPATH( FN STRINGLOWERCASESTRING( @\"/BIN/ZSH\" ) ) )\n CFSTRINGREF CMDSTR = FN STRINGWITHFORMAT( @\"%@\", FN STRINGLOWERCASESTRING( CMD ) )\n CFARRAYREF ARGS = FN ARRAYWITHOBJECTS( FN STRINGLOWERCASESTRING( @\"-C\" ), CMDSTR, NULL )\n TASKSETARGUMENTS( TASK, ARGS )\n\n PIPEREF P = FN PIPEINIT\n TASKSETSTANDARDOUTPUT( TASK, P )\n TASKSETSTANDARDERROR( TASK, P )\n FILEHANDLEREF FH = FN PIPEFILEHANDLEFORREADING( P )\n\n FN TASKLAUNCH( TASK, NULL )\n TASKWAITUNTILEXIT( TASK )\n\n ERRORREF ERR\n CFDATAREF DTA = FN FILEHANDLEREADDATATOENDOFFILE( FH, @ERR )\n IF ERR THEN NSLOG( @\"%@\", FN ERRORLOCALIZEDDESCRIPTION( ERR ) ) : EXIT FN\n OUTPUTSTR = FN STRINGWITHDATA( DTA, NSUTF8STRINGENCODING )\n OUTPUTSTR = FN STRINGUPPERCASESTRING( OUTPUTSTR )\nEND FN = OUTPUTSTR\n\nVOID LOCAL FN BUILDSNOOPYCALENDAR\n CFSTRINGREF CALSTR = FN STRINGWITHFORMAT( FN STRINGLOWERCASESTRING( @\"\\n%37S\\n\\n%@\" ), FN STRINGUTF8STRING( @\"[SNOOPY HERE]\" ), FN RUNTERMINALCOMMAND( FN STRINGLOWERCASESTRING( @\"CAL 1969\" ) ) )\n NSLOG( @\"%@\", CALSTR )\nEND FN\n\nFN BUILDSNOOPYCALENDAR\n\nHANDLEEVENTS\n", "language": "FutureBasic" }, { "code": "PACKAGE MAIN\n\nIMPORT (\n \"FMT\"\n \"TIME\"\n)\n\nCONST PAGEWIDTH = 80\n\nFUNC MAIN() {\n PRINTCAL(1969)\n}\n\nFUNC PRINTCAL(YEAR INT) {\n THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC)\n VAR (\n DAYARR [12][7][6]INT // MONTH, WEEKDAY, WEEK\n MONTH, LASTMONTH TIME.MONTH\n WEEKINMONTH, DAYINMONTH INT\n )\n FOR THISDATE.YEAR() == YEAR {\n IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH {\n WEEKINMONTH = 0\n DAYINMONTH = 1\n }\n WEEKDAY := THISDATE.WEEKDAY()\n IF WEEKDAY == 0 && DAYINMONTH > 1 {\n WEEKINMONTH++\n }\n DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY()\n LASTMONTH = MONTH\n DAYINMONTH++\n THISDATE = THISDATE.ADD(TIME.HOUR * 24)\n }\n CENTRE := FMT.SPRINTF(\"%D\", PAGEWIDTH/2)\n FMT.PRINTF(\"%\"+CENTRE+\"S\\N\\N\", \"[SNOOPY]\")\n CENTRE = FMT.SPRINTF(\"%D\", PAGEWIDTH/2-2)\n FMT.PRINTF(\"%\"+CENTRE+\"D\\N\\N\", YEAR)\n MONTHS := [12]STRING{\n \" JANUARY \", \" FEBRUARY\", \" MARCH \", \" APRIL \",\n \" MAY \", \" JUNE \", \" JULY \", \" AUGUST \",\n \"SEPTEMBER\", \" OCTOBER \", \" NOVEMBER\", \" DECEMBER\"}\n DAYS := [7]STRING{\"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\"}\n FOR QTR := 0; QTR < 4; QTR++ {\n FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { // MONTH NAMES\n FMT.PRINTF(\" %S \", MONTHS[QTR*3+MONTHINQTR])\n }\n FMT.PRINTLN()\n FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { // DAY NAMES\n FOR DAY := 0; DAY < 7; DAY++ {\n FMT.PRINTF(\" %S\", DAYS[DAY])\n }\n FMT.PRINTF(\" \")\n }\n FMT.PRINTLN()\n FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ {\n FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {\n FOR DAY := 0; DAY < 7; DAY++ {\n IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 {\n FMT.PRINTF(\" \")\n } ELSE {\n FMT.PRINTF(\"%3D\", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH])\n }\n }\n FMT.PRINTF(\" \")\n }\n FMT.PRINTLN()\n }\n FMT.PRINTLN()\n }\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"io/ioutil\"\n \"log\"\n \"os\"\n \"os/exec\"\n \"strings\"\n)\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc main() {\n lower := []string{\n \"const \", \"else \", \"for \", \"func \", \"if \", \"import \", \"int \", \"package \", \"string \", \"var \",\n \" int\", \"int(\", \"string{\", \" main\", \"main(\", \"fmt\", \"time\", \"%d\", \"%s\", \"%3d\", `d\\n\\n`, `s\\n\\n`,\n }\n title := []string{\n \".add\", \".date\", \".day\", \".hour\", \".month\", \".printf\", \".println\", \".sprintf\", \".weekday\", \".year\",\n }\n code, err := ioutil.ReadFile(\"realcal_UC.txt\")\n check(err)\n text := string(code)\n for _, lwr := range lower {\n text = strings.Replace(text, strings.ToUpper(lwr), lwr, -1)\n }\n for _, ttl := range title {\n text = strings.Replace(text, strings.ToUpper(ttl), \".\"+strings.Title(ttl[1:]), -1)\n }\n err = ioutil.WriteFile(\"realcal_NC.go\", []byte(text), 0666)\n check(err)\n cmd := exec.Command(\"go\", \"run\", \"realcal_NC.go\")\n cmd.Stdout = os.Stdout\n cmd.Stderr = os.Stderr\n check(cmd.Run())\n}\n", "language": "Go" }, { "code": "RIGHTCLICK:CLOCK,ADJUST DATE AND TIME,BUTTON:CANCEL\n", "language": "GUISS" }, { "code": "$include \"REALIZE.ICN\"\n\nLINK DATETIME\n$define ISLEAPYEAR IsLeapYear\n$define JULIAN julian\n\nPROCEDURE MAIN(A)\n PRINTCALENDAR(\\A$<1$>|1969)\t\nEND\n\nPROCEDURE PRINTCALENDAR(YEAR)\n COLS := 3\n MONS := $<$>\n \"JANUARY FEBRUARY MARCH APRIL MAY JUNE \" ||\n \"JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER \" ?\n WHILE PUT(MONS, TAB(FIND(\" \"))) DO MOVE(1)\n\n WRITE(CENTER(\"$<SNOOPY PICTURE$>\",COLS * 24 + 4))\n WRITE(CENTER(YEAR,COLS * 24 + 4), CHAR(10))\n\n M := LIST(COLS)\t\n EVERY MON := 0 TO 9 BY COLS DO $(\n WRITES(\" \")\n EVERY I := 1 TO COLS DO {\n WRITES(CENTER(MONS$<MON+I$>,24))\n M$<I$> := CREATE CALENDARFORMATWEEK(YEAR,MON + I)\n $)\n WRITE()\n EVERY 1 TO 7 DO $(\n EVERY C := 1 TO COLS DO $(\n WRITES(\" \")\n EVERY 1 TO 7 DO WRITES(RIGHT(@M$<C$>,3))\n $)\n WRITE()\n $)\n $)\n RETURN\nEND\n\nPROCEDURE CALENDARFORMATWEEK(YEAR,M)\n STATIC D\n INITIAL D := $<31,28,31,30,31,30,31,31,30,31,30,31$>\n\n EVERY SUSPEND \"SU\"|\"MO\"|\"TU\"|\"WE\"|\"TH\"|\"FR\"|\"SA\"\n EVERY 1 TO (DAY := (JULIAN(M,1,YEAR)+1)%7) DO SUSPEND \"\"\n EVERY SUSPEND 1 TO D$<M$> DO DAY +:= 1\n IF M = 2 & ISLEAPYEAR(YEAR) THEN SUSPEND (DAY +:= 1, 29)\n EVERY DAY TO (6*7) DO SUSPEND \"\"\nEND\n", "language": "Icon" }, { "code": "$define PROCEDURE procedure\n$define END end\n$define WRITE write\n$define WRITES writes\n$define SUSPEND suspend\n$define DO do\n$define TO to\n$define EVERY every\n$define LIST list\n$define WHILE while\n$define MAIN main\n$define PUT put\n$define TAB tab\n$define MOVE move\n$define CHAR move\n$define CENTER center\n$define RIGHT right\n$define FIND find\n$define STATIC static\n$define INITIAL initial\n$define CREATE create\n$define LINK link\n$define IF if\n$define THEN then\n$define BY by\n$define DATETIME datetime\n$define RETURN return\n", "language": "Icon" }, { "code": "B=: + 4 100 400 -/@:<.@:%~ <:\nM=: 28+ 3, (10$5$3 2),~ 0 ~:/@:= 4 100 400 | ]\nR=: (7 -@| B+ 0, +/\\@}:@M) |.\"0 1 (0,#\\#~41) (]&:>: *\"1 >/)~ M\nH=. _3(_11&{.)\\'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'\nH=. 'SU MO TU WE TH FR SA',:\"1~H\nC=: H <@,\"(2) 12 6 21 }.\"1@($,) (' ',3 \":,.#\\#~31) {~ R\nD=: 0 \": -@<.@%&21@+&1@[ ]\\ C@]\nL=: |.\"0 1~ +/ .(*./\\@:=)\"1&' '\nE=: (|.\"0 1~ _2 <.@%~ +/ .(*./\\.@:=)\"1&' ')@:({.\"1) L\nF=: 0 _1 }. 0 1 }. (2+[) E '[INSERT SNOOPY HERE]', \":@], D\n", "language": "J" }, { "code": " 132 F 1969\n [INSERT SNOOPY HERE]\n 1969\n ┌────────────────────┬────────────────────┬────────────────────┬────────────────────┬────────────────────┬────────────────────┐\n │ JAN │ FEB │ MAR │ APR │ MAY │ JUN │\n │SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│\n │ 1 2 3 4│ 1│ 1│ 1 2 3 4 5│ 1 2 3│ 1 2 3 4 5 6 7│\n │ 5 6 7 8 9 10 11│ 2 3 4 5 6 7 8│ 2 3 4 5 6 7 8│ 6 7 8 9 10 11 12│ 4 5 6 7 8 9 10│ 8 9 10 11 12 13 14│\n │12 13 14 15 16 17 18│ 9 10 11 12 13 14 15│ 9 10 11 12 13 14 15│13 14 15 16 17 18 19│11 12 13 14 15 16 17│15 16 17 18 19 20 21│\n │19 20 21 22 23 24 25│16 17 18 19 20 21 22│16 17 18 19 20 21 22│20 21 22 23 24 25 26│18 19 20 21 22 23 24│22 23 24 25 26 27 28│\n │26 27 28 29 30 31 │23 24 25 26 27 28 │23 24 25 26 27 28 29│27 28 29 30 │25 26 27 28 29 30 31│29 30 │\n │ │ │30 31 │ │ │ │\n ├────────────────────┼────────────────────┼────────────────────┼────────────────────┼────────────────────┼────────────────────┤\n │ JUL │ AUG │ SEP │ OCT │ NOV │ DEC │\n │SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│\n │ 1 2 3 4 5│ 1 2│ 1 2 3 4 5 6│ 1 2 3 4│ 1│ 1 2 3 4 5 6│\n │ 6 7 8 9 10 11 12│ 3 4 5 6 7 8 9│ 7 8 9 10 11 12 13│ 5 6 7 8 9 10 11│ 2 3 4 5 6 7 8│ 7 8 9 10 11 12 13│\n │13 14 15 16 17 18 19│10 11 12 13 14 15 16│14 15 16 17 18 19 20│12 13 14 15 16 17 18│ 9 10 11 12 13 14 15│14 15 16 17 18 19 20│\n │20 21 22 23 24 25 26│17 18 19 20 21 22 23│21 22 23 24 25 26 27│19 20 21 22 23 24 25│16 17 18 19 20 21 22│21 22 23 24 25 26 27│\n │27 28 29 30 31 │24 25 26 27 28 29 30│28 29 30 │26 27 28 29 30 31 │23 24 25 26 27 28 29│28 29 30 31 │\n │ │31 │ │ │30 │ │\n └────────────────────┴────────────────────┴────────────────────┴────────────────────┴────────────────────┴────────────────────┘\n", "language": "J" }, { "code": "# IF THIS SMALL FUNCTION IS PLACED IN THE STARTUP.JL\n# FILE, IT WILL BE LOADED ON STARTUP. THE REST OF\n# THIS EXAMPLE IS IN ALL UPPERCASE.\nfunction RUNUPPERCASECODE(CO)\n COD = replace(lowercase(CO), \"date\" => \"Date\")\n for E in Meta.parse(COD, 1) eval(E) end\nend\n\n\nCODE = \"\"\"BEGIN\n\nUSING DATES;\nCENTEROBJECT(X, N) = BEGIN S = UPPERCASE(STRING(X)); RPAD(LPAD(S, DIV(N + LENGTH(S), 2)), N) END;\nFUNCTION FORMATMONTH(YR, MO)\n DT = DATE(\\\"\\$YR-\\$MO-01\\\");\n DAYOFWEEKFIRST = DAYOFWEEK(DT);\n NUMWEEKLINES = 1;\n STR = UPPERCASE(CENTEROBJECT(MONTHNAME(DT), 20) * \\\"\\\\NMO TU WE TH FR SA SU\\\\N\\\");\n STR *= \\\" \\\" ^ (3 * (DAYOFWEEKFIRST - 1)) * LPAD(STRING(1), 2);\n FOR I = 2:DAYSINMONTH(DT)\n IF (I + DAYOFWEEKFIRST + 5) % 7 == 0\n STR *= \\\"\\\\N\\\" * LPAD(I, 2);\n NUMWEEKLINES += 1;\n ELSE\n STR *= LPAD(STRING(I), 3);\n END;\n END;\n STR *= NUMWEEKLINES < 6 ? \\\"\\\\N\\\\N\\\\N\\\" : \\\"\\\\N\\\\N\\\";\n ARR = [];\n FOR S IN SPLIT(STR, \\\"\\\\N\\\")\n PUSH!(ARR, RPAD(S, 20)[1:20])\n END;\n JOIN(ARR, \\\"\\\\N\\\");\nEND;\n\nFUNCTION FORMATYEAR(DISPLAYYEAR)\n CALMONTHS = [FORMATMONTH(DISPLAYYEAR, MO) FOR MO IN 1:12];\n MONTHSPERLINE = 6;\n JOINSPACES = 2;\n STR = \\\"\\\\N\\\" * CENTEROBJECT(DISPLAYYEAR, 132) * \\\"\\\\N\\\";\n MONTHCAL = [SPLIT(FORMATMONTH(DISPLAYYEAR, I), \\\"\\\\N\\\") FOR I IN 1:12];\n FOR I IN 1:MONTHSPERLINE:LENGTH(CALMONTHS) - 1\n FOR J IN 1:LENGTH(MONTHCAL[1])\n MONTHLINES = MAP(X->MONTHCAL[X][J], I:I + MONTHSPERLINE - 1);\n STR *= RPAD(JOIN(MONTHLINES, \\\" \\\" ^ JOINSPACES), 132) * \\\"\\\\N\\\";\n END;\n STR *= \\\"\\\\N\\\";\n END;\n STR;\nEND;\n\nPRINTLN(FORMATYEAR(1969));\n\nEND;\n\"\"\"\n\nRUNUPPERCASECODE(CODE)\n", "language": "Julia" }, { "code": "IMPORT JAVA.TEXT.*\nIMPORT JAVA.UTIL.*\nIMPORT JAVA.IO.PRINTSTREAM\n\nINTERNAL FUN PRINTSTREAM.PRINTCALENDAR(YEAR: INT, NCOLS: BYTE, LOCALE: LOCALE?) {\n IF (NCOLS < 1 || NCOLS > 12)\n THROW ILLEGALARGUMENTEXCEPTION(\"ILLEGAL COLUMN WIDTH.\")\n VAL W = NCOLS * 24\n VAL NROWS = MATH.CEIL(12.0 / NCOLS).TOINT()\n\n VAL DATE = GREGORIANCALENDAR(YEAR, 0, 1)\n VAR OFFS = DATE.GET(CALENDAR.DAY_OF_WEEK) - 1\n\n VAL DAYS = DATEFORMATSYMBOLS(LOCALE).SHORTWEEKDAYS.SLICE(1..7).MAP { IT.SLICE(0..1) }.JOINTOSTRING(\" \", \" \")\n VAL MONS = ARRAY(12) { ARRAY(8) { \"\" } }\n DATEFORMATSYMBOLS(LOCALE).MONTHS.SLICE(0..11).FOREACHINDEXED { M, NAME ->\n VAL LEN = 11 + NAME.LENGTH / 2\n VAL FORMAT = MESSAGEFORMAT.FORMAT(\"%{0}S%{1}S\", LEN, 21 - LEN)\n MONS[M][0] = STRING.FORMAT(FORMAT, NAME, \"\")\n MONS[M][1] = DAYS\n VAL DIM = DATE.GETACTUALMAXIMUM(CALENDAR.DAY_OF_MONTH)\n FOR (D IN 1..42) {\n VAL ISDAY = D > OFFS && D <= OFFS + DIM\n VAL ENTRY = IF (ISDAY) STRING.FORMAT(\" %2S\", D - OFFS) ELSE \" \"\n IF (D % 7 == 1)\n MONS[M][2 + (D - 1) / 7] = ENTRY\n ELSE\n MONS[M][2 + (D - 1) / 7] += ENTRY\n }\n OFFS = (OFFS + DIM) % 7\n DATE.ADD(CALENDAR.MONTH, 1)\n }\n\n PRINTF(\"%\" + (W / 2 + 10) + \"S%N\", \"[SNOOPY PICTURE]\")\n PRINTF(\"%\" + (W / 2 + 4) + \"S%N%N\", YEAR)\n\n FOR (R IN 0..NROWS - 1) {\n FOR (I IN 0..7) {\n VAR C = R * NCOLS\n WHILE (C < (R + 1) * NCOLS && C < 12) {\n PRINTF(\" %S\", MONS[C][I].TOUPPERCASE()) // ORIGINAL CHANGED TO PRINT IN UPPER CASE\n C++\n }\n PRINTLN()\n }\n PRINTLN()\n }\n}\n\nFUN MAIN(ARGS: ARRAY<STRING>) {\n SYSTEM.OUT.PRINTCALENDAR(1969, 3, LOCALE.US)\n}\n", "language": "Kotlin" }, { "code": "// version 1.1.3\n\nimport java.io.File\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\n\nfun main(args: Array<String>) {\n val keywords = listOf(\n \"import\", \"internal\", \"fun\", \"if\", \"throw\", \"val\", \"var\", \"for\", \"in\", \"while\"\n )\n\n val singleCase = listOf(\n \"java.text\",\n \"java.util\",\n \"java.io\",\n \"else\", // really a keyword but doesn't have a following space here\n \"ceil\",\n \"it\", // really a keyword but doesn't have a following space here\n \"get(\", // also included in GETACTUALMAXIMUM\n \"slice\",\n \"map\",\n \"months\",\n \"length\",\n \".format\", // also variable called FORMAT\n \"add\",\n \"printf\",\n \"println\",\n \"out\",\n \"main\",\n \"args\",\n \"s%{1}s\",\n \"%2s\",\n \"s%n%n\",\n \"s%n\",\n \"%s\"\n )\n\n val mixedCase = listOf(\n \"PRINTSTREAM\" to \"PrintStream\",\n \"INT,\" to \"Int,\", // also included in PRINTCALENDAR\n \"BYTE\" to \"Byte\",\n \"LOCALE?\" to \"Locale?\", // also variable called LOCALE\n \"LOCALE.\" to \"Locale.\",\n \"ILLEGALARGUMENTEXCEPTION\" to \"IllegalArgumentException\",\n \"MATH\" to \"Math\",\n \"GREGORIANCALENDAR\" to \"GregorianCalendar\",\n \"DATEFORMATSYMBOLS\" to \"DateFormatSymbols\",\n \"ARRAY\" to \"Array\",\n \"MESSAGEFORMAT\" to \"MessageFormat\",\n \"JOINTOSTRING\" to \"joinToString\",\n \"STRING\" to \"String\",\n \"CALENDAR.\" to \"Calendar.\", // also included in PRINTCALENDAR\n \"SYSTEM\" to \"System\",\n \"TOINT\" to \"toInt\",\n \"SHORTWEEKDAYS\" to \"shortWeekdays\",\n \"FOREACHINDEXED\" to \"forEachIndexed\",\n \"GETACTUALMAXIMUM\" to \"getActualMaximum\",\n \"TOUPPERCASE\" to \"toUpperCase\"\n )\n\n var text = File(\"calendar_UC.txt\").readText()\n for (k in keywords) text = text.replace(\"${k.toUpperCase()} \", \"$k \") // add a following space to be on safe side\n for (s in singleCase) text = text.replace(s.toUpperCase(), s)\n for (m in mixedCase) text = text.replace(m.first, m.second)\n File(\"calendar_NC.kt\").writeText(text)\n val commands = listOf(\"kotlinc\", \"calendar_NC.kt\", \"-include-runtime\", \"-d\", \"calendar_X.jar\")\n val pb = ProcessBuilder(commands)\n pb.redirectErrorStream(true)\n val process = pb.start()\n process.waitFor()\n val commands2 = listOf(\"java\", \"-jar\", \"calendar_NC.jar\")\n val pb2 = ProcessBuilder(commands2)\n pb2.redirectErrorStream(true)\n val process2 = pb2.start()\n val out = StringBuilder()\n val br = BufferedReader(InputStreamReader(process2.inputStream))\n while (true) {\n val line = br.readLine()\n if (line == null) break\n out.append(line).append('\\n')\n }\n br.close()\n println(out.toString())\n}\n", "language": "Kotlin" }, { "code": "import java.text.*\nimport java.util.*\nimport java.io.PrintStream\n\ninternal fun PrintStream.PRINTCALENDAR(YEAR: Int, NCOLS: Byte, LOCALE: Locale?) {\n if (NCOLS < 1 || NCOLS > 12)\n throw IllegalArgumentException(\"ILLEGAL COLUMN WIDTH.\")\n val W = NCOLS * 24\n val NROWS = Math.ceil(12.0 / NCOLS).toInt()\n\n val DATE = GregorianCalendar(YEAR, 0, 1)\n var OFFS = DATE.get(Calendar.DAY_OF_WEEK) - 1\n\n val DAYS = DateFormatSymbols(LOCALE).shortWeekdays.slice(1..7).map { it.slice(0..1) }.joinToString(\" \", \" \")\n val MONS = Array(12) { Array(8) { \"\" } }\n DateFormatSymbols(LOCALE).months.slice(0..11).forEachIndexed { M, NAME ->\n val LEN = 11 + NAME.length / 2\n val FORMAT = MessageFormat.format(\"%{0}s%{1}s\", LEN, 21 - LEN)\n MONS[M][0] = String.format(FORMAT, NAME, \"\")\n MONS[M][1] = DAYS\n val DIM = DATE.getActualMaximum(Calendar.DAY_OF_MONTH)\n for (D in 1..42) {\n val ISDAY = D > OFFS && D <= OFFS + DIM\n val ENTRY = if (ISDAY) String.format(\" %2s\", D - OFFS) else \" \"\n if (D % 7 == 1)\n MONS[M][2 + (D - 1) / 7] = ENTRY\n else\n MONS[M][2 + (D - 1) / 7] += ENTRY\n }\n OFFS = (OFFS + DIM) % 7\n DATE.add(Calendar.MONTH, 1)\n }\n\n printf(\"%\" + (W / 2 + 10) + \"s%n\", \"[SNOOPY PICTURE]\")\n printf(\"%\" + (W / 2 + 4) + \"s%n%n\", YEAR)\n\n for (R in 0..NROWS - 1) {\n for (I in 0..7) {\n var C = R * NCOLS\n while (C < (R + 1) * NCOLS && C < 12) {\n printf(\" %s\", MONS[C][I].toUpperCase()) // ORIGINAL CHANGED TO PRINT in UPPER CASE\n C++\n }\n println()\n }\n println()\n }\n}\n\nfun main(args: Array<String>) {\n System.out.PRINTCALENDAR(1969, 3, Locale.US)\n}\n", "language": "Kotlin" }, { "code": "FUNCTION PRINT_CAL(YEAR)\n LOCAL MONTHS={\"JANUARY\",\"FEBRUARY\",\"MARCH\",\"APRIL\",\"MAY\",\"JUNE\",\n \"JULY\",\"AUGUST\",\"SEPTEMBER\",\"OCTOBER\",\"NOVEMBER\",\"DECEMBER\"}\n LOCAL DAYSTITLE=\"MO TU WE TH FR SA SU\"\n LOCAL DAYSPERMONTH={31,28,31,30,31,30,31,31,30,31,30,31}\n LOCAL STARTDAY=((YEAR-1)*365+MATH.FLOOR((YEAR-1)/4)-MATH.FLOOR((YEAR-1)/100)+MATH.FLOOR((YEAR-1)/400))%7\n IF YEAR%4==0 AND YEAR%100~=0 OR YEAR%400==0 THEN\n DAYSPERMONTH[2]=29\n END\n LOCAL SEP=5\n LOCAL MONTHWIDTH=DAYSTITLE:LEN()\n LOCAL CALWIDTH=3*MONTHWIDTH+2*SEP\n\n FUNCTION CENTER(STR, WIDTH)\n LOCAL FILL1=MATH.FLOOR((WIDTH-STR:LEN())/2)\n LOCAL FILL2=WIDTH-STR:LEN()-FILL1\n RETURN STRING.REP(\" \",FILL1)..STR..STRING.REP(\" \",FILL2)\n END\n\n FUNCTION MAKEMONTH(NAME, SKIP,DAYS)\n LOCAL CAL={\n CENTER(NAME,MONTHWIDTH),\n DAYSTITLE\n }\n LOCAL CURDAY=1-SKIP\n WHILE #CAL<9 DO\n LINE={}\n FOR I=1,7 DO\n IF CURDAY<1 OR CURDAY>DAYS THEN\n LINE[I]=\" \"\n ELSE\n LINE[I]=STRING.FORMAT(\"%2D\",CURDAY)\n END\n CURDAY=CURDAY+1\n END\n CAL[#CAL+1]=TABLE.CONCAT(LINE,\" \")\n END\n RETURN CAL\n END\n\n LOCAL CALENDAR={}\n FOR I,MONTH IN IPAIRS(MONTHS) DO\n LOCAL DPM=DAYSPERMONTH[I]\n CALENDAR[I]=MAKEMONTH(MONTH, STARTDAY, DPM)\n STARTDAY=(STARTDAY+DPM)%7\n END\n\n\n PRINT(CENTER(\"[SNOOPY]\",CALWIDTH):UPPER(),\"\\N\")\n PRINT(CENTER(\"--- \"..YEAR..\" ---\",CALWIDTH):UPPER(),\"\\N\")\n\n FOR Q=0,3 DO\n FOR L=1,9 DO\n LINE={}\n FOR M=1,3 DO\n LINE[M]=CALENDAR[Q*3+M][L]\n END\n PRINT(TABLE.CONCAT(LINE,STRING.REP(\" \",SEP)):UPPER())\n END\n END\nEND\n\nPRINT_CAL(1969)\n", "language": "Lua" }, { "code": "do io.input( arg[ 1 ] ); local s = io.read( \"*a\" ):lower(); io.close(); assert( load( s ) )() end\n", "language": "Lua" }, { "code": "\\\\ Calendar - for \"REAL\" programmers\n\\\\ All statements in UPPERCASE\n\\\\ Output to 132 characters console - as a line printer\n\\\\ USE COURIER NEW (FONT \"COURIER NEW\")\n\n\\\\ CHANGE THE VALUE OF PRINT_IT TO TRUE FOR PRINTING\nGLOBAL CONST PRINT_IT AS BOOLEAN=FALSE\nMODULE GLOBAL SNOOPY {\nIF NOT PRINT_IT THEN CURSOR 0,ROW ELSE IF ROW>0 THEN PAGE 1\nPRINT $(,8)\nPRINT #-2, {\n\t\t\t\t\t XXXX\n\t\t\t\t\t X XX\n\t\t\t\t\t X *** X\t\t XXXXX\n\t\t\t\t\tX ***** X\t XXX XX\n\t\t\t\t XXXX ******* XXX\t XXXX \t XX\n\t\t\t\t XX\tX ****** XXXXXXXXX El@\t XX XXX\n\t\t\t\t XX\t X **** X\t\t\t X** X\n\t\t\t\tX\t XX XX X \t\t X***X\n\t\t\t X\t //XXXX X \t\t XXXX\n\t\t\t X \t// X\t\t\t\t XX\n\t\t\t X\t // X\t\tXXXXXXXXXXXXXXXXXX/\n\t\t\t X\t XXX// X\t X\n\t\t\t X\t X X X\t X\n\t\t\t X\t X X X\t X\n\t\t\t X X X X\t X\t\t\t XX\n\t\t\t X X X X\t X\t\t XXX XX\n\t\t\t X XXX X\t X \t X X X X\n\t\t\t X\t X\t X\t XX X XXXX\n\t\t\t\tX\t X \tXXXXXXXX\\ XX XX X\n\t\t\t\t XX\t XX\t X X\t @X XX\n\t\t\t\t XX\t\t XXXX\tXXXXXX/ X\t XXXX\n\t\t\t\t XXX\t XX***\t X\t X\n\t\t\t\t\tXXXXXXXXXXXXX * *\t X\tX\n\t\t\t\t\t\t *---* X\t X X\n\t\t\t\t\t\t *-* * XXX X X\n\t\t\t\t\t\t *- * XXX X\n\t\t\t\t\t\t *- *X\t XXX\n\t\t\t\t\t\t *- *X X\t XXX\n\t\t\t\t\t\t *- *X X\t\tXX\n\t\t\t\t\t\t *- *XX X\t\t X\n\t\t\t\t\t\t * *X* X X\t\t X\n\t\t\t\t\t\t * *X * X X \t X\n\t\t\t\t\t\t* * X** X XXXX\t X\n\t\t\t\t\t\t* * X** XX\t X\t X\n\t\t\t\t\t * ** X** X XX\t X\n\t\t\t\t\t * ** X* XXX\tX\t X\n\t\t\t\t\t * ** XX XXXX XXX\n\t\t\t\t\t *\t* *\t XXXX\t X\t X\n\t\t\t\t\t *\t* *\t X\t X\t X\n\t\t\t =======******* * *\t X\t X\t XXXXXXXX\\\n\t\t\t\t *\t * *\t/XXXXX\t XXXXXXXX\\\t )\n\t\t\t\t=====********** * X\t\t )\t\\ )\n\t\t\t\t ====* \t* X \t \\ \\ )XXXXX\n\t\t\t =========********** XXXXXXXXXXXXXXXXXXXXXX\n\n}\n}\nMODULE CALENDAR (YEAR, LOCALEID) {\n FUNCTION GETMAX(YEAR, MONTH) {\n A=DATE(STR$(YEAR)+\"-\"+STR$(MONTH)+\"-1\")\n MAX=32\n DO {\n MAX--\n M=VAL(STR$(CDATE(A,0,0,MAX), \"M\"))\n } UNTIL M=MONTH\n =MAX+1\n }\n FUNCTION SKIPMO(YEAR, MONTH) {\n A=DATE(STR$(YEAR)+\"-\"+STR$(MONTH)+\"-1\")\n =(VAL(STR$(A, \"W\"))-8) MOD 7 +7\n }\n FUNCTION TITLE$(A$) {\n =UCASE$(LEFT$(A$,1))+LCASE$(MID$(A$, 2))\n }\n LOCALE LOCALEID\n IF NOT PRINT_IT THEN CURSOR 0,HEIGHT-1 ' LAST LINE, SO EACH NEW LINE SCROLL ALL LINES UP\n SNOOPY\n\n PRINT UNDER ' PRINT UNDERLINE\n PRINT OVER $(2), YEAR\n PRINT\n FOR J=0 TO 1 {\n PRINT\n FOR I=1 TO 6 {\n MONTH=I+J*6\n PRINT PART @((I-1)*22+1), $(2,21), UCASE$(LOCALE$(55+MONTH))\n }\n PRINT\n DIM SKIP(1 TO 6), COUNT(1 TO 6), D(1 TO 6)=1\n FOR I=1 TO 6 {\n MONTH=I+J*6\n IF I>1 THEN PRINT \" \";\n FOR K=42 TO 48 :PRINT \" \";UCASE$(LEFT$(LOCALE$(K),2));:NEXT K\n SKIP(I)=SKIPMO(YEAR, MONTH)\n COUNT(I)=GETMAX(YEAR, MONTH)\n }\n PRINT\n IF PRINT_IT ELSE REFRESH 1000\n FOR I=1 TO 6 {\n IF I>1 THEN PRINT \" \";\n FOR K=1 TO 7 {\n SKIP(I)--\n IF SKIP(I)>0 THEN PRINT \" \"; :CONTINUE\n COUNT(I)--\n PRINT FORMAT$(\" {0::-2}\", D(I));\n D(I)++\n }\n }\n PRINT\n IF PRINT_IT ELSE REFRESH 1000\n PRINT @(0)\n FOR M=1 TO 5 {\n FOR I=1 TO 6 {\n IF I>1 THEN PRINT \" \";\n FOR K=1 TO 7 {\n COUNT(I)--\n IF COUNT(I)<0 THEN PRINT \" \"; : CONTINUE\n PRINT FORMAT$(\" {0::-2}\", D(I));\n D(I)++\n }\n }\n PRINT\n IF PRINT_IT ELSE REFRESH 1000\n }\n }\n}\nWHILE INKEY$<>\"\" : END WHILE\nIF PRINT_IT THEN PRINTING ON ELSE REFRESH 1000\nFONT \"COURIER NEW\"\nPEN 0\nCLS 15, 0\nFORM 132,68\nCALENDAR 1966, 1032 ' GREEK\nGOSUB WAITKEY_OR_MOUSE\nFOR I=2020 TO 2026\nCALENDAR I, 1033 ' ENGLISH\nGOSUB WAITKEY_OR_MOUSE\nNEXT I\nIF PRINT_IT THEN PRINTING OFF ELSE REFRESH 50\nCLEAR ' CLEAR VARIABLES FROM THIS MODULE\nEND\nWAITKEY_OR_MOUSE:\nIF PRINT_IT THEN RETURN\nWHILE INKEY$=\"\" AND MOUSE=0\nEND WHILE\nRETURN\n", "language": "M2000-Interpreter" }, { "code": "import strutils\n\nconst progUpper = staticRead(\"calendar_upper.txt\")\n\nproc transformed(s: string): string {.compileTime.} =\n ## Return a transformed version (which can compile) of a program in uppercase.\n\n let upper = s.toLower() # Convert all to lowercase.\n var inString = false # Text in string should be in uppercase…\n var inBraces = false # … except if this is in an expression to interpolate.\n for ch in upper:\n case ch\n of '\"':\n inString = not inString\n of '{':\n if inString: inBraces = true\n of '}':\n if inString: inBraces = false\n of 'a'..'z':\n if inString and not inBraces:\n result.add(ch.toUpperAscii()) # Restore content of strings to uppercase.\n continue\n else:\n discard\n result.add(ch)\n\nconst prog = progUpper.transformed()\n\nstatic: writeFile(\"calendar_transformed.nim\", prog)\n\ninclude \"calendar_transformed.nim\"\n", "language": "Nim" }, { "code": "IMPORT TIMES\nIMPORT STRFORMAT\n\nPROC PRINTCALENDAR(YEAR, NCOLS: INT) =\n VAR ROWS = 12 DIV NCOLS\n VAR DATE = INITDATETIME(1, MJAN, YEAR, 0, 0, 0, UTC())\n IF ROWS MOD NCOLS != 0:\n INC ROWS\n VAR OFFS = GETDAYOFWEEK(DATE.MONTHDAY, DATE.MONTH, DATE.YEAR).INT\n VAR MONS: ARRAY[12, ARRAY[8, STRING]]\n FOR M IN 0..11:\n MONS[M][0] = &\"{$DATE.MONTH:^21}\"\n MONS[M][1] = \" SU MO TU WE TH FR SA\"\n VAR DIM = GETDAYSINMONTH(DATE.MONTH, DATE.YEAR)\n FOR D IN 1..42:\n VAR DAY = D > OFFS AND D <= OFFS + DIM\n VAR STR = IF DAY: &\" {D-OFFS:2}\" ELSE: \" \"\n MONS[M][2 + (D - 1) DIV 7] &= STR\n OFFS = (OFFS + DIM) MOD 7\n DATE = DATE + MONTHS(1)\n VAR SNOOPYSTRING, YEARSTRING: STRING\n FORMATVALUE(SNOOPYSTRING, \"[SNOOPY PICTURE]\", \"^\" & $(NCOLS * 24 + 4))\n FORMATVALUE(YEARSTRING, $YEAR, \"^\" & $(NCOLS * 24 + 4))\n ECHO SNOOPYSTRING, \"\\N\" , YEARSTRING, \"\\N\"\n FOR R IN 0..<ROWS:\n VAR S: ARRAY[8, STRING]\n FOR C IN 0..<NCOLS:\n IF R * NCOLS + C > 11:\n BREAK\n FOR I, LINE IN MONS[R * NCOLS + C]:\n S[I] &= &\" {LINE}\"\n FOR LINE IN S:\n IF LINE == \"\":\n BREAK\n ECHO LINE\n ECHO \"\"\n\nPRINTCALENDAR(1969, 5)\n", "language": "Nim" }, { "code": "$PROGRAM = '\\'\n\nMY @START_DOW = (3, 6, 6, 2, 4, 0,\n 2, 5, 1, 3, 6, 1);\nMY @DAYS = (31, 28, 31, 30, 31, 30,\n 31, 31, 30, 31, 30, 31);\n\nMY @MONTHS;\nFOREACH MY $M (0 .. 11) {\n FOREACH MY $R (0 .. 5) {\n $MONTHS[$M][$R] = JOIN \" \",\n MAP { $_ < 1 || $_ > $DAYS[$M] ? \" \" : SPRINTF \"%2D\", $_ }\n MAP { $_ - $START_DOW[$M] + 1 }\n $R * 7 .. $R * 7 + 6;\n }\n}\n\nSUB P { WARN $_[0], \"\\\\N\" }\nP UC \" [INSERT SNOOPY HERE]\";\nP \" 1969\";\nP \"\";\nFOREACH (UC(\" JANUARY FEBRUARY MARCH APRIL MAY JUNE\"),\n UC(\" JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER\")) {\n P $_;\n MY @MS = SPLICE @MONTHS, 0, 6;\n P JOIN \" \", ((UC \"SU MO TU WE TH FR SA\") X 6);\n P JOIN \" \", MAP { SHIFT @$_ } @MS FOREACH 0 .. 5;\n}\n\n\\'';\n\n# LOWERCASE LETTERS\n$E = '%' | '@';\n$C = '#' | '@';\n$H = '(' | '@';\n$O = '/' | '@';\n$T = '4' | '@';\n$R = '2' | '@';\n$A = '!' | '@';\n$Z = ':' | '@';\n$P = '0' | '@';\n$L = ',' | '@';\n\n`${E}${C}${H}${O} $PROGRAM | ${T}${R} A-Z ${A}-${Z} | ${P}${E}${R}${L}`;\n", "language": "Perl" }, { "code": "$_=$ARGV[0]//1969;`\\143\\141\\154 $_ >&2`\n", "language": "Perl" }, { "code": "--return repeat(' ',left)&s&repeat(' ',right)\nreturn repeat(' ',left)&upper(s)&repeat(' ',right)\n", "language": "Phix" }, { "code": "initialSymEntry(\"integer\", S_Type,\"TI\",opInt, E_none) -- #01 / 0b0001 integer\n", "language": "Phix" }, { "code": "Alias(\"INTEGER\",symlimit)\n", "language": "Phix" }, { "code": "procedure tt_stringA(sequence text, integer alias)\n tt_string(text,-2)\n tt[pcurr] = alias\nend procedure\n", "language": "Phix" }, { "code": "global constant T_include = 596 tt_stringF(\"include\",T_include)\n", "language": "Phix" }, { "code": "tt_stringA(\"INCLUDE\",T_include)\n", "language": "Phix" }, { "code": "--Ch = find(Ch,escchar)\nCh = find(lower(Ch),escchar)\n", "language": "Phix" }, { "code": "<?PHP\nECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n JANUARY FEBRUARY MARCH APRIL MAY JUNE\n MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO\n 1 2 3 4 5 1 2 1 2 1 2 3 4 5 6 1 2 3 4 1\n 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8\n 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15\n 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22\n 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29\n 31 30\n\n JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER\n MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO\n 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 1 2 1 2 3 4 5 6 7\n 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14\n 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21\n 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28\n 28 29 30 31 25 26 27 28 29 30 31 29 30 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31\nREALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n ; // MAGICAL SEMICOLON\n", "language": "PHP" }, { "code": "(DE CAL (YEAR)\n (PRINL \"====== \" YEAR \" ======\")\n (FOR DAT (RANGE (DATE YEAR 1 1) (DATE YEAR 12 31))\n (LET D (DATE DAT)\n (TAB (3 3 4 8)\n (WHEN (= 1 (CADDR D))\n (GET `(INTERN (PACK (MAPCAR CHAR (42 77 111 110)))) (CADR D)) )\n (CADDR D)\n (DAY DAT `(INTERN (PACK (MAPCAR CHAR (42 68 97 121)))))\n (WHEN (=0 (% (INC DAT) 7))\n (PACK (CHAR 87) \"EEk \" (WEEK DAT)) ) ) ) ) )\n\n(CAL 1969)\n(BYE)\n", "language": "PicoLisp" }, { "code": "(SUBRG, SIZE, FOFL):\nCALENDAR: PROCEDURE (YEAR) OPTIONS (MAIN);\n DECLARE YEAR CHARACTER (4) VARYING;\n DECLARE (A, B, C) (0:5,0:6) CHARACTER (3);\n DECLARE NAME_MONTH(12) STATIC CHARACTER (9) VARYING INITIAL (\n 'JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE',\n 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER');\n DECLARE I FIXED;\n DECLARE (MM, MMP1, MMP2) PIC '99';\n\n PUT EDIT (CENTER('CALENDAR FOR ' || YEAR, 67)) (A);\n PUT SKIP (2);\n\n DO MM = 1 TO 12 BY 3;\n MMP1 = MM + 1; MMP2 = MM + 2;\n CALL PREPARE_MONTH('01' || MM || YEAR, A);\n CALL PREPARE_MONTH('01' || MMP1 || YEAR, B);\n CALL PREPARE_MONTH('01' || MMP2 || YEAR, C);\n\n PUT SKIP EDIT (CENTER(NAME_MONTH(MM), 23),\n CENTER(NAME_MONTH(MMP1), 23),\n CENTER(NAME_MONTH(MMP2), 23) ) (A);\n PUT SKIP EDIT ((3)' M T W T F S S ') (A);\n DO I = 0 TO 5;\n PUT SKIP EDIT (A(I,*), B(I,*), C(I,*)) (7 A, X(2));\n END;\n END;\n\nPREPARE_MONTH: PROCEDURE (START, MONTH);\n DECLARE MONTH(0:5,0:6) CHARACTER (3);\n DECLARE START CHARACTER (8);\n DECLARE I PIC 'ZZ9';\n DECLARE OFFSET FIXED;\n DECLARE (J, DAY) FIXED BINARY (31);\n DECLARE (THIS_MONTH, NEXT_MONTH, K) FIXED BINARY;\n\n DAY = DAYS(START, 'DDMMYYYY');\n OFFSET = WEEKDAY(DAY) - 1;\n IF OFFSET = 0 THEN OFFSET = 7;\n MONTH = '';\n DO J = DAY BY 1;\n THIS_MONTH = SUBSTR(DAYSTODATE(J, 'DDMMYYYY'), 3, 2);\n NEXT_MONTH = SUBSTR(DAYSTODATE(J+1, 'DDMMYYYY'), 3, 2);\n IF THIS_MONTH^= NEXT_MONTH THEN LEAVE;\n END;\n I = 1;\n DO K = OFFSET-1 TO OFFSET+J-DAY-1;\n MONTH(K/7, MOD(K,7)) = I; I = I + 1;\n END;\nEND PREPARE_MONTH;\n\nEND CALENDAR;\n", "language": "PL-I" }, { "code": "#CI(MODULE NAME-OF-THIS-FILE RACKET\n(REQUIRE RACKET/DATE)\n(DEFINE (CALENDAR YR)\n (DEFINE (NSPLIT N L) (IF (NULL? L) L (CONS (TAKE L N) (NSPLIT N (DROP L N)))))\n (DEFINE MONTHS\n (FOR/LIST ([MN (IN-NATURALS 1)]\n [MNAME '(JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY\n AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER)])\n (DEFINE S (FIND-SECONDS 0 0 12 1 MN YR))\n (DEFINE PFX (DATE-WEEK-DAY (SECONDS->DATE S)))\n (DEFINE DAYS\n (LET ([? (IF (= MN 12) (Λ(X Y) Y) (Λ(X Y) X))])\n (ROUND (/ (- (FIND-SECONDS 0 0 12 1 (? (+ 1 MN) 1) (? YR (+ 1 YR))) S)\n 60 60 24))))\n (LIST* (~A MNAME #:WIDTH 20 #:ALIGN 'CENTER) \"SU MO TU WE TH FR SA\"\n (MAP STRING-JOIN\n (NSPLIT 7 `(,@(MAKE-LIST PFX \" \")\n ,@(FOR/LIST ([D DAYS])\n (~A (+ D 1) #:WIDTH 2 #:ALIGN 'RIGHT))\n ,@(MAKE-LIST (- 42 PFX DAYS) \" \")))))))\n (LET* ([S '(\" 11,-~4-._3. 41-4! 10/ ()=(2) 3\\\\ 40~A! 9( 3( 80 39-4! 10\\\\._\\\\\"\n \", ,-4'! 5#2X3@7! 12/ 2-3'~2;! 11/ 4/~2|-! 9=( 3~4 2|! 3/~42\\\\! \"\n \"2/_23\\\\! /_25\\\\!/_27\\\\! 3|_20|! 3|_20|! 3|_20|! 3| 20|!!\")]\n [S (REGEXP-REPLACE* \"!\" (STRING-APPEND* S) \"~%\")]\n [S (REGEXP-REPLACE* \"@\" S (STRING-FOLDCASE \"X\"))]\n [S (REGEXP-REPLACE* \".(?:[1-7][0-9]*|[1-9])\" S\n (Λ(M) (MAKE-STRING (STRING->NUMBER (SUBSTRING M 1))\n (STRING-REF M 0))))])\n (PRINTF S YR))\n (FOR-EACH (COMPOSE1 DISPLAYLN STRING-TITLECASE)\n (DROPF-RIGHT (FOR*/LIST ([3MS (NSPLIT 3 MONTHS)] [S (APPLY MAP LIST 3MS)])\n (REGEXP-REPLACE \" +$\" (STRING-JOIN S \" \") \"\"))\n (Λ(S) (EQUAL? \"\" S)))))\n\n(CALENDAR 1969))\n", "language": "Racket" }, { "code": "$_=\"\\0\"..\"~\";<\n115 97 121 32 34 91 73 78 83 69 82 84 32 83 78 79 79 80 89 32 72 69 82 69 93 34\n59 114 117 110 32 60 99 97 108 62 44 64 42 65 82 71 83 91 48 93 47 47 49 57 54 57\n>.\"$_[99]$_[104]$_[114]$_[115]\"().\"$_[69]$_[86]$_[65]$_[76]\"()\n", "language": "Raku" }, { "code": "/*REXX PROGRAM TO SHOW ANY YEAR'S (MONTHLY) CALENDAR (WITH/WITHOUT GRID)*/\n@ABC=\nPARSE VALUE SCRSIZE() WITH SD SW .\nDO J=0 TO 255;_=D2C(J);IF DATATYPE(_,'L') THEN @ABC=@ABC||_;END\n@ABCU=@ABC; UPPER @ABCU\nDAYS_='SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY'\nMONTHS_='JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER'\nDAYS=; MONTHS=\n DO J=1 FOR 7\n _=LOWER(WORD(DAYS_,J))\n DAYS=DAYS TRANSLATE(LEFT(_,1))SUBSTR(_,2)\n END\n DO J=1 FOR 12\n _=LOWER(WORD(MONTHS_,J))\n MONTHS=MONTHS TRANSLATE(LEFT(_,1))SUBSTR(_,2)\n END\nCALFILL=' '; MC=12; _='1 3 1234567890' \"FB\"X\nPARSE VAR _ GRID CALSPACES # CHK . CV_ DAYS.1 DAYS.2 DAYS.3 DAYSN\n_=0; PARSE VAR _ COLS 1 JD 1 LOWERCASE 1 MAXKALPUTS 1 NARROW 1,\n NARROWER 1 NARROWEST 1 SHORT 1 SHORTER 1 SHORTEST 1,\n SMALL 1 SMALLER 1 SMALLEST 1 UPPERCASE\nPARSE ARG MM '/' DD \"/\" YYYY _ '(' OPS; UOPS=OPS\nIF _\\=='' | \\IS#(MM) | \\IS#(DD) | \\IS#(YYYY) THEN CALL ERX 86\n\n@CALMONTHS ='CALMON' || LOWER('THS')\n@CALSPACES ='CALSP' || LOWER('ACES')\n@DEPTH ='DEP' || LOWER('TH')\n@GRIDS ='GRID' || LOWER('S')\n@LOWERCASE ='LOW' || LOWER('ERCASE')\n@NARROW ='NAR' || LOWER('ROW')\n@NARROWER ='NARROWER'\n@NARROWEST ='NARROWES' || LOWER('T')\n@SHORT ='SHOR' || LOWER('T')\n@SHORTER ='SHORTER'\n@SHORTEST ='SHORTES' || LOWER('T')\n@UPPERCASE ='UPP' || LOWER('ERCASE')\n@WIDTH ='WID' || LOWER('TH')\n DO WHILE OPS\\==''; OPS=STRIP(OPS,'L'); PARSE VAR OPS _1 2 1 _ . 1 _O OPS\n UPPER _\n SELECT\n WHEN ABB(@CALMONTHS) THEN MC=NAI()\n WHEN ABB(@CALSPACES) THEN CALSPACES=NAI()\n WHEN ABB(@DEPTH) THEN SD=NAI()\n WHEN ABBN(@GRIDS) THEN GRID=NO()\n WHEN ABBN(@LOWERCASE) THEN LOWERCASE=NO()\n WHEN ABBN(@NARROW) THEN NARROW=NO()\n WHEN ABBN(@NARROWER) THEN NARROWER=NO()\n WHEN ABBN(@NARROWEST) THEN NARROWEST=NO()\n WHEN ABBN(@SHORT) THEN SHORT=NO()\n WHEN ABBN(@SHORTER) THEN SHORTER=NO()\n WHEN ABBN(@SHORTEST) THEN SHORTEST=NO()\n WHEN ABBN(@SMALL) THEN SMALL=NO()\n WHEN ABBN(@SMALLER) THEN SMALLER=NO()\n WHEN ABBN(@SMALLEST) THEN SMALLEST=NO()\n WHEN ABBN(@UPPERCASE) THEN UPPERCASE=NO()\n WHEN ABB(@WIDTH) THEN SW=NAI()\n OTHERWISE NOP\n END /*SELECT*/\n END /*DO WHILE OPTS\\== ...*/\n\nIF SD==0 THEN SD= 43; SD= SD-3\nIF SW==0 THEN SW= 80; SW= SW-1\nMC=INT(MC,'MONTHSCALENDER'); IF MC>0 THEN CAL=1\nDAYS=' 'DAYS; MONTHS=' 'MONTHS\nCYYYY=RIGHT(DATE(),4); HYY=LEFT(CYYYY,2); LYY=RIGHT(CYYYY,2)\nDY.=31; _=30; PARSE VAR _ DY.4 1 DY.6 1 DY.9 1 DY.11; DY.2=28+LY(YYYY)\nYY=RIGHT(YYYY,2); CW=10; CINDENT=1; CALWIDTH=76\nIF SMALL THEN DO; NARROW=1 ; SHORT=1 ; END\nIF SMALLER THEN DO; NARROWER=1 ; SHORTER=1 ; END\nIF SMALLEST THEN DO; NARROWEST=1; SHORTEST=1; END\nIF SHORTEST THEN SHORTER=1\nIF SHORTER THEN SHORT =1\nIF NARROW THEN DO; CW=9; CINDENT=3; CALWIDTH=69; END\nIF NARROWER THEN DO; CW=4; CINDENT=1; CALWIDTH=34; END\nIF NARROWEST THEN DO; CW=2; CINDENT=1; CALWIDTH=20; END\nCV_=CALWIDTH+CALSPACES+2\nCALFILL=LEFT(COPIES(CALFILL,CW),CW)\n DO J=1 FOR 7; _=WORD(DAYS,J)\n DO JW=1 FOR 3; _D=STRIP(SUBSTR(_,CW*JW-CW+1,CW))\n IF JW=1 THEN _D=CENTRE(_D,CW+1)\n ELSE _D=LEFT(_D,CW+1)\n DAYS.JW=DAYS.JW||_D\n END /*JW*/\n __=DAYSN\n IF NARROWER THEN DAYSN=__||CENTRE(LEFT(_,3),5)\n IF NARROWEST THEN DAYSN=__||CENTER(LEFT(_,2),3)\n END /*J*/\n_YYYY=YYYY; CALPUTS=0; CV=1; _MM=MM+0; MONTH=WORD(MONTHS,MM)\nDY.2=28+LY(_YYYY); DIM=DY._MM; _DD=01; DOW=DOW(_MM,_DD,_YYYY); $DD=DD+0\n\n/*─────────────────────────────NOW: THE BUSINESS OF THE BUILDING THE CAL*/\nCALL CALGEN\n DO _J=2 TO MC\n IF CV_\\=='' THEN DO\n CV=CV+CV_\n IF CV+CV_>=SW THEN DO; CV=1; CALL CALPUT\n CALL FCALPUTS;CALL CALPB\n END\n ELSE CALPUTS=0\n END\n ELSE DO;CALL CALPB;CALL CALPUT;CALL FCALPUTS;END\n _MM=_MM+1; IF _MM==13 THEN DO; _MM=1; _YYYY=_YYYY+1; END\n MONTH=WORD(MONTHS,_MM); DY.2=28+LY(_YYYY); DIM=DY._MM\n DOW=DOW(_MM,_DD,_YYYY); $DD=0; CALL CALGEN\n END /*_J*/\nCALL FCALPUTS\nRETURN _\n\n/*─────────────────────────────CALGEN SUBROUTINE────────────────────────*/\nCALGEN: CELLX=;CELLJ=;CELLM=;CALCELLS=0;CALLINE=0\nCALL CALPUT\nCALL CALPUTL COPIES('─',CALWIDTH),\"┌┐\"; CALL CALHD\nCALL CALPUTL MONTH ' ' _YYYY ; CALL CALHD\nIF NARROWEST | NARROWER THEN CALL CALPUTL DAYSN\n ELSE DO JW=1 FOR 3\n IF SPACE(DAYS.JW)\\=='' THEN CALL CALPUTL DAYS.JW\n END\nCALFT=1; CALFB=0\n DO JF=1 FOR DOW-1; CALL CELLDRAW CALFILL,CALFILL; END\n DO JY=1 FOR DIM; CALL CELLDRAW JY; END\nCALFB=1\n DO 7; CALL CELLDRAW CALFILL,CALFILL; END\nIF SD>32 & \\SHORTER THEN CALL CALPUT\nRETURN\n\n/*─────────────────────────────CELLDRAW SUBROUTINE──────────────────────*/\nCELLDRAW: PARSE ARG ZZ,CDDOY;ZZ=RIGHT(ZZ,2);CALCELLS=CALCELLS+1\nIF CALCELLS>7 THEN DO\n CALLINE=CALLINE+1\n CELLX=SUBSTR(CELLX,2)\n CELLJ=SUBSTR(CELLJ,2)\n CELLM=SUBSTR(CELLM,2)\n CELLB=TRANSLATE(CELLX,,\")(─-\"#)\n IF CALLINE==1 THEN CALL CX\n CALL CALCSM; CALL CALPUTL CELLX; CALL CALCSJ; CALL CX\n CELLX=; CELLJ=; CELLM=; CALCELLS=1\n END\nCDDOY=RIGHT(CDDOY,CW); CELLM=CELLM'│'CENTER('',CW)\nCELLX=CELLX'│'CENTRE(ZZ,CW); CELLJ=CELLJ'│'CENTER('',CW)\nRETURN\n\n/*═════════════════════════════GENERAL 1-LINE SUBS══════════════════════*/\nABB:ARG ABBU;PARSE ARG ABB;RETURN ABBREV(ABBU,_,ABBL(ABB))\nABBL:RETURN VERIFY(ARG(1)LEFT(@ABC,1),@ABC,'M')-1\nABBN:PARSE ARG ABBN;RETURN ABB(ABBN)|ABB('NO'ABBN)\nCALCSJ:IF SD>49&\\SHORTER THEN CALL CALPUTL CELLB;IF SD>24&\\SHORT THEN CALL CALPUTL CELLJ; RETURN\nCALCSM:IF SD>24&\\SHORT THEN CALL CALPUTL CELLM;IF SD>49&\\SHORTER THEN CALL CALPUTL CELLB;RETURN\nCALHD:IF SD>24&\\SHORTER THEN CALL CALPUTL;IF SD>32&\\SHORTEST THEN CALL CALPUTL;RETURN\nCALPB:IF \\GRID&SHORTEST THEN CALL PUT CHK;RETURN\nCALPUT:CALPUTS=CALPUTS+1;MAXKALPUTS=MAX(MAXKALPUTS,CALPUTS);IF SYMBOL('CT.'CALPUTS)\\=='VAR' THEN CT.CALPUTS=;CT.CALPUTS=OVERLAY(ARG(1),CT.CALPUTS,CV);RETURN\nCALPUTL:CALL CALPUT COPIES(' ',CINDENT)LEFT(ARG(2)\"│\",1)CENTER(ARG(1),CALWIDTH)||RIGHT('│'ARG(2),1);RETURN\nCX:CX_='├┤';CX=COPIES(COPIES('─',CW)'┼',7);IF CALFT THEN DO;CX=TRANSLATE(CX,'┬',\"┼\");CALFT=0;END;IF CALFB THEN DO;CX=TRANSLATE(CX,'┴',\"┼\");CX_='└┘';CALFB=0;END;CALL CALPUTL CX,CX_;RETURN\nDOW:PROCEDURE;ARG M,D,Y;IF M<3 THEN DO;M=M+12;Y=Y-1;END;YL=LEFT(Y,2);YR=RIGHT(Y,2);W=(D+(M+1)*26%10+YR+YR%4+YL%4+5*YL)//7;IF W==0 THEN W=7;RETURN W\nER:PARSE ARG _1,_2;CALL '$ERR' \"14\"P(_1) P(WORD(_1,2) !FID(1)) _2;IF _1<0 THEN RETURN _1;EXIT RESULT\nERR:CALL ER '-'ARG(1),ARG(2);RETURN ''\nERX:CALL ER '-'ARG(1),ARG(2);EXIT ''\nFCALPUTS: DO J=1 FOR MAXKALPUTS;CALL PUT CT.J;END;CT.=;MAXKALPUTS=0;CALPUTS=0;RETURN\nINT:INT=NUMX(ARG(1),ARG(2));IF \\ISINT(INT) THEN CALL ERX 92,ARG(1) ARG(2);RETURN INT/1\nIS#:RETURN VERIFY(ARG(1),#)==0\nISINT:RETURN DATATYPE(ARG(1),'W')\nLOWER:RETURN TRANSLATE(ARG(1),@ABC,@ABCU)\nLY:ARG _;IF LENGTH(_)==2 THEN _=HYY||_;LY=_//4==0;IF LY==0 THEN RETURN 0;LY=((_//100\\==0)|_//400==0);RETURN LY\nNA:IF ARG(1)\\=='' THEN CALL ERX 01,ARG(2);PARSE VAR OPS NA OPS;IF NA=='' THEN CALL ERX 35,_O;RETURN NA\nNAI:RETURN INT(NA(),_O)\nNAN:RETURN NUMX(NA(),_O)\nNO:IF ARG(1)\\=='' THEN CALL ERX 01,ARG(2);RETURN LEFT(_,2)\\=='NO'\nNUM:PROCEDURE;PARSE ARG X .,F,Q;IF X=='' THEN RETURN X;IF DATATYPE(X,'N') THEN RETURN X/1;X=SPACE(TRANSLATE(X,,','),0);IF DATATYPE(X,'N') THEN RETURN X/1;RETURN NUMNOT()\nNUMNOT:IF Q==1 THEN RETURN X;IF Q=='' THEN CALL ER 53,X F;CALL ERX 53,X F\nNUMX:RETURN NUM(ARG(1),ARG(2),1)\nP:RETURN WORD(ARG(1),1)\nPUT:_=ARG(1);_=TRANSLATE(_,,'_'CHK);IF \\GRID THEN _=UNGRID(_);IF LOWERCASE THEN _=LOWER(_);IF UPPERCASE THEN UPPER _;IF SHORTEST&_=' ' THEN RETURN;CALL TELL _;RETURN\nTELL:SAY ARG(1);RETURN\nUNGRID:RETURN TRANSLATE(ARG(1),,\"│║─═┤┐└┴┬├┼┘┌╔╗╚╝╟╢╞╡╫╪╤╧╥╨╠╣\")\n", "language": "REXX" }, { "code": "# PROJECT : CALENDAR - FOR \"REAL\" PROGRAMMERS\n# DATE : 2018/06/28\n# AUTHOR : GAL ZSOLT (~ CALMOSOFT ~)\n# EMAIL : <[email protected]>\n\nLOAD \"GUILIB.RING\"\nLOAD \"STDLIB.RING\"\n\nNEW QAPP\n {\n WIN1 = NEW QWIDGET() {\n DAY = LIST(12)\n POS = NEWLIST(12,37)\n MONTH = LIST(12)\n WEEK = LIST(7)\n WEEKDAY = LIST(7)\n BUTTON = NEWLIST(7,6)\n MONTHSNAMES = LIST(12)\n WEEK = [\"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\"]\n MONTHS = [\"JANUARY\", \"FEBRUARY\", \"MARCH\", \"APRIL\", \"MAY\", \"JUNE\", \"JULY\",\n \"AUGUST\", \"SEPTEMBER\", \"OCTOBER\", \"NOVEMBER\", \"DECEMBER\"]\n DAYSNEW = [[5,1], [6,2], [7,3], [1,4], [2,5], [3,6], [4,7]]\n MO = [4,0,0,3,5,1,3,6,2,4,0,2]\n MON = [31,28,31,30,31,30,31,31,30,31,30,31]\n M2 = (((1969-1900)%7) + FLOOR((1969 - 1900)/4) % 7) % 7\n FOR N = 1 TO 12\n MONTH[N] = (MO[N] + M2) % 7\n X = (MONTH[N] + 1) % 7 + 1\n FOR M = 1 TO LEN(DAYSNEW)\n IF DAYSNEW[M][1] = X\n NR = M\n OK\n NEXT\n DAY[N] = DAYSNEW[NR][2]\n NEXT\n FOR M = 1 TO 12\n FOR N = 1 TO DAY[M] - 1\n POS[M][N] = \" \"\n NEXT\n NEXT\n FOR M = 1 TO 12\n FOR N = DAY[M] TO 37\n IF N < (MON[M] + DAY[M])\n POS[M][N] = N - DAY[M] + 1\n ELSE\n POS[M][N] = \" \"\n OK\n NEXT\n NEXT\n SETWINDOWTITLE(\"CALENDAR\")\n SETGEOMETRY(100,100,650,800)\n LABEL1 = NEW QLABEL(WIN1) {\n SETGEOMETRY(10,10,800,600)\n SETTEXT(\"\")\n }\n YEAR = NEW QPUSHBUTTON(WIN1)\n {\n SETGEOMETRY(280,20,63,20)\n YEAR.SETTEXT(\"1969\")\n }\n FOR N = 1 TO 4\n NR = (N-1)*3+1\n SHOWMONTHS(NR)\n NEXT\n FOR N = 1 TO 12\n SHOWWEEKS(N)\n NEXT\n FOR N = 1 TO 12\n SHOWDAYS(N)\n NEXT\n SHOW()\n }\n EXEC()\n }\n\nFUNC SHOWMONTHS(M)\n FOR N = M TO M + 2\n MONTHSNAMES[N] = NEW QPUSHBUTTON(WIN1)\n {\n IF N%3 = 1\n COL = 120\n ROWNR = FLOOR(N/3)\n IF ROWNR = 0\n ROWNR = N/3\n OK\n IF N = 1\n ROW = 40\n ELSE\n ROW = 40+ROWNR*180\n OK\n ELSE\n COLNR = N%3\n IF COLNR = 0\n COLNR = 3\n OK\n ROWNR = FLOOR(N/3)\n IF N%3 = 0\n ROWNR = FLOOR(N/3)-1\n OK\n COL = 120 + (COLNR-1)*160\n ROW = 40 + ROWNR*180\n OK\n SETGEOMETRY(COL,ROW,63,20)\n MONTHSNAMES[N].SETTEXT(MONTHS[N])\n }\n NEXT\n\nFUNC SHOWWEEKS(N)\n FOR M = 1 TO 7\n COL = M%7\n IF COL = 0 COL = 7 OK\n WEEKDAY[M] = NEW QPUSHBUTTON(WIN1)\n {\n COLNR = N % 3\n IF COLNR = 0\n COLNR = 3\n OK\n ROWNR = FLOOR(N/3)\n IF N%3 = 0\n ROWNR = FLOOR(N/3)-1\n OK\n COLBEGIN = 60 + (COLNR-1)*160\n ROWBEGIN = 60 + (ROWNR)*180\n SETGEOMETRY(COLBEGIN+COL*20,ROWBEGIN,25,20)\n WEEKDAY[M].SETTEXT(WEEK[M])\n }\n NEXT\n\nFUNC SHOWDAYS(IND)\n ROWNR = FLOOR(IND/3)\n IF IND%3 = 0\n ROWNR = FLOOR(IND/3)-1\n OK\n ROWBEGIN = 60+ROWNR*180\n FOR M = 1 TO 6\n FOR N = 1 TO 7\n COL = N%7\n IF COL = 0 COL = 7 OK\n ROW = M\n BUTTON[N][M] = NEW QPUSHBUTTON(WIN1)\n {\n IF IND%3 = 1\n COLBEGIN = 60\n ELSEIF IND%3 = 2\n COLBEGIN = 220\n ELSE\n COLBEGIN = 380\n OK\n SETGEOMETRY(COLBEGIN+COL*20,ROWBEGIN+ROW*20,25,20)\n NR = (M-1)*7+N\n IF NR <= 37\n IF POS[IND][NR] != \" \"\n BUTTON[N][M].SETTEXT(STRING(POS[IND][NR]))\n OK\n OK\n }\n NEXT\n NEXT\n", "language": "Ring" }, { "code": "# loadup.rb - run UPPERCASE RUBY program\n\nclass Object\n alias lowercase_method_missing method_missing\n\n # Allow UPPERCASE method calls.\n def method_missing(sym, *args, &block)\n str = sym.to_s\n if str == (down = str.downcase)\n lowercase_method_missing sym, *args, &block\n else\n send down, *args, &block\n end\n end\n\n # RESCUE an exception without the 'rescue' keyword.\n def RESCUE(_BEGIN, _CLASS, _RESCUE)\n begin _BEGIN.CALL\n rescue _CLASS\n _RESCUE.CALL; end\n end\nend\n\n_PROGRAM = ARGV.SHIFT\n_PROGRAM || ABORT(\"USAGE: #{$0} PROGRAM.RB ARGS...\")\nLOAD($0 = _PROGRAM)\n", "language": "Ruby" }, { "code": "# CAL.RB - CALENDAR\nREQUIRE 'DATE'.DOWNCASE\n\n# FIND CLASSES.\nOBJECT = [].CLASS.SUPERCLASS\nDATE = OBJECT.CONST_GET('DATE'.DOWNCASE.CAPITALIZE)\n\n# CREATES A CALENDAR OF _YEAR_. RETURNS THIS CALENDAR AS A MULTI-LINE\n# STRING FIT TO _COLUMNS_.\nOBJECT.SEND(:DEFINE_METHOD, :CAL) {|_YEAR, _COLUMNS|\n\n # START AT JANUARY 1.\n #\n # DATE::ENGLAND MARKS THE SWITCH FROM JULIAN CALENDAR TO GREGORIAN\n # CALENDAR AT 1752 SEPTEMBER 14. THIS REMOVES SEPTEMBER 3 TO 13 FROM\n # YEAR 1752. (BY FORTUNE, IT KEEPS JANUARY 1.)\n #\n _DATE = DATE.NEW(_YEAR, 1, 1, DATE::ENGLAND)\n\n # COLLECT CALENDARS OF ALL 12 MONTHS.\n _MONTHS = (1..12).COLLECT {|_MONTH|\n _ROWS = [DATE::MONTHNAMES[_MONTH].UPCASE.CENTER(20),\n \"SU MO TU WE TH FR SA\"]\n\n # MAKE ARRAY OF 42 DAYS, STARTING WITH SUNDAY.\n _DAYS = []\n _DATE.WDAY.TIMES { _DAYS.PUSH \" \" }\n CATCH(:BREAK) {\n LOOP {\n (_DATE.MONTH == _MONTH) || THROW(:BREAK)\n _DAYS.PUSH(\"%2D\".DOWNCASE % _DATE.MDAY)\n _DATE += 1 }}\n (42 - _DAYS.LENGTH).TIMES { _DAYS.PUSH \" \" }\n\n _DAYS.EACH_SLICE(7) {|_WEEK| _ROWS.PUSH(_WEEK.JOIN \" \") }\n _ROWS }\n\n # CALCULATE MONTHS PER ROW (MPR).\n # 1. DIVIDE COLUMNS BY 22 COLUMNS PER MONTH, ROUNDED DOWN. (PRETEND\n # TO HAVE 2 EXTRA COLUMNS; LAST MONTH USES ONLY 20 COLUMNS.)\n # 2. DECREASE MPR IF 12 MONTHS WOULD FIT IN THE SAME MONTHS PER\n # COLUMN (MPC). FOR EXAMPLE, IF WE CAN FIT 5 MPR AND 3 MPC, THEN\n # WE USE 4 MPR AND 3 MPC.\n _MPR = (_COLUMNS + 2).DIV 22\n _MPR = 12.DIV((12 + _MPR - 1).DIV _MPR)\n\n # USE 20 COLUMNS PER MONTH + 2 SPACES BETWEEN MONTHS.\n _WIDTH = _MPR * 22 - 2\n\n # JOIN MONTHS INTO CALENDAR.\n _ROWS = [\"[SNOOPY]\".CENTER(_WIDTH), \"#{_YEAR}\".CENTER(_WIDTH)]\n _MONTHS.EACH_SLICE(_MPR) {|_SLICE|\n _SLICE[0].EACH_INDEX {|_I|\n _ROWS.PUSH(_SLICE.MAP {|_A| _A[_I]}.JOIN \" \") }}\n _ROWS.JOIN(\"\\012\") }\n\n\n(ARGV.LENGTH == 1) || ABORT(\"USAGE: #{$0} YEAR\")\n\n# GUESS WIDTH OF TERMINAL.\n# 1. OBEY ENVIRONMENT VARIABLE COLUMNS.\n# 2. TRY TO REQUIRE 'IO/CONSOLE' FROM RUBY 1.9.3.\n# 3. TRY TO RUN `TPUT CO`.\n# 4. ASSUME 80 COLUMNS.\nLOADERROR = OBJECT.CONST_GET('LOAD'.DOWNCASE.CAPITALIZE +\n 'ERROR'.DOWNCASE.CAPITALIZE)\nSTANDARDERROR = OBJECT.CONST_GET('STANDARD'.DOWNCASE.CAPITALIZE +\n 'ERROR'.DOWNCASE.CAPITALIZE)\n_INTEGER = 'INTEGER'.DOWNCASE.CAPITALIZE\n_TPUT_CO = 'TPUT CO'.DOWNCASE\n_COLUMNS = RESCUE(PROC {SEND(_INTEGER, ENV[\"COLUMNS\"] || \"\")},\n STANDARDERROR,\n PROC {\n RESCUE(PROC {\n REQUIRE 'IO/CONSOLE'.DOWNCASE\n IO.CONSOLE.WINSIZE[1]\n }, LOADERROR,\n PROC {\n RESCUE(PROC {\n SEND(_INTEGER, `#{_TPUT_CO}`)\n }, STANDARDERROR,\n PROC {80}) }) })\n\nPUTS CAL(ARGV[0].TO_I, _COLUMNS)\n", "language": "Ruby" }, { "code": "$ include \"seed7_05.s7i\";\n include \"getf.s7i\";\n include \"progs.s7i\";\n\nconst proc: main is func\n local\n var string: source is \"\";\n begin\n source := lower(getf(\"CALENDAR.TXT\"));\n source := replace(source, \"dayofweek\", \"dayOfWeek\");\n source := replace(source, \"daysinmonth\", \"daysInMonth\");\n execute(parseStri(source));\n end func;\n", "language": "Seed7" }, { "code": "-> DT { ('DATE'.(\"\\LWC\") + 'TIME'.(\"\\LWC\")).(\"\\LREQUIRE\") }\n\n-> MONTHS_PER_COL { 6 }\n-> WEEK_DAY_NAMES { <MO TU WE TH FR SA SU> }\n-> MONTH_NAMES { <JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC> }\n\n-> FMT_MONTH (YEAR, MONTH, STR=\"\", WEEK_DAY=0) {\n STR = \"%11\\LS\\E%9\\LS\\E\\12\".(\"\\LSPRINTF\")(MONTH_NAMES()[MONTH-1],'')\n STR += (WEEK_DAY_NAMES().(\"\\LJOIN\")(' ') + \"\\12\")\n\n -> DATE { DT().(\"\\LNEW\")(\"\\LYEAR\" => YEAR, \"\\LMONTH\" => MONTH) }\n\n WEEK_DAY = DATE().(\"\\LDAY_OF_WEEK\")\n STR += ([\" \"] * WEEK_DAY-1 -> (\"\\LJOIN\")(\" \"))\n\n -> LAST_DAY {\n DT().(\"\\LLAST_DAY_OF_MONTH\")(\n \"\\LYEAR\" => YEAR, \"\\LMONTH\" => MONTH\n ).(\"\\LDAY\")\n }\n\n (DATE().(\"\\LDAY\") .. LAST_DAY()).(\"\\LEACH\")({ |DAY|\n (WEEK_DAY ~~ (2..7)) && (STR += \" \")\n\n (WEEK_DAY == 8) && (\n STR += \"\\12\"\n WEEK_DAY = 1\n )\n STR += (\"%2\\LD\" % DAY)\n ++WEEK_DAY\n })\n (WEEK_DAY < 8) && (STR += \" \")\n STR += ([\" \"] * 8-WEEK_DAY -> (\"\\LJOIN\")(\" \"))\n STR += \"\\12\"\n}\n\n-> FMT_YEAR (YEAR, STR=\"\", MONTH_STRS=[]) {\n MONTH_STRS = 12.(\"\\LOF\")({|I| FMT_MONTH(YEAR, I+1).(\"\\LLINES\") })\n\n STR += (' '*(MONTHS_PER_COL()*10 + 2) + YEAR + \"\\12\")\n (0..11 -> (\"\\LBY\")(MONTHS_PER_COL())).(\"\\LEACH\")({ |MONTH|\n MONTH_STRS[MONTH] && ->() {\n { |I|\n MONTH_STRS[MONTH + I] && (\n STR += MONTH_STRS[MONTH + I].(\"\\LSHIFT\")\n STR += ' '*2\n )\n } * MONTHS_PER_COL()\n\n STR += \"\\12\"\n MONTH_STRS[MONTH] && __FUNC__()\n }()\n STR += \"\\12\"\n })\n\n STR\n}\n\nFMT_YEAR(ARGV ? ARGV[0].(\"\\LTO_I\") : 1969).(\"\\LPRINT\")\n", "language": "Sidef" }, { "code": "\\146\\157\\162\\145\\141\\143\\150 42 [\\151\\156\\146\\157 \\143\\157\\155\\155\\141\\156\\144\\163] {\n\t\\145\\166\\141\\154 \"\n\t\t\\160\\162\\157\\143 [\\163\\164\\162\\151\\156\\147 \\164\\157\\165\\160\\160\\145\\162 $42] {\\141\\162\\147\\163} \\{\n\t\t\t\\163\\145\\164 \\151 1\n\t\t\t\\146\\157\\162\\145\\141\\143\\150 \\141 \\$\\141\\162\\147\\163 \\{\n\t\t\t\t\\151\\146 \\[\\163\\164\\162\\151\\156\\147 \\155\\141\\164\\143\\150 _ \\$\\141\\] \\{\\151\\156\\143\\162 \\151; \\143\\157\\156\\164\\151\\156\\165\\145\\}\n\t\t\t\t\\151\\146 \\$\\151%2 \\{\\154\\141\\160\\160\\145\\156\\144 \\156\\141\\162\\147\\163 \\[\\163\\164\\162\\151\\156\\147 \\164\\157\\154\\157\\167\\145\\162 \\$\\141\\]\\} \\{\\154\\141\\160\\160\\145\\156\\144 \\156\\141\\162\\147\\163 \\$\\141\\}\n\t\t\t\t\\}\n\t\t\t\\165\\160\\154\\145\\166\\145\\154 \\\"$42 \\$\\156\\141\\162\\147\\163\\\"\n\t\t\t\\}\n\t\t\"\n\t}\n\nPROC _ CPUTS {L S} {\n\tUPVAR _ CAL CAL\n\tAPPEND _ CAL($L) $S\n\t}\nPROC _ CENTER {S LN} {\n\tSET _ C [STRING LENGTH $S]\n\tSET _ L [EXPR _ ($LN-$C)/2]; SET _ R [EXPR _ $LN-$L-$C]\n\tFORMAT \"%${L}S%${C}S%${R}S\" _ \"\" $S \"\"\n\t}\nPROC _ CALENDAR {{YEAR 1969} {WIDTH 80}} {\n\tARRAY SET CAL \"\"\n\tSET _ YRS [EXPR $YEAR-1584]\n\tSET _ SDAY [EXPR (6+$YRS+(($YRS+3)/4)-(($YRS-17)/100+1)+(($YRS+383)/400))%7]\n\tCPUTS 0 [CENTER \"(SNOOPY)\" [EXPR $WIDTH/25*25]]; CPUTS 1 \"\"\n\tCPUTS 2 [CENTER \"--- $YEAR ---\" [EXPR $WIDTH/25*25]]; CPUTS 3 \"\"\n\tFOR _ {SET _ NR 0} {$NR<=11} {INCR _ NR} {\n\t\tSET _ LINE [EXPR ($NR/($WIDTH/25))*8+4]\n\t\tSET _ NAME [LINDEX _ \"JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER\" $NR]\n\t\tSET _ DAYS [EXPR 31-((($NR)%7)%2)-($NR==1)*(2-((($YEAR%4==0)&&($YEAR%100>0))||($YEAR%400==0)))]\n\t\tCPUTS $LINE \"[CENTER $NAME 20] \"\n\t\tCPUTS [INCR _ LINE] \"MO TU WE TH FR SA SU \"; INCR _ LINE\n\t\tSET _ DAY [EXPR 1-$SDAY]\n\t\tFOR _ {SET _ X 0} {$X<42} {INCR _ X} {\n\t\t\tIF _ ($DAY>0)&&($DAY<=$DAYS) {CPUTS $LINE [FORMAT \"%2d \" $DAY]} {CPUTS $LINE \" \"}\n\t\t\tIF _ (($X+1)%7)==0 {CPUTS $LINE \" \"; INCR _ LINE}\n\t\t\tINCR _ DAY\n\t\t\t}\n\t\tSET _ SDAY [EXPR ($SDAY+($DAYS%7))%7]\n\t\t}\n\tFOR _ {SET _ X 0} {$X<[ARRAY SIZE _ CAL]} {INCR _ X} {\n\t\tPUTS _ $CAL($X)\n\t\t}\n\t}\n\t\nCALENDAR\n", "language": "Tcl" }, { "code": "CAL=CAL\nTR=TR\nA=A\nZ=Z\nLANG=C ${CAL,,} 1969 | ${TR,,} ${A,}-${Z,} A-Z\n", "language": "UNIX-Shell" }, { "code": "BS(BF)\nCFT(22)\n#3 = 6 // NUMBER OF MONTHS PER LINE\n#2 = 1969 // YEAR\n#1 = 1 // STARTING MONTH\nIC(' ', COUNT, #3*9) IT(\"[SNOOPY]\") IN(2)\nIC(' ', COUNT, #3*9+1) NI(#2) IN\nREPEAT(12/#3) {\n REPEAT (#3) {\n BS(BF)\n\tCALL(\"DRAW_CALENDAR\")\n\tRCB(10, 1, EOB_POS, COLSET, 1, 21)\n\tBQ(OK)\n\t#5 = CP\n\tRI(10)\n\tGP(#5)\n\tEOL IC(9)\n\t#1++\n }\n EOF IN(2)\n}\nRETURN\n\n:DRAW_CALENDAR:\nNUM_PUSH(4,20)\n#20 = RF\nBOF DC(ALL)\n\nNI(#1, LEFT+NOCR) IT(\"/1/\") NI(#2, LEFT+NOCR)\nRCB(#20, BOL_POS, EOL_POS, DELETE)\n#10 = JDATE(@(#20))\n\n#4 = #2+(#1==12)\nNI(#1%12+1, LEFT+NOCR) IT(\"/1/\") NI(#4, LEFT+NOCR)\nRCB(#20, BOL_POS, CP, DELETE)\n#11 = JDATE(@(#20)) - #10\n#7 = (#10-1) % 7\n\nIF (#1==1) { RS(#20,\" JANUARY \") }\nIF (#1==2) { RS(#20,\" FEBRUARY\") }\nIF (#1==3) { RS(#20,\" MARCH \") }\nIF (#1==4) { RS(#20,\" APRIL \") }\nIF (#1==5) { RS(#20,\" MAY \") }\nIF (#1==6) { RS(#20,\" JUNE \") }\nIF (#1==7) { RS(#20,\" JULY \") }\nIF (#1==8) { RS(#20,\" AUGUST \") }\nIF (#1==9) { RS(#20,\"SEPTEMBER\") }\nIF (#1==10) { RS(#20,\" OCTOBER \") }\nIF (#1==11) { RS(#20,\" NOVEMBER\") }\nIF (#1==12) { RS(#20,\" DECEMBER\") }\n\nIT(\" \") RI(#20) IN\nIT(\" MO TU WE TH FR SA SU\") IN\nIT(\" --------------------\") IN\nIC(' ', COUNT, #7*3)\nFOR (#8 = 1; #8 <= #11; #8++) {\n NI(#8, COUNT, 3)\n #5 = (#8+#10+5) % 7\n IF (#5 == 6) { IN }\n}\nIT(\" \")\n\nREG_EMPTY(#20)\nNUM_POP(4,20)\nRETURN\n", "language": "Vedit-macro-language" }, { "code": "OPTION COMPARE BINARY\nOPTION EXPLICIT ON\nOPTION INFER ON\nOPTION STRICT ON\n\nIMPORTS SYSTEM.GLOBALIZATION\nIMPORTS SYSTEM.TEXT\nIMPORTS SYSTEM.RUNTIME.INTEROPSERVICES\nIMPORTS SYSTEM.RUNTIME.COMPILERSERVICES\n\nMODULE ARGHELPER\n READONLY _ARGDICT AS NEW DICTIONARY(OF STRING, STRING)()\n\n DELEGATE FUNCTION TRYPARSE(OF T, TRESULT)(VALUE AS T, <OUT> BYREF RESULT AS TRESULT) AS BOOLEAN\n\n SUB INITIALIZEARGUMENTS(ARGS AS STRING())\n FOR EACH ITEM IN ARGS\n ITEM = ITEM.TOUPPERINVARIANT()\n\n IF ITEM.LENGTH > 0 ANDALSO ITEM(0) <> \"\"\"\"C THEN\n DIM COLONPOS = ITEM.INDEXOF(\":\"C, STRINGCOMPARISON.ORDINAL)\n\n IF COLONPOS <> -1 THEN\n ' SPLIT ARGUMENTS WITH COLUMNS INTO KEY(PART BEFORE COLON) / VALUE(PART AFTER COLON) PAIRS.\n _ARGDICT.ADD(ITEM.SUBSTRING(0, COLONPOS), ITEM.SUBSTRING(COLONPOS + 1, ITEM.LENGTH - COLONPOS - 1))\n END IF\n END IF\n NEXT\n END SUB\n\n SUB FROMARGUMENT(OF T)(\n KEY AS STRING,\n <OUT> BYREF VAR AS T,\n GETDEFAULT AS FUNC(OF T),\n TRYPARSE AS TRYPARSE(OF STRING, T),\n OPTIONAL VALIDATE AS PREDICATE(OF T) = NOTHING)\n\n DIM VALUE AS STRING = NOTHING\n IF _ARGDICT.TRYGETVALUE(KEY.TOUPPERINVARIANT(), VALUE) THEN\n IF NOT (TRYPARSE(VALUE, VAR) ANDALSO (VALIDATE IS NOTHING ORELSE VALIDATE(VAR))) THEN\n CONSOLE.WRITELINE($\"INVALID VALUE FOR {KEY}: {VALUE}\")\n ENVIRONMENT.EXIT(-1)\n END IF\n ELSE\n VAR = GETDEFAULT()\n END IF\n END SUB\nEND MODULE\n\nMODULE PROGRAM\n SUB MAIN(ARGS AS STRING())\n DIM DT AS DATE\n DIM COLUMNS, ROWS, MONTHSPERROW AS INTEGER\n DIM VERTSTRETCH, HORIZSTRETCH, RESIZEWINDOW AS BOOLEAN\n\n INITIALIZEARGUMENTS(ARGS)\n FROMARGUMENT(\"DATE\", DT, FUNCTION() NEW DATE(1969, 1, 1), ADDRESSOF DATE.TRYPARSE)\n FROMARGUMENT(\"COLS\", COLUMNS, FUNCTION() 80, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 20)\n FROMARGUMENT(\"ROWS\", ROWS, FUNCTION() 43, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 0)\n FROMARGUMENT(\"MS/ROW\", MONTHSPERROW, FUNCTION() 0, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V <= 12 ANDALSO V <= COLUMNS \\ 20)\n FROMARGUMENT(\"VSTRETCH\", VERTSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n FROMARGUMENT(\"HSTRETCH\", HORIZSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n FROMARGUMENT(\"WSIZE\", RESIZEWINDOW, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n\n ' THE SCROLL BAR IN COMMAND PROMPT SEEMS TO TAKE UP PART OF THE LAST COLUMN.\n IF RESIZEWINDOW THEN\n CONSOLE.WINDOWWIDTH = COLUMNS + 1\n CONSOLE.WINDOWHEIGHT = ROWS\n END IF\n\n IF MONTHSPERROW < 1 THEN MONTHSPERROW = MATH.MAX(COLUMNS \\ 22, 1)\n\n FOR EACH ROW IN GETCALENDARROWS(DT:=DT, WIDTH:=COLUMNS, HEIGHT:=ROWS, MONTHSPERROW:=MONTHSPERROW, VERTSTRETCH:=VERTSTRETCH, HORIZSTRETCH:=HORIZSTRETCH)\n CONSOLE.WRITE(ROW)\n NEXT\n END SUB\n\n ITERATOR FUNCTION GETCALENDARROWS(\n DT AS DATE,\n WIDTH AS INTEGER,\n HEIGHT AS INTEGER,\n MONTHSPERROW AS INTEGER,\n VERTSTRETCH AS BOOLEAN,\n HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)\n\n DIM YEAR = DT.YEAR\n DIM CALENDARROWCOUNT AS INTEGER = CINT(MATH.CEILING(12 / MONTHSPERROW))\n ' MAKE ROOM FOR THE THREE EMPTY LINES ON TOP.\n DIM MONTHGRIDHEIGHT AS INTEGER = HEIGHT - 3\n\n YIELD \"[SNOOPY]\".PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE\n YIELD YEAR.TOSTRING(CULTUREINFO.INVARIANTCULTURE).PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE\n YIELD ENVIRONMENT.NEWLINE\n\n DIM MONTH = 0\n DO WHILE MONTH < 12\n DIM ROWHIGHESTMONTH = MATH.MIN(MONTH + MONTHSPERROW, 12)\n\n DIM CELLWIDTH = WIDTH \\ MONTHSPERROW\n DIM CELLCONTENTWIDTH = IF(MONTHSPERROW = 1, CELLWIDTH, (CELLWIDTH * 19) \\ 20)\n\n DIM CELLHEIGHT = MONTHGRIDHEIGHT \\ CALENDARROWCOUNT\n DIM CELLCONTENTHEIGHT = (CELLHEIGHT * 19) \\ 20\n\n ' CREATES A MONTH CELL FOR THE SPECIFIED MONTH (1-12).\n DIM GETMONTHFROM =\n FUNCTION(M AS INTEGER) BUILDMONTH(\n DT:=NEW DATE(DT.YEAR, M, 1),\n WIDTH:=CELLCONTENTWIDTH,\n HEIGHT:=CELLCONTENTHEIGHT,\n VERTSTRETCH:=VERTSTRETCH,\n HORIZSTRETCH:=HORIZSTRETCH).SELECT(FUNCTION(X) X.PADCENTER(CELLWIDTH))\n\n ' THE MONTHS IN THIS ROW OF THE CALENDAR.\n DIM MONTHSTHISROW AS IENUMERABLE(OF IENUMERABLE(OF STRING)) =\n ENUMERABLE.SELECT(ENUMERABLE.RANGE(MONTH + 1, ROWHIGHESTMONTH - MONTH), GETMONTHFROM)\n\n DIM CALENDARROW AS IENUMERABLE(OF STRING) =\n INTERLEAVED(\n MONTHSTHISROW,\n USEINNERSEPARATOR:=FALSE,\n USEOUTERSEPARATOR:=TRUE,\n OUTERSEPARATOR:=ENVIRONMENT.NEWLINE)\n\n DIM EN = CALENDARROW.GETENUMERATOR()\n DIM HASNEXT = EN.MOVENEXT()\n DO WHILE HASNEXT\n\n DIM CURRENT AS STRING = EN.CURRENT\n\n ' TO MAINTAIN THE (NOT STRICTLY NEEDED) CONTRACT OF YIELDING COMPLETE ROWS, KEEP THE NEWLINE AFTER\n ' THE CALENDAR ROW WITH THE LAST TERMINAL ROW OF THE ROW.\n HASNEXT = EN.MOVENEXT()\n YIELD IF(HASNEXT, CURRENT, CURRENT & ENVIRONMENT.NEWLINE)\n LOOP\n\n MONTH += MONTHSPERROW\n LOOP\n END FUNCTION\n\n ''' <SUMMARY>\n ''' INTERLEAVES THE ELEMENTS OF THE SPECIFIED SUB-SOURCES BY MAKING SUCCESSIVE PASSES THROUGH THE SOURCE\n ''' ENUMERABLE, YIELDING A SINGLE ELEMENT FROM EACH SUB-SOURCE IN SEQUENCE IN EACH PASS, OPTIONALLY INSERTING A\n ''' SEPARATOR BETWEEN ELEMENTS OF ADJACENT SUB-SOURCES AND OPTIONALLY A DIFFERENT SEPARATOR AT THE END OF EACH\n ''' PASS THROUGH ALL THE SOURCES. (I.E., BETWEEN ELEMENTS OF THE LAST AND FIRST SOURCE)\n ''' </SUMMARY>\n ''' <TYPEPARAM NAME=\"T\">THE TYPE OF THE ELEMENTS OF THE SUB-SOURCES.</TYPEPARAM>\n ''' <PARAM NAME=\"SOURCES\">A SEQUENCE OF THE SEQUENCES WHOSE ELEMENTS ARE TO BE INTERLEAVED.</PARAM>\n ''' <PARAM NAME=\"USEINNERSEPARATOR\">WHETHER TO INSERT <PARAMREF NAME=\"USEINNERSEPARATOR\"/> BETWEEN THE ELEMENTS OFADJACENT SUB-SOURCES.</PARAM>\n ''' <PARAM NAME=\"INNERSEPARATOR\">THE SEPARATOR BETWEEN ELEMENTS OF ADJACENT SUB-SOURCES.</PARAM>\n ''' <PARAM NAME=\"USEOUTERSEPARATOR\">WHETHER TO INSERT <PARAMREF NAME=\"OUTERSEPARATOR\"/> BETWEEN THE ELEMENTS OF THE LAST AND FIRST SUB-SOURCES.</PARAM>\n ''' <PARAM NAME=\"OUTERSEPARATOR\">THE SEPARATOR BETWEEN ELEMENTS OF THE LAST AND FIRST SUB-SOURCE.</PARAM>\n ''' <PARAM NAME=\"WHILEANY\">IF <SEE LANGWORD=\"TRUE\"/>, THE ENUMERATION CONTINUES UNTIL EVERY GIVEN SUBSOURCE IS EMPTY;\n ''' IF <SEE LANGWORD=\"FALSE\"/>, THE ENUMERATION STOPS AS SOON AS ANY ENUMERABLE NO LONGER HAS AN ELEMENT TO SUPPLY FOR THE NEXT PASS.</PARAM>\n ITERATOR FUNCTION INTERLEAVED(OF T)(\n SOURCES AS IENUMERABLE(OF IENUMERABLE(OF T)),\n OPTIONAL USEINNERSEPARATOR AS BOOLEAN = FALSE,\n OPTIONAL INNERSEPARATOR AS T = NOTHING,\n OPTIONAL USEOUTERSEPARATOR AS BOOLEAN = FALSE,\n OPTIONAL OUTERSEPARATOR AS T = NOTHING,\n OPTIONAL WHILEANY AS BOOLEAN = TRUE) AS IENUMERABLE(OF T)\n DIM SOURCEENUMERATORS AS IENUMERATOR(OF T)() = NOTHING\n\n TRY\n SOURCEENUMERATORS = SOURCES.SELECT(FUNCTION(X) X.GETENUMERATOR()).TOARRAY()\n DIM NUMSOURCES = SOURCEENUMERATORS.LENGTH\n DIM ENUMERATORSTATES(NUMSOURCES - 1) AS BOOLEAN\n\n DIM ANYPREVITERS AS BOOLEAN = FALSE\n DO\n ' INDICES OF FIRST AND LAST SUB-SOURCES THAT HAVE ELEMENTS.\n DIM FIRSTACTIVE = -1, LASTACTIVE = -1\n\n ' DETERMINE WHETHER EACH SUB-SOURCE THAT STILL HAVE ELEMENTS.\n FOR I = 0 TO NUMSOURCES - 1\n ENUMERATORSTATES(I) = SOURCEENUMERATORS(I).MOVENEXT()\n IF ENUMERATORSTATES(I) THEN\n IF FIRSTACTIVE = -1 THEN FIRSTACTIVE = I\n LASTACTIVE = I\n END IF\n NEXT\n\n ' DETERMINE WHETHER TO YIELD ANYTHING IN THIS ITERATION BASED ON WHETHER WHILEANY IS TRUE.\n ' NOT YIELDING ANYTHING THIS ITERATION IMPLIES THAT THE ENUMERATION HAS ENDED.\n DIM THISITERHASRESULTS AS BOOLEAN = IF(WHILEANY, FIRSTACTIVE <> -1, FIRSTACTIVE = 0 ANDALSO LASTACTIVE = NUMSOURCES - 1)\n IF NOT THISITERHASRESULTS THEN EXIT DO\n\n ' DON'T INSERT A SEPARATOR ON THE FIRST PASS.\n IF ANYPREVITERS THEN\n IF USEOUTERSEPARATOR THEN YIELD OUTERSEPARATOR\n ELSE\n ANYPREVITERS = TRUE\n END IF\n\n ' GO THROUGH AND YIELD FROM THE SUB-SOURCES THAT STILL HAVE ELEMENTS.\n FOR I = 0 TO NUMSOURCES - 1\n IF ENUMERATORSTATES(I) THEN\n ' DON'T INSERT A SEPARATOR BEFORE THE FIRST ELEMENT.\n IF I > FIRSTACTIVE ANDALSO USEINNERSEPARATOR THEN YIELD INNERSEPARATOR\n YIELD SOURCEENUMERATORS(I).CURRENT\n END IF\n NEXT\n LOOP\n\n FINALLY\n IF SOURCEENUMERATORS ISNOT NOTHING THEN\n FOR EACH EN IN SOURCEENUMERATORS\n EN.DISPOSE()\n NEXT\n END IF\n END TRY\n END FUNCTION\n\n ''' <SUMMARY>\n ''' RETURNS THE ROWS REPRESENTING ONE MONTH CELL WITHOUT TRAILING NEWLINES. APPROPRIATE LEADING AND TRAILING\n ''' WHITESPACE IS ADDED SO THAT EVERY ROW HAS THE LENGTH OF WIDTH.\n ''' </SUMMARY>\n ''' <PARAM NAME=\"DT\">A DATE WITHIN THE MONTH TO REPRESENT.</PARAM>\n ''' <PARAM NAME=\"WIDTH\">THE WIDTH OF THE CELL.</PARAM>\n ''' <PARAM NAME=\"HEIGHT\">THE HEIGHT.</PARAM>\n ''' <PARAM NAME=\"VERTSTRETCH\">IF <SEE LANGWORD=\"TRUE\" />, BLANK ROWS ARE INSERTED TO FIT THE AVAILABLE HEIGHT.\n ''' OTHERWISE, THE CELL HAS A CONSTANT HEIGHT OF </PARAM>\n ''' <PARAM NAME=\"HORIZSTRETCH\">IF <SEE LANGWORD=\"TRUE\" />, THE SPACING BETWEEN INDIVIDUAL DAYS IS INCREASED TO\n ''' FIT THE AVAILABLE WIDTH. OTHERWISE, THE CELL HAS A CONSTANT WIDTH OF 20 CHARACTERS AND IS PADDED TO BE IN\n ''' THE CENTER OF THE EXPECTED WIDTH.</PARAM>\n ITERATOR FUNCTION BUILDMONTH(DT AS DATE, WIDTH AS INTEGER, HEIGHT AS INTEGER, VERTSTRETCH AS BOOLEAN, HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)\n CONST DAY_WDT = 2 ' WIDTH OF A DAY.\n CONST ALLDAYS_WDT = DAY_WDT * 7 ' WIDTH OF AL LDAYS COMBINED.\n\n ' NORMALIZE THE DATE TO JANUARY 1.\n DT = NEW DATE(DT.YEAR, DT.MONTH, 1)\n\n ' HORIZONTAL WHITESPACE BETWEEN DAYS OF THE WEEK. CONSTANT OF 6 REPRESENTS 6 SEPARATORS PER LINE.\n DIM DAYSEP AS NEW STRING(\" \"C, MATH.MIN((WIDTH - ALLDAYS_WDT) \\ 6, IF(HORIZSTRETCH, INTEGER.MAXVALUE, 1)))\n ' NUMBER OF BLANK LINES BETWEEN ROWS.\n DIM VERTBLANKCOUNT = IF(NOT VERTSTRETCH, 0, (HEIGHT - 8) \\ 7)\n\n ' WIDTH OF EACH DAY * 7 DAYS IN ONE ROW + DAY SEPARATOR LENGTH * 6 SEPARATORS PER LINE.\n DIM BLOCKWIDTH = ALLDAYS_WDT + DAYSEP.LENGTH * 6\n\n ' THE WHITESPACE AT THE BEGINNING OF EACH LINE.\n DIM LEFTPAD AS NEW STRING(\" \"C, (WIDTH - BLOCKWIDTH) \\ 2)\n ' THE WHITESPACE FOR BLANK LINES.\n DIM FULLPAD AS NEW STRING(\" \"C, WIDTH)\n\n ' LINES ARE \"STAGED\" IN THE STRINGBUILDER.\n DIM SB AS NEW STRINGBUILDER(LEFTPAD)\n DIM NUMLINES = 0\n\n ' GET THE CURRENT LINE SO FAR FORM THE STRINGBUILDER AND BEGIN A NEW LINE.\n ' RETURNS THE CURRENT LINE AND TRAILING BLANK LINES USED FOR VERTICAL PADDING (IF ANY).\n ' RETURNS EMPTY ENUMERABLE IF THE HEIGHT REQUIREMENT HAS BEEN REACHED.\n DIM ENDLINE =\n FUNCTION() AS IENUMERABLE(OF STRING)\n DIM FINISHEDLINE AS STRING = SB.TOSTRING().PADRIGHT(WIDTH)\n SB.CLEAR()\n SB.APPEND(LEFTPAD)\n\n ' USE AN INNER ITERATOR TO PREVENT LAZY EXECUTION OF SIDE EFFECTS OF OUTER FUNCTION.\n RETURN IF(NUMLINES >= HEIGHT,\n ENUMERABLE.EMPTY(OF STRING)(),\n ITERATOR FUNCTION() AS IENUMERABLE(OF STRING)\n YIELD FINISHEDLINE\n NUMLINES += 1\n\n FOR I = 1 TO VERTBLANKCOUNT\n IF NUMLINES >= HEIGHT THEN RETURN\n YIELD FULLPAD\n NUMLINES += 1\n NEXT\n END FUNCTION())\n END FUNCTION\n\n ' YIELD THE MONTH NAME.\n SB.APPEND(PADCENTER(DT.TOSTRING(\"MMMM\", CULTUREINFO.INVARIANTCULTURE), BLOCKWIDTH).TOUPPER())\n FOR EACH L IN ENDLINE()\n YIELD L\n NEXT\n\n ' YIELD THE HEADER OF WEEKDAY NAMES.\n DIM WEEKNMABBREVS = [ENUM].GETNAMES(GETTYPE(DAYOFWEEK)).SELECT(FUNCTION(X) X.SUBSTRING(0, 2).TOUPPER())\n SB.APPEND(STRING.JOIN(DAYSEP, WEEKNMABBREVS))\n FOR EACH L IN ENDLINE()\n YIELD L\n NEXT\n\n ' DAY OF WEEK OF FIRST DAY OF MONTH.\n DIM STARTWKDY = CINT(DT.DAYOFWEEK)\n\n ' INITIALIZE WITH EMPTY SPACE FOR THE FIRST LINE.\n DIM FIRSTPAD AS NEW STRING(\" \"C, (DAY_WDT + DAYSEP.LENGTH) * STARTWKDY)\n SB.APPEND(FIRSTPAD)\n\n DIM D = DT\n DO WHILE D.MONTH = DT.MONTH\n SB.APPENDFORMAT(CULTUREINFO.INVARIANTCULTURE, $\"{{0,{DAY_WDT}}}\", D.DAY)\n\n ' EACH ROW ENDS ON SATURDAY.\n IF D.DAYOFWEEK = DAYOFWEEK.SATURDAY THEN\n FOR EACH L IN ENDLINE()\n YIELD L\n NEXT\n ELSE\n SB.APPEND(DAYSEP)\n END IF\n\n D = D.ADDDAYS(1)\n LOOP\n\n ' KEEP ADDING EMPTY LINES UNTIL THE HEIGHT QUOTA IS MET.\n DIM NEXTLINES AS IENUMERABLE(OF STRING)\n DO\n NEXTLINES = ENDLINE()\n FOR EACH L IN NEXTLINES\n YIELD L\n NEXT\n LOOP WHILE NEXTLINES.ANY()\n END FUNCTION\n\n ''' <SUMMARY>\n ''' RETURNS A NEW STRING THAT CENTER-ALIGNS THE CHARACTERS IN THIS STRING BY PADDING TO THE LEFT AND RIGHT WITH\n ''' THE SPECIFIED CHARACTER TO A SPECIFIED TOTAL LENGTH.\n ''' </SUMMARY>\n ''' <PARAM NAME=\"S\">THE STRING TO CENTER-ALIGN.</PARAM>\n ''' <PARAM NAME=\"TOTALWIDTH\">THE NUMBER OF CHARACTERS IN THE RESULTING STRING.</PARAM>\n ''' <PARAM NAME=\"PADDINGCHAR\">THE PADDING CHARACTER.</PARAM>\n <EXTENSION()>\n PRIVATE FUNCTION PADCENTER(S AS STRING, TOTALWIDTH AS INTEGER, OPTIONAL PADDINGCHAR AS CHAR = \" \"C) AS STRING\n RETURN S.PADLEFT(((TOTALWIDTH - S.LENGTH) \\ 2) + S.LENGTH, PADDINGCHAR).PADRIGHT(TOTALWIDTH, PADDINGCHAR)\n END FUNCTION\nEND MODULE\n", "language": "Visual-Basic-.NET" }, { "code": "IMPORT \"./DATE\" FOR DATE\nIMPORT \"./FMT\" FOR FMT\nIMPORT \"./SEQ\" FOR LST\n\nVAR CALENDAR = FN.NEW { |YEAR|\n VAR SNOOPY = \"🐶\"\n VAR DAYS = \"SU MO TU WE TH FR SA\"\n VAR MONTHS = [\n \"JANUARY\", \"FEBRUARY\", \"MARCH\", \"APRIL\", \"MAY\", \"JUNE\",\n \"JULY\", \"AUGUST\", \"SEPTEMBER\", \"OCTOBER\", \"NOVEMBER\", \"DECEMBER\"\n ]\n FMT.PRINT(\"$70M\", SNOOPY)\n VAR YEARSTR = \"--- %(YEAR) ---\"\n FMT.PRINT(\"$70M\\N\", YEARSTR)\n VAR FIRST = LIST.FILLED(3, 0)\n VAR MLEN = LIST.FILLED(3, 0)\n VAR C = 0\n FOR (CHUNK IN LST.CHUNKS(MONTHS, 3)) {\n FOR (I IN 0..2) FMT.WRITE(\"$20M \", CHUNK[I])\n SYSTEM.PRINT()\n FOR (I IN 0..2) SYSTEM.WRITE(\"%(DAYS) \")\n SYSTEM.PRINT()\n FIRST[0] = DATE.NEW(YEAR, C*3 + 1, 1).DAYOFWEEK % 7\n FIRST[1] = DATE.NEW(YEAR, C*3 + 2, 1).DAYOFWEEK % 7\n FIRST[2] = DATE.NEW(YEAR, C*3 + 3, 1).DAYOFWEEK % 7\n MLEN[0] = DATE.MONTHLENGTH(YEAR, C*3 + 1)\n MLEN[1] = DATE.MONTHLENGTH(YEAR, C*3 + 2)\n MLEN[2] = DATE.MONTHLENGTH(YEAR, C*3 + 3)\n FOR (I IN 0..5) {\n FOR (J IN 0..2) {\n VAR START = 1 + 7 * I - FIRST[J]\n FOR (K IN START..START+6) {\n IF (K >= 1 && K <= MLEN[J]) {\n FMT.WRITE(\"$2D \", K)\n } ELSE {\n SYSTEM.WRITE(\" \")\n }\n }\n SYSTEM.WRITE(\" \")\n }\n SYSTEM.PRINT()\n }\n SYSTEM.PRINT()\n C = C + 1\n }\n}\n\nCALENDAR.CALL(1969)\n", "language": "Wren" }, { "code": "import \"io\" for File\nimport \"./str\" for Str\nimport \"meta\" for Meta\n\nvar keywords = [\"import\", \"for\", \"var\", \"in\", \"if\", \"else\"]\nvar modules = [\"/date\", \"/fmt\", \"/seq\"]\nvar classes = [\"Date\", \"Fmt\", \"Lst\", \"Fn\", \"List\", \"System\"]\nvar methods = [\"print\", \"filled\", \"chunks\", \"write\", \"new\", \"dayOfWeek\", \"monthLength\", \"call\"]\nvar formats = [\"$70m\", \"\\\\n\", \"$20m\", \"$2d\"]\n\nvar text = File.read(\"calendar_real_uc.txt\")\nfor (keyword in keywords) text = text.replace(Str.upper(keyword) + \" \", keyword + \" \")\nfor (module in modules) text = text.replace(Str.upper(module), module)\nfor (clazz in classes) text = text.replace(Str.upper(clazz), clazz)\nfor (method in methods) text = text.replace(\".\" + Str.upper(method), \".\" + method)\nfor (format in formats) text = text.replace(Str.upper(format), format)\n\nMeta.compile(text).call()\n", "language": "Wren" }, { "code": " .MODEL TINY\n .CODE\n .486\n ORG 100H ;.COM FILES START HERE\nYEAR EQU 1969 ;DISPLAY CALENDAR FOR SPECIFIED YEAR\nSTART: MOV CX, 61 ;SPACE(61); TEXT(0, \"[SNOOPY]\"); CRLF(0)\n CALL SPACE\n MOV DX, OFFSET SNOOPY\n CALL TEXT\n MOV CL, 63 ;SPACE(63); INTOUT(0, YEAR); CRLF(0); CRLF(0)\n CALL SPACE\n MOV AX, YEAR\n CALL INTOUT\n CALL CRLF\n CALL CRLF\n\n MOV DI, 1 ;FOR MONTH:= 1 TO 12 DO DI=MONTH\nL22: XOR SI, SI ; FOR COL:= 0 TO 6-1 DO SI=COL\nL23: MOV CL, 5 ; SPACE(5)\n CALL SPACE\n MOV DX, DI ; TEXT(0, MONAME(MONTH+COL-1)); SPACE(7);\n DEC DX ; DX:= (MONTH+COL-1)*10+MONAME\n ADD DX, SI\n IMUL DX, 10\n ADD DX, OFFSET MONAME\n CALL TEXT\n MOV CL, 7\n CALL SPACE\n CMP SI, 5 ; IF COL<5 THEN SPACE(1);\n JGE L24\n MOV CL, 1\n CALL SPACE\n INC SI\n JMP L23\nL24: CALL CRLF\n\n MOV SI, 6 ; FOR COL:= 0 TO 6-1 DO\nL25: MOV DX, OFFSET SUMO ; TEXT(0, \"SU MO TU WE TH FR SA\");\n CALL TEXT\n DEC SI ; IF COL<5 THEN SPACE(2);\n JE L27\n MOV CL, 2\n CALL SPACE\n JMP L25\nL27: CALL CRLF\n\n XOR SI, SI ;FOR COL:= 0 TO 6-1 DO\nL28: MOV BX, DI ;DAY OF FIRST SUNDAY OF MONTH (CAN BE NEGATIVE)\n ADD BX, SI ;DAY(COL):= 1 - WEEKDAY(YEAR, MONTH+COL, 1);\n MOV BP, YEAR\n\n;DAY OF WEEK FOR FIRST DAY OF THE MONTH (0=SUN 1=MON..6=SAT)\n CMP BL, 2 ;IF MONTH<=2 THEN\n JG L3\n ADD BL, 12 ; MONTH:= MONTH+12;\n DEC BP ; YEAR:= YEAR-1;\nL3:\n;REM((1-1 + (MONTH+1)*26/10 + YEAR + YEAR/4 + YEAR/100*6 + YEAR/400)/7)\n INC BX ;MONTH\n IMUL AX, BX, 26\n MOV CL, 10\n CWD\n IDIV CX\n MOV BX, AX\n MOV AX, BP ;YEAR\n ADD BX, AX\n SHR AX, 2\n ADD BX, AX\n MOV CL, 25\n CWD\n IDIV CX\n IMUL DX, AX, 6 ;YEAR/100*6\n ADD BX, DX\n SHR AX, 2 ;YEAR/400\n ADD AX, BX\n MOV CL, 7\n CWD\n IDIV CX\n NEG DX\n INC DX\n MOV [SI+DAY], DL ;COL+DAY\n INC SI\n CMP SI, 5\n JLE L28\n\n MOV BP, 6 ;FOR LINE:= 0 TO 6-1 DO BP=LINE\nL29: XOR SI, SI ; FOR COL:= 0 TO 6-1 DO SI=COL\nL30: MOV BX, DI ; DAYMAX:= DAYS(MONTH+COL);\n MOV BL, [BX+SI+DAYS]\n\n;IF MONTH+COL=2 & (REM(YEAR/4)=0 & REM(YEAR/100)#0 ! REM(YEAR/400)=0) THEN\n MOV AX, DI ;MONTH\n ADD AX, SI\n CMP AL, 2\n JNE L32\n MOV AX, YEAR\n TEST AL, 03H\n JNE L32\n MOV CL,100\n CWD\n IDIV CX\n TEST DX, DX\n JNE L31\n TEST AL, 03H\n JNE L32\nL31: INC BX ;IF FEBRUARY AND LEAP YEAR THEN ADD A DAY\nL32:\n MOV DX, 7 ;FOR WEEKDAY:= 0 TO 7-1 DO\nL33: MOVZX AX, [SI+DAY] ; IF DAY(COL)>=1 & DAY(COL)<=DAYMAX THEN\n CMP AL, 1\n JL L34\n CMP AL, BL\n JG L34\n CALL INTOUT ; INTOUT(0, DAY(COL));\n CMP AL, 10 ; IF DAY(COL)<10 THEN SPACE(1); LEFT JUSTIFY\n JGE L36\n MOV CL, 1\n CALL SPACE\n JMP L36\nL34: MOV CL, 2 ; ELSE SPACE(2);\n CALL SPACE ; SUPPRESS OUT OF RANGE DAYS\nL36: MOV CL, 1 ; SPACE(1);\n CALL SPACE\n INC BYTE PTR [SI+DAY] ; DAY(COL):= DAY(COL)+1;\n DEC DX ;NEXT WEEKDAY\n JNE L33\n\n CMP SI, 5 ;IF COL<5 THEN SPACE(1);\n JGE L37\n MOV CL, 1\n CALL SPACE\n INC SI\n JMP L30\nL37: CALL CRLF\n\n DEC BP ;NEXT LINE DOWN\n JNE L29\n CALL CRLF\n\n ADD DI, 6 ;NEXT 6 MONTHS\n CMP DI, 12\n JLE L22\n RET\n\n;DISPLAY POSITIVE INTEGER IN AX\nINTOUT: PUSHA\n MOV BX, 10\n XOR CX, CX\nNO10: CWD\n IDIV BX\n PUSH DX\n INC CX\n TEST AX, AX\n JNE NO10\nNO20: MOV AH, 02H\n POP DX\n ADD DL, '0'\n INT 21H\n LOOP NO20\n POPA\n RET\n\n;DISPLAY CX SPACE CHARACTERS\nSPACE: PUSHA\nSP10: MOV AH, 02H\n MOV DL, 20H\n INT 21H\n LOOP SP10\n POPA\n RET\n\n;START A NEW LINE\nCRLF: MOV DX, OFFSET LCRLF\n\n;DISPLAY STRING AT DX\nTEXT: MOV AH, 09H\n INT 21H\n RET\n\nSNOOPY DB \"[SNOOPY]\"\nLCRLF DB 0DH, 0AH, '$'\nMONAME DB \" JANUARY $ FEBRUARY$ MARCH $ APRIL $ MAY $ JUNE $\"\n DB \" JULY $ AUGUST $SEPTEMBER$ OCTOBER$ NOVEMBER$ DECEMBER$\"\nSUMO DB \"SU MO TU WE TH FR SA$\"\nDAYS DB 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31\nDAY DB ?, ?, ?, ?, ?, ?\n END START\n", "language": "X86-Assembly" }, { "code": "(SETQ YR 1969)\n(SETQ M #(\"JANUARY\" \"FEBRUARY\" \"MARCH\" \"APRIL\" \"MAY\" \"JUNE\" \"JULY\" \"AUGUST\" \"SEPTEMBER\" \"OCTOBER\" \"NOVEMBER\" \"DECEMBER\"))\n(SETQ ML #(31 28 31 30 31 30 31 31 30 31 30 31))\n(SETQ WD #(\"SU\" \"MO\" \"TU\" \"WE\" \"TH\" \"FR\" \"SA\"))\n(IF (AND (= (REM YR 4) 0) (OR (/= (REM YR 100) 0) (= (REM YR 400) 0))) (VECTOR-SET! ML 1 29))\n(SETQ D (REM (+ 1 (+ (* 5 (REM (- YR 1) 4)) (* 4 (REM (- YR 1) 100)) (* 6 (REM (- YR 1) 400)))) 7))\n(TERPRI)\n(DO ((I 0 (+ I 1))) ((> I 60))\n(PRINC \" \"))\n(PRINC \"SNOOPY CALENDAR \")\n(PRINC YR)\n(TERPRI)\n(DO ((I 0 (+ I 1))) ((> I 11))\n(TERPRI)\n(DO ((J 0 (+ J 1))) ((> J 65))\n(PRINC \" \"))\n(PRINC (VECTOR-REF M I))\n(TERPRI)\n(PRINC \" \")\n(DO ((J 0 (+ J 1))) ((> J 6))\n(DO ((K 0 (+ K 1))) ((> K 14))\n(PRINC \" \"))\n(PRINC (VECTOR-REF WD J))\n(PRINC \" \"))\n(TERPRI)\n(DO ((J 0 (+ J 1))) ((> J 6))\n(IF (< J D) (DO ((K 0 (+ K 1))) ((> K 18)) (PRINC \" \"))))\n(DO ((J 1 (+ J 1))) ((> J (VECTOR-REF ML I)))\n(PRINC \" \")\n(IF (< J 10) (PRINC \" \"))\n(DO ((K 0 (+ K 1))) ((> K 14))\n(PRINC \" \"))\n(PRINC J)\n(SETQ D (+ D 1))\n(IF (> D 6) (TERPRI))\n(IF (> D 6) (SETQ D 0))))\n", "language": "XLISP" }, { "code": "VAR [CONST] D=TIME.DATE, DAYS=\"SU MO TU WE TH FR SA\";\n\nFCN CENTER(TEXT,M) { STRING(\" \"*((M-TEXT.LEN())/2),TEXT) }\n\nFCN ONEMONTH(YEAR,MONTH){\n DAY1:=D.ZELLER(YEAR,MONTH,1); //1969-1-1 -->3 (WED, ISO 8601)\n DAYZ:=D.DAYSINMONTH(YEAR,MONTH); //1969-1 -->31\n LIST(CENTER(D.MONTHNAMES[MONTH],DAYS.LEN()),DAYS).EXTEND(\n (1).PUMP(DAYZ,(0).PUMP(DAY1,LIST,T(VOID,\"\"))).APPLY(\"%2S \".FMT)\n .PUMP(LIST,T(VOID.READ,DAYS.LEN()/3,FALSE),STRING.CREATE));\n}\n...\n", "language": "Zkl" }, { "code": "code:=File(vm.arglist[0]).read();\ncode=Data(Void,code.text.toLower());\nmixed:=T(\"string\",\"String\", \"list\",\"List\", \" t(\",\" T(\",\",t(\",\",T(\",\n \".tostring\",\".toString\", \"void.read\",\"Void.Read\",\n \"time.date\",\"Time.Date\", \"utils.\",\"Utils.\", \"zipwith\",\"zipWith\",\n \"daysinmonth\",\"daysInMonth\", \"monthnames\",\"monthNames\",\n \"void\",\"Void\", \"false\",\"False\",\n \"d.october\",\"d.October\",\n);\nmixed.pump(Void,Void.Read,'wrap(up,down){ code.replace(up,down) });\nCompiler.Compiler.compileText(code)();\n", "language": "Zkl" } ]
Calendar---for-REAL-programmers
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Calkin-Wilf_sequence\n", "language": "00-META" }, { "code": "The '''Calkin-Wilf sequence''' contains every nonnegative rational number exactly once. \n\nIt can be calculated recursively as follows:\n\n <big> {{math|a<sub>1</sub>}} = {{math|1}} </big>\n <big> {{math|a<sub>n+1</sub>}} = {{math|1/(2&lfloor;a<sub>n</sub>&rfloor;+1-a<sub>n</sub>)}} for n > 1 </big>\n\n\n;Task part 1:\n* Show on this page terms 1 through 20 of the Calkin-Wilf sequence.\n\n<br>To avoid floating point error, you may want to use a rational number data type.\n\n\nIt is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. \nIt only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:\n\n <big> {{math|[a<sub>0</sub>; a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub>]}} = {{math|[a<sub>0</sub>; a<sub>1</sub>, a<sub>2</sub> ,..., a<sub>n</sub>-1, 1]}} </big>\n\n\n;Example:\nThe fraction &nbsp; '''9/4''' &nbsp; has odd continued fraction representation &nbsp; &nbsp; <big> {{math|2; 3, 1}},</big> &nbsp; &nbsp; giving a binary representation of &nbsp; '''100011''', \n<br>which means &nbsp; '''9/4''' &nbsp; appears as the &nbsp; '''35th''' &nbsp; term of the sequence.\n\n\n;Task part 2:\n* Find the position of the number &nbsp; <big>'''<sup>83116</sup>'''<big>'''/'''</big>'''<sub>51639</sub>'''</big> &nbsp; in the Calkin-Wilf sequence.\n\n;Related tasks:\n:* &nbsp; [[Fusc sequence]].\n\n;See also:\n* Wikipedia entry: [[wp:Calkin%E2%80%93Wilf_tree|Calkin-Wilf tree]]\n* [[Continued fraction]]\n* [[Continued fraction/Arithmetic/Construct from rational number]]\n<br><br>\n", "language": "00-TASK" }, { "code": "T CalkinWilf\n n = 1\n d = 1\n\n F ()()\n V r = (.n, .d)\n .n = 2 * (.n I/ .d) * .d + .d - .n\n swap(&.n, &.d)\n R r\n\nprint(‘The first 20 terms of the Calkwin-Wilf sequence are:’)\nV cw = CalkinWilf()\n[String] seq\nL 20\n V (n, d) = cw()\n seq.append(I d == 1 {String(n)} E n‘/’d)\nprint(seq.join(‘, ’))\n\ncw = CalkinWilf()\nV index = 1\nL cw() != (83116, 51639)\n index++\nprint(\"\\nThe element 83116/51639 is at position \"index‘ in the sequence.’)\n", "language": "11l" }, { "code": "BEGIN\n # Show elements 1-20 of the Calkin-Wilf sequence as rational numbers #\n # also show the position of a specific element in the seuence #\n # Uses code from the Arithmetic/Rational #\n # & Continued fraction/Arithmetic/Construct from rational number tasks #\n\n\n # Code from the Arithmetic/Rational task #\n # ============================================================== #\n\n MODE FRAC = STRUCT( INT num #erator#, den #ominator#);\n\n PROC gcd = (INT a, b) INT: # greatest common divisor #\n (a = 0 | b |: b = 0 | a |: ABS a > ABS b | gcd(b, a MOD b) | gcd(a, b MOD a));\n\n PROC lcm = (INT a, b)INT: # least common multiple #\n a OVER gcd(a, b) * b;\n\n PRIO // = 9; # higher then the ** operator #\n OP // = (INT num, den)FRAC: ( # initialise and normalise #\n INT common = gcd(num, den);\n IF den < 0 THEN\n ( -num OVER common, -den OVER common)\n ELSE\n ( num OVER common, den OVER common)\n FI\n );\n\n OP + = (FRAC a, b)FRAC: (\n INT common = lcm(den OF a, den OF b);\n FRAC result := ( common OVER den OF a * num OF a + common OVER den OF b * num OF b, common );\n num OF result//den OF result\n );\n\n OP - = (FRAC a, b)FRAC: a + -b,\n * = (FRAC a, b)FRAC: (\n INT num = num OF a * num OF b,\n den = den OF a * den OF b;\n INT common = gcd(num, den);\n (num OVER common) // (den OVER common)\n );\n\n OP - = (FRAC frac)FRAC: (-num OF frac, den OF frac);\n\n # ============================================================== #\n # end code from the Arithmetic/Rational task #\n\n # code from the Continued fraction/Arithmetic/Construct from rational number task #\n # ================================================================================#\n\n # returns the quotient of numerator over denominator and sets #\n # numerator and denominator to the next values for #\n # the continued fraction #\n PROC r2cf = ( REF INT numerator, REF INT denominator )INT:\n IF denominator = 0\n THEN 0\n ELSE INT quotient := numerator OVER denominator;\n INT prev numerator = numerator;\n numerator := denominator;\n denominator := prev numerator MOD denominator;\n\t quotient\n FI # r2cf # ;\n\n # ====================================================================================#\n # end code from the Continued fraction/Arithmetic/Construct from rational number task #\n\n # Additional FRACrelated operators #\n OP * = ( INT a, FRAC b )FRAC: ( num OF b * a ) // den OF b;\n OP / = ( FRAC a, b )FRAC: ( num OF a * den OF b ) // ( num OF b * den OF a );\n OP FLOOR = ( FRAC a )INT: num OF a OVER den OF a;\n OP + = ( INT a, FRAC b )FRAC: ( a // 1 ) + b;\n\n FRAC one = 1 // 1;\n\n # returns the first n elements of the Calkin-Wilf sequence #\n PROC calkin wilf = ( INT n )[]FRAC:\n BEGIN\n [ 1 : n ]FRAC q;\n IF n > 0 THEN\n q[ 1 ] := 1 // 1;\n FOR i FROM 2 TO UPB q DO\n q[ i ] := one / ( ( 2 * FLOOR q[ i - 1 ] ) + one - q[ i - 1 ] )\n OD\n FI;\n q\n END # calkin wilf # ;\n\n # returns the position of a FRAC in the Calkin-Wilf sequence by computing its #\n # continued fraction representation and converting that to a bit string #\n # - the position must fit in a 2-bit number #\n PROC position in calkin wilf sequence = ( FRAC f )INT:\n IF INT result := 0;\n [ 1 : 32 ]INT cf; FOR i FROM LWB cf TO UPB cf DO cf[ i ] := 0 OD;\n INT num := num OF f;\n INT den := den OF f;\n INT cf length := 0;\n FOR i FROM LWB cf WHILE den /= 0 DO\n cf[ cf length := i ] := r2cf( num, den )\n OD;\n NOT ODD cf length\n THEN # the continued fraction does not have an odd length #\n -1\n ELSE # the continued fraction has an odd length so we can compute the seuence length #\n # build the number by alternating d 1s and 0s where d is the digits of the #\n # continued fraction, starting at the least significant #\n INT digit := 1;\n FOR d pos FROM cf length BY -1 TO 1 DO\n FOR i TO cf[ d pos ] DO\n result *:= 2 +:= digit\n OD;\n digit := IF digit = 0 THEN 1 ELSE 0 FI\n OD;\n result\n FI # position in calkin wilf sequence # ;\n\n BEGIN # task #\n # get and show the first 20 Calkin-Wilf sequence numbers #\n []FRAC cw = calkin wilf( 20 );\n print( ( \"The first 20 elements of the Calkin-Wilf sequence are:\", newline, \" \" ) );\n FOR n FROM LWB cw TO UPB cw DO\n FRAC sn = cw[ n ];\n print( ( \" \", whole( num OF sn, 0 ), \"/\", whole( den OF sn, 0 ) ) )\n OD;\n print( ( newline ) );\n # show the position of a specific element in the sequence #\n print( ( \"Position of 83116/51639 in the sequence: \"\n , whole( position in calkin wilf sequence( 83116//51639 ), 0 )\n )\n )\n END\nEND\n", "language": "ALGOL-68" }, { "code": "-- Return the first n terms of the sequence. Tree generation. Faster for this purpose.\non CalkinWilfSequence(n)\n script o\n property sequence : {{1, 1}} -- Initialised with the first term ({numerator, denominator}).\n end script\n\n -- Work through the growing sequence list, adding the two children of each term to the end and\n -- converting each term to text representing the vulgar fraction. Stop adding children halfway through.\n set halfway to n div 2\n repeat with position from 1 to n\n set {numerator, denominator} to item position of o's sequence\n if (position ≤ halfway) then\n tell numerator + denominator\n set end of o's sequence to {numerator, it}\n if ((position < halfway) or (position * 2 < n)) then set end of o's sequence to {it, denominator}\n end tell\n end if\n set item position of o's sequence to (numerator as text) & \"/\" & denominator\n end repeat\n\n return o's sequence\nend CalkinWilfSequence\n\n-- Alternatively, return terms pos1 to pos2. Binary run-length encoding. Doesn't need to work from the beginning of the sequence.\non CalkinWilfSequence2(pos1, pos2)\n script o\n property sequence : {}\n end script\n\n repeat with position from pos1 to pos2\n -- Build a continued fraction list from the binary run-length encoding of this position index.\n -- There's no need to put the last value into the list as it's used immediately.\n set continuedFraction to {}\n set bitValue to 1\n set runLength to 0\n repeat until (position = 0)\n if (position mod 2 = bitValue) then\n set runLength to runLength + 1\n else\n set end of continuedFraction to runLength\n set bitValue to (bitValue + 1) mod 2\n set runLength to 1\n end if\n set position to position div 2\n end repeat\n -- Work out the numerator and denominator from the continued fraction and derive text representing the vulgar fraction.\n set numerator to runLength\n set denominator to 1\n repeat with i from (count continuedFraction) to 1 by -1\n tell numerator\n set numerator to numerator * (item i of continuedFraction) + denominator\n set denominator to it\n end tell\n end repeat\n set end of o's sequence to (numerator as text) & \"/\" & denominator\n end repeat\n\n return o's sequence\nend CalkinWilfSequence2\n\n-- Return the sequence position of the term with the given numerator and denominator.\non CalkinWilfSequencePosition(numerator, denominator)\n -- Build a continued fraction list from the input.\n set continuedFraction to {}\n repeat until (denominator is 0)\n set end of continuedFraction to numerator div denominator\n set {numerator, denominator} to {denominator, numerator mod denominator}\n end repeat\n -- If it has an even number of entries, convert to the equivalent odd number.\n if ((count continuedFraction) mod 2 is 0) then\n set last item of continuedFraction to (last item of continuedFraction) - 1\n set end of continuedFraction to 1\n end if\n -- \"Binary run-length decode\" the entries to get the position index.\n set position to 0\n set bitValue to 1\n repeat with i from (count continuedFraction) to 1 by -1\n repeat (item i of continuedFraction) times\n set position to position * 2 + bitValue\n end repeat\n set bitValue to (bitValue + 1) mod 2\n end repeat\n\n return position\nend CalkinWilfSequencePosition\n\n-- Task code:\nlocal sequenceResult1, sequenceResult2, positionResult, output, astid\nset sequenceResult1 to CalkinWilfSequence(20)\nset sequenceResult2 to CalkinWilfSequence2(1, 20)\nset positionResult to CalkinWilfSequencePosition(83116, 51639)\nset astid to AppleScript's text item delimiters\nset AppleScript's text item delimiters to \", \"\nset output to \"First twenty terms of sequence using tree generation:\" & (linefeed & sequenceResult1)\nset output to output & (linefeed & \"Ditto using binary run-length encoding:\") & (linefeed & sequenceResult1)\nset AppleScript's text item delimiters to astid\nset output to output & (linefeed & \"83116/51639 is term number \" & positionResult)\nreturn output\n", "language": "AppleScript" }, { "code": "\"First twenty terms of sequence using tree generation:\n1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, 1/4, 4/3, 3/5, 5/2, 2/5, 5/3, 3/4, 4/1, 1/5, 5/4, 4/7, 7/3, 3/8\nDitto using binary run-length encoding:\n1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, 1/4, 4/3, 3/5, 5/2, 2/5, 5/3, 3/4, 4/1, 1/5, 5/4, 4/7, 7/3, 3/8\n83116/51639 is term number 123456789\"\n", "language": "AppleScript" }, { "code": "n: new 1\nd: new 1\ncalkinWilf: function [] .export:[n,d] [\n n: (d - n) + 2 * (n/d) * d\n tmp: d\n d: n\n n: tmp\n return @[n d]\n]\n\nfirst20: [[1 1]] ++ map 1..19 => calkinWilf\nprint \"The first 20 terms of the Calkwin-Wilf sequence are:\"\nprint map first20 'f -> ~\"|f\\0|/|f\\1|\"\n\nn: new 1\nd: new 1\nindx: new 1\n\ntarget: [83116, 51639]\n\nwhile ø [\n inc 'indx\n if target = calkinWilf -> break\n]\n\nprint \"\"\nprint [\"The element\" ~\"|target\\0|/|target\\1|\" \"is at position\" indx \"in the sequence.\"]\n", "language": "Arturo" }, { "code": "GCD ← {m 𝕊⍟(0<m←𝕨|𝕩) 𝕨}\n_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}\nSim ← { # Simplify a fraction\n x𝕊1: 𝕨‿1;\n 0𝕊y: 0‿𝕩;\n ⌊𝕨‿𝕩 ÷ 𝕨 GCD 𝕩\n}\nAdd ← { # Add two fractions\n 0‿b 𝕊 𝕩: 𝕩;\n 𝕨 𝕊 0‿y: 𝕨;\n a‿b 𝕊 x‿y:\n ((a×y)+x×b) Sim b×y\n}\nNext ← {n‿d: ⌽(2×⌊÷´n‿d)‿1 Add (d-n)‿d} # Next term\nCal ← {Next⍟𝕩 1‿1}\n\n•Show Cal 1+↕20\n\n•Show {\n cnt‿fr:\n ⟨cnt+1,Next fr⟩\n} _while_ {\n cnt‿fr:\n fr ≢ 83116‿51639\n} ⟨1,1‿1⟩\n", "language": "BQN" }, { "code": "⟨ ⟨ 1 2 ⟩ ⟨ 2 1 ⟩ ⟨ 1 3 ⟩ ⟨ 3 2 ⟩ ⟨ 2 3 ⟩ ⟨ 3 1 ⟩ ⟨ 1 4 ⟩ ⟨ 4 3 ⟩ ⟨ 3 5 ⟩ ⟨ 5 2 ⟩ ⟨ 2 5 ⟩ ⟨ 5 3 ⟩ ⟨ 3 4 ⟩ ⟨ 4 1 ⟩ ⟨ 1 5 ⟩ ⟨ 5 4 ⟩ ⟨ 4 7 ⟩ ⟨ 7 3 ⟩ ⟨ 3 8 ⟩ ⟨ 8 5 ⟩ ⟩\n⟨ 123456789 ⟨ 83116 51639 ⟩ ⟩\n", "language": "BQN" }, { "code": "( 1:?a\n& 0:?i\n& whl\n ' ( 1+!i:<20:?i\n & (2*div$(!a,1)+1+-1*!a)^-1:?a\n & out$!a\n )\n& ( r2cf\n = floor\n . div$(!arg,1):?floor\n & ( !floor:!arg\n | !floor r2cf$((!arg+-1*!floor)^-1)\n )\n )\n& ( get-term-num\n = ans dig pwr\n . (0,1,1):(?ans,?dig,?pwr)\n & r2cf$!arg:?n\n & map\n $ ( (\n =\n . whl\n ' ( !arg+-1:~<0:?arg\n & !dig*!pwr+!ans:?ans\n & 2*!pwr:?pwr\n )\n & 1+-1*!dig:?dig\n )\n . !n\n )\n & !ans\n )\n& out$(get-term-num$83116/51639)\n);\n", "language": "Bracmat" }, { "code": "#include <iostream>\n#include <vector>\n#include <boost/rational.hpp>\n\nusing rational = boost::rational<unsigned long>;\n\nunsigned long floor(const rational& r) {\n return r.numerator()/r.denominator();\n}\n\nrational calkin_wilf_next(const rational& term) {\n return 1UL/(2UL * floor(term) + 1UL - term);\n}\n\nstd::vector<unsigned long> continued_fraction(const rational& r) {\n unsigned long a = r.numerator();\n unsigned long b = r.denominator();\n std::vector<unsigned long> result;\n do {\n result.push_back(a/b);\n unsigned long c = a;\n a = b;\n b = c % b;\n } while (a != 1);\n if (result.size() > 0 && result.size() % 2 == 0) {\n --result.back();\n result.push_back(1);\n }\n return result;\n}\n\nunsigned long term_number(const rational& r) {\n unsigned long result = 0;\n unsigned long d = 1;\n unsigned long p = 0;\n for (unsigned long n : continued_fraction(r)) {\n for (unsigned long i = 0; i < n; ++i, ++p)\n result |= (d << p);\n d = !d;\n }\n return result;\n}\n\nint main() {\n rational term = 1;\n std::cout << \"First 20 terms of the Calkin-Wilf sequence are:\\n\";\n for (int i = 1; i <= 20; ++i) {\n std::cout << std::setw(2) << i << \": \" << term << '\\n';\n term = calkin_wilf_next(term);\n }\n rational r(83116, 51639);\n std::cout << r << \" is the \" << term_number(r) << \"th term of the sequence.\\n\";\n}\n", "language": "C++" }, { "code": "subr first\n n = 1 ; d = 1\n.\nproc next . .\n n = 2 * (n div d) * d + d - n\n swap n d\n.\nprint \"The first 20 terms of the Calkwin-Wilf sequence are:\"\nfirst\nfor i to 20\n write n & \"/\" & d & \" \"\n next\n.\nprint \"\"\n#\nfirst\ni = 1\nwhile n <> 83116 or d <> 51639\n next\n i += 1\n.\nprint \"83116/51639 is at position \" & i\n", "language": "EasyLang" }, { "code": "[For Rosetta Code. EDSAC program, Initial Orders 2.\n Prints the first 20 terms of the Calkin-Wilf sequence.\n Uses term{n} to calculate term{n + 1}.]\n\n[Print subroutine for non-negative 17-bit integers.\n Parameters: 0F = integer to be printed (not preserved)\n 1F = character for leading zero (preserved)\n Workspace: 4F, 5F. Even address; 40 locations]\n T 56 K [define load address]\nGKA3FT34@A1FT35@S37@T36@AFT5FT4FH38#@V4DH30@\nR32FR16FYFE23@O35@A2FT36@T5FV4DYFL8FT4DA5FL1024F\nUFA36@G16@OFTFT35@A36@G17@ZFPFPFP4FT1714FZ219D\n\n[Main routine]\n T 100 K [define load address]\n G K [set up relative addressing via @ (theta)]\n [Constants]\n [0] P 10 F [maximum index = 20, edit ad lib.]\n [1] P D [constant 1]\n [Teleprinter characters]\n [2] # F [set figures mode]\n [3] C F [colon (in figures mode)]\n [4] X F [slash (in figures mode)]\n [5] ! F [space]\n [6] @ F [carriage return]\n [7] & F [line feed]\n [8] K 4096 F [null]\n [Variables]\n [9] P F [index]\n [10] P F [a (where term = a/b)]\n [11] P F [b]\n [Enter with acc = 0]\n [12] O 2 @ [set teleprinter to figures]\n A 1 @ [acc := 1]\n U 9 @ [index := 1]\n U 10 @ [a := 1]\n T 11 @ [b := 1 (and clear acc)]\n E 34 @ [jump to print first term]\n [Loop back here if not yet printed enough terms]\n [18] A @ [restore index after test]\n A 1 @ [add 1]\n T 9 @ [update index]\n [Calculate next term. New b := a + b - 2(a mod b).\n Code below calculates c := (a mod b) - b, then new b := a - b - 2*c]\n A 10 @ [acc := a]\n [22] S 11 @ [subtract b]\n E 22 @ [if acc >= 0, subtract again]\n T F [result c < 0, store in 0F]\n A 10 @ [acc := a]\n S 11 @ [subtract b]\n S F [subtract c]\n S F [subtract c]\n T F [new b = a - b - 2*c; store in 0F]\n A 11 @ [acc := old b]\n T 10 @ [copy to a]\n A F [acc := new b]\n T 11 @ [copy to b]\n [Print index and a/b. Assume acc = 0 here.]\n [34] A 5 @ [space to replace leading 0's]\n T 1 F [pass to print subroutine]\n A 9 @ [acc := index]\n T F [pass to print subroutine]\n [38] A 38 @ [for return from subroutine]\n G 56 F [call subroutine, clears acc]\n O 3 @ [print colon]\n O 5 @ [print space]\n A 8 @ [null to replace leading 0's]\n T 1 F [pass to print subroutine]\n A10@ TF A46@ G56F O4@ [print a followed by slash]\n A11@ TF A51@ G56F O6@ O7@ [print b followed by CR LF]\n [Test whether enough terms have been printed]\n A 9 @ [acc := index]\n S @ [subtract maximum index]\n G 18 @ [loop back if acc < 0]\n [Exit]\n O 8 @ [print null to flush teleprinter buffer]\n Z F [stop]\n E 12 Z [relative address of entry point]\n P F [enter with acc = 0]\n[end]\n", "language": "EDSAC-order-code" }, { "code": "[For Rosetta Code. EDSAC program, Initial Orders 2.]\n[Finds the index of a given rational in the Calkin-Wilf series.]\n\n[Library subroutine R2: input of positive integers.\n Runs during input of the program, and is then overwritten.\n Allows integers to be written in decimal, rather than as \"pseudo-orders\".\n See Wilkes, Williams & Gill, 1951 edn, pp. 96-97, 148.]\n T 54 K [to access integers via C parameter]\n P 110 F [where to load integers]\nGKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13Z\n T #C [tell R2 where to load integers]\n[F after each integer except the last, and # after the last.]\n 83116F51639#\n\n[Modified library subroutine P7.\n Prints signed integer up to 10 digits, left-justified.\n Input: Number to be printed is at 0D.\n 54 locations. Load at even address. Workspace 4D.]\n\n T 56 K\n GKA3FT42@A49@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@\nTFH17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@\nT31@A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFSFL8FT4DE39@\n\n[Main routine.]\n T 120 K [define load address (must be even)]\n G K [set up relative addressing via @ (theta)]\n\n [Put 35-bit values first, to ensure each is at an even address]\n [Variables]\n [0] P F P F [a]\n [2] P F P F [b]\n [4] P F P F [power of 2]\n [6] P F P F [calculated index]\n [Constants]\n T8#Z PF T8Z [clears sandwich digit between 8 and 9]\n [8] P D P F [35-bit constant 1]\n [Teleprinter characters]\n [10] # F [set figures mode]\n [11] X F [slash (in figures mode)]\n [12] K 2048 F [set letters mode]\n [13] I F [letter I]\n [14] R F [letter R]\n [15] ! F [space]\n [16] @ F [carriage return]\n [17] & F [line feed]\n [18] K 4096 F [null char]\n\n [Enter with acc = 0]\n [19] A #C [acc := initial a]\n T #@ [copy to variable]\n A 2#C [acc := initial b]\n T 2#@ [copy to variable]\n [23] A 8#@ [acc := 1]\n [24] T 4#@ [initialize power of 2]\n T 6#@ [initialize index to 0]\n [Loop]\n [26] A #@ [acc := a]\n [27] S 2#@ [subtract b]\n [28] E 33 @ [jump if a >= b]\n [Here if a < b]\n T D [store a - b in 0D]\n S D [negate]\n T 2#@ [b := b - a]\n E 40 @ [join common code]\n [Here if a >= b]\n [33] S 8#@ [acc = a - b; test for a = b]\n G 45 @ [jump out of loop if so]\n A 8#@ [restore a - b]\n T #@ [a := a - b]\n A 6#@ [acc := index]\n A 4#@ [inc index by power of 2]\n T 6#@\n [Code common to both cases]\n [40] A 4#@ [acc := power of 2]\n L D [shift left]\n G 76 @\n T 4#@ [update power of 2]\n E 26 @ [loop back]\n [Exit from loop.]\n [45] T D [dump acc to clear it]\n A 6#@ [acc := index]\n A 4#@ [add power of 2 ]\n T 6#@ [store final value of index]\n [Finished calcualting index, now do printing]\n O 10 @ [set teleprinter to figures]\n A #C [acc := initial a]\n T D [to 0D for printing]\n [52] A 52 @ [for return from subroutine]\n G 56 F [call print subroutine, clears acc]\n O 11 @ [print slash]\n A 2#C [print initial b similarly]\n T D\n [57] A 57 @\n G 56 F\n O 12 @ [set teleprinter to letters and print ' IS AT ']\n O15@ O13@ O27@ O15@ O23@ O24@ O15@\n O 10 @ [set teleprinter to figures]\n A 6#@ [acc := calculated index]\n T D [send to print subroutine]\n [70] A 70 @\n G 56 F\n [72] O16@ O17@ [print CR, LF]\n O 18 @ [print null to flush teleprinter buffer]\n Z F [stop]\n [Here if power of 2 goes negative (accumulator overflow)]\n [76] O 12 @ [set teleprinter to letters]\n O28@ O14@ O14@ O76@ O14@ [print'ERROR']\n G 72 @ [jump to common exit]\n E 19 Z [relative address of entry point]\n P F [enter with acc = 0]\n", "language": "EDSAC-order-code" }, { "code": "// Calkin Wilf Sequence. Nigel Galloway: January 9th., 2021\nlet cW=Seq.unfold(fun(n)->Some(n,seq{for n,g in n do yield (n,n+g); yield (n+g,g)}))(seq[(1,1)])|>Seq.concat\n", "language": "F-Sharp" }, { "code": "cW |> Seq.take 20 |> Seq.iter(fun(n,g)->printf \"%d/%d \" n g);printfn \"\"\n", "language": "F-Sharp" }, { "code": "printfn \"%d\" (1+Seq.findIndex(fun n->n=(83116,51639)) cW)\n", "language": "F-Sharp" }, { "code": "USING: formatting io kernel lists lists.lazy math\nmath.continued-fractions math.functions math.parser prettyprint\nsequences strings vectors ;\n\n: next-cw ( x -- y ) [ floor dup + ] [ 1 swap - + recip ] bi ;\n\n: calkin-wilf ( -- list ) 1 [ next-cw ] lfrom-by ;\n\n: >continued-fraction ( x -- seq )\n 1vector [ dup last integer? ] [ dup next-approx ] until\n dup length even? [ unclip-last 1 - suffix! 1 suffix! ] when ;\n\n: cw-index ( x -- n )\n >continued-fraction <reversed>\n [ even? CHAR: 1 CHAR: 0 ? <string> ] map-index concat bin> ;\n\n! Task\n\"First 20 terms of the Calkin-Wilf sequence:\" print\n20 calkin-wilf ltake [ pprint bl ] leach nl nl\n\n83116/51639 cw-index \"83116/51639 is at index %d.\\n\" printf\n", "language": "Factor" }, { "code": "\\ Calkin-Wilf sequence\n\n: frac. swap . .\" / \" . ;\n: cw-next ( num den -- num den ) 2dup / over * 2* over + rot - ;\n: cw-seq ( n -- )\n 1 1 rot\n 0 do\n cr 2dup frac. cw-next\n loop 2drop ;\n\nvariable index\nvariable bit-state\nvariable bit-position\n: r2cf-next ( num1 den1 -- num2 den2 u ) swap over >r s>d r> sm/rem ;\n\n: n2bitlength ( n -- )\n bit-state @ if\n 1 swap lshift 1- bit-position @ lshift index +!\n else drop then ;\n\n: index-init true bit-state ! 0 bit-position ! 0 index ! ;\n: index-build ( n -- )\n dup n2bitlength bit-position +! bit-state @ invert bit-state ! ;\n: index-finish ( n 0 -- ) 2drop -1 bit-position +! 1 index-build ;\n\n: cw-index ( num den -- )\n index-init\n begin r2cf-next index-build dup 0<> while repeat\n index-finish ;\n\n: cw-demo\n 20 cw-seq\n cr 83116 51639 2dup frac. cw-index index @ . ;\ncw-demo\n", "language": "Forth" }, { "code": "#include \"gcd.bas\"\n\ntype rational\n num as integer\n den as integer\nend type\n\ndim shared as rational ONE, TWO\nONE.num = 1 : ONE.den = 1\nTWO.num = 2 : TWO.den = 1\n\nfunction simplify( byval a as rational ) as rational\n dim as uinteger g = gcd( a.num, a.den )\n a.num /= g : a.den /= g\n if a.den < 0 then\n a.den = -a.den\n a.num = -a.num\n end if\n return a\nend function\n\noperator + ( a as rational, b as rational ) as rational\n dim as rational ret\n ret.num = a.num * b.den + b.num*a.den\n ret.den = a.den * b.den\n return simplify(ret)\nend operator\n\noperator - ( a as rational, b as rational ) as rational\n dim as rational ret\n ret.num = a.num * b.den - b.num*a.den\n ret.den = a.den * b.den\n return simplify(ret)\nend operator\n\noperator * ( a as rational, b as rational ) as rational\n dim as rational ret\n ret.num = a.num * b.num\n ret.den = a.den * b.den\n return simplify(ret)\nend operator\n\noperator / ( a as rational, b as rational ) as rational\n dim as rational ret\n ret.num = a.num * b.den\n ret.den = a.den * b.num\n return simplify(ret)\nend operator\n\nfunction floor( a as rational ) as rational\n dim as rational ret\n ret.den = 1\n ret.num = a.num \\ a.den\n return ret\nend function\n\nfunction cw_nextterm( q as rational ) as rational\n dim as rational ret = (TWO*floor(q))\n ret = ret + ONE : ret = ret - q\n return ONE / ret\nend function\n\nfunction frac_to_int( byval a as rational ) as uinteger\n redim as uinteger cfrac(-1)\n dim as integer lt = -1, ones = 1, ret = 0\n do\n lt += 1\n redim preserve as uinteger cfrac(0 to lt)\n cfrac(lt) = floor(a).num\n a = a - floor(a) : a = ONE / a\n loop until a.num = 0 or a.den = 0\n if lt mod 2 = 1 and cfrac(lt) = 1 then\n lt -= 1\n cfrac(lt)+=1\n redim preserve as uinteger cfrac(0 to lt)\n end if\n if lt mod 2 = 1 and cfrac(lt) > 1 then\n cfrac(lt) -= 1\n lt += 1\n redim preserve as uinteger cfrac(0 to lt)\n cfrac(lt) = 1\n end if\n for i as integer = lt to 0 step -1\n for j as integer = 1 to cfrac(i)\n ret *= 2\n if ones = 1 then ret += 1\n next j\n ones = 1 - ones\n next i\n return ret\nend function\n\nfunction disp_rational( a as rational ) as string\n if a.den = 1 or a.num= 0 then return str(a.num)\n return str(a.num)+\"/\"+str(a.den)\nend function\n\ndim as rational q\nq.num = 1\nq.den = 1\nfor i as integer = 1 to 20\n print i, disp_rational(q)\n q = cw_nextterm(q)\nnext i\n\nq.num = 83116\nq.den = 51639\nprint disp_rational(q)+\" is the \"+str(frac_to_int(q))+\"th term.\"\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/big\"\n \"strconv\"\n \"strings\"\n)\n\nfunc calkinWilf(n int) []*big.Rat {\n cw := make([]*big.Rat, n+1)\n cw[0] = big.NewRat(1, 1)\n one := big.NewRat(1, 1)\n two := big.NewRat(2, 1)\n for i := 1; i < n; i++ {\n t := new(big.Rat).Set(cw[i-1])\n f, _ := t.Float64()\n f = math.Floor(f)\n t.SetFloat64(f)\n t.Mul(t, two)\n t.Sub(t, cw[i-1])\n t.Add(t, one)\n t.Inv(t)\n cw[i] = new(big.Rat).Set(t)\n }\n return cw\n}\n\nfunc toContinued(r *big.Rat) []int {\n a := r.Num().Int64()\n b := r.Denom().Int64()\n var res []int\n for {\n res = append(res, int(a/b))\n t := a % b\n a, b = b, t\n if a == 1 {\n break\n }\n }\n le := len(res)\n if le%2 == 0 { // ensure always odd\n res[le-1]--\n res = append(res, 1)\n }\n return res\n}\n\nfunc getTermNumber(cf []int) int {\n b := \"\"\n d := \"1\"\n for _, n := range cf {\n b = strings.Repeat(d, n) + b\n if d == \"1\" {\n d = \"0\"\n } else {\n d = \"1\"\n }\n }\n i, _ := strconv.ParseInt(b, 2, 64)\n return int(i)\n}\n\nfunc commatize(n int) string {\n s := fmt.Sprintf(\"%d\", n)\n if n < 0 {\n s = s[1:]\n }\n le := len(s)\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0:i] + \",\" + s[i:]\n }\n if n >= 0 {\n return s\n }\n return \"-\" + s\n}\n\nfunc main() {\n cw := calkinWilf(20)\n fmt.Println(\"The first 20 terms of the Calkin-Wilf sequnence are:\")\n for i := 1; i <= 20; i++ {\n fmt.Printf(\"%2d: %s\\n\", i, cw[i-1].RatString())\n }\n fmt.Println()\n r := big.NewRat(83116, 51639)\n cf := toContinued(r)\n tn := getTermNumber(cf)\n fmt.Printf(\"%s is the %sth term of the sequence.\\n\", r.RatString(), commatize(tn))\n}\n", "language": "Go" }, { "code": "import Control.Monad (forM_)\nimport Data.Bool (bool)\nimport Data.List.NonEmpty (NonEmpty, fromList, toList, unfoldr)\nimport Text.Printf (printf)\n\n-- The infinite Calkin-Wilf sequence, a(n), starting with a(1) = 1.\ncalkinWilfs :: [Rational]\ncalkinWilfs = iterate (recip . succ . ((-) =<< (2 *) . fromIntegral . floor)) 1\n\n-- The index into the Calkin-Wilf sequence of a given rational number, starting\n-- with 1 at index 1.\ncalkinWilfIdx :: Rational -> Integer\ncalkinWilfIdx = rld . cfo\n\n-- A continued fraction representation of a given rational number, guaranteed\n-- to have an odd length.\ncfo :: Rational -> NonEmpty Int\ncfo = oddLen . cf\n\n-- The canonical (i.e. shortest) continued fraction representation of a given\n-- rational number.\ncf :: Rational -> NonEmpty Int\ncf = unfoldr step\n where\n step r =\n case properFraction r of\n (n, 1) -> (succ n, Nothing)\n (n, 0) -> (n, Nothing)\n (n, f) -> (n, Just (recip f))\n\n-- Ensure a continued fraction has an odd length.\noddLen :: NonEmpty Int -> NonEmpty Int\noddLen = fromList . go . toList\n where\n go [x, y] = [x, pred y, 1]\n go (x:y:zs) = x : y : go zs\n go xs = xs\n\n-- Run-length decode a continued fraction.\nrld :: NonEmpty Int -> Integer\nrld = snd . foldr step (True, 0)\n where\n step i (b, n) =\n let p = 2 ^ i\n in (not b, n * p + bool 0 (pred p) b)\n\nmain :: IO ()\nmain = do\n forM_ (take 20 $ zip [1 :: Int ..] calkinWilfs) $\n \\(i, r) -> printf \"%2d %s\\n\" i (show r)\n let r = 83116 / 51639\n printf\n \"\\n%s is at index %d of the Calkin-Wilf sequence.\\n\"\n (show r)\n (calkinWilfIdx r)\n", "language": "Haskell" }, { "code": "cw_next_term=: [: % +:@<. + -.\n\nccf =: compute_continued_fraction=: 3 :0\n if. 0 -: y do.\n , 0\n else.\n result=. i. 0\n remainder=. % y\n whilst. remainder do.\n remainder=. % remainder\n integer_part=. <. remainder\n remainder=. remainder - integer_part\n result=. result , integer_part\n end.\n end.\n)\n\nmolcf =: make_odd_length_continued_fraction=: (}: , 1 ,~ <:@{:)^:(0 -: 2 | #)\n\nNB. base 2 @ reverse @ the cf's representation copies of 1 0 1 0 ...\nindex_cw_term=: #.@|.@(# 1 0 $~ #)@molcf@ccf\n", "language": "J" }, { "code": "ccf=: _1 {\"1 |.@(0 1 #: %@{.)^:(0~:{.)^:a:\n", "language": "J" }, { "code": "import java.util.ArrayDeque;\nimport java.util.Deque;\n\npublic final class CalkinWilfSequence {\n\n\tpublic static void main(String[] aArgs) {\n\t\tRational term = Rational.ONE;\n\t System.out.println(\"First 20 terms of the Calkin-Wilf sequence are:\");\n\t for ( int i = 1; i <= 20; i++ ) {\n\t \tSystem.out.println(String.format(\"%2d\", i) + \": \" + term);\n\t \tterm = nextCalkinWilf(term);\n\t }\n\t System.out.println();\n\t\n\t Rational rational = new Rational(83_116, 51_639);\n\t System.out.println(\" \" + rational + \" is the \" + termIndex(rational) + \"th term of the sequence.\");\n\n\t}\n\t\n\tprivate static Rational nextCalkinWilf(Rational aTerm) {\n\t\tRational divisor = Rational.TWO.multiply(aTerm.floor()).add(Rational.ONE).subtract(aTerm);\n\t\treturn Rational.ONE.divide(divisor);\n\t}\n\t\n\tprivate static long termIndex(Rational aRational) {\n\t long result = 0;\n\t long binaryDigit = 1;\n\t long power = 0;\n\t for ( long term : continuedFraction(aRational) ) {\n\t for ( long i = 0; i < term; power++, i++ ) {\n\t result |= ( binaryDigit << power );\n\t }\n\t binaryDigit = ( binaryDigit == 0 ) ? 1 : 0;\n\t }\n\t return result;\n\t}\n\t\n\tprivate static Deque<Long> continuedFraction(Rational aRational) {\n\t long numerator = aRational.numerator();\n\t long denominator = aRational.denominator();\n\t Deque<Long> result = new ArrayDeque<Long>();\n\t\n\t while ( numerator != 1 ) {\n\t result.addLast(numerator / denominator);\n\t long copyNumerator = numerator;\n\t numerator = denominator;\n\t denominator = copyNumerator % denominator;\n\t }\n\t\n\t if ( ! result.isEmpty() && result.size() % 2 == 0 ) {\n\t \tfinal long back = result.removeLast();\n\t \tresult.addLast(back - 1);\n\t result.addLast(1L);\n\t }\n\t return result;\n\t}\n\n}\n\nfinal class Rational {\n\t\n\tpublic Rational(long aNumerator, long aDenominator) {\n \tif ( aDenominator == 0 ) {\n \t\tthrow new ArithmeticException(\"Denominator cannot be zero\");\n \t}\n \tif ( aNumerator == 0 ) {\n \t\taDenominator = 1;\n \t}\n \tif ( aDenominator < 0 ) {\n \t\tnumer = -aNumerator;\n \t\tdenom = -aDenominator;\n \t} else {\n \t\tnumer = aNumerator;\n \t\tdenom = aDenominator;\n \t} \t\n \tfinal long gcd = gcd(numer, denom);\n \tnumer = numer / gcd;\n \tdenom = denom / gcd;\n }\n\t\n\tpublic Rational add(Rational aOther) {\n \treturn new Rational(numer * aOther.denom + aOther.numer * denom, denom * aOther.denom);\n }\n\t\n\tpublic Rational subtract(Rational aOther) {\n\t\treturn new Rational(numer * aOther.denom - aOther.numer * denom, denom * aOther.denom);\n\t}\n\n public Rational multiply(Rational aOther) {\n\t\treturn new Rational(numer * aOther.numer, denom * aOther.denom);\n\t}\n\n public Rational divide(Rational aOther) {\n\t\treturn new Rational(numer * aOther.denom, denom * aOther.numer);\n\t}\n\n public Rational floor() {\n \treturn new Rational(numer / denom, 1);\n }\n\n public long numerator() {\n \treturn numer;\n }\n\n public long denominator() {\n \treturn denom;\n }\n\n @Override\n public String toString() {\n \treturn numer + \"/\" + denom;\n }\n\n public static final Rational ONE = new Rational(1, 1);\n public static final Rational TWO = new Rational(2, 1);\n\n private long gcd(long aOne, long aTwo) {\n \tif ( aTwo == 0 ) {\n \t\treturn aOne;\n \t}\n \treturn gcd(aTwo, aOne % aTwo);\n }\n\n private long numer;\n private long denom;\n\n}\n", "language": "Java" }, { "code": "include \"rational\"; # see [[Arithmetic/Rational#jq]]\n\n### Generic Utilities\n\n# counting from 0\ndef enumerate(s): foreach s as $x (-1; .+1; [., $x]);\n\n# input string is converted from \"base\" to an integer, within limits\n# of the underlying arithmetic operations, and without error-checking:\ndef to_i(base):\n explode\n | reverse\n | map(if . > 96 then . - 87 else . - 48 end) # \"a\" ~ 97 => 10 ~ 87\n | reduce .[] as $c\n # state: [power, ans]\n ([1,0]; (.[0] * base) as $b | [$b, .[1] + (.[0] * $c)])\n | .[1];\n\n### The Calkin-Wilf Sequence\n\n# Emit an array of $n terms\ndef calkinWilf($n):\n reduce range(1;$n) as $i ( [r(1;1)];\n radd(1; rminus( rmult(2; (.[$i-1]|rfloor)); .[$i-1])) as $t\n | .[$i] = rdiv(r(1;1) ; $t)) ;\n\n# input: a Rational\ndef toContinued:\n { a: .n,\n b: .d,\n res: [] }\n | until( .break;\n .res += [.a / .b | floor]\n | (.a % .b) as $t\n | .a = .b\n | .b = $t\n | .break = (.a == 1) )\n | if .res|length % 2 == 0\n then # ensure always odd\n .res[-1] += -1\n | .res += [1]\n else .\n end\n | .res;\n\n# input: an array representing a continued fraction\ndef getTermNumber:\n reduce .[] as $n ( {b: \"\", d: \"1\"};\n .b = (.d * $n) + .b\n | .d = (if .d == \"1\" then \"0\" else \"1\" end))\n | .b | to_i(2) ;\n\n# input: a Rational in the Calkin-Wilf sequence\ndef getTermNumber:\n reduce .[] as $n ( {b: \"\", d: \"1\"};\n .b = (.d * $n) + .b\n | .d = (if .d == \"1\" then \"0\" else \"1\" end))\n | .b | to_i(2) ;\n\ndef task(r):\n \"The first 20 terms of the Calkin-Wilf sequence are:\",\n (enumerate(calkinWilf(20)[]) | \"\\(1+.[0]): \\(.[1]|rpp)\" ),\n \"\",\n \"\\(r|rpp) is term # \\(r|toContinued|getTermNumber) of the sequence.\";\n\ntask( r(83116; 51639) )\n", "language": "Jq" }, { "code": "function calkin_wilf(n)\n cw = zeros(Rational, n + 1)\n for i in 2:n + 1\n t = Int(floor(cw[i - 1])) * 2 - cw[i - 1] + 1\n cw[i] = 1 // t\n end\n return cw[2:end]\nend\n\nfunction continued(r::Rational)\n a, b = r.num, r.den\n res = []\n while true\n push!(res, Int(floor(a / b)))\n a, b = b, a % b\n a == 1 && break\n end\n return res\nend\n\nfunction term_number(cf)\n b, d = \"\", \"1\"\n for n in cf\n b = d^n * b\n d = (d == \"1\") ? \"0\" : \"1\"\n end\n return parse(Int, b, base=2)\nend\n\nconst cw = calkin_wilf(20)\nprintln(\"The first 20 terms of the Calkin-Wilf sequence are: $cw\")\n\nconst r = 83116 // 51639\nconst cf = continued(r)\nconst tn = term_number(cf)\nprintln(\"$r is the $tn-th term of the sequence.\")\n", "language": "Julia" }, { "code": "// Little Man Computer, for Rosetta Code.\n// Displays terms of Calkin-Wilf sequence up to the given index.\n// The chosen algorithm calculates the i-th term directly from i\n// (i.e. not using any previous terms).\ninput INP // get number of terms from user\n BRZ exit // exit if 0\n STA max_i // store maximum index\n LDA c1 // index := 1\nnext_i STA i\n// Write index followed by '->'\n OTX 3 // non-standard: minimum width 3, no new line\n LDA asc_hy\n OTC\n LDA asc_gt\n OTC\n// Find greatest power of 2 not exceeding i,\n// and count the number of binary digits in i.\n LDA c1\n STA pwr2\nloop2 STA nrDigits\n LDA i\n SUB pwr2\n SUB pwr2\n BRP double\n BRA part2 // jump out if next power of 2 would exceed i\ndouble LDA pwr2\n ADD pwr2\n STA pwr2\n LDA nrDigits\n ADD c1\n BRA loop2\n// The nth term a/b is calculated from the binary digits of i.\n// The leading 1 is not used.\npart2 LDA c1\n STA a // a := 1\n STA b // b := 1\n LDA i\n SUB pwr2\n STA diff\n// Pre-decrement count, since leading 1 is not used\ndec_ct LDA nrDigits // count down the number of digits\n SUB c1\n BRZ output // if all digits done, output the result\n STA nrDigits\n// We now want to compare diff with pwr2/2.\n// Since division is awkward in LMC, we compare 2*diff with pwr2.\n LDA diff // diff := 2*diff\n ADD diff\n STA diff\n SUB pwr2 // is diff >= pwr2 ?\n BRP digit_1 // binary digit is 1 if yes, 0 if no\n// If binary digit is 0 then set b := a + b\n LDA a\n ADD b\n STA b\n BRA dec_ct\n// If binary digit is 1 then update diff and set a := a + b\ndigit_1 STA diff\n LDA a\n ADD b\n STA a\n BRA dec_ct\n// Now have nth term a/b. Write it to the output.\noutput LDA a // write a\n OTX 1 // non-standard: minimum width 1; no new line\n LDA asc_sl // write slash\n OTC\n LDA b // write b\n OTX 11 // non-standard: minimum width 1; add new line\n LDA i // have we done maximum i yet?\n SUB max_i\n BRZ exit // if yes, exit\n LDA i // if no, increment i and loop back\n ADD c1\n BRA next_i\nexit HLT\n// Constants\nc1 DAT 1\nasc_hy DAT 45\nasc_gt DAT 62\nasc_sl DAT 47\n// Variables\ni DAT\nmax_i DAT\npwr2 DAT\nnrDigits DAT\ndiff DAT\na DAT\nb DAT\n// end\n", "language": "Little-Man-Computer" }, { "code": "// Little Man Computer, for Rosetta Code.\n// Calkin-Wilf sequence: displays index of term entered by user.\n INP // get numerator from user\n BRZ exit // exit if 0\n STA num\n STA a // initialize a := numerator\n INP // get denominator from user\n BRZ exit // exit if 0\n STA den\n STA b // initialize b := denominator\n LDA c0 // initialize index := 0\n STA index\n LDA c1 // initialize power of 2 := 1\n STA pwr2\n// Build binary digits of the index\nloop LDA a // is a = b yet?\n SUB b\n BRZ break // if yes, break out of loop\n BRP a_gt_b // jump if a > b\n// If a < b then b := b - a, binary digit is 0\n LDA b\n SUB a\n STA b\n BRA double\n// If a > b then a := a - b, binary digit is 1\na_gt_b STA a\n LDA index\n ADD pwr2\n STA index\n// In either case, on to next power of 2\ndouble LDA pwr2\n ADD pwr2\n STA pwr2\n BRA loop\n// Out of loop, add leading binary digit 1\nbreak LDA index\n ADD pwr2\n STA index\n// Output the result\n LDA num\n OTX 1 // non-standard: minimum width = 1, no new line\n LDA asc_sl\n OTC\n LDA den\n OTX 1\n LDA asc_lt // write '<-' after fraction\n OTC\n LDA asc_hy\n OTC\n LDA index\n OTX 11 // non-standard: minimum width = 1, add new line\nexit HLT\n// Constants\nc0 DAT 0\nc1 DAT 1\nasc_sl DAT 47\nasc_lt DAT 60\nasc_hy DAT 45\n// Variables\nnum DAT\nden DAT\na DAT\nb DAT\npwr2 DAT\nindex DAT\n// end\n", "language": "Little-Man-Computer" }, { "code": "ClearAll[a]\na[1] = 1;\na[n_?(GreaterThan[1])] := a[n] = 1/(2 Floor[a[n - 1]] + 1 - a[n - 1])\na /@ Range[20]\n\nClearAll[a]\na = 1;\nn = 1;\nDynamic[n]\ndone = False;\nWhile[! done,\n a = 1/(2 Floor[a] + 1 - a);\n n++;\n If[a == 83116/51639,\n Print[n];\n Break[];\n ]\n ]\n", "language": "Mathematica" }, { "code": "/* The function fusc is related to Calkin-Wilf sequence */\nfusc(n):=block(\n [k:n,a:1,b:0],\n while k>0 do (if evenp(k) then (k:k/2,a:a+b) else (k:(k-1)/2,b:a+b)),\n b)$\n\n/* Calkin-Wilf function using fusc */\ncalkin_wilf(n):=fusc(n)/fusc(n+1)$\n\n/* Function that given a nonnegative rational returns its position in the Calkin-Wilf sequence */\ncf_bin(fracti):=block(\n cf_list:cf(fracti),\n cf_len:length(cf_list),\n if oddp(cf_len) then cf_list:reverse(cf_list) else cf_list:reverse(append(at(cf_list,[cf_list[cf_len]=cf_list[cf_len]-1]),[1])),\n makelist(lambda([x],if oddp(x) then makelist(1,j,1,cf_list[x]) else makelist(0,j,1,cf_list[x]))(i),i,1,length(cf_list)), /* decoding part begins here */\n apply(append,%%),\n apply(\"+\",makelist(2^i,i,0,length(%%)-1)*reverse(%%)))$\n\n/* Test cases */\n/* 20 first terms of the sequence */\nmakelist(calkin_wilf(i),i,1,20);\n\n/* Position of 83116/51639 in Calkin-Wilf sequence */\n83116/51639$\ncf_bin(%);\n", "language": "Maxima" }, { "code": "type Fraction = tuple[num, den: uint32]\n\niterator calkinWilf(): Fraction =\n ## Yield the successive values of the sequence.\n var n, d = 1u32\n yield (n, d)\n while true:\n n = 2 * (n div d) * d + d - n\n swap n, d\n yield (n, d)\n\nproc `$`(fract: Fraction): string =\n ## Return the representation of a fraction.\n $fract.num & '/' & $fract.den\n\nfunc `==`(a, b: Fraction): bool {.inline.} =\n ## Compare two fractions. Slightly faster than comparison of tuples.\n a.num == b.num and a.den == b.den\n\nwhen isMainModule:\n\n echo \"The first 20 terms of the Calkwin-Wilf sequence are:\"\n var count = 0\n for an in calkinWilf():\n inc count\n stdout.write $an & ' '\n if count == 20: break\n stdout.write '\\n'\n\n const Target: Fraction = (83116u32, 51639u32)\n var index = 0\n for an in calkinWilf():\n inc index\n if an == Target: break\n echo \"\\nThe element \", $Target, \" is at position \", $index, \" in the sequence.\"\n", "language": "Nim" }, { "code": "\\\\ This function assumes the existence of a global variable 'an' for 'a[n]'\na(n) = if(n==1, 1, 1 / (2 * floor(an[n-1]) + 1 - an[n-1]));\n\n\\\\ We will use a vector to hold the values and compute them iteratively to avoid stack overflow\nan = vector(20);\nan[1] = 1;\nfor(i=2, 20, an[i] = a(i));\n\n\\\\ Now we print the vector\nprint(an);\n\n\\\\ Initialize variables for the while loop\na = 1;\nn = 1;\n\n\\\\ Loop until the condition is met\nwhile(a != 83116/51639,{\n a = 1/(2 * floor(a) + 1 - a);\n if(n>=123456789,print(n));\n n++;\n});\n\n\\\\ Output the number of iterations needed to reach 83116/51639\nprint(n);\n", "language": "PARI-GP" }, { "code": "program CWTerms;\n\n{-------------------------------------------------------------------------------\nFreePascal command-line program.\nCalculates the Calkin-Wilf sequence up to the specified maximum index,\n where the first term 1/1 has index 1.\nCommand line format is: CWTerms <max_index>\n\nThe program demonstrates 3 algorithms for calculating the sequence:\n(1) Calculate term[2n] and term[2n + 1] from term[n]\n(2) Calculate term[n + 1] from term[n]\n(3) Calculate term[n] directly from n, without using other terms\nAlgorithm 1 is called first, and stores the terms in an array.\nThen the program calls Algorithms 2 and 3, and checks that they agree\n with Algorithm 1.\n-------------------------------------------------------------------------------}\n\nuses SysUtils;\n\ntype TRational = record\n Num, Den : integer;\nend;\n\nvar\n terms : array of TRational;\n max_index, k : integer;\n\n // Routine to calculate array of terms up the the maiximum index\n procedure CalcTerms_algo_1();\n var\n j, k : integer;\n begin\n SetLength( terms, max_index + 1);\n j := 1; // index to earlier term, from which current term is calculated\n k := 1; // index to current term\n terms[1].Num := 1;\n terms[1].Den := 1;\n while (k < max_index) do begin\n inc(k);\n if (k and 1) = 0 then begin // or could write \"if not Odd(k)\"\n terms[k].Num := terms[j].Num;\n terms[k].Den := terms[j].Num + terms[j].Den;\n end\n else begin\n terms[k].Num := terms[j].Num + terms[j].Den;\n terms[k].Den := terms[j].Den;\n inc(j);\n end;\n end;\n end;\n\n // Method to get each term from the preceding term.\n // a/b --> b/(a + b - 2(a mod b));\n function CheckTerms_algo_2() : boolean;\n var\n index, a, b, temp : integer;\n begin\n result := true;\n index := 1;\n a := 1;\n b := 1;\n while (index <= max_index) do begin\n if (a <> terms[index].Num) or (b <> terms[index].Den) then\n result := false;\n temp := a + b - 2*(a mod b);\n a := b;\n b := temp;\n inc( index)\n end;\n end;\n\n // Mathod to calcualte each term from its index, without using other terms.\n function CheckTerms_algo_3() : boolean;\n var\n index, a, b, pwr2, idiv2 : integer;\n begin\n result := true;\n for index := 1 to max_index do begin\n\n idiv2 := index div 2;\n pwr2 := 1;\n while (pwr2 <= idiv2) do pwr2 := pwr2 shl 1;\n a := 1;\n b := 1;\n while (pwr2 > 1) do begin\n pwr2 := pwr2 shr 1;\n if (pwr2 and index) = 0 then\n inc( b, a)\n else\n inc( a, b);\n end;\n if (a <> terms[index].Num) or (b <> terms[index].Den) then\n result := false;\n end;\n end;\n\nbegin\n // Read and validate maximum index\n max_index := SysUtils.StrToIntDef( paramStr(1), -1); // -1 if not an integer\n if (max_index <= 0) then begin\n WriteLn( 'Maximum index must be a positive integer');\n exit;\n end;\n\n // Calculate terms by algo 1, then check that algos 2 and 3 agree.\n CalcTerms_algo_1();\n if not CheckTerms_algo_2() then begin\n WriteLn( 'Algorithm 2 failed');\n exit;\n end;\n if not CheckTerms_algo_3() then begin\n WriteLn( 'Algorithm 3 failed');\n exit;\n end;\n\n // Display the terms\n for k := 1 to max_index do\n with terms[k] do\n WriteLn( SysUtils.Format( '%8d: %d/%d', [k, Num, Den]));\nend.\n", "language": "Pascal" }, { "code": "program CWIndex;\n\n{-------------------------------------------------------------------------------\nFreePascal command-line program.\nCalculates index of a rational number in the Calkin-Wilf sequence,\n where the first term 1/1 has index 1.\nCommand line format is\n CWIndex <numerator> <denominator>\ne.g. for the Rosetta Code example\n CWIndex 83116 51639\n-------------------------------------------------------------------------------}\n\nuses SysUtils;\n\nvar\n num, den : integer;\n a, b : integer;\n pwr2, index : qword; // 64-bit unsiged\nbegin\n // Read and validate input.\n num := SysUtils.StrToIntDef( paramStr(1), -1); // return -1 if not an integer\n den := SysUtils.StrToIntDef( paramStr(2), -1);\n if (num <= 0) or (den <= 0) then begin\n WriteLn( 'Numerator and denominator must be positive integers');\n exit;\n end;\n\n // Input OK, calculate and display index of num/den\n // The index may overflow 64 bits, so turn on overflow detection\n{$Q+}\n a := num;\n b := den;\n pwr2 := 1;\n index := 0;\n try\n while (a <> b) do begin\n if (a < b) then\n dec( b, a)\n else begin\n dec( a, b);\n inc( index, pwr2);\n end;\n pwr2 := 2*pwr2;\n end;\n inc( index, pwr2);\n WriteLn( SysUtils.Format( 'Index of %d/%d is %u', [num, den, index]));\n except\n WriteLn( 'Index is too large for 64 bits');\n end;\nend.\n", "language": "Pascal" }, { "code": "use strict;\nuse warnings;\nuse feature qw(say state);\n\nuse ntheory 'fromdigits';\nuse List::Lazy 'lazy_list';\nuse Math::AnyNum ':overload';\n\nmy $calkin_wilf = lazy_list { state @cw = 1; push @cw, 1 / ( (2 * int $cw[0]) + 1 - $cw[0] ); shift @cw };\n\nsub r2cf {\n my($num, $den) = @_;\n my($n, @cf);\n my $f = sub { return unless $den;\n my $q = int($num/$den);\n ($num, $den) = ($den, $num - $q*$den);\n $q;\n };\n push @cf, $n while defined($n = $f->());\n reverse @cf;\n}\n\nsub r2cw {\n my($num, $den) = @_;\n my $bits;\n my @f = r2cf($num, $den);\n $bits .= ($_%2 ? 0 : 1) x $f[$_] for 0..$#f;\n fromdigits($bits, 2);\n}\n\nsay 'First twenty terms of the Calkin-Wilf sequence:';\nprintf \"%s \", $calkin_wilf->next() for 1..20;\nsay \"\\n\\n83116/51639 is at index: \" . r2cw(83116,51639);\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #7060A8;\">requires</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"1.0.0\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (new even() builtin)</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">calkin_wilf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cw</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">len</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,(</span><span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #000000;\">cw</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">cw</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">odd_length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cf</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- replace even length continued fraction with odd length equivalent\n -- if remainder(length(cf),2)=0 then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">even</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cf</span><span style=\"color: #0000FF;\">))</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">cf</span><span style=\"color: #0000FF;\">[$]</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">cf</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">cf</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">to_continued_fraction</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">r</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cf</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">cf</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)}</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #000000;\">cf</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">odd_length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cf</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">cf</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">get_term_number</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cf</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">b</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cf</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">b</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cf</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">d</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">bits_to_int</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">t</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- additional verification methods (2 of)</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">i_to_cf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- sequence b = trim_tail(int_to_bits(i,32),0)&2,</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">b</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">int_to_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)&</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">cf</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}:{})</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)></span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">cf</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">b</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">..$]</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #000000;\">cf</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">odd_length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cf</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">cf</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">cf2r</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cf</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cf</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">cf</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">cf</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]*</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">prettyr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">r</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">):</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d/%d\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">}))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cw</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">calkin_wilf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">20</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"The first 20 terms of the Calkin-Wilf sequence are:\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">20</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">prettyr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cw</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]),</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">prettyr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cf2r</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i_to_cf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">get_term_number</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">to_continued_fraction</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cw</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%2d: %-4s [==&gt; %2d: %-3s]\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">83116</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">51639</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cf</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">to_continued_fraction</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">tn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">get_term_number</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cf</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d/%d is the %,d%s term of the sequence.\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">&{</span><span style=\"color: #000000;\">tn</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">ord</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tn</span><span style=\"color: #0000FF;\">)})</span>\n<!--\n", "language": "Phix" }, { "code": "% John Devou: 26-Nov-2021\n\n% g(N,X):- consecutively generate in X the first N elements of the Calkin-Wilf sequence\n\ng(N,[A/B|_]-_,A/B):- N > 0.\ng(N,[A/B|Ls]-[A/C,C/B|Ys],X):- N > 1, M is N-1, C is A+B, g(M,Ls-Ys,X).\ng(N,X):- g(N,[1/1|Ls]-Ls,X).\n\n% t(A/B,X):- generate in X the index of A/B in the Calkin-Wilf sequence\n\nt(A/1,S,C,X):- X is C*(2**(A-1+S)-S).\nt(A/B,S,C,X):- B > 1, divmod(A,B,M,N), T is 1-S, D is C*2**M, t(B/N,T,D,Y), X is Y + S*C*(2**M-1).\nt(A/B,X):- t(A/B,1,1,X), !.\n", "language": "Prolog" }, { "code": "from fractions import Fraction\nfrom math import floor\nfrom itertools import islice, groupby\n\n\ndef cw():\n a = Fraction(1)\n while True:\n yield a\n a = 1 / (2 * floor(a) + 1 - a)\n\ndef r2cf(rational):\n num, den = rational.numerator, rational.denominator\n while den:\n num, (digit, den) = den, divmod(num, den)\n yield digit\n\ndef get_term_num(rational):\n ans, dig, pwr = 0, 1, 0\n for n in r2cf(rational):\n for _ in range(n):\n ans |= dig << pwr\n pwr += 1\n dig ^= 1\n return ans\n\n\nif __name__ == '__main__':\n print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))\n x = Fraction(83116, 51639)\n print(f\"\\n{x} is the {get_term_num(x):_}'th term.\")\n", "language": "Python" }, { "code": " [ $ \"bigrat.qky\" loadfile ] now!\n\n [ ' [ [ 1 1 ] ]\n swap 1 - times\n [ dup -1 peek do\n 2dup proper 2drop\n 2 * n->v\n 2swap -v 1 n->v v+ v+\n 1/v join nested join ] ] is calkin-wilf ( n --> [ )\n\n [ 1 & ] is odd ( n --> b )\n\n [ dup size odd not if\n [ -1 split do\n 1 - join\n 1 join ] ] is oddcf ( [ --> [ )\n\n [ 0 swap\n reverse witheach\n [ i odd iff\n << done\n dup dip <<\n bit 1 - | ] ] is rl->n ( [ --> n )\n\n [ cf oddcf rl->n ] is cw-term ( n/d --> n )\n\n 20 calkin-wilf\n witheach\n [ do vulgar$ echo$ sp ]\n cr cr\n 83116 51639 cw-term echo\n", "language": "Quackery" }, { "code": "my @calkin-wilf = Any, 1, {1 / (.Int × 2 + 1 - $_)} … *;\n\n# Rational to Calkin-Wilf index\nsub r2cw (Rat $rat) { :2( join '', flat (flat (1,0) xx *) Zxx reverse r2cf $rat ) }\n\n# The task\n\nsay \"First twenty terms of the Calkin-Wilf sequence: \",\n @calkin-wilf[1..20]».&prat.join: ', ';\n\nsay \"\\n99991st through 100000th: \",\n (my @tests = @calkin-wilf[99_991 .. 100_000])».&prat.join: ', ';\n\nsay \"\\nCheck reversibility: \", @tests».Rat».&r2cw.join: ', ';\n\nsay \"\\n83116/51639 is at index: \", r2cw 83116/51639;\n\n\n# Helper subs\nsub r2cf (Rat $rat is copy) { # Rational to continued fraction\n gather loop {\n\t $rat -= take $rat.floor;\n\t last if !$rat;\n\t $rat = 1 / $rat;\n }\n}\n\nsub prat ($num) { # pretty Rat\n return $num unless $num ~~ Rat|FatRat;\n return $num.numerator if $num.denominator == 1;\n $num.nude.join: '/';\n}\n", "language": "Raku" }, { "code": "/*REXX pgm finds the Nth value of the Calkin─Wilf sequence (which will be a fraction),*/\n/*────────────────────── or finds which sequence number contains a specified fraction). */\nnumeric digits 2000 /*be able to handle ginormic integers. */\nparse arg LO HI te . /*obtain optional arguments from the CL*/\nif LO=='' | LO==\",\" then LO= 1 /*Not specified? Then use the default.*/\nif HI=='' | HI==\",\" then HI= 20 /* \" \" \" \" \" \" */\nif te=='' | te==\",\" then te= '/' /* \" \" \" \" \" \" */\nif datatype(LO, 'W') then call CW_terms /*Is LO numeric? Then show some terms.*/\nif pos('/', te)>0 then call CW_frac te /*Does TE have a / ? Then find term #*/\nexit 0\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncommas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?\nth: parse arg th; return word('th st nd rd', 1+(th//10) *(th//100%10\\==1) *(th//10<4))\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nCW_frac: procedure; parse arg p '/' q .; say\n if q=='' then do; p= 83116; q= 51639; end\n n= rle2dec( frac2cf(p q) ); @CWS= 'the Calkin─Wilf sequence'\n say 'for ' p\"/\"q', the element number for' @CWS \"is: \" commas(n)th(n)\n if length(n)<10 then return\n say; say 'The above number has ' commas(length(n)) \" decimal digits.\"\n return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nCW_term: procedure; parse arg z; dd= 1; nn= 0\n do z\n parse value dd dd*(2*(nn%dd)+1)-nn with nn dd\n end /*z*/\n return nn'/'dd\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nCW_terms: $=; if LO\\==0 then do j=LO to HI; $= $ CW_term(j)','\n end /*j*/\n if $=='' then return\n say 'Calkin─Wilf sequence terms for ' commas(LO) \" ──► \" commas(HI) ' are:'\n say strip( strip($), 'T', \",\")\n return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nfrac2cf: procedure; parse arg p q; if q=='' then return p; cf= p % q; m= q\n p= p - cf*q; n= p; if p==0 then return cf\n do k=1 until n==0; @.k= m % n\n m= m - @.k * n; parse value n m with m n /*swap N M*/\n end /*k*/\n /*for inverse Calkin─Wilf, K must be even.*/\n if k//2 then do; @.k= @.k - 1; k= k + 1; @.k= 1; end\n do k=1 for k; cf= cf @.k; end /*k*/\n return cf\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nrle2dec: procedure; parse arg f1 rle; obin= copies(1, f1)\n do until rle==''; parse var rle f0 f1 rle\n obin= copies(1, f1)copies(0, f0)obin\n end /*until*/\n return x2d( b2x(obin) ) /*RLE2DEC: Run Length Encoding ──► decimal*/\n", "language": "REXX" }, { "code": "cw = Enumerator.new do |y|\n y << a = 1.to_r\n loop { y << a = 1/(2*a.floor + 1 - a) }\nend\n\ndef term_num(rat)\n num, den, res, pwr, dig = rat.numerator, rat.denominator, 0, 0, 1\n while den > 0\n num, (digit, den) = den, num.divmod(den)\n digit.times do\n res |= dig << pwr\n pwr += 1\n end\n dig ^= 1\n end\n res\nend\n\nputs cw.take(20).join(\", \")\nputs term_num (83116/51639r)\n", "language": "Ruby" }, { "code": "// [dependencies]\n// num = \"0.3\"\n\nuse num::rational::Rational;\n\nfn calkin_wilf_next(term: &Rational) -> Rational {\n Rational::from_integer(1) / (Rational::from_integer(2) * term.floor() + 1 - term)\n}\n\nfn continued_fraction(r: &Rational) -> Vec<isize> {\n let mut a = *r.numer();\n let mut b = *r.denom();\n let mut result = Vec::new();\n loop {\n let (q, r) = num::integer::div_rem(a, b);\n result.push(q);\n a = b;\n b = r;\n if a == 1 {\n break;\n }\n }\n let len = result.len();\n if len != 0 && len % 2 == 0 {\n result[len - 1] -= 1;\n result.push(1);\n }\n result\n}\n\nfn term_number(r: &Rational) -> usize {\n let mut result: usize = 0;\n let mut d: usize = 1;\n let mut p: usize = 0;\n for n in continued_fraction(r) {\n for _ in 0..n {\n result |= d << p;\n p += 1;\n }\n d ^= 1;\n }\n result\n}\n\nfn main() {\n println!(\"First 20 terms of the Calkin-Wilf sequence are:\");\n let mut term = Rational::from_integer(1);\n for i in 1..=20 {\n println!(\"{:2}: {}\", i, term);\n term = calkin_wilf_next(&term);\n }\n let r = Rational::new(83116, 51639);\n println!(\"{} is the {}th term of the sequence.\", r, term_number(&r));\n}\n", "language": "Rust" }, { "code": "; Create a terminating Continued Fraction generator for the given rational number.\n; Returns one term per call; returns #f when no more terms remaining.\n(define make-continued-fraction-gen\n (lambda (rat)\n (let ((num (numerator rat)) (den (denominator rat)))\n (lambda ()\n (if (= den 0)\n #f\n (let ((ret (quotient num den))\n (rem (modulo num den)))\n (set! num den)\n (set! den rem)\n ret))))))\n\n; Return the continued fraction representation of a rational number as a list of terms.\n(define rat->cf-list\n (lambda (rat)\n (let ((cf (make-continued-fraction-gen rat))\n (lst '()))\n (let loop ((term (cf)))\n (when term\n (set! lst (append lst (list term)))\n (loop (cf))))\n lst)))\n\n; Enforce the length of the given continued fraction list to be odd.\n; Changes the list in situ (if needed), and returns its possibly changed value.\n(define continued-fraction-list-enforce-odd-length!\n (lambda (cf)\n (when (even? (length cf))\n (let ((cf-last-cons (list-tail cf (1- (length cf)))))\n (set-car! cf-last-cons (1- (car cf-last-cons)))\n (set-cdr! cf-last-cons (cons 1 '()))))\n cf))\n", "language": "Scheme" }, { "code": "; Create a Calkin-Wilf sequence generator.\n(define make-calkin-wilf-gen\n (lambda ()\n (let ((an 1))\n (lambda ()\n (let ((ret an))\n (set! an (/ 1 (+ (* 2 (floor an)) 1 (- an))))\n ret)))))\n\n; Return the position in the Calkin-Wilf sequence of the given rational number.\n(define calkin-wilf-position\n (lambda (rat)\n ; Run-length encodes binary value. Assumes first run is 1's. Args: initial value,\n ; starting place value (a power of 2), and list of run lengths (list must be odd length).\n (define encode-list-of-runs\n (lambda (value placeval lstruns)\n ; Encode a single run in a binary value. Args: initial value, bit value (0 or 1),\n ; starting place value (a power of 2), number of places (bits) to encode.\n ; Returns multiple values: the encoded value, and the new place value.\n (define encode-run\n (lambda (value bitval placeval places)\n (if (= places 1)\n (values (+ value (* bitval placeval)) (* 2 placeval))\n (encode-run (+ value (* bitval placeval)) bitval (* 2 placeval) (1- places)))))\n ; Loop through the list of runs two at a time. If list of length 1, do a final\n ; '1'-bit encode and return the value. Otherwise, do a '1'-bit then '0'-bit encode,\n ; and recurse to do the next two runs.\n (let-values (((value-1 placeval-1) (encode-run value 1 placeval (car lstruns))))\n (if (= 1 (length lstruns))\n value-1\n (let-values (((value-2 placeval-2) (encode-run value-1 0 placeval-1 (cadr lstruns))))\n (encode-list-of-runs value-2 placeval-2 (cddr lstruns)))))))\n ; Return the run-length binary encoding from the odd-length Calkin-Wilf sequence of the\n ; given rational number. This is equal to the number's position in the sequence.\n (encode-list-of-runs 0 1 (continued-fraction-list-enforce-odd-length! (rat->cf-list rat)))))\n", "language": "Scheme" }, { "code": "(let ((count 20)\n (cw (make-calkin-wilf-gen)))\n (printf \"~%First ~a terms of the Calkin-Wilf sequence:~%\" count)\n (do ((num 1 (1+ num)))\n ((> num count))\n (printf \"~2d : ~a~%\" num (cw))))\n\n(printf \"~%Positions in Calkin-Wilf sequence of given numbers:~%\")\n(let ((num 9/4))\n (printf \"~a @ ~a~%\" num (calkin-wilf-position num)))\n(let ((num 83116/51639))\n (printf \"~a @ ~a~%\" num (calkin-wilf-position num)))\n", "language": "Scheme" }, { "code": "func calkin_wilf(n) is cached {\n return 1 if (n == 1)\n 1/(2*floor(__FUNC__(n-1)) + 1 - __FUNC__(n-1))\n}\n\nfunc r2cw(r) {\n\n var cfrac = r.as_cfrac\n cfrac.len.is_odd || return nil\n\n Num(cfrac.flip.map_kv {|k,v| (k.is_odd ? '0' : '1') * v }.join, 2)\n}\n\nwith (20) {|n|\n say \"First #{n} terms of the Calkin-Wilf sequence:\"\n say calkin_wilf.map(1..n)\n}\n\nwith (83116/51639) {|r|\n say (\"\\n#{r.as_rat} is at index: \", r2cw(r))\n}\n", "language": "Sidef" }, { "code": "import math.fractions\nimport math\nimport strconv\n\nfn calkin_wilf(n int) []fractions.Fraction {\n mut cw := []fractions.Fraction{len: n+1}\n cw[0] = fractions.fraction(1, 1)\n one := fractions.fraction(1, 1)\n two := fractions.fraction(2, 1)\n for i in 1..n {\n mut t := cw[i-1]\n mut f := t.f64()\n f = math.floor(f)\n t = fractions.approximate(f)\n t*=two\n t-= cw[i-1]\n t+=one\n t=t.reciprocal()\n cw[i] = t\n }\n return cw\n}\n\nfn to_continued(r fractions.Fraction) []int {\n\tidx := r.str().index('/') or {0}\n mut a := r.str()[..idx].i64()\n mut b := r.str()[idx+1..].i64()\n mut res := []int{}\n for {\n res << int(a/b)\n t := a % b\n a, b = b, t\n if a == 1 {\n break\n }\n }\n le := res.len\n if le%2 == 0 { // ensure always odd\n res[le-1]--\n res << 1\n }\n return res\n}\n\nfn get_term_number(cf []int) ?int {\n mut b := \"\"\n mut d := \"1\"\n for n in cf {\n b = d.repeat(n)+b\n if d == \"1\" {\n d = \"0\"\n } else {\n d = \"1\"\n }\n }\n i := strconv.parse_int(b, 2, 64)?\n return int(i)\n}\n\nfn commatize(n int) string {\n mut s := \"$n\"\n if n < 0 {\n s = s[1..]\n }\n le := s.len\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0..i] + \",\" + s[i..]\n }\n if n >= 0 {\n return s\n }\n return \"-\" + s\n}\n\nfn main() {\n cw := calkin_wilf(20)\n println(\"The first 20 terms of the Calkin-Wilf sequnence are:\")\n for i := 1; i <= 20; i++ {\n println(\"${i:2}: ${cw[i-1]}\")\n }\n println('')\n r := fractions.fraction(83116, 51639)\n cf := to_continued(r)\n tn := get_term_number(cf) or {0}\n println(\"$r is the ${commatize(tn)}th term of the sequence.\")\n}\n", "language": "V-(Vlang)" }, { "code": "import \"./rat\" for Rat\nimport \"./fmt\" for Fmt, Conv\n\nvar calkinWilf = Fn.new { |n|\n var cw = List.filled(n, null)\n cw[0] = Rat.one\n for (i in 1...n) {\n var t = cw[i-1].floor * 2 - cw[i-1] + 1\n cw[i] = Rat.one / t\n }\n return cw\n}\n\nvar toContinued = Fn.new { |r|\n var a = r.num\n var b = r.den\n var res = []\n while (true) {\n res.add((a/b).floor)\n var t = a % b\n a = b\n b = t\n if (a == 1) break\n }\n if (res.count%2 == 0) { // ensure always odd\n res[-1] = res[-1] - 1\n res.add(1)\n }\n return res\n}\n\nvar getTermNumber = Fn.new { |cf|\n var b = \"\"\n var d = \"1\"\n for (n in cf) {\n b = (d * n) + b\n d = (d == \"1\") ? \"0\" : \"1\"\n }\n return Conv.atoi(b, 2)\n}\n\nvar cw = calkinWilf.call(20)\nSystem.print(\"The first 20 terms of the Calkin-Wilf sequence are:\")\nRat.showAsInt = true\nfor (i in 1..20) Fmt.print(\"$2d: $s\", i, cw[i-1])\nSystem.print()\nvar r = Rat.new(83116, 51639)\nvar cf = toContinued.call(r)\nvar tn = getTermNumber.call(cf)\nFmt.print(\"$s is the $,r term of the sequence.\", r, tn)\n", "language": "Wren" } ]
Calkin-Wilf-sequence
[ { "code": "---\ncategory:\n- Functions and subroutines\n- Simple\nfrom: http://rosettacode.org/wiki/Call_a_function\n", "language": "00-META" }, { "code": ";Task:\nDemonstrate the different syntax and semantics provided for calling a function. \n\n\nThis may include:\n:* &nbsp; Calling a function that requires no arguments\n:* &nbsp; Calling a function with a fixed number of arguments\n:* &nbsp; Calling a function with [[Optional parameters|optional arguments]]\n:* &nbsp; Calling a function with a [[Variadic function|variable number of arguments]]\n:* &nbsp; Calling a function with [[Named parameters|named arguments]]\n:* &nbsp; Using a function in statement context\n:* &nbsp; Using a function in [[First-class functions|first-class context]] within an expression\n:* &nbsp; Obtaining the return value of a function\n:* &nbsp; Distinguishing built-in functions and user-defined functions\n:* &nbsp; Distinguishing subroutines and functions\n;* &nbsp; Stating whether arguments are [[:Category:Parameter passing|passed]] by value or by reference\n;* &nbsp; Is partial application possible and how\n\n<br>\nThis task is ''not'' about [[Function definition|defining functions]].\n<br><bR>\n", "language": "00-TASK" }, { "code": "F no_args() {}\n// call\nno_args()\n\nF fixed_args(x, y)\n print(‘x=#., y=#.’.format(x, y))\n// call\nfixed_args(1, 2) // x=1, y=2\n\n// named arguments\nfixed_args(x' 1, y' 2)\n\nF opt_args(x = 1)\n print(x)\n// calls\nopt_args() // 1\nopt_args(3.141) // 3.141\n", "language": "11l" }, { "code": "X DS F\nY DS F\nZ DS F\n", "language": "360-Assembly" }, { "code": " L R15,=V(MULTPLIC)\n LA R1,PARMLIST address of the paramter list\n BALR R14,R15 branch and link\n ST R0,Z Z=MULTPLIC(X,Y)\n* ...\nPARMLIST DC A(X)\n DC A(Y)\n", "language": "360-Assembly" }, { "code": " CALL MULTPLIC,(X,Y) call MULTPLIC(X,Y)\n ST R0,Z Z=MULTPLIC(X,Y)\n", "language": "360-Assembly" }, { "code": " LOAD EP=MULTPLIC load load-module\n LR R15,R0 retrieve entry address\n CALL (R15),(X,Y) call MULTPLIC(X,Y)\n ST R0,Z Z=MULTPLIC(X,Y)\n", "language": "360-Assembly" }, { "code": "JSR myFunction\n", "language": "6502-Assembly" }, { "code": "sum:\n;adds the values in zero page address $00 and $01, outputs to accumulator.\nLDA $00 ;load the byte stored at memory address $0000\nCLC\nADC $01 ;add the byte at memory address $0001\nRTS ;return\n", "language": "6502-Assembly" }, { "code": "JSR myFunction\n", "language": "68000-Assembly" }, { "code": "call foo\n", "language": "8086-Assembly" }, { "code": "push ax ;second argument\npush bx ;first argument - typically arguments are pushed in the reverse order they are listed.\ncall foo\npop bx\npop ax\n\nfoo:\npush bp\nmov bp,sp\n;now bp+4 = the value pushed from BX, and bp+6 = the value pushed from AX\n", "language": "8086-Assembly" }, { "code": "foo:\nld ax,word ptr[ds:bar] ;load from bar, which is a 16 bit storage location in the data segment (DS), into AX\n", "language": "8086-Assembly" }, { "code": "mov AH,4Ch\nmov AL,00h\nint 21h\n", "language": "8086-Assembly" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program callfonct.s */\n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n/***********************/\n/* Initialized data */\n/***********************/\n.data\nszMessage: .asciz \"Hello. \\n\" // message\nszRetourLigne: .asciz \"\\n\"\nszMessResult: .asciz \"Resultat : \" // message result\n\n/***********************/\n/* No Initialized data */\n/***********************/\n.bss\nsZoneConv: .skip 100\n\n.text\n.global main\nmain:\n ldr x0,=szMessage // adresse of message short program\n bl affichageMess // call function with 1 parameter (x0)\n\n // call function with parameters in register\n mov x0,#5\n mov x1,#10\n bl fonction1 // call function with 2 parameters (x0,x1)\n ldr x1,qAdrsZoneConv // result in x0\n bl conversion10S // call function with 2 parameter (x0,x1)\n ldr x0,=szMessResult\n bl affichageMess // call function with 1 parameter (x0)\n ldr x0,qAdrsZoneConv\n bl affichageMess\n ldr x0,qAdrszRetourLigne\n bl affichageMess\n // call function with parameters on stack\n mov x0,#5\n mov x1,#10\n stp x0,x1,[sp,-16]! // store registers on stack\n bl fonction2 // call function with 2 parameters on the stack\n // result in x0\n ldr x1,qAdrsZoneConv\n bl conversion10S // call function with 2 parameter (x0,x1)\n ldr x0,=szMessResult\n bl affichageMess // call function with 1 parameter (x0)\n ldr x0,qAdrsZoneConv\n bl affichageMess\n ldr x0,qAdrszRetourLigne\n bl affichageMess\n // end of program\n mov x0, #0 // return code\n mov x8, #EXIT // request to exit program\n svc 0 // perform the system call\nqAdrsZoneConv: .quad sZoneConv\nqAdrszRetourLigne: .quad szRetourLigne\n/******************************************************************/\n/* call function parameter in register */\n/******************************************************************/\n/* x0 value one */\n/* x1 value two */\n/* return in x0 */\nfonction1:\n stp x2,lr,[sp,-16]! // save registers\n mov x2,#20\n mul x0,x0,x2\n add x0,x0,x1\n ldp x2,lr,[sp],16 // restaur 2 registres\n ret // retour adresse lr x30\n\n/******************************************************************/\n/* call function parameter in the stack */\n/******************************************************************/\n/* return in x0 */\nfonction2:\n stp fp,lr,[sp,-16]! // save registers\n add fp,sp,#16 // address parameters in the stack\n stp x1,x2,[sp,-16]! // save others registers\n ldr x0,[fp] // second paraméter\n ldr x1,[fp,#8] // first parameter\n mov x2,#-20\n mul x0,x0,x2\n add x0,x0,x1\n ldp x1,x2,[sp],16 // restaur 2 registres\n ldp fp,lr,[sp],16 // restaur 2 registres\n add sp,sp,#16 // very important, for stack aligned\n ret // retour adresse lr x30\n\n\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": " myfunction(); /* function with no arguments in statement context */\n myfunction(6,b); // function with two arguments in statement context\n stringit(\"apples\"); //function with a string argument\n", "language": "ActionScript" }, { "code": "S: String := Ada.Text_IO.Get_Line;\n", "language": "Ada" }, { "code": "function F(X: Integer; Y: Integer := 0) return Integer; -- Y is optional\n...\nA : Integer := F(12);\nB : Integer := F(12, 0); -- the same as A\nC : Integer := F(12, 1); -- something different\n", "language": "Ada" }, { "code": "type Integer_Array is array (Positive range <>) of Integer;\nfunction Sum(A: Integer_Array) return Integer is\n S: Integer := 0;\nbegin\n for I in A'Range loop\n S := S + A(I);\n end loop;\n return S;\nend Sum;\n...\nA := Sum((1,2,3)); -- A = 6\nB := Sum((1,2,3,4)); -- B = 10\n", "language": "Ada" }, { "code": "function H (Int: Integer;\n Fun: not null access function (X: Integer; Y: Integer)\n return Integer);\n return Integer;\n\n...\n\nX := H(A, F'Access) -- assuming X and A are Integers, and F is a function\n -- taking two Integers and returning an Integer.\n", "language": "Ada" }, { "code": "Positional := H(A, F'Access);\nNamed := H(Int => A, Fun => F'Access);\nMixed := H(A, Fun=>F'Access);\n", "language": "Ada" }, { "code": "# Note functions and subroutines are called procedures (or PROCs) in Algol 68 #\n# A function called without arguments: #\nf;\n# Algol 68 does not expect an empty parameter list for calls with no arguments, \"f()\" is a syntax error #\n# A function with a fixed number of arguments: #\nf(1, x);\n\n# variable number of arguments: #\n# functions that accept an array as a parameter can effectively provide variable numbers of arguments #\n# a \"literal array\" (called a row-display in Algol 68) can be passed, as is often the case for the I/O #\n# functions - e.g.: #\nprint( ( \"the result is: \", r, \" after \", n, \" iterations\", newline ) );\n# the outer brackets indicate the parameters of print, the inner brackets indicates the contents are a \"literal array\" #\n\n# ALGOL 68 does not support optional arguments, though in some cases an empty array could be passed to a function #\n# expecting an array, e.g.: #\nf( () );\n\n# named arguments - see the Algol 68 sample in: http://rosettacode.org/wiki/Named_parameters #\n\n# In \"Talk:Call a function\" a statement context is explained as\n\"The function is used as an instruction (with a void context),\nrather than used within an expression.\"\nBased on that, the examples above are already in a statement context.\nTechnically, when a function that returns other than VOID (i.e. is not a subroutine)\nis called in a statement context, the result of the call is \"voided\" i.e. discarded.\nIf desired, this can be made explicit using a cast, e.g.: #\nVOID(f);\n\n# A function's return value being used: #\nx := f(y);\n\n# There is no distinction between built-in functions and user-defined functions. #\n\n# A subroutine is simply a function that returns VOID. #\n\n# If the function is declared with argument(s) of mode REF MODE,\nthen those arguments are being passed by reference. #\n# Technically, all parameters are passed by value, however the value of a REF MODE is a reference... #\n", "language": "ALGOL-68" }, { "code": "% Note, in Algol W, functions are called procedures %\n% calling a function with no parameters: %\nf;\n\n% calling a function with a fixed number of parameters %\ng( 1, 2.3, \"4\" );\n\n% Algol W does not support optional parameters in general, however constructors for records can %\n% be called wither with parameters (one for each field in the record) or no parameters #\n\n% Algol W does not support variable numbers of parameters, except for the built-in I/O functions #\n% Algol W does not support named arguments %\n\n% A function can be used in a statement context by calling it, as in the examples above %\n\n% First class context: A function can be passed as a parameter to another procedure, e.g.: %\nv := integrate( sin, 0, 1 )\n% assuming a suitable definition of integrate %\n% Algol W does not support functions returning functions %\n\n% obtaining the return value of a function: e.g.: %\nv := g( x, y, z );\n\n% There is no syntactic distinction between user-defined and built-in functions %\n\n% Subroutines and functions are both procedures, a subroutine is a procedure with no return type %\n% (called a proper procedure in Algol W) %\n% There is no syntactic distinction between a call to a function and a call to a subroutine %\n% other than the context %\n\n% In Algol W, parameters are passed by value, result or value result. This must be stated in the %\n% definition of the function/subroutine. Value parameters are passed by value, result and value result %\n% are effectively passed by reference and assigned on function exit. Result parameters are \"out\" parameters %\n% and value result parameters are \"in out\". %\n% Algol W also has \"name\" parameters (not to be confused with named parameters). Functions with name %\n% parameters are somewhat like macros %\n\n% Partial application is not possible in Algol W %\n", "language": "ALGOL-W" }, { "code": "2*2+9\n", "language": "ANT" }, { "code": "*[2;+[2;9]]\necho[\"Hello!\"]\ntime[]\n", "language": "ANT" }, { "code": "/* ARM assembly Raspberry PI */\n/* program callfonct.s */\n\n/* Constantes */\n.equ STDOUT, 1\n.equ WRITE, 4\n.equ EXIT, 1\n\n/***********************/\n/* Initialized data */\n/***********************/\n.data\nszMessage: .asciz \"Hello. \\n\" @ message\nszRetourLigne: .asciz \"\\n\"\nszMessResult: .ascii \"Resultat : \" @ message result\nsMessValeur: .fill 12, 1, ' '\n .asciz \"\\n\"\n/***********************/\t\t\t\t\n/* No Initialized data */\n/***********************/\n.bss\niValeur: .skip 4 @ reserve 4 bytes in memory\n\n.text\n.global main\nmain:\n ldr r0,=szMessage @ adresse of message short program\n bl affichageMess @ call function with 1 parameter (r0)\n\n @ call function with parameters in register\n mov r0,#5\n mov r1,#10\n bl fonction1 @ call function with 2 parameters (r0,r1)\n ldr r1,=sMessValeur @ result in r0\n bl conversion10S @ call function with 2 parameter (r0,r1)\n ldr r0,=szMessResult\n bl affichageMess @ call function with 1 parameter (r0)\n\n @ call function with parameters on stack\n mov r0,#5\n mov r1,#10\n push {r0,r1}\n bl fonction2 @ call function with 2 parameters on the stack\n @ result in r0\n ldr r1,=sMessValeur\n bl conversion10S @ call function with 2 parameter (r0,r1)\n ldr r0,=szMessResult\n bl affichageMess @ call function with 1 parameter (r0)\n\n\n /* end of program */\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\n\n/******************************************************************/\n/* call function parameter in register */\n/******************************************************************/\n/* r0 value one */\n/* r1 value two */\n/* return in r0 */\nfonction1:\n push {fp,lr} /* save des 2 registres */\n push {r1,r2} /* save des autres registres */\n mov r2,#20\n mul r0,r2\n add r0,r0,r1\n pop {r1,r2} /* restaur des autres registres */\n pop {fp,lr} /* restaur des 2 registres */\n bx lr /* retour procedure */\t\n\n/******************************************************************/\n/* call function parameter in the stack */\n/******************************************************************/\n/* return in r0 */\nfonction2:\n push {fp,lr} /* save des 2 registres */\n add fp,sp,#8 /* address parameters in the stack*/\n push {r1,r2} /* save des autres registres */\n ldr r0,[fp]\n ldr r1,[fp,#4]\n mov r2,#-20\n mul r0,r2\n add r0,r0,r1\n pop {r1,r2} /* restaur des autres registres */\n pop {fp,lr} /* restaur des 2 registres */\n add sp,#8 /* very important, for stack aligned */\n bx lr /* retour procedure */\t\n\n/******************************************************************/\n/* affichage des messages avec calcul longueur */\n/******************************************************************/\n/* r0 contient l adresse du message */\naffichageMess:\n push {fp,lr} /* save des 2 registres */\n push {r0,r1,r2,r7} /* save des autres registres */\n mov r2,#0 /* compteur longueur */\n1: /*calcul de la longueur */\n ldrb r1,[r0,r2] /* recup octet position debut + indice */\n cmp r1,#0 /* si 0 c est fini */\n beq 1f\n add r2,r2,#1 /* sinon on ajoute 1 */\n b 1b\n1: /* donc ici r2 contient la longueur du message */\n mov r1,r0 /* adresse du message en r1 */\n mov r0,#STDOUT /* code pour écrire sur la sortie standard Linux */\n mov r7, #WRITE /* code de l appel systeme 'write' */\n swi #0 /* appel systeme */\n pop {r0,r1,r2,r7} /* restaur des autres registres */\n pop {fp,lr} /* restaur des 2 registres */\n bx lr\t /* retour procedure */\t\n/***************************************************/\n/* conversion registre en décimal signé */\n/***************************************************/\n/* r0 contient le registre */\n/* r1 contient l adresse de la zone de conversion */\nconversion10S:\n push {fp,lr} /* save des 2 registres frame et retour */\n push {r0-r5} /* save autres registres */\n mov r2,r1 /* debut zone stockage */\n mov r5,#'+' /* par defaut le signe est + */\n cmp r0,#0 /* nombre négatif ? */\n movlt r5,#'-' /* oui le signe est - */\n mvnlt r0,r0 /* et inversion en valeur positive */\n addlt r0,#1\n\n mov r4,#10 /* longueur de la zone */\n1: /* debut de boucle de conversion */\n bl divisionpar10 /* division */\n add r1,#48 /* ajout de 48 au reste pour conversion ascii */\t\n strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */\n sub r4,r4,#1 /* position précedente */\n cmp r0,#0\n bne 1b\t /* boucle si quotient different de zéro */\n strb r5,[r2,r4] /* stockage du signe à la position courante */\n subs r4,r4,#1 /* position précedente */\n blt 100f /* si r4 < 0 fin */\n /* sinon il faut completer le debut de la zone avec des blancs */\n mov r3,#' ' /* caractere espace */\t\n2:\n strb r3,[r2,r4] /* stockage du byte */\n subs r4,r4,#1 /* position précedente */\n bge 2b /* boucle si r4 plus grand ou egal a zero */\n100: /* fin standard de la fonction */\n pop {r0-r5} /*restaur des autres registres */\n pop {fp,lr} /* restaur des 2 registres frame et retour */\n bx lr\n\n/***************************************************/\n/* division par 10 signé */\n/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*\n/* and http://www.hackersdelight.org/ */\n/***************************************************/\n/* r0 contient le dividende */\n/* r0 retourne le quotient */\t\n/* r1 retourne le reste */\ndivisionpar10:\t\n /* r0 contains the argument to be divided by 10 */\n push {r2-r4} /* save autres registres */\n mov r4,r0\n ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */\n smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */\n mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */\n mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */\n add r0, r2, r1 /* r0 <- r2 + r1 */\n add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */\n sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */\n pop {r2-r4}\n bx lr /* leave function */\n .align 4\n.Ls_magic_number_10: .word 0x66666667\n", "language": "ARM-Assembly" }, { "code": "printHello: $[][\n\tprint \"Hello World!\"\n]\n\nsayHello: $[name][\n\tprint [\"Hello\" name \"!\"]\n]\n\nprintAll: $[args][\n\tloop args [arg][\n\t\tprint arg\n\t]\n]\n\ngetNumber: $[][3]\n\n; Calling a function that requires no arguments\nprintHello\n\n; Calling a function with a fixed number of arguments\nsayHello \"John\"\n\n; Calling a function with a variable number of arguments\nprintAll [\"one\" \"two\" \"three\"]\n\n; Using a function in statement context\nif true [printHello]\nprint getNumber\n\n; Using a function in first-class context within an expression\nif getNumber=3 [print \"yep, it worked\"]\n\n; Obtaining the return value of a function:\nnum: getNumber\n\nprint num\n", "language": "Arturo" }, { "code": "; Call a function without arguments:\nf()\n\n; Call a function with a fixed number of arguments:\nf(\"string\", var, 15.5)\n\n; Call a function with optional arguments:\nf(\"string\", var, 15.5)\n\n; Call a function with a variable number of arguments:\nf(\"string\", var, 15.5)\n\n; Call a function with named arguments:\n ; AutoHotkey does not have named arguments. However, in v1.1+,\n ; we can pass an object to the function:\nf({named: \"string\", otherName: var, thirdName: 15.5})\n\n; Use a function in statement context:\nf(1), f(2) ; What is statement context?\n\n; No first-class functions in AHK\n\n; Obtaining the return value of a function:\nvarThatGetsReturnValue := f(1, \"a\")\n\n; Cannot distinguish built-in functions\n\n; Subroutines are called with GoSub; functions are called as above.\n; Subroutines cannot be passed variables\n\n; Stating whether arguments are passed by value or by reference:\n; [v1.1.01+]: The IsByRef() function can be used to determine\n; whether the caller supplied a variable for a given ByRef parameter.\n; A variable cannot be passed by value to a byRef parameter. Instead, do this:\nf(tmp := varIdoNotWantChanged)\n; the function f will receive the value of varIdoNotWantChanged, but any\n; modifications will be made to the variable tmp.\n\n; Partial application is impossible.\n", "language": "AutoHotkey" }, { "code": "BEGIN {\n sayhello() # Call a function with no parameters in statement context\n b=squareit(3) # Obtain the return value from a function with a single parameter in first class context\n}\n", "language": "AWK" }, { "code": "NOARG()\nARGS(1,5,42)\n", "language": "Axe" }, { "code": "OPARG(1,2,3,4,5,6)\nOPARG(1,2,3)\nOPARG()\n", "language": "Axe" }, { "code": "MATHS(2,4)→A\nDisp GETSTR()\n", "language": "Axe" }, { "code": "USER()\naxeFunc()\n", "language": "Axe" }, { "code": "function Copialo$ (txt$, siNo, final$)\n\tnuevaCadena$ = \"\"\n\n\tfor cont = 1 to siNo\n\t\tnuevaCadena$ += txt$\n\tnext cont\n\n\treturn trim(nuevaCadena$) + final$\nend function\n\nsubroutine Saludo()\n\tprint \"Hola mundo!\"\nend subroutine\n\nsubroutine testCadenas (txt$)\n\tfor cont = 1 to length(txt$)\n\t\tprint mid(txt$, cont, 1); \"\";\n\tnext cont\nend subroutine\n\nsubroutine testNumeros (a, b, c)\n\tprint a, b, c\nend subroutine\n\ncall Saludo()\nprint Copialo$(\"Saludos \", 6, \"\")\nprint Copialo$(\"Saludos \", 3, \"!!\")\nprint\ncall testNumeros(1, 2, 3)\ncall testNumeros(1, 2, 0)\nprint\ncall testCadenas(\"1, 2, 3, 4, cadena, 6, 7, 8, \\#incluye texto\\#\")\nend\n", "language": "BASIC256" }, { "code": ":: http://rosettacode.org/wiki/Call_a_function\n:: Demonstrate the different syntax and semantics provided for calling a function.\n\n@echo off\n\necho Calling myFunction1\ncall:myFunction1\necho.\n\necho Calling myFunction2 11 8\ncall:myFunction2 11 8\necho.\n\necho Calling myFunction3 /fi and saving the output into %%filecount%%\ncall:myFunction3 /fi\necho.%filecount%\necho.\n\necho Calling myFunction4 1 2 3 4 5\ncall:myFunction4 1 2 3 4 5\necho.\n\necho Calling myFunction5 \"filename=test.file\" \"filepath=C:\\Test Directory\\\"\ncall:myFunction5 \"filename=test.file\" \"filepath=C:\\Test Directory\\\"\necho.\necho Calling myFunction5 \"filepath=C:\\Test Directory\\\" \"filename=test.file\"\ncall:myFunction5 \"filepath=C:\\Test Directory\\\" \"filename=test.file\"\necho.\n\npause>nul\nexit\n\n:: Requires no arguments\n:myFunction1\n\techo myFunction1 has been called.\n\tgoto:eof\n\n:: Fixed number of arguments (%a% & %b%)\n:myFunction2\n\t:: Returns %a% + %b%\n\tsetlocal\n\tset /a c=%~1+%~2\n\tendlocal & echo %c%\n\tgoto:eof\n\n:: Optional arguments\n:myFunction3\n\t:: Returns the amount of folders + files in the current directory\n\t:: /fi Returns only file count\n\t:: /fo Returns only folder count\n\t\n\tsetlocal\n\tset count=0\n\t\n\tif \"%~1\"==\"\" set \"command=dir /b\"\n\tif \"%~1\"==\"/fi\" set \"command=dir /b /A-d\"\n\tif \"%~1\"==\"/fo\" set \"command=dir /b /Ad\"\n\n\tfor /f \"usebackq\" %%i in (`%command%`) do set /a count+=1\n\t\n\tendlocal & set filecount=%count%\n\tgoto:eof\n\n:: Variable number of arguments\n:myFunction4\n\t:: Returns sum of arguments\n\tsetlocal\n\t:myFunction4loop\n\tset sum=0\n\tfor %%i in (%*) do set /a sum+=%%i\n\tendlocal & echo %sum%\n\tgoto:eof\n\n:: Named Arguments (filepath=[path] & filename=[name])\n:myFunction5\n\t:: Returns the complete path based off the 2 arguments\n\tif \"%~1\"==\"\" then goto:eof\n\tsetlocal enabledelayedexpansion\n\tset \"param=%~1\"\n\t\n\tfor /l %%i in (1,1,2) do (\n\t\tfor /f \"tokens=1,2 delims==\" %%j in (\"!param!\") do set %%j=%%k\n\t\tset \"param=%~2\"\n\t)\n\tendlocal & echo.%filepath%%filename%\n\tgoto:eof\n", "language": "Batch-File" }, { "code": "PRINT SQR(2)\n", "language": "BBC-BASIC" }, { "code": "PRINT SQR 2\n", "language": "BBC-BASIC" }, { "code": "PRINT FN_foo(bar$, baz%)\n", "language": "BBC-BASIC" }, { "code": "PRINT FN_foo\n", "language": "BBC-BASIC" }, { "code": "PROC_foo\n", "language": "BBC-BASIC" }, { "code": "PROC_foo(bar$, baz%, quux)\n", "language": "BBC-BASIC" }, { "code": "DEF PROC_foo(a$, RETURN b%, RETURN c)\n", "language": "BBC-BASIC" }, { "code": "200 GOSUB 30050\n", "language": "BBC-BASIC" }, { "code": "{𝕊 ·: 1 + 1}0\n", "language": "BQN" }, { "code": "2⊸-\n", "language": "BQN" }, { "code": "F 1\n", "language": "BQN" }, { "code": "2 F 1\n", "language": "BQN" }, { "code": "{\n 𝕊 one‿two‿three:\n one∾two∾three\n}\n", "language": "BQN" }, { "code": "1 {𝕨+𝕩} 2\n", "language": "BQN" }, { "code": "1 + 2\n", "language": "BQN" }, { "code": "⟨+, -, ∾⟩\n", "language": "BQN" }, { "code": "var ← Func # insert arg here\n", "language": "BQN" }, { "code": "+⟜2\n", "language": "BQN" }, { "code": "aFunctionWithoutArguments$\n", "language": "Bracmat" }, { "code": "aFunctionWithoutArguments'\n", "language": "Bracmat" }, { "code": "func$!myargument;\n", "language": "Bracmat" }, { "code": "(yourfunc=local vars.function body)\n", "language": "Bracmat" }, { "code": "('$myfunc:(=?yourfunc))\n", "language": "Bracmat" }, { "code": "myfunc$!myarg:?myresult\n", "language": "Bracmat" }, { "code": "myfunc$!myarg&yourfunc$!yourarg\n", "language": "Bracmat" }, { "code": "`(myfunc$!myarg)&yourfunc$!yourarg\n", "language": "Bracmat" }, { "code": "( ( plus\n = a b\n . !arg:%?a ?b\n & !b:\n & '(.!arg+$a)\n | !a+!b\n )\n& out$(\"1+2, not partial:\" plus$(1 2))\n& out$(\"1+2, partial:\" (plus$1)$2)\n);\n", "language": "Bracmat" }, { "code": "/* function with no argument */\nf();\n\n/* fix number of arguments */\ng(1, 2, 3);\n\n/* Optional arguments: err...\n Feel free to make sense of the following. I can't. */\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n} /* end of sensible code */\n\n/* Variadic function: how the args list is handled solely depends on the function */\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n/* call it as: (if you feed it something it doesn't expect, don't count on it working) */\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n/* named arguments: this is only possible through some pre-processor abuse\n*/\nstruct v_args {\n int arg1;\n int arg2;\n char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); // prints \"17,5\"\n/* NOTE the above implementation gives us optional typesafe optional arguments as well (unspecified arguments are initialized to zero)*/\nv(.arg2=1); // prints \"0,1\"\nv(); // prints \"0,0\"\n\n/* as a first-class object (i.e. function pointer) */\nprintf(\"%p\", f); /* that's the f() above */\n\n/* return value */\ndouble a = asin(1);\n\n/* built-in functions: no such thing. Compiler may interally give special treatment\n to bread-and-butter functions such as memcpy(), but that's not a C built-in per se */\n\n/* subroutines: no such thing. You can goto places, but I doubt that counts. */\n\n/* Scalar values are passed by value by default. However, arrays are passed by reference. */\n/* Pointers *sort of* work like references, though. */\n", "language": "C" }, { "code": "/* function with no arguments */\nfoo();\n", "language": "C++" }, { "code": "/* passing arguments by value*/\n/* function with one argument */\nbar(arg1);\n/* function with multiple arguments */\nbaz(arg1, arg2);\n", "language": "C++" }, { "code": "/* get return value of a function */\nvariable = function(args);\n", "language": "C++" }, { "code": "#include <iostream>\nusing namespace std;\n/* passing arguments by reference */\nvoid f(int &y) /* variable is now passed by reference */\n{\ny++;\n}\nint main()\n{\nint x = 0;\ncout<<\"x = \"<<x<<endl; /* should produce result \"x = 0\" */\nf(x); /* call function f */\ncout<<\"x = \"<<x<<endl; /* should produce result \"x = 1\" */\n}\n", "language": "C++" }, { "code": "/* a function that has no argument */\n\tpublic int MyFunction();\n\n\t/* a function with a fixed number of arguments */\n\tFunctionWithArguments(4, 3, 2);\n\n\t/* a function with optional arguments */\n\tpublic void OptArg();\n\n\tpublic static void Main()\n\t{\n\t\tOptArg(1);\n\t\tOptArg(1, 2);\n\t\tOptArg(1, 2, 3);\n\t}\n\tpublic void ExampleMethod(int required,\n string optionalstr = \"default string\",\n\t\tint optionalint = 10)\n\t/* If you know the first and the last parameter */\n\tExampleMethod(3, optionalint: 4);\n\n\t/* If you know all the parameter */\n\tExampleMethod(3, \"Hello World\", 4);\n\n\t/* Variable number of arguments use array */\n\tpublic static void UseVariableParameters(params int[] list)\n\n\t/* Obtain return value from function */\n\tpublic internal MyFunction();\n\tint returnValue = MyFunction();\n", "language": "C-sharp" }, { "code": "(defn one []\n \"Function that takes no arguments and returns 1\"\n 1)\n\n(one); => 1\n", "language": "Clojure" }, { "code": ";;You can assign it to a variable:\n\n(def receipt-us (format-receipt \"Toilet Paper\" 5 format-price-us))\n\n;; Then the variable holds the value\nreceipt-us; => \"Toilet Paper $5\"\n\n;; Or you can use it in a call to another function\n\n(defn add-store-name [receipt]\n \"A function to add a footer to the receipt\"\n (str receipt \"\\n Thanks for shopping at Safeway\" ))\n\n;; Calls add-store-name with the result of the format function\n(add-store-name (format-receipt \"Toilet Paper\" 5 format-price-us)); => \"Toilet Paper $5\\n Thanks for shopping at Safeway\"\n", "language": "Clojure" }, { "code": ";; They are indistinguishable in Clojure, and you can even override a built in one\n\n;; Using built-in addition\n\n(+ 5 5); => 10\n\n;; Using custom defined addition\n\n(defn ? [a b]\n \"Returns the sum of two numbers\"\n (+ a b))\n\n(? 5 5); => 10\n\n;; Overriding a built in function is possible but not recommended\n\n(defn * [a b] ;; Redefining the multiplication operator\n \"Returns the sum of two numbers\"\n (+ a b))\n\n(* 5 5); => 10\n", "language": "Clojure" }, { "code": ";; They are the same thing - indeed, everything in clojure is a function\n;; Functions without return values simply return nil\n\n(defn no-return-value [a]\n (print (str \"Your argument was\" a \"; now returning nil\")))\n\n(no-return-value \"hi\"); => nil\n", "language": "Clojure" }, { "code": ";; Set up a variable that we will pass to a function\n(def the-queen {:name \"Elizabeth\"\n :title \"Your Majesty\"\n :address \"Buckingham Palace\"\n :pets [\"Corgi\" \"Horse\"]})\n\n;; A function to modify the data\n(defn adopt-pet [person pet]\n \"Adds pet to the person's list of pets\"\n (update person\n :pets\n #(conj % pet)))\n\n;; Calling the function returns a new data structure with the modified pets\n(adopt-pet the-queen \"Ferret\"); => {:name \"Elizabeth\":title \"Your Majesty\" :address \"Buckingham Palace\" :pets [\"Corgi\" \"Horse\" \"Ferret]}\n\n;; The original data structure is not changed\nthe-queen; => {:name \"Elizabeth\" :title \"Your Majesty\" :address \"Buckingham Palace\" :pets [\"Corgi\" \"Horse\"]}\n", "language": "Clojure" }, { "code": "(defn apply-discount [discount-percentage price]\n \"Function to apply a discount to a price\"\n (-> price\n (* (- 100 discount-percentage)) ;; Apply discount\n (/ 100.0)))\n\n;; Here we have assigned the variable to a partial function\n;; It means 'call apply-discount with 10 as the first argument'\n(def discount-10pc-option-1 (partial apply-discount 10))\n\n;; And is equivalent to this:\n(defn discount-10pc-option-2 [price]\n (apply-discount 10 price))\n\n(discount-10pc-option-1 100); => 90\n\n(discount-10pc-option-2 100); => 90\n", "language": "Clojure" }, { "code": "(defn total-cost [item-price num-items]\n \"Returns the total price to buy the given number of items\"\n (* item-price num-items))\n\n(total-cost 1 5); => 5\n", "language": "Clojure" }, { "code": "(defn total-cost-with-discount [item-price num-items & [discount-percentage]]\n \"Returns total price to buy the items after discount is applied (if given)\"\n (let [discount (or discount-percentage 0)] ;; Assign discount to either the discount-percentage (if given) or default 0 if not\n (-> item-price\n (* num-items) ;; Calculate total cost\n (* (- 100 discount)) ;; Apply discount\n (/ 100.0))))\n\n;; Now we can use the function without the optional arguments, and see the same behaviour as our total-cost function\n(total-cost-with-discount 1 5); => 5\n\n;; Or we can add the third parameter to calculate the cost with 20% discount\n(total-cost-with-discount 1 5 20); => 4\n", "language": "Clojure" }, { "code": "(defn make-address\n ([city place-name] (str place-name \", \" city))\n ([city street house-number] (str house-number \" \" street \", \" city))\n ([city street house-number apartment] (str house-number \" \" street \", Apt. \" apartment \", \" city)))\n\n;; To call the function you just need to pass whatever arguments you are supplying as you would with a fixed number\n\n;; First case- the queen doesn't need a street name\n(make-address \"London\" \"Buckingham Palace\"); => \"Buckingham Palace, London\"\n\n;; Second case\n(make-address \"London\" \"Downing Street\" 10); => \"10 Downing Street, London\"\n\n;; Third case\n(make-address \"London\" \"Baker Street\" 221 \"B\"); => \"221 Baker Street, Apt. B, London\"\n", "language": "Clojure" }, { "code": "(defn make-mailing-label [{:keys [name address country]}]\n \"Returns the correct text to mail a letter to the addressee\"\n (str name \"\\n\" address \"\\n\" (or country \"UK\"))) ;; If country is nil, assume it is the UK\n\n;; We can call it with all three arguments in a map to get mickey's international address\n(make-mailing-label {:name \"Mickey Mouse\"\n :address \"1 Disney Avenue, Los Angeles\"\n :country \"USA\"}); => \"Mickey Mouse\\n1 Disney Avenue, Los Angeles\\nUSA\"\n\n;; Or we can call it with fewer arguments for domestic mail\n(make-mailing-label {:name \"Her Majesty\"\n :address \"Buckingham Palace, London\"}); => \"Her Majesty\\nBuckingham Palace, London\\nUK\"\n", "language": "Clojure" }, { "code": "(defn multiply-by-10 [number]\n (* 10 number))\n\n(def fifty (multiply-by-10 5))\n\nfifty; => 50\n", "language": "Clojure" }, { "code": "(defn make-discount-function [discount-percent]\n \"Returns a function that takes a price and applies the given discount\"\n (fn [price] (-> price\n (* (- 100 discount-percent))\n (/ 100.0))))\n\n;; Now we can create a '20% off' function to calculate prices with your discount card\n(def discount-20pc (make-discount-function 20))\n\n;; Use the function to calculate some discount prices\n(discount-20pc 100); => 80\n(discount-20pc 5); => 4\n\n;; Your friend has a better discount card, we can use the same function to create their discount card function\n(def discount-50pc (make-discount-function 50))\n(discount-50pc 100); => 50\n(discount-50pc 5); => 2.5\n", "language": "Clojure" }, { "code": ";; Continuing on the same example, let's imagine Anna has a 20% discount card and Bill has 50%. Charlie pays full price\n;; We can store their discount functions in a map\n\n(def discount-cards {\"Anna\" discount-20pc\n \"Bill\" discount-50pc\n \"Charlie\" identity}) ;; Identity returns whatever value was passed to the function (in this case it will be price)\n\n;; Now we can access them by cardholder name in another function\n(defn calculate-discounted-price [price shopper-name]\n \"Applies the correct discount for the person\"\n (let [discount-fn (get discount-cards shopper-name)] ;; Get the right discount function\n (discount-fn price))) ;; Apply discount function to the price\n\n(calculate-discounted-price 100 \"Anna\"); => 80\n(calculate-discounted-price 100 \"Bill\"); => 50\n(calculate-discounted-price 100 \"Charlie\"); => 100\n", "language": "Clojure" }, { "code": ";; Here we have two functions to format a price depending on the country\n\n(defn format-price-uk [price]\n (str \"£\" price))\n\n(defn format-price-us [price]\n (str \"$\" price))\n\n;; And one function that takes a price formatting function as an argument\n\n(defn format-receipt [item-name price price-formatting-function]\n \"Return the item name and price formatted according to the function\"\n (str item-name\n \" \"\n (price-formatting-function price))) ;; Call the format function to get the right representation of the price\n\n(format-receipt \"Loo Roll\" 5 format-price-uk); => \"Loo Roll £5\"\n\n(format-receipt \"Toilet Paper\" 5 format-price-us); => \"Toilet Paper $5\"\n", "language": "Clojure" }, { "code": "CALL \"No-Arguments\"\n\n*> Fixed number of arguments.\nCALL \"2-Arguments\" USING Foo Bar\n\nCALL \"Optional-Arguments\" USING Foo\nCALL \"Optional-Arguments\" USING Foo Bar\n*> If an optional argument is omitted and replaced with OMITTED, any following\n*> arguments can still be specified.\nCALL \"Optional-Arguments\" USING Foo OMITTED Bar\n*> Interestingly, even arguments not marked as optional can be omitted without\n*> a compiler warning. It is highly unlikely the function will still work,\n*> however.\nCALL \"2-Arguments\" USING Foo\n\n*> COBOL does not support a variable number of arguments, or named arguments.\n\n*> Values to return can be put in either one of the arguments or, in OpenCOBOL,\n*> the RETURN-CODE register.\n*> A standard function call cannot be done in another statement.\nCALL \"Some-Func\" USING Foo\nMOVE Return-Code TO Bar\n\n*> Intrinsic functions can be used in any place a literal value may go (i.e. in\n*> statements) and are optionally preceded by FUNCTION.\n*> Intrinsic functions that do not take arguments may optionally have a pair of\n*> empty parentheses.\n*> Intrinsic functions cannot be defined by the user.\nMOVE FUNCTION PI TO Bar\nMOVE FUNCTION MEDIAN(4, 5, 6) TO Bar\n\n*> Built-in functions/subroutines typically have prefixes indicating which\n*> compiler originally incorporated it:\n*> - C$ - ACUCOBOL-GT\n*> - CBL_ - Micro Focus\n*> - CBL_OC_ - OpenCOBOL\n*> Note: The user could name their functions similarly if they wanted to.\nCALL \"C$MAKEDIR\" USING Foo\nCALL \"CBL_CREATE_DIR\" USING Foo\nCALL \"CBL_OC_NANOSLEEP\" USING Bar\n*> Although some built-in functions identified by numbers.\nCALL X\"F4\" USING Foo Bar\n\n*> Parameters can be passed in 3 different ways:\n*> - BY REFERENCE - this is the default way in OpenCOBOL and this clause may\n*> be omitted. The address of the argument is passed to the function.\n*> The function is allowed to modify the variable.\n*> - BY CONTENT - a copy is made and the function is passed the address\n*> of the copy, which it can then modify. This is recomended when\n*> passing a literal to a function.\n*> - BY VALUE - the function is passed the address of the argument (like a\n*> pointer). This is mostly used to provide compatibility with other\n*> languages, such as C.\nCALL \"Modify-Arg\" USING BY REFERENCE Foo *> Foo is modified.\nCALL \"Modify-Arg\" USING BY CONTENT Foo *> Foo is unchanged.\nCALL \"C-Func\" USING BY VALUE Bar\n\n*> Partial application is impossible as COBOL does not support first-class\n*> functions.\n*> However, as functions are called using a string of their PROGRAM-ID,\n*> you could pass a 'function' as an argument to another function, or store\n*> it in a variable, or get it at runtime.\nACCEPT Foo *> Get a PROGRAM-ID from the user.\nCALL \"Use-Func\" USING Foo\nCALL Foo USING Bar\n", "language": "COBOL" }, { "code": "# Calling a function that requires no arguments\nfoo()\n\n# Calling a function with a fixed number of arguments\nfoo 1\n\n# Calling a function with optional arguments\n# (Optional arguments are done using an object with named keys)\nfoo 1, optionalBar: 1, optionalBaz: 'bax'\n\n# Calling a function with a variable number of arguments\n# for a function `foo` defined as `foo = ( args... ) ->`\nfoo 1, 2, 3, 4\n\n# Calling a function with named arguments\n# (Named arguments are done using an object with named keys)\nfoo bar: 1, bax: 'baz'\n\n# Using a function in statement context\nx = foo 1\n\n# Using a function in first-class context within an expression\n# (For `foo` defined as `foo = ( x ) -> x + 1`\nx = [ 1, 2, 3 ].map foo\n\n# Obtaining the return value of a function\nx = foo 1\n\n# Arguments are passed by value, even objects. Objects\n# are passed as the _value_ of the reference to an object.\n# Example:\nbar = ( person ) ->\n # Since `person` is a reference\n # to the person passed in, we can assign\n # a new value to its `name` key.\n person.name = 'Bob'\n\n # Since `person` is just the value of\n # the original reference, assigning to it\n # does not modify the original reference.\n person = new Person 'Frank'\n\n# Partial application is only possible manually through closures\ncurry = ( f, fixedArgs... ) ->\n ( args... ) -> f fixedArgs..., args...\n\n# Example usage\nadd = ( x, y ) -> x + y\n\nadd2 = curry add, 2\n\nadd2 1 #=> 3\n", "language": "CoffeeScript" }, { "code": ";Calling a function that requires no arguments\n(defun a () \"This is the 'A' function\")\n(a)\n;Calling a function with a fixed number of arguments\n(defun b (x y) (list x y))\n(b 1 2)\n;Calling a function with optional arguments\n(defun c (&optional x y) (list x y))\n(c 1)\n;Calling a function with a variable number of arguments\n(defun d (&rest args) args)\n(d 1 2 3 4 5 6 7 8)\n;Calling a function with named arguments\n(defun e (&key (x 1) (y 2)) (list x y))\n(e :x 10 :y 20)\n;Using a function in first-class context within an expression\n(defun f (func) (funcall func))\n(f #'a)\n;Obtaining the return value of a function\n(defvar return-of-a (a))\n;Is partial application possible and how\n(defun curry (function &rest args-1)\n (lambda (&rest args-2)\n (apply function (append args-1 args-2))))\n(funcall (curry #'+ 1) 2)\n", "language": "Common-Lisp" }, { "code": "// No arguments\nmyfunction\n\n// All functions can take a variable number of arguments.\n// These can be accessed from within the function with the aliases:\n// $arg1, $arg2, $arg3... $numargs tells the amount of args passed.\nmyfunction word \"text string\" 1 3.14\n\n// Getting a function's return value\nretval = (myfunction)\n\n// Trying to do a variable lookup on a builtin function will return an empty\n// string. This can be used to distinguish builtin functions from user-defined\n// ones.\nif (strcmp $echo \"\") [echo builtin function] // true\nif (strcmp $myfunction \"\") [echo builtin function] // false\n", "language": "Cubescript" }, { "code": "import std.traits;\n\nenum isSubroutine(alias F) = is(ReturnType!F == void);\n\nvoid main() {\n void foo1() {}\n\n // Calling a function that requires no arguments:\n foo1();\n foo1; // Alternative syntax.\n\n\n void foo2(int x, int y) {}\n\n immutable lambda = function int(int x) => x ^^ 2;\n\n // Calling a function with a fixed number of arguments:\n foo2(1, 2);\n foo2(1, 2);\n cast(void)lambda(1);\n\n\n void foo3(int x, int y=2) {}\n\n // Calling a function with optional arguments:\n foo3(1);\n foo3(1, 3);\n\n int sum(int[] arr...) {\n int tot = 0;\n foreach (immutable x; arr)\n tot += x;\n return tot;\n }\n\n real sum2(Args...)(Args arr) {\n typeof(return) tot = 0;\n foreach (immutable x; arr)\n tot += x;\n return tot;\n }\n\n // Calling a function with a variable number of arguments:\n assert(sum(1, 2, 3) == 6);\n assert(sum(1, 2, 3, 4) == 10);\n assert(sum2(1, 2.5, 3.5) == 7);\n\n // Calling a function with named arguments:\n // Various struct or tuple-based tricks can be used for this,\n // but currently D doesn't have named arguments.\n\n\n // Using a function in statement context (?):\n if (1)\n foo1;\n\n // Using a function in first-class context within an expression:\n assert(sum(1) == 1);\n\n\n auto foo4() { return 1; }\n\n // Obtaining the return value of a function:\n immutable x = foo4;\n\n\n // Distinguishing built-in functions and user-defined functions:\n // There are no built-in functions, beside the operators, and\n // pseudo-functions like assert().\n\n\n int myFynction(int x) { return x; }\n void mySubroutine(int x) {}\n\n // Distinguishing subroutines and functions:\n // (A subroutine is merely a function that has no explicit\n // return statement and will return void).\n pragma(msg, isSubroutine!mySubroutine); // Prints: true\n pragma(msg, isSubroutine!myFynction); // Prints: false\n\n\n void foo5(int a, in int b, ref int c, out int d, lazy int e, scope int f) {}\n\n // Stating whether arguments are passed by value, by reference, etc:\n alias STC = ParameterStorageClass;\n alias psct = ParameterStorageClassTuple!foo5;\n static assert(psct.length == 6); // Six parameters.\n static assert(psct[0] == STC.none);\n static assert(psct[1] == STC.none);\n static assert(psct[2] == STC.ref_);\n static assert(psct[3] == STC.out_);\n static assert(psct[4] == STC.lazy_);\n static assert(psct[5] == STC.scope_);\n // There are also inout and auto ref.\n\n\n int foo6(int a, int b) { return a + b; }\n\n // Is partial application possible and how:\n import std.functional;\n alias foo6b = partial!(foo6, 5);\n assert(foo6b(6) == 11);\n}\n", "language": "D" }, { "code": "void main() {\n // Function definition\n // See the \"Function definition\" task for more info\n void noArgs() {}\n void fixedArgs(int arg1, int arg2) {}\n void optionalArgs([int arg1 = 1]) {}\n void namedArgs({required int arg1}) {}\n int returnsValue() {return 1;}\n\n // Calling a function that requires no arguments\n noArgs();\n\n // Calling a function with a fixed number of arguments\n fixedArgs(1, 2);\n\n // Calling a function with optional arguments\n optionalArgs();\n optionalArgs(2);\n\n // Calling a function with named arguments\n namedArgs(arg1: 1);\n\n // Using a function in statement context\n if (true) {\n noArgs();\n }\n\n // Obtaining the return value of a function\n var value = returnsValue();\n}\n", "language": "Dart" }, { "code": "foo()\n", "language": "Delphi" }, { "code": "foo(1)\n", "language": "Delphi" }, { "code": "foo(1, 2, 3, 4, 5)\n", "language": "Delphi" }, { "code": "writeLn('Hello world.');\nfoo;\nwriteLn('Goodbye world')\n", "language": "Delphi" }, { "code": "myMethod()\n", "language": "Dragon" }, { "code": "myMethod(97, 3.14)\n", "language": "Dragon" }, { "code": "func foo() { }\nfoo()\n", "language": "Dyalect" }, { "code": "//There is no difference between subroutines and functions:\nfunc foo() { } //doesn't explicitly return something (but in fact returns nil)\nfunc bar(x) { return x * 2 } //explicitly returns value (keyword \"return\" can be omitted)\n", "language": "Dyalect" }, { "code": "//All arguments are passed by reference\n", "language": "Dyalect" }, { "code": "//Using a closure:\nfunc apply(fun, fst) { snd => fun(fst, snd) }\n\n//Usage:\nfunc sum(x, y) { x + y }\n\nvar sum2 = apply(sum, 2)\nvar x = sum2(3) //x is 5\n\n//By second argument\nfunc flip(fun) { (y, x) => fun(x, y) }\nfunc sub(x, y) { x - y }\n\nvar sub3 = apply(flip(sub), 3)\nx = sub3(9) //x is 6\n", "language": "Dyalect" }, { "code": "func foo(x, y, z) { }\nfoo(1, 2, 3)\n", "language": "Dyalect" }, { "code": "func foo(x, y = 0, z = 1) { }\nfoo(1)\n", "language": "Dyalect" }, { "code": "func foo(args...) { }\nfoo(1, 2, 3)\n", "language": "Dyalect" }, { "code": "func foo(x, y, z) { }\nfoo(z: 3, x: 1, y: 2)\n", "language": "Dyalect" }, { "code": "func foo() { }\nif true {\n foo()\n}\n", "language": "Dyalect" }, { "code": "func foo() { }\nvar x = if foo() {\n 1\n} else {\n 2\n}\n", "language": "Dyalect" }, { "code": "func foo(x) { x * 2 }\nvar x = 2\nvar y = foo(x)\n", "language": "Dyalect" }, { "code": "//Built-in functions are regular functions from an implicitly imported \"lang\" module\n//There is no actual difference between these functions and user-defined functions\n\n//You can however write a function that would check if a given function is declared in \"lang\" module:\nfunc isBuiltin(fn) =>\n fn.Name is not nil && fn.Name in lang && lang[fn.Name] == fn\n\n//Usage:\nfunc foo() { } //A user-defined function\nprint(isBuiltin(foo)) //Prints: false\nprint(isBuiltin(assert)) //Prints: true\n", "language": "Dyalect" }, { "code": "func sqr n .\n return n * n\n.\nprint sqr 3\n#\nproc divmod a b . q r .\n q = a div b\n r = a mod b\n.\ndivmod 11 3 q r\nprint q & \" \" & r\n#\nsubr sqr2\n a = a * a\n.\na = 5\nsqr2\nprint a\n", "language": "EasyLang" }, { "code": "foo(); // <-- this is \"invoking a function in statement context\"\nInt x = bar(); // <-- this is \"invoking a function in expression context\"\n", "language": "Ecstasy" }, { "code": "foo(1, 2, 3);\nInt x = bar(4, 5, 6);\n", "language": "Ecstasy" }, { "code": "module CallOptArgsFunc {\n static Int foo(Int a=0, Int b=99, Int c=-1) {\n return a + b + c;\n }\n\n void run() {\n @Inject Console console;\n console.print($\"{foo()=}\");\n console.print($\"{foo(1)=}\");\n console.print($\"{foo(1, 2)=}\");\n console.print($\"{foo(1, 2, 3)=}\");\n }\n}\n", "language": "Ecstasy" }, { "code": "module CallVarArgsFunc {\n // Ecstasy does not have a var-args concept; instead, array notation is used\n static Int foo(Int[] args = []) {\n return args.size;\n }\n\n void run() {\n @Inject Console console;\n console.print($\"{foo()=}\");\n console.print($\"{foo([])=}\");\n console.print($\"{foo([1])=}\");\n console.print($\"{foo([1, 2])=}\");\n console.print($\"{foo([1, 2, 3])=}\");\n }\n}\n", "language": "Ecstasy" }, { "code": "module CallNamedArgsFunc {\n static String foo(Int a=1, Int b=2, Int c=3) {\n return $\"a:{a}, b:{b}, c:{c}\";\n }\n\n void run() {\n @Inject Console console;\n console.print($\"{foo(c=9, b=8, a=7)=}\");\n console.print($\"{foo(4, c=6, b=5)=}\");\n console.print($\"{foo(c=99)=}\");\n }\n}\n", "language": "Ecstasy" }, { "code": "module FirstClassFunctions {\n @Inject Console console;\n void run() {\n function Int(String) stringLen = s -> s.size;\n function Int(Int, Int) sum = (n1, n2) -> n1+n2;\n String[] testData = [\"abc\", \"easy\", \"as\", \"123\"];\n console.print($|total string length of values in {testData} =\\\n | {testData.map(stringLen).reduce(0, sum)}\n );\n }\n}\n", "language": "Ecstasy" }, { "code": "module ObtainReturnValues {\n (Int, String, Dec) foo() {\n return 3, \"hello!\", 9.87;\n }\n\n void run() {\n foo(); // ignore return values\n Int i1 = foo(); // only use first returned value\n (Int i2, String s2) = foo(); // only use first two returned values\n (Int i3, String s3, Dec d3) = foo(); // use all returned values\n Tuple<Int, String, Dec> t = foo(); // alternatively, get the tuple instead\n\n @Inject Console console;\n console.print($\"{i3=}, {s3=}, {d3=}, {t=}\");\n }\n}\n", "language": "Ecstasy" }, { "code": "// Ecstasy does not have any built-in functions. However, there are two keywords\n// (\"is\" and \"as\") that use a function-like syntax:\nmodule IsAndAs {\n Int|String foo() {\n return \"hello\";\n }\n\n void run() {\n @Inject Console console;\n Object o = foo();\n if (o.is(String)) { // <- looks like a function call\n String s = o.as(String); // <- looks like a function call\n console.print($\"foo returned the string: {s.quoted()}\");\n }\n }\n}\n", "language": "Ecstasy" }, { "code": "module PartialApplication {\n void foo(String s, Int i, Dec d) {\n @Inject Console console;\n console.print($\"inside call to foo({s=}, {i=}, {d=})\");\n }\n\n void run() {\n // note that the \"&\" obtains the reference to the function, and suppresses the\n // invocation thereof, so it is *allowed* in all three of these cases, but it\n // is *required* in the third case:\n function void(String, Int, Dec) unbound = foo; // or \"foo(_, _, _)\"\n function void(String, Dec) partBound = unbound(_, 99, _);\n function void() allBound = &partBound(\"world\", 3.14);\n\n unbound(\"nothing\", 0, 0.0);\n partBound(\"hello\", 2.718);\n allBound();\n }\n}\n", "language": "Ecstasy" }, { "code": "var c0 := { console.writeLine(\"No argument provided\") };\nvar c2 := (int a, int b){ console.printLine(\"Arguments \",a,\" and \",b,\" provided\") };\n", "language": "Elena" }, { "code": " c0();\n", "language": "Elena" }, { "code": " c2(2,4);\n", "language": "Elena" }, { "code": " var exch := (ref object x){ x := 2 };\n var a := 1;\n exch(ref a);\n", "language": "Elena" }, { "code": "# Anonymous function\n\nfoo = fn() ->\n IO.puts(\"foo\")\nend\n\nfoo() #=> undefined function foo/0\nfoo.() #=> \"foo\"\n\n# Using `def`\n\ndefmodule Foo do\n def foo do\n IO.puts(\"foo\")\n end\nend\n\nFoo.foo #=> \"foo\"\nFoo.foo() #=> \"foo\"\n\n\n# Calling a function with a fixed number of arguments\n\ndefmodule Foo do\n def foo(x) do\n IO.puts(x)\n end\nend\n\nFoo.foo(\"foo\") #=> \"foo\"\n\n# Calling a function with a default argument\n\ndefmodule Foo do\n def foo(x \\\\ \"foo\") do\n IO.puts(x)\n end\nend\n\nFoo.foo() #=> \"foo\"\nFoo.foo(\"bar\") #=> \"bar\"\n\n# There is no such thing as a function with a variable number of arguments. So in Elixir, you'd call the function with a list\n\ndefmodule Foo do\n def foo(args) when is_list(args) do\n Enum.each(args, &(IO.puts(&1)))\n end\nend\n\n# Calling a function with named arguments\n\ndefmodule Foo do\n def foo([x: x]) do\n IO.inspect(x)\n end\nend\n", "language": "Elixir" }, { "code": "fun task = void by text about, fun code\n writeLine(0U00b7 + \" \" + about)\n code()\nend\nfun answer = void by var message do writeLine(\" \" + message) end\n# few definitions\nfun noArgumentsFunction = int by block do return 97 end\nfun fixedArgumentsFunction = void by var a, var b do end\nfun variadicFunction = void by text a, some var values do end\nfun funArgumentFunction = var by fun f, var b do return f() + b end\ntask(\"Calling a function that requires no arguments\", void by block\n answer(\"Is supported.\")\n noArgumentsFunction()\nend)\ntask(\"Calling a function with a fixed number of arguments\", void by block\n answer(\"Is supported.\")\n fixedArgumentsFunction(97, 3.14)\nend)\ntask(\"Calling a function with optional arguments\", void by block\n answer(\"Not supported in EMal.\")\nend)\ntask(\"Calling a function with a variable number of arguments\", void by block\n answer(\"Variadic functions are supported.\")\n variadicFunction(\"mandatory\", 97, 3.14)\n variadicFunction(\"mandatory\", 97)\nend)\ntask(\"Calling a function with named arguments\", void by block\n answer(\"Not supported in EMal.\")\nend)\ntask(\"Using a function in statement context\", void by block\n answer(\"Is supported.\")\n if true do noArgumentsFunction()\n else do fixedArgumentsFunction(97, 3.14) end\nend)\ntask(\"Using a function in first-class context within an expression\", void by block\n answer(\"Functions are first class, can be passed as arguments and returned.\")\n answer(funArgumentFunction(noArgumentsFunction, 3.14))\nend)\ntask(\"Obtaining the return value of a function\", void by block\n answer(\"Is supported.\")\n int value = noArgumentsFunction()\n answer(value)\nend)\ntask(\"Distinguishing built-in functions and user-defined functions\", void by block\n answer(\"No distinction.\")\nend)\ntask(\"Distinguishing subroutines and functions\", void by block\n answer(\"No distinction, we support void return type.\")\nend)\ntask(\"Stating whether arguments are passed by value or by reference\", void by block\n answer(\"Pass by value, but text, blob, objects hold a reference.\")\nend)\ntask(\"Is partial application possible and how\", void by block\n answer(\"Is supported.\")\n ^|I had some confusion about partial application and currying, thanks to these links:\n | https://stackoverflow.com/questions/218025/what-is-the-difference-between-currying-and-partial-application\n | https://web.archive.org/web/20161023205431/http://www.uncarved.com/articles/not_curryin\n |^\n # Partial applying\n fun add = int by int a, int b do return a + b end\n fun partial = fun by fun f, int a\n return int by int b\n return add(a, b)\n end\n end\n fun add7 = partial(add, 7)\n answer(add(7, 5))\n answer(add7(5))\n # Currying\n fun addN = fun by int n\n return int by int x\n return x + n\n end\n end\n fun plus = int by int a, int b\n fun addA = addN(a)\n return addA(b)\n end\n answer(plus(7, 5))\nend)\n", "language": "EMal" }, { "code": "no_argument()\none_argument( Arg )\noptional_arguments( Arg, [{opt1, Opt1}, {another_opt, Another}] )\nvariable_arguments( [Arg1, Arg2 | Rest] )\nnames_arguments([{name1, Arg1}, {another_name, Another}] )\n% Statement context?\n% First class context?\nResult = obtain_result( Arg1 )\n% No way to distinguish builtin/user functions\n% Subroutines?\n% Arguments are passed by reference, but you can not change them.\n% Partial application is possible (a function returns a function that has one argument bound)\n", "language": "Erlang" }, { "code": "// No arguments\nnoArgs()\n\n// Fixed number of arguments\noneArg x\n\n// Optional arguments\n// In a normal function:\noptionalArgs <| Some(5) <| None\n// In a function taking a tuple:\noptionalArgsInTuple(Some(5), None)\n// In a function in a type:\nfoo.optionalArgs 5;;\n// However, if you want to pass more than one paramter, the arguments must be\n// passed in a tuple:\nfoo.optionalArgs(5, 6)\n\n// Function with a variable number of arguments\nvariableArgs 5 6 7 // etc...\n\n// Named arguments can only be used in type methods taking a tuple. The\n// arguments can appear in any order.\nfoo.namedArgs(x = 5, y = 6)\n\n// Using a function in a statement\nfor i = 0 to someFunc() do\n printfn \"Something\"\n\n// Using a function in a first-class context\nfuncArgs someFunc\n\n// Obtaining a return value\nlet x = someFunc()\n\n// Built-in functions: do functions like (+) or (-) count?\n\n// Parameters are normally passed by value (as shown in the previous examples),\n// but they can be passed by reference.\n// Passing by reference:\nrefArgs &mutableVal\n\n// Partial application example\nlet add2 = (+) 2\n", "language": "F-Sharp" }, { "code": "foo\n", "language": "Factor" }, { "code": "foo\n", "language": "Factor" }, { "code": "\"a\" \"b\" \"c\" 3 narray\n! { \"a\" \"b\" \"c\" }\n", "language": "Factor" }, { "code": "<email>\n \"[email protected]\" >>from\n { \"[email protected]\" } >>to\n \"Hello there\" >>subject\n body >>body\nsend-email\n", "language": "Factor" }, { "code": "\\ foo\n", "language": "Factor" }, { "code": "{ foo } [ foo ]\n", "language": "Factor" }, { "code": "foo\n", "language": "Factor" }, { "code": "\\ foo primitive?\n", "language": "Factor" }, { "code": "{ 1 2 3 } 2 [ - ] curry map .\n! { -1 0 1 }\n", "language": "Factor" }, { "code": "a-function \\ requiring no arguments\na-function \\ with a fixed number of arguents\na-function \\ having optional arguments\na-function \\ having a variable number of arguments\na-function \\ having such named arguments as we have in Forth\n' a-function var ! \\ using a function in a first-class context (here: storing it in a variable)\na-function \\ in which we obtain a function's return value\n\n \\ forth lacks 'statement contenxt'\n \\ forth doesn't distinguish between built-in and user-defined functions\n \\ forth doesn't distinguish between functions and subroutines\n \\ forth doesn't care about by-value or by-reference\n\n\\ partial application is achieved by creating functions and manipulating stacks\n: curried 0 a-function ;\n: only-want-third-argument 1 2 rot a-function ;\n\n\\ Realistic example:\n: move ( delta-x delta-y -- )\n y +! x +! ;\n\n: down ( n -- ) 0 swap move ;\n: up ( n -- ) negate down ;\n: right ( n -- ) 0 move ;\n: left ( n -- ) negate right ;\n", "language": "Forth" }, { "code": "program main\nimplicit none\ninteger :: a\ninteger :: f, g\nlogical :: lresult\ninterface\n integer function h(a,b,c)\n integer :: a, b\n integer, optional :: c\n end function\nend interface\nwrite(*,*) 'no arguments: ', f()\nwrite(*,*) '-----------------'\nwrite(*,*) 'fixed arguments: ', g(5,8,lresult)\nwrite(*,*) '-----------------'\nwrite(*,*) 'optional arguments: ', h(5,8), h(5,8,4)\nwrite(*,*) '-----------------'\nwrite(*,*) 'function with variable arguments: Does not apply!'\nwrite(*,*) 'An option is to pass arrays of variable lengths.'\nwrite(*,*) '-----------------'\nwrite(*,*) 'named arguments: ', h(c=4,b=8,a=5)\nwrite(*,*) '-----------------'\nwrite(*,*) 'function in statement context: Does not apply!'\nwrite(*,*) '-----------------'\nwrite(*,*) 'Fortran passes memory location of variables as arguments.'\nwrite(*,*) 'So an argument can hold the return value.'\nwrite(*,*) 'function result: ', g(5,8,lresult) , ' function successful? ', lresult\nwrite(*,*) '-----------------'\nwrite(*,*) 'Distinguish between built-in and user-defined functions: Does not apply!'\nwrite(*,*) '-----------------'\nwrite(*,*) 'Calling a subroutine: '\na = 30\ncall sub(a)\nwrite(*,*) 'Function call: ', f()\nwrite(*,*) '-----------------'\nwrite(*,*) 'All variables are passed as pointers.'\nwrite(*,*) 'Problems can arise if instead of sub(a), one uses sub(10).'\nwrite(*,*) '-----------------'\nend program\n\n!no argument\ninteger function f()\nf = 10\nend function\n\n!fixed number of arguments\ninteger function g(a, b, lresult)\ninteger :: a, b\nlogical :: lresult\ng = a+b\nlresult = .TRUE.\nend function\n\n!optional arguments\ninteger function h(a, b, c)\ninteger :: a, b\ninteger, optional :: c\n\nh = a+b\nif(present(c)) then\n h = h+10*c\nend if\nend function\n\n!subroutine\nsubroutine sub(a)\ninteger :: a\na = a*100\nwrite(*,*) 'Output of subroutine: ', a\nend subroutine\n", "language": "Fortran" }, { "code": " REAL this,that\n DIST(X,Y,Z) = SQRT(X**2 + Y**2 + Z**2) + this/that !One arithmetic statement, possibly lengthy.\n ...\n D = 3 + DIST(X1 - X2,YDIFF,SQRT(ZD2)) !Invoke local function DIST.\n", "language": "Fortran" }, { "code": " H = A + B\n IF (blah) H = 3*H - 7\n", "language": "Fortran" }, { "code": " REAL FUNCTION INTG8(F,A,B,DX)\t!Integrate function F.\n EXTERNAL F\t!Some function of one parameter.\n REAL A,B\t\t!Bounds.\n REAL DX\t\t!Step.\n INTEGER N\t!A counter.\n INTG8 = F(A) + F(B)\t!Get the ends exactly.\n N = (B - A)/DX\t\t!Truncates. Ignore A + N*DX = B chances.\n DO I = 1,N\t\t!Step along the interior.\n INTG8 = INTG8 + F(A + I*DX)\t!Evaluate the function.\n END DO\t\t\t!On to the next.\n INTG8 = INTG8/(N + 2)*(B - A)\t!Average value times interval width.\n END FUNCTION INTG8\t!This is not a good calculation!\n\n FUNCTION TRIAL(X)\t\t!Some user-written function.\n REAL X\n TRIAL = 1 + X\t\t!This will do.\n END FUNCTION TRIAL\t!Not the name of a library function.\n\n PROGRAM POKE\n INTRINSIC SIN\t!Thus, not an (undeclared) ordinary variable.\n EXTERNAL TRIAL\t!Likewise, but also, not an intrinsic function.\n REAL INTG8\t!Don't look for the result in an integer place.\n WRITE (6,*) \"Result=\",INTG8(SIN, 0.0,8*ATAN(1.0),0.01)\n WRITE (6,*) \"Linear=\",INTG8(TRIAL,0.0,1.0, 0.01)\n END\n", "language": "Fortran" }, { "code": " TYPE MIXED\n CHARACTER*12 NAME\n INTEGER STUFF\n END TYPE MIXED\n TYPE(MIXED) LOTS(12000)\n", "language": "Fortran" }, { "code": "component call_a_function\n export Executable\n (* Declaring test functions that allow the various ways to call functions in Fortress to be demonstrated. *)\n addition(i:ZZ32, j:ZZ32): ZZ32 = i+j\n addition(i:ZZ32): ZZ32 = i+1\n\n (* Strings are concatenated by using a space as an infix operator. *)\n addition(i:String, j:String): String = i j\n\n printAString(s:String): () = println(s)\n\n (* Functions can be passed to other functions as arguments. When passing a function as an argument, the argument's type should be\n represented as follows: \"typeOfArgument(s)->returnType,\" which, in this case, is \"String->().\" You could also technically use the\n \"Any\" type, but that isn't type-safe. *)\n printAString(s:String, f:String->()) = f(s)\n\n (* Defined functions can then be called as follows. *)\n var x:ZZ32 = addition(1, 2)\n var str:String = addition(\"This is \", \"another string.\")\n\n run() = do\n (* You can call built-in functions the same way that you call functions that you define. *)\n println(\"x at start: \" x)\n\n x := addition(x, 2)\n\n println(\"x at middle: \" x)\n\n printAString(\"This \" \"is \" \"a \" \"string.\")\n printAString(str)\n printAString(\"\\nThis is a string that is being printed by a function of the same name \\nthat takes a function as an argument.\\n\",\n printAString)\n\n x := addition(4)\n\n println(\"x at end: \" x)\n end\nend\n", "language": "Fortress" }, { "code": "Sub Saludo()\n Print \"Hola mundo!\"\nEnd Sub\n\nFunction Copialo(txt As String, siNo As Short, final As String = \"\") As String\n Dim nuevaCadena As String\n\n For cont As Short = 1 To siNo\n nuevaCadena &= txt\n Next\n\n Return Trim(nuevaCadena) & final\nEnd Function\n\nSub testNumeros(a As Integer, b As Integer, c As Integer = 0)\n\tPrint a, b, c\nEnd Sub\n\nSub testCadenas(txt As String)\n For cont As Byte = 0 To Len(txt)\n Print Chr(txt[cont]); \"\";\n Next cont\nEnd Sub\n\nSaludo\nPrint Copialo(\"Saludos \", 6)\nPrint Copialo(\"Saludos \", 3, \"!!\")\n?\ntestNumeros(1, 2, 3)\ntestNumeros(1, 2)\n?\ntestCadenas(\"1, 2, 3, 4, cadena, 6, 7, 8, \\'incluye texto\\'\")\n", "language": "FreeBASIC" }, { "code": "void local fn MyFunction\n print @\"MyFunction\"\nend fn\n\nfn MyFunction\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "void local fn MyFunction( arg1 as long, arg2 as long, arg3 as long )\n print @\"MyFunction\"\nend fn\n\nfn MyFunction( 1, 2, 3 )\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "void local fn MyFunction( count as long, ... )\n va_list ap\n long i, value\n\n va_start( ap, count )\n for i = 1 to count\n value = fn va_arglong( ap )\n print value\n next\n\n va_end( ap )\nend fn\n\nfn MyFunction( 3, 12, 24, 36 )\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "local fn MultiplyByThree( value as long ) as long\nend fn = value * 3\n\nprint fn MultiplyByThree( 13 )\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "void local fn MultiplyByThree( value as ^long )\n *value *= 3\nend fn\n\nlong num\nnum = 9\nfn MultiplyByThree( @num )\nprint num\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\n\nHello\nPrint CopyIt(\"Hello \", 6)\nPrint CopyIt(\"Hello \", 3, \"!!\")\n\nEnd\n'_____________________________________________________________________________________\nPublic Sub CopyIt(sString As String, siNo As Short, Optional sEnd As String) As String\nDim siCount As Short\nDim sNewString As String\n\nFor siCount = 1 To siNo\n sNewString &= sString\nNext\n\nReturn Trim(sNewString) & sEnd\n\nEnd\n'_____________________________________________________________________________________\nPublic Sub Hello()\n\nPrint \"Hello world!\"\n\nEnd\n", "language": "Gambas" }, { "code": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64) { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int) {}\n", "language": "Go" }, { "code": "\tlist = append(list, a, d, e, i)\n\ti = len(list)\n", "language": "Go" }, { "code": "package main\n\nimport \"fmt\"\n\n// int parameter, so arguments will be passed to it by value.\nfunc zeroval(ival int) {\n\tival = 0\n}\n// has an *int parameter, meaning that it takes an int pointer.\nfunc zeroptr(iptr *int) {\n\t*iptr = 0\n}\nfunc main() {\n\ti := 1\n\tfmt.Println(\"initial:\", i) // prt initial: 1\n\tzeroval(i)\n\tfmt.Println(\"zeroval:\", i) // prt zeroval: 1\n\tzeroptr(&i)\n\tfmt.Println(\"zeroptr:\", i) // prt zeroptr: 0\n\tfmt.Println(\"pointer:\", &i) // prt pointer: 0xc0000140b8\n}\n", "language": "Go" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc mkAdd(a int) func(int) int {\n\treturn func(b int) int {\n\t\treturn a + b\n\t}\n}\nfunc sum(x, y int) int {\n\treturn x + y\n}\n\nfunc partialSum(x int) func(int) int {\n\treturn func(y int) int {\n\t\treturn sum(x, y)\n\t}\n}\nfunc main() {\n\t// Is partial application possible and how\n\tadd2 := mkAdd(2)\n\tadd3 := mkAdd(3)\n\tfmt.Println(add2(5), add3(6)) // prt 7 9\n\t// Currying functions in go\n\tpartial := partialSum(13)\n\tfmt.Println(partial(5)) //prt 18\n}\n", "language": "Go" }, { "code": "\tf()\n\tg(1, 2.0)\n\t// If f() is defined to return exactly the number and type of\n\t// arguments that g() accepts than they can be used in place:\n\tg(f())\n\t// But only without other arguments, this won't compile:\n\t//h(\"fail\", f())\n\t// But this will:\n\tg(g(1, 2.0), 3.0)\n", "language": "Go" }, { "code": "\th(\"ex1\")\n\th(\"ex2\", 1, 2)\n\th(\"ex3\", 1, 2, 3, 4)\n\t// such functions can also be called by expanding a slice:\n\tlist := []int{1,2,3,4}\n\th(\"ex4\", list...)\n\t// but again, not mixed with other arguments, this won't compile:\n\t//h(\"fail\", 2, list...)\n", "language": "Go" }, { "code": "\tgif.Encode(ioutil.Discard, image.Black, &gif.Options{NumColors: 16})\n", "language": "Go" }, { "code": "package main\n\nimport \"fmt\"\n\ntype Params struct {\n\ta, b, c int\n}\nfunc doIt(p Params) int {\n\treturn p.a + p.b + p.c\n}\n\nfunc main() {\n\tfmt.Println(doIt(Params{a: 1, c: 9})) // prt 10\n}\n", "language": "Go" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc bar(a, b, c int) {\n\tfmt.Printf(\"%d, %d, %d\", a, b, c)\n}\n\nfunc main() {\n\targs := make(map[string]int)\n\targs[\"a\"] = 3\n\targs[\"b\"] = 2\n\targs[\"c\"] = 1\n\tbar(args[\"a\"], args[\"b\"], args[\"c\"]) // prt 3, 2, 1\n}\n", "language": "Go" }, { "code": "\tif 2*g(1, 3.0)+4 > 0 {}\n", "language": "Go" }, { "code": "\tfn := func(r rune) rune {\n\t\tif unicode.IsSpace(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}\n\tstrings.Map(fn, \"Spaces removed\")\n\tstrings.Map(unicode.ToLower, \"Test\")\n\tstrings.Map(func(r rune) rune { return r + 1 }, \"shift\")\n", "language": "Go" }, { "code": "\ta, b := f() // multivalue return\n\t_, c := f() // only some of a multivalue return\n\td := g(a, c) // single return value\n\te, i := g(d, b), g(d, 2) // multiple assignment\n", "language": "Go" }, { "code": "noArgs()\n", "language": "Groovy" }, { "code": "def retVal = func(x, y, z)\n", "language": "Groovy" }, { "code": "fixedArgs(1, \"Zing\", Color.BLUE, ZonedDateTime.now(), true)\n", "language": "Groovy" }, { "code": "optArgs(\"It's\", \"a\", \"beautiful\", \"day\")\noptArgs(\"It's\", \"a\", \"beautiful\")\noptArgs(\"It's\", \"a\")\noptArgs(\"It's\")\n", "language": "Groovy" }, { "code": "varArgs(\"It's\", \"a\", \"beautiful\", \"day\")\nvarArgs(\"It's\", \"a\", \"beautiful\")\nvarArgs(\"It's\", \"a\")\nvarArgs(\"It's\")\n", "language": "Groovy" }, { "code": "def mean = calcAverage(1.2, 4.5, 3, 8.9, 22, 3)\n", "language": "Groovy" }, { "code": "def oldFunc = { arg1, arg2 -> arg1 + arg2 }\ndef newFunc = oldFunc.curry(30)\nassert newFunc(12) == 42\n", "language": "Groovy" }, { "code": "def funcList = [func1, func2, func3]\n", "language": "Groovy" }, { "code": "def eltChangeFunc = { it * 3 - 1 }\ndef changedList = list.collect(eltChangeFunc)\n", "language": "Groovy" }, { "code": "def funcMaker = { String s, int reps, boolean caps ->\n caps ? { String transString -> ((transString + s) * reps).toUpperCase() }\n : { String transString -> (transString + s) * reps }\n}\ndef func = funcMaker(\"a\", 2, true)\nassert func(\"pook\") == \"POOKAPOOKA\"\n", "language": "Groovy" }, { "code": "-- Calling a function with a fixed number of arguments\nmultiply x y = x * y\nmultiply 10 20 -- returns 200\n\n-- Calling a function that requires no arguments\n-- Normally, you use constant instead of function without arguments:\ntwopi = 6.28\n-- But you can also pass special value as the first argument indicating function call:\ntwopi () = 6.28 -- definition\ntwopi :: Num a => () -> a -- its type\ntwopi () -- returns 6.28\n\n-- Partial application and auto-currying is built-in.\nmultiply_by_10 = (10 * )\nmap multiply_by_10 [1, 2, 3] -- [10, 20, 30]\nmultiply_all_by_10 = map multiply_by_10\nmultiply_all_by_10 [1, 2, 3] -- [10, 20, 30]\n\n-- TODO:\n-- Calling a function with optional arguments\n-- Calling a function with a variable number of arguments\n-- Calling a function with named arguments\n-- Using a function in statement context\n-- Using a function in first-class context within an expression\n-- Obtaining the return value of a function\n-- Distinguishing built-in functions and user-defined functions\n-- Distinguishing subroutines and functions\n-- Stating whether arguments are passed by value or by reference\n", "language": "Haskell" }, { "code": "//The type of the function argument determines whether or not the value is passed by reference or not.\n//Eg. numbers are passed by value and lists/arrays are passed by reference.\n\nsoftware {\n\tprint() \t\t\t\t\t//Calling a function with no arguments.\n\tprint(\"Input a number!\")\t//Calling a function with fixed arguments.\n\tprint(1,2,3,4,5,6,7,8,9,0) \t//Calling a function with variable arguments.\n\tinput = read() \t\t\t\t//Obtaining the return value of a function.\n\tmyprint = print\n\tmyprint(\"It was: \", input)\t//Calling first class functions, the same as calling ordinary functions.\n\t\n\t//The only distinction that can be made between two functions is if they are 'real' or not.\n\tif type(myprint) = concept\n\t\tprint(\"myprint is a not a real function\")\n\telse if type(myprint) = function\n\t\tprint(\"myprint is a real function\")\n\tend\n\n\t//Partial functions can be created with static parts.\n\tDebugPrint = print[\"[DEBUG] \", text]\n\tDebugPrint(\"partial function!\")\t\t//This would output '[DEBUG] partial function!'\n\n\tif type(DebugPrint) = concept\n\t\tprint(\"DebugPrint is a not a real function\")\n\telse if type(DebugPrint) = function\n\t\tprint(\"DebugPrint is a real function\")\n\tend\n}\n", "language": "I" }, { "code": "procedure main() # demonstrate and describe function calling syntax and semantics\n\n # normal procedure/function calling\n\n f() # no arguments, also command context\n f(x) # fixed number of arguments\n f(x,h,w) # variable number of arguments (varargs)\n y := f(x) # Obtaining the returned value of a function\n\n # procedures as first class values and string invocation\n\n f!L # Alternate calling syntax using a list as args\n (if \\x then f else g)() # call (f or g)()\n f := write # assign a procedure\n f(\"Write is now called\") # ... and call it\n \"f\"() # string invocation, procedure\n \"-\"(1) # string invocation, operator\n\n # Co-expressions\n\n f{e1,e2} # parallel evaluation co-expression call\n # equivalent to f([create e1, create e2])\n expr @ coexp # transmission of a single value to a coexpression\n [e1,e2]@coexp # ... of multiple values (list) to a coexpression\n coexp(e1,e2) # ... same as above but only in Unicon\n\n # Other\n\n f(\"x:=\",1,\"y:=\",2) # named parameters (user defined)\nend\n", "language": "Icon" }, { "code": " verb noun\n noun verb noun\n", "language": "J" }, { "code": "f 1; 2; 3; 4; <5\n", "language": "J" }, { "code": "f 1; 2; 3; 4; 5\n", "language": "J" }, { "code": "f 'george';'tom';'howard'\n", "language": "J" }, { "code": "1 2 3 f 'george';'tom';'howard'\n", "language": "J" }, { "code": " obj=: conew'blank'\n george__obj=: 1\n tom__obj=: 2\n howard__obj=: 3\n f obj\n coerase obj\n", "language": "J" }, { "code": "f 'george';1;'tom';2;'howard';3\n", "language": "J" }, { "code": "f ('george';1),('tom';2),:(howard';3)\n", "language": "J" }, { "code": "f ('george';1);('tom';2);<howard';3\n", "language": "J" }, { "code": "1 + f 2\n", "language": "J" }, { "code": " function argumentList\n", "language": "J" }, { "code": " sum(1,2,3)\n", "language": "J" }, { "code": "f''\n", "language": "J" }, { "code": "f 'one argument'\n", "language": "J" }, { "code": "'this example has two arguments' f 'the other argument'\n", "language": "J" }, { "code": " f 1,2,3,4,5\n", "language": "J" }, { "code": "f (<1),(<2),(<3),(<4),(<5)\n", "language": "J" }, { "code": "f (<1),(<2),(<3),(<4),<5\n", "language": "J" }, { "code": "Object.methodName();\n", "language": "Java" }, { "code": "myMethod(97, 3.14)\n", "language": "Java" }, { "code": "int myMethod(int a, double b){\n // return result of doing sums with a and b\n}\n\nint myMethod(int a){\n return f(a, 1.414);\n}\n", "language": "Java" }, { "code": "System.out.println( myMethod( 97, 3.14 ) );\nSystem.out.println( myMethod( 97 ) );\n", "language": "Java" }, { "code": "void printAll(String... strings){\n for ( String s : strings )\n System.out.println( s );\n}\n", "language": "Java" }, { "code": "printAll( \"Freeman\" );\nprintAll( \"Freeman\", \"Hardy\", \"Willis\" );\n", "language": "Java" }, { "code": "int myMethod( Map<String,Object> params ){\n return\n ((Integer)params.get(\"x\")).intValue()\n + ((Integer)params.get(\"y\")).intValue();\n}\n", "language": "Java" }, { "code": "System.out.println( myMethod(new HashMap<String,Object>(){{put(\"x\",27);put(\"y\",52);}}) );\n", "language": "Java" }, { "code": "int i = myMethod(x);\n", "language": "Java" }, { "code": "myMethod(List<String> list){\n // If I change the contents of the list here, the caller will see the change\n}\n", "language": "Java" }, { "code": "Object.methodName(\"rosetta\", \"code\");\n", "language": "Java" }, { "code": "interface Example {\n int add(int valueA, int valueB);\n}\n", "language": "Java" }, { "code": "int sum(Example example) {\n return example.add(1, 2);\n}\n", "language": "Java" }, { "code": "Example example = (valueA, valueB) -> valueA + valueB;\nsum(example);\n", "language": "Java" }, { "code": "String string = Object.methodName(\"rosetta\", \"code\");\n", "language": "Java" }, { "code": "String methodA();\nvoid methodB();\n", "language": "Java" }, { "code": "<X, Y, Z> Function<Y, Z> exampleA(BiFunction<X, Y, Z> exampleB, X value) {\n return y -> exampleB.apply(value, y);\n}\n", "language": "Java" }, { "code": "myMethod()\n", "language": "Java" }, { "code": "var foo = function() { return arguments.length };\nfoo() // 0\nfoo(1, 2, 3) // 3\n", "language": "JavaScript" }, { "code": "var squares = [1, 2, 3].map(function (n) { return n * n }); // [1, 4, 9]\n", "language": "JavaScript" }, { "code": "var make_adder = function(m) {\n return function(n) { return m + n }\n};\nvar add42 = make_adder(42);\nadd42(10) // 52\n", "language": "JavaScript" }, { "code": "foo.toString()\n\"function () { return arguments.length }\"\nalert.toString()\n\"function alert() { [native code] }\"\n", "language": "JavaScript" }, { "code": "var mutate = function(victim) {\n victim[0] = null;\n victim = 42;\n};\nvar foo = [1, 2, 3];\nmutate(foo) // foo is now [null, 2, 3], not 42\n", "language": "JavaScript" }, { "code": "# Calling a function that requires no arguments:\nf() = print(\"Hello world!\")\nf()\n\n\n# Calling a function with a fixed number of arguments:\nfunction f(x, y, z)\n x*y - z^2\nend\n\nf(3, 4, 2)\n\n\n# Calling a function with optional arguments:\n# Note Julia uses multiple dispatch based on argument number and type, so\n# f() is always different from f(x) unless default arguments are used, as in:\n\npimultiple(mult=1.0) = pi * mult # so pimultiple() defaults to pi * (1.0) or pi\n\n\n# Calling a function with a variable number of arguments:\n\nf(a,b,x...) = reduce(+, 0, x) - a - b\n\n\n# here a and b are single arguments, but x is a tuple of x plus whatever follows x, so:\na = b = c = d = e = 3\nf(a,b,c) # x within the function is (c) so == 0 + c - a - b\nf(a,b,c,d,e) # x is a tuple == (c,d,e) so == (0 + c + d + e) - a - b\nf(a,b) # x is () so == 0 - a - b\n\n\n# Calling a function with named arguments:\n# Functions with keyword arguments are defined using a semicolon in the function signature,\n# as in\n# function plot(x, y; style=\"solid\", width=1, color=\"black\")\n#\n# When the function is called, the semicolon is optional, so plot here can be\n# either called with plot(x, y, width=2) or less commonly as plot(x, y; width=2).\n\n\n# Using a function in statement context:\n# Any function can be used as a variable by its name.\n\ncirclearea(x) = x^2 * pi\nmap(circlearea, [r1, r2, r3, r4])\n\n\n# Using a function in first-class context within an expression:\ncylindervolume = circlearea(r) * h\n\n\n# Obtaining the return value of a function:\nradius = 2.5\narea = circlearea(2.5)\n\n\n# Distinguishing built-in functions and user-defined functions:\n# Julia does not attempt to distinguish these in any special way,\n# but at the REPL command line there is ? help available for builtin\n# functions that would not generally be available for the user-defined ones.\n\n\n# Distinguishing subroutines and functions:\n# All subroutines are called functions in Julia, regardless of whether they return values.\n\n\n# Stating whether arguments are passed by value or by reference:\n# As in Python, all arguments are passed by pointer reference, but assignment to a passed argument\n# only changes the variable within the function. Assignment to the values referenced by the argument\n## DOES however change those values. For instance:\n\na = 3\nb = [3]\nc = [3]\n\nfunction f(x, y)\n a = 0\n b[1] = 0\n c = [0]\nend # a and c are now unchanged but b = [0]\n\n\n# Is partial application possible and how:\n# In Julia, there are many different ways to compose functions. In particular,\n# Julia has an \"arrow\" operator -> that may be used to curry other functions.\n\nf(a, b) = a^2 + a + b\nv = [4, 6, 8]\nmap(x -> f(x, 10), v) # v = [30, 52, 82]\n", "language": "Julia" }, { "code": "fun fun1() = println(\"No arguments\")\n\nfun fun2(i: Int) = println(\"One argument = $i\")\n\nfun fun3(i: Int, j: Int = 0) = println(\"One required argument = $i, one optional argument = $j\")\n\nfun fun4(vararg v: Int) = println(\"Variable number of arguments = ${v.asList()}\")\n\nfun fun5(i: Int) = i * i\n\nfun fun6(i: Int, f: (Int) -> Int) = f(i)\n\nfun fun7(i: Int): Double = i / 2.0\n\nfun fun8(x: String) = { y: String -> x + \" \" + y }\n\nfun main() {\n fun1() // no arguments\n fun2(2) // fixed number of arguments, one here\n fun3(3) // optional argument, default value used here\n fun4(4, 5, 6) // variable number of arguments\n fun3(j = 8, i = 7) // using named arguments, order unimportant\n val b = false\n if (b) fun1() else fun2(9) // statement context\n println(1 + fun6(4, ::fun5) + 3) // first class context within an expression\n println(fun5(5)) // obtaining return value\n println(kotlin.math.round(2.5)) // no distinction between built-in and user-defined functions, though former usually have a receiver\n fun1() // calling sub-routine which has a Unit return type by default\n println(fun7(11)) // calling function with a return type of Double (here explicit but can be implicit)\n println(fun8(\"Hello\")(\"world\")) // partial application isn't supported though you can do this\n}\n", "language": "Kotlin" }, { "code": "The command\n\nreplace :a0 :a1 ... an-1\n in expression containing some occurences of :ai\n by v0 v1 ... vp-1\n\nis rewritten in a prefixed parenthesized form\n\n{{lambda {:a0 :a1 ... an-1}\n expression containing some occurences of :ai}\n v0 v1 ... vp-1}\n\nso called IIFE (Immediately Invoked Function Expression), and defines an anonymous function containing a sequence of n arguments :ai, immediately invoked on a sequence of p values vi, and returning the expression in its body as so modified:\n\n1) if p < n (partial application)\n\n• the occurrences of the p first arguments are replaced in the function's body by the corresponding p given values,\n• a function waiting for missing n-p values is created,\n• and its reference is returned.\n• example:\n{{lambda {:x :y} ... :y ... :x ...} hello}\n-> {lambda {:y} ... :y ... hello ...} // replaces :x by hello\n-> LAMB_123 // the new functions's reference\n• called with the value world this function will return ... world ... hello ...\n\n2) if p = n (normal application)\n\n• the occurences of the n arguments are replaced in the function's body by the corresponding p given values,\n• the body is evaluated and the result is returned.\n• example\n{{lambda {:x :y} ... :y ... :x ...} hello world}\n-> {{lambda {:y} ... :y ... hello ...} world} // replaces :x by hello\n-> {{lambda {} ... world ... hello ...} } // replaces :y by world\n-> ... world ... hello ... // the value\n\n3) if p > n (variadicity)\n\n• the occurrences of the n-1 first arguments are replaced in the function's body by the corresponding n-1 given values,\n• the occurrences of the last argument are replaced in the body by the sequence of p-n supernumerary values,\n• the body is evaluated and the result is returned.\n• example:\n{{lambda {:x :y} ... :y ... :x ...} hello world good morning}\n-> {{lambda {:y} ... :y ... hello ...} world good morning}\n-> {{lambda {} ... world good morning ... hello ...}}\n-> ... world good morning ... hello ... // the value\n\nMore can be seen in http://lambdaway.free.fr/lambdawalks/?view=lambda\n", "language": "Lambdatalk" }, { "code": "fp.noArgs = () -> \\!\nfp.noArgs()\n\n# For user defined-functions, the argument count is not checked: If too many arguments were provided, they are ignored. If not enough arguments were provided, the last argument will be duplicated (If none was provided, VOID values will be filled in). [This process is is referred to as implict argument duplication]\nfp.noArgs(42) # No Error nor Warning\n\nfp.fixArgs = ($x, $y) -> \\!\nfp.fixArgs(1, 2)\n\nfp.fixArgs(2) # Fix args will be called with $x=2 and $y=2\nfp.fixArgs() # Fix args will be called with $x=VOID and $y=VOID\n\n# fn.argCntX (X must be replaced with 0, 1, 2, 3, 4, or 5) can be used to force the caller to provided the exact argument count\n# fn.argCntX must be called with the function to apply the constraint to and will return a new function\nfp.realFixArgs = fn.argCnt2(fp.fixArgs)\nfp.realFixArgs(1, 2)\n\nfp.realFixArgs() # Error\nfp.realFixArgs(1) # Error\nfp.realFixArgs(1, 2, 3) # Error\n\n# Arrays can be unpacked in function calls\n&values $= [1, 2]\nfp.fixArgs(&values...) # Fix args will be called with $x=1 and $y=2\n\n\n# In Lang there are text and array varags parameters\nfp.varArgsText = ($text...) -> \\!\nfp.varArgsText(1) # Var args text will be called with \"1\"\nfp.varArgsText(1, 2) # Var args text will be called with \"1, 2\"\nfp.varArgsText(1,2) # Var args text will be called with \"1,2\"\nfp.varArgsText(1,text ,3) # Var args text will be called with \"1,text ,3\"\n\nfp.varArgsArray = (&args...) -> \\!\nfp.varArgsArray(1) # Var args array will be called with [1]\nfp.varArgsArray(1, 2) # Var args array will be called with [1, 2]\nfp.varArgsArray(1,2) # Var args array will be called with [1, 2]\nfp.varArgsArray(1,text ,3) # Var args array will be called with [1, text, 3]\n\n# Functions with named arguments can not be created\n\n# Using a function in a statement context\n$x = fp.fixArgs(1, 2)\n\n# Functions (Even predefined and linker functions) can be used as values\nfp.retAFunc = () -> {\n\treturn ($x) -> \\!\n}\nfp.func = fp.retAFunc()\nfp.func(2)\n\n# Multiple call-expressions can be used directly\nfp.retAFunc()(2)\n\nfp.retAFunc = () -> return fn.println\nfp.retAFunc()(test, values)\n\nfp.retAFunc = () -> return ln.loadModule\nfp.retAFunc()(x.lm) # Error, because file not found\n\n# The return value or the thrown error can be obtained with the assignment operator\nfp.inc2 = ($x) -> return parser.op($x + 2)\n$ret = fp.inc2(40) # $ret is 42\n\n# Built-in (They are called predefined functions in Lang) start with the \"func.\" or \"fn.\" prefix wheras user-defined functions start with \"fp.\"\n# Linker functions start with \"linker.\" or \"ln.\"\n# Predefined and linker functions can be stored in a user-defined function\nfp.userDefinedFunc = fn.println\nfp.userDefinedFunc(Called println)\n\n# In Lang there are no subroutines\n\n# In Lang functions can have call-by-pointer values\n# $ptr is a pointer to the called value\nfp.callByPtr = ($[ptr]) -> \\!\nfp.callByPtr(42) # This will create a pointer to an anonymous value, therefor it can not be changed\n\nfp.inc2 = ($[ptr]) -> $*ptr += 2\nfp.inc2(40) # Error\n$val = 40\nfp.inc2($val) # $val is now 42\n\n# Functions can also be called with pointers directly\nfp.inc2 = ($ptr) -> $*ptr += 2\nfp.inc2(40) # Multiple Errors (Value will be dereferenced as NULL -> + is not defined for NULL and INT AND anonymous values can not be changed)\n\n$val = 40\nfp.inc2($[val]) # $val is now 42\n\n# Partial apllication of functions is possible by using combinator functions\n# The simplest combinator function-family is the A combinator family (Other families change the order of arguments, can call multiple function, ...)\nfp.partialAdd = fn.combA2(fn.add) # When all arguments for fn.combA2(a, b, c) are provided, the execution of a(b, c) will begin\nfp.add42 = fp.partialAdd(42) # Creates a function which still needs 1 argument\nfp.add42(2) # Will return 44\n\n# Without the use of fn.argCntX 0 args can also be provied\nfp.add42()()()(2) # Will also return 44\n", "language": "Lang" }, { "code": "# The function argument auto un-pack operator (▲ or +|) can be used to create a function which must be called with an array value that is automatically unpacked\nfp.fixArgs = ($x, $y) -> \\!\nfp.unpackingFixArgs $= +|fp.fixArgs\nfp.unpackingFixArgs(&values) # Fix args will be called with $x=1 and $y=2\n\n# The function argument auto pack operator (▼ or -|) can be used to cerate a function wich must be called with varargs and will call the original function with a single array argument\nfp.arrayArg = (&arr) -> \\!\nfp.packingArrayArg $= -|fp.arrayArg\nfp.packingArrayArg(1, 2) # Array arg will be called with [1, 2]\n\n# Functions can also be called with the pipe operators (|, >>, and >>>)\n# The \"|\" and \">>\" pipe operators are identical apart from the operator precedence\n# The \">>>\" pipe operator automatically unpacks array values\nfp.func = ($x) -> \\!\nparser.op(42 | fp.func) # fp.func is called with 42\nparser.op(42 >> fp.func) # fp.func is called with 42\nparser.op([42] >>> fp.func) # fp.func is called with 42\n\n# Function calls can be concatinated with the concat operator (|||)\nfp.incAndPrint $= fn.inc ||| fn.println # Calling fp.incAndPrint($x) has the same effect as calling fn.println(fn.inc($x))\nfp.incAndPrint(2) # Prints 3\n\n# The pow operator can be used to call a function multiple times in succession\n# This works only with exponents >= 0 (If the exponent is 0 a function will be returned, that always returns VOID)\nfp.voidFunc $= fn.inc ** 0\nfp.voidFunc(2) # Returns VOID\n\nfn.pow(fn.inc, 1)(2) # Returns 3\nfn.pow(fn.inc, 2)(2) # Returns 4\nfn.pow(fn.inc, 3)(2) # Returns 5\nfn.pow(fn.inc, 10)(2) # Returns 12\n", "language": "Lang" }, { "code": ".x()\n# call user-defined function\n", "language": "Langur" }, { "code": "write(.key, \": \", .value)\n# call built-in with parentheses\n", "language": "Langur" }, { "code": "write .key, \": \", .value\n# call built-in with unbounded list\n", "language": "Langur" }, { "code": "writeln \"numbers: \", join \", \", [.a1, .a2, .a3, .a4]\n# unbounded lists on writeln and join\n# later function join takes remaining arguments\n", "language": "Langur" }, { "code": "writeln \"numbers: \", join(\", \", [.a1, .a2, .a3, .a4]), \" === \"\n# unbounded list on writeln\n# join using parentheses so it doesn't take remaining arguments\n", "language": "Langur" }, { "code": "val .sum = foldfrom(\n fn(.sum, .i, .c) .sum + number(.c, 36) * .weight[.i],\n 0,\n pseries len .code,\n split .code,\n)\n# split, pseries, and len using unbounded lists, ending before comma preceding line return\n", "language": "Langur" }, { "code": "for .key in sort(keys .tests) {\n ...\n}\n# unbounded list on keys bounded by closing parenthesis of sort\n", "language": "Langur" }, { "code": "foo (1, 2, 3). ; (1) Ordinary call\nfoo (). ; (2) No arguments\nfoo. ; (3) Equivalent to (2)\nfoo (1). ; (4) Single-argument function\nfoo 1. ; (5) Equivalent to (4)\nfoo (bar). ; (6) Parentheses necessary here since bar is not a literal\nfoo: 1, 2, 3. ; (7) Alternative syntax, equivalent to (1)\n", "language": "Latitude" }, { "code": "myProc := proc { foo. }.\nmyProc call (1, 2, 3).\n", "language": "Latitude" }, { "code": "myProc1 := #'foo shield.\nmyProc2 := proc { foo. }.\nmyProc3 := proc { foo. } shield.\n", "language": "Latitude" }, { "code": "(defun my-func()\n (: io format '\"I get called with NOTHING!~n\"))\n", "language": "LFE" }, { "code": "> (my-func)\nI get called with NOTHING!\nok\n", "language": "LFE" }, { "code": "(defun my-func(a b)\n (: io format '\"I got called with ~p and ~p~n\" (list a b)))\n", "language": "LFE" }, { "code": "> (my-func '\"bread\" '\"cheese\")\nI got called with \"bread\" and \"cheese\"\nok\n", "language": "LFE" }, { "code": "(defmodule args\n (export all))\n\n(defun my-func ()\n (my-func () () ()))\n\n(defun my-func (a)\n (my-func a () ()))\n\n(defun my-func (a b)\n (my-func a b ()))\n\n(defun my-func (a b c)\n (: io format '\"~p ~p ~p~n\" (list a b c)))\n", "language": "LFE" }, { "code": "> (slurp '\"args.lfe\")\n#(ok args)\n> (my-func)\n[] [] []\nok\n> (my-func '\"apple\")\n\"apple\" [] []\nok\n> (my-func '\"apple\" '\"banana\")\n\"apple\" \"banana\" []\nok\n> (my-func '\"apple\" '\"banana\" '\"cranberry\")\n\"apple\" \"banana\" \"cranberry\"\nok\n> (my-func '\"apple\" '\"banana\" '\"cranberry\" '\"bad arg\")\nexception error: #(unbound_func #(my-func 4))\n", "language": "LFE" }, { "code": "...\n (cond ((== count limit) (hit-limit-func arg-1 arg-2))\n ((/= count limit) (keep-going-func count)))\n ...\n", "language": "LFE" }, { "code": "> (>= 0.5 (: math sin 0.5))\ntrue\n", "language": "LFE" }, { "code": "(let ((x (: math sin 0.5)))\n ...)\n", "language": "LFE" }, { "code": "'Call a function - Liberty BASIC\n\n'First, function result could not be discarded\n' that is, you cannot do \"f(x)\" as a separate statement\n\n'Calling a function that requires no arguments\nres = f() 'brackets required\n\n'Calling a function with a fixed number of arguments\nres = g(x)\nres = h(x,y)\n'Calling a function with optional arguments\n 'impossible for user-defined functions\n 'Some build-in functions ex. INSTR and MID$ could be called with last argument omitted\n'Calling a function with a variable number of arguments\n 'impossible\n'Calling a function with named arguments\n 'impossible\n'Using a function in statement context\n 'impossible (see starting notice)\n'Using a function in first-class context within an expression\n 'impossible\n'Obtaining the return value of a function\nres = g(x)\n'Distinguishing built-in functions and user-defined functions\n 'I would say impossible. Though built-in functions could be EVAL'ed,\n 'while user-defined would not be called (tries address array instead).\n 'Still cannot distinguish user-defined function from array.\n'Distinguishing subroutines and functions\n 'then defined, subroutines and functions defined with words\n 'SUB and FUNCTION (case incensitive)\n 'Then used, function used as expression (with return value),\n res = g(x)\n 'while subroutines called with special keyword CALL and without brackets\n call test x, y\n'Stating whether arguments are passed by value or by reference\n 'Variables passed as arguments into functions and subs are passed \"by value\" by default\n 'parameters could be passed \"by reference\" if formal parameter in sub/function definition uses the \"byref\" specifier\n 'Then calling a function, you can prevent pass by reference by changing variable to expression\n ' like x+0, x$+\"\" or just (x), (x$)\n'Is partial application possible and how\n 'impossible\n", "language": "Liberty-BASIC" }, { "code": "foo()\n-- or alternatively:\ncall(#foo, _movie)\n", "language": "Lingo" }, { "code": "on getAllUserFunctions ()\n res = []\n repeat with i = 1 to _movie.castlib.count\n c = _movie.castlib(i)\n repeat with j = 1 to c.member.count\n m = c.member[j]\n if m.type<>#script then next repeat\n if m.scripttype=#movie then\n functions = m.script.handlers()\n repeat with f in functions\n res.append(f)\n end repeat\n end if\n end repeat\n end repeat\n return res\nend\n", "language": "Lingo" }, { "code": "put getAllUserFunctions()\n-- [#sum, #double, #getAllUserFunctions]\n", "language": "Lingo" }, { "code": "on double (someList)\n cnt = someList.count\n repeat with i = 1 to cnt\n someList[i] = someList[i] * 2\n end repeat\nend\n", "language": "Lingo" }, { "code": "l = [1,2,3]\ndouble(l)\nput l\n-- [2, 4, 6]\n\nl = [1,2,3]\ndouble(l.duplicate())\nput l\n-- [1, 2, 3]\n", "language": "Lingo" }, { "code": "foo(1,2,3)\n-- or alternatively:\ncall(#foo, _movie, 1, 2, 3)\n", "language": "Lingo" }, { "code": "on foo (a, b)\n if voidP(b) then b = 1\n return a * b\nend\n", "language": "Lingo" }, { "code": "put foo(23, 2)\n-- 46\nput foo(23)\n-- 23\n", "language": "Lingo" }, { "code": "on sum ()\n res = 0\n repeat with i = 1 to the paramCount\n res = res + param(i)\n end repeat\n return res\nend\n", "language": "Lingo" }, { "code": "put sum (1,2,3)\n-- 6\n", "language": "Lingo" }, { "code": "----------------------------------------\n-- One of the five native iterative methods defined in ECMAScript 5\n-- @param {list} tList\n-- @param {symbol} cbFunc\n-- @param {object} [cbObj=_movie]\n-- @return {list}\n----------------------------------------\non map (tList, cbFunc, cbObj)\n if voidP(cbObj) then cbObj = _movie\n res = []\n cnt = tList.count\n repeat with i = 1 to cnt\n res[i] = call(cbFunc, cbObj, tList[i], i, tList)\n end repeat\n return res\nend\n\non doubleInt (n)\n return n*2\nend\n", "language": "Lingo" }, { "code": "l = [1,2,3]\nput map(l, #doubleInt)\n-- [2, 4, 6]\n", "language": "Lingo" }, { "code": "x = foo(1,2)\n", "language": "Lingo" }, { "code": "// Calling a function that requires no arguments\nvoid foo() {puts(\"Calling a function with no arguments\");}\nfoo();\n\n// Calling a function with a fixed number of arguments\nabs(-36);\n\n// Calling a function with optional arguments\nputs(nonewline: \"nonewline is an optional argument\");\nputs(\"\\n\");\n\n// Calling a function with a variable number of arguments\nvoid var_arg_func(...args) {\n puts(length(args));\n}\nvar_arg_func(1, 2);\nvar_arg_func(1, 2, 3);\n\n// Obtaining the return value of a function\nint s = clock(\"seconds\"); //current time in seconds\n// Calling a function with named arguments\n// format is a named argument in Clock_format\nint str = Clock_format(s, format: \"%B\");\nputs(str);\n\n// Stating whether arguments are passed by value or by reference\nvoid f(int a, int &b) { a++; b++; }\n{\nint a = 0;\nint b = 0;\n\nf(a, &b);\nputs (a);\nputs (b);\n}\n", "language": "Little" }, { "code": "-- Lua functions accept any number of arguments; missing arguments are nil-padded, extras are dropped.\nfunction fixed (a, b, c) print(a, b, c) end\nfixed() --> nil nil nil\nfixed(1, 2, 3, 4, 5) --> 1 2 3\n\n-- True vararg functions include a trailing ... parameter, which captures all additional arguments as a group of values.\nfunction vararg (...) print(...) end\nvararg(1, 2, 3, 4, 5) -- 1 2 3 4 5\n\n-- Lua also allows dropping the parentheses if table or string literals are used as the sole argument\nprint \"some string\"\nprint { foo = \"bar\" } -- also serves as a form of named arguments\n\n-- First-class functions in expression context\nprint((\"this is backwards uppercase\"):gsub(\"%w+\", function (s) return s:upper():reverse() end))\n\n-- Functions can return multiple values (including none), which can be counted via select()\nlocal iter, obj, start = ipairs { 1, 2, 3 }\nprint(select(\"#\", (function () end)())) --> 0\nprint(select(\"#\", unpack { 1, 2, 3, 4 })) --> 4\n\n-- Partial application\nfunction prefix (pre)\n return function (suf) return pre .. suf end\nend\n\nlocal prefixed = prefix \"foo\"\nprint(prefixed \"bar\", prefixed \"baz\", prefixed \"quux\")\n\n-- nil, booleans, and numbers are always passed by value. Everything else is always passed by reference.\n-- There is no separate notion of subroutines\n-- Built-in functions are not easily distinguishable from user-defined functions\n", "language": "Lua" }, { "code": "/* Calling a function that requires no arguments */\nf();;\n\n/* Calling a function with a fixed number of arguments */\nf(1,2);;\n\n/* Calling a function with optional arguments\n Note: defining the function is cumbersome but will get easier in future versions. */\nf(1,2,new {default with x=3, y=4});;\n\n/* Calling a function with a variable number of arguments */\nprintf(\"%d %d %d %d\":char*,2,3,4,5);;\n\n/* Calling a function with named arguments\n Note: may get syntax sugar in future versions */\nf(1,2,new {default with x=3, y=4});;\n\n/* Using a function in statement context (what?) */\nf();f();f();;\n\n/* Using a function in first-class context within an expression */\n[1,2,3].map(string);;\n\n/* Obtaining the return value of a function */\nlet x:int = f();;\n\n/* Distinguishing built-in functions and user-defined functions */\n/* Builtin function i.e. custom calling convention: */\n(@ binop \"==\" l r);;\n/* User defined function i.e. normal function */\nf(l)(r);;\n\n/* Distinguishing subroutines and functions: both are supported, but compiler is not aware of difference */\nsub();;\nfun();;\n\n/* Stating whether arguments are passed by value or by reference */\nf(value);; /* by value */\nf(&value);; /* by pointer reference */\nf(ref(value));; /* by managed reference */\n\n/* Is partial application possible and how */\ntasty_curry(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)(q)(r)(s)(t)(u)(v)(w)(x)(y)(z);;\n", "language": "Luck" }, { "code": " f()\n", "language": "Maple" }, { "code": "f(1,sin(x), g -> int(g(t),t=0..1)\n", "language": "Maple" }, { "code": "f(1, sin(x), g -> int(g(t),t=0..1)\n", "language": "Maple" }, { "code": "f(1, sin(x), g -> int(g(t),t=0..1)\n", "language": "Maple" }, { "code": "f(a,b,method = foo)\n", "language": "Maple" }, { "code": "f(a); f(b);\n", "language": "Maple" }, { "code": "f(a) + g(b)\n", "language": "Maple" }, { "code": " x := f(1)\n", "language": "Maple" }, { "code": "> type( op, 'builtin' );\n true\n", "language": "Maple" }, { "code": "f[]\n", "language": "Mathematica" }, { "code": "f[1,2]\n", "language": "Mathematica" }, { "code": "f[1,Option1->True]\n", "language": "Mathematica" }, { "code": "f[1,Option1->True]\nf[1,Option1->True,Option2->False]\n", "language": "Mathematica" }, { "code": "f[Option1->True,Option2->False]\n", "language": "Mathematica" }, { "code": "f[1,2];f[2,3]\n", "language": "Mathematica" }, { "code": "(#^2)&[3];\n", "language": "Mathematica" }, { "code": " % Calling a function that requires no arguments\n function a=foo();\n a=4;\n end;\n x = foo();\n % Calling a function with a fixed number of arguments\n function foo(a,b,c);\n %% function definition;\n end;\n foo(x,y,z);\n % Calling a function with optional arguments\n function foo(a,b,c);\n\tif nargin<2, b=0; end;\n\tif nargin<3, c=0; end;\n %% function definition;\n end;\n foo(x,y);\n % Calling a function with a variable number of arguments\n function foo(varargin);\n\t for k=1:length(varargin)\n arg{k} = varargin{k};\t\n end;\n foo(x,y);\n % Calling a function with named arguments\n\t%% does not apply\n % Using a function in statement context\n\t%% does not apply\n % Using a function in first-class context within an expression\n % Obtaining the return value of a function\n function [a,b]=foo();\n a=4;\n b='result string';\n end;\n [x,y] = foo();\n % Distinguishing built-in functions and user-defined functions\n\tfun = 'foo';\t\n\tif (exist(fun,'builtin'))\n \t\tprintf('function %s is a builtin\\n');\n elseif (exist(fun,'file'))\n \t\tprintf('function %s is user-defined\\n');\n elseif (exist(fun,'var'))\n \t\tprintf('function %s is a variable\\n');\n else\n \t\tprintf('%s is not a function or variable.\\n');\n end\n % Distinguishing subroutines and functions\n % there are only scripts and functions, any function declaration starts with the keyword function, otherwise it is a script that runs in the workspace\n % Stating whether arguments are passed by value or by reference\n % arguments are passed by value, however Matlab has delayed evaluation, such that a copy of large data structures are done only when an element is written to.\n", "language": "MATLAB" }, { "code": "// function with no arguments\nno_args()\n\n// function with fixed amount of arguments\nthree_args(a, b, c)\n\n// nanoquery does not support optional, variable, or named arguments\n\n// obtaining a return value\nvalue = returns_value()\n\n// checking if a function called \"func\" is user-defined\ntry\n type(func)\n println \"func is user-defined\"\ncatch\n println \"func is a built-in or doesn't exist\"\nend\n", "language": "Nanoquery" }, { "code": "// no arguments\nf()\n\n// fixed arguments\ndef f(a, b) { ... } // as an aside, functions defined with 'def' use type inference for parameters and return types\nf(1, 'a')\n\n// optional arguments\ndef f(a, b = 0) { ... }\nf(\"hello\")\nf(\"goodbye\", 2)\nf(\"hey\", b = 2) // using the name makes more sense if there's more than one optional argument, obviously\n\n// variable number of arguments\ndef f(params args) { ... }\ndef g(a, b, params rest) { ... }\nf(1, 2, 3) // arguments should all have the same type or may be coerced to a supertype\ng(1.0, 2, \"a\", \"hello\")\n\n// named arguments\nf(a = 'a', b = 0)\nf(b = 0, a = 'a')\nf('a', b = 0) // if mixing named and unnamed args, unnamed must be first and in correct order\n\n// statement context\nif (f(foo) == 42)\n WriteLine($\"$foo is the meaning to life, the universe and everything.\")\nelse WriteLine($\"$foo is meaningless.\")\n\n// first class function in an expression\ndef a = numList.FoldLeft(f)\n\n// obtaining return value\ndef a = f(3)\n\n// distinguishing built-in from user functions\n// N/A?\n\n// distinguishing subroutines from functions\n// N/A\n\n// stating whether passed by value or by reference\n// .NET distinguishes between value types and reference types; if a reference type is passed by reference (using ref or out),\n// the reference is passed by reference, which would allow a method to modify the object to which the reference refers\ndef f(a, ref b) { ... }\nmutable someVar = \"hey there\" // doesn't make sense to pass immutable value by ref\nf(2, ref someVar)\ndef g(a, out b) { ... }\nmutable someOtherVar // if passed by ref using 'out', the variable needn't be initialized\ng(2, out someOtherVar)\n\n// partial application\ndef f(a, b) { ... }\ndef g = f(2, _)\ndef h = f(_, 2)\ndef a = g(3) // equivalent to: def a = f(2, 3)\ndef b = h(3) // equivalent to: def b = f(3, 2)\n", "language": "Nemerle" }, { "code": "proc no_args() =\n discard\n# call\nno_args()\n\nproc fixed_args(x, y) =\n echo x\n echo y\n# calls\nfixed_args(1, 2) # x=1, y=2\nfixed_args 1, 2 # same call\n1.fixed_args(2) # same call\n\n\nproc opt_args(x=1.0) =\n echo x\n# calls\nopt_args() # 1\nopt_args(3.141) # 3.141\n\nproc var_args(v: varargs[string, `$`]) =\n for x in v: echo x\n# calls\nvar_args(1, 2, 3) # (1, 2, 3)\nvar_args(1, (2,3)) # (1, (2, 3))\nvar_args() # ()\n\n## Named arguments\nfixed_args(y=2, x=1) # x=1, y=2\n\n## As a statement\nif true:\n no_args()\n\nproc return_something(x): int =\n x + 1\n\nvar a = return_something(2)\n\n## First-class within an expression\nlet x = return_something(19) + 10\nlet y = 19.return_something() + 10\nlet z = 19.return_something + 10\n", "language": "Nim" }, { "code": "f ()\n", "language": "OCaml" }, { "code": "f 1 2 3\n", "language": "OCaml" }, { "code": "val f : ?a:int -> int -> unit\n", "language": "OCaml" }, { "code": "f 10\nf ~a:6 10\n", "language": "OCaml" }, { "code": "g ()\ng ~b:1.0 ()\n", "language": "OCaml" }, { "code": "f ~arg:3\n", "language": "OCaml" }, { "code": "let arg = 3 in\nf ~arg\n", "language": "OCaml" }, { "code": "(* TODO *)\n", "language": "OCaml" }, { "code": "let ret = f ()\nlet a, b, c = f () (* if there are several returned values given as a tuple *)\nlet _ = f () (* if we want to ignore the returned value *)\nlet v, _ = f () (* if we want to ignore one of the returned value *)\n", "language": "OCaml" }, { "code": "a b c f\n", "language": "Oforth" }, { "code": "f(a, b, c)\n", "language": "Oforth" }, { "code": "a b c f\na b f(c)\na f(b, c)\nf(a, b, c)\n", "language": "Oforth" }, { "code": "a b c r m\n", "language": "Oforth" }, { "code": "r m(a, b, c)\n", "language": "Oforth" }, { "code": "; note: sign \"==>\" indicates expected output\n\n;;; Calling a function that requires no arguments\n(define (no-args-function)\n (print \"ok.\"))\n\n(no-args-function)\n; ==> ok.\n\n\n;;; Calling a function with a fixed number of arguments\n(define (two-args-function a b)\n (print \"a: \" a)\n (print \"b: \" b))\n\n(two-args-function 8 13)\n; ==> a: 8\n; ==> b: 13\n\n\n;;; Calling a function with optional arguments\n(define (optional-args-function a . args)\n (print \"a: \" a)\n (if (null? args)\n (print \"no optional arguments\"))\n (if (less? 0 (length args))\n (print \"b: \" (car args)))\n (if (less? 1 (length args))\n (print \"c: \" (cadr args)))\n ; etc...\n)\n\n(optional-args-function 3)\n; ==> a: 3\n; ==> no optional arguments\n(optional-args-function 3 8)\n; ==> a: 3\n; ==> b: 8\n(optional-args-function 3 8 13)\n; ==> a: 3\n; ==> b: 8\n; ==> c: 13\n(optional-args-function 3 8 13 77)\n; ==> a: 3\n; ==> b: 8\n; ==> c: 13\n\n\n;;; Calling a function with a variable number of arguments\n; /same as optional arguments\n\n\n;;; Calling a function with named arguments\n; /no named arguments \"from the box\" is provided, but it can be easily simulated using builtin associative arrays (named \"ff\")\n(define (named-args-function args)\n (print \"a: \" (get args 'a 8)) ; 8 is default value if no variable value given\n (print \"b: \" (get args 'b 13)); same as above\n)\n\n(named-args-function #empty)\n; ==> a: 8\n; ==> b: 13\n(named-args-function (list->ff '((a . 3))))\n; ==> a: 3\n; ==> b: 13\n; or nicer (and shorter) form available from ol version 2.1\n(named-args-function '{a 3})\n; ==> a: 3\n; ==> b: 13\n(named-args-function '{b 7})\n; ==> a: 8\n; ==> b: 7\n(named-args-function '{a 3 b 7})\n; ==> a: 3\n; ==> b: 7\n\n\n;;; Using a function in first-class context within an expression\n(define (first-class-arg-function arg a b)\n (print (arg a b))\n)\n\n(first-class-arg-function + 2 3)\n; ==> 5\n(first-class-arg-function - 2 3)\n; ==> -1\n\n;;; Using a function in statement context\n(let ((function (lambda (x) (* x x))))\n (print (function 4))\n; ==> 16\n;(print (function 4))\n; ==> What is 'function'?\n\n;;; Obtaining the return value of a function\n(define (return-value-function)\n (print \"ok.\")\n 123)\n\n(let ((result (return-value-function)))\n (print result))\n; ==> ok.\n; ==> 123\n\n;;; Obtaining the return value of a function while breaking the function execution (for example infinite loop)\n(print\n (call/cc (lambda (return)\n (let loop ((n 0))\n (if (eq? n 100)\n (return (* n n)))\n (loop (+ n 1))))))) ; this is infinite loop\n; ==> 10000\n\n\n;;; Is partial application possible and how\n(define (make-partial-function n)\n (lambda (x y)\n (print (n x y)))\n)\n\n(define plus (make-partial-function +))\n(define minus (make-partial-function -))\n\n(plus 2 3)\n; ==> 5\n(minus 2 3)\n; ==> -1\n\n;;; Distinguishing built-in functions and user-defined functions\n; ol has no builtin functions but only eight builtin forms: quote, values, lambda, setq, letq, ifeq, either, values-apply.\n; all other functions is \"user-defined\", and some of them defined in base library, for example (scheme core) defines if, or, and, zero?, length, append...\n\n;;; Distinguishing subroutines and functions\n; Both subroutines and functions is a functions in Ol.\n; Btw, the \"subroutine\" has a different meaning in Ol - the special function that executes simultaneously in own context. The intersubroutine messaging mechanism is provided, sure.\n\n;;; Stating whether arguments are passed by value or by reference\n; The values in Ol always passed as values and objects always passed as references. If you want to pass an object copy - make a copy by yourself.\n", "language": "Ol" }, { "code": "say 'DATE'()\nSay date()\nExit\ndaTe: Return 'my date'\n", "language": "OoRexx" }, { "code": "f(); \\\\ zero arguments\nsin(Pi/2); \\\\ fixed number of arguments\nvecsort([5,6]) != vecsort([5,6],,4) \\\\ optional arguments\nStr(\"gg\", 1, \"hh\") \\\\ variable number of arguments\ncall(Str, [\"gg\", 1, \"hh\"]) \\\\ variable number of arguments in a vector\n(x->x^2)(3); \\\\ first-class\nx = sin(0); \\\\ get function value\n", "language": "PARI-GP" }, { "code": "foo\n", "language": "Pascal" }, { "code": "foo(1, 'abc', true)\n", "language": "Pascal" }, { "code": "foo(); # Call foo on the null list\n&foo(); # Ditto\nfoo($arg1, $arg2); # Call foo on $arg1 and $arg2\n&foo($arg1, $arg2); # Ditto; ignores prototypes\n", "language": "Perl" }, { "code": "foo;\n", "language": "Perl" }, { "code": "&foo;\n", "language": "Perl" }, { "code": "goto &foo;\n", "language": "Perl" }, { "code": "&$fooref('foo', 'bar');\n&{$fooref}('foo', 'bar');\n$fooref->('foo', 'bar');\n", "language": "Perl" }, { "code": "-->\n <span style=\"color: #0000FF;\">{<span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">myfunction<span style=\"color: #0000FF;\">(<span style=\"color: #0000FF;\">)\n<!--\n", "language": "Phix" }, { "code": "-->\n <span style=\"color: #0000FF;\">{<span style=\"color: #000000;\">cities<span style=\"color: #0000FF;\">,<span style=\"color: #000000;\">populations<span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">columnize<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">muncipalities<span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">{<span style=\"color: #0000FF;\">{<span style=\"color: #0000FF;\">}<span style=\"color: #0000FF;\">,<span style=\"color: #000000;\">populations<span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">columnize<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">muncipalities<span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- discard result[1]</span>\n <span style=\"color: #0000FF;\">{<span style=\"color: #000000;\">cities<span style=\"color: #0000FF;\">,<span style=\"color: #0000FF;\">{<span style=\"color: #0000FF;\">}<span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">columnize<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">muncipalities<span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- discard result[2]</span>\n <span style=\"color: #0000FF;\">{<span style=\"color: #000000;\">cities<span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">columnize<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">muncipalities<span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- \"\"\n<!--\n", "language": "Phix" }, { "code": "-->\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">myfunction<span style=\"color: #0000FF;\">(<span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">a<span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">b<span style=\"color: #0000FF;\">=<span style=\"color: #008000;\">\"default\"<span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{<span style=\"color: #000000;\">a<span style=\"color: #0000FF;\">,<span style=\"color: #000000;\">b<span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #000080;font-style:italic;\">--? myfunction() -- illegal, compile-time error</span>\n <span style=\"color: #0000FF;\">?<span style=\"color: #000000;\">myfunction<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">1<span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- displays {1,\"default\"}</span>\n <span style=\"color: #0000FF;\">?<span style=\"color: #000000;\">myfunction<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">2<span style=\"color: #0000FF;\">,<span style=\"color: #008000;\">\"that\"<span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- displays {2,\"that\"}\n<!--\n", "language": "Phix" }, { "code": "-->\n <span style=\"color: #0000FF;\">?<span style=\"color: #000000;\">myfunction<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">b<span style=\"color: #0000FF;\">:=<span style=\"color: #008000;\">\"then\"<span style=\"color: #0000FF;\">,<span style=\"color: #000000;\">a<span style=\"color: #0000FF;\">:=<span style=\"color: #000000;\">3<span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- displays {3,\"then\"}\n --?myfunction(b:=\"though\") -- compile-time error\n<!--\n", "language": "Phix" }, { "code": "-->\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">r_myfunction</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">routine_id<span style=\"color: #0000FF;\">(<span style=\"color: #008000;\">\"myfunction\"<span style=\"color: #0000FF;\">)<span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">first_class</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">myfunction</span>\n <span style=\"color: #0000FF;\">?<span style=\"color: #7060A8;\">call_func<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">r_myfunction<span style=\"color: #0000FF;\">,<span style=\"color: #0000FF;\">{<span style=\"color: #000000;\">1<span style=\"color: #0000FF;\">}<span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- displays {1,\"default\"}</span>\n <span style=\"color: #0000FF;\">?<span style=\"color: #7060A8;\">call_func<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">myfunction<span style=\"color: #0000FF;\">,<span style=\"color: #0000FF;\">{<span style=\"color: #000000;\">1<span style=\"color: #0000FF;\">}<span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- \"\"</span>\n <span style=\"color: #0000FF;\">?<span style=\"color: #7060A8;\">call_func<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">first_class<span style=\"color: #0000FF;\">,<span style=\"color: #0000FF;\">{<span style=\"color: #000000;\">1<span style=\"color: #0000FF;\">}<span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- \"\"</span>\n <span style=\"color: #0000FF;\">?<span style=\"color: #000000;\">first_class<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">1<span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- \"\"\n<!--\n", "language": "Phix" }, { "code": "-->\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">s<span style=\"color: #0000FF;\">,<span style=\"color: #000000;\">item<span style=\"color: #0000FF;\">)\n<!--\n", "language": "Phix" }, { "code": "/# Phixmonti does not distinguish between subroutines and functions.\n Each word (as they are called), takes its arguments (if any) from the data stack. #/\n\ndef saludo\n\t\"Hola mundo\" print nl\nenddef\n\nsaludo /# 'saludo' is a user-defined word. #/\n\n2 3 + print /# The '+' sign and 'print' are intrinsic words. The return value is deposited on the data stack #/\n", "language": "Phixmonti" }, { "code": "(foo)\n(bar 1 'arg 2 'mumble)\n", "language": "PicoLisp" }, { "code": "(mapc println Lst) # The value of 'printlin' is a number\n(apply '((A B C) (foo (+ A (* B C)))) (3 5 7)) # A list is passed\n", "language": "PicoLisp" }, { "code": "(setq A (+ 3 4) B (* 3 4))\n", "language": "PicoLisp" }, { "code": "Procedure Saludo()\n PrintN(\"Hola mundo!\")\nEndProcedure\n\nProcedure.s Copialo(txt.s, siNo.b, final.s = \"\")\n Define nuevaCadena.s, resul.s\n\n For cont.b = 1 To siNo\n nuevaCadena + txt\n Next\n\n Resul = Trim(nuevaCadena) + final\n\n ProcedureReturn resul\nEndProcedure\n\nProcedure testNumeros(a.i, b.i, c.i = 0)\n PrintN(Str(a) + #TAB$ + Str(b) + #TAB$ + Str(c))\nEndProcedure\n\nProcedure testCadenas(txt.s)\n For cont.b = 1 To Len(txt)\n Print(Mid(txt,cont,1))\n Next cont\nEndProcedure\n\nOpenConsole()\nSaludo()\nPrintN(Copialo(\"Saludos \", 6))\nPrintN(Copialo(\"Saludos \", 3, \"!!\"))\nPrintN(\"\")\ntestNumeros(1, 2, 3)\ntestNumeros(1, 2)\nPrintN(\"\")\ntestCadenas(\"1, 2, 3, 4, cadena, 6, 7, 8, \\'incluye texto\\'\")\n\nInput()\nCloseConsole()\n", "language": "PureBasic" }, { "code": "def no_args():\n pass\n# call\nno_args()\n\ndef fixed_args(x, y):\n print('x=%r, y=%r' % (x, y))\n# call\nfixed_args(1, 2) # x=1, y=2\n\n## Can also called them using the parameter names, in either order:\nfixed_args(y=2, x=1)\n\n## Can also \"apply\" fixed_args() to a sequence:\nmyargs=(1,2) # tuple\nfixed_args(*myargs)\n\ndef opt_args(x=1):\n print(x)\n# calls\nopt_args() # 1\nopt_args(3.141) # 3.141\n\ndef var_args(*v):\n print(v)\n# calls\t\nvar_args(1, 2, 3) # (1, 2, 3)\nvar_args(1, (2,3)) # (1, (2, 3))\nvar_args() # ()\n\n## Named arguments\nfixed_args(y=2, x=1) # x=1, y=2\n\n## As a statement\nif 1:\n no_args()\n\n## First-class within an expression\nassert no_args() is None\n\ndef return_something():\n return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n# calls\nis_builtin(pow) # True\nis_builtin(is_builtin) # False\n\n# Very liberal function definition\n\ndef takes_anything(*args, **kwargs):\n for each in args:\n print(each)\n for key, value in sorted(kwargs.items()):\n print(\"%s:%s\" % (key, value))\n # Passing those to another, wrapped, function:\n wrapped_fn(*args, **kwargs)\n # (Function being wrapped can have any parameter list\n # ... that doesn't have to match this prototype)\n\n## A subroutine is merely a function that has no explicit\n## return statement and will return None.\n\n## Python uses \"Call by Object Reference\".\n## See, for example, http://www.python-course.eu/passing_arguments.php\n\n## For partial function application see:\n## http://rosettacode.org/wiki/Partial_function_application#Python\n", "language": "Python" }, { "code": "FUNCTION Copialo$ (txt$, siNo, final$)\n DIM nuevaCadena$\n\n FOR cont = 1 TO siNo\n\tnuevaCadena$ = nuevaCadena$ + txt$\n NEXT cont\n\n Copialo$ = LTRIM$(RTRIM$(nuevaCadena$)) + final$\nEND FUNCTION\n\nSUB Saludo\n PRINT \"Hola mundo!\"\nEND SUB\n\nSUB testCadenas (txt$)\n FOR cont = 1 TO LEN(txt$)\n\tPRINT MID$(txt$, cont, 1); \"\";\n NEXT cont\nEND SUB\n\nSUB testNumeros (a, b, c)\n\tPRINT a, b, c\nEND SUB\n\nCALL Saludo\nPRINT Copialo$(\"Saludos \", 6, \"\")\nPRINT Copialo$(\"Saludos \", 3, \"!!\")\nPRINT\nCALL testNumeros(1, 2, 3)\nCALL testNumeros(1, 2, 0)\nPRINT\nCALL testCadenas(\"1, 2, 3, 4, cadena, 6, 7, 8, \\'incluye texto\\'\")\n", "language": "QBasic" }, { "code": "### Calling a function that requires no arguments\nno_args <- function() NULL\nno_args()\n\n\n### Calling a function with a fixed number of arguments\nfixed_args <- function(x, y) print(paste(\"x=\", x, \", y=\", y, sep=\"\"))\nfixed_args(1, 2) # x=1, y=2\nfixed_args(y=2, x=1) # y=1, x=2\n\n\n### Calling a function with optional arguments\nopt_args <- function(x=1) x\nopt_args() # x=1\nopt_args(3.141) # x=3.141\n\n\n### Calling a function with a variable number of arguments\nvar_args <- function(...) print(list(...))\nvar_args(1, 2, 3)\nvar_args(1, c(2,3))\nvar_args()\n\n\n### Calling a function with named arguments\nfixed_args(y=2, x=1) # x=1, y=2\n\n\n### Using a function in statement context\nif (TRUE) no_args()\n\n\n### Using a function in first-class context within an expression\nprint(no_args)\n\n\n### Obtaining the return value of a function\nreturn_something <- function() 1\nx <- return_something()\nx\n\n\n### Distinguishing built-in functions and user-defined functions\n# Not easily possible. See\n# http://cran.r-project.org/doc/manuals/R-ints.html#g_t_002eInternal-vs-_002ePrimitive\n# for details.\n\n\n### Distinguishing subroutines and functions\n# No such distinction.\n\n\n### Stating whether arguments are passed by value or by reference\n# Pass by value.\n\n\n### Is partial application possible and how\n# Yes, see http://rosettacode.org/wiki/Partial_function_application#R\n", "language": "R" }, { "code": "#lang racket\n\n;; Calling a function that requires no arguments\n(foo)\n\n;; Calling a function with a fixed number of arguments\n(foo 1 2 3)\n\n;; Calling a function with optional arguments\n;; Calling a function with a variable number of arguments\n(foo 1 2 3) ; same in both cases\n\n;; Calling a function with named arguments\n(foo 1 2 #:x 3) ; using #:keywords for the names\n\n;; Using a function in statement context\n;; Using a function in first-class context within an expression\n;; Obtaining the return value of a function\n;; -> Makes no sense for Racket, as well as most other functional PLs\n\n;; Distinguishing built-in functions and user-defined functions\n(primitive? foo)\n;; but this is mostly useless, since most of Racket is implemented in\n;; itself\n\n;; Distinguishing subroutines and functions\n;; -> No difference, though `!' is an idiomatic suffix for names of\n;; side-effect functions, and they usually return (void)\n\n;; Stating whether arguments are passed by value or by reference\n\n;; -> Always by value, but it's possible to implement languages with\n;; other argument passing styles, including passing arguments by\n;; reference (eg, there is \"#lang algol60\")\n\n;; Is partial application possible and how\n(curry foo 1 2) ; later apply this on 3\n(λ(x) (foo 1 2 x)) ; a direct way of doing the same\n", "language": "Racket" }, { "code": "foo # as list operator\nfoo() # as function\nfoo.() # as function, explicit postfix form\n$ref() # as object invocation\n$ref.() # as object invocation, explicit postfix\n&foo() # as object invocation\n&foo.() # as object invocation, explicit postfix\n::($name)() # as symbolic ref\n", "language": "Raku" }, { "code": "my $result = somefunc(1,2,3) + 2;\n", "language": "Raku" }, { "code": "{\nstate $n;\n\nmulti f () { print ' f' ~ ++$n }\nmulti f ($a) { die if 1 != $a; print ' f' ~ ++$n }\nmulti f ($a,$b) { die if 3 != $a+$b; print ' f' ~ ++$n }\nmulti f (@a) { die if @a != [2,3,4]; print ' f' ~ ++$n }\nmulti f ($a,$b,$c) { die if 2 != $a || 4 != $c; print ' f' ~ ++$n }\nsub g ($a,*@b) { die if @b != [2,3,4] || 1 != $a; print ' g' ~ ++$n }\n\nmy \\i = -> { print ' i' ~ ++$n }\nmy \\l = -> $a { die if 1 != $a; print ' l' ~ ++$n }\nmy \\m = -> $a,$b { die if 1 != $a || 2 != $b; print ' m' ~ ++$n }\nmy \\n = -> @a { die if @a != [2,3,4]; print ' n' ~ ++$n }\n\nInt.^add_method( 'j', method ()\n { die if 1 != self; print ' j' ~ ++$n } );\nInt.^add_method( 'k', method ($a)\n { die if 1 != self || 2 != $a; print ' k' ~ ++$n } );\nInt.^add_method( 'h', method (@a)\n { die if @a != [2,3,4] || 1 != self; print ' h' ~ ++$n } );\n\nmy $ref = &f; # soft ref\nmy $f := &f; # hard ref\nmy $g := &g; # hard ref\nmy $f-sym = '&f'; # symbolic ref\nmy $g-sym = '&g'; # symbolic ref\nmy $j-sym = 'j'; # symbolic ref\nmy $k-sym = 'k'; # symbolic ref\nmy $h-sym = 'h'; # symbolic ref\n\n# Calling a function with no arguments:\n\nf; # 1 as list operator\nf(); # 2 as function\ni.(); # 3 as function, explicit postfix form # defined via pointy-block\n$ref(); # 4 as object invocation\n$ref.(); # 5 as object invocation, explicit postfix\n&f(); # 6 as object invocation\n&f.(); # 7 as object invocation, explicit postfix\n::($f-sym)(); # 8 as symbolic ref\n\n# Calling a function with exactly one argument:\n\nf 1; # 9 as list operator\nf(1); # 10 as named function\nl.(1); # 11 as named function, explicit postfix # defined via pointy-block\n$f(1); # 12 as object invocation (must be hard ref)\n$ref.(1); # 13 as object invocation, explicit postfix\n1.$f; # 14 as pseudo-method meaning $f(1) (hard ref only)\n1.$f(); # 15 as pseudo-method meaning $f(1) (hard ref only)\n1.&f; # 16 as pseudo-method meaning &f(1) (is hard f)\n1.&f(); # 17 as pseudo-method meaning &f(1) (is hard f)\n1.j; # 18 as method via dispatcher # requires custom method, via 'Int.^add_method'\n1.j(); # 19 as method via dispatcher\n1.\"$j-sym\"(); # 20 as method via dispatcher, symbolic\n\n# Calling a function with exactly two arguments:\n\nf 1,2; # 21 as list operator\nf(1,2); # 22 as named function\nm.(1,2); # 23 as named function, explicit postfix # defined via pointy-block\n$ref(1,2); # 24 as object invocation (must be hard ref)\n$ref.(1,2); # 25 as object invocation, explicit postfix\n1.$f: 2; # 26 as pseudo-method meaning $f(1,2) (hard ref only)\n1.$f(2); # 27 as pseudo-method meaning $f(1,2) (hard ref only)\n1.&f: 2; # 28 as pseudo-method meaning &f(1,2) (is hard f)\n1.&f(2); # 29 as pseudo-method meaning &f(1,2) (is hard f)\n1.k: 2; # 30 as method via dispatcher # requires custom method, via 'Int.^add_method'\n1.k(2); # 31 as method via dispatcher\n1.\"$k-sym\"(2); # 32 as method via dispatcher, symbolic\n\n# Calling a function with a variable number of arguments (varargs):\n\nmy @args = 2,3,4;\n\nf @args; # 33 as list operator\nf(@args); # 34 as named function\nn.(@args); # 35 as named function, explicit postfix # defined via pointy-block\n$ref(@args); # 36 as object invocation (must be hard ref)\n$ref.(@args); # 37 as object invocation, explicit postfix\n1.$g: @args; # 38 as pseudo-method meaning $f(1,@args) (hard ref)\n1.$g(@args); # 39 as pseudo-method meaning $f(1,@args) (hard ref)\n1.&g: @args; # 40 as pseudo-method meaning &f(1,@args)\n1.&g(@args); # 41 as pseudo-method meaning &f(1,@args)\n1.h: @args; # 42 as method via dispatcher # requires custom method, via 'Int.^add_method'\n1.h(@args); # 43 as method via dispatcher\n1.\"$h-sym\"(@args); # 44 as method via dispatcher, symbolic\nf(|@args); # 45 equivalent to f(1,2,3)\n\n}\n", "language": "Raku" }, { "code": "foo 1 # as list operator\nfoo(1) # as named function\nfoo.(1) # as named function, explicit postfix\n$ref(1) # as object invocation (must be hard ref)\n$ref.(1) # as object invocation, explicit postfix\n1.$foo # as pseudo-method meaning $foo(1) (hard ref only)\n1.$foo() # as pseudo-method meaning $foo(1) (hard ref only)\n1.&foo # as pseudo-method meaning &foo(1) (is hard foo)\n1.&foo() # as pseudo-method meaning &foo(1) (is hard foo)\n1.foo # as method via dispatcher\n1.foo() # as method via dispatcher\n1.\"$name\"() # as method via dispatcher, symbolic\n+1 # as operator to prefix:<+> function\n", "language": "Raku" }, { "code": "foo 1,2 # as list operator\nfoo(1,2) # as named function\nfoo.(1,2) # as named function, explicit postfix\n$ref(1,2) # as object invocation (must be hard ref)\n$ref.(1,2) # as object invocation, explicit postfix\n1.$foo: 2 # as pseudo-method meaning $foo(1,2) (hard ref only)\n1.$foo(2) # as pseudo-method meaning $foo(1,2) (hard ref only)\n1.&foo: 2 # as pseudo-method meaning &foo(1,2) (is hard foo)\n1.&foo(2) # as pseudo-method meaning &foo(1,2) (is hard foo)\n1.foo: 2 # as method via dispatcher\n1.foo(2) # as method via dispatcher\n1.\"$name\"(2) # as method via dispatcher, symbolic\n1 + 2 # as operator to infix:<+> function\n", "language": "Raku" }, { "code": "foo @args # as list operator\nfoo(@args) # as named function\nfoo.(@args) # as named function, explicit postfix\n$ref(@args) # as object invocation (must be hard ref)\n$ref.(@args) # as object invocation, explicit postfix\n1.$foo: @args # as pseudo-method meaning $foo(1,@args) (hard ref)\n1.$foo(@args) # as pseudo-method meaning $foo(1,@args) (hard ref)\n1.&foo: @args # as pseudo-method meaning &foo(1,@args)\n1.&foo(@args) # as pseudo-method meaning &foo(1,@args)\n1.foo: @args # as method via dispatcher\n1.foo(@args) # as method via dispatcher\n1.\"$name\"(@args) # as method via dispatcher, symbolic\n@args X @blargs # as list infix operator to infix:<X>\n", "language": "Raku" }, { "code": "my @args = 1,2,3;\nfoo(|@args); # equivalent to foo(1,2,3)\n", "language": "Raku" }, { "code": "foo :a, :b(4), :!c, d => \"stuff\"\nfoo(:a, :b(4), :!c, d => \"stuff\")\n", "language": "Raku" }, { "code": "1 + 1 :a :b(4) :!c :d(\"stuff\") # calls infix:<+>(1,1,:a, :b(4), :!c, d => \"stuff\")\n", "language": "Raku" }, { "code": "foo(); bar(); baz(); # evaluate for side effects\n", "language": "Raku" }, { "code": "1 / find-a-func(1,2,3)(4,5,6) ** 2;\n", "language": "Raku" }, { "code": "/*REXX pgms demonstrates various methods/approaches of invoking/calling a REXX function.*/\n\n /*╔════════════════════════════════════════════════════════════════════╗\n ║ Calling a function that REQUIRES no arguments. ║\n ║ ║\n ║ In the REXX language, there is no way to require the caller to not ║\n ║ pass arguments, but the programmer can check if any arguments were ║\n ║ (or weren't) passed. ║\n ╚════════════════════════════════════════════════════════════════════╝*/\n\nyr= yearFunc() /*the function name is caseless if it isn't */\n /*enclosed in quotes (') or apostrophes (\").*/\nsay 'year=' yr\nexit /*stick a fork in it, we're all done. */\n\nyearFunc: procedure /*function ARG returns the # of args.*/\n errmsg= '***error***' /*an error message eyecatcher string. */\n if arg() \\== 0 then say errmsg \"the YEARFUNC function won't accept arguments.\"\n return left( date('Sorted'), 3)\n", "language": "REXX" }, { "code": " /*╔════════════════════════════════════════════════════════════════════╗\n ║ Calling a function with a fixed number of arguments. ║\n ║ ║\n ║ I take this to mean that the function requires a fixed number of ║\n ║ arguments. As above, REXX doesn't enforce calling (or invoking) ║\n ║ a (any) function with a certain number of arguments, but the ║\n ║ programmer can check if the correct number of arguments have been ║\n ║ specified (or not). ║\n ║ In some languages, these are known as \"generic\" functions. ║\n ╚════════════════════════════════════════════════════════════════════╝*/\n\nggg= FourFunc(12, abc, 6+q, zz%2, 'da 5th disagreement')\nsay 'ggg squared=' ggg**2\nexit /*stick a fork in it, we're all done. */\n\nFourFunc: procedure; parse arg a1,a2,a3 /*obtain the first three arguments. */\n a4= arg(4) /*another way to obtain the 4th arg. */\n errmsg= '***error***' /*an error message eyecatcher string. */\n if arg() \\== 4 then do\n say err \"FourFunc function requires 4 arguments,\"\n say err \"but instead it found\" arg() 'arguments.'\n exit 13 /*exit function with a RC of 13*/\n end\n\n return a1 + a2 + a3 + a4\n", "language": "REXX" }, { "code": " /*╔════════════════════════════════════════════════════════════════════╗\n ║ Calling a function with optional arguments. ║\n ║ ║\n ║ Note that not passing an argument isn't the same as passing a null ║\n ║ argument (a REXX variable whose value is length zero). ║\n ╚════════════════════════════════════════════════════════════════════╝*/\n\nx= 12; w= x/2; y= x**2; z= x//7 /* z is x modulo seven. */\nsay 'sum of w, x, y, & z=' SumIt(w,x,y,,z) /*pass five args, the 4th arg is \"null\"*/\nexit /*stick a fork in it, we're all done. */\n\nSumIt: procedure\n $= 0 /*initialize the sum to zero. */\n do j=1 for arg() /*obtain the sum of a number of args. */\n if arg(j,'E') then $= $ + arg(j) /*the Jth arg may have been omitted. */\n end /*j*/\n\n return $\n", "language": "REXX" }, { "code": " /*╔════════════════════════════════════════════════════════════════════╗\n ║ Calling a function with a variable number of arguments. ║\n ║ ║\n ║ This situation isn't any different then the previous example. ║\n ║ It's up to the programmer to code how to utilize the arguments. ║\n ╚════════════════════════════════════════════════════════════════════╝*/\n\n /*╔════════════════════════════════════════════════════════════════════╗\n ║ Calling a function with named arguments. ║\n ║ ║\n ║ REXX allows almost anything to be passed, so the following is one ║\n ║ way this can be accomplished. ║\n ╚════════════════════════════════════════════════════════════════════╝*/\n\nwhat= parserFunc('name=Luna', \"gravity=.1654\", 'moon=yes')\nsay 'name=' common.name\ngr= common.gr\nsay 'gravity=' gr\nexit /*stick a fork in it, we're all done. */\n\nparseFunc: procedure expose common.\n do j=1 for arg()\n parse var arg(j) name '=' val\n upper name /*uppercase it.*/\n call value 'COMMON.'name,val\n end\n return arg()\n", "language": "REXX" }, { "code": " /*╔════════════════════════════════════════════════════════════════════╗\n ║ Calling a function in statement context. ║\n ║ ║\n ║ REXX allows functions to be called (invoked) two ways, the first ║\n ║ example (above) is calling a function in statement context. ║\n ╚════════════════════════════════════════════════════════════════════╝*/\n\n /*╔════════════════════════════════════════════════════════════════════╗\n ║ Calling a function in within an expression. ║\n ║ ║\n ║ This is a variant of the first example. ║\n ╚════════════════════════════════════════════════════════════════════╝*/\n\nyr= yearFunc() + 20\nsay 'two decades from now, the year will be:' yr\nexit /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": " /*╔════════════════════════════════════════════════════════════════════╗\n ║ Obtaining the return value of a function. ║\n ║ ║\n ║ There are 2 ways to get the (return) value (RESULT) of a function. ║\n ╚════════════════════════════════════════════════════════════════════╝*/\n\ncurrYear= yearFunc()\nsay 'the current year is' currYear\n\ncall yearFunc\nsay 'the current year is' result /*result can be RESULT, it is caseless.*/\n", "language": "REXX" }, { "code": " /*╔════════════════════════════════════════════════════════════════════╗\n ║ Distinguishing built-in functions and user-defined functions. ║\n ║ ║\n ║ One objective of the REXX language is to allow the user to use any ║\n ║ function (or subroutine) name whether or not there is a built-in ║\n ║ function with the same name (there isn't a penality for this). ║\n ╚════════════════════════════════════════════════════════════════════╝*/\n\n /*date: as in going out with someone. */\nqqq= date() /*number of real dates that Bob was on.*/\n /*hopefully, it accurately counts dates*/\nsay \"Bob's been out\" qqq 'times.'\nwww= 'DATE'(\"USA\") /*returns date in format mm/dd/yyyy */\n /*any function in quotes is external. */\nexit /*stick a fork in it, we're all done. */\n\ndate: return 4 /*Bob only \"went out\" 4 times, no need */\n /* to actually count, he quit after 4. */\n", "language": "REXX" }, { "code": " /*╔════════════════════════════════════════════════════════════════════╗\n ║ Distinguishing subroutines and functions. ║\n ║ ║\n ║ There is no programmatic difference between subroutines and ║\n ║ functions if the subroutine returns a value (which effectively ║\n ║ makes it a function). REXX allows you to call a function as if ║\n ║ it were a subroutine. ║\n ╚════════════════════════════════════════════════════════════════════╝*/\n\n /*╔════════════════════════════════════════════════════════════════════╗\n ║ In REXX, all arguments are passed by value, never by name, but it ║\n ║ is possible to accomplish this if the variable's name is passed ║\n ║ and the subroutine/function could use the built-in-function VALUE ║\n ║ to retrieve the variable's value. ║\n ╚════════════════════════════════════════════════════════════════════╝*/\n\n /*╔════════════════════════════════════════════════════════════════════╗\n ║ In the REXX language, partial application is possible, depending ║\n ║ how partial application is defined; I prefer the 1st definition ║\n ║ (as per the \"discussion\" for \"Partial Function Application\" task: ║\n ║ 1. The \"syntactic sugar\" that allows one to write some examples ║\n ║ are: map (f 1 9) [1..9] ║\n ║ or: map (f(1,_,9)) [1, ..., 9] ║\n ╚════════════════════════════════════════════════════════════════════╝*/\n", "language": "REXX" }, { "code": "/* REXX ***************************************************************\n* 29.07.2013 Walter Pachl trying to address the task concisely\n***********************************************************************\n* f1 Calling a function that requires no arguments\n* f2 Calling a function with a fixed number of arguments\n* f3 Calling a function with optional arguments\n* f4 Calling a function with a variable number of arguments\n* f5 Calling a function with named arguments\n* f6 Using a function in statement context\n* f7 Using a function within an expression\n* f8 Obtaining the return value of a function\n* f8(...) is replaced by the returned value\n* call f8 ... returned value is in special vatiable RESULT\n* f9 Distinguishing built-in functions and user-defined functions\n* bif is enforced by using its name quoted in uppercase\n* fa,fb Distinguishing subroutines and functions\n* Stating whether arguments are passed by value or by reference\n* Arguments are passed by value\n* ooRexx supports passing by reference (Use Arg instruction)\n* Is partial application possible and how\n* no ideas\n**********************************************************************/\nsay f1()\nSay f2(1,2,3)\nsay f2(1,2,3,4)\nsay f3(1,,,4)\nSay f4(1,2)\nSay f4(1,2,3)\na=4700; b=11;\nSay f5('A','B')\nf6() /* returned value is used as command */\nx=f7()**2\ncall f8 1,2; Say result '=' f8(1,2)\nf9: Say 'DATE'('S') date()\ncall fa 11,22; Say result '=' fa(1,,\n 2) /* the second comma above is for line continuation */\nSignal On Syntax\nCall fb 1,2\nx=fb(1,2)\nExit\nf1: Return 'f1 doesn''t need an argument'\nf2: If arg()=3 Then\n Return 'f2: Sum of 3 arguments:' arg(1)+arg(2)+arg(3)\n Else\n Return 'f2: Invalid invocation:' arg() 'arguments. Needed: 3'\nf3: sum=0\n do i=1 To arg()\n If arg(i,'E')=0 Then Say 'f3: Argument' i 'omitted'\n Else sum=sum+arg(i)\n End\n Return 'f3 sum=' sum\nf4: sum=0; Do i=1 To arg(); sum=sum+arg(i); End\n Return 'f4: Sum of' arg() 'arguments is' sum\nf5: Parse Arg p1,p2\n Say 'f5: Argument 1 ('p1') contains' value(p1)\n Say 'f5: Argument 2 ('p2') contains' value(p2)\n Return 'f5: sum='value(p1)+value(p2)\nf6: Say 'f6: dir ft.rex'\n Return 'dir ft.rex'\nf7: Say 'f7 returns 7'\n Return 7\nf8: Say 'f8 returns arg(1)+arg(2)'\n Return arg(1)+arg(2)\ndate: Say 'date is my date function'\n Return translate('ef/gh/abcd','DATE'('S'),'abcdefgh')\nfa: Say 'fa returns arg(1)+arg(2)'\n Return arg(1)+arg(2)\nfb: Say 'fb:' arg(1)','arg(2)\n Return\n\nSyntax:\n Say 'Syntax raised in line' sigl\n Say sourceline(sigl)\n Say 'rc='rc '('errortext(rc)')'\n If sigl=39 Then\n Say 'fb cannot be invoked as function (it does not return a value'\n Exit\n", "language": "REXX" }, { "code": "hello()\nfunc hello\n see \"Hello from function\" + nl\n", "language": "Ring" }, { "code": "first() second()\nfunc first see \"message from the first function\" + nl\nfunc second see \"message from the second function\" + nl\n", "language": "Ring" }, { "code": "sum(3,5) sum(1000,2000)\nfunc sum x,y see x+y+nl\n", "language": "Ring" }, { "code": "# this program will print the hello world message first then execute the main function\nSee \"Hello World!\" + nl\nfunc main\n see \"Message from the main function\" + nl\n", "language": "Ring" }, { "code": "def foo() p \"foo\" end\n\nfoo #=> \"foo\"\nfoo() #=> \"foo\"\n", "language": "Ruby" }, { "code": "# return value substance\ni = 3\np 1 + i #=> 4 1.+(i)\np i < 5 #=> true i.<(5)\np 2 ** i #=> 8 2.**(i)\np -i #=> -3 i.-@()\na = [1,2,3]\np a[0] #=> 1 a.[](0)\na[2] = \"0\" # a.[]=(2,\"0\")\np a << 5 #=> [1, 2, \"0\", 5] a.<<(5)\np a & [4,2] #=> [2] a.&([4,2])\np \"abcde\"[1..3] #=> \"bcd\" \"abcde\".[](1..3)\np \"%2d %4s\" % [1,\"xyz\"] #=> \" 1 xyz\" \"%2d %4s\".%([1,\"xyz\"])\n", "language": "Ruby" }, { "code": "def foo arg; p arg end # one argument\n\nfoo(1) #=> 1\nfoo \"1\" #=> \"1\"\nfoo [0,1,2] #=> [0, 1, 2] (one Array)\n", "language": "Ruby" }, { "code": "def foo(x=0, y=x, flag=true) p [x,y,flag] end\n\nfoo #=> [0, 0, true]\nfoo(1) #=> [1, 1, true]\nfoo(1,2) #=> [1, 2, true]\nfoo 1,2,false #=> [1, 2, false]\n", "language": "Ruby" }, { "code": "def foo(*args) p args end\n\nfoo #=> []\nfoo(1,2,3,4,5) #=> [1, 2, 3, 4, 5]\n", "language": "Ruby" }, { "code": "def foo(id:0, name:\"\", age:0) p [id, name, age] end\n\nfoo(age:22, name:\"Tom\") #=> [0, \"Tom\", 22]\n", "language": "Ruby" }, { "code": "def foo(a,b) a + b end\n\nbar = foo 10,20\np bar #=> 30\np foo(\"abc\",\"def\") #=> \"abcdef\"\n\n# return multiple values\ndef sum_and_product(a,b) return a+b,a*b end\n\nx,y = sum_and_product(3,5)\np x #=> 8\np y #=> 15\n", "language": "Ruby" }, { "code": "puts \"OK!\" # Kernel#puts\nraise \"Error input\" # Kernel#raise\nInteger(\"123\") # Kernel#Integer\nrand(6) # Kernel#rand\nthrow(:exit) # Kernel#throw\n\n# method which can be seen like a reserved word.\nattr_accessor # Module#attr_accessor\ninclude # Module#include\nprivate # Module#private\nrequire # Kernel#require\nloop { } # Kernel#loop\n", "language": "Ruby" }, { "code": "class Array\n def sum(init=0, &blk)\n if blk\n inject(init){|s, n| s + blk.call(n)}\n else\n inject(init){|s, n| s + n}\n end\n end\nend\n\nary = [1,2,3,4,5]\np ary.sum #=> 15\np ary.sum(''){|n| (-n).to_s} #=> \"-1-2-3-4-5\"\np (ary.sum do |n| n * n end) #=> 55\n", "language": "Ruby" }, { "code": "def foo(a,b,c) p [a,b,c] end\n\nargs = [1,2,3]\nfoo *args #=> [1, 2, 3]\nargs = [1,2]\nfoo(0,*args) #=> [0, 1, 2]\n", "language": "Ruby" }, { "code": "fn main() {\n // Rust has a lot of neat things you can do with functions: let's go over the basics first\n fn no_args() {}\n // Run function with no arguments\n no_args();\n\n // Calling a function with fixed number of arguments.\n // adds_one takes a 32-bit signed integer and returns a 32-bit signed integer\n fn adds_one(num: i32) -> i32 {\n // the final expression is used as the return value, though `return` may be used for early returns\n num + 1\n }\n adds_one(1);\n\n // Optional arguments\n // The language itself does not support optional arguments, however, you can take advantage of\n // Rust's algebraic types for this purpose\n fn prints_argument(maybe: Option<i32>) {\n match maybe {\n Some(num) => println!(\"{}\", num),\n None => println!(\"No value given\"),\n };\n }\n prints_argument(Some(3));\n prints_argument(None);\n\n // You could make this a bit more ergonomic by using Rust's Into trait\n fn prints_argument_into<I>(maybe: I)\n where I: Into<Option<i32>>\n {\n match maybe.into() {\n Some(num) => println!(\"{}\", num),\n None => println!(\"No value given\"),\n };\n }\n prints_argument_into(3);\n prints_argument_into(None);\n\n // Rust does not support functions with variable numbers of arguments. Macros fill this niche\n // (println! as used above is a macro for example)\n\n // Rust does not support named arguments\n\n // We used the no_args function above in a no-statement context\n\n // Using a function in an expression context\n adds_one(1) + adds_one(5); // evaluates to eight\n\n // Obtain the return value of a function.\n let two = adds_one(1);\n\n // In Rust there are no real built-in functions (save compiler intrinsics but these must be\n // manually imported)\n\n // In rust there are no such thing as subroutines\n\n // In Rust, there are three ways to pass an object to a function each of which have very important\n // distinctions when it comes to Rust's ownership model and move semantics. We may pass by\n // value, by immutable reference, or mutable reference.\n\n let mut v = vec![1, 2, 3, 4, 5, 6];\n\n // By mutable reference\n fn add_one_to_first_element(vector: &mut Vec<i32>) {\n vector[0] += 1;\n }\n add_one_to_first_element(&mut v);\n // By immutable reference\n fn print_first_element(vector: &Vec<i32>) {\n println!(\"{}\", vector[0]);\n }\n print_first_element(&v);\n\n // By value\n fn consume_vector(vector: Vec<i32>) {\n // We can do whatever we want to vector here\n }\n consume_vector(v);\n // Due to Rust's move semantics, v is now inaccessible because it was moved into consume_vector\n // and was then dropped when it went out of scope\n\n // Partial application is not possible in rust without wrapping the function in another\n // function/closure e.g.:\n fn average(x: f64, y: f64) -> f64 {\n (x + y) / 2.0\n }\n let average_with_four = |y| average(4.0, y);\n average_with_four(2.0);\n\n\n}\n", "language": "Rust" }, { "code": "def ??? = throw new NotImplementedError // placeholder for implementation of hypothetical methods\ndef myFunction0() = ???\nmyFunction0() // function invoked with empty parameter list\nmyFunction0 // function invoked with empty parameter list omitted\n\ndef myFunction = ???\nmyFunction // function invoked with no arguments or empty arg list\n/* myFunction() */ // error: does not take parameters\n\ndef myFunction1(x: String) = ???\nmyFunction1(\"foobar\") // function invoked with single argument\nmyFunction1 { \"foobar\" } // function invoked with single argument provided by a block\n // (a block of code within {}'s' evaluates to the result of its last expression)\n\ndef myFunction2(first: Int, second: String) = ???\nval b = \"foobar\"\nmyFunction2(6, b) // function with two arguments\n\ndef multipleArgLists(first: Int)(second: Int, third: String) = ???\nmultipleArgLists(42)(17, \"foobar\") // function with three arguments in two argument lists\n\ndef myOptionalParam(required: Int, optional: Int = 42) = ???\nmyOptionalParam(1) // function with optional param\nmyOptionalParam(1, 2) // function with optional param provided\n\ndef allParamsOptional(firstOpt: Int = 42, secondOpt: String = \"foobar\") = ???\nallParamsOptional() // function with all optional args\n/* allParamsOptional */ // error: missing arguments for method allParamsOptional;\n // follow with `_' if you want to treat it as a partially applied function\n\ndef sum[Int](values: Int*) = values.foldLeft(0)((a, b) => a + b)\nsum(1, 2, 3) // function accepting variable arguments as literal\n\nval values = List(1, 2, 3)\nsum(values: _*) // function acception variable arguments from collection\nsum() // function accepting empty variable arguments\n\ndef mult(firstValue: Int, otherValues: Int*) = otherValues.foldLeft(firstValue)((a, b) => a * b)\nmult(1, 2, 3) // function with non-empty variable arguments\nmyOptionalParam(required = 1) // function called with named arguments (all functions have named arguments)\nmyFunction2(second = \"foo\", first = 1) // function with re-ordered named arguments\nmult(firstValue = 1, otherValues = 2, 3) // function with named variable argument as literal\n\nval otherValues = Seq(2, 3)\nmult(1, otherValues = otherValues: _*) // function with named variable argument from collection\nval result = myFunction0() // function called in an expression context\nmyFunction0() // function called in statement context\n/* myOptionalParam(optional = 1, 2) */ // error: positional after named argument.\n\ndef transform[In, Out](initial: In)(transformation: In => Out) = transformation(initial)\nval result = transform(42)(x => x * x) // function in first-class context within an expression\n\ndef divide(top: Double, bottom: Double) = top / bottom\nval div = (divide _) // partial application -- defer application of entire arg list\nval halve = divide(_: Double, 2) // partial application -- defer application of some arguments\n\nclass Foo(var value: Int)\ndef incFoo(foo: Foo) = foo.value += 1 // function showing AnyRef's are passed by reference\n/* def incInt(i: Int) = i += 1 */ // error: += is not a member of Int\n // (All arguments are passed by reference, but reassignment\n // or setter must be defined on a type or a field\n // (respectively) in order to modify its value.)\n\n// No distinction between built-in functions and user-defined functions\n// No distinction between subroutines and functions\n", "language": "Scala" }, { "code": "env := environment; # Call a function that requires no arguments.\nenv := environment(); # Alternative possibility to call of a function with no arguments.\ncmp := compare(i, j); # Call a function with a fixed number of arguments.\n", "language": "Seed7" }, { "code": "write(aFile, \"asdf\"); # Variant of write with a parameter to specify a file.\nwrite(\"asdf\"); # Variant of write which writes to the file OUT.\n", "language": "Seed7" }, { "code": "const func integer: sum (in array integer: intElems) is func\n result\n var integer: sum is 0;\n local\n var integer: element is 0;\n begin\n for element range intElems do\n sum +:= element;\n end for;\n end func;\n\ns := sum([] (1, 2, 3)); # Use an aggregate to generate an array.\nt := sum([] (2, 3, 5, 7));\n", "language": "Seed7" }, { "code": "write(\"Nr: \" <& num); # Use operators to concatenate arguments.\n", "language": "Seed7" }, { "code": "ignore(getln(IN)); # Using a function in statement context (ignore the result).\n", "language": "Seed7" }, { "code": "seq := doMap([](1, 2, 4, 6, 10, 12, 16), x, succ(x));\n", "language": "Seed7" }, { "code": "put zeroArgsFn()\n\n// Function calls can also be made using the following syntax:\nput the zeroArgsFn\n\nfunction zeroArgsFn\n put \"This function was run with zero arguments.\"\n return \"Return value from zero argument function\"\nend zeroArgsFn\n", "language": "SenseTalk" }, { "code": "put TwoArgFn(\"variable\", (3, 4)) into _\n\n// Alternatively, the function can be called like so:\nput the TwoArgFn of \"variable\", (3, 4)\n\n// The parameter list is flexible, allowing any amount of variable to be passed in.\n// These can be accessed with the keyword `the parameterList`\n// The specified parameters only limits to named parameters\nget TwoArgFn(\"variable\", (3, 4), \"hello\")\nget the TwoArgFn of \"variable\", (3, 4), \"hello\"\n\nfunction TwoArgFn arg1, arg2\n put \"2 argument function: arg1 = \" & arg1 & \"; arg2 = \" & arg2\n put \"Parameters = \" & the parameterList\nend TwoArgFn\n", "language": "SenseTalk" }, { "code": "get ThreeArgFn(\"variable\", (3, 4))\n\nfunction ThreeArgFn arg1, arg2, arg3\n put \"3 argument function: arg1 = \" & arg1 & \"; arg2 = \" & arg2 & \"; arg3 = \" & arg3\nend ThreeArgFn\n", "language": "SenseTalk" }, { "code": "get OneArgFn() -- arg1 is 5\nget OneArgFn(10) -- arg1 is now 10\n\nfunction OneArgFn arg1\n if arg1 is \"\"\n set arg1 to 5\n end if\n put \"One argument function; arg1 = \" & arg1\nend OneArgFn\n", "language": "SenseTalk" }, { "code": "put 3 into a\nget AddOne(a)\nput \"Value of a = \" & a\n// Value of a = 3\n\nput 5 into b\nget AddOne(container b)\nput \"Value of b = \" & b\n// Value of b = 6\n\nfunction AddOne n\n add 1 to n\nend AddOne\n", "language": "SenseTalk" }, { "code": "CustomHandler 1, 2, 3\n// Prints: 1 - 2 - 3\n\nto handle CustomHandler arg1, arg2, arg3\n put arg1 && \"-\" && arg2 && \"-\" && arg3\nend CustomHandler\n", "language": "SenseTalk" }, { "code": "MyCommand 1, \"variable\", (4, 5, 6)\n\nto MyCommand args\n...\nend MyCommand\n", "language": "SenseTalk" }, { "code": "to MyFn args\n...\nend MyFn\n\nfunction MyFn args\n...\nend args\n\non MyFn args\n...\nend args\n", "language": "SenseTalk" }, { "code": "foo(); # without arguments\nfoo(1, 2); # with two arguments\nfoo(args...); # with a variable number of arguments\nfoo(name: 'Bar', age: 42); # with named arguments\n\nvar f = foo; # store the function foo inside 'f'\nvar result = f(); # obtain the return value of a function\n\nvar arr = [1,2,3];\nfoo(arr); # the arguments are passed by object-reference\n", "language": "Sidef" }, { "code": "func curry(f, *args1) {\n func (*args2) {\n f(args1..., args2...);\n }\n}\n\nfunc add(a, b) {\n a + b\n}\n\nvar adder = curry(add, 1);\nsay adder(3); #=>4\n", "language": "Sidef" }, { "code": "(define hello-world (lambda () (display \"Hello, world!\\n\"))\n(hello-world)\n", "language": "Slope" }, { "code": "((lambda () (display \"Hello, world!\\n\")))\n", "language": "Slope" }, { "code": "(define hello (lambda (name) (display \"Hello, \" name \"!\\n\")))\n(hello \"Rosetta Code\")\n", "language": "Slope" }, { "code": "((lambda (name) (display \"Hello, \" name \"!\\n\")) \"Rosetta Code\")\n", "language": "Slope" }, { "code": "((lambda (op ...)\n (if (null? ...)\n (! \"At least one argument is required\")\n (apply op ...)))\n* 1 2 3 4)\n", "language": "Slope" }, { "code": "((lambda (first ...)\n (define last (if (null? ...) \"\" (append \" \" (car ...))))\n (display \"Hello \" first last \"\\n\")) \"John\" \"Kimball\")\n", "language": "Slope" }, { "code": "f valueWithArguments: arguments.\n", "language": "Smalltalk" }, { "code": "00110000000000100000000000000000 10. -12 to c\n10110000000000000000000000000000 11. 13 to CI\n11001111111111111111111111111111 12. -13\n11001000000000000000000000000000 13. 19\n", "language": "SSEM" }, { "code": "// call a function with no args\nnoArgs()\n\n// call a function with one arg with no external name\noneArgUnnamed(1)\n\n// call a function with one arg with external name\noneArgNamed(arg: 1)\n\n// call a function with two args with no external names\ntwoArgsUnnamed(1, 2)\n\n// call a function with two args and external names\ntwoArgsNamed(arg1: 1, arg2: 2)\n\n// call a function with an optional arg\n// with arg\noptionalArguments(arg: 1)\n// without\noptionalArguments() // defaults to 0\n\n// function that takes another function as arg\nfuncArg(noArgs)\n\n// variadic function\nvariadic(opts: \"foo\", \"bar\")\n\n// getting a return value\nlet foo = returnString()\n\n// getting a bunch of return values\nlet (foo, bar, baz) = returnSomeValues()\n\n// getting a bunch of return values, discarding second returned value\nlet (foo, _, baz) = returnSomeValues()\n", "language": "Swift" }, { "code": "aCallToACommandWithNoArguments\naCallToACommandWithOne argument\naCallToACommandWith arbitrarily many arguments\naCallToACommandWith {*}$manyArgumentsComingFromAListInAVariable\naCallToACommandWith -oneNamed argument -andAnother namedArgument\naCallToACommandWith theNameOfAnotherCommand\naCallToOneCommand [withTheResultOfAnother]\n", "language": "Tcl" }, { "code": "expr {func() + [cmd]}\nexpr {func(1,2,3} + [cmd a b c]}\n", "language": "Tcl" }, { "code": "FUNCTION Copialo$ (txt$, siNo, final$)\n FOR cont = 1 TO ROUND(siNo)\n LET nuevaCadena$ = nuevaCadena$ & txt$\n NEXT cont\n\n LET Copialo$ = LTRIM$(RTRIM$(nuevaCadena$)) & final$\nEND FUNCTION\n\nSUB Saludo\n PRINT \"Hola mundo!\"\nEND SUB\n\nSUB testCadenas (txt$)\n FOR cont = 1 TO ROUND(LEN(txt$))\n PRINT (txt$)[cont:cont+1-1]; \"\";\n NEXT cont\nEND SUB\n\nSUB testNumeros (a, b, c)\n PRINT a, b, c\nEND SUB\n\nCALL Saludo\nPRINT Copialo$(\"Saludos \", 6, \"\")\nPRINT Copialo$(\"Saludos \", 3, \"! !\")\nPRINT\nCALL testNumeros(1, 2, 3)\nCALL testNumeros(1, 2, 0)\nPRINT\nCALL testCadenas(\"1, 2, 3, 4, cadena, 6, 7, 8, \\'incluye texto\\'\")\nEND\n", "language": "True-BASIC" }, { "code": "sayhello # Call a function in statement context with no arguments\nmultiply 3 4 # Call a function in statement context with two arguments\n", "language": "UNIX-Shell" }, { "code": "'definitions/declarations\n\n'Calling a function that requires no arguments\nFunction no_arguments() As String\n no_arguments = \"ok\"\nEnd Function\n\n'Calling a function with a fixed number of arguments\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n fixed_number = argument1 + argument2\nEnd Function\n\n'Calling a function with optional arguments\nFunction optional_parameter(Optional argument1 = 1) As Integer\n 'Optional parameters come at the end of the parameter list\n optional_parameter = argument1\nEnd Function\n\n'Calling a function with a variable number of arguments\nFunction variable_number(arguments As Variant) As Integer\n variable_number = UBound(arguments)\nEnd Function\n\n'Calling a function with named arguments\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n named_arguments = argument1 + argument2\nEnd Function\n\n'Using a function in statement context\nFunction statement() As String\n Debug.Print \"function called as statement\"\n statement = \"ok\"\nEnd Function\n\n'Using a function in first-class context within an expression\n'see call the functions\n\n'Obtaining the return value of a function\nFunction return_value() As String\n return_value = \"ok\"\nEnd Function\n\n'Distinguishing built-in functions and user-defined functions\n'There is no way to distinguish built-in function and user-defined functions\n\n'Distinguishing subroutines And functions\n'subroutines are declared with the reserved word \"sub\" and have no return value\nSub foo()\n Debug.Print \"subroutine\",\nEnd Sub\n'functions are declared with the reserved word \"function\" and can have a return value\nFunction bar() As String\n bar = \"function\"\nEnd Function\n\n'Stating whether arguments are passed by value or by reference\nFunction passed_by_value(ByVal s As String) As String\n s = \"written over\"\n passed_by_value = \"passed by value\"\nEnd Function\n'By default, parameters in VBA are by reference\nFunction passed_by_reference(ByRef s As String) As String\n s = \"written over\"\n passed_by_reference = \"passed by reference\"\nEnd Function\n\n'Is partial application possible and how\n'I don't know\n\n'calling a subroutine with arguments does not require parentheses\nSub no_parentheses(myargument As String)\n Debug.Print myargument,\nEnd Sub\n\n'call the functions\nPublic Sub calling_a_function()\n 'Calling a function that requires no arguments\n Debug.Print \"no arguments\", , no_arguments\n Debug.Print \"no arguments\", , no_arguments()\n 'Parentheses are not required\n\n 'Calling a function with a fixed number of arguments\n Debug.Print \"fixed_number\", , fixed_number(1, 1)\n\n 'Calling a function with optional arguments\n Debug.Print \"optional parameter\", optional_parameter\n Debug.Print \"optional parameter\", optional_parameter(2)\n\n 'Calling a function with a variable number of arguments\n Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n 'The variable number of arguments have to be passed as an array\n\n 'Calling a function with named arguments\n Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n\n 'Using a function in statement context\n statement\n\n 'Using a function in first-class context within an expression\n s = \"no_arguments\"\n Debug.Print \"first-class context\", Application.Run(s)\n 'A function name can be passed as argument in a string\n\n 'Obtaining the return value of a function\n returnvalue = return_value\n Debug.Print \"obtained return value\", returnvalue\n\n 'Distinguishing built-in functions and user-defined functions\n\n 'Distinguishing subroutines And functions\n foo\n Debug.Print , bar\n\n 'Stating whether arguments are passed by value or by reference\n Dim t As String\n t = \"unaltered\"\n Debug.Print passed_by_value(t), t\n Debug.Print passed_by_reference(t), t\n\n 'Is partial application possible and how\n 'I don 't know\n\n 'calling a subroutine with arguments does not require parentheses\n no_parentheses \"calling a subroutine\"\n Debug.Print \"does not require parentheses\"\n Call no_parentheses(\"deprecated use\")\n Debug.Print \"of parentheses\"\n\nEnd Sub\n", "language": "VBA" }, { "code": "let noargs => + 2 5;\nnoargs -- print;\n\nlet fixedargs a b => + a b;\nfixedargs 3 5 -- print;\n\nlet m => import 'math';\nm.cos 3 -- print;\n\n# WDTE only has expressions, not statements, so statement vs.\n# first-class context doesn't make sense.\n\n# Arguments in WDTE are technically passed by reference, in a way, but\n# because it's a functional language and everything's immutable\n# there's no real usability difference from that.\n\n# Partial application is possible. For example, the following\n# evaluates `+ 3` and then passes 7 to the resulting partially applied\n# function.\n(+ 3) 7 -- print;\n", "language": "WDTE" }, { "code": "(func $main (export \"_start\")\n\n (local $result i32)\n\n ;;Call a function with no arguments\n call $noargfunc\n\n ;;Multiply two numbers and store the result, flat syntax\n i32.const 12\n i32.const 3\n call $multipy\n set_local $result\n\n ;;Multiply two numbers and store the result, indented syntax\n (set_local $result\n (call $multipy\n (i32.const 12)\n (i32.const 3)\n )\n )\n\n ;;Add two numbers in linear memory (similar to using pointers)\n (i32.store (i32.const 0) (i32.const 5))\n (i32.store (i32.const 4) (i32.const 7))\n\n (call $addinmemory\n (i32.const 0)\n (i32.const 4)\n (i32.const 8)\n )\n)\n", "language": "WebAssembly" }, { "code": "var f1 = Fn.new { System.print(\"Function 'f1' with no arguments called.\") }\nvar f2 = Fn.new { |a, b|\n System.print(\"Function 'f2' with 2 arguments called and passed %(a) & %(b).\")\n}\nvar f3 = Fn.new { 42 } // function which returns a concrete value\n\nf1.call() // statement context\nf2.call(2, 3) // ditto\nvar v1 = 8 + f3.call() // calling function within an expression\nvar v2 = f3.call() // obtaining return value\nSystem.print([v1, v2]) // print last two results as a list\n\nclass MyClass {\n static m() { System.print(\"Static method 'm' called.\") }\n\n construct new(x) { _x = x } // stores 'x' in a field\n\n x { _x } // gets the field\n x=(y) { _x = y } // sets the field to 'y'\n\n - { MyClass.new(-_x) } // prefix operator\n +(o) { MyClass.new(_x + o.x) } // infix operator\n\n toString { _x.toString } // instance method\n}\n\nMyClass.m() // call static method 'm'\nvar mc1 = MyClass.new(40) // construct 'mc1'\nvar mc2 = MyClass.new(8) // construct 'mc2'\nSystem.print(mc1.x) // print mc1's field using getter\nmc1.x = 42 // change mc1's field using setter\nSystem.print(-mc1.x) // invoke prefix operator -\nSystem.print(mc1 + mc2) // invoke infix operator +\n", "language": "Wren" }, { "code": "; call a function (procedure) with no arguments:\n(foo)\n\n; call a function (procedure) with arguments:\n(foo bar baz)\n; the first symbol after \"(\" is the name of the function\n; the other symbols are the arguments\n\n; call a function on a list of arguments formed at run time:\n(apply foo bar)\n\n; In a REPL, the return value will be printed.\n; In other contexts, it can be fed as argument into a further function:\n(foo (bar baz))\n; this calls bar on the argument baz and then calls foo on the return value\n\n; or it can simply be discarded\n(foo bar)\n; nothing is done with the return value\n", "language": "XLISP" }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n <xsl:output method=\"xml\" indent=\"yes\"/>\n <xsl:template match=\"/\">\n <demo>\n <!--\n XSLT 1.0 actually defines two function-like constructs that\n are used variously depending on the context.\n -->\n <xsl:call-template name=\"xpath-function-demos\"/>\n <xsl:call-template name=\"xslt-template-demos\"/>\n </demo>\n </xsl:template>\n\n <xsl:template name=\"xpath-function-demos\">\n <!--\n A 'function' in XSLT 1.0 is a function that can be called from\n an XPath 1.0 expression (such as from \"select\" or \"test\"\n attribute of several XSLT elements). The following demos apply\n to these functions.\n -->\n\n <!-- Calling function that requires no arguments -->\n <!-- false() always returns a boolean false value -->\n <line>This test is <xsl:if test=\"false()\">NOT</xsl:if> OK.</line>\n\n <!-- Calling a function with a fixed number of arguments -->\n <!-- not() takes exactly 1 argument. starts-with() takes exactly 2 arguments. -->\n <line>'haystack' does <xsl:if test=\"not(starts-with('haystack', 'hay'))\">NOT</xsl:if> start with 'hay'.</line>\n\n <!-- Calling a function with optional arguments -->\n <!-- If the third argument of substring() is omitted, the length of the string is assumed. -->\n <line>'<xsl:value-of select=\"substring('haystack', 1, 3)\"/>' = 'hay'</line>\n <line>'<xsl:value-of select=\"substring('haystack', 4)\"/>' = 'stack'</line>\n\n <!-- Calling a function with a variable number of arguments -->\n <!-- concat() accepts two or more arguments. -->\n <line>'<xsl:value-of select=\"concat('abcd', 'efgh')\"/>' = 'abcdefgh'</line>\n <line>'<xsl:value-of select=\"concat('ij', 'kl', 'mn', 'op')\"/>' = 'ijklmnop'</line>\n <!--\n Aggregate functions such as sum() and count() accept nodesets.\n This isn't quite the same as varargs but are probably worth\n mentioning.\n -->\n <line>The number of root elements in the input document is <xsl:value-of select=\"count(/*)\"/> (should be 1).</line>\n\n <!-- Calling a function with named arguments -->\n <!-- XPath 1.0 uses only positional parameters. -->\n\n <!-- Using a function in statement context -->\n <!--\n In general, XPath 1.0 functions have no side effects, so calling\n them as statements is useless. While implementations often allow\n writing extensions in imperative languages, the semantics of\n calling a function with side effects are, at the very least,\n implementation-dependent.\n -->\n\n <!-- Using a function in first-class context within an expression -->\n <!-- Functions are not natively first-class values in XPath 1.0. -->\n\n <!-- Obtaining the return value of a function -->\n <!--\n The return value of the function is handled as specified by the\n various contexts in which an XPath expression is used. The\n return value can be stored in a \"variable\" (no destructive\n assignment is allowed), passed as a parameter to a function or a\n template, used as a conditional in an <xsl:if/> or <xsl:when/>,\n interpolated into text using <xsl:value-of/> or into an\n attribute value using brace syntax, and so forth.\n -->\n <!-- Here, concat() is interpolated into an attribute value using braces ({}). -->\n <line foo=\"{concat('Hello, ', 'Hello, ', 'Hello')}!\">See attribute.</line>\n\n <!-- Distinguishing built-in functions and user-defined functions -->\n <!--\n Given that functions aren't first-class here, the origin of any\n given function is known before run time. Incidentally, functions\n defined by the standard are generally unprefixed while\n implementation-specific extensions (and user extensions, if\n available) must be defined within a separate namespace and\n prefixed.\n -->\n\n <!-- Distinguishing subroutines and functions -->\n <!--\n There are no \"subroutines\" in this sense—everything that looks\n like a subroutine has some sort of return or result value.\n -->\n\n <!-- Stating whether arguments are passed by value or by reference -->\n <!-- There is no meaningful distinction since there is no mechanism by which to mutate values. -->\n\n <!-- Is partial application possible and how -->\n <!-- Not natively. -->\n </xsl:template>\n\n <xsl:template name=\"xslt-template-demos\">\n <!--\n A 'template' in XSLT 1.0 is a subroutine-like construct. When\n given a name (and, optionally, parameters), it can be called\n from within another template using the <xsl:call-template/>\n element. (An unnamed template is instead called according to its\n match and mode attributes.) The following demos apply to named\n templates.\n -->\n <!--\n Unlike with functions, there are no built-in named templates to\n speak of. The ones used here are defined later in this\n transform.\n -->\n\n <!--\n Answers for these prompts are the same as with XPath functions (above):\n Using a function in statement context\n Distinguishing subroutines and functions\n Stating whether arguments are passed by value or by reference\n Is partial application possible and how\n -->\n\n <!-- Calling function that requires no arguments -->\n <xsl:call-template name=\"nullary-demo\"/>\n <!--\n Note that even if a template has no parameters, it has access to\n the current node (.) as of the time of the call. This\n <xsl:apply-templates/> runs a matching template above that calls\n the template \"nullary-context-demo\" with no parameters. Another\n way to manipulate a template's idea of which node is current is\n by calling from inside a <xsl:for-each/> loop.\n -->\n <xsl:apply-templates select=\"/*\" mode=\"nullary-context-demo-mode\"/>\n\n <!--\n A template parameter is made optional in the definition of the\n template by supplying an expression as its select attribute,\n which is evaluated and used as its value if the parameter is\n omitted. Note, though, that all template parameters have an\n implicit default value, the empty string, if the select\n attribute is not specified. Therefore, all template parameters\n are always optional, even when semantically they should not be.\n -->\n\n <!-- Calling a function with a fixed number of arguments -->\n <working note=\"When all parameters are supplied\">\n <xsl:call-template name=\"ternary-demo\">\n <xsl:with-param name=\"a\" select=\"4\"/>\n <xsl:with-param name=\"b\">3</xsl:with-param>\n <xsl:with-param name=\"c\" select=\"2 + 3\"/>\n </xsl:call-template>\n </working>\n <broken note=\"When the third parameter 'c' is omitted\">\n <xsl:call-template name=\"ternary-demo\">\n <xsl:with-param name=\"a\" select=\"4\"/>\n <xsl:with-param name=\"b\">3</xsl:with-param>\n </xsl:call-template>\n </broken>\n\n <!-- Calling a function with optional arguments -->\n <!-- With the optional third parameter -->\n <working name=\"When all parameters are supplied\">\n <xsl:call-template name=\"binary-or-ternary-demo\">\n <xsl:with-param name=\"a\" select=\"4\"/>\n <xsl:with-param name=\"b\" select=\"3\"/>\n <xsl:with-param name=\"c\" select=\"5\"/>\n </xsl:call-template>\n </working>\n <!-- Without the optional third parameter (which defaults to 0) -->\n <working name=\"When 'a' and 'b' are supplied but 'c' is defaulted to 0\">\n <xsl:call-template name=\"binary-or-ternary-demo\">\n <xsl:with-param name=\"a\" select=\"4\"/>\n <xsl:with-param name=\"b\" select=\"3\"/>\n </xsl:call-template>\n </working>\n\n <!-- Calling a function with a variable number of arguments -->\n <!--\n Templates are not varargs-capable. Variable numbers of arguments\n usually appear in the form of a nodeset which is then bound to a\n single parameter name.\n -->\n\n <!-- Calling a function with named arguments -->\n <!--\n Other than what comes with the current context, template\n arguments are always named and can be supplied in any order.\n Templates do not support positional arguments. Additionally,\n even arguments not specified by the template may be passed; they\n are silently ignored.\n -->\n\n <!-- Using a function in first-class context within an expression -->\n <!-- Templates are not first-class values in XSLT 1.0. -->\n\n <!-- Obtaining the return value of a function -->\n <!--\n The output of a template is interpolated into the place of the\n call. Often, this is directly into the output of the transform,\n as with most of the above examples. However, it is also possible\n to bind the output as a variable or parameter. This is useful\n for using templates to compute parameters for other templates or\n for XPath functions.\n -->\n <!-- Which is the least of 34, 78, 12, 56? -->\n <xsl:variable name=\"lesser-demo-result\">\n <!-- The variable is bound to the output of this call -->\n <xsl:call-template name=\"lesser-value\">\n <xsl:with-param name=\"a\">\n <!-- A call as a parameter to another call -->\n <xsl:call-template name=\"lesser-value\">\n <xsl:with-param name=\"a\" select=\"34\"/>\n <xsl:with-param name=\"b\" select=\"78\"/>\n </xsl:call-template>\n </xsl:with-param>\n <xsl:with-param name=\"b\">\n <!-- and again -->\n <xsl:call-template name=\"lesser-value\">\n <xsl:with-param name=\"a\" select=\"12\"/>\n <xsl:with-param name=\"b\" select=\"56\"/>\n </xsl:call-template>\n </xsl:with-param>\n </xsl:call-template>\n </xsl:variable>\n <!-- The variable is used here in an XPath expression -->\n <line>\n <xsl:value-of select=\"concat('And the answer, which should be 12, is ', $lesser-demo-result, ', of course.')\"/>\n </line>\n\n <!-- Distinguishing built-in functions and user-defined functions -->\n <!-- Virtually all templates are user-defined. -->\n\n </xsl:template>\n\n <!-- Templates supporting template demos above -->\n <xsl:template match=\"/*\" mode=\"nullary-context-demo-mode\">\n <xsl:call-template name=\"nullary-context-demo\"/>\n </xsl:template>\n\n <xsl:template name=\"nullary-demo\">\n <line>No parameters needed here!</line>\n </xsl:template>\n\n <xsl:template name=\"nullary-context-demo\">\n <!-- When a template is called it has access to the current node of the caller -->\n <xsl:for-each select=\"self::*\">\n <line>The context element here is named \"<xsl:value-of select=\"local-name()\"/>\"</line>\n </xsl:for-each>\n </xsl:template>\n\n <xsl:template name=\"ternary-demo\">\n <!-- This demo requires, at least semantically, all three parameters. -->\n <xsl:param name=\"a\"/>\n <xsl:param name=\"b\"/>\n <xsl:param name=\"c\"/>\n <line>(<xsl:value-of select=\"$a\"/> * <xsl:value-of select=\"$b\"/>) + <xsl:value-of select=\"$c\"/> = <xsl:value-of select=\"($a * $b) + $c\"/></line>\n </xsl:template>\n\n <xsl:template name=\"binary-or-ternary-demo\">\n <!-- This demo requires the first two parameters, but defaults the third to 0 if it is not supplied. -->\n <xsl:param name=\"a\"/>\n <xsl:param name=\"b\"/>\n <xsl:param name=\"c\" select=\"0\"/>\n <line>(<xsl:value-of select=\"$a\"/> * <xsl:value-of select=\"$b\"/>) + <xsl:value-of select=\"$c\"/> = <xsl:value-of select=\"($a * $b) + $c\"/></line>\n </xsl:template>\n\n <xsl:template name=\"lesser-value\">\n <xsl:param name=\"a\"/>\n <xsl:param name=\"b\"/>\n <xsl:choose>\n <xsl:when test=\"number($a) &lt; number($b)\">\n <xsl:value-of select=\"$a\"/>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"$b\"/>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:template>\n</xsl:stylesheet>\n", "language": "XSLT" }, { "code": "sub test(a, b, c) :\tprint a, b, c : end sub\n\ntest(1, 2, 3)\t// show 1 2 3\ntest(1, 2)\t// show 1 2 0\n\nexecute(\"test\", 1, 2, 3)\t// show 1 2 3\n\nsub test$(a$)\t// show all members of a \"list\"\n\tlocal n, i, t$(1)\n\t\n\tn = token(a$, t$(), \", \")\n\tfor i = 1 to n\n\t\tprint t$(i), \" \";\n\tnext\nend sub\n\ntest$(\"1, 2, 3, 4, text, 6, 7, 8, \\\"include text\\\"\")\nprint\n", "language": "Yabasic" }, { "code": "PackNibbles:\n;input: B = top nibble, C = bottom nibble. Outputs to accumulator.\n;usage: B = &0X, C = &0Y, => A = &XY\nLD A,B\nAND %00001111\nRLCA\nRLCA\nRLCA\nRLCA\nOR C\nRET\n", "language": "Z80-Assembly" }, { "code": "AddTwoNumbers\n;input registers: A,B. Outputs to A.\nADD a,b\nRET\n", "language": "Z80-Assembly" }, { "code": "f(); f(1,2,3,4);\nfcn f(a=1){}() // define and call f, which gets a set to 1\nfcn{vm.arglist}(1,2,3,4) // arglist is L(1,2,3,4)\nfcn{a1:=vm.nthArg(1)}(1,2,3) // a1 == 2\n(f() == True); (f() and 1 or 2)\nif (f()) println()\nf(f) // pass f to itself\ns:=f()\nfcn{}.isType(self.fcn) //True\nfcn{}.len.isType(self.fcn) //False, len is a Method\n", "language": "Zkl" }, { "code": "fcn(a,b,c).fp(1)() // call function with a always set to 1\nfcn(a,b,c).fp1(2,3)() // call function with b & c always set to 2 & 3\nfcn(a,b,c,d).fpN(3,5)() // call function with d always set to 5\nfcn{vm.arglist}.fpN(3,66)(1,2,3,4,5) //-->L(1,2,3,66,4,5)\nfcn{}.fpM(\"01-\",5) // use a mask to select parameters\n // 1 is supplied, 0 is get upon call, - is chop arglist\nfcn{vm.arglist}.fpM(\"01-\",66)(1,2,3,4) //-->L(1,66)\n\na:=5; f('wrap(b){a+b}) // 'wrap is syntactic sugar for .fpN\n // to create a lexical closure --> f(fcn(b,a){a+b}.fpN(1,a))\n", "language": "Zkl" }, { "code": "module CallingProcs;\n\ttype\n\t\t{public} Vector = array {math} * of integer;\n\n\tvar\n\t\tnums: array {math} 4 of integer;\n\t\tints: Vector;\n\t\ttotal: integer;\n\n\t\tprocedure Init(): boolean; (* private by default *)\n\t\tbegin\n\t\t\tnums := [1,2,3,4];\n\t\t\tints := new Vector(5);\n\t\t\tints := [2,4,6,8,10];\n\t\t\treturn true;\n\t\tend Init;\n\n\t\t(* function *)\n\t\tprocedure Sum(v: Vector): integer;\n\t\tvar\n\t\t\ti,s: integer;\n\t\tbegin\n\t\t\ts := 0;\n\t\t\tfor i := 0 to len(v) - 1 do\n\t\t\t\t(* inc is a predefined subroutine *)\n\t\t\t\tinc(s,v[i])\n\t\t\tend;\n\t\t\treturn s\n\t\tend Sum;\n\n\t\t(* subroutine\n\t\t * @param v: by value\n\t\t * @param t: by reference\n\t\t *)\n\t\tprocedure Sum2(v: array {math} * of integer; var t: integer);\n\t\tvar\t\n\t\t\ti: integer;\n\t\tbegin\n\t\t\tt := 0;\n\t\t\tfor i := 0 to len(v) - 1 do\n\t\t\t\tinc(t,v[i])\n\t\t\tend\t\n\t\tend Sum2;\n\tbegin\n\t\tInit; (* calling a function without parameters *)\n\t\ttotal := Sum(nums);\n\t\twriteln(total);\n\t\t(* optional arguments not supported *)\n\t\t(* variable arguments through open arrays *)\n\t\twriteln(Sum(ints));\n\t\t(* named arguments not supported *)\n\t\tints := [1,3,5,7,9];\n\t\tSum2(ints,total);\n\t\twriteln(total);\n\tend CallingProcs.\n", "language": "Zonnon" }, { "code": "10 REM functions cannot be called in statement context\n20 PRINT FN a(5): REM The function is used in first class context. Arguments are not named\n30 PRINT FN b(): REM Here we call a function that has no arguments\n40 REM subroutines cannot be passed parameters, however variables are global\n50 LET n=1: REM This variable will be visible to the called subroutine\n60 GO SUB 1000: REM subroutines are called by line number and do not have names\n70 REM subroutines do not return a value, but we can see any variables it defined\n80 REM subroutines cannot be used in first class context\n90 REM builtin functions are used in first class context, and do not need the FN keyword prefix\n100 PRINT SIN(50): REM here we pass a parameter to a builtin function\n110 PRINT RND(): REM here we use a builtin function without parameters\n120 RANDOMIZE: REM statements are not functions and cannot be used in first class context.\n", "language": "ZX-Spectrum-Basic" } ]
Call-a-function
[ { "code": "---\ncategory:\n- Functions and subroutines\nfrom: http://rosettacode.org/wiki/Call_a_function_in_a_shared_library\nnote: Programming environment operations\n", "language": "00-META" }, { "code": "Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.\n\nThis is a special case of [[Call foreign language function|calling a foreign language function]] where the focus is close to the [https://en.wikipedia.org/wiki/Application_binary_interface ABI] level and not at the normal API level.\n\n\n;Related task:\n* [[OpenGL]] -- OpenGL is usually maintained as a shared library.\n<br><br>\n", "language": "00-TASK" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\nwith Interfaces; use Interfaces;\nwith Interfaces.C; use Interfaces.C;\nwith System; use System;\n\nwith Ada.Unchecked_Conversion;\n\nprocedure Shared_Library_Call is\n --\n -- Interface to kernel32.dll which is responsible for loading DLLs under Windows.\n -- There are ready to use Win32 bindings. We don't want to use them here.\n --\n type HANDLE is new Unsigned_32; -- on x64 system, replace by Unsigned_64 to make it work\n function LoadLibrary (lpFileName : char_array) return HANDLE;\n pragma Import (stdcall, LoadLibrary, \"LoadLibrary\", \"_LoadLibraryA\"); -- Ada95 does not have the @n suffix.\n\n function GetProcAddress (hModule : HANDLE; lpProcName : char_array)\n return Address;\n pragma Import (stdcall, GetProcAddress, \"GetProcAddress\", \"_GetProcAddress\"); --\n --\n -- The interface of the function we want to call. It is a pointer (access type)\n -- because we will link it dynamically. The function is from User32.dll\n --\n type MessageBox is access function\n ( hWnd : Address := Null_Address;\n lpText : char_array;\n lpCaption : char_array := To_C (\"Greeting\");\n uType : Unsigned_16 := 0\n ) return Integer_16;\n pragma Convention (Stdcall, MessageBox);\n function To_MessageBox is new Ada.Unchecked_Conversion (Address, MessageBox);\n\n Library : HANDLE := LoadLibrary (To_C (\"user32.dll\"));\n Pointer : Address := GetProcAddress (Library, To_C (\"MessageBoxA\"));\nbegin\n if Pointer /= Null_Address then\n declare\n Result : Integer_16;\n begin\n Result := To_MessageBox (Pointer) (lpText => To_C (\"Hello!\"));\n end;\n else\n Put_Line (\"Unable to load the library \" & HANDLE'Image (Library));\n end if;\nend Shared_Library_Call;\n", "language": "Ada" }, { "code": "with Ada.Environment_Variables; use Ada.Environment_Variables;\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Interfaces; use Interfaces;\nwith Interfaces.C; use Interfaces.C;\nwith System; use System;\n\nwith Ada.Unchecked_Conversion;\n\nprocedure Shared_Library_Call is\n --\n -- Interface to libdl to load dynamically linked libraries\n --\n function dlopen (FileName : char_array; Flag : int) return Address;\n pragma Import (C, dlopen);\n\n function dlsym (Handle : address; Symbol : char_array) return Address;\n pragma Import (C, dlsym);\n --\n -- The interfaces of the functions we want to call. These are pointers\n -- (access type) because we will link it dynamically. The functions\n -- come from libX11.so.\n --\n type XOpenDisplay is access function (Display_Name : char_array) return Address;\n pragma Convention (C, XOpenDisplay);\n function To_Ptr is new Ada.Unchecked_Conversion (Address, XOpenDisplay);\n\n type XDisplayWidth is access function (Display : Address; Screen : int) return int;\n pragma Convention (C, XDisplayWidth);\n function To_Ptr is new Ada.Unchecked_Conversion (Address, XDisplayWidth);\n\n Library : Address := dlopen (To_C (\"libX11.so\"), 1);\n OpenDisplay : XOpenDisplay := To_Ptr (dlsym (Library, To_C (\"XOpenDisplay\")));\n DisplayWidth : XDisplayWidth := To_Ptr (dlsym (Library, To_C (\"XDisplayWidth\")));\nbegin\n if OpenDisplay /= null and then DisplayWidth /= null then\n declare\n Display : Address;\n begin\n Display := OpenDisplay (To_C (Value (\"DISPLAY\")));\n if Display = Null_Address then\n Put_Line (\"Unable to open display \" & Value (\"DISPLAY\"));\n else\n Put_Line (Value (\"DISPLAY\") & \" width is\" & int'image (DisplayWidth (Display, 0)));\n end if;\n end;\n else\n Put_Line (\"Unable to load the library\");\n end if;\nend Shared_Library_Call;\n", "language": "Ada" }, { "code": "getCurlVersion: function [][\n try? [\n call.external:'curl \"curl_version\" .expect: :string []\n ]\n else [\n \"library not found\"\n ]\n]\n\nprint [\"curl version:\" getCurlVersion]\n", "language": "Arturo" }, { "code": "ahkdll := DllCall(\"LoadLibrary\", \"str\", \"AutoHotkey.dll\")\nclientHandle := DllCall(\"AutoHotkey\\ahkdll\", \"str\", \"dllclient.ahk\", \"str\"\n, \"\", \"str\", \"parameter1 parameter2\", \"Cdecl Int\")\n", "language": "AutoHotkey" }, { "code": "Msgbox, hello from client\n", "language": "AutoHotkey" }, { "code": "' Call a dynamic library function\nPROTO j0\nbessel0 = j0(1.0)\nPRINT bessel0\n", "language": "BaCon" }, { "code": " SYS \"MessageBox\", @hwnd%, \"This is a test message\", 0, 0\n", "language": "BBC-BASIC" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <dlfcn.h>\n\nint myopenimage(const char *in)\n{\n static int handle=0;\n fprintf(stderr, \"internal openimage opens %s...\\n\", in);\n return handle++;\n}\n\nint main()\n{\n void *imglib;\n int (*extopenimage)(const char *);\n int imghandle;\n\n imglib = dlopen(\"./fakeimglib.so\", RTLD_LAZY);\n if ( imglib != NULL ) {\n /* extopenimage = (int (*)(const char *))dlsym(imglib,...)\n \"man dlopen\" says that C99 standard leaves casting from\n \"void *\" to a function pointer undefined. The following is the\n POSIX.1-2003 workaround found in man */\n *(void **)(&extopenimage) = dlsym(imglib, \"openimage\");\n /* the following works with gcc, gives no warning even with\n -Wall -std=c99 -pedantic options... :D */\n /* extopenimage = dlsym(imglib, \"openimage\"); */\n imghandle = extopenimage(\"fake.img\");\n } else {\n imghandle = myopenimage(\"fake.img\");\n }\n printf(\"opened with handle %d\\n\", imghandle);\n /* ... */\n if (imglib != NULL ) dlclose(imglib);\n return EXIT_SUCCESS;\n}\n", "language": "C" }, { "code": "#include <stdio.h>\n/* gcc -shared -nostartfiles fakeimglib.c -o fakeimglib.so */\nint openimage(const char *s)\n{\n static int handle = 100;\n fprintf(stderr, \"opening %s\\n\", s);\n return handle++;\n}\n", "language": "C" }, { "code": "using System.Runtime.InteropServices;\n\nclass Program {\n [DllImport(\"fakelib.dll\")]\n public static extern int fakefunction(int args);\n\n static void Main(string[] args) {\n int r = fakefunction(10);\n }\n}\n", "language": "C-sharp" }, { "code": " identification division.\n program-id. callsym.\n\n data division.\n working-storage section.\n 01 handle usage pointer.\n 01 addr usage program-pointer.\n\n procedure division.\n call \"dlopen\" using\n by reference null\n by value 1\n returning handle\n on exception\n display function exception-statement upon syserr\n goback\n end-call\n if handle equal null then\n display function module-id \": error getting dlopen handle\"\n upon syserr\n goback\n end-if\n\n call \"dlsym\" using\n by value handle\n by content z\"perror\"\n returning addr\n end-call\n if addr equal null then\n display function module-id \": error getting perror symbol\"\n upon syserr\n else\n call addr returning omitted\n end-if\n\n goback.\n end program callsym.\n", "language": "COBOL" }, { "code": "CL-USER> (cffi:load-foreign-library \"libX11.so\")\n#<CFFI::FOREIGN-LIBRARY {1004F4ECC1}>\nCL-USER> (cffi:foreign-funcall \"XOpenDisplay\"\n :string #+sbcl (sb-posix:getenv \"DISPLAY\")\n #-sbcl \":0.0\"\n :pointer)\n#.(SB-SYS:INT-SAP #X00650FD0)\n", "language": "Common-Lisp" }, { "code": "libm = LibC.dlopen(\"libm.so.6\", LibC::RTLD_LAZY)\nsqrtptr = LibC.dlsym(libm, \"sqrt\") unless libm.null?\n\nif sqrtptr\n sqrtproc = Proc(Float64, Float64).new sqrtptr, Pointer(Void).null\n at_exit { LibC.dlclose(libm) }\nelse\n sqrtproc = ->Math.sqrt(Float64)\nend\n\nputs \"the sqrt of 4 is #{sqrtproc.call(4.0)}\"\n", "language": "Crystal" }, { "code": "pragma(lib, \"user32.lib\");\n\nimport std.stdio, std.c.windows.windows;\n\nextern(Windows) UINT GetDoubleClickTime();\n\nvoid main() {\n writeln(GetDoubleClickTime());\n}\n", "language": "D" }, { "code": "int add(int num1, int num2) {\n\treturn num1 + num2;\n}\n", "language": "Dart" }, { "code": "import 'dart:ffi'\nshow DynamicLibrary, NativeFunction, Int32;\n\nmain(){\n\tfinal lib = DynamicLibrary.open('add.dylib'); // Load library\n\n\tfinal int Function(int num1,int num2) add = lib // Write Dart function binding\n\t\t.lookup<NativeFunction<Int32 Function( Int32, Int32 )>>('add') // Lookup function in library\n\t\t.asFunction(); // convert to Dart Function\n\n\tprint( add( 1, 2 ) );\n}\n", "language": "Dart" }, { "code": "procedure DoSomething; external 'MYLIB.DLL';\n", "language": "Delphi" }, { "code": "procedure DoSomething; external 'MYLIB.DLL' delayed;\n", "language": "Delphi" }, { "code": "var\n lLibraryHandle: THandle;\n lDoSomething: procedure; stdcall;\nbegin\n lLibraryHandle := LoadLibrary('MYLIB.DLL');\n if lLibraryHandle >= 32 then { success }\n begin\n lDoSomething := GetProcAddress(lLibraryHandle, 'DoSomething');\n lDoSomething();\n FreeLibrary(lLibraryHandle);\n end;\nend;\n", "language": "Delphi" }, { "code": "c-library math\n\ns\" m\" add-lib\n\\c #include <math.h>\nc-function gamma tgamma r -- r\n\nend-c-library\n", "language": "Forth" }, { "code": "double add_n(double* a, double* b)\n{\nreturn *a + *b;\n}\n", "language": "Fortran" }, { "code": "function add_nf(a,b) bind(c, name='add_nf')\nuse, intrinsic :: iso_c_binding\nimplicit none\nreal(c_double), intent(in) :: a,b\nreal(c_double) :: add_nf\n\nadd_nf = a + b\nend function add_nf\n", "language": "Fortran" }, { "code": "!-----------------------------------------------------------------------\n!module dll_module\n!-----------------------------------------------------------------------\nmodule dll_module\n use iso_c_binding\n implicit none\n private ! all by default\n public :: os_type, dll_type, load_dll, free_dll, init_os_type, init_dll\n ! general constants:\n ! the number of bits in an address (32-bit or 64-bit).\n integer, parameter :: bits_in_addr = c_intptr_t*8\n ! global error-level variables:\n integer, parameter :: errid_none = 0\n integer, parameter :: errid_info = 1\n integer, parameter :: errid_warn = 2\n integer, parameter :: errid_severe = 3\n integer, parameter :: errid_fatal = 4\n\n integer :: os_id\n\n type os_type\n character(10) :: endian\n character(len=:), allocatable :: newline\n character(len=:), allocatable :: os_desc\n character(1) :: pathsep\n character(1) :: swchar\n character(11) :: unfform\n end type os_type\n\n type dll_type\n integer(c_intptr_t) :: fileaddr\n type(c_ptr) :: fileaddrx\n type(c_funptr) :: procaddr\n character(1024) :: filename\n character(1024) :: procname\n end type dll_type\n\n ! interface to linux API\n interface\n function dlopen(filename,mode) bind(c,name=\"dlopen\")\n ! void *dlopen(const char *filename, int mode);\n use iso_c_binding\n implicit none\n type(c_ptr) :: dlopen\n character(c_char), intent(in) :: filename(*)\n integer(c_int), value :: mode\n end function\n\n function dlsym(handle,name) bind(c,name=\"dlsym\")\n ! void *dlsym(void *handle, const char *name);\n use iso_c_binding\n implicit none\n type(c_funptr) :: dlsym\n type(c_ptr), value :: handle\n character(c_char), intent(in) :: name(*)\n end function\n\n function dlclose(handle) bind(c,name=\"dlclose\")\n ! int dlclose(void *handle);\n use iso_c_binding\n implicit none\n integer(c_int) :: dlclose\n type(c_ptr), value :: handle\n end function\n end interface\n\ncontains\n\n\n !-----------------------------------------------------------------------\n !Subroutine init_dll\n !-----------------------------------------------------------------------\n subroutine init_dll(dll)\n implicit none\n type(dll_type), intent(inout) :: dll\n dll % fileaddr = 0\n dll % fileaddrx = c_null_ptr\n dll % procaddr = c_null_funptr\n dll % filename = \" \"\n dll % procname = \" \"\n end subroutine init_dll\n\n !-----------------------------------------------------------------------\n !Subroutine init_os_type\n !-----------------------------------------------------------------------\n subroutine init_os_type(os_id,os)\n implicit none\n integer, intent(in) :: os_id\n type(os_type), intent(inout) :: os\n\n select case (os_id)\n case (1) ! Linux\n\n os % endian = 'big_endian'\n os % newline = achar(10)\n os % os_desc = 'Linux'\n os % pathsep = '/'\n os % swchar = '-'\n os % unfform = 'unformatted'\n\n case (2) ! MacOS\n\n os % endian = 'big_endian'\n os % newline = achar(10)\n os % os_desc = 'MacOS'\n os % pathsep = '/'\n os % swchar = '-'\n os % unfform = 'unformatted'\n\n case default\n\n end select\n\n end subroutine init_os_type\n\n !-----------------------------------------------------------------------\n !Subroutine load_dll\n !-----------------------------------------------------------------------\n subroutine load_dll (os, dll, errstat, errmsg )\n ! this subroutine is used to dynamically load a dll.\n\n\n type (os_type), intent(in) :: os\n type (dll_type), intent(inout) :: dll\n integer, intent( out) :: errstat\n character(*), intent( out) :: errmsg\n\n integer(c_int), parameter :: rtld_lazy=1\n integer(c_int), parameter :: rtld_now=2\n integer(c_int), parameter :: rtld_global=256\n integer(c_int), parameter :: rtld_local=0\n\n errstat = errid_none\n errmsg = ''\n\n select case (os%os_desc)\n case (\"Linux\",\"MacOS\")\n ! load the dll and get the file address:\n dll%fileaddrx = dlopen( trim(dll%filename)//c_null_char, rtld_lazy )\n if( .not. c_associated(dll%fileaddrx) ) then\n errstat = errid_fatal\n write(errmsg,'(i2)') bits_in_addr\n errmsg = 'the dynamic library '//trim(dll%filename)//' could not be loaded. check that the file '// &\n 'exists in the specified location and that it is compiled for '//trim(errmsg)//'-bit systems.'\n return\n end if\n\n ! get the procedure address:\n dll%procaddr = dlsym( dll%fileaddrx, trim(dll%procname)//c_null_char )\n if(.not. c_associated(dll%procaddr)) then\n errstat = errid_fatal\n errmsg = 'the procedure '//trim(dll%procname)//' in file '//trim(dll%filename)//' could not be loaded.'\n return\n end if\n\n case (\"Windows\")\n errstat = errid_fatal\n errmsg = ' load_dll not implemented for '//trim(os%os_desc)\n\n case default\n errstat = errid_fatal\n errmsg = ' load_dll not implemented for '//trim(os%os_desc)\n end select\n return\n end subroutine load_dll\n\n !-----------------------------------------------------------------------\n !Subroutine free_dll\n !-----------------------------------------------------------------------\n subroutine free_dll (os, dll, errstat, errmsg )\n\n ! this subroutine is used to free a dynamically loaded dll\n type (os_type), intent(in) :: os\n type (dll_type), intent(inout) :: dll\n integer, intent( out) :: errstat\n character(*), intent( out) :: errmsg\n\n integer(c_int) :: success\n\n errstat = errid_none\n errmsg = ''\n\n select case (os%os_desc)\n case (\"Linux\",\"MacOS\")\n\n ! close the library:\n success = dlclose( dll%fileaddrx )\n if ( success /= 0 ) then\n errstat = errid_fatal\n errmsg = 'the dynamic library could not be freed.'\n return\n else\n errstat = errid_none\n errmsg = ''\n end if\n\n case (\"Windows\")\n\n errstat = errid_fatal\n errmsg = ' free_dll not implemented for '//trim(os%os_desc)\n\n case default\n errstat = errid_fatal\n errmsg = ' free_dll not implemented for '//trim(os%os_desc)\n end select\n\n return\n end subroutine free_dll\nend module dll_module\n\n\n\n!-----------------------------------------------------------------------\n!Main program\n!-----------------------------------------------------------------------\nprogram test_load_dll\n use, intrinsic :: iso_c_binding\n use dll_module\n implicit none\n\n ! interface to our shared lib\n abstract interface\n function add_n(a,b)\n use, intrinsic :: iso_c_binding\n implicit none\n real(c_double), intent(in) :: a,b\n real(c_double) :: add_n\n end function add_n\n end interface\n\n type(os_type) :: os\n type(dll_type) :: dll\n integer :: errstat\n character(1024) :: errmsg\n type(c_funptr) :: cfun\n procedure(add_n), pointer :: fproc\n\n call init_os_type(1,os)\n call init_dll(dll)\n\n dll%filename=\"/full_path_to/shared_lib/shared_lib_new.so\"\n ! name of the procedure in shared_lib\n ! c version of the function\n dll%procname=\"add_n\"\n\n write(*,*) \"address: \", dll%procaddr\n\n call load_dll(os, dll, errstat, errmsg )\n write(*,*)\"load_dll: errstat=\", errstat\n write(*,*) \"address: \", dll%procaddr\n\n call c_f_procpointer(dll%procaddr,fproc)\n\n write(*,*) \"add_n(2,5)=\",fproc(2.d0,5.d0)\n\n call free_dll (os, dll, errstat, errmsg )\n write(*,*)\"free_dll: errstat=\", errstat\n\n ! fortran version\n dll%procname=\"add_nf\"\n\n call load_dll(os, dll, errstat, errmsg )\n write(*,*)\"load_dll: errstat=\", errstat\n write(*,*) \"address: \", dll%procaddr\n\n call c_f_procpointer(dll%procaddr,fproc)\n\n write(*,*) \"add_nf(2,5)=\",fproc(2.d0,5.d0)\n\n call free_dll (os, dll, errstat, errmsg )\n write(*,*)\"free_dll: errstat=\", errstat\n\n\nend program test_load_dll\n", "language": "Fortran" }, { "code": "function ffun(x, y)\n implicit none\n !DEC$ ATTRIBUTES DLLEXPORT, STDCALL, REFERENCE :: FFUN\n double precision :: x, y, ffun\n ffun = x + y * y\nend function\n", "language": "Fortran" }, { "code": "program dynload\n use kernel32\n use iso_c_binding\n implicit none\n\n abstract interface\n function ffun_int(x, y)\n !DEC$ ATTRIBUTES STDCALL, REFERENCE :: ffun_int\n double precision :: ffun_int, x, y\n end function\n end interface\n\n procedure(ffun_int), pointer :: ffun_ptr\n\n integer(c_intptr_t) :: ptr\n integer(handle) :: h\n double precision :: x, y\n\n h = LoadLibrary(\"dllfun.dll\" // c_null_char)\n if (h == 0) error stop \"Error: LoadLibrary\"\n\n ptr = GetProcAddress(h, \"ffun\" // c_null_char)\n if (ptr == 0) error stop \"Error: GetProcAddress\"\n\n call c_f_procpointer(transfer(ptr, c_null_funptr), ffun_ptr)\n read *, x, y\n print *, ffun_ptr(x, y)\n\n if (FreeLibrary(h) == 0) error stop \"Error: FreeLibrary\"\nend program\n", "language": "Fortran" }, { "code": "function ffun(x, y)\n implicit none\n !GCC$ ATTRIBUTES DLLEXPORT, STDCALL :: FFUN\n double precision :: x, y, ffun\n ffun = x + y * y\nend function\n", "language": "Fortran" }, { "code": "program dynload\n use kernel32\n use iso_c_binding\n implicit none\n\n abstract interface\n function ffun_int(x, y)\n !GCC$ ATTRIBUTES DLLEXPORT, STDCALL :: FFUN\n double precision :: ffun_int, x, y\n end function\n end interface\n\n procedure(ffun_int), pointer :: ffun_ptr\n\n integer(c_intptr_t) :: ptr\n integer(handle) :: h\n double precision :: x, y\n\n h = LoadLibrary(\"dllfun.dll\" // c_null_char)\n if (h == 0) error stop \"Error: LoadLibrary\"\n\n ptr = GetProcAddress(h, \"ffun_@8\" // c_null_char)\n if (ptr == 0) error stop \"Error: GetProcAddress\"\n\n call c_f_procpointer(transfer(ptr, c_null_funptr), ffun_ptr)\n read *, x, y\n print *, ffun_ptr(x, y)\n\n if (FreeLibrary(h) == 0) error stop \"Error: FreeLibrary\"\nend program\n", "language": "Fortran" }, { "code": "module kernel32\n use iso_c_binding\n implicit none\n integer, parameter :: HANDLE = C_INTPTR_T\n integer, parameter :: PVOID = C_INTPTR_T\n integer, parameter :: BOOL = C_INT\n\n interface\n function LoadLibrary(lpFileName) bind(C, name=\"LoadLibraryA\")\n import C_CHAR, HANDLE\n !GCC$ ATTRIBUTES STDCALL :: LoadLibrary\n integer(HANDLE) :: LoadLibrary\n character(C_CHAR) :: lpFileName\n end function\n end interface\n\n interface\n function FreeLibrary(hModule) bind(C, name=\"FreeLibrary\")\n import HANDLE, BOOL\n !GCC$ ATTRIBUTES STDCALL :: FreeLibrary\n integer(BOOL) :: FreeLibrary\n integer(HANDLE), value :: hModule\n end function\n end interface\n\n interface\n function GetProcAddress(hModule, lpProcName) bind(C, name=\"GetProcAddress\")\n import C_CHAR, PVOID, HANDLE\n !GCC$ ATTRIBUTES STDCALL :: GetProcAddress\n integer(PVOID) :: GetProcAddress\n integer(HANDLE), value :: hModule\n character(C_CHAR) :: lpProcName\n end function\n end interface\nend module\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\n' Attempt to call Beep function in Win32 API\nDim As Any Ptr library = DyLibLoad(\"kernel32.dll\") '' load dll\n\nIf library = 0 Then\n Print \"Unable to load kernel32.dll - calling built in Beep function instead\"\n Beep : Beep : Beep\nElse\n Dim beep_ As Function (ByVal As ULong, ByVal As ULong) As Long '' declare function pointer\n beep_ = DyLibSymbol(library, \"Beep\")\n If beep_ = 0 Then\n Print \"Unable to retrieve Beep function from kernel32.dll - calling built in Beep function instead\"\n Beep : Beep : Beep\n Else\n For i As Integer = 1 To 3 : beep_(1000, 250) : Next\n End If\n DyLibFree(library) '' unload library\nEnd If\n\nPrint\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "include \"tlbx GameplayKit.incl\"\n\nUInt64 randomInteger\nNSUInteger i\n\nfor i = 1 to 20\n randomInteger = fn GKLinearCongruentialRandomSourceSeed( fn GKLinearCongruentialRandomSourceInit )\n print randomInteger\nnext\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "#include <stdio.h>\n/* gcc -shared -fPIC -nostartfiles fakeimglib.c -o fakeimglib.so */\nint openimage(const char *s)\n{\n static int handle = 100;\n fprintf(stderr, \"opening %s\\n\", s);\n return handle++;\n}\n", "language": "Go" }, { "code": "package main\n\n/*\n#cgo LDFLAGS: -ldl\n\n#include <stdlib.h>\n#include <dlfcn.h>\n\ntypedef int (*someFunc) (const char *s);\n\nint bridge_someFunc(someFunc f, const char *s) {\n return f(s);\n}\n*/\nimport \"C\"\nimport (\n \"fmt\"\n \"os\"\n \"unsafe\"\n)\n\nvar handle = -1\n\nfunc myOpenImage(s string) int {\n fmt.Fprintf(os.Stderr, \"internal openImage opens %s...\\n\", s)\n handle++\n return handle\n}\n\nfunc main() {\n libpath := C.CString(\"./fakeimglib.so\")\n defer C.free(unsafe.Pointer(libpath))\n imglib := C.dlopen(libpath, C.RTLD_LAZY)\n var imghandle int\n if imglib != nil {\n openimage := C.CString(\"openimage\")\n defer C.free(unsafe.Pointer(openimage))\n fp := C.dlsym(imglib, openimage)\n if fp != nil {\n fi := C.CString(\"fake.img\")\n defer C.free(unsafe.Pointer(fi))\n imghandle = int(C.bridge_someFunc(C.someFunc(fp), fi))\n\n } else {\n imghandle = myOpenImage(\"fake.img\")\n }\n C.dlclose(imglib)\n } else {\n imghandle = myOpenImage(\"fake.img\")\n }\n fmt.Printf(\"opened with handle %d\\n\", imghandle)\n}\n", "language": "Go" }, { "code": "#!/usr/bin/env stack\n-- stack --resolver lts-6.33 --install-ghc runghc --package unix\n\nimport Control.Exception ( try )\nimport Foreign ( FunPtr, allocaBytes )\nimport Foreign.C\n ( CSize(..), CString, withCAStringLen, peekCAStringLen )\nimport System.Info ( os )\nimport System.IO.Error ( ioeGetErrorString )\nimport System.IO.Unsafe ( unsafePerformIO )\nimport System.Posix.DynamicLinker\n ( RTLDFlags(RTLD_LAZY), dlsym, dlopen )\n\ndlSuffix :: String\ndlSuffix = if os == \"darwin\" then \".dylib\" else \".so\"\n\ntype RevFun = CString -> CString -> CSize -> IO ()\n\nforeign import ccall \"dynamic\"\n mkFun :: FunPtr RevFun -> RevFun\n\ncallRevFun :: RevFun -> String -> String\ncallRevFun f s = unsafePerformIO $ withCAStringLen s $ \\(cs, len) -> do\n allocaBytes len $ \\buf -> do\n f buf cs (fromIntegral len)\n peekCAStringLen (buf, len)\n\ngetReverse :: IO (String -> String)\ngetReverse = do\n lib <- dlopen (\"libcrypto\" ++ dlSuffix) [RTLD_LAZY]\n fun <- dlsym lib \"BUF_reverse\"\n return $ callRevFun $ mkFun fun\n\nmain = do\n x <- try getReverse\n let (msg, rev) =\n case x of\n Left e -> (ioeGetErrorString e ++ \"; using fallback\", reverse)\n Right f -> (\"Using BUF_reverse from OpenSSL\", f)\n putStrLn msg\n putStrLn $ rev \"a man a plan a canal panama\"\n", "language": "Haskell" }, { "code": "require 'dll'\nstrdup=: 'msvcrt.dll _strdup >x *' cd <\nfree=: 'msvcrt.dll free n x' cd <\ngetstr=: free ] memr@,&0 _1\n\nDupStr=:verb define\n try.\n getstr@strdup y\n catch.\n y\n end.\n)\n", "language": "J" }, { "code": " DupStr 'hello'\nhello\n getstr@strdup ::] 'hello'\nhello\n", "language": "J" }, { "code": "/* TrySort.java */\n\nimport java.util.Collections;\nimport java.util.Random;\n\npublic class TrySort {\n static boolean useC;\n static {\n\ttry {\n\t System.loadLibrary(\"TrySort\");\n\t useC = true;\n\t} catch(UnsatisfiedLinkError e) {\n\t useC = false;\n\t}\n }\n\n static native void sortInC(int[] ary);\n\n static class IntList extends java.util.AbstractList<Integer> {\n\tint[] ary;\n\tIntList(int[] ary) { this.ary = ary; }\n\tpublic Integer get(int i) { return ary[i]; }\n\tpublic Integer set(int i, Integer j) {\n\t Integer o = ary[i]; ary[i] = j; return o;\n\t}\n\tpublic int size() { return ary.length; }\n }\n\n static class ReverseAbsCmp\n\timplements java.util.Comparator<Integer>\n {\n\tpublic int compare(Integer pa, Integer pb) {\n\t /* Order from highest to lowest absolute value. */\n\t int a = pa > 0 ? -pa : pa;\n\t int b = pb > 0 ? -pb : pb;\n\t return a < b ? -1 : a > b ? 1 : 0;\n\t}\n }\n\n static void sortInJava(int[] ary) {\n\tCollections.sort(new IntList(ary), new ReverseAbsCmp());\n }\n\n public static void main(String[] args) {\n\t/* Create an array of random integers. */\n\tint[] ary = new int[1000000];\n\tRandom rng = new Random();\n\tfor (int i = 0; i < ary.length; i++)\n\t ary[i] = rng.nextInt();\n\n\t/* Do the reverse sort. */\n\tif (useC) {\n\t System.out.print(\"Sorting in C... \");\n\t sortInC(ary);\n\t} else {\n\t System.out.print\n\t\t(\"Missing library for C! Sorting in Java... \");\n\t sortInJava(ary);\n\t}\n\n\tfor (int i = 0; i < ary.length - 1; i++) {\n\t int a = ary[i];\n\t int b = ary[i + 1];\n\t if ((a > 0 ? -a : a) > (b > 0 ? -b : b)) {\n\t\tSystem.out.println(\"*BUG IN SORT*\");\n\t\tSystem.exit(1);\n\t }\n\t}\n\tSystem.out.println(\"ok\");\n }\n}\n", "language": "Java" }, { "code": "/* TrySort.c */\n\n#include <stdlib.h>\n#include \"TrySort.h\"\n\nstatic void fail(JNIEnv *jenv, const char *error_name) {\n jclass error_class = (*jenv)->FindClass(jenv, error_name);\n (*jenv)->ThrowNew(jenv, error_class, NULL);\n}\n\nstatic int reverse_abs_cmp(const void *pa, const void *pb) {\n jint a = *(jint *)pa;\n jint b = *(jint *)pb;\n a = a > 0 ? -a : a;\n b = b > 0 ? -b : b;\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nvoid Java_TrySort_sortInC(JNIEnv *jenv, jclass obj, jintArray ary) {\n jint *elem, length;\n\n if (ary == NULL) {\n\tfail(jenv, \"java/lang/NullPointerException\");\n\treturn;\n }\n length = (*jenv)->GetArrayLength(jenv, ary);\n elem = (*jenv)->GetPrimitiveArrayCritical(jenv, ary, NULL);\n if (elem == NULL) {\n\tfail(jenv, \"java/lang/OutOfMemoryError\");\n\treturn;\n }\n qsort(elem, length, sizeof(jint), reverse_abs_cmp);\n (*jenv)->ReleasePrimitiveArrayCritical(jenv, ary, elem, 0);\n}\n", "language": "Java" }, { "code": "# Makefile\n\n# Edit the next lines to match your JDK.\nJAVA_HOME = /usr/local/jdk-1.8.0\nCPPFLAGS = -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/openbsd\nJAVAC = $(JAVA_HOME)/bin/javac\nJAVAH = $(JAVA_HOME)/bin/javah\n\nCC = cc\nLDFLAGS = -shared -fPIC\nLIB = libTrySort.so\n\nall: TrySort.class $(LIB)\n\n$(LIB): TrySort.c TrySort.h\n\t$(CC) $(CPPFLAGS) $(LDFLAGS) -o $@ TrySort.c\n\n.SUFFIXES: .class .java .h\n.class.h:\n\trm -f $@\n\t$(JAVAH) -jni -o $@ $(<:.class=)\n.java.class:\n\t$(JAVAC) $<\n\nclean:\n\trm -f TrySort.class TrySort?IntList.class \\\n\t TrySort?ReverseAbsCmp.class TrySort.h $(LIB)\n", "language": "Java" }, { "code": "import com.sun.jna.Library;\nimport com.sun.jna.Native;\n\npublic class LoadLibJNA{\n private interface YourSharedLibraryName extends Library{\n //put shared library functions here with no definition\n public void sharedLibraryfunction();\n }\n\n public static void main(String[] args){\n YourSharedLibraryName lib = (YourSharedLibraryName)Native.loadLibrary(\"sharedLibrary\",//as in \"sharedLibrary.dll\"\n YourSharedLibraryName.class);\n lib.sharedLibraryFunction();\n }\n}\n", "language": "Java" }, { "code": "#!/usr/local/bin/jsish\nload('byjsi.so');\n", "language": "Jsish" }, { "code": " identification division.\n program-id. sample as \"Jsi_Initbyjsi\".\n\n environment division.\n configuration section.\n special-names.\n call-convention 0 is extern.\n repository.\n function all intrinsic.\n\n data division.\n linkage section.\n 01 jsi-interp usage pointer.\n 01 rel usage binary-long.\n\n procedure division using by value jsi-interp rel.\n sample-main.\n if rel equal zero then\n display \"GnuCOBOL from jsish load of \" module-source()\n \" and cobc -m -fimplicit-init\" upon syserr\n goback\n end-if\n\n display \"Called again with: \" jsi-interp \", \" rel upon syserr\n goback.\n end program sample.\n", "language": "Jsish" }, { "code": "#this example works on Windows\nccall( (:GetDoubleClickTime, \"User32\"), stdcall,\n\tUint, (), )\n\nccall( (:clock, \"libc\"), Int32, ())\n", "language": "Julia" }, { "code": "#include <stdio.h>\n/* gcc -shared -fPIC -nostartfiles fakeimglib.c -o fakeimglib.so */\nint openimage(const char *s)\n{\n static int handle = 100;\n fprintf(stderr, \"opening %s\\n\", s);\n return handle++;\n}\n", "language": "Kotlin" }, { "code": "// Kotlin Native version 0.5\n\nimport kotlinx.cinterop.*\nimport platform.posix.*\nimport platform.linux.*\n\ntypealias Func = (String)-> Int\n\nvar handle = 0\n\nfun myOpenImage(s: String): Int {\n fprintf(stderr, \"internal openImage opens %s...\\n\", s)\n return handle++\n}\n\nfun main(args: Array<String>) {\n var imgHandle: Int\n val imglib = dlopen(\"./fakeimglib.so\", RTLD_LAZY)\n if (imglib != null) {\n val fp = dlsym(imglib, \"openimage\")\n if (fp != null) {\n val extOpenImage: CPointer<CFunction<Func>> = fp.reinterpret()\n imgHandle = extOpenImage(\"fake.img\")\n }\n else {\n imgHandle = myOpenImage(\"fake.img\")\n }\n dlclose(imglib)\n }\n else {\n imgHandle = myOpenImage(\"fake.img\")\n }\n println(\"opened with handle $imgHandle\")\n}\n", "language": "Kotlin" }, { "code": "{script\n LAMBDATALK.DICT['BN.*'] = function(){\n var args = arguments[0].split(' '),\n a = new BigNumber( args[0], BN_DEC ),\n b = new BigNumber( args[1], BN_DEC );\n return a.multiply( b )\n };\n", "language": "Lambdatalk" }, { "code": "{BN.* 123456789123456789123456789 123456789123456789123456789}\n-> 15241578780673678546105778281054720515622620750190521\n\nto be compared with the \"standard\" lambdatalk builtin * operator\n\n{* 123456789123456789123456789 123456789123456789123456789}\n-> 1.524157878067368e+52\n", "language": "Lambdatalk" }, { "code": "-- calculate CRC-32 checksum\nstr = \"The quick brown fox jumps over the lazy dog\"\n\n-- is shared library (in Director called \"Xtra\", a DLL in windows, a sharedLib in\n-- OS X) available?\nif ilk(xtra(\"Crypto\"))=#xtra then\n\n -- use shared library\n cx = xtra(\"Crypto\").new()\n crc = cx.cx_crc32_string(str)\n\nelse\n\n -- otherwise use (slower) pure lingo solution\n crcObj = script(\"CRC\").new()\n crc = crcObj.crc32(str)\n\nend if\n", "language": "Lingo" }, { "code": "alien = require(\"alien\")\nmsgbox = alien.User32.MessageBoxA\nmsgbox:types({ ret='long', abi='stdcall', 'long', 'string', 'string', 'long' })\nretval = msgbox(0, 'Please press Yes, No or Cancel', 'The Title', 3)\nprint(retval) --> 6, 7 or 2\n", "language": "Lua" }, { "code": "> cfloor := define_external( floor, s::float[8], RETURN::float[8], LIB = \"libm.so\" ):\n> cfloor( 2.3 );\n 2.\n", "language": "Maple" }, { "code": "Needs[\"NETLink`\"];\nexternalFloor = DefineDLLFunction[\"floor\", \"msvcrt.dll\", \"double\", { \"double\" }];\nexternalFloor[4.2]\n-> 4.\n", "language": "Mathematica" }, { "code": "proc openimage(s: cstring): cint {.importc, dynlib: \"./fakeimglib.so\".}\n\necho openimage(\"foo\")\necho openimage(\"bar\")\necho openimage(\"baz\")\n", "language": "Nim" }, { "code": "#include <stdio.h>\n/* gcc -shared -nostartfiles fakeimglib.c -o fakeimglib.so */\nint openimage(const char *s)\n{\n static int handle = 100;\n fprintf(stderr, \"opening %s\\n\", s);\n return handle++;\n}\n", "language": "Nim" }, { "code": "proc openimage(s: string): int {.importc, dynlib: \"./libfakeimg.so\".}\n\necho openimage(\"foo\")\necho openimage(\"bar\")\necho openimage(\"baz\")\n", "language": "Nim" }, { "code": "# nim c --app:lib fakeimg.nim\nvar handle = 100\n\nproc openimage*(s: string): int {.exportc, dynlib.} =\n stderr.writeln \"opening \", s\n result = handle\n inc(handle)\n", "language": "Nim" }, { "code": "open Dlffi\n\nlet get_int = function Int v -> v | _ -> failwith \"get_int\"\nlet get_ptr = function Ptr v -> v | _ -> failwith \"get_ptr\"\nlet get_float = function Float v -> v | _ -> failwith \"get_float\"\nlet get_double = function Double v -> v | _ -> failwith \"get_double\"\nlet get_string = function String v -> v | _ -> failwith \"get_string\"\n\nlet () =\n (* load the library *)\n let xlib = dlopen \"/usr/lib/libX11.so\" [RTLD_LAZY] in\n (* load the functions *)\n let _open_display = dlsym xlib \"XOpenDisplay\"\n and _default_screen = dlsym xlib \"XDefaultScreen\"\n and _display_width = dlsym xlib \"XDisplayWidth\"\n and _display_height = dlsym xlib \"XDisplayHeight\"\n in\n (* wrap functions to provide a higher level interface *)\n let open_display ~name = get_ptr(fficall _open_display [| String name |] Return_ptr)\n and default_screen ~dpy = get_int(fficall _default_screen [| (Ptr dpy) |] Return_int)\n and display_width ~dpy ~scr = get_int(fficall _display_width [| (Ptr dpy); (Int scr) |] Return_int)\n and display_height ~dpy ~scr = get_int(fficall _display_height [| (Ptr dpy); (Int scr) |] Return_int)\n in\n (* use our functions *)\n let dpy = open_display ~name:\":0\" in\n let screen_number = default_screen ~dpy in\n let width = display_width ~dpy ~scr:screen_number\n and height = display_height ~dpy ~scr:screen_number in\n Printf.printf \"# Screen dimensions are: %d x %d pixels\\n\" width height;\n dlclose xlib;\n;;\n", "language": "OCaml" }, { "code": "(import (otus ffi))\n\n(define self (load-dynamic-library #f))\n(define strdup\n (self type-string \"strdup\" type-string))\n\n(print (strdup \"Hello World!\"))\n", "language": "Ol" }, { "code": "(import (otus ffi))\n\n(define self (load-dynamic-library #f))\n(define strdup\n (let ((strdup (self type-vptr \"strdup\" type-string))\n (free (self fft-void \"free\" type-vptr)))\n (lambda (str)\n (let*((dupped (strdup str))\n (result (vptr->string dupped)))\n (free dupped)\n result))))\n\n(print (strdup \"Hello World!\"))\n", "language": "Ol" }, { "code": "'Loading a shared library at run time and calling a function.\n\ndeclare MessageBox(sys hWnd, String text,caption, sys utype)\n\nsys user32 = LoadLibrary \"user32.dll\"\n\nif user32 then @Messagebox = getProcAddress user32,\"MessageBoxA\"\n\nif @MessageBox then MessageBox 0,\"Hello\",\"OxygenBasic\",0\n\n'...\n\nFreeLibrary user32\n", "language": "OxygenBasic" }, { "code": "install(\"function_name\",\"G\",\"gp_name\",\"./test.gp.so\");\n", "language": "PARI-GP" }, { "code": "use Inline\n C => \"DATA\",\n ENABLE => \"AUTOWRAP\",\n LIBS => \"-lm\";\n\nprint 4*atan(1) . \"\\n\";\n\n__DATA__\n__C__\ndouble atan(double x);\n", "language": "Perl" }, { "code": "use FFI::Platypus;\nmy $ffi = FFI::Platypus->new;\n$ffi->lib(undef);\n$ffi->attach(puts => ['string'] => 'int');\n$ffi->attach(atan => ['double'] => 'double');\n\nputs(4*atan(1));\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span> <span style=\"color: #000080;font-style:italic;\">-- not from a browser, mate!</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">libname</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">funcname</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">WINDOWS</span><span style=\"color: #0000FF;\">?{</span><span style=\"color: #008000;\">\"user32\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"CharLowerA\"</span><span style=\"color: #0000FF;\">}:{</span><span style=\"color: #008000;\">\"libc\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"tolower\"</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">lib</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">open_dll</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">libname</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">func</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">define_c_func</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lib</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">funcname</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">C_INT</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #000000;\">C_INT</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">func</span><span style=\"color: #0000FF;\">=-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #0000FF;\">?{{</span><span style=\"color: #7060A8;\">lower</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">'A'</span><span style=\"color: #0000FF;\">)}}</span> <span style=\"color: #000080;font-style:italic;\">-- (you don't //have// to crash!)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">c_func</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">func</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #008000;\">'A'</span><span style=\"color: #0000FF;\">})</span> <span style=\"color: #000080;font-style:italic;\">-- ('A'==65)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n<!--\n", "language": "Phix" }, { "code": "(load \"@lib/gcc.l\")\n\n(gcc \"x11\" '(\"-lX11\") 'xOpenDisplay 'xCloseDisplay)\n\n#include <X11/Xlib.h>\n\nany xOpenDisplay(any ex) {\n any x = evSym(cdr(ex)); // Get display name\n char display[bufSize(x)]; // Create a buffer for the name\n\n bufString(x, display); // Upack the name\n return boxCnt((long)XOpenDisplay(display));\n}\n\nany xCloseDisplay(any ex) {\n return boxCnt(XCloseDisplay((Display*)evCnt(ex, cdr(ex))));\n}\n/**/\n\n# With that we can open and close the display:\n: (setq Display (xOpenDisplay \":0.7\")) # Wrong\n-> 0\n: (setq Display (xOpenDisplay \":0.0\")) # Correct\n-> 158094320\n: (xCloseDisplay Display)\n-> 0\n", "language": "PicoLisp" }, { "code": ": (setq Display (native \"/usr/lib/libX11.so.6\" \"XOpenDisplay\" 'N \":0.0\"))\n-> 6502688\n: (native \"/usr/lib/libX11.so.6\" \"XCloseDisplay\" 'I Display)\n-> 0\n", "language": "PicoLisp" }, { "code": "#INCLUDE \"Win32API.inc\"\n\nFUNCTION PBMAIN () AS LONG\n DIM hWnd AS LONG\n DIM msg AS ASCIIZ * 14, titl AS ASCIIZ * 8\n\n hWnd = LoadLibrary (\"user32\")\n msg = \"Hello, world!\"\n titl = \"Example\"\n IF ISTRUE (hWnd) THEN\n funcAddr& = GetProcAddress (hWnd, \"MessageBoxA\")\n IF ISTRUE (funcAddr&) THEN\n ASM push 0&\n tAdr& = VARPTR(titl)\n ASM push tAdr&\n mAdr& = VARPTR(msg)\n ASM push mAdr&\n ASM push 0&\n CALL DWORD funcAddr&\n ELSE\n GOTO epicFail\n END IF\n ELSE\n GOTO epicFail\n END IF\n\n GOTO getMeOuttaHere\n\nepicFail:\n MSGBOX msg, , titl\n\ngetMeOuttaHere:\n IF ISTRUE(hWnd) THEN\n tmp& = FreeLibrary (hWnd)\n IF ISFALSE(tmp&) THEN MSGBOX \"Error freeing library... [shrug]\"\n END IF\nEND FUNCTION\n", "language": "PowerBASIC" }, { "code": "if OpenLibrary(0, \"USER32.DLL\")\n *MessageBox = GetFunction(0, \"MessageBoxA\")\n CallFunctionFast(*MessageBox, 0, \"Body\", \"Title\", 0)\n CloseLibrary(0)\nendif\n", "language": "PureBasic" }, { "code": "Prototype.l ProtoMessageBoxW(Window.l, Body.p-unicode, Title.p-unicode, Flags.l = 0)\n\nIf OpenLibrary(0, \"User32.dll\")\n MsgBox.ProtoMessageBoxW = GetFunction(0, \"MessageBoxW\")\n MsgBox(0, \"Hello\", \"World\")\n CloseLibrary(0)\nEndIf\n", "language": "PureBasic" }, { "code": "import ctypes\n\nuser32_dll = ctypes.cdll.LoadLibrary('User32.dll')\nprint user32_dll.GetDoubleClickTime()\n", "language": "Python" }, { "code": ">>> import ctypes\n>>> # libc = ctypes.cdll.msvcrt # Windows\n>>> # libc = ctypes.CDLL('libc.dylib') # Mac\n>>> libc = ctypes.CDLL('libc.so') # Linux and most other *nix\n>>> libc.printf(b'hi there, %s\\n', b'world')\nhi there, world.\n17\n", "language": "Python" }, { "code": ">>> from cffi import FFI\n>>> ffi = FFI()\n>>> ffi.cdef(\"\"\"\n... int printf(const char *format, ...); // copy-pasted from the man page\n... \"\"\")\n>>> C = ffi.dlopen(None) # loads the entire C namespace\n>>> arg = ffi.new(\"char[]\", b\"world\") # equivalent to C code: char arg[] = \"world\";\n>>> C.printf(b\"hi there, %s.\\n\", arg) # call printf\nhi there, world.\n17\n", "language": "Python" }, { "code": "Declare Dynamic Library \"Kernel32\"\n Sub SetLastError (ByVal dwErr As Long)\n Function GetLastError& ()\nEnd Declare\n\nSetLastError 20\nPrint GetLastError\n", "language": "QB64" }, { "code": "dyn.load(\"my/special/R/lib.so\")\n.Call(\"my_lib_fun\", arg1, arg2)\n", "language": "R" }, { "code": ".C(\"my_lib_fun\", arg1, arg2, ret)\n", "language": "R" }, { "code": "#lang racket\n(require ffi/unsafe)\n(define libm (ffi-lib \"libm\")) ; get a handle for the C math library\n; look up sqrt in the math library. if we can't find it, return the builtin sqrt\n(define extern-sqrt (get-ffi-obj 'sqrt libm (_fun _double -> _double)\n (lambda () sqrt)))\n", "language": "Racket" }, { "code": "use NativeCall;\n\nsub XOpenDisplay(Str $s --> int64) is native('X11') {*}\nsub XCloseDisplay(int64 $i --> int32) is native('X11') {*}\n\nif try my $d = XOpenDisplay \":0.0\" {\n say \"ID = $d\";\n XCloseDisplay($d);\n}\nelse {\n say \"No X11 library!\";\n say \"Use this window instead --> ⬜\";\n}\n", "language": "Raku" }, { "code": "/*REXX program calls a function (sysTextScreenSize) in a shared library (regUtil). */\n\n /*Note: the REGUTIL.DLL (REGina UTILity Dynamic Link Library */\n /* should be in the PATH or the current directory. */\n\nrca= rxFuncAdd('sysLoadFuncs', \"regUtil\", 'sysLoadFuncs') /*add a function library. */\nif rca\\==0 then do /*examine the return code.*/\n say 'return code' rca \"from rxFuncAdd\" /*tell about bad \" \" */\n exit rca /*exit this program with RC. */\n end\n\nrcl= sysLoadFuncs() /*we can load the functions. */\nif rcl\\==0 then do /*examine the return code.*/\n say 'return code' rcl \"from sysLoadFuncs\" /*tell about bad \" \" */\n exit rcl /*exit this program with RC. */\n end\n /* [↓] call a function. */\n$= sysTextScreenSize() /*$ has 2 words: rows cols */\nparse var $ rows cols . /*get two numeric words in $.*/\nsay ' rows=' rows /*show number of screen rows.*/\nsay ' cols=' cols /* \" \" \" \" cols.*/\n\nrcd= SysDropFuncs() /*make functions inaccessible*/\nif rcd\\==0 then do /*examine the return code.*/\n say 'return code' rcd \"from sysDropFuncs\" /*tell about bad \" \" */\n exit rcd /*exit this program with RC. */\n end\nexit 0 /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "require 'fiddle/import'\n\nmodule FakeImgLib\n extend Fiddle::Importer\n begin\n dlload './fakeimglib.so'\n extern 'int openimage(const char *)'\n rescue Fiddle::DLError\n # Either fakeimglib or openimage() is missing.\n @@handle = -1\n def openimage(path)\n $stderr.puts \"internal openimage opens #{path}\\n\"\n @@handle += 1\n end\n module_function :openimage\n end\nend\n\nhandle = FakeImgLib.openimage(\"path/to/image\")\nputs \"opened with handle #{handle}\"\n", "language": "Ruby" }, { "code": "# This script shows the width x height of some images.\n# Example:\n# $ ruby imsize.rb dwarf-vs-elf.png swedish-chef.jpg\n# dwarf-vs-elf.png: 242x176\n# swedish-chef.jpg: 256x256\n\nbegin\n require 'rmagick'\n lib = :rmagick\nrescue LoadError\n # Missing rmagick. Try ffi.\n begin\n require 'ffi'\n module F\n extend FFI::Library\n ffi_lib 'MagickWand-6.Q16'\n attach_function :DestroyMagickWand, [:pointer], :pointer\n attach_function :MagickGetImageHeight, [:pointer], :size_t\n attach_function :MagickGetImageWidth, [:pointer], :size_t\n attach_function :MagickPingImage, [:pointer, :string], :bool\n attach_function :MagickWandGenesis, [], :void\n attach_function :NewMagickWand, [], :pointer\n end\n lib = :ffi\n rescue LoadError\n # Missing ffi, MagickWand lib, or function in lib.\n end\nend\n\ncase lib\nwhen :rmagick\n # Returns [width, height] of an image file.\n def size(path)\n img = Magick::Image.ping(path).first\n [img.columns, img.rows]\n end\nwhen :ffi\n F.MagickWandGenesis()\n def size(path)\n wand = F.NewMagickWand()\n F.MagickPingImage(wand, path) or fail 'problem reading image'\n [F.MagickGetImageWidth(wand), F.MagickGetImageHeight(wand)]\n ensure\n F.DestroyMagickWand(wand) if wand\n end\nelse\n PngSignature = \"\\x89PNG\\r\\n\\x1A\\n\".force_encoding('binary')\n def size(path)\n File.open(path, 'rb') do |file|\n # Only works with PNG: https://www.w3.org/TR/PNG/\n # Reads [width, height] from IDHR chunk.\n # Checks height != nil, but doesn't check CRC of chunk.\n sig, width, height = file.read(24).unpack('a8@16NN')\n sig == PngSignature and height or fail 'not a PNG image'\n [width, height]\n end\n end\nend\n\n# Show the size of each image in ARGV.\nstatus = true\nARGV.empty? and (warn \"usage: $0 file...\"; exit false)\nARGV.each do |path|\n begin\n r, c = size(path)\n puts \"#{path}: #{r}x#{c}\"\n rescue\n status = false\n puts \"#{path}: #$!\"\n end\nend\nexit status\n", "language": "Ruby" }, { "code": "#![allow(unused_unsafe)]\nextern crate libc;\n\nuse std::io::{self,Write};\nuse std::{mem,ffi,process};\n\nuse libc::{c_double, RTLD_NOW};\n\n// Small macro which wraps turning a string-literal into a c-string.\n// This is always safe to call, and the resulting pointer has 'static lifetime\nmacro_rules! to_cstr {\n ($s:expr) => {unsafe {ffi::CStr::from_bytes_with_nul_unchecked(concat!($s, \"\\0\").as_bytes()).as_ptr()}}\n}\n\nmacro_rules! from_cstr {\n ($p:expr) => {ffi::CStr::from_ptr($p).to_string_lossy().as_ref() }\n}\n\nfn main() {\n unsafe {\n let handle = libc::dlopen(to_cstr!(\"libm.so.6\"), RTLD_NOW);\n\n if handle.is_null() {\n writeln!(&mut io::stderr(), \"{}\", from_cstr!(libc::dlerror())).unwrap();\n process::exit(1);\n }\n\n let extern_cos = libc::dlsym(handle, to_cstr!(\"cos\"))\n .as_ref()\n .map(mem::transmute::<_,fn (c_double) -> c_double)\n .unwrap_or(builtin_cos);\n println!(\"{}\", extern_cos(4.0));\n }\n}\n\nfn builtin_cos(x: c_double) -> c_double {\n x.cos()\n}\n", "language": "Rust" }, { "code": "import net.java.dev.sna.SNA\nimport com.sun.jna.ptr.IntByReference\n\nobject GetDiskFreeSpace extends App with SNA {\n\n snaLibrary = \"Kernel32\" // Native library name\n/*\n * Important Note!\n *\n * The val holding the SNA-returned function must have the same name as the native function itself\n * (see line following this comment). This is the only place you specify the native function name.\n */\n val GetDiskFreeSpaceA = SNA[String, IntByReference, IntByReference, IntByReference, IntByReference, Boolean]\n\n // This Windows function is described here:\n // http://msdn.microsoft.com/en-us/library/aa364935(v=vs.85).aspx\n val (disk, spc, bps, fc, tc) = (\"C:\\\\\",\n new IntByReference, // Sectors per cluster\n new IntByReference, // Bytes per sector\n new IntByReference, // Free clusters\n new IntByReference) // Total clusters\n\n val ok = GetDiskFreeSpaceA(disk, spc, bps, fc, tc) // status\n println(f\"'$disk%s' ($ok%s): sectors/cluster: ${spc.getValue}%d, bytes/sector: ${bps.getValue}%d, \" +\n f\" free-clusters: ${fc.getValue}%d, total/clusters: ${tc.getValue}%d%n\")\n}}\n", "language": "Scala" }, { "code": "DLD addLibrary: 'fakeimglib'.\n\nObject subclass: ExtLib [\n ExtLib class >> openimage: aString [\n (CFunctionDescriptor isFunction: 'openimage')\n ifTrue: [\n (CFunctionDescriptor for: 'openimage'\n returning: #int\n withArgs: #( #string ) ) callInto: (ValueHolder null).\n ] ifFalse: [ ('internal open image %1' % { aString }) displayNl ]\n ]\n].\n\nExtLib openimage: 'test.png'.\n", "language": "Smalltalk" }, { "code": "-INCLUDE 'ffi.sno'\n\n ffi_m = FFI_DLOPEN('/usr/lib/x86_64-linux-gnu/libm.so')\n ffi_m_hypot = FFI_DLSYM(ffi_m, 'hypot')\n DEFINE_FFI('hypot(double,double)double', ffi_m_hypot)\n\n OUTPUT = hypot(1,2)\n OUTPUT = hypot(2,3)\n OUTPUT = hypot(3,4)\n OUTPUT = hypot(4,5)\n\nEND\n", "language": "SNOBOL4" }, { "code": "package require Ffidl\n\nif {[catch {\n ffidl::callout OpenImage {pointer-utf8} int [ffidl::symbol fakeimglib.so openimage]\n}]} then {\n # Create the OpenImage command by other means here...\n}\nset handle [OpenImage \"/the/file/name\"]\n", "language": "Tcl" }, { "code": "#import std\n#import flo\n\nmy_replacement = fleq/0.?/~& negative\n\nabs = math.|fabs my_replacement\n", "language": "Ursala" }, { "code": "function ffun(x, y)\n implicit none\n !DEC$ ATTRIBUTES DLLEXPORT, STDCALL, REFERENCE :: ffun\n double precision :: x, y, ffun\n ffun = x + y * y\nend function\n", "language": "VBA" }, { "code": "Option Explicit\nDeclare Function ffun Lib \"vbafun\" (ByRef x As Double, ByRef y As Double) As Double\nSub Test()\n Dim x As Double, y As Double\n x = 2#\n y = 10#\n Debug.Print ffun(x, y)\nEnd Sub\n", "language": "VBA" }, { "code": "/* Call_a_function_in_a_shared_library.wren */\n\nvar RTLD_LAZY = 1\n\nforeign class DL {\n construct open(file, mode) {}\n\n foreign call(symbol, arg)\n\n foreign close()\n}\n\nclass My {\n static openimage(s) {\n System.print(\"internal openimage opens %(s)...\")\n if (!__handle) __handle = 0\n __handle = __handle + 1\n return __handle - 1\n }\n}\n\nvar file = \"fake.img\"\nvar imglib = DL.open(\"./fakeimglib.so\", RTLD_LAZY)\nvar imghandle = (imglib != null) ? imglib.call(\"openimage\", file) : My.openimage(file)\nSystem.print(\"opened with handle %(imghandle)\")\nif (imglib != null) imglib.close()\n", "language": "Wren" }, { "code": "/*\n gcc -c -fpic fakeimglib.c\n gcc -shared fakeimglib.o -o fakeimglib.so\n*/\n#include <stdio.h>\n\nint openimage(const char *s) {\n static int handle = 100;\n fprintf(stderr, \"opening %s\\n\", s);\n return handle++;\n}\n", "language": "Wren" }, { "code": "/* gcc Call_a_function_in_a_shared_library.c -o Call_a_function_in_a_shared_library -ldl -lwren -lm */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <dlfcn.h>\n#include \"wren.h\"\n\n/* C <=> Wren interface functions */\n\nvoid C_dlAllocate(WrenVM* vm) {\n const char *file = wrenGetSlotString(vm, 1);\n int mode = (int)wrenGetSlotDouble(vm, 2);\n void *imglib = dlopen(file, mode);\n if (imglib == NULL) wrenSetSlotNull(vm, 0);\n void** pimglib = (void**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(void*));\n *pimglib = imglib;\n}\n\nvoid C_call(WrenVM* vm) {\n void *imglib = *(void**)wrenGetSlotForeign(vm, 0);\n const char *symbol = wrenGetSlotString(vm, 1);\n const char *arg = wrenGetSlotString(vm, 2);\n int (*extopenimage)(const char *);\n extopenimage = dlsym(imglib, symbol);\n int imghandle = extopenimage(arg);\n wrenSetSlotDouble(vm, 0, (double)imghandle);\n}\n\nvoid C_close(WrenVM* vm) {\n void *imglib = *(void**)wrenGetSlotForeign(vm, 0);\n dlclose(imglib);\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n WrenForeignClassMethods methods;\n methods.finalize = NULL;\n if (strcmp(module, \"main\") == 0) {\n if (strcmp(className, \"DL\") == 0) {\n methods.allocate = C_dlAllocate;\n }\n }\n return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n WrenVM* vm,\n const char* module,\n const char* className,\n bool isStatic,\n const char* signature) {\n if (strcmp(module, \"main\") == 0) {\n if (strcmp(className, \"DL\") == 0) {\n if (!isStatic && strcmp(signature, \"call(_,_)\") == 0) return C_call;\n if (!isStatic && strcmp(signature, \"close()\") == 0) return C_close;\n }\n }\n return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n switch (errorType) {\n case WREN_ERROR_COMPILE:\n printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_STACK_TRACE:\n printf(\"[%s line %d] in %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_RUNTIME:\n printf(\"[Runtime Error] %s\\n\", msg);\n break;\n }\n}\n\nchar *readFile(const char *fileName) {\n FILE *f = fopen(fileName, \"r\");\n fseek(f, 0, SEEK_END);\n long fsize = ftell(f);\n rewind(f);\n char *script = malloc(fsize + 1);\n fread(script, 1, fsize, f);\n fclose(f);\n script[fsize] = 0;\n return script;\n}\n\nint main(int argc, char **argv) {\n WrenConfiguration config;\n wrenInitConfiguration(&config);\n config.writeFn = &writeFn;\n config.errorFn = &errorFn;\n config.bindForeignClassFn = &bindForeignClass;\n config.bindForeignMethodFn = &bindForeignMethod;\n WrenVM* vm = wrenNewVM(&config);\n const char* module = \"main\";\n const char* fileName = \"Call_a_function_in_a_shared_library.wren\";\n char *script = readFile(fileName);\n WrenInterpretResult result = wrenInterpret(vm, module, script);\n switch (result) {\n case WREN_RESULT_COMPILE_ERROR:\n printf(\"Compile Error!\\n\");\n break;\n case WREN_RESULT_RUNTIME_ERROR:\n printf(\"Runtime Error!\\n\");\n break;\n case WREN_RESULT_SUCCESS:\n break;\n }\n wrenFreeVM(vm);\n free(script);\n return 0;\n}\n", "language": "Wren" }, { "code": "option casemap:none\n\nwindows64 equ 1\nlinux64 equ 3\n\nifndef __LIB_CLASS__\n__LIB_CLASS__ equ 1\n\n if @Platform eq windows64\n option dllimport:<kernel32>\n HeapAlloc proto :qword, :dword, :qword\n HeapFree proto :qword, :dword, :qword\n ExitProcess proto :dword\n GetProcessHeap proto\n LoadLibraryA proto :qword\n FreeLibrary proto :qword\n GetProcAddress proto :qword, :qword\n option dllimport:none\n exit equ ExitProcess\n dlsym equ GetProcAddress\n dlclose equ FreeLibrary\n elseif @Platform eq linux64\n malloc proto :qword\n free proto :qword\n exit proto :dword\n dlclose proto :qword\n dlopen proto :qword, :dword\n dlsym proto :qword, :qword\n endif\n\n printf proto :qword, :vararg\n\n CLASS libldr\n CMETHOD getproc\n ENDMETHODS\n libname db 100 dup (0)\n plib dq ?\n ENDCLASS\n\n METHOD libldr, Init, <VOIDARG>, <>, library:qword, namelen:qword\n mov rbx, thisPtr\n assume rbx:ptr libldr\n .if library != 0\n mov rcx, namelen\n mov rsi, library\n lea rdi, [rbx].libname\n rep movsb\n if @Platform eq windows64\n invoke LoadLibraryA, addr [rbx].libname\n .if rax == 0\n invoke printf, CSTR(\"--> Failed to load library\",10)\n .else\n mov [rbx].plib, rax\n .endif\n elseif @Platform eq linux64\n invoke dlopen, addr [rbx].libname, 1\n .if rax == 0\n lea rax, [rbx].libname\n invoke printf, CSTR(\"--> Failed to load library %s\",10), rax\n .else\n mov [rbx].plib, rax\n .endif\n endif\n .else\n invoke printf, CSTR(\"--> Library name to load required..\",10)\n .endif\n mov rax, rbx\n assume rbx:nothing\n ret\n ENDMETHOD\n\n METHOD libldr, getproc, <VOIDARG>, <>, func:qword\n local tmp:qword\n mov tmp, func\n ;; Just return RAX..\n invoke dlsym, [thisPtr].libldr.plib, tmp\n ret\n ENDMETHOD\n\n METHOD libldr, Destroy, <VOIDARG>, <>\n mov rbx, thisPtr\n assume rbx:ptr libldr\n .if [rbx].plib != 0\n invoke dlclose, [rbx].plib\n .endif\n assume rbx:nothing\n ret\n ENDMETHOD\nendif\n\n.data\nLibName db \"./somelib.l\",0\n\n.code\nmain proc\n local ldr:ptr libldr\n\n invoke printf, CSTR(\"--> Loading %s .. \",10), addr LibName\n mov ldr, _NEW(libldr, addr LibName, sizeof(LibName))\n ldr->getproc(CSTR(\"disappointment\"))\n .if rax == 0\n lea rax, idisappointment\n .endif\n call rax\n _DELETE(ldr)\n invoke exit, 0\n ret\nmain endp\n\nidisappointment:\n push rbp\n mov rbp, rsp\n invoke printf, CSTR(\"--> Well this is a internal disappointment..\",10)\n pop rbp\n mov rax, 0\n ret\nend\n", "language": "X86-64-Assembly" }, { "code": "var BN=Import(\"zklBigNum\");\nBN(1)+2 //--> BN(3)\n", "language": "Zkl" } ]
Call-a-function-in-a-shared-library
[ { "code": "---\ncategory:\n- Object oriented\n- Encyclopedia\nfrom: http://rosettacode.org/wiki/Call_an_object_method\nnote: Basic language learning\n", "language": "00-META" }, { "code": "In [[object-oriented programming]] a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.\n\nShow how to call a static or class method, and an instance method of a class.\n", "language": "00-TASK" }, { "code": "// Static\nMyClass.method(someParameter);\n\n// Instance\nmyInstance.method(someParameter);\n", "language": "ActionScript" }, { "code": " package My_Class is\n type Object is tagged private;\n procedure Primitive(Self: Object); -- primitive subprogram\n procedure Dynamic(Self: Object'Class);\n procedure Static;\n private\n type Object is tagged null record;\n end My_Class;\n", "language": "Ada" }, { "code": " package body My_Class is\n procedure Primitive(Self: Object) is\n begin\n\t Put_Line(\"Hello World!\");\n end Primitive;\n\n procedure Dynamic(Self: Object'Class) is\n begin\n\t Put(\"Hi there! ... \");\n\t Self.Primitive; -- dispatching call: calls different subprograms,\n -- depending on the type of Self\n end Dynamic;\n\n procedure Static is\n begin\n\t Put_Line(\"Greetings\");\n end Static;\n end My_Class;\n", "language": "Ada" }, { "code": " package Other_Class is\n type Object is new My_Class.Object with null record;\n overriding procedure Primitive(Self: Object);\n end Other_Class;\n\n package body Other_Class is\n procedure Primitive(Self: Object) is\n begin\n\t Put_Line(\"Hello Universe!\");\n end Primitive;\n end Other_Class;\n", "language": "Ada" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Call_Method is\n\n package My_Class is ... -- see above\n package body My_Class is ... -- see above\n\n package Other_Class is ... -- see above\n package body Other_Class is ... -- see above\n\n Ob1: My_Class.Object; -- our \"root\" type\n Ob2: Other_Class.Object; -- a type derived from the \"root\" type\n\nbegin\n My_Class.Static;\n Ob1.Primitive;\n Ob2.Primitive;\n Ob1.Dynamic;\n Ob2.Dynamic;\nend Call_Method;\n", "language": "Ada" }, { "code": "BEGIN # demonstrate a possible method of simulating class & instance methods #\n # declare a \"class\" #\n MODE ANIMAL = STRUCT( STRING species\n , PROC( REF ANIMAL )VOID print # instance method #\n , PROC VOID cm # class method #\n );\n # constructor #\n PROC new animal = ( STRING species )REF REF ANIMAL:\n BEGIN\n HEAP ANIMAL newv := ANIMAL( species\n , ( REF ANIMAL this )VOID:\n print( ( \"[animal instance[\", species OF this, \"]]\" ) )\n , VOID: print( ( \"[animal class method called]\" ) )\n );\n HEAP REF ANIMAL newa := newv;\n newa\n END # new animal # ;\n\n REF ANIMAL a\n := new animal( \"PANTHERA TIGRIS\" ); # create an instance of ANIMAL #\n cm OF a; # call the class method #\n ( print OF a )( a ) # call the instance method #\nEND\n", "language": "ALGOL-68" }, { "code": "// Static\nMyClass.method(someParameter);\n\n// Instance\nmyInstance.method(someParameter);\n", "language": "Apex" }, { "code": "class myClass\n{\n\tMethod(someParameter){\n\t\tMsgBox % SomeParameter\n\t}\n}\n\nmyClass.method(\"hi\")\nmyInstance := new myClass\nmyInstance.Method(\"bye\")\n", "language": "AutoHotkey" }, { "code": "( ( myClass\n = (name=aClass)\n ( Method\n = .out$(str$(\"Output from \" !(its.name) \": \" !arg))\n )\n (new=.!arg:?(its.name))\n )\n& (myClass.Method)$\"Example of calling a 'class' method\"\n& new$(myClass,object1):?MyObject\n& (MyObject..Method)$\"Example of calling an instance method\"\n& !MyObject:?Alias\n& (Alias..Method)$\"Example of calling an instance method from an alias\"\n);\n", "language": "Bracmat" }, { "code": "#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n int x;\n int (*funcPtr)(int);\n}functionPair;\n\nint factorial(int num){\n if(num==0||num==1)\n return 1;\n else\n return num*factorial(num-1);\n}\n\nint main(int argc,char** argv)\n{\n functionPair response;\n\n if(argc!=2)\n return printf(\"Usage : %s <non negative integer>\",argv[0]);\n else{\n response = (functionPair){.x = atoi(argv[1]),.funcPtr=&factorial};\n printf(\"\\nFactorial of %d is %d\\n\",response.x,response.funcPtr(response.x));\n }\n return 0;\n}\n", "language": "C" }, { "code": "// Static\nMyClass::method(someParameter);\n\n// Instance\nmyInstance.method(someParameter);\n\n// Pointer\nMyPointer->method(someParameter);\n", "language": "C++" }, { "code": "// Static\nMyClass.Method(someParameter);\n\n// Instance\nmyInstance.Method(someParameter);\n", "language": "C-sharp" }, { "code": "MyClass myClassObject;\nmyClassObject.myFunction(some parameter);\n", "language": "ChucK" }, { "code": "(Long/toHexString 15) ; use forward slash for static methods\n(System/currentTimeMillis)\n\n(.equals 1 2) ; use dot operator to call instance methods\n(. 1 (equals 2)) ; alternative style\n", "language": "Clojure" }, { "code": "*> INVOKE statements.\nINVOKE my-class \"some-method\" *> Factory object\n USING BY REFERENCE some-parameter\n RETURNING foo\nINVOKE my-instance \"another-method\" *> Instance object\n USING BY REFERENCE some-parameter\n RETURNING foo\n\n*> Inline method invocation.\nMOVE my-class::\"some-method\"(some-parameter) TO foo *> Factory object\nMOVE my-instance::\"another-method\"(some-parameter) TO foo *> Instance object\n", "language": "COBOL" }, { "code": "INVOKE some-instance \"FactoryObject\" RETURNING foo-factory\n*> foo-factory can be treated like a normal object reference.\nINVOKE foo-factory \"someMethod\"\n", "language": "COBOL" }, { "code": "class Foo\n @staticMethod: -> 'Bar'\n\n instanceMethod: -> 'Baz'\n\nfoo = new Foo\n\nfoo.instanceMethod() #=> 'Baz'\nFoo.staticMethod() #=> 'Bar'\n", "language": "CoffeeScript" }, { "code": "(defclass my-class ()\n ((x\n :accessor get-x ;; getter function\n :initarg :x ;; arg name\n :initform 0))) ;; initial value\n\n;; declaring a public class method\n(defmethod square-x ((class-instance my-class))\n (* (get-x class-instance) (get-x class-instance)))\n\n;; create an instance of my-class\n(defvar *instance*\n (make-instance 'my-class :x 10))\n\n(format t \"Value of x: ~a~%\" (get-x *instance*))\n\n(format t \"Value of x^2: ~a~%\" (square-x *instance*))\n", "language": "Common-Lisp" }, { "code": "struct Cat {\n static int staticMethod() {\n return 2;\n }\n\n string dynamicMethod() { // Never virtual.\n return \"Mew!\";\n }\n}\n\nclass Dog {\n static int staticMethod() {\n return 5;\n }\n\n string dynamicMethod() { // Virtual method.\n return \"Woof!\";\n }\n}\n\nvoid main() {\n // Static methods calls:\n assert(Cat.staticMethod() == 2);\n assert(Dog.staticMethod() == 5);\n\n Cat c; // This is a value on the stack.\n Dog d; // This is just a reference, set to null.\n\n // Other static method calls, discouraged:\n assert(c.staticMethod() == 2);\n assert(d.staticMethod() == 5);\n\n // Instance method calls:\n assert(c.dynamicMethod() == \"Mew!\");\n d = new Dog;\n assert(d.dynamicMethod() == \"Woof!\");\n}\n", "language": "D" }, { "code": "{Simple stack interface}\n\ntype TSimpleStack = class(TObject)\n private\n FStack: array of integer;\n protected\n public\n procedure Push(I: integer);\n function Pop(var I: integer): boolean;\n constructor Create;\n end;\n\n\n{ TSimpleStack implementation }\n\nconstructor TSimpleStack.Create;\n{Initialize stack by setting size to zero}\nbegin\nSetLength(FStack,0);\nend;\n\nfunction TSimpleStack.Pop(var I: integer): boolean;\n{Pop top item off stack into \"I\" returns False if stack empty}\nbegin\nResult:=Length(FStack)>=1;\nif Result then\n\tbegin\n\t{Get item from top of stack}\n\tI:=FStack[High(FStack)];\n\t{Delete the top item}\n\tSetLength(FStack,Length(FStack)-1);\n\tend;\nend;\n\nprocedure TSimpleStack.Push(I: integer);\n{Push item on stack by adding to end of array}\nbegin\n{Increase stack size by one}\nSetLength(FStack,Length(FStack)+1);\n{Insert item}\nFStack[High(FStack)]:=I;\nend;\n\n\nprocedure ShowStaticMethodCall(Memo: TMemo);\nvar Stack: TSimpleStack;\t{Declare stack object}\nvar I: integer;\nbegin\n{Instanciate stack object}\nStack:=TSimpleStack.Create;\n{Push items on stack by calling static method \"Push\"}\nfor I:=1 to 10 do Stack.Push(I);\n{Call static method \"Pop\" to retrieve and display stack items}\nwhile Stack.Pop(I) do\n\tbegin\n\tMemo.Lines.Add(IntToStr(I));\n\tend;\n{release stack memory and delete object}\nStack.Free;\nend;\n", "language": "Delphi" }, { "code": "r = new run()\nr.val()\n", "language": "Dragon" }, { "code": "//Static method on a built-in type Integer\nstatic func Integer.Div(x, y) {\n x / y\n}\n\n//Instance method\nfunc Integer.Div(n) {\n this / n\n}\n\nprint(Integer.Div(12, 3))\nprint(12.Div(3))\n", "language": "Dyalect" }, { "code": "someObject.someMethod(someParameter)\n", "language": "E" }, { "code": "module CallMethod {\n /**\n * This is a class with a method and a function.\n */\n const Example(String text) {\n @Override\n String toString() { // <-- this is a method\n return $\"This is an example with text={text}\";\n }\n\n static Int oneMoreThan(Int n) { // <-- this is a function\n return n+1;\n }\n }\n\n void run() {\n @Inject Console console;\n\n Example example = new Example(\"hello!\");\n String methodResult = example.toString(); // <-- call a method\n console.print($\"Result from calling a method: {methodResult.quoted()}\");\n\n // Int funcResult = example.oneMoreThan(12); // <-- compiler error\n Int funcResult = Example.oneMoreThan(12); // <-- call a function\n console.print($\"Results from calling a function: {funcResult}\");\n\n // methods and functions are also objects that can be manipulated;\n // note that \"function String()\" === \"Function<<>, <String>>\"\n Method<Example, <>, <String>> method = Example.toString;\n function String() func = method.bindTarget(example);\n console.print($\"Calling a bound method: {func().quoted()}\");\n\n // by default, a method with target T converts to a function taking a T;\n // Ecstasy refers to this as \"Bjarning\" (because C++ takes \"this\" as a param)\n val func2 = Example.toString; // <-- type: function String()\n console.print($\"Calling a Bjarne'd function: {func2(example).quoted()}\");\n\n // the function is just an object, and invocation (and in this case, binding,\n // as indicated by the '&' operator which requests a reference) is accomplished\n // using the \"()\" operator\n val func3 = Example.oneMoreThan; // <-- type: function Int(Int)\n val func4 = &func3(13); // <-- type: function Int()\n console.print($\"Calling a fully bound function: {func4()}\");\n }\n}\n", "language": "Ecstasy" }, { "code": " console.printLine(\"Hello\",\" \",\"World!\");\n", "language": "Elena" }, { "code": "defmodule ObjectCall do\n def new() do\n spawn_link(fn -> loop end)\n end\n\n defp loop do\n receive do\n {:concat, {caller, [str1, str2]}} ->\n result = str1 <> str2\n send caller, {:ok, result}\n loop\n end\n end\n\n def concat(obj, str1, str2) do\n send obj, {:concat, {self(), [str1, str2]}}\n\n receive do\n {:ok, result} ->\n result\n end\n end\nend\n\nobj = ObjectCall.new()\n\nIO.puts(obj |> ObjectCall.concat(\"Hello \", \"World!\"))\n", "language": "Elixir" }, { "code": "type MyClass ^|we are defining a new data type and entering in its static context|^\nfun method = void by block do writeLine(\"static method called\") end\nmodel ^|we enter the instance context|^\n fun method = void by block do writeLine(\"instance method called\") end\nend\ntype CallAnObjectMethod\nvar myInstance = MyClass() ^|creating an instance|^\nmyInstance.method()\nMyClass.method()\n", "language": "EMal" }, { "code": "USING: accessors io kernel literals math sequences ;\nIN: rosetta-code.call-a-method\n\n! Define some classes.\nSINGLETON: dog\nTUPLE: cat sassiness ;\n\n! Define a constructor for cat.\nC: <cat> cat\n\n! Define a generic word that dispatches on the object at the top\n! of the data stack.\nGENERIC: speak ( obj -- )\n\n! Define methods in speak which specialize on various classes.\nM: dog speak drop \"Woof!\" print ;\nM: cat speak sassiness>> 0.5 > \"Hiss!\" \"Meow!\" ? print ;\nM: object speak drop \"I don't know how to speak!\" print ;\n\n! Call speak on various objects.\n! Despite being a method, it's called like any other word.\ndog speak\n0.75 <cat> speak\n0.1 <cat> speak\n\"bird\" speak\n", "language": "Factor" }, { "code": "include lib/compare.4th\ninclude 4pp/lib/foos.4pp\n\n[ASSERT] \\ enable assertions\n\n:: Cat\n class\n method: dynamicCat \\ virtual method\n end-class {\n\n :static staticCat { 2 } ; \\ static method\n :method { s\" Mew!\" } ; defines dynamicCat\n } \\ for unrelated classes,\n; \\ method names have to differ\n\n:: Dog\n class\n method: dynamicDog \\ virtual method\n end-class {\n\n :static staticDog { 5 } ;\n :method { s\" Woof!\" } ; defines dynamicDog\n } \\ for unrelated classes,\n; \\ method names have to differ\n\nstatic Cat c \\ create two static objects\nstatic Dog d\n\n: main\n assert( class -> staticCat 2 = ) \\ check for valid method return\n assert( class -> staticDog 5 = ) \\ of a static method\n\n assert( c -> staticCat 2 = ) \\ check for valid method return\n assert( d -> staticDog 5 = ) \\ of a static method\n\n assert( c => dynamicCat s\" Mew!\" compare 0= )\n assert( d => dynamicDog s\" Woof!\" compare 0= )\n; \\ same for dynamic methods\n\nmain\n", "language": "Forth" }, { "code": "include FMS-SI.f\n\n:class animal\n variable cnt 0 cnt ! \\ static instance variable\n :m init: 1 cnt +! ;m\n :m cnt: cnt @ . ;m\n;class\n\n:class cat <super animal\n :m speak .\" meow\" ;m\n;class\n\n:class dog <super animal\n :m speak .\" woof\" ;m\n;class\n\ncat Frisky \\ instantiate a cat object named Frisky\ndog Sparky \\ instantiate a dog object named Sparky\n\n\\ The class method cnt: will return the number of animals instantiated\n\\ regardless of which animal object is used.\n\n\\ The instance method speak will respond differently depending\n\\ on the class of the instance object.\n\nFrisky cnt: \\ => 2 ok\nSparky cnt: \\ => 2 ok\nFrisky speak \\ => meow ok\nSparky speak \\ => woof ok\n", "language": "Forth" }, { "code": "! type declaration\ntype my_type\n contains\nprocedure, pass :: method1\nprocedure, pass, pointer :: method2\nend type my_type\n\n! declare object of type my_type\ntype(my_type) :: mytype_object\n\n!static call\n call mytype_object%method1() ! call method1 defined as subroutine\n!instance?\n mytype_object%method2() ! call method2 defined as function\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nType MyType\n Public:\n Declare Sub InstanceMethod(s As String)\n Declare Static Sub StaticMethod(s As String)\n Private:\n dummy_ As Integer ' types cannot be empty in FB\nEnd Type\n\nSub MyType.InstanceMethod(s As String)\n Print s\nEnd Sub\n\nStatic Sub MyType.StaticMethod(s As String)\n Print s\nEnd Sub\n\nDim t As MyType\nt.InstanceMethod(\"Hello world!\")\nMyType.Staticmethod(\"Hello static world!\")\nPrint\nPrint \"Press any key to quit the program\"\nSleep\n", "language": "FreeBASIC" }, { "code": "local fn FBClassDemo\n // Class\n ClassRef class = fn MutableStringClass\n // Cocoa base class name as human-readable string\n print fn StringFromClass( class )\n\n // Instantiate\n CFMutableStringRef mutStr = fn MutableStringNew\n\n // Method with single argument\n MutableStringSetString( mutStr, @\"Hello, World!\" )\n print mutStr\n\n // Method with multiple arguments\n MutableStringReplaceAllOccurrencesOfString( mutStr, @\"World\", @\"Rosetta Code\" )\n print mutStr\nend fn\n\nfn FBClassDemo\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "type Foo int // some custom type\n\n// method on the type itself; can be called on that type or its pointer\nfunc (self Foo) ValueMethod(x int) { }\n\n// method on the pointer to the type; can be called on pointers\nfunc (self *Foo) PointerMethod(x int) { }\n\n\nvar myValue Foo\nvar myPointer *Foo = new(Foo)\n\n// Calling value method on value\nmyValue.ValueMethod(someParameter)\n// Calling pointer method on pointer\nmyPointer.PointerMethod(someParameter)\n\n// Value methods can always be called on pointers\n// equivalent to (*myPointer).ValueMethod(someParameter)\nmyPointer.ValueMethod(someParameter)\n\n// In a special case, pointer methods can be called on values that are addressable (i.e. lvalues)\n// equivalent to (&myValue).PointerMethod(someParameter)\nmyValue.PointerMethod(someParameter)\n\n// You can get the method out of the type as a function, and then explicitly call it on the object\nFoo.ValueMethod(myValue, someParameter)\n(*Foo).PointerMethod(myPointer, someParameter)\n(*Foo).ValueMethod(myPointer, someParameter)\n", "language": "Go" }, { "code": "package box\n\nimport \"sync/atomic\"\n\nvar sn uint32\n\ntype box struct {\n Contents string\n secret uint32\n}\n\nfunc New() (b *box) {\n b = &box{secret: atomic.AddUint32(&sn, 1)}\n switch sn {\n case 1:\n b.Contents = \"rabbit\"\n case 2:\n b.Contents = \"rock\"\n }\n return\n}\n\nfunc (b *box) TellSecret() uint32 {\n return b.secret\n}\n\nfunc Count() uint32 {\n return atomic.LoadUint32(&sn)\n}\n", "language": "Go" }, { "code": "package main\n\nimport \"box\"\n\nfunc main() {\n // Call constructor. Technically it's just an exported function,\n // but it's a Go idiom to naming a function New that serves the purpose\n // of a constructor.\n b := box.New()\n\n // Call instance method. In Go terms, simply a method.\n b.TellSecret()\n\n // Call class method. In Go terms, another exported function.\n box.Count()\n}\n", "language": "Go" }, { "code": "procedure main()\n\n bar := foo() # create instance\n bar.m2() # call method m2 with self=bar, an implicit first parameter\n\n foo_m1( , \"param1\", \"param2\") # equivalent of static class method, first (self) parameter is null\nend\n\nclass foo(cp1,cp2)\n method m1(m1p1,m1p2)\n local ml1\n static ms1\n ml1 := m1p1\n # do something\n return\n end\n method m2(m2p1)\n # do something else\n return\n end\ninitially\n L := [cp1]\nend\n", "language": "Go" }, { "code": "data Obj = Obj { field :: Int, method :: Int -> Int }\n\n-- smart constructor\nmkAdder :: Int -> Obj\nmkAdder x = Obj x (+x)\n\n-- adding method from a type class\ninstanse Show Obj where\n show o = \"Obj \" ++ show (field o)\n", "language": "Haskell" }, { "code": "methodName_className_ parameters\n", "language": "J" }, { "code": "objectReference=:'' conew 'className'\n", "language": "J" }, { "code": "methodName__objectReference parameters\n", "language": "J" }, { "code": "parameters methodName_className_ parameters\n", "language": "J" }, { "code": "parameters methodName__objectReference parameters\n", "language": "J" }, { "code": "classReference=: <'className'\nmethodName__classReference parameters\n", "language": "J" }, { "code": "methodName_123_ parameters\n", "language": "J" }, { "code": "ClassWithStaticMethod.staticMethodName(argument1, argument2);//for methods with no arguments, use empty parentheses\n", "language": "Java" }, { "code": "ClassWithMethod varName = new ClassWithMethod();\nvarName.methodName(argument1, argument2);\n//or\nnew ClassWithMethod().methodName(argument1, argument2);\n", "language": "Java" }, { "code": "x.y()\n", "language": "JavaScript" }, { "code": "class MyClass {\n fun instanceMethod(s: String) = println(s)\n\n companion object {\n fun staticMethod(s: String) = println(s)\n }\n}\n\nfun main() {\n val mc = MyClass()\n mc.instanceMethod(\"Hello instance world!\")\n MyClass.staticMethod(\"Hello static world!\")\n}\n", "language": "Kotlin" }, { "code": "myObject someMethod (arg1, arg2, arg3).\nMyClass someMethod (arg1, arg2, arg3).\n", "language": "Latitude" }, { "code": "myObject someMethod \"string constant argument\".\nmyObject someMethod (argument). ;; Parentheses are necessary here\nmyObject someMethod. ;; No arguments\n", "language": "Latitude" }, { "code": "myObject someMethod: arg1, arg2, arg3.\n", "language": "Latitude" }, { "code": "(defmodule aquarium\n (export all))\n\n(defun fish-class (species)\n \"\n This is the constructor that will be used most often, only requiring that\n one pass a 'species' string.\n\n When the children are not defined, simply use an empty list.\n \"\n (fish-class species ()))\n\n(defun fish-class (species children)\n \"\n This contructor is mostly useful as a way of abstracting out the id\n generation from the larger constructor. Nothing else uses fish-class/2\n besides fish-class/1, so it's not strictly necessary.\n\n When the id isn't know, generate one.\n \"\n (let* (((binary (id (size 128))) (: crypto rand_bytes 16))\n (formatted-id (car\n (: io_lib format\n '\"~32.16.0b\" (list id)))))\n (fish-class species children formatted-id)))\n\n(defun fish-class (species children id)\n \"\n This is the constructor used internally, once the children and fish id are\n known.\n \"\n (let ((move-verb '\"swam\"))\n (lambda (method-name)\n (case method-name\n ('id\n (lambda (self) id))\n ('species\n (lambda (self) species))\n ('children\n (lambda (self) children))\n ('info\n (lambda (self)\n (: io format\n '\"id: ~p~nspecies: ~p~nchildren: ~p~n\"\n (list (get-id self)\n (get-species self)\n (get-children self)))))\n ('move\n (lambda (self distance)\n (: io format\n '\"The ~s ~s ~p feet!~n\"\n (list species move-verb distance))))\n ('reproduce\n (lambda (self)\n (let* ((child (fish-class species))\n (child-id (get-id child))\n (children-ids (: lists append\n (list children (list child-id))))\n (parent-id (get-id self))\n (parent (fish-class species children-ids parent-id)))\n (list parent child))))\n ('children-count\n (lambda (self)\n (: erlang length children)))))))\n\n(defun get-method (object method-name)\n \"\n This is a generic function, used to call into the given object (class\n instance).\n \"\n (funcall object method-name))\n\n; define object methods\n(defun get-id (object)\n (funcall (get-method object 'id) object))\n\n(defun get-species (object)\n (funcall (get-method object 'species) object))\n\n(defun get-info (object)\n (funcall (get-method object 'info) object))\n\n(defun move (object distance)\n (funcall (get-method object 'move) object distance))\n\n(defun reproduce (object)\n (funcall (get-method object 'reproduce) object))\n\n(defun get-children (object)\n (funcall (get-method object 'children) object))\n\n(defun get-children-count (object)\n (funcall (get-method object 'children-count) object))\n", "language": "LFE" }, { "code": "; Load the file and create a fish-class instance:\n\n> (slurp '\"object.lfe\")\n#(ok object)\n> (set mommy-fish (fish-class '\"Carp\"))\n#Fun<lfe_eval.10.91765564>\n\n; Execute some of the basic methods:\n\n> (get-species mommy-fish)\n\"Carp\"\n> (move mommy-fish 17)\nThe Carp swam 17 feet!\nok\n> (get-id mommy-fish)\n\"47eebe91a648f042fc3fb278df663de5\"\n\n; Now let's look at \"modifying\" state data (e.g., children counts):\n\n> (get-children mommy-fish)\n()\n> (get-children-count mommy-fish)\n0\n> (set (mommy-fish baby-fish-1) (reproduce mommy-fish))\n(#Fun<lfe_eval.10.91765564> #Fun<lfe_eval.10.91765564>)\n> (get-id mommy-fish)\n\"47eebe91a648f042fc3fb278df663de5\"\n> (get-id baby-fish-1)\n\"fdcf35983bb496650e558a82e34c9935\"\n> (get-children-count mommy-fish)\n1\n> (set (mommy-fish baby-fish-2) (reproduce mommy-fish))\n(#Fun<lfe_eval.10.91765564> #Fun<lfe_eval.10.91765564>)\n> (get-id mommy-fish)\n\"47eebe91a648f042fc3fb278df663de5\"\n> (get-id baby-fish-2)\n\"3e64e5c20fb742dd88dac1032749c2fd\"\n> (get-children-count mommy-fish)\n2\n> (get-info mommy-fish)\nid: \"47eebe91a648f042fc3fb278df663de5\"\nspecies: \"Carp\"\nchildren: [\"fdcf35983bb496650e558a82e34c9935\",\n \"3e64e5c20fb742dd88dac1032749c2fd\"]\nok\n", "language": "LFE" }, { "code": "(defmodule object\n (export all))\n\n(defun fish-class (species)\n \"\n This is the constructor that will be used most often, only requiring that\n one pass a 'species' string.\n\n When the children are not defined, simply use an empty list.\n \"\n (fish-class species ()))\n\n(defun fish-class (species children)\n \"\n This constructor is useful for two reasons:\n 1) as a way of abstracting out the id generation from the\n larger constructor, and\n 2) spawning the 'object loop' code (fish-class/3).\n \"\n (let* (((binary (id (size 128))) (: crypto rand_bytes 16))\n (formatted-id (car\n (: io_lib format\n '\"~32.16.0b\" (list id)))))\n (spawn 'object\n 'fish-class\n (list species children formatted-id))))\n\n(defun fish-class (species children id)\n \"\n This function is intended to be spawned as a separate process which is\n used to track the state of a fish. In particular, fish-class/2 spawns\n this function (which acts as a loop, pattern matching for messages).\n \"\n (let ((move-verb '\"swam\"))\n (receive\n ((tuple caller 'move distance)\n (! caller (list species move-verb distance))\n (fish-class species children id))\n ((tuple caller 'species)\n (! caller species)\n (fish-class species children id))\n ((tuple caller 'children)\n (! caller children)\n (fish-class species children id))\n ((tuple caller 'children-count)\n (! caller (length children))\n (fish-class species children id))\n ((tuple caller 'id)\n (! caller id)\n (fish-class species children id))\n ((tuple caller 'info)\n (! caller (list id species children))\n (fish-class species children id))\n ((tuple caller 'reproduce)\n (let* ((child (fish-class species))\n (child-id (get-id child))\n (children-ids (: lists append\n (list children (list child-id)))))\n (! caller child)\n (fish-class species children-ids id))))))\n\n(defun call-method (object method-name)\n \"\n This is a generic function, used to call into the given object (class\n instance).\n \"\n (! object (tuple (self) method-name))\n (receive\n (data data)))\n\n(defun call-method (object method-name arg)\n \"\n Same as above, but with an additional argument.\n \"\n (! object (tuple (self) method-name arg))\n (receive\n (data data)))\n\n; define object methods\n(defun get-id (object)\n (call-method object 'id))\n\n(defun get-species (object)\n (call-method object 'species))\n\n(defun get-info (object)\n (let ((data (call-method object 'info)))\n (: io format '\"id: ~s~nspecies: ~s~nchildren: ~p~n\" data)))\n\n(defun move (object distance)\n (let ((data (call-method object 'move distance)))\n (: io format '\"The ~s ~s ~p feet!~n\" data)))\n\n(defun reproduce (object)\n (call-method object 'reproduce))\n\n(defun get-children (object)\n (call-method object 'children))\n\n(defun get-children-count (object)\n (call-method object 'children-count))\n", "language": "LFE" }, { "code": "; Load the file and create a fish-class instance:\n\n> (slurp '\"object.lfe\")\n#(ok object)\n> (set mommy-fish (fish-class '\"Carp\"))\n<0.33.0>\n\n; Execute some of the basic methods:\n\n> (get-species mommy-fish)\n\"Carp\"\n> (move mommy-fish 17)\nThe Carp swam 17 feet!\nok\n> (get-id mommy-fish)\n\"47eebe91a648f042fc3fb278df663de5\"\n\n; Now let's look at modifying state data:\n\n> (get-children mommy-fish)\n()\n> (get-children-count mommy-fish)\n0\n> (set baby-fish-1 (reproduce mommy-fish))\n<0.34.0>\n> (get-id mommy-fish)\n\"47eebe91a648f042fc3fb278df663de5\"\n> (get-id baby-fish-1)\n\"fdcf35983bb496650e558a82e34c9935\"\n> (get-children-count mommy-fish)\n1\n> (set baby-fish-2 (reproduce mommy-fish))\n<0.35.0>\n> (get-id mommy-fish)\n\"47eebe91a648f042fc3fb278df663de5\"\n> (get-id baby-fish-2)\n\"3e64e5c20fb742dd88dac1032749c2fd\"\n> (get-children-count mommy-fish)\n2\n> (get-info mommy-fish)\nid: 47eebe91a648f042fc3fb278df663de5\nspecies: Carp\nchildren: [\"fdcf35983bb496650e558a82e34c9935\",\n \"3e64e5c20fb742dd88dac1032749c2fd\"]\nok\n", "language": "LFE" }, { "code": "-- call static method\nscript(\"MyClass\").foo()\n\n-- call instance method\nobj = script(\"MyClass\").new()\nobj.foo()\n", "language": "Lingo" }, { "code": "% avoid infinite metaclass regression by\n% making the metaclass an instance of itself\n:- object(metaclass,\n instantiates(metaclass)).\n\n :- public(me/1).\n me(Me) :-\n self(Me).\n\n:- end_object.\n", "language": "Logtalk" }, { "code": ":- object(class,\n instantiates(metaclass)).\n\n :- public(my_class/1).\n my_class(Class) :-\n self(Self),\n instantiates_class(Self, Class).\n\n:- end_object.\n", "language": "Logtalk" }, { "code": ":- object(instance,\n instantiates(class)).\n\n:- end_object.\n", "language": "Logtalk" }, { "code": "| ?- class::me(Me).\nMe = class\nyes\n\n| ?- instance::my_class(Class).\nClass = class\nyes\n", "language": "Logtalk" }, { "code": "local object = { name = \"foo\", func = function (self) print(self.name) end }\n\nobject:func() -- with : sugar\nobject.func(object) -- without : sugar\n", "language": "Lua" }, { "code": "local methods = { }\nfunction methods:func () -- if a function is declared using :, it is given an implicit 'self' parameter\n print(self.name)\nend\n\nlocal object = setmetatable({ name = \"foo\" }, { __index = methods })\n\nobject:func() -- with : sugar\nmethods.func(object) -- without : sugar\n", "language": "Lua" }, { "code": "local count = 0\nlocal box = { }\nlocal boxmt = { __index = box }\nfunction box:tellSecret ()\n return self.secret\nend\n\nlocal M = { }\nfunction M.new ()\n count = count + 1\n return setmetatable({ secret = count, contents = count % 2 == 0 and \"rabbit\" or \"rock\" }, boxmt)\nend\nfunction M.count ()\n return count\nend\nreturn M\n", "language": "Lua" }, { "code": "local box = require 'box'\n\nlocal b = box.new()\n\nprint(b:tellSecret())\nprint(box.count())\n", "language": "Lua" }, { "code": "Module CheckIt {\n \\\\ A class definition is a function which return a Group\n \\\\ We can make groups and we can alter them using Group statement\n \\\\ Groups may have other groups inside\n\n Group Alfa {\n Private:\n myvalue=100\n Public:\n Group SetValue {\n Set (x) {\n Link parent myvalue to m\n m<=x\n }\n }\n Module MyMethod {\n Read x\n Print x*.myvalue\n }\n }\n\n Alfa.MyMethod 5 '500\n Alfa.MyMethod %x=200 ' 20000\n \\\\ we can copy Alfa to Z\n Z=Alfa\n Z.MyMethod 5\n Z.SetValue=300\n Z.MyMethod 5 ' 1500\n Alfa.MyMethod 5 ' 500\n Dim A(10)\n A(3)=Z\n A(3).MyMethod 5 '1500\n A(3).SetValue=200\n A(3).MyMethod 5 '1000\n \\\\ get a pointer of group in A(3)\n k->A(3)\n k=>SetValue=100\n A(3).MyMethod 5 '500\n \\\\ k get pointer to Alfa\n k->Alfa\n k=>SetValue=500\n Alfa.MyMethod 5 '2500\n k->Z\n k=>MyMethod 5 ' 1500\n Z.SetValue=100\n k=>MyMethod 5 ' 500\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "# Static\nMethod( obj, other, arg );\n", "language": "Maple" }, { "code": "# Instance\nMethod( obj, other, arg );\n", "language": "Maple" }, { "code": "Dog = {}\nDog.name = \"\"\nDog.help = function()\n print \"This class represents dogs.\"\nend function\nDog.speak = function()\n print self.name + \" says Woof!\"\nend function\n\nfido = new Dog\nfido.name = \"Fido\"\n\nDog.help // calling a \"class method\"\nfido.speak // calling an \"instance method\"\n", "language": "MiniScript" }, { "code": "class MyClass\n\tdeclare static id = 5\n\tdeclare MyName\n\n\t// constructor\n\tdef MyClass(MyName)\n\t\tthis.MyName = MyName\n\tend\n\n\t// class method\n\tdef getName()\n\t\treturn this.MyName\n\tend\n\n\t// static method\n\tdef static getID()\n\t\treturn id\n\tend\nend\n\n// call the static method\nprintln MyClass.getID()\n\n// instantiate a new MyClass object with the name \"test\"\n// and call the class method\nmyclass = new(MyClass, \"test\")\nprintln myclass.getName()\n", "language": "Nanoquery" }, { "code": "// Static\nMyClass.Method(someParameter);\n\n// Instance\nmyInstance.Method(someParameter);\n", "language": "Nemerle" }, { "code": "SomeClass.staticMethod()\n", "language": "NetRexx" }, { "code": "objectInstance = SomeClass() -- create a new instance of the class\nobjectInstance.instanceMethod() -- call the instance method\n\nSomeClass().instanceMethod() -- same as above; create a new instance of the class and call the instance method immediately\n", "language": "NetRexx" }, { "code": "var x = @[1, 2, 3]\nadd(x, 4)\nx.add(5)\n", "language": "Nim" }, { "code": "+&GO\n", "language": "OASYS-Assembler" }, { "code": "ClassName->some_function(); # call class function\ninstance->some_method(); # call instance method\n", "language": "Objeck" }, { "code": "// Static (known in Pascal as class method)\nMyClass.method(someParameter);\n\n// Instance\nmyInstance.method(someParameter);\n", "language": "Object-Pascal" }, { "code": "// Class\n[MyClass method:someParameter];\n// or equivalently:\nid foo = [MyClass class];\n[foo method:someParameter];\n\n// Instance\n[myInstance method:someParameter];\n\n// Method with multiple arguments\n[myInstance methodWithRed:arg1 green:arg2 blue:arg3];\n\n// Method with no arguments\n[myInstance method];\n", "language": "Objective-C" }, { "code": "my_obj#my_meth params\n", "language": "OCaml" }, { "code": "1.2 sqrt\n", "language": "Oforth" }, { "code": "Date now\n", "language": "Oforth" }, { "code": "say \"pi:\" .circle~pi\nc=.circle~new(1)\nsay \"c~area:\" c~area\nDo r=2 To 10\n c.r=.circle~new(r)\n End\nsay .circle~instances('') 'circles were created'\n\n::class circle\n::method pi class -- a class method\n return 3.14159265358979323\n\n::method instances class -- another class method\n expose in\n use arg a\n If datatype(in)<>'NUM' Then in=0\n If a<>'' Then\n in+=1\n Return in\n\n::method init\n expose radius\n use arg radius\n self~class~instances('x')\n\n::method area -- an instance method\n expose radius\n Say self~class\n Say self\n return self~class~pi * radius * radius\n", "language": "OoRexx" }, { "code": "# Class method\nMyClass->classMethod($someParameter);\n# Equivalently using a class name\nmy $foo = 'MyClass';\n$foo->classMethod($someParameter);\n\n\n# Instance method\n$myInstance->method($someParameter);\n\n# Calling a method with no parameters\n$myInstance->anotherMethod;\n\n# Class and instance method calls are made behind the scenes by getting the function from\n# the package and calling it on the class name or object reference explicitly\nMyClass::classMethod('MyClass', $someParameter);\nMyClass::method($myInstance, $someParameter);\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span> <span style=\"color: #000080;font-style:italic;\">-- (no class in p2js)</span>\n <span style=\"color: #008080;\">class</span> <span style=\"color: #000000;\">test</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"this is a test\"</span>\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">show</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">this</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">msg</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">inst</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"this is dynamic\"</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">class</span>\n <span style=\"color: #000000;\">test</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">new</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">show</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #000080;font-style:italic;\">-- prints \"this is a test\"</span>\n <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">inst</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #000080;font-style:italic;\">-- prints \"this is dynamic\"</span>\n <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">inst</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">show</span>\n <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">inst</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #000080;font-style:italic;\">-- prints \"this is a test\"</span>\n<!--\n", "language": "Phix" }, { "code": "// Static method\nMyClass::method($someParameter);\n// In PHP 5.3+, static method can be called on a string of the class name\n$foo = 'MyClass';\n$foo::method($someParameter);\n\n\n// Instance method\n$myInstance->method($someParameter);\n", "language": "PHP" }, { "code": "(foo> MyClass)\n(foo> MyObject)\n", "language": "PicoLisp" }, { "code": "obj->method();\nobj[\"method\"]();\ncall_function(obj->method);\ncall_function(obj[\"method\"]);\n", "language": "Pike" }, { "code": "function func = obj->method;\nfunc();\n", "language": "Pike" }, { "code": "module.func();\nmodule[\"func\"]();\n", "language": "Pike" }, { "code": "create or replace TYPE myClass AS OBJECT (\n -- A class needs at least one member even though we don't use it\n dummy NUMBER,\n STATIC FUNCTION static_method RETURN VARCHAR2,\n MEMBER FUNCTION instance_method RETURN VARCHAR2\n);\n/\nCREATE OR REPLACE TYPE BODY myClass AS\n STATIC FUNCTION static_method RETURN VARCHAR2 IS\n BEGIN\n RETURN 'Called myClass.static_method';\n END static_method;\n\n MEMBER FUNCTION instance_method RETURN VARCHAR2 IS\n BEGIN\n RETURN 'Called myClass.instance_method';\n END instance_method;\nEND;\n/\n\nDECLARE\n myInstance myClass;\nBEGIN\n myInstance := myClass(null);\n DBMS_OUTPUT.put_line( myClass.static_method() );\n DBMS_OUTPUT.put_line( myInstance.instance_method() );\nEND;/\n", "language": "PL-SQL" }, { "code": "$Date = Get-Date\n$Date.AddDays( 1 )\n[System.Math]::Sqrt( 2 )\n", "language": "PowerShell" }, { "code": "// define a rudimentary class\nclass HelloWorld\n{\n public static void sayHello()\n {\n println(\"Hello, world!\");\n }\n public void sayGoodbye()\n {\n println(\"Goodbye, cruel world!\");\n }\n}\n\n// call the class method\nHelloWorld.sayHello();\n\n// create an instance of the class\nHelloWorld hello = new HelloWorld();\n\n// and call the instance method\nhello.sayGoodbye();\n", "language": "Processing" }, { "code": "class MyClass(object):\n\t@classmethod\n\tdef myClassMethod(self, x):\n\t\tpass\n\t@staticmethod\n\tdef myStaticMethod(x):\n\t\tpass\n\tdef myMethod(self, x):\n\t\treturn 42 + x\n\nmyInstance = MyClass()\n\n# Instance method\nmyInstance.myMethod(someParameter)\n# A method can also be retrieved as an attribute from the class, and then explicitly called on an instance:\nMyClass.myMethod(myInstance, someParameter)\n\n\n# Class or static methods\nMyClass.myClassMethod(someParameter)\nMyClass.myStaticMethod(someParameter)\n# You can also call class or static methods on an instance, which will simply call it on the instance's class\nmyInstance.myClassMethod(someParameter)\nmyInstance.myStaticMethod(someParameter)\n", "language": "Python" }, { "code": "( ---------------- zen object orientation -------------- )\n\n[ immovable\n ]this[ swap do ]done[ ] is object ( --> )\n\n[ ]'[ ] is method ( --> [ )\n\n[ method\n [ dup share\n swap put ] ] is localise ( --> [ )\n\n[ method [ release ] ] is delocalise ( --> [ )\n\n\n( -------------- example: counter methods -------------- )\n\n( to create a counter object, use:\n \"[ object 0 ] is 'name' ( [ --> )\" )\n\n[ method\n [ 0 swap replace ] ] is reset-counter ( --> [ )\n\n[ method\n [ 1 swap tally ] ] is increment-counter ( --> [ )\n\n[ method [ share ] ] is report-counter ( --> [ )\n\n\n( -------------------- demonstration ------------------- )\n\nsay 'Creating counter object: \"mycounter\".' cr cr\n[ object 0 ] is mycounter ( [ --> )\n\nsay \"Initial value of mycounter: \"\nreport-counter mycounter echo cr cr\n\nsay \"Incrementing mycounter three times.\" cr\n3 times [ increment-counter mycounter ]\n\nsay \"Current value of mycounter: \"\nreport-counter mycounter echo cr cr\n\nsay \"Localising mycounter.\" cr cr\nlocalise mycounter\n\nsay \" Current value of mycounter: \"\nreport-counter mycounter echo cr cr\n\nsay \" Resetting mycounter.\" cr\nreset-counter mycounter\n\nsay \" Current value of mycounter: \"\nreport-counter mycounter echo cr cr\n\nsay \" Incrementing mycounter six times.\" cr\n6 times [ increment-counter mycounter ]\n\nsay \" Current value of mycounter: \"\nreport-counter mycounter echo cr cr\n\nsay \"Delocalising mycounter.\" cr cr\ndelocalise mycounter\n\nsay \"Current value of mycounter: \"\nreport-counter mycounter echo cr cr\n\nsay \"Resetting mycounter.\" cr\nreset-counter mycounter\n\nsay \"Current value of mycounter: \"\nreport-counter mycounter echo cr cr\n", "language": "Quackery" }, { "code": "#lang racket/gui\n\n(define timer (new timer%))\n(send timer start 100)\n", "language": "Racket" }, { "code": "class Thing {\n method regular-example() { say 'I haz a method' }\n\n multi method multi-example() { say 'No arguments given' }\n multi method multi-example(Str $foo) { say 'String given' }\n multi method multi-example(Int $foo) { say 'Integer given' }\n};\n\n# 'new' is actually a method, not a special keyword:\nmy $thing = Thing.new;\n\n# No arguments: parentheses are optional\n$thing.regular-example;\n$thing.regular-example();\n$thing.multi-example;\n$thing.multi-example();\n\n# Arguments: parentheses or colon required\n$thing.multi-example(\"This is a string\");\n$thing.multi-example: \"This is a string\";\n$thing.multi-example(42);\n$thing.multi-example: 42;\n\n# Indirect (reverse order) method call syntax: colon required\nmy $foo = new Thing: ;\nmulti-example $thing: 42;\n", "language": "Raku" }, { "code": "my @array = <a z c d y>;\n@array .= sort; # short for @array = @array.sort;\n\nsay @array».uc; # uppercase all the strings: A C D Y Z\n", "language": "Raku" }, { "code": "my $object = \"a string\"; # Everything is an object.\nmy method example-method {\n return \"This is { self }.\";\n}\n\nsay $object.&example-method; # Outputs \"This is a string.\"\n", "language": "Raku" }, { "code": "new point { print() }\nClass Point\n x = 10 y = 20 z = 30\n func print see x + nl + y + nl + z + nl\n", "language": "Ring" }, { "code": "o1 = new System.output.console\no1.print(\"Hello World\")\n\nPackage System.Output\n Class Console\n Func Print cText\n see cText + nl\n", "language": "Ring" }, { "code": "# Class method\nMyClass.some_method(some_parameter)\n\n# Class may be computed at runtime\nfoo = MyClass\nfoo.some_method(some_parameter)\n\n\n# Instance method\nmy_instance.a_method(some_parameter)\n\n# The parentheses are optional\nmy_instance.a_method some_parameter\n\n# Calling a method with no parameters\nmy_instance.another_method\n", "language": "Ruby" }, { "code": "struct Foo;\n\nimpl Foo {\n // implementation of an instance method for struct Foo\n // returning the answer to life\n fn get_the_answer_to_life(&self) -> i32 {\n 42\n }\n\n // implementation of a static method for struct Foo\n // returning a new instance object\n fn new() -> Foo {\n println!(\"Hello, world!\");\n Foo // returning the new Foo object\n }\n}\n\nfn main() {\n // create the instance object foo,\n // by calling the static method new of struct Foo\n let foo = Foo::new();\n\n // get the answer to life\n // by calling the instance method of object foo\n println!(\"The answer to life is {}.\", foo.get_the_answer_to_life());\n\n // Note that in Rust, methods still work on references to the object.\n // Rust will automatically do the appropriate dereferencing to get the method to work:\n let lots_of_references = &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&foo;\n println!(\"The answer to life is still {}.\" lots_of_references.get_the_answer_to_life());\n}\n", "language": "Rust" }, { "code": "/* This class implicitly includes a constructor which accepts an Int and\n * creates \"val variable1: Int\" with that value.\n */\nclass MyClass(val memberVal: Int) { // Acts like a getter, getter automatically generated.\n var variable2 = \"asdf\" // Another instance variable; a public mutable this time\n def this() = this(0) // An auxilliary constructor that instantiates with a default value\n}\n\nobject HelloObject {\n val s = \"Hello\" // Not private, so getter auto-generated\n}\n\n/** Demonstrate use of our example class.\n */\nobject Call_an_object_method extends App {\n val s = \"Hello\"\n val m = new MyClass\n val n = new MyClass(3)\n\n assert(HelloObject.s == \"Hello\") // \"Hello\" by object getterHelloObject\n assert(m.memberVal == 0)\n assert(n.memberVal == 3)\n println(\"Successfully completed without error.\")\n}\n", "language": "Scala" }, { "code": "class MyClass {\n method foo(arg) { say arg }\n}\n\nvar arg = 42;\n\n# Call a class method\nMyClass.foo(arg);\n\n# Alternatively, using an expression for the method name\nMyClass.(:foo)(arg);\n\n# Create an instance\nvar instance = MyClass();\n\n# Instance method\ninstance.foo(arg);\n\n# Alternatively, by using an expression for the method name\ninstance.(:foo)(arg);\n\n# Alternatively, by asking for a method\ninstance.method(:foo)(arg);\n", "language": "Sidef" }, { "code": "\" Class \"\nMyClass selector: someArgument .\n\" or equivalently \"\nfoo := MyClass .\nfoo selector: someArgument.\n\n\" Instance \"\nmyInstance selector: someArgument.\n\n\" Message with multiple arguments \"\nmyInstance fooWithRed:arg1 green:arg2 blue:arg3 .\n\n\" Message with no arguments \"\nmyInstance selector.\n\n\" Binary (operator) message\"\nmyInstance + argument .\n", "language": "Smalltalk" }, { "code": "theCar := (someCondition ifTrue:[ Ford ] ifFalse: [ Jaguar ]) new.\n", "language": "Smalltalk" }, { "code": "whichMessage := #( #'red' #'green' #'blue') at: computedIndex.\nfoo perform: whichMessage\n", "language": "Smalltalk" }, { "code": "theMessage := ('handleFileType' , suffix) asSymbol.\nfoo perform: theMessage.\n", "language": "Smalltalk" }, { "code": "[\n foo perform: theMessage\n] on: MessageNotUnderstood do:[\n Dialog information: 'sorry'\n]\n", "language": "Smalltalk" }, { "code": "\tSomeClass {\n\t\n\t\t*someClassMethod {\n\t\t\t\n\t\t}\n\t\t\n\t\tsomeInstanceMethod {\n\t\t\t\n\t\t}\n\t\t\n\t}\n\t\n\tSomeClass.someClassMethod;\n\t\n\ta = SomeClass.new;\n\ta.someInstanceMethod;\n", "language": "SuperCollider" }, { "code": "// Class\nMyClass.method(someParameter)\n// or equivalently:\nlet foo = MyClass.self\nfoo.method(someParameter)\n\n// Instance\nmyInstance.method(someParameter)\n\n// Method with multiple arguments\nmyInstance.method(red:arg1, green:arg2, blue:arg3)\n", "language": "Swift" }, { "code": "package require Tcl 8.6\n# \"Static\" (on class object)\nMyClass mthd someParameter\n\n# Instance\n$myInstance mthd someParameter\n", "language": "Tcl" }, { "code": "(defvarl thing-count 0)\n\n(defstruct thing ()\n (call-count 0)\n\n (:init (me)\n (inc thing-count))\n (:function get-thing-count () thing-count)\n (:method get-call-count (me) (inc me.call-count)))\n\n(let ((t1 (new thing))\n (t2 (new thing)))\n (prinl t1.(get-call-count)) ;; prints 1\n (prinl t1.(get-call-count)) ;; prints 2\n (prinl t1.(get-call-count)) ;; prints 3\n (prinl t2.(get-call-count)) ;; prints 1\n (prinl t2.(get-call-count)) ;; prints 2\n (prinl t2.(get-call-count)) ;; prints 3\n\n (prinl [t1.get-thing-count]) ;; prints 2\n (prinl [t2.get-thing-count])) ;; prints 2\n", "language": "TXR" }, { "code": "# create an instance of the built-in file class\ndecl file f\n\n# call the file.open method\nf.open \"filename.txt\"\n", "language": "Ursa" }, { "code": "// Assigning methods to structs\nstruct HelloWorld {}\n\n// Method's in Vlang are functions with special receiver arguments at the front (between fn and method name)\nfn (sh HelloWorld) say_hello() {\n\t println(\"Hello, world!\")\n}\n\nfn (sb HelloWorld) say_bye() {\n\t println(\"Goodbye, world!\")\n}\n\nfn main() {\n\n\t// instantiate object\n\thw := HelloWorld{}\n\t\n\t// call methods of object\n\thw.say_hello()\n\thw.say_bye()\n}\n", "language": "V-(Vlang)" }, { "code": "// myfile.v\nmodule mymodule\n\n// Use \"pub\" to export a function\npub fn say_hi() {\n\tprintln(\"hello from mymodule!\")\n}\n", "language": "V-(Vlang)" }, { "code": "import mymodule\n\nfn main() {\n\tmymodule.say_hi()\n}\n", "language": "V-(Vlang)" }, { "code": "Option Explicit\n\nSub Method_1(Optional myStr As String)\nDim strTemp As String\n If myStr <> \"\" Then strTemp = myStr\n Debug.Print strTemp\nEnd Sub\n\nStatic Sub Method_2(Optional myStr As String)\nDim strTemp As String\n If myStr <> \"\" Then strTemp = myStr\n Debug.Print strTemp\nEnd Sub\n", "language": "VBA" }, { "code": "Option Explicit\n\nSub test()\nDim Obj As New myObject\n Obj.Method_1 \"Hello to you\"\n Obj.Method_2 \"What is your name ?\"\n Obj.Method_1\n Obj.Method_2\nEnd Sub\n", "language": "VBA" }, { "code": "class MyClass {\n construct new() {}\n method() { System.print(\"instance method called\") }\n static method() { System.print(\"static method called\") }\n}\n\nvar mc = MyClass.new()\nmc.method()\nMyClass.method()\n", "language": "Wren" }, { "code": "class MyClass {\n\tconstruct=func(self,Props){\n\t\tself:Props=Props;\n\t}{Props={}}\n\tGetProp=func(self,Name){\n\t\tsend self.Props[Name];\n\t}\n}\n\nset Class = new MyClass with [{Name=\"MyClass Name\"}];\nlog(Class::GetProp(\"Name\"));\n", "language": "XBS" }, { "code": "set MyObj = {\n\ta=10;\n\tAddA=func(self,x){\n\t\tsend self.a+x;\n\t};\n}\n\nlog(MyObj::AddA(2));\n", "language": "XBS" }, { "code": "(DEFINE-CLASS MY-CLASS)\n\n(DEFINE-CLASS-METHOD (MY-CLASS 'DO-SOMETHING-WITH SOME-PARAMETER)\n (DISPLAY \"I am the class -- \")\n (DISPLAY SELF)\n (NEWLINE)\n (DISPLAY \"You sent me the parameter \")\n (DISPLAY SOME-PARAMETER)\n (NEWLINE))\n\n(DEFINE-METHOD (MY-CLASS 'DO-SOMETHING-WITH SOME-PARAMETER)\n (DISPLAY \"I am an instance of the class -- \")\n (DISPLAY SELF)\n (NEWLINE)\n (DISPLAY \"You sent me the parameter \")\n (DISPLAY SOME-PARAMETER)\n (NEWLINE))\n\n(MY-CLASS 'DO-SOMETHING-WITH 'FOO)\n\n(DEFINE MY-INSTANCE (MY-CLASS 'NEW))\n\n(MY-INSTANCE 'DO-SOMETHING-WITH 'BAR)\n", "language": "XLISP" }, { "code": "const testing = @import(\"std\").testing;\n\npub const ID = struct {\n name: []const u8,\n age: u7,\n\n const Self = @This();\n\n pub fn init(name: []const u8, age: u7) Self {\n return Self{\n .name = name,\n .age = age,\n };\n }\n\n pub fn getAge(self: Self) u7 {\n return self.age;\n }\n};\n\ntest \"call an object method\" {\n // Declare an instance of a struct by using a struct method.\n const person1 = ID.init(\"Alice\", 18);\n\n // Or by declaring it manually.\n const person2 = ID{\n .name = \"Bob\",\n .age = 20,\n };\n\n // test getAge() method call\n try testing.expectEqual(@as(u7, 18), person1.getAge());\n try testing.expectEqual(@as(u7, 20), ID.getAge(person2));\n}\n", "language": "Zig" }, { "code": "class C{var v; fcn f{v}}\nC.f() // call function f in class C\nC.v=5; c2:=C(); // create new instance of C\nprintln(C.f(),\" \",c2.f()) //-->5 Void\nC.f.isStatic //--> False\n\nclass [static] D{var v=123; fcn f{v}}\nD.f(); D().f(); // both return 123\nD.f.isStatic //-->False\n\nclass E{var v; fcn f{}} E.f.isStatic //-->True\n", "language": "Zkl" } ]
Call-an-object-method
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Canny_edge_detector\nnote: Image processing\n", "language": "00-META" }, { "code": ";Task:\nWrite a program that performs so-called [[wp:Canny edge detector|canny edge detection]] on an image.\n\n\n\nA possible algorithm consists of the following steps:\n\n# '''Noise reduction.''' &nbsp; May be performed by [[wp:Gaussian blur|Gaussian filter]]. <br> &nbsp;\n# Compute '''intensity gradient''' &nbsp; (matrices <math>G_x</math> and <math>G_y</math>) &nbsp; and its '''magnitude''' &nbsp; <math>G</math>:<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <math>G=\\sqrt{G_x^2+G_y^2}</math><br>May be performed by [[image convolution|convolution of an image]] with [[wp:Sobel operator|Sobel operators]]. <br> &nbsp;\n# '''Non-maximum suppression.''' &nbsp; <br>For each pixel compute the orientation of intensity gradient vector: &nbsp; <math>\\theta = {\\rm atan2}\\left(G_y, \\, G_x\\right)</math>. &nbsp; &nbsp; <br>Transform &nbsp; angle <math>\\theta</math> &nbsp; to one of four directions: &nbsp; 0,&nbsp;45,&nbsp;90,&nbsp;135&nbsp;degrees. &nbsp; &nbsp; <br>Compute new array &nbsp; <math>N</math>: &nbsp; &nbsp; if &nbsp; &nbsp; &nbsp; &nbsp; <math>G\\left(p_a\\right)<G\\left(p\\right)<G\\left(p_b\\right)</math><br>where &nbsp; <math>p</math> &nbsp; is the current pixel, &nbsp; <math>p_a</math> &nbsp; and &nbsp; <math>p_b</math> &nbsp; are the two neighbour pixels in the direction of gradient, &nbsp; <br>then &nbsp; &nbsp; <math>N(p) = G(p)</math>, &nbsp; &nbsp; &nbsp; otherwise &nbsp; <math>N(p) = 0</math>. &nbsp; <br>Nonzero pixels in resulting array correspond to local maxima of &nbsp; <math>G</math> &nbsp; in direction &nbsp; <math>\\theta(p)</math>. <br> &nbsp;\n# '''Tracing edges with hysteresis.''' &nbsp; <br>At this stage two thresholds for the values of &nbsp; <math>G</math> &nbsp; are introduced: &nbsp; <math>T_{min}</math> &nbsp; and &nbsp; <math>T_{max}</math>. &nbsp; <br>Starting from pixels with &nbsp; <math>N(p) \\geqslant T_{max}</math>, &nbsp; <br>find all paths of pixels with &nbsp; <math>N(p) \\geqslant T_{min}</math> &nbsp; and put them to the resulting image.\n<br><br>\n", "language": "00-TASK" }, { "code": "#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <float.h>\n#include <math.h>\n#include <string.h>\n#include <stdbool.h>\n#include <assert.h>\n\n#define MAX_BRIGHTNESS 255\n\n// C99 doesn't define M_PI (GNU-C99 does)\n#define M_PI 3.14159265358979323846264338327\n\n/*\n * Loading part taken from\n * http://www.vbforums.com/showthread.php?t=261522\n * BMP info:\n * http://en.wikipedia.org/wiki/BMP_file_format\n *\n * Note: the magic number has been removed from the bmpfile_header_t\n * structure since it causes alignment problems\n * bmpfile_magic_t should be written/read first\n * followed by the\n * bmpfile_header_t\n * [this avoids compiler-specific alignment pragmas etc.]\n */\n\ntypedef struct {\n uint8_t magic[2];\n} bmpfile_magic_t;\n\ntypedef struct {\n uint32_t filesz;\n uint16_t creator1;\n uint16_t creator2;\n uint32_t bmp_offset;\n} bmpfile_header_t;\n\ntypedef struct {\n uint32_t header_sz;\n int32_t width;\n int32_t height;\n uint16_t nplanes;\n uint16_t bitspp;\n uint32_t compress_type;\n uint32_t bmp_bytesz;\n int32_t hres;\n int32_t vres;\n uint32_t ncolors;\n uint32_t nimpcolors;\n} bitmap_info_header_t;\n\ntypedef struct {\n uint8_t r;\n uint8_t g;\n uint8_t b;\n uint8_t nothing;\n} rgb_t;\n\n// Use short int instead `unsigned char' so that we can\n// store negative values.\ntypedef short int pixel_t;\n\npixel_t *load_bmp(const char *filename,\n bitmap_info_header_t *bitmapInfoHeader)\n{\n FILE *filePtr = fopen(filename, \"rb\");\n if (filePtr == NULL) {\n perror(\"fopen()\");\n return NULL;\n }\n\n bmpfile_magic_t mag;\n if (fread(&mag, sizeof(bmpfile_magic_t), 1, filePtr) != 1) {\n fclose(filePtr);\n return NULL;\n }\n\n // verify that this is a bmp file by check bitmap id\n // warning: dereferencing type-punned pointer will break\n // strict-aliasing rules [-Wstrict-aliasing]\n if (*((uint16_t*)mag.magic) != 0x4D42) {\n fprintf(stderr, \"Not a BMP file: magic=%c%c\\n\",\n mag.magic[0], mag.magic[1]);\n fclose(filePtr);\n return NULL;\n }\n\n bmpfile_header_t bitmapFileHeader; // our bitmap file header\n // read the bitmap file header\n if (fread(&bitmapFileHeader, sizeof(bmpfile_header_t),\n 1, filePtr) != 1) {\n fclose(filePtr);\n return NULL;\n }\n\n // read the bitmap info header\n if (fread(bitmapInfoHeader, sizeof(bitmap_info_header_t),\n 1, filePtr) != 1) {\n fclose(filePtr);\n return NULL;\n }\n\n if (bitmapInfoHeader->compress_type != 0)\n fprintf(stderr, \"Warning, compression is not supported.\\n\");\n\n // move file point to the beginning of bitmap data\n if (fseek(filePtr, bitmapFileHeader.bmp_offset, SEEK_SET)) {\n fclose(filePtr);\n return NULL;\n }\n\n // allocate enough memory for the bitmap image data\n pixel_t *bitmapImage = malloc(bitmapInfoHeader->bmp_bytesz *\n sizeof(pixel_t));\n\n // verify memory allocation\n if (bitmapImage == NULL) {\n fclose(filePtr);\n return NULL;\n }\n\n // read in the bitmap image data\n size_t pad, count=0;\n unsigned char c;\n pad = 4*ceil(bitmapInfoHeader->bitspp*bitmapInfoHeader->width/32.) - bitmapInfoHeader->width;\n for(size_t i=0; i<bitmapInfoHeader->height; i++){\n\t for(size_t j=0; j<bitmapInfoHeader->width; j++){\n\t\t if (fread(&c, sizeof(unsigned char), 1, filePtr) != 1) {\n\t\t\t fclose(filePtr);\n\t\t\t return NULL;\n\t\t }\n\t\t bitmapImage[count++] = (pixel_t) c;\n\t }\n\t fseek(filePtr, pad, SEEK_CUR);\n }\n\n // If we were using unsigned char as pixel_t, then:\n // fread(bitmapImage, 1, bitmapInfoHeader->bmp_bytesz, filePtr);\n\n // close file and return bitmap image data\n fclose(filePtr);\n return bitmapImage;\n}\n\n// Return: true on error.\nbool save_bmp(const char *filename, const bitmap_info_header_t *bmp_ih,\n const pixel_t *data)\n{\n FILE* filePtr = fopen(filename, \"wb\");\n if (filePtr == NULL)\n return true;\n\n bmpfile_magic_t mag = {{0x42, 0x4d}};\n if (fwrite(&mag, sizeof(bmpfile_magic_t), 1, filePtr) != 1) {\n fclose(filePtr);\n return true;\n }\n\n const uint32_t offset = sizeof(bmpfile_magic_t) +\n sizeof(bmpfile_header_t) +\n sizeof(bitmap_info_header_t) +\n ((1U << bmp_ih->bitspp) * 4);\n\n const bmpfile_header_t bmp_fh = {\n .filesz = offset + bmp_ih->bmp_bytesz,\n .creator1 = 0,\n .creator2 = 0,\n .bmp_offset = offset\n };\n\n if (fwrite(&bmp_fh, sizeof(bmpfile_header_t), 1, filePtr) != 1) {\n fclose(filePtr);\n return true;\n }\n if (fwrite(bmp_ih, sizeof(bitmap_info_header_t), 1, filePtr) != 1) {\n fclose(filePtr);\n return true;\n }\n\n // Palette\n for (size_t i = 0; i < (1U << bmp_ih->bitspp); i++) {\n const rgb_t color = {(uint8_t)i, (uint8_t)i, (uint8_t)i};\n if (fwrite(&color, sizeof(rgb_t), 1, filePtr) != 1) {\n fclose(filePtr);\n return true;\n }\n }\n\n // We use int instead of uchar, so we can't write img\n // in 1 call any more.\n // fwrite(data, 1, bmp_ih->bmp_bytesz, filePtr);\n\n // Padding: http://en.wikipedia.org/wiki/BMP_file_format#Pixel_storage\n size_t pad = 4*ceil(bmp_ih->bitspp*bmp_ih->width/32.) - bmp_ih->width;\n unsigned char c;\n for(size_t i=0; i < bmp_ih->height; i++) {\n\t for(size_t j=0; j < bmp_ih->width; j++) {\n\t\t c = (unsigned char) data[j + bmp_ih->width*i];\n\t\t if (fwrite(&c, sizeof(char), 1, filePtr) != 1) {\n\t\t\t fclose(filePtr);\n\t\t\t return true;\n\t\t }\n\t }\n\t c = 0;\n\t for(size_t j=0; j<pad; j++)\n\t\t if (fwrite(&c, sizeof(char), 1, filePtr) != 1) {\n\t\t\t fclose(filePtr);\n\t\t\t return true;\n\t\t }\n }\n\n fclose(filePtr);\n return false;\n}\n\n// if normalize is true, map pixels to range 0..MAX_BRIGHTNESS\nvoid convolution(const pixel_t *in, pixel_t *out, const float *kernel,\n const int nx, const int ny, const int kn,\n const bool normalize)\n{\n assert(kn % 2 == 1);\n assert(nx > kn && ny > kn);\n const int khalf = kn / 2;\n float min = FLT_MAX, max = -FLT_MAX;\n\n if (normalize)\n for (int m = khalf; m < nx - khalf; m++)\n for (int n = khalf; n < ny - khalf; n++) {\n float pixel = 0.0;\n size_t c = 0;\n for (int j = -khalf; j <= khalf; j++)\n for (int i = -khalf; i <= khalf; i++) {\n pixel += in[(n - j) * nx + m - i] * kernel[c];\n c++;\n }\n if (pixel < min)\n min = pixel;\n if (pixel > max)\n max = pixel;\n }\n\n for (int m = khalf; m < nx - khalf; m++)\n for (int n = khalf; n < ny - khalf; n++) {\n float pixel = 0.0;\n size_t c = 0;\n for (int j = -khalf; j <= khalf; j++)\n for (int i = -khalf; i <= khalf; i++) {\n pixel += in[(n - j) * nx + m - i] * kernel[c];\n c++;\n }\n\n if (normalize)\n pixel = MAX_BRIGHTNESS * (pixel - min) / (max - min);\n out[n * nx + m] = (pixel_t)pixel;\n }\n}\n\n/*\n * gaussianFilter:\n * http://www.songho.ca/dsp/cannyedge/cannyedge.html\n * determine size of kernel (odd #)\n * 0.0 <= sigma < 0.5 : 3\n * 0.5 <= sigma < 1.0 : 5\n * 1.0 <= sigma < 1.5 : 7\n * 1.5 <= sigma < 2.0 : 9\n * 2.0 <= sigma < 2.5 : 11\n * 2.5 <= sigma < 3.0 : 13 ...\n * kernelSize = 2 * int(2*sigma) + 3;\n */\nvoid gaussian_filter(const pixel_t *in, pixel_t *out,\n const int nx, const int ny, const float sigma)\n{\n const int n = 2 * (int)(2 * sigma) + 3;\n const float mean = (float)floor(n / 2.0);\n float kernel[n * n]; // variable length array\n\n fprintf(stderr, \"gaussian_filter: kernel size %d, sigma=%g\\n\",\n n, sigma);\n size_t c = 0;\n for (int i = 0; i < n; i++)\n for (int j = 0; j < n; j++) {\n kernel[c] = exp(-0.5 * (pow((i - mean) / sigma, 2.0) +\n pow((j - mean) / sigma, 2.0)))\n / (2 * M_PI * sigma * sigma);\n c++;\n }\n\n convolution(in, out, kernel, nx, ny, n, true);\n}\n\n/*\n * Links:\n * http://en.wikipedia.org/wiki/Canny_edge_detector\n * http://www.tomgibara.com/computer-vision/CannyEdgeDetector.java\n * http://fourier.eng.hmc.edu/e161/lectures/canny/node1.html\n * http://www.songho.ca/dsp/cannyedge/cannyedge.html\n *\n * Note: T1 and T2 are lower and upper thresholds.\n */\npixel_t *canny_edge_detection(const pixel_t *in,\n const bitmap_info_header_t *bmp_ih,\n const int tmin, const int tmax,\n const float sigma)\n{\n const int nx = bmp_ih->width;\n const int ny = bmp_ih->height;\n\n pixel_t *G = calloc(nx * ny * sizeof(pixel_t), 1);\n pixel_t *after_Gx = calloc(nx * ny * sizeof(pixel_t), 1);\n pixel_t *after_Gy = calloc(nx * ny * sizeof(pixel_t), 1);\n pixel_t *nms = calloc(nx * ny * sizeof(pixel_t), 1);\n pixel_t *out = malloc(bmp_ih->bmp_bytesz * sizeof(pixel_t));\n\n if (G == NULL || after_Gx == NULL || after_Gy == NULL ||\n nms == NULL || out == NULL) {\n fprintf(stderr, \"canny_edge_detection:\"\n \" Failed memory allocation(s).\\n\");\n exit(1);\n }\n\n gaussian_filter(in, out, nx, ny, sigma);\n\n const float Gx[] = {-1, 0, 1,\n -2, 0, 2,\n -1, 0, 1};\n\n convolution(out, after_Gx, Gx, nx, ny, 3, false);\n\n const float Gy[] = { 1, 2, 1,\n 0, 0, 0,\n -1,-2,-1};\n\n convolution(out, after_Gy, Gy, nx, ny, 3, false);\n\n for (int i = 1; i < nx - 1; i++)\n for (int j = 1; j < ny - 1; j++) {\n const int c = i + nx * j;\n // G[c] = abs(after_Gx[c]) + abs(after_Gy[c]);\n G[c] = (pixel_t)hypot(after_Gx[c], after_Gy[c]);\n }\n\n // Non-maximum suppression, straightforward implementation.\n for (int i = 1; i < nx - 1; i++)\n for (int j = 1; j < ny - 1; j++) {\n const int c = i + nx * j;\n const int nn = c - nx;\n const int ss = c + nx;\n const int ww = c + 1;\n const int ee = c - 1;\n const int nw = nn + 1;\n const int ne = nn - 1;\n const int sw = ss + 1;\n const int se = ss - 1;\n\n const float dir = (float)(fmod(atan2(after_Gy[c],\n after_Gx[c]) + M_PI,\n M_PI) / M_PI) * 8;\n\n if (((dir <= 1 || dir > 7) && G[c] > G[ee] &&\n G[c] > G[ww]) || // 0 deg\n ((dir > 1 && dir <= 3) && G[c] > G[nw] &&\n G[c] > G[se]) || // 45 deg\n ((dir > 3 && dir <= 5) && G[c] > G[nn] &&\n G[c] > G[ss]) || // 90 deg\n ((dir > 5 && dir <= 7) && G[c] > G[ne] &&\n G[c] > G[sw])) // 135 deg\n nms[c] = G[c];\n else\n nms[c] = 0;\n }\n\n // Reuse array\n // used as a stack. nx*ny/2 elements should be enough.\n int *edges = (int*) after_Gy;\n memset(out, 0, sizeof(pixel_t) * nx * ny);\n memset(edges, 0, sizeof(pixel_t) * nx * ny);\n\n // Tracing edges with hysteresis . Non-recursive implementation.\n size_t c = 1;\n for (int j = 1; j < ny - 1; j++)\n for (int i = 1; i < nx - 1; i++) {\n if (nms[c] >= tmax && out[c] == 0) { // trace edges\n out[c] = MAX_BRIGHTNESS;\n int nedges = 1;\n edges[0] = c;\n\n do {\n nedges--;\n const int t = edges[nedges];\n\n int nbs[8]; // neighbours\n nbs[0] = t - nx; // nn\n nbs[1] = t + nx; // ss\n nbs[2] = t + 1; // ww\n nbs[3] = t - 1; // ee\n nbs[4] = nbs[0] + 1; // nw\n nbs[5] = nbs[0] - 1; // ne\n nbs[6] = nbs[1] + 1; // sw\n nbs[7] = nbs[1] - 1; // se\n\n for (int k = 0; k < 8; k++)\n if (nms[nbs[k]] >= tmin && out[nbs[k]] == 0) {\n out[nbs[k]] = MAX_BRIGHTNESS;\n edges[nedges] = nbs[k];\n nedges++;\n }\n } while (nedges > 0);\n }\n c++;\n }\n\n free(after_Gx);\n free(after_Gy);\n free(G);\n free(nms);\n\n return out;\n}\n\nint main(const int argc, const char ** const argv)\n{\n if (argc < 2) {\n printf(\"Usage: %s image.bmp\\n\", argv[0]);\n return 1;\n }\n\n static bitmap_info_header_t ih;\n const pixel_t *in_bitmap_data = load_bmp(argv[1], &ih);\n if (in_bitmap_data == NULL) {\n fprintf(stderr, \"main: BMP image not loaded.\\n\");\n return 1;\n }\n\n printf(\"Info: %d x %d x %d\\n\", ih.width, ih.height, ih.bitspp);\n\n const pixel_t *out_bitmap_data =\n canny_edge_detection(in_bitmap_data, &ih, 45, 50, 1.0f);\n if (out_bitmap_data == NULL) {\n fprintf(stderr, \"main: failed canny_edge_detection.\\n\");\n return 1;\n }\n\n if (save_bmp(\"out.bmp\", &ih, out_bitmap_data)) {\n fprintf(stderr, \"main: BMP image not saved.\\n\");\n return 1;\n }\n\n free((pixel_t*)in_bitmap_data);\n free((pixel_t*)out_bitmap_data);\n return 0;\n}\n", "language": "C" }, { "code": "import core.stdc.stdio, std.math, std.typecons, std.string, std.conv,\n std.algorithm, std.ascii, std.array, bitmap, grayscale_image;\n\nenum maxBrightness = 255;\n\nalias Pixel = short;\nalias IntT = typeof(size_t.init.signed);\n\n// If normalize is true, map pixels to range 0...maxBrightness.\nvoid convolution(bool normalize)(in Pixel[] inp, Pixel[] outp,\n in float[] kernel,\n in IntT nx, in IntT ny, in IntT kn)\npure nothrow @nogc in {\n assert(kernel.length == kn ^^ 2);\n assert(kn % 2 == 1);\n assert(nx > kn && ny > kn);\n assert(inp.length == outp.length);\n} body {\n //immutable IntT kn = sqrti(kernel.length);\n immutable IntT khalf = kn / 2;\n\n static if (normalize) {\n float pMin = float.max, pMax = -float.max;\n\n foreach (immutable m; khalf .. nx - khalf) {\n foreach (immutable n; khalf .. ny - khalf) {\n float pixel = 0.0;\n size_t c;\n foreach (immutable j; -khalf .. khalf + 1) {\n foreach (immutable i; -khalf .. khalf + 1) {\n pixel += inp[(n - j) * nx + m - i] * kernel[c];\n c++;\n }\n }\n\n if (pixel < pMin) pMin = pixel;\n if (pixel > pMax) pMax = pixel;\n }\n }\n }\n\n foreach (immutable m; khalf .. nx - khalf) {\n foreach (immutable n; khalf .. ny - khalf) {\n float pixel = 0.0;\n size_t c;\n foreach (immutable j; -khalf .. khalf + 1) {\n foreach (immutable i; -khalf .. khalf + 1) {\n pixel += inp[(n - j) * nx + m - i] * kernel[c];\n c++;\n }\n }\n\n static if (normalize)\n pixel = maxBrightness * (pixel - pMin) / (pMax - pMin);\n outp[n * nx + m] = cast(Pixel)pixel;\n }\n }\n}\n\n\nvoid gaussianFilter(in Pixel[] inp, Pixel[] outp,\n in IntT nx, in IntT ny, in float sigma)\npure nothrow in {\n assert(inp.length == outp.length);\n} body {\n immutable IntT n = 2 * cast(IntT)(2 * sigma) + 3;\n immutable float mean = floor(n / 2.0);\n auto kernel = new float[n * n];\n\n debug fprintf(stderr,\n \"gaussianFilter: kernel size %d, sigma=%g\\n\",\n n, sigma);\n\n size_t c;\n foreach (immutable i; 0 .. n) {\n foreach (immutable j; 0 .. n) {\n kernel[c] = exp(-0.5 * (((i - mean) / sigma) ^^ 2 +\n ((j - mean) / sigma) ^^ 2))\n / (2 * PI * sigma * sigma);\n c++;\n }\n }\n\n convolution!true(inp, outp, kernel, nx, ny, n);\n}\n\n\nImage!Pixel cannyEdgeDetection(in Image!Pixel inp,\n in IntT tMin, in IntT tMax,\n in float sigma)\npure nothrow in {\n assert(inp !is null);\n} body {\n immutable IntT nx = inp.nx.signed;\n immutable IntT ny = inp.ny.signed;\n auto outp = new Pixel[nx * ny];\n\n gaussianFilter(inp.image, outp, nx, ny, sigma);\n\n static immutable float[] Gx = [-1, 0, 1,\n -2, 0, 2,\n -1, 0, 1];\n auto after_Gx = new Pixel[nx * ny];\n convolution!false(outp, after_Gx, Gx, nx, ny, 3);\n\n static immutable float[] Gy = [ 1, 2, 1,\n 0, 0, 0,\n -1,-2,-1];\n auto after_Gy = new Pixel[nx * ny];\n convolution!false(outp, after_Gy, Gy, nx, ny, 3);\n\n auto G = new Pixel[nx * ny];\n foreach (i; 1 .. nx - 1)\n foreach (j; 1 .. ny - 1) {\n immutable size_t c = i + nx * j;\n G[c] = cast(Pixel)hypot(after_Gx[c], after_Gy[c]);\n }\n\n // Non-maximum suppression, straightforward implementation.\n auto nms = new Pixel[nx * ny];\n foreach (immutable i; 1 .. nx - 1)\n foreach (immutable j; 1 .. ny - 1) {\n immutable IntT c = i + nx * j,\n nn = c - nx,\n ss = c + nx,\n ww = c + 1,\n ee = c - 1,\n nw = nn + 1,\n ne = nn - 1,\n sw = ss + 1,\n se = ss - 1;\n\n immutable aux = atan2(double(after_Gy[c]),\n double(after_Gx[c])) + PI;\n immutable float dir = float((aux % PI) / PI) * 8;\n\n if (((dir <= 1 || dir > 7) && G[c] > G[ee] &&\n G[c] > G[ww]) || // 0 deg.\n ((dir > 1 && dir <= 3) && G[c] > G[nw] &&\n G[c] > G[se]) || // 45 deg.\n ((dir > 3 && dir <= 5) && G[c] > G[nn] &&\n G[c] > G[ss]) || // 90 deg.\n ((dir > 5 && dir <= 7) && G[c] > G[ne] &&\n G[c] > G[sw])) // 135 deg.\n nms[c] = G[c];\n else\n nms[c] = 0;\n }\n\n // Reuse array used as a stack. nx*ny/2 elements should be enough.\n IntT[] edges = (cast(IntT*)after_Gy.ptr)[0 .. after_Gy.length / 2];\n outp[] = Pixel.init;\n edges[] = 0;\n\n // Tracing edges with hysteresis. Non-recursive implementation.\n size_t c = 1;\n foreach (immutable j; 1 .. ny - 1) {\n foreach (immutable i; 1 .. nx - 1) {\n if (nms[c] >= tMax && outp[c] == 0) { // Trace edges.\n outp[c] = maxBrightness;\n IntT nedges = 1;\n edges[0] = c;\n\n do {\n nedges--;\n immutable IntT t = edges[nedges];\n\n immutable IntT[8] neighbours = [\n t - nx, // nn\n t + nx, // ss\n t + 1, // ww\n t - 1, // ee\n t - nx + 1, // nw\n t - nx - 1, // ne\n t + nx + 1, // sw\n t + nx - 1]; // se\n\n foreach (immutable n; neighbours)\n if (nms[n] >= tMin && outp[n] == 0) {\n outp[n] = maxBrightness;\n edges[nedges] = n;\n nedges++;\n }\n } while (nedges > 0);\n }\n c++;\n }\n }\n\n return Image!Pixel.fromData(outp, nx, ny);\n}\n\n\nvoid main(in string[] args) {\n immutable fileName = (args.length == 2) ? args[1] : \"lena.pgm\";\n Image!Pixel imIn;\n imIn = imIn.loadPGM(fileName);\n printf(\"Image size: %d x %d\\n\", imIn.nx, imIn.ny);\n imIn.cannyEdgeDetection(45, 50, 1.0f).savePGM(\"lena_canny.pgm\");\n}\n", "language": "D" }, { "code": "package main\n\nimport (\n ed \"github.com/Ernyoke/Imger/edgedetection\"\n \"github.com/Ernyoke/Imger/imgio\"\n \"log\"\n)\n\nfunc main() {\n img, err := imgio.ImreadRGBA(\"Valve_original_(1).png\")\n if err != nil {\n log.Fatal(\"Could not read image\", err)\n }\n\n cny, err := ed.CannyRGBA(img, 15, 45, 5)\n if err != nil {\n log.Fatal(\"Could not perform Canny Edge detection\")\n }\n\n err = imgio.Imwrite(cny, \"Valve_canny_(1).png\")\n if err != nil {\n log.Fatal(\"Could not write Canny image to disk\")\n }\n}\n", "language": "Go" }, { "code": "NB. 2D convolution, filtering, ...\n\nconvolve =: 4 : 'x apply (($x) partition y)'\npartition=: 2 1 3 0 |: {:@[ ]\\ 2 1 0 |: {.@[ ]\\ ]\napply=: [: +/ [: +/ *\nmax3x3 =: 3 : '(0<1{1{y) * (>./>./y)'\naddborder =: (0&,@|:@|.)^:4\nnormalize =: ]%+/@,\nattach =: 3 : 'max3x3 (3 3 partition (addborder y))'\nunique =: 3 : 'y*i.$y'\nconnect =: 3 : 'attach^:_ unique y'\n\nNB. on low memory devices, cropping or resampling of high-resolution images may be required\ncrop =: 4 : 0\n 'h w h0 w0' =: x\n |: w{. w0}. |: h{. h0}. y\n)\nresample =: 4 : '|: (1{-x)(+/%#)\\ |: (0{-x)(+/%#)\\ y'\nNB. on e. g. smartphones, image may need to be expanded for viewing\ninflate1 =: 4 : 0\n 'h w' =: $y\n r =: ,y\n c =: #r\n rr =: (c$x) # r\n (h,x*w)$rr\n)\ninflate =: 4 : '|: x inflate1 (|: x inflate1 y)'\n\nNB. Step 1 - gaussian smoothing\nstep1 =: 3 : 0\n NB. Gaussian kernel (from Wikipedia article)\n <] gaussianKernel =: 5 5$2 4 5 4 2 4 9 12 9 4 5 12 15 12 5 4 9 12 9 4 2 4 5 4 2\n gaussianKernel =: gaussianKernel % 159\n gaussianKernel convolve y\n)\n\nNB. Step 2 - gradient\nstep2 =: 3 : 0\n <] gradientKernel =: 3 3$0 _1 0 0j_1 0 0j1 0 1 0\n gradientKernel convolve y\n)\n\nNB. Step 3 - edge detection\nstep3 =: 3 : 0\n NB. find the octant (eighth of circle) in which the gradient lies\n octant =: 3 : '4|(>.(_0.5+((4%(o. 1))*(12&o. y))))'\n <(i:6)(4 : 'octant (x j. y)')\"0/(i:6)\n\n NB. is this gradient greater than [the projection of] a neighbor?\n greaterThan =: 4 : ' (9 o.((x|.y)%y))<1'\n\n NB. is this gradient the greatest of immmediate colinear neighbore?\n greatestOf =: 4 : '(x greaterThan y) *. ((-x) greaterThan y)'\n\n NB. relative address of neighbor relevant to grad direction\n krnl0 =. _1 0\n krnl1 =. _1 _1\n krnl2 =. 0 _1\n krnl3 =. 1 _1\n\n image =. y\n og =. octant image\n\n NB. mask for maximum gradient colinear with gradient\n ok0 =. (0=og) *. krnl0 greatestOf image\n ok1 =. (1=og) *. krnl1 greatestOf image\n ok2 =. (2=og) *. krnl2 greatestOf image\n ok3 =. (3=og) *. krnl3 greatestOf image\n image *. (ok0 +. ok1 +. ok2 +. ok3)\n)\n\nNB. Step 4 - Weak edge suppression\nstep4 =: 3 : 0\n magnitude =. 10&o. y\n NB. weak, strong threshholds\n NB. TODO: parameter picker algorithm or helper\n threshholds =. 1e14 1e15\n nearbyKernel =. 3 3 $ 4 1 4 # 1 0 1\n weak =. magnitude > 0{threshholds\n strong =. magnitude > 1{threshholds\n strongs =. addborder (nearbyKernel convolve strong) > 0\n strong +. (weak *. strongs)\n)\n\nNB. given the edge points, find the edges\n step5 =: connect\n\ncanny =: step5 @ step4 @ step3 @ step2 @ step1\n", "language": "J" }, { "code": "require 'gl2'\ncoclass 'edge'\ncoinsert'jgl2'\n\nPJ=: jpath '~Projects/edges/' NB. optionally install and run as project under IDE\nload PJ,'canny.ijs'\n\nrun=: 3 : 0\n wd 'pc form;pn canny'\n wd 'cc txt static;cn \"Canny in J\";'\n wd 'cc png isidraw'\n wd 'cc inc button;cn \"Next\";'\n wd 'pshow'\n glclear''\n image =: readimg_jqtide_ PJ,'valve.png'\n image =: 240 360 120 150 crop image\n edges =: canny 256 | image\n ids =: }. ~.,edges\n nids =: # ids\n case =: 0\n)\n\nform_inc_button =: 3 : 0\n select. case\n case. 0 do.\n wd 'set txt text \"original image\";'\n img =: 255 setalpha image\n case. 1 do.\n wd 'set txt text \"points on edges\";'\n img =: edges>0\n img =: 1-img\n img =: img * (+/ 256^i.3) * 255\n img =: 255 setalpha img\n ix =: 0\n case. 2 do.\n wd 'set txt text \"... iterating over edges with >75 points ...\";'\n img =: edges=ix{ids\n whilst. (num<75) *. (ix<nids) do.\n img =: edges=ix{ids\n num =: +/,img\n ix=:>:ix\n if. ix=#ids do. case=:_1 end.\n end.\n img =: 1-img\n img =: img * (+/ 256^i.3) * 255\n img =: 255 setalpha img\n ix =: (#ids)|(>:ix)\n end.\n if. case<2 do. case =: >: case end.\n NB. img =: 5 inflate img NB. might need this for high-res cellphone display\n glfill 255 128 255\n glpixels 0 0,(|.$img), ,img\n glpaint''\n)\n\nform_close=: exit bind 0\n\nrun''\n", "language": "J" }, { "code": "import java.awt.image.BufferedImage;\nimport java.util.Arrays;\n\n/**\n * <p><em>This software has been released into the public domain.\n * <strong>Please read the notes in this source file for additional information.\n * </strong></em></p>\n *\n * <p>This class provides a configurable implementation of the Canny edge\n * detection algorithm. This classic algorithm has a number of shortcomings,\n * but remains an effective tool in many scenarios. <em>This class is designed\n * for single threaded use only.</em></p>\n *\n * <p>Sample usage:</p>\n *\n * <pre><code>\n * //create the detector\n * CannyEdgeDetector detector = new CannyEdgeDetector();\n * //adjust its parameters as desired\n * detector.setLowThreshold(0.5f);\n * detector.setHighThreshold(1f);\n * //apply it to an image\n * detector.setSourceImage(frame);\n * detector.process();\n * BufferedImage edges = detector.getEdgesImage();\n * </code></pre>\n *\n * <p>For a more complete understanding of this edge detector's parameters\n * consult an explanation of the algorithm.</p>\n *\n * @author Tom Gibara\n *\n */\n\npublic class CannyEdgeDetector {\n\n\t// statics\n\t\n\tprivate final static float GAUSSIAN_CUT_OFF = 0.005f;\n\tprivate final static float MAGNITUDE_SCALE = 100F;\n\tprivate final static float MAGNITUDE_LIMIT = 1000F;\n\tprivate final static int MAGNITUDE_MAX = (int) (MAGNITUDE_SCALE * MAGNITUDE_LIMIT);\n\n\t// fields\n\t\n\tprivate int height;\n\tprivate int width;\n\tprivate int picsize;\n\tprivate int[] data;\n\tprivate int[] magnitude;\n\tprivate BufferedImage sourceImage;\n\tprivate BufferedImage edgesImage;\n\t\n\tprivate float gaussianKernelRadius;\n\tprivate float lowThreshold;\n\tprivate float highThreshold;\n\tprivate int gaussianKernelWidth;\n\tprivate boolean contrastNormalized;\n\n\tprivate float[] xConv;\n\tprivate float[] yConv;\n\tprivate float[] xGradient;\n\tprivate float[] yGradient;\n\t\n\t// constructors\n\t\n\t/**\n\t * Constructs a new detector with default parameters.\n\t */\n\t\n\tpublic CannyEdgeDetector() {\n\t\tlowThreshold = 2.5f;\n\t\thighThreshold = 7.5f;\n\t\tgaussianKernelRadius = 2f;\n\t\tgaussianKernelWidth = 16;\n\t\tcontrastNormalized = false;\n\t}\n\n\t// accessors\n\t\n\t/**\n\t * The image that provides the luminance data used by this detector to\n\t * generate edges.\n\t *\n\t * @return the source image, or null\n\t */\n\t\n\tpublic BufferedImage getSourceImage() {\n\t\treturn sourceImage;\n\t}\n\t\n\t/**\n\t * Specifies the image that will provide the luminance data in which edges\n\t * will be detected. A source image must be set before the process method\n\t * is called.\n\t *\n\t * @param image a source of luminance data\n\t */\n\t\n\tpublic void setSourceImage(BufferedImage image) {\n\t\tsourceImage = image;\n\t}\n\n\t/**\n\t * Obtains an image containing the edges detected during the last call to\n\t * the process method. The buffered image is an opaque image of type\n\t * BufferedImage.TYPE_INT_ARGB in which edge pixels are white and all other\n\t * pixels are black.\n\t *\n\t * @return an image containing the detected edges, or null if the process\n\t * method has not yet been called.\n\t */\n\t\n\tpublic BufferedImage getEdgesImage() {\n\t\treturn edgesImage;\n\t}\n\n\t/**\n\t * Sets the edges image. Calling this method will not change the operation\n\t * of the edge detector in any way. It is intended to provide a means by\n\t * which the memory referenced by the detector object may be reduced.\n\t *\n\t * @param edgesImage expected (though not required) to be null\n\t */\n\t\n\tpublic void setEdgesImage(BufferedImage edgesImage) {\n\t\tthis.edgesImage = edgesImage;\n\t}\n\n\t/**\n\t * The low threshold for hysteresis. The default value is 2.5.\n\t *\n\t * @return the low hysteresis threshold\n\t */\n\t\n\tpublic float getLowThreshold() {\n\t\treturn lowThreshold;\n\t}\n\t\n\t/**\n\t * Sets the low threshold for hysteresis. Suitable values for this parameter\n\t * must be determined experimentally for each application. It is nonsensical\n\t * (though not prohibited) for this value to exceed the high threshold value.\n\t *\n\t * @param threshold a low hysteresis threshold\n\t */\n\t\n\tpublic void setLowThreshold(float threshold) {\n\t\tif (threshold < 0) throw new IllegalArgumentException();\n\t\tlowThreshold = threshold;\n\t}\n\n\t/**\n\t * The high threshold for hysteresis. The default value is 7.5.\n\t *\n\t * @return the high hysteresis threshold\n\t */\n\t\n\tpublic float getHighThreshold() {\n\t\treturn highThreshold;\n\t}\n\t\n\t/**\n\t * Sets the high threshold for hysteresis. Suitable values for this\n\t * parameter must be determined experimentally for each application. It is\n\t * nonsensical (though not prohibited) for this value to be less than the\n\t * low threshold value.\n\t *\n\t * @param threshold a high hysteresis threshold\n\t */\n\t\n\tpublic void setHighThreshold(float threshold) {\n\t\tif (threshold < 0) throw new IllegalArgumentException();\n\t\thighThreshold = threshold;\n\t}\n\n\t/**\n\t * The number of pixels across which the Gaussian kernel is applied.\n\t * The default value is 16.\n\t *\n\t * @return the radius of the convolution operation in pixels\n\t */\n\t\n\tpublic int getGaussianKernelWidth() {\n\t\treturn gaussianKernelWidth;\n\t}\n\t\n\t/**\n\t * The number of pixels across which the Gaussian kernel is applied.\n\t * This implementation will reduce the radius if the contribution of pixel\n\t * values is deemed negligable, so this is actually a maximum radius.\n\t *\n\t * @param gaussianKernelWidth a radius for the convolution operation in\n\t * pixels, at least 2.\n\t */\n\t\n\tpublic void setGaussianKernelWidth(int gaussianKernelWidth) {\n\t\tif (gaussianKernelWidth < 2) throw new IllegalArgumentException();\n\t\tthis.gaussianKernelWidth = gaussianKernelWidth;\n\t}\n\n\t/**\n\t * The radius of the Gaussian convolution kernel used to smooth the source\n\t * image prior to gradient calculation. The default value is 16.\n\t *\n\t * @return the Gaussian kernel radius in pixels\n\t */\n\t\n\tpublic float getGaussianKernelRadius() {\n\t\treturn gaussianKernelRadius;\n\t}\n\t\n\t/**\n\t * Sets the radius of the Gaussian convolution kernel used to smooth the\n\t * source image prior to gradient calculation.\n\t *\n\t * @return a Gaussian kernel radius in pixels, must exceed 0.1f.\n\t */\n\t\n\tpublic void setGaussianKernelRadius(float gaussianKernelRadius) {\n\t\tif (gaussianKernelRadius < 0.1f) throw new IllegalArgumentException();\n\t\tthis.gaussianKernelRadius = gaussianKernelRadius;\n\t}\n\t\n\t/**\n\t * Whether the luminance data extracted from the source image is normalized\n\t * by linearizing its histogram prior to edge extraction. The default value\n\t * is false.\n\t *\n\t * @return whether the contrast is normalized\n\t */\n\t\n\tpublic boolean isContrastNormalized() {\n\t\treturn contrastNormalized;\n\t}\n\t\n\t/**\n\t * Sets whether the contrast is normalized\n\t * @param contrastNormalized true if the contrast should be normalized,\n\t * false otherwise\n\t */\n\t\n\tpublic void setContrastNormalized(boolean contrastNormalized) {\n\t\tthis.contrastNormalized = contrastNormalized;\n\t}\n\t\n\t// methods\n\t\n\tpublic void process() {\n\t\twidth = sourceImage.getWidth();\n\t\theight = sourceImage.getHeight();\n\t\tpicsize = width * height;\n\t\tinitArrays();\n\t\treadLuminance();\n\t\tif (contrastNormalized) normalizeContrast();\n\t\tcomputeGradients(gaussianKernelRadius, gaussianKernelWidth);\n\t\tint low = Math.round(lowThreshold * MAGNITUDE_SCALE);\n\t\tint high = Math.round( highThreshold * MAGNITUDE_SCALE);\n\t\tperformHysteresis(low, high);\n\t\tthresholdEdges();\n\t\twriteEdges(data);\n\t}\n\n\t// private utility methods\n\t\n\tprivate void initArrays() {\n\t\tif (data == null || picsize != data.length) {\n\t\t\tdata = new int[picsize];\n\t\t\tmagnitude = new int[picsize];\n\n\t\t\txConv = new float[picsize];\n\t\t\tyConv = new float[picsize];\n\t\t\txGradient = new float[picsize];\n\t\t\tyGradient = new float[picsize];\n\t\t}\n\t}\n\t\n\t//NOTE: The elements of the method below (specifically the technique for\n\t//non-maximal suppression and the technique for gradient computation)\n\t//are derived from an implementation posted in the following forum (with the\n\t//clear intent of others using the code):\n\t// http://forum.java.sun.com/thread.jspa?threadID=546211&start=45&tstart=0\n\t//My code effectively mimics the algorithm exhibited above.\n\t//Since I don't know the providence of the code that was posted it is a\n\t//possibility (though I think a very remote one) that this code violates\n\t//someone's intellectual property rights. If this concerns you feel free to\n\t//contact me for an alternative, though less efficient, implementation.\n\t\n\tprivate void computeGradients(float kernelRadius, int kernelWidth) {\n\t\t\n\t\t//generate the gaussian convolution masks\n\t\tfloat kernel[] = new float[kernelWidth];\n\t\tfloat diffKernel[] = new float[kernelWidth];\n\t\tint kwidth;\n\t\tfor (kwidth = 0; kwidth < kernelWidth; kwidth++) {\n\t\t\tfloat g1 = gaussian(kwidth, kernelRadius);\n\t\t\tif (g1 <= GAUSSIAN_CUT_OFF && kwidth >= 2) break;\n\t\t\tfloat g2 = gaussian(kwidth - 0.5f, kernelRadius);\n\t\t\tfloat g3 = gaussian(kwidth + 0.5f, kernelRadius);\n\t\t\tkernel[kwidth] = (g1 + g2 + g3) / 3f / (2f * (float) Math.PI * kernelRadius * kernelRadius);\n\t\t\tdiffKernel[kwidth] = g3 - g2;\n\t\t}\n\n\t\tint initX = kwidth - 1;\n\t\tint maxX = width - (kwidth - 1);\n\t\tint initY = width * (kwidth - 1);\n\t\tint maxY = width * (height - (kwidth - 1));\n\t\t\n\t\t//perform convolution in x and y directions\n\t\tfor (int x = initX; x < maxX; x++) {\n\t\t\tfor (int y = initY; y < maxY; y += width) {\n\t\t\t\tint index = x + y;\n\t\t\t\tfloat sumX = data[index] * kernel[0];\n\t\t\t\tfloat sumY = sumX;\n\t\t\t\tint xOffset = 1;\n\t\t\t\tint yOffset = width;\n\t\t\t\tfor(; xOffset < kwidth ;) {\n\t\t\t\t\tsumY += kernel[xOffset] * (data[index - yOffset] + data[index + yOffset]);\n\t\t\t\t\tsumX += kernel[xOffset] * (data[index - xOffset] + data[index + xOffset]);\n\t\t\t\t\tyOffset += width;\n\t\t\t\t\txOffset++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tyConv[index] = sumY;\n\t\t\t\txConv[index] = sumX;\n\t\t\t}\n\n\t\t}\n\n\t\tfor (int x = initX; x < maxX; x++) {\n\t\t\tfor (int y = initY; y < maxY; y += width) {\n\t\t\t\tfloat sum = 0f;\n\t\t\t\tint index = x + y;\n\t\t\t\tfor (int i = 1; i < kwidth; i++)\n\t\t\t\t\tsum += diffKernel[i] * (yConv[index - i] - yConv[index + i]);\n\n\t\t\t\txGradient[index] = sum;\n\t\t\t}\n\n\t\t}\n\n\t\tfor (int x = kwidth; x < width - kwidth; x++) {\n\t\t\tfor (int y = initY; y < maxY; y += width) {\n\t\t\t\tfloat sum = 0.0f;\n\t\t\t\tint index = x + y;\n\t\t\t\tint yOffset = width;\n\t\t\t\tfor (int i = 1; i < kwidth; i++) {\n\t\t\t\t\tsum += diffKernel[i] * (xConv[index - yOffset] - xConv[index + yOffset]);\n\t\t\t\t\tyOffset += width;\n\t\t\t\t}\n\n\t\t\t\tyGradient[index] = sum;\n\t\t\t}\n\n\t\t}\n\n\t\tinitX = kwidth;\n\t\tmaxX = width - kwidth;\n\t\tinitY = width * kwidth;\n\t\tmaxY = width * (height - kwidth);\n\t\tfor (int x = initX; x < maxX; x++) {\n\t\t\tfor (int y = initY; y < maxY; y += width) {\n\t\t\t\tint index = x + y;\n\t\t\t\tint indexN = index - width;\n\t\t\t\tint indexS = index + width;\n\t\t\t\tint indexW = index - 1;\n\t\t\t\tint indexE = index + 1;\n\t\t\t\tint indexNW = indexN - 1;\n\t\t\t\tint indexNE = indexN + 1;\n\t\t\t\tint indexSW = indexS - 1;\n\t\t\t\tint indexSE = indexS + 1;\n\t\t\t\t\n\t\t\t\tfloat xGrad = xGradient[index];\n\t\t\t\tfloat yGrad = yGradient[index];\n\t\t\t\tfloat gradMag = hypot(xGrad, yGrad);\n\n\t\t\t\t//perform non-maximal supression\n\t\t\t\tfloat nMag = hypot(xGradient[indexN], yGradient[indexN]);\n\t\t\t\tfloat sMag = hypot(xGradient[indexS], yGradient[indexS]);\n\t\t\t\tfloat wMag = hypot(xGradient[indexW], yGradient[indexW]);\n\t\t\t\tfloat eMag = hypot(xGradient[indexE], yGradient[indexE]);\n\t\t\t\tfloat neMag = hypot(xGradient[indexNE], yGradient[indexNE]);\n\t\t\t\tfloat seMag = hypot(xGradient[indexSE], yGradient[indexSE]);\n\t\t\t\tfloat swMag = hypot(xGradient[indexSW], yGradient[indexSW]);\n\t\t\t\tfloat nwMag = hypot(xGradient[indexNW], yGradient[indexNW]);\n\t\t\t\tfloat tmp;\n\t\t\t\t/*\n\t\t\t\t * An explanation of what's happening here, for those who want\n\t\t\t\t * to understand the source: This performs the \"non-maximal\n\t\t\t\t * supression\" phase of the Canny edge detection in which we\n\t\t\t\t * need to compare the gradient magnitude to that in the\n\t\t\t\t * direction of the gradient; only if the value is a local\n\t\t\t\t * maximum do we consider the point as an edge candidate.\n\t\t\t\t *\n\t\t\t\t * We need to break the comparison into a number of different\n\t\t\t\t * cases depending on the gradient direction so that the\n\t\t\t\t * appropriate values can be used. To avoid computing the\n\t\t\t\t * gradient direction, we use two simple comparisons: first we\n\t\t\t\t * check that the partial derivatives have the same sign (1)\n\t\t\t\t * and then we check which is larger (2). As a consequence, we\n\t\t\t\t * have reduced the problem to one of four identical cases that\n\t\t\t\t * each test the central gradient magnitude against the values at\n\t\t\t\t * two points with 'identical support'; what this means is that\n\t\t\t\t * the geometry required to accurately interpolate the magnitude\n\t\t\t\t * of gradient function at those points has an identical\n\t\t\t\t * geometry (upto right-angled-rotation/reflection).\n\t\t\t\t *\n\t\t\t\t * When comparing the central gradient to the two interpolated\n\t\t\t\t * values, we avoid performing any divisions by multiplying both\n\t\t\t\t * sides of each inequality by the greater of the two partial\n\t\t\t\t * derivatives. The common comparand is stored in a temporary\n\t\t\t\t * variable (3) and reused in the mirror case (4).\n\t\t\t\t *\n\t\t\t\t */\n\t\t\t\tif (xGrad * yGrad <= (float) 0 /*(1)*/\n\t\t\t\t\t? Math.abs(xGrad) >= Math.abs(yGrad) /*(2)*/\n\t\t\t\t\t\t? (tmp = Math.abs(xGrad * gradMag)) >= Math.abs(yGrad * neMag - (xGrad + yGrad) * eMag) /*(3)*/\n\t\t\t\t\t\t\t&& tmp > Math.abs(yGrad * swMag - (xGrad + yGrad) * wMag) /*(4)*/\n\t\t\t\t\t\t: (tmp = Math.abs(yGrad * gradMag)) >= Math.abs(xGrad * neMag - (yGrad + xGrad) * nMag) /*(3)*/\n\t\t\t\t\t\t\t&& tmp > Math.abs(xGrad * swMag - (yGrad + xGrad) * sMag) /*(4)*/\n\t\t\t\t\t: Math.abs(xGrad) >= Math.abs(yGrad) /*(2)*/\n\t\t\t\t\t\t? (tmp = Math.abs(xGrad * gradMag)) >= Math.abs(yGrad * seMag + (xGrad - yGrad) * eMag) /*(3)*/\n\t\t\t\t\t\t\t&& tmp > Math.abs(yGrad * nwMag + (xGrad - yGrad) * wMag) /*(4)*/\n\t\t\t\t\t\t: (tmp = Math.abs(yGrad * gradMag)) >= Math.abs(xGrad * seMag + (yGrad - xGrad) * sMag) /*(3)*/\n\t\t\t\t\t\t\t&& tmp > Math.abs(xGrad * nwMag + (yGrad - xGrad) * nMag) /*(4)*/\n\t\t\t\t\t) {\n\t\t\t\t\tmagnitude[index] = gradMag >= MAGNITUDE_LIMIT ? MAGNITUDE_MAX : (int) (MAGNITUDE_SCALE * gradMag);\n\t\t\t\t\t//NOTE: The orientation of the edge is not employed by this\n\t\t\t\t\t//implementation. It is a simple matter to compute it at\n\t\t\t\t\t//this point as: Math.atan2(yGrad, xGrad);\n\t\t\t\t} else {\n\t\t\t\t\tmagnitude[index] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t//NOTE: It is quite feasible to replace the implementation of this method\n\t//with one which only loosely approximates the hypot function. I've tested\n\t//simple approximations such as Math.abs(x) + Math.abs(y) and they work fine.\n\tprivate float hypot(float x, float y) {\n\t\treturn (float) Math.hypot(x, y);\n\t}\n\n\tprivate float gaussian(float x, float sigma) {\n\t\treturn (float) Math.exp(-(x * x) / (2f * sigma * sigma));\n\t}\n\n\tprivate void performHysteresis(int low, int high) {\n\t\t//NOTE: this implementation reuses the data array to store both\n\t\t//luminance data from the image, and edge intensity from the processing.\n\t\t//This is done for memory efficiency, other implementations may wish\n\t\t//to separate these functions.\n\t\tArrays.fill(data, 0);\n\n\t\tint offset = 0;\n\t\tfor (int y = 0; y < height; y++) {\n\t\t\tfor (int x = 0; x < width; x++) {\n\t\t\t\tif (data[offset] == 0 && magnitude[offset] >= high) {\n\t\t\t\t\tfollow(x, y, offset, low);\n\t\t\t\t}\n\t\t\t\toffset++;\n\t\t\t}\n\t\t}\n \t}\n\n\tprivate void follow(int x1, int y1, int i1, int threshold) {\n\t\tint x0 = x1 == 0 ? x1 : x1 - 1;\n\t\tint x2 = x1 == width - 1 ? x1 : x1 + 1;\n\t\tint y0 = y1 == 0 ? y1 : y1 - 1;\n\t\tint y2 = y1 == height -1 ? y1 : y1 + 1;\n\t\t\n\t\tdata[i1] = magnitude[i1];\n\t\tfor (int x = x0; x <= x2; x++) {\n\t\t\tfor (int y = y0; y <= y2; y++) {\n\t\t\t\tint i2 = x + y * width;\n\t\t\t\tif ((y != y1 || x != x1)\n\t\t\t\t\t&& data[i2] == 0\n\t\t\t\t\t&& magnitude[i2] >= threshold) {\n\t\t\t\t\tfollow(x, y, i2, threshold);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void thresholdEdges() {\n\t\tfor (int i = 0; i < picsize; i++) {\n\t\t\tdata[i] = data[i] > 0 ? -1 : 0xff000000;\n\t\t}\n\t}\n\t\n\tprivate int luminance(float r, float g, float b) {\n\t\treturn Math.round(0.299f * r + 0.587f * g + 0.114f * b);\n\t}\n\t\n\tprivate void readLuminance() {\n\t\tint type = sourceImage.getType();\n\t\tif (type == BufferedImage.TYPE_INT_RGB || type == BufferedImage.TYPE_INT_ARGB) {\n\t\t\tint[] pixels = (int[]) sourceImage.getData().getDataElements(0, 0, width, height, null);\n\t\t\tfor (int i = 0; i < picsize; i++) {\n\t\t\t\tint p = pixels[i];\n\t\t\t\tint r = (p & 0xff0000) >> 16;\n\t\t\t\tint g = (p & 0xff00) >> 8;\n\t\t\t\tint b = p & 0xff;\n\t\t\t\tdata[i] = luminance(r, g, b);\n\t\t\t}\n\t\t} else if (type == BufferedImage.TYPE_BYTE_GRAY) {\n\t\t\tbyte[] pixels = (byte[]) sourceImage.getData().getDataElements(0, 0, width, height, null);\n\t\t\tfor (int i = 0; i < picsize; i++) {\n\t\t\t\tdata[i] = (pixels[i] & 0xff);\n\t\t\t}\n\t\t} else if (type == BufferedImage.TYPE_USHORT_GRAY) {\n\t\t\tshort[] pixels = (short[]) sourceImage.getData().getDataElements(0, 0, width, height, null);\n\t\t\tfor (int i = 0; i < picsize; i++) {\n\t\t\t\tdata[i] = (pixels[i] & 0xffff) / 256;\n\t\t\t}\n\t\t} else if (type == BufferedImage.TYPE_3BYTE_BGR) {\n byte[] pixels = (byte[]) sourceImage.getData().getDataElements(0, 0, width, height, null);\n int offset = 0;\n for (int i = 0; i < picsize; i++) {\n int b = pixels[offset++] & 0xff;\n int g = pixels[offset++] & 0xff;\n int r = pixels[offset++] & 0xff;\n data[i] = luminance(r, g, b);\n }\n } else {\n\t\t\tthrow new IllegalArgumentException(\"Unsupported image type: \" + type);\n\t\t}\n\t}\n\n\tprivate void normalizeContrast() {\n\t\tint[] histogram = new int[256];\n\t\tfor (int i = 0; i < data.length; i++) {\n\t\t\thistogram[data[i]]++;\n\t\t}\n\t\tint[] remap = new int[256];\n\t\tint sum = 0;\n\t\tint j = 0;\n\t\tfor (int i = 0; i < histogram.length; i++) {\n\t\t\tsum += histogram[i];\n\t\t\tint target = sum*255/picsize;\n\t\t\tfor (int k = j+1; k <=target; k++) {\n\t\t\t\tremap[k] = i;\n\t\t\t}\n\t\t\tj = target;\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < data.length; i++) {\n\t\t\tdata[i] = remap[data[i]];\n\t\t}\n\t}\n\t\n\tprivate void writeEdges(int pixels[]) {\n\t\t//NOTE: There is currently no mechanism for obtaining the edge data\n\t\t//in any other format other than an INT_ARGB type BufferedImage.\n\t\t//This may be easily remedied by providing alternative accessors.\n\t\tif (edgesImage == null) {\n\t\t\tedgesImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n\t\t}\n\t\tedgesImage.getWritableTile(0, 0).setDataElements(0, 0, width, height, pixels);\n\t}\n\n}\n", "language": "Java" }, { "code": "using Images\n\ncanny_edges = canny(img, sigma = 1.4, upperThreshold = 0.80, lowerThreshold = 0.20)\n", "language": "Julia" }, { "code": "Export[\"out.bmp\", EdgeDetect[Import[InputString[]]]];\n", "language": "Mathematica" }, { "code": "BWImage = edge(GrayscaleImage,'canny');\n", "language": "MATLAB" }, { "code": "import lenientops\nimport math\nimport nimPNG\n\nconst MaxBrightness = 255\n\ntype Pixel = int16 # Used instead of byte to be able to store negative values.\n\n#---------------------------------------------------------------------------------------------------\n\nfunc convolution*[normalize: static bool](input: seq[Pixel]; output: var seq[Pixel];\n kernel: seq[float]; nx, ny, kn: int) =\n ## Do a convolution.\n ## If normalize is true, map pixels to range 0...maxBrightness.\n\n doAssert kernel.len == kn * kn\n doAssert (kn and 1) == 1\n doAssert nx > kn and ny > kn\n doAssert input.len == output.len\n\n let khalf = kn div 2\n\n when normalize:\n\n var pMin = float.high\n var pMax = -float.high\n\n for m in khalf..<(nx - khalf):\n for n in khalf..<(ny - khalf):\n var pixel = 0.0\n var c = 0\n for j in -khalf..khalf:\n for i in -khalf..khalf:\n pixel += input[(n - j) * nx + m - i] * kernel[c]\n inc c\n if pixel < pMin:\n pMin = pixel\n if pixel > pMax:\n pMax = pixel\n\n for m in khalf..<(nx - khalf):\n for n in khalf..<(ny - khalf):\n var pixel = 0.0\n var c = 0\n for j in -khalf..khalf:\n for i in -khalf..khalf:\n pixel += input[(n - j) * nx + m - i] * kernel[c]\n inc c\n when normalize:\n pixel = MaxBrightness * (pixel - pMin) / (pMax - pMin)\n output[n * nx + m] = Pixel(pixel)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc gaussianFilter(input: seq[Pixel]; output: var seq[Pixel]; nx, ny: int; sigma: float) =\n ## Apply a gaussian filter.\n\n doAssert input.len == output.len\n\n let n = 2 * (2 * sigma).toInt + 3\n let mean = floor(n / 2)\n var kernel = newSeq[float](n * n)\n\n var c = 0\n for i in 0..<n:\n for j in 0..<n:\n kernel[c] = exp(-0.5 * (((i - mean) / sigma) ^ 2 + ((j - mean) / sigma) ^ 2)) /\n (2 * PI * sigma * sigma)\n inc c\n\n convolution[true](input, output, kernel, nx, ny, n)\n\n#---------------------------------------------------------------------------------------------------\n\nproc cannyEdgeDetection(input: seq[Pixel];\n nx, ny: int;\n tmin, tmax: int;\n sigma: float): seq[byte] =\n\n\n\n ## Detect edges.\n var output = newSeq[Pixel](input.len)\n gaussianFilter(input, output, nx, ny, sigma)\n\n const Gx = @[float -1, 0, 1,\n -2, 0, 2,\n -1, 0, 1]\n var afterGx = newSeq[Pixel](input.len)\n convolution[false](input, afterGx, Gx, nx, ny, 3)\n\n const Gy = @[float 1, 2, 1,\n 0, 0, 0,\n -1, -2, -1]\n var afterGy = newSeq[Pixel](input.len)\n convolution[false](input, afterGy, Gy, nx, ny, 3)\n\n var g = newSeq[Pixel](input.len)\n for i in 1..(nx - 2):\n for j in 1..(ny - 2):\n let c = i + nx * j\n g[c] = hypot(afterGx[c].toFloat, afterGy[c].toFloat).Pixel\n\n # Non-maximum suppression: straightforward implementation.\n var nms = newSeq[Pixel](input.len)\n for i in 1..(nx - 2):\n for j in 1..(ny - 2):\n let\n c = i + nx * j\n nn = c - nx\n ss = c + nx\n ww = c + 1\n ee = c - 1\n nw = nn + 1\n ne = nn - 1\n sw = ss + 1\n se = ss - 1\n let aux = arctan2(afterGy[c].toFloat, afterGx[c].toFloat) + PI\n let dir = aux mod PI / PI * 8\n if (((dir <= 1 or dir > 7) and g[c] > g[ee] and g[c] > g[ww]) or # O°.\n ((dir > 1 and dir <= 3) and g[c] > g[nw] and g[c] > g[se]) or # 45°.\n ((dir > 3 and dir <= 5) and g[c] > g[nn] and g[c] > g[ss]) or # 90°.\n ((dir > 5 and dir <= 7) and g[c] > g[ne] and g[c] > g[sw])): # 135°.\n nms[c] = g[c]\n else:\n nms[c] = 0\n\n # Tracing edges with hysteresis. Non-recursive implementation.\n var edges = newSeq[int](input.len div 2)\n for item in output.mitems: item = 0\n var c = 0\n for j in 1..(ny - 2):\n for i in 1..(nx - 2):\n inc c\n\n if nms[c] >= tMax and output[c] == 0:\n # Trace edges.\n output[c] = MaxBrightness\n var nedges = 1\n edges[0] = c\n\n while nedges > 0:\n dec nedges\n let t = edges[nedges]\n let neighbors = [t - nx, # nn.\n t + nx, # ss.\n t + 1, # ww.\n t - 1, # ee.\n t - nx + 1, # nw.\n t - nx - 1, # ne.\n t + nx + 1, # sw.\n t + nx - 1] # se.\n\n for n in neighbors:\n if nms[n] >= tMin and output[n] == 0:\n output[n] = MaxBrightness\n edges[nedges] = n\n inc nedges\n\n # Store the result as a sequence of bytes.\n result = newSeqOfCap[byte](output.len)\n for val in output:\n result.add(byte(val))\n\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nwhen isMainModule:\n\n const\n Input = \"Valve.png\"\n Output = \"Valve_edges.png\"\n\n let pngImage = loadPNG24(seq[byte], Input).get()\n\n # Convert to grayscale and store luminances as 16 bits signed integers.\n var pixels = newSeq[Pixel](pngImage.width * pngImage.height)\n for i in 0..pixels.high:\n pixels[i] = Pixel(0.2126 * pngImage.data[3 * i] +\n 0.7152 * pngImage.data[3 * i + 1] +\n 0.0722 * pngImage.data[3 * i + 2] + 0.5)\n\n # Find edges.\n let data = cannyEdgeDetection(pixels, pngImage.width, pngImage.height, 45, 50, 1.0)\n\n # Save result as a PNG image.\n let status = savePNG(Output, data, LCT_GREY, 8, pngImage.width, pngImage.height)\n if status.isOk:\n echo \"File \", Input, \" processed. Result is available in file \", Output\n else:\n echo \"Error: \", status.error\n", "language": "Nim" }, { "code": "# 20220120 Perl programming solution\n\nuse strict;\nuse warnings;\n\nuse lib '/home/hkdtam/lib';\nuse Image::EdgeDetect;\n\nmy $detector = Image::EdgeDetect->new();\n$detector->process('./input.jpg', './output.jpg') or die; # na.cx/i/pHYdUrV.jpg\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Canny_Edge_Detection.exw\n -- =====================================\n --</span>\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span> <span style=\"color: #000080;font-style:italic;\">-- imImage, im_width, im_height, im_pixel, IupImageRGB,\n -- imFileImageLoadBitmap, and IupImageFromImImage()</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">TITLE</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"Canny Edge Detection\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">IMGFILE</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"Valve.png\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">C_E_D</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}}</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">detect_edges</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">imImage</span> <span style=\"color: #000000;\">img</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">width</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">im_width</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">img</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">height</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">im_height</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">img</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">original</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">fh</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">C_E_D</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">hh</span><span style=\"color: #0000FF;\">=(</span><span style=\"color: #000000;\">fh</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">fw</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">C_E_D</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]),</span> <span style=\"color: #000000;\">hw</span><span style=\"color: #0000FF;\">=(</span><span style=\"color: #000000;\">fw</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">divisor</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">C_E_D</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- read original pixels and make them grey,</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">c1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">c2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">c3</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">im_pixel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">img</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">grey</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">((</span><span style=\"color: #000000;\">c1</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">114</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">c2</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">587</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">c3</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">299</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">1000</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">original</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">grey</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">grey</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">grey</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- then apply an edge detection filter</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">new_image</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">original</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">hh</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">hh</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">hw</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">hw</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">newrgb</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=-</span><span style=\"color: #000000;\">hh</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">hh</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=-</span><span style=\"color: #000000;\">hw</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">hw</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">newrgb</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">newrgb</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">sq_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">C_E_D</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">hh</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">hw</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">original</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">new_image</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_min</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_floor_div</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">newrgb</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">divisor</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">255</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #000000;\">new_image</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">flatten</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">new_image</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (as needed by IupImageRGB)</span>\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">new_img</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">IupImageRGB</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">new_image</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">new_img</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">imImage</span> <span style=\"color: #000000;\">im1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">imFileImageLoadBitmap</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">IMGFILE</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">assert</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">im1</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"error opening \"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">IMGFILE</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">label1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(),</span>\n <span style=\"color: #000000;\">label2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupSetAttributeHandle</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">label1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"IMAGE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">IupImageFromImImage</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">im1</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupSetAttributeHandle</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">label2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"IMAGE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">detect_edges</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">im1</span><span style=\"color: #0000FF;\">))</span>\n\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">IupHbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">label1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">label2</span><span style=\"color: #0000FF;\">}),</span><span style=\"color: #008000;\">`TITLE=\"%s\"`</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">TITLE</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "// input: r,g,b in range 0..255\nfunction RGBtoHSV($r, $g, $b) {\n\t$r = $r/255.; // convert to range 0..1\n\t$g = $g/255.;\n\t$b = $b/255.;\n\t$cols = array(\"r\" => $r, \"g\" => $g, \"b\" => $b);\n\tasort($cols, SORT_NUMERIC);\n\t$min = key(array_slice($cols, 1)); // \"r\", \"g\" or \"b\"\n\t$max = key(array_slice($cols, -1)); // \"r\", \"g\" or \"b\"\n\n\t// hue\n\tif($cols[$min] == $cols[$max]) {\n\t\t$h = 0;\n\t} else {\n\t\tif($max == \"r\") {\n\t\t\t$h = 60. * ( 0 + ( ($cols[\"g\"]-$cols[\"b\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"g\") {\n\t\t\t$h = 60. * ( 2 + ( ($cols[\"b\"]-$cols[\"r\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"b\") {\n\t\t\t$h = 60. * ( 4 + ( ($cols[\"r\"]-$cols[\"g\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t}\n\t\tif($h < 0) {\n\t\t\t$h += 360;\n\t\t}\n\t}\n\n\t// saturation\n\tif($cols[$max] == 0) {\n\t\t$s = 0;\n\t} else {\n\t\t$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );\n\t\t$s = $s * 255;\n\t}\n\n\t// lightness\n\t$v = $cols[$max];\n\t$v = $v * 255;\n\n\treturn(array($h, $s, $v));\n}\n\n$filename = \"image.png\";\n$dimensions = getimagesize($filename);\n$w = $dimensions[0]; // width\n$h = $dimensions[1]; // height\n\n$im = imagecreatefrompng($filename);\n\nfor($hi=0; $hi < $h; $hi++) {\n\n\tfor($wi=0; $wi < $w; $wi++) {\n\t\t$rgb = imagecolorat($im, $wi, $hi);\n\n\t\t$r = ($rgb >> 16) & 0xFF;\n\t\t$g = ($rgb >> 8) & 0xFF;\n\t\t$b = $rgb & 0xFF;\n\t\t$hsv = RGBtoHSV($r, $g, $b);\n\n\t\t// compare pixel below with current pixel\n\t\t$brgb = imagecolorat($im, $wi, $hi+1);\n\t\t$br = ($brgb >> 16) & 0xFF;\n\t\t$bg = ($brgb >> 8) & 0xFF;\n\t\t$bb = $brgb & 0xFF;\n\t\t$bhsv = RGBtoHSV($br, $bg, $bb);\n\n\t\t// if difference in hue > 20, edge is detected\n\t\tif($hsv[2]-$bhsv[2] > 20) {\n imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));\n\t\t}\n else {\n\t\t imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));\n\t\t}\n\t\t\t\n }\n\n}\n\nheader('Content-Type: image/jpeg');\nimagepng($im);\nimagedestroy($im);\n", "language": "PHP" }, { "code": "#!/bin/python\nimport numpy as np\nfrom scipy.ndimage.filters import convolve, gaussian_filter\nfrom scipy.misc import imread, imshow\n\t\ndef CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):\n\tim = np.array(im, dtype=float) #Convert to float to prevent clipping values\n\n\t#Gaussian blur to reduce noise\n\tim2 = gaussian_filter(im, blur)\n\n\t#Use sobel filters to get horizontal and vertical gradients\n\tim3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]])\n\tim3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])\n\n\t#Get gradient and direction\n\tgrad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)\n\ttheta = np.arctan2(im3v, im3h)\n\tthetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 #Quantize direction\n\n\t#Non-maximum suppression\n\tgradSup = grad.copy()\n\tfor r in range(im.shape[0]):\n\t\tfor c in range(im.shape[1]):\n\t\t\t#Suppress pixels at the image edge\n\t\t\tif r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:\n\t\t\t\tgradSup[r, c] = 0\n\t\t\t\tcontinue\n\t\t\ttq = thetaQ[r, c] % 4\n\n\t\t\tif tq == 0: #0 is E-W (horizontal)\n\t\t\t\tif grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 1: #1 is NE-SW\n\t\t\t\tif grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 2: #2 is N-S (vertical)\n\t\t\t\tif grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 3: #3 is NW-SE\n\t\t\t\tif grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\n\t#Double threshold\n\tstrongEdges = (gradSup > highThreshold)\n\n\t#Strong has value 2, weak has value 1\n\tthresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)\n\n\t#Tracing edges with hysteresis\t\n\t#Find weak edge pixels near strong edge pixels\n\tfinalEdges = strongEdges.copy()\n\tcurrentPixels = []\n\tfor r in range(1, im.shape[0]-1):\n\t\tfor c in range(1, im.shape[1]-1):\t\n\t\t\tif thresholdedEdges[r, c] != 1:\n\t\t\t\tcontinue #Not a weak pixel\n\t\t\t\n\t\t\t#Get 3x3 patch\t\n\t\t\tlocalPatch = thresholdedEdges[r-1:r+2,c-1:c+2]\n\t\t\tpatchMax = localPatch.max()\n\t\t\tif patchMax == 2:\n\t\t\t\tcurrentPixels.append((r, c))\n\t\t\t\tfinalEdges[r, c] = 1\n\n\t#Extend strong edges based on current pixels\n\twhile len(currentPixels) > 0:\n\t\tnewPix = []\n\t\tfor r, c in currentPixels:\n\t\t\tfor dr in range(-1, 2):\n\t\t\t\tfor dc in range(-1, 2):\n\t\t\t\t\tif dr == 0 and dc == 0: continue\n\t\t\t\t\tr2 = r+dr\n\t\t\t\t\tc2 = c+dc\n\t\t\t\t\tif thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0:\n\t\t\t\t\t\t#Copy this weak pixel to final result\n\t\t\t\t\t\tnewPix.append((r2, c2))\n\t\t\t\t\t\tfinalEdges[r2, c2] = 1\n\t\tcurrentPixels = newPix\n\n\treturn finalEdges\n\nif __name__==\"__main__\":\n\tim = imread(\"test.jpg\", mode=\"L\") #Open image, convert to greyscale\n\tfinalEdges = CannyEdgeDetector(im)\n\timshow(finalEdges)\n", "language": "Python" }, { "code": "#include <stdio.h>\n#include <string.h>\n#include <magick/MagickCore.h>\n\nint CannyEdgeDetector(\n const char *infile, const char *outfile,\n double radius, double sigma, double lower, double upper ) {\n\n ExceptionInfo *exception;\n Image *image, *processed_image, *output;\n ImageInfo *input_info;\n\n exception = AcquireExceptionInfo();\n input_info = CloneImageInfo((ImageInfo *) NULL);\n (void) strcpy(input_info->filename, infile);\n image = ReadImage(input_info, exception);\n output = NewImageList();\n processed_image = CannyEdgeImage(image,radius,sigma,lower,upper,exception);\n (void) AppendImageToList(&output, processed_image);\n (void) strcpy(output->filename, outfile);\n WriteImage(input_info, output);\n // after-party clean up\n DestroyImage(image);\n output=DestroyImageList(output);\n input_info=DestroyImageInfo(input_info);\n exception=DestroyExceptionInfo(exception);\n MagickCoreTerminus();\n\n return 0;\n}\n", "language": "Raku" }, { "code": "# 20220103 Raku programming solution\n\nuse NativeCall;\n\nsub CannyEdgeDetector(CArray[uint8], CArray[uint8], num64, num64, num64, num64\n) returns int32 is native( '/home/hkdtam/LibCannyEdgeDetector.so' ) {*};\n\nCannyEdgeDetector( # imagemagick.org/script/command-line-options.php#canny\n CArray[uint8].new( 'input.jpg'.encode.list, 0), # pbs.org/wgbh/nova/next/wp-content/uploads/2013/09/fingerprint-1024x575.jpg\n CArray[uint8].new( 'output.jpg'.encode.list, 0),\n 0e0, 2e0, 0.05e0, 0.05e0\n)\n", "language": "Raku" }, { "code": "package require crimp\npackage require crimp::pgm\n\nproc readPGM {filename} {\n set f [open $filename rb]\n set data [read $f]\n close $f\n return [crimp read pgm $data]\n}\nproc writePGM {filename image} {\n crimp write 2file pgm-raw $filename $image\n}\n\nproc cannyFilterFile {{inputFile \"lena.pgm\"} {outputFile \"lena_canny.pgm\"}} {\n writePGM $outputFile [crimp filter canny sobel [readPGM $inputFile]]\n}\ncannyFilterFile {*}$argv\n", "language": "Tcl" }, { "code": "import \"dome\" for Window\nimport \"graphics\" for Canvas, Color, ImageData\nimport \"math\" for Math\nimport \"./check\" for Check\n\nvar MaxBrightness = 255\n\nclass Canny {\n construct new(inFile, outFile) {\n Window.title = \"Canny edge detection\"\n var image1 = ImageData.load(inFile)\n var w = image1.width\n var h = image1.height\n Window.resize(w * 2 + 20, h)\n Canvas.resize(w * 2 + 20, h)\n var image2 = ImageData.create(outFile, w, h)\n var pixels = List.filled(w * h, 0)\n var ix = 0\n // convert image1 to gray scale as a list of pixels\n for (y in 0...h) {\n for (x in 0...w) {\n var c1 = image1.pget(x, y)\n var lumin = (0.2126 * c1.r + 0.7152 * c1.g + 0.0722 * c1.b).floor\n pixels[ix] = lumin\n ix = ix + 1\n }\n }\n\n // find edges\n var data = cannyEdgeDetection(pixels, w, h, 45, 50, 1)\n\n // write to image2\n ix = 0\n for (y in 0...h) {\n for (x in 0...w) {\n var d = data[ix]\n var c = Color.rgb(d, d, d)\n image2.pset(x, y, c)\n ix = ix + 1\n }\n }\n\n // display the two images side by side\n image1.draw(0, 0)\n image2.draw(w + 20, 0)\n\n // save image2 to outFile\n image2.saveToFile(outFile)\n }\n\n init() {}\n\n // If normalize is true, map pixels to range 0..MaxBrightness\n convolution(input, output, kernel, nx, ny, kn, normalize) {\n Check.ok((kn % 2) == 1)\n Check.ok(nx > kn && ny > kn)\n var khalf = (kn / 2).floor\n var min = Num.largest\n var max = -min\n if (normalize) {\n for (m in khalf...nx-khalf) {\n for (n in khalf...ny-khalf) {\n var pixel = 0\n var c = 0\n for (j in -khalf..khalf) {\n for (i in -khalf..khalf) {\n pixel = pixel + input[(n-j)*nx + m - i] * kernel[c]\n c = c + 1\n }\n }\n if (pixel < min) min = pixel\n if (pixel > max) max = pixel\n }\n }\n }\n\n for (m in khalf...nx-khalf) {\n for (n in khalf...ny-khalf) {\n var pixel = 0\n var c = 0\n for (j in -khalf..khalf) {\n for (i in -khalf..khalf) {\n pixel = pixel + input[(n-j)*nx + m - i] * kernel[c]\n c = c + 1\n }\n }\n if (normalize) pixel = MaxBrightness * (pixel - min) / (max - min)\n output[n * nx + m] = pixel.truncate\n }\n }\n }\n\n gaussianFilter(input, output, nx, ny, sigma) {\n var n = 2 * (2 * sigma).truncate + 3\n var mean = (n / 2).floor\n var kernel = List.filled(n * n, 0)\n System.print(\"Gaussian filter: kernel size = %(n), sigma = %(sigma)\")\n var c = 0\n for (i in 0...n) {\n for (j in 0...n) {\n var t = (-0.5 * (((i - mean) / sigma).pow(2) + ((j - mean) / sigma).pow(2))).exp\n kernel[c] = t / (2 * Num.pi * sigma * sigma)\n c = c + 1\n }\n }\n convolution(input, output, kernel, nx, ny, n, true)\n }\n\n // Returns the square root of 'x' squared + 'y' squared.\n hypot(x, y) { (x*x + y*y).sqrt }\n\n cannyEdgeDetection(input, nx, ny, tmin, tmax, sigma) {\n var output = List.filled(input.count, 0)\n gaussianFilter(input, output, nx, ny, sigma)\n var Gx = [-1, 0, 1, -2, 0, 2, -1, 0, 1]\n var afterGx = List.filled(input.count, 0)\n convolution(output, afterGx, Gx, nx, ny, 3, false)\n var Gy = [1, 2, 1, 0, 0, 0, -1, -2, -1]\n var afterGy = List.filled(input.count, 0)\n convolution(output, afterGy, Gy, nx, ny, 3, false)\n var G = List.filled(input.count, 0)\n for (i in 1..nx-2) {\n for (j in 1..ny-2) {\n var c = i + nx * j\n G[c] = hypot(afterGx[c], afterGy[c]).floor\n }\n }\n\n // non-maximum suppression: straightforward implementation\n var nms = List.filled(input.count, 0)\n for (i in 1..nx-2) {\n for (j in 1..ny-2) {\n var c = i + nx * j\n var nn = c - nx\n var ss = c + nx\n var ww = c + 1\n var ee = c - 1\n var nw = nn + 1\n var ne = nn - 1\n var sw = ss + 1\n var se = ss - 1\n var temp = Math.atan(afterGy[c], afterGx[c]) + Num.pi\n var dir = (temp % Num.pi) / Num.pi * 8\n if (((dir <= 1 || dir > 7) && G[c] > G[ee] && G[c] > G[ww]) || // O°\n ((dir > 1 && dir <= 3) && G[c] > G[nw] && G[c] > G[se]) || // 45°\n ((dir > 3 && dir <= 5) && G[c] > G[nn] && G[c] > G[ss]) || // 90°\n ((dir > 5 && dir <= 7) && G[c] > G[ne] && G[c] > G[sw])) { // 135°\n nms[c] = G[c]\n } else {\n nms[c] = 0\n }\n }\n }\n\n // tracing edges with hysteresis: non-recursive implementation\n var edges = List.filled((input.count/2).floor, 0)\n for (i in 0...output.count) output[i] = 0\n var c = 1\n for (j in 1..ny-2) {\n for (i in 1..nx-2) {\n if (nms[c] >= tmax && output[c] == 0) {\n // trace edges\n output[c] = MaxBrightness\n var nedges = 1\n edges[0] = c\n while (true) {\n nedges = nedges - 1\n var t = edges[nedges]\n var nbs = [ // neighbors\n t - nx, // nn\n t + nx, // ss\n t + 1, // ww\n t - 1, // ee\n t - nx + 1, // nw\n t - nx - 1, // ne\n t + nx + 1, // sw\n t + nx - 1 // se\n ]\n for (n in nbs) {\n if (nms[n] >= tmin && output[n] == 0) {\n output[n] = MaxBrightness\n edges[nedges] = n\n nedges = nedges + 1\n }\n }\n if (nedges == 0) break\n }\n }\n c = c + 1\n }\n }\n return output\n }\n\n update() {}\n\n draw(alpha) {}\n}\nvar Game = Canny.new(\"Valve_original.png\", \"Valve_monchrome_canny.png\")\n", "language": "Wren" }, { "code": "// Rosetta Code problem: http://rosettacode.org/wiki/Canny_edge_detector\n// Adapted from Phix to Yabasic by Galileo, 01/2022\n\nimport ReadFromPPM2\n\nMaxBrightness = 255\n\nreadPPM(\"Valve.ppm\")\nprint \"Be patient, please ...\"\n\nwidth = peek(\"winwidth\")\nheight = peek(\"winheight\")\ndim pixels(width, height), C_E_D(3, 3)\n\ndata -1, -1, -1, -1, 8, -1, -1, -1, -1\nfor i = 0 to 2\n for j = 0 to 2\n read C_E_D(i, j)\n next\nnext\n\n// convert image to gray scale\nfor y = 1 to height\n for x = 1 to width\n c$ = right$(getbit$(x, y, x, y), 6)\n r = dec(left$(c$, 2))\n g = dec(mid$(c$, 3, 2))\n b = dec(right$(c$, 2))\n lumin = floor(0.2126 * r + 0.7152 * g + 0.0722 * b)\n pixels(x, y) = lumin\n next\nnext\n\ndim new_image(width, height)\n\ndivisor = 1\n\n// apply an edge detection filter\n\nfor y = 2 to height-2\n for x = 2 to width-2\n newrgb = 0\n for i = -1 to 1\n for j = -1 to 1\n newrgb = newrgb + C_E_D(i+1, j+1) * pixels(x+i, y+j)\n next\n new_image(x, y) = max(min(newrgb / divisor,255),0)\n next\n next\nnext\n\n// show result\n\nfor x = 1 to width\n for y = 1 to height\n c = new_image(x, y)\n color c, c, c\n dot x, y\n next\nnext\n", "language": "Yabasic" } ]
Canny-edge-detector
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Canonicalize_CIDR\n", "language": "00-META" }, { "code": ";Task:\nImplement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. \n\nThat is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.\n\n\n;Example:\nGiven &nbsp; '''87.70.141.1/22''', &nbsp; your code should output &nbsp; '''87.70.140.0/22'''\n\n\n;Explanation:\nAn Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.\n\nIn general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.\n\nThe example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 → 87.70.140.0.\n\n\n;More examples for testing\n<pre>\n 36.18.154.103/12 → 36.16.0.0/12\n 62.62.197.11/29 → 62.62.197.8/29\n 67.137.119.181/4 → 64.0.0.0/4\n 161.214.74.21/24 → 161.214.74.0/24\n 184.232.176.184/18 → 184.232.128.0/18\n</pre>\n<br><br>\n", "language": "00-TASK" }, { "code": "F cidr_parse(str)\n V (addr_str, m_str) = str.split(‘/’)\n V (a, b, c, d) = addr_str.split(‘.’).map(Int)\n V m = Int(m_str)\n I m < 1 | m > 32\n | a < 0 | a > 255\n | b < 0 | b > 255\n | c < 0 | c > 255\n | d < 0 | d > 255\n R (0, 0)\n V mask = ~((1 << (32 - m)) - 1)\n V address = (a << 24) + (b << 16) + (c << 8) + d\n address [&]= mask\n R (address, m)\n\nF cidr_format(=address, mask_length)\n V d = address [&] F'F\n address >>= 8\n V c = address [&] F'F\n address >>= 8\n V b = address [&] F'F\n address >>= 8\n V a = address [&] F'F\n R a‘.’b‘.’c‘.’d‘/’mask_length\n\nL(test) [‘87.70.141.1/22’,\n ‘36.18.154.103/12’,\n ‘62.62.197.11/29’,\n ‘67.137.119.181/4’,\n ‘161.214.74.21/24’,\n ‘184.232.176.184/18’]\n V (address, mask_length) = cidr_parse(test)\n print(‘#<18 -> #.’.format(test, cidr_format(address, mask_length)))\n", "language": "11l" }, { "code": "BEGIN # show IPv4 addresses in CIDR notation in canonical form #\n # mode to hold an IPv4 address in CIDR notation #\n MODE CIDR = STRUCT( BITS address\n , INT network bits\n , BOOL valid\n , STRING error\n );\n # returns a CIDR parsed from address #\n OP TOCIDR = ( STRING address text )CIDR:\n BEGIN\n STRING addr = \".\" + address text + \"$\";\n STRING error := \"\";\n BITS address := 16r0;\n INT bits count := 0;\n INT dot count := 0;\n INT slash count := 0;\n BOOL valid := TRUE;\n INT s pos := LWB addr;\n INT s max = UPB addr;\n WHILE s pos < s max AND valid DO\n IF addr[ s pos ] = \".\" THEN\n # must have an octet next #\n dot count +:= 1;\n INT octet := 0;\n INT digits := 0;\n WHILE CHAR c = addr[ s pos +:= 1 ];\n c >= \"0\" AND c <= \"9\"\n DO\n octet *:= 10 +:= ( ABS c - ABS \"0\" );\n digits +:= 1\n OD;\n address := ( address SHL 8 ) OR BIN ( octet MOD 256 );\n valid := valid AND digits > 0 AND digits < 4 AND octet < 256;\n IF NOT valid THEN error := \"too many digits/octet to large\" FI\n ELIF addr[ s pos ] = \"/\" THEN\n # must have the network mask length next #\n slash count +:= 1;\n WHILE CHAR c = addr[ s pos +:= 1 ];\n c >= \"0\" AND c <= \"9\"\n DO\n bits count *:= 10 +:= ( ABS c - ABS \"0\" )\n OD;\n # should be \"$\" ( end of string marker ) next #\n valid := valid AND addr[ s pos ] = \"$\";\n IF NOT valid THEN error := \"bit length not followed by end-of-string\" FI\n ELIF addr[ s pos ] = \"$\" THEN\n # end of address marker - must be the final character #\n valid := valid AND s pos = s max;\n IF NOT valid THEN error := \"Invalid character: \"\"$\"\"\" FI\n ELSE\n # invalid character #\n valid := FALSE;\n error := \"Invalid character: \"\"\" + addr[ s pos ] + \"\"\"\"\n FI\n OD;\n IF valid THEN\n # address is OK so far - check it had four octets and one mask length #\n valid := dot count = 4 # note a leading \".\" was added for parsing #\n AND slash count = 1\n AND bits count > 0\n AND bits count < 33;\n IF NOT valid THEN error := \"too many dots, slashes or bits\" FI\n FI;\n CIDR( address, bits count, valid, error )\n END # TOCIDR # ;\n # returns address in canonical form #\n OP CANONICALISE = ( CIDR address )CIDR:\n IF NOT valid OF address THEN\n # invalid address #\n address\n ELSE\n # valid address - retain the top most bits #\n CIDR( address OF address AND ( 16rffffffff\n SHL ( 32 - network bits OF address )\n )\n , network bits OF address\n , TRUE\n , \"\"\n )\n FI # CANONICALISE # ;\n # returns a readable form of address #\n OP TOSTRING = ( CIDR address )STRING:\n BEGIN\n [ 1 : 4 ]INT octet;\n BITS addr := address OF address;\n FOR o pos FROM UPB octet BY -1 TO LWB octet DO\n octet[ o pos ] := ABS ( addr AND 16rff );\n addr := addr SHR 8\n OD;\n STRING result := whole( octet[ LWB octet ], 0 );\n FOR o pos FROM 1 + LWB octet TO UPB octet DO\n result +:= \".\" + whole( octet[ o pos ], 0 )\n OD;\n result + \"/\" + whole( network bits OF address, 0 )\n END # TOSTRING # ;\n # task examples : input expected result #\n [,]STRING test cases = ( ( \"87.70.141.1/22\", \"87.70.140.0/22\" )\n , ( \"36.18.154.103/12\", \"36.16.0.0/12\" )\n , ( \"62.62.197.11/29\", \"62.62.197.8/29\" )\n , ( \"67.137.119.181/4\", \"64.0.0.0/4\" )\n , ( \"161.214.74.21/24\", \"161.214.74.0/24\" )\n , ( \"184.232.176.184/18\", \"184.232.128.0/18\" )\n );\n FOR t pos FROM 1 LWB test cases TO 1 UPB test cases DO\n STRING addr = test cases[ t pos, 1 ];\n CIDR canon = CANONICALISE TOCIDR addr;\n IF NOT valid OF canon THEN\n print( ( \"Invalid address: \"\"\", addr, \"\"\": \", error OF canon, newline ) )\n ELSE\n STRING actual = TOSTRING canon;\n STRING expected = test cases[ t pos, 2 ];\n print( ( addr\n , \" -> \"\n , actual\n , IF expected = actual THEN \"\" ELSE \" ** EXPECTED: \"\"\" + expected + \"\"\"\" FI\n , newline\n )\n )\n FI\n OD\nEND\n", "language": "ALGOL-68" }, { "code": " canonicalize←{\n nums←(2⊃⎕VFI)¨(~⍵∊'./')⊆⍵\n ip len←(4↑nums)(5⊃nums)\n ip←(32/2)⊤256⊥⊃¨ip\n ip←ip∧32↑len⍴1\n ip←(4/256)⊤2⊥ip\n (1↓∊'.',¨⍕¨ip),'/',⍕len\n }\n", "language": "APL" }, { "code": " canonicalize '87.70.141.1/22'\n87.70.140.0/22\n", "language": "APL" }, { "code": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef struct cidr_tag {\n uint32_t address;\n unsigned int mask_length;\n} cidr_t;\n\n// Convert a string in CIDR format to an IPv4 address and netmask,\n// if possible. Also performs CIDR canonicalization.\nbool cidr_parse(const char* str, cidr_t* cidr) {\n int a, b, c, d, m;\n if (sscanf(str, \"%d.%d.%d.%d/%d\", &a, &b, &c, &d, &m) != 5)\n return false;\n if (m < 1 || m > 32\n || a < 0 || a > UINT8_MAX\n || b < 0 || b > UINT8_MAX\n || c < 0 || c > UINT8_MAX\n || d < 0 || d > UINT8_MAX)\n return false;\n uint32_t mask = ~((1 << (32 - m)) - 1);\n uint32_t address = (a << 24) + (b << 16) + (c << 8) + d;\n address &= mask;\n cidr->address = address;\n cidr->mask_length = m;\n return true;\n}\n\n// Write a string in CIDR notation into the supplied buffer.\nvoid cidr_format(const cidr_t* cidr, char* str, size_t size) {\n uint32_t address = cidr->address;\n unsigned int d = address & UINT8_MAX;\n address >>= 8;\n unsigned int c = address & UINT8_MAX;\n address >>= 8;\n unsigned int b = address & UINT8_MAX;\n address >>= 8;\n unsigned int a = address & UINT8_MAX;\n snprintf(str, size, \"%u.%u.%u.%u/%u\", a, b, c, d,\n cidr->mask_length);\n}\n\nint main(int argc, char** argv) {\n const char* tests[] = {\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\"\n };\n for (int i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i) {\n cidr_t cidr;\n if (cidr_parse(tests[i], &cidr)) {\n char out[32];\n cidr_format(&cidr, out, sizeof(out));\n printf(\"%-18s -> %s\\n\", tests[i], out);\n } else {\n fprintf(stderr, \"%s: invalid CIDR\\n\", tests[i]);\n }\n }\n return 0;\n}\n", "language": "C" }, { "code": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n\n// Class representing an IPv4 address + netmask length\nclass ipv4_cidr {\npublic:\n ipv4_cidr() {}\n ipv4_cidr(std::uint32_t address, unsigned int mask_length)\n : address_(address), mask_length_(mask_length) {}\n std::uint32_t address() const {\n return address_;\n }\n unsigned int mask_length() const {\n return mask_length_;\n }\n friend std::istream& operator>>(std::istream&, ipv4_cidr&);\nprivate:\n std::uint32_t address_ = 0;\n unsigned int mask_length_ = 0;\n};\n\n// Stream extraction operator, also performs canonicalization\nstd::istream& operator>>(std::istream& in, ipv4_cidr& cidr) {\n int a, b, c, d, m;\n char ch;\n if (!(in >> a >> ch) || a < 0 || a > UINT8_MAX || ch != '.'\n || !(in >> b >> ch) || b < 0 || b > UINT8_MAX || ch != '.'\n || !(in >> c >> ch) || c < 0 || c > UINT8_MAX || ch != '.'\n || !(in >> d >> ch) || d < 0 || d > UINT8_MAX || ch != '/'\n || !(in >> m) || m < 1 || m > 32) {\n in.setstate(std::ios_base::failbit);\n return in;\n }\n uint32_t mask = ~((1 << (32 - m)) - 1);\n uint32_t address = (a << 24) + (b << 16) + (c << 8) + d;\n address &= mask;\n cidr.address_ = address;\n cidr.mask_length_ = m;\n return in;\n}\n\n// Stream insertion operator\nstd::ostream& operator<<(std::ostream& out, const ipv4_cidr& cidr) {\n uint32_t address = cidr.address();\n unsigned int d = address & UINT8_MAX;\n address >>= 8;\n unsigned int c = address & UINT8_MAX;\n address >>= 8;\n unsigned int b = address & UINT8_MAX;\n address >>= 8;\n unsigned int a = address & UINT8_MAX;\n out << a << '.' << b << '.' << c << '.' << d << '/'\n << cidr.mask_length();\n return out;\n}\n\nint main(int argc, char** argv) {\n const char* tests[] = {\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\"\n };\n for (auto test : tests) {\n std::istringstream in(test);\n ipv4_cidr cidr;\n if (in >> cidr)\n std::cout << std::setw(18) << std::left << test << \" -> \"\n << cidr << '\\n';\n else\n std::cerr << test << \": invalid CIDR\\n\";\n }\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Net;\nusing System.Linq;\n\npublic class Program\n{\n public static void Main()\n {\n string[] tests = {\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\"\n };\n\n foreach (string t in tests) Console.WriteLine($\"{t} => {Canonicalize(t)}\");\n }\n\n static string Canonicalize(string cidr) => CIDR.Parse(cidr).Canonicalize().ToString();\n}\n\nreadonly struct CIDR\n{\n public readonly IPAddress ip;\n public readonly int length;\n\n public static CIDR Parse(string cidr)\n {\n string[] parts = cidr.Split('/');\n return new CIDR(IPAddress.Parse(parts[0]), int.Parse(parts[1]));\n }\n\n public CIDR(IPAddress ip, int length) => (this.ip, this.length) = (ip, length);\n\n public CIDR Canonicalize() =>\n new CIDR(\n new IPAddress(\n ToBytes(\n ToInt(\n ip.GetAddressBytes()\n )\n & ~((1 << (32 - length)) - 1)\n )\n ),\n length\n );\n\n private int ToInt(byte[] bytes) => bytes.Aggregate(0, (n, b) => (n << 8) | b);\n\n private byte[] ToBytes(int n)\n {\n byte[] bytes = new byte[4];\n for (int i = 3; i >= 0; i--) {\n bytes[i] = (byte)(n & 0xFF);\n n >>= 8;\n }\n return bytes;\n }\n\n public override string ToString() => $\"{ip}/{length}\";\n}\n", "language": "C-sharp" }, { "code": "100 REM THE BINARY OPS ONLY WORK ON SIGNED 16-BIT NUMBERS\n110 REM SO WE STORE THE IP ADDRESS AS AN ARRAY OF FOUR OCTETS\n120 DIM IP(3)\n130 REM READ DEMO DATA\n140 READ CI$\n150 IF CI$=\"\" THEN END\n160 REM FIND /\n170 SL=0\n180 FOR I=LEN(CI$) TO 1 STEP -1\n190 : IF MID$(CI$,I,1)=\"/\" THEN SL=I:I=1\n200 NEXT I\n210 IF SL=0 THEN PRINT \"INVALID CIDR STRING: '\"CI$\"'\":GOTO 140\n220 NW=VAL(MID$(CI$,SL+1))\n230 IF NW < 1 OR NW > 32 THEN PRINT \"INVALID NETWORK WIDTH:\"NW:GOTO 140\n240 REM PARSE OCTETS INTO IP ARRAY\n250 BY=0:N=0\n260 FOR I=1 TO SL-1\n270 : C$=MID$(CI$,I,1):IF C$<>\".\" THEN 300\n280 : IP(N)=BY:N=N+1:BY=0:IF IP(N-1)<256 THEN 310\n290 : PRINT \"INVALID OCTET VALUE:\"IP(N-1):GOTO 140\n300 : C=VAL(C$):IF C OR (C$=\"0\") THEN BY=BY*10+C\n310 NEXT I\n320 IP(N)=BY:N=N+1:IF IP(N-1)>255 THEN 290\n330 REM NUMBER OF COMPLETE OCTETS IN NETWORK PART\n340 NB=INT(NW/8)\n350 REM NUMBER OF NETWORK BITS IN PARTIAL OCTET\n360 XB=NW AND 7\n370 REM ZERO OUT HOST BITS IN PARTIAL OCTET\n380 IP(NB) = IP(NB) AND (255 - 2^(8-XB) + 1)\n390 REM AND SET ANY ALL-HOST OCTETS TO 0\n400 IF NB<3 THEN FOR I=NB+1 TO 3:IP(I)=0 :NEXT I\n410 REM PRINT OUT THE RESULT\n420 PRINT MID$(STR$(IP(0)),2);\n430 FOR I=1 TO 3: PRINT \".\"MID$(STR$(IP( I)),2);:NEXT I\n440 PRINT MID$(CI$,SL)\n450 REM AND GO BACK FOR NEXT INPUT\n460 GOTO 140\n500 DATA 87.70.141.1/22, 36.18.154.103/12, 62.62.197.11/29\n510 DATA 67.137.119.181/4, 161.214.74.21/24, 184.232.176.184/18\n520 REM SOME INVALID INPUTS\n530 DATA 127.0.0.1, 123.45.67.89/0, 98.76.54.32/100, 123.456.789.0/12\n540 DATA\n", "language": "Commodore-BASIC" }, { "code": "(defun ip->bit-vector (ip)\n (flet ((int->bits (int)\n (loop :for i :below 8\n :collect (if (logbitp i int) 1 0) :into bits\n :finally (return (nreverse bits)))))\n (loop :repeat 4\n :with start := 0\n :for pos := (position #\\. ip :start start)\n :collect (parse-integer ip :start start :end pos) :into res\n :while pos\n :do (setf start (1+ pos))\n :finally (return (apply #'concatenate 'bit-vector (mapcar #'int->bits res))))))\n\n(defun bit-vector->ip (vec &optional n)\n (loop :repeat 4\n :for end :from 8 :by 8\n :for start := (- end 8)\n :for sub := (subseq vec start end)\n :collect (parse-integer (map 'string #'digit-char sub) :radix 2) :into res\n :finally (return (format nil \"~{~D~^.~}~@[/~A~]\" res n))))\n\n(defun canonicalize-cidr (cidr)\n (let* ((n (position #\\/ cidr))\n (ip (subseq cidr 0 n))\n (sn (parse-integer cidr :start (1+ n)))\n (ip* (ip->bit-vector ip))\n (canonical-ip (fill ip* 0 :start sn)))\n (bit-vector->ip canonical-ip sn)))\n\n(loop :for cidr :in '(\"36.18.154.103/12\" \"62.62.197.11/29\"\n \"67.137.119.181/4\" \"161.214.74.21/24\"\n \"184.232.176.184/18\")\n :for ccidr := (canonicalize-cidr cidr)\n :do (format t \"~&~A~20,T→ ~A~%\" cidr ccidr))\n", "language": "Common-Lisp" }, { "code": "include \"cowgol.coh\";\n\ntypedef IP is uint32;\n\nrecord CIDR is\n ip: IP;\n len: uint8;\nend record;\n\nsub ParseIP(buffer: [uint8]): (result: IP, ptr: [uint8]) is\n var parts: uint8 := 4;\n var part: int32;\n result := 0;\n loop\n (part, buffer) := AToI(buffer);\n parts := parts - 1;\n result := result | ((part as IP & 0xFF) << (parts * 8));\n if parts == 0 then break;\n else buffer := @next buffer;\n end if;\n end loop;\n ptr := buffer;\nend sub;\n\nsub ParseCIDR(buffer: [uint8], cidr: [CIDR]) is\n var len: int32;\n (cidr.ip, buffer) := ParseIP(buffer);\n (len, buffer) := AToI(@next buffer);\n cidr.len := len as uint8;\nend sub;\n\nsub Canonicalize(cidr: [CIDR]) is\n var mask: IP := 0;\n var ones: uint8 := cidr.len;\n var len: uint8 := 32;\n while ones != 0 loop\n mask := (mask << 1) | 1;\n ones := ones - 1;\n len := len - 1;\n end loop;\n while len != 0 loop;\n mask := mask << 1;\n len := len - 1;\n end loop;\n cidr.ip := cidr.ip & mask;\nend sub;\n\nsub FormatIP(ip: IP, buffer: [uint8]): (ptr: [uint8]) is\n ptr := buffer;\n ptr := UIToA((ip >> 24) & 0xFF, 10, ptr);\n [ptr] := '.';\n ptr := UIToA((ip >> 16) & 0xFF, 10, @next ptr);\n [ptr] := '.';\n ptr := UIToA((ip >> 8) & 0xFF, 10, @next ptr);\n [ptr] := '.';\n ptr := UIToA(ip & 0xFF, 10, @next ptr);\n [ptr] := 0;\nend sub;\n\nsub FormatCIDR(cidr: [CIDR], buffer: [uint8]) is\n buffer := FormatIP(cidr.ip, buffer);\n [buffer] := '/';\n buffer := UIToA(cidr.len as uint32, 10, @next buffer);\nend sub;\n\nvar buffer: uint8[256];\nvar string := &buffer[0];\nvar cidr: CIDR;\n\nParseCIDR(\"87.70.141.1/22\", &cidr);\nFormatCIDR(&cidr, string);\n\nprint(\"Before canonicalization: \");\nprint(string);\nprint_nl();\n\nCanonicalize(&cidr);\nFormatCIDR(&cidr, string);\n\nprint(\" After canonicalization: \");\nprint(string);\nprint_nl();\n", "language": "Cowgol" }, { "code": "func$ can_cidr s$ .\n n[] = number strsplit s$ \"./\"\n if len n[] <> 5\n return \"\"\n .\n for i to 4\n if n[i] < 0 or n[i] > 255\n return \"\"\n .\n ad = ad * 256 + n[i]\n .\n if n[5] > 31 or n[5] < 1\n return \"\"\n .\n mask = bitnot (bitshift 1 (32 - n[5]) - 1)\n ad = bitand ad mask\n for i to 4\n if r$ <> \"\"\n r$ = \".\" & r$\n .\n r$ = ad mod 256 & r$\n ad = ad div 256\n .\n return r$ & \"/\" & n[5]\n.\nrepeat\n s$ = input\n until s$ = \"\"\n print s$ & \" -> \" & can_cidr s$\n.\n#\ninput_data\n87.70.141.1/22\n36.18.154.103/12\n62.62.197.11/29\n67.137.119.181/4\n161.214.74.21/24\n184.232.176.184/18\n", "language": "EasyLang" }, { "code": "USING: command-line formatting grouping io kernel math.parser\nnamespaces prettyprint sequences splitting ;\nIN: rosetta-code.canonicalize-cidr\n\n! canonicalize a CIDR block: make sure none of the host bits are set\ncommand-line get [ lines ] when-empty\n[\n ! ( CIDR-IP -- bits-in-network-part dotted-decimal )\n \"/\" split first2 string>number swap\n\n ! get IP as binary string\n \".\" split [ string>number \"%08b\" sprintf ] map \"\" join\n\n ! replace the host part with all zeros\n over cut length [ CHAR: 0 ] \"\" replicate-as append\n\n ! convert back to dotted-decimal\n 8 group [ bin> number>string ] map \".\" join swap\n\n ! and output\n \"%s/%d\\n\" printf\n] each\n", "language": "Factor" }, { "code": "#lang \"qb\"\n\nREM THE Binary OPS ONLY WORK On SIGNED 16-Bit NUMBERS\nREM SO WE STORE THE IP ADDRESS As AN ARRAY OF FOUR OCTETS\nCls\nDim IP(3)\nDo\n REM Read DEMO Data\n 140 Read CI$\n If CI$ = \"\" Then Exit Do 'Sleep: End\n REM FIND /\n SL = 0\n For I = Len(CI$) To 1 Step -1\n If Mid$(CI$,I,1) = \"/\" Then SL = I : I = 1\n Next I\n If SL = 0 Then Print \"INVALID CIDR STRING: '\"; CI$; \"'\": Goto 140\n NW = Val(Mid$(CI$,SL+1))\n If NW < 1 Or NW > 32 Then Print \"INVALID NETWORK WIDTH:\"; NW: Goto 140\n REM PARSE OCTETS INTO IP ARRAY\n BY = 0 : N = 0\n For I = 1 To SL-1\n C$ = Mid$(CI$,I,1)\n If Not (C$ <> \".\") Then\n IP(N) = BY : N = N + 1\n BY = 0\n If IP(N-1) < 256 Then 310\n Print \"INVALID OCTET VALUE:\"; IP(N-1): Goto 140\n Else C = Val(C$):If C Or (C$=\"0\") Then BY = BY*10+C\n End If\n 310 '\n Next I\n IP(N) = BY : N = N + 1\n If IP(N-1) > 255 Then Print \"INVALID OCTET VALUE:\"; IP(N-1): Goto 140\n REM NUMBER OF COMPLETE OCTETS IN NETWORK PART\n NB = Int(NW/8)\n REM NUMBER OF NETWORK BITS IN PARTIAL OCTET\n XB = NW And 7\n REM ZERO Out HOST BITS IN PARTIAL OCTET\n IP(NB) = IP(NB) And (255 - 2^(8-XB) + 1)\n REM And SET Any ALL-HOST OCTETS To 0\n If NB < 3 Then For I = NB +1 To 3 : IP(I) = 0 : Next I\n REM Print Out THE RESULT\n Print Mid$(Str$(IP(0)),2);\n For I = 1 To 3\n Print \".\"; Mid$(Str$(IP( I)),2);\n Next I\n Print Mid$(CI$,SL)\nLoop\nData \"87.70.141.1/22\", \"36.18.154.103/12\", \"62.62.197.11/29\"\nData \"67.137.119.181/4\", \"161.214.74.21/24\", \"184.232.176.184/18\"\nREM SOME INVALID INPUTS\nData \"127.0.0.1\", \"123.45.67.89/0\", \"98.76.54.32/100\", \"123.456.789.0/12\"\n\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"strconv\"\n \"strings\"\n)\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\n// canonicalize a CIDR block: make sure none of the host bits are set\nfunc canonicalize(cidr string) string {\n // dotted-decimal / bits in network part\n split := strings.Split(cidr, \"/\")\n dotted := split[0]\n size, err := strconv.Atoi(split[1])\n check(err)\n\n // get IP as binary string\n var bin []string\n for _, n := range strings.Split(dotted, \".\") {\n i, err := strconv.Atoi(n)\n check(err)\n bin = append(bin, fmt.Sprintf(\"%08b\", i))\n }\n binary := strings.Join(bin, \"\")\n\n // replace the host part with all zeros\n binary = binary[0:size] + strings.Repeat(\"0\", 32-size)\n\n // convert back to dotted-decimal\n var canon []string\n for i := 0; i < len(binary); i += 8 {\n num, err := strconv.ParseInt(binary[i:i+8], 2, 64)\n check(err)\n canon = append(canon, fmt.Sprintf(\"%d\", num))\n }\n\n // and return\n return strings.Join(canon, \".\") + \"/\" + split[1]\n}\n\nfunc main() {\n tests := []string{\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\",\n }\n\n for _, test := range tests {\n fmt.Printf(\"%-18s -> %s\\n\", test, canonicalize(test))\n }\n}\n", "language": "Go" }, { "code": "use fmt;\nuse net::ip;\nuse strings;\n\nexport fn main() void = {\n\tconst array = [\"87.70.141.1/22\",\n\t\t\"36.18.154.103/12\",\n\t\t\"62.62.197.11/29\",\n\t\t\"67.137.119.181/4\",\n\t\t\"161.214.74.21/24\",\n\t\t\"184.232.176.184/18\"];\n\n\tfor (let i = 0z; i < len(array); i += 1) {\n\t\tmatch (canonicalizecidr(array[i])) {\n\t\tcase let s: str =>\n\t\t\tfmt::printfln(\"{:-18} => {}\", array[i], s)!;\n\t\t\tfree(s);\n\t\tcase net::ip::invalid =>\n\t\t\tfmt::errorfln(\"Error: invalid item: {}\", array[i])!;\n\t\t};\n\t};\n};\n\nfn canonicalizecidr(a: str) (str | net::ip::invalid) = {\n\tconst sub = net::ip::parsecidr(a)?;\n\tmatch (sub.addr) {\n\tcase let addr4: net::ip::addr4 => void;\n\tcase net::ip::addr6 => return net::ip::invalid;\n\t};\n\n\tconst net = sub.addr as [4]u8;\n\tconst msk = sub.mask as [4]u8;\n\n\tconst net: u32 = net[0]: u32 << 24 | net[1]: u32 << 16 | net[2]: u32 << 8 | net[3]: u32;\n\tconst msk: u32 = msk[0]: u32 << 24 | msk[1]: u32 << 16 | msk[2]: u32 << 8 | msk[3]: u32;\n\n\tconst result: u32 = net & msk;\n\treturn fmt::asprintf(\"{}.{}.{}.{}/{}\",\n\t\tresult >> 24,\n\t\t0xff & result >> 16,\n\t\t0xff & result >> 8,\n\t\t0xff & result,\n\t\tstrings::cut(a, \"/\").1);\n};\n", "language": "Hare" }, { "code": "import Control.Monad (guard)\nimport Data.Bits ((.|.), (.&.), complement, shiftL, shiftR, zeroBits)\nimport Data.Maybe (listToMaybe)\nimport Data.Word (Word32, Word8)\nimport Text.ParserCombinators.ReadP (ReadP, char, readP_to_S)\nimport Text.Printf (printf)\nimport Text.Read.Lex (readDecP)\n\n-- A 32-bit IPv4 address, with a netmask applied, and the number of leading bits\n-- that are in the network portion of the address.\ndata CIDR = CIDR Word32 Word8\n\n-- Convert a string to a CIDR, or nothing if it's invalid.\ncidrRead :: String -> Maybe CIDR\ncidrRead = listToMaybe . map fst . readP_to_S cidrP\n\n-- Convert the CIDR to a string.\ncidrShow :: CIDR -> String\ncidrShow (CIDR addr n) = let (a, b, c, d) = octetsFrom addr\n in printf \"%u.%u.%u.%u/%u\" a b c d n\n\n-- Parser for the string representation of a CIDR. For a successful parse the\n-- string must have the form a.b.c.d/n, where each of a, b, c and d are decimal\n-- numbers in the range [0, 255] and n is a decimal number in the range [0, 32].\ncidrP :: ReadP CIDR\ncidrP = do a <- octetP <* char '.'\n b <- octetP <* char '.'\n c <- octetP <* char '.'\n d <- octetP <* char '/'\n n <- netBitsP\n return $ CIDR (addrFrom a b c d .&. netmask n) n\n where octetP = wordP 255\n netBitsP = wordP 32\n\n-- Parser for a decimal string, whose value is in the range [0, lim].\n--\n-- We want the limit argument to be an Integer, so that we can detect values\n-- that are too large, rather than having them silently wrap.\nwordP :: Integral a => Integer -> ReadP a\nwordP lim = do n <- readDecP\n guard $ n <= lim\n return $ fi n\n\n-- The octets of an IPv4 address.\noctetsFrom :: Word32 -> (Word8, Word8, Word8, Word8)\noctetsFrom addr = (oct addr 3, oct addr 2, oct addr 1, oct addr 0)\n where oct w n = fi $ w `shiftR` (8*n) .&. 0xff\n\n-- An IPv4 address from four octets. `ipAddr4 1 2 3 4' is the address 1.2.3.4.\naddrFrom :: Word8 -> Word8 -> Word8 -> Word8 -> Word32\naddrFrom a b c d = 0 <<+ a <<+ b <<+ c <<+ d\n where w <<+ o = w `shiftL` 8 .|. fi o\n\n-- The value `netmask n' is the netmask whose leftmost n bits are 1, and the\n-- remainder are 0.\nnetmask :: Word8 -> Word32\nnetmask n = complement $ complement zeroBits `shiftR` fi n\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\n\ntest :: String -> IO ()\ntest str = do\n let cidrStr = maybe \"invalid CIDR string\" cidrShow (cidrRead str)\n printf \"%-18s -> %s\\n\" str cidrStr\n\nmain :: IO ()\nmain = do\n test \"87.70.141.1/22\"\n test \"36.18.154.103/12\"\n test \"62.62.197.11/29\"\n test \"67.137.119.181/4\"\n test \"161.214.74.21/24\"\n test \"184.232.176.184/18\"\n\n test \"184.256.176.184/12\" -- octet value is too large\n test \"184.232.176.184/33\" -- netmask size is too large\n test \"184.232.184/18\" -- too few components\n", "language": "Haskell" }, { "code": "cidr=: {{\n 'a e'=. 0 \".each (y rplc'. ')-.&;:'/'\n ('/',\":e),~rplc&' .'\":_8#.\\32{.e{.,(8#2)#:a\n}}\n", "language": "J" }, { "code": " cidr '87.70.141.1/22'\n87.70.140.0/22\n cidr '36.18.154.103/12'\n36.16.0.0/12\n cidr '62.62.197.11/29'\n62.62.197.8/29\n cidr '67.137.119.181/4'\n64.0.0.0/4\n cidr '161.214.74.21/24'\n161.214.74.0/24\n cidr '184.232.176.184/18'\n184.232.128.0/18\n", "language": "J" }, { "code": "import java.text.MessageFormat;\nimport java.text.ParseException;\n\npublic class CanonicalizeCIDR {\n public static void main(String[] args) {\n for (String test : TESTS) {\n try {\n CIDR cidr = new CIDR(test);\n System.out.printf(\"%-18s -> %s\\n\", test, cidr.toString());\n } catch (Exception ex) {\n System.err.printf(\"Error parsing '%s': %s\\n\", test, ex.getLocalizedMessage());\n }\n }\n }\n\n private static class CIDR {\n private CIDR(int address, int maskLength) {\n this.address = address;\n this.maskLength = maskLength;\n }\n\n private CIDR(String str) throws Exception {\n Object[] args = new MessageFormat(FORMAT).parse(str);\n int address = 0;\n for (int i = 0; i < 4; ++i) {\n int a = ((Number)args[i]).intValue();\n if (a < 0 || a > 255)\n throw new Exception(\"Invalid IP address\");\n address <<= 8;\n address += a;\n }\n int maskLength = ((Number)args[4]).intValue();\n if (maskLength < 1 || maskLength > 32)\n throw new Exception(\"Invalid mask length\");\n int mask = ~((1 << (32 - maskLength)) - 1);\n this.address = address & mask;\n this.maskLength = maskLength;\n }\n\n public String toString() {\n int address = this.address;\n int d = address & 0xFF;\n address >>= 8;\n int c = address & 0xFF;\n address >>= 8;\n int b = address & 0xFF;\n address >>= 8;\n int a = address & 0xFF;\n Object[] args = { a, b, c, d, maskLength };\n return new MessageFormat(FORMAT).format(args);\n }\n\n private int address;\n private int maskLength;\n private static final String FORMAT = \"{0,number,integer}.{1,number,integer}.{2,number,integer}.{3,number,integer}/{4,number,integer}\";\n };\n\n private static final String[] TESTS = {\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\"\n };\n}\n", "language": "Java" }, { "code": "const canonicalize = s => {\n\n // Prepare a DataView over a 16 Byte Array buffer.\n // Initialised to all zeros.\n const dv = new DataView(new ArrayBuffer(16));\n\n // Get the ip-address and cidr components\n const [ip, cidr] = s.split('/');\n\n // Make sure the cidr component is a usable int, and\n // default to 32 if it does not exist.\n const cidrInt = parseInt(cidr || 32, 10);\n\n // Populate the buffer with uint8 ip address components.\n // Use zero as the default for shorthand pool definitions.\n ip.split('.').forEach(\n (e, i) => dv.setUint8(i, parseInt(e || 0, 10))\n );\n\n // Grab the whole buffer as a uint32\n const ipAsInt = dv.getUint32(0);\n\n // Zero out the lower bits as per the CIDR number.\n const normIpInt = (ipAsInt >> 32 - cidrInt) << 32 - cidrInt;\n\n // Plonk it back into the buffer\n dv.setUint32(0, normIpInt);\n\n // Read each of the uint8 slots in the buffer and join them with a dot.\n const canonIp = [...'0123'].map((e, i) => dv.getUint8(i)).join('.');\n\n // Attach the cidr number to the back of the normalised IP address.\n return [canonIp, cidrInt].join('/');\n }\n\n const test = s => console.log(s, '->', canonicalize(s));\n [\n '255.255.255.255/10',\n '87.70.141.1/22',\n '36.18.154.103/12',\n '62.62.197.11/29',\n '67.137.119.181/4',\n '161.214.74.21/24',\n '184.232.176.184/18',\n '10.207.219.251/32',\n '10.207.219.251',\n '110.200.21/4',\n '10..55/8',\n '10.../8'\n ].forEach(test)\n", "language": "JavaScript" }, { "code": "# For gojq and fq\ndef _nwise($n):\n def nw: if length <= $n then . else .[0:$n] , (.[$n:] | nw) end;\n nw;\n\ndef lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .;\ndef lpad($len): lpad($len;\" \");\n\n# Convert the input integer to a string in the specified base (2 to 36 inclusive)\ndef convert(base):\n def stream:\n recurse(if . >= base then ./base|floor else empty end) | . % base ;\n [stream] | reverse\n | if base < 10 then map(tostring) | join(\"\")\n elif base <= 36 then map(if . < 10 then 48 + . else . + 87 end) | implode\n else error(\"base too large\")\n end;\n\n# input string is converted from \"base\" to an integer, within limits\n# of the underlying arithmetic operations, and without error-checking:\ndef to_i(base):\n explode\n | reverse\n | map(if . > 96 then . - 87 else . - 48 end) # \"a\" ~ 97 => 10 ~ 87\n | reduce .[] as $c\n # state: [power, ans]\n ([1,0]; (.[0] * base) as $b | [$b, .[1] + (.[0] * $c)])\n | .[1];\n", "language": "Jq" }, { "code": "# Canonicalize a CIDR block: make sure none of the host bits are set\ndef canonicalize:\n # dotted-decimal / bits in network part\n (. / \"/\") as [$dotted, $bits]\n | ($bits | tonumber) as $size\n\n # get IP as binary string\n | {binary: (($dotted / \".\") | map( tonumber | convert(2) | lpad(8; \"0\") ) | join(\"\") )}\n\n # replace the host part with all zeros\n | .binary |= .[0:$size] + \"0\" * (32 - $size)\n\n # convert back to dotted-decimal\n | [.binary | explode | _nwise(8) | implode]\n | (map( to_i(2) | tostring ) | join(\".\")) as $canon\n\n | $canon + \"/\" + $bits;\n\ndef tests:\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\"\n;\n\ntests\n| \"\\(lpad(18)) -> \\(canonicalize)\"\n", "language": "Jq" }, { "code": "using Sockets\n\nfunction canonCIDR(cidr::String)\n cidr = replace(cidr, r\"\\.(\\.|\\/)\" => s\".0\\1\") # handle ..\n cidr = replace(cidr, r\"\\.(\\.|\\/)\" => s\".0\\1\") # handle ...\n ip = split(cidr, \"/\")\n dig = length(ip) > 1 ? 2^(32 - parse(UInt8, ip[2])) : 1\n ip4 = IPv4(UInt64(IPv4(ip[1])) & (0xffffffff - dig + 1))\n return length(ip) == 1 ? \"$ip4/32\" : \"$ip4/$(ip[2])\"\nend\n\nprintln(canonCIDR(\"87.70.141.1/22\"))\nprintln(canonCIDR(\"100.68.0.18/18\"))\nprintln(canonCIDR(\"10.4.30.77/30\"))\nprintln(canonCIDR(\"10.207.219.251/32\"))\nprintln(canonCIDR(\"10.207.219.251\"))\nprintln(canonCIDR(\"110.200.21/4\"))\nprintln(canonCIDR(\"10..55/8\"))\nprintln(canonCIDR(\"10.../8\"))\n", "language": "Julia" }, { "code": "inet = require 'inet'\n\ntest_cases = {\n '87.70.141.1/22', '36.18.154.103/12', '62.62.197.11/29', '67.137.119.181/4',\n '161.214.74.21/24', '184.232.176.184/18'\n}\n\nfor i, cidr in ipairs(test_cases) do\n print( inet(cidr):network() )\nend\n", "language": "Lua" }, { "code": "ClearAll[CanonicalizeCIDR]\nCanonicalizeCIDR[str_String] := Module[{i, ip, chop, keep, change},\n If[StringMatchQ[str, \"*.*.*.*/*\"],\n i = StringSplit[str, \".\" | \"/\"];\n i = Interpreter[\"Integer\"] /@ i;\n If[MatchQ[i, {_Integer, _Integer, _Integer, _Integer, _Integer}],\n If[AllTrue[i, Between[{0, 255}]],\n {ip, {chop}} = TakeDrop[i, 4];\n ip = Catenate[IntegerDigits[ip, 2, 8]];\n {keep, change} = TakeDrop[ip, chop];\n change = ConstantArray[0, Length[change]];\n ip = Partition[Join[keep, change], 8];\n ip = ToString[FromDigits[#, 2]] & /@ ip;\n StringRiffle[ip, \".\"] <> \"/\" <> ToString[chop]\n ,\n Failure[\"Invalid range of numbers\", <|\"Input\" -> str|>]\n ]\n ,\n Failure[\"Invalid format\", <|\"Input\" -> str|>]\n ]\n ]\n ]\nCanonicalizeCIDR[\"87.70.141.1/22\"]\nCanonicalizeCIDR[\"36.18.154.103/12\"]\nCanonicalizeCIDR[\"62.62.197.11/29\"]\nCanonicalizeCIDR[\"67.137.119.181/4\"]\nCanonicalizeCIDR[\"161.214.74.21/24\"]\nCanonicalizeCIDR[\"184.232.176.184/18\"]\n", "language": "Mathematica" }, { "code": "clear all;close all;clc;\ncidrCanonicalizer();\n\nfunction cidrCanonicalizer\n % Main function to test CIDR canonicalization\n\n % Define test cases\n testCases = {\n '36.18.154.103/12', '36.16.0.0/12';\n '62.62.197.11/29', '62.62.197.8/29';\n '67.137.119.181/4', '64.0.0.0/4';\n '161.214.74.21/24', '161.214.74.0/24';\n '184.232.176.184/18', '184.232.128.0/18'\n };\n\n % Run test cases\n for i = 1:size(testCases, 1)\n ip = testCases{i, 1};\n expected = testCases{i, 2};\n result = canonicalize(ip);\n fprintf('%s -> %s\\n', ip, result);\n assert(strcmp(result, expected));\n end\nend\n\nfunction result = dottedToInt(dotted)\n % Convert dotted IP to integer representation\n parts = str2double(strsplit(dotted, '.'));\n result = sum(parts .* (256 .^ (3:-1:0)));\nend\n\nfunction result = intToDotted(ip)\n % Convert integer IP to dotted representation\n result = strjoin(arrayfun(@(x) num2str(bitshift(bitand(ip, bitshift(255, x)), -x)), [24 16 8 0], 'UniformOutput', false), '.');\nend\n\nfunction result = networkMask(numberOfBits)\n % Create a network mask for the given number of bits\n result = bitshift((bitshift(1, numberOfBits) - 1), (32 - numberOfBits));\nend\n\nfunction result = canonicalize(ip)\n % Canonicalize the given CIDR IP\n [dotted, networkBits] = strtok(ip, '/');\n networkBits = str2double(strrep(networkBits, '/', ''));\n i = dottedToInt(dotted);\n mask = networkMask(networkBits);\n result = strcat(intToDotted(bitand(i, mask)), '/', num2str(networkBits));\nend\n", "language": "MATLAB" }, { "code": "import net\nimport strutils\n\n\nproc canonicalize*(address: var IpAddress; nbits: Positive) =\n ## Canonicalize an IP address.\n\n var zbits = 32 - nbits # Number of bits to reset.\n\n # We process byte by byte which avoids byte order issues.\n for idx in countdown(address.address_v4.high, address.address_v4.low):\n if zbits == 0:\n # No more bits to reset.\n break\n if zbits >= 8:\n # Reset the current byte and continue with the remaining bits.\n address.address_v4[idx] = 0\n dec zbits, 8\n else:\n # Use a mask to reset the bits.\n address.address_v4[idx] = address.address_v4[idx] and (0xff'u8 shl zbits)\n zbits = 0\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nwhen isMainModule:\n\n import strformat\n\n var ipAddress: IpAddress\n var nbits: int\n\n for address in [\"87.70.141.1/22\", \"36.18.154.103/12\", \"62.62.197.11/29\",\n \"67.137.119.181/4\", \"161.214.74.21/24\", \"184.232.176.184/18\"]:\n\n # Parse the address.\n let parts = address.split('/')\n try:\n ipAddress = parseIpAddress(parts[0])\n if ipAddress.family == IPV6:\n raise newException(ValueError, \"\")\n except ValueError:\n echo \"Invalid IP V4 address: \", parts[0]\n quit(QuitFailure)\n\n # Check the number of bits.\n try:\n nbits = parseInt(parts[1])\n if nbits notin 1..32:\n raise newException(ValueError, \"\")\n except ValueError:\n echo \"Invalid number of bits: \", parts[1]\n quit(QuitFailure)\n\n # Canonicalize the address and display the result.\n ipAddress.canonicalize(nbits)\n echo &\"{address:<18} ⇢ {ipAddress}/{nbits}\"\n", "language": "Nim" }, { "code": "let mask = function\n | _, 0 -> 0l, 0\n | a, l -> Int32.(logand (shift_left minus_one (-l land 31)) a), l\n\nlet str_to_cidr s =\n let (<<+) b a = Int32.(add (shift_left b 8) a) in\n let recv d c b a l = d <<+ c <<+ b <<+ a, l in\n Scanf.sscanf s \"%3lu.%3lu.%3lu.%3lu/%2u\" recv\n\nlet cidr_to_str (a, l) =\n let addr n =\n let dgt = function\n | h :: t -> Int32.shift_right_logical h 8 :: Int32.logand h 255l :: t\n | l -> l\n in\n dgt [n] |> dgt |> dgt |> List.map Int32.to_string |> String.concat \".\"\n in\n Printf.sprintf \"%s/%u\" (addr a) l\n\nlet () =\n [\"87.70.141.1/22\"; \"36.18.154.103/12\"; \"62.62.197.11/29\"; \"67.137.119.181/4\"; \"161.214.74.21/24\"; \"184.232.176.184/18\"; \"10.207.219.251/32\"]\n |> List.iter (fun s -> str_to_cidr s |> mask |> cidr_to_str |> print_endline)\n", "language": "OCaml" }, { "code": "#!/usr/bin/env perl\nuse v5.16;\nuse Socket qw(inet_aton inet_ntoa);\n\n# canonicalize a CIDR block: make sure none of the host bits are set\nif (!@ARGV) {\n chomp(@ARGV = <>);\n}\n\nfor (@ARGV) {\n\n # dotted-decimal / bits in network part\n my ($dotted, $size) = split m#/#;\n\n # get IP as binary string\n my $binary = sprintf \"%032b\", unpack('N', inet_aton $dotted);\n\n # Replace the host part with all zeroes\n substr($binary, $size) = 0 x (32 - $size);\n\n # Convert back to dotted-decimal\n $dotted = inet_ntoa(pack 'B32', $binary);\n\n # And output\n say \"$dotted/$size\";\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span> <span style=\"color: #000080;font-style:italic;\">-- (not likely useful)</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">canonicalize_cidr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">cidr</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cidr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">substitute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cidr</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\".\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (else %d eats 0.0 etc)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">'/'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cidr</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">cidr</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #008000;\">\"/32\"</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">scanf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cidr</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d %d %d %d/%d\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">255</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">255</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">255</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">255</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">32</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">mask</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">32</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">addr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">bytes_to_int</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">addr</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #7060A8;\">and_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">addr</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">mask</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">int_to_bytes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">addr</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d.%d.%d.%d/%d\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #008000;\">\"???\"</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"87.70.141.1/22\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"36.18.154.103/12\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"62.62.197.11/29\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"67.137.119.181/4\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"161.214.74.21/24\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"184.232.176.184/18\"</span><span style=\"color: #0000FF;\">}</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">ti</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%-18s -&gt; %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">canonicalize_cidr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "(de cidr (S)\n (let\n (L (rot (mapcar format (split (chop S) \".\" \"/\")))\n N (++ L)\n M\n (&\n (sum >> (-24 -16 -8 0) L)\n (rev 32 (dec (** 2 N))) ) )\n (pack\n (>> 24 M)\n \".\"\n (& 255 (>> 16 M))\n \".\"\n (& 255 (>> 8 M))\n \".\"\n (& 255 (& 255 M))\n \"/\"\n N ) ) )\n(let Fmt (18 3 17)\n (for A\n (quote\n \"87.70.141.1/22\"\n \"36.18.154.103/12\"\n \"62.62.197.11/29\"\n \"67.137.119.181/4\"\n \"161.214.74.21/24\"\n \"184.232.176.184/18\" )\n (tab Fmt A \"=>\" (cidr A)) ) )\n", "language": "PicoLisp" }, { "code": "#!/usr/bin/env python\n# canonicalize a CIDR block specification:\n# make sure none of the host bits are set\n\nimport sys\nfrom socket import inet_aton, inet_ntoa\nfrom struct import pack, unpack\n\nargs = sys.argv[1:]\nif len(args) == 0:\n args = sys.stdin.readlines()\n\nfor cidr in args:\n # IP in dotted-decimal / bits in network part\n dotted, size_str = cidr.split('/')\n size = int(size_str)\n\n numeric = unpack('!I', inet_aton(dotted))[0] # IP as an integer\n binary = f'{numeric:#034b}' # then as a padded binary string\n prefix = binary[:size + 2] # just the network part\n # (34 and +2 are to account\n # for leading '0b')\n\n canon_binary = prefix + '0' * (32 - size) # replace host part with all zeroes\n canon_numeric = int(canon_binary, 2) # convert back to integer\n canon_dotted = inet_ntoa(pack('!I',\n (canon_numeric))) # and then to dotted-decimal\n print(f'{canon_dotted}/{size}') # output result\n", "language": "Python" }, { "code": "\"\"\"Canonicalize CIDR\"\"\"\nDIGITS = (24, 16, 8, 0)\n\n\ndef dotted_to_int(dotted: str) -> int:\n digits = [int(digit) for digit in dotted.split(\".\")]\n return sum(a << b for a, b in zip(digits, DIGITS))\n\n\ndef int_to_dotted(ip: int) -> str:\n digits = [(ip & (255 << d)) >> d for d in DIGITS]\n return \".\".join(str(d) for d in digits)\n\n\ndef network_mask(number_of_bits: int) -> int:\n return ((1 << number_of_bits) - 1) << (32 - number_of_bits)\n\n\ndef canonicalize(ip: str) -> str:\n dotted, network_bits = ip.split(\"/\")\n i = dotted_to_int(dotted)\n mask = network_mask(int(network_bits))\n return int_to_dotted(i & mask) + \"/\" + network_bits\n\n\nTEST_CASES = [\n (\"36.18.154.103/12\", \"36.16.0.0/12\"),\n (\"62.62.197.11/29\", \"62.62.197.8/29\"),\n (\"67.137.119.181/4\", \"64.0.0.0/4\"),\n (\"161.214.74.21/24\", \"161.214.74.0/24\"),\n (\"184.232.176.184/18\", \"184.232.128.0/18\"),\n]\n\nif __name__ == \"__main__\":\n for ip, expect in TEST_CASES:\n rv = canonicalize(ip)\n print(f\"{ip:<18} -> {rv}\")\n assert rv == expect\n", "language": "Python" }, { "code": "import ipaddress\n\ndef canonicalize(address: str) -> str:\n return str(ipaddress.ip_network(address, strict=False))\n\nTEST_CASES = [\n (\"36.18.154.103/12\", \"36.16.0.0/12\"),\n (\"62.62.197.11/29\", \"62.62.197.8/29\"),\n (\"67.137.119.181/4\", \"64.0.0.0/4\"),\n (\"161.214.74.21/24\", \"161.214.74.0/24\"),\n (\"184.232.176.184/18\", \"184.232.128.0/18\"),\n]\n\nif __name__ == \"__main__\":\n for ip, expect in TEST_CASES:\n rv = canonicalize(ip)\n print(f\"{ip:<18} -> {rv}\")\n assert rv == expect, expect\n", "language": "Python" }, { "code": "CLS\nDIM IP(3)\nDO\n REM Read DEMO Data\n140 READ CI$\n IF CI$ = \"\" THEN EXIT DO 'Sleep: End\n REM FIND /\n SL = 0\n FOR I = LEN(CI$) TO 1 STEP -1\n IF MID$(CI$, I, 1) = \"/\" THEN SL = I: I = 1\n NEXT I\n IF SL = 0 THEN PRINT \"INVALID CIDR STRING: '\"; CI$; \"'\": GOTO 140\n NW = VAL(MID$(CI$, SL + 1))\n IF NW < 1 OR NW > 32 THEN PRINT \"INVALID NETWORK WIDTH:\"; NW: GOTO 140\n REM PARSE OCTETS INTO IP ARRAY\n BY = 0: N = 0\n FOR I = 1 TO SL - 1\n C$ = MID$(CI$, I, 1): IF C$ <> \".\" THEN 300\n IP(N) = BY: N = N + 1: BY = 0: IF IP(N - 1) < 256 THEN 310\n290 PRINT \"INVALID OCTET VALUE:\"; IP(N - 1): GOTO 140\n300 C = VAL(C$): IF C OR (C$ = \"0\") THEN BY = BY * 10 + C\n310 '\n NEXT I\n IP(N) = BY: N = N + 1: IF IP(N - 1) > 255 THEN 290\n REM NUMBER OF COMPLETE OCTETS IN NETWORK PART\n NB = INT(NW / 8)\n REM NUMBER OF NETWORK BITS IN PARTIAL OCTET\n XB = NW AND 7\n REM ZERO Out HOST BITS IN PARTIAL OCTET\n IP(NB) = IP(NB) AND (255 - 2 ^ (8 - XB) + 1)\n REM And SET Any ALL-HOST OCTETS To 0\n IF NB < 3 THEN FOR I = NB + 1 TO 3: IP(I) = 0: NEXT I\n REM Print Out THE RESULT\n PRINT MID$(STR$(IP(0)), 2);\n FOR I = 1 TO 3\n PRINT \".\"; MID$(STR$(IP(I)), 2);\n NEXT I\n PRINT MID$(CI$, SL)\nLOOP\nDATA 87.70.141.1/22, 36.18.154.103/12, 62.62.197.11/29\nDATA 67.137.119.181/4, 161.214.74.21/24, 184.232.176.184/18\nREM SOME INVALID INPUTS\nDATA 127.0.0.1, 123.45.67.89/0, 98.76.54.32/100, 123.456.789.0/12\nDATA\n", "language": "QBasic" }, { "code": "use IP::Addr;\nfor «87.70.141.1/22 36.18.154.103/12 62.62.197.11/29 67.137.119.181/4 161.214.74.21/24 184.232.176.184/18» -> $cidr {\n say \"$cidr -> $(IP::Addr.new($cidr).network)\";\n}\n", "language": "Raku" }, { "code": "#!/usr/bin/env raku\nunit sub MAIN(*@cidrs);\n\nif !@cidrs {\n # test data\n @cidrs = «87.70.141.1/22 36.18.154.103/12 62.62.197.11/29 67.137.119.181/4 161.214.74.21/24 184.232.176.184/18»;\n}\n\nfor @cidrs -> $cidr {\n say \"$cidr -> $(canonicalize $cidr)\";\n}\n\n# canonicalize a CIDR block: make sure none of the host bits are set\nsub canonicalize($cidr) {\n # dotted-decimal / bits in network part\n my ($dotted, $size) = $cidr.split: '/';\n\n # get network part of the IP as binary string\n my $binary = $dotted.split('.')».fmt('%08b').join.substr(0, $size);\n\n # Add host part with all zeroes\n $binary ~= 0 x (32 - $size);\n\n # Convert back to dotted-decimal\n my $canon = $binary.comb(8)».parse-base(2).join: '.';\n\n # And output\n say \"$canon/$size\";\n}\n", "language": "Raku" }, { "code": "# canonicalize a IP4 CIDR block\nsub CIDR-IP4-canonicalize ($address) {\n constant @mask = 24, 16, 8, 0;\n\n # dotted-decimal / subnet size\n my ($dotted, $size) = |$address.split('/'), 32;\n\n # get IP as binary address\n my $binary = sum $dotted.comb(/\\d+/) Z+< @mask;\n\n # mask off subnet\n $binary +&= (2 ** $size - 1) +< (32 - $size);\n\n # Return dotted-decimal notation\n (@mask.map($binary +> * +& 0xFF).join('.'), $size)\n}\n\nmy @tests = <\n 87.70.141.1/22\n 36.18.154.103/12\n 62.62.197.11/29\n 67.137.119.181/4\n 161.214.74.21/24\n 184.232.176.184/18\n 100.68.0.18/18\n 10.4.30.77/30\n 10.207.219.251/32\n 10.207.219.251\n 110.200.21/4\n 10.11.12.13/8\n 10.../8\n>;\n\nprintf \"CIDR: %18s Routing prefix: %s/%s\\n\", $_, |.&CIDR-IP4-canonicalize\n for @*ARGS || @tests;\n", "language": "Raku" }, { "code": "/*REXX pgm canonicalizes IPv4 addresses that are in CIDR notation (dotted─dec/network).*/\nparse arg a . /*obtain optional argument from the CL.*/\nif a=='' | a==\",\" then a= '87.70.141.1/22' , /*Not specified? Then use the defaults*/\n '36.18.154.103/12' ,\n '62.62.197.11/29' ,\n '67.137.119.181/4' ,\n '161.214.74.21/24' ,\n '184.232.176.184/18'\n\n do i=1 for words(a); z= word(a, i) /*process each IPv4 address in the list*/\n parse var z # '/' -0 mask /*get the address nodes & network mask.*/\n #= subword( translate(#, , .) 0 0 0, 1, 4) /*elide dots from addr, ensure 4 nodes.*/\n $= # /*use original node address (for now). */\n hb= 32 - substr(word(mask .32, 1), 2) /*obtain the size of the host bits. */\n $=; ##= /*crop the host bits only if mask ≤ 32.*/\n do k=1 for 4; _= word(#, k) /*create a 32-bit (binary) IPv4 address*/\n ##= ## || right(d2b(_), 8, 0) /*append eight bits of the \" \" */\n end /*k*/ /* [↑] ... and ensure a node is 8 bits.*/\n ##= left(##, 32-hb, 0) /*crop bits in host part of IPv4 addr. */\n ##= left(##, 32, 0) /*replace cropped bits with binary '0's*/\n do j=8 by 8 for 4 /* [↓] parse the four nodes of address*/\n $= $ || . || b2d(substr(##, j-7, 8)) /*reconstitute the decimal nodes. */\n end /*j*/ /* [↑] and insert a dot between nodes.*/\n say /*introduce a blank line between IPv4's*/\n $= substr($, 2) /*elid the leading decimal point in $ */\n say ' original IPv4 address: ' z /*display the original IPv4 address. */\n say ' canonicalized address: ' translate( space($), ., \" \")mask /*canonicalized.*/\n end /*i*/\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nb2d: return x2d( b2x( arg(1) ) ) + 0 /*convert binary ───► decimal number.*/\nd2b: return x2b( d2x( arg(1) ) ) + 0 /* \" decimal ───► binary \" */\n", "language": "REXX" }, { "code": "#!/usr/bin/env ruby\n\n# canonicalize a CIDR block: make sure none of the host bits are set\nif ARGV.length == 0 then\n ARGV = $stdin.readlines.map(&:chomp)\nend\n\nARGV.each do |cidr|\n\n # dotted-decimal / bits in network part\n dotted, size_str = cidr.split('/')\n size = size_str.to_i\n\n # get IP as binary string\n binary = dotted.split('.').map { |o| \"%08b\" % o }.join\n\n # Replace the host part with all zeroes\n binary[size .. -1] = '0' * (32 - size)\n\n # Convert back to dotted-decimal\n canon = binary.chars.each_slice(8).map { |a| a.join.to_i(2) }.join('.')\n\n # And output\n puts \"#{canon}/#{size}\"\nend\n", "language": "Ruby" }, { "code": "require \"ipaddr\"\n\ntests = [\"87.70.141.1/22\", \"36.18.154.103/12\", \"62.62.197.11/29\",\n \"67.137.119.181/4\", \"161.214.74.21/24\", \"184.232.176.184/18\"]\n\ntests.each do |str|\n ia = IPAddr.new(str)\n puts \"#{ia}/#{ia.prefix}\"\nend\n", "language": "Ruby" }, { "code": "use std::net::Ipv4Addr;\n\nfn canonical_cidr(cidr: &str) -> Result<String, &str> {\n let mut split = cidr.splitn(2, '/');\n if let (Some(addr), Some(mask)) = (split.next(), split.next()) {\n let addr = addr.parse::<Ipv4Addr>().map(u32::from).map_err(|_| cidr)?;\n let mask = mask.parse::<u8>().map_err(|_| cidr)?;\n let bitmask = 0xff_ff_ff_ffu32 << (32 - mask);\n let addr = Ipv4Addr::from(addr & bitmask);\n Ok(format!(\"{}/{}\", addr, mask))\n } else {\n Err(cidr)\n }\n}\n\n#[cfg(test)]\nmod tests {\n\n #[test]\n fn valid() {\n [\n (\"87.70.141.1/22\", \"87.70.140.0/22\"),\n (\"36.18.154.103/12\", \"36.16.0.0/12\"),\n (\"62.62.197.11/29\", \"62.62.197.8/29\"),\n (\"67.137.119.181/4\", \"64.0.0.0/4\"),\n (\"161.214.74.21/24\", \"161.214.74.0/24\"),\n (\"184.232.176.184/18\", \"184.232.128.0/18\"),\n ]\n .iter()\n .cloned()\n .for_each(|(input, expected)| {\n assert_eq!(expected, super::canonical_cidr(input).unwrap());\n });\n }\n}\n\nfn main() {\n println!(\"{}\", canonical_cidr(\"127.1.2.3/24\").unwrap());\n}\n", "language": "Rust" }, { "code": "import java.text.MessageFormat\n\nobject CanonicalizeCIDR extends App {\n case class CIDR(address: Int, maskLength: Int) {\n override def toString: String = {\n val a = (address >> 24) & 0xFF\n val b = (address >> 16) & 0xFF\n val c = (address >> 8) & 0xFF\n val d = address & 0xFF\n MessageFormat.format(CIDR.format, a.asInstanceOf[AnyRef], b.asInstanceOf[AnyRef], c.asInstanceOf[AnyRef], d.asInstanceOf[AnyRef], maskLength.asInstanceOf[AnyRef])\n }\n }\n\n object CIDR {\n private val format = \"{0,number,integer}.{1,number,integer}.{2,number,integer}.{3,number,integer}/{4,number,integer}\"\n\n def apply(str: String): CIDR = {\n val args = new MessageFormat(format).parse(str)\n val address = args.take(4).foldLeft(0) { (acc, arg) =>\n val a = arg.asInstanceOf[Number].intValue()\n require(a >= 0 && a <= 255, \"Invalid IP address\")\n (acc << 8) + a\n }\n val maskLength = args(4).asInstanceOf[Number].intValue()\n require(maskLength >= 1 && maskLength <= 32, \"Invalid mask length\")\n val mask = ~((1 << (32 - maskLength)) - 1)\n new CIDR(address & mask, maskLength)\n }\n }\n\n val tests = Array(\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\"\n )\n\n tests.foreach { test =>\n try {\n val cidr = CIDR(test)\n println(f\"$test%-18s -> $cidr\")\n } catch {\n case ex: Exception => println(s\"Error parsing '$test': ${ex.getLocalizedMessage}\")\n }\n }\n}\n", "language": "Scala" }, { "code": "* Pattern to match any number of digits\n D = SPAN('0123456789')\n\n* Convert a dotted-decimal IP address to an integer\n DEFINE('INET_ATON(Str),B3,B2,B1,B0') :(END_INET_ATON)\nINET_ATON Str D . B3 '.' D . B2 '.' D . B1 '.' D . B0 :F(FRETURN)\n INET_ATON = B3 * 16777216 + B2 * 65536 + B1 * 256 + B0 :(RETURN)\nEND_INET_ATON\n\n* Convert an integer to dotted-decimal\n DEFINE('INET_NTOA(Addr),Count,Byte') :(END_INET_NTOA)\nINET_NTOA Count = 0\nN2ALOOP Byte = REMDR(Addr,256)\n Addr = (Addr - Byte) / 256\n INET_NTOA = Byte '.' INET_NTOA\n Count = Count + 1\n LT(Count,4) :S(N2ALOOP)\n INET_NTOA '.' RPOS(0) = '' :(RETURN)\nEND_INET_NTOA\n\n* Convert a CIDR range to canonical form\n DEFINE('FIXCIDR(Cidr),IP,Net,In,Host,Count,Pow,Out,Bit') :(END_FIXCIDR)\nFIXCIDR Cidr Arb . IP '/' D . Net :F(FRETURN)\n In = INET_ATON(IP)\n Host = 32 - Net\n\n* Compute result of treating all bits in the host part as 0\n Out = 0\n Count = 0\n Pow = 1\nMASKLOOP Bit = REMDR(In, 2)\n In = (In - Bit) / 2\n Out = GE(Count, Host) Out + Bit * Pow\n Count = Count + 1\n Pow = Pow * 2\n LT(Count, 32) :S(MASKLOOP)\n\n* Convert back to dotted-decimal\n FIXCIDR = INET_NTOA(Out) '/' Net :(RETURN)\nEND_FIXCIDR\n\n OUTPUT = FIXCIDR('87.70.141.1/22')\n OUTPUT = FIXCIDR('36.18.154.103/12')\n OUTPUT = FIXCIDR('62.62.197.11/29')\n OUTPUT = FIXCIDR('67.137.119.181/4')\n OUTPUT = FIXCIDR('161.214.74.21/24')\n OUTPUT = FIXCIDR('184.232.176.184/18')\nEND\n", "language": "Snobol" }, { "code": "import Foundation\n\nfunc dottedToInt(_ dotted: String) -> UInt32 {\n let digits = dotted.split(separator: \".\").map { UInt32($0)! }\n return digits.enumerated().reduce(0) { $0 + ($1.element << (24 - $1.offset * 8)) }\n}\n\nfunc intToDotted(_ ip: UInt32) -> String {\n let digits = [24, 16, 8, 0].map { (ip & (255 << $0)) >> $0 }\n return digits.map { String($0) }.joined(separator: \".\")\n}\n\nfunc networkMask(_ numberOfBits: Int) -> UInt32 {\n // Explicitly use UInt32 for bitwise operations\n return UInt32((1 << numberOfBits) - 1) << (32 - numberOfBits)\n}\n\nfunc canonicalize(_ ip: String) -> String {\n let parts = ip.split(separator: \"/\")\n let dotted = String(parts[0])\n let networkBits = Int(parts[1])!\n\n let i = dottedToInt(dotted)\n let mask = networkMask(networkBits)\n return \"\\(intToDotted(i & mask))/\\(networkBits)\"\n}\n\nlet testCases = [\n (\"36.18.154.103/12\", \"36.16.0.0/12\"),\n (\"62.62.197.11/29\", \"62.62.197.8/29\"),\n (\"67.137.119.181/4\", \"64.0.0.0/4\"),\n (\"161.214.74.21/24\", \"161.214.74.0/24\"),\n (\"184.232.176.184/18\", \"184.232.128.0/18\"),\n]\n\nfor testCase in testCases {\n let (ip, expect) = testCase\n let result = canonicalize(ip)\n print(\"\\(ip) -> \\(result)\")\n assert(result == expect, \"Test failed for \\(ip)\")\n}\n", "language": "Swift" }, { "code": "# Canonicalize CIDR in Tcl\n\n# Convert dotted IP address to integer\nproc dotted_to_int {dotted} {\n set digits [split $dotted .]\n set result 0\n foreach digit $digits {\n set result [expr {$result * 256 + $digit}]\n }\n return $result\n}\n\n# Convert integer IP address to dotted format\nproc int_to_dotted {ip} {\n set result {}\n for {set i 3} {$i >= 0} {incr i -1} {\n lappend result [expr {($ip >> ($i * 8)) & 0xFF}]\n }\n return [join $result .]\n}\n\n# Calculate network mask\nproc network_mask {number_of_bits} {\n return [expr {(1 << $number_of_bits) - 1 << (32 - $number_of_bits)}]\n}\n\n# Canonicalize IP address\nproc canonicalize {ip} {\n regexp {^(.*)/(.*)$} $ip -> dotted network_bits\n set i [dotted_to_int $dotted]\n set mask [network_mask $network_bits]\n return [int_to_dotted [expr {$i & $mask}]]/$network_bits\n}\n\n# Test cases\nset test_cases {\n {\"36.18.154.103/12\" \"36.16.0.0/12\"}\n {\"62.62.197.11/29\" \"62.62.197.8/29\"}\n {\"67.137.119.181/4\" \"64.0.0.0/4\"}\n {\"161.214.74.21/24\" \"161.214.74.0/24\"}\n {\"184.232.176.184/18\" \"184.232.128.0/18\"}\n}\n\n# Main execution\nforeach test $test_cases {\n foreach {ip expect} $test {}\n set rv [canonicalize $ip]\n puts \"$ip -> $rv\"\n if {$rv ne $expect} {\n error \"Test failed: $rv != $expect\"\n }\n}\n", "language": "Tcl" }, { "code": "(defun cidr-canon (str)\n (let ((a (inaddr-str str)))\n `@(str-inaddr a.addr)/@{a.prefix}`))\n", "language": "TXR" }, { "code": "(defun cidr-canon (str)\n (let ((a (inaddr-str str)))\n (str-inaddr-net a.addr a.prefix)))\n", "language": "TXR" }, { "code": "(defun cidr-canon (str)\n (flow str\n inaddr-str\n (str-inaddr-net @1.addr @1.prefix)))\n", "language": "TXR" }, { "code": "function inet_aton {\n typeset -i addr byte\n typeset -a bytes\n if [[ -n $BASH_VERSION ]]; then\n IFS=. read -a bytes <<<\"$1\"\n elif [[ -n $ZSH_VERSION ]]; then\n IFS=. bytes=($=1)\n else\n IFS=. bytes=($1)\n fi\n addr=0\n for byte in \"${bytes[@]}\"; do\n (( addr = 256 * addr + byte ))\n done\n printf '%s\\n' \"$addr\"\n}\n\nfunction inet_ntoa {\n typeset -i addr=$1\n typeset dotted i\n for (( i=0; i<4; ++i )); do\n dotted=$(( addr & 255 ))${dotted:+.$dotted}\n (( addr >>= 8 ))\n done\n printf '%s\\n' \"$dotted\"\n}\n\nfunction canonicalize_cidr {\n typeset ip prefix fixed\n typeset -i netmask addr\n while (( $# )); do\n IFS=/ read ip prefix <<<\"$1\"\n netmask=$(( (-1 << (32-prefix)) & -1 ))\n addr=$(inet_aton \"$ip\")\n fixed=$(( addr & netmask ))\n printf '%s/%s\\n' \"$(inet_ntoa $fixed)\" \"$prefix\"\n shift\n done\n}\n\n# demo code\nif (( ! $# )); then\n set -- 36.18.154.103/12 62.62.197.11/29 67.137.119.181/4 161.214.74.21/24 184.232.176.184/18\nfi\ncanonicalize_cidr \"$@\"\n", "language": "UNIX-Shell" }, { "code": "import \"./fmt\" for Fmt, Conv\nimport \"./str\" for Str\n\n// canonicalize a CIDR block: make sure none of the host bits are set\nvar canonicalize = Fn.new { |cidr|\n // dotted-decimal / bits in network part\n var split = cidr.split(\"/\")\n var dotted = split[0]\n var size = Num.fromString(split[1])\n\n // get IP as binary string\n var binary = dotted.split(\".\").map { |n| Fmt.swrite(\"$08b\", Num.fromString(n)) }.join()\n\n // replace the host part with all zeros\n binary = binary[0...size] + \"0\" * (32 - size)\n\n // convert back to dotted-decimal\n var chunks = Str.chunks(binary, 8)\n var canon = chunks.map { |c| Conv.atoi(c, 2) }.join(\".\")\n\n // and return\n return canon + \"/\" + split[1]\n}\n\nvar tests = [\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\"\n]\n\nfor (test in tests) {\n Fmt.print(\"$-18s -> $s\", test, canonicalize.call(test))\n}\n", "language": "Wren" }, { "code": "proc Canonicalize(IPAddr);\nchar IPAddr;\nint N, I, HostBits;\n[Text(0, IPAddr);\nText(0, \" ^i-> \"); \\^i = tab\nOpenO(8);\nText(8, IPAddr); \\ASCII out\nOpenI(8);\nN:= 0;\nfor I:= 0 to 3 do\n N:= N<<8 + IntIn(8); \\binary in\nHostBits:= IntIn(8);\nN:= N & -1<<(32-HostBits);\nfor I:= 3 downto 0 do\n [IntOut(0, N>>(I*8) & $FF);\n ChOut(0, if I = 0 then ^/ else ^.);\n ];\nIntOut(0, HostBits);\nCrLf(0);\n];\n\nint IPAddrs, I;\n[IPAddrs:= [\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\" ];\nfor I:= 0 to 6-1 do\n Canonicalize(IPAddrs(I));\n]\n", "language": "XPL0" } ]
Canonicalize-CIDR
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Cantor_set\n", "language": "00-META" }, { "code": ";Task:\nDraw a Cantor set.\n\n\nSee details at this Wikipedia webpage: &nbsp; [https://en.wikipedia.org/wiki/Cantor_set Cantor set]\n<br><br>\n", "language": "00-TASK" }, { "code": "V WIDTH = 81\nV HEIGHT = 5\n\nF cantor(start, len, index)\n V seg = len I/ 3\n I seg == 0\n R\n L(it) 0 .< :HEIGHT - index\n V i = index + it\n L(jt) 0 .< seg\n V j = start + seg + jt\n V pos = i * :WIDTH + j\n :lines[pos] = ‘ ’\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\n\nV lines = [‘*’] * (WIDTH * HEIGHT)\ncantor(0, WIDTH, 1)\n\nL(i) 0 .< HEIGHT\n V beg = WIDTH * i\n print((lines[beg .< beg + WIDTH]).join(‘’))\n", "language": "11l" }, { "code": "PROC FillRect(INT x,y,w,h)\n INT i\n\n FOR i=y TO y+h-1\n DO\n Plot(x,i)\n DrawTo(x+w-1,i)\n OD\nRETURN\n\nPROC DrawCantor(INT x0,y0,h,level)\n INT x,y,i,j,w,w2,h2\n\n w=1\n FOR i=0 TO level-1\n DO w==*3 OD\n\n Color=1\n y=y0\n FOR i=0 TO level\n DO\n FillRect(x0,y,w,h)\n y==+h*2\n OD\n\n Color=0\n w2=1 h2=h*2\n FOR i=0 TO level-1\n DO\n x=w2 y=(level-i)*(h*2)\n WHILE x<w\n DO\n FillRect(x0+x,y0+y,w2,h2)\n x==+w2*2\n OD\n w2==*3\n h2==+h*2\n OD\nRETURN\n\nPROC Main()\n BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6\n\n Graphics(8+16)\n COLOR1=$0C\n COLOR2=$02\n\n DrawCantor(38,48,8,5)\n\n DO UNTIL CH#$FF OD\n CH=$FF\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO;\n\nprocedure Cantor_Set is\n\n subtype Level_Range is Integer range 1 .. 5;\n Image : array (Level_Range) of String (1 .. 81) := (others => (others => ' '));\n\n procedure Cantor (Level : Natural; Length : Natural; Start : Natural) is\n begin\n if Level in Level_Range then\n Image (Level) (Start .. Start + Length - 1) := (others => '*');\n Cantor (Level + 1, Length / 3, Start);\n Cantor (Level + 1, Length / 3, Start + 2 * Length / 3);\n end if;\n end Cantor;\nbegin\n Cantor (Level => Level_Range'First,\n Length => 81,\n Start => 1);\n\n for L in Level_Range loop\n Ada.Text_IO.Put_Line (Image (L));\n end loop;\nend Cantor_Set;\n", "language": "Ada" }, { "code": "BEGIN\n # draw a Cantor Set using ASCII #\n INT lines = 5; # number of lines for the set #\n # we must choose the line width so that the width of each segment is #\n # divisible by 3 ( except for the final line where the segment width will #\n # be 1 ) #\n INT set width = 3 ^ ( lines - 1 );\n [ set width ]CHAR set;\n # start with a complete line #\n FOR i TO set width DO set[ i ] := \"#\" OD;\n print( ( set, newline ) );\n # repeatedly modify the line, replacing the middle third of each segment #\n # with blanks #\n INT segment width := set width OVER 3;\n WHILE segment width > 0 DO\n INT set pos := 1;\n WHILE set pos < ( set width - segment width ) DO\n set pos +:= segment width;\n FOR char pos FROM set pos TO ( set pos + segment width ) - 1 DO\n set[ char pos ] := \" \"\n OD;\n set pos +:= segment width\n OD;\n print( ( set, newline ) );\n segment width OVERAB 3\n OD\nEND\n", "language": "ALGOL-68" }, { "code": "begin\n % draw a Cantor Set using ASCII %\n integer LINES; % number of lines for the set %\n integer setWidth; % width of each line of the set %\n % we must choose the line width so that the width of each segment is %\n % divisible by 3 ( except for the final line where the segment width will %\n % be 1 ) %\n LINES := 5;\n setWidth := round( 3 ** ( LINES - 1 ) );\n begin % start new block so the array can have computed bounds %\n logical array set ( 1 :: setWidth );\n integer segmentWidth;\n % start with a complete line %\n for i := 1 until setWidth do set( i ) := true;\n segmentWidth := setWidth;\n for l := 1 until LINES do begin\n % print the latest line, all lines start with a \"#\" %\n write( \"#\" );\n for i := 2 until setWidth do writeon( if set( i ) then \"#\" else \" \" );\n % modify the line, replacing the middle third of each segment %\n % with blanks, unless this was the last line %\n if l < LINES then begin\n integer setPos;\n segmentWidth := segmentWidth div 3;\n setPos := 1;\n while setPos < ( setWidth - segmentWidth ) do begin\n setPos := setPos + segmentWidth;\n for charPos := setPos until ( setPos + segmentWidth ) - 1 do set( charPos ) := false;\n setPos := setPos + segmentWidth\n end while_setPos_in_range ;\n end if_l_lt_LINES\n end for_l\n end\nend.\n", "language": "ALGOL-W" }, { "code": "#include <basico.h>\n\n#define WIDTH 81\n#define HEIGHT 5\n\n#proto cantor(_X_,_Y_,_Z_)\n\nalgoritmo\n\n decimales '0'\n dimensionar(HEIGHT,WIDTH) matriz rellena(\"#\",líneas)\n\n _cantor(1, WIDTH, 2)\n\n fijar separador 'NULO', imprimir( líneas, NL)\n\nterminar\n\nsubrutinas\n\ncantor(inicio, largo, índice)\n seg=0\n #( seg:=(int(largo/3))), no es cero?, entonces{\n #basic{\n líneas[índice:HEIGHT, (inicio+seg):((inicio+seg*2)-1)] = \" \")\n cantor( inicio, seg, índice+1 ) )\n cantor( (inicio+(seg*2)), seg, índice+1 ) )\n }\n }\nretornar\n", "language": "Amazing-Hopper" }, { "code": "#include <basico.h>\n\n#define HEIGHT 5\n\nalgoritmo\n\n decimales '0'\n cantor=\"\", j=0\n iterar\n i=0\n cadenas 's,v'\n iterar grupo ( ++i, #(i< (3^j)),\\\n #( v = occurs(\"1\", dectobase(i,3)) ? \" \" : \"#\"; )\\\n #( s = s $ replicate(v, 3^(HEIGHT-j-1) )) )\n #(cantor = cantor $ s $ NL)\n mientras ' #(j<=HEIGHT); ++j '\n imprimir(cantor)\n\nterminar\n", "language": "Amazing-Hopper" }, { "code": "------------------------- CANTOR SET -----------------------\n\n-- cantor :: [String] -> [String]\non cantor(xs)\n script go\n on |λ|(s)\n set m to (length of s) div 3\n set blocks to text 1 thru m of s\n\n if \"█\" = text 1 of s then\n {blocks, replicate(m, space), blocks}\n else\n {s}\n end if\n end |λ|\n end script\n concatMap(go, xs)\nend cantor\n\n\n---------------------------- TEST --------------------------\non run\n showCantor(5)\nend run\n\n-- showCantor :: Int -> String\non showCantor(n)\n unlines(map(my concat, ¬\n take(n, iterate(cantor, ¬\n {replicate(3 ^ (n - 1), \"█\")}))))\nend showCantor\n\n\n--------------------- GENERIC FUNCTIONS --------------------\n\n-- concat :: [[a]] -> [a]\n-- concat :: [String] -> String\non concat(xs)\n set lng to length of xs\n if 0 < lng and string is class of (item 1 of xs) then\n set acc to \"\"\n else\n set acc to {}\n end if\n repeat with i from 1 to lng\n set acc to acc & item i of xs\n end repeat\n acc\nend concat\n\n\n-- concatMap :: (a -> [b]) -> [a] -> [b]\non concatMap(f, xs)\n set lng to length of xs\n set acc to {}\n tell mReturn(f)\n repeat with i from 1 to lng\n set acc to acc & |λ|(item i of xs, i, xs)\n end repeat\n end tell\n return acc\nend concatMap\n\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: First-class m => (a -> b) -> m (a -> b)\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n\n-- iterate :: (a -> a) -> a -> Gen [a]\non iterate(f, x)\n script\n property v : missing value\n property g : mReturn(f)'s |λ|\n on |λ|()\n if missing value is v then\n set v to x\n else\n set v to g(v)\n end if\n return v\n end |λ|\n end script\nend iterate\n\n\n-- replicate :: Int -> String -> String\non replicate(n, s)\n set out to \"\"\n if n < 1 then return out\n set dbl to s\n\n repeat while (n > 1)\n if (n mod 2) > 0 then set out to out & dbl\n set n to (n div 2)\n set dbl to (dbl & dbl)\n end repeat\n return out & dbl\nend replicate\n\n\n-- take :: Int -> [a] -> [a]\n-- take :: Int -> String -> String\non take(n, xs)\n set c to class of xs\n if list is c then\n if 0 < n then\n items 1 thru min(n, length of xs) of xs\n else\n {}\n end if\n else if string is c then\n if 0 < n then\n text 1 thru min(n, length of xs) of xs\n else\n \"\"\n end if\n else if script is c then\n set ys to {}\n repeat with i from 1 to n\n set v to xs's |λ|()\n if missing value is v then\n return ys\n else\n set end of ys to v\n end if\n end repeat\n return ys\n else\n missing value\n end if\nend take\n\n\n-- unlines :: [String] -> String\non unlines(xs)\n set {dlm, my text item delimiters} to ¬\n {my text item delimiters, linefeed}\n set str to xs as text\n set my text item delimiters to dlm\n str\nend unlines\n", "language": "AppleScript" }, { "code": "width: 81\nheight: 5\n\nlines: array.of: height repeat `*` width\n\ncantor: function [start length idx].export:[lines][\n seg: length / 3\n if seg = 0 -> return null\n\n loop idx..dec height 'i [\n loop (start + seg).. dec start + 2 * seg 'j\n -> set lines\\[i] j ` `\n ]\n cantor start seg idx+1\n cantor start + 2 * seg seg idx+1\n]\n\ncantor 0 width 1\n\nloop lines 'line\n -> print join line\n", "language": "Arturo" }, { "code": "# syntax: GAWK -f CANTOR_SET.AWK\n# converted from C\nBEGIN {\n WIDTH = 81\n HEIGHT = 5\n for (i=0; i<HEIGHT; ++i) {\n for (j=0; j<WIDTH; ++j) {\n lines[i][j] = \"*\"\n }\n }\n cantor(0,WIDTH,1)\n for (i=0; i<HEIGHT; ++i) {\n for (j=0; j<WIDTH; ++j) {\n printf(\"%s\",lines[i][j])\n }\n printf(\"\\n\")\n }\n exit(0)\n}\nfunction cantor(start,leng,indx, i,j,seg) {\n seg = int(leng/3)\n if (seg == 0) { return }\n for (i=indx; i<HEIGHT; ++i) {\n for (j=start+seg; j<start+seg*2; ++j) {\n lines[i][j] = \" \"\n }\n }\n cantor(start,seg,indx+1)\n cantor(start+seg*2,seg,indx+1)\n}\n", "language": "AWK" }, { "code": "10 DEFINT A-Z\n20 N = 4\n30 W = 3^(N-1)\n40 S = W\n50 L$ = STRING$(W, \"#\")\n60 PRINT L$\n70 IF S = 1 THEN END\n80 S = S\\3\n90 P = 1\n100 IF P >= W-S GOTO 60\n110 P = P+S\n120 MID$(L$,P,S) = SPACE$(S)\n130 P = P+S\n140 GOTO 100\n", "language": "BASIC" }, { "code": "global ancho, alto, intervalo\nancho = 81 : alto = 5\ndim intervalo(alto, ancho)\n\nsubroutine Cantor()\n\tfor i = 0 to alto - 1\n\t\tfor j = 0 to ancho - 1\n\t\t\tintervalo[i, j] = \"■\"\n\t\tnext j\n\tnext i\nend subroutine\n\nsubroutine ConjCantor(inicio, longitud, indice)\n\tsegmento = longitud / 3\n\tif segmento = 0 then return\n\tfor i = indice to alto - 1\n\t\tfor j = inicio + segmento to inicio + segmento * 2 - 1\n\t\t\tintervalo[i, j] = \" \"\n\t\tnext j\n\tnext i\n\tcall ConjCantor(inicio, segmento, indice + 1)\n\tcall ConjCantor(inicio + segmento * 2, segmento, indice + 1)\nend subroutine\n\ncall Cantor()\ncall ConjCantor(0, ancho, 1)\nfor i = 0 to alto - 1\n\tfor j = 0 to ancho - 1\n\t\tprint intervalo[i, j];\n\tnext j\n\tprint\nnext i\nend\n", "language": "BASIC256" }, { "code": "Cantor ← {\" •\" ⊏˜ >⥊¨(¯1⊸⊏⊢¨¨⊢)1‿0‿1∧⌜⍟(↕𝕩)1}\n", "language": "BQN" }, { "code": "#include <stdio.h>\n\n#define WIDTH 81\n#define HEIGHT 5\n\nchar lines[HEIGHT][WIDTH];\n\nvoid init() {\n int i, j;\n for (i = 0; i < HEIGHT; ++i) {\n for (j = 0; j < WIDTH; ++j) lines[i][j] = '*';\n }\n}\n\nvoid cantor(int start, int len, int index) {\n int i, j, seg = len / 3;\n if (seg == 0) return;\n for (i = index; i < HEIGHT; ++i) {\n for (j = start + seg; j < start + seg * 2; ++j) lines[i][j] = ' ';\n }\n cantor(start, seg, index + 1);\n cantor(start + seg * 2, seg, index + 1);\n}\n\nvoid print() {\n int i, j;\n for (i = 0; i < HEIGHT; ++i) {\n for (j = 0; j < WIDTH; ++j) printf(\"%c\", lines[i][j]);\n printf(\"\\n\");\n }\n}\n\nint main() {\n init();\n cantor(0, WIDTH, 1);\n print();\n return 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n\nconst int WIDTH = 81;\nconst int HEIGHT = 5;\n\nchar lines[WIDTH*HEIGHT];\n\nvoid cantor(int start, int len, int index) {\n\tint seg = len / 3;\n\tif (seg == 0) return;\n\tfor (int i = index; i < HEIGHT; i++) {\n\t\tfor (int j = start + seg; j < start + seg * 2; j++) {\n\t\t\tint pos = i * WIDTH + j;\n\t\t\tlines[pos] = ' ';\n\t\t}\n\t}\n\tcantor(start, seg, index + 1);\n\tcantor(start + 2 * seg, seg, index + 1);\n}\n\nint main() {\n\t// init\n\tfor (int i = 0; i < WIDTH*HEIGHT; i++) {\n\t\tlines[i] = '*';\n\t}\n\n\t// calculate\n\tcantor(0, WIDTH, 1);\n\n\t// print\n\tfor (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) {\n\t\tprintf(\"%.*s\\n\", WIDTH, lines + i);\n\t}\n\n\treturn 0;\n}\n", "language": "C++" }, { "code": "using System;\n\nnamespace CantorSet {\n class Program {\n const int WIDTH = 81;\n const int HEIGHT = 5;\n private static char[,] lines = new char[HEIGHT, WIDTH];\n\n static Program() {\n for (int i = 0; i < HEIGHT; i++) {\n for (int j = 0; j < WIDTH; j++) {\n lines[i, j] = '*';\n }\n }\n }\n\n private static void Cantor(int start, int len, int index) {\n int seg = len / 3;\n if (seg == 0) return;\n for (int i = index; i < HEIGHT; i++) {\n for (int j = start + seg; j < start + seg * 2; j++) {\n lines[i, j] = ' ';\n }\n }\n Cantor(start, seg, index + 1);\n Cantor(start + seg * 2, seg, index + 1);\n }\n\n static void Main(string[] args) {\n Cantor(0, WIDTH, 1);\n for (int i = 0; i < HEIGHT; i++) {\n for (int j = 0; j < WIDTH; j++) {\n Console.Write(lines[i,j]);\n }\n Console.WriteLine();\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "100 cls\n110 ancho = 81\n120 alto = 5\n130 dim intervalo$(alto,ancho)\n140 '\n150 sub cantor()\n160 for i = 0 to alto-1\n170 for j = 0 to ancho-1\n180 intervalo$(i,j) = chr$(254)\n190 next j\n200 next i\n210 end sub\n220 '\n230 sub conjcantor(inicio,longitud,indice)\n240 segmento = longitud/3\n250 if segmento = 0 then exit sub\n260 for i = indice to alto-1\n270 for j = inicio+segmento to inicio+segmento*2-1\n280 intervalo$(i,j) = chr$(32)\n290 next j\n300 next i\n310 conjcantor(inicio,segmento,indice+1)\n320 conjcantor(inicio+segmento*2,segmento,indice+1)\n330 end sub\n340 '\n350 cantor()\n360 conjcantor(0,ancho,1)\n370 for i = 0 to alto-1\n380 for j = 0 to ancho-1\n390 print intervalo$(i,j);\n400 next j\n410 print\n420 next i\n430 end\n", "language": "Chipmunk-Basic" }, { "code": "cantor = cluster is make\n rep = null\n ac = array[char]\n aac = array[array[char]]\n\n make = proc (width, height: int, ch: char) returns (string)\n lines: aac := aac$fill_copy(0, height, ac$fill(0, width, ch))\n cantor_step(lines, 0, width, 1)\n s: stream := stream$create_output()\n for line: ac in aac$elements(lines) do\n stream$putl(s, string$ac2s(line))\n end\n return(stream$get_contents(s))\n end make\n\n cantor_step = proc (lines: aac, start, len, index: int)\n seg: int := len / 3\n if seg = 0 then return end\n for i: int in int$from_to(index, aac$high(lines)) do\n for j: int in int$from_to(start+seg, start+seg*2-1) do\n lines[i][j] := ' '\n end\n end\n cantor_step(lines, start, seg, index+1)\n cantor_step(lines, start+seg*2, seg, index+1)\n end cantor_step\nend cantor\n\nstart_up = proc ()\n po: stream := stream$primary_output()\n cs: string := cantor$make(81, 5, '*')\n stream$puts(po, cs)\nend start_up\n", "language": "CLU" }, { "code": " IDENTIFICATION DIVISION.\n PROGRAM-ID. CANTOR.\n\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 SETTINGS.\n 03 NUM-LINES PIC 9 VALUE 5.\n 03 FILL-CHAR PIC X VALUE '#'.\n 01 VARIABLES.\n 03 CUR-LINE.\n 05 CHAR PIC X OCCURS 81 TIMES.\n 03 WIDTH PIC 99.\n 03 CUR-SIZE PIC 99.\n 03 POS PIC 99.\n 03 MAXPOS PIC 99.\n 03 NEXTPOS PIC 99.\n 03 I PIC 99.\n\n PROCEDURE DIVISION.\n BEGIN.\n COMPUTE WIDTH = 3 ** (NUM-LINES - 1).\n PERFORM INIT.\n MOVE WIDTH TO CUR-SIZE.\n DISPLAY CUR-LINE.\n PERFORM DO-LINE UNTIL CUR-SIZE IS EQUAL TO 1.\n STOP RUN.\n\n INIT.\n PERFORM INIT-CHAR VARYING I FROM 1 BY 1\n UNTIL I IS GREATER THAN WIDTH.\n\n INIT-CHAR.\n MOVE FILL-CHAR TO CHAR(I).\n\n DO-LINE.\n DIVIDE 3 INTO CUR-SIZE.\n MOVE 1 TO POS.\n SUBTRACT CUR-SIZE FROM WIDTH GIVING MAXPOS.\n PERFORM BLANK-REGIONS UNTIL POS IS GREATER THAN MAXPOS.\n DISPLAY CUR-LINE.\n\n BLANK-REGIONS.\n ADD CUR-SIZE TO POS.\n PERFORM BLANK-CHAR CUR-SIZE TIMES.\n\n BLANK-CHAR.\n MOVE SPACE TO CHAR(POS).\n ADD 1 TO POS.\n", "language": "COBOL" }, { "code": "import std.stdio;\n\nenum WIDTH = 81;\nenum HEIGHT = 5;\n\nchar[WIDTH*HEIGHT] lines;\n\nvoid cantor(int start, int len, int index) {\n int seg = len / 3;\n if (seg == 0) return;\n for (int i=index; i<HEIGHT; i++) {\n for (int j=start+seg; j<start+seg*2; j++) {\n int pos = i*WIDTH + j;\n lines[pos] = ' ';\n }\n }\n cantor(start, seg, index+1);\n cantor(start+seg*2, seg, index+1);\n}\n\nvoid main() {\n // init\n lines[] = '*';\n\n // calculate\n cantor(0, WIDTH, 1);\n\n // print\n for (int i=0; i<HEIGHT; i++) {\n int beg = WIDTH * i;\n writeln(lines[beg..beg+WIDTH]);\n }\n}\n", "language": "D" }, { "code": "program Cantor_set;\n\n{$APPTYPE CONSOLE}\n\nconst\n WIDTH: Integer = 81;\n HEIGHT: Integer = 5;\n\nvar\n Lines: TArray<TArray<Char>>;\n\nprocedure Init;\nvar\n i, j: Integer;\nbegin\n SetLength(lines, HEIGHT, WIDTH);\n for i := 0 to HEIGHT - 1 do\n for j := 0 to WIDTH - 1 do\n lines[i, j] := '*';\nend;\n\nprocedure Cantor(start, len, index: Integer);\nvar\n seg, i, j: Integer;\nbegin\n seg := len div 3;\n if seg = 0 then\n Exit;\n for i := index to HEIGHT - 1 do\n for j := start + seg to start + seg * 2 - 1 do\n lines[i, j] := ' ';\n Cantor(start, seg, index + 1);\n Cantor(start + seg * 2, seg, index + 1);\nend;\n\nvar\n i, j: Integer;\n\nbegin\n Init;\n Cantor(0, WIDTH, 1);\n for i := 0 to HEIGHT - 1 do\n begin\n for j := 0 to WIDTH - 1 do\n Write(lines[i, j]);\n Writeln;\n end;\n Readln;\nend.\n", "language": "Delphi" }, { "code": "color 555\nproc cantor x y sz . .\n if sz > 0.1\n sz3 = sz / 3\n move x y - sz3\n rect sz sz3\n cantor x y - sz3 sz3\n cantor x + 2 * sz3 y - sz3 sz3\n .\n.\ncantor 0 80 100\n", "language": "EasyLang" }, { "code": "defmodule Cantor do\n @pos \"█\"\n @neg \" \"\n\n def run(lines) do\n Enum.map(0..lines, fn line ->\n segment_size = 3 ** (lines - line - 1)\n chars = (3 ** line)\n\n Enum.map(0..chars, fn char ->\n char\n |> Integer.digits(3)\n |> Enum.any?(fn x -> x === 1 end)\n |> case do\n true -> @neg\n false -> @pos\n end\n end)\n |> Enum.reduce([], fn el, acc -> duplicate_char(acc, el, segment_size) end)\n |> Enum.join()\n |> String.trim_trailing()\n end)\n |> Enum.filter(fn line -> line !== \"\" end)\n end\n\n def duplicate_char(acc, el, segment_size) when segment_size >= 1, do: acc ++ [String.duplicate(el, segment_size)]\n def duplicate_char(acc, _el, segment_size) when segment_size < 1, do: acc\nend\n\nCantor.run(5) |> IO.inspect()\n", "language": "Elixir" }, { "code": "int WIDTH = 81\nint HEIGHT = 5\nList lines = text[].with(HEIGHT) # a list with HEIGHT empty texts\nfor each int i in range(0, HEIGHT) do lines[i] = text(\"█\", WIDTH) end\nfun cantor = void by int start, int len, int index\n int seg = len / 3\n if seg == 0 do return end\n for int i = index; i < HEIGHT; i++\n for int j = start + seg; j < start + seg * 2; j++\n lines[i][j] = \" \"\n end\n end\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\nend\ncantor(0, WIDTH, 1)\nfor each text line in lines do writeLine(line) end\n", "language": "EMal" }, { "code": "CANTOR\n=LAMBDA(n,\n APPLYN(n)(\n LAMBDA(grid,\n APPENDROWS(grid)(\n CANTOROW(\n LASTROW(grid)\n )\n )\n )\n )({0,1})\n)\n\n\nCANTOROW\n=LAMBDA(xys,\n LET(\n nCols, COLUMNS(xys),\n\n IF(2 > nCols,\n xys,\n IF(3 < nCols,\n APPENDCOLS(\n CANTORSLICES(TAKECOLS(2)(xys))\n )(\n CANTOROW(DROPCOLS(2)(xys))\n ),\n CANTORSLICES(TAKECOLS(2)(xys))\n )\n )\n )\n)\n\n\nCANTORSLICES\n=LAMBDA(ab,\n LET(\n a, INDEX(ab, 1),\n b, INDEX(ab, 2),\n third, (b - a) / 3,\n\n CHOOSE({1,2,3,4}, a, a + third, b - third, b)\n )\n)\n\n\nSHOWCANTOR\n=LAMBDA(grid,\n LET(\n leaves, LASTROW(grid),\n leafWidth, INDEX(leaves, 1, 2) - INDEX(leaves, 1, 1),\n leafCount, 1 / leafWidth,\n\n SHOWCANTROWS(leafCount)(grid)\n )\n)\n\n\nSHOWCANTROWS\n=LAMBDA(leafCount,\n LAMBDA(grid,\n LET(\n xs, FILTERP(\n LAMBDA(x, NOT(ISNA(x)))\n )(\n HEADCOL(grid)\n ),\n\n runLengths, LAMBDA(x,\n CEILING.MATH(leafCount * x))(\n SUBTRACT(TAILROW(xs))(INITROW(xs)\n )\n ),\n\n iCols, SEQUENCE(1, COLUMNS(runLengths)),\n\n CONCAT(\n REPT(\n IF(ISEVEN(iCols), \" \", \"█\"),\n runLengths\n )\n ) & IF(1 < ROWS(grid),\n CHAR(10) & SHOWCANTROWS(leafCount)(\n TAILCOL(grid)\n ),\n \"\"\n )\n )\n )\n)\n", "language": "Excel" }, { "code": "APPENDCOLS\n=LAMBDA(xs,\n LAMBDA(ys,\n LET(\n nx, COLUMNS(xs),\n ny, COLUMNS(ys),\n colIndexes, SEQUENCE(1, nx + ny),\n rowIndexes, SEQUENCE(MAX(ROWS(xs), ROWS(ys))),\n\n IFERROR(\n IF(nx < colIndexes,\n INDEX(ys, rowIndexes, colIndexes - nx),\n INDEX(xs, rowIndexes, colIndexes)\n ),\n NA()\n )\n )\n )\n)\n\n\nAPPENDROWS\n=LAMBDA(xs,\n LAMBDA(ys,\n LET(\n nx, ROWS(xs),\n rowIndexes, SEQUENCE(nx + ROWS(ys)),\n colIndexes, SEQUENCE(\n 1,\n MAX(COLUMNS(xs), COLUMNS(ys))\n ),\n\n IFERROR(\n IF(rowIndexes <= nx,\n INDEX(xs, rowIndexes, colIndexes),\n INDEX(ys, rowIndexes - nx, colIndexes)\n ),\n NA()\n )\n )\n )\n)\n\n\nAPPLYN\n=LAMBDA(n,\n LAMBDA(f,\n LAMBDA(x,\n IF(0 < n,\n APPLYN(n - 1)(f)(\n f(x)\n ),\n x\n )\n )\n )\n)\n\n\nDROPCOLS\n=LAMBDA(n,\n LAMBDA(xs,\n INDEX(\n xs,\n SEQUENCE(ROWS(xs), 1),\n SEQUENCE(1, (COLUMNS(xs) - n), 1 + n, 1)\n )\n )\n)\n\n\nFILTERP\n=LAMBDA(p,\n LAMBDA(xs,\n FILTER(xs, p(xs))\n )\n)\n\n\nHEADCOL\n=LAMBDA(xs,\n LET(REM, \"The first item of each column in xs\",\n\n INDEX(xs, 1, SEQUENCE(1, COLUMNS(xs)))\n )\n)\n\n\nINITROW\n=LAMBDA(xs,\n INDEX(\n xs,\n SEQUENCE(\n 1,\n COLUMNS(xs) - 1,\n 1, 1\n )\n )\n)\n\n\nLASTROW\n=LAMBDA(xs,\n INDEX(\n xs,\n ROWS(xs),\n SEQUENCE(1, COLUMNS(xs), 1, 1)\n )\n)\n\n\nSUBTRACT\n=LAMBDA(a,\n LAMBDA(b, a - b)\n)\n\n\nTAILCOL\n=LAMBDA(cols,\n LET(REM, \"The tail of each column in the grid.\",\n\n INDEX(\n cols,\n SEQUENCE(ROWS(cols) - 1, 1, 2, 1),\n SEQUENCE(1, COLUMNS(cols))\n )\n )\n)\n\n\nTAILROW\n=LAMBDA(xs,\n LET(REM,\"The tail of each row in the grid\",\n n, COLUMNS(xs) - 1,\n\n IF(0 < n,\n INDEX(\n xs,\n SEQUENCE(ROWS(xs), 1, 1, 1),\n SEQUENCE(1, n, 2, 1)\n ),\n NA()\n )\n )\n)\n\n\nTAKECOLS\n=LAMBDA(n,\n LAMBDA(xs,\n INDEX(\n xs,\n SEQUENCE(ROWS(xs)),\n SEQUENCE(1, n)\n )\n )\n)\n", "language": "Excel" }, { "code": "█\n", "language": "Excel" }, { "code": "███\n█ █\n", "language": "Excel" }, { "code": "█████████\n███ ███\n█ █ █ █\n", "language": "Excel" }, { "code": "███████████████████████████\n█████████ █████████\n███ ███ ███ ███\n█ █ █ █ █ █ █ █\n", "language": "Excel" }, { "code": "USING: grouping.extras io kernel math sequences\nsequences.repeating ;\nIN: rosetta-code.cantor-set\n\nCONSTANT: width 81\nCONSTANT: depth 5\n\n: cantor ( n -- seq )\n dup 0 = [ drop { 0 1 } ]\n [ 1 - cantor [ 3 / ] map dup [ 2/3 + ] map append ] if ;\n\n! Produces a sequence of lengths from a Cantor set, depending on\n! width. Even indices are solid; odd indices are blank.\n! e.g. 2 cantor gaps -> { 9 9 9 27 9 9 9 }\n!\n: gaps ( seq -- seq )\n [ width * ] map [ - abs ] 2clump-map ;\n\n: print-cantor ( n -- )\n cantor gaps [ even? \"#\" \" \" ? swap repeat ] map-index\n concat print ;\n\ndepth <iota> [ print-cantor ] each\n", "language": "Factor" }, { "code": "warnings off\n\n4 \\ iterations\n: ** 1 swap 0 ?DO over * LOOP nip ;\n3 swap ** constant width \\ Make smallest step 1\n\ncreate string here width char # fill width allot\n: print string width type cr ;\n\n\\ Overwrite string with new holes of size 'length'.\n\\ Pointer into string at TOS.\ncreate length width ,\n: reduce length dup @ 3 / swap ! ;\n: done? dup string - width >= ;\n: hole? dup c@ bl = ;\n: skip length @ + ;\n: whipe dup length @ bl fill skip ;\n: step hole? IF skip skip skip ELSE skip whipe skip THEN ;\n: split reduce string BEGIN step done? UNTIL drop ;\n\n\\ Main\n: done? length @ 1 <= ;\n: step split print ;\n: go print BEGIN step done? UNTIL ;\n\ngo bye\n", "language": "Forth" }, { "code": "Const ancho = 81\nConst alto = 5\nDim Shared intervalo(alto, ancho) As String\nDim As Integer i, j\n\nSub Cantor()\n Dim As Integer i, j\n For i = 0 To alto - 1\n For j = 0 To ancho - 1\n intervalo(i, j) = Chr(254)\n Next j\n Next i\nEnd Sub\n\nSub ConjCantor(inicio As Integer, longitud As Integer, indice As Integer)\n Dim As Integer i, j\n Dim segmento As Integer = longitud / 3\n If segmento = 0 Then Return\n For i = indice To alto - 1\n For j = inicio + segmento To inicio + segmento * 2 - 1\n intervalo(i, j) = Chr(32)\n Next j\n Next i\n ConjCantor(inicio, segmento, indice + 1)\n ConjCantor(inicio + segmento * 2, segmento, indice + 1)\nEnd Sub\n\nCantor()\nConjCantor(0, ancho, 1)\nFor i = 0 To alto - 1\n For j = 0 To ancho - 1\n Print intervalo(i, j);\n Next j\n Print\nNext i\nEnd\n", "language": "FreeBASIC" }, { "code": "_window = 1\n\n_width = 81\n_height = 5\n\nwindow _window, @\"FutureBasic Cantor Set\", ( 0, 0, 695, 100 )\nWindowSetBackgroundColor( _window, fn ColorWhite )\ntext @\"Menlo\", 14.0, fn ColorRed\n\nbegin globals\nCFStringRef gInterval( _height, _width )\nend globals\n\nlocal fn Init\n NSInteger i, j\n\n for i = 0 to _height - 1\n for j = 0 to _width - 1\n gInterval( i, j ) = @\"◼︎\"\n next\n next\nend fn\n\nlocal fn CantorSet( start as NSInteger, length as NSInteger, index as NSInteger )\n NSInteger i, j, segment = length / 3\n\n if segment == 0 then exit fn\n for i = index to _height - 1\n for j = start + segment to start + segment * 2 - 1\n gInterval( i, j ) = @\" \"\n next\n next\n fn CantorSet( start, segment, index + 1 )\n fn CantorSet( start + segment * 2, segment, index + 1 )\nend fn\n\nNSInteger i, j\n\nfn Init\nfn CantorSet ( 0, _width, 1 )\nfor i = 0 to _height - 1\n for j = 0 to _width - 1\n print gInterval( i, j );\n next\n print\nnext\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport \"fmt\"\n\nconst (\n width = 81\n height = 5\n)\n\nvar lines [height][width]byte\n\nfunc init() {\n for i := 0; i < height; i++ {\n for j := 0; j < width; j++ {\n lines[i][j] = '*'\n }\n }\n}\n\nfunc cantor(start, len, index int) {\n seg := len / 3\n if seg == 0 {\n return\n }\n for i := index; i < height; i++ {\n for j := start + seg; j < start + 2 * seg; j++ {\n lines[i][j] = ' '\n }\n }\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\n}\n\nfunc main() {\n cantor(0, width, 1)\n for _, line := range lines {\n fmt.Println(string(line[:]))\n }\n}\n", "language": "Go" }, { "code": "class App {\n private static final int WIDTH = 81\n private static final int HEIGHT = 5\n\n private static char[][] lines\n static {\n lines = new char[HEIGHT][WIDTH]\n for (int i = 0; i < HEIGHT; i++) {\n for (int j = 0; j < WIDTH; j++) {\n lines[i][j] = '*'\n }\n }\n }\n\n private static void cantor(int start, int len, int index) {\n int seg = (int) (len / 3)\n if (seg == 0) return\n for (int i = index; i < HEIGHT; i++) {\n for (int j = start + seg; j < start + seg * 2; j++) {\n lines[i][j] = ' '\n }\n }\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\n }\n\n static void main(String[] args) {\n cantor(0, WIDTH, 1)\n for (int i = 0; i < HEIGHT; i++) {\n for (int j = 0; j < WIDTH; j++) {\n System.out.print(lines[i][j])\n }\n System.out.println()\n }\n }\n}\n", "language": "Groovy" }, { "code": "-------------------------- CANTOR ------------------------\n\ncantor :: [(Bool, Int)] -> [(Bool, Int)]\ncantor = concatMap go\n where\n go (bln, n)\n | bln && 1 < n =\n let m = quot n 3\n in [(True, m), (False, m), (True, m)]\n | otherwise = [(bln, n)]\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain = putStrLn $ cantorLines 5\n\n------------------------- DISPLAY ------------------------\ncantorLines :: Int -> String\ncantorLines n =\n unlines $\n showCantor\n <$> take n (iterate cantor [(True, 3 ^ pred n)])\n\nshowCantor :: [(Bool, Int)] -> String\nshowCantor = concatMap $ uncurry (flip replicate . c)\n where\n c True = '*'\n c False = ' '\n", "language": "Haskell" }, { "code": "-------------------------- CANTOR ------------------------\n\ncantor :: [String] -> [String]\ncantor = (go =<<)\n where\n go x\n | '█' == head x = [block, replicate m ' ', block]\n | otherwise = [x]\n where\n m = quot (length x) 3\n block = take m x\n\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain = putStrLn $ cantorLines 5\n\n\n------------------------- DISPLAY ------------------------\ncantorLines :: Int -> String\ncantorLines =\n unlines . (concat <$>)\n . ( take\n <*> ( iterate cantor\n . return\n . flip replicate '█'\n . (3 ^)\n . pred\n )\n )\n", "language": "Haskell" }, { "code": "import Control.Monad (join)\nimport Data.Bifunctor (bimap)\nimport Data.List (intercalate, mapAccumL, maximumBy)\nimport Data.Ratio (Ratio, denominator, numerator, (%))\n\n-------------------------- CANTOR ------------------------\n\ncantor :: (Rational, Rational) -> [[(Rational, Rational)]]\ncantor = iterate (go =<<) . pure\n where\n go (x, y) = [(x, x + r), (y - r, y)]\n where\n r = (y - x) / 3\n\n--------------------------- TEST -------------------------\n\nmain :: IO ()\nmain =\n ( ( (>>)\n . putStrLn\n . unlines\n . fmap intervalRatios\n )\n <*> (putStrLn . intervalBars)\n )\n $ take 4 $ cantor (0, 1)\n\n------------------------- DISPLAY ------------------------\n\nintervalBars :: [[(Rational, Rational)]] -> String\nintervalBars xs = unlines $ go (d % 1) <$> xs\n where\n d = maximum $ denominator . fst <$> last xs\n go w xs =\n concat . snd $\n mapAccumL\n ( \\a (rx, ry) ->\n let (wy, wx) = (w * ry, w * rx)\n in ( wy,\n replicate (floor (wx - a)) ' '\n <> replicate (floor (wy - wx)) '█'\n )\n )\n 0\n xs\n\nintervalRatios :: [(Rational, Rational)] -> String\nintervalRatios =\n ('(' :) . (<> \")\")\n . intercalate \") (\"\n . fmap\n (uncurry ((<>) . (<> \", \")) . join bimap showRatio)\n\nshowRatio :: Rational -> String\nshowRatio = ((<>) . show . numerator) <*> (go . denominator)\n where\n go x\n | 1 /= x = '/' : show x\n | otherwise = []\n", "language": "Haskell" }, { "code": "100 PROGRAM \"Cantor.bas\"\n110 GRAPHICS HIRES 2\n120 SET PALETTE BLACK,WHITE\n130 CALL CANTOR(28,500,1216,32)\n140 DEF CANTOR(X,Y,L,HEIGHT)\n150 IF L>3 THEN\n160 PLOT X,Y;X+L,Y,X,Y+4;X+L,Y+4\n170 CALL CANTOR(X,Y-HEIGHT,L/3,HEIGHT)\n180 CALL CANTOR(X+2*L/3,Y-HEIGHT,L/3,HEIGHT)\n190 END IF\n200 END DEF\n", "language": "IS-BASIC" }, { "code": "odometer =: [: (4 $. $.) $&1\n\ncantor_dust =: monad define\n shape =. ,~ 3 ^ y\n a =. shape $ ' '\n i =. odometer shape\n < (}:\"1) 1j1 #\"1 '#' (([: <\"1 [: ;/\"1 (#~ 1 e.\"1 [: (,/\"2) 3 3&#:)) i)}a\n)\n", "language": "J" }, { "code": "cantor_dust =: 2&$: :(dyad define)\n shape =. x # 3 ^ y\n a =. shape $ ' '\n i =. odometer shape\n < (}:\"1) 1j1 #\"1 '#' (([: <\"1 [: ;/\"1 (#~ 1 e.\"1 [: (,/\"2) 3 3&#:)) i)} a\n)\n", "language": "J" }, { "code": "public class App {\n private static final int WIDTH = 81;\n private static final int HEIGHT = 5;\n\n private static char[][] lines;\n static {\n lines = new char[HEIGHT][WIDTH];\n for (int i = 0; i < HEIGHT; i++) {\n for (int j = 0; j < WIDTH; j++) {\n lines[i][j] = '*';\n }\n }\n }\n\n private static void cantor(int start, int len, int index) {\n int seg = len / 3;\n if (seg == 0) return;\n for (int i = index; i < HEIGHT; i++) {\n for (int j = start + seg; j < start + seg * 2; j++) {\n lines[i][j] = ' ';\n }\n }\n cantor(start, seg, index + 1);\n cantor(start + seg * 2, seg, index + 1);\n }\n\n public static void main(String[] args) {\n cantor(0, WIDTH, 1);\n for (int i = 0; i < HEIGHT; i++) {\n for (int j = 0; j < WIDTH; j++) {\n System.out.print(lines[i][j]);\n }\n System.out.println();\n }\n }\n}\n", "language": "Java" }, { "code": "(() => {\n \"use strict\";\n\n // -------------- CANTOR BOOL-INT PAIRS --------------\n\n // cantor :: [(Bool, Int)] -> [(Bool, Int)]\n const cantor = xs => {\n const go = ([bln, n]) =>\n bln && 1 < n ? (() => {\n const x = Math.floor(n / 3);\n\n return [\n [true, x],\n [false, x],\n [true, x]\n ];\n })() : [\n [bln, n]\n ];\n\n return xs.flatMap(go);\n };\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () =>\n cantorLines(5);\n\n\n // --------------------- DISPLAY ---------------------\n\n // cantorLines :: Int -> String\n const cantorLines = n =>\n take(n)(\n iterate(cantor)([\n [true, 3 ** (n - 1)]\n ])\n )\n .map(showCantor)\n .join(\"\\n\");\n\n\n // showCantor :: [(Bool, Int)] -> String\n const showCantor = xs =>\n xs.map(\n ([bln, n]) => (\n bln ? (\n \"*\"\n ) : \" \"\n ).repeat(n)\n )\n .join(\"\");\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // iterate :: (a -> a) -> a -> Gen [a]\n const iterate = f =>\n // An infinite list of repeated\n // applications of f to x.\n function* (x) {\n let v = x;\n\n while (true) {\n yield v;\n v = f(v);\n }\n };\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => \"GeneratorFunction\" !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat(...Array.from({\n length: n\n }, () => {\n const x = xs.next();\n\n return x.done ? [] : [x.value];\n }));\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "(() => {\n \"use strict\";\n\n // ----------------- CANTOR STRINGS ------------------\n\n // cantor :: [String] -> [String]\n const cantor = xs => {\n const go = s => {\n const\n m = Math.floor(s.length / 3),\n blocks = take(m)(s);\n\n return \"█\" === s[0] ? (\n [blocks, \" \".repeat(m), blocks]\n ) : [s];\n };\n\n return xs.flatMap(go);\n };\n\n // ---------------------- TEST -----------------------\n const main = () =>\n showCantor(5);\n\n\n // --------------------- DISPLAY ---------------------\n // showCantor :: Int -> String\n const showCantor = n =>\n take(n)(\n iterate(cantor)([\n \"█\".repeat(3 ** (n - 1))\n ])\n )\n .map(x => x.join(\"\"))\n .join(\"\\n\");\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // iterate :: (a -> a) -> a -> Gen [a]\n const iterate = f =>\n // An infinite list of repeated\n // applications of f to x.\n function* (x) {\n let v = x;\n\n while (true) {\n yield v;\n v = f(v);\n }\n };\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => \"GeneratorFunction\" !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat(...Array.from({\n length: n\n }, () => {\n const x = xs.next();\n\n return x.done ? [] : [x.value];\n }));\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "(() => {\n \"use strict\";\n\n // -------------- CANTOR RATIONAL PAIRS --------------\n\n // cantor :: [(Rational, Rational)] ->\n // [(Rational, Rational)]\n const cantor = xs => {\n const go = ab => {\n const [r1, r2] = Array.from(ab).map(rational);\n const third = ratioDiv(ratioMinus(r2)(r1))(3);\n\n return [\n Tuple(r1)(ratioPlus(r1)(third)),\n Tuple(ratioMinus(r2)(third))(r2)\n ];\n };\n\n return xs.flatMap(go);\n };\n\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () => {\n const\n xs = take(4)(\n iterate(cantor)([Tuple(0)(1)])\n );\n\n return [\n `${unlines(xs.map(intervalRatios))}\\n`,\n intervalBars(xs)\n ]\n .join(\"\\n\\n\");\n };\n\n\n // --------------------- DISPLAY ---------------------\n\n // intervalRatios :: [(Rational, Rational)] -> String\n const intervalRatios = xs => {\n const go = ab =>\n Array.from(ab).map(\n compose(showRatio, rational)\n )\n .join(\", \");\n\n return `(${xs.map(go).join(\") (\")})`;\n };\n\n // intervalBars :: [[(Rational, Rational)]] -> String\n const intervalBars = rs => {\n const go = w => xs =>\n snd(mapAccumL(\n a => ab => {\n const [wx, wy] = Array.from(ab).map(\n r => ratioMult(w)(\n rational(r)\n )\n );\n\n return Tuple(wy)(\n replicateString(\n floor(ratioMinus(wx)(a))\n )(\" \") + replicateString(\n floor(ratioMinus(wy)(wx))\n )(\"█\")\n );\n }\n )(0)(xs)).join(\"\");\n const d = maximum(\n last(rs).map(x => fst(x).d)\n );\n\n return unlines(rs.map(\n go(Ratio(d)(1))\n ));\n };\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // Ratio :: Integral a => a -> a -> Ratio a\n const Ratio = a => b => {\n const go = (x, y) =>\n 0 !== y ? (() => {\n const d = gcd(x)(y);\n\n return {\n type: \"Ratio\",\n // numerator\n \"n\": Math.trunc(x / d),\n // denominator\n \"d\": Math.trunc(y / d)\n };\n })() : undefined;\n\n return go(a * signum(b), abs(b));\n };\n\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a =>\n b => ({\n type: \"Tuple\",\n \"0\": a,\n \"1\": b,\n length: 2\n });\n\n\n // abs :: Num -> Num\n const abs =\n // Absolute value of a given number\n // without the sign.\n x => 0 > x ? (\n -x\n ) : x;\n\n\n // approxRatio :: Float -> Float -> Ratio\n const approxRatio = eps =>\n n => {\n const\n gcde = (e, x, y) => {\n const _gcd = (a, b) =>\n b < e ? (\n a\n ) : _gcd(b, a % b);\n\n return _gcd(Math.abs(x), Math.abs(y));\n },\n c = gcde(Boolean(eps) ? (\n eps\n ) : (1 / 10000), 1, n);\n\n return Ratio(\n Math.floor(n / c)\n )(\n Math.floor(1 / c)\n );\n };\n\n\n // floor :: Num -> Int\n const floor = x => {\n const\n nr = (\n \"Ratio\" !== x.type ? (\n properFraction\n ) : properFracRatio\n )(x),\n n = nr[0];\n\n return 0 > nr[1] ? n - 1 : n;\n };\n\n\n // fst :: (a, b) -> a\n const fst = ab =>\n // First member of a pair.\n ab[0];\n\n\n // gcd :: Integral a => a -> a -> a\n const gcd = x =>\n y => {\n const zero = x.constructor(0);\n const go = (a, b) =>\n zero === b ? (\n a\n ) : go(b, a % b);\n\n return go(abs(x), abs(y));\n };\n\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n // A function defined by the right-to-left\n // composition of all the functions in fs.\n fs.reduce(\n (f, g) => x => f(g(x)),\n x => x\n );\n\n\n // iterate :: (a -> a) -> a -> Gen [a]\n const iterate = f =>\n // An infinite list of repeated\n // applications of f to x.\n function* (x) {\n let v = x;\n\n while (true) {\n yield v;\n v = f(v);\n }\n };\n\n\n // last :: [a] -> a\n const last = xs =>\n // The last item of a list.\n 0 < xs.length ? (\n xs.slice(-1)[0]\n ) : null;\n\n\n // lcm :: Int -> Int -> Int\n const lcm = x =>\n // The smallest positive integer divisible\n // without remainder by both x and y.\n y => (x === 0 || y === 0) ? (\n 0\n ) : Math.abs(Math.floor(x / gcd(x)(y)) * y);\n\n\n // mapAccumL :: (acc -> x -> (acc, y)) ->\n // acc -> [x] -> (acc, [y])\n const mapAccumL = f =>\n // A tuple of an accumulation and a list\n // obtained by a combined map and fold,\n // with accumulation from left to right.\n acc => xs => [...xs].reduce(\n (a, x) => {\n const ab = f(a[0])(x);\n\n return [ab[0], a[1].concat(ab[1])];\n },\n [acc, []]\n );\n\n\n // maximum :: Ord a => [a] -> a\n const maximum = xs => (\n // The largest value in a non-empty list.\n ys => 0 < ys.length ? (\n ys.slice(1).reduce(\n (a, y) => y > a ? (\n y\n ) : a, ys[0]\n )\n ) : undefined\n )(xs);\n\n\n // properFracRatio :: Ratio -> (Int, Ratio)\n const properFracRatio = nd => {\n const [q, r] = Array.from(quotRem(nd.n)(nd.d));\n\n return Tuple(q)(Ratio(r)(nd.d));\n };\n\n\n // properFraction :: Real -> (Int, Real)\n const properFraction = n => {\n const i = Math.floor(n) + (n < 0 ? 1 : 0);\n\n return Tuple(i)(n - i);\n };\n\n\n // quotRem :: Integral a => a -> a -> (a, a)\n const quotRem = m =>\n // The quotient, tupled with the remainder.\n n => Tuple(\n Math.trunc(m / n)\n )(\n m % n\n );\n\n\n // ratioDiv :: Rational -> Rational -> Rational\n const ratioDiv = n1 => n2 => {\n const [r1, r2] = [n1, n2].map(rational);\n\n return Ratio(r1.n * r2.d)(\n r1.d * r2.n\n );\n };\n\n\n // ratioMinus :: Rational -> Rational -> Rational\n const ratioMinus = n1 => n2 => {\n const [r1, r2] = [n1, n2].map(rational);\n const d = lcm(r1.d)(r2.d);\n\n return Ratio(\n (r1.n * (d / r1.d)) - (r2.n * (d / r2.d))\n )(d);\n };\n\n\n // ratioMult :: Rational -> Rational -> Rational\n const ratioMult = n1 => n2 => {\n const [r1, r2] = [n1, n2].map(rational);\n\n return Ratio(r1.n * r2.n)(\n r1.d * r2.d\n );\n };\n\n\n // ratioPlus :: Rational -> Rational -> Rational\n const ratioPlus = n1 =>\n n2 => {\n const [r1, r2] = [n1, n2].map(rational);\n const d = lcm(r1.d)(r2.d);\n\n return Ratio(\n (r1.n * (d / r1.d)) + (\n r2.n * (d / r2.d)\n )\n )(d);\n };\n\n\n // rational :: Num a => a -> Rational\n const rational = x =>\n isNaN(x) ? x : Number.isInteger(x) ? (\n Ratio(x)(1)\n ) : approxRatio(undefined)(x);\n\n\n // replicateString :: Int -> String -> String\n const replicateString = n =>\n s => s.repeat(n);\n\n\n // showRatio :: Ratio -> String\n const showRatio = r =>\n \"Ratio\" !== r.type ? (\n r.toString()\n ) : r.n.toString() + (\n 1 !== r.d ? (\n `/${r.d}`\n ) : \"\"\n );\n\n\n // signum :: Num -> Num\n const signum = n =>\n // | Sign of a number.\n n.constructor(\n 0 > n ? (\n -1\n ) : (\n 0 < n ? 1 : 0\n )\n );\n\n\n // snd :: (a, b) -> b\n const snd = ab =>\n // Second member of a pair.\n ab[1];\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => \"GeneratorFunction\" !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat(...Array.from({\n length: n\n }, () => {\n const x = xs.next();\n\n return x.done ? [] : [x.value];\n }));\n\n\n // unlines :: [String] -> String\n const unlines = xs =>\n // A single string formed by the intercalation\n // of a list of strings with the newline character.\n xs.join(\"\\n\");\n\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "# cantor(width; height)\ndef cantor($w; $h):\n def init: [range(0; $h) | [range(0; $w) | \"*\"]];\n\n def cantor($start; $leng; $ix):\n ($leng/3|floor) as $seg\n | if $seg == 0 then .\n else reduce range($ix; $h) as $i (.;\n reduce range($start+$seg; $start + 2*$seg) as $j (.; .[$i][$j] = \" \"))\n | cantor($start; $seg; $ix+1)\n | cantor($start + 2*$seg; $seg; $ix+1)\n end ;\n init | cantor(0; $w; 1);\n\ndef pp: .[] | join(\"\");\n\ncantor($width; $height)\n| pp\n", "language": "Jq" }, { "code": "const width = 81\nconst height = 5\n\nfunction cantor!(lines, start, len, idx)\n seg = div(len, 3)\n if seg > 0\n for i in idx+1:height, j in start + seg + 1: start + seg * 2\n lines[i, j] = ' '\n end\n cantor!(lines, start, seg, idx + 1)\n cantor!(lines, start + 2 * seg, seg, idx + 1)\n end\nend\n\nlines = fill(UInt8('#'), height, width)\ncantor!(lines, 0, width, 1)\n\nfor i in 1:height, j in 1:width\n print(Char(lines[i, j]), j == width ? \"\\n\" : \"\")\nend\n", "language": "Julia" }, { "code": "// Version 1.2.31\n\nconst val WIDTH = 81\nconst val HEIGHT = 5\n\nval lines = List(HEIGHT) { CharArray(WIDTH) { '*' } }\n\nfun cantor(start: Int, len: Int, index: Int) {\n val seg = len / 3\n if (seg == 0) return\n for (i in index until HEIGHT) {\n for (j in start + seg until start + seg * 2) lines[i][j] = ' '\n }\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\n}\n\nfun main(args: Array<String>) {\n cantor(0, WIDTH, 1)\n lines.forEach { println(it) }\n}\n", "language": "Kotlin" }, { "code": "local WIDTH = 81\nlocal HEIGHT = 5\nlocal lines = {}\n\nfunction cantor(start, length, index)\n -- must be local, or only one side will get calculated\n local seg = math.floor(length / 3)\n if 0 == seg then\n return nil\n end\n\n -- remove elements that are not in the set\n for it=0, HEIGHT - index do\n i = index + it\n for jt=0, seg - 1 do\n j = start + seg + jt\n pos = WIDTH * i + j\n lines[pos] = ' '\n end\n end\n\n -- left side\n cantor(start, seg, index + 1)\n -- right side\n cantor(start + seg * 2, seg, index + 1)\n return nil\nend\n\n-- initialize the lines\nfor i=0, WIDTH * HEIGHT do\n lines[i] = '*'\nend\n\n-- calculate\ncantor(0, WIDTH, 1)\n\n-- print the result sets\nfor i=0, HEIGHT-1 do\n beg = WIDTH * i\n for j=beg, beg+WIDTH-1 do\n if j <= WIDTH * HEIGHT then\n io.write(lines[j])\n end\n end\n print()\nend\n", "language": "Lua" }, { "code": "Graphics[MeshPrimitives[CantorMesh[#],1]/.{x_}:>{x,-0.05#}&/@Range[5],ImageSize->600]\n", "language": "Mathematica" }, { "code": "cantorSet = function(start, length, depth)\n\tif depth == 0 then return [[start, start+length - 1]]\n\t\n\tnewLen = length / 3\n\t\n\tleftInterval = cantorSet(start, newLen, depth - 1)\n\trightInterval = cantorSet(start + 2 * newLen, newLen, depth - 1)\n\t\n\treturn leftInterval + rightInterval\nend function\n\nfor depth in range(0, 4)\n\toutput =[\" \"] * 81\n\tsegments = cantorSet(1, 81,depth)\n\tfor segment in segments\n\t\tfor x in range(segment[0] - 1, segment[1]-1)\n\t\t\toutput[x] = \"#\"\n\t\tend for\n\tend for\n\tprint output.join(\"\")\nend for\n", "language": "MiniScript" }, { "code": "MODULE Cantor;\nFROM Terminal IMPORT Write,WriteLn,ReadChar;\n\nCONST\n WIDTH = 81;\n HEIGHT = 5;\nVAR\n lines : ARRAY[0..HEIGHT] OF ARRAY[0..WIDTH] OF CHAR;\n\nPROCEDURE Init;\nVAR i,j : CARDINAL;\nBEGIN\n FOR i:=0 TO HEIGHT DO\n FOR j:=0 TO WIDTH DO\n lines[i,j] := '*'\n END\n END\nEND Init;\n\nPROCEDURE Cantor(start,len,index : CARDINAL);\nVAR i,j,seg : CARDINAL;\nBEGIN\n seg := len DIV 3;\n IF seg=0 THEN RETURN END;\n FOR i:=index TO HEIGHT-1 DO\n j := start+seg;\n FOR j:=start+seg TO start+seg*2-1 DO\n lines[i,j] := ' '\n END\n END;\n Cantor(start, seg, index+1);\n Cantor(start+seg*2, seg, index+1)\nEND Cantor;\n\nPROCEDURE Print;\nVAR i,j : CARDINAL;\nBEGIN\n FOR i:=0 TO HEIGHT-1 DO\n FOR j:=0 TO WIDTH-1 DO\n Write(lines[i,j])\n END;\n WriteLn\n END\nEND Print;\n\nBEGIN\n Init;\n Cantor(0,WIDTH,1);\n Print;\n\n ReadChar;\nEND Cantor.\n", "language": "Modula-2" }, { "code": "import strutils\n\nconst\n Width = 81\n Height = 5\n\nvar lines: array[Height, string]\nfor line in lines.mitems: line = repeat('*', Width)\n\nproc cantor(start, length, index: Natural) =\n let seg = length div 3\n if seg == 0: return\n for i in index..<Height:\n for j in (start + seg)..<(start + seg * 2):\n lines[i][j] = ' '\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\n\ncantor(0, Width, 1)\nfor line in lines:\n echo line\n", "language": "Nim" }, { "code": "class CantorSet {\n WIDTH : static : Int;\n HEIGHT : static : Int;\n lines : static : Char[,];\n\n function : Init() ~ Nil {\n WIDTH := 81;\n HEIGHT := 5;\n lines := Char->New[HEIGHT, WIDTH];\n\n each(i : HEIGHT) {\n each(j : WIDTH) {\n lines[i,j] := '*';\n };\n };\n }\n\n function : Cantor(start : Int, len : Int, index : Int) ~ Nil {\n seg : Int := len / 3;\n\n if(seg = 0) {\n return;\n };\n\n for(i := index; i < HEIGHT; i += 1;) {\n for(j := start + seg; j < start + seg * 2; j += 1;) {\n lines[i,j] := ' ';\n };\n };\n\n Cantor(start, seg, index + 1);\n Cantor(start + seg * 2, seg, index + 1);\n }\n\n function : Main(args : String[]) ~ Nil {\n Init();\n\n Cantor(0, WIDTH, 1);\n each(i : HEIGHT) {\n each(j : WIDTH) {\n lines[i,j]->Print();\n };\n \"\"->PrintLine();\n };\n }\n}\n", "language": "Objeck" }, { "code": "use strict;\nuse feature 'say';\n\nsub cantor {\n our($height) = @_;\n my $width = 3 ** ($height - 1);\n\n our @lines = ('#' x $width) x $height;\n\n sub trim_middle_third {\n my($len, $start, $index) = @_;\n my $seg = int $len / 3\n or return;\n\n for my $i ( $index .. $height - 1 ) {\n for my $j ( 0 .. $seg - 1 ) {\n substr $lines[$i], $start + $seg + $j, 1, ' ';\n }\n }\n\n trim_middle_third( $seg, $start + $_, $index + 1 ) for 0, $seg * 2;\n }\n\n trim_middle_third( $width, 0, 1 );\n @lines;\n}\n\nsay for cantor(5);\n", "language": "Perl" }, { "code": "#!/usr/bin/perl -l\n\nuse strict; # https://rosettacode.org/wiki/Cantor_set\nuse warnings;\n\n$_ = '#' x 81;\n\n1 while print, s/(#+)\\1\\1/ $1 . $1 =~ tr!#! !r . $1 /ge;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">w</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">len</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">w</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">line</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">'#'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">)&</span><span style=\"color: #008000;\">\"\\n\"</span>\n\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">len</span> <span style=\"color: #0000FF;\">/=</span> <span style=\"color: #000000;\">3</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">pos</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">pos</span><span style=\"color: #0000FF;\"><(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">pos</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">len</span>\n <span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">pos</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">pos</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">' '</span>\n <span style=\"color: #000000;\">pos</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">len</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n<!--\n", "language": "Phix" }, { "code": "include ..\\Utilitys.pmt\n\n5 >ps\n3 tps 1 - power var w\n\"#\" 1 get nip w repeat var line\n\nps> for\n 3 swap 1 - power\n w over / int var step\n true >ps\n for var j\n \ttps not if\n step for var k\n \tline 32 j 1 - step * k + set var line\n endfor\n endif\n ps> not >ps\n endfor\n cps\n line ?\nendfor\n", "language": "Phixmonti" }, { "code": "include ..\\Utilitys.pmt\n\n5 >ps\n3 tps 1 - power var w\n\"#\" 1 get nip w repeat var line\n\n( 2 ps> ) for\n line ?\n 3 swap 1 - power\n w over / int var step\n 2 swap 2 3 tolist for var j\n step for var k\n line 32 j 1 - step * k + set var line\n endfor\n endfor\nendfor\nline ?\n", "language": "Phixmonti" }, { "code": "100H: /* DRAW A CANTOR SET USING ASCII */\n\n /* BDOS SYSTEM CALL AND I/O ROUTINES */\n BDOS: PROCEDURE( F, A ); DECLARE F BYTE, A ADDRESS; GOTO 5; END;\n PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;\n PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;\n\n /* DRAW A CANTOR SET */\n\n DECLARE LINES LITERALLY '4';\n DECLARE WIDTH LITERALLY '27'; /* MUST BE 3**(LINES-1) */\n\n DECLARE LINE (WIDTH)BYTE;\n DECLARE ( I, L, C, W, S, SEGMENTS ) BYTE;\n\n DO I = 0 TO LAST( LINE );\n LINE( I ) = 023H;\n CALL PR$CHAR( LINE( I ) );\n END;\n CALL PR$NL;\n W = WIDTH;\n SEGMENTS = 1;\n DO L = 2 TO LINES;\n W = W / 3;\n SEGMENTS = SEGMENTS * 3;\n C = 0;\n DO S = 1 TO SEGMENTS;\n DO I = 1 TO W;\n IF NOT S THEN LINE( C ) = ' '; /* EVEN SEGMENT - BLANK IT */\n CALL PR$CHAR( LINE( C ) );\n C = C + 1;\n END;\n END;\n CALL PR$NL;\n END;\n\nEOF\n", "language": "PL-M" }, { "code": "//Aamrun, 1st July 2022\n\nvoid cantorSet(int x1,int y1,int x2,int y2,int strWt,int gap,int n){\n strokeWeight(strWt);\n line(x1,y1,x2,y2);\n if(n>0){\n cantorSet(x1,gap + y1,(2*x1+x2)/3,gap + (2*y1+y2)/3,strWt,gap,n-1);\n cantorSet((2*x2+x1)/3,gap + (2*y2+y1)/3,x2,gap + y2,strWt,gap,n-1);\n }\n}\n\nvoid setup(){\n size(1000,1000);\n cantorSet(100,10,900,10,1,10,5);\n}\n", "language": "Processing" }, { "code": "WIDTH = 81\nHEIGHT = 5\n\nlines=[]\ndef cantor(start, len, index):\n seg = len / 3\n if seg == 0:\n return None\n for it in xrange(HEIGHT-index):\n i = index + it\n for jt in xrange(seg):\n j = start + seg + jt\n pos = i * WIDTH + j\n lines[pos] = ' '\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\n return None\n\nlines = ['*'] * (WIDTH*HEIGHT)\ncantor(0, WIDTH, 1)\n\nfor i in xrange(HEIGHT):\n beg = WIDTH * i\n print ''.join(lines[beg : beg+WIDTH])\n", "language": "Python" }, { "code": "'''Cantor set – separating model from display'''\n\nfrom functools import (reduce)\nimport itertools\n\n\n# cantor :: [(Bool, Int)] -> [(Bool, Int)]\ndef cantor(xs):\n '''A Cantor segmentation step.'''\n def go(tpl):\n (bln, n) = tpl\n m = n // 3\n return [\n (True, m), (False, m), (True, m)\n ] if bln and (1 < n) else [tpl]\n return concatMap(go)(xs)\n\n\n# cantorLines :: Int -> String\ndef cantorLines(n):\n '''A text block display of n\n Cantor-segmented lines.\n '''\n m = n - 1\n repeat = itertools.repeat\n return '\\n'.join(\n [showCantor(x) for x in (\n reduce(\n lambda a, f: a + [f(a[-1])],\n repeat(cantor, m),\n [[(True, 3 ** m)]]\n )\n )]\n )\n\n\n# showCantor :: [(Bool, Int)] -> String\ndef showCantor(xs):\n '''A text block display of a list of\n Cantor line segments.\n '''\n return ''.join(\n concatMap(lambda tpl: tpl[1] * ('█' if tpl[0] else ' '))(\n xs\n )\n )\n\n\n# main :: IO ()\ndef main():\n '''Testing to depth 5'''\n\n print(\n cantorLines(5)\n )\n\n\n# GENERIC -------------------------------------------------------------\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been mapped.\n The list monad can be derived by using a function f which\n wraps its output in a list,\n (using an empty list to represent computational failure).'''\n chain = itertools.chain\n return lambda xs: list(\n chain.from_iterable(map(f, xs))\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "'''Cantor set – strings as both model and display.'''\n\nfrom itertools import (chain, islice)\n\n\n# cantorLines :: Int -> String\ndef cantorLines(n):\n '''N levels of cantor segmentation,\n obtained and displayed in the\n form of lines of block characters.\n '''\n return '\\n'.join(\n [''.join(x) for x in islice(\n iterate(cantor)(\n [3 ** (n - 1) * '█']\n ), n\n )]\n )\n\n\n# cantor :: [String] -> [String]\ndef cantor(xs):\n '''A cantor line derived from its predecessor.'''\n def go(s):\n m = len(s) // 3\n blocks = s[0:m]\n return [\n blocks, m * ' ', blocks\n ] if '█' == s[0] else [s]\n return concatMap(go)(xs)\n\n\n# MAIN ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Testing cantor line generation to level 5'''\n\n print(\n cantorLines(5)\n )\n\n# GENERIC -------------------------------------------------\n\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been mapped.\n The list monad can be derived by using a function f which\n wraps its output in a list,\n (using an empty list to represent computational failure).'''\n return lambda xs: list(\n chain.from_iterable(map(f, xs))\n )\n\n\n# iterate :: (a -> a) -> a -> Gen [a]\ndef iterate(f):\n '''An infinite list of repeated\n applications of f to x.\n '''\n def go(x):\n v = x\n while True:\n yield v\n v = f(v)\n return lambda x: go(x)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "'''A Cantor set generator, and two different\n representations of its output.\n'''\n\nfrom itertools import (islice, chain)\nfrom fractions import Fraction\nfrom functools import (reduce)\n\n\n# ----------------------- CANTOR SET -----------------------\n\n# cantor :: Generator [[(Fraction, Fraction)]]\ndef cantor():\n '''A non-finite stream of successive Cantor\n partitions of the line, in the form of\n lists of fraction pairs.\n '''\n def go(xy):\n (x, y) = xy\n third = Fraction(y - x, 3)\n return [(x, x + third), (y - third, y)]\n\n return iterate(\n concatMap(go)\n )(\n [(0, 1)]\n )\n\n\n# fractionLists :: [(Fraction, Fraction)] -> String\ndef fractionLists(xs):\n '''A fraction pair representation of a\n Cantor-partitioned line.\n '''\n def go(xy):\n return ', '.join(map(showRatio, xy))\n return ' '.join('(' + go(x) + ')' for x in xs)\n\n\n# intervalBars :: [(Fraction, Fraction)] -> String\ndef intervalBars(w):\n '''A block diagram representation of a\n Cantor-partitioned line.\n '''\n def go(xs):\n def show(a, tpl):\n [x, y] = [int(w * r) for r in tpl]\n return (\n y,\n (' ' * (x - a)) + ('█' * (y - x))\n )\n return mapAccumL(show)(0)(xs)\n return lambda xs: ''.join(go(xs)[1])\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Testing the generation of successive\n Cantor subdivisions of the line, and\n displaying them both as lines of fraction\n pairs and as graphic interval bars.\n '''\n xs = list(islice(cantor(), 4))\n w = max(xy[1].denominator for xy in xs[-1])\n print(\n '\\n'.join(map(fractionLists, xs)),\n '\\n'\n )\n print(\n '\\n'.join(map(intervalBars(w), xs))\n )\n\n\n# ------------------------ GENERIC -------------------------\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been mapped.\n The list monad can be derived by using a function f which\n wraps its output in a list,\n (using an empty list to represent computational failure).'''\n return lambda xs: list(\n chain.from_iterable(map(f, xs))\n )\n\n\n# iterate :: (a -> a) -> a -> Gen [a]\ndef iterate(f):\n '''An infinite list of repeated\n applications of f to x.\n '''\n def go(x):\n v = x\n while True:\n yield v\n v = f(v)\n return go\n\n\n# mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\ndef mapAccumL(f):\n '''A tuple of an accumulation and a list derived by a\n combined map and fold,\n with accumulation from left to right.\n '''\n def go(a, x):\n tpl = f(a[0], x)\n return (tpl[0], a[1] + [tpl[1]])\n return lambda acc: lambda xs: (\n reduce(go, xs, (acc, []))\n )\n\n\n# showRatio :: Ratio -> String\ndef showRatio(r):\n '''String representation of the ratio r.'''\n d = r.denominator\n return str(r.numerator) + (\n '/' + str(d) if 1 != d else ''\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "_Title \"Cantor Set\"\n\nDim Shared As Integer sw, sh, wide, high\nsw = 800: sh = 200: wide = 729: high = 7\nDim Shared As Integer a(wide, high)\n\nScreen _NewImage(sw, sh, 8)\nCls , 15: Color 0\n\nCall calc(0, wide, 1)\nCall CantorSet\n\nSleep\nSystem\n\nSub calc (start As Integer, length As Integer, index As Integer)\n Dim As Integer i, j, newLength\n newLength = length \\ 3\n If newLength = 0 Then Exit Sub\n For j = index To high - 1\n For i = start + newLength To start + newLength * 2 - 1\n a(i, j) = 1\n Next\n Next\n Call calc(start, newLength, index + 1)\n Call calc(start + newLength * 2, newLength, index + 1)\nEnd Sub\n\nSub CantorSet\n Dim As Integer i, j, x, y\n For y = 0 To high - 1\n j = y + 1\n For x = 0 To wide - 1\n i = x + 34\n If a(x, y) = 0 Then Line (i, j * 24 - 5)-(i, j * 24 + 17)\n Next\n Next\nEnd Sub\n", "language": "QB64" }, { "code": "SUB Cantor\n FOR i = 0 TO alto - 1\n FOR j = 0 TO ancho - 1\n intervalo$(i, j) = CHR$(254) '\"#\"\n NEXT j\n NEXT i\nEND SUB\n\nSUB ConjCantor (inicio, longitud, indice)\n segmento = INT(longitud / 3)\n IF segmento = 0 THEN EXIT SUB\n FOR i = indice TO alto - 1\n FOR j = inicio + segmento TO inicio + segmento * 2 - 1\n intervalo$(i, j) = CHR$(32) '\" \"\n NEXT j\n NEXT i\n CALL ConjCantor(inicio, segmento, indice + 1)\n CALL ConjCantor(inicio + segmento * 2, segmento, indice + 1)\nEND SUB\n\nCONST ancho = 81\nCONST alto = 5\nDIM SHARED intervalo$(alto, ancho)\n\nCLS\nCALL Cantor\nCALL ConjCantor(0, ancho, 1)\nFOR i = 0 TO alto - 1\n FOR j = 0 TO ancho - 1\n PRINT intervalo$(i, j);\n NEXT j\n PRINT\nNEXT i\nEND\n", "language": "QBasic" }, { "code": " [ $ \"\" swap witheach\n [ nested quackery join ] ] is expand ( $ --> $ )\n\n [ $ \"ABA\" ] is A ( $ --> $ )\n\n [ $ \"BBB\" ] is B ( $ --> $ )\n\n [ char A = iff\n [ char q ] else space\n swap of echo$ ] is draw ( n c --> $ )\n\n 81 $ \"A\"\n 5 times\n [ dup witheach\n [ dip over draw ]\n cr\n i if\n [ expand\n dip [ 3 / ] ] ]\n 2drop\n", "language": "Quackery" }, { "code": "cantorSet <- function() {\n depth <- 6L\n cs <- vector('list', depth)\n cs[[1L]] <- c(0, 1)\n for(k in seq_len(depth)) {\n cs[[k + 1L]] <- unlist(sapply(seq_len(length(cs[[k]]) / 2L), function(j) {\n p <- cs[[k]][2L] / 3\n h <- 2L * (j - 1L)\n c(\n cs[[k]][h + 1L] + c(0, p),\n cs[[k]][h + 2L] - c(p, 0)\n )\n }, simplify = FALSE))\n }\n cs\n}\n\ncantorSetGraph <- function() {\n cs <- cantorSet()\n\n u <- unlist(cs)\n\n df <- data.frame(\n x_start = u[seq_along(u) %% 2L == 1L],\n x_end = u[seq_along(u) %% 2L == 0L],\n depth = unlist(lapply(cs, function(e) {\n l <- length(e)\n n <- 0\n while(l > 1) {\n n <- n + 1L\n l <- l / 2\n }\n rep(n, length(e) / 2)\n }))\n )\n\n require(ggplot2)\n g <- ggplot(df, aes_string(x = 'x_start', y = 'depth')) +\n geom_segment(aes_string(xend = 'x_end', yend = 'depth', size = 3)) +\n scale_y_continuous(trans = \"reverse\") +\n theme(\n axis.title = element_blank(),\n axis.line = element_blank(),\n axis.text = element_blank(),\n axis.ticks = element_blank(),\n legend.position = 'none',\n aspect.ratio = 1/5\n )\n\n list(graph = g, data = df, set = cs)\n}\n", "language": "R" }, { "code": "#lang racket/base\n;; {trans|Kotlin}}\n\n(define current-width (make-parameter 81))\n\n(define current-height (make-parameter 5))\n\n(define (Cantor_set (w (current-width)) (h (current-height)))\n (define lines (build-list h (λ (_) (make-bytes w (char->integer #\\#)))))\n (define (cantor start len index)\n (let* ((seg (quotient len 3))\n (seg-start (+ start seg))\n (seg-end (+ seg-start seg)))\n (unless (zero? seg)\n (for* ((i (in-range index h))\n (j (in-range seg-start seg-end)))\n (bytes-set! (list-ref lines i) j (char->integer #\\space)))\n (cantor start seg (add1 index))\n (cantor seg-end seg (add1 index)))))\n (cantor 0 w 1)\n lines)\n\n(module+ main\n (for-each displayln (Cantor_set)))\n", "language": "Racket" }, { "code": "sub cantor ( Int $height ) {\n my $width = 3 ** ($height - 1);\n\n my @lines = ( \"\\c[FULL BLOCK]\" x $width ) xx $height;\n\n my sub _trim_middle_third ( $len, $start, $index ) {\n my $seg = $len div 3\n or return;\n\n for ( $index ..^ $height ) X ( 0 ..^ $seg ) -> ( $i, $j ) {\n @lines[$i].substr-rw( $start + $seg + $j, 1 ) = ' ';\n }\n\n _trim_middle_third( $seg, $start + $_, $index + 1 ) for 0, $seg * 2;\n }\n\n _trim_middle_third( $width, 0, 1 );\n return @lines;\n}\n\n.say for cantor(5);\n", "language": "Raku" }, { "code": "/*REXX program displays an ASCII diagram of a Canter Set as a set of (character) lines. */\nw= linesize() /*obtain the width of the display term.*/\nif w==0 then w= 81 /*Can't obtain width? Use the default.*/\n do lines=0; _ = 3 ** lines /*calculate powers of three (# lines).*/\n if _>w then leave /*Too large? We passed the max value. */\n #=_ /*this value of a width─of─line is OK. */\n end /*lines*/ /* [↑] calculate a useable line width.*/\nw= # /*use the (last) useable line width. */\n$= copies('■', #) /*populate the display line with blocks*/\n do j=0 until #==0 /*show Cantor set as a line of chars. */\n if j>0 then do k=#+1 by #+# to w /*skip 1st line blanking*/\n $= overlay( left('', #), $, k) /*blank parts of a line.*/\n end /*j*/\n say $ /*display a line of the Cantor Set. */\n #= # % 3 /*the part (thirds) to be blanked out. */\n end /*j*/ /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "# Project : Cantor set\n\nload \"guilib.ring\"\npaint = null\n\nnew qapp\n {\n win1 = new qwidget() {\n setwindowtitle(\"\")\n setgeometry(100,100,800,600)\n label1 = new qlabel(win1) {\n setgeometry(10,10,800,600)\n settext(\"\")\n }\n new qpushbutton(win1) {\n setgeometry(150,500,100,30)\n settext(\"draw\")\n setclickevent(\"draw()\")\n }\n show()\n }\n exec()\n }\n\nfunc draw\n p1 = new qpicture()\n color = new qcolor() {\n setrgb(0,0,255,255)\n }\n pen = new qpen() {\n setcolor(color)\n setwidth(10)\n }\n paint = new qpainter() {\n begin(p1)\n setpen(pen)\n\n cantor(10,20,600)\n\n endpaint()\n }\n label1 { setpicture(p1) show() }\n return\n\nfunc cantor(x,y,lens)\n if lens >= 10\n paint.drawline(x,y,x+lens,y)\n y = y + 20\n cantor(x,y,floor(lens/3))\n cantor(x+floor(lens*2/3),y,floor(lens/3))\n ok\n", "language": "Ring" }, { "code": "lines = 5\n\n(0..lines).each do |exp|\n seg_size = 3**(lines-exp-1)\n chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? \" \" : \"█\"}\n puts chars.map{ |c| c * seg_size }.join\nend\n", "language": "Ruby" }, { "code": "use convert_base::Convert;\nuse std::fmt;\n\nstruct CantorSet {\n cells: Vec<Vec<bool>>,\n}\nfn number_to_vec(n: usize) -> Vec<u32> {\n // for the conversion we need the digits in reverse order\n // i.e the least significant digit in the first element of the vector\n n.to_string()\n .chars()\n .rev()\n .map(|c| c.to_digit(10).unwrap())\n .collect()\n}\n\nimpl CantorSet {\n fn new(lines: usize) -> CantorSet {\n // Convert from base 10- to base 3\n let mut base = Convert::new(10, 3);\n let mut cells: Vec<Vec<bool>> = vec![];\n\n for line in 0..lines {\n // calculate how many repeating sequence will be in the given line\n let segment_size = 3_usize.pow((lines - line - 1) as u32);\n let segment: Vec<bool> = (0..3_usize.pow(line as u32))\n .map(|n| {\n let output = base.convert::<u32, u32>(&number_to_vec(n));\n // return false in case the base 3 number contains at least one \"1\"\n // otherwise return true\n !output.contains(&1)\n })\n .collect();\n\n // copy the segment \"segment_size\" time\n let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size);\n for c in segment.iter() {\n accum.extend(std::iter::repeat(*c).take(segment_size))\n }\n\n cells.push(accum);\n }\n\n CantorSet { cells }\n }\n}\n\nimpl fmt::Display for CantorSet {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n for line in self.cells.iter() {\n for c in line {\n write!(f, \"{}\", if *c { \"█\" } else { \" \" })?\n }\n writeln!(f)?;\n }\n\n Ok(())\n }\n}\nfn main() {\n let cs = CantorSet::new(5);\n println!(\"Cantor set:\");\n println!(\"{}\", cs);\n}\n", "language": "Rust" }, { "code": "object CantorSetQD extends App {\n val (width, height) = (81, 5)\n\n val lines = Seq.fill[Array[Char]](height)(Array.fill[Char](width)('*'))\n\n def cantor(start: Int, len: Int, index: Int) {\n val seg = len / 3\n\n println(start, len, index)\n\n if (seg != 0) {\n for (i <- index until height;\n j <- (start + seg) until (start + seg * 2)) lines(i)(j) = ' '\n\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\n }\n }\n\n cantor(0, width, 1)\n lines.foreach(l => println(l.mkString))\n}\n", "language": "Scala" }, { "code": "object CantorSetFP extends App {\n val (width, height) = (81, 5)\n\n def lines = (1 to height).map(_ => (0 until width).toSet)\n\n def cantorSet(pre: Seq[Set[Int]], start: Int, len: Int, index: Int): Seq[Set[Int]] = {\n val seg = len / 3\n\n def cantorSet1(pre: Seq[Set[Int]], start: Int, index: Int): Seq[Set[Int]] = {\n def elementsStuffing(pre: Set[Int], start: Int): Set[Int] =\n pre -- ((start + seg) until (start + seg * 2))\n\n for (n <- 0 until height)\n yield if (index to height contains n) elementsStuffing(pre(n), start)\n else pre(n)\n }\n\n if (seg == 0) pre\n else {\n def version0 = cantorSet1(pre, start, index)\n def version1 = cantorSet(cantorSet1(pre, start, index), start, seg, index + 1)\n\n cantorSet(version1, start + seg * 2, seg, index + 1)\n }\n }\n\n def output: Seq[Set[Int]] = cantorSet(lines, 0, width, 1)\n\n println(\n output.map(l => (0 to width).map(pos => if (l contains pos) '*' else ' ').mkString)\n .mkString(\"\\n\"))\n}\n", "language": "Scala" }, { "code": "func cantor (height) {\n var width = 3**(height - 1)\n var lines = height.of { \"\\N{FULL BLOCK}\" * width }\n\n func trim_middle_third (len, start, index) {\n var seg = (len // 3) || return()\n\n for i, j in ((index ..^ height) ~X (0 ..^ seg)) {\n lines[i].replace!(Regex(\"^.{#{start + seg + j}}\\\\K.\"), ' ')\n }\n\n [0, 2*seg].each { |k|\n trim_middle_third(seg, start + k, index + 1)\n }\n }\n\n trim_middle_third(width, 0, 1)\n return lines\n}\n\ncantor(5).each { .say }\n", "language": "Sidef" }, { "code": "Object subclass: CantorSet [\n\n | intervals |\n\n CantorSet class >> new\n [^self basicNew\n initialize;\n yourself]\n\n initialize\n [intervals := Array with: (CantorInterval\n from: 0\n to: 1)]\n\n split\n [intervals := intervals gather: [:each | each split]]\n\n displayOn: aStream atScale: aNumber\n [| current |\n current := 0.\n intervals do:\n [:each |\n (each start - current) * aNumber timesRepeat: [aStream space].\n each length * aNumber timesRepeat: [aStream nextPut: $#].\n current := each stop].\n aStream nl]\n]\n\nInterval subclass: CantorInterval [\n\n split\n [| oneThird left right |\n oneThird := self length / 3.\n left := self class\n from: start\n to: start + oneThird.\n right := self class\n from: stop - oneThird\n to: stop.\n ^Array\n with: left\n with: right]\n\n start [^start]\n stop [^stop]\n length [^stop - start]\n\n printOn: aStream\n [aStream << ('%1[%2,%3]' % {self class name. start. stop})]\n]\n\nObject subclass: TestCantor [\n\n TestCantor class >> iterations: anInteger\n [| cantorset scale count |\n scale := 3 raisedTo: anInteger. \"Make smallest interval 1\"\n count := 0.\n cantorset := CantorSet new.\n\n [cantorset\n displayOn: Transcript\n atScale: scale.\n count < anInteger] whileTrue:\n [cantorset split.\n count := count + 1]]\n]\n\nTestCantor iterations: 4.\n", "language": "Smalltalk" }, { "code": "LET ancho = 81\nLET alto = 5\nDIM intervalo$(0,0)\nMAT REDIM intervalo$(0 TO alto, 0 TO ancho)\n\nSUB cantor\n FOR i = 0 TO alto-1\n FOR j = 0 TO ancho-1\n LET intervalo$(i, j) = \"#\" !CHR$(254)\n NEXT j\n NEXT i\nEND SUB\n\nSUB conjcantor (inicio,longitud,indice)\n LET segmento = INT(longitud/3)\n IF segmento = 0 THEN EXIT SUB\n FOR i = indice TO alto-1\n FOR j = inicio+segmento TO inicio+segmento*2-1\n LET intervalo$(i, j) = CHR$(32) !\" \"\n NEXT j\n NEXT i\n CALL conjcantor (inicio, segmento, indice+1)\n CALL conjcantor (inicio+segmento*2, segmento, indice+1)\nEND SUB\n\nCALL cantor\nCALL conjcantor (0, ancho, 1)\nFOR i = 0 TO alto-1\n FOR j = 0 TO ancho-1\n PRINT intervalo$(i, j);\n NEXT j\n PRINT\nNEXT i\nEND\n", "language": "True-BASIC" }, { "code": "const (\n width = 81\n height = 5\n)\n\nfn cantor(mut lines [][]u8, start int, len int, index int) {\n seg := len / 3\n if seg == 0 {\n return\n }\n for i in index.. height {\n for j in start + seg..start + 2 * seg {\n lines[i][j] = ' '[0]\n }\n }\n cantor(mut lines, start, seg, index + 1)\n cantor(mut lines, start + seg * 2, seg, index + 1)\n}\n\nfn main() {\n\tmut lines := [][]u8{len:height, init: []u8{len:width, init:'*'[0]}}\n cantor(mut lines, 0, width, 1)\n for line in lines {\n println(line.bytestr())\n }\n}\n", "language": "V-(Vlang)" }, { "code": "Module Module1\n\n Const WIDTH = 81\n Const HEIGHT = 5\n Dim lines(HEIGHT, WIDTH) As Char\n\n Sub Init()\n For i = 0 To HEIGHT - 1\n For j = 0 To WIDTH - 1\n lines(i, j) = \"*\"\n Next\n Next\n End Sub\n\n Sub Cantor(start As Integer, len As Integer, index As Integer)\n Dim seg As Integer = len / 3\n If seg = 0 Then\n Return\n End If\n For i = index To HEIGHT - 1\n For j = start + seg To start + seg * 2 - 1\n lines(i, j) = \" \"\n Next\n Next\n Cantor(start, seg, index + 1)\n Cantor(start + seg * 2, seg, index + 1)\n End Sub\n\n Sub Main()\n Init()\n Cantor(0, WIDTH, 1)\n For i = 0 To HEIGHT - 1\n For j = 0 To WIDTH - 1\n Console.Write(lines(i, j))\n Next\n Console.WriteLine()\n Next\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "1010 L=4\n1020 I=1\n1030 X=1\n1040 I=I+1\n1050 X=X*3\n1060 #=I<L*1040\n2010 I=0\n2020 :I)=35\n2030 $=:I)\n2040 I=I+1\n2050 #=I<X*2020\n2060 ?=\"\"\n2070 W=X\n2080 G=1\n2090 W=W/3\n2100 G=G*3\n2110 S=1\n2120 C=0\n2130 I=1\n2140 #=S/2*0+%=1*2160\n2150 :C)=32\n2160 $=:C)\n2170 C=C+1\n2180 I=I+1\n2190 #=W>I*2140\n2200 S=S+1\n2210 #=C<X*2130\n2220 ?=\"\"\n2230 L=L-1\n2240 #=1<L*2090\n", "language": "VTL-2" }, { "code": "var width = 81\nvar height = 5\n\nvar lines = [[]] * height\nfor (i in 0...height) lines[i] = [\"*\"] * width\n\nvar cantor // recursive so need to declare variable first\ncantor = Fn.new { |start, len, index|\n var seg = (len/3).floor\n if (seg == 0) return\n for (i in index...height) {\n for (j in (start+seg)...(start+seg*2)) lines[i][j] = \" \"\n }\n cantor.call(start, seg, index + 1)\n cantor.call(start + seg*2, seg, index + 1)\n}\n\ncantor.call(0, width, 1)\nfor (i in 0...height) System.print(lines[i].join())\n", "language": "Wren" }, { "code": "proc Cantor(N, LineSeg, Len); \\Delete middle third of LineSeg\nint N; char LineSeg; int Len, Third, I;\n[if N>0 and Len>1 then\n [Third:= Len/3;\n for I:= Third, 2*Third-1 do LineSeg(I):= ^ ;\n Cantor(N-1, LineSeg, Third);\n Cantor(N-1, LineSeg+2*Third, Third);\n ];\n];\n\nchar LineSeg, N;\n[LineSeg:=\n\"#################################################################################\n\";\nfor N:= 0 to 4 do\n [Cantor(N, LineSeg, 81);\n Text(0, LineSeg);\n ];\n]\n", "language": "XPL0" }, { "code": "ancho = 81\nalto = 5\ndim intervalo$(alto, ancho)\n\nCantor()\nConjCantor(0, ancho, 1)\nfor i = 0 to alto - 1\n for j = 0 to ancho - 1\n print intervalo$(i, j);\n next j\n print\nnext i\nend\n\nsub Cantor()\n for i = 0 to alto - 1\n for j = 0 to ancho - 1\n intervalo$(i, j) = chr$(254) //\"#\"\n next j\n next i\nend sub\n\nsub ConjCantor(inicio, longitud, indice)\n segmento = longitud / 3\n if segmento = 0 return\n for i = indice to alto - 1\n for j = inicio + segmento to inicio + segmento * 2 - 1\n intervalo$(i, j) = \" \"\n next j\n next i\n ConjCantor(inicio, segmento, indice + 1)\n ConjCantor(inicio + segmento * 2, segmento, indice + 1)\nend sub\n", "language": "Yabasic" }, { "code": "const WIDTH=81, HEIGHT=5;\nvar lines=HEIGHT.pump(List,List.createLong(WIDTH,\"\\U2588;\").copy); // full block\n\nfcn cantor(start,len,index){\n (seg:=len/3) or return();\n foreach i,j in ([index..HEIGHT-1], [start + seg .. start + seg*2 - 1]){\n lines[i][j]=\" \";\n }\n cantor(start, seg, index + 1);\n cantor(start + seg*2, seg, index + 1);\n}(0,WIDTH,1);\n\nlines.pump(Console.println,\"concat\");\n", "language": "Zkl" } ]
Cantor-set
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists\n", "language": "00-META" }, { "code": ";Task:\nShow one or more idiomatic ways of generating the [[wp:Cartesian_product|Cartesian product]] of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n::{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\n\nand, in contrast:\n::{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\n\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n:: {1, 2} × {} = {}\n:: {} × {1, 2} = {}\n\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your [[wp:Cartesian_product#Finite_n-ary_product|n-ary Cartesian product]] function to show the following products:\n:: {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}\n:: {1, 2, 3} × {30} × {500, 100}\n:: {1, 2, 3} × {} × {500, 100}\n\n<br>\n", "language": "00-TASK" }, { "code": "F cart_prod(a, b)\n V p = [(0, 0)] * (a.len * b.len)\n V i = 0\n L(aa) a\n L(bb) b\n p[i++] = (aa, bb)\n R p\n\nprint(cart_prod([1, 2], [3, 4]))\nprint(cart_prod([3, 4], [1, 2]))\n[Int] empty_array\nprint(cart_prod([1, 2], empty_array))\nprint(cart_prod(empty_array, [1, 2]))\n", "language": "11l" }, { "code": "F cart_prod(a, b)\n R multiloop(a, b, (aa, bb) -> (aa, bb))\n", "language": "11l" }, { "code": "DEFINE MAX_COUNT=\"10\"\nDEFINE MAX_RESULT=\"100\"\n\nDEFINE PTR=\"CARD\"\n\nPROC PrintInput(PTR ARRAY a INT count)\n INT i,j,n\n INT ARRAY tmp\n\n FOR i=0 TO count-1\n DO\n tmp=a(i) n=tmp(0)\n Put('[)\n FOR j=1 TO n\n DO\n PrintI(tmp(j))\n IF j<n THEN Put(',) FI\n OD\n Put('])\n IF i<count-1 THEN Put('x) FI\n OD\nRETURN\n\nPROC PrintOutput(INT ARRAY a INT groups,count)\n INT i,j,k\n\n Put('[)\n k=0\n FOR i=0 TO groups-1\n DO\n Put('()\n FOR j=0 TO count-1\n DO\n PrintI(a(k)) k==+1\n IF j<count-1 THEN Put(',) FI\n OD\n Put('))\n IF i<groups-1 THEN Put(',) FI\n OD\n Put('])\nRETURN\n\nPROC Product(PTR ARRAY a INT count\n INT ARRAY r INT POINTER groups)\n INT ARRAY ind(MAX_COUNT),tmp\n INT i,j,k\n\n IF count>MAX_COUNT THEN Break() FI\n groups^=1\n FOR i=0 TO count-1\n DO\n ind(i)=1 tmp=a(i)\n groups^==*tmp(0)\n OD\n IF groups^=0 THEN RETURN FI\n\n j=count-1 k=0\n DO\n FOR i=0 TO count-1\n DO\n tmp=a(i)\n r(k)=tmp(ind(i)) k==+1\n OD\n\n DO\n tmp=a(j)\n IF ind(j)<tmp(0) THEN\n ind(j)==+1\n FOR i=j+1 TO count-1\n DO\n ind(i)=1\n OD\n j=count-1\n EXIT\n ELSE\n IF j=0 THEN RETURN FI\n j==-1\n FI\n OD\n OD\nRETURN\n\nPROC Test(PTR ARRAY a INT count)\n INT ARRAY r(MAX_RESULT)\n INT groups\n\n IF count<2 THEN Break() FI\n Product(a,count,r,@groups)\n PrintInput(a,count)\n Put('=)\n PrintOutput(r,groups,count)\n PutE()\nRETURN\n\nPROC Main()\n INT ARRAY\n a1=[2 1 2],a2=[2 3 4],a3=[0],\n a4=[2 1776 1789],a5=[2 7 12],\n a6=[3 4 14 23],a7=[2 0 1],\n a8=[3 1 2 3],a9=[1 30],a10=[2 500 100]\n PTR ARRAY a(4)\n\n a(0)=a1 a(1)=a2 Test(a,2)\n a(0)=a2 a(1)=a1 Test(a,2)\n a(0)=a1 a(1)=a3 Test(a,2)\n a(0)=a3 a(1)=a1 Test(a,2) PutE()\n a(0)=a4 a(1)=a5 a(2)=a6 a(3)=a7 Test(a,4) PutE()\n a(0)=a8 a(1)=a9 a(2)=a10 Test(a,3) PutE()\n a(0)=a8 a(1)=a3 a(2)=a10 Test(a,3)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO; use Ada.Text_Io;\nwith Ada.Containers.Doubly_Linked_Lists;\nwith Ada.Strings.Fixed;\n\nprocedure Cartesian is\n\n type Element_Type is new Long_Integer;\n\n package Lists is\n new Ada.Containers.Doubly_Linked_Lists (Element_Type);\n package List_Lists is\n new Ada.Containers.Doubly_Linked_Lists (Lists.List, Lists.\"=\");\n\n subtype List is Lists.List;\n subtype List_List is List_Lists.List;\n\n function \"*\" (Left, Right : List) return List_List is\n Result : List_List;\n Sub : List;\n begin\n for Outer of Left loop\n for Inner of Right loop\n Sub.Clear;\n Sub.Append (Outer);\n Sub.Append (Inner);\n Result.Append (Sub);\n end loop;\n end loop;\n return Result;\n end \"*\";\n\n function \"*\" (Left : List_List;\n Right : List) return List_List\n is\n Result : List_List;\n Sub : List;\n begin\n for Outer of Left loop\n for Inner of Right loop\n Sub := Outer;\n Sub.Append (Inner);\n Result.Append (Sub);\n end loop;\n end loop;\n return Result;\n end \"*\";\n\n procedure Put (L : List) is\n use Ada.Strings;\n First : Boolean := True;\n begin\n Put (\"(\");\n for E of L loop\n if not First then\n Put (\",\");\n end if;\n Put (Fixed.Trim (E'Image, Left));\n First := False;\n end loop;\n Put (\")\");\n end Put;\n\n procedure Put (LL : List_List) is\n First : Boolean := True;\n begin\n Put (\"{\");\n for E of LL loop\n if not First then\n Put (\",\");\n end if;\n Put (E);\n First := False;\n end loop;\n Put (\"}\");\n end Put;\n\n function \"&\" (Left : List; Right : Element_Type) return List is\n Result : List := Left;\n begin\n Result.Append (Right);\n return Result;\n end \"&\";\n\n Nil : List renames Lists.Empty_List;\n List_1_2 : constant List := Nil & 1 & 2;\n List_3_4 : constant List := Nil & 3 & 4;\n List_Empty : constant List := Nil;\n List_1_2_3 : constant List := Nil & 1 & 2 & 3;\nbegin\n Put (List_1_2 * List_3_4); New_Line;\n\n Put (List_3_4 * List_1_2); New_Line;\n\n Put (List_Empty * List_1_2); New_Line;\n\n Put (List_1_2 * List_Empty); New_Line;\n\n Put (List'(Nil & 1776 & 1789) * List'(Nil & 7 & 12) *\n List'(Nil & 4 & 14 & 23) * List'(Nil & 0 & 1)); New_Line;\n\n Put (List_1_2_3 * List'(Nil & 30) * List'(Nil & 500 & 100)); New_Line;\n\n Put (List_1_2_3 * List_Empty * List'(Nil & 500 & 100)); New_Line;\nend Cartesian;\n", "language": "Ada" }, { "code": "BEGIN # Cartesian Product #\n # Cartesian product operators #\n PRIO X = 7; # give X he same priority as * #\n # returns the Cartesian product of the lists a and b #\n OP X = ( []INT a, b )[,]INT:\n BEGIN\n []INT a1 = a[ AT 1 ];\n []INT b1 = b[ AT 1 ];\n INT len = UPB a1 * UPB b1;\n [ 1 : len, 1 : IF len > 0 THEN 2 ELSE 0 FI ]INT result;\n INT pos := 0;\n FOR i TO UPB a1 DO\n FOR j TO UPB b1 DO\n pos +:= 1;\n result[ pos, 1 ] := a1[ i ];\n result[ pos, 2 ] := b1[ j ]\n OD\n OD;\n result\n END # X # ;\n # returns the Cartesian product of the Cartesian product a and list b #\n OP X = ( [,]INT a, []INT b )[,]INT:\n BEGIN\n [,]INT a1 = a[ AT 1, AT 1 ];\n []INT b1 = b[ AT 1 ];\n INT len = 1 UPB a1 * UPB b1;\n INT width = IF len <= 0 THEN 0 ELSE 2 UPB a1 + 1 FI;\n [ 1 : len, 1 : width ]INT result;\n INT pos := 0;\n FOR i TO 1 UPB a1 DO\n FOR j TO UPB b1 DO\n result[ pos +:= 1, 1 : width - 1 ] := a1[ i, : ];\n result[ pos, width ] := b1[ j ]\n OD\n OD;\n result\n END # X # ;\n # returns the Cartesian product of the lists in a #\n OP X = ( [][]INT a )[,]INT:\n IF UPB a <= LWB a\n THEN # zero or 1 list #\n [,]INT()\n ELSE # 2 or more lists #\n FLEX[ 1 : 0, 1 : 0 ]INT result := a[ LWB a ] X a[ LWB a + 1 ];\n FOR i FROM LWB a + 2 TO UPB a DO\n result := result X a[ i ]\n OD;\n result\n FI # X # ;\n # print a Cartesian product #\n PROC print product = ( [,]INT p )VOID:\n BEGIN\n print( ( \"[\" ) );\n STRING close := \"]\";\n STRING open := \"(\";\n FOR i FROM 1 LWB p TO 1 UPB p DO\n STRING separator := open;\n FOR j FROM 2 LWB p TO 2 UPB p DO\n print( ( separator, whole( p[ i, j ], 0 ) ) );\n separator := \",\"\n OD;\n open := \"),(\";\n close := \")]\"\n OD;\n print( ( close ) )\n END # print product # ;\n # print a list #\n PROC print list = ( []INT t )VOID:\n BEGIN\n print( ( \"[\" ) );\n STRING separator := \"\";\n FOR i FROM LWB t TO UPB t DO\n print( ( separator, whole( t[ i ], 0 ) ) );\n separator := \",\"\n OD;\n print( ( \"]\" ) )\n END # print list # ;\n BEGIN # test the X operators #\n # prints the product of two lists #\n PROC print lxl = ( []INT a, b )VOID:\n BEGIN\n print list( a );print( ( \"X\" ) );print list( b );\n print( ( \"=\" ) );print product( a X b );\n print( ( newline ) )\n END # print lxl # ;\n # prints the product of a list of lists #\n PROC print xll = ( [][]INT a )VOID:\n IF LWB a < UPB a THEN\n # non empty list of lists #\n print list( a[ LWB a ] );\n FOR i FROM LWB a + 1 TO UPB a DO\n print( ( \"X\" ) );print list( a[ i ] )\n OD;\n print( ( \"=\" ) );print product( X a );\n print( ( newline ) )\n FI # print xll # ;\n print lxl( ( 1, 2 ), ( 3, 4 ) );\n print lxl( ( 3, 4 ), ( 1, 2 ) );\n print lxl( ( 1, 2 ), () );\n print lxl( (), ( 1, 2 ) );\n print xll( ( ( 1776, 1789 ), ( 7, 12 ), ( 4, 14, 23 ), ( 0, 1 ) ) );\n print xll( ( ( 1, 2, 3 ), ( 30 ), ( 500, 100 ) ) );\n print xll( ( ( 1, 2, 3 ), (), ( 500, 100 ) ) )\n END\nEND\n", "language": "ALGOL-68" }, { "code": "cart ← ,∘.,\n", "language": "APL" }, { "code": "nary_cart ← ⊃(,∘.,)/\n", "language": "APL" }, { "code": "-- CARTESIAN PRODUCTS ---------------------------------------------------------\n\n-- Two lists:\n\n-- cartProd :: [a] -> [b] -> [(a, b)]\non cartProd(xs, ys)\n script\n on |λ|(x)\n script\n on |λ|(y)\n [[x, y]]\n end |λ|\n end script\n concatMap(result, ys)\n end |λ|\n end script\n concatMap(result, xs)\nend cartProd\n\n-- N-ary – a function over a list of lists:\n\n-- cartProdNary :: [[a]] -> [[a]]\non cartProdNary(xss)\n script\n on |λ|(accs, xs)\n script\n on |λ|(x)\n script\n on |λ|(a)\n {x & a}\n end |λ|\n end script\n concatMap(result, accs)\n end |λ|\n end script\n concatMap(result, xs)\n end |λ|\n end script\n foldr(result, {{}}, xss)\nend cartProdNary\n\n-- TESTS ----------------------------------------------------------------------\non run\n set baseExamples to unlines(map(show, ¬\n [cartProd({1, 2}, {3, 4}), ¬\n cartProd({3, 4}, {1, 2}), ¬\n cartProd({1, 2}, {}), ¬\n cartProd({}, {1, 2})]))\n\n set naryA to unlines(map(show, ¬\n cartProdNary([{1776, 1789}, {7, 12}, {4, 14, 23}, {0, 1}])))\n\n set naryB to show(cartProdNary([{1, 2, 3}, {30}, {500, 100}]))\n\n set naryC to show(cartProdNary([{1, 2, 3}, {}, {500, 100}]))\n\n intercalate(linefeed & linefeed, {baseExamples, naryA, naryB, naryC})\nend run\n\n\n-- GENERIC FUNCTIONS ----------------------------------------------------------\n\n-- concatMap :: (a -> [b]) -> [a] -> [b]\non concatMap(f, xs)\n set lst to {}\n set lng to length of xs\n tell mReturn(f)\n repeat with i from 1 to lng\n set lst to (lst & |λ|(item i of xs, i, xs))\n end repeat\n end tell\n return lst\nend concatMap\n\n-- foldr :: (a -> b -> a) -> a -> [b] -> a\non foldr(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from lng to 1 by -1\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldr\n\n-- intercalate :: Text -> [Text] -> Text\non intercalate(strText, lstText)\n set {dlm, my text item delimiters} to {my text item delimiters, strText}\n set strJoined to lstText as text\n set my text item delimiters to dlm\n return strJoined\nend intercalate\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n-- show :: a -> String\non show(e)\n set c to class of e\n if c = list then\n script serialized\n on |λ|(v)\n show(v)\n end |λ|\n end script\n\n \"[\" & intercalate(\", \", map(serialized, e)) & \"]\"\n else if c = record then\n script showField\n on |λ|(kv)\n set {k, ev} to kv\n \"\\\"\" & k & \"\\\":\" & show(ev)\n end |λ|\n end script\n\n \"{\" & intercalate(\", \", ¬\n map(showField, zip(allKeys(e), allValues(e)))) & \"}\"\n else if c = date then\n \"\\\"\" & iso8601Z(e) & \"\\\"\"\n else if c = text then\n \"\\\"\" & e & \"\\\"\"\n else if (c = integer or c = real) then\n e as text\n else if c = class then\n \"null\"\n else\n try\n e as text\n on error\n (\"«\" & c as text) & \"»\"\n end try\n end if\nend show\n\n-- unlines :: [String] -> String\non unlines(xs)\n intercalate(linefeed, xs)\nend unlines\n", "language": "AppleScript" }, { "code": "100 HOME : rem 10 CLS FOR Chipmunk Basic & GW-BASIC\n110 DIM array(2,2)\n120 array(1,1) = 1 : array(1,2) = 2\n130 array(2,1) = 3 : array(2,2) = 4\n140 GOSUB 190\n150 array(1,1) = 3 : array(1,2) = 4\n160 array(2,1) = 1 : array(2,2) = 2\n170 GOSUB 190\n180 END\n190 rem SUB cartesian(list)\n200 u1 = 2 : u2 = 2\n210 FOR i = 1 TO u1\n220 PRINT \"{ \";\n230 FOR j = 1 TO u2\n240 PRINT array(i,j);\n250 IF j < u1 THEN PRINT \", \";\n260 NEXT j\n270 PRINT \"}\";\n280 IF i < u2 THEN PRINT \" x \";\n290 NEXT i\n300 PRINT \" = { \";\n310 FOR i = 1 TO u1\n320 FOR j = 1 TO u2\n330 PRINT \"{ \"; array(1,i); \", \"; array(2,j); \"} \";\n340 IF i < u2 THEN PRINT \", \";\n350 IF i => u2 THEN IF j < u1 THEN PRINT \", \";\n360 NEXT j\n370 NEXT i\n380 PRINT \"}\"\n390 RETURN\n", "language": "Applesoft-BASIC" }, { "code": "loop [\n [[1 2][3 4]]\n [[3 4][1 2]]\n [[1 2][]]\n [[][1 2]]\n [[1776 1789][7 12][4 14 23][0 1]]\n [[1 2 3][30][500 100]]\n [[1 2 3][][500 100]]\n] 'lst [\n print as.code product.cartesian lst\n]\n", "language": "Arturo" }, { "code": "example := [\n(join,\n[[1, 2], [3, 4]]\n[[3, 4], [1, 2]]\n[[1, 2], []]\n[[], [1, 2]]\n[[1776, 1789], [7, 12], [4, 14, 23], [0, 1]]\n[[1, 2, 3], [30] , [500, 100]]\n[[1, 2, 3], [] , [500, 100]]\n)]\n\nfor i, obj in example\n{\n Product := CartesianProduct(obj)\n out := dispRes(Product)\n result .= out \"`n`n\"\n}\nMsgBox % result\nreturn\n\ndispRes(Product){\n for i, o in Product\n {\n for j, v in o\n output .= v \", \"\n\n output := Trim(output, \", \")\n output .= \"], [\"\n }\n return \"[[\" trim(output, \", []\") \"]]\"\n}\n\nCartesianProduct(obj){\n CP(obj, Product:=[], [])\n return Product\n}\n\nCP(obj, Product, stack, v:=\"\"){\n oClone := obj.clone()\n oClone.RemoveAt(1)\n stack.= v \",\"\n\n for i, o in obj\n {\n for j, v in o\n CP(oClone, Product, stack, v)\n return\n }\n stack := trim(stack, \",\")\n oTemp := []\n for i, v in StrSplit(stack, \",\")\n oTemp.Push(v)\n Product.push(oTemp)\n}\n", "language": "AutoHotkey" }, { "code": "arraybase 1\nsubroutine cartesian(list)\n\tu1 = list[?][]\n\tu2 = list[][?]\n\n\tfor i = 1 to u1\n\t\tprint \"{\";\n\t\tfor j = 1 to u2\n\t\t\tprint list[i,j];\n\t\t\tif j < u1 then print \", \";\n\t\tnext\n\t\tprint \"}\";\n\t\tif i < u2 then print \" x \";\n\tnext i\n\tprint \" = { \";\n\tfor i = 1 to u1\n\t\tfor j = 1 to u2\n\t\t\tprint \"{\"; list[1, i]; \", \"; list[2, j]; \"} \";\n\t\t\tif i < u2 then\n\t\t\t\tprint \", \";\n\t\t\telse\n\t\t\t\tif j < u1 then print \", \";\n\t\t\tend if\n\t\tnext j\n\tnext i\n\tprint \"}\"\nend subroutine\n\ndim list1 = {{1,2},{3,4}}\ndim list2 = {{3,4},{1,2}}\ncall cartesian(list1)\ncall cartesian(list2)\nend\n", "language": "BASIC256" }, { "code": "( ( mul\n = R a b A B\n . :?R\n & !arg:(.?A) (.?B)\n & ( !A\n : ?\n ( %@?a\n & !B\n : ?\n ( (%@?b|(.?b))\n & !R (.!a !b):?R\n & ~\n )\n ?\n )\n ?\n | (.!R)\n )\n )\n& ( cartprod\n = a\n . !arg:%?a %?arg&mul$(!a cartprod$!arg)\n | !arg\n )\n& out\n $ ( cartprod\n $ ( (.1776 1789)\n (.7 12)\n (.4 14 23)\n (.0 1)\n )\n )\n& out$(cartprod$((.1 2 3) (.30) (.500 100)))\n& out$(cartprod$((.1 2 3) (.) (.500 100)))\n)\n", "language": "Bracmat" }, { "code": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n std::cout << \"{ \";\n for (const auto& p : v) {\n std::cout << \"(\";\n for (const auto& e : p) {\n std::cout << e << \" \";\n }\n std::cout << \") \";\n }\n std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n std::vector<std::vector<int>> result;\n if (std::find_if(std::begin(lists), std::end(lists),\n [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n return result;\n }\n for (auto& e : lists[0]) {\n result.push_back({ e });\n }\n for (size_t i = 1; i < lists.size(); ++i) {\n std::vector<std::vector<int>> temp;\n for (auto& e : result) {\n for (auto f : lists[i]) {\n auto e_tmp = e;\n e_tmp.push_back(f);\n temp.push_back(e_tmp);\n }\n }\n result = temp;\n }\n return result;\n}\n\nint main() {\n std::vector<std::vector<int>> prods[] = {\n { { 1, 2 }, { 3, 4 } },\n { { 3, 4 }, { 1, 2} },\n { { 1, 2 }, { } },\n { { }, { 1, 2 } },\n { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n { { 1, 2, 3 }, { }, { 500, 100 } }\n };\n for (const auto& p : prods) {\n print(product(p));\n }\n std::cin.ignore();\n std::cin.get();\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\npublic class Program\n{\n public static void Main()\n {\n int[] empty = new int[0];\n int[] list1 = { 1, 2 };\n int[] list2 = { 3, 4 };\n int[] list3 = { 1776, 1789 };\n int[] list4 = { 7, 12 };\n int[] list5 = { 4, 14, 23 };\n int[] list6 = { 0, 1 };\n int[] list7 = { 1, 2, 3 };\n int[] list8 = { 30 };\n int[] list9 = { 500, 100 };\n\n foreach (var sequenceList in new [] {\n new [] { list1, list2 },\n new [] { list2, list1 },\n new [] { list1, empty },\n new [] { empty, list1 },\n new [] { list3, list4, list5, list6 },\n new [] { list7, list8, list9 },\n new [] { list7, empty, list9 }\n }) {\n var cart = sequenceList.CartesianProduct()\n .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n }\n }\n}\n\npublic static class Extensions\n{\n public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n return sequences.Aggregate(\n emptyProduct,\n (accumulator, sequence) =>\n from acc in accumulator\n from item in sequence\n select acc.Concat(new [] { item }));\n }\n}\n", "language": "C-sharp" }, { "code": "public static void Main()\n{\n ///...\n var cart1 =\n from a in list1\n from b in list2\n select (a, b); // C# 7.0 tuple\n Console.WriteLine($\"{{{string.Join(\", \", cart1)}}}\");\n\n var cart2 =\n from a in list7\n from b in list8\n from c in list9\n select (a, b, c);\n Console.WriteLine($\"{{{string.Join(\", \", cart2)}}}\");\n}\n", "language": "C-sharp" }, { "code": "100 cls\n110 dim array(2,2)\n120 array(1,1) = 1 : array(1,2) = 2\n130 array(2,1) = 3 : array(2,2) = 4\n140 gosub 190\n150 array(1,1) = 3 : array(1,2) = 4\n160 array(2,1) = 1 : array(2,2) = 2\n170 gosub 190\n180 end\n190 rem sub cartesian(list)\n200 u1 = 2 : u2 = 2\n210 for i = 1 to u1\n220 print \"{ \";\n230 for j = 1 to u2\n240 print array(i,j);\n250 if j < u1 then print \", \";\n260 next j\n270 print \"}\";\n280 if i < u2 then print \" x \";\n290 next i\n300 print \" = { \";\n310 for i = 1 to u1\n320 for j = 1 to u2\n330 print \"{ \";array(1,i);\", \";array(2,j);\"} \";\n340 if i < u2 then\n350 print \", \";\n360 else\n370 if j < u1 then print \", \";\n380 endif\n390 next j\n400 next i\n410 print \"}\"\n420 return\n", "language": "Chipmunk-Basic" }, { "code": " (ns clojure.examples.product\n\t(:gen-class)\n\t(:require [clojure.pprint :as pp]))\n\n(defn cart [colls]\n \"Compute the cartesian product of list of lists\"\n (if (empty? colls)\n '(())\n (for [more (cart (rest colls))\n x (first colls)]\n (cons x more))))\n", "language": "Clojure" }, { "code": "(doseq [lst [ [[1,2],[3,4]],\n [[3,4],[1,2]], [[], [1, 2]],\n [[1, 2], []],\n [[1776, 1789], [7, 12], [4, 14, 23], [0, 1]],\n [[1, 2, 3], [30,], [500, 100]],\n [[1, 2, 3], [], [500, 100]]\n ]\n ]\n (println lst \"=>\")\n (pp/pprint (cart lst)))\n", "language": "Clojure" }, { "code": "(defun cartesian-product (s1 s2)\n \"Compute the cartesian product of two sets represented as lists\"\n (loop for x in s1\n\tnconc (loop for y in s2 collect (list x y))))\n", "language": "Common-Lisp" }, { "code": "CL-USER> (cartesian-product '(1 2) '(3 4))\n((1 3) (1 4) (2 3) (2 4))\nCL-USER> (cartesian-product '(3 4) '(1 2))\n((3 1) (3 2) (4 1) (4 2))\nCL-USER> (cartesian-product '(1 2) '())\nNIL\nCL-USER> (cartesian-product '() '(1 2))\nNIL\n", "language": "Common-Lisp" }, { "code": "(defun n-cartesian-product (l)\n \"Compute the n-cartesian product of a list of sets (each of them represented as list).\n Algorithm:\n If there are no sets, then produce an empty set of tuples;\n otherwise, for all the elements x of the first set, concatenate the sets obtained by\n inserting x at the beginning of each tuple of the n-cartesian product of the remaining sets.\"\n (if (null l)\n (list nil)\n (loop for x in (car l)\n nconc (loop for y in (n-cartesian-product (cdr l))\n collect (cons x y)))))\n", "language": "Common-Lisp" }, { "code": "CL-USER> (n-cartesian-product '((1776 1789) (7 12) (4 14 23) (0 1)))\n((1776 7 4 0) (1776 7 4 1) (1776 7 14 0) (1776 7 14 1) (1776 7 23 0) (1776 7 23 1) (1776 12 4 0) (1776 12 4 1) (1776 12 14 0) (1776 12 14 1) (1776 12 23 0) (1776 12 23 1) (1789 7 4 0) (1789 7 4 1) (1789 7 14 0) (1789 7 14 1) (1789 7 23 0) (1789 7 23 1) (1789 12 4 0) (1789 12 4 1) (1789 12 14 0) (1789 12 14 1) (1789 12 23 0) (1789 12 23 1))\nCL-USER> (n-cartesian-product '((1 2 3) (30) (500 100)))\n((1 30 500) (1 30 100) (2 30 500) (2 30 100) (3 30 500) (3 30 100))\nCL-USER> (n-cartesian-product '((1 2 3) () (500 100)))\nNIL\n", "language": "Common-Lisp" }, { "code": "def cartesian_product(a, b)\n return a.flat_map { |i| b.map { |j| [i, j] } }\nend\n\n\ndef cartesian_product(l)\n if l.size <= 1\n return l\n elsif l.size == 2\n return cartesian_product(l[0], l[1])\n end\n\n return l[0].flat_map { |i|\n cartesian_product(l[1..]).map { |j|\n [i, j].flatten\n }\n }\nend\n\n\ntests = [ [[1, 2], [3, 4]],\n [[3, 4], [1, 2]],\n [[1, 2], [] of Int32],\n [[] of Int32, [1, 2]],\n [[1, 2, 3], [30], [500, 100]],\n [[1, 2, 3], [] of Int32, [500, 100]],\n [[1776, 1789], [7, 12], [4, 14, 23], [0, 1]] ]\n\ntests.each { |test|\n puts \"#{test.join(\" x \")} ->\"\n puts \" #{cartesian_product(test)}\"\n puts \"\"\n}\n", "language": "Crystal" }, { "code": "import std.stdio;\n\nvoid main() {\n auto a = listProduct([1,2], [3,4]);\n writeln(a);\n\n auto b = listProduct([3,4], [1,2]);\n writeln(b);\n\n auto c = listProduct([1,2], []);\n writeln(c);\n\n auto d = listProduct([], [1,2]);\n writeln(d);\n}\n\nauto listProduct(T)(T[] ta, T[] tb) {\n struct Result {\n int i, j;\n\n bool empty() {\n return i>=ta.length\n || j>=tb.length;\n }\n\n T[] front() {\n return [ta[i], tb[j]];\n }\n\n void popFront() {\n if (++j>=tb.length) {\n j=0;\n i++;\n }\n }\n }\n\n return Result();\n}\n", "language": "D" }, { "code": "program Cartesian_product_of_two_or_more_lists;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils;\n\ntype\n TList = TArray<Integer>;\n\n TLists = TArray<TList>;\n\n TListHelper = record helper for TList\n function ToString: string;\n end;\n\n TListsHelper = record helper for TLists\n function ToString(BreakLines: boolean = false): string;\n end;\n\nfunction cartN(arg: TLists): TLists;\nvar\n b, n: TList;\n argc: Integer;\nbegin\n argc := length(arg);\n\n var c := 1;\n for var a in arg do\n c := c * length(a);\n\n if c = 0 then\n exit;\n\n SetLength(result, c);\n SetLength(b, c * argc);\n SetLength(n, argc);\n\n var s := 0;\n for var i := 0 to c - 1 do\n begin\n var e := s + argc;\n var Resi := copy(b, s, e - s);\n Result[i] := Resi;\n\n s := e;\n for var j := 0 to high(n) do\n begin\n var nj := n[j];\n Resi[j] := arg[j, nj];\n end;\n\n for var j := high(n) downto 0 do\n begin\n inc(n[j]);\n if n[j] < Length(arg[j]) then\n Break;\n n[j] := 0;\n end;\n end;\nend;\n\n{ TListHelper }\n\nfunction TListHelper.ToString: string;\nbegin\n Result := '[';\n for var i := 0 to High(self) do\n begin\n Result := Result + self[i].ToString;\n if i < High(self) then\n Result := Result + ' ';\n end;\n Result := Result + ']';\nend;\n\n{ TListsHelper }\n\nfunction TListsHelper.ToString(BreakLines: boolean = false): string;\nbegin\n Result := '[';\n for var i := 0 to High(self) do\n begin\n Result := Result + self[i].ToString;\n if i < High(self) then\n begin\n if BreakLines then\n Result := Result + #10\n else\n Result := Result + ' ';\n end;\n end;\n Result := Result + ']';\nend;\n\nbegin\n writeln(#10, cartN([[1, 2], [3, 4]]).ToString);\n writeln(#10, cartN([[3, 4], [1, 2]]).ToString);\n writeln(#10, cartN([[1, 2], []]).ToString);\n writeln(#10, cartN([[], [1, 2]]).ToString);\n\n writeln(#10, cartN([[1776, 1789], [17, 12], [4, 14, 23], [0, 1]]).ToString(True));\n\n writeln(#10, cartN([[1, 2, 3], [30], [500, 100]]).ToString);\n\n writeln(#10, cartN([[1, 2, 3], [], [500, 100]]).ToString);\n\n {$IFNDEF UNIX} readln; {$ENDIF}\nend.\n", "language": "Delphi" }, { "code": "proc cart2 a[] b[] . p[][] .\n p[][] = [ ]\n for a in a[]\n for b in b[]\n p[][] &= [ a b ]\n .\n .\n.\ncart2 [ 1 2 ] [ 3 4 ] r[][]\nprint r[][]\ncart2 [ 3 4 ] [ 1 2 ] r[][]\nprint r[][]\ncart2 [ 1 2 ] [ ] r[][]\nprint r[][]\ncart2 [ ] [ 1 2 ] r[][]\nprint r[][]\n", "language": "EasyLang" }, { "code": "-module(cartesian).\n-export([product/2]).\n\nproduct(S1, S2) -> [{A,B} || A <- S1, B <- S2].\n", "language": "Erlang" }, { "code": "//Nigel Galloway February 12th., 2018\nlet cP2 n g = List.map (fun (n,g)->[n;g]) (List.allPairs n g)\n", "language": "F-Sharp" }, { "code": "//Nigel Galloway August 14th., 2018\nlet cP ng=Seq.foldBack(fun n g->[for n' in n do for g' in g do yield n'::g']) ng [[]]\n", "language": "F-Sharp" }, { "code": "IN: scratchpad { 1 2 } { 3 4 } cartesian-product .\n{ { { 1 3 } { 1 4 } } { { 2 3 } { 2 4 } } }\nIN: scratchpad { 3 4 } { 1 2 } cartesian-product .\n{ { { 3 1 } { 3 2 } } { { 4 1 } { 4 2 } } }\nIN: scratchpad { 1 2 } { } cartesian-product .\n{ { } { } }\nIN: scratchpad { } { 1 2 } cartesian-product .\n{ }\n", "language": "Factor" }, { "code": " ! Created by simon on 29/04/2021.\n\n ! ifort -o cartesian_product cartesian_product.f90 -check all\n\n module tuple\n implicit none\n private\n public :: tuple_t, operator(*), print\n\n type tuple_t(n)\n integer, len :: n\n integer, private :: v(n)\n contains\n procedure, public :: print => print_tuple_t\n generic, public :: assignment(=) => eq_tuple_t\n procedure, public :: eq_tuple_t\n end type tuple_t\n\n interface print\n module procedure print_tuple_a_t\n end interface print\n interface operator(*)\n module procedure tup_times_tup\n end interface\n\n contains\n subroutine eq_tuple_t(this, src)\n class(tuple_t(*)), intent(inout) :: this\n integer, intent(in) :: src(:)\n this%v = src\n end subroutine eq_tuple_t\n\n pure function tup_times_tup(a, b) result(r)\n type(tuple_t(*)), intent(in) :: a\n type(tuple_t(*)), intent(in) :: b\n type(tuple_t(2)), allocatable :: r(:)\n integer :: i, j, k\n\n allocate(r(a%n*b%n))\n k = 0\n do i=1,a%n\n do j=1,b%n\n k = k + 1\n r(k)%v = [a%v(i),b%v(j)]\n end do\n end do\n end function tup_times_tup\n\n subroutine print_tuple_t(this)\n class(tuple_t(*)), intent(in) :: this\n integer :: i\n write(*,fmt='(a)',advance='no') '{'\n do i=1,size(this%v)\n write(*,fmt='(i0)',advance='no') this%v(i)\n if (i < size(this%v)) write(*,fmt='(a)',advance='no') ','\n end do\n write(*,fmt='(a)',advance='no') '}'\n end subroutine print_tuple_t\n\n subroutine print_tuple_a_t(r)\n type(tuple_t(*)), intent(in) :: r(:)\n integer :: i\n write(*,fmt='(a)',advance='no') '{'\n do i=1,size(r)\n call r(i)%print\n if (i < size(r)) write(*,fmt='(a)',advance='no') ','\n end do\n write(*,fmt='(a)') '}'\n end subroutine print_tuple_a_t\n end module tuple\n\n program cartesian_product\n use tuple\n\n implicit none\n type(tuple_t(2)) :: a, b\n type(tuple_t(0)) :: z\n\n a = [1,2]\n b = [3,4]\n\n call print_product(a, b)\n call print_product(b, a)\n call print_product(z, a)\n call print_product(a, z)\n\n stop\n contains\n subroutine print_product(s, t)\n type(tuple_t(*)), intent(in) :: s\n type(tuple_t(*)), intent(in) :: t\n call s%print\n write(*,fmt='(a)',advance='no') ' x '\n call t%print\n write(*,fmt='(a)',advance='no') ' = '\n call print(s*t)\n end subroutine print_product\n end program cartesian_product\n", "language": "Fortran" }, { "code": "#define MAXLEN 64\n\ntype listitem ' An item of a list may be a number\n is_num as boolean ' or another list, so I have to account\n union ' for both, implemented as a union.\n list as any ptr ' FreeBASIC is twitchy about circularly\n num as uinteger ' defined types, so one workaround is to\n end union ' use a generic pointer that I will cast\nend type ' later.\n\ntype list\n length as uinteger 'simple, fixed storage length lists\n item(1 to MAXLEN) as listitem 'are good enough for this example\nend type\n\nsub print_list( list as list )\n print \"{\";\n if list.length = 0 then print \"}\"; : return\n for i as uinteger = 1 to list.length\n if list.item(i).is_num then\n print str(list.item(i).num);\n else 'recursively print sublist\n print_list( *cast(list ptr, list.item(i).list) )\n end if\n if i<list.length then print \", \"; else print \"}\"; 'handle comma\n next i 'gracefully\n return\nend sub\n\nfunction cartprod( A as list, B as list ) as list\n dim as uinteger i, j\n dim as list C\n dim as list ptr inner 'for brevity\n C.length = 0\n for i = 1 to A.length\n for j = 1 to B.length\n C.length += 1\n C.item(C.length).is_num = false 'each item of the new list is a list itself\n inner = allocate( sizeof(list) ) 'make space for it\n C.item(C.length).list = inner\n inner->length = 2 'each inner list contains two items\n inner->item(1) = A.item(i) 'one from the first list\n inner->item(2) = B.item(j) 'and one from the second\n next j\n next i\n return C\nend function\n\ndim as list EMPTY, A, B, R\nEMPTY.length = 0\nA.length = 2\nA.item(1).is_num = true : A.item(1).num = 1\nA.item(2).is_num = true : A.item(2).num = 2\nB.length = 2\nB.item(1).is_num = true : B.item(1).num = 3\nB.item(2).is_num = true : B.item(2).num = 4\n\nR = cartprod(A, B)\nprint_list(R) : print 'print_list does not supply a final newline\nR = cartprod(B, A) : print_list(R) : print\nR = cartprod(A, EMPTY) : print_list(R) : print\nR = cartprod(EMPTY, A) : print_list(R) : print\n", "language": "FreeBASIC" }, { "code": "Public array[2, 2] As Integer\n\nPublic Sub Main()\n\n array[0, 0] = 1\n array[0, 1] = 2\n array[1, 0] = 3\n array[1, 1] = 4\n cartesian(array)\n array[0, 0] = 3\n array[0, 1] = 4\n array[1, 0] = 1\n array[1, 1] = 2\n cartesian(array)\n\nEnd\n\nSub cartesian(arr As Integer[])\n\n Dim u1 As Integer = arr.Max - 2\n Dim u2 As Integer = arr.Max - 2\n Dim i As Integer, j As Integer\n\n For i = 0 To u1\n Print \"{\";\n For j = 0 To u2\n Print arr[i, j];\n If j < u1 Then Print \",\";\n Next\n Print \"}\";\n If i < u2 Then Print \" x \";\n Next\n Print \" = {\";\n For i = 0 To u1\n For j = 0 To u2\n Print \"{\"; arr[0, i]; \",\"; arr[1, j]; \"}\";\n If i < u2 Then\n Print \", \";\n Else\n If j < u1 Then Print \", \";\n End If\n Next\n Next\n Print \"}\"\n\nEnd Sub\n", "language": "Gambas" }, { "code": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n p := make([]pair, len(a)*len(b))\n i := 0\n for _, a := range a {\n for _, b := range b {\n p[i] = pair{a, b}\n i++\n }\n }\n return p\n}\n\nfunc main() {\n fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n fmt.Println(cart2([]int{1, 2}, nil))\n fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "language": "Go" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc cartN(a ...[]int) [][]int {\n c := 1\n for _, a := range a {\n c *= len(a)\n }\n if c == 0 {\n return nil\n }\n p := make([][]int, c)\n b := make([]int, c*len(a))\n n := make([]int, len(a))\n s := 0\n for i := range p {\n e := s + len(a)\n pi := b[s:e]\n p[i] = pi\n s = e\n for j, n := range n {\n pi[j] = a[j][n]\n }\n for j := len(n) - 1; j >= 0; j-- {\n n[j]++\n if n[j] < len(a[j]) {\n break\n }\n n[j] = 0\n }\n }\n return p\n}\n\nfunc main() {\n fmt.Println(cartN([]int{1, 2}, []int{3, 4}))\n fmt.Println(cartN([]int{3, 4}, []int{1, 2}))\n fmt.Println(cartN([]int{1, 2}, nil))\n fmt.Println(cartN(nil, []int{1, 2}))\n\n fmt.Println()\n fmt.Println(\"[\")\n for _, p := range cartN(\n []int{1776, 1789},\n []int{7, 12},\n []int{4, 14, 23},\n []int{0, 1},\n ) {\n fmt.Println(\" \", p)\n }\n fmt.Println(\"]\")\n fmt.Println(cartN([]int{1, 2, 3}, []int{30}, []int{500, 100}))\n fmt.Println(cartN([]int{1, 2, 3}, []int{}, []int{500, 100}))\n\n fmt.Println()\n fmt.Println(cartN(nil))\n fmt.Println(cartN())\n}\n", "language": "Go" }, { "code": "func cartN(a ...[]int) (c [][]int) {\n if len(a) == 0 {\n return [][]int{nil}\n }\n r := cartN(a[1:]...)\n for _, e := range a[0] {\n for _, p := range r {\n c = append(c, append([]int{e}, p...))\n }\n }\n return\n}\n", "language": "Go" }, { "code": "func cartN(a ...[]int) (c [][]int) {\n if len(a) == 0 {\n return [][]int{nil}\n }\n last := len(a) - 1\n l := cartN(a[:last]...)\n for _, e := range a[last] {\n for _, p := range l {\n c = append(c, append(p, e))\n }\n }\n return\n}\n", "language": "Go" }, { "code": "class CartesianCategory {\n static Iterable multiply(Iterable a, Iterable b) {\n assert [a,b].every { it != null }\n def (m,n) = [a.size(),b.size()]\n (0..<(m*n)).inject([]) { prod, i -> prod << [a[i.intdiv(n)], b[i%n]].flatten() }\n }\n}\n", "language": "Groovy" }, { "code": "Iterable.metaClass.mixin CartesianCategory\n\nprintln \"\\nCore Solution:\"\nprintln \"[1, 2] × [3, 4] = ${[1, 2] * [3, 4]}\"\nprintln \"[3, 4] × [1, 2] = ${[3, 4] * [1, 2]}\"\nprintln \"[1, 2] × [] = ${[1, 2] * []}\"\nprintln \"[] × [1, 2] = ${[] * [1, 2]}\"\n\nprintln \"\\nExtra Credit:\"\nprintln \"[1776, 1789] × [7, 12] × [4, 14, 23] × [0, 1] = ${[1776, 1789] * [7, 12] * [4, 14, 23] * [0, 1]}\"\nprintln \"[1, 2, 3] × [30] × [500, 100] = ${[1, 2, 3] * [30] * [500, 100]}\"\nprintln \"[1, 2, 3] × [] × [500, 100] = ${[1, 2, 3] * [] * [500, 100]}\"\n\nprintln \"\\nNon-Numeric Example:\"\nprintln \"[John,Paul,George,Ringo] × [Emerson,Lake,Palmer] × [Simon,Garfunkle] = [\"\n( [\"John\",\"Paul\",\"George\",\"Ringo\"] * [\"Emerson\",\"Lake\",\"Palmer\"] * [\"Simon\",\"Garfunkle\"] ).each { println \"\\t${it},\" }\nprintln \"]\"\n", "language": "Groovy" }, { "code": "100 CLS\n110 DIM ARR(2,2)\n120 ARR(1,1) = (1) : ARR(1,2) = (2)\n130 ARR(2,1) = (3) : ARR(2,2) = (4)\n140 GOSUB 190\n150 ARR(1,1) = 3 : ARR(1,2) = 4\n160 ARR(2,1) = 1 : ARR(2,2) = 2\n170 GOSUB 190\n180 END\n190 REM SUB cartesian(list)\n200 U1 = 2 : U2 = 2\n210 FOR I = 1 TO U1\n220 PRINT \"{\";\n230 FOR J = 1 TO U2\n240 PRINT ARR(I,J);\n250 IF J < U1 THEN PRINT \",\";\n260 NEXT J\n270 PRINT \"}\";\n280 IF I < U2 THEN PRINT \" x \";\n290 NEXT I\n300 PRINT \" = {\";\n310 FOR I = 1 TO U1\n320 FOR J = 1 TO U2\n330 PRINT \"{\"; ARR(1,I); \",\"; ARR(2,J); \"}\";\n340 IF I < U2 THEN PRINT \", \";\n350 IF I => U2 THEN IF J < U1 THEN PRINT \",\";\n360 NEXT J\n370 NEXT I\n380 PRINT \"}\"\n390 RETURN\n", "language": "GW-BASIC" }, { "code": "cartProd :: [a] -> [b] -> [(a, b)]\ncartProd xs ys =\n [ (x, y)\n | x <- xs\n , y <- ys ]\n", "language": "Haskell" }, { "code": "cartProd :: [a] -> [b] -> [(a, b)]\ncartProd xs ys = xs >>= \\x -> ys >>= \\y -> [(x, y)]\n", "language": "Haskell" }, { "code": "cartProd :: [a] -> [b] -> [(a, b)]\ncartProd xs ys = (,) <$> xs <*> ys\n", "language": "Haskell" }, { "code": "cartProd :: [a] -> [b] -> [(a, b)]\ncartProd = (<*>) . fmap (,)\n", "language": "Haskell" }, { "code": "main :: IO ()\nmain =\n mapM_ print $\n uncurry cartProd <$>\n [([1, 2], [3, 4]), ([3, 4], [1, 2]), ([1, 2], []), ([], [1, 2])]\n", "language": "Haskell" }, { "code": "cartProdN :: [[a]] -> [[a]]\ncartProdN = sequence\n\nmain :: IO ()\nmain = print $ cartProdN [[1, 2], [3, 4], [5, 6]]\n", "language": "Haskell" }, { "code": "cartProdN :: [[a]] -> [[a]]\ncartProdN = foldr (\\xs as -> xs >>= (<$> as) . (:)) [[]]\n", "language": "Haskell" }, { "code": "cartProdN :: [[a]] -> [[a]]\ncartProdN = foldr\n (\\xs as ->\n [ x : a\n | x <- xs\n , a <- as ])\n [[]]\n", "language": "Haskell" }, { "code": "main :: IO ()\nmain = do\n mapM_ print $\n cartProdN [[1776, 1789], [7,12], [4, 14, 23], [0,1]]\n putStrLn \"\"\n print $ cartProdN [[1,2,3], [30], [500, 100]]\n putStrLn \"\"\n print $ cartProdN [[1,2,3], [], [500, 100]]\n", "language": "Haskell" }, { "code": " { 1776 1789 ; 7 12 ; 4 14 23 ; 0 1 NB. result is 4 dimensional array with shape 2 2 3 2\n┌────────────┬────────────┐\n│1776 7 4 0 │1776 7 4 1 │\n├────────────┼────────────┤\n│1776 7 14 0 │1776 7 14 1 │\n├────────────┼────────────┤\n│1776 7 23 0 │1776 7 23 1 │\n└────────────┴────────────┘\n\n┌────────────┬────────────┐\n│1776 12 4 0 │1776 12 4 1 │\n├────────────┼────────────┤\n│1776 12 14 0│1776 12 14 1│\n├────────────┼────────────┤\n│1776 12 23 0│1776 12 23 1│\n└────────────┴────────────┘\n\n\n┌────────────┬────────────┐\n│1789 7 4 0 │1789 7 4 1 │\n├────────────┼────────────┤\n│1789 7 14 0 │1789 7 14 1 │\n├────────────┼────────────┤\n│1789 7 23 0 │1789 7 23 1 │\n└────────────┴────────────┘\n\n┌────────────┬────────────┐\n│1789 12 4 0 │1789 12 4 1 │\n├────────────┼────────────┤\n│1789 12 14 0│1789 12 14 1│\n├────────────┼────────────┤\n│1789 12 23 0│1789 12 23 1│\n└────────────┴────────────┘\n { 1 2 3 ; 30 ; 50 100 NB. result is a 2-dimensional array with shape 2 3\n┌───────┬────────┐\n│1 30 50│1 30 100│\n├───────┼────────┤\n│2 30 50│2 30 100│\n├───────┼────────┤\n│3 30 50│3 30 100│\n└───────┴────────┘\n { 1 2 3 ; '' ; 50 100 NB. result is an empty 3-dimensional array with shape 3 0 2\n", "language": "J" }, { "code": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n public List<?> product(List<?>... a) {\n if (a.length >= 2) {\n List<?> product = a[0];\n for (int i = 1; i < a.length; i++) {\n product = product(product, a[i]);\n }\n return product;\n }\n\n return emptyList();\n }\n\n private <A, B> List<?> product(List<A> a, List<B> b) {\n return of(a.stream()\n .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n .flatMap(List::stream)\n .collect(toList())).orElse(emptyList());\n }\n}\n", "language": "Java" }, { "code": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class CartesianProduct<V> {\n\n\tpublic List<List<V>> product(List<List<V>> lists) {\n\t\tList<List<V>> product = new ArrayList<>();\n\n\t\t// We first create a list for each value of the first list\n\t\tproduct(product, new ArrayList<>(), lists);\n\n\t\treturn product;\n\t}\n\n\tprivate void product(List<List<V>> result, List<V> existingTupleToComplete, List<List<V>> valuesToUse) {\n\t\tfor (V value : valuesToUse.get(0)) {\n\t\t\tList<V> newExisting = new ArrayList<>(existingTupleToComplete);\n\t\t\tnewExisting.add(value);\n\n\t\t\t// If only one column is left\n\t\t\tif (valuesToUse.size() == 1) {\n\t\t\t\t// We create a new list with the exiting tuple for each value with the value\n\t\t\t\t// added\n\t\t\t\tresult.add(newExisting);\n\t\t\t} else {\n\t\t\t\t// If there are still several columns, we go into recursion for each value\n\t\t\t\tList<List<V>> newValues = new ArrayList<>();\n\t\t\t\t// We build the next level of values\n\t\t\t\tfor (int i = 1; i < valuesToUse.size(); i++) {\n\t\t\t\t\tnewValues.add(valuesToUse.get(i));\n\t\t\t\t}\n\n\t\t\t\tproduct(result, newExisting, newValues);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tList<Integer> list1 = new ArrayList<>(Arrays.asList(new Integer[] { 1776, 1789 }));\n\t\tList<Integer> list2 = new ArrayList<>(Arrays.asList(new Integer[] { 7, 12 }));\n\t\tList<Integer> list3 = new ArrayList<>(Arrays.asList(new Integer[] { 4, 14, 23 }));\n\t\tList<Integer> list4 = new ArrayList<>(Arrays.asList(new Integer[] { 0, 1 }));\n\n\t\tList<List<Integer>> input = new ArrayList<>();\n\t\tinput.add(list1);\n\t\tinput.add(list2);\n\t\tinput.add(list3);\n\t\tinput.add(list4);\n\n\t\tCartesianProduct<Integer> cartesianProduct = new CartesianProduct<>();\n\t\tList<List<Integer>> product = cartesianProduct.product(input);\n\t\tSystem.out.println(product);\n\t}\n}\n", "language": "Java" }, { "code": "(() => {\n // CARTESIAN PRODUCT OF TWO LISTS ---------------------\n\n // cartProd :: [a] -> [b] -> [[a, b]]\n const cartProd = xs => ys =>\n xs.flatMap(x => ys.map(y => [x, y]))\n\n\n // TEST -----------------------------------------------\n return [\n cartProd([1, 2])([3, 4]),\n cartProd([3, 4])([1, 2]),\n cartProd([1, 2])([]),\n cartProd([])([1, 2]),\n ].map(JSON.stringify).join('\\n');\n})();\n", "language": "JavaScript" }, { "code": "(() => {\n\n // CARTESIAN PRODUCT OF TWO LISTS ---------------------\n\n // cartesianProduct :: [a] -> [b] -> [(a, b)]\n const cartesianProduct = xs =>\n ap(xs.map(Tuple));\n\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // e.g. [(*2),(/2), sqrt] <*> [1,2,3]\n // --> ap([dbl, hlf, root], [1, 2, 3])\n // --> [2,4,6,0.5,1,1.5,1,1.4142135623730951,1.7320508075688772]\n\n // Each member of a list of functions applied to each\n // of a list of arguments, deriving a list of new values.\n\n // ap (<*>) :: [(a -> b)] -> [a] -> [b]\n const ap = fs => xs =>\n // The sequential application of each of a list\n // of functions to each of a list of values.\n fs.flatMap(\n f => xs.map(f)\n );\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a => b => [a, b];\n\n // TEST -----------------------------------------------\n return [\n cartesianProduct([1, 2])([3, 4]),\n cartesianProduct([3, 4])([1, 2]),\n cartesianProduct([1, 2])([]),\n cartesianProduct([])([1, 2]),\n ]\n .map(JSON.stringify)\n .join('\\n');\n})();\n", "language": "JavaScript" }, { "code": "(() => {\n const main = () => {\n // n-ary Cartesian product of a list of lists.\n\n // cartProdN :: [[a]] -> [[a]]\n const cartProdN = foldr(\n xs => as =>\n bind(as)(\n x => bind(xs)(\n a => [\n [a].concat(x)\n ]\n )\n )\n )([\n []\n ]);\n\n // TEST -------------------------------------------\n return intercalate('\\n\\n')([\n map(show)(\n cartProdN([\n [1776, 1789],\n [7, 12],\n [4, 14, 23],\n [0, 1]\n ])\n ).join('\\n'),\n show(cartProdN([\n [1, 2, 3],\n [30],\n [50, 100]\n ])),\n show(cartProdN([\n [1, 2, 3],\n [],\n [50, 100]\n ]))\n ])\n };\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // bind :: [a] -> (a -> [b]) -> [b]\n const bind = xs => f => xs.flatMap(f);\n\n // foldr :: (a -> b -> b) -> b -> [a] -> b\n const foldr = f => a => xs =>\n xs.reduceRight((a, x) => f(x)(a), a);\n\n // intercalate :: String -> [a] -> String\n const intercalate = s => xs => xs.join(s);\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f => xs => xs.map(f);\n\n // show :: a -> String\n const show = x => JSON.stringify(x);\n\n return main();\n})();\n", "language": "JavaScript" }, { "code": "(() => {\n // n-ary Cartesian product of a list of lists\n // ( Imperative implementation )\n\n // cartProd :: [a] -> [b] -> [[a, b]]\n const cartProd = lists => {\n let ps = [],\n acc = [\n []\n ],\n i = lists.length;\n while (i--) {\n let subList = lists[i],\n j = subList.length;\n while (j--) {\n let x = subList[j],\n k = acc.length;\n while (k--) ps.push([x].concat(acc[k]))\n };\n acc = ps;\n ps = [];\n };\n return acc.reverse();\n };\n\n // GENERIC FUNCTIONS ------------------------------------------------------\n\n // intercalate :: String -> [a] -> String\n const intercalate = (s, xs) => xs.join(s);\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // show :: a -> String\n const show = x => JSON.stringify(x);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // TEST -------------------------------------------------------------------\n return intercalate('\\n\\n', [show(cartProd([\n [1, 2],\n [3, 4]\n ])),\n show(cartProd([\n [3, 4],\n [1, 2]\n ])),\n show(cartProd([\n [1, 2],\n []\n ])),\n show(cartProd([\n [],\n [1, 2]\n ])),\n unlines(map(show, cartProd([\n [1776, 1789],\n [7, 12],\n [4, 14, 23],\n [0, 1]\n ]))),\n show(cartProd([\n [1, 2, 3],\n [30],\n [50, 100]\n ])),\n show(cartProd([\n [1, 2, 3],\n [],\n [50, 100]\n ]))\n ]);\n})();\n", "language": "JavaScript" }, { "code": "def products: .[0][] as $x | .[1][] as $y | [$x,$y];\n", "language": "Jq" }, { "code": "def product: [products];\n", "language": "Jq" }, { "code": "[[1,2], []] | product\n", "language": "Jq" }, { "code": "def cartesians:\n if length <= 2 then products\n else .[0][] as $x\n | (.[1:] | cartesians) as $y\n | [$x] + $y\n end;\n", "language": "Jq" }, { "code": "# Product {1, 2} × {3, 4}\ncollect(Iterators.product([1, 2], [3, 4]))\n# Product {3, 4} × {1, 2}\ncollect(Iterators.product([3, 4], [1, 2]))\n\n# Product {1, 2} × {}\ncollect(Iterators.product([1, 2], []))\n# Product {} × {1, 2}\ncollect(Iterators.product([], [1, 2]))\n\n# Product {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}\ncollect(Iterators.product([1776, 1789], [7, 12], [4, 14, 23], [0, 1]))\n# Product {1, 2, 3} × {30} × {500, 100}\ncollect(Iterators.product([1, 2, 3], [30], [500, 100]))\n# Product {1, 2, 3} × {} × {500, 100}\ncollect(Iterators.product([1, 2, 3], [], [500, 100]))\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nfun flattenList(nestList: List<Any>): List<Any> {\n val flatList = mutableListOf<Any>()\n\n fun flatten(list: List<Any>) {\n for (e in list) {\n if (e !is List<*>)\n flatList.add(e)\n else\n @Suppress(\"UNCHECKED_CAST\")\n flatten(e as List<Any>)\n }\n }\n\n flatten(nestList)\n return flatList\n}\n\noperator fun List<Any>.times(other: List<Any>): List<List<Any>> {\n val prod = mutableListOf<List<Any>>()\n for (e in this) {\n for (f in other) {\n prod.add(listOf(e, f))\n }\n }\n return prod\n}\n\nfun nAryCartesianProduct(lists: List<List<Any>>): List<List<Any>> {\n require(lists.size >= 2)\n return lists.drop(2).fold(lists[0] * lists[1]) { cp, ls -> cp * ls }.map { flattenList(it) }\n}\n\nfun printNAryProduct(lists: List<List<Any>>) {\n println(\"${lists.joinToString(\" x \")} = \")\n println(\"[\")\n println(nAryCartesianProduct(lists).joinToString(\"\\n \", \" \"))\n println(\"]\\n\")\n}\n\nfun main(args: Array<String>) {\n println(\"[1, 2] x [3, 4] = ${listOf(1, 2) * listOf(3, 4)}\")\n println(\"[3, 4] x [1, 2] = ${listOf(3, 4) * listOf(1, 2)}\")\n println(\"[1, 2] x [] = ${listOf(1, 2) * listOf()}\")\n println(\"[] x [1, 2] = ${listOf<Any>() * listOf(1, 2)}\")\n println(\"[1, a] x [2, b] = ${listOf(1, 'a') * listOf(2, 'b')}\")\n println()\n printNAryProduct(listOf(listOf(1776, 1789), listOf(7, 12), listOf(4, 14, 23), listOf(0, 1)))\n printNAryProduct(listOf(listOf(1, 2, 3), listOf(30), listOf(500, 100)))\n printNAryProduct(listOf(listOf(1, 2, 3), listOf<Int>(), listOf(500, 100)))\n printNAryProduct(listOf(listOf(1, 2, 3), listOf(30), listOf('a', 'b')))\n}\n", "language": "Kotlin" }, { "code": "val .X = fn(... .x) .x\n\nwriteln mapX(.X, [1, 2], [3, 4]) == [[1, 3], [1, 4], [2, 3], [2, 4]]\nwriteln mapX(.X, [3, 4], [1, 2]) == [[3, 1], [3, 2], [4, 1], [4, 2]]\nwriteln mapX(.X, [1, 2], []) == []\nwriteln mapX(.X, [], [1, 2]) == []\nwriteln()\n\nwriteln mapX .X, [1776, 1789], [7, 12], [4, 14, 23], [0, 1]\nwriteln()\n\nwriteln mapX .X, [1, 2, 3], [30], [500, 100]\nwriteln()\n\nwriteln mapX .X, [1, 2, 3], [], [500, 100]\nwriteln()\n", "language": "Langur" }, { "code": " local pk,upk = table.pack, table.unpack\n local getn = function(t)return #t end\n local const = function(k)return function(e) return k end end\n local function attachIdx(f)-- one-time-off function modifier\n local idx = 0\n return function(e)idx=idx+1 ; return f(e,idx)end\n end\n\n local function reduce(t,acc,f)\n for i=1,t.n or #t do acc=f(acc,t[i])end\n return acc\n end\n local function imap(t,f)\n local r = {n=t.n or #t, r=reduce, u=upk, m=imap}\n for i=1,r.n do r[i]=f(t[i])end\n return r\n end\n\n local function prod(...)\n local ts = pk(...)\n local limit = imap(ts,getn)\n local idx, cnt = imap(limit,const(1)), 0\n local max = reduce(limit,1,function(a,b)return a*b end)\n local function ret(t,i)return t[idx[i]] end\n return function()\n if cnt>=max then return end -- no more output\n if cnt==0 then -- skip for 1st\n cnt = cnt + 1\n else\n cnt, idx[#idx] = cnt + 1, idx[#idx] + 1\n for i=#idx,2,-1 do -- update index list\n if idx[i]<=limit[i] then\n break -- no further update need\n else -- propagate limit overflow\n idx[i],idx[i-1] = 1, idx[i-1]+1\n end\n end\n end\n return cnt,imap(ts,attachIdx(ret)):u()\n end\n end\n--- test\n for i,a,b in prod({1,2},{3,4}) do\n print(i,a,b)\n end\n print()\n for i,a,b in prod({3,4},{1,2}) do\n print(i,a,b)\n end\n", "language": "Lua" }, { "code": "local function cartesian_product(sets)\n local result = {}\n local set_count = #sets\n--[[ I believe that this should make the below go very slightly faster, because it doesn't need to lookup yield in coroutine each time it\n yields, though perhaps the compiler optimises the lookup away? ]]\n local yield = coroutine.yield\n local function descend(depth)\n if depth == set_count then\n for k,v in pairs(sets[depth]) do\n result[depth] = v\n yield(result)\n end\n else\n for k,v in pairs(sets[depth]) do\n result[depth] = v\n descend(depth + 1)\n end\n end\n end\n return coroutine.wrap(function() descend(1) end)\nend\n\n--- tests\nlocal test_cases = {\n {{1, 2}, {3, 4}},\n {{3, 4}, {1, 2}},\n {{1776, 1789}, {7, 12}, {4, 14, 23}, {0,1}},\n {{1,2,3}, {30}, {500, 100}},\n {{1,2,3}, {}, {500, 100}}\n}\n\nlocal function format_nested_list(list)\n if list[1] and type(list[1]) == \"table\" then\n local formatted_items = {}\n for i, item in ipairs(list) do\n formatted_items[i] = format_nested_list(item)\n end\n return format_nested_list(formatted_items)\n else\n return \"{\" .. table.concat(list, \",\") .. \"}\"\n end\nend\n\nfor _,test_case in ipairs(test_cases) do\n print(format_nested_list(test_case))\n for product in cartesian_product(test_case) do\n print(\" \" .. format_nested_list(product))\n end\nend\n", "language": "Lua" }, { "code": "local function cartesian_product(sets)\n local item_counts = {}\n local indices = {}\n local results = {}\n local set_count = #sets\n local combination_count = 1\n\n for set_index=set_count, 1, -1 do\n local set = sets[set_index]\n local item_count = #set\n item_counts[set_index] = item_count\n indices[set_index] = 1\n results[set_index] = set[1]\n combination_count = combination_count * item_count\n end\n\n local combination_index = 0\n\n return function()\n if combination_index >= combination_count then return end -- no more output\n\n if combination_index == 0 then goto skip_update end -- skip first index update\n\n indices[set_count] = indices[set_count] + 1\n\n for set_index=set_count, 1, -1 do -- update index list\n local set = sets[set_index]\n local index = indices[set_index]\n if index <= item_counts[set_index] then\n results[set_index] = set[index]\n break -- no further update needed\n else -- propagate item_counts overflow\n results[set_index] = set[1]\n indices[set_index] = 1\n if set_index > 1 then\n indices[set_index - 1] = indices[set_index - 1] + 1\n end\n end\n end\n\n ::skip_update::\n\n combination_index = combination_index + 1\n\n return combination_index, results\n end\nend\n--- tests\nlocal test_cases = {\n {{1, 2}, {3, 4}},\n {{3, 4}, {1, 2}},\n {{1776, 1789}, {7, 12}, {4, 14, 23}, {0,1}},\n {{1,2,3}, {30}, {500, 100}},\n {{1,2,3}, {}, {500, 100}}\n}\n\nlocal function format_nested_list(list)\n if list[1] and type(list[1]) == \"table\" then\n local formatted_items = {}\n for i, item in ipairs(list) do\n formatted_items[i] = format_nested_list(item)\n end\n return format_nested_list(formatted_items)\n else\n return \"{\" .. table.concat(list, \",\") .. \"}\"\n end\nend\n\nfor _,test_case in ipairs(test_cases) do\n print(format_nested_list(test_case))\n for i, product in cartesian_product(test_case) do\n print(i, format_nested_list(product))\n end\nend\n", "language": "Lua" }, { "code": "-- support:\nfunction T(t) return setmetatable(t, {__index=table}) end\ntable.clone = function(t) local s=T{} for k,v in ipairs(t) do s[k]=v end return s end\ntable.reduce = function(t,f,acc) for i=1,#t do acc=f(t[i],acc) end return acc end\n\n-- implementation:\nlocal function cartprod(sets)\n local temp, prod = T{}, T{}\n local function descend(depth)\n for _,v in ipairs(sets[depth]) do\n temp[depth] = v\n if (depth==#sets) then prod[#prod+1]=temp:clone() else descend(depth+1) end\n end\n end\n descend(1)\n return prod\nend\n\n-- demonstration:\ntests = {\n { {1, 2}, {3, 4} },\n { {3, 4}, {1, 2} },\n { {1, 2}, {} },\n { {}, {1, 2} },\n { {1776, 1789}, {7, 12}, {4, 14, 23}, {0, 1} },\n { {1, 2, 3}, {30}, {500, 100} },\n { {1, 2, 3}, {}, {500, 100} }\n}\nfor _,test in ipairs(tests) do\n local cp = cartprod(test)\n print(\"{\"..cp:reduce(function(t,a) return (a==\"\" and a or a..\", \")..\"(\"..t:concat(\", \")..\")\" end,\"\")..\"}\")\nend\n", "language": "Lua" }, { "code": "cartmulti := proc ()\n local m, v;\n if [] in {args} then\n return [];\n else\nm := Iterator:-CartesianProduct(args);\n for v in m do\n printf(\"%{}a\\n\", v);\n end do;\n end if;\n end proc;\n", "language": "Maple" }, { "code": "cartesianProduct[args__] := Flatten[Outer[List, args], Length[{args}] - 1]\n", "language": "Mathematica" }, { "code": "cartesian_product({1,2},{3,4});\n/* {[1,3],[1,4],[2,3],[2,4]} */\ncartesian_product({3,4},{1,2});\n/* {[3,1],[3,2],[4,1],[4,2]} */\ncartesian_product({1,2},{});\n/* {} */\ncartesian_product({},{1,2});\n/* {} */\n", "language": "Maxima" }, { "code": "cartesian_product_list([1,2],[3,4]);\n/* [[1,3],[1,4],[2,3],[2,4]] */\ncartesian_product_list([3,4],[1,2]);\n/* [[3,1],[3,2],[4,1],[4,2]] */\ncartesian_product_list([1,2],[]);\n/* [] */\ncartesian_product_list([],[1,2]);\n/* [] */\n", "language": "Maxima" }, { "code": "create_list([i,j],i,[1,2],j,[3,4]);\n/* [[1,3],[1,4],[2,3],[2,4]] */\ncreate_list([i,j],i,[3,4],j,[1,2]);\n/* [[3,1],[3,2],[4,1],[4,2]] */\ncreate_list([i,j],i,[1,2],j,[]);\n/* [] */\ncreate_list([i,j],i,[],j,[1,2]);\n/* [] */\n", "language": "Maxima" }, { "code": "my_cartesian(lst1,lst2):=create_list([i,j],i,lst1,j,lst2);\nn_ary_cartesian(singleargument):=block(lreduce(my_cartesian,singleargument),map(flatten,%%));\n\n[[1776,1789],[7,12],[4,14,23],[0,1]]$\nn_ary_cartesian(%);\n/* \t[[1776,7,4,0],[1776,7,4,1],[1776,7,14,0],[1776,7,14,1],[1776,7,23,0],[1776,7,23,1],[1776,12,4,0],[1776,12,4,1],[1776,12,14,0],[1776,12,14,1],[1776,12,23,0],[1776,12,23,1],[1789,7,4,0],[1789,7,4,1],[1789,7,14,0],[1789,7,14,1],[1789,7,23,0],[1789,7,23,1],[1789,12,4,0],[1789,12,4,1],[1789,12,14,0],[1789,12,14,1],[1789,12,23,0],[1789,12,23,1]] */\n\n[[1,2,3],[30],[500,100]]$\nn_ary_cartesian(%);\n/* [[1,30,500],[1,30,100],[2,30,500],[2,30,100],[3,30,500],[3,30,100]] */\n\n[[1,2,3],[],[500,100]]$\nn_ary_cartesian(%);\n/* [] */\n", "language": "Maxima" }, { "code": "MODULE CartesianProduct;\nFROM FormatString IMPORT FormatString;\nFROM Terminal IMPORT WriteString,WriteLn,ReadChar;\n\nPROCEDURE WriteInt(a : INTEGER);\nVAR buf : ARRAY[0..9] OF CHAR;\nBEGIN\n FormatString(\"%i\", buf, a);\n WriteString(buf)\nEND WriteInt;\n\nPROCEDURE Cartesian(a,b : ARRAY OF INTEGER);\nVAR i,j : CARDINAL;\nBEGIN\n WriteString(\"[\");\n FOR i:=0 TO HIGH(a) DO\n FOR j:=0 TO HIGH(b) DO\n IF (i>0) OR (j>0) THEN\n WriteString(\",\");\n END;\n WriteString(\"[\");\n WriteInt(a[i]);\n WriteString(\",\");\n WriteInt(b[j]);\n WriteString(\"]\")\n END\n END;\n WriteString(\"]\");\n WriteLn\nEND Cartesian;\n\nTYPE\n AP = ARRAY[0..1] OF INTEGER;\n E = ARRAY[0..0] OF INTEGER;\nVAR\n a,b : AP;\nBEGIN\n a := AP{1,2};\n b := AP{3,4};\n Cartesian(a,b);\n\n a := AP{3,4};\n b := AP{1,2};\n Cartesian(a,b);\n\n (* If there is a way to create an empty array, I do not know of it *)\n\n ReadChar\nEND CartesianProduct.\n", "language": "Modula-2" }, { "code": "iterator product[T1, T2](a: openArray[T1]; b: openArray[T2]): tuple[a: T1, b: T2] =\n # Yield the element of the cartesian product of \"a\" and \"b\".\n # Yield tuples rather than arrays as it allows T1 and T2 to be different.\n\n for x in a:\n for y in b:\n yield (x, y)\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nwhen isMainModule:\n\n from seqUtils import toSeq\n import strformat\n from strutils import addSep\n\n #-------------------------------------------------------------------------------------------------\n\n proc `$`[T1, T2](t: tuple[a: T1, b: T2]): string =\n ## Overloading of `$` to display a tuple without the field names.\n &\"({t.a}, {t.b})\"\n\n proc `$$`[T](s: seq[T]): string =\n ## New operator to display a sequence using mathematical set notation.\n result = \"{\"\n for item in s:\n result.addSep(\", \", 1)\n result.add($item)\n result.add('}')\n\n#-------------------------------------------------------------------------------------------------\n\n const Empty = newSeq[int]() # Empty list of \"int\".\n\n for (a, b) in [(@[1, 2], @[3, 4]),\n (@[3, 4], @[1, 2]),\n (@[1, 2], Empty ),\n ( Empty, @[1, 2])]:\n\n echo &\"{$$a} x {$$b} = {$$toSeq(product(a, b))}\"\n", "language": "Nim" }, { "code": "proc product[T](a: varargs[seq[T]]): seq[seq[T]] =\n ## Return the product of several sets (sequences).\n\n if a.len == 1:\n for x in a[0]:\n result.add(@[x])\n else:\n for x in a[0]:\n for s in product(a[1..^1]):\n result.add(x & s)\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nwhen isMainModule:\n\n import strformat\n\n let\n a = @[1, 2]\n b = @[3, 4]\n c = @[5, 6]\n echo &\"{a} x {b} x {c} = {product(a, b, c)}\"\n", "language": "Nim" }, { "code": "import macros\n\nmacro product(args: varargs[typed]): untyped =\n ## Macro to generate the code to build the product of several sequences.\n\n let t = args[0].getType()\n if t.kind != nnkBracketExpr or t[0].kind != nnkSym or $t[0] != \"seq\":\n error(\"Arguments must be sequences\", args)\n\n # Build the result type i.e. a tuple with \"args.len\" elements.\n # Fields are named \"f0\", \"f1\", etc.\n let tupleTyNode = newNimNode(nnkTupleTy)\n for idx, arg in args:\n let identDefsNode = newIdentDefs(ident('f' & $idx), arg.getType()[1])\n tupleTyNode.add(identDefsNode)\n\n # Build the nested for loops with counter \"i0\", \"i1\", etc.\n var stmtListNode = newStmtList()\n let loopsNode = nnkForStmt.newTree(ident(\"i0\"), ident($args[0]), stmtListNode)\n var idx = 0\n for arg in args[1..^1]:\n inc idx\n let loopNode = nnkForStmt.newTree(ident('i' & $idx), ident($arg))\n stmtListNode.add(loopNode)\n stmtListNode = newStmtList()\n loopNode.add(stmtListNode)\n\n # Build the instruction \"result.add(i1, i2,...)\".\n let parNode = newPar()\n let addNode = newCall(newDotExpr(ident(\"result\"), ident(\"add\")), parNode)\n for i, arg in args:\n parNode.add(ident('i' & $i))\n stmtListNode.add(addNode)\n\n # Build the tree.\n result = nnkStmtListExpr.newTree(\n nnkVarSection.newTree(\n newIdentDefs(\n ident(\"result\"),\n nnkBracketExpr.newTree(ident(\"seq\"), tupleTyNode))),\n loopsNode,\n ident(\"result\"))\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nwhen isMainModule:\n\n import strformat\n import strutils\n\n #-------------------------------------------------------------------------------------------------\n\n proc `$`[T: tuple](t: T): string =\n ## Overloading of `$` to display a tuple without the field names.\n result = \"(\"\n for f in t.fields:\n result.addSep(\", \", 1)\n result.add($f)\n result.add(']')\n\n proc `$$`[T](s: seq[T]): string =\n ## New operator to display a sequence using mathematical set notation.\n result = \"{\"\n for item in s:\n result.addSep(\", \", 1)\n result.add($item)\n result.add('}')\n\n #-------------------------------------------------------------------------------------------------\n\n var a = @[1, 2]\n var b = @['a', 'b']\n var c = @[false, true]\n echo &\"{$$a} x {$$b} x {$$c} = {$$product(a, b, c)}\"\n", "language": "Nim" }, { "code": "let rec product l1 l2 =\n match l1, l2 with\n | [], _ | _, [] -> []\n | h1::t1, h2::t2 -> (h1,h2)::(product [h1] t2)@(product t1 l2)\n;;\n\nproduct [1;2] [3;4];;\n(*- : (int * int) list = [(1, 3); (1, 4); (2, 3); (2, 4)]*)\nproduct [3;4] [1;2];;\n(*- : (int * int) list = [(3, 1); (3, 2); (4, 1); (4, 2)]*)\nproduct [1;2] [];;\n(*- : (int * 'a) list = []*)\nproduct [] [1;2];;\n(*- : ('a * int) list = []*)\n", "language": "OCaml" }, { "code": "let product' l1 l2 =\n let rec aux ~acc l1' l2' =\n match l1', l2' with\n | [], _ | _, [] -> acc\n | h1::t1, h2::t2 ->\n let acc = (h1,h2)::acc in\n let acc = aux ~acc t1 l2' in\n aux ~acc [h1] t2\n in aux [] l1 l2\n;;\n\nproduct' [1;2] [3;4];;\n(*- : (int * int) list = [(1, 4); (2, 4); (2, 3); (1, 3)]*)\nproduct' [3;4] [1;2];;\n(*- : (int * int) list = [(3, 2); (4, 2); (4, 1); (3, 1)]*)\nproduct' [1;2] [];;\n(*- : (int * 'a) list = []*)\nproduct' [] [1;2];;\n(*- : ('a * int) list = []*)\n", "language": "OCaml" }, { "code": "let cart_prod l1 l2 =\n List.fold_left (fun acc1 ele1 ->\n List.fold_left (fun acc2 ele2 -> (ele1,ele2)::acc2) acc1 l2) [] l1 ;;\n\ncart_prod [1; 2; 3] ['a'; 'b'; 'c'] ;;\n(*- : (int * char) list = [(3, 'c'); (3, 'b'); (3, 'a'); (2, 'c'); (2, 'b'); (2, 'a'); (1, 'c'); (1, 'b'); (1, 'a')]*)\ncart_prod [1; 2; 3] [] ;;\n(*- : ('a * int) list = [] *)\n", "language": "OCaml" }, { "code": "let rec product'' l =\n (* We need to do the cross product of our current list and all the others\n * so we define a helper function for that *)\n let rec aux ~acc l1 l2 = match l1, l2 with\n | [], _ | _, [] -> acc\n | h1::t1, h2::t2 ->\n let acc = (h1::h2)::acc in\n let acc = (aux ~acc t1 l2) in\n aux ~acc [h1] t2\n (* now we can do the actual computation *)\n in match l with\n | [] -> []\n | [l1] -> List.map (fun x -> [x]) l1\n | l1::tl ->\n let tail_product = product'' tl in\n aux ~acc:[] l1 tail_product\n\n\nproduct'' [[1;2];[3;4]];;\n(*- : int list list = [[1; 4]; [2; 4]; [2; 3]; [1; 3]]*)\nproduct'' [[3;4];[1;2]];;\n(*- : int list list = [[3; 2]; [4; 2]; [4; 1]; [3; 1]]*)\nproduct'' [[1;2];[]];;\n(*- : int list list = []*)\nproduct'' [[];[1;2]];;\n(*- : int list list = []*)\nproduct'' [[1776; 1789];[7; 12];[4; 14; 23];[0; 1]];;\n(*\n- : int list list =\n\n[[1776; 7; 4; 1]; [1776; 12; 4; 1]; [1776; 12; 14; 1]; [1776; 12; 23; 1];\n [1776; 12; 23; 0]; [1776; 12; 14; 0]; [1776; 12; 4; 0]; [1776; 7; 14; 1];\n [1776; 7; 23; 1]; [1776; 7; 23; 0]; [1776; 7; 14; 0]; [1789; 7; 4; 1];\n [1789; 12; 4; 1]; [1789; 12; 14; 1]; [1789; 12; 23; 1]; [1789; 12; 23; 0];\n [1789; 12; 14; 0]; [1789; 12; 4; 0]; [1789; 7; 14; 1]; [1789; 7; 23; 1];\n [1789; 7; 23; 0]; [1789; 7; 14; 0]; [1789; 7; 4; 0]; [1776; 7; 4; 0]]\n*)\nproduct'' [[1; 2; 3];[30];[500; 100]];;\n(*\n- : int list list =\n\n[[1; 30; 500]; [2; 30; 500]; [3; 30; 500]; [3; 30; 100]; [2; 30; 100];\n [1; 30; 100]]\n*)\nproduct'' [[1; 2; 3];[];[500; 100]];;\n(*- : int list list = []*)\n", "language": "OCaml" }, { "code": "val product'' : 'a list list -> 'a list list = <fun>\n", "language": "OCaml" }, { "code": "type 'a tuple = 'a list\n\nlet rec product'' (l:'a list tuple) =\n (* We need to do the cross product of our current list and all the others\n * so we define a helper function for that *)\n let rec aux ~acc l1 l2 = match l1, l2 with\n | [], _ | _, [] -> acc\n | h1::t1, h2::t2 ->\n let acc = (h1::h2)::acc in\n let acc = (aux ~acc t1 l2) in\n aux ~acc [h1] t2\n (* now we can do the actual computation *)\n in match l with\n | [] -> []\n | [l1] -> List.map ~f:(fun x -> ([x]:'a tuple)) l1\n | l1::tl ->\n let tail_product = product'' tl in\n aux ~acc:[] l1 tail_product\n;;\n\ntype 'a tuple = 'a list\nval product'' : 'a list tuple -> 'a tuple list = <fun>\n", "language": "OCaml" }, { "code": "sub cartesian {\n my $sets = shift @_;\n for (@$sets) { return [] unless @$_ }\n\n my $products = [[]];\n for my $set (reverse @$sets) {\n my $partial = $products;\n $products = [];\n for my $item (@$set) {\n for my $product (@$partial) {\n push @$products, [$item, @$product];\n }\n }\n }\n $products;\n}\n\nsub product {\n my($s,$fmt) = @_;\n my $tuples;\n for $a ( @{ cartesian( \\@$s ) } ) { $tuples .= sprintf \"($fmt) \", @$a; }\n $tuples . \"\\n\";\n}\n\nprint\nproduct([[1, 2], [3, 4] ], '%1d %1d' ).\nproduct([[3, 4], [1, 2] ], '%1d %1d' ).\nproduct([[1, 2], [] ], '%1d %1d' ).\nproduct([[], [1, 2] ], '%1d %1d' ).\nproduct([[1,2,3], [30], [500,100] ], '%1d %1d %3d' ).\nproduct([[1,2,3], [], [500,100] ], '%1d %1d %3d' ).\nproduct([[1776,1789], [7,12], [4,14,23], [0,1]], '%4d %2d %2d %1d')\n", "language": "Perl" }, { "code": "$tuples = [ map { [split /:/] } glob '{1,2,3}:{30}:{500,100}' ];\n\nfor $a (@$tuples) { printf \"(%1d %2d %3d) \", @$a; }\n", "language": "Perl" }, { "code": "use ntheory qw/forsetproduct/;\nforsetproduct { say \"@_\" } [1,2,3],[qw/a b c/],[qw/@ $ !/];\n\nuse Set::Product qw/product/;\nproduct { say \"@_\" } [1,2,3],[qw/a b c/],[qw/@ $ !/];\n\nuse Math::Cartesian::Product;\ncartesian { say \"@_\" } [1,2,3],[qw/a b c/],[qw/@ $ !/];\n\nuse Algorithm::Loops qw/NestedLoops/;\nNestedLoops([[1,2,3],[qw/a b c/],[qw/@ $ !/]], sub { say \"@_\"; });\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">cart</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]&</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">cart</span><span style=\"color: #0000FF;\">({{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">}})</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">cart</span><span style=\"color: #0000FF;\">({{</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">}})</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">cart</span><span style=\"color: #0000FF;\">({{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},{}})</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">cart</span><span style=\"color: #0000FF;\">({{},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">}})</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">cart</span><span style=\"color: #0000FF;\">({{</span><span style=\"color: #000000;\">1776</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1789</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">14</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">23</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}})</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">cart</span><span style=\"color: #0000FF;\">({{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">30</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">500</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">}})</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">cart</span><span style=\"color: #0000FF;\">({{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},{},{</span><span style=\"color: #000000;\">500</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">}})</span>\n<!--\n", "language": "Phix" }, { "code": "include ..\\Utilitys.pmt\n\ndef cart\n ( ) var res\n -1 get var ta -1 del\n -1 get var he -1 del\n ta \"\" != he \"\" != and if\n he len nip for\n he swap get var h drop\n ta len nip for\n ta swap get var t drop\n ( h t ) flatten res swap 0 put var res\n endfor\n endfor\n len if res 0 put cart endif\n endif\nenddef\n\n/# ---------- MAIN ---------- #/\n\n( ( 1 2 ) ( 3 4 ) ) cart\ndrop res print nl nl\n\n( ( 1776 1789 ) ( 7 12 ) ( 4 14 23 ) ( 0 1 ) ) cart\ndrop res print nl nl\n\n( ( 1 2 3 ) ( 30 ) ( 500 100 ) ) cart\ndrop res print nl nl\n\n( ( 1 2 ) ( ) ) cart\ndrop res print nl nl\n", "language": "Phixmonti" }, { "code": "(de 2lists (L1 L2)\n (mapcan\n '((I)\n (mapcar\n '((A) ((if (atom A) list cons) I A))\n L2 ) )\n L1 ) )\n(de reduce (L . @)\n (ifn (rest) L (2lists L (apply reduce (rest)))) )\n(de cartesian (L . @)\n (and L (rest) (pass reduce L)) )\n\n(println\n (cartesian (1 2)) )\n(println\n (cartesian NIL (1 2)) )\n(println\n (cartesian (1 2) (3 4)) )\n(println\n (cartesian (3 4) (1 2)) )\n(println\n (cartesian (1776 1789) (7 12) (4 14 23) (0 1)) )\n(println\n (cartesian (1 2 3) (30) (500 100)) )\n(println\n (cartesian (1 2 3) NIL (500 100)) )\n", "language": "PicoLisp" }, { "code": "product([A|_], Bs, [A, B]) :- member(B, Bs).\nproduct([_|As], Bs, X) :- product(As, Bs, X).\n", "language": "Prolog" }, { "code": "import itertools\n\ndef cp(lsts):\n return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n from pprint import pprint as pp\n\n for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)),\n ((1, 2, 3), (30,), (500, 100)),\n ((1, 2, 3), (), (500, 100))]:\n print(lists, '=>')\n pp(cp(lists), indent=2)\n", "language": "Python" }, { "code": "# ap (<*>) :: [(a -> b)] -> [a] -> [b]\ndef ap(fs):\n return lambda xs: foldl(\n lambda a: lambda f: a + foldl(\n lambda a: lambda x: a + [f(x)])([])(xs)\n )([])(fs)\n", "language": "Python" }, { "code": "ap(map(Tuple, xs))\n", "language": "Python" }, { "code": "# nAryCartProd :: [[a], [b], [c] ...] -> [(a, b, c ...)]\ndef nAryCartProd(xxs):\n return foldl1(cartesianProduct)(\n xxs\n )\n", "language": "Python" }, { "code": "# Two lists -> list of tuples\n\n\n# cartesianProduct :: [a] -> [b] -> [(a, b)]\ndef cartesianProduct(xs):\n return ap(map(Tuple, xs))\n\n\n# List of lists -> list of tuples\n\n# nAryCartProd :: [[a], [b], [c] ...] -> [(a, b, c ...)]\ndef nAryCartProd(xxs):\n return foldl1(cartesianProduct)(\n xxs\n )\n\n\n# main :: IO ()\ndef main():\n # Product of lists of different types\n print (\n 'Product of two lists of different types:'\n )\n print(\n cartesianProduct(['a', 'b', 'c'])(\n [1, 2]\n )\n )\n\n # TESTS OF PRODUCTS OF TWO LISTS\n\n print(\n '\\nSpecified tests of products of two lists:'\n )\n print(\n cartesianProduct([1, 2])([3, 4]),\n ' <--> ',\n cartesianProduct([3, 4])([1, 2])\n )\n print (\n cartesianProduct([1, 2])([]),\n ' <--> ',\n cartesianProduct([])([1, 2])\n )\n\n # TESTS OF N-ARY CARTESIAN PRODUCTS\n\n print('\\nSpecified tests of nAry products:')\n for xs in nAryCartProd([[1776, 1789], [7, 12], [4, 14, 23], [0, 1]]):\n print(xs)\n\n for xs in (\n map_(nAryCartProd)(\n [\n [[1, 2, 3], [30], [500, 100]],\n [[1, 2, 3], [], [500, 100]]\n ]\n )\n ):\n print(\n xs\n )\n\n# GENERIC -------------------------------------------------\n\n\n# Applicative function for lists\n\n# ap (<*>) :: [(a -> b)] -> [a] -> [b]\ndef ap(fs):\n return lambda xs: foldl(\n lambda a: lambda f: a + foldl(\n lambda a: lambda x: a + [f(x)])([])(xs)\n )([])(fs)\n\n\n# foldl :: (a -> b -> a) -> a -> [b] -> a\ndef foldl(f):\n def go(v, xs):\n a = v\n for x in xs:\n a = f(a)(x)\n return a\n return lambda acc: lambda xs: go(acc, xs)\n\n\n# foldl1 :: (a -> a -> a) -> [a] -> a\ndef foldl1(f):\n return lambda xs: foldl(f)(xs[0])(\n xs[1:]\n ) if xs else None\n\n\n# map :: (a -> b) -> [a] -> [b]\ndef map_(f):\n return lambda xs: list(map(f, xs))\n\n\n# Tuple :: a -> b -> (a, b)\ndef Tuple(x):\n return lambda y: (\n x + (y,)\n ) if tuple is type(x) else (x, y)\n\n\n# TEST ----------------------------------------------------\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "DECLARE SUB cartesian (arr!())\n\nCLS\nDIM array(2, 2)\narray(1, 1) = 1: array(1, 2) = 2\narray(2, 1) = 3: array(2, 2) = 4\nCALL cartesian(array())\narray(1, 1) = 3: array(1, 2) = 4\narray(2, 1) = 1: array(2, 2) = 2\nCALL cartesian(array())\nEND\n\nSUB cartesian (arr())\nu1 = 2: u2 = 2\nFOR i = 1 TO u1\n PRINT \"{\";\n FOR j = 1 TO u2\n PRINT arr(i, j);\n IF j < u1 THEN PRINT \",\";\n NEXT j\n PRINT \"}\";\n IF i < u2 THEN PRINT \" x \";\nNEXT i\nPRINT \" = {\";\nFOR i = 1 TO u1\n FOR j = 1 TO u2\n PRINT \"{\"; arr(1, i); \",\"; arr(2, j); \"}\";\n IF i < u2 THEN\n PRINT \", \";\n ELSE\n IF j < u1 THEN PRINT \", \";\n END IF\n NEXT j\nNEXT i\nPRINT \"}\"\nEND SUB\n", "language": "QBasic" }, { "code": " [ [] unrot\n swap witheach\n [ over witheach\n [ over nested\n swap nested join\n nested dip rot join\n unrot ]\n drop ] drop ] is cartprod ( [ [ --> [ )\n\n ' [ 1 2 ] ' [ 3 4 ] cartprod echo cr\n ' [ 3 4 ] ' [ 1 2 ] cartprod echo cr\n ' [ 1 2 ] ' [ ] cartprod echo cr\n ' [ ] ' [ 1 2 ] cartprod echo cr\n", "language": "Quackery" }, { "code": "one_w_many <- function(one, many) lapply(many, function(x) c(one,x))\n\n# Let's define an infix operator to perform a cartesian product.\n\n\"%p%\" <- function( a, b ) {\n p = c( sapply(a, function (x) one_w_many(x, b) ) )\n if (is.null(unlist(p))) list() else p}\n\ndisplay_prod <-\n function (xs) { for (x in xs) cat( paste(x, collapse=\", \"), \"\\n\" ) }\n\nfmt_vec <- function(v) sprintf(\"(%s)\", paste(v, collapse=', '))\n\ngo <- function (...) {\n cat(\"\\n\", paste( sapply(list(...),fmt_vec), collapse=\" * \"), \"\\n\")\n prod = Reduce( '%p%', list(...) )\n display_prod( prod ) }\n", "language": "R" }, { "code": "> display_prod( c(1, 2) %p% c(3, 4) )\n1, 3\n1, 4\n2, 3\n2, 4\n> display_prod( c(3, 4) %p% c(1, 2) )\n3, 1\n3, 2\n4, 1\n4, 2\n> display_prod( c(3, 4) %p% c() )\n>\n", "language": "R" }, { "code": "go( c(1776, 1789), c(7, 12), c(4, 14, 23), c(0, 1) )\ngo( c(1, 2, 3), c(30), c(500, 100) )\ngo( c(1, 2, 3), c(), c(500, 100) )\n", "language": "R" }, { "code": "#lang racket/base\n(require rackunit\n ;; usually, included in \"racket\", but we're using racket/base so we\n ;; show where this comes from\n (only-in racket/list cartesian-product))\n;; these tests will pass silently\n(check-equal? (cartesian-product '(1 2) '(3 4))\n '((1 3) (1 4) (2 3) (2 4)))\n(check-equal? (cartesian-product '(3 4) '(1 2))\n '((3 1) (3 2) (4 1) (4 2)))\n(check-equal? (cartesian-product '(1 2) '()) '())\n(check-equal? (cartesian-product '() '(1 2)) '())\n\n;; these will print\n(cartesian-product '(1776 1789) '(7 12) '(4 14 23) '(0 1))\n(cartesian-product '(1 2 3) '(30) '(500 100))\n(cartesian-product '(1 2 3) '() '(500 100))\n", "language": "Racket" }, { "code": "# cartesian product of two lists using the X cross meta-operator\nsay (1, 2) X (3, 4);\nsay (3, 4) X (1, 2);\nsay (1, 2) X ( );\nsay ( ) X ( 1, 2 );\n\n# cartesian product of variable number of lists using\n# the [X] reduce cross meta-operator\nsay [X] (1776, 1789), (7, 12), (4, 14, 23), (0, 1);\nsay [X] (1, 2, 3), (30), (500, 100);\nsay [X] (1, 2, 3), (), (500, 100);\n", "language": "Raku" }, { "code": "/*REXX program calculates the Cartesian product of two arbitrary-sized lists. */\n@.= /*assign the default value to @. array*/\nparse arg @.1 /*obtain the optional value of @.1 */\nif @.1='' then do; @.1= \"{1,2} {3,4}\" /*Not specified? Then use the defaults*/\n @.2= \"{3,4} {1,2}\" /* \" \" \" \" \" \" */\n @.3= \"{1,2} {}\" /* \" \" \" \" \" \" */\n @.4= \"{} {3,4}\" /* \" \" \" \" \" \" */\n @.5= \"{1,2} {3,4,5}\" /* \" \" \" \" \" \" */\n end\n /* [↓] process each of the @.n values*/\n do n=1 while @.n \\= '' /*keep processing while there's a value*/\n z= translate( space( @.n, 0), , ',') /*translate the commas to blanks. */\n do #=1 until z=='' /*process each elements in first list. */\n parse var z '{' x.# '}' z /*parse the list (contains elements). */\n end /*#*/\n $=\n do i=1 for #-1 /*process the subsequent lists. */\n do a=1 for words(x.i) /*obtain the elements of the first list*/\n do j=i+1 for #-1 /* \" \" subsequent lists. */\n do b=1 for words(x.j) /* \" \" elements of subsequent list*/\n $=$',('word(x.i, a)\",\"word(x.j, b)')' /*append partial Cartesian product ──►$*/\n end /*b*/\n end /*j*/\n end /*a*/\n end /*i*/\n say 'Cartesian product of ' space(@.n) \" is ───► {\"substr($, 2)'}'\n end /*n*/ /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "/* REXX computes the Cartesian Product of up to 4 sets */\nCall cart '{1, 2} x {3, 4}'\nCall cart '{3, 4} x {1, 2}'\nCall cart '{1, 2} x {}'\nCall cart '{} x {1, 2}'\nCall cart '{1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}'\nCall cart '{1, 2, 3} x {30} x {500, 100}'\nCall cart '{1, 2, 3} x {} x {500, 100}'\nExit\n\ncart:\n Parse Arg sl\n Say sl\n Do i=1 By 1 while pos('{',sl)>0\n Parse Var sl '{' list '}' sl\n Do j=1 By 1 While list<>''\n Parse Var list e.i.j . ',' list\n End\n n.i=j-1\n If n.i=0 Then Do /* an empty set */\n Say '{}'\n Say ''\n Return\n End\n End\n n=i-1\n ct2.=0\n Do i=1 To n.1\n Do j=1 To n.2\n z=ct2.0+1\n ct2.z=e.1.i e.2.j\n ct2.0=z\n End\n End\n If n<3 Then\n Return output(2)\n ct3.=0\n Do i=1 To ct2.0\n Do k=1 To n.3\n z=ct3.0+1\n ct3.z=ct2.i e.3.k\n ct3.0=z\n End\n End\n If n<4 Then\n Return output(3)\n ct4.=0\n Do i=1 To ct3.0\n Do l=1 To n.4\n z=ct4.0+1\n ct4.z=ct3.i e.4.l\n ct4.0=z\n End\n End\n Return output(4)\n\noutput:\n Parse Arg u\n Do v=1 To value('ct'u'.0')\n res='{'translate(value('ct'u'.'v),',',' ')'}'\n Say res\n End\n Say ' '\n Return 0\n", "language": "REXX" }, { "code": "# Project : Cartesian product of two or more lists\n\nlist1 = [[1,2],[3,4]]\nlist2 = [[3,4],[1,2]]\ncartesian(list1)\ncartesian(list2)\n\nfunc cartesian(list1)\n for n = 1 to len(list1[1])\n for m = 1 to len(list1[2])\n see \"(\" + list1[1][n] + \", \" + list1[2][m] + \")\" + nl\n next\n next\n see nl\n", "language": "Ring" }, { "code": "p [1, 2].product([3, 4])\np [3, 4].product([1, 2])\np [1, 2].product([])\np [].product([1, 2])\np [1776, 1789].product([7, 12], [4, 14, 23], [0, 1])\np [1, 2, 3].product([30], [500, 100])\np [1, 2, 3].product([], [500, 100])\n", "language": "Ruby" }, { "code": "cls\ndim array(2,2)\narray(1,1) = 1 : array(1,2) = 2\narray(2,1) = 3 : array(2,2) = 4\ngosub [cartesian]\narray(1,1) = 3 : array(1,2) = 4\narray(2,1) = 1 : array(2,2) = 2\ngosub [cartesian]\nend\n\n[cartesian]\nu1 = 2 : u2 = 2\nfor i = 1 to u1\n print \"{\";\n for j = 1 to u2\n print array(i,j);\n if j < u1 then print \",\";\n next j\n print \"}\";\n if i < u2 then print \" x \";\nnext i\nprint \" = {\";\nfor i = 1 to u1\n for j = 1 to u2\n print \"{\"; array(1,i); \",\"; array(2,j); \"}\";\n if i < u2 then\n print \",\";\n else\n if j < u1 then print \",\";\n end if\n next j\nnext i\nprint \"}\"\nreturn\n", "language": "Run-BASIC" }, { "code": "fn cartesian_product(lists: &Vec<Vec<u32>>) -> Vec<Vec<u32>> {\n let mut res = vec![];\n\n let mut list_iter = lists.iter();\n if let Some(first_list) = list_iter.next() {\n for &i in first_list {\n res.push(vec![i]);\n }\n }\n for l in list_iter {\n let mut tmp = vec![];\n for r in res {\n for &el in l {\n let mut tmp_el = r.clone();\n tmp_el.push(el);\n tmp.push(tmp_el);\n }\n }\n res = tmp;\n }\n res\n}\n\nfn main() {\n let cases = vec![\n vec![vec![1, 2], vec![3, 4]],\n vec![vec![3, 4], vec![1, 2]],\n vec![vec![1, 2], vec![]],\n vec![vec![], vec![1, 2]],\n vec![vec![1776, 1789], vec![7, 12], vec![4, 14, 23], vec![0, 1]],\n vec![vec![1, 2, 3], vec![30], vec![500, 100]],\n vec![vec![1, 2, 3], vec![], vec![500, 100]],\n ];\n for case in cases {\n println!(\n \"{}\\n{:?}\\n\",\n case.iter().map(|c| format!(\"{:?}\", c)).collect::<Vec<_>>().join(\" × \"),\n cartesian_product(&case)\n )\n }\n}\n", "language": "Rust" }, { "code": "def cartesianProduct[T](lst: List[T]*): List[List[T]] = {\n\n /**\n * Prepend single element to all lists of list\n * @param e single elemetn\n * @param ll list of list\n * @param a accumulator for tail recursive implementation\n * @return list of lists with prepended element e\n */\n def pel(e: T,\n ll: List[List[T]],\n a: List[List[T]] = Nil): List[List[T]] =\n ll match {\n case Nil => a.reverse\n case x :: xs => pel(e, xs, (e :: x) :: a )\n }\n\n lst.toList match {\n case Nil => Nil\n case x :: Nil => List(x)\n case x :: _ =>\n x match {\n case Nil => Nil\n case _ =>\n lst.par.foldRight(List(x))( (l, a) =>\n l.flatMap(pel(_, a))\n ).map(_.dropRight(x.size))\n }\n }\n}\n", "language": "Scala" }, { "code": "cartesianProduct(List(1, 2), List(3, 4))\n .map(_.mkString(\"(\", \", \", \")\")).mkString(\"{\",\", \",\"}\")\n", "language": "Scala" }, { "code": "cartesianProduct(List(3, 4), List(1, 2))\n .map(_.mkString(\"(\", \", \", \")\")).mkString(\"{\",\", \",\"}\")\n", "language": "Scala" }, { "code": "cartesianProduct(List(1, 2), List.empty)\n .map(_.mkString(\"(\", \", \", \")\")).mkString(\"{\",\", \",\"}\")\n", "language": "Scala" }, { "code": "cartesianProduct(List.empty, List(1, 2))\n .map(_.mkString(\"(\", \", \", \")\")).mkString(\"{\",\", \",\"}\")\n", "language": "Scala" }, { "code": "cartesianProduct(List(1776, 1789), List(7, 12), List(4, 14, 23), List(0, 1))\n .map(_.mkString(\"(\", \", \", \")\")).mkString(\"{\",\", \",\"}\")\n", "language": "Scala" }, { "code": "cartesianProduct(List(1, 2, 3), List(30), List(500, 100))\n .map(_.mkString(\"(\", \", \", \")\")).mkString(\"{\",\", \",\"}\")\n", "language": "Scala" }, { "code": "cartesianProduct(List(1, 2, 3), List.empty, List(500, 100))\n .map(_.mkString(\"[\", \", \", \"]\")).mkString(\"\\n\")\n", "language": "Scala" }, { "code": "(define cartesian-product (lambda (xs ys)\n (if (or (zero? (length xs)) (zero? (length ys)))\n '()\n (fold append (map (lambda (x) (map (lambda (y) (list x y)) ys)) xs)))))\n\n(define nary-cartesian-product (lambda (ls)\n (if (fold (lambda (a b) (or a b)) (map (compose zero? length) ls))\n '()\n (map flatten (fold cartesian-product ls)))))\n\n> (cartesian-product '(1 2) '(3 4))\n((1 3) (1 4) (2 3) (2 4))\n> (cartesian-product '(3 4) '(1 2))\n((3 1) (3 2) (4 1) (4 2))\n> (cartesian-product '(1 2) '())\n()\n> (cartesian-product '() '(1 2))\n()\n> (nary-cartesian-product '((1 2)(a b)(x y)))\n((1 a x) (1 a y) (1 b x) (1 b y) (2 a x) (2 a y) (2 b x) (2 b y))\n", "language": "Scheme" }, { "code": "cartesian([[1,2], [3,4], [5,6]]).say\ncartesian([[1,2], [3,4], [5,6]], {|*arr| say arr })\n", "language": "Sidef" }, { "code": "func cartesian_product(*arr) {\n\n var c = []\n var r = []\n\n func {\n if (c.len < arr.len) {\n for item in (arr[c.len]) {\n c.push(item)\n __FUNC__()\n c.pop\n }\n }\n else {\n r.push([c...])\n }\n }()\n\n return r\n}\n", "language": "Sidef" }, { "code": "say cartesian_product([1,2], [3,4])\nsay cartesian_product([3,4], [1,2])\n", "language": "Sidef" }, { "code": "say cartesian_product([1,2], [])\nsay cartesian_product([], [1,2])\n", "language": "Sidef" }, { "code": "cartesian_product([1776, 1789], [7, 12], [4, 14, 23], [0, 1]).each{ .say }\n", "language": "Sidef" }, { "code": "say cartesian_product([1, 2, 3], [30], [500, 100])\nsay cartesian_product([1, 2, 3], [], [500, 100])\n", "language": "Sidef" }, { "code": "-- set up list 1\ncreate table L1 (value integer);\ninsert into L1 values (1);\ninsert into L1 values (2);\n-- set up list 2\ncreate table L2 (value integer);\ninsert into L2 values (3);\ninsert into L2 values (4);\n-- get the product\nselect * from L1, L2;\n", "language": "SQL" }, { "code": "select * from L1 cross join L2;\n", "language": "SQL" }, { "code": "delete from L2;\nselect * from L1, L2;\n", "language": "SQL" }, { "code": "insert into L1 values (3);\ninsert into L2 values (30);\ncreate table L3 (value integer);\ninsert into L3 values (500);\ninsert into L3 values (100);\n-- product works the same for as many \"lists\" as you'd like\nselect * from L1, L2, L3;\n", "language": "SQL" }, { "code": "fun prodList (nil, _) = nil\n | prodList ((x::xs), ys) = map (fn y => (x,y)) ys @ prodList (xs, ys)\n\nfun naryProdList zs = foldl (fn (xs, ys) => map op:: (prodList (xs, ys))) [[]] (rev zs)\n", "language": "Standard-ML" }, { "code": ". list\n\n +-------+\n | a b |\n |-------|\n 1. | 1 3 |\n 2. | 2 4 |\n +-------+\n\n. fillin a b\n. list\n\n +-----------------+\n | a b _fillin |\n |-----------------|\n 1. | 1 3 0 |\n 2. | 1 4 1 |\n 3. | 2 3 1 |\n 4. | 2 4 0 |\n +-----------------+\n", "language": "Stata" }, { "code": ". list\n\n +-------+\n | a b |\n |-------|\n 1. | 3 1 |\n 2. | 4 2 |\n +-------+\n\n. fillin a b\n. list\n\n +-----------------+\n | a b _fillin |\n |-----------------|\n 1. | 3 1 0 |\n 2. | 3 2 1 |\n 3. | 4 1 1 |\n 4. | 4 2 0 |\n +-----------------+\n", "language": "Stata" }, { "code": ". list\n\n +-------+\n | a b |\n |-------|\n 1. | 1 . |\n 2. | 2 . |\n +-------+\n\n. fillin a b\n. list\n\n +-----------------+\n | a b _fillin |\n |-----------------|\n 1. | 1 . 0 |\n 2. | 2 . 0 |\n +-----------------+\n", "language": "Stata" }, { "code": ". list\n\n +-----------+\n | a b c |\n |-----------|\n 1. | 1 4 6 |\n 2. | 2 5 . |\n 3. | 3 . . |\n +-----------+\n\n. fillin a b c\n. list\n\n +---------------------+\n | a b c _fillin |\n |---------------------|\n 1. | 1 4 6 0 |\n 2. | 1 4 . 1 |\n 3. | 1 5 6 1 |\n 4. | 1 5 . 1 |\n 5. | 1 . 6 1 |\n |---------------------|\n 6. | 1 . . 1 |\n 7. | 2 4 6 1 |\n 8. | 2 4 . 1 |\n 9. | 2 5 6 1 |\n 10. | 2 5 . 0 |\n |---------------------|\n 11. | 2 . 6 1 |\n 12. | 2 . . 1 |\n 13. | 3 4 6 1 |\n 14. | 3 4 . 1 |\n 15. | 3 5 6 1 |\n |---------------------|\n 16. | 3 5 . 1 |\n 17. | 3 . 6 1 |\n 18. | 3 . . 0 |\n +---------------------+\n\n. foreach var of varlist _all {\n quietly drop if missing(`var')\n }\n\n. list\n\n +---------------------+\n | a b c _fillin |\n |---------------------|\n 1. | 1 4 6 0 |\n 2. | 1 5 6 1 |\n 3. | 2 4 6 1 |\n 4. | 2 5 6 1 |\n 5. | 3 4 6 1 |\n |---------------------|\n 6. | 3 5 6 1 |\n +---------------------+\n", "language": "Stata" }, { "code": "func + <T>(el: T, arr: [T]) -> [T] {\n var ret = arr\n\n ret.insert(el, at: 0)\n\n return ret\n}\n\nfunc cartesianProduct<T>(_ arrays: [T]...) -> [[T]] {\n guard let head = arrays.first else {\n return []\n }\n\n let first = Array(head)\n\n func pel(\n _ el: T,\n _ ll: [[T]],\n _ a: [[T]] = []\n ) -> [[T]] {\n switch ll.count {\n case 0:\n return a.reversed()\n case _:\n let tail = Array(ll.dropFirst())\n let head = ll.first!\n\n return pel(el, tail, el + head + a)\n }\n }\n\n return arrays.reversed()\n .reduce([first], {res, el in el.flatMap({ pel($0, res) }) })\n .map({ $0.dropLast(first.count) })\n}\n\n\nprint(cartesianProduct([1, 2], [3, 4]))\nprint(cartesianProduct([3, 4], [1, 2]))\nprint(cartesianProduct([1, 2], []))\nprint(cartesianProduct([1776, 1789], [7, 12], [4, 14, 23], [0, 1]))\nprint(cartesianProduct([1, 2, 3], [30], [500, 100]))\nprint(cartesianProduct([1, 2, 3], [], [500, 100])\n", "language": "Swift" }, { "code": "'{1,2}x{3,4} = $:[by [1,2]..., by [3,4]...];\n' -> !OUT::write\n\n'{3,4}x{1,2} = $:[by [3,4]..., by [1,2]...];\n' -> !OUT::write\n\n'{1,2}x{} = $:[by [1,2]..., by []...];\n' -> !OUT::write\n\n'{}x{1,2} = $:[by []..., by [1,2]...];\n' -> !OUT::write\n\n'{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} = $:[by [1776, 1789]..., by [7, 12]..., by [4, 14, 23]..., by [0, 1]...];\n' -> !OUT::write\n\n'{1, 2, 3} × {30} × {500, 100} = $:[by [1, 2, 3] ..., by [30]..., by [500, 100]...];\n' -> !OUT::write\n\n'{1, 2, 3} × {} × {500, 100} = $:[by [1, 2, 3]..., by []..., by [500, 100]...];\n' -> !OUT::write\n\n// You can also generate structures with named fields\n'year {1776, 1789} × month {7, 12} × day {4, 14, 23} = $:{by [1776, 1789]... -> (year:$), by [7, 12]... -> (month:$), by [4, 14, 23]... -> (day:$)};\n' -> !OUT::write\n", "language": "Tailspin" }, { "code": "proc cartesianProduct {l1 l2} {\n set result {}\n foreach el1 $l1 {\n foreach el2 $l2 {\n lappend result [list $el1 $el2]\n }\n }\n return $result\n}\n\nputs \"simple\"\nputs \"result: [cartesianProduct {1 2} {3 4}]\"\nputs \"result: [cartesianProduct {3 4} {1 2}]\"\nputs \"result: [cartesianProduct {1 2} {}]\"\nputs \"result: [cartesianProduct {} {3 4}]\"\n\nproc cartesianNaryProduct {lists} {\n set result {{}}\n foreach l $lists {\n set res {}\n foreach comb $result {\n foreach el $l {\n lappend res [linsert $comb end $el]\n }\n }\n set result $res\n }\n return $result\n}\n\nputs \"n-ary\"\nputs \"result: [cartesianNaryProduct {{1776 1789} {7 12} {4 14 23} {0 1}}]\"\nputs \"result: [cartesianNaryProduct {{1 2 3} {30} {500 100}}]\"\nputs \"result: [cartesianNaryProduct {{1 2 3} {} {500 100}}]\"\n", "language": "Tcl" }, { "code": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n <Extension()>\n Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n End Function\n\n Sub Main()\n Dim empty(-1) As Integer\n Dim list1 = {1, 2}\n Dim list2 = {3, 4}\n Dim list3 = {1776, 1789}\n Dim list4 = {7, 12}\n Dim list5 = {4, 14, 23}\n Dim list6 = {0, 1}\n Dim list7 = {1, 2, 3}\n Dim list8 = {30}\n Dim list9 = {500, 100}\n\n For Each sequnceList As Integer()() In {\n ({list1, list2}),\n ({list2, list1}),\n ({list1, empty}),\n ({empty, list1}),\n ({list3, list4, list5, list6}),\n ({list7, list8, list9}),\n ({list7, empty, list9})\n }\n Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n Next\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./seq\" for Lst\n\nvar prod2 = Fn.new { |l1, l2|\n var res = []\n for (e1 in l1) {\n for (e2 in l2) res.add([e1, e2])\n }\n return res\n}\n\nvar prodN = Fn.new { |ll|\n if (ll.count < 2) Fiber.abort(\"There must be at least two lists.\")\n var p2 = prod2.call(ll[0], ll[1])\n return ll.skip(2).reduce(p2) { |acc, l| prod2.call(acc, l) }.map { |l| Lst.flatten(l) }.toList\n}\n\nvar printProdN = Fn.new { |ll|\n System.print(\"%(ll.join(\" x \")) = \")\n System.write(\"[\\n \")\n System.print(prodN.call(ll).join(\"\\n \"))\n System.print(\"]\\n\")\n}\n\nSystem.print(\"[1, 2] x [3, 4] = %(prodN.call([ [1, 2], [3, 4] ]))\")\nSystem.print(\"[3, 4] x [1, 2] = %(prodN.call([ [3, 4], [1, 2] ]))\")\nSystem.print(\"[1, 2] x [] = %(prodN.call([ [1, 2], [] ]))\")\nSystem.print(\"[] x [1, 2] = %(prodN.call([ [], [1, 2] ]))\")\nSystem.print(\"[1, a] x [2, b] = %(prodN.call([ [1, \"a\"], [2, \"b\"] ]))\")\nSystem.print()\nprintProdN.call([ [1776, 1789], [7, 12], [4, 14, 23], [0, 1] ])\nprintProdN.call([ [1, 2, 3], [30], [500, 100] ])\nprintProdN.call([ [1, 2, 3], [], [500, 100] ])\nprintProdN.call([ [1, 2, 3], [30], [\"a\", \"b\"] ])\n", "language": "Wren" }, { "code": "zkl: Walker.cproduct(List(1,2),List(3,4)).walk().println();\nL(L(1,3),L(1,4),L(2,3),L(2,4))\nzkl: foreach a,b in (List(1,2),List(3,4)){ print(\"(%d,%d) \".fmt(a,b)) }\n(1,3) (1,4) (2,3) (2,4)\n\nzkl: Walker.cproduct(List(3,4),List(1,2)).walk().println();\nL(L(3,1),L(3,2),L(4,1),L(4,2))\n", "language": "Zkl" }, { "code": "zkl: Walker.cproduct(List(3,4),List).walk().println();\nException thrown: TheEnd(Ain't no more)\n\nzkl: Walker.cproduct(List(3,4),List).pump(List).println();\nL()\nzkl: Walker.cproduct(List,List(3,4)).pump(List).println();\nL()\n", "language": "Zkl" }, { "code": "zkl: Walker.cproduct(L(1776,1789),L(7,12),L(4,14,23),L(0,1)).walk().println();\nL(L(1776,7,4,0),L(1776,7,4,1),L(1776,7,14,0),L(1776,7,14,1),L(1776,7,23,0),L(1776,7,23,1),L(1776,12,4,0),L(1776,12,4,1),L(1776,12,14,0),L(1776,12,14,1),L(1776,12,23,0),L(1776,12,23,1),L(1789,7,4,0),L(1789,7,4,1),L(1789,7,14,0),L(1789,7,14,1),L(1789,7,23,0),L(1789,7,23,1),L(1789,12,4,0),L(1789,12,4,1),...)\n\nzkl: Walker.cproduct(L(1,2,3),L(30),L(500,100)).walk().println();\nL(L(1,30,500),L(1,30,100),L(2,30,500),L(2,30,100),L(3,30,500),L(3,30,100))\n\nzkl: Walker.cproduct(L(1,2,3),List,L(500,100)).pump(List).println();\nL()\n", "language": "Zkl" } ]
Cartesian-product-of-two-or-more-lists
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Case-sensitivity_of_identifiers\nnote: Case Sensitivity\n", "language": "00-META" }, { "code": "Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:\n<pre>\nThe three dogs are named Benjamin, Samba and Bernie.\n</pre>\nFor a language that is lettercase insensitive, we get the following output:\n<pre>\nThere is just one dog named Bernie.\n</pre>\n\n\n;Related task:\n* [[Unicode variable names]]\n<br><br>\n", "language": "00-TASK" }, { "code": "V dog = ‘Benjamin’\nV Dog = ‘Samba’\nV DOG = ‘Bernie’\nprint(‘The three dogs are named ’dog‘, ’Dog‘ and ’DOG‘.’)\n", "language": "11l" }, { "code": "PROC Main()\n CHAR ARRAY dog=\"Bernie\"\n\n PrintF(\"There is just one dog named %S.\",dog)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO;\nprocedure Dogs is\n Dog : String := \"Bernie\";\nbegin\n Ada.Text_IO.Put_Line (\"There is just one dog named \" & DOG);\nend Dogs;\n", "language": "Ada" }, { "code": "scope\n local dog := \"Benjamin\";\n scope\n local Dog := \"Samba\";\n scope\n local DOG := \"Bernie\";\n if DOG <> Dog or DOG <> dog\n then print( \"The three dogs are named: \" & dog & \", \" & Dog & \" and \" & DOG )\n else print( \"There is just one dog named: \" & DOG )\n fi\n epocs\n epocs\nepocs\n", "language": "Agena" }, { "code": "text dog, Dog, DOG;\n\ndog = \"Benjamin\";\nDog = \"Samba\";\nDOG = \"Bernie\";\n\no_form(\"The three dogs are named ~, ~ and ~.\\n\", dog, Dog, DOG);\n", "language": "Aime" }, { "code": "#!/usr/bin/a68g --script #\n# -*- coding: utf-8 -*- #\n\nSTRING dog = \"Benjamin\";\nOP D = (INT og)STRING: \"Samba\";\nOP DOG = (INT gy)STRING: \"Bernie\";\nINT og=~, gy=~;\n\nmain:(\n printf(($\"The three dogs are named \"g\", \"g\" and \"g\".\"l$, dog, Dog, DOGgy));\n 0\n)\n", "language": "ALGOL-68" }, { "code": "'begin'\n 'string' dog = \"Benjamin\";\n 'begin'\n 'string' Dog = \"Samba\";\n 'begin'\n 'string' DOG = \"Bernie\";\n 'if' DOG /= Dog 'or' DOG /= dog\n 'then' print( ( \"The three dogs are named: \", dog, \", \", Dog, \" and \", DOG ) )\n 'else' print( ( \"There is just one dog named: \", DOG ) )\n 'fi'\n 'end'\n 'end'\n'end'\n", "language": "ALGOL-68" }, { "code": "begin\n string(8) dog;\n dog := \"Benjamin\";\n begin\n string(8) Dog;\n Dog := \"Samba\";\n begin\n string(8) DOG;\n DOG := \"Bernie\";\n if DOG not = Dog\n or DOG not = dog\n then write( \"The three dogs are named: \", dog, \", \", Dog, \" and \", DOG )\n else write( \"There is just one dog named: \", DOG )\n end\n end\nend.\n", "language": "ALGOL-W" }, { "code": " DOG←'Benjamin'\n Dog←'Samba'\n dog←'Bernie'\n 'The three dogs are named ',DOG,', ',Dog,', and ',dog\nThe three dogs are named Benjamin, Samba, and Bernie\n", "language": "APL" }, { "code": "set {dog, |Dog|, |DOG|} to {\"Benjamin\", \"Samba\", \"Bernie\"}\n\nif (dog = |Dog|) then\n if (dog = |DOG|) then return \"There is just one dog named \" & dog & \".\"\n return \"There are two dogs named \" & dog & \" and \" & |DOG| & \".\"\nelse if (dog = |DOG|) then\n return \"There are two dogs named \" & dog & \" and \" & |Dog| & \".\"\nend if\nreturn \"The three dogs are named \" & dog & \", \" & |Dog| & \", and \" & |DOG| & \".\"\n", "language": "AppleScript" }, { "code": "\"There is just one dog named Bernie.\"\n", "language": "AppleScript" }, { "code": "dog$ = \"Benjamin\":Dog$ = \"Samba\":DOG$ = \"Bernie\":III = 254 * (DOG$ = dog$ AND Dog$ = DOG$) + 1: PRINT MID$ (\"There is just one dog\",256 - III) MID$ (\"The three dogs are\",III)\" named \" MID$ (dog$ + \", \" + Dog$ + \" and \",III)DOG$\".\"\n", "language": "Applesoft-BASIC" }, { "code": "dog: \"Benjamin\"\nDog: \"Samba\"\nDOG: \"Bernie\"\n\ndogs: @[dog Dog DOG]\n\nprint [\"The\" size dogs \"dog(s) are named\" join.with:\", \" dogs]\n", "language": "Arturo" }, { "code": "dog := \"Benjamin\"\nDog := \"Samba\"\nDOG := \"Bernie\"\nMsgBox There is just one dog named %dOG%\n", "language": "AutoHotkey" }, { "code": "BEGIN {\n\tdog = \"Benjamin\"\n\tDog = \"Samba\"\n\tDOG = \"Bernie\"\n\tprintf \"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG\n}\n", "language": "AWK" }, { "code": "dog = \"Benjamin\"\nDog = \"Samba\"\nDOG = \"Bernie\"\nprint \"There is just one dog, named \"; dog\nend\n", "language": "BASIC256" }, { "code": "@echo off\n\nset dog=Benjamin\nset Dog=Samba\nset DOG=Bernie\n\necho There is just one dog named %dog%.\npause>nul\n", "language": "Batch-File" }, { "code": " dog$ = \"Benjamin\"\n Dog$ = \"Samba\"\n DOG$ = \"Bernie\"\n PRINT \"The three dogs are \" dog$ \", \" Dog$ \" and \" DOG$ \".\"\n", "language": "BBC-BASIC" }, { "code": "obase = 16\nibase = 16\n\n/*\n * Store the hexadecimal number 'BE27A312'\n * in the variable 'd'.\n */\nd = BE27A312\n\"There is just one dog named \"; d\nquit\n", "language": "Bc" }, { "code": "( Benjamin:?dog\n& Samba:?Dog\n& Bernie:?DOG\n& out$(\"There are three dogs:\" !dog !Dog and !DOG)\n);\n", "language": "Bracmat" }, { "code": "opendb dogs.g y # Create a database to hold our dogs\nunits ft # The dogs are measured in feet\nin dog.s sph 0 0 0 1 # Benjie is a little Scottie dog\nin Dog.s sph 4 0 0 3 # Samba is a Labrador\nin DOG.s sph 13 0 0 5 # Bernie is massive. He is a New Foundland\necho The three dogs are named Benjamin, Samba and Bernie\n", "language": "Brlcad" }, { "code": "#include <stdio.h>\n\nstatic const char *dog = \"Benjamin\";\nstatic const char *Dog = \"Samba\";\nstatic const char *DOG = \"Bernie\";\n\nint main()\n{\n printf(\"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG);\n return 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n string dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\";\n\n cout << \"The three dogs are named \" << dog << \", \" << Dog << \", and \" << DOG << endl;\n}\n", "language": "C++" }, { "code": "using System;\n\nclass Program\n{\n static void Main(string[] args)\n {\n string dog = \"Benjamin\";\n string Dog = \"Samba\";\n string DOG = \"Bernie\";\n Console.WriteLine(string.Format(\"The three dogs are named {0}, {1}, and {2}.\", dog, Dog, DOG));\n }\n}\n", "language": "C-sharp" }, { "code": "10 dog$ = \"Benjamin\"\n20 dog$ = \"Smokey\"\n30 dog$ = \"Samba\"\n40 dog$ = \"Bernie\"\n50 print \"There is just one dog, named \";dog$\n", "language": "Chipmunk-Basic" }, { "code": "* Case sensitivity of identifiers\n *>* Commented-out lines in the working storage\n *>* are considered as invalid redefinitions\n *>* of ''dog'' that can only be ambiguously\n *>* referenced in the procedure body.\n\n IDENTIFICATION DIVISION.\n PROGRAM-ID. case-sensitivity.\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n *>* 01 dog PICTURE X(8) VALUE IS \"Benjamin\".\n *>* 01 Dog PICTURE X(5) VALUE IS \"Samba\".\n 01 DOG PICTURE X(6) VALUE IS \"Bernie\".\n PROCEDURE DIVISION.\n DISPLAY\n *>* \"The three dogs are named \"\n *>* dog \", \" Dog \" and \" DOG \".\"\n \"There is just one dog named \" DOG \".\"\n END-DISPLAY\n STOP RUN.\n END PROGRAM case-sensitivity.\n", "language": "COBOL" }, { "code": "dog=\"Benjamin\"\nDog = \"Samba\"\nDOG = \"Bernie\"\nconsole.log \"The three dogs are names #{dog}, #{Dog}, and #{DOG}.\"\n", "language": "CoffeeScript" }, { "code": "> coffee foo.coffee\nThe three dogs are names Benjamin, Samba, and Bernie.\n", "language": "CoffeeScript" }, { "code": "CL-USER> (let* ((dog \"Benjamin\") (Dog \"Samba\") (DOG \"Bernie\"))\n\t (format nil \"There is just one dog named ~a.\" dog))\n; in: LAMBDA NIL\n; (LET* ((DOG \"Benjamin\") (DOG \"Samba\") (DOG \"Bernie\"))\n; (FORMAT NIL \"There is just one dog named ~a.\" DOG))\n;\n; caught STYLE-WARNING:\n; The variable DOG is defined but never used.\n;\n; caught STYLE-WARNING:\n; The variable DOG is defined but never used.\n;\n; compilation unit finished\n; caught 2 STYLE-WARNING conditions\n\"There is just one dog named Bernie.\"\n", "language": "Common-Lisp" }, { "code": "include \"cowgol.coh\";\n\nvar dog := \"Benjamin\";\nvar Dog := \"Samba\";\nvar DOG := \"Bernie\";\n\nprint(\"There are three dogs named \");\nprint(dog);\nprint(\", \");\nprint(Dog);\nprint(\", and \");\nprint(DOG);\nprint(\".\\n\");\n", "language": "Cowgol" }, { "code": "dog = \"Benjamin\"\nDog = \"Samba\"\nDOG = \"Bernie\"\n\nputs \"The three dogs are named #{dog}, #{Dog} and #{DOG}.\"\n", "language": "Crystal" }, { "code": "import std.stdio;\n\nvoid main() {\n string dog = \"Benjamin\";\n // identifiers that start with capital letters are type names\n string Dog = \"Samba\";\n string DOG = \"Bernie\";\n writefln(\"There are three dogs named \",\n dog, \", \", Dog, \", and \", DOG, \"'\");\n}\n", "language": "D" }, { "code": "void main() {\n String dog = \"Benjamin\", doG = \"Smokey\", Dog = \"Samba\", DOG = \"Bernie\";\n\n print(\"The four dogs are named $dog, $doG, $Dog and $DOG\");\n}\n", "language": "Dart" }, { "code": "[Benjamin]sd\n[Samba]sD\n[The two dogs are named ]P ldP [ and ]P lDP [.\n]P\n", "language": "Dc" }, { "code": "program CaseSensitiveIdentifiers;\n\n{$APPTYPE CONSOLE}\n\nvar\n dog: string;\nbegin\n dog := 'Benjamin';\n Dog := 'Samba';\n DOG := 'Bernie';\n Writeln('There is just one dog named ' + dog);\nend.\n", "language": "Delphi" }, { "code": "proc main() void:\n *char dog = \"Benjamin\",\n Dog = \"Samba\",\n DOG = \"Bernie\";\n\n writeln(\"There are three dogs named \",\n dog, \", \", Dog, \", and \", DOG, \".\")\ncorp\n", "language": "Draco" }, { "code": "var dog : String;\n\ndog := 'Benjamin';\nDog := 'Samba';\nDOG := 'Bernie';\n\nPrintLn('There is just one dog named ' + dog);\n", "language": "DWScript" }, { "code": "dog$ = \"Benjamin\"\nDog$ = \"Samba\"\nDOG$ = \"Bernie\"\n#\nprint \"The three dogs are named \" & dog$ & \", \" & Dog$ & \", and \" & DOG$ & \".\"\n", "language": "EasyLang" }, { "code": "(define dog \"Benjamin\")\n(define Dog \"Samba\")\n(define DOG \"Bernie\")\n\n(printf \"The three dogs are named %a, %a and %a. \" dog Dog DOG)\n The three dogs are named Benjamin, Samba and Bernie.\n", "language": "EchoLisp" }, { "code": "String dog = \"Benjamin\"; // convention: lower camelCase for variable and property names\nString Dog = \"Samba\"; // convention: upper CamelCase for class, type, and constant names\nString DOG = \"Bernie\"; // convention: all-caps only for constants\n\n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\n", "language": "Ecstasy" }, { "code": "import extensions;\n\npublic program()\n{\n var dog := \"Benjamin\";\n var Dog := \"Samba\";\n var DOG := \"Bernie\";\n console.printLineFormatted(\"The three dogs are named {0}, {1} and {2}\", dog, Dog, DOG)\n}\n", "language": "Elena" }, { "code": "dog = \"Benjamin\"\ndoG = \"Samba\"\ndOG = \"Bernie\"\nIO.puts \"The three dogs are named #{dog}, #{doG} and #{dOG}.\"\n", "language": "Elixir" }, { "code": "-module( case_sensitivity_of_identifiers ).\n\n-export( [task/0] ).\n\ntask() ->\n\tcatch dog = \"Benjamin\", % Function will crash without catch\n\tDog = \"Samba\",\n\tDOG = \"Bernie\",\n\tio:fwrite( \"The three dogs are named ~s, ~s and ~s~n\", [dog, Dog, DOG] ).\n", "language": "Erlang" }, { "code": "-- These variables are all different\nsequence dog = \"Benjamin\"\nsequence Dog = \"Samba\"\nsequence DOG = \"Bernie\"\nprintf( 1, \"The three dogs are named %s, %s and %s\\n\", {dog, Dog, DOG} )\n", "language": "Euphoria" }, { "code": "let dog = \"Benjamin\"\nlet Dog = \"Samba\"\nlet DOG = \"Bernie\"\nprintfn \"There are three dogs named %s, %s and %s\" dog Dog DOG\n", "language": "F-Sharp" }, { "code": "USING: formatting locals ;\nIN: scratchpad\n[let\n \"Benjamin\" :> dog\n \"Samba\" :> Dog\n \"Bernie\" :> DOG\n { dog Dog DOG } \"There are three dogs named %s, %s, and %s.\" vprintf\n]\n", "language": "Factor" }, { "code": ": DOG .\" Benjamin\" ;\n: Dog .\" Samba\" ;\n: dog .\" Bernie\" ;\n: HOWMANYDOGS .\" There is just one dog named \" DOG ;\nHOWMANYDOGS\n", "language": "Forth" }, { "code": "program Example\n implicit none\n\n character(8) :: dog, Dog, DOG\n\n dog = \"Benjamin\"\n Dog = \"Samba\"\n DOG = \"Bernie\"\n\n if (dog == DOG) then\n write(*,*) \"There is just one dog named \", dog\n else\n write(*,*) \"The three dogs are named \", dog, Dog, \" and \", DOG\n end if\n\nend program Example\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\n' FreeBASIC is case-insensitive\nDim dog As String\ndog = \"Benjamin\"\nDog = \"Samba\"\nDOG = \"Bernie\"\nPrint \"There is just one dog, named \"; dog\nSleep\n", "language": "FreeBASIC" }, { "code": "dog = \"Benjamin\"\nDog = \"Samba\"\nDOG = \"Bernie\"\nprintln[\"There are three dogs named $dog, $Dog and $DOG\"]\n", "language": "Frink" }, { "code": "CFDictionaryRef canines\ncanines = @{@\"dog\":@\"Benjamin\", @\"Dog\":@\"Samba\", @\"DOG\":@\"Bernie\"}\nprint \"The three dogs are \"; canines[@\"dog\"]; \", \"; canines[@\"Dog\"]; \" and \"; canines[@\"DOG\"]; \".\"\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\nDim dog As String\n\nDog = \"Benjamin\"\nDOG = \"Samba\"\ndog = \"Bernie\"\nPrint \"There is just one dog, named \"; dog\n\nEnd\n", "language": "Gambas" }, { "code": "# GAP is case sensitive\nThreeDogs := function()\n\tlocal dog, Dog, DOG;\n\tdog := \"Benjamin\";\n\tDog := \"Samba\";\n\tDOG := \"Bernie\";\n\tif dog = DOG then\n\t\tPrint(\"There is just one dog named \", dog, \"\\n\");\n\telse\n\t\tPrint(\"The three dogs are named \", dog, \", \", Dog, \" and \", DOG, \"\\n\");\n\tfi;\nend;\n\nThreeDogs();\n# The three dogs are named Benjamin, Samba and Bernie\n", "language": "GAP" }, { "code": "package dogs\n\nimport \"fmt\"\n\n// Three variables, three different names.\n// (It wouldn't compile if the compiler saw the variable names as the same.)\nvar dog = \"Salt\"\nvar Dog = \"Pepper\"\nvar DOG = \"Mustard\"\n\nfunc PackageSees() map[*string]int {\n // Print dogs visible from here.\n fmt.Println(\"Package sees:\", dog, Dog, DOG)\n // Return addresses of the variables visible from here.\n // The point of putting them in a map is that maps store only\n // unique keys, so it will end up with three items only if\n // the variables really represent different places in memory.\n return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1}\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n . \"dogs\"\n \"fmt\"\n)\n\nfunc main() {\n // with the dogs package imported, there are three dogs.\n d := PackageSees()\n fmt.Println(\"There are\", len(d), \"dogs.\\n\")\n\n // Declaration of new variable dog. It lives in this package, main.\n dog := \"Benjamin\"\n d = PackageSees()\n fmt.Println(\"Main sees: \", dog, Dog, DOG)\n // Four dogs now. two of the three visible from here are the\n // the same as ones in the dogs package.\n d[&dog] = 1\n d[&Dog] = 1\n d[&DOG] = 1\n fmt.Println(\"There are\", len(d), \"dogs.\\n\")\n\n // Not a declaration, just an assigment. This assigns a new value to\n // the variable Dog declared in the package. Dog is visible because\n // it begins with an upper case letter.\n Dog = \"Samba\"\n // same four dogs, same three visible, one just has a new name.\n d = PackageSees()\n fmt.Println(\"Main sees: \", dog, Dog, DOG)\n d[&dog] = 1\n d[&Dog] = 1\n d[&DOG] = 1\n fmt.Println(\"There are\", len(d), \"dogs.\\n\")\n\n // Of course you can still declare a variable if you want to. This\n // declares a new variable, shadowing DOG in the package and rendering\n // it inaccessable even though it begins with an upper case letter.\n var DOG = \"Bernie\"\n // five dogs now. three visible from here.\n d = PackageSees()\n fmt.Println(\"Main sees: \", dog, Dog, DOG)\n d[&dog] = 1\n d[&Dog] = 1\n d[&DOG] = 1\n fmt.Println(\"There are\", len(d), \"dogs.\")\n}\n", "language": "Go" }, { "code": "def dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\"\nprintln (dog == DOG ? \"There is one dog named ${dog}\" : \"There are three dogs named ${dog}, ${Dog} and ${DOG}.\")\n", "language": "Groovy" }, { "code": "10 dog$ = \"Benjamin\"\n20 dog$ = \"Smokey\"\n30 dog$ = \"Samba\"\n40 dog$ = \"Bernie\"\n50 print \"There is just one dog, named \";dog$\n", "language": "GW-BASIC" }, { "code": "import Text.Printf\n\nmain = printf \"The three dogs are named %s, %s and %s.\\n\" dog dOG dOg\n where dog = \"Benjamin\"\n dOG = \"Samba\"\n dOg = \"Bernie\"\n", "language": "Haskell" }, { "code": "procedure main()\n\n dog := \"Benjamin\"\n Dog := \"Samba\"\n DOG := \"Bernie\"\n\t\n if dog == DOG then\n write(\"There is just one dog named \", dog,\".\")\n else\n write(\"The three dogs are named \", dog, \", \", Dog, \" and \", DOG, \".\")\n\nend\n", "language": "Icon" }, { "code": " NB. These variables are all different\n dog=: 'Benjamin'\n Dog=: 'Samba'\n DOG=: 'Bernie'\n 'The three dogs are named ',dog,', ',Dog,', and ',DOG\nThe three dogs are named Benjamin, Samba, and Bernie\n", "language": "J" }, { "code": "String dog = \"Benjamin\";\nString Dog = \"Samba\"; //in general, identifiers that start with capital letters are class names\nString DOG = \"Bernie\"; //in general, identifiers in all caps are constants\n//the conventions listed in comments here are not enforced by the language\nSystem.out.println(\"There are three dogs named \" + dog + \", \" + Dog + \", and \" + DOG + \"'\");\n", "language": "Java" }, { "code": "var dog = \"Benjamin\";\nvar Dog = \"Samba\";\nvar DOG = \"Bernie\";\ndocument.write(\"The three dogs are named \" + dog + \", \" + Dog + \", and \" + DOG + \".\");\n", "language": "JavaScript" }, { "code": "def task(dog; Dog; DOG):\n \"The three dogs are named \\(dog), \\(Dog), and \\(DOG).\" ;\n\ntask(\"Benjamin\"; \"Samba\"; \"Bernie\")\n", "language": "Jq" }, { "code": "\"Benjamin\" as $dog | \"Samba\" as $Dog | \"Bernie\" as $DOG\n | \"The three dogs are named \\($dog), \\($Dog), and \\($DOG).\"\n", "language": "Jq" }, { "code": "dog, Dog, DOG = \"Benjamin\", \"Samba\", \"Bernie\"\n\nif dog === Dog\n println(\"There is only one dog, \", DOG)\nelse\n println(\"The three dogs are: \", dog, \", \", Dog, \" and \", DOG)\nend\n", "language": "Julia" }, { "code": " dog: \"Benjamin\"\n Dog: \"Samba\"\n DOG: \"Bernie\"\n \"There are three dogs named \",dog,\", \",Dog,\" and \",DOG\n\"There are three dogs named Benjamin, Samba and Bernie\"\n", "language": "K" }, { "code": "fun main(args: Array<String>) {\n val dog = \"Benjamin\"\n val Dog = \"Samba\"\n val DOG = \"Bernie\"\n println(\"The three dogs are named $dog, $Dog and $DOG\")\n}\n", "language": "Kotlin" }, { "code": "local(dog = 'Benjamin')\nlocal(Dog = 'Samba')\nlocal(DOG = 'Bernie')\n\nstdoutnl('There is just one dog named ' + #dog)\n", "language": "Lasso" }, { "code": "local(dogs = map(\n\t'dog' = 'Benjamin',\n\t'Dog' = 'Samba',\n\t'DOG' = 'Bernie'\n))\nstdoutnl(#dogs -> size)\n", "language": "Lasso" }, { "code": "local(dogs = map(\n\tbytes('dog') = 'Benjamin',\n\tbytes('Dog') = 'Samba',\n\tbytes('DOG') = 'Bernie'\n))\n\nstdoutnl(#dogs -> size)\n\nstdoutnl(#dogs -> find(bytes('Dog')))\n", "language": "Lasso" }, { "code": "dog$ = \"Benjamin\"\nDog$ = \"Samba\"\nDOG$ = \"Bernie\"\nprint \"The three dogs are \"; dog$; \", \"; Dog$; \" and \"; DOG$; \".\"\n\nend\n", "language": "Liberty-BASIC" }, { "code": ":- object(three_dogs_or_one).\n\n :- public(test/0).\n\n test :-\n fill_dogs(DOG, Dog, DoG),\n write_message(DOG, Dog, DoG).\n\n % Note: this predicate would actually fail if variables weren't case sensitive...\n fill_dogs('Benjamin', 'Samba', 'Bernie').\n\n % Note: ...as a result there is no way for this clause to ever succeed.\n write_message(A, A, A) :-\n format('There is one dog named ~w.~n', [A]).\n\n write_message(A, B, C) :-\n A \\= B, B \\= C, A \\= C,\n format('There are three dogs named ~w, ~w, and ~w.~n', [A, B, C]).\n\n:- end_object.\n", "language": "Logtalk" }, { "code": "dog = \"Benjamin\"\nDog = \"Samba\"\nDOG = \"Bernie\"\n\nprint( \"There are three dogs named \"..dog..\", \"..Dog..\" and \"..DOG..\".\" )\n", "language": "Lua" }, { "code": "MoDuLe CheckIT {\n \\\\ keys as case sensitive if they are strings\n Inventory A= \"Dog\":=1, \"dog\":=2,\"DOG\":=\"Hello\", 100:=\"Dog\"\n Print A(\"Dog\"), A(\"dog\"), A$(\"DOG\"), A$(100)\n\n \\\\ Enumeration get type as defined (same case)\n Enum Dogs {Benjamin, Samba, Bernie}\n Print Type$(Bernie)=\"Dogs\"\n Print Type$(DOGS)=\"Dogs\"\n m=BenJamiN\n m++\n Print Eval$(m)=\"Samba\" ' same case as defined\n\n DoG$=\"Benjamin\"\n DOG$=\"Samba\"\n doG$=\"Bernie\"\n PrinT \"There is just one dog named \"+Dog$+\".\"\n goto Dog\ndog:\n Print \"dog\"\n Exit\nDog:\n Print \"Dog\"\n GoTo dog\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "> dog, Dog, DOG := \"Benjamin\", \"Samba\", \"Bernie\":\n> if nops( { dog, Dog, DOG } ) = 3 then\n> printf( \"There are three dogs named %s, %s and %s.\\n\", dog, Dog, DOG )\n> elif nops( { dog, Dog, DOG } ) = 2 then\n> printf( \"WTF? There are two dogs named %s and %s.\\n\", op( { dog, Dog, DOG } ) )\n> else\n> printf( \"There is one dog named %s.\\n\", dog )\n> end if:\nThere are three dogs named Benjamin, Samba and Bernie.\n", "language": "Maple" }, { "code": "dog = \"Benjamin\"; Dog = \"Samba\"; DOG = \"Bernie\";\n\"The three dogs are named \"<> dog <>\", \"<> Dog <>\" and \"<> DOG\n\n-> \"The three dogs are named Benjamin, Samba and Bernie\"\n", "language": "Mathematica" }, { "code": " dog = 'Benjamin';\n Dog = 'Samba';\n DOG = 'Bernie';\n\n printf('There are three dogs %s, %s, %s.\\n',dog, Dog, DOG);\n", "language": "MATLAB" }, { "code": "/* Maxima is case sensitive */\na: 1$\nA: 2$\n\nis(a = A);\nfalse\n", "language": "Maxima" }, { "code": "\"Benjamin\" :dog\n\"Samba\" :Dog\n\"Bernie\" :DOG\n\n\"There are three dogs named $1, $2, and $3.\" (dog Dog DOG) =% puts!\n", "language": "Min" }, { "code": "10 let d$ = \"Benjamin\"\n20 let D$ = \"Samba\"\n30 print \"There is just one dog, named \"; d$\n40 end\n", "language": "Minimal-BASIC" }, { "code": "dog = \"Benjamin\"\nDog = \"Samba\"\nDOG = \"Bernie\"\n\nprint \"There are three dogs named \" + dog + \", \" + Dog + \" and \" + DOG\n", "language": "MiniScript" }, { "code": "MODULE dog;\n\nIMPORT InOut;\n\nTYPE String = ARRAY [0..31] OF CHAR;\n\nVAR dog, Dog, DOG : String;\n\n(* No compiler error, so the rest is simple *)\n\nBEGIN\n InOut.WriteString (\"Three happy dogs.\");\n InOut.WriteLn\nEND dog.\n", "language": "Modula-2" }, { "code": "10 dog$ = \"Benjamin\"\n20 dog$ = \"Smokey\"\n30 dog$ = \"Samba\"\n40 dog$ = \"Bernie\"\n50 print \"There is just one dog, named \";dog$\n", "language": "MSX-Basic" }, { "code": ".ds dog Benjamin\n.ds Dog Samba\n.ds DOG Bernie\nThe three dogs are named \\*[dog], \\*[Dog] and \\*[DOG].\n", "language": "N-t-roff" }, { "code": "dog = \"Benjamin\"\nDog = \"Samba\"\nDOG = \"Bernie\"\n\nprint format(\"The three dogs are named %s, %s, and %s.\\n\", dog, Dog, DOG)\n", "language": "Nanoquery" }, { "code": "def dog = \"Benjamin\";\ndef Dog = \"Samba\";\ndef DOG = \"Bernie\";\nWriteLine($\"The three dogs are named $dog, $Dog, and $DOG\");\n", "language": "Nemerle" }, { "code": "dog = \"Benjamin\";\nDog = \"Samba\";\nDOG = \"Bernie\";\n\"There is just one dog, named \" ++ dog;\n", "language": "NESL" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\ndog = \"Benjamin\";\nDog = \"Samba\";\nDOG = \"Bernie\";\n\nif dog == Dog & Dog == DOG & dog == DOG then do\n say 'There is just one dog named' dog'.'\n end\nelse do\n say 'The three dogs are named' dog',' Dog 'and' DOG'.'\n end\n\nreturn\n", "language": "NetRexx" }, { "code": "var dog, Dog: string\n(dog, Dog, DOG) = (\"Benjamin\", \"Samba\", \"Bernie\")\n\nif dog == Dog:\n if dog == DOG:\n echo \"There is only one dog, \", DOG)\n else:\n echo \"There are two dogs: \", dog, \" and \", DOG\nelif Dog == DOG :\n echo \"There are two dogs: \", dog, \" and \", DOG\nelse:\n echo \"There are three dogs: \", dog, \", \", Dog, \" and \", DOG\n", "language": "Nim" }, { "code": "MODULE CaseSensitivity;\nIMPORT\n Out;\nVAR\n dog, Dog, DOG: STRING;\nBEGIN\n dog := \"Benjamin\";\n Dog := \"Samba\";\n DOG := \"Bernie\";\n Out.Object(\"The three dogs are named \" + dog + \", \" + Dog + \" and \" + DOG);\n Out.Ln\nEND CaseSensitivity.\n", "language": "Oberon" }, { "code": "class Program {\n function : Main(args : String[]) ~ Nil {\n dog := \"Benjamin\";\n Dog := \"Samba\";\n DOG := \"Bernie\";\n \"The three dogs are named {$dog}, {$Dog}, and {$DOG}.\"->PrintLine();\n }\n}\n", "language": "Objeck" }, { "code": "let () =\n let dog = \"Benjamin\" in\n let dOG = \"Samba\" in\n let dOg = \"Bernie\" in\n Printf.printf \"The three dogs are named %s, %s and %s.\\n\" dog dOG dOg\n", "language": "OCaml" }, { "code": ": threeDogs\n| dog Dog DOG |\n\n \"Benjamin\" ->dog\n \"Samba\" ->Dog\n \"Bernie\" ->DOG\n\n System.Out \"The three dogs are named \" << dog << \", \" << Dog << \" and \" << DOG << \".\" << cr ;\n", "language": "Oforth" }, { "code": "(define dog \"Benjamin\")\n(define Dog \"Samba\")\n(define DOG \"Bernie\")\n\t\n(print \"The three dogs are named \" dog \", \" Dog \" and \" DOG \".\\n\")\n", "language": "Ol" }, { "code": "dog=\"Benjamin\";\nDog=\"Samba\";\nDOG=\"Bernie\";\nprintf(\"The three dogs are named %s, %s, and %s.\", dog, Dog, DOG)\n", "language": "PARI-GP" }, { "code": "# These variables are all different\n$dog='Benjamin';\n$Dog='Samba';\n$DOG='Bernie';\nprint \"The three dogs are named $dog, $Dog, and $DOG \\n\"\n", "language": "Perl" }, { "code": "-->\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">dog</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"Benjamin\"<span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">Dog</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"Samba\"<span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">DOG</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"Bernie\"</span>\n <span style=\"color: #7060A8;\">printf<span style=\"color: #0000FF;\">(</span> <span style=\"color: #000000;\">1<span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"The three dogs are named %s, %s and %s\\n\"<span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{<span style=\"color: #000000;\">dog<span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">Dog<span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">DOG<span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">)\n<!--\n", "language": "Phix" }, { "code": "<?php\n\n// In true PHP style, this example is inconsistent.\n// Variable identifiers are case sensitive\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n// Whereas function identifiers are case insensitive\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n", "language": "PHP" }, { "code": "(let (dog \"Benjamin\" Dog \"Samba\" DOG \"Bernie\")\n (prinl \"The three dogs are named \" dog \", \" Dog \" and \" DOG) )\n", "language": "PicoLisp" }, { "code": "*process or(!) source xref attributes macro options;\n /*********************************************************************\n * Program to show that PL/I is case-insensitive\n * 28.05.2013 Walter Pachl\n *********************************************************************/\n case: proc options(main);\n Dcl dog Char(20) Var;\n dog = \"Benjamin\";\n Dog = \"Samba\";\n DOG = \"Bernie\";\n Put Edit(dog,Dog,DOG)(Skip,3(a,x(1)));\n End;\n", "language": "PL-I" }, { "code": "To run:\nStart up.\nPut \"Benjamin\" into a DOG string.\nPut \"Samba\" into the Dog string.\nPut \"Bernie\" into the dog string.\nWrite \"There is just one dog named \" then the DOG on the console.\nWait for the escape key.\nShut down.\n", "language": "Plain-English" }, { "code": "$dog = \"Benjamin\"\n$Dog = \"Samba\"\n$DOG = \"Bernie\"\n\n\"There is just one dog named {0}.\" -f $dOg\n", "language": "PowerShell" }, { "code": "three_dogs :-\n\tDoG = 'Benjamin',\n\tDog = 'Samba',\n\tDOG = 'Bernie',\n\tformat('The three dogs are named ~w, ~w and ~w.~n', [DoG, Dog, DOG]).\n", "language": "Prolog" }, { "code": "dog$=\"Benjamin\"\nDog$=\"Samba\"\nDOG$=\"Bernie\"\nDebug \"There is just one dog named \"+dog$\n", "language": "PureBasic" }, { "code": "dog = 'Benjamin'\nDog = 'Samba'\nDOG = 'Bernie'\n\nprint(f\"The three dogs are named {dog}, {Dog} and {DOG}.\")\n", "language": "Python" }, { "code": "DOG$ = \"Benjamin\"\nDOG$ = \"Samba\"\nDOG$ = \"Bernie\"\nPRINT \"There is just one dog, named \"; DOG$\n", "language": "QBasic" }, { "code": "[ $ 'Benjamin' ] is dog ( --> $ )\n\n[ $ 'Samba' ] is Dog ( --> $ )\n\n[ $ 'Bernie' ] is DOG ( --> $ )\n\nsay 'There are three dogs named '\ndog echo$ say ', '\nDog echo$ say ', and '\nDOG echo$ say '.' cr\n", "language": "Quackery" }, { "code": "10 let d$ = \"Benjamin\"\n20 let D$ = \"Samba\"\n30 print \"There is just one dog, named \"; d$\n40 end\n", "language": "Quite-BASIC" }, { "code": "dog <- 'Benjamin'\nDog <- 'Samba'\nDOG <- 'Bernie'\n\n# Having fun with cats and dogs\ncat('The three dogs are named ')\ncat(dog)\ncat(', ')\ncat(Dog)\ncat(' and ')\ncat(DOG)\ncat('.\\n')\n# In one line it would be:\n# cat('The three dogs are named ', dog, ', ', Dog, ' and ', DOG, '.\\n', sep = '')\n", "language": "R" }, { "code": "#lang racket\n(define dog \"Benjamin\")\n(define Dog \"Samba\")\n(define DOG \"Bernie\")\n\n(if (equal? dog DOG)\n (displayln (~a \"There is one dog named \" DOG \".\"))\n (displayln (~a \"The three dogs are named \" dog \", \" Dog \", and, \" DOG \".\")))\n", "language": "Racket" }, { "code": "#lang racket\n#ci(module dogs racket\n (define dog \"Benjamin\")\n (set! Dog \"Samba\")\n (set! DOG \"Bernie\")\n (if (equal? dog DOG)\n (displayln (~a \"There is one dog named \" DOG \".\"))\n (displayln (~a \"The three dogs are named \" dog \", \" Dog \", and, \" DOG \".\"))))\n(require 'dogs)\n", "language": "Racket" }, { "code": "my $dog = 'Benjamin';\nmy $Dog = 'Samba';\nmy $DOG = 'Bernie';\nsay \"The three dogs are named $dog, $Dog, and $DOG.\"\n", "language": "Raku" }, { "code": "constant dog = 'Benjamin';\nsub Dog() { 'Samba' }\nmy &DOG = { 'Bernie' }\nsay \"The three dogs are named {dog}, {Dog}, and {DOG}.\"\n", "language": "Raku" }, { "code": ": dog ( -$ ) \"Benjamin\" ;\n: Dog ( -$ ) \"Samba\" ;\n: DOG ( -$ ) \"Bernie\" ;\n\nDOG Dog dog \"The three dogs are named %s, %s, and %s.\\n\" puts\n", "language": "Retro" }, { "code": "/*REXX program demonstrate case insensitivity for simple REXX variable names. */\n\n /* ┌──◄── all 3 left─hand side REXX variables are identical (as far as assignments). */\n /* │ */\n /* ↓ */\n dog= 'Benjamin' /*assign a lowercase variable (dog)*/\n Dog= 'Samba' /* \" \" capitalized \" Dog */\n DOG= 'Bernie' /* \" an uppercase \" DOG */\n\n say center('using simple variables', 35, \"─\") /*title.*/\n say\n\nif dog\\==Dog | DOG\\==dog then say 'The three dogs are named:' dog\",\" Dog 'and' DOG\".\"\n else say 'There is just one dog named:' dog\".\"\n\n /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "/*REXX program demonstrate case sensitive REXX index names (for compound variables). */\n\n /* ┌──◄── all 3 indices (for an array variable) are unique (as far as array index). */\n /* │ */\n /* ↓ */\nx= 'dog'; dogname.x= \"Gunner\" /*assign an array index, lowercase dog*/\nx= 'Dog'; dogname.x= \"Thor\" /* \" \" \" \" capitalized Dog*/\nx= 'DOG'; dogname.x= \"Jax\" /* \" \" \" \" uppercase DOG*/\nx= 'doG'; dogname.x= \"Rex\" /* \" \" \" \" mixed doG*/\n\n say center('using compound variables', 35, \"═\") /*title.*/\n say\n\n_= 'dog'; say \"dogname.dog=\" dogname._ /*display an array index, lowercase dog*/\n_= 'Dog'; say \"dogname.Dog=\" dogname._ /* \" \" \" \" capitalized Dog*/\n_= 'DOG'; say \"dogname.DOG=\" dogname._ /* \" \" \" \" uppercase DOG*/\n_= 'doG'; say \"dogname.doG=\" dogname._ /* \" \" \" \" mixed doG*/\n\n /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "dog = \"Benjamin\"\ndoG = \"Smokey\"\nDog = \"Samba\"\nDOG = \"Bernie\"\nsee \"The 4 dogs are : \" + dog + \", \" + doG + \", \" + Dog + \" and \" + DOG + \".\"\n", "language": "Ring" }, { "code": "module FiveDogs\n dog = \"Benjamin\"\n dOg = \"Dogley\"\n doG = \"Fido\"\n Dog = \"Samba\" # this constant is FiveDogs::Dog\n DOG = \"Bernie\" # this constant is FiveDogs::DOG\n\n names = [dog, dOg, doG, Dog, DOG]\n names.uniq!\n puts \"There are %d dogs named %s.\" % [names.length, names.join(\", \")]\n puts\n puts \"The local variables are %s.\" % local_variables.join(\", \")\n puts \"The constants are %s.\" % constants.join(\", \")\nend\n", "language": "Ruby" }, { "code": "dog$ = \"Benjamin\"\ndoG$ = \"Smokey\"\nDog$ = \"Samba\"\nDOG$ = \"Bernie\"\nprint \"The 4 dogs are \"; dog$; \", \"; doG$; \", \"; Dog$; \" and \"; DOG$; \".\"\n", "language": "Run-BASIC" }, { "code": "fn main() {\n let dog = \"Benjamin\";\n let Dog = \"Samba\";\n let DOG = \"Bernie\";\n println!(\"The three dogs are named {}, {} and {}.\", dog, Dog, DOG);\n}\n", "language": "Rust" }, { "code": "<anon>:3:9: 3:12 warning: variable `Dog` should have a snake case name such as `dog`, #[warn(non_snake_case)] on by default\n<anon>:3 let Dog = \"Samba\";\n ^~~\n<anon>:4:9: 4:12 warning: variable `DOG` should have a snake case name such as `dog`, #[warn(non_snake_case)] on by default\n<anon>:4 let DOG = \"Bernie\";\n ^~~\n", "language": "Rust" }, { "code": "The three dogs are named Benjamin, Samba and Bernie.\n", "language": "Rust" }, { "code": "class MAIN is\n main is\n dog ::= \"Benjamin\";\n Dog ::= \"Samba\";\n DOG ::= \"Bernie\";\n #OUT + #FMT(\"The three dogs are %s, %s and %s\\n\",\n dog, Dog, DOG);\n end;\nend;\n", "language": "Sather" }, { "code": "val dog = \"Benjamin\"\nval Dog = \"Samba\"\nval DOG = \"Bernie\"\nprintln(\"There are three dogs named \" + dog + \", \" + Dog + \", and \" + DOG + \".\")\n", "language": "Scala" }, { "code": "(define dog \"Benjamin\")\n(define Dog \"Samba\")\n(define DOG \"Bernie\")\n\n(if (eq? dog DOG)\n (begin (display \"There is one dog named \")\n (display DOG)\n (display \".\")\n (newline))\n (begin (display \"The three dogs are named \")\n (display dog) (display \", \")\n (display Dog) (display \" and \")\n (display DOG)\n (display \".\")\n (newline)))\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst string: dog is \"Benjamin\";\nconst string: Dog is \"Samba\";\nconst string: DOG is \"Bernie\";\n\nconst proc: main is func\n begin\n writeln(\"The three dogs are named \" <& dog <& \", \" <& Dog <& \" and \" <& DOG <& \".\");\n end func;\n", "language": "Seed7" }, { "code": "set dog to \"Benjamin\"\nset Dog to \"Samba\"\nset DOG to \"Bernie\"\n\nput !\"There is just one dog named [[dog]].\"\n", "language": "SenseTalk" }, { "code": "dog := 'Benjamin';\nDog := 'Samba';\nDOG := 'Bernie';\nprint( 'There is just one dog named', dOg );\n", "language": "SETL" }, { "code": "var dog = 'Benjamin';\nvar Dog = 'Samba';\nvar DOG = 'Bernie';\nsay \"The three dogs are named #{dog}, #{Dog}, and #{DOG}.\";\n", "language": "Sidef" }, { "code": "begin\n text dog;\n dog :- blanks( 8 );\n dog := \"Benjamin\";\n Dog := \"Samba\";\n DOG := \"Bernie\";\n outtext( \"There is just one dog, named \" );\n outtext( dog );\n outimage\nend\n", "language": "Simula" }, { "code": "|dog Dog DOG|\ndog := 'Benjamin'.\nDog := 'Samba'.\nDOG := 'Bernie'.\n( 'The three dogs are named %1, %2 and %3' %\n { dog . Dog . DOG } ) displayNl.\n", "language": "Smalltalk" }, { "code": " DOG = 'Benjamin'\n Dog = 'Samba'\n dog = 'Bernie'\n OUTPUT = 'The three dogs are named ' DOG ', ' Dog ', and ' dog\nEND\n", "language": "SNOBOL4" }, { "code": "let\n val dog = \"Benjamin\"\n val Dog = \"Samba\"\n val DOG = \"Bernie\"\nin\n print(\"The three dogs are named \" ^ dog ^ \", \" ^ Dog ^ \", and \" ^ DOG ^ \".\\n\")\nend;\n", "language": "Standard-ML" }, { "code": ". local dog Benjamin\n. local Dog Samba\n. local DOG Bernie\n. display \"The three dogs are named $_dog, $_Dog, and $_DOG.\"\nThe three dogs are named Benjamin, Samba, and Bernie.\n", "language": "Stata" }, { "code": "let dog = \"Benjamin\"\nlet Dog = \"Samba\"\nlet DOG = \"Bernie\"\nprintln(\"The three dogs are named \\(dog), \\(Dog), and \\(DOG).\")\n", "language": "Swift" }, { "code": "set dog \"Benjamin\"\nset Dog \"Samba\"\nset DOG \"Bernie\"\nputs \"The three dogs are named $dog, $Dog and $DOG\"\n", "language": "Tcl" }, { "code": "LET dog$ = \"Benjamin\"\nLET Dog$ = \"Samba\"\nLET DOG$ = \"Bernie\"\nPRINT \"There is just one dog, named \"; dog$\nEND\n", "language": "True-BASIC" }, { "code": "dog=\"Benjamin\"\nDog=\"Samba\"\nDOG=\"Bernie\"\necho \"The three dogs are named $dog, $Dog and $DOG.\"\n", "language": "UNIX-Shell" }, { "code": "> decl string dog Dog DOG\n> set dog \"Benjamin\"\n> set Dog \"Samba\"\n> set DOG \"Bernie\"\n> out \"The three dogs are named \" dog \", \" Dog \", and \" DOG endl console\nThe three dogs are named Benjamin, Samba, and Bernie\n>\n", "language": "Ursa" }, { "code": "Public Sub case_sensitivity()\n 'VBA does not allow variables that only differ in case\n 'The VBA IDE vbe will rename variable 'dog' to 'DOG'\n 'when trying to define a second variable 'DOG'\n Dim DOG As String\n DOG = \"Benjamin\"\n DOG = \"Samba\"\n DOG = \"Bernie\"\n Debug.Print \"There is just one dog named \" & DOG\nEnd Sub\n", "language": "VBA" }, { "code": "var dog = \"Benjamin\"\nvar Dog = \"Samba\"\nvar DOG = \"Bernie\"\nSystem.print(\"The three dogs are named %(dog), %(Dog) and %(DOG).\")\n", "language": "Wren" }, { "code": "PROGRAM\t\"Case-sensitivity\"\nVERSION\t\"0.0000\"\n\nDECLARE FUNCTION Entry ()\n\nFUNCTION Entry ()\n dog$ = \"Benjamin\"\n dog$ = \"Smokey\"\n dog$ = \"Samba\"\n dog$ = \"Bernie\"\n\n PRINT \"There is just one dog, named \"; dog$\nEND FUNCTION\nEND PROGRAM\n", "language": "XBasic" }, { "code": "set dog=\"Benjamin\";\nset DOG=\"Samba\";\nset Dog=\"Bernie\";\nlog(`The three dogs are named {dog}, {DOG} and {Dog}.`);\n", "language": "XBS" }, { "code": "(SETQ DOG 'BENJAMIN)\n(SETQ Dog 'SAMBA)\n(SETQ dog 'BERNIE)\n(DISPLAY `(THERE IS JUST ONE DOG NAMED ,DOG))\n", "language": "XLISP" }, { "code": "dog$ = \"Benjamin\"\ndoG$ = \"Smokey\"\nDog$ = \"Samba\"\nDOG$ = \"Bernie\"\nprint \"The four dogs are named \", dog$, \", \", doG$, \", \", Dog$, \" and \", DOG$\nend\n", "language": "Yabasic" }, { "code": "const std = @import(\"std\");\n\npub fn main() void {\n const dog = \"Benjamin\";\n const Dog = \"Samba\";\n const DOG = \"Bernie\";\n\n std.debug.print(\"The three dogs are named {s}, {s}, and {s}.\\n\", .{ dog, Dog, DOG });\n}\n", "language": "Zig" }, { "code": "var dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\";\n", "language": "Zkl" }, { "code": "10 LET D$=\"Benjamin\"\n20 PRINT \"There is just one dog named \";d$\n", "language": "ZX-Spectrum-Basic" } ]
Case-sensitivity-of-identifiers
[ { "code": "---\ncategory:\n- Checksums\nfrom: http://rosettacode.org/wiki/Casting_out_nines\n", "language": "00-META" }, { "code": ";Task &nbsp; (in three parts):\n\n\n;Part 1\nWrite a procedure (say <math>\\mathit{co9}(x)</math>) which implements [https://web.archive.org/web/20120619091249/http://mathforum.org/library/drmath/view/55926.html Casting Out Nines] as described by returning the checksum for <math>x</math>. Demonstrate the procedure using the examples given there, or others you may consider lucky.\n\nNote that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.\n\nWith that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be \"casting out nines\", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.\n\n;Part 2\nNotwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:\n: Consider the statement \"318682 is 101558 + 217124 and squared is 101558217124\" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).\n: note that <math>318682</math> has the same checksum as (<math>101558 + 217124</math>);\n: note that <math>101558217124</math> has the same checksum as (<math>101558 + 217124</math>) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);\n: note that this implies that for Kaprekar numbers the checksum of <math>k</math> equals the checksum of <math>k^2</math>.\n\nDemonstrate that your procedure can be used to generate or filter a range of numbers with the property <math>\\mathit{co9}(k) = \\mathit{co9}(k^2)</math> and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;Part 3\nConsidering [http://mathworld.wolfram.com/CastingOutNines.html this MathWorld page], produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:\n: <math>\\mathit{co9}(x)</math> is the residual of <math>x</math> mod <math>9</math>;\n: the procedure can be extended to bases other than 9.\n\nDemonstrate your algorithm by generating or filtering a range of numbers with the property <math>k%(\\mathit{Base}-1) == (k^2)%(\\mathit{Base}-1)</math> and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n<br>\n;related tasks\n* [[First perfect square in base N with N unique digits]]\n* [[Kaprekar numbers]]\n<br>\n", "language": "00-TASK" }, { "code": "F CastOut(Base, Start, End)\n V ran = (0 .< Base - 1).filter(y -> y % (@Base - 1) == (y * y) % (@Base - 1))\n V (x, y) = divmod(Start, Base - 1)\n [Int] r\n L\n L(n) ran\n V k = (Base - 1) * x + n\n I k < Start\n L.continue\n I k > End\n R r\n r.append(k)\n x++\n\nL(v) CastOut(Base' 16, Start' 1, End' 255)\n print(v, end' ‘ ’)\nprint()\nL(v) CastOut(Base' 10, Start' 1, End' 99)\n print(v, end' ‘ ’)\nprint()\nL(v) CastOut(Base' 17, Start' 1, End' 288)\n print(v, end' ‘ ’)\nprint()\n", "language": "11l" }, { "code": "* Casting out nines 08/02/2017\nCASTOUT CSECT\n USING CASTOUT,R13 base register\n B 72(R15) skip savearea\n DC 17F'0' savearea\n STM R14,R12,12(R13) prolog\n ST R13,4(R15) \" <-\n ST R15,8(R13) \" ->\n LR R13,R15 \" addressability\n L R1,LOW low\n XDECO R1,XDEC edit low\n MVC PGT+4(4),XDEC+8 output low\n L R1,HIGH high\n XDECO R1,XDEC edit high\n MVC PGT+12(4),XDEC+8 output low\n L R1,BASE base\n XDECO R1,XDEC edit base\n MVC PGT+24(4),XDEC+8 output base\n XPRNT PGT,L'PGT print buffer\n L R2,BASE base\n BCTR R2,0 -1\n ST R2,RM rm=base-1\n LA R8,PG ipg=0\n SR R7,R7 j=0\n L R6,LOW i=low\n DO WHILE=(C,R6,LE,HIGH) do i=low to high\n LR R5,R6 i\n SR R4,R4 clear for div\n D R4,RM /rm\n LR R2,R4 r2=i mod rm\n LR R5,R6 i\n MR R4,R6 i*i\n SR R4,R4 clear for div\n D R4,RM /rm\n IF CR,R2,EQ,R4 THEN if (i//rm)=(i*i//rm) then\n LA R7,1(R7) j=j+1\n XDECO R6,XDEC edit i\n MVC 0(4,R8),XDEC+8 output i\n LA R8,4(R8) ipg=ipg+4\n IF C,R7,EQ,=F'20' THEN if j=20 then\n XPRNT PG,L'PG print buffer\n LA R8,PG ipg=0\n SR R7,R7 j=0\n MVC PG,=CL80' ' clear buffer\n ENDIF , end if\n ENDIF , end if\n LA R6,1(R6) i=i+1\n ENDDO , end do i\n IF LTR,R7,NE,R7 THEN if j<>0 then\n XPRNT PG,L'PG print buffer\n ENDIF , end if\n L R13,4(0,R13) epilog\n LM R14,R12,12(R13) \" restore\n XR R15,R15 \" rc=0\n BR R14 exit\nLOW DC F'1' low\nHIGH DC F'500' high\nBASE DC F'10' base\nRM DS F rm\nPGT DC CL80'for ... to ... base ...' buffer\nPG DC CL80' ' buffer\nXDEC DS CL12 temp for xdeco\n YREGS\n END CASTOUT\n", "language": "360-Assembly" }, { "code": "\\ casting out nines - based on the Action! sample\n\nHOW TO ADD v TO n: PUT n + v IN n\n\nPUT 10, 2, 0, 0 IN base, n, count, total\nFOR i IN { 1 .. base ** n }:\n ADD 1 TO total\n IF i mod ( base - 1 ) = ( i * i ) mod ( base - 1 ):\n ADD 1 TO count\n WRITE i\nWRITE // \"Trying\", count, \"numbers instead of\", total, \"numbers saves\"\nWRITE 100 - ( ( 100 * count ) / total ), \"%\" /\n", "language": "ABC" }, { "code": "INT FUNC Power(INT a,b)\n INT i,res\n\n res=1\n FOR i=1 TO b\n DO\n res==*a\n OD\nRETURN (res)\n\nPROC Main()\n DEFINE BASE=\"10\"\n DEFINE N=\"2\"\n INT i,max,count,total,perc\n\n max=Power(BASE,N)\n count=0 total=0\n FOR i=1 TO max\n DO\n total==+1\n IF i MOD (BASE-1)=(i*i) MOD (BASE-1) THEN\n count==+1\n PrintI(i) Put(32)\n FI\n OD\n perc=100-100*count/total\n PrintF(\"%E%ETrying %I numbers instead of %I numbers saves %I%%\",count,total,perc)\nRETURN\n", "language": "Action-" }, { "code": "BEGIN # casting out nines - translated from the Action! sample #\n INT base = 10;\n INT n = 2;\n INT count := 0;\n INT total := 0;\n FOR i TO base ^ n DO\n total +:= 1;\n IF i MOD ( base - 1 ) = ( i * i ) MOD ( base - 1 ) THEN\n count +:= 1;\n print( ( whole( i, 0 ), \" \" ) )\n FI\n OD;\n print( ( newline, newline, \"Trying \", whole( count, 0 )\n , \" numbers instead of \", whole( total, 0 )\n , \" numbers saves \", fixed( 100 - ( ( 100 * count ) / total ), -6, 2 )\n , \"%\", newline\n )\n )\nEND\n", "language": "ALGOL-68" }, { "code": "N: 2\nbase: 10\nc1: 0\nc2: 0\n\nloop 1..(base^N)-1 'k [\n c1: c1 + 1\n\n if (k%base-1)= (k*k)%base-1 [\n c2: c2 + 1\n prints ~\"|k| \"\n ]\n]\n\nprint \"\"\nprint [\"Trying\" c2 \"numbers instead of\" c1 \"numbers saves\" 100.0 - 100.0*c2//c1 \"%\"]\n", "language": "Arturo" }, { "code": "# syntax: GAWK -f CASTING_OUT_NINES.AWK\n# converted from C\nBEGIN {\n base = 10\n for (k=1; k<=base^2; k++) {\n c1++\n if (k % (base-1) == (k*k) % (base-1)) {\n c2++\n printf(\"%d \",k)\n }\n }\n printf(\"\\nTrying %d numbers instead of %d numbers saves %.2f%%\\n\",c2,c1,100-(100*c2/c1))\n exit(0)\n}\n", "language": "AWK" }, { "code": "base = 10\nc1 = 0\nc2 = 0\nfor k = 1 to (base ^ 2) - 1\n\tc1 += 1\n\tif k % (base - 1) = (k * k) % (base - 1) then c2 += 1: print k; \" \";\nnext k\nprint\nprint \"Trying \"; c2; \" numbers instead of \"; c1; \" numbers saves \"; 100 - (100 * c2 / c1); \"%\"\nend\n", "language": "BASIC256" }, { "code": "#include <stdio.h>\n#include <math.h>\n\nint main() {\n const int N = 2;\n int base = 10;\n int c1 = 0;\n int c2 = 0;\n int k;\n\n for (k = 1; k < pow(base, N); k++) {\n c1++;\n if (k % (base - 1) == (k * k) % (base - 1)) {\n c2++;\n printf(\"%d \", k);\n }\n }\n\n printf(\"\\nTring %d numbers instead of %d numbers saves %f%%\\n\", c2, c1, 100.0 - 100.0 * c2 / c1);\n return 0;\n}\n", "language": "C" }, { "code": "// Casting Out Nines\n//\n// Nigel Galloway. June 24th., 2012\n//\n#include <iostream>\nint main() {\n\tint Base = 10;\n\tconst int N = 2;\n\tint c1 = 0;\n\tint c2 = 0;\n\tfor (int k=1; k<pow((double)Base,N); k++){\n\t\tc1++;\n\t\tif (k%(Base-1) == (k*k)%(Base-1)){\n\t\t\tc2++;\n\t\t\tstd::cout << k << \" \";\n\t\t}\n\t}\n\tstd::cout << \"\\nTrying \" << c2 << \" numbers instead of \" << c1 << \" numbers saves \" << 100 - ((double)c2/c1)*100 << \"%\" <<std::endl;\n\treturn 0;\n}\n", "language": "C++" }, { "code": "// Casting Out Nines Generator - Compiles with gcc4.6, MSVC 11, and CLang3\n//\n// Nigel Galloway. June 24th., 2012\n//\n#include <iostream>\n#include <vector>\nstruct ran {\n\tconst int base;\n\tstd::vector<int> rs;\n\tran(const int base) : base(base) { for (int nz=0; nz<base-1; nz++) if(nz*(nz-1)%(base-1) == 0) rs.push_back(nz); }\n};\nclass co9 {\nprivate:\n\tconst ran* _ran;\n\tconst int _end;\n\tint _r,_x,_next;\npublic:\n\tbool operator!=(const co9& other) const {return operator*() <= _end;}\n\tco9 begin() const {return *this;}\n co9 end() const {return *this;}\n\tint operator*() const {return _next;}\n\tco9(const int start, const int end, const ran* r)\n\t:_ran(r)\n\t,_end(end)\n\t,_r(1)\n\t,_x(start/_ran->base)\n\t,_next((_ran->base-1)*_x + _ran->rs[_r])\n\t{\n\t\twhile (operator*() < start) operator++();\n\t}\n\tconst co9& operator++() {\n\t\tconst int oldr = _r;\n\t\t_r = ++_r%_ran->rs.size();\n\t\tif (_r<oldr) _x++;\n\t\t_next = (_ran->base-1)*_x + _ran->rs[_r];\n\t\treturn *this;\n\t}\n};\n\nint main() {\n\tran r(10);\n\tfor (int i : co9(1,99,&r)) { std::cout << i << ' '; }\n\treturn 0;\n}\n", "language": "C++" }, { "code": "struct ran {\n\tconst int base;\n\tstd::vector<int> rs;\n\tran(const int base) : base(base) { for (int nz=0; nz<base-1; nz++) if(SumDigits(nz) == SumDigits(nz*nz)) rs.push_back(nz); }\n};\n", "language": "C++" }, { "code": "int main() {\n\tran r(16);\n\tfor (int i : co9(1,255,&r)) { std::cout << i << ' '; }\n\treturn 0;\n}\n", "language": "C++" }, { "code": "int main() {\n\tran r(17);\n\tfor (int i : co9(1,288,&r)) { std::cout << i << ' '; }\n\treturn 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace CastingOutNines {\n public static class Helper {\n public static string AsString<T>(this IEnumerable<T> e) {\n var it = e.GetEnumerator();\n\n StringBuilder builder = new StringBuilder();\n builder.Append(\"[\");\n\n if (it.MoveNext()) {\n builder.Append(it.Current);\n }\n while (it.MoveNext()) {\n builder.Append(\", \");\n builder.Append(it.Current);\n }\n\n builder.Append(\"]\");\n return builder.ToString();\n }\n }\n\n class Program {\n static List<int> CastOut(int @base, int start, int end) {\n int[] ran = Enumerable\n .Range(0, @base - 1)\n .Where(a => a % (@base - 1) == (a * a) % (@base - 1))\n .ToArray();\n int x = start / (@base - 1);\n\n List<int> result = new List<int>();\n while (true) {\n foreach (int n in ran) {\n int k = (@base - 1) * x + n;\n if (k < start) {\n continue;\n }\n if (k > end) {\n return result;\n }\n result.Add(k);\n }\n x++;\n }\n }\n\n static void Main() {\n Console.WriteLine(CastOut(16, 1, 255).AsString());\n Console.WriteLine(CastOut(10, 1, 99).AsString());\n Console.WriteLine(CastOut(17, 1, 288).AsString());\n }\n }\n}\n", "language": "C-sharp" }, { "code": "100 cls\n110 bs = 10 : c1 = 0 : c2 = 0\n120 for k = 1 to (bs^2)-1\n130 c1 = c1+1\n140 if k mod (bs-1) = (k*k) mod (bs-1) then c2 = c2+1 : print k;\n150 next k\n160 print\n170 print \"Trying \";c2;\"numbers instead of \";c1;\"numbers saves \";100-(100*c2/c1);\"%\"\n180 end\n", "language": "Chipmunk-Basic" }, { "code": ";;A macro was used to ensure that the filter is inlined.\n;;Larry Hignight. Last updated on 7/3/2012.\n(defmacro kaprekar-number-filter (n &optional (base 10))\n `(= (mod ,n (1- ,base)) (mod (* ,n ,n) (1- ,base))))\n\n(defun test (&key (start 1) (stop 10000) (base 10) (collect t))\n (let ((count 0)\n\t(nums))\n (loop for i from start to stop do\n\t (when (kaprekar-number-filter i base)\n\t (if collect (push i nums))\n\t (incf count)))\n (format t \"~d potential Kaprekar numbers remain (~~~$% filtered out).~%\"\n\t count (* (/ (- stop count) stop) 100))\n (if collect (reverse nums))))\n", "language": "Common-Lisp" }, { "code": "precision 4\n\ndefine base = 10, c1 = 0, c2 = 0\n\nfor k = 1 to (base ^ 2) - 1\n\n\tlet c1 = c1 + 1\n\n\tif k % (base - 1) = (k * k) % (base - 1) then\n\n\t\tlet c2 = c2 + 1\n\t\tprint k\n\n\tendif\n\nnext k\n\nprint \"trying \", c2, \" numbers instead of \", c1, \" numbers saves \", 100 - (100 * c2 / c1), \"%\"\n", "language": "Craft-Basic" }, { "code": "import std.stdio, std.algorithm, std.range;\n\nuint[] castOut(in uint base=10, in uint start=1, in uint end=999999) {\n auto ran = iota(base - 1)\n .filter!(x => x % (base - 1) == (x * x) % (base - 1));\n auto x = start / (base - 1);\n immutable y = start % (base - 1);\n\n typeof(return) result;\n while (true) {\n foreach (immutable n; ran) {\n immutable k = (base - 1) * x + n;\n if (k < start)\n continue;\n if (k > end)\n return result;\n result ~= k;\n }\n x++;\n }\n}\n\nvoid main() {\n castOut(16, 1, 255).writeln;\n castOut(10, 1, 99).writeln;\n castOut(17, 1, 288).writeln;\n}\n", "language": "D" }, { "code": "base = 10\nfor k = 1 to base * base - 1\n c1 += 1\n if k mod (base - 1) = (k * k) mod (base - 1)\n c2 += 1\n write k & \" \"\n .\n.\nprint \"\"\nprint \"Trying \" & c2 & \" numbers instead of \" & c1 & \" numbers saves \" & 100 - 100 * c2 / c1\n", "language": "EasyLang" }, { "code": "program castout9;\n{$ifdef fpc}{$mode delphi}{$endif}\nuses generics.collections;\ntype\n TIntegerList = TSortedList<integer>;\n\nprocedure co9(const start,base,lim:integer;kaprekars:array of integer);\nvar\n C1:integer = 0;\n C2:integer = 0;\n S:TIntegerlist;\n k,i:integer;\nbegin\n S:=TIntegerlist.Create;\n for k := start to lim do\n begin\n inc(C1);\n if k mod (base-1) = (k*k) mod (base-1) then\n begin\n inc(C2);\n S.Add(k);\n end;\n end;\n writeln('Valid subset: ');\n for i in Kaprekars do\n if not s.contains(i) then\n writeln('invalid ',i);\n\n for i in s do write(i:4);\n writeln;\n write('The Kaprekars in this range [');\n for i in kaprekars do write(i:4);\n writeln('] are included');\n writeln('Trying ',C2, ' numbers instead of ', C1,' saves ',100-(C2 * 100 /C1):3:2,',%.');\n writeln;\n S.Free;\nend;\n\nbegin\n co9(1, 10, 99, [1,9,45,55,99]);\n co9(1, 10, 1000, [1,9,45,55,99,297,703,999]);\nend.\n", "language": "Free-Pascal-Lazarus" }, { "code": "Const base10 = 10\nDim As Integer c1 = 0, c2 = 0, k = 1\n\nFor k = 1 To base10^2\n c1 += 1\n If (k Mod (base10-1) = (k*k) Mod (base10-1)) Then c2 += 1: Print k;\" \";\nNext k\n\nPrint\nPrint Using \"Intentar ## numeros en lugar de ### numeros ahorra un ##.##%\"; c2; c1; 100-(100*c2/c1)\nSleep\n", "language": "FreeBASIC" }, { "code": "_base10 = 10\n\nvoid local fn CastingOutNines\n NSUInteger i, c1 = 0, c2 = 0\n float percent\n\n for i = 1 to _base10^2\n c1++\n if ( i mod ( _base10 -1 ) == ( i * i ) mod ( _base10 - 1 ) ) then c2++ : printf @\"%d \\b\", i\n next\n print\n percent = 100 -( 100 * c2 / c1 )\n printf @\"Trying %d numbers instead of %d numbers saves %.2f%%\", c2, c1, percent\nend fn\n\nfn CastingOutNines\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\n\n Dim base10 As Integer = 10\n Dim c1 As Integer = 0, c2 As Integer = 0, k As Integer\n\n For k = 1 To base10 ^ 2\n c1 += 1\n If (k Mod (base10 - 1) = (k * k) Mod (base10 - 1)) Then\n c2 += 1\n Print k; \" \";\n End If\n Next\n\n Print \"\\nTrying \"; c2; \" numbers instead of \"; c1; \" numbers saves \"; 100 - (100 * c2 / c1); \"%\"\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"strconv\"\n)\n\n// A casting out nines algorithm.\n\n// Quoting from: http://mathforum.org/library/drmath/view/55926.html\n/*\nFirst, for any number we can get a single digit, which I will call the\n\"check digit,\" by repeatedly adding the digits. That is, we add the\ndigits of the number, then if there is more than one digit in the\nresult we add its digits, and so on until there is only one digit\nleft.\n\n...\n\nYou may notice that when you add the digits of 6395, if you just\nignore the 9, and the 6+3 = 9, you still end up with 5 as your check\ndigit. This is because any 9's make no difference in the result.\nThat's why the process is called \"casting out\" nines. Also, at any\nstep in the process, you can add digits, not just at the end: to do\n8051647, I can say 8 + 5 = 13, which gives 4; plus 1 is 5, plus 6 is\n11, which gives 2, plus 4 is 6, plus 7 is 13 which gives 4. I never\nhave to work with numbers bigger than 18.\n*/\n// The twist is that co9Peterson returns a function to do casting out nines\n// in any specified base from 2 to 36.\nfunc co9Peterson(base int) (cob func(string) (byte, error), err error) {\n if base < 2 || base > 36 {\n return nil, fmt.Errorf(\"co9Peterson: %d invalid base\", base)\n }\n // addDigits adds two digits in the specified base.\n // People perfoming casting out nines by hand would usually have their\n // addition facts memorized. In a program, a lookup table might be\n // analogous, but we expediently use features of the programming language\n // to add digits in the specified base.\n addDigits := func(a, b byte) (string, error) {\n ai, err := strconv.ParseInt(string(a), base, 64)\n if err != nil {\n return \"\", err\n }\n bi, err := strconv.ParseInt(string(b), base, 64)\n if err != nil {\n return \"\", err\n }\n return strconv.FormatInt(ai+bi, base), nil\n }\n // a '9' in the specified base. that is, the greatest digit.\n s9 := strconv.FormatInt(int64(base-1), base)\n b9 := s9[0]\n // define result function. The result function may return an error\n // if n is not a valid number in the specified base.\n cob = func(n string) (r byte, err error) {\n r = '0'\n for i := 0; i < len(n); i++ { // for each digit of the number\n d := n[i]\n switch {\n case d == b9: // if the digit is '9' of the base, cast it out\n continue\n // if the result so far is 0, the digit becomes the result\n case r == '0':\n r = d\n continue\n }\n // otherwise, add the new digit to the result digit\n s, err := addDigits(r, d)\n if err != nil {\n return 0, err\n }\n switch {\n case s == s9: // if the sum is \"9\" of the base, cast it out\n r = '0'\n continue\n // if the sum is a single digit, it becomes the result\n case len(s) == 1:\n r = s[0]\n continue\n }\n // otherwise, reduce this two digit intermediate result before\n // continuing.\n r, err = cob(s)\n if err != nil {\n return 0, err\n }\n }\n return\n }\n return\n}\n\n// Subset code required by task. Given a base and a range specified with\n// beginning and ending number in that base, return candidate Kaprekar numbers\n// based on the observation that k%(base-1) must equal (k*k)%(base-1).\n// For the % operation, rather than the language built-in operator, use\n// the method of casting out nines, which in fact implements %(base-1).\nfunc subset(base int, begin, end string) (s []string, err error) {\n // convert begin, end to native integer types for easier iteration\n begin64, err := strconv.ParseInt(begin, base, 64)\n if err != nil {\n return nil, fmt.Errorf(\"subset begin: %v\", err)\n }\n end64, err := strconv.ParseInt(end, base, 64)\n if err != nil {\n return nil, fmt.Errorf(\"subset end: %v\", err)\n }\n // generate casting out nines function for specified base\n cob, err := co9Peterson(base)\n if err != nil {\n return\n }\n for k := begin64; k <= end64; k++ {\n ks := strconv.FormatInt(k, base)\n rk, err := cob(ks)\n if err != nil { // assertion\n panic(err) // this would indicate a bug in subset\n }\n rk2, err := cob(strconv.FormatInt(k*k, base))\n if err != nil { // assertion\n panic(err) // this would indicate a bug in subset\n }\n // test for candidate Kaprekar number\n if rk == rk2 {\n s = append(s, ks)\n }\n }\n return\n}\n\nvar testCases = []struct {\n base int\n begin, end string\n kaprekar []string\n}{\n {10, \"1\", \"100\", []string{\"1\", \"9\", \"45\", \"55\", \"99\"}},\n {17, \"10\", \"gg\", []string{\"3d\", \"d4\", \"gg\"}},\n}\n\nfunc main() {\n for _, tc := range testCases {\n fmt.Printf(\"\\nTest case base = %d, begin = %s, end = %s:\\n\",\n tc.base, tc.begin, tc.end)\n s, err := subset(tc.base, tc.begin, tc.end)\n if err != nil {\n log.Fatal(err)\n }\n fmt.Println(\"Subset: \", s)\n fmt.Println(\"Kaprekar:\", tc.kaprekar)\n sx := 0\n for _, k := range tc.kaprekar {\n for {\n if sx == len(s) {\n fmt.Printf(\"Fail:\", k, \"not in subset\")\n return\n }\n if s[sx] == k {\n sx++\n break\n }\n sx++\n }\n }\n fmt.Println(\"Valid subset.\")\n }\n}\n", "language": "Go" }, { "code": "co9 n\n | n <= 8 = n\n | otherwise = co9 $ sum $ filter (/= 9) $ digits 10 n\n\ntask2 = filter (\\n -> co9 n == co9 (n ^ 2)) [1 .. 100]\n\ntask3 k = filter (\\n -> n `mod` k == n ^ 2 `mod` k) [1 .. 100]\n", "language": "Haskell" }, { "code": "digits base = map (`mod` base) . takeWhile (> 0) . iterate (`div` base)\n", "language": "Haskell" }, { "code": "digits base = Data.List.unfoldr modDiv\n where modDiv 0 = Nothing\n modDiv n = let (q, r) = (n `divMod` base) in Just (r, q)\n", "language": "Haskell" }, { "code": "castout=: 1 :0\n [: (#~ ] =&((m-1)&|) *:) <. + [: i. (+*)@-~\n)\n", "language": "J" }, { "code": " 0 (10 castout) 100\n0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100\n", "language": "J" }, { "code": "castout=: 1 :0\n [: (#~ 0 = (m-1) | 0 _1 1&p.) <. + [: i. (+*)@-~\n)\n", "language": "J" }, { "code": " (#~ 0=9|0 _1 1&p.) i.101\n0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100\n (#~ ] =&(9&|) *:) i. 101\n0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100\n", "language": "J" }, { "code": " (#~ ] =&(co9=: 9&|) *:) i. 101\n0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100\n", "language": "J" }, { "code": "co9=: 9&|\n (#~ ] =&co9 *:) i. 101\n0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100\n", "language": "J" }, { "code": "import java.util.*;\nimport java.util.stream.IntStream;\n\npublic class CastingOutNines {\n\n public static void main(String[] args) {\n System.out.println(castOut(16, 1, 255));\n System.out.println(castOut(10, 1, 99));\n System.out.println(castOut(17, 1, 288));\n }\n\n static List<Integer> castOut(int base, int start, int end) {\n int[] ran = IntStream\n .range(0, base - 1)\n .filter(x -> x % (base - 1) == (x * x) % (base - 1))\n .toArray();\n\n int x = start / (base - 1);\n\n List<Integer> result = new ArrayList<>();\n while (true) {\n for (int n : ran) {\n int k = (base - 1) * x + n;\n if (k < start)\n continue;\n if (k > end)\n return result;\n result.add(k);\n }\n x++;\n }\n }\n}\n", "language": "Java" }, { "code": "function main(s, e, bs, pbs) {\n bs = bs || 10;\n pbs = pbs || 10\n document.write('start:', toString(s), ' end:', toString(e),\n ' base:', bs, ' printBase:', pbs)\n document.write('<br>castOutNine: ');\n castOutNine()\n document.write('<br>kaprekar: ');\n kaprekar()\n document.write('<br><br>')\n\n function castOutNine() {\n for (var n = s, k = 0, bsm1 = bs - 1; n <= e; n += 1)\n if (n % bsm1 == (n * n) % bsm1) k += 1,\n document.write(toString(n), ' ')\n document.write('<br>trying ', k, ' numbers instead of ', n = e - s + 1,\n ' numbers saves ', (100 - k / n * 100)\n .toFixed(3), '%')\n }\n\n function kaprekar() {\n for (var n = s; n <= e; n += 1)\n if (isKaprekar(n)) document.write(toString(n), ' ')\n\n function isKaprekar(n) {\n if (n < 1) return false\n if (n == 1) return true\n var s = (n * n)\n .toString(bs)\n for (var i = 1, e = s.length; i < e; i += 1) {\n var a = parseInt(s.substr(0, i), bs)\n var b = parseInt(s.substr(i), bs)\n if (b && a + b == n) return true\n }\n return false\n }\n }\n\n function toString(n) {\n return n.toString(pbs)\n .toUpperCase()\n }\n}\nmain(1, 10 * 10 - 1)\nmain(1, 16 * 16 - 1, 16)\nmain(1, 17 * 17 - 1, 17)\nmain(parseInt('10', 17), parseInt('gg', 17), 17, 17)\n", "language": "JavaScript" }, { "code": "(() => {\n 'use strict';\n\n // co9 :: Int -> Int\n const co9 = n =>\n n <= 8 ? n : co9(\n digits(10, n)\n .reduce((a, x) => x !== 9 ? a + x : a, 0)\n );\n\n // GENERIC FUNCTIONS\n\n // digits :: Int -> Int -> [Int]\n const digits = (base, n) => {\n if (n < base) return [n];\n const [q, r] = quotRem(n, base);\n return [r].concat(digits(base, q));\n };\n\n // quotRem :: Integral a => a -> a -> (a, a)\n const quotRem = (m, n) => [Math.floor(m / n), m % n];\n\n // range :: Int -> Int -> [Int]\n const range = (m, n) =>\n Array.from({\n length: Math.floor(n - m) + 1\n }, (_, i) => m + i);\n\n // squared :: Num a => a -> a\n const squared = n => Math.pow(n, 2);\n\n // show :: a -> String\n const show = x => JSON.stringify(x, null, 2);\n\n // TESTS\n return show({\n test1: co9(232345), //-> 1\n test2: co9(34234234), //-> 7\n test3: co9(232345 + 34234234) === co9(232345) + co9(34234234), //-> true\n test4: co9(232345 * 34234234) === co9(232345) * co9(34234234), //-> true,\n task2: range(1, 100)\n .filter(n => co9(n) === co9(squared(n))),\n task3: (k => range(1, 100)\n .filter(n => (n % k) === (squared(n) % k)))(16)\n });\n})();\n", "language": "JavaScript" }, { "code": "def co9:\n def digits: tostring | explode | map(. - 48); # \"0\" is 48\n if . == 9 then 0\n elif 0 <= . and . <= 8 then .\n else digits | add | co9\n end;\n", "language": "Jq" }, { "code": "def co9_equals_co9_squared: co9 == ((.*.)|co9);\n", "language": "Jq" }, { "code": "[range (1;101) | select( co9_equals_co9_squared )\n", "language": "Jq" }, { "code": "[ range(1;101) | select(is_kaprekar) ]\n", "language": "Jq" }, { "code": "def verify:\n range(1; .)\n | select(is_kaprekar and (co9_equals_co9_squared | not));\n", "language": "Jq" }, { "code": "def proportion(base):\n def count(stream): reduce stream as $i (0; . + 1);\n . as $n\n | (base - 1) as $b\n | count( range(1; 1+$n) | select( . % $b == (.*.) % $b) ) / $n ;\n", "language": "Jq" }, { "code": "0.3\n0.27\n0.267\n0.2667\n0.26667\n", "language": "Jq" }, { "code": "co9(x) = x == 9 ? 0 :\n 1<=x<=8 ? x :\n co9(sum(digits(x)))\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nfun castOut(base: Int, start: Int, end: Int): List<Int> {\n val b = base - 1\n val ran = (0 until b).filter { it % b == (it * it) % b }\n var x = start / b\n val result = mutableListOf<Int>()\n while (true) {\n for (n in ran) {\n val k = b * x + n\n if (k < start) continue\n if (k > end) return result\n result.add(k)\n }\n x++\n }\n}\n\nfun main(args: Array<String>) {\n println(castOut(16, 1, 255))\n println()\n println(castOut(10, 1, 99))\n println()\n println(castOut(17, 1, 288))\n}\n", "language": "Kotlin" }, { "code": "local N = 2\nlocal base = 10\nlocal c1 = 0\nlocal c2 = 0\n\nfor k = 1, math.pow(base, N) - 1 do\n c1 = c1 + 1\n if k % (base - 1) == (k * k) % (base - 1) then\n c2 = c2 + 1\n io.write(k .. ' ')\n end\nend\n\nprint()\nprint(string.format(\"Trying %d numbers instead of %d numbers saves %f%%\", c2, c1, 100.0 - 100.0 * c2 / c1))\n", "language": "Lua" }, { "code": "Co9[n_, b_: 10] :=\n With[{ans = FixedPoint[Total@IntegerDigits[#, b] &, n]},\n If[ans == b - 1, 0, ans]];\n", "language": "Mathematica" }, { "code": "Co9 /@ (vals = {1235, 2345, 4753})\n {2, 5, 1}\n\nTotal[Co9 /@ vals] == Co9[Total[vals]]\n True\n", "language": "Mathematica" }, { "code": "task2 = Select[Range@100, Co9[#] == Co9[#^2] &]\n", "language": "Mathematica" }, { "code": "Co9eff[n_, b_: 10] := Mod[n, b - 1];\n", "language": "Mathematica" }, { "code": "task2 == Select[Range@100, Co9eff[#] == Co9eff[#^2] &]\n True\n\nSelect[Range@100, Co9eff[#, 17] == Co9eff[#^2, 17] &]\n {1, 16, 17, 32, 33, 48, 49, 64, 65, 80, 81, 96, 97}\n", "language": "Mathematica" }, { "code": "100 CLS\n110 BS = 10 : C1 = 0 : C2 = 0\n120 FOR K = 1 TO (BS^2)-1\n130 C1 = C1+1\n140 IF K MOD (BS-1) = (K*K) MOD (BS-1) THEN C2 = C2+1 : PRINT K;\n150 NEXT K\n160 PRINT\n170 PRINT USING \"Trying ## numbers instead of ### numbers saves ##.##%\";C2;C1;100-(100*C2/C1)\n180 END\n", "language": "MSX-Basic" }, { "code": "import sequtils\n\niterator castOut(base = 10, start = 1, ending = 999_999): int =\n var ran: seq[int] = @[]\n for y in 0 ..< base-1:\n if y mod (base - 1) == (y*y) mod (base - 1):\n ran.add(y)\n\n var x = start div (base - 1)\n var y = start mod (base - 1)\n\n block outer:\n while true:\n for n in ran:\n let k = (base - 1) * x + n\n if k < start:\n continue\n if k > ending:\n break outer\n yield k\n inc x\n\necho toSeq(castOut(base=16, start=1, ending=255))\n", "language": "Nim" }, { "code": "class CastingNines {\n function : Main(args : String[]) ~ Nil {\n base := 10;\n N := 2;\n c1 := 0;\n c2 := 0;\n\n for (k:=1; k<base->As(Float)->Power(N->As(Float)); k+=1;){\n c1+=1;\n if (k%(base-1) = (k*k)%(base-1)){\n c2+=1;\n IO.Console->Print(k)->Print(\" \");\n };\n };\n\n IO.Console->Print(\"\\nTrying \")->Print(c2)->Print(\" numbers instead of \")\n ->Print(c1)->Print(\" numbers saves \")->Print(100 - (c2->As(Float)/c1\n ->As(Float)*100))->PrintLine(\"%\");\n }\n}\n", "language": "Objeck" }, { "code": "{base=10;\nN=2;\nc1=c2=0;\nfor(k=1,base^N-1,\n c1++;\n if (k%(base-1) == k^2%(base-1),\n c2++;\n print1(k\" \")\n );\n);\nprint(\"\\nTrying \"c2\" numbers instead of \"c1\" numbers saves \" 100.-(c2/c1)*100 \"%\")}\n", "language": "PARI-GP" }, { "code": "sub co9 { # Follows the simple procedure asked for in Part 1\n my $n = shift;\n return $n if $n < 10;\n my $sum = 0; $sum += $_ for split(//,$n);\n co9($sum);\n}\n\nsub showadd {\n my($n,$m) = @_;\n print \"( $n [\",co9($n),\"] + $m [\",co9($m),\"] ) [\",co9(co9($n)+co9($m)),\"]\",\n \" = \", $n+$m,\" [\",co9($n+$m),\"]\\n\";\n}\n\nsub co9filter {\n my $base = shift;\n die unless $base >= 2;\n my($beg, $end, $basem1) = (1, $base*$base-1, $base-1);\n my @list = grep { $_ % $basem1 == $_*$_ % $basem1 } $beg .. $end;\n ($end, scalar(@list), @list);\n}\n\nprint \"Part 1: Create a simple filter and demonstrate using simple example.\\n\";\nshowadd(6395, 1259);\n\nprint \"\\nPart 2: Use this to filter a range with co9(k) == co9(k^2).\\n\";\nprint join(\" \", grep { co9($_) == co9($_*$_) } 1..99), \"\\n\";\n\nprint \"\\nPart 3: Use efficient method on range.\\n\";\nfor my $base (10, 17) {\n my($N, $n, @l) = co9filter($base);\n printf \"[@l]\\nIn base %d, trying %d numbers instead of %d saves %.4f%%\\n\\n\",\n $base, $n, $N, 100-($n/$N)*100;\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">co9</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">start</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">lim</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">kaprekars</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">c1</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">c2</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">start</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">lim</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">c1</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">c2</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">k</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"valid subset\"</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">kaprekars</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">kaprekars</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"***INVALID***\"</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)></span><span style=\"color: #000000;\">25</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">..-</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"...\"</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%V\\nKaprekar numbers: %V - %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">kaprekars</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Trying %d numbers instead of %d saves %3.2f%%\\n\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">c2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">c1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">-(</span><span style=\"color: #000000;\">c2</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">c1</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">co9</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">99</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">45</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">55</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">99</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">co9</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0(17)10</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0(17)3d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0(17)d4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0(17)gg</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">co9</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1000</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">45</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">55</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">99</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">297</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">703</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">999</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "go =>\n Base10 = 10,\n foreach(N in [2,6])\n casting_out_nines(Base10,N)\n end,\n nl,\n Base16 = 16,\n foreach(N in [2,6])\n casting_out_nines(Base16,N)\n end,\n nl.\n\ncasting_out_nines(Base,N) =>\n println([base=Base,n=N]),\n C1 = 0,\n C2 = 0,\n Ks = [],\n LimitN = 3,\n foreach(K in 1..Base**N-1)\n C1 := C1 + 1,\n if K mod (Base-1) == (K*K) mod (Base-1) then\n C2 := C2+1,\n if N <= LimitN then\n Ks := Ks ++ [K]\n end\n end\n end,\n if C2 <= 100 then\n println(ks=Ks)\n end,\n printf(\"Trying %d numbers instead of %d numbers saves %2.3f%%\\n\", C2, C1, 100 - ((C2/C1)*100)),\n nl.\n", "language": "Picat" }, { "code": "(de kaprekar (N)\n (let L (cons 0 (chop (* N N)))\n (for ((I . R) (cdr L) R (cdr R))\n (NIL (gt0 (format R)))\n (T (= N (+ @ (format (head I L)))) N) ) ) )\n\n(de co9 (N)\n (until\n (> 9\n (setq N\n (sum\n '((N) (unless (= \"9\" N) (format N)))\n (chop N) ) ) ) )\n N )\n\n(println 'Part1:)\n(println\n (=\n (co9 (+ 6395 1259))\n (co9 (+ (co9 6395) (co9 1259))) ) )\n\n(println 'Part2:)\n(println\n (filter\n '((N) (= (co9 N) (co9 (* N N))))\n (range 1 100) ) )\n(println\n (filter kaprekar (range 1 100)) )\n\n(println 'Part3 '- 'base17:)\n(println\n (filter\n '((N) (= (% N 16) (% (* N N) 16)))\n (range 1 100) ) )\n\n(bye)\n", "language": "PicoLisp" }, { "code": "OpenConsole()\nDefine.i base, c1, c2, k\n\nbase = 10\nc1 = 0\nc2 = 0\nFor k = 1 To Pow(base, 2) - 1\n c1 + 1\n If k % (base - 1) = (k * k) % (base - 1)\n c2 + 1\n Print(Str(k) + \" \")\n EndIf\nNext k\n\nPrintN(#CRLF$ + \"Trying \" + Str(c2) + \" numbers instead of \" + Str(c1) + \" numbers saves \" + Str(100 - (100 * c2 / c1)) + \"%\")\n\nPrintN(#CRLF$ + \"Press ENTER to exit\"): Input()\nCloseConsole()\n", "language": "PureBasic" }, { "code": "# Casting out Nines\n#\n# Nigel Galloway: June 27th., 2012,\n#\ndef CastOut(Base=10, Start=1, End=999999):\n ran = [y for y in range(Base-1) if y%(Base-1) == (y*y)%(Base-1)]\n x,y = divmod(Start, Base-1)\n while True:\n for n in ran:\n k = (Base-1)*x + n\n if k < Start:\n continue\n if k > End:\n return\n yield k\n x += 1\n\nfor V in CastOut(Base=16,Start=1,End=255):\n print(V, end=' ')\n", "language": "Python" }, { "code": "CLS\nbs = 10: c1 = 0: c2 = 0\nFOR k = 1 TO (bs ^ 2) - 1\n c1 = c1 + 1\n IF k MOD (bs - 1) = (k * k) MOD (bs - 1) THEN c2 = c2 + 1: PRINT k;\nNEXT k\nPRINT\nPRINT USING \"Trying ## numbers instead of ### numbers saves ##.##%\"; c2; c1; 100 - (100 * c2 / c1)\n", "language": "QBasic" }, { "code": " [ true unrot swap\n witheach\n [ over find\n over found not if\n [ dip not\n conclude ] ]\n drop ] is subset ( [ [ --> [ )\n\n [ abs 0 swap\n [ 10 /mod rot +\n dup 8 > if [ 9 - ]\n swap dup 0 = until ]\n drop ] is co9 ( n --> n )\n\n say \"Part 1: Examples from Dr Math page.\" cr cr\n say \"6395 1259 + = \" 6395 1259 + echo cr\n say \"6395 co9 = \" 6395 co9 echo cr\n say \"1259 co9 = \" 1259 co9 echo cr\n say \"5 8 + co9 = \" 5 8 + co9 echo cr\n say \"7654 co9 = \" 7654 co9 echo cr cr\n\n say \"6395 1259 * = \" 6395 1259 * echo cr\n say \"6395 co9 = \" 6395 co9 echo cr\n say \"1259 co9 = \" 1259 co9 echo cr\n say \"5 8 * co9 = \" 5 8 * co9 echo cr\n say \"8051305 co9 = \" 7654 co9 echo cr cr\n\n say \"Part 2: Kaprekar numbers.\" cr cr\n\n say \"Kaprekar numbers less than one hundred: \"\n []\n 100 times\n [ i^ kaprekar if\n [ i^ join ] ]\n dup echo cr\n say '0...99 with property \"n co9 n 2 ** co9 =\": '\n []\n 100 times\n [ i^ co9\n i^ 2 ** co9 = if\n [ i^ join ] ]\n dup echo cr\n say \"Is the former a subset of the latter? \"\n subset iff [ say \"Yes.\" ] else [ say \"No.\" ] cr cr\n\n say \"Part 3: Same as Part 2, but base 17.\" cr cr\n\n say \"Kaprekar (base 17) numbers less than one hundred: \"\n 17 base put\n []\n 100 times\n [ i^ kaprekar if\n [ i^ join ] ]\n base release\n dup echo cr\n say '0...99 with property \"n 16 mod n 2 ** 16 mod =\": '\n []\n 100 times\n [ i^ 16 mod\n i^ 2 ** 16 mod = if\n [ i^ join ] ]\n dup echo cr\n say \"Is the former a subset of the latter? \"\n subset iff [ say \"Yes.\" ] else [ say \"No.\" ]\n", "language": "Quackery" }, { "code": "co9 <- function(base) {\n x <- 1:(base^2-1)\n x[(x %% (base-1)) == (x^2 %% (base-1))]\n}\nMap(co9,c(10,16,17))\n", "language": "R" }, { "code": "#lang racket\n(require math)\n\n(define (digits n)\n (map (compose1 string->number string)\n (string->list (number->string n))))\n\n(define (cast-out-nines n)\n (with-modulus 9\n (for/fold ([sum 0]) ([d (digits n)])\n (mod+ sum d))))\n", "language": "Racket" }, { "code": "sub cast-out(\\BASE = 10, \\MIN = 1, \\MAX = BASE**2 - 1) {\n my \\B9 = BASE - 1;\n my @ran = ($_ if $_ % B9 == $_**2 % B9 for ^B9);\n my $x = MIN div B9;\n gather loop {\n for @ran -> \\n {\n my \\k = B9 * $x + n;\n take k if k >= MIN;\n }\n $x++;\n } ...^ * > MAX;\n}\n\nsay cast-out;\nsay cast-out 16;\nsay cast-out 17;\n", "language": "Raku" }, { "code": "/*REXX program demonstrates the casting─out─nines algorithm (with Kaprekar numbers). */\nparse arg LO HI base . /*obtain optional arguments from the CL*/\nif LO=='' | LO==\",\" then do; LO=1; HI=1000; end /*Not specified? Then use the default*/\nif HI=='' | HI==\",\" then HI= LO /* \" \" \" \" \" \" */\nif base=='' | base==\",\" then base= 10 /* \" \" \" \" \" \" */\nnumeric digits max(9, 2*length(HI**2) ) /*insure enough decimal digits for HI².*/\nnumbers= castOut(LO, HI, base) /*generate a list of (cast out) numbers*/\n@cast_out= 'cast-out-' || (base-1) \"test\" /*construct a shortcut text for output.*/\nsay 'For' LO \"through\" HI', the following passed the' @cast_out\":\"\nsay numbers; say /*display the list of cast out numbers.*/\nq= HI - LO + 1 /*Q: is the range of numbers in list.*/\np= words(numbers) /*P\" \" \" number \" \" \" \" */\npc= format(p/q * 100, , 2) / 1 || '%' /*calculate the percentage (%) cast out*/\nsay 'For' q \"numbers,\" p 'passed the' @cast_out \"(\"pc') for base' base\".\"\nif base\\==10 then exit /*if radix isn't ten, then exit program*/\nKaps= Kaprekar(LO, HI) /*generate a list of Kaprekar numbers. */\nsay; say 'The Kaprekar numbers in the same range are:' Kaps\nsay\n do i=1 for words(Kaps); x= word(Kaps, i) /*verify 'em in list.*/\n if wordpos(x, numbers)\\==0 then iterate /*it's OK so far ··· */\n say 'Kaprekar number' x \"isn't in the numbers list.\" /*oops─ay! */\n exit 13 /*go spank the coder.*/\n end /*i*/\n\nsay 'All Kaprekar numbers are in the' @cast_out \"numbers list.\" /*OK*/\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncastOut: procedure; parse arg low,high,radix; rm= word(radix 10, 1) - 1; $=\n do j=low to word(high low, 1) /*test a range of numbers. */\n if j//rm == j*j//rm then $= $ j /*did number pass the test?*/\n end /*j*/ /* [↑] Then add # to list.*/\n return strip($) /*strip and leading blanks from result.*/\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nKaprekar: procedure; parse arg L,H; $=; if L<=1 then $= 1 /*add unity if in range*/\n do j=max(2, L) to H; s= j*j /*a slow way to find Kaprekar numbers. */\n do m=1 for length(s)%2\n if j==left(s, m) + substr(s, m+1) then do; $= $ j; leave; end\n end /*m*/ /* [↑] found a Kaprekar number. */\n end /*j*/\n return strip($) /*return Kaprekar numbers to invoker. */\n", "language": "REXX" }, { "code": "# Project : Casting out nines\n\nco9(1, 10, 99, [1,9,45,55,99])\nco9(1, 10, 1000, [1,9,45,55,99,297,703,999])\n\nfunc co9(start,base,lim,kaprekars)\nc1=0\nc2=0\ns = []\nfor k = start to lim\n c1 = c1 + 1\n if k % (base-1) = (k*k) % (base-1)\n c2 = c2 + 1\n add(s,k)\n ok\nnext\nmsg = \"Valid subset\" + nl\nfor i = 1 to len(kaprekars)\n if not find(s,kaprekars[i])\n msg = \"***Invalid***\" + nl\n exit\n ok\nnext\nshowarray(s)\nsee \"Kaprekar numbers:\" + nl\nshowarray(kaprekars)\nsee msg\nsee \"Trying \" + c2 + \" numbers instead of \" + c1 + \" saves \" + (100-(c2/c1)*100) + \"%\" + nl + nl\n\nfunc showarray(vect)\n see \"{\"\n svect = \"\"\n for n = 1 to len(vect)\n svect = svect + vect[n] + \", \"\n next\n svect = left(svect, len(svect) - 2)\n see svect + \"}\" + nl\n", "language": "Ring" }, { "code": "N = 2\nbase = 10\nc1 = 0\nc2 = 0\n\nfor k in 1 .. (base ** N) - 1\n c1 = c1 + 1\n if k % (base - 1) == (k * k) % (base - 1) then\n c2 = c2 + 1\n print \"%d \" % [k]\n end\nend\n\nputs\nprint \"Trying %d numbers instead of %d numbers saves %f%%\" % [c2, c1, 100.0 - 100.0 * c2 / c1]\n", "language": "Ruby" }, { "code": "base = 10\nc1 = 0\nc2 = 0\nfor k = 1 to (base ^ 2) - 1\n c1 = c1 + 1\n if k mod (base - 1) = (k * k) mod (base - 1) then c2 = c2 + 1: print k; \" \";\nnext k\nprint\nprint \"Trying \"; using(\"##\", c2); \" numbers instead of \"; using(\"###\", c1); \" numbers saves \"; using(\"##.##\", (100 - (100 * c2 / c1))); \"%\"\nend\n", "language": "Run-BASIC" }, { "code": "fn compare_co9_efficiency(base: u64, upto: u64) {\n let naive_candidates: Vec<u64> = (1u64..upto).collect();\n let co9_candidates: Vec<u64> = naive_candidates.iter().cloned()\n .filter(|&x| x % (base - 1) == (x * x) % (base - 1))\n .collect();\n for candidate in &co9_candidates {\n print!(\"{} \", candidate);\n }\n println!();\n println!(\n \"Trying {} numbers instead of {} saves {:.2}%\",\n co9_candidates.len(),\n naive_candidates.len(),\n 100.0 - 100.0 * (co9_candidates.len() as f64 / naive_candidates.len() as f64)\n );\n}\n\nfn main() {\n compare_co9_efficiency(10, 100);\n compare_co9_efficiency(16, 256);\n}\n", "language": "Rust" }, { "code": "object kaprekar{\n // PART 1\n val co_base = ((x:Int,base:Int) => (x%(base-1) == (x*x)%(base-1)))\n //PART 2\n def get_cands(n:Int,base:Int):List[Int] = {\n if(n==1) List[Int]()\n else if (co_base(n,base)) n :: get_cands(n-1,base)\n else get_cands(n-1,base)\n }\n def main(args:Array[String]) : Unit = {\n //PART 3\n val base = 31\n println(\"Candidates for Kaprekar numbers found by casting out method with base %d:\".format(base))\n println(get_cands(1000,base))\n }\n}\n", "language": "Scala" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst func bitset: castOut (in integer: base, in integer: start, in integer: ending) is func\n result\n var bitset: casted is {};\n local\n var bitset: ran is {};\n var integer: x is 0;\n var integer: n is 0;\n var integer: k is 0;\n var boolean: finished is FALSE;\n begin\n for x range 0 to base - 2 do\n if x rem pred(base) = x ** 2 rem pred(base) then\n incl(ran, x);\n end if;\n end for;\n x := start div pred(base);\n repeat\n for n range ran until finished do\n k := pred(base) * x + n;\n if k >= start then\n if k > ending then\n finished := TRUE;\n else\n incl(casted, k);\n end if;\n end if;\n end for;\n incr(x);\n until finished;\n end func;\n\nconst proc: main is func\n begin\n writeln(castOut(16, 1, 255));\n end func;\n", "language": "Seed7" }, { "code": "func cast_out(base = 10, min = 1, max = (base**2 - 1)) {\n\n var b9 = base-1\n var ran = b9.range.grep {|n| n%b9 == (n*n % b9) }\n\n var x = min//b9\n var r = []\n\n loop {\n ran.each {|n|\n var k = (b9*x + n)\n return r if (k > max)\n r << k if (k >= min)\n }\n ++x\n }\n\n return r\n}\n\nsay cast_out().join(' ')\nsay cast_out(16).join(' ')\nsay cast_out(17).join(' ')\n", "language": "Sidef" }, { "code": "proc co9 {x} {\n while {[string length $x] > 1} {\n\tset x [tcl::mathop::+ {*}[split $x \"\"]]\n }\n return $x\n}\n# Extended to the general case\nproc coBase {x {base 10}} {\n while {$x >= $base} {\n\tfor {set digits {}} {$x} {set x [expr {$x / $base}]} {\n\t lappend digits [expr {$x % $base}]\n\t}\n\tset x [tcl::mathop::+ {*}$digits]\n }\n return $x\n}\n\n# Simple helper\nproc percent {part whole} {format \"%.2f%%\" [expr {($whole - $part) * 100.0 / $whole}]}\n\nputs \"In base 10...\"\nset satisfying {}\nfor {set i 1} {$i < 100} {incr i} {\n if {[co9 $i] == [co9 [expr {$i*$i}]]} {\n\tlappend satisfying $i\n }\n}\nputs $satisfying\nputs \"Trying [llength $satisfying] numbers instead of 99 numbers saves [percent [llength $satisfying] 99]\"\n\nputs \"In base 16...\"\nset satisfying {}\nfor {set i 1} {$i < 256} {incr i} {\n if {[coBase $i 16] == [coBase [expr {$i*$i}] 16]} {\n\tlappend satisfying $i\n }\n}\nputs $satisfying\nputs \"Trying [llength $satisfying] numbers instead of 255 numbers saves [percent [llength $satisfying] 255]\"\n", "language": "Tcl" }, { "code": "LET bs = 10\nLET c1 = 0\nLET c2 = 0\nFOR k = 1 TO (bs^2)-1\n LET c1 = c1 + 1\n IF REMAINDER(k,(bs-1)) = REMAINDER((k*k),(bs-1)) THEN\n LET c2 = c2 + 1\n PRINT k;\n END IF\nNEXT k\nPRINT\nPRINT USING \"Trying ## numbers instead of ### numbers saves ##.##%\": c2, c1, 100-(100*c2/c1)\nEND\n", "language": "True-BASIC" }, { "code": "fn main() {\n println(cast_out(16, 1, 255))\n println(\"\")\n println(cast_out(10, 1, 99))\n println(\"\")\n println(cast_out(17, 1, 288))\n}\n\nfn cast_out(base int, start int, end int) []int {\n b := []int{len: base - 1, init: index}\n\tran := b.filter(it % b.len == (it * it) % b.len)\n\tmut x, mut k := start / b.len, 0\n\tmut result := []int{}\n for {\n for n in ran {\n k = b.len * x + n\n if k < start {continue}\n if k > end {return result}\n result << k\n }\n x++\n }\n\treturn result\n}\n", "language": "V-(Vlang)" }, { "code": "Module Module1\n Sub Print(ls As List(Of Integer))\n Dim iter = ls.GetEnumerator\n Console.Write(\"[\")\n If iter.MoveNext Then\n Console.Write(iter.Current)\n End If\n While iter.MoveNext\n Console.Write(\", \")\n Console.Write(iter.Current)\n End While\n Console.WriteLine(\"]\")\n End Sub\n\n Function CastOut(base As Integer, start As Integer, last As Integer) As List(Of Integer)\n Dim ran = Enumerable.Range(0, base - 1).Where(Function(y) y Mod (base - 1) = (y * y) Mod (base - 1)).ToArray()\n Dim x = start \\ (base - 1)\n\n Dim result As New List(Of Integer)\n While True\n For Each n In ran\n Dim k = (base - 1) * x + n\n If k < start Then\n Continue For\n End If\n If k > last Then\n Return result\n End If\n result.Add(k)\n Next\n x += 1\n End While\n Return result\n End Function\n\n Sub Main()\n Print(CastOut(16, 1, 255))\n Print(CastOut(10, 1, 99))\n Print(CastOut(17, 1, 288))\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "var castOut = Fn.new { |base, start, end|\n var b = base - 1\n var ran = (0...b).where { |n| n % b == (n * n) % b }\n var x = (start/b).floor\n var result = []\n while (true) {\n for (n in ran) {\n var k = b*x + n\n if (k >= start) {\n if (k > end) return result\n result.add(k)\n }\n }\n x = x + 1\n }\n}\n\nSystem.print(castOut.call(16, 1, 255))\nSystem.print()\nSystem.print(castOut.call(10, 1, 99))\nSystem.print()\nSystem.print(castOut.call(17, 1, 288))\n", "language": "Wren" }, { "code": "PROGRAM \"Casting out nines\"\nVERSION \"0.0000\"\n\nDECLARE FUNCTION Entry ()\n\nFUNCTION Entry ()\n bs = 10\n c1 = 0\n c2 = 0\n FOR k = 1 TO (bs ** 2) - 1\n INC c1\n IF k MOD (bs - 1) = (k * k) MOD (bs - 1) THEN INC c2: PRINT k;\n NEXT k\n PRINT\n PRINT \"Trying \"; c2; \" numbers instead of \"; c1; \" numbers saves \"; 100 - (100 * c2 / c1); \"%\"\nEND FUNCTION\nEND PROGRAM\n", "language": "XBasic" }, { "code": "include xpllib;\n\ndef N = 2.;\nint Base, C1, C2, K;\n\\int Main\\ [\n Base:= 10; C1:= 0; C2:= 0;\n for K:= 1 to fix(Pow(float(Base), N)) - 1 do [\n C1:= C1+1;\n if rem(K/(Base-1)) = rem((K*K)/(Base-1)) then [\n C2:= C2+1;\n Print(\"%d \", K);\n ]\n ];\n\n Print(\"\\nTrying %d numbers instead of %d numbers saves %1f%%\\n\",\n C2, C1, 100.0 - 100.0*float(C2)/float(C1));\n return 0;\n]\n", "language": "XPL0" }, { "code": "base = 10\nc1 = 0\nc2 = 0\nfor k = 1 to (base ^ 2) - 1\n\tc1 = c1 + 1\n\tif mod(k, (base - 1)) = mod((k * k), (base - 1)) then c2 = c2 + 1: print k, \" \"; : fi\nnext k\nprint \"\\nTrying \", c2 using(\"##\"), \" numbers instead of \", c1 using(\"###\"), \" numbers saves \", (100 - (100 * c2 / c1)) using(\"##.##\"), \"%\"\nend\n", "language": "Yabasic" }, { "code": "fcn castOut(base=10, start=1, end=999999){\n base-=1;\n ran:=(0).filter(base,'wrap(n){ n%base == (n*n)%base });\n result:=Sink(List);\n foreach a,b in ([start/base ..],ran){ // foreach{ foreach {} }\n k := base*a + b;\n if (k < start) continue;\n if (k > end) return(result.close());\n result.write(k);\n }\n // doesn't get here\n}\n", "language": "Zkl" }, { "code": "castOut(16, 1, 255).toString(*).println(\"\\n-----\");\ncastOut(10, 1, 99).toString(*).println(\"\\n-----\");\ncastOut(17, 1, 288).toString(*).println();\n", "language": "Zkl" }, { "code": "10 LET Base=10\n20 LET N=2\n30 LET c1=0\n40 LET c2=0\n50 LET k=1\n60 IF k>=(Base^N)-1 THEN GO TO 150\n70 LET c1=c1+1\n80 IF FN m(k,Base-1)=FN m(k*k,Base-1) THEN LET c2=c2+1: PRINT k;\" \";\n90 LET k=k+1\n100 GO TO 60\n150 PRINT '\"Trying \";c2;\" numbers instead of \";c1;\" numbers saves \";100-(c2/c1)*100;\"%\"\n160 STOP\n170 DEF FN m(a,b)=a-INT (a/b)*b\n", "language": "ZX-Spectrum-Basic" } ]
Casting-out-nines
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Catalan_numbers/Pascal's_triangle\n", "language": "00-META" }, { "code": ";Task:\nPrint out the first &nbsp; '''15''' &nbsp; Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* &nbsp; [https://archive.is/0IrNp Catalan Numbers and the Pascal Triangle]. <!-- Relation Pascal Triangle and the Catalan Numbers Radoslav Jovanovic --> &nbsp; &nbsp; This method enables calculation of Catalan Numbers using only addition and subtraction.\n<!-- '''http://milan.milanovic.org/math/english/fibo/fibo4.html is broken. -->\n* &nbsp; [http://mathworld.wolfram.com/CatalansTriangle.html Catalan's Triangle] for a Number Triangle that generates Catalan Numbers using only addition.\n* &nbsp; Sequence [[oeis:A000108|A000108 on OEIS]] has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n<br><br>\n", "language": "00-TASK" }, { "code": "V n = 15\nV t = [0] * (n + 2)\nt[1] = 1\nL(i) 1 .. n\n L(j) (i .< 1).step(-1)\n t[j] += t[j - 1]\n t[i + 1] = t[i]\n L(j) (i + 1 .< 1).step(-1)\n t[j] += t[j - 1]\n print(t[i + 1] - t[i], end' ‘ ’)\n", "language": "11l" }, { "code": "CATALAN CSECT\n USING CATALAN,R13,R12\nSAVEAREA B STM-SAVEAREA(R15)\n DC 17F'0'\n DC CL8'CATALAN'\nSTM STM R14,R12,12(R13)\n ST R13,4(R15)\n ST R15,8(R13)\n LR R13,R15\n LA R12,4095(R13)\n LA R12,1(R12)\n* ---- CODE\n LA R0,1\n ST R0,T t(1)=1\n LA R4,0 ix:i=1\n LA R6,1 by 1\n LH R7,N to n\nLOOPI BXH R4,R6,ENDLOOPI loop i\n LR R5,R4 ix:j=i+1\n LA R5,2(R5) i+2\n LA R8,0\n BCTR R8,0 by -1\n LA R9,1 to 2\nLOOP1J BXLE R5,R8,ENLOOP1J loop j\n LR R10,R5 j\n BCTR R10,0\n SLA R10,2\n L R2,T(R10) r2=t(j)\n LR R1,R10 j\n SH R1,=H'4'\n L R3,T(R1) r3=t(j-1)\n AR R2,R3 r2=r2+r3\n ST R2,T(R10) t(j)=t(j)+t(j-1)\n B LOOP1J\nENLOOP1J EQU *\n LR R1,R4 i\n BCTR R1,0\n SLA R1,2\n L R3,T(R1) t(i)\n LA R1,4(R1)\n ST R3,T(R1) t(i+1)\n LR R5,R4 ix:j=i+2\n LA R5,3(R5) i+3\n LA R8,0\n BCTR R8,0 by -1\n LA R9,1 to 2\nLOOP2J BXLE R5,R8,ENLOOP2J loop j\n LR R10,R5 j\n BCTR R10,0\n SLA R10,2\n L R2,T(R10) r2=t(j)\n LR R1,R10 j\n SH R1,=H'4'\n L R3,T(R1) r3=t(j-1)\n AR R2,R3 r2=r2+r3\n ST R2,T(R10) t(j)=t(j)+t(j-1)\n B LOOP2J\nENLOOP2J EQU *\n LR R1,R4 i\n BCTR R1,0\n SLA R1,2\n L R2,T(R1) t(i)\n LA R1,4(R1)\n L R3,T(R1) t(i+1)\n SR R3,R2\n CVD R3,P\n UNPK Z,P\n MVC C,Z\n OI C+L'C-1,X'F0'\n MVC WTOBUF(8),C+8\n WTO MF=(E,WTOMSG)\t\t\n B LOOPI\nENDLOOPI EQU *\n* ---- END CODE\n CNOP 0,4\n L R13,4(0,R13)\n LM R14,R12,12(R13)\n XR R15,R15\n BR R14\n* ---- DATA\nN DC H'15'\nT DC 17F'0'\nP DS PL8\nZ DS ZL16\nC DS CL16\nWTOMSG DS 0F\n DC H'80'\n DC H'0'\nWTOBUF DC CL80' '\n YREGS\n END\n", "language": "360-Assembly" }, { "code": "INCLUDE \"D2:REAL.ACT\" ;from the Action! Tool Ki\n\nDEFINE PTR=\"CARD\"\nDEFINE REALSIZE=\"6\"\n\nPTR FUNC GetItemAddr(PTR buf BYTE i)\nRETURN (buf+REALSIZE*i)\n\nPROC Main()\n DEFINE COUNT=\"15\"\n BYTE ARRAY buf(102) ;(COUNT+2)*REALSIZE\n REAL POINTER r1,r2\n REAL c\n BYTE i,j\n\n Put(125) PutE() ;clear the screen\n\n r1=GetItemAddr(buf,1)\n IntToReal(1,r1)\n\n FOR i=1 TO COUNT\n DO\n j=i+1\n WHILE j>=2\n DO\n r1=GetItemAddr(buf,j)\n r2=GetItemAddr(buf,j-1)\n RealAdd(r1,r2,r1) ;t(j)==+t(j-1)\n j==-1\n OD\n r1=GetItemAddr(buf,i)\n r2=GetItemAddr(buf,i+1)\n RealAssign(r1,r2) ;t(i+1)=t(i)\n\n j=i+2\n WHILE j>=2\n DO\n r1=GetItemAddr(buf,j)\n r2=GetItemAddr(buf,j-1)\n RealAdd(r1,r2,r1) ;t(j)==+t(j-1)\n j==-1\n OD\n r1=GetItemAddr(buf,i)\n r2=GetItemAddr(buf,i+1)\n RealSub(r2,r1,c) ;c=t(i+1)-t(i)\n PrintF(\"C(%B)=\",i) PrintRE(c)\n OD\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO, Pascal;\n\nprocedure Catalan is\n\n Last: Positive := 15;\n Row: Pascal.Row := Pascal.First_Row(2*Last+1);\n\nbegin\n for I in 1 .. Last loop\n Row := Pascal.Next_Row(Row);\n Row := Pascal.Next_Row(Row);\n Ada.Text_IO.Put(Integer'Image(Row(I+1)-Row(I+2)));\n end loop;\nend Catalan;\n", "language": "Ada" }, { "code": "INT n = 15;\n[ 0 : n + 1 ]INT t;\nt[0] := 0;\nt[1] := 1;\nFOR i TO n DO\n FOR j FROM i BY -1 TO 2 DO t[j] := t[j] + t[j-1] OD;\n t[i+1] := t[i];\n FOR j FROM i+1 BY -1 TO 2 DO t[j] := t[j] + t[j-1] OD;\n print( ( whole( t[i+1] - t[i], 0 ), \" \" ) )\nOD\n", "language": "ALGOL-68" }, { "code": "begin\n % print the first 15 Catalan numbers from Pascal's triangle %\n integer n;\n n := 15;\n begin\n integer array pascalLine ( 1 :: n + 1 );\n % the Catalan numbers are the differences between the middle and middle - 1 numbers of the odd %\n % lines of Pascal's triangle (lines with 3 or more numbers) %\n % note - we only need to calculate the left side of the triangle %\n pascalLine( 1 ) := 1;\n for c := 2 until n + 1 do begin\n % even line %\n for i := c - 1 step -1 until 2 do pascalLine( i ) := pascalLine( i - 1 ) + pascalLine( i );\n pascalLine( c ) := pascalLine( c - 1 );\n % odd line %\n for i := c step -1 until 2 do pascalLine( i ) := pascalLine( i - 1 ) + pascalLine( i );\n writeon( i_w := 1, s_w := 0, \" \", pascalLine( c ) - pascalLine( c - 1 ) )\n end for_c\n end\nend.\n", "language": "ALGOL-W" }, { "code": " ⍝ Based heavily on the J solution\n CATALAN←{¯1↓↑-/1 ¯1↓¨(⊂⎕IO+0 0)⍉¨0 2⌽¨⊂(⎕IO-⍨⍳N){+\\⍣⍺⊢⍵}⍤0 1⊢1⍴⍨N←⍵+2}\n", "language": "APL" }, { "code": "10 HOME\n20 n = 15\n30 DIM t(n+2)\n50 t(1) = 1\n55 PRINT \"The first 15 Catalan numbers are: \"; CHR$(10)\n60 FOR i = 1 TO n\n70 FOR j = i TO 1 STEP -1 : t(j) = t(j) + t(j-1) : NEXT j\n80 t(i+1) = t(i)\n90 FOR j = i+1 TO 1 STEP -1 : t(j) = t(j) + t(j-1) : NEXT j\n100 PRINT i; \": \"; t(i+1) - t(i)\n120 NEXT i\n130 END\n", "language": "Applesoft-BASIC" }, { "code": "n: 15\nt: new array.of:n+2 0\n\nt\\[1]: 1\n\nloop 1..n 'i [\n loop i..1 'j -> t\\[j]: t\\[j] + t\\[j-1]\n t\\[i+1]: t\\[i]\n loop (i+1)..1 'j -> t\\[j]: t\\[j] + t\\[j-1]\n prints t\\[i+1] - t\\[i]\n prints \" \"\n]\nprint \"\"\n", "language": "Arturo" }, { "code": "/* Generate Catalan Numbers\n//\n// smgs: 20th Feb, 2014\n*/\nArray := [], Array[2,1] := Array[2,2] := 1 ; Array inititated and 2nd row of pascal's triangle assigned\nINI := 3 ; starts with calculating the 3rd row and as such the value\nLoop, 31 ; every odd row is taken for calculating catalan number as such to obtain 15 we need 2n+1\n{\n\tif ( A_index > 2 )\n\t{\n\t\tLoop, % A_INDEX\n\t\t{\n\t\t\told := ini-1, \t\tindex := A_index, \t\tindex_1 := A_index + 1\n\t\t\tArray[ini, index_1] := Array[old, index] + Array[old, index_1]\n\t\t\tArray[ini, 1] := Array[ini, ini] := 1\n\t\t\tline .= Array[ini, A_index] \" \"\n\t\t}\n\t;~ MsgBox % line ; gives rows of pascal's triangle\n\t; calculating every odd row starting from 1st so as to obtain catalan's numbers\n\t\tif ( mod(ini,2) != 0)\n\t\t{\n\t\t\tStringSplit, res, line, %A_Space%\n\t\t\tans := res0//2, ans_1 := ans++\n\t\t\tresult := result . res%ans_1% - res%ans% \" \"\n\t\t}\n\tline :=\n\tini++\n\t}\n}\nMsgBox % result\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f CATALAN_NUMBERS_PASCALS_TRIANGLE.AWK\n# converted from C\nBEGIN {\n printf(\"1\")\n for (n=2; n<=15; n++) {\n num = den = 1\n for (k=2; k<=n; k++) {\n num *= (n + k)\n den *= k\n catalan = num / den\n }\n printf(\" %d\",catalan)\n }\n printf(\"\\n\")\n exit(0)\n}\n", "language": "AWK" }, { "code": "@echo off\nsetlocal ENABLEDELAYEDEXPANSION\nset n=15\nset /A nn=n+1\nfor /L %%i in (0,1,%nn%) do set t.%%i=0\nset t.1=1\nfor /L %%i in (1,1,%n%) do (\n set /A ip=%%i+1\n for /L %%j in (%%i,-1,1) do (\n set /A jm=%%j-1\n\t set /A t.%%j=t.%%j+t.!jm!\n\t)\n set /A t.!ip!=t.%%i\t\n for /L %%j in (!ip!,-1,1) do (\n set /A jm=%%j-1\n\t set /A t.%%j=t.%%j+t.!jm!\n\t)\n set /A ci=t.!ip!-t.%%i\n\techo !ci!\n )\n)\npause\n", "language": "Batch-File" }, { "code": "//This code implements the print of 15 first Catalan's Numbers\n//Formula used:\n// __n__\n// | | (n + k) / k n>0\n// k=2\n\n#include <stdio.h>\n#include <stdlib.h>\n\n//the number of Catalan's Numbers to be printed\nconst int N = 15;\n\nint main()\n{\n //loop variables (in registers)\n register int k, n;\n\n //necessarily ull for reach big values\n unsigned long long int num, den;\n\n //the nmmber\n int catalan;\n\n //the first is not calculated for the formula\n printf(\"1 \");\n\n //iterating from 2 to 15\n for (n=2; n<=N; ++n) {\n //initializaing for products\n num = den = 1;\n //applying the formula\n for (k=2; k<=n; ++k) {\n num *= (n+k);\n den *= k;\n catalan = num /den;\n }\n\n //output\n printf(\"%d \", catalan);\n }\n\n //the end\n printf(\"\\n\");\n return 0;\n}\n", "language": "C" }, { "code": "// Generate Catalan Numbers\n//\n// Nigel Galloway: June 9th., 2012\n//\n#include <iostream>\nint main() {\n const int N = 15;\n int t[N+2] = {0,1};\n for(int i = 1; i<=N; i++){\n for(int j = i; j>1; j--) t[j] = t[j] + t[j-1];\n t[i+1] = t[i];\n for(int j = i+1; j>1; j--) t[j] = t[j] + t[j-1];\n std::cout << t[i+1] - t[i] << \" \";\n }\n return 0;\n}\n", "language": "C++" }, { "code": "int n = 15;\nList<int> t = new List<int>() { 0, 1 };\nfor (int i = 1; i <= n; i++)\n{\n for (var j = i; j > 1; j--) t[j] += t[j - 1];\n t.Add(t[i]);\n for (var j = i + 1; j > 1; j--) t[j] += t[j - 1];\n Console.Write(((i == 1) ? \"\" : \", \") + (t[i + 1] - t[i]));\n}\n", "language": "C-sharp" }, { "code": "100 cls\n110 n = 15\n120 dim t(n+2)\n130 t(1) = 1\n140 print \"The first 15 Catalan numbers are: \";chr$(10)\n150 for i = 1 to n\n160 for j = i to 1 step -1 : t(j) = t(j)+t(j-1) : next j\n170 t(i+1) = t(i)\n180 for j = i+1 to 1 step -1 : t(j) = t(j)+t(j-1) : next j\n190 print using \"###\";i;\": \";\n200 print using \"#########\";t(i+1)-t(i)\n210 next i\n220 end\n", "language": "Chipmunk-Basic" }, { "code": "(defun catalan (n)\n \"Return the n-th Catalan number\"\n (if (<= n 1) 1\n (let ((result 2))\n (dotimes (k (- n 2) result)\n (setq result (* result (/ (+ n k 2) (+ k 2)))) ))))\n\n\n(dotimes (n 15)\n (print (catalan (1+ n))) )\n", "language": "Common-Lisp" }, { "code": "void main() {\n import std.stdio;\n\n enum uint N = 15;\n uint[N + 2] t;\n t[1] = 1;\n\n foreach (immutable i; 1 .. N + 1) {\n foreach_reverse (immutable j; 2 .. i + 1)\n t[j] += t[j - 1];\n t[i + 1] = t[i];\n foreach_reverse (immutable j; 2 .. i + 2)\n t[j] += t[j - 1];\n write(t[i + 1] - t[i], ' ');\n }\n}\n", "language": "D" }, { "code": "print 1\nfor n = 2 to 15\n num = 1\n den = 1\n for k = 2 to n\n num *= n + k\n den *= k\n cat = num / den\n .\n print cat\n.\n", "language": "EasyLang" }, { "code": "(define dim 100)\n(define-syntax-rule (Tidx i j) (+ i (* dim j)))\n\n;; generates Catalan's triangle\n;; T (i , j) = T(i-1,j) + T (i, j-1)\n\n(define (T n)\n\t(define i (modulo n dim))\n\t(define j (quotient n dim))\n\t(cond\n\t\t((zero? i) 1) ;; left column = 1\n\t\t((= i j) (T (Tidx (1- i) j))) ;; diagonal value = left value\n\t\t(else (+ (T (Tidx (1- i) j)) (T (Tidx i (1- j)))))))\n\t\n(remember 'T #(1))\n", "language": "EchoLisp" }, { "code": ";; take elements on diagonal = Catalan numbers\n(for ((i (in-range 0 16))) (write (T (Tidx i i))))\n\n → 1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845\n", "language": "EchoLisp" }, { "code": " [Catalan numbers from Pascal triangle, Rosetta Code website.\n EDSAC program, Initial Orders 2]\n ..PZ [blank tape and terminator]\n T54K [refer to working array with 'C']\n P300F [address of working array]\n T46K [to call print subroutine with 'G N']\n P56F [address of print subroutine]\n\n [Modification of library subroutine P7.\n Prints non-negative integer, up to 10 digits, right-justified.\n 55 locations, load at even address.]\n E25KTN\n GKA3FT42@A47@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@\n TFH17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@\n T31@A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFO46@SFL8FT4DE39@\n\n [Main program]\n PK T200K GK\n [Constants]\n [0] PD [short constant 1]\n [1] P2F [to inc address by 2]\n [2] T#C [used in manufacturing EDSAC orders]\n [3] MF [add to T order to make A order with same address]\n [4] #F [set figures]\n [5] &F [line feed]\n [6] @F [carriage return]\n [7] P7D [maximum n = 15]\n [Variable]\n [8] PF [n]\n [Enter with acc = 0]\n [9] O4@ [set teleprinter to figures]\n T4#C T2#C T#C A@ TC [initialize first 3 terms to 1, 0, 0]\n T8@ E58@ [set n := 0; jump to inc n and print C_n]\n [Outer loop; here with n updated]\n [17] TF A8@ [acc := latest n]\n L1F A2@ T22@ [make and store order 'T 2n #C']\n [22] T#C [sets term := 0; also used to test for end of loop]\n A2@ [load 'T#C', initial value of order 31]\n [Loop to convert e.g. (20, 15, 6, 1) to (35, 21, 7, 1); works left to right]\n [24] U31@ A3@ U29@ A1@ T30@ [set up orders on next line]\n [29] A#C A#C T#C [replaced by manufactured orders]\n A31@ A1@ S22@ E38@ [inc address in order 31, jump out if done]\n A22@ E24@ [not done, loop back]\n [38] A22@ T48@ [initialize order 48]\n [Loop to convert e.g. (35, 21, 7, 1) to (70, 56, 28, 8, 1); works right to left]\n [40] TF A48@ A3@ U46@ S1@ T47@ [set up orders on next line]\n [46] A#C A#C T#C [replaced by manufactured orders]\n A48@ S1@ T48@ [dec address in order 48]\n A2@ S48@ G40@ [test for done, loop back if not]\n A#C LD T#C [double first term, e.g. 35 -> 70 (not done in loop)]\n [Increment n and print Catalan number C_n]\n [58] TD [clear 0D, ensures sandwich bit = 0]\n A8@ A@ U8@ TF [inc n; set 0D := n by setting 0F := n]\n A63@ GN [print n]\n A#C S4#C TD A68@ GN [print Catalan number C_n, e.g. C_5 = 70 - 28 = 42]\n O6@ O5@ [print CR, LF]\n A8@ S7@ G17@ [test for maximum n, loop back if not]\n [75] O4@ ZF [flush printer buffer; stop]\n E9Z PF [define entry point; enter with acc = 0]\n", "language": "EDSAC-order-code" }, { "code": "defmodule Catalan do\n def numbers(num) do\n {result,_} = Enum.reduce(1..num, {[],{0,1}}, fn i,{list,t0} ->\n t1 = numbers(i, t0)\n t2 = numbers(i+1, Tuple.insert_at(t1, i+1, elem(t1, i)))\n {[elem(t2, i+1) - elem(t2, i) | list], t2}\n end)\n Enum.reverse(result)\n end\n\n defp numbers(0, t), do: t\n defp numbers(n, t), do: numbers(n-1, put_elem(t, n, elem(t, n-1) + elem(t, n)))\nend\n\nIO.inspect Catalan.numbers(15)\n", "language": "Elixir" }, { "code": "-module(catalin).\n-compile(export_all).\nmul(N,D,S,S)->\n\tN2=N*(S+S),\n\tD2=D*S,\n\tK = N2 div D2 ;\nmul(N,D,S,L)->\n\tN2=N*(S+L),\n\tD2=D*L,\n\tK = mul(N2,D2,S,L+1).\n\t\ncatl(Ans,16) -> Ans;\ncatl(D,S)->\n\tC=mul(1,1,S,2),\n\tcatl([D|C],S+1).\nmain()->\n\tAns=catl(1,2).\n", "language": "Erlang" }, { "code": "PROGRAM CATALAN\n\n!$DOUBLE\n\nDIM CATALAN[50]\n\nFUNCTION ODD(X)\n ODD=FRC(X/2)<>0\nEND FUNCTION\n\nPROCEDURE GETCATALAN(L)\n LOCAL J,K,W\n LOCAL DIM PASTRI[100]\n\n L=L*2\n PASTRI[0]=1\n J=0\n WHILE J<L DO\n J+=1\n K=INT((J+1)/2)\n PASTRI[K]=PASTRI[K-1]\n FOR W=K TO 1 STEP -1 DO\n PASTRI[W]+=PASTRI[W-1]\n END FOR\n IF NOT(ODD(J)) THEN\n K=INT(J/2)\n CATALAN[K]=PASTRI[K]-PASTRI[K-1]\n END IF\n END WHILE\nEND PROCEDURE\n\nBEGIN\n LL=15\n GETCATALAN(LL)\n FOR I=1 TO LL DO\n WRITE(\"### ####################\";I;CATALAN[I])\n END FOR\nEND PROGRAM\n", "language": "ERRE" }, { "code": "let mutable nm=uint64(1)\nlet mutable dm=uint64(1)\nlet mutable a=uint64(1)\n\nprintf \"1, \"\nfor i = 2 to 15 do\n nm<-uint64(1)\n dm<-uint64(1)\n for k = 2 to i do\n nm <-uint64( uint64(nm) * (uint64(i)+uint64(k)))\n dm <-uint64( uint64(dm) * uint64(k))\n let a = uint64(uint64(nm)/uint64(dm))\n printf \"%u\"a\n if(i<>15) then\n printf \", \"\n", "language": "F-Sharp" }, { "code": "USING: arrays grouping io kernel math prettyprint sequences ;\nIN: rosetta-code.catalan-pascal\n\n: next-row ( seq -- seq' )\n 2 clump [ sum ] map 1 prefix 1 suffix ;\n\n: pascal ( n -- seq )\n 1 - { { 1 } } swap [ dup last next-row suffix ] times ;\n\n15 2 * pascal [ length odd? ] filter [\n dup length 1 = [ 1 ]\n [ dup midpoint@ dup 1 + 2array swap nths first2 - ] if\n pprint bl\n] each drop\n", "language": "Factor" }, { "code": "' version 15-09-2015\n' compile with: fbc -s console\n\n#Define size 31 ' (N * 2 + 1)\n\nSub pascal_triangle(rows As Integer, Pas_tri() As ULongInt)\n\n Dim As Integer x, y\n\n For x = 1 To rows\n Pas_tri(1,x) = 1\n Pas_tri(x,1) = 1\n Next\n\n For x = 2 To rows\n For y = 2 To rows + 1 - x\n Pas_tri(x, y) = pas_tri(x - 1 , y) + pas_tri(x, y - 1)\n Next\n Next\n\nEnd Sub\n\n' ------=< MAIN >=------\n\nDim As Integer count, row\nDim As ULongInt triangle(1 To size, 1 To size)\n\npascal_triangle(size, triangle())\n\n' 1 1 1 1 1 1\n' 1 2 3 4 5 6\n' 1 3 6 10 15 21\n' 1 4 10 20 35 56\n' 1 5 15 35 70 126\n' 1 6 21 56 126 252\n' The Pascal triangle is rotated 45 deg.\n' to find the Catalan number we need to follow the diagonal\n' for top left to bottom right\n' take the number on diagonal and subtract the number in de cell\n' one up and one to right\n' 1 (2 - 1), 2 (6 - 4), 5 (20 - 15) ...\n\n\nPrint \"The first 15 Catalan numbers are\" : print\ncount = 1 : row = 2\nDo\n Print Using \"###: #########\"; count; triangle(row, row) - triangle(row +1, row -1)\n row = row + 1\n count = count + 1\nLoop Until count > 15\n\n' empty keyboard buffer\nWhile InKey <> \"\" : Wend\nPrint : Print \"hit any key to end program\"\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc main() {\n const n = 15\n t := [n + 2]uint64{0, 1}\n for i := 1; i <= n; i++ {\n for j := i; j > 1; j-- {\n t[j] += t[j-1]\n }\n t[i+1] = t[i]\n for j := i + 1; j > 1; j-- {\n t[j] += t[j-1]\n }\n fmt.Printf(\"%2d : %d\\n\", i, t[i+1]-t[i])\n }\n}\n", "language": "Go" }, { "code": "class Catalan\n{\n public static void main(String[] args)\n {\n BigInteger N = 15;\n BigInteger k,n,num,den;\n BigInteger catalan;\n print(1);\n for(n=2;n<=N;n++)\n {\n num = 1;\n den = 1;\n for(k=2;k<=n;k++)\n {\n num = num*(n+k);\n den = den*k;\n catalan = num/den;\n }\n print(\" \" + catalan);\n }\n\n }\n}\n​\n", "language": "Groovy" }, { "code": "import System.Environment (getArgs)\n\n-- Pascal's triangle.\npascal :: [[Integer]]\npascal = [1] : map (\\row -> 1 : zipWith (+) row (tail row) ++ [1]) pascal\n\n-- The Catalan numbers from Pascal's triangle. This uses a method from\n-- http://www.cut-the-knot.org/arithmetic/algebra/CatalanInPascal.shtml\n-- (see \"Grimaldi\").\ncatalan :: [Integer]\ncatalan = map (diff . uncurry drop) $ zip [0..] (alt pascal)\n where alt (x:_:zs) = x : alt zs -- every other element of an infinite list\n diff (x:y:_) = x - y\n diff (x:_) = x\n\nmain :: IO ()\nmain = do\n ns <- fmap (map read) getArgs :: IO [Int]\n mapM_ (print . flip take catalan) ns\n", "language": "Haskell" }, { "code": "link math\n\nprocedure main(A)\n limit := (integer(A[1])|15)+1\n every write(right(binocoef(i := 2*seq(0)\\limit,i/2)-binocoef(i,i/2+1),30))\nend\n", "language": "Icon" }, { "code": " Catalan=. }:@:(}.@:((<0 1)&|:) - }:@:((<0 1)&|:@:(2&|.)))@:(i. +/\\@]^:[ #&1)@:(2&+)\n", "language": "J" }, { "code": " Catalan 15\n1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845\n", "language": "J" }, { "code": " o=. @: NB. Composition of verbs (functions)\n ( PascalTriangle=. i. ((+/\\@]^:[)) #&1 ) 5\n1 1 1 1 1\n1 2 3 4 5\n1 3 6 10 15\n1 4 10 20 35\n1 5 15 35 70\n ( MiddleDiagonal=. (<0 1)&|: ) o PascalTriangle 5\n1 2 6 20 70\n ( AdjacentLeft=. MiddleDiagonal o (2&|.) ) o PascalTriangle 5\n1 4 15 1 5\n\n ( Catalan=. }: o (}. o MiddleDiagonal - }: o AdjacentLeft) o PascalTriangle o (2&+) f. ) 5\n1 2 5 14 42\n\n Catalan\n}:@:(}.@:((<0 1)&|:) - }:@:((<0 1)&|:@:(2&|.)))@:(i. +/\\@]^:[ #&1)@:(2&+)\n", "language": "J" }, { "code": "public class Test {\n public static void main(String[] args) {\n int N = 15;\n int[] t = new int[N + 2];\n t[1] = 1;\n\n for (int i = 1; i <= N; i++) {\n\n for (int j = i; j > 1; j--)\n t[j] = t[j] + t[j - 1];\n\n t[i + 1] = t[i];\n\n for (int j = i + 1; j > 1; j--)\n t[j] = t[j] + t[j - 1];\n\n System.out.printf(\"%d \", t[i + 1] - t[i]);\n }\n }\n}\n", "language": "Java" }, { "code": "var n = 15;\nfor (var t = [0, 1], i = 1; i <= n; i++) {\n for (var j = i; j > 1; j--) t[j] += t[j - 1];\n t[i + 1] = t[i];\n for (var j = i + 1; j > 1; j--) t[j] += t[j - 1];\n document.write(i == 1 ? '' : ', ', t[i + 1] - t[i]);\n}\n", "language": "JavaScript" }, { "code": "(() => {\n 'use strict';\n\n // CATALAN\n\n // catalanSeries :: Int -> [Int]\n let catalanSeries = n => {\n let alternate = xs => xs.reduce(\n (a, x, i) => i % 2 === 0 ? a.concat([x]) : a, []\n ),\n diff = xs => xs.length > 1 ? xs[0] - xs[1] : xs[0];\n\n return alternate(pascal(n * 2))\n .map((xs, i) => diff(drop(i, xs)));\n }\n\n // PASCAL\n\n // pascal :: Int -> [[Int]]\n let pascal = n => until(\n m => m.level <= 1,\n m => {\n let nxt = zipWith(\n (a, b) => a + b, [0].concat(m.row), m.row.concat(0)\n );\n return {\n row: nxt,\n triangle: m.triangle.concat([nxt]),\n level: m.level - 1\n }\n }, {\n level: n,\n row: [1],\n triangle: [\n [1]\n ]\n }\n )\n .triangle;\n\n\n // GENERIC FUNCTIONS\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n let zipWith = (f, xs, ys) =>\n xs.length === ys.length ? (\n xs.map((x, i) => f(x, ys[i]))\n ) : undefined;\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n let until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n }\n\n // drop :: Int -> [a] -> [a]\n let drop = (n, xs) => xs.slice(n);\n\n // tail :: [a] -> [a]\n let tail = xs => xs.length ? xs.slice(1) : undefined;\n\n return tail(catalanSeries(16));\n})();\n", "language": "JavaScript" }, { "code": "[1,2,5,14,42,132,429,1430,4862,16796,58786,208012,742900,2674440,9694845]\n", "language": "JavaScript" }, { "code": "def binomial(n; k):\n if k > n / 2 then binomial(n; n-k)\n else reduce range(1; k+1) as $i (1; . * (n - $i + 1) / $i)\n end;\n\n# Direct (naive) computation using two numbers in Pascal's triangle:\ndef catalan_by_pascal: . as $n | binomial(2*$n; $n) - binomial(2*$n; $n-1);\n", "language": "Jq" }, { "code": "$ jq -n -c -f Catalan_numbers_Pascal.jq\n[0,0]\n[1,1]\n[2,2]\n[3,5]\n[4,14]\n[5,42]\n[6,132]\n[7,429]\n[8,1430]\n[9,4862]\n[10,16796]\n[11,58786]\n[12,208012]\n[13,742900]\n[14,2674440]\n[15,9694845]\n[30,3814986502092304]\n[31,14544636039226880]\n[510,5.491717746183512e+302]\n[511,null]\n", "language": "Jq" }, { "code": "# v0.6\n\nfunction pascal(n::Int)\n r = ones(Int, n, n)\n for i in 2:n, j in 2:n\n r[i, j] = r[i-1, j] + r[i, j-1]\n end\n return r\nend\n\nfunction catalan_num(n::Int)\n p = pascal(n + 2)\n p[n+4:n+3:end-1] - diag(p, 2)\nend\n\n@show catalan_num(15)\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nimport java.math.BigInteger\n\nval ONE = BigInteger.ONE\n\nfun pascal(n: Int, k: Int): BigInteger {\n if (n == 0 || k == 0) return ONE\n val num = (k + 1..n).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }\n val den = (2..n - k).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }\n return num / den\n}\n\nfun catalanFromPascal(n: Int) {\n for (i in 1 until n step 2) {\n val mi = i / 2 + 1\n val catalan = pascal(i, mi) - pascal(i, mi - 2)\n println(\"${\"%2d\".format(mi)} : $catalan\")\n }\n}\n\nfun main(args: Array<String>) {\n val n = 15\n catalanFromPascal(n * 2)\n}\n", "language": "Kotlin" }, { "code": "function nextrow (t)\n local ret = {}\n t[0], t[#t + 1] = 0, 0\n for i = 1, #t do ret[i] = t[i - 1] + t[i] end\n return ret\nend\n\nfunction catalans (n)\n local t, middle = {1}\n for i = 1, n do\n middle = math.ceil(#t / 2)\n io.write(t[middle] - (t[middle + 1] or 0) .. \" \")\n t = nextrow(nextrow(t))\n end\nend\n\ncatalans(15)\n", "language": "Lua" }, { "code": "Module CatalanNumbers {\n Def Integer count, t_row, size=31\n Dim triangle(1 to size, 1 to size)\n\n \\\\ call sub\n pascal_triangle(size, &triangle())\n\n\n Print \"The first 15 Catalan numbers are\"\n count = 1% : t_row = 2%\n\n Do {\n Print Format$(\"{0:0:-3}:{1:0:-15}\", count, triangle(t_row, t_row) - triangle(t_row +1, t_row -1))\n t_row++\n count++\n } Until count > 15\n End\n\n Sub pascal_triangle(rows As Integer, &Pas_tri())\n Local x=0%, y=0%\n For x = 1 To rows\n Pas_tri( 1%, x ) = 1@\n Pas_tri( x, 1% ) = 1@\n Next x\n if rows<2 then exit sub\n For x = 2 To rows-1\n For y = 2 To rows + 1 - x\n Pas_tri(x, y) = pas_tri(x - 1 , y) + pas_tri(x, y - 1)\n Next y\n Next x\n End Sub\n}\nCatalanNumbers\n", "language": "M2000-Interpreter" }, { "code": "catalan:=proc(n)\n local i,a:=[1],C:=[1];\n for i to n do\n a:=[0,op(a)]+[op(a),0];\n a:=[0,op(a)]+[op(a),0];\n C:=[op(C),a[i+1]-a[i]];\n od;\n C\nend:\n\ncatalan(10);\n# [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796]\n", "language": "Maple" }, { "code": "nextrow[lastrow_] := Module[{output},\n output = ConstantArray[1, Length[lastrow] + 1];\n Do[\n output[[i + 1]] = lastrow[[i]] + lastrow[[i + 1]];\n , {i, 1, Length[lastrow] - 1}];\n output\n ]\npascaltriangle[size_] := NestList[nextrow, {1}, size]\ncatalannumbers[length_] := Module[{output, basetriangle},\n basetriangle = pascaltriangle[2 length];\n list1 = basetriangle[[# *2 + 1, # + 1]] & /@ Range[length];\n list2 = basetriangle[[# *2 + 1, # + 2]] & /@ Range[length];\n list1 - list2\n ]\n(* testing *)\ncatalannumbers[15]\n", "language": "Mathematica" }, { "code": "n = 15;\np = pascal(n + 2);\np(n + 4 : n + 3 : end - 1)' - diag(p, 2)\n", "language": "MATLAB" }, { "code": "/* The Catalan triangle can be generated using genmatrix */\ngenmatrix(lambda([n,k],if n>=k then binomial(n+k-1,k-1)-2*binomial(n+k-2,k-2) else 0),15,15)$\n\n/* The Catalan numbers are in the main diagonal */\nmakelist(%[i,i],i,1,15);\n", "language": "Maxima" }, { "code": "100 CLS\n110 N = 15\n120 DIM T(N+2)\n130 T(1) = 1\n140 PRINT \"The first 15 Catalan numbers are: \"; CHR$(10)\n150 FOR I = 1 TO N\n160 FOR J = I TO 1 STEP -1 : T(J) = T(J) + T(J-1) : NEXT J\n170 T(I+1) = T(I)\n180 FOR J = I+1 TO 1 STEP -1 : T(J) = T(J) + T(J-1) : NEXT J\n190 PRINT USING \"###: #########\";I; T(I+1) - T(I)\n200 NEXT I\n210 END\n", "language": "MSX-Basic" }, { "code": "const n = 15\nvar t = newSeq[int](n + 2)\n\nt[1] = 1\nfor i in 1..n:\n for j in countdown(i, 1): t[j] += t[j-1]\n t[i+1] = t[i]\n for j in countdown(i+1, 1): t[j] += t[j-1]\n stdout.write t[i+1] - t[i], \" \"\nstdout.write '\\n'\n", "language": "Nim" }, { "code": "let catalan : int ref = ref 0 in\nPrintf.printf \"%d ,\" 1 ;\nfor i = 2 to 9 do\nlet nm : int ref = ref 1 in\nlet den : int ref = ref 1 in\nfor k = 2 to i do\nnm := (!nm)*(i+k);\nden := (!den)*k;\ncatalan := (!nm)/(!den) ;\ndone;\nprint_int (!catalan); print_string \",\" ;\ndone;;\n", "language": "OCaml" }, { "code": "import: mapping\n\n: pascal( n -- [] )\n [ 1 ] n #[ dup [ 0 ] + [ 0 ] rot + zipWith( #+ ) ] times ;\n\n: catalan( n -- m )\n n 2 * pascal at( n 1+ ) n 1+ / ;\n", "language": "Oforth" }, { "code": "vector(15,n,binomial(2*n,n)-binomial(2*n,n+1))\n", "language": "PARI-GP" }, { "code": "Program CatalanNumbers\ntype\n tElement = Uint64;\nvar\n Catalan : array[0..50] of tElement;\nprocedure GetCatalan(L:longint);\nvar\n PasTri : array[0..100] of tElement;\n j,k: longInt;\nbegin\n l := l*2;\n PasTri[0] := 1;\n j := 0;\n while (j<L) do\n begin\n inc(j);\n k := (j+1) div 2;\n PasTri[k] :=PasTri[k-1];\n For k := k downto 1 do\n inc(PasTri[k],PasTri[k-1]);\n IF NOT(Odd(j)) then\n begin\n k := j div 2;\n Catalan[k] :=PasTri[k]-PasTri[k-1];\n end;\n end;\nend;\n\nvar\n i,l: longint;\nBegin\n l := 15;\n GetCatalan(L);\n For i := 1 to L do\n Writeln(i:3,Catalan[i]:20);\nend.\n", "language": "Pascal" }, { "code": "use constant N => 15;\nmy @t = (0, 1);\nfor(my $i = 1; $i <= N; $i++) {\n for(my $j = $i; $j > 1; $j--) { $t[$j] += $t[$j-1] }\n $t[$i+1] = $t[$i];\n for(my $j = $i+1; $j>1; $j--) { $t[$j] += $t[$j-1] }\n print $t[$i+1] - $t[$i], \" \";\n}\n", "language": "Perl" }, { "code": "use ntheory qw/binomial/;\nprint join(\" \", map { binomial( 2*$_, $_) / ($_+1) } 1 .. 1000), \"\\n\";\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">N</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">15</span> <span style=\"color: #000080;font-style:italic;\">-- accurate to 30, nan/inf for anything over 514 (gmp version is below).</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">catalan</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span> <span style=\"color: #000080;font-style:italic;\">-- (&gt;=1 only)</span>\n <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">N</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">p1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">N</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">p1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]*</span><span style=\"color: #000000;\">2</span>\n <span style=\"color: #000000;\">catalan</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">catalan</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p1</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">N</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">p1</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">p1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000080;font-style:italic;\">-- ?p[1..N-i+1]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">catalan</span>\n<!--\n", "language": "Phix" }, { "code": "-- FreeBASIC said:\n--' 1 1 1 1 1 1\n--' 1 2 3 4 5 6\n--' 1 3 6 10 15 21\n--' 1 4 10 20 35 56\n--' 1 5 15 35 70 126\n--' 1 6 21 56 126 252\n--' The Pascal triangle is rotated 45 deg.\n--' to find the Catalan number we need to follow the diagonal\n--' for top left to bottom right\n--' take the number on diagonal and subtract the number in de cell\n--' one up and one to right\n--' 1 (2 - 1), 2 (6 - 4), 5 (20 - 15) ...\n--\n-- The first thing that struck me was it is twice as big as it needs to be,\n-- something like this would do...\n-- 1 1 1 1 1 1\n-- 2 3 4 5 6\n-- 6 10 15 21\n-- 20 35 56\n-- 70 126\n-- 252\n-- It is more obvious from the upper square that the diagonal on that, which is\n-- that same as column 1 on this, is twice the previous, which on the second\n-- diagram is in column 2. Further, once we have calculated the value for column\n-- one above, we can use it immediately to calculate the next catalan number and\n-- do not need to store it. Lastly we can overwrite row 1 with row 2 etc in situ,\n-- and the following shows what we need for subsequent rounds:\n-- 1 1 1 1 1\n-- 3 4 5 6\n-- 10 15 21\n-- 35 56\n-- 126 (unused)\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">builtins</span><span style=\"color: #0000FF;\">\\</span><span style=\"color: #004080;\">mpfr</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">catalanB</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- very very fast!</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">catalan</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_inits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_inits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">p1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_init</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">p1</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">mpz_mul_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpz_sub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">catalan</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">p1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">mpz_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #7060A8;\">mpz_set</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">p1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">catalan</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d: %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">shorten</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">mpz_get_str</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">catalanB</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">)))})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d: %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">250</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">shorten</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">mpz_get_str</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">catalanB</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">250</span><span style=\"color: #0000FF;\">)))})</span>\n<!--\n", "language": "Phix" }, { "code": "(de bino (N K)\n (let f\n '((N)\n (if (=0 N) 1 (apply * (range 1 N))) )\n (/\n (f N)\n (* (f (- N K)) (f K)) ) ) )\n\n(for N 15\n (println\n (-\n (bino (* 2 N) N)\n (bino (* 2 N) (inc N)) ) ) )\n(bye)\n", "language": "PicoLisp" }, { "code": "#MAXNUM = 15\nDeclare catalan()\n\nIf OpenConsole(\"Catalan numbers\")\n catalan()\n Input()\n End 0\nElse\n End -1\nEndIf\n\nProcedure catalan()\n Define k.i, n.i, num.d, den.d, cat.d\n\n Print(\"1 \")\n\n For n=2 To #MAXNUM\n num=1 : den =1\n For k=2 To n\n num * (n+k)\n den * k\n cat = num / den\n Next\n Print(Str(cat)+\" \")\n Next\nEndProcedure\n", "language": "PureBasic" }, { "code": ">>> n = 15\n>>> t = [0] * (n + 2)\n>>> t[1] = 1\n>>> for i in range(1, n + 1):\n\tfor j in range(i, 1, -1): t[j] += t[j - 1]\n\tt[i + 1] = t[i]\n\tfor j in range(i + 1, 1, -1): t[j] += t[j - 1]\n\tprint(t[i+1] - t[i], end=' ')\n\n\t\n1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845\n>>>\n", "language": "Python" }, { "code": "def catalan_number(n):\n nm = dm = 1\n for k in range(2, n+1):\n nm, dm = ( nm*(n+k), dm*k )\n return nm/dm\n\nprint [catalan_number(n) for n in range(1, 16)]\n\n[1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845]\n", "language": "Python" }, { "code": "'''Catalan numbers from Pascal's triangle'''\n\nfrom itertools import (islice)\nfrom operator import (add)\n\n\n# nCatalans :: Int -> [Int]\ndef nCatalans(n):\n '''The first n Catalan numbers,\n derived from Pascal's triangle.'''\n\n # diff :: [Int] -> Int\n def diff(xs):\n '''Difference between the first two items in the list,\n if its length is more than one.\n Otherwise, the first (only) item in the list.'''\n return (\n xs[0] - (xs[1] if 1 < len(xs) else 0)\n ) if xs else None\n return list(map(\n compose(diff)(uncurry(drop)),\n enumerate(map(fst, take(n)(\n everyOther(\n pascalTriangle()\n )\n )))\n ))\n\n\n# pascalTriangle :: Gen [[Int]]\ndef pascalTriangle():\n '''A non-finite stream of\n Pascal's triangle rows.'''\n return iterate(nextPascal)([1])\n\n\n# nextPascal :: [Int] -> [Int]\ndef nextPascal(xs):\n '''A row of Pascal's triangle\n derived from a preceding row.'''\n return zipWith(add)([0] + xs)(xs + [0])\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''First 16 Catalan numbers.'''\n\n print(\n nCatalans(16)\n )\n\n\n# GENERIC -------------------------------------------------\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# drop :: Int -> [a] -> [a]\n# drop :: Int -> String -> String\ndef drop(n):\n '''The sublist of xs beginning at\n (zero-based) index n.'''\n def go(xs):\n if isinstance(xs, list):\n return xs[n:]\n else:\n take(n)(xs)\n return xs\n return lambda xs: go(xs)\n\n\n# everyOther :: Gen [a] -> Gen [a]\ndef everyOther(g):\n '''Every other item of a generator stream.'''\n while True:\n yield take(1)(g)\n take(1)(g) # Consumed, not yielded.\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First component of a pair.'''\n return tpl[0]\n\n\n# iterate :: (a -> a) -> a -> Gen [a]\ndef iterate(f):\n '''An infinite list of repeated applications of f to x.'''\n def go(x):\n v = x\n while True:\n yield v\n v = f(v)\n return lambda x: go(x)\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.'''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, list)\n else list(islice(xs, n))\n )\n\n\n# uncurry :: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n '''A function over a tuple\n derived from a curried function.'''\n return lambda xy: f(xy[0])(\n xy[1]\n )\n\n\n# zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\ndef zipWith(f):\n '''A list constructed by zipping with a\n custom function, rather than with the\n default tuple constructor.'''\n return lambda xs: lambda ys: (\n list(map(f, xs, ys))\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": " [ [] 0 rot 0 join\n witheach\n [ tuck +\n rot join swap ]\n drop ] is nextline ( [ --> [ )\n\n [ ' [ 1 ] swap times\n [ nextline nextline\n dup dup size 2 /\n split nip\n 2 split drop\n do - echo sp ]\n drop ] is catalan ( n --> )\n\n 15 catalan\n", "language": "Quackery" }, { "code": "#lang racket\n\n(define (next-half-row r)\n (define r1 (for/list ([x r] [y (cdr r)]) (+ x y)))\n `(,(* 2 (car r1)) ,@(for/list ([x r1] [y (cdr r1)]) (+ x y)) 1 0))\n\n(let loop ([n 15] [r '(1 0)])\n (cons (- (car r) (cadr r))\n (if (zero? n) '() (loop (sub1 n) (next-half-row r)))))\n;; -> '(1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900\n;; 2674440 9694845)\n", "language": "Racket" }, { "code": "constant @pascal = [1], -> @p { [0, |@p Z+ |@p, 0] } ... *;\n\nconstant @catalan = gather for 2, 4 ... * -> $ix {\n my @row := @pascal[$ix];\n my $mid = +@row div 2;\n take [-] @row[$mid, $mid+1]\n}\n\n.say for @catalan[^20];\n", "language": "Raku" }, { "code": "/*REXX program obtains and displays Catalan numbers from a Pascal's triangle. */\nparse arg N . /*Obtain the optional argument from CL.*/\nif N=='' | N==\",\" then N=15 /*Not specified? Then use the default.*/\nnumeric digits max(9, N%2 + N%8) /*so we can handle huge Catalan numbers*/\n@.=0; @.1=1 /*stem array default; define 1st value.*/\n\n do i=1 for N; ip=i+1\n do j=i by -1 for N; jm=j-1; @[email protected][email protected]; end /*j*/\n @[email protected]; do k=ip by -1 for N; km=k-1; @[email protected][email protected]; end /*k*/\n say @.ip - @.i /*display the Ith Catalan number. */\n end /*i*/ /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "/*REXX program obtains and displays Catalan numbers from a Pascal's triangle. */\nparse arg N . /*Obtain the optional argument from CL.*/\nif N=='' | N==\",\" then N=15 /*Not specified? Then use the default.*/\nnumeric digits max(9, N%2 + N%8) /*so we can handle huge Catalan numbers*/\n@.=0; @.1=1 /*stem array default; define 1st value.*/\n do i=1 for N; ip=i+1\n do j=i by -1 for N; @[email protected]+@(j-1); end /*j*/\n @[email protected]; do k=ip by -1 for N; @[email protected]+@(k-1); end /*k*/\n say @.ip - @.i /*display the Ith Catalan number. */\n end /*i*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n@: parse arg !; return @.! /*return the value of @.[arg(1)] */\n", "language": "REXX" }, { "code": "/*REXX program obtains and displays Catalan numbers from a Pascal's triangle. */\nparse arg N . /*Obtain the optional argument from CL.*/\nif N=='' | N==\",\" then N=15 /*Not specified? Then use the default.*/\nnumeric digits max(9, N%2 + N%8) /*so we can handle huge Catalan numbers*/\n do j=1 for N /* [↓] display N Catalan numbers. */\n say comb(j+j, j) % (j+1) /*display the Jth Catalan number. */\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n!: procedure; parse arg z; _=1; do j=1 for arg(1); _=_*j; end; return _\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncomb: procedure; parse arg x,y; if x=y then return 1; if y>x then return 0\n if x-y<y then y=x-y; _=1; do j=x-y+1 to x; _=_*j; end; return _/!(y)\n", "language": "REXX" }, { "code": "/*REXX program obtains and displays Catalan numbers from a Pascal's triangle. */\nparse arg N . /*Obtain the optional argument from CL.*/\nif N=='' | N==\",\" then N=15 /*Not specified? Then use the default.*/\nnumeric digits max(9, N%2 + N%8) /*so we can handle huge Catalan numbers*/\n!.=.\n do j=1 for N /* [↓] display N Catalan numbers. */\n say comb(j+j, j) % (j+1) /*display the Jth Catalan number. */\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n!: procedure expose !.; parse arg z; if !.z\\==. then return !.z; _=1\n do j=1 for arg(1); _=_*j; end; !.z=_; return _\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncomb: procedure expose !.; parse arg x,y; if x=y then return 1; if y>x then return 0\n if x-y<y then y=x-y; _=1; do j=x-y+1 to x; _=_*j; end; return _/!(y)\n", "language": "REXX" }, { "code": "n=15\ncat = list(n+2)\ncat[1]=1\nfor i=1 to n\n for j=i+1 to 2 step -1\n cat[j]=cat[j]+cat[j-1]\n next\n cat[i+1]=cat[i]\n for j=i+2 to 2 step -1\n cat[j]=cat[j]+cat[j-1]\n next\n see \"\" + (cat[i+1]-cat[i]) + \" \"\nnext\n", "language": "Ring" }, { "code": "def catalan(num)\n t = [0, 1] #grows as needed\n (1..num).map do |i|\n i.downto(1){|j| t[j] += t[j-1]}\n t[i+1] = t[i]\n (i+1).downto(1) {|j| t[j] += t[j-1]}\n t[i+1] - t[i]\n end\nend\n\np catalan(15)\n", "language": "Ruby" }, { "code": "n = 15\ndim t(n+2)\nt(1) = 1\nfor i = 1 to n\n for j = i to 1 step -1 : t(j) = t(j) + t(j-1): next j\n t(i+1) = t(i)\n for j = i+1 to 1 step -1: t(j) = t(j) + t(j-1 : next j\nprint t(i+1) - t(i);\" \";\nnext i\n", "language": "Run-BASIC" }, { "code": "fn main()\n{let n=15usize;\n let mut t= [0; 17];\n t[1]=1;\n let mut j:usize;\n for i in 1..n+1\n {\n\tj=i;\n\tloop{\n\t if j==1{\n\t\t break;\n\t\t}\n\t\tt[j]=t[j] + t[j-1];\n\t\tj=j-1;\n\t}\n\tt[i+1]= t[i];\n\tj=i+1;\n\tloop{\n\t\tif j==1{\n\t\tbreak;\n\t\t}\n\t\tt[j]=t[j] + t[j-1];\n\t\tj=j-1;\n\t}\n\tprint!(\"{} \", t[i+1]-t[i]);\n }\n}\n", "language": "Rust" }, { "code": "def catalan(n: Int): Int =\n if (n <= 1) 1\n else (0 until n).map(i => catalan(i) * catalan(n - i - 1)).sum\n\n(1 to 15).map(catalan(_))\n", "language": "Scala" }, { "code": "n=15\nt=zeros(1,n+2)\nt(1)=1\nfor i=1:n\n for j=i+1:-1:2\n t(j)=t(j)+t(j-1)\n end\n t(i+1)=t(i)\n for j=i+2:-1:2\n t(j)=t(j)+t(j-1)\n end\n disp(t(i+1)-t(i))\nend\n", "language": "Scilab" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst proc: main is func\n local\n const integer: N is 15;\n var array integer: t is [] (1) & N times 0;\n var integer: i is 0;\n var integer: j is 0;\n begin\n for i range 1 to N do\n for j range i downto 2 do\n t[j] +:= t[j - 1];\n end for;\n t[i + 1] := t[i];\n for j range i + 1 downto 2 do\n t[j] +:= t[j - 1];\n end for;\n write(t[i + 1] - t[i] <& \" \");\n end for;\n writeln;\n end func;\n", "language": "Seed7" }, { "code": "func catalan(num) {\n var t = [0, 1]\n (1..num).map { |i|\n flip(^i ).each {|j| t[j+1] += t[j] }\n t[i+1] = t[i]\n flip(^i.inc).each {|j| t[j+1] += t[j] }\n t[i+1] - t[i]\n }\n}\n\nsay catalan(15).join(' ')\n", "language": "Sidef" }, { "code": "PRINT \"Catalan Numbers from Pascal's Triangle\"!PRINT\nx = 15\nDIM t(x+2)\nt(1) = 1\nFOR n = 1 TO x\n FOR m = n TO 1 STEP -1\n t(m) = t(m) + t(m-1)\n NEXT m\n t(n+1) = t(n)\n FOR m = n+1 TO 1 STEP -1\n t(m) = t(m) + t(m-1)\n NEXT m\nPRINT n,\"#######\":t(n+1) - t(n)\nNEXT n\n", "language": "Smart-BASIC" }, { "code": "proc catalan n {\n set result {}\n array set t {0 0 1 1}\n for {set i 1} {[set k $i] <= $n} {incr i} {\n\tfor {set j $i} {$j > 1} {} {incr t($j) $t([incr j -1])}\n\tset t([incr k]) $t($i)\n\tfor {set j $k} {$j > 1} {} {incr t($j) $t([incr j -1])}\n\tlappend result [expr {$t($k) - $t($i)}]\n }\n return $result\n}\n\nputs [catalan 15]\n", "language": "Tcl" }, { "code": "\"CATALAN\n15→N\nseq(0,I,1,N+2)→L1\n1→L1(1)\nFor(I,1,N)\nFor(J,I+1,2,-1)\nL1(J)+L1(J-1)→L1(J)\nEnd\nL1(I)→L1(I+1)\nFor(J,I+2,2,-1)\nL1(J)+L1(J-1)→L1(J)\nEnd\nDisp L1(I+1)-L1(I)\nEnd\n", "language": "TI-83-BASIC" }, { "code": "void main() {\n const int N = 15;\n uint64[] t = {0, 1};\n for (int i = 1; i <= N; i++) {\n for (int j = i; j > 1; j--) t[j] = t[j] + t[j - 1];\n t[i + 1] = t[i];\n for (int j = i + 1; j > 1; j--) t[j] = t[j] + t[j - 1];\n print(@\"$(t[i + 1] - t[i]) \");\n }\n print(\"\\n\");\n}\n", "language": "Vala" }, { "code": "dim t()\nif Wscript.arguments.count=1 then\n n=Wscript.arguments.item(0)\nelse\n n=15\nend if\nredim t(n+1)\n't(*)=0\nt(1)=1\nfor i=1 to n\n ip=i+1\n for j = i to 1 step -1\n t(j)=t(j)+t(j-1)\n next 'j\n t(i+1)=t(i)\n for j = i+1 to 1 step -1\n t(j)=t(j)+t(j-1)\n next 'j\n Wscript.echo t(i+1)-t(i)\nnext 'i\n", "language": "VBScript" }, { "code": "Sub catalan()\n Const n = 15\n Dim t(n + 2) As Long\n Dim i As Integer, j As Integer\n t(1) = 1\n For i = 1 To n\n For j = i + 1 To 2 Step -1\n t(j) = t(j) + t(j - 1)\n Next j\n t(i + 1) = t(i)\n For j = i + 2 To 2 Step -1\n t(j) = t(j) + t(j - 1)\n Next j\n Debug.Print i, t(i + 1) - t(i)\n Next i\nEnd Sub 'catalan\n", "language": "Visual-Basic" }, { "code": "var n = 15\nvar t = List.filled(n+2, 0)\nt[1] = 1\nfor (i in 1..n) {\n if (i > 1) for (j in i..2) t[j] = t[j] + t[j-1]\n t[i+1] = t[i]\n if (i > 0) for (j in i+1..2) t[j] = t[j] + t[j-1]\n System.write(\"%(t[i+1]-t[i]) \")\n}\nSystem.print()\n", "language": "Wren" }, { "code": "PROGRAM\t\"Pascal's triangle\"\nVERSION\t\"0.0000\"\n\n\nDECLARE FUNCTION Entry ()\n\n\nFUNCTION Entry ()\n N = 15\n DIM T[N+2]\n T[1] = 1\n\n PRINT \"The first 15 Catalan numbers are: \"; CHR$(10)\n FOR I = 1 TO N\n FOR J = I TO 1 STEP -1\n T[J] = T[J] + T[J-1]\n NEXT J\n T[I+1] = T[I]\n FOR J = I+1 TO 1 STEP -1\n T[J] = T[J] + T[J-1]\n NEXT J\n PRINT FORMAT$(\"###\",I); \": \"; FORMAT$(\"#########\",(T[I+1] - T[I]))\n NEXT I\n\nEND FUNCTION\nEND PROGRAM\n", "language": "XBasic" }, { "code": "def N = 15;\nint T(N+2), I, J;\n[T(0):= 0; T(1):= 1;\nfor I:= 1 to N do\n [for J:= I downto 2 do T(J):= T(J) + T(J-1);\n T(I+1):= T(I);\n for J:= I+1 downto 2 do T(J):= T(J) + T(J-1);\n IntOut(0, T(I+1) - T(I)); ChOut(0, ^ );\n ];\n]\n", "language": "XPL0" }, { "code": "n = 15\ndim t(n+2)\nt(1) = 1\nprint \"The first 15 Catalan numbers are: \\n\"\nfor i = 1 to n\n for j = i to 1 step -1\n t(j) = t(j) + t(j-1)\n next j\n t(i+1) = t(i)\n for j = i+1 to 1 step -1\n t(j) = t(j) + t(j-1)\n next j\n print i using(\"###\");\n print \": \";\n print t(i+1)-t(i) using (\"#########\")\nnext i\n", "language": "Yabasic" }, { "code": "const std = @import(\"std\");\n\npub fn main() !void {\n const stdout = std.io.getStdOut().writer();\n\n var n: u32 = 1;\n while (n <= 15) : (n += 1) {\n const row = binomial(n * 2).?;\n try stdout.print(\"{d:2} {d:8}\\n\", .{ n, row[n] - row[n + 1] });\n }\n}\n\npub fn binomial(n: u32) ?[]const u64 {\n if (n >= rmax)\n return null\n else {\n const k = n * (n + 1) / 2;\n return pascal[k .. k + n + 1];\n }\n}\n\nconst rmax = 68;\n\n// evaluated and created at compile-time\nconst pascal = build: {\n @setEvalBranchQuota(100_000);\n var coefficients: [(rmax * (rmax + 1)) / 2]u64 = undefined;\n coefficients[0] = 1;\n var j: u32 = 0;\n var k: u32 = 1;\n var n: u32 = 1;\n while (n < rmax) : (n += 1) {\n var prev = coefficients[j .. j + n];\n var next = coefficients[k .. k + n + 1];\n next[0] = 1;\n var i: u32 = 1;\n while (i < n) : (i += 1)\n next[i] = prev[i] + prev[i - 1];\n next[i] = 1;\n j = k;\n k += n + 1;\n }\n break :build coefficients;\n};\n", "language": "Zig" }, { "code": "fcn binomial(n,k){ (1).reduce(k,fcn(p,i,n){ p*(n-i+1)/i },1,n) }\n(1).pump(15,List,fcn(n){ binomial(2*n,n)-binomial(2*n,n+1) })\n", "language": "Zkl" }, { "code": "10 LET N=15\n20 DIM t(N+2)\n30 LET t(2)=1\n40 FOR i=2 TO N+1\n50 FOR j=i TO 2 STEP -1: LET t(j)=t(j)+t(j-1): NEXT j\n60 LET t(i+1)=t(i)\n70 FOR j=i+1 TO 2 STEP -1: LET t(j)=t(j)+t(j-1): NEXT j\n80 PRINT t(i+1)-t(i);\" \";\n90 NEXT i\n", "language": "ZX-Spectrum-Basic" } ]
Catalan-numbers-Pascals-triangle
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Catamorphism\n", "language": "00-META" }, { "code": "''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. \n\n\n;Task:\nShow how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.\n\n\n;See also:\n* Wikipedia article: &nbsp; [[wp:Fold (higher-order function)|Fold]]\n* Wikipedia article: &nbsp; [[wp:Catamorphism|Catamorphism]]\n<br><br>\n", "language": "00-TASK" }, { "code": "print((1..3).reduce((x, y) -> x + y))\nprint((1..3).reduce(3, (x, y) -> x + y))\nprint([1, 1, 3].reduce((x, y) -> x + y))\nprint([1, 1, 3].reduce(2, (x, y) -> x + y))\n", "language": "11l" }, { "code": "define catbuf $10\ndefine catbuf_temp $12\n\nldx #0\nramloop:\ntxa\nsta $00,x\ninx\ncpx #$10\nbne ramloop\t\n;load zero page addresses $00-$0f with values equal\n;to that address\n\n\nldx #0\t\t;zero X\nloop_cata:\nlda $00,x\t;load the zeroth element\nclc\nadc $01,x\t;add the first to it.\ninx\t\t\ninx\t\t;inx twice. Otherwise the same element\n\t\t;would get added twice\nsta catbuf_temp ;store in temp ram\nlda catbuf\t\nclc\nadc catbuf_temp ;add to previously stored value\nsta catbuf\t;store in result\ncpx #$10\t;is the range over?\nbne loop_cata\t;if not, loop again\n\nldx #$00\nlda catbuf\nsta $00,x\t\n;store the sum in the zeroth entry of the range\n\ninx\nlda #$00\n\n;now clear the rest of zeropage, leaving only the sum\n\nclear_ram:\nsta $00,x\ninx\ncpx #$ff\nbne clear_ram\n", "language": "6502-Assembly" }, { "code": "report z_catamorphism.\n\ndata(numbers) = value int4_table( ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 ) ).\n\nwrite: |numbers = { reduce string(\n init output = `[`\n index = 1\n for number in numbers\n next output = cond string(\n when index eq lines( numbers )\n then |{ output }, { number } ]|\n when index > 1\n then |{ output }, { number }|\n else |{ output } { number }| )\n index = index + 1 ) }|, /.\n\nwrite: |sum(numbers) = { reduce int4(\n init result = 0\n for number in numbers\n next result = result + number ) }|, /.\n\nwrite: |product(numbers) = { reduce int4(\n init result = 1\n for number in numbers\n next result = result * number ) }|, /.\n\ndata(strings) = value stringtab( ( `reduce` ) ( `in` ) ( `ABAP` ) ).\n\nwrite: |strings = { reduce string(\n init output = `[`\n index = 1\n for string in strings\n next output = cond string(\n when index eq lines( strings )\n then |{ output }, { string } ]|\n when index > 1\n then |{ output }, { string }|\n else |{ output } { string }| )\n index = index + 1 ) }|, /.\n\nwrite: |concatenation(strings) = { reduce string(\n init text = ``\n for string in strings\n next text = |{ text } { string }| ) }|, /.\n", "language": "ABAP" }, { "code": "with Ada.Text_IO;\n\nprocedure Catamorphism is\n\n type Fun is access function (Left, Right: Natural) return Natural;\n type Arr is array(Natural range <>) of Natural;\n\n function Fold_Left (F: Fun; A: Arr) return Natural is\n Result: Natural := A(A'First);\n begin\n for I in A'First+1 .. A'Last loop\n\t Result := F(Result, A(I));\n end loop;\n return Result;\n end Fold_Left;\n\n function Max (L, R: Natural) return Natural is (if L > R then L else R);\n function Min (L, R: Natural) return Natural is (if L < R then L else R);\n function Add (Left, Right: Natural) return Natural is (Left + Right);\n function Mul (Left, Right: Natural) return Natural is (Left * Right);\n\n package NIO is new Ada.Text_IO.Integer_IO(Natural);\n\nbegin\n NIO.Put(Fold_Left(Min'Access, (1,2,3,4)), Width => 3);\n NIO.Put(Fold_Left(Max'Access, (1,2,3,4)), Width => 3);\n NIO.Put(Fold_Left(Add'Access, (1,2,3,4)), Width => 3);\n NIO.Put(Fold_Left(Mul'Access, (1,2,3,4)), Width => 3);\nend Catamorphism;\n", "language": "Ada" }, { "code": "integer s;\n\ns = 0;\nlist(1, 2, 3, 4, 5, 6, 7, 8, 9).ucall(add_i, 1, s);\no_(s, \"\\n\");\n", "language": "Aime" }, { "code": "# applies fn to successive elements of the array of values #\n# the result is 0 if there are no values #\nPROC reduce = ( []INT values, PROC( INT, INT )INT fn )INT:\n IF UPB values < LWB values\n THEN # no elements #\n 0\n ELSE # there are some elements #\n INT result := values[ LWB values ];\n FOR pos FROM LWB values + 1 TO UPB values\n DO\n result := fn( result, values[ pos ] )\n OD;\n result\n FI; # reduce #\n\n# test the reduce procedure #\nBEGIN print( ( reduce( ( 1, 2, 3, 4, 5 ), ( INT a, b )INT: a + b ), newline ) ) # sum #\n ; print( ( reduce( ( 1, 2, 3, 4, 5 ), ( INT a, b )INT: a * b ), newline ) ) # product #\n ; print( ( reduce( ( 1, 2, 3, 4, 5 ), ( INT a, b )INT: a - b ), newline ) ) # difference #\nEND\n", "language": "ALGOL-68" }, { "code": " +/ 1 2 3 4 5 6 7\n28\n ×/ 1 2 3 4 5 6 7\n5040\n", "language": "APL" }, { "code": " +/⍬\n0\n ×/⍬\n1\n ⌈/⍬ ⍝ this gives the minimum supported value\n¯1.797693135E308\n", "language": "APL" }, { "code": " {⎕←'Input:',⍺,⍵ ⋄ ⍺+⍵}/ 1 2 3 4 5\nInput: 4 5\nInput: 3 9\nInput: 2 12\nInput: 1 14\n15\n {⎕←'Input:',⍺,⍵ ⋄ ⍺+⍵}/ 1\n1\n {⎕←'Input:',⍺,⍵ ⋄ ⍺+⍵}/ ⍬\nDOMAIN ERROR\n", "language": "APL" }, { "code": "---------------------- CATAMORPHISMS ---------------------\n\n-- the arguments available to the called function f(a, x, i, l) are\n-- a: current accumulator value\n-- x: current item in list\n-- i: [ 1-based index in list ] optional\n-- l: [ a reference to the list itself ] optional\n\n-- foldl :: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n-- the arguments available to the called function f(a, x, i, l) are\n-- a: current accumulator value\n-- x: current item in list\n-- i: [ 1-based index in list ] optional\n-- l: [ a reference to the list itself ] optional\n\n-- foldr :: (a -> b -> a) -> a -> [b] -> a\non foldr(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from lng to 1 by -1\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldr\n\n\n--- OTHER FUNCTIONS DEFINED IN TERMS OF FOLDL AND FOLDR --\n\n-- concat :: [String] -> string\non concat(xs)\n foldl(my append, \"\", xs)\nend concat\n\n\n-- product :: Num a => [a] -> a\non product(xs)\n script\n on |λ|(a, b)\n a * b\n end |λ|\n end script\n\n foldr(result, 1, xs)\nend product\n\n\n-- str :: a -> String\non str(x)\n x as string\nend str\n\n\n-- sum :: Num a => [a] -> a\non sum(xs)\n script\n on |λ|(a, b)\n a + b\n end |λ|\n end script\n\n foldl(result, 0, xs)\nend sum\n\n\n--------------------------- TEST -------------------------\non run\n set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n\n {sum(xs), product(xs), concat(map(str, xs))}\n\n --> {55, 3628800, \"10987654321\"}\nend run\n\n\n-------------------- GENERIC FUNCTIONS -------------------\n\n-- append :: String -> String -> String\non append(a, b)\n a & b\nend append\n\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n -- The list obtained by applying f\n -- to each element of xs.\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n", "language": "AppleScript" }, { "code": "; find the sum, with seed:0 (default)\nprint fold [1 2 3 4] => add\n\n; find the product, with seed:1\nprint fold [1 2 3 4] .seed:1 => mul\n", "language": "Arturo" }, { "code": "arraybase 1\nglobal n\ndim n = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n\nprint \" +: \"; \" \"; cat(10, \"+\")\nprint \" -: \"; \" \"; cat(10, \"-\")\nprint \" *: \"; \" \"; cat(10, \"*\")\nprint \" /: \"; \" \"; cat(10, \"/\")\nprint \" ^: \"; \" \"; cat(10, \"^\")\nprint \"max: \"; \" \"; cat(10, \"max\")\nprint \"min: \"; \" \"; cat(10, \"min\")\nprint \"avg: \"; \" \"; cat(10, \"avg\")\nprint \"cat: \"; \" \"; cat(10, \"cat\")\nend\n\nfunction min(a, b)\n if a < b then return a else return b\nend function\nfunction max(a, b)\n if a > b then return a else return b\nend function\n\nfunction cat(cont, op$)\n temp = n[1]\n temp$ = \"\"\n for i = 2 to cont\n if op$ = \"+\" then temp += n[i]\n if op$ = \"-\" then temp -= n[i]\n if op$ = \"*\" then temp *= n[i]\n if op$ = \"/\" then temp /= n[i]\n if op$ = \"^\" then temp = temp ^ n[i]\n if op$ = \"max\" then temp = max(temp, n[i])\n if op$ = \"min\" then temp = min(temp, n[i])\n if op$ = \"avg\" then temp += n[i]\n if op$ = \"cat\" then temp$ += string(n[i])\n next i\n if op$ = \"avg\" then temp /= cont\n if op$ = \"cat\" then temp = int(string(n[1]) + temp$)\n return temp\nend function\n", "language": "BASIC256" }, { "code": " DIM a(4)\n a() = 1, 2, 3, 4, 5\n PRINT FNreduce(a(), \"+\")\n PRINT FNreduce(a(), \"-\")\n PRINT FNreduce(a(), \"*\")\n END\n\n DEF FNreduce(arr(), op$)\n REM!Keep tmp, arr()\n LOCAL I%, tmp\n tmp = arr(0)\n FOR I% = 1 TO DIM(arr(), 1)\n tmp = EVAL(\"tmp \" + op$ + \" arr(I%)\")\n NEXT\n = tmp\n", "language": "BBC-BASIC" }, { "code": "get \"libhdr\"\n\nlet reduce(f, v, len, seed) =\n len = 0 -> seed,\n reduce(f, v+1, len-1, f(!v, seed))\n\nlet start() be\n$( let add(x, y) = x+y\n let mul(x, y) = x*y\n\n let nums = table 1,2,3,4,5,6,7\n\n writef(\"%N*N\", reduce(add, nums, 7, 0))\n writef(\"%N*N\", reduce(mul, nums, 7, 1))\n$)\n", "language": "BCPL" }, { "code": "( ( fold\n = f xs init first rest\n . !arg:(?f.?xs.?init)\n & ( !xs:&!init\n | !xs:%?first ?rest\n & !f$(!first.fold$(!f.!rest.!init))\n )\n )\n& out\n $ ( fold\n $ ( (=a b.!arg:(?a.?b)&!a+!b)\n . 1 2 3 4 5\n . 0\n )\n )\n& (product=a b.!arg:(?a.?b)&!a*!b)\n& out$(fold$(product.1 2 3 4 5.1))\n);\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n\ntypedef int (*intFn)(int, int);\n\nint reduce(intFn fn, int size, int *elms)\n{\n int i, val = *elms;\n for (i = 1; i < size; ++i)\n val = fn(val, elms[i]);\n return val;\n}\n\nint add(int a, int b) { return a + b; }\nint sub(int a, int b) { return a - b; }\nint mul(int a, int b) { return a * b; }\n\nint main(void)\n{\n int nums[] = {1, 2, 3, 4, 5};\n printf(\"%d\\n\", reduce(add, 5, nums));\n printf(\"%d\\n\", reduce(sub, 5, nums));\n printf(\"%d\\n\", reduce(mul, 5, nums));\n return 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <numeric>\n#include <functional>\n#include <vector>\n\nint main() {\n\tstd::vector<int> nums = { 1, 2, 3, 4, 5 };\n\tauto nums_added = std::accumulate(std::begin(nums), std::end(nums), 0, std::plus<int>());\n\tauto nums_other = std::accumulate(std::begin(nums), std::end(nums), 0, [](const int& a, const int& b) {\n\t\treturn a + 2 * b;\n\t});\n\tstd::cout << \"nums_added: \" << nums_added << std::endl;\n\tstd::cout << \"nums_other: \" << nums_other << std::endl;\n}\n", "language": "C++" }, { "code": "var nums = Enumerable.Range(1, 10);\n\nint summation = nums.Aggregate((a, b) => a + b);\n\nint product = nums.Aggregate((a, b) => a * b);\n\nstring concatenation = nums.Aggregate(String.Empty, (a, b) => a.ToString() + b.ToString());\n\nConsole.WriteLine(\"{0} {1} {2}\", summation, product, concatenation);\n", "language": "C-sharp" }, { "code": "100 DIM n(10)\n110 FOR i = 1 TO 10 : n(i) = i : NEXT i\n120 SUB cat(cnt,op$)\n130 temp = n(1)\n140 FOR i = 2 TO cnt\n150 IF op$ = \"+\" THEN temp = temp+n(i)\n160 IF op$ = \"-\" THEN temp = temp-n(i)\n170 IF op$ = \"*\" THEN temp = temp*n(i)\n180 IF op$ = \"/\" THEN temp = temp/n(i)\n190 IF op$ = \"^\" THEN temp = temp^n(i)\n200 IF op$ = \"max\" THEN temp = FN MAX(temp,n(i))\n210 IF op$ = \"min\" THEN temp = FN MIN(temp,n(i))\n220 IF op$ = \"avg\" THEN temp = temp+n(i)\n230 IF op$ = \"cat\" THEN temp$ = temp$+STR$(n(i))\n240 NEXT i\n250 IF op$ = \"avg\" THEN temp = temp/cnt\n260 IF op$ = \"cat\" THEN temp = VAL(STR$(n(1))+temp$)\n270 cat = temp\n280 END SUB\n290 '\n300 PRINT \" +: \";cat(10,\"+\")\n310 PRINT \" -: \";cat(10,\"-\")\n320 PRINT \" *: \";cat(10,\"*\")\n330 PRINT \" /: \";cat(10,\"/\")\n340 PRINT \" ^: \";cat(10,\"^\")\n350 PRINT \"min: \";cat(10,\"min\")\n360 PRINT \"max: \";cat(10,\"max\")\n370 PRINT \"avg: \";cat(10,\"avg\")\n380 PRINT \"cat: \";cat(10,\"cat\")\n390 END\n", "language": "Chipmunk-Basic" }, { "code": "; Basic usage\n> (reduce * '(1 2 3 4 5))\n120\n; Using an initial value\n> (reduce + 100 '(1 2 3 4 5))\n115\n", "language": "Clojure" }, { "code": "% Reduction.\n% First type = sequence type (must support S$elements and yield R)\n% Second type = right (input) datatype\n% Third type = left (output) datatype\nreduce = proc [S,R,L: type] (f: proctype (L,R) returns (L),\n id: L,\n seq: S)\n returns (L)\n where S has elements: itertype (S) yields (R)\n\n for elem: R in S$elements(seq) do\n id := f(id, elem)\n end\n return(id)\nend reduce\n\n% This is necessary to get rid of the exceptions\nadd = proc (a,b: int) returns (int) return (a+b) end add\nmul = proc (a,b: int) returns (int) return (a*b) end mul\n\n% Usage\nstart_up = proc ()\n % abbreviation - reducing int->int->int function over an array[int]\n int_reduce = reduce[array[int], int, int]\n\n po: stream := stream$primary_output()\n nums: array[int] := array[int]$[1,2,3,4,5,6,7,8,9,10]\n\n % find the sum and the product using reduce\n sum: int := int_reduce(add, 0, nums)\n product: int := int_reduce(mul, 1, nums)\n\n stream$putl(po, \"The sum of [1..10] is: \" || int$unparse(sum))\n stream$putl(po, \"The product of [1..10] is: \" || int$unparse(product))\nend start_up\n", "language": "CLU" }, { "code": "; Basic usage\n> (reduce #'* '(1 2 3 4 5))\n120\n; Using an initial value\n> (reduce #'+ '(1 2 3 4 5) :initial-value 100)\n115\n; Using only a subsequence\n> (reduce #'+ '(1 2 3 4 5) :start 1 :end 4)\n9\n; Apply a function to each element first\n> (reduce #'+ '((a 1) (b 2) (c 3)) :key #'cadr)\n6\n; Right-associative reduction\n> (reduce #'expt '(2 3 4) :from-end T)\n2417851639229258349412352\n; Compare with\n> (reduce #'expt '(2 3 4))\n4096\n", "language": "Common-Lisp" }, { "code": "void main() {\n import std.stdio, std.algorithm, std.range, std.meta, std.numeric,\n std.conv, std.typecons;\n\n auto list = iota(1, 11);\n alias ops = AliasSeq!(q{a + b}, q{a * b}, min, max, gcd);\n\n foreach (op; ops)\n writeln(op.stringof, \": \", list.reduce!op);\n\n // std.algorithm.reduce supports multiple functions in parallel:\n reduce!(ops[0], ops[3], text)(tuple(0, 0.0, \"\"), list).writeln;\n}\n", "language": "D" }, { "code": "$ list = \"1,2,3,4,5\"\n$ call reduce list \"+\"\n$ show symbol result\n$\n$ numbers = \"5,4,3,2,1\"\n$ call reduce numbers \"-\"\n$ show symbol result\n$\n$ call reduce list \"*\"\n$ show symbol result\n$ exit\n$\n$ reduce: subroutine\n$ local_list = 'p1\n$ value = f$integer( f$element( 0, \",\", local_list ))\n$ i = 1\n$ loop:\n$ element = f$element( i, \",\", local_list )\n$ if element .eqs. \",\" then $ goto done\n$ value = value 'p2 f$integer( element )\n$ i = i + 1\n$ goto loop\n$ done:\n$ result == value\n$ exit\n$ endsubroutine\n", "language": "DCL" }, { "code": ";; rem : the foldX family always need an initial value\n;; fold left a list\n(foldl + 0 (iota 10)) ;; 0 + 1 + .. + 9\n → 45\n\n;; fold left a sequence\n(lib 'sequences)\n(foldl * 1 [ 1 .. 10])\n → 362880 ;; 10!\n\n;; folding left and right\n(foldl / 1 ' ( 1 2 3 4))\n → 8/3\n(foldr / 1 '(1 2 3 4))\n → 3/8\n\n;;scanl gives the list (or sequence) of intermediate values :\n(scanl * 1 '( 1 2 3 4 5))\n → (1 1 2 6 24 120)\n", "language": "EchoLisp" }, { "code": "import system'collections;\nimport system'routines;\nimport extensions;\nimport extensions'text;\n\npublic program()\n{\n var numbers := new Range(1,10).summarize(new ArrayList());\n\n var summary := numbers.accumulate(new Variable(0), (a,b => a + b));\n\n var product := numbers.accumulate(new Variable(1), (a,b => a * b));\n\n var concatenation := numbers.accumulate(new StringWriter(), (a,b => a.toPrintable() + b.toPrintable()));\n\n console.printLine(summary,\" \",product,\" \",concatenation)\n}\n", "language": "Elena" }, { "code": "iex(1)> Enum.reduce(1..10, fn i,acc -> i+acc end)\n55\niex(2)> Enum.reduce(1..10, fn i,acc -> i*acc end)\n3628800\niex(3)> Enum.reduce(10..-10, \"\", fn i,acc -> acc <> to_string(i) end)\n\"109876543210-1-2-3-4-5-6-7-8-9-10\"\n", "language": "Elixir" }, { "code": "-module(catamorphism).\n\n-export([test/0]).\n\ntest() ->\n\tNums = lists:seq(1,10),\n\tSummation =\n\t\tlists:foldl(fun(X, Acc) -> X + Acc end, 0, Nums),\n\tProduct =\n\t\tlists:foldl(fun(X, Acc) -> X * Acc end, 1, Nums),\n\tConcatenation =\n\t\tlists:foldr(\n\t\t\tfun(X, Acc) -> integer_to_list(X) ++ Acc end,\n\t\t\t\"\",\n\t\t\tNums),\n\t{Summation, Product, Concatenation}.\n", "language": "Erlang" }, { "code": "FOLDROW\n=LAMBDA(op,\n LAMBDA(a,\n LAMBDA(xs,\n LET(\n b, op(a)(HEADROW(xs)),\n\n IF(1 < COLUMNS(xs),\n FOLDROW(op)(b)(\n TAILROW(xs)\n ),\n b\n )\n )\n )\n )\n)\n\n\nupdatedBracketDepth\n=LAMBDA(depth,\n LAMBDA(c,\n IF(0 <= depth,\n IF(\"[\" = c,\n 1 + depth,\n IF(\"]\" = c,\n depth - 1,\n depth\n )\n ),\n depth\n )\n )\n)\n\n\nbracketCount\n=LAMBDA(a,\n LAMBDA(c,\n IF(ISNUMBER(FIND(c, \"[]\", 1)),\n 1 + a,\n a\n )\n )\n)\n\n\nHEADROW\n=LAMBDA(xs,\n LET(REM, \"The first item of each row in xs\",\n\n INDEX(\n xs,\n SEQUENCE(ROWS(xs)),\n SEQUENCE(1, 1)\n )\n )\n)\n\n\nTAILROW\n=LAMBDA(xs,\n LET(REM,\"The tail of each row in the grid\",\n n, COLUMNS(xs) - 1,\n\n IF(0 < n,\n INDEX(\n xs,\n SEQUENCE(ROWS(xs), 1, 1, 1),\n SEQUENCE(1, n, 2, 1)\n ),\n NA()\n )\n )\n)\n\n\nCHARSROW\n=LAMBDA(s,\n MID(s,\n SEQUENCE(1, LEN(s), 1, 1),\n 1\n )\n)\n", "language": "Excel" }, { "code": "{ 1 2 4 6 10 } 0 [ + ] reduce .\n", "language": "Factor" }, { "code": ": lowercase? ( c -- f )\n [char] a [ char z 1+ ] literal within ;\n\n: char-upcase ( c -- C )\n dup lowercase? if bl xor then ;\n", "language": "Forth" }, { "code": ": string-at ( c-addr u +n -- c )\n nip + c@ ;\n: string-at! ( c-addr u +n c -- )\n rot drop -rot + c! ;\n\n: type-lowercase ( c-addr u -- )\n dup 0 ?do\n 2dup i string-at dup lowercase? if emit else drop then\n loop 2drop ;\n\n: upcase ( 'string' -- 'STRING' )\n dup 0 ?do\n 2dup 2dup i string-at char-upcase i swap string-at!\n loop ;\n\n: count-lowercase ( c-addr u -- n )\n 0 -rot dup 0 ?do\n 2dup i string-at lowercase? if rot 1+ -rot then\n loop 2drop ;\n", "language": "Forth" }, { "code": ": next-char ( a +n -- a' n' c -1 ) ( a 0 -- 0 )\n dup if 2dup 1 /string 2swap drop c@ true\n else 2drop 0 then ;\n\n: type-lowercase ( c-addr u -- )\n begin next-char while\n dup lowercase? if emit else drop then\n repeat ;\n", "language": "Forth" }, { "code": ": each-char[ ( c-addr u -- )\n postpone BOUNDS postpone ?DO\n postpone I postpone C@ ; immediate\n\n \\ interim code: ( c -- )\n\n: ]each-char ( -- )\n postpone LOOP ; immediate\n\n: type-lowercase ( c-addr u -- )\n each-char[ dup lowercase? if emit else drop then ]each-char ;\n\n: upcase ( 'string' -- 'STRING' )\n 2dup each-char[ char-upcase i c! ]each-char ;\n\n: count-lowercase ( c-addr u -- n )\n 0 -rot each-char[ lowercase? if 1+ then ]each-char ;\n", "language": "Forth" }, { "code": ": each-char ( c-addr u xt -- )\n {: xt :} bounds ?do\n i c@ xt execute\n loop ;\n\n: type-lowercase ( c-addr u -- )\n [: dup lowercase? if emit else drop then ;]\n each-char ;\n\n\\ producing a new string\n: upcase ( 'string' -- 'STRING' )\n dup cell+ allocate throw -rot\n [: ( new-string-addr c -- new-string-addr )\n upcase over c+! ;] each-char $@ ;\n\n: count-lowercase ( c-addr u -- n )\n 0 -rot [: lowercase? if 1+ then ;] each-char ;\n", "language": "Forth" }, { "code": " SUBROUTINE FOLD(t,F,i,ist,lst)\n INTEGER t\n BYNAME F\n DO i = ist,lst\n t = F\n END DO\n END SUBROUTINE FOLD !Result in temp.\n\n temp = a(1); CALL FOLD(temp,temp*a(i),i,2,N)\n", "language": "Fortran" }, { "code": " INTEGER FUNCTION IFOLD(F,A,N)\t!\"Catamorphism\"...\n INTEGER F\t!We're working only with integers.\n EXTERNAL F\t!This is a function, not an array.\n INTEGER A(*)\t!An 1-D array, of unspecified size.\n INTEGER N\t!The number of elements.\n INTEGER I\t!A stepper.\n IFOLD = 0\t\t!A default value.\n IF (N.LE.0) RETURN\t!Dodge silly invocations.\n IFOLD = A(1)\t\t!The function is to have two arguments.\n IF (N.EQ.1) RETURN\t!So, if there is only one element, silly.\n DO I = 2,N\t\t!Otherwise, stutter along the array.\n IFOLD = F(IFOLD,A(I))\t\t!Applying the function.\n END DO\t\t\t!On to the next element.\n END FUNCTION IFOLD!Thus, F(A(1),A(2)), or F(F(A(1),A(2)),A(3)), or F(F(F(A(1),A(2)),A(3)),A(4)), etc.\n\n INTEGER FUNCTION IADD(I,J)\n INTEGER I,J\n IADD = I + J\n END FUNCTION IADD\n\n INTEGER FUNCTION IMUL(I,J)\n INTEGER I,J\n IMUL = I*J\n END FUNCTION IMUL\n\n INTEGER FUNCTION IDIV(I,J)\n INTEGER I,J\n IDIV = I/J\n END FUNCTION IDIV\n\n INTEGER FUNCTION IVID(I,J)\n INTEGER I,J\n IVID = J/I\n END FUNCTION IVID\n\n PROGRAM POKE\n INTEGER ENUFF\n PARAMETER (ENUFF = 6)\n INTEGER A(ENUFF)\n PARAMETER (A = (/1,2,3,4,5,6/))\n INTEGER MSG\n EXTERNAL IADD,IMUL,IDIV,IVID\t!Warn that these are the names of functions.\n\n MSG = 6\t!Standard output.\n WRITE (MSG,1) ENUFF,A\n 1 FORMAT ('To apply a function in the \"catamorphic\" style ',\n 1 \"to the \",I0,\" values \",/,(20I3))\n\n WRITE (MSG,*) \"Iadd\",IFOLD(IADD,A,ENUFF)\n WRITE (MSG,*) \"Imul\",IFOLD(IMUL,A,ENUFF)\n WRITE (MSG,*) \"Idiv\",IFOLD(IDIV,A,ENUFF)\n WRITE (MSG,*) \"Ivid\",IFOLD(IVID,A,ENUFF)\n END PROGRAM POKE\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nType IntFunc As Function(As Integer, As Integer) As Integer\n\nFunction reduce(a() As Integer, f As IntFunc) As Integer\n '' if array is empty or function pointer is null, return 0 say\n If UBound(a) = -1 OrElse f = 0 Then Return 0\n Dim result As Integer = a(LBound(a))\n For i As Integer = LBound(a) + 1 To UBound(a)\n result = f(result, a(i))\n Next\n Return result\nEnd Function\n\nFunction add(x As Integer, y As Integer) As Integer\n Return x + y\nEnd Function\n\nFunction subtract(x As Integer, y As Integer) As Integer\n Return x - y\nEnd Function\n\nFunction multiply(x As Integer, y As Integer) As Integer\n Return x * y\nEnd Function\n\nFunction max(x As Integer, y As Integer) As Integer\n Return IIf(x > y, x, y)\nEnd Function\n\nFunction min(x As Integer, y As Integer) As Integer\n Return IIf(x < y, x, y)\nEnd Function\n\nDim a(4) As Integer = {1, 2, 3, 4, 5}\nPrint \"Sum is :\"; reduce(a(), @add)\nPrint \"Difference is :\"; reduce(a(), @subtract)\nPrint \"Product is :\"; reduce(a(), @multiply)\nPrint \"Maximum is :\"; reduce(a(), @max)\nPrint \"Minimum is :\"; reduce(a(), @min)\nPrint \"No op is :\"; reduce(a(), 0)\nPrint\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\tn := []int{1, 2, 3, 4, 5}\n\n\tfmt.Println(reduce(add, n))\n\tfmt.Println(reduce(sub, n))\n\tfmt.Println(reduce(mul, n))\n}\n\nfunc add(a int, b int) int { return a + b }\nfunc sub(a int, b int) int { return a - b }\nfunc mul(a int, b int) int { return a * b }\n\nfunc reduce(rf func(int, int) int, m []int) int {\n\tr := m[0]\n\tfor _, v := range m[1:] {\n\t\tr = rf(r, v)\n\t}\n\treturn r\n}\n", "language": "Go" }, { "code": "def vector1 = [1,2,3,4,5,6,7]\ndef vector2 = [7,6,5,4,3,2,1]\ndef map1 = [a:1, b:2, c:3, d:4]\n\nprintln vector1.inject { acc, val -> acc + val } // sum\nprintln vector1.inject { acc, val -> acc + val*val } // sum of squares\nprintln vector1.inject { acc, val -> acc * val } // product\nprintln vector1.inject { acc, val -> acc<val?val:acc } // max\nprintln ([vector1,vector2].transpose().inject(0) { acc, val -> acc + val[0]*val[1] }) //dot product (with seed 0)\n\nprintln (map1.inject { Map.Entry accEntry, Map.Entry entry -> // some sort of weird map-based reduction\n [(accEntry.key + entry.key):accEntry.value + entry.value ].entrySet().toList().pop()\n})\n", "language": "Groovy" }, { "code": "main :: IO ()\nmain =\n putStrLn . unlines $\n [ show . foldr (+) 0 -- sum\n , show . foldr (*) 1 -- product\n , foldr ((++) . show) \"\" -- concatenation\n ] <*>\n [[1 .. 10]]\n", "language": "Haskell" }, { "code": "import Data.Monoid\n\nmain :: IO ()\nmain =\n let xs = [1 .. 10]\n in (putStrLn . unlines)\n [ (show . getSum . foldr (<>) mempty) (Sum <$> xs)\n , (show . getProduct . foldr (<>) mempty) (Product <$> xs)\n , (show . foldr (<>) mempty) (show <$> xs)\n , (show . foldr (<>) mempty) (words\n \"Love is one damned thing after each other\")\n ]\n", "language": "Haskell" }, { "code": "procedure main(A)\n write(A[1],\": \",curry(A[1],A[2:0]))\nend\n\nprocedure curry(f,A)\n r := A[1]\n every r := f(r, !A[2:0])\n return r\nend\n", "language": "Icon" }, { "code": " /\n", "language": "J" }, { "code": " +/ 1 2 3 4 5\n15\n */ 1 2 3 4 5\n120\n !/ 1 2 3 4 5 NB. \"n ! k\" is \"n choose k\"\n45\n", "language": "J" }, { "code": "1 * 2 * 3 * 20\n1 * 2 * 60\n1 * 120\n120\n", "language": "J" }, { "code": "import java.util.stream.Stream;\n\npublic class ReduceTask {\n\n public static void main(String[] args) {\n System.out.println(Stream.of(1, 2, 3, 4, 5).mapToInt(i -> i).sum());\n System.out.println(Stream.of(1, 2, 3, 4, 5).reduce(1, (a, b) -> a * b));\n }\n}\n", "language": "Java" }, { "code": "var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\nfunction add(a, b) {\n return a + b;\n}\n\nvar summation = nums.reduce(add);\n\nfunction mul(a, b) {\n return a * b;\n}\n\nvar product = nums.reduce(mul, 1);\n\nvar concatenation = nums.reduce(add, \"\");\n\nconsole.log(summation, product, concatenation);\n", "language": "JavaScript" }, { "code": "(function (xs) {\n 'use strict';\n\n // foldl :: (b -> a -> b) -> b -> [a] -> b\n function foldl(f, acc, xs) {\n return xs.reduce(f, acc);\n }\n\n // foldr :: (b -> a -> b) -> b -> [a] -> b\n function foldr(f, acc, xs) {\n return xs.reduceRight(f, acc);\n }\n\n // Test folds in both directions\n return [foldl, foldr].map(function (f) {\n return f(function (acc, x) {\n return acc + (x * 2).toString() + ' ';\n }, [], xs);\n });\n\n})([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\n", "language": "JavaScript" }, { "code": "var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\nconsole.log(nums.reduce((a, b) => a + b, 0)); // sum of 1..10\nconsole.log(nums.reduce((a, b) => a * b, 1)); // product of 1..10\nconsole.log(nums.reduce((a, b) => a + b, '')); // concatenation of 1..10\n", "language": "JavaScript" }, { "code": "println([reduce(op, 1:5) for op in [+, -, *]])\nprintln([foldl(op, 1:5) for op in [+, -, *]])\nprintln([foldr(op, 1:5) for op in [+, -, *]])\n", "language": "Julia" }, { "code": "fun main(args: Array<String>) {\n val a = intArrayOf(1, 2, 3, 4, 5)\n println(\"Array : ${a.joinToString(\", \")}\")\n println(\"Sum : ${a.reduce { x, y -> x + y }}\")\n println(\"Difference : ${a.reduce { x, y -> x - y }}\")\n println(\"Product : ${a.reduce { x, y -> x * y }}\")\n println(\"Minimum : ${a.reduce { x, y -> if (x < y) x else y }}\")\n println(\"Maximum : ${a.reduce { x, y -> if (x > y) x else y }}\")\n}\n", "language": "Kotlin" }, { "code": "{def nums 1 2 3 4 5}\n-> nums\n{S.reduce {lambda {:a :b} {+ :a :b}} {nums}}\n-> 15\n{S.reduce {lambda {:a :b} {- :a :b}} {nums}}\n-> -13\n{S.reduce {lambda {:a :b} {* :a :b}} {nums}}\n-> 120\n{S.reduce min {nums}}\n-> 1\n{S.reduce max {nums}}\n-> 5\n", "language": "Lambdatalk" }, { "code": ":- object(folding_examples).\n\n :- public(show/0).\n show :-\n integer::sequence(1, 10, List),\n write('List: '), write(List), nl,\n meta::fold_left([Acc,N,Sum0]>>(Sum0 is Acc+N), 0, List, Sum),\n write('Sum of all elements: '), write(Sum), nl,\n meta::fold_left([Acc,N,Product0]>>(Product0 is Acc*N), 1, List, Product),\n write('Product of all elements: '), write(Product), nl,\n meta::fold_left([Acc,N,Concat0]>>(number_codes(N,NC), atom_codes(NA,NC), atom_concat(Acc,NA,Concat0)), '', List, Concat),\n write('Concatenation of all elements: '), write(Concat), nl.\n\n:- end_object.\n", "language": "Logtalk" }, { "code": "HAI 1.3\n\nHOW IZ I reducin YR array AN YR size AN YR fn\n I HAS A val ITZ array'Z SRS 0\n IM IN YR loop UPPIN YR i TIL BOTH SAEM i AN DIFF OF size AN 1\n val R I IZ fn YR val AN YR array'Z SRS SUM OF i AN 1 MKAY\n IM OUTTA YR loop\n FOUND YR val\nIF U SAY SO\n\nO HAI IM array\n I HAS A SRS 0 ITZ 1\n I HAS A SRS 1 ITZ 2\n I HAS A SRS 2 ITZ 3\n I HAS A SRS 3 ITZ 4\n I HAS A SRS 4 ITZ 5\nKTHX\n\nHOW IZ I add YR a AN YR b, FOUND YR SUM OF a AN b, IF U SAY SO\nHOW IZ I sub YR a AN YR b, FOUND YR DIFF OF a AN b, IF U SAY SO\nHOW IZ I mul YR a AN YR b, FOUND YR PRODUKT OF a AN b, IF U SAY SO\n\nVISIBLE I IZ reducin YR array AN YR 5 AN YR add MKAY\nVISIBLE I IZ reducin YR array AN YR 5 AN YR sub MKAY\nVISIBLE I IZ reducin YR array AN YR 5 AN YR mul MKAY\n\nKTHXBYE\n", "language": "LOLCODE" }, { "code": "table.unpack = table.unpack or unpack -- 5.1 compatibility\nlocal nums = {1,2,3,4,5,6,7,8,9}\n\nfunction add(a,b)\n return a+b\nend\n\nfunction mult(a,b)\n return a*b\nend\n\nfunction cat(a,b)\n return tostring(a)..tostring(b)\nend\n\nlocal function reduce(fun,a,b,...)\n if ... then\n return reduce(fun,fun(a,b),...)\n else\n return fun(a,b)\n end\nend\n\nlocal arithmetic_sum = function (...) return reduce(add,...) end\nlocal factorial5 = reduce(mult,5,4,3,2,1)\n\nprint(\"Σ(1..9) : \",arithmetic_sum(table.unpack(nums)))\nprint(\"5! : \",factorial5)\nprint(\"cat {1..9}: \",reduce(cat,table.unpack(nums)))\n", "language": "Lua" }, { "code": "Module CheckIt {\n Function Reduce (a, f) {\n if len(a)=0 then Error \"Nothing to reduce\"\n if len(a)=1 then =Array(a) : Exit\n k=each(a, 2, -1)\n m=Array(a)\n While k {\n m=f(m, array(k))\n }\n =m\n }\n a=(1, 2, 3, 4, 5)\n Print \"Array\", a\n Print \"Sum\", Reduce(a, lambda (x,y)->x+y)\n Print \"Difference\", Reduce(a, lambda (x,y)->x-y)\n Print \"Product\", Reduce(a, lambda (x,y)->x*y)\n Print \"Minimum\", Reduce(a, lambda (x,y)->if(x<y->x, y))\n Print \"Maximum\", Reduce(a, lambda (x,y)->if(x>y->x, y))\n}\nCheckIt\n", "language": "M2000-Interpreter" }, { "code": "> nums := seq( 1 .. 10 );\n nums := 1, 2, 3, 4, 5, 6, 7, 8, 9, 10\n\n> foldl( `+`, 0, nums ); # compute sum using foldl\n 55\n\n> foldr( `*`, 1, nums ); # compute product using foldr\n 3628800\n", "language": "Maple" }, { "code": "> foldl( (a,b) ->a*T+b, op(map2(op,1,[op( 72*T^5+37*T^4-23*T^3+87*T^2+44*T+29 )])));\n ((((72 T + 37) T - 23) T + 87) T + 44) T + 29\n", "language": "Maple" }, { "code": "Fold[f, x, {a, b, c, d}]\n", "language": "Mathematica" }, { "code": "lreduce(f, [a, b, c, d], x0);\n/* (%o1) f(f(f(f(x0, a), b), c), d) */\n", "language": "Maxima" }, { "code": "lreduce(\"+\", [1, 2, 3, 4], 100);\n/* (%o1) 110 */\n", "language": "Maxima" }, { "code": "(1 2 3 4) 0 '+ reduce puts! ; sum\n(1 2 3 4) 1 '* reduce puts! ; product\n", "language": "Min" }, { "code": "MODULE Catamorphism;\nFROM InOut IMPORT WriteString, WriteCard, WriteLn;\n\n(* Alas, there are no generic types. This function works for\n CARDINAL only - you would have to copy it and change the types\n to reduce functions of other types. *)\nTYPE Reduction = PROCEDURE (CARDINAL, CARDINAL): CARDINAL;\nPROCEDURE reduce(func: Reduction;\n arr: ARRAY OF CARDINAL;\n first: CARDINAL): CARDINAL;\n VAR i: CARDINAL;\nBEGIN\n FOR i := 0 TO HIGH(arr) DO\n first := func(first, arr[i]);\n END;\n RETURN first;\nEND reduce;\n\n(* Demonstration *)\nPROCEDURE add(a,b: CARDINAL): CARDINAL;\nBEGIN RETURN a+b; END add;\nPROCEDURE mul(a,b: CARDINAL): CARDINAL;\nBEGIN RETURN a*b; END mul;\n\nPROCEDURE Demonstration;\n VAR a: ARRAY [1..5] OF CARDINAL;\n i: CARDINAL;\nBEGIN\n FOR i := 1 TO 5 DO a[i] := i; END;\n\n WriteString(\"Sum of [1..5]: \");\n WriteCard(reduce(add, a, 0), 3);\n WriteLn;\n WriteString(\"Product of [1..5]: \");\n WriteCard(reduce(mul, a, 1), 3);\n WriteLn;\nEND Demonstration;\n\nBEGIN Demonstration;\nEND Catamorphism.\n", "language": "Modula-2" }, { "code": "def seq = [1, 4, 6, 3, 7];\ndef sum = seq.Fold(0, _ + _); // Fold takes an initial value and a function, here the + operator\n", "language": "Nemerle" }, { "code": "import sequtils\n\nblock:\n let\n numbers = @[5, 9, 11]\n addition = foldl(numbers, a + b)\n substraction = foldl(numbers, a - b)\n multiplication = foldl(numbers, a * b)\n words = @[\"nim\", \"is\", \"cool\"]\n concatenation = foldl(words, a & b)\n\nblock:\n let\n numbers = @[5, 9, 11]\n addition = foldr(numbers, a + b)\n substraction = foldr(numbers, a - b)\n multiplication = foldr(numbers, a * b)\n words = @[\"nim\", \"is\", \"cool\"]\n concatenation = foldr(words, a & b)\n", "language": "Nim" }, { "code": "MODULE Catamorphism;\nIMPORT\n Object,\n NPCT:Tools,\n NPCT:Args,\n IntStr,\n Out;\n\nTYPE\n BinaryFunc= PROCEDURE (x,y: LONGINT): LONGINT;\n\nVAR\n data: POINTER TO ARRAY OF LONGINT;\n i: LONGINT;\n\n PROCEDURE Sum(x,y: LONGINT): LONGINT;\n BEGIN\n RETURN x + y\n END Sum;\n\n PROCEDURE Sub(x,y: LONGINT): LONGINT;\n BEGIN\n RETURN x - y;\n END Sub;\n\n PROCEDURE Mul(x,y: LONGINT): LONGINT;\n BEGIN\n RETURN x * y;\n END Mul;\n\n PROCEDURE Reduce(x: ARRAY OF LONGINT; f: BinaryFunc): LONGINT;\n VAR\n i,res: LONGINT;\n BEGIN\n res := x[0];i := 1;\n WHILE (i < LEN(x)) DO;\n res := f(res,x[i]);\n INC(i)\n END;\n RETURN res\n END Reduce;\n\n PROCEDURE InitData(VAR x: ARRAY OF LONGINT);\n VAR\n i, j: LONGINT;\n res: IntStr.ConvResults;\n aux: Object.CharsLatin1;\n BEGIN\n i := 0;j := 1;\n WHILE (j <= LEN(x)) DO\n aux := Tools.AsString(Args.Get(j));\n IntStr.StrToInt(aux^,x[i],res);\n IF res # IntStr.strAllRight THEN\n Out.String(\"Incorrect format for data at index \");Out.LongInt(j,0);Out.Ln;\n HALT(1);\n END;\n INC(j);INC(i)\n END\n END InitData;\n\nBEGIN\n IF Args.Number() = 1 THEN\n Out.String(\"Invalid number of arguments. \");Out.Ln;\n HALT(0)\n ELSE\n NEW(data,Args.Number() - 1);\n InitData(data^);\n Out.LongInt(Reduce(data^,Sum),0);Out.Ln;\n Out.LongInt(Reduce(data^,Sub),0);Out.Ln;\n Out.LongInt(Reduce(data^,Mul),0);Out.Ln\n END\nEND Catamorphism.\n", "language": "Oberon" }, { "code": "use Collection;\n\nclass Reducer {\n function : Main(args : String[]) ~ Nil {\n values := IntVector->New([1, 2, 3, 4, 5]);\n values->Reduce(Add(Int, Int) ~ Int)->PrintLine();\n values->Reduce(Mul(Int, Int) ~ Int)->PrintLine();\n }\n\n function : Add(a : Int, b : Int) ~ Int {\n return a + b;\n }\n\n function : Mul(a : Int, b : Int) ~ Int {\n return a * b;\n }\n}\n", "language": "Objeck" }, { "code": "# let nums = [1;2;3;4;5;6;7;8;9;10];;\nval nums : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\n# let sum = List.fold_left (+) 0 nums;;\nval sum : int = 55\n# let product = List.fold_left ( * ) 1 nums;;\nval product : int = 3628800\n", "language": "OCaml" }, { "code": "[ 1, 2, 3, 4, 5 ] reduce(#max)\n[ \"abc\", \"def\", \"gfi\" ] reduce(#+)\n", "language": "Oforth" }, { "code": "reduce(f, v)={\n my(t=v[1]);\n for(i=2,#v,t=f(t,v[i]));\n t\n};\nreduce((a,b)->a+b, [1,2,3,4,5,6,7,8,9,10])\n", "language": "PARI-GP" }, { "code": "fold((a,b)->a+b, [1..10])\n", "language": "PARI-GP" }, { "code": "program reduceApp;\n\ntype\n// tmyArray = array of LongInt;\n tmyArray = array[-5..5] of LongInt;\n tmyFunc = function (a,b:LongInt):LongInt;\n\nfunction add(x,y:LongInt):LongInt;\nbegin\n add := x+y;\nend;\n\nfunction sub(k,l:LongInt):LongInt;\nbegin\n sub := k-l;\nend;\n\nfunction mul(r,t:LongInt):LongInt;\nbegin\n mul := r*t;\nend;\n\nfunction reduce(myFunc:tmyFunc;a:tmyArray):LongInt;\nvar\n i,res : LongInt;\nbegin\n res := a[low(a)];\n For i := low(a)+1 to high(a) do\n res := myFunc(res,a[i]);\n reduce := res;\nend;\n\nprocedure InitMyArray(var a:tmyArray);\nvar\n i: LongInt;\nbegin\n For i := low(a) to high(a) do\n begin\n //no a[i] = 0\n a[i] := i + ord(i=0);\n write(a[i],',');\n end;\n writeln(#8#32);\nend;\n\nvar\n ma : tmyArray;\nBEGIN\n InitMyArray(ma);\n writeln(reduce(@add,ma));\n writeln(reduce(@sub,ma));\n writeln(reduce(@mul,ma));\nEND.\n", "language": "Pascal" }, { "code": "use List::Util 'reduce';\n\n# note the use of the odd $a and $b globals\nprint +(reduce {$a + $b} 1 .. 10), \"\\n\";\n\n# first argument is really an anon function; you could also do this:\nsub func { $b & 1 ? \"$a $b\" : \"$b $a\" }\nprint +(reduce \\&func, 1 .. 10), \"\\n\"\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">b</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">sub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">b</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">b</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">reduce</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">rid</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">rid</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">reduce</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">add</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">reduce</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">sub</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">reduce</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mul</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">))</span>\n<!--\n", "language": "Phix" }, { "code": "include ..\\Utilitys.pmt\n\ndef add + enddef\ndef sub - enddef\ndef mul * enddef\n\ndef reduce >ps\n 1 get\n swap len 2 swap 2 tolist for\n get rot swap tps exec swap\n endfor\n ps> drop\n swap\nenddef\n\n\n( 1 2 3 4 5 )\ngetid add reduce ?\ngetid sub reduce ?\ngetid mul reduce ?\n", "language": "Phixmonti" }, { "code": "(de reduce (\"Fun\" \"Lst\")\n (let \"A\" (car \"Lst\")\n (for \"N\" (cdr \"Lst\")\n (setq \"A\" (\"Fun\" \"A\" \"N\")) )\n \"A\" ) )\n\n(println\n (reduce + (1 2 3 4 5))\n (reduce * (1 2 3 4 5)) )\n\n(bye)\n", "language": "PicoLisp" }, { "code": "1..5 | ForEach-Object -Begin {$result = 0} -Process {$result += $_} -End {$result}\n", "language": "PowerShell" }, { "code": ":- use_module(library(lambda)).\n\ncatamorphism :-\n\tnumlist(1,10,L),\n\tfoldl(\\XS^YS^ZS^(ZS is XS+YS), L, 0, Sum),\n\tformat('Sum of ~w is ~w~n', [L, Sum]),\n\tfoldl(\\XP^YP^ZP^(ZP is XP*YP), L, 1, Prod),\n\tformat('Prod of ~w is ~w~n', [L, Prod]),\n\tstring_to_list(LV, \"\"),\n\tfoldl(\\XC^YC^ZC^(string_to_atom(XS, XC),string_concat(YC,XS,ZC)),\n\t L, LV, Concat),\n\tformat('Concat of ~w is ~w~n', [L, Concat]).\n", "language": "Prolog" }, { "code": "% List to be folded:\n%\n% +---+---+---+---[] <-- list backbone/spine, composed of nodes, terminating in the empty list\n% | | | |\n% a b c d <-- list items/entries/elements/members\n%\n", "language": "Prolog" }, { "code": "% Computes \"Out\" as:\n%\n% starter value -->--f-->--f-->--f-->--f-->-- Out\n% | | | |\n% a b c d\n\n\nfoldl(Foldy,[Item|Items],Acc,Result) :- % case of nonempty list\n !, % GREEN CUT for determinism\n call(Foldy,Item,Acc,AccNext), % call Foldy(Item,Acc,AccNext)\n foldl(Foldy,Items,AccNext,Result). % then recurse (open to tail call optimization)\n\nfoldl(_,[],Acc,Result) :- % case of empty list\n Acc=Result. % unification not in head for clarity\n", "language": "Prolog" }, { "code": "% Computes \"Out\" as:\n%\n% Out --<--f--<--f--<--f--<--f--<-- starter value\n% | | | |\n% a b c d\n\nfoldr(Foldy,[Item|Items],Starter,AccUp) :- % case of nonempty list\n !, % GREEN CUT for determinism\n foldr(Foldy,Items,Starter,AccUpPrev), % recurse (NOT open to tail-call optimization)\n call(Foldy,Item,AccUpPrev,AccUp). % call Foldy(Item,AccupPrev,AccUp) as last action\n\nfoldr(_,[],Starter,AccUp) :- % empty list: bounce Starter \"upwards\" into AccUp\n AccUp=Starter. % unification not in head for clarity\n", "language": "Prolog" }, { "code": ":- use_module(library(clpfd)). % We are using #= instead of the raw \"is\".\n\nfoldy_len(_Item,ThreadIn,ThreadOut) :-\n succ(ThreadIn,ThreadOut).\n\nfoldy_add(Item,ThreadIn,ThreadOut) :-\n ThreadOut #= Item+ThreadIn.\n\nfoldy_mult(Item,ThreadIn,ThreadOut) :-\n ThreadOut #= Item*ThreadIn.\n\nfoldy_squadd(Item,ThreadIn,ThreadOut) :-\n ThreadOut #= Item+(ThreadIn^2).\n\n% '[|]' is SWI-Prolog specific, replace by '.' as consbox constructor in other Prologs\n\nfoldy_build(Item,ThreadIn,ThreadOut) :-\n ThreadOut = '[|]'(Item,ThreadIn).\n\nfoldy_join(Item,ThreadIn,ThreadOut) :-\n (ThreadIn \\= \"\")\n -> with_output_to(string(ThreadOut),format(\"~w,~w\",[Item,ThreadIn]))\n ; with_output_to(string(ThreadOut),format(\"~w\",[Item])).\n\n% '=..' (\"univ\") constructs a term from a list of functor and arguments\n\nfoldy_expr(Functor,Item,ThreadIn,ThreadOut) :-\n ThreadOut =.. [Functor,Item,ThreadIn].\n", "language": "Prolog" }, { "code": ":- begin_tests(foldr).\n\nin([1,2,3,4,5]).\n\nffr(Foldy,List,Starter,AccUp) :- foldr(Foldy,List,Starter,AccUp).\n\ntest(foo_foldr_len) :- in(L),ffr(foldy_len , L , 0 , R), R=5.\ntest(foo_foldr_add) :- in(L),ffr(foldy_add , L , 0 , R), R=15.\ntest(foo_foldr_mult) :- in(L),ffr(foldy_mult , L , 1 , R), R=120.\ntest(foo_foldr_build) :- in(L),ffr(foldy_build , L , [] , R), R=[1,2,3,4,5].\ntest(foo_foldr_squadd) :- in(L),ffr(foldy_squadd , L , 0 , R), R=507425426245.\ntest(foo_foldr_join) :- in(L),ffr(foldy_join , L , \"\" , R), R=\"1,2,3,4,5\".\ntest(foo_foldr_expr) :- in(L),ffr(foldy_expr(*) , L , 1 , R), R=1*(2*(3*(4*(5*1)))).\n\ntest(foo_foldr_len_empty) :- ffr(foldy_len , [], 0 , R), R=0.\ntest(foo_foldr_add_empty) :- ffr(foldy_add , [], 0 , R), R=0.\ntest(foo_foldr_mult_empty) :- ffr(foldy_mult , [], 1 , R), R=1.\ntest(foo_foldr_build_empty) :- ffr(foldy_build , [], [] , R), R=[].\ntest(foo_foldr_squadd_empty) :- ffr(foldy_squadd , [], 0 , R), R=0.\ntest(foo_foldr_join_empty) :- ffr(foldy_join , [], \"\" , R), R=\"\".\ntest(foo_foldr_expr_empty) :- ffr(foldy_expr(*) , [], 1 , R), R=1.\n\n% library(apply) has no \"foldr\" so no comparison tests!\n\n:- end_tests(foldr).\n\n\n:- begin_tests(foldl).\n\nin([1,2,3,4,5]).\n\nffl(Foldy,List,Starter,Result) :- foldl(Foldy,List,Starter,Result).\n\ntest(foo_foldl_len) :- in(L),ffl(foldy_len , L , 0 , R), R=5.\ntest(foo_foldl_add) :- in(L),ffl(foldy_add , L, 0 , R), R=15.\ntest(foo_foldl_mult) :- in(L),ffl(foldy_mult , L, 1 , R), R=120.\ntest(foo_foldl_build) :- in(L),ffl(foldy_build , L, [] , R), R=[5,4,3,2,1].\ntest(foo_foldl_squadd) :- in(L),ffl(foldy_squadd , L, 0 , R), R=21909.\ntest(foo_foldl_join) :- in(L),ffl(foldy_join , L, \"\" , R), R=\"5,4,3,2,1\".\ntest(foo_foldl_expr) :- in(L),ffl(foldy_expr(*) , L, 1 , R), R=5*(4*(3*(2*(1*1)))).\n\ntest(foo_foldl_len_empty) :- ffl(foldy_len , [], 0 , R), R=0.\ntest(foo_foldl_add_empty) :- ffl(foldy_add , [], 0 , R), R=0.\ntest(foo_foldl_mult_empty) :- ffl(foldy_mult , [], 1 , R), R=1.\ntest(foo_foldl_build_empty) :- ffl(foldy_build , [], [] , R), R=[].\ntest(foo_foldl_squadd_empty) :- ffl(foldy_squadd , [], 0 , R), R=0.\ntest(foo_foldl_join_empty) :- ffl(foldy_join , [], \"\" , R), R=\"\".\ntest(foo_foldl_expr_empty) :- ffl(foldy_expr(*) , [], 1 , R), R=1.\n\n:- end_tests(foldl).\n\nrt :- run_tests(foldr),run_tests(foldl).\n", "language": "Prolog" }, { "code": "Procedure.i reduce(List l(),op$=\"+\")\n If FirstElement(l())\n x=l()\n While NextElement(l())\n Select op$\n Case \"+\" : x+l()\n Case \"-\" : x-l()\n Case \"*\" : x*l()\n EndSelect\n Wend\n EndIf\n ProcedureReturn x\nEndProcedure\n\nNewList fold()\nFor i=1 To 5 : AddElement(fold()) : fold()=i : Next\n\nDebug reduce(fold())\nDebug reduce(fold(),\"-\")\nDebug reduce(fold(),\"*\")\n", "language": "PureBasic" }, { "code": ">>> # Python 2.X\n>>> from operator import add\n>>> listoflists = [['the', 'cat'], ['sat', 'on'], ['the', 'mat']]\n>>> help(reduce)\nHelp on built-in function reduce in module __builtin__:\n\nreduce(...)\n reduce(function, sequence[, initial]) -> value\n\n Apply a function of two arguments cumulatively to the items of a sequence,\n from left to right, so as to reduce the sequence to a single value.\n For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n of the sequence in the calculation, and serves as a default when the\n sequence is empty.\n\n>>> reduce(add, listoflists, [])\n['the', 'cat', 'sat', 'on', 'the', 'mat']\n>>>\n", "language": "Python" }, { "code": "# Python 3.X\n\nfrom functools import reduce\nfrom operator import add, mul\n\nnums = range(1,11)\n\nsummation = reduce(add, nums)\n\nproduct = reduce(mul, nums)\n\nconcatenation = reduce(lambda a, b: str(a) + str(b), nums)\n\nprint(summation, product, concatenation)\n", "language": "Python" }, { "code": "DIM SHARED n(10)\nFOR i = 1 TO 10: n(i) = i: NEXT i\n\nFUNCTION FNMIN (a, b)\nIF (a < b) THEN FNMIN = a ELSE FNMIN = b\nEND FUNCTION\nFUNCTION FNMAX (a, b)\nIF (a < b) THEN FNMAX = b ELSE FNMAX = a\nEND FUNCTION\n\nFUNCTION cat# (cont, op$)\ntemp = n(1)\nFOR i = 2 TO cont\n IF op$ = \"+\" THEN temp = temp + n(i)\n IF op$ = \"-\" THEN temp = temp - n(i)\n IF op$ = \"*\" THEN temp = temp * n(i)\n IF op$ = \"/\" THEN temp = temp / n(i)\n IF op$ = \"^\" THEN temp = temp ^ n(i)\n IF op$ = \"max\" THEN temp = FNMAX(temp, n(i))\n IF op$ = \"min\" THEN temp = FNMIN(temp, n(i))\n IF op$ = \"avg\" THEN temp = temp + n(i)\nNEXT i\nIF op$ = \"avg\" THEN temp = temp / cont\ncat = temp\nEND FUNCTION\n\nPRINT \" +: \"; \" \"; cat(10, \"+\")\nPRINT \" -: \"; \" \"; cat(10, \"-\")\nPRINT \" *: \"; \" \"; cat(10, \"*\")\nPRINT \" /: \"; \" \"; cat(10, \"/\")\nPRINT \" ^: \"; \" \"; cat(10, \"^\")\nPRINT \"min: \"; \" \"; cat(10, \"min\")\nPRINT \"max: \"; \" \"; cat(10, \"max\")\nPRINT \"avg: \"; \" \"; cat(10, \"avg\")\n", "language": "QBasic" }, { "code": "/O> 0 ' [ 1 2 3 4 5 ] witheach +\n... 1 ' [ 1 2 3 4 5 ] witheach *\n...\n\nStack: 15 120\n", "language": "Quackery" }, { "code": "Reduce('+', c(2,30,400,5000))\n5432\n", "language": "R" }, { "code": "Reduce(function(a,b){c(a,0,b)}, c(2,3,4,5))\n2 0 3 0 4 0 5\n", "language": "R" }, { "code": "Reduce(paste0, unlist(strsplit(\"freedom\", NULL)), accum=T)\n\"f\" \"fr\" \"fre\" \"free\" \"freed\" \"freedo\" \"freedom\"\n", "language": "R" }, { "code": "Reduce(function(x,acc){if (0==x%%3) c(x*x,acc) else acc}, 0:22,\n init=c(), right=T)\n 0 9 36 81 144 225 324 441\n", "language": "R" }, { "code": "#lang racket\n(define (fold f xs init)\n (if (empty? xs)\n init\n (f (first xs)\n (fold f (rest xs) init))))\n\n(fold + '(1 2 3) 0) ; the result is 6\n", "language": "Racket" }, { "code": "my @list = 1..10;\nsay [+] @list;\nsay [*] @list;\nsay [~] @list;\nsay min @list;\nsay max @list;\nsay [lcm] @list;\n", "language": "Raku" }, { "code": "my @list = 1..10;\nsay reduce &infix:<+>, @list;\nsay reduce &infix:<*>, @list;\nsay reduce &infix:<~>, @list;\nsay reduce &infix:<min>, @list;\nsay reduce &infix:<max>, @list;\nsay reduce &infix:<lcm>, @list;\n", "language": "Raku" }, { "code": "$ENTRY Go {\n , 1 2 3 4 5 6 7: e.List\n = <Prout <Reduce Add e.List>>\n <Prout <Reduce Mul e.List>>;\n};\n\nReduce {\n s.F t.I = t.I;\n s.F t.I t.J e.X = <Reduce s.F <Mu s.F t.I t.J> e.X>;\n};\n", "language": "Refal" }, { "code": "/*REXX program demonstrates a method for catamorphism for some simple functions. */\n@list= 1 2 3 4 5 6 7 8 9 10\n say 'list:' fold(@list, \"list\")\n say ' sum:' fold(@list, \"+\" )\n say 'prod:' fold(@list, \"*\" )\n say ' cat:' fold(@list, \"||\" )\n say ' min:' fold(@list, \"min\" )\n say ' max:' fold(@list, \"max\" )\n say ' avg:' fold(@list, \"avg\" )\n say ' GCD:' fold(@list, \"GCD\" )\n say ' LCM:' fold(@list, \"LCM\" )\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nfold: procedure; parse arg z; arg ,f; z = space(z); BIFs= 'MIN MAX LCM GCD'\n za= translate(z, f, ' '); zf= f\"(\"translate(z, ',' , \" \")')'\n if f== '+' | f==\"*\" then interpret \"return\" za\n if f== '||' then return space(z, 0)\n if f== 'AVG' then interpret \"return\" fold(z, '+') \"/\" words(z)\n if wordpos(f, BIFs)\\==0 then interpret \"return\" zf\n if f=='LIST' | f==\"SHOW\" then return z\n return 'illegal function:' arg(2)\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nGCD: procedure; $=; do j=1 for arg(); $= $ arg(j)\n end /*j*/\n parse var $ x z .; if x=0 then x= z /* [↑] build an arg list.*/\n x= abs(x)\n do k=2 to words($); y= abs( word($, k)); if y=0 then iterate\n do until _=0; _= x // y; x= y; y= _\n end /*until*/\n end /*k*/\n return x\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nLCM: procedure; $=; do j=1 for arg(); $= $ arg(j)\n end /*j*/\n x= abs(word($, 1)) /* [↑] build an arg list.*/\n do k=2 to words($); != abs(word($, k)); if !=0 then return 0\n x= x*! / GCD(x, !) /*GCD does the heavy work*/\n end /*k*/\n return x\n", "language": "REXX" }, { "code": "n = list(10)\nfor i = 1 to 10\n n[i] = i\nnext\n\nsee \" +: \" + cat(10,\"+\") + nl+\n \" -: \" + cat(10,\"-\") + nl +\n \" *: \" + cat(10,\"*\") + nl +\n \" /: \" + cat(10,\"/\") + nl+\n \" ^: \" + cat(10,\"^\") + nl +\n \"min: \" + cat(10,\"min\") + nl+\n \"max: \" + cat(10,\"max\") + nl+\n \"avg: \" + cat(10,\"avg\") + nl +\n \"cat: \" + cat(10,\"cat\") + nl\n\nfunc cat count,op\n cat = n[1]\n cat2 = \"\"\n for i = 2 to count\n switch op\n on \"+\" cat += n[i]\n on \"-\" cat -= n[i]\n on \"*\" cat *= n[i]\n on \"/\" cat /= n[i]\n on \"^\" cat ^= n[i]\n on \"max\" cat = max(cat,n[i])\n on \"min\" cat = min(cat,n[i])\n on \"avg\" cat += n[i]\n on \"cat\" cat2 += string(n[i])\n off\n next\nif op = \"avg\" cat = cat / count ok\nif op = \"cat\" decimals(0) cat = string(n[1])+cat2 ok\nreturn cat\n", "language": "Ring" }, { "code": "# sum:\np (1..10).inject(:+)\n# smallest number divisible by all numbers from 1 to 20:\np (1..20).inject(:lcm) #lcm: lowest common multiple\n", "language": "Ruby" }, { "code": "p row = [1]\n10.times{p row = row.each_cons(2).inject([1,1]){|ar,(a,b)| ar.insert(-2, a+b)} }\n\n# [1]\n# [1, 1]\n# [1, 2, 1]\n# [1, 3, 3, 1]\n# [1, 4, 6, 4, 1]\n# [1, 5, 10, 10, 5, 1]\n# [1, 6, 15, 20, 15, 6, 1]\n# etc\n", "language": "Ruby" }, { "code": "for i = 1 to 10 :n(i) = i:next i\n\nprint \" +: \";\" \";cat(10,\"+\")\nprint \" -: \";\" \";cat(10,\"-\")\nprint \" *: \";\" \";cat(10,\"*\")\nprint \" /: \";\" \";cat(10,\"/\")\nprint \" ^: \";\" \";cat(10,\"^\")\nprint \"min: \";\" \";cat(10,\"min\")\nprint \"max: \";\" \";cat(10,\"max\")\nprint \"avg: \";\" \";cat(10,\"avg\")\nprint \"cat: \";\" \";cat(10,\"cat\")\n\nfunction cat(count,op$)\ncat = n(1)\nfor i = 2 to count\n if op$ = \"+\" \tthen cat = cat + n(i)\n if op$ = \"-\" \tthen cat = cat - n(i)\n if op$ = \"*\" \tthen cat = cat * n(i)\n if op$ = \"/\" \tthen cat = cat / n(i)\n if op$ = \"^\" \tthen cat = cat ^ n(i)\n if op$ = \"max\"\tthen cat = max(cat,n(i))\n if op$ = \"min\"\tthen cat = min(cat,n(i))\n if op$ = \"avg\"\tthen cat = cat + n(i)\n if op$ = \"cat\"\tthen cat$ = cat$ + str$(n(i))\nnext i\nif op$ = \"avg\" then cat = cat / count\nif op$ = \"cat\" then cat = val(str$(n(1))+cat$)\nend function\n", "language": "Run-BASIC" }, { "code": "fn main() {\n println!(\"Sum: {}\", (1..10).fold(0, |acc, n| acc + n));\n println!(\"Product: {}\", (1..10).fold(1, |acc, n| acc * n));\n let chars = ['a', 'b', 'c', 'd', 'e'];\n println!(\"Concatenation: {}\",\n chars.iter().map(|&c| (c as u8 + 1) as char).collect::<String>());\n}\n", "language": "Rust" }, { "code": "object Main extends App {\n val a = Seq(1, 2, 3, 4, 5)\n println(s\"Array : ${a.mkString(\", \")}\")\n println(s\"Sum : ${a.sum}\")\n println(s\"Difference : ${a.reduce { (x, y) => x - y }}\")\n println(s\"Product : ${a.product}\")\n println(s\"Minimum : ${a.min}\")\n println(s\"Maximum : ${a.max}\")\n}\n", "language": "Scala" }, { "code": "(define (reduce fn init lst)\n (do ((val init (fn (car rem) val)) ; accumulated value passed as second argument\n (rem lst (cdr rem)))\n ((null? rem) val)))\n\n(display (reduce + 0 '(1 2 3 4 5))) (newline) ; => 15\n(display (reduce expt 2 '(3 4))) (newline) ; => 262144\n", "language": "Scheme" }, { "code": "say (1..10 -> reduce('+'));\nsay (1..10 -> reduce{|a,b| a + b});\n", "language": "Sidef" }, { "code": "- val nums = [1,2,3,4,5,6,7,8,9,10];\nval nums = [1,2,3,4,5,6,7,8,9,10] : int list\n- val sum = foldl op+ 0 nums;\nval sum = 55 : int\n- val product = foldl op* 1 nums;\nval product = 3628800 : int\n", "language": "Standard-ML" }, { "code": "let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nprint(nums.reduce(0, +))\nprint(nums.reduce(1, *))\nprint(nums.reduce(\"\", { $0 + String($1) }))\n", "language": "Swift" }, { "code": "[1..5] -> \\(@: $(1); $(2..last)... -> @: $@ + $; $@!\\) -> '$;\n' -> !OUT::write\n[1..5] -> \\(@: $(1); $(2..last)... -> @: $@ - $; $@!\\) -> '$;\n' -> !OUT::write\n[1..5] -> \\(@: $(1); $(2..last)... -> @: $@ * $; $@!\\) -> '$;\n' -> !OUT::write\n", "language": "Tailspin" }, { "code": "templates fold&{op:}\n @: $(1);\n $(2..last)... -> @: [$@, $] -> op;\n $@ !\nend fold\n\ntemplates add\n $(1) + $(2) !\nend add\n\ntemplates mul\n $(1) * $(2) !\nend mul\n\n[1..5] -> fold&{op:add} -> '$;\n' -> !OUT::write\n\n[1..5] -> fold&{op:mul} -> '$;\n' -> !OUT::write\n", "language": "Tailspin" }, { "code": "proc fold {lambda zero list} {\n set accumulator $zero\n foreach item $list {\n\tset accumulator [apply $lambda $accumulator $item]\n }\n return $accumulator\n}\n", "language": "Tcl" }, { "code": "set 1to5 {1 2 3 4 5}\n\nputs [fold {{a b} {expr {$a+$b}}} 0 $1to5]\nputs [fold {{a b} {expr {$a*$b}}} 1 $1to5]\nputs [fold {{a b} {return $a,$b}} x $1to5]\n", "language": "Tcl" }, { "code": "puts [::tcl::mathop::+ {*}$1to5]\nputs [::tcl::mathop::* {*}$1to5]\nputs x,[join $1to5 ,]\n", "language": "Tcl" }, { "code": "SHARE n(10)\nFOR i = 1 to 10\n LET n(i) = i\nNEXT i\n\nFUNCTION fnmin(a,b)\n IF (a < b) then LET fnmin = a else LET fnmin = b\nEND FUNCTION\nFUNCTION fnmax(a,b)\n IF (a < b) then LET fnmax = b else LET fnmax = a\nEND FUNCTION\n\nFUNCTION cat(cont, op$)\n LET temp = n(1)\n LET temp$ = \"\"\n FOR i = 2 TO cont\n IF op$ = \"+\" then LET temp = temp+n(i)\n IF op$ = \"-\" then LET temp = temp-n(i)\n IF op$ = \"*\" then LET temp = temp*n(i)\n IF op$ = \"/\" then LET temp = temp/n(i)\n IF op$ = \"^\" then LET temp = temp^n(i)\n IF op$ = \"max\" then LET temp = fnmax(temp,n(i))\n IF op$ = \"min\" then LET temp = fnmin(temp,n(i))\n IF op$ = \"avg\" then LET temp = temp+n(i)\n IF op$ = \"cat\" then LET temp$ = temp$ & str$(n(i))\n NEXT i\n IF op$ = \"avg\" then\n LET temp = temp / cont\n END IF\n IF op$ = \"cat\" then\n LET t$ = str$(n(1)) & temp$\n LET temp = VAL(t$)\n END IF\n LET cat = temp\nEND FUNCTION\n\nPRINT \" +: \"; \" \"; cat(10, \"+\")\nPRINT \" -: \"; \" \"; cat(10, \"-\")\nPRINT \" *: \"; \" \"; cat(10, \"*\")\nPRINT \" /: \"; \" \"; cat(10, \"/\")\nPRINT \" ^: \"; \" \"; cat(10, \"^\")\nPRINT \"min: \"; \" \"; cat(10, \"min\")\nPRINT \"max: \"; \" \"; cat(10, \"max\")\nPRINT \"avg: \"; \" \"; cat(10, \"avg\")\nPRINT \"cat: \"; \" \"; cat(10, \"cat\")\nEND\n", "language": "True-BASIC" }, { "code": "fn main() {\n\tn := [1, 2, 3, 4, 5]\n\n\tprintln(reduce(add, n))\n\tprintln(reduce(sub, n))\n\tprintln(reduce(mul, n))\n}\n\nfn add(a int, b int) int { return a + b }\nfn sub(a int, b int) int { return a - b }\nfn mul(a int, b int) int { return a * b }\n\nfn reduce(rf fn(int, int) int, m []int) int {\n\tmut r := m[0]\n\tfor v in m[1..] {\n\t\tr = rf(r, v)\n\t}\n\treturn r\n}\n", "language": "V-(Vlang)" }, { "code": "Public Sub reduce()\n s = [{1,2,3,4,5}]\n Debug.Print WorksheetFunction.Sum(s)\n Debug.Print WorksheetFunction.Product(s)\nEnd Sub\n", "language": "VBA" }, { "code": "let a => import 'arrays';\nlet s => import 'stream';\nlet str => import 'strings';\n\n# Sum of [1, 10]:\nlet nums => [1; 2; 3; 4; 5; 6; 7; 8; 9; 10];\na.stream nums -> s.reduce 0 + -- io.writeln io.stdout;\n\n# As an alternative to an array, a range stream can be used. Here's the product of [1, 11):\ns.range 1 11 -> s.reduce 1 * -- io.writeln io.stdout;\n\n# And here's a concatenation:\ns.range 1 11 -> s.reduce '' (str.format '{}{}') -- io.writeln io.stdout;\n", "language": "WDTE" }, { "code": "!/ ^+ [1 2 3] ; returns 6\n", "language": "Wortel" }, { "code": "@fold ^+ 1 [1 2 3] ; returns 7\n", "language": "Wortel" }, { "code": "var a = [1, 2, 3, 4, 5]\nvar sum = a.reduce { |acc, i| acc + i }\nvar prod = a.reduce { |acc, i| acc * i }\nvar sumSq = a.reduce { |acc, i| acc + i*i }\nSystem.print(a)\nSystem.print(\"Sum is %(sum)\")\nSystem.print(\"Product is %(prod)\")\nSystem.print(\"Sum of squares is %(sumSq)\")\n", "language": "Wren" }, { "code": "dim n(10)\nfor i = 1 to 10 : n(i) = i : next i\n\nprint \" +: \", \" \", cat(10, \"+\")\nprint \" -: \", \" \", cat(10, \"-\")\nprint \" *: \", \" \", cat(10, \"*\")\nprint \" /: \", \" \", cat(10, \"/\")\nprint \" ^: \", \" \", cat(10, \"^\")\nprint \"min: \", \" \", cat(10, \"min\")\nprint \"max: \", \" \", cat(10, \"max\")\nprint \"avg: \", \" \", cat(10, \"avg\")\nend\n\nsub cat(cont,op$)\ncat = n(1)\nfor i = 2 to cont\n if op$ = \"+\" cat = cat + n(i)\n if op$ = \"-\" cat = cat - n(i)\n if op$ = \"*\" cat = cat * n(i)\n if op$ = \"/\" cat = cat / n(i)\n if op$ = \"^\" cat = cat ^ n(i)\n if op$ = \"max\" cat = max(cat,n(i))\n if op$ = \"min\" cat = min(cat,n(i))\n if op$ = \"avg\" cat = cat + n(i)\nnext i\nif op$ = \"avg\" cat = cat / cont\nreturn cat\nend sub\n", "language": "Yabasic" }, { "code": "/// Asserts that `array`.len >= 1.\npub fn reduce(comptime T: type, comptime applyFn: fn (T, T) T, array: []const T) T {\n var val: T = array[0];\n for (array[1..]) |elem| {\n val = applyFn(val, elem);\n }\n return val;\n}\n", "language": "Zig" }, { "code": "const std = @import(\"std\");\n\nfn add(a: i32, b: i32) i32 {\n return a + b;\n}\n\nfn mul(a: i32, b: i32) i32 {\n return a * b;\n}\n\nfn min(a: i32, b: i32) i32 {\n return @min(a, b);\n}\n\nfn max(a: i32, b: i32) i32 {\n return @max(a, b);\n}\n\npub fn main() void {\n const arr: [5]i32 = .{ 1, 2, 3, 4, 5 };\n std.debug.print(\"Array: {any}\\n\", .{arr});\n std.debug.print(\" * Reduce with add: {d}\\n\", .{reduce(i32, add, &arr)});\n std.debug.print(\" * Reduce with mul: {d}\\n\", .{reduce(i32, mul, &arr)});\n std.debug.print(\" * Reduce with min: {d}\\n\", .{reduce(i32, min, &arr)});\n std.debug.print(\" * Reduce with max: {d}\\n\", .{reduce(i32, max, &arr)});\n}\n", "language": "Zig" }, { "code": "const std = @import(\"std\");\n\npub fn main() void {\n const vec: @Vector(5, i32) = .{ 1, 2, 3, 4, 5 };\n std.debug.print(\"Vec: {any}\\n\", .{vec});\n std.debug.print(\" * Reduce with add: {d}\\n\", .{@reduce(.Add, vec)});\n std.debug.print(\" * Reduce with mul: {d}\\n\", .{@reduce(.Mul, vec)});\n std.debug.print(\" * Reduce with min: {d}\\n\", .{@reduce(.Min, vec)});\n std.debug.print(\" * Reduce with max: {d}\\n\", .{@reduce(.Max, vec)});\n}\n", "language": "Zig" }, { "code": "const std = @import(\"std\");\n\npub fn main() void {\n const vec: @Vector(2, i32) = .{ std.math.minInt(i32), std.math.minInt(i32) + 1 };\n std.debug.print(\"Vec: {any}\\n\", .{vec});\n std.debug.print(\" * Reduce with .Add: {d}\\n\", .{@reduce(.Add, vec)});\n std.debug.print(\" * Reduce with .Mul: {d}\\n\", .{@reduce(.Mul, vec)});\n\n var zero: usize = 0; // Small trick to make compiler not emit compile error for overflow below:\n std.debug.print(\" * Reduce with regular add operator: {d}\\n\", .{vec[zero] + vec[1]});\n std.debug.print(\" * Reduce with regular mul operator: {d}\\n\", .{vec[zero] * vec[1]});\n}\n", "language": "Zig" }, { "code": "T(\"foo\",\"bar\").reduce(fcn(p,n){p+n}) //--> \"foobar\"\n\"123four5\".reduce(fcn(p,c){p+(c.matches(\"[0-9]\") and c or 0)}, 0) //-->11\nFile(\"foo.zkl\").reduce('+(1).fpM(\"0-\"),0) //->5 (lines in file)\n", "language": "Zkl" }, { "code": "10 DIM a(5)\n20 FOR i=1 TO 5\n30 READ a(i)\n40 NEXT i\n50 DATA 1,2,3,4,5\n60 LET o$=\"+\": GO SUB 1000: PRINT tmp\n70 LET o$=\"-\": GO SUB 1000: PRINT tmp\n80 LET o$=\"*\": GO SUB 1000: PRINT tmp\n90 STOP\n1000 REM Reduce\n1010 LET tmp=a(1)\n1020 FOR i=2 TO 5\n1030 LET tmp=VAL (\"tmp\"+o$+\"a(i)\")\n1040 NEXT i\n1050 RETURN\n", "language": "ZX-Spectrum-Basic" } ]
Catamorphism
[ { "code": "---\ncategory:\n- Graphics algorithms\n- Geometry\nfrom: http://rosettacode.org/wiki/Catmull–Clark_subdivision_surface\nnote: 3D\nrequires:\n- Graphics\n", "language": "00-META" }, { "code": "Implement the Catmull-Clark surface subdivision ([[wp:Catmull–Clark_subdivision_surface|description on Wikipedia]]), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals.\n\nThe process for computing the new locations of the points works as follows when the surface is free of holes:\n[[Image:CatmullClark_subdiv_0.png|thumb|Starting cubic mesh; the meshes below are derived from this.]]\n[[Image:CatmullClark_subdiv_1.png|thumb|After one round of the Catmull-Clark algorithm applied to a cubic mesh.]]\n[[Image:CatmullClark_subdiv_2.png|thumb|After two rounds of the Catmull-Clark algorithm. As can be seen, this is converging to a surface that looks nearly spherical.]]\n# for each face, a ''face point'' is created which is the average of all the points of the face.\n# for each edge, an ''edge point'' is created which is the average between the center of the edge and the center of the segment made with the face points of the two adjacent faces.\n# for each vertex point, its coordinates are updated from (<tt>new_coords</tt>):\n## the old coordinates (<tt>old_coords</tt>),\n## the average of the face points of the faces the point belongs to (<tt>avg_face_points</tt>),\n## the average of the centers of edges the point belongs to (<tt>avg_mid_edges</tt>),\n## how many faces a point belongs to (<tt>n</tt>), then use this formula:\n m<sub>1</sub> = (n - 3) / n\n m<sub>2</sub> = 1 / n\n m<sub>3</sub> = 2 / n\n new_coords = (m<sub>1</sub> * old_coords)\n + (m<sub>2</sub> * avg_face_points)\n + (m<sub>3</sub> * avg_mid_edges)\n\nThen each face is replaced by new faces made with the new points,\n* for a triangle face (a,b,c):\n (a, edge_point<sub>ab</sub>, face_point<sub>abc</sub>, edge_point<sub>ca</sub>)\n (b, edge_point<sub>bc</sub>, face_point<sub>abc</sub>, edge_point<sub>ab</sub>)\n (c, edge_point<sub>ca</sub>, face_point<sub>abc</sub>, edge_point<sub>bc</sub>)\n* for a quad face (a,b,c,d):\n (a, edge_point<sub>ab</sub>, face_point<sub>abcd</sub>, edge_point<sub>da</sub>)\n (b, edge_point<sub>bc</sub>, face_point<sub>abcd</sub>, edge_point<sub>ab</sub>)\n (c, edge_point<sub>cd</sub>, face_point<sub>abcd</sub>, edge_point<sub>bc</sub>)\n (d, edge_point<sub>da</sub>, face_point<sub>abcd</sub>, edge_point<sub>cd</sub>)\n\nWhen there is a hole, we can detect it as follows:\n* an edge is the border of a hole if it belongs to only one face,\n* a point is on the border of a hole if <tt>n<sub>faces</sub> != n<sub>edges</sub></tt> with <tt>n<sub>faces</sub></tt> the number of faces the point belongs to, and <tt>n<sub>edges</sub></tt> the number of edges a point belongs to.\n\nOn the border of a hole the subdivision occurs as follows:\n# for the edges that are on the border of a hole, the edge point is just the middle of the edge.\n# for the vertex points that are on the border of a hole, the new coordinates are calculated as follows:\n## in all the edges the point belongs to, only take in account the middles of the edges that are on the border of the hole\n## calculate the average between these points (on the hole boundary) and the old coordinates (also on the hole boundary).\n\nFor edges and vertices not next to a hole, the standard algorithm from above is used.\n", "language": "00-TASK" }, { "code": "vertex face_point(face f)\n{\n\tint i;\n\tvertex v;\n\n\tif (!f->avg) {\n\t\tf->avg = vertex_new();\n\t\tforeach(i, v, f->v)\n\t\t\tif (!i) f->avg->pos = v->pos;\n\t\t\telse vadd(f->avg->pos, v->pos);\n\n\t\tvdiv(f->avg->pos, len(f->v));\n\t}\n\treturn f->avg;\n}\n\n#define hole_edge(e) (len(e->f)==1)\nvertex edge_point(edge e)\n{\n\tint i;\n\tface f;\n\n\tif (!e->e_pt) {\n\t\te->e_pt = vertex_new();\n\t\te->avg = e->v[0]->pos;\n\t\tvadd(e->avg, e->v[1]->pos);\n\t\te->e_pt->pos = e->avg;\n\n\t\tif (!hole_edge(e)) {\n\t\t\tforeach (i, f, e->f)\n\t\t\t\tvadd(e->e_pt->pos, face_point(f)->pos);\n\t\t\tvdiv(e->e_pt->pos, 4);\n\t\t} else\n\t\t\tvdiv(e->e_pt->pos, 2);\n\n\t\tvdiv(e->avg, 2);\n\t}\n\n\treturn e->e_pt;\n}\n\n#define hole_vertex(v) (len((v)->f) != len((v)->e))\nvertex updated_point(vertex v)\n{\n\tint i, n = 0;\n\tedge e;\n\tface f;\n\tcoord_t sum = {0, 0, 0};\n\n\tif (v->v_new) return v->v_new;\n\n\tv->v_new = vertex_new();\n\tif (hole_vertex(v)) {\n\t\tv->v_new->pos = v->pos;\n\t\tforeach(i, e, v->e) {\n\t\t\tif (!hole_edge(e)) continue;\n\t\t\tvadd(v->v_new->pos, edge_point(e)->pos);\n\t\t\tn++;\n\t\t}\n\t\tvdiv(v->v_new->pos, n + 1);\n\t} else {\n\t\tn = len(v->f);\n\t\tforeach(i, f, v->f)\n\t\t\tvadd(sum, face_point(f)->pos);\n\t\tforeach(i, e, v->e)\n\t\t\tvmadd(sum, edge_point(e)->pos, 2, sum);\n\t\tvdiv(sum, n);\n\t\tvmadd(sum, v->pos, n - 3, sum);\n\t\tvdiv(sum, n);\n\t\tv->v_new->pos = sum;\n\t}\n\n\treturn v->v_new;\n}\n\nmodel catmull(model m)\n{\n\tint i, j, a, b, c, d;\n\tface f;\n\tvertex v, x;\n\n\tmodel nm = model_new();\n\tforeach (i, f, m->f) {\n\t\tforeach(j, v, f->v) {\n\t\t\t_get_idx(a, updated_point(v));\n\t\t\t_get_idx(b, edge_point(elem(f->e, (j + 1) % len(f->e))));\n\t\t\t_get_idx(c, face_point(f));\n\t\t\t_get_idx(d, edge_point(elem(f->e, j)));\n\t\t\tmodel_add_face(nm, 4, a, b, c, d);\n\t\t}\n\t}\n\treturn nm;\n}\n", "language": "C" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n)\n\ntype (\n Point [3]float64\n Face []int\n\n Edge struct {\n pn1 int // point number 1\n pn2 int // point number 2\n fn1 int // face number 1\n fn2 int // face number 2\n cp Point // center point\n }\n\n PointEx struct {\n p Point\n n int\n }\n)\n\nfunc sumPoint(p1, p2 Point) Point {\n sp := Point{}\n for i := 0; i < 3; i++ {\n sp[i] = p1[i] + p2[i]\n }\n return sp\n}\n\nfunc mulPoint(p Point, m float64) Point {\n mp := Point{}\n for i := 0; i < 3; i++ {\n mp[i] = p[i] * m\n }\n return mp\n}\n\nfunc divPoint(p Point, d float64) Point {\n return mulPoint(p, 1.0/d)\n}\n\nfunc centerPoint(p1, p2 Point) Point {\n return divPoint(sumPoint(p1, p2), 2)\n}\n\nfunc getFacePoints(inputPoints []Point, inputFaces []Face) []Point {\n facePoints := make([]Point, len(inputFaces))\n for i, currFace := range inputFaces {\n facePoint := Point{}\n for _, cpi := range currFace {\n currPoint := inputPoints[cpi]\n facePoint = sumPoint(facePoint, currPoint)\n }\n facePoint = divPoint(facePoint, float64(len(currFace)))\n facePoints[i] = facePoint\n }\n return facePoints\n}\n\nfunc getEdgesFaces(inputPoints []Point, inputFaces []Face) []Edge {\n var edges [][3]int\n for faceNum, face := range inputFaces {\n numPoints := len(face)\n for pointIndex := 0; pointIndex < numPoints; pointIndex++ {\n pointNum1 := face[pointIndex]\n var pointNum2 int\n if pointIndex < numPoints-1 {\n pointNum2 = face[pointIndex+1]\n } else {\n pointNum2 = face[0]\n }\n if pointNum1 > pointNum2 {\n pointNum1, pointNum2 = pointNum2, pointNum1\n }\n edges = append(edges, [3]int{pointNum1, pointNum2, faceNum})\n }\n }\n sort.Slice(edges, func(i, j int) bool {\n if edges[i][0] == edges[j][0] {\n if edges[i][1] == edges[j][1] {\n return edges[i][2] < edges[j][2]\n }\n return edges[i][1] < edges[j][1]\n }\n return edges[i][0] < edges[j][0]\n })\n numEdges := len(edges)\n eIndex := 0\n var mergedEdges [][4]int\n for eIndex < numEdges {\n e1 := edges[eIndex]\n if eIndex < numEdges-1 {\n e2 := edges[eIndex+1]\n if e1[0] == e2[0] && e1[1] == e2[1] {\n mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], e2[2]})\n eIndex += 2\n } else {\n mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1})\n eIndex++\n }\n } else {\n mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1})\n eIndex++\n }\n }\n var edgesCenters []Edge\n for _, me := range mergedEdges {\n p1 := inputPoints[me[0]]\n p2 := inputPoints[me[1]]\n cp := centerPoint(p1, p2)\n edgesCenters = append(edgesCenters, Edge{me[0], me[1], me[2], me[3], cp})\n }\n return edgesCenters\n}\n\nfunc getEdgePoints(inputPoints []Point, edgesFaces []Edge, facePoints []Point) []Point {\n edgePoints := make([]Point, len(edgesFaces))\n for i, edge := range edgesFaces {\n cp := edge.cp\n fp1 := facePoints[edge.fn1]\n var fp2 Point\n if edge.fn2 == -1 {\n fp2 = fp1\n } else {\n fp2 = facePoints[edge.fn2]\n }\n cfp := centerPoint(fp1, fp2)\n edgePoints[i] = centerPoint(cp, cfp)\n }\n return edgePoints\n}\n\nfunc getAvgFacePoints(inputPoints []Point, inputFaces []Face, facePoints []Point) []Point {\n numPoints := len(inputPoints)\n tempPoints := make([]PointEx, numPoints)\n for faceNum := range inputFaces {\n fp := facePoints[faceNum]\n for _, pointNum := range inputFaces[faceNum] {\n tp := tempPoints[pointNum].p\n tempPoints[pointNum].p = sumPoint(tp, fp)\n tempPoints[pointNum].n++\n }\n }\n avgFacePoints := make([]Point, numPoints)\n for i, tp := range tempPoints {\n avgFacePoints[i] = divPoint(tp.p, float64(tp.n))\n }\n return avgFacePoints\n}\n\nfunc getAvgMidEdges(inputPoints []Point, edgesFaces []Edge) []Point {\n numPoints := len(inputPoints)\n tempPoints := make([]PointEx, numPoints)\n for _, edge := range edgesFaces {\n cp := edge.cp\n for _, pointNum := range []int{edge.pn1, edge.pn2} {\n tp := tempPoints[pointNum].p\n tempPoints[pointNum].p = sumPoint(tp, cp)\n tempPoints[pointNum].n++\n }\n }\n avgMidEdges := make([]Point, len(tempPoints))\n for i, tp := range tempPoints {\n avgMidEdges[i] = divPoint(tp.p, float64(tp.n))\n }\n return avgMidEdges\n}\n\nfunc getPointsFaces(inputPoints []Point, inputFaces []Face) []int {\n numPoints := len(inputPoints)\n pointsFaces := make([]int, numPoints)\n for faceNum := range inputFaces {\n for _, pointNum := range inputFaces[faceNum] {\n pointsFaces[pointNum]++\n }\n }\n return pointsFaces\n}\n\nfunc getNewPoints(inputPoints []Point, pointsFaces []int, avgFacePoints, avgMidEdges []Point) []Point {\n newPoints := make([]Point, len(inputPoints))\n for pointNum := range inputPoints {\n n := float64(pointsFaces[pointNum])\n m1, m2, m3 := (n-3)/n, 1.0/n, 2.0/n\n oldCoords := inputPoints[pointNum]\n p1 := mulPoint(oldCoords, m1)\n afp := avgFacePoints[pointNum]\n p2 := mulPoint(afp, m2)\n ame := avgMidEdges[pointNum]\n p3 := mulPoint(ame, m3)\n p4 := sumPoint(p1, p2)\n newPoints[pointNum] = sumPoint(p4, p3)\n }\n return newPoints\n}\n\nfunc switchNums(pointNums [2]int) [2]int {\n if pointNums[0] < pointNums[1] {\n return pointNums\n }\n return [2]int{pointNums[1], pointNums[0]}\n}\n\nfunc cmcSubdiv(inputPoints []Point, inputFaces []Face) ([]Point, []Face) {\n facePoints := getFacePoints(inputPoints, inputFaces)\n edgesFaces := getEdgesFaces(inputPoints, inputFaces)\n edgePoints := getEdgePoints(inputPoints, edgesFaces, facePoints)\n avgFacePoints := getAvgFacePoints(inputPoints, inputFaces, facePoints)\n avgMidEdges := getAvgMidEdges(inputPoints, edgesFaces)\n pointsFaces := getPointsFaces(inputPoints, inputFaces)\n newPoints := getNewPoints(inputPoints, pointsFaces, avgFacePoints, avgMidEdges)\n var facePointNums []int\n nextPointNum := len(newPoints)\n for _, facePoint := range facePoints {\n newPoints = append(newPoints, facePoint)\n facePointNums = append(facePointNums, nextPointNum)\n nextPointNum++\n }\n edgePointNums := make(map[[2]int]int)\n for edgeNum := range edgesFaces {\n pointNum1 := edgesFaces[edgeNum].pn1\n pointNum2 := edgesFaces[edgeNum].pn2\n edgePoint := edgePoints[edgeNum]\n newPoints = append(newPoints, edgePoint)\n edgePointNums[[2]int{pointNum1, pointNum2}] = nextPointNum\n nextPointNum++\n }\n var newFaces []Face\n for oldFaceNum, oldFace := range inputFaces {\n if len(oldFace) == 4 {\n a, b, c, d := oldFace[0], oldFace[1], oldFace[2], oldFace[3]\n facePointAbcd := facePointNums[oldFaceNum]\n edgePointAb := edgePointNums[switchNums([2]int{a, b})]\n edgePointDa := edgePointNums[switchNums([2]int{d, a})]\n edgePointBc := edgePointNums[switchNums([2]int{b, c})]\n edgePointCd := edgePointNums[switchNums([2]int{c, d})]\n newFaces = append(newFaces, Face{a, edgePointAb, facePointAbcd, edgePointDa})\n newFaces = append(newFaces, Face{b, edgePointBc, facePointAbcd, edgePointAb})\n newFaces = append(newFaces, Face{c, edgePointCd, facePointAbcd, edgePointBc})\n newFaces = append(newFaces, Face{d, edgePointDa, facePointAbcd, edgePointCd})\n }\n }\n return newPoints, newFaces\n}\n\nfunc main() {\n inputPoints := []Point{\n {-1.0, 1.0, 1.0},\n {-1.0, -1.0, 1.0},\n {1.0, -1.0, 1.0},\n {1.0, 1.0, 1.0},\n {1.0, -1.0, -1.0},\n {1.0, 1.0, -1.0},\n {-1.0, -1.0, -1.0},\n {-1.0, 1.0, -1.0},\n }\n\n inputFaces := []Face{\n {0, 1, 2, 3},\n {3, 2, 4, 5},\n {5, 4, 6, 7},\n {7, 0, 3, 5},\n {7, 6, 1, 0},\n {6, 1, 2, 4},\n }\n\n outputPoints := make([]Point, len(inputPoints))\n outputFaces := make([]Face, len(inputFaces))\n copy(outputPoints, inputPoints)\n copy(outputFaces, inputFaces)\n iterations := 1\n for i := 0; i < iterations; i++ {\n outputPoints, outputFaces = cmcSubdiv(outputPoints, outputFaces)\n }\n for _, p := range outputPoints {\n fmt.Printf(\"% .4f\\n\", p)\n }\n fmt.Println()\n for _, f := range outputFaces {\n fmt.Printf(\"%2d\\n\", f)\n }\n}\n", "language": "Go" }, { "code": "{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Data.Array\nimport Data.Foldable (length, concat, sum)\nimport Data.List (genericLength)\nimport Data.Maybe (mapMaybe)\nimport Prelude hiding (length, concat, sum)\nimport qualified Data.Map.Strict as Map\n\n{-\nA SimpleMesh consists of only vertices and faces that refer to them.\nA Mesh extends the SimpleMesh to contain edges as well as references to\nadjoining mesh components for each other component, such as a vertex\nalso contains what faces it belongs to.\nAn isolated edge can be represented as a degenerate face with 2 vertices.\nFaces with 0 or 1 vertices can be thrown out, as they do not contribute to\nthe result (they can also propagate NaNs).\n-}\n\nnewtype VertexId = VertexId { getVertexId :: Int } deriving (Ix, Ord, Eq, Show)\nnewtype EdgeId = EdgeId { getEdgeId :: Int } deriving (Ix, Ord, Eq, Show)\nnewtype FaceId = FaceId { getFaceId :: Int } deriving (Ix, Ord, Eq, Show)\n\ndata Vertex a = Vertex\n { vertexPoint :: a\n , vertexEdges :: [EdgeId]\n , vertexFaces :: [FaceId]\n } deriving Show\n\ndata Edge = Edge\n { edgeVertexA :: VertexId\n , edgeVertexB :: VertexId\n , edgeFaces :: [FaceId]\n } deriving Show\n\ndata Face = Face\n { faceVertices :: [VertexId]\n , faceEdges :: [EdgeId]\n } deriving Show\n\ntype VertexArray a = Array VertexId (Vertex a)\ntype EdgeArray = Array EdgeId Edge\ntype FaceArray = Array FaceId Face\n\ndata Mesh a = Mesh\n { meshVertices :: VertexArray a\n , meshEdges :: EdgeArray\n , meshFaces :: FaceArray\n } deriving Show\n\ndata SimpleVertex a = SimpleVertex { sVertexPoint :: a } deriving Show\ndata SimpleFace = SimpleFace { sFaceVertices :: [VertexId] } deriving Show\n\ntype SimpleVertexArray a = Array VertexId (SimpleVertex a)\ntype SimpleFaceArray = Array FaceId SimpleFace\n\ndata SimpleMesh a = SimpleMesh\n { sMeshVertices :: SimpleVertexArray a\n , sMeshFaces :: SimpleFaceArray\n } deriving Show\n\n-- Generic helpers.\nfmap1 :: Functor f => (t -> a -> b) -> (t -> f a) -> t -> f b\nfmap1 g h x = fmap (g x) (h x)\n\naZipWith :: Ix i1 => (a -> b -> e) -> Array i1 a -> Array i b -> Array i1 e\naZipWith f a b = listArray (bounds a) $ zipWith f (elems a) (elems b)\n\naverage :: (Foldable f, Fractional a) => f a -> a\naverage xs = (sum xs) / (fromIntegral $ length xs)\n\n-- Intermediary point types for ultimately converting into a point `a`.\nnewtype FacePoint a = FacePoint { getFacePoint :: a } deriving Show\nnewtype EdgeCenterPoint a = EdgeCenterPoint { getEdgeCenterPoint :: a } deriving Show\nnewtype EdgePoint a = EdgePoint { getEdgePoint :: a } deriving Show\nnewtype VertexPoint a = VertexPoint { getVertexPoint :: a } deriving Show\n\ntype FacePointArray a = Array FaceId (FacePoint a)\ntype EdgePointArray a = Array EdgeId (EdgePoint a)\ntype EdgeCenterPointArray a = Array EdgeId (EdgeCenterPoint a)\ntype IsEdgeHoleArray = Array EdgeId Bool\ntype VertexPointArray a = Array VertexId (VertexPoint a)\n\n-- Subdivision helpers.\nfacePoint :: Fractional a => Mesh a -> Face -> FacePoint a\nfacePoint mesh = FacePoint . average . (fmap $ vertexPointById mesh) . faceVertices\n\nallFacePoints :: Fractional a => Mesh a -> FacePointArray a\nallFacePoints = fmap1 facePoint meshFaces\n\nvertexPointById :: Mesh a -> VertexId -> a\nvertexPointById mesh = vertexPoint . (meshVertices mesh !)\n\nedgeCenterPoint :: Fractional a => Mesh a -> Edge -> EdgeCenterPoint a\nedgeCenterPoint mesh (Edge ea eb _)\n = EdgeCenterPoint . average $ fmap (vertexPointById mesh) [ea, eb]\n\nallEdgeCenterPoints :: Fractional a => Mesh a -> EdgeCenterPointArray a\nallEdgeCenterPoints = fmap1 edgeCenterPoint meshEdges\n\nallIsEdgeHoles :: Mesh a -> IsEdgeHoleArray\nallIsEdgeHoles = fmap ((< 2) . length . edgeFaces) . meshEdges\n\nedgePoint :: Fractional a => Edge -> FacePointArray a -> EdgeCenterPoint a -> EdgePoint a\nedgePoint (Edge _ _ [_]) _ (EdgeCenterPoint ecp) = EdgePoint ecp\nedgePoint (Edge _ _ faceIds) facePoints (EdgeCenterPoint ecp)\n = EdgePoint $ average [ecp, average $ fmap (getFacePoint . (facePoints !)) faceIds]\n\nallEdgePoints :: Fractional a => Mesh a -> FacePointArray a -> EdgeCenterPointArray a -> EdgePointArray a\nallEdgePoints mesh fps ecps = aZipWith (\\e ecp -> edgePoint e fps ecp) (meshEdges mesh) ecps\n\nvertexPoint' :: Fractional a => Vertex a -> FacePointArray a -> EdgeCenterPointArray a -> IsEdgeHoleArray -> VertexPoint a\nvertexPoint' vertex facePoints ecps iehs\n | length faceIds == length edgeIds = VertexPoint newCoords\n | otherwise = VertexPoint avgHoleEcps\n where\n newCoords = (oldCoords * m1) + (avgFacePoints * m2) + (avgMidEdges * m3)\n oldCoords = vertexPoint vertex\n avgFacePoints = average $ fmap (getFacePoint . (facePoints !)) faceIds\n avgMidEdges = average $ fmap (getEdgeCenterPoint . (ecps !)) edgeIds\n m1 = (n - 3) / n\n m2 = 1 / n\n m3 = 2 / n\n n = genericLength faceIds\n faceIds = vertexFaces vertex\n edgeIds = vertexEdges vertex\n avgHoleEcps = average . (oldCoords:) . fmap (getEdgeCenterPoint . (ecps !)) $ filter (iehs !) edgeIds\n\nallVertexPoints :: Fractional a => Mesh a -> FacePointArray a -> EdgeCenterPointArray a -> IsEdgeHoleArray -> VertexPointArray a\nallVertexPoints mesh fps ecps iehs = fmap (\\v -> vertexPoint' v fps ecps iehs) (meshVertices mesh)\n\n-- For each vertex in a face, generate a set of new faces from it with its vertex point,\n-- neighbor edge points, and face point. The new faces will refer to vertices in the\n-- combined vertex array.\nnewFaces :: Face -> FaceId -> Int -> Int -> [SimpleFace]\nnewFaces (Face vertexIds edgeIds) faceId epOffset vpOffset\n = take (genericLength vertexIds)\n $ zipWith3 newFace (cycle vertexIds) (cycle edgeIds) (drop 1 (cycle edgeIds))\n where\n f = VertexId . (+ epOffset) . getEdgeId\n newFace vid epA epB = SimpleFace\n [ VertexId . (+ vpOffset) $ getVertexId vid\n , f epA\n , VertexId $ getFaceId faceId\n , f epB]\n\nsubdivide :: Fractional a => SimpleMesh a -> SimpleMesh a\nsubdivide simpleMesh\n = SimpleMesh combinedVertices (listArray (FaceId 0, FaceId (genericLength faces - 1)) faces)\n where\n mesh = makeComplexMesh simpleMesh\n fps = allFacePoints mesh\n ecps = allEdgeCenterPoints mesh\n eps = allEdgePoints mesh fps ecps\n iehs = allIsEdgeHoles mesh\n vps = allVertexPoints mesh fps ecps iehs\n edgePointOffset = length fps\n vertexPointOffset = edgePointOffset + length eps\n combinedVertices\n = listArray (VertexId 0, VertexId (vertexPointOffset + length vps - 1))\n . fmap SimpleVertex\n $ concat [ fmap getFacePoint $ elems fps\n , fmap getEdgePoint $ elems eps\n , fmap getVertexPoint $ elems vps]\n faces\n = concat $ zipWith (\\face fid -> newFaces face fid edgePointOffset vertexPointOffset)\n (elems $ meshFaces mesh) (fmap FaceId [0..])\n\n-- Transform to a Mesh by filling in the missing references and generating edges.\n-- Faces can be updated with their edges, but must be ordered.\n-- Edge and face order does not matter for vertices.\n-- TODO: Discard degenerate faces (ones with 0 to 2 vertices/edges),\n-- or we could transform these into single edges or vertices.\nmakeComplexMesh :: forall a. SimpleMesh a -> Mesh a\nmakeComplexMesh (SimpleMesh sVertices sFaces) = Mesh vertices edges faces\n where\n makeEdgesFromFace :: SimpleFace -> FaceId -> [Edge]\n makeEdgesFromFace (SimpleFace vertexIds) fid\n = take (genericLength vertexIds)\n $ zipWith (\\a b -> Edge a b [fid]) verts (drop 1 verts)\n where\n verts = cycle vertexIds\n\n edgeKey :: VertexId -> VertexId -> (VertexId, VertexId)\n edgeKey a b = (min a b, max a b)\n\n sFacesList :: [SimpleFace]\n sFacesList = elems sFaces\n\n fids :: [FaceId]\n fids = fmap FaceId [0..]\n\n eids :: [EdgeId]\n eids = fmap EdgeId [0..]\n\n faceEdges :: [[Edge]]\n faceEdges = zipWith makeEdgesFromFace sFacesList fids\n\n edgeMap :: Map.Map (VertexId, VertexId) Edge\n edgeMap\n = Map.fromListWith (\\(Edge a b fidsA) (Edge _ _ fidsB) -> Edge a b (fidsA ++ fidsB))\n . fmap (\\edge@(Edge a b _) -> (edgeKey a b, edge))\n $ concat faceEdges\n\n edges :: EdgeArray\n edges = listArray (EdgeId 0, EdgeId $ (Map.size edgeMap) - 1) $ Map.elems edgeMap\n\n edgeIdMap :: Map.Map (VertexId, VertexId) EdgeId\n edgeIdMap = Map.fromList $ zipWith (\\(Edge a b _) eid -> ((edgeKey a b), eid)) (elems edges) eids\n\n faceEdgeIds :: [[EdgeId]]\n faceEdgeIds = fmap (mapMaybe (\\(Edge a b _) -> Map.lookup (edgeKey a b) edgeIdMap)) faceEdges\n\n faces :: FaceArray\n faces\n = listArray (FaceId 0, FaceId $ (length sFaces) - 1)\n $ zipWith (\\(SimpleFace verts) edgeIds -> Face verts edgeIds) sFacesList faceEdgeIds\n\n vidsToFids :: Map.Map VertexId [FaceId]\n vidsToFids\n = Map.fromListWith (++)\n . concat\n $ zipWith (\\(SimpleFace vertexIds) fid -> fmap (\\vid -> (vid, [fid])) vertexIds) sFacesList fids\n\n vidsToEids :: Map.Map VertexId [EdgeId]\n vidsToEids\n = Map.fromListWith (++)\n . concat\n $ zipWith (\\(Edge a b _) eid -> [(a, [eid]), (b, [eid])]) (elems edges) eids\n\n simpleToComplexVert :: SimpleVertex a -> VertexId -> Vertex a\n simpleToComplexVert (SimpleVertex point) vid\n = Vertex point\n (Map.findWithDefault [] vid vidsToEids)\n (Map.findWithDefault [] vid vidsToFids)\n\n vertices :: VertexArray a\n vertices\n = listArray (bounds sVertices)\n $ zipWith simpleToComplexVert (elems sVertices) (fmap VertexId [0..])\n\npShowSimpleMesh :: Show a => SimpleMesh a -> String\npShowSimpleMesh (SimpleMesh vertices faces)\n = \"Vertices:\\n\" ++ (arrShow vertices sVertexPoint)\n ++ \"Faces:\\n\" ++ (arrShow faces (fmap getVertexId . sFaceVertices))\n where\n arrShow a f = concatMap ((++ \"\\n\") . show . (\\(i, e) -> (i, f e))) . zip [0 :: Int ..] $ elems a\n\n-- Testing types.\ndata Point a = Point a a a deriving (Show)\n\ninstance Functor Point where\n fmap f (Point x y z) = Point (f x) (f y) (f z)\n\nzipPoint :: (a -> b -> c) -> Point a -> Point b -> Point c\nzipPoint f (Point x y z) (Point x' y' z') = Point (f x x') (f y y') (f z z')\n\ninstance Num a => Num (Point a) where\n (+) = zipPoint (+)\n (-) = zipPoint (-)\n (*) = zipPoint (*)\n negate = fmap negate\n abs = fmap abs\n signum = fmap signum\n fromInteger i = let i' = fromInteger i in Point i' i' i'\n\ninstance Fractional a => Fractional (Point a) where\n recip = fmap recip\n fromRational r = let r' = fromRational r in Point r' r' r'\n\ntestCube :: SimpleMesh (Point Double)\ntestCube = SimpleMesh vertices faces\n where\n vertices = listArray (VertexId 0, VertexId 7)\n $ fmap SimpleVertex\n [ Point (-1) (-1) (-1)\n , Point (-1) (-1) 1\n , Point (-1) 1 (-1)\n , Point (-1) 1 1\n , Point 1 (-1) (-1)\n , Point 1 (-1) 1\n , Point 1 1 (-1)\n , Point 1 1 1]\n faces = listArray (FaceId 0, FaceId 5)\n $ fmap (SimpleFace . (fmap VertexId))\n [ [0, 4, 5, 1]\n , [4, 6, 7, 5]\n , [6, 2, 3, 7]\n , [2, 0, 1, 3]\n , [1, 5, 7, 3]\n , [0, 2, 6, 4]]\n\ntestCubeWithHole :: SimpleMesh (Point Double)\ntestCubeWithHole\n = SimpleMesh (sMeshVertices testCube) (ixmap (FaceId 0, FaceId 4) id (sMeshFaces testCube))\n\ntestTriangle :: SimpleMesh (Point Double)\ntestTriangle = SimpleMesh vertices faces\n where\n vertices = listArray (VertexId 0, VertexId 2)\n $ fmap SimpleVertex\n [ Point 0 0 0\n , Point 0 0 1\n , Point 0 1 0]\n faces = listArray (FaceId 0, FaceId 0)\n $ fmap (SimpleFace . (fmap VertexId))\n [ [0, 1, 2]]\n\nmain :: IO ()\nmain = putStr . pShowSimpleMesh $ subdivide testCube\n", "language": "Haskell" }, { "code": "avg=: +/ % #\n\nhavePoints=: e.\"1/~ i.@#\n\ncatmullclark=:3 :0\n 'mesh points'=. y\n face_point=. avg\"2 mesh{points\n point_face=. |: mesh havePoints points\n avg_face_points=. point_face avg@#\"1 2 face_point\n edges=. ~.,/ meshEdges=. mesh /:~@,\"+1|.\"1 mesh\n edge_face=. *./\"2 edges e.\"0 1/ mesh\n edge_center=. avg\"2 edges{points\n edge_point=. (0.5*edge_center) + 0.25 * edge_face +/ .* face_point\n point_edge=. |: edges havePoints points\n avg_mid_edges=. point_edge avg@#\"1 2 edge_center\n n=. +/\"1 point_edge\n 'm3 m2 m1'=. (2,1,:n-3)%\"1 n\n new_coords=. (m1 * points) + (m2 * avg_face_points) + (m3 * avg_mid_edges)\n pts=. face_point,edge_point,new_coords\n c0=. (#edge_point)+ e0=. #face_point\n msh=. (,c0+mesh),.(,e0+edges i. meshEdges),.((#i.)~/$mesh),.,e0+_1|.\"1 edges i. meshEdges\n msh;pts\n)\n", "language": "J" }, { "code": "NB.cube\npoints=: _1+2*#:i.8\nmesh=: 1 A.\"1 I.(,1-|.)8&$@#&0 1\">4 2 1\n\n catmullclark mesh;points\n┌──────────┬─────────────────────────────┐\n│22 6 0 9│ 1 0 0│\n│23 7 0 6│ 0 1 0│\n│25 8 0 7│ 0 0 1│\n│24 9 0 8│ 0 0 _1│\n│20 10 1 12│ 0 _1 0│\n│21 11 1 10│ _1 0 0│\n│25 8 1 11│ 0.75 _0.75 0│\n│24 12 1 8│ 0.75 0 0.75│\n│19 13 2 14│ 0.75 0.75 0│\n│21 11 2 13│ 0.75 0 _0.75│\n│25 7 2 11│ _0.75 0.75 0│\n│23 14 2 7│ 0 0.75 0.75│\n│18 15 3 16│ 0 0.75 _0.75│\n│20 12 3 15│ _0.75 0 0.75│\n│24 9 3 12│ 0 _0.75 0.75│\n│22 16 3 9│ _0.75 0 _0.75│\n│18 17 4 16│ 0 _0.75 _0.75│\n│19 14 4 17│ _0.75 _0.75 0│\n│23 6 4 14│_0.555556 _0.555556 _0.555556│\n│22 16 4 6│_0.555556 _0.555556 0.555556│\n│18 17 5 15│_0.555556 0.555556 _0.555556│\n│19 13 5 17│_0.555556 0.555556 0.555556│\n│21 10 5 13│ 0.555556 _0.555556 _0.555556│\n│20 15 5 10│ 0.555556 _0.555556 0.555556│\n│ │ 0.555556 0.555556 _0.555556│\n│ │ 0.555556 0.555556 0.555556│\n└──────────┴─────────────────────────────┘\n", "language": "J" }, { "code": "using Makie, Statistics\n\n# Point3f0 is a 3-tuple of 32-bit floats for 3-dimensional space, and all Points are 3D.\nPoint = Point3f0\n\n# a Face is defined by the points that are its vertices, in order.\nFace = Vector{Point}\n\n# an Edge is a line segment where the points are sorted\nstruct Edge\n p1::Point\n p2::Point\n Edge(a, b) = new(min(a, b), max(a, b))\nend\n\nedgemidpoint(edge) = (edge.p1 + edge.p2) / 2.0\nfacesforpoint(p, faces) = [f for f in faces if p in f]\nfacesforedge(e, faces) = [f for f in faces if (e.p1 in f) && (e.p2 in f)]\nnexttohole(edge, faces) = length(facesforedge(edge, faces)) < 2\n\nfunction newedgepoint(edge, faces)\n f = facesforedge(edge, faces)\n p1, p2, len = edge.p1, edge.p2, length(f)\n if len == 2\n return (p1 + p2 + mean(f[1]) + mean(f[2])) / 4.0\n elseif len == 1\n return (p1 + p2 + mean(f[1])) / 3.0\n end\n return (p1 + p2) / 2.0\nend\n\nfunction edgesforface(face)\n ret, indices = Vector{Edge}(), collect(1:length(face))\n for i in 1:length(face)-1\n push!(ret, Edge(face[indices[1]], face[indices[2]]))\n indices .= circshift(indices, 1)\n end\n ret\nend\n\nfunction edgesforpoint(p, faces)\n f = filter(x -> p in x, faces)\n return filter(e -> p == e.p1 || p == e.p2, mapreduce(edgesforface, vcat, f))\nend\n\nfunction adjacentpoints(point, face)\n a = indexin([point], face)\n if a[1] != nothing\n adjacent = (a[1] == 1) ? [face[end], face[2]] :\n a[1] == length(face) ? [face[end-1], face[1]] :\n [face[a[1] - 1], face[a[1] + 1]]\n return sort(adjacent)\n else\n throw(\"point $point not in face $face\")\n end\nend\n\nadjacentedges(point, face) = [Edge(point, x) for x in adjacentpoints(point, face)]\nfacewrapped(face) = begin f = deepcopy(face); push!(f, f[1]); f end\ndrawface(face, colr) = lines(facewrapped(face); color=colr)\ndrawface!(face, colr) = lines!(facewrapped(face); color=colr)\ndrawfaces!(faces, colr) = for f in faces drawface!(f, colr) end\nconst colors = [:red, :green, :blue, :gold]\n\nfunction drawfaces(faces, colr)\n scene = drawface(faces[1], colr)\n if length(faces) > 1\n for f in faces[2:end]\n drawface!(f, colr)\n end\n end\n scene\nend\n\nfunction catmullclarkstep(faces)\n d, E, dprime = Set(reduce(vcat, faces)), Dict{Vector, Point}(), Dict{Point, Point}()\n for face in faces, (i, p) in enumerate(face)\n edge = (p == face[end]) ? Edge(p, face[1]) : Edge(p, face[i + 1])\n E[[edge, face]] = newedgepoint(edge, faces)\n end\n for p in d\n F = mean([mean(face) for face in facesforpoint(p, faces)])\n pe = edgesforpoint(p, faces)\n R = mean(map(edgemidpoint, pe))\n n = length(pe)\n dprime[p] = (F + 2 * R + p * (n - 3)) / n\n end\n newfaces = Vector{Face}()\n for face in faces\n v = mean(face)\n for point in face\n fp1, fp2 = map(x -> E[[x, face]], adjacentedges(point, face))\n push!(newfaces, [fp1, dprime[point], fp2, v])\n end\n end\n return newfaces\nend\n\n\"\"\"\n catmullclark(faces, iters, scene)\n\nPerform a multistep Catmull-Clark subdivision of a surface. See Wikipedia or page 53\nof http://graphics.stanford.edu/courses/cs468-10-fall/LectureSlides/10_Subdivision.pdf\nPlots the iterations, with colors for each iteration as set in the colors array.\nUses a Makie Scene of scene to plot the iters iterations.\n\"\"\"\nfunction catmullclark(faces, iters, scene)\n nextfaces = deepcopy(faces)\n for i in 1:iters\n nextfaces = catmullclarkstep(nextfaces)\n drawfaces!(nextfaces, colors[i])\n display(scene)\n sleep(1)\n end\nend\n\nconst inputpoints = [\n [-1.0, -1.0, -1.0],\n [-1.0, -1.0, 1.0],\n [-1.0, 1.0, -1.0],\n [-1.0, 1.0, 1.0],\n [1.0, -1.0, -1.0],\n [1.0, -1.0, 1.0],\n [1.0, 1.0, -1.0],\n [1.0, 1.0, 1.0]\n]\n\nconst inputfaces = [\n [0, 4, 5, 1],\n [4, 6, 7, 5],\n [6, 2, 3, 7],\n [2, 0, 1, 3],\n [1, 5, 7, 3],\n [0, 2, 6, 4]\n]\n\nconst faces = [map(x -> Point3f0(inputpoints[x]), p .+ 1) for p in inputfaces]\n\nscene = drawfaces(faces, :black)\ndisplay(scene)\nsleep(1)\n\ncatmullclark(faces, 4, scene)\n\nprintln(\"Press Enter to continue\", readline())\n", "language": "Julia" }, { "code": "subSetQ[large_,small_] := MemberQ[large,small]\nsubSetQ[large_,small_List] := And@@(MemberQ[large,#]&/@small)\n\ncontaining[groupList_,item_]:= Flatten[Position[groupList,group_/;subSetQ[group,item]]]\n\nReplaceFace[face_]:=Transpose[Prepend[Transpose[{#[[1]],face,#[[2]]}&/@Transpose[Partition[face,2,1,1]//{#,RotateRight[#]}&]],face]]\n", "language": "Mathematica" }, { "code": "CatMullClark[{Points_,faces_}]:=Block[{avgFacePoints,avgEdgePoints,updatedPoints,newEdgePoints,newPoints,edges,newFaces,weights,pointUpdate,edgeUpdate,newIndex},\nedges = DeleteDuplicates[Flatten[Partition[#,2,1,-1]&/@faces,1],Sort[#1]==Sort[#2]&];\navgFacePoints=Mean[Points[[#]]] &/@ faces;\navgEdgePoints=Mean[Points[[#]]] &/@ edges;\n\nweights[vertex_]:= Count[faces,vertex,2]//{(#-3),1,2}/#&;\npointUpdate[vertex_]:=\n\tIf[Length[faces~containing~vertex]!=Length[edges~containing~vertex],\n\t\tMean[avgEdgePoints[[Select[edges~containing~vertex,holeQ[edges[[#]],faces]&]]]],\n\t\tTotal[weights[vertex]{ Points[[vertex]], Mean[avgFacePoints[[faces~containing~vertex]]], Mean[avgEdgePoints[[edges~containing~vertex]]]}]\n\t];\n\nedgeUpdate[edge_]:=\n\tIf[Length[faces~containing~edge]==1,\n\t\tMean[Points[[edge]]],\n\t\tMean[Points[[Flatten[{edge, faces[[faces~containing~edge]]}]]]]\n\t];\n\nupdatedPoints = pointUpdate/@Range[1,Length[Points]];\nnewEdgePoints = edgeUpdate/@edges;\nnewPoints = Join[updatedPoints,avgFacePoints,newEdgePoints];\n\nnewIndex[edge_/;Length[edge]==2] := Length[Points]+Length[faces]+Position[Sort/@edges,Sort@edge][[1,1]]\nnewIndex[face_] := Length[Points]+Position[faces,face][[1,1]]\n\nnewFaces = Flatten[Map[newIndex[#,{Points,edges,faces}]&,ReplaceFace/@faces,{-2}],1];\n{newPoints,newFaces}\n]\n", "language": "Mathematica" }, { "code": "{points,faces}=PolyhedronData[\"Cube\",{\"VertexCoordinates\",\"FaceIndices\"}];\n\nFunction[iteration,\nGraphics3D[(Polygon[iteration[[1]][[#]]]&/@iteration[[2]])]\n]/@NestList[CatMullClark,{points,faces},3]//GraphicsRow\n", "language": "Mathematica" }, { "code": "faces = Delete[faces, 6];\nFunction[iteration, Graphics3D[\n (Polygon[iteration[[1]][[#]]] & /@ iteration[[2]])\n ]] /@ NestList[CatMullClark, {points, faces}, 3] // GraphicsRow\n", "language": "Mathematica" }, { "code": "import algorithm\nimport tables\n\nconst None = -1 # Index number used to indicate no data.\n\ntype\n\n Point = array[3, float]\n Face = seq[int]\n\n Edge = object\n pn1: int # Point number 1.\n pn2: int # Point number 2.\n fn1: int # Face number 1.\n fn2: int # Face number 2.\n cp: Point # Center point.\n\n PointEx = object\n p: Point\n n: int\n\n PointNums = tuple[pn1, pn2: int]\n\n\n####################################################################################################\n# Point operations.\n\nfunc `+`(p1, p2: Point): Point =\n ## Adds points p1 and p2.\n for i in 0..Point.high:\n result[i] = p1[i] + p2[i]\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `*`(p: Point; m: float): Point =\n ## Multiply point p by m.\n for i in 0..Point.high:\n result[i] = p[i] * m\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `/`(p: Point; d: float): Point =\n ## Divide point p by d.\n for i in 0..Point.high:\n result[i] = p[i] / d\n\n#---------------------------------------------------------------------------------------------------\n\nfunc centerPoint(p1, p2: Point): Point =\n ## Return a point in the center of the segment ended by points p1 and p2.\n for i in 0..Point.high:\n result[i] = (p1[i] + p2[i]) / 2\n\n\n####################################################################################################\n\nfunc getFacePoints(inputPoints: seq[Point]; inputFaces: seq[Face]): seq[Point] =\n ## For each face, a face point is created which is the average of all the points of the face.\n\n result.setLen(inputFaces.len)\n for i, currFace in inputFaces:\n var facePoint: Point\n for currPointIndex in currFace:\n # Add currPoint to facePoint. Will divide later.\n facePoint = facePoint + inputPoints[currPointIndex]\n result[i] = facePoint / currFace.len.toFloat\n\n#---------------------------------------------------------------------------------------------------\n\nfunc getEdgesFaces(inputPoints: seq[Point]; inputFaces: seq[Face]): seq[Edge] =\n ## Get list of edges and the one or two adjacent faces in a list.\n ## Also get center point of edge.\n\n # Get edges for each face.\n var edges: seq[array[3, int]]\n for faceNum, face in inputFaces:\n # Loop over index into face.\n for pointIndex in 0..face.high:\n # If not last point then edge is current point and next point\n # and for last point, edge is current point and first point.\n var pointNum1 = face[pointIndex]\n var pointNum2 = if pointIndex < face.high: face[pointIndex + 1] else: face[0]\n # Order points in edge by lowest point number.\n if pointNum1 > pointNum2:\n swap pointNum1, pointNum2\n edges &= [pointNum1, pointNum2, faceNum]\n\n # Sort edges by pointNum1, pointNum2, faceNum.\n edges.sort(proc(a1, a2: array[3, int]): int =\n result = cmp(a1[0], a2[0])\n if result == 0:\n result = cmp(a1[1], a2[1])\n if result == 0:\n result = cmp(a1[2], a2[2]))\n\n # Merge edges with 2 adjacent faces:\n # [pointNum1, pointNum2, faceNum1, faceNum2] or\n # [pointNum1, pointNum2, faceNum1, None]\n var eIndex = 0\n var mergedEdges: seq[array[4, int]]\n while eIndex < edges.len:\n let e1 = edges[eIndex]\n # Check if not last edge.\n if eIndex < edges.high:\n let e2 = edges[eIndex + 1]\n if e1[0] == e2[0] and e1[1] == e2[1]:\n mergedEdges &= [e1[0], e1[1], e1[2], e2[2]]\n inc eIndex, 2\n else:\n mergedEdges &= [e1[0], e1[1], e1[2], None]\n inc eIndex\n else:\n mergedEdges &= [e1[0], e1[1], e1[2], None]\n inc eIndex\n\n # Add edge centers.\n for me in mergedEdges:\n let p1 = inputPoints[me[0]]\n let p2 = inputPoints[me[1]]\n let cp = centerPoint(p1, p2)\n result.add(Edge(pn1: me[0], pn2: me[1], fn1: me[2], fn2: me[3], cp: cp))\n\n#---------------------------------------------------------------------------------------------------\n\nfunc getEdgePoints(inputPoints: seq[Point];\n edgesFaces: seq[Edge];\n facePoints: seq[Point]): seq[Point] =\n ## For each edge, an edge point is created which is the average between the center of the\n ## edge and the center of the segment made with the face points of the two adjacent faces.\n\n result.setLen(edgesFaces.len)\n for i, edge in edgesFaces:\n # Get center of two facepoints.\n let fp1 = facePoints[edge.fn1]\n # If not two faces, just use one facepoint (should not happen for solid like a cube).\n let fp2 = if edge.fn2 == None: fp1 else: facePoints[edge.fn2]\n let cfp = centerPoint(fp1, fp2)\n # Get average between center of edge and center of facePoints.\n result[i] = centerPoint(edge.cp, cfp)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc getAvgFacePoints(inputPoints: seq[Point];\n inputFaces: seq[Face];\n facePoints: seq[Point]): seq[Point] =\n ## For each point calculate the average of the face points of the faces the\n ## point belongs to (avgFacePoints), create a list of lists of two numbers\n ## [facePointSum, numPoints] by going through the points in all the faces then\n ## create the avgFacePoints list of point by dividing pointSum(x, y, z) by numPoints\n\n var tempPoints = newSeq[PointEx](inputPoints.len)\n\n # Loop through faces, updating tempPoints.\n for faceNum, pointNums in inputFaces:\n let fp = facePoints[faceNum]\n for pointNum in pointNums:\n let tp = tempPoints[pointNum].p\n tempPoints[pointNum].p = tp + fp\n inc tempPoints[pointNum].n\n\n # Divide to build the result.\n result.setLen(inputPoints.len)\n for i, tp in tempPoints:\n result[i] = tp.p / tp.n.toFloat\n\n#---------------------------------------------------------------------------------------------------\n\nfunc getAvgMidEdges(inputPoints: seq[Point]; edgesFaces: seq[Edge]): seq[Point] =\n ## Return the average of the centers of edges the point belongs to (avgMidEdges).\n ## Create list with entry for each point. Each entry has two elements. One is a point\n ## that is the sum of the centers of the edges and the other is the number of edges.\n ## After going through all edges divide by number of edges.\n\n var tempPoints = newSeq[PointEx](inputPoints.len)\n\n # Go through edgesFaces using center updating each point.\n for edge in edgesFaces:\n for pointNum in [edge.pn1, edge.pn2]:\n let tp = tempPoints[pointNum].p\n tempPoints[pointNum].p = tp + edge.cp\n inc tempPoints[pointNum].n\n\n # Divide out number of points to get average.\n result.setLen(inputPoints.len)\n for i, tp in tempPoints:\n result[i] = tp.p / tp.n.toFloat\n\n#---------------------------------------------------------------------------------------------------\n\nfunc getPointsFaces(inputPoints: seq[Point]; inputFaces: seq[Face]): seq[int] =\n # Return the number of faces for each point.\n\n result.setLen(inputPoints.len)\n\n # Loop through faces updating the result.\n for pointNums in inputFaces:\n for pointNum in pointNums:\n inc result[pointNum]\n\n#---------------------------------------------------------------------------------------------------\n\nfunc getNewPoints(inputPoints: seq[Point]; pointsFaces: seq[int];\n avgFacePoints, avgMidEdges: seq[Point]): seq[Point] =\n ## m1 = (n - 3.0) / n\n ## m2 = 1.0 / n\n ## m3 = 2.0 / n\n ## newCoords = (m1 * oldCoords) + (m2 * avgFacePoints) + (m3 * avgMidEdges)\n\n result.setLen(inputPoints.len)\n for pointNum, oldCoords in inputPoints:\n let n = pointsFaces[pointNum].toFloat\n let (m1, m2, m3) = ((n - 3) / n, 1 / n, 2 / n)\n let p1 = oldCoords * m1\n let afp = avgFacePoints[pointNum]\n let p2 = afp * m2\n let ame = avgMidEdges[pointNum]\n let p3 = ame * m3\n let p4 = p1 + p2\n result[pointNum] = p4 + p3\n\n#---------------------------------------------------------------------------------------------------\n\nfunc switchNums(pointNums: PointNums): PointNums =\n ## Return tuple of point numbers sorted least to most.\n\n if pointNums.pn1 < pointNums.pn2: pointNums\n else: (pointNums.pn2, pointNums.pn1)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc cmcSubdiv(inputPoints: seq[Point];\n inputFaces: seq[Face]): tuple[p: seq[Point], f: seq[Face]] =\n ## For each face, a face point is created which is the average of all the points of the face.\n ## Each entry in the returned list is a point (x, y, z).\n\n let facePoints = getFacePoints(inputPoints, inputFaces)\n let edgesFaces = getEdgesFaces(inputPoints, inputFaces)\n let edgePoints = getEdgePoints(inputPoints, edgesFaces, facePoints)\n let avgFacePoints = getAvgFacePoints(inputPoints, inputFaces, facePoints)\n let avgMidEdges = getAvgMidEdges(inputPoints, edgesFaces)\n let pointsFaces = getPointsFaces(inputPoints, inputFaces)\n var newPoints = getNewPoints(inputPoints, pointsFaces, avgFacePoints, avgMidEdges)\n\n #[Then each face is replaced by new faces made with the new points,\n\n for a triangle face (a,b,c):\n (a, edgePoint ab, facePoint abc, edgePoint ca)\n (b, edgePoint bc, facePoint abc, edgePoint ab)\n (c, edgePoint ca, facePoint abc, edgePoint bc)\n\n for a quad face (a,b,c,d):\n (a, edgePoint ab, facePoint abcd, edgePoint da)\n (b, edgePoint bc, facePoint abcd, edgePoint ab)\n (c, edgePoint cd, facePoint abcd, edgePoint bc)\n (d, edgePoint da, facePoint abcd, edgePoint cd)\n\n facePoints is a list indexed by face number so that is easy to get.\n\n edgePoints is a list indexed by the edge number which is an index into edgesFaces.\n\n Need to add facePoints and edgePoints to newPoints and get index into each.\n\n Then create two new structures:\n\n facePointNums: list indexes by faceNum whose value is the index into newPoints.\n\n edgePointNums: dictionary with key (pointNum1, pointNum2) and value is index into newPoints.\n ]#\n\n # Add face points to newPoints.\n var facePointNums: seq[int]\n var nextPointNum = newPoints.len # PointNum after next append to newPoints.\n for facePoint in facePoints:\n newPoints.add(facePoint)\n facePointNums.add(nextPointNum)\n inc nextPointNum\n\n # Add edge points to newPoints.\n var edgePointNums: Table[tuple[pn1, pn2: int], int]\n for edgeNum, edgesFace in edgesFaces:\n let pointNum1 = edgesFace.pn1\n let pointNum2 = edgesFace.pn2\n newPoints.add(edgePoints[edgeNum])\n edgePointNums[(pointNum1, pointNum2)] = nextPointNum\n inc nextPointNum\n\n # newPoints now has the points to output. Need new faces.\n\n #[Just doing this case for now:\n\n for a quad face (a,b,c,d):\n (a, edgePoint ab, facePoint abcd, edgePoint da)\n (b, edgePoint bc, facePoint abcd, edgePoint ab)\n (c, edgePoint cd, facePoint abcd, edgePoint bc)\n (d, edgePoint da, facePoint abcd, edgePoint cd)\n\n newFaces will be a list of lists where the elements are like this:\n [pointNum1, pointNum2, pointNum3, pointNum4]\n ]#\n\n var newFaces: seq[Face]\n for oldFaceNum, oldFace in inputFaces:\n # 4 points face.\n if oldFace.len == 4:\n let (a, b, c, d) = (oldFace[0], oldface[1], oldface[2], oldface[3])\n let facePointAbcd = facePointNums[oldFaceNum]\n let edgePointAb = edgePointNums[switchNums((a, b))]\n let edgePointDa = edgePointNums[switchNums((d, a))]\n let edgePointBc = edgePointNums[switchNums((b, c))]\n let edgePointCd = edgePointNums[switchNums((c, d))]\n newFaces &= @[a, edgePointAb, facePointAbcd, edgePointDa]\n newFaces &= @[b, edgePointBc, facePointAbcd, edgePointAb]\n newFaces &= @[c, edgePointCd, facePointAbcd, edgePointBc]\n newFaces &= @[d, edgePointDa, facePointAbcd, edgePointCd]\n\n result = (newPoints, newFaces)\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nwhen isMainModule:\n\n import strformat, strutils\n\n let inputPoints = @[[-1.0, 1.0, 1.0],\n [-1.0, -1.0, 1.0],\n [1.0, -1.0, 1.0],\n [1.0, 1.0, 1.0],\n [1.0, -1.0, -1.0],\n [1.0, 1.0, -1.0],\n [-1.0, -1.0, -1.0],\n [-1.0, 1.0, -1.0]]\n\n let inputFaces = @[@[0, 1, 2, 3],\n @[3, 2, 4, 5],\n @[5, 4, 6, 7],\n @[7, 0, 3, 5],\n @[7, 6, 1, 0],\n @[6, 1, 2, 4]]\n\n var outputPoints = inputPoints\n var outputFaces = inputFaces\n const Iterations = 1\n\n for i in 1..Iterations:\n (outputPoints, outputFaces) = cmcSubdiv(outputPoints, outputFaces)\n\n for p in outputPoints:\n echo fmt\"[{p[0]: .4f}, {p[1]: .4f}, {p[2]: .4f}]\"\n echo \"\"\n for nums in outputFaces:\n var s = \"[\"\n for n in nums:\n s.addSep(\", \", 1)\n s.add(fmt\"{n:2d}\")\n s.add(']')\n echo s\n", "language": "Nim" }, { "code": "open Dynar\n\nlet add3 (x1, y1, z1) (x2, y2, z2) (x3, y3, z3) =\n ( (x1 +. x2 +. x3),\n (y1 +. y2 +. y3),\n (z1 +. z2 +. z3) )\n\nlet mul m (x,y,z) = (m *. x, m *. y, m *. z)\n\nlet avg pts =\n let n, (x,y,z) =\n List.fold_left\n (fun (n, (xt,yt,zt)) (xi,yi,zi) ->\n succ n, (xt +. xi, yt +. yi, zt +. zi))\n (1, List.hd pts) (List.tl pts)\n in\n let n = float_of_int n in\n (x /. n, y /. n, z /. n)\n\n\nlet catmull ~points ~faces =\n let da_points = Dynar.of_array points in\n let new_faces = Dynar.of_array [| |] in\n let push_face face = Dynar.push new_faces face in\n let h1 = Hashtbl.create 43 in\n let h2 = Hashtbl.create 43 in\n let h3 = Hashtbl.create 43 in\n let h4 = Hashtbl.create 43 in\n let blg = Array.make (Array.length points) 0 in (* how many faces a point belongs to *)\n let f_incr p = blg.(p) <- succ blg.(p) in\n let eblg = Array.make (Array.length points) 0 in (* how many edges a point belongs to *)\n let e_incr p = eblg.(p) <- succ eblg.(p) in\n let edge a b = (min a b, max a b) in (* suitable for hash-table keys *)\n let mid_edge p1 p2 =\n let x1, y1, z1 = points.(p1)\n and x2, y2, z2 = points.(p2) in\n ( (x1 +. x2) /. 2.0,\n (y1 +. y2) /. 2.0,\n (z1 +. z2) /. 2.0 )\n in\n let mid_face p1 p2 p3 p4 =\n let x1, y1, z1 = points.(p1)\n and x2, y2, z2 = points.(p2)\n and x3, y3, z3 = points.(p3)\n and x4, y4, z4 = points.(p4) in\n ( (x1 +. x2 +. x3 +. x4) /. 4.0,\n (y1 +. y2 +. y3 +. y4) /. 4.0,\n (z1 +. z2 +. z3 +. z4) /. 4.0 )\n in\n Array.iteri (fun i (a,b,c,d) ->\n f_incr a; f_incr b; f_incr c; f_incr d;\n\n let face_point = mid_face a b c d in\n let face_pi = pushi da_points face_point in\n Hashtbl.add h3 a face_point;\n Hashtbl.add h3 b face_point;\n Hashtbl.add h3 c face_point;\n Hashtbl.add h3 d face_point;\n\n let process_edge a b =\n let ab = edge a b in\n if not(Hashtbl.mem h1 ab)\n then begin\n let mid_ab = mid_edge a b in\n let index = pushi da_points mid_ab in\n Hashtbl.add h1 ab (index, mid_ab, [face_point]);\n Hashtbl.add h2 a mid_ab;\n Hashtbl.add h2 b mid_ab;\n Hashtbl.add h4 mid_ab 1;\n (index)\n end\n else begin\n let index, mid_ab, fpl = Hashtbl.find h1 ab in\n Hashtbl.replace h1 ab (index, mid_ab, face_point::fpl);\n Hashtbl.add h4 mid_ab (succ(Hashtbl.find h4 mid_ab));\n (index)\n end\n in\n let mid_ab = process_edge a b\n and mid_bc = process_edge b c\n and mid_cd = process_edge c d\n and mid_da = process_edge d a in\n\n push_face (a, mid_ab, face_pi, mid_da);\n push_face (b, mid_bc, face_pi, mid_ab);\n push_face (c, mid_cd, face_pi, mid_bc);\n push_face (d, mid_da, face_pi, mid_cd);\n ) faces;\n\n Hashtbl.iter (fun (a,b) (index, mid_ab, fpl) ->\n e_incr a; e_incr b;\n if List.length fpl = 2 then\n da_points.ar.(index) <- avg (mid_ab::fpl)\n ) h1;\n\n Array.iteri (fun i old_vertex ->\n let n = blg.(i)\n and e_n = eblg.(i) in\n (* if the vertex doesn't belongs to as many faces than edges\n this means that this is a hole *)\n if n = e_n then\n begin\n let avg_face_points =\n let face_point_list = Hashtbl.find_all h3 i in\n (avg face_point_list)\n in\n let avg_mid_edges =\n let mid_edge_list = Hashtbl.find_all h2 i in\n (avg mid_edge_list)\n in\n let n = float_of_int n in\n let m1 = (n -. 3.0) /. n\n and m2 = 1.0 /. n\n and m3 = 2.0 /. n in\n da_points.ar.(i) <-\n add3 (mul m1 old_vertex)\n (mul m2 avg_face_points)\n (mul m3 avg_mid_edges)\n end\n else begin\n let mid_edge_list = Hashtbl.find_all h2 i in\n let mid_edge_list =\n (* only average mid-edges near the hole *)\n List.fold_left (fun acc mid_edge ->\n match Hashtbl.find h4 mid_edge with\n | 1 -> mid_edge::acc\n | _ -> acc\n ) [] mid_edge_list\n in\n da_points.ar.(i) <- avg (old_vertex :: mid_edge_list)\n end\n ) points;\n\n (Dynar.to_array da_points,\n Dynar.to_array new_faces)\n;;\n", "language": "OCaml" }, { "code": "type point = { x: float; y : float; z : float }\nlet zero = { x = 0.0; y = 0.0; z = 0.0 }\nlet add a b = { x = a.x+.b.x; y = a.y+.b.y; z = a.z+.b.z }\nlet mul a k = { x = a.x*.k; y = a.y*.k; z= a.z*.k }\nlet div p k = mul p (1.0/.k)\n\ntype face = Face of point list\ntype edge = Edge of point*point\n\nlet make_edge a b = Edge (min a b, max a b)\nlet make_face a b c d = Face [a;b;c;d]\n\nlet centroid plist = div (List.fold_left add zero plist) (float (List.length plist))\nlet mid_edge (Edge (p1,p2)) = div (add p1 p2) 2.0\nlet face_point (Face pl) = centroid pl\nlet point_in_face p (Face pl) = List.mem p pl\nlet point_in_edge p (Edge (p1,p2)) = p = p1 || p = p2\nlet edge_in_face (Edge (p1,p2)) f = point_in_face p1 f && point_in_face p2 f\n\nlet border_edge faces e =\n List.length (List.filter (edge_in_face e) faces) < 2\n\nlet edge_point faces e =\n if border_edge faces e then mid_edge e else\n let adjacent = List.filter (edge_in_face e) faces in\n let fps = List.map face_point adjacent in\n centroid [mid_edge e; centroid fps]\n\nlet mod_vertex faces edges p =\n let v_edges = List.filter (point_in_edge p) edges in\n let v_faces = List.filter (point_in_face p) faces in\n let n = List.length v_faces in\n let is_border = n <> (List.length v_edges) in\n if is_border then\n let border_mids = List.map mid_edge (List.filter (border_edge faces) v_edges) in\n (* description ambiguity: average (border+p) or average(average(border),p) ?? *)\n centroid (p :: border_mids)\n else\n let avg_face = centroid (List.map face_point v_faces) in\n let avg_mid = centroid (List.map mid_edge v_edges) in\n div (add (add (mul p (float(n-3))) avg_face) (mul avg_mid 2.0)) (float n)\n\nlet edges_of_face (Face pl) =\n let rec next acc = function\n | [] -> invalid_arg \"empty face\"\n | a :: [] -> List.rev (make_edge a (List.hd pl) :: acc)\n | a :: (b :: _ as xs) -> next (make_edge a b :: acc) xs in\n next [] pl\n\nlet catmull_clark faces =\n let module EdgeSet = Set.Make(struct type t = edge let compare = compare end) in\n let edges = EdgeSet.elements (EdgeSet.of_list (List.concat (List.map edges_of_face faces))) in\n let mod_face ((Face pl) as face) =\n let fp = face_point face in\n let ep = List.map (edge_point faces) (edges_of_face face) in\n let e_tl = List.hd (List.rev ep) in\n let vl = List.map (mod_vertex faces edges) pl in\n let add_facet (e', acc) v e = e, (make_face e' v e fp :: acc) in\n let _, new_faces = List.fold_left2 add_facet (e_tl, []) vl ep in\n List.rev new_faces in\n List.concat (List.map mod_face faces)\n\nlet show_faces fl =\n let pr_point p = Printf.printf \" (%.4f, %.4f, %.4f)\" p.x p.y p.z in\n let pr_face (Face pl) = print_string \"Face:\"; List.iter pr_point pl; print_string \"\\n\" in\n (print_string \"surface {\\n\"; List.iter pr_face fl; print_string \"}\\n\")\n\nlet c p q r = let s i = if i = 0 then -1.0 else 1.0 in { x = s p; y = s q; z = s r } ;;\nlet cube = [\n Face [c 0 0 0; c 0 0 1; c 0 1 1; c 0 1 0]; Face [c 1 0 0; c 1 0 1; c 1 1 1; c 1 1 0];\n Face [c 0 0 0; c 1 0 0; c 1 0 1; c 0 0 1]; Face [c 0 1 0; c 1 1 0; c 1 1 1; c 0 1 1];\n Face [c 0 0 0; c 0 1 0; c 1 1 0; c 1 0 0]; Face [c 0 0 1; c 0 1 1; c 1 1 1; c 1 0 1] ] in\nshow_faces cube;\nshow_faces (catmull_clark cube)\n", "language": "OCaml" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">-- demo\\rosetta\\Catmull_Clark_subdivision_surface.exw</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">newPoint</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">newPointEx</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">newPoint</span><span style=\"color: #0000FF;\">(),</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">centerPoint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">p1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">p2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">sq_div</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">p2</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">getFacePoints</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">facePoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">currFace</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">facePoint</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">currFace</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">currFace</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">facePoint</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">facePoint</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">currFace</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">facePoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_div</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">facePoint</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">currFace</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">facePoints</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">getEdgesFaces</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">edges</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">faceNum</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">face</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">faceNum</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">numPoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">face</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">pointIndex</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">numPoints</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">pointNum1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">face</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">pointIndex</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">pointNum2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">face</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pointIndex</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">numPoints</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">pointIndex</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">pointNum1</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #000000;\">pointNum2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">pointNum1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">pointNum2</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">pointNum2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">pointNum1</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">edges</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">edges</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">pointNum1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">pointNum2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">faceNum</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">edges</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sort</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">edges</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">numEdges</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">edges</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">eIndex</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">mergedEdges</span> <span style=\"color: #0000FF;\">={}</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">eIndex</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">numEdges</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">e1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">edges</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">eIndex</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">e4</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">eIndex</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">numEdges</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">e1</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]==</span><span style=\"color: #000000;\">edges</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">eIndex</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">e4</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">edges</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">eIndex</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">eIndex</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">e1</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">e4</span>\n <span style=\"color: #000000;\">mergedEdges</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mergedEdges</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">e1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">eIndex</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">edgesCenters</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mergedEdges</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">me</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mergedEdges</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]),</span>\n <span style=\"color: #000000;\">cp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">centerPoint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">me</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]],</span>\n <span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">me</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]])</span>\n <span style=\"color: #000000;\">me</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">me</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cp</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">edgesCenters</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">edgesCenters</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">me</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">edgesCenters</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">getEdgePoints</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">edgesFaces</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">facePoints</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">edgePoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">edgesFaces</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">edgesFaces</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">edge</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">edgesFaces</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">cp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">edge</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">fp1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">facePoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">edge</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">]],</span>\n <span style=\"color: #000000;\">fp2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">edge</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">]=-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">fp1</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">facePoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">edge</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">]]),</span>\n <span style=\"color: #000000;\">cfp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">centerPoint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fp1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">fp2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">edgePoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">centerPoint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cp</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cfp</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">edgePoints</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">getAvgFacePoints</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">facePoints</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">numPoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tempPoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">newPointEx</span><span style=\"color: #0000FF;\">(),</span><span style=\"color: #000000;\">numPoints</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">faceNum</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">fp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">facePoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">faceNum</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">faceNum</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">pointNum</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">faceNum</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tempPoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">pointNum</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">tempPoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">pointNum</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tp</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">fp</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">tempPoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">pointNum</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">avgFacePoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">numPoints</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tempPoints</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tempPoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">avgFacePoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_div</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tp</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">tp</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">avgFacePoints</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">getAvgMidEdges</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">edgesFaces</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">numPoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tempPoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">newPointEx</span><span style=\"color: #0000FF;\">(),</span> <span style=\"color: #000000;\">numPoints</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">edgesFaces</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">edge</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">edgesFaces</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">cp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">edge</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">edx</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">pointNum</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">edge</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">edx</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tempPoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">pointNum</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">tempPoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">pointNum</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tp</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cp</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">tempPoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">pointNum</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">avgMidEdges</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tempPoints</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tempPoints</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tempPoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">avgMidEdges</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_div</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tp</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">tp</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">avgMidEdges</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">getPointsFaces</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">numPoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">pointsFaces</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">numPoints</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">faceNum</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">faceNum</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">pointNum</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">faceNum</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">pointsFaces</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">pointNum</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">pointsFaces</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">getNewPoints</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">pointsFaces</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">avgFacePoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">avgMidEdges</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">newPoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">pointNum</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">pointsFaces</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">pointNum</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">p1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">pointNum</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">p2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">avgFacePoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">pointNum</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">p3</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">avgMidEdges</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">pointNum</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">newPoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">pointNum</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">p2</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">p3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">newPoints</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">switchNums</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">pointNums</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">pointNums</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\"><</span> <span style=\"color: #000000;\">pointNums</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">pointNums</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">pointNums</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">pointNums</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">cmcSubdiv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">facePoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">getFacePoints</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">edgesFaces</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">getEdgesFaces</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">edgePoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">getEdgePoints</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">edgesFaces</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">facePoints</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">avgFacePoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">getAvgFacePoints</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">facePoints</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">avgMidEdges</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">getAvgMidEdges</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">edgesFaces</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">pointsFaces</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">getPointsFaces</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">newPoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">getNewPoints</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">pointsFaces</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">avgFacePoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">avgMidEdges</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">facePointNums</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">nextPointNum</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">newPoints</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">facePoints</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">facePoint</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">facePoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">newPoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">newPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">facePoint</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">facePointNums</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">facePointNums</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nextPointNum</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">nextPointNum</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">edgePointNums</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">new_dict</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">edgeNum</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">edgesFaces</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">pointNum1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">pointNum2</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">edgesFaces</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">edgeNum</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">edgePoint</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">edgePoints</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">edgeNum</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">newPoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">newPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">edgePoint</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">setd</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">pointNum1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">pointNum2</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #000000;\">nextPointNum</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">edgePointNums</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">nextPointNum</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">newFaces</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">oldFaceNum</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">oldFace</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">oldFaceNum</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">oldFace</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">==</span> <span style=\"color: #000000;\">4</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">oldFace</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">facePointAbcd</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">facePointNums</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">oldFaceNum</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">edgePointAb</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">getd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">switchNums</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">}),</span><span style=\"color: #000000;\">edgePointNums</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">edgePointDa</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">getd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">switchNums</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">}),</span><span style=\"color: #000000;\">edgePointNums</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">edgePointBc</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">getd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">switchNums</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">}),</span><span style=\"color: #000000;\">edgePointNums</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">edgePointCd</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">getd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">switchNums</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">}),</span><span style=\"color: #000000;\">edgePointNums</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">newFaces</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">newFaces</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">edgePointAb</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">facePointAbcd</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">edgePointDa</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">newFaces</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">newFaces</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">edgePointBc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">facePointAbcd</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">edgePointAb</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">newFaces</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">newFaces</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">edgePointCd</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">facePointAbcd</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">edgePointBc</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">newFaces</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">newFaces</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">edgePointDa</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">facePointAbcd</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">edgePointCd</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">newPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">newFaces</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">inputPoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}},</span>\n\n <span style=\"color: #000000;\">inputFaces</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">}}</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">outputPoints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">inputPoints</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">outputFaces</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inputFaces</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">iterations</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">iterations</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">outputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">outputFaces</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">cmcSubdiv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">outputPoints</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">outputFaces</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">ppOpt</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #004600;\">pp_Nest</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">pp_FltFmt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%7.4f\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">pp_IntFmt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%7.4f\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">pp_IntCh</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">pp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">outputPoints</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">pp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_sub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">outputFaces</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),{</span><span style=\"color: #004600;\">pp_IntFmt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%2d\"</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "\"\"\"\n\nInput and output are assumed to be in this form based on the talk\npage for the task:\n\ninput_points = [\n [-1.0, 1.0, 1.0],\n [-1.0, -1.0, 1.0],\n [ 1.0, -1.0, 1.0],\n [ 1.0, 1.0, 1.0],\n [ 1.0, -1.0, -1.0],\n [ 1.0, 1.0, -1.0],\n [-1.0, -1.0, -1.0],\n [-1.0, 1.0, -1.0]\n]\n\ninput_faces = [\n [0, 1, 2, 3],\n [3, 2, 4, 5],\n [5, 4, 6, 7],\n [7, 0, 3, 5],\n [7, 6, 1, 0],\n [6, 1, 2, 4],\n]\n\nSo, the graph is a list of points and a list of faces.\nEach face is a list of indexes into the points list.\n\n\"\"\"\n\nfrom mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\n\ndef center_point(p1, p2):\n \"\"\"\n returns a point in the center of the\n segment ended by points p1 and p2\n \"\"\"\n cp = []\n for i in range(3):\n cp.append((p1[i]+p2[i])/2)\n\n return cp\n\ndef sum_point(p1, p2):\n \"\"\"\n adds points p1 and p2\n \"\"\"\n sp = []\n for i in range(3):\n sp.append(p1[i]+p2[i])\n\n return sp\n\ndef div_point(p, d):\n \"\"\"\n divide point p by d\n \"\"\"\n sp = []\n for i in range(3):\n sp.append(p[i]/d)\n\n return sp\n\ndef mul_point(p, m):\n \"\"\"\n multiply point p by m\n \"\"\"\n sp = []\n for i in range(3):\n sp.append(p[i]*m)\n\n return sp\n\ndef get_face_points(input_points, input_faces):\n \"\"\"\n From http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface\n\n 1. for each face, a face point is created which is the average of all the points of the face.\n \"\"\"\n\n # 3 dimensional space\n\n NUM_DIMENSIONS = 3\n\n # face_points will have one point for each face\n\n face_points = []\n\n for curr_face in input_faces:\n face_point = [0.0, 0.0, 0.0]\n for curr_point_index in curr_face:\n curr_point = input_points[curr_point_index]\n # add curr_point to face_point\n # will divide later\n for i in range(NUM_DIMENSIONS):\n face_point[i] += curr_point[i]\n # divide by number of points for average\n num_points = len(curr_face)\n for i in range(NUM_DIMENSIONS):\n face_point[i] /= num_points\n face_points.append(face_point)\n\n return face_points\n\ndef get_edges_faces(input_points, input_faces):\n \"\"\"\n\n Get list of edges and the one or two adjacent faces in a list.\n also get center point of edge\n\n Each edge would be [pointnum_1, pointnum_2, facenum_1, facenum_2, center]\n\n \"\"\"\n\n # will have [pointnum_1, pointnum_2, facenum]\n\n edges = []\n\n # get edges from each face\n\n for facenum in range(len(input_faces)):\n face = input_faces[facenum]\n num_points = len(face)\n # loop over index into face\n for pointindex in range(num_points):\n # if not last point then edge is curr point and next point\n if pointindex < num_points - 1:\n pointnum_1 = face[pointindex]\n pointnum_2 = face[pointindex+1]\n else:\n # for last point edge is curr point and first point\n pointnum_1 = face[pointindex]\n pointnum_2 = face[0]\n # order points in edge by lowest point number\n if pointnum_1 > pointnum_2:\n temp = pointnum_1\n pointnum_1 = pointnum_2\n pointnum_2 = temp\n edges.append([pointnum_1, pointnum_2, facenum])\n\n # sort edges by pointnum_1, pointnum_2, facenum\n\n edges = sorted(edges)\n\n # merge edges with 2 adjacent faces\n # [pointnum_1, pointnum_2, facenum_1, facenum_2] or\n # [pointnum_1, pointnum_2, facenum_1, None]\n\n num_edges = len(edges)\n eindex = 0\n merged_edges = []\n\n while eindex < num_edges:\n e1 = edges[eindex]\n # check if not last edge\n if eindex < num_edges - 1:\n e2 = edges[eindex+1]\n if e1[0] == e2[0] and e1[1] == e2[1]:\n merged_edges.append([e1[0],e1[1],e1[2],e2[2]])\n eindex += 2\n else:\n merged_edges.append([e1[0],e1[1],e1[2],None])\n eindex += 1\n else:\n merged_edges.append([e1[0],e1[1],e1[2],None])\n eindex += 1\n\n # add edge centers\n\n edges_centers = []\n\n for me in merged_edges:\n p1 = input_points[me[0]]\n p2 = input_points[me[1]]\n cp = center_point(p1, p2)\n edges_centers.append(me+[cp])\n\n return edges_centers\n\ndef get_edge_points(input_points, edges_faces, face_points):\n \"\"\"\n for each edge, an edge point is created which is the average\n between the center of the edge and the center of the segment made\n with the face points of the two adjacent faces.\n \"\"\"\n\n edge_points = []\n\n for edge in edges_faces:\n # get center of edge\n cp = edge[4]\n # get center of two facepoints\n fp1 = face_points[edge[2]]\n # if not two faces just use one facepoint\n # should not happen for solid like a cube\n if edge[3] == None:\n fp2 = fp1\n else:\n fp2 = face_points[edge[3]]\n cfp = center_point(fp1, fp2)\n # get average between center of edge and\n # center of facepoints\n edge_point = center_point(cp, cfp)\n edge_points.append(edge_point)\n\n return edge_points\n\ndef get_avg_face_points(input_points, input_faces, face_points):\n \"\"\"\n\n for each point calculate\n\n the average of the face points of the faces the point belongs to (avg_face_points)\n\n create a list of lists of two numbers [facepoint_sum, num_points] by going through the\n points in all the faces.\n\n then create the avg_face_points list of point by dividing point_sum (x, y, z) by num_points\n\n \"\"\"\n\n # initialize list with [[0.0, 0.0, 0.0], 0]\n\n num_points = len(input_points)\n\n temp_points = []\n\n for pointnum in range(num_points):\n temp_points.append([[0.0, 0.0, 0.0], 0])\n\n # loop through faces updating temp_points\n\n for facenum in range(len(input_faces)):\n fp = face_points[facenum]\n for pointnum in input_faces[facenum]:\n tp = temp_points[pointnum][0]\n temp_points[pointnum][0] = sum_point(tp,fp)\n temp_points[pointnum][1] += 1\n\n # divide to create avg_face_points\n\n avg_face_points = []\n\n for tp in temp_points:\n afp = div_point(tp[0], tp[1])\n avg_face_points.append(afp)\n\n return avg_face_points\n\ndef get_avg_mid_edges(input_points, edges_faces):\n \"\"\"\n\n the average of the centers of edges the point belongs to (avg_mid_edges)\n\n create list with entry for each point\n each entry has two elements. one is a point that is the sum of the centers of the edges\n and the other is the number of edges. after going through all edges divide by\n number of edges.\n\n \"\"\"\n\n # initialize list with [[0.0, 0.0, 0.0], 0]\n\n num_points = len(input_points)\n\n temp_points = []\n\n for pointnum in range(num_points):\n temp_points.append([[0.0, 0.0, 0.0], 0])\n\n # go through edges_faces using center updating each point\n\n for edge in edges_faces:\n cp = edge[4]\n for pointnum in [edge[0], edge[1]]:\n tp = temp_points[pointnum][0]\n temp_points[pointnum][0] = sum_point(tp,cp)\n temp_points[pointnum][1] += 1\n\n # divide out number of points to get average\n\n avg_mid_edges = []\n\n for tp in temp_points:\n ame = div_point(tp[0], tp[1])\n avg_mid_edges.append(ame)\n\n return avg_mid_edges\n\ndef get_points_faces(input_points, input_faces):\n # initialize list with 0\n\n num_points = len(input_points)\n\n points_faces = []\n\n for pointnum in range(num_points):\n points_faces.append(0)\n\n # loop through faces updating points_faces\n\n for facenum in range(len(input_faces)):\n for pointnum in input_faces[facenum]:\n points_faces[pointnum] += 1\n\n return points_faces\n\ndef get_new_points(input_points, points_faces, avg_face_points, avg_mid_edges):\n \"\"\"\n\n m1 = (n - 3.0) / n\n m2 = 1.0 / n\n m3 = 2.0 / n\n new_coords = (m1 * old_coords)\n + (m2 * avg_face_points)\n + (m3 * avg_mid_edges)\n\n \"\"\"\n\n new_points =[]\n\n for pointnum in range(len(input_points)):\n n = points_faces[pointnum]\n m1 = (n - 3.0) / n\n m2 = 1.0 / n\n m3 = 2.0 / n\n old_coords = input_points[pointnum]\n p1 = mul_point(old_coords, m1)\n afp = avg_face_points[pointnum]\n p2 = mul_point(afp, m2)\n ame = avg_mid_edges[pointnum]\n p3 = mul_point(ame, m3)\n p4 = sum_point(p1, p2)\n new_coords = sum_point(p4, p3)\n\n new_points.append(new_coords)\n\n return new_points\n\ndef switch_nums(point_nums):\n \"\"\"\n Returns tuple of point numbers\n sorted least to most\n \"\"\"\n if point_nums[0] < point_nums[1]:\n return point_nums\n else:\n return (point_nums[1], point_nums[0])\n\ndef cmc_subdiv(input_points, input_faces):\n # 1. for each face, a face point is created which is the average of all the points of the face.\n # each entry in the returned list is a point (x, y, z).\n\n face_points = get_face_points(input_points, input_faces)\n\n # get list of edges with 1 or 2 adjacent faces\n # [pointnum_1, pointnum_2, facenum_1, facenum_2, center] or\n # [pointnum_1, pointnum_2, facenum_1, None, center]\n\n edges_faces = get_edges_faces(input_points, input_faces)\n\n # get edge points, a list of points\n\n edge_points = get_edge_points(input_points, edges_faces, face_points)\n\n # the average of the face points of the faces the point belongs to (avg_face_points)\n\n avg_face_points = get_avg_face_points(input_points, input_faces, face_points)\n\n # the average of the centers of edges the point belongs to (avg_mid_edges)\n\n avg_mid_edges = get_avg_mid_edges(input_points, edges_faces)\n\n # how many faces a point belongs to\n\n points_faces = get_points_faces(input_points, input_faces)\n\n \"\"\"\n\n m1 = (n - 3) / n\n m2 = 1 / n\n m3 = 2 / n\n new_coords = (m1 * old_coords)\n + (m2 * avg_face_points)\n + (m3 * avg_mid_edges)\n\n \"\"\"\n\n new_points = get_new_points(input_points, points_faces, avg_face_points, avg_mid_edges)\n\n \"\"\"\n\n Then each face is replaced by new faces made with the new points,\n\n for a triangle face (a,b,c):\n (a, edge_point ab, face_point abc, edge_point ca)\n (b, edge_point bc, face_point abc, edge_point ab)\n (c, edge_point ca, face_point abc, edge_point bc)\n\n for a quad face (a,b,c,d):\n (a, edge_point ab, face_point abcd, edge_point da)\n (b, edge_point bc, face_point abcd, edge_point ab)\n (c, edge_point cd, face_point abcd, edge_point bc)\n (d, edge_point da, face_point abcd, edge_point cd)\n\n face_points is a list indexed by face number so that is\n easy to get.\n\n edge_points is a list indexed by the edge number\n which is an index into edges_faces.\n\n need to add face_points and edge points to\n new_points and get index into each.\n\n then create two new structures\n\n face_point_nums - list indexes by facenum\n whose value is the index into new_points\n\n edge_point num - dictionary with key (pointnum_1, pointnum_2)\n and value is index into new_points\n\n \"\"\"\n\n # add face points to new_points\n\n face_point_nums = []\n\n # point num after next append to new_points\n next_pointnum = len(new_points)\n\n for face_point in face_points:\n new_points.append(face_point)\n face_point_nums.append(next_pointnum)\n next_pointnum += 1\n\n # add edge points to new_points\n\n edge_point_nums = dict()\n\n for edgenum in range(len(edges_faces)):\n pointnum_1 = edges_faces[edgenum][0]\n pointnum_2 = edges_faces[edgenum][1]\n edge_point = edge_points[edgenum]\n new_points.append(edge_point)\n edge_point_nums[(pointnum_1, pointnum_2)] = next_pointnum\n next_pointnum += 1\n\n # new_points now has the points to output. Need new\n # faces\n\n \"\"\"\n\n just doing this case for now:\n\n for a quad face (a,b,c,d):\n (a, edge_point ab, face_point abcd, edge_point da)\n (b, edge_point bc, face_point abcd, edge_point ab)\n (c, edge_point cd, face_point abcd, edge_point bc)\n (d, edge_point da, face_point abcd, edge_point cd)\n\n new_faces will be a list of lists where the elements are like this:\n\n [pointnum_1, pointnum_2, pointnum_3, pointnum_4]\n\n \"\"\"\n\n new_faces =[]\n\n for oldfacenum in range(len(input_faces)):\n oldface = input_faces[oldfacenum]\n # 4 point face\n if len(oldface) == 4:\n a = oldface[0]\n b = oldface[1]\n c = oldface[2]\n d = oldface[3]\n face_point_abcd = face_point_nums[oldfacenum]\n edge_point_ab = edge_point_nums[switch_nums((a, b))]\n edge_point_da = edge_point_nums[switch_nums((d, a))]\n edge_point_bc = edge_point_nums[switch_nums((b, c))]\n edge_point_cd = edge_point_nums[switch_nums((c, d))]\n new_faces.append((a, edge_point_ab, face_point_abcd, edge_point_da))\n new_faces.append((b, edge_point_bc, face_point_abcd, edge_point_ab))\n new_faces.append((c, edge_point_cd, face_point_abcd, edge_point_bc))\n new_faces.append((d, edge_point_da, face_point_abcd, edge_point_cd))\n\n return new_points, new_faces\n\n\ndef graph_output(output_points, output_faces):\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n \"\"\"\n\n Plot each face\n\n \"\"\"\n\n for facenum in range(len(output_faces)):\n curr_face = output_faces[facenum]\n xcurr = []\n ycurr = []\n zcurr = []\n for pointnum in range(len(curr_face)):\n xcurr.append(output_points[curr_face[pointnum]][0])\n ycurr.append(output_points[curr_face[pointnum]][1])\n zcurr.append(output_points[curr_face[pointnum]][2])\n xcurr.append(output_points[curr_face[0]][0])\n ycurr.append(output_points[curr_face[0]][1])\n zcurr.append(output_points[curr_face[0]][2])\n\n ax.plot(xcurr,ycurr,zcurr,color='b')\n\n plt.show()\n\n\n# cube\n\ninput_points = [\n [-1.0, 1.0, 1.0],\n [-1.0, -1.0, 1.0],\n [ 1.0, -1.0, 1.0],\n [ 1.0, 1.0, 1.0],\n [ 1.0, -1.0, -1.0],\n [ 1.0, 1.0, -1.0],\n [-1.0, -1.0, -1.0],\n [-1.0, 1.0, -1.0]\n]\n\ninput_faces = [\n [0, 1, 2, 3],\n [3, 2, 4, 5],\n [5, 4, 6, 7],\n [7, 0, 3, 5],\n [7, 6, 1, 0],\n [6, 1, 2, 4],\n]\n\nif len(sys.argv) != 2:\n print(\"Should have one argument integer number of iterations\")\n sys.exit()\nelse:\n iterations = int(sys.argv[1])\n\n output_points, output_faces = input_points, input_faces\n\n for i in range(iterations):\n output_points, output_faces = cmc_subdiv(output_points, output_faces)\n\ngraph_output(output_points, output_faces)\n", "language": "Python" }, { "code": "pub struct Vector3 {pub x: f64, pub y: f64, pub z: f64, pub w: f64}\n\npub struct Triangle {pub r: [usize; 3], pub(crate) col: [f32; 4], pub(crate) p: [Vector3; 3], n: Vector3, pub t: [Vector2; 3]}\npub struct Mesh{pub v: Vec<Vector3>, pub f: Vec<Triangle>}\n\nimpl Triangle{\n pub fn new() -> Triangle {return Triangle {r: [0, 0, 0], col: [0.0; 4], p: [Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0)], n: Vector3::new(0.0, 0.0, 0.0), t: [Vector2::new(0.0, 0.0), Vector2::new(0.0, 0.0), Vector2::new(0.0, 0.0)]}}\n pub fn copy(&self) -> Triangle {return Triangle {r: self.r.clone(), col: self.col, p: [self.p[0].copy(), self.p[1].copy(), self.p[2].copy()], n: self.n.copy(), t: [self.t[0].copy(), self.t[1].copy(), self.t[2].copy()]}}\n}\n\n\nimpl Vector3 {\n pub fn new(x: f64, y: f64, z: f64) -> Vector3 {return Vector3 {x, y, z, w: 1.0}}\n pub fn normalize(&mut self) {\n let l = (self.x * self.x + self.y * self.y + self.z * self.z).sqrt();\n self.x /= l;\n self.y /= l;\n self.z /= l;\n }\n pub fn dot_product(v1: &Vector3, v2: &Vector3) -> f64 {return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z}\n pub fn cross_product(v1: &Vector3, v2: &Vector3) -> Vector3 {return Vector3::new(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y - v1.y * v2.x)}\n pub fn intersect_plane(plane_n: &Vector3, plane_p: &Vector3, line_start: &Vector3, line_end: &Vector3, mut t: f64) -> Vector3 {\n let mut p_n = plane_n.copy();\n\n p_n.normalize();\n let plane_d = -Vector3::dot_product(&p_n, plane_p);\n let ad = Vector3::dot_product(line_start, &p_n);\n let bd = Vector3::dot_product(line_end, &p_n);\n t = (-plane_d - ad) / (bd - ad);\n let line = line_end.copy() - line_start;\n let line_i = line * t;\n return line_start.copy() + &line_i;\n }\n pub fn copy(&self) -> Vector3 {return Vector3 {x: self.x, y: self.y, z: self.z, w: self.w}}\n}\n\nimpl Mesh {\n pub fn get_face_points(&self) -> Vec<Vector3> {\n let mut face_points: Vec<Vector3> = Vec::new();\n\n for curr_face in &self.f {\n let mut face_point = Vector3::new(0.0, 0.0, 0.0);\n for curr_point_index in curr_face.r {\n let curr_point = &self.v[curr_point_index];\n face_point += &curr_point\n }\n\n face_point /= curr_face.r.len() as f64;\n face_points.push(face_point.copy());\n }\n return face_points;\n }\n pub fn get_edges_faces(&self) -> Vec<[f64; 7]> {\n let mut edges: Vec<[usize; 3]> = Vec::new();\n\n for face_num in 0..self.f.len() {\n let face: Triangle = self.f[face_num].copy();\n let num_points = face.p.len();\n for point_index in 0..num_points {\n let mut point_num_1 = 0;\n let mut point_num_2 = 0;\n if point_index < num_points - 1 {\n point_num_1 = face.r[point_index];\n point_num_2 = face.r[point_index + 1];\n } else {\n point_num_1 = face.r[point_index];\n point_num_2 = face.r[0];\n }\n if point_num_1 > point_num_2 {\n let temp = point_num_1;\n point_num_1 = point_num_2;\n point_num_2 = temp;\n }\n edges.push([point_num_1, point_num_2, face_num]);\n }\n }\n edges.sort();\n\n let num_edges = edges.len();\n let mut index = 0;\n let mut merged_edges: Vec<[f64; 4]> = Vec::new();\n\n while index < num_edges {\n let e1 = edges[index];\n if index < num_edges - 1 {\n let e2 = edges[index + 1];\n if e1[0] == e2[0] && e1[1] == e2[1] {\n merged_edges.push([e1[0] as f64, e1[1] as f64, e1[2] as f64, e2[2] as f64]);\n index += 2;\n } else {\n merged_edges.push([e1[0] as f64, e1[1] as f64, e1[2] as f64, -1.0]);\n index += 1;\n }\n } else {\n merged_edges.push([e1[0] as f64, e1[1] as f64, e1[2] as f64, -1.0]);\n index += 1\n }\n }\n\n let mut edges_centers = Vec::new();\n\n for me in merged_edges {\n let p1 = self.v[me[0] as usize].copy();\n let p2 = self.v[me[1] as usize].copy();\n let cp: Vector3 = Mesh::center_point(&p1, &p2);\n edges_centers.push([me[0] as f64, me[1] as f64, me[2] as f64, me[3] as f64, cp.x, cp.y, cp.z]);\n }\n return edges_centers;\n }\n pub fn get_edge_points(&self, edges_faces: &Vec<[f64; 7]>, face_points: &Vec<Vector3>) -> Vec<Vector3> {\n let mut edge_points = Vec::new();\n\n for edge in edges_faces {\n let cp = Vector3::new(edge[4], edge[5], edge[6]);\n let fp1: Vector3 = face_points[edge[2] as usize].copy();\n let mut fp2: Vector3 = fp1.copy();\n if edge[3] != -1.0 { fp2 = face_points[edge[3] as usize].copy() };\n let cfp = Mesh::center_point(&fp1, &fp2);\n let edge_point = Mesh::center_point(&cp, &cfp);\n edge_points.push(edge_point);\n }\n\n return edge_points\n }\n pub fn get_avg_face_points(&self, face_points: &Vec<Vector3>) -> Vec<Vector3> {\n let num_points = self.v.len();\n let mut temp_points = Vec::new();\n let mut div: Vec<i32> = Vec::new();\n\n for _ in 0..num_points {\n temp_points.push(Vector3::new(0.0, 0.0, 0.0));\n div.push(0)\n };\n\n for face_num in 0..self.f.len() {\n let mut fp = face_points[face_num].copy();\n for point_num in self.f[face_num].r {\n let tp = temp_points[point_num].copy();\n temp_points[point_num] = tp + &fp;\n div[point_num] += 1;\n }\n }\n\n let mut avg_face_points: Vec<Vector3> = Vec::new();\n for i in 0..temp_points.len() {\n let tp: Vector3 = temp_points[i].copy();\n let t = tp / (div[i] as f64);\n avg_face_points.push(t.copy());\n }\n\n return avg_face_points;\n }\n pub fn get_avg_mid_edges(&self, edges_faces: &Vec<[f64; 7]>) -> Vec<Vector3> {\n let num_points = self.v.len();\n let mut temp_points = Vec::new();\n let mut div: Vec<i32> = Vec::new();\n\n for point_num in 0..num_points{ temp_points.push(Vector3::new(0.0, 0.0, 0.0)); div.push(0)}\n for edge in edges_faces {\n let cp = Vector3::new(edge[4], edge[5], edge[6]);\n for point_num in [edge[0] as usize, edge[1] as usize] {\n let tp = temp_points[point_num].copy();\n temp_points[point_num] = tp + &cp;\n div[point_num] += 1\n }\n }\n\n let mut avg_mid_edges: Vec<Vector3> = Vec::new();\n\n for i in 0..temp_points.len(){\n let ame: Vector3 = temp_points[i].copy() / (div[i] as f64);\n avg_mid_edges.push(ame)}\n\n return avg_mid_edges\n }\n pub fn get_points_faces(&self) -> Vec<i32> {\n let num_points = self.v.len();\n let mut points_faces: Vec<i32> = Vec::new();\n\n for point_num in 0..num_points{points_faces.push(0)}\n\n for face_num in 0..self.f.len() {\n for point_num in self.f[face_num].r {\n points_faces[point_num] += 1;\n }\n }\n return points_faces\n }\n pub fn get_new_points(&self, points_faces: &Vec<i32>, avg_face_points: &Vec<Vector3>, avg_mid_edges: &Vec<Vector3>) -> Vec<Vector3> {\n let mut new_points: Vec<Vector3> = Vec::new();\n\n for point_num in 0..self.v.len() {\n let n = points_faces[point_num] as f64;\n let m1 = (n - 3.0) / n;\n let m2 = 1.0 / n;\n let m3 = 2.0 / n;\n let old_coords = self.v[point_num].copy();\n let p1 = old_coords * m1;\n let afp = avg_face_points[point_num].copy();\n let p2 = afp * m2;\n let ame = avg_mid_edges[point_num].copy();\n let p3 = ame * m3;\n let p4 = p1 + &p2;\n let new_coords = p4 + &p3;\n\n new_points.push(new_coords);\n }\n\n return new_points;\n }\n\n pub fn switch_nums(point_nums: [f64; 2]) -> [f64; 2] {\n return if point_nums[0] < point_nums[1] { point_nums } else {[point_nums[1], point_nums[0]]}\n }\n\n pub fn get_key(points: [f64; 2]) -> String {\n return points[0].to_string() + \";\" + &*points[1].to_string();\n }\n\n pub fn subdivide(&mut self) {\n let face_points = self.get_face_points();\n let edges_faces = self.get_edges_faces();\n let edge_points = self.get_edge_points(&edges_faces, &face_points);\n let avg_face_points = self.get_avg_face_points(&face_points);\n let avg_mid_edges = self.get_avg_mid_edges(&edges_faces);\n let points_faces = self.get_points_faces();\n let mut new_points = self.get_new_points(&points_faces, &avg_face_points, &avg_mid_edges);\n\n let mut face_point_nums = Vec::new();\n let mut next_point_num = new_points.len();\n\n for face_point in face_points {\n new_points.push(face_point);\n face_point_nums.push(next_point_num);\n next_point_num += 1;\n }\n\n let mut edge_point_nums: HashMap<String, usize> = HashMap::new();\n\n for edge_num in 0..edges_faces.len() {\n let point_num_1 = edges_faces[edge_num][0];\n let point_num_2 = edges_faces[edge_num][1];\n let edge_point = edge_points[edge_num].copy();\n new_points.push(edge_point);\n edge_point_nums.insert(Mesh::get_key([point_num_1, point_num_2]), next_point_num);\n next_point_num += 1;\n }\n\n let mut new_faces = Vec::new();\n\n for old_face_num in 0..self.f.len() {\n let old_face = self.f[old_face_num].copy();\n let a = old_face.r[0] as f64;\n let b = old_face.r[1] as f64;\n let c = old_face.r[2] as f64;\n let face_point_abc = face_point_nums[old_face_num];\n let edge_point_ab = *edge_point_nums.get(&*Mesh::get_key(Mesh::switch_nums([a, b]))).unwrap();\n let edge_point_bc = *edge_point_nums.get(&*Mesh::get_key(Mesh::switch_nums([b, c]))).unwrap();\n let edge_point_ca = *edge_point_nums.get(&*Mesh::get_key(Mesh::switch_nums([c, a]))).unwrap();\n new_faces.push([a, edge_point_ab as f64, face_point_abc as f64, edge_point_ca as f64]);\n new_faces.push([b, edge_point_bc as f64, face_point_abc as f64, edge_point_ab as f64]);\n new_faces.push([c, edge_point_ca as f64, face_point_abc as f64, edge_point_bc as f64]);\n }\n self.f = Vec::new();\n\n for face_num in 0..new_faces.len() {\n let curr_face = new_faces[face_num];\n let mut t1: Triangle = Triangle::new();\n let mut t2: Triangle = Triangle::new();\n t1.p[0] = Vector3::new(new_points[curr_face[0] as usize].x, new_points[curr_face[0] as usize].y, new_points[curr_face[0] as usize].z);\n t1.p[1] = Vector3::new(new_points[curr_face[1] as usize].x, new_points[curr_face[1] as usize].y, new_points[curr_face[1] as usize].z);\n t1.p[2] = Vector3::new(new_points[curr_face[2] as usize].x, new_points[curr_face[2] as usize].y, new_points[curr_face[2] as usize].z);\n t2.p[0] = Vector3::new(new_points[curr_face[2] as usize].x, new_points[curr_face[2] as usize].y, new_points[curr_face[2] as usize].z);\n t2.p[1] = Vector3::new(new_points[curr_face[3] as usize].x, new_points[curr_face[3] as usize].y, new_points[curr_face[3] as usize].z);\n t2.p[2] = Vector3::new(new_points[curr_face[0] as usize].x, new_points[curr_face[0] as usize].y, new_points[curr_face[0] as usize].z);\n t1.r = [curr_face[0] as usize, curr_face[1] as usize, curr_face[2] as usize];\n t2.r = [curr_face[2] as usize, curr_face[3] as usize, curr_face[0] as usize];\n self.f.push(t1);\n self.f.push(t2);\n }\n self.v = new_points;\n }\n}\n", "language": "Rust" }, { "code": "package require Tcl 8.5\n\n# Use math functions and operators as commands (Lisp-like).\nnamespace path {tcl::mathfunc tcl::mathop}\n\n# Add 3 points.\nproc add3 {A B C} {\n lassign $A Ax Ay Az\n lassign $B Bx By Bz\n lassign $C Cx Cy Cz\n list [+ $Ax $Bx $Cx] [+ $Ay $By $Cy] [+ $Az $Bz $Cz]\n}\n\n# Multiply a point by a constant.\nproc mulC {m A} {\n lassign $A x y z\n list [* $m $x] [* $m $y] [* $m $z]\n}\n\n# Take the centroid of a set of points.\n# Note that each of the arguments is a *list* of coordinate triples\n# This makes things easier later.\nproc centroid args {\n set x [set y [set z 0.0]]\n foreach plist $args {\n\tincr n [llength $plist]\n\tforeach p $plist {\n\t lassign $p px py pz\n\t set x [+ $x $px]\n\t set y [+ $y $py]\n\t set z [+ $z $pz]\n\t}\n }\n set n [double $n]\n list [/ $x $n] [/ $y $n] [/ $z $n]\n}\n\n# Select from the list the value from each of the indices in the *lists*\n# in the trailing arguments.\nproc selectFrom {list args} {\n foreach is $args {foreach i $is {lappend r [lindex $list $i]}}\n return $r\n}\n\n# Rotate a list.\nproc lrot {list {n 1}} {\n set n [% $n [llength $list]]\n list {*}[lrange $list $n end] {*}[lrange $list 0 [incr n -1]]\n}\n\n# Generate an edge by putting the smaller coordinate index first.\nproc edge {a b} {\n list [min $a $b] [max $a $b]\n}\n\n# Perform one step of Catmull-Clark subdivision of a surface.\nproc CatmullClark {points faces} {\n # Generate the new face-points and list of edges, plus some lookup tables.\n set edges {}\n foreach f $faces {\n\tset ps [selectFrom $points $f]\n\tset fp [centroid $ps]\n\tlappend facepoints $fp\n\tforeach p $ps {\n\t lappend fp4p($p) $fp\n\t}\n\tforeach p1 $f p2 [lrot $f] {\n\t set e [edge $p1 $p2]\n\t if {$e ni $edges} {\n\t\tlappend edges $e\n\t }\n\t lappend fp4e($e) $fp\n\t}\n }\n\n # Generate the new edge-points and mid-points of edges, and a few more\n # lookup tables.\n set i [+ [llength $points] [llength $faces]]\n foreach e $edges {\n\tset ep [selectFrom $points $e]\n\tif {[llength $fp4e($e)] > 1} {\n\t set mid [centroid $ep $fp4e($e)]\n\t} else {\n\t set mid [centroid $ep]\n\t foreach p $ep {\n\t\tlappend ep_heavy($p) $mid\n\t }\n\t}\n\tlappend edgepoints $mid\n\tset en4e($e) $i\n\tforeach p $ep {\n\t lappend ep4p($p) $mid\n\t}\n\tincr i\n }\n\n # Generate the new vertex points with our lookup tables.\n foreach p $points {\n\tif {[llength $fp4p($p)] >= 4} {\n\t set n [llength $fp4p($p)]\n\t lappend newPoints [add3 [mulC [/ [- $n 3.0] $n] $p] \\\n\t\t [mulC [/ 1.0 $n] [centroid $fp4p($p)]] \\\n\t\t [mulC [/ 2.0 $n] [centroid $ep4p($p)]]]\n\t} else {\n\t # Update a point on the edge of a hole. This formula is not\n\t # described on the WP page, but produces a nice result.\n\t lappend newPoints [centroid $ep_heavy($p) [list $p $p]]\n\t}\n }\n\n # Now compute the new set of quadrilateral faces.\n set i [llength $points]\n foreach f $faces {\n\tforeach a $f b [lrot $f] c [lrot $f -1] {\n\t lappend newFaces [list \\\n\t\t $a $en4e([edge $a $b]) $i $en4e([edge $c $a])]\n\t}\n\tincr i\n }\n\n list [concat $newPoints $facepoints $edgepoints] $newFaces\n}\n", "language": "Tcl" }, { "code": "import \"./dynamic\" for Tuple, Struct\nimport \"./sort\" for Sort\nimport \"./math\" for Int\nimport \"./fmt\" for Fmt\n\nvar Point = Tuple.create(\"Point\", [\"x\", \"y\", \"z\"])\nvar fields = [\n \"pn1\", // point number 1\n \"pn2\", // point number 2\n \"fn1\", // face number 1\n \"fn2\", // face number 2\n \"cp\" // center point\n]\nvar Edge = Tuple.create(\"Edge\", fields)\nvar PointEx = Struct.create(\"PointEx\", [\"p\", \"n\"])\n\nvar sumPoint = Fn.new { |p1, p2| Point.new(p1.x + p2.x, p1.y + p2.y, p1.z + p2.z) }\n\nvar mulPoint = Fn.new { |p, m| Point.new(p.x * m, p.y * m, p.z * m) }\n\nvar divPoint = Fn.new { |p, d| mulPoint.call(p, 1/d) }\n\nvar centerPoint = Fn.new { |p1, p2| divPoint.call(sumPoint.call(p1, p2), 2) }\n\nvar getFacePoints = Fn.new { |inputPoints, inputFaces|\n var facePoints = List.filled(inputFaces.count, null)\n var i = 0\n for (currFace in inputFaces) {\n var facePoint = Point.new(0, 0, 0)\n for (cpi in currFace) {\n var currPoint = inputPoints[cpi]\n facePoint = sumPoint.call(facePoint, currPoint)\n }\n facePoints[i] = divPoint.call(facePoint, currFace.count)\n i = i + 1\n }\n return facePoints\n}\n\nvar getEdgesFaces = Fn.new { |inputPoints, inputFaces|\n var edges = []\n var faceNum = 0\n for (face in inputFaces) {\n var numPoints = face.count\n for (pointIndex in 0...numPoints) {\n var pointNum1 = face[pointIndex]\n var pointNum2 = (pointIndex < numPoints-1) ? face[pointIndex+1] : face[0]\n if (pointNum1 > pointNum2) {\n var t = pointNum1\n pointNum1 = pointNum2\n pointNum2 = t\n }\n edges.add([pointNum1, pointNum2, faceNum])\n }\n faceNum = faceNum + 1\n }\n var cmp = Fn.new { |e1, e2|\n if (e1[0] == e2[0]) {\n if (e1[1] == e2[1]) return (e1[2] - e2[2]).sign\n return (e1[1] - e2[1]).sign\n }\n return (e1[0] - e2[0]).sign\n }\n var numEdges = edges.count\n Sort.quick(edges, 0, numEdges-1, cmp)\n var eIndex = 0\n var mergedEdges = []\n while (eIndex < numEdges) {\n var e1 = edges[eIndex]\n if (eIndex < numEdges-1) {\n var e2 = edges[eIndex+1]\n if (e1[0] == e2[0] && e1[1] == e2[1]) {\n mergedEdges.add([e1[0], e1[1], e1[2], e2[2]])\n eIndex = eIndex + 2\n } else {\n mergedEdges.add([e1[0], e1[1], e1[2], -1])\n eIndex = eIndex + 1\n }\n } else {\n mergedEdges.add([e1[0], e1[1], e1[2], -1])\n eIndex = eIndex + 1\n }\n }\n var edgesCenters = []\n for (me in mergedEdges) {\n var p1 = inputPoints[me[0]]\n var p2 = inputPoints[me[1]]\n var cp = centerPoint.call(p1, p2)\n edgesCenters.add(Edge.new(me[0], me[1], me[2], me[3], cp))\n }\n return edgesCenters\n}\n\nvar getEdgePoints = Fn.new { |inputPoints, edgesFaces, facePoints|\n var edgePoints = List.filled(edgesFaces.count, null)\n var i = 0\n for (edge in edgesFaces) {\n var cp = edge.cp\n var fp1 = facePoints[edge.fn1]\n var fp2 = (edge.fn2 == -1) ? fp1 : facePoints[edge.fn2]\n var cfp = centerPoint.call(fp1, fp2)\n edgePoints[i] = centerPoint.call(cp, cfp)\n i = i + 1\n }\n return edgePoints\n}\n\nvar getAvgFacePoints = Fn.new { |inputPoints, inputFaces, facePoints|\n var numPoints = inputPoints.count\n var tempPoints = List.filled(numPoints, null)\n for (i in 0...numPoints) tempPoints[i] = PointEx.new(Point.new(0, 0, 0), 0)\n for (faceNum in 0...inputFaces.count) {\n var fp = facePoints[faceNum]\n for (pointNum in inputFaces[faceNum]) {\n var tp = tempPoints[pointNum].p\n tempPoints[pointNum].p = sumPoint.call(tp, fp)\n tempPoints[pointNum].n = tempPoints[pointNum].n + 1\n }\n }\n var avgFacePoints = List.filled(numPoints, null)\n var i = 0\n for (tp in tempPoints) {\n avgFacePoints[i] = divPoint.call(tp.p, tp.n)\n i = i + 1\n }\n return avgFacePoints\n}\n\nvar getAvgMidEdges = Fn.new { |inputPoints, edgesFaces|\n var numPoints = inputPoints.count\n var tempPoints = List.filled(numPoints, null)\n for (i in 0...numPoints) tempPoints[i] = PointEx.new(Point.new(0, 0, 0), 0)\n for (edge in edgesFaces) {\n var cp = edge.cp\n for (pointNum in [edge.pn1, edge.pn2]) {\n var tp = tempPoints[pointNum].p\n tempPoints[pointNum].p = sumPoint.call(tp, cp)\n tempPoints[pointNum].n = tempPoints[pointNum].n + 1\n }\n }\n var avgMidEdges = List.filled(tempPoints.count, null)\n var i = 0\n for (tp in tempPoints) {\n avgMidEdges[i] = divPoint.call(tp.p, tp.n)\n i = i + 1\n }\n return avgMidEdges\n}\n\nvar getPointsFaces = Fn.new { |inputPoints, inputFaces|\n var numPoints = inputPoints.count\n var pointsFaces = List.filled(numPoints, 0)\n for (faceNum in 0...inputFaces.count) {\n for (pointNum in inputFaces[faceNum]) {\n pointsFaces[pointNum] = pointsFaces[pointNum] + 1\n }\n }\n return pointsFaces\n}\n\nvar getNewPoints = Fn.new { |inputPoints, pointsFaces, avgFacePoints, avgMidEdges|\n var newPoints = List.filled(inputPoints.count, null)\n for (pointNum in 0...inputPoints.count) {\n var n = pointsFaces[pointNum]\n var m1 = (n-3) / n\n var m2 = 1 / n\n var m3 = 2 / n\n var oldCoords = inputPoints[pointNum]\n var p1 = mulPoint.call(oldCoords, m1)\n var afp = avgFacePoints[pointNum]\n var p2 = mulPoint.call(afp, m2)\n var ame = avgMidEdges[pointNum]\n var p3 = mulPoint.call(ame, m3)\n var p4 = sumPoint.call(p1, p2)\n newPoints[pointNum] = sumPoint.call(p4, p3)\n }\n return newPoints\n}\n\nvar switchNums = Fn.new { |pointNums|\n if (pointNums[0] < pointNums[1]) return pointNums\n return [pointNums[1], pointNums[0]]\n}\n\nvar cmcSubdiv = Fn.new { |inputPoints, inputFaces|\n var facePoints = getFacePoints.call(inputPoints, inputFaces)\n var edgesFaces = getEdgesFaces.call(inputPoints, inputFaces)\n var edgePoints = getEdgePoints.call(inputPoints, edgesFaces, facePoints)\n var avgFacePoints = getAvgFacePoints.call(inputPoints, inputFaces, facePoints)\n var avgMidEdges = getAvgMidEdges.call(inputPoints, edgesFaces)\n var pointsFaces = getPointsFaces.call(inputPoints, inputFaces)\n var newPoints = getNewPoints.call(inputPoints, pointsFaces, avgFacePoints, avgMidEdges)\n var facePointNums = []\n var nextPointNum = newPoints.count\n for (facePoint in facePoints) {\n newPoints.add(facePoint)\n facePointNums.add(nextPointNum)\n nextPointNum = nextPointNum + 1\n }\n var edgePointNums = {}\n for (edgeNum in 0...edgesFaces.count) {\n var pointNum1 = edgesFaces[edgeNum].pn1\n var pointNum2 = edgesFaces[edgeNum].pn2\n var edgePoint = edgePoints[edgeNum]\n newPoints.add(edgePoint)\n edgePointNums[Int.cantorPair(pointNum1, pointNum2)] = nextPointNum\n nextPointNum = nextPointNum + 1\n }\n var newFaces = []\n var oldFaceNum = 0\n for (oldFace in inputFaces) {\n if (oldFace.count == 4) {\n var a = oldFace[0]\n var b = oldFace[1]\n var c = oldFace[2]\n var d = oldFace[3]\n var facePointAbcd = facePointNums[oldFaceNum]\n var p = switchNums.call([a, b])\n var edgePointAb = edgePointNums[Int.cantorPair(p[0], p[1])]\n p = switchNums.call([d, a])\n var edgePointDa = edgePointNums[Int.cantorPair(p[0], p[1])]\n p = switchNums.call([b, c])\n var edgePointBc = edgePointNums[Int.cantorPair(p[0], p[1])]\n p = switchNums.call([c, d])\n var edgePointCd = edgePointNums[Int.cantorPair(p[0], p[1])]\n newFaces.add([a, edgePointAb, facePointAbcd, edgePointDa])\n newFaces.add([b, edgePointBc, facePointAbcd, edgePointAb])\n newFaces.add([c, edgePointCd, facePointAbcd, edgePointBc])\n newFaces.add([d, edgePointDa, facePointAbcd, edgePointCd])\n }\n oldFaceNum = oldFaceNum + 1\n }\n return [newPoints, newFaces]\n}\n\nvar inputPoints = [\n Point.new(-1, 1, 1),\n Point.new(-1, -1, 1),\n Point.new( 1, -1, 1),\n Point.new( 1, 1, 1),\n Point.new( 1, -1, -1),\n Point.new( 1, 1, -1),\n Point.new(-1, -1, -1),\n Point.new(-1, 1, -1)\n]\n\nvar inputFaces = [\n [0, 1, 2, 3],\n [3, 2, 4, 5],\n [5, 4, 6, 7],\n [7, 0, 3, 5],\n [7, 6, 1, 0],\n [6, 1, 2, 4]\n]\n\nvar outputPoints = inputPoints.toList\nvar outputFaces = inputFaces.toList\nvar iterations = 1\nfor (i in 0...iterations) {\n var res = cmcSubdiv.call(outputPoints, outputFaces)\n outputPoints = res[0]\n outputFaces = res[1]\n}\nfor (p in outputPoints) {\n Fmt.aprint([p.x, p.y, p.z], 7, 4, \"[]\")\n}\nSystem.print()\nfor (f in outputFaces) {\n Fmt.aprint(f, 2, 0, \"[]\")\n}\n", "language": "Wren" } ]
Catmull-Clark-subdivision-surface
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Chaos_game\n", "language": "00-META" }, { "code": "The [[wp:Chaos_game|Chaos Game]] is a method of generating the attractor of an iterated function system (IFS). \n\nOne of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.\n\n\n;Task\nPlay the Chaos Game using the corners of an equilateral triangle as the reference points. &nbsp; Add a starting point at random (preferably inside the triangle). &nbsp; Then add the next point halfway between the starting point and one of the reference points. &nbsp; This reference point is chosen at random.\n\nAfter a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.\n\n\n;See also\n* [http://www.geoastro.de/ChaosSpiel/ChaosEnglish.html The Game of Chaos]\n<br><br>\n", "language": "00-TASK" }, { "code": "\tcpu\t8086\n\tbits\t16\nvmode:\tequ\t0Fh\t\t; Get current video mode\ntime:\tequ\t2Ch\t\t; Get current system time\nCGALO:\tequ\t4\t\t; Low-res (4-color) CGA mode\nMDA:\tequ\t7\t\t; MDA text mode\nsection\t.text\n\torg\t100h\n\tmov\tah,vmode\t; Get current video mode\n\tint\t10h\n\tcmp\tal,MDA\t\t; If MDA mode, no CGA supported, so stop\n\tjne\tgr_ok\n\tret\ngr_ok:\tpush\tax\t\t; Store old video mode on stack\n\tmov\tax,CGALO\t; Switch to low-resolution CGA mode\n\tint\t10h\n\tmov\tah,time\t\t; Get system time\n\tint\t21h\n\tmov\tdi,cx\t\t; Store as RNG seed\n\tmov\tbp,dx\ngenX:\tcall\trandom\t\t; Generate random X coordinate\n\tcmp\tal,200\n\tjae\tgenX\n\tmov\tdh,al\t\t; DH = X\ngenY:\tcall\trandom\t\t; Generate random Y coordinate\n\tcmp\tal,173\n\tjae\tgenY\n\tmov\tdl,al\t\t; DL = Y\nmloop:\tmov\tah,1\t\t; Is a key pressed?\n\tint\t16h\n\tjz\tpoint\t\t; If not, calculate another point\n\tpop\tax\t\t; But if so, restore the old video mode\n\tcbw\n\tint\t10h\n\tret\t\t\t; And quit\npoint:\tcall\trandom\t\t; Generate random direction\n\tand\tal,3\n\tcmp\tal,3\n\tje\tpoint\n\tmov\tah,al\t\t; Keep direction (for color later)\n\tdec\tal\t\t; Select direction\n\tjz\td2\n\tdec\tal\n\tjz\td3\n\tshr\tdh,1\t\t; X /= 2\n\tshr\tdl,1\t\t; Y /= 2\n\tjmp\tplot\nd2:\tmov\tcl,ah\t\t; Keep color in CL\n\tmov\tsi,100\t\t; X = 100+(100-X)/2\n\txor\tax,ax\t\t; (doing intermediate math in 16 bits)\n\tmov\tal,dh\n\tneg\tax\n\tadd\tax,si\n\tshr\tax,1\n\tadd\tax,si\n\tmov\tdh,al\n\tmov\tsi,173\t\t; Y = 173-(173-Y)/2\n\txor\tax,ax\t\t; (doing intermediate math in 16 bits)\n\tmov\tal,dl\n\tneg\tax\n\tadd\tax,si\n\tshr\tax,1\n\tneg\tax\n\tadd\tax,si\n\tmov\tdl,al\n\tmov\tah,cl\t\t; Restore color\n\tjmp\tplot\nd3:\tmov\tcl,ah\t\t; Keep color\n\tmov\tsi,200\t\t; X = 200-(200-X)/2\n\txor\tax,ax\t\t; (doing intermediate math in 16 bits)\n\tmov\tal,dh\n\tneg\tax\n\tadd\tax,si\n\tshr\tax,1\n\tneg\tax\n\tadd\tax,si\n\tmov\tdh,al\n\tmov\tah,cl\t\t; Restore color\n\tshr\tdl,1\t\t; Y /= 2\nplot:\tmov\tcl,dl\t\t; There's a plot function in the BIOS, but it's\n\tclc\t\t\t; behind an INT and needs all the registers,\n\trcr\tcl,1\t\t; so we'll do it by hand.\n\tsbb\tbh,bh\t\t; The even rows are at B800:NNNN, odd at BA00,\n\txor\tbl,bl\t\t; CL (Y coord) is divided by two, and if odd\n\tand\tbh,2\t\t; we add 2(00) to B8(00) to get the right\n\tadd\tbh,0B8h\t\t; segment.\n\tmov\tds,bx\t\t; We can safely stick it in DS since we're not\n\txor\tbx,bx\t\t; using any RAM otherwise. 80 bytes per line,\n\tmov\tbl,cl\t\t; so BX=Y * 80,\n\txor\tch,ch\t\t\n\tshl\tbx,1\t\t\n\tshl\tbx,1\n\tadd\tbx,cx\n\tmov\tcl,4\n\tshl\tbx,cl\n\tmov\tcl,dh\t\t; and 4 pixels per byte, so BX += Y/4\n\tshr\tcl,1\n\tshr\tcl,1\n\tadd\tbx,cx\n\tinc\tah\t\t; Add 1 to direction to get 1 of 3 colors\n\tmov\tch,dh\t\t; See which pixel within the byte we're\n\tand\tch,3\t\t; looking at\n\tmov\tcl,3\t\t; Leftmost pixel is in highest bits\n\tsub\tcl,ch\n\tshl\tcl,1\t\t; Pixels are 2 bits wide\n\tshl\tah,cl \t\t; Shift AH into place\n\tor\t[bx],ah\t\t; Set the pixel in video memory\n\tjmp\tmloop\t\t; Next pixel\nrandom:\txchg\tbx,bp\t\t; Load RNG state into byte-addressable\n\txchg\tcx,di \t\t; registers.\n\tinc\tbl\t\t; X++\n\txor\tbh,ch\t\t; A ^= C\n\txor\tbh,bl\t\t; A ^= X\n\tadd\tcl,bh\t\t; B += A\n\tmov\tal,cl\t\t; C' = B\n\tshr\tal,1\t\t; C' >>= 1\n\tadd\tal,ch\t\t; C' += C\n\txor\tal,bh\t\t; C' ^= A\n\tmov\tch,al\t\t; C = C'\n\txchg\tbx,bp\t\t; Restore the registers\n\txchg\tcx,di\n\tret\n", "language": "8086-Assembly" }, { "code": "PROC Main()\n INT x,w=[220],h=[190]\n BYTE y,i,CH=$02FC,COLOR1=$02C5,COLOR2=$02C6\n\n Graphics(8+16)\n Color=1\n COLOR1=$0C\n COLOR2=$02\n\n x=Rand(w)\n y=Rand(h)\n DO\n i=Rand(3)\n IF i=0 THEN\n x==/2\n y==/2\n ELSEIF i=1 THEN\n x=w/2+(w/2-x)/2\n y=h-(h-y)/2\n ELSE\n x=w-(w-x)/2\n y=y/2\n FI\n Plot((320-w)/2+x,191-y)\n UNTIL CH#$FF\n OD\n CH=$FF\nRETURN\n", "language": "Action-" }, { "code": "/* Chaos game - JAMBO hopper */\n\n#include <jambo.h>\n\n#define LIMITE 50000\n\nMain\n ancho = 700, alto = 150\n x=0,y=0,color=0\n vertice=0,\n c=0, Let( c := Utf8(Chr(219)))\n Let(x := Int(Rand(ancho)))\n Let(y := Int(Rand(alto)))\n\n mid ancho=0, Let( mid ancho:= Div(ancho,2))\n\n Cls\n i=LIMITE\n Void(pixeles)\n\n Loop\n Ceil(Rand(3)), On gosub( EQ1, EQ2, EQ3 )\n\n Set( Int(y), Int(x), color),Apndrow(pixeles)\n --i\n Back if (i) is not zero\n\n Canvas-term\n Cls\n i=1\n Iterator(++i, Leq(i,LIMITE), Colorfore([i,3]Get(pixeles)), \\\n Locate( [i,1]Get(pixeles), [i,2]Get(pixeles) ), Print(c) )\n Pause\n\nEnd\nSubrutines\n EQ1:\n Let(x := Div(x, 2))\n Let(y := Div(y, 2))\n Let(color:=9), Return\n\n EQ2:\n Let(x := Add( mid ancho, Div(Sub(mid ancho, x), 2) ) )\n Let(y := Sub( alto, Div( Sub(alto, y), 2 )))\n Let(color:=10), Return\n EQ3:\n Let(x := Sub(ancho, Div( Sub(ancho, x), 2)))\n Let(y := Div(y, 2))\n Let(color:=4), Return\n", "language": "Amazing-Hopper" }, { "code": "10 HGR2\n20 X = INT(RND(1) * 200)\n30 Y = INT(RND(1) * 173)\n40 FOR I=1 TO 20000\n50 V = INT(RND(1) * 3) + 1\n60 ON V GOTO 70,100,130\n70 X = X/2\n80 Y = Y/2\n90 GOTO 150\n100 X = 100 + (100-X)/2\n110 Y = 173 - (173-Y)/2\n120 GOTO 150\n130 X = 200 - (200-X)/2\n140 Y = Y/2\n150 HCOLOR=V+4\n160 HPLOT X,Y\n170 NEXT I\n", "language": "Applesoft-BASIC" }, { "code": "10 SCREEN 1\n20 X = INT(RND(0) * 200)\n30 Y = INT(RND(0) * 173)\n40 FOR I=1 TO 20000\n50 V = INT(RND(0) * 3) + 1\n60 ON V GOTO 70,100,130\n70 X = X/2\n80 Y = Y/2\n90 GOTO 150\n100 X = 100 + (100-X)/2\n110 Y = 173 - (173-Y)/2\n120 GOTO 150\n130 X = 200 - (200-X)/2\n140 Y = Y/2\n150 PSET X,Y,V\n160 NEXT I\n", "language": "BASIC" }, { "code": "#Chaos game\n\nancho = 500 : alto = 300\nx = Int(Rand * ancho)\ny = Int(Rand * alto)\n\nClg\nFastGraphics\nGraphsize ancho , alto\n\nFor iteracion = 1 To 30000\n\tvertice = Int(Rand * 3) + 1\n\tBegin Case\n\t\tCase vertice = 1\n\t\t\tx = x / 2\n\t\t\ty = y / 2\n\t\t\tColor red\n\t\tCase vertice = 2\n\t\t\tx = (ancho/2) + ((ancho/2)-x) / 2\n\t\t\ty = alto - (alto-y) / 2\n\t\t\tColor green\n\t\tCase vertice = 3\n\t\t\tx = ancho - (ancho-x) / 2\n\t\t\ty = y / 2\n\t\t\tColor blue\n\tEnd Case\n\t#Pset (x,y),vertice\n\tPlot (x,y)\nNext iteracion\nRefresh\nImgSave \"chaos_game.jpg\", \"jpg\"\nEnd\n", "language": "BASIC256" }, { "code": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n#include<time.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\ttime_t t;\n\tdouble side, vertices[3][3],seedX,seedY,windowSide;\n\tint i,iter,choice;\n\t\n\tprintf(\"Enter triangle side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\t\n\twindowSide = 10 + 2*side;\n\n\tinitwindow(windowSide,windowSide,\"Sierpinski Chaos\");\n\t\n\tfor(i=0;i<3;i++){\n\t\tvertices[i][0] = windowSide/2 + side*cos(i*2*pi/3);\n\t\tvertices[i][1] = windowSide/2 + side*sin(i*2*pi/3);\n\t\tputpixel(vertices[i][0],vertices[i][1],15);\n\t}\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tseedX = rand()%(int)(vertices[0][0]/2 + (vertices[1][0] + vertices[2][0])/4);\n\tseedY = rand()%(int)(vertices[0][1]/2 + (vertices[1][1] + vertices[2][1])/4);\n\t\n\tputpixel(seedX,seedY,15);\n\t\n\tfor(i=0;i<iter;i++){\n\t\tchoice = rand()%3;\n\t\t\n\t\tseedX = (seedX + vertices[choice][0])/2;\n\t\tseedY = (seedY + vertices[choice][1])/2;\n\t\t\n\t\tputpixel(seedX,seedY,15);\n\t}\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <windows.h>\n#include <ctime>\n#include <string>\n#include <iostream>\n\nconst int BMP_SIZE = 600;\n\nclass myBitmap {\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap() {\n DeleteObject( pen ); DeleteObject( brush );\n DeleteDC( hdc ); DeleteObject( bmp );\n }\n bool create( int w, int h ) {\n BITMAPINFO bi;\n ZeroMemory( &bi, sizeof( bi ) );\n bi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biWidth = w;\n bi.bmiHeader.biHeight = -h;\n\n HDC dc = GetDC( GetConsoleWindow() );\n bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n if( !bmp ) return false;\n\n hdc = CreateCompatibleDC( dc );\n SelectObject( hdc, bmp );\n ReleaseDC( GetConsoleWindow(), dc );\n\n width = w; height = h;\n return true;\n }\n void clear( BYTE clr = 0 ) {\n memset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n void setBrushColor( DWORD bClr ) {\n if( brush ) DeleteObject( brush );\n brush = CreateSolidBrush( bClr );\n SelectObject( hdc, brush );\n }\n void setPenColor( DWORD c ) {\n clr = c; createPen();\n }\n void setPenWidth( int w ) {\n wid = w; createPen();\n }\n void saveBitmap( std::string path ) {\n BITMAPFILEHEADER fileheader;\n BITMAPINFO infoheader;\n BITMAP bitmap;\n DWORD wb;\n\n GetObject( bmp, sizeof( bitmap ), &bitmap );\n DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n infoheader.bmiHeader.biCompression = BI_RGB;\n infoheader.bmiHeader.biPlanes = 1;\n infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n fileheader.bfType = 0x4D42;\n fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n CloseHandle( file );\n\n delete [] dwpBits;\n }\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\nprivate:\n void createPen() {\n if( pen ) DeleteObject( pen );\n pen = CreatePen( PS_SOLID, wid, clr );\n SelectObject( hdc, pen );\n }\n HBITMAP bmp; HDC hdc;\n HPEN pen; HBRUSH brush;\n void *pBits; int width, height, wid;\n DWORD clr;\n};\nclass chaos {\npublic:\n void start() {\n POINT org;\n fillPts(); initialPoint( org ); initColors();\n int cnt = 0, i;\n bmp.create( BMP_SIZE, BMP_SIZE );\n bmp.clear( 255 );\n\n while( cnt++ < 1000000 ) {\n switch( rand() % 6 ) {\n case 0: case 3: i = 0; break;\n case 1: case 5: i = 1; break;\n case 2: case 4: i = 2;\n }\n setPoint( org, myPoints[i], i );\n }\n // --- edit this path --- //\n bmp.saveBitmap( \"F:/st.bmp\" );\n }\nprivate:\n void setPoint( POINT &o, POINT v, int i ) {\n POINT z;\n o.x = ( o.x + v.x ) >> 1; o.y = ( o.y + v.y ) >> 1;\n SetPixel( bmp.getDC(), o.x, o.y, colors[i] );\n }\n void fillPts() {\n int a = BMP_SIZE - 1;\n myPoints[0].x = BMP_SIZE >> 1; myPoints[0].y = 0;\n myPoints[1].x = 0; myPoints[1].y = myPoints[2].x = myPoints[2].y = a;\n }\n void initialPoint( POINT& p ) {\n p.x = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 );\n p.y = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 );\n }\n void initColors() {\n colors[0] = RGB( 255, 0, 0 );\n colors[1] = RGB( 0, 255, 0 );\n colors[2] = RGB( 0, 0, 255 );\n }\n\n myBitmap bmp;\n POINT myPoints[3];\n COLORREF colors[3];\n};\nint main( int argc, char* argv[] ) {\n srand( ( unsigned )time( 0 ) );\n chaos c; c.start();\n return 0;\n}\n", "language": "C++" }, { "code": "using System.Diagnostics;\nusing System.Drawing;\n\nnamespace RosettaChaosGame\n{\n class Program\n {\n static void Main(string[] args)\n {\n var bm = new Bitmap(600, 600);\n\n var referencePoints = new Point[] {\n new Point(0, 600),\n new Point(600, 600),\n new Point(300, 81)\n };\n var r = new System.Random();\n var p = new Point(r.Next(600), r.Next(600));\n for (int count = 0; count < 10000; count++)\n {\n bm.SetPixel(p.X, p.Y, Color.Magenta);\n int i = r.Next(3);\n p.X = (p.X + referencePoints[i].X) / 2;\n p.Y = (p.Y + referencePoints[i].Y) / 2;\n }\n const string filename = \"Chaos Game.png\";\n bm.Save(filename);\n Process.Start(filename);\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(defpackage #:chaos\n (:use #:cl\n #:opticl))\n\n(in-package #:chaos)\n\n(defparameter *image-size* 600)\n(defparameter *margin* 50)\n(defparameter *edge-size* (- *image-size* *margin* *margin*))\n(defparameter *iterations* 1000000)\n\n(defun chaos ()\n (let ((image (make-8-bit-rgb-image *image-size* *image-size* :initial-element 255))\n (a (list (- *image-size* *margin*) *margin*))\n (b (list (- *image-size* *margin*) (- *image-size* *margin*)))\n (c (list (- *image-size* *margin* (round (* (tan (/ pi 3)) *edge-size*) 2))\n (round *image-size* 2)))\n (point (list (+ (random *edge-size*) *margin*)\n (+ (random *edge-size*) *margin*))))\n (dotimes (i *iterations*)\n (let ((ref (ecase (random 3)\n (0 a)\n (1 b)\n (2 c))))\n (setf point (list (round (+ (first point) (first ref)) 2)\n (round (+ (second point) (second ref)) 2))))\n (setf (pixel image (first point) (second point))\n (values 255 0 0)))\n (write-png-file \"chaos.png\" image)))\n", "language": "Common-Lisp" }, { "code": "unit main;\n\ninterface\n\nuses\n Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.ExtCtrls,\n System.Generics.Collections;\n\ntype\n TColoredPoint = record\n P: TPoint;\n Index: Integer;\n constructor Create(PX, PY: Integer; ColorIndex: Integer);\n end;\n\n TForm1 = class(TForm)\n procedure FormCreate(Sender: TObject);\n procedure FormDestroy(Sender: TObject);\n procedure FormPaint(Sender: TObject);\n private\n Buffer: TBitmap;\n Points: array[0..2] of TPoint;\n Stack: TStack<TColoredPoint>;\n Tick: TTimer;\n procedure Run(Sender: TObject);\n procedure AddPoint;\n function HalfWayPoint(a: TColoredPoint; b: TPoint; index: Integer): TColoredPoint;\n { Private declarations }\n public\n { Public declarations }\n end;\n\nconst\n Colors: array[0..2] of Tcolor = (clRed, clGreen, clBlue);\n\nvar\n Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\n{ TColoredPoint }\n\nconstructor TColoredPoint.Create(PX, PY: Integer; ColorIndex: Integer);\nbegin\n self.P := Tpoint.Create(PX, PY);\n self.Index := ColorIndex;\nend;\n\n{ TForm1 }\n\nprocedure TForm1.FormCreate(Sender: TObject);\nbegin\n Buffer := TBitmap.Create;\n Stack := TStack<TColoredPoint>.Create;\n Tick := TTimer.Create(nil);\n Caption := 'Chaos Game';\n\n DoubleBuffered := True;\n\n ClientHeight := 640;\n ClientWidth := 640;\n var margin := 60;\n var size := ClientWidth - 2 * margin;\n\n Points[0] := TPoint.Create(ClientWidth div 2, margin);\n Points[1] := TPoint.Create(margin, size);\n Points[2] := TPoint.Create(margin + size, size);\n\n Stack.Push(TColoredPoint.Create(-1, -1, Colors[0]));\n\n Tick.Interval := 10;\n Tick.OnTimer := Run;\nend;\n\nfunction TForm1.HalfWayPoint(a: TColoredPoint; b: TPoint; index: Integer): TColoredPoint;\nbegin\n Result := TColoredPoint.Create((a.p.X + b.x) div 2, (a.p.y + b.y) div 2, index);\nend;\n\nprocedure TForm1.AddPoint;\nbegin\n var colorIndex := Random(3);\n var p1 := Stack.Peek;\n var p2 := Points[colorIndex];\n Stack.Push(HalfWayPoint(p1, p2, colorIndex));\nend;\n\nprocedure TForm1.Run(Sender: TObject);\nbegin\n if Stack.Count < 50000 then\n begin\n for var i := 0 to 999 do\n AddPoint;\n Invalidate;\n end;\nend;\n\nprocedure TForm1.FormDestroy(Sender: TObject);\nbegin\n Tick.Free;\n Buffer.Free;\n Stack.Free;\nend;\n\nprocedure TForm1.FormPaint(Sender: TObject);\nbegin\n for var p in Stack do\n begin\n with Canvas do\n begin\n Pen.Color := Colors[p.Index];\n Brush.Color := Colors[p.Index];\n Brush.Style := bsSolid;\n Ellipse(p.p.X - 1, p.p.y - 1, p.p.X + 1, p.p.y + 1);\n end;\n end;\nend;\nend.\n", "language": "Delphi" }, { "code": "color 900\nx[] = [ 0 100 50 ]\ny[] = [ 7 7 93 ]\nx = randomf * 100\ny = randomf * 100\nfor i = 1 to 100000\n move x y\n rect 0.3 0.3\n h = randint 3\n x = (x + x[h]) / 2\n y = (y + y[h]) / 2\n.\n", "language": "EasyLang" }, { "code": "; Chaos game\n\n(defun make-array (size)\n \"Create an empty array with size*size elements.\"\n (setq m-array (make-vector size nil))\n (dotimes (i size)\n (setf (aref m-array i) (make-vector size 0)))\n m-array)\n\n(defun chaos-next (p)\n \"Return the next coordinates.\"\n (let* ((points (list (cons 1 0) (cons -1 0) (cons 0 (sqrt 3))))\n \t (v (elt points (random 3)))\n (x (car p))\n (y (cdr p))\n (x2 (car v))\n (y2 (cdr v)))\n (setq nx (/ (+ x x2) 2.0))\n (setq ny (/ (+ y y2) 2.0))\n (cons nx ny)))\n\n(defun chaos-lines (arr size)\n \"Turn array into a string for XPM conversion.\"\n (setq all \"\")\n (dotimes (y size)\n (setq line \"\")\n (dotimes (x size)\n (setq line (concat line (if (= (elt (elt arr y) x) 1) \"*\" \".\"))))\n (setq all (concat all \"\\\"\" line \"\\\",\\n\")))\n all)\n\n(defun chaos-show (arr size)\n \"Convert size*size array to XPM image and show it.\"\n (insert-image (create-image (concat (format \"/* XPM */\nstatic char * chaos[] = {\n\\\"%i %i 2 1\\\",\n\\\". c #000000\\\",\n\\\"* c #00ff00\\\",\" size size)\n (chaos-lines arr size) \"};\") 'xpm t)))\n\n(defun chaos (size scale max-iter)\n \"Play the chaos game.\"\n (let ((arr (make-array size))\n (p (cons 0 0)))\n (dotimes (it max-iter)\n (setq p (chaos-next p))\n (setq x (round (+ (/ size 2) (* scale (car p)))))\n (setq y (round (+ (- size 10) (* -1 scale (cdr p)))))\n (setf (elt (elt arr y) x) 1))\n (chaos-show arr size)))\n\n(chaos 400 180 50000)\n", "language": "Emacs-Lisp" }, { "code": "open System.Windows.Forms\nopen System.Drawing\nopen System\n\nlet sz = 300\nlet polygon = [Point(sz/2, int (float sz*(1.0-sin(Math.PI/3.0)))); Point(0, sz-1); Point(sz-1, sz-1)]\n\nlet bmp = new Bitmap(sz, sz)\nlet paint (p: Point) = bmp.SetPixel(p.X, p.Y, Color.Black)\n\nlet random = Random()\nlet seed = Point(int (random.NextDouble() * float sz), int (random.NextDouble() * float sz))\nlet midpoint (p1: Point) (p2: Point) = Point((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2)\nlet randomVertex() = polygon.[random.Next(polygon.Length)]\nlet step p _ =\n paint p\n midpoint p (randomVertex())\nSeq.init 100000 id |> Seq.fold step seed\n\nlet f = new Form()\nf.ClientSize <- bmp.Size\nf.Paint.Add (fun args -> args.Graphics.DrawImage(bmp, Point(0, 0)))\nf.Show()\n", "language": "F-Sharp" }, { "code": "#! /usr/bin/gforth\n\\ Chaos Game\n\nrequire random.fs\n\n\\ initialize the random number generator with a time-dependent seed\nutime drop seed !\n\n\\ parses a number from a string\n: parse-number ( -- n )\n s>number? invert throw drop\n;\n\n\n\\ parse the width of the triangle, the number of steps and the output filename from the command-line\n\n.\" width: \" next-arg parse-number dup . cr CONSTANT WIDTH\n.\" steps: \" next-arg parse-number dup . cr CONSTANT STEPS\n.\" output: \" next-arg 2dup type cr 2CONSTANT OUT-FILE\n\n\n\\ height of the triangle: height = sqrt(3) / 2 * width\nWIDTH 0 d>f 3e fsqrt f* 2e f/ fround f>d drop CONSTANT HEIGHT \\ height of the triangle: height = sqrt(3) / 2 * width\n\n\n\\ coordinates of the three corners of the triangle\n\n0 CONSTANT X1\n0 CONSTANT Y1\nWIDTH CONSTANT X2\n0 CONSTANT Y2\nWIDTH 2 / CONSTANT X3\nHEIGHT CONSTANT Y3\n\n\n\\ minimal and maximal x and y coordinates\n\nX1 X2 X3 min min CONSTANT XMIN\nX1 X2 X3 max max CONSTANT XMAX\nY1 Y2 Y3 min min CONSTANT YMIN\nY1 Y2 Y3 max max CONSTANT YMAX\n\nXMAX XMIN - 1+ CONSTANT XSIZE\nYMAX YMIN - 1+ CONSTANT YSIZE\n\n\n\\ initialize array for all possible points\n\nXSIZE YSIZE *\ndup CREATE ARR cells allot\nARR swap cells erase\n\n\n\\ address of the cell corresponding to point (x,y)\n: addr? ( x y -- addr )\n XSIZE * + cells ARR +\n;\n\n\\ scalar product of the 2-vectors\n: sp ( x1 y1 x2 y2 -- n )\n swap >r * r> rot * +\n;\n\n\\ is the point (x,y) on the left of the ray from (px,py) to (qx,qy)?\n: left? ( px py qx qy x y -- f )\n { px py qx qy x y }\n py qy -\n qx px -\n x px -\n y py -\n sp 0>=\n;\n\n\\ is the point (x,y) in the triangle?\n: in-triangle? ( x y -- f )\n { x y }\n X1 Y1 X2 Y2 x y left?\n X2 Y2 X3 Y3 x y left?\n X3 Y3 X1 Y1 x y left?\n and and\n;\n\n\\ generates a random number in [a,b]\n: random-in-range ( a b -- n )\n over - 1+ random +\n;\n\n\\ generates a random point in the triangle\n: random-in-triangle ( -- x y )\n 0 0\n BEGIN\n 2drop\n XMIN XMAX random-in-range\n YMIN YMAX random-in-range\n 2dup in-triangle?\n UNTIL\n;\n\n\\ finds the middle of to points (px,py) and (qx,qy)\n: middle ( px py qx qy -- x y )\n swap -rot\n + 2/ -rot\n + 2/ swap\n;\n\n\\ plays the chaos game for a number of steps\n: game ( n -- )\n random-in-triangle\n rot\n 0 DO\n 2dup addr? true swap !\n 3 random CASE\n 0 OF X1 Y1 ENDOF\n 1 OF X2 Y2 ENDOF\n 2 OF X3 Y3 ENDOF\n ENDCASE\n middle\n LOOP\n 2drop\n;\n\n\\ writes the result in pbm-format\n: write-pbm ( -- )\n .\" P1\" cr\n XSIZE . YSIZE . cr\n YMIN 1- YMAX -DO\n XMAX 1+ XMIN DO\n i j addr? @ IF 1 . ELSE 0 . THEN\n LOOP\n cr\n 1 -LOOP\n;\n\n\\ writes the result to a pbm-file\n: to-pbm ( c-addr u -- )\n w/o create-file throw ['] write-pbm over outfile-execute close-file throw\n;\n\n\\ play the game and save the result\nSTEPS game OUT-FILE to-pbm\n\nbye\n", "language": "Forth" }, { "code": "PROGRAM CHAOS\n IMPLICIT NONE\n REAL, DIMENSION(3):: KA, KN ! Koordinates old/new\n REAL, DIMENSION(3):: DA, DB, DC ! Triangle\n INTEGER:: I, Z\n INTEGER, PARAMETER:: UT = 17\n ! Define corners of triangle\n DA = (/ 0., 0., 0. /)\n DB = (/ 600., 0., 0. /)\n DC = (/ 500., 0., 400. /)\n ! Define starting point\n KA = (/ 500., 0., 100. /)\n OPEN (UNIT = UT, FILE = 'aus.csv')\n DO I=1, 1000000\n Z = ZAHL()\n WRITE (UT, '(3(F12.6, \";\"))') KA\n SELECT CASE (Z)\n CASE (1)\n CALL MITTELP(KA, DA, KN)\n CASE (2)\n CALL MITTELP(KA, DB, KN)\n CASE (3)\n CALL MITTELP(KA, DC, KN)\n END SELECT\n KA = KN\n END DO\n CLOSE (UT)\n CONTAINS\n ! Calculates center of two points\n SUBROUTINE MITTELP(P1, P2, MP)\n REAL, INTENT(IN), DIMENSION(3):: P1, P2\n REAL, INTENT(OUT), DIMENSION(3):: MP\n MP = (P1 + P2) / 2.\n END SUBROUTINE MITTELP\n ! Returns random number\n INTEGER FUNCTION ZAHL()\n REAL:: ZZ\n CALL RANDOM_NUMBER(ZZ)\n ZZ = ZZ * 3.\n ZAHL = FLOOR(ZZ) + 1\n IF (ZAHL .GT. 3) ZAHL = 3\n END FUNCTION ZAHL\nEND PROGRAM CHAOS\n", "language": "Fortran" }, { "code": "set terminal jpeg enhanced size 1600,960\nset output 'chaos.jpg'\nset nokey\nset style line 1 lc rgb '#0060ad' lt 1 lw 3 pt 7 ps 0.3\nplot 'aus.csv' using 1:3 with points ls 1 notitle\n", "language": "Fortran" }, { "code": "' Chaos game\nConst ancho = 320, alto = 240\nDim As Integer x, y, iteracion, vertice\nx = Int(Rnd * ancho)\ny = Int(Rnd * alto)\n\nScreenres ancho, alto, 8\nCls\n\nFor iteracion = 1 To 30000\n\tvertice = Int(Rnd * 3) + 1\n\tSelect Case vertice\n Case 1\n x = x / 2\n y = y / 2\n vertice = 4 'red\n Case 2\n x = (ancho/2) + ((ancho/2)-x) / 2\n y = alto - (alto-y) / 2\n vertice = 2 'green\n Case 3\n x = ancho - (ancho-x) / 2\n y = y / 2\n vertice = 1 'blue\n End Select\n\tPset (x,y),vertice\nNext iteracion\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "void local fn DoIt\n long w = 460, h = 400, i, x = rnd(w), y = rnd(h)\n for i = 1 to 50000\n select ( rnd(3)-1 )\n case 1\n x = w/2+(w/2-x)/2\n y = h-(h-y)/2\n pen ,fn ColorRed\n case 2\n x = w-(w-x)/2\n y = y/2\n pen ,fn ColorGreen\n case else\n x = x/2\n y = y/2\n pen ,fn ColorBlue\n end select\n line x-0.5,y-0.5,x+0.5,y+0.5\n next\nend fn\n\nwindow 1, @\"Chaos Game\", (0,0,460,400)\nWindowSetBackgroundColor( 1, fn ColorWhite )\n\nfn DoIt\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "offset = 32; //Distance from triangle vertices to edges of window\n\n//triangle vertex coordinates\nx1 = room_width / 2;\ny1 = offset;\nx2 = room_width - offset;\ny2 = room_height - offset;\nx3 = offset;\ny3 = room_height - offset;\n\n//Coords of randomly chosen vertex (set to 0 to start, will automatically be set in step event)\nvx = 0;\nvy = 0;\n\n//Coords of current point\npx = random(room_width);\npy = random(room_height);\n\n//Make sure the point is within the triangle\nwhile(!point_in_triangle(px, py, x1, y1, x2, y2, x3, y3))\n{\n\tpx = random(room_width);\n\tpy = random(room_height);\n}\n\nvertex = 0; //This determines which vertex coords are chosen\nmax_iterations = 8000;\nstep = true; //Used with the interval alarm to change the step speed\nstep_count = 0;\ninterval = 1; //Number of frames between each step. 1 = no delay\nalarm[0] = interval;\n", "language": "GML" }, { "code": "if(step and step_count < max_iterations) //Wait for alarm to finish, or stop completely\n{\t\t\t\t\t\t\t\t\t\t// if the desired number of iterations is hit\n\tvertex = choose(1, 2, 3);\n\tstep = false;\n\talarm[0] = interval;\n\tswitch(vertex)\n\t{\n\t\tcase 1:\n\t\t\tvx = x1;\n\t\t\tvy = y1;\n\t\tbreak;\n\t\n\t\tcase 2:\n\t\t\tvx = x2;\n\t\t\tvy = y2;\n\t\tbreak;\n\t\n\t\tcase 3:\n\t\t\tvx = x3;\n\t\t\tvy = y3;\n\t\tbreak;\n\t}\n\n\tvar dir = point_direction(px, py, vx, vy);\n\tvar mid_dist = point_distance(px, py, vx, vy);\n\tvar midx = px + lengthdir_x(mid_dist / 2, dir);\n\tvar midy = py + lengthdir_y(mid_dist / 2, dir);\n\tinstance_create_layer(midx, midy, \"Instances\", Point);\n\n\tpx = midx;\n\tpy = midy;\n\t\n\tstep_count++;\n}\n", "language": "GML" }, { "code": "if(step_count < max_iterations)\n{\n\tdraw_triangle(x1, y1, x2, y2, x3, y3, true);\n\tdraw_circle(px, py, 1, false);\n\tdraw_line(px, py, vx, vy);\n}\n", "language": "GML" }, { "code": "step = true;\nalarm[0] = interval;\n", "language": "GML" }, { "code": "draw_circle(x, y, 5, false);\n", "language": "GML" }, { "code": "## Chaos Game (Sierpinski triangle) 2/16/17 aev\nreset\nfn=\"ChGS3Gnu1\"; clr='\"red\"';\nttl=\"Chaos Game (Sierpinski triangle)\"\nsz=600; sz1=sz/2; sz2=sz1*sqrt(3);\nx=y=xf=yf=v=0;\ndfn=fn.\".dat\"; ofn=fn.\".png\";\nset terminal png font arial 12 size 640,640\nset print dfn append\nset output ofn\nunset border; unset xtics; unset ytics; unset key;\nset size square\nset title ttl font \"Arial:Bold,12\"\nlim=30000; max=100; x=y=xw=yw=p=0;\nrandgp(top) = floor(rand(0)*top)\nx=randgp(sz); y=randgp(sz2);\ndo for [i=1:lim] {\n v=randgp(3);\n if (v==0) {x=x/2; y=y/2}\n if (v==1) {x=sz1+(sz1-x)/2; y=sz2-(sz2-y)/2}\n if (v==2) {x=sz-(sz-x)/2; y=y/2}\n xf=floor(x); yf=floor(y);\n if(!(xf<1||xf>sz||yf<1||yf>sz)) {print xf,\" \",yf};\n}\nplot dfn using 1:2 with points pt 7 ps 0.5 lc @clr\nset output\nunset print\n", "language": "Gnuplot" }, { "code": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"image/color\"\n\t\"image/draw\"\n\t\"image/gif\"\n\t\"log\"\n\t\"math\"\n\t\"math/rand\"\n\t\"os\"\n\t\"time\"\n)\n\nvar bwPalette = color.Palette{\n\tcolor.Transparent,\n\tcolor.White,\n\tcolor.RGBA{R: 0xff, A: 0xff},\n\tcolor.RGBA{G: 0xff, A: 0xff},\n\tcolor.RGBA{B: 0xff, A: 0xff},\n}\n\nfunc main() {\n\tconst (\n\t\twidth = 160\n\t\tframes = 100\n\t\tpointsPerFrame = 50\n\t\tdelay = 100 * time.Millisecond\n\t\tfilename = \"chaos_anim.gif\"\n\t)\n\n\tvar tan60 = math.Sin(math.Pi / 3)\n\theight := int(math.Round(float64(width) * tan60))\n\tb := image.Rect(0, 0, width, height)\n\tvertices := [...]image.Point{\n\t\t{0, height}, {width, height}, {width / 2, 0},\n\t}\n\n\t// Make a filled triangle.\n\tm := image.NewPaletted(b, bwPalette)\n\tfor y := b.Min.Y; y < b.Max.Y; y++ {\n\t\tbg := int(math.Round(float64(b.Max.Y-y) / 2 / tan60))\n\t\tfor x := b.Min.X + bg; x < b.Max.X-bg; x++ {\n\t\t\tm.SetColorIndex(x, y, 1)\n\t\t}\n\t}\n\n\t// Pick starting point\n\tvar p image.Point\n\trand.Seed(time.Now().UnixNano())\n\tp.Y = rand.Intn(height) + b.Min.Y\n\tp.X = rand.Intn(width) + b.Min.X // TODO: make within triangle\n\n\tanim := newAnim(frames, delay)\n\taddFrame(anim, m)\n\tfor i := 1; i < frames; i++ {\n\t\tfor j := 0; j < pointsPerFrame; j++ {\n\t\t\t// Pick a random vertex\n\t\t\tvi := rand.Intn(len(vertices))\n\t\t\tv := vertices[vi]\n\t\t\t// Move p halfway there\n\t\t\tp.X = (p.X + v.X) / 2\n\t\t\tp.Y = (p.Y + v.Y) / 2\n\t\t\tm.SetColorIndex(p.X, p.Y, uint8(2+vi))\n\t\t}\n\t\taddFrame(anim, m)\n\t}\n\tif err := writeAnim(anim, filename); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"wrote to %q\\n\", filename)\n}\n\n// Stuff for making a simple GIF animation.\n\nfunc newAnim(frames int, delay time.Duration) *gif.GIF {\n\tconst gifDelayScale = 10 * time.Millisecond\n\tg := &gif.GIF{\n\t\tImage: make([]*image.Paletted, 0, frames),\n\t\tDelay: make([]int, 1, frames),\n\t}\n\tg.Delay[0] = int(delay / gifDelayScale)\n\treturn g\n}\nfunc addFrame(anim *gif.GIF, m *image.Paletted) {\n\tb := m.Bounds()\n\tdst := image.NewPaletted(b, m.Palette)\n\tdraw.Draw(dst, b, m, image.ZP, draw.Src)\n\tanim.Image = append(anim.Image, dst)\n\tif len(anim.Delay) < len(anim.Image) {\n\t\tanim.Delay = append(anim.Delay, anim.Delay[0])\n\t}\n}\nfunc writeAnim(anim *gif.GIF, filename string) error {\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = gif.EncodeAll(f, anim)\n\tif cerr := f.Close(); err == nil {\n\t\terr = cerr\n\t}\n\treturn err\n}\n", "language": "Go" }, { "code": "import javafx.animation.AnimationTimer\nimport javafx.application.Application\nimport javafx.scene.Scene\nimport javafx.scene.layout.Pane\nimport javafx.scene.paint.Color\nimport javafx.scene.shape.Circle\nimport javafx.stage.Stage\n\nclass ChaosGame extends Application {\n\n final randomNumberGenerator = new Random()\n\n @Override\n void start(Stage primaryStage) {\n primaryStage.title = 'Chaos Game'\n primaryStage.scene = getScene()\n primaryStage.show()\n }\n\n def getScene() {\n def colors = [Color.RED, Color.GREEN, Color.BLUE]\n\n final width = 640, height = 640, margin = 60\n final size = width - 2 * margin\n\n def points = [\n new Circle(width / 2, margin, 1, colors[0]),\n new Circle(margin, size, 1, colors[1]),\n new Circle(margin + size, size, 1, colors[2])\n ]\n\n def pane = new Pane()\n pane.style = '-fx-background-color: black;'\n points.each {\n pane.children.add it\n }\n\n def currentPoint = new Circle().with {\n centerX = randomNumberGenerator.nextInt(size - margin) + margin\n centerY = randomNumberGenerator.nextInt(size - margin) + margin\n it\n }\n\n ({\n\n def newPoint = generatePoint(currentPoint, points, colors)\n pane.children.add newPoint\n currentPoint = newPoint\n\n } as AnimationTimer).start()\n\n new Scene(pane, width, height)\n }\n\n def generatePoint(currentPoint, points, colors) {\n def selection = randomNumberGenerator.nextInt 3\n new Circle().with {\n centerX = (currentPoint.centerX + points[selection].centerX) / 2\n centerY = (currentPoint.centerY + points[selection].centerY) / 2\n radius = 1\n fill = colors[selection]\n it\n }\n }\n\n static main(args) {\n launch(ChaosGame)\n }\n}\n", "language": "Groovy" }, { "code": "100 REM Chaos game\n110 CLS\n120 SCREEN 7 '320x200 EGA Color\n130 X = INT(RND(1) * 200)\n140 Y = INT(RND(1) * 173)\n150 FOR I=1 TO 20000\n160 V = INT(RND(1) * 3) + 1\n170 ON V GOTO 180,210,240\n180 X = X/2\n190 Y = Y/2\n200 GOTO 260\n210 X = 100 + (100-X)/2\n220 Y = 173 - (173-Y)/2\n230 GOTO 260\n240 X = 200 - (200-X)/2\n250 Y = Y/2\n260 PSET(X,Y),V\n270 NEXT I\n280 END\n", "language": "GW-BASIC" }, { "code": "import Control.Monad (replicateM)\nimport Control.Monad.Random (fromList)\n\ntype Point = (Float,Float)\ntype Transformations = [(Point -> Point, Float)] -- weighted transformations\n\n-- realization of the game for given transformations\ngameOfChaos :: MonadRandom m => Int -> Transformations -> Point -> m [Point]\ngameOfChaos n transformations x = iterateA (fromList transformations) x\n where iterateA f x = scanr ($) x <$> replicateM n f\n", "language": "Haskell" }, { "code": "-- the Sierpinsky`s triangle\ntriangle = [ (mid (0, 0), 1)\n , (mid (1, 0), 1)\n , (mid (0.5, 0.86), 1) ]\n where mid (a,b) (x,y) = ((a+x)/2, (b+y)/2)\n\n-- the Barnsley's fern\nfern = [(f1, 1), (f2, 85), (f3, 7), (f4, 7)]\n where f1 (x,y) = (0, 0.16*y)\n f2 (x,y) = (0.85*x + 0.04*y, -0.04*x + 0.85*y + 1.6)\n f3 (x,y) = (0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6)\n f4 (x,y) = (-0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44)\n\n-- A dragon curve\ndragon = [(f1, 1), (f2, 1)]\n where f1 (x,y) = (0.5*x - 0.5*y, 0.5*x + 0.5*y)\n f2 (x,y) = (-0.5*x + 0.5*y+1, -0.5*x - 0.5*y)\n", "language": "Haskell" }, { "code": "import Control.Monad.Random (getRandomR)\nimport Graphics.Gloss\n\nmain = do x <- getRandomR (0,1)\n y <- getRandomR (0,1)\n pts <- gameOfChaos 500000 triangle (x,y)\n display window white $ foldMap point pts\n where window = InWindow \"Game of Chaos\" (400,400) (0,0)\n point (x,y) = translate (100*x) (100*y) $ circle 0.02\n", "language": "Haskell" }, { "code": "100 PROGRAM \"ChaosGam.bas\"\n110 RANDOMIZE\n120 GRAPHICS HIRES 4\n130 LET X=RND(800):LET Y=RND(600)\n140 FOR I=1 TO 20000\n150 LET VERTEX=RND(3)\n160 SELECT CASE VERTEX\n170 CASE 0\n180 LET X=X/2\n190 LET Y=Y/2\n200 CASE 1\n210 LET X=400+(400-X)/2\n220 LET Y=600-(600-Y)/2\n230 CASE 2\n240 LET X=800-(800-X)/2\n250 LET Y=Y/2\n260 END SELECT\n270 SET INK VERTEX+1\n280 PLOT X,Y\n290 NEXT\n", "language": "IS-BASIC" }, { "code": "Note 'plan, Working in complex plane'\n Make an equilateral triangle.\n Make a list of N targets\n Starting with a random point near the triangle,\n iteratively generate new points.\n plot the new points.\n\n j has a particularly rich notation for numbers.\n\n 1ad_90 specifies a complex number with radius 1\n at an angle of negative 90 degrees.\n\n 2p1 is 2 times (pi raised to the first power).\n)\n\nN=: 3000\n\nrequire'plot'\nTAU=: 2p1 NB. tauday.com\nmean=: +/ % #\n\nNB. equilateral triangle with vertices on unit circle\nNB. rotated for fun.\nTRIANGLE=: *(j./2 1 o.(TAU%6)*?0)*1ad_90 1ad150 1ad30\n\nTARGETS=: (N ?@:# 3) { TRIANGLE\n\nNB. start on unit circle\nSTART=: j./2 1 o.TAU*?0\n\nNEW_POINTS=: (mean@:(, {.) , ])/ TARGETS , START\n\n'marker'plot NEW_POINTS\n", "language": "J" }, { "code": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\nimport javax.swing.Timer;\n\npublic class ChaosGame extends JPanel {\n static class ColoredPoint extends Point {\n int colorIndex;\n\n ColoredPoint(int x, int y, int idx) {\n super(x, y);\n colorIndex = idx;\n }\n }\n\n Stack<ColoredPoint> stack = new Stack<>();\n Point[] points = new Point[3];\n Color[] colors = {Color.red, Color.green, Color.blue};\n Random r = new Random();\n\n public ChaosGame() {\n Dimension dim = new Dimension(640, 640);\n setPreferredSize(dim);\n setBackground(Color.white);\n\n int margin = 60;\n int size = dim.width - 2 * margin;\n\n points[0] = new Point(dim.width / 2, margin);\n points[1] = new Point(margin, size);\n points[2] = new Point(margin + size, size);\n\n stack.push(new ColoredPoint(-1, -1, 0));\n\n new Timer(10, (ActionEvent e) -> {\n if (stack.size() < 50_000) {\n for (int i = 0; i < 1000; i++)\n addPoint();\n repaint();\n }\n }).start();\n }\n\n private void addPoint() {\n try {\n int colorIndex = r.nextInt(3);\n Point p1 = stack.peek();\n Point p2 = points[colorIndex];\n stack.add(halfwayPoint(p1, p2, colorIndex));\n } catch (EmptyStackException e) {\n e.printStackTrace();\n }\n }\n\n void drawPoints(Graphics2D g) {\n for (ColoredPoint p : stack) {\n g.setColor(colors[p.colorIndex]);\n g.fillOval(p.x, p.y, 1, 1);\n }\n }\n\n ColoredPoint halfwayPoint(Point a, Point b, int idx) {\n return new ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx);\n }\n\n @Override\n public void paintComponent(Graphics gg) {\n super.paintComponent(gg);\n Graphics2D g = (Graphics2D) gg;\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n\n drawPoints(g);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n JFrame f = new JFrame();\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setTitle(\"Chaos Game\");\n f.setResizable(false);\n f.add(new ChaosGame(), BorderLayout.CENTER);\n f.pack();\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n });\n }\n}\n", "language": "Java" }, { "code": "<html>\n\n<head>\n\n<meta charset=\"UTF-8\">\n\n<title>Chaos Game</title>\n\n</head>\n\n<body>\n\n<p>\n<canvas id=\"sierpinski\" width=400 height=346></canvas>\n</p>\n\n<p>\n<button onclick=\"chaosGame()\">Click here to see a Sierpiński triangle</button>\n</p>\n\n<script>\n\nfunction chaosGame() {\n var canv = document.getElementById('sierpinski').getContext('2d');\n var x = Math.random() * 400;\n var y = Math.random() * 346;\n for (var i=0; i<30000; i++) {\n var vertex = Math.floor(Math.random() * 3);\n switch(vertex) {\n case 0:\n x = x / 2;\n y = y / 2;\n canv.fillStyle = 'green';\n break;\n case 1:\n x = 200 + (200 - x) / 2\n y = 346 - (346 - y) / 2\n canv.fillStyle = 'red';\n break;\n case 2:\n x = 400 - (400 - x) / 2\n y = y / 2;\n canv.fillStyle = 'blue';\n }\n canv.fillRect(x,y, 1,1);\n }\n}\n\n</script>\n\n</body>\n\n</html>\n", "language": "JavaScript" }, { "code": "using Luxor\n\nfunction chaos()\n width = 1000\n height = 1000\n Drawing(width, height, \"./chaos.png\")\n t = Turtle(0, 0, true, 0, (0., 0., 0.))\n x = rand(1:width)\n y = rand(1:height)\n\n for l in 1:30_000\n v = rand(1:3)\n if v == 1\n x /= 2\n y /= 2\n elseif v == 2\n x = width/2 + (width/2 - x)/2\n y = height - (height - y)/2\n else\n x = width - (width - x)/2\n y = y / 2\n end\n Reposition(t, x, height-y)\n Circle(t, 3)\n end\nend\n\nchaos()\nfinish()\npreview()\n", "language": "Julia" }, { "code": "//Version 1.1.51\n\nimport java.awt.*\nimport java.util.Stack\nimport java.util.Random\nimport javax.swing.JPanel\nimport javax.swing.JFrame\nimport javax.swing.Timer\nimport javax.swing.SwingUtilities\n\nclass ChaosGame : JPanel() {\n\n class ColoredPoint(x: Int, y: Int, val colorIndex: Int) : Point(x, y)\n\n val stack = Stack<ColoredPoint>()\n val points: List<Point>\n val colors = listOf(Color.red, Color.green, Color.blue)\n val r = Random()\n\n init {\n val dim = Dimension(640, 640)\n preferredSize = dim\n background = Color.white\n val margin = 60\n val size = dim.width - 2 * margin\n points = listOf(\n Point(dim.width / 2, margin),\n Point(margin, size),\n Point(margin + size, size)\n )\n stack.push(ColoredPoint(-1, -1, 0))\n\n Timer(10) {\n if (stack.size < 50_000) {\n for (i in 0 until 1000) addPoint()\n repaint()\n }\n }.start()\n }\n\n private fun addPoint() {\n val colorIndex = r.nextInt(3)\n val p1 = stack.peek()\n val p2 = points[colorIndex]\n stack.add(halfwayPoint(p1, p2, colorIndex))\n }\n\n fun drawPoints(g: Graphics2D) {\n for (cp in stack) {\n g.color = colors[cp.colorIndex]\n g.fillOval(cp.x, cp.y, 1, 1)\n }\n }\n\n fun halfwayPoint(a: Point, b: Point, idx: Int) =\n ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx)\n\n override fun paintComponent(gg: Graphics) {\n super.paintComponent(gg)\n val g = gg as Graphics2D\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON)\n drawPoints(g)\n }\n}\n\nfun main(args: Array<String>) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n with (f) {\n defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n title = \"Chaos Game\"\n isResizable = false\n add(ChaosGame(), BorderLayout.CENTER)\n pack()\n setLocationRelativeTo(null)\n isVisible = true\n }\n }\n}\n", "language": "Kotlin" }, { "code": "10 mode 1:randomize time:defint a-z\n20 x = 640 * rnd\n30 y = 400 * rnd\n40 for i=1 to 20000\n50 v = rnd * 2 + 1\n60 on v goto 70,100,130\n70 x = x/2\n80 y = y/2\n90 goto 150\n100 x = 320 + (320-x)/2\n110 y = 400 - (400-y)/2\n120 goto 150\n130 x = 640 - (640-x)/2\n140 y = y/2\n150 plot x,y,v\n160 next i\n", "language": "Locomotive-Basic" }, { "code": "to chaosgame :sidelength :iterations\n make \"width :sidelength\n make \"height (:sidelength/2 * sqrt 3)\n make \"x (random :width)\n make \"y (random :height)\n repeat :iterations [\n make \"vertex (random 3)\n if :vertex = 0 [\n make \"x (:x / 2)\n make \"y (:y / 2)\n setpencolor \"green\n ]\n if :vertex = 1 [\n make \"x (:width / 2 + ((:width / 2 - :x) / 2))\n make \"y (:height - ((:height - :y) / 2))\n setpencolor \"red\n ]\n if :vertex = 2 [\n make \"x (:width - ((:width - :x) / 2))\n make \"y (:y / 2)\n setpencolor \"blue\n ]\n penup\n setxy (:x - :width / 2) (:y - :height / 2)\n pendown\n forward 1\n ]\n hideturtle\nend\n", "language": "Logo" }, { "code": "math.randomseed( os.time() )\ncolors, orig = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } }, {}\n\nfunction love.load()\n wid, hei = love.graphics.getWidth(), love.graphics.getHeight()\n\n orig[1] = { wid / 2, 3 }\n orig[2] = { 3, hei - 3 }\n orig[3] = { wid - 3, hei - 3 }\n local w, h = math.random( 10, 40 ), math.random( 10, 40 )\n if math.random() < .5 then w = -w end\n if math.random() < .5 then h = -h end\n orig[4] = { wid / 2 + w, hei / 2 + h }\n\n canvas = love.graphics.newCanvas( wid, hei )\n love.graphics.setCanvas( canvas ); love.graphics.clear()\n love.graphics.setColor( 255, 255, 255 )\n love.graphics.points( orig )\n love.graphics.setCanvas()\nend\nfunction love.draw()\n local iter = 100 --> make this number bigger to speed up rendering\n for rp = 1, iter do\n local r, pts = math.random( 6 ), {}\n if r == 1 or r == 4 then\n pt = 1\n elseif r == 2 or r == 5 then\n pt = 2\n else\n pt = 3\n end\n local x, y = ( orig[4][1] + orig[pt][1] ) / 2, ( orig[4][2] + orig[pt][2] ) / 2\n orig[4][1] = x; orig[4][2] = y\n pts[1] = { x, y, colors[pt][1], colors[pt][2], colors[pt][3], 255 }\n love.graphics.setCanvas( canvas )\n love.graphics.points( pts )\n end\n love.graphics.setCanvas()\n love.graphics.draw( canvas )\nend\n", "language": "Lua" }, { "code": "Module Chaos {\n\t01 Read Ox as integer, Oy as Integer\n\t02 def Screen$\n\t05 cls 0,0 // black background, row for split screen\n\t10 def integer x,y,i,v\n\t20 x = 640 * rnd\n\t30 y = 400 * rnd\n\t40 for i=1 to 20000\n\t50 v = rnd * 2 + 1\n\t60 on v goto 70,100,130\n\t70 x = x/2\n\t80 y = y/2\n\t90 goto 150\n\t100 x = 320 + (320-x)/2\n\t110 y = 400 - (400-y)/2\n\t120 goto 150\n\t130 x = 640 - (640-x)/2\n\t140 y = y/2\n\t150 pset v*2, x*twipsX+Ox,y*twipsY+Oy\n\t160 next i\n\t170 Move Ox, Oy\n\t180 Copy 640*twipsX, 400*twipsY to Screen$\n\t190 Clipboard Screen$\n}\nCall Chaos 3000, 3000\n", "language": "M2000-Interpreter" }, { "code": "chaosGame := proc(numPoints)\n\tlocal points, i;\n\trandomize();\n\tuse geometry in\n\tRegularPolygon(triSideways, 3, point(cent, [0, 0]), 1);\n\trotation(tri, triSideways, Pi/2, counterclockwise);\n\trandpoint(currentP, -1/2*sqrt(3)..1/2*sqrt(3), -1/2..1/2);\n\tpoints := [coordinates(currentP)];\n\tfor i to numPoints do\n\t\tmidpoint(mid, currentP, parse(cat(\"rotate_triSideways_\", rand(1..3)(), \"_tri\")));\n\t\tpoints := [op(points), coordinates(mid)];\n\t\tpoint(currentP, coordinates(mid));\n\tend do:\n\tend use;\n\tuse plottools in\n\t\tplots:-display( seq([plots:-display([seq(point(points[i]), i = 1..j)])], j = 1..numelems(points) ), insequence=true);\n\tend use;\nend proc:\n", "language": "Maple" }, { "code": "points = 5000;\na = {0, 0};\nb = {1, 0};\nc = {0.5, 1};\nd = {.7, .3};\nS = {};\nFor[i = 1, i < points, i++, t = RandomInteger[2];\n If[t == 0, d = Mean[{a, d}],\n If[t == 1, d = Mean[{b, d}], d = Mean[{c, d}]]]; AppendTo[S, d]]\nGraphics[Point[S]]\n", "language": "Mathematica" }, { "code": "100 REM Chaos game\n110 CLS\n120 SCREEN 2\n130 X = INT(RND(1) * 256)\n140 Y = INT(RND(1) * 192)\n150 FOR I=1 TO 20000\n160 V = INT(RND(1) * 3) + 1\n170 ON V GOTO 180,220,260\n180 X = X/2\n190 Y = Y/2\n200 V = 8 'red\n210 GOTO 290\n220 X = 128 + (128-X)/2\n230 Y = 192 - (192-Y)/2\n240 V = 3 'green\n250 GOTO 290\n260 X = 256 - (256-X)/2\n270 Y = Y/2\n280 V = 7 'blue\n290 PSET(X,Y),V\n300 NEXT I\n310 END\n", "language": "MSX-Basic" }, { "code": "\\\\ Chaos Game (Sierpinski triangle) 2/15/17 aev\npChaosGameS3(size,lim)={\nmy(sz1=size\\2,sz2=sz1*sqrt(3),M=matrix(size,size),x,y,xf,yf,v);\nx=random(size); y=random(sz2);\nfor(i=1,lim, v=random(3);\n if(v==0, x/=2; y/=2;);\n if(v==1, x=sz1+(sz1-x)/2; y=sz2-(sz2-y)/2;);\n if(v==2, x=size-(size-x)/2; y/=2;);\n xf=floor(x); yf=floor(y); if(xf<1||xf>size||yf<1||yf>size, next);\n M[xf,yf]=1;\n);\\\\fend\nplotmat(M);\n}\n\\\\ Test:\npChaosGameS3(600,30000); \\\\ SierpTri1.png\n", "language": "PARI-GP" }, { "code": "program ChaosGame;\n\n// FPC 3.0.2\nuses\n Graph, windows, math;\n\n// Return a point on a circle defined by angle and the circles radius\n// Angle 0 = Radius points to the left\n// Angle 90 = Radius points upwards\nFunction PointOfCircle(Angle: SmallInt; Radius: integer): TPoint;\nvar Ia: Double;\nbegin\n Ia:=DegToRad(-Angle);\n result.x:=round(cos(Ia)*Radius);\n result.y:=round(sin(Ia)*Radius);\nend;\n\n{ Main }\n\nvar\n GraphDev,GraphMode: smallint;\n Triangle: array[0..2] of Tpoint; // Corners of the triangle\n TriPnt: Byte; // Point in ^^^^\n Origin: TPoint; // Defines center of triangle\n Itterations: integer; // Number of Itterations\n Radius: Integer;\n View: viewPorttype;\n CurPnt: TPoint;\n Rect: TRect;\n Counter: integer;\nbegin\n\n Repeat {forever}\n\n // Get the Itteration count 0=exit\n Write('Itterations: ');\n ReadLn(Itterations);\n\n if Itterations=0 then halt;\n\n // Set Up Graphics screen (everythings Auto detect)\n GraphDev:=Detect;\n GraphMode:=0;\n InitGraph(GraphDev,GraphMode,'');\n if GraphResult<>grok then\n begin\n Writeln('Graphics doesn''t work');\n Halt;\n end;\n\n // set Origin to center of the _Triangle_ (Not the creen)\n GetViewSettings(View);\n Rect.Create(View.x1,View.y1+10,View.x2,View.y2-10);\n Origin:=Rect.CenterPoint;\n Origin.Offset(0,Rect.Height div 6); // Center Triangle on screen\n\n // Define Equilateral triangle,\n Radius:=Origin.y; // Radius of Circumscribed circle\n for Counter:=0 to 2 do\n Triangle[Counter]:=PointOfCircle((Counter*120)+90,Radius)+Origin;\n\n // Choose random starting point, in the incsribed circle of the triangle\n Radius:=Radius div 2; // Radius of inscribed circle\n CurPnt:=PointOfCircle(random(360),random(Radius div 2))+Origin;\n\n // Play the Chaos Game\n for Counter:=0 to Itterations do\n begin\n TriPnt:=Random(3); // Select Triangle Point\n Rect.Create(Triangle[TriPnt],CurPnt);; // Def. rect. between TriPnt and CurPnt\n CurPnt:=Rect.CenterPoint; // New CurPnt is center of rectangle\n putPixel(CurPnt.x,CurPnt.y,cyan); // Plot the new CurPnt\n end;\n\n until False;\nend.\n", "language": "Pascal" }, { "code": "use Imager;\n\nmy $width = 1000;\nmy $height = 1000;\n\nmy @points = (\n [ $width/2, 0],\n [ 0, $height-1],\n [$height-1, $height-1],\n);\n\nmy $img = Imager->new(\n xsize => $width,\n ysize => $height,\n channels => 3,\n );\n\nmy $color = Imager::Color->new('#ff0000');\nmy $r = [int(rand($width)), int(rand($height))];\n\nforeach my $i (1 .. 100000) {\n my $p = $points[rand @points];\n\n my $h = [\n int(($p->[0] + $r->[0]) / 2),\n int(($p->[1] + $r->[1]) / 2),\n ];\n\n $img->setpixel(\n x => $h->[0],\n y => $h->[1],\n color => $color,\n );\n\n $r = $h;\n}\n\n$img->write(file => 'chaos_game_triangle.png');\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Chaos_game.exw\n -- ===========================\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas</span>\n <span style=\"color: #004080;\">cdCanvas</span> <span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cdcanvas</span>\n\n <span style=\"color: #008080;\">enum</span> <span style=\"color: #000000;\">TRI</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">SQ1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">SQ2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">SQ3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">PENT</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">descs</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"Sierpinsky Triangle\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"Square 1\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"Square 2\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"Square 3\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"Pentagon\"</span><span style=\"color: #0000FF;\">}</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">mode</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">TRI</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">redraw_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000080;font-style:italic;\">/*posx*/</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">/*posy*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetIntInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"DRAWSIZE\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">0.05</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">0.05</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">0.9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">0.9</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">points</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mode</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">SQ1</span><span style=\"color: #0000FF;\">?{{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">}}:</span>\n <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mode</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">PENT</span><span style=\"color: #0000FF;\">?{{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">}}</span>\n <span style=\"color: #0000FF;\">:{{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">}}))</span>\n <span style=\"color: #7060A8;\">cdCanvasActivate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">last</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1000</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">rand</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">points</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">mode</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">TRI</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">last</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">nx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ny</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">points</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">nx</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,(</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">ny</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #7060A8;\">cdCanvasPixel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_GREY</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">mode</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">SQ2</span>\n <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">mode</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">SQ3</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">points</span><span style=\"color: #0000FF;\">))+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">mode</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">SQ3</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">points</span><span style=\"color: #0000FF;\">))+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">last</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">r</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">cdCanvasFlush</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"Chaos Game (%s)\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">descs</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">mode</span><span style=\"color: #0000FF;\">]})</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">timer_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupUpdate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_IGNORE</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">map_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cdcanvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_IUP</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cddbuffer</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_DBUFFER</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cdcanvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasSetBackground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_WHITE</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasSetForeground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_GRAY</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">key_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">K_ESC</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_CLOSE</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">' '</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">mode</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">mode</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">PENT</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">mode</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">TRI</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">cdCanvasClear</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupRedraw</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_CONTINUE</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n\n <span style=\"color: #000000;\">canvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"RASTERSIZE=640x640\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallbacks</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"MAP_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"map_cb\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #008000;\">\"ACTION\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"redraw_cb\"</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">`TITLE=\"Chaos Game\"`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"KEY_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"key_cb\"</span><span style=\"color: #0000FF;\">))</span>\n\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"RASTERSIZE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">timer</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupTimer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"timer_cb\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">40</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "To run:\nStart up.\nInitialize our reference points.\nClear the screen to the lightest gray color.\nPlay the chaos game.\nRefresh the screen.\nWait for the escape key.\nShut down.\n\nTo play the chaos game:\nPick a spot within 2 inches of the screen's center.\nLoop.\nDraw the spot.\nIf a counter is past 20000, exit.\nPick a reference spot.\nFind a middle spot of the spot and the reference spot.\nPut the middle spot into the spot.\nRepeat.\n\nTo find a middle spot of a spot and another spot:\nPut the spot's x coord plus the other spot's x coord divided by 2 into the middle spot's x coord.\nPut the spot's y coord plus the other spot's y coord divided by 2 into the middle spot's y coord.\n\nThe top spot is a spot.\nThe left spot is a spot.\nThe right spot is a spot.\n\nTo initialize our reference points:\nMove up 2-1/2 inches.\nPut the context's spot into the top spot.\nTurn right. Turn 1/6 of the way around.\nMove 5 inches.\nPut the context's spot into the right spot.\nTurn 1/3 of the way around.\nMove 5 inches.\nPut the context's spot into the left spot.\n\nTo pick a reference spot:\nPick a number between 1 and 3.\nIf the number is 1, put the top spot into the reference spot.\nIf the number is 2, put the right spot into the reference spot.\nIf the number is 3, put the left spot into the reference spot.\n", "language": "Plain-English" }, { "code": "size(300, 260);\n\nbackground(#ffffff); // white\n\nint x = floor(random(width));\nint y = floor(random(height));\n\nint colour = #ffffff;\n\nfor (int i=0; i<30000; i++) {\n int v = floor(random(3));\n switch (v) {\n case 0:\n x = x / 2;\n y = y / 2;\n colour = #00ff00; // green\n break;\n case 1:\n x = width/2 + (width/2 - x)/2;\n y = height - (height - y)/2;\n colour = #ff0000; // red\n break;\n case 2:\n x = width - (width - x)/2;\n y = y / 2;\n colour = #0000ff; // blue\n }\n set(x, height-y, colour);\n}\n", "language": "Processing" }, { "code": "from __future__ import division\n\nsize(300, 260)\n\nbackground(255) # white\n\nx = floor(random(width))\ny = floor(random(height))\n\nfor _ in range(30000):\n v = floor(random(3))\n if v == 0:\n x = x / 2\n y = y / 2\n colour = color(0, 255, 0) # green\n elif v == 1:\n x = width / 2 + (width / 2 - x) / 2\n y = height - (height - y) / 2\n colour = color(255, 0, 0) # red\n elif v == 2:\n x = width - (width - x) / 2\n y = y / 2\n colour = color(0, 0, 255) # blue\n\n set(x, height - y, colour)\n", "language": "Processing-Python-mode" }, { "code": "import argparse\nimport random\nimport shapely.geometry as geometry\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n\ndef main(args):\n # Styles\n plt.style.use(\"ggplot\")\n\n # Creating figure\n fig = plt.figure()\n line, = plt.plot([], [], \".\")\n\n # Limit axes\n plt.xlim(0, 1)\n plt.ylim(0, 1)\n\n # Titles\n title = \"Chaos Game\"\n plt.title(title)\n fig.canvas.set_window_title(title)\n\n # Getting data\n data = get_data(args.frames)\n\n # Creating animation\n line_ani = animation.FuncAnimation(\n fig=fig,\n func=update_line,\n frames=args.frames,\n fargs=(data, line),\n interval=args.interval,\n repeat=False\n )\n\n # To save the animation install ffmpeg and uncomment\n # line_ani.save(\"chaos_game.gif\")\n\n plt.show()\n\n\ndef get_data(n):\n \"\"\"\n Get data to plot\n \"\"\"\n leg = 1\n triangle = get_triangle(leg)\n cur_point = gen_point_within_poly(triangle)\n data = []\n for _ in range(n):\n data.append((cur_point.x, cur_point.y))\n cur_point = next_point(triangle, cur_point)\n return data\n\n\ndef get_triangle(n):\n \"\"\"\n Create right triangle\n \"\"\"\n ax = ay = 0.0\n a = ax, ay\n\n bx = 0.5 * n\n by = 0.75 * (n ** 2)\n b = bx, by\n\n cx = n\n cy = 0.0\n c = cx, cy\n\n triangle = geometry.Polygon([a, b, c])\n return triangle\n\n\ndef gen_point_within_poly(poly):\n \"\"\"\n Generate random point inside given polygon\n \"\"\"\n minx, miny, maxx, maxy = poly.bounds\n while True:\n x = random.uniform(minx, maxx)\n y = random.uniform(miny, maxy)\n point = geometry.Point(x, y)\n if point.within(poly):\n return point\n\n\ndef next_point(poly, point):\n \"\"\"\n Generate next point according to chaos game rules\n \"\"\"\n vertices = poly.boundary.coords[:-1] # Last point is the same as the first one\n random_vertex = geometry.Point(random.choice(vertices))\n line = geometry.linestring.LineString([point, random_vertex])\n return line.centroid\n\n\ndef update_line(num, data, line):\n \"\"\"\n Update line with new points\n \"\"\"\n new_data = zip(*data[:num]) or [(), ()]\n line.set_data(new_data)\n return line,\n\n\nif __name__ == \"__main__\":\n arg_parser = argparse.ArgumentParser(description=\"Chaos Game by Suenweek (c) 2017\")\n arg_parser.add_argument(\"-f\", dest=\"frames\", type=int, default=1000)\n arg_parser.add_argument(\"-i\", dest=\"interval\", type=int, default=10)\n\n main(arg_parser.parse_args())\n", "language": "Python" }, { "code": " [ $ \"turtleduck.qky\" loadfile ] now!\n\n [ 2 3 circle ] is dot ( --> )\n\n [ 1 fly\n -1 4 turn\n 1 fly\n 1 4 turn ] is toxy ( n n --> )\n\n [ swap 2dup toxy\n dot\n 1 2 turn\n toxy\n 1 2 turn ] is plot ( n n --> )\n\n [ 200 random\n 346 random\n over 346 *\n over 200 * < if\n [ dip [ 400 + ]\n 692 swap - ] ] is intriangle ( --> n n )\n\n [ 3 random\n [ table\n [ 2 /\n dip [ 2 / ] ]\n [ 2 /\n dip [ 800 + 2 / ] ]\n [ 692 + 2 /\n dip [ 400 + 2 / ] ] ]\n do ] is tovertex ( n n --> )\n\n turtle\n 0 frames\n -400 1 fly\n 1 4 turn\n 340 1 fly\n -1 4 turn\n intriangle\n 10000 times\n [ i^ 100 mod 0= if frame\n 2dup plot\n tovertex ]\n 2drop\n 1 frames\n", "language": "Quackery" }, { "code": "# Chaos Game (Sierpinski triangle) 2/15/17 aev\n# pChaosGameS3(size, lim, clr, fn, ttl)\n# Where: size - defines matrix and picture size; lim - limit of the dots;\n# fn - file name (.ext will be added); ttl - plot title;\npChaosGameS3 <- function(size, lim, clr, fn, ttl)\n{\n cat(\" *** START:\", date(), \"size=\",size, \"lim=\",lim, \"clr=\",clr, \"\\n\");\n sz1=floor(size/2); sz2=floor(sz1*sqrt(3)); xf=yf=v=0;\n M <- matrix(c(0), ncol=size, nrow=size, byrow=TRUE);\n x <- sample(1:size, 1, replace=FALSE);\n y <- sample(1:sz2, 1, replace=FALSE);\n pf=paste0(fn, \".png\");\n for (i in 1:lim) { v <- sample(0:3, 1, replace=FALSE);\n if(v==0) {x=x/2; y=y/2;}\n if(v==1) {x=sz1+(sz1-x)/2; y=sz2-(sz2-y)/2;}\n if(v==2) {x=size-(size-x)/2; y=y/2;}\n xf=floor(x); yf=floor(y); if(xf<1||xf>size||yf<1||yf>size) {next};\n M[xf,yf]=1;\n }\n plotmat(M, fn, clr, ttl, 0, size);\n cat(\" *** END:\",date(),\"\\n\");\n}\npChaosGameS3(600, 30000, \"red\", \"SierpTriR1\", \"Sierpinski triangle\")\n", "language": "R" }, { "code": "pta = c(1,2)\nptb = c(4,2)\nptc = c(2.5,4)\nspt = c(1,2)\n\nplot(t(data.frame(pta,ptb,ptc)),\n xlab= \"\", ylab = \"\", pch = 19, asp =1,\n xaxt='n',yaxt='n', ann=FALSE,frame.plot=FALSE)\npoints(x = spt[1], y = spt[2], col = \"blue\", pch = 19)\n\nittt = 100000\nptcex = .2\nfor (i in 1:ittt) {\n d = sample(1:6,1,TRUE)\n if (d == 1 | d == 2) {\n pta1 = spt + ((pta-spt)/2)\n points(pta1[1],pta1[2], col = \"red\", pch = 19, cex = ptcex)\n spt=pta1\n }\n if (d == 3 | d == 4) {\n ptb1 = spt + (ptb-spt)/2\n points(ptb1[1],ptb1[2], col = \"red\", pch = 19, cex = ptcex)\n spt=ptb1\n }\n if (d == 5 | d == 6) {\n ptc1 = spt + (ptc-spt)/2\n points(ptc1[1],ptc1[2], col = \"red\", pch = 19, cex = ptcex)\n spt=ptc1\n }\n}\n", "language": "R" }, { "code": "#lang racket\n\n(require 2htdp/image)\n\n(define SIZE 300)\n\n(define (game-of-chaos fns WIDTH HEIGHT SIZE\n #:offset-x [offset-x 0] #:offset-y [offset-y 0]\n #:iters [iters 10000]\n #:bg [bg 'white] #:fg [fg 'black])\n (define dot (square 1 'solid fg))\n (define all-choices (apply + (map first fns)))\n (for/fold ([image (empty-scene WIDTH HEIGHT bg)]\n [x (random)] [y (random)]\n #:result image)\n ([i (in-range iters)])\n (define picked (random all-choices))\n (define fn (for/fold ([acc 0] [result #f] #:result result) ([fn (in-list fns)])\n #:break (> acc picked)\n (values (+ (first fn) acc) (second fn))))\n (match-define (list x* y*) (fn x y))\n (values (place-image dot (+ offset-x (* SIZE x*)) (+ offset-y (* SIZE y*)) image)\n x* y*)))\n\n(define (draw-triangle)\n (define ((mid a b) x y) (list (/ (+ a x) 2) (/ (+ b y) 2)))\n (define (triangle-height x) (* (sqrt 3) 0.5 x))\n (game-of-chaos (list (list 1 (mid 0 0))\n (list 1 (mid 1 0))\n (list 1 (mid 0.5 (triangle-height 1))))\n SIZE (triangle-height SIZE) SIZE))\n\n(define (draw-fern)\n (define (f1 x y) (list 0 (* 0.16 y)))\n (define (f2 x y) (list (+ (* 0.85 x) (* 0.04 y)) (+ (* -0.04 x) (* 0.85 y) 1.6)))\n (define (f3 x y) (list (+ (* 0.2 x) (* -0.26 y)) (+ (* 0.23 x) (* 0.22 y) 1.6)))\n (define (f4 x y) (list (+ (* -0.15 x) (* 0.28 y)) (+ (* 0.26 x) (* 0.24 y) 0.44)))\n (game-of-chaos (list (list 1 f1) (list 85 f2) (list 7 f3) (list 7 f4))\n (/ SIZE 2) SIZE (/ SIZE 11) #:offset-x 70 #:offset-y 10\n #:bg 'black #:fg 'white))\n\n(define (draw-dragon)\n (game-of-chaos\n (list (list 1 (λ (x y) (list (+ (* 0.5 x) (* -0.5 y)) (+ (* 0.5 x) (* 0.5 y)))))\n (list 1 (λ (x y) (list (+ (* -0.5 x) (* 0.5 y) 1) (+ (* -0.5 x) (* -0.5 y))))))\n SIZE (* 0.8 SIZE) (/ SIZE 1.8) #:offset-x 64 #:offset-y 120))\n\n(draw-triangle)\n(draw-fern)\n(draw-dragon)\n", "language": "Racket" }, { "code": "use Image::PNG::Portable;\n\nmy ($w, $h) = (640, 640);\n\nmy $png = Image::PNG::Portable.new: :width($w), :height($h);\n\nmy @vertex = [0, 0], [$w, 0], [$w/2, $h];\n\nmy @xy = [0,0], [0,0], [0,0], [0,0];\n\n# :degree must be equal to or less than @xy elements.\n(^1e5).race(:4degree).map: {\n my $p = ++$ % +@xy;\n @xy[$p] = do given @vertex.pick -> @v { ((@xy[$p] »+« @v) »/» 2)».Int };\n $png.set: |@xy[$p], 0, 255, 0;\n}\n\n$png.write: 'Chaos-game-perl6.png';\n", "language": "Raku" }, { "code": "/*REXX pgm draws a Sierpinski triangle by running the chaos game with a million points*/\nparse value scrsize() with sd sw . /*obtain the depth and width of screen.*/\nsw= sw - 2 /*adjust the screen width down by two. */\nsd= sd - 4 /* \" \" \" depth \" \" four.*/\nparse arg pts chr seed . /*obtain optional arguments from the CL*/\nif pts=='' | pts==\",\" then pts= 1000000 /*Not specified? Then use the default.*/\nif chr=='' | chr==\",\" then chr= '∙' /* \" \" \" \" \" \" */\nif datatype(seed,'W') then call random ,,seed /*Is specified? \" \" RANDOM seed.*/\nx= sw; hx= x % 2; y= sd /*define the initial starting position.*/\n@.= ' ' /* \" all screen points as a blank. */\n do pts; ?= random(1, 3) /* [↓] draw a # of (million?) points.*/\n select /*?: will be a random number: 1 ──► 3.*/\n when ?==1 then parse value x%2 y%2 with x y\n when ?==2 then parse value hx+(hx-x)%2 sd-(sd-y)%2 with x y\n otherwise parse value sw-(sw-x)%2 y%2 with x y\n end /*select*/\n @.x.y= chr /*set the X, Y point to a bullet.*/\n end /*pts*/ /* [↑] one million points ≡ overkill? */\n /* [↓] display the points to the term.*/\n do row=sd to 0 by -1; _= /*display the points, one row at a time*/\n do col=0 for sw+2 /* \" a row (one line) of image. */\n _= _ || @.col.row /*construct a \" \" \" \" \" */\n end /*col*/ /*Note: display image from top──►bottom*/\n /* [↑] strip trailing blanks (output).*/\n say strip(_, 'T') /*display one row (line) of the image. */\n end /*row*/ /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "# Project : Chaos game\n\nload \"guilib.ring\"\n\npaint = null\n\nnew qapp\n {\n win1 = new qwidget() {\n setwindowtitle(\"Archimedean spiral\")\n setgeometry(100,100,500,600)\n label1 = new qlabel(win1) {\n setgeometry(10,10,400,400)\n settext(\"\")\n }\n new qpushbutton(win1) {\n setgeometry(150,500,100,30)\n settext(\"draw\")\n setclickevent(\"draw()\")\n }\n show()\n }\n exec()\n }\n\nfunc draw\n p1 = new qpicture()\n color = new qcolor() {\n setrgb(0,0,255,255)\n }\n pen = new qpen() {\n setcolor(color)\n setwidth(1)\n }\n paint = new qpainter() {\n begin(p1)\n setpen(pen)\n\n x = floor(random(10)/10 * 200)\n y = floor(random(10/10) * 173)\n for i = 1 to 20000\n v = floor(random(10)/10 * 3) + 1\n\t if v = 1\n\t x = x/2\n\t y = y/2\n\t ok\n\t if v = 2\n\t x = 100 + (100-x)/2\n\t y = 173 - (173-y)/2\n\t ok\n\t if v = 3\n\t x = 200 - (200-x)/2\n\t y = y/2\n\t ok\n\t drawpoint(x,y)\n next\n endpaint()\n }\n label1 {setpicture(p1) show()}\n", "language": "Ring" }, { "code": "x\t= int(rnd(0) * 200)\ny\t= int(rnd(0) * 173)\ngraphic #g, 200,200\n#g color(\"green\")\nfor i =1 TO 20000\n\tv = int(rnd(0) * 3) + 1\n\tif v = 1 then\n\t\tx = x/2\n\t\ty = y/2\n\tend if\n\tif v = 2 then\n\t\tx = 100 + (100-x)/2\n\t\ty = 173 - (173-y)/2\n\tend if\n\tif v = 3 then\n\t\tx = 200 - (200-x)/2\n\t\ty = y/2\n\tend if\n\t#g set(x,y)\nnext\nrender #g\n", "language": "Run-BASIC" }, { "code": "extern crate image;\nextern crate rand;\n\nuse rand::prelude::*;\nuse std::f32;\n\nfn main() {\n let max_iterations = 50_000;\n let img_side = 800;\n let tri_size = 400.0;\n\n // Create a new ImgBuf\n let mut imgbuf = image::ImageBuffer::new(img_side, img_side);\n\n // Create triangle vertices\n let mut vertices: [[f32; 2]; 3] = [[0.0, 0.0]; 3];\n for i in 0..vertices.len() {\n vertices[i][0] = (img_side as f32 / 2.0)\n + (tri_size / 2.0) * (f32::consts::PI * i as f32 * 2.0 / 3.0).cos();\n vertices[i][1] = (img_side as f32 / 2.0)\n + (tri_size / 2.0) * (f32::consts::PI * i as f32 * 2.0 / 3.0).sin();\n }\n for v in &vertices {\n imgbuf.put_pixel(v[0] as u32, v[1] as u32, image::Luma([255u8]));\n }\n println!(\"Verticies: {:?}\", vertices);\n\n // Iterate chaos game\n let mut rng = rand::thread_rng();\n let mut x = img_side as f32 / 2.0;\n let mut y = img_side as f32 / 2.0;\n for _ in 0..max_iterations {\n let choice = rng.gen_range(0..vertices.len());\n x = (x + vertices[choice][0]) / 2.0;\n y = (y + vertices[choice][1]) / 2.0;\n\n imgbuf.put_pixel(x as u32, y as u32, image::Luma([255u8]));\n }\n\n // Save image\n imgbuf.save(\"fractal.png\").unwrap();\n}\n", "language": "Rust" }, { "code": "import javax.swing._\nimport java.awt._\nimport java.awt.event.ActionEvent\n\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject ChaosGame extends App {\n SwingUtilities.invokeLater(() =>\n new JFrame(\"Chaos Game\") {\n\n class ChaosGame extends JPanel {\n private val (dim, margin)= (new Dimension(640, 640), 60)\n private val sizez: Int = dim.width - 2 * margin\n private val (stack, r) = (new mutable.Stack[ColoredPoint], new Random)\n private val points = Seq(new Point(dim.width / 2, margin),\n new Point(margin, sizez),\n new Point(margin + sizez, sizez)\n )\n private val colors = Seq(Color.red, Color.green, Color.blue)\n\n override def paintComponent(gg: Graphics): Unit = {\n val g = gg.asInstanceOf[Graphics2D]\n\n def drawPoints(g: Graphics2D): Unit = {\n for (p <- stack) {\n g.setColor(colors(p.colorIndex))\n g.fillOval(p.x, p.y, 1, 1)\n }\n }\n\n super.paintComponent(gg)\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)\n drawPoints(g)\n }\n\n\n private def addPoint(): Unit = {\n val colorIndex = r.nextInt(3)\n\n def halfwayPoint(a: Point, b: Point, idx: Int) =\n new ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx)\n\n stack.push(halfwayPoint(stack.top, points(colorIndex), colorIndex))\n }\n\n class ColoredPoint(x: Int, y: Int, val colorIndex: Int) extends Point(x, y)\n\n stack.push(new ColoredPoint(-1, -1, 0))\n new Timer(100, (_: ActionEvent) => {\n if (stack.size < 50000) {\n for (i <- 0 until 1000) addPoint()\n repaint()\n }\n }).start()\n setBackground(Color.white)\n setPreferredSize(dim)\n }\n\n add(new ChaosGame, BorderLayout.CENTER)\n pack()\n setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)\n setLocationRelativeTo(null)\n setResizable(false)\n setVisible(true)\n }\n )\n\n}\n", "language": "Scala" }, { "code": "//Input\nn_sides = 3;\nside_length = 1;\nratio = 0.5;\nn_steps = 1.0d5;\nfirst_step = 0;\n\nif n_sides<3 then\n error(\"n_sides should be at least 3.\");\nend\n\n//Calculating vertices' positions\ntheta = (2 * %pi) / n_sides;\nalpha = (180 - (360/n_sides)) / 2 * (%pi/180);\nradius = (sin(theta) / side_length) / sin(alpha);\nvertices = zeros(1,n_sides);\nfor i=1:n_sides\n vertices(i) = radius * exp( %i * theta * (i-1) ); //equally spaced vertices over a circumference\n //centered on 0 + 0i, or (0,0)\nend\nclear theta alpha radius i\n\n\n//Iterations\ntic();\npoints = zeros(1,n_steps);\npoints(1) = first_step;\ni = 2;\nwhile i <= n_steps\n random=grand(1,'prm',[1:n_sides]'); //sort vertices randomly\n random=random(1); //choose the first random vertices\n\n points(i) = ( vertices(random) - points(i-1) ) * (1-ratio) + points(i-1);\n\n i = i + 1;\nend\ntime=toc();\ndisp('Time: '+string(time)+'s.');\n\n//Ploting\nscf(0); clf();\nxname('Chaos game: '+string(n_sides)+'-sides polygon');\nplot2d(real(points),imag(points),0)\nplot2d(real(vertices),imag(vertices),-3);\nset(gca(),'isoview','on');\n", "language": "Scilab" }, { "code": "require('Imager')\n\nvar width = 600\nvar height = 600\n\nvar points = [\n [width//2, 0],\n [ 0, height-1],\n [height-1, height-1],\n]\n\nvar img = %O|Imager|.new(\n xsize => width,\n ysize => height,\n )\n\nvar color = %O|Imager::Color|.new('#ff0000')\nvar r = [(width-1).irand, (height-1).irand]\n\n30000.times {\n var p = points.rand\n\n r[] = (\n (p[0] + r[0]) // 2,\n (p[1] + r[1]) // 2,\n )\n\n img.setpixel(\n x => r[0],\n y => r[1],\n color => color,\n )\n}\n\nimg.write(file => 'chaos_game.png')\n", "language": "Sidef" }, { "code": "BEGIN\n INTEGER U, COLUMNS, LINES;\n COLUMNS := 40;\n LINES := 80;\n U := ININT;\n BEGIN\n CHARACTER ARRAY SCREEN(0:LINES, 0:COLUMNS);\n INTEGER X, Y, I, VERTEX;\n\n FOR X := 0 STEP 1 UNTIL LINES-1 DO\n FOR Y := 0 STEP 1 UNTIL COLUMNS-1 DO\n SCREEN(X, Y) := ' ';\n\n X := RANDINT(0, LINES - 1, U);\n Y := RANDINT(0, COLUMNS - 1, U);\n\n FOR I := 1 STEP 1 UNTIL 5000 DO\n BEGIN\n VERTEX := RANDINT(1, 3, U);\n IF VERTEX = 1 THEN BEGIN X := X // 2;\n Y := Y // 2;\n END ELSE\n IF VERTEX = 2 THEN BEGIN X := LINES // 2 + (LINES // 2 - X) // 2;\n Y := COLUMNS - (COLUMNS - Y) // 2;\n END ELSE\n IF VERTEX = 3 THEN BEGIN X := LINES - (LINES - X) // 2;\n Y := Y // 2;\n END ELSE ERROR(\"VERTEX OUT OF BOUNDS\");\n SCREEN(X, Y) := 'X';\n END;\n\n FOR Y := 0 STEP 1 UNTIL COLUMNS-1 DO\n BEGIN\n FOR X := 0 STEP 1 UNTIL LINES-1 DO\n OUTCHAR(SCREEN(X, Y));\n OUTIMAGE;\n END;\n END;\nEND\n", "language": "Simula" }, { "code": " 10 LET X=RND*46\n 20 LET Y=RND*40\n 30 FOR I=1 TO 5000\n 40 LET VERTEX=INT (RND*3)\n 50 GOTO 60+VERTEX*30\n 60 LET X=X/2\n 70 LET Y=Y/2\n 80 GOTO 140\n 90 LET X=23+(23-X)/2\n100 LET Y=40-(40-Y)/2\n110 GOTO 140\n120 LET X=46-(46-X)/2\n130 LET Y=Y/2\n140 PLOT X,42-Y\n150 NEXT I\n", "language": "Sinclair-ZX81-BASIC" }, { "code": "Dim ← 500\nPoints ← [[50 ⌊÷2Dim] [-50Dim 50] [-50Dim -50Dim]]\n# Uncomment to try different square or pentagonal references.\n# Points ← [[50 50] [-50Dim 50] [50 -50Dim][-50Dim -50Dim]]\n# Points ← [[50 ⌊÷2Dim] [⌊×0.4Dim 50] [⌊×0.4Dim -50Dim] [-50Dim 120] [-50Dim -120Dim]]\nColours ← [[1 0 0] [0 1 0] [0 0 1] [1 1 0] [1 0 1] [0 1 1]]\nRand ← ⌊×⚂\n\n↯Dim_Dim_3 0\n∧(⍜(⊡|[1 1 1]◌))Points\n⊟Rand Dim Rand Dim\n⍥(\n Rand⧻Points\n # Set next point and colour based on target.\n ⊃(⌊÷2+⊡:Points|⊙◌⊡:Colours)\n ⟜⍜⊡◌⊙:\n)10000\n◌\n# Uncomment to save image.\n# &fwa \"UiuaChaosGameSerpinski.png\" &ime \"png\"\n", "language": "Uiua" }, { "code": "import \"dome\" for Window\nimport \"graphics\" for Canvas, Color\nimport \"math\" for Point\nimport \"random\" for Random\nimport \"./dynamic\" for Tuple\nimport \"./seq\" for Stack\n\nvar ColoredPoint = Tuple.create(\"ColoredPoint\", [\"x\", \"y\", \"colorIndex\"])\n\nclass ChaosGame {\n construct new(width, height) {\n Window.resize(width, height)\n Canvas.resize(width, height)\n Window.title = \"Chaos game\"\n _width = width\n _height = height\n _stack = Stack.new()\n _points = null\n _colors = [Color.red, Color.green, Color.blue]\n _r = Random.new()\n }\n\n init() {\n Canvas.cls(Color.white)\n var margin = 60\n var size = _width - 2 * margin\n _points = [\n Point.new((_width/2).floor, margin),\n Point.new(margin, size),\n Point.new(margin + size, size)\n ]\n _stack.push(ColoredPoint.new(-1, -1, 0))\n }\n\n addPoint() {\n var colorIndex = _r.int(3)\n var p1 = _stack.peek()\n var p2 = _points[colorIndex]\n _stack.push(halfwayPoint(p1, p2, colorIndex))\n }\n\n drawPoints() {\n for (cp in _stack) {\n var c = _colors[cp.colorIndex]\n Canvas.circlefill(cp.x, cp.y, 1, c)\n }\n }\n\n halfwayPoint(a, b, idx) { ColoredPoint.new(((a.x + b.x)/2).floor, ((a.y + b.y)/2).floor, idx) }\n\n update() {\n if (_stack.count < 50000) {\n for (i in 0...25) addPoint()\n }\n }\n\n draw(alpha) {\n drawPoints()\n }\n}\n\nvar Game = ChaosGame.new(640, 640)\n", "language": "Wren" }, { "code": " 1 ;Assemble with: tasm, tlink /t\n 2 0000 .model tiny\n 3 0000 .code\n 4 .386\n 5 org 100h\n 6 ;assume: ax=0, bx=0, cx=00FFh, dx=cs, si=0100h\n 7\n 8 0100 B0 12 start: mov al, 12h ;set 640x480x4 graphic screen\n 9 0102 CD 10 int 10h\n 10\n 11 0104 69 04 4E35 cha10: imul ax, [si], 4E35h ;generate random number\n 12 0108 40 inc ax\n 13 0109 89 04 mov [si], ax ;save seed\n 14 010B 8A C4 mov al, ah ;use high byte\n 15 010D D4 03 aam 3 ;al:= rem(al/3)\n 16 010F 8A D8 mov bl, al\n 17 0111 02 DB add bl, bl ;double to index words\n 18\n 19 0113 03 8F 0130r add cx, [bx+Tx] ;X:= (X+Tx(R)) /2\n 20 0117 D1 E9 shr cx, 1\n 21\n 22 0119 03 97 0136r add dx, [bx+Ty] ;Y:= (Y+Ty(R)) /2\n 23 011D D1 EA shr dx, 1\n 24\n 25 011F B8 0C02 mov ax, 0C02h ;write green (2) graphics pixel\n 26 0122 CD 10 int 10h ;(bh=0)\n 27\n 28 0124 B4 01 mov ah, 01h ;loop until keystroke\n 29 0126 CD 16 int 16h\n 30 0128 74 DA jz cha10\n 31\n 32 012A B8 0003 mov ax, 0003h ;restore normal text-mode screen\n 33 012D CD 10 int 10h\n 34 012F C3 ret ;return to DOS\n 35\n 36 0130 0140 002B 0255 Tx dw 320, 320-277, 320+277 ;equilateral triangle\n 37 0136 0000 01DF 01DF Ty dw 0, 479, 479\n 38 end start\n", "language": "X86-Assembly" }, { "code": "int Tx, Ty, X, Y, R;\n[SetVid($12); \\640x480x4 graphics\nTx:= [320, 320-277, 320+277]; \\equilateral triangle\nTy:= [0, 479, 479]; \\277 = 480 / (2*Sin(60))\nX:= Ran(640); \\random starting point\nY:= Ran(480);\nrepeat R:= Ran(3); \\select random triangle point\n X:= (X+Tx(R))/2; \\new point is halfway to it\n Y:= (Y+Ty(R))/2;\n Point(X, Y, 2\\green\\); \\plot new point\nuntil KeyHit;\nSetVid($03); \\restore normal text mode\n]\n", "language": "XPL0" }, { "code": "width = 640 : height = 480\nopen window width, height\nwindow origin \"lb\"\n\nx = ran(width)\ny = ran(height)\n\nfor i = 1 to 200000\n vertex = int(ran(3))\n if vertex = 1 then\n x = width / 2 + (width / 2 - x) / 2\n y = height - (height - y) / 2\n elseif vertex = 2 then\n x = width - (width - x) / 2\n y = y / 2\n else\n x = x / 2\n y = y / 2\n end if\n color 255 * (vertex = 0), 255 * (vertex = 1), 255 * (vertex = 2)\n dot x, y\nnext\n", "language": "Yabasic" }, { "code": "VREG:\tequ\t99h\t; VDP register port\nVR0:\tequ\t0F3DFh\t; Copy of VDP R0 in memory\nVR1:\tequ\t0F3E0h\t; Copy of VDP R1 in memory\nNEWKEY:\tequ\t0FBE5h\t; MSX BIOS puts key data here\nVDP:\tequ\t98h\t; VDP data port\nROM:\tequ\t0FCC0h\t; Main ROM slot\nJIFFY:\tequ\t0FCE9h\t; BIOS timer\ncalslt:\tequ\t1Ch\t; Interslot call routine\ninitxt:\tequ\t6Ch\t; Switch to default text mode\n\torg\t100h\n\tld\tbc,(JIFFY)\t; Initialize RNG with time\n\tld\td,b\n\tld\te,c\n\texx\t\t; RNG state stored in alternate registers\n\tdi\t\t; Set up the VDP for 256x192 graphics mode\n\tld\ta,(VR0)\t; Get old value of R0\n\tand\t112\t; Blank out mode bits\n\tor\t6\t; Set high 3 bits = 011(0)\n\tout\t(VREG),a\n\tld\ta,128\t; Store in register 0\n\tout\t(VREG),a\n\tld\ta,(VR1)\t; Get old value of R1\n\tand\t99\t; Blank out mode bits\n\tout\t(VREG),a\n\tld\ta,129\t; Low mode bits are 0 so we can just send it\n\tout\t(VREG),a\n\tld\ta,31\t; Bitmap starts at beginning of VRAM\n\tout\t(VREG),a\n\tld\ta,130\n\tout\t(VREG),a\n\txor\ta\t; Zero out the VRAM - set address to 0\n\tout\t(VREG),a\n\tld\ta,142\n\tout\t(VREG),a\n\txor\ta\n\tout\t(VREG),a\n\tld\ta,64\t; Tell VDP to allow writing to VRAM\n\tout\t(VREG),a\n\txor\ta \t; Write zeroes to the VDP\n\tld\tc,192\t; 2 pixels per byte, meaning 128*192 bytes\nzero1:\tld\tb,128\nzero2:\tout\t(VDP),a\n\tdjnz\tzero2\n\tdec\tc\n\tjr\tnz,zero1\n\tei\ngenX:\tcall\trandom\t; Generate starting X coordinate\n\tcp\t200\n\tjr\tnc,genX\n\tld\tb,a\t; B = X\ngenY:\tcall\trandom\t; Generate starting Y coordinate\n\tcp\t173\n\tjr\tnc,genY\n\tld\tc,a\t; C = Y\nstep:\tcall\trandom\t; Get direction\n\tand\ta,3\t; Directions {0,1,2}\n\tcp \ta,3\n\tjr\tz,step\n\tld\tixh,a\t; Store direction in IXH for color\n\tdec\ta\t; Select direction\n\tjr \tz,d1\n\tdec\ta\n\tjr\tz,d2\n\txor\ta\t; X /= 2\n\trr\tb\n\txor\ta\t; Y /= 2\n\trr\tc\n\tjr\tplot\t\nd1:\txor\ta\t; There's a 16-bit SBC but not a 16-bit SUB\n\tld \thl,100\t; (16-bit math or intermediate values won't fit)\n\tld\td,a\t; DE = X\n\tld\te,b\n\tsbc\thl,de\t; 100 - X\n\txor\ta\t\n\trr\th\t; (100 - X) / 2\n\trr\tl\n\tld\te,100\t; (100 - X) / 2 + 100\n\tadd\thl,de\n\tld\tb,l\t; -> X\t\n\txor\ta\n\tld\thl,173\t; 173\n\tld\te,c\n\tsbc\thl,de\t; (173 - Y)\n\trr\th\t; (173 - Y) / 2\n\trr\tl\n\tex\tde,hl\n\tld\tl,173\n\txor\ta\n\tsbc\thl,de\t; 173 - (173-Y)/2\n\tld\tc,l \t; -> Y\n\tjr\tplot\t\nd2:\txor\ta\n\trr \tc\t; Y /= 2\n\txor\ta\n\tld\thl,200\n\tld\td,a\t; DE = X\n\tld\te,b\n\tsbc\thl,de\t; 200-X\n\txor\ta\n\trr\th\t; (200-X)/2\n\trr\tl\n\tex\tde,hl\n\tld \tl,200\n\tsbc\thl,de\t; 200 - (200-X)/2\n\tld\tb,l\t; -> X\nplot:\tld\td,c\t; Write address = CB/2\n\tld\te,b\n\txor\ta\n\trr\td\n\trr\te\n\tld\ta,d\t; First control byte =\n\trlca\t\t; high 2 bytes of address\n\trlca\n\tand\t3\n\tld\th,a\t; Keep this value, we'll need it again\n\tdi\n\tout\t(VREG),a\n\tld\ta,142\t; To port 14\n\tout\t(VREG),a\n\tld\ta,e\t; 2nd control byte = low 8 bits\n\tout\t(VREG),a\n\tld\ta,d\t; 3rd control byte = middle 6 bits\n\tand\t63\t; Bit 6 off = read\n\tout\t(VREG),a\n\tnop\t\t; Give it some processing time\n\tnop\n\tin\ta,(VDP)\t; Read the two pixels there\n\tld\tl,a\t; Keep this byte\n\tld\ta,h\t; Now set the VDP to write to that address\n\tout\t(VREG),a\n\tld\ta,142\n\tout\t(VREG),a\n\tld\ta,e\n\tout\t(VREG),a\n\tld\ta,d\n\tand\t63\t; Bit 6 on = write\n\tor\t64\n\tout\t(VREG),a\n\tld\ta,ixh\t; Get color\n\tadd\ta,12\n\tld\td,b\t; Left or right pixel?\n\trr\td\n\tjr \tc,wpix\n\trlca\t\t; Shift left if X is even\n\trlca\n\trlca\n\trlca\nwpix:\tor\tl\t; OR with other pixel in the byte\n\tout\t(VDP),a\t; Write byte\n\tei\nwkey:\tld\ta,(NEWKEY+8)\n\tinc\ta\t; Check if space key pushed\n\tjp\tz,step\t; If not, do another step\n\tld\tiy,ROM\t; Switch back to text mode and quit\n\tld\tix,initxt\n\tjp\tcalslt\nrandom:\texx\t\t; RNG state stored in alternate registers\n\tinc\tb\t; X++\n\tld\ta,b\t; X,\n\txor\te\t; ^ C,\n\txor\tc\t; ^ A,\n\tld\tc,a\t; -> A\n\tadd\ta,d\t; + B\n\tld\td,a\t; -> B\n\trra\t\t; >> 1\n\txor\tc\t; ^ A,\n\tadd\ta,e\t; + C,\n\tld\te,a\t; -> C\n\texx\n\tret\n", "language": "Z80-Assembly" }, { "code": "w,h:=640,640;\nbitmap:=PPM(w,h,0xFF|FF|FF); // White background\ncolors:=T(0xFF|00|00,0x00|FF|00,0x00|00|FF); // red,green,blue\n\nmargin,size:=60, w - 2*margin;\npoints:=T(T(w/2, margin), T(margin,size), T(margin + size,size) );\nN,done:=Atomic.Int(0),Atomic.Bool(False);\n\nThread.HeartBeat('wrap(hb){ // a thread\n var a=List(-1,-1);\n\n if(N.inc()<50){\n do(500){\n\t colorIndex:=(0).random(3); // (0..2)\n\t b,p:=points[colorIndex], halfwayPoint(a,b);\n\t x,y:=p;\n\t bitmap[x,y]=colors[colorIndex];\n\t a=p;\n }\n bitmap.writeJPGFile(\"chaosGame.jpg\",True);\n }\n else{ hb.cancel(); done.set(); } // stop thread and signal done\n},2).go(); // run every 2 seconds, starting now\n\nfcn halfwayPoint([(ax,ay)], [(bx,by)]){ T((ax + bx)/2, (ay + by)/2) }\n\ndone.wait(); // don't exit until thread is done\nprintln(\"Done\");\n", "language": "Zkl" }, { "code": " 10 LET x=RND*200\n 20 LET y=RND*173\n 30 FOR i=1 TO 20000\n 40 LET vertex=INT (RND*3)\n 50 IF vertex=1 THEN GO TO 100\n 60 IF vertex=2 THEN GO TO 130\n 70 LET x=x/2\n 80 LET y=y/2\n 90 GO TO 150\n100 LET x=100+(100-x)/2\n110 LET y=173-(173-y)/2\n120 GO TO 150\n130 LET x=200-(200-x)/2\n140 LET y=y/2\n150 INK vertex+1\n160 PLOT x,y\n170 NEXT i\n180 INK 0\n", "language": "ZX-Spectrum-Basic" } ]
Chaos-game
[ { "code": "---\ncategory:\n- Basic language learning\n- String manipulation\n- Simple\nfrom: http://rosettacode.org/wiki/Character_codes\nnote: Text processing\n", "language": "00-META" }, { "code": ";Task:\nGiven a character value in your language, print its code &nbsp; (could be ASCII code, Unicode code, or whatever your language uses). \n\n\n;Example:\nThe character &nbsp; 'a' &nbsp; (lowercase letter A) &nbsp; has a code of 97 in ASCII &nbsp; (as well as Unicode, as ASCII forms the beginning of Unicode). \n\nConversely, given a code, print out the corresponding character.\n<br><br>\n", "language": "00-TASK" }, { "code": "print(‘a’.code) // prints \"97\"\nprint(Char(code' 97)) // prints \"a\"\n", "language": "11l" }, { "code": "* Character codes EBCDIC 15/02/2017\nCHARCODE CSECT\n USING CHARCODE,R13 base register\n B 72(R15) skip savearea\n DC 17F'0' savearea\n STM R14,R12,12(R13) prolog\n ST R13,4(R15) \" <-\n ST R15,8(R13) \" ->\n LR R13,R15 \" addressability\n* Character to Decimal\n SR R1,R1 r1=0\n IC R1,=C'a' insert character 'a'\n XDECO R1,PG\n XPRNT PG,L'PG print -> 129\n* Hexadecimal to character\n SR R1,R1 r1=0\n IC R1,=X'81' insert character X'81'\n STC R1,CHAR store character r1\n XPRNT CHAR,L'CHAR print -> 'a'\n* Decimal to character\n LH R1,=H'129' r1=129\n STC R1,CHAR store character r1\n XPRNT CHAR,L'CHAR print -> 'a'\n*\n XDUMP CHAR,L'CHAR dump -> X'81'\n*\nRETURN L R13,4(0,R13) epilog\n LM R14,R12,12(R13) \" restore\n XR R15,R15 \" rc=0\n BR R14 exit\nPG DS CL12\nCHAR DS CL1\n YREGS\n END CHARCODE\n", "language": "360-Assembly" }, { "code": " JSR ResetCoords\t\t\t\t\t;RESET TYPING CURSOR\n\n\tMOVE.B #'A',D1\n\tMOVE.W #25,D2\n\tMOVE.B #0,(softCarriageReturn) ;new line takes the cursor to left edge of screen.\n\tjsr PrintAllTheCodes\n\t\n\tjsr ResetCoords\n\tMOVE.B #8,(Cursor_X)\n\tMOVE.B #'a',D1\n\tMOVE.W #25,D2\n\tMOVE.B #8,(softCarriageReturn)\n\t;set the writing cursor to column 3 of the screen\n\t;so we don't erase the old output.\n\t\n\t\n\tjsr PrintAllTheCodes\n\t\n\nforever:\n\tbra forever\n\t\n\n\t\nPrintAllTheCodes:\n\tMOVE.B D1,D0\n\tjsr PrintChar\t\t\t;print the character as-is\n\t\n\tMOVE.B #\" \",D0\n\tjsr PrintChar\n\tMOVE.B #\"=\",D0\n\tjsr PrintChar\n\tMOVE.B #\" \",D0\n\tjsr PrintChar\n\t\n\tMOVE.B D1,D0\t\t\t;get ready to print the code\n\t\n\tJSR UnpackNibbles8\n\tSWAP D0\n\tADD.B #$30,D0\n\tJSR PrintChar\n\n\tSWAP D0\n\tCMP.B #10,D0\n\tBCS noCorrectHex\n\tADD.B #$07,D0\nnoCorrectHex:\n\tADD.B #$30,D0\n\tJSR PrintChar\n\t\n\tMOVE.B (softCarriageReturn),D0\n\tJSR doNewLine2\t\t\t\t;new line, with D0 as the carraige return point.\n\t\n\tADDQ.B #1,D1\n\tDBRA D2,PrintAllTheCodes\n\trts\n\n\nUnpackNibbles8:\n; INPUT: D0 = THE VALUE YOU WISH TO UNPACK.\n; HIGH NIBBLE IN HIGH WORD OF D0, LOW NIBBLE IN LOW WORD. SWAP D0 TO GET THE OTHER HALF.\n\tpushWord D1\n\t\tCLR.W D1\t\t\n\t\tMOVE.B D0,D1\n\t\tCLR.L D0\n\t\tMOVE.B D1,D0\t ;now D0 = D1 = $000000II, where I = input\n\t\t\n\t\tAND.B #$F0,D0\t ;chop off bottom nibble\n\t\tLSR.B #4,D0\t\t ;downshift top nibble into bottom nibble of the word\n\t\tSWAP D0\t\t\t ;store in high word\n\t\tAND.B #$0F,D1\t ;chop off bottom nibble\n\t\tMOVE.B D1,D0\t ;store in low word\n\tpopWord D1\n\trts\n", "language": "68000-Assembly" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program character64.s */\n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n/*******************************************/\n/* Initialized data */\n/*******************************************/\n.data\nszMessCodeChar: .asciz \"The code of character is : @ \\n\"\n/*******************************************/\n/* UnInitialized data */\n/*******************************************/\n.bss\nsZoneconv: .skip 32\n/*******************************************/\n/* code section */\n/*******************************************/\n.text\n.global main\nmain: // entry of program\n\n mov x0,'A'\n ldr x1,qAdrsZoneconv\n bl conversion10S\n ldr x0,qAdrszMessCodeChar\n ldr x1,qAdrsZoneconv\n bl strInsertAtCharInc // insert result at @ character\n bl affichageMess\n mov x0,'a'\n ldr x1,qAdrsZoneconv\n bl conversion10S\n ldr x0,qAdrszMessCodeChar\n ldr x1,qAdrsZoneconv\n bl strInsertAtCharInc // insert result at @ character\n bl affichageMess\n mov x0,'1'\n ldr x1,qAdrsZoneconv\n bl conversion10S\n ldr x0,qAdrszMessCodeChar\n ldr x1,qAdrsZoneconv\n bl strInsertAtCharInc // insert result at @ character\n bl affichageMess\n\n100: // standard end of the program */\n mov x0,0 // return code\n mov x8,EXIT // request to exit program\n svc 0 // perform the system call\nqAdrsZoneconv: .quad sZoneconv\nqAdrszMessCodeChar: .quad szMessCodeChar\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "report zcharcode\ndata: c value 'A', n type i.\nfield-symbols <n> type x.\n\nassign c to <n> casting.\nmove <n> to n.\nwrite: c, '=', n left-justified.\n", "language": "ABAP" }, { "code": "(cw \"~x0\" (char-code #\\a))\n(cw \"~x0\" (code-char 97))\n", "language": "ACL2" }, { "code": "PROC Main()\n CHAR c=['a]\n BYTE b=[97]\n\n Put(c) Put('=) PrintBE(c)\n PrintB(b) Put('=) Put(b)\nRETURN\n", "language": "Action-" }, { "code": "trace(String.fromCharCode(97)); //prints 'a'\ntrace(\"a\".charCodeAt(0));//prints '97'\n", "language": "ActionScript" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Char_Code is\nbegin\n Put_Line (Character'Val (97) & \" =\" & Integer'Image (Character'Pos ('a')));\nend Char_Code;\n", "language": "Ada" }, { "code": "# prints \"97\"\no_integer('a');\no_byte('\\n');\n# prints \"a\"\no_byte(97);\no_byte('\\n');\n", "language": "Aime" }, { "code": "main:(\n printf(($gl$, ABS \"a\")); # for ASCII this prints \"+97\" EBCDIC prints \"+129\" #\n printf(($gl$, REPR 97)) # for ASCII this prints \"a\"; EBCDIC prints \"/\" #\n)\n", "language": "ALGOL-68" }, { "code": "FILE tape;\nINT errno = open(tape, \"/dev/tape1\", stand out channel)\nmake conv(tape, ebcdic conv);\nFOR record DO getf(tape, ( ~ )) OD; ~ # etc ... #\n", "language": "ALGOL-68" }, { "code": " make conv(tape, stand conv(stand out channel))\n", "language": "ALGOL-68" }, { "code": "begin\n % display the character code of \"a\" (97 in ASCII) %\n write( decode( \"a\" ) );\n % display the character corresponding to 97 (\"a\" in ASCII) %\n write( code( 97 ) );\nend.\n", "language": "ALGOL-W" }, { "code": " ⎕UCS 97\na\n", "language": "APL" }, { "code": " ⎕UCS 'a'\n97\n", "language": "APL" }, { "code": " ⎕UCS 65 80 76\nAPL\n ⎕UCS 'Hello, world!'\n72 101 108 108 111 44 32 119 111 114 108 100 33\n", "language": "APL" }, { "code": "log(id of \"a\")\nlog(id of \"aA\")\n", "language": "AppleScript" }, { "code": "character id 97\n--> \"a\"\n\ncharacter id {72, 101, 108, 108, 111, 33}\n--> \"Hello!\"\n\nstring id {72, 101, 108, 108, 111, 33}\n--> \"Hello!\"\n\nUnicode text id {72, 101, 108, 108, 111, 33}\n--> \"Hello!\"\n", "language": "AppleScript" }, { "code": "?CHR$(97)\"=\"ASC(CHR$(97))\n", "language": "Applesoft-BASIC" }, { "code": "/* ARM assembly Raspberry PI */\n/* program character.s */\n\n/* Constantes */\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n/* Initialized data */\n.data\nszMessCodeChar: .ascii \"The code of character is :\"\nsZoneconv:\t\t .fill 12,1,' '\nszCarriageReturn: .asciz \"\\n\"\n\n/* UnInitialized data */\n.bss\n\n/* code section */\n.text\n.global main\nmain: /* entry of program */\n push {fp,lr} /* saves 2 registers */\n\t\n mov r0,#'A'\n ldr r1,iAdrsZoneconv\n bl conversion10S\n ldr r0,iAdrszMessCodeChar\n bl affichageMess\n mov r0,#'a'\n ldr r1,iAdrsZoneconv\n bl conversion10S\n ldr r0,iAdrszMessCodeChar\n bl affichageMess\n mov r0,#'1'\n ldr r1,iAdrsZoneconv\n bl conversion10S\n ldr r0,iAdrszMessCodeChar\n bl affichageMess\n\n100: /* standard end of the program */\n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\niAdrsZoneconv:\t\t.int sZoneconv\niAdrszMessCodeChar:\t\t.int szMessCodeChar\n/******************************************************************/\n/* display text with size calculation */\n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {fp,lr} \t\t\t/* save registres */\n push {r0,r1,r2,r7} \t\t/* save others registers */\n mov r2,#0 \t\t\t\t/* counter length */\n1: \t/* loop length calculation */\n ldrb r1,[r0,r2] \t\t\t/* read octet start position + index */\n cmp r1,#0 \t\t\t/* if 0 its over */\n addne r2,r2,#1 \t\t\t/* else add 1 in the length */\n bne 1b \t\t\t/* and loop */\n /* so here r2 contains the length of the message */\n mov r1,r0 \t\t\t/* address message in r1 */\n mov r0,#STDOUT \t\t/* code to write to the standard output Linux */\n mov r7, #WRITE /* code call system \"write\" */\n swi #0 /* call systeme */\n pop {r0,r1,r2,r7} \t\t/* restaur others registers */\n pop {fp,lr} \t\t\t\t/* restaur des 2 registres */\n bx lr\t \t\t\t/* return */\n\t\n/***************************************************/\n/* conversion register signed décimal */\n/***************************************************/\n/* r0 contient le registre */\n/* r1 contient l adresse de la zone de conversion */\nconversion10S:\n push {r0-r5,lr} /* save des registres */\n mov r2,r1 /* debut zone stockage */\n mov r5,#'+' /* par defaut le signe est + */\n cmp r0,#0 /* nombre négatif ? */\n movlt r5,#'-' /* oui le signe est - */\n mvnlt r0,r0 /* et inversion en valeur positive */\n addlt r0,#1\n mov r4,#10 /* longueur de la zone */\n1: /* debut de boucle de conversion */\n bl divisionpar10 /* division */\n add r1,#48 /* ajout de 48 au reste pour conversion ascii */\t\n strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */\n sub r4,r4,#1 /* position précedente */\n cmp r0,#0\n bne 1b\t /* boucle si quotient different de zéro */\n strb r5,[r2,r4] /* stockage du signe à la position courante */\n subs r4,r4,#1 /* position précedente */\n blt 100f /* si r4 < 0 fin */\n /* sinon il faut completer le debut de la zone avec des blancs */\n mov r3,#' ' /* caractere espace */\t\n2:\n strb r3,[r2,r4] /* stockage du byte */\n subs r4,r4,#1 /* position précedente */\n bge 2b /* boucle si r4 plus grand ou egal a zero */\n100: /* fin standard de la fonction */\n pop {r0-r5,lr} /*restaur desregistres */\n bx lr\n\n/***************************************************/\n/* division par 10 signé */\n/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*\n/* and http://www.hackersdelight.org/ */\n/***************************************************/\n/* r0 contient le dividende */\n/* r0 retourne le quotient */\t\n/* r1 retourne le reste */\ndivisionpar10:\t\n /* r0 contains the argument to be divided by 10 */\n push {r2-r4} /* save registers */\n mov r4,r0\n ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */\n smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */\n mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */\n mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */\n add r0, r2, r1 /* r0 <- r2 + r1 */\n add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */\n sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */\n pop {r2-r4}\n bx lr /* leave function */\n bx lr /* leave function */\n.Ls_magic_number_10: .word 0x66666667\n", "language": "ARM-Assembly" }, { "code": "print to :integer first \"a\"\nprint to :integer `a`\nprint to :char 97\n", "language": "Arturo" }, { "code": "MsgBox % Chr(97)\nMsgBox % Asc(\"a\")\n", "language": "AutoHotkey" }, { "code": "function ord(c)\n{\n return chmap[c]\n}\nBEGIN {\n for(i=0; i < 256; i++) {\n chmap[sprintf(\"%c\", i)] = i\n }\n print ord(\"a\"), ord(\"b\")\n printf \"%c %c\\n\", 97, 98\n s = sprintf(\"%c%c\", 97, 98)\n print s\n}\n", "language": "AWK" }, { "code": "Disp 'a'▶Dec,i\nDisp 97▶Char,i\n", "language": "Axe" }, { "code": "'abcdefg' str2ar\n{%d nl <<} eachar\n", "language": "Babel" }, { "code": "(98 97 98 101 108) ls2lf ar2str nl <<\n", "language": "Babel" }, { "code": "' ASCII\nc$ = \"$\"\nPRINT c$, \": \", ASC(c$)\n\n' UTF-8\nuc$ = \"€\"\nPRINT uc$, \": \", UCS(uc$), \", \", UCS(c$)\n", "language": "BaCon" }, { "code": "charCode = 97\nchar = \"a\"\nPRINT CHR$(charCode) 'prints a\nPRINT ASC(char) 'prints 97\n", "language": "BASIC" }, { "code": "10 LET c = 97: REM c is a character code\n20 LET d$ = \"b\": REM d$ holds the character\n30 PRINT CHR$(c): REM this prints a\n40 PRINT CODE(d$): REM this prints 98\n", "language": "BASIC" }, { "code": "# ASCII char\ncharCode = 97\nchar$ = \"a\"\nprint chr(97)\t#prints a\nprint asc(\"a\") #prints 97\n\n# Unicode char\ncharCode = 960\nchar$ = \"π\"\nprint chr(960) #prints π\nprint asc(\"π\") #prints 960\n", "language": "BASIC256" }, { "code": "@echo off\n\n:: Supports all ASCII characters and codes from 34-126 with the exceptions of:\n:: 38 &\n:: 60 <\n:: 62 >\n:: 94 ^\n:: 124 |\n\n:_main\ncall:_toCode a\ncall:_toChar 97\npause>nul\nexit /b\n\n:_toCode\nsetlocal enabledelayedexpansion\nset codecount=32\n\nfor /l %%i in (33,1,126) do (\n set /a codecount+=1\n cmd /c exit %%i\n if %1==!=exitcodeAscii! (\n echo !codecount!\n exit /b\n )\n)\n\n:_toChar\nsetlocal\ncmd /c exit %1\necho %=exitcodeAscii%\nexit /b\n", "language": "Batch-File" }, { "code": " charCode = 97\n char$ = \"a\"\n PRINT CHR$(charCode) : REM prints a\n PRINT ASC(char$) : REM prints 97\n", "language": "BBC-BASIC" }, { "code": "\"a\". 99*44*+, @\n", "language": "Befunge" }, { "code": " FromCharCode ← @⊸+\n@⊸+\n FromCharCode 97\n'a'\n FromCharCode 97‿67‿126\n\"aC~\"\n FromCharCode⁼ 'a'\n97\n", "language": "BQN" }, { "code": "( put\n$ ( str\n $ ( \"\\nLatin a\n ISO-9959-1: \"\n asc$a\n \" = \"\n chr$97\n \"\n UTF-8: \"\n utf$a\n \" = \"\n chu$97\n \\n\n \"Cyrillic а (UTF-8): \"\n utf$а\n \" = \"\n chu$1072\n \\n\n )\n )\n)\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n\nint main() {\n printf(\"%d\\n\", 'a'); /* prints \"97\" */\n printf(\"%c\\n\", 97); /* prints \"a\"; we don't have to cast because printf is type agnostic */\n return 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n\nint main() {\n std::cout << (int)'a' << std::endl; // prints \"97\"\n std::cout << (char)97 << std::endl; // prints \"a\"\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\n\nnamespace RosettaCode.CharacterCode\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.WriteLine((int) 'a'); //Prints \"97\"\n Console.WriteLine((char) 97); //Prints \"a\"\n }\n }\n}\n", "language": "C-sharp" }, { "code": "10 print \"a - > \";asc(\"a\")\n20 print \"98 -> \";chr$(98)\n", "language": "Chipmunk-Basic" }, { "code": "(print (int \\a)) ; prints \"97\"\n(print (char 97)) ; prints \\a\n\n; Unicode is also available, as Clojure uses the underlying java Strings & chars\n(print (int \\π)) ; prints 960\n(print (char 960)) ; prints \\π\n\n; use String because char in Java can't represent characters outside Basic Multilingual Plane\n(print (.codePointAt \"𝅘𝅥𝅮\" 0)) ; prints 119136\n(print (String. (int-array 1 119136) 0 1)) ; prints 𝅘𝅥𝅮\n", "language": "Clojure" }, { "code": "start_up = proc ()\n po: stream := stream$primary_output()\n\n % To turn a character code into an integer, use char$c2i\n % (but then to print it, it needs to be turned into a string first\n % with int$unparse)\n stream$putl(po, int$unparse( char$c2i( 'a' ) ) ) % prints '97'\n\n % To turn an integer into a character code, use char$i2c\n stream$putc(po, char$i2c( 97 ) ); % prints 'a'\nend start_up\n", "language": "CLU" }, { "code": " identification division.\n program-id. character-codes.\n remarks. COBOL is an ordinal language, first is 1.\n remarks. 42nd ASCII code is \")\" not, \"*\".\n procedure division.\n display function char(42)\n display function ord('*')\n goback.\n end program character-codes.\n", "language": "COBOL" }, { "code": "console.log 'a'.charCodeAt 0 # 97\nconsole.log String.fromCharCode 97 # a\n", "language": "CoffeeScript" }, { "code": "10 CH = 65: REM IN PETSCII CODE FOR 'A' IS 65\n20 D$ = \"B\": REM D$ HOLDS THE CHARACTER 'B'\n30 PRINT CHR$(CH): REM THIS PRINTS 'A'\n40 PRINT ASC(D$): REM THIS PRINTS 66\n", "language": "Commodore-BASIC" }, { "code": "(princ (char-code #\\a)) ; prints \"97\"\n(princ (code-char 97)) ; prints \"a\"\n", "language": "Common-Lisp" }, { "code": "PROCEDURE CharCodes*;\nVAR\n\tc : CHAR;\nBEGIN\n\tc := 'A';\n\tStdLog.Char(c);StdLog.String(\":> \");StdLog.Int(ORD(c));StdLog.Ln;\n\tc := CHR(3A9H);\n\tStdLog.Char(c);StdLog.String(\":> \");StdLog.Int(ORD(c));StdLog.Ln\nEND CharCodes;\n", "language": "Component-Pascal" }, { "code": "void main() {\n import std.stdio, std.utf;\n\n string test = \"a\";\n size_t index = 0;\n\n // Get four-byte utf32 value for index 0.\n writefln(\"%d\", test.decode(index));\n\n // 'index' has moved to next character input position.\n assert(index == 1);\n}\n", "language": "D" }, { "code": "97P\n", "language": "Dc" }, { "code": "program Project1;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils;\nvar\n aChar:Char;\n aCode:Byte;\n uChar:WideChar;\n uCode:Word;\nbegin\n aChar := Chr(97); Writeln(aChar);\n aCode := Ord(aChar); Writeln(aCode);\n uChar := WideChar(97); Writeln(uChar);\n uCode := Ord(uChar); Writeln(uCode);\n\n Readln;\nend.\n", "language": "Delphi" }, { "code": "proc nonrec main() void:\n writeln(pretend(97, char)); /* prints \"a\" */\n writeln(pretend('a', byte)); /* prints 97 */\ncorp\n", "language": "Draco" }, { "code": "PrintLn(Ord('a'));\nPrintLn(Chr(97));\n", "language": "DWScript" }, { "code": "print('a'.Order())\nprint(Char(97))\n", "language": "Dyalect" }, { "code": "? 'a'.asInteger()\n# value: 97\n\n? <import:java.lang.makeCharacter>.asChar(97)\n# value: 'a'\n", "language": "E" }, { "code": "print strcode \"a\"\nprint strchar 97\n", "language": "EasyLang" }, { "code": "module CharacterCodes {\n @Inject Console console;\n void run() {\n for (Char char : ['\\0', '\\d', 'A', '$', '¢', '~', '˜']) {\n // character to its integer value\n UInt32 codepoint = char.codepoint;\n\n // integer value back to its character value\n Char fromCodePoint = codepoint.toChar(); // or: \"new Char(codepoint)\"\n\n console.print($|Character {char.quoted()}:\\\n | Unicode codepoint={char.codepoint},\\\n | ASCII={char.ascii},\\\n | UTF8 bytes={char.utf8()},\\\n | char from codepoint={fromCodePoint.quoted()}\n );\n }\n }\n}\n", "language": "Ecstasy" }, { "code": "class\n\tAPPLICATION\ninherit\n\tARGUMENTS\ncreate\n\tmake\n\nfeature {NONE} -- Initialization\n\n\tmake\n\t\t\t-- Run application.\n\t\tlocal\n\t\t\tc8: CHARACTER_8\n\t\t\tc32: CHARACTER_32\n\t\tdo\n\t\t\tc8 := '%/97/'\t\t\t-- using code value notation\n\t\t\tc8 := '%/0x61/'\t\t\t-- same as above, but using hexadecimal literal\n\t\t\tprint(c8.natural_32_code)\t-- prints \"97\"\n\t\t\tprint(c8)\t\t\t-- prints the character \"a\"\n\t\t\t\n\t\t\tc32 := 'a'\t\t\t-- using character literal\n\t\t\tprint(c32.natural_32_code)\t-- prints \"97\"\n\t\t\tprint(c32)\t\t\t-- prints \"U+00000061\"\n\n\t\t\t--c8 := 'π'\t\t\t-- compile-time error (c8 does not have enough range)\n\t\t\tc32 := 'π'\t\t\t-- assigns Unicode value 960\n\t\tend\nend\n", "language": "Eiffel" }, { "code": "import extensions;\n\npublic program()\n{\n var ch := $97;\n\n console.printLine(ch);\n console.printLine(ch.toInt())\n}\n", "language": "Elena" }, { "code": "iex(1)> code = ?a\n97\niex(2)> to_string([code])\n\"a\"\n", "language": "Elixir" }, { "code": "(string-to-char \"a\") ;=> 97\n(format \"%c\" 97) ;=> \"a\"\n", "language": "Emacs-Lisp" }, { "code": "^|ord and chr work with Unicode code points|^\nwriteLine(ord(\"a\")) # prints \"97\"\nwriteLine(chr(97)) # prints \"a\"\nwriteLine(ord(\"π\")) # prints \"960\"\nwriteLine(chr(960)) # prints \"π\"\nwriteLine()\nvar cps = int[]\nfor each var c in text[\"a\", \"π\", \"字\", \"🐘\"]\n var cp = ord(c)\n cps.append(cp)\n writeLine(c + \" = \" + cp)\nend\nwriteLine()\nfor each int i in cps\n var c = chr(i)\n writeLine(i + \" = \" + c)\nend\n", "language": "EMal" }, { "code": "1> F = fun([X]) -> X end.\n#Fun<erl_eval.6.13229925>\n2> F(\"a\").\n97\n", "language": "Erlang" }, { "code": "3> $a.\n97\n", "language": "Erlang" }, { "code": "printf(1,\"%d\\n\", 'a') -- prints \"97\"\nprintf(1,\"%s\\n\", 97) -- prints \"a\"\n", "language": "Euphoria" }, { "code": "let c = 'A'\nlet n = 65\nprintfn \"%d\" (int c)\nprintfn \"%c\" (char n)\n", "language": "F-Sharp" }, { "code": "CHAR: katakana-letter-a .\n\"ア\" first .\n\n12450 1string print\n", "language": "Factor" }, { "code": "'A.\"\n\"65,\n", "language": "FALSE" }, { "code": "fansh> 97.toChar\na\nfansh> 'a'.toInt\n97\n", "language": "Fantom" }, { "code": "(string.byte :A) ; 65\n(string.char 65) ; \"A\"\n", "language": "Fennel" }, { "code": "char a\ndup . \\ 97\nemit \\ a\n", "language": "Forth" }, { "code": "WRITE(*,*) ACHAR(97), IACHAR(\"a\")\nWRITE(*,*) CHAR(97), ICHAR(\"a\")\n", "language": "Fortran" }, { "code": "' FreeBASIC v1.05.0 win64\nPrint \"a - > \"; Asc(\"a\")\nPrint \"98 -> \"; Chr(98)\nPrint\nPrint \"Press any key to exit the program\"\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "println[char[\"a\"]] // prints 97\nprintln[chars[\"a\"]] // prints [97] (an array)\nprintln[char[97]] // prints a\nprintln[char[\"Frink rules!\"]] // prints [70, 114, 105, 110, 107, 32, 114, 117, 108, 101, 115, 33]\nprintln[[70, 114, 105, 110, 107, 32, 114, 117, 108, 101, 115, 33]] // prints \"Frink rules!\"\n", "language": "Frink" }, { "code": "print \"a -> \"; ASC(\"a\")\nprint \"98 -> \"; CHR$(98)\n\nhandleevents\n", "language": "FutureBasic" }, { "code": "Public Sub Form_Open()\nDim sChar As String\n\nsChar = InputBox(\"Enter a character\")\nPrint \"Character \" & sChar & \" = ASCII \" & Str(Asc(sChar))\n\nsChar = InputBox(\"Enter a ASCII code\")\nPrint \"ASCII code \" & sChar & \" represents \" & Chr(Val(sChar))\n\nEnd\n", "language": "Gambas" }, { "code": "# Code must be in 0 .. 255.\nCharInt(65);\n# 'A'\nIntChar('Z');\n# 90\n", "language": "Gambas" }, { "code": "fmt.Println('a') // prints \"97\"\nfmt.Println('π') // prints \"960\"\n", "language": "Go" }, { "code": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\t// Given a character value in your language, print its code\n\tfmt.Printf(\"%d\\n\", 'A') // prt 65\n\t// Given a code, print out the corresponding character.\n\tfmt.Printf(\"%c\\n\", 65) // prt A\n}\n", "language": "Go" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\t// yes, there is more concise syntax, but this makes\n\t// the data types very clear.\n\tvar b byte = 'a'\n\tvar r rune = 'π'\n\tvar s string = \"aπ\"\n\n\tfmt.Println(b, r, s)\n\tfmt.Println(\"string cast to []rune:\", []rune(s))\n\t// A range loop over a string gives runes, not bytes\n\tfmt.Print(\" string range loop: \")\n\tfor _, c := range s {\n\t\tfmt.Print(c, \" \") // c is type rune\n\t}\n\t// We can also print the bytes of a string without an explicit loop\n\tfmt.Printf(\"\\n string bytes: % #x\\n\", s)\n}\n", "language": "Go" }, { "code": "b := byte(97)\nr := rune(960)\nfmt.Printf(\"%c %c\\n%c %c\\n\", 97, 960, b, r)\n", "language": "Go" }, { "code": "fmt.Println(string(97)) // prints \"a\"\nfmt.Println(string(960)) // prints \"π\"\nfmt.Println(string([]rune{97, 960})) // prints \"aπ\"\n", "language": "Go" }, { "code": "97[]+''+p\n", "language": "Golfscript" }, { "code": "'a')\\;p\n'a'(\\;p\n'a'0=p\n'a'{}/p\n", "language": "Golfscript" }, { "code": "printf (\"%d\\n\", ('a' as char) as int)\nprintf (\"%c\\n\", 97)\n", "language": "Groovy" }, { "code": "10 PRINT \"a - > \"; ASC(\"a\")\n20 PRINT \"98 -> \"; CHR$(98)\n", "language": "GW-BASIC" }, { "code": "import Data.Char\n\nmain = do\n print (ord 'a') -- prints \"97\"\n print (chr 97) -- prints \"'a'\"\n print (ord 'π') -- prints \"960\"\n print (chr 960) -- prints \"'\\960'\"\n", "language": "Haskell" }, { "code": "WRITE(Messagebox) ICHAR('a'), CHAR(97)\n", "language": "HicEst" }, { "code": "Print(\"%d\\n\", 'a'); /* prints \"97\" */\nPrint(\"%c\\n\", 97); /* prints \"a\" */\n", "language": "HolyC" }, { "code": "|%\n++ enc\n |= char=@t `@ud`char\n++ dec\n |= code=@ud `@t`code\n--\n", "language": "Hoon" }, { "code": "software {\n\tprint(number('a'))\n\tprint(text([97]))\n}\n", "language": "I" }, { "code": "procedure main(arglist)\nif *arglist > 0 then L := arglist else L := [97, \"a\"]\n\nevery x := !L do\n write(x, \" ==> \", char(integer(x)) | ord(x) ) # char produces a character, ord produces a number\nend\n", "language": "Icon" }, { "code": "\"a\" at(0) println // --> 97\n97 asCharacter println // --> a\n\n\"π\" at(0) println // --> 960\n960 asCharacter println // --> π\n", "language": "Io" }, { "code": "100 PRINT ORD(\"A\")\n110 PRINT CHR$(65)\n", "language": "IS-BASIC" }, { "code": " 4 u: 97 98 99 9786\nabc☺\n\n 3 u: 7 u: 'abc☺'\n97 98 99 9786\n", "language": "J" }, { "code": " 3 u: 'abc☺'\n97 98 99 226 152 186\n", "language": "J" }, { "code": " 97 98 99{a.\nabc\n a.i.'abc'\n97 98 99\n", "language": "J" }, { "code": "(int) 'a'\n", "language": "Java" }, { "code": "(int) '\\u0061'\n", "language": "Java" }, { "code": "(char) 97\n", "language": "Java" }, { "code": "Character.digit('1', 10)\n", "language": "Java" }, { "code": "Character.forDigit(1, 10)\n", "language": "Java" }, { "code": "console.log('a'.charCodeAt(0)); // prints \"97\"\nconsole.log(String.fromCharCode(97)); // prints \"a\"\n", "language": "JavaScript" }, { "code": "['字'.codePointAt(0), '🐘'.codePointAt(0)]\n", "language": "JavaScript" }, { "code": "[23383, 128024]\n", "language": "JavaScript" }, { "code": "[23383, 128024].map(function (x) {\n\treturn String.fromCodePoint(x);\n})\n", "language": "JavaScript" }, { "code": "[\"字\", \"🐘\"]\n", "language": "JavaScript" }, { "code": "'a ord.\n97 chr.\n", "language": "Joy" }, { "code": "\"a\" | explode # => [ 97 ]\n[97] | implode # => \"a\"\n", "language": "Jq" }, { "code": "def chr: [.] | implode;\n", "language": "Jq" }, { "code": "println(Int('a'))\nprintln(Char(97))\n", "language": "Julia" }, { "code": " _ic \"abcABC\"\n97 98 99 65 66 67\n\n _ci 97 98 99 65 66 67\n\"abcABC\"\n", "language": "K" }, { "code": "fun main() {\n var c = 'a'\n var i = c.code\n println(\"$c <-> $i\")\n i += 2\n c = i.toChar()\n println(\"$i <-> $c\")\n}\n", "language": "Kotlin" }, { "code": "fn.println(fn.toValue(a)) # Prints \"97\"\nfn.println(fn.toChar(97)) # Prints \"a\"\n\n# Unicode\nfn.println(fn.toValue(π)) # Prints \"960\"\nfn.println(fn.toChar(960)) # Prints \"π\"\n", "language": "Lang" }, { "code": ": CHAR \"!\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\" comb\n '\\\\ comb -1 remove append \"]^_`abcdefghijklmnopqrstuvwxyz{|}~\" comb append ;\n: CODE 95 iota 33 + ; : comb \"\" split ;\n: extract' rot 1 compress index subscript expand drop ;\n: chr CHAR CODE extract' ;\n: ord CODE CHAR extract' ;\n\n'a ord . # 97\n97 chr . # a\n", "language": "Lang5" }, { "code": "val .a1 = 'a'\nval .a2 = 97\nval .a3 = \"a\"[1]\nval .a4 = s2cp \"a\", 1\nval .a5 = [.a1, .a2, .a3, .a4]\n\nwriteln .a1 == .a2\nwriteln .a2 == .a3\nwriteln .a3 == .a4\nwriteln \"numbers: \", join \", \", [.a1, .a2, .a3, .a4, .a5]\nwriteln \"letters: \", join \", \", map cp2s, [.a1, .a2, .a3, .a4, .a5]\n", "language": "Langur" }, { "code": "'a'->integer\n'A'->integer\n97->bytes\n65->bytes\n", "language": "Lasso" }, { "code": "> (list 68 111 110 39 116 32 80 97 110 105 99 46)\n\"Don't Panic.\"\n", "language": "LFE" }, { "code": "> (: io format '\"~w~n\" '\"a\")\n97\nok\n> (: io format '\"~p~n\" (list '(97)))\n\"a\"\nok\n", "language": "LFE" }, { "code": "charCode = 97\nchar$ = \"a\"\nprint chr$(charCode) 'prints a\nprint asc(char$) 'prints 97\n", "language": "Liberty-BASIC" }, { "code": "print [char 97]\nprint [codeat \"a\" 0]\n", "language": "LIL" }, { "code": "-- returns Unicode code point (=ASCII code for ASCII characters) for character\nput chartonum(\"a\")\n-- 97\n\n-- returns character for Unicode code point (=ASCII code for ASCII characters)\nput numtochar(934)\n-- Φ\n", "language": "Lingo" }, { "code": "puts(\"Unicode value of ñ is ${scan(\"ñ\", \"%c\")}\");\nprintf(\"The code 241 in Unicode is the letter: %c.\\n\", 241);\n", "language": "Little" }, { "code": "Since 7.0.x works with unicode\nput charToNum(\"\") && numToChar(240)\n", "language": "LiveCode" }, { "code": "print ascii \"a ; 97\nprint char 97 ; a\n", "language": "Logo" }, { "code": "|?- char_code(Char, 97), write(Char).\na\nChar = a\nyes\n", "language": "Logtalk" }, { "code": "|?- char_code(a, Code), write(Code).\n97\nCode = 97\nyes\n", "language": "Logtalk" }, { "code": "print(string.byte(\"a\")) -- prints \"97\"\nprint(string.char(97)) -- prints \"a\"\n", "language": "Lua" }, { "code": "\\\\ ANSI\nPrint Asc(\"a\")\nPrint Chr$(Asc(\"a\"))\n\\\\ Utf16-Le\nPrint ChrCode(\"a\")\nPrint ChrCode$(ChrCode(\"a\"))\n\n\\\\ (,) is an empty array.\n\nFunction Codes(a$) {\n If Len(A$)=0 then =(,) : Exit\n Buffer Mem as byte*Len(a$)\n \\\\ Str$(string) return one byte character\n Return Mem, 0:=Str$(a$)\n Inventory Codes\n For i=0 to len(Mem)-1\n Append Codes, i:=Eval(Mem, i)\n Next i\n =Codes\n}\nPrint Codes(\"abcd\")\n\\\\ 97 98 99 100\n", "language": "M2000-Interpreter" }, { "code": "> use StringTools in Ord( \"A\" ); Char( 65 ) end;\n 65\n\n \"A\"\n", "language": "Maple" }, { "code": "> convert( \"A\", bytes );\n [65]\n\n> convert( [65], bytes );\n \"A\"\n", "language": "Maple" }, { "code": "ToCharacterCode[\"abcd\"]\nFromCharacterCode[{97}]\n", "language": "Mathematica" }, { "code": "character = char(asciiNumber)\n", "language": "MATLAB" }, { "code": "asciiNumber = double(character)\n", "language": "MATLAB" }, { "code": "asciiNumber = uint16(character)\nasciiNumber = uint32(character)\nasciiNumber = uint64(character)\n", "language": "MATLAB" }, { "code": ">> char(87)\n\nans =\n\nW\n\n>> double('W')\n\nans =\n\n 87\n\n>> uint16('W')\n\nans =\n\n 87\n", "language": "MATLAB" }, { "code": "ascii(65);\n\"A\"\n\ncint(\"A\");\n65\n", "language": "Maxima" }, { "code": "message \"enter a letter: \";\nstring a;\na := readstring;\nmessage decimal (ASCII a); % writes the decimal number of the first character\n % of the string a\nmessage \"enter a number: \";\nnum := scantokens readstring;\nmessage char num; % num can be anything between 0 and 255; what will be seen\n % on output depends on the encoding used by the \"terminal\"; e.g.\n % any code beyond 127 when UTF-8 encoding is in use will give\n % a bad encoding; e.g. to see correctly an \"è\", we should write\nmessage char10; % (this add a newline...)\nmessage char hex\"c3\" & char hex\"a8\"; % since C3 A8 is the UTF-8 encoding for \"è\"\nend\n", "language": "Metafont" }, { "code": "TextWindow.WriteLine(\"The ascii code for 'A' is: \" + Text.GetCharacterCode(\"A\") + \".\")\nTextWindow.WriteLine(\"The character for '65' is: \" + Text.GetCharacter(65) + \".\")\n", "language": "Microsoft-Small-Basic" }, { "code": "The ascii code for 'A' is: 65.\nThe character for '65' is: A.\nPress any key to continue...\n", "language": "Microsoft-Small-Basic" }, { "code": "cps = []\nfor c in [\"a\", \"π\", \"字\", \"🐘\"]\n cp = c.code\n cps.push cp\n print c + \" = \" + cp\nend for\nprint\nfor i in cps\n print i + \" = \" + char(i)\nend for\n", "language": "MiniScript" }, { "code": "MODULE asc;\n\nIMPORT InOut;\n\nVAR letter : CHAR;\n ascii : CARDINAL;\n\nBEGIN\n letter := 'a';\n InOut.Write (letter);\n ascii := ORD (letter);\n InOut.Write (11C); (* ASCII TAB *)\n InOut.WriteCard (ascii, 8);\n ascii := ascii - ORD ('0');\n InOut.Write (11C); (* ASCII TAB *)\n InOut.Write (CHR (ascii));\n InOut.WriteLn\nEND asc.\n", "language": "Modula-2" }, { "code": "jan@Beryllium:~/modula/rosetta$ ./asc\na 97 1\n", "language": "Modula-2" }, { "code": "ORD('a') (* Returns 97 *)\nVAL(97, CHAR); (* Returns 'a' *)\n", "language": "Modula-3" }, { "code": "10 PRINT \"a - > \"; ASC(\"a\")\n20 PRINT \"98 -> \"; CHR$(98)\n", "language": "MSX-Basic" }, { "code": "WRITE $ASCII(\"M\")\nWRITE $CHAR(77)\n", "language": "MUMPS" }, { "code": "println ord(\"a\")\nprintln chr(97)\n\nprintln ord(\"π\")\nprintln chr(960)\n", "language": "Nanoquery" }, { "code": "// An 'a' and a 'b'\nvar s = \"a\";\nvar c = 98;\nvar h = \" \";\n\n$print(\"Character code for 'a': \", $sget(s, 0), \"\\n\");\n\n$sset(h, 0, c);\n$print(\"Character code \", c, \": \", h, \"\\n\");\n", "language": "Neko" }, { "code": "// While Neko also includes some UTF-8 operations,\n// native strings are just arrays of bytes\nvar us = \"¥·£·€·$·¢·₡·₢·₣·₤·₥·₦·₧·₨·₩·₪·₫·₭·₮·₯·₹\";\n\n// load some Std lib primitives\nutfGet = $loader.loadprim(\"std@utf8_get\", 2);\nutfSub = $loader.loadprim(\"std@utf8_sub\", 3);\nutfAlloc = $loader.loadprim(\"std@utf8_buf_alloc\", 1);\nutfAdd = $loader.loadprim(\"std@utf8_buf_add\", 2);\nutfContent = $loader.loadprim(\"std@utf8_buf_content\", 1);\n\n// Pull out the Euro currency symbol from the UTF-8 currency sampler\nvar uc = utfGet(us, 4);\n$print(\"UFT-8 code for '\", utfSub(us, 4, 1), \"': \", uc, \"\\n\");\n\n// Build a UTF-8 buffer\nvar buf = utfAlloc(4);\n\n// Add a Pound Sterling symbol\nuc = 8356;\nutfAdd(buf, uc);\n$print(\"UTF-8 code \", uc, \": \", utfContent(buf), \"\\n\");\n", "language": "Neko" }, { "code": "char_code(`a);\n\nit = 97 : int\n", "language": "NESL" }, { "code": "code_char(97);\n\nit = `a : char\n", "language": "NESL" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\nrunSample(arg)\nreturn\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod runSample(arg) private static\n -- create some sample data: character, hex and unicode\n samp = ' ' || 'a'.sequence('e') || '$' || '\\xa2'.sequence('\\xa5') || '\\u20a0'.sequence('\\u20b5')\n -- use the C2D C2X D2C and X2C built-in functions\n say \"'\"samp\"'\"\n say ' | Chr C2D C2X D2C X2C'\n say '---+ --- ------ ---- --- ---'\n loop ci = 1 to samp.length\n cc = samp.substr(ci, 1)\n cd = cc.c2d -- char to decimal\n cx = cc.c2x -- char to hexadecimal\n dc = cd.d2c -- decimal to char\n xc = cx.x2c -- hexadecimal to char\n say ci.right(3)\"| '\"cc\"'\" cd.right(6) cx.right(4, 0) \"'\"dc\"' '\"xc\"'\"\n end ci\n return\n", "language": "NetRexx" }, { "code": "echo ord('a') # echoes 97\necho chr(97) # echoes a\n\nimport unicode\n\necho int(\"π\".runeAt(0)) # echoes 960\necho Rune(960) # echoes π\n", "language": "Nim" }, { "code": "10 PRINT CODE \"A\"\n20 PRINT CHR$(38)\n", "language": "NS-HUBASIC" }, { "code": "MODULE Ascii;\nIMPORT Out;\nVAR\n\tc: CHAR;\n\td: INTEGER;\nBEGIN\n\tc := CHR(97);\n\td := ORD(\"a\");\n\tOut.Int(d,3);Out.Ln;\n\tOut.Char(c);Out.Ln\nEND Ascii.\n", "language": "Oberon" }, { "code": "'a'->As(Int)->PrintLine();\n97->As(Char)->PrintLine();\n", "language": "Objeck" }, { "code": "Printf.printf \"%d\\n\" (int_of_char 'a'); (* prints \"97\" *)\nPrintf.printf \"%c\\n\" (char_of_int 97); (* prints \"a\" *)\n", "language": "OCaml" }, { "code": "# Char.code ;;\n- : char -> int = <fun>\n# Char.chr;;\n- : int -> char = <fun>\n", "language": "OCaml" }, { "code": "'a' println\n", "language": "Oforth" }, { "code": "MESSAGE\n CHR(97) SKIP\n ASC(\"a\")\nVIEW-AS ALERT-BOX.\n", "language": "OpenEdge-Progress" }, { "code": "{System.show &a} %% prints \"97\"\n{System.showInfo [97]} %% prints \"a\"\n", "language": "Oz" }, { "code": "print(Vecsmall(\"a\")[1]);\nprint(Strchr([72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]))\n", "language": "PARI-GP" }, { "code": "writeln(ord('a'));\nwriteln(chr(97));\n", "language": "Pascal" }, { "code": "use strict;\nuse warnings;\nuse utf8;\nbinmode(STDOUT, ':utf8');\nuse Encode;\nuse Unicode::UCD 'charinfo';\nuse List::AllUtils qw(zip natatime);\n\nfor my $c (split //, 'AΑА薵') {\n my $o = ord $c;\n my $utf8 = join '', map { sprintf \"%x \", ord } split //, Encode::encode(\"utf8\", $c);\n my $iterator = natatime 2, zip\n @{['Character', 'Character name', 'Ordinal(s)', 'Hex ordinal(s)', 'UTF-8', 'Round trip']},\n @{[ $c, charinfo($o)->{'name'}, $o, sprintf(\"0x%x\",$o), $utf8, chr $o, ]};\n while ( my ($label, $value) = $iterator->() ) {\n printf \"%14s: %s\\n\", $label, $value\n }\n print \"\\n\";\n}\n", "language": "Perl" }, { "code": "use strict;\nuse warnings;\nuse feature 'say';\nuse utf8;\nbinmode(STDOUT, ':utf8');\nuse Unicode::Normalize 'NFC';\nuse Unicode::UCD qw(charinfo charprop);\n\nwhile ('Δ̂🇺🇸👨‍👩‍👧‍👦' =~ /(\\X)/g) {\n my @ordinals = map { ord } split //, my $c = $1;\n printf \"%14s: %s\\n\"x7 . \"\\n\",\n 'Character', NFC $c,\n 'Character name', join(', ', map { charinfo($_)->{'name'} } @ordinals),\n 'Unicode property', join(', ', map { charprop($_, \"Gc\") } @ordinals),\n 'Ordinal(s)', join(' ', @ordinals),\n 'Hex ordinal(s)', join(' ', map { sprintf(\"0x%x\", $_) } @ordinals),\n 'UTF-8', join('', map { sprintf \"%x \", ord } (utf8::encode($c), split //, $c)),\n 'Round trip', join('', map { chr } @ordinals);\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">'A'</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">65</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "'a' print nl\n97 tochar print\n", "language": "Phixmonti" }, { "code": "echo ord('a'), \"\\n\"; // prints \"97\"\necho chr(97), \"\\n\"; // prints \"a\"\n", "language": "PHP" }, { "code": "main =>\n println(chr(97)),\n println(ord('a')),\n println(ord(a)).\n", "language": "Picat" }, { "code": ": (char \"a\")\n-> 97\n: (char \"字\")\n-> 23383\n: (char 23383)\n-> \"字\"\n: (chop \"文字\")\n-> (\"文\" \"字\")\n: (mapcar char @)\n-> (25991 23383)\n", "language": "PicoLisp" }, { "code": "declare 1 u union,\n 2 c character (1),\n 2 i fixed binary (8) unsigned;\nc = 'a'; put skip list (i); /* prints 97 */\ni = 97; put skip list (c); /* prints 'a' */\n", "language": "PL-I" }, { "code": "\\ Obs: The little-a byte is a byte equal to 97.\nWrite the little-a byte's whereabouts on the console.\nPut 97 into a number.\nWrite the number's target on the console.\n", "language": "Plain-English" }, { "code": "$char = [convert]::toChar(0x2f) #=> /\n", "language": "PowerShell" }, { "code": "$char = [char] 'a'\n", "language": "PowerShell" }, { "code": "$charcode = [int] $char # => 97\n", "language": "PowerShell" }, { "code": "[int] [char] '☺' # => 9786\n", "language": "PowerShell" }, { "code": "[char] 97 # a\n[char] 9786 # ☺\n", "language": "PowerShell" }, { "code": "If OpenConsole()\n ;Results are the same when compiled for Ascii or Unicode\n charCode.c = 97\n Char.s = \"a\"\n PrintN(Chr(charCode)) ;prints a\n PrintN(Str(Asc(Char))) ;prints 97\n\n Print(#CRLF$ + #CRLF$ + \"Press ENTER to exit\")\n Input()\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": "If OpenConsole()\n ;UTF-8 encoding compiled for Unicode (UCS-2)\n charCode.c = 960\n Char.s = \"π\"\n PrintN(Chr(charCode)) ;prints π\n PrintN(Str(Asc(Char))) ;prints 960\n\n Print(#CRLF$ + #CRLF$ + \"Press ENTER to exit\")\n Input()\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": "print ord('a') # prints \"97\"\nprint chr(97) # prints \"a\"\n", "language": "Python" }, { "code": "print ord(u'π') # prints \"960\"\nprint unichr(960) # prints \"π\"\n", "language": "Python" }, { "code": "print(ord('a')) # prints \"97\" (will also work in 2.x)\nprint(ord('π')) # prints \"960\"\nprint(chr(97)) # prints \"a\" (will also work in 2.x)\nprint(chr(960)) # prints \"π\"\n", "language": "Python" }, { "code": "PRINT \"a - > \"; ASC(\"a\")\nPRINT \"98 -> \"; CHR$(98)\n", "language": "QBasic" }, { "code": "ascii <- as.integer(charToRaw(\"hello world\")); ascii\ntext <- rawToChar(as.raw(ascii)); text\n", "language": "R" }, { "code": "#lang racket\n\n(define (code ch)\n (printf \"The unicode number for ~s is ~a\\n\" ch (char->integer ch)))\n(code #\\a)\n(code #\\λ)\n\n(define (char n)\n (printf \"The unicode number ~a is the character ~s\\n\" n (integer->char n)))\n(char 97)\n(char 955)\n", "language": "Racket" }, { "code": "for 'AΑА𪚥🇺🇸👨‍👩‍👧‍👦'.comb {\n .put for\n [ 'Character',\n 'Character name',\n 'Unicode property',\n 'Unicode script',\n 'Unicode block',\n 'Added in Unicode version',\n 'Ordinal(s)',\n 'Hex ordinal(s)',\n 'UTF-8',\n 'UTF-16LE',\n 'UTF-16BE',\n 'Round trip by name',\n 'Round trip by ordinal'\n ]».fmt('%25s:')\n Z\n [ $_,\n .uninames.join(', '),\n .uniprops.join(', '),\n .uniprops('Script').join(', '),\n .uniprops('Block').join(', '),\n .uniprops('Age').join(', '),\n .ords,\n .ords.fmt('0x%X'),\n .encode('utf8' )».fmt('%02X'),\n .encode('utf16le')».fmt('%02X').join.comb(4),\n .encode('utf16be')».fmt('%02X').join.comb(4),\n .uninames».uniparse.join,\n .ords.chrs\n ];\n say '';\n}\n", "language": "Raku" }, { "code": "Print Chr$(97)\nPrint Asc(\"a\")\n", "language": "RapidQ" }, { "code": "Red []\nprint to-integer first \"a\" ;; -> 97\nprint to-integer #\"a\" ;; -> 97\nprint to-binary \"a\" ;; -> #{61}\nprint to-char 97 ;; -> a\n", "language": "Red" }, { "code": "'c putc\n", "language": "Retro" }, { "code": "/*REXX program displays a char's ASCII code/value (or EBCDIC if run on an EBCDIC system)*/\nyyy= 'c' /*assign a lowercase c to YYY. */\nyyy= \"c\" /* (same as above) */\nsay 'from char, yyy code=' yyy\n\nyyy= '63'x /*assign hexadecimal 63 to YYY. */\nyyy= '63'X /* (same as above) */\nsay 'from hex, yyy code=' yyy\n\nyyy= x2c(63) /*assign hexadecimal 63 to YYY. */\nsay 'from hex, yyy code=' yyy\n\nyyy= '01100011'b /*assign a binary 0011 0100 to YYY. */\nyyy= '0110 0011'b /* (same as above) */\nyyy= '0110 0011'B /* \" \" \" */\nsay 'from bin, yyy code=' yyy\n\nyyy= d2c(99) /*assign decimal code 99 to YYY. */\nsay 'from dec, yyy code=' yyy\n\nsay /* [↓] displays the value of YYY in ··· */\nsay 'char code: ' yyy /* character code (as an 8-bit ASCII character).*/\nsay ' hex code: ' c2x(yyy) /* hexadecimal */\nsay ' dec code: ' c2d(yyy) /* decimal */\nsay ' bin code: ' x2b( c2x(yyy) ) /* binary (as a bit string) */\n /*stick a fork in it, we're all done with display*/\n", "language": "REXX" }, { "code": "/* REXX */\nyyy='c' /*assign a lowercase c to YYY */\nyyy='83'x /*assign hexadecimal 83 to YYY */\n /*the X can be upper/lowercase.*/\nyyy=x2c(83) /* (same as above) */\nyyy='10000011'b /* (same as above) */\nyyy='1000 0011'b /* (same as above) */\n /*the B can be upper/lowercase.*/\nyyy=d2c(129) /*assign decimal code 129 to YYY */\n\nsay yyy /*displays the value of YYY */\nsay c2x(yyy) /*displays the value of YYY in hexadecimal. */\nsay c2d(yyy) /*displays the value of YYY in decimal. */\nsay x2b(c2x(yyy))/*displays the value of YYY in binary (bit string). */\n", "language": "REXX" }, { "code": "see ascii(\"a\") + nl\nsee char(97) + nl\n", "language": "Ring" }, { "code": "> \"a\".ord\n=> 97\n> 97.chr\n=> \"a\"\n", "language": "Ruby" }, { "code": "print chr$(97) 'prints a\nprint asc(\"a\") 'prints 97\n", "language": "Run-BASIC" }, { "code": "use std::char::from_u32;\n\nfn main() {\n //ascii char\n println!(\"{}\", 'a' as u8);\n println!(\"{}\", 97 as char);\n\n //unicode char\n println!(\"{}\", 'π' as u32);\n println!(\"{}\", from_u32(960).unwrap());\n}\n", "language": "Rust" }, { "code": "class MAIN is\n main is\n #OUT + 'a'.int + \"\\n\"; -- or\n #OUT + 'a'.ascii_int + \"\\n\";\n #OUT + CHAR::from_ascii_int(97) + \"\\n\";\n end;\nend;\n", "language": "Sather" }, { "code": "scala> 'a' toInt\nres2: Int = 97\n\nscala> 97 toChar\nres3: Char = a\n\nscala> '\\u0061'\nres4: Char = a\n\nscala> \"\\uD869\\uDEA5\"\nres5: String = 𪚥\n", "language": "Scala" }, { "code": "import java.lang.Character._; import scala.annotation.tailrec\n\nobject CharacterCode extends App {\n def intToChars(n: Int): Array[Char] = java.lang.Character.toChars(n)\n\n def UnicodeToList(UTFstring: String) = {\n @tailrec\n def inner(str: List[Char], acc: List[String], surrogateHalf: Option[Char]): List[String] = {\n (str, surrogateHalf) match {\n case (Nil, _) => acc\n case (ch :: rest, None) => if (ch.isSurrogate) inner(rest, acc, Some(ch))\n else inner(rest, acc :+ ch.toString, None)\n case (ch :: rest, Some(f)) => inner(rest, (acc :+ (f.toString + ch)), None)\n }\n }\n inner(UTFstring.toList, Nil, None)\n }\n\n def UnicodeToInt(utf: String) = {\n def charToInt(high: Char, low: Char) =\n { if (isSurrogatePair(high, low)) toCodePoint(high, low) else high.toInt }\n charToInt(utf(0), if (utf.size > 1) utf(1) else 0)\n }\n\n def UTFtoHexString(utf: String) = { utf.map(ch => f\"${ch.toInt}%04X\").mkString(\"\\\"\\\\u\", \"\\\\u\", \"\\\"\") }\n\n def flags(ch: String) = { // Testing Unicode character properties\n (if (ch matches \"\\\\p{M}\") \"Y\" else \"N\") + (if (ch matches \"\\\\p{Mn}\") \"Y\" else \"N\")\n }\n\n val str = '\\uFEFF' /*big-endian BOM*/ + \"\\u0301a\" +\n \"$áabcde¢£¤¥©ÇßIJijŁłʒλπक्तु•₠₡₢₣₤₥₦₧₨₩₪₫€₭₮₯₰₱₲₳₴₵℃←→⇒∙⌘☃☹☺☻ア字文𠀀\" + intToChars(173733).mkString\n\n println(s\"Example string: $str\")\n println(\"\"\" | Chr C/C++/Java source Code Point Hex Dec Mn Name\n\t\t \t!----+ --- ------------------------- ------- -------- -- \"\"\".stripMargin('!') + \"-\" * 27)\n\n (UnicodeToList(str)).zipWithIndex.map {\n case (coll, nr) =>\n f\"$nr%4d: $coll\\t${UTFtoHexString(coll)}%27s U+${UnicodeToInt(coll)}%05X\" +\n f\"${\"(\" + UnicodeToInt(coll).toString}%8s) ${flags(coll)} ${getName(coll(0).toInt)} \"\n }.foreach(println)\n}\n", "language": "Scala" }, { "code": "(display (char->integer #\\a)) (newline) ; prints \"97\"\n(display (integer->char 97)) (newline) ; prints \"a\"\n", "language": "Scheme" }, { "code": "writeln(ord('a'));\nwriteln(chr(97));\n", "language": "Seed7" }, { "code": "put CharToNum(\"a\")\nput NumToChar(97)\n", "language": "SenseTalk" }, { "code": "cmd:>asciiToInt('a')\n97\ncmd:>intToAscii(97)\n'a'\n", "language": "SequenceL" }, { "code": "say 'a'.ord; # => 97\nsay 97.chr; # => 'a'\n", "language": "Sidef" }, { "code": "10 REM THE ZX81 USES ITS OWN NON-ASCII CHARACTER SET\n20 REM WHICH DOES NOT INCLUDE LOWER-CASE LETTERS\n30 PRINT CODE \"A\"\n40 PRINT CHR$ 38\n", "language": "Sinclair-ZX81-BASIC" }, { "code": "$a code.\n97 as: String Character.\n", "language": "Slate" }, { "code": "($a asInteger) displayNl. \"output 97\"\n(Character value: 97) displayNl. \"output a\"\n", "language": "Smalltalk" }, { "code": "Transcript showCR:$a codePoint.\nTranscript showCR:(Character codePoint:97).\nTranscript showCR:(98 asCharacter).\n\n'abcmøøse𝔘𝔫𝔦𝔠𝔬𝔡𝔢' do:[:ch |\n Transcript showCR:ch codePoint\n]\n", "language": "Smalltalk" }, { "code": "PRINT CHR$(97) 'a\nPRINT ASC(\"a\") '97\n", "language": "SmileBASIC" }, { "code": " define('chr(n)') :(chr_end)\nchr &alphabet tab(n) len(1) . chr :s(return)f(freturn)\nchr_end\n\n define('asc(str)c') :(asc_end)\nasc str len(1) . c\n &alphabet break(c) @asc :s(return)f(freturn)\nasc_end\n\n* # Test and display\n output = char(65) ;* Built-in\n output = chr(65)\n output = asc('A')\nend\n", "language": "SNOBOL4" }, { "code": "#!/usr/local/bin/spar\npragma annotate( summary, \"charcode\" )\n @( description, \"Given a character value in your language, print its code (could be\" )\n @( description, \"ASCII code, Unicode code, or whatever your language uses). For example,\" )\n @( description, \"the character 'a' (lowercase letter A) has a code of 97 in ASCII (as\" )\n @( description, \"well as Unicode, as ASCII forms the beginning of Unicode). Conversely,\" )\n @( description, \"given a code, print out the corresponding character. \" )\n @( category, \"tutorials\" )\n @( see_also, \"http://rosettacode.org/wiki/Character_codes\" )\n @( author, \"Ken O. Burtch\");\npragma license( unrestricted );\n\npragma restriction( no_external_commands );\n\nprocedure charcode is\n code : constant natural := 97;\n ch : constant character := 'a';\nbegin\n put_line( \"character code\" & strings.image( code ) & \" = character \" & strings.val( code ) );\n put_line( \"character \" & ch & \" = character code\" & strings.image( numerics.pos( ch ) ) );\nend charcode;\n", "language": "SparForte" }, { "code": "x = #.array(\"a\")\n#.output(\"a -> \",x[1],\" \",x[2])\nx = [98,0]\n#.output(\"98 0 -> \",#.str(x))\n", "language": "SPL" }, { "code": "print (Int.toString (ord #\"a\") ^ \"\\n\"); (* prints \"97\" *)\nprint (Char.toString (chr 97) ^ \"\\n\"); (* prints \"a\" *)\n", "language": "Standard-ML" }, { "code": ": ascii(\"α\")\n 1 2\n +-------------+\n 1 | 206 177 |\n +-------------+\n", "language": "Stata" }, { "code": ": ascii(\"We the People\")\n 1 2 3 4 5 6 7 8 9 10 11 12 13\n +-------------------------------------------------------------------------------+\n 1 | 87 101 32 116 104 101 32 80 101 111 112 108 101 |\n +-------------------------------------------------------------------------------+\n", "language": "Stata" }, { "code": ": char((73,32,115,116,97,110,100,32,104,101,114,101))\n I stand here\n", "language": "Stata" }, { "code": "let c1: UnicodeScalar = \"a\"\nprintln(c1.value) // prints \"97\"\nlet c2: UnicodeScalar = \"π\"\nprintln(c2.value) // prints \"960\"\n", "language": "Swift" }, { "code": "let s1 = \"a\"\nfor c in s1.unicodeScalars {\n println(c.value) // prints \"97\"\n}\nlet s2 = \"π\"\nfor c in s2.unicodeScalars {\n println(c.value) // prints \"960\"\n}\n", "language": "Swift" }, { "code": "let i1: UInt32 = 97\nprintln(UnicodeScalar(i1)) // prints \"a\"\nlet i2: UInt32 = 960\nprintln(UnicodeScalar(i2)) // prints \"π\"\n", "language": "Swift" }, { "code": "'abc' -> $::asCodePoints -> !OUT::write\n'$#10;' -> !OUT::write\n'$#97;' -> !OUT::write\n", "language": "Tailspin" }, { "code": "# ASCII\nputs [scan \"a\" %c] ;# ==> 97\nputs [format %c 97] ;# ==> a\n# Unicode is the same\nputs [scan \"π\" %c] ;# ==> 960\nputs [format %c 960] ;# ==> π\n", "language": "Tcl" }, { "code": "\"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789→Str1\nDisp inString(Str1,\"A\nInput \"CODE? \",A\nDisp sub(Str1,A,1\n", "language": "TI-83-BASIC" }, { "code": "Prgm\n Local k, s\n ClrIO\n Loop\n Disp \"Press a key, or ON to exit.\"\n getKey() © clear buffer\n 0 → k : While k = 0 : getKey() → k : EndWhile\n ClrIO\n If k ≥ 256 Then\n Disp \"Not a character.\"\n Disp \"Code: \" & string(k)\n Else\n\n char(k) → s ©\n © char() and ord() are inverses. ©\n Disp \"Character: \" & s ©\n Disp \"Code: \" & string(ord(s)) ©\n\n EndIf\n EndLoop\nEndPrgm\n", "language": "TI-89-BASIC" }, { "code": "\"a\" ord print\n97 chr print\n", "language": "Trith" }, { "code": "\"π\" ord print\n960 chr print\n", "language": "Trith" }, { "code": "PRINT \"a - > \"; ord(\"a\")\nPRINT \"98 -> \"; chr$(98)\nEND\n", "language": "True-BASIC" }, { "code": "$$ MODE TUSCRIPT\nSET character =\"a\", code=DECODE (character,byte)\nPRINT character,\"=\",code\n", "language": "TUSCRIPT" }, { "code": "Aamrun$ printf \"%d\\n\" \\'a\n97\nAamrun$ printf \"\\x$(printf %x 97)\\n\"\na\nAamrun$\n", "language": "UNIX-Shell" }, { "code": "# outputs the character value for 'a'\nout (ord \"a\") endl console\n# outputs the character 'a' given its value\nout (chr 97) endl console\n", "language": "Ursa" }, { "code": "#import std\n#import nat\n\nchr = -: num characters\nasc = -:@rlXS num characters\n\n#cast %cnX\n\ntest = (chr97,asc`a)\n", "language": "Ursala" }, { "code": "( uxnasm char-codes.tal char-codes.rom && uxncli char-codes.rom )\n\n|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1\n|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1\n\n|0100\n [ LIT \"a ] print-hex\n newline\n #61 .Console/write DEO\n newline\n\n ( exit )\n #80 .System/state DEO\nBRK\n\n@print-hex\n DUP #04 SFT print-digit #0f AND print-digit\nJMP2r\n\n@print-digit\n DUP #09 GTH #27 MUL ADD #30 ADD .Console/write DEO\nJMP2r\n\n@newline\n #0a .Console/write DEO\nJMP2r\n", "language": "Uxntal" }, { "code": "fn main() {\n println('a'[0]) // prints \"97\"\n\tprintln('π'[0]) // prints \"207\"\n\n\ts := 'aπ'\n\tprintln('string cast to bytes: ${s.bytes()}')\n\tfor c in s {\n\t\tprint('0x${c:x} ')\n\t}\n}\n", "language": "V-(Vlang)" }, { "code": "Debug.Print Chr(97) 'Prints a\nDebug.Print [Code(\"a\")] ' Prints 97\n", "language": "VBA" }, { "code": "'prints a\nWScript.StdOut.WriteLine Chr(97)\n\n'prints 97\nWScript.StdOut.WriteLine Asc(\"a\")\n", "language": "VBScript" }, { "code": "\"encoding is set to utf-8\necho char2nr(\"a\")\n\"Prints 97\n\necho nr2char(97)\n\"Prints a\n", "language": "Vim-Script" }, { "code": "Console.WriteLine(Chr(97)) 'Prints a\nConsole.WriteLine(Asc(\"a\")) 'Prints 97\n", "language": "Visual-Basic-.NET" }, { "code": "var cps = []\nfor (c in [\"a\", \"π\", \"字\", \"🐘\"]) {\n var cp = c.codePoints[0]\n cps.add(cp)\n System.print(\"%(c) = %(cp)\")\n}\nSystem.print()\nfor (i in cps) {\n var c = String.fromCodePoint(i)\n System.print(\"%(i) = %(c)\")\n}\n", "language": "Wren" }, { "code": "PROGRAM\t\"Character codes\"\nVERSION\t\"0.0000\"\n\nDECLARE FUNCTION Entry ()\n\nFUNCTION Entry ()\n PRINT \"a - >\"; ASC(\"a\")\n PRINT \"98 -> \"; CHR$(98)\nEND FUNCTION\nEND PROGRAM\n", "language": "XBasic" }, { "code": "[1] (INTEGER->CHAR 97)\n\n#\\a\n[2] (CHAR->INTEGER #\\a)\n\n97\n", "language": "XLISP" }, { "code": "IntOut(0, ^a); \\(Integer Out) displays \"97\" on the console (device 0)\nChOut(0, 97); \\(Character Out) displays \"a\" on the console (device 0)\n", "language": "XPL0" }, { "code": "print \"a - > \", asc(\"a\")\nprint \"98 -> \", chr$(98)\n", "language": "Yabasic" }, { "code": "LD A,'a'\ncall &BB5a\n", "language": "Z80-Assembly" }, { "code": "ShowHex:\t\n\tpush af\n\t\tand %11110000\n\t\t\trrca\n\t\t\trrca\n\t\t\trrca\n\t\t\trrca\n\t\tcall PrintHexChar\n\tpop af\n\tand %00001111\n\t;call PrintHexChar (execution flows into it naturally)\nPrintHexChar:\n\tor a\t ;Clear Carry Flag\n\tdaa\n\tadd a,&F0\n\tadc a,&40 ;this sequence of instructions converts a single hex digit to ASCII.\n\n\tjp PrintChar ;this is whatever routine prints to the screen on your system.\n ; It must end in a \"ret\" and it must take the accumulator as its argument.\n", "language": "Z80-Assembly" }, { "code": "const std = @import(\"std\");\nconst unicode = std.unicode;\n\npub fn main() !void {\n const stdout = std.io.getStdOut().writer();\n\n try characterAsciiCodes(stdout);\n try characterUnicodeCodes(stdout);\n}\n\nfn characterAsciiCodes(writer: anytype) !void {\n try writer.writeAll(\"Sample ASCII characters and codes:\\n\");\n\n // Zig's string is just an array of bytes (u8).\n const message: []const u8 = \"ABCabc\";\n\n for (message) |val| {\n try writer.print(\" '{c}' code: {d} [hexa: 0x{x}]\\n\", .{ val, val, val });\n }\n try writer.writeByte('\\n');\n}\n\nfn characterUnicodeCodes(writer: anytype) !void {\n try writer.writeAll(\"Sample Unicode characters and codes:\\n\");\n\n const message: []const u8 = \"あいうえお\";\n\n const utf8_view = unicode.Utf8View.initUnchecked(message);\n var iter = utf8_view.iterator();\n\n while (iter.nextCodepoint()) |val| {\n var array: [4]u8 = undefined;\n const slice = array[0..try unicode.utf8Encode(val, &array)];\n\n try writer.print(\" '{s}' code: {d} [hexa: U+{x}]\\n\", .{ slice, val, val });\n }\n try writer.writeByte('\\n');\n}\n", "language": "Zig" }, { "code": " \"a\".toAsc() //-->97\n(97).toChar() //-->\"a\"\n", "language": "Zkl" }, { "code": "program: character_codes\n input: a\n output: 97\n", "language": "Zoea" }, { "code": "10 PRINT CHR$ 97: REM prints a\n20 PRINT CODE \"a\": REM prints 97\n", "language": "ZX-Spectrum-Basic" } ]
Character-codes
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Chat_server\nnote: Networking and Web Interaction\n", "language": "00-META" }, { "code": ";Task:\nWrite a server for a minimal text based chat. \n\nPeople should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.\n<br><br>\n", "language": "00-TASK" }, { "code": "with Ada.Containers.Vectors;\nwith Ada.Command_Line; use Ada.Command_Line;\nwith Ada.Exceptions; use Ada.Exceptions;\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Strings.Unbounded; use Ada.Strings.Unbounded;\nwith Sockets; use Sockets;\n\nprocedure Chat_Server is\n\n package Client_Vectors is new Ada.Containers.Vectors\n (Element_Type => Socket_FD, Index_Type => Positive);\n All_Clients : Client_Vectors.Vector;\n\n procedure Write (S : String) is\n procedure Output (Position : Client_Vectors.Cursor) is\n Sock : Socket_FD := Client_Vectors.Element (Position);\n begin\n Put_Line (Sock, S);\n end Output;\n begin\n All_Clients.Iterate (Output'Access);\n end Write;\n\n task type Client_Task is\n entry Start (FD : Socket_FD);\n end Client_Task;\n\n task body Client_Task is\n Sock : Socket_FD;\n Sock_ID : Positive;\n Name : Unbounded_String;\n begin\n select\n accept Start (FD : Socket_FD) do\n Sock := FD;\n end Start;\n or\n terminate;\n end select;\n\n while Name = Null_Unbounded_String loop\n Put (Sock, \"Enter Name:\");\n Name := To_Unbounded_String (Get_Line (Sock));\n end loop;\n Write (To_String (Name) & \" joined.\");\n All_Clients.Append (Sock);\n Sock_ID := All_Clients.Find_Index (Sock);\n loop\n declare\n Input : String := Get_Line (Sock);\n begin\n Write (To_String (Name) & \": \" & Input);\n end;\n end loop;\n exception\n when Connection_Closed =>\n Put_Line (\"Connection closed\");\n Shutdown (Sock, Both);\n All_Clients.Delete (Sock_ID);\n Write (To_String (Name) & \" left.\");\n end Client_Task;\n\n Accepting_Socket : Socket_FD;\n Incoming_Socket : Socket_FD;\n\n type Client_Access is access Client_Task;\n Dummy : Client_Access;\nbegin\n if Argument_Count /= 1 then\n Raise_Exception (Constraint_Error'Identity,\n \"Usage: \" & Command_Name & \" port\");\n end if;\n Socket (Accepting_Socket, PF_INET, SOCK_STREAM);\n Setsockopt (Accepting_Socket, SOL_SOCKET, SO_REUSEADDR, 1);\n Bind (Accepting_Socket, Positive'Value (Argument (1)));\n Listen (Accepting_Socket);\n loop\n Put_Line (\"Waiting for new connection\");\n Accept_Socket (Accepting_Socket, Incoming_Socket);\n Put_Line (\"New connection acknowledged\");\n\n Dummy := new Client_Task;\n Dummy.Start (Incoming_Socket);\n end loop;\nend Chat_Server;\n", "language": "Ada" }, { "code": "DECLARE user$ ASSOC STRING\nDECLARE connect ASSOC long\nOPEN \"localhost:51000\" FOR SERVER AS mynet\nWHILE TRUE\n IF WAIT(mynet, 30) THEN\n fd = ACCEPT(mynet)\n connect(GETPEER$(fd)) = fd\n SEND \"Enter your name: \" TO fd\n ELSE\n FOR con$ IN OBTAIN$(connect)\n IF WAIT(connect(con$), 10) THEN\n RECEIVE in$ FROM connect(con$)\n IF user$(GETPEER$(connect(con$))) = \"\" THEN\n user$(GETPEER$(connect(con$))) = CHOP$(in$)\n chat$ = chat$ & user$(GETPEER$(connect(con$))) & \" joined the chat.\" & NL$\n SEND \"Welcome, \" & CHOP$(in$) & \"!\" & NL$ TO connect(con$)\n ELIF LEFT$(in$, 4) = \"quit\" THEN\n SEND \"You're disconnected!\" & NL$ TO connect(con$)\n chat$ = chat$ & user$(GETPEER$(connect(con$))) & \" left the chat.\" & NL$\n FREE user$(GETPEER$(connect(con$)))\n FREE connect(con$)\n CLOSE SERVER connect(con$)\n ELIF LEFT$(in$, 4) = \"say \" THEN\n chat$ = chat$ & user$(GETPEER$(connect(con$))) & \" said: \" & MID$(in$, 5)\n ENDIF\n ENDIF\n NEXT\n IF LEN(chat$) > 0 THEN\n FOR con$ IN OBTAIN$(connect)\n IF user$(GETPEER$(connect(con$))) <> \"\" THEN SEND chat$ TO connect(con$)\n NEXT\n chat$ = \"\"\n ENDIF\n ENDIF\nWEND\n", "language": "BaCon" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n\nint tsocket;\nstruct sockaddr_in tsockinfo;\nfd_set status, current;\nvoid ClientText(int handle, char *buf, int buf_len);\n\nstruct client\n{\n char buffer[4096];\n int pos;\n char name[32];\n} *connections[FD_SETSIZE];\n\nvoid AddConnection(int handle)\n{\n connections[handle] = malloc(sizeof(struct client));\n connections[handle]->buffer[0] = '\\0';\n connections[handle]->pos = 0;\n connections[handle]->name[0] = '\\0';\n}\n\nvoid CloseConnection(int handle)\n{\n char buf[512];\n int j;\n\n FD_CLR(handle, &status);\n\n if (connections[handle]->name[0])\n {\n sprintf(buf, \"* Disconnected: %s\\r\\n\", connections[handle]->name);\n\n for (j = 0; j < FD_SETSIZE; j++)\n {\n if (handle != j && j != tsocket && FD_ISSET(j, &status))\n {\n if (write(j, buf, strlen(buf)) < 0)\n {\n CloseConnection(j);\n }\n }\n }\n } else\n {\n printf (\"-- Connection %d disconnected\\n\", handle);\n }\n if (connections[handle])\n {\n free(connections[handle]);\n }\n close(handle);\n}\n\nvoid strip(char *buf)\n{\n char *x;\n\n x = strchr(buf, '\\n');\n if (x) { *x='\\0'; }\n x = strchr(buf, '\\r');\n if (x) { *x='\\0'; }\n}\n\nint RelayText(int handle)\n{\n char *begin, *end;\n int ret = 0;\n begin = connections[handle]->buffer;\n if (connections[handle]->pos == 4000)\n {\n if (begin[3999] != '\\n')\n begin[4000] = '\\0';\n else {\n begin[4000] = '\\n';\n begin[4001] = '\\0';\n }\n } else {\n begin[connections[handle]->pos] = '\\0';\n }\n\n end = strchr(begin, '\\n');\n while (end != NULL)\n {\n char output[8000];\n output[0] = '\\0';\n if (!connections[handle]->name[0])\n {\n strncpy(connections[handle]->name, begin, 31);\n connections[handle]->name[31] = '\\0';\n\n strip(connections[handle]->name);\n sprintf(output, \"* Connected: %s\\r\\n\", connections[handle]->name);\n ret = 1;\n } else\n {\n sprintf(output, \"%s: %.*s\\r\\n\", connections[handle]->name,\n end-begin, begin);\n ret = 1;\n }\n\n if (output[0])\n {\n int j;\n for (j = 0; j < FD_SETSIZE; j++)\n {\n if (handle != j && j != tsocket && FD_ISSET(j, &status))\n {\n if (write(j, output, strlen(output)) < 0)\n {\n CloseConnection(j);\n }\n }\n }\n }\n begin = end+1;\n end = strchr(begin, '\\n');\n }\n\n strcpy(connections[handle]->buffer, begin);\n connections[handle]->pos -= begin - connections[handle]->buffer;\n return ret;\n}\n\nvoid ClientText(int handle, char *buf, int buf_len)\n{\n int i, j;\n if (!connections[handle])\n return;\n j = connections[handle]->pos;\n\n for (i = 0; i < buf_len; ++i, ++j)\n {\n connections[handle]->buffer[j] = buf[i];\n\n if (j == 4000)\n {\n while (RelayText(handle));\n j = connections[handle]->pos;\n }\n }\n connections[handle]->pos = j;\n\n while (RelayText(handle));\n}\n\n\nint ChatLoop()\n{\n int i, j;\n FD_ZERO(&status);\n\n FD_SET(tsocket, &status);\n FD_SET(0, &status);\n\n while(1)\n {\n current = status;\n if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)\n {\n perror(\"Select\");\n return 0;\n }\n for (i = 0; i < FD_SETSIZE; ++i)\n {\n if (FD_ISSET(i, &current))\n {\n if (i == tsocket)\n {\n struct sockaddr_in cliinfo;\n socklen_t addrlen = sizeof(cliinfo);\n int handle;\n handle = accept(tsocket, &cliinfo, &addrlen);\n if (handle == -1)\n {\n perror (\"Couldn't accept connection\");\n } else if (handle > FD_SETSIZE)\n {\n printf (\"Unable to accept new connection.\\n\");\n close(handle);\n }\n else\n {\n if (write(handle, \"Enter name: \", 12) >= 0)\n {\n printf(\"-- New connection %d from %s:%hu\\n\",\n handle,\n inet_ntoa (cliinfo.sin_addr),\n ntohs(cliinfo.sin_port));\n FD_SET(handle, &status);\n\n AddConnection(handle);\n }\n }\n } /* Read data, relay to others. */\n else\n {\n char buf[512];\n int b;\n\n b = read(i, buf, 500);\n if (b <= 0)\n {\n CloseConnection(i);\n }\n else\n {\n ClientText(i, buf, b);\n }\n }\n }\n }\n } /* While 1 */\n}\n\nint main (int argc, char*argv[])\n{\n tsocket = socket(PF_INET, SOCK_STREAM, 0);\n\n tsockinfo.sin_family = AF_INET;\n tsockinfo.sin_port = htons(7070);\n if (argc > 1)\n {\n tsockinfo.sin_port = htons(atoi(argv[1]));\n }\n tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);\n printf (\"Socket %d on port %hu\\n\", tsocket, ntohs(tsockinfo.sin_port));\n\n if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)\n {\n perror(\"Couldn't bind socket\");\n return -1;\n }\n\n if (listen(tsocket, 10) == -1)\n {\n perror(\"Couldn't listen to port\");\n }\n\n ChatLoop();\n\n return 0;\n}\n", "language": "C" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nnamespace ChatServer {\n class State {\n private TcpClient client;\n private StringBuilder sb = new StringBuilder();\n\n public string Name { get; }\n\n public State(string name, TcpClient client) {\n Name = name;\n this.client = client;\n }\n\n public void Add(byte b) {\n sb.Append((char)b);\n }\n\n public void Send(string text) {\n var bytes = Encoding.ASCII.GetBytes(string.Format(\"{0}\\r\\n\", text));\n client.GetStream().Write(bytes, 0, bytes.Length);\n }\n }\n\n class Program {\n static TcpListener listen;\n static Thread serverthread;\n static Dictionary<int, State> connections = new Dictionary<int, State>();\n\n static void Main(string[] args) {\n listen = new TcpListener(System.Net.IPAddress.Parse(\"127.0.0.1\"), 4004);\n serverthread = new Thread(new ThreadStart(DoListen));\n serverthread.Start();\n }\n\n private static void DoListen() {\n // Listen\n listen.Start();\n Console.WriteLine(\"Server: Started server\");\n\n while (true) {\n Console.WriteLine(\"Server: Waiting...\");\n TcpClient client = listen.AcceptTcpClient();\n Console.WriteLine(\"Server: Waited\");\n\n // New thread with client\n Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));\n clientThread.Start(client);\n }\n }\n\n private static void DoClient(object client) {\n // Read data\n TcpClient tClient = (TcpClient)client;\n\n Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId);\n byte[] bytes = Encoding.ASCII.GetBytes(\"Enter name: \");\n tClient.GetStream().Write(bytes, 0, bytes.Length);\n\n string name = string.Empty;\n bool done = false;\n do {\n if (!tClient.Connected) {\n Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n tClient.Close();\n Thread.CurrentThread.Abort(); // Kill thread.\n }\n\n name = Receive(tClient);\n done = true;\n\n if (done) {\n foreach (var cl in connections) {\n var state = cl.Value;\n if (state.Name == name) {\n bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \");\n tClient.GetStream().Write(bytes, 0, bytes.Length);\n done = false;\n }\n }\n }\n } while (!done);\n\n connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));\n Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n Broadcast(string.Format(\"+++ {0} arrived +++\", name));\n\n do {\n string text = Receive(tClient);\n if (text == \"/quit\") {\n Broadcast(string.Format(\"Connection from {0} closed.\", name));\n connections.Remove(Thread.CurrentThread.ManagedThreadId);\n Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n break;\n }\n\n if (!tClient.Connected) {\n break;\n }\n Broadcast(string.Format(\"{0}> {1}\", name, text));\n } while (true);\n\n Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n tClient.Close();\n Thread.CurrentThread.Abort();\n }\n\n private static string Receive(TcpClient client) {\n StringBuilder sb = new StringBuilder();\n do {\n if (client.Available > 0) {\n while (client.Available > 0) {\n char ch = (char)client.GetStream().ReadByte();\n if (ch == '\\r') {\n //ignore\n continue;\n }\n if (ch == '\\n') {\n return sb.ToString();\n }\n sb.Append(ch);\n }\n }\n\n // Pause\n Thread.Sleep(100);\n } while (true);\n }\n\n private static void Broadcast(string text) {\n Console.WriteLine(text);\n foreach (var oClient in connections) {\n if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {\n State state = oClient.Value;\n state.Send(text);\n }\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "net = require(\"net\")\nsys = require(\"sys\")\nEventEmitter = require(\"events\").EventEmitter\n\nisNicknameLegal = (nickname) ->\n return false unless nickname.replace(/[A-Za-z0-9]*/, \"\") is \"\"\n for used_nick of @chatters\n return false if used_nick is nickname\n true\n\nclass ChatServer\n constructor: ->\n @chatters = {}\n @server = net.createServer @handleConnection\n @server.listen 1212, \"localhost\"\n\n handleConnection: (connection) =>\n console.log \"Incoming connection from \" + connection.remoteAddress\n connection.setEncoding \"utf8\"\n chatter = new Chatter(connection, this)\n chatter.on \"chat\", @handleChat\n chatter.on \"join\", @handleJoin\n chatter.on \"leave\", @handleLeave\n\n handleChat: (chatter, message) =>\n @sendToEveryChatterExcept chatter, chatter.nickname + \": \" + message\n\n handleJoin: (chatter) =>\n console.log chatter.nickname + \" has joined the chat.\"\n @sendToEveryChatter chatter.nickname + \" has joined the chat.\"\n @addChatter chatter\n\n handleLeave: (chatter) =>\n console.log chatter.nickname + \" has left the chat.\"\n @removeChatter chatter\n @sendToEveryChatter chatter.nickname + \" has left the chat.\"\n\n addChatter: (chatter) =>\n @chatters[chatter.nickname] = chatter\n\n removeChatter: (chatter) =>\n delete @chatters[chatter.nickname]\n\n sendToEveryChatter: (data) =>\n for nickname of @chatters\n @chatters[nickname].send data\n\n sendToEveryChatterExcept: (chatter, data) =>\n for nickname of @chatters\n @chatters[nickname].send data unless nickname is chatter.nickname\n\n\nclass Chatter extends EventEmitter\n constructor: (socket, server) ->\n EventEmitter.call this\n @socket = socket\n @server = server\n @nickname = \"\"\n @lineBuffer = new SocketLineBuffer(socket)\n @lineBuffer.on \"line\", @handleNickname\n @socket.on \"close\", @handleDisconnect\n @send \"Welcome! What is your nickname?\"\n\n handleNickname: (nickname) =>\n if isNicknameLegal(nickname)\n @nickname = nickname\n @lineBuffer.removeAllListeners \"line\"\n @lineBuffer.on \"line\", @handleChat\n @send \"Welcome to the chat, \" + nickname + \"!\"\n @emit \"join\", this\n else\n @send \"Sorry, but that nickname is not legal or is already in use!\"\n @send \"What is your nickname?\"\n\n handleChat: (line) =>\n @emit \"chat\", this, line\n\n handleDisconnect: =>\n @emit \"leave\", this\n\n send: (data) =>\n @socket.write data + \"\\r\\n\"\n\n\nclass SocketLineBuffer extends EventEmitter\n constructor: (socket) ->\n EventEmitter.call this\n @socket = socket\n @buffer = \"\"\n @socket.on \"data\", @handleData\n\n handleData: (data) =>\n console.log \"Handling data\", data\n i = 0\n\n while i < data.length\n char = data.charAt(i)\n @buffer += char\n if char is \"\\n\"\n @buffer = @buffer.replace(\"\\r\\n\", \"\")\n @buffer = @buffer.replace(\"\\n\", \"\")\n @emit \"line\", @buffer\n console.log \"incoming line: #{@buffer}\"\n @buffer = \"\"\n i++\n\nserver = new ChatServer()\n", "language": "CoffeeScript" }, { "code": "(ql:quickload '(:usocket :simple-actors :bordeaux-threads))\n\n(defpackage :chat-server\n (:use :common-lisp :usocket :simple-actors :bordeaux-threads)\n (:export :accept-connections))\n\n(in-package :chat-server)\n\n(defvar *whitespace* '(#\\Space #\\Tab #\\Page #\\Vt #\\Newline #\\Return))\n\n(defun send-message (users from-user message)\n (loop for (nil . actor) in users\n do (send actor :message from-user message)))\n\n(defun socket-format (socket format-control &rest format-arguments)\n (apply #'format (socket-stream socket) format-control format-arguments)\n (finish-output (socket-stream socket)))\n\n(defvar *log* *standard-output*)\n\n(defmacro log-errors (&body body)\n `(handler-case\n (progn ,@body)\n (t (err)\n (format *log* \"Error: ~a\" err))))\n\n(defparameter *user-manager*\n (let ((users nil))\n (actor (action &rest args)\n (format *log* \"Handling message ~s~%\" (cons action args))\n (ecase action\n\t (:newuser\n\t (destructuring-bind (username session-actor)\n\t args\n\t (cond ((assoc username users :test #'equalp)\n\t\t (send session-actor :rejected\n\t\t\t (format nil \"Username ~a is already taken. Send /NICK new-nick with a valid name to enter the chat~%\" username)))\n\t\t ((equalp username \"Server\")\n\t\t (send session-actor :rejected\n\t\t\t (format nil \"Server is not a valid username. Send /NICK new-nick with a valid name to enter the chat~%\")))\n\t\t (t (send-message users \"Server\" (format nil \"~a has joined the chat.\" username))\n\t\t (send session-actor :accepted\n\t\t\t (format nil \"Welcome to the Rosetta Code chat server in Common Lisp. ~a users connected.~%\"\n\t\t\t\t (length users)))\n\t\t (pushnew (cons username session-actor)\n\t\t\t users\n\t\t\t :key #'car\n\t\t\t :test #'equalp)))))\n\t (:who\n\t (destructuring-bind (username) args\n\t (let ((actor (cdr (assoc username users :test #'equalp))))\n\t (send actor :message \"Server\"\n\t\t \"Users connected right now:\")\n\t (loop for (user . nil) in users\n\t\t do (send actor :message \"Server\" user)))))\n\t (:message\n\t (apply #'send-message users args))\n\t (:dropuser\n\t (destructuring-bind (username) args\n\t (let ((user-actor (cdr (assoc username users :test #'equalp))))\n\t (send user-actor :close)\n\t (send user-actor 'stop))\n\t (setf users (remove username users\n\t\t\t\t:key #'car\n\t\t\t\t:test #'equalp))\n\t (send-message users \"Server\" (format nil \"~a has left.\" username))))))))\n\n(defmacro drop-connection-on-error (&body body)\n `(handler-case (progn ,@body)\n (t (err)\n (format *log* \"Error: ~a; Closing connection\" err)\n (send self :close)\n (send self 'stop)\n (send *user-manager* :dropuser username))))\n\n(defun parse-command (message)\n (let* ((space-at (position #\\Space message))\n\t (after-space (and space-at\n\t\t\t (position-if (lambda (ch)\n\t\t\t\t (not (char= ch #\\Space)))\n\t\t\t\t\tmessage :start (1+ space-at)))))\n (values (subseq message 0 space-at)\n\t (and after-space\n\t\t (string-trim *whitespace*\n\t\t\t (subseq message after-space))))))\n\n(defun help (socket)\n (socket-format socket \"/QUIT to quit, /WHO to list users.~%\"))\n\n(defun make-user (username socket)\n (let* ((state :unregistered)\n\t (actor\n\t (actor (message &rest args)\n\t (drop-connection-on-error\n\t (ecase message\n\t\t(:register\n\t\t (send *user-manager* :newuser username self))\n\t\t(:accepted\n\t\t (destructuring-bind (message) args\n\t\t (write-string message (socket-stream socket))\n\t\t (finish-output (socket-stream socket))\n\t\t (setf state :registered)))\n\t\t(:rejected\n\t\t (destructuring-bind (message) args\n\t\t (write-string message (socket-stream socket))\n\t\t (finish-output (socket-stream socket))\n\t\t (setf state :unregistered)))\n\t\t(:user-typed\n\t\t (destructuring-bind (message) args\n\t\t (when (> (length message) 0)\n\t\t (if (char= (aref message 0) #\\/)\n\t\t\t (multiple-value-bind (cmd arg)\n\t\t\t (parse-command message)\n\t\t\t (cond ((equalp cmd \"/nick\")\n\t\t\t\t (ecase state\n\t\t\t\t (:unregistered\n\t\t\t\t (setf username arg)\n\t\t\t\t (send *user-manager* :newuser username self))\n\t\t\t\t (:registered\n\t\t\t\t (socket-format socket\n\t\t\t\t\t\t \"Can't change your name after successfully registering~%\"))))\n\t\t\t\t ((equalp cmd \"/help\")\n\t\t\t\t (help socket))\n\t\t\t\t ((equalp cmd \"/who\")\n\t\t\t\t (send *user-manager* :who username))\n\t\t\t\t ((equalp cmd \"/quit\")\n\t\t\t\t (socket-format socket\n\t\t\t\t\t \"Goodbye.~%\")\n\t\t\t\t (send *user-manager* :dropuser username))\n\t\t\t\t (t\n\t\t\t\t (socket-format socket\n\t\t\t\t\t \"Unknown command~%\"))))\n\t\t\t (send *user-manager* :message username message)))))\n\t\t(:message\n\t\t (destructuring-bind (from-user message) args\n\t\t (socket-format socket \"<~a> ~a~%\" from-user message)))\n\t\t(:close\n\t\t (log-errors\n\t\t (close (socket-stream socket)))))))))\n (bt:make-thread (lambda ()\n\t\t (handler-case\n\t\t\t (loop for line = (read-line (socket-stream socket) nil :eof)\n\t\t\t do (if (eq line :eof)\n\t\t\t\t (send *user-manager* :dropuser username)\n\t\t\t\t (send actor :user-typed (remove #\\Return line))))\n\t\t\t(t () (send *user-manager* :dropuser username))))\n\t\t\t\n\t\t :name \"Reader thread\")\n actor))\n\t\t\t\n\n(defun initialize-user (socket)\n (bt:make-thread\n (lambda ()\n (format *log* \"Handling new connection ~s\" socket)\n (log-errors\n (loop do\n\t (socket-format socket \"Your name: \")\n\t (let ((name (string-trim *whitespace* (read-line (socket-stream socket)))))\n\t (format *log* \"Registering user ~a\" name)\n\t (cond ((equalp name \"Server\")\n\t\t (socket-format socket\n\t\t\t\t \"Server is not a valid username.~%\"))\n\t\t (t (send *user-manager*\n\t\t\t :newuser name (make-user name socket))\n\t\t (return)))))))\n :name \"INITIALIZE-USER\"))\n\t\n\n(defun accept-connections ()\n (let ((accepting-socket (socket-listen \"0.0.0.0\" 7070)))\n (loop for new-connection = (socket-accept accepting-socket)\n\t do (initialize-user new-connection))))\n\n(make-thread #'accept-connections)\n", "language": "Common-Lisp" }, { "code": "import std.getopt;\nimport std.socket;\nimport std.stdio;\nimport std.string;\n\nstruct client {\n int pos;\n char[] name;\n char[] buffer;\n Socket socket;\n}\n\nvoid broadcast(client[] connections, size_t self, const char[] message) {\n writeln(message);\n for (size_t i = 0; i < connections.length; i++) {\n if (i == self) continue;\n\n connections[i].socket.send(message);\n connections[i].socket.send(\"\\r\\n\");\n }\n}\n\nbool registerClient(client[] connections, size_t self) {\n for (size_t i = 0; i < connections.length; i++) {\n if (i == self) continue;\n\n if (icmp(connections[i].name, connections[self].name) == 0) {\n return false;\n }\n }\n\n return true;\n}\n\nvoid main(string[] args) {\n ushort port = 4004;\n\n auto helpInformation = getopt\n (\n args,\n \"port|p\", \"The port to listen to chat clients on [default is 4004]\", &port\n );\n\n if (helpInformation.helpWanted) {\n defaultGetoptPrinter(\"A simple chat server based on a task in rosettacode.\", helpInformation.options);\n return;\n }\n\n auto listener = new TcpSocket();\n assert(listener.isAlive);\n listener.blocking = false;\n listener.bind(new InternetAddress(port));\n listener.listen(10);\n writeln(\"Listening on port: \", port);\n\n enum MAX_CONNECTIONS = 60;\n auto socketSet = new SocketSet(MAX_CONNECTIONS + 1);\n client[] connections;\n\n while(true) {\n socketSet.add(listener);\n\n foreach (con; connections) {\n socketSet.add(con.socket);\n }\n\n Socket.select(socketSet, null, null);\n\n for (size_t i = 0; i < connections.length; i++) {\n if (socketSet.isSet(connections[i].socket)) {\n char[1024] buf;\n auto datLength = connections[i].socket.receive(buf[]);\n\n if (datLength == Socket.ERROR) {\n writeln(\"Connection error.\");\n } else if (datLength != 0) {\n if (buf[0] == '\\n' || buf[0] == '\\r') {\n if (connections[i].buffer == \"/quit\") {\n connections[i].socket.close();\n if (connections[i].name.length > 0) {\n writeln(\"Connection from \", connections[i].name, \" closed.\");\n } else {\n writeln(\"Connection from \", connections[i].socket.remoteAddress(), \" closed.\");\n }\n\n connections[i] = connections[$-1];\n connections.length--;\n i--;\n\n writeln(\"\\tTotal connections: \", connections.length);\n continue;\n } else if (connections[i].name.length == 0) {\n connections[i].buffer = strip(connections[i].buffer);\n if (connections[i].buffer.length > 0) {\n connections[i].name = connections[i].buffer;\n if (registerClient(connections, i)) {\n connections.broadcast(i, \"+++ \" ~ connections[i].name ~ \" arrived +++\");\n } else {\n connections[i].socket.send(\"Name already registered. Please enter your name: \");\n connections[i].name.length = 0;\n }\n } else {\n connections[i].socket.send(\"A name is required. Please enter your name: \");\n }\n } else {\n connections.broadcast(i, connections[i].name ~ \"> \" ~ connections[i].buffer);\n }\n connections[i].buffer.length = 0;\n } else {\n connections[i].buffer ~= buf[0..datLength];\n }\n } else {\n try {\n if (connections[i].name.length > 0) {\n writeln(\"Connection from \", connections[i].name, \" closed.\");\n } else {\n writeln(\"Connection from \", connections[i].socket.remoteAddress(), \" closed.\");\n }\n } catch (SocketException) {\n writeln(\"Connection closed.\");\n }\n }\n }\n }\n\n if (socketSet.isSet(listener)) {\n Socket sn = null;\n scope(failure) {\n writeln(\"Error accepting\");\n\n if (sn) {\n sn.close();\n }\n }\n sn = listener.accept();\n assert(sn.isAlive);\n assert(listener.isAlive);\n\n if (connections.length < MAX_CONNECTIONS) {\n client newclient;\n\n writeln(\"Connection from \", sn.remoteAddress(), \" established.\");\n sn.send(\"Enter name: \");\n\n newclient.socket = sn;\n connections ~= newclient;\n\n writeln(\"\\tTotal connections: \", connections.length);\n } else {\n writeln(\"Rejected connection from \", sn.remoteAddress(), \"; too many connections.\");\n sn.close();\n assert(!sn.isAlive);\n assert(listener.isAlive);\n }\n }\n\n socketSet.reset();\n }\n}\n", "language": "D" }, { "code": "-module(chat).\n\n-export([start/0, start/1]).\n\n-record(client, {name=none, socket=none}).\n\nstart() -> start(8080).\nstart(Port) ->\n register(server, spawn(fun() -> server() end)),\n {ok, LSocket} = gen_tcp:listen(Port, [binary, {packet, 0}, {active, false}, {reuseaddr, true}]),\n accept(LSocket).\n\n% main loop for message dispatcher\nserver() -> server([]).\nserver(Clients) ->\n receive\n {join, Client=#client{name = Name, socket = Socket}} ->\n self() ! {say, Socket, \"has joined.\" ++ [10, 13]},\n server(Clients ++ [Client]);\n {leave, Socket} ->\n {value, #client{name = Name}, List} = lists:keytake(Socket, 3, Clients),\n self() ! {say, none, Message = \"has left.\"},\n server(List);\n {say, Socket, Data} ->\n {value, #client{name = From}, List} = lists:keytake(Socket, 3, Clients),\n Message = From ++ \" : \" ++ Data,\n lists:map(fun(#client{socket = S}) ->\n gen_tcp:send(S, Message)\n end, List)\n end,\n server(Clients).\n\n% accepts connections then spawns the client handler\naccept(LSocket) ->\n {ok, Socket} = gen_tcp:accept(LSocket),\n spawn(fun() -> connecting(Socket) end),\n accept(LSocket).\n\n% when client is first connect send prompt for user name\nconnecting(Socket) ->\n gen_tcp:send(Socket, \"What is your name? \"),\n case listen(Socket) of\n {ok, N} ->\n Name = binary_to_list(N),\n server ! {join, #client{name = lists:sublist(Name, 1, length(Name) - 2), socket = Socket} },\n client(Socket);\n _ -> ok\n end.\n\n% main client loop that listens for data\nclient(Socket) ->\n case listen(Socket) of\n {ok, Data} ->\n server ! {say, Socket, binary_to_list(Data)},\n client(Socket);\n _ -> server ! {leave, Socket}\n end.\n\n% utility function that listens for data on a socket\nlisten(Socket) ->\n case gen_tcp:recv(Socket, 0) of\n Response -> Response\n end.\n", "language": "Erlang" }, { "code": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"chat: \")\n\taddr := flag.String(\"addr\", \"localhost:4000\", \"listen address\")\n\tflag.Parse()\n\tlog.Fatal(ListenAndServe(*addr))\n}\n\n// A Server represents a chat server that accepts incoming connections.\ntype Server struct {\n\tadd chan *conn // To add a connection\n\trem chan string // To remove a connection by name\n\tmsg chan string // To send a message to all connections\n\tstop chan bool // To stop early\n}\n\n// ListenAndServe listens on the TCP network address addr for\n// new chat client connections.\nfunc ListenAndServe(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening for connections on\", addr)\n\tdefer ln.Close()\n\ts := &Server{\n\t\tadd: make(chan *conn),\n\t\trem: make(chan string),\n\t\tmsg: make(chan string),\n\t\tstop: make(chan bool),\n\t}\n\tgo s.handleConns()\n\tfor {\n\t\t// TODO use AcceptTCP() so that we can get a TCPConn on which\n\t\t// we can call SetKeepAlive() and SetKeepAlivePeriod()\n\t\trwc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t// TODO Could handle err.(net.Error).Temporary()\n\t\t\t// here by adding a backoff delay.\n\t\t\tclose(s.stop)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"New connection from\", rwc.RemoteAddr())\n\t\tgo newConn(s, rwc).welcome()\n\t}\n}\n\n// handleConns is run as a go routine to handle adding and removal of\n// chat client connections as well as broadcasting messages to them.\nfunc (s *Server) handleConns() {\n\t// We define the `conns` map here rather than within Server,\n\t// and we use local function literals rather than methods to be\n\t// extra sure that the only place that touches this map is this\n\t// method. In this way we forgo any explicit locking needed as\n\t// we're the only go routine that can see or modify this.\n\tconns := make(map[string]*conn)\n\n\tvar dropConn func(string)\n\twriteAll := func(str string) {\n\t\tlog.Printf(\"Broadcast: %q\", str)\n\t\t// TODO handle blocked connections\n\t\tfor name, c := range conns {\n\t\t\tc.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))\n\t\t\t_, err := c.Write([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error writing to %q: %v\", name, err)\n\t\t\t\tc.Close()\n\t\t\t\tdelete(conns, name)\n\t\t\t\t// Defer all the disconnect messages until after\n\t\t\t\t// we've closed all currently problematic conns.\n\t\t\t\tdefer dropConn(name)\n\t\t\t}\n\t\t}\n\t}\n\n\tdropConn = func(name string) {\n\t\tif c, ok := conns[name]; ok {\n\t\t\tlog.Printf(\"Closing connection with %q from %v\",\n\t\t\t\tname, c.RemoteAddr())\n\t\t\tc.Close()\n\t\t\tdelete(conns, name)\n\t\t} else {\n\t\t\tlog.Printf(\"Dropped connection with %q\", name)\n\t\t}\n\t\tstr := fmt.Sprintf(\"--- %q disconnected ---\\n\", name)\n\t\twriteAll(str)\n\t}\n\n\tdefer func() {\n\t\twriteAll(\"Server stopping!\\n\")\n\t\tfor _, c := range conns {\n\t\t\tc.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase c := <-s.add:\n\t\t\tif _, exists := conns[c.name]; exists {\n\t\t\t\tfmt.Fprintf(c, \"Name %q is not available\\n\", c.name)\n\t\t\t\tgo c.welcome()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"+++ %q connected +++\\n\", c.name)\n\t\t\twriteAll(str)\n\t\t\tconns[c.name] = c\n\t\t\tgo c.readloop()\n\t\tcase str := <-s.msg:\n\t\t\twriteAll(str)\n\t\tcase name := <-s.rem:\n\t\t\tdropConn(name)\n\t\tcase <-s.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// A conn represents the server side of a single chat connection.\n// Note we embed the bufio.Reader and net.Conn (and specifically in\n// that order) so that a conn gets the appropriate methods from each\n// to be a full io.ReadWriteCloser.\ntype conn struct {\n\t*bufio.Reader // buffered input\n\tnet.Conn // raw connection\n\tserver *Server // the Server on which the connection arrived\n\tname string\n}\n\nfunc newConn(s *Server, rwc net.Conn) *conn {\n\treturn &conn{\n\t\tReader: bufio.NewReader(rwc),\n\t\tConn: rwc,\n\t\tserver: s,\n\t}\n}\n\n// welcome requests a name from the client before attempting to add the\n// named connect to the set handled by the server.\nfunc (c *conn) welcome() {\n\tvar err error\n\tfor c.name = \"\"; c.name == \"\"; {\n\t\tfmt.Fprint(c, \"Enter your name: \")\n\t\tc.name, err = c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Reading name from %v: %v\", c.RemoteAddr(), err)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\t\tc.name = strings.TrimSpace(c.name)\n\t}\n\t// The server will take this *conn and do a final check\n\t// on the name, possibly starting c.welcome() again.\n\tc.server.add <- c\n}\n\n// readloop is started as a go routine by the server once the initial\n// welcome phase has completed successfully. It reads single lines from\n// the client and passes them to the server for broadcast to all chat\n// clients (including us).\n// Once done, we ask the server to remove (and close) our connection.\nfunc (c *conn) readloop() {\n\tfor {\n\t\tmsg, err := c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t//msg = strings.TrimSpace(msg)\n\t\tc.server.msg <- c.name + \"> \" + msg\n\t}\n\tc.server.rem <- c.name\n}\n", "language": "Go" }, { "code": "class ChatServer implements Runnable {\n private int port = 0\n private List<Client> clientList = new ArrayList<>()\n\n ChatServer(int port) {\n this.port = port\n }\n\n @SuppressWarnings(\"GroovyInfiniteLoopStatement\")\n @Override\n void run() {\n try {\n ServerSocket serverSocket = new ServerSocket(port)\n while (true) {\n Socket socket = serverSocket.accept()\n new Thread(new Client(socket)).start()\n }\n } catch (Exception e) {\n e.printStackTrace()\n }\n }\n\n private synchronized boolean registerClient(Client client) {\n for (Client other : clientList) {\n if (other.clientName.equalsIgnoreCase(client.clientName)) {\n return false\n }\n }\n clientList.add(client)\n return true\n }\n\n private void deRegisterClient(Client client) {\n boolean wasRegistered\n synchronized (this) {\n wasRegistered = clientList.remove(client)\n }\n if (wasRegistered) {\n broadcast(client, \"--- \" + client.clientName + \" left ---\")\n }\n }\n\n private synchronized String getOnlineListCSV() {\n StringBuilder sb = new StringBuilder()\n sb.append(clientList.size()).append(\" user(s) online: \")\n def it = clientList.iterator()\n if (it.hasNext()) {\n sb.append(it.next().clientName)\n }\n while (it.hasNext()) {\n sb.append(\", \")\n sb.append(it.next().clientName)\n }\n return sb.toString()\n }\n\n private void broadcast(Client fromClient, String msg) {\n // Copy client list (don't want to hold lock while doing IO)\n List<Client> clients\n synchronized (this) {\n clients = new ArrayList<>(this.clientList)\n }\n for (Client client : clients) {\n if (client == fromClient) {\n continue\n }\n try {\n client.write(msg + \"\\r\\n\")\n } catch (Exception ignored) {\n // empty\n }\n }\n }\n\n class Client implements Runnable {\n private Socket socket = null\n private Writer output = null\n private String clientName = null\n\n Client(Socket socket) {\n this.socket = socket\n }\n\n @Override\n void run() {\n try {\n socket.setSendBufferSize(16384)\n socket.setTcpNoDelay(true)\n BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()))\n output = new OutputStreamWriter(socket.getOutputStream())\n write(\"Please enter your name: \")\n String line\n while (null != (line = input.readLine())) {\n if (null == clientName) {\n line = line.trim()\n if (line.isEmpty()) {\n write(\"A name is required. Please enter your name: \")\n continue\n }\n clientName = line\n if (!registerClient(this)) {\n clientName = null\n write(\"Name already registered. Please enter your name: \")\n continue\n }\n write(getOnlineListCSV() + \"\\r\\n\")\n broadcast(this, \"+++ \" + clientName + \" arrived +++\")\n continue\n }\n if (line.equalsIgnoreCase(\"/quit\")) {\n return\n }\n broadcast(this, clientName + \"> \" + line)\n }\n } catch (Exception ignored) {\n // empty\n } finally {\n deRegisterClient(this)\n output = null\n try {\n socket.close()\n } catch (Exception ignored) {\n // empty\n }\n socket = null\n }\n }\n\n void write(String msg) {\n output.write(msg)\n output.flush()\n }\n\n @Override\n boolean equals(client) {\n return (null != client) && (client instanceof Client) && (null != clientName) && clientName == client.clientName\n }\n\n @Override\n int hashCode() {\n int result\n result = (socket != null ? socket.hashCode() : 0)\n result = 31 * result + (output != null ? output.hashCode() : 0)\n result = 31 * result + (clientName != null ? clientName.hashCode() : 0)\n return result\n }\n }\n\n static void main(String[] args) {\n int port = 4004\n if (args.length > 0) {\n port = Integer.parseInt(args[0])\n }\n new ChatServer(port).run()\n }\n}\n", "language": "Groovy" }, { "code": "{-# LANGUAGE OverloadedStrings #-}\nimport Network\nimport System.IO\nimport Control.Concurrent\nimport qualified Data.Text as T\nimport Data.Text (Text)\nimport qualified Data.Text.IO as T\nimport qualified Data.Map as M\nimport Data.Map (Map)\nimport Control.Monad.Reader\nimport Control.Monad.Error\nimport Control.Exception\nimport Data.Monoid\nimport Control.Applicative\n\ntype ServerApp = ReaderT ThreadData IO\ndata Speaker = Server | Client Text\ndata ThreadData = ThreadData { threadHandle :: Handle\n , userTableMV :: MVar (Map Text Handle)}\n\nechoLocal = liftIO . T.putStrLn\nechoRemote = echoMessage . (\">> \"<>)\nechoMessage msg = viewHandle >>= \\h -> liftIO $ T.hPutStrLn h msg\ngetRemoteLine = viewHandle >>= liftIO . T.hGetLine\nputMVarT = (liftIO.) . putMVar\ntakeMVarT = liftIO . takeMVar\nreadMVarT = liftIO . readMVar\nmodifyUserTable fn = viewUsers >>= \\mv ->\n liftIO $ modifyMVar_ mv (return . fn)\nviewHandle = threadHandle <$> ask\nviewUsers = userTableMV <$> ask\n\nuserChat :: ServerApp ()\nuserChat = do\n name <- addUser\n echoLocal name\n h <- viewHandle\n (flip catchError) (\\_ -> removeUser name) $\n do echoLocal $ \"Accepted \" <> name\n forever $ getRemoteLine >>= broadcast (Client name)\n\nremoveUser :: Text -> ServerApp ()\nremoveUser name = do\n echoLocal $ \"Exception with \" <> name <> \", removing from userTable\"\n broadcast Server $ name <> \" has left the server\"\n modifyUserTable (M.delete name)\n\naddUser :: ServerApp Text\naddUser = do\n h <- viewHandle\n usersMV <- viewUsers\n echoRemote \"Enter username\"\n name <- T.filter (/='\\r') <$> getRemoteLine\n userTable <- takeMVarT usersMV\n if name `M.member` userTable\n then do echoRemote \"Username already exists!\"\n putMVarT usersMV userTable\n addUser\n else do putMVarT usersMV (M.insert name h userTable)\n broadcast Server $ name <> \" has joined the server\"\n echoRemote \"Welcome to the server!\\n>> Other users:\"\n readMVarT usersMV >>=\n mapM_ (echoRemote . (\"*\" <>) . fst)\n . filter ((/=name). fst) . M.toList\n return name\n\nbroadcast :: Speaker -> Text -> ServerApp ()\nbroadcast user msg =\n viewUsers >>= readMVarT >>= mapM_ (f . snd) . fn . M.toList\n where f h = liftIO $ T.hPutStrLn h $ nm <> msg\n (fn, nm) = case user of\n Server -> (id, \">> \")\n Client t -> (filter ((/=t) . fst), t <> \"> \")\n\nclientLoop socket users = do\n (h, _, _) <- accept socket\n hSetBuffering h LineBuffering\n forkIO $ runReaderT userChat (ThreadData h users)\n clientLoop socket users\n\nmain = do\n server <- listenOn $ PortNumber 5002\n T.putStrLn \"Server started\"\n newMVar (M.empty) >>= clientLoop server\n", "language": "Haskell" }, { "code": "global mlck, nCons, cons\n\nprocedure main()\n mlck := mutex()\n nCons := 0\n cons := mutex(set())\n while f := open(\":12321\",\"na\") do {\n handle_client(f)\n critical mlck: if nCons <= 0 then close(f)\n }\nend\n\nprocedure handle_client(f)\n critical mlck: nCons +:= 1\n thread {\n select(f,1000) & {\n writes(f, \"Name? \")\n nick := (read(f) ? tab(upto('\\n\\r')))\n every write(!cons, nick,\" has joined.\")\n insert(cons, f)\n while s := read(f) do every write(!cons, nick,\": \",s)\n }\n delete(cons, f)\n every write(!cons, nick,\" has left.\")\n critical mlck: nCons -:= 1\n }\nend\n", "language": "Haskell" }, { "code": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n private int port = 0;\n private List<Client> clients = new ArrayList<Client>();\n\n public ChatServer(int port)\n { this.port = port; }\n\n public void run()\n {\n try\n {\n ServerSocket ss = new ServerSocket(port);\n while (true)\n {\n Socket s = ss.accept();\n new Thread(new Client(s)).start();\n }\n }\n catch (Exception e)\n { e.printStackTrace(); }\n }\n\n private synchronized boolean registerClient(Client client)\n {\n for (Client otherClient : clients)\n if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n return false;\n clients.add(client);\n return true;\n }\n\n private void deregisterClient(Client client)\n {\n boolean wasRegistered = false;\n synchronized (this)\n { wasRegistered = clients.remove(client); }\n if (wasRegistered)\n broadcast(client, \"--- \" + client.clientName + \" left ---\");\n }\n\n private synchronized String getOnlineListCSV()\n {\n StringBuilder sb = new StringBuilder();\n sb.append(clients.size()).append(\" user(s) online: \");\n for (int i = 0; i < clients.size(); i++)\n sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n return sb.toString();\n }\n\n private void broadcast(Client fromClient, String msg)\n {\n // Copy client list (don't want to hold lock while doing IO)\n List<Client> clients = null;\n synchronized (this)\n { clients = new ArrayList<Client>(this.clients); }\n for (Client client : clients)\n {\n if (client.equals(fromClient))\n continue;\n try\n { client.write(msg + \"\\r\\n\"); }\n catch (Exception e)\n { }\n }\n }\n\n public class Client implements Runnable\n {\n private Socket socket = null;\n private Writer output = null;\n private String clientName = null;\n\n public Client(Socket socket)\n {\n this.socket = socket;\n }\n\n public void run()\n {\n try\n {\n socket.setSendBufferSize(16384);\n socket.setTcpNoDelay(true);\n BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n output = new OutputStreamWriter(socket.getOutputStream());\n write(\"Please enter your name: \");\n String line = null;\n while ((line = input.readLine()) != null)\n {\n if (clientName == null)\n {\n line = line.trim();\n if (line.isEmpty())\n {\n write(\"A name is required. Please enter your name: \");\n continue;\n }\n clientName = line;\n if (!registerClient(this))\n {\n clientName = null;\n write(\"Name already registered. Please enter your name: \");\n continue;\n }\n write(getOnlineListCSV() + \"\\r\\n\");\n broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n continue;\n }\n if (line.equalsIgnoreCase(\"/quit\"))\n return;\n broadcast(this, clientName + \"> \" + line);\n }\n }\n catch (Exception e)\n { }\n finally\n {\n deregisterClient(this);\n output = null;\n try\n { socket.close(); }\n catch (Exception e)\n { }\n socket = null;\n }\n }\n\n public void write(String msg) throws IOException\n {\n output.write(msg);\n output.flush();\n }\n\n public boolean equals(Client client)\n {\n return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n }\n }\n\n public static void main(String[] args)\n {\n int port = 4004;\n if (args.length > 0)\n port = Integer.parseInt(args[0]);\n new ChatServer(port).run();\n }\n}\n", "language": "Java" }, { "code": "const net = require(\"net\");\nconst EventEmitter = require(\"events\").EventEmitter;\n\n/*******************************************************************************\n * ChatServer\n *\n * Manages connections, users, and chat messages.\n ******************************************************************************/\n\nclass ChatServer {\n constructor() {\n this.chatters = {};\n this.server = net.createServer(this.handleConnection.bind(this));\n this.server.listen(1212, \"localhost\");\n }\n isNicknameLegal(nickname) {\n // A nickname may contain letters or numbers only,\n // and may only be used once.\n if (nickname.replace(/[A-Za-z0-9]*/, '') !== \"\") {\n return false;\n }\n for (const used_nick in this.chatters) {\n if (used_nick === nickname) {\n return false;\n }\n }\n return true;\n }\n handleConnection(connection) {\n console.log(`Incoming connection from ${connection.remoteAddress}`);\n connection.setEncoding(\"utf8\");\n\n let chatter = new Chatter(connection, this);\n chatter.on(\"chat\", this.handleChat.bind(this));\n chatter.on(\"join\", this.handleJoin.bind(this));\n chatter.on(\"leave\", this.handleLeave.bind(this));\n }\n handleChat(chatter, message) {\n this.sendToEveryChatterExcept(chatter, chatter.nickname + \": \" + message);\n }\n handleJoin(chatter) {\n console.log(`${chatter.nickname} has joined the chat.`);\n this.sendToEveryChatter(`${chatter.nickname} has joined the chat.`);\n this.addChatter(chatter);\n }\n handleLeave(chatter) {\n console.log(`${chatter.nickname} has left the chat.`);\n this.removeChatter(chatter);\n this.sendToEveryChatter(`${chatter.nickname} has left the chat.`);\n }\n addChatter(chatter) {\n this.chatters[chatter.nickname] = chatter;\n }\n removeChatter(chatter) {\n delete this.chatters[chatter.nickname];\n }\n sendToEveryChatter(data) {\n for (const nickname in this.chatters) {\n this.chatters[nickname].send(data);\n }\n }\n sendToEveryChatterExcept(chatter, data) {\n for (const nickname in this.chatters) {\n if (nickname !== chatter.nickname) {\n this.chatters[nickname].send(data);\n }\n }\n }\n}\n\n\n/*******************************************************************************\n * Chatter\n *\n * Represents a single user/connection in the chat server.\n ******************************************************************************/\n\nclass Chatter extends EventEmitter {\n constructor(socket, server) {\n super();\n\n this.socket = socket;\n this.server = server;\n this.nickname = \"\";\n this.lineBuffer = new SocketLineBuffer(socket);\n\n this.lineBuffer.on(\"line\", this.handleNickname.bind(this));\n this.socket.on(\"close\", this.handleDisconnect.bind(this));\n\n this.send(\"Welcome! What is your nickname?\");\n }\n handleNickname(nickname) {\n if (server.isNicknameLegal(nickname)) {\n this.nickname = nickname;\n this.lineBuffer.removeAllListeners(\"line\");\n this.lineBuffer.on(\"line\", this.handleChat.bind(this));\n this.send(`Welcome to the chat, ${nickname}!`);\n this.emit(\"join\", this);\n } else {\n this.send(\"Sorry, but that nickname is not legal or is already in use!\");\n this.send(\"What is your nickname?\");\n }\n }\n handleChat(line) {\n this.emit(\"chat\", this, line);\n }\n handleDisconnect() {\n this.emit(\"leave\", this);\n }\n send(data) {\n this.socket.write(data + \"\\r\\n\");\n }\n};\n\n\n/*******************************************************************************\n * SocketLineBuffer\n *\n * Listens for and buffers incoming data on a socket and emits a 'line' event\n * whenever a complete line is detected.\n ******************************************************************************/\n\nclass SocketLineBuffer extends EventEmitter {\n constructor(socket) {\n super();\n\n this.socket = socket;\n this.buffer = \"\";\n\n this.socket.on(\"data\", this.handleData.bind(this));\n }\n handleData(data) {\n for (let i = 0; i < data.length; i++) {\n const char = data.charAt(i);\n this.buffer += char;\n if (char == \"\\n\") {\n this.buffer = this.buffer.replace(\"\\r\\n\", \"\");\n this.buffer = this.buffer.replace(\"\\n\", \"\");\n this.emit(\"line\", this.buffer);\n this.buffer = \"\";\n }\n }\n }\n};\n\n\n// Start the server!\nserver = new ChatServer();\n", "language": "JavaScript" }, { "code": "using HttpServer\nusing WebSockets\n\nconst connections = Dict{Int,WebSocket}()\nconst usernames = Dict{Int,String}()\n\nfunction decodeMessage( msg )\n String(copy(msg))\nend\n\n\nwsh = WebSocketHandler() do req, client\n global connections\n @show connections[client.id] = client\n println(\"req is $req\")\n notifyonline = \"Connection from user number $(client.id) is now online.\"\n for (k,v) in connections\n if k != client.id\n try\n write(v, notifyonline)\n catch\n continue\n end\n end\n end\n while true\n try\n msg = read(client)\n catch\n telloffline = \"User $(usernames[client.id]) disconnected.\"\n println(telloffline, \"(The client id was $(client.id).)\")\n delete!(connections, client.id)\n if haskey(usernames, client.id)\n delete!(usernames, client.id)\n end\n for (k,v) in connections\n try\n write(v, telloffline)\n catch\n continue\n end\n end\n return\n end\n msg = decodeMessage(msg)\n if startswith(msg, \"setusername:\")\n println(\"SETTING USERNAME: $msg\")\n usernames[client.id] = msg[13:end]\n notifyusername = \"User number $(client.id) chose $(usernames[client.id]) as name handle.\"\n for (k,v) in connections\n try\n write(v, notifyusername)\n catch\n println(\"Caught exception writing to user $k\")\n continue\n end\n end\n end\n if startswith(msg, \"say:\")\n println(\"EMITTING MESSAGE: $msg\")\n for (k,v) in connections\n if k != client.id\n try\n write(v, (usernames[client.id] * \": \" * msg[5:end]))\n catch\n println(\"Caught exception writing to user $k\")\n continue\n end\n end\n end\n end\n end\nend\n\nonepage = readstring(Pkg.dir(\"WebSockets\",\"examples\",\"chat-client.html\"))\nhttph = HttpHandler() do req::Request, res::Response\n Response(onepage)\nend\n\nserver = Server(httph, wsh)\nprintln(\"Chat server listening on 8000...\")\nrun(server,8000)\n", "language": "Julia" }, { "code": "import java.io.BufferedReader\nimport java.io.IOException\nimport java.io.InputStreamReader\nimport java.io.OutputStreamWriter\nimport java.io.Writer\nimport java.net.ServerSocket\nimport java.net.Socket\nimport java.util.ArrayList\nimport java.util.Collections\n\nclass ChatServer private constructor(private val port: Int) : Runnable {\n private val clients = ArrayList<Client>()\n\n private val onlineListCSV: String\n @Synchronized get() {\n val sb = StringBuilder()\n sb.append(clients.size).append(\" user(s) online: \")\n for (i in clients.indices) {\n sb.append(if (i > 0) \", \" else \"\").append(clients[i].clientName)\n }\n return sb.toString()\n }\n\n override fun run() {\n try {\n val ss = ServerSocket(port)\n while (true) {\n val s = ss.accept()\n Thread(Client(s)).start()\n }\n } catch (e: Exception) {\n e.printStackTrace()\n }\n }\n\n @Synchronized\n private fun registerClient(client: Client): Boolean {\n for (otherClient in clients) {\n if (otherClient.clientName!!.equals(client.clientName!!, ignoreCase = true)) {\n return false\n }\n }\n clients.add(client)\n return true\n }\n\n private fun deRegisterClient(client: Client) {\n var wasRegistered = false\n synchronized(this) {\n wasRegistered = clients.remove(client)\n }\n if (wasRegistered) {\n broadcast(client, \"--- \" + client.clientName + \" left ---\")\n }\n }\n\n private fun broadcast(fromClient: Client, msg: String) {\n // Copy client list (don't want to hold lock while doing IO)\n var clients: List<Client> = Collections.emptyList()\n synchronized(this) {\n clients = ArrayList(this.clients)\n }\n for (client in clients) {\n if (client.equals(fromClient)) {\n continue\n }\n try {\n client.write(msg + \"\\r\\n\")\n } catch (e: Exception) {\n e.printStackTrace()\n }\n\n }\n }\n\n inner class Client internal constructor(private var socket: Socket?) : Runnable {\n private var output: Writer? = null\n var clientName: String? = null\n\n override fun run() {\n try {\n socket!!.sendBufferSize = 16384\n socket!!.tcpNoDelay = true\n val input = BufferedReader(InputStreamReader(socket!!.getInputStream()))\n output = OutputStreamWriter(socket!!.getOutputStream())\n write(\"Please enter your name: \")\n var line: String\n while (true) {\n line = input.readLine()\n if (null == line) {\n break\n }\n if (clientName == null) {\n line = line.trim { it <= ' ' }\n if (line.isEmpty()) {\n write(\"A name is required. Please enter your name: \")\n continue\n }\n clientName = line\n if (!registerClient(this)) {\n clientName = null\n write(\"Name already registered. Please enter your name: \")\n continue\n }\n write(onlineListCSV + \"\\r\\n\")\n broadcast(this, \"+++ $clientName arrived +++\")\n continue\n }\n if (line.equals(\"/quit\", ignoreCase = true)) {\n return\n }\n broadcast(this, \"$clientName> $line\")\n }\n } catch (e: Exception) {\n e.printStackTrace()\n } finally {\n deRegisterClient(this)\n output = null\n try {\n socket!!.close()\n } catch (e: Exception) {\n e.printStackTrace()\n }\n\n socket = null\n }\n }\n\n @Throws(IOException::class)\n internal fun write(msg: String) {\n output!!.write(msg)\n output!!.flush()\n }\n\n internal fun equals(client: Client?): Boolean {\n return (client != null\n && clientName != null\n && client.clientName != null\n && clientName == client.clientName)\n }\n }\n\n companion object {\n @JvmStatic\n fun main(args: Array<String>) {\n var port = 4004\n if (args.isNotEmpty()) {\n port = Integer.parseInt(args[0])\n }\n ChatServer(port).run()\n }\n }\n}\n", "language": "Kotlin" }, { "code": "import asyncnet, asyncdispatch\n\ntype\n Client = tuple\n socket: AsyncSocket\n name: string\n connected: bool\n\nvar clients {.threadvar.}: seq[Client]\n\nproc sendOthers(client: Client, line: string) {.async.} =\n for c in clients:\n if c != client and c.connected:\n await c.socket.send(line & \"\\c\\L\")\n\nproc processClient(socket: AsyncSocket) {.async.} =\n await socket.send(\"Please enter your name: \")\n var client: Client = (socket, await socket.recvLine(), true)\n\n clients.add(client)\n asyncCheck client.sendOthers(\"+++ \" & client.name & \" arrived +++\")\n\n while true:\n let line = await client.socket.recvLine()\n if line == \"\":\n asyncCheck client.sendOthers(\"--- \" & client.name & \" leaves ---\")\n client.connected = false\n return\n asyncCheck client.sendOthers(client.name & \"> \" & line)\n\nproc serve() {.async.} =\n clients = @[]\n var server = newAsyncSocket()\n server.bindAddr(Port(4004))\n server.listen()\n\n while true:\n let socket = await server.accept()\n asyncCheck processClient(socket)\n\nasyncCheck serve()\nrunForever()\n", "language": "Nim" }, { "code": "use System.IO.Net;\nuse System.Concurrency;\nuse Collection;\n\nbundle Default {\n class ChatServer {\n @clients : StringMap;\n @clients_mutex : ThreadMutex;\n\n New() {\n @clients := StringMap->New();\n @clients_mutex := ThreadMutex->New(\"clients_mutex\");\n }\n\n method : ValidLogin(login_name : String, clients : StringMap) ~ Bool {\n if(clients->Has(login_name)) {\n return false;\n };\n\n return true;\n }\n\n function : Main(args : String[]) ~ Nil {\n chat_server := ChatServer->New();\n chat_server->Run();\n }\n\n method : public : Broadcast(message : String, sender : Client) ~ Nil {\n client_array : Vector;\n critical(@clients_mutex) {\n client_array := @clients->GetValues();\n };\n each(i : client_array) {\n client := client_array->Get(i)->As(Client);\n if(client <> sender) {\n client->Send(message);\n };\n };\n }\n\n method : public : Disconnect(sender : Client) ~ Nil {\n send_name := sender->GetName();\n Broadcast(\"+++ {$send_name} has left +++\", sender);\n critical(@clients_mutex) {\n @clients->Remove(sender->GetName());\n };\n sender->Close();\n }\n\n method : public : Run() ~ Nil {\n server := TCPSocketServer->New(4661);\n if(server->Listen(5)) {\n while(true) {\n client_sock := server->Accept();\n critical(@clients_mutex) {\n client_sock->WriteString(\"login: \");\n login_name := client_sock->ReadString();\n if(ValidLogin(login_name, @clients)) {\n client := Client->New(login_name, client_sock, @self);\n @clients->Insert(client->GetName(), client);\n client->Execute(Nil);\n }\n else {\n client_sock->WriteString(\"+++ login in use +++\\r\\n\");\n client_sock->Close();\n };\n };\n };\n };\n server->Close();\n }\n }\n\n class Client from Thread {\n @client_sock : TCPSocket;\n @server : ChatServer;\n\n New(login_name : String, client_sock : TCPSocket, server : ChatServer) {\n Parent(login_name);\n @client_sock := client_sock;\n @server := server;\n }\n\n method : public : Close() ~ Nil {\n @client_sock->Close();\n }\n\n method : public : Send(message : String) ~ Nil {\n if(@client_sock->IsOpen() & message->Size() > 0) {\n @client_sock->WriteString(\"{$message}\\r\\n\");\n }\n else {\n @server->Disconnect(@self);\n };\n }\n\n method : public : Run(param : Base) ~ Nil {\n client_name := GetName();\n @server->Broadcast(\"+++ {$client_name} has arrived +++\", @self);\n\n message := @client_sock->ReadString();\n while(message->Size() > 0 & message->Equals(\"/quit\") = false) {\n @server->Broadcast(\"{$client_name}> {$message}\", @self);\n message := @client_sock->ReadString();\n };\n @server->Disconnect(@self);\n }\n }\n}\n", "language": "Objeck" }, { "code": "(define (timestamp) (syscall 201 \"%c\"))\n\n(fork-server 'chat-room (lambda ()\n(let this ((visitors #empty))\n(let* ((envelope (wait-mail))\n (sender msg envelope))\n (case msg\n (['join who name]\n (let ((visitors (put visitors who name)))\n (for-each (lambda (who)\n (print-to (car who) name \" joined to as\"))\n (ff->alist visitors))\n (this visitors)))\n (['talk message]\n (for-each (lambda (who)\n (print-to (car who) (cdr who) \": \" message))\n (ff->alist visitors))\n (this visitors))\n (['part who]\n (for-each (lambda (who)\n (print-to (car who) (visitors (car who) \"unknown\") \" leaved\"))\n (ff->alist visitors))\n (let ((visitors (del visitors who)))\n (this visitors))))))))\n\n\n(define (on-accept name fd)\n(lambda ()\n (print \"# \" (timestamp) \"> we got new visitor: \" name)\n (mail 'chat-room ['join fd name])\n\n (let*((ss1 ms1 (clock)))\n (let loop ((str #null) (stream (force (port->bytestream fd))))\n (cond\n ((null? stream)\n #false)\n ((function? stream)\n (mail 'chat-room ['talk (list->string (reverse str))])\n (loop #null (force stream)))\n (else\n (loop (cons (car stream) str) (cdr stream)))))\n (syscall 3 fd)\n (let*((ss2 ms2 (clock)))\n (print \"# \" (timestamp) \"> visitor leave us. It takes \" (+ (* (- ss2 ss1) 1000) (- ms2 ms1)) \"ms.\")))\n (mail 'chat-room ['part fd])\n ))\n\n(define (run port)\n(let ((socket (syscall 41)))\n ; bind\n (let loop ((port port))\n (if (not (syscall 49 socket port)) ; bind\n (loop (+ port 2))\n (print \"Server binded to \" port)))\n ; listen\n (if (not (syscall 50 socket)) ; listen\n (shutdown (print \"Can't listen\")))\n\n ; accept\n (let loop ()\n (if (syscall 23 socket) ; select\n (let ((fd (syscall 43 socket))) ; accept\n ;(print \"\\n# \" (timestamp) \": new request from \" (syscall 51 fd))\n (fork (on-accept (syscall 51 fd) fd))))\n (sleep 0)\n (loop))))\n\n(run 8080)\n", "language": "Ol" }, { "code": "use 5.010;\nuse strict;\nuse warnings;\n\nuse threads;\nuse threads::shared;\n\nuse IO::Socket::INET;\nuse Time::HiRes qw(sleep ualarm);\n\nmy $HOST = \"localhost\";\nmy $PORT = 4004;\n\nmy @open;\nmy %users : shared;\n\nsub broadcast {\n my ($id, $message) = @_;\n print \"$message\\n\";\n foreach my $i (keys %users) {\n if ($i != $id) {\n $open[$i]->send(\"$message\\n\");\n }\n }\n}\n\nsub sign_in {\n my ($conn) = @_;\n\n state $id = 0;\n\n threads->new(\n sub {\n while (1) {\n $conn->send(\"Please enter your name: \");\n $conn->recv(my $name, 1024, 0);\n\n if (defined $name) {\n $name = unpack('A*', $name);\n\n if (exists $users{$name}) {\n $conn->send(\"Name entered is already in use.\\n\");\n }\n elsif ($name ne '') {\n $users{$id} = $name;\n broadcast($id, \"+++ $name arrived +++\");\n last;\n }\n }\n }\n }\n );\n\n ++$id;\n push @open, $conn;\n}\n\nmy $server = IO::Socket::INET->new(\n Timeout => 0,\n LocalPort => $PORT,\n Proto => \"tcp\",\n LocalAddr => $HOST,\n Blocking => 0,\n Listen => 1,\n Reuse => 1,\n );\n\nlocal $| = 1;\nprint \"Listening on $HOST:$PORT\\n\";\n\nwhile (1) {\n my ($conn) = $server->accept;\n\n if (defined($conn)) {\n sign_in($conn);\n }\n\n foreach my $i (keys %users) {\n\n my $conn = $open[$i];\n my $message;\n\n eval {\n local $SIG{ALRM} = sub { die \"alarm\\n\" };\n ualarm(500);\n $conn->recv($message, 1024, 0);\n ualarm(0);\n };\n\n if ($@ eq \"alarm\\n\") {\n next;\n }\n\n if (defined($message)) {\n if ($message ne '') {\n $message = unpack('A*', $message);\n broadcast($i, \"$users{$i}> $message\");\n }\n else {\n broadcast($i, \"--- $users{$i} leaves ---\");\n delete $users{$i};\n undef $open[$i];\n }\n }\n }\n\n sleep(0.1);\n}\n", "language": "Perl" }, { "code": "#!/usr/bin/perl\n\nuse strict; # http://www.rosettacode.org/wiki/Chat_server\nuse warnings;\nuse IO::Socket;\nuse IO::Select; # with write queueing\n\nmy $port = shift // 6666;\nmy (%nicks, @users, %data);\n\nmy $listen = IO::Socket::INET->new(LocalPort => $port, Listen => 9,\n Reuse => 1) or die \"$@ opening socket on port $port\";\nmy $rsel = IO::Select->new($listen);\nmy $wsel = IO::Select->new();\nprint \"ready on $port...\\n\";\n\nsub to\n {\n my $text = pop;\n for ( @_ )\n {\n length $data{$_}{out} or $wsel->add( $_ );\n length( $data{$_}{out} .= $text ) > 1e4 and left( $_ );\n }\n return $text;\n }\n\nsub left\n {\n my $h = shift;\n @users = grep $h != $_, @users;\n if( defined( my $nick = delete $nicks{$h} ) )\n {\n print to @users, \"$nick has left\\n\";\n }\n delete $data{$h};\n $rsel->remove($h);\n }\n\nwhile( 1 )\n {\n my ($reads, $writes) = IO::Select->select($rsel, $wsel, undef, 5);\n for my $h ( @{ $writes // [] } )\n {\n my $len = syswrite $h, $data{$h}{out};\n $len and substr $data{$h}{out}, 0, $len, '';\n length $data{$h}{out} or $wsel->remove( $h );\n }\n for my $h ( @{ $reads // [] } )\n {\n if( $h == $listen ) # new connection\n {\n $rsel->add( my $client = $h->accept );\n $data{$client} = { h => $client, out => \"enter nick: \", in => '' };\n $wsel->add( $client );\n }\n elsif( not sysread $h, $data{$h}{in}, 4096, length $data{$h}{in} ) # closed\n {\n left $h;\n }\n elsif( exists $nicks{$h} ) # user is signed in\n {\n my @others = grep $h != $_, @users;\n to @others, \"$nicks{$h}> $&\" while $data{$h}{in} =~ s/.*\\n//;\n }\n elsif( $data{$h}{in} =~ s/^(\\w+)\\r?\\n.*//s and\n not grep lc $1 eq lc, values %nicks )\n { # user has joined\n my $all = join ' ', sort values %nicks;\n $nicks{$h} = $1;\n push @users, $h;\n print to @users, \"$nicks{$h} has joined $all\\n\";\n }\n else # bad nick\n {\n to $h, \"nick invalid or in use, enter nick: \";\n $data{$h}{in} = '';\n }\n }\n }\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\ChatServer.exw\n -- ========================\n --\n -- translation of (qchat) chatServ.exw\n --\n -- Run this first, then ChatClient.exw, see also IRC_Gateway.exw\n --\n -- Note that I've only got a 32-bit windows eulibnet.dll, but it should not\n -- be dificult to use a \"real\" libnet.dll/so, or something a little newer.\n --</span>\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">dl</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">`Download rosetta\\eulibnet\\ from http://phix.x10.mx/pmwiki/pmwiki.php?n=Main.Eulibnet`</span>\n <span style=\"color: #7060A8;\">assert</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">get_file_type</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"eulibnet\"</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #004600;\">FILETYPE_DIRECTORY</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">dl</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">eulibnet</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">eulibnet</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">ew</span>\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">log_list</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">log_window</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">statusbar</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">timer</span>\n\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">listconn</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">IP</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"127.0.0.1\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">port</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"29029\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">IPaddress</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">IP</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #008000;\">\":\"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">port</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">MAX_MSG</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">550</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">connections</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span>\n <span style=\"color: #000000;\">nicknames</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">max_log_len</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">300</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">log_to_window</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">to_number</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">IupGetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">log_list</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"COUNT\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #000000;\">max_log_len</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">max_log_len</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">log_list</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"REMOVEITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"1\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">log_list</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"APPENDITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">log_list</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TOPITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">IupGetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">log_list</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"COUNT\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupUpdate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">log_list</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">args</span><span style=\"color: #0000FF;\">={})</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">args</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">args</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">statusbar</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">log_to_window</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">shutDown</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Shutting down euLibnet...\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">connections</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_closeconn</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">connections</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">crash</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error closing connection!\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_closeconn</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">listconn</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">crash</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error closing listconn!\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_shutdown</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">crash</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error shutting down euLibnet!\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">sendToAll</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- Send msg to all clients</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">connections</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">ci</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">connections</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Sending to connection %d (%s)\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nicknames</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]})</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_send_rdm</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error sending to connection %d\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">mainWindow_onOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Initializing euLibnet...\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_init</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">crash</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error initializing euLibnet!\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"done.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Initializing driver...\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_initdriver</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">NET_DRIVER_WSOCK_WIN</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">!=</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">crash</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error initializing WinSock driver!\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"done.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Opening port \"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">IPaddress</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #008000;\">\"...\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">listconn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">net_openconn</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">NET_DRIVER_WSOCK_WIN</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">IPaddress</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">listconn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">NULL</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">crash</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Couldn't open connection (server already running?)\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"done.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_listen</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">listconn</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">crash</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error trying to listen to port\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Listening on port \"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">IPaddress</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">timer_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*timer*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">conn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">net_poll_listen</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">listconn</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">conn</span> <span style=\"color: #0000FF;\">!=</span> <span style=\"color: #004600;\">NULL</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">connections</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">connections</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">conn</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">nicknames</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nicknames</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"New connection open from \"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">net_getpeer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">conn</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- Check for messages from clients</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">connections</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ci</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">connections</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_query_rdm</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">ni</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">nicknames</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000080;font-style:italic;\">--Get the message</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">net_receive_rdm</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">MAX_MSG</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"received msg \\\"%s\\\" of length %d from %d aka %s\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ni</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\"><</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000080;font-style:italic;\">--Exit on error</span>\n <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">net_ignore_rdm</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">sendToAll</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Server error: some data may be lost\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #000000;\">4</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">equal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #008000;\">\"/n:\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)],</span> <span style=\"color: #000000;\">nicknames</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_send_rdm</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"/nt\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error sending to %d\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">prevname</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">ni</span>\n <span style=\"color: #000000;\">ni</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)]</span>\n <span style=\"color: #000000;\">nicknames</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">ni</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">prevname</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">sendToAll</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"/j:\"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">ni</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #008000;\">\" has joined\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- send fake \"has joined\"s to the new joiner,\n -- so that it can build a full members list (see allj)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nicknames</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">i</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"/j:\"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">nicknames</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #008000;\">\" has joined\"</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_send_rdm</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error sending to connection %d\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">sendToAll</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"/c:\"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">prevname</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #008000;\">\" has changed name to \"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">ni</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #7060A8;\">equal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"/d\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"/l:\"</span><span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">ni</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #008000;\">\" has left\"</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">nicknames</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #000000;\">connections</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #000000;\">sendToAll</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #000080;font-style:italic;\">-- Aside: bunch of popup and file transfer stuff was here in qchat.exw,\n -- all ripped out in the name of keeping this short and sweet.</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">sendToAll</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ni</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #008000;\">\": \"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (Add nickname to message)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_IGNORE</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">close_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">shutDown</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">log_list</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupList</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"EXPAND=YES, CANFOCUS=NO, MULTIPLE=YES\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">statusbar</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Loading...\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"EXPAND=HORIZONTAL\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">log_window</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">IupVbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">log_list</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">statusbar</span><span style=\"color: #0000FF;\">}),</span>\n <span style=\"color: #008000;\">`TITLE=\"Chat Server\", RASTERSIZE=400x400`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">log_window</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"CLOSE_CB\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"close_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">log_window</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">mainWindow_onOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">timer</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupTimer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"timer_cb\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">500</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "(notonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\ChatClient.exw\n -- ===========================\n --\n -- translation of (qchat) QChat.exw\n --\n -- Probably best to run ChatServer.exw before this.\n --</span>\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">bViaGateway</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #000080;font-style:italic;\">--constant bool bViaGateway = true -- see IRC_Gateway.exw</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">dl</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">`Download rosetta\\eulibnet\\ from http://phix.x10.mx/pmwiki/pmwiki.php?n=Main.Eulibnet`</span>\n <span style=\"color: #7060A8;\">assert</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">get_file_type</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"eulibnet\"</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #004600;\">FILETYPE_DIRECTORY</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">dl</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">eulibnet</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">eulibnet</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">ew</span>\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">about</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">help</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">quit</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nickle</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nickname</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">login</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">memble</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">members</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">logle</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">log_list</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">messle</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">statusbar</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">chat_window</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">timer</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">conn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">conFlag</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">allj</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #000080;font-style:italic;\">-- (suppress initial flurry of fake \"has joined\" messages)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">nick</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">conTextBack</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">IP</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"127.0.0.1\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">port</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">bViaGateway</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"29030\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"29029\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">-- See IRC_Gateway.exw</span>\n <span style=\"color: #000000;\">timeout</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">20</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">IPaddress</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">IP</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #008000;\">\":\"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">port</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">cr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\\r\\n\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">MAX_MSG</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">80</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">about_text</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"\"\n Translated by Pete Lomax from qchat by Andrew/Norman (and win32lib ==&gt; pGUI).\n Uses Libnet by George Foot and Chad Catlet as wrapped by Ray Smith.\"\n \"\"\"</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">about_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupMessage</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"About\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">about_text</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">help_text</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"\"\n Make sure ChatServer.exw is running first...\n\n Enter a nickname and press the Connect Button (or Return), then\n enter your messages in the message area.\n \"\"\"</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">help_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandln</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupMessage</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Chat client\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">help_text</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">statusbar</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- This should probably be cropped once it gets too long...</span>\n <span style=\"color: #000000;\">conTextBack</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">message</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">cr</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">log_list</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">conTextBack</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">log_list</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"SCROLLTOPOS\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">conTextBack</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">sendMsg</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">conFlag</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"You must be connected to do this\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_send_rdm</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">conn</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error sending message \\'\"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #008000;\">\"\\'\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">shutDown</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nick</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Disconnecting from server...\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_send_rdm</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">conn</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"/d\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error disconnecting from server!\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Shutting down euLibnet...\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">conn</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_closeconn</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">conn</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">crash</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error closing connection!\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_shutdown</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">crash</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error shutting down euLibnet!\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">conFlag</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">quit_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">shutDown</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_CLOSE</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">connect_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">nick</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nickname</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nick</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Opening connection...\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">conn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">net_openconn</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">NET_DRIVER_WSOCK_WIN</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">conn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">NULL</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Couldn't open connection.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"done.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Attempting to connect to chat server...\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ret</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">net_connect_wait_time</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">conn</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">IPaddress</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">timeout</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ret</span> <span style=\"color: #0000FF;\"><</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error trying to establish connection.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">ret</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Timeout trying to establish connection.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"done.\"</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000000;\">conFlag</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nickname</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Chat Client - \"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">nick</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">nickname</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">login</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #008000;\">\"ACTIVE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">sendMsg</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"/n:\"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">nick</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">timer</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"RUN\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">members</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nick</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ACTIVE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetFocus</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">mainWindow_onOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Initializing euLibnet...\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_init</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">crash</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error initializing euLibnet!\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"done.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Initializing driver...\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_initdriver</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">NET_DRIVER_WSOCK_WIN</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">!=</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">crash</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error initializing WinSock driver!\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"done.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetFocus</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nickname</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">member_has_joined</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">joiner</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">mt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">members</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">ml</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'\\n'</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">mt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">unique</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ml</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">joiner</span><span style=\"color: #0000FF;\">)),</span><span style=\"color: #008000;\">'\\n'</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">members</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">mt</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">member_has_left</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">leaver</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">mt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">members</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">ml</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'\\n'</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">leaver</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ml</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">ml</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">members</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ml</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'\\n'</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">timer_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*timer*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">net_query_rdm</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">conn</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000080;font-style:italic;\">--Check for message</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">net_receive_rdm</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">conn</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">MAX_MSG</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\"><</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Error receiving message!\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">net_ignore_rdm</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">conn</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">equal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"/nt\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Nickname \"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">nick</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #008000;\">\" already taken\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">nick</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #008000;\">\"b\"</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Trying \"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">nick</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #008000;\">\" instead\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Type /n:nickname to try a different one\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">sendMsg</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"/n:\"</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">nick</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- As per ChatServer, bunch of popup and file transfer stuff was\n -- all ripped out in the name of keeping this short and sweet.</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)></span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">equal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #008000;\">\"/j:\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">member_has_joined</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #7060A8;\">match</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\" has joined\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">allj</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">..$]</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)></span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">equal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #008000;\">\"/l:\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">member_has_left</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #7060A8;\">match</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\" has left\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">..$]</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)></span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">equal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #008000;\">\"/c:\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">shcnts</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\" has changed name to \"</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">match</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">shcnts</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">member_has_left</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">member_has_joined</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">shcnts</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..$])</span>\n <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">..$]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">allj</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">key_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">K_ESC</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">shutDown</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_CLOSE</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">K_F1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">help_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'\\r'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">input</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">sendMsg</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">IupGetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">nickname</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">connect_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">about</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupButton</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"About\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"about_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">help</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupButton</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Help\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"help_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">quit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupButton</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Exit\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"quit_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">nickle</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Nickname\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">nickname</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupText</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"EXPAND=HORIZONTAL\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">login</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupButton</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Connect\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"connect_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">memble</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Members online\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">members</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupText</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"EXPAND=VERTICAL, CANFOCUS=NO, MULTILINE=YES, SIZE=70x\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">logle</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Incoming text\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">log_list</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupText</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"EXPAND=YES, CANFOCUS=NO, MULTILINE=YES\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">messle</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Message\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">input</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupText</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"EXPAND=HORIZONTAL\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">nickname</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #008000;\">\"KEY_CB\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"key_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"CUEBANNER\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"This Is Where You Type\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"NC\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">72</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- Max 72 characters allowed</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ACTIVE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">statusbar</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Loading...\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"EXPAND=HORIZONTAL\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">chat_window</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">IupVbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #7060A8;\">IupHbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">about</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">help</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">quit</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nickle</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nickname</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">login</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #008000;\">\"NORMALIZESIZE=VERTICAL,GAP=10,MARGIN=5x5\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #7060A8;\">IupHbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #7060A8;\">IupVbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">memble</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">members</span><span style=\"color: #0000FF;\">}),</span>\n <span style=\"color: #7060A8;\">IupVbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">logle</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">log_list</span><span style=\"color: #0000FF;\">})},</span>\n <span style=\"color: #008000;\">\"NGAP=10,NMARGIN=5x5\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #7060A8;\">IupHbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">messle</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #008000;\">\"GAP=10,MARGIN=5x5\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">statusbar</span><span style=\"color: #0000FF;\">}),</span>\n <span style=\"color: #008000;\">`TITLE=\"Chat Client\", RASTERSIZE=400x400`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">chat_window</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"CLOSE_CB\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"quit_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupSetAttributeHandle</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"PARENTDIALOG\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">chat_window</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">chat_window</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">mainWindow_onOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">timer</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupTimer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"timer_cb\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">500</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "#!/usr/bin/picolisp /usr/lib/picolisp/lib.l\n\n(de chat Lst\n (out *Sock\n (mapc prin Lst)\n (prinl) ) )\n\n(setq *Port (port 4004))\n\n(loop\n (setq *Sock (listen *Port))\n (NIL (fork) (close *Port))\n (close *Sock) )\n\n(out *Sock\n (prin \"Please enter your name: \")\n (flush) )\n(in *Sock (setq *Name (line T)))\n\n(tell 'chat \"+++ \" *Name \" arrived +++\")\n\n(task *Sock\n (in @\n (ifn (eof)\n (tell 'chat *Name \"> \" (line T))\n (tell 'chat \"--- \" *Name \" left ---\")\n (bye) ) ) )\n(wait)\n", "language": "PicoLisp" }, { "code": ":- initialization chat_server(5000).\n\nchat_server(Port) :-\n tcp_socket(Socket),\n tcp_bind(Socket, Port),\n tcp_listen(Socket, 5),\n tcp_open_socket(Socket, AcceptFd, _),\n dispatch(AcceptFd).\n\ndispatch(AcceptFd) :-\n tcp_accept(AcceptFd, Socket, _),\n thread_create(process_client(Socket, _), _, [detached(true)]),\n dispatch(AcceptFd).\n\nprocess_client(Socket, _) :-\n setup_call_cleanup(\n tcp_open_socket(Socket, Str),\n handle_connection(Str),\n close(Str)).\n\n% a connection was made, get the username and add the streams so the\n% client can be broadcast to.\nhandle_connection(Str) :-\n send_msg(Str, msg_welcome, []),\n repeat,\n send_msg(Str, msg_username, []),\n read_line_to_string(Str, Name),\n connect_user(Name, Str), !.\n\n% connections are stored here\n:- dynamic(connected/2).\n\nconnect_user(Name, Str) :-\n connected(Name, _),\n send_msg(Str, msg_username_taken, []),\n fail.\nconnect_user(Name, Str) :-\n \\+ connected(Name, _),\n send_msg(Str, msg_welcome_name, Name),\n\n % make sure that the connection is removed when the client leaves.\n setup_call_cleanup(\n assert(connected(Name, Str)),\n (\n broadcast(Name, msg_joined, Name),\n chat_loop(Name, Str), !,\n broadcast(Name, msg_left, Name)\n ),\n retractall(connected(Name, _))\n ).\n\n% wait for a line to be sent then broadcast to the rest of the clients\n% finish this goal when the client disconnects (end of stream)\nchat_loop(Name, Str) :-\n read_line_to_string(Str, S),\n dif(S, end_of_file),\n broadcast(Name, msg_by_user, [Name, S]),\n chat_loop(Name, Str).\nchat_loop(_, Str) :- at_end_of_stream(Str).\n\n% send a message to all connected clients except Name (the sender)\nbroadcast(Name, Msg, Params) :-\n forall(\n (connected(N, Str), dif(N, Name)),\n (send_msg(Str, Msg, Params), send_msg(Str, msg_new_line, []))\n ).\n\nsend_msg(St, MsgConst, Params) :-\n call(MsgConst, Msg),\n format(St, Msg, Params),\n flush_output(St).\n\n% constants for the various message types that are sent\nmsg_welcome('Welcome to Chatalot\\n\\r').\nmsg_username('Please enter your nickname: ').\nmsg_welcome_name('Welcome ~p\\n\\r').\nmsg_joined(' -- \"~w\" has joined the chat --').\nmsg_left(' -- \"~w\" has left the chat. --').\nmsg_username_taken('That username is already taken, choose another\\n\\r').\nmsg_new_line('\\n\\r').\nmsg_by_user('~w> ~w').\n", "language": "Prolog" }, { "code": "#!/usr/bin/env python\n\nimport socket\nimport thread\nimport time\n\nHOST = \"\"\nPORT = 4004\n\ndef accept(conn):\n \"\"\"\n Call the inner func in a thread so as not to block. Wait for a\n name to be entered from the given connection. Once a name is\n entered, set the connection to non-blocking and add the user to\n the users dict.\n \"\"\"\n def threaded():\n while True:\n conn.send(\"Please enter your name: \")\n try:\n name = conn.recv(1024).strip()\n except socket.error:\n continue\n if name in users:\n conn.send(\"Name entered is already in use.\\n\")\n elif name:\n conn.setblocking(False)\n users[name] = conn\n broadcast(name, \"+++ %s arrived +++\" % name)\n break\n thread.start_new_thread(threaded, ())\n\ndef broadcast(name, message):\n \"\"\"\n Send a message to all users from the given name.\n \"\"\"\n print message\n for to_name, conn in users.items():\n if to_name != name:\n try:\n conn.send(message + \"\\n\")\n except socket.error:\n pass\n\n# Set up the server socket.\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.setblocking(False)\nserver.bind((HOST, PORT))\nserver.listen(1)\nprint \"Listening on %s\" % (\"%s:%s\" % server.getsockname())\n\n# Main event loop.\nusers = {}\nwhile True:\n try:\n # Accept new connections.\n while True:\n try:\n conn, addr = server.accept()\n except socket.error:\n break\n accept(conn)\n # Read from connections.\n for name, conn in users.items():\n try:\n message = conn.recv(1024)\n except socket.error:\n continue\n if not message:\n # Empty string is given on disconnect.\n del users[name]\n broadcast(name, \"--- %s leaves ---\" % name)\n else:\n broadcast(name, \"%s> %s\" % (name, message.strip()))\n time.sleep(.1)\n except (SystemExit, KeyboardInterrupt):\n break\n", "language": "Python" }, { "code": "chat_loop <- function(server, sockets, delay = 0.5) {\n repeat {\n Sys.sleep(delay) # Saves CPU resources\n\n ## Exhausts queue each iteration\n while (in_queue(server))\n sockets <- new_socket_entry(server, sockets)\n\n ## Update which sockets have sent messages\n sockets <- check_messages(sockets)\n\n ## No sockets, nothing to do\n if (nrow(sockets) == 0)\n next\n\n ## No new messages, nothing to do\n if (all(!sockets$message_ready))\n next\n\n\n sockets <- read_messages(sockets) # Messages are stored until sent\n sockets <- drop_dead(sockets) # Dead = ready to read, but no data\n\n ## In case all sockets were dropped\n if (nrow(sockets) == 0)\n next\n\n sockets <- update_nicknames(sockets)\n sockets <- send_messages(sockets) # Only to users with nicknames\n }\n}\n\ncheck_messages <- function(sockets) {\n if (nrow(sockets) != 0)\n sockets$message_ready <- socketSelect(sockets$conn, timeout = 0)\n\n sockets\n}\n\ndrop_dead <- function(sockets) {\n lapply(with(sockets, conn[!alive]), close)\n dropped <- with(sockets, nickname[nickname_exists(sockets) & !alive])\n sockets <- sockets[sockets$alive, ]\n\n if (length(dropped) != 0) {\n send_named(sockets, paste0(dropped, \" has disconnected.\"))\n }\n\n sockets\n}\n\nin_queue <- function(server) socketSelect(list(server), timeout = 0)\nis_valid_name <- function(nicks) gsub(\"[A-Za-z0-9]*\", \"\", nicks) == \"\"\nmessage_exists <- function(sockets) !is.na(sockets$message)\n\nnew_row <- function(df) {\n df[nrow(df) + 1, ] <- NA\n df\n}\n\nnew_socket_entry <- function(server, sockets) {\n sockets <- new_row(sockets)\n n <- nrow(sockets)\n within(sockets, {\n conn[[n]] <- new_user(server)\n alive[n] <- TRUE\n message_ready[n] <- FALSE\n })\n}\n\nnew_user <- function(server) {\n conn <- socketAccept(server)\n writeLines(\"Hello! Please enter a nickname.\", conn)\n conn\n}\n\nnickname_exists <- function(sockets) !is.na(sockets$nickname)\n\nread_messages <- function(sockets) {\n if (all(!sockets$message_ready))\n return(sockets)\n\n msgs <- lapply(with(sockets, conn[message_ready]), readLines, n = 1)\n empty_msgs <- sapply(msgs, identical, character(0))\n sockets <- within(sockets, alive[message_ready & empty_msgs] <- FALSE)\n msgs <- unlist(ifelse(empty_msgs, NA, msgs))\n within(sockets, message[message_ready] <- msgs)\n}\n\nsend_messages <- function(sockets) {\n named_message <- message_exists(sockets) & nickname_exists(sockets)\n\n if (all(!named_message))\n return(sockets)\n\n rows <- which(named_message)\n socksub <- sockets[rows, ]\n time <- format(Sys.time(), \"[%H:%M:%S] \")\n with(socksub, send_named(sockets, paste0(time, nickname, \": \", message)))\n within(sockets, message[rows] <- NA)\n}\n\nsend_named <- function(sockets, msg) {\n has_nickname <- nickname_exists(sockets)\n invisible(lapply(sockets$conn[has_nickname], writeLines, text = msg))\n}\n\nstart_chat_server <- function(port = 50525) {\n server <- serverSocket(port) # Start listening\n on.exit(closeAllConnections()) # Cleanup connections\n\n ## All socket data is stored and passed using this object\n sockets <- data.frame(conn = I(list()), nickname = character(),\n message = character(), alive = logical(),\n message_ready = logical())\n\n ## Main event loop\n chat_loop(server, sockets)\n}\n\nupdate_nicknames <- function(sockets) {\n sent_nickname <- message_exists(sockets) & !nickname_exists(sockets)\n nickname_valid <- is_valid_name(sockets$message)\n\n if (all(!sent_nickname))\n return(sockets)\n\n is_taken <- with(sockets, (tolower(message) %in% tolower(sockets$nickname)) &\n !is.na(message))\n sent_ok <- sent_nickname & nickname_valid & !is_taken\n sockets <- within(sockets, {\n nickname[sent_ok] <- message[sent_ok]\n message[sent_nickname] <- NA\n lapply(conn[sent_nickname & !nickname_valid], writeLines,\n text = \"Alphanumeric characters only. Try again.\")\n lapply(conn[is_taken], writeLines,\n text = \"Name already taken. Try again.\")\n })\n\n if (any(sent_ok))\n send_named(sockets, paste0(sockets$nickname[sent_ok], \" has connected.\"))\n\n sockets\n}\n\nstart_chat_server()\n", "language": "R" }, { "code": "#lang racket\n\n(define outs (list (current-output-port)))\n(define ((tell-all who o) line)\n (for ([c outs] #:unless (eq? o c)) (displayln (~a who \": \" line) c)))\n\n(define ((client i o))\n (define nick (begin (display \"Nick: \" o) (read-line i)))\n (define tell (tell-all nick o))\n (let loop ([line \"(joined)\"])\n (if (eof-object? line)\n (begin (tell \"(left)\") (set! outs (remq o outs)) (close-output-port o))\n (begin (tell line) (loop (read-line i))))))\n\n(define (chat-server listener)\n (define-values [i o] (tcp-accept listener))\n (for ([p (list i o)]) (file-stream-buffer-mode p 'none))\n (thread (client i o)) (set! outs (cons o outs)) (chat-server listener))\n\n(void (thread (λ() (chat-server (tcp-listen 12321)))))\n((client (current-input-port) (current-output-port)))\n", "language": "Racket" }, { "code": "react {\n my %connections;\n\n whenever IO::Socket::Async.listen('localhost', 4004) -> $conn {\n my $name;\n\n $conn.print: \"Please enter your name: \";\n\n whenever $conn.Supply.lines -> $message {\n if !$name {\n if %connections{$message} {\n $conn.print: \"Name already taken, choose another one: \";\n }\n else {\n $name = $message;\n %connections{$name} = $conn;\n broadcast \"+++ %s arrived +++\", $name;\n }\n }\n else {\n broadcast \"%s> %s\", $name, $message;\n }\n LAST {\n broadcast \"--- %s left ---\", $name;\n %connections{$name}:delete;\n $conn.close ;\n }\n QUIT {\n default {\n say \"oh no, $_\";\n }\n }\n }\n }\n\n sub broadcast ($format, $from, *@message) {\n my $text = sprintf $format, $from, |@message;\n say $text;\n for %connections.kv -> $name, $conn {\n $conn.print: \"$text\\n\" if $name ne $from;\n }\n }\n}\n", "language": "Raku" }, { "code": "require 'gserver'\n\nclass ChatServer < GServer\n def initialize *args\n super\n\n #Keep a list for broadcasting messages\n @chatters = []\n\n #We'll need this for thread safety\n @mutex = Mutex.new\n end\n\n #Send message out to everyone but sender\n def broadcast message, sender = nil\n #Need to use \\r\\n for our Windows friends\n message = message.strip << \"\\r\\n\"\n\n #Mutex for safety - GServer uses threads\n @mutex.synchronize do\n @chatters.each do |chatter|\n begin\n chatter.print message unless chatter == sender\n rescue\n @chatters.delete chatter\n end\n end\n end\n end\n\n #Handle each connection\n def serve io\n io.print 'Name: '\n name = io.gets\n\n #They might disconnect\n return if name.nil?\n\n name.strip!\n\n broadcast \"--+ #{name} has joined +--\"\n\n #Add to our list of connections\n @mutex.synchronize do\n @chatters << io\n end\n\n #Get and broadcast input until connection returns nil\n loop do\n message = io.gets\n\n if message\n broadcast \"#{name}> #{message}\", io\n else\n break\n end\n end\n\n broadcast \"--+ #{name} has left +--\"\n end\nend\n\n#Start up the server on port 7000\n#Accept connections for any IP address\n#Allow up to 100 connections\n#Send information to stderr\n#Turn on informational messages\nChatServer.new(7000, '0.0.0.0', 100, $stderr, true).start.join\n", "language": "Ruby" }, { "code": "use std::collections::HashMap;\nuse std::io;\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::net::{TcpListener, TcpStream};\nuse std::sync::{Arc, RwLock};\nuse std::thread;\n\ntype Username = String;\n\n/// Sends a message to all clients except the sending client.\nfn broadcast_message(\n user: &str,\n clients: &mut HashMap<String, TcpStream>,\n message: &str,\n) -> io::Result<()> {\n for (client, stream) in clients.iter_mut() {\n if client != user {\n writeln!(stream, \"{}\", message)?;\n }\n }\n\n Ok(())\n}\n\nfn chat_loop(listener: &TcpListener) -> io::Result<()> {\n let local_clients: Arc<RwLock<HashMap<Username, TcpStream>>> =\n Arc::new(RwLock::new(HashMap::new()));\n\n println!(\"Accepting connections on {}\", listener.local_addr()?.port());\n\n for stream in listener.incoming() {\n match stream {\n Ok(stream) => {\n let client_clients = Arc::clone(&local_clients);\n thread::spawn(move || -> io::Result<()> {\n let mut reader = BufReader::new(stream.try_clone()?);\n let mut writer = stream;\n\n let mut name = String::new();\n loop {\n write!(writer, \"Please enter a username: \")?;\n reader.read_line(&mut name)?;\n name = name.trim().to_owned();\n\n let clients = client_clients.read().unwrap();\n if !clients.contains_key(&name) {\n writeln!(writer, \"Welcome, {}!\", &name)?;\n break;\n }\n\n writeln!(writer, \"That username is taken.\")?;\n name.clear();\n }\n\n {\n let mut clients = client_clients.write().unwrap();\n clients.insert(name.clone(), writer);\n broadcast_message(\n &name,\n &mut *clients,\n &format!(\"{} has joined the chat room.\", &name),\n )?;\n }\n\n for line in reader.lines() {\n let mut clients = client_clients.write().unwrap();\n broadcast_message(&name, &mut *clients, &format!(\"{}: {}\", &name, line?))?;\n }\n\n {\n let mut clients = client_clients.write().unwrap();\n clients.remove(&name);\n broadcast_message(\n &name,\n &mut *clients,\n &format!(\"{} has left the chat room.\", &name),\n )?;\n }\n\n Ok(())\n });\n }\n Err(e) => {\n println!(\"Connection failed: {}\", e);\n }\n }\n }\n\n Ok(())\n}\n\nfn main() {\n let listener = TcpListener::bind((\"localhost\", 7000)).unwrap();\n chat_loop(&listener).unwrap();\n}\n", "language": "Rust" }, { "code": "package require Tcl 8.6\n\n# Write a message to everyone except the sender of the message\nproc writeEveryoneElse {sender message} {\n dict for {who ch} $::cmap {\n\tif {$who ne $sender} {\n\t puts $ch $message\n\t}\n }\n}\n\n# How to read a line (up to 256 chars long) in a coroutine\nproc cgets {ch var} {\n upvar 1 $var v\n while {[gets $ch v] < 0} {\n\tif {[eof $ch] || [chan pending input $ch] > 256} {\n\t return false\n\t}\n\tyield\n }\n return true\n}\n\n# The chatting, as seen by one user\nproc chat {ch addr port} {\n ### CONNECTION CODE ###\n #Log \"connection from ${addr}:${port} on channel $ch\"\n fconfigure $ch -buffering none -blocking 0 -encoding utf-8\n fileevent $ch readable [info coroutine]\n global cmap\n try {\n\n\t### GET THE NICKNAME OF THE USER ###\n\tputs -nonewline $ch \"Please enter your name: \"\n\tif {![cgets $ch name]} {\n\t return\n\t}\n\t#Log \"Mapping ${addr}:${port} to ${name} on channel $ch\"\n\tdict set cmap $name $ch\n\twriteEveryoneElse $name \"+++ $name arrived +++\"\n\n\t### MAIN CHAT LOOP ###\n\twhile {[cgets $ch line]} {\n\t writeEveryoneElse $name \"$name> $line\"\n\t}\n\n } finally {\n\t### DISCONNECTION CODE ###\n\tif {[info exists name]} {\n\t writeEveryoneElse $name \"--- $name left ---\"\n\t dict unset cmap $name\n\t}\n\tclose $ch\n\t#Log \"disconnection from ${addr}:${port} on channel $ch\"\n }\n}\n\n# Service the socket by making corouines running [chat]\nsocket -server {coroutine c[incr count] chat} 4004\nset ::cmap {};\t\t# Dictionary mapping nicks to channels\nvwait forever;\t\t# Run event loop\n", "language": "Tcl" }, { "code": "Imports System.Net.Sockets\nImports System.Text\nImports System.Threading\n\nModule Module1\n\n Class State\n Private ReadOnly client As TcpClient\n Private ReadOnly sb As New StringBuilder\n\n Public Sub New(name As String, client As TcpClient)\n Me.Name = name\n Me.client = client\n End Sub\n\n Public ReadOnly Property Name As String\n\n Public Sub Send(text As String)\n Dim bytes = Encoding.ASCII.GetBytes(String.Format(\"{0}\" & vbCrLf, text))\n client.GetStream().Write(bytes, 0, bytes.Length)\n End Sub\n End Class\n\n ReadOnly connections As New Dictionary(Of Integer, State)\n Dim listen As TcpListener\n Dim serverThread As Thread\n\n Sub Main()\n listen = New TcpListener(Net.IPAddress.Parse(\"127.0.0.1\"), 4004)\n serverThread = New Thread(New ThreadStart(AddressOf DoListen))\n serverThread.Start()\n End Sub\n\n Private Sub DoListen()\n listen.Start()\n Console.WriteLine(\"Server: Started server\")\n\n Do\n Console.Write(\"Server: Waiting...\")\n Dim client = listen.AcceptTcpClient()\n Console.WriteLine(\" Connected\")\n\n ' New thread with client\n Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))\n\n clientThread.Start(client)\n Loop\n End Sub\n\n Private Sub DoClient(client As TcpClient)\n Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId)\n Dim bytes = Encoding.ASCII.GetBytes(\"Enter name: \")\n client.GetStream().Write(bytes, 0, bytes.Length)\n\n Dim done As Boolean\n Dim name As String\n Do\n If Not client.Connected Then\n Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n client.Close()\n Thread.CurrentThread.Abort() ' Kill thread\n End If\n\n name = Receive(client)\n done = True\n\n For Each cl In connections\n Dim state = cl.Value\n If state.Name = name Then\n bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \")\n client.GetStream().Write(bytes, 0, bytes.Length)\n done = False\n End If\n Next\n Loop While Not done\n\n connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))\n Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n Broadcast(String.Format(\"+++ {0} arrived +++\", name))\n\n Do\n Dim text = Receive(client)\n If text = \"/quit\" Then\n Broadcast(String.Format(\"Connection from {0} closed.\", name))\n connections.Remove(Thread.CurrentThread.ManagedThreadId)\n Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n Exit Do\n End If\n\n If Not client.Connected Then\n Exit Do\n End If\n\n Broadcast(String.Format(\"{0}> {1}\", name, text))\n Loop\n\n Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n client.Close()\n Thread.CurrentThread.Abort()\n End Sub\n\n Private Function Receive(client As TcpClient) As String\n Dim sb As New StringBuilder\n Do\n If client.Available > 0 Then\n While client.Available > 0\n Dim ch = Chr(client.GetStream.ReadByte())\n If ch = vbCr Then\n ' ignore\n Continue While\n End If\n If ch = vbLf Then\n Return sb.ToString()\n End If\n sb.Append(ch)\n End While\n\n ' pause\n Thread.Sleep(100)\n End If\n Loop\n End Function\n\n Private Sub Broadcast(text As String)\n Console.WriteLine(text)\n For Each client In connections\n If client.Key <> Thread.CurrentThread.ManagedThreadId Then\n Dim state = client.Value\n state.Send(text)\n End If\n Next\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "/* Chat_server.wren */\n\nclass Clients {\n foreign static max\n foreign static count\n foreign static isActive(vmi)\n foreign static connfd(vmi)\n foreign static uid(vmi)\n foreign static name(vmi)\n foreign static setName(vmi, s)\n foreign static printAddr(vmi)\n foreign static delete(vmi)\n}\n\nclass Mutex {\n foreign static clientsLock()\n foreign static clientsUnlock()\n\n foreign static topicLock()\n foreign static topicUnlock()\n}\n\nclass Chat {\n // send message to all clients but the sender\n static sendMessage(s, uid) {\n Mutex.clientsLock()\n for (i in 0...Clients.max) {\n if (Clients.isActive(i) && Clients.uid(i) != uid) {\n if (write(Clients.connfd(i), s, s.bytes.count) < 0) {\n System.print(\"Write to descriptor %(Clients.connfd(i)) failed.\")\n break\n }\n }\n }\n Mutex.clientsUnlock()\n }\n\n // send message to all clients\n static sendMessageAll(s) {\n Mutex.clientsLock()\n for (i in 0...Clients.max) {\n if (Clients.isActive(i)) {\n if (write(Clients.connfd(i), s, s.bytes.count) < 0) {\n System.print(\"Write to descriptor %(Clients.connfd(i)) failed.\")\n break\n }\n }\n }\n Mutex.clientsUnlock()\n }\n\n // send message to sender\n static sendMessageSelf(s, connfd) {\n if (write(connfd, s, s.bytes.count) < 0) {\n Fiber.abort(\"Write to descriptor %(connfd) failed.\")\n }\n }\n\n // send message to client\n static sendMessageClient(s, uid) {\n Mutex.clientsLock()\n for (i in 0...Clients.max) {\n if (Clients.isActive(i) && Clients.uid(i) == uid) {\n if (write(Clients.connfd(i), s, s.bytes.count) < 0) {\n System.print(\"Write to descriptor %(Clients.connfd(i)) failed.\")\n break\n }\n }\n }\n Mutex.clientsUnlock()\n }\n\n // send list of active clients\n static sendActiveClients(connfd) {\n Mutex.clientsLock()\n for (i in 0...Clients.max) {\n if (Clients.isActive(i)) {\n var s = \"<< [%(Clients.uid(i))] %(Clients.name(i))\\r\\n\"\n sendMessageSelf(s, connfd)\n }\n }\n Mutex.clientsUnlock()\n }\n\n // handle all communication with the client\n static handleClient(vmi) {\n if (!Clients.isActive(vmi)) {\n Fiber.abort(\"The client handled by VM[%(vmi)] is inactive.\")\n }\n var connfd = Clients.connfd(vmi)\n var uid = Clients.uid(vmi)\n var name = Clients.name(vmi)\n System.write(\"<< accept \")\n Clients.printAddr(vmi)\n System.print(\" referenced by %(uid)\")\n var buffOut = \"<< %(name) has joined\\r\\n\"\n sendMessageAll(buffOut)\n Mutex.topicLock()\n if (topic != \"\") {\n buffOut = \"<< topic: %(topic)\\r\\n\"\n sendMessageSelf(buffOut, connfd)\n }\n Mutex.topicUnlock()\n sendMessageSelf(\"<< see /help for assistance\\r\\n\", connfd)\n\n /* receive input from client */\n var buffIn = \"\"\n while ((buffIn = read(connfd, bufferSize/2 - 1)) && buffIn.bytes.count > 0) {\n buffOut = \"\"\n buffIn = buffIn.trimEnd(\"\\r\\n\")\n\n /* ignore empty buffer */\n if (buffIn == \"\") continue\n\n /* special options */\n if (buffIn[0] == \"/\") {\n var split = buffIn.split(\" \")\n var command = split[0]\n if (command == \"/quit\") {\n break\n } else if (command == \"/ping\") {\n sendMessageSelf(\"<< pong\\r\\n\", connfd)\n } else if (command == \"/topic\") {\n if (split.count > 0) {\n Mutex.topicLock()\n topic = split[1..-1].join(\" \")\n Mutex.topicUnlock()\n buffOut = \"<< topic changed to: %(topic)\\r\\n\"\n sendMessageAll(buffOut)\n } else {\n sendMessageSelf(\"<< message cannot be null\\r\\n\", connfd)\n }\n } else if (command == \"/nick\") {\n if (split.count > 0) {\n var newName = split[1..-1].join(\" \")\n buffOut = \"<< %(name) is now known as %(newName)\\r\\n\"\n Clients.setName(vmi, newName)\n name = newName\n sendMessageAll(buffOut)\n } else {\n sendMessageSelf(\"<< name cannot be null\\r\\n\", connfd)\n }\n } else if (command == \"/msg\") {\n if (split.count > 0) {\n var toUid = Num.fromString(split[1])\n if (split.count > 1) {\n buffOut = \"[PM][%(name)] \"\n buffOut = buffOut + split[2..-1].join(\" \") + \"\\r\\n\"\n sendMessageClient(buffOut, toUid)\n } else {\n sendMessageSelf(\"<< message cannot be null\\r\\n\", connfd)\n }\n } else {\n sendMessageSelf(\"<< reference cannot be null\\r\\n\", connfd)\n }\n } else if (command == \"/list\") {\n buffOut = \"<< clients %(Clients.count)\\r\\n\"\n sendMessageSelf(buffOut, connfd)\n sendActiveClients(connfd)\n } else if (command == \"/help\") {\n buffOut = \"\"\n buffOut = buffOut + \"<< /quit Quit chatroom\\r\\n\"\n buffOut = buffOut + \"<< /ping Server test\\r\\n\"\n buffOut = buffOut + \"<< /topic <message> Set chat topic\\r\\n\"\n buffOut = buffOut + \"<< /nick <name> Change nickname\\r\\n\"\n buffOut = buffOut + \"<< /msg <reference> <message> Send private message\\r\\n\"\n buffOut = buffOut + \"<< /list Show active clients\\r\\n\"\n buffOut = buffOut + \"<< /help Show help\\r\\n\"\n sendMessageSelf(buffOut, connfd)\n } else {\n sendMessageSelf(\"<< unknown command\\r\\n\", connfd)\n }\n } else {\n /* send message */\n buffOut = \"[%(name)] %(buffIn)\\r\\n\"\n sendMessage(buffOut, uid)\n }\n }\n\n /* close connection */\n buffOut = \"<< [%(name)] has left\\r\\n\"\n sendMessageAll(buffOut)\n close(connfd)\n\n /* delete client from queue and yield thread (from C side) */\n System.write(\"<< quit \")\n Clients.printAddr(vmi)\n System.print(\" referenced by %(uid)\")\n Clients.delete(vmi)\n }\n\n foreign static topic\n foreign static topic=(s)\n\n foreign static bufferSize\n foreign static write(connfd, buf, count)\n foreign static read(connfd, count)\n foreign static close(connfd)\n}\n", "language": "Wren" }, { "code": "/* gcc Chat_server.c -o Chat_server -lpthread -lwren -lm */\n\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <errno.h>\n#include <string.h>\n#include <pthread.h>\n#include <sys/types.h>\n#include <signal.h>\n#include <wren.h>\n\n#define MAX_CLIENTS 10\n#define BUFFER_SZ 2048\n\nstatic _Atomic unsigned int cli_count = 0;\nstatic int listenfd = 0, uid = 10;\nchar *script = NULL;\n\n/* Client structure */\ntypedef struct {\n struct sockaddr_in addr; /* Client remote address */\n int connfd; /* Connection file descriptor */\n int uid; /* Client unique identifier */\n int vmi; /* The index of the VM which handles this client */\n char name[32]; /* Client name */\n} client_t;\n\nclient_t *clients[MAX_CLIENTS];\n\npthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER;\n\nstatic char topic[BUFFER_SZ/2];\n\npthread_mutex_t topic_mutex = PTHREAD_MUTEX_INITIALIZER;\n\nWrenVM* vms[MAX_CLIENTS]; // array of VMs\n\n/* add client to queue */\nvoid queue_add(client_t *cl){\n pthread_mutex_lock(&clients_mutex);\n for (int i = 0; i < MAX_CLIENTS; ++i) {\n if (!clients[i]) {\n cl->vmi = i;\n clients[i] = cl;\n break;\n }\n }\n pthread_mutex_unlock(&clients_mutex);\n}\n\n/* Delete client from queue */\nvoid queue_delete(int uid){\n pthread_mutex_lock(&clients_mutex);\n for (int i = 0; i < MAX_CLIENTS; ++i) {\n if (clients[i]) {\n if (clients[i]->uid == uid) {\n clients[i] = NULL;\n break;\n }\n }\n }\n pthread_mutex_unlock(&clients_mutex);\n}\n\n/* print ip address */\nvoid print_client_addr(struct sockaddr_in addr){\n printf(\"%d.%d.%d.%d\",\n addr.sin_addr.s_addr & 0xff,\n (addr.sin_addr.s_addr & 0xff00) >> 8,\n (addr.sin_addr.s_addr & 0xff0000) >> 16,\n (addr.sin_addr.s_addr & 0xff000000) >> 24);\n}\n\n/* enable Wren to handle all client communication */\nvoid *handle_client(void *arg) {\n client_t *cli = (client_t *)arg;\n cli_count++;\n int vmi = cli->vmi;\n WrenHandle *callHandle = wrenMakeCallHandle(vms[vmi], \"handleClient(_)\");\n wrenEnsureSlots(vms[vmi], 2);\n wrenGetVariable(vms[vmi], \"main\", \"Chat\", 0);\n wrenSetSlotDouble(vms[vmi], 1, (double)vmi);\n wrenCall(vms[vmi], callHandle);\n}\n\n/* C <= Wren interface functions */\n\nvoid C_max(WrenVM* vm) {\n wrenSetSlotDouble(vm, 0, (double)MAX_CLIENTS);\n}\n\nvoid C_count(WrenVM* vm) {\n wrenSetSlotDouble(vm, 0, (double)cli_count);\n}\n\nvoid C_isActive(WrenVM* vm) {\n int vmi = (int)wrenGetSlotDouble(vm, 1);\n bool res = clients[vmi] != NULL;\n wrenSetSlotBool(vm, 0, res);\n}\n\nvoid C_connfd(WrenVM* vm) {\n int vmi = (int)wrenGetSlotDouble(vm, 1);\n wrenSetSlotDouble(vm, 0, (double)clients[vmi]->connfd);\n}\n\nvoid C_uid(WrenVM* vm) {\n int vmi = (int)wrenGetSlotDouble(vm, 1);\n wrenSetSlotDouble(vm, 0, (double)clients[vmi]->uid);\n}\n\nvoid C_name(WrenVM* vm) {\n int vmi = (int)wrenGetSlotDouble(vm, 1);\n wrenSetSlotString(vm, 0, (const char *)clients[vmi]->name);\n}\n\nvoid C_setName(WrenVM* vm) {\n int vmi = (int)wrenGetSlotDouble(vm, 1);\n const char *name = wrenGetSlotString(vm, 2);\n size_t size = sizeof(clients[vmi]->name);\n strncpy(clients[vmi]->name, name, size);\n clients[vmi]->name[size-1] = '\\0';\n}\n\nvoid C_clientsLock(WrenVM* vm) {\n pthread_mutex_lock(&clients_mutex);\n}\n\nvoid C_clientsUnlock(WrenVM* vm) {\n pthread_mutex_unlock(&clients_mutex);\n}\n\nvoid C_topicLock(WrenVM* vm) {\n pthread_mutex_lock(&topic_mutex);\n}\n\nvoid C_topicUnlock(WrenVM* vm) {\n pthread_mutex_unlock(&topic_mutex);\n}\n\nvoid C_printAddr(WrenVM* vm) {\n int vmi = (int)wrenGetSlotDouble(vm, 1);\n print_client_addr(clients[vmi]->addr);\n}\n\nvoid C_topic(WrenVM* vm) {\n wrenSetSlotString(vm, 0, (const char *)topic);\n}\n\nvoid C_setTopic(WrenVM* vm) {\n const char *t = wrenGetSlotString(vm, 1);\n strncpy(topic, t, sizeof(topic));\n topic[sizeof(topic)-1] = '\\0';\n}\n\nvoid C_bufferSize(WrenVM* vm) {\n wrenSetSlotDouble(vm, 0, (double)BUFFER_SZ);\n}\n\nvoid C_write(WrenVM* vm) {\n int fd = (int)wrenGetSlotDouble(vm, 1);\n const void *buf = (const void *)wrenGetSlotString(vm, 2);\n size_t count = (size_t)wrenGetSlotDouble(vm, 3);\n ssize_t res = write(fd, buf, count);\n wrenSetSlotDouble(vm, 0, (double)res);\n}\n\nvoid C_read(WrenVM* vm) {\n char buf[BUFFER_SZ / 2];\n int fd = (int)wrenGetSlotDouble(vm, 1);\n size_t count = (size_t)wrenGetSlotDouble(vm, 2);\n ssize_t rlen = read(fd, buf, count);\n buf[rlen] = '\\0';\n wrenSetSlotString(vm, 0, (const char *)buf);\n}\n\nvoid C_close(WrenVM* vm) {\n int connfd = (int)wrenGetSlotDouble(vm, 1);\n close(connfd);\n}\n\nvoid C_delete(WrenVM* vm) {\n int vmi = (int)wrenGetSlotDouble(vm, 1);\n client_t *cli = clients[vmi];\n queue_delete(cli->uid);\n free(cli);\n cli_count--;\n pthread_detach(pthread_self());\n}\n\nWrenForeignMethodFn bindForeignMethod(\n WrenVM* vm,\n const char* module,\n const char* className,\n bool isStatic,\n const char* signature) {\n if (strcmp(module, \"main\") == 0) {\n if (strcmp(className, \"Clients\") == 0) {\n if (isStatic && strcmp(signature, \"max\") == 0) return C_max;\n if (isStatic && strcmp(signature, \"count\") == 0) return C_count;\n if (isStatic && strcmp(signature, \"isActive(_)\") == 0) return C_isActive;\n if (isStatic && strcmp(signature, \"connfd(_)\") == 0) return C_connfd;\n if (isStatic && strcmp(signature, \"uid(_)\") == 0) return C_uid;\n if (isStatic && strcmp(signature, \"name(_)\") == 0) return C_name;\n if (isStatic && strcmp(signature, \"setName(_,_)\") == 0) return C_setName;\n if (isStatic && strcmp(signature, \"printAddr(_)\") == 0) return C_printAddr;\n if (isStatic && strcmp(signature, \"delete(_)\") == 0) return C_delete;\n } else if (strcmp(className, \"Mutex\") == 0) {\n if (isStatic && strcmp(signature, \"clientsLock()\") == 0) return C_clientsLock;\n if (isStatic && strcmp(signature, \"clientsUnlock()\") == 0) return C_clientsUnlock;\n if (isStatic && strcmp(signature, \"topicLock()\") == 0) return C_topicLock;\n if (isStatic && strcmp(signature, \"topicUnlock()\") == 0) return C_topicUnlock;\n } else if (strcmp(className, \"Chat\") == 0) {\n if (isStatic && strcmp(signature, \"topic\") == 0) return C_topic;\n if (isStatic && strcmp(signature, \"topic=(_)\") == 0) return C_setTopic;\n if (isStatic && strcmp(signature, \"bufferSize\") == 0) return C_bufferSize;\n if (isStatic && strcmp(signature, \"write(_,_,_)\") == 0) return C_write;\n if (isStatic && strcmp(signature, \"read(_,_)\") == 0) return C_read;\n if (isStatic && strcmp(signature, \"close(_)\") == 0) return C_close;\n }\n }\n return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n switch (errorType) {\n case WREN_ERROR_COMPILE:\n printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_STACK_TRACE:\n printf(\"[%s line %d] in %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_RUNTIME:\n printf(\"[Runtime Error] %s\\n\", msg);\n break;\n }\n}\n\nchar *readFile(const char *fileName) {\n FILE *f = fopen(fileName, \"r\");\n fseek(f, 0, SEEK_END);\n long fsize = ftell(f);\n rewind(f);\n char *script = malloc(fsize + 1);\n fread(script, 1, fsize, f);\n fclose(f);\n script[fsize] = 0;\n return script;\n}\n\nvoid catch_ctrl_c(int sig) {\n /* clean up and exit */\n for (int i = 0; i < MAX_CLIENTS; ++i) {\n wrenFreeVM(vms[i]);\n if (clients[i]) {\n close(clients[i]->connfd);\n free(clients[i]);\n }\n }\n close(listenfd);\n free(script);\n printf(\"\\n<[ SERVER ENDED ]>\\n\");\n exit(EXIT_SUCCESS);\n}\n\nint main(int argc, char **argv) {\n WrenConfiguration config;\n wrenInitConfiguration(&config);\n config.writeFn = &writeFn;\n config.errorFn = &errorFn;\n config.bindForeignMethodFn = &bindForeignMethod;\n const char* module = \"main\";\n const char* fileName = \"Chat_server.wren\";\n script = readFile(fileName);\n\n /* config the VMs and interpret the script */\n for (int i = 0; i < MAX_CLIENTS; ++i) {\n vms[i] = wrenNewVM(&config);\n wrenInterpret(vms[i], module, script);\n }\n\n /* prepare to start the server */\n int connfd = 0;\n struct sockaddr_in serv_addr;\n struct sockaddr_in cli_addr;\n pthread_t tid;\n\n /* socket settings */\n listenfd = socket(AF_INET, SOCK_STREAM, 0);\n serv_addr.sin_family = AF_INET;\n serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);\n serv_addr.sin_port = htons(5000);\n\n /* ignore pipe signals */\n signal(SIGPIPE, SIG_IGN);\n\n /* catch ctrl-c being pressed */\n signal(SIGINT, catch_ctrl_c);\n\n /* bind */\n if (bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {\n perror(\"Socket binding failed\");\n return EXIT_FAILURE;\n }\n\n /* listen */\n if (listen(listenfd, 10) < 0) {\n perror(\"Socket listening failed\");\n return EXIT_FAILURE;\n }\n\n printf(\"<[ SERVER STARTED ]>\\n\");\n\n /* accept clients */\n while (1) {\n socklen_t clilen = sizeof(cli_addr);\n connfd = accept(listenfd, (struct sockaddr*)&cli_addr, &clilen);\n\n /* check if max clients is reached */\n if ((cli_count + 1) == MAX_CLIENTS) {\n printf(\"<< max clients reached\\n\");\n printf(\"<< reject \");\n print_client_addr(cli_addr);\n printf(\"\\n\");\n close(connfd);\n continue;\n }\n\n /* client settings */\n client_t *cli = (client_t *)malloc(sizeof(client_t));\n cli->addr = cli_addr;\n cli->connfd = connfd;\n cli->uid = uid++;\n sprintf(cli->name, \"%d\", cli->uid);\n\n /* add client to the queue and fork thread */\n queue_add(cli);\n pthread_create(&tid, NULL, &handle_client, (void*)cli);\n\n /* reduce CPU usage */\n sleep(1);\n }\n\n return 0;\n}\n", "language": "Wren" }, { "code": "const PORT=23;\n\nvar users=Dictionary(); // ( handle:socket, ...)\npipe:=Thread.Pipe(); // how server tells thread to connect to user\n\nfcn accept(pipe){ // a thread waiting for the server to send a socket\n while(socket:=pipe.read()){\n println(\"Somebody is connecting ...\");\n socket.read(); // telnet stuff\n while(True){ // get credentials\n\t reg name;\n\t socket.write(\"Your handle: \"); // bottle neck\n\t try{ name = socket.read().text.strip() } catch(IOError){ continue }\n\t if(users.holds(name)) socket.write(\"Handle is already in use.\\n\");\n\t else if(name){\n\t users[name] = socket;\n\t chat.launch(name,socket);\t// thread\n\t broadcast(name, \"+++ %s arrived +++\".fmt(name));\n\t break;\t// wait for next connection\n\t }\n }//while\n }//while\n}.launch(pipe); // thread\n\nfcn chat(name,socket){\t\t// a thread, one per user\n try{\n socket.write(\"^D to disconnect\\n\");\n while(True){\n\t message:=socket.read().text.strip();\n\t if(message==\"\\xff\\xec\") break; // ^D to disconnect.\n\t broadcast(name, \"%s> %s\".fmt(name,message));\n }\n }catch{} // eg socket pukes\n users.del(name); socket.close();\n broadcast(name, \"--- %s leaves ---\".fmt(name));\n}\n\n // Send a message to all users from the given name.\nfcn broadcast(name, message){ // called from user thread\n println(message); // log message to server console\n users.pump(Void,'wrap([(toName,socket)]){\n if(toName != name) try{ socket.write(message + \"\\n\") } catch(IOError){}\n });\n}\n\n // Set up the server socket.\nserver:=Network.TCPServerSocket.open(PORT);\nprintln(\"Listening on %s:%s\".fmt(server.hostname,server.port));\nserver.listen(pipe); // Main event loop\n", "language": "Zkl" } ]
Chat-server
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Check_Machin-like_formulas\n", "language": "00-META" }, { "code": "[[wp:Machin-like_formula|Machin-like formulas]] &nbsp; are useful for efficiently computing numerical approximations for <big><big><math>\\pi</math></big></big>\n\n\n;Task:\nVerify the following Machin-like formulas are correct by calculating the value of '''tan''' &nbsp; (''right hand side)'' for each equation using exact arithmetic and showing they equal '''1''':\n\n: <math>{\\pi\\over4} = \\arctan{1\\over2} + \\arctan{1\\over3}</math> \n: <math>{\\pi\\over4} = 2 \\arctan{1\\over3} + \\arctan{1\\over7}</math>\n: <math>{\\pi\\over4} = 4 \\arctan{1\\over5} - \\arctan{1\\over239}</math>\n: <math>{\\pi\\over4} = 5 \\arctan{1\\over7} + 2 \\arctan{3\\over79}</math>\n: <math>{\\pi\\over4} = 5 \\arctan{29\\over278} + 7 \\arctan{3\\over79}</math>\n: <math>{\\pi\\over4} = \\arctan{1\\over2} + \\arctan{1\\over5} + \\arctan{1\\over8}</math> \n: <math>{\\pi\\over4} = 4 \\arctan{1\\over5} - \\arctan{1\\over70} + \\arctan{1\\over99}</math> \n: <math>{\\pi\\over4} = 5 \\arctan{1\\over7} + 4 \\arctan{1\\over53} + 2 \\arctan{1\\over4443}</math>\n: <math>{\\pi\\over4} = 6 \\arctan{1\\over8} + 2 \\arctan{1\\over57} + \\arctan{1\\over239}</math>\n: <math>{\\pi\\over4} = 8 \\arctan{1\\over10} - \\arctan{1\\over239} - 4 \\arctan{1\\over515}</math>\n: <math>{\\pi\\over4} = 12 \\arctan{1\\over18} + 8 \\arctan{1\\over57} - 5 \\arctan{1\\over239}</math>\n: <math>{\\pi\\over4} = 16 \\arctan{1\\over21} + 3 \\arctan{1\\over239} + 4 \\arctan{3\\over1042}</math>\n: <math>{\\pi\\over4} = 22 \\arctan{1\\over28} + 2 \\arctan{1\\over443} - 5 \\arctan{1\\over1393} - 10 \\arctan{1\\over11018}</math>\n: <math>{\\pi\\over4} = 22 \\arctan{1\\over38} + 17 \\arctan{7\\over601} + 10 \\arctan{7\\over8149}</math>\n: <math>{\\pi\\over4} = 44 \\arctan{1\\over57} + 7 \\arctan{1\\over239} - 12 \\arctan{1\\over682} + 24 \\arctan{1\\over12943}</math>\n: <math>{\\pi\\over4} = 88 \\arctan{1\\over172} + 51 \\arctan{1\\over239} + 32 \\arctan{1\\over682} + 44 \\arctan{1\\over5357} + 68 \\arctan{1\\over12943}</math>\n\nand confirm that the following formula is ''incorrect'' by showing &nbsp; '''tan''' &nbsp; (''right hand side)'' &nbsp; is ''not'' &nbsp; '''1''':\n\n: <math>{\\pi\\over4} = 88 \\arctan{1\\over172} + 51 \\arctan{1\\over239} + 32 \\arctan{1\\over682} + 44 \\arctan{1\\over5357} + 68 \\arctan{1\\over12944}</math>\n\nThese identities are useful in calculating the values:\n: <math>\\tan(a + b) = {\\tan(a) + \\tan(b) \\over 1 - \\tan(a) \\tan(b)}</math>\n\n: <math>\\tan\\left(\\arctan{a \\over b}\\right) = {a \\over b}</math>\n\n: <math>\\tan(-a) = -\\tan(a)</math>\n\n<br>\nYou can store the equations in any convenient data structure, but for extra credit parse them from human-readable [[Check_Machin-like_formulas/text_equations|text input]].\n\nNote: to formally prove the formula correct, it would have to be shown that ''<math>{-3 pi \\over 4}</math> < right hand side < <math>{5 pi \\over 4}</math>'' due to ''<math>\\tan()</math>'' periodicity.\n\n<br><br>\n\n", "language": "00-TASK" }, { "code": "(ns tanevaulator\n (:gen-class))\n\n;; Notation: [a b c] -> a x arctan(a/b)\n(def test-cases [\n [[1, 1, 2], [1, 1, 3]],\n [[2, 1, 3], [1, 1, 7]],\n [[4, 1, 5], [-1, 1, 239]],\n [[5, 1, 7], [2, 3, 79]],\n [[1, 1, 2], [1, 1, 5], [1, 1, 8]],\n [[4, 1, 5], [-1, 1, 70], [1, 1, 99]],\n [[5, 1, 7], [4, 1, 53], [2, 1, 4443]],\n [[6, 1, 8], [2, 1, 57], [1, 1, 239]],\n [[8, 1, 10], [-1, 1, 239], [-4, 1, 515]],\n [[12, 1, 18], [8, 1, 57], [-5, 1, 239]],\n [[16, 1, 21], [3, 1, 239], [4, 3, 1042]],\n [[22, 1, 28], [2, 1, 443], [-5, 1, 1393], [-10, 1, 11018]],\n [[22, 1, 38], [17, 7, 601], [10, 7, 8149]],\n [[44, 1, 57], [7, 1, 239], [-12, 1, 682], [24, 1, 12943]],\n [[88, 1, 172], [51, 1, 239], [32, 1, 682], [44, 1, 5357], [68, 1, 12943]],\n [[88, 1, 172], [51, 1, 239], [32, 1, 682], [44, 1, 5357], [68, 1, 12944]]\n ])\n\n(defn tan-sum [a b]\n \" tan (a + b) \"\n (/ (+ a b) (- 1 (* a b))))\n\n(defn tan-eval [m]\n \" Evaluates tan of a triplet (e.g. [1, 1, 2])\"\n (let [coef (first m)\n rat (/ (nth m 1) (nth m 2))]\n (cond\n (= 1 coef) rat\n (neg? coef) (tan-eval [(- (nth m 0)) (- (nth m 1)) (nth m 2)])\n :else (let [\n ca (quot coef 2)\n cb (- coef ca)\n a (tan-eval [ca (nth m 1) (nth m 2)])\n b (tan-eval [cb (nth m 1) (nth m 2)])]\n (tan-sum a b)))))\n\n(defn tans [m]\n \" Evaluates tan of set of triplets (e.g. [[1, 1, 2], [1, 1, 3]])\"\n (if (= 1 (count m))\n (tan-eval (nth m 0))\n (let [a (tan-eval (first m))\n b (tans (rest m))]\n (tan-sum a b))))\n\n(doseq [q test-cases]\n \" Display results \"\n (println \"tan \" q \" = \"(tans q)))\n", "language": "Clojure" }, { "code": "import std.stdio, std.regex, std.conv, std.string, std.range,\n arithmetic_rational;\n\nstruct Pair { int x; Rational r; }\n\nPair[][] parseEquations(in string text) /*pure nothrow*/ {\n auto r = regex(r\"\\s*(?P<sign>[+-])?\\s*(?:(?P<mul>\\d+)\\s*\\*)?\\s*\" ~\n r\"arctan\\((?P<num>\\d+)/(?P<denom>\\d+)\\)\");\n Pair[][] machins;\n foreach (const line; text.splitLines) {\n Pair[] formula;\n foreach (part; line.split(\"=\")[1].matchAll(r)) {\n immutable mul = part[\"mul\"],\n num = part[\"num\"],\n denom = part[\"denom\"];\n formula ~= Pair((part[\"sign\"] == \"-\" ? -1 : 1) *\n (mul.empty ? 1 : mul.to!int),\n Rational(num.to!int,\n denom.empty ? 1 : denom.to!int));\n }\n machins ~= formula;\n }\n return machins;\n}\n\n\nRational tans(in Pair[] xs) pure nothrow {\n static Rational tanEval(in int coef, in Rational f)\n pure nothrow {\n if (coef == 1)\n return f;\n if (coef < 0)\n return -tanEval(-coef, f);\n immutable a = tanEval(coef / 2, f),\n b = tanEval(coef - coef / 2, f);\n return (a + b) / (1 - a * b);\n }\n\n if (xs.length == 1)\n return tanEval(xs[0].tupleof);\n immutable a = xs[0 .. $ / 2].tans,\n b = xs[$ / 2 .. $].tans;\n return (a + b) / (1 - a * b);\n}\n\nvoid main() {\n immutable equationText =\n\"pi/4 = arctan(1/2) + arctan(1/3)\npi/4 = 2*arctan(1/3) + arctan(1/7)\npi/4 = 4*arctan(1/5) - arctan(1/239)\npi/4 = 5*arctan(1/7) + 2*arctan(3/79)\npi/4 = 5*arctan(29/278) + 7*arctan(3/79)\npi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)\npi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)\npi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)\npi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)\npi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)\npi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)\npi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)\npi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)\npi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)\npi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)\npi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)\npi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)\";\n\n const machins = equationText.parseEquations;\n foreach (const machin, const eqn; machins.zip(equationText.splitLines)) {\n immutable ans = machin.tans;\n writefln(\"%5s: %s\", ans == 1 ? \"OK\" : \"ERROR\", eqn);\n }\n}\n", "language": "D" }, { "code": "(lib 'math)\n(lib 'match)\n(math-precision 1.e-10)\n\n;; formally derive (tan ..) expressions\n;; copied from Racket\n;; adapted and improved for performance\n\n(define (reduce e)\n;; (set! rcount (1+ rcount)) ;; # of calls\n (match e\n [(? number? a) a]\n [('+ (? number? a) (? number? b)) (+ a b)]\n [('- (? number? a) (? number? b)) (- a b)]\n [('- (? number? a)) (- a)]\n [('* (? number? a) (? number? b)) (* a b)]\n [('/ (? number? a) (? number? b)) (/ a b)] ; patch\n\n [( '+ a b) (reduce `(+ ,(reduce a) ,(reduce b)))]\n [( '- a b) (reduce `(- ,(reduce a) ,(reduce b)))]\n [( '- a) (reduce `(- ,(reduce a)))]\n [( '* a b) (reduce `(* ,(reduce a) ,(reduce b)))]\n [( '/ a b) (reduce `(/ ,(reduce a) ,(reduce b)))]\n\n [( 'tan ('arctan a)) (reduce a)]\n [( 'tan ( '- a)) (reduce `(- (tan ,a)))]\n\n ;; x 100 # calls reduction : derive (tan ,a) only once\n [( 'tan ( '+ a b))\n (let ((alpha (reduce `(tan ,a))) (beta (reduce `(tan ,b))))\n \t (reduce `(/ (+ ,alpha ,beta) (- 1 (* ,alpha ,beta)))))]\n\n [( 'tan ( '+ a b c ...)) (reduce `(tan (+ ,a (+ ,b ,@c))))]\n\n [( 'tan ( '- a b))\n (let ((alpha (reduce `(tan ,a))) (beta (reduce `(tan ,b))))\n \t\t(reduce `(/ (- ,alpha ,beta) (+ 1 (* ,alpha ,beta)))))]\n\n ;; add formula for (tan 2 (arctan a)) = 2 a / (1 - a^2))\n [( 'tan ( '* 2 ('arctan a))) (reduce `(/ (* 2 ,a) (- 1 (* ,a ,a))))]\n [( 'tan ( '* 1 ('arctan a))) (reduce a)] ; added\n\n [( 'tan ( '* (? number? n) a))\n (cond [(< n 0) (reduce `(- (tan (* ,(- n) ,a))))]\n [(= n 0) 0]\n [(= n 1) (reduce `(tan ,a))]\n [(even? n)\n (let ((alpha (reduce `(tan (* ,(/ n 2) ,a))))) ;; # calls reduction\n \t (reduce `(/ (* 2 ,alpha) (- 1 (* ,alpha ,alpha)))))]\n [else (reduce `(tan (+ ,a (* ,(- n 1) ,a))))])]\n ))\n\n(define (task)\n\t(for ((f machins))\n\t(if (~= 1 (reduce f))\n\t\t(writeln '👍 f '⟾ 1 )\n\t\t(writeln '❌ f '➽ (reduce f) ))))\n\t\n", "language": "EchoLisp" }, { "code": "(define machins\n '((tan (+ (arctan 1/2) (arctan 1/3)))\n (tan (+ (* 2 (arctan 1/3)) (arctan 1/7)))\n (tan (- (* 4 (arctan 1/5)) (arctan 1/239)))\n (tan (+ (* 5 (arctan 1/7)) (* 2 (arctan 3/79))))\n (tan (+ (* 5 (arctan 29/278)) (* 7 (arctan 3/79))))\n (tan (+ (arctan 1/2) (arctan 1/5) (arctan 1/8)))\n (tan (+ (* 4 (arctan 1/5)) (* -1 (arctan 1/70)) (arctan 1/99)))\n (tan (+ (* 5 (arctan 1/7)) (* 4 (arctan 1/53)) (* 2 (arctan 1/4443))))\n (tan (+ (* 6 (arctan 1/8)) (* 2 (arctan 1/57)) (arctan 1/239)))\n (tan (+ (* 8 (arctan 1/10)) (* -1 (arctan 1/239)) (* -4 (arctan 1/515))))\n (tan (+ (* 12 (arctan 1/18)) (* 8 (arctan 1/57)) (* -5 (arctan 1/239))))\n (tan (+ (* 16 (arctan 1/21)) (* 3 (arctan 1/239)) (* 4 (arctan 3/1042))))\n (tan (+ (* 22 (arctan 1/28)) (* 2 (arctan 1/443)) (* -5 (arctan 1/1393)) (* -10 (arctan 1/11018))))\n (tan (+ (* 22 (arctan 1/38)) (* 17 (arctan 7/601)) (* 10 (arctan 7/8149))))\n (tan (+ (* 44 (arctan 1/57)) (* 7 (arctan 1/239)) (* -12 (arctan 1/682)) (* 24 (arctan 1/12943))))\n (tan (+ (* 88 (arctan 1/172)) (* 51 (arctan 1/239)) (* 32 (arctan 1/682))\n (* 44 (arctan 1/5357)) (* 68 (arctan 1/12943))))\n (tan (+ (* 88 (arctan 1/172)) (* 51 (arctan 1/239)) (* 32 (arctan 1/682))\n (* 44 (arctan 1/5357)) (* 68 (arctan 1/12944))))))\n\n(task)\n\n👍 (tan (+ (arctan 1/2) (arctan 1/3))) ⟾ 1\n👍 (tan (+ (* 2 (arctan 1/3)) (arctan 1/7))) ⟾ 1\n👍 (tan (- (* 4 (arctan 1/5)) (arctan 1/239))) ⟾ 1\n👍 (tan (+ (* 5 (arctan 1/7)) (* 2 (arctan 3/79)))) ⟾ 1\n👍 (tan (+ (* 5 (arctan 29/278)) (* 7 (arctan 3/79)))) ⟾ 1\n👍 (tan (+ (arctan 1/2) (arctan 1/5) (arctan 1/8))) ⟾ 1\n👍 (tan (+ (* 4 (arctan 1/5)) (* -1 (arctan 1/70)) (arctan 1/99))) ⟾ 1\n👍 (tan (+ (* 5 (arctan 1/7)) (* 4 (arctan 1/53)) (* 2 (arctan 1/4443)))) ⟾ 1\n👍 (tan (+ (* 6 (arctan 1/8)) (* 2 (arctan 1/57)) (arctan 1/239))) ⟾ 1\n👍 (tan (+ (* 8 (arctan 1/10)) (* -1 (arctan 1/239)) (* -4 (arctan 1/515)))) ⟾ 1\n👍 (tan (+ (* 12 (arctan 1/18)) (* 8 (arctan 1/57)) (* -5 (arctan 1/239)))) ⟾ 1\n👍 (tan (+ (* 16 (arctan 1/21)) (* 3 (arctan 1/239)) (* 4 (arctan 3/1042)))) ⟾ 1\n👍 (tan (+ (* 22 (arctan 1/28)) (* 2 (arctan 1/443)) (* -5 (arctan 1/1393)) (* -10 (arctan 1/11018)))) ⟾ 1\n👍 (tan (+ (* 22 (arctan 1/38)) (* 17 (arctan 7/601)) (* 10 (arctan 7/8149)))) ⟾ 1\n👍 (tan (+ (* 44 (arctan 1/57)) (* 7 (arctan 1/239)) (* -12 (arctan 1/682)) (* 24 (arctan 1/12943)))) ⟾ 1\n👍 (tan (+ (* 88 (arctan 1/172)) (* 51 (arctan 1/239)) (* 32 (arctan 1/682))\n (* 44 (arctan 1/5357)) (* 68 (arctan 1/12943)))) ⟾ 1\n❌ (tan (+ (* 88 (arctan 1/172)) (* 51 (arctan 1/239)) (* 32 (arctan 1/682))\n (* 44 (arctan 1/5357)) (* 68 (arctan 1/12944)))) ➽ 0.9999991882257442\n", "language": "EchoLisp" }, { "code": "USING: combinators formatting kernel locals math sequences ;\nIN: rosetta-code.machin\n\n: tan+ ( x y -- z ) [ + ] [ * 1 swap - / ] 2bi ;\n\n:: tan-eval ( coef frac -- x )\n {\n { [ coef zero? ] [ 0 ] }\n { [ coef neg? ] [ coef neg frac tan-eval neg ] }\n { [ coef odd? ] [ frac coef 1 - frac tan-eval tan+ ] }\n [ coef 2/ frac tan-eval dup tan+ ]\n } cond ;\n\n: tans ( seq -- x ) [ first2 tan-eval ] [ tan+ ] map-reduce ;\n\n: machin ( -- )\n {\n { { 1 1/2 } { 1 1/3 } }\n { { 2 1/3 } { 1 1/7 } }\n { { 4 1/5 } { -1 1/239 } }\n { { 5 1/7 } { 2 3/79 } }\n { { 5 29/278 } { 7 3/79 } }\n { { 1 1/2 } { 1 1/5 } { 1 1/8 } }\n { { 5 1/7 } { 4 1/53 } { 2 1/4443 } }\n { { 6 1/8 } { 2 1/57 } { 1 1/239 } }\n { { 8 1/10 } { -1 1/239 } { -4 1/515 } }\n { { 12 1/18 } { 8 1/57 } { -5 1/239 } }\n { { 16 1/21 } { 3 1/239 } { 4 3/1042 } }\n { { 22 1/28 } { 2 1/443 }\n { -5 1/1393 } { -10 1/11018 } }\n { { 22 1/38 } { 17 7/601 } { 10 7/8149 } }\n { { 44 1/57 } { 7 1/239 } { -12 1/682 } { 24 1/12943 } }\n { { 88 1/172 } { 51 1/239 } { 32 1/682 }\n { 44 1/5357 } { 68 1/12943 } }\n { { 88 1/172 } { 51 1/239 } { 32 1/682 }\n { 44 1/5357 } { 68 1/12944 } }\n } [ dup tans \"tan %u = %u\\n\" printf ] each ;\n\nMAIN: machin\n", "language": "Factor" }, { "code": "' version 07-04-2018\n' compile with: fbc -s console\n\n#Include \"gmp.bi\"\n\n#Define _a(Q) (@(Q)->_mp_num) 'a\n#Define _b(Q) (@(Q)->_mp_den) 'b\n\nData \"[1, 1, 2] [1, 1, 3]\"\nData \"[2, 1, 3] [1, 1, 7]\"\nData \"[4, 1, 5] [-1, 1, 239]\"\nData \"[5, 1, 7] [2, 3, 79]\"\nData \"[1, 1, 2] [1, 1, 5] [1, 1, 8]\"\nData \"[4, 1, 5] [-1, 1, 70] [1, 1, 99]\"\nData \"[5, 1, 7] [4, 1, 53] [2, 1, 4443]\"\nData \"[6, 1, 8] [2, 1, 57] [1, 1, 239]\"\nData \"[8, 1, 10] [-1, 1, 239] [-4, 1, 515]\"\nData \"[12, 1, 18] [8, 1, 57] [-5, 1, 239]\"\nData \"[16, 1, 21] [3, 1, 239] [4, 3, 1042]\"\nData \"[22, 1, 28] [2, 1, 443] [-5, 1, 1393] [-10, 1, 11018]\"\nData \"[22, 1, 38] [17, 7, 601] [10, 7, 8149]\"\nData \"[44, 1, 57] [7, 1, 239] [-12, 1, 682] [24, 1, 12943]\"\nData \"[88, 1, 172] [51, 1, 239] [32, 1, 682] [44, 1, 5357] [68, 1, 12943]\"\nData \"[88, 1, 172] [51, 1, 239] [32, 1, 682] [44, 1, 5357] [68, 1, 12944]\"\nData \"\"\n\nSub work2do (ByRef a As LongInt, f1 As mpq_ptr)\n\n Dim As LongInt flag = -1\n\n Dim As Mpq_ptr x, y, z\n x = Allocate(Len(__mpq_struct)) : Mpq_init(x)\n y = Allocate(Len(__mpq_struct)) : Mpq_init(y)\n z = Allocate(Len(__mpq_struct)) : Mpq_init(z)\n\n Dim As Mpz_ptr temp1, temp2\n temp1 = Allocate(Len(__Mpz_struct)) : Mpz_init(temp1)\n temp2 = Allocate(Len(__Mpz_struct)) : Mpz_init(temp2)\n\n mpq_set(y, f1)\n\n While a > 0\n If (a And 1) = 1 Then\n If flag = -1 Then\n mpq_set(x, y)\n flag = 0\n Else\n Mpz_mul(temp1, _a(x), _b(y))\n Mpz_mul(temp2, _b(x), _a(y))\n Mpz_add(_a(z), temp1, temp2)\n Mpz_mul(temp1, _b(x), _b(y))\n Mpz_mul(temp2, _a(x), _a(y))\n Mpz_sub(_b(z), temp1, temp2)\n mpq_canonicalize(z)\n mpq_set(x, z)\n End If\n End If\n\n Mpz_mul(temp1, _a(y), _b(y))\n Mpz_mul(temp2, _b(y), _a(y))\n Mpz_add(_a(z), temp1, temp2)\n Mpz_mul(temp1, _b(y), _b(y))\n Mpz_mul(temp2, _a(y), _a(y))\n Mpz_sub(_b(z), temp1, temp2)\n mpq_canonicalize(z)\n mpq_set(y, z)\n\n a = a Shr 1\n Wend\n\n mpq_set(f1, x)\n\nEnd Sub\n\n' ------=< MAIN >=------\n\nDim As Mpq_ptr f1, f2, f3\nf1 = Allocate(Len(__mpq_struct)) : Mpq_init(f1)\nf2 = Allocate(Len(__mpq_struct)) : Mpq_init(f2)\nf3 = Allocate(Len(__mpq_struct)) : Mpq_init(f3)\n\nDim As Mpz_ptr temp1, temp2\ntemp1 = Allocate(Len(__Mpz_struct)) : Mpz_init(temp1)\ntemp2 = Allocate(Len(__Mpz_struct)) : Mpz_init(temp2)\n\nDim As mpf_ptr float\nfloat = Allocate(Len(__mpf_struct)) : Mpf_init(float)\n\nDim As LongInt m1, a1, b1, flag, t1, t2, t3, t4\nDim As String s, s1, s2, s3, sign\nDim As ZString Ptr zstr\n\nDo\n\n Read s\n If s = \"\" Then Exit Do\n flag = -1\n\n While s <> \"\"\n t1 = InStr(s, \"[\") +1\n t2 = InStr(t1, s, \",\") +1\n t3 = InStr(t2, s, \",\") +1\n t4 = InStr(t3, s, \"]\")\n s1 = Trim(Mid(s, t1, t2 - t1 -1))\n s2 = Trim(Mid(s, t2, t3 - t2 -1))\n s3 = Trim(Mid(s, t3, t4 - t3))\n m1 = Val(s1)\n a1 = Val(s2)\n b1 = Val(s3)\n\n sign = IIf(m1 < 0, \" - \", \" + \")\n If m1 < 0 Then a1 = -a1 : m1 = Abs(m1)\n s = Mid(s, t4 +1)\n Print IIf(flag = 0, sign, \"\"); IIf(m1 = 1, \"\", Str(m1));\n Print \"Atn(\"; s2; \"/\" ;s3; \")\";\n\n If flag = -1 Then\n flag = 0\n Mpz_set_si(_a(f1), a1)\n Mpz_set_si(_b(f1), b1)\n If m1 > 1 Then work2do(m1, f1)\n Continue While\n End If\n\n Mpz_set_si(_a(f2), a1)\n Mpz_set_si(_b(f2), b1)\n If m1 > 1 Then work2do(m1, f2)\n\n Mpz_mul(temp1, _a(f1), _b(f2))\n Mpz_mul(temp2, _b(f1), _a(f2))\n Mpz_add(_a(f3), temp1, temp2)\n Mpz_mul(temp1, _b(f1), _b(f2))\n Mpz_mul(temp2, _a(f1), _a(f2))\n Mpz_sub(_b(f3), temp1, temp2)\n mpq_canonicalize(f3)\n mpq_set(f1, f3)\n\n Wend\n\n If Mpz_cmp_ui(_b(f1), 1) = 0 AndAlso Mpz_cmp(_a(f1), _b(f1)) = 0 Then\n Print \" = 1\"\n Else\n Mpf_set_q(float, f1)\n gmp_printf(!\" = %.*Ff\\n\", 15, float)\n End If\n\nLoop\n\n' empty keyboard buffer\nWhile InKey <> \"\" : Wend\nPrint : Print \"hit any key to end program\"\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "TanPlus := function(a, b)\n return (a + b) / (1 - a * b);\nend;\n\nTanTimes := function(n, a)\n local x;\n x := 0;\n while n > 0 do\n if IsOddInt(n) then\n x := TanPlus(x, a);\n fi;\n a := TanPlus(a, a);\n n := QuoInt(n, 2);\n od;\n return x;\nend;\n\nCheck := function(a)\n local x, p;\n x := 0;\n for p in a do\n x := TanPlus(x, SignInt(p[1]) * TanTimes(AbsInt(p[1]), p[2]));\n od;\n return x = 1;\nend;\n\nForAll([\n [[1, 1/2], [1, 1/3]],\n [[2, 1/3], [1, 1/7]],\n [[4, 1/5], [-1, 1/239]],\n [[5, 1/7], [2, 3/79]],\n [[5, 29/278], [7, 3/79]],\n [[1, 1/2], [1, 1/5], [1, 1/8]],\n [[5, 1/7], [4, 1/53], [2, 1/4443]],\n [[6, 1/8], [2, 1/57], [1, 1/239]],\n [[8, 1/10], [-1, 1/239], [-4, 1/515]],\n [[12, 1/18], [8, 1/57], [-5, 1/239]],\n [[16, 1/21], [3, 1/239], [4, 3/1042]],\n [[22, 1/28], [2, 1/443], [-5, 1/1393], [-10, 1/11018]],\n [[22, 1/38], [17, 7/601], [10, 7/8149]],\n [[44, 1/57], [7, 1/239], [-12, 1/682], [24, 1/12943]],\n [[88, 1/172], [51, 1/239], [32, 1/682], [44, 1/5357], [68, 1/12943]]], Check);\n\nCheck([[88, 1/172], [51, 1/239], [32, 1/682], [44, 1/5357], [68, 1/12944]]);\n", "language": "GAP" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\ntype mTerm struct {\n a, n, d int64\n}\n\nvar testCases = [][]mTerm{\n {{1, 1, 2}, {1, 1, 3}},\n {{2, 1, 3}, {1, 1, 7}},\n {{4, 1, 5}, {-1, 1, 239}},\n {{5, 1, 7}, {2, 3, 79}},\n {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},\n {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},\n {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},\n {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},\n {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},\n {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},\n {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},\n {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},\n {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},\n {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},\n {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},\n {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},\n}\n\nfunc main() {\n for _, m := range testCases {\n fmt.Printf(\"tan %v = %v\\n\", m, tans(m))\n }\n}\n\nvar one = big.NewRat(1, 1)\n\nfunc tans(m []mTerm) *big.Rat {\n if len(m) == 1 {\n return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))\n }\n half := len(m) / 2\n a := tans(m[:half])\n b := tans(m[half:])\n r := new(big.Rat)\n return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n\nfunc tanEval(coef int64, f *big.Rat) *big.Rat {\n if coef == 1 {\n return f\n }\n if coef < 0 {\n r := tanEval(-coef, f)\n return r.Neg(r)\n }\n ca := coef / 2\n cb := coef - ca\n a := tanEval(ca, f)\n b := tanEval(cb, f)\n r := new(big.Rat)\n return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n", "language": "Go" }, { "code": "import Data.Ratio\nimport Data.List (foldl')\n\ntanPlus :: Fractional a => a -> a -> a\ntanPlus a b = (a + b) / (1 - a * b)\n\ntanEval :: (Integral a, Fractional b) => (a, b) -> b\ntanEval (0,_) = 0\ntanEval (coef,f)\n\t| coef < 0 = -tanEval (-coef, f)\n\t| odd coef = tanPlus f $ tanEval (coef - 1, f)\n\t| otherwise = tanPlus a a\n\t\twhere a = tanEval (coef `div` 2, f)\n\ntans :: (Integral a, Fractional b) => [(a, b)] -> b\ntans = foldl' tanPlus 0 . map tanEval\n\nmachins = [\n\t[(1, 1%2), (1, 1%3)],\n\t[(2, 1%3), (1, 1%7)],\n\t[(12, 1%18), (8, 1%57), (-5, 1%239)],\n\t[(88, 1%172), (51, 1%239), (32 , 1%682), (44, 1%5357), (68, 1%12943)]]\n\nnot_machin = [(88, 1%172), (51, 1%239), (32 , 1%682), (44, 1%5357), (68, 1%12944)]\n\nmain = do\n\tputStrLn \"Machins:\"\n\tmapM_ (\\x -> putStrLn $ show (tans x) ++ \" <-- \" ++ show x) machins\n\n\tputStr \"\\nnot Machin: \"; print not_machin\n\tprint (tans not_machin)\n", "language": "Haskell" }, { "code": "import Data.Ratio\n\n-- Private type. Do not use outside of the tans function\nnewtype Tan a = Tan a deriving (Eq, Show)\ninstance Fractional a => Num (Tan a) where\n _ + _ = undefined\n Tan a * Tan b = Tan $ (a + b) / (1 - a * b)\n negate _ = undefined\n abs _ = undefined\n signum _ = undefined\n fromInteger 1 = Tan 0 -- identity for the (*) above\n fromInteger _ = undefined\ninstance Fractional a => Fractional (Tan a) where\n fromRational _ = undefined\n recip (Tan f) = Tan (-f) -- inverse for the (*) above\n\ntans :: (Integral a, Fractional b) => [(a, b)] -> b\ntans xs = x where\n Tan x = product [Tan f ^^ coef | (coef,f) <- xs]\n\nmachins = [\n\t[(1, 1%2), (1, 1%3)],\n\t[(2, 1%3), (1, 1%7)],\n\t[(12, 1%18), (8, 1%57), (-5, 1%239)],\n\t[(88, 1%172), (51, 1%239), (32 , 1%682), (44, 1%5357), (68, 1%12943)]]\n\nnot_machin = [(88, 1%172), (51, 1%239), (32 , 1%682), (44, 1%5357), (68, 1%12944)]\n\nmain = do\n\tputStrLn \"Machins:\"\n\tmapM_ (\\x -> putStrLn $ show (tans x) ++ \" <-- \" ++ show x) machins\n\n\tputStr \"\\nnot Machin: \"; print not_machin\n\tprint (tans not_machin)\n", "language": "Haskell" }, { "code": " machin =: 1r4p1 = [: +/ ({. * _3 o. %/@:}.)\"1@:x:\n", "language": "J" }, { "code": " R =: <@:(0&\".);._2 ];._2 noun define\n  1  1     2\n  1  1     3\n------------\n  2  1     3\n  1  1     7\n------------\n  4  1     5\n _1  1   239\n------------\n  5  1     7\n  2  3    79\n------------\n  5 29   278\n  7  3    79\n------------\n  1  1     2\n  1  1     5\n  1  1     8\n------------\n  4  1     5\n _1  1    70\n  1  1    99\n------------\n  5  1     7\n  4  1    53\n  2  1  4443\n------------\n  6  1     8\n  2  1    57\n  1  1   239\n------------\n  8  1    10\n _1  1   239\n _4  1   515\n------------\n 12  1    18\n  8  1    57\n _5  1   239\n------------\n 16  1    21\n  3  1   239\n  4  3  1042\n------------\n 22  1    28\n  2  1   443\n _5  1  1393\n_10  1 11018\n------------\n 22  1    38\n 17  7   601\n 10  7  8149\n------------\n 44  1    57\n  7  1   239\n_12  1   682\n 24  1 12943\n------------\n 88  1   172\n 51  1   239\n 32  1   682\n 44  1  5357\n 68  1 12943\n------------\n)\n\n   machin&> R\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n", "language": "J" }, { "code": "   counterExample=. 12944 (<_1;_1)} >{:R\n   counterExample  NB. Same as final test case with 12943 incremented to 12944\n88 1   172\n51 1   239\n32 1   682\n44 1  5357\n68 1 12944\n   machin counterExample\n0\n", "language": "J" }, { "code": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CheckMachinFormula {\n\n private static String FILE_NAME = \"MachinFormula.txt\";\n\n public static void main(String[] args) {\n try {\n runPrivate();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n private static void runPrivate() throws IOException {\n try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {\n String inLine = null;\n while ( (inLine = reader.readLine()) != null ) {\n String[] split = inLine.split(\"=\");\n System.out.println(tanLeft(split[0].trim()) + \" = \" + split[1].trim().replaceAll(\"\\\\s+\", \" \") + \" = \" + tanRight(split[1].trim()));\n }\n }\n }\n\n private static String tanLeft(String formula) {\n if ( formula.compareTo(\"pi/4\") == 0 ) {\n return \"1\";\n }\n throw new RuntimeException(\"ERROR 104: Unknown left side: \" + formula);\n }\n\n private static final Pattern ARCTAN_PATTERN = Pattern.compile(\"(-{0,1}\\\\d+)\\\\*arctan\\\\((\\\\d+)/(\\\\d+)\\\\)\");\n\n private static Fraction tanRight(String formula) {\n Matcher matcher = ARCTAN_PATTERN.matcher(formula);\n List<Term> terms = new ArrayList<>();\n while ( matcher.find() ) {\n terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));\n }\n return evaluateArctan(terms);\n }\n\n private static Fraction evaluateArctan(List<Term> terms) {\n if ( terms.size() == 1 ) {\n Term term = terms.get(0);\n return evaluateArctan(term.coefficient, term.fraction);\n }\n int size = terms.size();\n List<Term> left = terms.subList(0, (size+1) / 2);\n List<Term> right = terms.subList((size+1) / 2, size);\n return arctanFormula(evaluateArctan(left), evaluateArctan(right));\n }\n\n private static Fraction evaluateArctan(int coefficient, Fraction fraction) {\n //System.out.println(\"C = \" + coefficient + \", F = \" + fraction);\n if ( coefficient == 1 ) {\n return fraction;\n }\n else if ( coefficient < 0 ) {\n return evaluateArctan(-coefficient, fraction).negate();\n }\n if ( coefficient % 2 == 0 ) {\n Fraction f = evaluateArctan(coefficient/2, fraction);\n return arctanFormula(f, f);\n }\n Fraction a = evaluateArctan(coefficient/2, fraction);\n Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);\n return arctanFormula(a, b);\n }\n\n private static Fraction arctanFormula(Fraction f1, Fraction f2) {\n return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));\n }\n\n private static class Fraction {\n\n public static final Fraction ONE = new Fraction(\"1\", \"1\");\n\n private BigInteger numerator;\n private BigInteger denominator;\n\n public Fraction(String num, String den) {\n numerator = new BigInteger(num);\n denominator = new BigInteger(den);\n }\n\n public Fraction(BigInteger num, BigInteger den) {\n numerator = num;\n denominator = den;\n }\n\n public Fraction negate() {\n return new Fraction(numerator.negate(), denominator);\n }\n\n public Fraction add(Fraction f) {\n BigInteger gcd = denominator.gcd(f.denominator);\n BigInteger first = numerator.multiply(f.denominator.divide(gcd));\n BigInteger second = f.numerator.multiply(denominator.divide(gcd));\n return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));\n }\n\n public Fraction subtract(Fraction f) {\n return add(f.negate());\n }\n\n public Fraction multiply(Fraction f) {\n BigInteger num = numerator.multiply(f.numerator);\n BigInteger den = denominator.multiply(f.denominator);\n BigInteger gcd = num.gcd(den);\n return new Fraction(num.divide(gcd), den.divide(gcd));\n }\n\n public Fraction divide(Fraction f) {\n return multiply(new Fraction(f.denominator, f.numerator));\n }\n\n @Override\n public String toString() {\n if ( denominator.compareTo(BigInteger.ONE) == 0 ) {\n return numerator.toString();\n }\n return numerator + \" / \" + denominator;\n }\n }\n\n private static class Term {\n\n private int coefficient;\n private Fraction fraction;\n\n public Term(int c, Fraction f) {\n coefficient = c;\n fraction = f;\n }\n }\n\n}\n", "language": "Java" }, { "code": "using AbstractAlgebra # implements arbitrary precision rationals\n\ntanplus(x,y) = (x + y) / (1 - x * y)\n\nfunction taneval(coef, frac)\n if coef == 0\n return 0\n elseif coef < 0\n return -taneval(-coef, frac)\n elseif isodd(coef)\n return tanplus(frac, taneval(coef - 1, frac))\n else\n x = taneval(div(coef, 2), frac)\n return tanplus(x, x)\n end\nend\n\ntaneval(tup::Tuple) = taneval(tup[1], tup[2])\n\ntans(v::Vector{Tuple{BigInt, Rational{BigInt}}}) = foldl(tanplus, map(taneval, v), init=0)\n\nconst testmats = Dict{Vector{Tuple{BigInt, Rational{BigInt}}}, Bool}([\n ([(1, 1//2), (1, 1//3)], true), ([(2, 1//3), (1, 1//7)], true),\n ([(12, 1//18), (8, 1//57), (-5, 1//239)], true),\n ([(88, 1//172), (51, 1//239), (32, 1//682), (44, 1//5357), (68, 1//12943)], true),\n ([(88, 1//172), (51, 1//239), (32, 1//682), (44, 1//5357), (68, 1//12944)], false)])\n\n\nfunction runtestmats()\n println(\"Testing matrices:\")\n for (k, m) in testmats\n ans = tans(k)\n println((ans == 1) == m ? \"Verified as $m: \" : \"Not Verified as $m: \", \"tan $k = $ans\")\n end\nend\n\nruntestmats()\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nimport java.math.BigInteger\n\nval bigZero = BigInteger.ZERO\nval bigOne = BigInteger.ONE\n\nclass BigRational : Comparable<BigRational> {\n\n val num: BigInteger\n val denom: BigInteger\n\n constructor(n: BigInteger, d: BigInteger) {\n require(d != bigZero)\n var nn = n\n var dd = d\n if (nn == bigZero) {\n dd = bigOne\n }\n else if (dd < bigZero) {\n nn = -nn\n dd = -dd\n }\n val g = nn.gcd(dd)\n if (g > bigOne) {\n nn /= g\n dd /= g\n }\n num = nn\n denom = dd\n }\n\n constructor(n: Long, d: Long) : this(BigInteger.valueOf(n), BigInteger.valueOf(d))\n\n operator fun plus(other: BigRational) =\n BigRational(num * other.denom + denom * other.num, other.denom * denom)\n\n operator fun unaryMinus() = BigRational(-num, denom)\n\n operator fun minus(other: BigRational) = this + (-other)\n\n operator fun times(other: BigRational) = BigRational(this.num * other.num, this.denom * other.denom)\n\n fun inverse(): BigRational {\n require(num != bigZero)\n return BigRational(denom, num)\n }\n\n operator fun div(other: BigRational) = this * other.inverse()\n\n override fun compareTo(other: BigRational): Int {\n val diff = this - other\n return when {\n diff.num < bigZero -> -1\n diff.num > bigZero -> +1\n else -> 0\n }\n }\n\n override fun equals(other: Any?): Boolean {\n if (other == null || other !is BigRational) return false\n return this.compareTo(other) == 0\n }\n\n override fun toString() = if (denom == bigOne) \"$num\" else \"$num/$denom\"\n\n companion object {\n val ZERO = BigRational(bigZero, bigOne)\n val ONE = BigRational(bigOne, bigOne)\n }\n}\n\n/** represents a term of the form: c * atan(n / d) */\nclass Term(val c: Long, val n: Long, val d: Long) {\n\n override fun toString() = when {\n c == 1L -> \" + \"\n c == -1L -> \" - \"\n c < 0L -> \" - ${-c}*\"\n else -> \" + $c*\"\n } + \"atan($n/$d)\"\n}\n\nval one = BigRational.ONE\n\nfun tanSum(terms: List<Term>): BigRational {\n if (terms.size == 1) return tanEval(terms[0].c, BigRational(terms[0].n, terms[0].d))\n val half = terms.size / 2\n val a = tanSum(terms.take(half))\n val b = tanSum(terms.drop(half))\n return (a + b) / (one - (a * b))\n}\n\nfun tanEval(c: Long, f: BigRational): BigRational {\n if (c == 1L) return f\n if (c < 0L) return -tanEval(-c, f)\n val ca = c / 2\n val cb = c - ca\n val a = tanEval(ca, f)\n val b = tanEval(cb, f)\n return (a + b) / (one - (a * b))\n}\n\nfun main(args: Array<String>) {\n val termsList = listOf(\n listOf(Term(1, 1, 2), Term(1, 1, 3)),\n listOf(Term(2, 1, 3), Term(1, 1, 7)),\n listOf(Term(4, 1, 5), Term(-1, 1, 239)),\n listOf(Term(5, 1, 7), Term(2, 3, 79)),\n listOf(Term(5, 29, 278), Term(7, 3, 79)),\n listOf(Term(1, 1, 2), Term(1, 1, 5), Term(1, 1, 8)),\n listOf(Term(4, 1, 5), Term(-1, 1, 70), Term(1, 1, 99)),\n listOf(Term(5, 1, 7), Term(4, 1, 53), Term(2, 1, 4443)),\n listOf(Term(6, 1, 8), Term(2, 1, 57), Term(1, 1, 239)),\n listOf(Term(8, 1, 10), Term(-1, 1, 239), Term(-4, 1, 515)),\n listOf(Term(12, 1, 18), Term(8, 1, 57), Term(-5, 1, 239)),\n listOf(Term(16, 1, 21), Term(3, 1, 239), Term(4, 3, 1042)),\n listOf(Term(22, 1, 28), Term(2, 1, 443), Term(-5, 1, 1393), Term(-10, 1, 11018)),\n listOf(Term(22, 1, 38), Term(17, 7, 601), Term(10, 7, 8149)),\n listOf(Term(44, 1, 57), Term(7, 1, 239), Term(-12, 1, 682), Term(24, 1, 12943)),\n listOf(Term(88, 1, 172), Term(51, 1, 239), Term(32, 1, 682), Term(44, 1, 5357), Term(68, 1, 12943)),\n listOf(Term(88, 1, 172), Term(51, 1, 239), Term(32, 1, 682), Term(44, 1, 5357), Term(68, 1, 12944))\n )\n\n for (terms in termsList) {\n val f = String.format(\"%-5s << 1 == tan(\", tanSum(terms) == one)\n print(f)\n print(terms[0].toString().drop(3))\n for (i in 1 until terms.size) print(terms[i])\n println(\")\")\n }\n}\n", "language": "Kotlin" }, { "code": "Tan[ArcTan[1/2] + ArcTan[1/3]] == 1\nTan[2 ArcTan[1/3] + ArcTan[1/7]] == 1\nTan[4 ArcTan[1/5] - ArcTan[1/239]] == 1\nTan[5 ArcTan[1/7] + 2 ArcTan[3/79]] == 1\nTan[5 ArcTan[29/278] + 7 ArcTan[3/79]] == 1\nTan[ArcTan[1/2] + ArcTan[1/5] + ArcTan[1/8]] == 1\nTan[4 ArcTan[1/5] - ArcTan[1/70] + ArcTan[1/99]] == 1\nTan[5 ArcTan[1/7] + 4 ArcTan[1/53] + 2 ArcTan[1/4443]] == 1\nTan[6 ArcTan[1/8] + 2 ArcTan[1/57] + ArcTan[1/239]] == 1\nTan[8 ArcTan[1/10] - ArcTan[1/239] - 4 ArcTan[1/515]] == 1\nTan[12 ArcTan[1/18] + 8 ArcTan[1/57] - 5 ArcTan[1/239]] == 1\nTan[16 ArcTan[1/21] + 3 ArcTan[1/239] + 4 ArcTan[3/1042]] == 1\nTan[22 ArcTan[1/28] + 2 ArcTan[1/443] - 5 ArcTan[1/1393] -\n 10 ArcTan[1/11018]] == 1\nTan[22 ArcTan[1/38] + 17 ArcTan[7/601] + 10 ArcTan[7/8149]] == 1\nTan[44 ArcTan[1/57] + 7 ArcTan[1/239] - 12 ArcTan[1/682] +\n 24 ArcTan[1/12943]] == 1\nTan[88 ArcTan[1/172] + 51 ArcTan[1/239] + 32 ArcTan[1/682] +\n 44 ArcTan[1/5357] + 68 ArcTan[1/12943]] == 1\nTan[88 ArcTan[1/172] + 51 ArcTan[1/239] + 32 ArcTan[1/682] +\n 44 ArcTan[1/5357] + 68 ArcTan[1/12944]] == 1\n", "language": "Mathematica" }, { "code": "trigexpand:true$\nis(tan(atan(1/2)+atan(1/3))=1);\nis(tan(2*atan(1/3)+atan(1/7))=1);\nis(tan(4*atan(1/5)-atan(1/239))=1);\nis(tan(5*atan(1/7)+2*atan(3/79))=1);\nis(tan(5*atan(29/278)+7*atan(3/79))=1);\nis(tan(atan(1/2)+atan(1/5)+atan(1/8))=1);\nis(tan(4*atan(1/5)-atan(1/70)+atan(1/99))=1);\nis(tan(5*atan(1/7)+4*atan(1/53)+2*atan(1/4443))=1);\nis(tan(6*atan(1/8)+2*atan(1/57)+atan(1/239))=1);\nis(tan(8*atan(1/10)-atan(1/239)-4*atan(1/515))=1);\nis(tan(12*atan(1/18)+8*atan(1/57)-5*atan(1/239))=1);\nis(tan(16*atan(1/21)+3*atan(1/239)+4*atan(3/1042))=1);\nis(tan(22*atan(1/28)+2*atan(1/443)-5*atan(1/1393)-10*atan(1/11018))=1);\nis(tan(22*atan(1/38)+17*atan(7/601)+10*atan(7/8149))=1);\nis(tan(44*atan(1/57)+7*atan(1/239)-12*atan(1/682)+24*atan(1/12943))=1);\nis(tan(88*atan(1/172)+51*atan(1/239)+32*atan(1/682)+44*atan(1/5357)+68*atan(1/12943))=1);\nis(tan(88*atan(1/172)+51*atan(1/239)+32*atan(1/682)+44*atan(1/5357)+68*atan(1/12944))=1);\n", "language": "Maxima" }, { "code": "import bignum\n\ntype\n\n # Description of a term.\n Term = object\n factor: int # Multiplier (may be negative).\n fract: Rat # Argument of arc tangent.\n\n Expression = seq[Term]\n\n# Rational 1.\nlet One = newRat(1)\n\n\n####################################################################################################\n# Formula parser.\n\ntype\n\n # Possible tokens for parsing.\n Token = enum tkPi, tkArctan, tkNumber, tkEqual, tkAdd, tkSub,\n tkMul, tkDiv, tkLPar, tkRPar, tkError, tkEnd\n\n # Lexer description.\n Lexer = object\n line: string # The line to parse.\n pos: Natural # Current position of lexer.\n token: Token # Current token.\n value: Natural # Associated value (for numbers).\n\n # Exception raised if an error is found.\n SyntaxError = object of CatchableError\n\n#---------------------------------------------------------------------------------------------------\n\nproc initLexer(line: string): Lexer =\n ## Create and initialize a lexer.\n result.line = line\n result.pos = 0\n\n#---------------------------------------------------------------------------------------------------\n\nproc parseName(lexer: var Lexer; pos: Natural) =\n ## Parse a name.\n\n # Build the name.\n var pos = pos\n var name = \"\"\n while pos < lexer.line.len and (let c = lexer.line[pos]; c) in 'a'..'z':\n name.add(c)\n inc pos\n\n # Update lexer state.\n lexer.token = if name == \"arctan\": tkArctan\n elif name == \"pi\": tkPi\n else: tkError\n lexer.pos = pos\n\n#---------------------------------------------------------------------------------------------------\n\nproc parseNumber(lexer: var Lexer; pos: Natural) =\n ## Parse a number.\n\n # Build the number.\n var pos = pos\n var value = 0\n while pos < lexer.line.len and (let c = lexer.line[pos]; c) in '0'..'9':\n value = 10 * value + ord(c) - ord('0')\n inc pos\n\n # Update lexer state.\n lexer.token = tkNumber\n lexer.value = value\n lexer.pos = pos\n\n#---------------------------------------------------------------------------------------------------\n\nproc getNextToken(lexer: var Lexer) =\n ## Find next token.\n\n var pos = lexer.pos\n var token: Token\n while pos < lexer.line.len and lexer.line[pos] == ' ': inc pos\n if pos == lexer.line.len:\n # Reached end of string.\n lexer.pos = pos\n lexer.token = tkEnd\n return\n\n # Find token.\n case lexer.line[pos]\n of '=': token = tkEqual\n of '+': token = tkAdd\n of '-': token = tkSub\n of '*': token = tkMul\n of '/': token = tkDiv\n of '(': token = tkLPar\n of ')': token = tkRPar\n of 'a'..'z':\n lexer.parseName(pos)\n return\n of '0'..'9':\n lexer.parseNumber(pos)\n return\n else: token = tkError\n\n # Update lexer state.\n lexer.pos = pos + 1\n lexer.token = token\n\n#---------------------------------------------------------------------------------------------------\n\ntemplate syntaxError(message: string) =\n ## Raise a syntax error exception.\n raise newException(SyntaxError, message)\n\n#---------------------------------------------------------------------------------------------------\n\nproc parseFraction(lexer: var Lexer): Rat =\n ## Parse a fraction: number / number.\n\n lexer.getNextToken()\n if lexer.token != tkNumber:\n syntaxError(\"number expected.\")\n let num = lexer.value\n lexer.getNextToken()\n if lexer.token != tkDiv:\n syntaxError(\"“/” expected.\")\n lexer.getNextToken()\n if lexer.token != tkNumber:\n syntaxError(\"number expected\")\n if lexer.value == 0:\n raise newException(ValueError, \"null denominator.\")\n let den = lexer.value\n result = newRat(num, den)\n\n#---------------------------------------------------------------------------------------------------\n\nproc parseTerm(lexer: var Lexer): Term =\n ## Parse a term: factor * arctan(fraction) or arctan(fraction).\n\n lexer.getNextToken()\n\n # Parse factor.\n if lexer.token == tkNumber:\n result.factor = lexer.value\n lexer.getNextToken\n if lexer.token != tkMul:\n syntaxError(\"“*” expected.\")\n lexer.getNextToken()\n else:\n result.factor = 1\n\n # Parse arctan.\n if lexer.token != tkArctan:\n syntaxError(\"“arctan” expected.\")\n lexer.getNextToken()\n if lexer.token != tkLPar:\n syntaxError(\"“(” expected.\")\n result.fract = lexer.parseFraction()\n lexer.getNextToken()\n if lexer.token != tkRPar:\n syntaxError(\"“)” expected.\")\n\n#---------------------------------------------------------------------------------------------------\n\nproc parse(line: string): Expression =\n ## Parse a formula.\n\n var lexer = initLexer(line)\n lexer.getNextToken()\n\n if lexer.token != tkPi:\n syntaxError(\"pi symbol expected.\")\n lexer.getNextToken()\n\n if lexer.token != tkDiv:\n syntaxError(\"'/' expected.\")\n lexer.getNextToken()\n\n if lexer.token != tkNumber:\n syntaxError(\"number expected.\")\n if lexer.value != 4:\n raise newException(ValueError, \"value 4 expected.\")\n lexer.getNextToken()\n\n if lexer.token != tkEqual:\n syntaxError(\"“=” expected.\")\n result.add(lexer.parseTerm())\n lexer.getNextToken()\n\n # Parse the next terms.\n while (let token = lexer.token; token) in {tkAdd, tkSub}:\n var term = lexer.parseTerm()\n if token == tkSub:\n term.factor = -term.factor\n result.add(term)\n lexer.getNextToken()\n\n if lexer.token != tkEnd:\n syntaxError(\"invalid characters at end of formula.\")\n\n\n####################################################################################################\n# Evaluator.\n\nproc tangent(factor: int; fract: Rat): Rat =\n ## Compute the tangent of \"factor * arctan(fract)\".\n\n if factor == 1:\n return fract\n if factor < 0:\n return -tangent(-factor, fract)\n\n # Split in two parts.\n let n = factor div 2\n let a = tangent(n, fract)\n let b = tangent(factor - n, fract)\n result = (a + b) / (One - a * b)\n\n#---------------------------------------------------------------------------------------------------\n\nproc tangent(expr: Expression): Rat =\n ## Compute the tangent of a sum of terms.\n\n if expr.len == 1:\n result = tangent(expr[0].factor, expr[0].fract)\n else:\n # Split in two parts.\n let a = tangent(expr[0..<(expr.len div 2)])\n let b = tangent(expr[(expr.len div 2)..^1])\n result = (a + b) / (One - a * b)\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nwhen isMainModule:\n\n const Formulas = [\n \"pi/4 = arctan(1/2) + arctan(1/3)\",\n \"pi/4 = 2*arctan(1/3) + arctan(1/7)\",\n \"pi/4 = 4*arctan(1/5) - arctan(1/239)\",\n \"pi/4 = 5*arctan(1/7) + 2*arctan(3/79)\",\n \"pi/4 = 5*arctan(29/278) + 7*arctan(3/79)\",\n \"pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)\",\n \"pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)\",\n \"pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)\",\n \"pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)\",\n \"pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)\",\n \"pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)\",\n \"pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)\",\n \"pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)\",\n \"pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)\",\n \"pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)\",\n \"pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)\",\n \"pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)\"]\n\nfor formula in Formulas:\n let expr = formula.parse()\n let value = tangent(expr)\n if value == 1:\n echo \"True: \", formula\n else:\n echo \"False: \", formula\n echo \"Tangent of the right expression is about \", value.toFloat\n", "language": "Nim" }, { "code": "open Num;; (* use exact rationals for results *)\n\nlet tadd p q = (p +/ q) // ((Int 1) -/ (p */ q)) in\n\n(* tan(n*arctan(a/b)) *)\nlet rec tan_expr (n,a,b) =\n if n = 1 then (Int a)//(Int b) else\n if n = -1 then (Int (-a))//(Int b) else\n let m = n/2 in\n let tm = tan_expr (m,a,b) in\n let m2 = tadd tm tm and k = n-m-m in\n if k = 0 then m2 else tadd (tan_expr (k,a,b)) m2 in\n\nlet verify (k, tlist) =\n Printf.printf \"Testing: pi/%d = \" k;\n let t_str = List.map (fun (x,y,z) -> Printf.sprintf \"%d*atan(%d/%d)\" x y z) tlist in\n print_endline (String.concat \" + \" t_str);\n let ans_terms = List.map tan_expr tlist in\n let answer = List.fold_left tadd (Int 0) ans_terms in\n Printf.printf \" tan(RHS) is %s\\n\" (if answer = (Int 1) then \"one\" else \"not one\") in\n\n(* example: prog 4 5 29 278 7 3 79 represents pi/4 = 5*atan(29/278) + 7*atan(3/79) *)\nlet args = Sys.argv in\nlet nargs = Array.length args in\nlet v k = int_of_string args.(k) in\nlet rec triples n =\n if n+2 > nargs-1 then []\n else (v n, v (n+1), v (n+2)) :: triples (n+3) in\nif nargs > 4 then\nlet dat = (v 1, triples 2) in\nverify dat\nelse\nList.iter verify [\n (4,[(1,1,2);(1,1,3)]);\n (4,[(2,1,3);(1,1,7)]);\n (4,[(4,1,5);(-1,1,239)]);\n (4,[(5,1,7);(2,3,79)]);\n (4,[(5,29,278);(7,3,79)]);\n (4,[(1,1,2);(1,1,5);(1,1,8)]);\n (4,[(4,1,5);(-1,1,70);(1,1,99)]);\n (4,[(5,1,7);(4,1,53);(2,1,4443)]);\n (4,[(6,1,8);(2,1,57);(1,1,239)]);\n (4,[(8,1,10);(-1,1,239);(-4,1,515)]);\n (4,[(12,1,18);(8,1,57);(-5,1,239)]);\n (4,[(16,1,21);(3,1,239);(4,3,1042)]);\n (4,[(22,1,28);(2,1,443);(-5,1,1393);(-10,1,11018)]);\n (4,[(22,1,38);(17,7,601);(10,7,8149)]);\n (4,[(44,1,57);(7,1,239);(-12,1,682);(24,1,12943)]);\n (4,[(88,1,172);(51,1,239);(32,1,682);(44,1,5357);(68,1,12943)]);\n (4,[(88,1,172);(51,1,239);(32,1,682);(44,1,5357);(68,1,12944)])\n]\n", "language": "OCaml" }, { "code": "/*REXX ----------------------------------------------------------------\n* 09.04.2014 Walter Pachl the REXX solution adapted for ooRexx\n* which provides a function package rxMath\n*--------------------------------------------------------------------*/\nNumeric Digits 16\nNumeric Fuzz 3; pi=rxCalcpi(); a.=''\n a.1 = 'pi/4 = rxCalcarctan(1/2,16,'R') + rxCalcarctan(1/3,16,'R')'\n a.2 = 'pi/4 = 2*rxCalcarctan(1/3,16,'R') + rxCalcarctan(1/7,16,'R')'\n a.3 = 'pi/4 = 4*rxCalcarctan(1/5,16,'R') - rxCalcarctan(1/239,16,'R')'\n a.4 = 'pi/4 = 5*rxCalcarctan(1/7,16,'R') + 2*rxCalcarctan(3/79,16,'R')'\n a.5 = 'pi/4 = 5*rxCalcarctan(29/278,16,'R') + 7*rxCalcarctan(3/79,16,'R')'\n a.6 = 'pi/4 = rxCalcarctan(1/2,16,'R') + rxCalcarctan(1/5,16,'R') + rxCalcarctan(1/8,16,'R')'\n a.7 = 'pi/4 = 4*rxCalcarctan(1/5,16,'R') - rxCalcarctan(1/70,16,'R') + rxCalcarctan(1/99,16,'R')'\n a.8 = 'pi/4 = 5*rxCalcarctan(1/7,16,'R') + 4*rxCalcarctan(1/53,16,'R') + 2*rxCalcarctan(1/4443,16,'R')'\n a.9 = 'pi/4 = 6*rxCalcarctan(1/8,16,'R') + 2*rxCalcarctan(1/57,16,'R') + rxCalcarctan(1/239,16,'R')'\na.10 = 'pi/4 = 8*rxCalcarctan(1/10,16,'R') - rxCalcarctan(1/239,16,'R') - 4*rxCalcarctan(1/515,16,'R')'\na.11 = 'pi/4 = 12*rxCalcarctan(1/18,16,'R') + 8*rxCalcarctan(1/57,16,'R') - 5*rxCalcarctan(1/239,16,'R')'\na.12 = 'pi/4 = 16*rxCalcarctan(1/21,16,'R') + 3*rxCalcarctan(1/239,16,'R') + 4*rxCalcarctan(3/1042,16,'R')'\na.13 = 'pi/4 = 22*rxCalcarctan(1/28,16,'R') + 2*rxCalcarctan(1/443,16,'R') - 5*rxCalcarctan(1/1393,16,'R') - 10*rxCalcarctan(1/11018,16,'R')'\na.14 = 'pi/4 = 22*rxCalcarctan(1/38,16,'R') + 17*rxCalcarctan(7/601,16,'R') + 10*rxCalcarctan(7/8149,16,'R')'\na.15 = 'pi/4 = 44*rxCalcarctan(1/57,16,'R') + 7*rxCalcarctan(1/239,16,'R') - 12*rxCalcarctan(1/682,16,'R') + 24*rxCalcarctan(1/12943,16,'R')'\na.16 = 'pi/4 = 88*rxCalcarctan(1/172,16,'R') + 51*rxCalcarctan(1/239,16,'R') + 32*rxCalcarctan(1/682,16,'R') + 44*rxCalcarctan(1/5357,16,'R') + 68*rxCalcarctan(1/12943,16,'R')'\na.17 = 'pi/4 = 88*rxCalcarctan(1/172,16,'R') + 51*rxCalcarctan(1/239,16,'R') + 32*rxCalcarctan(1/682,16,'R') + 44*rxCalcarctan(1/5357,16,'R') + 68*rxCalcarctan(1/12944,16,'R')'\n do j=1 while a.j\\=='' /*evaluate each of the formulas. */\n interpret 'answer=' \"(\" a.j \")\" /*the heavy lifting.*/\n say right(word('bad OK',answer+1),3)\": \" space(a.j,0)\n end /*j*/ /* [?] show OK | bad, formula. */\n::requires rxmath library\n", "language": "OoRexx" }, { "code": "tanEval(coef, f)={\n\tif (coef <= 1, return(if(coef<1,-tanEval(-coef, f),f)));\n\tmy(a=tanEval(coef\\2, f), b=tanEval(coef-coef\\2, f));\n\t(a + b)/(1 - a*b)\n};\ntans(xs)={\n\tif (#xs == 1, return(tanEval(xs[1][1], xs[1][2])));\n\tmy(a=tans(xs[1..#xs\\2]),b=tans(xs[#xs\\2+1..#xs]));\n\t(a + b)/(1 - a*b)\n};\ntest(v)={\n\tmy(t=tans(v));\n\tif(t==1,print(\"OK\"),print(\"Error: \"v))\n};\ntest([[1,1/2],[1,1/3]]);\ntest([[2,1/3],[1,1/7]]);\ntest([[4,1/5],[-1,1/239]]);\ntest([[5,1/7],[2,3/79]]);\ntest([[5,29/278],[7,3/79]]);\ntest([[1,1/2],[1,1/5],[1,1/8]]);\ntest([[4,1/5],[-1,1/70],[1,1/99]]);\ntest([[5,1/7],[4,1/53],[2,1/4443]]);\ntest([[6,1/8],[2,1/57],[1,1/239]]);\ntest([[8,1/10],[-1,1/239],[-4,1/515]]);\ntest([[12,1/18],[8,1/57],[-5,1/239]]);\ntest([[16,1/21],[3,1/239],[4,3/1042]]);\ntest([[22,1/28],[2,1/443],[-5,1/1393],[-10,1/11018]]);\ntest([[22,1/38],[17,7/601],[10,7/8149]]);\ntest([[44,1/57],[7,1/239],[-12,1/682],[24,1/12943]]);\ntest([[88,1/172],[51,1/239],[32,1/682],[44,1/5357],[68,1/12943]]);\ntest([[88,1/172],[51,1/239],[32,1/682],[44,1/5357],[68,1/12944]]);\n", "language": "PARI-GP" }, { "code": "use Math::BigRat try=>\"GMP\";\n\nsub taneval {\n my($coef,$f) = @_;\n $f = Math::BigRat->new($f) unless ref($f);\n return 0 if $coef == 0;\n return $f if $coef == 1;\n return -taneval(-$coef, $f) if $coef < 0;\n my($a,$b) = ( taneval($coef>>1, $f), taneval($coef-($coef>>1),$f) );\n ($a+$b)/(1-$a*$b);\n}\n\nsub tans {\n my @xs=@_;\n return taneval(@{$xs[0]}) if scalar(@xs)==1;\n my($a,$b) = ( tans(@xs[0..($#xs>>1)]), tans(@xs[($#xs>>1)+1..$#xs]) );\n ($a+$b)/(1-$a*$b);\n}\n\nsub test {\n printf \"%5s (%s)\\n\", (tans(@_)==1)?\"OK\":\"Error\", join(\" \",map{\"[@$_]\"} @_);\n}\n\ntest([1,'1/2'], [1,'1/3']);\ntest([2,'1/3'], [1,'1/7']);\ntest([4,'1/5'], [-1,'1/239']);\ntest([5,'1/7'],[2,'3/79']);\ntest([5,'29/278'],[7,'3/79']);\ntest([1,'1/2'],[1,'1/5'],[1,'1/8']);\ntest([4,'1/5'],[-1,'1/70'],[1,'1/99']);\ntest([5,'1/7'],[4,'1/53'],[2,'1/4443']);\ntest([6,'1/8'],[2,'1/57'],[1,'1/239']);\ntest([8,'1/10'],[-1,'1/239'],[-4,'1/515']);\ntest([12,'1/18'],[8,'1/57'],[-5,'1/239']);\ntest([16,'1/21'],[3,'1/239'],[4,'3/1042']);\ntest([22,'1/28'],[2,'1/443'],[-5,'1/1393'],[-10,'1/11018']);\ntest([22,'1/38'],[17,'7/601'],[10,'7/8149']);\ntest([44,'1/57'],[7,'1/239'],[-12,'1/682'],[24,'1/12943']);\ntest([88,'1/172'],[51,'1/239'],[32,'1/682'],[44,'1/5357'],[68,'1/12943']);\ntest([88,'1/172'],[51,'1/239'],[32,'1/682'],[44,'1/5357'],[68,'1/12944']);\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #004600;\">PI</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">4</span> <span style=\"color: #0000FF;\">>=</span> <span style=\"color: #000000;\">a</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #004600;\">PI</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">4</span> <span style=\"color: #0000FF;\"><=</span> <span style=\"color: #000000;\">a</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">tan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">s</span> <span style=\"color: #000080;font-style:italic;\">-- or test for \"1.0\"/\"1\", but not 1.0</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span> <span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">239</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">3</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">79</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">29</span><span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">278</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">3</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">79</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span> <span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">70</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">99</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">53</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">4443</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">57</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">239</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">239</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">515</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">18</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">57</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">239</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">21</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">239</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">3</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">1042</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">22</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">28</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">443</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">1393</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">11018</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">22</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">38</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">7</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">601</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">7</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">8149</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">44</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">57</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">239</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">682</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">24</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">12943</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">88</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">172</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">51</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">239</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">32</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">682</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">44</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">5357</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">68</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">12943</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"===\"</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">88</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">172</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">51</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">239</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">32</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">682</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">44</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">5357</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">68</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">12944</span><span style=\"color: #0000FF;\">))</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">mpfr</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">tans</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">args</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #004080;\">mpq</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">aab</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">mab</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpq_inits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">h</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">mpq</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">mpq_set</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">a</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">f</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tans</span><span style=\"color: #0000FF;\">({{-</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">}})</span>\n <span style=\"color: #7060A8;\">mpq_neg</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">f</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tans</span><span style=\"color: #0000FF;\">({{</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">}})</span>\n <span style=\"color: #000000;\">b</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tans</span><span style=\"color: #0000FF;\">({{</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">}})</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tans</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">b</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tans</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..$])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">mpq_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mab</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpq_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">aab</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpq_set_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpq_sub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">mab</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpq_div</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">aab</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">aab</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">mab</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpq_free</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">aab</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">mab</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">a</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">parse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- obviously the error handling here is a bit brutal...</span>\n <span style=\"color: #000000;\">formula</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">substitute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- strip spaces</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #008000;\">\"pi/4=\"</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">formula</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">..$]</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span> <span style=\"color: #000000;\">r</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">sgn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">d</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008000;\">'-'</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">sgn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">;</span> <span style=\"color: #008080;\">fallthrough</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">formula</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">..$]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #008000;\">'a'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">sgn</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">scanf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d*%s\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #000000;\">sgn</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">scanf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"arctan(%d/%d)%s\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">mpq_init_set_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">mpq</span> <span style=\"color: #000000;\">f</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tans</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">parse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">mpq_cmp_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"OK: %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ERROR: %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">formula</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #004080;\">mpz</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_inits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpq_get_num</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpq_get_den</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" %s\\n\\\\ %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">shorten</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">mpz_get_str</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)),</span>\n <span style=\"color: #7060A8;\">shorten</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">mpz_get_str</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">))})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">formulae</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"pi/4 = arctan(1/2) + arctan(1/3)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 2*arctan(1/3) + arctan(1/7)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 4*arctan(1/5) - arctan(1/239)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 5*arctan(1/7) + 2*arctan(3/79)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 5*arctan(29/278) + 7*arctan(3/79)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)\"</span><span style=\"color: #0000FF;\">}</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">formulae</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">formulae</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = '''\\\n pi/4 = arctan(1/2) + arctan(1/3)\n pi/4 = 2*arctan(1/3) + arctan(1/7)\n pi/4 = 4*arctan(1/5) - arctan(1/239)\n pi/4 = 5*arctan(1/7) + 2*arctan(3/79)\n pi/4 = 5*arctan(29/278) + 7*arctan(3/79)\n pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)\n pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)\n pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)\n pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)\n pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)\n pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)\n pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)\n pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)\n pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)\n pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)\n pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)\n pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)\n'''\n\ndef parse_eqn(equationtext=equationtext):\n eqn_re = re.compile(r\"\"\"(?mx)\n (?P<lhs> ^ \\s* pi/4 \\s* = \\s*)? # LHS of equation\n (?: # RHS\n \\s* (?P<sign> [+-])? \\s*\n (?: (?P<mult> \\d+) \\s* \\*)?\n \\s* arctan\\( (?P<numer> \\d+) / (?P<denom> \\d+)\n )\"\"\")\n\n found = eqn_re.findall(equationtext)\n machins, part = [], []\n for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n if lhs and part:\n machins.append(part)\n part = []\n part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n Fraction(int(numer), (int(denom) if denom else 1)) ) )\n machins.append(part)\n return machins\n\n\ndef tans(xs):\n xslen = len(xs)\n if xslen == 1:\n return tanEval(*xs[0])\n aa, bb = xs[:xslen//2], xs[xslen//2:]\n a, b = tans(aa), tans(bb)\n return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n if coef == 1:\n return f\n if coef < 0:\n return -tanEval(-coef, f)\n ca = coef // 2\n cb = coef - ca\n a, b = tanEval(ca, f), tanEval(cb, f)\n return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n machins = parse_eqn()\n #pp(machins, width=160)\n for machin, eqn in zip(machins, equationtext.split('\\n')):\n ans = tans(machin)\n print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))\n", "language": "Python" }, { "code": "#lang R\nlibrary(Rmpfr)\nprec <- 1000 # precision in bits\n`%:%` <- function(e1, e2) '/'(mpfr(e1, prec), mpfr(e2, prec)) # operator %:% for high precision division\n# function for checking identity of tan of expression and 1, making use of high precision division operator %:%\ntanident_1 <- function(x) identical(round(tan(eval(parse(text = gsub(\"/\", \"%:%\", deparse(substitute(x)))))), (prec/10)), mpfr(1, prec))\n", "language": "R" }, { "code": "tanident_1( 1*atan(1/2) + 1*atan(1/3) )\n## [1] TRUE\ntanident_1( 2*atan(1/3) + 1*atan(1/7))\n## [1] TRUE\ntanident_1( 4*atan(1/5) + -1*atan(1/239))\n## [1] TRUE\ntanident_1( 5*atan(1/7) + 2*atan(3/79))\n## [1] TRUE\ntanident_1( 5*atan(29/278) + 7*atan(3/79))\n## [1] TRUE\ntanident_1( 1*atan(1/2) + 1*atan(1/5) + 1*atan(1/8) )\n## [1] TRUE\ntanident_1( 4*atan(1/5) + -1*atan(1/70) + 1*atan(1/99) )\n## [1] TRUE\ntanident_1( 5*atan(1/7) + 4*atan(1/53) + 2*atan(1/4443))\n## [1] TRUE\ntanident_1( 6*atan(1/8) + 2*atan(1/57) + 1*atan(1/239))\n## [1] TRUE\ntanident_1( 8*atan(1/10) + -1*atan(1/239) + -4*atan(1/515))\n## [1] TRUE\ntanident_1(12*atan(1/18) + 8*atan(1/57) + -5*atan(1/239))\n## [1] TRUE\ntanident_1(16*atan(1/21) + 3*atan(1/239) + 4*atan(3/1042))\n## [1] TRUE\ntanident_1(22*atan(1/28) + 2*atan(1/443) + -5*atan(1/1393) + -10*atan(1/11018))\n## [1] TRUE\ntanident_1(22*atan(1/38) + 17*atan(7/601) + 10*atan(7/8149))\n## [1] TRUE\ntanident_1(44*atan(1/57) + 7*atan(1/239) + -12*atan(1/682) + 24*atan(1/12943))\n## [1] TRUE\ntanident_1(88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68*atan(1/12943))\n## [1] TRUE\ntanident_1(88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68*atan(1/12944))\n## [1] FALSE\n", "language": "R" }, { "code": "#lang racket\n(define (reduce e)\n (match e\n [(? number? a) a]\n [(list '+ (? number? a) (? number? b)) (+ a b)]\n [(list '- (? number? a) (? number? b)) (- a b)]\n [(list '- (? number? a)) (- a)]\n [(list '* (? number? a) (? number? b)) (* a b)]\n [(list '/ (? number? a) (? number? b)) (/ a b)]\n [(list '+ a b) (reduce `(+ ,(reduce a) ,(reduce b)))]\n [(list '- a b) (reduce `(- ,(reduce a) ,(reduce b)))]\n [(list '- a) (reduce `(- ,(reduce a)))]\n [(list '* a b) (reduce `(* ,(reduce a) ,(reduce b)))]\n [(list '/ a b) (reduce `(/ ,(reduce a) ,(reduce b)))]\n [(list 'tan (list 'arctan a)) (reduce a)]\n [(list 'tan (list '- a)) (reduce `(- ,(reduce `(tan ,a))))]\n [(list 'tan (list '+ a b)) (reduce `(/ (+ (tan ,a) (tan ,b))\n (- 1 (* (tan ,a) (tan ,b)))))]\n [(list 'tan (list '+ a b c ...)) (reduce `(tan (+ ,a (+ ,b ,@c))))]\n [(list 'tan (list '- a b)) (reduce `(/ (+ (tan ,a) (tan (- ,b)))\n (- 1 (* (tan ,a) (tan (- ,b))))))]\n [(list 'tan (list '* 1 a)) (reduce `(tan ,a))]\n [(list 'tan (list '* (? number? n) a))\n (cond [(< n 0) (reduce `(- (tan (* ,(- n) ,a))))]\n [(= n 0) 0]\n [(even? n) (reduce `(tan (+ (* ,(/ n 2) ,a) (* ,(/ n 2) ,a))))]\n [else (reduce `(tan (+ ,a (* ,(- n 1) ,a))))])]))\n\n(define correct-formulas\n '((tan (+ (arctan 1/2) (arctan 1/3)))\n (tan (+ (* 2 (arctan 1/3)) (arctan 1/7)))\n (tan (- (* 4 (arctan 1/5)) (arctan 1/239)))\n (tan (+ (* 5 (arctan 1/7)) (* 2 (arctan 3/79))))\n (tan (+ (* 5 (arctan 29/278)) (* 7 (arctan 3/79))))\n (tan (+ (arctan 1/2) (arctan 1/5) (arctan 1/8)))\n (tan (+ (* 4 (arctan 1/5)) (* -1 (arctan 1/70)) (arctan 1/99)))\n (tan (+ (* 5 (arctan 1/7)) (* 4 (arctan 1/53)) (* 2 (arctan 1/4443))))\n (tan (+ (* 6 (arctan 1/8)) (* 2 (arctan 1/57)) (arctan 1/239)))\n (tan (+ (* 8 (arctan 1/10)) (* -1 (arctan 1/239)) (* -4 (arctan 1/515))))\n (tan (+ (* 12 (arctan 1/18)) (* 8 (arctan 1/57)) (* -5 (arctan 1/239))))\n (tan (+ (* 16 (arctan 1/21)) (* 3 (arctan 1/239)) (* 4 (arctan 3/1042))))\n (tan (+ (* 22 (arctan 1/28)) (* 2 (arctan 1/443)) (* -5 (arctan 1/1393)) (* -10 (arctan 1/11018))))\n (tan (+ (* 22 (arctan 1/38)) (* 17 (arctan 7/601)) (* 10 (arctan 7/8149))))\n (tan (+ (* 44 (arctan 1/57)) (* 7 (arctan 1/239)) (* -12 (arctan 1/682)) (* 24 (arctan 1/12943))))\n (tan (+ (* 88 (arctan 1/172)) (* 51 (arctan 1/239)) (* 32 (arctan 1/682))\n (* 44 (arctan 1/5357)) (* 68 (arctan 1/12943))))))\n\n(define wrong-formula\n '(tan (+ (* 88 (arctan 1/172)) (* 51 (arctan 1/239)) (* 32 (arctan 1/682))\n (* 44 (arctan 1/5357)) (* 68 (arctan 1/12944)))))\n\n(displayln \"Do all correct formulas reduce to 1?\")\n(for/and ([f correct-formulas]) (= 1 (reduce f)))\n\n(displayln \"The incorrect formula reduces to:\")\n(reduce wrong-formula)\n", "language": "Racket" }, { "code": "Do all correct formulas reduce to 1?\n#t\nThe incorrect formula reduces to:\n1009288018000944050967896710431587186456256928584351786643498522649995492271475761189348270710224618853590682465929080006511691833816436374107451368838065354726517908250456341991684635768915704374493675498637876700129004484434187627909285979251682006538817341793224963346197503893270875008524149334251672855130857035205217929335932890740051319216343365800342290782260673215928499123722781078448297609548233999010983373327601187505623621602789012550584784738082074783523787011976757247516095289966708782862528690942242793667539020699840402353522108223/1009288837315638583415701528780402795721935641614456853534313491853293025565940011104051964874275710024625850092154664245109626053906509780125743180758231049920425664246286578958307532545458843067352531217230461290763258378749459637420702619029075083089762088232401888676895047947363883809724322868121990870409574061477638203859217672620508200713073485398199091153535700094640095900731630771349477187594074169815106104524371099618096164871416282464532355211521113449237814080332335526420331468258917484010722587072087349909684004660371264507984339711\n", "language": "Racket" }, { "code": "sub taneval ($coef, $f) {\n return 0 if $coef == 0;\n return $f if $coef == 1;\n return -taneval(-$coef, $f) if $coef < 0;\n\n my $a = taneval($coef+>1, $f);\n my $b = taneval($coef - $coef+>1, $f);\n ($a+$b)/(1-$a*$b);\n}\n\nsub tans (@xs) {\n return taneval(@xs[0;0], @xs[0;1].FatRat) if @xs == 1;\n\n my $a = tans(@xs[0 .. (-1+@xs+>1)]);\n my $b = tans(@xs[(-1+@xs+>1)+1 .. -1+@xs]);\n ($a+$b)/(1-$a*$b);\n}\n\nsub verify (@eqn) {\n printf \"%5s (%s)\\n\", (tans(@eqn) == 1) ?? \"OK\" !! \"Error\",\n (map { \"[{.[0]} {.[1].nude.join('/')}]\" }, @eqn).join(' ');\n}\n\nverify($_) for\n ([[1,1/2], [1,1/3]],\n [[2,1/3], [1,1/7]],\n [[4,1/5], [-1,1/239]],\n [[5,1/7], [2,3/79]],\n [[5,29/278], [7,3/79]],\n [[1,1/2], [1,1/5], [1,1/8]],\n [[4,1/5], [-1,1/70], [1,1/99]],\n [[5,1/7], [4,1/53], [2,1/4443]],\n [[6,1/8], [2,1/57], [1,1/239]],\n [[8,1/10], [-1,1/239], [-4,1/515]],\n [[12,1/18], [8,1/57], [-5,1/239]],\n [[16,1/21], [3,1/239], [4,3/1042]],\n [[22,1/28], [2,1/443], [-5,1/1393], [-10,1/11018]],\n [[22,1/38], [17,7/601], [10,7/8149]],\n [[44,1/57], [7,1/239], [-12,1/682], [24,1/12943]],\n [[88,1/172], [51,1/239], [32,1/682], [44,1/5357], [68,1/12943]],\n [[88,1/172], [51,1/239], [32,1/682], [44,1/5357], [68,1/21944]]\n );\n", "language": "Raku" }, { "code": "/*REXX program evaluates some Machin─like formulas and verifies their veracity. */\n@.=; pi= pi(); numeric digits( length(pi) ) - length(.); numeric fuzz 3\nsay center(' computing with ' digits() \" decimal digits \", 110, '═')\[email protected] = 'pi/4 = atan(1/2) + atan(1/3)'\[email protected] = 'pi/4 = 2*atan(1/3) + atan(1/7)'\[email protected] = 'pi/4 = 4*atan(1/5) - atan(1/239)'\[email protected] = 'pi/4 = 5*atan(1/7) + 2*atan(3/79)'\[email protected] = 'pi/4 = 5*atan(29/278) + 7*atan(3/79)'\[email protected] = 'pi/4 = atan(1/2) + atan(1/5) + atan(1/8)'\[email protected] = 'pi/4 = 4*atan(1/5) - atan(1/70) + atan(1/99)'\[email protected] = 'pi/4 = 5*atan(1/7) + 4*atan(1/53) + 2*atan(1/4443)'\[email protected] = 'pi/4 = 6*atan(1/8) + 2*atan(1/57) + atan(1/239)'\[email protected]= 'pi/4 = 8*atan(1/10) - atan(1/239) - 4*atan(1/515)'\[email protected]= 'pi/4 = 12*atan(1/18) + 8*atan(1/57) - 5*atan(1/239)'\[email protected]= 'pi/4 = 16*atan(1/21) + 3*atan(1/239) + 4*atan(3/1042)'\[email protected]= 'pi/4 = 22*atan(1/28) + 2*atan(1/443) - 5*atan(1/1393) - 10*atan(1/11018)'\[email protected]= 'pi/4 = 22*atan(1/38) + 17*atan(7/601) + 10*atan(7/8149)'\[email protected]= 'pi/4 = 44*atan(1/57) + 7*atan(1/239) - 12*atan(1/682) + 24*atan(1/12943)'\[email protected]= 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68 *atan(1/12943)'\[email protected]= 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68 *atan(1/12944)'\[email protected]= 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 67.9999999994*atan(1/12943)'\n\n do j=1 while @.j\\=='' /*evaluate each \"Machin─like\" formulas.*/\n interpret 'answer=' @.j /*where REXX does the heavy lifting. */\n say right( word( 'bad OK', answer + 1), 3)\": \" @.j\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\npi: return 3.141592653589793238462643383279502884197169399375105820974944592307816406286\nAcos: procedure; parse arg x; return pi() * .5 - Asin(x)\nAtan: procedure; arg x; if abs(x)=1 then return pi()/4*sign(x); return Asin(x/sqrt(1+x*x))\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nAsin: procedure; parse arg x 1 z 1 o 1 p; a=abs(x); aa=a*a\n if a>=sqrt(2)*.5 then return sign(x) * Acos( sqrt(1 - aa) )\n do j=2 by 2 until p=z; p=z; o=o*aa*(j-1)/j; z=z+o/(j+1); end /*j*/; return z\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; h=d+6; numeric form\n numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_ % 2\n do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/\n do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g\n", "language": "REXX" }, { "code": "$ include \"seed7_05.s7i\";\n include \"bigint.s7i\";\n include \"bigrat.s7i\";\n\nconst type: mTerms is array array bigInteger;\n\nconst array mTerms: testCases is [] (\n [] ([] ( 1_, 1_, 2_), [] ( 1_, 1_, 3_)),\n [] ([] ( 2_, 1_, 3_), [] ( 1_, 1_, 7_)),\n [] ([] ( 4_, 1_, 5_), [] (-1_, 1_, 239_)),\n [] ([] ( 5_, 1_, 7_), [] ( 2_, 3_, 79_)),\n [] ([] ( 1_, 1_, 2_), [] ( 1_, 1_, 5_), [] ( 1_, 1_, 8_)),\n [] ([] ( 4_, 1_, 5_), [] (-1_, 1_, 70_), [] ( 1_, 1_, 99_)),\n [] ([] ( 5_, 1_, 7_), [] ( 4_, 1_, 53_), [] ( 2_, 1_, 4443_)),\n [] ([] ( 6_, 1_, 8_), [] ( 2_, 1_, 57_), [] ( 1_, 1_, 239_)),\n [] ([] ( 8_, 1_, 10_), [] (-1_, 1_, 239_), [] ( -4_, 1_, 515_)),\n [] ([] (12_, 1_, 18_), [] ( 8_, 1_, 57_), [] ( -5_, 1_, 239_)),\n [] ([] (16_, 1_, 21_), [] ( 3_, 1_, 239_), [] ( 4_, 3_, 1042_)),\n [] ([] (22_, 1_, 28_), [] ( 2_, 1_, 443_), [] ( -5_, 1_, 1393_), [] (-10_, 1_, 11018_)),\n [] ([] (22_, 1_, 38_), [] (17_, 7_, 601_), [] ( 10_, 7_, 8149_)),\n [] ([] (44_, 1_, 57_), [] ( 7_, 1_, 239_), [] (-12_, 1_, 682_), [] ( 24_, 1_, 12943_)),\n [] ([] (88_, 1_, 172_), [] (51_, 1_, 239_), [] ( 32_, 1_, 682_), [] ( 44_, 1_, 5357_), [] (68_, 1_, 12943_)),\n [] ([] (88_, 1_, 172_), [] (51_, 1_, 239_), [] ( 32_, 1_, 682_), [] ( 44_, 1_, 5357_), [] (68_, 1_, 12944_))\n );\n\nconst func bigRational: tanEval (in bigInteger: coef, in bigRational: f) is func\n result\n var bigRational: tanEval is bigRational.value;\n local\n var bigRational: a is bigRational.value;\n var bigRational: b is bigRational.value;\n begin\n if coef = 1_ then\n tanEval := f;\n elsif coef < 0_ then\n tanEval := -tanEval(-coef, f);\n else\n a := tanEval(coef div 2_, f);\n b := tanEval(coef - coef div 2_, f);\n tanEval := (a + b) / (1_/1_ - a * b);\n end if;\n end func;\n\nconst func bigRational: tans (in mTerms: terms) is func\n result\n var bigRational: tans is bigRational.value;\n local\n var bigRational: a is bigRational.value;\n var bigRational: b is bigRational.value;\n begin\n if length(terms) = 1 then\n tans := tanEval(terms[1][1], terms[1][2] / terms[1][3]);\n else\n a := tans(terms[.. length(terms) div 2]);\n b := tans(terms[succ(length(terms) div 2) ..]);\n tans := (a + b) / (1_/1_ - a * b);\n end if;\n end func;\n\nconst proc: main is func\n local\n var integer: index is 0;\n var array bigInteger: term is 0 times 0_;\n begin\n for key index range testCases do\n write(tans(testCases[index]) = 1_/1_ <& \": pi/4 = \");\n for term range testCases[index] do\n write([0] (\"+\", \"-\")[ord(term[1] < 0_)] <& abs(term[1]) <& \"*arctan(\" <& term[2] <& \"/\" <& term[3] <& \")\");\n end for;\n writeln;\n end for;\n end func;\n", "language": "Seed7" }, { "code": "var equationtext = <<'EOT'\n pi/4 = arctan(1/2) + arctan(1/3)\n pi/4 = 2*arctan(1/3) + arctan(1/7)\n pi/4 = 4*arctan(1/5) - arctan(1/239)\n pi/4 = 5*arctan(1/7) + 2*arctan(3/79)\n pi/4 = 5*arctan(29/278) + 7*arctan(3/79)\n pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)\n pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)\n pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)\n pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)\n pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)\n pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)\n pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)\n pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)\n pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)\n pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)\n pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)\n pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)\nEOT\n\nfunc parse_eqn(equation) {\n static eqn_re = %r{\n (^ \\s* pi/4 \\s* = \\s* )? # LHS of equation\n (?: # RHS\n \\s* ( [-+] )? \\s*\n (?: ( \\d+ ) \\s* \\*)?\n \\s* arctan\\((.*?)\\)\n )}x\n\n gather {\n for lhs,sign,mult,rat in (equation.findall(eqn_re)) {\n take([\n [+1, -1][sign == '-'] * (mult ? Num(mult) : 1),\n Num(rat)\n ])\n }\n }\n}\n\nfunc tanEval(coef, f) {\n return f if (coef == 1)\n return -tanEval(-coef, f) if (coef < 0)\n var ca = coef>>1\n var cb = (coef - ca)\n var (a, b) = (tanEval(ca, f), tanEval(cb, f))\n (a + b) / (1 - a*b)\n}\n\nfunc tans(xs) {\n var xslen = xs.len\n return tanEval(xs[0]...) if (xslen == 1)\n var (aa, bb) = xs.part(xslen>>1)\n var (a, b) = (tans(aa), tans(bb))\n (a + b) / (1 - a*b)\n}\n\nvar machins = equationtext.lines.map(parse_eqn)\n\nfor machin,eqn in (machins ~Z equationtext.lines) {\n var ans = tans(machin)\n printf(\"%5s: %s\\n\", (ans == 1 ? 'OK' : 'ERROR'), eqn)\n}\n", "language": "Sidef" }, { "code": "package require Tcl 8.5\n\n# Compute tan(atan(p)+atan(q)) using rationals\nproc tadd {p q} {\n lassign $p pp pq\n lassign $q qp qq\n set topp [expr {$pp*$qq + $qp*$pq}]\n set topq [expr {$pq*$qq}]\n set prodp [expr {$pp*$qp}]\n set prodq [expr {$pq*$qq}]\n set lowp [expr {$prodq - $prodp}]\n set resultp [set gcd1 [expr {$topp * $prodq}]]\n set resultq [set gcd2 [expr {$topq * $lowp}]]\n # Critical! Normalize using the GCD\n while {$gcd2 != 0} {\n\tlassign [list $gcd2 [expr {$gcd1 % $gcd2}]] gcd1 gcd2\n }\n list [expr {$resultp / abs($gcd1)}] [expr {$resultq / abs($gcd1)}]\n}\nproc termTan {n a b} {\n if {$n < 0} {\n\tset n [expr {-$n}]\n\tset a [expr {-$a}]\n }\n if {$n == 1} {\n\treturn [list $a $b]\n }\n set k [expr {$n - [set m [expr {$n / 2}]]*2}]\n set t2 [termTan $m $a $b]\n set m2 [tadd $t2 $t2]\n if {$k == 0} {\n\treturn $m2\n }\n return [tadd [termTan $k $a $b] $m2]\n}\nproc machinTan {terms} {\n set sum {0 1}\n foreach term $terms {\n\tset sum [tadd $sum [termTan {*}$term]]\n }\n return $sum\n}\n\n# Assumes that the formula is in the very specific form below!\nproc parseFormula {formula} {\n set RE {(-?\\s*\\d*\\s*\\*?)\\s*arctan\\s*\\(\\s*(-?\\s*\\d+)\\s*/\\s*(-?\\s*\\d+)\\s*\\)}\n set nospace {\" \" \"\" \"*\" \"\"}\n foreach {all n a b} [regexp -inline -all $RE $formula] {\n\tif {![regexp {\\d} $n]} {append n 1}\n\tlappend result [list [string map $nospace $n] [string map $nospace $a] [string map $nospace $b]]\n }\n return $result\n}\n\nforeach formula {\n \"pi/4 = arctan(1/2) + arctan(1/3)\"\n \"pi/4 = 2*arctan(1/3) + arctan(1/7)\"\n \"pi/4 = 4*arctan(1/5) - arctan(1/239)\"\n \"pi/4 = 5*arctan(1/7) + 2*arctan(3/79)\"\n \"pi/4 = 5*arctan(29/278) + 7*arctan(3/79)\"\n \"pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)\"\n \"pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)\"\n \"pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)\"\n \"pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)\"\n \"pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)\"\n \"pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)\"\n \"pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)\"\n \"pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)\"\n \"pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)\"\n \"pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)\"\n \"pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)\"\n \"pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)\"\n} {\n if {[tcl::mathop::== {*}[machinTan [parseFormula $formula]]]} {\n\tputs \"Yes! '$formula' is true\"\n } else {\n\tputs \"No! '$formula' not true\"\n }\n}\n", "language": "Tcl" }, { "code": "Imports System.Numerics\n\nPublic Class BigRat ' Big Rational Class constructed with BigIntegers\n Implements IComparable\n Public nu, de As BigInteger\n Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),\n One = New BigRat(BigInteger.One, BigInteger.One)\n Sub New(bRat As BigRat)\n nu = bRat.nu : de = bRat.de\n End Sub\n Sub New(n As BigInteger, d As BigInteger)\n If d = BigInteger.Zero Then _\n Throw (New Exception(String.Format(\"tried to set a BigRat with ({0}/{1})\", n, d)))\n Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)\n If bi > BigInteger.One Then n /= bi : d /= bi\n If d < BigInteger.Zero Then n = -n : d = -d\n nu = n : de = d\n End Sub\n Shared Operator -(x As BigRat) As BigRat\n Return New BigRat(-x.nu, x.de)\n End Operator\n Shared Operator +(x As BigRat, y As BigRat)\n Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)\n End Operator\n Shared Operator -(x As BigRat, y As BigRat) As BigRat\n Return x + (-y)\n End Operator\n Shared Operator *(x As BigRat, y As BigRat) As BigRat\n Return New BigRat(x.nu * y.nu, x.de * y.de)\n End Operator\n Shared Operator /(x As BigRat, y As BigRat) As BigRat\n Return New BigRat(x.nu * y.de, x.de * y.nu)\n End Operator\n Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo\n Dim dif As BigRat = New BigRat(nu, de) - obj\n If dif.nu < BigInteger.Zero Then Return -1\n If dif.nu > BigInteger.Zero Then Return 1\n Return 0\n End Function\n Shared Operator =(x As BigRat, y As BigRat) As Boolean\n Return x.CompareTo(y) = 0\n End Operator\n Shared Operator <>(x As BigRat, y As BigRat) As Boolean\n Return x.CompareTo(y) <> 0\n End Operator\n Overrides Function ToString() As String\n If de = BigInteger.One Then Return nu.ToString\n Return String.Format(\"({0}/{1})\", nu, de)\n End Function\n Shared Function Combine(a As BigRat, b As BigRat) As BigRat\n Return (a + b) / (BigRat.One - (a * b))\n End Function\nEnd Class\n\nPublic Structure Term ' coefficent, BigRational construction for each term\n Dim c As Integer, br As BigRat\n Sub New(cc As Integer, bigr As BigRat)\n c = cc : br = bigr\n End Sub\nEnd Structure\n\nModule Module1\n Function Eval(c As Integer, x As BigRat) As BigRat\n If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)\n Dim hc As Integer = c \\ 2\n Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))\n End Function\n\n Function Sum(terms As List(Of Term)) As BigRat\n If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)\n Dim htc As Integer = terms.Count / 2\n Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))\n End Function\n\n Function ParseLine(ByVal s As String) As List(Of Term)\n ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)\n While t.Contains(\" \") : t = t.Replace(\" \", \"\") : End While\n p = t.IndexOf(\"pi/4=\") : If p < 0 Then _\n Console.WriteLine(\"warning: tan(left side of equation) <> 1\") : ParseLine.Add(x) : Exit Function\n t = t.Substring(p + 5)\n For Each item As String In t.Split(\")\")\n If item.Length > 5 Then\n If (Not item.Contains(\"tan\") OrElse item.IndexOf(\"a\") < 0 OrElse\n item.IndexOf(\"a\") > item.IndexOf(\"tan\")) AndAlso Not item.Contains(\"atn\") Then\n Console.WriteLine(\"warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]\", item)\n ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function\n End If\n x.c = 1 : x.br = New BigRat(BigRat.One)\n p = item.IndexOf(\"/\") : If p > 0 Then\n x.br.de = UInt64.Parse(item.Substring(p + 1))\n item = item.Substring(0, p)\n p = item.IndexOf(\"(\") : If p > 0 Then\n x.br.nu = UInt64.Parse(item.Substring(p + 1))\n p = item.IndexOf(\"a\") : If p > 0 Then\n Integer.TryParse(item.Substring(0, p).Replace(\"*\", \"\"), x.c)\n If x.c = 0 Then x.c = 1\n If item.Contains(\"-\") AndAlso x.c > 0 Then x.c = -x.c\n End If\n ParseLine.Add(x)\n End If\n End If\n End If\n Next\n End Function\n\n Sub Main(ByVal args As String())\n Dim nl As String = vbLf\n For Each item In (\"pi/4 = ATan(1 / 2) + ATan(1/3)\" & nl &\n \"pi/4 = 2Atan(1/3) + ATan(1/7)\" & nl &\n \"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)\" & nl &\n \"pi/4 = 5arctan(1/7) + 2 * atan(3/79)\" & nl &\n \"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)\" & nl &\n \"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)\" & nl &\n \"PI/4 = 4ATan(1/5) - Atan(1/70) + ATan(1/99)\" & nl &\n \"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)\" & nl &\n \"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)\" & nl &\n \"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)\" & nl &\n \"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)\" & nl &\n \"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)\" & nl &\n \"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393) - 10 ATan( 1 / 11018 )\" & nl &\n \"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 / 8149)\" & nl &\n \"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)\" & nl &\n \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)\" & nl &\n \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)\").Split(nl)\n Console.WriteLine(\"{0}: {1}\", If(Sum(ParseLine(item)) = BigRat.One, \"Pass\", \"Fail\"), item)\n Next\n End Sub\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./big\" for BigRat\nimport \"./fmt\" for Fmt\n\n/** represents a term of the form: c * atan(n / d) */\nclass Term {\n construct new(c, n, d) {\n _c = c\n _n = n\n _d = d\n }\n\n c { _c }\n n { _n }\n d { _d }\n\n toString {\n var a = \"atan(%(n)/%(d))\"\n return ((_c == 1) ? \" + \" :\n (_c == -1) ? \" - \" :\n (_c < 0) ? \" - %(-c)*\" : \" + %(c)*\") + a\n }\n}\n\nvar tanEval // recursive function\ntanEval = Fn.new { |c, f|\n if (c == 1) return f\n if (c < 0) return -tanEval.call(-c, f)\n var ca = (c/2).truncate\n var cb = c - ca\n var a = tanEval.call(ca, f)\n var b = tanEval.call(cb, f)\n return (a + b) / (BigRat.one - (a * b))\n}\n\nvar tanSum // recursive function\ntanSum = Fn.new { |terms|\n if (terms.count == 1) return tanEval.call(terms[0].c, BigRat.new(terms[0].n, terms[0].d))\n var half = (terms.count/2).floor\n var a = tanSum.call(terms.take(half).toList)\n var b = tanSum.call(terms.skip(half).toList)\n return (a + b) / (BigRat.one - (a * b))\n}\n\nvar T = Term // type alias\n\nvar termsList = [\n [T.new(1, 1, 2), T.new(1, 1, 3)],\n [T.new(2, 1, 3), T.new(1, 1, 7)],\n [T.new(4, 1, 5), T.new(-1, 1, 239)],\n [T.new(5, 1, 7), T.new(2, 3, 79)],\n [T.new(5, 29, 278), T.new(7, 3, 79)],\n [T.new(1, 1, 2), T.new(1, 1, 5), T.new(1, 1, 8)],\n [T.new(4, 1, 5), T.new(-1, 1, 70), T.new(1, 1, 99)],\n [T.new(5, 1, 7), T.new(4, 1, 53), T.new(2, 1, 4443)],\n [T.new(6, 1, 8), T.new(2, 1, 57), T.new(1, 1, 239)],\n [T.new(8, 1, 10), T.new(-1, 1, 239), T.new(-4, 1, 515)],\n [T.new(12, 1, 18), T.new(8, 1, 57), T.new(-5, 1, 239)],\n [T.new(16, 1, 21), T.new(3, 1, 239), T.new(4, 3, 1042)],\n [T.new(22, 1, 28), T.new(2, 1, 443), T.new(-5, 1, 1393), T.new(-10, 1, 11018)],\n [T.new(22, 1, 38), T.new(17, 7, 601), T.new(10, 7, 8149)],\n [T.new(44, 1, 57), T.new(7, 1, 239), T.new(-12, 1, 682), T.new(24, 1, 12943)],\n [T.new(88, 1, 172), T.new(51, 1, 239), T.new(32, 1, 682), T.new(44, 1, 5357), T.new(68, 1, 12943)],\n [T.new(88, 1, 172), T.new(51, 1, 239), T.new(32, 1, 682), T.new(44, 1, 5357), T.new(68, 1, 12944)]\n]\n\nfor (terms in termsList) {\n var f = Fmt.swrite(\"$-5s: 1 == tan(\", tanSum.call(terms) == BigRat.one)\n System.write(f)\n System.write(terms[0].toString.skip(3).join())\n for (i in 1...terms.count) System.write(terms[i])\n System.print(\")\")\n}\n", "language": "Wren" }, { "code": "code ChOut=8, Text=12; \\intrinsic routines\nint Number(18); \\numbers from equations\ndef LF=$0A; \\ASCII line feed (end-of-line character)\n\nfunc Parse(S); \\Convert numbers in string S to binary in Number array\nchar S;\nint I, Neg;\n\n proc GetNum; \\Get number from string S\n int N;\n [while S(0)<^0 ! S(0)>^9 do S:= S+1;\n N:= S(0)-^0; S:= S+1;\n while S(0)>=^0 & S(0)<=^9 do\n [N:= N*10 + S(0) - ^0; S:= S+1];\n Number(I):= N; I:= I+1;\n ];\n\n[while S(0)#^= do S:= S+1; \\skip to \"=\"\nI:= 0;\nloop [Neg:= false; \\assume positive term\n loop [S:= S+1; \\next char\n case S(0) of\n LF: [Number(I):= 0; return S+1]; \\mark end of array\n ^-: Neg:= true; \\term is negative\n ^a: [Number(I):= 1; I:= I+1; quit] \\no coefficient so use 1\n other if S(0)>=^0 & S(0)<=^9 then \\if digit\n [S:= S-1; GetNum; quit]; \\backup and get number\n ];\n GetNum; \\numerator\n if Neg then Number(I-1):= -Number(I-1); \\tan(-a) = -tan(a)\n GetNum; \\denominator\n ];\n];\n\n\nfunc GCD(U, V); \\Return the greatest common divisor of U and V\nint U, V;\nint T;\n[while V do \\Euclid's method\n [T:= U; U:= V; V:= rem(T/V)];\nreturn abs(U);\n];\n\nproc Verify; \\Verify that tangent of equation = 1 (i.e: E = F)\nint E, F, I, J;\n\n proc Machin(A, B, C, D);\n int A, B, C, D;\n int Div;\n \\tan(a+b) = (tan(a) + tan(b)) / (1 - tan(a)*tan(b))\n \\tan(arctan(A/B) + arctan(C/D))\n \\ = (tan(arctan(A/B)) + tan(arctan(C/D))) / (1 - tan(arctan(A/B))*tan(arctan(C/D)))\n \\ = (A/B + C/D) / (1 - A/B*C/D)\n \\ = (A*D/B*D + B*C/B*D) / (B*D/B*D - A*C/B*D)\n \\ = (A*D + B*C) / (B*D - A*C)\n [E:= A*D + B*C; F:= B*D - A*C;\n Div:= GCD(E, F); \\keep integers from getting too big\n E:= E/Div; F:= F/Div;\n ];\n\n[E:= 0; F:= 1; I:= 0;\nwhile Number(I) do\n [for J:= 1 to Number(I) do\n Machin(E, F, Number(I+1), Number(I+2));\n I:= I+3;\n ];\nText(0, if E=F then \"Yes \" else \"No \");\n];\n\n\nchar S, SS; int I;\n[S:= \"pi/4 = arctan(1/2) + arctan(1/3)\npi/4 = 2*arctan(1/3) + arctan(1/7)\npi/4 = 4*arctan(1/5) - arctan(1/239)\npi/4 = 5*arctan(1/7) + 2*arctan(3/79)\npi/4 = 5*arctan(29/278) + 7*arctan(3/79)\npi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)\npi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)\npi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)\npi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)\npi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)\npi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)\npi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)\npi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)\npi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)\npi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)\npi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)\npi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)\n \"; \\Python version of equations (thanks!)\nfor I:= 1 to 17 do\n [SS:= S; \\save start of string line\n S:= Parse(S); \\returns start of next line\n Verify; \\correct Machin equation? Yes or No\n repeat ChOut(0, SS(0)); SS:= SS+1 until SS(0)=LF; ChOut(0, LF); \\show equation\n ];\n]\n", "language": "XPL0" } ]
Check-Machin-like-formulas
[ { "code": "---\ncategory:\n- Hardware\n- Terminal control\n- Initialization\nfrom: http://rosettacode.org/wiki/Check_output_device_is_a_terminal\n", "language": "00-META" }, { "code": ";Task:\nDemonstrate how to check whether the output device is a terminal or not.\n\n\n;Related task:\n* &nbsp; [[Check input device is a terminal]]\n<br><br>\n", "language": "00-TASK" }, { "code": "LDA $D011 ;screen control register 1\nAND #%00100000 ;bit 5 clear = text mode, bit 5 set = gfx mode\nBEQ isTerminal\n", "language": "6502-Assembly" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\nwith Interfaces.C_Streams; use Interfaces.C_Streams;\n\nprocedure Test_tty is\nbegin\n if Isatty(Fileno(Stdout)) = 0 then\n Put_Line(Standard_Error, \"stdout is not a tty.\");\n else\n Put_Line(Standard_Error, \"stdout is a tty.\");\n end if;\nend Test_tty;\n", "language": "Ada" }, { "code": "#include <unistd.h> // for isatty()\n#include <stdio.h> // for fileno()\n\nint main()\n{\n puts(isatty(fileno(stdout))\n ? \"stdout is tty\"\n : \"stdout is not tty\");\n return 0;\n}\n", "language": "C" }, { "code": "#if _WIN32\n#include <io.h>\n#define ISATTY _isatty\n#define FILENO _fileno\n#else\n#include <unistd.h>\n#define ISATTY isatty\n#define FILENO fileno\n#endif\n\n#include <iostream>\n\nint main() {\n if (ISATTY(FILENO(stdout))) {\n std::cout << \"stdout is a tty\\n\";\n } else {\n std::cout << \"stdout is not a tty\\n\";\n }\n\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\n\nnamespace CheckTerminal {\n class Program {\n static void Main(string[] args) {\n Console.WriteLine(\"Stdout is tty: {0}\", Console.IsOutputRedirected);\n }\n }\n}\n", "language": "C-sharp" }, { "code": " *>\n *> istty, check id fd 0 is a tty\n *> Tectonics: cobc -xj istty.cob\n *> echo \"test\" | ./istty\n *>\n identification division.\n program-id. istty.\n\n data division.\n working-storage section.\n 01 rc usage binary-long.\n\n procedure division.\n sample-main.\n\n call \"isatty\" using by value 0 returning rc\n display \"fd 0 tty: \" rc\n\n call \"isatty\" using by value 1 returning rc\n display \"fd 1 tty: \" rc upon syserr\n\n call \"isatty\" using by value 2 returning rc\n display \"fd 2 tty: \" rc\n\n goback.\n end program istty.\n", "language": "COBOL" }, { "code": "(with-open-stream (s *standard-output*)\n (format T \"stdout is~:[ not~;~] a terminal~%\"\n (interactive-stream-p s)))\n", "language": "Common-Lisp" }, { "code": "(ffi:clines \"\n #include <sys/ioctl.h>\n #include <unistd.h>\n int ttyPredicate() {\n return isatty(fileno(stdout));\n }\")\n\n(ffi:def-function\n (\"ttyPredicate\" c-ttyp)\n () :returning :int)\n\n(defun tty-p()\n (if (= 1 (c-ttyp))\n t\n nil))\n\n(format T \"stdout is~:[ not~;~] a terminal~%\" (tty-p))\n(quit)\n", "language": "Common-Lisp" }, { "code": "File.new(\"testfile\").tty? #=> false\nFile.new(\"/dev/tty\").tty? #=> true\nSTDOUT.tty? #=> true\n", "language": "Crystal" }, { "code": "import std.stdio;\n\nextern(C) int isatty(int);\n\nvoid main() {\n writeln(\"Stdout is tty: \", stdout.fileno.isatty == 1);\n}\n", "language": "D" }, { "code": "IN: scratchpad USE: unix.ffi\nIN: scratchpad 1 isatty\n\n--- Data stack:\n1\n", "language": "Factor" }, { "code": "Open Cons For Output As #1\n' Open Cons abre los flujos de entrada (stdin) o salida (stdout) estándar\n' de la consola para leer o escribir.\n\nIf Err > 0 Then\n Print #1, \"stdout is not a tty.\"\nElse\n Print #1, \"stdout is a tty.\"\nEnd If\nClose #1\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"os\"\n \"fmt\"\n)\n\nfunc main() {\n if fileInfo, _ := os.Stdout.Stat(); (fileInfo.Mode() & os.ModeCharDevice) != 0 {\n fmt.Println(\"Hello terminal\")\n } else {\n fmt.Println(\"Who are you? You're not a terminal\")\n }\n}\n", "language": "Go" }, { "code": "module Main where\n\n-- requires the unix package\n-- https://hackage.haskell.org/package/unix\nimport System.Posix.Terminal (queryTerminal)\nimport System.Posix.IO (stdOutput)\n\nmain :: IO ()\nmain = do\n istty <- queryTerminal stdOutput\n putStrLn\n (if istty\n then \"stdout is tty\"\n else \"stdout is not tty\")\n", "language": "Haskell" }, { "code": "3=nc<'wd'\n", "language": "J" }, { "code": "if isa(STDOUT, Base.TTY)\n println(\"This program sees STDOUT as a TTY.\")\nelse\n println(\"This program does not see STDOUT as a TTY.\")\nend\n", "language": "Julia" }, { "code": "// Kotlin Native version 0.5\n\nimport platform.posix.*\n\nfun main(args: Array<String>) {\n if (isatty(STDOUT_FILENO) != 0)\n println(\"stdout is a terminal\")\n else\n println(\"stdout is not a terminal\")\n}\n", "language": "Kotlin" }, { "code": "local function isTTY ( fd )\n fd = tonumber( fd ) or 1\n local ok, exit, signal = os.execute( string.format( \"test -t %d\", fd ) )\n return (ok and exit == \"exit\") and signal == 0 or false\nend\n\nprint( \"stdin\", isTTY( 0 ) )\nprint( \"stdout\", isTTY( 1 ) )\nprint( \"stderr\", isTTY( 2 ) )\n", "language": "Lua" }, { "code": "local unistd = require( \"posix.unistd\" )\n\nlocal function isTTY ( fd )\n fd = tonumber( fd ) or 1\n local ok, err, errno = unistd.isatty( fd )\n return ok and true or false\nend\n\nprint( \"stdin\", isTTY( 0 ) )\nprint( \"stdout\", isTTY( 1 ) )\nprint( \"stderr\", isTTY( 2 ) )\n", "language": "Lua" }, { "code": "def isTerm = System.Console.IsOutputRedirected;\n", "language": "Nemerle" }, { "code": "import terminal\n\nstderr.write if stdout.isatty: \"stdout is a terminal\\n\" else: \"stdout is not a terminal\\n\"\n", "language": "Nim" }, { "code": "let () =\n print_endline (\n if Unix.isatty Unix.stdout\n then \"Output goes to tty.\"\n else \"Output doesn't go to tty.\"\n )\n", "language": "OCaml" }, { "code": "(define (isatty? fd) (syscall 16 fd 19))\n(print (if (isatty? stdout)\n \"stdout is a tty.\"\n \"stdout is not a tty.\"))\n", "language": "Ol" }, { "code": "$ perl -e \"warn -t STDOUT ? 'Terminal' : 'Other'\"\nTerminal\n$ perl -e \"warn -t STDOUT ? 'Terminal' : 'Other'\" > x.tmp\nOther\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span> <span style=\"color: #000080;font-style:italic;\">-- (no input or output redirection in a browser!)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"stdin:%t, stdout:%t, stderr:%t\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">isatty</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">isatty</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">isatty</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)})</span>\n<!--\n", "language": "Phix" }, { "code": "if(posix_isatty(STDOUT)) {\n echo \"The output device is a terminal\".PHP_EOL;\n} else {\n echo \"The output device is NOT a terminal\".PHP_EOL;\n}\n", "language": "PHP" }, { "code": "from sys import stdout\nif stdout.isatty():\n print 'The output device is a teletype. Or something like a teletype.'\nelse:\n print 'The output device isn\\'t like a teletype.'\n", "language": "Python" }, { "code": " [ $ |from sys import stdout\nto_stack( 1 if stdout.isatty() else 0)|\n python ] is ttyout ( --> b )\n\n ttyout if\n [ say \"Looks like a teletype.\" ]\n else\n [ say \"Not a teletype.\" ]\n", "language": "Quackery" }, { "code": "(terminal-port? (current-output-port))\n", "language": "Racket" }, { "code": "/*REXX program determines if the STDIN is a terminal device or other. */\nsignal on syntax /*if syntax error, then jump ──► SYNTAX*/\nsay 'output device:' testSTDIN() /*displays terminal ──or── other */\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ntestSTDIN: syntax.=1; signal .; .: z.= sigl; call linein ,2; ..: syntax.= 0; return z..\n /* [↑] must/should be all on one line.*/\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsyntax: z..= 'other' /*when a SYNTAX error occurs, come here*/\nif syntax. then do /*are we handling STDIN thingy error?*/\n if sigl==z. then z..= 'terminal'; signal .. /*is this a stdin ?*/\n end /* [↑] can't use a RETURN here. */\n\n /* ··· handle other REXX syntax errors here ··· */\n", "language": "REXX" }, { "code": "f = File.open(\"test.txt\")\np f.isatty # => false\np STDOUT.isatty # => true\n", "language": "Ruby" }, { "code": "/* Uses C library interface */\n\nextern crate libc;\n\nfn main() {\n let istty = unsafe { libc::isatty(libc::STDOUT_FILENO as i32) } != 0;\n if istty {\n println!(\"stdout is tty\");\n } else {\n println!(\"stdout is not tty\");\n }\n}\n", "language": "Rust" }, { "code": "import org.fusesource.jansi.internal.CLibrary._\n\nobject IsATty extends App {\n\n var enabled = true\n\n def apply(enabled: Boolean): Boolean = {\n // We must be on some unix variant..\n try {\n enabled && isatty(STDOUT_FILENO) == 1\n }\n catch {\n case ignore: Throwable =>\n ignore.printStackTrace()\n false\n\n }\n }\n\n println(\"tty \" + apply(true))\n}\n", "language": "Scala" }, { "code": "val stdoutRefersToTerminal : bool = Posix.ProcEnv.isatty Posix.FileSys.stdout\n", "language": "Standard-ML" }, { "code": "print(isatty(STDOUT_FILENO) != 0 ? \"TTY\" : \"Not TTY\" )\n", "language": "Swift" }, { "code": "set toTTY [dict exists [fconfigure stdout] -mode]\nputs [expr {$toTTY ? \"Output goes to tty\" : \"Output doesn't go to tty\"}]\n", "language": "Tcl" }, { "code": "set toTTY [expr {![catch {fconfigure stdout -mode}]}]\n", "language": "Tcl" }, { "code": "#!/bin/sh\n\nif [ -t 1 ]\nthen\n echo \"Output is a terminal\"\nelse\n echo \"Output is NOT a terminal\" >/dev/tty\nfi\n", "language": "UNIX-Shell" }, { "code": "Module Module1\n\n Sub Main()\n Console.WriteLine(\"Stdout is tty: {0}\", Console.IsOutputRedirected)\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "/* Check_output_device_is_a_terminal.wren */\n\nclass C {\n foreign static isOutputDeviceTerminal\n}\n\nSystem.print(\"Output device is a terminal = %(C.isOutputDeviceTerminal)\")\n", "language": "Wren" }, { "code": "#include <stdlib.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <string.h>\n#include \"wren.h\"\n\nvoid C_isOutputDeviceTerminal(WrenVM* vm) {\n bool isTerminal = (bool)isatty(fileno(stdout));\n wrenSetSlotBool(vm, 0, isTerminal);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n WrenVM* vm,\n const char* module,\n const char* className,\n bool isStatic,\n const char* signature) {\n if (strcmp(module, \"main\") == 0) {\n if (strcmp(className, \"C\") == 0) {\n if (isStatic && strcmp(signature, \"isOutputDeviceTerminal\") == 0) {\n return C_isOutputDeviceTerminal;\n }\n }\n }\n return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n switch (errorType) {\n case WREN_ERROR_COMPILE:\n printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_STACK_TRACE:\n printf(\"[%s line %d] in %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_RUNTIME:\n printf(\"[Runtime Error] %s\\n\", msg);\n break;\n }\n}\n\nchar *readFile(const char *fileName) {\n FILE *f = fopen(fileName, \"r\");\n fseek(f, 0, SEEK_END);\n long fsize = ftell(f);\n rewind(f);\n char *script = malloc(fsize + 1);\n fread(script, 1, fsize, f);\n fclose(f);\n script[fsize] = 0;\n return script;\n}\n\nint main() {\n WrenConfiguration config;\n wrenInitConfiguration(&config);\n config.writeFn = &writeFn;\n config.errorFn = &errorFn;\n config.bindForeignMethodFn = &bindForeignMethod;\n WrenVM* vm = wrenNewVM(&config);\n const char* module = \"main\";\n const char* fileName = \"Check_output_device_is_a_terminal.wren\";\n char *script = readFile(fileName);\n WrenInterpretResult result = wrenInterpret(vm, module, script);\n switch (result) {\n case WREN_RESULT_COMPILE_ERROR:\n printf(\"Compile Error!\\n\");\n break;\n case WREN_RESULT_RUNTIME_ERROR:\n printf(\"Runtime Error!\\n\");\n break;\n case WREN_RESULT_SUCCESS:\n break;\n }\n wrenFreeVM(vm);\n free(script);\n return 0;\n}\n", "language": "Wren" }, { "code": "const S_IFCHR=0x2000;\nfcn S_ISCHR(f){ f.info()[4].bitAnd(S_IFCHR).toBool() }\nS_ISCHR(File.stdout).println();\n", "language": "Zkl" } ]
Check-output-device-is-a-terminal
[ { "code": "---\ncategory:\n- Simple\nfrom: http://rosettacode.org/wiki/Check_that_file_exists\nnote: File System Operations\n", "language": "00-META" }, { "code": ";Task:\nVerify that a file called &nbsp; &nbsp; '''input.txt''' &nbsp; &nbsp; and &nbsp; a directory called &nbsp; &nbsp; '''docs''' &nbsp; &nbsp; exist.\n \n\nThis should be done twice: &nbsp; \n:::* &nbsp; once for the current working directory, &nbsp; and\n:::* &nbsp; once for a file and a directory in the filesystem root.\n\n<br>\nOptional criteria (May 2015): &nbsp; verify it works with:\n:::* &nbsp; zero-length files\n:::* &nbsp; an unusual filename: &nbsp; <big> ''' `Abdu'l-Bahá.txt ''' </big>\n<br><br>\n", "language": "00-TASK" }, { "code": "fs:is_file(‘input.txt’)\nfs:is_file(‘/input.txt’)\nfs:is_dir(‘docs’)\nfs:is_dir(‘/docs’)\n", "language": "11l" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program verifFic64.s */\n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n.equ CHDIR, 49\n.equ AT_FDCWD, -100\n\n/*******************************************/\n/* Initialized data */\n/*******************************************/\n.data\nszMessFound1: .asciz \"File 1 found.\\n\"\nszMessFound2: .asciz \"File 2 found.\\n\"\nszMessNotFound1: .asciz \"File 1 not found.\\n\"\nszMessNotFound2: .asciz \"File 2 not found.\\n\"\nszMessDir2: .asciz \"File 2 is a directory.\\n\"\nszMessNotAuth2: .asciz \"File 2 permission denied.\\n\"\nszCarriageReturn: .asciz \"\\n\"\n\n/* areas strings */\nszPath2: .asciz \"/\"\nszFicName1: .asciz \"test1.txt\"\nszFicName2: .asciz \"root\"\n\n/*******************************************/\n/* UnInitialized data */\n/*******************************************/\n.bss\n/*******************************************/\n/* code section */\n/*******************************************/\n.text\n.global main\nmain: // entry of program\n\n /*************************************\n open file 1\n ************************************/\n mov x0,AT_FDCWD // current directory\n ldr x1,qAdrszFicName1 // file name\n mov x2,#O_RDWR // flags\n mov x3,#0 // mode\n mov x8, #OPEN // call system OPEN\n svc 0\n cmp x0,#0 // error ?\n ble 1f\n mov x1,x0 // FD\n ldr x0,qAdrszMessFound1\n bl affichageMess\n // close file\n mov x0,x1 // Fd\n mov x8, #CLOSE\n svc 0\n b 2f\n1:\n ldr x0,qAdrszMessNotFound1\n bl affichageMess\n2:\n /*************************************\n open file 2\n ************************************/\n ldr x0,qAdrszPath2\n mov x8,CHDIR // call system change directory\n svc 0\n mov x0,AT_FDCWD // current directory\n ldr x1,qAdrszFicName2 // file name\n mov x2,O_RDWR // flags\n mov x3,0 // mode\n mov x8,OPEN // call system OPEN\n svc 0\n cmp x0,-21 // is a directory ?\n beq 4f\n cmp x0,0 // error ?\n ble 3f\n mov x1,x0 // FD\n ldr x0,qAdrszMessFound2\n bl affichageMess\n // close file\n mov x0,x1 // Fd\n mov x8, #CLOSE\n svc 0\n b 100f\n3:\n ldr x0,qAdrszMessNotFound2\n bl affichageMess\n b 100f\n4:\n ldr x0,qAdrszMessDir2\n bl affichageMess\n100: // standard end of the program\n mov x0,0 // return code\n mov x8,EXIT // request to exit program\n svc 0 // perform the system call\nqAdrszFicName1: .quad szFicName1\nqAdrszFicName2: .quad szFicName2\nqAdrszMessFound1: .quad szMessFound1\nqAdrszMessFound2: .quad szMessFound2\nqAdrszMessNotFound1: .quad szMessNotFound1\nqAdrszMessNotFound2: .quad szMessNotFound2\nqAdrszMessNotAuth2: .quad szMessNotAuth2\nqAdrszPath2: .quad szPath2\nqAdrszMessDir2: .quad szMessDir2\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "BYTE lastError\n\nPROC MyError(BYTE errCode)\n lastError=errCode\nRETURN\n\nBYTE FUNC FileExists(CHAR ARRAY fname)\n DEFINE PTR=\"CARD\"\n PTR old\n BYTE dev=[1]\n\n lastError=0\n old=Error\n Error=MyError ;replace error handling to capture I/O error\n\n Close(dev)\n Open(dev,fname,4)\n Close(dev)\n\n Error=old ;restore the original error handling\n\n IF lastError=0 THEN\n RETURN (1)\n FI\nRETURN (0)\n\nPROC Test(CHAR ARRAY fname)\n BYTE exists\n\n exists=FileExists(fname)\n IF exists THEN\n PrintF(\"File \"\"%S\"\" exists.%E\",fname)\n ELSE\n PrintF(\"File \"\"%S\"\" does not exist.%E\",fname)\n FI\nRETURN\n\nPROC Main()\n Test(\"D:INPUT.TXT\")\n Test(\"D:DOS.SYS\")\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\n\nprocedure File_Exists is\n function Does_File_Exist (Name : String) return Boolean is\n The_File : Ada.Text_IO.File_Type;\n begin\n Open (The_File, In_File, Name);\n Close (The_File);\n return True;\n exception\n when Name_Error =>\n return False;\n end Does_File_Exist;\nbegin\n Put_Line (Boolean'Image (Does_File_Exist (\"input.txt\" )));\n Put_Line (Boolean'Image (Does_File_Exist (\"\\input.txt\")));\nend File_Exists;\n", "language": "Ada" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Directories; use Ada.Directories;\n\nprocedure File_Exists is\n procedure Print_File_Exist (Name : String) is\n begin\n Put_Line (\"Does \" & Name & \" exist? \" &\n Boolean'Image (Exists (Name)));\n end Print_File_Exist;\n procedure Print_Dir_Exist (Name : String) is\n begin\n Put_Line (\"Does directory \" & Name & \" exist? \" &\n Boolean'Image (Exists (Name) and then Kind (Name) = Directory));\n end Print_Dir_Exist;\nbegin\n Print_File_Exist (\"input.txt\" );\n Print_File_Exist (\"/input.txt\");\n Print_Dir_Exist (\"docs\");\n Print_Dir_Exist (\"/docs\");\nend File_Exists;\n", "language": "Ada" }, { "code": "function exists (filename) {\n return stat (filename) != null\n}\n\nexists (\"input.txt\")\nexists (\"/input.txt\")\nexists (\"docs\")\nexists (\"/docs\")\n", "language": "Aikido" }, { "code": "# Check files and directories exist #\n\n# check a file exists by attempting to open it for input #\n# returns TRUE if the file exists, FALSE otherwise #\nPROC file exists = ( STRING file name )BOOL:\n IF FILE f;\n open( f, file name, stand in channel ) = 0\n THEN\n # file opened OK so must exist #\n close( f );\n TRUE\n ELSE\n # file cannot be opened - assume it does not exist #\n FALSE\n FI # file exists # ;\n\n# print a suitable messages if the specified file exists #\nPROC test file exists = ( STRING name )VOID:\n print( ( \"file: \"\n , name\n , IF file exists( name ) THEN \" does\" ELSE \" does not\" FI\n , \" exist\"\n , newline\n )\n );\n# print a suitable messages if the specified directory exists #\nPROC test directory exists = ( STRING name )VOID:\n print( ( \"dir: \"\n , name\n , IF file is directory( name ) THEN \" does\" ELSE \" does not\" FI\n , \" exist\"\n , newline\n )\n );\n\n# test the flies and directories mentioned in the task exist or not #\ntest file exists( \"input.txt\" );\ntest file exists( \"\\input.txt\");\ntest directory exists( \"docs\" );\ntest directory exists( \"\\docs\" )\n", "language": "ALGOL-68" }, { "code": "#include <flow.h>\n\nDEF-MAIN(argv, argc)\n WHEN( IS-FILE?(\"hopper\") ){\n MEM(\"File \\\"hopper\\\" exist!\\n\")\n }\n WHEN( IS-DIR?(\"fl\") ){\n MEM(\"Directory \\\"fl\\\" exist!\\n\")\n }\n IF( IS-DIR?(\"noExisDir\"), \"Directory \\\"noExistDir\\\" exist!\\n\", \\\n \"Directory \\\"noExistDir\\\" does NOT exist!\\n\" )\n //\"arch mañoso bacán.txt\" text-file created\n\n STR-TO-UTF8(\"File \\\"arch mañoso bacán.txt\\\" \")\n IF( IS-FILE?( STR-TO-UTF8(\"arch mañoso bacán.txt\") ), \"exist!\\n\", \"NOT exist!\\n\")\n\n PRNL\nEND\n", "language": "Amazing-Hopper" }, { "code": " h ← ⎕fio['fopen'] 'input.txt'\n h\n7\n ⎕fio['fstat'] h\n66311 803134 33188 1 1000 1000 0 11634 4096 24 1642047105 1642047105 1642047105\n ⎕fio['fclose'] h\n0\n h ← ⎕fio['fopen'] 'docs/'\n h\n7\n ⎕fio['fstat'] h\n66311 3296858 16877 2 1000 1000 0 4096 4096 8 1642047108 1642047108 1642047108\n ⎕fio['fclose'] h\n0\n h ← ⎕fio['fopen'] 'does_not_exist.txt'\n h\n¯1\n", "language": "APL" }, { "code": "use framework \"Foundation\" -- YOSEMITE OS X onwards\nuse scripting additions\n\non run\n setCurrentDirectory(\"~/Desktop\")\n\n ap({doesFileExist, doesDirectoryExist}, ¬\n {\"input.txt\", \"/input.txt\", \"docs\", \"/docs\"})\n\n --> {true, true, true, true, false, false, true, true}\n\n -- The first four booleans are returned by `doesFileExist`.\n\n -- The last four are returned by `doesDirectoryExist`,\n -- which yields false for simple files, and true for directories.\nend run\n\n-- GENERIC SYSTEM DIRECTORY FUNCTIONS -----------------------------------------\n\n-- doesDirectoryExist :: String -> Bool\non doesDirectoryExist(strPath)\n set ca to current application\n set oPath to (ca's NSString's stringWithString:strPath)'s ¬\n stringByStandardizingPath\n set {bln, int} to (ca's NSFileManager's defaultManager()'s ¬\n fileExistsAtPath:oPath isDirectory:(reference))\n bln and (int = 1)\nend doesDirectoryExist\n\n-- doesFileExist :: String -> Bool\non doesFileExist(strPath)\n set ca to current application\n set oPath to (ca's NSString's stringWithString:strPath)'s ¬\n stringByStandardizingPath\n ca's NSFileManager's defaultManager()'s fileExistsAtPath:oPath\nend doesFileExist\n\n-- getCurrentDirectory :: String\non getCurrentDirectory()\n set ca to current application\n ca's NSFileManager's defaultManager()'s currentDirectoryPath as string\nend getCurrentDirectory\n\n-- getFinderDirectory :: String\non getFinderDirectory()\n tell application \"Finder\" to POSIX path of (insertion location as alias)\nend getFinderDirectory\n\n-- getHomeDirectory :: String\non getHomeDirectory()\n (current application's NSHomeDirectory() as string)\nend getHomeDirectory\n\n-- setCurrentDirectory :: String -> IO ()\non setCurrentDirectory(strPath)\n if doesDirectoryExist(strPath) then\n set ca to current application\n set oPath to (ca's NSString's stringWithString:strPath)'s ¬\n stringByStandardizingPath\n ca's NSFileManager's defaultManager()'s ¬\n changeCurrentDirectoryPath:oPath\n end if\nend setCurrentDirectory\n\n\n-- GENERIC HIGHER ORDER FUNCTIONS FOR THE TEST --------------------------------\n\n-- A list of functions applied to a list of arguments\n-- (<*> | ap) :: [(a -> b)] -> [a] -> [b]\non ap(fs, xs)\n set {intFs, intXs} to {length of fs, length of xs}\n set lst to {}\n repeat with i from 1 to intFs\n tell mReturn(item i of fs)\n repeat with j from 1 to intXs\n set end of lst to |λ|(contents of (item j of xs))\n end repeat\n end tell\n end repeat\n return lst\nend ap\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n", "language": "AppleScript" }, { "code": "{true, true, true, true, false, false, true, true}\n", "language": "AppleScript" }, { "code": "100 F$ = \"THAT FILE\"\n110 T$(0) = \"DOES NOT EXIST.\"\n120 T$(1) = \"EXISTS.\"\n130 GOSUB 200\"FILE EXISTS?\n140 PRINT F$; \" \"; T$(E)\n150 END\n\n200 REM FILE EXISTS?\n210 REM TRY\n220 ON ERR GOTO 300\"CATCH\n230 PRINT CHR$(4); \"VERIFY \"; F$\n240 POKE 216, 0 : REM ONERR OFF\n250 E = 1\n260 GOTO 350\"END TRY\n300 REM CATCH\n310 E = PEEK(222) <> 6\n320 POKE 216, 0 : REM ONERR OFF\n330 IF E THEN RESUME : REM THROW\n340 CALL - 3288 : REM RECOVER\n350 REM END TRY\n360 RETURN\n", "language": "Applesoft-BASIC" }, { "code": "/* ARM assembly Raspberry PI */\n/* program verifFic.s */\n\n/* Constantes */\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ OPEN, 5 @ Linux syscall\n.equ CLOSE, 6 @ Linux syscall\n\n.equ O_RDWR,\t0x0002\t\t/* open for reading and writing */\n\n/*******************************************/\n/* Fichier des macros */\n/********************************************/\n.include \"../../ficmacros.s\"\n\n/* Initialized data */\n.data\nszMessFound1: .asciz \"File 1 found.\\n\"\nszMessFound2: .asciz \"File 2 found.\\n\"\nszMessNotFound1: .asciz \"File 1 not found.\\n\"\nszMessNotFound2: .asciz \"File 2 not found.\\n\"\nszMessNotAuth2: .asciz \"File 2 permission denied.\\n\"\nszCarriageReturn: .asciz \"\\n\"\n\n/* areas strings */\nszFicName1: .asciz \"test1.txt\"\nszFicName2: .asciz \"/debian-binary\"\n\n\n/* UnInitialized data */\n.bss\n\n/* code section */\n.text\n.global main\nmain: /* entry of program */\n push {fp,lr} /* saves 2 registers */\n\n /*************************************\n open file 1\n ************************************/\n ldr r0,iAdrszFicName1 @ file name\n mov r1,#O_RDWR @ flags\n mov r2,#0 @ mode\n mov r7, #OPEN @ call system OPEN\n swi 0\n cmp r0,#0 @ error ?\n ble 1f\n mov r1,r0 @ FD\n ldr r0,iAdrszMessFound1\n bl affichageMess\n @ close file\n mov r0,r1 @ Fd\n mov r7, #CLOSE\n swi 0\n b 2f\n1:\n ldr r0,iAdrszMessNotFound1\n bl affichageMess\n2:\n /*************************************\n open file 2\n ************************************/\n ldr r0,iAdrszFicName2 @ file name\n mov r1,#O_RDWR @ flags\n mov r2,#0 @ mode\n mov r7, #OPEN @ call system OPEN\n swi 0\n vidregtit verif\n cmp r0,#-13 @ permission denied\n beq 4f\n cmp r0,#0 @ error ?\n ble 3f\n mov r1,r0 @ FD\n ldr r0,iAdrszMessFound2\n bl affichageMess\n @ close file\n mov r0,r1 @ Fd\n mov r7, #CLOSE\n swi 0\n b 100f\n3:\n ldr r0,iAdrszMessNotFound2\n bl affichageMess\n b 100f\n4:\n ldr r0,iAdrszMessNotAuth2\n bl affichageMess\n100: /* standard end of the program */\n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\niAdrszFicName1:\t\t\t.int szFicName1\niAdrszFicName2:\t\t\t.int szFicName2\niAdrszMessFound1:\t\t.int szMessFound1\niAdrszMessFound2:\t\t.int szMessFound2\niAdrszMessNotFound1: \t.int szMessNotFound1\niAdrszMessNotFound2: \t.int szMessNotFound2\niAdrszMessNotAuth2:\t.int szMessNotAuth2\n/******************************************************************/\n/* display text with size calculation */\n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {fp,lr} \t\t\t/* save registres */\n push {r0,r1,r2,r7} \t\t/* save others registers */\n mov r2,#0 \t\t\t\t/* counter length */\n1: \t/* loop length calculation */\n ldrb r1,[r0,r2] \t\t\t/* read octet start position + index */\n cmp r1,#0 \t\t\t/* if 0 its over */\n addne r2,r2,#1 \t\t\t/* else add 1 in the length */\n bne 1b \t\t\t/* and loop */\n /* so here r2 contains the length of the message */\n mov r1,r0 \t\t\t/* address message in r1 */\n mov r0,#STDOUT \t\t/* code to write to the standard output Linux */\n mov r7, #WRITE /* code call system \"write\" */\n swi #0 /* call systeme */\n pop {r0,r1,r2,r7} \t\t/* restaur others registers */\n pop {fp,lr} \t\t\t\t/* restaur des 2 registres */\n bx lr\t \t\t\t/* return */\n", "language": "ARM-Assembly" }, { "code": "checkIfExists: function [fpath][\n (or? exists? fpath\n exists? .directory fpath)? -> print [fpath \"exists\"]\n -> print [fpath \"doesn't exist\"]\n]\n\ncheckIfExists \"input.txt\"\ncheckIfExists \"docs\"\n\ncheckIfExists \"/input.txt\"\ncheckIfExists \"/docs\"\n", "language": "Arturo" }, { "code": "; FileExist() function examples\nShowFileExist(\"input.txt\")\nShowFileExist(\"\\input.txt\")\nShowFolderExist(\"docs\")\nShowFolderExist(\"\\docs\")\n\n; IfExist/IfNotExist command examples (from documentation)\nIfExist, D:\\\n MsgBox, The drive exists.\nIfExist, D:\\Docs\\*.txt\n MsgBox, At least one .txt file exists.\nIfNotExist, C:\\Temp\\FlagFile.txt\n MsgBox, The target file does not exist.\n\nReturn\n\nShowFileExist(file)\n{\n If (FileExist(file) && !InStr(FileExist(file), \"D\"))\n MsgBox, file: %file% exists.\n Else\n MsgBox, file: %file% does NOT exist.\n Return\n}\n\nShowFolderExist(folder)\n{\n If InStr(FileExist(folder), \"D\")\n MsgBox, folder: %folder% exists.\n Else\n MsgBox, folder: %folder% does NOT exist.\n Return\n}\n", "language": "AutoHotkey" }, { "code": "@load \"filefuncs\"\n\nfunction exists(name ,fd) {\n if ( stat(name, fd) == -1)\n print name \" doesn't exist\"\n else\n print name \" exists\"\n}\nBEGIN {\n exists(\"input.txt\")\n exists(\"/input.txt\")\n exists(\"docs\")\n exists(\"/docs\")\n}\n", "language": "AWK" }, { "code": "#\n# Check if file or directory exists, even 0-length file.\n# Return 0 if not exist, 1 if exist\n#\nfunction exists(file ,line, msg)\n{\n if ( (getline line < file) == -1 )\n {\n # \"Permission denied\" is for MS-Windows\n msg = (ERRNO ~ /Permission denied/ || ERRNO ~ /a directory/) ? 1 : 0\n close(file)\n return msg\n }\n else {\n close(file)\n return 1\n }\n}\nBEGIN {\n exists(\"input.txt\")\n exists(\"\\\\input.txt\")\n exists(\"docs\")\n exists(\"\\\\docs\")\n exit(0)\n}\n", "language": "AWK" }, { "code": "gawk 'BEGINFILE{if (ERRNO) {print \"Not exist.\"; nextfile} else {print \"Exist.\"; nextfile}}' input.txt input-missing.txt\n", "language": "AWK" }, { "code": "If GetCalc(\"appvINPUT\")\n Disp \"EXISTS\",i\nElse\n Disp \"DOES NOT EXIST\",i\nEnd\n", "language": "Axe" }, { "code": "' File exists\nf$ = \"input.txt\"\nd$ = \"docs\"\nIF FILEEXISTS(f$) THEN PRINT f$, \" exists\"\nIF FILEEXISTS(d$) AND FILETYPE(d$) = 2 THEN PRINT d$, \" directory exists\"\n\nf$ = \"/\" & f$\nd$ = \"/\" & d$\nPRINT f$, IIF$(FILEEXISTS(f$), \" exists\", \" does not exist\")\nPRINT d$, IIF$(FILEEXISTS(d$) AND FILETYPE(d$) = 2, \" is\", \" is not\"), \" a directory\"\n\nf$ = \"empty.bac\"\nPRINT f$, IIF$(FILEEXISTS(f$), \" exists\", \" does not exist\")\n\nf$ = \"`Abdu'l-Bahá.txt\"\nPRINT f$, IIF$(FILEEXISTS(f$), \" exists\", \" does not exist\")\n", "language": "BaCon" }, { "code": "ON ERROR GOTO ohNo\nf$ = \"input.txt\"\nGOSUB opener\nf$ = \"\\input.txt\"\nGOSUB opener\n\n'can't directly check for directories,\n'but can check for the NUL device in the desired dir\nf$ = \"docs\\nul\"\nGOSUB opener\nf$ = \"\\docs\\nul\"\nGOSUB opener\nEND\n\nopener:\n e$ = \" found\"\n OPEN f$ FOR INPUT AS 1\n PRINT f$; e$\n CLOSE\n RETURN\n\nohNo:\n IF (53 = ERR) OR (76 = ERR) THEN\n e$ = \" not\" + e$\n ELSE\n e$ = \"Unknown error\"\n END IF\n RESUME NEXT\n", "language": "BASIC" }, { "code": "ON ERROR GOTO ohNo\nd$ = \"docs\"\nCHDIR d$\nd$ = \"\\docs\"\nCHDIR d$\nEND\n\nohNo:\n IF 76 = ERR THEN\n PRINT d$; \" not found\"\n ELSE\n PRINT \"Unknown error\"\n END IF\n RESUME NEXT\n", "language": "BASIC" }, { "code": "f$ = \"input.txt\"\nGOSUB opener\nf$ = \"\\input.txt\"\nGOSUB opener\n\n'can't directly check for directories,\n'but can check for the NUL device in the desired dir\nf$ = \"docs\\nul\"\nGOSUB opener\nf$ = \"\\docs\\nul\"\nGOSUB opener\nEND\n\nopener:\n d$ = DIR$(f$)\n IF LEN(d$) THEN\n PRINT f$; \" found\"\n ELSE\n PRINT f$; \" not found\"\n END IF\n RETURN\n", "language": "BASIC" }, { "code": "subroutine opener (filename$)\n if exists(filename$) then\n\tprint filename$; \" exists\"\n else\n\tprint filename$; \" does not exists\"\n end if\nend subroutine\n\ncall opener (\"input.txt\")\ncall opener (\"\\input.txt\")\ncall opener (\"docs\\nul\")\ncall opener (\"\\docs\\nul\")\ncall opener (\"empty.kbs\")\ncall opener (\"`Abdu'l-Bahá.txt\"))\nend\n", "language": "BASIC256" }, { "code": "if exist input.txt echo The following file called input.txt exists.\nif exist \\input.txt echo The following file called \\input.txt exists.\nif exist docs echo The following directory called docs exists.\nif exist \\docs\\ echo The following directory called \\docs\\ exists.\n", "language": "Batch-File" }, { "code": " test% = OPENIN(\"input.txt\")\n IF test% THEN\n CLOSE #test%\n PRINT \"File input.txt exists\"\n ENDIF\n\n test% = OPENIN(\"\\input.txt\")\n IF test% THEN\n CLOSE #test%\n PRINT \"File \\input.txt exists\"\n ENDIF\n\n test% = OPENIN(\"docs\\NUL\")\n IF test% THEN\n CLOSE #test%\n PRINT \"Directory docs exists\"\n ENDIF\n\n test% = OPENIN(\"\\docs\\NUL\")\n IF test% THEN\n CLOSE #test%\n PRINT \"Directory \\docs exists\"\n ENDIF\n", "language": "BBC-BASIC" }, { "code": "fname ← ⊑args\n•Out fname∾\" Does not exist\"‿\" Exists\"⊑˜•File.exists fname\n", "language": "BQN" }, { "code": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <stdio.h>\n#include <unistd.h>\n\n/* Check for regular file. */\nint check_reg(const char *path) {\n\tstruct stat sb;\n\treturn stat(path, &sb) == 0 && S_ISREG(sb.st_mode);\n}\n\n/* Check for directory. */\nint check_dir(const char *path) {\n\tstruct stat sb;\n\treturn stat(path, &sb) == 0 && S_ISDIR(sb.st_mode);\n}\n\nint main() {\n\tprintf(\"input.txt is a regular file? %s\\n\",\n\t check_reg(\"input.txt\") ? \"yes\" : \"no\");\n\tprintf(\"docs is a directory? %s\\n\",\n\t check_dir(\"docs\") ? \"yes\" : \"no\");\n\tprintf(\"/input.txt is a regular file? %s\\n\",\n\t check_reg(\"/input.txt\") ? \"yes\" : \"no\");\n\tprintf(\"/docs is a directory? %s\\n\",\n\t check_dir(\"/docs\") ? \"yes\" : \"no\");\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <gadget/gadget.h>\n\nLIB_GADGET_START\n\n/* input.txt = check_file.c\n docs = tests */\n\nMain\n Print \"tests/check_file.c is a regular file? %s\\n\", Exist_file(\"tests/check_file.c\") ? \"yes\" : \"no\";\n Print \"tests is a directory? %s\\n\", Exist_dir(\"tests\") ? \"yes\" : \"no\";\n Print \"some.txt is a regular file? %s\\n\", Exist_file(\"some.txt\") ? \"yes\" : \"no\";\n Print \"/tests is a directory? %s\\n\", Exist_dir(\"/tests\") ? \"yes\" : \"no\";\nEnd\n", "language": "C" }, { "code": "#include \"boost/filesystem.hpp\"\n#include <string>\n#include <iostream>\n\nvoid testfile(std::string name)\n{\n boost::filesystem::path file(name);\n if (exists(file))\n {\n if (is_directory(file))\n std::cout << name << \" is a directory.\\n\";\n else\n std::cout << name << \" is a non-directory file.\\n\";\n }\n else\n std::cout << name << \" does not exist.\\n\";\n}\n\nint main()\n{\n testfile(\"input.txt\");\n testfile(\"docs\");\n testfile(\"/input.txt\");\n testfile(\"/docs\");\n}\n", "language": "C++" }, { "code": "#include <iostream>\n#include <filesystem>\n\nvoid file_exists(const std::filesystem::path& path) {\n std::cout << path;\n if ( std::filesystem::exists(path) ) {\n \tif ( std::filesystem::is_directory(path) ) {\n \t\tstd::cout << \" is a directory\" << std::endl;\n \t} else {\n \t\tstd::cout << \" exists with a file size of \" << std::filesystem::file_size(path) << \" bytes.\" << std::endl;\n \t}\n } else {\n std::cout << \" does not exist\" << std::endl;\n }\n}\n\nint main() {\n\tfile_exists(\"input.txt\");\n\tfile_exists(\"zero_length.txt\");\n\tfile_exists(\"docs/input.txt\");\n\tfile_exists(\"docs/zero_length.txt\");\n}\n", "language": "C++" }, { "code": "using System.IO;\n\nConsole.WriteLine(File.Exists(\"input.txt\"));\nConsole.WriteLine(File.Exists(\"/input.txt\"));\nConsole.WriteLine(Directory.Exists(\"docs\"));\nConsole.WriteLine(Directory.Exists(\"/docs\"));\n", "language": "C-sharp" }, { "code": "(dorun (map #(.exists (clojure.java.io/as-file %)) '(\"/input.txt\" \"/docs\" \"./input.txt\" \"./docs\")))\n", "language": "Clojure" }, { "code": " identification division.\n program-id. check-file-exist.\n\n environment division.\n configuration section.\n repository.\n function all intrinsic.\n\n data division.\n working-storage section.\n 01 skip pic 9 value 2.\n 01 file-name.\n 05 value \"/output.txt\".\n 01 dir-name.\n 05 value \"/docs/\".\n 01 unusual-name.\n 05 value \"Abdu'l-Bahá.txt\".\n\n 01 test-name pic x(256).\n\n 01 file-handle usage binary-long.\n 01 file-info.\n 05 file-size pic x(8) comp-x.\n 05 file-date.\n 10 file-day pic x comp-x.\n 10 file-month pic x comp-x.\n 10 file-year pic xx comp-x.\n 05 file-time.\n 10 file-hours pic x comp-x.\n 10 file-minutes pic x comp-x.\n 10 file-seconds pic x comp-x.\n 10 file-hundredths pic x comp-x.\n\n procedure division.\n files-main.\n\n *> check in current working dir\n move file-name(skip:) to test-name\n perform check-file\n\n move dir-name(skip:) to test-name\n perform check-file\n\n move unusual-name to test-name\n perform check-file\n\n *> check in root dir\n move 1 to skip\n move file-name(skip:) to test-name\n perform check-file\n\n move dir-name(skip:) to test-name\n perform check-file\n\n goback.\n\n check-file.\n call \"CBL_CHECK_FILE_EXIST\" using test-name file-info\n if return-code equal zero then\n display test-name(1:32) \": size \" file-size \", \"\n file-year \"-\" file-month \"-\" file-day space\n file-hours \":\" file-minutes \":\" file-seconds \".\"\n file-hundredths\n else\n display \"error: CBL_CHECK_FILE_EXIST \" return-code space\n trim(test-name)\n end-if\n .\n\n end program check-file-exist.\n", "language": "COBOL" }, { "code": "fs = require 'fs'\npath = require 'path'\n\nroot = path.resolve '/'\ncurrent_dir = __dirname\nfilename = 'input.txt'\ndirname = 'docs'\n\nlocal_file = path.join current_dir, filename\nlocal_dir = path.join current_dir, dirname\n\nroot_file = path.join root, filename\nroot_dir = path.join root, dirname\n\nfor p in [ local_file, local_dir, root_file, root_dir ] then do ( p ) ->\n fs.exists p, ( p_exists ) ->\n unless p_exists\n console.log \"#{ p } does not exist.\"\n else then fs.stat p, ( error, stat ) ->\n console.log \"#{ p } exists and is a #{ if stat.isFile() then 'file' else then 'directory' }.\"\n", "language": "CoffeeScript" }, { "code": "10 REM CHECK FILE EXISTS\n15 ER=0:EM$=\"\":MSG$=\"FILE EXISTS.\"\n20 PRINT CHR$(147);:REM CLEAR SCREEN\n30 FI$=\"\":INPUT \"ENTER FILENAME TO CHECK\";FI$:PRINT\n35 IF FI$=\"\" THEN PRINT \"ABORTED.\":END\n40 OPEN 8,8,8,FI$\n50 GOSUB 1000:REM FETCH ERROR STATUS FROM DRIVE: 0=OK, 62=FILE NOT FOUND\n55 REM COMPARE ERROR NUMBER\n60 IF ER<>0 THEN MSG$=\"I/O ERROR:\"+STR$(ER)+\" \"+EM$\n70 IF ER=62 THEN MSG$=\"'\"+FI$+\"' IS NOT HERE.\"\n80 REM DO THINGS WITH FILE...\n100 CLOSE 8\n110 PRINT MSG$\n120 PRINT:GOTO 30:REM REPEAT UNTIL EMPTY FILENAME IS ENTERED\n1000 REM CHECK ERROR CHANNEL FOR STATUS OF LAST DISK OPERATION\n1010 OPEN 15,8,15\n1015 REM GET ERROR CODE, ERROR MESSAGE, TRACK, SECTOR\n1020 INPUT#15,ER,EM$,T,S\n1030 CLOSE 15\n1040 RETURN\n", "language": "Commodore-BASIC" }, { "code": "(if (probe-file (make-pathname :name \"input.txt\"))\n (print \"rel file exists\"))\n(if (probe-file (make-pathname :directory '(:absolute \"\") :name \"input.txt\"))\n (print \"abs file exists\"))\n\n(if (directory (make-pathname :directory '(:relative \"docs\")))\n (print \"rel directory exists\")\n (print \"rel directory is not known to exist\"))\n(if (directory (make-pathname :directory '(:absolute \"docs\")))\n (print \"abs directory exists\")\n (print \"abs directory is not known to exist\"))\n", "language": "Common-Lisp" }, { "code": "(if (cl-fad:directory-exists-p (make-pathname :directory '(:relative \"docs\")))\n (print \"rel directory exists\")\n (print \"rel directory does not exist\"))\n", "language": "Common-Lisp" }, { "code": "def check_file(filename : String)\n if File.directory?(filename)\n puts \"#{filename} is a directory\"\n elsif File.exists?(filename)\n puts \"#{filename} is a file\"\n else\n puts \"#{filename} does not exist\"\n end\nend\n\ncheck_file(\"input.txt\")\ncheck_file(\"docs\")\ncheck_file(\"/input.txt\")\ncheck_file(\"/docs\")\n", "language": "Crystal" }, { "code": "import std.stdio, std.file, std.path;\n\nvoid verify(in string name) {\n if (name.exists())\n writeln(\"'\", name, \"' exists\");\n else\n writeln(\"'\", name, \"' doesn't exist\");\n}\n\nvoid main() {\n // check in current working dir\n verify(\"input.txt\");\n verify(\"docs\");\n\n // check in root\n verify(dirSeparator ~ \"input.txt\");\n verify(dirSeparator ~ \"docs\");\n}\n", "language": "D" }, { "code": ";\n; Check file and directory exists for DBL version 4 by Dario B.\n;\n PROC\n;------------------------------------------------------------------\n XCALL FLAGS (0007000000,1) ;Suppress STOP message\n\n CLOSE 1\n OPEN (1,O,'TT:')\n\n ;The file path can be written as:\n ; \"input.txt\" (current directory)\n ; \"/directory/input.txt\" (complete path)\n ; \"DEV:input.txt\" (device DEV defined in shell)\n ; \"$DEV/input.txt\" (device DEV defined in shell)\n CLOSE 2\n OPEN (2,I,\"input.txt\") [ERR=NOFIL]\n CLOSE 2\n\n ;Check directory (unix/linux systems)\n CLOSE 2\n OPEN (2,O,\"/docs/.\") [ERR=NODIR]\n\n GOTO CLOS\n\n;--------------------------------------------------------\nNOFIL, DISPLAY (1,\"File input.txt not found!\",10)\n GOTO CLOS\n\nNODIR, DISPLAY (1,\"Directory /docs not found!\",10)\n GOTO CLOS\n\nCLOS, CLOSE 1\n CLOSE 2\n STOP\n", "language": "DBL" }, { "code": "$ if f$search( \"input.txt\" ) .eqs. \"\"\n$ then\n$ write sys$output \"input.txt not found\"\n$ else\n$ write sys$output \"input.txt found\"\n$ endif\n$ if f$search( \"docs.dir\" ) .eqs. \"\"\n$ then\n$ write sys$output \"directory docs not found\"\n$ else\n$ write sys$output \"directory docs found\"\n$ endif\n$ if f$search( \"[000000]input.txt\" ) .eqs. \"\"\n$ then\n$ write sys$output \"[000000]input.txt not found\"\n$ else\n$ write sys$output \"[000000]input.txt found\"\n$ endif\n$ if f$search( \"[000000]docs.dir\" ) .eqs. \"\"\n$ then\n$ write sys$output \"directory [000000]docs not found\"\n$ else\n$ write sys$output \"directory [000000]docs found\"\n$ endif\n", "language": "DCL" }, { "code": "program EnsureFileExists;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils;\n\nbegin\n if FileExists('input.txt') then\n Writeln('File \"input.txt\" exists.')\n else\n Writeln('File \"input.txt\" does not exist.');\n\n if FileExists('\\input.txt') then\n Writeln('File \"\\input.txt\" exists.')\n else\n Writeln('File \"\\input.txt\" does not exist.');\n\n if DirectoryExists('docs') then\n Writeln('Directory \"docs\" exists.')\n else\n Writeln('Directory \"docs\" does not exists.');\n\n if DirectoryExists('\\docs') then\n Writeln('Directory \"\\docs\" exists.')\n else\n Writeln('Directory \"\\docs\" does not exists.');\nend.\n", "language": "Delphi" }, { "code": "for file in [<file:input.txt>,\n <file:///input.txt>] {\n require(file.exists(), fn { `$file is missing!` })\n require(!file.isDirectory(), fn { `$file is a directory!` })\n}\n\nfor file in [<file:docs>,\n <file:///docs>] {\n require(file.exists(), fn { `$file is missing!` })\n require(file.isDirectory(), fn { `$file is not a directory!` })\n}\n", "language": "E" }, { "code": "import system'io;\nimport extensions;\n\nextension op\n{\n validatePath()\n = self.Available.iif(\"exists\",\"not found\");\n}\n\npublic program()\n{\n console.printLine(\"input.txt file \",File.assign(\"input.txt\").validatePath());\n\n console.printLine(\"\\input.txt file \",File.assign(\"\\input.txt\").validatePath());\n\n console.printLine(\"docs directory \",Directory.assign(\"docs\").validatePath());\n\n console.printLine(\"\\docs directory \",Directory.assign(\"\\docs\").validatePath())\n}\n", "language": "Elena" }, { "code": "File.regular?(\"input.txt\")\nFile.dir?(\"docs\")\nFile.regular?(\"/input.txt\")\nFile.dir?(\"/docs\")\n", "language": "Elixir" }, { "code": "(file-exists-p \"input.txt\")\n(file-directory-p \"docs\")\n(file-exists-p \"/input.txt\")\n(file-directory-p \"/docs\")\n", "language": "Emacs-Lisp" }, { "code": "#!/usr/bin/escript\nexistence( true ) ->\"exists\";\nexistence( false ) ->\"does not exist\".\n\nprint_result(Type, Name, Flag) -> io:fwrite( \"~s ~s ~s~n\", [Type, Name, existence(Flag)] ).\n\n\nmain(_) ->\n print_result( \"File\", \"input.txt\", filelib:is_regular(\"input.txt\") ),\n print_result( \"Directory\", \"docs\", filelib:is_dir(\"docs\") ),\n print_result( \"File\", \"/input.txt\", filelib:is_regular(\"/input.txt\") ),\n print_result( \"Directory\", \"/docs\", filelib:is_dir(\"/docs\") ).\n", "language": "Erlang" }, { "code": "include file.e\n\nprocedure ensure_exists(sequence name)\n object x\n sequence s\n x = dir(name)\n if sequence(x) then\n if find('d',x[1][D_ATTRIBUTES]) then\n s = \"directory\"\n else\n s = \"file\"\n end if\n printf(1,\"%s %s exists.\\n\",{name,s})\n else\n printf(1,\"%s does not exist.\\n\",{name})\n end if\nend procedure\n\nensure_exists(\"input.txt\")\nensure_exists(\"docs\")\nensure_exists(\"/input.txt\")\nensure_exists(\"/docs\")\n", "language": "Euphoria" }, { "code": "open System.IO\nFile.Exists(\"input.txt\")\nDirectory.Exists(\"docs\")\nFile.Exists(\"/input.txt\")\nDirectory.Exists(@\"\\docs\")\n", "language": "F-Sharp" }, { "code": ": print-exists? ( path -- )\n [ write \": \" write ] [ exists? \"exists.\" \"doesn't exist.\" ? print ] bi ;\n\n{ \"input.txt\" \"/input.txt\" \"docs\" \"/docs\" } [ print-exists? ] each\n", "language": "Factor" }, { "code": ": .exists ( str len -- )\n 2dup file-status nip 0= if\n .\" exists: \"\n else\n .\" does not exist: \"\n then\n type\n;\n\ns\" input.txt\" .exists cr\ns\" /input.txt\" .exists cr\ns\" docs\" .exists cr\ns\" /docs\" .exists cr\n", "language": "Forth" }, { "code": "LOGICAL :: file_exists\nINQUIRE(FILE=\"input.txt\", EXIST=file_exists) ! file_exists will be TRUE if the file\n ! exists and FALSE otherwise\nINQUIRE(FILE=\"/input.txt\", EXIST=file_exists)\n", "language": "Fortran" }, { "code": "logical :: dir_e\n! a trick to be sure docs is a dir\ninquire( file=\"./docs/.\", exist=dir_e )\nif ( dir_e ) then\n write(*,*), \"dir exists!\"\nelse\n ! workaround: it calls an extern program...\n call system('mkdir docs')\nend if\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\n' Enable FileExists() function to be used\n#include \"file.bi\"\n\n' Use Win32 function to check if directory exists on Windows 10\nDeclare Function GetFileAttributes Lib \"kernel32.dll\" Alias \"GetFileAttributesA\" _\n(ByVal lpFileName As ZString Ptr) As ULong\n\nConst InvalidFileAttributes As ULong = -1UL\nConst FileAttributeDirectory As ULong = &H10UL\n\nSub CheckFileExists(ByRef filePath As String)\n If FileExists(filePath) Then\n Print \"'\"; filePath; \"' exists\"\n Else\n Print \"'\"; filePath; \"' does not exist\"\n End If\nEnd Sub\n\nSub CheckDirectoryExists(ByVal dirPath As ZString Ptr)\n Dim attrib As ULong = GetFileAttributes(dirPath)\n Dim dirExists As ULong = attrib <> InvalidFileAttributes AndAlso (attrib And FileAttributeDirectory) <> 0\n If dirExists Then\n Print \"'\"; *dirPath; \"' exists\"\n Else\n Print \"'\"; *dirPath; \"' does not exist\"\n End If\nEnd Sub\n\nCheckFileExists(CurDir + \"\\input.txt\")\nDim dirPath As String = CurDir + \"\\docs\"\nCheckDirectoryExists(StrPtr(dirPath))\nCheckFileExists(\"c:\\input.txt\")\nCheckDirectoryExists(StrPtr(\"c:\\docs\"))\nPrint\nPrint \"Press any key to quit the program\"\nSleep\n", "language": "FreeBASIC" }, { "code": "checkFile[filename] :=\n{\n file = newJava[\"java.io.File\", [filename]]\n if file.exists[] and file.isFile[]\n println[\"$filename is a file\"]\n else\n println[\"$filename is not a file\"]\n}\n\ncheckDir[filename] :=\n{\n file = newJava[\"java.io.File\", [filename]]\n if file.exists[] and file.isDirectory[]\n println[\"$filename is a directory\"]\n else\n println[\"$filename is not a directory\"]\n}\n\ncheckFile[\"input.txt\"]\ncheckFile[\"/input.txt\"]\ncheckDir[\"docs\"]\ncheckDir[\"/docs\"]\n\n// This tests the \"unusual\" filename with various Unicode\n// normalizations that would look identical to a human\n// For example, the á character could be written as either\n// the Unicode sequences\n// \\u00e1 ('LATIN SMALL LETTER A WITH ACUTE')\n// or\n// \\u0061\\u0301 ('LATIN SMALL LETTER A' 'COMBINING ACUTE ACCENT')\nunusual = \"`Abdu'l-Bahá.txt\"\ncheckFile[unusual]\ncheckFile[normalizeUnicode[unusual, \"NFC\"]]\ncheckFile[normalizeUnicode[unusual, \"NFD\"]]\n", "language": "Frink" }, { "code": "include \"NSLog.incl\"\n\nCFURLRef url\nurl = fn URLFileURLWithPath( fn StringByExpandingTildeInPath(@\"~/Desktop/input.txt\") )\nif (fn FileManagerFileExistsAtURL( url ) )\n NSLog( @\"File \\\"input.txt\\\" exists.\" )\nelse\n NSLog( @\"File \\\"input.txt\\\" does not exist at this location.\" )\nend if\n\nurl = fn URLFileURLWithPath( fn StringByExpandingTildeInPath(@\"~/Desktop/docs\") )\nif (fn FileManagerIsDirectoryAtURL( url ) )\n NSLog( @\"Directory \\\"docs\\\" exists.\" )\nelse\n NSLog( @\"Directory \\\"docs\\\" does not exist at this location.\" )\nend if\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\n\nIf Exist(User.Home &/ \"input.txt\") Then Print \"'input.txt' does exist in the Home folder\"\nIf Not Exist(\"/input.txt\") Then Print \"'input.txt' does NOT exist in Root\" 'Not messing With my Root files\n\nIf Exist(User.home &/ \"docs/\") Then Print \"The folder '~/docs' does exist\"\nIf Not Exist(\"/docs/\") Then Print \"The folder '/docs' does NOT exist\" 'Not messing With my Root files\n\nFile.Save(User.Home &/ \"`Abdu'l-Bahá.txt\", \"\")\nIf Exist(User.Home &/ \"`Abdu'l-Bahá.txt\") Then Print \"'`Abdu'l-Bahá.txt' does exist (zero length and unusual name)\"\n\nEnd\n", "language": "Gambas" }, { "code": "IsExistingFile(\"input.txt\");\nIsDirectoryPath(\"docs\");\nIsExistingFile(\"/input.txt\");\nIsDirectoryPath(\"/docs\");\n", "language": "GAP" }, { "code": "[indent=4]\n/*\n Check file exists, in Genie\n valac --pkg=gio-2.0 checkFile.gs\n*/\n\ninit\n Intl.setlocale()\n\n files:array of string[] = {\"input.txt\", \"docs\",\n Path.DIR_SEPARATOR_S + \"input.txt\", Path.DIR_SEPARATOR_S + \"docs\", \"`Abdu'l-Bahá.txt\"}\n for f:string in files\n var file = File.new_for_path(f)\n var exists = file.query_exists()\n var dir = false\n if exists\n dir = file.query_file_type(0) == FileType.DIRECTORY\n print(\"%s %sexist%s%s\", f, exists ? \"\" : \"does not \", exists ? \"s\" : \"\", dir ? \" and is a directory\" : \"\")\n", "language": "Genie" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"os\"\n)\n\nfunc printStat(p string) {\n switch i, err := os.Stat(p); {\n case err != nil:\n fmt.Println(err)\n case i.IsDir():\n fmt.Println(p, \"is a directory\")\n default:\n fmt.Println(p, \"is a file\")\n }\n}\n\nfunc main() {\n printStat(\"input.txt\")\n printStat(\"/input.txt\")\n printStat(\"docs\")\n printStat(\"/docs\")\n}\n", "language": "Go" }, { "code": "println new File('input.txt').exists()\nprintln new File('/input.txt').exists()\nprintln new File('docs').exists()\nprintln new File('/docs').exists()\n", "language": "Groovy" }, { "code": "import System.Directory (doesFileExist, doesDirectoryExist)\n\ncheck :: (FilePath -> IO Bool) -> FilePath -> IO ()\ncheck p s = do\n result <- p s\n putStrLn $\n s ++\n if result\n then \" does exist\"\n else \" does not exist\"\n\nmain :: IO ()\nmain = do\n check doesFileExist \"input.txt\"\n check doesDirectoryExist \"docs\"\n check doesFileExist \"/input.txt\"\n check doesDirectoryExist \"/docs\"\n", "language": "Haskell" }, { "code": "println \"File \\\"input.txt\\\"? \" + (exists \"input.txt\")\nprintln \"Dir \\\"docs\\\"? \" + (exists \"docs/\")\nprintln \"File \\\"/input.txt\\\"? \" + (exists \"/input.txt\")\nprintln \"Dir \\\"/docs\\\"? \" + (exists \"/docs/\")\n", "language": "Hexiscript" }, { "code": " OPEN(FIle= 'input.txt', OLD, IOStat=ios, ERror=99)\n OPEN(FIle='C:\\input.txt', OLD, IOStat=ios, ERror=99)\n! ...\n99 WRITE(Messagebox='!') 'File does not exist. Error message ', ios\n", "language": "HicEst" }, { "code": "U0 FileExists(U8 *f) {\n if (FileFind(f) && !IsDir(f)) {\n Print(\"'%s' file exists.\\n\", f);\n } else {\n Print(\"'%s' file does not exist.\\n\", f);\n }\n}\n\nU0 DirExists(U8 *d) {\n if (IsDir(d)) {\n Print(\"'%s' directory exists.\\n\", d);\n } else {\n Print(\"'%s' directory does not exist.\\n\", d);\n }\n}\n\nFileExists(\"input.txt\");\nFileExists(\"::/input.txt\");\nDirExists(\"docs\");\nDirExists(\"::/docs\");\n", "language": "HolyC" }, { "code": "concept exists(path) {\n\topen(path)\n\terrors {\n\t\tif error.DoesNotExist()\n\t\t\tprint(path, \" does not exist!\")\n\t\tend\n\t\treturn\n\t}\n\tprint(path, \" exists!\")\n}\n\nsoftware {\n\texists(\"input.txt\")\n\texists(\"/input.txt\")\n\texists(\"docs\")\n\texists(\"/docs\")\n\texists(\"docs/Abdu'l-Bahá.txt\")\n}\n", "language": "I" }, { "code": "every dir := ![\"./\",\"/\"] do {\n write(\"file \", f := dir || \"input.txt\", if stat(f) then \" exists.\" else \" doesn't exist.\")\n write(\"directory \", f := dir || \"docs\", if stat(f) then \" exists.\" else \" doesn't exist.\")\n }\n", "language": "Icon" }, { "code": "print, FILE_TEST('input.txt')\nprint, FILE_TEST(PATH_SEP()+'input.txt')\nprint, FILE_TEST('docs', /DIRECTORY)\nprint, FILE_TEST(PATH_SEP()+'docs', /DIRECTORY)\n", "language": "IDL" }, { "code": "require 'files'\nfexist 'input.txt'\nfexist '/input.txt'\ndirexist=: 2 = ftype\ndirexist 'docs'\ndirexist '/docs'\n", "language": "J" }, { "code": "new File(\"docs/input.txt\").exists();\nnew File(\"/docs/input.txt\").exists();\n", "language": "Java" }, { "code": "new File(\"`Abdu'l-Bahá.txt\").exists()\n", "language": "Java" }, { "code": "new File(\"`Abdu'l-Bah\\u00E1.txt\").exists();\n", "language": "Java" }, { "code": "import java.io.File;\npublic class FileExistsTest {\n public static boolean isFileExists(String filename) {\n boolean exists = new File(filename).exists();\n return exists;\n }\n public static void test(String type, String filename) {\n System.out.println(\"The following \" + type + \" called \" + filename +\n (isFileExists(filename) ? \" exists.\" : \" not exists.\")\n );\n }\n public static void main(String args[]) {\n test(\"file\", \"input.txt\");\n test(\"file\", File.separator + \"input.txt\");\n test(\"directory\", \"docs\");\n test(\"directory\", File.separator + \"docs\" + File.separator);\n }\n}\n", "language": "Java" }, { "code": "import java.nio.file.FileSystem;\nimport java.nio.file.FileSystems;\nimport java.nio.file.Files;\npublic class FileExistsTest{\n private static FileSystem defaultFS = FileSystems.getDefault();\n public static boolean isFileExists(String filename){\n return Files.exists(defaultFS.getPath(filename));\n }\n public static void test(String type, String filename){\n System.out.println(\"The following \" + type + \" called \" + filename +\n (isFileExists(filename) ? \" exists.\" : \" not exists.\")\n );\n }\n public static void main(String args[]){\n test(\"file\", \"input.txt\");\n test(\"file\", defaultFS.getSeparator() + \"input.txt\");\n test(\"directory\", \"docs\");\n test(\"directory\", defaultFS.getSeparator() + \"docs\" + defaultFS.getSeparator());\n }\n}\n", "language": "Java" }, { "code": "var fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\nfso.FileExists('input.txt');\nfso.FileExists('c:/input.txt');\nfso.FolderExists('docs');\nfso.FolderExists('c:/docs');\n", "language": "JavaScript" }, { "code": "(() => {\n\n // SYSTEM DIRECTORY FUNCTIONS\n // FOR MAC OS 'JAVASCRIPT FOR AUTOMATION' SCRIPTING -----------------------\n\n // doesDirectoryExist :: String -> IO Bool\n const doesDirectoryExist = strPath => {\n const\n dm = $.NSFileManager.defaultManager,\n ref = Ref();\n return dm\n .fileExistsAtPathIsDirectory(\n $(strPath)\n .stringByStandardizingPath, ref\n ) && ref[0] === 1;\n };\n\n // doesFileExist :: String -> Bool\n const doesFileExist = strPath => {\n var error = $();\n return (\n $.NSFileManager.defaultManager\n .attributesOfItemAtPathError(\n $(strPath)\n .stringByStandardizingPath,\n error\n ),\n error.code === undefined\n );\n };\n\n // getCurrentDirectory :: String\n const getCurrentDirectory = () =>\n ObjC.unwrap($.NSFileManager.defaultManager.currentDirectoryPath);\n\n // getFinderDirectory :: String\n const getFinderDirectory = () =>\n Application('Finder')\n .insertionLocation()\n .url()\n .slice(7);\n\n // getHomeDirectory :: String\n const getHomeDirectory = () =>\n ObjC.unwrap($.NSHomeDirectory());\n\n // setCurrentDirectory :: String -> IO ()\n const setCurrentDirectory = strPath =>\n $.NSFileManager.defaultManager\n .changeCurrentDirectoryPath(\n $(strPath)\n .stringByStandardizingPath\n );\n\n // GENERIC FUNCTIONS FOR THE TEST -----------------------------------------\n\n // A list of functions applied to a list of arguments\n // <*> :: [(a -> b)] -> [a] -> [b]\n const ap = (fs, xs) => //\n [].concat.apply([], fs.map(f => //\n [].concat.apply([], xs.map(x => [f(x)]))));\n\n // show :: a -> String\n const show = x => JSON.stringify(x, null, 2);\n\n // TEST -------------------------------------------------------------------\n return (\n setCurrentDirectory('~/Desktop'),\n show(ap(\n [doesFileExist, doesDirectoryExist],\n ['input.txt', '/input.txt', 'docs', '/docs']\n ))\n );\n})();\n", "language": "JavaScript" }, { "code": "@show isfile(\"input.txt\")\n@show isfile(\"/input.txt\")\n@show isdir(\"docs\")\n@show isdir(\"/docs\")\n@show isfile(\"\")\n@show isfile(\"`Abdu'l-Bahá.txt\")\n", "language": "Julia" }, { "code": "include ..\\Utilitys.tlhy\n\n\"foo.bar\" \"w\" fopen\n\"Hallo !\" over fputs\nfclose\n\n\"fou.bar\" \"r\" fopen\ndup 0 < ( [\"Could not open 'fou.bar' for reading\" print drop] [fclose] ) if\n\n\" \" input\n", "language": "Klingphix" }, { "code": "// version 1.0.6\n\nimport java.io.File\n\nfun main(args: Array<String>) {\n val filePaths = arrayOf(\"input.txt\", \"c:\\\\input.txt\", \"zero_length.txt\", \"`Abdu'l-Bahá.txt\")\n val dirPaths = arrayOf(\"docs\", \"c:\\\\docs\")\n for (filePath in filePaths) {\n val f = File(filePath)\n println(\"$filePath ${if (f.exists() && !f.isDirectory) \"exists\" else \"does not exist\"}\")\n }\n for (dirPath in dirPaths) {\n val d = File(dirPath)\n println(\"$dirPath ${if (d.exists() && d.isDirectory) \"exists\" else \"does not exist\"}\")\n }\n}\n", "language": "Kotlin" }, { "code": "# Load the IO module\n# Replace \"<pathToIO.lm>\" with the location where the io.lm Lang module was installed to without \"<\" and \">\"\nln.loadModule(<pathToIO.lm>)\n\n$file1 = [[io]]::fp.openFile(input.txt)\n[[io]]::fp.existsFile($file1)\n[[io]]::fp.closeFile($file1)\n\n$file2 = [[io]]::fp.openFile(/input.txt)\n[[io]]::fp.existsFile($file2)\n[[io]]::fp.closeFile($file2)\n\n$dir1 = [[io]]::fp.openFile(docs)\n[[io]]::fp.existsFile($dir1)\n[[io]]::fp.closeFile($dir1)\n\n$dir2 = [[io]]::fp.openFile(/docs)\n[[io]]::fp.existsFile($dir2)\n[[io]]::fp.closeFile($dir2)\n", "language": "Lang" }, { "code": "val .printresult = impure fn(.file) {\n write .file, \": \"\n if val .p = prop(.file) {\n if .p'isdir {\n writeln \"is directory\"\n } else {\n writeln \"is file\"\n }\n } else {\n writeln \"nothing\"\n }\n}\n\n.printresult(\"input.txt\")\n.printresult(\"/input.txt\")\n.printresult(\"docs\")\n.printresult(\"/docs\")\n", "language": "Langur" }, { "code": "// local file\nfile_exists('input.txt')\n\n// local directory\nfile_exists('docs')\n\n// file in root file system (requires permissions at user OS level)\nfile_exists('//input.txt')\n\n// directory in root file system (requires permissions at user OS level)\nfile_exists('//docs')\n", "language": "Lasso" }, { "code": "> (: filelib is_regular '\"input.txt\")\nfalse\n> (: filelib is_dir '\"docs\")\nfalse\n> (: filelib is_regular '\"/input.txt\")\nfalse\n> (: filelib is_dir '\"/docs\"))\nfalse\n", "language": "LFE" }, { "code": "'fileExists.bas - Show how to determine if a file exists\ndim info$(10,10)\ninput \"Type a file path (ie. c:\\windows\\somefile.txt)?\"; fpath$\nif fileExists(fpath$) then\n print fpath$; \" exists!\"\nelse\n print fpath$; \" doesn't exist!\"\nend if\nend\n\n'return a true if the file in fullPath$ exists, else return false\nfunction fileExists(fullPath$)\n files pathOnly$(fullPath$), filenameOnly$(fullPath$), info$()\n fileExists = val(info$(0, 0)) > 0\nend function\n\n'return just the directory path from a full file path\nfunction pathOnly$(fullPath$)\n pathOnly$ = fullPath$\n while right$(pathOnly$, 1) <> \"\\\" and pathOnly$ <> \"\"\n pathOnly$ = left$(pathOnly$, len(pathOnly$)-1)\n wend\nend function\n\n'return just the filename from a full file path\nfunction filenameOnly$(fullPath$)\n pathLength = len(pathOnly$(fullPath$))\n filenameOnly$ = right$(fullPath$, len(fullPath$)-pathLength)\nend function\n", "language": "Liberty-BASIC" }, { "code": "if (exists(\"input.txt\")) {\n puts(\"The file \\\"input.txt\\\" exist\");\n}\nif (exists(\"/input.txt\")) {\n puts(\"The file \\\"/input.txt\\\" exist\");\n}\nif (exists(\"docs\")) {\n puts(\"The file \\\"docs\\\" exist\");\n}\nif (exists(\"/docs\")) {\n puts(\"The file \\\"/docs\\\" exist\");\n}\n", "language": "Little" }, { "code": "there is a file \"/input.txt\"\nthere is a file \"input.txt\"\nthere is a folder \"docs\"\nthere is a file \"/docs/input.txt\"\n", "language": "LiveCode" }, { "code": "set the defaultFolder to \"docs\"\nthere is a file \"input.txt\"\n", "language": "LiveCode" }, { "code": "show file? \"input.txt\nshow file? \"/input.txt\nshow file? \"docs\nshow file? \"/docs\n", "language": "Logo" }, { "code": "setprefix \"/\nshow file? \"input.txt\n", "language": "Logo" }, { "code": "function output( s, b )\n if b then\n print ( s, \" does not exist.\" )\n else\n print ( s, \" does exist.\" )\n end\nend\n\noutput( \"input.txt\", io.open( \"input.txt\", \"r\" ) == nil )\noutput( \"/input.txt\", io.open( \"/input.txt\", \"r\" ) == nil )\noutput( \"docs\", io.open( \"docs\", \"r\" ) == nil )\noutput( \"/docs\", io.open( \"/docs\", \"r\" ) == nil )\n", "language": "Lua" }, { "code": "require \"lfs\"\nfor i, path in ipairs({\"input.txt\", \"/input.txt\", \"docs\", \"/docs\"}) do\n local mode = lfs.attributes(path, \"mode\")\n if mode then\n print(path .. \" exists and is a \" .. mode .. \".\")\n else\n print(path .. \" does not exist.\")\n end\nend\n", "language": "Lua" }, { "code": "Module ExistDirAndFile {\n Let WorkingDir$=Dir$, RootDir$=\"C:\\\"\n\n task(WorkingDir$)\n task(RootDir$)\n Dir User ' return to user directroy\n\n Sub task(WorkingDir$)\n Local counter\n Dir WorkingDir$\n If Not Exist.Dir(\"docs\") then Report \"docs not exist in \"+WorkingDir$ : counter++\n If Not Exist(\"output.txt\") Then {\n Report \"output.txt not exist in \"+ WorkingDir$ : counter++\n } Else.if Filelen(\"output.txt\")=0 Then Report \"output.txt has zero length\"\n If counter =0 then Report WorkingDir$+ \" has docs directory and file output.txt\"\n End Sub\n}\nExistDirAndFile\n", "language": "M2000-Interpreter" }, { "code": "with(FileTools):\nExists(\"input.txt\");\nExists(\"docs\") and IsDirectory(\"docs\");\nExists(\"/input.txt\");\nExists(\"/docs\") and IsDirectory(\"/docs\");\n", "language": "Maple" }, { "code": "wd = NotebookDirectory[];\nFileExistsQ[wd <> \"input.txt\"]\nDirectoryQ[wd <> \"docs\"]\n\nFileExistsQ[\"/\" <> \"input.txt\"]\nDirectoryQ[\"/\" <> \"docs\"]\n", "language": "Mathematica" }, { "code": " exist('input.txt','file')\n exist('/input.txt','file')\n exist('docs','dir')\n exist('/docs','dir')\n", "language": "MATLAB" }, { "code": "-- Here\ndoesFileExist \"input.txt\"\n(getDirectories \"docs\").count == 1\n-- Root\ndoesFileExist \"\\input.txt\"\n(getDirectories \"C:\\docs\").count == 1\n", "language": "MAXScript" }, { "code": "MODULE FileTest EXPORTS Main;\n\nIMPORT IO, Fmt, FS, File, OSError, Pathname;\n\nPROCEDURE FileExists(file: Pathname.T): BOOLEAN =\n VAR status: File.Status;\n BEGIN\n TRY\n status := FS.Status(file);\n RETURN TRUE;\n EXCEPT\n | OSError.E => RETURN FALSE;\n END;\n END FileExists;\n\nBEGIN\n IO.Put(Fmt.Bool(FileExists(\"input.txt\")) & \"\\n\");\n IO.Put(Fmt.Bool(FileExists(\"/input.txt\")) & \"\\n\");\n IO.Put(Fmt.Bool(FileExists(\"docs/\")) & \"\\n\");\n IO.Put(Fmt.Bool(FileExists(\"/docs\")) & \"\\n\");\nEND FileTest.\n", "language": "Modula-3" }, { "code": "import Nanoquery.IO\n\ndef exists(fname)\n\tf = new(File, fname)\n\n\treturn f.exists()\nend\n", "language": "Nanoquery" }, { "code": "/**\n Check that file/dir exists, in Neko\n*/\n\nvar sys_exists = $loader.loadprim(\"std@sys_exists\", 1)\nvar sys_file_type = $loader.loadprim(\"std@sys_file_type\", 1)\nvar sys_command = $loader.loadprim(\"std@sys_command\", 1)\n\nvar name = \"input.txt\"\n$print(name, \" exists as file: \", sys_exists(name), \"\\n\")\n\n$print(name = \"docs\", \" exists as dir: \", sys_exists(name) && sys_file_type(name) == \"dir\", \"\\n\")\n$print(name = \"neko\", \" exists as dir: \", sys_exists(name) && sys_file_type(name) == \"dir\", \"\\n\")\n\n$print(name = \"/input.txt\", \" exists as file: \", sys_exists(name) && sys_file_type(name) == \"file\", \"\\n\")\n$print(name = \"/docs\", \" exists as dir: \", sys_exists(name) && sys_file_type(name) == \"dir\", \"\\n\")\n$print(name = \"/tmp\", \" exists as dir: \", sys_exists(name) && sys_file_type(name) == \"dir\", \"\\n\")\n\n/* bonus round */\nname = \"empty.txt\"\nvar stat_size = $loader.loadprim(\"std@sys_stat\", 1)(name).size\n$print(name, \" exists as empty file: \", sys_exists(name) && stat_size == 0, \"\\n\")\n\nname = \"`Abdu'l-Bahá.txt\"\n$print(name, \" exists as file: \", sys_exists(name) && sys_file_type(name) == \"file\", \"\\n\")\n", "language": "Neko" }, { "code": "using System.Console;\nusing System.IO;\n\nWriteLine(File.Exists(\"input.txt\"));\nWriteLine(File.Exists(\"/input.txt\"));\nWriteLine(Directory.Exists(\"docs\"));\nWriteLine(Directory.Exists(\"/docs\"));\n", "language": "Nemerle" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols binary\n\nrunSample(arg)\nreturn\n\n-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\nmethod isExistingFile(fn) public static returns boolean\n ff = File(fn)\n fExists = ff.exists() & ff.isFile()\n return fExists\n\n-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\nmethod isExistingDirectory(fn) public static returns boolean\n ff = File(fn)\n fExists = ff.exists() & ff.isDirectory()\n return fExists\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod runSample(arg) private static\n parse arg files\n if files = '' then files = 'input.txt F docs D /input.txt F /docs D'\n loop while files.length > 0\n parse files fn ft files\n select case(ft.upper())\n when 'F' then do\n if isExistingFile(fn) then ex = 'exists'\n else ex = 'does not exist'\n say 'File '''fn'''' ex\n end\n when 'D' then do\n if isExistingDirectory(fn) then ex = 'exists'\n else ex = 'does not exist'\n say 'Directory '''fn'''' ex\n end\n otherwise do\n if isExistingFile(fn) then ex = 'exists'\n else ex = 'does not exist'\n say 'File '''fn'''' ex\n end\n end\n end\n\n return\n", "language": "NetRexx" }, { "code": "(dolist (file '(\"input.txt\" \"/input.txt\"))\n (if (file? file true)\n (println \"file \" file \" exists\")))\n\n(dolist (dir '(\"docs\" \"/docs\"))\n (if (directory? dir)\n (println \"directory \" dir \" exists\")))\n", "language": "NewLISP" }, { "code": "import os\n\necho fileExists \"input.txt\"\necho fileExists \"/input.txt\"\necho dirExists \"docs\"\necho dirExists \"/docs\"\n", "language": "Nim" }, { "code": "use IO;\n\nbundle Default {\n class Test {\n function : Main(args : String[]) ~ Nil {\n File->Exists(\"input.txt\")->PrintLine();\n File->Exists(\"/input.txt\")->PrintLine();\n Directory->Exists(\"docs\")->PrintLine();\n Directory->Exists(\"/docs\")->PrintLine();\n }\n}\n", "language": "Objeck" }, { "code": "NSFileManager *fm = [NSFileManager defaultManager];\nNSLog(@\"input.txt %s\", [fm fileExistsAtPath:@\"input.txt\"] ? @\"exists\" : @\"doesn't exist\");\nNSLog(@\"docs %s\", [fm fileExistsAtPath:@\"docs\"] ? @\"exists\" : @\"doesn't exist\");\n", "language": "Objective-C" }, { "code": "Sys.file_exists \"input.txt\";;\nSys.file_exists \"docs\";;\nSys.file_exists \"/input.txt\";;\nSys.file_exists \"/docs\";;\n", "language": "OCaml" }, { "code": "package main\n\nimport \"core:os\"\n\nmain :: proc() {\n os.exists(\"input.txt\")\n os.exists(\"/input.txt\")\n os.exists(\"docs\")\n os.exists(\"/docs\")\n}\n", "language": "Odin" }, { "code": "/**********************************************************************\n* exists(filespec)\n* returns 1 if filespec identifies a file with size>0\n* (a file of size 0 is deemed not to exist.)\n* or a directory\n* 0 otherwise\n* 09.06.2013 Walter Pachl (retrieved from my toolset)\n**********************************************************************/\nexists:\n parse arg spec\n call sysfiletree spec, 'LIST', 'BL'\n if list.0\\=1 then return 0 -- does not exist\n parse var list.1 . . size flags .\n if size>0 then return 1 -- real file\n If substr(flags,2,1)='D' Then Do\n Say spec 'is a directory'\n Return 1\n End\n If size=0 Then Say spec 'is a zero-size file'\n Return 0\n", "language": "OoRexx" }, { "code": "declare\n [Path] = {Module.link ['x-oz://system/os/Path.ozf']}\nin\n {Show {Path.exists \"docs\"}}\n {Show {Path.exists \"input.txt\"}}\n {Show {Path.exists \"/docs\"}}\n {Show {Path.exists \"/input.txt\"}}\n", "language": "Oz" }, { "code": "trap(,\"does not exist\",read(\"input.txt\");\"exists\")\ntrap(,\"does not exist\",read(\"c:\\\\input.txt\");\"exists\")\ntrap(,\"does not exist\",read(\"c:\\\\dirname\\\\nul\");\"exists\")\n", "language": "PARI-GP" }, { "code": "use File::Spec::Functions qw(catfile rootdir);\n# here\nprint -e 'input.txt';\nprint -d 'docs';\n# root dir\nprint -e catfile rootdir, 'input.txt';\nprint -d catfile rootdir, 'docs';\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span> <span style=\"color: #000080;font-style:italic;\">-- (file i/o)</span>\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">check</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">name</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">bExists</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">file_exists</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">name</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">bDir</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">get_file_type</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">name</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #004600;\">FILETYPE_DIRECTORY</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">exists</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">bExists</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"exists\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"does not exist\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">dfs</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">bExists</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">bDir</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"directory \"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"file \"</span><span style=\"color: #0000FF;\">):</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s%s %s.\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">dfs</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">name</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">exists</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">check</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"input.txt\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">check</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"docs\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">check</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"/input.txt\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">check</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"/docs\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">check</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"/pagefile.sys\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">check</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"/Program Files (x86)\"</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "\"foo.bar\" \"w\" fopen\n\"Hallo !\" over fputs\nfclose\n\n\"fou.bar\" \"r\" fopen\ndup 0 < if \"Could not open 'foo.bar' for reading\" print drop else fclose endif\n", "language": "Phixmonti" }, { "code": "if (file_exists('input.txt')) echo 'input.txt is here right by my side';\nif (file_exists('docs' )) echo 'docs is here with me';\nif (file_exists('/input.txt')) echo 'input.txt is over there in the root dir';\nif (file_exists('/docs' )) echo 'docs is over there in the root dir';\n", "language": "PHP" }, { "code": "(if (info \"file.txt\")\n (prinl \"Size: \" (car @) \" bytes, last modified \" (stamp (cadr @) (cddr @)))\n (prinl \"File doesn't exist\") )\n\n# for directory existing\n# Nehal-Singhal 2018-05-25\n\n(if (info \"./docs\")\n (print 'exists)\n (print 'doesNotExist)))\n\n# To verify if it's really a directory, (CAR of return value will be 'T').\n# abu 2018-05-25\n\n (let I (info \"./docs\")\n (prinl\n (nond\n (I \"Does not exist\")\n ((=T (car I)) \"Is not a directory\")\n (NIL \"Directory exists\") ) ) )\n", "language": "PicoLisp" }, { "code": "import Stdio;\n\nint main(){\n if(exist(\"/var\")){\n write(\"/var exists!\\n\");\n }\n\n if(exist(\"file-exists.pike\")){\n write(\"I exist!\\n\");\n }\n}\n", "language": "Pike" }, { "code": "*Process source or(!);\n /*********************************************************************\n * 20.10.2013 Walter Pachl\n * 'set dd:f=d:\\_l\\xxx.txt,recsize(300)'\n * 'tex'\n *********************************************************************/\n tex: Proc Options(main);\n Dcl fid Char(30) Var Init('D:\\_l\\tst.txt');\n Dcl xxx Char(30) Var Init('D:\\_l\\nix.txt');\n Dcl r Char(1000) Var;\n Dcl f Record input;\n On Undefinedfile(f) Goto label;\n Open File(f) Title('/'!!fid);\n Read file(f) Into(r);\n Put Skip List('First line of file '!!fid!!': '!!r);\n Close File(f);\n Open File(f) Title('/'!!xxx);\n Read file(f) Into(r);\n Put Skip List(r);\n Close File(f);\n Label: Put Skip List('File '!!xxx!!' not found');\n End;\n", "language": "PL-I" }, { "code": "100H:\n\n DECLARE FCB$SIZE LITERALLY '36';\n\n BDOS: PROCEDURE( FN, ARG )BYTE; /* CP/M BDOS SYSTEM CALL, RETURNS A VALUE */\n DECLARE FN BYTE, ARG ADDRESS;\n GOTO 5;\n END BDOS;\n BDOS$P: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL, NO RETURN VALUE */\n DECLARE FN BYTE, ARG ADDRESS;\n GOTO 5;\n END BDOS$P;\n PRINT$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS$P( 2, C ); END;\n PRINT$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS$P( 9, S ); END;\n PRINT$NL: PROCEDURE; CALL PRINT$STRING( .( 0DH, 0AH, '$' ) ); END;\n SEARCH$FIRST: PROCEDURE( FCB )BYTE; /* RETURN 0, 1, 2, 3 IF FILE IN FCB */\n DECLARE FCB ADDRESS; /* EXISTS, 255 OTHERWISE */\n RETURN BDOS( 17, FCB );\n END SEARCH$FIRST ;\n\n INIT$FCB: PROCEDURE( FCB, NAME ); /* INITIALISE A FILE-CONTROL-BLOCK */\n DECLARE ( FCB, NAME ) ADDRESS; /* SETTING THE FILE NAME */\n DECLARE ( F$PTR, N$PTR, X$PTR ) ADDRESS;\n DECLARE F BASED F$PTR BYTE, N BASED N$PTR BYTE;\n DECLARE BLANKS ( 5 )BYTE INITIAL( ' ', ' ', ' ', ' ', '$' );\n X$PTR = .BLANKS;\n N$PTR = NAME + 1;\n F$PTR = FCB;\n IF N <> ':' THEN DO; /* NO DRIVE LETTER */\n F = 0;\n N$PTR = NAME;\n END;\n ELSE DO; /* FIRST CHAR IS THE DRIVE LETTER */\n N$PTR = NAME;\n F = ( N + 1 ) - 'A';\n N$PTR = N$PTR + 2;\n END;\n DO F$PTR = FCB + 1 TO FCB + 8; /* NAME */\n IF N = '$' THEN N$PTR = .BLANKS;\n ELSE IF N = '.' THEN DO; /* START OF THE EXTENSION */\n X$PTR = N$PTR + 1;\n N$PTR = .BLANKS;\n END;\n F = N;\n N$PTR = N$PTR + 1;\n END;\n N$PTR = X$PTR; /* EXTENSION */\n DO F$PTR = FCB + 9 TO FCB + 11;\n IF N = '$' THEN N$PTR =.BLANKS;\n F = N;\n N$PTR = N$PTR + 1;\n END;\n DO F$PTR = FCB + 12 TO FCB + ( FCB$SIZE - 1 ); /* OTHER FIELDS */\n F = 0;\n END;\n END INIT$FCB ;\n\n EXISTS: PROCEDURE( FCB )BYTE; /* RETURNS TRUE IF THE FILE NAMED IN THE */\n DECLARE FCB ADDRESS; /* FCB EXISTS */\n RETURN ( SEARCH$FIRST( FCB ) < 4 );\n END EXISTS ;\n\n DECLARE FCB$1$DATA ( FCB$SIZE )BYTE; /* DECLARE A FILE-CONTROL-BLOCK */\n DECLARE FCB$1 ADDRESS;\n FCB$1 = .FCB$1$DATA;\n\n /* CP/M DOES NOT HAVE DIRECTORIES/FOLDERS - THIS TESTS FOR INPUT.TXT IN */\n /* THE CURRENT DEFAULT DRIVE */\n CALL INIT$FCB( FCB$1, .'INPUT.TXT$' );\n CALL PRINT$STRING( .'INPUT.TXT: $' );\n IF EXISTS( FCB$1 ) THEN CALL PRINT$STRING( .'EXISTS$' );\n ELSE CALL PRINT$STRING( .'DOES NOT EXIST$' );\n CALL PRINT$NL;\n\n /* CHECK FOR INPUT.TXT IN THE D: DRIVE */\n /* !!! THIS WILL CAUSE AN ERROR IF THERE IS NO DRIVE D: !!! */\n /* !!! OR THERE IS NO DISC IN DRIVE D: !!! */\n CALL INIT$FCB( FCB$1, .'D:INPUT.TXT$' );\n CALL PRINT$STRING( .'D:INPUT.TXT: $' );\n IF EXISTS( FCB$1 ) THEN CALL PRINT$STRING( .'EXISTS$' );\n ELSE CALL PRINT$STRING( .'DOES NOT EXIST$' );\n CALL PRINT$NL;\n\nEOF\n", "language": "PL-M" }, { "code": "To run:\nStart up.\n\\ In the current working directory\nCheck that \".\\input.txt\" is in the file system.\nCheck that \".\\docs\\\" is in the file system.\n\\ In the filesystem root\nCheck that \"C:\\input.txt\" is in the file system.\nCheck that \"C:\\docs\\\" is in the file system.\nWait for the escape key.\nShut down.\n\nTo check that a path is in the file system:\nIf the path is in the file system, write the path then \" exists\" to the output; exit.\nIf the path is not in the file system, write the path then \" does not exist\" to the output; exit.\n", "language": "Plain-English" }, { "code": "sys_file_exists('input.txt') =>\nsys_file_exists('/input.txt') =>\nsys_file_exists('docs') =>\nsys_file_exists('/docs') =>\n", "language": "Pop11" }, { "code": ";;; Define an auxilary function, returns boolean\ndefine file_readable(fname);\n lvars f = sysopen(fname, 0, true, `A`);\n if f then\n sysclose(f);\n return (true);\n else\n return (false);\n endif;\nenddefine;\n", "language": "Pop11" }, { "code": " if (Test-Path -Path .\\input.txt) {\n write-host \"File input exist\"\n}\nelse {\n write-host \"File input doesn't exist\"\n}\n", "language": "PowerShell" }, { "code": "exists_file('input.txt'),\nexists_directory('docs').\n\nexits_file('/input.txt'),\nexists_directory('/docs').\n", "language": "Prolog" }, { "code": "result = ReadFile(#PB_Any, \"input.txt\")\nIf result>0 : Debug \"this local file exists\"\n Else : Debug \"result=\" +Str(result) +\" so this local file is missing\"\nEndIf\n\nresult = ReadFile(#PB_Any, \"/input.txt\")\nIf result>0 : Debug \"this root file exists\"\n Else : Debug \"result=\" +Str(result) +\" so this root file is missing\"\nEndIf\n\nresult = ExamineDirectory(#PB_Any,\"docs\",\"\")\nIf result>0 : Debug \"this local directory exists\"\n Else : Debug \"result=\" +Str(result) +\" so this local directory is missing\"\nEndIf\n\nresult = ExamineDirectory(#PB_Any,\"/docs\",\"\")\nIf result>0 : Debug \"this root directory exists\"\n Else : Debug \"result=\" +Str(result) +\" so this root directory is missing\"\nEndIf\n", "language": "PureBasic" }, { "code": "import os\n\nos.path.isfile(\"input.txt\")\nos.path.isfile(\"/input.txt\")\nos.path.isdir(\"docs\")\nos.path.isdir(\"/docs\")\n", "language": "Python" }, { "code": "$NOPREFIX\nPRINT DIREXISTS(\"docs\")\nPRINT DIREXISTS(\"\\docs\")\nPRINT FILEEXISTS(\"input.txt\")\nPRINT FILEEXISTS(\"\\input.txt\")\n", "language": "QB64" }, { "code": "file.exists(\"input.txt\")\nfile.exists(\"/input.txt\")\nfile.exists(\"docs\")\nfile.exists(\"/docs\")\n\n# or\nfile.exists(\"input.txt\", \"/input.txt\", \"docs\", \"/docs\")\n", "language": "R" }, { "code": "file.exists(\"`Abdu'l-Bahá.txt\")\n", "language": "R" }, { "code": "#lang racket\n\n;; here\n(file-exists? \"input.txt\")\n(file-exists? \"docs\")\n\n;; in the root\n(file-exists? \"/input.txt\")\n(file-exists? \"/docs\")\n\n;; or in the root with relative paths\n(parameterize ([current-directory \"/\"])\n (and (file-exists? \"input.txt\")\n (file-exists? \"docs\")))\n", "language": "Racket" }, { "code": "my $path = \"/etc/passwd\";\nsay $path.IO.e ?? \"Exists\" !! \"Does not exist\";\n\ngiven $path.IO {\n when :d { say \"$path is a directory\"; }\n when :f { say \"$path is a regular file\"; }\n when :e { say \"$path is neither a directory nor a file, but it does exist\"; }\n default { say \"$path does not exist\" }\n}\n", "language": "Raku" }, { "code": "run ('touch', \"♥ Unicode.txt\");\n\nsay \"♥ Unicode.txt\".IO.e; # \"True\"\nsay \"♥ Unicode.txt\".IO ~~ :e; # same\n", "language": "Raku" }, { "code": "'input.txt' exists if 'input.txt exists' print\n'/input.txt' exists if '/input.txt exists' print\n'docs' isdir if 'docs exists and is a directory' print\n'/docs' isdir if '/docs exists and is a directory' print\n", "language": "Raven" }, { "code": "exists? %input.txt\nexists? %docs/\n\nexists? %/input.txt\nexists? %/docs/\n", "language": "REBOL" }, { "code": "exists? %input.txt\nexists? %docs/\nexists? %/c/input.txt\nexists? %/c/docs/\nexists? %//input.txt\nexists? %//docs/\n\n>> exists? %`Abdu'l-Bahá.txt\n== true\n", "language": "Red" }, { "code": "/*REXX program creates a new empty file and directory in current directory and root dir.*/\nfn= 'input.txt' /*default name of a file. */\ndn= 'docs' /*default name of a directory (folder).*/\[email protected]= 'current directory'; @.2= 'root directory' /*messages used to indicate which pass.*/\nparse upper version v /*obtain name of the REXX being used. */\nregina= pos('REGINA' , v)\\==0 /*is this the Regina REXX being used? */\nr4 = pos('REXX-R4' , v)\\==0 /*is this the R4 REXX being used? */\n@doesnt= \"doesn't exist in the\"\n@does = \"does exist in the\"\n\n do j=1 for 2; say /* [↑] perform these statements twice.*/\n if stream(fn, 'C', \"QUERY EXISTS\")=='' then say 'file ' fn @doesnt @.j\n else say 'file ' fn @does @.j\n\n if j==2 then iterate\n if stream(dn, 'C', \"QUERY EXISTS\")=='' then say 'directory' dn @doesnt @.j\n else say 'directory' dn @does @.j\n if j==1 then select\n when regina then call chdir '\\' /*use Regina's version of CHDIR. */\n when r4 then call stream '\\', \"C\", 'CHDIR' /*R4's version. */\n otherwise call doschdir '\\' /*PC/REXX & Personal REXX version.*/\n end /*select*/\n end /*j*/ /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "/* Check if a file already exists */\nfilename='file.txt'\nIF ~Openfile(filename) THEN CALL Openfile(':'filename)\nEXIT 0\nOpenfile:\nIF ~Exists(filename) THEN RETURN 0\nCALL Open(filehandle,filename,'APPEND')\nRETURN 1\n", "language": "REXX" }, { "code": "aFile = \"C:\\Ring\\ReadMe.txt\"\nsee aFile\nif Fexists(aFile) see \" exists\" + nl\nelse see \" doesn't exist\" + nl ok\n", "language": "Ring" }, { "code": ">> isdir(\"docs\")\n 0\n>> isfile(\"input.txt\")\n 0\n", "language": "RLaB" }, { "code": "File.file?(\"input.txt\")\nFile.file?(\"/input.txt\")\nFile.directory?(\"docs\")\nFile.directory?(\"/docs\")\n", "language": "Ruby" }, { "code": "[\"input.txt\", \"/input.txt\"].each { |f|\n printf \"%s is a regular file? %s\\n\", f, File.file?(f) }\n[\"docs\", \"/docs\"].each { |d|\n printf \"%s is a directory? %s\\n\", d, File.directory?(d) }\n", "language": "Ruby" }, { "code": "files #f,\"input.txt\"\nif #f hasanswer() = 1 then print \"File does not exist\"\nfiles #f,\"docs\"\nif #f hasanswer() = 1 then print \"File does not exist\"\nif #f isDir() = 0 then print \"This is a directory\"\n", "language": "Run-BASIC" }, { "code": "use std::fs;\n\nfn main() {\n for file in [\"input.txt\", \"docs\", \"/input.txt\", \"/docs\"].iter() {\n match fs::metadata(file) {\n Ok(attr) => {\n if attr.is_dir() {\n println!(\"{} is a directory\", file);\n }else {\n println!(\"{} is a file\", file);\n }\n },\n Err(_) => {\n println!(\"{} does not exist\", file);\n }\n };\n }\n}\n", "language": "Rust" }, { "code": "import java.nio.file.{ Files, FileSystems }\n\nobject FileExistsTest extends App {\n\n val defaultFS = FileSystems.getDefault()\n val separator = defaultFS.getSeparator()\n\n def test(filename: String) {\n val path = defaultFS.getPath(filename)\n\n println(s\"The following ${if (Files.isDirectory(path)) \"directory\" else \"file\"} called $filename\" +\n (if (Files.exists(path)) \" exists.\" else \" not exists.\"))\n }\n\n // main\n List(\"output.txt\", separator + \"output.txt\", \"docs\", separator + \"docs\" + separator).foreach(test)\n}\n", "language": "Scala" }, { "code": "(file-exists? filename)\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst proc: main is func\n begin\n writeln(fileType(\"input.txt\") = FILE_REGULAR);\n writeln(fileType(\"/input.txt\") = FILE_REGULAR);\n writeln(fileType(\"docs\") = FILE_DIR);\n writeln(fileType(\"/docs\") = FILE_DIR);\n end func;\n", "language": "Seed7" }, { "code": "put file \"input.txt\" exists\t\nput folder \"docs\" exists\n \t\t \t\t\nput file \"/input.txt\" exists\t\nput there is a folder \"/docs\"\t\n", "language": "SenseTalk" }, { "code": "# Here\nsay (Dir.cwd + %f'input.txt' -> is_file);\nsay (Dir.cwd + %d'docs' -> is_dir);\n\n# Root\nsay (Dir.root + %f'input.txt' -> is_file);\nsay (Dir.root + %d'docs' -> is_dir);\n", "language": "Sidef" }, { "code": "(File newNamed: 'input.txt') exists\n(File newNamed: '/input.txt') exists\n(Directory root / 'input.txt') exists\n(Directory newNamed: 'docs') exists\n(Directory newNamed: '/docs') exists\n", "language": "Slate" }, { "code": "FileDirectory new fileExists: 'c:\\serial'.\n(FileDirectory on: 'c:\\') directoryExists: 'docs'.\n", "language": "Smalltalk" }, { "code": "(Directory name: 'docs') exists ifTrue: [ ... ]\n(Directory name: 'c:\\docs') exists ifTrue: [ ... ]\n(File name: 'serial') isFile ifTrue: [ ... ]\n(File name: 'c:\\serial') isFile ifTrue: [ ... ]\n", "language": "Smalltalk" }, { "code": "OS.FileSys.access (\"input.txt\", []);\nOS.FileSys.access (\"docs\", []);\nOS.FileSys.access (\"/input.txt\", []);\nOS.FileSys.access (\"/docs\", []);\n", "language": "Standard-ML" }, { "code": "mata\nfileexists(\"input.txt\")\ndirexists(\"docs\")\nend\n", "language": "Stata" }, { "code": "capture confirm file input.txt\nif !_rc {\n\t* do something if the file exists\n}\n", "language": "Stata" }, { "code": "confirmdir docs\nif !`r(confirmdir)' {\n\t* do something if the directory exists\n}\n", "language": "Stata" }, { "code": "confirm file \"\\`Abdu'l-Bahá.txt\"\n", "language": "Stata" }, { "code": "if { [file exists \"input.txt\"] } {\n puts \"input.txt exists\"\n}\n\nif { [file exists [file nativename \"/input.txt\"]] } {\n puts \"/input.txt exists\"\n}\n\nif { [file isdirectory \"docs\"] } {\n puts \"docs exists and is a directory\"\n}\n\nif { [file isdirectory [file nativename \"/docs\"]] } {\n puts \"/docs exists and is a directory\"\n}\n", "language": "Tcl" }, { "code": "[ \"R\" file.open dup 0 <> [ dup file.close ] ifTrue 0 <> ] is exists?\n\" input.txt\" exists? .\n\" /input.txt\" exists? .\n\" docs\" exists? .\n\" /docs\" exists? .\n", "language": "Toka" }, { "code": "SUB opener (a$)\n WHEN EXCEPTION IN\n OPEN #1: NAME f$\n PRINT f$; \" exists\"\n USE\n PRINT f$; \" not exists\"\n END WHEN\n CLOSE #1\nEND SUB\n\nLET f$ = \"input.txt\"\nCALL opener (f$)\nLET f$ = \"\\input.txt\"\nCALL opener (f$)\nLET f$ = \"docs\\nul\"\nCALL opener (f$)\nLET f$ = \"\\docs\\nul\"\nCALL opener (f$)\n\nLET f$ = \"empty.tru\"\nCALL opener (f$)\nLET f$ = \"`Abdu'l-Bahá.txt\"\nCALL opener (f$)\nEND\n", "language": "True-BASIC" }, { "code": "$$ MODE TUSCRIPT\nfile=\"input.txt\",directory=\"docs\"\nIF (file=='file') THEN\nPRINT file, \" exists\"\nELSE\nPRINT/ERROR file,\" not exists\"\nENDIF\nIF (directory=='project') THEN\nPRINT directory,\" exists\"\nELSE\nPRINT/ERROR \"directory \",directory,\" not exists\"\nENDIF\n", "language": "TUSCRIPT" }, { "code": "test -f input.txt\ntest -f /input.txt\ntest -d docs\ntest -d /docs\n", "language": "UNIX-Shell" }, { "code": "for f in input.txt /input.txt; do\n\ttest -f \"$f\" && r=true || r=false\n\techo \"$f is a regular file? $r\"\ndone\nfor d in docs /docs; do\n\ttest -d \"$d\" && r=true || r=false\n\techo \"$d is a directory? $r\"\ndone\n", "language": "UNIX-Shell" }, { "code": "def exists (string filename)\n\tdecl file f\n\ttry\n\t\tf.open filename\n\t\treturn true\n\tcatch ioerror\n\t\treturn false\n\tend try\nend exists\n", "language": "Ursa" }, { "code": "// Check file exists in V\n// Tectonics: v run check-that-file-exists.v\nmodule main\nimport os\n\n// starts here\npub fn main() {\n // file and directory checks\n _ := os.execute(\"touch input.txt\")\n println(\"os.is_file('input.txt'): ${os.is_file('input.txt')}\")\n\n // make doc directory in current dir if it doesn't exist\n _ := os.execute(\"mkdir -p doc\")\n println(\"os.is_dir('doc'): ${os.is_dir('doc')}\")\n\n // check in the root dir\n println(\"os.is_file('/input.txt'): ${os.is_file('/input.txt')}\")\n println(\"os.is_dir('/doc'): ${os.is_dir('/doc')}\")\n\n // check for file, with empty file\n _ := os.execute(\"truncate -s 0 empty.txt\")\n println(\"os.is_file('empty.txt'): ${os.is_file('empty.txt')}\")\n\n // check for file, with exotic name\n wfn := \"`Abdu'l-Bahá.txt\"\n efn := wfn.replace_each([\"'\", r\"\\'\", \"`\", r\"\\`\"])\n _ := os.execute('touch $efn')\n println('os.is_file(\"$wfn\"): ${os.is_file(wfn)}')\n}\n", "language": "V-(Vlang)" }, { "code": "int main (string[] args) {\n string[] files = {\"input.txt\", \"docs\", Path.DIR_SEPARATOR_S + \"input.txt\", Path.DIR_SEPARATOR_S + \"docs\"};\n foreach (string f in files) {\n var file = File.new_for_path (f);\n print (\"%s exists: %s\\n\", f, file.query_exists ().to_string ());\n }\n return 0;\n}\n", "language": "Vala" }, { "code": "int main (string[] args) {\n string[] files = {\"input.txt\", \"docs\", Path.DIR_SEPARATOR_S + \"input.txt\", Path.DIR_SEPARATOR_S + \"docs\"};\n foreach (var f in files) {\n var file = File.new_for_path (f);\n var exists = file.query_exists ();\n var name = \"\";\n if (!exists) {\n print (\"%s does not exist\\n\", f);\n } else {\n var type = file.query_file_type (FileQueryInfoFlags.NOFOLLOW_SYMLINKS);\n if (type == 1) {\n name = \"file\";\n } else if (type == 2) {\n name = \"directory\";\n }\n print (\"%s %s exists\\n\", name, f);\n }\n }\n return 0;\n}\n", "language": "Vala" }, { "code": "Option Explicit\n\nSub Main_File_Exists()\nDim myFile As String, myDirectory As String\n\n myFile = \"Abdu'l-Bahá.txt\"\n myDirectory = \"C:\\\"\n Debug.Print File_Exists(myFile, myDirectory)\nEnd Sub\n\nFunction File_Exists(F As String, D As String) As Boolean\n If F = \"\" Then\n File_Exists = False\n Else\n D = IIf(Right(D, 1) = \"\\\", D, D & \"\\\")\n File_Exists = (Dir(D & F) <> \"\")\n End If\nEnd Function\n", "language": "VBA" }, { "code": "Set FSO = CreateObject(\"Scripting.FileSystemObject\")\n\nFunction FileExists(strFile)\n If FSO.FileExists(strFile) Then\n FileExists = True\n Else\n FileExists = False\n End If\nEnd Function\n\nFunction FolderExists(strFolder)\n If FSO.FolderExists(strFolder) Then\n FolderExists = True\n Else\n Folderexists = False\n End If\nEnd Function\n\n'''''Usage (apostrophes indicate comments-this section will not be run)'''''\n'If FileExists(\"C:\\test.txt\") Then\n' MsgBox \"It Exists!\"\n'Else\n' Msgbox \"awww\"\n'End If\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n\n'Shorter version\n\nIf CreateObject(\"Scripting.FileSystemObject\").FileExists(\"d:\\test.txt\") Then\n Wscript.Echo \"File Exists\"\nElse\n Wscript.Echo \"File Does Not Exist\")\nEnd If\n", "language": "VBScript" }, { "code": "// In current directory\nif (File_Exist(\"input.txt\")) { M(\"input.txt exists\\n\") } else { M(\"input.txt does not exist\\n\") }\nif (File_Exist(\"docs/nul\", NOERR)) { M(\"docs exists\\n\") } else { M(\"docs does not exist\\n\") }\n\n// In the root directory\nif (File_Exist(\"/input.txt\")) { M(\"/input.txt exists\\n\") } else { M(\"/input.txt does not exist\\n\") }\nif (File_Exist(\"/docs/nul\", NOERR)) { M(\"/docs exists\\n\") } else { M(\"/docs does not exist\\n\") }\n", "language": "Vedit-macro-language" }, { "code": "'declarations:\nPublic Declare Function GetFileAttributes Lib \"kernel32\" _\n Alias \"GetFileAttributesA\" (ByVal lpFileName As String) As Long\nPublic Const INVALID_FILE_ATTRIBUTES As Long = -1\nPublic Const ERROR_SHARING_VIOLATION As Long = 32&\n\n'implementation:\nPublic Function FileExists(ByVal Filename As String) As Boolean\nDim l As Long\nl = GetFileAttributes(Filename)\n If l <> INVALID_FILE_ATTRIBUTES Then\n FileExists = ((l And vbDirectory) = 0)\n ElseIf Err.LastDllError = ERROR_SHARING_VIOLATION Then\n FileExists = True\n End If\nEnd Function\n", "language": "Visual-Basic" }, { "code": "'Current Directory\nConsole.WriteLine(If(IO.Directory.Exists(\"docs\"), \"directory exists\", \"directory doesn't exists\"))\nConsole.WriteLine(If(IO.Directory.Exists(\"output.txt\"), \"file exists\", \"file doesn't exists\"))\n\n'Root\nConsole.WriteLine(If(IO.Directory.Exists(\"\\docs\"), \"directory exists\", \"directory doesn't exists\"))\nConsole.WriteLine(If(IO.Directory.Exists(\"\\output.txt\"), \"file exists\", \"file doesn't exists\"))\n\n'Root, platform independent\nConsole.WriteLine(If(IO.Directory.Exists(IO.Path.DirectorySeparatorChar & \"docs\"), _\n \"directory exists\", \"directory doesn't exists\"))\nConsole.WriteLine(If(IO.Directory.Exists(IO.Path.DirectorySeparatorChar & \"output.txt\"), _\n \"file exists\", \"file doesn't exists\"))\n", "language": "Visual-Basic-.NET" }, { "code": "import \"io\" for Directory, File\n\nfor (name in [\"input.txt\", \"`Abdu'l-Bahá.txt\"]) {\n if (File.exists(name)) {\n System.print(\"%(name) file exists and has a size of %(File.size(name)) bytes.\")\n } else {\n System.print(\"%(name) file does not exist.\")\n }\n}\n\nvar dir = \"docs\"\n// if it exists get number of files it contains\nif (Directory.exists(dir)) {\n var files = Directory.list(dir).count\n System.print(\"%(dir) directory exists and contains %(files) files.\")\n} else {\n System.print(\"%(dir) directory does not exist.\")\n}\n", "language": "Wren" }, { "code": "int FD; \\file descriptor\n[Trap(false);\t\\prevent errors from aborting program\nFD:= FOpen(\"input.txt\", 0);\nif GetErr then Text(0, \"input.txt doesn't exist^m^j\");\nFD:= FOpen(\"dir\", 0);\nif GetErr then Text(0, \"dir doesn't exist^m^j\");\nFD:= FOpen(\"/input.txt\", 0);\nif GetErr then Text(0, \"/input.txt doesn't exist^m^j\");\nFD:= FOpen(\"/dir\", 0);\nif GetErr then Text(0, \"/dir doesn't exist^m^j\");\n]\n", "language": "XPL0" }, { "code": "open \"foo.bar\" for writing as #1\nprint #1 \"Hallo !\"\nclose #1\nif (not open(1,\"foo.bar\")) print \"Could not open 'foo.bar' for reading\"\nclose #1\nif (not open(1,\"buzz.bar\")) print \"Could not open 'buzz.bar' for reading\"\n", "language": "Yabasic" }, { "code": "File.exists(\"input.txt\") //--> True (in this case a sym link)\nFile.exists(\"/input.txt\") //-->False\nFile.isDir(\"/\") //-->True\nFile.isDir(\"docs\") //-->False\n", "language": "Zkl" } ]
Check-that-file-exists
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Chernick's_Carmichael_numbers\nnote: Mathematics\n", "language": "00-META" }, { "code": "[[category:Prime Numbers]]\nIn 1939, Jack Chernick proved that, for '''n ≥ 3''' and '''m ≥ 1''':\n\n U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)\n\nis a [https://en.wikipedia.org/wiki/Carmichael_number Carmichael number] if all the factors are primes and, for '''n > 4''', '''m''' is a multiple of '''2^(n-4)'''.\n\n\n;Example\n\n U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)\n U(4, m) = U(3, m) * (2^2 * 9m + 1)\n U(5, m) = U(4, m) * (2^3 * 9m + 1)\n ...\n U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1)\n\n* The smallest Chernick's Carmichael number with '''3''' prime factors, is: U(3, 1) = 1729.\n* The smallest Chernick's Carmichael number with '''4''' prime factors, is: U(4, 1) = 63973.\n* The smallest Chernick's Carmichael number with '''5''' prime factors, is: U(5, 380) = 26641259752490421121.\n\n\nFor '''n = 5''', the smallest number '''m''' that satisfy Chernick's conditions, is '''m = 380''', therefore '''U(5, 380)''' is the smallest Chernick's Carmichael number with '''5''' prime factors.\n\n'''U(5, 380)''' is a Chernick's Carmichael number because '''m = 380''' is a multiple of '''2^(n-4)''', where '''n = 5''', and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers.\n\n\n;Task\n\nFor '''n ≥ 3''', let '''a(n)''' be the smallest Chernick's Carmichael number with '''n''' prime factors.\n\n* Compute '''a(n)''' for '''n = 3..9'''.\n* Optional: find '''a(10)'''.\n\n\n'''Note''': it's perfectly acceptable to show the terms in factorized form:\n\n a(3) = 7 * 13 * 19\n a(4) = 7 * 13 * 19 * 37\n a(5) = 2281 * 4561 * 6841 * 13681 * 27361\n ...\n\n\n;See also\n\n* [http://www.ams.org/journals/bull/1939-45-04/S0002-9904-1939-06953-X/S0002-9904-1939-06953-X.pdf Jack Chernick, On Fermat's simple theorem (PDF)]\n\n* [https://oeis.org/A318646 OEIS A318646: The least Chernick's \"universal form\" Carmichael number with n prime factors]\n\n\n; Related tasks\n* [[Carmichael 3 strong pseudoprimes]]\n\n<br><br>\n", "language": "00-TASK" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef unsigned long long int u64;\n\n#define TRUE 1\n#define FALSE 0\n\nint primality_pretest(u64 k) {\n if (!(k % 3) || !(k % 5) || !(k % 7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23);\n return TRUE;\n}\n\nint probprime(u64 k, mpz_t n) {\n mpz_set_ui(n, k);\n return mpz_probab_prime_p(n, 0);\n}\n\nint is_chernick(int n, u64 m, mpz_t z) {\n u64 t = 9 * m;\n if (primality_pretest(6 * m + 1) == FALSE) return FALSE;\n if (primality_pretest(12 * m + 1) == FALSE) return FALSE;\n for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE;\n if (probprime(6 * m + 1, z) == FALSE) return FALSE;\n if (probprime(12 * m + 1, z) == FALSE) return FALSE;\n for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE;\n return TRUE;\n}\n\nint main(int argc, char const *argv[]) {\n mpz_t z;\n mpz_inits(z, NULL);\n\n for (int n = 3; n <= 10; n ++) {\n u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n if (n > 5) multiplier *= 5;\n\n for (u64 k = 1; ; k++) {\n u64 m = k * multiplier;\n\n if (is_chernick(n, m, z) == TRUE) {\n printf(\"a(%d) has m = %llu\\n\", n, m);\n break;\n }\n }\n }\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <gmp.h>\n#include <iostream>\n\nusing namespace std;\n\ntypedef unsigned long long int u64;\n\nbool primality_pretest(u64 k) { // for k > 23\n\n if (!(k % 3) || !(k % 5) || !(k % 7) || !(k % 11) ||\n !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)\n ) {\n return (k <= 23);\n }\n\n return true;\n}\n\nbool probprime(u64 k, mpz_t n) {\n mpz_set_ui(n, k);\n return mpz_probab_prime_p(n, 0);\n}\n\nbool is_chernick(int n, u64 m, mpz_t z) {\n\n if (!primality_pretest(6 * m + 1)) {\n return false;\n }\n\n if (!primality_pretest(12 * m + 1)) {\n return false;\n }\n\n u64 t = 9 * m;\n\n for (int i = 1; i <= n - 2; i++) {\n if (!primality_pretest((t << i) + 1)) {\n return false;\n }\n }\n\n if (!probprime(6 * m + 1, z)) {\n return false;\n }\n\n if (!probprime(12 * m + 1, z)) {\n return false;\n }\n\n for (int i = 1; i <= n - 2; i++) {\n if (!probprime((t << i) + 1, z)) {\n return false;\n }\n }\n\n return true;\n}\n\nint main() {\n\n mpz_t z;\n mpz_inits(z, NULL);\n\n for (int n = 3; n <= 10; n++) {\n\n // `m` is a multiple of 2^(n-4), for n > 4\n u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n // For n > 5, m is also a multiple of 5\n if (n > 5) {\n multiplier *= 5;\n }\n\n for (u64 k = 1; ; k++) {\n\n u64 m = k * multiplier;\n\n if (is_chernick(n, m, z)) {\n cout << \"a(\" << n << \") has m = \" << m << endl;\n break;\n }\n }\n }\n\n return 0;\n}\n", "language": "C++" }, { "code": "// Generate Chernick's Carmichael numbers. Nigel Galloway: June 1st., 2019\nlet fMk m k=isPrime(6*m+1) && isPrime(12*m+1) && [1..k-2]|>List.forall(fun n->isPrime(9*(pown 2 n)*m+1))\nlet fX k=Seq.initInfinite(fun n->(n+1)*(pown 2 (k-4))) |> Seq.filter(fun n->fMk n k )\nlet cherCar k=let m=Seq.head(fX k) in printfn \"m=%d primes -> %A \" m ([6*m+1;12*m+1]@List.init(k-2)(fun n->9*(pown 2 (n+1))*m+1))\n[4..9] |> Seq.iter cherCar\n", "language": "F-Sharp" }, { "code": "#include \"isprime.bas\"\n\nFunction PrimalityPretest(k As Integer) As Boolean\n Dim As Integer ppp(1 To 8) = {3,5,7,11,13,17,19,23}\n For i As Integer = 1 To Ubound(ppp)\n If k Mod ppp(i) = 0 Then Return (k <= 23)\n Next i\n Return True\nEnd Function\n\nFunction isChernick(n As Integer, m As Integer) As Boolean\n Dim As Integer i, t = 9 * m\n\n If Not PrimalityPretest(6 * m + 1) Then Return False\n If Not PrimalityPretest(12 * m + 1) Then Return False\n\n For i = 1 To n-1\n If Not PrimalityPretest(t * (2 ^ i) + 1) Then Return False\n Next i\n\n If Not isPrime(6 * m + 1) Then Return False\n If Not isPrime(12 * m + 1) Then Return False\n\n For i = 1 To n - 2\n If Not isPrime(t * (2 ^ i) + 1) Then Return False\n Next i\n Return True\nEnd Function\n\nDim As Uinteger multiplier, k, m = 1\nFor n As Integer = 3 To 9\n multiplier = Iif (n > 4, 2 ^ (n-4), 1)\n If n > 5 Then multiplier *= 5\n\n k = 1\n Do\n m = k * multiplier\n If isChernick(n, m) Then\n Print \"a(\" & n & \") has m = \" & m\n Exit Do\n End If\n k += 1\n Loop\nNext n\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nvar (\n zero = new(big.Int)\n prod = new(big.Int)\n fact = new(big.Int)\n)\n\nfunc ccFactors(n, m uint64) (*big.Int, bool) {\n prod.SetUint64(6*m + 1)\n if !prod.ProbablyPrime(0) {\n return zero, false\n }\n fact.SetUint64(12*m + 1)\n if !fact.ProbablyPrime(0) { // 100% accurate up to 2 ^ 64\n return zero, false\n }\n prod.Mul(prod, fact)\n for i := uint64(1); i <= n-2; i++ {\n fact.SetUint64((1<<i)*9*m + 1)\n if !fact.ProbablyPrime(0) {\n return zero, false\n }\n prod.Mul(prod, fact)\n }\n return prod, true\n}\n\nfunc ccNumbers(start, end uint64) {\n for n := start; n <= end; n++ {\n m := uint64(1)\n if n > 4 {\n m = 1 << (n - 4)\n }\n for {\n num, ok := ccFactors(n, m)\n if ok {\n fmt.Printf(\"a(%d) = %d\\n\", n, num)\n break\n }\n if n <= 4 {\n m++\n } else {\n m += 1 << (n - 4)\n }\n }\n }\n}\n\nfunc main() {\n ccNumbers(3, 9)\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"fmt\"\n big \"github.com/ncw/gmp\"\n)\n\nconst (\n min = 3\n max = 10\n)\n\nvar (\n prod = new(big.Int)\n fact = new(big.Int)\n factors = [max]uint64{}\n bigFactors = [max]*big.Int{}\n)\n\nfunc init() {\n for i := 0; i < max; i++ {\n bigFactors[i] = big.NewInt(0)\n }\n}\n\nfunc isPrimePretest(k uint64) bool {\n if k%3 == 0 || k%5 == 0 || k%7 == 0 || k%11 == 0 ||\n k%13 == 0 || k%17 == 0 || k%19 == 0 || k%23 == 0 {\n return k <= 23\n }\n return true\n}\n\nfunc ccFactors(n, m uint64) bool {\n if !isPrimePretest(6*m + 1) {\n return false\n }\n if !isPrimePretest(12*m + 1) {\n return false\n }\n factors[0] = 6*m + 1\n factors[1] = 12*m + 1\n t := 9 * m\n for i := uint64(1); i <= n-2; i++ {\n tt := (t << i) + 1\n if !isPrimePretest(tt) {\n return false\n }\n factors[i+1] = tt\n }\n\n for i := 0; i < int(n); i++ {\n fact.SetUint64(factors[i])\n if !fact.ProbablyPrime(0) {\n return false\n }\n bigFactors[i].Set(fact)\n }\n return true\n}\n\nfunc prodFactors(n uint64) *big.Int {\n prod.Set(bigFactors[0])\n for i := 1; i < int(n); i++ {\n prod.Mul(prod, bigFactors[i])\n }\n return prod\n}\n\nfunc ccNumbers(start, end uint64) {\n for n := start; n <= end; n++ {\n mult := uint64(1)\n if n > 4 {\n mult = 1 << (n - 4)\n }\n if n > 5 {\n mult *= 5\n }\n m := mult\n for {\n if ccFactors(n, m) {\n num := prodFactors(n)\n fmt.Printf(\"a(%d) = %d\\n\", n, num)\n fmt.Printf(\"m(%d) = %d\\n\", n, m)\n fmt.Println(\"Factors:\", factors[:n], \"\\n\")\n break\n }\n m += mult\n }\n }\n}\n\nfunc main() {\n ccNumbers(min, max)\n}\n", "language": "Go" }, { "code": "a=: {{)v\n if.3=y do.1729 return.end.\n m=. z=. 2^y-4\n f=. 6 12,9*2^}.i.y-1\n while.do.\n uf=.1+f*m\n if.*/1 p: uf do. */x:uf return.end.\n m=.m+z\n end.\n}}\n", "language": "J" }, { "code": " a 3\n1729\n a 4\n63973\n a 5\n26641259752490421121\n a 6\n1457836374916028334162241\n a 7\n24541683183872873851606952966798288052977151461406721\n a 8\n53487697914261966820654105730041031613370337776541835775672321\n a 9\n58571442634534443082821160508299574798027946748324125518533225605795841\n", "language": "J" }, { "code": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ChernicksCarmichaelNumbers {\n\n public static void main(String[] args) {\n for ( long n = 3 ; n < 10 ; n++ ) {\n long m = 0;\n boolean foundComposite = true;\n List<Long> factors = null;\n while ( foundComposite ) {\n m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5);\n factors = U(n, m);\n foundComposite = false;\n for ( long factor : factors ) {\n if ( ! isPrime(factor) ) {\n foundComposite = true;\n break;\n }\n }\n }\n System.out.printf(\"U(%d, %d) = %s = %s %n\", n, m, display(factors), multiply(factors));\n }\n }\n\n private static String display(List<Long> factors) {\n return factors.toString().replace(\"[\", \"\").replace(\"]\", \"\").replaceAll(\", \", \" * \");\n }\n\n private static BigInteger multiply(List<Long> factors) {\n BigInteger result = BigInteger.ONE;\n for ( long factor : factors ) {\n result = result.multiply(BigInteger.valueOf(factor));\n }\n return result;\n }\n\n private static List<Long> U(long n, long m) {\n List<Long> factors = new ArrayList<>();\n factors.add(6*m + 1);\n factors.add(12*m + 1);\n for ( int i = 1 ; i <= n-2 ; i++ ) {\n factors.add(((long)Math.pow(2, i)) * 9 * m + 1);\n }\n return factors;\n }\n\n private static final int MAX = 100_000;\n private static final boolean[] primes = new boolean[MAX];\n private static boolean SIEVE_COMPLETE = false;\n\n private static final boolean isPrimeTrivial(long test) {\n if ( ! SIEVE_COMPLETE ) {\n sieve();\n SIEVE_COMPLETE = true;\n }\n return primes[(int) test];\n }\n\n private static final void sieve() {\n // primes\n for ( int i = 2 ; i < MAX ; i++ ) {\n primes[i] = true;\n }\n for ( int i = 2 ; i < MAX ; i++ ) {\n if ( primes[i] ) {\n for ( int j = 2*i ; j < MAX ; j += i ) {\n primes[j] = false;\n }\n }\n }\n }\n\n // See http://primes.utm.edu/glossary/page.php?sort=StrongPRP\n public static final boolean isPrime(long testValue) {\n if ( testValue == 2 ) return true;\n if ( testValue % 2 == 0 ) return false;\n if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n long d = testValue-1;\n int s = 0;\n while ( d % 2 == 0 ) {\n s += 1;\n d /= 2;\n }\n if ( testValue < 1373565L ) {\n if ( ! aSrp(2, s, d, testValue) ) {\n return false;\n }\n if ( ! aSrp(3, s, d, testValue) ) {\n return false;\n }\n return true;\n }\n if ( testValue < 4759123141L ) {\n if ( ! aSrp(2, s, d, testValue) ) {\n return false;\n }\n if ( ! aSrp(7, s, d, testValue) ) {\n return false;\n }\n if ( ! aSrp(61, s, d, testValue) ) {\n return false;\n }\n return true;\n }\n if ( testValue < 10000000000000000L ) {\n if ( ! aSrp(3, s, d, testValue) ) {\n return false;\n }\n if ( ! aSrp(24251, s, d, testValue) ) {\n return false;\n }\n return true;\n }\n // Try 5 \"random\" primes\n if ( ! aSrp(37, s, d, testValue) ) {\n return false;\n }\n if ( ! aSrp(47, s, d, testValue) ) {\n return false;\n }\n if ( ! aSrp(61, s, d, testValue) ) {\n return false;\n }\n if ( ! aSrp(73, s, d, testValue) ) {\n return false;\n }\n if ( ! aSrp(83, s, d, testValue) ) {\n return false;\n }\n //throw new RuntimeException(\"ERROR isPrime: Value too large = \"+testValue);\n return true;\n }\n\n private static final boolean aSrp(int a, int s, long d, long n) {\n long modPow = modPow(a, d, n);\n //System.out.println(\"a = \"+a+\", s = \"+s+\", d = \"+d+\", n = \"+n+\", modpow = \"+modPow);\n if ( modPow == 1 ) {\n return true;\n }\n int twoExpR = 1;\n for ( int r = 0 ; r < s ; r++ ) {\n if ( modPow(modPow, twoExpR, n) == n-1 ) {\n return true;\n }\n twoExpR *= 2;\n }\n return false;\n }\n\n private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n\n public static final long modPow(long base, long exponent, long modulus) {\n long result = 1;\n while ( exponent > 0 ) {\n if ( exponent % 2 == 1 ) {\n if ( result > SQRT || base > SQRT ) {\n result = multiply(result, base, modulus);\n }\n else {\n result = (result * base) % modulus;\n }\n }\n exponent >>= 1;\n if ( base > SQRT ) {\n base = multiply(base, base, modulus);\n }\n else {\n base = (base * base) % modulus;\n }\n }\n return result;\n }\n\n\n // Result is a*b % mod, without overflow.\n public static final long multiply(long a, long b, long modulus) {\n long x = 0;\n long y = a % modulus;\n long t;\n while ( b > 0 ) {\n if ( b % 2 == 1 ) {\n t = x + y;\n x = (t > modulus ? t-modulus : t);\n }\n t = y << 1;\n y = (t > modulus ? t-modulus : t);\n b >>= 1;\n }\n return x % modulus;\n }\n\n}\n", "language": "Java" }, { "code": "using Primes\n\nfunction trial_pretest(k::UInt64)\n\n if ((k % 3)==0 || (k % 5)==0 || (k % 7)==0 || (k % 11)==0 ||\n (k % 13)==0 || (k % 17)==0 || (k % 19)==0 || (k % 23)==0)\n return (k <= 23)\n end\n\n return true\nend\n\nfunction gcd_pretest(k::UInt64)\n\n if (k <= 107)\n return true\n end\n\n gcd(29*31*37*41*43*47*53*59*61*67, k) == 1 &&\n gcd(71*73*79*83*89*97*101*103*107, k) == 1\nend\n\nfunction is_chernick(n::Int64, m::UInt64)\n\n t = 9*m\n\n if (!trial_pretest(6*m + 1))\n return false\n end\n\n if (!trial_pretest(12*m + 1))\n return false\n end\n\n for i in 1:n-2\n if (!trial_pretest((t << i) + 1))\n return false\n end\n end\n\n if (!gcd_pretest(6*m + 1))\n return false\n end\n\n if (!gcd_pretest(12*m + 1))\n return false\n end\n\n for i in 1:n-2\n if (!gcd_pretest((t << i) + 1))\n return false\n end\n end\n\n if (!isprime(6*m + 1))\n return false\n end\n\n if (!isprime(12*m + 1))\n return false\n end\n\n for i in 1:n-2\n if (!isprime((t << i) + 1))\n return false\n end\n end\n\n return true\nend\n\nfunction chernick_carmichael(n::Int64, m::UInt64)\n prod = big(1)\n\n prod *= 6*m + 1\n prod *= 12*m + 1\n\n for i in 1:n-2\n prod *= ((big(9)*m)<<i) + 1\n end\n\n prod\nend\n\nfunction cc_numbers(from, to)\n\n for n in from:to\n\n multiplier = 1\n\n if (n > 4) multiplier = 1 << (n-4) end\n if (n > 5) multiplier *= 5 end\n\n m = UInt64(multiplier)\n\n while true\n\n if (is_chernick(n, m))\n println(\"a(\", n, \") = \", chernick_carmichael(n, m))\n break\n end\n\n m += multiplier\n end\n end\nend\n\ncc_numbers(3, 10)\n", "language": "Julia" }, { "code": "ClearAll[PrimeFactorCounts, U]\nPrimeFactorCounts[n_Integer] := Total[FactorInteger[n][[All, 2]]]\nU[n_, m_] := (6 m + 1) (12 m + 1) Product[2^i 9 m + 1, {i, 1, n - 2}]\nFindFirstChernickCarmichaelNumber[n_Integer?Positive] :=\n Module[{step, i, m, formula, value},\n step = Ceiling[2^(n - 4)];\n If[n > 5, step *= 5];\n i = step;\n formula = U[n, m];\n PrintTemporary[Dynamic[i]];\n While[True,\n value = formula /. m -> i;\n If[PrimeFactorCounts[value] == n,\n Break[];\n ];\n i += step\n ];\n {i, value}\n ]\nFindFirstChernickCarmichaelNumber[3]\nFindFirstChernickCarmichaelNumber[4]\nFindFirstChernickCarmichaelNumber[5]\nFindFirstChernickCarmichaelNumber[6]\nFindFirstChernickCarmichaelNumber[7]\nFindFirstChernickCarmichaelNumber[8]\nFindFirstChernickCarmichaelNumber[9]\n", "language": "Mathematica" }, { "code": "import strutils, sequtils\nimport bignum\n\nconst\n Max = 10\n Factors: array[3..Max, int] = [1, 1, 2, 4, 8, 16, 32, 64] # 1 for n=3 then 2^(n-4).\n FirstPrimes = [3, 5, 7, 11, 13, 17, 19, 23]\n\n#---------------------------------------------------------------------------------------------------\n\niterator factors(n, m: Natural): Natural =\n ## Yield the factors of U(n, m).\n\n yield 6 * m + 1\n yield 12 * m + 1\n var k = 2\n for _ in 1..(n - 2):\n yield 9 * k * m + 1\n inc k, k\n\n#---------------------------------------------------------------------------------------------------\n\nproc mayBePrime(n: int): bool =\n ## First primality test.\n\n if n < 23: return true\n\n for p in FirstPrimes:\n if n mod p == 0:\n return false\n\n result = true\n\n#---------------------------------------------------------------------------------------------------\n\nproc isChernick(n, m: Natural): bool =\n ## Check if U(N, m) if a Chernick-Carmichael number.\n\n # Use the first and quick test.\n for factor in factors(n, m):\n if not factor.mayBePrime():\n return false\n\n # Use the slow probability test (need to use a big int).\n for factor in factors(n, m):\n if probablyPrime(newInt(factor), 25) == 0:\n return false\n\n result = true\n\n#---------------------------------------------------------------------------------------------------\n\nproc a(n: Natural): tuple[m: Natural, factors: seq[Natural]] =\n ## For a given \"n\", find the smallest Charnick-Carmichael number.\n\n var m: Natural = 0\n var incr = (if n >= 5: 5 else: 1) * Factors[n] # For n >= 5, a(n) is a multiple of 5.\n\n while true:\n inc m, incr\n if isChernick(n, m):\n return (m, toSeq(factors(n, m)))\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nimport strformat\n\nfor n in 3..Max:\n let (m, factors) = a(n)\n\n stdout.write fmt\"a({n}) = U({n}, {m}) = \"\n var s = \"\"\n for factor in factors:\n s.addSep(\" × \")\n s.add($factor)\n stdout.write s, '\\n'\n", "language": "Nim" }, { "code": "cherCar(n)={\n my(C=vector(n));C[1]=6; C[2]=12; for(g=3,n,C[g]=2^(g-2)*9);\n my(i=1); my(N(g)=while(i<=n&ispseudoprime(g*C[i]+1),i=i+1); return(i>n));\n i=1; my(G(g)=while(i<=n&isprime(g*C[i]+1),i=i+1); return(i>n));\n i=1; if(n>4,i=2^(n-4)); if(n>5,i=i*5); my(m=i); while(!(N(m)&G(m)),m=m+i);\n printf(\"cherCar(%d): m = %d\\n\",n,m)}\nfor(x=3,9,cherCar(x))\n", "language": "PARI-GP" }, { "code": "use 5.020;\nuse warnings;\nuse ntheory qw/:all/;\nuse experimental qw/signatures/;\n\nsub chernick_carmichael_factors ($n, $m) {\n (6*$m + 1, 12*$m + 1, (map { (1 << $_) * 9*$m + 1 } 1 .. $n-2));\n}\n\nsub chernick_carmichael_number ($n, $callback) {\n\n my $multiplier = ($n > 4) ? (1 << ($n-4)) : 1;\n\n for (my $m = 1 ; ; ++$m) {\n my @f = chernick_carmichael_factors($n, $m * $multiplier);\n next if not vecall { is_prime($_) } @f;\n $callback->(@f);\n last;\n }\n}\n\nforeach my $n (3..9) {\n chernick_carmichael_number($n, sub (@f) { say \"a($n) = \", vecprod(@f) });\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">chernick_carmichael_factors</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">mpfr</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_init</span><span style=\"color: #0000FF;\">()</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">m_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpz_set_d</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">mpz_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">is_chernick_carmichael</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">==</span><span style=\"color: #000000;\">2</span> <span style=\"color: #0000FF;\">?</span> <span style=\"color: #000000;\">m_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">m_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">m_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">and</span>\n <span style=\"color: #000000;\">is_chernick_carmichael</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">chernick_carmichael_number</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">4</span> <span style=\"color: #0000FF;\">?</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">mm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">m</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">is_chernick_carmichael</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">mm</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #000000;\">mm</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">m</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">chernick_carmichael_factors</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">mm</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">mm</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">9</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">chernick_carmichael_number</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpz_set_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">mpz_mul_d</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"U(%d,%d): %s = %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">mpz_get_str</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" * \"</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">mpfr</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">ppp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">13</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">19</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">23</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">primality_pretest</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ppp</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ppp</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">23</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">probprime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpz_set_d</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">mpz_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">is_chernick</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">9</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">;</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">primality_pretest</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">6</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">==</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">primality_pretest</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">12</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">==</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">primality_pretest</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">==</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">probprime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">6</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">==</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">probprime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">12</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">==</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">probprime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">==</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">z</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_init</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">multiplier</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">4</span> <span style=\"color: #0000FF;\">?</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">5</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">multiplier</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #000000;\">5</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">12564168</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span> <span style=\"color: #000080;font-style:italic;\">-- cheat!</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">multiplier</span><span style=\"color: #0000FF;\">;</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">is_chernick</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"a(%d) has m = %d\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "?- use_module(library(primality)).\n\nu(3, M, A * B * C) :-\n A is 6*M + 1, B is 12*M + 1, C is 18*M + 1, !.\nu(N, M, U0 * D) :-\n succ(Pn, N), u(Pn, M, U0),\n D is 9*(1 << (N - 2))*M + 1.\n\nprime_factorization(A*B) :- prime(B), prime_factorization(A), !.\nprime_factorization(A) :- prime(A).\n\nstep(N, 1) :- N < 5, !.\nstep(5, 2) :- !.\nstep(N, K) :- K is 5*(1 << (N - 4)).\n\na(N, Factors) :- % due to backtracking nature of Prolog, a(n) will return all chernick-carmichael numbers.\n N > 2, !,\n step(N, I),\n between(1, infinite, J), M is I * J,\n u(N, M, Factors),\n prime_factorization(Factors).\n\nmain :-\n forall(\n (between(3, 9, K), once(a(K, Factorization)), N is Factorization),\n format(\"~w: ~w = ~w~n\", [K, Factorization, N])),\n halt.\n\n?- main.\n", "language": "Prolog" }, { "code": "prime(N) :-\n integer(N),\n N > 1,\n divcheck(\n N,\n [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,\n 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79,\n 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137,\n 139, 149],\n Result),\n ((Result = prime, !); miller_rabin_primality_test(N)).\n\ndivcheck(_, [], unknown) :- !.\ndivcheck(N, [P|_], prime) :- P*P > N, !.\ndivcheck(N, [P|Ps], State) :- N mod P =\\= 0, divcheck(N, Ps, State).\n\nmiller_rabin_primality_test(N) :-\n bases(Bases, N),\n forall(member(A, Bases), strong_fermat_pseudoprime(N, A)).\n\nmiller_rabin_precision(16).\n\nbases([31, 73], N) :- N < 9_080_191, !.\nbases([2, 7, 61], N) :- N < 4_759_123_141, !.\nbases([2, 325, 9_375, 28_178, 450_775, 9_780_504, 1_795_265_022], N) :-\n N < 18_446_744_073_709_551_616, !. % 2^64\nbases(Bases, N) :-\n miller_rabin_precision(T), RndLimit is N - 2,\n length(Bases, T), maplist(random_between(2, RndLimit), Bases).\n\nstrong_fermat_pseudoprime(N, A) :- % miller-rabin strong pseudoprime test with base A.\n succ(Pn, N), factor_2s(Pn, S, D),\n X is powm(A, D, N),\n ((X =:= 1, !); \\+ composite_witness(N, S, X)).\n\ncomposite_witness(_, 0, _) :- !.\ncomposite_witness(N, K, X) :-\n X =\\= N-1,\n succ(Pk, K), X2 is (X*X) mod N, composite_witness(N, Pk, X2).\n\nfactor_2s(N, S, D) :- factor_2s(0, N, S, D).\nfactor_2s(S, D, S, D) :- D /\\ 1 =\\= 0, !.\nfactor_2s(S0, D0, S, D) :-\n succ(S0, S1), D1 is D0 >> 1,\n factor_2s(S1, D1, S, D).\n", "language": "Prolog" }, { "code": "\"\"\"\n\nPython implementation of\nhttp://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers\n\n\"\"\"\n\n# use sympy for prime test\n\nfrom sympy import isprime\n\n# based on C version\n\ndef primality_pretest(k):\n if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):\n return (k <= 23)\n\n return True\n\ndef is_chernick(n, m):\n\n t = 9 * m\n\n if not primality_pretest(6 * m + 1):\n return False\n\n if not primality_pretest(12 * m + 1):\n return False\n\n for i in range(1,n-1):\n if not primality_pretest((t << i) + 1):\n return False\n\n if not isprime(6 * m + 1):\n return False\n\n if not isprime(12 * m + 1):\n return False\n\n for i in range(1,n - 1):\n if not isprime((t << i) + 1):\n return False\n\n return True\n\nfor n in range(3,10):\n\n if n > 4:\n multiplier = 1 << (n - 4)\n else:\n multiplier = 1\n\n if n > 5:\n multiplier *= 5\n\n\n k = 1\n\n while True:\n m = k * multiplier\n\n if is_chernick(n, m):\n print(\"a(\"+str(n)+\") has m = \"+str(m))\n break\n\n k += 1\n", "language": "Python" }, { "code": "use Inline::Perl5;\nuse ntheory:from<Perl5> <:all>;\n\nsub chernick-factors ($n, $m) {\n 6×$m + 1, 12×$m + 1, |((1 .. $n-2).map: { (1 +< $_) × 9×$m + 1 } )\n}\n\nsub chernick-carmichael-number ($n) {\n\n my $multiplier = 1 +< (($n-4) max 0);\n my $iterator = $n < 5 ?? (1 .. *) !! (1 .. *).map: * × 5;\n\n $multiplier × $iterator.first: -> $m {\n [&&] chernick-factors($n, $m × $multiplier).map: { is_prime($_) }\n }\n\n}\n\nfor 3 .. 9 -> $n {\n my $m = chernick-carmichael-number($n);\n my @f = chernick-factors($n, $m);\n say \"U($n, $m): {[×] @f} = {@f.join(' ⨉ ')}\";\n}\n", "language": "Raku" }, { "code": "func chernick_carmichael_factors (n, m) {\n [6*m + 1, 12*m + 1, {|i| 2**i * 9*m + 1 }.map(1 .. n-2)...]\n}\n\nfunc is_chernick_carmichael (n, m) {\n (n == 2) ? (is_prime(6*m + 1) && is_prime(12*m + 1))\n : (is_prime(2**(n-2) * 9*m + 1) && __FUNC__(n-1, m))\n}\n\nfunc chernick_carmichael_number(n, callback) {\n var multiplier = (n>4 ? 2**(n-4) : 1)\n var m = (1..Inf -> first {|m| is_chernick_carmichael(n, m * multiplier) })\n var f = chernick_carmichael_factors(n, m * multiplier)\n callback(f...)\n}\n\nfor n in (3..9) {\n chernick_carmichael_number(n, {|*f| say \"a(#{n}) = #{f.join(' * ')}\" })\n}\n", "language": "Sidef" }, { "code": "import \"./big\" for BigInt, BigInts\nimport \"./fmt\" for Fmt\n\nvar min = 3\nvar max = 9\nvar prod = BigInt.zero\nvar fact = BigInt.zero\nvar factors = List.filled(max, 0)\nvar bigFactors = List.filled(max, null)\n\nvar init = Fn.new {\n for (i in 0...max) bigFactors[i] = BigInt.zero\n}\n\nvar isPrimePretest = Fn.new { |k|\n if (k%3 == 0 || k%5 == 0 || k%7 == 0 || k%11 == 0 ||\n (k%13 == 0) || k%17 == 0 || k%19 == 0 || k%23 == 0) return k <= 23\n return true\n}\n\nvar ccFactors = Fn.new { |n, m|\n if (!isPrimePretest.call(6*m + 1)) return false\n if (!isPrimePretest.call(12*m + 1)) return false\n factors[0] = 6*m + 1\n factors[1] = 12*m + 1\n var t = 9 * m\n var i = 1\n while (i <= n-2) {\n var tt = (t << i) + 1\n if (!isPrimePretest.call(tt)) return false\n factors[i+1] = tt\n i = i + 1\n }\n for (i in 0...n) {\n fact = BigInt.new(factors[i])\n if (!fact.isProbablePrime(1)) return false\n bigFactors[i] = fact\n }\n return true\n}\n\nvar ccNumbers = Fn.new { |start, end|\n for (n in start..end) {\n var mult = 1\n if (n > 4) mult = 1 << (n - 4)\n if (n > 5) mult = mult * 5\n var m = mult\n while (true) {\n if (ccFactors.call(n, m)) {\n var num = BigInts.prod(bigFactors.take(n))\n Fmt.print(\"a($d) = $i\", n, num)\n Fmt.print(\"m($d) = $d\", n, m)\n Fmt.print(\"Factors: $n\\n\", factors[0...n])\n break\n }\n m = m + mult\n }\n }\n}\n\ninit.call()\nccNumbers.call(min, max)\n", "language": "Wren" }, { "code": "var [const] BI=Import(\"zklBigNum\"); // libGMP\n\nfcn ccFactors(n,m){\t// not re-entrant\n prod:=BI(6*m + 1);\n if(not prod.probablyPrime()) return(False);\n fact:=BI(12*m + 1);\n if(not fact.probablyPrime()) return(False);\n prod.mul(fact);\n foreach i in ([1..n-2]){\n fact.set((2).pow(i) *9*m + 1);\n if(not fact.probablyPrime()) return(False);\n prod.mul(fact);\n }\n prod\n}\n\nfcn ccNumbers(start,end){\n foreach n in ([start..end]){\n a,m := ( if(n<=4) 1 else (2).pow(n - 4) ), a;\n while(1){\n\t if(num := ccFactors(n,m)){\n\t println(\"a(%d) = %,d\".fmt(n,num));\n\t break;\n\t }\n\t m+=a;\n }\n }\n}\n", "language": "Zkl" }, { "code": "ccNumbers(3,9);\n", "language": "Zkl" } ]
Chernicks-Carmichael-numbers
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Cheryl's_birthday\n", "language": "00-META" }, { "code": "Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.\n\nCheryl gave them a list of ten possible dates:\n May 15, May 16, May 19\n June 17, June 18\n July 14, July 16\n August 14, August 15, August 17\n\nCheryl then tells Albert the &nbsp; ''month'' &nbsp; of birth, &nbsp; and Bernard the &nbsp; ''day'' &nbsp; (of the month) &nbsp; of birth.\n 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\n 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\n 3) Albert: Then I also know when Cheryl's birthday is.\n\n\n;Task\nWrite a computer program to deduce, by successive elimination, Cheryl's birthday.\n\n\n;Related task:\n* [[Sum and Product Puzzle]]\n\n\n;References\n* [https://en.wikipedia.org/wiki/Cheryl%27s_Birthday Wikipedia article] of the same name.\n* [https://en.wikipedia.org/wiki/Tuple_relational_calculus, Tuple Relational Calculus]\n<br><br>\n", "language": "00-TASK" }, { "code": "T Date\n String month\n Int day\n F (month, day)\n .month = month\n .day = day\n\nV dates = [Date(‘May’, 15), Date(‘May’, 16), Date(‘May’, 19), Date(‘June’, 17), Date(‘June’, 18),\n Date(‘July’, 14), Date(‘July’, 16), Date(‘August’, 14), Date(‘August’, 15), Date(‘August’, 17)]\n\nDefaultDict[Int, Set[String]] monthTable\nL(date) dates\n monthTable[date.day].add(date.month)\n\nDefaultDict[String, Set[Int]] dayTable\nL(date) dates\n dayTable[date.month].add(date.day)\n\nSet[String] possibleMonths\nSet[Int] possibleDays\n\nL(month, days) dayTable\n I days.len > 1\n possibleMonths.add(month)\n\nL(month, days) dayTable\n L(day) days\n I monthTable[day].len == 1\n possibleMonths.remove(month)\nprint(‘After first Albert's sentence, possible months are ’Array(possibleMonths).join(‘, ’)‘.’)\n\nL(day, months) monthTable\n I months.len > 1\n possibleDays.add(day)\n\nSet[Int] impossibleDays\nL(day) possibleDays\n I monthTable[day].intersection(possibleMonths).len > 1\n impossibleDays.add(day)\nL(day) impossibleDays\n possibleDays.remove(day)\nprint(‘After Bernard's sentence, possible days are ’Array(possibleDays).join(‘, ’)‘.’)\n\nSet[String] impossibleMonths\nL(month) possibleMonths\n I dayTable[month].intersection(possibleDays).len > 1\n impossibleMonths.add(month)\nL(month) impossibleMonths\n possibleMonths.remove(month)\n\nassert(possibleMonths.len == 1)\nV month = possibleMonths.pop()\nprint(‘After second Albert's sentence, remaining month is ’month‘...’)\n\npossibleDays = possibleDays.intersection(dayTable[month])\nassert(possibleDays.len == 1)\nV day = possibleDays.pop()\nprint(‘and thus remaining day is ’day‘.’)\n\nprint()\nprint(‘So birthday date is ’month‘ ’day‘.’)\n", "language": "11l" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Main is\n type Months is\n (January, February, March, April, May, June, July, August, September,\n November, December);\n type day_num is range 1 .. 31;\n type birthdate is record\n Month : Months;\n Day : day_num;\n Active : Boolean;\n end record;\n\n type birthday_list is array (Positive range <>) of birthdate;\n\n Possible_birthdates : birthday_list :=\n ((May, 15, True), (May, 16, True), (May, 19, True), (June, 17, True),\n (June, 18, True), (July, 14, True), (July, 16, True), (August, 14, True),\n (August, 15, True), (August, 17, True));\n\n procedure print_answer is\n begin\n for the_day of Possible_birthdates loop\n if the_day.Active then\n Put_Line (the_day.Month'Image & \",\" & the_day.Day'Image);\n end if;\n end loop;\n end print_answer;\n\n procedure print_remaining is\n count : Natural := 0;\n begin\n for date of Possible_birthdates loop\n if date.Active then\n count := count + 1;\n end if;\n end loop;\n Put_Line (count'Image & \" remaining.\");\n end print_remaining;\n\n -- the month cannot have a unique day\n procedure first_pass is\n count : Natural;\n begin\n for first_day of Possible_birthdates loop\n count := 0;\n for next_day of Possible_birthdates loop\n if first_day.Day = next_day.Day then\n count := count + 1;\n end if;\n end loop;\n\n if count = 1 then\n for the_day of Possible_birthdates loop\n if the_day.Active and then first_day.Month = the_day.Month then\n the_day.Active := False;\n end if;\n end loop;\n end if;\n end loop;\n end first_pass;\n\n -- the day must now be unique\n procedure second_pass is\n count : Natural;\n begin\n for first_day of Possible_birthdates loop\n if first_day.Active then\n count := 0;\n for next_day of Possible_birthdates loop\n if next_day.Active then\n if next_day.Day = first_day.Day then\n count := count + 1;\n end if;\n end if;\n end loop;\n\n if count > 1 then\n for next_day of Possible_birthdates loop\n if next_day.Active and then next_day.Day = first_day.Day then\n next_day.Active := False;\n end if;\n end loop;\n end if;\n end if;\n end loop;\n end second_pass;\n\n -- the month must now be unique\n procedure third_pass is\n count : Natural;\n begin\n for first_day of Possible_birthdates loop\n if first_day.Active then\n count := 0;\n for next_day of Possible_birthdates loop\n if next_day.Active and then next_day.Month = first_day.Month\n then\n count := count + 1;\n end if;\n end loop;\n if count > 1 then\n for next_day of Possible_birthdates loop\n if next_day.Active and then next_day.Month = first_day.Month\n then\n next_day.Active := False;\n end if;\n end loop;\n end if;\n end if;\n end loop;\n end third_pass;\n\nbegin\n print_remaining;\n first_pass;\n\n print_remaining;\n second_pass;\n\n print_remaining;\n third_pass;\n\n print_answer;\nend Main;\n", "language": "11l" }, { "code": "BEGIN # Cheryl's birthday puzzle #\n\n [ 1 : 4, 1 : 6 ]INT dates # non-zero indicates a possible date #\n := ( ( 0, 15, 16, 0, 0, 19 ) # may #\n , ( 0, 0, 0, 17, 18, 0 ) # june #\n , ( 14, 0, 16, 0, 0, 0 ) # july #\n , ( 14, 15, 0, 17, 0, 0 ) # august #\n );\n []STRING month name = ( \"May\", \"June\", \"July\", \"August\" );\n print( ( \"Cheryl tells Albert the month and Bernard the day\", newline ) );\n print( ( \"Albert doesn't know the date and knows Bernard doesn't either\", newline ) );\n FOR d TO 2 UPB dates DO # elimiate the months with unique days #\n INT day count := 0;\n INT day := 0;\n INT month := 0;\n FOR m TO 1 UPB dates DO\n IF dates[ m, d ] /= 0 THEN\n day count +:= 1;\n day := dates[ m, d ];\n month := m\n FI\n OD;\n IF day count = 1 THEN\n print( ( \" Eliminating \", month name[ month ], \", \", whole( day, 0 ), \"th is unique\", newline ) );\n FOR p TO 2 UPB dates DO dates[ month, p ] := 0 OD\n FI\n OD;\n print( ( \"Bernard now knows the date\", newline ) );\n FOR d TO 2 UPB dates DO # eliminate the days that aren't unique #\n INT day count := 0;\n INT day := 0;\n INT month := 0;\n FOR m TO 1 UPB dates DO\n IF dates[ m, d ] /= 0 THEN\n day count +:= 1;\n day := dates[ m, d ];\n month := m\n FI\n OD;\n IF day count > 1 THEN\n print( ( \" Eliminating \", whole( day, 0 ), \"th, it is non-unique\", newline ) );\n FOR p TO 1 UPB dates DO dates[ p, d ] := 0 OD\n FI\n OD;\n print( ( \"Albert now knows the date\", newline ) );\n FOR m TO 1 UPB dates DO # eliminate months with non-unique days #\n INT day count := 0;\n INT day := 0;\n INT month := 0;\n FOR d TO 2 UPB dates DO\n IF dates[ m, d ] /= 0 THEN\n day count +:= 1;\n day := dates[ m, d ];\n month := m\n FI\n OD;\n IF day count > 1 THEN\n print( ( \" Eliminating \", month name[ m ], \", it has multiple days\", newline ) );\n FOR p TO 2 UPB dates DO dates[ m, p ] := 0 OD\n FI\n OD;\n print( ( \"Cheryl's birthday: \" ) ); # show the solution(s) #\n FOR m TO 1 UPB dates DO\n FOR d TO 2 UPB dates DO\n IF dates[ m, d ] /= 0 THEN\n print( ( \" \", month name[ m ], \" \", whole( dates[ m, d ], 0 ), \"th\" ) )\n FI\n OD\n OD;\n print( ( newline ) )\nEND\n", "language": "ALGOL-68" }, { "code": "use AppleScript version \"2.4\"\nuse framework \"Foundation\"\nuse scripting additions\n\nproperty M : 1 -- Month\nproperty D : 2 -- Day\n\non run\n -- The MONTH with only one remaining day\n -- among the DAYs with unique months,\n -- EXCLUDING months with unique days,\n -- in Cheryl's list:\n\n showList(uniquePairing(M, ¬\n uniquePairing(D, ¬\n monthsWithUniqueDays(false, ¬\n map(composeList({tupleFromList, |words|, toLower}), ¬\n splitOn(\", \", ¬\n \"May 15, May 16, May 19, June 17, June 18, \" & ¬\n \"July 14, July 16, Aug 14, Aug 15, Aug 17\"))))))\n\n --> \"[('july', '16')]\"\nend run\n\n\n-- QUERY FUNCTIONS ----------------------------------------\n\n-- monthsWithUniqueDays :: Bool -> [(Month, Day)] -> [(Month, Day)]\non monthsWithUniqueDays(blnInclude, xs)\n set _months to map(my fst, uniquePairing(D, xs))\n script uniqueDay\n on |λ|(md)\n set bln to elem(fst(md), _months)\n if blnInclude then\n bln\n else\n not bln\n end if\n end |λ|\n end script\n filter(uniqueDay, xs)\nend monthsWithUniqueDays\n\n\n-- uniquePairing :: DatePart -> [(M, D)] -> [(M, D)]\non uniquePairing(dp, xs)\n script go\n property f : my mReturn(item dp of {my fst, my snd})\n on |λ|(md)\n\n set dct to f's |λ|(md)\n script unique\n on |λ|(k)\n set mb to lookupDict(k, dct)\n if Nothing of mb then\n false\n else\n 1 = length of (Just of mb)\n end if\n end |λ|\n end script\n set uniques to filter(unique, keys(dct))\n\n script found\n on |λ|(tpl)\n elem(f's |λ|(tpl), uniques)\n end |λ|\n end script\n filter(found, xs)\n end |λ|\n end script\n bindPairs(xs, go)\nend uniquePairing\n\n\n-- bindPairs :: [(M, D)] -> ((Dict Text [Text], Dict Text [Text])\n-- -> [(M, D)]) -> [(M, D)]\non bindPairs(xs, f)\n tell mReturn(f)\n |λ|(Tuple(dictFromPairs(xs), ¬\n dictFromPairs(map(my swap, xs))))\n end tell\nend bindPairs\n\n-- dictFromPairs :: [(M, D)] -> Dict Text [Text]\non dictFromPairs(mds)\n set gps to groupBy(|on|(my eq, my fst), ¬\n sortBy(comparing(my fst), mds))\n script kv\n on |λ|(gp)\n Tuple(fst(item 1 of gp), map(my snd, gp))\n end |λ|\n end script\n mapFromList(map(kv, gps))\nend dictFromPairs\n\n\n-- LIBRARY GENERICS ---------------------------------------\n\n-- comparing :: (a -> b) -> (a -> a -> Ordering)\non comparing(f)\n script\n on |λ|(a, b)\n tell mReturn(f)\n set fa to |λ|(a)\n set fb to |λ|(b)\n if fa < fb then\n -1\n else if fa > fb then\n 1\n else\n 0\n end if\n end tell\n end |λ|\n end script\nend comparing\n\n-- composeList :: [(a -> a)] -> (a -> a)\non composeList(fs)\n script\n on |λ|(x)\n script\n on |λ|(f, a)\n mReturn(f)'s |λ|(a)\n end |λ|\n end script\n\n foldr(result, x, fs)\n end |λ|\n end script\nend composeList\n\n-- drop :: Int -> [a] -> [a]\n-- drop :: Int -> String -> String\non drop(n, xs)\n set c to class of xs\n if c is not script then\n if c is not string then\n if n < length of xs then\n items (1 + n) thru -1 of xs\n else\n {}\n end if\n else\n if n < length of xs then\n text (1 + n) thru -1 of xs\n else\n \"\"\n end if\n end if\n else\n take(n, xs) -- consumed\n return xs\n end if\nend drop\n\n-- dropAround :: (a -> Bool) -> [a] -> [a]\n-- dropAround :: (Char -> Bool) -> String -> String\non dropAround(p, xs)\n dropWhile(p, dropWhileEnd(p, xs))\nend dropAround\n\n-- dropWhile :: (a -> Bool) -> [a] -> [a]\n-- dropWhile :: (Char -> Bool) -> String -> String\non dropWhile(p, xs)\n set lng to length of xs\n set i to 1\n tell mReturn(p)\n repeat while i ≤ lng and |λ|(item i of xs)\n set i to i + 1\n end repeat\n end tell\n drop(i - 1, xs)\nend dropWhile\n\n-- dropWhileEnd :: (a -> Bool) -> [a] -> [a]\n-- dropWhileEnd :: (Char -> Bool) -> String -> String\non dropWhileEnd(p, xs)\n set i to length of xs\n tell mReturn(p)\n repeat while i > 0 and |λ|(item i of xs)\n set i to i - 1\n end repeat\n end tell\n take(i, xs)\nend dropWhileEnd\n\n-- elem :: Eq a => a -> [a] -> Bool\non elem(x, xs)\n considering case\n xs contains x\n end considering\nend elem\n\n-- enumFromToInt :: Int -> Int -> [Int]\non enumFromToInt(M, n)\n if M ≤ n then\n set lst to {}\n repeat with i from M to n\n set end of lst to i\n end repeat\n return lst\n else\n return {}\n end if\nend enumFromToInt\n\n-- eq (==) :: Eq a => a -> a -> Bool\non eq(a, b)\n a = b\nend eq\n\n-- filter :: (a -> Bool) -> [a] -> [a]\non filter(f, xs)\n tell mReturn(f)\n set lst to {}\n set lng to length of xs\n repeat with i from 1 to lng\n set v to item i of xs\n if |λ|(v, i, xs) then set end of lst to v\n end repeat\n return lst\n end tell\nend filter\n\n-- foldl :: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n-- foldr :: (a -> b -> b) -> b -> [a] -> b\non foldr(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from lng to 1 by -1\n set v to |λ|(item i of xs, v, i, xs)\n end repeat\n return v\n end tell\nend foldr\n\n-- fst :: (a, b) -> a\non fst(tpl)\n if class of tpl is record then\n |1| of tpl\n else\n item 1 of tpl\n end if\nend fst\n\n-- Typical usage: groupBy(on(eq, f), xs)\n-- groupBy :: (a -> a -> Bool) -> [a] -> [[a]]\non groupBy(f, xs)\n set mf to mReturn(f)\n\n script enGroup\n on |λ|(a, x)\n if length of (active of a) > 0 then\n set h to item 1 of active of a\n else\n set h to missing value\n end if\n\n if h is not missing value and mf's |λ|(h, x) then\n {active:(active of a) & {x}, sofar:sofar of a}\n else\n {active:{x}, sofar:(sofar of a) & {active of a}}\n end if\n end |λ|\n end script\n\n if length of xs > 0 then\n set dct to foldl(enGroup, {active:{item 1 of xs}, sofar:{}}, rest of xs)\n if length of (active of dct) > 0 then\n sofar of dct & {active of dct}\n else\n sofar of dct\n end if\n else\n {}\n end if\nend groupBy\n\n-- insertMap :: Dict -> String -> a -> Dict\non insertMap(rec, k, v)\n tell (current application's NSMutableDictionary's ¬\n dictionaryWithDictionary:rec)\n its setValue:v forKey:(k as string)\n return it as record\n end tell\nend insertMap\n\n-- intercalateS :: String -> [String] -> String\non intercalateS(sep, xs)\n set {dlm, my text item delimiters} to {my text item delimiters, sep}\n set s to xs as text\n set my text item delimiters to dlm\n return s\nend intercalateS\n\n-- Just :: a -> Maybe a\non Just(x)\n {type:\"Maybe\", Nothing:false, Just:x}\nend Just\n\n-- keys :: Dict -> [String]\non keys(rec)\n (current application's NSDictionary's dictionaryWithDictionary:rec)'s allKeys() as list\nend keys\n\n-- lookupDict :: a -> Dict -> Maybe b\non lookupDict(k, dct)\n set ca to current application\n set v to (ca's NSDictionary's dictionaryWithDictionary:dct)'s objectForKey:k\n if v ≠ missing value then\n Just(item 1 of ((ca's NSArray's arrayWithObject:v) as list))\n else\n Nothing()\n end if\nend lookupDict\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: First-class m => (a -> b) -> m (a -> b)\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- mapFromList :: [(k, v)] -> Dict\non mapFromList(kvs)\n set tpl to unzip(kvs)\n script\n on |λ|(x)\n x as string\n end |λ|\n end script\n (current application's NSDictionary's ¬\n dictionaryWithObjects:(|2| of tpl) ¬\n forKeys:map(result, |1| of tpl)) as record\nend mapFromList\n\n-- min :: Ord a => a -> a -> a\non min(x, y)\n if y < x then\n y\n else\n x\n end if\nend min\n\n-- Nothing :: Maybe a\non Nothing()\n {type:\"Maybe\", Nothing:true}\nend Nothing\n\n-- e.g. sortBy(|on|(compare, |length|), [\"epsilon\", \"mu\", \"gamma\", \"beta\"])\n-- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c\non |on|(f, g)\n script\n on |λ|(a, b)\n tell mReturn(g) to set {va, vb} to {|λ|(a), |λ|(b)}\n tell mReturn(f) to |λ|(va, vb)\n end |λ|\n end script\nend |on|\n\n-- partition :: predicate -> List -> (Matches, nonMatches)\n-- partition :: (a -> Bool) -> [a] -> ([a], [a])\non partition(f, xs)\n tell mReturn(f)\n set ys to {}\n set zs to {}\n repeat with x in xs\n set v to contents of x\n if |λ|(v) then\n set end of ys to v\n else\n set end of zs to v\n end if\n end repeat\n end tell\n Tuple(ys, zs)\nend partition\n\n-- show :: a -> String\non show(e)\n set c to class of e\n if c = list then\n showList(e)\n else if c = record then\n set mb to lookupDict(\"type\", e)\n if Nothing of mb then\n showDict(e)\n else\n script\n on |λ|(t)\n if \"Either\" = t then\n set f to my showLR\n else if \"Maybe\" = t then\n set f to my showMaybe\n else if \"Ordering\" = t then\n set f to my showOrdering\n else if \"Ratio\" = t then\n set f to my showRatio\n else if class of t is text and t begins with \"Tuple\" then\n set f to my showTuple\n else\n set f to my showDict\n end if\n tell mReturn(f) to |λ|(e)\n end |λ|\n end script\n tell result to |λ|(Just of mb)\n end if\n else if c = date then\n \"\\\"\" & showDate(e) & \"\\\"\"\n else if c = text then\n \"'\" & e & \"'\"\n else if (c = integer or c = real) then\n e as text\n else if c = class then\n \"null\"\n else\n try\n e as text\n on error\n (\"«\" & c as text) & \"»\"\n end try\n end if\nend show\n\n-- showList :: [a] -> String\non showList(xs)\n \"[\" & intercalateS(\", \", map(my show, xs)) & \"]\"\nend showList\n\n-- showTuple :: Tuple -> String\non showTuple(tpl)\n set ca to current application\n script\n on |λ|(n)\n set v to (ca's NSDictionary's dictionaryWithDictionary:tpl)'s objectForKey:(n as string)\n if v ≠ missing value then\n unQuoted(show(item 1 of ((ca's NSArray's arrayWithObject:v) as list)))\n else\n missing value\n end if\n end |λ|\n end script\n \"(\" & intercalateS(\", \", map(result, enumFromToInt(1, length of tpl))) & \")\"\nend showTuple\n\n-- snd :: (a, b) -> b\non snd(tpl)\n if class of tpl is record then\n |2| of tpl\n else\n item 2 of tpl\n end if\nend snd\n\n-- Enough for small scale sorts.\n-- Use instead sortOn :: Ord b => (a -> b) -> [a] -> [a]\n-- which is equivalent to the more flexible sortBy(comparing(f), xs)\n-- and uses a much faster ObjC NSArray sort method\n-- sortBy :: (a -> a -> Ordering) -> [a] -> [a]\non sortBy(f, xs)\n if length of xs > 1 then\n set h to item 1 of xs\n set f to mReturn(f)\n script\n on |λ|(x)\n f's |λ|(x, h) ≤ 0\n end |λ|\n end script\n set lessMore to partition(result, rest of xs)\n sortBy(f, |1| of lessMore) & {h} & ¬\n sortBy(f, |2| of lessMore)\n else\n xs\n end if\nend sortBy\n\n-- splitOn :: String -> String -> [String]\non splitOn(pat, src)\n set {dlm, my text item delimiters} to ¬\n {my text item delimiters, pat}\n set xs to text items of src\n set my text item delimiters to dlm\n return xs\nend splitOn\n\n-- swap :: (a, b) -> (b, a)\non swap(ab)\n if class of ab is record then\n Tuple(|2| of ab, |1| of ab)\n else\n {item 2 of ab, item 1 of ab}\n end if\nend swap\n\n-- take :: Int -> [a] -> [a]\n-- take :: Int -> String -> String\non take(n, xs)\n set c to class of xs\n if list is c then\n if 0 < n then\n items 1 thru min(n, length of xs) of xs\n else\n {}\n end if\n else if string is c then\n if 0 < n then\n text 1 thru min(n, length of xs) of xs\n else\n \"\"\n end if\n else if script is c then\n set ys to {}\n repeat with i from 1 to n\n set v to xs's |λ|()\n if missing value is v then\n return ys\n else\n set end of ys to v\n end if\n end repeat\n return ys\n else\n missing value\n end if\nend take\n\n-- toLower :: String -> String\non toLower(str)\n set ca to current application\n ((ca's NSString's stringWithString:(str))'s ¬\n lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text\nend toLower\n\n-- Tuple (,) :: a -> b -> (a, b)\non Tuple(a, b)\n {type:\"Tuple\", |1|:a, |2|:b, length:2}\nend Tuple\n\n-- tupleFromList :: [a] -> (a, a ...)\non tupleFromList(xs)\n set lng to length of xs\n if 1 < lng then\n if 2 < lng then\n set strSuffix to lng as string\n else\n set strSuffix to \"\"\n end if\n script kv\n on |λ|(a, x, i)\n insertMap(a, (i as string), x)\n end |λ|\n end script\n foldl(kv, {type:\"Tuple\" & strSuffix}, xs) & {length:lng}\n else\n missing value\n end if\nend tupleFromList\n\n-- unQuoted :: String -> String\non unQuoted(s)\n script p\n on |λ|(x)\n --{34, 39} contains id of x\n 34 = id of x\n end |λ|\n end script\n dropAround(p, s)\nend unQuoted\n\n-- unzip :: [(a,b)] -> ([a],[b])\non unzip(xys)\n set xs to {}\n set ys to {}\n repeat with xy in xys\n set end of xs to |1| of xy\n set end of ys to |2| of xy\n end repeat\n return Tuple(xs, ys)\nend unzip\n\n-- words :: String -> [String]\non |words|(s)\n set ca to current application\n (((ca's NSString's stringWithString:(s))'s ¬\n componentsSeparatedByCharactersInSet:(ca's ¬\n NSCharacterSet's whitespaceAndNewlineCharacterSet()))'s ¬\n filteredArrayUsingPredicate:(ca's ¬\n NSPredicate's predicateWithFormat:\"0 < length\")) as list\nend |words|\n", "language": "AppleScript" }, { "code": "dates: [\n [May 15] [May 16] [May 19]\n [June 17] [June 18]\n [July 14] [July 16]\n [August 14] [August 15] [August 17]\n]\n\nprint [\"possible dates:\" dates]\n\nprint \"\\n(1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\"\nprint \"\\t-> meaning: the month cannot have a unique day\"\ndates: filter dates 'd [\n in? d\\0 map select dates 'dd [\n 1 = size select dates 'pd -> pd\\1=dd\\1\n ] 'dd -> dd\\0\n]\nprint [\"\\t-> remaining:\" dates]\n\nprint \"\\n(2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\"\nprint \"\\t-> meaning: the day must be unique\"\ndates: select dates 'd [\n 1 = size select dates 'pd -> pd\\1=d\\1\n]\nprint [\"\\t-> remaining:\" dates]\n\nprint \"\\n(3) Albert: Then I also know when Cheryl's birthday is.\"\nprint \"\\t-> meaning: the month must be unique\"\ndates: select dates 'd [\n 1 = size select dates 'pd -> pd\\0=d\\0\n]\nprint [\"\\t-> remaining:\" dates]\n\nprint [\"\\nCheryl's birthday:\" first dates]\n", "language": "Arturo" }, { "code": "oDates:= {\"May\" : [ 15, 16, 19]\n ,\"Jun\" : [ 17, 18]\n ,\"Jul\" : [14, 16]\n ,\"Aug\" : [14, 15, 17]}\n\nfilter1(oDates)\nfilter2(oDates)\nfilter3(oDates)\nMsgBox % result := checkAnswer(oDates)\nreturn\n\nfilter1(ByRef oDates){ ; remove months that has a unique day in it.\n for d, obj in MonthsOfDay(oDates)\n if (obj.count() = 1)\n for m, bool in obj\n oDates.Remove(m)\n}\n\nfilter2(ByRef oDates){ ; remove non-unique days from remaining months.\n for d, obj in MonthsOfDay(oDates)\n if (obj.count() > 1)\n for m, bool in obj\n for i, day in oDates[m]\n if (day=d)\n oDates[m].Remove(i)\n}\n\nfilter3(ByRef oDates){ ; remove months that has multiple days from remaining months.\n oRemove := []\n for m, obj in oDates\n if obj.count() > 1\n oRemove.Push(m)\n for i, m in oRemove\n oDates.Remove(m)\n}\n\nMonthsOfDay(oDates){ ; create a list of months per day.\n MonthsOfDay := []\n for m, obj in oDates\n for i, d in obj\n MonthsOfDay[d, m] := 1\n return MonthsOfDay\n}\n\ncheckAnswer(oDates){ ; check unique answer if any.\n if oDates.count()>1\n return false\n for m, obj in oDates\n if obj.count() > 1\n return false\n else\n return m \" \" obj.1\n}\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f CHERYLS_BIRTHDAY.AWK [-v debug={0|1}]\n#\n# sorting:\n# PROCINFO[\"sorted_in\"] is used by GAWK\n# SORTTYPE is used by Thompson Automation's TAWK\n#\nBEGIN {\n debug += 0\n PROCINFO[\"sorted_in\"] = \"@ind_num_asc\" ; SORTTYPE = 1\n n = split(\"05/15,05/16,05/19,06/17,06/18,07/14,07/16,08/14,08/15,08/17\",arr,\",\")\n for (i=1; i<=n; i++) { # move dates to a more friendly structure\n mmdd_arr[arr[i]] = \"\"\n }\n print(\"Cheryl offers these ten MM/DD choices:\")\n cb_show_dates()\n printf(\"Cheryl then tells Albert her birth 'month' and Bernard her birth 'day'.\\n\\n\")\n print(\"1. Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\")\n cb_filter1()\n print(\"2. Bernard: At first I don't know when Cheryl's birthday is, but I know now.\")\n cb_filter2()\n print(\"3. Albert: Then I also know when Cheryl's birthday is.\")\n cb_filter3()\n exit(0)\n}\nfunction cb_filter1( i,j) {\n print(\"deduction: the month cannot have a unique day, leaving:\")\n cb_load_arrays(4)\n for (j in arr1) {\n if (arr1[j] == 1) {\n if (debug) { printf(\"unique day %s\\n\",j) }\n arr3[arr2[j]] = \"\"\n }\n }\n cb_remove_dates()\n}\nfunction cb_filter2( i,j) {\n print(\"deduction: the day must be unique, leaving:\")\n cb_load_arrays(4)\n for (j in arr1) {\n if (arr1[j] > 1) {\n if (debug) { printf(\"non-unique day %s\\n\",j) }\n arr3[j] = \"\"\n }\n }\n cb_remove_dates(\"...\")\n}\nfunction cb_filter3( i,j) {\n print(\"deduction: the month must be unique, leaving:\")\n cb_load_arrays(1)\n for (j in arr1) {\n if (arr1[j] > 1) {\n if (debug) { printf(\"non-unique month %s\\n\",j) }\n arr3[j] = \"\"\n }\n }\n cb_remove_dates()\n}\nfunction cb_load_arrays(col, i,key) {\n delete arr1\n delete arr2\n delete arr3\n for (i in mmdd_arr) {\n key = substr(i,col,2)\n arr1[key]++\n arr2[key] = substr(i,1,2)\n }\n}\nfunction cb_remove_dates(pattern, i,j) {\n for (j in arr3) {\n for (i in mmdd_arr) {\n if (i ~ (\"^\" pattern j)) {\n if (debug) { printf(\"removing %s\\n\",i) }\n delete mmdd_arr[i]\n }\n }\n }\n cb_show_dates()\n}\nfunction cb_show_dates( i) {\n if (debug) { printf(\"%d remaining\\n\",length(mmdd_arr)) }\n for (i in mmdd_arr) {\n printf(\"%s \",i)\n }\n printf(\"\\n\\n\")\n}\n", "language": "AWK" }, { "code": "#include <stdbool.h>\n#include <stdio.h>\n\nchar *months[] = {\n \"ERR\", \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"\n};\n\nstruct Date {\n int month, day;\n bool active;\n} dates[] = {\n {5,15,true}, {5,16,true}, {5,19,true},\n {6,17,true}, {6,18,true},\n {7,14,true}, {7,16,true},\n {8,14,true}, {8,15,true}, {8,17,true}\n};\n#define UPPER_BOUND (sizeof(dates) / sizeof(struct Date))\n\nvoid printRemaining() {\n int i, c;\n for (i = 0, c = 0; i < UPPER_BOUND; i++) {\n if (dates[i].active) {\n c++;\n }\n }\n printf(\"%d remaining.\\n\", c);\n}\n\nvoid printAnswer() {\n int i;\n for (i = 0; i < UPPER_BOUND; i++) {\n if (dates[i].active) {\n printf(\"%s, %d\\n\", months[dates[i].month], dates[i].day);\n }\n }\n}\n\nvoid firstPass() {\n // the month cannot have a unique day\n int i, j, c;\n for (i = 0; i < UPPER_BOUND; i++) {\n c = 0;\n\n for (j = 0; j < UPPER_BOUND; j++) {\n if (dates[j].day == dates[i].day) {\n c++;\n }\n }\n\n if (c == 1) {\n for (j = 0; j < UPPER_BOUND; j++) {\n if (!dates[j].active) continue;\n if (dates[j].month == dates[i].month) {\n dates[j].active = false;\n }\n }\n }\n }\n}\n\nvoid secondPass() {\n // the day must now be unique\n int i, j, c;\n for (i = 0; i < UPPER_BOUND; i++) {\n if (!dates[i].active) continue;\n c = 0;\n\n for (j = 0; j < UPPER_BOUND; j++) {\n if (!dates[j].active) continue;\n if (dates[j].day == dates[i].day) {\n c++;\n }\n }\n\n if (c > 1) {\n for (j = 0; j < UPPER_BOUND; j++) {\n if (!dates[j].active) continue;\n if (dates[j].day == dates[i].day) {\n dates[j].active = false;\n }\n }\n }\n }\n}\n\nvoid thirdPass() {\n // the month must now be unique\n int i, j, c;\n for (i = 0; i < UPPER_BOUND; i++) {\n if (!dates[i].active) continue;\n c = 0;\n\n for (j = 0; j < UPPER_BOUND; j++) {\n if (!dates[j].active) continue;\n if (dates[j].month == dates[i].month) {\n c++;\n }\n }\n\n if (c > 1) {\n for (j = 0; j < UPPER_BOUND; j++) {\n if (!dates[j].active) continue;\n if (dates[j].month == dates[i].month) {\n dates[j].active = false;\n }\n }\n }\n }\n}\n\nint main() {\n printRemaining();\n // the month cannot have a unique day\n firstPass();\n\n printRemaining();\n // the day must now be unique\n secondPass();\n\n printRemaining();\n // the month must now be unique\n thirdPass();\n\n printAnswer();\n return 0;\n}\n", "language": "C" }, { "code": "#include <algorithm>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nconst vector<string> MONTHS = {\n \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"\n};\n\nstruct Birthday {\n int month, day;\n\n friend ostream &operator<<(ostream &, const Birthday &);\n};\n\nostream &operator<<(ostream &out, const Birthday &birthday) {\n return out << MONTHS[birthday.month - 1] << ' ' << birthday.day;\n}\n\ntemplate <typename C>\nbool monthUniqueIn(const Birthday &b, const C &container) {\n auto it = cbegin(container);\n auto end = cend(container);\n int count = 0;\n while (it != end) {\n if (it->month == b.month) {\n count++;\n }\n it = next(it);\n }\n return count == 1;\n}\n\ntemplate <typename C>\nbool dayUniqueIn(const Birthday &b, const C &container) {\n auto it = cbegin(container);\n auto end = cend(container);\n int count = 0;\n while (it != end) {\n if (it->day == b.day) {\n count++;\n }\n it = next(it);\n }\n return count == 1;\n}\n\ntemplate <typename C>\nbool monthWithUniqueDayIn(const Birthday &b, const C &container) {\n auto it = cbegin(container);\n auto end = cend(container);\n while (it != end) {\n if (it->month == b.month && dayUniqueIn(*it, container)) {\n return true;\n }\n it = next(it);\n }\n return false;\n}\n\nint main() {\n vector<Birthday> choices = {\n {5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18},\n {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17},\n };\n\n // Albert knows the month but doesn't know the day.\n // So the month can't be unique within the choices.\n vector<Birthday> filtered;\n for (auto bd : choices) {\n if (!monthUniqueIn(bd, choices)) {\n filtered.push_back(bd);\n }\n }\n\n // Albert also knows that Bernard doesn't know the answer.\n // So the month can't have a unique day.\n vector<Birthday> filtered2;\n for (auto bd : filtered) {\n if (!monthWithUniqueDayIn(bd, filtered)) {\n filtered2.push_back(bd);\n }\n }\n\n // Bernard now knows the answer.\n // So the day must be unique within the remaining choices.\n vector<Birthday> filtered3;\n for (auto bd : filtered2) {\n if (dayUniqueIn(bd, filtered2)) {\n filtered3.push_back(bd);\n }\n }\n\n // Albert now knows the answer too.\n // So the month must be unique within the remaining choices.\n vector<Birthday> filtered4;\n for (auto bd : filtered3) {\n if (monthUniqueIn(bd, filtered3)) {\n filtered4.push_back(bd);\n }\n }\n\n if (filtered4.size() == 1) {\n cout << \"Cheryl's birthday is \" << filtered4[0] << '\\n';\n } else {\n cout << \"Something went wrong!\\n\";\n }\n\n return 0;\n}\n", "language": "C++" }, { "code": "public static class CherylsBirthday\n{\n public static void Main() {\n var dates = new HashSet<(string month, int day)> {\n (\"May\", 15),\n (\"May\", 16),\n (\"May\", 19),\n (\"June\", 17),\n (\"June\", 18),\n (\"July\", 14),\n (\"July\", 16),\n (\"August\", 14),\n (\"August\", 15),\n (\"August\", 17)\n };\n\n Console.WriteLine(dates.Count + \" remaining.\");\n //The month cannot have a unique day.\n var monthsWithUniqueDays = dates.GroupBy(d => d.day).Where(g => g.Count() == 1).Select(g => g.First().month).ToHashSet();\n dates.RemoveWhere(d => monthsWithUniqueDays.Contains(d.month));\n Console.WriteLine(dates.Count + \" remaining.\");\n //The day must now be unique.\n dates.IntersectWith(dates.GroupBy(d => d.day).Where(g => g.Count() == 1).Select(g => g.First()));\n Console.WriteLine(dates.Count + \" remaining.\");\n //The month must now be unique.\n dates.IntersectWith(dates.GroupBy(d => d.month).Where(g => g.Count() == 1).Select(g => g.First()));\n Console.WriteLine(dates.Single());\n }\n\n}\n", "language": "C-sharp" }, { "code": ";; Author: Amir Teymuri, Saturday 20.10.2018\n\n(defparameter *possible-dates*\n '((15 . may) (16 . may) (19 . may)\n (17 . june) (18 . june)\n (14 . july) (16 . july)\n (14 . august) (15 . august) (17 . august)))\n\n(defun unique-date-parts (possible-dates &key (alist-look-at #'car) (alist-r-assoc #'assoc))\n (let* ((date-parts (mapcar alist-look-at possible-dates))\t\n\t (unique-date-parts (remove-if #'(lambda (part) (> (count part date-parts) 1)) date-parts)))\n (mapcar #'(lambda (part) (funcall alist-r-assoc part possible-dates))\n \t unique-date-parts)))\n\n(defun person (person possible-dates)\n \"Who's turn is it to think?\"\n (case person\n ('albert (unique-date-parts possible-dates :alist-look-at #'cdr :alist-r-assoc #'rassoc))\n ('bernard (unique-date-parts possible-dates :alist-look-at #'car :alist-r-assoc #'assoc))))\n\n(defun cheryls-birthday (possible-dates)\n (person 'albert\t\t\t\n\t (person 'bernard\t\t\n\t\t (set-difference\n\t\t possible-dates\n\t\t (person 'bernard possible-dates)\n\t\t :key #'cdr))))\n\n(cheryls-birthday *possible-dates*) ;; => ((16 . JULY))\n", "language": "Common-Lisp" }, { "code": "import std.algorithm.iteration : filter, joiner, map;\nimport std.algorithm.searching : canFind;\nimport std.algorithm.sorting : sort;\nimport std.array : array;\nimport std.datetime.date : Date, Month;\nimport std.stdio : writeln;\n\nvoid main() {\n auto choices = [\n // Month.jan\n Date(2019, Month.may, 15),\n Date(2019, Month.may, 16),\n Date(2019, Month.may, 19), // unique day (1)\n\n Date(2019, Month.jun, 17),\n Date(2019, Month.jun, 18), // unique day (1)\n\n Date(2019, Month.jul, 14),\n Date(2019, Month.jul, 16), // final answer\n\n Date(2019, Month.aug, 14),\n Date(2019, Month.aug, 15),\n Date(2019, Month.aug, 17),\n ];\n\n // The month cannot have a unique day because Albert knows the month, and knows that Bernard does not know the answer\n auto uniqueMonths = choices.sort!\"a.day < b.day\".groupBy.filter!\"a.array.length == 1\".joiner.map!\"a.month\";\n // writeln(uniqueMonths.save);\n auto filter1 = choices.filter!(a => !canFind(uniqueMonths.save, a.month)).array;\n\n // Bernard now knows the answer, so the day must be unique within the remaining choices\n auto uniqueDays = filter1.sort!\"a.day < b.day\".groupBy.filter!\"a.array.length == 1\".joiner.map!\"a.day\";\n auto filter2 = filter1.filter!(a => canFind(uniqueDays.save, a.day)).array;\n\n // Albert knows the answer too, so the month must be unique within the remaining choices\n auto birthDay = filter2.sort!\"a.month < b.month\".groupBy.filter!\"a.array.length == 1\".joiner.front;\n\n // print the result\n writeln(birthDay.month, \" \", birthDay.day);\n}\n", "language": "D" }, { "code": "//Find Cheryl's Birthday. Nigel Galloway: October 23rd., 2018\ntype Month = |May |June |July |August\nlet fN n= n |> List.filter(fun (_,n)->(List.length n) < 2) |> List.unzip\nlet dates = [(May,15);(May,16);(May,19);(June,17);(June,18);(July,14);(July,16);(August,14);(August,15);(August,17)]\nlet _,n = dates |> List.groupBy snd |> fN\nlet i = n |> List.concat |> List.map fst |> Set.ofList\nlet _,g = dates |> List.filter(fun (n,_)->not (Set.contains n i)) |> List.groupBy snd |> fN\nlet _,e = List.concat g |> List.groupBy fst |> fN\nprintfn \"%A\" e\n", "language": "F-Sharp" }, { "code": "USING: assocs calendar.english fry io kernel prettyprint\nsequences sets.extras ;\n\n: unique-by ( seq quot -- newseq )\n 2dup map non-repeating '[ @ _ member? ] filter ; inline\n\nALIAS: day first\nALIAS: month second\n\n{\n { 15 5 } { 16 5 } { 19 5 } { 17 6 } { 18 6 }\n { 14 7 } { 16 7 } { 14 8 } { 15 8 } { 17 8 }\n}\n\n! the month cannot have a unique day\ndup [ day ] map non-repeating over extract-keys values\n'[ month _ member? ] reject\n\n! of the remaining dates, day must be unique\n[ day ] unique-by\n\n! of the remaining dates, month must be unique\n[ month ] unique-by\n\n! print a date that looks like { { 16 7 } }\nfirst first2 month-name write bl .\n", "language": "Factor" }, { "code": "program code_translation\n implicit none\n character(len=3), dimension(13) :: months = [\"ERR\", \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\",&\n \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n type :: Date\n integer :: month, day\n logical :: active\n end type Date\n type(Date), dimension(10) :: dates = [Date(5,15,.true.), Date(5,16,.true.), Date(5,19,.true.), &\n Date(6,17,.true.), Date(6,18,.true.), &\n Date(7,14,.true.), Date(7,16,.true.), &\n Date(8,14,.true.), Date(8,15,.true.), Date(8,17,.true.)]\n integer, parameter :: UPPER_BOUND = size(dates)\nwrite(*,*) 'possible dates: [[May 15] [May 16] [May 19] [June 17] [June 18] [July 14] [July 16] [August 14] [August 15] [August &\n 17]]'\nwrite(*,*)\nwrite(*,*) '(1) Albert: I don''t know when Cheryl''s birthday is, but I know that Bernard does not know too.'\nwrite(*,*) '\t-> meaning: the month cannot have a unique day'\nwrite(*,*) '\t-> remaining: [[July 14] [July 16] [August 14] [August 15] [August 17]] '\nwrite(*,*)\nwrite(*,*) \"(2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\"\nwrite(*,*) '\t-> meaning: the day must be unique'\nwrite(*,*) '\t-> remaining: [[July 16] [August 15] [August 17]] '\nwrite(*,*)\nwrite(*,*) '(3) Albert: Then I also know when Cheryl''s birthday is.'\nwrite(*,*) '\t-> meaning: the month must be unique'\nwrite(*,*) '\t-> remaining: [[July 16]] '\n\n call printRemaining()\n ! the month cannot have a unique day\n call firstPass()\n call printRemaining()\n ! the day must now be unique\n call secondPass()\n call printRemaining()\n ! the month must now be unique\n call thirdPass()\n call printAnswer()\n\ncontains\n\n subroutine printRemaining()\n integer :: i, c\n do i = 1, UPPER_BOUND\n if (dates(i)%active) then\n write(*,'(a,1x,i0,1x)',advance=\"no\") months(dates(i)%month+1),dates(i)%day\n c = c + 1\n end if\n end do\n!\n write(*,*)\n end subroutine printRemaining\n\n subroutine printAnswer()\n integer :: i\n write(*,'(a)',advance ='no') 'Cheryl''s birtday is on '\n do i = 1, UPPER_BOUND\n if (dates(i)%active) then\n write(*,'(a,1a1,i0)') trim(months(dates(i)%month+1)), \",\", dates(i)%day\n end if\n end do\n end subroutine printAnswer\n\n subroutine firstPass()\n ! the month cannot have a unique day\n integer :: i, j, c\n do i = 1, UPPER_BOUND\n c = 0\n do j = 1, UPPER_BOUND\n if (dates(j)%day == dates(i)%day) then\n c = c + 1\n end if\n end do\n if (c == 1) then\n do j = 1, UPPER_BOUND\n if (.not. dates(j)%active) cycle\n if (dates(j)%month == dates(i)%month) then\n dates(j)%active = .false.\n end if\n end do\n end if\n end do\n end subroutine firstPass\n\n subroutine secondPass()\n ! the day must now be unique\n integer :: i, j, c\n do i = 1, UPPER_BOUND\n if (.not. dates(i)%active) cycle\n c = 0\n do j = 1, UPPER_BOUND\n if (.not. dates(j)%active) cycle\n if (dates(j)%day == dates(i)%day) then\n c = c + 1\n end if\n end do\n if (c > 1) then\n do j = 1, UPPER_BOUND\n if (.not. dates(j)%active) cycle\n if (dates(j)%day == dates(i)%day) then\n dates(j)%active = .false.\n end if\n end do\n end if\n end do\n end subroutine secondPass\n\n subroutine thirdPass()\n ! the month must now be unique\n integer :: i, j, c\n do i = 1, UPPER_BOUND\n if (.not. dates(i)%active) cycle\n c = 0\n do j = 1, UPPER_BOUND\n if (.not. dates(j)%active) cycle\n if (dates(j)%month == dates(i)%month) then\n c = c + 1\n end if\n end do\n if (c > 1) then\n do j = 1, UPPER_BOUND\n if (.not. dates(j)%active) cycle\n if (dates(j)%month == dates(i)%month) then\n dates(j)%active = .false.\n end if\n end do\n end if\n end do\n end subroutine thirdPass\n\nend program code_translation\n", "language": "Fortran" }, { "code": "Dim As Integer i, j, contarDias, dia, mes\nDim fechas(1 To 4, 1 To 6) As Integer => {{0, 15, 16, 0, 0, 19}, {0, 0, 0, 17, 18, 0}, {14, 0, 16, 0, 0, 0}, {14, 15, 0, 17, 0, 0}}\nDim nombreMes(1 To 4) As String => {\"May\", \"June\", \"July\", \"August\"}\n\nPrint \"Cheryl tells Albert the month and Bernard the day\"\nPrint \"Albert doesn't know the date and knows Bernard doesn't either\"\n\n' elimiate the months with unique days\nFor i = 1 To 6\n contarDias = 0\n dia = 0\n mes = 0\n For j = 1 To 4\n If fechas(j, i) <> 0 Then\n contarDias += 1\n dia = fechas(j, i)\n mes = j\n End If\n Next j\n If contarDias = 1 Then\n Print \" Eliminating \"; nombreMes(mes); \", \"; Str(dia); \"th is unique\"\n For j = 1 To 6\n fechas(mes, j) = 0\n Next j\n End If\nNext i\n\nPrint \"Bernard now knows the date\"\n\n' eliminate the days that aren't unique\nFor i = 1 To 6\n contarDias = 0\n dia = 0\n mes = 0\n For j = 1 To 4\n If fechas(j, i) <> 0 Then\n contarDias += 1\n dia = fechas(j, i)\n mes = j\n End If\n Next j\n If contarDias > 1 Then\n Print \" Eliminating \"; Str(dia); \"th, it is non-unique\"\n For j = 1 To 4\n fechas(j, i) = 0\n Next j\n End If\nNext i\n\nPrint \"Albert now knows the date\"\n\n' eliminate months with non-unique days\nFor i = 1 To 4\n contarDias = 0\n dia = 0\n mes = 0\n For j = 1 To 6\n If fechas(i, j) <> 0 Then\n contarDias += 1\n dia = fechas(i, j)\n mes = i\n End If\n Next j\n If contarDias > 1 Then\n Print \" Eliminating \"; nombreMes(i); \", it has multiple days\"\n For j = 1 To 6\n fechas(i, j) = 0\n Next j\n End If\nNext i\n\nPrint \"Cheryl's birthday: \";\nFor i = 1 To 4\n For j = 1 To 6\n If fechas(i, j) <> 0 Then\n Print \" \"; nombreMes(i); \" \"; Str(fechas(i, j)); \"th\"\n End If\n Next j\nNext i\n\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"time\"\n)\n\ntype birthday struct{ month, day int }\n\nfunc (b birthday) String() string {\n return fmt.Sprintf(\"%s %d\", time.Month(b.month), b.day)\n}\n\nfunc (b birthday) monthUniqueIn(bds []birthday) bool {\n count := 0\n for _, bd := range bds {\n if bd.month == b.month {\n count++\n }\n }\n if count == 1 {\n return true\n }\n return false\n}\n\nfunc (b birthday) dayUniqueIn(bds []birthday) bool {\n count := 0\n for _, bd := range bds {\n if bd.day == b.day {\n count++\n }\n }\n if count == 1 {\n return true\n }\n return false\n}\n\nfunc (b birthday) monthWithUniqueDayIn(bds []birthday) bool {\n for _, bd := range bds {\n if bd.month == b.month && bd.dayUniqueIn(bds) {\n return true\n }\n }\n return false\n}\n\nfunc main() {\n choices := []birthday{\n {5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18},\n {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17},\n }\n\n // Albert knows the month but doesn't know the day.\n // So the month can't be unique within the choices.\n var filtered []birthday\n for _, bd := range choices {\n if !bd.monthUniqueIn(choices) {\n filtered = append(filtered, bd)\n }\n }\n\n // Albert also knows that Bernard doesn't know the answer.\n // So the month can't have a unique day.\n var filtered2 []birthday\n for _, bd := range filtered {\n if !bd.monthWithUniqueDayIn(filtered) {\n filtered2 = append(filtered2, bd)\n }\n }\n\n // Bernard now knows the answer.\n // So the day must be unique within the remaining choices.\n var filtered3 []birthday\n for _, bd := range filtered2 {\n if bd.dayUniqueIn(filtered2) {\n filtered3 = append(filtered3, bd)\n }\n }\n\n // Albert now knows the answer too.\n // So the month must be unique within the remaining choices.\n var filtered4 []birthday\n for _, bd := range filtered3 {\n if bd.monthUniqueIn(filtered3) {\n filtered4 = append(filtered4, bd)\n }\n }\n\n if len(filtered4) == 1 {\n fmt.Println(\"Cheryl's birthday is\", filtered4[0])\n } else {\n fmt.Println(\"Something went wrong!\")\n }\n}\n", "language": "Go" }, { "code": "import java.time.Month\n\nclass Main {\n private static class Birthday {\n private Month month\n private int day\n\n Birthday(Month month, int day) {\n this.month = month\n this.day = day\n }\n\n Month getMonth() {\n return month\n }\n\n int getDay() {\n return day\n }\n\n @Override\n String toString() {\n return month.toString() + \" \" + day\n }\n }\n\n static void main(String[] args) {\n List<Birthday> choices = [\n new Birthday(Month.MAY, 15),\n new Birthday(Month.MAY, 16),\n new Birthday(Month.MAY, 19),\n new Birthday(Month.JUNE, 17),\n new Birthday(Month.JUNE, 18),\n new Birthday(Month.JULY, 14),\n new Birthday(Month.JULY, 16),\n new Birthday(Month.AUGUST, 14),\n new Birthday(Month.AUGUST, 15),\n new Birthday(Month.AUGUST, 17)\n ]\n println(\"There are ${choices.size()} candidates remaining.\")\n\n // The month cannot have a unique day because Albert knows the month, and knows that Bernard does not know the answer\n Set<Birthday> uniqueMonths = choices.groupBy { it.getDay() }\n .values()\n .findAll() { it.size() == 1 }\n .flatten()\n .collect { ((Birthday) it).getMonth() }\n .toSet() as Set<Birthday>\n def f1List = choices.findAll { !uniqueMonths.contains(it.getMonth()) }\n println(\"There are ${f1List.size()} candidates remaining.\")\n\n // Bernard now knows the answer, so the day must be unique within the remaining choices\n List<Birthday> f2List = f1List.groupBy { it.getDay() }\n .values()\n .findAll { it.size() == 1 }\n .flatten()\n .toList() as List<Birthday>\n println(\"There are ${f2List.size()} candidates remaining.\")\n\n // Albert knows the answer too, so the month must be unique within the remaining choices\n List<Birthday> f3List = f2List.groupBy { it.getMonth() }\n .values()\n .findAll { it.size() == 1 }\n .flatten()\n .toList() as List<Birthday>\n println(\"There are ${f3List.size()} candidates remaining.\")\n\n if (f3List.size() == 1) {\n println(\"Cheryl's birthday is ${f3List.head()}\")\n } else {\n System.out.println(\"No unique choice found\")\n }\n }\n}\n", "language": "Groovy" }, { "code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.List as L (filter, groupBy, head, length, sortOn)\nimport Data.Map.Strict as M (Map, fromList, keys, lookup)\nimport Data.Text as T (Text, splitOn, words)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Data.Function (on)\nimport Data.Tuple (swap)\nimport Data.Bool (bool)\n\ndata DatePart\n = Month\n | Day\n\ntype M = Text\n\ntype D = Text\n\nmain :: IO ()\nmain =\n print $\n -- The month with only one remaining day,\n --\n -- (A's month contains only one remaining day)\n -- (3 :: A \"Then I also know\")\n uniquePairing Month $\n -- among the days with unique months,\n --\n -- (B's day is paired with only one remaining month)\n -- (2 :: B \"I know now\")\n uniquePairing Day $\n -- excluding months with unique days,\n --\n -- (A's month is not among those with unique days)\n -- (1 :: A \"I know that Bernard does not know\")\n monthsWithUniqueDays False $\n -- from the given month-day pairs:\n --\n -- (0 :: Cheryl's list)\n (\\(x:y:_) -> (x, y)) . T.words <$>\n splitOn\n \", \"\n \"May 15, May 16, May 19, June 17, June 18, \\\n \\July 14, July 16, Aug 14, Aug 15, Aug 17\"\n\n----------------------QUERY FUNCTIONS----------------------\nmonthsWithUniqueDays :: Bool -> [(M, D)] -> [(M, D)]\nmonthsWithUniqueDays bln xs =\n let months = fst <$> uniquePairing Day xs\n in L.filter (bool not id bln . (`elem` months) . fst) xs\n\nuniquePairing :: DatePart -> [(M, D)] -> [(M, D)]\nuniquePairing dp xs =\n let f =\n case dp of\n Month -> fst\n Day -> snd\n in (\\md ->\n let dct = f md\n uniques =\n L.filter\n ((1 ==) . L.length . fromJust . flip M.lookup dct)\n (keys dct)\n in L.filter ((`elem` uniques) . f) xs)\n ((((,) . mapFromPairs) <*> mapFromPairs . fmap swap) xs)\n\nmapFromPairs :: [(M, D)] -> Map Text [Text]\nmapFromPairs xs =\n M.fromList $\n ((,) . fst . L.head) <*> fmap snd <$>\n L.groupBy (on (==) fst) (L.sortOn fst xs)\n", "language": "Haskell" }, { "code": "Dates=: cutLF noun define\n15 May\n16 May\n19 May\n17 June\n18 June\n14 July\n16 July\n14 August\n15 August\n17 August\n)\n\ngetDayMonth=: |:@:(cut&>) NB. retrieve lists of days and months from dates\nkeep=: adverb def '] #~ u' NB. apply mask to filter dates\n\nmonthsWithUniqueDay=: {./. #~ (1=#)/. NB. list months that have a unique day\nisMonthWithoutUniqueDay=: (] -.@e. monthsWithUniqueDay)/@getDayMonth NB. mask of dates with a month that doesn't have a unique day\n\nuniqueDayInMonth=: ~.@[ #~ (1=#)/. NB. list of days that are unique to 1 month\nisUniqueDayInMonth=: ([ e. uniqueDayInMonth)/@getDayMonth NB. mask of dates with a day that is unique to 1 month\n\nuniqueMonth=: ~.@] #~ (1=#)/.~ NB. list of months with 1 unique day\nisUniqueMonth=: (] e. uniqueMonth)/@getDayMonth NB. mask of dates with a month that has 1 unique day\n", "language": "J" }, { "code": " isUniqueMonth keep isUniqueDayInMonth keep isMonthWithoutUniqueDay keep Dates\n+-------+\n|16 July|\n+-------+\n", "language": "J" }, { "code": "possible=: cut;._2 'May 15, May 16, May 19, June 17, June 18, July 14, July 16, August 14, August 15, August 17,'\n\nAlbert=: {.\"1 NB. Albert knows month\nBernard=: {:\"1 NB. Bernard knows day\n\nNB. Bernard's understanding of Albert's first pass\n days=: {:\"1 possible\n invaliddays=: (1=#/.~ days)#~.days\n months=: {.\"1 possible\n validmonths=: months -. (days e. invaliddays)#months\n possibleA=. (months e. validmonths)# possible\n\nNB. Albert's understanding of Bernard's pass\n days=: {:\"1 possibleA\n invaliddays=: (1<#/.~ days)#~.days\n possibleB=. (days e. days-.invaliddays)# possibleA\n\nNB. our understanding of Albert's understanding of Bernard's understanding of Albert's first pass\n months=: {.\"1 possibleB\n invalidmonths=: (1<#/.~months)#~.months\n echo ;:inv (months e. months -. invalidmonths)#possibleB\n", "language": "J" }, { "code": "import java.time.Month;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\npublic class Main {\n private static class Birthday {\n private Month month;\n private int day;\n\n public Birthday(Month month, int day) {\n this.month = month;\n this.day = day;\n }\n\n public Month getMonth() {\n return month;\n }\n\n public int getDay() {\n return day;\n }\n\n @Override\n public String toString() {\n return month + \" \" + day;\n }\n }\n\n public static void main(String[] args) {\n List<Birthday> choices = List.of(\n new Birthday(Month.MAY, 15),\n new Birthday(Month.MAY, 16),\n new Birthday(Month.MAY, 19),\n new Birthday(Month.JUNE, 17),\n new Birthday(Month.JUNE, 18),\n new Birthday(Month.JULY, 14),\n new Birthday(Month.JULY, 16),\n new Birthday(Month.AUGUST, 14),\n new Birthday(Month.AUGUST, 15),\n new Birthday(Month.AUGUST, 17)\n );\n System.out.printf(\"There are %d candidates remaining.\\n\", choices.size());\n\n // The month cannot have a unique day because Albert knows the month, and knows that Bernard does not know the answer\n Set<Month> uniqueMonths = choices.stream()\n .collect(Collectors.groupingBy(Birthday::getDay))\n .values()\n .stream()\n .filter(g -> g.size() == 1)\n .flatMap(Collection::stream)\n .map(Birthday::getMonth)\n .collect(Collectors.toSet());\n List<Birthday> f1List = choices.stream()\n .filter(birthday -> !uniqueMonths.contains(birthday.month))\n .collect(Collectors.toList());\n System.out.printf(\"There are %d candidates remaining.\\n\", f1List.size());\n\n // Bernard now knows the answer, so the day must be unique within the remaining choices\n List<Birthday> f2List = f1List.stream()\n .collect(Collectors.groupingBy(Birthday::getDay))\n .values()\n .stream()\n .filter(g -> g.size() == 1)\n .flatMap(Collection::stream)\n .collect(Collectors.toList());\n System.out.printf(\"There are %d candidates remaining.\\n\", f2List.size());\n\n // Albert knows the answer too, so the month must be unique within the remaining choices\n List<Birthday> f3List = f2List.stream()\n .collect(Collectors.groupingBy(Birthday::getMonth))\n .values()\n .stream()\n .filter(g -> g.size() == 1)\n .flatMap(Collection::stream)\n .collect(Collectors.toList());\n System.out.printf(\"There are %d candidates remaining.\\n\", f3List.size());\n\n if (f3List.size() == 1) {\n System.out.printf(\"Cheryl's birthday is %s\\n\", f3List.get(0));\n } else {\n System.out.println(\"No unique choice found\");\n }\n }\n}\n", "language": "Java" }, { "code": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () => {\n const\n month = fst,\n day = snd;\n showLog(\n map(x => Array.from(x), (\n\n // The month with only one remaining day,\n\n // (A's month contains only one remaining day)\n // (3 :: A \"Then I also know\")\n uniquePairing(month)(\n\n // among the days with unique months,\n\n // (B's day is paired with only one remaining month)\n // (2 :: B \"I know now\")\n uniquePairing(day)(\n\n // excluding months with unique days,\n\n // (A's month is not among those with unique days)\n // (1 :: A \"I know that Bernard does not know\")\n monthsWithUniqueDays(false)(\n\n // from the given month-day pairs:\n\n // (0 :: Cheryl's list)\n map(x => tupleFromList(words(strip(x))),\n splitOn(/,\\s+/,\n `May 15, May 16, May 19,\n June 17, June 18, July 14, July 16,\n Aug 14, Aug 15, Aug 17`\n )\n )\n )\n )\n )\n ))\n );\n };\n\n // monthsWithUniqueDays :: Bool -> [(Month, Day)] -> [(Month, Day)]\n const monthsWithUniqueDays = blnInclude => xs => {\n const months = map(fst, uniquePairing(snd)(xs));\n return filter(\n md => (blnInclude ? id : not)(\n elem(fst(md), months)\n ),\n xs\n );\n };\n\n // uniquePairing :: ((a, a) -> a) ->\n // -> [(Month, Day)] -> [(Month, Day)]\n const uniquePairing = f => xs =>\n bindPairs(xs,\n md => {\n const\n dct = f(md),\n matches = filter(\n k => 1 === length(dct[k]),\n Object.keys(dct)\n );\n return filter(tpl => elem(f(tpl), matches), xs);\n }\n );\n\n // bindPairs :: [(Month, Day)] -> (Dict, Dict) -> [(Month, Day)]\n const bindPairs = (xs, f) => f(\n Tuple(\n dictFromPairs(fst)(snd)(xs),\n dictFromPairs(snd)(fst)(xs)\n )\n );\n\n // dictFromPairs :: ((a, a) -> a) -> ((a, a) -> a) -> [(a, a)] -> Dict\n const dictFromPairs = f => g => xs =>\n foldl((a, tpl) => Object.assign(\n a, {\n [f(tpl)]: (a[f(tpl)] || []).concat(g(tpl).toString())\n }\n ), {}, xs);\n\n\n // GENERIC ABSTRACTIONS -------------------------------\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // elem :: Eq a => a -> [a] -> Bool\n const elem = (x, xs) => xs.includes(x);\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = (f, xs) => xs.filter(f);\n\n // foldl :: (a -> b -> a) -> a -> [b] -> a\n const foldl = (f, a, xs) => xs.reduce(f, a);\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // id :: a -> a\n const id = x => x;\n\n // intersect :: (Eq a) => [a] -> [a] -> [a]\n const intersect = (xs, ys) =>\n xs.filter(x => -1 !== ys.indexOf(x));\n\n // Returns Infinity over objects without finite length\n // this enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // not :: Bool -> Bool\n const not = b => !b;\n\n // showLog :: a -> IO ()\n const showLog = (...args) =>\n console.log(\n args\n .map(JSON.stringify)\n .join(' -> ')\n );\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // splitOn :: String -> String -> [String]\n const splitOn = (pat, src) =>\n src.split(pat);\n\n // strip :: String -> String\n const strip = s => s.trim();\n\n // tupleFromList :: [a] -> (a, a ...)\n const tupleFromList = xs =>\n TupleN.apply(null, xs);\n\n // TupleN :: a -> b ... -> (a, b ... )\n function TupleN() {\n const\n args = Array.from(arguments),\n lng = args.length;\n return lng > 1 ? Object.assign(\n args.reduce((a, x, i) => Object.assign(a, {\n [i]: x\n }), {\n type: 'Tuple' + (2 < lng ? lng.toString() : ''),\n length: lng\n })\n ) : args[0];\n };\n\n // words :: String -> [String]\n const words = s => s.split(/\\s+/);\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "def count(stream; cond):\n reduce stream as $i (0; if $i|cond then .+1 else . end);\n\ndef Months: [\n \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n];\n\n# tostring\ndef birthday: \"\\(Months[.month-1]) \\(.day)\";\n\n# Input: a Birthday\ndef monthUniqueIn($bds):\n .month as $thisMonth\n | count( $bds[]; .month == $thisMonth) == 1;\n\n# Input: a Birthday\ndef dayUniqueIn($bds):\n .day as $thisDay\n | count( $bds[]; .day == $thisDay) == 1;\n\n# Input: a Birthday\ndef monthWithUniqueDayIn($bds):\n .month as $thisMonth\n | any( $bds[]; $thisMonth == .month and dayUniqueIn($bds));\n\ndef choices: [\n {month: 5, day: 15}, {month: 5, day: 16}, {month: 5, day: 19}, {month: 6, day: 17},\n {month: 6, day: 18}, {month: 7, day: 14}, {month: 7, day: 16}, {month: 8, day: 14},\n {month: 8, day: 15}, {month: 8, day: 17}\n];\n\n# Albert knows the month but doesn't know the day,\n# so the month can't be unique within the choices.\ndef filter1:\n . as $in\n | map(select( monthUniqueIn($in) | not));\n\n# Albert also knows that Bernard doesn't know the answer,\n# so the month can't have a unique day.\ndef filter2:\n . as $in\n | map(select( monthWithUniqueDayIn($in) | not));\n\n# Bernard now knows the answer,\n# so the day must be unique within the remaining choices.\ndef filter3:\n . as $in\n | map(select( dayUniqueIn($in) ));\n\n# Albert now knows the answer too.\n# So the month must be unique within the remaining choices.\ndef filter4:\n . as $in\n | map(select( monthUniqueIn($in) ));\n\ndef solve:\n (choices | filter1 | filter2 | filter3 | filter4) as $bds\n | if $bds|length == 1\n then \"Cheryl's birthday is \\($bds[0]|birthday).\"\n else \"Whoops!\"\n end;\n\nsolve\n", "language": "Jq" }, { "code": "const dates = [[15, \"May\"], [16, \"May\"], [19, \"May\"], [17, \"June\"], [18, \"June\"],\n [14, \"July\"], [16, \"July\"], [14, \"August\"], [15, \"August\"], [17, \"August\"]]\n\nuniqueday(parr) = filter(x -> count(y -> y[1] == x[1], parr) == 1, parr)\n\n# At the start, they come to know that they have no unique day of month to identify.\nconst f1 = filter(m -> !(m[2] in [d[2] for d in uniqueday(dates)]), dates)\n\n# After cutting months with unique dates, get months remaining that now have a unique date.\nconst f2 = uniqueday(f1)\n\n# filter for those of the finally remaining months that have only one date left.\nconst bday = filter(x -> count(m -> m[2] == x[2], f2) == 1, f2)[]\n\nprintln(\"Cheryl's birthday is $(bday[2]) $(bday[1]).\")\n", "language": "Julia" }, { "code": "// Version 1.2.71\n\nval months = listOf(\n \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n)\n\nclass Birthday(val month: Int, val day: Int) {\n public override fun toString() = \"${months[month - 1]} $day\"\n\n public fun monthUniqueIn(bds: List<Birthday>): Boolean {\n return bds.count { this.month == it.month } == 1\n }\n\n public fun dayUniqueIn(bds: List<Birthday>): Boolean {\n return bds.count { this.day == it.day } == 1\n }\n\n public fun monthWithUniqueDayIn(bds: List<Birthday>): Boolean {\n return bds.any { (this.month == it.month) && it.dayUniqueIn(bds) }\n }\n}\n\nfun main(args: Array<String>) {\n val choices = listOf(\n Birthday(5, 15), Birthday(5, 16), Birthday(5, 19), Birthday(6, 17),\n Birthday(6, 18), Birthday(7, 14), Birthday(7, 16), Birthday(8, 14),\n Birthday(8, 15), Birthday(8, 17)\n )\n\n // Albert knows the month but doesn't know the day.\n // So the month can't be unique within the choices.\n var filtered = choices.filterNot { it.monthUniqueIn(choices) }\n\n // Albert also knows that Bernard doesn't know the answer.\n // So the month can't have a unique day.\n filtered = filtered.filterNot { it.monthWithUniqueDayIn(filtered) }\n\n // Bernard now knows the answer.\n // So the day must be unique within the remaining choices.\n filtered = filtered.filter { it.dayUniqueIn(filtered) }\n\n // Albert now knows the answer too.\n // So the month must be unique within the remaining choices.\n filtered = filtered.filter { it.monthUniqueIn(filtered) }\n\n if (filtered.size == 1)\n println(\"Cheryl's birthday is ${filtered[0]}\")\n else\n println(\"Something went wrong!\")\n}\n", "language": "Kotlin" }, { "code": "-- Cheryl's Birthday in Lua 6/15/2020 db\n\nlocal function Date(mon,day)\n return { mon=mon, day=day, valid=true }\nend\n\nlocal choices = {\n Date(\"May\", 15), Date(\"May\", 16), Date(\"May\", 19),\n Date(\"June\", 17), Date(\"June\", 18),\n Date(\"July\", 14), Date(\"July\", 16),\n Date(\"August\", 14), Date(\"August\", 15), Date(\"August\", 17)\n}\n\nlocal function apply(t, f)\n for k, v in ipairs(t) do\n f(k, v)\n end\nend\n\nlocal function filter(t, f)\n local result = {}\n for k, v in ipairs(t) do\n if f(k, v) then\n result[#result+1] = v\n end\n end\n return result\nend\n\nlocal function map(t, f)\n local result = {}\n for k, v in ipairs(t) do\n result[#result+1] = f(k, v)\n end\n return result\nend\n\nlocal function count(t) return #t end\nlocal function isvalid(k, v) return v.valid end\nlocal function invalidate(k, v) v.valid = false end\nlocal function remaining() return filter(choices, isvalid) end\n\nlocal function listValidChoices()\n print(\" \" .. table.concat(map(remaining(), function(k, v) return v.mon .. \" \" .. v.day end), \", \"))\n print()\nend\n\nprint(\"Cheryl offers these ten choices:\")\nlistValidChoices()\n\nprint(\"1) Albert knows that Bernard also cannot yet know, so cannot be a month with a unique day, leaving:\")\napply(remaining(), function(k, v)\n if count(filter(choices, function(k2, v2) return v.day==v2.day end)) == 1 then\n apply(filter(remaining(), function(k2, v2) return v.mon==v2.mon end), invalidate)\n end\nend)\nlistValidChoices()\n\nprint(\"2) After Albert's revelation, Bernard now knows, so day must be unique, leaving:\")\napply(remaining(), function(k, v)\n local subset = filter(remaining(), function(k2, v2) return v.day==v2.day end)\n if count(subset) > 1 then apply(subset, invalidate) end\nend)\nlistValidChoices()\n\nprint(\"3) After Bernard's revelation, Albert now knows, so month must be unique, leaving only:\")\napply(remaining(), function(k, v)\n local subset = filter(remaining(), function(k2, v2) return v.mon==v2.mon end)\n if count(subset) > 1 then apply(subset, invalidate) end\nend)\nlistValidChoices()\n", "language": "Lua" }, { "code": "opts = Tuples[{{\"May\"}, {15, 16, 19}}]~Join~Tuples[{{\"June\"}, {17, 18}}]~Join~Tuples[{{\"July\"}, {14, 16}}]~Join~Tuples[{{\"August\"}, {14, 15, 17}}];\nmonthsdelete = Select[GatherBy[opts, Last], Length /* EqualTo[1]][[All, 1, 1]];\nopts = DeleteCases[opts, {Alternatives @@ monthsdelete, _}]\nremovedates = Catenate@Select[GatherBy[opts, Last], Length /* GreaterThan[1]];\nopts = DeleteCases[opts, Alternatives @@ removedates]\nSelect[GatherBy[opts, First], Length /* EqualTo[1]]\n", "language": "Mathematica" }, { "code": "import tables\nimport sets\nimport strformat\n\ntype Date = tuple[month: string, day: int]\n\nconst Dates = [Date (\"May\", 15), (\"May\", 16), (\"May\", 19), (\"June\", 17), (\"June\", 18),\n (\"July\", 14), (\"July\", 16), (\"August\", 14), (\"August\", 15), (\"August\", 17)]\n\nconst\n\n MonthTable: Table[int, HashSet[string]] =\n static:\n var t: Table[int, HashSet[string]]\n for date in Dates:\n t.mgetOrPut(date.day, initHashSet[string]()).incl(date.month)\n t\n\n DayTable: Table[string, HashSet[int]] =\n static:\n var t: Table[string, HashSet[int]]\n for date in Dates:\n t.mgetOrPut(date.month, initHashSet[int]()).incl(date.day)\n t\n\nvar possibleMonths: HashSet[string] # Set of possible months.\nvar possibleDays: HashSet[int] # Set of possible days.\n\n\n# Albert: I don't know when Cheryl's birthday is, ...\n# => eliminate months with a single possible day.\nfor month, days in DayTable.pairs:\n if days.len > 1:\n possibleMonths.incl(month)\n\n# ... but I know that Bernard does not know too.\n# => eliminate months with one day present only in this month.\nfor month, days in DayTable.pairs:\n for day in days:\n if MonthTable[day].len == 1:\n possibleMonths.excl(month)\necho fmt\"After first Albert's sentence, possible months are {possibleMonths}.\"\n\n# Bernard: At first I don't know when Cheryl's birthday is, ...\n# => eliminate days with a single possible month.\nfor day, months in MonthTable.pairs:\n if months.len > 1:\n possibleDays.incl(day)\n\n# ... but I know now.\n# => eliminate days which are compatible with several months in \"possibleMonths\".\nvar impossibleDays: HashSet[int] # Days which are eliminated by this sentence.\nfor day in possibleDays:\n if (MonthTable[day] * possibleMonths).len > 1:\n impossibleDays.incl(day)\npossibleDays.excl(impossibleDays)\necho fmt\"After Bernard's sentence, possible days are {possibleDays}.\"\n\n# Albert: Then I also know when Cheryl's birthday is.\n# => eliminate months which are compatible with several days in \"possibleDays\".\nvar impossibleMonths: HashSet[string] # Months which are eliminated by this sentence.\nfor month in possibleMonths:\n if (DayTable[month] * possibleDays).len > 1:\n impossibleMonths.incl(month)\npossibleMonths.excl(impossibleMonths)\n\ndoAssert possibleMonths.len == 1\nlet month = possibleMonths.pop()\necho fmt\"After second Albert's sentence, remaining month is {month}...\"\n\npossibleDays = possibleDays * DayTable[month]\ndoAssert possibleDays.len == 1\nlet day = possibleDays.pop()\necho fmt\"and thus remaining day is {day}.\"\n\necho \"\"\necho fmt\"So birthday date is {month} {day}.\"\n", "language": "Nim" }, { "code": "sub filter {\n my($test,@dates) = @_;\n my(%M,%D,@filtered);\n\n # analysis of potential birthdays, keyed by month and by day\n for my $date (@dates) {\n my($mon,$day) = split '-', $date;\n $M{$mon}{cnt}++;\n $D{$day}{cnt}++;\n push @{$M{$mon}{day}}, $day;\n push @{$D{$day}{mon}}, $mon;\n push @{$M{$mon}{bday}}, \"$mon-$day\";\n push @{$D{$day}{bday}}, \"$mon-$day\";\n }\n\n # eliminates May/Jun dates based on 18th and 19th being singletons\n if ($test eq 'singleton') {\n my %skip;\n for my $day (grep { $D{$_}{cnt} == 1 } keys %D) { $skip{ @{$D{$day}{mon}}[0] }++ }\n for my $mon (grep { ! $skip{$_} } keys %M) { push @filtered, @{$M{$mon}{bday}} }\n\n # eliminates Jul/Aug 14th because day count > 1 across months\n } elsif ($test eq 'duplicate') {\n for my $day (grep { $D{$_}{cnt} == 1 } keys %D) { push @filtered, @{$D{$day}{bday}} }\n\n # eliminates Aug 15th/17th because day count > 1, within month\n } elsif ($test eq 'multiple') {\n for my $day (grep { $M{$_}{cnt} == 1 } keys %M) { push @filtered, @{$M{$day}{bday}} }\n }\n return @filtered;\n}\n\n# doesn't matter what order singleton/duplicate tests are run, but 'multiple' must be last;\nmy @dates = qw<5-15 5-16 5-19 6-17 6-18 7-14 7-16 8-14 8-15 8-17>;\n@dates = filter($_, @dates) for qw<singleton duplicate multiple>;\n\nmy @months = qw<_ January February March April May June July August September October November December>;\n\nmy ($m, $d) = split '-', $dates[0];\nprint \"Cheryl's birthday is $months[$m] $d.\\n\";\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">-- demo\\rosetta\\Cheryls_Birthday.exw</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">choices</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">15</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">19</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">18</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">14</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">14</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">15</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">}}</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">mwud</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- months with unique days</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">step</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">4</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">months</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">days</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">columnize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">choices</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">impossible</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">choices</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">choices</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">step</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">mwud</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_eq</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">days</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">))=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">impossible</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">mwud</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">impossible</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_eq</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">days</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">))!=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">impossible</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_eq</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">months</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">))!=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">impossible</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">choices</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">choices</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">enum</span> <span style=\"color: #000000;\">MONTH</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">DAY</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">unique_month</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">months</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_eq</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">months</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">MONTH</span><span style=\"color: #0000FF;\">]))=</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">unique_day</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">days</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_eq</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">days</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">DAY</span><span style=\"color: #0000FF;\">]))=</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">month_without_unique_day</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">months_with_unique_day</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">MONTH</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">months_with_unique_day</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">choices</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">15</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">19</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">18</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">14</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">14</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">15</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">}}</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- Albert knows the month but does not know the day.\n -- So the month cannot be unique within the choices.\n -- However this step would change nothing, hence omit it.\n -- (obvs. non_unique_month() would be as above, but !=1)\n --choices = filter(choices,non_unique_month,vslice(choices,MONTH))\n\n -- Albert also knows that Bernard doesn't know the answer.\n -- So the month cannot have a unique day.</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">unique_days</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">choices</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">unique_day</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">vslice</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">choices</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">DAY</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">months_with_unique_day</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">unique</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">vslice</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">unique_days</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">MONTH</span><span style=\"color: #0000FF;\">))</span>\n\n <span style=\"color: #000000;\">choices</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">choices</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">month_without_unique_day</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">months_with_unique_day</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- Bernard now knows the answer.\n -- So the day must be unique within the remaining choices.</span>\n <span style=\"color: #000000;\">choices</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">choices</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">unique_day</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">vslice</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">choices</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">DAY</span><span style=\"color: #0000FF;\">))</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- Albert now knows the answer too.\n -- So the month must be unique within the remaining choices.</span>\n <span style=\"color: #000000;\">choices</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">choices</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">unique_month</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">vslice</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">choices</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">MONTH</span><span style=\"color: #0000FF;\">))</span>\n\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">choices</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">crash</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Something went wrong!\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">builtins</span><span style=\"color: #0000FF;\">\\</span><span style=\"color: #004080;\">timedate</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #004080;\">timedate</span> <span style=\"color: #000000;\">td</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">td</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #004600;\">DT_MONTH</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">td</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #004600;\">DT_DAY</span><span style=\"color: #0000FF;\">]}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">choices</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Cheryl's birthday is %s\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #7060A8;\">format_timedate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">td</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Mmmm ddth\"</span><span style=\"color: #0000FF;\">)})</span>\n<!--\n", "language": "Phix" }, { "code": "'''Cheryl's Birthday'''\n\nfrom itertools import groupby\nfrom re import split\n\n\n# main :: IO ()\ndef main():\n '''Derivation of the date.'''\n\n month, day = 0, 1\n print(\n # (3 :: A \"Then I also know\")\n # (A's month contains only one remaining day)\n uniquePairing(month)(\n # (2 :: B \"I know now\")\n # (B's day is paired with only one remaining month)\n uniquePairing(day)(\n # (1 :: A \"I know that Bernard does not know\")\n # (A's month is not among those with unique days)\n monthsWithUniqueDays(False)([\n # 0 :: Cheryl's list:\n tuple(x.split()) for x in\n split(\n ', ',\n 'May 15, May 16, May 19, ' +\n 'June 17, June 18, ' +\n 'July 14, July 16, ' +\n 'Aug 14, Aug 15, Aug 17'\n )\n ])\n )\n )\n )\n\n\n# ------------------- QUERY FUNCTIONS --------------------\n\n# monthsWithUniqueDays :: Bool -> [(Month, Day)] -> [(Month, Day)]\ndef monthsWithUniqueDays(blnInclude):\n '''The subset of months with (or without) unique days.\n '''\n def go(xs):\n month, day = 0, 1\n months = [fst(x) for x in uniquePairing(day)(xs)]\n return [\n md for md in xs\n if blnInclude or not (md[month] in months)\n ]\n return go\n\n\n# uniquePairing :: DatePart -> [(Month, Day)] -> [(Month, Day)]\ndef uniquePairing(i):\n '''Subset of months (or days) with a unique intersection.\n '''\n def go(xs):\n def inner(md):\n dct = md[i]\n uniques = [\n k for k in dct.keys()\n if 1 == len(dct[k])\n ]\n return [tpl for tpl in xs if tpl[i] in uniques]\n return inner\n return ap(bindPairs)(go)\n\n\n# bindPairs :: [(Month, Day)] ->\n# ((Dict String [String], Dict String [String])\n# -> [(Month, Day)]) -> [(Month, Day)]\ndef bindPairs(xs):\n '''List monad injection operator for lists\n of (Month, Day) pairs.\n '''\n return lambda f: f(\n (\n dictFromPairs(xs),\n dictFromPairs(\n [(b, a) for (a, b) in xs]\n )\n )\n )\n\n\n# dictFromPairs :: [(Month, Day)] -> Dict Text [Text]\ndef dictFromPairs(xs):\n '''A dictionary derived from a list of\n month day pairs.\n '''\n return {\n k: [snd(x) for x in m] for k, m in groupby(\n sorted(xs, key=fst), key=fst\n )\n }\n\n\n# ----------------------- GENERIC ------------------------\n\n# ap :: (a -> b -> c) -> (a -> b) -> a -> c\ndef ap(f):\n '''Applicative instance for functions.\n '''\n def go(g):\n def fxgx(x):\n return f(x)(\n g(x)\n )\n return fxgx\n return go\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First component of a pair.\n '''\n return tpl[0]\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second component of a pair.\n '''\n return tpl[1]\n\n\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "options <- dplyr::tibble(mon = rep(c(\"May\", \"June\", \"July\", \"August\"),times = c(3,2,2,3)),\n day = c(15, 16, 19, 17, 18, 14, 16, 14, 15, 17))\n\nokMonths <- c()\n# Albert's first clue - it is a month with no unique day\nfor (i in unique(options$mon)){\n if(all(options$day[options$mon == i] %in% options$day[options$mon != i])) {okMonths <- c(okMonths, i)}\n}\n\nokDays <- c()\n# Bernard's clue - it is a day that only occurs once in the remaining dates\nfor (i in unique(options$day)){\n if(!all(options$mon[options$day == i] %in% options$mon[(options$mon %in% okMonths)])) {okDays <- c(okDays, i)}\n}\n\nremaining <- options[(options$mon %in% okMonths) & (options$day %in% okDays), ]\n# Albert's second clue - must be a month with only one un-eliminated date\nfor(i in unique(remaining$mon)){\n if(sum(remaining$mon == i) == 1) {print(remaining[remaining$mon == i,])}\n}\n", "language": "R" }, { "code": "#lang racket\n\n(define ((is x #:key [key identity]) y) (equal? (key x) (key y)))\n\n(define albert first)\n(define bernard second)\n\n(define (((unique who) chs) date) (= 1 (count (is date #:key who) chs)))\n\n(define (((unique-fix who-fix who) chs) date)\n (ormap (conjoin (is date #:key who-fix) ((unique who) chs)) chs))\n\n(define-syntax-rule (solve <chs> [<act> <arg>] ...)\n (let* ([chs <chs>] [chs (<act> (<arg> chs) chs)] ...) chs))\n\n(solve '((May 15) (May 16) (May 19) (June 17) (June 18)\n (July 14) (July 16) (August 14) (August 15) (August 17))\n\n ;; Albert knows the month but doesn't know the day.\n ;; So the month can't be unique within the choices.\n [filter-not (unique albert)]\n ;; Albert also knows that Bernard doesn't know the answer.\n ;; So the month can't have a unique day.\n [filter-not (unique-fix albert bernard)]\n ;; Bernard now knows the answer.\n ;; So the day must be unique within the remaining choices.\n [filter (unique bernard)]\n ;; Albert now knows the answer too.\n ;; So the month must be unique within the remaining choices\n [filter (unique albert)])\n", "language": "Racket" }, { "code": "my @dates =\n { :15day, :5month },\n { :16day, :5month },\n { :19day, :5month },\n { :17day, :6month },\n { :18day, :6month },\n { :14day, :7month },\n { :16day, :7month },\n { :14day, :8month },\n { :15day, :8month },\n { :17day, :8month }\n;\n\n# Month can't have a unique day\nmy @filtered = @dates.grep(*.<month> != one(@dates.grep(*.<day> == one(@dates».<day>))».<month>));\n\n# Day must be unique and unambiguous in remaining months\nmy $birthday = @filtered.grep(*.<day> == one(@filtered».<day>)).classify({.<month>})\\\n .first(*.value.elems == 1).value[0];\n\n# convenience array\nmy @months = <'' January February March April May June July August September October November December>;\n\nsay \"Cheryl's birthday is { @months[$birthday<month>] } {$birthday<day>}.\";\n", "language": "Raku" }, { "code": "/*REXX pgm finds Cheryl's birth date based on a person knowing the birth month, another */\n/*──────────────────────── person knowing the birth day, given a list of possible dates.*/\n$= 'May-15 May-16 May-19 June-17 June-18 July-14 July-16 August-14 August-15 August-17'\ncall delDays unique('day')\n$= unique('day')\n$= unique('month')\nif words($)==1 then say \"Cheryl's birthday is\" translate($, , '-')\n else say \"error in the program's logic.\"\nexit 0\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nunique: arg u 2, dups; #= words($); $$= $\n do j=# to 2 by -1\n if u=='D' then parse value word($, j) with '-' x\n else parse value word($, j) with x '-'\n do k=1 for j-1\n if u=='D' then parse value word($, k) with '-' y\n else parse value word($, k) with y '-'\n if x==y then dups= dups k j\n end /*k*/\n end /*j*/\n do d=# for # by -1\n do p=1 for words(dups) until ?==d; ?= word(dups,p)\n if ?==d then $$= delword($$, ?, 1)\n end /*d*/\n end /*d*/\n if words($$)==0 then return $\n else return $$\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ndelDays: parse arg days; #= words(days)\n do j=# for # by -1; parse value word(days, j) with x '-'; ##= words($)\n do k=## for ## by -1; parse value word($, k) with y '-'\n if x\\==y then iterate; $= delword($, k, 1)\n end /*k*/\n end /*j*/\n return $\n", "language": "REXX" }, { "code": "dates = [\n [\"May\", 15],\n [\"May\", 16],\n [\"May\", 19],\n [\"June\", 17],\n [\"June\", 18],\n [\"July\", 14],\n [\"July\", 16],\n [\"August\", 14],\n [\"August\", 15],\n [\"August\", 17],\n]\n\nprint dates.length, \" remaining\\n\"\n\n# the month cannot have a unique day\nuniqueMonths = dates.group_by { |m,d| d }\n .select { |k,v| v.size == 1 }\n .map { |k,v| v.flatten }\n .map { |m,d| m }\ndates.delete_if { |m,d| uniqueMonths.include? m }\nprint dates.length, \" remaining\\n\"\n\n# the day must be unique\ndates = dates .group_by { |m,d| d }\n .select { |k,v| v.size == 1 }\n .map { |k,v| v.flatten }\nprint dates.length, \" remaining\\n\"\n\n# the month must now be unique\ndates = dates .group_by { |m,d| m }\n .select { |k,v| v.size == 1 }\n .map { |k,v| v }\n .flatten\nprint dates\n", "language": "Ruby" }, { "code": "// This version is based on the Go version on Rosettacode\n\n#[derive(PartialEq, Debug, Copy, Clone)]\nenum Month {\n May,\n June,\n July,\n August,\n}\n\n#[derive(PartialEq, Debug, Copy, Clone)]\nstruct Birthday {\n month: Month,\n day: u8,\n}\n\nimpl Birthday {\n fn month_unique_in(&self, birthdays: &[Birthday]) -> bool {\n birthdays\n .iter()\n .filter(|birthday| birthday.month == self.month)\n .count()\n == 1\n }\n\n fn day_unique_in(&self, birthdays: &[Birthday]) -> bool {\n birthdays\n .iter()\n .filter(|birthday| birthday.day == self.day)\n .count()\n == 1\n }\n\n fn month_with_unique_day_in(&self, birthdays: &[Birthday]) -> bool {\n birthdays\n .iter()\n .any(|birthday| self.month == birthday.month && birthday.day_unique_in(birthdays))\n }\n}\n\nfn solution() -> Option<Birthday> {\n let mut choices: Vec<Birthday> = vec![\n Birthday {\n month: Month::May,\n day: 15,\n },\n Birthday {\n month: Month::May,\n day: 16,\n },\n Birthday {\n month: Month::May,\n day: 19,\n },\n Birthday {\n month: Month::June,\n day: 17,\n },\n Birthday {\n month: Month::June,\n day: 18,\n },\n Birthday {\n month: Month::July,\n day: 14,\n },\n Birthday {\n month: Month::July,\n day: 16,\n },\n Birthday {\n month: Month::August,\n day: 14,\n },\n Birthday {\n month: Month::August,\n day: 15,\n },\n Birthday {\n month: Month::August,\n day: 17,\n },\n ];\n\n // Albert knows the month but doesn't know the day.\n // So the month can't be unique within the choices.\n let choices_copy = choices.clone();\n choices.retain(|birthday| !(&birthday.month_unique_in(&choices_copy)));\n\n // Albert also knows that Bernard doesn't know the answer.\n // So the month can't have a unique day.\n let choices_copy = choices.clone();\n choices.retain(|birthday| !(birthday.month_with_unique_day_in(&choices_copy)));\n\n // Bernard now knows the answer.\n // So the day must be unique within the remaining choices.\n let choices_copy = choices.clone();\n choices.retain(|birthday| birthday.day_unique_in(&choices_copy));\n\n // Albert now knows the answer too.\n // So the month must be unique within the remaining choices.\n let choices_copy = choices.clone();\n choices.retain(|birthday| birthday.month_unique_in(&choices_copy));\n\n if choices.len() == 1 {\n Some(choices[0])\n } else {\n None\n }\n}\n\nfn main() {\n match solution() {\n Some(solution) => println!(\"Cheryl's birthday is {:?}\", solution),\n None => panic!(\"Didn't work!\"),\n }\n}\n", "language": "Rust" }, { "code": "import java.time.format.DateTimeFormatter\nimport java.time.{LocalDate, Month}\n\nobject Cheryl {\n def main(args: Array[String]): Unit = {\n val choices = List(\n LocalDate.of(2019, Month.MAY, 15),\n LocalDate.of(2019, Month.MAY, 16),\n LocalDate.of(2019, Month.MAY, 19),\n\n LocalDate.of(2019, Month.JUNE, 17),\n LocalDate.of(2019, Month.JUNE, 18),\n\n LocalDate.of(2019, Month.JULY, 14),\n LocalDate.of(2019, Month.JULY, 16),\n\n LocalDate.of(2019, Month.AUGUST, 14),\n LocalDate.of(2019, Month.AUGUST, 15),\n LocalDate.of(2019, Month.AUGUST, 17)\n )\n\n // The month cannot have a unique day because Albert knows the month, and knows that Bernard does not know the answer\n val uniqueMonths = choices.groupBy(_.getDayOfMonth)\n .filter(a => a._2.length == 1)\n .flatMap(a => a._2)\n .map(a => a.getMonth)\n val filter1 = choices.filterNot(a => uniqueMonths.exists(b => a.getMonth == b))\n\n // Bernard now knows the answer, so the day must be unique within the remaining choices\n val uniqueDays = filter1.groupBy(_.getDayOfMonth)\n .filter(a => a._2.length == 1)\n .flatMap(a => a._2)\n .map(a => a.getDayOfMonth)\n val filter2 = filter1.filter(a => uniqueDays.exists(b => a.getDayOfMonth == b))\n\n // Albert knows the answer too, so the month must be unique within the remaining choices\n val birthDay = filter2.groupBy(_.getMonth)\n .filter(a => a._2.length == 1)\n .flatMap(a => a._2)\n .head\n\n // print the result\n printf(birthDay.format(DateTimeFormatter.ofPattern(\"MMMM dd\")))\n }\n}\n", "language": "Scala" }, { "code": "object Cheryl_sBirthday extends App {\n\n private val possiblerDates = Set(\n Date(\"May\", 15), Date(\"May\", 16), Date(\"May\", 19),\n Date(\"June\", 17), Date(\"June\", 18),\n Date(\"July\", 14), Date(\"July\", 16),\n Date(\"August\", 14), Date(\"August\", 15), Date(\"August\", 17)\n )\n\n private def clou3: Date = {\n // Find the dates with ONE unique once and only occurrence of the day of the month.\n def onceDates[K](toBeExcluded: Set[Date], selector: Date => K): Seq[Date] =\n toBeExcluded.groupBy(selector).filter { case (_, multiSet) => multiSet.size == 1 }.values.flatten.toSeq\n\n // 1) Albert tells us that Bernard doesn't know the answer,\n // so we know the answer must be in months that does NOT have a same day of month.\n val uniqueMonths = onceDates(possiblerDates, (date: Date) => date.dayOfMonth).map(_.month)\n // Remove the dates with those months. The dates remain which has NOT those months.\n val clou1 = possiblerDates.filterNot(p => uniqueMonths.contains(p.month))\n // 2) Since Bernard now knows the answer, that tells us that the day MUST be unique among the remaining birthdays.\n val uniqueDays = onceDates(clou1, (date: Date) => date.dayOfMonth).map(_.dayOfMonth)\n\n // 3) Since Albert now knows the answer, that tells us the answer has to be unique by month.\n // First, as the first parameter, intersect clou1 (Albert) with uniqueDays (Bernard)\n onceDates(clou1.filter(date => uniqueDays.contains(date.dayOfMonth)), (date: Date) => date.month).head\n }\n\n case class Date(month: String, dayOfMonth: Int) {\n override def toString: String = s\"${\"🎂 \" * 3}$dayOfMonth $month${\" 🎂\" * 3}\"\n }\n\n println(clou3)\n}\n", "language": "Scala" }, { "code": "func f(day, month) {\n Date.parse(\"#{day} #{month}\", \"%d %B\")\n}\n\nvar dates = [\n f(15, \"May\"),\n f(16, \"May\"),\n f(19, \"May\"),\n f(17, \"June\"),\n f(18, \"June\"),\n f(14, \"July\"),\n f(16, \"July\"),\n f(14, \"August\"),\n f(15, \"August\"),\n f(17, \"August\")\n]\n \nvar filtered = dates.grep {\n dates.grep {\n dates.map{ .day }.count(.day) == 1\n }.map{ .month }.count(.month) != 1\n}\n \nvar birthday = filtered.grep {\n filtered.map{ .day }.count(.day) == 1\n}.group_by{ .month }.values.first_by { .len == 1 }[0]\n \nsay \"Cheryl's birthday is #{birthday.fullmonth} #{birthday.day}.\"\n", "language": "Sidef" }, { "code": "struct MonthDay: CustomStringConvertible {\n static let months = [\n \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n ]\n\n var month: Int\n var day: Int\n\n var description: String { \"\\(MonthDay.months[month - 1]) \\(day)\" }\n\n private func isUniqueIn(months: [MonthDay], by prop: KeyPath<MonthDay, Int>) -> Bool {\n return months.lazy.filter({ $0[keyPath: prop] == self[keyPath: prop] }).count == 1\n }\n\n func monthIsUniqueIn(months: [MonthDay]) -> Bool {\n return isUniqueIn(months: months, by: \\.month)\n }\n\n func dayIsUniqueIn(months: [MonthDay]) -> Bool {\n return isUniqueIn(months: months, by: \\.day)\n }\n\n func monthWithUniqueDayIn(months: [MonthDay]) -> Bool {\n return months.firstIndex(where: { $0.month == month && $0.dayIsUniqueIn(months: months) }) != nil\n }\n}\n\nlet choices = [\n MonthDay(month: 5, day: 15),\n MonthDay(month: 5, day: 16),\n MonthDay(month: 5, day: 19),\n MonthDay(month: 6, day: 17),\n MonthDay(month: 6, day: 18),\n MonthDay(month: 7, day: 14),\n MonthDay(month: 7, day: 16),\n MonthDay(month: 8, day: 14),\n MonthDay(month: 8, day: 15),\n MonthDay(month: 8, day: 17)\n]\n\n// Albert knows the month, but not the day, so he doesn't have a gimmie month\nlet albertKnows = choices.filter({ !$0.monthIsUniqueIn(months: choices) })\n\n// Albert also knows that Bernard doesn't know, so it can't be a gimmie day\nlet bernardKnows = albertKnows.filter({ !$0.monthWithUniqueDayIn(months: albertKnows) })\n\n// Bernard now knows the birthday, so it must be a unique day within the remaining choices\nlet bernardKnowsMore = bernardKnows.filter({ $0.dayIsUniqueIn(months: bernardKnows) })\n\n// Albert knows the birthday now, so it must be a unique month within the remaining choices\nguard let birthday = bernardKnowsMore.filter({ $0.monthIsUniqueIn(months: bernardKnowsMore) }).first else {\n fatalError()\n}\n\nprint(\"Cheryl's birthday is \\(birthday)\")\n", "language": "Swift" }, { "code": "import time\n\nstruct Birthday {\n\tmonth int\n\tday int\n}\n\nfn (b Birthday) str() string {\n return \"${time.long_months[b.month-1]} $b.day\"\n}\n\nfn (b Birthday) month_uniquie_in(bds []Birthday) bool {\n mut count := 0\n for bd in bds {\n if bd.month == b.month {\n count++\n }\n }\n if count == 1 {\n return true\n }\n return false\n}\n\nfn (b Birthday) day_unique_in(bds []Birthday) bool {\n mut count := 0\n for bd in bds {\n if bd.day == b.day {\n count++\n }\n }\n if count == 1 {\n return true\n }\n return false\n}\n\nfn (b Birthday) month_with_unique_day_in(bds []Birthday) bool {\n for bd in bds {\n if bd.month == b.month && bd.day_unique_in(bds) {\n return true\n }\n }\n return false\n}\n\nfn main() {\n choices := [\n Birthday{5, 15}, Birthday{5, 16}, Birthday{5, 19}, Birthday{6, 17}, Birthday{6, 18},\n Birthday{7, 14}, Birthday{7, 16}, Birthday{8, 14}, Birthday{8, 15}, Birthday{8, 17},\n\t]\n\n // Albert knows the month but doesn't know the day.\n // So the month can't be unique within the choices.\n mut filtered := []Birthday{}\n for bd in choices {\n if !bd.month_uniquie_in(choices) {\n filtered << bd\n }\n }\n\n // Albert also knows that Bernard doesn't know the answer.\n // So the month can't have a unique day.\n mut filtered2 := []Birthday{}\n for bd in filtered {\n if !bd.month_with_unique_day_in(filtered) {\n filtered2 << bd\n }\n }\n\n // Bernard now knows the answer.\n // So the day must be unique within the remaining choices.\n mut filtered3 := []Birthday{}\n for bd in filtered2 {\n if bd.day_unique_in(filtered2) {\n filtered3 << bd\n }\n }\n\n // Albert now knows the answer too.\n // So the month must be unique within the remaining choices.\n mut filtered4 := []Birthday{}\n for bd in filtered3 {\n if bd.month_uniquie_in(filtered3) {\n filtered4 << bd\n }\n }\n\n if filtered4.len == 1 {\n println(\"Cheryl's Birthday is ${filtered4[0]}\")\n } else {\n println(\"Something went wrong!\")\n }\n}\n", "language": "V-(Vlang)" }, { "code": "Private Sub exclude_unique_days(w As Collection)\n Dim number_of_dates(31) As Integer\n Dim months_to_exclude As New Collection\n For Each v In w\n number_of_dates(v(1)) = number_of_dates(v(1)) + 1\n Next v\n For i = w.Count To 1 Step -1\n If number_of_dates(w(i)(1)) = 1 Then\n months_to_exclude.Add w(i)(0)\n w.Remove i\n End If\n Next i\n For Each m In months_to_exclude\n exclude_month w, m\n Next m\nEnd Sub\nPrivate Sub exclude_month(x As Collection, v As Variant)\n For i = x.Count To 1 Step -1\n If x(i)(0) = v Then x.Remove i\n Next i\nEnd Sub\nPrivate Sub exclude_non_unique_days(w As Collection)\n Dim number_of_dates(31) As Integer\n For Each v In w\n number_of_dates(v(1)) = number_of_dates(v(1)) + 1\n Next v\n For i = w.Count To 1 Step -1\n If number_of_dates(w(i)(1)) > 1 Then\n w.Remove i\n End If\n Next i\nEnd Sub\nPrivate Sub exclude_non_unique_months(w As Collection)\n Dim months As New Collection\n For Each v In w\n On Error GoTo 1\n months.Add v(0), v(0)\n Next v\n1:\n For i = w.Count To 1 Step -1\n If w(i)(0) = v(0) Then\n w.Remove i\n End If\n Next i\nEnd Sub\nPublic Sub cherylsbirthday()\n Dim v As New Collection\n s = \"May 15, May 16, May 19, June 17, June 18, July 14, July 16, August 14, August 15, August 17\"\n t = Split(s, \",\")\n For Each u In t\n v.Add Split(Trim(u), \" \")\n Next u\n '1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\n exclude_unique_days v\n '2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\n exclude_non_unique_days v\n '3) Albert: Then I also know when Cheryl's birthday is.\n exclude_non_unique_months v\n Debug.Print v(1)(0); \" \"; v(1)(1)\nEnd Sub\n", "language": "VBA" }, { "code": "Module Module1\n\n Structure MonDay\n Dim month As String\n Dim day As Integer\n\n Sub New(m As String, d As Integer)\n month = m\n day = d\n End Sub\n\n Public Overrides Function ToString() As String\n Return String.Format(\"({0}, {1})\", month, day)\n End Function\n End Structure\n\n Sub Main()\n Dim dates = New HashSet(Of MonDay) From {\n New MonDay(\"May\", 15),\n New MonDay(\"May\", 16),\n New MonDay(\"May\", 19),\n New MonDay(\"June\", 17),\n New MonDay(\"June\", 18),\n New MonDay(\"July\", 14),\n New MonDay(\"July\", 16),\n New MonDay(\"August\", 14),\n New MonDay(\"August\", 15),\n New MonDay(\"August\", 17)\n }\n Console.WriteLine(\"{0} remaining.\", dates.Count)\n\n ' The month cannot have a unique day.\n Dim monthsWithUniqueDays = dates.GroupBy(Function(d) d.day).Where(Function(g) g.Count() = 1).Select(Function(g) g.First().month).ToHashSet()\n dates.RemoveWhere(Function(d) monthsWithUniqueDays.Contains(d.month))\n Console.WriteLine(\"{0} remaining.\", dates.Count)\n\n ' The day must now be unique.\n dates.IntersectWith(dates.GroupBy(Function(d) d.day).Where(Function(g) g.Count() = 1).Select(Function(g) g.First()))\n Console.WriteLine(\"{0} remaining.\", dates.Count)\n\n ' The month must now be unique.\n dates.IntersectWith(dates.GroupBy(Function(d) d.month).Where(Function(g) g.Count() = 1).Select(Function(g) g.First()))\n Console.WriteLine(dates.Single())\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "var Months = [\n \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n]\n\nclass Birthday {\n construct new(month, day) {\n _month = month\n _day = day\n }\n\n month { _month }\n day { _day }\n\n toString { \"%(Months[_month-1]) %(day)\" }\n\n monthUniqueIn(bds) { bds.count { |bd| _month == bd.month } == 1 }\n\n dayUniqueIn(bds) { bds.count { |bd| _day == bd.day } == 1 }\n\n monthWithUniqueDayIn(bds) { bds.any { |bd| (_month == bd.month) && bd.dayUniqueIn(bds) } }\n}\n\nvar choices = [\n Birthday.new(5, 15), Birthday.new(5, 16), Birthday.new(5, 19), Birthday.new(6, 17),\n Birthday.new(6, 18), Birthday.new(7, 14), Birthday.new(7, 16), Birthday.new(8, 14),\n Birthday.new(8, 15), Birthday.new(8, 17)\n]\n\n// Albert knows the month but doesn't know the day.\n// So the month can't be unique within the choices.\nvar filtered = choices.where { |bd| !bd.monthUniqueIn(choices) }.toList\n\n// Albert also knows that Bernard doesn't know the answer.\n// So the month can't have a unique day.\nfiltered = filtered.where { |bd| !bd.monthWithUniqueDayIn(filtered) }.toList\n\n// Bernard now knows the answer.\n// So the day must be unique within the remaining choices.\nfiltered = filtered.where { |bd| bd.dayUniqueIn(filtered) }.toList\n\n// Albert now knows the answer too.\n// So the month must be unique within the remaining choices.\nfiltered = filtered.where { |bd| bd.monthUniqueIn(filtered) }.toList\n\nif (filtered.count == 1) {\n System.print(\"Cheryl's birthday is %(filtered[0])\")\n} else {\n System.print(\"Something went wrong!\")\n}\n", "language": "Wren" }, { "code": "dates:=T(T(\"May\", 15), T(\"May\", 16), T(\"May\", 19),\n T(\"June\", 17), T(\"June\", 18),\n\t T(\"July\", 14), T(\"July\", 16),\n\t T(\"August\",14), T(\"August\",15), T(\"August\",17) );\nmDs:=dates.pump(Dictionary().appendKV); // \"June\":(15,16,19), ...\ndMs:=dates.pump(Dictionary().appendKV,\"reverse\"); // 15:\"May\", 16:\"May\", 19:\"May\", ...\n\n// remove unique days (18,19) --> \"July\":(14,16),\"August\":(14,15,17)\ndMs.values.apply2('wrap(ms){ if(ms.len()==1) mDs.del(ms[0]) });\n\n// find intersection of above days --> (14)\nfcn intersection(l1,l2){ l1.pump(List,l2.holds,'==(True),Void.Filter) }\nbadDs:=mDs.values.reduce(intersection);\n\n// --> July:(16),August:(15,17) --> ( (\"July\",(16)) )\ntheDay:=mDs.filter('wrap([(m,ds)]){ ds.removeEach(badDs).len()==1 });\n\n// print birthday such that muliples are shown, if any\nprintln(\"Cheryl's birthday is \",theDay.flatten().flatten().concat(\" \"));\n", "language": "Zkl" } ]
Cheryls-birthday
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Chinese_remainder_theorem\n", "language": "00-META" }, { "code": "Suppose &nbsp; <math>n_1</math>, &nbsp; <math>n_2</math>, &nbsp; <math>\\ldots</math>, &nbsp; <math>n_k</math> &nbsp; are positive [[integer]]s that are pairwise co-prime. &nbsp; \n\nThen, for any given sequence of integers &nbsp; <math>a_1</math>, &nbsp; <math>a_2</math>, &nbsp; <math>\\dots</math>, &nbsp; <math>a_k</math>, &nbsp; there exists an integer &nbsp; <math>x</math> &nbsp; solving the following system of simultaneous congruences:\n\n::: <math>\\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}</math>\n\nFurthermore, all solutions &nbsp; <math>x</math> &nbsp; of this system are congruent modulo the product, &nbsp; <math>N=n_1n_2\\ldots n_k</math>.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the &nbsp; [[wp:Chinese Remainder Theorem|Chinese Remainder Theorem]]. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution &nbsp; <math>s</math> &nbsp; where &nbsp; <math>0 \\leq s \\leq n_1n_2\\ldots n_k</math>.\n\n\n''Show the functionality of this program'' by printing the result such that the &nbsp; <math>n</math>'s &nbsp; are &nbsp; <math>[3,5,7]</math> &nbsp; and the &nbsp; <math>a</math>'s &nbsp; are &nbsp; <math>[2,3,2]</math>.\n\n\n'''Algorithm''': &nbsp; The following algorithm only applies if the &nbsp; <math>n_i</math>'s &nbsp; are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: <math>x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k</math>\n\nAgain, to begin, the product &nbsp; <math>N = n_1n_2 \\ldots n_k</math> &nbsp; is defined. \n\nThen a solution &nbsp; <math>x</math> &nbsp; can be found as follows:\n\nFor each &nbsp; <math>i</math>, &nbsp; the integers &nbsp; <math>n_i</math> &nbsp; and &nbsp; <math>N/n_i</math> &nbsp; are co-prime. \n\nUsing the &nbsp; [[wp:Extended Euclidean algorithm|Extended Euclidean algorithm]], &nbsp; we can find integers &nbsp; <math>r_i</math> &nbsp; and &nbsp; <math>s_i</math> &nbsp; such that &nbsp; <math>r_i n_i + s_i N/n_i = 1</math>. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: <math>x = \\sum_{i=1}^k a_i s_i N/n_i</math>\n\nand the minimal solution,\n\n::: <math>x \\pmod{N}</math>.\n<br><br>\n", "language": "00-TASK" }, { "code": "F mul_inv(=a, =b)\n V b0 = b\n V x0 = 0\n V x1 = 1\n I b == 1\n R 1\n L a > 1\n V q = a I/ b\n (a, b) = (b, a % b)\n (x0, x1) = (x1 - q * x0, x0)\n I x1 < 0\n x1 += b0\n R x1\n\nF chinese_remainder(n, a)\n V sum = 0\n V prod = product(n)\n L(n_i, a_i) zip(n, a)\n V p = prod I/ n_i\n sum += a_i * mul_inv(p, n_i) * p\n R sum % prod\n\nV n = [3, 5, 7]\nV a = [2, 3, 2]\nprint(chinese_remainder(n, a))\n", "language": "11l" }, { "code": "* Chinese remainder theorem 06/09/2015\nCHINESE CSECT\n USING CHINESE,R12 base addr\n LR R12,R15\nBEGIN LA R9,1 m=1\n LA R6,1 j=1\nLOOPJ C R6,NN do j=1 to nn\n BH ELOOPJ\n LR R1,R6 j\n SLA R1,2 j*4\n M R8,N-4(R1) m=m*n(j)\n LA R6,1(R6) j=j+1\n B LOOPJ\nELOOPJ LA R6,1 x=1\nLOOPX CR R6,R9 do x=1 to m\n BH ELOOPX\n LA R7,1 i=1\nLOOPI C R7,NN do i=1 to nn\n BH ELOOPI\n LR R1,R7 i\n SLA R1,2 i*4\n LR R5,R6 x\n LA R4,0\n D R4,N-4(R1) x//n(i)\n C R4,A-4(R1) if x//n(i)^=a(i)\n BNE ITERX then iterate x\n LA R7,1(R7) i=i+1\n B LOOPI\nELOOPI MVC PG(2),=C'x='\n XDECO R6,PG+2 edit x\n XPRNT PG,14 print buffer\n B RETURN\nITERX LA R6,1(R6) x=x+1\n B LOOPX\nELOOPX XPRNT NOSOL,17 print\nRETURN XR R15,R15 rc=0\n BR R14\nNN DC F'3'\nN DC F'3',F'5',F'7'\nA DC F'2',F'3',F'2'\nPG DS CL80\nNOSOL DC CL17'no solution found'\n YREGS\n END CHINESE\n", "language": "360-Assembly" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program chineserem64.s */\n\n/************************************/\n/* Constantes */\n/************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessResult: .asciz \"Result = \"\nszCarriageReturn: .asciz \"\\n\"\n.align 2\narrayN: .quad 3,5,7\narrayA: .quad 2,3,2\n .equ ARRAYSIZE, (. - arrayA)/8\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\nsZoneConv: .skip 24\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain:\n ldr x0,qAdrarrayN // N array address\n ldr x1,qAdrarrayA // A array address\n mov x2,#ARRAYSIZE // array size\n bl chineseremainder\n\n ldr x1,qAdrsZoneConv\n bl conversion10 // call décimal conversion\n mov x0,#3\n ldr x1,qAdrszMessResult\n ldr x2,qAdrsZoneConv // insert conversion in message\n ldr x3,qAdrszCarriageReturn\n bl displayStrings // display message\n\n100: // standard end of the program\n mov x0, #0 // return code\n mov x8,EXIT\n svc #0 // perform the system call\nqAdrszCarriageReturn: .quad szCarriageReturn\nqAdrsZoneConv: .quad sZoneConv\nqAdrszMessResult: .quad szMessResult\nqAdrarrayA: .quad arrayA\nqAdrarrayN: .quad arrayN\n\n/******************************************************************/\n/* compute chinese remainder */\n/******************************************************************/\n/* x0 contains n array address */\n/* x1 contains a array address */\n/* x2 contains array size */\nchineseremainder:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n stp x4,x5,[sp,-16]! // save registers\n stp x6,x7,[sp,-16]! // save registers\n stp x8,x9,[sp,-16]! // save registers\n mov x4,#1 // product\n mov x5,#0 // sum\n mov x6,#0 // indice\n1:\n ldr x3,[x0,x6,lsl #3] // load a value\n mul x4,x3,x4 // compute product\n add x6,x6,#1\n cmp x6,x2\n blt 1b\n mov x6,#0\n mov x7,x0 // save entry\n mov x8,x1\n mov x9,x2\n2:\n mov x0,x4 // product\n ldr x1,[x7,x6,lsl #3] // value of n\n sdiv x2,x0,x1\n mov x0,x2 // p\n bl inverseModulo\n mul x0,x2,x0 // = product / n * invmod\n ldr x3,[x8,x6,lsl #3] // value a\n madd x5,x0,x3,x5 // sum = sum + (result1 * a)\n add x6,x6,#1\n cmp x6,x9\n blt 2b\n sdiv x1,x5,x4 // divide sum by produc\n msub x0,x1,x4,x5 // compute remainder\n100:\n ldp x8,x9,[sp],16 // restaur registers\n ldp x6,x7,[sp],16 // restaur registers\n ldp x4,x5,[sp],16 // restaur registers\n ldp x2,x3,[sp],16 // restaur registers\n ldp x1,lr,[sp],16 // restaur registers\n ret\n/***************************************************/\n/* Calcul modulo inverse */\n/***************************************************/\n/* x0 cont.quad number, x1 modulo */\n/* x0 return result */\ninverseModulo:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n stp x4,x5,[sp,-16]! // save registers\n stp x6,x7,[sp,-16]! // save registers\n mov x7,x1 // save Modulo\n mov x6,x1 // A x0=B\n mov x4,#1 // X\n mov x5,#0 // Y\n1: //\n cmp x0,#0 // B = 0\n beq 2f\n mov x1,x0 // T = B\n mov x0,x6 // A\n sdiv x2,x0,x1 // A / T\n msub x0,x2,x1,x0 // B and x2=Q\n mov x6,x1 // A=T\n mov x1,x4 // T=X\n msub x4,x2,x1,x5 // X=Y-(Q*T)\n mov x5,x1 // Y=T\n b 1b\n2:\n add x7,x7,x5 // = Y + N\n cmp x5,#0 // Y > 0\n bge 3f\n mov x0,x7\n b 100f\n3:\n mov x0,x5\n100:\n ldp x6,x7,[sp],16 // restaur registers\n ldp x4,x5,[sp],16 // restaur registers\n ldp x2,x3,[sp],16 // restaur registers\n ldp x1,lr,[sp],16 // restaur registers\n ret\n/***************************************************/\n/* display multi strings */\n/***************************************************/\n/* x0 contains number strings address */\n/* x1 address string1 */\n/* x2 address string2 */\n/* x3 address string3 */\n/* other address on the stack */\n/* thinck to add number other address * 4 to add to the stack */\ndisplayStrings: // INFO: affichageStrings\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n stp x4,x5,[sp,-16]! // save registers\n add fp,sp,#48 // save paraméters address (6 registers saved * 8 bytes)\n mov x4,x0 // save strings number\n cmp x4,#0 // 0 string -> end\n ble 100f\n mov x0,x1 // string 1\n bl affichageMess\n cmp x4,#1 // number > 1\n ble 100f\n mov x0,x2\n bl affichageMess\n cmp x4,#2\n ble 100f\n mov x0,x3\n bl affichageMess\n cmp x4,#3\n ble 100f\n mov x3,#3\n sub x2,x4,#4\n1: // loop extract address string on stack\n ldr x0,[fp,x2,lsl #3]\n bl affichageMess\n subs x2,x2,#1\n bge 1b\n100:\n ldp x4,x5,[sp],16 // restaur registers\n ldp x2,x3,[sp],16 // restaur registers\n ldp x1,lr,[sp],16 // restaur registers\n ret\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "INT FUNC MulInv(INT a,b)\n INT b0,x0,x1,q,tmp\n\n IF b=1 THEN RETURN (1) FI\n\n b0=b x0=0 x1=1\n WHILE a>1\n DO\n q=a/b\n\n tmp=b\n b=a MOD b\n a=tmp\n\n tmp=x0\n x0=x1-q*x0\n x1=tmp\n OD\n IF x1<0 THEN\n x1==+b0\n FI\nRETURN (x1)\n\nINT FUNC ChineseRemainder(BYTE ARRAY n,a BYTE len)\n INT prod,sum,p,m\n BYTE i\n\n prod=1 sum=0\n FOR i=0 TO len-1\n DO\n prod==*n(i)\n OD\n FOR i=0 TO len-1\n DO\n p=prod/n(i)\n m=MulInv(p,n(i))\n sum==+a(i)*m*p\n OD\nRETURN (sum MOD prod)\n\nPROC Main()\n BYTE ARRAY n=[3 5 7],a=[2 3 2]\n INT res\n\n res=ChineseRemainder(n,a,3)\n PrintI(res)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO, Mod_Inv;\n\nprocedure Chin_Rema is\n N: array(Positive range <>) of Positive := (3, 5, 7);\n A: array(Positive range <>) of Positive := (2, 3, 2);\n Tmp: Positive;\n Prod: Positive := 1;\n Sum: Natural := 0;\n\nbegin\n for I in N'Range loop\n Prod := Prod * N(I);\n end loop;\n\n for I in A'Range loop\n Tmp := Prod / N(I);\n Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp;\n end loop;\n Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod));\nend Chin_Rema;\n", "language": "Ada" }, { "code": "BEGIN # Chinese remainder theorewm - translated from the C sample #\n\n PROC mul inv = ( INT a in, b in )INT:\n IF b in = 1\n THEN 1\n ELSE\n INT b0 = b in;\n INT a := a in, b := b in, x0 := 0, x1 := 1;\n WHILE a > 1 DO\n IF b = 0 THEN\n print( ( \"Numbers not pairwise coprime\", newline ) ); stop\n FI;\n INT q = a OVER b;\n INT t;\n t := b; b := a MOD b; a := t;\n t := x0; x0 := x1 - q * x0; x1 := t\n OD;\n IF x1 < 0 THEN x1 + b0 ELSE x1 FI\n FI # mul inv # ;\n\n PROC chinese remainder = ( []INT n, a )INT:\n IF LWB n /= LWB a OR UPB n /= UPB a OR ( UPB a - LWB a ) + 1 < 1\n THEN print( ( \"Array bounds mismatch or empty arrays\", newline ) ); stop\n ELSE\n INT prod := 1, sum := 0;\n FOR i FROM LWB n TO UPB n DO prod *:= n[ i ] OD;\n IF prod = 0 THEN\n print( ( \"Numbers not pairwise coprime\", newline ) ); stop\n FI;\n FOR i FROM LWB n TO UPB n DO\n INT p = prod OVER n[ i ];\n sum +:= a[ i ] * mul inv( p, n[ i ] ) * p\n OD;\n sum MOD prod\n FI # chinese remainder # ;\n\n print( ( whole( chinese remainder( ( 3, 5, 7 ), ( 2, 3, 2 ) ), 0 ), newline ) )\n\nEND\n", "language": "ALGOL-68" }, { "code": "/* ARM assembly Raspberry PI or android with termux */\n/* program chineserem.s */\n\n /* REMARK 1 : this program use routines in a include file\n see task Include a file language arm assembly\n for the routine affichageMess conversion10\n see at end of this program the instruction include */\n/* for constantes see task include a file in arm assembly */\n/************************************/\n/* Constantes */\n/************************************/\n.include \"../constantes.inc\"\n\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessResult: .asciz \"Result = \"\nszCarriageReturn: .asciz \"\\n\"\n.align 2\narrayN: .int 3,5,7\narrayA: .int 2,3,2\n .equ ARRAYSIZE, (. - arrayA)/4\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\nsZoneConv: .skip 24\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain:\n ldr r0,iAdrarrayN @ N array address\n ldr r1,iAdrarrayA @ A array address\n mov r2,#ARRAYSIZE @ array size\n bl chineseremainder\n\n ldr r1,iAdrsZoneConv\n bl conversion10 @ call décimal conversion\n mov r0,#3\n ldr r1,iAdrszMessResult\n ldr r2,iAdrsZoneConv @ insert conversion in message\n ldr r3,iAdrszCarriageReturn\n bl displayStrings @ display message\n\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsZoneConv: .int sZoneConv\niAdrszMessResult: .int szMessResult\niAdrarrayA: .int arrayA\niAdrarrayN: .int arrayN\n\n/******************************************************************/\n/* compute chinese remainder */\n/******************************************************************/\n/* r0 contains n array address */\n/* r1 contains a array address */\n/* r2 contains array size */\nchineseremainder:\n push {r1-r9,lr} @ save registers\n mov r4,#1 @ product\n mov r5,#0 @ sum\n mov r6,#0 @ indice\n1:\n ldr r3,[r0,r6,lsl #2] @ load a value\n mul r4,r3,r4 @ compute product\n add r6,#1\n cmp r6,r2\n blt 1b\n mov r6,#0\n mov r7,r0 @ save entry\n mov r8,r1\n mov r9,r2\n2:\n mov r0,r4 @ product\n ldr r1,[r7,r6,lsl #2] @ value of n\n bl division\n mov r0,r2 @ p\n bl inverseModulo\n mul r0,r2,r0 @ = product / n * invmod\n ldr r3,[r8,r6,lsl #2] @ value a\n mla r5,r0,r3,r5 @ sum = sum + (result1 * a)\n add r6,#1\n cmp r6,r9\n blt 2b\n mov r0,r5 @ sum\n mov r1,r4 @ product\n bl division\n mov r0,r3\n\n100:\n pop {r1-r9,pc} @ restaur registers\n/***************************************************/\n/* Calcul modulo inverse */\n/***************************************************/\n/* r0 containt number, r1 modulo */\n/* x0 return result */\ninverseModulo:\n push {r1-r7,lr} @ save registers\n mov r7,r1 // save Modulo\n mov r6,r1 // A r0=B\n mov r4,#1 // X\n mov r5,#0 // Y\n1: //\n cmp r0,#0 // B = 0\n beq 2f\n mov r1,r0 // T = B\n mov r0,r6 // A\n bl division // A / T\n mov r0,r3 // B and r2=Q\n mov r6,r1 // A=T\n mov r1,r4 // T=X\n mls r4,r2,r1,r5 // X=Y-(Q*T)\n mov r5,r1 // Y=T\n b 1b\n2:\n add r7,r7,r5 // = Y + N\n cmp r5,#0 // Y > 0\n bge 3f\n mov r0,r7\n b 100f\n3:\n mov r0,r5\n100:\n pop {r1-r7,pc}\n/***************************************************/\n/* display multi strings */\n/***************************************************/\n/* r0 contains number strings address */\n/* r1 address string1 */\n/* r2 address string2 */\n/* r3 address string3 */\n/* other address on the stack */\n/* thinck to add number other address * 4 to add to the stack */\ndisplayStrings: @ INFO: affichageStrings\n push {r1-r4,fp,lr} @ save des registres\n add fp,sp,#24 @ save paraméters address (6 registers saved * 4 bytes)\n mov r4,r0 @ save strings number\n cmp r4,#0 @ 0 string -> end\n ble 100f\n mov r0,r1 @ string 1\n bl affichageMess\n cmp r4,#1 @ number > 1\n ble 100f\n mov r0,r2\n bl affichageMess\n cmp r4,#2\n ble 100f\n mov r0,r3\n bl affichageMess\n cmp r4,#3\n ble 100f\n mov r3,#3\n sub r2,r4,#4\n1: @ loop extract address string on stack\n ldr r0,[fp,r2,lsl #2]\n bl affichageMess\n subs r2,#1\n bge 1b\n100:\n pop {r1-r4,fp,pc}\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n.include \"../affichage.inc\"\n", "language": "ARM-Assembly" }, { "code": "mulInv: function [a0, b0][\n [a b x0]: @[a0 b0 0]\n result: 1\n if b = 1 -> return result\n while [a > 1][\n q: a / b\n a: a % b\n tmp: a\n a: b\n b: tmp\n result: result - q * x0\n tmp: x0\n x0: result\n result: tmp\n ]\n if result < 0 -> result: result + b0\n return result\n]\n\nchineseRemainder: function [N, A][\n prod: 1\n s: 0\n\n loop N 'x -> prod: prod * x\n\n loop.with:'i N 'x [\n p: prod / x\n s: s + (mulInv p x) * p * A\\[i]\n ]\n return s % prod\n]\n\nprint chineseRemainder [3 5 7] [2 3 2]\n", "language": "Arturo" }, { "code": "# Usage: GAWK -f CHINESE_REMAINDER_THEOREM.AWK\nBEGIN {\n len = split(\"3 5 7\", n)\n len = split(\"2 3 2\", a)\n printf(\"%d\\n\", chineseremainder(n, a, len))\n}\nfunction chineseremainder(n, a, len, p, i, prod, sum) {\n prod = 1\n sum = 0\n for (i = 1; i <= len; i++)\n prod *= n[i]\n for (i = 1; i <= len; i++) {\n p = prod / n[i]\n sum += a[i] * mulinv(p, n[i]) * p\n }\n return sum % prod\n}\nfunction mulinv(a, b, b0, t, q, x0, x1) {\n # returns x where (a * x) % b == 1\n b0 = b\n x0 = 0\n x1 = 1\n if (b == 1)\n return 1\n while (a > 1) {\n q = int(a / b)\n t = b\n b = a % b\n a = t\n t = x0\n x0 = x1 - q * x0\n x1 = t\n }\n if (x1 < 0)\n x1 += b0\n return x1\n}\n", "language": "AWK" }, { "code": "MulInv←⊣|·⊑{0=𝕨?1‿0;(⌽-(0⋈𝕩⌊∘÷𝕨)⊸×)𝕨𝕊˜𝕨|𝕩}\nChRem←{\n num 𝕊 rem:\n prod←×´num\n prod|+´rem×(⊢×num⊸(MulInv¨))prod⌊∘÷num\n}\n\n•Show 3‿5‿7 ChRem 2‿3‿2\n•Show 10‿4‿9 ChRem 11‿22‿19\n", "language": "BQN" }, { "code": "23\n172\n", "language": "BQN" }, { "code": "( ( mul-inv\n = a b b0 q x0 x1\n . !arg:(?a.?b:?b0)\n & ( !b:1\n | 0:?x0\n & 1:?x1\n & whl\n ' ( !a:>1\n & (!b.mod$(!a.!b):?q.!x1+-1*!q*!x0.!x0)\n : (?a.?b.?x0.?x1)\n )\n & ( !x1:<0&!b0+!x1\n | !x1\n )\n )\n )\n& ( chinese-remainder\n = n a as p ns ni prod sum\n . !arg:(?n.?a)\n & 1:?prod\n & 0:?sum\n & !n:?ns\n & whl'(!ns:%?ni ?ns&!prod*!ni:?prod)\n & !n:?ns\n & !a:?as\n & whl\n ' ( !ns:%?ni ?ns\n & !as:%?ai ?as\n & div$(!prod.!ni):?p\n & !sum+!ai*mul-inv$(!p.!ni)*!p:?sum\n )\n & mod$(!sum.!prod):?arg\n & !arg\n )\n& 3 5 7:?n\n& 2 3 2:?a\n& put$(str$(chinese-remainder$(!n.!a) \\n))\n);\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n\n// returns x where (a * x) % b == 1\nint mul_inv(int a, int b)\n{\n\tint b0 = b, t, q;\n\tint x0 = 0, x1 = 1;\n\tif (b == 1) return 1;\n\twhile (a > 1) {\n\t\tq = a / b;\n\t\tt = b, b = a % b, a = t;\n\t\tt = x0, x0 = x1 - q * x0, x1 = t;\n\t}\n\tif (x1 < 0) x1 += b0;\n\treturn x1;\n}\n\nint chinese_remainder(int *n, int *a, int len)\n{\n\tint p, i, prod = 1, sum = 0;\n\n\tfor (i = 0; i < len; i++) prod *= n[i];\n\n\tfor (i = 0; i < len; i++) {\n\t\tp = prod / n[i];\n\t\tsum += a[i] * mul_inv(p, n[i]) * p;\n\t}\n\n\treturn sum % prod;\n}\n\nint main(void)\n{\n\tint n[] = { 3, 5, 7 };\n\tint a[] = { 2, 3, 2 };\n\n\tprintf(\"%d\\n\", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));\n\treturn 0;\n}\n", "language": "C" }, { "code": "// Requires C++17\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n\n\tcout << chineseRemainder(n,a) << endl;\n\n\treturn 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Linq;\n\nnamespace ChineseRemainderTheorem\n{\n class Program\n {\n static void Main(string[] args)\n {\n int[] n = { 3, 5, 7 };\n int[] a = { 2, 3, 2 };\n\n int result = ChineseRemainderTheorem.Solve(n, a);\n\n int counter = 0;\n int maxCount = n.Length - 1;\n while (counter <= maxCount)\n {\n Console.WriteLine($\"{result} ≡ {a[counter]} (mod {n[counter]})\");\n counter++;\n }\n }\n }\n\n public static class ChineseRemainderTheorem\n {\n public static int Solve(int[] n, int[] a)\n {\n int prod = n.Aggregate(1, (i, j) => i * j);\n int p;\n int sm = 0;\n for (int i = 0; i < n.Length; i++)\n {\n p = prod / n[i];\n sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;\n }\n return sm % prod;\n }\n\n private static int ModularMultiplicativeInverse(int a, int mod)\n {\n int b = a % mod;\n for (int x = 1; x < mod; x++)\n {\n if ((b * x) % mod == 1)\n {\n return x;\n }\n }\n return 1;\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(ns test-p.core\n (:require [clojure.math.numeric-tower :as math]))\n\n(defn extended-gcd\n \"The extended Euclidean algorithm\n Returns a list containing the GCD and the Bézout coefficients\n corresponding to the inputs. \"\n [a b]\n (cond (zero? a) [(math/abs b) 0 1]\n (zero? b) [(math/abs a) 1 0]\n :else (loop [s 0\n s0 1\n t 1\n t0 0\n r (math/abs b)\n r0 (math/abs a)]\n (if (zero? r)\n [r0 s0 t0]\n (let [q (quot r0 r)]\n (recur (- s0 (* q s)) s\n (- t0 (* q t)) t\n (- r0 (* q r)) r))))))\n\n(defn chinese_remainder\n \" Main routine to return the chinese remainder \"\n [n a]\n (let [prod (apply * n)\n reducer (fn [sum [n_i a_i]]\n (let [p (quot prod n_i) ; p = prod / n_i\n egcd (extended-gcd p n_i) ; Extended gcd\n inv_p (second egcd)] ; Second item is the inverse\n (+ sum (* a_i inv_p p))))\n sum-prod (reduce reducer 0 (map vector n a))] ; Replaces the Python for loop to sum\n ; (map vector n a) is same as\n ; ; Python's version Zip (n, a)\n (mod sum-prod prod))) ; Result line\n\n(def n [3 5 7])\n(def a [2 3 2])\n\n(println (chinese_remainder n a))\n", "language": "Clojure" }, { "code": "crt = (n,a) ->\n\tsum = 0\n\tprod = n.reduce (a,c) -> a*c\n\tfor [ni,ai] in _.zip n,a\n\t\tp = prod // ni\n\t\tsum += ai * p * mulInv p,ni\n\tsum % prod\n\t\nmulInv = (a,b) ->\n\tb0 = b\n\t[x0,x1] = [0,1]\n\tif b==1 then return 1\n\twhile a > 1\n\t\tq = a // b\n\t\t[a,b] = [b, a % b]\n\t\t[x0,x1] = [x1-q*x0, x0]\n\tif x1 < 0 then x1 += b0\n\tx1\n\t\nprint crt [3,5,7], [2,3,2]\n", "language": "CoffeeScript" }, { "code": "(defun chinese-remainder (am)\n\"Calculates the Chinese Remainder for the given set of integer modulo pairs.\n Note: All the ni and the N must be coprimes.\"\n (loop :for (a . m) :in am\n :with mtot = (reduce #'* (mapcar #'(lambda(X) (cdr X)) am))\n :with sum = 0\n :finally (return (mod sum mtot))\n :do\n (incf sum (* a (invmod (/ mtot m) m) (/ mtot m)))))\n", "language": "Common-Lisp" }, { "code": "def extended_gcd(a, b)\n last_remainder, remainder = a.abs, b.abs\n x, last_x = 0, 1\n\n until remainder == 0\n tmp = remainder\n quotient, remainder = last_remainder.divmod(remainder)\n last_remainder = tmp\n x, last_x = last_x - quotient * x, x\n end\n\n return last_remainder, last_x * (a < 0 ? -1 : 1)\nend\n\n\ndef invmod(e, et)\n g, x = extended_gcd(e, et)\n unless g == 1\n raise \"Multiplicative inverse modulo does not exist\"\n end\n return x % et\nend\n\n\ndef chinese_remainder(mods, remainders)\n max = mods.product\n series = remainders.zip(mods).map { |r, m| r * max * invmod(max // m, m) // m }\n return series.sum % max\nend\n\n\nputs chinese_remainder([3, 5, 7], [2, 3, 2])\nputs chinese_remainder([5, 7, 9, 11], [1, 2, 3, 4])\n", "language": "Common-Lisp" }, { "code": "import std.stdio, std.algorithm;\n\nT chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc\nin {\n assert(n.length == a.length);\n} body {\n static T mulInv(T)(T a, T b) pure nothrow @safe @nogc {\n auto b0 = b;\n T x0 = 0, x1 = 1;\n if (b == 1)\n return T(1);\n while (a > 1) {\n immutable q = a / b;\n immutable amb = a % b;\n a = b;\n b = amb;\n immutable xqx = x1 - q * x0;\n x1 = x0;\n x0 = xqx;\n }\n if (x1 < 0)\n x1 += b0;\n return x1;\n }\n\n immutable prod = reduce!q{a * b}(T(1), n);\n\n T p = 1, sm = 0;\n foreach (immutable i, immutable ni; n) {\n p = prod / ni;\n sm += a[i] * mulInv(p, ni) * p;\n }\n return sm % prod;\n}\n\nvoid main() {\n immutable n = [3, 5, 7],\n a = [2, 3, 2];\n chineseRemainder(n, a).writeln;\n}\n", "language": "D" }, { "code": "program ChineseRemainderTheorem;\n\nuses\n System.SysUtils, Velthuis.BigIntegers;\n\nfunction mulInv(a, b: BigInteger): BigInteger;\nvar\n b0, x0, x1, q, amb, xqx: BigInteger;\nbegin\n b0 := b;\n x0 := 0;\n x1 := 1;\n\n if (b = 1) then\n exit(1);\n\n while (a > 1) do\n begin\n q := a div b;\n amb := a mod b;\n a := b;\n b := amb;\n xqx := x1 - q * x0;\n x1 := x0;\n x0 := xqx;\n end;\n\n if (x1 < 0) then\n x1 := x1 + b0;\n\n Result := x1;\nend;\n\nfunction chineseRemainder(n: TArray<BigInteger>; a: TArray<BigInteger>)\n : BigInteger;\nvar\n i: Integer;\n prod, p, sm: BigInteger;\nbegin\n prod := 1;\n\n for i := 0 to High(n) do\n prod := prod * n[i];\n\n p := 0;\n sm := 0;\n\n for i := 0 to High(n) do\n begin\n p := prod div n[i];\n sm := sm + a[i] * mulInv(p, n[i]) * p;\n end;\n Result := sm mod prod;\nend;\n\nvar\n n, a: TArray<BigInteger>;\n\nbegin\n n := [3, 5, 7];\n a := [2, 3, 2];\n\n Writeln(chineseRemainder(n, a).ToString);\nend.\n", "language": "Delphi" }, { "code": "func mul_inv a b .\n b0 = b\n x1 = 1\n if b <> 1\n while a > 1\n q = a div b\n t = b\n b = a mod b\n a = t\n t = x0\n x0 = x1 - q * x0\n x1 = t\n .\n if x1 < 0\n x1 += b0\n .\n .\n return x1\n.\nproc remainder . n[] a[] r .\n prod = 1\n sum = 0\n for i = 1 to len n[]\n prod *= n[i]\n .\n for i = 1 to len n[]\n p = prod / n[i]\n sum += a[i] * (mul_inv p n[i]) * p\n r = sum mod prod\n .\n.\nn[] = [ 3 5 7 ]\na[] = [ 2 3 2 ]\nremainder n[] a[] h\nprint h\n", "language": "EasyLang" }, { "code": "(lib 'math)\nmath.lib v1.10 ® EchoLisp\nLib: math.lib loaded.\n\n(crt-solve '(2 3 2) '(3 5 7))\n → 23\n(crt-solve '(2 3 2) '(7 1005 15))\n💥 error: mod[i] must be co-primes : assertion failed : 1005\n", "language": "EchoLisp" }, { "code": "defmodule Chinese do\n def remainder(mods, remainders) do\n max = Enum.reduce(mods, fn x,acc -> x*acc end)\n Enum.zip(mods, remainders)\n |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end)\n |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end)\n |> MapSet.to_list\n end\nend\n\nIO.inspect Chinese.remainder([3,5,7], [2,3,2])\nIO.inspect Chinese.remainder([10,4,9], [11,22,19])\nIO.inspect Chinese.remainder([11,12,13], [10,4,12])\n", "language": "Elixir" }, { "code": "-module(crt).\n-import(lists, [zip/2, unzip/1, foldl/3, sum/1]).\n-export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]).\n\negcd(_, 0) -> {1, 0};\negcd(A, B) ->\n {S, T} = egcd(B, A rem B),\n {T, S - (A div B)*T}.\n\nmod_inv(A, B) ->\n {X, Y} = egcd(A, B),\n if\n A*X + B*Y =:= 1 -> X;\n true -> undefined\n end.\n\nmod(A, M) ->\n X = A rem M,\n if\n X < 0 -> X + M;\n true -> X\n end.\n\ncalc_inverses([], []) -> [];\ncalc_inverses([N | Ns], [M | Ms]) ->\n case mod_inv(N, M) of\n undefined -> undefined;\n Inv -> [Inv | calc_inverses(Ns, Ms)]\n end.\n\nchinese_remainder(Congruences) ->\n {Residues, Modulii} = unzip(Congruences),\n ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii),\n CRT_Modulii = [ModPI div M || M <- Modulii],\n case calc_inverses(CRT_Modulii, Modulii) of\n undefined -> undefined;\n Inverses ->\n Solution = sum([A*B || {A,B} <- zip(CRT_Modulii,\n [A*B || {A,B} <- zip(Residues, Inverses)])]),\n mod(Solution, ModPI)\n end.\n", "language": "Erlang" }, { "code": "let rec sieve cs x N =\n match cs with\n | [] -> Some(x)\n | (a,n)::rest ->\n let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x\n let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n)\n match firstXmodNequalA (Seq.take n arrProgress) with\n | None -> None\n | Some(x) -> sieve rest x (N*n)\n\n[ [(2,3);(3,5);(2,7)];\n [(10,11); (4,22); (9,19)];\n [(10,11); (4,12); (12,13)] ]\n|> List.iter (fun congruences ->\n let cs =\n congruences\n |> List.map (fun (a,n) -> (a % n, n))\n |> List.sortBy (snd>>(~-))\n let an = List.head cs\n match sieve (List.tail cs) (fst an) (snd an) with\n | None -> printfn \"no solution\"\n | Some(x) -> printfn \"result = %i\" x\n)\n", "language": "F-Sharp" }, { "code": "//Chinese Division Theorem: Nigel Galloway: April 3rd., 2017\nlet CD n g =\n match Seq.fold(fun n g->if (gcd n g)=1 then n*g else 0) 1 g with\n |0 -> None\n |fN-> Some ((Seq.fold2(fun n i g -> n+i*(fN/g)*(MI g ((fN/g)%g))) 0 n g)%fN)\n", "language": "F-Sharp" }, { "code": "USING: math.algebra prettyprint ;\n{ 2 3 2 } { 3 5 7 } chinese-remainder .\n", "language": "Factor" }, { "code": ": egcd ( a b -- a b )\n dup 0= IF\n 2drop 1 0\n ELSE\n dup -rot /mod \\ -- b r=a%b q=a/b\n -rot recurse \\ -- q (s,t) = egcd(b, r)\n >r swap r@ * - r> swap \\ -- t (s - q*t)\n THEN ;\n\n: egcd>gcd ( a b x y -- n ) \\ calculate gcd from egcd\n rot * -rot * + ;\n\n: mod-inv ( a m -- a' ) \\ modular inverse with coprime check\n 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ;\n\n: array-product ( adr count -- n )\n 1 -rot cells bounds ?DO i @ * cell +LOOP ;\n\n: crt-from-array ( adr1 adr2 count -- n )\n 2dup array-product locals| M count m[] a[] |\n 0 \\ result\n count 0 DO\n m[] i cells + @\n dup M swap /\n dup rot mod-inv *\n a[] i cells + @ * +\n LOOP M mod ;\n\ncreate crt-residues[] 10 cells allot\ncreate crt-moduli[] 10 cells allot\n\n: crt ( .... n -- n ) \\ takes pairs of \"n (mod m)\" from stack.\n 10 min locals| n |\n n 0 DO\n crt-moduli[] i cells + !\n crt-residues[] i cells + !\n LOOP\n crt-residues[] crt-moduli[] n crt-from-array ;\n", "language": "Forth" }, { "code": "* RC task: use the Chinese Remainder Theorem to solve a system of congruences.\n\n FUNCTION crt(n, residues, moduli)\n IMPLICIT INTEGER (A-Z)\n DIMENSION residues(n), moduli(n)\n\n p = product(moduli)\n crt = 0\n DO 10 i = 1, n\n m = p/moduli(i)\n CALL egcd(moduli(i), m, r, s, gcd)\n IF (gcd .ne. 1) GO TO 20 ! error exit\n10 crt = crt + residues(i)*s*m\n crt = modulo(crt, p)\n RETURN\n\n20 crt = -1 ! will never be negative, so flag an error\n END\n\n\n* Compute egcd(a, b), returning x, y, g s.t.\n* g = gcd(a, b) and a*x + b*y = g\n*\n SUBROUTINE egcd(a, b, x, y, g)\n IMPLICIT INTEGER (A-Z)\n\n g = a\n u = 0\n v = 1\n w = b\n x = 1\n y = 0\n\n1 IF (w .eq. 0) RETURN\n q = g/w\n u next = x - q*u\n v next = y - q*v\n w next = g - q*w\n x = u\n y = v\n g = w\n u = u next\n v = v next\n w = w next\n GO TO 1\n END\n\n\n PROGRAM Chinese Remainder\n IMPLICIT INTEGER (A-Z)\n\n PRINT *, crt(3, [2, 3, 2], [3, 5, 7])\n PRINT *, crt(3, [2, 3, 2], [3, 6, 7]) ! no solution\n\n END\n", "language": "Fortran" }, { "code": "#include \"gcd.bas\"\nfunction mul_inv( a as integer, b as integer ) as integer\n\tif b = 1 then return 1\n for i as integer = 1 to b\n if a*i mod b = 1 then return i\n next i\n return 0\nend function\n\nfunction chinese_remainder(n() as integer, a() as integer) as integer\n\tdim as integer p, i, prod = 1, sum = 0, ln = ubound(n)\n\tfor p = 0 to ln-1\n\t for i = p+1 to ln\n\t if gcd(n(i), n(p))>1 then\n\t print \"N not coprime\"\n\t end\n\t end if\n\t next i\n\tnext p\n\tfor i = 0 to ln\n\t prod *= n(i)\n\tnext i\n\tfor i = 0 to ln\n\t p = prod/n(i)\n\t sum += a(i) * mul_inv(p, n(i))*p\n\tnext i\n\treturn sum mod prod\nend function\n\ndim as integer n(0 to 2) = { 3, 5, 7 }\ndim as integer a(0 to 2) = { 2, 3, 2 }\n\nprint chinese_remainder(n(), a())\n", "language": "FreeBASIC" }, { "code": "/** arguments:\n [r, m, d=0] where r and m are arrays of the remainder terms r and the\n modulus terms m respectively. These must be of the same length.\n returns\n x, the unique solution mod N where N is the product of all the M terms where x &gt;= d.\n*/\nChineseRemainder[r, m, d=0] :=\n{\n if length[r] != length[m]\n {\n println[\"ChineseRemainder: r and m must be arrays of the same length.\"]\n return undef\n }\n\n N = product[m]\n\n y = new array\n z = new array\n x = 0\n for i = rangeOf[m]\n {\n y@i = N / m@i\n z@i = modInverse[y@i, m@i]\n if z@i == undef\n {\n println[\"ChineseRemainder: modInverse returned undef for modInverse[\" + y@i + \", \" + m@i + \"]\"]\n return undef\n }\n\n x = x + r@i y@i z@i\n }\n\n xp = x mod N\n f = d div N\n r = f * N + xp\n if r < d\n r = r + N\n\n return r\n}\n\nprintln[ChineseRemainder[[2,3,2],[3,5,7]] ]\n", "language": "Frink" }, { "code": "import integers.modinv\n\ndef crt( congruences ) =\n N = product( n | (_, n) <- congruences )\n sum( a*modinv(N/n, n)*N/n | (a, n) <- congruences ) mod N\n\nprintln( crt([(2, 3), (3, 5), (2, 7)]) )\n", "language": "FunL" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n p := new(big.Int).Set(n[0])\n for _, n1 := range n[1:] {\n p.Mul(p, n1)\n }\n var x, q, s, z big.Int\n for i, n1 := range n {\n q.Div(p, n1)\n z.GCD(nil, &s, n1, &q)\n if z.Cmp(one) != 0 {\n return nil, fmt.Errorf(\"%d not coprime\", n1)\n }\n x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n }\n return x.Mod(&x, p), nil\n}\n\nfunc main() {\n n := []*big.Int{\n big.NewInt(3),\n big.NewInt(5),\n big.NewInt(7),\n }\n a := []*big.Int{\n big.NewInt(2),\n big.NewInt(3),\n big.NewInt(2),\n }\n fmt.Println(crt(a, n))\n}\n", "language": "Go" }, { "code": "class ChineseRemainderTheorem {\n static int chineseRemainder(int[] n, int[] a) {\n int prod = 1\n for (int i = 0; i < n.length; i++) {\n prod *= n[i]\n }\n\n int p, sm = 0\n for (int i = 0; i < n.length; i++) {\n p = prod.intdiv(n[i])\n sm += a[i] * mulInv(p, n[i]) * p\n }\n return sm % prod\n }\n\n private static int mulInv(int a, int b) {\n int b0 = b\n int x0 = 0\n int x1 = 1\n\n if (b == 1) {\n return 1\n }\n\n while (a > 1) {\n int q = a.intdiv(b)\n int amb = a % b\n a = b\n b = amb\n int xqx = x1 - q * x0\n x1 = x0\n x0 = xqx\n }\n\n if (x1 < 0) {\n x1 += b0\n }\n\n return x1\n }\n\n static void main(String[] args) {\n int[] n = [3, 5, 7]\n int[] a = [2, 3, 2]\n println(chineseRemainder(n, a))\n }\n}\n", "language": "Groovy" }, { "code": "import Control.Monad (zipWithM)\n\negcd :: Int -> Int -> (Int, Int)\negcd _ 0 = (1, 0)\negcd a b = (t, s - q * t)\n where\n (s, t) = egcd b r\n (q, r) = a `quotRem` b\n\nmodInv :: Int -> Int -> Either String Int\nmodInv a b =\n case egcd a b of\n (x, y)\n | a * x + b * y == 1 -> Right x\n | otherwise ->\n Left $ \"No modular inverse for \" ++ show a ++ \" and \" ++ show b\n\nchineseRemainder :: [Int] -> [Int] -> Either String Int\nchineseRemainder residues modulii =\n zipWithM modInv crtModulii modulii >>=\n (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues)\n where\n modPI = product modulii\n crtModulii = (modPI `div`) <$> modulii\n\nmain :: IO ()\nmain =\n mapM_ (putStrLn . either id show) $\n uncurry chineseRemainder <$>\n [ ([10, 4, 12], [11, 12, 13])\n , ([10, 4, 9], [11, 22, 19])\n , ([2, 3, 2], [3, 5, 7])\n ]\n", "language": "Haskell" }, { "code": "link numbers # for gcd()\n\nprocedure main()\n write(cr([3,5,7],[2,3,2]) | \"No solution!\")\n write(cr([10,4,9],[11,22,19]) | \"No solution!\")\nend\n\nprocedure cr(n,a)\n if 1 ~= gcd(n[i := !*n],a[i]) then fail # Not pairwise coprime\n (prod := 1, sm := 0)\n every prod *:= !n\n every p := prod/(ni := n[i := !*n]) do sm +:= a[i] * mul_inv(p,ni) * p\n return sm%prod\nend\n\nprocedure mul_inv(a,b)\n if b = 1 then return 1\n (b0 := b, x0 := 0, x1 := 1)\n while q := (1 < a)/b do {\n (t := a, a := b, b := t%b)\n (t := x0, x0 := x1-q*t, x1 := t)\n }\n return if x1 < 0 then x1+b0 else x1\nend\n", "language": "Icon" }, { "code": " crt =: (1 + ] - {:@:[ -: {.@:[ | ])^:_&0@:,:\n", "language": "J" }, { "code": " 3 5 7 crt 2 3 2\n23\n 11 12 13 crt 10 4 12\n1000\n", "language": "J" }, { "code": "import static java.util.Arrays.stream;\n\npublic class ChineseRemainderTheorem {\n\n public static int chineseRemainder(int[] n, int[] a) {\n\n int prod = stream(n).reduce(1, (i, j) -> i * j);\n\n int p, sm = 0;\n for (int i = 0; i < n.length; i++) {\n p = prod / n[i];\n sm += a[i] * mulInv(p, n[i]) * p;\n }\n return sm % prod;\n }\n\n private static int mulInv(int a, int b) {\n int b0 = b;\n int x0 = 0;\n int x1 = 1;\n\n if (b == 1)\n return 1;\n\n while (a > 1) {\n int q = a / b;\n int amb = a % b;\n a = b;\n b = amb;\n int xqx = x1 - q * x0;\n x1 = x0;\n x0 = xqx;\n }\n\n if (x1 < 0)\n x1 += b0;\n\n return x1;\n }\n\n public static void main(String[] args) {\n int[] n = {3, 5, 7};\n int[] a = {2, 3, 2};\n System.out.println(chineseRemainder(n, a));\n }\n}\n", "language": "Java" }, { "code": "function crt(num, rem) {\n let sum = 0;\n const prod = num.reduce((a, c) => a * c, 1);\n\n for (let i = 0; i < num.length; i++) {\n const [ni, ri] = [num[i], rem[i]];\n const p = Math.floor(prod / ni);\n sum += ri * p * mulInv(p, ni);\n }\n return sum % prod;\n}\n\nfunction mulInv(a, b) {\n const b0 = b;\n let [x0, x1] = [0, 1];\n\n if (b === 1) {\n return 1;\n }\n while (a > 1) {\n const q = Math.floor(a / b);\n [a, b] = [b, a % b];\n [x0, x1] = [x1 - q * x0, x0];\n }\n if (x1 < 0) {\n x1 += b0;\n }\n return x1;\n}\n\nconsole.log(crt([3,5,7], [2,3,2]))\n", "language": "JavaScript" }, { "code": "# mul_inv(a;b) returns x where (a * x) % b == 1, or else null\ndef mul_inv(a; b):\n\n # state: [a, b, x0, x1]\n def iterate:\n .[0] as $a | .[1] as $b\n | if $a > 1 then\n if $b == 0 then null\n else ($a / $b | floor) as $q\n | [$b, ($a % $b), (.[3] - ($q * .[2])), .[2]] | iterate\n end\n else .\n end ;\n\n if (b == 1) then 1\n else [a,b,0,1] | iterate\n | if . == null then .\n else .[3] | if . < 0 then . + b else . end\n end\n end;\n\ndef chinese_remainder(mods; remainders):\n (reduce mods[] as $i (1; . * $i)) as $prod\n | reduce range(0; mods|length) as $i\n (0;\n ($prod/mods[$i]) as $p\n | mul_inv($p; mods[$i]) as $mi\n | if $mi == null then error(\"nogo: p=\\($p) mods[\\($i)]=\\(mods[$i])\")\n else . + (remainders[$i] * $mi * $p)\n end )\n | . % $prod ;\n", "language": "Jq" }, { "code": "function chineseremainder(n::Array, a::Array)\n Π = prod(n)\n mod(sum(ai * invmod(Π ÷ ni, ni) * (Π ÷ ni) for (ni, ai) in zip(n, a)), Π)\nend\n\n@show chineseremainder([3, 5, 7], [2, 3, 2])\n", "language": "Julia" }, { "code": "// version 1.1.2\n\n/* returns x where (a * x) % b == 1 */\nfun multInv(a: Int, b: Int): Int {\n if (b == 1) return 1\n var aa = a\n var bb = b\n var x0 = 0\n var x1 = 1\n while (aa > 1) {\n val q = aa / bb\n var t = bb\n bb = aa % bb\n aa = t\n t = x0\n x0 = x1 - q * x0\n x1 = t\n }\n if (x1 < 0) x1 += b\n return x1\n}\n\nfun chineseRemainder(n: IntArray, a: IntArray): Int {\n val prod = n.fold(1) { acc, i -> acc * i }\n var sum = 0\n for (i in 0 until n.size) {\n val p = prod / n[i]\n sum += a[i] * multInv(p, n[i]) * p\n }\n return sum % prod\n}\n\nfun main(args: Array<String>) {\n val n = intArrayOf(3, 5, 7)\n val a = intArrayOf(2, 3, 2)\n println(chineseRemainder(n, a))\n}\n", "language": "Kotlin" }, { "code": "import std\n\ndef extended_gcd(a, b):\n var s = 0\n var old_s = 1\n var t = 1\n var old_t = 0\n var r = b\n var old_r = a\n\n while r != 0:\n let quotient = old_r / r\n old_r, r = r, old_r - quotient * r\n old_s, s = s, old_s - quotient * s\n old_t, t = t, old_t - quotient * t\n\n return old_r, old_s, old_t, t, s\n\ndef for2(xs, ys, fun): return for xs.length: fun(xs[_], ys[_])\n\ndef crt(xs, ys):\n let p = reduce(xs): _a * _b\n var r = 0\n for2(xs,ys) x, y:\n let q = p / x\n let z,s,_t,_qt,_qs = q.extended_gcd(x)\n if z != 1:\n return \"ng \" + x + \" not coprime\", 0\n if s < 0: r += y * (s + x) * q\n else: r += y * s * q\n return \"ok\", r % p\n\n\ndef print_crt(xs, ys):\n let msg, res = crt(xs, ys)\n print(msg + \" \" + res)\n\nprint_crt([3,5,7],[2,3,2])\nprint_crt([11,12,13],[10,4,12])\nprint_crt([11,22,19],[10,4,9])\nprint_crt([100,23],[19,0])\n", "language": "Lobster" }, { "code": "-- Taken from https://www.rosettacode.org/wiki/Sum_and_product_of_an_array#Lua\nfunction prodf(a, ...) return a and a * prodf(...) or 1 end\nfunction prodt(t) return prodf(unpack(t)) end\n\nfunction mulInv(a, b)\n local b0 = b\n local x0 = 0\n local x1 = 1\n\n if b == 1 then\n return 1\n end\n\n while a > 1 do\n local q = math.floor(a / b)\n local amb = math.fmod(a, b)\n a = b\n b = amb\n local xqx = x1 - q * x0\n x1 = x0\n x0 = xqx\n end\n\n if x1 < 0 then\n x1 = x1 + b0\n end\n\n return x1\nend\n\nfunction chineseRemainder(n, a)\n local prod = prodt(n)\n\n local p\n local sm = 0\n for i=1,#n do\n p = prod / n[i]\n sm = sm + a[i] * mulInv(p, n[i]) * p\n end\n\n return math.fmod(sm, prod)\nend\n\nn = {3, 5, 7}\na = {2, 3, 2}\nio.write(chineseRemainder(n, a))\n", "language": "Lua" }, { "code": "Function ChineseRemainder(n(), a()) {\n\tFunction mul_inv(a, b) {\n\t\tif b==1 then =1 : exit\n\t\tb0=b\n\t\tx1=1 : x0=0\n\t\twhile a>1\n\t\t\tq=a div b\n\t\t\tt=b : b=a mod b: a=t\n\t\t\tt=x0: x0=x1-q*x0:x1=t\n\t\tend while\n\t\tif x1<0 then x1+=b0\n\t\t=x1\n\t}\n\tdef p, i, prod=1, sum\n\tfor i=0 to len(n())-1 {prod*=n(i)}\n\tfor i=0 to len(a())-1\n\t\tp=prod div n(i)\n\t\tsum+=a(i)*mul_inv(p, n(i))*p\n\tnext\n\t=sum mod prod\n}\nPrint ChineseRemainder((3,5,7), (2,3,2))\n", "language": "M2000-Interpreter" }, { "code": "> chrem( [2, 3, 2], [3, 5, 7] );\n 23\n", "language": "Maple" }, { "code": "ChineseRemainder[{2, 3, 2}, {3, 5, 7}]\n23\n", "language": "Mathematica" }, { "code": "function f = chineseRemainder(r, m)\n s = prod(m) ./ m;\n [~, t] = gcd(s, m);\n f = s .* t * r';\n", "language": "MATLAB" }, { "code": ">> chineseRemainder([2 3 2], [3 5 7])\n ans = 23\n", "language": "MATLAB" }, { "code": "/* Function that checks pairwise coprimality */\ncheck_pwc(lst):=block(\nsublist(cartesian_product_list(makelist(i,i,length(lst)),makelist(i,i,length(lst))),lambda([x],x[1]#x[2])),\n makelist([lst[%%[i][1]],lst[%%[i][2]]],i,length(%%)),\n makelist(apply('gcd,%%[i]),i,length(%%)),\n if length(unique(%%))=1 and first(unique(%%))=1 then true)$\n\n/* Chinese remainder function */\nc_remainder(A,N):=if check_pwc(N)=false then \"chinese remainder theorem not applicable\" else block(\n cn:apply(\"*\",N),\n makelist(gcdex(cn/N[i],N[i]),i,1,length(N)),\n makelist(A[i]*%%[i][1]*cn/N[i],i,1,length(N)),\n apply(\"+\",%%),\n mod(%%,cn));\nAlis:[2,3,2]$\nNlis:[3,5,7]$\nc_remainder(Alis,Nlis);\n", "language": "Maxima" }, { "code": "MODULE CRT;\nFROM FormatString IMPORT FormatString;\nFROM Terminal IMPORT WriteString,WriteLn,ReadChar;\n\nPROCEDURE WriteInt(n : INTEGER);\nVAR buf : ARRAY[0..15] OF CHAR;\nBEGIN\n FormatString(\"%i\", buf, n);\n WriteString(buf)\nEND WriteInt;\n\nPROCEDURE MulInv(a,b : INTEGER) : INTEGER;\nVAR\n b0,x0,x1,q,amb,xqx : INTEGER;\nBEGIN\n b0 := b;\n x0 := 0;\n x1 := 1;\n\n IF b=1 THEN\n RETURN 1\n END;\n\n WHILE a>1 DO\n q := a DIV b;\n amb := a MOD b;\n a := b;\n b := amb;\n xqx := x1 - q * x0;\n x1 := x0;\n x0 := xqx\n END;\n\n IF x1<0 THEN\n x1 := x1 + b0\n END;\n\n RETURN x1\nEND MulInv;\n\nPROCEDURE ChineseRemainder(n,a : ARRAY OF INTEGER) : INTEGER;\nVAR\n i : CARDINAL;\n prod,p,sm : INTEGER;\nBEGIN\n prod := n[0];\n FOR i:=1 TO HIGH(n) DO\n prod := prod * n[i]\n END;\n\n sm := 0;\n FOR i:=0 TO HIGH(n) DO\n p := prod DIV n[i];\n sm := sm + a[i] * MulInv(p, n[i]) * p\n END;\n\n RETURN sm MOD prod\nEND ChineseRemainder;\n\nTYPE TA = ARRAY[0..2] OF INTEGER;\nVAR n,a : TA;\nBEGIN\n n := TA{3, 5, 7};\n a := TA{2, 3, 2};\n WriteInt(ChineseRemainder(n, a));\n WriteLn;\n\n ReadChar\nEND CRT.\n", "language": "Modula-2" }, { "code": "proc mulInv(a0, b0: int): int =\n var (a, b, x0) = (a0, b0, 0)\n result = 1\n if b == 1: return\n while a > 1:\n let q = a div b\n a = a mod b\n swap a, b\n result = result - q * x0\n swap x0, result\n if result < 0: result += b0\n\nproc chineseRemainder[T](n, a: T): int =\n var prod = 1\n var sum = 0\n for x in n: prod *= x\n\n for i in 0..<n.len:\n let p = prod div n[i]\n sum += a[i] * mulInv(p, n[i]) * p\n\n sum mod prod\n\necho chineseRemainder([3,5,7], [2,3,2])\n", "language": "Nim" }, { "code": "exception Modular_inverse\nlet inverse_mod a = function\n | 1 -> 1\n | b -> let rec inner a b x0 x1 =\n if a <= 1 then x1\n else if b = 0 then raise Modular_inverse\n else inner b (a mod b) (x1 - (a / b) * x0) x0 in\n let x = inner a b 0 1 in\n if x < 0 then x + b else x\n\nlet chinese_remainder_exn congruences =\n let mtot = congruences\n |> List.map (fun (_, x) -> x)\n |> List.fold_left ( *) 1 in\n (List.fold_left (fun acc (r, n) ->\n acc + r * inverse_mod (mtot / n) n * (mtot / n)\n ) 0 congruences)\n mod mtot\n\nlet chinese_remainder congruences =\n try Some (chinese_remainder_exn congruences)\n with modular_inverse -> None\n", "language": "OCaml" }, { "code": "open Core.Std\nopen Option.Monad_infix\n\nlet rec egcd a b =\n if b = 0 then (1, 0)\n else\n let q = a/b and r = a mod b in\n let (s, t) = egcd b r in\n (t, s - q*t)\n\n\nlet mod_inv a b =\n let (x, y) = egcd a b in\n if a*x + b*y = 1 then Some x else None\n\n\nlet calc_inverses ns ms =\n let rec list_inverses ns ms l =\n match (ns, ms) with\n | ([], []) -> Some l\n | ([], _)\n | (_, []) -> assert false\n | (n::ns, m::ms) ->\n let inv = mod_inv n m in\n match inv with\n | None -> None\n | Some v -> list_inverses ns ms (v::l)\n in\n list_inverses ns ms [] >>= fun l -> Some (List.rev l)\n\n\nlet chinese_remainder congruences =\n let (residues, modulii) = List.unzip congruences in\n let mod_pi = List.reduce_exn modulii ~f:( * ) in\n let crt_modulii = List.map modulii ~f:(fun m -> mod_pi / m) in\n calc_inverses crt_modulii modulii >>=\n fun inverses ->\n Some (List.map3_exn residues inverses crt_modulii ~f:(fun a b c -> a*b*c)\n |> List.reduce_exn ~f:(+)\n |> fun n -> let n' = n mod mod_pi in if n' < 0 then n' + mod_pi else n')\n", "language": "OCaml" }, { "code": "chivec(residues, moduli)={\n my(m=Mod(0,1));\n for(i=1,#residues,\n m=chinese(Mod(residues[i],moduli[i]),m)\n );\n lift(m)\n};\nchivec([2,3,2], [3,5,7])\n", "language": "PARI-GP" }, { "code": "lift( chinese([Mod(2,3),Mod(3,5),Mod(2,7)]) )\n", "language": "PARI-GP" }, { "code": "chivec(residues,moduli)={\n lift(chinese(vector(#residues,i,Mod(residues[i],moduli[i]))))\n}\n", "language": "PARI-GP" }, { "code": "// Rosetta Code task \"Chinese remainder theorem\".\nprogram ChineseRemThm;\nuses SysUtils;\ntype TIntArray = array of integer;\n\n// Defining EXTRA adds optional explanatory code\n{$DEFINE EXTRA}\n\n// Return (if possible) a residue res_out that satifies\n// res_out = res1 modulo mod1, res_out = res2 modulo mod2.\n// Return mod_out = LCM( mod1, mod2), or mod_out = 0 if there's no solution.\nprocedure Solve2( const res1, res2, mod1, mod2 : integer;\n out res_out, mod_out : integer);\nvar\n a, c, d, k, m, m1, m2, r, temp : integer;\n p, p_prev : integer;\n{$IFDEF EXTRA}\n q, q_prev : integer;\n{$ENDIF}\nbegin\n if (mod1 = 0) or (mod2 = 0) then\n raise SysUtils.Exception.Create( 'Solve2: Modulus cannot be 0');\n m1 := Abs( mod1);\n m2 := Abs( mod2);\n // Extended Euclid's algorithm for HCF( m1, m2), except that only one\n // of the Bezout coefficients is needed (here p, could have used q)\n c := m1; d := m2;\n p :=0; p_prev := 1;\n{$IFDEF EXTRA}\n q := 1; q_prev := 0;\n{$ENDIF}\n a := 0;\n while (d > 0) do begin\n temp := p_prev - a*p; p_prev := p; p := temp;\n {$IFDEF EXTRA}\n temp := q_prev - a*q; q_prev := q; q := temp;\n {$ENDIF}\n a := c div d;\n temp := c - a*d; c := d; d := temp;\n end;\n // Here with c = HCF( m1, m2)\n{$IFDEF EXTRA}\n Assert( c = p*m2 + q*m1); // p and q are the Bezout coefficients\n{$ENDIF}\n // A soution exists iff c divides (res2 - res1)\n k := (res2 - res1) div c;\n if res2 - res1 <> k*c then begin\n res_out := 0; mod_out := 0; // indicate that there's no xolution\n end\n else begin\n m := (m1 div c) * m2; // m := LCM( m1, m2)\n r:= res2 - k*p*m2; // r := a solution modulo m\n{$IFDEF EXTRA}\n Assert( r = res1 + k*q*m1); // alternative formula in terms of q\n{$ENDIF}\n // Return the solution in the range 0..(m - 1)\n // Don't trust the compiler with a negative argument to mod\n if (r >= 0) then r := r mod m\n else begin\n r := (-r) mod m;\n if (r > 0) then r := m - r;\n end;\n res_out := r; mod_out := m;\n end;\nend;\n\n// Return (if possible) a residue res_out that satifies\n// res_out = res_array[j] modulo mod_array[j], for j = 0..High(res_array).\n// Return mod_out = LCM of the moduli, or mod_out = 0 if there's no solution.\nprocedure SolveMulti( const res_array, mod_array : TIntArray;\n out res_out, mod_out : integer);\nvar\n count, k, m, r : integer;\nbegin\n count := Length( mod_array);\n if count <> Length( res_array) then\n raise SysUtils.Exception.Create( 'Arrays are different sizes')\n else if count = 0 then\n raise SysUtils.Exception.Create( 'Arrays are empty');\n k := 1;\n m := mod_array[0]; r := res_array[0];\n while (k < count) and (m > 0) do begin\n Solve2( r, res_array[k], m, mod_array[k], r, m);\n inc(k);\n end;\n res_out := r; mod_out := m;\nend;\n\n// Cosmetic to turn an integer array into a string for printout.\nfunction ArrayToString( a : TIntArray) : string;\nvar\n j : integer;\nbegin\n result := '[';\n for j := 0 to High(a) do begin\n result := result + SysUtils.IntToStr(a[j]);\n if j < High(a) then result := result + ', '\n else result := result + ']';\n end;\nend;\n\n// For the passed-in res_array and mod_array, show the solution\n// found by SolveMulti (above), or state that there's no solution.\nprocedure ShowSolution( const res_array, mod_array : TIntArray);\nvar\n mod_out, res_out : integer;\nbegin\n SolveMulti( res_array, mod_array, res_out, mod_out);\n Write( ArrayToString( res_array) + ' mod '\n + ArrayToString( mod_array) + ' --> ');\n if mod_out = 0 then\n WriteLn( 'No solution')\n else\n WriteLn( SysUtils.Format( '%d mod %d', [res_out, mod_out]));\nend;\n\n// Main routine. Examples for Rosetta Code task.\nbegin\n ShowSolution([2, 3, 2], [3, 5, 7]);\n ShowSolution([3, 5, 7], [2, 3, 2]);\n ShowSolution([10, 4, 12], [11, 12, 13]);\n ShowSolution([1, 2, 3, 4], [5, 7, 9, 11]);\n ShowSolution([11, 22, 19], [10, 4, 9]);\n ShowSolution([2328, 410], [16256, 5418]);\n ShowSolution([19, 0], [100, 23]);\nend.\n", "language": "Pascal" }, { "code": "use ntheory qw/chinese/;\nsay chinese([2,3], [3,5], [2,7]);\n", "language": "Perl" }, { "code": "use Math::ModInt qw(mod);\nuse Math::ModInt::ChineseRemainder qw(cr_combine);\nsay cr_combine(mod(2,3),mod(3,5),mod(2,7));\n", "language": "Perl" }, { "code": "use ntheory qw/chinese lcm/;\nsay chinese( [2328,16256], [410,5418] ), \" mod \", lcm(16256,5418);\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">mul_inv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(-</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">;</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">nr</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">q</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">nr</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nt</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">nt</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">q</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">nt</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nr</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">nr</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">q</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">nr</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #008000;\">\"a is not invertible\"</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">t</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">chinese_remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">prod</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">tot</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">;</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #000000;\">prod</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">prod</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">];</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">mul_inv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #004080;\">string</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #008000;\">\"fail\"</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">tot</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">;</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tot</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">prod</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">chinese_remainder</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">chinese_remainder</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">13</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">chinese_remainder</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">22</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">19</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">chinese_remainder</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">23</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">19</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "(de modinv (A B)\n (let (B0 B X0 0 X1 1 Q 0 T1 0)\n (while (< 1 A)\n (setq\n Q (/ A B)\n T1 B\n B (% A B)\n A T1\n T1 X0\n X0 (- X1 (* Q X0))\n X1 T1 ) )\n (if (lt0 X1) (+ X1 B0) X1) ) )\n\n(de chinrem (N A)\n (let P (apply * N)\n (%\n (sum\n '((N A)\n (setq T1 (/ P N))\n (* A (modinv T1 N) T1) )\n N\n A )\n P ) ) )\n\n(println\n (chinrem (3 5 7) (2 3 2))\n (chinrem (11 12 13) (10 4 12)) )\n\n(bye)\n", "language": "PicoLisp" }, { "code": "product(A, B, C) :- C is A*B.\n\npair(X, Y, X-Y).\n\negcd(_, 0, 1, 0) :- !.\negcd(A, B, X, Y) :-\n divmod(A, B, Q, R),\n egcd(B, R, S, X),\n Y is S - Q*X.\n\nmodinv(A, B, X) :-\n egcd(A, B, X, Y),\n A*X + B*Y =:= 1.\n\ncrt_fold(A, M, P, R0, R1) :- % system of equations of (x = a) (mod m); p = M/m\n modinv(P, M, Inv),\n R1 is R0 + A*Inv*P.\n\ncrt(Pairs, N) :-\n maplist(pair, As, Ms, Pairs),\n foldl(product, Ms, 1, M),\n maplist(divmod(M), Ms, Ps, _), % p(n) <- M/m(n)\n foldl(crt_fold, As, Ms, Ps, 0, N0),\n N is N0 mod M.\n", "language": "Prolog" }, { "code": "/* Chinese remainder Theorem: Input chinrest([2,3,2], [3,5,7], R). -----> R == 23\n or chinrest([2,3], [5,13], R). ---------> R == 42\n Written along the lines of \"Introduction to Algorithms\" by\n Thomas Cormen\n Charles Leiserson\n Ronald Rivest\ncompiled with gprolog 1.4.5 (64 Bits)\n*/\n\nchinrest(A, N, X) :-\n sort(N),\n prime(N,Nn), !, lenok(A, Nn), /* test as to whether the ni are primes */\n product(Nn,P), !, /* P is the product of the ni */\n milist(P, Nn, Mi), /* The Mi List: mi = n/ni */\n cilist(Mi, Nn, Ci), /* The first Ci List: mi-1 mod ni */\n mult_lists(Mi, Ci, Ac), /* The ci List :mi*(mi-1 mod ni) */\n mult_lists(Ac, A, Ad), /* The ai*ci List */\n sum_list(Ad, S), /* Sum of the ai*cis */\n X is S mod P, ! . /* a is (a1c1 + ... +akck) mod n */\n\nprime([X|Ys], Zs) :- fd_not_prime(X), !, prime(Ys,Zs). /* sift the primes of [list] */\nprime([Y|Ys], [Y|Zs]) :- fd_prime(Y), !, prime(Ys,Zs).\nprime([],[]).\n\nproduct([], 0). /* n1.n2.n3. ... .ni. ... .nk */\nproduct([H|T], P) :- product_1(T, H, P).\n\nproduct_1([], P, P).\nproduct_1([H|T], H0, P) :- product_1(T, H, P0), P is P0 * H0.\n\nlenok(A, N) :- length(A, X), length(N, Y), X=:=Y.\nlenok(_, _) :- write('Please enter equal length prime numbers only'), fail.\n\ncilist(Mi, Ni, Ci) :- maplist( (modinv), Mi, Ni, Ci). /* generate the Cis */\n\nmult_lists(Ai, Ci, Ac) :- maplist( (pro), Ai, Ci, Ac). /* The mi*ci */\npro(X, Y, Z) :- Z is X * Y.\n\nmilist(_, [],[]).\nmilist(P, [H|T],[X|Y]) :- X is truncate(P/H), milist(P, T, Y).\n\nmodinv(A, B, N) :- eeuclid(A, B, P, _, GCD),\n GCD =:= 1,\n N is P mod B.\n\neeuclid(A,B,P,S,GCD) :-\n A >= B,\n a_b_p_s_(A,B,P,S,1-0,0-1,GCD),\n GCD is A*P + B*S.\n\neeuclid(A,B,P,S,GCD) :-\n A < B,\n a_b_p_s_(B,A,S,P,1-0,0-1,GCD);\n GCD is A*P + B*S.\n\na_b_p_s_(A,0,P1,S1,P1-_P2,S1-_S2,A).\na_b_p_s_(A,B,P,S,P1-P2,S1-S2,GCD) :-\n B > 0,\n A > B,\n Q is truncate(A/B),\n B1 is A mod B,\n P3 is P1-(Q*P2),\n S3 is S1-(Q*S2),\n a_b_p_s_(B,B1,P,S,P2-P3,S2-S3,GCD).\n", "language": "Prolog" }, { "code": "EnableExplicit\nDisableDebugger\nDataSection\n LBL_n1:\n Data.i 3,5,7\n LBL_a1:\n Data.i 2,3,2\n LBL_n2:\n Data.i 11,12,13\n LBL_a2:\n Data.i 10,4,12\n LBL_n3:\n Data.i 10,4,9\n LBL_a3:\n Data.i 11,22,19\nEndDataSection\n\nProcedure ErrorHdl()\n Print(ErrorMessage())\n Input()\nEndProcedure\n\nMacro PrintData(n,a)\n Define Idx.i=0\n Print(\"[\")\n While n+SizeOf(Integer)*Idx<a\n Print(\"( \")\n Print(Str(PeekI(a+SizeOf(Integer)*Idx)))\n Print(\" . \")\n Print(Str(PeekI(n+SizeOf(Integer)*Idx)))\n Print(\" )\")\n Idx+1\n Wend\n Print(~\"]\\nx = \")\nEndMacro\n\nProcedure.i Produkt_n(n_Adr.i,a_Adr.i)\n Define p.i=1\n While n_Adr<a_Adr\n p*PeekI(n_Adr)\n n_Adr+SizeOf(Integer)\n Wend\n ProcedureReturn p\nEndProcedure\n\nProcedure.i Eval_x1(a.i,b.i)\n Define b0.i=b, x0.i=0, x1.i=1, q.i, t.i\n If b=1 : ProcedureReturn x1 : EndIf\n While a>1\n q=Int(a/b)\n t=b : b=a%b : a=t\n t=x0 : x0=x1-q*x0 : x1=t\n Wend\n If x1<0 : ProcedureReturn x1+b0 : EndIf\n ProcedureReturn x1\nEndProcedure\n\nProcedure.i ChineseRem(n_Adr.i,a_Adr.i)\n Define prod.i=Produkt_n(n_Adr,a_Adr), a.i, b.i, p.i, Idx.i=0, sum.i\n While n_Adr+SizeOf(Integer)*Idx<a_Adr\n b=PeekI(n_Adr+SizeOf(Integer)*Idx)\n p=Int(prod/b) : a=p\n sum+PeekI(a_Adr+SizeOf(Integer)*Idx)*Eval_x1(a,b)*p\n Idx+1\n Wend\n ProcedureReturn sum%prod\nEndProcedure\n\nOnErrorCall(@ErrorHdl())\nOpenConsole(\"Chinese remainder theorem\")\nPrintData(?LBL_n1,?LBL_a1)\nPrintN(Str(ChineseRem(?LBL_n1,?LBL_a1)))\nPrintData(?LBL_n2,?LBL_a2)\nPrintN(Str(ChineseRem(?LBL_n2,?LBL_a2)))\nPrintData(?LBL_n3,?LBL_a3)\nPrintN(Str(ChineseRem(?LBL_n3,?LBL_a3)))\nInput()\n", "language": "PureBasic" }, { "code": "# Python 2.7\ndef chinese_remainder(n, a):\n sum = 0\n prod = reduce(lambda a, b: a*b, n)\n\n for n_i, a_i in zip(n, a):\n p = prod / n_i\n sum += a_i * mul_inv(p, n_i) * p\n return sum % prod\n\n\ndef mul_inv(a, b):\n b0 = b\n x0, x1 = 0, 1\n if b == 1: return 1\n while a > 1:\n q = a / b\n a, b = b, a%b\n x0, x1 = x1 - q * x0, x0\n if x1 < 0: x1 += b0\n return x1\n\nif __name__ == '__main__':\n n = [3, 5, 7]\n a = [2, 3, 2]\n print chinese_remainder(n, a)\n", "language": "Python" }, { "code": "# Python 3.6\nfrom functools import reduce\ndef chinese_remainder(n, a):\n sum = 0\n prod = reduce(lambda a, b: a*b, n)\n for n_i, a_i in zip(n, a):\n p = prod // n_i\n sum += a_i * mul_inv(p, n_i) * p\n return sum % prod\n\n\n\ndef mul_inv(a, b):\n b0 = b\n x0, x1 = 0, 1\n if b == 1: return 1\n while a > 1:\n q = a // b\n a, b = b, a%b\n x0, x1 = x1 - q * x0, x0\n if x1 < 0: x1 += b0\n return x1\n\n\n\nif __name__ == '__main__':\n n = [3, 5, 7]\n a = [2, 3, 2]\n print(chinese_remainder(n, a))\n", "language": "Python" }, { "code": "'''Chinese remainder theorem'''\n\nfrom operator import (add, mul)\nfrom functools import reduce\n\n\n# cnRemainder :: [Int] -> [Int] -> Either String Int\ndef cnRemainder(ms):\n '''Chinese remainder theorem.\n (moduli, residues) -> Either explanation or solution\n '''\n def go(ms, rs):\n mp = numericProduct(ms)\n cms = [(mp // x) for x in ms]\n\n def possibleSoln(invs):\n return Right(\n sum(map(\n mul,\n cms, map(mul, rs, invs)\n )) % mp\n )\n return bindLR(\n zipWithEither(modMultInv)(cms)(ms)\n )(possibleSoln)\n\n return lambda rs: go(ms, rs)\n\n\n# modMultInv :: Int -> Int -> Either String Int\ndef modMultInv(a, b):\n '''Modular multiplicative inverse.'''\n x, y = eGcd(a, b)\n return Right(x) if 1 == (a * x + b * y) else (\n Left('no modular inverse for ' + str(a) + ' and ' + str(b))\n )\n\n\n# egcd :: Int -> Int -> (Int, Int)\ndef eGcd(a, b):\n '''Extended greatest common divisor.'''\n def go(a, b):\n if 0 == b:\n return (1, 0)\n else:\n q, r = divmod(a, b)\n (s, t) = go(b, r)\n return (t, s - q * t)\n return go(a, b)\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Tests of soluble and insoluble cases.'''\n\n print(\n fTable(\n __doc__ + ':\\n\\n (moduli, residues) -> ' + (\n 'Either solution or explanation\\n'\n )\n )(repr)(\n either(compose(quoted(\"'\"))(curry(add)('No solution: ')))(\n compose(quoted(' '))(repr)\n )\n )(uncurry(cnRemainder))([\n ([10, 4, 12], [11, 12, 13]),\n ([11, 12, 13], [10, 4, 12]),\n ([10, 4, 9], [11, 22, 19]),\n ([3, 5, 7], [2, 3, 2]),\n ([2, 3, 2], [3, 5, 7])\n ])\n )\n\n\n# GENERIC -------------------------------------------------\n\n# Left :: a -> Either a b\ndef Left(x):\n '''Constructor for an empty Either (option type) value\n with an associated string.'''\n return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right :: b -> Either a b\ndef Right(x):\n '''Constructor for a populated Either (option type) value'''\n return {'type': 'Either', 'Left': None, 'Right': x}\n# any :: (a -> Bool) -> [a] -> Bool\n\n\ndef any_(p):\n '''True if p(x) holds for at least\n one item in xs.'''\n def go(xs):\n for x in xs:\n if p(x):\n return True\n return False\n return lambda xs: go(xs)\n\n\n# bindLR (>>=) :: Either a -> (a -> Either b) -> Either b\ndef bindLR(m):\n '''Either monad injection operator.\n Two computations sequentially composed,\n with any value produced by the first\n passed as an argument to the second.'''\n return lambda mf: (\n mf(m.get('Right')) if None is m.get('Left') else m\n )\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# curry :: ((a, b) -> c) -> a -> b -> c\ndef curry(f):\n '''A curried function derived\n from an uncurried function.'''\n return lambda a: lambda b: f(a, b)\n\n\n# either :: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n '''The application of fl to e if e is a Left value,\n or the application of fr to e if e is a Right value.'''\n return lambda fr: lambda e: fl(e['Left']) if (\n None is e['Right']\n ) else fr(e['Right'])\n\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function ->\n fx display function ->\n f -> value list -> tabular string.'''\n def go(xShow, fxShow, f, xs):\n w = max(map(compose(len)(xShow), xs))\n return s + '\\n' + '\\n'.join([\n xShow(x).rjust(w, ' ') + (' -> ') + fxShow(f(x))\n for x in xs\n ])\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# numericProduct :: [Num] -> Num\ndef numericProduct(xs):\n '''The arithmetic product of all numbers in xs.'''\n return reduce(mul, xs, 1)\n\n\n# partitionEithers :: [Either a b] -> ([a],[b])\ndef partitionEithers(lrs):\n '''A list of Either values partitioned into a tuple\n of two lists, with all Left elements extracted\n into the first list, and Right elements\n extracted into the second list.\n '''\n def go(a, x):\n ls, rs = a\n r = x.get('Right')\n return (ls + [x.get('Left')], rs) if None is r else (\n ls, rs + [r]\n )\n return reduce(go, lrs, ([], []))\n\n\n# quoted :: Char -> String -> String\ndef quoted(c):\n '''A string flanked on both sides\n by a specified quote character.\n '''\n return lambda s: c + s + c\n\n\n# uncurry :: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n '''A function over a tuple,\n derived from a curried function.'''\n return lambda xy: f(xy[0])(xy[1])\n\n\n# zipWithEither :: (a -> b -> Either String c)\n# -> [a] -> [b] -> Either String [c]\ndef zipWithEither(f):\n '''Either a list of results if f succeeds with every pair\n in the zip of xs and ys, or an explanatory string\n if any application of f returns no result.\n '''\n def go(xs, ys):\n ls, rs = partitionEithers(map(f, xs, ys))\n return Left(ls[0]) if ls else Right(rs)\n return lambda xs: lambda ys: go(xs, ys)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "mul_inv <- function(a, b)\n{\n b0 <- b\n x0 <- 0L\n x1 <- 1L\n\n if (b == 1) return(1L)\n while(a > 1){\n q <- as.integer(a/b)\n\n t <- b\n b <- a %% b\n a <- t\n\n t <- x0\n x0 <- x1 - q*x0\n x1 <- t\n }\n\n if (x1 < 0) x1 <- x1 + b0\n return(x1)\n}\n\nchinese_remainder <- function(n, a)\n{\n len <- length(n)\n\n prod <- 1L\n sum <- 0L\n\n for (i in 1:len) prod <- prod * n[i]\n\n for (i in 1:len){\n p <- as.integer(prod / n[i])\n sum <- sum + a[i] * mul_inv(p, n[i]) * p\n }\n\n return(sum %% prod)\n}\n\nn <- c(3L, 5L, 7L)\na <- c(2L, 3L, 2L)\n\nchinese_remainder(n, a)\n", "language": "R" }, { "code": "#lang racket\n(require (only-in math/number-theory solve-chinese))\n(define as '(2 3 2))\n(define ns '(3 5 7))\n(solve-chinese as ns)\n", "language": "Racket" }, { "code": "# returns x where (a * x) % b == 1\nsub mul-inv($a is copy, $b is copy) {\n return 1 if $b == 1;\n my ($b0, @x) = $b, 0, 1;\n ($a, $b, @x) = (\n\t$b,\n\t$a % $b,\n\t@x[1] - ($a div $b)*@x[0],\n\t@x[0]\n ) while $a > 1;\n @x[1] += $b0 if @x[1] < 0;\n return @x[1];\n}\n\nsub chinese-remainder(*@n) {\n my \\N = [*] @n;\n -> *@a {\n\tN R% [+] map {\n\t my \\p = N div @n[$_];\n\t @a[$_] * mul-inv(p, @n[$_]) * p\n\t}, ^@n\n }\n}\n\nsay chinese-remainder(3, 5, 7)(2, 3, 2);\n", "language": "Raku" }, { "code": "/*REXX program demonstrates Sun Tzu's (or Sunzi's) Chinese Remainder Theorem. */\nparse arg Ns As . /*get optional arguments from the C.L. */\nif Ns=='' | Ns==\",\" then Ns= '3,5,7' /*Ns not specified? Then use default.*/\nif As=='' | As==\",\" then As= '2,3,2' /*As \" \" \" \" \" */\n say 'Ns: ' Ns\n say 'As: ' As; say\nNs= space( translate(Ns, , ',')); #= words(Ns) /*elide any superfluous blanks from N's*/\nAs= space( translate(As, , ',')); _= words(As) /* \" \" \" \" \" A's*/\nif #\\==_ then do; say \"size of number sets don't match.\"; exit 131; end\nif #==0 then do; say \"size of the N set isn't valid.\"; exit 132; end\nif _==0 then do; say \"size of the A set isn't valid.\"; exit 133; end\nN= 1 /*the product─to─be for prod(n.j). */\n do j=1 for # /*process each number for As and Ns. */\n n.j= word(Ns, j); N= N * n.j /*get an N.j and calculate product. */\n a.j= word(As, j) /* \" \" A.j from the As list. */\n end /*j*/\n\n do x=1 for N /*use a simple algebraic method. */\n do i=1 for # /*process each N.i and A.i number.*/\n if x//n.i\\==a.i then iterate x /*is modulus correct for the number X ?*/\n end /*i*/ /* [↑] limit solution to the product. */\n say 'found a solution with X=' x /*display one possible solution. */\n exit 0 /*stick a fork in it, we're all done. */\n end /*x*/\n\nsay 'no solution found.' /*oops, announce that solution ¬ found.*/\n", "language": "REXX" }, { "code": "/*REXX program demonstrates Sun Tzu's (or Sunzi's) Chinese Remainder Theorem. */\nparse arg Ns As . /*get optional arguments from the C.L. */\nif Ns=='' | Ns==\",\" then Ns= '3,5,7' /*Ns not specified? Then use default.*/\nif As=='' | As==\",\" then As= '2,3,2' /*As \" \" \" \" \" */\n say 'Ns: ' Ns\n say 'As: ' As; say\nNs= space( translate(Ns, , ',')); #= words(Ns) /*elide any superfluous blanks from N's*/\nAs= space( translate(As, , ',')); _= words(As) /* \" \" \" \" \" A's*/\nif #\\==_ then do; say \"size of number sets don't match.\"; exit 131; end\nif #==0 then do; say \"size of the N set isn't valid.\"; exit 132; end\nif _==0 then do; say \"size of the A set isn't valid.\"; exit 133; end\nN= 1 /*the product─to─be for prod(n.j). */\n do j=1 for # /*process each number for As and Ns. */\n n.j= word(Ns,j); N= N * n.j /*get an N.j and calculate product. */\n a.j= word(As,j) /* \" \" A.j from the As list. */\n end /*j*/\n@.= /* [↓] converts congruences ───► sets.*/\n do i=1 for #; _= a.i; @.i._= a.i; p= a.i\n do N; p= p + n.i; @.i.p= p /*build a (array) list of modulo values*/\n end /*N*/\n end /*i*/\n /* [↓] find common number in the sets.*/\n do x=1 for N; if @.1.x=='' then iterate /*locate a number. */\n do v=2 to #; if @.v.x=='' then iterate x /*Is in all sets ? */\n end /*v*/\n say 'found a solution with X=' x /*display one possible solution. */\n exit 0 /*stick a fork in it, we're all done. */\n end /*x*/\n\nsay 'no solution found.' /*oops, announce that solution ¬ found.*/\n", "language": "REXX" }, { "code": "def chinese_remainder(mods, remainders)\n max = mods.inject( :* )\n series = remainders.zip( mods ).map{|r,m| r.step( max, m ).to_a }\n series.inject( :& ).first #returns nil when empty\nend\n\np chinese_remainder([3,5,7], [2,3,2]) #=> 23\np chinese_remainder([10,4,9], [11,22,19]) #=> nil\n", "language": "Ruby" }, { "code": "def extended_gcd(a, b)\n last_remainder, remainder = a.abs, b.abs\n x, last_x = 0, 1\n while remainder != 0\n last_remainder, (quotient, remainder) = remainder, last_remainder.divmod(remainder)\n x, last_x = last_x - quotient*x, x\n end\n return last_remainder, last_x * (a < 0 ? -1 : 1)\nend\n\ndef invmod(e, et)\n g, x = extended_gcd(e, et)\n if g != 1\n raise 'Multiplicative inverse modulo does not exist!'\n end\n x % et\nend\n\ndef chinese_remainder(mods, remainders)\n max = mods.inject( :* ) # product of all moduli\n series = remainders.zip(mods).map{ |r,m| (r * max * invmod(max/m, m) / m) }\n series.inject( :+ ) % max\nend\n\np chinese_remainder([3,5,7], [2,3,2]) #=> 23\np chinese_remainder([17353461355013928499, 3882485124428619605195281, 13563122655762143587], [7631415079307304117, 1248561880341424820456626, 2756437267211517231]) #=> 937307771161836294247413550632295202816\np chinese_remainder([10,4,9], [11,22,19]) #=> nil\n", "language": "Ruby" }, { "code": "fn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if a == 0 {\n (b, 0, 1)\n } else {\n let (g, x, y) = egcd(b % a, a);\n (g, y - (b / a) * x, x)\n }\n}\n\nfn mod_inv(x: i64, n: i64) -> Option<i64> {\n let (g, x, _) = egcd(x, n);\n if g == 1 {\n Some((x % n + n) % n)\n } else {\n None\n }\n}\n\nfn chinese_remainder(residues: &[i64], modulii: &[i64]) -> Option<i64> {\n let prod = modulii.iter().product::<i64>();\n\n let mut sum = 0;\n\n for (&residue, &modulus) in residues.iter().zip(modulii) {\n let p = prod / modulus;\n sum += residue * mod_inv(p, modulus)? * p\n }\n\n Some(sum % prod)\n}\n\nfn main() {\n let modulii = [3,5,7];\n let residues = [2,3,2];\n\n match chinese_remainder(&residues, &modulii) {\n Some(sol) => println!(\"{}\", sol),\n None => println!(\"modulii not pairwise coprime\")\n }\n\n}\n", "language": "Rust" }, { "code": "import scala.util.{Success, Try}\n\nobject ChineseRemainderTheorem extends App {\n\n def chineseRemainder(n: List[Int], a: List[Int]): Option[Int] = {\n require(n.size == a.size)\n val prod = n.product\n\n def iter(n: List[Int], a: List[Int], sm: Int): Int = {\n def mulInv(a: Int, b: Int): Int = {\n def loop(a: Int, b: Int, x0: Int, x1: Int): Int = {\n if (a > 1) loop(b, a % b, x1 - (a / b) * x0, x0) else x1\n }\n\n if (b == 1) 1\n else {\n val x1 = loop(a, b, 0, 1)\n if (x1 < 0) x1 + b else x1\n }\n }\n\n if (n.nonEmpty) {\n val p = prod / n.head\n\n iter(n.tail, a.tail, sm + a.head * mulInv(p, n.head) * p)\n } else sm\n }\n\n Try {\n iter(n, a, 0) % prod\n } match {\n case Success(v) => Some(v)\n case _ => None\n }\n }\n\n println(chineseRemainder(List(3, 5, 7), List(2, 3, 2)))\n println(chineseRemainder(List(11, 12, 13), List(10, 4, 12)))\n println(chineseRemainder(List(11, 22, 19), List(10, 4, 9)))\n\n}\n", "language": "Scala" }, { "code": "$ include \"seed7_05.s7i\";\n include \"bigint.s7i\";\n\nconst func integer: modInverse (in integer: a, in integer: b) is\n return ord(modInverse(bigInteger conv a, bigInteger conv b));\n\nconst proc: main is func\n local\n const array integer: n is [] (3, 5, 7);\n const array integer: a is [] (2, 3, 2);\n var integer: num is 0;\n var integer: prod is 1;\n var integer: sum is 0;\n var integer: index is 0;\n begin\n for num range n do\n prod *:= num;\n end for;\n for key index range a do\n num := prod div n[index];\n sum +:= a[index] * modInverse(num, n[index]) * num;\n end for;\n writeln(sum mod prod);\n end func;\n", "language": "Seed7" }, { "code": "func chinese_remainder(*n) {\n var N = n.prod\n func (*a) {\n n.range.sum { |i|\n var p = (N / n[i])\n a[i] * p.invmod(n[i]) * p\n } % N\n }\n}\n\nsay chinese_remainder(3, 5, 7)(2, 3, 2)\n", "language": "Sidef" }, { "code": "create temporary table inputs(remainder int, modulus int);\n\ninsert into inputs values (2, 3), (3, 5), (2, 7);\n\nwith recursive\n\n-- Multiply out the product of moduli\nmultiplication(idx, product) as (\n select 1, 1\n\n union all\n\n select\n multiplication.idx+1,\n multiplication.product * inputs.modulus\n from\n multiplication,\n inputs\n where\n inputs.rowid = multiplication.idx\n),\n\n-- Take the final value from the product table\nproduct(final_value) as (\n select max(product) from multiplication\n),\n\n-- Calculate the multiplicative inverse from each equation\nmultiplicative_inverse(id, a, b, x, y) as (\n select\n inputs.modulus,\n product.final_value / inputs.modulus,\n inputs.modulus,\n 0,\n 1\n from\n inputs,\n product\n\n union all\n\n select\n id,\n b, a%b,\n y - (a/b)*x, x\n from\n multiplicative_inverse\n where\n a>0\n)\n-- Combine residues into final answer\nselect\n sum(\n (y % inputs.modulus) * inputs.remainder * (product.final_value / inputs.modulus)\n ) % product.final_value\n from\n multiplicative_inverse, product, inputs\n where\n a=1 and multiplicative_inverse.id = inputs.modulus;\n", "language": "SQL" }, { "code": "import Darwin\n\n/*\n * Function: euclid\n * Usage: (r,s) = euclid(m,n)\n * --------------------------\n * The extended Euclidean algorithm subsequently performs\n * Euclidean divisions till the remainder is zero and then\n * returns the Bézout coefficients r and s.\n */\n\nfunc euclid(_ m:Int, _ n:Int) -> (Int,Int) {\n if m % n == 0 {\n return (0,1)\n } else {\n let rs = euclid(n % m, m)\n let r = rs.1 - rs.0 * (n / m)\n let s = rs.0\n\n return (r,s)\n }\n}\n\n/*\n * Function: gcd\n * Usage: x = gcd(m,n)\n * -------------------\n * The greatest common divisor of two numbers a and b\n * is expressed by ax + by = gcd(a,b) where x and y are\n * the Bézout coefficients as determined by the extended\n * euclidean algorithm.\n */\n\nfunc gcd(_ m:Int, _ n:Int) -> Int {\n let rs = euclid(m, n)\n return m * rs.0 + n * rs.1\n}\n\n/*\n * Function: coprime\n * Usage: truth = coprime(m,n)\n * ---------------------------\n * If two values are coprime, their greatest common\n * divisor is 1.\n */\n\nfunc coprime(_ m:Int, _ n:Int) -> Bool {\n return gcd(m,n) == 1 ? true : false\n}\n\ncoprime(14,26)\n//coprime(2,4)\n\n/*\n * Function: crt\n * Usage: x = crt(a,n)\n * -------------------\n * The Chinese Remainder Theorem supposes that given the\n * integers n_1...n_k that are pairwise co-prime, then for\n * any sequence of integers a_1...a_k there exists an integer\n * x that solves the system of linear congruences:\n *\n * x === a_1 (mod n_1)\n * ...\n * x === a_k (mod n_k)\n */\n\nfunc crt(_ a_i:[Int], _ n_i:[Int]) -> Int {\n // There is no identity operator for elements of [Int].\n // The offset of the elements of an enumerated sequence\n // can be used instead, to determine if two elements of the same\n // array are the same.\n let divs = n_i.enumerated()\n\n // Check if elements of n_i are pairwise coprime divs.filter{ $0.0 < n.0 }\n divs.forEach{\n n in divs.filter{ $0.0 < n.0 }.forEach{\n assert(coprime(n.1, $0.1))\n }\n }\n\n // Calculate factor N\n let N = n_i.map{$0}.reduce(1, *)\n\n // Euclidean algorithm determines s_i (and r_i)\n var s:[Int] = []\n\n // Using euclidean algorithm to calculate r_i, s_i\n n_i.forEach{ s += [euclid($0, N / $0).1] }\n\n // Solve for x\n var x = 0\n a_i.enumerated().forEach{\n x += $0.1 * s[$0.0] * N / n_i[$0.0]\n }\n\n // Return minimal solution\n return x % N\n}\n\nlet a = [2,3,2]\nlet n = [3,5,7]\n\nlet x = crt(a,n)\n\nprint(x)\n", "language": "Swift" }, { "code": "proc ::tcl::mathfunc::mulinv {a b} {\n if {$b == 1} {return 1}\n set b0 $b; set x0 0; set x1 1\n while {$a > 1} {\n\tset x0 [expr {$x1 - ($a / $b) * [set x1 $x0]}]\n\tset b [expr {$a % [set a $b]}]\n }\n incr x1 [expr {($x1 < 0) * $b0}]\n}\nproc chineseRemainder {nList aList} {\n set sum 0; set prod [::tcl::mathop::* {*}$nList]\n foreach n $nList a $aList {\n\tset p [expr {$prod / $n}]\n\tincr sum [expr {$a * mulinv($p, $n) * $p}]\n }\n expr {$sum % $prod}\n}\nputs [chineseRemainder {3 5 7} {2 3 2}]\n", "language": "Tcl" }, { "code": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n Dim p As Long, prod As Long, tot As Long\n prod = 1: tot = 0\n For i = 1 To UBound(n)\n prod = prod * n(i)\n Next i\n Dim m As Variant\n For i = 1 To UBound(n)\n p = prod / n(i)\n m = mul_inv(p, n(i))\n If WorksheetFunction.IsText(m) Then\n chinese_remainder = \"fail\"\n Exit Function\n End If\n tot = tot + a(i) * m * p\n Next i\n chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n", "language": "VBA" }, { "code": "Module Module1\n\n Function ModularMultiplicativeInverse(a As Integer, m As Integer) As Integer\n Dim b = a Mod m\n For x = 1 To m - 1\n If (b * x) Mod m = 1 Then\n Return x\n End If\n Next\n Return 1\n End Function\n\n Function Solve(n As Integer(), a As Integer()) As Integer\n Dim prod = n.Aggregate(1, Function(i, j) i * j)\n Dim sm = 0\n Dim p As Integer\n For i = 0 To n.Length - 1\n p = prod / n(i)\n sm = sm + a(i) * ModularMultiplicativeInverse(p, n(i)) * p\n Next\n Return sm Mod prod\n End Function\n\n Sub Main()\n Dim n = {3, 5, 7}\n Dim a = {2, 3, 2}\n\n Dim result = Solve(n, a)\n\n Dim counter = 0\n Dim maxCount = n.Length - 1\n While counter <= maxCount\n Console.WriteLine($\"{result} = {a(counter)} (mod {n(counter)})\")\n counter = counter + 1\n End While\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "/* returns x where (a * x) % b == 1 */\nvar mulInv = Fn.new { |a, b|\n if (b == 1) return 1\n var b0 = b\n var x0 = 0\n var x1 = 1\n while (a > 1) {\n var q = (a/b).floor\n var t = b\n b = a % b\n a = t\n t = x0\n x0 = x1 - q*x0\n x1 = t\n }\n if (x1 < 0) x1 = x1 + b0\n return x1\n}\n\nvar chineseRemainder = Fn.new { |n, a|\n var prod = n.reduce { |acc, i| acc * i }\n var sum = 0\n for (i in 0...n.count) {\n var p = (prod/n[i]).floor\n sum = sum + a[i]*mulInv.call(p, n[i])*p\n }\n return sum % prod\n}\n\nvar n = [3, 5, 7]\nvar a = [2, 3, 2]\nSystem.print(chineseRemainder.call(n, a))\n", "language": "Wren" }, { "code": "func MulInv(A, B); \\Returns X where rem((A*X) / B) = 1\nint A, B;\nint B0, T, Q;\nint X0, X1;\n[B0:= B; X0:= 0; X1:= 1;\nif B = 1 then return 1;\nwhile A > 1 do\n [Q:= A / B;\n T:= B; B:= rem(A/B); A:= T;\n T:= X0; X0:= X1 - Q*X0; X1:= T;\n ];\nif X1 < 0 then X1:= X1 + B0;\nreturn X1;\n];\n\nfunc ChineseRem(N, A, Len);\nint N, A, Len;\nint P, I, Prod, Sum;\n[Prod:= 1; Sum:= 0;\nfor I:= 0 to Len-1 do Prod:= Prod*N(I);\nfor I:= 0 to Len-1 do\n [P:= Prod / N(I);\n Sum:= Sum + A(I) * MulInv(P,N(I)) * P;\n ];\nreturn rem(Sum/Prod);\n];\n\nint N, A;\n[N:= [ 3, 5, 7 ];\n A:= [ 2, 3, 2 ];\n IntOut(0, ChineseRem(N, A, 3)); CrLf(0);\n]\n", "language": "XPL0" }, { "code": "var BN=Import(\"zklBigNum\"), one=BN(1);\n\nfcn crt(xs,ys){\n p:=xs.reduce('*,BN(1));\n X:=BN(0);\n foreach x,y in (xs.zip(ys)){\n q:=p/x;\n z,s,_:=q.gcdExt(x);\n if(z!=one) throw(Exception.ValueError(\"%d not coprime\".fmt(x)));\n X+=y*s*q;\n }\n return(X % p);\n}\n", "language": "Zkl" }, { "code": "println(crt(T(3,5,7), T(2,3,2))); //-->23\nprintln(crt(T(11,12,13),T(10,4,12))); //-->1000\nprintln(crt(T(11,22,19), T(10,4,9))); //-->ValueError: 11 not coprime\n", "language": "Zkl" }, { "code": "10 DIM n(3): DIM a(3)\n20 FOR i=1 TO 3\n30 READ n(i),a(i)\n40 NEXT i\n50 DATA 3,2,5,3,7,2\n100 LET prod=1: LET sum=0\n110 FOR i=1 TO 3: LET prod=prod*n(i): NEXT i\n120 FOR i=1 TO 3\n130 LET p=INT (prod/n(i)): LET a=p: LET b=n(i)\n140 GO SUB 1000\n150 LET sum=sum+a(i)*x1*p\n160 NEXT i\n170 PRINT FN m(sum,prod)\n180 STOP\n200 DEF FN m(a,b)=a-INT (a/b)*b: REM Modulus function\n1000 LET b0=b: LET x0=0: LET x1=1\n1010 IF b=1 THEN RETURN\n1020 IF a<=1 THEN GO TO 1100\n1030 LET q=INT (a/b)\n1040 LET t=b: LET b=FN m(a,b): LET a=t\n1050 LET t=x0: LET x0=x1-q*x0: LET x1=t\n1060 GO TO 1020\n1100 IF x1<0 THEN LET x1=x1+b0\n1110 RETURN\n", "language": "ZX-Spectrum-Basic" } ]
Chinese-remainder-theorem
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Cholesky_decomposition\nnote: Matrices\n", "language": "00-META" }, { "code": "Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:\n\n:<math>A = LL^T</math>\n\n<math>L</math> is called the ''Cholesky factor'' of <math>A</math>, and can be interpreted as a generalized square root of <math>A</math>, as described in [[wp:Cholesky decomposition|Cholesky decomposition]].\n\nIn a 3x3 example, we have to solve the following system of equations:\n\n:<math>\\begin{align}\nA &=\n\\begin{pmatrix}\n a_{11} & a_{21} & a_{31}\\\\\n a_{21} & a_{22} & a_{32}\\\\\n a_{31} & a_{32} & a_{33}\\\\\n\\end{pmatrix}\\\\\n& = \n\\begin{pmatrix}\n l_{11} & 0 & 0 \\\\\n l_{21} & l_{22} & 0 \\\\\n l_{31} & l_{32} & l_{33}\\\\\n\\end{pmatrix}\n\\begin{pmatrix}\n l_{11} & l_{21} & l_{31} \\\\\n 0 & l_{22} & l_{32} \\\\\n 0 & 0 & l_{33}\n\\end{pmatrix} \\equiv LL^T\\\\\n&= \\begin{pmatrix}\n l_{11}^2 & l_{21}l_{11} & l_{31}l_{11} \\\\\n l_{21}l_{11} & l_{21}^2 + l_{22}^2& l_{31}l_{21}+l_{32}l_{22} \\\\\n l_{31}l_{11} & l_{31}l_{21}+l_{32}l_{22} & l_{31}^2 + l_{32}^2+l_{33}^2\n\\end{pmatrix}\\end{align}\n</math>\n\nWe can see that for the diagonal elements (<math>l_{kk}</math>) of <math>L</math> there is a calculation pattern:\n\n:<math>l_{11} = \\sqrt{a_{11}}</math>\n:<math>l_{22} = \\sqrt{a_{22} - l_{21}^2}</math>\n:<math>l_{33} = \\sqrt{a_{33} - (l_{31}^2 + l_{32}^2)}</math>\n\nor in general:\n\n:<math>l_{kk} = \\sqrt{a_{kk} - \\sum_{j=1}^{k-1} l_{kj}^2}</math>\n\nFor the elements below the diagonal (<math>l_{ik}</math>, where <math>i > k </math>) there is also a calculation pattern:\n\n:<math>l_{21} = \\frac{1}{l_{11}} a_{21}</math>\n:<math>l_{31} = \\frac{1}{l_{11}} a_{31}</math>\n:<math>l_{32} = \\frac{1}{l_{22}} (a_{32} - l_{31}l_{21})</math>\n\nwhich can also be expressed in a general formula:\n\n:<math>l_{ik} = \\frac{1}{l_{kk}} \\left ( a_{ik} - \\sum_{j=1}^{k-1} l_{ij}l_{kj} \\right )</math>\n\n'''Task description'''\n\nThe task is to implement a routine which will return a lower Cholesky factor <math>L</math> for every given symmetric, positive definite nxn matrix <math>A</math>. You should then test it on the following two examples and include your output.\n\nExample 1:\n\n<pre>\n25 15 -5 5 0 0\n15 18 0 --> 3 3 0\n-5 0 11 -1 1 3\n</pre>\n\nExample 2:\n\n<pre>\n18 22 54 42 4.24264 0.00000 0.00000 0.00000\n22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000\n54 86 174 134 12.72792 3.04604 1.64974 0.00000\n42 62 134 106 9.89949 1.62455 1.84971 1.39262\n</pre>\n\n\n;Note:\n# The Cholesky decomposition of a [[Pascal matrix generation‎|Pascal]] upper-triangle matrix is the [[wp:Identity matrix|Identity matrix]] of the same size. \n# The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.\n", "language": "00-TASK" }, { "code": "F cholesky(A)\n V l = [[0.0] * A.len] * A.len\n L(i) 0 .< A.len\n L(j) 0 .. i\n V s = sum((0 .< j).map(k -> @l[@i][k] * @l[@j][k]))\n l[i][j] = I (i == j) {sqrt(A[i][i] - s)} E (1.0 / l[j][j] * (A[i][j] - s))\n R l\n\nF pprint(m)\n print(‘[’)\n L(row) m\n print(row)\n print(‘]’)\n\nV m1 = [[25, 15, -5],\n [15, 18, 0],\n [-5, 0, 11]]\nprint(cholesky(m1))\nprint()\n\nV m2 = [[18, 22, 54, 42],\n [22, 70, 86, 62],\n [54, 86, 174, 134],\n [42, 62, 134, 106]]\npprint(cholesky(m2))\n", "language": "11l" }, { "code": "with Ada.Numerics.Generic_Real_Arrays;\ngeneric\n with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>);\npackage Decomposition is\n\n -- decompose a square matrix A by A = L * Transpose (L)\n procedure Decompose (A : Matrix.Real_Matrix; L : out Matrix.Real_Matrix);\n\nend Decomposition;\n", "language": "Ada" }, { "code": "with Ada.Numerics.Generic_Elementary_Functions;\n\npackage body Decomposition is\n package Math is new Ada.Numerics.Generic_Elementary_Functions\n (Matrix.Real);\n\n procedure Decompose (A : Matrix.Real_Matrix; L : out Matrix.Real_Matrix) is\n use type Matrix.Real_Matrix, Matrix.Real;\n Order : constant Positive := A'Length (1);\n S : Matrix.Real;\n begin\n L := (others => (others => 0.0));\n for I in 0 .. Order - 1 loop\n for K in 0 .. I loop\n S := 0.0;\n for J in 0 .. K - 1 loop\n S := S +\n L (L'First (1) + I, L'First (2) + J) *\n L (L'First (1) + K, L'First (2) + J);\n end loop;\n -- diagonals\n if K = I then\n L (L'First (1) + K, L'First (2) + K) :=\n Math.Sqrt (A (A'First (1) + K, A'First (2) + K) - S);\n else\n L (L'First (1) + I, L'First (2) + K) :=\n 1.0 / L (L'First (1) + K, L'First (2) + K) *\n (A (A'First (1) + I, A'First (2) + K) - S);\n end if;\n end loop;\n end loop;\n end Decompose;\nend Decomposition;\n", "language": "Ada" }, { "code": "with Ada.Numerics.Real_Arrays;\nwith Ada.Text_IO;\nwith Decomposition;\nprocedure Decompose_Example is\n package Real_Decomposition is new Decomposition\n (Matrix => Ada.Numerics.Real_Arrays);\n\n package Real_IO is new Ada.Text_IO.Float_IO (Float);\n\n procedure Print (M : Ada.Numerics.Real_Arrays.Real_Matrix) is\n begin\n for Row in M'Range (1) loop\n for Col in M'Range (2) loop\n Real_IO.Put (M (Row, Col), 4, 3, 0);\n end loop;\n Ada.Text_IO.New_Line;\n end loop;\n end Print;\n\n Example_1 : constant Ada.Numerics.Real_Arrays.Real_Matrix :=\n ((25.0, 15.0, -5.0),\n (15.0, 18.0, 0.0),\n (-5.0, 0.0, 11.0));\n L_1 : Ada.Numerics.Real_Arrays.Real_Matrix (Example_1'Range (1),\n Example_1'Range (2));\n Example_2 : constant Ada.Numerics.Real_Arrays.Real_Matrix :=\n ((18.0, 22.0, 54.0, 42.0),\n (22.0, 70.0, 86.0, 62.0),\n (54.0, 86.0, 174.0, 134.0),\n (42.0, 62.0, 134.0, 106.0));\n L_2 : Ada.Numerics.Real_Arrays.Real_Matrix (Example_2'Range (1),\n Example_2'Range (2));\nbegin\n Real_Decomposition.Decompose (A => Example_1,\n L => L_1);\n Real_Decomposition.Decompose (A => Example_2,\n L => L_2);\n Ada.Text_IO.Put_Line (\"Example 1:\");\n Ada.Text_IO.Put_Line (\"A:\"); Print (Example_1);\n Ada.Text_IO.Put_Line (\"L:\"); Print (L_1);\n Ada.Text_IO.New_Line;\n Ada.Text_IO.Put_Line (\"Example 2:\");\n Ada.Text_IO.Put_Line (\"A:\"); Print (Example_2);\n Ada.Text_IO.Put_Line (\"L:\"); Print (L_2);\nend Decompose_Example;\n", "language": "Ada" }, { "code": "#!/usr/local/bin/a68g --script #\n\nMODE FIELD=LONG REAL;\nPROC (FIELD)FIELD field sqrt = long sqrt;\nINT field prec = 5;\nFORMAT field fmt = $g(-(2+1+field prec),field prec)$;\n\nMODE MAT = [0,0]FIELD;\n\nPROC cholesky = (MAT a) MAT:(\n [UPB a, 2 UPB a]FIELD l;\n\n FOR i FROM LWB a TO UPB a DO\n FOR j FROM 2 LWB a TO i DO\n FIELD s := 0;\n FOR k FROM 2 LWB a TO j-1 DO\n s +:= l[i,k] * l[j,k]\n OD;\n l[i,j] := IF i = j\n THEN field sqrt(a[i,i] - s)\n ELSE 1.0 / l[j,j] * (a[i,j] - s) FI\n OD;\n FOR j FROM i+1 TO 2 UPB a DO\n l[i,j]:=0 # Not required if matrix is declared as triangular #\n OD\n OD;\n l\n);\n\nPROC print matrix v1 =(MAT a)VOID:(\n FOR i FROM LWB a TO UPB a DO\n FOR j FROM 2 LWB a TO 2 UPB a DO\n printf(($g(-(2+1+field prec),field prec)$, a[i,j]))\n OD;\n printf($l$)\n OD\n);\n\nPROC print matrix =(MAT a)VOID:(\n FORMAT vector fmt = $\"(\"f(field fmt)n(2 UPB a-2 LWB a)(\", \" f(field fmt))\")\"$;\n FORMAT matrix fmt = $\"(\"f(vector fmt)n( UPB a- LWB a)(\",\"lxf(vector fmt))\")\"$;\n printf((matrix fmt, a))\n);\n\nmain: (\n MAT m1 = ((25, 15, -5),\n (15, 18, 0),\n (-5, 0, 11));\n MAT c1 = cholesky(m1);\n print matrix(c1);\n printf($l$);\n\n MAT m2 = ((18, 22, 54, 42),\n (22, 70, 86, 62),\n (54, 86, 174, 134),\n (42, 62, 134, 106));\n MAT c2 = cholesky(m2);\n print matrix(c2)\n)\n", "language": "ALGOL-68" }, { "code": "cholesky: function [m][\n result: array.of: @[size m, size m] 0.0\n\n loop 0..dec size m\\0 'i [\n loop 0..i 'j [\n s: 0.0\n loop 0..j 'k ->\n s: s + result\\[i]\\[k] * result\\[j]\\[k]\n\n result\\[i]\\[j]: (i = j)? -> sqrt m\\[i]\\[i] - s\n -> (1.0 // result\\[j]\\[j]) * (m\\[i]\\[j] - s)\n ]\n ]\n return result\n]\n\nprintMatrix: function [a]->\n loop a 'b ->\n print to [:string] .format:\"8.5f\" b\n\nm1: @[\n @[25.0, 15.0, neg 5.0]\n @[15.0, 18.0, 0.0]\n @[neg 5.0, 0.0, 11.0]\n]\nprintMatrix cholesky m1\n\nprint \"\"\n\nm2: [\n [18.0, 22.0, 54.0, 42.0]\n [22.0, 70.0, 86.0, 62.0]\n [54.0, 86.0, 174.0, 134.0]\n [42.0, 62.0, 134.0, 106.0]\n]\nprintMatrix cholesky m2\n", "language": "Arturo" }, { "code": "%{^\n#include <math.h>\n#include <float.h>\n%}\n\n#include \"share/atspre_staload.hats\"\n\nmacdef NAN = g0f2f ($extval (float, \"NAN\"))\nmacdef Zero = g0i2f 0\nmacdef One = g0i2f 1\n\n(* The sqrt(3) function made part of the ‘g0float’ typekind series.\n (The ats2-xprelude package will do this for you, but it is easy\n to do if you are not using a lot of math functions. *)\nextern fn {tk : tkind} g0float_sqrt : g0float tk -<> g0float tk\noverload sqrt with g0float_sqrt\nimplement g0float_sqrt<fltknd> x = $extfcall (float, \"sqrtf\", x)\nimplement g0float_sqrt<dblknd> x = $extfcall (double, \"sqrt\", x)\nimplement g0float_sqrt<ldblknd> x = $extfcall (ldouble, \"sqrtl\", x)\n\n(*------------------------------------------------------------------*)\n(* A \"very little matrix library\" *)\n\ntypedef Matrix_Index_Map (m1 : int, n1 : int, m0 : int, n0 : int) =\n {i1, j1 : pos | i1 <= m1; j1 <= n1}\n (int i1, int j1) -<cloref0>\n [i0, j0 : pos | i0 <= m0; j0 <= n0]\n @(int i0, int j0)\n\ndatatype Real_Matrix (tk : tkind,\n m1 : int, n1 : int,\n m0 : int, n0 : int) =\n| Real_Matrix of (matrixref (g0float tk, m0, n0),\n int m1, int n1, int m0, int n0,\n Matrix_Index_Map (m1, n1, m0, n0))\ntypedef Real_Matrix (tk : tkind, m1 : int, n1 : int) =\n [m0, n0 : pos] Real_Matrix (tk, m1, n1, m0, n0)\ntypedef Real_Vector (tk : tkind, m1 : int, n1 : int) =\n [m1 == 1 || n1 == 1] Real_Matrix (tk, m1, n1)\ntypedef Real_Row (tk : tkind, n1 : int) = Real_Vector (tk, 1, n1)\ntypedef Real_Column (tk : tkind, m1 : int) = Real_Vector (tk, m1, 1)\n\nextern fn {tk : tkind}\nReal_Matrix_make_elt :\n {m0, n0 : pos}\n (int m0, int n0, g0float tk) -< !wrt >\n Real_Matrix (tk, m0, n0, m0, n0)\n\nextern fn {tk : tkind}\nReal_Matrix_copy :\n {m1, n1 : pos}\n Real_Matrix (tk, m1, n1) -< !refwrt > Real_Matrix (tk, m1, n1)\n\nextern fn {tk : tkind}\nReal_Matrix_copy_to :\n {m1, n1 : pos}\n (Real_Matrix (tk, m1, n1), (* destination *)\n Real_Matrix (tk, m1, n1)) -< !refwrt >\n void\n\nextern fn {}\nReal_Matrix_dimension :\n {tk : tkind}\n {m1, n1 : pos}\n Real_Matrix (tk, m1, n1) -<> @(int m1, int n1)\n\nextern fn {tk : tkind}\nReal_Matrix_get_at :\n {m1, n1 : pos}\n {i1, j1 : pos | i1 <= m1; j1 <= n1}\n (Real_Matrix (tk, m1, n1), int i1, int j1) -< !ref > g0float tk\n\nextern fn {tk : tkind}\nReal_Matrix_set_at :\n {m1, n1 : pos}\n {i1, j1 : pos | i1 <= m1; j1 <= n1}\n (Real_Matrix (tk, m1, n1), int i1, int j1, g0float tk) -< !refwrt >\n void\n\nextern fn {}\nReal_Matrix_reflect_lower_triangle :\n (* This operation makes every It is a change in how INDEXING\n works. All the storage is still in the lower triangle. *)\n {tk : tkind}\n {n1 : pos}\n {m0, n0 : pos}\n Real_Matrix (tk, n1, n1, m0, n0) -<>\n Real_Matrix (tk, n1, n1, m0, n0)\n\nextern fn {tk : tkind}\nReal_Matrix_fprint :\n {m, n : pos}\n (FILEref, Real_Matrix (tk, m, n)) -<1> void\n\noverload copy with Real_Matrix_copy\noverload copy_to with Real_Matrix_copy_to\noverload dimension with Real_Matrix_dimension\noverload [] with Real_Matrix_get_at\noverload [] with Real_Matrix_set_at\noverload reflect_lower_triangle with\n Real_Matrix_reflect_lower_triangle\n\n(*------------------------------------------------------------------*)\n(* Implementation of the \"very little matrix library\" *)\n\nimplement {tk}\nReal_Matrix_make_elt (m0, n0, elt) =\n Real_Matrix (matrixref_make_elt<g0float tk> (i2sz m0, i2sz n0, elt),\n m0, n0, m0, n0, lam (i1, j1) => @(i1, j1))\n\nimplement {}\nReal_Matrix_dimension A =\n case+ A of Real_Matrix (_, m1, n1, _, _, _) => @(m1, n1)\n\nimplement {tk}\nReal_Matrix_get_at (A, i1, j1) =\n let\n val+ Real_Matrix (storage, _, _, _, n0, index_map) = A\n val @(i0, j0) = index_map (i1, j1)\n in\n matrixref_get_at<g0float tk> (storage, pred i0, n0, pred j0)\n end\n\nimplement {tk}\nReal_Matrix_set_at (A, i1, j1, x) =\n let\n val+ Real_Matrix (storage, _, _, _, n0, index_map) = A\n val @(i0, j0) = index_map (i1, j1)\n in\n matrixref_set_at<g0float tk> (storage, pred i0, n0, pred j0, x)\n end\n\nimplement {}\nReal_Matrix_reflect_lower_triangle {..} {n1} A =\n let\n typedef t = intBtwe (1, n1)\n val+ Real_Matrix (storage, n1, _, m0, n0, index_map) = A\n in\n Real_Matrix (storage, n1, n1, m0, n0,\n lam (i, j) =>\n index_map ((if j <= i then i else j) : t,\n (if j <= i then j else i) : t))\n end\n\nimplement {tk}\nReal_Matrix_copy A =\n let\n val @(m1, n1) = dimension A\n val C = Real_Matrix_make_elt<tk> (m1, n1, A[1, 1])\n val () = copy_to<tk> (C, A)\n in\n C\n end\n\nimplement {tk}\nReal_Matrix_copy_to (Dst, Src) =\n let\n val @(m1, n1) = dimension Src\n prval [m1 : int] EQINT () = eqint_make_gint m1\n prval [n1 : int] EQINT () = eqint_make_gint n1\n\n var i : intGte 1\n in\n for* {i : pos | i <= m1 + 1} .<(m1 + 1) - i>.\n (i : int i) =>\n (i := 1; i <> succ m1; i := succ i)\n let\n var j : intGte 1\n in\n for* {j : pos | j <= n1 + 1} .<(n1 + 1) - j>.\n (j : int j) =>\n (j := 1; j <> succ n1; j := succ j)\n Dst[i, j] := Src[i, j]\n end\n end\n\nimplement {tk}\nReal_Matrix_fprint {m, n} (outf, A) =\n let\n val @(m, n) = dimension A\n var i : intGte 1\n in\n for* {i : pos | i <= m + 1} .<(m + 1) - i>.\n (i : int i) =>\n (i := 1; i <> succ m; i := succ i)\n let\n var j : intGte 1\n in\n for* {j : pos | j <= n + 1} .<(n + 1) - j>.\n (j : int j) =>\n (j := 1; j <> succ n; j := succ j)\n let\n typedef FILEstar = $extype\"FILE *\"\n extern castfn FILEref2star : FILEref -<> FILEstar\n val _ = $extfcall (int, \"fprintf\", FILEref2star outf,\n \"%16.6g\", A[i, j])\n in\n end;\n fprintln! (outf)\n end\n end\n\n(*------------------------------------------------------------------*)\n(* Cholesky-Banachiewicz, in place. See\n https://en.wikipedia.org/w/index.php?title=Cholesky_decomposition&oldid=1149960985#The_Cholesky%E2%80%93Banachiewicz_and_Cholesky%E2%80%93Crout_algorithms\n\n I would use Cholesky-Crout if my matrices were stored in column\n major order. But it makes little difference. *)\n\nextern fn {tk : tkind}\nReal_Matrix_cholesky_decomposition :\n (* Only the lower triangle is considered. *)\n {n : pos}\n Real_Matrix (tk, n, n) -< !refwrt > void\n\noverload cholesky_decomposition with\n Real_Matrix_cholesky_decomposition\n\nimplement {tk}\nReal_Matrix_cholesky_decomposition {n} A =\n let\n val @(n, _) = dimension A\n\n (* I arrange the nested loops somewhat differently from how it is\n done in the Wikipedia article's C snippet. *)\n fun\n repeat {i, j : pos | j <= i; i <= n + 1} (* <-- allowed values *)\n .<(n + 1) - i, i - j>. (* <-- proof of termination *)\n (i : int i, j : int j) :<!refwrt> void =\n if i = n + 1 then\n () (* All done. *)\n else\n let\n fun\n _sum {k : pos | k <= j} .<j - k>.\n (x : g0float tk, k : int k) :<!refwrt> g0float tk =\n if k = j then\n x\n else\n _sum (x + (A[i, k] * A[j, k]), succ k)\n\n val sum = _sum (Zero, 1)\n in\n if j = i then\n begin\n A[i, j] := sqrt (A[i, i] - sum);\n repeat (succ i, 1)\n end\n else\n begin\n A[i, j] := (One / A[j, j]) * (A[i, j] - sum);\n repeat (i, succ j)\n end\n end\n in\n repeat (1, 1)\n end\n\n(*------------------------------------------------------------------*)\n\nfn {tk : tkind} (* We like Fortran, so COLUMN major here. *)\ncolumn_major_list_to_square_matrix\n {n : pos}\n (n : int n,\n lst : list (g0float tk, n * n))\n : Real_Matrix (tk, n, n) =\n let\n #define :: list_cons\n prval () = mul_gte_gte_gte {n, n} ()\n val A = Real_Matrix_make_elt (n, n, NAN)\n val lstref : ref (List0 (g0float tk)) = ref lst\n var j : intGte 1\n in\n for* {j : pos | j <= n + 1} .<(n + 1) - j>.\n (j : int j) =>\n (j := 1; j <> succ n; j := succ j)\n let\n var i : intGte 1\n in\n for* {i : pos | i <= n + 1} .<(n + 1) - i>.\n (i : int i) =>\n (i := 1; i <> succ n; i := succ i)\n case- !lstref of\n | hd :: tl =>\n begin\n A[i, j] := hd;\n !lstref := tl\n end\n end;\n A\n end\n\nimplement\nmain0 () =\n let\n val _A =\n column_major_list_to_square_matrix\n (3, $list (25.0, 15.0, ~5.0,\n 0.0, 18.0, 0.0,\n 0.0, 0.0, 11.0))\n val A = reflect_lower_triangle _A\n and B = copy _A\n val () =\n begin\n cholesky_decomposition B;\n print! (\"\\nThe Cholesky decomposition of\\n\\n\");\n Real_Matrix_fprint (stdout_ref, A);\n print! (\"is\\n\");\n Real_Matrix_fprint (stdout_ref, B)\n end\n\n val _A =\n column_major_list_to_square_matrix\n (4, $list (18.0, 22.0, 54.0, 42.0,\n 0.0, 70.0, 86.0, 62.0,\n 0.0, 0.0, 174.0, 134.0,\n 0.0, 0.0, 0.0, 106.0))\n val A = reflect_lower_triangle _A\n and B = copy _A\n val () =\n begin\n cholesky_decomposition B;\n print! (\"\\nThe Cholesky decomposition of\\n\\n\");\n Real_Matrix_fprint (stdout_ref, A);\n print! (\"is\\n\");\n Real_Matrix_fprint (stdout_ref, B)\n end\n in\n println! ()\n end\n\n(*------------------------------------------------------------------*)\n", "language": "ATS" }, { "code": "Cholesky_Decomposition(A){\n L := [], n := A.Count()\n L[1,1] := Sqrt(A[1,1])\n loop % n {\n k := A_Index\n loop % n-1 {\n i := A_Index+1\n\n Sigma := 0, j := 0\n while (++j <= k-1)\n Sigma += L[i, j] * L[k, j]\n L[i, k] := (A[i, k] - Sigma) / L[k, k]\n\n Sigma := 0, j := 0\n while (++j <= k-1)\n Sigma += (L[k, j])**2\n L[k, k] := Sqrt(A[k, k] - Sigma)\n }\n }\n loop % n{\n k := A_Index\n loop % n\n L[k, A_Index] := L[k, A_Index] ? L[k, A_Index] : 0\n }\n return L\n}\nShowMatrix(L){\n for r, obj in L{\n row := \"\"\n for c, v in obj\n row .= Format(\"{:.3f}\", v) \", \"\n output .= \"[\" trim(row, \", \") \"]`n,\"\n }\n return \"[\" Trim(output, \"`n,\") \"]\"\n}\n", "language": "AutoHotkey" }, { "code": "A := [[25, 15, -5]\n , [15, 18, 0]\n , [-5, 0 , 11]]\nL1 := Cholesky_Decomposition(A)\n\nA := [[18, 22, 54, 42]\n , [22, 70, 86, 62]\n , [54, 86, 174, 134]\n , [42, 62, 134, 106]]\nL2 := Cholesky_Decomposition(A)\n\nMsgBox % Result := ShowMatrix(L1) \"`n----`n\" ShowMatrix(L2) \"`n----\"\nreturn\n", "language": "AutoHotkey" }, { "code": " DIM m1(2,2)\n m1() = 25, 15, -5, \\\n \\ 15, 18, 0, \\\n \\ -5, 0, 11\n PROCcholesky(m1())\n PROCprint(m1())\n PRINT\n\n @% = &2050A\n DIM m2(3,3)\n m2() = 18, 22, 54, 42, \\\n \\ 22, 70, 86, 62, \\\n \\ 54, 86, 174, 134, \\\n \\ 42, 62, 134, 106\n PROCcholesky(m2())\n PROCprint(m2())\n END\n\n DEF PROCcholesky(a())\n LOCAL i%, j%, k%, l(), s\n DIM l(DIM(a(),1),DIM(a(),2))\n FOR i% = 0 TO DIM(a(),1)\n FOR j% = 0 TO i%\n s = 0\n FOR k% = 0 TO j%-1\n s += l(i%,k%) * l(j%,k%)\n NEXT\n IF i% = j% THEN\n l(i%,j%) = SQR(a(i%,i%) - s)\n ELSE\n l(i%,j%) = (a(i%,j%) - s) / l(j%,j%)\n ENDIF\n NEXT j%\n NEXT i%\n a() = l()\n ENDPROC\n\n DEF PROCprint(a())\n LOCAL row%, col%\n FOR row% = 0 TO DIM(a(),1)\n FOR col% = 0 TO DIM(a(),2)\n PRINT a(row%,col%);\n NEXT\n PRINT\n NEXT row%\n ENDPROC\n", "language": "BBC-BASIC" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ndouble *cholesky(double *A, int n) {\n double *L = (double*)calloc(n * n, sizeof(double));\n if (L == NULL)\n exit(EXIT_FAILURE);\n\n for (int i = 0; i < n; i++)\n for (int j = 0; j < (i+1); j++) {\n double s = 0;\n for (int k = 0; k < j; k++)\n s += L[i * n + k] * L[j * n + k];\n L[i * n + j] = (i == j) ?\n sqrt(A[i * n + i] - s) :\n (1.0 / L[j * n + j] * (A[i * n + j] - s));\n }\n\n return L;\n}\n\nvoid show_matrix(double *A, int n) {\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++)\n printf(\"%2.5f \", A[i * n + j]);\n printf(\"\\n\");\n }\n}\n\nint main() {\n int n = 3;\n double m1[] = {25, 15, -5,\n 15, 18, 0,\n -5, 0, 11};\n double *c1 = cholesky(m1, n);\n show_matrix(c1, n);\n printf(\"\\n\");\n free(c1);\n\n n = 4;\n double m2[] = {18, 22, 54, 42,\n 22, 70, 86, 62,\n 54, 86, 174, 134,\n 42, 62, 134, 106};\n double *c2 = cholesky(m2, n);\n show_matrix(c2, n);\n free(c2);\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <cassert>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n matrix(size_t rows, size_t columns)\n : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n matrix(size_t rows, size_t columns, scalar_type value)\n : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n matrix(size_t rows, size_t columns,\n const std::initializer_list<std::initializer_list<scalar_type>>& values)\n : rows_(rows), columns_(columns), elements_(rows * columns) {\n assert(values.size() <= rows_);\n size_t i = 0;\n for (const auto& row : values) {\n assert(row.size() <= columns_);\n std::copy(begin(row), end(row), &elements_[i]);\n i += columns_;\n }\n }\n\n size_t rows() const { return rows_; }\n size_t columns() const { return columns_; }\n\n const scalar_type& operator()(size_t row, size_t column) const {\n assert(row < rows_);\n assert(column < columns_);\n return elements_[row * columns_ + column];\n }\n scalar_type& operator()(size_t row, size_t column) {\n assert(row < rows_);\n assert(column < columns_);\n return elements_[row * columns_ + column];\n }\nprivate:\n size_t rows_;\n size_t columns_;\n std::vector<scalar_type> elements_;\n};\n\ntemplate <typename scalar_type>\nvoid print(std::ostream& out, const matrix<scalar_type>& a) {\n size_t rows = a.rows(), columns = a.columns();\n out << std::fixed << std::setprecision(5);\n for (size_t row = 0; row < rows; ++row) {\n for (size_t column = 0; column < columns; ++column) {\n if (column > 0)\n out << ' ';\n out << std::setw(9) << a(row, column);\n }\n out << '\\n';\n }\n}\n\ntemplate <typename scalar_type>\nmatrix<scalar_type> cholesky_factor(const matrix<scalar_type>& input) {\n assert(input.rows() == input.columns());\n size_t n = input.rows();\n matrix<scalar_type> result(n, n);\n for (size_t i = 0; i < n; ++i) {\n for (size_t k = 0; k < i; ++k) {\n scalar_type value = input(i, k);\n for (size_t j = 0; j < k; ++j)\n value -= result(i, j) * result(k, j);\n result(i, k) = value/result(k, k);\n }\n scalar_type value = input(i, i);\n for (size_t j = 0; j < i; ++j)\n value -= result(i, j) * result(i, j);\n result(i, i) = std::sqrt(value);\n }\n return result;\n}\n\nvoid print_cholesky_factor(const matrix<double>& matrix) {\n std::cout << \"Matrix:\\n\";\n print(std::cout, matrix);\n std::cout << \"Cholesky factor:\\n\";\n print(std::cout, cholesky_factor(matrix));\n}\n\nint main() {\n matrix<double> matrix1(3, 3,\n {{25, 15, -5},\n {15, 18, 0},\n {-5, 0, 11}});\n print_cholesky_factor(matrix1);\n\n matrix<double> matrix2(4, 4,\n {{18, 22, 54, 42},\n {22, 70, 86, 62},\n {54, 86, 174, 134},\n {42, 62, 134, 106}});\n print_cholesky_factor(matrix2);\n\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Cholesky\n{\n class Program\n {\n /// <summary>\n /// This is example is written in C#, and compiles with .NET Framework 4.0\n /// </summary>\n /// <param name=\"args\"></param>\n static void Main(string[] args)\n {\n double[,] test1 = new double[,]\n {\n {25, 15, -5},\n {15, 18, 0},\n {-5, 0, 11},\n };\n\n double[,] test2 = new double[,]\n {\n {18, 22, 54, 42},\n {22, 70, 86, 62},\n {54, 86, 174, 134},\n {42, 62, 134, 106},\n };\n\n double[,] chol1 = Cholesky(test1);\n double[,] chol2 = Cholesky(test2);\n\n Console.WriteLine(\"Test 1: \");\n Print(test1);\n Console.WriteLine(\"\");\n Console.WriteLine(\"Lower Cholesky 1: \");\n Print(chol1);\n Console.WriteLine(\"\");\n Console.WriteLine(\"Test 2: \");\n Print(test2);\n Console.WriteLine(\"\");\n Console.WriteLine(\"Lower Cholesky 2: \");\n Print(chol2);\n\n }\n\n public static void Print(double[,] a)\n {\n int n = (int)Math.Sqrt(a.Length);\n\n StringBuilder sb = new StringBuilder();\n for (int r = 0; r < n; r++)\n {\n string s = \"\";\n for (int c = 0; c < n; c++)\n {\n s += a[r, c].ToString(\"f5\").PadLeft(9) + \",\";\n }\n sb.AppendLine(s);\n }\n\n Console.WriteLine(sb.ToString());\n }\n\n /// <summary>\n /// Returns the lower Cholesky Factor, L, of input matrix A.\n /// Satisfies the equation: L*L^T = A.\n /// </summary>\n /// <param name=\"a\">Input matrix must be square, symmetric,\n /// and positive definite. This method does not check for these properties,\n /// and may produce unexpected results of those properties are not met.</param>\n /// <returns></returns>\n public static double[,] Cholesky(double[,] a)\n {\n int n = (int)Math.Sqrt(a.Length);\n\n double[,] ret = new double[n, n];\n for (int r = 0; r < n; r++)\n for (int c = 0; c <= r; c++)\n {\n if (c == r)\n {\n double sum = 0;\n for (int j = 0; j < c; j++)\n {\n sum += ret[c, j] * ret[c, j];\n }\n ret[c, c] = Math.Sqrt(a[c, c] - sum);\n }\n else\n {\n double sum = 0;\n for (int j = 0; j < c; j++)\n sum += ret[r, j] * ret[c, j];\n ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum);\n }\n }\n\n return ret;\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(defn cholesky\n [matrix]\n (let [n (count matrix)\n A (to-array-2d matrix)\n L (make-array Double/TYPE n n)]\n (doseq [i (range n) j (range (inc i))]\n (let [s (reduce + (for [k (range j)] (* (aget L i k) (aget L j k))))]\n (aset L i j (if (= i j)\n (Math/sqrt (- (aget A i i) s))\n (* (/ 1.0 (aget L j j)) (- (aget A i j) s))))))\n (vec (map vec L))))\n", "language": "Clojure" }, { "code": "(cholesky [[25 15 -5] [15 18 0] [-5 0 11]])\n;=> [[ 5.0 0.0 0.0]\n; [ 3.0 3.0 0.0]\n; [-1.0 1.0 3.0]]\n\n(cholesky [[18 22 54 42] [22 70 86 62] [54 86 174 134] [42 62 134 106]])\n;=> [[ 4.242640687119285 0.0 0.0 0.0 ]\n; [ 5.185449728701349 6.565905201197403 0.0 0.0 ]\n; [12.727922061357857 3.0460384954008553 1.6497422479090704 0.0 ]\n; [ 9.899494936611667 1.624553864213788 1.8497110052313648 1.3926212476456026]]\n", "language": "Clojure" }, { "code": ";; Calculates the Cholesky decomposition matrix L\n;; for a positive-definite, symmetric nxn matrix A.\n(defun chol (A)\n (let* ((n (car (array-dimensions A)))\n (L (make-array `(,n ,n) :initial-element 0)))\n\n (do ((k 0 (incf k))) ((> k (- n 1)) nil)\n ;; First, calculate diagonal elements L_kk.\n (setf (aref L k k)\n (sqrt (- (aref A k k)\n (do* ((j 0 (incf j))\n (sum (expt (aref L k j) 2)\n (incf sum (expt (aref L k j) 2))))\n ((> j (- k 1)) sum)))))\n\n ;; Then, all elements below a diagonal element, L_ik, i=k+1..n.\n (do ((i (+ k 1) (incf i)))\n ((> i (- n 1)) nil)\n\n (setf (aref L i k)\n (/ (- (aref A i k)\n (do* ((j 0 (incf j))\n (sum (* (aref L i j) (aref L k j))\n (incf sum (* (aref L i j) (aref L k j)))))\n ((> j (- k 1)) sum)))\n (aref L k k)))))\n\n ;; Return the calculated matrix L.\n L))\n", "language": "Common-Lisp" }, { "code": ";; Example 1:\n(setf A (make-array '(3 3) :initial-contents '((25 15 -5) (15 18 0) (-5 0 11))))\n(chol A)\n#2A((5.0 0 0)\n (3.0 3.0 0)\n (-1.0 1.0 3.0))\n", "language": "Common-Lisp" }, { "code": ";; Example 2:\n(setf B (make-array '(4 4) :initial-contents '((18 22 54 42) (22 70 86 62) (54 86 174 134) (42 62 134 106))))\n(chol B)\n#2A((4.2426405 0 0 0)\n (5.18545 6.565905 0 0)\n (12.727922 3.0460374 1.6497375 0)\n (9.899495 1.6245536 1.849715 1.3926151))\n", "language": "Common-Lisp" }, { "code": ";; case of matrix stored as a list of lists (inner lists are rows of matrix)\n;; as above, returns the Cholesky decomposition matrix of a square positive-definite, symmetric matrix\n(defun cholesky (m)\n (let ((l (list (list (sqrt (caar m))))) x (j 0) i)\n (dolist (cm (cdr m) (mapcar #'(lambda (x) (nconc x (make-list (- (length m) (length x)) :initial-element 0))) l))\n (setq x (list (/ (car cm) (caar l))) i 0)\n (dolist (cl (cdr l))\n (setf (cdr (last x)) (list (/ (- (elt cm (incf i)) (*v x cl)) (car (last cl))))))\n (setf (cdr (last l)) (list (nconc x (list (sqrt (- (elt cm (incf j)) (*v x x))))))))))\n;; where *v is the scalar product defined as\n(defun *v (v1 v2) (reduce #'+ (mapcar #'* v1 v2)))\n", "language": "Common-Lisp" }, { "code": ";; example 1\nCL-USER> (setf a '((25 15 -5) (15 18 0) (-5 0 11)))\n((25 15 -5) (15 18 0) (-5 0 11))\nCL-USER> (cholesky a)\n((5 0 0) (3 3 0) (-1 1 3))\nCL-USER> (format t \"~{~{~5d~}~%~}\" (cholesky a))\n 5 0 0\n 3 3 0\n -1 1 3\nNIL\n", "language": "Common-Lisp" }, { "code": ";; example 2\nCL-USER> (setf a '((18 22 54 42) (22 70 86 62) (54 86 174 134) (42 62 134 106)))\n((18 22 54 42) (22 70 86 62) (54 86 174 134) (42 62 134 106))\nCL-USER> (cholesky a)\n((4.2426405 0 0 0) (5.18545 6.565905 0 0) (12.727922 3.0460374 1.6497375 0) (9.899495 1.6245536 1.849715 1.3926151))\nCL-USER> (format t \"~{~{~10,5f~}~%~}\" (cholesky a))\n 4.24264 0.00000 0.00000 0.00000\n 5.18545 6.56591 0.00000 0.00000\n 12.72792 3.04604 1.64974 0.00000\n 9.89950 1.62455 1.84971 1.39262\nNIL\n", "language": "Common-Lisp" }, { "code": "import std.stdio, std.math, std.numeric;\n\nT[][] cholesky(T)(in T[][] A) pure nothrow /*@safe*/ {\n auto L = new T[][](A.length, A.length);\n foreach (immutable r, row; L)\n row[r + 1 .. $] = 0;\n foreach (immutable i; 0 .. A.length)\n foreach (immutable j; 0 .. i + 1) {\n auto t = dotProduct(L[i][0 .. j], L[j][0 .. j]);\n L[i][j] = (i == j) ? (A[i][i] - t) ^^ 0.5 :\n (1.0 / L[j][j] * (A[i][j] - t));\n }\n return L;\n}\n\nvoid main() {\n immutable double[][] m1 = [[25, 15, -5],\n [15, 18, 0],\n [-5, 0, 11]];\n writefln(\"%(%(%2.0f %)\\n%)\\n\", m1.cholesky);\n\n immutable double[][] m2 = [[18, 22, 54, 42],\n [22, 70, 86, 62],\n [54, 86, 174, 134],\n [42, 62, 134, 106]];\n writefln(\"%(%(%2.3f %)\\n%)\", m2.cholesky);\n}\n", "language": "D" }, { "code": "function Cholesky(a : array of Float) : array of Float;\nvar\n i, j, k, n : Integer;\n s : Float;\nbegin\n n:=Round(Sqrt(a.Length));\n Result:=new Float[n*n];\n for i:=0 to n-1 do begin\n for j:=0 to i do begin\n s:=0 ;\n for k:=0 to j-1 do\n s+=Result[i*n+k] * Result[j*n+k];\n if i=j then\n Result[i*n+j]:=Sqrt(a[i*n+i]-s)\n else Result[i*n+j]:=1/Result[j*n+j]*(a[i*n+j]-s);\n end;\n end;\nend;\n\nprocedure ShowMatrix(a : array of Float);\nvar\n i, j, n : Integer;\nbegin\n n:=Round(Sqrt(a.Length));\n for i:=0 to n-1 do begin\n for j:=0 to n-1 do\n Print(Format('%2.5f ', [a[i*n+j]]));\n PrintLn('');\n end;\nend;\n\nvar m1 := new Float[9];\nm1 := [ 25.0, 15.0, -5.0,\n 15.0, 18.0, 0.0,\n -5.0, 0.0, 11.0 ];\nvar c1 := Cholesky(m1);\nShowMatrix(c1);\n\nPrintLn('');\n\nvar m2 : array of Float := [ 18.0, 22.0, 54.0, 42.0,\n 22.0, 70.0, 86.0, 62.0,\n 54.0, 86.0, 174.0, 134.0,\n 42.0, 62.0, 134.0, 106.0 ];\nvar c2 := Cholesky(m2);\nShowMatrix(c2);\n", "language": "DWScript" }, { "code": "open Microsoft.FSharp.Collections\n\nlet cholesky a =\n let calc (a: float[,]) (l: float[,]) i j =\n let c1 j =\n let sum = List.sumBy (fun k -> l.[j, k] ** 2.0) [0..j - 1]\n sqrt (a.[j, j] - sum)\n let c2 i j =\n let sum = List.sumBy (fun k -> l.[i, k] * l.[j, k]) [0..j - 1]\n (1.0 / l.[j, j]) * (a.[i, j] - sum)\n if j > i then 0.0 else\n if i = j\n then c1 j\n else c2 i j\n let l = Array2D.zeroCreate (Array2D.length1 a) (Array2D.length2 a)\n Array2D.iteri (fun i j _ -> l.[i, j] <- calc a l i j) l\n l\n\nlet printMat a =\n let arrow = (Array2D.length2 a |> float) / 2.0 |> int\n let c = cholesky a\n for row in 0..(Array2D.length1 a) - 1 do\n for col in 0..(Array2D.length2 a) - 1 do\n printf \"%.5f,\\t\" a.[row, col]\n printf (if arrow = row then \"--> \\t\" else \"\\t\\t\")\n for col in 0..(Array2D.length2 c) - 1 do\n printf \"%.5f,\\t\" c.[row, col]\n printfn \"\"\n\nlet ex1 = array2D [\n [25.0; 15.0; -5.0];\n [15.0; 18.0; 0.0];\n [-5.0; 0.0; 11.0]]\n\nlet ex2 = array2D [\n [18.0; 22.0; 54.0; 42.0];\n [22.0; 70.0; 86.0; 62.0];\n [54.0; 86.0; 174.0; 134.0];\n [42.0; 62.0; 134.0; 106.0]]\n\nprintfn \"ex1:\"\nprintMat ex1\n\nprintfn \"ex2:\"\nprintMat ex2\n", "language": "F-Sharp" }, { "code": "**\n** Cholesky decomposition\n**\n\nclass Main\n{\n // create an array of Floats, initialised to 0.0\n Float[][] makeArray (Int i, Int j)\n {\n Float[][] result := [,]\n i.times { result.add ([,]) }\n i.times |Int x|\n {\n j.times\n {\n result[x].add(0f)\n }\n }\n return result\n }\n\n // perform the Cholesky decomposition\n Float[][] cholesky (Float[][] array)\n {\n m := array.size\n Float[][] l := makeArray (m, m)\n m.times |Int i|\n {\n (i+1).times |Int k|\n {\n Float sum := (0..<k).toList.reduce (0f) |Float a, Int j -> Float|\n {\n a + l[i][j] * l[k][j]\n }\n if (i == k)\n l[i][k] = (array[i][i]-sum).sqrt\n else\n l[i][k] = (1.0f / l[k][k]) * (array[i][k] - sum)\n }\n }\n return l\n }\n\n Void runTest (Float[][] array)\n {\n echo (array)\n echo (cholesky (array))\n }\n\n Void main ()\n {\n runTest ([[25f,15f,-5f],[15f,18f,0f],[-5f,0f,11f]])\n runTest ([[18f,22f,54f,42f],[22f,70f,86f,62f],[54f,86f,174f,134f],[42f,62f,134f,106f]])\n }\n}\n", "language": "Fantom" }, { "code": "Program Cholesky_decomp\n! *************************************************!\n! LBH @ ULPGC 06/03/2014\n! Compute the Cholesky decomposition for a matrix A\n! after the attached\n! http://rosettacode.org/wiki/Cholesky_decomposition\n! note that the matrix A is complex since there might\n! be values, where the sqrt has complex solutions.\n! Here, only the real values are taken into account\n!*************************************************!\nimplicit none\n\nINTEGER, PARAMETER :: m=3 !rows\nINTEGER, PARAMETER :: n=3 !cols\nCOMPLEX, DIMENSION(m,n) :: A\nREAL, DIMENSION(m,n) :: L\nREAL :: sum1, sum2\nINTEGER i,j,k\n\n! Assign values to the matrix\nA(1,:)=(/ 25, 15, -5 /)\nA(2,:)=(/ 15, 18, 0 /)\nA(3,:)=(/ -5, 0, 11 /)\n! !!!!!!!!!!!another example!!!!!!!\n! A(1,:) = (/ 18, 22, 54, 42 /)\n! A(2,:) = (/ 22, 70, 86, 62 /)\n! A(3,:) = (/ 54, 86, 174, 134 /)\n! A(4,:) = (/ 42, 62, 134, 106 /)\n\n\n\n\n\n! Initialize values\nL(1,1)=real(sqrt(A(1,1)))\nL(2,1)=A(2,1)/L(1,1)\nL(2,2)=real(sqrt(A(2,2)-L(2,1)*L(2,1)))\nL(3,1)=A(3,1)/L(1,1)\n! for greater order than m,n=3 add initial row value\n! for instance if m,n=4 then add the following line\n! L(4,1)=A(4,1)/L(1,1)\n\n\n\n\n\ndo i=1,n\n do k=1,i\n sum1=0\n sum2=0\n do j=1,k-1\n if (i==k) then\n sum1=sum1+(L(k,j)*L(k,j))\n L(k,k)=real(sqrt(A(k,k)-sum1))\n elseif (i > k) then\n sum2=sum2+(L(i,j)*L(k,j))\n L(i,k)=(1/L(k,k))*(A(i,k)-sum2)\n else\n L(i,k)=0\n end if\n end do\n end do\nend do\n\n! write output\ndo i=1,m\n print \"(3(1X,F6.1))\",L(i,:)\nend do\n\nEnd program Cholesky_decomp\n", "language": "Fortran" }, { "code": "' version 18-01-2017\n' compile with: fbc -s console\n\nSub Cholesky_decomp(array() As Double)\n\n Dim As Integer i, j, k\n Dim As Double s, l(UBound(array), UBound(array, 2))\n\n For i = 0 To UBound(array)\n For j = 0 To i\n s = 0\n For k = 0 To j -1\n s += l(i, k) * l(j, k)\n Next\n If i = j Then\n l(i, j) = Sqr(array(i, i) - s)\n Else\n l(i, j) = (array(i, j) - s) / l(j, j)\n End If\n Next\n Next\n\n For i = 0 To UBound(array)\n For j = 0 To UBound(array, 2)\n Swap array(i, j), l(i, j)\n Next\n Next\n\nEnd Sub\n\nSub Print_(array() As Double)\n\n Dim As Integer i, j\n\n For i = 0 To UBound(array)\n For j = 0 To UBound(array, 2)\n Print Using \"###.#####\";array(i,j);\n Next\n Print\n Next\n\nEnd Sub\n\n' ------=< MAIN >=------\n\nDim m1(2,2) As Double => {{25, 15, -5}, _\n {15, 18, 0}, _\n {-5, 0, 11}}\n\nDim m2(3, 3) As Double => {{18, 22, 54, 42}, _\n {22, 70, 86, 62}, _\n {54, 86, 174, 134}, _\n {42, 62, 134, 106}}\n\nCholesky_decomp(m1())\nPrint_(m1())\n\nPrint\nCholesky_decomp(m2())\nPrint_(m2())\n\n' empty keyboard buffer\nWhile Inkey <> \"\" : Wend\nPrint : Print \"hit any key to end program\"\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "Cholesky[array] :=\n{\n n = length[array]\n L = new array[[n,n], 0]\n\n for j = 0 to n-1\n {\n sum = 0\n for k = 0 to j-1\n sum = sum + (L@j@k)^2\n\n L@j@j = sqrt[array@j@j - sum]\n\n for i = j+1 to n-1\n {\n sum = 0\n for k = 0 to j-1\n sum = sum + L@i@k * L@j@k\n\n L@i@j = (1 / L@j@j * (array@i@j -sum))\n }\n }\n\n return L\n}\n\nA = [[ 25, 15, -5],\n [ 15, 18, 0],\n [ -5, 0, 11]]\n\nprintln[formatTable[[[formatMatrix[A], \"->\", formatMatrix[Cholesky[A]]]]]]\n\nB = [[18, 22, 54, 42],\n [22, 70, 86, 62],\n [54, 86, 174, 134],\n [42, 62, 134, 106]]\n\nprintln[formatTable[[[formatMatrix[B], \"->\", formatMatrix[formatFix[Cholesky[B], 1, 5]]]]]]\n", "language": "Frink" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\n// symmetric and lower use a packed representation that stores only\n// the lower triangle.\n\ntype symmetric struct {\n order int\n ele []float64\n}\n\ntype lower struct {\n order int\n ele []float64\n}\n\n// symmetric.print prints a square matrix from the packed representation,\n// printing the upper triange as a transpose of the lower.\nfunc (s *symmetric) print() {\n const eleFmt = \"%10.5f \"\n row, diag := 1, 0\n for i, e := range s.ele {\n fmt.Printf(eleFmt, e)\n if i == diag {\n for j, col := diag+row, row; col < s.order; j += col {\n fmt.Printf(eleFmt, s.ele[j])\n col++\n }\n fmt.Println()\n row++\n diag += row\n }\n }\n}\n\n// lower.print prints a square matrix from the packed representation,\n// printing the upper triangle as all zeros.\nfunc (l *lower) print() {\n const eleFmt = \"%10.5f \"\n row, diag := 1, 0\n for i, e := range l.ele {\n fmt.Printf(eleFmt, e)\n if i == diag {\n for j := row; j < l.order; j++ {\n fmt.Printf(eleFmt, 0.)\n }\n fmt.Println()\n row++\n diag += row\n }\n }\n}\n\n// choleskyLower returns the cholesky decomposition of a symmetric real\n// matrix. The matrix must be positive definite but this is not checked.\nfunc (a *symmetric) choleskyLower() *lower {\n l := &lower{a.order, make([]float64, len(a.ele))}\n row, col := 1, 1\n dr := 0 // index of diagonal element at end of row\n dc := 0 // index of diagonal element at top of column\n for i, e := range a.ele {\n if i < dr {\n d := (e - l.ele[i]) / l.ele[dc]\n l.ele[i] = d\n ci, cx := col, dc\n for j := i + 1; j <= dr; j++ {\n cx += ci\n ci++\n l.ele[j] += d * l.ele[cx]\n }\n col++\n dc += col\n } else {\n l.ele[i] = math.Sqrt(e - l.ele[i])\n row++\n dr += row\n col = 1\n dc = 0\n }\n }\n return l\n}\n\nfunc main() {\n demo(&symmetric{3, []float64{\n 25,\n 15, 18,\n -5, 0, 11}})\n demo(&symmetric{4, []float64{\n 18,\n 22, 70,\n 54, 86, 174,\n 42, 62, 134, 106}})\n}\n\nfunc demo(a *symmetric) {\n fmt.Println(\"A:\")\n a.print()\n fmt.Println(\"L:\")\n a.choleskyLower().print()\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math/cmplx\"\n)\n\ntype matrix struct {\n stride int\n ele []complex128\n}\n\nfunc like(a *matrix) *matrix {\n return &matrix{a.stride, make([]complex128, len(a.ele))}\n}\n\nfunc (m *matrix) print(heading string) {\n if heading > \"\" {\n fmt.Print(\"\\n\", heading, \"\\n\")\n }\n for e := 0; e < len(m.ele); e += m.stride {\n fmt.Printf(\"%7.2f \", m.ele[e:e+m.stride])\n fmt.Println()\n }\n}\n\nfunc (a *matrix) choleskyDecomp() *matrix {\n l := like(a)\n // Cholesky-Banachiewicz algorithm\n for r, rxc0 := 0, 0; r < a.stride; r++ {\n // calculate elements along row, up to diagonal\n x := rxc0\n for c, cxc0 := 0, 0; c < r; c++ {\n sum := a.ele[x]\n for k := 0; k < c; k++ {\n sum -= l.ele[rxc0+k] * cmplx.Conj(l.ele[cxc0+k])\n }\n l.ele[x] = sum / l.ele[cxc0+c]\n x++\n cxc0 += a.stride\n }\n // calcualate diagonal element\n sum := a.ele[x]\n for k := 0; k < r; k++ {\n sum -= l.ele[rxc0+k] * cmplx.Conj(l.ele[rxc0+k])\n }\n l.ele[x] = cmplx.Sqrt(sum)\n rxc0 += a.stride\n }\n return l\n}\n\nfunc main() {\n demo(\"A:\", &matrix{3, []complex128{\n 25, 15, -5,\n 15, 18, 0,\n -5, 0, 11,\n }})\n demo(\"A:\", &matrix{4, []complex128{\n 18, 22, 54, 42,\n 22, 70, 86, 62,\n 54, 86, 174, 134,\n 42, 62, 134, 106,\n }})\n // one more example, from the Numpy manual, with a non-real\n demo(\"A:\", &matrix{2, []complex128{\n 1, -2i,\n 2i, 5,\n }})\n}\n\nfunc demo(heading string, a *matrix) {\n a.print(heading)\n a.choleskyDecomp().print(\"Cholesky factor L:\")\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"fmt\"\n\n \"gonum.org/v1/gonum/mat\"\n)\n\nfunc cholesky(order int, elements []float64) fmt.Formatter {\n var c mat.Cholesky\n c.Factorize(mat.NewSymDense(order, elements))\n return mat.Formatted(c.LTo(nil))\n}\n\nfunc main() {\n fmt.Println(cholesky(3, []float64{\n 25, 15, -5,\n 15, 18, 0,\n -5, 0, 11,\n }))\n fmt.Printf(\"\\n%.5f\\n\", cholesky(4, []float64{\n 18, 22, 54, 42,\n 22, 70, 86, 62,\n 54, 86, 174, 134,\n 42, 62, 134, 106,\n }))\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"fmt\"\n\n mat \"github.com/skelterjohn/go.matrix\"\n)\n\nfunc main() {\n demo(mat.MakeDenseMatrix([]float64{\n 25, 15, -5,\n 15, 18, 0,\n -5, 0, 11,\n }, 3, 3))\n demo(mat.MakeDenseMatrix([]float64{\n 18, 22, 54, 42,\n 22, 70, 86, 62,\n 54, 86, 174, 134,\n 42, 62, 134, 106,\n }, 4, 4))\n}\n\nfunc demo(m *mat.DenseMatrix) {\n fmt.Println(\"A:\")\n fmt.Println(m)\n l, err := m.Cholesky()\n if err != nil {\n fmt.Println(err)\n return\n }\n fmt.Println(\"L:\")\n fmt.Println(l)\n}\n", "language": "Go" }, { "code": "def decompose = { a ->\n assert a.size > 0 && a[0].size == a.size\n def m = a.size\n def l = [].withEagerDefault { [].withEagerDefault { 0 } }\n (0..<m).each { i ->\n (0..i).each { k ->\n Number s = (0..<k).sum { j -> l[i][j] * l[k][j] } ?: 0\n l[i][k] = (i == k)\n ? Math.sqrt(a[i][i] - s)\n : (1.0 / l[k][k] * (a[i][k] - s))\n }\n }\n l\n}\n", "language": "Groovy" }, { "code": "def test1 = [[25, 15, -5],\n [15, 18, 0],\n [-5, 0, 11]]\n\ndef test2 = [[18, 22, 54, 42],\n [22, 70, 86, 62],\n [54, 86, 174, 134],\n [42, 62, 134, 106]];\n\n[test1,test2]. each { test ->\n println()\n decompose(test).each { println it[0..<(test.size)] }\n}\n", "language": "Groovy" }, { "code": "module Cholesky (Arr, cholesky) where\n\nimport Data.Array.IArray\nimport Data.Array.MArray\nimport Data.Array.Unboxed\nimport Data.Array.ST\n\ntype Idx = (Int,Int)\ntype Arr = UArray Idx Double\n\n-- Return the (i,j) element of the lower triangular matrix. (We assume the\n-- lower array bound is (0,0).)\nget :: Arr -> Arr -> Idx -> Double\nget a l (i,j) | i == j = sqrt $ a!(j,j) - dot\n | i > j = (a!(i,j) - dot) / l!(j,j)\n | otherwise = 0\n where dot = sum [l!(i,k) * l!(j,k) | k <- [0..j-1]]\n\n-- Return the lower triangular matrix of a Cholesky decomposition. We assume\n-- the input is a real, symmetric, positive-definite matrix, with lower array\n-- bounds of (0,0).\ncholesky :: Arr -> Arr\ncholesky a = let n = maxBnd a\n in runSTUArray $ do\n l <- thaw a\n mapM_ (update a l) [(i,j) | i <- [0..n], j <- [0..n]]\n return l\n where maxBnd = fst . snd . bounds\n update a l i = unsafeFreeze l >>= \\l' -> writeArray l i (get a l' i)\n", "language": "Haskell" }, { "code": "import Data.Array.IArray\nimport Data.List\nimport Cholesky\n\nfm _ [] = \"\"\nfm _ [x] = fst x\nfm width ((a,b):xs) = a ++ (take (width - b) $ cycle \" \") ++ (fm width xs)\n\nfmt width row (xs,[]) = fm width xs\nfmt width row (xs,ys) = fm width xs ++ \"\\n\" ++ fmt width row (splitAt row ys)\n\nshowMatrice row xs = ys where\n vs = map (\\s -> let sh = show s in (sh,length sh)) xs\n width = (maximum $ snd $ unzip vs) + 1\n ys = fmt width row (splitAt row vs)\n\nex1, ex2 :: Arr\nex1 = listArray ((0,0),(2,2)) [25, 15, -5,\n 15, 18, 0,\n -5, 0, 11]\n\nex2 = listArray ((0,0),(3,3)) [18, 22, 54, 42,\n 22, 70, 86, 62,\n 54, 86, 174, 134,\n 42, 62, 134, 106]\n\nmain :: IO ()\nmain = do\n putStrLn $ showMatrice 3 $ elems $ cholesky ex1\n putStrLn $ showMatrice 4 $ elems $ cholesky ex2\n", "language": "Haskell" }, { "code": "import Numeric.LinearAlgebra\n\na,b :: Matrix R\na = (3><3)\n [25, 15, -5\n ,15, 18, 0\n ,-5, 0, 11]\n\nb = (4><4)\n [ 18, 22, 54, 42\n , 22, 70, 86, 62\n , 54, 86,174,134\n , 42, 62,134,106]\n\nmain = do\n let sa = sym a\n sb = sym b\n print sa\n print $ chol sa\n print sb\n print $ chol sb\n print $ tr $ chol sb\n", "language": "Haskell" }, { "code": "procedure cholesky (array)\n result := make_square_array (*array)\n every (i := 1 to *array) do {\n every (k := 1 to i) do {\n sum := 0\n every (j := 1 to (k-1)) do {\n sum +:= result[i][j] * result[k][j]\n }\n if (i = k)\n then result[i][k] := sqrt(array[i][i] - sum)\n else result[i][k] := 1.0 / result[k][k] * (array[i][k] - sum)\n }\n }\n return result\nend\n\nprocedure make_square_array (n)\n result := []\n every (1 to n) do push (result, list(n, 0))\n return result\nend\n\nprocedure print_array (array)\n every (row := !array) do {\n every writes (!row || \" \")\n write ()\n }\nend\n\nprocedure do_cholesky (array)\n write (\"Input:\")\n print_array (array)\n result := cholesky (array)\n write (\"Result:\")\n print_array (result)\nend\n\nprocedure main ()\n do_cholesky ([[25,15,-5],[15,18,0],[-5,0,11]])\n do_cholesky ([[18,22,54,42],[22,70,86,62],[54,86,174,134],[42,62,134,106]])\nend\n", "language": "Icon" }, { "code": "module Main\n\nimport Data.Vect\n\nMatrix : Nat -> Nat -> Type -> Type\nMatrix m n t = Vect m (Vect n t)\n\n\nzeros : (m : Nat) -> (n : Nat) -> Matrix m n Double\nzeros m n = replicate m (replicate n 0.0)\n\n\nindexM : (Fin m, Fin n) -> Matrix m n t -> t\nindexM (i, j) a = index j (index i a)\n\n\nreplaceAtM : (Fin m, Fin n) -> t -> Matrix m n t -> Matrix m n t\nreplaceAtM (i, j) e a = replaceAt i (replaceAt j e (index i a)) a\n\n\nget : Matrix m m Double -> Matrix m m Double -> (Fin m, Fin m) -> Double\nget a l (i, j) {m} = if i == j then sqrt $ indexM (j, j) a - dot\n else if i > j then (indexM (i, j) a - dot) / indexM (j, j) l\n else 0.0\n\n where\n -- Obtain indicies 0 to j -1\n ks : List (Fin m)\n ks = case (findIndices (\\_ => True) a) of\n [] => []\n (x::xs) => init (x::xs)\n\n dot : Double\n dot = sum [(indexM (i, k) l) * (indexM (j, k) l) | k <- ks]\n\n\nupdateL : Matrix m m Double -> Matrix m m Double -> (Fin m, Fin m) -> Matrix m m Double\nupdateL a l idx = replaceAtM idx (get a l idx) l\n\n\ncholesky : Matrix m m Double -> Matrix m m Double\ncholesky a {m} =\n foldl (\\l',i =>\n foldl (\\l'',j => updateL a l'' (i, j)) l' (js i))\n l is\n where l = zeros m m\n\n is : List (Fin m)\n is = findIndices (\\_ => True) a\n\n js : Fin m -> List (Fin m)\n js n = filter (<= n) is\n\n\nex1 : Matrix 3 3 Double\nex1 = cholesky [[25.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]]\n\nex2 : Matrix 4 4 Double\nex2 = cholesky [[18.0, 22.0, 54.0, 42.0], [22.0, 70.0, 86.0, 62.0],\n [54.0, 86.0, 174.0, 134.0], [42.0, 62.0, 134.0, 106.0]]\n\nmain : IO ()\nmain = do\n print ex1\n putStrLn \"\\n\"\n print ex2\n putStrLn \"\\n\"\n", "language": "Idris" }, { "code": "mp=: +/ . * NB. matrix product\nh =: +@|: NB. conjugate transpose\n\ncholesky=: 3 : 0\n n=. #A=. y\n if. 1>:n do.\n assert. (A=|A)>0=A NB. check for positive definite\n %:A\n else.\n 'X Y t Z'=. , (;~n$(>.-:n){.1) <;.1 A\n L0=. cholesky X\n L1=. cholesky Z-(T=.(h Y) mp %.X) mp Y\n L0,(T mp L0),.L1\n end.\n)\n", "language": "J" }, { "code": " eg1=: 25 15 _5 , 15 18 0 ,: _5 0 11\n eg2=: 18 22 54 42 , 22 70 86 62 , 54 86 174 134 ,: 42 62 134 106\n cholesky eg1\n 5 0 0\n 3 3 0\n_1 1 3\n cholesky eg2\n4.24264 0 0 0\n5.18545 6.56591 0 0\n12.7279 3.04604 1.64974 0\n9.89949 1.62455 1.84971 1.39262\n", "language": "J" }, { "code": " load 'math/lapack'\n load 'math/lapack/potrf'\n potrf_jlapack_ eg1\n 5 0 0\n 3 3 0\n_1 1 3\n potrf_jlapack_ eg2\n4.24264 0 0 0\n5.18545 6.56591 0 0\n12.7279 3.04604 1.64974 0\n9.89949 1.62455 1.84971 1.39262\n", "language": "J" }, { "code": "import java.util.Arrays;\n\npublic class Cholesky {\n\tpublic static double[][] chol(double[][] a){\n\t\tint m = a.length;\n\t\tdouble[][] l = new double[m][m]; //automatically initialzed to 0's\n\t\tfor(int i = 0; i< m;i++){\n\t\t\tfor(int k = 0; k < (i+1); k++){\n\t\t\t\tdouble sum = 0;\n\t\t\t\tfor(int j = 0; j < k; j++){\n\t\t\t\t\tsum += l[i][j] * l[k][j];\n\t\t\t\t}\n\t\t\t\tl[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) :\n\t\t\t\t\t(1.0 / l[k][k] * (a[i][k] - sum));\n\t\t\t}\n\t\t}\n\t\treturn l;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tdouble[][] test1 = {{25, 15, -5},\n\t\t\t\t\t\t\t{15, 18, 0},\n\t\t\t\t\t\t\t{-5, 0, 11}};\n\t\tSystem.out.println(Arrays.deepToString(chol(test1)));\n\t\tdouble[][] test2 = {{18, 22, 54, 42},\n\t\t\t\t\t\t\t{22, 70, 86, 62},\n\t\t\t\t\t\t\t{54, 86, 174, 134},\n\t\t\t\t\t\t\t{42, 62, 134, 106}};\n\t\tSystem.out.println(Arrays.deepToString(chol(test2)));\n\t}\n}\n", "language": "Java" }, { "code": "const cholesky = function (array) {\n\tconst zeros = [...Array(array.length)].map( _ => Array(array.length).fill(0));\n\tconst L = zeros.map((row, r, xL) => row.map((v, c) => {\n\t\tconst sum = row.reduce((s, _, i) => i < c ? s + xL[r][i] * xL[c][i] : s, 0);\n\t\treturn xL[r][c] = c < r + 1 ? r === c ? Math.sqrt(array[r][r] - sum) : (array[r][c] - sum) / xL[c][c] : v;\n\t}));\n\treturn L;\n}\n\nlet arr3 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]];\nconsole.log(cholesky(arr3));\nlet arr4 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]];\nconsole.log(cholesky(arr4));\n", "language": "JavaScript" }, { "code": "# Create an m x n matrix\n def matrix(m; n; init):\n if m == 0 then []\n elif m == 1 then [range(0; n)] | map(init)\n elif m > 0 then\n matrix(1; n; init) as $row\n | [range(0; m)] | map( $row )\n else error(\"matrix\\(m);_;_) invalid\")\n end ;\n\n# Print a matrix neatly, each cell ideally occupying n spaces,\n# but without truncation\ndef neatly(n):\n def right: tostring | ( \" \" * (n-length) + .);\n . as $in\n | length as $length\n | reduce range (0; $length) as $i\n (\"\"; . + reduce range(0; $length) as $j\n (\"\"; \"\\(.) \\($in[$i][$j] | right )\" ) + \"\\n\" ) ;\n\ndef is_square:\n type == \"array\" and (map(type == \"array\") | all) and\n length == 0 or ( (.[0]|length) as $l | map(length == $l) | all) ;\n\n# This implementation of is_symmetric/0 uses a helper function that circumvents\n# limitations of jq 1.4:\ndef is_symmetric:\n # [matrix, i,j, len]\n def test:\n if .[1] > .[3] then true\n elif .[1] == .[2] then [ .[0], .[1] + 1, 0, .[3]] | test\n elif .[0][.[1]][.[2]] == .[0][.[2]][.[1]]\n then [ .[0], .[1], .[2]+1, .[3]] | test\n else false\n end;\n if is_square|not then false\n else [ ., 0, 0, length ] | test\n end ;\n", "language": "Jq" }, { "code": "def cholesky_factor:\n if is_symmetric then\n length as $length\n | . as $self\n | reduce range(0; $length) as $k\n ( matrix(length; length; 0); # the matrix that will hold the answer\n reduce range(0; $length) as $i\n (.;\n if $i == $k\n then (. as $lower\n | reduce range(0; $k) as $j\n (0; . + ($lower[$k][$j] | .*.) )) as $sum\n | .[$k][$k] = (($self[$k][$k] - $sum) | sqrt)\n elif $i > $k\n then (. as $lower\n | reduce range(0; $k) as $j\n (0; . + $lower[$i][$j] * $lower[$k][$j])) as $sum\n | .[$i][$k] = (($self[$k][$i] - $sum) / .[$k][$k] )\n else .\n end ))\n else error( \"cholesky_factor: matrix is not symmetric\" )\n end ;\n", "language": "Jq" }, { "code": " 4.242640687119285 0 0 0\n 5.185449728701349 6.565905201197403 0 0\n 12.727922061357857 3.0460384954008553 1.6497422479090704 0\n 9.899494936611665 1.6245538642137891 1.849711005231382 1.3926212476455924\n", "language": "Jq" }, { "code": "a = [25 15 5; 15 18 0; -5 0 11]\nb = [18 22 54 22; 22 70 86 62; 54 86 174 134; 42 62 134 106]\n\nprintln(a, \"\\n => \\n\", chol(a, :L))\nprintln(b, \"\\n => \\n\", chol(b, :L))\n", "language": "Julia" }, { "code": "// version 1.0.6\n\nfun cholesky(a: DoubleArray): DoubleArray {\n val n = Math.sqrt(a.size.toDouble()).toInt()\n val l = DoubleArray(a.size)\n var s: Double\n for (i in 0 until n)\n for (j in 0 .. i) {\n s = 0.0\n for (k in 0 until j) s += l[i * n + k] * l[j * n + k]\n l[i * n + j] = when {\n (i == j) -> Math.sqrt(a[i * n + i] - s)\n else -> 1.0 / l[j * n + j] * (a[i * n + j] - s)\n }\n }\n return l\n}\n\nfun showMatrix(a: DoubleArray) {\n val n = Math.sqrt(a.size.toDouble()).toInt()\n for (i in 0 until n) {\n for (j in 0 until n) print(\"%8.5f \".format(a[i * n + j]))\n println()\n }\n}\n\nfun main(args: Array<String>) {\n val m1 = doubleArrayOf(25.0, 15.0, -5.0,\n 15.0, 18.0, 0.0,\n -5.0, 0.0, 11.0)\n val c1 = cholesky(m1)\n showMatrix(c1)\n println()\n val m2 = doubleArrayOf(18.0, 22.0, 54.0, 42.0,\n 22.0, 70.0, 86.0, 62.0,\n 54.0, 86.0, 174.0, 134.0,\n 42.0, 62.0, 134.0, 106.0)\n val c2 = cholesky(m2)\n showMatrix(c2)\n}\n", "language": "Kotlin" }, { "code": "import std\n\n// choleskyLower returns the cholesky decomposition of a symmetric real\n// matrix. The matrix must be positive definite but this is not checked\ndef choleskyLower(order, a) -> [float]:\n let l = map(a.length): 0.0\n var row, col = 1, 1\n var dr = 0 // index of diagonal element at end of row\n var dc = 0 // index of diagonal element at top of column\n for(a) e, i:\n if i < dr:\n let d = (e - l[i]) / l[dc]\n l[i] = d\n var ci, cx = col, dc\n var j = i + 1\n while j <= dr:\n cx += ci\n ci += 1\n l[j] += d * l[cx]\n j += 1\n col += 1\n dc += col\n else:\n l[i] = sqrt(e - l[i])\n row += 1\n dr += row\n col = 1\n dc = 0\n return l\n\n// symmetric.print prints a square matrix from the packed representation,\n// printing the upper triange as a transpose of the lower\ndef print_symmetric(order, s):\n //const eleFmt = \"%10.5f \"\n var str = \"\"\n var row, diag = 1, 0\n for(s) e, i:\n str += e + \" \" // format?\n if i == diag:\n var j, col = diag+row, row\n while col < order:\n str += s[j] + \" \" // format?\n col++\n j += col\n print(str); str = \"\"\n row += 1\n diag += row\n\n// lower.print prints a square matrix from the packed representation,\n// printing the upper triangle as all zeros.\ndef print_lower(order, l):\n //const eleFmt = \"%10.5f \"\n var str = \"\"\n var row, diag = 1, 0\n for(l) e, i:\n str += e + \" \" // format?\n if i == diag:\n var j = row\n while j < order:\n str += 0.0 + \" \" // format?\n j += 1\n print(str); str = \"\"\n row += 1\n diag += row\n\ndef demo(order, a):\n print(\"A:\")\n print_symmetric(order, a)\n print(\"L:\")\n print_lower(order, choleskyLower(order, a))\n\ndemo(3, [25.0,\n 15.0, 18.0,\n -5.0, 0.0, 11.0])\n\ndemo(4, [18.0,\n 22.0, 70.0,\n 54.0, 86.0, 174.0,\n 42.0, 62.0, 134.0, 106.0])\n", "language": "Lobster" }, { "code": "> A := << 25, 15, -5; 15, 18, 0; -5, 0, 11 >>;\n [25 15 -5]\n [ ]\n A := [15 18 0]\n [ ]\n [-5 0 11]\n\n> B := << 18, 22, 54, 42; 22, 70, 86, 62; 54, 86, 174, 134; 42, 62, 134, 106>>;\n [18 22 54 42]\n [ ]\n [22 70 86 62]\n B := [ ]\n [54 86 174 134]\n [ ]\n [42 62 134 106]\n\n> use LinearAlgebra in\n> LUDecomposition( A, method = Cholesky );\n> LUDecomposition( B, method = Cholesky );\n> evalf( % );\n> end use;\n [ 5 0 0]\n [ ]\n [ 3 3 0]\n [ ]\n [-1 1 3]\n\n [ 1/2 ]\n [3 2 0 0 0 ]\n [ ]\n [ 1/2 1/2 ]\n [11 2 2 97 ]\n [------- ------- 0 0 ]\n [ 3 3 ]\n [ ]\n [ 1/2 1/2 ]\n [ 1/2 30 97 2 6402 ]\n [9 2 -------- --------- 0 ]\n [ 97 97 ]\n [ ]\n [ 1/2 1/2 1/2]\n [ 1/2 16 97 74 6402 8 33 ]\n [7 2 -------- ---------- -------]\n [ 97 3201 33 ]\n\n [4.242640686 0. 0. 0. ]\n [ ]\n [5.185449728 6.565905202 0. 0. ]\n [ ]\n [12.72792206 3.046038495 1.649742248 0. ]\n [ ]\n [9.899494934 1.624553864 1.849711006 1.392621248]\n", "language": "Maple" }, { "code": "CholeskyDecomposition[{{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}]\n", "language": "Mathematica" }, { "code": "chol[A_] :=\n Module[{L},\n L[k_, k_] := L[k, k] = Sqrt[A[[k, k]] - Sum[L[k, j]^2, {j, 1, k-1}]];\n L[i_, k_] := L[i, k] = L[k, k]^-1 (A[[i, k]] - Sum[L[i, j] L[k, j], {j, 1, k-1}]);\n PadRight[Table[L[i, j], {i, Length[A]}, {j, i}]]\n ]\n", "language": "Mathematica" }, { "code": " A = [\n 25 15 -5\n 15 18 0\n -5 0 11 ];\n\n B = [\n 18 22 54 42\n 22 70 86 62\n 54 86 174 134\n 42 62 134 106 ];\n\n [L] = chol(A,'lower')\n [L] = chol(B,'lower')\n", "language": "MATLAB" }, { "code": "/* Cholesky decomposition is built-in */\n\na: hilbert_matrix(4)$\n\nb: cholesky(a);\n/* matrix([1, 0, 0, 0 ],\n [1/2, 1/(2*sqrt(3)), 0, 0 ],\n [1/3, 1/(2*sqrt(3)), 1/(6*sqrt(5)), 0 ],\n [1/4, 3^(3/2)/20, 1/(4*sqrt(5)), 1/(20*sqrt(7))]) */\n\nb . transpose(b) - a;\nmatrix([0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0])\n", "language": "Maxima" }, { "code": "import math, strutils, strformat\n\ntype Matrix[N: static int, T: SomeFloat] = array[N, array[N, T]]\n\nproc cholesky[Matrix](a: Matrix): Matrix =\n for i in 0 ..< a[0].len:\n for j in 0 .. i:\n var s = 0.0\n for k in 0 ..< j:\n s += result[i][k] * result[j][k]\n result[i][j] = if i == j: sqrt(a[i][i]-s)\n else: 1.0 / result[j][j] * (a[i][j] - s)\n\nproc `$`(a: Matrix): string =\n result = \"\"\n for b in a:\n var line = \"\"\n for c in b:\n line.addSep(\" \", 0)\n line.add fmt\"{c:8.5f}\"\n result.add line & '\\n'\n\nlet m1 = [[25.0, 15.0, -5.0],\n [15.0, 18.0, 0.0],\n [-5.0, 0.0, 11.0]]\necho cholesky(m1)\n\nlet m2 = [[18.0, 22.0, 54.0, 42.0],\n [22.0, 70.0, 86.0, 62.0],\n [54.0, 86.0, 174.0, 134.0],\n [42.0, 62.0, 134.0, 106.0]]\necho cholesky(m2)\n", "language": "Nim" }, { "code": "class Cholesky {\n function : Main(args : String[]) ~ Nil {\n n := 3;\n m1 := [25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0];\n c1 := Cholesky(m1, n);\n ShowMatrix(c1, n);\n\n IO.Console->PrintLine();\n\n n := 4;\n m2 := [18.0, 22.0, 54.0, 42.0, 22.0, 70.0, 86.0, 62.0,\n 54.0, 86.0, 174.0, 134.0, 42.0, 62.0, 134.0, 106.0];\n c2 := Cholesky(m2, n);\n ShowMatrix(c2, n);\n }\n\n function : ShowMatrix(A : Float[], n : Int) ~ Nil {\n for (i := 0; i < n; i+=1;) {\n for (j := 0; j < n; j+=1;) {\n IO.Console->Print(A[i * n + j])->Print('\\t');\n };\n IO.Console->PrintLine();\n };\n }\n\n function : Cholesky(A : Float[], n : Int) ~ Float[] {\n L := Float->New[n * n];\n\n for (i := 0; i < n; i+=1;) {\n for (j := 0; j < (i+1); j+=1;) {\n s := 0.0;\n for (k := 0; k < j; k+=1;) {\n s += L[i * n + k] * L[j * n + k];\n };\n L[i * n + j] := (i = j) ?\n (A[i * n + i] - s)->SquareRoot() :\n (1.0 / L[j * n + j] * (A[i * n + j] - s));\n };\n };\n\n return L;\n }\n}\n", "language": "Objeck" }, { "code": "let cholesky inp =\n let n = Array.length inp in\n let res = Array.make_matrix n n 0.0 in\n let factor i k =\n let rec sum j =\n if j = k then 0.0 else\n res.(i).(j) *. res.(k).(j) +. sum (j+1) in\n inp.(i).(k) -. sum 0 in\n for col = 0 to n-1 do\n res.(col).(col) <- sqrt (factor col col);\n for row = col+1 to n-1 do\n res.(row).(col) <- (factor row col) /. res.(col).(col)\n done\n done;\n res\n\nlet pr_vec v = Array.iter (Printf.printf \" %9.5f\") v; print_newline()\nlet show = Array.iter pr_vec\nlet test a =\n print_endline \"\\nin:\"; show a;\n print_endline \"out:\"; show (cholesky a)\n\nlet _ =\n test [| [|25.0; 15.0; -5.0|];\n [|15.0; 18.0; 0.0|];\n [|-5.0; 0.0; 11.0|] |];\n test [| [|18.0; 22.0; 54.0; 42.0|];\n [|22.0; 70.0; 86.0; 62.0|];\n [|54.0; 86.0; 174.0; 134.0|];\n [|42.0; 62.0; 134.0; 106.0|] |];\n", "language": "OCaml" }, { "code": "/*REXX program performs the Cholesky decomposition on a square matrix. */\nniner = '25 15 -5' , /*define a 3x3 matrix. */\n '15 18 0' ,\n '-5 0 11'\n call Cholesky niner\nhexer = 18 22 54 42, /*define a 4x4 matrix. */\n 22 70 86 62,\n 54 86 174 134,\n 42 62 134 106\n call Cholesky hexer\nexit /*stick a fork in it, we're all done. */\n/*----------------------------------------------------------------------------*/\nCholesky: procedure; parse arg mat; say; say; call tell 'input matrix',mat\n do r=1 for ord\n do c=1 for r; d=0; do i=1 for c-1; d=d+!.r.i*!.c.i; end /*i*/\n if r=c then !.r.r=sqrt(!.r.r-d)\n else !.r.c=1/!.c.c*(a.r.c-d)\n end /*c*/\n end /*r*/\n call tell 'Cholesky factor',,!.,'-'\n return\n/*----------------------------------------------------------------------------*/\nerr: say; say; say '***error***!'; say; say arg(1); say; say; exit 13\n/*----------------------------------------------------------------------------*/\ntell: parse arg hdr,x,y,sep; n=0; if sep=='' then sep='-'\n dPlaces= 5 /*n decimal places past the decimal point*/\n width =10 /*width of field used to display elements*/\n if y=='' then !.=0\n else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end\n w=words(x)\n do ord=1 until ord**2>=w; end /*a fast way to find matrix's order*/\n say\n if ord**2\\==w then call err \"matrix elements don't form a square matrix.\"\n say center(hdr, ((width+1)*w)%ord, sep)\n say\n do row=1 for ord; z=''\n do col=1 for ord; n=n+1\n a.row.col=word(x,n)\n if col<=row then !.row.col=a.row.col\n z=z right( format(a.row.col,, dPlaces) / 1, width)\n end /*col*/\n say z\n end /*row*/\n return\n/*----------------------------------------------------------------------------*/\nsqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=''; m.=9\n numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end\n parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2\n do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/\n do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/\n numeric digits d; return (g/1)i /*make complex if X < 0.*/\n", "language": "OoRexx" }, { "code": "cholesky(M) =\n{\n my (L = matrix(#M,#M));\n\n for (i = 1, #M,\n for (j = 1, i,\n s = sum (k = 1, j-1, L[i,k] * L[j,k]);\n L[i,j] = if (i == j, sqrt(M[i,i] - s), (M[i,j] - s) / L[j,j])\n )\n );\n L\n}\n", "language": "PARI-GP" }, { "code": "program CholeskyApp;\n\ntype\n D2Array = array of array of double;\n\nfunction cholesky(const A: D2Array): D2Array;\nvar\n i, j, k: integer;\n s: double;\nbegin\n setlength(Result, length(A), length(A));\n for i := low(Result) to high(Result) do\n for j := 0 to i do\n begin\n s := 0;\n for k := 0 to j - 1 do\n s := s + Result[i][k] * Result[j][k];\n if i = j then\n Result[i][j] := sqrt(A[i][i] - s)\n else\n Result[i][j] := (A[i][j] - s) / Result[j][j]; // save one multiplication compared to the original\n end;\nend;\n\nprocedure printM(const A: D2Array);\nvar\n i, j: integer;\nbegin\n for i := low(A) to high(A) do\n begin\n for j := low(A) to high(A) do\n write(A[i, j]: 8: 5);\n writeln;\n end;\nend;\n\nconst\n m1: array[0..2, 0..2] of double = ((25, 15, -5), (15, 18, 0), (-5, 0, 11));\n m2: array[0..3, 0..3] of double = ((18, 22, 54, 42), (22, 70, 86, 62), (54, 86,\n 174, 134), (42, 62, 134, 106));\n\nvar\n index, i: integer;\n cIn, cOut: D2Array;\n\nbegin\n setlength(cIn, length(m1), length(m1));\n for index := low(m1) to high(m1) do\n begin\n SetLength(cIn[index], length(m1[index]));\n for i := 0 to High(m1[Index]) do\n cIn[index][i] := m1[index][i];\n end;\n cOut := cholesky(cIn);\n printM(cOut);\n\n writeln;\n\n setlength(cIn, length(m2), length(m2));\n for index := low(m2) to high(m2) do\n begin\n SetLength(cIn[index], length(m2[Index]));\n for i := 0 to High(m2[Index]) do\n cIn[index][i] := m2[index][i];\n end;\n cOut := cholesky(cIn);\n printM(cOut);\nend.\n", "language": "Pascal" }, { "code": "sub cholesky {\n my $matrix = shift;\n my $chol = [ map { [(0) x @$matrix ] } @$matrix ];\n for my $row (0..@$matrix-1) {\n for my $col (0..$row) {\n my $x = $$matrix[$row][$col];\n $x -= $$chol[$row][$_]*$$chol[$col][$_] for 0..$col;\n $$chol[$row][$col] = $row == $col ? sqrt $x : $x/$$chol[$col][$col];\n }\n }\n return $chol;\n}\n\nmy $example1 = [ [ 25, 15, -5 ],\n\t\t [ 15, 18, 0 ],\n\t\t [ -5, 0, 11 ] ];\nprint \"Example 1:\\n\";\nprint +(map { sprintf \"%7.4f\\t\", $_ } @$_), \"\\n\" for @{ cholesky $example1 };\n\nmy $example2 = [ [ 18, 22, 54, 42],\n\t\t [ 22, 70, 86, 62],\n\t\t [ 54, 86, 174, 134],\n\t\t [ 42, 62, 134, 106] ];\nprint \"\\nExample 2:\\n\";\nprint +(map { sprintf \"%7.4f\\t\", $_ } @$_), \"\\n\" for @{ cholesky $example2 };\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">cholesky</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">matrix</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">matrix</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">chol</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">row</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">col</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">row</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">matrix</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">row</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">col</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">col</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">chol</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">row</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">chol</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">col</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">chol</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">row</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">col</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">row</span> <span style=\"color: #0000FF;\">==</span> <span style=\"color: #000000;\">col</span> <span style=\"color: #0000FF;\">?</span> <span style=\"color: #7060A8;\">sqrt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">chol</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">col</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">col</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">chol</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">ppOpt</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #004600;\">pp_Nest</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">pp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cholesky</span><span style=\"color: #0000FF;\">({{</span> <span style=\"color: #000000;\">25</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">15</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">5</span> <span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">15</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">18</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">11</span> <span style=\"color: #0000FF;\">}}))</span>\n <span style=\"color: #7060A8;\">pp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cholesky</span><span style=\"color: #0000FF;\">({{</span> <span style=\"color: #000000;\">18</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">22</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">54</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">42</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">22</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">70</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">86</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">62</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">54</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">86</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">174</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">134</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">42</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">62</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">134</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">106</span><span style=\"color: #0000FF;\">}}))</span>\n<!--\n", "language": "Phix" }, { "code": "(scl 9)\n(load \"@lib/math.l\")\n\n(de cholesky (A)\n (let L (mapcar '(() (need (length A) 0)) A)\n (for (I . R) A\n (for J I\n (let S (get R J)\n (for K (inc J)\n (dec 'S (*/ (get L I K) (get L J K) 1.0)) )\n (set (nth L I J)\n (if (= I J)\n (sqrt S 1.0)\n (*/ S 1.0 (get L J J)) ) ) ) ) )\n (for R L\n (for N R (prin (align 9 (round N 5))))\n (prinl) ) ) )\n", "language": "PicoLisp" }, { "code": "(cholesky\n '((25.0 15.0 -5.0) (15.0 18.0 0) (-5.0 0 11.0)) )\n\n(prinl)\n\n(cholesky\n (quote\n (18.0 22.0 54.0 42.0)\n (22.0 70.0 86.0 62.0)\n (54.0 86.0 174.0 134.0)\n (42.0 62.0 134.0 106.0) ) )\n", "language": "PicoLisp" }, { "code": "(subscriptrange):\ndecompose: procedure options (main); /* 31 October 2013 */\n declare a(*,*) float controlled;\n\n allocate a(3,3) initial (25, 15, -5,\n 15, 18, 0,\n -5, 0, 11);\n put skip list ('Original matrix:');\n put edit (a) (skip, 3 f(4));\n\n call cholesky(a);\n put skip list ('Decomposed matrix');\n put edit (a) (skip, 3 f(4));\n free a;\n allocate a(4,4) initial (18, 22, 54, 42,\n 22, 70, 86, 62,\n 54, 86, 174, 134,\n 42, 62, 134, 106);\n put skip list ('Original matrix:');\n put edit (a) (skip, (hbound(a,1)) f(12) );\n call cholesky(a);\n put skip list ('Decomposed matrix');\n put edit (a) (skip, (hbound(a,1)) f(12,5) );\n\ncholesky: procedure(a);\n declare a(*,*) float;\n declare L(hbound(a,1), hbound(a,2)) float;\n declare s float;\n declare (i, j, k) fixed binary;\n\n L = 0;\n do i = lbound(a,1) to hbound(a,1);\n do j = lbound(a,2) to i;\n s = 0;\n do k = lbound(a,2) to j-1;\n s = s + L(i,k) * L(j,k);\n end;\n if i = j then\n L(i,j) = sqrt(a(i,i) - s);\n else\n L(i,j) = (a(i,j) - s) / L(j,j);\n end;\n end;\n a = L;\nend cholesky;\n\nend decompose;\n", "language": "PL-I" }, { "code": "function cholesky ($a) {\n $l = @()\n if ($a) {\n $n = $a.count\n $end = $n - 1\n $l = 1..$n | foreach {$row = @(0) * $n; ,$row}\n foreach ($k in 0..$end) {\n $m = $k - 1\n $sum = 0\n if(0 -lt $k) {\n foreach ($j in 0..$m) {$sum += $l[$k][$j]*$l[$k][$j]}\n }\n $l[$k][$k] = [Math]::Sqrt($a[$k][$k] - $sum)\n if ($k -lt $end) {\n foreach ($i in ($k+1)..$end) {\n $sum = 0\n if (0 -lt $k) {\n foreach ($j in 0..$m) {$sum += $l[$i][$j]*$l[$k][$j]}\n }\n $l[$i][$k] = ($a[$i][$k] - $sum)/$l[$k][$k]\n }\n }\n }\n }\n $l\n}\n\nfunction show($a) {$a | foreach {\"$_\"}}\n\n$a1 = @(\n@(25, 15, -5),\n@(15, 18, 0),\n@(-5, 0, 11)\n)\n\"a1 =\"\nshow $a1\n\"\"\n\"l1 =\"\nshow (cholesky $a1)\n\"\"\n$a2 = @(\n@(18, 22, 54, 42),\n@(22, 70, 86, 62),\n@(54, 86, 174, 134),\n@(42, 62, 134, 106)\n)\n\"a2 =\"\nshow $a2\n\"\"\n\"l2 =\"\nshow (cholesky $a2)\n", "language": "PowerShell" }, { "code": "from __future__ import print_function\n\nfrom pprint import pprint\nfrom math import sqrt\n\n\ndef cholesky(A):\n L = [[0.0] * len(A) for _ in xrange(len(A))]\n for i in xrange(len(A)):\n for j in xrange(i+1):\n s = sum(L[i][k] * L[j][k] for k in xrange(j))\n L[i][j] = sqrt(A[i][i] - s) if (i == j) else \\\n (1.0 / L[j][j] * (A[i][j] - s))\n return L\n\nif __name__ == \"__main__\":\n m1 = [[25, 15, -5],\n [15, 18, 0],\n [-5, 0, 11]]\n pprint(cholesky(m1))\n print()\n\n m2 = [[18, 22, 54, 42],\n [22, 70, 86, 62],\n [54, 86, 174, 134],\n [42, 62, 134, 106]]\n pprint(cholesky(m2), width=120)\n", "language": "Python" }, { "code": "def cholesky(A):\n L = [[0.0] * len(A) for _ in range(len(A))]\n for i, (Ai, Li) in enumerate(zip(A, L)):\n for j, Lj in enumerate(L[:i+1]):\n s = sum(Li[k] * Lj[k] for k in range(j))\n Li[j] = sqrt(Ai[i] - s) if (i == j) else \\\n (1.0 / Lj[j] * (Ai[j] - s))\n return L\n", "language": "Python" }, { "code": "solve:{[A;B] $[0h>type A;B%A;inv[A] mmu B]}\nak:{[m;k] (),/:m[;k]til k:k-1}\nakk:{[m;k] m[k;k:k-1]}\ntranspose:{$[0h=type x;flip x;enlist each x]}\nmult:{[A;B]$[0h=type A;A mmu B;A*B]}\t\t\ncholesky:{[A]\n\t{[A;L;n]\n\t\tl_k:solve[L;ak[A;n]];\n\t\tl_kk:first over sqrt[akk[A;n] - mult[transpose l_k;l_k]];\n\t\t({$[0h<type x;enlist x;x]}L,'0f),enlist raze transpose[l_k],l_kk\n\t\t}[A]/[sqrt A[0;0];1_1+til count first A]\n\t}\n\nshow cholesky (25 15 -5f;15 18 0f;-5 0 11f)\n-1\"\";\nshow cholesky (18 22 54 42f;22 70 86 62f;54 86 174 134f;42 62 134 106f)\n", "language": "Q" }, { "code": "t(chol(matrix(c(25, 15, -5, 15, 18, 0, -5, 0, 11), nrow=3, ncol=3)))\n# [,1] [,2] [,3]\n# [1,] 5 0 0\n# [2,] 3 3 0\n# [3,] -1 1 3\n\nt(chol(matrix(c(18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106), nrow=4, ncol=4)))\n# [,1] [,2] [,3] [,4]\n# [1,] 4.242641 0.000000 0.000000 0.000000\n# [2,] 5.185450 6.565905 0.000000 0.000000\n# [3,] 12.727922 3.046038 1.649742 0.000000\n# [4,] 9.899495 1.624554 1.849711 1.392621\n", "language": "R" }, { "code": "#lang racket\n(require math)\n\n(define (cholesky A)\n (define mref matrix-ref)\n (define n (matrix-num-rows A))\n (define L (for/vector ([_ n]) (for/vector ([_ n]) 0)))\n (define (set L i j x) (vector-set! (vector-ref L i) j x))\n (define (ref L i j) (vector-ref (vector-ref L i) j))\n (for* ([i n] [k n])\n (set L i k\n (cond\n [(= i k)\n (sqrt (- (mref A i i) (for/sum ([j k]) (sqr (ref L k j)))))]\n [(> i k)\n (/ (- (mref A i k) (for/sum ([j k]) (* (ref L i j) (ref L k j))))\n (ref L k k))]\n [else 0])))\n L)\n\n(cholesky (matrix [[25 15 -5]\n [15 18 0]\n [-5 0 11]]))\n\n(cholesky (matrix [[18 22 54 42]\n [22 70 86 62]\n [54 86 174 134]\n [42 62 134 106]]))\n", "language": "Racket" }, { "code": "'#(#(5 0 0)\n #(3 3 0)\n #(-1 1 3))\n'#(#(4.242640687119285 0 0 0)\n #( 5.185449728701349 6.565905201197403 0 0)\n #(12.727922061357857 3.0460384954008553 1.6497422479090704 0)\n #( 9.899494936611665 1.6245538642137891 1.849711005231382 1.3926212476455924))\n", "language": "Racket" }, { "code": "sub cholesky(@A) {\n my @L = @A »×» 0;\n for ^@A -> \\i {\n for 0..i -> \\j {\n @L[i;j] = (i == j ?? &sqrt !! 1/@L[j;j] × * )\\ # select function\n (@A[i;j] - [+] (@L[i;*] Z× @L[j;*])[^j]) # provide value\n }\n }\n @L\n}\n\n.fmt('%3d').say for cholesky [\n [25],\n [15, 18],\n [-5, 0, 11],\n];\n\nsay '';\n\n.fmt('%6.3f').say for cholesky [\n [18, 22, 54, 42],\n [22, 70, 86, 62],\n [54, 86, 174, 134],\n [42, 62, 134, 106],\n];\n", "language": "Raku" }, { "code": "/*REXX program performs the Cholesky decomposition on a square matrix & displays results*/\nniner = '25 15 -5' , /*define a 3x3 matrix with elements. */\n '15 18 0' ,\n '-5 0 11'\n call Cholesky niner\nhexer = 18 22 54 42, /*define a 4x4 matrix with elements. */\n 22 70 86 62,\n 54 86 174 134,\n 42 62 134 106\n call Cholesky hexer\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nCholesky: procedure; parse arg mat; say; say; call tell 'input array',mat\n do r=1 for ord\n do c=1 for r; $=0; do i=1 for c-1; $= $ + !.r.i * !.c.i; end /*i*/\n if r=c then !.r.r= sqrt(!.r.r - $)\n else !.r.c= 1 / !.c.c * (@.r.c - $)\n end /*c*/\n end /*r*/\n call tell 'Cholesky factor',,!.,'─'\n return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nerr: say; say; say '***error***!'; say; say arg(1); say; say; exit 13\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ntell: parse arg hdr,x,y,sep; #=0; if sep=='' then sep= '═'\n dPlaces= 5 /*# dec. places past the decimal point.*/\n width =10 /*field width used to display elements.*/\n if y=='' then !.=0\n else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end\n w=words(x)\n do ord=1 until ord**2>=w; end /*a fast way to find the matrix's order*/\n say\n if ord**2\\==w then call err \"matrix elements don't form a square matrix.\"\n say center(hdr, ((width + 1) * w) % ord, sep)\n say\n do row=1 for ord; z=\n do col=1 for ord; #= # + 1\n @.row.col= word(x, #)\n if col<=row then !.row.col= @.row.col\n z=z right( format(@.row.col, , dPlaces) / 1, width)\n end /*col*/ /* ↑↑↑ */\n say z /* └┴┴──◄──normalization for zero*/\n end /*row*/\n return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h=d+6\n numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_ %2\n do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/\n do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g/1\n", "language": "REXX" }, { "code": "# Project : Cholesky decomposition\n\nload \"stdlib.ring\"\ndecimals(5)\nm1 = [[25, 15, -5],\n [15, 18, 0],\n [-5, 0, 11]]\ncholesky(m1)\nprintarray(m1)\nsee nl\n\nm2 = [[18, 22, 54, 42],\n [22, 70, 86, 62],\n [54, 86, 174, 134],\n [42, 62, 134, 106]]\ncholesky(m2)\nprintarray(m2)\n\nfunc cholesky(a)\nl = newlist(len(a), len(a))\nfor i = 1 to len(a)\n for j = 1 to i\n s = 0\n for k = 1 to j\n s = s + l[i][k] * l[j][k]\n next\n if i = j\n l[i][j] = sqrt(a[i][i] - s)\n else\n l[i][j] = (a[i][j] - s) / l[j][j]\n ok\n next\nnext\na = l\n\nfunc printarray(a)\n for row = 1 to len(a)\n for col = 1 to len(a)\n see \"\" + a[row][col] + \" \"\n next\n see nl\n next\n", "language": "Ring" }, { "code": "require 'matrix'\n\nclass Matrix\n def cholesky_factor\n raise ArgumentError, \"must provide symmetric matrix\" unless symmetric?\n l = Array.new(row_size) {Array.new(row_size, 0)}\n (0 ... row_size).each do |k|\n (0 ... row_size).each do |i|\n if i == k\n sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[k][j] ** 2}\n val = Math.sqrt(self[k,k] - sum)\n l[k][k] = val\n elsif i > k\n sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[i][j] * l[k][j]}\n val = (self[k,i] - sum) / l[k][k]\n l[i][k] = val\n end\n end\n end\n Matrix[*l]\n end\nend\n\nputs Matrix[[25,15,-5],[15,18,0],[-5,0,11]].cholesky_factor\nputs Matrix[[18, 22, 54, 42],\n [22, 70, 86, 62],\n [54, 86, 174, 134],\n [42, 62, 134, 106]].cholesky_factor\n", "language": "Ruby" }, { "code": "fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {\n let mut res = vec![0.0; mat.len()];\n for i in 0..n {\n for j in 0..(i+1){\n let mut s = 0.0;\n for k in 0..j {\n s += res[i * n + k] * res[j * n + k];\n }\n res[i * n + j] = if i == j { (mat[i * n + i] - s).sqrt() } else { (1.0 / res[j * n + j] * (mat[i * n + j] - s)) };\n }\n }\n res\n}\n\nfn show_matrix(matrix: Vec<f64>, n: usize){\n for i in 0..n {\n for j in 0..n {\n print!(\"{:.4}\\t\", matrix[i * n + j]);\n }\n println!(\"\");\n }\n println!(\"\");\n}\n\nfn main(){\n let dimension = 3 as usize;\n let m1 = vec![25.0, 15.0, -5.0,\n 15.0, 18.0, 0.0,\n -5.0, 0.0, 11.0];\n let res1 = cholesky(m1, dimension);\n show_matrix(res1, dimension);\n\n let dimension = 4 as usize;\n let m2 = vec![18.0, 22.0, 54.0, 42.0,\n 22.0, 70.0, 86.0, 62.0,\n 54.0, 86.0, 174.0, 134.0,\n 42.0, 62.0, 134.0, 106.0];\n let res2 = cholesky(m2, dimension);\n show_matrix(res2, dimension);\n}\n", "language": "Rust" }, { "code": "case class Matrix( val matrix:Array[Array[Double]] ) {\n\n // Assuming matrix is positive-definite, symmetric and not empty...\n\n val rows,cols = matrix.size\n\n def getOption( r:Int, c:Int ) : Option[Double] = Pair(r,c) match {\n case (r,c) if r < rows && c < rows => Some(matrix(r)(c))\n case _ => None\n }\n\n def isLowerTriangle( r:Int, c:Int ) : Boolean = { c <= r }\n def isDiagonal( r:Int, c:Int ) : Boolean = { r == c}\n\n override def toString = matrix.map(_.mkString(\", \")).mkString(\"\\n\")\n\n /**\n * Perform Cholesky Decomposition of this matrix\n */\n lazy val cholesky : Matrix = {\n\n val l = Array.ofDim[Double](rows*cols)\n\n for( i <- (0 until rows); j <- (0 until cols) ) yield {\n\t\n val s = (for( k <- (0 until j) ) yield { l(i*rows+k) * l(j*rows+k) }).sum\n\t\n l(i*rows+j) = (i,j) match {\n case (r,c) if isDiagonal(r,c) => scala.math.sqrt(matrix(i)(i) - s)\n case (r,c) if isLowerTriangle(r,c) => (1.0 / l(j*rows+j) * (matrix(i)(j) - s))\n case _ => 0\n }\n }\n\n val m = Array.ofDim[Double](rows,cols)\n for( i <- (0 until rows); j <- (0 until cols) ) m(i)(j) = l(i*rows+j)\n Matrix(m)\n }\n}\n\n// A little test...\nval a1 = Matrix(Array[Array[Double]](Array(25,15,-5),Array(15,18,0),Array(-5,0,11)))\nval a2 = Matrix(Array[Array[Double]](Array(18,22,54,42), Array(22,70,86,62), Array(54,86,174,134), Array(42,62,134,106)))\n\nval l1 = a1.cholesky\nval l2 = a2.cholesky\n\n\n// Given test results\nval r1 = Array[Double](5,0,0,3,3,0,-1,1,3)\nval r2 = Array[Double](4.24264,0.00000,0.00000,0.00000,5.18545,6.56591,0.00000,0.00000,\n 12.72792,3.04604,1.64974,0.00000,9.89949,1.62455,1.84971,1.39262)\n\n// Verify assertions\t\t\t\t\t\t\n(l1.matrix.flatten.zip(r1)).foreach{ case (result,test) =>\n assert(math.round( result * 100000 ) * 0.00001 == math.round( test * 100000 ) * 0.00001)\n}\n\n(l2.matrix.flatten.zip(r2)).foreach{ case (result,test) =>\n assert(math.round( result * 100000 ) * 0.00001 == math.round( test * 100000 ) * 0.00001)\n}\n", "language": "Scala" }, { "code": "a = [25 15 -5; 15 18 0; -5 0 11];\nchol(a)\n ans =\n\n 5. 3. -1.\n 0. 3. 1.\n 0. 0. 3.\n\n\na = [18 22 54 42; 22 70 86 62;\n 54 86 174 134; 42 62 134 106];\n\nchol(a)\n ans =\n\n 4.2426407 5.1854497 12.727922 9.8994949\n 0. 6.5659052 3.0460385 1.6245539\n 0. 0. 1.6497422 1.849711\n 0. 0. 0. 1.3926212\n", "language": "Scilab" }, { "code": "$ include \"seed7_05.s7i\";\n include \"float.s7i\";\n include \"math.s7i\";\n\nconst type: matrix is array array float;\n\nconst func matrix: cholesky (in matrix: a) is func\n result\n var matrix: cholesky is 0 times 0 times 0.0;\n local\n var integer: i is 0;\n var integer: j is 0;\n var integer: k is 0;\n var float: sum is 0.0;\n begin\n cholesky := length(a) times length(a) times 0.0;\n for key i range cholesky do\n for j range 1 to i do\n\tsum := 0.0;\n\tfor k range 1 to j do\n\t sum +:= cholesky[i][k] * cholesky[j][k];\n end for;\n\tif i = j then\n\t cholesky[i][i] := sqrt(a[i][i] - sum)\n\telse\n cholesky[i][j] := (a[i][j] - sum) / cholesky[j][j];\n end if;\n end for;\n end for;\n end func;\n\nconst proc: writeMat (in matrix: a) is func\n local\n var integer: i is 0;\n var float: num is 0.0;\n begin\n for key i range a do\n for num range a[i] do\n write(num digits 5 lpad 8);\n end for;\n writeln;\n end for;\n end func;\n\nconst matrix: m1 is [] (\n [] (25.0, 15.0, -5.0),\n [] (15.0, 18.0, 0.0),\n [] (-5.0, 0.0, 11.0));\nconst matrix: m2 is [] (\n [] (18.0, 22.0, 54.0, 42.0),\n [] (22.0, 70.0, 86.0, 62.0),\n [] (54.0, 86.0, 174.0, 134.0),\n [] (42.0, 62.0, 134.0, 106.0));\n\nconst proc: main is func\n begin\n writeMat(cholesky(m1));\n writeln;\n writeMat(cholesky(m2));\n end func;\n", "language": "Seed7" }, { "code": "func cholesky(matrix) {\n var chol = matrix.len.of { matrix.len.of(0) }\n for row in ^matrix {\n for col in (0..row) {\n var x = matrix[row][col]\n for i in (0..col) {\n x -= (chol[row][i] * chol[col][i])\n }\n chol[row][col] = (row == col ? x.sqrt : x/chol[col][col])\n }\n }\n return chol\n}\n", "language": "Sidef" }, { "code": "var example1 = [ [ 25, 15, -5 ],\n [ 15, 18, 0 ],\n [ -5, 0, 11 ] ];\n\nsay \"Example 1:\";\ncholesky(example1).each { |row|\n say row.map {'%7.4f' % _}.join(' ');\n}\n\nvar example2 = [ [ 18, 22, 54, 42],\n [ 22, 70, 86, 62],\n [ 54, 86, 174, 134],\n [ 42, 62, 134, 106] ];\n\nsay \"\\nExample 2:\";\ncholesky(example2).each { |row|\n say row.map {'%7.4f' % _}.join(' ');\n}\n", "language": "Sidef" }, { "code": "FloatMatrix>>#cholesky\n\t| l |\n\tl := FloatMatrix zero: numRows.\n\t1 to: numRows do: [:i |\n\t\t1 to: i do: [:k | | rowSum lkk factor aki partialSum |\n\t\t\ti = k\n\t\t\t\tifTrue: [\n\t\t\t\t\trowSum := (1 to: k - 1) sum: [:j | | lkj |\n\t\t\t\t\t\tlkj := l at: j @ k.\n\t\t\t\t\t\tlkj squared].\n\t\t\t\t\tlkk := (self at: k @ k) - rowSum.\n\t\t\t\t\tlkk := lkk sqrt.\n\t\t\t\t\tl at: k @ k put: lkk]\n\t\t\t\tifFalse: [\n\t\t\t\t\tfactor := l at: k @ k.\n\t\t\t\t\taki := self at: k @ i.\n\t\t\t\t\tpartialSum := (1 to: k - 1) sum: [:j | | ljk lji |\n\t\t\t\t\t\tlji := l at: j @ i.\n\t\t\t\t\t\tljk := l at: j @ k.\n\t\t\t\t\t\tlji * ljk].\n\t\t\t\t\tl at: k @ i put: aki - partialSum * factor reciprocal]]].\n\t^l\n", "language": "Smalltalk" }, { "code": "mata\n: a=25,15,-5\\15,18,0\\-5,0,11\n\n: a\n[symmetric]\n 1 2 3\n +----------------+\n 1 | 25 |\n 2 | 15 18 |\n 3 | -5 0 11 |\n +----------------+\n\n: cholesky(a)\n 1 2 3\n +----------------+\n 1 | 5 0 0 |\n 2 | 3 3 0 |\n 3 | -1 1 3 |\n +----------------+\n\n: a=18,22,54,42\\22,70,86,62\\54,86,174,134\\42,62,134,106\n\n: a\n[symmetric]\n 1 2 3 4\n +-------------------------+\n 1 | 18 |\n 2 | 22 70 |\n 3 | 54 86 174 |\n 4 | 42 62 134 106 |\n +-------------------------+\n\n: cholesky(a)\n 1 2 3 4\n +---------------------------------------------------------+\n 1 | 4.242640687 0 0 0 |\n 2 | 5.185449729 6.565905201 0 0 |\n 3 | 12.72792206 3.046038495 1.649742248 0 |\n 4 | 9.899494937 1.624553864 1.849711005 1.392621248 |\n +---------------------------------------------------------+\n", "language": "Stata" }, { "code": "func cholesky(matrix: [Double], n: Int) -> [Double] {\n var res = [Double](repeating: 0, count: matrix.count)\n\n for i in 0..<n {\n for j in 0..<i+1 {\n var s = 0.0\n\n for k in 0..<j {\n s += res[i * n + k] * res[j * n + k]\n }\n\n if i == j {\n res[i * n + j] = (matrix[i * n + i] - s).squareRoot()\n } else {\n res[i * n + j] = (1.0 / res[j * n + j] * (matrix[i * n + j] - s))\n }\n }\n }\n\n return res\n}\n\nfunc printMatrix(_ matrix: [Double], n: Int) {\n for i in 0..<n {\n for j in 0..<n {\n print(matrix[i * n + j], terminator: \" \")\n }\n\n print()\n }\n}\n\nlet res1 = cholesky(\n matrix: [25.0, 15.0, -5.0,\n 15.0, 18.0, 0.0,\n -5.0, 0.0, 11.0],\n n: 3\n)\n\nlet res2 = cholesky(\n matrix: [18.0, 22.0, 54.0, 42.0,\n 22.0, 70.0, 86.0, 62.0,\n 54.0, 86.0, 174.0, 134.0,\n 42.0, 62.0, 134.0, 106.0],\n n: 4\n)\n\nprintMatrix(res1, n: 3)\nprint()\nprintMatrix(res2, n: 4)\n", "language": "Swift" }, { "code": "proc cholesky a {\n set m [llength $a]\n set n [llength [lindex $a 0]]\n set l [lrepeat $m [lrepeat $n 0.0]]\n for {set i 0} {$i < $m} {incr i} {\n\tfor {set k 0} {$k < $i+1} {incr k} {\n\t set sum 0.0\n\t for {set j 0} {$j < $k} {incr j} {\n\t\tset sum [expr {$sum + [lindex $l $i $j] * [lindex $l $k $j]}]\n\t }\n\t lset l $i $k [expr {\n\t\t$i == $k\n\t\t? sqrt([lindex $a $i $i] - $sum)\n\t\t: (1.0 / [lindex $l $k $k] * ([lindex $a $i $k] - $sum))\n\t }]\n\t}\n }\n return $l\n}\n", "language": "Tcl" }, { "code": "set test1 {\n {25 15 -5}\n {15 18 0}\n {-5 0 11}\n}\nputs [cholesky $test1]\nset test2 {\n {18 22 54 42}\n {22 70 86 62}\n {54 86 174 134}\n {42 62 134 106}\n}\nputs [cholesky $test2]\n", "language": "Tcl" }, { "code": "import math\n\n// Symmetric and Lower use a packed representation that stores only\n// the Lower triangle.\n\nstruct Symmetric {\n order int\n ele []f64\n}\n\nstruct Lower {\nmut:\n order int\n ele []f64\n}\n\n// Symmetric.print prints a square matrix from the packed representation,\n// printing the upper triange as a transpose of the Lower.\nfn (s Symmetric) print() {\n mut row, mut diag := 1, 0\n for i, e in s.ele {\n print(\"${e:10.5f} \")\n if i == diag {\n for j, col := diag+row, row; col < s.order; j += col {\n print(\"${s.ele[j]:10.5f} \")\n col++\n }\n println('')\n row++\n diag += row\n }\n }\n}\n\n// Lower.print prints a square matrix from the packed representation,\n// printing the upper triangle as all zeros.\nfn (l Lower) print() {\n mut row, mut diag := 1, 0\n for i, e in l.ele {\n print(\"${e:10.5f} \")\n if i == diag {\n for _ in row..l.order {\n print(\"${0.0:10.5f} \")\n }\n println('')\n row++\n diag += row\n }\n }\n}\n\n// cholesky_lower returns the cholesky decomposition of a Symmetric real\n// matrix. The matrix must be positive definite but this is not checked.\nfn (a Symmetric) cholesky_lower() Lower {\n mut l := Lower{a.order, []f64{len: a.ele.len}}\n mut row, mut col := 1, 1\n mut dr := 0 // index of diagonal element at end of row\n mut dc := 0 // index of diagonal element at top of column\n for i, e in a.ele {\n if i < dr {\n d := (e - l.ele[i]) / l.ele[dc]\n l.ele[i] = d\n mut ci, mut cx := col, dc\n for j := i + 1; j <= dr; j++ {\n cx += ci\n ci++\n l.ele[j] += d * l.ele[cx]\n }\n col++\n dc += col\n } else {\n l.ele[i] = math.sqrt(e - l.ele[i])\n row++\n dr += row\n col = 1\n dc = 0\n }\n }\n return l\n}\n\nfn main() {\n demo(Symmetric{3, [\n f64(25),\n 15, 18,\n -5, 0, 11]})\n demo(Symmetric{4, [\n f64(18),\n 22, 70,\n 54, 86, 174,\n 42, 62, 134, 106]})\n}\n\nfn demo(a Symmetric) {\n println(\"A:\")\n a.print()\n println(\"L:\")\n a.cholesky_lower().print()\n}\n", "language": "V-(Vlang)" }, { "code": "Function Cholesky(Mat As Range) As Variant\n\nDim A() As Double, L() As Double, sum As Double, sum2 As Double\nDim m As Byte, i As Byte, j As Byte, k As Byte\n\n'Ensure matrix is square\n If Mat.Rows.Count <> Mat.Columns.Count Then\n MsgBox (\"Correlation matrix is not square\")\n Exit Function\n End If\n\n m = Mat.Rows.Count\n\n'Initialize and populate matrix A of values and matrix L which will be the lower Cholesky\n ReDim A(0 To m - 1, 0 To m - 1)\n ReDim L(0 To m - 1, 0 To m - 1)\n For i = 0 To m - 1\n For j = 0 To m - 1\n A(i, j) = Mat(i + 1, j + 1).Value2\n L(i, j) = 0\n Next j\n Next i\n\n'Handle the simple cases explicitly to save time\n Select Case m\n Case Is = 1\n L(0, 0) = Sqr(A(0, 0))\n\n Case Is = 2\n L(0, 0) = Sqr(A(0, 0))\n L(1, 0) = A(1, 0) / L(0, 0)\n L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))\n\n Case Else\n L(0, 0) = Sqr(A(0, 0))\n L(1, 0) = A(1, 0) / L(0, 0)\n L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))\n For i = 2 To m - 1\n sum2 = 0\n For k = 0 To i - 1\n sum = 0\n For j = 0 To k\n sum = sum + L(i, j) * L(k, j)\n Next j\n L(i, k) = (A(i, k) - sum) / L(k, k)\n sum2 = sum2 + L(i, k) * L(i, k)\n Next k\n L(i, i) = Sqr(A(i, i) - sum2)\n Next i\n End Select\n Cholesky = L\nEnd Function\n", "language": "VBA" }, { "code": "import \"./matrix\" for Matrix\nimport \"./fmt\" for Fmt\n\nvar arrays = [\n [ [25, 15, -5],\n [15, 18, 0],\n [-5, 0, 11] ],\n\n [ [18, 22, 54, 42],\n [22, 70, 86, 62],\n [54, 86, 174, 134],\n [42, 62, 134, 106] ]\n]\n\nfor (array in arrays) {\n System.print(\"Original:\")\n Fmt.mprint(array, 3, 0)\n System.print(\"\\nLower Cholesky factor:\")\n Fmt.mprint(Matrix.new(array).cholesky(), 8, 5)\n System.print()\n}\n", "language": "Wren" }, { "code": "real L(4*4);\n\nfunc real Cholesky(A, N);\nreal A; int N;\nreal S;\nint I, J, K;\n[for I:= 0 to N*N-1 do L(I):= 0.;\nfor I:= 0 to N-1 do\n for J:= 0 to I do\n [S:= 0.;\n for K:= 0 to J-1 do\n S:= S + L(I*N+K) * L(J*N+K);\n L(I*N+J):= if I = J then sqrt(A(I*N+I) - S)\n else (1.0 / L(J*N+J) * (A(I*N+J) - S));\n ];\nreturn L;\n];\n\nproc ShowMatrix(A, N);\nreal A; int N;\nint I, J;\n[for I:= 0 to N-1 do\n [for J:= 0 to N-1 do\n RlOut(0, A(I*N+J));\n CrLf(0);\n ];\n];\n\nint N;\nreal M1, C1, M2, C2;\n[N:= 3;\nM1:= [25., 15., -5.,\n 15., 18., 0.,\n -5., 0., 11.];\nC1:= Cholesky(M1, N);\nShowMatrix(C1, N);\nCrLf(0);\n\nN:= 4;\nM2:= [18., 22., 54., 42.,\n 22., 70., 86., 62.,\n 54., 86., 174., 134.,\n 42., 62., 134., 106.];\nC2:= Cholesky(M2, N);\nShowMatrix(C2, N);\n]\n", "language": "XPL0" }, { "code": "var [const] GSL=Import(\"zklGSL\");\t// libGSL (GNU Scientific Library)\nfcn lowerCholesky(m){ // trans: C\n rows:=m.rows;\n lcm:=GSL.Matrix(rows,rows);\t// zero filled\n foreach i,j in (rows,i+1){\n s:=(0).reduce(j,'wrap(s,k){ s + lcm[i,k]*lcm[j,k] },0.0);\n lcm[i,j]=( if(i==j)(m[i,i] - s).sqrt()\n\t else 1.0/lcm[j,j]*(m[i,j] - s) );\n }\n lcm\n}\n", "language": "Zkl" }, { "code": "fcn cholesky(mat){\n rows:=mat.len();\n r:=(0).pump(rows,List().write, (0).pump(rows,List,0.0).copy); // matrix of zeros\n foreach i,j in (rows,i+1){\n s:=(0).reduce(j,'wrap(s,k){ s + r[i][k]*r[j][k] },0.0);\n r[i][j]=( if(i==j)(mat[i][i] - s).sqrt()\n\t else 1.0/r[j][j]*(mat[i][j] - s) );\n }\n r\n}\n", "language": "Zkl" }, { "code": "ex1:=L( L(25.0,15.0,-5.0), L(15.0,18.0,0.0), L(-5.0,0.0,11.0) );\nprintM(cholesky(ex1));\nprintln(\"-----------------\");\nex2:=L( L(18.0, 22.0, 54.0, 42.0,),\n L(22.0, 70.0, 86.0, 62.0,),\n\tL(54.0, 86.0, 174.0, 134.0,),\n\tL(42.0, 62.0, 134.0, 106.0,) );\nprintM(cholesky(ex2));\n", "language": "Zkl" }, { "code": "fcn printM(m){ m.pump(Console.println,rowFmt) }\nfcn rowFmt(row){ (\"%9.5f \"*row.len()).fmt(row.xplode()) }\n", "language": "Zkl" }, { "code": "10 LET d=2000: GO SUB 1000: GO SUB 4000: GO SUB 5000\n20 LET d=3000: GO SUB 1000: GO SUB 4000: GO SUB 5000\n30 STOP\n1000 RESTORE d\n1010 READ a,b\n1020 DIM m(a,b)\n1040 FOR i=1 TO a\n1050 FOR j=1 TO b\n1060 READ m(i,j)\n1070 NEXT j\n1080 NEXT i\n1090 RETURN\n2000 DATA 3,3,25,15,-5,15,18,0,-5,0,11\n3000 DATA 4,4,18,22,54,42,22,70,86,62,54,86,174,134,42,62,134,106\n4000 REM Cholesky decomposition\n4005 DIM l(a,b)\n4010 FOR i=1 TO a\n4020 FOR j=1 TO i\n4030 LET s=0\n4050 FOR k=1 TO j-1\n4060 LET s=s+l(i,k)*l(j,k)\n4070 NEXT k\n4080 IF i=j THEN LET l(i,j)=SQR (m(i,i)-s): GO TO 4100\n4090 LET l(i,j)=(m(i,j)-s)/l(j,j)\n4100 NEXT j\n4110 NEXT i\n4120 RETURN\n5000 REM Print\n5010 FOR r=1 TO a\n5020 FOR c=1 TO b\n5030 PRINT l(r,c);\" \";\n5040 NEXT c\n5050 PRINT\n5060 NEXT r\n5070 RETURN\n", "language": "ZX-Spectrum-Basic" } ]
Cholesky-decomposition
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Chowla_numbers\nnote: Prime Numbers\n", "language": "00-META" }, { "code": "Chowla numbers are also known as:\n::* &nbsp; Chowla's function\n::* &nbsp; chowla numbers \n::* &nbsp; the chowla function\n::* &nbsp; the chowla number\n::* &nbsp; the chowla sequence\n\n\n\n\nThe chowla number of &nbsp; <big>'''n'''</big> &nbsp; is &nbsp; (as defined by Chowla's function):\n::* &nbsp; the sum of the divisors of &nbsp; <big>'''n'''</big> &nbsp; &nbsp; excluding unity and &nbsp; <big>'''n'''</big>\n::* &nbsp; where &nbsp; <big>'''n'''</big> &nbsp; is a positive integer\n\n\n\nThe sequence is named after &nbsp; Sarvadaman D. S. Chowla, &nbsp; (22 October 1907 ──► 10 December 1995),\n<br>a London born Indian American mathematician specializing in ''number theory''.\n\n\n\nGerman mathematician Carl Friedrich Gauss (1777─1855) said: \n \"Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics\".\n\n\n\n;Definitions:\nChowla numbers can also be expressed as:\n <big>\n chowla(<big>'''n'''</big>) = sum of divisors of <big>'''n'''</big> excluding unity and <big>'''n'''</big>\n chowla(<big>'''n'''</big>) = sum( divisors(<big>'''n'''</big>)) <big>'''- 1 - n''' </big>\n chowla(<big>'''n'''</big>) = sum( properDivisors(<big>'''n'''</big>)) <big>'''- 1''' </big>\n chowla(<big>'''n'''</big>) = sum(aliquotDivisors(<big>'''n'''</big>)) <big>'''- 1''' </big> \n chowla(<big>'''n'''</big>) = aliquot(<big>'''n'''</big>) <big>'''- 1''' </big>\n chowla(<big>'''n'''</big>) = sigma(<big>'''n'''</big>) <big>'''- 1 - n''' </big>\n chowla(<big>'''n'''</big>) = sigmaProperDivisiors(<big>'''n'''</big>) <big>'''- 1''' </big>\n &nbsp;\n chowla(<big>'''a'''*'''b'''</big>) = <big>'''a + b'''</big>, &nbsp; ''if'' <big>'''a'''</big> and <big>'''b'''</big> are distinct primes\n if chowla(<big>'''n'''</big>) = <big>'''0'''</big>,&nbsp; and <big>'''n > 1'''</big>, then <big>'''n'''</big> is prime\n if chowla(<big>'''n'''</big>) = <big>'''n - 1'''</big>, and <big>'''n > 1'''</big>, then <big>'''n'''</big> is a perfect number\n </big> \n\n;Task:\n::* &nbsp; create a &nbsp; '''chowla''' &nbsp; function that returns the &nbsp; '''chowla number''' &nbsp; for a positive integer &nbsp; '''n'''\n::* &nbsp; Find and display &nbsp; (1 per line) &nbsp; for the 1<sup>st</sup> &nbsp; '''37''' &nbsp; integers:\n::::* &nbsp; the integer &nbsp; (the index)\n::::* &nbsp; the chowla number for that integer\n::* &nbsp; For finding primes, use the &nbsp; '''chowla''' &nbsp; function to find values of zero\n::* &nbsp; Find and display the &nbsp; ''count'' &nbsp; of the primes up to &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; '''100'''\n::* &nbsp; Find and display the &nbsp; ''count'' &nbsp; of the primes up to &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '''1,000'''\n::* &nbsp; Find and display the &nbsp; ''count'' &nbsp; of the primes up to &nbsp; &nbsp; &nbsp; &nbsp; '''10,000'''\n::* &nbsp; Find and display the &nbsp; ''count'' &nbsp; of the primes up to &nbsp; &nbsp; &nbsp; '''100,000'''\n::* &nbsp; Find and display the &nbsp; ''count'' &nbsp; of the primes up to &nbsp;&nbsp; '''1,000,000'''\n::* &nbsp; Find and display the &nbsp; ''count'' &nbsp; of the primes up to&nbsp; '''10,000,000'''\n::* &nbsp; For finding perfect numbers, use the &nbsp; '''chowla''' &nbsp; function to find values of &nbsp; '''n - 1'''\n::* &nbsp; Find and display all &nbsp; perfect numbers &nbsp; up to &nbsp; '''35,000,000'''\n::* &nbsp; use commas within appropriate numbers\n::* &nbsp; show all output here\n\n\n\n\n;Related tasks:\n:* &nbsp; [[Totient_function| totient function]]\n:* &nbsp; [[Perfect_numbers| perfect numbers]]\n:* &nbsp; [[Proper divisors]]\n:* &nbsp; [[Sieve of Eratosthenes]]\n\n\n\n;See also:\n:* &nbsp; the OEIS entry for &nbsp; [http://oeis.org/A048050 A48050 Chowla's function].\n<br><br>\n", "language": "00-TASK" }, { "code": "F chowla(n)\n V sum = 0\n V i = 2\n L i * i <= n\n I n % i == 0\n sum += i\n V j = n I/ i\n I i != j\n sum += j\n i++\n R sum\n\nL(n) 1..37\n print(‘chowla(’n‘) = ’chowla(n))\n\nV count = 0\nV power = 100\nL(n) 2..10'000'000\n I chowla(n) == 0\n count++\n I n % power == 0\n print(‘There are ’count‘ primes < ’power)\n power *= 10\n\ncount = 0\nV limit = 350'000'000\nV k = 2\nV kk = 3\nL\n V p = k * kk\n I p > limit\n L.break\n I chowla(p) == p - 1\n print(p‘ is a perfect number’)\n count++\n k = kk + 1\n kk += k\nprint(‘There are ’count‘ perfect numbers < ’limit)\n", "language": "11l" }, { "code": "with Ada.Text_IO;\n\nprocedure Chowla_Numbers is\n\n function Chowla (N : Positive) return Natural is\n Sum : Natural := 0;\n I : Positive := 2;\n J : Positive;\n begin\n while I * I <= N loop\n if N mod I = 0 then\n J := N / I;\n Sum := Sum + I + (if I = J then 0 else J);\n end if;\n I := I + 1;\n end loop;\n return Sum;\n end Chowla;\n\n procedure Put_37_First is\n use Ada.Text_IO;\n begin\n for A in Positive range 1 .. 37 loop\n Put_Line (\"chowla(\" & A'Image & \") = \" & Chowla (A)'Image);\n end loop;\n end Put_37_First;\n\n procedure Put_Prime is\n use Ada.Text_IO;\n Count : Natural := 0;\n Power : Positive := 100;\n begin\n for N in Positive range 2 .. 10_000_000 loop\n if Chowla (N) = 0 then\n Count := Count + 1;\n end if;\n if N mod Power = 0 then\n Put_Line (\"There is \" & Count'Image & \" primes < \" & Power'Image);\n Power := Power * 10;\n end if;\n end loop;\n end Put_Prime;\n\n procedure Put_Perfect is\n use Ada.Text_IO;\n Count : Natural := 0;\n Limit : constant := 350_000_000;\n K : Natural := 2;\n Kk : Natural := 3;\n P : Natural;\n begin\n loop\n P := K * Kk;\n exit when P > Limit;\n\n if Chowla (P) = P - 1 then\n Put_Line (P'Image & \" is a perfect number\");\n Count := Count + 1;\n end if;\n K := Kk + 1;\n Kk := Kk + K;\n end loop;\n Put_Line (\"There are \" & Count'Image & \" perfect numbers < \" & Limit'Image);\n end Put_Perfect;\n\nbegin\n Put_37_First;\n Put_Prime;\n Put_Perfect;\nend Chowla_Numbers;\n", "language": "Ada" }, { "code": "BEGIN # find some Chowla numbers ( Chowla n = sum of divisors of n exclusing n and 1 ) #\n # returs the Chowla number of n #\n PROC chowla = ( INT n )INT:\n BEGIN\n INT sum := 0;\n FOR i FROM 2 WHILE i * i <= n DO\n IF n MOD i = 0 THEN\n INT j = n OVER i;\n sum +:= i + IF i = j THEN 0 ELSE j FI\n FI\n OD;\n sum\n END # chowla # ;\n\n FOR n TO 37 DO print( ( \"chowla(\", whole( n, 0 ), \") = \", whole( chowla( n ), 0 ), newline ) ) OD;\n\n INT count := 0, power := 100;\n FOR n FROM 2 TO 10 000 000 DO\n IF chowla( n ) = 0 THEN count +:= 1 FI;\n IF n MOD power = 0 THEN\n print( ( \"There are \", whole( count, 0 ), \" primes < \", whole( power, 0 ), newline ) );\n power *:= 10\n FI\n OD;\n count := 0;\n INT limit = 350 000 000;\n INT k := 2, kk := 3;\n WHILE INT p = k * kk;\n p <= limit\n DO\n IF chowla( p ) = p - 1 THEN\n print( ( whole( p, 0 ), \" is a perfect number\", newline ) );\n count +:= 1\n FI;\n k := kk + 1; kk +:= k\n OD;\n print( ( \"There are \", whole( count, 0 ), \" perfect numbers < \", whole( limit, 0 ), newline ) )\nEND\n", "language": "ALGOL-68" }, { "code": "chowla: function [n]-> sum remove remove factors n 1 n\ncountPrimesUpTo: function [limit][\n count: 1\n loop 3.. .step: 2 limit 'x [\n if zero? chowla x -> count: count + 1\n ]\n return count\n]\n\nloop 1..37 'i -> print [i \"=>\" chowla i]\nprint \"\"\n\nloop [100 1000 10000 100000 1000000 10000000] 'lim [\n print [\"primes up to\" lim \"=>\" countPrimesUpTo lim]\n]\nprint \"\"\nprint \"perfect numbers up to 35000000:\"\ni: 2\nwhile [i < 35000000][\n if (chowla i) = i - 1 -> print i\n i: i + 2\n]\n", "language": "Arturo" }, { "code": "# syntax: GAWK -f CHOWLA_NUMBERS.AWK\n# converted from Go\nBEGIN {\n for (i=1; i<=37; i++) {\n printf(\"chowla(%2d) = %s\\n\",i,chowla(i))\n }\n printf(\"\\nCount of primes up to:\\n\")\n count = 1\n limit = 1e7\n sieve(limit)\n power = 100\n for (i=3; i<limit; i+=2) {\n if (!c[i]) {\n count++\n }\n if (i == power-1) {\n printf(\"%10s = %s\\n\",commatize(power),commatize(count))\n power *= 10\n }\n }\n printf(\"\\nPerfect numbers:\")\n count = 0\n limit = 35000000\n k = 2\n kk = 3\n while (1) {\n if ((p = k * kk) > limit) {\n break\n }\n if (chowla(p) == p-1) {\n printf(\" %s\",commatize(p))\n count++\n }\n k = kk + 1\n kk += k\n }\n printf(\"\\nThere are %d perfect numbers <= %s\\n\",count,commatize(limit))\n exit(0)\n}\nfunction chowla(n, i,j,sum) {\n if (n < 1 || n != int(n)) {\n return sprintf(\"%s is invalid\",n)\n }\n for (i=2; i*i<=n; i++) {\n if (n%i == 0) {\n j = n / i\n sum += (i == j) ? i : i + j\n }\n }\n return(sum+0)\n}\nfunction commatize(x, num) {\n if (x < 0) {\n return \"-\" commatize(-x)\n }\n x = int(x)\n num = sprintf(\"%d.\",x)\n while (num ~ /^[0-9][0-9][0-9][0-9]/) {\n sub(/[0-9][0-9][0-9][,.]/,\",&\",num)\n }\n sub(/\\.$/,\"\",num)\n return(num)\n}\nfunction sieve(limit, i,j) {\n for (i=1; i<=limit; i++) {\n c[i] = 0\n }\n for (i=3; i*3<limit; i+=2) {\n if (!c[i] && chowla(i) == 0) {\n for (j=3*i; j<limit; j+=2*i) {\n c[j] = 1\n }\n }\n }\n}\n", "language": "AWK" }, { "code": "#include <stdio.h>\n\nunsigned chowla(const unsigned n) {\n unsigned sum = 0;\n for (unsigned i = 2, j; i * i <= n; i ++) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);\n return sum;\n}\n\nint main(int argc, char const *argv[]) {\n unsigned a;\n for (unsigned n = 1; n < 38; n ++) printf(\"chowla(%u) = %u\\n\", n, chowla(n));\n\n unsigned n, count = 0, power = 100;\n for (n = 2; n < 10000001; n ++) {\n if (chowla(n) == 0) count ++;\n if (n % power == 0) printf(\"There is %u primes < %u\\n\", count, power), power *= 10;\n }\n\n count = 0;\n unsigned limit = 350000000;\n unsigned k = 2, kk = 3, p;\n for ( ; ; ) {\n if ((p = k * kk) > limit) break;\n if (chowla(p) == p - 1) {\n printf(\"%d is a perfect number\\n\", p);\n count ++;\n }\n k = kk + 1; kk += k;\n }\n printf(\"There are %u perfect numbers < %u\\n\", count, limit);\n return 0;\n}\n", "language": "C" }, { "code": "#include <vector>\n#include <iostream>\n\nusing namespace std;\n\nint chowla(int n)\n{\n\tint sum = 0;\n\tfor (int i = 2, j; i * i <= n; i++)\n\t\tif (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);\n\treturn sum;\n}\n\nvector<bool> sieve(int limit)\n{\n\t// True denotes composite, false denotes prime.\n\t// Only interested in odd numbers >= 3\n\tvector<bool> c(limit);\n\tfor (int i = 3; i * 3 < limit; i += 2)\n\t\tif (!c[i] && (chowla(i) == 0))\n\t\t\tfor (int j = 3 * i; j < limit; j += 2 * i)\n\t\t\t\tc[j] = true;\n\treturn c;\n}\n\nint main()\n{\n\tcout.imbue(locale(\"\"));\n\tfor (int i = 1; i <= 37; i++)\n\t\tcout << \"chowla(\" << i << \") = \" << chowla(i) << \"\\n\";\n\tint count = 1, limit = (int)(1e7), power = 100;\n\tvector<bool> c = sieve(limit);\n\tfor (int i = 3; i < limit; i += 2)\n\t{\n\t\tif (!c[i]) count++;\n\t\tif (i == power - 1)\n\t\t{\n\t\t\tcout << \"Count of primes up to \" << power << \" = \"<< count <<\"\\n\";\n\t\t\tpower *= 10;\n\t\t}\n\t}\n\n\tcount = 0; limit = 35000000;\n\tint k = 2, kk = 3, p;\n\tfor (int i = 2; ; i++)\n\t{\n\t\tif ((p = k * kk) > limit) break;\n\t\tif (chowla(p) == p - 1)\n\t\t{\n\t\t\tcout << p << \" is a number that is perfect\\n\";\n\t\t\tcount++;\n\t\t}\n\t\tk = kk + 1; kk += k;\n\t}\n\tcout << \"There are \" << count << \" perfect numbers <= 35,000,000\\n\";\n\treturn 0;\n}\n", "language": "C++" }, { "code": "using System;\n\nnamespace chowla_cs\n{\n class Program\n {\n static int chowla(int n)\n {\n int sum = 0;\n for (int i = 2, j; i * i <= n; i++)\n if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);\n return sum;\n }\n\n static bool[] sieve(int limit)\n {\n // True denotes composite, false denotes prime.\n // Only interested in odd numbers >= 3\n bool[] c = new bool[limit];\n for (int i = 3; i * 3 < limit; i += 2)\n if (!c[i] && (chowla(i) == 0))\n for (int j = 3 * i; j < limit; j += 2 * i)\n c[j] = true;\n return c;\n }\n\n static void Main(string[] args)\n {\n for (int i = 1; i <= 37; i++)\n Console.WriteLine(\"chowla({0}) = {1}\", i, chowla(i));\n int count = 1, limit = (int)(1e7), power = 100;\n bool[] c = sieve(limit);\n for (int i = 3; i < limit; i += 2)\n {\n if (!c[i]) count++;\n if (i == power - 1)\n {\n Console.WriteLine(\"Count of primes up to {0,10:n0} = {1:n0}\", power, count);\n power *= 10;\n }\n }\n\n count = 0; limit = 35000000;\n int k = 2, kk = 3, p;\n for (int i = 2; ; i++)\n {\n if ((p = k * kk) > limit) break;\n if (chowla(p) == p - 1)\n {\n Console.WriteLine(\"{0,10:n0} is a number that is perfect\", p);\n count++;\n }\n k = kk + 1; kk += k;\n }\n Console.WriteLine(\"There are {0} perfect numbers <= 35,000,000\", count);\n if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey();\n }\n }\n}\n", "language": "C-sharp" }, { "code": "% Chowla's function\nchowla = proc (n: int) returns (int)\n sum: int := 0\n i: int := 2\n while i*i <= n do\n if n//i = 0 then\n sum := sum + i\n j: int := n/i\n if i ~= j then\n sum := sum + j\n end\n end\n i := i + 1\n end\n return(sum)\nend chowla\n\n% A number is prime iff chowla(n) is 0\nprime = proc (n: int) returns (bool)\n return(chowla(n) = 0)\nend prime\n\n% A number is perfect iff chowla(n) equals n-1\nperfect = proc (n: int) returns (bool)\n return(chowla(n) = n-1)\nend perfect\n\nstart_up = proc ()\n LIMIT = 35000000\n po: stream := stream$primary_output()\n\n % Show chowla(1) through chowla(37)\n for i: int in int$from_to(1, 37) do\n stream$putl(po, \"chowla(\" || int$unparse(i) || \") = \"\n || int$unparse(chowla(i)))\n end\n\n % Count primes up to powers of 10\n pow10: int := 2 % start with 100\n primecount: int := 1 % assume 2 is prime, then test only odd numbers\n candidate: int := 3\n while pow10 <= 7 do\n if candidate >= 10**pow10 then\n stream$putl(po, \"There are \"\n || int$unparse(primecount)\n || \" primes up to \"\n || int$unparse(10**pow10))\n pow10 := pow10 + 1\n end\n if prime(candidate) then primecount := primecount + 1 end\n candidate := candidate + 2\n end\n\n % Find perfect numbers up to 35 million\n perfcount: int := 0\n k: int := 2\n kk: int := 3\n while true do\n n: int := k * kk\n if n >= LIMIT then break end\n if perfect(n) then\n perfcount := perfcount + 1\n stream$putl(po, int$unparse(n) || \" is a perfect number.\")\n end\n k := kk + 1\n kk := kk + k\n end\n stream$putl(po, \"There are \" || int$unparse(perfcount) ||\n \" perfect numbers < 35,000,000.\")\nend start_up\n", "language": "CLU" }, { "code": "include \"cowgol.coh\";\n\nsub chowla(n: uint32): (sum: uint32) is\n sum := 0;\n var i: uint32 := 2;\n\n while i*i <= n loop\n if n % i == 0 then\n sum := sum + i;\n var j := n / i;\n if i != j then\n sum := sum + j;\n end if;\n end if;\n i := i + 1;\n end loop;\nend sub;\n\nvar n: uint32 := 1;\nwhile n <= 37 loop\n print(\"chowla(\");\n print_i32(n);\n print(\") = \");\n print_i32(chowla(n));\n print(\"\\n\");\n n := n + 1;\nend loop;\n\nn := 2;\nvar power: uint32 := 100;\nvar count: uint32 := 0;\nwhile n <= 10000000 loop\n if chowla(n) == 0 then\n count := count + 1;\n end if;\n if n % power == 0 then\n print(\"There are \");\n print_i32(count);\n print(\" primes < \");\n print_i32(power);\n print_nl();\n power := power * 10;\n end if;\n n := n + 1;\nend loop;\n\ncount := 0;\nconst LIMIT := 35000000;\nvar k: uint32 := 2;\nvar kk: uint32 := 3;\nloop\n n := k * kk;\n if n > LIMIT then break; end if;\n if chowla(n) == n-1 then\n print_i32(n);\n print(\" is a perfect number.\\n\");\n count := count + 1;\n end if;\n k := kk + 1;\n kk := kk + k;\nend loop;\n\nprint(\"There are \");\nprint_i32(count);\nprint(\" perfect numbers < \");\nprint_i32(LIMIT);\nprint_nl();\n", "language": "Cowgol" }, { "code": "import std.stdio;\n\nint chowla(int n) {\n int sum;\n for (int i = 2, j; i * i <= n; ++i) {\n if (n % i == 0) {\n sum += i + (i == (j = n / i) ? 0 : j);\n }\n }\n return sum;\n}\n\nbool[] sieve(int limit) {\n // True denotes composite, false denotes prime.\n // Only interested in odd numbers >= 3\n auto c = new bool[limit];\n for (int i = 3; i * 3 < limit; i += 2) {\n if (!c[i] && (chowla(i) == 0)) {\n for (int j = 3 * i; j < limit; j += 2 * i) {\n c[j] = true;\n }\n }\n }\n return c;\n}\n\nvoid main() {\n foreach (i; 1..38) {\n writefln(\"chowla(%d) = %d\", i, chowla(i));\n }\n int count = 1;\n int limit = cast(int)1e7;\n int power = 100;\n bool[] c = sieve(limit);\n for (int i = 3; i < limit; i += 2) {\n if (!c[i]) {\n count++;\n }\n if (i == power - 1) {\n writefln(\"Count of primes up to %10d = %d\", power, count);\n power *= 10;\n }\n }\n\n count = 0;\n limit = 350_000_000;\n int k = 2;\n int kk = 3;\n int p;\n for (int i = 2; ; ++i) {\n p = k * kk;\n if (p > limit) {\n break;\n }\n if (chowla(p) == p - 1) {\n writefln(\"%10d is a number that is perfect\", p);\n count++;\n }\n k = kk + 1;\n kk += k;\n }\n writefln(\"There are %d perfect numbers <= 35,000,000\", count);\n}\n", "language": "D" }, { "code": "func chowla(n) {\n var sum = 0\n var i = 2\n var j = 0\n while i * i <= n {\n if n % i == 0 {\n j = n / i\n var app = if i == j {\n 0\n } else {\n j\n }\n sum += i + app\n }\n i += 1\n }\n return sum\n}\n\nfunc sieve(limit) {\n var c = Array.Empty(limit)\n var i = 3\n while i * 3 < limit {\n if !c[i] && (chowla(i) == 0) {\n var j = 3 * i\n while j < limit {\n c[j] = true\n j += 2 * i\n }\n }\n i += 2\n }\n return c\n}\n\nfor i in 1..37 {\n print(\"chowla(\\(i)) = \\(chowla(i))\")\n}\n\nvar count = 1\nvar limit = 10000000\nvar power = 100\nvar c = sieve(limit)\n\nvar i = 3\nwhile i < limit {\n if !c[i] {\n count += 1\n }\n if i == power - 1 {\n print(\"Count of primes up to \\(power) = \\(count)\")\n power *= 10\n }\n i += 2\n}\n\ncount = 0\nlimit = 35000000\nvar k = 2\nvar kk = 3\nvar p\ni = 2\n\nwhile true {\n p = k * kk\n if p > limit {\n break\n }\n if chowla(p) == p - 1 {\n print(\"\\(p) is a number that is perfect\")\n count += 1\n }\n k = kk + 1\n kk += k\n}\n\nprint(\"There are \\(count) perfect numbers <= 35,000,000\")\n", "language": "Dyalect" }, { "code": "fastfunc chowla n .\n sum = 0\n i = 2\n while i * i <= n\n if n mod i = 0\n j = n div i\n if i = j\n sum += i\n else\n sum += i + j\n .\n .\n i += 1\n .\n return sum\n.\nproc sieve . c[] .\n i = 3\n while i * 3 <= len c[]\n if c[i] = 0\n if chowla i = 0\n j = 3 * i\n while j <= len c[]\n c[j] = 1\n j += 2 * i\n .\n .\n .\n i += 2\n .\n.\nproc commatize n . s$ .\n s$[] = strchars n\n s$ = \"\"\n l = len s$[]\n for i = 1 to len s$[]\n if i > 1 and l mod 3 = 0\n s$ &= \",\"\n .\n l -= 1\n s$ &= s$[i]\n .\n.\nprint \"chowla number from 1 to 37\"\nfor i = 1 to 37\n print \" \" & i & \": \" & chowla i\n.\nproc main . .\n print \"\"\n len c[] 10000000\n count = 1\n sieve c[]\n power = 100\n i = 3\n while i <= len c[]\n if c[i] = 0\n count += 1\n .\n if i = power - 1\n commatize power p$\n commatize count c$\n print \"There are \" & c$ & \" primes up to \" & p$\n power *= 10\n .\n i += 2\n .\n print \"\"\n limit = 35000000\n count = 0\n i = 2\n k = 2\n kk = 3\n repeat\n p = k * kk\n until p > limit\n if chowla p = p - 1\n commatize p s$\n print s$ & \" is a perfect number\"\n count += 1\n .\n k = kk + 1\n kk += k\n i += 1\n .\n commatize limit s$\n print \"There are \" & count & \" perfect mumbers up to \" & s$\n.\nmain\n", "language": "EasyLang" }, { "code": "fun chowla = int by int n\n int sum = 0\n int j = 0\n for int i = 2; i * i <= n; i++ do\n if n % i == 0 do sum += i + when(i == (j = n / i), 0, j) end\n end\n return sum\nend\nfun sieve = List by int limit\n List c = logic[].with(limit)\n for int i = 3; i * 3 < limit; i += 2\n if c[i] or chowla(i) != 0 do continue end\n for int j = 3 * i; j < limit; j += 2 * i do c[j] = true end\n end\n return c\nend\n# find and display (1 per line) for the 1st 37 integers\nfor int i = 1; i <= 37; i++ do writeLine(\"chowla(\" + i + \") = \" + chowla(i)) end\nint count = 1\nint limit = 10000000\nint power = 100\nList c = sieve(limit)\nfor int i = 3; i < limit; i += 2\n if not c[i] do count++ end\n if i == power - 1\n writeLine(\"Count of primes up to \" + power + \" = \" + count)\n power *= 10\n end\nend\ncount = 0\nlimit = 35000000\nint k = 2\nint kk = 3\nint p\nfor int i = 2; ; i++\n if (p = k * kk) > limit do break end\n if chowla(p) == p - 1\n writeLine(p + \" is a number that is perfect\")\n count++\n end\n k = kk + 1\n kk += k\nend\nwriteLine(\"There are \" + count + \" perfect numbers <= 35,000,000\")\n", "language": "EMal" }, { "code": "USING: formatting fry grouping.extras io kernel math\nmath.primes.factors math.ranges math.statistics sequences\ntools.memory.private ;\nIN: rosetta-code.chowla-numbers\n\n: chowla ( n -- m )\n dup 1 = [ 1 - ] [ [ divisors sum ] [ - 1 - ] bi ] if ;\n\n: show-chowla ( n -- )\n [1,b] [ dup chowla \"chowla(%02d) = %d\\n\" printf ] each ;\n\n: count-primes ( seq -- )\n dup 0 prefix [ [ 1 + ] dip 2 <range> ] 2clump-map\n [ [ chowla zero? ] count ] map cum-sum\n [ [ commas ] bi@ \"Primes up to %s: %s\\n\" printf ] 2each ;\n\n: show-perfect ( n -- )\n [ 2 3 ] dip '[ 2dup * dup _ > ] [\n dup [ chowla ] [ 1 - = ] bi\n [ commas \"%s is perfect\\n\" printf ] [ drop ] if\n [ nip 1 + ] [ nip dupd + ] 2bi\n ] until 3drop ;\n\n: chowla-demo ( -- )\n 37 show-chowla nl { 100 1000 10000 100000 1000000 10000000 }\n count-primes nl 35e7 show-perfect ;\n\nMAIN: chowla-demo\n", "language": "Factor" }, { "code": " PROGRAM CHOWLA\n\n CALL PUT_1ST_37\n CALL PUT_PRIME\n CALL PUT_PERFECT\n\n END\n\n INTEGER*4 FUNCTION CHOWLA1(N)\n\nC The Chowla number of N is the sum of the divisors of N\nC excluding unity and N where N is a positive integer\n\n IMPLICIT INTEGER*4 (A-Z)\n\n IF (N .LE. 0) STOP 'Argument to Chowla function must be > 0'\n\n SUM = 0\n I = 2\n\n 100 CONTINUE\n IF (I * I .GT. N) GOTO 200\n\n IF (MOD(N, I) .NE. 0) GOTO 110\n J = N / I\n SUM = SUM + I\n IF ( I .NE. J) SUM = SUM + J\n 110 CONTINUE\n\n I = I + 1\n GOTO 100\n\n 200 CONTINUE\n\n CHOWLA1 = SUM\n\n RETURN\n\n END\n\n SUBROUTINE PUT_1ST_37\n IMPLICIT INTEGER*4 (A-Z)\n\n DO 100 I = 1, 37\n PRINT 900, I, CHOWLA1(I)\n 100 CONTINUE\n\n RETURN\n\n 900 FORMAT(1H , 'CHOWLA(', I2, ') = ', I2)\n\n END\n\n SUBROUTINE PUT_PRIME\n IMPLICIT INTEGER*4 (A-Z)\n PARAMETER LIMIT = 10000000\n\n COUNT = 0\n POWER = 100\n\n DO 200 N = 2, LIMIT\n\n IF (CHOWLA1(N) .EQ. 0) COUNT = COUNT + 1\n\n IF (MOD(N, POWER) .NE. 0) GOTO 100\n\n PRINT 900, COUNT, POWER\n POWER = POWER * 10\n\n 100 CONTINUE\n\n 200 CONTINUE\n\n RETURN\n\n 900 FORMAT(1H ,'There are ', I12, ' primes < ', I12)\n\n END\n\n SUBROUTINE PUT_PERFECT\n IMPLICIT INTEGER*4 (A-Z)\n PARAMETER LIMIT = 35000000\n\n COUNT = 0\n K = 2\n KK = 3\n\n 100 CONTINUE\n\n P = K * KK\n\n IF (P .GT. LIMIT) GOTO 300\n\n IF (CHOWLA1(P) .NE. P - 1) GOTO 200\n PRINT 900, P\n COUNT = COUNT + 1\n\n 200 CONTINUE\n\n K = KK + 1\n KK = KK + K\n\n GOTO 100\n\n 300 CONTINUE\n\n PRINT 910, COUNT, LIMIT\n\n RETURN\n\n 900 FORMAT(1H , I10, ' is a perfect number')\n 910 FORMAT(1H , 'There are ', I10, ' perfect numbers < ', I10)\n\n END\n", "language": "Fortran" }, { "code": "' Chowla_numbers\n\n#include \"string.bi\"\n\nDim Shared As Long limite\nlimite = 10000000\nDim Shared As Boolean c(limite)\nDim As Long count, topenumprimo, a\ncount = 1\ntopenumprimo = 100\nDim As Longint p, k, kk, limitenumperfect\nlimitenumperfect = 35000000\nk = 2: kk = 3\n\nDeclare Function chowla(Byval n As Longint) As Longint\nDeclare Sub sieve(Byval limite As Long, c() As Boolean)\n\nFunction chowla(Byval n As Longint) As Longint\n Dim As Long i, j, r\n i = 2\n Do While i * i <= n\n j = n \\ i\n If n Mod i = 0 Then\n r += i\n If i <> j Then r += j\n End If\n i += 1\n Loop\n chowla = r\nEnd Function\n\nSub sieve(Byval limite As Long, c() As Boolean)\n Dim As Long i, j\n Redim As Boolean c(limite - 1)\n i = 3\n Do While i * 3 < limite\n If Not c(i) Then\n If chowla(i) = false Then\n j = 3 * i\n Do While j < limite\n c(j) = true\n j += 2 * i\n Loop\n End If\n End If\n i += 2\n Loop\nEnd Sub\n\nPrint \"Chowla numbers\"\nFor a = 1 To 37\n Print \"chowla(\" & Trim(Str(a)) & \") = \" & Trim(Str(chowla(a)))\nNext a\n\n' Si chowla(n) = falso and n > 1 Entonces n es primo\nPrint: Print \"Contando los numeros primos hasta: \"\nsieve(limite, c())\nFor a = 3 To limite - 1 Step 2\n If Not c(a) Then count += 1\n If a = topenumprimo - 1 Then\n Print Using \"########## hay\"; topenumprimo;\n Print count\n topenumprimo *= 10\n End If\nNext a\n\n' Si chowla(n) = n - 1 and n > 1 Entonces n es un número perfecto\nPrint: Print \"Buscando numeros perfectos... \"\ncount = 0\nDo\n p = k * kk : If p > limitenumperfect Then Exit Do\n If chowla(p) = p - 1 Then\n Print Using \"##########,# es un numero perfecto\"; p\n count += 1\n End If\n k = kk + 1 : kk += k\nLoop\nPrint: Print \"Hay \" & count & \" numeros perfectos <= \" & Format(limitenumperfect, \"###############################,#\")\n\nPrint: Print \"Pulsa una tecla para salir\"\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "local fn Chowla( n as NSUInteger ) as NSUInteger\n NSUInteger i, j, r = 0\n\n i = 2\n while ( i * i <= n )\n j = n / i\n if ( n mod i == 0 )\n r += i\n if ( i != j )\n r += j\n end if\n end if\n i++\n wend\nend fn = r\n\nlocal fn DoIt\n NSUInteger n, count = 0, power = 100, limit, k, kk, p = 0\n\n for n = 1 to 37\n printf @\"chowla(%u) = %u\", n, fn Chowla( n )\n next\n\n for n = 2 to 10000000\n if ( fn Chowla(n) == 0 ) then count ++\n if ( n mod power == 0 ) then printf @\"There are %u primes < %-7u\", count, power : power *= 10\n next\n\n count = 0\n limit = 350000000\n k = 2 : kk = 3\n do\n p = k * kk\n if ( fn Chowla( p ) == p - 1 )\n printf @\"%9u is a perfect number\", p\n count++\n end if\n k = kk + 1\n kk = kk + k\n until ( p > limit )\n printf @\"There are %u perfect numbers < %u\", count, limit\nend fn\n\nfn DoIt\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc chowla(n int) int {\n if n < 1 {\n panic(\"argument must be a positive integer\")\n }\n sum := 0\n for i := 2; i*i <= n; i++ {\n if n%i == 0 {\n j := n / i\n if i == j {\n sum += i\n } else {\n sum += i + j\n }\n }\n }\n return sum\n}\n\nfunc sieve(limit int) []bool {\n // True denotes composite, false denotes prime.\n // Only interested in odd numbers >= 3\n c := make([]bool, limit)\n for i := 3; i*3 < limit; i += 2 {\n if !c[i] && chowla(i) == 0 {\n for j := 3 * i; j < limit; j += 2 * i {\n c[j] = true\n }\n }\n }\n return c\n}\n\nfunc commatize(n int) string {\n s := fmt.Sprintf(\"%d\", n)\n le := len(s)\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0:i] + \",\" + s[i:]\n }\n return s\n}\n\nfunc main() {\n for i := 1; i <= 37; i++ {\n fmt.Printf(\"chowla(%2d) = %d\\n\", i, chowla(i))\n }\n fmt.Println()\n\n count := 1\n limit := int(1e7)\n c := sieve(limit)\n power := 100\n for i := 3; i < limit; i += 2 {\n if !c[i] {\n count++\n }\n if i == power-1 {\n fmt.Printf(\"Count of primes up to %-10s = %s\\n\", commatize(power), commatize(count))\n power *= 10\n }\n }\n\n fmt.Println()\n count = 0\n limit = 35000000\n for i := uint(2); ; i++ {\n p := 1 << (i - 1) * (1<<i - 1) // perfect numbers must be of this form\n if p > limit {\n break\n }\n if chowla(p) == p-1 {\n fmt.Printf(\"%s is a perfect number\\n\", commatize(p))\n count++\n }\n }\n fmt.Println(\"There are\", count, \"perfect numbers <= 35,000,000\")\n}\n", "language": "Go" }, { "code": "class Chowla {\n static int chowla(int n) {\n if (n < 1) throw new RuntimeException(\"argument must be a positive integer\")\n int sum = 0\n int i = 2\n while (i * i <= n) {\n if (n % i == 0) {\n int j = (int) (n / i)\n sum += (i == j) ? i : i + j\n }\n i++\n }\n return sum\n }\n\n static boolean[] sieve(int limit) {\n // True denotes composite, false denotes prime.\n // Only interested in odd numbers >= 3\n boolean[] c = new boolean[limit]\n for (int i = 3; i < limit / 3; i += 2) {\n if (!c[i] && chowla(i) == 0) {\n for (int j = 3 * i; j < limit; j += 2 * i) {\n c[j] = true\n }\n }\n }\n return c\n }\n\n static void main(String[] args) {\n for (int i = 1; i <= 37; i++) {\n printf(\"chowla(%2d) = %d\\n\", i, chowla(i))\n }\n println()\n\n int count = 1\n int limit = 10_000_000\n boolean[] c = sieve(limit)\n int power = 100\n for (int i = 3; i < limit; i += 2) {\n if (!c[i]) {\n count++\n }\n if (i == power - 1) {\n printf(\"Count of primes up to %,10d = %,7d\\n\", power, count)\n power *= 10\n }\n }\n println()\n\n count = 0\n limit = 35_000_000\n int i = 2\n while (true) {\n int p = (1 << (i - 1)) * ((1 << i) - 1) // perfect numbers must be of this form\n if (p > limit) break\n if (chowla(p) == p - 1) {\n printf(\"%,d is a perfect number\\n\", p)\n count++\n }\n i++\n }\n printf(\"There are %,d perfect numbers <= %,d\\n\", count, limit)\n }\n}\n", "language": "Groovy" }, { "code": "import Control.Concurrent (setNumCapabilities)\nimport Control.Monad.Par (runPar, get, spawnP)\nimport Control.Monad (join, (>=>))\nimport Data.List.Split (chunksOf)\nimport Data.List (intercalate, mapAccumL, genericTake, genericDrop)\nimport Data.Bifunctor (bimap)\nimport GHC.Conc (getNumProcessors)\nimport Math.NumberTheory.Primes (factorise, unPrime)\nimport Text.Printf (printf)\n\nchowla :: Word -> Word\nchowla 1 = 0\nchowla n = f n\n where\n f = (-) =<< pred . product . fmap sumFactor . factorise\n sumFactor (n, e) = foldr (\\p s -> s + unPrime n^p) 1 [1..e]\n\nchowlas :: [Word] -> [(Word, Word)]\nchowlas [] = []\nchowlas xs = runPar $ join <$>\n (mapM (spawnP . fmap ((,) <*> chowla)) >=> mapM get) (chunksOf (10^6) xs)\n\nchowlaPrimes :: [(Word, Word)] -> (Word, Word) -> (Word, Word)\nchowlaPrimes chowlas range = (count chowlas, snd range)\n where\n isPrime (1, n) = False\n isPrime (_, n) = n == 0\n count = fromIntegral . length . filter isPrime . between range\n between (min, max) = genericTake (max - pred min) . genericDrop (pred min)\n\nchowlaPerfects :: [(Word, Word)] -> [Word]\nchowlaPerfects = fmap fst . filter isPerfect\n where\n isPerfect (1, _) = False\n isPerfect (n, c) = c == pred n\n\ncommas :: (Show a, Integral a) => a -> String\ncommas = reverse . intercalate \",\" . chunksOf 3 . reverse . show\n\nmain :: IO ()\nmain = do\n cores <- getNumProcessors\n setNumCapabilities cores\n printf \"Using %d cores\\n\" cores\n\n mapM_ (uncurry (printf \"chowla(%2d) = %d\\n\")) $ take 37 allChowlas\n mapM_ (uncurry (printf \"There are %8s primes < %10s\\n\"))\n (chowlaP\n [ (1, 10^2)\n , (succ $ 10^2, 10^3)\n , (succ $ 10^3, 10^4)\n , (succ $ 10^4, 10^5)\n , (succ $ 10^5, 10^6)\n , (succ $ 10^6, 10^7) ])\n\n mapM_ (printf \"%10s is a perfect number.\\n\" . commas) perfects\n printf \"There are %2d perfect numbers < 35,000,000\\n\" $ length perfects\n where\n chowlaP = fmap (bimap commas commas) . snd\n . mapAccumL (\\total (count, max) -> (total + count, (total + count, max))) 0\n . fmap (chowlaPrimes $ take (10^7) allChowlas)\n perfects = chowlaPerfects allChowlas\n allChowlas = chowlas [1..35*10^6]\n", "language": "Haskell" }, { "code": "chowla=: >: -~ >:@#.~/.~&.q: NB. sum of factors - (n + 1)\n\nintsbelow=: (2 }. i.)\"0\ncountPrimesbelow=: +/@(0 = chowla)@intsbelow\nfindPerfectsbelow=: (#~ <: = chowla)@intsbelow\n", "language": "J" }, { "code": " (] ,. chowla) >: i. 37 NB. chowla numbers 1-37\n 1 0\n 2 0\n 3 0\n 4 2\n 5 0\n 6 5\n 7 0\n 8 6\n 9 3\n10 7\n11 0\n12 15\n13 0\n14 9\n15 8\n16 14\n17 0\n18 20\n19 0\n20 21\n21 10\n22 13\n23 0\n24 35\n25 5\n26 15\n27 12\n28 27\n29 0\n30 41\n31 0\n32 30\n33 14\n34 19\n35 12\n36 54\n37 0\n countPrimesbelow 100 1000 10000 100000 1000000 10000000\n25 168 1229 9592 78498 664579\n findPerfectsbelow 35000000\n6 28 496 8128 33550336\n", "language": "J" }, { "code": "public class Chowla {\n\n public static void main(String[] args) {\n int[] chowlaNumbers = findChowlaNumbers(37);\n for (int i = 0; i < chowlaNumbers.length; i++) {\n System.out.printf(\"chowla(%d) = %d%n\", (i+1), chowlaNumbers[i]);\n }\n System.out.println();\n\n int[][] primes = countPrimes(100, 10_000_000);\n for (int i = 0; i < primes.length; i++) {\n System.out.printf(Locale.US, \"There is %,d primes up to %,d%n\", primes[i][1], primes[i][0]);\n }\n System.out.println();\n\n int[] perfectNumbers = findPerfectNumbers(35_000_000);\n for (int i = 0; i < perfectNumbers.length; i++) {\n System.out.printf(\"%d is a perfect number%n\", perfectNumbers[i]);\n }\n System.out.printf(Locale.US, \"There are %d perfect numbers < %,d%n\", perfectNumbers.length, 35_000_000);\n }\n\n public static int chowla(int n) {\n if (n < 0) throw new IllegalArgumentException(\"n is not positive\");\n int sum = 0;\n for (int i = 2, j; i * i <= n; i++)\n if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);\n return sum;\n }\n\n protected static int[][] countPrimes(int power, int limit) {\n int count = 0;\n int[][] num = new int[countMultiplicity(limit, power)][2];\n for (int n = 2, i=0; n <= limit; n++) {\n if (chowla(n) == 0) count++;\n if (n % power == 0) {\n num[i][0] = power;\n num[i][1] = count;\n i++;\n power *= 10;\n }\n }\n return num;\n }\n\n protected static int countMultiplicity(int limit, int start) {\n int count = 0;\n int cur = limit;\n while(cur >= start) {\n count++;\n cur = cur/10;\n }\n return count;\n }\n\n protected static int[] findChowlaNumbers(int limit) {\n int[] num = new int[limit];\n for (int i = 0; i < limit; i++) {\n num[i] = chowla(i+1);\n }\n return num;\n }\n\n protected static int[] findPerfectNumbers(int limit) {\n int count = 0;\n int[] num = new int[count];\n\n int k = 2, kk = 3, p;\n while ((p = k * kk) < limit) {\n if (chowla(p) == p - 1) {\n num = increaseArr(num);\n num[count++] = p;\n }\n k = kk + 1;\n kk += k;\n }\n return num;\n }\n\n private static int[] increaseArr(int[] arr) {\n int[] tmp = new int[arr.length + 1];\n System.arraycopy(arr, 0, tmp, 0, arr.length);\n return tmp;\n }\n}\n", "language": "Java" }, { "code": "def add(stream): reduce stream as $x (0; . + $x);\n\n# input should be an integer\ndef commatize:\n def digits: tostring | explode | reverse;\n if . == null then \"\"\n elif . < 0 then \"-\" + ((- .) | commatize)\n else [foreach digits[] as $d (-1; .+1;\n # \",\" is 44\n (select(. > 0 and . % 3 == 0)|44), $d)]\n | reverse\n | implode\n end;\n\ndef count(stream): reduce stream as $i (0; . + 1);\n\ndef lpad($len): tostring | ($len - length) as $l | (\" \" * $l)[:$l] + .;\n\n# To take advantage of gojq's arbitrary-precision integer arithmetic:\ndef power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);\n\n# unordered\ndef proper_divisors:\n . as $n\n | if $n > 1 then 1,\n ( range(2; 1 + (sqrt|floor)) as $i\n | if ($n % $i) == 0 then $i,\n (($n / $i) | if . == $i then empty else . end)\n else empty\n\t end)\n else empty\n end;\n\ndef chowla:\n if . == 1 then 0\n else add(proper_divisors) - 1\n end;\n\n# Input: a positive integer\ndef is_chowla_prime:\n . > 1 and chowla == 0;\n\n# In the interests of green(er) computing ...\ndef chowla_primes($n):\n 2, range(3; $n; 2) | select(is_chowla_prime);\n\ndef report_chowla_primes:\n reduce range(2; 10000000) as $i (null;\n if $i | is_chowla_prime\n then if $i < 10000000 then .[7] += 1 else . end\n | if $i < 1000000 then .[6] += 1 else . end\n | if $i < 100000 then .[5] += 1 else . end\n | if $i < 10000 then .[4] += 1 else . end\n | if $i < 1000 then .[3] += 1 else . end\n | if $i < 100 then .[2] += 1 else . end\n else . end)\n | (range(2;8) as $i\n | \"10 ^ \\($i) \\(.[$i]|commatize|lpad(16))\") ;\n\ndef is_chowla_perfect:\n (. > 1) and (chowla == . - 1);\n\ndef task:\n \" n\\(\"chowla\"|lpad(16))\",\n (range(1;38) | \"\\(lpad(3)): \\(chowla|lpad(10))\"),\n \"\\n n \\(\"Primes < n\"|lpad(10))\",\n report_chowla_primes,\n# \"\\nPerfect numbers up to 35e6\",\n# (range(1; 35e6) | select(is_chowla_perfect) | commatize)\n\"\"\n;\n\ntask\n", "language": "Jq" }, { "code": "using Primes, Formatting\n\nfunction chowla(n)\n if n < 1\n throw(\"Chowla function argument must be positive\")\n elseif n < 4\n return zero(n)\n else\n f = [one(n)]\n for (p,e) in factor(n)\n f = reduce(vcat, [f*p^j for j in 1:e], init=f)\n end\n return sum(f) - one(n) - n\n end\nend\n\nfunction countchowlas(n, asperfect=false, verbose=false)\n count = 0\n for i in 2:n # 1 is not prime or perfect so skip\n chow = chowla(i)\n if (asperfect && chow == i - 1) || (!asperfect && chow == 0)\n count += 1\n verbose && println(\"The number $(format(i, commas=true)) is \", asperfect ? \"perfect.\" : \"prime.\")\n end\n end\n count\nend\n\nfunction testchowla()\n println(\"The first 37 chowla numbers are:\")\n for i in 1:37\n println(\"Chowla($i) is \", chowla(i))\n end\n for i in [100, 1000, 10000, 100000, 1000000, 10000000]\n println(\"The count of the primes up to $(format(i, commas=true)) is $(format(countchowlas(i), commas=true))\")\n end\n println(\"The count of perfect numbers up to 35,000,000 is $(countchowlas(35000000, true, true)).\")\nend\n\ntestchowla()\n", "language": "Julia" }, { "code": "// Version 1.3.21\n\nfun chowla(n: Int): Int {\n if (n < 1) throw RuntimeException(\"argument must be a positive integer\")\n var sum = 0\n var i = 2\n while (i * i <= n) {\n if (n % i == 0) {\n val j = n / i\n sum += if (i == j) i else i + j\n }\n i++\n }\n return sum\n}\n\nfun sieve(limit: Int): BooleanArray {\n // True denotes composite, false denotes prime.\n // Only interested in odd numbers >= 3\n val c = BooleanArray(limit)\n for (i in 3 until limit / 3 step 2) {\n if (!c[i] && chowla(i) == 0) {\n for (j in 3 * i until limit step 2 * i) c[j] = true\n }\n }\n return c\n}\n\nfun main() {\n for (i in 1..37) {\n System.out.printf(\"chowla(%2d) = %d\\n\", i, chowla(i))\n }\n println()\n\n var count = 1\n var limit = 10_000_000\n val c = sieve(limit)\n var power = 100\n for (i in 3 until limit step 2) {\n if (!c[i]) count++\n if (i == power - 1) {\n System.out.printf(\"Count of primes up to %,-10d = %,d\\n\", power, count)\n power *= 10\n }\n }\n\n println()\n count = 0\n limit = 35_000_000\n var i = 2\n while (true) {\n val p = (1 shl (i - 1)) * ((1 shl i) - 1) // perfect numbers must be of this form\n if (p > limit) break\n if (chowla(p) == p - 1) {\n System.out.printf(\"%,d is a perfect number\\n\", p)\n count++\n }\n i++\n }\n println(\"There are $count perfect numbers <= 35,000,000\")\n}\n", "language": "Kotlin" }, { "code": "function chowla(n)\n local sum = 0\n local i = 2\n local j = 0\n while i * i <= n do\n if n % i == 0 then\n j = math.floor(n / i)\n sum = sum + i\n if i ~= j then\n sum = sum + j\n end\n end\n i = i + 1\n end\n return sum\nend\n\nfunction sieve(limit)\n -- True denotes composite, false denotes prime.\n -- Only interested in odd numbers >= 3\n local c = {}\n local i = 3\n while i * 3 < limit do\n if not c[i] and (chowla(i) == 0) then\n local j = 3 * i\n while j < limit do\n c[j] = true\n j = j + 2 * i\n end\n end\n i = i + 2\n end\n return c\nend\n\nfunction main()\n for i = 1, 37 do\n print(string.format(\"chowla(%d) = %d\", i, chowla(i)))\n end\n local count = 1\n local limit = math.floor(1e7)\n local power = 100\n local c = sieve(limit)\n local i = 3\n while i < limit do\n if not c[i] then\n count = count + 1\n end\n if i == power - 1 then\n print(string.format(\"Count of primes up to %10d = %d\", power, count))\n power = power * 10\n end\n i = i + 2\n end\n\n count = 0\n limit = 350000000\n local k = 2\n local kk = 3\n local p = 0\n i = 2\n while true do\n p = k * kk\n if p > limit then\n break\n end\n if chowla(p) == p - 1 then\n print(string.format(\"%10d is a number that is perfect\", p))\n count = count + 1\n end\n k = kk + 1\n kk = kk + k\n i = i + 1\n end\n print(string.format(\"There are %d perfect numbers <= 35,000,000\", count))\nend\n\nmain()\n", "language": "Lua" }, { "code": " NORMAL MODE IS INTEGER\n\n INTERNAL FUNCTION(N)\n ENTRY TO CHOWLA.\n SUM = 0\n THROUGH LOOP, FOR I=2, 1, I*I.G.N\n J = N/I\n WHENEVER J*I.E.N\n SUM = SUM + I\n WHENEVER I.NE.J, SUM = SUM + J\n END OF CONDITIONAL\nLOOP CONTINUE\n FUNCTION RETURN SUM\n END OF FUNCTION\n\n VECTOR VALUES CHWFMT = $7HCHOWLA(,I2,4H) = ,I2*$\n THROUGH CH37, FOR CH=1, 1, CH.G.37\nCH37 PRINT FORMAT CHWFMT, CH, CHOWLA.(CH)\n\n VECTOR VALUES PRIMES =\n 0 $10HTHERE ARE ,I6,S1,13HPRIMES BELOW ,I8*$\n\n POWER = 100\n COUNT = 0\n THROUGH PRM, FOR CH=2, 1, CH.G.10000000\n WHENEVER CHOWLA.(CH).E.0, COUNT = COUNT + 1\n WHENEVER (CH/POWER)*POWER.E.CH\n PRINT FORMAT PRIMES, COUNT, POWER\n POWER = POWER * 10\nPRM END OF CONDITIONAL\n\n COUNT = 0\n LIMIT = 35000000\n VECTOR VALUES PERFCT = $I8,S1,20HIS A PERFECT NUMBER.*$\n VECTOR VALUES PRFCNT =\n 0 $10HTHERE ARE ,I1,S1,22HPERFECT NUMBERS BELOW ,I8*$\n K = 2\n KK = 3\nLOOP CH = K * KK\n WHENEVER CH.G.LIMIT, TRANSFER TO DONE\n WHENEVER CHOWLA.(CH).E.CH-1\n PRINT FORMAT PERFCT, CH\n COUNT = COUNT + 1\n END OF CONDITIONAL\n K = KK + 1\n KK = KK + K\n TRANSFER TO LOOP\n\nDONE PRINT FORMAT PRFCNT, COUNT, LIMIT\n\n END OF PROGRAM\n", "language": "MAD" }, { "code": "ChowlaFunction := n -> NumberTheory:-SumOfDivisors(n) - n - 1;\n\nPrintChowla := proc(n::posint) local i;\nprintf(\"Integer : Chowla Number\\n\");\nfor i to n do\n printf(\"%d : %d\\n\", i, ChowlaFunction(i));\nend do;\nend proc:\n\ncountPrimes := n -> nops([ListTools[SearchAll](0, map(ChowlaFunction, [seq(1 .. n)]))]);\n\nfindPerfect := proc(n::posint) local to_check, found, k;\nto_check := map(ChowlaFunction, [seq(1 .. n)]);\nfound := [];\nfor k to n do\n if to_check(k) = k - 1 then\n found := [found, k];\n end if;\nend do;\nend proc:\n\nPrintChowla(37);\ncountPrimes(100);\ncountPrimes(1000);\ncountPrimes(10000);\ncountPrimes(100000);\ncountPrimes(1000000);\ncountPrimes(10000000);\nfindPerfect(35000000)\n", "language": "Maple" }, { "code": "ClearAll[Chowla]\nChowla[0 | 1] := 0\nChowla[n_] := DivisorSigma[1, n] - 1 - n\nTable[{i, Chowla[i]}, {i, 37}] // Grid\nPrintTemporary[Dynamic[n]];\ni = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 100, 2}]; i\ni = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 1000, 2}]; i\ni = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 10000, 2}]; i\ni = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 100000, 2}]; i\ni = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 1000000, 2}]; i\ni = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 10000000, 2}]; i\nReap[Do[If[Chowla[n] == n - 1, Sow[n]], {n, 1, 35 10^6}]][[2, 1]]\n", "language": "Mathematica" }, { "code": "import strformat\nimport strutils\n\nfunc chowla(n: uint64): uint64 =\n var sum = 0u64\n var i = 2u64\n var j: uint64\n while i * i <= n:\n if n mod i == 0:\n j = n div i\n sum += i\n if i != j:\n sum += j\n inc i\n sum\n\nfor n in 1u64..37:\n echo &\"chowla({n}) = {chowla(n)}\"\n\nvar count = 0\nvar power = 100u64\nfor n in 2u64..10_000_000:\n if chowla(n) == 0:\n inc count\n if n mod power == 0:\n echo &\"There are {insertSep($count, ','):>7} primes < {insertSep($power, ','):>10}\"\n power *= 10\n\ncount = 0\nconst limit = 350_000_000u64\nvar k = 2u64\nvar kk = 3u64\nvar p: uint64\nwhile true:\n p = k * kk\n if p > limit:\n break\n if chowla(p) == p - 1:\n echo &\"{insertSep($p, ','):>10} is a perfect number\"\n inc count\n k = kk + 1\n kk += k\necho &\"There are {count} perfect numbers < {insertSep($limit, ',')}\"\n", "language": "Nim" }, { "code": "chowla(n) = {\n if (n < 1, error(\"Chowla function argument must be positive\"));\n if (n < 4, return(0));\n my(divs = divisors(n));\n sum(i=1, #divs, divs[i]) - n - 1;\n}\n\n\\\\ Function to count Chowla numbers\ncountchowlas(n, asperfect = 1, verbose = 1) = {\n my(count = 0, chow, i);\n for (i = 2, n,\n chow = chowla(i);\n if ( (asperfect && (chow == i - 1)) || ((!asperfect) && (chow == 0)),\n count++;\n if (verbose, print(\"The number \" i \" is \" if (asperfect, \"perfect.\", \"prime.\")));\n );\n );\n count;\n}\n\n\\\\ Main execution block\n{\n print(\"The first 37 chowla numbers are:\");\n for (i = 1, 37, printf(\"Chowla(%s) is %s\\n\", Str(i), Str(chowla(i)) ) );\n m=100;\n while(m<=10000000, print(\"The count of the primes up to \" m \" is \" countchowlas(m, 0, 0)); m=m*10);\n print(\"The count of perfect numbers up to 35,000,000 is \" countchowlas(35000000, 1, 1));\n}\n", "language": "PARI-GP" }, { "code": "program Chowla_numbers;\n\n{$IFDEF FPC}\n {$MODE Delphi}\n{$ELSE}\n {$APPTYPE CONSOLE}\n{$ENDIF}\n\nuses\n SysUtils\n {$IFDEF FPC}\n ,StrUtils{for Numb2USA}\n {$ENDIF}\n;\n\n\n{$IFNDEF FPC}\nfunction Numb2USA(const S: string): string;\nvar\n I, NA: Integer;\nbegin\n I := Length(S);\n Result := S;\n NA := 0;\n while (I > 0) do\n begin\n if ((Length(Result) - I + 1 - NA) mod 3 = 0) and (I <> 1) then\n begin\n Insert(',', Result, I);\n Inc(NA);\n end;\n Dec(I);\n end;\nend;\n{$ENDIF}\n\nfunction Chowla(n: NativeUint): NativeUint;\nvar\n Divisor, Quotient: NativeUint;\nbegin\n result := 0;\n Divisor := 2;\n while sqr(Divisor) < n do\n begin\n Quotient := n div Divisor;\n if Quotient * Divisor = n then\n inc(result, Divisor + Quotient);\n inc(Divisor);\n end;\n if sqr(Divisor) = n then\n inc(result, Divisor);\nend;\n\nprocedure Count10Primes(Limit: NativeUInt);\nvar\n n, i, cnt: integer;\nbegin\n writeln;\n writeln(' primes til | count');\n i := 100;\n n := 2;\n cnt := 0;\n repeat\n repeat\n // Ord (true) = 1 ,Ord (false) = 0\n inc(cnt, ORD(chowla(n) = 0));\n inc(n);\n until n > i;\n writeln(Numb2USA(IntToStr(i)): 12, '|', Numb2USA(IntToStr(cnt)): 10);\n i := i * 10;\n until i > Limit;\nend;\n\nprocedure CheckPerf;\nvar\n k, kk, p, cnt, limit: NativeInt;\nbegin\n writeln;\n writeln(' number that is perfect');\n cnt := 0;\n limit := 35000000;\n k := 2;\n kk := 3;\n repeat\n p := k * kk;\n if p > limit then\n BREAK;\n if chowla(p) = (p - 1) then\n begin\n writeln(Numb2USA(IntToStr(p)): 12);\n inc(cnt);\n end;\n k := kk + 1;\n inc(kk, k);\n until false;\nend;\n\nvar\n I: integer;\n\nbegin\n for I := 2 to 37 do\n writeln('chowla(', I: 2, ') =', chowla(I): 3);\n Count10Primes(10 * 1000 * 1000);\n CheckPerf;\nend.\n", "language": "Pascal" }, { "code": "use strict;\nuse warnings;\nuse ntheory 'divisor_sum';\n\nsub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }\n\nsub chowla {\n my($n) = @_;\n $n < 2 ? 0 : divisor_sum($n) - ($n + 1);\n}\n\nsub prime_cnt {\n my($n) = @_;\n my $cnt = 1;\n for (3..$n) {\n $cnt++ if $_%2 and chowla($_) == 0\n }\n $cnt;\n}\n\nsub perfect {\n my($n) = @_;\n my @p;\n for my $i (1..$n) {\n push @p, $i if $i > 1 and chowla($i) == $i-1;\n }\n # map { push @p, $_ if $_ > 1 and chowla($_) == $_-1 } 1..$n; # speed penalty\n @p;\n}\n\nprintf \"chowla(%2d) = %2d\\n\", $_, chowla($_) for 1..37;\nprint \"\\nCount of primes up to:\\n\";\nprintf \"%10s %s\\n\", comma(10**$_), comma(prime_cnt(10**$_)) for 2..7;\nmy @perfect = perfect(my $limit = 35_000_000);\nprintf \"\\nThere are %d perfect numbers up to %s: %s\\n\",\n 1+$#perfect, comma($limit), join(' ', map { comma($_) } @perfect);\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">chowla</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">factors</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">sieve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">limit</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- True denotes composite, false denotes prime.\n -- Only interested in odd numbers &gt;= 3</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">limit</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">limit</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000080;font-style:italic;\">-- if not c[i] and chowla(i)==0 then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000080;font-style:italic;\">-- (see note below)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">i</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">limit</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">i</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">c</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">limit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1e7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">pow10</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">37</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">chowla</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"chowla[1..37]: %V\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">sieve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">limit</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">limit</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">==</span><span style=\"color: #000000;\">pow10</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Count of primes up to %,d = %,d\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">pow10</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">pow10</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #000000;\">10</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #000000;\">limit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">machine_bits</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #000000;\">32</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">1.4e11</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">2.4e18</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">--limit = power(2,iff(machine_bits()=32?53:64)) -- (see note below)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)*(</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- perfect numbers must be of this form</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">limit</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">chowla</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)==</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%,d is a perfect number\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"There are %d perfect numbers &lt;= %,d\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">limit</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "table\nchowla(1) = 0.\nchowla(2) = 0.\nchowla(3) = 0.\nchowla(N) = C, N>3 =>\n Max = floor(sqrt(N)),\n Sum = 0,\n foreach (X in 2..Max, N mod X == 0)\n Y := N div X,\n Sum := Sum + X + Y\n end,\n if (N == Max * Max) then\n Sum := Sum - Max\n end,\n C = Sum.\n\nmain =>\n foreach (I in 1..37)\n printf(\"chowla(%d) = %d\\n\", I, chowla(I))\n end,\n Ranges = {100, 1000, 10000, 100000, 1000000, 10000000},\n foreach (Range in Ranges)\n Count = 0,\n foreach (I in 2..Range)\n if (chowla(I) == 0) then\n Count := Count + 1\n end\n end,\n printf(\"There are %d primes less than %d.\\n\", Count, Range)\n end,\n Limit = 35000000,\n Count = 0,\n foreach (I in 2..Limit)\n if (chowla(I) == I-1) then\n printf(\"%d is a perfect number\\n\", I),\n Count := Count + 1\n end\n end,\n printf(\"There are %d perfect numbers less than %d.\\n\", Count, Limit).\n", "language": "Picat" }, { "code": "(de accu1 (Var Key)\n (if (assoc Key (val Var))\n (con @ (inc (cdr @)))\n (push Var (cons Key 1)) )\n Key )\n(de factor (N)\n (let\n (R NIL\n D 2\n L (1 2 2 . (4 2 4 2 4 6 2 6 .))\n M (sqrt N) )\n (while (>= M D)\n (if (=0 (% N D))\n (setq M\n (sqrt (setq N (/ N (accu1 'R D)))) )\n (inc 'D (pop 'L)) ) )\n (accu1 'R N)\n (mapcar\n '((L)\n (make\n (for N (cdr L)\n (link (** (car L) N)) ) ) )\n R ) ) )\n(de chowla (N)\n (let F (factor N)\n (-\n (sum\n prog\n (make\n (link 1)\n (mapc\n '((A)\n (chain\n (mapcan\n '((B)\n (mapcar '((C) (* C B)) (made)) )\n A ) ) )\n F ) ) )\n N\n 1 ) ) )\n(de prime (N)\n (and (> N 1) (=0 (chowla N))) )\n(de perfect (N)\n (and\n (> N 1)\n (= (chowla N) (dec N))) )\n(de countP (N)\n (let C 0\n (for I N\n (and (prime I) (inc 'C)) )\n C ) )\n(de listP (N)\n (make\n (for I N\n (and (perfect I) (link I)) ) ) )\n(for I 37\n (prinl \"chowla(\" I \") = \" (chowla I)) )\n(prinl \"Count of primes up to 100 = \" (countP 100))\n(prinl \"Count of primes up to 1000 = \" (countP 1000))\n(prinl \"Count of primes up to 10000 = \" (countP 10000))\n(prinl \"Count of primes up to 100000 = \" (countP 100000))\n(prinl \"Count of primes up to 1000000 = \" (countP 1000000))\n(prinl \"Count of primes up to 10000000 = \" (countP 10000000))\n(println (listP 35000000))\n", "language": "PicoLisp" }, { "code": "#COMPILE EXE\n#DIM ALL\n#COMPILER PBCC 6\n\nFUNCTION chowla(BYVAL n AS LONG) AS LONG\nREGISTER i AS LONG, j AS LONG\nLOCAL r AS LONG\n i = 2\n DO WHILE i * i <= n\n j = n \\ i\n IF n MOD i = 0 THEN\n r += i\n IF i <> j THEN\n r += j\n END IF\n END IF\n INCR i\n LOOP\n FUNCTION = r\nEND FUNCTION\n\nFUNCTION chowla1(BYVAL n AS QUAD) AS QUAD\nLOCAL i, j, r AS QUAD\n i = 2\n DO WHILE i * i <= n\n j = n \\ i\n IF n MOD i = 0 THEN\n r += i\n IF i <> j THEN\n r += j\n END IF\n END IF\n INCR i\n LOOP\n FUNCTION = r\nEND FUNCTION\n\nSUB sieve(BYVAL limit AS LONG, BYREF c() AS INTEGER)\nLOCAL i, j AS LONG\nREDIM c(limit - 1)\n i = 3\n DO WHILE i * 3 < limit\n IF NOT c(i) THEN\n IF chowla(i) = 0 THEN\n j = 3 * i\n DO WHILE j < limit\n c(j) = -1\n j += 2 * i\n LOOP\n END IF\n END IF\n i += 2\n LOOP\nEND SUB\n\nFUNCTION PBMAIN () AS LONG\nLOCAL i, count, limit, power AS LONG\nLOCAL c() AS INTEGER\nLOCAL s AS STRING\nLOCAL s30 AS STRING * 30\nLOCAL p, k, kk, r, ql AS QUAD\n FOR i = 1 TO 37\n s = \"chowla(\" & TRIM$(STR$(i)) & \") = \" & TRIM$(STR$(chowla(i)))\n CON.PRINT s\n NEXT i\n count = 1\n limit = 10000000\n power = 100\n CALL sieve(limit, c())\n FOR i = 3 TO limit - 1 STEP 2\n IF ISFALSE c(i) THEN count += 1\n IF i = power - 1 THEN\n RSET s30 = FORMAT$(power, \"#,##0\")\n s = \"Count of primes up to \" & s30 & \" =\" & STR$(count)\n CON.PRINT s\n power *= 10\n END IF\n NEXT i\n\n ql = 2 ^ 61\n k = 2: kk = 3\n RESET count\n DO\n p = k * kk : IF p > ql THEN EXIT DO\n IF chowla1(p) = p - 1 THEN\n RSET s30 = FORMAT$(p, \"#,##0\")\n s = s30 & \" is a number that is perfect\"\n CON.PRINT s\n count += 1\n END IF\n k = kk + 1 : kk += k\n LOOP\n s = \"There are\" & STR$(count) & \" perfect numbers <= \" & FORMAT$(ql, \"#,##0\")\n CON.PRINT s\n\n CON.PRINT \"press any key to exit program\"\n CON.WAITKEY$\nEND FUNCTION\n", "language": "PowerBASIC" }, { "code": "chowla(1, 0).\nchowla(2, 0).\nchowla(N, C) :-\n N > 2,\n Max is floor(sqrt(N)),\n findall(X, (between(2, Max, X), N mod X =:= 0), Xs),\n findall(Y, (member(X1, Xs), Y is N div X1, Y \\= Max), Ys),\n !,\n sum_list(Xs, S1),\n sum_list(Ys, S2),\n C is S1 + S2.\n\nprime_count(Upper, Upper, Count, Count) :-\n !.\n\nprime_count(Lower, Upper, Add, Count) :-\n chowla(Lower, 0),\n !,\n Lower1 is Lower + 1,\n Add1 is Add + 1,\n prime_count(Lower1, Upper, Add1, Count).\n\nprime_count(Lower, Upper, Add, Count) :-\n Lower1 is Lower + 1,\n prime_count(Lower1, Upper, Add, Count).\n\nperfect_numbers(Upper, Upper, AccNums, Nums) :-\n !,\n reverse(AccNums, Nums).\n\nperfect_numbers(Lower, Upper, AccNums, Nums) :-\n Perfect is Lower - 1,\n chowla(Lower, Perfect),\n !,\n Lower1 is Lower + 1,\n AccNums1 = [Lower|AccNums],\n perfect_numbers(Lower1, Upper, AccNums1, Nums).\n\nperfect_numbers(Lower, Upper, AccNums, Nums) :-\n Lower1 is Lower + 1,\n perfect_numbers(Lower1, Upper, AccNums, Nums).\n\nmain :-\n % Chowla numbers\n forall(between(1, 37, N), (\n chowla(N, C),\n format('chowla(~D) = ~D\\n', [N, C])\n )),\n\n % Prime numbers\n Ranges = [100, 1000, 10000, 100000, 1000000, 10000000],\n forall(member(Range, Ranges), (\n prime_count(2, Range, 0, PrimeCount),\n format('There are ~D primes less than ~D.\\n', [PrimeCount, Range])\n )),\n\n % Perfect numbers\n Limit = 35000000,\n perfect_numbers(2, Limit, [], Nums),\n forall(member(Perfect, Nums), (\n format('~D is a perfect number.\\n', [Perfect])\n )),\n length(Nums, PerfectCount),\n format('There are ~D perfect numbers < ~D.\\n', [PerfectCount, Limit]).\n", "language": "Prolog" }, { "code": "# https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.factor_.divisors\nfrom sympy import divisors\n\ndef chowla(n):\n return 0 if n < 2 else sum(divisors(n, generator=True)) - 1 -n\n\ndef is_prime(n):\n return chowla(n) == 0\n\ndef primes_to(n):\n return sum(chowla(i) == 0 for i in range(2, n))\n\ndef perfect_between(n, m):\n c = 0\n print(f\"\\nPerfect numbers between [{n:_}, {m:_})\")\n for i in range(n, m):\n if i > 1 and chowla(i) == i - 1:\n print(f\" {i:_}\")\n c += 1\n print(f\"Found {c} Perfect numbers between [{n:_}, {m:_})\")\n\n\nif __name__ == '__main__':\n for i in range(1, 38):\n print(f\"chowla({i:2}) == {chowla(i)}\")\n for i in range(2, 6):\n print(f\"primes_to({10**i:_}) == {primes_to(10**i):_}\")\n perfect_between(1, 1_000_000)\n print()\n for i in range(6, 8):\n print(f\"primes_to({10**i:_}) == {primes_to(10**i):_}\")\n perfect_between(1_000_000, 35_000_000)\n", "language": "Python" }, { "code": "from numba import jit\n\n# https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.factor_.divisors\nfrom sympy import divisors\n\n@jit\ndef chowla(n):\n return 0 if n < 2 else sum(divisors(n, generator=True)) - 1 -n\n\n@jit\ndef is_prime(n):\n return chowla(n) == 0\n\n@jit\ndef primes_to(n):\n acc = 0\n for i in range(2, n):\n if chowla(i) == 0:\n acc += 1\n return acc\n\n@jit\ndef _perfect_between(n, m):\n for i in range(n, m):\n if i > 1 and chowla(i) == i - 1:\n yield i\n\ndef perfect_between(n, m):\n c = 0\n print(f\"\\nPerfect numbers between [{n:_}, {m:_})\")\n for i in _perfect_between(n, m):\n print(f\" {i:_}\")\n c += 1\n print(f\"Found {c} Perfect numbers between [{n:_}, {m:_})\")\n", "language": "Python" }, { "code": "#lang racket\n\n(require racket/fixnum)\n\n(define cache-size 35000000)\n\n(define chowla-cache (make-fxvector cache-size -1))\n\n(define (chowla/uncached n)\n (for/sum ((i (sequence-filter (λ (x) (zero? (modulo n x))) (in-range 2 (add1 (quotient n 2)))))) i))\n\n(define (chowla n)\n (if (> n cache-size)\n (chowla/uncached n)\n (let ((idx (sub1 n)))\n (if (negative? (fxvector-ref chowla-cache idx))\n (let ((c (chowla/uncached n))) (fxvector-set! chowla-cache idx c) c)\n (fxvector-ref chowla-cache idx)))))\n\n(define (prime?/chowla n)\n (and (> n 1)\n (zero? (chowla n))))\n\n(define (perfect?/chowla n)\n (and (> n 1)\n (= n (add1 (chowla n)))))\n\n(define (make-chowla-sieve n)\n (let ((v (make-vector n 0)))\n (for* ((i (in-range 2 n)) (j (in-range (* 2 i) n i))) (vector-set! v j (+ i (vector-ref v j))))\n (for ((i (in-range 1 n))) (fxvector-set! chowla-cache (sub1 i) (vector-ref v i)))))\n\n(module+\n main\n (define (count-and-report-primes limit)\n (printf \"Primes < ~a: ~a~%\" limit (for/sum ((i (sequence-filter prime?/chowla (in-range 2 (add1 limit))))) 1)))\n\n (for ((i (in-range 1 (add1 37)))) (printf \"(chowla ~a) = ~a~%\" i (chowla i)))\n\n (make-chowla-sieve cache-size)\n\n (for-each count-and-report-primes '(1000 10000 100000 1000000 10000000))\n\n (let ((ns (for/list ((n (sequence-filter perfect?/chowla (in-range 2 35000000)))) n)))\n (printf \"There are ~a perfect numbers <= 35000000: ~a~%\" (length ns) ns)))\n", "language": "Racket" }, { "code": "sub comma { $^i.flip.comb(3).join(',').flip }\n\nsub schnitzel (\\Radda, \\radDA = 0) {\n Radda.is-prime ?? !Radda !! ?radDA ?? Radda\n !! sum flat (2 .. Radda.sqrt.floor).map: -> \\RAdda {\n my \\RADDA = Radda div RAdda;\n next if RADDA * RAdda !== Radda;\n RAdda !== RADDA ?? (RAdda, RADDA) !! RADDA\n }\n}\n\nmy \\chowder = cache (1..Inf).hyper(:8degree).grep( !*.&schnitzel: 'panini' );\n\nmy \\mung-daal = lazy gather for chowder -> \\panini {\n my \\gazpacho = 2**panini - 1;\n take gazpacho * 2**(panini - 1) unless schnitzel gazpacho, panini;\n}\n\nprintf \"chowla(%2d) = %2d\\n\", $_, .&schnitzel for 1..37;\n\nsay '';\n\nprintf \"Count of primes up to %10s: %s\\n\", comma(10**$_),\n comma chowder.first( * > 10**$_, :k) for 2..7;\n\nsay \"\\nPerfect numbers less than 35,000,000\";\n\n.&comma.say for mung-daal[^5];\n", "language": "Raku" }, { "code": "/*REXX program computes/displays chowla numbers (and may count primes & perfect numbers.*/\nparse arg LO HI . /*obtain optional arguments from the CL*/\nif LO=='' | LO==\",\" then LO= 1 /*Not specified? Then use the default.*/\nperf= LO<0; LO= abs(LO) /*Negative? Then determine if perfect.*/\nif HI=='' | HI==\",\" then HI= LO /*Not specified? Then use the default.*/\nprim= HI<0; HI= abs(HI) /*Negative? Then determine if a prime.*/\nnumeric digits max(9, length(HI) + 1 ) /*use enough decimal digits for // */\nw= length( commas(HI) ) /*W: used in aligning output numbers.*/\ntell= \\(prim | perf) /*set boolean value for showing chowlas*/\np= 0 /*the number of primes found (so far).*/\n do j=LO to HI; #= chowla(j) /*compute the cholwa number for J. */\n if tell then say right('chowla('commas(j)\")\", w+9) ' = ' right( commas(#), w)\n else if #==0 then if j>1 then p= p+1\n if perf then if j-1==# & j>1 then say right(commas(j), w) ' is a perfect number.'\n end /*j*/\n\nif prim & \\perf then say 'number of primes found for the range ' commas(LO) \" to \" ,\n commas(HI) \" (inclusive) is: \" commas(p)\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nchowla: procedure; parse arg x; if x<2 then return 0; odd= x // 2\n s=0 /* [↓] use EVEN or ODD integers. ___*/\n do k=2+odd by 1+odd while k*k<x /*divide by all the integers up to √ X */\n if x//k==0 then s=s + k + x%k /*add the two divisors to the sum. */\n end /*k*/ /* [↓] adkust for square. ___*/\n if k*k==x then s=s + k /*Was X a square? If so, add √ X */\n return s /*return \" \" \" \" \" */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncommas: parse arg _; do k=length(_)-3 to 1 by -3; _= insert(',', _, k); end; return _\n", "language": "REXX" }, { "code": "def chowla(n)\n sum = 0\n i = 2\n while i * i <= n do\n if n % i == 0 then\n sum = sum + i\n j = n / i\n if i != j then\n sum = sum + j\n end\n end\n i = i + 1\n end\n return sum\nend\n\ndef main\n for n in 1 .. 37 do\n puts \"chowla(%d) = %d\" % [n, chowla(n)]\n end\n\n count = 0\n power = 100\n for n in 2 .. 10000000 do\n if chowla(n) == 0 then\n count = count + 1\n end\n if n % power == 0 then\n puts \"There are %d primes < %d\" % [count, power]\n power = power * 10\n end\n end\n\n count = 0\n limit = 350000000\n k = 2\n kk = 3\n loop do\n p = k * kk\n if p > limit then\n break\n end\n if chowla(p) == p - 1 then\n puts \"%d is a perfect number\" % [p]\n count = count + 1\n end\n k = kk + 1\n kk = kk + k\n end\n puts \"There are %d perfect numbers < %d\" % [count, limit]\nend\n\nmain()\n", "language": "Ruby" }, { "code": "fn chowla(n: usize) -> usize {\n let mut sum = 0;\n let mut i = 2;\n while i * i <= n {\n if n % i == 0 {\n sum += i;\n let j = n / i;\n if i != j {\n sum += j;\n }\n }\n i += 1;\n }\n sum\n}\n\nfn sieve(limit: usize) -> Vec<bool> {\n let mut c = vec![false; limit];\n let mut i = 3;\n while i * i < limit {\n if !c[i] && chowla(i) == 0 {\n let mut j = 3 * i;\n while j < limit {\n c[j] = true;\n j += 2 * i;\n }\n }\n i += 2;\n }\n c\n}\n\nfn main() {\n for i in 1..=37 {\n println!(\"chowla({}) = {}\", i, chowla(i));\n }\n\n let mut count = 1;\n let limit = 1e7 as usize;\n let mut power = 100;\n let c = sieve(limit);\n for i in (3..limit).step_by(2) {\n if !c[i] {\n count += 1;\n }\n if i == power - 1 {\n println!(\"Count of primes up to {} = {}\", power, count);\n power *= 10;\n }\n }\n\n count = 0;\n let limit = 35000000;\n let mut k = 2;\n let mut kk = 3;\n loop {\n let p = k * kk;\n if p > limit {\n break;\n }\n if chowla(p) == p - 1 {\n println!(\"{} is a number that is perfect\", p);\n count += 1;\n }\n k = kk + 1;\n kk += k;\n }\n println!(\"There are {} perfect numbers <= 35,000,000\", count);\n}\n", "language": "Rust" }, { "code": "object ChowlaNumbers {\n def main(args: Array[String]): Unit = {\n println(\"Chowla Numbers...\")\n for(n <- 1 to 37){println(s\"$n: ${chowlaNum(n)}\")}\n println(\"\\nPrime Counts...\")\n for(i <- (2 to 7).map(math.pow(10, _).toInt)){println(f\"$i%,d: ${primesPar(i).size}%,d\")}\n println(\"\\nPerfect Numbers...\")\n print(perfectsPar(35000000).toVector.sorted.zipWithIndex.map{case (n, i) => f\"${i + 1}%,d: $n%,d\"}.mkString(\"\\n\"))\n }\n\n def primesPar(num: Int): ParVector[Int] = ParVector.range(2, num + 1).filter(n => chowlaNum(n) == 0)\n def perfectsPar(num: Int): ParVector[Int] = ParVector.range(6, num + 1).filter(n => chowlaNum(n) + 1 == n)\n\n def chowlaNum(num: Int): Int = Iterator.range(2, math.sqrt(num).toInt + 1).filter(n => num%n == 0).foldLeft(0){case (s, n) => if(n*n == num) s + n else s + n + (num/n)}\n}\n", "language": "Scala" }, { "code": "import Foundation\n\n@inlinable\npublic func chowla<T: BinaryInteger>(n: T) -> T {\n stride(from: 2, to: T(Double(n).squareRoot()+1), by: 1)\n .lazy\n .filter({ n % $0 == 0 })\n .reduce(0, {(s: T, m: T) in\n m*m == n ? s + m : s + m + (n / m)\n })\n}\n\nextension Dictionary where Key == ClosedRange<Int> {\n subscript(n: Int) -> Value {\n get {\n guard let key = keys.first(where: { $0.contains(n) }) else {\n fatalError(\"dict does not contain range for \\(n)\")\n }\n\n return self[key]!\n }\n\n set {\n guard let key = keys.first(where: { $0.contains(n) }) else {\n fatalError(\"dict does not contain range for \\(n)\")\n }\n\n self[key] = newValue\n }\n }\n}\n\nlet lock = DispatchSemaphore(value: 1)\n\nvar perfect = [Int]()\nvar primeCounts = [\n 1...100: 0,\n 101...1_000: 0,\n 1_001...10_000: 0,\n 10_001...100_000: 0,\n 100_001...1_000_000: 0,\n 1_000_001...10_000_000: 0\n]\n\nfor i in 1...37 {\n print(\"chowla(\\(i)) = \\(chowla(n: i))\")\n}\n\nDispatchQueue.concurrentPerform(iterations: 35_000_000) {i in\n let chowled = chowla(n: i)\n\n if chowled == 0 && i > 1 && i < 10_000_000 {\n lock.wait()\n primeCounts[i] += 1\n lock.signal()\n }\n\n if chowled == i - 1 && i > 1 {\n lock.wait()\n perfect.append(i)\n lock.signal()\n }\n}\n\nlet numPrimes = primeCounts\n .sorted(by: { $0.key.lowerBound < $1.key.lowerBound })\n .reduce(into: [(Int, Int)](), {counts, oneCount in\n guard !counts.isEmpty else {\n counts.append((oneCount.key.upperBound, oneCount.value))\n\n return\n }\n\n counts.append((oneCount.key.upperBound, counts.last!.1 + oneCount.value))\n })\n\nfor (upper, count) in numPrimes {\n print(\"Number of primes < \\(upper) = \\(count)\")\n}\n\nfor p in perfect {\n print(\"\\(p) is a perfect number\")\n}\n", "language": "Swift" }, { "code": "fn chowla(n int) int {\n if n < 1 {\n panic(\"argument must be a positive integer\")\n }\n mut sum := 0\n for i := 2; i*i <= n; i++ {\n if n%i == 0 {\n j := n / i\n if i == j {\n sum += i\n } else {\n sum += i + j\n }\n }\n }\n return sum\n}\n\nfn sieve(limit int) []bool {\n // True denotes composite, false denotes prime.\n // Only interested in odd numbers >= 3\n mut c := []bool{len: limit}\n for i := 3; i*3 < limit; i += 2 {\n if !c[i] && chowla(i) == 0 {\n for j := 3 * i; j < limit; j += 2 * i {\n c[j] = true\n }\n }\n }\n return c\n}\n\nfn main() {\n for i := 1; i <= 37; i++ {\n println(\"chowla(${i:2}) = ${chowla(i)}\")\n }\n println('')\n\n mut count := 1\n mut limit := int(1e7)\n c := sieve(limit)\n mut power := 100\n for i := 3; i < limit; i += 2 {\n if !c[i] {\n count++\n }\n if i == power-1 {\n println(\"Count of primes up to ${power:-10} = $count\")\n power *= 10\n }\n }\n\n println('')\n count = 0\n limit = 35000000\n for i := 2; ; i++ {\n p := (1 << (i -1)) * ((1<<i) - 1)\n if p > limit {\n break\n }\n if chowla(p) == p-1 {\n println(\"$p is a perfect number\")\n count++\n }\n }\n println(\"There are $count perfect numbers <= 35,000,000\")\n}\n", "language": "V-(Vlang)" }, { "code": "Option Explicit\n\nPrivate Declare Function AllocConsole Lib \"kernel32.dll\" () As Long\nPrivate Declare Function FreeConsole Lib \"kernel32.dll\" () As Long\nDim mStdOut As Scripting.TextStream\n\nFunction chowla(ByVal n As Long) As Long\nDim j As Long, i As Long\n i = 2\n Do While i * i <= n\n j = n \\ i\n If n Mod i = 0 Then\n chowla = chowla + i\n If i <> j Then\n chowla = chowla + j\n End If\n End If\n i = i + 1\n Loop\nEnd Function\n\nFunction sieve(ByVal limit As Long) As Boolean()\nDim c() As Boolean\nDim i As Long\nDim j As Long\n i = 3\n ReDim c(limit - 1)\n Do While i * 3 < limit\n If Not c(i) Then\n If (chowla(i) = 0) Then\n j = 3 * i\n Do While j < limit\n c(j) = True\n j = j + 2 * i\n Loop\n End If\n End If\n i = i + 2\n Loop\n sieve = c()\nEnd Function\n\nSub Display(ByVal s As String)\n Debug.Print s\n mStdOut.Write s & vbNewLine\nEnd Sub\n\nSub Main()\nDim i As Long\nDim count As Long\nDim limit As Long\nDim power As Long\nDim c() As Boolean\nDim p As Long\nDim k As Long\nDim kk As Long\nDim s As String * 30\nDim mFSO As Scripting.FileSystemObject\nDim mStdIn As Scripting.TextStream\n\n AllocConsole\n Set mFSO = New Scripting.FileSystemObject\n Set mStdIn = mFSO.GetStandardStream(StdIn)\n Set mStdOut = mFSO.GetStandardStream(StdOut)\n\n For i = 1 To 37\n Display \"chowla(\" & i & \")=\" & chowla(i)\n Next i\n\n count = 1\n limit = 10000000\n power = 100\n c = sieve(limit)\n\n For i = 3 To limit - 1 Step 2\n If Not c(i) Then\n count = count + 1\n End If\n If i = power - 1 Then\n RSet s = FormatNumber(power, 0, vbUseDefault, vbUseDefault, True)\n Display \"Count of primes up to \" & s & \" = \" & FormatNumber(count, 0, vbUseDefault, vbUseDefault, True)\n power = power * 10\n End If\n Next i\n\n count = 0: limit = 35000000\n k = 2: kk = 3\n\n Do\n p = k * kk\n If p > limit Then\n Exit Do\n End If\n\n If chowla(p) = p - 1 Then\n RSet s = FormatNumber(p, 0, vbUseDefault, vbUseDefault, True)\n Display s & \" is a number that is perfect\"\n count = count + 1\n End If\n k = kk + 1\n kk = kk + k\n Loop\n\n Display \"There are \" & CStr(count) & \" perfect numbers <= 35.000.000\"\n\n mStdOut.Write \"press enter to quit program.\"\n mStdIn.Read 1\n\n FreeConsole\n\nEnd Sub\n", "language": "Visual-Basic" }, { "code": "Imports System\n\nModule Program\n Function chowla(ByVal n As Integer) As Integer\n chowla = 0 : Dim j As Integer, i As Integer = 2\n While i * i <= n\n j = n / i : If n Mod i = 0 Then chowla += i + (If(i = j, 0, j))\n i += 1\n End While\n End Function\n\n Function sieve(ByVal limit As Integer) As Boolean()\n Dim c As Boolean() = New Boolean(limit - 1) {}, i As Integer = 3\n While i * 3 < limit\n If Not c(i) AndAlso (chowla(i) = 0) Then\n Dim j As Integer = 3 * i\n While j < limit : c(j) = True : j += 2 * i : End While\n End If : i += 2\n End While\n Return c\n End Function\n\n Sub Main(args As String())\n For i As Integer = 1 To 37\n Console.WriteLine(\"chowla({0}) = {1}\", i, chowla(i))\n Next\n Dim count As Integer = 1, limit As Integer = CInt((10000000.0)), power As Integer = 100,\n c As Boolean() = sieve(limit)\n For i As Integer = 3 To limit - 1 Step 2\n If Not c(i) Then count += 1\n If i = power - 1 Then\n Console.WriteLine(\"Count of primes up to {0,10:n0} = {1:n0}\", power, count)\n power = power * 10\n End If\n Next\n count = 0 : limit = 35000000\n Dim p As Integer, k As Integer = 2, kk As Integer = 3\n While True\n p = k * kk : If p > limit Then Exit While\n If chowla(p) = p - 1 Then\n Console.WriteLine(\"{0,10:n0} is a number that is perfect\", p)\n count += 1\n End If\n k = kk + 1 : kk += k\n End While\n Console.WriteLine(\"There are {0} perfect numbers <= 35,000,000\", count)\n If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()\n End Sub\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "Imports System.Numerics\n\nModule Program\n Function chowla(n As Integer) As Integer\n chowla = 0 : Dim j As Integer, i As Integer = 2\n While i * i <= n\n If n Mod i = 0 Then j = n / i : chowla += i : If i <> j Then chowla += j\n i += 1\n End While\n End Function\n\n Function chowla1(ByRef n As BigInteger, x As Integer) As BigInteger\n chowla1 = 1 : Dim j As BigInteger, lim As BigInteger = BigInteger.Pow(2, x - 1)\n For i As BigInteger = 2 To lim\n If n Mod i = 0 Then j = n / i : chowla1 += i : If i <> j Then chowla1 += j\n Next\n End Function\n\n Function sieve(ByVal limit As Integer) As Boolean()\n Dim c As Boolean() = New Boolean(limit - 1) {}, i As Integer = 3\n While i * 3 < limit\n If Not c(i) AndAlso (chowla(i) = 0) Then\n Dim j As Integer = 3 * i\n While j < limit : c(j) = True : j += 2 * i : End While\n End If : i += 2\n End While\n Return c\n End Function\n\n Sub Main(args As String())\n For i As Integer = 1 To 37\n Console.WriteLine(\"chowla({0}) = {1}\", i, chowla(i))\n Next\n Dim count As Integer = 1, limit As Integer = CInt((10000000.0)), power As Integer = 100,\n c As Boolean() = sieve(limit)\n For i As Integer = 3 To limit - 1 Step 2\n If Not c(i) Then count += 1\n If i = power - 1 Then\n Console.WriteLine(\"Count of primes up to {0,10:n0} = {1:n0}\", power, count)\n power = power * 10\n End If\n Next\n count = 0\n Dim p As BigInteger, k As BigInteger = 2, kk As BigInteger = 3\n For i As Integer = 2 To 31 ' if you dare, change the 31 to 61 or 89\n If {2, 3, 5, 7, 13, 17, 19, 31, 61, 89}.Contains(i) Then\n p = k * kk\n If chowla1(p, i) = p Then\n Console.WriteLine(\"{0,25:n0} is a number that is perfect\", p)\n st = DateTime.Now\n count += 1\n End If\n End If\n k = kk + 1 : kk += k\n Next\n Console.WriteLine(\"There are {0} perfect numbers <= {1:n0}\", count, 25 * BigInteger.Pow(10, 18))\n If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()\n End Sub\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./fmt\" for Fmt\nimport \"./math\" for Int, Nums\n\nvar chowla = Fn.new { |n| (n > 1) ? Nums.sum(Int.properDivisors(n)) - 1 : 0 }\n\nfor (i in 1..37) Fmt.print(\"chowla($2d) = $d\", i, chowla.call(i))\nSystem.print()\nvar count = 1\nvar limit = 1e7\nvar c = Int.primeSieve(limit, false)\nvar power = 100\nvar i = 3\nwhile (i < limit) {\n if (!c[i]) count = count + 1\n if (i == power - 1) {\n Fmt.print(\"Count of primes up to $,-10d = $,d\", power, count)\n power = power * 10\n }\n i = i + 2\n}\nSystem.print()\ncount = 0\nlimit = 35 * 1e6\ni = 2\nwhile (true) {\n var p = (1 << (i -1)) * ((1<<i) - 1) // perfect numbers must be of this form\n if (p > limit) break\n if (chowla.call(p) == p-1) {\n Fmt.print(\"$,d is a perfect number\", p)\n count = count + 1\n }\n i = i + 1\n}\nSystem.print(\"There are %(count) perfect numbers <= 35,000,000\")\n", "language": "Wren" }, { "code": "func Chowla(N); \\Return sum of divisors\nint N, Div, Sum, Quot;\n[Div:= 2; Sum:= 0;\nloop [Quot:= N/Div;\n if Quot < Div then quit;\n if Quot = Div and rem(0) = 0 then \\N is a square\n [Sum:= Sum+Quot; quit];\n if rem(0) = 0 then\n Sum:= Sum + Div + Quot;\n Div:= Div+1;\n ];\nreturn Sum;\n];\n\nint N, C, P;\n[for N:= 1 to 37 do\n [IntOut(0, N); Text(0, \": \");\n IntOut(0, Chowla(N)); CrLf(0);\n ];\nC:= 1; \\count 2 as prime\nN:= 3; \\only check odd numbers\nrepeat if Chowla(N) = 0 then \\N is prime\n C:= C+1;\n case N+1 of 100, 1000, 10_000, 100_000, 1_000_000, 10_000_000:\n [Text(0, \"There are \"); IntOut(0, C); Text(0, \" primes < \");\n IntOut(0, N+1); CrLf(0)]\n other [];\n N:= N+2;\nuntil N >= 10_000_000;\nP:= 1; \\perfect numbers are of form: 2^(P-1) * (2^P - 1)\nloop [P:= P*2;\n N:= P*(P*2-1);\n if N > 35_000_000 then quit;\n if Chowla(N) = N-1 then \\N is perfect\n [IntOut(0, N); CrLf(0)];\n ];\n]\n", "language": "XPL0" }, { "code": "fcn chowla(n){\n if(n<1)\n throw(Exception.ValueError(\"Chowla function argument must be positive\"));\n sum:=0;\n foreach i in ([2..n.toFloat().sqrt()]){\n if(n%i == 0){\n\t j:=n/i;\n\t if(i==j) sum+=i;\n\t else sum+=i+j;\n }\n }\n sum\n}\n\nfcn chowlaSieve(limit){\n // True denotes composite, false denotes prime.\n // Only interested in odd numbers >= 3\n c:=Data(limit+100).fill(0); # slop at the end (for reverse wrap around)\n foreach i in ([3..limit/3,2]){\n if(not c[i] and chowla(i)==0)\n { foreach j in ([3*i..limit,2*i]){ c[j]=True } }\n }\n c\n}\n", "language": "Zkl" }, { "code": "fcn testChowla{\n println(\"The first 37 Chowla numbers:\\n\",\n [1..37].apply(chowla).concat(\" \",\"[\",\"]\"), \"\\n\");\n\n count,limit,power := 1, (1e7).toInt(), 100;\n c:=chowlaSieve(limit);\n foreach i in ([3..limit-1,2]){\n if(not c[i]) count+=1;\n if(i == power - 1){\n\t println(\"The count of the primes up to %10,d is %8,d\".fmt(power,count));\n\t power*=10;\n }\n }\n\n println();\n count, limit = 0, 35_000_000;\n foreach i in ([2..]){\n p:=(1).shiftLeft(i - 1) * ((1).shiftLeft(i)-1); // perfect numbers must be of this form\n if(p>limit) break;\n if(p-1 == chowla(p)){\n println(\"%,d is a perfect number\".fmt(p));\n\t count+=1;\n }\n }\n println(\"There are %,d perfect numbers <= %,d\".fmt(count,limit));\n}();\n", "language": "Zkl" } ]
Chowla-numbers
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Church_numerals\n", "language": "00-META" }, { "code": ";Task:\nIn [[wp:Church_encoding#Church_numerals|the Church encoding of natural numbers]], the number N is encoded by a function that applies its first argument N times to its second argument.\n\n* '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.\n* '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)'''\n* '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))'''\n* and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.\n\n\nArithmetic operations on natural numbers can be similarly [[wp:Church_encoding#Calculation_with_Church_numerals|represented as functions on Church numerals]].\n\nIn your language define:\n\n* Church Zero,\n* a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),\n* functions for Addition, Multiplication and Exponentiation over Church numerals,\n* a function to convert integers to corresponding Church numerals,\n* and a function to convert Church numerals to corresponding integers.\n\n\nYou should:\n\n* Derive Church numerals three and four in terms of Church zero and a Church successor function.\n* use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,\n* similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,\n* convert each result back to an integer, and return it or print it to the console.\n\n<br>\n", "language": "00-TASK" }, { "code": "(setq zero '(lambda (f x) x))\n\n(defun succ (n)\n (freeze '(n) '(lambda (f x) (f (n f x)))))\n\n(defun add (m n)\n (freeze '(m n) '(lambda (f x) (m f (n f x)))))\n\n(defun mul (m n)\n (n (freeze '(m) '(lambda (sum) (add m sum))) zero))\n\n(defun pow (m n)\n (n (freeze '(m) '(lambda (product) (mul m product))) one))\n\n(defun church (i)\n (cond ((zerop i) zero)\n (t (succ (church (sub1 i))))))\n\n(defun unchurch (n)\n (n add1 0))\n\n(setq one (succ zero))\n(setq two (succ one))\n(setq three (succ two))\n(setq four (succ three))\n\n(defun show (example)\n (prin example)\n (princ '! =>! )\n (print (unchurch (eval example))))\n\n(defun examples ()\n (show '(church 3))\n (show '(add three four))\n (show '(mul three four))\n (show '(pow three four))\n (show '(pow four three))\n (show '(pow (pow two two) (add two one))))\n", "language": "Acornsoft-Lisp" }, { "code": "--------------------- CHURCH NUMERALS --------------------\n\n-- churchZero :: (a -> a) -> a -> a\non churchZero(f, x)\n x\nend churchZero\n\n\n-- churchSucc :: ((a -> a) -> a -> a) -> (a -> a) -> a -> a\non churchSucc(n)\n script\n on |λ|(f)\n script\n property mf : mReturn(f)\n on |λ|(x)\n mf's |λ|(mReturn(n)'s |λ|(mf)'s |λ|(x))\n end |λ|\n end script\n end |λ|\n end script\nend churchSucc\n\n\n-- churchFromInt(n) :: Int -> (b -> b) -> b -> b\non churchFromInt(n)\n script\n on |λ|(f)\n foldr(my compose, my |id|, replicate(n, f))\n end |λ|\n end script\nend churchFromInt\n\n\n-- intFromChurch :: ((Int -> Int) -> Int -> Int) -> Int\non intFromChurch(cn)\n mReturn(cn)'s |λ|(my succ)'s |λ|(0)\nend intFromChurch\n\n\non churchAdd(m, n)\n script\n on |λ|(f)\n script\n property mf : mReturn(m)\n property nf : mReturn(n)\n on |λ|(x)\n nf's |λ|(f)'s |λ|(mf's |λ|(f)'s |λ|(x))\n end |λ|\n end script\n end |λ|\n end script\nend churchAdd\n\n\non churchMult(m, n)\n script\n on |λ|(f)\n script\n property mf : mReturn(m)\n property nf : mReturn(n)\n on |λ|(x)\n mf's |λ|(nf's |λ|(f))'s |λ|(x)\n end |λ|\n end script\n end |λ|\n end script\nend churchMult\n\n\non churchExp(m, n)\n n's |λ|(m)\nend churchExp\n\n\n--------------------------- TEST -------------------------\non run\n set cThree to churchFromInt(3)\n set cFour to churchFromInt(4)\n\n map(intFromChurch, ¬\n {churchAdd(cThree, cFour), churchMult(cThree, cFour), ¬\n churchExp(cFour, cThree), churchExp(cThree, cFour)})\nend run\n\n\n------------------------- GENERIC ------------------------\n\n-- compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\non compose(f, g)\n script\n property mf : mReturn(f)\n property mg : mReturn(g)\n on |λ|(x)\n mf's |λ|(mg's |λ|(x))\n end |λ|\n end script\nend compose\n\n\n-- id :: a -> a\non |id|(x)\n x\nend |id|\n\n\n-- foldr :: (a -> b -> b) -> b -> [a] -> b\non foldr(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from lng to 1 by -1\n set v to |λ|(item i of xs, v, i, xs)\n end repeat\n return v\n end tell\nend foldr\n\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: First-class m => (a -> b) -> m (a -> b)\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n\n-- Egyptian multiplication - progressively doubling a list, appending\n-- stages of doubling to an accumulator where needed for binary\n-- assembly of a target length\n-- replicate :: Int -> a -> [a]\non replicate(n, a)\n set out to {}\n if n < 1 then return out\n set dbl to {a}\n\n repeat while (n > 1)\n if (n mod 2) > 0 then set out to out & dbl\n set n to (n div 2)\n set dbl to (dbl & dbl)\n end repeat\n return out & dbl\nend replicate\n\n\n-- succ :: Int -> Int\non succ(x)\n 1 + x\nend succ\n", "language": "AppleScript" }, { "code": "#include <iostream>\n\n// apply the function zero times (return an identity function)\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n// define Church True and False\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n// apply the function f one more time\nauto Successor(auto a) {\n return [=](auto f) {\n return [=](auto x) {\n return a(f)(f(x));\n };\n };\n}\n\n// apply the function a times after b times\nauto Add(auto a, auto b) {\n return [=](auto f) {\n return [=](auto x) {\n return a(f)(b(f)(x));\n };\n };\n}\n\n// apply the function a times b times\nauto Multiply(auto a, auto b) {\n return [=](auto f) {\n return a(b(f));\n };\n}\n\n// apply the function a^b times\nauto Exp(auto a, auto b) {\n return b(a);\n}\n\n// check if a number is zero\nauto IsZero(auto a){\n return a([](auto){ return False; })(True);\n}\n\n// apply the function f one less time\nauto Predecessor(auto a) {\n return [=](auto f) {\n return [=](auto x) {\n return a(\n [=](auto g) {\n return [=](auto h){\n return h(g(f));\n };\n }\n )([=](auto){ return x; })([](auto y){ return y; });\n };\n };\n}\n\n// apply the Predecessor function b times to a\nauto Subtract(auto a, auto b) {\n {\n return b([](auto c){ return Predecessor(c); })(a);\n };\n}\n\nnamespace\n{\n // helper functions for division.\n\n // end the recusrion\n auto Divr(decltype(Zero), auto) {\n return Zero;\n }\n\n // count how many times b can be subtracted from a\n auto Divr(auto a, auto b) {\n auto a_minus_b = Subtract(a, b);\n auto isZero = IsZero(a_minus_b);\n\n // normalize all Church zeros to be the same (intensional equality).\n // In this implemetation, Church numerals have extensional equality\n // but not intensional equality. '6 - 3' and '4 - 1' have extensional\n // equality because they will both cause a function to be called\n // three times but due to the static type system they do not have\n // intensional equality. Internally the two numerals are represented\n // by different lambdas. Normalize all Church zeros (1 - 1, 2 - 2, etc.)\n // to the same zero (Zero) so it will match the function that end the\n // recursion.\n return isZero\n (Zero)\n (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n }\n}\n\n// apply the function a / b times\nauto Divide(auto a, auto b) {\n return Divr(Successor(a), b);\n}\n\n// create a Church numeral from an integer at compile time\ntemplate <int N> constexpr auto ToChurch() {\n if constexpr(N<=0) return Zero;\n else return Successor(ToChurch<N-1>());\n}\n\n// use an increment function to convert the Church number to an integer\nint ToInt(auto church) {\n return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n // show some examples\n auto three = Successor(Successor(Successor(Zero)));\n auto four = Successor(three);\n auto six = ToChurch<6>();\n auto ten = ToChurch<10>();\n auto thousand = Exp(ten, three);\n\n std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n auto looloolool = Successor(looloolooo);\n std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n // calculate the golden ratio by using a Church numeral to\n // apply the funtion 'f(x) = 1 + 1/x' a thousand times\n std::cout << \"\\n golden ratio = \" <<\n thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n", "language": "C++" }, { "code": "using System;\n\npublic delegate Church Church(Church f);\n\npublic static class ChurchNumeral\n{\n public static readonly Church ChurchZero = _ => x => x;\n public static readonly Church ChurchOne = f => f;\n\n public static Church Successor(this Church n) => f => x => f(n(f)(x));\n public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n public static Church Multiply(this Church m, Church n) => f => m(n(f));\n public static Church Exponent(this Church m, Church n) => n(m);\n public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n public static Church Predecessor(this Church n) =>\n f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n static Church looper(this Church v, Church d) =>\n v(_ => v.divr(d).Successor())(ChurchZero);\n static Church divr(this Church n, Church d) =>\n n.Subtract(d).looper(d);\n public static Church Divide(this Church dvdnd, Church dvsr) =>\n (dvdnd.Successor()).divr(dvsr);\n\n public static Church FromInt(int i) =>\n i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n\n public static int ToInt(this Church ch) {\n int count = 0;\n ch(x => { count++; return x; })(null);\n return count;\n }\n\n public static void Main() {\n Church c3 = FromInt(3);\n Church c4 = c3.Successor();\n Church c11 = FromInt(11);\n Church c12 = c11.Successor();\n int sum = c3.Add(c4).ToInt();\n int product = c3.Multiply(c4).ToInt();\n int exp43 = c4.Exponent(c3).ToInt();\n int exp34 = c3.Exponent(c4).ToInt();\n int tst0 = ChurchZero.IsZero().ToInt();\n int pred4 = c4.Predecessor().ToInt();\n int sub43 = c4.Subtract(c3).ToInt();\n int div11by3 = c11.Divide(c3).ToInt();\n int div12by3 = c12.Divide(c3).ToInt();\n Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n }\n}\n", "language": "C-sharp" }, { "code": "class Church { // identity Church function by default\n proc this(f: shared Church): shared Church { return f; }\n}\n\n// utility Church functions...\nclass ComposeChurch : Church {\n const l, r: shared Church;\n override proc this(f: shared Church): shared Church {\n return l(r(f)); }\n}\n\nproc composeChurch(chl: shared Church, chr: shared Church) : shared Church {\n return new shared ComposeChurch(chl, chr): shared Church;\n}\n\nclass ConstChurch : Church {\n const ch: shared Church;\n override proc this(f: shared Church): shared Church { return ch; }\n}\n\nproc constChurch(ch: shared Church): shared Church {\n return new shared ConstChurch(ch): shared Church;\n}\n\n// Church constants...\nconst cIdentityChurch: shared Church = new shared Church();\nconst cChurchZero = constChurch(cIdentityChurch);\nconst cChurchOne = cIdentityChurch; // default is identity!\n\n// Church functions...\nclass SuccChurch: Church {\n const curr: shared Church;\n override proc this(f: shared Church): shared Church {\n return composeChurch(f, curr(f)); }\n}\n\nproc succChurch(ch: shared Church): shared Church {\n return new shared SuccChurch(ch) : shared Church;\n}\n\nclass AddChurch: Church {\n const chf, chs: shared Church;\n override proc this(f: shared Church): shared Church {\n return composeChurch(chf(f), chs(f)); }\n}\n\nproc addChurch(cha: shared Church, chb: shared Church): shared Church {\n return new shared AddChurch(cha, chb) : shared Church;\n}\n\nclass MultChurch: Church {\n const chf, chs: shared Church;\n override proc this(f: shared Church): shared Church {\n return composeChurch(chf, chs)(f); }\n}\n\nproc multChurch(cha: shared Church, chb: shared Church): shared Church {\n return new shared MultChurch(cha, chb) : shared Church;\n}\n\nclass ExpChurch : Church {\n const b, e : shared Church;\n override proc this(f : shared Church): shared Church { return e(b)(f); }\n}\n\nproc expChurch(chbs: shared Church, chexp: shared Church): shared Church {\n return new shared ExpChurch(chbs, chexp) : shared Church;\n}\n\nclass IsZeroChurch : Church {\n const c : shared Church;\n override proc this(f : shared Church): shared Church {\n return c(constChurch(cChurchZero))(cChurchOne)(f); }\n}\n\nproc isZeroChurch(ch: shared Church): shared Church {\n return new shared IsZeroChurch(ch) : shared Church;\n}\n\nclass PredChurch : Church {\n const c : shared Church;\n class XFunc : Church {\n const cf, fnc: shared Church;\n class GFunc : Church {\n const fnc: shared Church;\n class HFunc : Church {\n const fnc, g: shared Church;\n override proc this(f : shared Church): shared Church {\n return f(g(fnc)); }\n }\n override proc this(f : shared Church): shared Church {\n return new shared HFunc(fnc, f): shared Church; }\n }\n override proc this(f : shared Church): shared Church {\n const prd = new shared GFunc(fnc): shared Church;\n return cf(prd)(constChurch(f))(cIdentityChurch); }\n }\n override proc this(f : shared Church): shared Church {\n return new shared XFunc(c, f) : shared Church; }\n}\n\nproc predChurch(ch: shared Church): shared Church {\n return new shared PredChurch(ch) : shared Church;\n}\n\nclass SubChurch : Church {\n const a, b : shared Church;\n class PredFunc : Church {\n override proc this(f : shared Church): shared Church {\n return new shared PredChurch(f): shared Church;\n }\n }\n override proc this(f : shared Church): shared Church {\n const prdf = new shared PredFunc(): shared Church;\n return b(prdf)(a)(f); }\n}\n\nproc subChurch(cha: shared Church, chb: shared Church): shared Church {\n return new shared SubChurch(cha, chb) : shared Church;\n}\n\nclass DivrChurch : Church {\n const v, d : shared Church;\n override proc this(f : shared Church): shared Church {\n const loopr = constChurch(succChurch(divr(v, d)));\n return v(loopr)(cChurchZero)(f); }\n}\n\nproc divr(n: shared Church, d : shared Church): shared Church {\n return new shared DivrChurch(subChurch(n, d), d): shared Church;\n}\n\nproc divChurch(chdvdnd: shared Church, chdvsr: shared Church): shared Church {\n return divr(succChurch(chdvdnd), chdvsr);\n}\n\n// conversion functions...\nproc loopChurch(i: int, ch: shared Church) : shared Church { // tail call...\n return if (i <= 0) then ch else loopChurch(i - 1, succChurch(ch));\n}\n\nproc churchFromInt(n: int): shared Church {\n return loopChurch(n, cChurchZero); // can't embed \"worker\" proc!\n}\n\nclass IntChurch : Church {\n const value: int;\n}\n\nclass IncChurch : Church {\n override proc this(f: shared Church): shared Church {\n const tst = f: IntChurch;\n if tst != nil {\n return new shared IntChurch(tst.value + 1): shared Church; }\n else return f; } // shouldn't happen!\n}\n\nproc intFromChurch(ch: shared Church): int {\n const zero = new shared IntChurch(0): shared Church;\n const tst = ch(new shared IncChurch(): shared Church)(zero): IntChurch;\n if tst != nil { return tst.value; }\n else return -1; // should never happen!\n}\n\n// testing...\nconst ch3 = churchFromInt(3); const ch4 = succChurch(ch3);\nconst ch11 = churchFromInt(11); const ch12 = succChurch(ch11);\nwrite(intFromChurch(addChurch(ch3, ch4)), \", \");\nwrite(intFromChurch(multChurch(ch3, ch4)), \", \");\nwrite(intFromChurch(expChurch(ch3, ch4)), \", \");\nwrite(intFromChurch(expChurch(ch4, ch3)), \", \");\nwrite(intFromChurch(isZeroChurch(cChurchZero)), \", \");\nwrite(intFromChurch(isZeroChurch(ch3)), \", \");\nwrite(intFromChurch(predChurch(ch4)), \", \");\nwrite(intFromChurch(predChurch(cChurchZero)), \", \");\nwrite(intFromChurch(subChurch(ch11, ch3)), \", \");\nwrite(intFromChurch(divChurch(ch11, ch3)), \", \");\nwriteln(intFromChurch(divChurch(ch12, ch3)));\n", "language": "Chapel" }, { "code": "(defn zero [f] identity)\n(defn succ [n] (fn [f] (fn [x] (f ((n f) x)))))\n(defn add [n,m] (fn [f] (fn [x] ((m f)((n f) x)))))\n(defn mult [n,m] (fn [f] (fn [x] ((m (n f)) x))))\n(defn power [b,e] (e b))\n\n(defn to-int [c] ((c inc) 0))\n\n(defn from-int [n]\n (letfn [(countdown [i] (if (zero? i) zero (succ (countdown (- i 1)))))]\n (countdown n)))\n\n(def three (succ (succ (succ zero))))\n(def four (from-int 4))\n\n(doseq [n [(add three four) (mult three four)\n (power three four) (power four three)]]\n (println (to-int n)))\n", "language": "Clojure" }, { "code": "(defvar zero (lambda (f x) x))\n\n(defun succ (n) (lambda (f x) (funcall f (funcall n f x))))\n\n(defun plus (m n)\n (lambda (f x) (funcall m f (funcall n f x))))\n\n(defun times (m n)\n (funcall n (lambda (sum) (plus m sum)) zero))\n\n(defun power (m n)\n (funcall n (lambda (product) (times m product)) one))\n\n(defun church (i) ; int -> Church\n (if (zerop i) zero (succ (church (1- i)))))\n\n(defun unchurch (n) ; Church -> int\n (funcall n #'1+ 0))\n\n(defun show (example)\n (format t \"~(~S => ~S~)~%\"\n example (unchurch (eval example))))\n\n(defvar one (succ zero))\n(defvar two (succ one))\n(defvar three (succ two))\n(defvar four (succ three))\n\n(show '(church 3))\n(show '(plus three four))\n(show '(times three four))\n(show '(power three four))\n(show '(power four three))\n(show '(power (power two two) (plus two one)))\n", "language": "Common-Lisp" }, { "code": "(defvar zero (lambda (f) (lambda (x) x)))\n\n(defun succ (n) (lambda (f) (compose f (funcall n f))))\n\n(defun plus (m n)\n (lambda (f) (compose (funcall m f) (funcall n f))))\n\n(defun times (m n)\n (compose m n))\n\n(defun power (m n)\n (funcall n m))\n\n(defun compose (f g)\n (lambda (x) (funcall f (funcall g x))))\n\n(defun church (i) ; int -> Church\n (if (zerop i) zero (succ (church (1- i)))))\n\n(defun unchurch (n) ; Church -> int\n (funcall (funcall n #'1+) 0))\n", "language": "Common-Lisp" }, { "code": "(defun pred (n)\n (flet ((value (v) (lambda (h) (funcall h v)))\n (extract (k) (funcall k (lambda (u) u))))\n (lambda (f x)\n (let ((inc (lambda (g) (value (funcall g f))))\n (const (lambda (u) x)))\n (extract (funcall n inc const))))))\n\n(defun minus (m n)\n (funcall n #'pred m))\n", "language": "Common-Lisp" }, { "code": "(defmacro church-if (test then else)\n `(funcall ,test (lambda () ,then) (lambda () ,else)))\n\n(defvar true (lambda (f g) (funcall f)))\n(defvar false (lambda (f g) (funcall g)))\n", "language": "Common-Lisp" }, { "code": "(defun is-zero (n)\n (funcall n (lambda (x) false) true))\n\n(defun divide (m n)\n (divide1 (succ m) n))\n\n(defun divide1 (m n)\n (let ((d (minus m n)))\n (church-if (is-zero d)\n zero\n (succ (divide1 d n)))))\n", "language": "Common-Lisp" }, { "code": "(show '(pred four))\n(show '(minus (church 11) three))\n(show '(divide (church 11) three))\n(show '(divide (church 12) three))\n", "language": "Common-Lisp" }, { "code": "(defun pred (n)\n (flet ((value (v) (lambda (h) (funcall h v)))\n (extract (k) (funcall k (lambda (u) u))))\n (lambda (f)\n (lambda (x)\n (let ((inc (lambda (g) (value (funcall g f))))\n (const (lambda (u) x)))\n (extract (funcall (funcall n inc) const)))))))\n\n(defun minus (m n)\n (funcall (funcall n #'pred) m))\n\n...\n\n(defun is-zero (n)\n (funcall (funcall n (lambda (x) false)) true))\n\n...\n", "language": "Common-Lisp" }, { "code": "struct Church # can't be generic!\n getter church : (Church -> Church) | Int32\n def initialize(@church) end\n def apply(ch)\n chf = @church\n chf.responds_to?(:call) ? chf.call(ch) : self\n end\n def compose(chr)\n chlf = @church\n chrf = chr.church\n if chlf.responds_to?(:call) && chrf.responds_to?(:call)\n Church.new(-> (f : Church) { chlf.call(chrf.call(f)) })\n else\n self\n end\n end\nend\n\n# Church Numeral constants...\nCHURCH_ZERO = begin\n Church.new(-> (f : Church) {\n Church.new(-> (x : Church) { x }) })\nend\n\nCHURCH_ONE = begin\n Church.new(-> (f : Church) { f })\nend\n\n# Church Numeral functions...\ndef succChurch\n -> (ch : Church) {\n Church.new(-> (f : Church) { f.compose(ch.apply(f)) }) }\nend\n\ndef addChurch\n -> (cha : Church, chb : Church) {\n Church.new(-> (f : Church) { cha.apply(f).compose(chb.apply(f)) }) }\nend\n\ndef multChurch\n -> (cha : Church, chb : Church) { cha.compose(chb) }\nend\n\ndef expChurch\n -> (chbs : Church, chexp : Church) { chexp.apply(chbs) }\nend\n\ndef isZeroChurch\n liftZero = Church.new(-> (f : Church) { CHURCH_ZERO })\n -> (ch : Church) { ch.apply(liftZero).apply(CHURCH_ONE) }\nend\n\ndef predChurch\n -> (ch : Church) {\n Church.new(-> (f : Church) { Church.new(-> (x : Church) {\n prd = Church.new(-> (g : Church) { Church.new(-> (h : Church) {\n h.apply(g.apply(f)) }) })\n frst = Church.new(-> (d : Church) { x })\n id = Church.new(-> (a : Church) { a })\n ch.apply(prd).apply(frst).apply(id)\n }) }) }\nend\n\ndef subChurch\n -> (cha : Church, chb : Church) {\n chb.apply(Church.new(predChurch)).apply(cha) }\nend\n\ndef divr # can't be nested in another def...\n -> (n : Church, d: Church) {\n tstr = -> (v : Church) {\n loopr = Church.new(-> (a : Church) {\n succChurch.call(divr.call(v, d)) }) # recurse until zero\n v.apply(loopr).apply(CHURCH_ZERO) }\n tstr.call(subChurch.call(n, d)) }\nend\n\ndef divChurch\n -> (chdvdnd : Church, chdvsr : Church) {\n divr.call(succChurch.call(chdvdnd), chdvsr) }\nend\n\n# conversion functions...\ndef intToChurch(i) : Church\n rslt = CHURCH_ZERO\n cntr = 0\n while cntr < i\n rslt = succChurch.call(rslt)\n cntr += 1\n end\n rslt\nend\n\ndef churchToInt(ch) : Int32\n succInt32 = Church.new(-> (v : Church) {\n vi = v.church\n vi.is_a?(Int32) ? Church.new(vi + 1) : v })\n rslt = ch.apply(succInt32).apply(Church.new(0)).church\n rslt.is_a?(Int32) ? rslt : -1\nend\n\n# testing...\nch3 = intToChurch(3)\nch4 = succChurch.call(ch3)\nch11 = intToChurch(11)\nch12 = succChurch.call(ch11)\nadd = churchToInt(addChurch.call(ch3, ch4))\nmult = churchToInt(multChurch.call(ch3, ch4))\nexp1 = churchToInt(expChurch.call(ch3, ch4))\nexp2 = churchToInt(expChurch.call(ch4, ch3))\niszero1 = churchToInt(isZeroChurch.call(CHURCH_ZERO))\niszero2 = churchToInt(isZeroChurch.call(ch3))\npred1 = churchToInt(predChurch.call(ch4))\npred2 = churchToInt(predChurch.call(CHURCH_ZERO))\nsub = churchToInt(subChurch.call(ch11, ch3))\ndiv1 = churchToInt(divChurch.call(ch11, ch3))\ndiv2 = churchToInt(divChurch.call(ch12, ch3))\nprint(\"#{add} #{mult} #{exp1} #{exp2} #{iszero1} #{iszero2} \")\nprint(\"#{pred1} #{pred2} #{sub} #{div1} #{div2}\\r\\n\")\n", "language": "Crystal" }, { "code": "module Main exposing ( main )\n\nimport Html exposing ( Html, text )\n\ntype alias Church a = (a -> a) -> a -> a\n\nchurchZero : Church a -- a Church constant\nchurchZero = always identity\n\nsuccChurch : Church a -> Church a\nsuccChurch ch = \\ f -> f << ch f -- add one recursion\n\naddChurch : Church a -> Church a -> Church a\naddChurch chaf chbf = \\ f -> chaf f << chbf f\n\nmultChurch : Church a -> Church a -> Church a\nmultChurch = (<<)\n\nexpChurch : Church a -> (Church a -> Church a) -> Church a\nexpChurch = (\\ f x y -> f y x) identity -- `flip` inlined\n\nchurchFromInt : Int -> Church a\nchurchFromInt n = if n <= 0 then churchZero\n else succChurch <| churchFromInt (n - 1)\n\nintFromChurch : Church Int -> Int\nintFromChurch cn = cn ((+) 1) 0 -- `succ` inlined\n\n--------------------------- TEST -------------------------\nmain : Html Never\nmain =\n let cThree = churchFromInt 3\n cFour = succChurch cThree\n in [ addChurch cThree cFour\n , multChurch cThree cFour\n , expChurch cThree cFour\n , expChurch cFour cThree\n ] |> List.map intFromChurch\n |> Debug.toString |> text\n", "language": "Elm" }, { "code": "module Main exposing (main)\n\nimport Html exposing (text)\n\n-- the Church wrapper and functions...\ntype Church a = Church (Church a -> Church a)\n | ArityZero a -- treat a value as a function\napplyChurch : Church a -> Church a -> Church a\napplyChurch ch charg = case ch of Church chf -> chf charg\n ArityZero _ -> charg -- never happens!\ncomposeChurch : Church a -> Church a -> Church a\ncomposeChurch chl chr =\n case chl of Church chlf ->\n case chr of Church chrf -> Church <| \\ f -> (chlf << chrf) f\n otherwise -> chr -- never happens!\n otherwise -> chr -- never happens!\n\n-- the Church Numeral functions...\nchurchZero : Church a\nchurchZero = Church <| always <| Church identity\nchurchOne : Church a\nchurchOne = Church identity\nsuccChurch : Church a -> Church a\nsuccChurch ch = Church <| \\ f -> composeChurch f <| applyChurch ch f\naddChurch : Church a -> Church a -> Church a\naddChurch cha chb =\n Church <| \\ f -> composeChurch (applyChurch cha f) (applyChurch chb f)\nmultChurch : Church a -> Church a -> Church a\nmultChurch cha chb = composeChurch cha chb\nexpChurch : Church a -> Church a -> Church a\nexpChurch chbs chexp = applyChurch chexp chbs\nisZeroChurch : Church a -> Church a\nisZeroChurch ch =\n applyChurch (applyChurch ch (Church <| \\ _ -> churchZero)) churchOne\npredChurch : Church a -> Church a\npredChurch ch =\n Church <| \\ f -> Church <| \\ x ->\n let prdf = Church <| \\ g -> Church <| \\ h ->\n applyChurch h (applyChurch g f)\n in applyChurch (applyChurch (applyChurch ch prdf)\n (Church <| \\ _ -> x)) <| Church identity\nsubChurch : Church a -> Church a -> Church a\nsubChurch cha chb = applyChurch (applyChurch chb <| Church predChurch) cha\n\ndivChurch : Church a -> Church a -> Church a\ndivChurch chdvdnd chdvsr =\n let divr n =\n let loop v = Church <| \\ _ -> succChurch <| divr v\n tst v = applyChurch (applyChurch v <| loop v) churchZero\n in tst <| subChurch n chdvsr\n in divr <| succChurch chdvdnd\n\n-- conversion functions...\nintToChurch : Int -> Church a\nintToChurch i = List.foldl (\\ _ ch -> succChurch ch) churchZero (List.range 1 i)\nchurchToInt : Church Int -> Int\nchurchToInt ch =\n let succInt = Church <| \\ ach -> case ach of ArityZero v -> ArityZero (v + 1)\n otherwise -> ach -- never happens!\n in case applyChurch (applyChurch ch succInt) <| ArityZero 0 of\n ArityZero r -> r\n otherwise -> -1 -- never happens!\n\n--------------------------------------TEST--------------------------------------\nmain : Html.Html Never\nmain =\n let chThree = intToChurch 3\n chFour = succChurch chThree\n chEleven = intToChurch 11\n chTwelve = succChurch chEleven\n in [ addChurch chThree chFour\n , multChurch chThree chFour\n , expChurch chThree chFour\n , expChurch chFour chThree\n , isZeroChurch churchZero\n , isZeroChurch chThree\n , predChurch chFour\n , subChurch chEleven chThree\n , divChurch chEleven chThree\n , divChurch chTwelve chThree\n ] |> List.map (String.fromInt << churchToInt)\n |> String.join \", \" |> text\n", "language": "Elm" }, { "code": "-module(church).\n-export([main/1, zero/1]).\nzero(_) -> fun(F) -> F end.\nsucc(N) -> fun(F) -> fun(X) -> F((N(F))(X)) end end.\nadd(N,M) -> fun(F) -> fun(X) -> (M(F))((N(F))(X)) end end.\nmult(N,M) -> fun(F) -> fun(X) -> (M(N(F)))(X) end end.\npower(B,E) -> E(B).\n\nto_int(C) -> CountUp = fun(I) -> I + 1 end, (C(CountUp))(0).\n\nfrom_int(0) -> fun church:zero/1;\nfrom_int(I) -> succ(from_int(I-1)).\n\nmain(_) ->\n Zero = fun church:zero/1,\n Three = succ(succ(succ(Zero))),\n Four = from_int(4),\n lists:map(fun(C) -> io:fwrite(\"~w~n\",[to_int(C)]) end,\n\t [add(Three,Four), mult(Three,Four),\n\t power(Three,Four), power(Four,Three)]).\n", "language": "Erlang" }, { "code": "type IChurch =\n abstract Apply : ('a -> 'a) -> ('a -> 'a)\n\nlet zeroChurch = { new IChurch with override __.Apply _ = id }\nlet oneChurch = { new IChurch with override __.Apply f = f }\nlet succChurch (n: IChurch) =\n { new IChurch with override __.Apply f = fun x -> f (n.Apply f x) }\nlet addChurch (m: IChurch) (n: IChurch) =\n { new IChurch with override __.Apply f = fun x -> m.Apply f (n.Apply f x) }\nlet multChurch (m: IChurch) (n: IChurch) =\n { new IChurch with override __.Apply f = m.Apply (n.Apply f) }\nlet expChurch (m: IChurch) (n: IChurch) =\n { new IChurch with override __.Apply f = n.Apply m.Apply f }\nlet iszeroChurch (n: IChurch) =\n { new IChurch with\n override __.Apply f = n.Apply (fun _ -> zeroChurch.Apply) oneChurch.Apply f }\nlet predChurch (n: IChurch) =\n { new IChurch with\n override __.Apply f = fun x -> n.Apply (fun g h -> h (g f))\n (fun _ -> x) id }\nlet subChurch (m: IChurch) (n: IChurch) =\n { new IChurch with override __.Apply f = (n.Apply predChurch m).Apply f }\nlet divChurch (dvdnd: IChurch) (dvsr: IChurch) =\n let rec divr (n: IChurch) (d: IChurch) =\n { new IChurch with\n override __.Apply f =\n ((fun (v: IChurch) -> // test v for Church zeroChurch...\n v.Apply (fun _ -> (succChurch (divr v d)).Apply) // if not zeroChurch\n zeroChurch.Apply)(subChurch n d)) f }\n divr (succChurch dvdnd) dvsr\n\nlet chtoi (ch: IChurch) = ch.Apply ((+) 1) 0\nlet itoch i = List.fold (>>) id (List.replicate i succChurch) zeroChurch\n\n#nowarn \"25\" // skip incomplete pattern warning\n[<EntryPoint>]\nlet main _ =\n let [c3; c4; c11; c12] = List.map itoch [3; 4; 11; 12]\n\n [ addChurch c3 c4\n ; multChurch c3 c4\n ; expChurch c3 c4\n ; expChurch c4 c3\n ; iszeroChurch zeroChurch\n ; iszeroChurch oneChurch\n ; predChurch c3\n ; subChurch c11 c3\n ; divChurch c11 c3\n ; divChurch c12 c3\n ] |> List.map chtoi |> printfn \"%A\"\n 0 // return an integer exit code\n", "language": "F-Sharp" }, { "code": "// types...\ntype Church = Church of (Church -> Church)\nlet applyChurch (Church chf) charg = chf charg\nlet composeChurch (Church chlf) (Church chrf) =\n Church <| fun f -> (chlf << chrf) f\n\nlet churchZero = Church(fun _ -> Church id)\nlet churchOne = Church id\nlet succChurch (Church chf) =\n Church <| fun f -> composeChurch f <| chf f\nlet addChurch cha chb =\n Church <| fun f -> composeChurch (applyChurch cha f) (applyChurch chb f)\nlet multChurch cha chb =\n composeChurch cha chb\nlet expChurch chbs chexp =\n applyChurch chexp chbs\nlet isZeroChurch ch =\n applyChurch (applyChurch ch (Church <| fun _ -> churchZero)) churchOne\nlet predChurch ch =\n Church <| fun f -> Church <| fun x ->\n let prdf = Church <| fun g -> Church <| fun h ->\n applyChurch h (applyChurch g f)\n applyChurch (applyChurch (applyChurch ch prdf)\n (Church <| fun _ -> x)) <| Church id\nlet subChurch cha chb =\n applyChurch (applyChurch chb <| Church predChurch) cha\n\nlet divChurch chdvdnd chdvsr =\n let rec divr n =\n let loop v = Church <| fun _ -> succChurch <| divr v\n let tst v = applyChurch (applyChurch v <| loop v) churchZero\n tst <| subChurch n chdvsr\n divr <| succChurch chdvdnd\n\nlet intToChurch i =\n List.fold (>>) id (List.replicate i succChurch) churchZero\nlet churchToInt ch =\n let mutable count: int = 0\n let addint1 = Church <| fun v -> count <- count + 1; v\n applyChurch (applyChurch ch addint1) churchZero |> ignore\n count\n\n#nowarn \"25\" // eliminate incomplete pattern match warning\n[<EntryPoint>]\nlet main _ =\n let [c3; c4; c11; c12] = List.map intToChurch [3; 4; 11; 12]\n [ addChurch c3 c4\n ; multChurch c3 c4\n ; expChurch c3 c4\n ; expChurch c4 c3\n ; isZeroChurch churchZero\n ; isZeroChurch c3\n ; predChurch c4\n ; subChurch c11 c3\n ; divChurch c11 c3\n ; division c12 c3\n ] |> List.map churchToInt |> printfn \"%A\"\n 0 // return an integer exit code\n", "language": "F-Sharp" }, { "code": "#nowarn \"25\" // eliminate incomplete pattern match warning\n\n// types...\ntype Church<'a> = Church of (Church<'a> -> Church<'a>)\n | ArityZero of 'a\nlet applyChurch (Church chf) charg =\n chf charg\nlet composeChurch (Church chlf) (Church chrf) =\n Church <| fun f -> (chlf << chrf) f\n\nlet churchZero<'a> = Church <| fun (_: Church<'a>) -> Church id\nlet churchOne = Church id\nlet succChurch (Church chf) =\n Church <| fun f -> composeChurch f <| chf f\nlet addChurch cha chb =\n Church <| fun f -> composeChurch (applyChurch cha f) (applyChurch chb f)\nlet multChurch cha chb =\n composeChurch cha chb\nlet expChurch chbs chexp =\n applyChurch chexp chbs\nlet isZeroChurch ch =\n applyChurch (applyChurch ch (Church <| fun _ -> churchZero)) churchOne\nlet predChurch ch =\n Church <| fun f -> Church <| fun x ->\n let prdf = Church <| fun g -> Church <| fun h ->\n applyChurch h (applyChurch g f)\n applyChurch (applyChurch (applyChurch ch prdf)\n (Church <| fun _ -> x)) <| Church id\nlet subChurch cha chb =\n applyChurch (applyChurch chb <| Church predChurch) cha\n\nlet divChurch chdvdnd chdvsr =\n let rec divr n =\n let loop v = Church <| fun _ -> succChurch <| divr v\n let tst v = applyChurch (applyChurch v <| loop v) churchZero\n tst <| subChurch n chdvsr\n divr <| succChurch chdvdnd\n\nlet intToChurch<'a> i =\n List.fold (>>) id (List.replicate i succChurch) churchZero<'a>\nlet churchToInt ch =\n let succInt = Church <| fun (ArityZero v) -> ArityZero <| v + 1\n match applyChurch (applyChurch ch succInt) <| ArityZero 0 with\n ArityZero r -> r\n\n[<EntryPoint>]\nlet main _ =\n let [c3; c4; c11; c12] = List.map intToChurch [3; 4; 11; 12]\n [ addChurch c3 c4\n ; multChurch c3 c4\n ; expChurch c3 c4\n ; expChurch c4 c3\n ; isZeroChurch churchZero\n ; isZeroChurch c3\n ; predChurch c4\n ; subChurch c11 c3\n ; divChurch c11 c3\n ; divChurch c12 c3\n ] |> List.map churchToInt |> printfn \"%A\"\n 0 // return an integer exit code\n", "language": "F-Sharp" }, { "code": "Type church\n ' eg {r_add,1,{a,b}}\n op As Integer\n n As Integer\n x(1 To 2) As Integer\nEnd Type\n\nDim Shared As church zero = Type<church>(1, 0, {0, 1})\n\nFunction succ(c As church) As church\n ' eg {r_add,1,{a,b}} => {r_add,2,{a,b}} aka a+b -> a+b+b\n c.n += 1\n Return c\nEnd Function\n\n' three normal integer-handling routines...\nFunction sum(n As Integer, a As Integer, b As Integer) As Integer\n For i As Integer = 1 To n\n a += b\n Next i\n Return a\nEnd Function\n\nFunction mul(n As Integer, a As Integer, b As Integer) As Integer\n For i As Integer = 1 To n\n a *= b\n Next i\n Return a\nEnd Function\n\nFunction pow(n As Integer, a As Integer, b As Integer) As Integer\n For i As Integer = 1 To n\n a = a ^ b\n Next i\n Return a\nEnd Function\n\n' ...and three church constructors to match\n' (no maths here, just pure static data)\nFunction churchSum(c As church, d As church) As church\n Dim res As church\n res.op = 1 ' 1 for add\n res.n = 1\n res.x(1) = c.n\n res.x(2) = d.n\n Return res\nEnd Function\n\nFunction churchMul(c As church, d As church) As church\n Dim res As church\n res.op = 2 ' 2 for mul\n res.n = 1\n res.x(1) = c.n\n res.x(2) = d.n\n Return res\nEnd Function\n\nFunction churchPow(c As church, d As church) As church\n Dim res As church\n res.op = 3 ' 3 for pow\n res.n = 1\n res.x(1) = c.n\n res.x(2) = d.n\n Return res\nEnd Function\n\nFunction churchToNum(c As church) As Integer\n ' note this is where the bulk of any processing happens\n Select Case c.op\n Case 1\n Return sum(c.n, c.x(1), c.x(2))\n Case 2\n Return mul(c.n, c.x(1), c.x(2))\n Case 3\n Return pow(c.n, c.x(1), c.x(2))\n End Select\nEnd Function\n\nFunction numToChurch(i As Integer) As church\n Return Iif(i = 0, zero, succ(numToChurch(i - 1)))\nEnd Function\n\nDim As church three = succ(succ(succ(zero)))\nDim As church four = succ(three)\nPrint \"three -> \"; churchToNum(three)\nPrint \"four -> \"; churchToNum(four)\nPrint \"three + four -> \"; churchToNum(churchSum(three, four))\nPrint \"three * four -> \"; churchToNum(churchMul(three, four))\nPrint \"three ^ four -> \"; churchToNum(churchPow(three, four))\nPrint \"four ^ three -> \"; churchToNum(churchPow(four, three))\nPrint \"5 -> five -> \"; churchToNum(numToChurch(5))\n\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n return func(x any) any {\n return x\n }\n}\n\nfunc (c church) succ() church {\n return func(f fn) fn {\n return func(x any) any {\n return f(c(f)(x))\n }\n }\n}\n\nfunc (c church) add(d church) church {\n return func(f fn) fn {\n return func(x any) any {\n return c(f)(d(f)(x))\n }\n }\n}\n\nfunc (c church) mul(d church) church {\n return func(f fn) fn {\n return func(x any) any {\n return c(d(f))(x)\n }\n }\n}\n\nfunc (c church) pow(d church) church {\n di := d.toInt()\n prod := c\n for i := 1; i < di; i++ {\n prod = prod.mul(c)\n }\n return prod\n}\n\nfunc (c church) toInt() int {\n return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n if i == 0 {\n return zero\n } else {\n return intToChurch(i - 1).succ()\n }\n}\n\nfunc incr(i any) any {\n return i.(int) + 1\n}\n\nfunc main() {\n z := church(zero)\n three := z.succ().succ().succ()\n four := three.succ()\n\n fmt.Println(\"three ->\", three.toInt())\n fmt.Println(\"four ->\", four.toInt())\n fmt.Println(\"three + four ->\", three.add(four).toInt())\n fmt.Println(\"three * four ->\", three.mul(four).toInt())\n fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n fmt.Println(\"5 -> five ->\", intToChurch(5).toInt())\n}\n", "language": "Go" }, { "code": "package main\n\nimport \"fmt\"\n\ntype Church func(Church) Church\n\nfunc id[X any](x X) X {\n return x\n}\n\nfunc compose[X any, Y any, Z any](f func(Y) Z, g func(X) Y) func(X) Z {\n return func(x X) Z {\n return f(g(x))\n }\n}\n\nfunc zero() Church {\n return func(f Church) Church {\n return id[Church]\n }\n}\n\nfunc one() Church {\n return id[Church]\n}\n\nfunc succ(n Church) Church {\n return func(f Church) Church {\n return compose(f, n(f))\n }\n}\n\nfunc plus(m, n Church) Church {\n return func(f Church) Church {\n return compose(m(f), n(f))\n }\n}\n\nfunc mult(m, n Church) Church {\n return compose(m, n)\n}\n\nfunc exp(m, n Church) Church {\n return n(m)\n}\n\nfunc toInt(x Church) int {\n counter := 0\n fCounter := func(f Church) Church {\n counter++\n return f\n }\n\n x(fCounter)(id[Church])\n return counter\n}\n\nfunc toStr(x Church) string {\n counter := \"\"\n fCounter := func(f Church) Church {\n counter += \"|\"\n return f\n }\n\n x(fCounter)(id[Church])\n return counter\n}\n\nfunc main() {\n fmt.Println(\"zero =\", toInt(zero()))\n\n one := one()\n fmt.Println(\"one =\", toInt(one))\n\n two := succ(succ(zero()))\n fmt.Println(\"two =\", toInt(two))\n\n three := plus(one, two)\n fmt.Println(\"three =\", toInt(three))\n\n four := mult(two, two)\n fmt.Println(\"four =\", toInt(four))\n\n eight := exp(two, three)\n fmt.Println(\"eight =\", toInt(eight))\n\n fmt.Println(\"toStr(four) =\", toStr(four))\n}\n", "language": "Go" }, { "code": "class ChurchNumerals {\n static void main(args) {\n\n def zero = { f -> { a -> a } }\n def succ = { n -> { f -> { a -> f(n(f)(a)) } } }\n def add = { n -> { k -> { n(succ)(k) } } }\n def mult = { f -> { g -> { a -> f(g(a)) } } }\n def pow = { f -> { g -> g(f) } }\n\n def toChurchNum\n toChurchNum = { n ->\n n == 0 ? zero : succ(toChurchNum(n - 1))\n }\n\n def toInt = { n ->\n n(x -> x + 1)(0)\n }\n\n def three = succ(succ(succ(zero)))\n println toInt(three) // prints 3\n\n def four = succ(three)\n println toInt(four) // prints 4\n\n println \"3 + 4 = ${toInt(add(three)(four))}\" // prints 3 + 4 = 7\n println \"4 + 3 = ${toInt(add(four)(three))}\" // prints 4 + 3 = 7\n\n println \"3 * 4 = ${toInt(mult(three)(four))}\" // prints 3 * 4 = 12\n println \"4 * 3 = ${toInt(mult(four)(three))}\" // prints 4 * 3 = 12\n\n println \"3 ^ 4 = ${toInt(pow(three)(four))}\" // prints 3 ^ 4 = 81\n println \"4 ^ 3 = ${toInt(pow(four)(three))}\" // prints 4 ^ 3 = 64\n }\n}\n", "language": "Groovy" }, { "code": "import Unsafe.Coerce ( unsafeCoerce )\n\ntype Church a = (a -> a) -> a -> a\n\nchurchZero :: Church a\nchurchZero = const id\n\nchurchOne :: Church a\nchurchOne = id\n\nsuccChurch :: Church a -> Church a\nsuccChurch = (<*>) (.) -- add one recursion, or \\ ch f -> f . ch f\n\naddChurch :: Church a -> Church a -> Church a\naddChurch = (<*>). fmap (.) -- or \\ ach bch f -> ach f . bch f\n\nmultChurch :: Church a -> Church a -> Church a\nmultChurch = (.) -- or \\ ach bch -> ach . bch\n\nexpChurch :: Church a -> Church a -> Church a\nexpChurch basech expch = unsafeCoerce expch basech\n\nisChurchZero :: Church a -> Church a\nisChurchZero ch = unsafeCoerce ch (const churchZero) churchOne\n\npredChurch :: Church a -> Church a\npredChurch ch f x = unsafeCoerce ch (\\ g h -> h (g f)) (const x) id\n\nminusChurch :: Church a -> Church a -> Church a\nminusChurch ach bch = unsafeCoerce bch predChurch ach\n\n-- counts the times divisor can be subtracted from dividend to zero...\ndivChurch :: Church a -> Church a -> Church a\ndivChurch dvdnd dvsr =\n let divr n d =\n (\\ v -> v (const $ succChurch $ divr v d) -- if branch\n churchZero -- else branch\n ) (minusChurch n d)\n in divr (unsafeCoerce succChurch dvdnd) $ unsafeCoerce dvsr\n\nchurchFromInt :: Int -> Church a\nchurchFromInt 0 = churchZero\nchurchFromInt n = succChurch $ churchFromInt (n - 1)\n\n-- Or as a fold:\n-- churchFromInt n = foldr (.) id . replicate n\n\n-- Or as an iterated application:\n-- churchFromInt n = iterate succChurch churchZero !! n\n\nintFromChurch :: Church Int -> Int\nintFromChurch ch = ch succ 0\n\n------------------------------------- TEST -------------------------------------\nmain :: IO ()\nmain = do\n let [cThree, cFour, cEleven, cTwelve] = churchFromInt <$> [3, 4, 11, 12]\n print $ fmap intFromChurch [ addChurch cThree cFour\n , multChurch cThree cFour\n , expChurch cFour cThree\n , expChurch cThree cFour\n , isChurchZero churchZero\n , predChurch cFour\n , minusChurch cEleven cThree\n , divChurch cEleven cThree\n , divChurch cTwelve cThree\n ]\n", "language": "Haskell" }, { "code": "{-# LANGUAGE RankNTypes #-}\n\nnewtype Church = Church { unChurch :: forall a. (a -> a) -> a -> a }\n\nchurchZero :: Church\nchurchZero = Church $ const id\n\nsuccChurch :: Church -> Church\nsuccChurch ch = Church $ (<*>) (.) $ unChurch ch -- add one recursion\n\naddChurch :: Church -> Church -> Church\naddChurch ach bch =\n Church $ ((<*>) . fmap (.)) (unChurch ach) (unChurch bch)\n\nmultChurch :: Church -> Church -> Church\nmultChurch ach bch = Church $ unChurch ach . unChurch bch\n\nexpChurch :: Church -> Church -> Church\nexpChurch basech expch = Church $ unChurch expch $ unChurch basech\n\npredChurch :: Church -> Church\npredChurch ch = Church $ \\ f x ->\n unChurch ch (\\ g h -> h (g f)) (const x) id\n\nminusChurch :: Church -> Church -> Church\nminusChurch ach bch = unChurch bch predChurch ach\n\nisChurchZero :: Church -> Church\nisChurchZero ch = unChurch ch (const churchZero) $ Church id\n\ndivChurch :: Church -> Church -> Church\ndivChurch dvdnd dvsr =\n let divr n =\n (\\ v -> unChurch v\n (const $ succChurch $ divr v)\n churchZero\n )(minusChurch n dvsr)\n in divr (succChurch dvdnd)\n\nchurchFromInt :: Int -> Church\nchurchFromInt 0 = churchZero\nchurchFromInt n = succChurch $ churchFromInt (n - 1)\n\n-- Or as a fold:\n-- churchFromInt n = foldr (.) id . replicate n\n\n-- Or as an iterated application:\n-- churchFromInt n = iterate succChurch churchZero !! n\n\nintFromChurch :: Church -> Int\nintFromChurch ch = unChurch ch succ 0\n\n------------------------------------- TEST -------------------------------------\nmain :: IO ()\nmain = do\n let [cThree, cFour, cEleven, cTwelve] = churchFromInt <$> [3, 4, 11, 12]\n print $ fmap intFromChurch [ addChurch cThree cFour\n , multChurch cThree cFour\n , expChurch cFour cThree\n , expChurch cThree cFour\n , isChurchZero churchZero\n , predChurch cFour\n , minusChurch cEleven cThree\n , divChurch cEleven cThree\n , divChurch cTwelve cThree\n ]\n", "language": "Haskell" }, { "code": "chget=: {{(0;1;1;1) {:: y}}\n\nchset=: {{\n 'A B'=.;y\n 'C D'=.B\n 'E F'=.D\n <A;<C;<E;<<.x\n}}\n\nch0=: {{\n if.0=#y do.y=.;:'>:' end. NB. replace empty gerund with increment\n 0 chset y`:6^:2`''\n}}\n\napply=: `:6\n\nchNext=: {{(1+chget y) chset y}}\n\nchAdd=: {{(x +&chget y) chset y}}\nchSub=: {{(x -&chget y) chset y}}\nchMul=: {{(x *&chget y) chset y}}\nchExp=: {{(x ^&chget y) chset y}}\nint2ch=: {{y chset ch0 ''}}\nch2int=: chget\n", "language": "J" }, { "code": "three=: chNext^:3 ch0''\nfour=: chNext^:4 ch0''\nsixtyfour=: four chExp three\neightyone=: three chExp four\n four apply 1\n16\n chget three\n3\n chget four\n4\n chget sixtyfour\n64\n chget eightyone\n81\n", "language": "J" }, { "code": " three apply 0\n3\n three apply 10\n13\n four=: 4 chset ch0 {{2*y}}`''\n chget four\n4\n four apply 0\n0\n four apply 10\n160\n", "language": "J" }, { "code": " four=: 4 chset ch0 +:`''\n four apply 10\n160\n (three chSub four) apply 10\n5\n (sixtyfour chSub three chExp four) apply 10x^20\n762939453125000\n (sixtyfour chSub three chExp 4 chset ch0 5x&*`'') apply 10x^20\n131072000\n", "language": "J" }, { "code": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n }\n\n public static ChurchNum zero() {\n return f -> x -> x;\n }\n\n public static ChurchNum next(ChurchNum n) {\n return f -> x -> f.apply(n.apply(f).apply(x));\n }\n\n public static ChurchNum plus(ChurchNum a) {\n return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n }\n\n public static ChurchNum pow(ChurchNum m) {\n return n -> m.apply(n);\n }\n\n public static ChurchNum mult(ChurchNum a) {\n return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n }\n\n public static ChurchNum toChurchNum(int n) {\n if (n <= 0) {\n return zero();\n }\n return next(toChurchNum(n - 1));\n }\n\n public static int toInt(ChurchNum c) {\n AtomicInteger counter = new AtomicInteger(0);\n ChurchNum funCounter = f -> {\n counter.incrementAndGet();\n return f;\n };\n\n plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n return counter.get();\n }\n\n public static void main(String[] args) {\n ChurchNum zero = zero();\n ChurchNum three = next(next(next(zero)));\n ChurchNum four = next(next(next(next(zero))));\n\n System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); // prints 7\n System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); // prints 7\n\n System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); // prints 12\n System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); // prints 12\n\n // exponentiation. note the reversed order!\n System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); // prints 81\n System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); // prints 64\n\n System.out.println(\" 8=\" + toInt(toChurchNum(8))); // prints 8\n }\n}\n", "language": "Java" }, { "code": "(() => {\n 'use strict';\n\n // ----------------- CHURCH NUMERALS -----------------\n\n const churchZero = f =>\n identity;\n\n\n const churchSucc = n =>\n f => compose(f)(n(f));\n\n\n const churchAdd = m =>\n n => f => compose(n(f))(m(f));\n\n\n const churchMult = m =>\n n => f => n(m(f));\n\n\n const churchExp = m =>\n n => n(m);\n\n\n const intFromChurch = n =>\n n(succ)(0);\n\n\n const churchFromInt = n =>\n compose(\n foldl(compose)(identity)\n )(\n replicate(n)\n );\n\n\n // Or, by explicit recursion:\n const churchFromInt_ = x => {\n const go = i =>\n 0 === i ? (\n churchZero\n ) : churchSucc(go(pred(i)));\n return go(x);\n };\n\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () => {\n const [cThree, cFour] = map(churchFromInt)([3, 4]);\n\n return map(intFromChurch)([\n churchAdd(cThree)(cFour),\n churchMult(cThree)(cFour),\n churchExp(cFour)(cThree),\n churchExp(cThree)(cFour),\n ]);\n };\n\n\n // --------------------- GENERIC ---------------------\n\n // compose (>>>) :: (a -> b) -> (b -> c) -> a -> c\n const compose = f =>\n g => x => f(g(x));\n\n\n // foldl :: (a -> b -> a) -> a -> [b] -> a\n const foldl = f =>\n a => xs => [...xs].reduce(\n (x, y) => f(x)(y),\n a\n );\n\n\n // identity :: a -> a\n const identity = x => x;\n\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f =>\n // The list obtained by applying f\n // to each element of xs.\n // (The image of xs under f).\n xs => [...xs].map(f);\n\n\n // pred :: Enum a => a -> a\n const pred = x =>\n x - 1;\n\n\n // replicate :: Int -> a -> [a]\n const replicate = n =>\n // n instances of x.\n x => Array.from({\n length: n\n }, () => x);\n\n\n // succ :: Enum a => a -> a\n const succ = x =>\n 1 + x;\n\n // MAIN ---\n console.log(JSON.stringify(main()));\n})();\n", "language": "JavaScript" }, { "code": "def church(f; $x; $m):\n if $m == 0 then .\n elif $m == 1 then $x|f\n else church(f; $x; $m - 1)\n end;\n", "language": "Jq" }, { "code": "def church(f; $m):\n if $m < 0 then error(\"church is not defined on negative integers\")\n elif $m == 0 then .\n elif $m == 1 then f\n else church(f; $m - 1) | f\n end;\n", "language": "Jq" }, { "code": "id(x) = x -> x\nzero() = x -> id(x)\nadd(m) = n -> (f -> (x -> n(f)(m(f)(x))))\nmult(m) = n -> (f -> (x -> n(m(f))(x)))\nexp(m) = n -> n(m)\nsucc(i::Int) = i + 1\nsucc(cn) = f -> (x -> f(cn(f)(x)))\nchurch2int(cn) = cn(succ)(0)\nint2church(n) = n < 0 ? throw(\"negative Church numeral\") : (n == 0 ? zero() : succ(int2church(n - 1)))\n\nfunction runtests()\n church3 = int2church(3)\n church4 = int2church(4)\n println(\"Church 3 + Church 4 = \", church2int(add(church3)(church4)))\n println(\"Church 3 * Church 4 = \", church2int(mult(church3)(church4)))\n println(\"Church 4 ^ Church 3 = \", church2int(exp(church4)(church3)))\n println(\"Church 3 ^ Church 4 = \", church2int(exp(church3)(church4)))\nend\n\nruntests()\n", "language": "Julia" }, { "code": "id = x -> x\nalways(f) = d -> f\nstruct Church # used for \"infinite\" Church type resolution\n unchurch::Function\nend\n(cn::Church)(ocn::Church) = cn.unchurch(ocn)\ncompose(cnl::Church) = cnr::Church -> Church(f -> cnl(cnr(f)))\n(cn::Church)(fn::Function) = cn.unchurch(fn)\n(cn::Church)(i::Int) = cn.unchurch(i)\nzero = Church(always(Church(id)))\none = Church(id)\nsucc(cn::Church) = Church(f -> (x -> f(cn(f)(x))))\nadd(m::Church) = n::Church -> Church(f -> n(f) ∘ m(f))\nmult(m::Church) = n::Church -> Church(f -> m(n(f)))\nexp(m::Church) = n::Church -> Church(n(m))\niszero(n::Church) = n.unchurch(Church(always(zero)))(one)\npred(n::Church) = Church(f -> Church(x -> n(\n g -> (h -> h(g(f))))(Church(always(x)))(Church(id))))\nsubt(n::Church) = m::Church -> Church(f -> m(pred)(n)(f))\ndivr(n::Church) = d::Church ->\n Church(f -> ((v::Church -> v(Church(always(succ(divr(v)(d)))))(zero))(\n subt(n)(d)))(f))\ndiv(dvdnd::Church) = dvsr::Church -> divr(succ(dvdnd))(dvsr)\nchurch2int(cn::Church) = cn(i -> i + 1)(0)\nint2church(n) = n <= 0 ? zero : succ(int2church(n - 1))\n\nfunction runtests()\n church3 = int2church(3)\n church4 = succ(church3)\n church11 = int2church(11)\n church12 = succ(church11)\n println(\"Church 3 + Church 4 = \", church2int(add(church3)(church4)))\n println(\"Church 3 * Church 4 = \", church2int(mult(church3)(church4)))\n println(\"Church 3 ^ Church 4 = \", church2int(exp(church3)(church4)))\n println(\"Church 4 ^ Church 3 = \", church2int(exp(church4)(church3)))\n println(\"isZero(Church 0) = \", church2int(iszero(zero)))\n println(\"isZero(Church 3) = \", church2int(iszero(church3)))\n println(\"pred(Church 4) = \", church2int(pred(church4)))\n println(\"pred(Church 0) = \", church2int(pred(zero)))\n println(\"Church 11 - Church 3 = \", church2int(subt(church11)(church3)))\n println(\"Church 11 / Church 3 = \", church2int(div(church11)(church3)))\n println(\"Church 12 / Church 3 = \", church2int(div(church12)(church3)))\nend\n\nruntests()\n", "language": "Julia" }, { "code": "{def succ {lambda {:n :f :x} {:f {:n :f :x}}}}\n{def add {lambda {:n :m :f :x} {{:n :f} {:m :f :x}}}}\n{def mul {lambda {:n :m :f} {:m {:n :f}}}}\n{def power {lambda {:n :m} {:m :n}}}\n\n{def church {lambda {:n} {{:n {+ {lambda {:x} {+ :x 1}}}} 0}}}\n\n{def zero {lambda {:f :x} :x}}\n{def three {succ {succ {succ zero}}}}\n{def four {succ {succ {succ {succ zero}}}}}\n\n3+4 = {church {add {three} {four}}} -> 7\n3*4 = {church {mul {three} {four}}} -> 12\n3^4 = {church {power {three} {four}}} -> 81\n4^3 = {church {power {four} {three}}} -> 64\n", "language": "Lambdatalk" }, { "code": "function churchZero()\n return function(x) return x end\nend\n\nfunction churchSucc(c)\n return function(f)\n return function(x)\n return f(c(f)(x))\n end\n end\nend\n\nfunction churchAdd(c, d)\n return function(f)\n return function(x)\n return c(f)(d(f)(x))\n end\n end\nend\n\nfunction churchMul(c, d)\n return function(f)\n return c(d(f))\n end\nend\n\nfunction churchExp(c, e)\n return e(c)\nend\n\nfunction numToChurch(n)\n local ret = churchZero\n for i = 1, n do\n ret = succ(ret)\n end\n return ret\nend\n\nfunction churchToNum(c)\n return c(function(x) return x + 1 end)(0)\nend\n\nthree = churchSucc(churchSucc(churchSucc(churchZero)))\nfour = churchSucc(churchSucc(churchSucc(churchSucc(churchZero))))\n\nprint(\"'three'\\t=\", churchToNum(three))\nprint(\"'four' \\t=\", churchToNum(four))\nprint(\"'three' * 'four' =\", churchToNum(churchMul(three, four)))\nprint(\"'three' + 'four' =\", churchToNum(churchAdd(three, four)))\nprint(\"'three' ^ 'four' =\", churchToNum(churchExp(three, four)))\nprint(\"'four' ^ 'three' =\", churchToNum(churchExp(four, three)))\n", "language": "Lua" }, { "code": "import macros, sugar\ntype\n Fn = proc(p: pointer): pointer{.noSideEffect.}\n Church = proc(f: Fn): Fn{.noSideEffect.}\n MetaChurch = proc(c: Church): Church{.noSideEffect.}\n\n#helpers:\ntemplate λfλx(exp): untyped = (f: Fn){.closure.}=>((x: pointer){.closure.}=>exp)\ntemplate λcλf(exp): untyped = (c: Church){.closure.}=>((f: Fn){.closure.}=>exp)\nmacro type_erase(body: untyped): untyped =\n let\n name = if body[0].kind == nnkPostFix: body[0][1] else: body[0]\n typ = body[3][0]\n quote do:\n `body`\n proc `name`(p: pointer): pointer =\n template erased: untyped = cast[ptr `typ`](p)[]\n erased = erased.`name`\n p\nmacro type_erased(body: untyped): untyped =\n let (id1, id2, id3) = (body[0][0][0], body[0][0][1], body[0][1])\n quote do:\n result = `id3`\n result = cast[ptr typeof(`id3`)](\n `id1`(`id2`)(result.addr)\n )[]\n\n#simple math\nfunc zero*(): Church = λfλx: x\nfunc succ*(c: Church): Church = λfλx: f (c f)x\nfunc `+`*(c, d: Church): Church = λfλx: (c f) (d f)x\nfunc `*`*(c, d: Church): Church = λfλx: c(d f)x\n\n#exponentiation\nfunc metazero(): MetaChurch = λcλf: f\nfunc succ(m: MetaChurch): MetaChurch{.type_erase.} = λcλf: c (m c)f\nconverter toMeta*(c: Church): MetaChurch = type_erased: c(succ)(metazero())\nfunc `^`*(c: Church, d: MetaChurch): Church = d c\n\n#conversions to/from actual numbers\nfunc incr(x: int): int{.type_erase.} = x+1\nfunc toInt(c: Church): int = type_erased: c(incr)(0)\nfunc toChurch*(x: int): Church = return if x <= 0: zero() else: toChurch(x-1).succ\nfunc `$`*(c: Church): string = $c.toInt\n\nwhen isMainModule:\n let three = zero().succ.succ.succ\n let four = 4.toChurch\n echo [three+four, three*four, three^four, four^three]\n", "language": "Nim" }, { "code": "import sugar\n\ntype # use a thunk closure as a data type...\n In = () -> int # a lazy thunk producing an int\n Func = In -> In\n Church = Func -> Func\n MetaChurch = Church -> Church\n MetaMetaChurch = MetaChurch -> MetaChurch\n PredChurch = (Func -> In) -> (Func -> In)\n MetaPredChurch = PredChurch -> PredChurch\n\ntype # type Kind to/from conversions...\n Pun {.union.} = object # does safer casting...\n normal: Church\n upone: MetaChurch\n uptwo: MetaMetaChurch\n preded: MetaPredChurch\nfunc lift1(ch: Church): MetaChurch = Pun(normal: ch).upone\nfunc lift2(ch: Church): MetaMetaChurch = Pun(normal: ch).uptwo\nfunc liftpred(ch: Church): MetaPredChurch = Pun(normal: ch).preded\n\nlet\n zeroChurch: Church = (_: Func) -> Func => ((x: In) => x)\n oneChurch: Church = (f: Func) -> Func => f\n succChurch = (ch: Church) -> Church =>\n ((f: Func) => ((x: In) => f(ch(f)x)))\n addChurch = (ach, bch: Church) -> Church =>\n ((f: Func) => ((x: In) => ((ach f)(bch(f)x))))\n multChurch = (ach, bch: Church) -> Church => ((f: Func) => ach(bch(f)))\n expChurch = (basech, expch: Church) -> Church => (expch.lift1() basech)\n isZeroChurch = (ch: Church) -> Church =>\n (ch.lift2()((_: Church) => zeroChurch) oneChurch)\n predChurch = (ch: Church) -> Church =>\n (func(f: Func): Func =\n let prd = (gf: Func -> In) => ((hf: In -> In) => (hf(gf(f))))\n # magic is here, reduces by one function level...\n ((x: In) => (ch.liftpred())(prd)((_: Func) => x)((t:In) => t)))\n minusChurch = (ach, bch: Church) -> Church =>\n (bch.lift2()(predChurch)(ach))\n # recursively counts times divisor can be subtracted from dividend...\n divChurch = proc(dvdndch, dvsrch: Church): Church =\n proc divr(n: Church): Church =\n (((vch: Church) =>\n vch.lift2()( # test for zero\n (_: Church) => (divr(vch).succChurch))( # not zero, loop\n zeroChurch)) # if zero, return zero\n )(n.minusChurch(dvsrch)) # subtract one more divisor per loop\n divr(dvdndch.succChurch)\n\n# conversions to/from Church and int...\nproc toChurch(x: int): Church =\n result = zeroChurch\n for _ in 1 .. x: result = result.succChurch\nlet incr = (x: In) => (() => x() + 1)\nproc toInt(ch: Church): int = ch(incr)(() => 0)()\nproc `$`(ch: Church): string = $(ch.toInt)\n\nwhen isMainModule:\n let threeChurch = 3.toChurch\n let fourChurch = threeChurch.succChurch\n let elevenChurch = 11.toChurch\n let twelveChurch = elevenChurch.succChurch\n echo [ threeChurch.addChurch(fourChurch)\n , threeChurch.multChurch(fourChurch)\n , threeChurch.expChurch(fourChurch)\n , fourChurch.expChurch(threeChurch)\n , zeroChurch.isZeroChurch, oneChurch.isZeroChurch\n , fourChurch.predChurch\n , elevenChurch.minusChurch(threeChurch)\n , elevenChurch.divChurch(threeChurch)\n , twelveChurch.divChurch(threeChurch)\n ]\n", "language": "Nim" }, { "code": "import sugar\n\ntype\n Tag = enum tgChurch, tgArityZero\n Church = ref object\n case tag: Tag\n of tgChurch: church: Church -> Church\n of tgArityZero: value: int\nfunc makeCChurch(chf: Church -> Church): Church =\n Church(tag: tgChurch, church: chf)\nproc applyChurch(ch, charg: Church): Church =\n case ch.tag\n of tgChurch: ch.church(charg)\n of tgArityZero: charg # never happens!\nfunc composeChurch(chl, chr: Church): Church =\n case chl.tag\n of tgChurch:\n case chr.tag\n of tgChurch: makeCChurch((f: Church) => chl.church(chr.church(f)))\n of tgArityZero: chl # never happens!\n of tgArityZero: chl # never happens!\n\nlet churchZero = makeCChurch((f: Church) => makeCChurch((x) => x))\nlet churchOne = makeCChurch((x) => x)\nproc succChurch(ch: Church): Church =\n makeCChurch((f) => composeChurch(f, applyChurch(ch, f)))\nproc addChurch(cha, chb: Church): Church =\n makeCChurch((f) =>\n composeChurch(applyChurch(cha, f), applyChurch(chb, f)))\nproc multChurch(cha, chb: Church): Church = composeChurch(cha, chb)\nproc expChurch(chbs, chexp: Church): Church = applyChurch(chexp, chbs)\nproc isZeroChurch(ch: Church): Church =\n applyChurch(applyChurch(ch, Church(tag: tgChurch,\n church: (_: Church) => churchZero)),\n churchOne)\nproc predChurch(ch: Church): Church =\n proc ff(f: Church): Church =\n proc xf(x: Church): Church =\n let prd = makeCChurch((g) => makeCChurch((h) =>\n applyChurch(h, applyChurch(g, f))))\n let frstch = makeCChurch((_) => x)\n let idch = makeCChurch((a) => a)\n applyChurch(applyChurch(applyChurch(ch, prd), frstch), idch)\n makeCChurch(xf)\n makeCChurch(ff)\nproc subChurch(cha, chb: Church): Church =\n applyChurch(applyChurch(chb, makeCChurch(predChurch)), cha)\nproc divChurch(chdvdnd, chdvsr: Church): Church =\n proc divr(chn: Church): Church =\n proc tst(chv: Church): Church =\n let loopr = makeCChurch((_) => succChurch(divr(chv)))\n applyChurch(applyChurch(chv, loopr), churchZero)\n tst(subChurch(chn, chdvsr))\n divr(succChurch(chdvdnd))\n\n# converters...\nconverter intToChurch(i: int): Church =\n func loop(n: int, rch: Church): Church = # recursive function call\n if n <= 0: rch else: loop(n - 1, succChurch(rch))\n loop(i, churchZero)\n# result = churchZero # imperative non recursive way...\n# for _ in 1 .. i: result = succChurch(result)\nconverter churchToInt(ch: Church): int =\n func succInt(chv: Church): Church =\n case chv.tag\n of tgArityZero: Church(tag: tgArityZero, value: chv.value + 1)\n of tgChurch: chv\n let rslt = applyChurch(applyChurch(ch, Church(tag: tgChurch, church: succInt)),\n Church(tag: tgArityZero, value: 0))\n case rslt.tag\n of tgArityZero: rslt.value\n of tgChurch: -1\nproc `$`(ch: Church): string = $ch.int\n\n# test it...\nwhen isMainModule:\n let c3: Church = 3\n let c4 = succChurch c3\n let c11: Church = 11\n let c12 = succChurch c11\n echo addChurch(c3, c4), \" \",\n multChurch(c3, c4), \" \",\n expChurch(c3, c4), \" \",\n expChurch(c4, c3), \" \",\n isZeroChurch(churchZero), \" \",\n isZeroChurch(c3), \" \",\n predChurch(c4), \" \",\n subChurch(c11, c3), \" \",\n divChurch(c11, c3), \" \",\n divChurch(c12, c3)\n", "language": "Nim" }, { "code": "(* Using type as suggested in https://stackoverflow.com/questions/43426709/does-ocamls-type-system-prevent-it-from-modeling-church-numerals\n This is an explicitly polymorphic type : it says that f must be of type ('a -> 'a) -> 'a -> 'a for any possible a \"at same time\".\n*)\ntype church_num = { f : 'a. ('a -> 'a) -> 'a -> 'a }\n\n(* Zero means apply f 0 times to x, aka return x *)\nlet ch_zero : church_num = { f = fun _ -> fun x -> x }\n\n(* One simplifies to just returning the function *)\nlet ch_one : church_num = { f = fun fn -> fn }\n\n(* The next numeral of a church numeral would apply f one more time *)\nlet ch_succ (c : church_num) : church_num = { f = fun fn x -> fn (c.f fn x) }\n\n(* Adding m and n is applying f m times and then also n times *)\nlet ch_add (m : church_num) (n : church_num) : church_num =\n { f = fun fn x -> n.f fn (m.f fn x) }\n\n(* Multiplying is repeated addition : add n, m times *)\nlet ch_mul (m : church_num) (n : church_num) : church_num =\n { f = fun fn x -> m.f (n.f fn) x }\n\n(* Exp is repeated multiplication : multiply by base, exp times.\n However, Church numeral n is in some sense the n'th power of a function f applied to x\n So exp base = apply function base to the exp'th power = base^exp.\n*)\nlet ch_exp (base : church_num) (exp : church_num) : church_num =\n { f = fun fn x -> (exp.f base.f) fn x }\n\n(* extended Church functions: *)\n\n(* test function for church zero *)\nlet ch_is_zero (c : church_num) : church_num =\n { f = fun fn x -> c.f (fun _ -> fun _ -> fun xi -> xi) (* when argument is not ch_zero *)\n (fun fi -> fi) (* when argument is ch_zero *) fn x }\n\n(* church predecessor function; reduces function calls by one unless already church zero *)\nlet ch_pred (c : church_num) : church_num =\n { f = fun fn x -> c.f (fun g h -> h (g fn)) (fun _ -> x) (fun xi -> xi) }\n\n(* church subtraction function; calls predecessor function second argument times on first *)\nlet ch_sub (m : church_num) (n : church_num) : church_num = n.f ch_pred m\n\n(* church division function; counts number of times divisor can be recursively\n subtracted from dividend *)\nlet ch_div (dvdnd : church_num) (dvsr : church_num) : church_num =\n let rec divr n = (fun v -> v.f (fun _ -> (ch_succ (divr v)))\n ch_zero) (ch_sub n dvsr)\n in divr (ch_succ dvdnd)\n\n(* conversion functions: *)\n\n(* Convert a number to a church_num via recursion *)\nlet church_of_int (n : int) : church_num =\n if n < 0\n then raise (Invalid_argument (string_of_int n ^ \" is not a natural number\"))\n else\n (* Tail-recursed helper *)\n let rec helper n acc =\n if n = 0\n then acc\n else helper (n-1) (ch_succ acc)\n in helper n ch_zero\n\n(* Convert a church_num to an int is rather easy! Just +1 n times. *)\nlet int_of_church (n : church_num) : int = n.f succ 0\n\n(* Now the tasks at hand: *)\n\n(* Derive Church numerals three, four, eleven, and twelve,\n in terms of Church zero and a Church successor function *)\n\nlet ch_three = church_of_int 3\nlet ch_four = ch_three |> ch_succ\nlet ch_eleven = church_of_int 11\nlet ch_twelve = ch_eleven |> ch_succ\n\n(* Use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4 *)\nlet ch_7 = ch_add ch_three ch_four\nlet ch_12 = ch_mul ch_three ch_four\n\n(* Similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function *)\nlet ch_64 = ch_exp ch_four ch_three\nlet ch_81 = ch_exp ch_three ch_four\n\n(* check that ch_is_zero works *)\nlet ch_1 = ch_is_zero ch_zero\nlet ch_0 = ch_is_zero ch_three\n\n(* check church predecessor, subtraction, and division, functions work *)\nlet ch_2 = ch_pred ch_three\nlet ch_8 = ch_sub ch_eleven ch_three\nlet ch_3 = ch_div ch_eleven ch_three\nlet ch_4 = ch_div ch_twelve ch_three\n\n(* Convert each result back to an integer, and return it as a string *)\nlet result = List.map (fun c -> string_of_int(int_of_church c))\n [ ch_three; ch_four; ch_7; ch_12; ch_64; ch_81;\n ch_eleven; ch_twelve; ch_1; ch_0; ch_2; ch_8; ch_3; ch_4 ]\n |> String.concat \"; \" |> Printf.sprintf \"[ %s ]\"\n\n;;\n\nprint_endline result\n", "language": "OCaml" }, { "code": "zero = @(f) @(x) x;\nsucc = @(n) @(f) @(x) f(n(f)(x));\nadd = @(m, n) @(f) @(x) m(f)(n(f)(x));\nmul = @(m, n) @(f) @(x) m(n(f))(x);\npow = @(b, e) e(b);\n\n% Need a short-circuiting ternary\niif = @(varargin) varargin{3 - varargin{1}}();\n\n% Helper for anonymous recursion\n% The branches are thunked to prevent infinite recursion\nto_church_ = @(f, i) iif(i == 0, @() zero, @() succ(f(f, i - 1)));\nto_church = @(i) to_church_(to_church_, i);\n\nto_int = @(c) c(@(n) n + 1)(0);\n\nthree = succ(succ(succ(zero)));\nfour = succ(succ(succ(succ(zero))));\n\ncellfun(to_int, {\n add(three, four),\n mul(three, four),\n pow(three, four),\n pow(four, three)})\n", "language": "Octave" }, { "code": "use 5.020;\nuse feature qw<signatures>;\nno warnings qw<experimental::signatures>;\n\nuse constant zero => sub ($f) {\n sub ($x) { $x }};\n\nuse constant succ => sub ($n) {\n sub ($f) {\n sub ($x) { $f->($n->($f)($x)) }}};\n\nuse constant add => sub ($n) {\n sub ($m) {\n sub ($f) {\n sub ($x) { $m->($f)($n->($f)($x)) }}}};\n\nuse constant mult => sub ($n) {\n sub ($m) {\n sub ($f) {\n sub ($x) { $m->($n->($f))($x) }}}};\n\nuse constant power => sub ($b) {\n sub ($e) { $e->($b) }};\n\nuse constant countup => sub ($i) { $i + 1 };\nuse constant countdown => sub ($i) { $i == 0 ? zero : succ->( __SUB__->($i - 1) ) };\nuse constant to_int => sub ($f) { $f->(countup)->(0) };\nuse constant from_int => sub ($x) { countdown->($x) };\n\nuse constant three => succ->(succ->(succ->(zero)));\nuse constant four => from_int->(4);\n\nsay join ' ', map { to_int->($_) } (\n add ->( three )->( four ),\n mult ->( three )->( four ),\n power->( four )->( three ),\n power->( three )->( four ),\n);\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n\n <span style=\"color: #008080;\">type</span> <span style=\"color: #000000;\">church</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- eg {r_add,1,{a,b}}</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004080;\">sequence</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">3</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #004080;\">integer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #004080;\">integer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #004080;\">sequence</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])=</span><span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">type</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">succ</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">church</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- eg {r_add,1,{a,b}} =&gt; {r_add,2,{a,b}} aka a+b -&gt; a+b+b</span>\n <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">c</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- three normal integer-handling routines...</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">b</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">a</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">r_add</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">routine_id</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"add\"</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #000000;\">b</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">a</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">r_mul</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">routine_id</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"mul\"</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">pow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">a</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">r_pow</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">routine_id</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"pow\"</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- ...and three church constructors to match\n -- (no maths here, just pure static data)</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">addch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">church</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">church</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">r_add</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">}}</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">mulch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">church</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">church</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">r_mul</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">}}</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">powch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">church</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">church</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">r_pow</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">}}</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">tointch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">church</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- note this is where the bulk of any processing happens</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">rid</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">c</span>\n <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">church</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tointch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000080;font-style:italic;\">-- return call_func(rid,n&x)</span>\n <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">})&</span><span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">call_func</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">rid</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">church</span> <span style=\"color: #000000;\">zero</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">r_add</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}}</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">inttoch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">zero</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">succ</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inttoch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #000000;\">church</span> <span style=\"color: #000000;\">three</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">succ</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">succ</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">succ</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">zero</span><span style=\"color: #0000FF;\">))),</span>\n <span style=\"color: #000000;\">four</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">succ</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">three</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"three -&gt; %d\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tointch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">three</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"four -&gt; %d\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tointch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">four</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"three + four -&gt; %d\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tointch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">addch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">three</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">four</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"three * four -&gt; %d\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tointch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mulch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">three</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">four</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"three ^ four -&gt; %d\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tointch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">powch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">three</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">four</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"four ^ three -&gt; %d\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tointch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">powch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">four</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">three</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"5 -&gt; five -&gt; %d\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tointch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inttoch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">)))</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) {\n return function($f) use (&$n) {\n return function($x) use (&$n, &$f) {\n return $f( ($n($f))($x) );\n };\n };\n};\n\n$add = function($n, $m) {\n return function($f) use (&$n, &$m) {\n return function($x) use (&$f, &$n, &$m) {\n return ($m($f))(($n($f))($x));\n };\n };\n};\n\n$mult = function($n, $m) {\n return function($f) use (&$n, &$m) {\n return function($x) use (&$f, &$n, &$m) {\n return ($m($n($f)))($x);\n };\n };\n};\n\n$power = function($b,$e) {\n return $e($b);\n};\n\n$to_int = function($f) {\n $count_up = function($i) { return $i+1; };\n return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n $countdown = function($i) use (&$countdown) {\n global $zero, $succ;\n if ( $i == 0 ) {\n return $zero;\n } else {\n return $succ($countdown($i-1));\n };\n };\n return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t $power($three,$four), $power($four,$three)) as $ch) {\n print($to_int($ch));\n print(\"\\n\");\n}\n?>\n", "language": "PHP" }, { "code": "church_zero(z).\n\nchurch_successor(Z, c(Z)).\n\nchurch_add(z, Z, Z).\nchurch_add(c(X), Y, c(Z)) :-\n church_add(X, Y, Z).\n\nchurch_multiply(z, _, z).\nchurch_multiply(c(X), Y, R) :-\n church_add(Y, S, R),\n church_multiply(X, Y, S).\n\n% N ^ M\nchurch_power(z, z, z).\nchurch_power(N, c(z), N).\nchurch_power(N, c(c(Z)), R) :-\n church_multiply(N, R1, R),\n church_power(N, c(Z), R1).\n\nint_church(0, z).\nint_church(I, c(Z)) :-\n int_church(Is, Z),\n succ(Is, I).\n\nrun :-\n int_church(3, Three),\n church_successor(Three, Four),\n church_add(Three, Four, Sum),\n church_multiply(Three, Four, Product),\n church_power(Four, Three, Power43),\n church_power(Three, Four, Power34),\n\n int_church(ISum, Sum),\n int_church(IProduct, Product),\n int_church(IPower43, Power43),\n int_church(IPower34, Power34),\n\n !,\n maplist(format('~w '), [ISum, IProduct, IPower43, IPower34]),\n nl.\n", "language": "Prolog" }, { "code": "'''Church numerals'''\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n# ----- CHURCH ENCODINGS OF NUMERALS AND OPERATIONS ------\n\ndef churchZero():\n '''The identity function.\n No applications of any supplied f\n to its argument.\n '''\n return lambda f: identity\n\n\ndef churchSucc(cn):\n '''The successor of a given\n Church numeral. One additional\n application of f. Equivalent to\n the arithmetic addition of one.\n '''\n return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n '''The arithmetic sum of two Church numerals.'''\n return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n '''The arithmetic product of two Church numerals.'''\n return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n '''Exponentiation of Church numerals. m^n'''\n return lambda n: n(m)\n\n\ndef churchFromInt(n):\n '''The Church numeral equivalent of\n a given integer.\n '''\n return lambda f: (\n foldl\n (compose)\n (identity)\n (replicate(n)(f))\n )\n\n\n# OR, alternatively:\ndef churchFromInt_(n):\n '''The Church numeral equivalent of a given\n integer, by explicit recursion.\n '''\n if 0 == n:\n return churchZero()\n else:\n return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n '''The integer equivalent of a\n given Church numeral.\n '''\n return cn(succ)(0)\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n 'Tests'\n\n cThree = churchFromInt(3)\n cFour = churchFromInt(4)\n\n print(list(map(intFromChurch, [\n churchAdd(cThree)(cFour),\n churchMult(cThree)(cFour),\n churchExp(cFour)(cThree),\n churchExp(cThree)(cFour),\n ])))\n\n\n# ------------------ GENERIC FUNCTIONS -------------------\n\n# compose (flip (.)) :: (a -> b) -> (b -> c) -> a -> c\ndef compose(f):\n '''A left to right composition of two\n functions f and g'''\n return lambda g: lambda x: g(f(x))\n\n\n# foldl :: (a -> b -> a) -> a -> [b] -> a\ndef foldl(f):\n '''Left to right reduction of a list,\n using the binary operator f, and\n starting with an initial value a.\n '''\n def go(acc, xs):\n return reduce(lambda a, x: f(a)(x), xs, acc)\n return lambda acc: lambda xs: go(acc, xs)\n\n\n# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# replicate :: Int -> a -> [a]\ndef replicate(n):\n '''A list of length n in which every\n element has the value x.\n '''\n return lambda x: repeat(x, n)\n\n\n# succ :: Enum a => a -> a\ndef succ(x):\n '''The successor of a value.\n For numeric types, (1 +).\n '''\n return 1 + x if isinstance(x, int) else (\n chr(1 + ord(x))\n )\n\n\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": " [ this nested ] is zero ( --> cn )\n\n [ this nested join ] is succ ( cn --> cn )\n\n [ zero\n [ 2dup = if done\n succ\n rot succ unrot\n recurse ]\n 2drop ] is add ( cn cn --> cn )\n\n [ zero unrot zero\n [ 2dup = if done\n succ\n 2swap\n tuck add swap\n 2swap recurse ]\n 2drop drop ] is mul ( cn cn --> cn )\n\n [ zero succ unrot zero\n [ 2dup = if done\n succ\n 2swap\n tuck mul swap\n 2swap recurse ]\n 2drop drop ] is exp ( cn cn --> cn )\n\n [ zero swap times succ ] is n->cn ( n --> cn )\n\n [ size 1 - ] is cn->n ( cn --> n )\n\n ( - - - - - - - - - - - - - - - - - - - - - - - - )\n\n [ zero succ succ succ ] is three ( --> cn )\n\n [ three succ ] is four ( --> cn )\n\n four three add cn->n echo sp\n four three mul cn->n echo sp\n four three exp cn->n echo sp\n three four exp cn->n echo\n", "language": "Quackery" }, { "code": "zero <- function(f) {function(x) x}\nsucc <- function(n) {function(f) {function(x) f(n(f)(x))}}\nadd <- function(n) {function(m) {function(f) {function(x) m(f)(n(f)(x))}}}\nmult <- function(n) {function(m) {function(f) m(n(f))}}\nexpt <- function(n) {function(m) m(n)}\nnatToChurch <- function(n) {if(n == 0) zero else succ(natToChurch(n - 1))}\nchurchToNat <- function(n) {(n(function(x) x + 1))(0)}\n\nthree <- natToChurch(3)\nfour <- natToChurch(4)\n\nchurchToNat(add(three)(four))\nchurchToNat(mult(three)(four))\nchurchToNat(expt(three)(four))\nchurchToNat(expt(four)(three))\n", "language": "R" }, { "code": "zeroAlt <- function(x) identity\none <- function(f) f #Not actually requested by the task and only used to define Alt functions, so placed here.\noneAlt <- identity\nsuccAlt <- function(n) {function(f) {function(x) n(f)(f(x))}}\nsuccAltAlt <- add(one)\naddAlt <- function(n) n(succ)\nmultAlt <- function(n) {function(m) m(add(n))(zero)}\nexptAlt <- function(n) {function(m) m(mult(n))(one)}\n", "language": "R" }, { "code": "churchToNat(addAlt(three)(four))\nchurchToNat(multAlt(three)(four))\nchurchToNat(exptAlt(three)(four))\nchurchToNat(exptAlt(four)(three))\nchurchToNat(succ(four))\nchurchToNat(succAlt(four))\nchurchToNat(succAltAlt(four))\n", "language": "R" }, { "code": "const <- function(f) {function(d) f}\nzero <- const(identity)\none <- identity\nsucc <- function(n) {function(f) {function(x) f(n(f)(x))}}\nadd <- function(n) {function(m) {function(f) {function(x) m(f)(n(f)(x))}}}\nmult <- function(n) {function(m) {function(f) m(n(f))}}\nexpt <- function(n) {function(m) m(n)}\niszero <- function(n) n(const(zero))(one)\npred <- function(n) {function(f) {function(x)\n n(function(g) {function(h) h(g(f))})(const(x))(identity)}}\nsubt <- function(m) {function(n) n(pred)(m)}\ndivr <- function(n) {function(d)\n (function(v) v(const(succ(divr(v)(d))))(zero))(subt(n)(d))}\ndiv <- function(dvdnd) {function(dvsr) divr(succ(dvdnd))(dvsr)}\nnatToChurch <- function(n) {if(n == 0) zero else succ(natToChurch(n - 1))}\nchurchToNat <- function(n) {(n(function(x) x + 1))(0)}\n\nthree <- natToChurch(3)\nfour <- succ(three)\neleven <- natToChurch(11)\ntwelve <- succ(eleven)\n\nchurchToNat(add(three)(four))\nchurchToNat(mult(three)(four))\nchurchToNat(expt(three)(four))\nchurchToNat(expt(four)(three))\nchurchToNat(iszero(zero))\nchurchToNat(iszero(three))\nchurchToNat(pred(four))\nchurchToNat(pred(zero))\nchurchToNat(subt(eleven)(three))\nchurchToNat(div(eleven)(three))\nchurchToNat(div(twelve)(three))\n", "language": "R" }, { "code": "#lang racket\n\n(define zero (λ (f) (λ (x) x)))\n(define zero* (const identity)) ; zero renamed\n\n(define one (λ (f) f))\n(define one* identity) ; one renamed\n\n(define succ (λ (n) (λ (f) (λ (x) (f ((n f) x))))))\n(define succ* (λ (n) (λ (f) (λ (x) ((n f) (f x)))))) ; different impl\n\n(define add (λ (n) (λ (m) (λ (f) (λ (x) ((m f) ((n f) x)))))))\n(define add* (λ (n) (n succ)))\n\n(define succ** (add one))\n\n(define mult (λ (n) (λ (m) (λ (f) (m (n f))))))\n(define mult* (λ (n) (λ (m) ((m (add n)) zero))))\n\n(define expt (λ (n) (λ (m) (m n))))\n(define expt* (λ (n) (λ (m) ((m (mult n)) one))))\n\n(define (nat->church n)\n (cond\n [(zero? n) zero]\n [else (succ (nat->church (sub1 n)))]))\n\n(define (church->nat n) ((n add1) 0))\n\n(define three (nat->church 3))\n(define four (nat->church 4))\n\n(church->nat ((add three) four))\n(church->nat ((mult three) four))\n(church->nat ((expt three) four))\n(church->nat ((expt four) three))\n", "language": "Racket" }, { "code": "constant $zero = sub (Code $f) {\n sub ( $x) { $x }}\n\nconstant $succ = sub (Code $n) {\n sub (Code $f) {\n sub ( $x) { $f($n($f)($x)) }}}\n\nconstant $add = sub (Code $n) {\n sub (Code $m) {\n sub (Code $f) {\n sub ( $x) { $m($f)($n($f)($x)) }}}}\n\nconstant $mult = sub (Code $n) {\n sub (Code $m) {\n sub (Code $f) {\n sub ( $x) { $m($n($f))($x) }}}}\n\nconstant $power = sub (Code $b) {\n sub (Code $e) { $e($b) }}\n\nsub to_int (Code $f) {\n sub countup (Int $i) { $i + 1 }\n return $f(&countup).(0)\n}\n\nsub from_int (Int $x) {\n multi sub countdown ( 0) { $zero }\n multi sub countdown (Int $i) { $succ( countdown($i - 1) ) }\n return countdown($x);\n}\n\nconstant $three = $succ($succ($succ($zero)));\nconstant $four = from_int(4);\n\nsay map &to_int,\n $add( $three )( $four ),\n $mult( $three )( $four ),\n $power( $four )( $three ),\n $power( $three )( $four ),\n;\n", "language": "Raku" }, { "code": "my \\zero = -> \\f { -> \\x { x }}\nmy \\succ = -> \\n { -> \\f { -> \\x { f.(n.(f)(x)) }}}\nmy \\add = -> \\n { -> \\m { -> \\f { -> \\x { m.(f)(n.(f)(x)) }}}}\nmy \\mult = -> \\n { -> \\m { -> \\f { -> \\x { m.(n.(f))(x) }}}}\nmy \\power = -> \\b { -> \\e { e.(b) }}\n\nmy \\to_int = -> \\f { f.( -> \\i { i + 1 } ).(0) }\nmy \\from_int = -> \\i { i == 0 ?? zero !! succ.( &?BLOCK(i - 1) ) }\n\nmy \\three = succ.(succ.(succ.(zero)));\nmy \\four = from_int.(4);\n\nsay map -> \\f { to_int.(f) },\n add.( three )( four ),\n mult.( three )( four ),\n power.( four )( three ),\n power.( three )( four ),\n;\n", "language": "Raku" }, { "code": "def zero(f)\n return lambda {|x| x}\nend\nZero = lambda { |f| zero(f) }\n\ndef succ(n)\n return lambda { |f| lambda { |x| f.(n.(f).(x)) } }\nend\n\nThree = succ(succ(succ(Zero)))\n\ndef add(n, m)\n return lambda { |f| lambda { |x| m.(f).(n.(f).(x)) } }\nend\n\ndef mult(n, m)\n return lambda { |f| lambda { |x| m.(n.(f)).(x) } }\nend\n\ndef power(b, e)\n return e.(b)\nend\n\ndef int_from_couch(f)\n countup = lambda { |i| i+1 }\n f.(countup).(0)\nend\n\ndef couch_from_int(x)\n countdown = lambda { |i|\n case i\n when 0 then Zero\n else succ(countdown.(i-1))\n end\n }\n countdown.(x)\nend\n\nFour = couch_from_int(4)\n\nputs [ add(Three, Four),\n mult(Three, Four),\n power(Three, Four),\n power(Four, Three) ].map {|f| int_from_couch(f) }\n", "language": "Ruby" }, { "code": "Zero = proc { |f| proc { |x| x } }\n\nSucc = proc { |n| proc { |f| proc { |x| f[n[f][x]] } } }\n\nAdd = proc { |n, m| proc { |f| proc { |x| m[f][n[f][x]] } } }\n\nMult = proc { |n, m| proc { |f| proc { |x| m[n[f]][x] } } }\n\nPower = proc { |b, e| e[b] }\n\nToInt = proc { |f| countup = proc { |i| i+1 }; f[countup][0] }\n\nFromInt = proc { |x|\n countdown = proc { |i|\n case i\n when 0 then Zero\n else Succ[countdown[i-1]]\n end\n }\n countdown[x]\n}\n\nThree = Succ[Succ[Succ[Zero]]]\nFour = FromInt[4]\n\nputs [ Add[Three, Four],\n Mult[Three, Four],\n Power[Three, Four],\n Power[Four, Three] ].map(&ToInt)\n", "language": "Ruby" }, { "code": "use std::rc::Rc;\nuse std::ops::{Add, Mul};\n\n#[derive(Clone)]\nstruct Church<'a, T: 'a> {\n runner: Rc<dyn Fn(Rc<dyn Fn(T) -> T + 'a>) -> Rc<dyn Fn(T) -> T + 'a> + 'a>,\n}\n\nimpl<'a, T> Church<'a, T> {\n fn zero() -> Self {\n Church {\n runner: Rc::new(|_f| {\n Rc::new(|x| x)\n })\n }\n }\n\n fn succ(self) -> Self {\n Church {\n runner: Rc::new(move |f| {\n let g = self.runner.clone();\n Rc::new(move |x| f(g(f.clone())(x)))\n })\n }\n }\n\n fn run(&self, f: impl Fn(T) -> T + 'a) -> Rc<dyn Fn(T) -> T + 'a> {\n (self.runner)(Rc::new(f))\n }\n\n fn exp(self, rhs: Church<'a, Rc<dyn Fn(T) -> T + 'a>>) -> Self\n {\n Church {\n runner: (rhs.runner)(self.runner)\n }\n }\n}\n\nimpl<'a, T> Add for Church<'a, T> {\n type Output = Church<'a, T>;\n\n fn add(self, rhs: Church<'a, T>) -> Church<T> {\n Church {\n runner: Rc::new(move |f| {\n let self_runner = self.runner.clone();\n let rhs_runner = rhs.runner.clone();\n Rc::new(move |x| (self_runner)(f.clone())((rhs_runner)(f.clone())(x)))\n })\n }\n }\n}\n\nimpl<'a, T> Mul for Church<'a, T> {\n type Output = Church<'a, T>;\n\n fn mul(self, rhs: Church<'a, T>) -> Church<T> {\n Church {\n runner: Rc::new(move |f| {\n (self.runner)((rhs.runner)(f))\n })\n }\n }\n}\n\nimpl<'a, T> From<i32> for Church<'a, T> {\n fn from(n: i32) -> Church<'a, T> {\n let mut ret = Church::zero();\n for _ in 0..n {\n ret = ret.succ();\n }\n ret\n }\n}\n\nimpl<'a> From<&Church<'a, i32>> for i32 {\n fn from(c: &Church<'a, i32>) -> i32 {\n c.run(|x| x + 1)(0)\n }\n}\n\nfn three<'a, T>() -> Church<'a, T> {\n Church::zero().succ().succ().succ()\n}\n\nfn four<'a, T>() -> Church<'a, T> {\n Church::zero().succ().succ().succ().succ()\n}\n\nfn main() {\n println!(\"three =\\t{}\", i32::from(&three()));\n println!(\"four =\\t{}\", i32::from(&four()));\n\n println!(\"three + four =\\t{}\", i32::from(&(three() + four())));\n println!(\"three * four =\\t{}\", i32::from(&(three() * four())));\n\n println!(\"three ^ four =\\t{}\", i32::from(&(three().exp(four()))));\n println!(\"four ^ three =\\t{}\", i32::from(&(four().exp(three()))));\n}\n", "language": "Rust" }, { "code": "object Church {\n\n trait ChurchNum extends (ChurchNum => ChurchNum)\n\n def zero: ChurchNum = f => x => x\n\n def next(n: ChurchNum): ChurchNum = f => x => f(n(f)(x))\n\n def plus(a: ChurchNum)(b: ChurchNum): ChurchNum = f => x => b(f)(a(f)(x))\n\n def mult(a: ChurchNum)(b: ChurchNum): ChurchNum = f => x => b(a(f))(x)\n\n def pow(m: ChurchNum)(n: ChurchNum): ChurchNum = n(m)\n\n def toChurchNum(n: Int): ChurchNum = if (n <= 0) zero else next(toChurchNum(n - 1))\n\n def toInt(c: ChurchNum): Int = {\n var counter = 0\n val funCounter: ChurchNum = f => { counter += 1; f }\n plus(zero)(c)(funCounter)(x => x)\n counter\n }\n\n def main(args: Array[String]): Unit = {\n val zero = Church.zero\n val three = next(next(next(zero)))\n val four = next(next(next(next(zero))))\n\n println(s\"3+4=${toInt(plus(three)(four))}\") // prints 7\n println(s\"4+3=${toInt(plus(four)(three))}\") // prints 7\n\n println(s\"3*4=${toInt(mult(three)(four))}\") // prints 12\n println(s\"4*3=${toInt(mult(four)(three))}\") // prints 12\n\n // exponentiation. note the reversed order!\n println(s\"3^4=${toInt(pow(four)(three))}\") // prints 81\n println(s\"4^3=${toInt(pow(three)(four))}\") // prints 64\n\n println(s\" 8=${toInt(toChurchNum(8))}\") // prints 8\n }\n}\n", "language": "Scala" }, { "code": "val demo = fn () =>\nlet\n open IntInf\n\n val zero = fn f => fn x => x ;\n fun succ n = fn f => f o (n f) ; (* successor *)\n val rec church = fn 0 => zero\n | n => succ ( church (n-1) ) ; (* natural to church numeral *)\n val natural = fn churchn => churchn (fn x => x+1) (fromInt 0) ; (* church numeral to natural *)\n\n val mult = fn cn => fn cm => cn o cm ;\n val add = fn cn => fn cm => fn f => (cn f) o (cm f) ;\n val exp = fn cn => fn em => em cn;\n\n in\n\n List.app (fn i=>print( (toString i)^\"\\n\" )) ( List.map natural\n [ add (church 3) (church 4) , mult (church 3) (church 4) , exp (church 4) (church 3) , exp (church 3) (church 4) ] )\n\nend;\n", "language": "Standard-ML" }, { "code": "demo ();\n7\n12\n64\n81\n", "language": "Standard-ML" }, { "code": "func succ<A, B, C>(_ n: @escaping (@escaping (A) -> B) -> (C) -> A) -> (@escaping (A) -> B) -> (C) -> B {\n return {f in\n return {x in\n return f(n(f)(x))\n }\n }\n}\n\nfunc zero<A, B>(_ a: A) -> (B) -> B {\n return {b in\n return b\n }\n}\n\nfunc three<A>(_ f: @escaping (A) -> A) -> (A) -> A {\n return {x in\n return succ(succ(succ(zero)))(f)(x)\n }\n}\n\nfunc four<A>(_ f: @escaping (A) -> A) -> (A) -> A {\n return {x in\n return succ(succ(succ(succ(zero))))(f)(x)\n }\n}\n\nfunc add<A, B, C>(_ m: @escaping (B) -> (A) -> C) -> (@escaping (B) -> (C) -> A) -> (B) -> (C) -> C {\n return {n in\n return {f in\n return {x in\n return m(f)(n(f)(x))\n }\n }\n }\n}\n\nfunc mult<A, B, C>(_ m: @escaping (A) -> B) -> (@escaping (C) -> A) -> (C) -> B {\n return {n in\n return {f in\n return m(n(f))\n }\n }\n}\n\nfunc exp<A, B, C>(_ m: A) -> (@escaping (A) -> (B) -> (C) -> C) -> (B) -> (C) -> C {\n return {n in\n return {f in\n return {x in\n return n(m)(f)(x)\n }\n }\n }\n}\n\nfunc church<A>(_ x: Int) -> (@escaping (A) -> A) -> (A) -> A {\n guard x != 0 else { return zero }\n\n return {f in\n return {a in\n return f(church(x - 1)(f)(a))\n }\n }\n}\n\nfunc unchurch<A>(_ f: (@escaping (Int) -> Int) -> (Int) -> A) -> A {\n return f({i in\n return i + 1\n })(0)\n}\n\nlet a = unchurch(add(three)(four))\nlet b = unchurch(mult(three)(four))\n// We can even compose operations\nlet c = unchurch(exp(mult(four)(church(1)))(three))\nlet d = unchurch(exp(mult(three)(church(1)))(four))\n\nprint(a, b, c, d)\n", "language": "Swift" }, { "code": "processor ChurchZero\n templates apply&{f:}\n $ !\n end apply\nend ChurchZero\n\ndef zero: $ChurchZero;\n\nprocessor Successor\n def predecessor: $;\n templates apply&{f:}\n $ -> predecessor::apply&{f: f} -> f !\n end apply\nend Successor\n\ntemplates churchFromInt\n @: $zero;\n $ -> #\n when <=0> do $@!\n when <1..> do @: $@ -> Successor; $-1 -> #\nend churchFromInt\n\ntemplates intFromChurch\n templates add1\n $ + 1 !\n end add1\n def church: $;\n 0 -> church::apply&{f: add1} !\nend intFromChurch\n\ndef three: $zero -> Successor -> Successor -> Successor;\ndef four: 4 -> churchFromInt;\n\nprocessor Add&{to:}\n def add: $;\n templates apply&{f:}\n $ -> add::apply&{f: f} -> to::apply&{f: f} !\n end apply\nend Add\n\n$three -> Add&{to: $four} -> intFromChurch -> '$;\n' -> !OUT::write\n\nprocessor Multiply&{by:}\n def multiply: $;\n templates apply&{f:}\n $ -> multiply::apply&{f: by::apply&{f: f}} !\n end apply\nend Multiply\n\n$three -> Multiply&{by: $four} -> intFromChurch -> '$;\n' -> !OUT::write\n\nprocessor Power&{exp:}\n def base: $;\n templates apply&{f:}\n processor Wrap&{f:}\n templates function\n $ -> f !\n end function\n end Wrap\n templates compose\n def p:$;\n $Wrap&{f: base::apply&{f: p::function}} !\n end compose\n def pow: $Wrap&{f: f} -> exp::apply&{f: compose};\n $ -> pow::function !\n end apply\nend Power\n\n$three -> Power&{exp: $four} -> intFromChurch -> '$;\n' -> !OUT::write\n\n$four -> Power&{exp: $three} -> intFromChurch -> '$;\n' -> !OUT::write\n", "language": "Tailspin" }, { "code": "processor ChurchZero\n templates apply&{f:}\n $ !\n end apply\nend ChurchZero\n\ndef zero: $ChurchZero;\n\nprocessor Successor\n def predecessor: $;\n templates apply&{f:}\n $ -> predecessor::apply&{f: f} -> f !\n end apply\nend Successor\n\ntemplates churchFromInt\n @: $zero;\n $ -> #\n when <=0> do $@!\n when <1..> do @: $@ -> Successor; $-1 -> #\nend churchFromInt\n\ntemplates intFromChurch\n templates add1\n $ + 1 !\n end add1\n def church: $;\n 0 -> church::apply&{f: add1} !\nend intFromChurch\n\ndef three: $zero -> Successor -> Successor -> Successor;\ndef four: 4 -> churchFromInt;\n\ntemplates add&{to:}\n $ -> to::apply&{f: Successor} !\nend add\n\n$three -> add&{to: $four} -> intFromChurch -> '$;\n' -> !OUT::write\n\ntemplates multiply&{by:}\n def m: $;\n $zero -> by::apply&{f: add&{to: $m}} !\nend multiply\n\n$three -> multiply&{by: $four} -> intFromChurch -> '$;\n' -> !OUT::write\n\ntemplates power&{exp:}\n def base: $;\n $zero -> Successor -> exp::apply&{f: multiply&{by: $base}} !\nend power\n\n$three -> power&{exp: $four} -> intFromChurch -> '$;\n' -> !OUT::write\n\n$four -> power&{exp: $three} -> intFromChurch -> '$;\n' -> !OUT::write\n", "language": "Tailspin" }, { "code": "#lang typed/racket\n\n(define-type ChurchNat (All (x) (-> (-> x x) (-> x x))))\n\n(: zero ChurchNat)\n(define zero (λ (f) (λ (x) x)))\n\n(: one ChurchNat)\n(define one (λ (f) f))\n\n(: succ (-> ChurchNat ChurchNat))\n(: succ* (-> ChurchNat ChurchNat))\n(define succ (λ (n) (λ (f) (λ (x) (f ((n f) x))))))\n(define succ* (λ (n) (λ (f) (λ (x) ((n f) (f x)))))) ; different impl\n\n(: add (-> ChurchNat (-> ChurchNat ChurchNat)))\n(: add* (-> ChurchNat (-> ChurchNat ChurchNat)))\n(define add (λ (n) (λ (m) (λ (f) (λ (x) ((m f) ((n f) x)))))))\n(define add* (λ (n) (n succ)))\n\n(: succ** (-> ChurchNat ChurchNat))\n(define succ** (add one))\n\n(: mult (-> ChurchNat (-> ChurchNat ChurchNat)))\n(: mult* (-> ChurchNat (-> ChurchNat ChurchNat)))\n(define mult (λ (n) (λ (m) (λ (f) (m (n f))))))\n(define mult* (λ (n) (λ (m) ((m (add n)) zero))))\n\n(: expt (-> ChurchNat (-> ChurchNat ChurchNat)))\n(define expt (λ (n) (λ (m) ((m (mult n)) one))))\n\n(: nat->church (-> Natural ChurchNat))\n(define (nat->church n)\n (cond\n [(zero? n) zero]\n [else (succ (nat->church (sub1 n)))]))\n\n(: church->nat (-> ChurchNat Natural))\n(define (church->nat n) (((inst n Natural) add1) 0))\n\n(: three ChurchNat)\n(: four ChurchNat)\n(define three (nat->church 3))\n(define four (nat->church 4))\n\n(church->nat ((add three) four))\n(church->nat ((mult three) four))\n(church->nat ((expt three) four))\n(church->nat ((expt four) three))\n", "language": "Typed-Racket" }, { "code": "class Church {\n static zero { Fn.new { Fn.new { |x| x } } }\n\n static succ(c) { Fn.new { |f| Fn.new { |x| f.call(c.call(f).call(x)) } } }\n\n static add(c, d) { Fn.new { |f| Fn.new { |x| c.call(f).call(d.call(f).call(x)) } } }\n\n static mul(c, d) { Fn.new { |f| c.call(d.call(f)) } }\n\n static pow(c, e) { e.call(c) }\n\n static fromInt(n) {\n var ret = zero\n if (n > 0) for (i in 1..n) ret = succ(ret)\n return ret\n }\n\n static toInt(c) { c.call(Fn.new { |x| x + 1 }).call(0) }\n}\n\nvar three = Church.succ(Church.succ(Church.succ(Church.zero)))\nvar four = Church.succ(three)\n\nSystem.print(\"three -> %(Church.toInt(three))\")\nSystem.print(\"four -> %(Church.toInt(four))\")\nSystem.print(\"three + four -> %(Church.toInt(Church.add(three, four)))\")\nSystem.print(\"three * four -> %(Church.toInt(Church.mul(three, four)))\")\nSystem.print(\"three ^ four -> %(Church.toInt(Church.pow(three, four)))\")\nSystem.print(\"four ^ three -> %(Church.toInt(Church.pow(four, three)))\")\n", "language": "Wren" }, { "code": "class Church{ // kinda heavy, just an int + fcn churchAdd(ca,cb) would also work\n fcn init(N){ var n=N; }\t// Church Zero is Church(0)\n fcn toInt(f,x){ do(n){ x=f(x) } x } // c(3)(f,x) --> f(f(f(x)))\n fcn succ{ self(n+1) }\n fcn __opAdd(c){ self(n+c.n) }\n fcn __opMul(c){ self(n*c.n) }\n fcn pow(c) { self(n.pow(c.n)) }\n fcn toString{ String(\"Church(\",n,\")\") }\n}\n", "language": "Zkl" }, { "code": "c3,c4 := Church(3),c3.succ();\nf,x := Op(\"+\",1),0;\nprintln(\"f=\",f,\", x=\",x);\nprintln(\"%s+%s=%d\".fmt(c3,c4, (c3+c4).toInt(f,x) ));\nprintln(\"%s*%s=%d\".fmt(c3,c4, (c3*c4).toInt(f,x) ));\nprintln(\"%s^%s=%d\".fmt(c4,c3, (c4.pow(c3)).toInt(f,x) ));\nprintln(\"%s^%s=%d\".fmt(c3,c4, (c3.pow(c4)).toInt(f,x) ));\nprintln();\nT(c3+c4,c3*c4,c4.pow(c3),c3.pow(c4)).apply(\"toInt\",f,x).println();\n", "language": "Zkl" }, { "code": "fcn churchZero{ return(fcn(x){ x }) } // or fcn churchZero{ self.fcn.idFcn }\nfcn churchSucc(c){ return('wrap(f){ return('wrap(x){ f(c(f)(x)) }) }) }\nfcn churchAdd(c1,c2){ return('wrap(f){ return('wrap(x){ c1(f)(c2(f)(x)) }) }) }\nfcn churchMul(c1,c2){ return('wrap(f){ c1(c2(f)) }) }\nfcn churchPow(c1,c2){ return('wrap(f){ c2(c1)(f) }) }\nfcn churchToInt(c,f,x){ c(f)(x) }\nfcn churchFromInt(n){ c:=churchZero; do(n){ c=churchSucc(c) } c }\n//fcn churchFromInt(n){ (0).reduce(n,churchSucc,churchZero) } // what ever\n", "language": "Zkl" }, { "code": "c3,c4 := churchFromInt(3),churchSucc(c3);\nf,x := Op(\"+\",1),0;\t// x>=0, ie natural number\nT(c3,c4,churchAdd(c3,c4),churchMul(c3,c4),churchPow(c4,c3),churchPow(c3,c4))\n .apply(churchToInt,f,x).println();\n", "language": "Zkl" } ]
Church-numerals
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Circular_primes\nnote: Prime Numbers\n", "language": "00-META" }, { "code": ";Definitions\nA '''circular prime''' is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. \n\nFor example:\n'''1193''' is a circular prime, since '''1931''', '''9311''' and '''3119''' are all also prime.\n\nNote that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So '''13''' is a circular prime, but '''31''' is not. \n\n\nA '''repunit''' (denoted by R) is a number whose base 10 representation contains only the digit '''1'''.\n\nFor example:\nR(2) = 11 and R(5) = 11111 are repunits.\n\n\n;Task\n* Find the first 19 circular primes.\n\n\n* If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.\n\n\n* (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.\n\n\n;See also\n* [[wp:Circular_prime|Wikipedia article - Circular primes]].\n* [[wp:Repunit|Wikipedia article - Repunit]].\n* [[oeis:A016114|OEIS sequence A016114 - Circular primes]].\n", "language": "00-TASK" }, { "code": "BEGIN # find circular primes - primes where all cyclic permutations #\n # of the digits are also prime #\n # genertes a sieve of circular primes, only the first #\n # permutation of each prime is flagged as TRUE #\n OP CIRCULARPRIMESIEVE = ( INT n )[]BOOL:\n BEGIN\n [ 0 : n ]BOOL prime;\n prime[ 0 ] := prime[ 1 ] := FALSE;\n prime[ 2 ] := TRUE;\n FOR i FROM 3 BY 2 TO UPB prime DO prime[ i ] := TRUE OD;\n FOR i FROM 4 BY 2 TO UPB prime DO prime[ i ] := FALSE OD;\n FOR i FROM 3 BY 2 TO ENTIER sqrt( UPB prime ) DO\n IF prime[ i ] THEN\n FOR s FROM i * i BY i + i TO UPB prime DO prime[ s ] := FALSE OD\n FI\n OD;\n INT first digit multiplier := 10;\n INT max with multiplier := 99;\n # the 1 digit primes are non-curcular, so start at 10 #\n FOR i FROM 10 TO UPB prime DO\n IF i > max with multiplier THEN\n # starting a new power of ten #\n first digit multiplier *:= 10;\n max with multiplier *:= 10 +:= 9\n FI;\n IF prime[ i ] THEN\n # have a prime #\n # cycically permute the number until we get back #\n # to the original - flag all the permutations #\n # except the original as non-prime #\n INT permutation := i;\n WHILE permutation := ( permutation OVER 10 )\n + ( ( permutation MOD 10 ) * first digit multiplier )\n ;\n permutation /= i\n DO\n IF NOT prime[ permutation ] THEN\n # the permutation is not prime #\n prime[ i ] := FALSE\n ELIF permutation > i THEN\n # haven't permutated e.g. 101 to 11 #\n IF NOT prime[ permutation ] THEN\n # i is not a circular prime #\n prime[ i ] := FALSE\n FI;\n prime[ permutation ] := FALSE\n FI\n OD\n FI\n OD;\n prime\n END # CIRCULARPRIMESIEVE # ;\n # construct a sieve of circular primes up to 999 999 #\n # only the first permutation is included #\n []BOOL prime = CIRCULARPRIMESIEVE 999 999;\n # print the first 19 circular primes #\n INT c count := 0;\n print( ( \"First 19 circular primes: \" ) );\n FOR i WHILE c count < 19 DO\n IF prime[ i ] THEN\n print( ( \" \", whole( i, 0 ) ) );\n c count +:= 1\n FI\n OD;\n print( ( newline ) )\nEND\n", "language": "ALGOL-68" }, { "code": "begin % find circular primes - primes where all cyclic permutations %\n % of the digits are also prime %\n % sets p( 1 :: n ) to a sieve of primes up to n %\n procedure Eratosthenes ( logical array p( * ) ; integer value n ) ;\n begin\n p( 1 ) := false; p( 2 ) := true;\n for i := 3 step 2 until n do p( i ) := true;\n for i := 4 step 2 until n do p( i ) := false;\n for i := 3 step 2 until truncate( sqrt( n ) ) do begin\n integer ii; ii := i + i;\n if p( i ) then for pr := i * i step ii until n do p( pr ) := false\n end for_i ;\n end Eratosthenes ;\n % find circular primes in p in the range lo to hi, if they are circular, flag the %\n % permutations as non-prime so we do not consider them again %\n % non-circular primes are also flageed as non-prime %\n % lo must be a power of ten and hi must be at most ( lo * 10 ) - 1 %\n procedure keepCircular ( logical array p ( * ); integer value lo, hi ) ;\n for n := lo until hi do begin\n if p( n ) then begin\n % have a prime %\n integer c, pCount;\n logical isCircular;\n integer array permutations ( 1 :: 10 );\n c := n;\n isCircular := true;\n pCount := 0;\n % cyclically permute c until we get back to p or find a non-prime value for c %\n while begin\n integer first, rest;\n first := c div lo;\n rest := c rem lo;\n c := ( rest * 10 ) + first;\n isCircular := p( c );\n c not = n and isCircular\n end do begin\n pCount := pCount + 1;\n permutations( pCount ) := c\n end while_have_another_prime_permutation ;\n if not isCircular\n then p( n ) := false\n else begin\n % have a circular prime - flag the permutations as non-prime %\n for i := 1 until pCount do p( permutations( i ) ) := false\n end if_not_isCircular__\n end if_p_n\n end keepCircular ;\n integer cCount;\n % sieve the primes up to 999999 %\n logical array p ( 1 :: 999999 );\n Eratosthenes( p, 999999 );\n % remove non-circular primes from the sieve %\n % the single digit primes are all circular so we start at 10 %\n keepCircular( p, 10, 99 );\n keepCircular( p, 100, 999 );\n keepCircular( p, 1000, 9999 );\n keepCircular( p, 10000, 99999 );\n keepCircular( p, 100000, 200000 );\n % print the first 19 circular primes %\n cCount := 0;\n write( \"First 19 circular primes: \" );\n for i := 1 until 200000 do begin\n if p( i ) then begin\n writeon( i_w := 1, s_w := 1, i );\n cCount := cCount + 1;\n if cCount = 19 then goto end_circular\n end if_p_i\n end for_i ;\nend_circular:\nend.\n", "language": "ALGOL-W" }, { "code": "on isPrime(n)\n if (n < 4) then return (n > 1)\n if ((n mod 2 is 0) or (n mod 3 is 0)) then return false\n repeat with i from 5 to (n ^ 0.5) div 1 by 6\n if ((n mod i is 0) or (n mod (i + 2) is 0)) then return false\n end repeat\n\n return true\nend isPrime\n\non isCircularPrime(n)\n if (not isPrime(n)) then return false\n set temp to n\n set c to 0\n repeat while (temp > 9)\n set temp to temp div 10\n set c to c + 1\n end repeat\n set p to (10 ^ c) as integer\n set temp to n\n repeat c times\n set temp to temp mod p * 10 + temp div p\n if ((temp < n) or (not isPrime(temp))) then return false\n end repeat\n return true\nend isCircularPrime\n\n-- Return the first c circular primes.\n-- Takes 2 as read and checks only odd numbers thereafter.\non circularPrimes(c)\n if (c < 1) then return {}\n set output to {2}\n set n to 3\n set counter to 1\n repeat until (counter = c)\n if (isCircularPrime(n)) then\n set end of output to n\n set counter to counter + 1\n end if\n set n to n + 2\n end repeat\n return output\nend circularPrimes\n\nreturn circularPrimes(19)\n", "language": "AppleScript" }, { "code": "{2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933}\n", "language": "AppleScript" }, { "code": "perms: function [n][\n str: repeat to :string n 2\n result: new []\n lim: dec size digits n\n loop 0..lim 'd ->\n 'result ++ slice str d lim+d\n\n return to [:integer] result\n]\n\ncirculars: new []\n\ncircular?: function [x][\n if not? prime? x -> return false\n\n loop perms x 'y [\n if not? prime? y -> return false\n if contains? circulars y -> return false\n ]\n\n 'circulars ++ x\n\n return true\n]\n\ni: 2\nfound: 0\nwhile [found < 19][\n if circular? i [\n print i\n found: found + 1\n ]\n i: i + 1\n]\n", "language": "Arturo" }, { "code": "# syntax: GAWK -f CIRCULAR_PRIMES.AWK\nBEGIN {\n p = 2\n printf(\"first 19 circular primes:\")\n for (count=0; count<19; p++) {\n if (is_circular_prime(p)) {\n printf(\" %d\",p)\n count++\n }\n }\n printf(\"\\n\")\n exit(0)\n}\nfunction cycle(n, m,p) { # E.G. if n = 1234 returns 2341\n m = n\n p = 1\n while (m >= 10) {\n p *= 10\n m /= 10\n }\n return int(m+10*(n%p))\n}\nfunction is_circular_prime(p, p2) {\n if (!is_prime(p)) {\n return(0)\n }\n p2 = cycle(p)\n while (p2 != p) {\n if (p2 < p || !is_prime(p2)) {\n return(0)\n }\n p2 = cycle(p2)\n }\n return(1)\n}\nfunction is_prime(x, i) {\n if (x <= 1) {\n return(0)\n }\n for (i=2; i<=int(sqrt(x)); i++) {\n if (x % i == 0) {\n return(0)\n }\n }\n return(1)\n}\n", "language": "AWK" }, { "code": "p = 2\ndp = 1\ncont = 0\nprint(\"Primeros 19 primos circulares:\")\nwhile cont < 19\n\tif isCircularPrime(p) then print p;\" \"; : cont += 1\n\tp += dp\n\tdp = 2\nend while\nend\n\nfunction isPrime(v)\n\tif v < 2 then return False\n\tif v mod 2 = 0 then return v = 2\n\tif v mod 3 = 0 then return v = 3\n\td = 5\n\twhile d * d <= v\n\t\tif v mod d = 0 then return False else d += 2\n\tend while\n\treturn True\nend function\n\nfunction isCircularPrime(p)\n\tn = floor(log(p)/log(10))\n\tm = 10^n\n\tq = p\n\tfor i = 0 to n\n\t\tif (q < p or not isPrime(q)) then return false\n\t\tq = (q mod m) * 10 + floor(q / m)\n\tnext i\n\treturn true\nend function\n", "language": "BASIC256" }, { "code": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gmp.h>\n\nbool is_prime(uint32_t n) {\n if (n == 2)\n return true;\n if (n < 2 || n % 2 == 0)\n return false;\n for (uint32_t p = 3; p * p <= n; p += 2) {\n if (n % p == 0)\n return false;\n }\n return true;\n}\n\n// e.g. returns 2341 if n = 1234\nuint32_t cycle(uint32_t n) {\n uint32_t m = n, p = 1;\n while (m >= 10) {\n p *= 10;\n m /= 10;\n }\n return m + 10 * (n % p);\n}\n\nbool is_circular_prime(uint32_t p) {\n if (!is_prime(p))\n return false;\n uint32_t p2 = cycle(p);\n while (p2 != p) {\n if (p2 < p || !is_prime(p2))\n return false;\n p2 = cycle(p2);\n }\n return true;\n}\n\nvoid test_repunit(uint32_t digits) {\n char* str = malloc(digits + 1);\n if (str == 0) {\n fprintf(stderr, \"Out of memory\\n\");\n exit(1);\n }\n memset(str, '1', digits);\n str[digits] = 0;\n mpz_t bignum;\n mpz_init_set_str(bignum, str, 10);\n free(str);\n if (mpz_probab_prime_p(bignum, 10))\n printf(\"R(%u) is probably prime.\\n\", digits);\n else\n printf(\"R(%u) is not prime.\\n\", digits);\n mpz_clear(bignum);\n}\n\nint main() {\n uint32_t p = 2;\n printf(\"First 19 circular primes:\\n\");\n for (int count = 0; count < 19; ++p) {\n if (is_circular_prime(p)) {\n if (count > 0)\n printf(\", \");\n printf(\"%u\", p);\n ++count;\n }\n }\n printf(\"\\n\");\n printf(\"Next 4 circular primes:\\n\");\n uint32_t repunit = 1, digits = 1;\n for (; repunit < p; ++digits)\n repunit = 10 * repunit + 1;\n mpz_t bignum;\n mpz_init_set_ui(bignum, repunit);\n for (int count = 0; count < 4; ) {\n if (mpz_probab_prime_p(bignum, 15)) {\n if (count > 0)\n printf(\", \");\n printf(\"R(%u)\", digits);\n ++count;\n }\n ++digits;\n mpz_mul_ui(bignum, bignum, 10);\n mpz_add_ui(bignum, bignum, 1);\n }\n mpz_clear(bignum);\n printf(\"\\n\");\n test_repunit(5003);\n test_repunit(9887);\n test_repunit(15073);\n test_repunit(25031);\n test_repunit(35317);\n test_repunit(49081);\n return 0;\n}\n", "language": "C" }, { "code": "#include <cstdint>\n#include <algorithm>\n#include <iostream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_prime(const integer& n, int reps = 50) {\n return mpz_probab_prime_p(n.get_mpz_t(), reps);\n}\n\nbool is_circular_prime(const integer& p) {\n if (!is_prime(p))\n return false;\n std::string str = p.get_str();\n for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {\n std::rotate(str.begin(), str.begin() + 1, str.end());\n integer p2(str, 10);\n if (p2 < p || !is_prime(p2))\n return false;\n }\n return true;\n}\n\ninteger next_repunit(const integer& n) {\n integer p = 1;\n while (p < n)\n p = 10 * p + 1;\n return p;\n}\n\ninteger repunit(int digits) {\n std::string str(digits, '1');\n integer p(str);\n return p;\n}\n\nvoid test_repunit(int digits) {\n if (is_prime(repunit(digits), 10))\n std::cout << \"R(\" << digits << \") is probably prime\\n\";\n else\n std::cout << \"R(\" << digits << \") is not prime\\n\";\n}\n\nint main() {\n integer p = 2;\n std::cout << \"First 19 circular primes:\\n\";\n for (int count = 0; count < 19; ++p) {\n if (is_circular_prime(p)) {\n if (count > 0)\n std::cout << \", \";\n std::cout << p;\n ++count;\n }\n }\n std::cout << '\\n';\n std::cout << \"Next 4 circular primes:\\n\";\n p = next_repunit(p);\n std::string str = p.get_str();\n int digits = str.size();\n for (int count = 0; count < 4; ) {\n if (is_prime(p, 15)) {\n if (count > 0)\n std::cout << \", \";\n std::cout << \"R(\" << digits << \")\";\n ++count;\n }\n p = repunit(++digits);\n }\n std::cout << '\\n';\n test_repunit(5003);\n test_repunit(9887);\n test_repunit(15073);\n test_repunit(25031);\n test_repunit(35317);\n test_repunit(49081);\n return 0;\n}\n", "language": "C++" }, { "code": "import std.bigint;\nimport std.stdio;\n\nimmutable PRIMES = [\n 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,\n 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,\n 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,\n 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599,\n 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,\n 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797,\n 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887,\n 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997\n];\n\nbool isPrime(BigInt n) {\n if (n < 2) {\n return false;\n }\n\n foreach (p; PRIMES) {\n if (n == p) {\n return true;\n }\n if (n % p == 0) {\n return false;\n }\n if (p * p > n) {\n return true;\n }\n }\n\n for (auto m = BigInt(PRIMES[$ - 1]); m * m <= n ; m += 2) {\n if (n % m == 0) {\n return false;\n }\n }\n\n return true;\n}\n\n// e.g. returns 2341 if n = 1234\nBigInt cycle(BigInt n) {\n BigInt m = n;\n BigInt p = 1;\n while (m >= 10) {\n p *= 10;\n m /= 10;\n }\n return m + 10 * (n % p);\n}\n\nbool isCircularPrime(BigInt p) {\n if (!isPrime(p)) {\n return false;\n }\n for (auto p2 = cycle(p); p2 != p; p2 = cycle(p2)) {\n if (p2 < p || !isPrime(p2)) {\n return false;\n }\n }\n return true;\n}\n\nBigInt repUnit(int len) {\n BigInt n = 0;\n while (len > 0) {\n n = 10 * n + 1;\n len--;\n }\n return n;\n}\n\nvoid main() {\n writeln(\"First 19 circular primes:\");\n int count = 0;\n foreach (p; PRIMES) {\n if (isCircularPrime(BigInt(p))) {\n if (count > 0) {\n write(\", \");\n }\n write(p);\n count++;\n }\n }\n for (auto p = BigInt(PRIMES[$ - 1]) + 2; count < 19; p += 2) {\n if (isCircularPrime(BigInt(p))) {\n if (count > 0) {\n write(\", \");\n }\n write(p);\n count++;\n }\n }\n writeln;\n}\n", "language": "D" }, { "code": "procedure ShowCircularPrimes(Memo: TMemo);\n{Show list of the first 19, cicular primes}\nvar I,Cnt: integer;\nvar S: string;\n\n\n\n\tprocedure RotateStr(var S: string);\n\t{Rotate characters in string}\n\tvar I: integer;\n\tvar C: char;\n\tbegin\n\tC:=S[Length(S)];\n\tfor I:=Length(S)-1 downto 1 do S[I+1]:=S[I];\n\tS[1]:=C;\n\tend;\n\n\n\tfunction IsCircularPrime(N: integer): boolean;\n\t{Test if all rotations of number are prime and}\n\t{A rotation of the number hasn't been used before}\n\tvar I,P: integer;\n\tvar NS: string;\n\tbegin\n\tResult:=False;\n\tNS:=IntToStr(N);\n\tfor I:=1 to Length(NS)-1 do\n\t\tbegin\n\t\t{Rotate string and convert to integer}\n\t\tRotateStr(NS);\n\t\tP:=StrToInt(NS);\n\t\t{Exit if number is not prime or}\n\t\t{Is prime, is less than N i.e. we've seen it before}\n\t\tif not IsPrime(P) or (P<N) then exit;\n\t\tend;\n\tResult:=True;\n\tend;\n\nbegin\nS:='';\nCnt:=0;\n{Look for circular primes and display 1st 19}\nfor I:=0 to High(I) do\n if IsPrime(I) then\n if IsCircularPrime(I) then\n \tbegin\n\tInc(Cnt);\n\tS:=S+Format('%7D',[I]);\n\tif Cnt>=19 then break;\n\tIf (Cnt mod 5)=0 then S:=S+CRLF;\n\tend;\nMemo.Lines.Add(S);\nMemo.Lines.Add('Count = '+IntToStr(Cnt));\nend;\n", "language": "Delphi" }, { "code": "fastfunc prime n .\n if n mod 2 = 0 and n > 2\n return 0\n .\n i = 3\n sq = sqrt n\n while i <= sq\n if n mod i = 0\n return 0\n .\n i += 2\n .\n return 1\n.\nfunc cycle n .\n m = n\n p = 1\n while m >= 10\n p *= 10\n m = m div 10\n .\n return m + n mod p * 10\n.\nfunc circprime p .\n if prime p = 0\n return 0\n .\n p2 = cycle p\n while p2 <> p\n if p2 < p or prime p2 = 0\n return 0\n .\n p2 = cycle p2\n .\n return 1\n.\np = 2\nwhile count < 19\n if circprime p = 1\n print p\n count += 1\n .\n p += 1\n.\n", "language": "EasyLang" }, { "code": "// Circular primes - Nigel Galloway: September 13th., 2021\nlet fG n g=let rec fG y=if y=g then true else if y>g && isPrime y then fG(10*(y%n)+y/n) else false in fG(10*(g%n)+g/n)\nlet rec fN g l=seq{let g=[for n in g do for g in [1;3;7;9] do let g=n*10+g in yield g] in yield! g|>List.filter(fun n->isPrime n && fG l n); yield! fN g (l*10)}\nlet circP()=seq{yield! [2;3;5;7]; yield! fN [1;3;7;9] 10}\ncircP()|> Seq.take 19 |>Seq.iter(printf \"%d \"); printfn \"\"\nprintf \"The first 5 repunit primes are \"; rUnitP(10)|>Seq.take 5|>Seq.iter(fun n->printf $\"R(%d{n}) \"); printfn \"\"\n", "language": "F-Sharp" }, { "code": "USING: combinators.short-circuit formatting io kernel lists\nlists.lazy math math.combinatorics math.functions math.parser\nmath.primes sequences sequences.extras ;\n\n! Create an ordered infinite lazy list of circular prime\n! \"candidates\" -- the numbers 2, 3, 5 followed by numbers\n! composed of only the digits 1, 3, 7, and 9.\n\n: candidates ( -- list )\n L{ \"2\" \"3\" \"5\" \"7\" } 2 lfrom\n [ \"1379\" swap selections >list ] lmap-lazy lconcat lappend ;\n\n: circular-prime? ( str -- ? )\n all-rotations {\n [ [ infimum ] [ first = ] bi ]\n [ [ string>number prime? ] all? ]\n } 1&& ;\n\n: circular-primes ( -- list )\n candidates [ circular-prime? ] lfilter ;\n\n: prime-repunits ( -- list )\n 7 lfrom [ 10^ 1 - 9 / prime? ] lfilter ;\n\n\"The first 19 circular primes are:\" print\n19 circular-primes ltake [ write bl ] leach nl nl\n\n\"The next 4 circular primes, in repunit format, are:\" print\n4 prime-repunits ltake [ \"R(%d) \" printf ] leach nl\n", "language": "Factor" }, { "code": "create 235-wheel 6 c, 4 c, 2 c, 4 c, 2 c, 4 c, 6 c, 2 c,\n does> swap 7 and + c@ ;\n\n0 1 2constant init-235 \\ roll 235 wheel at position 1\n: next-235 over 235-wheel + swap 1+ swap ;\n\n\\ check that n is prime excepting multiples of 2, 3, 5.\n: sq dup * ;\n: wheel-prime? ( n -- f )\n >r init-235 begin\n next-235\n dup sq r@ > if rdrop 2drop true exit then\n r@ over mod 0= if rdrop 2drop false exit then\n again ;\n\n: prime? ( n -- f )\n dup 2 < if drop false exit then\n dup 2 mod 0= if 2 = exit then\n dup 3 mod 0= if 3 = exit then\n dup 5 mod 0= if 5 = exit then\n wheel-prime? ;\n\n: log10^ ( n -- 10^[log n], log n )\n dup 0<= abort\" log10^: argument error.\"\n 1 0 rot\n begin dup 9 > while\n >r swap 10 * swap 1+ r> 10 /\n repeat drop ;\n\n: log10 ( n -- n ) log10^ nip ;\n\n: rotate ( n -- n )\n dup log10^ drop /mod swap 10 * + ;\n\n: prime-rotation? ( p0 p -- f )\n tuck <= swap prime? and ;\n\n: circular? ( n -- f ) \\ assume n is not a multiple of 2, 3, 5\n dup wheel-prime? invert\n if drop false exit\n then dup >r true\n over log10 0 ?do\n swap rotate j over prime-rotation? rot and\n loop nip rdrop ;\n\n: .primes\n 2 . 3 . 5 .\n 16 init-235 \\ -- count, [n1 n2] as 2,3,5 wheel\n begin\n next-235 dup circular?\n if dup . rot 1- -rot\n then\n third 0= until 2drop drop ;\n\n.\" The first 19 circular primes are:\" cr .primes cr\nbye\n", "language": "Forth" }, { "code": "program CircularPrimes;\n//nearly the way it is done:\n//http://www.worldofnumbers.com/circular.htm\n//base 4 counter to create numbers with first digit is the samallest used.\n//check if numbers are tested before and reduce gmp-calls by checking with prime 3,7\n\n{$IFDEF FPC}\n {$MODE DELPHI}{$OPTIMIZATION ON,ALL}\n uses\n Sysutils,gmp;\n{$ENDIF}\n{$IFDEF Delphi}\n uses\n System.Sysutils,?gmp?;\n{$ENDIF}\n\n{$IFDEF WINDOWS}\n {$APPTYPE CONSOLE}\n{$ENDIF}\nconst\n MAXCNTOFDIGITS = 14;\n MAXDGTVAL = 3;\n conv : array[0..MAXDGTVAL+1] of byte = (9,7,3,1,0);\ntype\n tDigits = array[0..23] of byte;\n tUint64 = NativeUint;\nvar\n mpz : mpz_t;\n digits,\n revDigits : tDigits;\n CheckNum : array[0..19] of tUint64;\n Found : array[0..23] of tUint64;\n Pot_ten,Count,CountNumCyc,CountNumPrmTst : tUint64;\n\nprocedure CheckOne(MaxIdx:integer);\nvar\n Num : Uint64;\n i : integer;\nbegin\n i:= MaxIdx;\n repeat\n inc(CountNumPrmTst);\n num := CheckNum[i];\n mpz_set_ui(mpz,Num);\n If mpz_probab_prime_p(mpz,3)=0then\n EXIT;\n dec(i);\n until i < 0;\n Found[Count] := CheckNum[0];\n inc(count);\nend;\n\nfunction CycleNum(MaxIdx:integer):Boolean;\n//first create circular numbers to minimize prime checks\nvar\n cycNum,First,P10 : tUint64;\n i,j,cv : integer;\nBegin\n i:= MaxIdx;\n j := 0;\n First := 0;\n repeat\n cv := conv[digits[i]];\n dec(i);\n First := First*10+cv;\n revDigits[j]:= cv;\n inc(j);\n until i < 0;\n // if num is divisible by 3 then cycle numbers also divisible by 3 same sum of digits\n IF First MOD 3 = 0 then\n EXIT(false);\n If First mod 7 = 0 then\n EXIT(false);\n\n //if one of the cycled number must have been tested before break\n P10 := Pot_ten;\n i := 0;\n j := 0;\n CheckNum[j] := First;\n cycNum := First;\n repeat\n inc(CountNumCyc);\n cv := revDigits[i];\n inc(j);\n cycNum := (cycNum - cv*P10)*10+cv;\n //num was checked before\n if cycNum < First then\n EXIT(false);\n if cycNum mod 7 = 0 then\n EXIT(false);\n CheckNum[j] := cycNum;\n inc(i);\n until i >= MaxIdx;\n EXIT(true);\nend;\n\nvar\n T0: Int64;\n\n idx,MaxIDx,dgt,MinDgt : NativeInt;\nbegin\n T0 := GetTickCount64;\n mpz_init(mpz);\n\n fillchar(digits,Sizeof(digits),chr(MAXDGTVAL));\n Count :=0;\n For maxIdx := 2 to 10 do\n if maxidx in[2,3,5,7] then\n begin\n Found[Count]:= maxIdx;\n inc(count);\n end;\n\n Pot_ten := 10;\n maxIdx := 1;\n idx := 0;\n MinDgt := MAXDGTVAL;\n repeat\n if CycleNum(MaxIdx) then\n CheckOne(MaxIdx);\n idx := 0;\n repeat\n dgt := digits[idx]-1;\n if dgt >=0 then\n break;\n digits[idx] := MinDgt;\n inc(idx);\n until idx >MAXCNTOFDIGITS-1;\n\n if idx > MAXCNTOFDIGITS-1 then\n BREAK;\n\n if idx<=MaxIDX then\n begin\n digits[idx] := dgt;\n //change all to leading digit\n if idx=MaxIDX then\n Begin\n For MinDgt := 0 to idx do\n digits[MinDgt]:= dgt;\n minDgt := dgt;\n end;\n end\n else\n begin\n minDgt := MAXDGTVAL;\n For maxidx := 0 to idx do\n digits[MaxIdx] := MAXDGTVAL;\n Maxidx := idx;\n Pot_ten := Pot_ten*10;\n writeln(idx:7,count:7,CountNumCyc:16,CountNumPrmTst:12,GetTickCount64-T0:8);\n end;\n until false;\n writeln(idx:7,count:7,CountNumCyc:16,CountNumPrmTst:12,GetTickCount64-T0:8);\n T0 := GetTickCount64-T0;\n\n For idx := 0 to count-2 do\n write(Found[idx],',');\n writeln(Found[count-1]);\n\n writeln('It took ',T0,' ms ','to check ',MAXCNTOFDIGITS,' decimals');\n mpz_clear(mpz);\n {$IFDEF WINDOWS}\n readln;\n {$ENDIF}\nend.\n", "language": "Free-Pascal-Lazarus" }, { "code": "#define floor(x) ((x*2.0-0.5) Shr 1)\n\nFunction isPrime(Byval p As Integer) As Boolean\n If p < 2 Then Return False\n If p Mod 2 = 0 Then Return p = 2\n If p Mod 3 = 0 Then Return p = 3\n Dim As Integer d = 5\n While d * d <= p\n If p Mod d = 0 Then Return False Else d += 2\n If p Mod d = 0 Then Return False Else d += 4\n Wend\n Return True\nEnd Function\n\nFunction isCircularPrime(Byval p As Integer) As Boolean\n Dim As Integer n = floor(Log(p)/Log(10))\n Dim As Integer m = 10^n, q = p\n For i As Integer = 0 To n\n If (q < p Or Not isPrime(q)) Then Return false\n q = (q Mod m) * 10 + floor(q / m)\n Next i\n Return true\nEnd Function\n\nDim As Integer p = 2, dp = 1, cont = 0\nPrint(\"Primeros 19 primos circulares:\")\nWhile cont < 19\n If isCircularPrime(p) Then Print p;\" \"; : cont += 1\n p += dp: dp = 2\nWend\nSleep\n", "language": "FreeBASIC" }, { "code": "begin globals\n_last1 = 7\nCFTimeInterval t\nbyte n(_last1 +1) //array of digits\nuint64 list(20), p10 = 1\nshort count, digits, first1 = _last1\nn(_last1) = 2 //First number to check\nend globals\n\nlocal fn convertToNumber as uint64\n short i = first1\n uint64 nr = n(i)\n while i < _last1\n i++ : nr = nr * 10 + n(i)\n wend\nend fn = nr\n\nvoid local fn increment( dgt as short )\n select n(dgt)\n case 1, 7, 5 : n(dgt) += 2\n case 3 : if digits then n(dgt) = 7 else n(dgt) = 5\n case 9 : n(dgt) = 1\n if dgt == first1 then first1-- : digits++ : p10 *= 10\n fn increment( dgt -1 )\n case else : n(dgt)++\n end select\nend fn\n\nlocal fn isPrime( v as uint64 ) as bool\n if v < 4 then exit fn = yes\n if v mod 3 == 0 then exit fn = no\n uint64 f = 5\n while f*f <= v\n if v mod f == 0 then exit fn = no\n f += 2\n if v mod f == 0 then exit fn = no\n f += 4\n wend\nend fn = yes\n\nvoid local fn circularPrimes\n uint64 num, nr\n short r\n while ( count < 19 )\n num = fn convertToNumber\n if fn isPrime( num )\n nr = num\n for r = 1 to digits\n nr = 10 * ( nr mod p10 ) + ( nr / p10 ) //Rotate\n if nr < num then break //Rotation of lower number\n if fn isPrime( nr ) == no then break //Not prime\n next\n if r > digits then list( count ) = num : count++\n end if\n fn increment( _last1 )\n wend\nend fn\n\nwindow 1, @\"Circular Primes in FutureBasic\", (0, 0, 280, 320)\nt = fn CACurrentMediaTime\nfn circularPrimes\nt = fn CACurrentMediaTime - t\nfor count = 0 to 18\n printf @\"%22u\",list(count)\nnext\nprintf @\"\\n Compute time: %.3f ms\", t * 1000\nhandleevents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport (\n \"fmt\"\n big \"github.com/ncw/gmp\"\n \"strings\"\n)\n\n// OK for 'small' numbers.\nfunc isPrime(n int) bool {\n switch {\n case n < 2:\n return false\n case n%2 == 0:\n return n == 2\n case n%3 == 0:\n return n == 3\n default:\n d := 5\n for d*d <= n {\n if n%d == 0 {\n return false\n }\n d += 2\n if n%d == 0 {\n return false\n }\n d += 4\n }\n return true\n }\n}\n\nfunc repunit(n int) *big.Int {\n ones := strings.Repeat(\"1\", n)\n b, _ := new(big.Int).SetString(ones, 10)\n return b\n}\n\nvar circs = []int{}\n\n// binary search is overkill for a small number of elements\nfunc alreadyFound(n int) bool {\n for _, i := range circs {\n if i == n {\n return true\n }\n }\n return false\n}\n\nfunc isCircular(n int) bool {\n nn := n\n pow := 1 // will eventually contain 10 ^ d where d is number of digits in n\n for nn > 0 {\n pow *= 10\n nn /= 10\n }\n nn = n\n for {\n nn *= 10\n f := nn / pow // first digit\n nn += f * (1 - pow)\n if alreadyFound(nn) {\n return false\n }\n if nn == n {\n break\n }\n if !isPrime(nn) {\n return false\n }\n }\n return true\n}\n\nfunc main() {\n fmt.Println(\"The first 19 circular primes are:\")\n digits := [4]int{1, 3, 7, 9}\n q := []int{1, 2, 3, 5, 7, 9} // queue the numbers to be examined\n fq := []int{1, 2, 3, 5, 7, 9} // also queue the corresponding first digits\n count := 0\n for {\n f := q[0] // peek first element\n fd := fq[0] // peek first digit\n if isPrime(f) && isCircular(f) {\n circs = append(circs, f)\n count++\n if count == 19 {\n break\n }\n }\n copy(q, q[1:]) // pop first element\n q = q[:len(q)-1] // reduce length by 1\n copy(fq, fq[1:]) // ditto for first digit queue\n fq = fq[:len(fq)-1]\n if f == 2 || f == 5 { // if digits > 1 can't contain a 2 or 5\n continue\n }\n // add numbers with one more digit to queue\n // only numbers whose last digit >= first digit need be added\n for _, d := range digits {\n if d >= fd {\n q = append(q, f*10+d)\n fq = append(fq, fd)\n }\n }\n }\n fmt.Println(circs)\n fmt.Println(\"\\nThe next 4 circular primes, in repunit format, are:\")\n count = 0\n var rus []string\n for i := 7; count < 4; i++ {\n if repunit(i).ProbablyPrime(10) {\n count++\n rus = append(rus, fmt.Sprintf(\"R(%d)\", i))\n }\n }\n fmt.Println(rus)\n fmt.Println(\"\\nThe following repunits are probably circular primes:\")\n for _, i := range []int{5003, 9887, 15073, 25031, 35317, 49081} {\n fmt.Printf(\"R(%-5d) : %t\\n\", i, repunit(i).ProbablyPrime(10))\n }\n}\n", "language": "Go" }, { "code": "import Math.NumberTheory.Primes (Prime, unPrime, nextPrime)\nimport Math.NumberTheory.Primes.Testing (isPrime, millerRabinV)\nimport Text.Printf (printf)\n\nrotated :: [Integer] -> [Integer]\nrotated xs\n | any (< head xs) xs = []\n | otherwise = map asNum $ take (pred $ length xs) $ rotate xs\n where\n rotate [] = []\n rotate (d:ds) = ds <> [d] : rotate (ds <> [d])\n\nasNum :: [Integer] -> Integer\nasNum [] = 0\nasNum n@(d:ds)\n | all (==1) n = read $ concatMap show n\n | otherwise = (d * (10 ^ length ds)) + asNum ds\n\ndigits :: Integer -> [Integer]\ndigits 0 = []\ndigits n = digits d <> [r]\n where (d, r) = n `quotRem` 10\n\nisCircular :: Bool -> Integer -> Bool\nisCircular repunit n\n | repunit = millerRabinV 0 n\n | n < 10 = True\n | even n = False\n | null rotations = False\n | any (<n) rotations = False\n | otherwise = all isPrime rotations\n where\n rotations = rotated $ digits n\n\nrepunits :: [Integer]\nrepunits = go 2\n where go n = asNum (replicate n 1) : go (succ n)\n\nasRepunit :: Int -> Integer\nasRepunit n = asNum $ replicate n 1\n\nmain :: IO ()\nmain = do\n printf \"The first 19 circular primes are:\\n%s\\n\\n\" $ circular primes\n printf \"The next 4 circular primes, in repunit format are:\\n\"\n mapM_ (printf \"R(%d) \") $ reps repunits\n printf \"\\n\\nThe following repunits are probably circular primes:\\n\"\n mapM_ (uncurry (printf \"R(%d) : %s\\n\") . checkReps) [5003, 9887, 15073, 25031, 35317, 49081]\n where\n primes = map unPrime [nextPrime 1..]\n circular = show . take 19 . filter (isCircular False)\n reps = map (sum . digits). tail . take 5 . filter (isCircular True)\n checkReps = (,) <$> id <*> show . isCircular True . asRepunit\n", "language": "Haskell" }, { "code": "R=: 10x #. #&1\nassert 11111111111111111111111111111111x -: R 32\n\nFilter=: (#~`)(`:6)\n\nrotations=: (|.\"0 1~ i.@#)&.(10&#.inv)\nassert 123 231 312 -: rotations 123\n\nprimes_less_than=: i.&.:(p:inv)\nassert 2 3 5 7 11 -: primes_less_than 12\n\n\nNB. circular y --> y is the order of magnitude.\ncircular=: monad define\n P25=: ([: -. (0 e. 1 3 7 9 e.~ 10 #.inv ])&>)Filter primes_less_than 10^y NB. Q25 are primes with 1 3 7 9 digits\n P=: 2 5 , P25\n en=: # P\n group=: en # 0\n next=: 1\n for_i. i. # group do.\n if. 0 = i { group do. NB. if untested\n j =: P i. rotations i { P NB. j are the indexes of the rotated numbers in the list of primes\n if. en e. j do. NB. if any are unfound\n j=: j -. en NB. prepare to mark them all as searched, and failed.\n g=: _1\n else.\n g=: next NB. mark the set as found in a new group. Because we can.\n next=: >: next\n end.\n group=: g j} group NB. apply the tested mark\n end.\n end.\n group </. P\n)\n", "language": "J" }, { "code": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class CircularPrimes {\n public static void main(String[] args) {\n System.out.println(\"First 19 circular primes:\");\n int p = 2;\n for (int count = 0; count < 19; ++p) {\n if (isCircularPrime(p)) {\n if (count > 0)\n System.out.print(\", \");\n System.out.print(p);\n ++count;\n }\n }\n System.out.println();\n System.out.println(\"Next 4 circular primes:\");\n int repunit = 1, digits = 1;\n for (; repunit < p; ++digits)\n repunit = 10 * repunit + 1;\n BigInteger bignum = BigInteger.valueOf(repunit);\n for (int count = 0; count < 4; ) {\n if (bignum.isProbablePrime(15)) {\n if (count > 0)\n System.out.print(\", \");\n System.out.printf(\"R(%d)\", digits);\n ++count;\n }\n ++digits;\n bignum = bignum.multiply(BigInteger.TEN);\n bignum = bignum.add(BigInteger.ONE);\n }\n System.out.println();\n testRepunit(5003);\n testRepunit(9887);\n testRepunit(15073);\n testRepunit(25031);\n }\n\n private static boolean isPrime(int n) {\n if (n < 2)\n return false;\n if (n % 2 == 0)\n return n == 2;\n if (n % 3 == 0)\n return n == 3;\n for (int p = 5; p * p <= n; p += 4) {\n if (n % p == 0)\n return false;\n p += 2;\n if (n % p == 0)\n return false;\n }\n return true;\n }\n\n private static int cycle(int n) {\n int m = n, p = 1;\n while (m >= 10) {\n p *= 10;\n m /= 10;\n }\n return m + 10 * (n % p);\n }\n\n private static boolean isCircularPrime(int p) {\n if (!isPrime(p))\n return false;\n int p2 = cycle(p);\n while (p2 != p) {\n if (p2 < p || !isPrime(p2))\n return false;\n p2 = cycle(p2);\n }\n return true;\n }\n\n private static void testRepunit(int digits) {\n BigInteger repunit = repunit(digits);\n if (repunit.isProbablePrime(15))\n System.out.printf(\"R(%d) is probably prime.\\n\", digits);\n else\n System.out.printf(\"R(%d) is not prime.\\n\", digits);\n }\n\n private static BigInteger repunit(int digits) {\n char[] ch = new char[digits];\n Arrays.fill(ch, '1');\n return new BigInteger(new String(ch));\n }\n}\n", "language": "Java" }, { "code": "def is_circular_prime:\n def circle: range(0;length) as $i | .[$i:] + .[:$i];\n tostring as $s\n | [$s|circle|tonumber] as $c\n | . == ($c|min) and all($c|unique[]; is_prime);\n\ndef circular_primes:\n 2, (range(3; infinite; 2) | select(is_circular_prime));\n\n# Probably only useful with unbounded-precision integer arithmetic:\ndef repunits:\n 1 | recurse(10*. + 1);\n", "language": "Jq" }, { "code": "limit(19; circular_primes)\n", "language": "Jq" }, { "code": "last(limit(19; circular_primes)) as $max\n| limit(4; repunits | select(. > $max and is_prime))\n| \"R(\\(tostring|length))\"\n", "language": "Jq" }, { "code": "using Lazy, Primes\n\nfunction iscircularprime(n)\n !isprime(n) && return false\n dig = digits(n)\n return all(i -> (m = evalpoly(10, circshift(dig, i))) >= n && isprime(m), 1:length(dig)-1)\nend\n\nfiltcircular(n, rang) = Int.(collect(take(n, filter(iscircularprime, rang))))\nisprimerepunit(n) = isprime(evalpoly(BigInt(10), ones(Int, n)))\nfiltrep(n, rang) = collect(take(n, filter(isprimerepunit, rang)))\n\nprintln(\"The first 19 circular primes are:\\n\", filtcircular(19, Lazy.range(2)))\nprint(\"\\nThe next 4 circular primes, in repunit format, are: \",\n mapreduce(n -> \"R($n) \", *, filtrep(4, Lazy.range(6))))\n\nprintln(\"\\n\\nChecking larger repunits:\")\nfor i in [5003, 9887, 15073, 25031, 35317, 49081]\n println(\"R($i) is \", isprimerepunit(i) ? \"prime.\" : \"not prime.\")\nend\n", "language": "Julia" }, { "code": "import java.math.BigInteger\n\nval SMALL_PRIMES = listOf(\n 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,\n 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,\n 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,\n 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599,\n 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,\n 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797,\n 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887,\n 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997\n)\n\nfun isPrime(n: BigInteger): Boolean {\n if (n < 2.toBigInteger()) {\n return false\n }\n\n for (sp in SMALL_PRIMES) {\n val spb = sp.toBigInteger()\n if (n == spb) {\n return true\n }\n if (n % spb == BigInteger.ZERO) {\n return false\n }\n if (n < spb * spb) {\n //if (n > SMALL_PRIMES.last().toBigInteger()) {\n // println(\"Next: $n\")\n //}\n return true\n }\n }\n\n return n.isProbablePrime(10)\n}\n\nfun cycle(n: BigInteger): BigInteger {\n var m = n\n var p = 1\n while (m >= BigInteger.TEN) {\n p *= 10\n m /= BigInteger.TEN\n }\n return m + BigInteger.TEN * (n % p.toBigInteger())\n}\n\nfun isCircularPrime(p: BigInteger): Boolean {\n if (!isPrime(p)) {\n return false\n }\n var p2 = cycle(p)\n while (p2 != p) {\n if (p2 < p || !isPrime(p2)) {\n return false\n }\n p2 = cycle(p2)\n }\n return true\n}\n\nfun testRepUnit(digits: Int) {\n var repUnit = BigInteger.ONE\n var count = digits - 1\n while (count > 0) {\n repUnit = BigInteger.TEN * repUnit + BigInteger.ONE\n count--\n }\n if (isPrime(repUnit)) {\n println(\"R($digits) is probably prime.\")\n } else {\n println(\"R($digits) is not prime.\")\n }\n}\n\nfun main() {\n println(\"First 19 circular primes:\")\n var p = 2\n var count = 0\n while (count < 19) {\n if (isCircularPrime(p.toBigInteger())) {\n if (count > 0) {\n print(\", \")\n }\n print(p)\n count++\n }\n p++\n }\n println()\n\n println(\"Next 4 circular primes:\")\n var repUnit = BigInteger.ONE\n var digits = 1\n count = 0\n while (repUnit < p.toBigInteger()) {\n repUnit = BigInteger.TEN * repUnit + BigInteger.ONE\n digits++\n }\n while (count < 4) {\n if (isPrime(repUnit)) {\n print(\"R($digits) \")\n count++\n }\n repUnit = BigInteger.TEN * repUnit + BigInteger.ONE\n digits++\n }\n println()\n\n testRepUnit(5003)\n testRepUnit(9887)\n testRepUnit(15073)\n testRepUnit(25031)\n testRepUnit(35317)\n testRepUnit(49081)\n}\n", "language": "Kotlin" }, { "code": "-- Circular primes, in Lua, 6/22/2020 db\nlocal function isprime(n)\n if n < 2 then return false end\n if n % 2 == 0 then return n==2 end\n if n % 3 == 0 then return n==3 end\n for f = 5, math.sqrt(n), 6 do\n if n % f == 0 or n % (f+2) == 0 then return false end\n end\n return true\nend\n\nlocal function iscircularprime(p)\n local n = math.floor(math.log10(p))\n local m, q = 10^n, p\n for i = 0, n do\n if (q < p or not isprime(q)) then return false end\n q = (q % m) * 10 + math.floor(q / m)\n end\n return true\nend\n\nlocal p, dp, list, N = 2, 1, {}, 19\nwhile #list < N do\n if iscircularprime(p) then list[#list+1] = p end\n p, dp = p + dp, 2\nend\nprint(table.concat(list, \", \"))\n", "language": "Lua" }, { "code": "ClearAll[RepUnit, CircularPrimeQ]\nRepUnit[n_] := (10^n - 1)/9\nCircularPrimeQ[n_Integer] := Module[{id = IntegerDigits[n], nums, t},\n AllTrue[\n Range[Length[id]]\n ,\n Function[{z},\n t = FromDigits[RotateLeft[id, z]];\n If[t < n,\n False\n ,\n PrimeQ[t]\n ]\n ]\n ]\n ]\nSelect[Range[200000], CircularPrimeQ]\n\nres = {};\nDynamic[res]\nDo[\n If[CircularPrimeQ[RepUnit[n]], AppendTo[res, n]]\n ,\n {n, 1000}\n ]\n\nScan[Print@*PrimeQ@*RepUnit, {5003, 9887, 15073, 25031, 35317, 49081}]\n", "language": "Mathematica" }, { "code": "import bignum\nimport strformat\n\nconst SmallPrimes = [\n 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,\n 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,\n 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,\n 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599,\n 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,\n 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797,\n 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887,\n 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]\n\nlet\n One = newInt(1)\n Two = newInt(2)\n Ten = newInt(10)\n\n#---------------------------------------------------------------------------------------------------\n\nproc isPrime(n: Int): bool =\n\n if n < Two: return false\n\n for sp in SmallPrimes:\n # let spb = newInt(sp)\n if n == sp: return true\n if (n mod sp).isZero: return false\n if n < sp * sp: return true\n\n result = probablyPrime(n, 25) != 0\n\n#---------------------------------------------------------------------------------------------------\n\nproc cycle(n: Int): Int =\n\n var m = n\n var p = 1\n while m >= Ten:\n p *= 10\n m = m div 10\n result = m + Ten * (n mod p)\n\n#---------------------------------------------------------------------------------------------------\n\nproc isCircularPrime(p: Int): bool =\n\n if not p.isPrime(): return false\n\n var p2 = cycle(p)\n while p2 != p:\n if p2 < p or not p2.isPrime():\n return false\n p2 = cycle(p2)\n result = true\n\n#---------------------------------------------------------------------------------------------------\n\nproc testRepunit(digits: int) =\n\n var repunit = One\n var count = digits - 1\n while count > 0:\n repunit = Ten * repunit + One\n dec count\n if repunit.isPrime():\n echo fmt\"R({digits}) is probably prime.\"\n else:\n echo fmt\"R({digits}) is not prime.\"\n\n#---------------------------------------------------------------------------------------------------\n\necho \"First 19 circular primes:\"\nvar p = 2\nvar line = \"\"\nvar count = 0\nwhile count < 19:\n if newInt(p).isCircularPrime():\n if count > 0: line.add(\", \")\n line.add($p)\n inc count\n inc p\necho line\n\necho \"\"\necho \"Next 4 circular primes:\"\nvar repunit = One\nvar digits = 1\nwhile repunit < p:\n repunit = Ten * repunit + One\n inc digits\nline = \"\"\ncount = 0\nwhile count < 4:\n if repunit.isPrime():\n if count > 0: line.add(' ')\n line.add(fmt\"R({digits})\")\n inc count\n repunit = Ten * repunit + One\n inc digits\necho line\n\necho \"\"\ntestRepUnit(5003)\ntestRepUnit(9887)\ntestRepUnit(15073)\ntestRepUnit(25031)\ntestRepUnit(35317)\ntestRepUnit(49081)\n", "language": "Nim" }, { "code": "use strict;\nuse warnings;\nuse feature 'say';\nuse List::Util 'min';\nuse ntheory 'is_prime';\n\nsub rotate { my($i,@a) = @_; join '', @a[$i .. @a-1, 0 .. $i-1] }\n\nsub isCircular {\n my ($n) = @_;\n return 0 unless is_prime($n);\n my @circular = split //, $n;\n return 0 if min(@circular) < $circular[0];\n for (1 .. scalar @circular) {\n my $r = join '', rotate($_,@circular);\n return 0 unless is_prime($r) and $r >= $n;\n }\n 1\n}\n\nsay \"The first 19 circular primes are:\";\nfor ( my $i = 1, my $count = 0; $count < 19; $i++ ) {\n ++$count and print \"$i \" if isCircular($i);\n}\n\nsay \"\\n\\nThe next 4 circular primes, in repunit format, are:\";\nfor ( my $i = 7, my $count = 0; $count < 4; $i++ ) {\n ++$count and say \"R($i)\" if is_prime 1 x $i\n}\n\nsay \"\\nRepunit testing:\";\n\nfor (5003, 9887, 15073, 25031, 35317, 49081) {\n say \"R($_): Prime? \" . (is_prime 1 x $_ ? 'True' : 'False');\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">circular</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">len</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)),</span>\n <span style=\"color: #000000;\">pow</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">p0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">p</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">pow</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">p0</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">is_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)<</span><span style=\"color: #000000;\">19</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">get_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">circular</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"The first 19 circular primes are:\\n%v\\n\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">})</span>\n\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">mpfr</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">repunit</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpz_set_str</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">'1'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">7</span>\n <span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">z</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_init</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)<</span><span style=\"color: #000000;\">4</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">repunit</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">mpz_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"R(%d)\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"The next 4 circular primes, in repunit format, are:\\n%s\\n\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)})</span>\n<!--\n", "language": "Phix" }, { "code": "-->\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5003</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9887</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">15073</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">25031</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">35317</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">49081</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"The following repunits are probably circular primes:\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ti</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">repunit</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">bPrime</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"R(%d) : %t (%s)\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">bPrime</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "(load \"plcommon/primality.l\") # see task: \"Miller-Rabin Primality Test\"\n\n(de candidates (Limit)\n (let Q (0)\n (nth\n (sort\n (make\n (while Q\n (let A (pop 'Q)\n (when (< A Limit)\n (link A)\n (setq Q\n (cons\n (+ (* 10 A) 1)\n (cons\n (+ (* 10 A) 3)\n (cons\n (+ (* 10 A) 7)\n (cons (+ (* 10 A) 9) Q))))))))))\n 6)))\n\n(de circular? (P0)\n (and\n (small-prime? P0)\n (fully '((P) (and (>= P P0) (small-prime? P))) (rotations P0))))\n\n(de rotate (L)\n (let ((X . Xs) L)\n (append Xs (list X))))\n\n(de rotations (N)\n (let L (chop N)\n (mapcar\n format\n (make\n (do (dec (length L))\n (link (setq L (rotate L))))))))\n\n(de small-prime? (N) # For small prime candidates only\n (if (< N 2)\n NIL\n (let W (1 2 2 . (4 2 4 2 4 6 2 6 .))\n (for (D 2 T (+ D (pop 'W)))\n (T (> (* D D) N) T)\n (T (=0 (% N D)) NIL)))))\n\n(de repunit-primes (N)\n (let (Test 111111 Remaining N K 6)\n (make\n (until (=0 Remaining)\n (setq Test (inc (* 10 Test)))\n (inc 'K)\n (when (prime? Test)\n (link K)\n (dec 'Remaining))))))\n\n(setq Circular\n (conc\n (2 3 5 7)\n (filter circular? (candidates 1000000))\n (mapcar '((X) (list 'R X)) (repunit-primes 4))))\n\n(prinl \"The first few circular primes:\")\n(println Circular)\n(bye)\n", "language": "PicoLisp" }, { "code": "?- use_module(library(primality)).\n\ncircular(N) :- member(N, [2, 3, 5, 7]).\ncircular(N) :-\n limit(15, (\n candidate(N),\n N > 9,\n circular_prime(N))).\ncircular(r(K)) :-\n between(6, inf, K),\n N is (10**K - 1) div 9,\n prime(N).\n\ncandidate(0).\ncandidate(N) :-\n candidate(M),\n member(D, [1, 3, 7, 9]),\n N is 10*M + D.\n\ncircular_prime(N) :-\n K is floor(log10(N)) + 1,\n circular_prime(N, N, K).\ncircular_prime(_, _, 0) :- !.\ncircular_prime(P0, P, K) :-\n P >= P0,\n prime(P),\n rotate(P, Q), succ(DecK, K),\n circular_prime(P0, Q, DecK).\n\nrotate(N, M) :-\n D is floor(log10(N)),\n divmod(N, 10, Q, R),\n M is R*10**D + Q.\n\nmain :-\n findall(P, limit(23, circular(P)), S),\n format(\"The first 23 circular primes:~n~w~n\", [S]),\n halt.\n\n?- main.\n", "language": "Prolog" }, { "code": "Macro floor(x)\n Round(x, #PB_Round_Down)\nEndMacro\n\nProcedure isPrime(v.i)\n If v <= 1 : ProcedureReturn #False\n ElseIf v < 4 : ProcedureReturn #True\n ElseIf v % 2 = 0 : ProcedureReturn #False\n ElseIf v < 9 : ProcedureReturn #True\n ElseIf v % 3 = 0 : ProcedureReturn #False\n Else\n Protected r = Round(Sqr(v), #PB_Round_Down)\n Protected f = 5\n While f <= r\n If v % f = 0 Or v % (f + 2) = 0\n ProcedureReturn #False\n EndIf\n f + 6\n Wend\n EndIf\n ProcedureReturn #True\nEndProcedure\n\nProcedure isCircularPrime(p.i)\n n.i = floor(Log(p)/Log(10))\n m.i = Pow(10, n)\n q.i = p\n For i.i = 0 To n\n If q < p Or Not isPrime(q)\n ProcedureReturn #False\n EndIf\n q = (q % m) * 10 + floor(q / m)\n Next i\n ProcedureReturn #True\nEndProcedure\n\nOpenConsole()\n\np.i = 2\ndp.i = 1\ncont.i = 0\nPrintN(\"Primeros 19 primos circulares:\")\nWhile cont < 19\n If isCircularPrime(p)\n Print(Str(p) + \" \")\n cont + 1\n EndIf\n p + dp\n dp = 2\nWend\n\nPrintN(#CRLF$ + \"--- terminado, pulsa RETURN---\"): Input()\nCloseConsole()\n", "language": "PureBasic" }, { "code": "import random\n\ndef is_Prime(n):\n \"\"\"\n Miller-Rabin primality test.\n\n A return value of False means n is certainly not prime. A return value of\n True means n is very likely a prime.\n \"\"\"\n if n!=int(n):\n return False\n n=int(n)\n #Miller-Rabin test for prime\n if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:\n return False\n\n if n==2 or n==3 or n==5 or n==7:\n return True\n s = 0\n d = n-1\n while d%2==0:\n d>>=1\n s+=1\n assert(2**s * d == n-1)\n\n def trial_composite(a):\n if pow(a, d, n) == 1:\n return False\n for i in range(s):\n if pow(a, 2**i * d, n) == n-1:\n return False\n return True\n\n for i in range(8):#number of trials\n a = random.randrange(2, n)\n if trial_composite(a):\n return False\n\n return True\n\ndef isPrime(n: int) -> bool:\n '''\n https://www.geeksforgeeks.org/python-program-to-check-whether-a-number-is-prime-or-not/\n '''\n # Corner cases\n if (n <= 1) :\n return False\n if (n <= 3) :\n return True\n # This is checked so that we can skip\n # middle five numbers in below loop\n if (n % 2 == 0 or n % 3 == 0) :\n return False\n i = 5\n while(i * i <= n) :\n if (n % i == 0 or n % (i + 2) == 0) :\n return False\n i = i + 6\n return True\n\ndef rotations(n: int)-> set((int,)):\n '''\n >>> {123, 231, 312} == rotations(123)\n True\n '''\n a = str(n)\n return set(int(a[i:] + a[:i]) for i in range(len(a)))\n\ndef isCircular(n: int) -> bool:\n '''\n >>> [isCircular(n) for n in (11, 31, 47,)]\n\t[True, True, False]\n '''\n return all(isPrime(int(o)) for o in rotations(n))\n\nfrom itertools import product\n\ndef main():\n result = [2, 3, 5, 7]\n first = '137'\n latter = '1379'\n for i in range(1, 6):\n s = set(int(''.join(a)) for a in product(first, *((latter,) * i)))\n while s:\n a = s.pop()\n b = rotations(a)\n if isCircular(a):\n result.append(min(b))\n s -= b\n result.sort()\n return result\n\nassert [2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933] == main()\n\n\nrepunit = lambda n: int('1' * n)\n\ndef repmain(n: int) -> list:\n '''\n returns the first n repunit primes, probably.\n '''\n result = []\n i = 2\n while len(result) < n:\n if is_Prime(repunit(i)):\n result.append(i)\n i += 1\n return result\n\nassert [2, 19, 23, 317, 1031] == repmain(5)\n\n# because this Miller-Rabin test is already on rosettacode there's no good reason to test the longer repunits.\n", "language": "Python" }, { "code": "sub isCircular(\\n) {\n return False unless n.is-prime;\n my @circular = n.comb;\n return False if @circular.min < @circular[0];\n for 1 ..^ @circular -> $i {\n return False unless .is-prime and $_ >= n given @circular.rotate($i).join;\n }\n True\n}\n\nsay \"The first 19 circular primes are:\";\nsay ((2..*).hyper.grep: { isCircular $_ })[^19];\n\nsay \"\\nThe next 4 circular primes, in repunit format, are:\";\nloop ( my $i = 7, my $count = 0; $count < 4; $i++ ) {\n ++$count, say \"R($i)\" if (1 x $i).is-prime\n}\n\nuse ntheory:from<Perl5> qw[is_prime];\n\nsay \"\\nRepunit testing:\";\n\n(5003, 9887, 15073, 25031, 35317, 49081).map: {\n my $now = now;\n say \"R($_): Prime? \", ?is_prime(\"{1 x $_}\"), \" {(now - $now).fmt: '%.2f'}\"\n}\n", "language": "Raku" }, { "code": "/*REXX program finds & displays circular primes (with a title & in a horizontal format).*/\nparse arg N hp . /*obtain optional arguments from the CL*/\nif N=='' | N==\",\" then N= 19 /* \" \" \" \" \" \" */\nif hp=='' | hp==\",\" then hip= 1000000 /* \" \" \" \" \" \" */\ncall genP /*gen primes up to hp (200,000). */\nq= 024568 /*digs that most circular P can't have.*/\nfound= 0; $= /*found: circular P count; $: a list.*/\n do j=1 until found==N; p= @.j /* [↓] traipse through all the primes.*/\n if p>9 & verify(p, q, 'M')>0 then iterate /*Does J contain forbidden digs? Skip.*/\n if \\circP(p) then iterate /*Not circular? Then skip this number.*/\n found= found + 1 /*bump the count of circular primes. */\n $= $ p /*add this prime number ──► $ list. */\n end /*j*/ /*at this point, $ has a leading blank.*/\n\nsay center(' first ' found \" circular primes \", 79, '─')\nsay strip($)\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncircP: procedure expose @. !.; parse arg x 1 ox /*obtain a prime number to be examined.*/\n do length(x)-1; parse var x f 2 y /*parse X number, rotating the digits*/\n x= y || f /*construct a new possible circular P. */\n if x<ox then return 0 /*is number < the original? ¬ circular*/\n if \\!.x then return 0 /* \" \" not prime? ¬ circular*/\n end /*length(x)···*/\n return 1 /*passed all tests, X is a circular P.*/\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ngenP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19 /*assign Ps; #Ps*/\n !.= 0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1; !.19=1 /* \" primality*/\n #= 8; sq.#= @.# **2 /*number of primes so far; prime square*/\n do j=@.#+4 by 2 to hip; parse var j '' -1 _ /*get last decimal digit of J. */\n if _==5 then iterate; if j// 3==0 then iterate; if j// 7==0 then iterate\n if j//11==0 then iterate; if j//13==0 then iterate; if j//17==0 then iterate\n do k=8 while sq.k<=j /*divide by some generated odd primes. */\n if j // @.k==0 then iterate j /*Is J divisible by P? Then not prime*/\n end /*k*/ /* [↓] a prime (J) has been found. */\n #= #+1; !.j= 1; sq.#= j*j; @.#= j /*bump P cnt; assign P to @. and !. */\n end /*j*/; return\n", "language": "REXX" }, { "code": "see \"working...\" + nl\nsee \"First 19 circular numbers are:\" + nl\nn = 0\nrow = 0\nPrimes = []\n\nwhile row < 19\n n++\n flag = 1\n nStr = string(n)\n lenStr = len(nStr)\n for m = 1 to lenStr\n leftStr = left(nStr,m)\n rightStr = right(nStr,lenStr-m)\n strOk = rightStr + leftStr\n nOk = number(strOk)\n ind = find(Primes,nOk)\n if ind < 1 and strOk != nStr\n add(Primes,nOk)\n ok\n if not isprimeNumber(nOk) or ind > 0\n flag = 0\n exit\n ok\n next\n if flag = 1\n row++\n see \"\" + n + \" \"\n if row%5 = 0\n see nl\n ok\n ok\nend\n\nsee nl + \"done...\" + nl\n\nfunc isPrimeNumber(num)\n if (num <= 1) return 0 ok\n if (num % 2 = 0) and (num != 2) return 0 ok\n for i = 2 to sqrt(num)\n\t if (num % i = 0) return 0 ok\n next\n return 1\n", "language": "Ring" }, { "code": "require 'gmp'\nrequire 'prime'\ncandidate_primes = Enumerator.new do |y|\n DIGS = [1,3,7,9]\n [2,3,5,7].each{|n| y << n.to_s}\n (2..).each do |size|\n DIGS.repeated_permutation(size) do |perm|\n y << perm.join if (perm == min_rotation(perm)) && GMP::Z(perm.join).probab_prime? > 0\n end\n end\nend\n\ndef min_rotation(ar) = Array.new(ar.size){|n| ar.rotate(n)}.min\n\ndef circular?(num_str)\n chars = num_str.chars\n return GMP::Z(num_str).probab_prime? > 0 if chars.all?(\"1\")\n chars.size.times.all? do\n GMP::Z(chars.rotate!.join).probab_prime? > 0\n # chars.rotate!.join.to_i.prime?\n end\nend\n\nputs \"First 19 circular primes:\"\nputs candidate_primes.lazy.select{|cand| circular?(cand)}.take(19).to_a.join(\", \"),\"\"\nputs \"First 5 prime repunits:\"\nreps = Prime.each.lazy.select{|pr| circular?(\"1\"*pr)}.take(5).to_a\nputs reps.map{|r| \"R\" + r.to_s}.join(\", \"), \"\"\n[5003, 9887, 15073, 25031].each {|rep| puts \"R#{rep} circular_prime ? #{circular?(\"1\"*rep)}\" }\n", "language": "Ruby" }, { "code": "// [dependencies]\n// rug = \"1.8\"\n\nfn is_prime(n: u32) -> bool {\n if n < 2 {\n return false;\n }\n if n % 2 == 0 {\n return n == 2;\n }\n if n % 3 == 0 {\n return n == 3;\n }\n let mut p = 5;\n while p * p <= n {\n if n % p == 0 {\n return false;\n }\n p += 2;\n if n % p == 0 {\n return false;\n }\n p += 4;\n }\n true\n}\n\nfn cycle(n: u32) -> u32 {\n let mut m: u32 = n;\n let mut p: u32 = 1;\n while m >= 10 {\n p *= 10;\n m /= 10;\n }\n m + 10 * (n % p)\n}\n\nfn is_circular_prime(p: u32) -> bool {\n if !is_prime(p) {\n return false;\n }\n let mut p2: u32 = cycle(p);\n while p2 != p {\n if p2 < p || !is_prime(p2) {\n return false;\n }\n p2 = cycle(p2);\n }\n true\n}\n\nfn test_repunit(digits: usize) {\n use rug::{integer::IsPrime, Integer};\n let repunit = \"1\".repeat(digits);\n let bignum = Integer::from_str_radix(&repunit, 10).unwrap();\n if bignum.is_probably_prime(10) != IsPrime::No {\n println!(\"R({}) is probably prime.\", digits);\n } else {\n println!(\"R({}) is not prime.\", digits);\n }\n}\n\nfn main() {\n use rug::{integer::IsPrime, Integer};\n println!(\"First 19 circular primes:\");\n let mut count = 0;\n let mut p: u32 = 2;\n while count < 19 {\n if is_circular_prime(p) {\n if count > 0 {\n print!(\", \");\n }\n print!(\"{}\", p);\n count += 1;\n }\n p += 1;\n }\n println!();\n println!(\"Next 4 circular primes:\");\n let mut repunit: u32 = 1;\n let mut digits: usize = 1;\n while repunit < p {\n repunit = 10 * repunit + 1;\n digits += 1;\n }\n let mut bignum = Integer::from(repunit);\n count = 0;\n while count < 4 {\n if bignum.is_probably_prime(15) != IsPrime::No {\n if count > 0 {\n print!(\", \");\n }\n print!(\"R({})\", digits);\n count += 1;\n }\n digits += 1;\n bignum = bignum * 10 + 1;\n }\n println!();\n test_repunit(5003);\n test_repunit(9887);\n test_repunit(15073);\n test_repunit(25031);\n test_repunit(35317);\n test_repunit(49081);\n}\n", "language": "Rust" }, { "code": "object CircularPrimes {\n def main(args: Array[String]): Unit = {\n println(\"First 19 circular primes:\")\n var p = 2\n var count = 0\n while (count < 19) {\n if (isCircularPrime(p)) {\n if (count > 0) {\n print(\", \")\n }\n print(p)\n count += 1\n }\n p += 1\n }\n println()\n\n println(\"Next 4 circular primes:\")\n var repunit = 1\n var digits = 1\n while (repunit < p) {\n repunit = 10 * repunit + 1\n digits += 1\n }\n var bignum = BigInt.apply(repunit)\n count = 0\n while (count < 4) {\n if (bignum.isProbablePrime(15)) {\n if (count > 0) {\n print(\", \")\n }\n print(s\"R($digits)\")\n count += 1\n }\n digits += 1\n bignum = bignum * 10\n bignum = bignum + 1\n }\n println()\n\n testRepunit(5003)\n testRepunit(9887)\n testRepunit(15073)\n testRepunit(25031)\n }\n\n def isPrime(n: Int): Boolean = {\n if (n < 2) {\n return false\n }\n if (n % 2 == 0) {\n return n == 2\n }\n if (n % 3 == 0) {\n return n == 3\n }\n var p = 5\n while (p * p <= n) {\n if (n % p == 0) {\n return false\n }\n p += 2\n if (n % p == 0) {\n return false\n }\n p += 4\n }\n true\n }\n\n def cycle(n: Int): Int = {\n var m = n\n var p = 1\n while (m >= 10) {\n p *= 10\n m /= 10\n }\n m + 10 * (n % p)\n }\n\n def isCircularPrime(p: Int): Boolean = {\n if (!isPrime(p)) {\n return false\n }\n var p2 = cycle(p)\n while (p2 != p) {\n if (p2 < p || !isPrime(p2)) {\n return false\n }\n p2 = cycle(p2)\n }\n true\n }\n\n def testRepunit(digits: Int): Unit = {\n val ru = repunit(digits)\n if (ru.isProbablePrime(15)) {\n println(s\"R($digits) is probably prime.\")\n } else {\n println(s\"R($digits) is not prime.\")\n }\n }\n\n def repunit(digits: Int): BigInt = {\n val ch = Array.fill(digits)('1')\n BigInt.apply(new String(ch))\n }\n}\n", "language": "Scala" }, { "code": "func is_circular_prime(n) {\n n.is_prime || return false\n\n var circular = n.digits\n circular.min < circular.tail && return false\n\n for k in (1 ..^ circular.len) {\n with (circular.rotate(k).digits2num) {|p|\n (p.is_prime && (p >= n)) || return false\n }\n }\n\n return true\n}\n\nsay \"The first 19 circular primes are:\"\nsay 19.by(is_circular_prime)\n\nsay \"\\nThe next 4 circular primes, in repunit format, are:\"\n{|n| (10**n - 1)/9 -> is_prob_prime }.first(4, 4..Inf).each {|n|\n say \"R(#{n})\"\n}\n\nsay \"\\nRepunit testing:\"\n[5003, 9887, 15073, 25031, 35317, 49081].each {|n|\n var now = Time.micro\n say (\"R(#{n}) -> \", is_prob_prime((10**n - 1)/9) ? 'probably prime' : 'composite',\n \" (took: #{'%.3f' % Time.micro-now} sec)\")\n}\n", "language": "Sidef" }, { "code": "import \"./math\" for Int\nimport \"./big\" for BigInt\nimport \"./str\" for Str\n\nvar circs = []\n\nvar isCircular = Fn.new { |n|\n var nn = n\n var pow = 1 // will eventually contain 10 ^ d where d is number of digits in n\n while (nn > 0) {\n pow = pow * 10\n nn = (nn/10).floor\n }\n nn = n\n while (true) {\n nn = nn * 10\n var f = (nn/pow).floor // first digit\n nn = nn + f * (1 - pow)\n if (circs.contains(nn)) return false\n if (nn == n) break\n if (!Int.isPrime(nn)) return false\n }\n return true\n}\n\nvar repunit = Fn.new { |n| BigInt.new(Str.repeat(\"1\", n)) }\n\nSystem.print(\"The first 19 circular primes are:\")\nvar digits = [1, 3, 7, 9]\nvar q = [1, 2, 3, 5, 7, 9] // queue the numbers to be examined\nvar fq = [1, 2, 3, 5, 7, 9] // also queue the corresponding first digits\nvar count = 0\nwhile (true) {\n var f = q[0] // peek first element\n var fd = fq[0] // peek first digit\n if (Int.isPrime(f) && isCircular.call(f)) {\n circs.add(f)\n count = count + 1\n if (count == 19) break\n }\n q.removeAt(0) // pop first element\n fq.removeAt(0) // ditto for first digit queue\n if (f != 2 && f != 5) { // if digits > 1 can't contain a 2 or 5\n // add numbers with one more digit to queue\n // only numbers whose last digit >= first digit need be added\n for (d in digits) {\n if (d >= fd) {\n q.add(f*10+d)\n fq.add(fd)\n }\n }\n }\n}\nSystem.print(circs)\n\nSystem.print(\"\\nThe next 4 circular primes, in repunit format, are:\")\ncount = 0\nvar rus = []\nvar primes = Int.primeSieve(10000)\nfor (p in primes[3..-1]) {\n if (repunit.call(p).isProbablePrime(1)) {\n rus.add(\"R(%(p))\")\n count = count + 1\n if (count == 4) break\n }\n}\nSystem.print(rus)\n", "language": "Wren" }, { "code": "/* Circular_primes_embedded.wren */\n\nimport \"./gmp\" for Mpz\nimport \"./math\" for Int\nimport \"./fmt\" for Fmt\nimport \"./str\" for Str\n\nvar circs = []\n\nvar isCircular = Fn.new { |n|\n var nn = n\n var pow = 1 // will eventually contain 10 ^ d where d is number of digits in n\n while (nn > 0) {\n pow = pow * 10\n nn = (nn/10).floor\n }\n nn = n\n while (true) {\n nn = nn * 10\n var f = (nn/pow).floor // first digit\n nn = nn + f * (1 - pow)\n if (circs.contains(nn)) return false\n if (nn == n) break\n if (!Int.isPrime(nn)) return false\n }\n return true\n}\n\nSystem.print(\"The first 19 circular primes are:\")\nvar digits = [1, 3, 7, 9]\nvar q = [1, 2, 3, 5, 7, 9] // queue the numbers to be examined\nvar fq = [1, 2, 3, 5, 7, 9] // also queue the corresponding first digits\nvar count = 0\nwhile (true) {\n var f = q[0] // peek first element\n var fd = fq[0] // peek first digit\n if (Int.isPrime(f) && isCircular.call(f)) {\n circs.add(f)\n count = count + 1\n if (count == 19) break\n }\n q.removeAt(0) // pop first element\n fq.removeAt(0) // ditto for first digit queue\n if (f != 2 && f != 5) { // if digits > 1 can't contain a 2 or 5\n // add numbers with one more digit to queue\n // only numbers whose last digit >= first digit need be added\n for (d in digits) {\n if (d >= fd) {\n q.add(f*10+d)\n fq.add(fd)\n }\n }\n }\n}\nSystem.print(circs)\n\nSystem.print(\"\\nThe next 4 circular primes, in repunit format, are:\")\ncount = 0\nvar rus = []\nvar primes = Int.primeSieve(10000)\nvar repunit = Mpz.new()\nfor (p in primes[3..-1]) {\n repunit.setStr(Str.repeat(\"1\", p), 10)\n if (repunit.probPrime(10) > 0) {\n rus.add(\"R(%(p))\")\n count = count + 1\n if (count == 4) break\n }\n}\nSystem.print(rus)\nSystem.print(\"\\nThe following repunits are probably circular primes:\")\nfor (i in [5003, 9887, 15073, 25031, 35317, 49081]) {\n repunit.setStr(Str.repeat(\"1\", i), 10)\n Fmt.print(\"R($-5d) : $s\", i, repunit.probPrime(15) > 0)\n}\n", "language": "Wren" }, { "code": "func IsPrime(N); \\Return 'true' if N > 2 is a prime number\nint N, I;\n[if (N&1) = 0 \\even number\\ then return false;\nfor I:= 3 to sqrt(N) do\n [if rem(N/I) = 0 then return false;\n I:= I+1;\n ];\nreturn true;\n];\n\nfunc CircPrime(N0); \\Return 'true' if N0 is a circular prime\nint N0, N, Digits, Rotation, I, R;\n[N:= N0;\nDigits:= 0; \\count number of digits in N\nrepeat Digits:= Digits+1;\n N:= N/10;\nuntil N = 0;\nN:= N0;\nfor Rotation:= 0 to Digits-1 do\n [if not IsPrime(N) then return false;\n N:= N/10; \\rotate least sig digit into high end\n R:= rem(0);\n for I:= 0 to Digits-2 do\n R:= R*10;\n N:= N+R;\n if N0 > N then \\reject N0 if it has a smaller prime rotation\n return false;\n ];\nreturn true;\n];\n\nint Counter, N;\n[IntOut(0, 2); ChOut(0, ^ ); \\show first circular prime\nCounter:= 1;\nN:= 3; \\remaining primes are odd\nloop [if CircPrime(N) then\n [IntOut(0, N); ChOut(0, ^ );\n Counter:= Counter+1;\n if Counter >= 19 then quit;\n ];\n N:= N+2;\n ];\n]\n", "language": "XPL0" }, { "code": "p = 2\ndp = 1\ncont = 0\nprint(\"Primeros 19 primos circulares:\")\nwhile cont < 19\n\tif isCircularPrime(p) then\n\t print p,\" \";\n\t\tcont = cont + 1\n\tfi\n\tp = p + dp\n\tdp = 2\nwend\nend\n\nsub isPrime(v)\n if v < 2 return False\n if mod(v, 2) = 0 return v = 2\n if mod(v, 3) = 0 return v = 3\n d = 5\n while d * d <= v\n if mod(v, d) = 0 then return False else d = d + 2 : fi\n wend\n return True\nend sub\n\nsub isCircularPrime(p)\n\tn = floor(log(p)/log(10))\n\tm = 10^n\n\tq = p\n\tfor i = 0 to n\n\t\tif (q < p or not isPrime(q)) return false\n\t\tq = (mod(q, m)) * 10 + floor(q / m)\n\tnext i\n\treturn true\nend sub\n", "language": "Yabasic" }, { "code": "const std = @import(\"std\");\nconst math = std.math;\nconst heap = std.heap;\n\npub fn main() !void {\n var arena = heap.ArenaAllocator.init(heap.page_allocator);\n defer arena.deinit();\n\n const allocator = arena.allocator();\n\n var candidates = std.PriorityQueue(u32, void, u32cmp).init(allocator, {});\n defer candidates.deinit();\n\n const stdout = std.io.getStdOut().writer();\n\n try stdout.print(\"The circular primes are:\\n\", .{});\n try stdout.print(\"{:10}\" ** 4, .{ 2, 3, 5, 7 });\n\n var c: u32 = 4;\n try candidates.add(0);\n while (true) {\n var n = candidates.remove();\n if (n > 1_000_000)\n break;\n if (n > 10 and circular(n)) {\n try stdout.print(\"{:10}\", .{n});\n c += 1;\n if (c % 10 == 0)\n try stdout.print(\"\\n\", .{});\n }\n try candidates.add(10 * n + 1);\n try candidates.add(10 * n + 3);\n try candidates.add(10 * n + 7);\n try candidates.add(10 * n + 9);\n }\n try stdout.print(\"\\n\", .{});\n}\n\nfn u32cmp(_: void, a: u32, b: u32) math.Order {\n return math.order(a, b);\n}\n\nfn circular(n0: u32) bool {\n if (!isPrime(n0))\n return false\n else {\n var n = n0;\n var d: u32 = @intFromFloat(@log10(@as(f32, @floatFromInt(n))));\n return while (d > 0) : (d -= 1) {\n n = rotate(n);\n if (n < n0 or !isPrime(n))\n break false;\n } else true;\n }\n}\n\nfn rotate(n: u32) u32 {\n if (n == 0)\n return 0\n else {\n const d: u32 = @intFromFloat(@log10(@as(f32, @floatFromInt(n)))); // digit count - 1\n const m = math.pow(u32, 10, d);\n return (n % m) * 10 + n / m;\n }\n}\n\nfn isPrime(n: u32) bool {\n if (n < 2)\n return false;\n\n inline for ([3]u3{ 2, 3, 5 }) |p| {\n if (n % p == 0)\n return n == p;\n }\n\n const wheel235 = [_]u3{\n 6, 4, 2, 4, 2, 4, 6, 2,\n };\n var i: u32 = 1;\n var f: u32 = 7;\n return while (f * f <= n) {\n if (n % f == 0)\n break false;\n f += wheel235[i];\n i = (i + 1) & 0x07;\n } else true;\n}\n", "language": "Zig" } ]
Circular-primes
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Cistercian_numerals\n", "language": "00-META" }, { "code": "Cistercian numerals were used across Europe by [https://en.wikipedia.org/wiki/Cistercians Cistercian] monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.\n\n;How they work\nAll Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:\n\n:* The '''upper-right''' quadrant represents the '''ones''' place.\n:* The '''upper-left''' quadrant represents the '''tens''' place.\n:* The '''lower-right''' quadrant represents the '''hundreds''' place.\n:* The '''lower-left''' quadrant represents the '''thousands''' place.\n\nPlease consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]\n\n;Task\n\n:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).\n\n:* Use the routine to show the following Cistercian numerals:\n\n::* 0\n::* 1\n::* 20\n::* 300\n::* 4000\n::* 5555\n::* 6789\n::* And a number of your choice!\n\n;Notes\nDue to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output.\n\n;See also\n\n:* '''[https://www.youtube.com/watch?v=9p55Qgt7Ciw Numberphile - The Forgotten Number System]'''\n:* '''[https://www.dcode.fr/cistercian-numbers dcode.fr - Online Cistercian numeral converter]'''\n", "language": "00-TASK" }, { "code": ";CONSTANTS\nVFLIP equ %0001000000000000\nHFLIP equ %0000100000000000\n;Ram Variables\nCursor_X equ $00FF0000\nCursor_Y equ Cursor_X+1\ntemp_cursor_x equ $00FF0002\ntemp_cursor_y equ $00FF0003\n;Video Ports\nVDP_data\tEQU\t$C00000\t; VDP data, R/W word or longword access only\nVDP_ctrl\tEQU\t$C00004\t; VDP control, word or longword writes only\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; \t\t\t\t\tTraps\n\tDC.L\t$FFFFFE00\t\t;SP register value\n\tDC.L\tProgramStart\t ;Start of Program Code\n\tDS.L\t7,IntReturn\t\t; bus err,addr err,illegal inst,divzero,CHK,TRAPV,priv viol\n\tDC.L\tIntReturn\t\t; TRACE\n\tDC.L\tIntReturn\t\t; Line A (1010) emulator\n\tDC.L\tIntReturn\t\t; Line F (1111) emulator\n\tDS.L\t4,IntReturn\t\t; Reserverd /Coprocessor/Format err/ Uninit Interrupt\n\tDS.L\t8,IntReturn\t\t; Reserved\n\tDC.L\tIntReturn\t\t; spurious interrupt\n\tDC.L\tIntReturn\t\t; IRQ level 1\n\tDC.L\tIntReturn\t\t; IRQ level 2 EXT\n\tDC.L\tIntReturn\t\t; IRQ level 3\n\tDC.L\tIntReturn\t\t; IRQ level 4 Hsync\n\tDC.L\tIntReturn\t\t; IRQ level 5\n\tDC.L\tIntReturn\t\t; IRQ level 6 Vsync\n\tDC.L\tIntReturn\t\t; IRQ level 7\n\tDS.L\t16,IntReturn\t; TRAPs\n\tDS.L\t16,IntReturn\t; Misc (FP/MMU)\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;\t\t\t\t\tHeader\n\tDC.B\t\"SEGA GENESIS \"\t;System Name\n\tDC.B\t\"(C)CHBI \"\t\t\t;Copyright\n \tDC.B\t\"2019.JAN\"\t\t\t;Date\n\tDC.B\t\"ChibiAkumas.com \" ; Cart Name\n\tDC.B\t\"ChibiAkumas.com \" ; Cart Name (Alt)\n\tDC.B\t\"GM CHIBI001-00\"\t;TT NNNNNNNN-RR T=Type (GM=Game) N=game Num R=Revision\n\tDC.W\t$0000\t\t\t\t;16-bit Checksum (Address $000200+)\n\tDC.B\t\"J \"\t;Control Data (J=3button K=Keyboard 6=6button C=cdrom)\n\tDC.L\t$00000000\t\t\t;ROM Start\n\tDC.L\t$003FFFFF\t\t\t;ROM Length\n\tDC.L\t$00FF0000,$00FFFFFF\t;RAM start/end (fixed)\n\tDC.B\t\" \"\t\t;External RAM Data\n\tDC.B\t\" \"\t\t;Modem Data\n\tDC.B\t\" \" ;MEMO\n\tDC.B\t\"JUE \"\t;Regions Allowed\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;\t\t\t\t\tGeneric Interrupt Handler\nIntReturn:\n\trte\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;\t\t\t\t\tProgram Start\nProgramStart:\n\t;initialize TMSS (TradeMark Security System)\n\tmove.b ($A10001),D0\t\t;A10001 test the hardware version\n\tand.b #$0F,D0\n\tbeq\tNoTmss\t\t\t\t;branch if no TMSS chip\n\tmove.l #'SEGA',($A14000);A14000 disable TMSS\nNoTmss:\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;\t\t\t\t\tSet Up Screen Settings\n\n\tlea VDPSettings,A5\t\t;Initialize Screen Registers\n\tmove.l #VDPSettingsEnd-VDPSettings,D1 ;length of Settings\n\t\n\tmove.w (VDP_ctrl),D0\t;C00004 read VDP status (interrupt acknowledge?)\n\tmove.l #$00008000,d5\t;VDP Reg command (%8rvv)\n\t\nNextInitByte:\n\tmove.b (A5)+,D5\t\t\t;get next video control byte\n\tmove.w D5,(VDP_ctrl)\t;C00004 send write register command to VDP\n\t\t; 8RVV - R=Reg V=Value\n\tadd.w #$0100,D5\t\t\t;point to next VDP register\n\tdbra D1,NextInitByte\t;loop for rest of block\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;\t\t\t\t\tSet up palette and graphics\n\t\n\tmove.l #$C0000000,d0\t;Color 0\n\tmove.l d0,VDP_Ctrl\n\tMOVE.W #$0A00,VDP_Data\t\t;BLUE\n\t\n\tmove.l #$C01E0000,d0\t;Color 0\n\tmove.l d0,VDP_Ctrl\n\tMOVE.W #$00EE,VDP_Data\t\t;YELLOW\n\t\n\tlea Graphics,a0\t\t\t\t\t\t;background tiles\n\tmove.w #(GraphicsEnd-Graphics)-1,d1\t;data size\n\tMOVEQ #0,D2\t\t\t\t\t\t\t;start loading at tile 0 of VRAM\n\tjsr DefineTiles\n\t\n\t;Turn on screen\n\tmove.w\t#$8144,(VDP_Ctrl);C00004 reg 1 = 0x44 unblank display\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\t\nMain:\n\tCLR.B Cursor_X\n\tCLR.B Cursor_Y\n\t\n\tLEA TestData,a3\n\tjsr PrintCistercian\n\tjsr PrintCistercian\n\tjsr PrintCistercian\n\tjsr PrintCistercian\n\tjsr PrintCistercian\n\tjsr PrintCistercian\n\tjsr PrintCistercian\n\tjsr PrintCistercian\n\tjmp *\t\t\t\t\t;halt the cpu - we're done\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\nPrintCistercian:\n\t;input:A3 = address of test data.\n\tMOVE.B Cursor_X,temp_Cursor_X\n\tMOVE.B Cursor_Y,temp_Cursor_Y\n\tMOVE.L (A3)+,D1\n\t;thousands, hundreds, tens, ones\n\t\n\t;PRINT TENS PLACE\n\tMOVE.L D1,D0\n\tROR.W #8,D0\t\t;get tens place into low byte\n\tAND.W #$FF,D0\n\tOR.W #HFLIP,D0\n\tjsr doPrint\n\t\n\taddq.b #1,(Cursor_X)\t;INC Xpos\n\t\n\t;PRINT ONES PLACE\n\tMOVE.L D1,D0\n\tAND.W #$FF,D0\n\tJSR doPrint\n\t\n\t\n\tMOVE.B temp_Cursor_X,Cursor_X\n\tADDQ.B #1,cursor_Y\n\t\n\t;PRINT STICK CENTER\n\tMOVE.W #10,D0\t;the center of the stick\n\tOR.W #HFLIP,D0\n\tjsr doPrint\n\taddq.b #1,(Cursor_X)\t;INC Xpos\n\tMOVE.W #10,D0\t;the center of the stick\n\tjsr doPrint\n\t\n\tMOVE.B temp_Cursor_X,Cursor_X\n\tADDQ.B #1,cursor_Y\n\t\n\t;PRINT THOUSANDS PLACE\n\tMOVE.L D1,D0\n\tSWAP D0\n\tROR.W #8,D0\t\t;get thousands place into low byte\n\tAND.W #$FF,D0\n\tOR.W #(HFLIP|VFLIP),D0\n\tjsr doPrint\n\t\n\taddq.b #1,(Cursor_X)\t;INC Xpos\n\tMOVE.L D1,D0\n\tSWAP D0\n\tAND.W #$FF,D0\n\tOR.W #(VFLIP),D0\n\tjsr doPrint\t\n\t\n\tMOVE.B temp_Cursor_X,Cursor_X\n\tMOVE.B temp_Cursor_Y,Cursor_Y\n\tADDQ.B #3,Cursor_X\n\t\n\trts\ndoPrint:\n;;; this code outputs the tile index in D0 to the Genesis's tilemap... don't worry if it doesn't make sense!\n\tMove.L #$40000003,d5\t\n\tclr.l d4\t\t\t\n\n\tMove.B (Cursor_Y),D4\t\n\trol.L #8,D4\t\t\t\t\n\trol.L #8,D4\n\trol.L #7,D4\t\t\t\t\n\tadd.L D4,D5\t\t\t\t\n\t\n\tMove.B (Cursor_X),D4\n\trol.L #8,D4\t\t\t\t\n\trol.L #8,D4\n\trol.L #1,D4\t\t\t\t\n\tadd.L D4,D5\t\t\t\t\n\t\n\tMOVE.L D5,(VDP_ctrl)\t\n\tMOVE.W D0,(VDP_data)\n\t\n\trts\nTestData:\n;I used 10 for zero since otherwise we'd have a bunch of sticks as the blank tile... not good!\n\tDC.B 10,10,10,10\n\tDC.B 10,10,10,1\n\tDC.B 10,10,2,10\n\tDC.B 10,3,10,10\n\tDC.B 4,10,10,10\n\tDC.B 5,5,5,5\n\tDC.B 6,7,8,9\n\tDC.B 1,2,3,4\n\t\n\t\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n\t\nDefineTiles:\t\t\t\t\t\t;Copy D1 bytes of data from A0 to VDP memory D2\n\tjsr prepareVram\t\t\t\t\t;Calculate the memory location we want to write\n.again:\t\t\t\t\t\t\t\t; the tile pattern definitions to\n\t\tmove.l (a0)+,(VDP_data)\t\t\t\t\n\t\tdbra d1,.again\n\trts\n\t\n\t\n\t\t\t\nprepareVram:\t\t\n\t;input: D2 = the vram memory address you want to write to.\n\t\t\t\t\t\t\t\t\t\t;To select a memory location D2 we need to calculate\n\t\t\t\t\t\t\t\t\t\t;the command byte... depending on the memory location\n\tMOVEM.L D0-D7/A0-A6,-(SP)\t\t\t\t\t\t\t;$7FFF0003 = Vram $FFFF.... $40000000=Vram $0000\n\t\tmove.l d2,d0\n\t\tand.w #%1100000000000000,d0\t\t;Shift the top two bits to the far right\n\t\trol.w #2,d0\n\t\t\n\t\tand.l #%0011111111111111,d2\t ; shift all the other bits left two bytes\n\t\trol.l #8,d2\t\t\n\t\trol.l #8,d2\n\t\t\n\t\tor.l d0,d2\t\t\t\t\t\t\n\t\tor.l #$40000000,d2\t\t\t\t;Set the second bit from the top to 1\n\t\t\t\t\t\t\t\t\t\t;#%01000000 00000000 00000000 00000000\n\t\tmove.l d2,(VDP_ctrl)\n\tMOVEM.L (SP)+,D0-D7/A0-A6\n\trts\nGraphics:\n\t;cistercian numerals\n\tDC.L 0,0,0,0,0,0,0,0\t;padding - this determines the default background tile.\n\tdc.l $FFFFFFFF,$F0000000,$F0000000,$F0000000,$F0000000,$F0000000,$F0000000,$F0000000\t\t;1\n\tdc.l $F0000000,$F0000000,$F0000000,$F0000000,$FFFFFFFF,$F0000000,$F0000000,$F0000000\t\t;2\n\tdc.l $FF000000,$F0F00000,$F00F0000,$F000F000,$F0000F00,$F00000F0,$F000000F,$F0000000\t\t;3\n\tdc.l $F0000000,$F000000F,$F00000F0,$F0000F00,$F000F000,$F00F0000,$F0F00000,$FF000000\t\t;4\n\tdc.l $FFFFFFFF,$F00000F0,$F0000F00,$F000F000,$F00F0000,$F0F00000,$FF000000,$F0000000\t\t;5\n\tdc.l $F000000F,$F000000F,$F000000F,$F000000F,$F000000F,$F000000F,$F000000F,$F000000F\t\t;6\n\tdc.l $FFFFFFFF,$F000000F,$F000000F,$F000000F,$F000000F,$F000000F,$F000000F,$F000000F\t\t;7\n\tdc.l $F000000F,$F000000F,$F000000F,$F000000F,$F000000F,$F000000F,$F000000F,$FFFFFFFF\t\t;8\n\tdc.l $FFFFFFFF,$F000000F,$F000000F,$F000000F,$F000000F,$F000000F,$F000000F,$FFFFFFFF\t\t;9\n\tDC.L $F0000000,$F0000000,$F0000000,$F0000000,$F0000000,$F0000000,$F0000000,$F0000000\t\t;the \"stick\"\nGraphicsEnd:\nVDPSettings:\n\tDC.B $04 ; 0 mode register 1\t\t\t\t\t\t\t\t\t\t\t---H-1M-\n\tDC.B $04 ; 1 mode register 2\t\t\t\t\t\t\t\t\t\t\t-DVdP---\n\tDC.B $30 ; 2 name table base for scroll A (A=top 3 bits)\t\t\t\t--AAA--- = $C000\n\tDC.B $3C ; 3 name table base for window (A=top 4 bits / 5 in H40 Mode)\t--AAAAA- = $F000\n\tDC.B $07 ; 4 name table base for scroll B (A=top 3 bits)\t\t\t\t-----AAA = $E000\n\tDC.B $6C ; 5 sprite attribute table base (A=top 7 bits / 6 in H40)\t\t-AAAAAAA = $D800\n\tDC.B $00 ; 6 unused register\t\t\t\t\t\t\t\t\t\t\t--------\n\tDC.B $00 ; 7 background color (P=Palette C=Color)\t\t\t\t\t\t--PPCCCC\n\tDC.B $00 ; 8 unused register\t\t\t\t\t\t\t\t\t\t\t--------\n\tDC.B $00 ; 9 unused register\t\t\t\t\t\t\t\t\t\t\t--------\n\tDC.B $FF ;10 H interrupt register (L=Number of lines)\t\t\t\t\tLLLLLLLL\n\tDC.B $00 ;11 mode register 3\t\t\t\t\t\t\t\t\t\t\t----IVHL\n\tDC.B $81 ;12 mode register 4 (C bits both1 = H40 Cell)\t\t\t\t\tC---SIIC\n\tDC.B $37 ;13 H scroll table base (A=Top 6 bits)\t\t\t\t\t\t\t--AAAAAA = $FC00\n\tDC.B $00 ;14 unused register\t\t\t\t\t\t\t\t\t\t\t--------\n\tDC.B $02 ;15 auto increment (After each Read/Write)\t\t\t\t\t\tNNNNNNNN\n\tDC.B $01 ;16 scroll size (Horiz & Vert size of ScrollA & B)\t\t\t\t--VV--HH = 64x32 tiles\n\tDC.B $00 ;17 window H position (D=Direction C=Cells)\t\t\t\t\tD--CCCCC\n\tDC.B $00 ;18 window V position (D=Direction C=Cells)\t\t\t\t\tD--CCCCC\n\tDC.B $FF ;19 DMA length count low\t\t\t\t\t\t\t\t\t\tLLLLLLLL\n\tDC.B $FF ;20 DMA length count high\t\t\t\t\t\t\t\t\t\tHHHHHHHH\n\tDC.B $00 ;21 DMA source address low\t\t\t\t\t\t\t\t\t\tLLLLLLLL\n\tDC.B $00 ;22 DMA source address mid\t\t\t\t\t\t\t\t\t\tMMMMMMMM\n\tDC.B $80 ;23 DMA source address high (C=CMD)\t\t\t\t\t\t\tCCHHHHHH\nVDPSettingsEnd:\n\teven\n", "language": "68000-Assembly" }, { "code": "BYTE FUNC AtasciiToInternal(CHAR c)\n BYTE c2\n\n c2=c&$7F\n IF c2<32 THEN RETURN (c+64)\n ELSEIF c2<96 THEN RETURN (c-32) FI\nRETURN (c)\n\nPROC CharOut(CARD x BYTE y CHAR c)\n BYTE i,j,v\n CARD addr\n\n addr=$E000+AtasciiToInternal(c)*8\n FOR j=0 TO 7\n DO\n v=Peek(addr) i=8\n WHILE i>0\n DO\n IF (v&1)=0 THEN Color=0\n ELSE Color=1 FI\n Plot(x+i,y+j)\n v=v RSH 1 i==-1\n OD\n addr==+1\n OD\nRETURN\n\nPROC TextOut(CARD x BYTE y CHAR ARRAY text)\n BYTE i\n\n FOR i=1 TO text(0)\n DO\n CharOut(x,y,text(i))\n x==+8\n OD\nRETURN\n\nPROC DrawDigit(BYTE d INT x BYTE y INT dx,dy)\n IF d=1 THEN\n Plot(x,y) DrawTo(x+dx,y)\n ELSEIF d=2 THEN\n Plot(x,y+dy) DrawTo(x+dx,y+dy)\n ELSEIF d=3 THEN\n Plot(x,y) DrawTo(x+dx,y+dy)\n ELSEIF d=4 THEN\n Plot(x,y+dy) DrawTo(x+dx,y)\n ELSEIF d=5 THEN\n Plot(x,y) DrawTo(x+dx,y) DrawTo(x,y+dy)\n ELSEIF d=6 THEN\n Plot(x+dx,y) DrawTo(x+dx,y+dy)\n ELSEIF d=7 THEN\n Plot(x,y) DrawTo(x+dx,y) DrawTo(x+dx,y+dy)\n ELSEIF d=8 THEN\n Plot(x,y+dy) DrawTo(x+dx,y+dy) DrawTo(x+dx,y)\n ELSEIF d=9 THEN\n Plot(x,y) DrawTo(x+dx,y)\n DrawTo(x+dx,y+dy) DrawTo(x,y+dy)\n FI\nRETURN\n\nPROC Cystersian(CARD n INT x BYTE y,s)\n INT ms\n\n ms=-s\n Color=1\n Plot(x+s,y) DrawTo(x+s,y+3*s)\n\n DrawDigit(n MOD 10,x+s,y,s,s)\n n==/10\n DrawDigit(n MOD 10,x+s,y,ms,s)\n n==/10\n DrawDigit(n MOD 10,x+s,y+3*s,s,ms)\n n==/10\n DrawDigit(n MOD 10,x+s,y+3*s,ms,ms)\nRETURN\n\nPROC Test(CARD n INT x BYTE y,s)\n CHAR ARRAY text(5)\n\n StrC(n,text)\n TextOut(x+(2*s-text(0)*8)/2,y-10,text)\n Cystersian(n,x,y,s)\nRETURN\n\nPROC Main()\n CARD ARRAY numbers=[0 1 20 300 4000 5555 6789 6502 1977 2021]\n BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6\n BYTE s=[16],i\n INT x,y\n\n Graphics(8+16)\n COLOR1=$0C\n COLOR2=$02\n\n x=s y=2*s\n FOR i=0 TO 9\n DO\n Test(numbers(i),x,y,s)\n x==+4*s\n IF x>=320-s THEN\n x=s y==+5*s\n FI\n OD\n\n DO UNTIL CH#$FF OD\n CH=$FF\nRETURN\n", "language": "Action-" }, { "code": "BEGIN # draw some Cistercian Numerals #\n\n INT ch = 6; # height of the representation of a Cistercian Numeral #\n INT cw = 5; # width of the representation of a Cistercian Numeral #\n INT cm = ( cw + 1 ) OVER 2; # mid-point of a line in the representation #\n # of a Cistercian Numeral #\n # returns a 5x6 CHAR array representing the Cistercian Nuneral of n #\n # 0 <= m <= 9999 must be TRUE #\n OP TOCISTERCIAN = ( INT n )[,]CHAR:\n IF n < 0 OR n > 9999 THEN # invalid n #\n ( \"?????\", \"?????\", \"?????\", \"?????\", \"?????\", \"?????\" )\n ELSE # n is OK #\n # if ch isn't 6 or cw isn't 5, the strinngs above and below will #\n [ 1 : ch, 1 : cw ]CHAR cn := # need to be adjusted #\n ( \" \", \" | \", \" | \", \" | \", \" | \", \" | \" );\n []STRING t digits = ( #1# \"__\", #2# \";;__\", #3# \"; /;/\"\n , #4# \";\\; \\\", #5# \"__; /;/\", #6# \"; |; |\"\n , #7# \"_; |; |\", #8# \"; |;_|\", #9# \"_; |;_|\"\n );\n []STRING b digits = ( #1# \"__\", #2# \";;__\", #3# \"\\; \\\"\n , #4# \" /;/\", #5# \"_/;/\", #6# \" |; |\"\n , #7# \"_|; |\", #8# \" |; |;_\", #9# \"_|; |;_\"\n );\n # adds 1 digit to the numeral #\n PROC add digit = ( INT digit, BOOL flip horizontal, flip vertical )VOID:\n IF digit > 0 THEN # have a visible digit #\n STRING d = IF flip vertical THEN b digits[ digit ] ELSE t digits[ digit ] FI;\n INT x := IF flip horizontal THEN -1 ELSE 1 FI + cm;\n INT y := IF flip vertical THEN ch ELSE 1 FI;\n INT x init = x;\n INT x step = IF flip horizontal THEN -1 ELSE 1 FI;\n INT y step = IF flip vertical THEN -1 ELSE 1 FI;\n FOR c pos FROM LWB d TO UPB d DO\n CHAR c = d[ c pos ];\n IF c = \";\" THEN\n y +:= y step;\n x := x init\n ELSE\n cn[ y, x ] := IF ( flip horizontal XOR flip vertical ) THEN\n IF c = \"/\" THEN \"\\\" ELIF c = \"\\\" THEN \"/\" ELSE c FI\n ELSE c\n FI;\n x +:= x step\n FI\n OD\n FI # add digit # ;\n INT v := n;\n add digit( v MOD 10, FALSE, FALSE ); v OVERAB 10;\n add digit( v MOD 10, TRUE, FALSE ); v OVERAB 10;\n add digit( v MOD 10, FALSE, TRUE ); v OVERAB 10;\n add digit( v MOD 10, TRUE, TRUE );\n cn\n FI # TOCISTERCIAN # ;\n # inserts a Cistercian Numeral representation of n into an set of lines #\n PROC insert cistercian = ( [,]CHAR cn, REF[]STRING lines, INT pos )VOID:\n FOR i FROM 1 TO ch DO\n lines[ i ][ pos : ( pos + cw ) - 1 ] := STRING( cn[ i, : ] )\n OD # print cistercian # ;\n\n []INT tests = ( 0, 20, 300, 4000, 5555, 6789, 1968 );\n # construct an array of blank lines and insert the Cistercian Numereals #\n [ 1 : ch ]STRING lines; # into them #\n FOR i FROM LWB lines TO UPB lines DO\n lines[ i ] := \" \" * ( ( ( UPB tests -LWB tests ) + 1 ) * ( cw * 2 ) )\n OD;\n FOR i FROM LWB tests TO UPB tests DO print( ( whole( tests[ i ], - cw ), \" \" * cw ) ) OD;\n print( ( newline ) );\n INT i pos := 1 - ( cw * 2 );\n FOR i FROM LWB tests TO UPB tests DO\n insert cistercian( TOCISTERCIAN tests[ i ], lines, i pos +:= cw * 2 )\n OD;\n FOR i FROM LWB lines TO UPB lines DO print( ( lines[ i ], newline ) ) OD\n\nEND\n", "language": "ALGOL-68" }, { "code": "CistercianNumerals(num){\n x := []\n ;UPPER LEFT 0 1 2 3 4 5 6 7 8 9\n x[1, \"UL\"] := [\"000\",\"111\",\"000\",\"000\",\"100\",\"111\",\"100\",\"111\",\"100\",\"111\"]\n x[2, \"UL\"] := [\"000\",\"000\",\"000\",\"001\",\"010\",\"010\",\"100\",\"100\",\"100\",\"100\"]\n x[3, \"UL\"] := [\"000\",\"000\",\"000\",\"010\",\"001\",\"001\",\"100\",\"100\",\"100\",\"100\"]\n x[4, \"UL\"] := [\"000\",\"000\",\"111\",\"100\",\"000\",\"000\",\"100\",\"100\",\"111\",\"111\"]\n\n ;UPPER RIGHT 0 1 2 3 4 5 6 7 8 9\n x[1, \"UR\"] := [\"000\",\"111\",\"000\",\"000\",\"001\",\"111\",\"001\",\"111\",\"001\",\"111\"]\n x[2, \"UR\"] := [\"000\",\"000\",\"000\",\"100\",\"010\",\"010\",\"001\",\"001\",\"001\",\"001\"]\n x[3, \"UR\"] := [\"000\",\"000\",\"000\",\"010\",\"100\",\"100\",\"001\",\"001\",\"001\",\"001\"]\n x[4, \"UR\"] := [\"000\",\"000\",\"111\",\"001\",\"000\",\"000\",\"001\",\"001\",\"111\",\"111\"]\n\n ;BOTTOM LEFT 0 1 2 3 4 5 6 7 8 9\n x[1, \"BL\"] := [\"000\",\"000\",\"111\",\"100\",\"000\",\"000\",\"100\",\"100\",\"111\",\"111\"]\n x[2, \"BL\"] := [\"000\",\"000\",\"000\",\"010\",\"001\",\"001\",\"100\",\"100\",\"100\",\"100\"]\n x[3, \"BL\"] := [\"000\",\"000\",\"000\",\"001\",\"010\",\"010\",\"100\",\"100\",\"100\",\"100\"]\n x[4, \"BL\"] := [\"000\",\"111\",\"000\",\"000\",\"100\",\"111\",\"100\",\"111\",\"100\",\"111\"]\n\n ;BOTTOM RIGHT 0 1 2 3 4 5 6 7 8 9\n x[1, \"BR\"] := [\"000\",\"000\",\"111\",\"001\",\"000\",\"000\",\"001\",\"001\",\"111\",\"111\"]\n x[2, \"BR\"] := [\"000\",\"000\",\"000\",\"010\",\"100\",\"100\",\"001\",\"001\",\"001\",\"001\"]\n x[3, \"BR\"] := [\"000\",\"000\",\"000\",\"100\",\"010\",\"010\",\"001\",\"001\",\"001\",\"001\"]\n x[4, \"BR\"] := [\"000\",\"111\",\"000\",\"000\",\"001\",\"111\",\"001\",\"111\",\"001\",\"111\"]\n\n num := SubStr(\"0000\" num, -3)\n n := StrSplit(num) ; n.1*1000 + n.2*100 + n.3*10 + n.4\n loop 4\n res .= x[A_Index, \"UL\", 1+n.3] . \"1\" . x[A_Index, \"UR\", 1+n.4] . \"`n\"\n loop 4\n res .= \"0001`n\"\n loop 4\n res .= x[A_Index, \"BL\", 1+n.1] . \"1\" . x[A_Index, \"BR\", 1+n.2] . \"`n\"\n res := StrReplace(res, 0, \" \")\n res := StrReplace(res, 1, \"#\")\n return Trim(res, \"`n\")\n}\n", "language": "AutoHotkey" }, { "code": "Gui, font, S24, Consolas\nGui, add, Text, vE1 w150 r12\nGui, show, x0 y0\nfor i, num in [0, 1, 20, 300, 4000, 5555, 6789, 2022]\n{\n GuiControl,, E1, % CistercianNumerals(num)\n MsgBox % num\n}\nreturn\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f CISTERCIAN_NUMERALS.AWK [-v debug={0|1}] [-v xc=anychar] numbers 0-9999 ...\n#\n# example: GAWK -f CISTERCIAN_NUMERALS.AWK 0 1 20 300 4000 5555 6789 1995 10000\n#\n# sorting:\n# PROCINFO[\"sorted_in\"] is used by GAWK\n# SORTTYPE is used by Thompson Automation's TAWK\n#\nBEGIN {\n cistercian_init()\n for (i=1; i<=ARGC-1; i++) {\n cistercian1(ARGV[i])\n }\n exit(0)\n}\nfunction cistercian1(n, i) {\n printf(\"\\n%6s\\n\",n)\n if (!(n ~ /^[0-9]+$/ && length(n) <= 4)) {\n print(\"invalid\")\n return\n }\n n = sprintf(\"%04d\",n)\n cistercian2(2,1,substr(n,3,1),substr(n,4,1))\n for (i=1; i<=5; i++) { # separator between upper and lower parts\n printf(\"%5s%1s%5s\\n\",\"\",xc,\"\")\n }\n cistercian2(4,3,substr(n,1,1),substr(n,2,1))\n}\nfunction cistercian2(i1,i2,n1,n2, i,L,R) {\n for (i=1; i<=5; i++) {\n L = substr(cn_arr[i1][i],n1*6+2,5)\n R = substr(cn_arr[i2][i],n2*6+2,5)\n printf(\"%5s%1s%5s\\n\",L,xc,R)\n }\n}\nfunction cistercian_init( header,i,j,LL,LR,UL,UR) {\n# 1-9 upper-right\n cn_arr[1][++UR] = \":xxxxx: :x : x:xxxxx: x:xxxxx: x:xxxxx:\"\n cn_arr[1][++UR] = \": : : x : x : x : x: x: x: x:\"\n cn_arr[1][++UR] = \": : : x : x : x : x: x: x: x:\"\n cn_arr[1][++UR] = \": : : x : x : x : x: x: x: x:\"\n cn_arr[1][++UR] = \": :xxxxx: x:x :x : x: x:xxxxx:xxxxx:\"\n# 10-90 upper-left\n cn_arr[2][++UL] = \":xxxxx: : x:x :xxxxx:x :xxxxx:x :xxxxx:\"\n cn_arr[2][++UL] = \": : : x : x : x :x :x :x :x :\"\n cn_arr[2][++UL] = \": : : x : x : x :x :x :x :x :\"\n cn_arr[2][++UL] = \": : : x : x : x :x :x :x :x :\"\n cn_arr[2][++UL] = \": :xxxxx:x : x: x:x :x :xxxxx:xxxxx:\"\n# 100-900 lower-right\n cn_arr[3][++LR] = \": :xxxxx: x:x :x : x: x:xxxxx:xxxxx:\"\n cn_arr[3][++LR] = \": : : x : x : x : x: x: x: x:\"\n cn_arr[3][++LR] = \": : : x : x : x : x: x: x: x:\"\n cn_arr[3][++LR] = \": : : x : x : x : x: x: x: x:\"\n cn_arr[3][++LR] = \":xxxxx: :x : x:xxxxx: x:xxxxx: x:xxxxx:\"\n# 1000-9000 lower-left\n cn_arr[4][++LL] = \": :xxxxx:x : x: x:x :x :xxxxx:xxxxx:\"\n cn_arr[4][++LL] = \": : : x : x : x :x :x :x :x :\"\n cn_arr[4][++LL] = \": : : x : x : x :x :x :x :x :\"\n cn_arr[4][++LL] = \": : : x : x : x :x :x :x :x :\"\n cn_arr[4][++LL] = \":xxxxx: : x:x :xxxxx:x :xxxxx:x :xxxxx:\"\n header = \":00000:11111:22222:33333:44444:55555:66666:77777:88888:99999:\"\n PROCINFO[\"sorted_in\"] = \"@ind_str_asc\" ; SORTTYPE = 1\n sub(/^ +/,\"\",xc)\n xc = (xc == \"\") ? \"x\" : substr(xc,1,1) # substitution character\n for (i in cn_arr) {\n for (j in cn_arr[i]) {\n gsub(/x/,xc,cn_arr[i][j]) # change \"x\" to substitution character\n cn_arr[i][j] = sprintf(\":%5s%s\",\"\",cn_arr[i][j]) # add zero column to table\n if (debug == 1) { printf(\"%s %2s %d.%d\\n\",cn_arr[i][j],substr(\"URULLRLL\",i*2-1,2),i,j) }\n }\n }\n if (debug == 1) { printf(\"%s\\n\",header) }\n}\n", "language": "AWK" }, { "code": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n int i, j;\n for (i = 0; i < GRID_SIZE; i++) {\n for (j = 0; j < GRID_SIZE; j++) {\n canvas[i][j] = ' ';\n }\n canvas[i][5] = 'x';\n }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n size_t c;\n for (c = c1; c <= c2; c++) {\n canvas[r][c] = 'x';\n }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n size_t r;\n for (r = r1; r <= r2; r++) {\n canvas[r][c] = 'x';\n }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n size_t c;\n for (c = c1; c <= c2; c++) {\n canvas[r + c - c1][c] = 'x';\n }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n size_t c;\n for (c = c1; c <= c2; c++) {\n canvas[r - c + c1][c] = 'x';\n }\n}\n\nvoid drawOnes(int v) {\n switch (v) {\n case 1:\n horizontal(6, 10, 0);\n break;\n case 2:\n horizontal(6, 10, 4);\n break;\n case 3:\n diagd(6, 10, 0);\n break;\n case 4:\n diagu(6, 10, 4);\n break;\n case 5:\n drawOnes(1);\n drawOnes(4);\n break;\n case 6:\n vertical(0, 4, 10);\n break;\n case 7:\n drawOnes(1);\n drawOnes(6);\n break;\n case 8:\n drawOnes(2);\n drawOnes(6);\n break;\n case 9:\n drawOnes(1);\n drawOnes(8);\n break;\n default:\n break;\n }\n}\n\nvoid drawTens(int v) {\n switch (v) {\n case 1:\n horizontal(0, 4, 0);\n break;\n case 2:\n horizontal(0, 4, 4);\n break;\n case 3:\n diagu(0, 4, 4);\n break;\n case 4:\n diagd(0, 4, 0);\n break;\n case 5:\n drawTens(1);\n drawTens(4);\n break;\n case 6:\n vertical(0, 4, 0);\n break;\n case 7:\n drawTens(1);\n drawTens(6);\n break;\n case 8:\n drawTens(2);\n drawTens(6);\n break;\n case 9:\n drawTens(1);\n drawTens(8);\n break;\n default:\n break;\n }\n}\n\nvoid drawHundreds(int hundreds) {\n switch (hundreds) {\n case 1:\n horizontal(6, 10, 14);\n break;\n case 2:\n horizontal(6, 10, 10);\n break;\n case 3:\n diagu(6, 10, 14);\n break;\n case 4:\n diagd(6, 10, 10);\n break;\n case 5:\n drawHundreds(1);\n drawHundreds(4);\n break;\n case 6:\n vertical(10, 14, 10);\n break;\n case 7:\n drawHundreds(1);\n drawHundreds(6);\n break;\n case 8:\n drawHundreds(2);\n drawHundreds(6);\n break;\n case 9:\n drawHundreds(1);\n drawHundreds(8);\n break;\n default:\n break;\n }\n}\n\nvoid drawThousands(int thousands) {\n switch (thousands) {\n case 1:\n horizontal(0, 4, 14);\n break;\n case 2:\n horizontal(0, 4, 10);\n break;\n case 3:\n diagd(0, 4, 10);\n break;\n case 4:\n diagu(0, 4, 14);\n break;\n case 5:\n drawThousands(1);\n drawThousands(4);\n break;\n case 6:\n vertical(10, 14, 0);\n break;\n case 7:\n drawThousands(1);\n drawThousands(6);\n break;\n case 8:\n drawThousands(2);\n drawThousands(6);\n break;\n case 9:\n drawThousands(1);\n drawThousands(8);\n break;\n default:\n break;\n }\n}\n\nvoid draw(int v) {\n int thousands = v / 1000;\n v %= 1000;\n\n int hundreds = v / 100;\n v %= 100;\n\n int tens = v / 10;\n int ones = v % 10;\n\n if (thousands > 0) {\n drawThousands(thousands);\n }\n if (hundreds > 0) {\n drawHundreds(hundreds);\n }\n if (tens > 0) {\n drawTens(tens);\n }\n if (ones > 0) {\n drawOnes(ones);\n }\n}\n\nvoid write(FILE *out) {\n int i;\n for (i = 0; i < GRID_SIZE; i++) {\n fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n putc('\\n', out);\n }\n}\n\nvoid test(int n) {\n printf(\"%d:\\n\", n);\n initN();\n draw(n);\n write(stdout);\n printf(\"\\n\\n\");\n}\n\nint main() {\n test(0);\n test(1);\n test(20);\n test(300);\n test(4000);\n test(5555);\n test(6789);\n test(9999);\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n Cistercian() {\n initN();\n }\n\n Cistercian(int v) {\n initN();\n draw(v);\n }\n\n Cistercian &operator=(int v) {\n initN();\n draw(v);\n }\n\n friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n FixedSquareGrid<char, 15> canvas;\n\n void initN() {\n for (auto &row : canvas) {\n row.fill(' ');\n row[5] = 'x';\n }\n }\n\n void horizontal(size_t c1, size_t c2, size_t r) {\n for (size_t c = c1; c <= c2; c++) {\n canvas[r][c] = 'x';\n }\n }\n\n void vertical(size_t r1, size_t r2, size_t c) {\n for (size_t r = r1; r <= r2; r++) {\n canvas[r][c] = 'x';\n }\n }\n\n void diagd(size_t c1, size_t c2, size_t r) {\n for (size_t c = c1; c <= c2; c++) {\n canvas[r + c - c1][c] = 'x';\n }\n }\n\n void diagu(size_t c1, size_t c2, size_t r) {\n for (size_t c = c1; c <= c2; c++) {\n canvas[r - c + c1][c] = 'x';\n }\n }\n\n void drawOnes(int v) {\n switch (v) {\n case 1:\n horizontal(6, 10, 0);\n break;\n case 2:\n horizontal(6, 10, 4);\n break;\n case 3:\n diagd(6, 10, 0);\n break;\n case 4:\n diagu(6, 10, 4);\n break;\n case 5:\n drawOnes(1);\n drawOnes(4);\n break;\n case 6:\n vertical(0, 4, 10);\n break;\n case 7:\n drawOnes(1);\n drawOnes(6);\n break;\n case 8:\n drawOnes(2);\n drawOnes(6);\n break;\n case 9:\n drawOnes(1);\n drawOnes(8);\n break;\n default:\n break;\n }\n }\n\n void drawTens(int v) {\n switch (v) {\n case 1:\n horizontal(0, 4, 0);\n break;\n case 2:\n horizontal(0, 4, 4);\n break;\n case 3:\n diagu(0, 4, 4);\n break;\n case 4:\n diagd(0, 4, 0);\n break;\n case 5:\n drawTens(1);\n drawTens(4);\n break;\n case 6:\n vertical(0, 4, 0);\n break;\n case 7:\n drawTens(1);\n drawTens(6);\n break;\n case 8:\n drawTens(2);\n drawTens(6);\n break;\n case 9:\n drawTens(1);\n drawTens(8);\n break;\n default:\n break;\n }\n }\n\n void drawHundreds(int hundreds) {\n switch (hundreds) {\n case 1:\n horizontal(6, 10, 14);\n break;\n case 2:\n horizontal(6, 10, 10);\n break;\n case 3:\n diagu(6, 10, 14);\n break;\n case 4:\n diagd(6, 10, 10);\n break;\n case 5:\n drawHundreds(1);\n drawHundreds(4);\n break;\n case 6:\n vertical(10, 14, 10);\n break;\n case 7:\n drawHundreds(1);\n drawHundreds(6);\n break;\n case 8:\n drawHundreds(2);\n drawHundreds(6);\n break;\n case 9:\n drawHundreds(1);\n drawHundreds(8);\n break;\n default:\n break;\n }\n }\n\n void drawThousands(int thousands) {\n switch (thousands) {\n case 1:\n horizontal(0, 4, 14);\n break;\n case 2:\n horizontal(0, 4, 10);\n break;\n case 3:\n diagd(0, 4, 10);\n break;\n case 4:\n diagu(0, 4, 14);\n break;\n case 5:\n drawThousands(1);\n drawThousands(4);\n break;\n case 6:\n vertical(10, 14, 0);\n break;\n case 7:\n drawThousands(1);\n drawThousands(6);\n break;\n case 8:\n drawThousands(2);\n drawThousands(6);\n break;\n case 9:\n drawThousands(1);\n drawThousands(8);\n break;\n default:\n break;\n }\n }\n\n void draw(int v) {\n int thousands = v / 1000;\n v %= 1000;\n\n int hundreds = v / 100;\n v %= 100;\n\n int tens = v / 10;\n int ones = v % 10;\n\n if (thousands > 0) {\n drawThousands(thousands);\n }\n if (hundreds > 0) {\n drawHundreds(hundreds);\n }\n if (tens > 0) {\n drawTens(tens);\n }\n if (ones > 0) {\n drawOnes(ones);\n }\n }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n for (auto &row : c.canvas) {\n for (auto cell : row) {\n os << cell;\n }\n os << '\\n';\n }\n return os;\n}\n\nint main() {\n for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n std::cout << number << \":\\n\";\n\n Cistercian c(number);\n std::cout << c << '\\n';\n }\n\n return 0;\n}\n", "language": "C++" }, { "code": "import std.stdio;\n\nclass Cistercian {\n private immutable SIZE = 15;\n private char[SIZE][SIZE] canvas;\n\n public this(int n) {\n initN();\n draw(n);\n }\n\n private void initN() {\n foreach (ref row; canvas) {\n row[] = ' ';\n row[5] = 'x';\n }\n }\n\n private void horizontal(int c1, int c2, int r) {\n for (int c = c1; c <= c2; c++) {\n canvas[r][c] = 'x';\n }\n }\n\n private void vertical(int r1, int r2, int c) {\n for (int r = r1; r <= r2; r++) {\n canvas[r][c] = 'x';\n }\n }\n\n private void diagd(int c1, int c2, int r) {\n for (int c = c1; c <= c2; c++) {\n canvas[r + c - c1][c] = 'x';\n }\n }\n\n private void diagu(int c1, int c2, int r) {\n for (int c = c1; c <= c2; c++) {\n canvas[r - c + c1][c] = 'x';\n }\n }\n\n private void draw(int v) {\n auto thousands = v / 1000;\n v %= 1000;\n\n auto hundreds = v / 100;\n v %= 100;\n\n auto tens = v / 10;\n auto ones = v % 10;\n\n drawPart(1000 * thousands);\n drawPart(100 * hundreds);\n drawPart(10 * tens);\n drawPart(ones);\n }\n\n private void drawPart(int v) {\n switch(v) {\n case 0:\n break;\n\n case 1:\n horizontal(6, 10, 0);\n break;\n case 2:\n horizontal(6, 10, 4);\n break;\n case 3:\n diagd(6, 10, 0);\n break;\n case 4:\n diagu(6, 10, 4);\n break;\n case 5:\n drawPart(1);\n drawPart(4);\n break;\n case 6:\n vertical(0, 4, 10);\n break;\n case 7:\n drawPart(1);\n drawPart(6);\n break;\n case 8:\n drawPart(2);\n drawPart(6);\n break;\n case 9:\n drawPart(1);\n drawPart(8);\n break;\n\n case 10:\n horizontal(0, 4, 0);\n break;\n case 20:\n horizontal(0, 4, 4);\n break;\n case 30:\n diagu(0, 4, 4);\n break;\n case 40:\n diagd(0, 4, 0);\n break;\n case 50:\n drawPart(10);\n drawPart(40);\n break;\n case 60:\n vertical(0, 4, 0);\n break;\n case 70:\n drawPart(10);\n drawPart(60);\n break;\n case 80:\n drawPart(20);\n drawPart(60);\n break;\n case 90:\n drawPart(10);\n drawPart(80);\n break;\n\n case 100:\n horizontal(6, 10, 14);\n break;\n case 200:\n horizontal(6, 10, 10);\n break;\n case 300:\n diagu(6, 10, 14);\n break;\n case 400:\n diagd(6, 10, 10);\n break;\n case 500:\n drawPart(100);\n drawPart(400);\n break;\n case 600:\n vertical(10, 14, 10);\n break;\n case 700:\n drawPart(100);\n drawPart(600);\n break;\n case 800:\n drawPart(200);\n drawPart(600);\n break;\n case 900:\n drawPart(100);\n drawPart(800);\n break;\n\n case 1000:\n horizontal(0, 4, 14);\n break;\n case 2000:\n horizontal(0, 4, 10);\n break;\n case 3000:\n diagd(0, 4, 10);\n break;\n case 4000:\n diagu(0, 4, 14);\n break;\n case 5000:\n drawPart(1000);\n drawPart(4000);\n break;\n case 6000:\n vertical(10, 14, 0);\n break;\n case 7000:\n drawPart(1000);\n drawPart(6000);\n break;\n case 8000:\n drawPart(2000);\n drawPart(6000);\n break;\n case 9000:\n drawPart(1000);\n drawPart(8000);\n break;\n\n default:\n import std.conv;\n assert(false, \"Not handled: \" ~ v.to!string);\n }\n }\n\n public void toString(scope void delegate(const(char)[]) sink) const {\n foreach (row; canvas) {\n sink(row);\n sink(\"\\n\");\n }\n }\n}\n\nvoid main() {\n foreach (number; [0, 1, 20, 300, 4000, 5555, 6789, 9999]) {\n writeln(number, ':');\n auto c = new Cistercian(number);\n writeln(c);\n }\n}\n", "language": "D" }, { "code": "proc cist x y n . .\n linewidth 0.5\n dx[] = [ 4 -4 4 -4 ]\n dy[] = [ 4 4 -4 -4 ]\n for i to 4\n dx = dx[i]\n dy = dy[i]\n dy2 = 2 * dy\n d = n mod 10\n n = n div 10\n move x y\n #\n line x y + 8\n move x y - 8\n line x y\n if d = 1\n move x y + dy2\n line x + dx y + dy2\n elif d = 2\n move x y + dy\n line x + dx y + dy\n elif d = 3\n move x y + dy2\n line x + dx y + dy\n elif d = 4\n move x y + dy\n line x + dx y + dy2\n elif d = 5\n move x y + dy\n line x + dx y + dy2\n line x y + dy2\n elif d = 6\n move x + dx y + dy\n line x + dx y + dy2\n elif d = 7\n move x y + dy2\n line x + dx y + dy2\n line x + dx y + dy\n elif d = 8\n move x y + dy\n line x + dx y + dy\n line x + dx y + dy2\n elif d = 9\n move x y + dy\n line x + dx y + dy\n line x + dx y + dy2\n line x y + dy2\n .\n .\n x += 12\n.\nx = 8\nfor n in [ 0 1 20 300 4000 5555 6789 2023 ]\n cist x 80 n\n x += 12\n.\n", "language": "EasyLang" }, { "code": "// Cistercian numerals. Nigel Galloway: February 2nd., 2021\nlet N=[|[[|' ';' ';' '|];[|' ';' ';' '|];[|' ';' ';' '|]];\n [[|'#';'#';'#'|];[|' ';' ';' '|];[|' ';' ';' '|]];\n [[|' ';' ';' '|];[|'#';'#';'#'|];[|' ';' ';' '|]];\n [[|'#';' ';' '|];[|' ';'#';' '|];[|' ';' ';'#'|]];\n [[|' ';' ';'#'|];[|' ';'#';' '|];[|'#';' ';' '|]];\n [[|'#';'#';'#'|];[|' ';'#';' '|];[|'#';' ';' '|]];\n [[|' ';' ';'#'|];[|' ';' ';'#'|];[|' ';' ';'#'|]];\n [[|'#';'#';'#'|];[|' ';' ';'#'|];[|' ';' ';'#'|]];\n [[|' ';' ';'#'|];[|' ';' ';'#'|];[|'#';'#';'#'|]];\n [[|'#';'#';'#'|];[|' ';' ';'#'|];[|'#';'#';'#'|]];|]\n\nlet fN i g e l=N.[l]|>List.iter2(fun n g->printfn \"%sO%s\" ((Array.rev>>System.String)n) (System.String g)) N.[e]\n printfn \" O\"\n N.[g]|>List.rev|>List.iter2(fun n g->printfn \"%sO%s\" ((Array.rev>>System.String)n) (System.String g)) (N.[i]|>List.rev)\n\n[(0,0,0,0);(0,0,0,1);(0,0,2,0);(0,3,0,0);(4,0,0,0);(5,5,5,5);(6,7,8,9)]|>List.iter(fun(i,g,e,l)->printfn \"\\n%d%d%d%d\\n____\" i g e l; fN i g e l)\n", "language": "F-Sharp" }, { "code": "USING: combinators continuations formatting grouping io kernel\nliterals math.order math.text.utils multiline sequences\nsplitting ;\n\nCONSTANT: numerals $[\nHEREDOC: END\n + +-+ + + + + +-+ + + +-+ + + +-+\n | | | |\\ |/ |/ | | | | | | | |\n | | +-+ | + + + | + | + +-+ +-+\n | | | | | | | | | |\n | | | | | | | | | |\n | | | | | | | | | |\n + + + + + + + + + +\nEND\n\"\\n\" split harvest [ 5 group ] map flip\n]\n\n: precedence ( char char -- char )\n 2dup [ CHAR: + = ] either? [ 2drop CHAR: + ] [ max ] if ;\n\n: overwrite ( glyph glyph -- newglyph )\n [ [ precedence ] 2map ] 2map ;\n\n: flip-slashes ( str -- new-str )\n [\n {\n { CHAR: / [ CHAR: \\ ] }\n { CHAR: \\ [ CHAR: / ] }\n [ ]\n } case\n ] map ;\n\n: hflip ( seq -- newseq ) [ reverse flip-slashes ] map ;\n: vflip ( seq -- newseq ) reverse [ flip-slashes ] map ;\n\n: get-digits ( n -- seq ) 1 digit-groups 4 0 pad-tail ;\n\n: check-cistercian ( n -- )\n 0 9999 between? [ \"Must be from 0 to 9999.\" throw ] unless ;\n\n: .cistercian ( n -- )\n [ check-cistercian ] [ \"%d:\\n\" printf ] [ get-digits ] tri\n [ numerals nth ] map\n [ { [ ] [ hflip ] [ vflip ] [ hflip vflip ] } spread ]\n with-datastack [ ] [ overwrite ] map-reduce [ print ] each ;\n\n{ 0 1 20 300 4000 5555 6789 8015 } [ .cistercian nl ] each\n", "language": "Factor" }, { "code": "_window = 1\nbegin enum 1\n _numView\n _numFld\nend enum\n\n_numHeight = 54\n_lineLength = _numHeight/3\n\n\nvoid local fn BuildWindow\n window _window, @\"Cistercian Numerals\",, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + NSWindowStyleMaskMiniaturizable\n subclass view _numView, (237,153,76,94)\n ViewSetFlipped( _numView, YES )\n textfield _numFld,, @\"0\", (237,20,76,21)\n ControlSetAlignment( _numFld, NSTextAlignmentCenter )\n ControlSetFormat( _numFld, @\"0123456789\", YES, 4, 0 )\n WindowMakeFirstResponder( _window, _numFld )\nend fn\n\n\nvoid local fn PathDraw( path as BezierPathRef, lines as CFStringRef, x as CGFloat, y as CGFloat )\n CGPoint pt1, pt2\n long i\n for i = 0 to 4\n if ( intval(mid(lines,i,1)) )\n select ( i )\n case 0\n pt1 = fn CGPointMake( x + _lineLength, y )\n pt2 = fn CGPointMake( x + _lineLength, y + _lineLength )\n case 1\n pt1 = fn CGPointMake( x, y + _lineLength )\n pt2 = fn CGPointMake( x + _lineLength, y )\n case 2\n pt1 = fn CGPointMake( x, y )\n pt2 = fn CGPointMake( x + _lineLength, y + _lineLength )\n case 3\n pt1 = fn CGPointMake( x, y + _lineLength )\n pt2 = fn CGPointMake( x + _lineLength, y + _lineLength )\n case 4\n pt1 = fn CGPointMake( x, y )\n pt2 = fn CGPointMake( x + _lineLength, y )\n end select\n BezierPathMoveToPoint( path, pt1 )\n BezierPathLineToPoint( path, pt2 )\n end if\n next\nend fn\n\n\nvoid local fn ViewDrawRect\n CFArrayRef lines = @[@\"00001\",@\"00010\",@\"00100\",@\"01000\",@\"01001\",@\"10000\",@\"10001\",@\"10010\",@\"10011\"]\n CFStringRef numString = fn ViewProperty( _numView, @\"num\" )\n if ( numString )\n CGFloat x = 38, y = 20\n\n long i\n for i = 0 to 3\n BezierPathRef path = fn BezierPathWithRect( fn ViewBounds(_numView) )\n BezierPathMoveToPoint( path, fn CGPointMake( x, y ) )\n BezierPathLineToPoint( path, fn CGPointMake( x, y + _numHeight ) )\n\n long num = intval( mid( numString, i, 1 ) )\n if ( num )\n fn PathDraw( path, lines[num-1], x, y )\n if ( i < 3 )\n CGFloat xScale = 1.0, yScale = 1.0\n select ( i )\n case 0 : xScale = -1.0 : yScale = -1.0 // 1000\n case 1 : yScale = -1.0 // 100\n case 2 : xScale = -1.0 // 10\n end select\n\n CGRect bounds = fn BezierPathBounds( path )\n AffineTransformRef tx = fn AffineTransformInit\n AffineTransformScaleXY( tx, xScale, yScale )\n if ( xScale < 0.0 ) then AffineTransformTranslate( tx, -bounds.origin.x-bounds.size.width, 0.0 )\n if ( yScale < 0.0 ) then AffineTransformTranslate( tx, 0.0, -bounds.size.height )\n\n BezierPathTransformUsingAffineTranform( path, tx )\n end if\n end if\n\n BezierPathStroke( path )\n next\n end if\nend fn\n\n\nvoid local fn DrawAction\n CFStringRef string = fn StringWithFormat( @\"%.4ld\", fn ControlIntegerValue( _numFld ) )\n ViewSetProperty( _numView, @\"num\", string )\n ViewSetNeedsDisplay( _numView )\nend fn\n\n\nvoid local fn DoAppEvent( ev as long )\n select ( ev )\n case _appDidFinishLaunching\n fn BuildWindow\n fn DrawAction\n case _appShouldTerminateAfterLastWindowClosed : AppEventSetBool(YES)\n end select\nend fn\n\n\nvoid local fn DoDialog( ev as long, tag as long, wnd as long )\n select ( ev )\n case _btnClick\n select ( tag )\n case _numFld : fn DrawAction\n end select\n\n case _viewDrawRect\n select ( tag )\n case _numView : fn ViewDrawRect\n end select\n end select\nend fn\n\n\non appevent fn DoAppEvent\non dialog fn DoDialog\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n for i := 0; i < 15; i++ {\n n[i] = make([]string, 11)\n for j := 0; j < 11; j++ {\n n[i][j] = \" \"\n }\n n[i][5] = \"x\"\n }\n}\n\nfunc horiz(c1, c2, r int) {\n for c := c1; c <= c2; c++ {\n n[r][c] = \"x\"\n }\n}\n\nfunc verti(r1, r2, c int) {\n for r := r1; r <= r2; r++ {\n n[r][c] = \"x\"\n }\n}\n\nfunc diagd(c1, c2, r int) {\n for c := c1; c <= c2; c++ {\n n[r+c-c1][c] = \"x\"\n }\n}\n\nfunc diagu(c1, c2, r int) {\n for c := c1; c <= c2; c++ {\n n[r-c+c1][c] = \"x\"\n }\n}\n\nvar draw map[int]func() // map contains recursive closures\n\nfunc initDraw() {\n draw = map[int]func(){\n 1: func() { horiz(6, 10, 0) },\n 2: func() { horiz(6, 10, 4) },\n 3: func() { diagd(6, 10, 0) },\n 4: func() { diagu(6, 10, 4) },\n 5: func() { draw[1](); draw[4]() },\n 6: func() { verti(0, 4, 10) },\n 7: func() { draw[1](); draw[6]() },\n 8: func() { draw[2](); draw[6]() },\n 9: func() { draw[1](); draw[8]() },\n\n 10: func() { horiz(0, 4, 0) },\n 20: func() { horiz(0, 4, 4) },\n 30: func() { diagu(0, 4, 4) },\n 40: func() { diagd(0, 4, 0) },\n 50: func() { draw[10](); draw[40]() },\n 60: func() { verti(0, 4, 0) },\n 70: func() { draw[10](); draw[60]() },\n 80: func() { draw[20](); draw[60]() },\n 90: func() { draw[10](); draw[80]() },\n\n 100: func() { horiz(6, 10, 14) },\n 200: func() { horiz(6, 10, 10) },\n 300: func() { diagu(6, 10, 14) },\n 400: func() { diagd(6, 10, 10) },\n 500: func() { draw[100](); draw[400]() },\n 600: func() { verti(10, 14, 10) },\n 700: func() { draw[100](); draw[600]() },\n 800: func() { draw[200](); draw[600]() },\n 900: func() { draw[100](); draw[800]() },\n\n 1000: func() { horiz(0, 4, 14) },\n 2000: func() { horiz(0, 4, 10) },\n 3000: func() { diagd(0, 4, 10) },\n 4000: func() { diagu(0, 4, 14) },\n 5000: func() { draw[1000](); draw[4000]() },\n 6000: func() { verti(10, 14, 0) },\n 7000: func() { draw[1000](); draw[6000]() },\n 8000: func() { draw[2000](); draw[6000]() },\n 9000: func() { draw[1000](); draw[8000]() },\n }\n}\n\nfunc printNumeral() {\n for i := 0; i < 15; i++ {\n for j := 0; j < 11; j++ {\n fmt.Printf(\"%s \", n[i][j])\n }\n fmt.Println()\n }\n fmt.Println()\n}\n\nfunc main() {\n initDraw()\n numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n for _, number := range numbers {\n initN()\n fmt.Printf(\"%d:\\n\", number)\n thousands := number / 1000\n number %= 1000\n hundreds := number / 100\n number %= 100\n tens := number / 10\n ones := number % 10\n if thousands > 0 {\n draw[thousands*1000]()\n }\n if hundreds > 0 {\n draw[hundreds*100]()\n }\n if tens > 0 {\n draw[tens*10]()\n }\n if ones > 0 {\n draw[ones]()\n }\n printNumeral()\n }\n}\n", "language": "Go" }, { "code": "NB. http://rosettacode.org/wiki/Cistercian_numerals\nNB. converted from\nNB. https://scipython.com/blog/cistercian-numerals/\n\nDyad=: [: :\n\nNB. numeric_vector format 'python {} string'\nformat=: ''&$: :([: ; (a: , [: \":&.> [) ,. '{}' ([ (E. <@}.;._1 ]) ,) ]) NB. literals x should be boxed\n\npwd=:1!:43\nrm=: 1!:55@boxopen ::empty\nprint=: echo@[ NB. debug\nprint=: (1!:3~,&LF)~ Dyad\nopen=: 1!:21\nclose=: 1!:22\n\nNB.# http://en.kpartner.kr/data/warrant-check-pzmwqyk/qrf56.php?3fff1d=cistercian-numbers-unicode\nNB.\nNB.# The paths to create the digits 1–9 in the \"units\" position.\nNB.d_paths = {\nNB.(0, 1): ((1, 0), (2, 0)),\nNB.(0, 2): ((1, 1), (2, 1)),\nNB.(0, 3): ((1, 0), (2, 1)),\nNB.(0, 4): ((1, 1), (2, 0)),\nNB.(0, 5): ((1, 1), (2, 0), (1, 0)),\nNB.(0, 6): ((2, 0), (2, 1)),\nNB.(0, 7): ((1, 0), (2, 0), (2, 1)),\nNB.(0, 8): ((1, 1), (2, 1), (2, 0)),\nNB.(0, 9): ((1, 1), (2, 1), (2, 0), (1, 0)),\nNB.}\nNB.# Generate the paths for the digits in the 10s, 100s and 1000s position by\nNB.# reflection.\nNB.for i in range(1, 10):\nNB. d_paths[(1, i)] = [(2-x, y) for x, y in d_paths[(0, i)]]\nNB. d_paths[(2, i)] = [(x, 3-y) for x, y in d_paths[(0, i)]]\nNB. d_paths[(3, i)] = [(2-x, 3-y) for x, y in d_paths[(0, i)]]\nNB.\nd_paths=: _2[\\L:0]((1, 0), (2, 0));((1, 1), (2, 1));((1, 0), (2, 1));((1, 1), (2, 0));((1, 1), (2, 0), (1, 0));((2, 0), (2, 1));((1, 0), (2, 0), (2, 1));((1, 1), (2, 1), (2, 0));((1, 1), (2, 1), (2, 0), (1, 0))\nd_paths=: (, ((2-[),])/\"1 L:0 , (,3&-)/\"1 L:0 , ((2-[),(3-]))/\"1 L:0) d_paths\nd_paths=: , a: ,. _9]\\ d_paths NB. adjust indexing\nNB.echo d_paths NB. test\n\nNB.def transform(x, y, dx, dy, sc):\nNB. \"\"\"Transform the coordinates (x, y) into the scaled, displaced system.\"\"\"\nNB. return x*sc + dx, y*sc + dy\nNB.\ntransform=: (] p.~ [: (2&{. (,.) 2 $ 2&}.) [) Dyad NB. (dx dy sx [sy]) transform (x y)\n\nNB.def get_path(i, d):\nNB. \"\"\"Return the SVG path to render the digit d in decimal position i.\"\"\"\nNB. if d == 0:\nNB. return\nNB. path = d_paths[(i, d)]\nNB. return 'M{},{} '.format(*transform(*path[0], *tprms)) + ' '.join(\nNB. ['L{},{}'.format(*transform(*xy, *tprms)) for xy in path[1:]])\nNB.\nget_path=: 3 :0\n 'i d'=. y\n if. d do.\n path=. d_paths {::~ 10 #. y\n result=. 'M{},{} 'format~ TPRMS transform {. path\n result=. result , }: , ' ' ,.~ 'L{},{}'format\"1~TPRMS transform\"1 }. path\n else.\n ''\n end.\n)\n\nNB.def make_digit(i, d):\nNB. \"\"\"Output the SVG path element for digit d in decimal position i.\"\"\"\nNB. print('<path d=\"{}\"/>'.format(get_path(i, d)), file=fo)\nNB.\nmake_digit=: (print~ (('<path d=\"{}\"/>') (format~ <) get_path)) Dyad NB. fo make_digit n\n\nNB.def make_stave():\nNB. \"\"\"Output the SVG line element for the vertical stave.\"\"\"\nNB. x1, y1 = transform(1, 0, *tprms)\nNB. x2, y2 = transform(1, 3, *tprms)\nNB. print('<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\"/>'.format(x1, y1, x2, y2),\nNB. file=fo)\nmake_stave=: 3 :'y print~ ''<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\"/>'' format~ , TPRMS (transform\"1) 1 0,:1 3'\n\nNB.def svg_preamble(fo):\nNB. \"\"\"Write the SVG preamble, including the styles.\"\"\"\nNB.\nNB. # Set the path stroke-width appropriate to the scale.\nNB. stroke_width = max(1.5, tprms[2] / 5)\nNB. print(\"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\nNB.<svg xmlns=\"http://www.w3.org/2000/svg\"\nNB. xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"2000\" height=\"2005\" >\nNB.<defs>\nNB.<style type=\"text/css\"><![CDATA[\nNB.line, path {\nNB. stroke: black;\nNB. stroke-width: %d;\nNB. stroke-linecap: square;\nNB.}\nNB.path {\nNB. fill: none;\nNB.}\nNB.]]>\nNB.</style>\nNB.</defs>\nNB.\"\"\" % stroke_width, file=fo)\nNB.\nPREAMBLE=: 0 :0\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\"\n xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"2000\" height=\"2005\" >\n<defs>\n<style type=\"text/css\"><![CDATA[\nline, path {\n stroke: black;\n stroke-width: {};\n stroke-linecap: square;\n}\npath {\n fill: none;\n}\n]]>\n</style>\n</defs>\n)\n\nsvg_preamble=: 3 :'(PREAMBLE format~ 1.5 >. 5 *inv 2 { TPRMS) print y'\n\nNB.def make_numeral(n, fo):\nNB. \"\"\"Output the SVG for the number n using the current transform.\"\"\"\nNB. make_stave()\nNB. for i, s_d in enumerate(str(n)[::-1]):\nNB. make_digit(i, int(s_d))\nNB.\nmake_numeral=: 4 :0\n fo=. x\n n=. y\n make_stave fo\n if. y do.\n fo make_digit\"1 (,.~ i.@#) |. 10 #.inv n\n end.\n)\n\nNB.# Transform parameters: dx, dy, scale.\nNB.tprms = [5, 5, 5]\nNB.\nNB.with open('all_cistercian_numerals.svg', 'w') as fo:\nNB. svg_preamble(fo)\nNB. for i in range(10000):\nNB. # Locate this number at the position dx, dy = tprms[:2].\nNB. tprms[0] = 15 * (i % 125) + 5\nNB. tprms[1] = 25 * (i // 125) + 5\nNB. make_numeral(i, fo)\nNB. print(\"\"\"</svg>\"\"\", file=fo)\nmain=: 3 :0 ::('Use: main ''filename.svg'''\"_)\n TPRMS=: 5 5 5\n rm<y\n fo=. open<y\n svg_preamble fo\n for_i. i. 10000 do.\n TPRMS=: (5 ,~ (5 + 15 * 125 | ]) , 5 + 25 * [: (<.) 125 *^:_1 ]) i\n fo make_numeral i\n end.\n '</svg>' print fo\n empty close fo\n 'open browser to {}/{}' format~ (pwd'') ; y\n)\nrc=: 3 :0 ::('Use: rc ''filename.svg'''\"_)\n scale=. 5\n TPRMS=: 5 5 , scale\n rm<y\n fo=. open<y\n svg_preamble fo\n RC=. 0 1 20 300 666 4000 5555 6789\n echo 'writing {}' format~ < RC\n for_k. (,.~ i.@#) RC do.\n 'j i'=. k\n TPRMS=: (scale ,~ (5 + scale * 15 * 125 | ]) , 5 + scale * 25 * [: (<.) 125 *^:_1 ]) j\n fo make_numeral i\n end.\n '</svg>' print fo\n empty close fo\n 'open browser to {}{}{}' format~ (pwd'') ; PATHJSEP_j_ ; y\n)\n", "language": "J" }, { "code": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n private static final int SIZE = 15;\n private final char[][] canvas = new char[SIZE][SIZE];\n\n public Cistercian(int n) {\n initN();\n draw(n);\n }\n\n public void initN() {\n for (var row : canvas) {\n Arrays.fill(row, ' ');\n row[5] = 'x';\n }\n }\n\n private void horizontal(int c1, int c2, int r) {\n for (int c = c1; c <= c2; c++) {\n canvas[r][c] = 'x';\n }\n }\n\n private void vertical(int r1, int r2, int c) {\n for (int r = r1; r <= r2; r++) {\n canvas[r][c] = 'x';\n }\n }\n\n private void diagd(int c1, int c2, int r) {\n for (int c = c1; c <= c2; c++) {\n canvas[r + c - c1][c] = 'x';\n }\n }\n\n private void diagu(int c1, int c2, int r) {\n for (int c = c1; c <= c2; c++) {\n canvas[r - c + c1][c] = 'x';\n }\n }\n\n private void draw(int v) {\n var thousands = v / 1000;\n v %= 1000;\n\n var hundreds = v / 100;\n v %= 100;\n\n var tens = v / 10;\n var ones = v % 10;\n\n drawPart(1000 * thousands);\n drawPart(100 * hundreds);\n drawPart(10 * tens);\n drawPart(ones);\n }\n\n private void drawPart(int v) {\n switch (v) {\n case 1:\n horizontal(6, 10, 0);\n break;\n case 2:\n horizontal(6, 10, 4);\n break;\n case 3:\n diagd(6, 10, 0);\n break;\n case 4:\n diagu(6, 10, 4);\n break;\n case 5:\n drawPart(1);\n drawPart(4);\n break;\n case 6:\n vertical(0, 4, 10);\n break;\n case 7:\n drawPart(1);\n drawPart(6);\n break;\n case 8:\n drawPart(2);\n drawPart(6);\n break;\n case 9:\n drawPart(1);\n drawPart(8);\n break;\n\n case 10:\n horizontal(0, 4, 0);\n break;\n case 20:\n horizontal(0, 4, 4);\n break;\n case 30:\n diagu(0, 4, 4);\n break;\n case 40:\n diagd(0, 4, 0);\n break;\n case 50:\n drawPart(10);\n drawPart(40);\n break;\n case 60:\n vertical(0, 4, 0);\n break;\n case 70:\n drawPart(10);\n drawPart(60);\n break;\n case 80:\n drawPart(20);\n drawPart(60);\n break;\n case 90:\n drawPart(10);\n drawPart(80);\n break;\n\n case 100:\n horizontal(6, 10, 14);\n break;\n case 200:\n horizontal(6, 10, 10);\n break;\n case 300:\n diagu(6, 10, 14);\n break;\n case 400:\n diagd(6, 10, 10);\n break;\n case 500:\n drawPart(100);\n drawPart(400);\n break;\n case 600:\n vertical(10, 14, 10);\n break;\n case 700:\n drawPart(100);\n drawPart(600);\n break;\n case 800:\n drawPart(200);\n drawPart(600);\n break;\n case 900:\n drawPart(100);\n drawPart(800);\n break;\n\n case 1000:\n horizontal(0, 4, 14);\n break;\n case 2000:\n horizontal(0, 4, 10);\n break;\n case 3000:\n diagd(0, 4, 10);\n break;\n case 4000:\n diagu(0, 4, 14);\n break;\n case 5000:\n drawPart(1000);\n drawPart(4000);\n break;\n case 6000:\n vertical(10, 14, 0);\n break;\n case 7000:\n drawPart(1000);\n drawPart(6000);\n break;\n case 8000:\n drawPart(2000);\n drawPart(6000);\n break;\n case 9000:\n drawPart(1000);\n drawPart(8000);\n break;\n\n }\n }\n\n @Override\n public String toString() {\n StringBuilder builder = new StringBuilder();\n for (var row : canvas) {\n builder.append(row);\n builder.append('\\n');\n }\n return builder.toString();\n }\n\n public static void main(String[] args) {\n for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n System.out.printf(\"%d:\\n\", number);\n var c = new Cistercian(number);\n System.out.println(c);\n }\n }\n}\n", "language": "Java" }, { "code": "// html\ndocument.write(`\n <p><input id=\"num\" type=\"number\" min=\"0\" max=\"9999\" value=\"0\" onchange=\"showCist()\"></p>\n <p><canvas id=\"cist\" width=\"200\" height=\"300\"></canvas></p>\n <p> <!-- EXAMPLES (can be deleted for normal use) -->\n <button onclick=\"set(0)\">0</button>\n <button onclick=\"set(1)\">1</button>\n <button onclick=\"set(20)\">20</button>\n <button onclick=\"set(300)\">300</button>\n <button onclick=\"set(4000)\">4000</button>\n <button onclick=\"set(5555)\">5555</button>\n <button onclick=\"set(6789)\">6789</button>\n <button onclick=\"set(Math.floor(Math.random()*1e4))\">Random</button>\n </p>\n`);\n\n// to show given examples\n// can be deleted for normal use\nfunction set(num) {\n document.getElementById('num').value = num;\n showCist();\n}\n\nconst SW = 10; // stroke width\nlet canvas = document.getElementById('cist'),\n cx = canvas.getContext('2d');\n\nfunction showCist() {\n // reset canvas\n cx.clearRect(0, 0, canvas.width, canvas.height);\n cx.lineWidth = SW;\n cx.beginPath();\n cx.moveTo(100, 0+.5*SW);\n cx.lineTo(100, 300-.5*SW);\n cx.stroke();\n\n let num = document.getElementById('num').value;\n while (num.length < 4) num = '0' + num; // fills leading zeros to $num\n\n /***********************\\\n | POINTS: |\n | ********************* |\n | |\n | a --- b --- c |\n | | | | |\n | d --- e --- f |\n | | | | |\n | g --- h --- i |\n | | | | |\n | j --- k --- l |\n | |\n \\***********************/\n let\n a = [0+SW, 0+SW], b = [100, 0+SW], c = [200-SW, 0+SW],\n d = [0+SW, 100], e = [100, 100], f = [200-SW, 100],\n g = [0+SW, 200], h = [100, 200], i = [200-SW, 200],\n j = [0+SW, 300-SW], k = [100, 300-SW], l = [200-SW, 300-SW];\n\n function draw() {\n let x = 1;\n cx.beginPath();\n cx.moveTo(arguments[0][0], arguments[0][1]);\n while (x < arguments.length) {\n cx.lineTo(arguments[x][0], arguments[x][1]);\n x++;\n }\n cx.stroke();\n }\n\n // 1000s\n switch (num[0]) {\n case '1': draw(j, k); break; case '2': draw(g, h); break;\n case '3': draw(g, k); break; case '4': draw(j, h); break;\n case '5': draw(k, j, h); break; case '6': draw(g, j); break;\n case '7': draw(g, j, k); break; case '8': draw(j, g, h); break;\n case '9': draw(h, g, j, k); break;\n }\n // 100s\n switch (num[1]) {\n case '1': draw(k, l); break; case '2': draw(h, i); break;\n case '3': draw(k, i); break; case '4': draw(h, l); break;\n case '5': draw(h, l, k); break; case '6': draw(i, l); break;\n case '7': draw(k, l, i); break; case '8': draw(h, i, l); break;\n case '9': draw(h, i, l, k); break;\n }\n // 10s\n switch (num[2]) {\n case '1': draw(a, b); break; case '2': draw(d, e); break;\n case '3': draw(d, b); break; case '4': draw(a, e); break;\n case '5': draw(b, a, e); break; case '6': draw(a, d); break;\n case '7': draw(d, a, b); break; case '8': draw(a, d, e); break;\n case '9': draw(b, a, d, e); break;\n }\n // 1s\n switch (num[3]) {\n case '1': draw(b, c); break; case '2': draw(e, f); break;\n case '3': draw(b, f); break; case '4': draw(e, c); break;\n case '5': draw(b, c, e); break; case '6': draw(c, f); break;\n case '7': draw(b, c, f); break; case '8': draw(e, f, c); break;\n case '9': draw(b, c, f, e); break;\n }\n}\n", "language": "JavaScript" }, { "code": "### Generic function\n# Replace whatever is at .[$i:$i+1] with $x.\n# The input and $x should be of the same type - strings or arrays.\ndef replace($i; $x): .[:$i] + $x + .[$i+1:];\n\n### Cistercian numerals\n\n# The canvas: an array of strings\ndef canvas:\n (\" \" * 11) as $row\n | [range(0; 15) | $row | replace(5; \"x\")];\n\ndef horiz($c1; $c2; $r):\n reduce range($c1; $c2+1) as $c (.; .[$r] |= replace($c; \"x\"));\n\ndef verti($r1; $r2; $c):\n reduce range($r1; $r2+1) as $r (.; .[$r] |= replace($c; \"x\"));\n\ndef diagd($c1; $c2; $r):\n reduce range($c1; $c2+1) as $c (.; .[$r+$c-$c1] |= replace($c;\"x\"));\n\ndef diagu($c1; $c2; $r):\n reduce range($c1; $c2+1) as $c (.; .[$r-$c+$c1] |= replace($c; \"x\"));\n\n# input: the canvas\ndef draw($n):\n if $n == 0 then .\n elif $n == 1 then horiz(6; 10; 0)\n elif $n == 2 then horiz(6; 10; 4)\n elif $n == 3 then diagd(6; 10; 0)\n elif $n == 4 then diagu(6; 10; 4)\n elif $n == 5 then draw(1) | draw(4)\n elif $n == 6 then verti(0; 4; 10)\n elif $n == 7 then draw(1) | draw(6)\n elif $n == 8 then draw(2) | draw(6)\n elif $n == 9 then draw(1) | draw(8)\n elif $n == 10 then horiz(0; 4; 0)\n elif $n == 20 then horiz(0; 4; 4)\n elif $n == 30 then diagu(0; 4; 4)\n elif $n == 40 then diagd(0; 4; 0)\n elif $n == 50 then draw(10) | draw(40)\n elif $n == 60 then verti(0; 4; 0)\n elif $n == 70 then draw(10) | draw(60)\n elif $n == 80 then draw(20) | draw(60)\n elif $n == 90 then draw(10) | draw(80)\n elif $n == 100 then horiz(6; 10; 14)\n elif $n == 200 then horiz(6; 10; 10)\n elif $n == 300 then diagu(6; 10; 14)\n elif $n == 400 then diagd(6; 10; 10)\n elif $n == 500 then draw(100) | draw(400)\n elif $n == 600 then verti(10; 14; 10)\n elif $n == 700 then draw(100) | draw(600)\n elif $n == 800 then draw(200) | draw(600)\n elif $n == 900 then draw(100) | draw(800)\n elif $n == 1000 then horiz(0; 4; 14)\n elif $n == 2000 then horiz(0; 4; 10)\n elif $n == 3000 then diagd(0; 4; 10)\n elif $n == 4000 then diagu(0; 4; 14)\n elif $n == 5000 then draw(1000) | draw(4000)\n elif $n == 6000 then verti(10; 14; 0)\n elif $n == 7000 then draw(1000) | draw(6000)\n elif $n == 8000 then draw(2000) | draw(6000)\n elif $n == 9000 then draw(1000) | draw(8000)\n else \"unable to draw \\(.)\" | error\n end;\n\ndef cistercian:\n (./1000|floor) as $thousands\n | (. % 1000) as $n\n | ($n/100|floor) as $hundreds\n | ($n % 100) as $n\n | ($n/10|floor) as $tens\n | ($n % 10) as $ones\n | \"\\(.):\",\n ( canvas\n | draw($thousands*1000)\n | draw($hundreds*100)\n | draw($tens*10)\n | draw($ones)\n | .[] ),\n \"\" ;\n\n0, 1, 20, 300, 4000, 5555, 6789, 9999\n| cistercian\n", "language": "Jq" }, { "code": "using Gtk, Cairo\n\nconst can = GtkCanvas(800, 100)\nconst win = GtkWindow(can, \"Canvas\")\nconst numbers = [0, 1, 20, 300, 4000, 5555, 6789, 8123]\n\nfunction drawcnum(ctx, xypairs)\n move_to(ctx, xypairs[1][1], xypairs[1][2])\n for p in xypairs[2:end]\n line_to(ctx, p[1], p[2])\n end\n stroke(ctx)\nend\n\n@guarded draw(can) do widget\n ctx = getgc(can)\n hlen, wlen, len = height(can), width(can), length(numbers)\n halfwspan, thirdcolspan, voffset = wlen ÷ (len * 2), wlen ÷ (len * 3), hlen ÷ 8\n set_source_rgb(ctx, 0, 0, 2550)\n for (i, n) in enumerate(numbers)\n # paint vertical as width 2 rectangle\n x = halfwspan * (2 * i - 1)\n rectangle(ctx, x, voffset, 2, hlen - 2 * voffset)\n stroke(ctx)\n # determine quadrant and draw numeral lines there\n dig = [(10^(i - 1), m) for (i, m) in enumerate(digits(n))]\n for (d, m) in dig\n y, dx, dy = (d == 1) ? (voffset, thirdcolspan, thirdcolspan) :\n (d == 10) ? (voffset, -thirdcolspan, thirdcolspan) :\n (d == 100) ? (hlen - voffset, thirdcolspan, -thirdcolspan) :\n (hlen - voffset, -thirdcolspan, -thirdcolspan)\n m == 1 && drawcnum(ctx, [[x, y], [x + dx, y]])\n m == 2 && drawcnum(ctx, [[x, y + dy], [x + dx, y + dy]])\n m == 3 && drawcnum(ctx, [[x, y], [x + dx, y + dy]])\n m == 4 && drawcnum(ctx, [[x, y + dy], [x + dx, y]])\n m == 5 && drawcnum(ctx, [[x, y + dy], [x + dx, y], [x, y]])\n m == 6 && drawcnum(ctx, [[x + dx, y], [x + dx, y + dy]])\n m == 7 && drawcnum(ctx, [[x, y], [x + dx, y], [x + dx, y + dy]])\n m == 8 && drawcnum(ctx, [[x, y + dy], [x + dx, y + dy], [x + dx, y]])\n m == 9 && drawcnum(ctx, [[x, y], [x + dx, y], [x + dx, y + dy], [x, y + dy]])\n end\n move_to(ctx, x - halfwspan ÷ 6, hlen - 4)\n Cairo.show_text(ctx, string(n))\n stroke(ctx)\n end\nend\n\nfunction mooncipher()\n draw(can)\n cond = Condition()\n endit(w) = notify(cond)\n signal_connect(endit, win, :destroy)\n show(can)\n wait(cond)\nend\n\nmooncipher()\n", "language": "Julia" }, { "code": "import java.io.StringWriter\n\nclass Cistercian() {\n constructor(number: Int) : this() {\n draw(number)\n }\n\n private val size = 15\n private var canvas = Array(size) { Array(size) { ' ' } }\n\n init {\n initN()\n }\n\n private fun initN() {\n for (row in canvas) {\n row.fill(' ')\n row[5] = 'x'\n }\n }\n\n private fun horizontal(c1: Int, c2: Int, r: Int) {\n for (c in c1..c2) {\n canvas[r][c] = 'x'\n }\n }\n\n private fun vertical(r1: Int, r2: Int, c: Int) {\n for (r in r1..r2) {\n canvas[r][c] = 'x'\n }\n }\n\n private fun diagd(c1: Int, c2: Int, r: Int) {\n for (c in c1..c2) {\n canvas[r + c - c1][c] = 'x'\n }\n }\n\n private fun diagu(c1: Int, c2: Int, r: Int) {\n for (c in c1..c2) {\n canvas[r - c + c1][c] = 'x'\n }\n }\n\n private fun drawPart(v: Int) {\n when (v) {\n 1 -> {\n horizontal(6, 10, 0)\n }\n 2 -> {\n horizontal(6, 10, 4)\n }\n 3 -> {\n diagd(6, 10, 0)\n }\n 4 -> {\n diagu(6, 10, 4)\n }\n 5 -> {\n drawPart(1)\n drawPart(4)\n }\n 6 -> {\n vertical(0, 4, 10)\n }\n 7 -> {\n drawPart(1)\n drawPart(6)\n }\n 8 -> {\n drawPart(2)\n drawPart(6)\n }\n 9 -> {\n drawPart(1)\n drawPart(8)\n }\n\n 10 -> {\n horizontal(0, 4, 0)\n }\n 20 -> {\n horizontal(0, 4, 4)\n }\n 30 -> {\n diagu(0, 4, 4)\n }\n 40 -> {\n diagd(0, 4, 0)\n }\n 50 -> {\n drawPart(10)\n drawPart(40)\n }\n 60 -> {\n vertical(0, 4, 0)\n }\n 70 -> {\n drawPart(10)\n drawPart(60)\n }\n 80 -> {\n drawPart(20)\n drawPart(60)\n }\n 90 -> {\n drawPart(10)\n drawPart(80)\n }\n\n 100 -> {\n horizontal(6, 10, 14)\n }\n 200 -> {\n horizontal(6, 10, 10)\n }\n 300 -> {\n diagu(6, 10, 14)\n }\n 400 -> {\n diagd(6, 10, 10)\n }\n 500 -> {\n drawPart(100)\n drawPart(400)\n }\n 600 -> {\n vertical(10, 14, 10)\n }\n 700 -> {\n drawPart(100)\n drawPart(600)\n }\n 800 -> {\n drawPart(200)\n drawPart(600)\n }\n 900 -> {\n drawPart(100)\n drawPart(800)\n }\n\n 1000 -> {\n horizontal(0, 4, 14)\n }\n 2000 -> {\n horizontal(0, 4, 10)\n }\n 3000 -> {\n diagd(0, 4, 10)\n }\n 4000 -> {\n diagu(0, 4, 14)\n }\n 5000 -> {\n drawPart(1000)\n drawPart(4000)\n }\n 6000 -> {\n vertical(10, 14, 0)\n }\n 7000 -> {\n drawPart(1000)\n drawPart(6000)\n }\n 8000 -> {\n drawPart(2000)\n drawPart(6000)\n }\n 9000 -> {\n drawPart(1000)\n drawPart(8000)\n }\n }\n }\n\n private fun draw(v: Int) {\n var v2 = v\n\n val thousands = v2 / 1000\n v2 %= 1000\n\n val hundreds = v2 / 100\n v2 %= 100\n\n val tens = v2 / 10\n val ones = v % 10\n\n if (thousands > 0) {\n drawPart(1000 * thousands)\n }\n if (hundreds > 0) {\n drawPart(100 * hundreds)\n }\n if (tens > 0) {\n drawPart(10 * tens)\n }\n if (ones > 0) {\n drawPart(ones)\n }\n }\n\n override fun toString(): String {\n val sw = StringWriter()\n for (row in canvas) {\n for (cell in row) {\n sw.append(cell)\n }\n sw.appendLine()\n }\n return sw.toString()\n }\n}\n\nfun main() {\n for (number in arrayOf(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n println(\"$number:\")\n\n val c = Cistercian(number)\n println(c)\n }\n\n}\n", "language": "Kotlin" }, { "code": "function initN()\n local n = {}\n for i=1,15 do\n n[i] = {}\n for j=1,11 do\n n[i][j] = \" \"\n end\n n[i][6] = \"x\"\n end\n return n\nend\n\nfunction horiz(n, c1, c2, r)\n for c=c1,c2 do\n n[r+1][c+1] = \"x\"\n end\nend\n\nfunction verti(n, r1, r2, c)\n for r=r1,r2 do\n n[r+1][c+1] = \"x\"\n end\nend\n\nfunction diagd(n, c1, c2, r)\n for c=c1,c2 do\n n[r+c-c1+1][c+1] = \"x\"\n end\nend\n\nfunction diagu(n, c1, c2, r)\n for c=c1,c2 do\n n[r-c+c1+1][c+1] = \"x\"\n end\nend\n\nfunction initDraw()\n local draw = {}\n\n draw[1] = function(n) horiz(n, 6, 10, 0) end\n draw[2] = function(n) horiz(n, 6, 10, 4) end\n draw[3] = function(n) diagd(n, 6, 10, 0) end\n draw[4] = function(n) diagu(n, 6, 10, 4) end\n draw[5] = function(n) draw[1](n) draw[4](n) end\n draw[6] = function(n) verti(n, 0, 4, 10) end\n draw[7] = function(n) draw[1](n) draw[6](n) end\n draw[8] = function(n) draw[2](n) draw[6](n) end\n draw[9] = function(n) draw[1](n) draw[8](n) end\n\n draw[10] = function(n) horiz(n, 0, 4, 0) end\n draw[20] = function(n) horiz(n, 0, 4, 4) end\n draw[30] = function(n) diagu(n, 0, 4, 4) end\n draw[40] = function(n) diagd(n, 0, 4, 0) end\n draw[50] = function(n) draw[10](n) draw[40](n) end\n draw[60] = function(n) verti(n, 0, 4, 0) end\n draw[70] = function(n) draw[10](n) draw[60](n) end\n draw[80] = function(n) draw[20](n) draw[60](n) end\n draw[90] = function(n) draw[10](n) draw[80](n) end\n\n draw[100] = function(n) horiz(n, 6, 10, 14) end\n draw[200] = function(n) horiz(n, 6, 10, 10) end\n draw[300] = function(n) diagu(n, 6, 10, 14) end\n draw[400] = function(n) diagd(n, 6, 10, 10) end\n draw[500] = function(n) draw[100](n) draw[400](n) end\n draw[600] = function(n) verti(n, 10, 14, 10) end\n draw[700] = function(n) draw[100](n) draw[600](n) end\n draw[800] = function(n) draw[200](n) draw[600](n) end\n draw[900] = function(n) draw[100](n) draw[800](n) end\n\n draw[1000] = function(n) horiz(n, 0, 4, 14) end\n draw[2000] = function(n) horiz(n, 0, 4, 10) end\n draw[3000] = function(n) diagd(n, 0, 4, 10) end\n draw[4000] = function(n) diagu(n, 0, 4, 14) end\n draw[5000] = function(n) draw[1000](n) draw[4000](n) end\n draw[6000] = function(n) verti(n, 10, 14, 0) end\n draw[7000] = function(n) draw[1000](n) draw[6000](n) end\n draw[8000] = function(n) draw[2000](n) draw[6000](n) end\n draw[9000] = function(n) draw[1000](n) draw[8000](n) end\n\n return draw\nend\n\nfunction printNumeral(n)\n for i,v in pairs(n) do\n for j,w in pairs(v) do\n io.write(w .. \" \")\n end\n print()\n end\n print()\nend\n\nfunction main()\n local draw = initDraw()\n for i,number in pairs({0, 1, 20, 300, 4000, 5555, 6789, 9999}) do\n local n = initN()\n print(number..\":\")\n local thousands = math.floor(number / 1000)\n number = number % 1000\n local hundreds = math.floor(number / 100)\n number = number % 100\n local tens = math.floor(number / 10)\n local ones = number % 10\n if thousands > 0 then\n draw[thousands * 1000](n)\n end\n if hundreds > 0 then\n draw[hundreds * 100](n)\n end\n if tens > 0 then\n draw[tens * 10](n)\n end\n if ones > 0 then\n draw[ones](n)\n end\n printNumeral(n)\n end\nend\n\nmain()\n", "language": "Lua" }, { "code": "ClearAll[CistercianNumberEncodeHelper, CistercianNumberEncode]\n\\[Delta] = 0.25;\nCistercianNumberEncodeHelper[0] := {}\nCistercianNumberEncodeHelper[1] := Line[{{0, 1}, {\\[Delta], 1}}]\nCistercianNumberEncodeHelper[2] := Line[{{0, 1 - \\[Delta]}, {\\[Delta], 1 - \\[Delta]}}]\nCistercianNumberEncodeHelper[3] := Line[{{0, 1}, {\\[Delta], 1 - \\[Delta]}}]\nCistercianNumberEncodeHelper[4] := Line[{{0, 1 - \\[Delta]}, {\\[Delta], 1}}]\nCistercianNumberEncodeHelper[5] := Line[{{0, 1 - \\[Delta]}, {\\[Delta], 1}, {0, 1}}]\nCistercianNumberEncodeHelper[6] := Line[{{\\[Delta], 1 - \\[Delta]}, {\\[Delta], 1}}]\nCistercianNumberEncodeHelper[7] := Line[{{\\[Delta], 1 - \\[Delta]}, {\\[Delta], 1}, {0, 1}}]\nCistercianNumberEncodeHelper[8] := Line[{{0, 1 - \\[Delta]}, {\\[Delta], 1 - \\[Delta]}, {\\[Delta], 1}}]\nCistercianNumberEncodeHelper[9] := Line[{{0, 1}, {\\[Delta], 1}, {\\[Delta], 1 - \\[Delta]}, {0, 1 - \\[Delta]}}]\nCistercianNumberEncode::nnarg = \"The argument `1` should be an integer between 0 and 9999 (inclusive).\";\nCistercianNumberEncode[n_Integer] := Module[{digs},\n If[0 <= n <= 9999,\n digs = IntegerDigits[n, 10, 4];\n Graphics[{Line[{{0, 0}, {0, 1}}],\n CistercianNumberEncodeHelper[digs[[4]]],\n GeometricTransformation[CistercianNumberEncodeHelper[digs[[3]]],\n ReflectionTransform[{1, 0}]],\n GeometricTransformation[CistercianNumberEncodeHelper[digs[[2]]],\n ReflectionTransform[{0, 1}, {0, 1/2}]],\n GeometricTransformation[CistercianNumberEncodeHelper[digs[[1]]],\n RotationTransform[Pi, {0, 1/2}]]\n },\n PlotRange -> {{-1.5 \\[Delta], 1.5 \\[Delta]}, {0 - 0.5 \\[Delta],\n 1 + 0.5 \\[Delta]}},\n ImageSize -> 50\n ]\n ,\n Message[CistercianNumberEncode::nnarg, n]\n ]\n ]\nCistercianNumberEncode[0]\nCistercianNumberEncode[1]\nCistercianNumberEncode[20]\nCistercianNumberEncode[300]\nCistercianNumberEncode[4000]\nCistercianNumberEncode[5555]\nCistercianNumberEncode[6789]\nCistercianNumberEncode[1337]\n", "language": "Mathematica" }, { "code": "const Size = 15\n\ntype Canvas = array[Size, array[Size, char]]\n\n\nfunc horizontal(canvas: var Canvas; col1, col2, row: Natural) =\n for col in col1..col2:\n canvas[row][col] = 'x'\n\n\nfunc vertical(canvas: var Canvas; row1, row2, col: Natural) =\n for row in row1..row2:\n canvas[row][col] = 'x'\n\n\nfunc diagd(canvas: var Canvas; col1, col2, row: Natural) =\n for col in col1..col2:\n canvas[row + col - col1][col] = 'x'\n\n\nfunc diagu(canvas: var Canvas; col1, col2, row: Natural) =\n for col in col1..col2:\n canvas[row - col + col1][col] = 'x'\n\n\nfunc drawPart(canvas: var Canvas; value: Natural) =\n\n case value\n of 1:\n canvas.horizontal(6, 10, 0)\n of 2:\n canvas.horizontal(6, 10, 4)\n of 3:\n canvas.diagd(6, 10, 0)\n of 4:\n canvas.diagu(6, 10, 4)\n of 5:\n canvas.drawPart(1)\n canvas.drawPart(4)\n of 6:\n canvas.vertical(0, 4, 10)\n of 7:\n canvas.drawPart(1)\n canvas.drawPart(6)\n of 8:\n canvas.drawPart(2)\n canvas.drawPart(6)\n of 9:\n canvas.drawPart(1)\n canvas.drawPart(8)\n of 10:\n canvas.horizontal(0, 4, 0)\n of 20:\n canvas.horizontal(0, 4, 4)\n of 30:\n canvas.diagu(0, 4, 4)\n of 40:\n canvas.diagd(0, 4, 0)\n of 50:\n canvas.drawPart(10)\n canvas.drawPart(40)\n of 60:\n canvas.vertical(0, 4, 0)\n of 70:\n canvas.drawPart(10)\n canvas.drawPart(60)\n of 80:\n canvas.drawPart(20)\n canvas.drawPart(60)\n of 90:\n canvas.drawPart(10)\n canvas.drawPart(80)\n of 100:\n canvas.horizontal(6, 10, 14)\n of 200:\n canvas.horizontal(6, 10, 10)\n of 300:\n canvas.diagu(6, 10, 14)\n of 400:\n canvas.diagd(6, 10, 10)\n of 500:\n canvas.drawPart(100)\n canvas.drawPart(400)\n of 600:\n canvas.vertical(10, 14, 10)\n of 700:\n canvas.drawPart(100)\n canvas.drawPart(600)\n of 800:\n canvas.drawPart(200)\n canvas.drawPart(600)\n of 900:\n canvas.drawPart(100)\n canvas.drawPart(800)\n of 1000:\n canvas.horizontal(0, 4, 14)\n of 2000:\n canvas.horizontal(0, 4, 10)\n of 3000:\n canvas.diagd(0, 4, 10)\n of 4000:\n canvas.diagu(0, 4, 14)\n of 5000:\n canvas.drawPart(1000)\n canvas.drawPart(4000)\n of 6000:\n canvas.vertical(10, 14, 0)\n of 7000:\n canvas.drawPart(1000)\n canvas.drawPart(6000)\n of 8000:\n canvas.drawPart(2000)\n canvas.drawPart(6000)\n of 9000:\n canvas.drawPart(1000)\n canvas.drawPart(8000)\n else:\n raise newException(ValueError, \"wrong value for 'drawPart'\")\n\n\nfunc draw(canvas: var Canvas; value: Natural) =\n\n var val = value\n let thousands = val div 1000\n val = val mod 1000\n let hundreds = val div 100\n val = val mod 100\n let tens = val div 10\n let ones = val mod 10\n\n if thousands != 0:\n canvas.drawPart(1000 * thousands)\n if hundreds != 0:\n canvas.drawPart(100 * hundreds)\n if tens != 0:\n canvas.drawPart(10 * tens)\n if ones != 0:\n canvas.drawPart(ones)\n\n\nfunc cistercian(n: Natural): Canvas =\n for row in result.mitems:\n for cell in row.mitems: cell = ' '\n row[5] = 'x'\n result.draw(n)\n\n\nproc `$`(canvas: Canvas): string =\n for row in canvas:\n for cell in row:\n result.add cell\n result.add '\\n'\n\n\nwhen isMainModule:\n\n for number in [0, 1, 20, 300, 4000, 5555, 6789, 9999]:\n echo number, ':'\n echo cistercian(number)\n", "language": "Nim" }, { "code": "#!/usr/bin/perl\n\nuse strict; # https://rosettacode.org/wiki/Cistercian_numerals\nuse warnings;\n\nmy @pts = ('', qw( 01 23 03 12 012 13 013 132 0132) );\nmy @dots = qw( 4-0 8-0 4-4 8-4 );\n\nmy @images = map { sprintf(\"%-9s\\n\", \"$_:\") . draw($_) }\n 0, 1, 20, 300, 4000, 5555, 6789, 1133;\nfor ( 1 .. 13 )\n {\n s/(.+)\\n/ print \" $1\"; '' /e for @images;\n print \"\\n\";\n }\n\nsub draw\n {\n my $n = shift;\n local $_ = \" # \\n\" x 12;\n my $quadrant = 0;\n for my $digit ( reverse split //, sprintf \"%04d\", $n )\n {\n my ($oldx, $oldy);\n for my $cell ( split //, $pts[$digit] )\n {\n my ($x, $y) = split /-/, $dots[$cell];\n if( defined $oldx )\n {\n my $dirx = $x <=> $oldx;\n my $diry = $y <=> $oldy;\n for my $place ( 0 .. 3 )\n {\n substr $_, $oldx + $oldy * 10, 1, '#';\n $oldx += $dirx;\n $oldy += $diry;\n }\n }\n ($oldx, $oldy) = ($x, $y);\n }\n s/.+/ reverse $& /ge;\n ++$quadrant & 1 or $_ = join '', reverse /.+\\n/g;\n }\n return $_;\n }\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- Define each digit as {up-down multiplier, left-right multiplier, char},\n -- that is starting each drawing from line 1 or 7, column 3,\n -- and with `/` and `\\` being flipped below when necessary.\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">ds</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'-'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'-'</span><span style=\"color: #0000FF;\">}},</span> <span style=\"color: #000080;font-style:italic;\">-- 1</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'-'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'-'</span><span style=\"color: #0000FF;\">}},</span> <span style=\"color: #000080;font-style:italic;\">-- 2</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'\\\\'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'\\\\'</span><span style=\"color: #0000FF;\">}},</span> <span style=\"color: #000080;font-style:italic;\">-- 3</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'/'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'/'</span><span style=\"color: #0000FF;\">}},</span> <span style=\"color: #000080;font-style:italic;\">-- 4</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'/'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'-'</span><span style=\"color: #0000FF;\">}},</span> <span style=\"color: #000080;font-style:italic;\">-- 5</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'|'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'|'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'|'</span><span style=\"color: #0000FF;\">}},</span> <span style=\"color: #000080;font-style:italic;\">-- 6</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'-'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'|'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'|'</span><span style=\"color: #0000FF;\">}},</span> <span style=\"color: #000080;font-style:italic;\">-- 7</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'-'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'|'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'|'</span><span style=\"color: #0000FF;\">}},</span> <span style=\"color: #000080;font-style:italic;\">-- 8</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'-'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'|'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'-'</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">}}}</span> <span style=\"color: #000080;font-style:italic;\">-- 9</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">cdigit</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">pos</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">--\n -- s is our canvas, 7 lines of 5 characters\n -- d is the digit, 0..9\n -- pos is 4..1 for bl,br,tl,tr (easier to say/see 'backwards')\n --</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">d</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ud</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}[</span><span style=\"color: #000000;\">pos</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">lr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}[</span><span style=\"color: #000000;\">pos</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">l</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">}[</span><span style=\"color: #000000;\">pos</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">dset</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">ds</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dset</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">udm</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">lrm</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">dset</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">tf</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`/\\`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">tf</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">ud</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">lr</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">`\\/`</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">tf</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">ud</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">udm</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">lr</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">lrm</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">ch</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">s</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">cisterian</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">cn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%4d:\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cn</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\" | \"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">pos</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">cn</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">cdigit</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cn</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">pos</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">pos</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">cn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cn</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">s</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">join_by</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">cisterian</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">20</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">300</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4000</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5555</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6789</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9394</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7922</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9999</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "To run:\nStart up.\nShow some example Cistercian numbers.\nWait for the escape key.\nShut down.\n\nTo show some example Cistercian numbers:\nPut the screen's left plus 1 inch into the context's spot's x.\nClear the screen to the lightest gray color.\nUse the black color.\nUse the fat pen.\nDraw 0.\nDraw 1.\nDraw 20.\nDraw 300.\nDraw 4000.\nDraw 5555.\nDraw 6789.\nDraw 9394.\nRefresh the screen.\n\nThe mirror flag is a flag.\n\nTo draw a Cistercian number:\nSplit the Cistercian number into some thousands and some hundreds and some tens and some ones.\nStroke zero.\nSet the mirror flag.\nStroke the ones.\nClear the mirror flag.\nStroke the tens.\nTurn around.\nStroke the hundreds.\nSet the mirror flag.\nStroke the thousands.\nTurn around.\nLabel the Cistercian number.\nMove the context's spot right 1 inch.\n\nTo label a Cistercian number:\nSave the context.\nMove down the half stem plus the small stem.\nImagine a box with the context's spot and the context's spot.\nDraw \"\" then the Cistercian number in the center of the box with the dark gray color.\nRestore the context.\n\nSome tens are a number.\n\nSome ones are a number.\n\nTo split a number into some thousands and some hundreds and some tens and some ones:\nDivide the number by 10 giving a quotient and a remainder.\nPut the remainder into the ones.\nDivide the quotient by 10 giving another quotient and another remainder.\nPut the other remainder into the tens.\nDivide the other quotient by 10 giving a third quotient and a third remainder.\nPut the third remainder into the hundreds.\nDivide the third quotient by 10 giving a fourth quotient and a fourth remainder.\nPut the fourth remainder into the thousands.\n\nThe small stem is a length equal to 1/6 inch.\n\nThe half stem is a length equal to 1/2 inch.\n\nThe tail is a length equal to 1/3 inch.\n\nThe slanted tail is a length equal to 6/13 inch.\n\nTo stroke a number:\nSave the context.\nIf the number is 1, stroke one.\nIf the number is 2, stroke two.\nIf the number is 3, stroke three.\nIf the number is 4, stroke four.\nIf the number is 5, stroke five.\nIf the number is 6, stroke six.\nIf the number is 7, stroke seven.\nIf the number is 8, stroke eight.\nIf the number is 9, stroke nine.\nRestore the context.\n\nTo turn home:\nIf the mirror flag is set, turn right; exit.\nTurn left.\n\nTo turn home some fraction of the way:\nIf the mirror flag is set, turn right the fraction; exit.\nTurn left the fraction.\n\nTo stroke zero:\nSave the context.\nStroke the half stem.\nTurn around.\nMove the half stem.\nStroke the half stem.\nRestore the context.\n\nTo stroke one:\nMove the half stem.\nTurn home.\nStroke the tail.\n\nTo stroke two:\nMove the small stem.\nTurn home.\nStroke the tail.\n\nTo stroke three:\nMove the half stem.\nTurn home 3/8 of the way.\nStroke the slanted tail.\n\nTo stroke four:\nMove the small stem.\nTurn home 1/8 of the way.\nStroke the slanted tail.\n\nTo stroke five:\nStroke 1.\nStroke 4.\n\nTo stroke six:\nMove the half stem.\nTurn home.\nMove the tail.\nTurn home.\nStroke the tail.\n\nTo stroke seven:\nStroke 1.\nStroke 6.\n\nTo stroke eight:\nStroke 2.\nStroke 6.\n\nTo stroke nine:\nStroke 1.\nStroke 8.\n", "language": "Plain-English" }, { "code": "# -*- coding: utf-8 -*-\n\"\"\"\nSome UTF-8 chars used:\n\n‾\t8254\t203E\t&oline;\tOVERLINE\n┃\t9475\t2503\t \tBOX DRAWINGS HEAVY VERTICAL\n╱\t9585\t2571\t \tBOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT\n╲\t9586\t2572\t \tBOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT\n◸\t9720\t25F8\t \tUPPER LEFT TRIANGLE\n◹\t9721\t25F9\t \tUPPER RIGHT TRIANGLE\n◺\t9722\t25FA\t \tLOWER LEFT TRIANGLE\n◻\t9723\t25FB\t \tWHITE MEDIUM SQUARE\n◿\t9727\t25FF\t \tLOWER RIGHT TRIANGLE\n\n\"\"\"\n\n#%% digit sections\n\ndef _init():\n \"digit sections for forming numbers\"\n digi_bits = \"\"\"\n#0 1 2 3 4 5 6 7 8 9\n#\n . ‾ _ ╲ ╱ ◸ .| ‾| _| ◻\n#\n . ‾ _ ╱ ╲ ◹ |. |‾ |_ ◻\n#\n . _ ‾ ╱ ╲ ◺ .| _| ‾| ◻\n#\n . _ ‾ ╲ ╱ ◿ |. |_ |‾ ◻\n\n\"\"\".strip()\n\n lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n for ln in digi_bits.strip().split('\\n')\n if '#' not in ln]\n formats = '<2 >2 <2 >2'.split()\n digits = [[f\"{dig:{f}}\" for dig in line]\n for f, line in zip(formats, lines)]\n\n return digits\n\n_digits = _init()\n\n\n#%% int to 3-line strings\ndef _to_digits(n):\n assert 0 <= n < 10_000 and int(n) == n\n\n return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n global _digits\n d = _to_digits(n)\n lines = [\n ''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])),\n ''.join((_digits[0][ 0], '┃', _digits[0][ 0])),\n ''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])),\n ]\n\n return lines\n\ndef cjoin(c1, c2, spaces=' '):\n return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n#%% main\nif __name__ == '__main__':\n #n = 6666\n #print(f\"Arabic {n} to Cistercian:\\n\")\n #print('\\n'.join(num_to_lines(n)))\n\n for pow10 in range(4):\n step = 10 ** pow10\n print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n lines = num_to_lines(step)\n for n in range(step*2, step*10, step):\n lines = cjoin(lines, num_to_lines(n))\n print('\\n'.join(lines))\n\n\n numbers = [0, 5555, 6789, 6666]\n print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n lines = num_to_lines(numbers[0])\n for n in numbers[1:]:\n lines = cjoin(lines, num_to_lines(n))\n print('\\n'.join(lines))\n", "language": "Python" }, { "code": " [ $ \"turtleduck.qky\" loadfile ] now!\n\n [ [ 50 dup * 2 * 1\n 10 vsqrt drop\n join ] constant\n do ] is diag ( --> n/d )\n\n [ stack 1 ] is side ( --> s )\n\n [ 0 side take\n - side put ] is otherside ( --> )\n\n [ 150 1 walk\n -150 1 fly ] is trunk ( --> )\n\n [ 50 1 fly ] is inset ( --> )\n\n [ -50 1 fly ] is outset ( --> )\n\n [ 150 1 fly\n 1 2 turn ] is otherend ( --> )\n\n [ ] is zero ( --> )\n\n [ -1 4 turn\n 50 side share *\n dup 1 walk\n negate 1 fly\n 1 4 turn ] is one ( --> )\n\n [ inset one outset ] is two ( --> )\n\n [ -1 side share *\n 8 turn\n diag walk\n diag -v fly\n 1 side share *\n 8 turn ] is three ( --> )\n\n [ inset\n -3 side share *\n 8 turn\n diag walk\n diag -v fly\n 3 side share *\n 8 turn\n outset ] is four ( --> )\n\n [ one four ] is five ( --> )\n\n [ 1 side share *\n 4 turn outset\n one\n inset\n -1 side share *\n 4 turn ] is six ( --> )\n\n [ one six ] is seven ( --> )\n\n [ two six ] is eight ( --> )\n\n [ one two six ] is nine ( --> )\n\n [ [ table\n zero one two\n three four five\n six seven eight\n nine ] do ] is thousands ( n --> )\n\n [ otherend\n thousands\n otherend ] is units ( n --> )\n\n [ otherside\n units\n otherside ] is tens ( n --> )\n\n [ otherside\n thousands\n otherside ] is hundreds ( n --> )\n\n [ inset\n -1 4 turn\n trunk\n ' [ units tens\n hundreds\n thousands ]\n witheach\n [ dip\n [ 10 /mod ]\n do ]\n drop\n 1 4 turn\n outset ] is cistercian ( n --> )\n\n [ dup witheach\n [ cistercian\n 3 times inset ]\n size 3 * times\n outset ] is task ( [ --> )\n\n\n turtle 5 wide -600 1 fly\n ' [ 0 1 20 300 4000 5555 6789 1234 ] task\n", "language": "Quackery" }, { "code": "my @line-segments = (0, 0, 0, 100),\n (0, 0, 35, 0), (0, 35, 35, 35), (0, 0, 35, 35), (0, 35, 35, 0), ( 35, 0, 35, 35),\n (0, 0,-35, 0), (0, 35,-35, 35), (0, 0,-35, 35), (0, 35,-35, 0), (-35, 0,-35, 35),\n (0,100, 35,100), (0, 65, 35, 65), (0,100, 35, 65), (0, 65, 35,100), ( 35, 65, 35,100),\n (0,100,-35,100), (0, 65,-35, 65), (0,100,-35, 65), (0, 65,-35,100), (-35, 65,-35,100);\n\nmy @components = map {@line-segments[$_]}, |((0, 5, 10, 15).map: -> $m {\n |((0,), (1,), (2,), (3,), (4,), (1,4), (5,), (1,5), (2,5), (1,2,5)).map: {$_ »+» $m}\n});\n\nmy $out = 'Cistercian-raku.svg'.IO.open(:w);\n\n$out.say: # insert header\nq|<svg width=\"875\" height=\"470\" style=\"stroke:black;\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect width=\"100%\" height=\"100%\" style=\"fill:white;\"/>|;\n\nmy $hs = 50; # horizontal spacing\nmy $vs = 25; # vertical spacing\n\nfor flat ^10, 20, 300, 4000, 5555, 6789, 9394, (^10000).pick(14) -> $cistercian {\n\n $out.say: |@components[0].map: { # draw zero / base vertical bar\n qq|<line x1=\"{.[0] + $hs}\" y1=\"{.[1] + $vs}\" x2=\"{.[2] + $hs}\" y2=\"{.[3] + $vs}\"/>|\n };\n\n my @orders-of-magnitude = $cistercian.polymod(10 xx *);\n\n for @orders-of-magnitude.kv -> $order, $value {\n next unless $value; # skip zeros, already drew zero bar\n last if $order > 3; # truncate too large integers\n\n # draw the component line segments\n $out.say: join \"\\n\", @components[$order * 10 + $value].map: {\n qq|<line x1=\"{.[0] + $hs}\" y1=\"{.[1] + $vs}\" x2=\"{.[2] + $hs}\" y2=\"{.[3] + $vs}\"/>|\n }\n }\n\n # insert the decimal number below\n $out.say: qq|<text x=\"{$hs - 5}\" y=\"{$vs + 120}\">{$cistercian}</text>|;\n\n if ++$ %% 10 { # next row\n $hs = -35;\n $vs += 150;\n }\n\n $hs += 85; # increment horizontal spacing\n\n\n}\n$out.say: q|</svg>|; # insert footer\n", "language": "Raku" }, { "code": "/*REXX program displays a (non-negative 4-digit) integer in Cistercian (monk) numerals.*/\nparse arg m /*obtain optional arguments from the CL*/\nif m='' | m=\",\" then m= 0 1 20 300 4000 5555 6789 9393 /*Not specified? Use defaults.*/\n$.=; nnn= words(m)\n do j=1 for nnn; z= word(m, j) /*process each of the numbers. */\n if \\datatype(z, 'W') then call serr \"number isn't numeric: \" z\n if \\datatype(z, 'N') then call serr \"number isn't an integer: \" z\n z= z / 1 /*normalize the number: 006 5.0 +4 */\n if z<0 then call serr \"number can't be negative: \" z\n if z>9999 then call serr \"number is too large (>9,999): \" z\n call monk z / 1 /*create the Cistercian quad numeral. */\n end /*j*/\ncall show /*display \" \" \" \" */\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n@: parse arg @x,@y; return @.@x.@y /*return a value from the point (@x,@y)*/\nquad: parse arg #; if #\\==0 then interpret 'call' #; return /*build a numeral.*/\nserr: say '***error*** ' arg(1); exit 13 /*issue error msg.*/\napp: do r= 9 for 10 by -1; do c=-5 for 11; $.r= $.r||@.c.r; end; $.r=$.r b5; end; return\neye: do a=0 for 10; @.0.a= '│'; end; return /*build an \"eye\" glyph (vertical axis).*/\np: do k=1 by 3 until k>arg(); x= arg(k); y= arg(k+1); @.x.y= arg(k+2); end; return\nsect: do q=1 for 4; call quad s.q; end; return /*build a Cistercian numeral character.*/\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nmonk: parse arg n; n= right(n, 4, 0); @.= ' ' /*zero─fill N; blank─out numeral grid.*/\n b4= left('', 4); b5= b4\" \"; $.11= $.11 || b4 || n || b4 || b5; call eye\n parse var n s.4 2 s.3 3 s.2 4 s.1; call sect; call nice; call app; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nnice: if @(-1, 9)=='─' then call p 0, 9, \"┐\"; if @(1,9)=='─' then call p 0, 9, \"┌\"\n if @(-1, 9)=='─' & @(1,9)=='─' then call p 0, 9, \"┬\"\n if @(-1, 0)=='─' then call p 0, 0, \"┘\"; if @(1,0)=='─' then call p 0, 0, \"└\"\n if @(-1, 0)=='─' & @(1,0)=='─' then call p 0, 0, \"┴\"\n do i=4 to 5\n if @(-1, i)=='─' then call p 0, i, \"┤\"; if @(1,i)=='─' then call p 0, i, \"├\"\n if @(-1, i)=='─' & @(1,i)==\"─\" then call p 0, i, \"┼\"\n end /*i*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nshow: do jj= 11 for 10+2 by -1; say strip($.jj, 'T') /*display 1 row at a time.*/\n if jj==5 then do 3; say strip( copies(b5'│'b5 b5, nnn), 'T'); end\n end /*r*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n1: ?= '─'; if q==1 then call p 1, 9, ?, 2, 9, ?, 3, 9, ?, 4, 9, ?, 5, 9, ?\n if q==2 then call p -1, 9, ?, -2, 9, ?, -3, 9, ?, -4, 9, ?, -5, 9, ?\n if q==3 then call p 1, 0, ?, 2, 0, ?, 3, 0, ?, 4, 0, ?, 5, 0, ?\n if q==4 then call p -1, 0, ?, -2, 0, ?, -3, 0, ?, -4, 0, ?, -5, 0, ?; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n2: ?= '─'; if q==1 then call p 1, 5, ?, 2, 5, ?, 3, 5, ?, 4, 5, ?, 5, 5, ?\n if q==2 then call p -1, 5, ?, -2, 5, ?, -3, 5, ?, -4, 5, ?, -5, 5, ?\n if q==3 then call p 1, 4, ?, 2, 4, ?, 3, 4, ?, 4, 4, ?, 5, 4, ?\n if q==4 then call p -1, 4, ?, -2, 4, ?, -3, 4, ?, -4, 4, ?, -5, 4, ?; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n3: ?= '\\'; if q==1 then call p 1, 9, ?, 2, 8, ?, 3, 7, ?, 4, 6, ?, 5, 5, ?\n ?= '/'; if q==2 then call p -1, 9, ?, -2, 8, ?, -3, 7, ?, -4, 6, ?, -5, 5, ?\n ?= '/'; if q==3 then call p 1, 0, ?, 2, 1, ?, 3, 2, ?, 4, 3, ?, 5, 4, ?\n ?= '\\'; if q==4 then call p -5, 4, ?, -4, 3, ?, -3, 2, ?, -2, 1, ?, -1, 0, ?; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n4: ?= '/'; if q==1 then call p 1, 5, ?, 2, 6, ?, 3, 7, ?, 4, 8, ?, 5, 9, ?\n ?= '\\'; if q==2 then call p -5, 9, ?, -4, 8, ?, -3, 7, ?, -2, 6, ?, -1, 5, ?\n ?= '\\'; if q==3 then call p 1, 4, ?, 2, 3, ?, 3, 2, ?, 4, 1, ?, 5, 0, ?\n ?= '/'; if q==4 then call p -5, 0, ?, -4, 1, ?, -3, 2, ?, -2, 3, ?, -1, 4, ?; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n5: ?= '/'; if q==1 then call p 1, 5, ?, 2, 6, ?, 3, 7, ?, 4, 8, ?\n ?= '\\'; if q==2 then call p -4, 8, ?, -3, 7, ?, -2, 6, ?, -1, 5, ?\n ?= '\\'; if q==3 then call p 1, 4, ?, 2, 3, ?, 3, 2, ?, 4, 1, ?\n ?= '/'; if q==4 then call p -4, 1, ?, -3, 2, ?, -2, 3, ?, -1, 4, ?; call 1; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n6: ?= '│'; if q==1 then call p 5, 9, ?, 5, 8, ?, 5, 7, ?, 5, 6, ?, 5, 5, ?\n if q==2 then call p -5, 9, ?, -5, 8, ?, -5, 7, ?, -5, 6, ?, -5, 5, ?\n if q==3 then call p 5, 0, ?, 5, 1, ?, 5, 2, ?, 5, 3, ?, 5, 4, ?\n if q==4 then call p -5, 0, ?, -5, 1, ?, -5, 2, ?, -5, 3, ?, -5, 4, ?; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n7: call 1; call 6; if q==1 then call p 5, 9, '┐'\n if q==2 then call p -5, 9, '┌'\n if q==3 then call p 5, 0, '┘'\n if q==4 then call p -5, 0, '└'; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n8: call 2; call 6; if q==1 then call p 5, 5, '┘'\n if q==2 then call p -5, 5, '└'\n if q==3 then call p 5, 4, '┐'\n if q==4 then call p -5, 4, '┌'; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n9: call 1; call 2; call 6; if q==1 then call p 5, 5, '┘', 5, 9, \"┐\"\n if q==2 then call p -5, 5, '└', -5, 9, \"┌\"\n if q==3 then call p 5, 0, '┘', 5, 4, \"┐\"\n if q==4 then call p -5, 0, '└', -5, 4, \"┌\"; return\n", "language": "REXX" }, { "code": "def initN\n n = Array.new(15){Array.new(11, ' ')}\n for i in 1..15\n n[i - 1][5] = 'x'\n end\n return n\nend\n\ndef horiz(n, c1, c2, r)\n for c in c1..c2\n n[r][c] = 'x'\n end\nend\n\ndef verti(n, r1, r2, c)\n for r in r1..r2\n n[r][c] = 'x'\n end\nend\n\ndef diagd(n, c1, c2, r)\n for c in c1..c2\n n[r+c-c1][c] = 'x'\n end\nend\n\ndef diagu(n, c1, c2, r)\n for c in c1..c2\n n[r-c+c1][c] = 'x'\n end\nend\n\ndef initDraw\n draw = []\n\n draw[1] = lambda do |n| horiz(n, 6, 10, 0) end\n draw[2] = lambda do |n| horiz(n, 6, 10, 4) end\n draw[3] = lambda do |n| diagd(n, 6, 10, 0) end\n draw[4] = lambda do |n| diagu(n, 6, 10, 4) end\n draw[5] = lambda do |n|\n draw[1].call(n)\n draw[4].call(n)\n end\n draw[6] = lambda do |n| verti(n, 0, 4, 10) end\n draw[7] = lambda do |n|\n draw[1].call(n)\n draw[6].call(n)\n end\n draw[8] = lambda do |n|\n draw[2].call(n)\n draw[6].call(n)\n end\n draw[9] = lambda do |n|\n draw[1].call(n)\n draw[8].call(n)\n end\n\n draw[10] = lambda do |n| horiz(n, 0, 4, 0) end\n draw[20] = lambda do |n| horiz(n, 0, 4, 4) end\n draw[30] = lambda do |n| diagu(n, 0, 4, 4) end\n draw[40] = lambda do |n| diagd(n, 0, 4, 0) end\n draw[50] = lambda do |n|\n draw[10].call(n)\n draw[40].call(n)\n end\n draw[60] = lambda do |n| verti(n, 0, 4, 0) end\n draw[70] = lambda do |n|\n draw[10].call(n)\n draw[60].call(n)\n end\n draw[80] = lambda do |n|\n draw[20].call(n)\n draw[60].call(n)\n end\n draw[90] = lambda do |n|\n draw[10].call(n)\n draw[80].call(n)\n end\n\n draw[100] = lambda do |n| horiz(n, 6, 10, 14) end\n draw[200] = lambda do |n| horiz(n, 6, 10, 10) end\n draw[300] = lambda do |n| diagu(n, 6, 10, 14) end\n draw[400] = lambda do |n| diagd(n, 6, 10, 10) end\n draw[500] = lambda do |n|\n draw[100].call(n)\n draw[400].call(n)\n end\n draw[600] = lambda do |n| verti(n, 10, 14, 10) end\n draw[700] = lambda do |n|\n draw[100].call(n)\n draw[600].call(n)\n end\n draw[800] = lambda do |n|\n draw[200].call(n)\n draw[600].call(n)\n end\n draw[900] = lambda do |n|\n draw[100].call(n)\n draw[800].call(n)\n end\n\n draw[1000] = lambda do |n| horiz(n, 0, 4, 14) end\n draw[2000] = lambda do |n| horiz(n, 0, 4, 10) end\n draw[3000] = lambda do |n| diagd(n, 0, 4, 10) end\n draw[4000] = lambda do |n| diagu(n, 0, 4, 14) end\n draw[5000] = lambda do |n|\n draw[1000].call(n)\n draw[4000].call(n)\n end\n draw[6000] = lambda do |n| verti(n, 10, 14, 0) end\n draw[7000] = lambda do |n|\n draw[1000].call(n)\n draw[6000].call(n)\n end\n draw[8000] = lambda do |n|\n draw[2000].call(n)\n draw[6000].call(n)\n end\n draw[9000] = lambda do |n|\n draw[1000].call(n)\n draw[8000].call(n)\n end\n\n return draw\nend\n\ndef printNumeral(n)\n for a in n\n for b in a\n print b\n end\n print \"\\n\"\n end\n print \"\\n\"\nend\n\ndraw = initDraw()\nfor number in [0, 1, 20, 300, 4000, 5555, 6789, 9999]\n n = initN()\n print number, \":\\n\"\n\n thousands = (number / 1000).floor\n number = number % 1000\n\n hundreds = (number / 100).floor\n number = number % 100\n\n tens = (number / 10).floor\n ones = number % 10\n\n if thousands > 0 then\n draw[thousands * 1000].call(n)\n end\n if hundreds > 0 then\n draw[hundreds * 100].call(n)\n end\n if tens > 0 then\n draw[tens * 10].call(n)\n end\n if ones > 0 then\n draw[ones].call(n)\n end\n printNumeral(n)\nend\n", "language": "Ruby" }, { "code": "use once_cell::sync::Lazy;\n\nconst GRID_SIZE: usize = 15;\nstatic mut CANVAS: Lazy<Vec<[char; GRID_SIZE]>> = Lazy::new(|| vec![[' '; GRID_SIZE]; GRID_SIZE],);\n\n/// initialize CANVAS\nfn init_n() {\n for i in 0..GRID_SIZE {\n for j in 0..GRID_SIZE {\n unsafe { CANVAS[i][j] = ' '; }\n }\n unsafe { CANVAS[i][5] = '#'; }\n }\n}\n\n/// draw horizontal\nfn horizontal(c1: usize, c2: usize, r: usize) {\n for c in c1..=c2 {\n unsafe { CANVAS[r][c] = '#'; }\n }\n}\n\n/// draw vertical\nfn vertical(r1: usize, r2: usize, c: usize) {\n for r in r1..=r2 {\n unsafe { CANVAS[r][c] = '#'; }\n }\n}\n\n/// draw diagonal NE to SW\nfn diag_d(c1 : usize, c2: usize, r: usize) {\n for c in c1..=c2 {\n unsafe { CANVAS[r + c - c1][c] = '#'; }\n }\n}\n\n/// draw diagonal SE to NW\nfn diag_u(c1: usize, c2: usize, r: usize) {\n for c in c1..=c2 {\n unsafe { CANVAS[r + c1 - c][c] = '#'; }\n }\n}\n\n/// Mark the portions of the ones place.\nfn draw_ones(v: i32) {\n match v {\n 1 => horizontal(6, 10, 0),\n 2 => horizontal(6, 10, 4),\n 3 => diag_d(6, 10, 0),\n 4 => diag_u(6, 10, 4),\n 5 => { draw_ones(1); draw_ones(4); },\n 6 => vertical(0, 4, 10),\n 7 => { draw_ones(1); draw_ones(6); },\n 8 => { draw_ones(2); draw_ones(6); },\n 9 => { draw_ones(1); draw_ones(8); },\n _ => {},\n }\n}\n\n/// Mark the portions of the tens place.\nfn draw_tens(v: i32) {\n match v {\n 1 => horizontal(0, 4, 0),\n 2 => horizontal(0, 4, 4),\n 3 => diag_u(0, 4, 4),\n 4 => diag_d(0, 4, 0),\n 5 => { draw_tens(1); draw_tens(4); },\n 6 => vertical(0, 4, 0),\n 7 => { draw_tens(1); draw_tens(6); },\n 8 => { draw_tens(2); draw_tens(6); },\n 9 => { draw_tens(1); draw_tens(8); },\n _ => {},\n }\n}\n\n/// Mark the portions of the hundreds place.\nfn draw_hundreds(hundreds: i32) {\n match hundreds {\n 1 => horizontal(6, 10, 14),\n 2 => horizontal(6, 10, 10),\n 3 => diag_u(6, 10, 14),\n 4 => diag_d(6, 10, 10),\n 5 => { draw_hundreds(1); draw_hundreds(4) },\n 6 => vertical(10, 14, 10),\n 7 => { draw_hundreds(1); draw_hundreds(6); },\n 8 => { draw_hundreds(2); draw_hundreds(6); },\n 9 => { draw_hundreds(1); draw_hundreds(8); },\n _ => {},\n }\n}\n\n/// Mark the portions of the thousands place.\nfn draw_thousands(thousands: i32) {\n match thousands {\n 1 => horizontal(0, 4, 14),\n 2 => horizontal(0, 4, 10),\n 3 => diag_d(0, 4, 10),\n 4 => diag_u(0, 4, 14),\n 5 => { draw_thousands(1); draw_thousands(4); },\n 6 => vertical(10, 14, 0),\n 7 => { draw_thousands(1); draw_thousands(6); },\n 8 => { draw_thousands(2); draw_thousands(6); },\n 9 => { draw_thousands(1); draw_thousands(8); },\n _ => {},\n }\n}\n\n/// Mark the char matrix for the numeral drawing.\nfn draw(mut v: i32) {\n let thousands: i32 = v / 1000;\n v %= 1000;\n let hundreds: i32 = v / 100;\n v %= 100;\n let tens: i32 = v / 10;\n let ones: i32 = v % 10;\n if thousands > 0 {\n draw_thousands(thousands);\n }\n if hundreds > 0 {\n draw_hundreds(hundreds);\n }\n if tens > 0 {\n draw_tens(tens);\n }\n if ones > 0 {\n draw_ones(ones);\n }\n}\n\n/// Test the drawings as outout to stdout.\nfn test_output(n: i32) {\n println!(\"{n}\");\n init_n();\n draw(n);\n unsafe {\n for line in CANVAS.iter() {\n for c in line.iter() {\n print!(\"{}\", *c);\n }\n println!();\n }\n }\n println!(\"\\n\");\n}\n\nfn main() {\n for n in [0, 1, 20, 300, 2022, 4000, 5555, 6789, 9999] {\n test_output(n);\n }\n}\n", "language": "Rust" }, { "code": "import \"./fmt\" for Fmt\n\nvar n\n\nvar init = Fn.new {\n n = List.filled(15, null)\n for (i in 0..14) {\n n[i] = List.filled(11, \" \")\n n[i][5] = \"x\"\n }\n}\n\nvar horiz = Fn.new { |c1, c2, r| (c1..c2).each { |c| n[r][c] = \"x\" } }\nvar verti = Fn.new { |r1, r2, c| (r1..r2).each { |r| n[r][c] = \"x\" } }\nvar diagd = Fn.new { |c1, c2, r| (c1..c2).each { |c| n[r+c-c1][c] = \"x\" } }\nvar diagu = Fn.new { |c1, c2, r| (c1..c2).each { |c| n[r-c+c1][c] = \"x\" } }\n\nvar draw // map contains recursive closures\ndraw = {\n 1: Fn.new { horiz.call(6, 10, 0) },\n 2: Fn.new { horiz.call(6, 10, 4) },\n 3: Fn.new { diagd.call(6, 10, 0) },\n 4: Fn.new { diagu.call(6, 10, 4) },\n 5: Fn.new {\n draw[1].call()\n draw[4].call()\n },\n 6: Fn.new { verti.call(0, 4, 10) },\n 7: Fn.new {\n draw[1].call()\n draw[6].call()\n },\n 8: Fn.new {\n draw[2].call()\n draw[6].call()\n },\n 9: Fn.new {\n draw[1].call()\n draw[8].call()\n },\n 10: Fn.new { horiz.call(0, 4, 0) },\n 20: Fn.new { horiz.call(0, 4, 4) },\n 30: Fn.new { diagu.call(0, 4, 4) },\n 40: Fn.new { diagd.call(0, 4, 0) },\n 50: Fn.new {\n draw[10].call()\n draw[40].call()\n },\n 60: Fn.new { verti.call(0, 4, 0) },\n 70: Fn.new {\n draw[10].call()\n draw[60].call()\n },\n 80: Fn.new {\n draw[20].call()\n draw[60].call()\n },\n 90: Fn.new {\n draw[10].call()\n draw[80].call()\n },\n 100: Fn.new { horiz.call(6, 10, 14) },\n 200: Fn.new { horiz.call(6, 10, 10) },\n 300: Fn.new { diagu.call(6, 10, 14) },\n 400: Fn.new { diagd.call(6, 10, 10) },\n 500: Fn.new {\n draw[100].call()\n draw[400].call()\n },\n 600: Fn.new { verti.call(10, 14, 10) },\n 700: Fn.new {\n draw[100].call()\n draw[600].call()\n },\n 800: Fn.new {\n draw[200].call()\n draw[600].call()\n },\n 900: Fn.new {\n draw[100].call()\n draw[800].call()\n },\n 1000: Fn.new { horiz.call(0, 4, 14) },\n 2000: Fn.new { horiz.call(0, 4, 10) },\n 3000: Fn.new { diagd.call(0, 4, 10) },\n 4000: Fn.new { diagu.call(0, 4, 14) },\n 5000: Fn.new {\n draw[1000].call()\n draw[4000].call()\n },\n 6000: Fn.new { verti.call(10, 14, 0) },\n 7000: Fn.new {\n draw[1000].call()\n draw[6000].call()\n },\n 8000: Fn.new {\n draw[2000].call()\n draw[6000].call()\n },\n 9000: Fn.new {\n draw[1000].call()\n draw[8000].call()\n }\n}\n\nvar numbers = [0, 1, 20, 300, 4000, 5555, 6789, 9999]\nfor (number in numbers) {\n init.call()\n System.print(\"%(number):\")\n var thousands = (number/1000).floor\n number = number % 1000\n var hundreds = (number/100).floor\n number = number % 100\n var tens = (number/10).floor\n var ones = number % 10\n if (thousands > 0) draw[thousands*1000].call()\n if (hundreds > 0) draw[hundreds*100].call()\n if (tens > 0) draw[tens*10].call()\n if (ones > 0) draw[ones].call()\n Fmt.mprint(n, 1, 0, \"\")\n System.print()\n}\n", "language": "Wren" } ]
Cistercian-numerals
[ { "code": "---\ncategory:\n- Object oriented\n- Type System\n- Encyclopedia\nfrom: http://rosettacode.org/wiki/Classes\nnote: Basic language learning\n", "language": "00-META" }, { "code": "In [[object-oriented programming]] '''class''' is a set (a [[wp:Transitive_closure|transitive closure]]) of types bound by the relation of [[inheritance]]. It is said that all types derived from some base type T and the type T itself form a class T. \n\nThe first type T from the class T sometimes is called the '''root type''' of the class.\n\nA class of types itself, as a type, has the values and operations of its own. \nThe operations of are usually called '''methods''' of the root type. \nBoth operations and values are called [[polymorphism | polymorphic]].\n\nA polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. \n\nThe action of choice the type-specific implementation of a polymorphic operation is called '''dispatch'''. Correspondingly, polymorphic operations are often called '''dispatching''' or '''virtual'''. \nOperations with multiple arguments and/or the results of the class are called '''multi-methods'''. \nA further generalization of is the operation with arguments and/or results from different classes.\n\n* single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation ''x''.''f''() is used instead of mathematical ''f''(''x'').\n* multiple-dispatch languages allow many arguments and/or results to control the dispatch.\n\n<br>\nA polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. \nThis type is sometimes called '''the most specific type''' of a [polymorphic] value. \nThe type tag of the value is used in order to resolve the dispatch. \nThe set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.\n\nIn many [[object-oriented programming | OO]] languages \nthe type of the class of T and T itself are considered equivalent. \nIn some languages they are distinct (like in [[Ada]]). \nWhen class T and T are equivalent, there is no way to distinguish \npolymorphic and specific values.\n\n\n;Task:\nCreate a basic class with a method, a constructor, an instance variable and how to instantiate it.\n<br><br>\n", "language": "00-TASK" }, { "code": "T MyType\n Int public_variable // member variable = instance variable\n . Int private_variable\n\n F () // constructor\n .private_variable = 0\n\n F someMethod() // member function = method\n .private_variable = 1\n .public_variable = 10\n", "language": "11l" }, { "code": "T MyType\n F.virtual.new someMethod() -> N // this is polymorphic\n print()\n", "language": "11l" }, { "code": "package {\n public class MyClass {\n\n private var myVariable:int; // Note: instance variables are usually \"private\"\n\n /**\n * The constructor\n */\n public function MyClass() {\n // creates a new instance\n }\n\n /**\n * A method\n */\n public function someMethod():void {\n this.myVariable = 1; // Note: \"this.\" is optional\n // myVariable = 1; works also\n }\n }\n}\n", "language": "ActionScript" }, { "code": "package My_Package is\n type My_Type is tagged private;\n procedure Some_Procedure(Item : out My_Type);\n function Set(Value : in Integer) return My_Type;\nprivate\n type My_Type is tagged record\n Variable : Integer := -12;\n end record;\nend My_Package;\n", "language": "Ada" }, { "code": " package body My_Package is\n procedure Some_Procedure(Item : out My_Type) is\n begin\n Item := 2 * Item;\n end Some_Procedure;\n\n function Set(Value : Integer) return My_Type is\n Temp : My_Type;\n begin\n Temp.Variable := Value;\n return Temp;\n end Set;\nend My_Package;\n", "language": "Ada" }, { "code": "with My_Package; use My_Package;\n\nprocedure Main is\n Foo : My_Type; -- Foo is created and initialized to -12\nbegin\n Some_Procedure(Foo); -- Foo is doubled\n Foo := Set(2007); -- Foo.Variable is set to 2007\nend Main;\n", "language": "Ada" }, { "code": "class Circle (radius, x, y) extends Shape (x, y) implements Drawable {\n var myvec = new Vector (x, y)\n\n public function draw() {\n // draw the circle\n }\n}\n", "language": "Aikido" }, { "code": "MODE MYDATA = STRUCT(\n INT name1\n);\nSTRUCT(\n INT name2,\n PROC (REF MYDATA)REF MYDATA new,\n PROC (REF MYDATA)VOID init,\n PROC (REF MYDATA)VOID some method\n) class my data;\nclass my data := (\n # name2 := # 2, # Class attribute #\n\n # PROC new := # (REF MYDATA new)REF MYDATA:(\n (init OF class my data)(new);\n new\n ),\n\n # PROC init := # (REF MYDATA self)VOID:(\n \"\"\" Constructor (Technically an initializer rather than a true 'constructor') \"\"\";\n name1 OF self := 0 # Instance attribute #\n ),\n\n # PROC some method := # (REF MYDATA self)VOID:(\n \"\"\" Method \"\"\";\n name1 OF self := 1;\n name2 OF class my data := 3\n )\n);\n\n# class name, invoked as a function is the constructor syntax #\nREF MYDATA my data = (new OF class my data)(LOC MYDATA);\n\nMODE GENDEROPT = UNION(STRING, VOID);\nMODE AGEOPT = UNION(INT, VOID);\n\nMODE MYOTHERDATA = STRUCT(\n STRING name,\n GENDEROPT gender,\n AGEOPT age\n);\nSTRUCT (\n INT count,\n PROC (REF MYOTHERDATA, STRING, GENDEROPT, AGEOPT)REF MYOTHERDATA new,\n PROC (REF MYOTHERDATA, STRING, GENDEROPT, AGEOPT)VOID init,\n PROC (REF MYOTHERDATA)VOID del\n) class my other data;\nclass my other data := (\n # count := # 0, # Population of \"(init OF class my other data)\" objects #\n# PROC new := # (REF MYOTHERDATA new, STRING name, GENDEROPT gender, AGEOPT age)REF MYOTHERDATA:(\n (init OF class my other data)(new, name, gender, age);\n new\n ),\n\n # PROC init := # (REF MYOTHERDATA self, STRING name, GENDEROPT gender, AGEOPT age)VOID:(\n \"\"\" One initializer required, others are optional (with different defaults) \"\"\";\n count OF class my other data +:= 1;\n name OF self := name;\n gender OF self := gender;\n CASE gender OF self IN\n (VOID):gender OF self := \"Male\"\n ESAC;\n age OF self := age\n ),\n\n # PROC del := # (REF MYOTHERDATA self)VOID:(\n count OF class my other data -:= 1\n )\n);\n\nPROC attribute error := STRING: error char; # mend the error with the \"error char\" #\n\n# Allocate the instance from HEAP #\nREF MYOTHERDATA person1 = (new OF class my other data)(HEAP MYOTHERDATA, \"John\", EMPTY, EMPTY);\nprint (((name OF person1), \": \",\n (gender OF person1|(STRING gender):gender|attribute error), \" \")); # \"John Male\" #\nprint (((age OF person1|(INT age):age|attribute error), new line)); # Raises AttributeError exception! #\n\n# Allocate the instance from LOC (stack) #\nREF MYOTHERDATA person2 = (new OF class my other data)(LOC MYOTHERDATA, \"Jane\", \"Female\", 23);\nprint (((name OF person2), \": \",\n (gender OF person2|(STRING gender):gender|attribute error), \" \"));\nprint (((age OF person2|(INT age):age|attribute error), new line)) # \"Jane Female 23\" #\n", "language": "ALGOL-68" }, { "code": "OBJECT a_class\n varA, varP\nENDOBJECT\n\n-> this could be used like a constructor\nPROC init() OF a_class\n self.varP := 10\n self.varA := 2\nENDPROC\n\n-> the special proc end() is for destructor\nPROC end() OF a_class\n-> nothing to do here...\nENDPROC\n\n-> a not so useful getter\nPROC getP() OF a_class IS self.varP\n\nPROC main()\n DEF obj : PTR TO a_class\n NEW obj.init()\n WriteF('\\d\\n', obj.varA) -> this can be done, while\n -> varP can't be accessed directly\n WriteF('\\d\\n', obj.varP) -> or\n WriteF('\\d\\n', obj.getP())\n END obj\nENDPROC\n", "language": "AmigaE" }, { "code": "; defining a custom type\ndefine :person [ ; define a new custom type \"Person\"\n name ; with fields: name, surname, age\n surname\n age\n][\n ; with custom post-construction initializer\n init: [\n this\\name: capitalize this\\name\n ]\n\n ; custom print function\n print: [\n render \"NAME: |this\\name|, SURNAME: |this\\surname|, AGE: |this\\age|\"\n ]\n\n ; custom comparison operator\n compare: 'age\n]\n\n; create a method for our custom type\nsayHello: function [this][\n ensure -> is? :person this\n\n print [\"Hello\" this\\name]\n]\n\n; create new objects of our custom type\na: to :person [\"John\" \"Doe\" 34] ; let's create 2 \"Person\"s\nb: to :person [\"jane\" \"Doe\" 33] ; and another one\n\n; call pseudo-inner method\nsayHello a ; Hello John\nsayHello b ; Hello Jane\n\n; access object fields\nprint [\"The first person's name is:\" a\\name] ; The first person's name is: John\nprint [\"The second person's name is:\" b\\name] ; The second person's name is: Jane\n\n; changing object fields\na\\name: \"Bob\"\nsayHello a ; Hello Bob\n\n; verifying object type\nprint type a ; :person\nprint is? :person a ; true\n\n; printing objects\nprint a ; NAME: John, SURNAME: Doe, AGE: 34\n\n; sorting user objects (using custom comparator)\nsort @[a b] ; Jane..., John...\nsort.descending @[a b] ; John..., Jane...\n", "language": "Arturo" }, { "code": "obj := new MyClass\nobj.WhenCreated()\n\nclass MyClass {\n; Instance Variable #1\n time := A_Hour \":\" A_Min \":\" A_Sec\n\n; Constructor\n __New() {\n MsgBox, % \"Constructing new object of type: \" this.__Class\n FormatTime, date, , MM/dd/yyyy\n ; Instance Variable #2\n this.date := date\n }\n; Method\n WhenCreated() {\n MsgBox, % \"Object created at \" this.time \" on \" this.date\n }\n}\n", "language": "AutoHotkey" }, { "code": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books\n\tpublic:\n\t\tconst char* title;\n\t\tconst char* author;\n\t\tconst char* subject;\n\t\tint book_id;\nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books)\nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1 = Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n", "language": "BaCon" }, { "code": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books\n\tpublic:\n\t\tconst char* title;\n\t\tconst char* author;\n\t\tconst char* subject;\n\t\tint book_id;\nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books)\nDECLARE Book1 TYPE Books*\n'--- the correct syntax for class\nBook1 = new Books()\n\n\n'--- initialize the strings const char* in c++\nBook1->title = \"C++ Programming to bacon \"\nBook1->author = \"anyone\"\nBook1->subject =\"RECORD Tutorial\"\nBook1->book_id = 1234567\n\n\nPRINT \"Book title : \" ,Book1->title FORMAT \"%s%s\\n\"\nPRINT \"Book author : \", Book1->author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1->subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1->book_id FORMAT \"%s%d\\n\"\n", "language": "BaCon" }, { "code": " INSTALL @lib$+\"CLASSLIB\"\n\n REM Declare the class:\n DIM MyClass{variable, @constructor, _method}\n DEF MyClass.@constructor MyClass.variable = PI : ENDPROC\n DEF MyClass._method = MyClass.variable ^ 2\n\n REM Register the class:\n PROC_class(MyClass{})\n\n REM Instantiate the class:\n PROC_new(myclass{}, MyClass{})\n\n REM Call the method:\n PRINT FN(myclass._method)\n\n REM Discard the instance:\n PROC_discard(myclass{})\n", "language": "BBC-BASIC" }, { "code": "# Constructors can take parameters (that automatically become properties)\nconstructor Ball(color, radius)\n\t\n\t# Objects can also have functions (closures)\n\t:volume\n\t\treturn 4/3 * {pi} * (radius ** 3)\n\tend\n\t:show\n\t\treturn \"a \" + color + \" ball with radius \" + radius\n\tend\n\t\nend\n\nred_ball = Ball(\"red\", 2)\nprint(red_ball)\n# => a red ball with radius 2\n", "language": "Blz" }, { "code": "ExClass ← {\n 𝕊 value: # Constructor portion\n priv ← value\n priv2 ⇐ 0\n ChangePriv ⇐ { priv ↩ 𝕩 }\n DispPriv ⇐ {𝕊: •Show priv‿priv2 }\n\n}\n\nobj ← ExClass 5\nobj.DispPriv@\nobj.ChangePriv 6\nobj.DispPriv@\n", "language": "BQN" }, { "code": "( ( resolution\n = (x=)\n (y=)\n (new=.!arg:(?(its.x),?(its.y)))\n )\n& new$(resolution,640,480):?VGA\n& new$(resolution,1920,1080):?1080p\n& out$(\"VGA: horizontal \" !(VGA..x) \" vertical \" !(VGA..y)));\n", "language": "Bracmat" }, { "code": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n int variable;\n} *MyClass;\n\nMyClass MyClass_new()\n{\n MyClass pthis = malloc(sizeof *pthis);\n pthis->variable = 0;\n return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n if (pthis)\n {\n free(*pthis);\n *pthis = NULL;\n }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n", "language": "C" }, { "code": "class MyClass\n{\npublic:\n void someMethod(); // member function = method\n MyClass(); // constructor\nprivate:\n int variable; // member variable = instance variable\n};\n\n// implementation of constructor\nMyClass::MyClass():\n variable(0)\n{\n // here could be more code\n}\n\n// implementation of member function\nvoid MyClass::someMethod()\n{\n variable = 1; // alternatively: this->variable = 1\n}\n\n// Create an instance as variable\nMyClass instance;\n\n// Create an instance on free store\nMyClass* pInstance = new MyClass;\n// Instances allocated with new must be explicitly destroyed when not needed any more:\ndelete pInstance;\n", "language": "C++" }, { "code": "class MyClass\n{\npublic:\n MyClass(): variable(0) {}\n void someMethod() { variable = 1; }\nprivate:\n int variable;\n};\n", "language": "C++" }, { "code": "class MyClass\n{\npublic:\n virtual void someMethod(); // this is polymorphic\n virtual ~MyClass(); // destructor\n};\n", "language": "C++" }, { "code": "public class MyClass\n{\n public MyClass()\n {\n }\n public void SomeMethod()\n {\n }\n private int _variable;\n public int Variable\n {\n get { return _variable; }\n set { _variable = value; }\n }\n public static void Main()\n {\n // instantiate it\n MyClass instance = new MyClass();\n // invoke the method\n instance.SomeMethod();\n // set the variable\n instance.Variable = 99;\n // get the variable\n System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n }\n}\n", "language": "C-sharp" }, { "code": "; You can think of this as an interface\n(defprotocol Foo (getFoo [this]))\n\n; Generates Example1 Class with foo as field, with method that returns foo.\n(defrecord Example1 [foo] Foo (getFoo [this] foo))\n\n; Create instance and invoke our method to return field value\n(-> (Example1. \"Hi\") .getFoo)\n\"Hi\"\n", "language": "Clojure" }, { "code": " IDENTIFICATION DIVISION.\n CLASS-ID. my-class INHERITS base.\n\n *> The 'INHERITS base' and the following ENVIRONMENT DIVISION\n *> are optional (in Visual COBOL).\n ENVIRONMENT DIVISION.\n CONFIGURATION SECTION.\n REPOSITORY.\n CLASS base.\n\n *> There is no way (as far as I can tell) of creating a\n *> constructor. However, you could wrap it with another\n *> method to achieve the desired effect.\n *>...\n\n OBJECT.\n *> Instance data\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 instance-variable PIC 9(8).\n\n *> Properties can have getters and setters automatically\n *> generated.\n 01 a-property PIC 9(8) PROPERTY.\n\n PROCEDURE DIVISION.\n\n METHOD-ID. some-method.\n PROCEDURE DIVISION.\n *> ...\n END METHOD some-method.\n END OBJECT.\n END CLASS my-class.\n\n IDENTIFICATION DIVISION.\n PROGRAM-ID. example-class-use.\n\n ENVIRONMENT DIVISION.\n CONFIGURATION SECTION.\n REPOSITORY.\n *> These declarations brings the class and property into\n *> scope.\n CLASS my-class\n PROPERTY a-property.\n\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n *> Declaring a my-class reference variable.\n 01 instance USAGE OBJECT REFERENCE my-class.\n\n PROCEDURE DIVISION.\n\n *> Invoking a static method or (in this case) a constructor.\n INVOKE my-class \"new\" RETURNING instance\n\n *> Invoking an instance method.\n INVOKE instance \"some-method\"\n\n *> Using the setter and getter of a-property.\n MOVE 5 TO a-property OF instance\n DISPLAY a-property OF instance\n\n GOBACK\n .\n\n END PROGRAM example-class-use.\n", "language": "COBOL" }, { "code": "class Rectangle\n # The constructor is defined as a bare function. This\n # constructor accepts one argument and automatically assigns it\n # to an instance variable.\n (@width) ->\n\n # Another instance variable.\n length: 10\n\n # A method.\n area: ->\n @width * @length\n\n# Instantiate the class using the 'new' operator.\nrect = new Rectangle 2\n", "language": "Coco" }, { "code": "# Create a basic class\nclass Rectangle\n # Constructor that accepts one argument\n constructor: (@width) ->\n\n # An instance variable\n length: 10\n\n # A method\n area: () ->\n @width * @length\n\n# Instantiate the class using the new operator\nrect = new Rectangle 2\n", "language": "CoffeeScript" }, { "code": "(defclass circle ()\n ((radius :initarg :radius\n :initform 1.0\n :type number\n :reader radius)))\n\n(defmethod area ((shape circle))\n (* pi (expt (radius shape) 2)))\n\n> (defvar *c* (make-instance 'circle :radius 2))\n> (area *c*)\n12.566370614359172d0\n", "language": "Common-Lisp" }, { "code": "MODULE Point;\nIMPORT\n\tStrings;\nTYPE\n\tInstance* = POINTER TO LIMITED RECORD\n\t\tx-, y- : LONGINT; (* Instance variables *)\n\tEND;\n\t\n\tPROCEDURE (self: Instance) Initialize*(x,y: LONGINT), NEW;\n\tBEGIN\n\t\tself.x := x;\n\t\tself.y := y\n\tEND Initialize;\n\t\n\t(* constructor *)\n\tPROCEDURE New*(x, y: LONGINT): Instance;\n\tVAR\n\t\tpoint: Instance;\n\tBEGIN\n\t\tNEW(point);\n\t\tpoint.Initialize(x,y);\n\t\tRETURN point\n\tEND New;\n\t\n\t(* methods *)\n\tPROCEDURE (self: Instance) Add*(other: Instance): Instance, NEW;\n\tBEGIN\n\t\tRETURN New(self.x + other.x,self.y + other.y);\n\tEND Add;\n\t\n\tPROCEDURE (self: Instance) ToString*(): POINTER TO ARRAY OF CHAR, NEW;\n\tVAR\n\t\txStr,yStr: ARRAY 64 OF CHAR;\n\t\tstr: POINTER TO ARRAY OF CHAR;\n\tBEGIN\n\t\tStrings.IntToString(self.x,xStr);\n\t\tStrings.IntToString(self.y,yStr);\n\t\tNEW(str,128);str^ := \"@(\" +xStr$ + \",\" + yStr$ + \")\";\n\t\tRETURN str\n\tEND ToString;\nEND Point.\n", "language": "Component-Pascal" }, { "code": "MODULE DrivePoint;\nIMPORT\n\tPoint,\n\tStdLog;\n\t\nPROCEDURE Do*;\nVAR\n\tp,q: Point.Instance;\nBEGIN\n\tp := Point.New(1,2);\n\tq := Point.New(2,1);\n\tStdLog.String(p.ToString() + \" + \" + q.ToString() + \" = \" + p.Add(q).ToString());StdLog.Ln;\n\tStdLog.String(\"p.x:> \");StdLog.Int(p.x);StdLog.Ln;\n\tStdLog.String(\"p.y:> \");StdLog.Int(p.y);StdLog.Ln\nEND Do;\n\nEND DrivePoint.\n", "language": "Component-Pascal" }, { "code": "class MyClass\n\n def initialize\n @instance_var = 0\n end\n\n def add_1\n @instance_var += 1\n end\n\nend\n\nmy_class = MyClass.new\n", "language": "Crystal" }, { "code": "import std.stdio;\n\nclass MyClass {\n //constructor (not necessary if empty)\n this() {}\n\n void someMethod() {\n variable = 1;\n }\n\n // getter method\n @property int variable() const {\n return variable_;\n }\n\n // setter method\n @property int variable(int newVariable) {\n return variable_ = newVariable;\n }\n\n private int variable_;\n}\n\nvoid main() {\n // On default class instances are allocated on the heap\n // The GC will manage their lifetime\n auto obj = new MyClass();\n\n // prints 'variable = 0', ints are initialized to 0 by default\n writeln(\"variable = \", obj.variable);\n\n // invoke the method\n obj.someMethod();\n\n // prints 'variable = 1'\n writeln(\"variable = \", obj.variable);\n\n // set the variable using setter method\n obj.variable = 99;\n\n // prints 'variable = 99'\n writeln(\"variable = \", obj.variable);\n}\n", "language": "D" }, { "code": "program SampleClass;\n\n{$APPTYPE CONSOLE}\n\ntype\n TMyClass = class\n private\n FSomeField: Integer; // by convention, fields are usually private and exposed as properties\n public\n constructor Create;\n destructor Destroy; override;\n procedure SomeMethod;\n property SomeField: Integer read FSomeField write FSomeField;\n end;\n\nconstructor TMyClass.Create;\nbegin\n FSomeField := -1\nend;\n\ndestructor TMyClass.Destroy;\nbegin\n // free resources, etc\n\n inherited Destroy;\nend;\n\nprocedure TMyClass.SomeMethod;\nbegin\n // do something\nend;\n\n\nvar\n lMyClass: TMyClass;\nbegin\n lMyClass := TMyClass.Create;\n try\n lMyClass.SomeField := 99;\n lMyClass.SomeMethod();\n finally\n lMyClass.Free;\n end;\nend.\n", "language": "Delphi" }, { "code": "s\n", "language": "DM" }, { "code": "// Declare the class \"/foo\"\nfoo\n // Everything inside the indented block is relative to the parent, \"/foo\" here.\n // Instance variable \"bar\", with a default value of 0\n // Here, var/bar is relative to /foo, thus it becomes \"/foo/var/bar\" ultimately.\n var/bar = 0\n\n // The \"New\" proc is the constructor.\n New()\n // Constructor code.\n\n // Declares a proc called \"Baz\" on /foo\n proc/baz()\n // Do things.\n\n// Instantiation code.\n// Overriding /client/New() means it is ran when a client connects.\n/client/New()\n ..()\n var/foo/x = new /foo()\n x.bar = 10 // Assign to the instance variable.\n x.baz() // Call \"baz\" on our instance.\n", "language": "DM" }, { "code": "class run{\nfunc val(){\nshowln 10+20\n}\n}\n", "language": "Dragon" }, { "code": "type\n TMyClass = class\n private\n FSomeField: Integer; // by convention, fields are usually private and exposed as properties\n public\n constructor Create;\n begin\n FSomeField := -1;\n end;\n procedure SomeMethod;\n property SomeField: Integer read FSomeField write FSomeField;\n end;\n\nprocedure TMyClass.SomeMethod;\nbegin\n // do something\nend;\n\n\nvar lMyClass: TMyClass;\n\nlMyClass := new TMyClass; // can also use TMyClass.Create\n\nlMyClass.SomeField := 99;\nlMyClass.SomeMethod;\n", "language": "DWScript" }, { "code": "def makeColor(name :String) {\n def color {\n to colorize(thing :String) {\n return `$name $thing`\n }\n }\n return color\n}\n", "language": "E" }, { "code": "? def red := makeColor(\"red\")\n# value: <color>\n\n? red.colorize(\"apple\")\n# value: \"red apple\"\n", "language": "E" }, { "code": "(lib 'gloops) ; load oo library\n\n(define-class Person null (name (age :initform 66)))\n(define-method tostring (Person) (lambda (p) ( format \"🚶 %a \" p.name)))\n(define-method mailto (Person Person) (lambda( p o) (printf \"From %a to️ %a : ...\" p o)))\n\n;; define a sub-class of Person with same methods\n(define-class Writer (Person) (books))\n(define-method tostring (Writer) (lambda (w)( format \"🎩 %a\" w.name)))\n(define-method mailto (Person Writer)\n\t(lambda (p w) (printf \" From %a (age %d). Dear writer of %a ...\" p p.age w.books )))\n", "language": "EchoLisp" }, { "code": ";; instantiate\n(define simone (make-instance Person :name 'simone :age 42)) ;; slots values by name\n(define antoinette (make-instance Person :name 'antoinette :age 37))\n(define albert (Person \"albert\" 33)) ;; quick way : slots values in order\n(define simon (make-instance Writer :name \"simon\" :books '(my-life my-bike)))\n\n\n(mailto simone simon) ;; method Person-Writer\n(mailto simone antoinette) ;; method Person-Person\n(mailto simon albert) ;; no method Writer-Person : call 'super' Person-Person\n(mailto simon simon) ;; no mehod Writer-Writer : call 'super' Person-Writer\n →\n From 🚶 simone (age 42). Dear writer of (my-life my-bike) ...\n From 🚶 simone to️ 🚶 antoinette : ...\n From 🎩 simon to️ 🚶 albert : ...\n From 🎩 simon (age 66). Dear writer of (my-life my-bike) ...\n", "language": "EchoLisp" }, { "code": "class MY_CLASS\nend\n", "language": "Eiffel" }, { "code": "class MY_CLASS\n\ncreate\n make\n\nfeature {NONE} -- Initialization\n\n make\n -- This is a creation procedure or \"Constructor\".\n do\n create my_string.make_empty\n end\n\nend\n", "language": "Eiffel" }, { "code": "class MY_CLASS\n\ncreate -- Here we are declaring ...\n make, -- In the Feature group (below) we are coding\n make_this_way, -- each of these declared creation procedures.\n make_that_way, -- We can have as many constructors as we need.\n make_another_way,\n a_name_other_than_make\n\nfeature {NONE} -- Initialization\n\n make\n -- This is a creation procedure or \"Constructor\".\n do\n -- Initialization code goes here ...\n end\n\n make_this_way\n -- Make this way, rather than a plain ole \"make\".\n do\n -- Initialization code goes here ...\n end\n\n make_that_way\n -- Create that way rather than this way (above).\n do\n -- Initialization code goes here ...\n end\n\n make_another_way\n -- And still another way to create MY_CLASS.\n do\n -- Initialization code goes here ...\n end\n\n a_name_other_than_make\n -- There is no requirement to use the word \"make\".\n -- The word \"make\" is just a naming convention.\n do\n -- Initialization code goes here ...\n end\n\nend\n", "language": "Eiffel" }, { "code": "class MY_CLASS\n\ncreate\n make\n\nfeature {NONE} -- Initialization\n\n make\n -- This is a creation procedure or \"Constructor\".\n do\n create my_string.make_empty\n end\n\nfeature -- Access (Properties)\n\n my_string: STRING\n -- This is a comment about `my_string', which is a \"Property\".\n\n my_integer: INTEGER\n -- Unlike `my_string' (above), the INTEGER type is an \"Expanded Type\".\n -- This means INTEGER objects know how to self-initialize.\n\n my_date: DATE\n -- This attribute (or \"Property\") will need to be initialized.\n -- One way to do that is to make a self-initializing attribute, thus ...\n attribute\n create Result.make_now\n end\n\nfeature -- Basic Operations (Methods)\n\n do_something\n -- Loop over and print the numbers 1 to 100 to the console.\n do\n across 1 |..| 100 as i loop print (i.out) end\n end\n\n do_something_else\n -- Set a and b and print the result.\n local\n a, b, c: INTEGER\n do\n a := 1\n b := 2\n c := a + b\n end\n\nend\n", "language": "Eiffel" }, { "code": "import extensions;\n\nclass MyClass\n{\n int Variable : prop;\n\n someMethod()\n {\n Variable := 1\n }\n\n constructor()\n {\n }\n}\n\npublic program()\n{\n // instantiate the class\n var instance := new MyClass();\n\n // invoke the method\n instance.someMethod();\n\n // get the variable\n console.printLine(\"Variable=\",instance.Variable)\n}\n", "language": "Elena" }, { "code": "type Bear ^| the type system is informed about the new type,\n | here we are in the static context\n |^\nmodel # instance context\n text name # instance variable\n ^|\n | in EMal the instance variables are ordered, and a default\n | variadic constructor is provided by the runtime.\n | Every value passed to the constructor sets the instance variable\n | according to the order.\n |^\n fun makeNoise = void by block # method of Bear\n writeLine(\"Growl!\")\n end\nend\ntype Cat\nmodel\n text noise\n new by text noise # an explicit constructor\n me.noise = noise # we must use me to access instance variables\n end\n fun makeNoise = void by block\n writeLine(me.noise)\n end\nend\ntype Main\nBear bear = Bear(\"Bruno\") # creating a new instance\nwriteLine(\"The bear is called \" + bear.name)\nbear.makeNoise()\nCat(\"Meow\").makeNoise()\n", "language": "EMal" }, { "code": "PROGRAM CLASS2_DEMO\n\nCLASS QUADRATO\n\n LOCAL LATO\n\n PROCEDURE GETLATO(L)\n LATO=L\n END PROCEDURE\n\n PROCEDURE AREA(->A)\n A=LATO*LATO\n END PROCEDURE\n\n PROCEDURE PERIMETRO(->P)\n P=4*LATO\n END PROCEDURE\n\nEND CLASS\n\nNEW P:QUADRATO,Q:QUADRATO\n\nBEGIN\n P_GETLATO(10)\n P_AREA(->AREAP)\n PRINT(AREAP)\n Q_GETLATO(20)\n Q_PERIMETRO(->PERIMETROQ)\n PRINT(PERIMETROQ)\nEND PROGRAM\n", "language": "ERRE" }, { "code": "type MyClass(init) = // constructor with one argument: init\n let mutable var = init // a private instance variable\n member x.Method() = // a simple method\n var <- var + 1\n printfn \"%d\" var\n\n// create an instance and use it\nlet myObject = new MyClass(42)\nmyObject.Method()\n", "language": "F-Sharp" }, { "code": "open System\n\ntype Shape =\n abstract Perimeter: unit -> float\n abstract Area: unit -> float\n\ntype Circle(radius) =\n interface Shape with\n member x.Perimeter() = 2.0 * radius * Math.PI\n member x.Area() = Math.PI * radius**2.0\n\ntype Rectangle(width, height) =\n interface Shape with\n member x.Perimeter() = 2.0 * width + 2.0 * height\n member x.Area() = width * height\n", "language": "F-Sharp" }, { "code": "TUPLE: my-class foo bar baz ;\nM: my-class quux foo>> 20 + ;\nC: <my-class> my-class\n10 20 30 <my-class> quux ! result: 30\nTUPLE: my-child-class < my-class quxx ;\nC: <my-child-class> my-child-class\nM: my-child-class foobar 20 >>quux ;\n20 20 30 <my-child-class> foobar quux ! result: 30\n", "language": "Factor" }, { "code": "class class_name[ ( param_list ) ] [ from inh1[, inh2, ..., inhN] ]\n [ static block ]\n [ properties declaration ]\n [init block]\n [method list]\nend\n", "language": "Falcon" }, { "code": "class mailbox( max_msg )\n\n capacity = max_msg * 10\n name = nil\n messages = []\n\n init\n printl( \"Box now ready for \", self.capacity, \" messages.\" )\n end\n\n function slot_left()\n return self.capacity - len( self.messages )\n end\n\nend\n", "language": "Falcon" }, { "code": "m = mailbox( 10 )\n// Ouputs: Box now ready for 100 messages.\n", "language": "Falcon" }, { "code": "class MyClass {\n read_slot: 'instance_var # creates getter method for @instance_var\n @@class_var = []\n\n def initialize {\n # 'initialize' is the constructor method invoked during 'MyClass.new' by convention\n @instance_var = 0\n }\n\n def some_method {\n @instance_var = 1\n @another_instance_var = \"foo\"\n }\n\n # define class methods: define a singleton method on the class object\n def self class_method {\n # ...\n }\n\n # you can also name the class object itself\n def MyClass class_method {\n # ...\n }\n}\n\nmyclass = MyClass new\n", "language": "Fancy" }, { "code": "class MyClass\n{\n // an instance variable\n Int x\n\n // a constructor, providing default value for instance variable\n new make (Int x := 1)\n {\n this.x = x\n }\n\n // a method, return double the number x\n public Int double ()\n {\n return 2 * x\n }\n}\n\nclass Main\n{\n public static Void main ()\n {\n a := MyClass (2) // instantiates the class, with x = 2\n b := MyClass() // instantiates the class, x defaults to 1\n c := MyClass { x = 3 } // instantiates the class, sets x to 3\n }\n}\n", "language": "Fantom" }, { "code": ":class MyClass <super Object\n\n int memvar\n\n :m ClassInit: ( -- )\n ClassInit: super\n 1 to memvar ;m\n\n :m ~: ( -- ) .\" Final \" show: [ Self ] ;m\n\n :m set: ( n -- ) to memvar ;m\n :m show: ( -- ) .\" Memvar = \" memvar . ;m\n\n;class\n", "language": "Forth" }, { "code": "MyClass newInstance\n", "language": "Forth" }, { "code": "New> MyClass value newInstance\n", "language": "Forth" }, { "code": "10 set: newInstance\nshow: newInstance\n", "language": "Forth" }, { "code": "newInstance dispose\n0 to newInstance \\ no dangling pointers!\n", "language": "Forth" }, { "code": ": test { \\ obj -- }\n New> MyClass to obj\n show: obj\n 1000 set: obj\n obj dispose ;\n", "language": "Forth" }, { "code": "include FMS-SI.f\n\n:class foo \\ begin class foo definition\n ivar x \\ declare an instance variable named x\n :m put ( n -- ) x ! ;m \\ a method/message definition\n :m init: 10 self put ;m \\ the constructor method\n :m print x ? ;m \\ a print method for x\n;class \\ end class foo definition\n\nfoo f1 \\ instantiate a foo object, in the dictionary, named f1\nf1 print \\ 10 send the print message to object f1\n20 f1 put \\ send a message with one parameter to the object\nf1 print \\ 20\n\n\n: bar \\ bar is a normal Forth function definition\n heap> foo \\ instantiate a nameless object in the heap\n dup print\n 30 over put\n dup print\n <free ; \\ destroy the heap object\n\n: bar' \\ bar' is an alternative to bar that uses a local variable\n heap> foo {: f :}\n f print\n 30 f put\n f print\n f <free ;\n\nbar \\ 10 30\nbar' \\ 10 30\n", "language": "Forth" }, { "code": "!-----------------------------------------------------------------------\n!Module accuracy defines precision and some constants\n!-----------------------------------------------------------------------\nmodule accuracy_module\n implicit none\n integer, parameter, public :: rdp = kind(1.d0)\n ! constants\n real(rdp), parameter :: pi=3.141592653589793238462643383279502884197_rdp\nend module accuracy_module\n\n!-----------------------------------------------------------------------\n!Module typedefs_module contains abstract derived type and extended type definitions.\n! Note that a reserved word \"class\" in Fortran is used to describe\n! some polymorphic variable whose data type may vary at run time.\n!-----------------------------------------------------------------------\nmodule typedefs_module\n use accuracy_module\n implicit none\n\n private ! all\n public :: TPoint, TShape, TCircle, TRectangle, TSquare ! public only these defined derived types\n\n ! abstract derived type\n type, abstract :: TShape\n real(rdp) :: area\n character(len=:),allocatable :: name\n contains\n ! deferred method i.e. abstract method = must be overridden in extended type\n procedure(calculate_area), deferred,pass :: calculate_area\n end type TShape\n ! just declaration of the abstract method/procedure for TShape type\n abstract interface\n function calculate_area(this)\n use accuracy_module\n import TShape !imports TShape type from host scoping unit and makes it accessible here\n implicit none\n class(TShape) :: this\n real(rdp) :: calculate_area\n\n end function calculate_area\n end interface\n\n ! auxiliary derived type\n type TPoint\n real(rdp) :: x,y\n end type TPoint\n\n ! extended derived type\n type, extends(TShape) :: TCircle\n real(rdp) :: radius\n real(rdp), private :: diameter\n type(TPoint) :: centre\n contains\n procedure, pass :: calculate_area => calculate_circle_area\n procedure, pass :: get_circle_diameter\n final :: finalize_circle\n end type TCircle\n\n ! extended derived type\n type, extends(TShape) :: TRectangle\n type(TPoint) :: A,B,C,D\n contains\n procedure, pass :: calculate_area => calculate_rectangle_area\n final :: finalize_rectangle\n end type TRectangle\n\n ! extended derived type\n type, extends(TRectangle) :: TSquare\n contains\n procedure, pass :: calculate_area => calculate_square_area\n final :: finalize_square\n end type TSquare\n\n contains\n\n ! finalization subroutines for each type\n ! They called recursively, i.e. finalize_rectangle\n ! will be called after finalize_square subroutine\n subroutine finalize_circle(x)\n type(TCircle), intent(inout) :: x\n write(*,*) \"Deleting TCircle object\"\n end subroutine finalize_circle\n\n subroutine finalize_rectangle(x)\n type(TRectangle), intent(inout) :: x\n write(*,*) \"Deleting also TRectangle object\"\n end subroutine finalize_rectangle\n\n subroutine finalize_square(x)\n type(TSquare), intent(inout) :: x\n write(*,*) \"Deleting TSquare object\"\n end subroutine finalize_square\n\n function calculate_circle_area(this)\n implicit none\n class(TCircle) :: this\n real(rdp) :: calculate_circle_area\n this%area = pi * this%radius**2\n calculate_circle_area = this%area\n end function calculate_circle_area\n\n function calculate_rectangle_area(this)\n implicit none\n class(TRectangle) :: this\n real(rdp) :: calculate_rectangle_area\n ! here could be more code\n this%area = 1\n calculate_rectangle_area = this%area\n end function calculate_rectangle_area\n\n function calculate_square_area(this)\n implicit none\n class(TSquare) :: this\n real(rdp) :: calculate_square_area\n ! here could be more code\n this%area = 1\n calculate_square_area = this%area\n end function calculate_square_area\n\n function get_circle_diameter(this)\n implicit none\n class(TCircle) :: this\n real(rdp) :: get_circle_diameter\n this % diameter = 2.0_rdp * this % radius\n get_circle_diameter = this % diameter\n end function get_circle_diameter\n\nend module typedefs_module\n\n!-----------------------------------------------------------------------\n!Main program\n!-----------------------------------------------------------------------\nprogram rosetta_class\n use accuracy_module\n use typedefs_module\n implicit none\n\n ! we need this subroutine in order to show the finalization\n call test_types()\n\n contains\n\n subroutine test_types()\n implicit none\n ! declare object of type TPoint\n type(TPoint), target :: point\n ! declare object of type TCircle\n type(TCircle),target :: circle\n ! declare object of type TSquare\n type(TSquare),target :: square\n\n ! declare pointers\n class(TPoint), pointer :: ppo\n class(TCircle), pointer :: pci\n class(TSquare), pointer :: psq\n\n !constructor\n point = TPoint(5.d0,5.d0)\n ppo => point\n write(*,*) \"x=\",point%x,\"y=\",point%y\n\n pci => circle\n\n pci % radius = 1\n write(*,*) pci % radius\n ! write(*,*) pci % diameter !No,it is a PRIVATE component\n write(*,*) pci % get_circle_diameter()\n write(*,*) pci % calculate_area()\n write(*,*) pci % area\n\n psq => square\n\n write(*,*) psq % area\n write(*,*) psq % calculate_area()\n write(*,*) psq % area\n end subroutine test_types\n\nend program rosetta_class\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nType MyClass\n Private:\n myInt_ As Integer\n Public:\n Declare Constructor(myInt_ As Integer)\n Declare Property MyInt() As Integer\n Declare Function Treble() As Integer\nEnd Type\n\nConstructor MyClass(myInt_ As Integer)\n This.myInt_ = myInt_\nEnd Constructor\n\nProperty MyClass.MyInt() As Integer\n Return myInt_\nEnd Property\n\nFunction MyClass.Treble() As Integer\n Return 3 * myInt_\nEnd Function\n\nDim mc As MyClass = MyClass(24)\nPrint mc.MyInt, mc.Treble()\nPrint \"Press any key to quit the program\"\nSleep\n", "language": "FreeBASIC" }, { "code": "struct Rectangle{\n float width;\n float height;\n};\n\nRectangle new(float width,float height){\n Rectangle self;\n self.width = width;\n self.height = height;\n return self;\n}\n\nfloat area(Rectangle self){\n return self.width*self.height;\n}\n\nfloat perimeter(Rectangle self){\n return (self.width+self.height)*2.0;\n}\n", "language": "GLSL" }, { "code": "package main\n\nimport \"fmt\"\n\n// a basic \"class.\"\n// In quotes because Go does not use that term or have that exact concept.\n// Go simply has types that can have methods.\ntype picnicBasket struct {\n nServings int // \"instance variables\"\n corkscrew bool\n}\n\n// a method (yes, Go uses the word method!)\nfunc (b *picnicBasket) happy() bool {\n return b.nServings > 1 && b.corkscrew\n}\n\n// a \"constructor.\"\n// Also in quotes as Go does not have that exact mechanism as part of the\n// language. A common idiom however, is a function with the name new<Type>,\n// that returns a new object of the type, fully initialized as needed and\n// ready to use. It makes sense to use this kind of constructor function when\n// non-trivial initialization is needed. In cases where the concise syntax\n// shown is sufficient however, it is not idiomatic to define the function.\n// Rather, code that needs a new object would simply contain &picnicBasket{...\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n // arbitrary code to interpret arguments, check resources, etc.\n // ...\n // return data new object.\n // this is the concise syntax. there are other ways of doing it.\n return &picnicBasket{nPeople, nPeople > 0}\n}\n\n// how to instantiate it.\nfunc main() {\n var pb picnicBasket // create on stack (probably)\n pbl := picnicBasket{} // equivalent to above\n pbp := &picnicBasket{} // create on heap. pbp is pointer to object.\n pbn := new(picnicBasket) // equivalent to above\n forTwo := newPicnicBasket(2) // using constructor\n // equivalent to above. field names, called keys, are optional.\n forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n fmt.Println(pb.nServings, pb.corkscrew)\n fmt.Println(pbl.nServings, pbl.corkscrew)\n fmt.Println(pbp)\n fmt.Println(pbn)\n fmt.Println(forTwo)\n fmt.Println(forToo)\n}\n", "language": "Go" }, { "code": "import reflect\n\ntype happinessTester interface {\n happy() bool\n}\n\ntype bottleOfWine struct {\n USD float64\n empty bool\n}\n\nfunc (b *bottleOfWine) happy() bool {\n return b.USD > 10 && !b.empty\n}\n\nfunc main() {\n partySupplies := []happinessTester{\n &picnicBasket{2, true},\n &bottleOfWine{USD: 6},\n }\n for _, ps := range partySupplies {\n fmt.Printf(\"%s: happy? %t\\n\",\n reflect.Indirect(reflect.ValueOf(ps)).Type().Name(),\n ps.happy())\n }\n}\n", "language": "Go" }, { "code": "/** Ye olde classe declaration */\nclass Stuff {\n /** Heare bee anne instance variable declared */\n def guts\n\n /** This constructor converts bits into Stuff */\n Stuff(injectedGuts) {\n guts = injectedGuts\n }\n\n /** Brethren and sistren, let us flangulate with this fine flangulating method */\n def flangulate() {\n println \"This stuff is flangulating its guts: ${guts}\"\n }\n}\n", "language": "Groovy" }, { "code": "def stuff = new Stuff('''\nI have made mistakes in the past.\nI have made mistakes in the future.\n -- Vice President Dan Quayle\n''')\n\nstuff.flangulate()\n\nstuff.guts = '''\nOur enemies are innovative and resourceful, and so are we.\nThey never stop thinking about new ways to harm our country and our people,\nand neither do we.\n -- President George W. Bush\n'''\n\nstuff.flangulate()\n", "language": "Groovy" }, { "code": "class Shape a where\n perimeter :: a -> Double\n area :: a -> Double\n{- A type class Shape. Types belonging to Shape must support two\nmethods, perimeter and area. -}\n\ndata Rectangle = Rectangle Double Double\n{- A new type with a single constructor. In the case of data types\nwhich have only one constructor, we conventionally give the\nconstructor the same name as the type, though this isn't mandatory. -}\n\ndata Circle = Circle Double\n\ninstance Shape Rectangle where\n perimeter (Rectangle width height) = 2 * width + 2 * height\n area (Rectangle width height) = width * height\n{- We made Rectangle an instance of the Shape class by\nimplementing perimeter, area :: Rectangle -> Int. -}\n\ninstance Shape Circle where\n perimeter (Circle radius) = 2 * pi * radius\n area (Circle radius) = pi * radius^2\n\napRatio :: Shape a => a -> Double\n{- A simple polymorphic function. -}\napRatio shape = area shape / perimeter shape\n\nmain = do\n print $ apRatio $ Circle 5\n print $ apRatio $ Rectangle 5 5\n{- The correct version of apRatio (and hence the correct\nimplementations of perimeter and area) is chosen based on the type\nof the argument. -}\n", "language": "Haskell" }, { "code": "data Shape = Rectangle Double Double | Circle Double\n{- This Shape is a type rather than a type class. Rectangle and\nCircle are its constructors. -}\n\nperimeter :: Shape -> Double\n{- An ordinary function, not a method. -}\nperimeter (Rectangle width height) = 2 * width + 2 * height\nperimeter (Circle radius) = 2 * pi * radius\n\narea :: Shape -> Double\narea (Rectangle width height) = width * height\narea (Circle radius) = pi * radius^2\n\napRatio :: Shape -> Double\n{- Technically, this version of apRatio is monomorphic. -}\napRatio shape = area shape / perimeter shape\n\nmain = do\n print $ apRatio $ Circle 5\n print $ apRatio $ Rectangle 5 5\n{- The value returned by apRatio is determined by the return values\nof area and perimeter, which just happen to be defined differently\nfor Rectangles and Circles. -}\n", "language": "Haskell" }, { "code": "class Example (x) # 'x' is a field in class\n\n # method definition\n method double ()\n return 2 * x\n end\n\n # 'initially' block is called on instance construction\n initially (x)\n if /x # if x is null (not given), then set field to 0\n then self.x := 0\n else self.x := x\nend\n\nprocedure main ()\n x1 := Example () # new instance with default value of x\n x2 := Example (2) # new instance with given value of x\n write (x1.x)\n write (x2.x)\n write (x2.double ()) # call a method\nend\n", "language": "Haskell" }, { "code": "coclass 'exampleClass'\n\nexampleMethod=: monad define\n 1+exampleInstanceVariable\n)\n\ncreate=: monad define\n 'this is the constructor'\n)\n\nexampleInstanceVariable=: 0\n", "language": "J" }, { "code": " exampleObject=: conew 'exampleClass'\n", "language": "J" }, { "code": "public class MyClass{\n\n // instance variable\n private int variable; // Note: instance variables are usually \"private\"\n\n /**\n * The constructor\n */\n public MyClass(){\n // creates a new instance\n }\n\n /**\n * A method\n */\n public void someMethod(){\n this.variable = 1;\n }\n}\n", "language": "Java" }, { "code": "new MyClass();\n", "language": "Java" }, { "code": "//Constructor function.\nfunction Car(brand, weight) {\n this.brand = brand;\n this.weight = weight || 1000; // Resort to default value (with 'or' notation).\n}\nCar.prototype.getPrice = function() { // Method of Car.\n return this.price;\n}\n\nfunction Truck(brand, size) {\n this.car = Car;\n this.car(brand, 2000); // Call another function, modifying the \"this\" object (e.g. \"superconstructor\".)\n this.size = size; // Custom property for just this object.\n}\nTruck.prototype = Car.prototype; // Also \"import\" the prototype from Car.\n\nvar cars = [ // Some example car objects.\n new Car(\"Mazda\"),\n new Truck(\"Volvo\", 2)\n];\nfor (var i=0; i<cars.length; i++) {\n alert(cars[i].brand + \" \" + cars[i].weight + \" \" + cars[i].size + \", \" +\n (cars[i] instanceof Car) + \" \" + (cars[i] instanceof Truck));\n}\n", "language": "JavaScript" }, { "code": "class Car {\n /**\n * A few brands of cars\n * @type {string[]}\n */\n static brands = ['Mazda', 'Volvo'];\n\n /**\n * Weight of car\n * @type {number}\n */\n weight = 1000;\n\n /**\n * Brand of car\n * @type {string}\n */\n brand;\n\n /**\n * Price of car\n * @type {number}\n */\n price;\n\n /**\n * @param {string} brand - car brand\n * @param {number} weight - mass of car\n */\n constructor(brand, weight) {\n if (brand) this.brand = brand;\n if (weight) this.weight = weight\n }\n\n /**\n * Drive\n * @param distance - distance to drive\n */\n drive(distance = 10) {\n console.log(`A ${this.brand} ${this.constructor.name} drove ${distance}cm`);\n }\n\n /**\n * Formatted stats string\n */\n get formattedStats() {\n let out =\n `Type: ${this.constructor.name.toLowerCase()}`\n + `\\nBrand: ${this.brand}`\n + `\\nWeight: ${this.weight}`;\n\n if (this.size) out += `\\nSize: ${this.size}`;\n\n return out\n }\n}\n\nclass Truck extends Car {\n /**\n * Size of truck\n * @type {number}\n */\n size;\n\n /**\n * @param {string} brand - car brand\n * @param {number} size - size of car\n */\n constructor(brand, size) {\n super(brand, 2000);\n if (size) this.size = size;\n }\n}\n\nlet myTruck = new Truck('Volvo', 2);\nconsole.log(myTruck.formattedStats);\nmyTruck.drive(40);\n", "language": "JavaScript" }, { "code": "abstract type Mammal end\nhabitat(::Mammal) = \"planet Earth\"\n\nstruct Whale <: Mammal\n mass::Float64\n habitat::String\nend\nBase.show(io::IO, ::Whale) = print(io, \"a whale\")\nhabitat(w::Whale) = w.habitat\n\nstruct Wolf <: Mammal\n mass::Float64\nend\nBase.show(io::IO, ::Wolf) = print(io, \"a wolf\")\n\narr = [Whale(1000, \"ocean\"), Wolf(50)]\nprintln(\"Type of $arr is \", typeof(arr))\nfor a in arr\n println(\"Habitat of $a: \", habitat(a))\nend\n", "language": "Julia" }, { "code": "class MyClass(val myInt: Int) {\n fun treble(): Int = myInt * 3\n}\n\nfun main(args: Array<String>) {\n val mc = MyClass(24)\n print(\"${mc.myInt}, ${mc.treble()}\")\n}\n", "language": "Kotlin" }, { "code": "define mytype => type {\n\tdata\n\t\tpublic id::integer\t\t= 0,\n\t\tpublic val::string\t\t= '',\n\t\tpublic rand::integer\t= 0\n\n\tpublic onCreate() => {\n\t\t// \"onCreate\" runs when instance created, populates .rand\n\t\t.rand = math_random(50,1)\n\t}\n\tpublic asString() => {\n\t\treturn 'has a value of: \"'+.val+'\" and a rand number of \"'+.rand+'\"'\n\t}\n\t\n}\n\nlocal(x = mytype)\n#x->val = '99 Bottles of beer'\n#x->asString // outputs 'has a value of: \"99 Bottles of beer\" and a rand number of \"48\"'\n", "language": "Lasso" }, { "code": "(defmodule simple-object\n (export all))\n\n(defun fish-class (species)\n \"\n This is the constructor used internally, once the children and fish id are\n known.\n \"\n (let ((habitat '\"water\"))\n (lambda (method-name)\n (case method-name\n ('habitat\n (lambda (self) habitat))\n ('species\n (lambda (self) species))))))\n\n(defun get-method (object method-name)\n \"\n This is a generic function, used to call into the given object (class\n instance).\n \"\n (funcall object method-name))\n\n; define object methods\n(defun get-habitat (object)\n \"Get a variable set in the class.\"\n (funcall (get-method object 'habitat) object))\n\n(defun get-species (object)\n \"Get a variable passed when constructing the object.\"\n (funcall (get-method object 'species) object))\n", "language": "LFE" }, { "code": "> (slurp '\"simple-object.lfe\")\n#(ok simple-object)\n> (set my-fish (fish-class '\"Carp\"))\n#Fun<lfe_eval.10.91765564>\n> (get-habitat my-fish)\n\"water\"\n> (get-species my-fish)\n\"Carp\"\n", "language": "LFE" }, { "code": "----------------------------------------\n-- @desc Class \"MyClass\"\n-- @file parent script \"MyClass\"\n----------------------------------------\n\n-- instance variable\nproperty _myvar\n\n-- constructor\non new (me)\n me._myvar = 23\n return me\nend\n\n-- a method\non doubleAndPrint (me)\n me._myvar = me._myvar * 2\n put me._myvar\nend\n", "language": "Lingo" }, { "code": "foo = script(\"MyClass\").new()\nfoo.doubleAndPrint()\n-- 46\n", "language": "Lingo" }, { "code": "Section Header\n\n+ name := SAMPLE;\n\nSection Inherit\n\n- parent : OBJECT := OBJECT;\n\nSection Private\n\n+ variable : INTEGER <- 0;\n\nSection Public\n\n- some_method <- (\n variable := 1;\n);\n\n- main <- (\n + sample : SAMPLE;\n\n sample := SAMPLE.clone;\n sample.some_method;\n);\n", "language": "Lisaac" }, { "code": ":- object(metaclass,\n instantiates(metaclass)).\n\n :- public(new/2).\n new(Instance, Value) :-\n self(Class),\n create_object(Instance, [instantiates(Class)], [], [state(Value)]).\n\n:- end_object.\n\n:- object(class,\n instantiates(metaclass)).\n\n :- public(method/1).\n method(Value) :-\n ::state(Value).\n\n :- private(state/1).\n\n:- end_object.\n", "language": "Logtalk" }, { "code": "| ?- class::new(Instance, 1).\nInstance = o1\nyes\n\n| ?- o1::method(Value).\nValue = 1\nyes\n", "language": "Logtalk" }, { "code": "myclass = setmetatable({\n__index = function(z,i) return myclass[i] end, --this makes class variables a possibility\nsetvar = function(z, n) z.var = n end\n}, {\n__call = function(z,n) return setmetatable({var = n}, myclass) end\n})\n\ninstance = myclass(3)\n\nprint(instance.var) -->3\n\ninstance:setvar(6)\n\nprint(instance.var) -->6\n", "language": "Lua" }, { "code": "Class zz {\n module bb {\n Superclass A {\n unique:\n counter\n }\n Superclass B1 {\n unique:\n counter\n }\n Superclass B2 {\n unique:\n counter\n }\n \\\\ We can make a group Alfa with a member, another group Beta\n \\\\ Group Beta can't see parent group, but can see own member groups\n \\\\ Group Alfa can see everything in nested groups, in any level,\n \\\\ but can't see inside modules/functions/operator/value/set\n Group Alfa {\n Group Beta { }\n }\n Alfa=A\n Alfa.Beta=B1\n \\\\ we make 3 groups for marshaling counters\n \\\\ each group get a superclass\n Marshal1=A\n Marshal2=B1\n Marshal3=B2\n \\\\ Now we want to add functionality7\n \\\\ Inc module to add 1 to counter\n \\\\ a Value function to return counter\n \\\\ Without Value a group return a copy\n \\\\ If a group has a value then we can get copy using Group(nameofgroup)\n \\\\ just delete Group Marshal1 and remove Rem when we make Marshal1 using a class function\n Group Marshal1 {\n Module Inc {\n For SuperClass {.counter++}\n }\n Value {\n For SuperClass {=.counter}\n }\n }\n Class AnyMarshal {\n Module Inc {\n For SuperClass {.counter++}\n }\n Value {\n For SuperClass {=.counter}\n }\n }\n \\\\ here we merge groups\n Rem : Marshal1=AnyMarshal()\n Marshal2=AnyMarshal()\n Marshal3=AnyMarshal()\n\n \\\\ So now we see counters (three zero)\n Print Marshal1, Marshal2, Marshal3 \\\\ 0, 0, 0\n \\\\ Now we prepare Alfa and Alfa.Beta groups\n Group Alfa {\n Group Beta {\n Function SuperClass.Counter {\n For SuperClass {\n =.counter\n }\n }\n }\n Module PrintData {\n For SuperClass {\n Print .counter, This.Beta.SuperClass.Counter()\n }\n }\n }\n \\\\ some marshaling to counters\n Marshal1.inc\n Marshal2.inc\n Marshal2.inc\n Marshal3.inc\n \\\\ lets print results\n Print Marshal1, Marshal2, Marshal3 \\\\ 1 2 1\n \\\\ Calling Alfa.PrintData\n Alfa.PrintData \\\\ 1 2\n \\\\ Merging a group in a group make a change to superclass pointer inside group\n Alfa.Beta=B2 \\\\ change supeclass\n Alfa.PrintData \\\\ 1 1\n For i=1 to 10 : Marshal3.inc : Next i\n Alfa.PrintData \\\\ 1 11\n Alfa.Beta=B1 \\\\ change supeclass\n Alfa.PrintData \\\\ 1 2\n Epsilon=Alfa\n Print Valid(@alfa as epsilon), Valid(@alfa.beta as epsilon.beta) \\\\ -1 -1\n Epsilon.PrintData \\\\ 1 2\n Alfa.Beta=B2 \\\\ change supeclass\n Alfa.PrintData \\\\ 1 11\n Epsilon.PrintData \\\\ 1 2\n \\\\ validation being for top group superclass and all members if are same\n \\\\ but not for inner superclasses. This maybe change in later revisions of language.\n Print Valid(@alfa as epsilon), Valid(@alfa.beta as epsilon.beta) \\\\ -1 0\n\n }\n}\nDim A(10)\nA(3)=zz()\nA(3).bb\n\nReport {\n\tthere is no super like java super in M2000 when we use inheritance through classes\n\tsee Superclass (example SUP) which is something differnent\n\t}\n\n\nclass Shape {\nprivate:\n super.X, super.Y\n Function super.toString$(a=10) {\n =\"Shape(\" + str$(.super.X,\"\") + \", \" + str$(.super.Y,\"\") + \")\"\n }\npublic:\n Module final setPosition (px, py) {\n .super.X <= px\n .super.Y <= py\n }\n Function toString$() {\n =.super.toString$()\n }\n}\nclass MoveShape {\n Module MoveRelative(xr, yr) {\n .super.X+=xr\n .super.Y+=yr\n }\n}\nclass Circle as MoveShape as Shape {\nprivate:\n radius\npublic:\n Module setRadius (r) {\n .radius <= r\n }\n Function toString$() {\n = .super.toString$() + \": Circle(\" + str$(.radius,\"\") + \")\"\n }\n}\n\nclass Rectangle as MoveShape as Shape {\nprivate:\n height, width\npublic:\n Module MoveLeftSide (p as *Rectangle) {\n \\\\ for same type objects private members are like public\n for This, p {\n .super.X<=..super.X+..width\n .super.Y<=..super.Y\n }\n }\n module setDimensions (h,w) {\n .height <= h\n .width <= w\n }\n Function toString$() {\n = .super.toString$() + \": Rectangle(\" + str$(.height,\"\") + \" x \" + str$(.width,\"\") + \")\"\n }\n}\nc =Circle()\nr = Rectangle()\n\nr.setPosition 1, 2\nr.setDimensions 50, 50\nc.setPosition 3, 4\nc.setRadius 10\nPrint r.tostring$()\nPrint c.tostring$()\nr.MoveRelative 100,100\nc.MoveRelative -50,-50\nPrint r.tostring$()\nPrint c.tostring$()\n\nReport {\n\twokring with pointers like in c++\n\tpointers in M2000 are objects, so null pointer (pc->0&) isn't a zero, but an empty Group (object)\n\t}\npc->circle()\npr->rectangle()\npr=>setPosition 1, 2\npr=>setDimensions 50, 50\npc=>setPosition 3, 4\npc=>setRadius 10\nPrint pr=>tostring$()\nPrint pc=>tostring$()\n\\\\ we can open up to ten objects (from one to ten dots, normaly one to three)\n\\\\ if we use nestef for object {} also we have up to ten objects in total\n\\\\ every for object {} is an area for temporary definitions, after exit from brackets\n\\\\ any new definition erased.\nFor pr, pc {\n\t.MoveRelative 100,100\n\t..MoveRelative -50,-50\n\tPrint .tostring$()\n\tPrint ..tostring$()\n}\npr2->rectangle()\npr2=>SetDimensions 30, 30\npr2=>MoveLeftSide pr\nPrint pr2=>toString$()\n", "language": "M2000-Interpreter" }, { "code": "function GenericClassInstance = GenericClass(varargin)\n\n if isempty(varargin) %No input arguments\n GenericClassInstance.classVariable = 0; %Generates a struct\n else\n GenericClassInstance.classVariable = varargin{1}; %Generates a struct\n end\n\n %Converts the struct to a class of type GenericClass\n GenericClassInstance = class(GenericClassInstance,'GenericClass');\n\nend\n", "language": "MATLAB" }, { "code": "%Get function\nfunction value = getValue(GenericClassInstance)\n value = GenericClassInstance.classVariable;\nend\n", "language": "MATLAB" }, { "code": "%Set function\nfunction GenericClassInstance = setValue(GenericClassInstance,newValue)\n GenericClassInstance.classVariable = newValue;\nend\n", "language": "MATLAB" }, { "code": "function display(GenericClassInstance)\n disp(sprintf('%f',GenericClassInstance.classVariable));\nend\n", "language": "MATLAB" }, { "code": ">> myClass = GenericClass(3)\n3.000000\n>> myClass = setValue(myClass,pi)\n3.141593\n>> getValue(myClass)\n\nans =\n\n 3.141592653589793\n", "language": "MATLAB" }, { "code": "classdef GenericClass2\n\n properties\n classVariable\n end %properties\n\n methods\n\n %Class constructor\n function objectInstance = GenericClass2(varargin)\n if isempty(varargin) %No input arguments\n objectInstance.classVariable = 0;\n else\n objectInstance.classVariable = varargin{1};\n end\n end\n\n %Set function\n function setValue(GenericClassInstance,newValue)\n GenericClassInstance.classVariable = newValue;\n\n %MATLAB magic that changes the object in the scope that called\n %this set function.\n assignin('caller',inputname(1),GenericClassInstance);\n end\n\n end %methods\nend\n", "language": "MATLAB" }, { "code": "%Get function\nfunction value = getValue(GenericClassInstance)\n value = GenericClassInstance.classVariable;\nend\n", "language": "MATLAB" }, { "code": "function display(GenericClassInstance)\n disp(sprintf('%f',GenericClassInstance.classVariable));\nend\n", "language": "MATLAB" }, { "code": ">> myClass = GenericClass2(3)\n3.000000\n>> setValue(myClass,pi)\n>> getValue(myClass)\n\nans =\n\n 3.141592653589793\n", "language": "MATLAB" }, { "code": "// MiniScript is prototype based\nWeapon = { \"name\": \"Sword\", \"damage\": 3 }\nWeapon.slice = function()\n print \"Did \" + self.damage + \" damage with \" + self.name\nend function\n\nwep = new Weapon // Same as: wep = { \"__isa\": Weapon }\n\nwep.name = \"Lance\"\n\nwep.slice\n", "language": "MiniScript" }, { "code": "% define a Rectangle \"class\"\nvar int: Rectangle(var int: width, var int: height) =\n let {\n var int: this;\n constraint Type(this) = Rectangle; %define the \"type\" of the instance\n %define some \"instance methods\"\n constraint area(this) = width*height;\n constraint width(this) = width;\n constraint height(this) = height;\n } in this;\n\n%this enum should contain the list of class names\nenum Type = {Rectangle};\nfunction var Type: Type(var int:a);\n\n%declare the \"instance methods\"\nfunction var int: area(var int:this) = let {var int:result;} in result;\nfunction var int: height(var int:a) = let {var int:result;} in result;\nfunction var int: width(var int:a) = let {var int:result;} in result;\n\n%create an instance of the \"class\"\nvar int: rect = Rectangle(3,4);\nvar int: area1 = area(rect);\n\nsolve satisfy;\n\n% print the area of the rectangle\noutput [show(area1),\"\\n\"];\n", "language": "MiniZinc" }, { "code": "class MyClass\n\tdeclare name\n\n\t// constructors are methods with the same name as the class\n\tdef MyClass(name)\n\t\tthis.name = name\n\tend\n\n\tdef getName()\n\t\treturn name\n\tend\nend\n\n// instantiate a new MyClass object\ninst = new(MyClass, \"name string goes here\")\n\n// display the name value\nprintln inst.getName()\n", "language": "Nanoquery" }, { "code": "public class MyClass\n{\n public this() { } // the constructor in Nemerle is always named 'this'\n\n public MyVariable : int\n {\n get;\n set;\n }\n\n public MyMethod() : void\n {\n }\n\n}\n\ndef myInstance = MyClass(); // no 'new' keyword needed\nmyInstance.MyVariable = 42; // set MyVariable\nSystem.Console.WriteLine($\"My variable is $(myInstance.MyVariable)\") // get MyVariable\n", "language": "Nemerle" }, { "code": "class ClassExample\n\n properties private -- class scope\n foo = int\n\n properties public -- publicly visible\n bar = boolean\n\n properties indirect -- generates bean patterns\n baz = String()\n\n method main(args=String[]) static -- main method\n clsex = ClassExample() -- instantiate\n clsex.foo = 42\n clsex.baz = 'forty-two'\n clsex.bar = 0 -- boolean false\n clsex.test(clsex.foo)\n clsex.test(clsex.bar)\n clsex.test(clsex.baz)\n\n method test(s=int)\n aap = 1 -- local (stack) variable\n say s aap\n\n method test(s=String)\n noot = 2\n say s noot\n\n method test(s=boolean)\n mies = 3\n say s mies\n", "language": "NetRexx" }, { "code": "type MyClass = object\n name: int\n\nproc initMyClass(): MyClass =\n result.name = 2\n\nproc someMethod(m: var MyClass) =\n m.name = 1\n\nvar mc = initMyClass()\nmc.someMethod()\n\ntype\n Gender = enum male, female, other\n\n MyOtherClass = object\n name: string\n gender: Gender\n age: Natural\n\nproc initMyOtherClass(name; gender = female; age = 50): auto =\n MyOtherClass(name: name, gender: gender, age: age)\n\nvar person1 = initMyOtherClass(\"Jane\")\necho person1.name, \" \", person1.gender, \" \", person1.age # Jane female 50\nvar person2 = initMyOtherClass(\"John\", male, 23)\necho person2.name, \" \", person2.gender, \" \", person2.age # John male 23\n", "language": "Nim" }, { "code": "MODULE M;\n\n TYPE\n T = POINTER TO TDesc;\n TDesc = RECORD\n x: INTEGER\n END;\n\n PROCEDURE New*(): T;\n VAR t: T;\n BEGIN\n NEW(t); t.x := 0;\n RETURN t\n END New;\n\n\n PROCEDURE (t: T) Increment*;\n BEGIN\n INC(t.x)\n END Increment;\n\nEND M.\n", "language": "Oberon" }, { "code": "bundle Default {\n class MyClass {\n @var : Int;\n\n New() {\n }\n\n method : public : SomeMethod() ~ Nil {\n \t@var := 1;\n }\n\n method : public : SetVar(var : Int) ~ Nil {\n @var := var;\n }\n\n method : public : GetVar() ~ Int {\n return @var;\n }\n }\n\n class Test {\n function : Main(args : String[]) ~ Nil {\n inst := MyClass->New();\n inst->GetVar()->PrintLine();\n\n inst->SomeMethod();\n inst->GetVar()->PrintLine();\n\n inst->SetVar(15);\n inst->GetVar()->PrintLine();\n }\n }\n}\n", "language": "Objeck" }, { "code": "type\n MyClass = object\n variable: integer;\n constructor init;\n destructor done;\n procedure someMethod;\n end;\n\nconstructor MyClass.init;\n begin\n variable := 0;\n end;\n\nprocedure MyClass.someMethod;\n begin\n variable := 1;\n end;\n\nvar\n instance: MyClass; { as variable }\n pInstance: ^MyClass; { on free store }\n\nbegin\n { create instances }\n instance.init;\n new(pInstance, init); { alternatively: pInstance := new(MyClass, init); }\n\n { call method }\n instance.someMethod;\n pInstance^.someMethod;\n\n { get rid of the objects }\n instance.done;\n dispose(pInstance, done);\nend;\n", "language": "Object-Pascal" }, { "code": "// There are no class variables, so static variables are used.\nstatic int myClassVariable = 0;\n\n@interface MyClass : NSObject\n{\n int variable; // instance variable\n}\n\n- (int)variable; // Typical accessor - you should use the same name as the variable\n\n@end\n", "language": "Objective-C" }, { "code": "@implementation MyClass\n\n// Was not declared because init is defined in NSObject\n- (instancetype)init\n{\n if (self = [super init]) {\n variable = 0; // not strictly necessary as all instance variables are initialized to zero\n }\n return self;\n}\n\n- (int)variable\n{\n return variable;\n}\n\n@end\n", "language": "Objective-C" }, { "code": "// Creating an instance\nMyClass *mc = [[MyClass alloc] init];\n\n// Sending a message\n[mc variable];\n", "language": "Objective-C" }, { "code": "class my_class =\n object (self)\n val mutable variable = 0\n method some_method = variable <- 1\n end\n", "language": "OCaml" }, { "code": "Object Class new: MyClass(att)\nMyClass method: initialize(v) v := att ;\n", "language": "Oforth" }, { "code": "MyClass new(\"some value\")\n", "language": "Oforth" }, { "code": "p = .point~new\nc = .circle~new\n\np~print\nc~print\n\n::class point\n::method init\n expose x y\n use strict arg x = 0, y = 0 -- defaults to 0 for any non-specified coordinates\n\n::attribute x\n::attribute y\n\n::method print\n expose x y\n say \"A point at location (\"||x\",\"y\")\"\n\n::class circle subclass point\n::method init\n expose radius\n use strict arg x = 0, y = 0, radius = 0\n self~init:super(x, y) -- call superclass constructor\n\n::attribute radius\n\n::method print\n expose radius\n say \"A circle of radius\" radius \"centered at location (\"||self~x\",\"self~y\")\"\n", "language": "OoRexx" }, { "code": "Class MyObject\n\nstatic int count 'statics are private\n\nint a,b,c\nbstring s\n\nmethod constructor(int pa,pb,pc)\n s=\"constructed\"\n a=pa : b=pb : c=pc\n count++\nend method\n\nmethod destructor()\n del s\nend method\n\nmethod sum() as int\n return a+b+c\nend method\n\nend class\n\nnew MyObject v(2,4,6)\n\nprint \"Sum: \" v.sum\n\ndel v\n", "language": "OxygenBasic" }, { "code": "declare\n class Something\n feat\n name %% immutable, public attribute (called a \"feature\")\n attr\n count %% mutable, private attribute\n\n %% public method which is used as an initializer\n meth init(N)\n self.name = N\n count := 0\n end\n\n %% public method\n meth increase\n count := @count + 1\n end\n end\nin\n %% create an instance\n Object = {New Something init(\"object\")}\n\n %% call a method\n {Object increase}\n", "language": "Oz" }, { "code": "{\n # a class is a package (i.e. a namespace) with methods in it\n package MyClass;\n\n # a constructor is a function that returns a blessed reference\n sub new {\n my $class = shift;\n bless {variable => 0}, $class;\n # the instance object is a hashref in disguise.\n # (it can be a ref to anything.)\n }\n\n # an instance method is a function that takes an object as first argument.\n # the -> invocation syntax takes care of that nicely, see Usage paragraph below.\n sub some_method {\n my $self = shift;\n $self->{variable} = 1;\n }\n}\n", "language": "Perl" }, { "code": "{\n package MyClass;\n use Moose;\n\n has 'variable' => (is => 'rw', default => 0);\n # constructor and accessor methods are added automatically\n\n sub some_method {\n my $self = shift;\n $self->variable(1);\n }\n}\n", "language": "Perl" }, { "code": "use MooseX::Declare;\nclass MyClass {\n has 'variable' => (is => 'rw', default => 0);\n method some_method {\n $self->variable(1);\n }\n}\n", "language": "Perl" }, { "code": "my $instance = MyClass->new; # invoke constructor method\n\n$instance->some_method; # invoke method on object instance\n # instance deallocates when the last reference falls out of scope\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span> <span style=\"color: #000080;font-style:italic;\">-- (else cffi namespaces error, classes not supported by pwa/p2js anyway)</span>\n <span style=\"color: #7060A8;\">requires</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"1.0.2\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (free up the temp used in the v.show() call)</span>\n\n <span style=\"color: #008080;\">class</span> <span style=\"color: #000000;\">five</span> <span style=\"color: #008080;\">nullable</span>\n <span style=\"color: #008080;\">private</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">3</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">get_n</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">n</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">set_n</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">this</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">n</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">show</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"show: n is %d\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">five</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"constructor five(%d) called\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">this</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">n</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">this</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #0000FF;\">~</span><span style=\"color: #000000;\">five</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"destructor ~five(%d) called\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">class</span>\n <span style=\"color: #000000;\">five</span> <span style=\"color: #000000;\">v</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">new</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">assert</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">6</span>\n <span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">show</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">NULL</span>\n<!--\n", "language": "Phix" }, { "code": "module classes;\n\nextern printf;\n\nclass @MyClass {\n\tfield @Integer myField { get:get_myField, set:set_myField };\n\t\n\tnew [\n\t\tthis.set_myField(2);\n\t]\n\t\n\t@Void method [\n\t\tthis.set_myField(this::get_myField + 1);\n\t]\n};\n\n@Integer main [\n\tvar obj = new @MyClass;\n\tprintf(\"obj.myField: %i\\n\", obj::get_myField);\n\tobj::method;\n\tprintf(\"obj.myField: %i\\n\", obj::get_myField);\n\treturn 0;\n]\n", "language": "PHL" }, { "code": "class MyClass {\n public static $classVar;\n public $instanceVar; // can also initialize it here\n function __construct() {\n $this->instanceVar = 0;\n }\n function someMethod() {\n $this->instanceVar = 1;\n self::$classVar = 3;\n }\n}\n$myObj = new MyClass();\n", "language": "PHP" }, { "code": "(class +Rectangle)\n# dx dy\n\n(dm area> () # Define a a method that calculates the rectangle's area\n (* (: dx) (: dy)) )\n\n(println # Create a rectangle, and print its area\n (area> (new '(+Rectangle) 'dx 3 'dy 4)) )\n", "language": "PicoLisp" }, { "code": "uses objectclass;\ndefine :class MyClass;\n slot value = 1;\nenddefine;\n", "language": "Pop11" }, { "code": ";;; Construct instance with default slot values\nlvars instance1 = newMyClass();\n;;; Construct instance with explicitely given slot values\nlvars instance2 = consMyClass(15);\n;;; Print slot value using dot notation\ninstance1.value =>\ninstance2.value =>\n;;; Print slot value using funtional notation\nvalue(instance1) =>\n;;; Change slot value\n12 -> value(instance1);\n;;; Print it\nvalue(instance1) =>\n", "language": "Pop11" }, { "code": "define :method reset(x : MyClass);\n 0 -> value(x);\nenddefine;\nreset(instance1);\n;;; Print it\ninstance1 =>\n", "language": "Pop11" }, { "code": "programa {\n inclua biblioteca Objetos --> obj\n\n // \"constructor\" returns address of object\n funcao inteiro my_class_new(inteiro value) {\n inteiro this = obj.criar_objeto()\n obj.atribuir_propriedade(this, \"variable\", value) // add property to object\n retorne this\n }\n\n // \"method\" takes the address returned by criar_objeto\n funcao my_class_some_method(inteiro this) {\n my_class_set_variable(this, 1)\n }\n\n // \"setter\"\n funcao my_class_set_variable(inteiro this, inteiro value) {\n obj.atribuir_propriedade(this, \"variable\", value)\n }\n\n // \"getter\"\n funcao inteiro my_class_get_variable(inteiro this) {\n retorne obj.obter_propriedade_tipo_inteiro(this, \"variable\")\n }\n\n funcao inicio() {\n inteiro this = my_class_new(0)\n\n escreva(\"variable = \", my_class_get_variable(this), \"\\n\")\n\n my_class_some_method(this)\n\n escreva(\"variable = \", my_class_get_variable(this), \"\\n\")\n\n my_class_set_variable(this, 99)\n\n escreva(\"variable = \", my_class_get_variable(this), \"\\n\")\n\n obj.liberar_objeto(this)\n }\n}\n", "language": "Portugol" }, { "code": "Add-Type -Language CSharp -TypeDefinition @'\npublic class MyClass\n{\n public MyClass()\n {\n }\n public void SomeMethod()\n {\n }\n private int _variable;\n public int Variable\n {\n get { return _variable; }\n set { _variable = value; }\n }\n public static void Main()\n {\n // instantiate it\n MyClass instance = new MyClass();\n // invoke the method\n instance.SomeMethod();\n // set the variable\n instance.Variable = 99;\n // get the variable\n System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n }\n}\n'@\n", "language": "PowerShell" }, { "code": "class MyClass\n{\n[type]$MyProperty1\n[type]$MyProperty2 = \"Default value\"\n\n # Constructor\n MyClass( [type]$MyParameter1, [type]$MyParameter2 )\n {\n # Code\n }\n\n # Method ( [returntype] defaults to [void] )\n [returntype] MyMethod( [type]$MyParameter3, [type]$MyParameter4 )\n {\n # Code\n }\n}\n", "language": "PowerShell" }, { "code": "class Banana\n{\n# Properties\n[string]$Color\n[boolean]$Peeled\n\n# Default constructor\nBanana()\n {\n $This.Color = \"Green\"\n }\n\n# Constructor\nBanana( [boolean]$Peeled )\n {\n $This.Color = \"Green\"\n $This.Peeled = $Peeled\n }\n\n# Method\nRipen()\n {\n If ( $This.Color -eq \"Green\" ) { $This.Color = \"Yellow\" }\n Else { $This.Color = \"Brown\" }\n }\n\n# Method\n[boolean] IsReadyToEat()\n {\n If ( $This.Color -eq \"Yellow\" -and $This.Peeled ) { return $True }\n Else { return $False }\n }\n}\n", "language": "PowerShell" }, { "code": "$MyBanana = [banana]::New()\n$YourBanana = [banana]::New( $True )\n$YourBanana.Ripen()\nIf ( -not $MyBanana.IsReadyToEat() -and $YourBanana.IsReadyToEat() )\n { $MySecondBanana = $YourBanana }\n", "language": "PowerShell" }, { "code": "class ProgrammingLanguage\n{\n // instance variable:\n private String name;\n // constructor (let's use it to give the instance variable a value):\n public ProgrammingLanguage(String name)\n {\n this.name = name;\n // note use of \"this\" to distinguish the instance variable from the argument\n }\n // a method:\n public void sayHello()\n {\n println(\"Hello from the programming language \" + name);\n // the method has no argument or local variable called \"name\", so we can omit the \"this\"\n }\n}\n", "language": "Processing" }, { "code": "// instantiate the class:\nProgrammingLanguage processing = new ProgrammingLanguage(\"Processing\");\n\n// call the method:\nprocessing.sayHello();\n", "language": "Processing" }, { "code": "Interface OO_Interface ; Interface for any value of this type\n Get.i()\n Set(Value.i)\n ToString.s()\n Destroy()\nEndInterface\n\nStructure OO_Structure ; The *VTable structure\n Get.i\n Set.i\n ToString.i\n Destroy.i\nEndStructure\n\nStructure OO_Var\n *VirtualTable.OO_Structure\n Value.i\nEndStructure\n\nProcedure OO_Get(*Self.OO_Var)\n ProcedureReturn *Self\\Value\nEndProcedure\n\nProcedure OO_Set(*Self.OO_Var, n)\n *Self\\Value = n\nEndProcedure\n\nProcedure.s OO_ToString(*Self.OO_Var)\n ProcedureReturn Str(*Self\\Value)\nEndProcedure\n\nProcedure Create_OO()\n *p.OO_Var=AllocateMemory(SizeOf(OO_Var))\n If *p\n *p\\VirtualTable=?VTable\n EndIf\n ProcedureReturn *p\nEndProcedure\n\nProcedure OO_Destroy(*Self.OO_Var)\n FreeMemory(*Self)\nEndProcedure\n\nDataSection\n VTable:\n Data.i @OO_Get()\n Data.i @OO_Set()\n Data.i @OO_ToString()\n Data.i @OO_Destroy()\nEndDataSection\n\n;- Test the code\n*Foo.OO_Interface = Create_OO()\n*Foo\\Set(341)\nMessageRequester(\"Info\", \"Foo = \" + *Foo\\ToString() )\n*Foo\\Destroy()\n", "language": "PureBasic" }, { "code": "Class Foo\n Private Value.i\n\n BeginPublic\n Method Init()\n ; Any needed code goes here\n EndMethod\n\n Method Release()\n ; Any code befoe freeing the object goes here\n EndMethod\n\n Method Get()\n MethodReturn This\\Value\n EndMethod\n\n Method Set(n)\n This\\Value = n\n EndMethod\n\n Method.s ToString()\n MethodReturn Str(This\\Value)\n EndMethod\n EndPublic\nEndClass\n\n;- Test the code\n*Demo.foo = NewObject.foo()\n*Demo\\Set(4)\nMessageRequester(\"Info\", \"Val= \" + *Demo\\ToString())\n", "language": "PureBasic" }, { "code": "class MyClass:\n name2 = 2 # Class attribute\n\n def __init__(self):\n \"\"\"\n Constructor (Technically an initializer rather than a true \"constructor\")\n \"\"\"\n self.name1 = 0 # Instance attribute\n\n def someMethod(self):\n \"\"\"\n Method\n \"\"\"\n self.name1 = 1\n MyClass.name2 = 3\n\n\nmyclass = MyClass() # class name, invoked as a function is the constructor syntax.\n\nclass MyOtherClass:\n count = 0 # Population of \"MyOtherClass\" objects\n def __init__(self, name, gender=\"Male\", age=None):\n \"\"\"\n One initializer required, others are optional (with different defaults)\n \"\"\"\n MyOtherClass.count += 1\n self.name = name\n self.gender = gender\n if age is not None:\n self.age = age\n def __del__(self):\n MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender # \"John Male\"\nprint person1.age # Raises AttributeError exception!\nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age # \"Jane Female 23\"\n", "language": "Python" }, { "code": "class MyClass(object):\n ...\n", "language": "Python" }, { "code": " TYPE MyClass\n Variable AS INTEGER\n END TYPE\n\n DECLARE SUB MyClassDelete (pthis AS MyClass)\n DECLARE SUB MyClassSomeMethod (pthis AS MyClass)\n DECLARE SUB MyClassInit (pthis AS MyClass)\n\n DIM obj AS MyClass\n MyClassInit obj\n MyClassSomeMethod obj\n\n SUB MyClassInit (pthis AS MyClass)\n pthis.Variable = 0\n END SUB\n\n SUB MyClassSomeMethod (pthis AS MyClass)\n pthis.Variable = 1\n END SUB\n", "language": "QuickBASIC" }, { "code": "#You define a class simply by setting the class attribute of an object\ncircS3 <- list(radius=5.5, centre=c(3, 4.2))\nclass(circS3) <- \"circle\"\n\n#plot is a generic function, so we can define a class specific method by naming it plot.classname\nplot.circle <- function(x, ...)\n{\n t <- seq(0, 2*pi, length.out=200)\n plot(x$centre[1] + x$radius*cos(t),\n x$centre[2] + x$radius*sin(t),\n type=\"l\", ...)\n}\nplot(circS3)\n", "language": "R" }, { "code": "setClass(\"circle\",\n representation(\n radius=\"numeric\",\n centre=\"numeric\"),\n prototype(\n radius=1,\n centre=c(0,0)))\n#Instantiate class with some arguments\ncircS4 <- new(\"circle\", radius=5.5)\n#Set other data slots (properties)\ncircS4@centre <- c(3,4.2)\n\n#Define a method\nsetMethod(\"plot\", #signature(\"circle\"),\n signature(x=\"circle\", y=\"missing\"),\n function(x, ...)\n {\n t <- seq(0, 2*pi, length.out=200)\n #Note the use of @ instead of $\n plot(x@centre[1] + x@radius*cos(t),\n x@centre[2] + x@radius*sin(t),\n type=\"l\", ...)\n })\nplot(circS4)\n", "language": "R" }, { "code": "#lang racket\n\n(define fish%\n (class object%\n (super-new)\n\n ;; an instance variable & constructor argument\n (init-field size)\n\n ;; a new method\n (define/public (eat)\n (displayln \"gulp!\"))))\n\n;; constructing an instance\n(new fish% [size 50])\n", "language": "Racket" }, { "code": "class Camel { has Int $.humps = 1; }\n\nmy Camel $a .= new;\nsay $a.humps; # Automatically generated accessor method.\n\nmy Camel $b .= new: humps => 2;\nsay $b.humps;\n", "language": "Raku" }, { "code": "class Butterfly {\n has Int $!age; # With the ! twigil, no public accessor method is generated\n has Str $.name;\n has Str $.color;\n has Bool $.wings;\n\n submethod BUILD(:$!name = 'Camelia', :$!age = 2, :$!color = 'pink') {\n # BUILD is called by bless. Its primary use is to to control\n # object initialization.\n $!wings = $!age > 1;\n }\n\n method flap() {\n say ($.wings\n ?? 'Watch out for that hurricane!'\n !! 'No wings to flap.');\n }\n}\n\nmy Butterfly $a .= new: age => 5;\nsay \"Name: {$a.name}, Color: {$a.color}\";\n$a.flap;\n\nmy Butterfly $b .= new(name => 'Osgood', age => 4);\nsay \"Name: {$b.name}, Color: {$b.color}\";\n$b.flap;\n", "language": "Raku" }, { "code": "TYPE MyClass EXTENDS QObject\n Variable AS INTEGER\n\n CONSTRUCTOR\n Variable = 0\n END CONSTRUCTOR\n\n SUB someMethod\n MyClass.Variable = 1\n END SUB\nEND TYPE\n\n' create an instance\nDIM instance AS MyClass\n\n' invoke the method\ninstance.someMethod\n", "language": "RapidQ" }, { "code": "class Alpha\n 'I am Alpha.' as greeting\n define say_hello\n greeting print\n\nclass Beta extend Alpha\n 'I am Beta!' as greeting\n", "language": "Raven" }, { "code": "Alpha as alpha\nBeta as beta\n", "language": "Raven" }, { "code": "alpha.say_hello\nbeta.say_hello\n", "language": "Raven" }, { "code": "I am Alpha.\nI am Beta!\n", "language": "Raven" }, { "code": "Class NumberContainer\n Private TheNumber As Integer\n Sub Constructor(InitialNumber As Integer)\n TheNumber = InitialNumber\n End Sub\n\n Function Number() As Integer\n Return TheNumber\n End Function\n\n Sub Number(Assigns NewNumber As Integer)\n TheNumber = NewNumber\n End Sub\nEnd Class\n", "language": "REALbasic" }, { "code": "Dim num As New NumberContainer(1) ' call the constructor\nnum.Number = num.Number + 5 ' call both Number methods\n", "language": "REALbasic" }, { "code": "rebol [\n Title: \"Classes\"\n URL: http://rosettacode.org/wiki/Classes\n]\n\n; Objects are derived from the base 'object!' type. REBOL uses a\n; prototyping object system, so any object can be treated as a class,\n; from which to derive others.\n\ncowboy: make object! [\n\tname: \"Tex\" ; Instance variable.\n\thi: does [ ; Method.\n\t\tprint [self/name \": Howdy!\"]]\n]\n\n; I create two instances of the 'cowboy' class.\n\ntex: make cowboy []\nroy: make cowboy [\n\tname: \"Roy\" ; Override 'name' property.\n]\n\nprint \"Say 'hello', boys:\" tex/hi roy/hi\nprint \"\"\n\n; Now I'll subclass 'cowboy'. Subclassing looks a lot like instantiation:\n\nlegend: make cowboy [\n\tdeed: \"...\"\n\tboast: does [\n\t\tprint [self/name \": I once\" self/deed \"!\"]]\n]\n\n; Instancing the legend:\n\npecos: make legend [name: \"Pecos Bill\" deed: \"lassoed a twister\"]\n\nprint \"Howdy, Pecos!\" pecos/hi\nprint \"Tell us about yourself?\" pecos/boast\n", "language": "REBOL" }, { "code": "struct Vector {\n var x: Decimal;\n var y: Decimal;\n\n func magnitude(this): Decimal {\n return Math.sqrt(this.x * this.x + this.y * this.y);\n }\n}\n", "language": "Rhovas" }, { "code": "class UnitVector {\n val x: Decimal;\n val y: Decimal;\n\n init(direction: Vector) {\n require direction.x != 0.0 || direction.y != 0.0;\n val magnitude = direction.magnitude();\n this { x: direction.x / magnitude, y: direction.y / magnitude };\n }\n}\n", "language": "Rhovas" }, { "code": "New point { x=10 y=20 z=30 print() }\nClass Point x y z func print see x + nl + y + nl + z + nl\n", "language": "Ring" }, { "code": "New point # create new object using the point class\n{ # access the new object attributes and methods\n x = 10 # set the x attribute to 10\n y = 20 # set the y attribute to 20\n z = 30 # set the z attribute to 30\n print() # call the print method\n} # end of object access\n\n\nClass Point # define the Point class\n x y z # the class contains three attributes x, y & z\n func print # define the print method\n see x + nl + # print the x attribute\n y + nl + # print the y attribute\n z + nl # print the z attribute\n", "language": "Ring" }, { "code": "class MyClass\n\n def initialize\n @instance_var = 0\n end\n\n def add_1\n @instance_var += 1\n end\n\nend\n\nmy_class = MyClass.new #allocates an object and calls it's initialize method, then returns it.\n", "language": "Ruby" }, { "code": "struct MyClass {\n variable: i32, // member variable = instance variable\n}\n\nimpl MyClass {\n // member function = method, with its implementation\n fn some_method(&mut self) {\n self.variable = 1;\n }\n\n // constructor, with its implementation\n fn new() -> MyClass {\n // Here could be more code.\n MyClass { variable: 0 }\n }\n}\n\nfn main () {\n // Create an instance in the stack.\n let mut instance = MyClass::new();\n\n // Create an instance in the heap.\n let mut p_instance = Box::new(MyClass::new());\n\n // Invoke method on both istances,\n instance.some_method();\n p_instance.some_method();\n\n // Both instances are automatically deleted when their scope ends.\n}\n", "language": "Rust" }, { "code": "class CLASSTEST is\n readonly attr x:INT; -- give a public getter, not a setter\n private attr y:INT; -- no getter, no setter\n attr z:INT; -- getter and setter\n\n -- constructor\n create(x, y, z:INT):CLASSTEST is\n res :CLASSTEST := new; -- or res ::= new\n res.x := x;\n res.y := y;\n res.z := z;\n return res;\n end;\n\n -- a getter for the private y summed to s\n getPrivateY(s:INT):INT is\n -- y is not shadowed so we can write y instead of\n -- self.y\n return y + s;\n end;\nend;\n", "language": "Sather" }, { "code": "class MAIN is\n main is\n test ::= #CLASSTEST(1, 2, 3);\n -- the previous line is syntactic sugar for\n -- test :CLASSTEST := CLASSTEST::create(1, 2, 3);\n #OUT + test.z + \"\\n\"; -- we can access z\n test.z := 25; -- we can set z\n #OUT + test.x + \"\\n\"; -- we can get x\n -- test.x := 5; -- we cannot set x\n #OUT + test.getPrivateY(0) + \"\\n\";\n end;\nend;\n", "language": "Sather" }, { "code": "/** This class implicitly includes a constructor which accepts an Int and\n * creates \"val variable1: Int\" with that value.\n */\nclass MyClass(val myMethod: Int) { // Acts like a getter, getter automatically generated.\n var variable2 = \"asdf\" // Another instance variable; a public var this time\n def this() = this(0) // An auxilliary constructor that instantiates with a default value\n}\n\nobject HelloObject {\n val s = \"Hello\" // Not private, so getter auto-generated\n}\n\n/** Demonstrate use of our example class.\n */\nobject Call_an_object_method extends App {\n val s = \"Hello\"\n val m = new MyClass()\n val n = new MyClass(3)\n\n println(HelloObject.s) // prints \"Hello\" by object getterHelloObject\n\n println(m.myMethod) // prints 0\n println(n.myMethod) // prints 3\n}\n", "language": "Scala" }, { "code": " (define (withdraw amount)\n (if (>= balance amount)\n (begin (set! balance (- balance amount))\n balance)\n \"Insufficient funds\"))\n (define (deposit amount)\n (set! balance (+ balance amount))\n balance)\n (define (dispatch m)\n (cond ((eq? m 'withdraw) withdraw)\n ((eq? m 'deposit) deposit)\n (else (error \"Unknown request -- MAKE-ACCOUNT\"\n m))))\n dispatch)\n", "language": "Scheme" }, { "code": "class MyClass(instance_var) {\n method add(num) {\n instance_var += num;\n }\n}\n\nvar obj = MyClass(3); # `instance_var` will be set to 3\nobj.add(5); # calls the add() method\nsay obj.instance_var; # prints the value of `instance_var`: 8\n", "language": "Sidef" }, { "code": "BEGIN\n CLASS MyClass(instanceVariable);\n INTEGER instanceVariable;\n BEGIN\n PROCEDURE doMyMethod(n);\n INTEGER n;\n BEGIN\n Outint(instanceVariable, 5);\n Outtext(\" + \");\n Outint(n, 5);\n Outtext(\" = \");\n Outint(instanceVariable + n, 5);\n Outimage\n END;\n END;\n REF(MyClass) myObject;\n myObject :- NEW MyClass(5);\n myObject.doMyMethod(2)\nEND\n", "language": "Simula" }, { "code": "prototypes define: #MyPrototype &parents: {Cloneable} &slots: #(instanceVar).\nMyPrototype traits addSlot: #classVar.\n\nx@(MyPrototype traits) new\n[\n x clone `>> [instanceVar: 0. ]\n].\n\nx@(MyPrototype traits) someMethod\n[\n x instanceVar = 1 /\\ (x classVar = 3)\n].\n", "language": "Slate" }, { "code": "Object subclass: #MyClass\n instanceVariableNames: 'instanceVar'\n classVariableNames: 'classVar'\n poolDictionaries: ''\n category: 'Testing' !\n\n!MyClass class methodsFor: 'instance creation'!\nnew\n ^self basicNew instanceVar := 0 ! !\n\n!MyClass methodsFor: 'testing'!\nsomeMethod\n ^self instanceVar = 1; classVar = 3 ! !\n\nMyClass new someMethod!\n", "language": "Smalltalk" }, { "code": "SpecialObject {\n\n\tclassvar a = 42, <b = 0, <>c; // Class variables. 42 and 0 are default values.\n\tvar <>x, <>y; // Instance variables.\n\t// Note: variables are private by default. In the above, \"<\" creates a getter, \">\" creates a setter\n\n\t*new { |value|\n\t\t^super.new.init(value) // constructor is a class method. typically calls some instance method to set up, here \"init\"\n\t}\n\n\tinit { |value|\n\t\tx = value;\n\t\ty = sqrt(squared(a) + squared(b))\n\t}\n\n\t// a class method\n\t*randomizeAll {\n\t\ta = 42.rand;\n\t\tb = 42.rand;\n\t\tc = 42.rannd;\n\t}\n\n\t// an instance method\n\tcoordinates {\n\t\t^Point(x, y) // The \"^\" means to return the result. If not specified, then the object itself will be returned (\"^this\")\n\t}\n\n\n}\n", "language": "SuperCollider" }, { "code": "SpecialObject.randomizeAll;\na = SpecialObject(8);\na.coordinates;\n", "language": "SuperCollider" }, { "code": "class MyClass{\n\n // stored property\n var variable : Int\n\n /**\n * The constructor\n */\n init() {\n self.variable = 42\n }\n\n /**\n * A method\n */\n func someMethod() {\n self.variable = 1\n }\n}\n", "language": "Swift" }, { "code": "MyClass()\n", "language": "Swift" }, { "code": "package require TclOO\noo::class create summation {\n variable v\n constructor {} {\n set v 0\n }\n method add x {\n incr v $x\n }\n method value {} {\n return $v\n }\n destructor {\n puts \"Ended with value $v\"\n }\n}\nset sum [summation new]\nputs \"Start with [$sum value]\"\nfor {set i 1} {$i <= 10} {incr i} {\n puts \"Add $i to get [$sum add $i]\"\n}\n$sum destroy\n", "language": "Tcl" }, { "code": "class Car\n{\n //Constructor function.\n function this(brand, weight, price = 0) {\n this.brand = brand;\n this.weight = weight || 1000; // Resort to default value (with 'or' notation).\n this._price = price;\n }\n property price(v) // computable property, special kind of member function\n {\n get { return this._price; } // getter section\n set { this._price = v; } // setter section\n }\n function toString() { // member function, method of a Car.\n return String.printf(\"<%s>\",this.brand);\n }\n}\n\nclass Truck : Car\n{\n function this(brand, size) {\n super(brand, 2000); // Call of constructor of super class (Car here)\n this.size = size; // Custom property for just this object.\n }\n}\n\nvar cars = [ // Some example car objects.\n new Car(\"Mazda\"),\n new Truck(\"Volvo\", 2, 30000)\n];\nfor (var (i,car) in cars) // TIScript allows enumerate indexes and values\n{\n stdout.printf(\"#%d %s $%d %v %v, %v %v\", i, car.brand, car.price, car.weight, car.size,\n car instanceof Car, car instanceof Truck);\n}\n", "language": "TIScript" }, { "code": "#lang transd\n\nclass Point : {\n x: Double(),\n y: Double(),\n @init: (λ v Vector<Double>() (= x (get v 0)) (= y (get v 1))),\n print: (λ (textout \"Point(\" x \"; \" y \")\\n\" ))\n}\n\nMainModule: {\n v_: [[1.0, 2.0], [3.0, 4.0]],\n\n _start: (λ\n\t// creating an instance of class\n \t(with pt Point([5.0, 6.0])\n\t // calling a class' method\n\t (print pt)\n\t)\n\n\t// creating several instances using data deserialization\n (with v Vector<Point>(v_)\n (for p in v do (print p))\n ) )\n}\n", "language": "Transd" }, { "code": "(defstruct shape ()\n cached-area\n\n (:init (self)\n (put-line `@self is born!`))\n\n (:fini (self)\n (put-line `@self says goodbye!`))\n\n (:method area (self)\n (or self.cached-area\n (set self.cached-area self.(calc-area)))))\n\n(defstruct circle shape\n (radius 1.0)\n\n (:method calc-area (self)\n (* %pi% self.radius self.radius)))\n\n(defstruct square shape\n (length 1.0)\n\n (:method calc-area (self)\n (* self.length self.length)))\n", "language": "TXR" }, { "code": "typeset -T Summation_t=(\n integer sum\n\n # the constructor\n function create {\n _.sum=0\n }\n\n # a method\n function add {\n (( _.sum += $1 ))\n }\n)\n\nSummation_t s\nfor i in 1 2 3 4 5; do\n s.add $i\ndone\nprint ${s.sum}\n", "language": "UNIX-Shell" }, { "code": "public class MyClass : Object {\n // Instance variable\n public int variable;\n\n // Method\n public void some_method() {\n variable = 24;\n }\n\n // Constructor\n public MyClass() {\n variable = 42;\n }\n}\nvoid main() {\n // Class instance\n MyClass instance = new MyClass();\n print(\"%d\\n\", instance.variable);\n instance.some_method();\n print(\"%d\\n\", instance.variable);\n instance.variable = 84;\n print(\"%d\\n\", instance.variable);\n}\n", "language": "Vala" }, { "code": "Private Const m_default = 10\nPrivate m_bar As Integer\n\nPrivate Sub Class_Initialize()\n 'constructor, can be used to set default values\n m_bar = m_default\nEnd Sub\n\nPrivate Sub Class_Terminate()\n 'destructor, can be used to do some cleaning up\n 'here we just print a message\n Debug.Print \"---object destroyed---\"\nEnd Sub\nProperty Let Bar(value As Integer)\n m_bar = value\nEnd Property\n\nProperty Get Bar() As Integer\n Bar = m_bar\nEnd Property\n\nFunction DoubleBar()\n m_bar = m_bar * 2\nEnd Function\n\nFunction MultiplyBar(x As Integer)\n 'another method\n MultiplyBar = m_bar * x\n 'Note: instead of using the instance variable m_bar we could refer to the Bar property of this object using the special word \"Me\":\n ' MultiplyBar = Me.Bar * x\nEnd Function\n", "language": "VBA" }, { "code": "Public Sub foodemo()\n'declare and create separately\nDim f As Foo\nDim f0 As Foo\n\nSet f = New Foo\n\n'set property\nf.Bar = 25\n'call method\nf.DoubleBar\n'alternative\nCall f.DoubleBar\nDebug.Print \"f.Bar is \"; f.Bar\nDebug.Print \"Five times f.Bar is \"; f.MultiplyBar(5)\n\n'declare and create at the same time\nDim f2 As New Foo\nDebug.Print \"f2.Bar is \"; f2.Bar 'prints default value\n\n'destroy an object\nSet f = Nothing\n\n'create an object or not, depending on a random number:\nIf Rnd() < 0.5 Then\n Set f0 = New Foo\nEnd If\n'check if object actually exists\nIf f0 Is Nothing Then\n Debug.Print \"object f0 does not exist\"\nElse\n Debug.Print \"object f0 was created\"\nEnd If\n'at the end of execution all remaining objects created in this sub will be released.\n'this will trigger one or two \"object destroyed\" messages\n'depending on whether f0 was created...\nEnd Sub\n", "language": "VBA" }, { "code": "Class Foo\n Private m_Bar As Integer\n\n Public Sub New()\n\n End Sub\n\n Public Sub New(ByVal bar As Integer)\n m_Bar = bar\n End Sub\n\n Public Property Bar() As Integer\n Get\n Return m_Bar\n End Get\n Set(ByVal value As Integer)\n m_Bar = value\n End Set\n End Property\n\n Public Sub DoubleBar()\n m_Bar *= 2\n End Sub\n\n Public Function MultiplyBar(ByVal x As Integer) As Integer\n Return x * Bar\n End Function\n\nEnd Class\n", "language": "Visual-Basic-.NET" }, { "code": "'Declare and create separately\nDim foo1 As Foo\nfoo1 = New Foo\n\n'Declare and create at the same time\nDim foo2 As New Foo\n\n'... while passing constructor parameters\nDim foo3 As New Foo(5)\n\n'... and them immediately set properties\nDim foo4 As New Foo With {.Bar = 10}\n\n'Calling a method that returns a value\nConsole.WriteLine(foo4.MultiplyBar(20))\n\n'Calling a method that performs an action\nfoo4.DoubleBar()\n\n'Reading/writing properties\nConsole.WriteLine(foo4.Bar)\nfoo4.Bar = 1000\n", "language": "Visual-Basic-.NET" }, { "code": "LOCAL o1 As MyClass, o2 As MyClass\n*!* Instantiate o1\no1 = NEWOBJECT(\"MyClass\")\no1.ShowInstance()\n*!* Instantiate o2\no2 = CREATEOBJECT(\"MyClass\", 2)\no2.ShowInstance()\n\n\nDEFINE CLASS MyClass As Session\n*!* Custom property (protected)\nPROTECTED nInstance\nnInstance = 0\n\n*!* Constructor\nPROCEDURE Init(tnInstance As Integer)\nIF VARTYPE(tnInstance) = \"N\"\n THIS.nInstance = tnInstance\nELSE\n THIS.nInstance = THIS.nInstance + 1\nENDIF\nENDPROC\n\n*!* Custom Method\nPROCEDURE ShowInstance\n? \"Instance\", THIS.nInstance\nENDPROC\nENDDEFINE\n", "language": "Visual-FoxPro" }, { "code": "class Bear {\n // Constructs a Bear instance passing it a name\n // which is stored in the field _name\n // automatically created by Wren.\n construct new(name) { _name = name }\n\n // Property to get the name\n name { _name }\n\n // Method to make a noise.\n makeNoise() { System.print(\"Growl!\") }\n}\n\n// Create a new Bear instance and assign a reference to it\n// to the variable b.\nvar b = Bear.new(\"Bruno\")\n\n// Print the bear's name.\nSystem.print(\"The bear is called %(b.name).\")\n// Make a noise.\nb.makeNoise()\n", "language": "Wren" }, { "code": "option casemap:none\n\nifndef __SOMECLASS_CLASS__\n__SOMECLASS_CLASS__ equ 1\n\n ;; Once again, HeapAlloc/Free is REQUIRED by the class extention for windows.\n ;; Malloc/Free are used by Linux and OSX. So the function prototypes have to\n ;; be defined somewhere. If you have include files where they're defined, just\n ;; include them in the usual way and remove the option dllimports.\n if @Platform eq 1 ;; Windows 64\n ;; include windows.inc\n ;; includelib kernel32.lib\n option dllimport:<kernel32>\n HeapAlloc proto :qword, :dword, :qword\n HeapFree proto :qword, :dword, :qword\n ExitProcess proto :dword\n GetProcessHeap proto\n option dllimport:none\n exit equ ExitProcess\n elseif @Platform eq 3 ;; Linux 64\n ;;include libc.inc\n malloc proto SYSTEMV :qword\n free proto SYSTEMV :qword\n exit proto SYSTEMV :dword\n endif\n\n printf proto :qword, :VARARG\n\n CLASS someClass\n CMETHOD someMethod\n ENDMETHODS\n var dd ?\n ENDCLASS\n\n ;; The OS' ABI has an effect on this class extention. That is, the class self pointetr\n ;; is usually refferenced in the first arg register. So for Windows it would be rcx and\n ;; Linux would be rdi. So to write code that will assemble on both we use a register\n ;; that ISN'T used to pass arguments in either ABI(Not sure about OSX's ABI however)\n METHOD someClass, Init, <VOIDARG>, <>, a:dword\n mov rbx, thisPtr\n assume rbx:ptr someClass\n mov [rbx].var, a\n mov rax, rbx\n assume rbx:nothing\n ret\n ENDMETHOD\n\n METHOD someClass, someMethod, <dword>, <>\n mov rbx, thisPtr\n assume rbx:ptr someClass\n mov eax, [rbx].var\n assume rbx:nothing\n ret\n ENDMETHOD\n\n METHOD someClass, Destroy, <VOIDARG>, <>\n ret\n ENDMETHOD\nendif ;; __CLASS_CLASS_\n\n.code\nmain proc\n local meh:ptr someClass\n ;; Create a new instance of someClass with an arg of 7\n mov meh, _NEW(someClass, 7)\n meh->someMethod() ;;Get meh->var value and return it in RAX\n invoke printf, CSTR(\"class->someMethod = %i\",10), rax\n _DELETE(meh) ;; DIIIIIIIE!\n invoke exit, 0 ;; Crashy crashy without it.\n ret\nmain endp\n\nend\n", "language": "X86-64-Assembly" }, { "code": "class Person {\n\tconstruct=func(self,Name,Age,Gender){\n\t\tself:Name=Name;\n\t\tself:Age=Age;\n\t\tself:Gender=Gender;\n\t}{Name=\"John\",Age=20,Gender=\"Male\"};\n\tToString=func(self){\n\t\tsend self.Name+\" (\"+self.Gender+\"): Age \"+self.Age;\n\t}\n}\n\nset John = new Person with [];\nlog(John::ToString());\nset Jane = new Person with [\"Jane\",20,\"Female\"]\nlog(Jane::ToString());\n", "language": "XBS" }, { "code": "(DEFINE-CLASS PROGRAMMING-LANGUAGE\n (INSTANCE-VARIABLES NAME YEAR))\n\n(DEFINE-METHOD (PROGRAMMING-LANGUAGE 'INITIALIZE X)\n (SETQ NAME X)\n SELF)\n\n(DEFINE-METHOD (PROGRAMMING-LANGUAGE 'WAS-CREATED-IN X)\n (SETQ YEAR X))\n\n(DEFINE-METHOD (PROGRAMMING-LANGUAGE 'DESCRIBE)\n `(THE PROGRAMMING LANGUAGE ,NAME WAS CREATED IN ,YEAR))\n\n(DEFINE LISP (PROGRAMMING-LANGUAGE 'NEW 'LISP))\n\n(LISP 'WAS-CREATED-IN 1958)\n\n(DISPLAY (LISP 'DESCRIBE))\n(NEWLINE)\n", "language": "XLISP" }, { "code": "class C{ // define class named \"C\", no parents or attributes\n println(\"starting construction\"); // all code outside functions is wrapped into the constructor\n var v; // instance data for this class\n fcn init(x) // initializer for this class, calls constructor\n { v = x }\n println(\"ending construction of \",self);\n}\nc1:=C(5); // create a new instance of C\nc2:=c1(\"hoho\"); // create another instance of C\nprintln(C.v,\" \",c1.v,\" \",c2.v);\n", "language": "Zkl" }, { "code": "C.__constructor(); // run base class constructor for giggles\nC.init(456); // initialize base class without creating instance\nprintln(C.v,\" \",c1.v);\n", "language": "Zkl" }, { "code": "module Graphics;\ntype\n\t{ref,public} (* class *)\n\tPoint = object(ord,abs: integer)\n\tvar\n\t\t(* instance variables *)\n\t\t{public,immutable} x,y: integer;\n\n\t(* method *)\n\tprocedure {public} Ord():integer;\n\tbegin\n\t\treturn y\n\tend Ord;\n\n\t(* method *)\n\tprocedure {public} Abs():integer;\n\tbegin\n\t\treturn x\n\tend Abs;\n\n\t(* constructor *)\n\tbegin\n\t\tself.x := ord;\n\t\tself.y := abs;\n\tend Point;\nend Graphics.\n\nmodule Main;\nimport Graphics;\nvar\n\tp: Graphics.Point;\n\nprocedure Write(p: Graphics.Point);\nbegin\n\twriteln('[':1,p.x:3,',':1,p.y:3,']':1)\nend Write;\n\nbegin\n\tp := new Graphics.Point(12,12);\n\tWrite(p);\n\twriteln(\"Abs: \":4,p.Abs():3,\" Ord: \":5,p.Ord():3);\nend Main.\n", "language": "Zonnon" } ]
Classes
[ { "code": "---\ncategory:\n- Functions and subroutines\nfrom: http://rosettacode.org/wiki/Closures/Value_capture\n", "language": "00-META" }, { "code": ";Task:\nCreate a list of ten functions, in the simplest manner possible &nbsp; (anonymous functions are encouraged), &nbsp; such that the function at index&nbsp;&nbsp;<big> ''<b> i </b>'' </big> &nbsp; (you may choose to start &nbsp; <big> ''<b> i </b>'' </big> &nbsp; from either &nbsp; <big> '''0''' </big> &nbsp; or &nbsp; <big> '''1'''), </big> &nbsp; when run, should return the square of the index, &nbsp; that is, &nbsp; <big> ''<b> i </b>'' <sup>2</sup>.</big> \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "language": "00-TASK" }, { "code": "[(() -> Int)] funcs\nL(i) 10\n funcs.append(() -> @=i * @=i)\nprint(funcs[3]())\n", "language": "11l" }, { "code": "(freeze '(a b) '(lambda (c) (list a b c)))\n", "language": "Acornsoft-Lisp" }, { "code": "(lambda (c)\n ((lambda ((a . 1) (b . 2))\n (list a b c))))\n", "language": "Acornsoft-Lisp" }, { "code": "( (lambda ((a . 1) (b . 2))\n (list a b c)) )\n", "language": "Acornsoft-Lisp" }, { "code": "(defun freeze (_fvars_ _lambda-expr_)\n (freeze-vars\n (mapc cons _fvars_ (mapc eval _fvars_))\n (cadr _lambda-expr_)\n (cddr _lambda-expr_)))\n\n(defun freeze-vars (bindings lvars lbody)\n (list 'lambda lvars\n (list (cons 'lambda (cons bindings lbody)))))\n", "language": "Acornsoft-Lisp" }, { "code": "(defun range (from to)\n (cond ((greaterp from to) '())\n (t (cons from (range (add1 from) to)))))\n\n(defun example ()\n (mapc '(lambda (f) (f))\n (mapc '(lambda (i)\n (freeze '(i) '(lambda () (times i i))))\n (range 1 10))))\n", "language": "Acornsoft-Lisp" }, { "code": "with Ada.Text_IO;\n\nprocedure Value_Capture is\n\n protected type Fun is -- declaration of the type of a protected object\n entry Init(Index: Natural);\n function Result return Natural;\n private\n N: Natural := 0;\n end Fun;\n\n protected body Fun is -- the implementation of a protected object\n entry Init(Index: Natural) when N=0 is\n begin -- after N has been set to a nonzero value, it cannot be changed any more\n N := Index;\n end Init;\n function Result return Natural is (N*N);\n end Fun;\n\n A: array (1 .. 10) of Fun; -- an array holding 10 protected objects\n\nbegin\n for I in A'Range loop -- initialize the protected objects\n A(I).Init(I);\n end loop;\n\n for I in A'First .. A'Last-1 loop -- evaluate the functions, except for the last\n Ada.Text_IO.Put(Integer'Image(A(I).Result));\n end loop;\nend Value_Capture;\n", "language": "Ada" }, { "code": "[1:10]PROC(BOOL)INT squares;\n\nFOR i FROM 1 TO 10 DO\n HEAP INT captured i := i;\n squares[i] := ((REF INT by ref i, INT by val i,BOOL b)INT:(INT i = by ref i; (b|by ref i := 0); by val i*i))\n (captured i, captured i,)\nOD;\n\nFOR i FROM 1 TO 8 DO print(squares[i](i MOD 2 = 0)) OD;\nprint(new line);\nFOR i FROM 1 TO 10 DO print(squares[i](FALSE)) OD\n", "language": "ALGOL-68" }, { "code": "fns: {n: x; {n expt 2}} map range[10]\n(8 elem fns)[]\n", "language": "ANT" }, { "code": "on run\n set fns to {}\n\n repeat with i from 1 to 10\n set end of fns to closure(i)\n end repeat\n\n |λ|() of item 3 of fns\nend run\n\non closure(x)\n script\n on |λ|()\n x * x\n end |λ|\n end script\nend closure\n", "language": "AppleScript" }, { "code": "-- CLOSURE --------------------------------------------------------------------\n\nscript closure\n on |λ|(x)\n script\n on |λ|()\n x * x\n end |λ|\n end script\n end |λ|\nend script\n\n|λ|() of (item 3 of (map(closure, enumFromTo(1, 10))))\n\n\n-- GENERIC FUNCTIONS ----------------------------------------------------------\n\n-- enumFromTo :: Int -> Int -> [Int]\non enumFromTo(m, n)\n if n < m then\n set d to -1\n else\n set d to 1\n end if\n set lst to {}\n repeat with i from m to n by d\n set end of lst to i\n end repeat\n return lst\nend enumFromTo\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n", "language": "AppleScript" }, { "code": "funcs: [ø]\n\nloop 1..10 'f ->\n 'funcs ++ function [] with 'f [\n f * f\n ]\n\nprint call funcs\\3 []\n", "language": "Arturo" }, { "code": ")abbrev package TESTP TestPackage\nTestPackage() : with\n test: () -> List((()->Integer))\n == add\n test() == [(() +-> i^2) for i in 1..10]\n", "language": "Axiom" }, { "code": "[x() for x in test()]\n", "language": "Axiom" }, { "code": "[1,4,9,16,25,36,49,64,81,100]\n Type: List(Integer)\n", "language": "Axiom" }, { "code": "((main {\n { iter\n 1 take bons 1 take\n dup cp\n {*} cp\n 3 take\n append }\n 10 times\n collect !\n {eval %d nl <<} each }))\n", "language": "Babel" }, { "code": "100\n81\n64\n49\n36\n25\n16\n9\n4\n1\n", "language": "Babel" }, { "code": "( -1:?i\n& :?funcs\n& whl\n ' ( 1+!i:<10:?i\n & !funcs ()'(.$i^2):?funcs\n )\n& whl'(!funcs:%?func %?funcs&out$(!func$))\n);\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <sys/mman.h>\n\ntypedef int (*f_int)();\n\n#define TAG 0xdeadbeef\nint _tmpl() {\n\tvolatile int x = TAG;\n\treturn x * x;\n}\n\n#define PROT (PROT_EXEC | PROT_WRITE)\n#define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS)\nf_int dupf(int v)\n{\n\tsize_t len = (void*)dupf - (void*)_tmpl;\n\tf_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0);\n\tchar *p;\n\tif(ret == MAP_FAILED) {\n\t\tperror(\"mmap\");\n\t\texit(-1);\n\t}\n\tmemcpy(ret, _tmpl, len);\n\tfor (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++)\n\t\tif (*(int *)p == TAG) *(int *)p = v;\n\treturn ret;\n}\n\nint main()\n{\n\tf_int funcs[10];\n\tint i;\n\tfor (i = 0; i < 10; i++) funcs[i] = dupf(i);\n\n\tfor (i = 0; i < 9; i++)\n\t\tprintf(\"func[%d]: %d\\n\", i, funcs[i]());\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "func[0]: 0\nfunc[1]: 1\nfunc[2]: 4\nfunc[3]: 9\nfunc[4]: 16\nfunc[5]: 25\nfunc[6]: 36\nfunc[7]: 49\nfunc[8]: 64\n", "language": "C" }, { "code": "void init(void)\n{\n t = intern(lit(\"t\"));\n x = intern(lit(\"x\"));\n}\n\nval square(val env)\n{\n val xbind = assoc(env, x); /* look up binding of variable x in env */\n val xval = cdr(xbind); /* value is the cdr of the binding cell */\n return num(cnum(xval) * cnum(xval));\n}\n\nint main(void)\n{\n int i;\n val funlist = nil, iter;\n\n init();\n\n for (i = 0; i < 10; i++) {\n val closure_env = cons(cons(x, num(i)), nil);\n funlist = cons(func_f0(closure_env, square), funlist);\n }\n\n for (iter = funlist; iter != nil; iter = cdr(iter)) {\n val fun = car(iter);\n val square = funcall(fun, nao);\n\n printf(\"%d\\n\", cnum(square));\n }\n return 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <functional>\n#include <vector>\n\nint main() {\n std::vector<std::function<int()> > funcs;\n for (int i = 0; i < 10; i++)\n funcs.push_back([=]() { return i * i; });\n for ( std::function<int( )> f : funcs )\n std::cout << f( ) << std::endl ;\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Linq;\n\nclass Program\n{\n static void Main()\n {\n var captor = (Func<int, Func<int>>)(number => () => number * number);\n var functions = Enumerable.Range(0, 10).Select(captor);\n foreach (var function in functions.Take(9))\n {\n Console.WriteLine(function());\n }\n }\n}\n", "language": "C-sharp" }, { "code": "0\n1\n4\n9\n16\n25\n36\n49\n64\n", "language": "C-sharp" }, { "code": "using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main( string[] args )\n {\n List<Func<int>> l = new List<Func<int>>();\n for ( int i = 0; i < 10; ++i )\n {\n // This is key to avoiding the closure trap, because\n // the anonymous delegate captures a reference to\n // outer variables, not their value. So we create 10\n // variables, and each created anonymous delegate\n // has references to that variable, not the loop variable\n var captured_val = i;\n l.Add( delegate() { return captured_val * captured_val; } );\n }\n\n l.ForEach( delegate( Func<int> f ) { Console.WriteLine( f() ); } );\n }\n}\n", "language": "C-sharp" }, { "code": "0\n1\n4\n9\n16\n25\n36\n49\n64\n", "language": "C-sharp" }, { "code": "shared void run() {\n\t\n\t//create a list of closures with a list comprehension\n\tvalue closures = [for(i in 0:10) () => i ^ 2];\n\t\n\tfor(i->closure in closures.indexed) {\n\t\tprint(\"closure number ``i`` returns: ``closure()``\");\n\t}\n}\n", "language": "Ceylon" }, { "code": "(def funcs (map #(fn [] (* % %)) (range 11)))\n(printf \"%d\\n%d\\n\" ((nth funcs 3)) ((nth funcs 4)))\n", "language": "Clojure" }, { "code": "# Generate an array of functions.\nfuncs = ( for i in [ 0...10 ] then do ( i ) -> -> i * i )\n\n# Call each function to demonstrate value capture.\nconsole.log func() for func in funcs\n", "language": "CoffeeScript" }, { "code": "CL-USER> (defparameter alist\n\t (loop for i from 1 to 10\n\t collect (cons i (let ((i i))\n\t\t\t\t(lambda () (* i i))))))\nALIST\nCL-USER> (funcall (cdr (assoc 2 alist)))\n4\nCL-USER> (funcall (cdr (assoc 8 alist)))\n64\n", "language": "Common-Lisp" }, { "code": "import std.stdio;\n\nvoid main() {\n int delegate()[] funcs;\n\n foreach (i; 0 .. 10)\n funcs ~= (i => () => i ^^ 2)(i);\n\n writeln(funcs[3]());\n}\n", "language": "D" }, { "code": "void main() {\n import std.stdio, std.range, std.algorithm;\n\n 10.iota.map!(i => () => i ^^ 2).map!q{ a() }.writeln;\n}\n", "language": "D" }, { "code": "program Project1;\n\ntype\n TFuncIntResult = reference to function: Integer;\n\n// use function that returns anonymous method to avoid capturing the loop variable\nfunction CreateFunc(i: Integer): TFuncIntResult;\nbegin\n Result :=\n function: Integer\n begin\n Result := i * i;\n end;\nend;\n\nvar\n Funcs: array[0..9] of TFuncIntResult;\n i: integer;\nbegin\n // create 10 anonymous functions\n for i := Low(Funcs) to High(Funcs) do\n Funcs[i] := CreateFunc(i);\n\n // call all 10 functions\n for i := Low(Funcs) to High(Funcs) do\n Writeln(Funcs[i]());\nend.\n", "language": "Delphi" }, { "code": "var xs = []\nlet num = 10\n\nfor n in 0..<num {\n xs.Add((n => () => n * n)(n))\n}\n\nfor x in xs {\n print(x())\n}\n", "language": "Dyalect" }, { "code": "(define (fgen i) (lambda () (* i i)))\n(define fs (for/vector ((i 10)) (fgen i))) ;; vector of 10 anonymous functions\n((vector-ref fs 5)) ;; calls fs[5]\n → 25\n", "language": "EchoLisp" }, { "code": "import system'routines;\nimport extensions;\n\npublic program()\n{\n var functions := Array.allocate(10).populate::(int i => { ^ i * i} );\n\n functions.forEach::(func) { console.printLine(func()) }\n}\n", "language": "Elena" }, { "code": "funs = for i <- 0..9, do: (fn -> i*i end)\nEnum.each(funs, &IO.puts &1.())\n", "language": "Elixir" }, { "code": ";; -*- lexical-binding: t; -*-\n(mapcar #'funcall\n (mapcar (lambda (x)\n (lambda ()\n (* x x)))\n '(1 2 3 4 5 6 7 8 9 10)))\n;; => (1 4 9 16 25 36 49 64 81 100)\n", "language": "Emacs-Lisp" }, { "code": "-module(capture_demo).\n-export([demo/0]).\n\ndemo() ->\n Funs = lists:map(fun (X) ->\n fun () ->\n X * X\n end\n end,\n lists:seq(1,10)),\n lists:foreach(fun (F) ->\n io:fwrite(\"~B~n\",[F()])\n end, Funs).\n", "language": "Erlang" }, { "code": "[<EntryPoint>]\nlet main argv =\n let fs = List.init 10 (fun i -> fun () -> i*i)\n do List.iter (fun f -> printfn \"%d\" <| f()) fs\n 0\n", "language": "F-Sharp" }, { "code": "[<EntryPoint>]\nlet main argv =\n let fs = List.map (fun i -> fun () -> i*i) [0..9]\n do List.iter (fun f -> printfn \"%d\" <| f()) fs\n 0\n", "language": "F-Sharp" }, { "code": "[<EntryPoint>]\nlet main argv =\n let fs = List.mapi (fun i x -> fun () -> i*i) (List.replicate 10 None)\n do List.iter (fun f -> printfn \"%d\" <| f()) fs\n 0\n", "language": "F-Sharp" }, { "code": "[<EntryPoint>]\nlet main argv =\n let fs = Seq.initInfinite (fun i -> fun () -> i*i)\n do Seq.iter (fun f -> printfn \"%d\" <| f()) (Seq.take 10 fs)\n 0\n", "language": "F-Sharp" }, { "code": "USING: io kernel locals math prettyprint sequences ;\n\n[let\n ! Create a sequence of 10 quotations\n 10 iota [\n :> i ! Bind lexical variable i\n [ i i * ] ! Push a quotation to calculate i squared\n ] map :> seq\n\n { 3 8 } [\n dup pprint \" squared is \" write\n seq nth call .\n ] each\n]\n", "language": "Factor" }, { "code": "USING: fry io kernel math prettyprint sequences ;\n\n! Push a sequence of 10 quotations\n10 iota [\n '[ _ dup * ] ! Push a quotation ( i -- i*i )\n] map\n\n{ 3 8 } [\n dup pprint \" squared is \" write\n over nth call .\n] each\ndrop\n", "language": "Factor" }, { "code": "class Closures\n{\n Void main ()\n {\n // define a list of functions, which take no arguments and return an Int\n |->Int|[] functions := [,]\n\n // create and store a function which returns i*i for i in 0 to 10\n (0..10).each |Int i|\n {\n functions.add (|->Int| { i*i })\n }\n\n // show result of calling function at index position 7\n echo (\"Function at index: \" + 7 + \" outputs \" + functions[7].call)\n }\n}\n", "language": "Fantom" }, { "code": ": xt-array here { a }\n 10 cells allot 10 0 do\n\t:noname i ]] literal dup * ; [[ a i cells + !\n loop a ;\n\nxt-array 5 cells + @ execute .\n", "language": "Forth" }, { "code": "25\n", "language": "Forth" }, { "code": "' FB 1.05.0 Win64\n\nType Closure\n Private:\n index As Integer\n Public:\n Declare Constructor(index As Integer = 0)\n Declare Function Square As Integer\nEnd Type\n\nConstructor Closure(index As Integer = 0)\n This.index = index\nEnd Constructor\n\nFunction Closure.Square As Integer\n Return index * index\nEnd Function\n\nDim a(1 To 10) As Closure\n\n' create Closure objects which capture their index\nFor i As Integer = 1 To 10\n a(i) = Closure(i)\nNext\n\n' call the Square method on all but the last object\nFor i As Integer = 1 to 9\n Print a(i).Square\nNext\n\nPrint\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc main() {\n fs := make([]func() int, 10)\n for i := range fs {\n i := i\n fs[i] = func() int {\n return i * i\n }\n }\n fmt.Println(\"func #0:\", fs[0]())\n fmt.Println(\"func #3:\", fs[3]())\n}\n", "language": "Go" }, { "code": "def closures = (0..9).collect{ i -> { -> i*i } }\n", "language": "Groovy" }, { "code": "assert closures instanceof List\nassert closures.size() == 10\nclosures.each { assert it instanceof Closure }\nprintln closures[7]()\n", "language": "Groovy" }, { "code": "fs = map (\\i _ -> i * i) [1 .. 10]\n", "language": "Haskell" }, { "code": "fs = [const $ i * i | i <- [1 .. 10]]\n", "language": "Haskell" }, { "code": "fs = take 10 coFs where coFs = [const $ i * i | i <- [1 ..]]\n", "language": "Haskell" }, { "code": "> :t fs\nfs :: [b -> Integer]\n> map ($ ()) fs\n[1,4,9,16,25,36,49,64,81,100]\n> fs !! 9 $ ()\n100\n> fs !! 8 $ undefined\n81\n", "language": "Haskell" }, { "code": "procedure main(args) # Closure/Variable Capture\n every put(L := [], vcapture(1 to 10)) # build list of index closures\n write(\"Randomly selecting L[\",i := ?*L,\"] = \",L[i]()) # L[i]() calls the closure\nend\n\n# The anonymous 'function', as a co-expression. Most of the code is standard\n# boilerplate needed to use a co-expression as an anonymous function.\n\nprocedure vcapture(x) # vcapture closes over its argument\n return makeProc { repeat { (x[1]^2) @ &source } }\nend\n\nprocedure makeProc(A) # the makeProc PDCO from the UniLib Utils package\n return (@A[1], A[1])\nend\n", "language": "Icon" }, { "code": "(var funcs (for x (range 11) #(* x x)))\n\n[(0 funcs) ((3 funcs)) ((4 funcs))]\n", "language": "Icon" }, { "code": "blist := list(0,1,2,3,4,5,6,7,8,9) map(i,block(i,block(i*i)) call(i))\nwriteln(blist at(3) call) // prints 9\n", "language": "Io" }, { "code": "constF=:3 :0\n {.''`(y \"_)\n)\n", "language": "J" }, { "code": "flist=: constF\"0 i.10\nslist=: constF\"0 *:i.10\n", "language": "J" }, { "code": " flist @.3\n3\"_\n slist @.3\n9\"_\n", "language": "J" }, { "code": " flist @.4''\n4\n slist @.4''\n16\n", "language": "J" }, { "code": " flist@.(?9) ''\n7\n slist@.(?9) ''\n25\n", "language": "J" }, { "code": "geni=: {{\n N=. cocreate''\n i__N=. y\n N\n}}\ntask=: {{ u {{ u {{ u i__n [ y }} (geni y)`'' }}\"0 i. y }}\n", "language": "J" }, { "code": " fns=: *: task 10\n [email protected] ''\n9\n [email protected] ''\n25\n [email protected] ''\n49\n", "language": "J" }, { "code": " ( VL=. (<@:((<'\"')(0:`)(,^:)&_))\"0@:(^&2)@:i. 10 ) NB. Producing a list of boxed anonymous verbs (functions)\n┌───┬───┬───┬───┬────┬────┬────┬────┬────┬────┐\n│0\"_│1\"_│4\"_│9\"_│16\"_│25\"_│36\"_│49\"_│64\"_│81\"_│\n└───┴───┴───┴───┴────┴────┴────┴────┴────┴────┘\n\n {::&VL 5 NB. Evoking the 6th verb (function)\n25\"_\n {::&VL 5 '' NB. Invoking the 6th verb with a dummy argument ('')\n25\n", "language": "J" }, { "code": "import java.util.function.Supplier;\nimport java.util.ArrayList;\n\npublic class ValueCapture {\n public static void main(String[] args) {\n\tArrayList<Supplier<Integer>> funcs = new ArrayList<>();\n\tfor (int i = 0; i < 10; i++) {\n\t int j = i;\n\t funcs.add(() -> j * j);\n\t}\n\n\tSupplier<Integer> foo = funcs.get(3);\n\tSystem.out.println(foo.get()); // prints \"9\"\n }\n}\n", "language": "Java" }, { "code": "import java.util.List;\nimport java.util.function.IntSupplier;\nimport java.util.stream.IntStream;\n\nimport static java.util.stream.Collectors.toList;\n\npublic interface ValueCapture {\n public static void main(String... arguments) {\n List<IntSupplier> closures = IntStream.rangeClosed(0, 10)\n .<IntSupplier>mapToObj(i -> () -> i * i)\n .collect(toList())\n ;\n\n IntSupplier closure = closures.get(3);\n System.out.println(closure.getAsInt()); // prints \"9\"\n }\n}\n", "language": "Java" }, { "code": "var funcs = [];\nfor (var i = 0; i < 10; i++) {\n funcs.push( (function(i) {\n return function() { return i * i; }\n })(i) );\n}\nwindow.alert(funcs[3]()); // alerts \"9\"\n", "language": "JavaScript" }, { "code": "<script type=\"application/javascript;version=1.7\">\nvar funcs = [];\nfor (var i = 0; i < 10; i++) {\n let (i = i) {\n funcs.push( function() { return i * i; } );\n }\n}\nwindow.alert(funcs[3]()); // alerts \"9\"\n</script>\n", "language": "JavaScript" }, { "code": "\"use strict\";\nlet funcs = [];\nfor (let i = 0; i < 10; ++i) {\n funcs.push((i => () => i*i)(i));\n}\nconsole.log(funcs[3]());\n", "language": "JavaScript" }, { "code": "(function () {\n 'use strict';\n\n // Int -> Int -> [Int]\n function range(m, n) {\n return Array.apply(null, Array(n - m + 1))\n .map(function (x, i) {\n return m + i;\n });\n }\n\n var lstFns = range(0, 10)\n .map(function (i) {\n return function () {\n return i * i;\n };\n })\n\n return lstFns[3]();\n\n})();\n", "language": "JavaScript" }, { "code": "let funcs = [...Array(10).keys()].map(i => () => i*i);\n", "language": "JavaScript" }, { "code": "funcs = [ () -> i^2 for i = 1:10 ]\n", "language": "Julia" }, { "code": "// version 1.0.6\n\nfun main(args: Array<String>) {\n // create an array of 10 anonymous functions which return the square of their index\n val funcs = Array(10){ fun(): Int = it * it }\n // call all but the last\n (0 .. 8).forEach { println(funcs[it]()) }\n}\n", "language": "Kotlin" }, { "code": "{def A\n {A.new\n {S.map {lambda {:x} {* :x :x}}\n {S.serie 0 10}\n}}}\n\n{A.get 3 {A}} // equivalent to A[3]\n-> 9\n{A.get 4 {A}}\n-> 16\n", "language": "Lambdatalk" }, { "code": "functions := 10 times to (Array) map {\n takes '[i].\n proc { (i) * (i). }.\n}.\n\nfunctions visit { println: $1 call. }.\n", "language": "Latitude" }, { "code": "> (set funcs (list-comp ((<- m (lists:seq 1 10)))\n (lambda () (math:pow m 2))))\n", "language": "LFE" }, { "code": "(#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>\n #Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>\n #Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>\n #Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>\n #Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>)\n", "language": "LFE" }, { "code": "> (funcall (car funcs))\n1.0\n> (funcall (cadr funcs))\n4.0\n> (funcall (cadddr funcs))\n16.0\n> (funcall (lists:nth 8 funcs))\n64.0\n", "language": "LFE" }, { "code": "-- parent script \"CallFunction\"\n\nproperty _code\n\n-- if the function is supposed to return something, the code must contain a line that starts with \"res=\"\non new (me, code)\n me._code = code\n return me\nend\n\non call (me)\n ----------------------------------------\n -- If custom arguments were passed, evaluate them in the current context.\n -- Note: in the code passed to the constructor they have to be referenced\n -- as arg[1], arg[2], ...\n arg = []\n repeat with i = 3 to the paramCount\n arg[i-2] = param(i)\n end repeat\n ----------------------------------------\n res = VOID\n do(me._code)\n return res\nend\n", "language": "Lingo" }, { "code": "funcs = []\nrepeat with i = 1 to 10\n code = \"res=\"&i&\"*\"&i\n funcs[i] = script(\"CallFunction\").new(code)\nend repeat\n\nput call(funcs[3], _movie)\n-- 9\n", "language": "Lingo" }, { "code": "funcs = []\nrepeat with i = 1 to 10\n code = \"\"\n put \"res = \"&i&\"*\"&i &RETURN after code\n put \"repeat with i = 1 to arg.count\" &RETURN after code\n put \" res = res + arg[i]\" &RETURN after code\n put \"end repeat\" after code\n funcs[i] = script(\"CallFunction\").new(code)\nend repeat\n\nput call(funcs[3], _movie, 23)\n-- 32\n\nput call(funcs[7], _movie, 4, 5, 6)\n-- 64\n", "language": "Lingo" }, { "code": ":- object(value_capture).\n\n :- public(show/0).\n show :-\n integer::sequence(1, 10, List),\n meta::map(create_closure, List, Closures),\n meta::map(call_closure, List, Closures).\n\n create_closure(Index, [Double]>>(Double is Index*Index)).\n\n call_closure(Index, Closure) :-\n call(Closure, Result),\n write('Closure '), write(Index), write(' : '), write(Result), nl.\n\n:- end_object.\n", "language": "Logtalk" }, { "code": "| ?- value_capture::show.\nClosure 1 : 1\nClosure 2 : 4\nClosure 3 : 9\nClosure 4 : 16\nClosure 5 : 25\nClosure 6 : 36\nClosure 7 : 49\nClosure 8 : 64\nClosure 9 : 81\nClosure 10 : 100\nyes\n", "language": "Logtalk" }, { "code": "funcs={}\nfor i=1,10 do\n table.insert(funcs, function() return i*i end)\nend\nfuncs[2]()\nfuncs[3]()\n", "language": "Lua" }, { "code": "Dim Base 0, A(10)\nFor i=0 to 9 {\n a(i)=lambda i -> i**2\n}\nFor i=0 to 9 {\n Print a(i)()\n}\n", "language": "M2000-Interpreter" }, { "code": "document a$\nFor i=0 to 9 {\n a$=format$(\"{0:0:-20}\",a(i)())+{\n }\n}\nClipboard a$\n", "language": "M2000-Interpreter" }, { "code": "Inventory Alfa\nFor i=0 to 9 {\n Append Alfa, i:=lambda i -> i**2\n}\nFor i=0 to 9 {\n Print Alfa(i)()\n}\n\nBeta=Stack\nStack Beta {\n For i=0 to 9 {\n Data lambda i -> i**2\n }\n}\nDef Fun(X)=X()\n\\\\ reading functions from position 1 to 10\nFor i=0 to 9 {\n Print fun(stackitem(Beta,i+1))\n}\n\\\\ pop functions form stack Beta\nStack Beta {\n While not empty {\n Read M\n Print M()\n }\n}\n", "language": "M2000-Interpreter" }, { "code": "> L := map( i -> (() -> i^2), [seq](1..10) ):\n> seq( L[i](),i=1..10);\n 1, 4, 9, 16, 25, 36, 49, 64, 81, 100\n> L[4]();\n 16\n", "language": "Maple" }, { "code": "Function[i, i^2 &] /@ Range@10\n->{1^2 &, 2^2 &, 3^2 &, 4^2 &, 5^2 &, 6^2 &, 7^2 &, 8^2 &, 9^2 &, 10^2 &}\n\n%[[2]][]\n->4\n", "language": "Mathematica" }, { "code": "using System.Console;\n\nmodule Closures\n{\n Main() : void\n {\n def f(x) { fun() { x ** 2 } }\n def funcs = $[f(x) | x in $[0 .. 10]].ToArray(); // using array for easy indexing\n\n WriteLine($\"$(funcs[4]())\");\n WriteLine($\"$(funcs[2]())\");\n }\n}\n", "language": "Nemerle" }, { "code": "var funcs: seq[proc(): int] = @[]\n\nfor i in 0..9:\n (proc =\n let x = i\n funcs.add(proc (): int = x * x))()\n\nfor i in 0..8:\n echo \"func[\", i, \"]: \", funcs[i]()\n", "language": "Nim" }, { "code": "use Collection.Generic;\n\nclass Capture {\n function : Main(args : String[]) ~ Nil {\n funcs := Vector->New()<FuncHolder<IntHolder> >;\n\n for(i := 0; i < 10; i += 1;) {\n funcs->AddBack(FuncHolder->New(\\() ~ IntHolder : () => i * i)<IntHolder>);\n };\n\n each(i : funcs) {\n func := funcs->Get(i)->Get()<IntHolder>;\n func()->Get()->PrintLine();\n };\n }\n}\n", "language": "Objeck" }, { "code": "NSMutableArray *funcs = [[NSMutableArray alloc] init];\nfor (int i = 0; i < 10; i++) {\n [funcs addObject:[^ { return i * i; } copy]];\n}\n\nint (^foo)(void) = funcs[3];\nNSLog(@\"%d\", foo()); // logs \"9\"\n", "language": "Objective-C" }, { "code": "let () =\n let cls = Array.init 10 (fun i -> (function () -> i * i)) in\n Random.self_init ();\n for i = 1 to 6 do\n let x = Random.int 9 in\n Printf.printf \" fun.(%d) = %d\\n\" x (cls.(x) ());\n done\n", "language": "OCaml" }, { "code": ": newClosure(i) #[ i sq ] ;\n10 seq map(#newClosure) at(7) perform .\n", "language": "Oforth" }, { "code": "vector(10,i,()->i^2)[5]()\n", "language": "PARI-GP" }, { "code": "my @f = map(sub { $_ * $_ }, 0 .. 9); # @f is an array of subs\nprint $f[$_](), \"\\n\" for (0 .. 8); # call and print all but last\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #000080;font-style:italic;\">-- First some generic handling stuff, handles partial_args\n -- of any mixture of any length and element types.</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">closures</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">add_closure</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">rid</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">partial_args</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">closures</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">closures</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">rid</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">partial_args</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">closures</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (return an integer id)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">call_closure</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">id</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">args</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">rid</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">partial_args</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">closures</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">id</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">call_func</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">rid</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">partial_args</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">args</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- The test routine to be made into a closure, or ten\n -- Note that all external references/captured variables must\n -- be passed as arguments, and grouped together on the lhs</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">square</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">i</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- Create the ten closures as asked for.\n -- Here, cids is just {1,2,3,4,5,6,7,8,9,10}, however ids would be more\n -- useful for a mixed bag of closures, possibly stored all over the shop.\n -- Likewise add_closure could have been a procedure for this demo, but\n -- you would probably want the function in a real-world application.</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cids</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000080;font-style:italic;\">--for i=11 to 20 do -- alternative test</span>\n <span style=\"color: #000000;\">cids</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">add_closure</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">routine_id</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"square\"</span><span style=\"color: #0000FF;\">),{</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000080;font-style:italic;\">-- And finally call em (this loop is blissfully unaware what function\n -- it is actually calling, and what partial_arguments it is passing)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" %d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">call_closure</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cids</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],{}))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">square</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">tid</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">getd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"i\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tid</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (setd valid here too)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">i</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tids</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000080;font-style:italic;\">--for i=11 to 20 do</span>\n <span style=\"color: #000000;\">tids</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">new_dict</span><span style=\"color: #0000FF;\">({{</span><span style=\"color: #008000;\">\"i\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">}})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" %d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">square</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tids</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "def power2\n dup *\nenddef\n\ngetid power2 10 repeat\n\nlen for\n dup rot swap get rot swap exec print \" \" print\nendfor\n\nnl\n\n/# Another mode #/\nlen for\n var i\n i get i swap exec print \" \" print\nendfor\n", "language": "Phixmonti" }, { "code": "<?php\n$funcs = array();\nfor ($i = 0; $i < 10; $i++) {\n $funcs[] = function () use ($i) { return $i * $i; };\n}\necho $funcs[3](), \"\\n\"; // prints 9\n?>\n", "language": "PHP" }, { "code": "<?php\n$funcs = array();\nfor ($i = 0; $i < 10; $i++) {\n $funcs[] = create_function('', '$i = ' . var_export($i, true) . '; return $i * $i;');\n}\necho $funcs[3](), \"\\n\"; // prints 9\n?>\n", "language": "PHP" }, { "code": "(setq FunList\n (make\n (for @N 10\n (link (curry (@N) () (* @N @N))) ) ) )\n", "language": "PicoLisp" }, { "code": "array funcs = ({});\nforeach(enumerate(10);; int i)\n{\n funcs+= ({\n lambda(int j)\n {\n return lambda()\n {\n return j*j;\n };\n }(i)\n });\n}\n", "language": "Pike" }, { "code": "function Get-Closure ([double]$Number)\n{\n {param([double]$Sum) return $script:Number *= $Sum}.GetNewClosure()\n}\n", "language": "PowerShell" }, { "code": "for ($i = 1; $i -lt 11; $i++)\n{\n $total = Get-Closure -Number $i\n\n [PSCustomObject]@{\n Function = $i\n Sum = & $total -Sum $i\n }\n}\n", "language": "PowerShell" }, { "code": "$numbers = 1..20 | Get-Random -Count 10\n\nforeach ($number in $numbers)\n{\n $total = Get-Closure -Number $number\n\n [PSCustomObject]@{\n Function = $number\n Sum = & $total -Sum $number\n }\n}\n", "language": "PowerShell" }, { "code": ":-use_module(library(lambda)).\n\n\nclosure :-\n\tnumlist(1,10, Lnum),\n\tmaplist(make_func, Lnum, Lfunc),\n\tmaplist(call_func, Lnum, Lfunc).\n\n\nmake_func(I, \\X^(X is I*I)).\n\ncall_func(N, F) :-\n\tcall(F, R),\n\tformat('Func ~w : ~w~n', [N, R]).\n", "language": "Prolog" }, { "code": "funcs = []\nfor i in range(10):\n funcs.append(lambda: i * i)\nprint funcs[3]() # prints 81\n", "language": "Python" }, { "code": "funcs = []\nfor i in range(10):\n funcs.append(lambda i=i: i * i)\nprint funcs[3]() # prints 9\n", "language": "Python" }, { "code": "funcs = [lambda i=i: i * i for i in range(10)]\nprint funcs[3]() # prints 9\n", "language": "Python" }, { "code": "funcs = []\nfor i in range(10):\n funcs.append((lambda i: lambda: i * i)(i))\nprint funcs[3]() # prints 9\n", "language": "Python" }, { "code": "funcs = [(lambda i: lambda: i)(i * i) for i in range(10)]\nprint funcs[3]() # prints 9\n", "language": "Python" }, { "code": "funcs = map(lambda i: lambda: i * i, range(10))\nprint funcs[3]() # prints 9\n", "language": "Python" }, { "code": "funcs=[eval(\"lambda:%s\"%i**2)for i in range(10)]\nprint funcs[3]() # prints 9\n", "language": "Python" }, { "code": " [ table ] is functions ( n --> [ )\n\n 10 times\n [ i^ ' [ dup * ] join\n ' functions put ]\n\n 5 functions do echo\n", "language": "Quackery" }, { "code": "# assign 's' a list of ten functions\ns <- sapply (1:10, # integers 1..10 become argument 'x' below\n function (x) {\n x # force evaluation of promise x\n\tfunction (i=x) i*i # this *function* is the return value\n })\n\ns[[5]]() # call the fifth function in the list of returned functions\n[1] 25 # returns vector of length 1 with the value 25\n", "language": "R" }, { "code": "s[[5]](10)\n[1] 100\n", "language": "R" }, { "code": "s <- sapply (1:10,\n function (x) {\n x # force evaluation of promise x\n\tfunction () {\n R <- x*x\n # evaluate the language expression \"x <- x + 1\" in the persistent parent environment\n evalq (x <- x + 1, parent.env(environment()))\n R # return squared value\n }})\n\ns[[5]]()\n[1] 25 # 5^2\ns[[5]]()\n[1] 36 # now 6^2\ns[[1]]()\n[1] 1 # 1^2\ns[[1]]()\n[1] 4 # now 2^2\n", "language": "R" }, { "code": " evalq (x <- x + 1, parent.env(environment()))\n", "language": "R" }, { "code": " x <<- x + 1\n", "language": "R" }, { "code": "#lang racket\n(define functions (for/list ([i 10]) (λ() (* i i))))\n(map (λ(f) (f)) functions)\n", "language": "Racket" }, { "code": "'(0 1 4 9 16 25 36 49 64 81)\n", "language": "Racket" }, { "code": "my @c = gather for ^10 -> $i {\n take { $i * $i }\n}\n\n.().say for @c.pick(*); # call them in random order\n", "language": "Raku" }, { "code": "say .() for pick *, map -> $i { -> {$i * $i} }, ^10\n", "language": "Raku" }, { "code": "funs: collect [repeat i 10 [keep func [] reduce [i ** 2]]]\n\n>> funs/7\n== 49\n", "language": "Red" }, { "code": "/*REXX program has a list of ten functions, each returns its invocation (index) squared.*/\nparse arg seed base $ /*obtain optional arguments from the CL*/\nif datatype(seed, 'W') then call random ,,seed /*Not given? Use random start seed. */\nif base=='' | base=\",\" then base=0 /* \" \" Use a zero─based list. */\nif $='' then $= 8 5 4 9 1 3 2 7 6 0 /* \" \" Use ordered function list*/\n /*the $ list must contain 10 functions.*/\nsay 'the' word(\"zero one\", base+1)'─based list is: ' $ /*show list of functions.*/\n /*BASED must be either 1 or 0. */\n?='.'random(0, 9) /*get a random name of a function. */\ninterpret 'CALL' ? /*invoke a randomly selected function. */\nsay 'function ' ? \" returned \" result /*display the value of random function.*/\nexit /*stick a fork in it, we're all done. */\n/*────────────────────────[Below are the closest things to anonymous functions in REXX].*/\n.0: return .(0) /*function .0 ─── bump its counter. */\n.1: return .(1) /* ' .1 \" \" \" \" */\n.2: return .(2) /* ' .2 \" \" \" \" */\n.3: return .(3) /* ' .3 \" \" \" \" */\n.4: return .(4) /* ' .4 \" \" \" \" */\n.5: return .(5) /* ' .5 \" \" \" \" */\n.6: return .(6) /* ' .6 \" \" \" \" */\n.7: return .(7) /* ' .7 \" \" \" \" */\n.8: return .(8) /* ' .8 \" \" \" \" */\n.9: return .(9) /* ' .9 \" \" \" \" */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n.: arg #; _=wordpos(#,$); if _==0 then return 'not in the list.'; return (_-(\\base))**2\n", "language": "REXX" }, { "code": "x = funcs(7)\nsee x + nl\n\nfunc funcs n\n fn = list(n)\n for i = 1 to n\n fn[i] =i*i\n next\n return fn\n", "language": "Ring" }, { "code": "procs = Array.new(10){|i| ->{i*i} } # -> creates a lambda\np procs[7].call # => 49\n", "language": "Ruby" }, { "code": "fn main() {\n let fs: Vec<_> = (0..10).map(|i| {move || i*i} ).collect();\n println!(\"7th val: {}\", fs[7]());\n}\n", "language": "Rust" }, { "code": "val closures=for(i <- 0 to 9) yield (()=>i*i)\n0 to 8 foreach (i=> println(closures(i)()))\nprintln(\"---\\n\"+closures(7)())\n", "language": "Scala" }, { "code": ";;; Collecting lambdas in a tail-recursive function.\n(define (build-list-of-functions n i list)\n (if (< i n)\n (build-list-of-functions n (+ i 1) (cons (lambda () (* (- n i) (- n i))) list))\n list))\n\n(define list-of-functions (build-list-of-functions 10 1 '()))\n\n(map (lambda (f) (f)) list-of-functions)\n\n((list-ref list-of-functions 8))\n", "language": "Scheme" }, { "code": "'(1 4 9 16 25 36 49 64 81)\n81\n", "language": "Scheme" }, { "code": "(define list-of-functions (map (lambda (x) (lambda () (* x x))) (iota 0 1 10)))\n\n; print the result\n(display\n (map (lambda (n) (n)) list-of-functions)\n(newline)\n", "language": "Scheme" }, { "code": "var f = (\n 10.of {|i| func(j){i * j} }\n)\n\n9.times { |j|\n say f[j](j)\n}\n", "language": "Sidef" }, { "code": "var f = (1..10).map { |i|\n func(j){i * j}\n}\n\nfor j (1..9) {\n say f[j-1](j)\n}\n", "language": "Sidef" }, { "code": "funcs := (1 to: 10) collect: [ :i | [ i * i ] ] .\n(funcs at: 3) value displayNl .\n", "language": "Smalltalk" }, { "code": "var fnlist = {};\nfor var i = 0; i < 10; i++ {\n\tfnlist[i] = function() {\n\t\treturn i * i;\n\t};\n}\n\nprint(fnlist[3]()); // prints 9\nprint(fnlist[5]()); // prints 25\n", "language": "Sparkling" }, { "code": "var fnlist = map(range(10), function(k, v) {\n\treturn function() {\n\t\treturn v * v;\n\t};\n});\n\nprint(fnlist[3]()); // prints 9\nprint(fnlist[5]()); // prints 25\n", "language": "Sparkling" }, { "code": "List.map (fn x => x () ) ( List.tabulate (10,(fn i => (fn ()=> i*i)) ) ) ;\n", "language": "Standard-ML" }, { "code": "val it = [0,1,4,9,16,25,36,49,64,81] : int list\n", "language": "Standard-ML" }, { "code": "var funcs: [() -> Int] = []\nfor var i = 0; i < 10; i++ {\n funcs.append({ i * i })\n}\nprintln(funcs[3]()) // prints 100\n", "language": "Swift" }, { "code": "var funcs: [() -> Int] = []\nfor i in 0..<10 {\n funcs.append({ i * i })\n}\nprintln(funcs[3]()) // prints 9\n", "language": "Swift" }, { "code": "var funcs: [() -> Int] = []\nfor var i = 0; i < 10; i++ {\n funcs.append({ [i] in i * i })\n}\nprintln(funcs[3]()) // prints 9\n", "language": "Swift" }, { "code": "let funcs = [] + map(0..<10) {i in { i * i }}\nprintln(funcs[3]()) // prints 9\n", "language": "Swift" }, { "code": "package require Tcl 8.6; # Just for tailcall command\n# Builds a value-capturing closure; does NOT couple variables\nproc closure {script} {\n set valuemap {}\n foreach v [uplevel 1 {info vars}] {\n\tlappend valuemap [list $v [uplevel 1 [list set $v]]]\n }\n set body [list $valuemap $script [uplevel 1 {namespace current}]]\n # Wrap, to stop untoward argument passing\n return [list apply [list {} [list tailcall apply $body]]]\n # A version of the previous line compatible with Tcl 8.5 would be this\n # code, but the closure generated is more fragile:\n ### return [list apply $body]\n}\n\n# Simple helper, to avoid capturing unwanted variable\nproc collectFor {var from to body} {\n upvar 1 $var v\n set result {}\n for {set v $from} {$v < $to} {incr v} {lappend result [uplevel 1 $body]}\n return $result\n}\n# Build a list of closures\nproc buildList {} {\n collectFor i 0 10 {\n\tclosure {\n\t # This is the body of the closure\n\t return [expr $i*$i]\n\t}\n }\n}\nset theClosures [buildList]\nforeach i {a b c d e} {# Do 5 times; demonstrates no variable leakage\n set idx [expr {int(rand()*9)}]; # pick random int from [0..9)\n puts $idx=>[{*}[lindex $theClosures $idx]]\n}\n", "language": "Tcl" }, { "code": "(let ((funs (mapcar (ret (op * @@1 @@1)) (range 1 10))))\n [mapcar call [funs 0..-1]])\n", "language": "TXR" }, { "code": "(1 4 9 16 25 36 49 64 81)\n", "language": "TXR" }, { "code": ";; Dropping distracting \"skip last\" requirement\n;; (not implemented in original Elisp either).\n(mapcar 'call\n\t(mapcar (lambda ()\n\t\t (lambda () (* x x))) '(1 2 3 4 5 6 7 8 9 10)))\n", "language": "TXR" }, { "code": "var fs = List.filled(10, null)\nfor (i in 0...fs.count) {\n fs[i] = Fn.new { i * i }\n}\n\nfor (i in 0...fs.count-1) System.print(\"Function #%(i): %(fs[i].call())\")\n", "language": "Wren" }, { "code": "dim funcs$(10)\n\nsub power2(i)\n return i * i\nend sub\n\nfor i = 1 to 10\n funcs$(i) = \"power2\"\nnext\n\nfor i = 1 to 10\n print execute(funcs$(i), i)\nnext\n", "language": "Yabasic" }, { "code": "(0).pump(10,List,fcn(i){i*i}.fp)[8]() //-->64\nlist:=(0).pump(10,List,fcn(i){i*i}.fp);\nforeach n in (list.len()-1) { list[n]().println() }\nlist.run(True).println()\n", "language": "Zkl" } ]
Closures-Value-capture
[ { "code": "---\ncategory:\n- Data Structures\nfrom: http://rosettacode.org/wiki/Collections\nnote: Basic language learning\n", "language": "00-META" }, { "code": "Collections are abstractions to represent sets of values. \n\nIn statically-typed languages, the values are typically of a common data type.\n\n\n;Task:\nCreate a collection, and add a few values to it.\n\n\n{{Template:See also lists}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "\tdc.l TrapString_Bus\n\tdc.l TrapString_Addr\n\tdc.l TrapString_Illegal\n\tdc.l TrapString_Div0\n\tdc.l TrapString_chk\n\tdc.l TrapString_v\n\tdc.l TrapString_priv\n\tdc.l TrapString_trace\n\t\nTrapString_Bus:\n\tdc.b \"Bus error\",255\n\teven\nTrapString_Addr:\n\tdc.b \"Address error\",255\n\teven\nTrapString_Illegal:\n\tdc.b \"Illegal Instruction\",255\n\teven\nTrapString_Div0:\n\tdc.b \"Divide By Zero\",255\n\teven\nTrapString_chk:\n\tdc.b \"CHK Failure\",255\n\teven\nTrapString_v:\n\tdc.b \"Signed Overflow\",255\n\teven\nTrapString_priv:\n\tdc.b \"Privilege Violation\",255\n\teven\nTrapString_trace:\n\tdc.b \"Tracing\",255\n\teven\n", "language": "68000-Assembly" }, { "code": "REPORT z_test_rosetta_collection.\n\nCLASS lcl_collection DEFINITION CREATE PUBLIC.\n\n PUBLIC SECTION.\n METHODS: start.\nENDCLASS.\n\nCLASS lcl_collection IMPLEMENTATION.\n METHOD start.\n DATA(itab) = VALUE int4_table( ( 1 ) ( 2 ) ( 3 ) ).\n\n cl_demo_output=>display( itab ).\n ENDMETHOD.\nENDCLASS.\n\nSTART-OF-SELECTION.\n NEW lcl_collection( )->start( ).\n", "language": "ABAP" }, { "code": "procedure Array_Collection is\n\n A : array (-3 .. -1) of Integer := (1, 2, 3);\n\nbegin\n\n A (-3) := 3;\n A (-2) := 2;\n A (-1) := 1;\n\nend Array_Collection;\n", "language": "Ada" }, { "code": "procedure Array_Collection is\n\n type Array_Type is array (1 .. 3) of Integer;\n A : Array_Type := (1, 2, 3);\n\nbegin\n\n A (1) := 3;\n A (2) := 2;\n A (3) := 1;\n\nend Array_Collection;\n", "language": "Ada" }, { "code": "procedure Array_Collection is\n\n type Array_Type is array (positive range <>) of Integer; -- may be indexed with any positive\n -- Integer value\n A : Array_Type(1 .. 3); -- creates an array of three integers, indexed from 1 to 3\n\nbegin\n\n A (1) := 3;\n A (2) := 2;\n A (3) := 1;\n\nend Array_Collection;\n", "language": "Ada" }, { "code": "with Ada.Containers.Doubly_Linked_Lists;\nuse Ada.Containers;\n\nprocedure Doubly_Linked_List is\n\n package DL_List_Pkg is new Doubly_Linked_Lists (Integer);\n use DL_List_Pkg;\n\n DL_List : List;\n\nbegin\n\n DL_List.Append (1);\n DL_List.Append (2);\n DL_List.Append (3);\n\nend Doubly_Linked_List;\n", "language": "Ada" }, { "code": "with Ada.Containers.Vectors;\nuse Ada.Containers;\n\nprocedure Vector_Example is\n\n package Vector_Pkg is new Vectors (Natural, Integer);\n use Vector_Pkg;\n\n V : Vector;\n\nbegin\n\n V.Append (1);\n V.Append (2);\n V.Append (3);\n\nend Vector_Example;\n", "language": "Ada" }, { "code": "list l;\n", "language": "Aime" }, { "code": "l_p_integer(l, 0, 7);\nl_push(l, \"a string\");\nl_append(l, 2.5);\n", "language": "Aime" }, { "code": "l_query(l, 2)\nl_head(l)\nl_q_text(l, 1)\nl[3]\n", "language": "Aime" }, { "code": "record r;\n", "language": "Aime" }, { "code": "r_p_integer(r, \"key1\", 7);\nr_put(r, \"key2\", \"a string\");\nr[\"key3\"] = .25;\n", "language": "Aime" }, { "code": "r_query(r, \"key1\")\nr_tail(r)\nr[\"key2\"]\n", "language": "Aime" }, { "code": "# create a constant array of integers and set its values #\n[]INT constant array = ( 1, 2, 3, 4 );\n# create an array of integers that can be changed, note the size mst be specified #\n# this array has the default lower bound of 1 #\n[ 5 ]INT mutable array := ( 9, 8, 7, 6, 5 );\n# modify the second element of the mutable array #\nmutable array[ 2 ] := -1;\n# array sizes are normally fixed when the array is created, however arrays can be #\n# declared to be FLEXible, allowing their sizes to change by assigning a new array to them #\n# The standard built-in STRING is notionally defined as FLEX[ 1 : 0 ]CHAR in the standard prelude #\n# Create a string variable: #\nSTRING str := \"abc\";\n# assign a longer value to it #\nstr := \"bbc/itv\";\n# add a few characters to str, +=: adds the text to the beginning, +:= adds it to the end #\n\"[\" +=: str; str +:= \"]\"; # str now contains \"[bbc/itv]\" #\n# Arrays of any type can be FLEXible: #\n# create an array of two integers #\nFLEX[ 1 : 2 ]INT fa := ( 0, 0 );\n# replace it with a new array of 5 elements #\nfa := LOC[ -2 : 2 ]INT;\n", "language": "ALGOL-68" }, { "code": "// Create an empty list of String\nList<String> my_list = new List<String>();\n// Create a nested list\nList<List<Set<Integer>>> my_list_2 = new List<List<Set<Integer>>>();\n", "language": "Apex" }, { "code": "List<Integer> myList = new List<Integer>(); // Define a new list\nmyList.add(47); // Adds a second element of value 47 to the end\n // of the list\nInteger i = myList.get(0); // Retrieves the element at index 0\nmyList.set(0, 1); // Adds the integer 1 to the list at index 0\nmyList.clear(); // Removes all elements from the list\n", "language": "Apex" }, { "code": "String[] colors = new List<String>();\nList<String> colors = new String[1];\ncolors[0] = 'Green';\n", "language": "Apex" }, { "code": "Set<String> s1 = new Set<String>{'a', 'b + c'}; // Defines a new set with two elements\nSet<String> s2 = new Set<String>(s1); // Defines a new set that contains the\n // elements of the set created in the previous step\n", "language": "Apex" }, { "code": "Set<Integer> s = new Set<Integer>(); // Define a new set\ns.add(1); // Add an element to the set\nSystem.assert(s.contains(1)); // Assert that the set contains an element\ns.remove(1); // Remove the element from the set\n", "language": "Apex" }, { "code": "Map<String, String> country_currencies = new Map<String, String>();\nMap<ID, Set<String>> m = new Map<ID, Set<String>>();\nMap<String, String> MyStrings = new Map<String, String>{'a' => 'b', 'c' => 'd'.toUpperCase()};\n", "language": "Apex" }, { "code": "Map<Integer, String> m = new Map<Integer, String>(); // Define a new map\nm.put(1, 'First entry'); // Insert a new key-value pair in the map\nm.put(2, 'Second entry'); // Insert a new key-value pair in the map\nSystem.assert(m.containsKey(1)); // Assert that the map contains a key\nString value = m.get(2); // Retrieve a value, given a particular key\nSystem.assertEquals('Second entry', value);\nSet<Integer> s = m.keySet(); // Return a set that contains all of the keys in the map\n", "language": "Apex" }, { "code": "; initialize array\narr: [\"one\" 2 \"three\" \"four\"]\n\n; add an element to the array\narr: arr ++ 5\n\n; print it\nprint arr\n", "language": "Arturo" }, { "code": "; initialize dictionary\ndict: #[\n\tname: \"john\"\n\tsurname: \"doe\"\n\tage: 34\n\tpreferredFood: [\"fruit\" \"pizza\"]\n]\n\n; add an element to the dictionary\ndict\\country: \"Spain\"\n\n; print it\nprint dict\n", "language": "Arturo" }, { "code": "myCol := Object()\nmycol.mykey := \"my value!\"\nmycol[\"mykey\"] := \"new val!\"\nMsgBox % mycol.mykey ; new val\n", "language": "AutoHotkey" }, { "code": "Loop 3\n array%A_Index% := A_Index * 9\nMsgBox % array1 \" \" array2 \" \" array3 ; 9 18 27\n", "language": "AutoHotkey" }, { "code": "VarSetCapacity(Rect, 16) ; A RECT is a struct consisting of four 32-bit integers (i.e. 4*4=16).\nDllCall(\"GetWindowRect\", UInt, WinExist(), UInt, &Rect) ; WinExist() returns an HWND.\nMsgBox % \"Left \" . NumGet(Rect, 0, true) . \" Top \" . NumGet(Rect, 4, true)\n . \" Right \" . NumGet(Rect, 8, true) . \" Bottom \" . NumGet(Rect, 12, true)\n", "language": "AutoHotkey" }, { "code": "a[0]=\"hello\"\n", "language": "AWK" }, { "code": "split(\"one two three\",a)\n", "language": "AWK" }, { "code": "print a[0]\n", "language": "AWK" }, { "code": "for(i in a) print i\":\"a[i]\n", "language": "AWK" }, { "code": "1→{L₁}\n2→{L₁+1}\n3→{L₁+2}\n4→{L₁+3}\nDisp {L₁}►Dec,i\nDisp {L₁+1}►Dec,i\nDisp {L₁+2}►Dec,i\nDisp {L₁+3}►Dec,i\n", "language": "Axe" }, { "code": " DIM text$(1)\n text$(0) = \"Hello \"\n text$(1) = \"world!\"\n", "language": "BBC-BASIC" }, { "code": " DIM collection{(1) name$, year%}\n collection{(0)}.name$ = \"Richard\"\n collection{(0)}.year% = 1952\n collection{(1)}.name$ = \"Sue\"\n collection{(1)}.year% = 1950\n", "language": "BBC-BASIC" }, { "code": " DIM node{name$, year%, link%}\n list% = 0\n PROCadd(list%, node{}, \"Richard\", 1952)\n PROCadd(list%, node{}, \"Sue\", 1950)\n PROClist(list%, node{})\n END\n\n DEF PROCadd(RETURN l%, c{}, n$, y%)\n LOCAL p%\n DIM p% DIM(c{})-1\n !(^c{}+4) = p%\n c.name$ = n$\n c.year% = y%\n c.link% = l%\n l% = p%\n ENDPROC\n\n DEF PROClist(l%, c{})\n WHILE l%\n !(^c{}+4) = l%\n PRINT c.name$, c.year%\n l% = c.link%\n ENDWHILE\n ENDPROC\n", "language": "BBC-BASIC" }, { "code": "#define cSize( a ) ( sizeof(a)/sizeof(a[0]) ) /* a.size() */\nint ar[10]; /* Collection<Integer> ar = new ArrayList<Integer>(10); */\nar[0] = 1; /* ar.set(0, 1); */\nar[1] = 2;\n\nint* p; /* Iterator<Integer> p; Integer pValue; */\nfor (p=ar; /* for( p = ar.itereator(), pValue=p.next(); */\n p<(ar+cSize(ar)); /* p.hasNext(); */\n p++) { /* pValue=p.next() ) { */\n printf(\"%d\\n\",*p); /* System.out.println(pValue); */\n} /* } */\n", "language": "C" }, { "code": "int* ar; /* Collection<Integer> ar; */\nint arSize;\narSize = (rand() % 6) + 1;\nar = calloc(arSize, sizeof(int) ); /* ar = new ArrayList<Integer>(arSize); */\nar[0] = 1; /* ar.set(0, 1); */\n\nint* p; /* Iterator<Integer> p; Integer pValue; */\nfor (p=ar; /* p=ar.itereator(); for( pValue=p.next(); */\n p<(ar+arSize); /* p.hasNext(); */\n p++) { /* pValue=p.next() ) { */\n printf(\"%d\\n\",*p); /* System.out.println(pValue); */\n} /* } */\n", "language": "C" }, { "code": "int a[5]; // array of 5 ints (since int is POD, the members are not initialized)\na[0] = 1; // indexes start at 0\n\nint primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; // arrays can be initialized on creation\n\n#include <string>\nstd::string strings[4]; // std::string is no POD, therefore all array members are default-initialized\n // (for std::string this means initialized with empty strings)\n", "language": "C++" }, { "code": "#include <vector>\n\nstd::vector<int> v; // empty vector\nv.push_back(5); // insert a 5 at the end\nv.insert(v.begin(), 7); // insert a 7 at the beginning\n", "language": "C++" }, { "code": "#include <deque>\n\nstd::deque<int> d; // empty deque\nd.push_back(5); // insert a 5 at the end\nd.push_front(7); // insert a 7 at the beginning\nd.insert(v.begin()+1, 6); // insert a 6 in the middle\n", "language": "C++" }, { "code": "#include <list>\n\nstd::list<int> l; // empty list\nl.push_back(5); // insert a 5 at the end\nl.push_front(7); // insert a 7 at the beginning\nstd::list::iterator i = l.begin();\n++l;\nl.insert(i, 6); // insert a 6 in the middle\n", "language": "C++" }, { "code": "#include <set>\n\nstd::set<int> s; // empty set\ns.insert(5); // insert a 5\ns.insert(7); // insert a 7 (automatically placed after the 5)\ns.insert(5); // try to insert another 5 (will not change the set)\n", "language": "C++" }, { "code": "#include <multiset>\n\nstd::multiset<int> m; // empty multiset\nm.insert(5); // insert a 5\nm.insert(7); // insert a 7 (automatically placed after the 5)\nm.insert(5); // insert a second 5 (now m contains two 5s, followed by one 7)\n", "language": "C++" }, { "code": "// Creates and initializes a new integer Array\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n//same as\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n//same as\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n//Arrays are zero-based\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n", "language": "C-sharp" }, { "code": "//Create and initialize ArrayList\nArrayList myAl = new ArrayList { \"Hello\", \"World\", \"!\" };\n\n//Create ArrayList and add some values\nArrayList myAL = new ArrayList();\n myAL.Add(\"Hello\");\n myAL.Add(\"World\");\n myAL.Add(\"!\");\n", "language": "C-sharp" }, { "code": "//Create and initialize List\nList<string> myList = new List<string> { \"Hello\", \"World\", \"!\" };\n\n//Create List and add some values\nList<string> myList2 = new List<string>();\n myList2.Add(\"Hello\");\n myList2.Add(\"World\");\n myList2.Add(\"!\");\n", "language": "C-sharp" }, { "code": "//Create an initialize Hashtable\nHashtable myHt = new Hashtable() { { \"Hello\", \"World\" }, { \"Key\", \"Value\" } };\n\n//Create Hashtable and add some Key-Value pairs.\nHashtable myHt2 = new Hashtable();\n\tmyHt2.Add(\"Hello\", \"World\");\n\tmyHt2.Add(\"Key\", \"Value\");\n", "language": "C-sharp" }, { "code": "//Create an initialize Dictionary\nDictionary<string, string> dict = new Dictionary<string, string>() { { \"Hello\", \"World\" }, { \"Key\", \"Value\" } };\n//Create Dictionary and add some Key-Value pairs.\nDictionary<string, string> dict2 = new Dictionary<string, string>();\n\tdict2.Add(\"Hello\", \"World\");\n\tdict2.Add(\"Key\", \"Value\");\n", "language": "C-sharp" }, { "code": "{1 \"a\", \"Q\" 10} ; commas are treated as whitespace\n(hash-map 1 \"a\" \"Q\" 10) ; equivalent to the above\n(let [my-map {1 \"a\"}]\n (assoc my-map \"Q\" 10)) ; \"adding\" an element\n", "language": "Clojure" }, { "code": "'(1 4 7) ; a linked list\n(list 1 4 7)\n(cons 1 (cons 4 '(7)))\n", "language": "Clojure" }, { "code": "['a 4 11] ; somewhere between array and list\n(vector 'a 4 11)\n(cons ['a 4] 11) ; vectors add at the *end*\n", "language": "Clojure" }, { "code": "#{:pig :dog :bear}\n(assoc #{:pig :bear} :dog)\n(set [:pig :bear :dog])\n", "language": "Clojure" }, { "code": " identification division.\n program-id. collections.\n\n data division.\n working-storage section.\n 01 sample-table.\n 05 sample-record occurs 1 to 3 times depending on the-index.\n 10 sample-alpha pic x(4).\n 10 filler pic x value \":\".\n 10 sample-number pic 9(4).\n 10 filler pic x value space.\n 77 the-index usage index.\n\n procedure division.\n collections-main.\n\n set the-index to 3\n move 1234 to sample-number(1)\n move \"abcd\" to sample-alpha(1)\n\n move \"test\" to sample-alpha(2)\n\n move 6789 to sample-number(3)\n move \"wxyz\" to sample-alpha(3)\n\n display \"sample-table : \" sample-table\n display \"sample-number(1): \" sample-number(1)\n display \"sample-record(2): \" sample-record(2)\n display \"sample-number(3): \" sample-number(3)\n\n *> abend: out of bounds subscript, -debug turns on bounds check\n set the-index down by 1\n display \"sample-table : \" sample-table\n display \"sample-number(3): \" sample-number(3)\n\n goback.\n end program collections.\n", "language": "COBOL" }, { "code": "CL-USER> (let ((list '())\n (hash-table (make-hash-table)))\n (push 1 list)\n (push 2 list)\n (push 3 list)\n (format t \"~S~%\" (reverse list))\n (setf (gethash 'foo hash-table) 42)\n (setf (gethash 'bar hash-table) 69)\n (maphash (lambda (key value)\n (format t \"~S => ~S~%\" key value))\n hash-table)\n ;; or print the hash-table in readable form\n ;; (inplementation-dependent)\n (write hash-table :readably t)\n ;; or describe it\n (describe hash-table)\n ;; describe the list as well\n (describe list))\n;; FORMAT on a list\n(1 2 3)\n;; FORMAT on a hash-table\nFOO => 42\nBAR => 69\n;; WRITE :readably t on a hash-table\n#.(SB-IMPL::%STUFF-HASH-TABLE\n (MAKE-HASH-TABLE :TEST 'EQL :SIZE '16 :REHASH-SIZE '1.5\n :REHASH-THRESHOLD '1.0 :WEAKNESS 'NIL)\n '((BAR . 69) (FOO . 42)))\n;; DESCRIBE on a hash-table\n#<HASH-TABLE :TEST EQL :COUNT 2 {1002B6F391}>\n [hash-table]\n\nOccupancy: 0.1\nRehash-threshold: 1.0\nRehash-size: 1.5\nSize: 16\nSynchronized: no\n;; DESCRIBE on a list\n(3 2 1)\n [list]\n; No value\n", "language": "Common-Lisp" }, { "code": ";;; Obtained from Usenet,\n;;; Message-ID: <b3b1cc90-2e2b-43c3-b7d9-785ae29870e7@e23g2000prf.googlegroups.com>\n;;; Posting by Kaz Kylheku, February 28, 2008.\n\n(eval-when (:compile-toplevel :load-toplevel :execute)\n (defun bisect-list (list &optional (minimum-length 0))\n (do ((double-skipper (cddr list) (cddr double-skipper))\n (single-skipper list (cdr single-skipper))\n (length 2 (+ length (if (cdr double-skipper) 2 1))))\n ((null double-skipper)\n (cond\n ((< length minimum-length)\n (values list nil))\n ((consp single-skipper)\n (multiple-value-prog1\n (values list (cdr single-skipper))\n (setf (cdr single-skipper) nil)))\n (t (values list nil))))))\n\n (defun pop-deque-helper (facing-piece other-piece)\n (if (null facing-piece)\n (multiple-value-bind (head tail) (bisect-list other-piece 10)\n (let ((remaining (if tail head))\n (moved (nreverse (or tail head))))\n (values (first moved) (rest moved) remaining)))\n (values (first facing-piece) (rest facing-piece) other-piece))))\n\n(defmacro pop-deque (facing-piece other-piece)\n (let ((result (gensym))\n (new-facing (gensym))\n (new-other (gensym)))\n `(multiple-value-bind (,result ,new-facing ,new-other)\n (pop-deque-helper ,facing-piece ,other-piece)\n (psetf ,facing-piece ,new-facing\n ,other-piece ,new-other)\n ,result)))\n", "language": "Common-Lisp" }, { "code": "int[3] array;\narray[0] = 5;\n// array.length = 4; // compile-time error\n", "language": "D" }, { "code": "int[] array;\narray ~= 5; // append 5\narray.length = 3;\narray[3] = 17; // runtime error: out of bounds. check removed in release mode.\narray = [2, 17, 3];\nwritefln(array.sort); // 2, 3, 17\n", "language": "D" }, { "code": "int[int] array;\n// array ~= 5; // it doesn't work that way!\narray[5] = 17;\narray[6] = 20;\n// prints \"[5, 6]\" -> \"[17, 20]\" - although the order is not specified.\nwritefln(array.keys, \" -> \", array.values);\nassert(5 in array); // returns a pointer, by the way\nif (auto ptr = 6 in array) writefln(*ptr); // 20\n", "language": "D" }, { "code": "// Creates and initializes a new integer Array\nvar\n // Dynamics arrays can be initialized, if it's global variable in declaration scope\n intArray: TArray<Integer> = [1, 2, 3, 4, 5];\n intArray2: array of Integer = [1, 2, 3, 4, 5];\n\n //Cann't initialize statics arrays in declaration scope\n intArray3: array [0..4]of Integer;\n intArray4: array [10..14]of Integer;\n\nprocedure\nvar\n // Any arrays can't be initialized, if it's local variable in declaration scope\n intArray5: TArray<Integer>;\nbegin\n // Dynamics arrays can be full assigned in routine scope\n intArray := [1,2,3];\n intArray2 := [1,2,3];\n\n // Dynamics arrays zero-based\n intArray[0] := 1;\n\n // Dynamics arrays must set size, if it not was initialized before\n SetLength(intArray,5);\n\n // Inline dynamics arrays can be created and initialized routine scope\n // only for version after 10.3 Tokyo\n var intArray6 := [1, 2, 3];\n var intArray7: TArray<Integer> := [1, 2, 3];\nend;\n", "language": "Delphi" }, { "code": "var\n // TLists can't be initialized or created in declaration scope\n List1, List2:TList<Integer>;\nbegin\n List1 := TList<Integer>.Create;\n List1.Add(1);\n list1.AddRange([2, 3]);\n List1.free;\n\n // TList can be initialized using a class derivative from TEnumerable, like it self\n List1 := TList<Integer>.Create;\n list1.AddRange([1,2, 3]);\n\n List2 := TList<Integer>.Create(list1);\n Writeln(List2[2]); // 3\n List1.free;\n List2.free;\n\n\n // Inline TList can be created in routine scope\n // only for version after 10.3 Tokyo\n var List3:= TList<Integer>.Create;\n List3.Add(2);\n List3.free;\n\n var List4: TList<Integer>:= TList<Integer>.Create;\n List4.free;\nend;\n", "language": "Delphi" }, { "code": " var\n // TDictionary can't be initialized or created in declaration scope\n Dic1: TDictionary<string, Integer>;\nbegin\n Dic1 := TDictionary<string, Integer>.Create;\n Dic1.Add('one',1);\n Dic1.free;\n\n // Inline TDictionary can be created in routine scope\n // only for version after 10.3 Tokyo\n var Dic2:= TDictionary<string, Integer>.Create;\n Dic2.Add('one',1);\n Dic2.free;\n\n var Dic3: TDictionary<string, Integer>:= TDictionary<string, Integer>.Create.Create;\n Dic3.Add('one',1);\n Dic3.free;\nend;\n", "language": "Delphi" }, { "code": "var\n Queue1, Queue2: TQueue<Integer>;\n List1:TList<Integer>;\nbegin\n Queue1 := TQueue<Integer>.Create;\n Queue1.Enqueue(1);\n Queue1.Enqueue(2);\n Writeln(Queue1.Dequeue); // 1\n Writeln(Queue1.Dequeue); // 2\n Queue1.free;\n\n // TQueue can be initialized using a class derivative from TEnumerable, like TList<T>\n List1 := TList<Integer>.Create;\n List1.Add(3);\n Queue2:= TQueue<Integer>.Create(List1);\n Writeln(Queue2.Dequeue); // 3\n List1.free;\n Queue2.free;\n\n // Inline TQueue can be created in routine scope\n // only for version after 10.3 Tokyo\n var Queue3 := TQueue<Integer>.Create;\n Queue3.free;\nend;\n", "language": "Delphi" }, { "code": "var\n Stack1, Stack2: TStack<Integer>;\n List1:TList<Integer>;\nbegin\n Stack1:= TStack<Integer>.Create;\n Stack1.Push(1);\n Stack1.Push(2);\n Writeln(Stack1.Pop); // 2\n Writeln(Stack1.Pop); // 1\n Stack1.free;\n\n // TStack can be initialized using a class derivative from TEnumerable, like TList<T>\n List1 := TList<Integer>.Create;\n List1.Add(3);\n Stack2:= TStack<Integer>.Create(List1);\n Writeln(Stack2.Pop); // 3\n List1.free;\n Stack2.free;\n\n // Inline TStack can be created in routine scope\n // only for version after 10.3 Tokyo\n var Stack3:= TStack<Integer>.Create;\n Stack3.free;\nend;\n", "language": "Delphi" }, { "code": "var\n Str1:String; // default WideString\n Str2:WideString;\n Str3:UnicodeString;\n Str4:AnsiString;\n Str5: PChar; //PWideChar is the same\n Str6: PAnsiChar;\n\n // Strings can be initialized, if it's global variable in declaration scope\n Str4: string = 'orange';\nbegin\n Str1 := 'apple';\n\n // WideString and AnsiString can be converted implicitly, but in some times can lost information about char\n Str4 := Str1;\n\n // PChar is a poiter to string (WideString), must be converted using type cast\n Str5 := Pchar(Str1);\n\n // PChar not must type cast to convert back string\n Str2 := Str5;\n\n //In any string, index start in 1 and end on length of string\n Writeln(Str1[1]); // 'a'\n Writeln(Str1[5]); // 'e'\n Writeln(Str1[length(str1)]); // the same above\nend;\n", "language": "Delphi" }, { "code": "use_namespace(rosettacode)_me();\n\n// Real world collections\nwith_route(wp1-wp2)_scalar(wp1wp2Distance)_distan({m},32); // simple distance scalar\n\n// Three dimensional vector (displacement - orientation (via quaternion) - energy consumption)\nwith_route(from-wp1-to-wp2)_vector(wp1Towp2Displacement)_distan({m},32)_orientatout(0.98,0.174i,0.044j,0.087k)_ergconsump({kJ},35.483);\n\nwith_robot(alif)_sensor(frontCamera)_type(camera_3d);\nwith_robot(alif)_abilit(frontalVision)_of[frontCamera]; // ability (1-dimensional)\nwith_robot(alif)_sensor(rearCamera)_type(camera_3d);\nwith_robot(alif)_spec(vision)_of([frontCamera],[rearCamera]); // specification (2-dimensional)\n\n// Inventory of wheels of robot 'alif'\nwith_robot(alif)_invent(wheels)_compon(frontLeftWheel, frontRightWheel, rearLeftWheel, rearRightWheel)_type(wheel);\n\n// Non-fungible token (blockchained) of robot photo (default ledger)\nwith_robot(beh)_camera(frontCamera)_snap(74827222-32232-22)\n add_nft()_[]_chain(block);\n;\n\n// Non-fungible token (crosschained) of robot photo (default ledger)\nwith_robot(beh)_camera(frontCamera)_snap(74827222-32232-42)\n add_nft()_[]_chain(cross);\n;\n\nreset_ns[];\n", "language": "Diego" }, { "code": "use_namespace(rosettacode)_me();\n\n// Abstract world collections\nadd_var({int},wp1wp2Distance)_value(32); // variable\nadd_stack({int},intStack)_values(1,2,3,6,7,9); // stack\nadd_queue({double},intStack)_values(0.03,0.04,0.05,0.06,0.07,0.08); // queue\nadd_ary({str},citrusFruit)_values(lime,orange,lemon); // array\nadd_matrix()_subs(4,4)_identity(); // simple identity matrix\n\n// rotation matrix\nadd_matrix(wp1Towp2DisplacementRotationMatrix)_row(0.981,-0.155,0.116)_row(0.186,0.924,-0.333)_row(-0.055,0.349,0.936);\n\nadd_clump()_subs(5,3,2,1); // simple clump (zero'ed)\n\n// list (of robots) from abstract robot objects\nadd_list({robot},robots)_values([alif],[bah],[tah],[thah],[jim]);\n\n// list (of robots) from SQL query\nadd_list({robot},robots)_sql(SELECT id, name, type FROM tbl_robot)_as(dba_admin);\n\n// dictionary\nadd_dict(tanzanianBanknoteWidths)_keys(500,1000,2000,5000,10000)_values(120,125,130,135,140);\n\n// hash of two images loaded from URIs\nadd_hash()_ary()_values()_img()_load(/img_027454322.jpg)_img()_load(/img_027454323.jpg);\n\nreset_ns[];\n", "language": "Diego" }, { "code": "? def constList := [1,2,3,4,5]\n# value: [1, 2, 3, 4, 5]\n\n? constList.with(6)\n# value: [1, 2, 3, 4, 5, 6]\n\n? def flexList := constList.diverge()\n# value: [1, 2, 3, 4, 5].diverge()\n\n? flexList.push(6)\n? flexList\n# value: [1, 2, 3, 4, 5, 6].diverge()\n\n? constList\n# value: [1, 2, 3, 4, 5]\n\n? def constMap := [1 => 2, 3 => 4]\n# value: [1 => 2, 3 => 4]\n\n? constMap[1]\n# value: 2\n\n? def constSet := [1, 2, 3, 2].asSet()\n# value: [1, 2, 3].asSet()\n\n? constSet.contains(3)\n# value: true\n", "language": "E" }, { "code": "array[] &= 1\narray[] &= 2\narray[] &= 3\narrayArray[][] &= [ 1 2 ]\narrayArray[][] &= [ 3 4 ]\narrayArray[][] &= [ 5 6 ]\nprint array[]\nprint arrayArray[][]\n", "language": "EasyLang" }, { "code": "(define my-collection ' ( 🌱 ☀️ ☔️ ))\n(set! my-collection (cons '🎥 my-collection))\n(set! my-collection (cons '🐧 my-collection))\nmy-collection\n → (🐧 🎥 🌱 ☀️ ☔️)\n\n;; save it\n(local-put 'my-collection)\n → my-collection\n", "language": "EchoLisp" }, { "code": "// Weak array\nvar stringArr := Array.allocate(5);\nstringArr[0] := \"string\";\n\n// initialized array\nvar intArray := new int[]{1, 2, 3, 4, 5};\n", "language": "Elena" }, { "code": "//Create and initialize ArrayList\nvar myAl := new system'collections'ArrayList().append(\"Hello\").append(\"World\").append(\"!\");\n\n//Create and initialize List\nvar myList := new system'collections'List().append(\"Hello\").append(\"World\").append(\"!\");\n", "language": "Elena" }, { "code": "//Create a dictionary\nvar dict := system'collections'Dictionary.new();\ndict[\"Hello\"] := \"World\";\ndict[\"Key\"] := \"Value\";\n", "language": "Elena" }, { "code": "empty_list = []\nlist = [1,2,3,4,5]\nlength(list) #=> 5\n[0 | list] #=> [0,1,2,3,4,5]\nhd(list) #=> 1\ntl(list) #=> [2,3,4,5]\nEnum.at(list,3) #=> 4\nlist ++ [6,7] #=> [1,2,3,4,5,6,7]\nlist -- [4,2] #=> [1,3,5]\n", "language": "Elixir" }, { "code": "empty_tuple = {} #=> {}\ntuple = {0,1,2,3,4} #=> {0, 1, 2, 3, 4}\ntuple_size(tuple) #=> 5\nelem(tuple, 2) #=> 2\nput_elem(tuple,3,:atom) #=> {0, 1, 2, :atom, 4}\n", "language": "Elixir" }, { "code": "list = [{:a,1},{:b,2}] #=> [a: 1, b: 2]\nlist == [a: 1, b: 2] #=> true\nlist[:a] #=> 1\nlist ++ [c: 3, a: 5] #=> [a: 1, b: 2, c: 3, a: 5]\n", "language": "Elixir" }, { "code": "empty_map = Map.new #=> %{}\nkwlist = [x: 1, y: 2] # Key Word List\nMap.new(kwlist) #=> %{x: 1, y: 2}\nMap.new([{1,\"A\"}, {2,\"B\"}]) #=> %{1 => \"A\", 2 => \"B\"}\nmap = %{:a => 1, 2 => :b} #=> %{2 => :b, :a => 1}\nmap[:a] #=> 1\nmap[2] #=> :b\n\n# If you pass duplicate keys when creating a map, the last one wins:\n%{1 => 1, 1 => 2} #=> %{1 => 2}\n\n# When all the keys in a map are atoms, you can use the keyword syntax for convenience:\nmap = %{:a => 1, :b => 2} #=> %{a: 1, b: 2}\nmap.a #=> 1\n%{map | :a => 2} #=> %{a: 2, b: 2} update only\n", "language": "Elixir" }, { "code": "empty_set = MapSet.new #=> #MapSet<[]>\nset1 = MapSet.new(1..4) #=> #MapSet<[1, 2, 3, 4]>\nMapSet.size(set1) #=> 4\nMapSet.member?(set1,3) #=> true\nMapSet.put(set1,9) #=> #MapSet<[1, 2, 3, 4, 9]>\nset2 = MapSet.new([6,4,2,0]) #=> #MapSet<[0, 2, 4, 6]>\nMapSet.union(set1,set2) #=> #MapSet<[0, 1, 2, 3, 4, 6]>\nMapSet.intersection(set1,set2) #=> #MapSet<[2, 4]>\nMapSet.difference(set1,set2) #=> #MapSet<[1, 3]>\nMapSet.subset?(set1,set2) #=> false\n", "language": "Elixir" }, { "code": "defmodule User do\n defstruct name: \"john\", age: 27\nend\njohn = %User{} #=> %User{age: 27, name: \"john\"}\njohn.name #=> \"john\"\n%User{age: age} = john # pattern matching\nage #=> 27\nmeg = %User{name: \"meg\"} #=> %User{age: 27, name: \"meg\"}\nis_map(meg) #=> true\n", "language": "Elixir" }, { "code": "USING: assocs deques dlists lists lists.lazy sequences sets ;\n\n! ===fixed-size sequences===\n{ 1 2 \"foo\" 3 } ! array\n[ 1 2 3 + * ] ! quotation\n\"Hello, world!\" ! string\nB{ 1 2 3 } ! byte array\n?{ f t t } ! bit array\n\n! Add an element to a fixed-size sequence\n{ 1 2 3 } 4 suffix ! { 1 2 3 4 }\n\n! Append a sequence to a fixed-size sequence\n{ 1 2 3 } { 4 5 6 } append ! { 1 2 3 4 5 6 }\n\n! Sequences are sets\n{ 1 1 2 3 } { 2 5 7 8 } intersect ! { 2 }\n\n! Strings are just arrays of code points\n\"Hello\" { } like ! { 72 101 108 108 111 }\n{ 72 101 108 108 111 } \"\" like ! \"Hello\"\n\n! ===resizable sequences===\nV{ 1 2 \"foo\" 3 } ! vector\nBV{ 1 2 255 } ! byte vector\nSBUF\" Hello, world!\" ! string buffer\n\n! Add an element to a resizable sequence by mutation\nV{ 1 2 3 } 4 suffix! ! V{ 1 2 3 4 }\n\n! Append a sequence to a resizable sequence by mutation\nV{ 1 2 3 } { 4 5 6 } append! ! V{ 1 2 3 4 5 6 }\n\n! Sequences are stacks\nV{ 1 2 3 } pop ! 3\n\n! ===associative mappings===\n{ { \"hamburger\" 150 } { \"soda\" 99 } { \"fries\" 99 } } ! alist\nH{ { 1 \"a\" } { 2 \"b\" } } ! hash table\n\n! Add a key-value pair to an assoc\n3 \"c\" H{ { 1 \"a\" } { 2 \"b\" } } [ set-at ] keep\n! H{ { 1 \"a\" } { 2 \"b\" } { \"c\" 3 } }\n\n! ===linked lists===\nT{ cons-state f 1 +nil+ } ! literal list syntax\nT{ cons-state { car 1 } { cdr +nil+ } } ! literal list syntax\n ! with car 1 and cdr nil\n\n! One method of manually constructing a list\n1 2 3 4 +nil+ cons cons cons cons\n\n1 2 2list ! convenience word for list construction\n ! T{ cons-state\n ! { car 1 }\n ! { cdr T{ cons-state { car 2 } { cdr +nil+ } } }\n ! }\n\n{ 1 2 3 4 } sequence>list ! make a list from a sequence\n\n0 lfrom ! a lazy list from 0 to infinity\n0 [ 2 + ] lfrom-by ! a lazy list of all even numbers >= 0.\n\nDL{ 1 2 3 } ! double linked list / deque\n3 DL{ 1 2 } [ push-front ] keep ! DL{ 3 1 2 }\n3 DL{ 1 2 } [ push-back ] keep ! DL{ 1 2 3 }\n\n! Factor also comes with disjoint sets, interval maps, heaps,\n! boxes, directed graphs, locked I/O buffers, trees, and more!\n", "language": "Factor" }, { "code": "# creating an empty array and adding values\n\na = [] # => []\na[0]: 1 # => [1]\na[3]: 2 # => [1, nil, nil, 2]\n\n# creating an array with the constructor\na = Array new # => []\n", "language": "Fancy" }, { "code": "# creating an empty hash\n\nh = <[]> # => <[]>\nh[\"a\"]: 1 # => <[\"a\" => 1]>\nh[\"test\"]: 2.4 # => <[\"a\" => 1, \"test\" => 2.4]>\nh[3]: \"Hello\" # => <[\"a\" => 1, \"test\" => 2.4, 3 => \"Hello\"]>\n\n# creating a hash with the constructor\nh = Hash new # => <[]>\n", "language": "Fancy" }, { "code": "include ffl/car.fs\n\n10 car-create ar \\ create a dynamic array with initial size 10\n\n2 0 ar car-set \\ ar[0] = 2\n3 1 ar car-set \\ ar[1] = 3\n1 0 ar car-insert \\ ar[0] = 1 ar[1] = 2 ar[2] = 3\n", "language": "Forth" }, { "code": "include ffl/dcl.fs\n\ndcl-create dl \\ create a double linked list\n\n3 dl dcl-append\n1 dl dcl-prepend\n2 1 dl dcl-insert \\ dl[0] = 1 dl[1] = 2 dl[2] = 3\n", "language": "Forth" }, { "code": "include ffl/hct.fs\n\n10 hct-create ht \\ create a hashtable with initial size 10\n\n1 s\" one\" ht hct-insert \\ ht[\"one\"] = 1\n2 s\" two\" ht hct-insert \\ ht[\"two\"] = 2\n3 s\" three\" ht hct-insert \\ ht[\"three\"] = 3\n", "language": "Forth" }, { "code": " REAL A(36) !Declares a one-dimensional array A(1), A(2), ... A(36)\n A(1) = 1 !Assigns a value to the first element.\n A(2) = 3*A(1) + 5 !The second element gets 8.\n", "language": "Fortran" }, { "code": " TYPE(MIXED) !Name the \"type\".\n INTEGER COUNTER !Its content is listed.\n REAL WEIGHT,DEPTH\n CHARACTER*28 MARKNAME\n COMPLEX PATH(6) !The mixed collection includes an array.\n END TYPE MIXED\n TYPE(MIXED) TEMP,A(6) !Declare some items of that type.\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\n'create fixed size array of integers\nDim a(1 To 5) As Integer = {1, 2, 3, 4, 5}\nPrint a(2), a(4)\n\n'create empty dynamic array of doubles\nDim b() As Double\n' add two elements by first redimensioning the array to hold this number of elements\nRedim b(0 To 1)\nb(0) = 3.5 : b(1) = 7.1\nPrint b(0), b(1)\n\n'create 2 dimensional fixed size array of bytes\nDim c(1 To 2, 1 To 2) As Byte = {{1, 2}, {3, 4}}\nPrint c(1, 1), c(2,2)\nSleep\n", "language": "FreeBASIC" }, { "code": "include \"NSLog.incl\"\n\nvoid local fn Array\n CFArrayRef array = @[@\"Alpha\",@\"Bravo\",@\"Charlie\",@\"Delta\"]\n NSLog(@\"Array:%@\\n\",array)\nend fn\n\nvoid local fn Dictionary\n CFDictionaryRef dict = @{@\"Key1\":@\"Value1\",@\"Key2\":@\"Value2\",@\"Key3\":@\"Value3\"}\n NSLog(@\"Dictionary:%@\\n\",dict)\nend fn\n\nvoid local fn Set\n CFSetRef set = fn SetWithArray( @[@\"Echo\",@\"Echo\",@\"FutureBasic\",@\"Golf\",@\"Hotel\",@\"India\"] )\n NSLog(@\"Set:%@\\n\",set)\nend fn\n\nvoid local fn IndexPath\n long indexes(3)\n indexes(0) = 1 : indexes(1) = 4 : indexes(2) = 3 : indexes(3) = 2\n IndexPathRef indexPath = fn IndexPathWithIndexes( @indexes(0), 4 )\n NSLog(@\"IndexPath:%@\\n\",indexPath)\nend fn\n\nvoid local fn IndexSet\n IndexSetRef indexSet = fn IndexSetWithIndexesInRange( fn CFRangeMake( 12, 5 ) )\n NSLog(@\"IndexSet:%@\\n\",indexSet)\nend fn\n\nvoid local fn CountedSet\n CountedSetRef countedSet = fn CountedSetWithArray( @[@\"Juliet\",@\"Lima\",@\"Mike\",@\"Lima\",@\"Kilo\",@\"Lima\",@\"Juliet\",@\"Mike\",@\"Lima\"] )\n NSLog(@\"CountedSet:%@\\n\",countedSet)\nend fn\n\nvoid local fn OrderedSet\n OrderedSetRef orderedSet = fn OrderedSetWithObjects( @\"November\", @\"Oscar\", @\"Papa\", NULL )\n NSLog(@\"OrderedSet:%@\\n\",orderedSet)\nend fn\n\nfn Array\nfn Dictionary\nfn Set\nfn IndexPath\nfn IndexSet\nfn CountedSet\nfn OrderedSet\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\nDim siCount As Short\nDim cCollection As Collection = [\"0\": \"zero\", \"1\": \"one\", \"2\": \"two\", \"3\": \"three\", \"4\": \"four\",\n \"5\": \"five\", \"6\": \"six\", \"7\": \"seven\", \"8\": \"eight\", \"9\": \"nine\"]\n\nFor siCount = 0 To 9\n Print cCollection[Str(siCount)]\nNext\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var a []interface{}\n a = append(a, 3)\n a = append(a, \"apples\", \"oranges\")\n fmt.Println(a)\n}\n", "language": "Go" }, { "code": "def emptyList = []\nassert emptyList.isEmpty() : \"These are not the items you're looking for\"\nassert emptyList.size() == 0 : \"Empty list has size 0\"\nassert ! emptyList : \"Empty list evaluates as boolean 'false'\"\n\ndef initializedList = [ 1, \"b\", java.awt.Color.BLUE ]\nassert initializedList.size() == 3\nassert initializedList : \"Non-empty list evaluates as boolean 'true'\"\nassert initializedList[2] == java.awt.Color.BLUE : \"referencing a single element (zero-based indexing)\"\nassert initializedList[-1] == java.awt.Color.BLUE : \"referencing a single element (reverse indexing of last element)\"\n\ndef combinedList = initializedList + [ \"more stuff\", \"even more stuff\" ]\nassert combinedList.size() == 5\nassert combinedList[1..3] == [\"b\", java.awt.Color.BLUE, \"more stuff\"] : \"referencing a range of elements\"\n\ncombinedList << \"even more stuff\"\nassert combinedList.size() == 6\nassert combinedList[-1..-3] == \\\n [\"even more stuff\", \"even more stuff\", \"more stuff\"] \\\n : \"reverse referencing last 3 elements\"\nprintln ([combinedList: combinedList])\n", "language": "Groovy" }, { "code": "def emptyMap = [:]\nassert emptyMap.isEmpty() : \"These are not the items you're looking for\"\nassert emptyMap.size() == 0 : \"Empty map has size 0\"\nassert ! emptyMap : \"Empty map evaluates as boolean 'false'\"\n\ndef initializedMap = [ count: 1, initial: \"B\", eyes: java.awt.Color.BLUE ]\nassert initializedMap.size() == 3\nassert initializedMap : \"Non-empty map evaluates as boolean 'true'\"\nassert initializedMap[\"eyes\"] == java.awt.Color.BLUE : \"referencing a single element (array syntax)\"\nassert initializedMap.eyes == java.awt.Color.BLUE : \"referencing a single element (member syntax)\"\nassert initializedMap.height == null : \\\n \"references to non-existant keys generally evaluate to null (implementation dependent)\"\n\ndef combinedMap = initializedMap \\\n + [hair: java.awt.Color.BLACK, birthdate: Date.parse(\"yyyy-MM-dd\", \"1960-05-17\") ]\nassert combinedMap.size() == 5\n\ncombinedMap[\"weight\"] = 185 // array syntax\ncombinedMap.lastName = \"Smith\" // member syntax\ncombinedMap << [firstName: \"Joe\"] // entry syntax\nassert combinedMap.size() == 8\nassert combinedMap.keySet().containsAll(\n [\"lastName\", \"count\", \"eyes\", \"hair\", \"weight\", \"initial\", \"firstName\", \"birthdate\"])\nprintln ([combinedMap: combinedMap])\n", "language": "Groovy" }, { "code": "def emptySet = new HashSet()\nassert emptySet.isEmpty() : \"These are not the items you're looking for\"\nassert emptySet.size() == 0 : \"Empty set has size 0\"\nassert ! emptySet : \"Empty set evaluates as boolean 'false'\"\n\ndef initializedSet = new HashSet([ 1, \"b\", java.awt.Color.BLUE ])\nassert initializedSet.size() == 3\nassert initializedSet : \"Non-empty list evaluates as boolean 'true'\"\n//assert initializedSet[2] == java.awt.Color.BLUE // SYNTAX ERROR!!! No indexing of set elements!\n\ndef combinedSet = initializedSet + new HashSet([ \"more stuff\", \"even more stuff\" ])\nassert combinedSet.size() == 5\n\ncombinedSet << \"even more stuff\"\nassert combinedSet.size() == 5 : \"No duplicate elements allowed!\"\nprintln ([combinedSet: combinedSet])\n", "language": "Groovy" }, { "code": "[1, 2, 3, 4, 5]\n", "language": "Haskell" }, { "code": "1 : [2, 3, 4]\n", "language": "Haskell" }, { "code": "[1, 2] ++ [3, 4]\n", "language": "Haskell" }, { "code": "concat [[1, 2], [3, 4], [5, 6, 7]]\n", "language": "Haskell" }, { "code": "import Data.Array (Array, listArray, Ix, (!))\n\ntriples :: Array Int (Char, String, String)\ntriples =\n listArray (0, 11) $\n zip3\n \"鼠牛虎兔龍蛇馬羊猴鸡狗豬\" -- 生肖 shengxiao – symbolic animals\n (words \"shǔ niú hǔ tù lóng shé mǎ yáng hóu jī gǒu zhū\")\n (words \"rat ox tiger rabbit dragon snake horse goat monkey rooster dog pig\")\n\nindexedItem\n :: Ix i\n => Array i (Char, String, String) -> i -> String\nindexedItem a n =\n let (c, w, w1) = a ! n\n in c : unwords [\"\\t\", w, w1]\n\nmain :: IO ()\nmain = (putStrLn . unlines) $ indexedItem triples <$> [2, 4, 6]\n", "language": "Haskell" }, { "code": "import qualified Data.Map as M\nimport Data.Maybe (isJust)\n\nmapSample :: M.Map String Int\nmapSample =\n M.fromList\n [ (\"alpha\", 1)\n , (\"beta\", 2)\n , (\"gamma\", 3)\n , (\"delta\", 4)\n , (\"epsilon\", 5)\n , (\"zeta\", 6)\n ]\n\nmaybeValue :: String -> Maybe Int\nmaybeValue = flip M.lookup mapSample\n\nmain :: IO ()\nmain =\n print $ sequence $ filter isJust (maybeValue <$> [\"beta\", \"delta\", \"zeta\"])\n", "language": "Haskell" }, { "code": "import qualified Data.Set as S\n\nsetA :: S.Set String\nsetA = S.fromList [\"alpha\", \"beta\", \"gamma\", \"delta\", \"epsilon\"]\n\nsetB :: S.Set String\nsetB = S.fromList [\"delta\", \"epsilon\", \"zeta\", \"eta\", \"theta\"]\n\nmain :: IO ()\nmain = (print . S.toList) (S.intersection setA setB)\n", "language": "Haskell" }, { "code": "# Creation of collections:\n s := \"abccd\" # string, an ordered collection of characters, immutable\n c := 'abcd' # cset, an unordered collection of characters, immutable\n S := set() # set, an unordered collection of unique values, mutable, contents may be of any type\n T := table() # table, an associative array of values accessed via unordered keys, mutable, contents may be of any type\n L := [] # list, an ordered collection of values indexed by position 1..n or as stack/queue, mutable, contents may be of any type\n record constructorname(field1,field2,fieldetc) # record, a collection of values stored in named fields, mutable, contents may be of any type (declare outside procedures)\n R := constructorname() # record (creation)\n", "language": "Icon" }, { "code": " s ||:= \"xyz\" # concatenation\n c ++:= 'xyz' # union\n insert(S,\"abc\") # insert\n T[\"abc\"] := \"xyz\" # insert create/overwrite\n put(L,1) # put (extend), also push\n R.field1 := \"xyz\" # overwrite\n", "language": "Icon" }, { "code": " S := S ++ S2 # union of two sets or two csets\n S ++:= S2 # augmented assignment\n L := L ||| L2 # list concatenation\n L |||:= L2 # augmented assignment\n", "language": "Icon" }, { "code": " c =: 0 10 20 30 40 NB. A collection\n\n c, 50 NB. Append 50 to the collection\n0 10 20 30 40 50\n _20 _10 , c NB. Prepend _20 _10 to the collection\n_20 _10 0 10 20 30 40\n\n ,~ c NB. Self-append\n0 10 20 30 40 0 10 20 30 40\n ,:~ c NB. Duplicate\n0 10 20 30 40\n0 10 20 30 40\n\n 30 e. c NB. Is 30 in the collection?\n1\n 30 i.~c NB. Where?\n3\n 30 80 e. c NB. Don't change anything to test multiple values -- collections are native.\n1 0\n\n 2 1 4 2 { c NB. From the collection, give me items two, one, four, and two again.\n20 10 40 20\n\n |.c NB. Reverse the collection\n40 30 20 10 0\n 1+c NB. Increment the collection\n1 11 21 31 41\n c%10 NB. Decimate the collection (divide by 10)\n0 1 2 3 4\n\n {. c NB. Give me the first item\n0\n {: c NB. And the last\n40\n 3{.c NB. Give me the first 3 items\n0 10 20\n 3}.c NB. Throw away the first 3 items\n30 40\n _3{.c NB. Give me the last 3 items\n20 30 40\n _3}.c NB. (Guess)\n0 10\n\n keys_map_ =: 'one';'two';'three'\n vals_map_ =: 'alpha';'beta';'gamma'\n lookup_map_ =: a:& $: : (dyad def ' (keys i. y) { vals,x')&boxopen\n exists_map_ =: verb def 'y e. keys'&boxopen\n\n exists_map_ 'bad key'\n0\n exists_map_ 'two';'bad key'\n1 0\n\n lookup_map_ 'one'\n+-----+\n|alpha|\n+-----+\n lookup_map_ 'three';'one';'two';'one'\n+-----+-----+----+-----+\n|gamma|alpha|beta|alpha|\n+-----+-----+----+-----+\n lookup_map_ 'bad key'\n++\n||\n++\n 'some other default' lookup_map_ 'bad key'\n+------------------+\n|some other default|\n+------------------+\n 'some other default' lookup_map_ 'two';'bad key'\n+----+------------------+\n|beta|some other default|\n+----+------------------+\n\n +/ c NB. Sum of collection\n100\n */ c NB. Product of collection\n0\n\n i.5 NB. Generate the first 5 nonnegative integers\n0 1 2 3 4\n 10*i.5 NB. Looks familiar\n0 10 20 30 40\n c = 10*i.5 NB. Test each for equality\n1 1 1 1 1\n c -: 10 i.5 NB. Test for identicality\n1\n", "language": "J" }, { "code": "fn main() {\n mut array: [String] = []\n array.push(\"Apple\")\n array.push(\"Banana\")\n println(\"{}\", array)\n}\n", "language": "Jakt" }, { "code": "fn main() {\n mut set: {String} = {}\n set.add(\"Apple\")\n set.add(\"Banana\")\n println(\"{}\", set)\n}\n", "language": "Jakt" }, { "code": "fn main() {\n mut dictionary: [i64:String] = [:]\n dictionary[1] = \"Apple\"\n dictionary[2] = \"Banana\"\n println(\"{}\", dictionary)\n}\n", "language": "Jakt" }, { "code": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n// alternative with primitive autoboxed to an Integer object automatically\narrayList.add(0);\n\n//other features of ArrayList\n//define the type in the arraylist, you can substitute a proprietary class in the \"<>\"\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n//add several values to the arraylist to be summed later\nint sum;\nfor(int i = 0; i < 10; i++) {\n myarrlist.add(i);\n}\n", "language": "Java" }, { "code": "//loop through myarrlist to sum each entry\nfor ( i = 0; i < myarrlist.size(); i++) {\n sum += myarrlist.get(i);\n}\n", "language": "Java" }, { "code": "for(int i : myarrlist) {\n sum += i;\n}\n", "language": "Java" }, { "code": "//remove the last entry in the ArrayList\nmyarrlist.remove(myarrlist.size()-1)\n\n//clear the ArrayList\nmyarrlist.clear();\n", "language": "Java" }, { "code": "import scala.Tuple2;\nimport scala.collection.concurrent.TrieMap;\nimport scala.collection.immutable.HashSet;\nimport scala.collection.mutable.ArrayBuffer;\n\npublic class Collections {\n\n\tpublic static void main(String[] args) {\n\t\tArrayBuffer<Integer> myarrlist = new ArrayBuffer<Integer>();\n\t\tArrayBuffer<Integer> myarrlist2 = new ArrayBuffer<Integer>(20);\n\n\t\tmyarrlist.$plus$eq(new Integer(42)); // $plus$eq is Scala += operator\n\t\tmyarrlist.$plus$eq(13); // to add an element.\n\t\tmyarrlist.$plus$eq(-1);\n\n\t\tmyarrlist2 = (ArrayBuffer<Integer>) myarrlist2.$minus(-1);\n\n\t\tfor (int i = 0; i < 10; i++)\n\t\t\tmyarrlist2.$plus$eq(i);\n\n\t\t// loop through myarrlist to sum each entry\n\t\tint sum = 0;\n\t\tfor (int i = 0; i < myarrlist2.size(); i++) {\n\t\t\tsum += myarrlist2.apply(i);\n\t\t}\n\t\tSystem.out.println(\"List is: \" + myarrlist2 + \" with head: \"\n\t\t\t\t+ myarrlist2.head() + \" sum is: \" + sum);\n\t\tSystem.out.println(\"Third element is: \" + myarrlist2.apply$mcII$sp(2));\n\n\t\tTuple2<String, String> tuple = new Tuple2<String, String>(\"US\",\n\t\t\t\t\"Washington\");\n\t\tSystem.out.println(\"Tuple2 is : \" + tuple);\n\n\t\tArrayBuffer<Tuple2<String, String>> capList = new ArrayBuffer<Tuple2<String, String>>();\n\t\tcapList.$plus$eq(new Tuple2<String, String>(\"US\", \"Washington\"));\n\t\tcapList.$plus$eq(new Tuple2<String, String>(\"France\", \"Paris\"));\n\t\tSystem.out.println(capList);\n\n\t\tTrieMap<String, String> trieMap = new TrieMap<String, String>();\n\t\ttrieMap.put(\"US\", \"Washington\");\n\t\ttrieMap.put(\"France\", \"Paris\");\n\n\t\tHashSet<Character> set = new HashSet<Character>();\n\n\t\tArrayBuffer<Tuple2<String, String>> capBuffer = new ArrayBuffer<Tuple2<String, String>>();\n\t\ttrieMap.put(\"US\", \"Washington\");\n\n\t\tSystem.out.println(trieMap);\n\t}\n}\n", "language": "Java" }, { "code": "var array = [];\narray.push('abc');\narray.push(123);\narray.push(new MyClass);\nconsole.log( array[2] );\n", "language": "JavaScript" }, { "code": "var obj = {};\nobj['foo'] = 'xyz'; //equivalent to: obj.foo = 'xyz';\nobj['bar'] = new MyClass; //equivalent to: obj.bar = new MyClass;\nobj['1x; ~~:-b'] = 'text'; //no equivalent\nconsole.log(obj['1x; ~~:-b']);\n", "language": "JavaScript" }, { "code": "{\"a\": 1} == {a: 1}\n", "language": "Jq" }, { "code": "\"a\" as $key | 1 as $value | {($key): $value}\n", "language": "Jq" }, { "code": "[0,1,2] | .[0] = 10\n", "language": "Jq" }, { "code": "julia> collection = []\n0-element Array{Any,1}\n\njulia> push!(collection, 1,2,4,7)\n4-element Array{Any,1}:\n 1\n 2\n 4\n 7\n", "language": "Julia" }, { "code": "import java.util.PriorityQueue\n\nfun main(args: Array<String>) {\n // generic array\n val ga = arrayOf(1, 2, 3)\n println(ga.joinToString(prefix = \"[\", postfix = \"]\"))\n\n // specialized array (one for each primitive type)\n val da = doubleArrayOf(4.0, 5.0, 6.0)\n println(da.joinToString(prefix = \"[\", postfix = \"]\"))\n\n // immutable list\n val li = listOf<Byte>(7, 8, 9)\n println(li)\n\n // mutable list\n val ml = mutableListOf<Short>()\n ml.add(10); ml.add(11); ml.add(12)\n println(ml)\n\n // immutable map\n val hm = mapOf('a' to 97, 'b' to 98, 'c' to 99)\n println(hm)\n\n // mutable map\n val mm = mutableMapOf<Char, Int>()\n mm.put('d', 100); mm.put('e', 101); mm.put('f', 102)\n println(mm)\n\n // immutable set (duplicates not allowed)\n val se = setOf(1, 2, 3)\n println(se)\n\n // mutable set (duplicates not allowed)\n val ms = mutableSetOf<Long>()\n ms.add(4L); ms.add(5L); ms.add(6L)\n println(ms)\n\n // priority queue (imported from Java)\n val pq = PriorityQueue<String>()\n pq.add(\"First\"); pq.add(\"Second\"); pq.add(\"Third\")\n println(pq)\n}\n", "language": "Kotlin" }, { "code": "-- list stuff\nl = [1, 2]\nl.add(3)\nl.add(4)\nput l\n-- [1, 2, 3, 4]\n\n-- property list stuff\npl = [#foo: 1, #bar: 2]\npl[#foobar] = 3\npl[\"barfoo\"] = 4\nput pl\n-- [#foo: 1, #bar: 2, #foobar: 3, \"barfoo\": 4]\n", "language": "Lingo" }, { "code": "+ vector : ARRAY[INTEGER];\nvector := ARRAY[INTEGER].create_with_capacity 32 lower 0;\nvector.add_last 1;\nvector.add_last 2;\n", "language": "Lisaac" }, { "code": "+ set : HASHED_SET[INTEGER];\nset := HASHED_SET[INTEGER].create;\nset.add 1;\nset.add 2;\n", "language": "Lisaac" }, { "code": "+ list : LINKED_LIST[INTEGER];\nlist := LINKED_LIST[INTEGER].create;\nlist.add_last 1;\nlist.add_last 2;\n", "language": "Lisaac" }, { "code": "+ dict : HASHED_DICTIONARY[INTEGER/*value*/, STRING_CONSTANT/*key*/];\ndict := HASHED_DICTIONARY[INTEGER, STRING_CONSTANT].create;\ndict.put 1 to \"one\";\ndict.put 2 to \"two\";\n", "language": "Lisaac" }, { "code": "collection = {0, '1'}\nprint(collection[1]) -- prints 0\n\ncollection = {[\"foo\"] = 0, [\"bar\"] = '1'} -- a collection of key/value pairs\nprint(collection[\"foo\"]) -- prints 0\nprint(collection.foo) -- syntactic sugar, also prints 0\n\ncollection = {0, '1', [\"foo\"] = 0, [\"bar\"] = '1'}\n", "language": "Lua" }, { "code": "Module Arr {\n \\\\ array as tuple\n A=(1,2,3,4,5)\n Print Array(A,0)=1\n Print A\n \\\\ add two arrays\n A=Cons(A, (6,))\n Print Len(A)=6\n Print A\n \\\\ arrays may have arrays, inventories, stacks as items\n A=((1,2,3),(4,5,6))\n Print Array(Array(A, 0),2)=3\n}\nArr\n", "language": "M2000-Interpreter" }, { "code": "Module CheckStack {\n \\\\ ordered collection: Stack\n \\\\ we can add values to top or bottom,\n \\\\ we can move values to and from top\n A=Stack:=100,300,600,800,900\n Print StackItem(A, 2)=300, Len(A)=5\n Stack A {\n \\\\ push to bottom (or end)\n Data 2000, 4000\n }\n Print StackItem(A, 7)=4000, Len(A)=7\n Stack A {\n \\\\ pop from top\n Read X, Y\n Print X=100, Y=300\n }\n Print StackItem(A,5)=4000, Len(A)=5\n Stack A {\n \\\\ push to top\n Push 2, 1\n Stack ' display stack items\n }\n \\\\ we can make a new stack merging other stacks\n A=Stack(A, stack:=5000,6000,7000)\n Print Len(A)=10\n Stack A {\n Shift 1,-Len(A) ' Reverse order\n Stack ' Display\n }\n Stack A {Drop 8}\n Print Len(A)=2\n Flush ' empty current stack\n Stack A ' dump A to current stack\n Print Stack.Size=2, Len(A)=0\n}\nCheckStack\n", "language": "M2000-Interpreter" }, { "code": "Module Maps {\n \\\\ Inventory as pairs of keys/values\n \\\\ keys has to be unique\n \\\\ Empty string \"\" can be used as key\n \\\\ Search, Add and Delete in O(1)\n \\\\ if we use delete we lost the order\n \\\\ keys can be numbers or strings, either can exist in same inventory. Values can be anything (including objects)\n \\\\ 0 can be used for string\n \\\\ Keys must be unique\n \\\\ a variable which hold an inventory is a pointer type\n Inventory A=10:=\"A\",20:=\"B\",40:=\"C\"\n Print A$(10)=\"A\", A$(\"20\")=\"B\"\n \\\\ split search from retrieval, using key one time\n If Exist(A,40) Then Print Eval$(A)=\"C\"\n k=Each(A)\n While k {\n \\\\ print keys as strings and values\n Print Eval$(k, k^), Eval$(k)\n }\n \\\\ We can use Sort to sort as numbers or text\n Append A, 5:=\"First\"\n Sort A as number\n \\\\ Print can print an inventory using columns\n Print A ' First A B C\n Sort A as text\n Print A ' A B C First\n}\nMaps\n", "language": "M2000-Interpreter" }, { "code": "Module Sets {\n \\\\ Inventory as set of keys\n \\\\ keys has to be unique\n \\\\ Empty string \"\" can be used as key\n \\\\ Search, Add and Delete in O(1)\n \\\\ if we use delete we lost the order\n \\\\ keys can be numbers or strings, either can exist in same inventory\n \\\\ 0 can be used for string\n \\\\ Keys must be unique\n \\\\ a variable which hold an inventory is a pointer type\n Inventory A=10,20,40\n If Exist(A,20) Then Print Eval(A)=20\n k=Each(A)\n While k {\n \\\\ print keys as strings and value same as key (as number here)\n Print Eval$(k, k^), Eval(k)\n }\n \\\\ sort is a Quick sort\n Sort Descending A as number\n Print A ' 40 20 10\n \\\\ For no unique keys\n \\\\ we can't delete from anywhere.\n \\\\ we can drop some keys from the end only\n \\\\ Exist() move internal index to last of the same key\n \\\\ we can give values also (make it as Map)\n Inventory Queue B=1,1,1,2,2,6,10\n Drop B 3\n Print B ' prints 1 1 1 2\n \\\\ sort is an insertion sort (stable)\n}\nSets\n", "language": "M2000-Interpreter" }, { "code": "Module GetC {\n declare c collection\n def decimal aDecimal=3000032131231231312312\n Document doc$\n Print type$(c)\n \\\\ we get an inventory list of all methods/properties of a com Object\n m=param(c)\n IF LEN(m)>1 THEN {\n For i=0 to len(m)-1\n \\\\ use index, not key so i! is index\n Doc$=m$(i!)+{\n } ' we use this block for new line\n Next i\n }\n Report Doc$\n Clipboard Doc$\n \\\\ so now we have to use it, using Methid to call Add\n Method c, \"Add\", 100, \"Hello\"\n Method c, \"Add\", 2000, \"There\"\n \\\\ add a decimal number\n\n Method c, \"Add\", aDecimal, \"Zero\"\n Method c, \"count\" as count\n Print count =3 ' we have three members\n Method C, \"_NewEnum\" as Item\n Method c, \"Item\", \"Zero\" as ZeroItem ' we get the decimal number\n Print ZeroItem\n Print type$(Item)=\"Nothing\" ' we have numbers\n k=0\n While Item {\n k++\n print k, eval(item)\n }\n c.item=lambda c (akey$) ->{\n try ok {\n method c, \"item\", akey$ as ret\n }\n If type$(Ret)=\"Empty\" Then Error \"Key not used\"\n =ret\n }\n Print c.item(\"Hello\")\n Try {\n val=c.item(\"Hello12\")\n }\n Print Error$\n Push c\n}\nGetC\nRead a\nPrint type$(a)=\"Collection\" ' if we don't declare\n", "language": "M2000-Interpreter" }, { "code": "L1 := [3, 4, 5, 6];\n L1 := [3, 4, 5, 6]\n\nL2 := [7, 8, 9];\n L2 := [7, 8, 9]\n", "language": "Maple" }, { "code": "[op(L1), op(L2)]\n [3, 4, 5, 6, 7, 8, 9]\n", "language": "Maple" }, { "code": "A1 := Array([3, 4, 5, 6]);\n A1 := [3, 4, 5, 6]\n", "language": "Maple" }, { "code": "ArrayTools:-Append(A1, 7);\n A1 := [3, 4, 5, 6, 7]\n", "language": "Maple" }, { "code": "Lst = {3, 4, 5, 6}\n->{3, 4, 5, 6}\n\nPrependTo[ Lst, 2]\n->{2, 3, 4, 5, 6}\nPrependTo[ Lst, 1]\n->{1, 2, 3, 4, 5, 6}\n\nLst\n->{1, 2, 3, 4, 5, 6}\n\nInsert[ Lst, X, 4]\n->{1, 2, 3, X, 4, 5, 6}\n", "language": "Mathematica" }, { "code": ">> A = {2,'TPS Report'} %Declare cell-array and initialize\n\nA =\n\n [2] 'TPS Report'\n\n>> A{2} = struct('make','honda','year',2003)\n\nA =\n\n [2] [1x1 struct]\n\n>> A{3} = {3,'HOVA'} %Create and assign A{3}\n\nA =\n\n [2] [1x1 struct] {1x2 cell}\n\n>> A{2} %Get A{2}\n\nans =\n\n make: 'honda'\n year: 2003\n", "language": "MATLAB" }, { "code": "seq = [0, \"foo\", pi]\nseq.push 42\nseq = seq + [1, 2, 3]\nprint seq\n", "language": "MiniScript" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\nmyVals = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]\nmySet = Set\nmySet = HashSet()\n\nloop val over myVals\n mySet.add(val)\n end val\n\nloop val over mySet\n say val\n end val\n\nreturn\n", "language": "NetRexx" }, { "code": "var a = [1,2,3,4,5,6,7,8,9]\nvar b: array[128, int]\nb[9] = 10\nb[0..8] = a\nvar c: array['a'..'d', float] = [1.0, 1.1, 1.2, 1.3]\nc['b'] = 10000\n", "language": "Nim" }, { "code": "var d = @[1,2,3,5,6,7,8,9]\nd.add(10)\nd.add([11,12,13,14])\nd[0] = 0\n\nvar e: seq[float] = @[]\ne.add(15.5)\n\nvar f = newSeq[string]()\nf.add(\"foo\")\nf.add(\"bar\")\n", "language": "Nim" }, { "code": "var g = (13, 13, 14)\ng[0] = 12\n\nvar h: tuple[key: string, val: int] = (\"foo\", 100)\n\n# A sequence of key-val tuples:\nvar i = {\"foo\": 12, \"bar\": 13}\n", "language": "Nim" }, { "code": "var j: set[char]\nj.incl('X')\n\nvar k = {'a'..'z', '0'..'9'}\n\nj = j + k\n", "language": "Nim" }, { "code": "import tables\nvar l = initTable[string, int]()\nl[\"foo\"] = 12\nl[\"bar\"] = 13\n\nvar m = {\"foo\": 12, \"bar\": 13}.toTable\nm[\"baz\"] = 14\n", "language": "Nim" }, { "code": "import sets\nvar n = initSet[string]()\nn.incl(\"foo\")\n\nvar o = [\"foo\", \"bar\", \"baz\"].toSet\no.incl(\"foobar\")\n", "language": "Nim" }, { "code": "import deques\nvar p = initDeque[int]()\np.addLast(12)\np.addFirst(13)\necho p.popFirst()\necho p.popLast()\n", "language": "Nim" }, { "code": "values := IntVector->New();\nvalues->AddBack(7);\nvalues->AddBack(3);\nvalues->AddBack(10);\n", "language": "Objeck" }, { "code": "values := IntList->New();\nvalues->AddBack(7);\nvalues->AddBack(3);\nvalues->AddBack(10);\n", "language": "Objeck" }, { "code": "values := StringHash->New();\nvalues->Insert(\"seven\", IntHolder->New(7));\nvalues->Insert(\"three\", IntHolder->New(3));\nvalues->Insert(\"ten\", IntHolder->New(10));\n", "language": "Objeck" }, { "code": "values := IntStack->New();\nvalues->Push(7);\nvalues->Push(3);\nvalues->Push(10);\n", "language": "Objeck" }, { "code": "#import <Foundation/Foundation.h>\n\nvoid show_collection(id coll)\n{\n for ( id el in coll )\n {\n if ( [coll isKindOfClass: [NSCountedSet class]] ) {\n NSLog(@\"%@ appears %lu times\", el, [coll countForObject: el]);\n } else if ( [coll isKindOfClass: [NSDictionary class]] ) {\n NSLog(@\"%@ -> %@\", el, coll[el]);\n } else {\n NSLog(@\"%@\", el);\n }\n }\n printf(\"\\n\");\n}\n\nint main()\n{\n @autoreleasepool {\n\n // create an empty set\n NSMutableSet *set = [[NSMutableSet alloc] init];\n // populate it\n [set addObject: @\"one\"];\n [set addObject: @10];\n [set addObjectsFromArray: @[@\"one\", @20, @10, @\"two\"] ];\n // let's show it\n show_collection(set);\n\n // create an empty counted set (a bag)\n NSCountedSet *cset = [[NSCountedSet alloc] init];\n // populate it\n [cset addObject: @\"one\"];\n [cset addObject: @\"one\"];\n [cset addObject: @\"two\"];\n // show it\n show_collection(cset);\n\n // create a dictionary\n NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];\n // populate it\n dict[@\"four\"] = @4;\n dict[@\"eight\"] = @8;\n // show it\n show_collection(dict);\n\n }\n return EXIT_SUCCESS;\n}\n", "language": "Objective-C" }, { "code": "[1; 2; 3; 4; 5]\n", "language": "OCaml" }, { "code": "1 :: [2; 3; 4; 5]\n", "language": "OCaml" }, { "code": "[1; 2] @ [3; 4; 5]\n", "language": "OCaml" }, { "code": "# List.flatten [[1; 2]; [3; 4]; [5; 6; 7]] ;;\n- : int list = [1; 2; 3; 4; 5; 6; 7]\n", "language": "OCaml" }, { "code": "[| 1; 2; 3; 4; 5 |]\n", "language": "OCaml" }, { "code": "[ 1, 1.2, \"abcd\", [ 1, 2, 3 ] ]\n", "language": "Oforth" }, { "code": "ListBuffer new dup add(10) dup add(\"aaa\") dup add(Date now) dup add(1.3) println\n", "language": "Oforth" }, { "code": "a = .array~new(4) -- creates an array of 4 items, with all slots empty\nsay a~size a~items -- size is 4, but there are 0 items\na[1] = \"Fred\" -- assigns a value to the first item\na[5] = \"Mike\" -- assigns a value to the fifth slot, expanding the size\nsay a~size a~items -- size is now 5, with 2 items\n", "language": "OoRexx" }, { "code": "l = .list~new -- lists have no inherent size\nindex = l~insert('123') -- adds an item to this list, returning the index\nl~insert('Fred', .nil) -- inserts this at the beginning\nl~insert('Mike') -- adds this to the end\nl~insert('Rick', index) -- inserts this after '123'\nl[index] = l[index] + 1 -- the original item is now '124'\ndo item over l -- iterate over the items, displaying them in order\n say item\nend\n", "language": "OoRexx" }, { "code": "q = .queue~of(2,4,6) -- creates a queue containing 3 items\nsay q[1] q[3] -- displays \"2 6\"\ni = q~pull -- removes the first item\nq~queue(i) -- adds it to the end\nsay q[1] q[3] -- displays \"4 2\"\nq[1] = q[1] + 1 -- updates the first item\nsay q[1] q[3] -- displays \"5 2\"\n", "language": "OoRexx" }, { "code": "t = .table~new\nt['abc'] = 1\nt['def'] = 2\nsay t['abc'] t['def'] -- displays \"1 2\"\n", "language": "OoRexx" }, { "code": "t = .table~new -- a table example to demonstrate the difference\nt['abc'] = 1 -- sets an item at index 'abc'\nt['abc'] = 2 -- updates that item\nsay t~items t['abc'] -- displays \"1 2\"\nr = .relation~new\nr['abc'] = 1 -- sets an item at index 'abc'\nr['abc'] = 2 -- adds an additional item at the same index\nsay r~items r['abc'] -- displays \"2 2\" this has two items in it now\n\ndo item over r~allAt('abc') -- retrieves all items at the index 'abc'\n say item\nend\n", "language": "OoRexx" }, { "code": "d = .directory~new\nd['abc'] = 1\nd['def'] = 2\nsay d['abc'] d['def'] -- displays \"1 2\"\n", "language": "OoRexx" }, { "code": "d = .directory~new\nd~abc = 1\nd~def = 2\nsay d~abc d~def -- displays \"1 2\"\n", "language": "OoRexx" }, { "code": "s = .set~new\ntext = \"the quick brown fox jumped over the lazy dog\"\ndo word over text~makearray(' ')\n s~put(word)\nend\n\nsay \"text has\" text~words\", but only\" s~items \"unique words\"\n", "language": "OoRexx" }, { "code": "declare\n %% Lists (immutable, recursive)\n Xs = [1 2 3 4]\n %% Add element at the front (cons)\n Xs0 = 0|Xs\n {Show {Length Xs}} %% output: 4\n\n %% Records (immutable maps with a label)\n Rec = label(1:2 symbol:3)\n {Show Rec} %% output: label(2 symbol:3)\n {Show Rec.1} %% output: 2\n %% create a new record with an added field\n Rec2 = {AdjoinAt Rec 2 value}\n {Show Rec2} %% output: label(2 value symbol:3)\n\n %% Dictionaries (mutable maps)\n Dict = {Dictionary.new}\n Dict.1 := 1\n Dict.symbol := 3\n {Show Dict.1} %% output: 1\n\n %% Arrays (mutable with integer keys)\n Arr = {Array.new 1 10 initValue}\n Arr.1 := 3\n {Show Arr.1} %% output: 3\n", "language": "Oz" }, { "code": "v = vector(0);\nv = [];\ncv = vectorv(0);\ncv = []~;\nm = matrix(1,1);\ns = Set(v);\nl = List(v);\nvs = vectorsmall(0);\nM = Map()\n", "language": "PARI-GP" }, { "code": "listput(l, \"hello world\")\nv=concat(v, [1,2,3]);\nv=concat(v, 4);\nmapput(M, \"key\", \"value\");\n", "language": "PARI-GP" }, { "code": "var\n MyArray: array[1..5] of real;\nbegin\n MyArray[1] := 4.35;\nend;\n", "language": "Pascal" }, { "code": "var\n MyArray: array of integer;\nbegin\n setlength (MyArray, 10);\n MyArray[4] := 99;\nend;\n", "language": "Pascal" }, { "code": "var\n MyRecord: record\n x, y, z: real;\n presence: boolean;\n end;\nbegin\n MyRecord.x := 0.3;\n MyRecord.y := 3.2;\n MyRecord.z := -4.0;\n MyRecord.presence := true;\nend;\n", "language": "Pascal" }, { "code": "type\n days = (Mon, Tue, Wed, Thu, Fri, Sat, Sun);\nvar\n workDays, week, weekendDays: set of days;\nbegin\n workdays := [Mon, Tue, Wed, Thu, Fri];\n week := workdays + [Sat, Sun];\n weekendDays := week - workdays;\nend;\n", "language": "Pascal" }, { "code": "var\n MyString: String;\nbegin\n MyString:= 'Some Text';\nend;\n", "language": "Pascal" }, { "code": "program ListDemo;\nuses\n classes;\nvar\n MyList: TList;\n a, b, c: integer;\n i: integer;\nbegin\n a := 1;\n b := 2;\n c := 3;\n MyList := TList.Create;\n MyList.Add(@a);\n MyList.Add(@c);\n MyList.Insert(1, @b);\n for i := MyList.IndexOf(MyList.First) to MyList.IndexOf(MyList.Last) do\n writeln (integer(MyList.Items[i]^));\n MyList.Destroy;\nend.\n", "language": "Pascal" }, { "code": "Program ex34;\n\n{ Program to demonstrate the TCollection.AtInsert method }\n\nUses Objects, MyObject; { For TMyObject definition and registration }\n\nVar C : PCollection;\n M : PMyObject;\n I : Longint;\n\nProcedure PrintField (Dummy : Pointer; P : PMyObject);\n\nbegin\n Writeln ('Field : ',P^.GetField);\nend;\n\nbegin\n Randomize;\n C:=New(PCollection, Init(120, 10));\n Writeln ('Inserting 100 records at random places.');\n For I:=1 to 100 do\n begin\n M:=New(PMyObject, Init);\n M^.SetField(I-1);\n If I=1 then\n C^.Insert(M)\n else\n With C^ do\n AtInsert(Random(Count), M);\n end;\n Writeln ('Values : ');\n C^.Foreach(@PrintField);\n Dispose(C, Done);\nend.\n", "language": "Pascal" }, { "code": "use strict;\nmy @c = (); # create an empty \"array\" collection\n\n# fill it\npush @c, 10, 11, 12;\npush @c, 65;\n# print it\nprint join(\" \",@c) . \"\\n\";\n\n# create an empty hash\nmy %h = ();\n# add some pair\n$h{'one'} = 1;\n$h{'two'} = 2;\n# print it\nforeach my $i ( keys %h ) {\n print $i . \" -> \" . $h{$i} . \"\\n\";\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">collection</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #000000;\">collection</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">collection</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"one\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">collection</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">prepend</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">collection</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span> <span style=\"color: #000000;\">collection</span> <span style=\"color: #000080;font-style:italic;\">-- {2,\"one\"}</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #7060A8;\">setd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"one\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">setd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">visitor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">key</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">object</span> <span style=\"color: #000080;font-style:italic;\">/*data*/</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">object</span> <span style=\"color: #000080;font-style:italic;\">/*user_data*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">key</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #7060A8;\">traverse_dict</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">routine_id</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"visitor\"</span><span style=\"color: #0000FF;\">))</span> <span style=\"color: #000080;font-style:italic;\">-- shows 2, \"one\"</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n", "language": "PHP" }, { "code": "go =>\n L = [1,2,3,4],\n L2 = L ++ [[5,6,7]], % adding a list\n L3 = [\"a string\"] ++ L2, % adding a string\n\n % Prolog way\n append([0],L,[5],L4).\n", "language": "Picat" }, { "code": "go2 =>\n L = {1,2,3,4},\n L2 = {0} ++ L ++ {5},\n\n % multi dimensional arrays\n M = new_array(4,4),\n bind_vars(M,0). % initialize to 0\n", "language": "Picat" }, { "code": "go3 =>\n Map = new_map(),\n Map.put(a,1),\n Map.put(b,2),\n\n % Initialize map with values\n Map2 = new_map([c=3,d=\"some value\"]).\n", "language": "Picat" }, { "code": "go4 =>\n S = new_set([1,2,3,4,5,\"picat\"]),\n S.put(1),\n S.put(21).\n", "language": "Picat" }, { "code": "go5 =>\n S = new_struct(a_struct,5),\n S[2] = 4, % place 4 at position 2\n arg(3,S,\"string\"). % place \"string\" at position 3\n", "language": "Picat" }, { "code": "go6 =>\n L = [1,3,2,4,5,3,6],\n H = new_min_heap(L),\n H.heap_push(-123).\n", "language": "Picat" }, { "code": ": (setq Lst (3 4 5 6))\n-> (3 4 5 6)\n\n: (push 'Lst 2)\n-> 2\n\n: (push 'Lst 1)\n-> 1\n\n: Lst\n-> (1 2 3 4 5 6)\n\n: (insert 4 Lst 'X)\n-> (1 2 3 X 4 5 6)\n", "language": "PicoLisp" }, { "code": " declare countries character (20) varying controlled;\n allocate countries initial ('Britain');\n allocate countries initial ('America');\n allocate countries initial ('Argentina');\n", "language": "PL-I" }, { "code": "# Create an Array by separating the elements with commas:\n$array = \"one\", 2, \"three\", 4\n\n# Using explicit syntax:\n$array = @(\"one\", 2, \"three\", 4)\n\n# Send the values back into individual variables:\n$var1, $var2, $var3, $var4 = $array\n\n# An array of several integer ([int]) values:\n$array = 0, 1, 2, 3, 4, 5, 6, 7\n\n# Using the range operator (..):\n$array = 0..7\n\n# Strongly typed:\n[int[]] $stronglyTypedArray = 1, 2, 4, 8, 16, 32, 64, 128\n\n# An empty array:\n$array = @()\n\n# An array with a single element:\n$array = @(\"one\")\n\n# I suppose this would be a jagged array:\n$jaggedArray = @((11, 12, 13),\n (21, 22, 23),\n (31, 32, 33))\n\n$jaggedArray | Format-Wide {$_} -Column 3 -Force\n\n$jaggedArray[1][1] # returns 22\n\n# A Multi-dimensional array:\n$multiArray = New-Object -TypeName \"System.Object[,]\" -ArgumentList 6,6\n\nfor ($i = 0; $i -lt 6; $i++)\n{\n for ($j = 0; $j -lt 6; $j++)\n {\n $multiArray[$i,$j] = ($i + 1) * 10 + ($j + 1)\n }\n}\n\n$multiArray | Format-Wide {$_} -Column 6 -Force\n\n$multiArray[2,2] # returns 33\n", "language": "PowerShell" }, { "code": "# An empty Hash Table:\n$hash = @{}\n\n# A Hash table populated with some values:\n$nfcCentralDivision = @{\n Packers = \"Green Bay\"\n Bears = \"Chicago\"\n Lions = \"Detroit\"\n}\n\n# Add items to a Hash Table:\n$nfcCentralDivision.Add(\"Vikings\",\"Minnesota\")\n$nfcCentralDivision.Add(\"Buccaneers\",\"Tampa Bay\")\n\n# Remove an item from a Hash Table:\n$nfcCentralDivision.Remove(\"Buccaneers\")\n\n# Searching for items\n$nfcCentralDivision.ContainsKey(\"Packers\")\n$nfcCentralDivision.ContainsValue(\"Green Bay\")\n\n# A bad value...\n$hash1 = @{\n One = 1\n Two = 3\n}\n\n# Edit an item in a Hash Table:\n$hash1.Set_Item(\"Two\",2)\n\n# Combine Hash Tables:\n\n$hash2 = @{\n Three = 3\n Four = 4\n}\n\n$hash1 + $hash2\n\n# Using the ([ordered]) accelerator the items in the Hash Table retain the order in which they were input:\n$nfcCentralDivision = [ordered]@{\n Bears = \"Chicago\"\n Lions = \"Detroit\"\n Packers = \"Green Bay\"\n Vikings = \"Minnesota\"\n}\n", "language": "PowerShell" }, { "code": "$list = New-Object -TypeName System.Collections.ArrayList -ArgumentList 1,2,3\n\n# or...\n\n$list = [System.Collections.ArrayList]@(1,2,3)\n\n\n$list.Add(4) | Out-Null\n$list.RemoveAt(2)\n", "language": "PowerShell" }, { "code": "% create a list\nL = [a,b,c,d],\n\n% prepend to the list\nL2 = [before_a|L],\n\n% append to the list\nappend(L2, ['Hello'], L3),\n\n% delete from list\nexclude(=(b), L3, L4).\n", "language": "Prolog" }, { "code": "% create an empty dict call 'point'\nD1 = point{},\n\n% add a value\t\nD2 = D1.put(x, 20).put(y, 30).put(z, 20),\n\n% update a value\nD3 = D2.put([x=25]),\n\n% remove a value\ndel_dict(z, D3, _, D4),\n\n% access a value randomly\nformat('x = ~w, y = ~w~n', [D4.x, D4.y]).\n", "language": "Prolog" }, { "code": "Dim Text.s(9)\n\nText(3)=\"Hello\"\nText(7)=\"World!\"\n", "language": "PureBasic" }, { "code": "NewList Cars.s()\n\nAddElement(Cars()): Cars()=\"Volvo\"\nAddElement(Cars()): Cars()=\"BMV\"\n", "language": "PureBasic" }, { "code": "NewMap Capitals.s()\n\nCapitals(\"USA\") = \"Washington\"\nCapitals(\"Sweden\")= \"Stockholm\"\n", "language": "PureBasic" }, { "code": "collection = [0, '1'] # Lists are mutable (editable) and can be sorted in place\nx = collection[0] # accessing an item (which happens to be a numeric 0 (zero)\ncollection.append(2) # adding something to the end of the list\ncollection.insert(0, '-1') # inserting a value into the beginning\ny = collection[0] # now returns a string of \"-1\"\ncollection.extend([2,'3']) # same as [collection.append(i) for i in [2,'3']] ... but faster\ncollection += [2,'3'] # same as previous line\ncollection[2:6] # a \"slice\" (collection of the list elements from the third up to but not including the sixth)\nlen(collection) # get the length of (number of elements in) the collection\ncollection = (0, 1) # Tuples are immutable (not editable)\ncollection[:] # ... slices work on these too; and this is equivalent to collection[0:len(collection)]\ncollection[-4:-1] # negative slices count from the end of the string\ncollection[::2] # slices can also specify a stride --- this returns all even elements of the collection\ncollection=\"some string\" # strings are treated as sequences of characters\nx = collection[::-1] # slice with negative step returns reversed sequence (string in this case).\ncollection[::2] == \"some string\"[::2] # True, literal objects don't need to be bound to name/variable to access slices or object methods\ncollection.__getitem__(slice(0,len(collection),2)) # same as previous expressions.\ncollection = {0: \"zero\", 1: \"one\"} # Dictionaries (Hash)\ncollection['zero'] = 2 # Dictionary members accessed using same syntax as list/array indexes.\ncollection = set([0, '1']) # sets (Hash)\n", "language": "Python" }, { "code": "numeric(5)\n1:10\nc(1, 3, 6, 10, 7 + 8, sqrt(441))\n", "language": "R" }, { "code": "integer(5)\nc(1L, -2L, 99L);\n", "language": "R" }, { "code": "logical(5)\nc(TRUE, FALSE)\n", "language": "R" }, { "code": "character(5)\nc(\"abc\", \"defg\", \"\")\n", "language": "R" }, { "code": "matrix(1:12, nrow=3)\n\narray(1:24, dim=c(2,3,4)) #output not shown\n", "language": "R" }, { "code": "list(a=123, b=\"abc\", TRUE, 1:5, c=list(d=runif(5), e=5+6))\n", "language": "R" }, { "code": "$a\n[1] 123\n$b\n[1] \"abc\"\n[[3]]\n[1] TRUE\n[[4]]\n[1] 1 2 3 4 5\n$c\n$c$d\n[1] 0.6013157 0.5011909 0.7106448 0.3882265 0.1274939\n$c$e\n[1] 11\n", "language": "R" }, { "code": "data.frame(name=c(\"Alice\", \"Bob\", \"Carol\"), age=c(23, 35, 17))\n", "language": "R" }, { "code": "#lang racket\n\n;; create a list\n(list 1 2 3 4)\n;; create a list of size N\n(make-list 100 0)\n;; add an element to the front of a list (non-destructively)\n(cons 1 (list 2 3 4))\n", "language": "Racket" }, { "code": "# Array\nmy @array = 1,2,3;\[email protected]: 4,5,6;\n\n# Hash\nmy %hash = 'a' => 1, 'b' => 2;\n%hash<c d> = 3,4;\n%hash.push: 'e' => 5, 'f' => 6;\n\n# SetHash\nmy $s = SetHash.new: <a b c>;\n$s ∪= <d e f>;\n\n# BagHash\nmy $b = BagHash.new: <b a k l a v a>;\n$b ⊎= <a b c>;\n", "language": "Raku" }, { "code": "# List\nmy @list := 1,2,3;\nmy @newlist := |@list, 4,5,6; # |@list will slip @list into the surrounding list instead of creating a list of lists\n\n# Set\nmy $set = set <a b c>;\nmy $newset = $set ∪ <d e f>;\n\n# Bag\nmy $bag = bag <b a k l a v a>;\nmy $newbag = $bag ⊎ <b e e f>;\n", "language": "Raku" }, { "code": "my $tail = d => e => f => Nil;\nmy $new = a => b => c => $tail;\n", "language": "Raku" }, { "code": "class Something { has $.foo; has $.bar };\nmy $obj = Something.new: foo => 1, bar => 2;\nmy $newobj = $obj but role { has $.baz = 3 } # anonymous mixin\n", "language": "Raku" }, { "code": "[ 1 2 3 'abc' ] as a_list\na_list print\n\nlist (4 items)\n 0 => 1\n 1 => 2\n 2 => 3\n 3 => \"abc\"\n", "language": "Raven" }, { "code": "{ 'a' 1 'b' 2 } as a_hash\na_hash print\n\nhash (2 items)\n a => 1\n b => 2\n", "language": "Raven" }, { "code": "17 a_list 1 set # set second item\n42 a_hash 'b' set # set item with key 'b'\n42 a_hash:b # shorthand\n", "language": "Raven" }, { "code": "a_list 1 get # get second item\na_hash 'b' get # get item with key 'b'\na_hash.b # shorthand\n", "language": "Raven" }, { "code": "42 a_list push # append an item\na_list pop # remove last item\n42 a_list shove # prepend an item\na_list shift # remove first item\n42 a_list 1 insert # insert item second, shuffling others down\na_list 1 remove # retrieve second item, shuffling others up\n", "language": "Raven" }, { "code": "pr. = /*define a default for all elements for the array*/\n\npr.1 = 2 /*note that this array starts at 1 (one). */\npr.2 = 3\npr.3 = 5\npr.4 = 7\npr.5 = 11\npr.6 = 13\npr.7 = 17\npr.8 = 19\npr.9 = 23\npr.10 = 29\npr.11 = 31\npr.12 = 37\npr.13 = 41\npr.14 = 43\npr.15 = 47\n\ny. = 0 /*define a default for all years (Y) to be zero*/\ny.1985 = 6020\ny.1986 = 7791\ny.1987 = 8244\ny.1988 = 10075\n\nx = y.2012 /*the variable X will have a value of zero (0).*/\n\nfib.0 = 0 /*this stemmed arrays will start with zero (0). */\nfib.1 = 1\nfib.2 = 1\nfib.3 = 2\nfib.4 = 3\nfib.5 = 5\nfib.6 = 8\nfib.7 = 17\n\n do n=-5 to 5 /*define a stemmed array from -5 to 5 */\n sawtooth.n = n /*the sawtooth array is, well, a sawtooth curve*/\n end /*n*/ /*note that eleven elements will be defined. */\n", "language": "REXX" }, { "code": " pr.0= 15 /*number of (data) entries in the stemmed array. */\n", "language": "REXX" }, { "code": " do j=1 while pr.j\\==''\n say 'prime' j \"is\" pr.j\n end /*j*/\n /*at this point, J=16 (because of the DO */\n /*loop incrementing the index. */\nj= j-1 /*J now has the count of primes stored. */\n", "language": "REXX" }, { "code": "primeList = '2 3 5 7 11 13 17 19 23 29 31 37 41 43' /* or ··· */\nprimeList = 2 3 5 7 11 13 17 19 23 29 31 37 41 43\n\n /*in this case, the quotes (') can be elided.*/\n\nprimes= words(primeList) /*the WORDS BIF counts the number of blank─ */\n /*separated words (in this case, prime numbers)*/\n /*in the value of the variable \"primeList\".*/\n\n do j=1 for primes /*can also be coded as: do j=1 to primes */\n say 'prime' j \"is\" word(primeList, j)\n /*this method (using the WORD BIF) isn't */\n /*very efficient for very large arrays (those */\n /*with many many thousands of elements). */\n end /*j*/\n", "language": "REXX" }, { "code": "pr. = 0 /*define a default for all elements for the array.*/\npr.2 = 1\npr.3 = 1\npr.5 = 1\npr.7 = 1\npr.11 = 1\npr.13 = 1\npr.17 = 1\npr.19 = 1\npr.23 = 1\npr.29 = 1\npr.31 = 1\npr.37 = 1\npr.41 = 1\npr.43 = 1\npr.47 = 1\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nprimes=0\n do j=1 for 10000 /*this method isn't very efficient. */\n if \\pr.j then iterate /*Not prime? Then skip this element. */\n primes = primes + 1 /*bump the number of primes (counter).*/\n end /*j*/\n /*note that the 10000 is a small \"∞\".*/\nsay '# of primes in list:' primes\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n#primes=0\n do j=1 for 10000 /*this method is not very efficient. */\n if pr.j\\==0 then #primes = #primes + 1 /*Not zero? Bump the number of primes.*/\n end /*j*/ /* [↑] not as idiomatic as 1st program*/\n\nsay '# of primes in the list:' #primes\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nPs=0\n do k=1 for 10000 /*and yet another inefficient method. */\n if pr.k==0 then iterate /*Not a prime? Then skip this element.*/\n Ps = Ps + 1 /*bump the counter for the # of primes.*/\n say 'prime' Ps \"is:\" k /*might as well echo this prime number.*/\n end /*k*/\n\nsay 'The number of primes found in the list is ' Ps\n/*──────────────────────────────────────────────────────────────────────────────────────*/\npr.0 = 47 /*hardcode the highest prime in array. */\n# = 0\n do k=2 to pr.0 /*and much more efficient method. */\n if \\pr.k then iterate /*Not a prime? Then skip this element.*/\n # = # + 1 /*bump the counter for the # of primes.*/\n say 'prime' Ps \"is:\" k /*might as well echo this prime number.*/\n end /*k*/\n\nsay 'The number of primes found in the list is: ' #\n", "language": "REXX" }, { "code": "text = list(2)\ntext[1] = \"Hello \"\ntext[2] = \"world!\"\nsee text[1] + text[2] + nl\n", "language": "Ring" }, { "code": "# creating an empty array and adding values\na = [] #=> []\na[0] = 1 #=> [1]\na[3] = \"abc\" #=> [1, nil, nil, \"abc\"]\na << 3.14 #=> [1, nil, nil, \"abc\", 3.14]\n\n# creating an array with the constructor\na = Array.new #=> []\na = Array.new(3) #=> [nil, nil, nil]\na = Array.new(3, 0) #=> [0, 0, 0]\na = Array.new(3){|i| i*2} #=> [0, 2, 4]\n", "language": "Ruby" }, { "code": "# creating an empty hash\nh = {} #=> {}\nh[\"a\"] = 1 #=> {\"a\"=>1}\nh[\"test\"] = 2.4 #=> {\"a\"=>1, \"test\"=>2.4}\nh[3] = \"Hello\" #=> {\"a\"=>1, \"test\"=>2.4, 3=>\"Hello\"}\nh = {a:1, test:2.4, World!:\"Hello\"}\n #=> {:a=>1, :test=>2.4, :World!=>\"Hello\"}\n\n# creating a hash with the constructor\nh = Hash.new #=> {} (default value : nil)\np h[1] #=> nil\nh = Hash.new(0) #=> {} (default value : 0)\np h[1] #=> 0\np h #=> {}\nh = Hash.new{|hash, key| key.to_s}\n #=> {}\np h[123] #=> \"123\"\np h #=> {}\nh = Hash.new{|hash, key| hash[key] = \"foo#{key}\"}\n #=> {}\np h[1] #=> \"foo1\"\np h #=> {1=>\"foo1\"}\n", "language": "Ruby" }, { "code": "# creating a struct\n\nPerson = Struct.new(:name, :age, :sex)\n\na = Person.new(\"Peter\", 15, :Man)\np a[0] #=> \"Peter\"\np a[:age] #=> 15\np a.sex #=> :Man\np a.to_a #=> [\"Peter\", 15, :Man]\np a.to_h #=> {:name=>\"Peter\", :age=>15, :sex=>:Man}\n\nb = Person.new\np b #=> #<struct Person name=nil, age=nil, sex=nil>\nb.name = \"Margaret\"\nb[\"age\"] = 18\nb[-1] = :Woman\np b.values #=> [\"Margaret\", 18, :Woman]\np b.members #=> [:name, :age, :sex]\np b.size #=> 3\n\nc = Person[\"Daniel\", 22, :Man]\np c.to_h #=> {:name=>\"Daniel\", :age=>22, :sex=>:Man}\n", "language": "Ruby" }, { "code": "require 'set'\n\n# different ways of creating a set\np s1 = Set[1, 2, 3, 4] #=> #<Set: {1, 2, 3, 4}>\np s2 = [8, 6, 4, 2].to_set #=> #<Set: {8, 6, 4, 2}>\np s3 = Set.new(1..4) {|x| x*2} #=> #<Set: {2, 4, 6, 8}>\n\n# Union\np s1 | s2 #=> #<Set: {1, 2, 3, 4, 8, 6}>\n# Intersection\np s1 & s2 #=> #<Set: {4, 2}>\n# Difference\np s1 - s2 #=> #<Set: {1, 3}>\n\np s1 ^ s2 #=> #<Set: {8, 6, 1, 3}>\n\np s2 == s3 #=> true\n\np s1.add(5) #=> #<Set: {1, 2, 3, 4, 5}>\np s1 << 0 #=> #<Set: {1, 2, 3, 4, 5, 0}>\np s1.delete(3) #=> #<Set: {1, 2, 4, 5, 0}>\n", "language": "Ruby" }, { "code": "require 'matrix'\n\n# creating a matrix\np m0 = Matrix.zero(3) #=> Matrix[[0, 0, 0], [0, 0, 0], [0, 0, 0]]\np m1 = Matrix.identity(3) #=> Matrix[[1, 0, 0], [0, 1, 0], [0, 0, 1]]\np m2 = Matrix[[11, 12], [21, 22]]\n #=> Matrix[[11, 12], [21, 22]]\np m3 = Matrix.build(3) {|row, col| row - col}\n #=> Matrix[[0, -1, -2], [1, 0, -1], [2, 1, 0]]\n\np m2[0,0] #=> 11\np m1 * 5 #=> Matrix[[5, 0, 0], [0, 5, 0], [0, 0, 5]]\np m1 + m3 #=> Matrix[[1, -1, -2], [1, 1, -1], [2, 1, 1]]\np m1 * m3 #=> Matrix[[0, -1, -2], [1, 0, -1], [2, 1, 0]]\n\n# creating a Vector\np v1 = Vector[1,3,5] #=> Vector[1, 3, 5]\np v2 = Vector[0,1,2] #=> Vector[0, 1, 2]\np v1[1] #=> 3\np v1 * 2 #=> Vector[2, 6, 10]\np v1 + v2 #=> Vector[1, 4, 7]\n\np m1 * v1 #=> Vector[1, 3, 5]\np m3 * v1 #=> Vector[-13, -4, 5]\n", "language": "Ruby" }, { "code": "require 'ostruct'\n\n# creating a OpenStruct\nab = OpenStruct.new\np ab #=> #<OpenStruct>\nab.foo = 25\np ab.foo #=> 25\nab[:bar] = 2\np ab[\"bar\"] #=> 2\np ab #=> #<OpenStruct foo=25, bar=2>\nab.delete_field(\"foo\")\np ab.foo #=> nil\np ab #=> #<OpenStruct bar=2>\n\np son = OpenStruct.new({ :name => \"Thomas\", :age => 3 })\n #=> #<OpenStruct name=\"Thomas\", age=3>\np son.name #=> \"Thomas\"\np son[:age] #=> 3\nson.age += 1\np son.age #=> 4\nson.items = [\"candy\",\"toy\"]\np son.items #=> [\"candy\",\"toy\"]\np son #=> #<OpenStruct name=\"Thomas\", age=4, items=[\"candy\", \"toy\"]\n", "language": "Ruby" }, { "code": "let a = [1u8,2,3,4,5]; // a is of type [u8; 5];\nlet b = [0;256] // Equivalent to `let b = [0,0,0,0,0,0... repeat 256 times]`\n", "language": "Rust" }, { "code": "let array = [1,2,3,4,5];\nlet slice = &array[0..2]\nprintln!(\"{:?}\", slice);\n", "language": "Rust" }, { "code": "let mut v = Vec::new();\nv.push(1);\nv.push(2);\nv.push(3);\n// Or (mostly) equivalently via a convenient macro in the standard library\nlet v = vec![1,2,3];\n", "language": "Rust" }, { "code": "let x = \"abc\"; // x is of type &str (a borrowed string slice)\nlet s = String::from(x);\n// or alternatively\nlet s = x.to_owned();\n", "language": "Rust" }, { "code": "Windows PowerShell\nCopyright (C) 2012 Microsoft Corporation. All rights reserved.\n\nPS C:\\Users\\FransAdm> scala\nWelcome to Scala version 2.10.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_25).\nType in expressions to have them evaluated.\nType :help for more information.\n\nscala> // Immutable collections do not and cannot change the instantiated object\n\nscala> // Lets start with Lists\n\nscala> val list = Nil // Empty List\nlist: scala.collection.immutable.Nil.type = List()\n\nscala> val list2 = List(\"one\", \"two\") // List with two elements (Strings)\nlist2: List[String] = List(one, two)\n\nscala> val list3 = 3 :: list2 // prepend 3 to list2, using a special operator\nlist3: List[Any] = List(3, one, two)\n\nscala> // The result was a mixture with a Int and Strings, so the common superclass Any is used.\n\nscala> // Let test the Set collection\n\nscala> val set = Set.empty[Char] // Empty Set of Char type\nset: scala.collection.immutable.Set[Char] = Set()\n\nscala> val set1 = set + 'c' // add an element\nset1: scala.collection.immutable.Set[Char] = Set(c)\n\nscala> val set2 = set + 'a' + 'c' + 'c' // try to add another and the same element twice\nset2: scala.collection.immutable.Set[Char] = Set(a, c)\n\nscala> // Let's look at the most universal map: TrieMap (Cache-aware lock-free concurrent hash trie)\n\nscala> val capital = collection.concurrent.TrieMap(\"US\" -> \"Washington\", \"France\" -> \"Paris\") // This map is mutable\ncapital: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington, France -> Paris)\n\nscala> capital - \"France\" // This is only an expression, does not modify the map itself\nres0: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington)\n\nscala> capital += (\"Tokio\" -> \"Japan\") // Adding an element, object is changed - not the val capital\nres1: capital.type = TrieMap(US -> Washington, Tokio -> Japan, France -> Paris)\n\nscala> capital // Check what we have sofar\nres2: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington, Tokio -> Japan, France -> Paris)\n\nscala> val queue = new scala.collection.mutable.Queue[String]\nqueue: scala.collection.mutable.Queue[String] = Queue()\n\nscala> queue += \"first\"\nres17: queue.type = Queue(\"first\")\n\nscala> queue += \"second\"\nres19: queue.type = Queue(\"first\", \"second\")\n\nscala>\n", "language": "Scala" }, { "code": " import collection.concurrent.TrieMap\n\n // super concurrent mutable hashmap\n val map = TrieMap(\"Amsterdam\" -> \"Netherlands\",\n \"New York\" -> \"USA\",\n \"Heemstede\" -> \"Netherlands\")\n\n map(\"Laussanne\") = \"Switzerland\" // 2 Ways of updating\n map += (\"Tokio\" -> \"Japan\")\n\n assert(map(\"New York\") == \"USA\")\n assert(!map.isDefinedAt(\"Gent\")) // isDefinedAt is false\n assert(map.isDefinedAt(\"Laussanne\")) // true\n\n val hash = new TrieMap[Int, Int]\n hash(1) = 2\n hash += (1 -> 2) // same as hash(1) = 2\n hash += (3 -> 4, 5 -> 6, 44 -> 99)\n hash(44) // 99\n hash.contains(33) // false\n hash.isDefinedAt(33) // same as contains\n hash.contains(44) // true\n // iterate over key/value\n // hash.foreach { case (key, val) => println( \"key \" + e._1 + \" value \" + e._2) } // e is a 2 element Tuple\n // same with for syntax\n for ((k, v) <- hash) println(\"key \" + k + \" value \" + v)\n // // items in map where the key is greater than 3\n map.filter { k => k._1 > 3 } // Map(5 -> 6, 44 -> 99)\n // // same with for syntax\n for ((k, v) <- map; if k > 3) yield (k, v)\n", "language": "Scala" }, { "code": "(list obj ...)\n", "language": "Scheme" }, { "code": "(display (list 1 2 3))\n(newline)\n(display (list))\n(newline)\n", "language": "Scheme" }, { "code": "(cons obj lst)\n", "language": "Scheme" }, { "code": "(display (cons 0 (list 1 2 3)))\n(newline)\n", "language": "Scheme" }, { "code": "(append lst ...)\n", "language": "Scheme" }, { "code": "(display (append (list 1 2 3) (list 4 5 6)))\n(newline)\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n\nenable_output(set of string);\n\nconst proc: main is func\n local\n var set of string: aSet is {\"iron\", \"copper\"};\n begin\n writeln(aSet);\n incl(aSet, \"silver\");\n writeln(aSet);\n end func;\n", "language": "Seed7" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst proc: main is func\n local\n var array string: anArray is [] (\"iron\", \"copper\");\n var string: element is \"\";\n begin\n for element range anArray do\n write(element <& \" \");\n end for;\n writeln;\n anArray &:= \"silver\";\n for element range anArray do\n write(element <& \" \");\n end for;\n writeln;\n end func;\n", "language": "Seed7" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst type: aHashType is hash [string] string;\n\nconst proc: main is func\n local\n var aHashType: aHash is aHashType.value;\n var string: aValue is \"\";\n var string: aKey is \"\";\n begin\n aHash @:= [\"gold\"] \"metal\";\n aHash @:= [\"helium\"] \"noble gas\";\n for aValue key aKey range aHash do\n writeln(aKey <& \": \" <& aValue);\n end for;a\n end func;\n", "language": "Seed7" }, { "code": "set = new('set 5 10 15 20 25 25')\nadd(set,30)\nshow(set)\n\nshow.eval('member(set,5)')\nshow.eval('member(set,6)')\n\nshow.eval(\"exists(set,'eq(this,10)')\")\nshow.eval(\"forall(set,'eq(this,40)')\")\n", "language": "Setl4" }, { "code": "iter = new('iter 1 10 2')\nshow(iter)\nshow.eval(\"eq(set.size(iter),5)\")\nshow.eval('member(iter,5)')\n", "language": "Setl4" }, { "code": "map = new('map one:1 two:2 ten:10 forty:40 hundred:100 thousand:1000')\nshow(map)\n\nshow.eval(\"eq(get(map,'one'),1)\")\nshow.eval(\"eq(get(map,'one'),6)\")\nshow.eval(\"exists(map,'eq(get(map,this),2)')\")\nshow.eval(\"forall(map,'eq(get(map,this),2)')\")\n", "language": "Setl4" }, { "code": "# creating an empty array and adding values\nvar a = [] #=> []\na[0] = 1 #=> [1]\na[3] = \"abc\" #=> [1, nil, nil, \"abc\"]\na << 3.14 #=> [1, nil, nil, \"abc\", 3.14]\n", "language": "Sidef" }, { "code": "# creating an empty hash\nvar h = Hash() #=> Hash()\nh{:foo} = 1 #=> Hash(\"foo\"=>1)\nh{:bar} = 2.4 #=> Hash(\"foo\"=>1, \"bar\"=>2.4)\nh{:bar} += 3 #=> Hash(\"foo\"=>1, \"bar\"=>5.4)\n", "language": "Sidef" }, { "code": "# create a simple pair\nvar p = Pair('a', 'b')\nsay p.first; #=> 'a'\nsay p.second; #=> 'b'\n\n# create a pair of pairs\nvar pair = 'foo':'bar':'baz':(); # => Pair('foo', Pair('bar', Pair('baz', nil)))\n\n# iterate over the values of a pair of pairs\nloop {\n say pair.first; #=> 'foo', 'bar', 'baz'\n pair = pair.second;\n pair == nil && break;\n}\n", "language": "Sidef" }, { "code": "# creating a struct\nstruct Person {\n String name,\n Number age,\n String sex\n}\n\nvar a = Person(\"John Smith\", 41, :man)\n\na.age += 1 # increment age\na.name = \"Dr. #{a.name}\" # update name\n\nsay a.name #=> \"Dr. John Smith\"\nsay a.age #=> 42\nsay a.sex #=> \"man\"\n", "language": "Sidef" }, { "code": "{1. 2. 3. 4. 5} collect: [|:x| x + 1]. \"--> {2. 3. 4. 5. 6}\"\n{1. 2. 3. 4. 5} select: #isOdd `er. \"--> {1. 3. 5}\"\n({3. 2. 7} collect: #+ `er <- 3) sort. \"--> {\"SortedArray traitsWindow\" 5. 6. 10}\"\nExtensibleArray new `>> [addLast: 3. addFirst: 4. ]. \"--> {\"ExtensibleArray traitsWindow\" 4. 3}\"\n", "language": "Slate" }, { "code": "|anOrdered aBag aSet aSorted aSorted2 aDictionary|\n\nanOrdered := OrderedCollection new.\nanOrdered add: 1; add: 5; add: 3.\nanOrdered printNl.\n\naBag := Bag new.\naBag add: 5; add: 5; add: 5; add: 6.\naBag printNl.\n\naSet := Set new.\naSet add: 10; add: 5; add: 5; add: 6; add: 10.\naSet printNl.\n\naSorted := SortedCollection new.\naSorted add: 10; add: 9; add: 8; add: 5.\naSorted printNl.\n\n\"another sorted with custom comparator: let's sort\n the other collections according to their size (number of\n elements)\"\naSorted2 := SortedCollection sortBlock: [ :a :b |\n (a size) < (b size) ].\naSorted2 add: anOrdered; add: aBag; add: aSet; add: aSorted.\naSorted2 printNl.\n\naDictionary := Dictionary new.\naDictionary at: 'OrderedCollection' put: anOrdered;\n at: 'Bag' put: aBag;\n at: 'Set' put: aSet;\n at: 'SortedCollection' put: { aSorted. aSorted2 }.\naDictionary printNl.\n", "language": "Smalltalk" }, { "code": "set c [list] ;# create an empty list\n# fill it\nlappend c 10 11 13\nset c [linsert $c 2 \"twelve goes here\"]\n# iterate over it\nforeach elem $c {puts $elem}\n\n# pass to a proc\nproc show_size {l} {\n puts [llength $l]\n}\nshow_size $c\n", "language": "Tcl" }, { "code": "# create an empty array\narray set h {}\n# add some pair\nset h(one) 1\nset h(two) 2\n# add more data\narray set h {three 3 four 4 more {5 6 7 8}}\n# iterate over it in a couple of ways\nforeach key [array names h] {puts \"$key -> $h($key)\"}\nforeach {key value} [array get h] {puts \"$key -> $value\"}\n\n# pass by name\nproc numkeys_byname {arrayName} {\n upvar 1 $arrayName arr\n puts \"array $arrayName has [llength [array names arr]] keys\"\n}\nnumkeys_byname h\n\n# pass serialized\nproc numkeys_bycopy {l} {\n array set arr $l\n puts \"array has [llength [array names arr]] keys\"\n}\nnumkeys_bycopy [array get h]\n", "language": "Tcl" }, { "code": "# create an empty dictionary\nset d [dict create]\ndict set d one 1\ndict set d two 2\n# create another\nset e [dict create three 3 four 4]\nset f [dict merge $d $e]\ndict set f nested [dict create five 5 more [list 6 7 8]]\nputs [dict get $f nested more] ;# ==> 6 7 8\n", "language": "Tcl" }, { "code": "$$ MODE TUSCRIPT\n\ncollection=*\nDATA apple\nDATA banana\nDATA orange\n\nmorestuff=*\nDATA peaches\nDATA apple\n\ncollection=APPEND(collection,morestuff)\nTRACE *collection\n", "language": "TUSCRIPT" }, { "code": "a_index=(one two three) # create an array with a few elements\na_index+=(four five) # append some elements\na_index[9]=ten # add a specific index\nfor elem in \"${a_index[@]}\"; do # interate over the elements\n echo \"$elem\"\ndone\nfor idx in \"${!a_index[@]}\"; do # interate over the array indices\n printf \"%d\\t%s\\n\" $idx \"${a_index[idx]}\"\ndone\n", "language": "UNIX-Shell" }, { "code": "declare -A a_assoc=([one]=1 [two]=2 [three]=3) # create an array with a few elements\na_assoc+=([four]=4 [five]=5) # add some elements\na_assoc[ten]=10\nfor value in \"${a_assoc[@]}\"; do # interate over the values\n echo \"$value\"\ndone\nfor key in \"${!a_assoc[@]}\"; do # interate over the array indices\n printf \"%s\\t%s\\n\" \"$key\" \"${a_assoc[$key]}\"\ndone\n", "language": "UNIX-Shell" }, { "code": "declare -A\n", "language": "UNIX-Shell" }, { "code": "typeset -A\n", "language": "UNIX-Shell" }, { "code": "x = <1,5,6>\ny = <'foo','bar'>\nz = 3:<6,8>\n", "language": "Ursala" }, { "code": "foo (\"newhead\",\"existing-list\") = \"newhead\":\"existing-list\"\n", "language": "Ursala" }, { "code": "x = {'a','b'}\ny = {'b','a'}\nz = {'a','b','a'}\n", "language": "Ursala" }, { "code": "m = <'foo': 1,'bar': 2,'baz': 3>\n", "language": "Ursala" }, { "code": "x =\n\n'z'^: <\n 'x'^: <\n '7'^: <>,\n '?'^: <'D'^: <>>>,\n 'a'^: <'E'^: <>,'j'^: <>>,\n 'b'^: <'i'^: <>>,\n 'c'^: <>>\n", "language": "Ursala" }, { "code": "x =\n\n[\n 4:0: 'foo',\n 4:1: 'bar',\n 4:2: 'baz',\n 4:3: 'volta',\n 4:4: 'pramim']\n", "language": "Ursala" }, { "code": "g =\n\n<\n [0:0: -9.483639e+00^: <4:10,4:14>],\n [\n 4:14: -9.681900e+00^: <4:15>,\n 4:10: 2.237330e+00^: <4:7>],\n [\n 4:15: -2.007562e+00^: <5:5>,\n 4:7: 2.419021e+00^: <5:5,5:15>],\n [\n 5:15: 8.215451e+00^: <11:118>,\n 5:5: 4.067704e+00^: <11:741>],\n [\n 11:741: -7.608967e+00^: <8:68>,\n 11:118: -1.552837e+00^: <8:68,8:208>],\n [\n 8:208: 5.348115e+00^: <4:7,4:9,4:12>,\n 8:68: -9.066821e+00^: <4:9,4:12>],\n [\n 4:12: -3.460494e+00^: <>,\n 4:9: 2.840319e+00^: <>,\n 4:7: -2.181140e+00^: <>]>\n", "language": "Ursala" }, { "code": "[4 3 2 1] 5 swap cons\n=[5 4 3 2 1]\n", "language": "V" }, { "code": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n", "language": "VBA" }, { "code": "Dim toys As New List(Of String)\ntoys.Add(\"Car\")\ntoys.Add(\"Boat\")\ntoys.Add(\"Train\")\n", "language": "Visual-Basic-.NET" }, { "code": "LOCAL loColl As Collection, o, a1, a2, a3\na1 = CREATEOBJECT(\"animal\", \"dog\", 4)\na2 = CREATEOBJECT(\"animal\", \"chicken\", 2)\na3 = CREATEOBJECT(\"animal\", \"snake\", 0)\nloColl = NEWOBJECT(\"Collection\")\nloColl.Add(a1)\nloColl.Add(a2)\nloColl.Add(a3)\n\nFOR EACH o IN loColl FOXOBJECT\n ? o.Name, o.Legs\nENDFOR\t\n\nDEFINE CLASS animal As Custom\nLegs = 0\n\nPROCEDURE Init(tcName, tnLegs)\nTHIS.Name = tcName\nTHIS.Legs = tnLegs\nENDPROC\n\nENDDEFINE\n", "language": "Visual-FoxPro" }, { "code": "var list = [] // Empty Array\nlist = [1, 2, 3, 4]\nlist.add(5)\nlist.clear()\nlist = [0] * 10\nlist.count // 10\n\nvar map = {}\nmap[\"key\"] = \"value\"\nmap[3] = 31\nmap.count // 2\nmap.clear()\n\nfor (e in map.keys) {\n // Do stuff\n}\n", "language": "Wren" }, { "code": "List:\nbyte 1,2,3,4,5\n", "language": "Z80-Assembly" }, { "code": "List:\nbyte 5 ;size byte\nbyte 1,2,3,4,5 ;the actual list\nbyte 0,0,0,0,0 ;free space\n\n;NOTE: separating the above list into different rows is just for visual clarity - it makes no difference to the CPU!\n\nAppendList:\n;input: A = the value you wish to append. ​\n ​ld hl,List\n ld a,(HL) ;get the size byte\n ld b,a ;store in B to use as loop counter for DJNZ\n inc hl\t\t\t;increment HL past the \"size byte\" to the actual data.\n ​push hl ;save this pointer for later\n\t push af ;save the value we want to append for later.\n\nGotoEndOfList:\n ​inc hl\n ​djnz GotoEndOfList\n;now, HL points to the first \"free\" byte.\n\t pop af\n\t ld (HL),a\t\t;store at the end of the list\n\tpop hl\t\t\t;go back to beginning of the list.\n\tinc (hl)\t\t;add 1 to the size byte.\n\tret\n", "language": "Z80-Assembly" }, { "code": "Lists: L(1,2,3).append(4); //-->L(1,2,3,4), mutable list\nRead only list: ROList(1,2,3).append(4); // creates two lists\n\nBit bucket: Data(0,Int,1,2,3) // three bytes\n The \"Int\" means treat contents as a byte stream\nData(0,Int,\"foo \",\"bar\") //-->7 bytes\n Data(0,Int,\"foo \").append(\"bar\") //ditto\n Data(0,Int,\"foo\\n\",\"bar\").readln() //-->\"foo\\n\"\nData(0,String,\"foo \",\"bar\") //-->9 bytes (2 \\0s)\n Data(0,String,\"foo \").append(\"bar\").readln() //-->\"foo \"\n", "language": "Zkl" } ]
Collections
[ { "code": "---\ncategory:\n- Testing\nfrom: http://rosettacode.org/wiki/Color_of_a_screen_pixel\nnote: GUI\n", "language": "00-META" }, { "code": ";Task:\nGet color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. \n\nThe mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "LDA $0200 ;get the color of the top-left pixel of the screen\nLDA $05FF ;get the color of the bottom-right pixel of the screen.\n", "language": "6502-Assembly" }, { "code": ";this code will fail to produce the desired result unless it executes during vblank or forced blank.\n;address $23C0 = first color cell of nametable $2000\nLDA #$23\nSTA $2006\nLDA #$C0\nSTA $2006\n\nLDA $2007\nAND #%11000000 ;00------ = top-left corner uses palette 0, 01------ = top-left corner uses palette 1, etc.\n", "language": "6502-Assembly" }, { "code": ";input: cx = x coordinate of pixel, dx = y coordinate of pixel, bh = page number\nmov ah,0Dh\nint 10h\n", "language": "8086-Assembly" }, { "code": "PROC Main()\n BYTE POINTER ptr\n BYTE\n w=[160],h=[160],x=[0],y=[0],c,k,update=[1],\n CH=$02FC ;Internal hardware value for last key pressed\n CARD size=[6400],i\n\n Graphics(15) ;Graphics 160x160 with 4 colors with text window\n ptr=PeekC(88)\n\n ; Fill screen with random colors\n FOR i=1 TO size\n DO\n ptr^=Rand(0)\n ptr==+1\n OD\n\n PrintE(\"Use arrow keys to change position and Esc to exit.\")\n DO\n IF update THEN\n c=Locate(x,y)\n PrintF(\"x=%B y=%B c=%B%E\",x,y,c)\n FI\n\n k=CH\n CH=$FF\n update=1\n IF k=134 THEN\n IF x=0 THEN x=w-1\n ELSE x==-1 FI\n ELSEIF k=135 THEN\n IF x=w-1 THEN x=0\n ELSE x==+1 FI\n ELSEIF k=142 THEN\n IF y=0 THEN y=h-1\n ELSE y==-1 FI\n ELSEIF k=143 THEN\n IF y=h-1 THEN y=0\n ELSE y==+1 FI\n ELSEIF k=28 THEN\n EXIT\n ELSE\n update=0\n FI\n OD\nRETURN\n", "language": "Action-" }, { "code": "MOUSE ON\n\nWHILE 1\n m=MOUSE(0)\n PRINT POINT(MOUSE(1),MOUSE(2))\nWEND\n", "language": "AmigaBASIC" }, { "code": "X = PDL (0) * 5 / 32\nY = PDL (1) * 3 / 16\n COLOR= SCRN( X,Y)\n", "language": "Applesoft-BASIC" }, { "code": " 100 REM GET HCOLOR\n 110 REM PARAMETERS: X Y\n 120 REM RETURNS: C\n 130 REM\n 140 P = 0:X = X + 1\n 150 ON (X < 280) GOSUB 300\n 160 PR = P:P = 0:X = X - 2\n 170 ON (X > = 0) GOSUB 300\n 180 PL = P:X = X + 1: GOSUB 300\n 190 ODD = X - INT (X / 2) * 2\n 200 C = H * 4\n 210 IF NOT ((PL = PR) AND (PL < > P)) THEN C = C + P * 3: RETURN\n 220 IF ODD THEN P = NOT P\n 230 C = C + P + 1\n 240 RETURN\n 250 REM\n 260 REM GET PIXEL\n 270 REM PARAMETERS: X Y\n 280 REM RETURNS: H P\n 290 REM\n 300 H = INT (X / 7)\n 310 V = INT (Y / 8)\n 320 VO = PEEK (37)\n 330 HO = PEEK (36)\n 340 VTAB V + 1: HTAB 1\n 350 A = PEEK (41) * 256\n 360 A = A + PEEK (40) + H\n 370 VTAB VO + 1: HTAB HO + 1\n 380 A = A + 8192 - 1024\n 390 P = PEEK (230) / 32\n 400 IF P = 2 THEN A = A + 8192\n 410 A = A + (Y - V * 8) * 1024\n 420 B = X - H * 7\n 430 V = PEEK (A)\n 440 H = INT (V / 128)\n 450 V = INT (V / (2 ^ B))\n 460 P = V - INT (V / 2) * 2\n 470 RETURN\n\nX = 267 : Y = 166 : GOSUB 100\nHCOLOR= C\n", "language": "Applesoft-BASIC" }, { "code": "PixelGetColor, color, %X%, %Y%\n", "language": "AutoHotkey" }, { "code": "Opt('MouseCoordMode',1) ; 1 = (default) absolute screen coordinates\n$pos = MouseGetPos()\n$c = PixelGetColor($pos[0], $pos[1])\nConsoleWrite(\"Color at x=\" & $pos[0] & \",y=\" & $pos[1] & _\n\t\t\" ==> \" & $c & \" = 0x\" & Hex($c) & @CRLF)\n", "language": "AutoIt" }, { "code": "Disp pxl-Test(50,50)▶Dec,i\n", "language": "Axe" }, { "code": "INCLUDE canvas\nFULLSCREEN\ncolor = GETINK(100, 100, 4)\nWAITKEY\n", "language": "BaCon" }, { "code": "color rgb(0, 255, 0)\nrect 50, 50, 75, 75\n\ncolor rgb(255, 0, 0)\nline (20,20,100,100)\n\nx = 60 : y = 50\n\nc = pixel(x, y)\nrojo = (c & 0xff0000) \\ 0x10000\nverde = (c & 0xff00) \\ 0x100\nazul = (c & 0xff)\n\nprint rojo; \" \"; verde; \" \"; azul\n", "language": "BASIC256" }, { "code": " palette_index% = POINT(x%, y%)\n RGB24b_colour% = TINT(x%, y%)\n", "language": "BBC-BASIC" }, { "code": "#include <X11/Xlib.h>\nvoid\nget_pixel_color (Display *d, int x, int y, XColor *color)\n{\n XImage *image;\n image = XGetImage (d, RootWindow (d, DefaultScreen (d)), x, y, 1, 1, AllPlanes, XYPixmap);\n color->pixel = XGetPixel (image, 0, 0);\n XFree (image);\n XQueryColor (d, DefaultColormap(d, DefaultScreen (d)), color);\n}\n\n// Your code\nXColor c;\nget_pixel_color (display, 30, 40, &c);\nprintf (\"%d %d %d\\n\", c.red, c.green, c.blue);\n", "language": "C" }, { "code": "#include <Windows.h>\n\nCOLORREF getColorAtCursor(void) {\n POINT p;\n COLORREF color;\n HDC hDC;\n BOOL b;\n\n /* Get the device context for the screen */\n hDC = GetDC(NULL);\n if (hDC == NULL)\n return CLR_INVALID;\n\n /* Get the current cursor position */\n b = GetCursorPos(&p);\n if (!b)\n return CLR_INVALID;\n\n /* Retrieve the color at that position */\n color = GetPixel(hDC, p.x, p.y);\n\n /* Release the device context again */\n ReleaseDC(GetDesktopWindow(), hDC);\n\n return color;\n}\n", "language": "C" }, { "code": "using namespace System;\nusing namespace System::Drawing;\nusing namespace System::Windows::Forms;\n\n[STAThreadAttribute]\nint main()\n{\n\tPoint^ MousePoint = gcnew Point();\n\tControl^ TempControl = gcnew Control();\n\tMousePoint = TempControl->MousePosition;\n\tBitmap^ TempBitmap = gcnew Bitmap(1,1);\n\tGraphics^ g = Graphics::FromImage(TempBitmap);\t\n\tg->CopyFromScreen((Point)MousePoint, Point(0, 0), Size(1, 1));\n\tColor color = TempBitmap->GetPixel(0,0);\n\tConsole::WriteLine(\"R: \"+color.R.ToString());\n\tConsole::WriteLine(\"G: \"+color.G.ToString());\n\tConsole::WriteLine(\"B: \"+color.B.ToString());\n}\n", "language": "C++-CLI" }, { "code": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass Program\n{\n static Color GetPixel(Point position)\n {\n using (var bitmap = new Bitmap(1, 1))\n {\n using (var graphics = Graphics.FromImage(bitmap))\n {\n graphics.CopyFromScreen(position, new Point(0, 0), new Size(1, 1));\n }\n return bitmap.GetPixel(0, 0);\n }\n }\n\n static void Main()\n {\n Console.WriteLine(GetPixel(Cursor.Position));\n }\n}\n", "language": "C-sharp" }, { "code": "Color [A=255, R=243, G=242, B=231]\n", "language": "C-sharp" }, { "code": "(defn get-color-at [x y]\n (.getPixelColor (java.awt.Robot.) x y))\n", "language": "Clojure" }, { "code": "5 rem commodore 64 example\n10 base=2*4096:x=100:y=50:poke53280,0\n20 gosub 1000:print chr$(147);\n30 bg=11:fg=1:rem set foreground and background colors\n40 for i=1024 to 1503:poke i,fg*16+bg:next\n50 for i=base to base+7990:poke i,0:next\n60 gosub 1200\n70 poke byte, peek(byte) or 2^bit\n80 print\"{home}{crsr-down 14}\";\n90 px=((peek(byte) and 2^bit)>0)\n100 co=peek(cb)and(15+(-225*px)):if px then co=co/16\n110 print\"pixel color at\";x;\"{crsr-left},\";y;\"{crsr-left}:\";co;\"{crsr-left} \"\n120 getk$:ifk$=\"\"then 120\n130 gosub 1100:end\n1000 rem turn on graphics\n1010 poke53272,peek(53272) or 8\n1020 poke53265,peek(53265) or 32\n1030 return\n1100 rem turn off graphics\n1110 poke53265,peek(53265) and 223\n1120 poke53272,peek(53272) and 247\n1130 return\n1200 rem convert x-y into mem location\n1210 ro=int(y/8):ch=int(x/8):li=y and 7\n1220 bit=7-(x and 7):byte=base+ro*320+char*8+li:cb=1024+ro+ch\n1230 return\n", "language": "Commodore-BASIC" }, { "code": "10 color 0,1:color 1,3: rem set border to black and pixel color to red\n15 graphic 2,1: rem enter split graphics/text mode and clear screen\n20 draw 1,100,50 : rem plot pixel at 100,50\n30 print \"pixel color at\";rdot(0);\",\";rdot(1);\"is\";rclr(rdot(2))\n40 get k$:if k$=\"\" then 40\n50 graphic 0,1 : rem return to text mode\n", "language": "Commodore-BASIC" }, { "code": "(in-package :cg-user)\n\n(defun print-hex (n)\n (let ((*print-base* 16.) (*print-radix* t))\n (print n)) t)\n\n(defun get-byte (n byte)\n (logand (ash n (* byte -8)) #xFF))\n\n(defun get-pixel (x y)\n (let ((pixval (caar (contents (get-screen-pixmap :box (make-box x y (+ x 1) (+ y 1)))))))\n (mapcar #'(lambda (i) (get-byte pixval i)) '(2 1 0 3))))\n\n(defun get-mouse-pixel ()\n (let ((pos (cursor-position (screen *system*))))\n (get-pixel (position-x pos) (position-y pos))))\n\n(print-hex (get-mouse-pixel))\n", "language": "Common-Lisp" }, { "code": "(#xe0 #x43 #x43 #xff)\n", "language": "Common-Lisp" }, { "code": "program ScreenPixel;\n\n{$APPTYPE CONSOLE}\n\nuses\n Windows,\n SysUtils,\n Graphics;\n\n\n// Use this function in a GUI application to return the color\nfunction GetPixelColourAsColor(const PixelCoords: TPoint): TColor;\nvar\n dc: HDC;\nbegin\n // Get Device Context of windows desktop\n dc := GetDC(0);\n // Read the color of the pixel at the given coordinates\n Result := GetPixel(dc,PixelCoords.X,PixelCoords.Y);\nend;\n\n// Use this function to get a string representation of the current colour\nfunction GetPixelColourAsString(const PixelCoords: TPoint): string;\nvar\n r,g,b: Byte;\n col: TColor;\nbegin\n col := GetPixelColourAsColor(PixelCoords);\n\n // Convert the Delphi TColor value to it's RGB components\n r := col and $FF;\n g := (col shr 8) and $FF;\n b := (col shr 16) and $FF;\n\n // Format the result\n Result := 'R('+IntToStr(r)+') G('+IntToStr(g)+') G('+IntToStr(b)+')';\n\n {\n Alternatively, format the result as follows to get a\n string representation of the Delphi TColor value\n\n Result := ColorToString(GetPixel(dc,curP.X,curP.Y));\n }\n\nend;\n\nvar\n s: string;\n P: TPoint;\nbegin\n s := '';\n\n Writeln('Move mouse over a pixel. Hit return to get colour of selected pixel.');\n\n repeat\n Readln(s);\n if s = '' then\n begin\n GetCursorPos(P);\n Writeln('Colour at cursor position X:'+\n IntToStr(P.X)+' Y:'+\n IntToStr(P.Y) +' = '+\n GetPixelColourAsString(P)\n );\n Writeln('');\n Writeln('Move mouse and hit enter again.');\n end;\n until\n SameText(s,'quit');\n\nend.\n", "language": "Delphi" }, { "code": "open System.Drawing\nopen System.Windows.Forms\n\nlet GetPixel x y =\n use img = new Bitmap(1,1)\n use g = Graphics.FromImage(img)\n g.CopyFromScreen(new Point(x,y), new Point(0,0), new Size(1,1))\n let clr = img.GetPixel(0,0)\n (clr.R, clr.G, clr.B)\n\nlet GetPixelAtMouse () =\n let pt = Cursor.Position\n GetPixel pt.X pt.Y\n", "language": "F-Sharp" }, { "code": "FB 1.05.0 Win64\n\n' Set an appropriate screen mode - 320 x 240 x 8bpp indexed color\nScreenRes 320, 240, 8\n\n' Draw a line using color 12 (light red)\nLine (20,20)-(100,100), 12\n\n' Print the color of a point on the line\nPrint Point(20,20) '' prints 12\n\n' Sleep before the program closes\nSleep\n", "language": "FreeBASIC" }, { "code": "_window = 1\nbegin enum 1\n _view\n _colorWell\n _imageView\nend enum\n\nvoid local fn BuildWindow\n window _window, @\"ColorUnderMouse\", (0,0,500,400), NSWindowStyleMaskTitled + NSWindowStyleMaskClosable\n view subclass _view, (0,0,500,300)\n colorwell _colorWell, YES, fn ColorWhite, ( 410, 310, 70, 70 ), NO, _window\nend fn\n\nvoid local fn DrawRect\n CFArrayRef array = @[fn ColorRed, fn ColorOrange, fn ColorYellow, fn ColorGreen, fn ColorBlue, fn ColorWithRGB(0,0.29,0.51,1), fn ColorWithRGB(0.58,0.0,0.83,1)]\n GradientRef grad = fn GradientWithColors( array )\n GradientDrawInRect( grad, fn ViewFrame(_view), 0 )\nend fn\n\n\nvoid local fn DoMouse( tag as NSInteger )\n CGPoint pt = fn EventLocationInView( tag )\n ColorRef color = fn ViewColorAtPoint( tag, pt )\n\n ColorWellSetColor( _colorWell, color )\n\n cls : printf @\"%.0fx, %.0fy, %@\", pt.x, pt.y, color\nend fn\n\nvoid local fn DoDialog( ev as long, tag as long )\n select ( tag )\n case _view\n select ( ev )\n case _viewDrawRect : fn DrawRect\n case _viewMouseDown : fn DoMouse( tag )\n case _viewMouseDragged : fn DoMouse( tag )\n end select\n end select\n\n select ( ev )\n case _windowWillClose : end\n end select\nend fn\n\nfn BuildWindow\n\non dialog fn DoDialog\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"github.com/go-vgo/robotgo\"\n)\n\nfunc main() {\n // get position of mouse cursor\n x, y := robotgo.GetMousePos()\n\n // get color of pixel at that position\n color := robotgo.GetPixelColor(x, y)\n fmt.Printf(\"Color of pixel at (%d, %d) is 0x%s\\n\", x, y, color)\n}\n", "language": "Go" }, { "code": "import java.awt.Robot\n\nclass GetPixelColor {\n static void main(args) {\n println getColorAt(args[0] as Integer, args[1] as Integer)\n }\n\n static getColorAt(x, y) {\n new Robot().getPixelColor(x, y)\n }\n}\n", "language": "Groovy" }, { "code": "link graphics,printf\n\nprocedure main()\n\n WOpen(\"canvas=hidden\") # hide for query\n height := WAttrib(\"displayheight\") - 45 # adjust for ...\n width := WAttrib(\"displaywidth\") - 20 # ... window 7 borders\n WClose(&window)\n\n W := WOpen(\"size=\"||width||\",\"||height,\"bg=black\") |\n stop(\"Unable to open window\")\n\n every 1 to 10 do { # generate some random rectangles within the frame\n x := ?width\n y := ?(height-100)\n WAttrib(\"fg=\"||?[\"red\",\"green\",\"blue\",\"purple\",\"yellow\"])\n FillRectangle(x,x+50,y,y+50)\n }\n\n while Event() do\n printf(\"x=%d,y=%d pixel=%s\\n\",&x,&y,Pixel(&x,&y,&x,&y))\n\n WDone(W) # q to exit\nend\n", "language": "Icon" }, { "code": "GetDC=: 'user32.dll GetDC >i i'&cd NB. hdx: GetDC hwnd\nGetPixel=: 'gdi32.dll GetPixel >l i i i'&cd NB. rgb: GetPixel hdc x y\nGetCursorPos=: 'user32.dll GetCursorPos i *i'&cd NB. success: point\n", "language": "J" }, { "code": " |.(3#256) #: GetPixel (GetDC<0),1{::GetCursorPos<0 0\n121 91 213\n", "language": "J" }, { "code": " GetDC<0\n1325469620\n GetCursorPos<0 0\n┌─┬───────┐\n│1│101 255│\n└─┴───────┘\n 1{::GetCursorPos<0 0\n101 255\n GetPixel 1325469620 101 255\n13982585\n |.(3#256)#:13982585\n121 91 213\n", "language": "J" }, { "code": "public static Color getColorAt(int x, int y){\n return new Robot().getPixelColor(x, y);\n}\n", "language": "Java" }, { "code": "# Windows GDI version\nfunction getpixelcolors(x, y)\n hdc = ccall((:GetDC, \"user32.dll\"), UInt32, (UInt32,), 0)\n pxl = ccall((:GetPixel, \"gdi32.dll\"), UInt32, (UInt32, Cint, Cint), hdc, Cint(x), Cint(y))\n return pxl & 0xff, (pxl >> 8) & 0xff, (pxl >> 16) & 0xff\nend\n\nconst x = 120\nconst y = 100\ncols = getpixelcolors(x, y)\nprintln(\"At screen point (x=$x, y=$y) the color RGB components are red: $(cols[1]), green: $(cols[2]), and blue: $(cols[3])\")\n", "language": "Julia" }, { "code": "import java.awt.*\n\nfun getMouseColor(): Color {\n val location = MouseInfo.getPointerInfo().location\n return getColorAt(location.x, location.y)\n}\n\nfun getColorAt(x: Int, y: Int): Color {\n return Robot().getPixelColor(x, y)\n}\n", "language": "Kotlin" }, { "code": "'This example requires the Windows API\nStruct point, x As long, y As long\n\nhDC = GetDC(0)\nresult = GetCursorPos()\nPrint GetPixel(hDC, point.x.struct, point.y.struct)\nCall ReleaseDC 0, hDC\nEnd\n\n\n Sub ReleaseDC hWnd, hDC\n CallDLL #user32,\"ReleaseDC\", hWnd As uLong, hDC As uLong, ret As Long\n End Sub\n\n Function GetDC(hWnd)\n CallDLL #user32, \"GetDC\", hWnd As uLong, GetDC As uLong\n End Function\n\n Function GetCursorPos()\n CallDLL #user32, \"GetCursorPos\", point As struct, GetCursorPos As uLong\n End Function\n\n Function GetPixel(hDC, x, y)\n CallDLL #gdi32, \"GetPixel\", hDC As uLong, x As long, y As long, GetPixel As long\n End Function\n", "language": "Liberty-BASIC" }, { "code": "on getScreenPixelColor (x, y)\n sx = xtra(\"ScrnXtra3\").new()\n img = sx.ScreenToImage(rect(x, y, x+1, y+1))\n return img.getPixel(0, 0)\nend\n", "language": "Lingo" }, { "code": "10 x=320:y=200\n20 color=TEST(x,y)\n30 PRINT \"Pen color at\"; x; y; \"is\"; color\n", "language": "Locomotive-Basic" }, { "code": "Module CheckColor {\n \\\\ Print hex code for color, and html code for color\n Every 25 {\n move mouse.x, mouse.y\n color$=Hex$(-point, 3) ' point has a negative value\n Print Over \"0x\"+color$+\", #\"+Right$(color$,2)+Mid$(color$, 3,2)+Left$(color$,2)\n if mouse<>0 then exit\n }\n Print\n}\nCheckColor\n", "language": "M2000-Interpreter" }, { "code": "getPixel[{x_?NumberQ, y_?NumberQ}, screenNumber_Integer: 1] := ImageValue[CurrentScreenImage[n], {x, y}]\n", "language": "Mathematica" }, { "code": "import gtk2, gdk2, gdk2pixbuf\n\ntype Color = tuple[r, g, b: byte]\n\ngtk2.nim_init()\n\nproc getPixelColor(x, y: int32): Color =\n var p = pixbufNew(COLORSPACE_RGB, false, 8, 1, 1)\n discard p.getFromDrawable(getDefaultRootWindow().Drawable,\n getDefaultScreen().getSystemColormap(), x, y, 0, 0, 1, 1)\n result = cast[ptr Color](p.getPixels)[]\n\necho getPixelColor(0, 0)\n", "language": "Nim" }, { "code": "import gintro/[gtk, gobject, gio, gdk, gdkpixbuf]\n\ntype Color = tuple[r, g, b: byte]\n\nproc getPixelColor(x, y: int32): Color =\n var pixbuf = pixbufGetFromWindow(getDefaultRootWindow(), x, y, 1, 1)\n result = cast[ptr Color](pixbuf.readPixels())[]\n\nproc activate(app: Application) =\n ## Needed by GTK3.\n discard\n\nlet app = newApplication(\"org.gtk.example\")\nconnect(app, \"activate\", activate)\ndiscard run(app)\n\necho getPixelColor(1500, 800)\n", "language": "Nim" }, { "code": "use strict;\nuse warnings;\nuse GD;\n\nmy $file = '/tmp/one-pixel-screen-capture.png';\n\nsystem \"screencapture -R 123,456,1,1 $file\";\n\nmy $image = GD::Image->newFromPng($file);\nmy $index = $image->getPixel(0,0);\nmy($red,$green,$blue) = $image->rgb($index);\nprint \"RGB: $red, $green, $blue\\n\";\n\nunlink $file;\n", "language": "Perl" }, { "code": "integer {r,g,b} = im_pixel(image, x, y)\n", "language": "Phix" }, { "code": "$img = imagegrabscreen();\n$color = imagecolorat($im, 10, 50);\nimagedestroy($im);\n", "language": "PHP" }, { "code": "(in '(grabc)\n (mapcar hex (cdr (line NIL 1 2 2 2))) )\n", "language": "PicoLisp" }, { "code": "void draw(){\n color c = get(mouseX,mouseY);\n println(c, red(c), green(c), blue(c));\n}\n", "language": "Processing" }, { "code": "void draw(){\n loadPixels();\n color c = pixels[mouseY * width + mouseX];\n println(c, c >> 16 & 0xFF, c >> 8 & 0xFF, c >> 8 & 0xFF);\n}\n", "language": "Processing" }, { "code": "Color = Point(x, y)\n", "language": "PureBasic" }, { "code": "hDC = GetDC_(0)\nColor = GetPixel_(hDC, x, y)\nReleaseDC_(0, hDC)\n", "language": "PureBasic" }, { "code": "poz.point\nIf OpenWindow(0,0,0,100,45,\"Get pixel color at cursor position\",#PB_Window_MinimizeGadget)\n TextGadget(0,0,0,50,12,\"Red: \")\n TextGadget(1,0,15,50,12,\"Green: \")\n TextGadget(2,0,30,50,12,\"Blue: \")\n TextGadget(3,50,0,50,12,\"\")\n TextGadget(4,50,15,50,12,\"\")\n TextGadget(5,50,30,50,12,\"\")\n hDC = GetDC_(0)\n Repeat\n oldx=poz\\x\n oldy=poz\\y\nGetCursorPos_(@poz)\nColor = GetPixel_(hDC, poz\\x, poz\\y)\nIf poz\\x<>oldx Or poz\\y<>oldy\n SetGadgetText(3,Str(Red(color)))\n SetGadgetText(4,Str(Green(color)))\n SetGadgetText(5,Str(Blue(color)))\nEndIf\nevent=WaitWindowEvent(200)\nUntil event=#PB_Event_CloseWindow\nReleaseDC_(0, hDC)\nEndIf\n", "language": "PureBasic" }, { "code": "def get_pixel_colour(i_x, i_y):\n\timport win32gui\n\ti_desktop_window_id = win32gui.GetDesktopWindow()\n\ti_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id)\n\tlong_colour = win32gui.GetPixel(i_desktop_window_dc, i_x, i_y)\n\ti_colour = int(long_colour)\n\twin32gui.ReleaseDC(i_desktop_window_id,i_desktop_window_dc)\n\treturn (i_colour & 0xff), ((i_colour >> 8) & 0xff), ((i_colour >> 16) & 0xff)\n\nprint (get_pixel_colour(0, 0))\n", "language": "Python" }, { "code": "def get_pixel_colour(i_x, i_y):\n\timport PIL.ImageGrab\n\treturn PIL.ImageGrab.grab().load()[i_x, i_y]\n\nprint (get_pixel_colour(0, 0))\n", "language": "Python" }, { "code": "def get_pixel_colour(i_x, i_y):\n\timport PIL.Image # python-imaging\n\timport PIL.ImageStat # python-imaging\n\timport Xlib.display # python-xlib\n\to_x_root = Xlib.display.Display().screen().root\n\to_x_image = o_x_root.get_image(i_x, i_y, 1, 1, Xlib.X.ZPixmap, 0xffffffff)\n\to_pil_image_rgb = PIL.Image.fromstring(\"RGB\", (1, 1), o_x_image.data, \"raw\", \"BGRX\")\n\tlf_colour = PIL.ImageStat.Stat(o_pil_image_rgb).mean\n\treturn tuple(map(int, lf_colour))\n\nprint (get_pixel_colour(0, 0))\n", "language": "Python" }, { "code": "def get_pixel_colour(i_x, i_y):\n\timport gtk # python-gtk2\n\to_gdk_pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 1, 1)\n\to_gdk_pixbuf.get_from_drawable(gtk.gdk.get_default_root_window(), gtk.gdk.colormap_get_system(), i_x, i_y, 0, 0, 1, 1)\n\treturn tuple(o_gdk_pixbuf.get_pixels_array().tolist()[0][0])\n\nprint (get_pixel_colour(0, 0))\n", "language": "Python" }, { "code": "def get_pixel_colour(i_x, i_y):\n\timport PyQt4.QtGui # python-qt4\n\tapp = PyQt4.QtGui.QApplication([])\n\tlong_qdesktop_id = PyQt4.QtGui.QApplication.desktop().winId()\n\tlong_colour = PyQt4.QtGui.QPixmap.grabWindow(long_qdesktop_id, i_x, i_y, 1, 1).toImage().pixel(0, 0)\n\ti_colour = int(long_colour)\n\treturn ((i_colour >> 16) & 0xff), ((i_colour >> 8) & 0xff), (i_colour & 0xff)\n\nprint (get_pixel_colour(0, 0))\n", "language": "Python" }, { "code": "'Example: Find color of a screen pixel in QBasic (adapted from QBasic Help file).\n' POINT(x%, y%) returns color of pixel at coordinates x,y.\nSCREEN 7 'Choose color graphics screen (1,2,4,7,8,9,11,12,13).\nLINE (0, 0)-(100, 100), 2 'Draw diagonal line in color attribute 2.\nLOCATE 14, 1 'Locate below diagonal line to show output.\nFOR y% = 1 TO 10\n FOR x% = 1 TO 10\n PRINT POINT(x%, y%); 'POINT(x%, y%) displays pixel color.\n NEXT x%\n PRINT\nNEXT y%\nEND\n", "language": "QBasic" }, { "code": "color = point(x, y)\n", "language": "QuickBASIC" }, { "code": "use GD::Raw;\n\nmy $file = '/tmp/one-pixel-screen-capture.png';\n\nqqx/screencapture -R 123,456,1,1 $file/;\n\nmy $fh = fopen($file, \"rb\") or die;\nmy $image = gdImageCreateFromPng($fh);\nmy $pixel = gdImageGetPixel($image, 0, 0);\nmy ($red,$green,$blue) =\n gdImageRed( $image, $pixel),\n gdImageGreen($image, $pixel),\n gdImageBlue( $image, $pixel);\n\nsay \"RGB: $red, $green, $blue\";\n\nfclose($fh);\nunlink $file;\n", "language": "Raku" }, { "code": "signal(SIGINT).tap: { sleep .1; cleanup(); print \"\\n\" xx 50, \"\\e[H\\e[J\"; exit(0) }\n\nmulti MAIN () {\n use X11::libxdo;\n my $xdo = Xdo.new;\n my ($lx, $ly) = 0, 0;\n loop {\n sleep .1;\n my ($x, $y, $) = $xdo.get-mouse-location;\n next if $lx == $x and $ly == $y;\n ($lx, $ly) = $x, $y;\n display $x, $y, |get-pixel($x, $y);\n }\n}\n\nmy %*SUB-MAIN-OPTS = :named-anywhere;\n\nmulti MAIN (\n Int $x, #= Integer x coordinate to pick\n Int $y, #= Integer y coordinate to pick\n $q = False #= Boolean \"quiet\" mode, set truthy for decimal values, set to h for hex values\n ) {\n my ($red, $green, $blue) = get-pixel($x, $y);\n\n if $q {\n $q.lc eq 'h' ??\n ( printf \"%02X:%02X:%02X\\n\", $red, $green, $blue ) !!\n ( printf \"%03d:%03d:%03d\\n\", $red, $green, $blue );\n } else {\n display($x, $y, $red, $green, $blue);\n cleanup();\n }\n exit(0);\n}\n\nsub get-pixel ($x, $y) {\n my $xcolor =\n qqx/import -window root -crop 1x1+{$x-1 max 0}+{$y-2 max 0} -depth 8 txt:-/\n .comb(/<?after '#'><xdigit> ** 6/);\n\n |$xcolor.comb(2)».parse-base(16);\n}\n\nsub display ($x, $y, $r, $g, $b) {\n print \"\\e[?25l\\e[48;2;0;0;0m\\e[38;2;255;255;255m\\e[H\\e[J\";\n printf \" x: %4d y: $y\\n\", $x;\n printf \" RGB: %03d:%03d:%03d \\n HEX: %02X:%02X:%02X\\n\",\n $r, $g, $b, $r, $g, $b;\n print \"\\e[38;2;{$r};{$g};{$b}m \",\n ('█' x 18 xx 6).join(\"\\n \"), \"\\n\\n\";\n}\n\nsub cleanup { print \"\\e[0m\\e[?25h\" }\n", "language": "Raku" }, { "code": "/*REXX program obtains the cursor position (within it's window) and displays it's color.*/\nparse value cursor() with r c . /*get cursor's location in DOS screen. */\n\nhue=scrRead(r, c, 1, 'A') /*get color of the cursor's location. */\nif hue=='00'x then color= 'black' /*or dark grey, dark gray. */\nif hue=='01'x then color= 'darkblue'\nif hue=='02'x then color= 'darkgreen'\nif hue=='03'x then color= 'darkturquoise' /*or dark cyan. */\nif hue=='04'x then color= 'darkred' /*or maroon. */\nif hue=='05'x then color= 'darkmagenta' /*or dark pink. */\nif hue=='06'x then color= 'orange' /*or dark yellow, orage, brown. */\nif hue=='07'x then color= 'gray' /*or grey, gray, dark white. */\nif hue=='08'x then color= 'gray' /*or grey, gray, dark white. */\nif hue=='09'x then color= 'blue' /*or bright blue. */\nif hue=='0A'x then color= 'green' /*or bright green. */\nif hue=='0B'x then color= 'turquoise' /*or bright turquoise, cyan, britecyan.*/\nif hue=='0C'x then color= 'red' /*or bright red. */\nif hue=='0D'x then color= 'magenta' /*or bright magenta, pink, brite pink. */\nif hue=='0E'x then color= 'yellow' /*or bright yellow. */\nif hue=='0F'x then color= 'white' /*or bright, brite white. */\nsay 'screen location ('r\",\"c') color is:' color /*display color of char at row, column.*/\n", "language": "REXX" }, { "code": "# Project : Color of a screen pixel\n\nLoad \"gamelib.ring\"\nr = 0\ng = 0\nb = 0\nal_init()\nal_init_image_addon()\ndisplay = al_create_display(1000,800)\nal_set_target_bitmap(al_get_backbuffer(display))\nal_clear_to_color(al_map_rgb(255,255,255))\nimage = al_load_bitmap(\"stock.jpg\")\nal_draw_rotated_bitmap(image,0,0,250,250,150,0)\nal_draw_scaled_bitmap(image,0,0,250,250,20,20,400,400,0)\nring_getpixel(image,300,300)\nsee \"r = \" + r + nl\nsee \"g = \" + g + nl\nsee \"b = \" + b + nl\nal_flip_display()\nal_rest(2)\nal_destroy_bitmap(image)\nal_destroy_display(display)\n\nfunc ring_getpixel(image,x,y)\n newcolor = al_get_pixel(image,x,y)\n r=copy(\" \",4) g=copy(\" \",4) b=copy(\" \",4)\n p1 = VarPtr(\"r\",\"float\")\n p2 = VarPtr(\"g\",\"float\")\n p3 = VarPtr(\"b\",\"float\")\n al_unmap_rgb_f(newcolor, p1 , p2 , p3 )\n r = bytes2float(r)\n g = bytes2float(g)\n b = bytes2float(b)\n return [r,g,b]\n", "language": "Ring" }, { "code": "module Screen\n IMPORT_COMMAND = '/usr/bin/import'\n\n # Returns an array with RGB values for the pixel at the given coords\n def self.pixel(x, y)\n if m = `#{IMPORT_COMMAND} -silent -window root -crop 1x1+#{x.to_i}+#{y.to_i} -depth 8 txt:-`.match(/\\((\\d+),(\\d+),(\\d+)\\)/)\n m[1..3].map(&:to_i)\n else\n false\n end\n end\nend\n", "language": "Ruby" }, { "code": "def getColorAt(x: Int, y: Int): Color = new Robot().getPixelColor(x, y)\n", "language": "Scala" }, { "code": "Display rootView colorAt:(10@10).\nDisplay rootView colorAt:(Display pointerPosition)\n", "language": "Smalltalk" }, { "code": "DEF GETPX X,Y OUT R,G,B\n PCOL=GSPOIT(X,Y)\n RGBREAD PCOL OUT R,G,B\nEND\n", "language": "SmileBASIC" }, { "code": "open XWindows ;\nval disp = XOpenDisplay \"\" ;\n\nval im =\nlet\n val pos = #4 (XQueryPointer (RootWindow disp)) ;\nin\n XGetImage (RootWindow disp) (MakeRect pos (AddPoint(pos,XPoint{x=1,y=1})) ) AllPlanes ZPixmap\nend;\n\n XGetPixel disp im (XPoint {x=0,y=0}) ;\n", "language": "Standard-ML" }, { "code": "package require Tcl 8.5\npackage require Tk\n\n# Farm out grabbing the screen to an external program.\n# If it was just for a Tk window, we'd use the tkimg library instead\nproc grabScreen {image} {\n set pipe [open {|xwd -root -silent | convert xwd:- ppm:-} rb]\n $image put [read $pipe]\n close $pipe\n}\n# Get the RGB data for a particular pixel (global coords)\nproc getPixelAtPoint {x y} {\n set buffer [image create photo]\n grabScreen $buffer\n set data [$image get $x $y]\n image delete $buffer\n return $data\n}\n\n# Demo...\nputs [format \"pixel at mouse: (%d,%d,%d)\" \\\n {*}[getPixelAtPoint {*}[winfo pointerxy .]]]\n", "language": "Tcl" }, { "code": "pxlTest(y, x) © returns boolean\n", "language": "TI-89-BASIC" }, { "code": "Option Explicit\n\nPrivate Type POINTAPI\n x As Long\n y As Long\nEnd Type\n\nPrivate Declare Function GetPixel Lib \"gdi32\" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long) As Long\nPrivate Declare Function GetCursorPos Lib \"USER32\" (lpPoint As POINTAPI) As Long\nPrivate Declare Function GetWindowDC Lib \"USER32\" (ByVal hWnd As Long) As Long\n\nSub Color_of_a_screen_pixel()\nDim myColor As Long\n myColor = Get_Color_Under_Cursor\nEnd Sub\n\nFunction Get_Color_Under_Cursor() As Long\nDim Pos As POINTAPI, lngDc As Long\n\n lngDc = GetWindowDC(0)\n GetCursorPos Pos\n Get_Color_Under_Cursor = GetPixel(lngDc, Pos.x, Pos.y)\nEnd Function\n", "language": "VBA" }, { "code": " Private Function GetPixelColor(ByVal Location As Point) As Color\n\n Dim b As New Bitmap(1, 1)\n Dim g As Graphics = Graphics.FromImage(b)\n\n g.CopyFromScreen(Location, Point.Empty, New Size(1, 1))\n\n Return b.GetPixel(0, 0)\n\n End Function\n", "language": "Visual-Basic-.NET" }, { "code": "import \"dome\" for Window, Process\nimport \"graphics\" for Canvas, Color\nimport \"input\" for Mouse\n\nclass Game {\n static init() {\n Window.title = \"Color of a screen pixel\"\n Canvas.cls(Color.orange) // {255, 163, 0} in the default palette\n }\n\n static update() {\n // report location and color of pixel at mouse cursor\n // when the left button is first pressed\n if (Mouse.isButtonPressed(\"left\")) {\n var x = Mouse.x\n var y = Mouse.y\n var col = Canvas.pget(x, y)\n System.print(\"The color of the pixel at (%(x), %(y)) is %(getRGB(col))\")\n Process.exit(0)\n }\n }\n\n static draw(dt) {}\n\n static getRGB(col) { \"{%(col.r), %(col.g), %(col.b)}\" }\n}\n", "language": "Wren" }, { "code": "code ReadPix=44;\nint Color, X, Y;\nColor:= ReadPix(X, Y);\n", "language": "XPL0" }, { "code": "open window 100, 100\nbackcolor 255, 0, 0\nclear window\ncolor 0, 255, 0\nfill rectangle 50, 50, 75, 75\n\nx = 60 : y = 60\n\ns$ = right$(getbit$(x, y, x, y), 6)\nblue = dec(right$(s$, 2))\ngreen = dec(mid$(s$, 3, 2))\nred = dec(left$(s$, 2))\n\nprint red, \" \", green, \" \", blue\n", "language": "Yabasic" } ]
Color-of-a-screen-pixel
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Color_wheel\nnote: Basic language learning\n", "language": "00-META" }, { "code": ";Task:\nWrite a function to draw a [[wp:HSL_and_HSV|HSV]] color wheel completely with code. \n\nThis is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel &nbsp; (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.\n\n\n\n", "language": "00-TASK" }, { "code": "choose color default color {0, 0, 0, 0}\n", "language": "AppleScript" }, { "code": " 100 LET R = 3.1415926535 / 180\n 110 LET YO = 20\n 120 LET XO = YO\n 130 LET MS = INT (YO * 7 / 8)\n 140 LET O$ = \"1111111111.1111111110.1111011110.1101110110.1101010110.1010101010.0010101001.0010001001.0000100001.0000000001.0000000000\"\n 150 GR\n 160 FOR S = 0 TO MS\n 170 LET D = S / MS\n 180 LET P$ = MID$ (O$, INT (D * 10) * 11 + 1,11)\n 190 LET SY = S\n 200 LET SX = S * 4 / 7\n 210 LET P = 0\n 220 FOR I = 0 TO 360\n 230 LET X = XO + SIN (I * R) * SX\n 240 LET Y = YO + COS (I * R) * SY\n 250 LET W = 15\n 260 IF I > = 30 - 22.4 AND I < 30 + 22.5 THEN COLOR= 9\n 270 IF I > = 75 - 22.5 AND I < 75 + 22.5 THEN COLOR= 13\n 280 IF I > = 120 - 22.5 AND I < 120 + 22.5 THEN COLOR= 12:W = 14\n 290 IF I > = 165 - 22.5 AND I < 165 + 22.5 THEN COLOR= 7:W = 14\n 300 IF I > = 210 - 22.5 AND I < 210 + 22.5 THEN COLOR= 6\n 310 IF I > = 255 - 22.5 AND I < 255 + 22.5 THEN COLOR= 2\n 320 IF I > = 300 - 22.5 AND I < 300 + 22.5 THEN COLOR= 3:W = 11\n 330 IF I > = 345 - 22.5 OR I < 345 + 22.5 - 360 THEN COLOR= 1:W = 11\n 340 IF D < .2 THEN W = 15\n 350 IF RND (1) < D THEN W = 15\n 360 IF VAL ( MID$ (P$,P + 1,1)) THEN COLOR= W\n 370 IF SCRN( X,Y) = 0 THEN PLOT X,Y:P = P + 1: IF P > = 9 THEN P = 0\n 380 NEXT I,S\n", "language": "Applesoft-BASIC" }, { "code": "// colorwheelwidget.cpp\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n double hp = h/60.0;\n double c = s * v;\n double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n double m = v - c;\n double r = 0, g = 0, b = 0;\n if (hp <= 1) {\n r = c;\n g = x;\n } else if (hp <= 2) {\n r = x;\n g = c;\n } else if (hp <= 3) {\n g = c;\n b = x;\n } else if (hp <= 4) {\n g = x;\n b = c;\n } else if (hp <= 5) {\n r = x;\n b = c;\n } else {\n r = c;\n b = x;\n }\n r += m;\n g += m;\n b += m;\n return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n : QWidget(parent) {\n setWindowTitle(tr(\"Color Wheel\"));\n resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n QPainter painter(this);\n painter.setRenderHint(QPainter::Antialiasing);\n const QColor backgroundColor(0, 0, 0);\n const QColor white(255, 255, 255);\n painter.fillRect(event->rect(), backgroundColor);\n const int margin = 10;\n const double diameter = std::min(width(), height()) - 2*margin;\n QPointF center(width()/2.0, height()/2.0);\n QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n diameter, diameter);\n for (int angle = 0; angle < 360; ++angle) {\n QColor color(hsvToRgb(angle, 1.0, 1.0));\n QRadialGradient gradient(center, diameter/2.0);\n gradient.setColorAt(0, white);\n gradient.setColorAt(1, color);\n QBrush brush(gradient);\n QPen pen(brush, 1.0);\n painter.setPen(pen);\n painter.setBrush(brush);\n painter.drawPie(rect, angle * 16, 16);\n }\n}\n", "language": "C++" }, { "code": "// colorwheelwidget.h\n#ifndef COLORWHEELWIDGET_H\n#define COLORWHEELWIDGET_H\n\n#include <QWidget>\n\nclass ColorWheelWidget : public QWidget {\n Q_OBJECT\npublic:\n ColorWheelWidget(QWidget *parent = nullptr);\nprotected:\n void paintEvent(QPaintEvent *event) override;\n};\n\n#endif // COLORWHEELWIDGET_H\n", "language": "C++" }, { "code": "// main.cpp\n#include \"colorwheelwidget.h\"\n#include <QApplication>\n\nint main(int argc, char *argv[]) {\n QApplication app(argc, argv);\n ColorWheelWidget widget;\n widget.show();\n return app.exec();\n}\n", "language": "C++" }, { "code": "// constructor of main window\n// in MainWindow.xaml just create <Image Name=\"imgMain\" />\npublic MainWindow()\n{\n InitializeComponent();\n RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);\n imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);\n // using slider you can change saturation and call DrawHue with different level\n DrawHue(100);\n}\n\nvoid DrawHue(int saturation)\n{\n var bmp = (WriteableBitmap)imgMain.Source;\n\n int centerX = (int)bmp.Width / 2;\n int centerY = (int)bmp.Height / 2;\n int radius = Math.Min(centerX, centerY);\n int radius2 = radius - 40;\n\n bmp.Lock();\n unsafe{\n var buf = bmp.BackBuffer;\n IntPtr pixLineStart;\n for(int y=0; y < bmp.Height; y++){\n pixLineStart = buf + bmp.BackBufferStride * y;\n double dy = (y - centerY);\n for(int x=0; x < bmp.Width; x++){\n double dx = (x - centerX);\n double dist = Math.Sqrt(dx * dx + dy * dy);\n if (radius2 <= dist && dist <= radius) {\n double theta = Math.Atan2(dy, dx);\n double hue = (theta + Math.PI) / (2.0 * Math.PI);\n *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);\n }\n }\n }\n }\n bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));\n bmp.Unlock();\n}\n\nstatic int HSB_to_RGB(int h, int s, int v)\n{\n var rgb = new int[3];\n\n var baseColor = (h + 60) % 360 / 120;\n var shift = (h + 60) % 360 - (120 * baseColor + 60 );\n var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;\n\n //Setting Hue\n rgb[baseColor] = 255;\n rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);\n\n //Setting Saturation\n for (var i = 0; i < 3; i++)\n rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));\n\n //Setting Value\n for (var i = 0; i < 3; i++)\n rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);\n\n return RGB2int(rgb[0], rgb[1], rgb[2]);\n}\n\npublic static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;\n", "language": "C-sharp" }, { "code": "program Color_wheel;\n\n{$APPTYPE CONSOLE}\n\nuses\n Winapi.Windows,\n System.SysUtils,\n Vcl.Graphics,\n System.Math,\n Vcl.Imaging.pngimage;\n\nconst\n TAU = 2 * PI;\n\nfunction HSBtoColor(hue, sat, bri: Double): TColor;\nvar\n f, h: Double;\n u, p, q, t: Byte;\nbegin\n u := Trunc(bri * 255 + 0.5);\n if sat = 0 then\n Exit(rgb(u, u, u));\n\n h := (hue - Floor(hue)) * 6;\n f := h - Floor(h);\n p := Trunc(bri * (1 - sat) * 255 + 0.5);\n q := Trunc(bri * (1 - sat * f) * 255 + 0.5);\n t := Trunc(bri * (1 - sat * (1 - f)) * 255 + 0.5);\n\n case Trunc(h) of\n 0:\n result := rgb(u, t, p);\n 1:\n result := rgb(q, u, p);\n 2:\n result := rgb(p, u, t);\n 3:\n result := rgb(p, q, u);\n 4:\n result := rgb(t, p, u);\n 5:\n result := rgb(u, p, q);\n else\n result := clwhite;\n end;\n\nend;\n\nfunction ColorWheel(Width, Height: Integer): TPngImage;\nvar\n Center: TPoint;\n Radius: Integer;\n x, y: Integer;\n Hue, dy, dx, dist, theta: Double;\n Bmp: TBitmap;\nbegin\n Bmp := TBitmap.Create;\n Bmp.SetSize(Width, Height);\n with Bmp.Canvas do\n begin\n Brush.Color := clWhite;\n FillRect(ClipRect);\n Center := ClipRect.CenterPoint;\n Radius := Center.X;\n if Center.Y < Radius then\n Radius := Center.Y;\n for y := 0 to Height - 1 do\n begin\n dy := y - Center.y;\n for x := 0 to Width - 1 do\n begin\n dx := x - Center.x;\n dist := Sqrt(Sqr(dx) + Sqr(dy));\n if dist <= Radius then\n begin\n theta := ArcTan2(dy, dx);\n Hue := (theta + PI) / TAU;\n Pixels[x, y] := HSBtoColor(Hue, 1, 1);\n end;\n end;\n end;\n end;\n\n Result := TPngImage.Create;\n Result.Assign(Bmp);\n Bmp.Free;\nend;\n\nbegin\n with ColorWheel(500, 500) do\n begin\n SaveToFile('ColorWheel.png');\n Free;\n end;\nend.\n", "language": "Delphi" }, { "code": "proc hsb2rgb hue sat bri . r g b .\n h = (hue - floor hue) * 6\n f = h - floor h\n p = bri * (1 - sat)\n q = bri * (1 - sat * f)\n t = bri * (1 - sat * (1 - f))\n h = floor h\n if h = 0\n r = bri ; g = t ; b = p\n elif h = 1\n r = q ; g = bri ; b = p\n elif h = 2\n r = p ; g = bri ; b = t\n elif h = 3\n r = p ; g = q ; b = bri\n elif h = 4\n r = t ; g = p ; b = bri\n else\n r = bri ; g = p ; b = q\n .\n.\nproc cwheel . .\n for y = 0 to 499\n dy = y - 250\n for x = 0 to 499\n dx = x - 250\n dist = sqrt (dx * dx + dy * dy)\n if dist <= 250\n theta = atan2 dy dx\n hue = (theta + 180) / 360\n hsb2rgb hue (dist / 250) 1 r g b\n color3 r g b\n move x / 5 y / 5\n rect 0.3 0.3\n .\n .\n .\n.\ncwheel\n", "language": "EasyLang" }, { "code": "#include \"fbgfx.bi\"\n\nSub HSVtoRGB(h As Single, s As Integer, v As Integer, Byref r As Integer, Byref g As Integer, Byref b As Integer)\n If s = 0 Then\n r = v\n g = v\n b = v\n Return\n End If\n\n h = h Mod 360\n Dim As Single hue = h\n\n Select Case h\n Case 0f To 51.5f\n hue = ((hue ) * (30f / (51.5f )))\n Case 51.5f To 122f\n hue = ((hue - 51.5f) * (30f / (122f - 51.5f))) + 30\n Case 122f To 142.5f\n hue = ((hue - 122f) * (30f / (142.5f - 122f))) + 60\n Case 142.5f To 165.5f\n hue = ((hue - 142.5f) * (30f / (165.5f - 142.5f))) + 90\n Case 165.5f To 192f\n hue = ((hue - 165.5f) * (30f / (192f - 165.5f))) + 120\n Case 192f To 218.5f\n hue = ((hue - 192f) * (30f / (218.5f - 192f))) + 150\n Case 218.5f To 247f\n hue = ((hue - 218.5f) * (30f / (247f - 218.5f))) + 180\n Case 247f To 275.5f\n hue = ((hue - 247f) * (30f / (275.5f - 247f))) + 210\n Case 275.5f To 302.5f\n hue = ((hue - 275.5f) * (30f / (302.5f - 275.5f))) + 240\n Case 302.5f To 330f\n hue = ((hue - 302.5f) * (30f / (330f - 302.5f))) + 270\n Case 330f To 344.5f\n hue = ((hue - 330f) * (30f / (344.5f - 330f))) + 300\n Case 344.5f To 360f\n hue = ((hue - 344.5f) * (30f / (360f - 344.5f))) + 330\n End Select\n h = hue\n\n h = h Mod 360\n\n Dim As Single h1 = h / 60\n Dim As Integer i = Int(h1)\n Dim As Single f = h1 - i\n Dim As Integer p = v * (255 - s) / 256\n Dim As Integer q = v * (255 - f * s) / 256\n Dim As Integer t = v * (255 - (1 - f) * s) / 256\n\n Select Case As Const i\n Case 0\n r = v\n g = t\n b = p\n Return\n Case 1\n r = q\n g = v\n b = p\n Return\n Case 2\n r = p\n g = v\n b = t\n Return\n Case 3\n r = p\n g = q\n b = v\n Return\n Case 4\n r = t\n g = p\n b = v\n Return\n Case 5\n r = v\n g = p\n b = q\n Return\n End Select\nEnd Sub\n\nConst pi As Single = 4 * Atn(1)\nConst radius = 160\nConst xres = (radius * 2) + 1, yres = xres\n\nScreenres xres, yres, 32\nWindowtitle \"Color wheel\"\n\nDim As Integer r,g,b\nDim As Single dx, dy, dist, angle\n\nDo\n Screenlock\n Cls\n For x As Integer = 0 To (radius * 2) - 1\n For y As Integer = 0 To (radius * 2) - 1\n dx = x - radius\n dy = radius - y\n dist = Sqr(dx * dx + dy * dy)\n If dist < radius Then\n angle = Atan2(dy, dx) * (180/pi)\n If angle < 0 Then angle += 360\n If angle > 360 Then angle -= 360\n HSVtoRGB(angle, (dist / radius) * 255, 255, r, g, b)\n Pset(x, y), Rgb(r, g, b)\n End If\n Next y\n Next x\n\n Screenunlock\nLoop Until Inkey = Chr(27)\n", "language": "FreeBASIC" }, { "code": "_window = 1\nbegin enum output 1\n _colorwheelImageView\nend enum\n\nvoid local fn BuildWindow\n CGRect r = fn CGRectMake( 0, 0, 400, 400 )\n window _window, @\"Programmatic Color Wheel\", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable\n\n r = fn CGRectMake( 20, 20, 360, 360 )\n imageview _colorwheelImageView, YES, , r, NSImageScaleProportionallyUpOrDown, NSImageAlignCenter, NSImageFrameNone, _window\nend fn\n\nlocal fn CIImageToImageRef( ciImage as CIImageRef ) as ImageRef\n CIImageRepRef rep = fn CIImageRepWithCIImage( ciImage )\n CGSize size = fn ImageRepSize( rep )\n ImageRef image = fn ImageWithSize( size )\n ImageAddRepresentation( image, rep )\nend fn = image\n\nlocal fn ColorWheelImage( colorSpace as CGColorSpaceRef, dither as CFNumberRef, radius as CFNumberRef, softness as CFNumberRef, lightness as CFNumberRef ) as CIImageRef\n CIFilterRef filter = fn CIFilterWithName( @\"CIHueSaturationValueGradient\" )\n ObjectSetValueForkey( filter, colorSpace, @\"inputColorSpace\" )\n ObjectSetValueForkey( filter, dither, @\"inputDither\" )\n ObjectSetValueForkey( filter, radius, @\"inputRadius\" )\n ObjectSetValueForkey( filter, softness, @\"inputSoftness\" )\n ObjectSetValueForkey( filter, lightness, @\"inputValue\" )\n CIImageRef outputCIImage = fn CIFilterOutputImage( filter )\nend fn = outputCIImage\n\nlocal fn BuildColorWheel\n CIImageRef colorWheelCIImage = fn ColorWheelImage( fn CGColorSpaceCreateDeviceRGB, @0, @160, @0, @1 )\n ImageRef colorWheelImage = fn CIImageToImageRef( colorWheelCIImage )\n ImageViewSetImage( _colorwheelImageView, colorWheelImage )\nend fn\n\nfn BuildWindow\nfn BuildColorWheel\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "for (var i = 1; i <= 360; i++) {\n for (var j = 0; j < 255; j++) {\n\n var hue = 255*(i/360);\n var saturation = j;\n var value = 255;\n\n var c = make_colour_hsv(hue,saturation,value);\n\n //size of circle determined by how far from the center it is\n //if you just draw them too small the circle won't be full.\n //it will have patches inside it that didn't get filled in with color\n var r = max(1,3*(j/255));\n\n //Math for built-in GMS functions\n //lengthdir_x(len,dir) = +cos(degtorad(direction))*length;\n //lengthdir_y(len,dir) = -sin(degtorad(direction))*length;\n draw_circle_colour(x+lengthdir_x(m_radius*(j/255),i),y+lengthdir_y(m_radius*(j/255),i),r,c,c,false);\n }\n}\n", "language": "GML" }, { "code": "package main\n\nimport (\n \"github.com/fogleman/gg\"\n \"math\"\n)\n\nconst tau = 2 * math.Pi\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n u := int(bri*255 + 0.5)\n if sat == 0 {\n r, g, b = u, u, u\n } else {\n h := (hue - math.Floor(hue)) * 6\n f := h - math.Floor(h)\n p := int(bri*(1-sat)*255 + 0.5)\n q := int(bri*(1-sat*f)*255 + 0.5)\n t := int(bri*(1-sat*(1-f))*255 + 0.5)\n switch int(h) {\n case 0:\n r, g, b = u, t, p\n case 1:\n r, g, b = q, u, p\n case 2:\n r, g, b = p, u, t\n case 3:\n r, g, b = p, q, u\n case 4:\n r, g, b = t, p, u\n case 5:\n r, g, b = u, p, q\n }\n }\n return\n}\n\nfunc colorWheel(dc *gg.Context) {\n width, height := dc.Width(), dc.Height()\n centerX, centerY := width/2, height/2\n radius := centerX\n if centerY < radius {\n radius = centerY\n }\n for y := 0; y < height; y++ {\n dy := float64(y - centerY)\n for x := 0; x < width; x++ {\n dx := float64(x - centerX)\n dist := math.Sqrt(dx*dx + dy*dy)\n if dist <= float64(radius) {\n theta := math.Atan2(dy, dx)\n hue := (theta + math.Pi) / tau\n r, g, b := hsb2rgb(hue, 1, 1)\n dc.SetRGB255(r, g, b)\n dc.SetPixel(x, y)\n }\n }\n }\n}\n\nfunc main() {\n const width, height = 480, 480\n dc := gg.NewContext(width, height)\n dc.SetRGB(1, 1, 1) // set background color to white\n dc.Clear()\n colorWheel(dc)\n dc.SavePNG(\"color_wheel.png\")\n}\n", "language": "Go" }, { "code": "rgbc=: {{1-x*0>.1<.(<.4&-)6|m+y%60}}\nhsv=: 5 rgbc(,\"0 1) 3 rgbc(,\"0) 1 rgbc\ndegrees=: {{180p_1*{:\"1+.^.y}}\nwheel=: {{((1>:|)*|hsv degrees)j./~y%~i:y}}\nrequire'viewmat'\n'rgb' viewmat 256#.<.255*wheel 400\n", "language": "J" }, { "code": "import java.awt.*;\nimport javax.swing.*;\n\npublic class ColorWheel {\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n ColorWheelFrame frame = new ColorWheelFrame();\n frame.setVisible(true);\n }\n });\n }\n\n private static class ColorWheelFrame extends JFrame {\n private ColorWheelFrame() {\n super(\"Color Wheel\");\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n getContentPane().add(new ColorWheelPanel());\n pack();\n }\n }\n\n private static class ColorWheelPanel extends JComponent {\n private ColorWheelPanel() {\n setPreferredSize(new Dimension(400, 400));\n }\n public void paint(Graphics g) {\n Graphics2D g2 = (Graphics2D)g;\n int w = getWidth();\n int h = getHeight();\n int margin = 10;\n int radius = (Math.min(w, h) - 2 * margin)/2;\n int cx = w/2;\n int cy = h/2;\n float[] dist = {0.F, 1.0F};\n g2.setColor(Color.BLACK);\n g2.fillRect(0, 0, w, h);\n for (int angle = 0; angle < 360; ++angle) {\n Color color = hsvToRgb(angle, 1.0, 1.0);\n Color[] colors = {Color.WHITE, color};\n RadialGradientPaint paint = new RadialGradientPaint(cx, cy,\n radius, dist, colors);\n g2.setPaint(paint);\n g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,\n angle, 1);\n }\n }\n }\n\n private static Color hsvToRgb(int h, double s, double v) {\n double hp = h/60.0;\n double c = s * v;\n double x = c * (1 - Math.abs(hp % 2.0 - 1));\n double m = v - c;\n double r = 0, g = 0, b = 0;\n if (hp <= 1) {\n r = c;\n g = x;\n } else if (hp <= 2) {\n r = x;\n g = c;\n } else if (hp <= 3) {\n g = c;\n b = x;\n } else if (hp <= 4) {\n g = x;\n b = c;\n } else if (hp <= 5) {\n r = x;\n b = c;\n } else {\n r = c;\n b = x;\n }\n r += m;\n g += m;\n b += m;\n return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));\n }\n}\n", "language": "Java" }, { "code": "using Gtk, Graphics, Colors\n\nconst win = GtkWindow(\"Color Wheel\", 450, 450) |> (const can = @GtkCanvas())\nset_gtk_property!(can, :expand, true)\n\n@guarded draw(can) do widget\n ctx = getgc(can)\n h = height(can)\n w = width(can)\n center = (x = w / 2, y = h / 2)\n anglestep = 1/w\n for θ in 0:0.1:360\n rgb = RGB(HSV(θ, 1, 1))\n set_source_rgb(ctx, rgb.r, rgb.g, rgb.b)\n line_to(ctx, center...)\n arc(ctx, center.x, center.y, w/2.2, 2π * θ / 360, anglestep)\n line_to(ctx, center...)\n stroke(ctx)\n end\nend\n\nshow(can)\nconst condition = Condition()\nendit(w) = notify(condition)\nsignal_connect(endit, win, :destroy)\nwait(condition)\n", "language": "Julia" }, { "code": "// Version 1.2.41\n\nimport java.awt.Color\nimport java.awt.Graphics\nimport java.awt.image.BufferedImage\nimport java.io.File\nimport javax.imageio.ImageIO\nimport kotlin.math.*\n\nclass BasicBitmapStorage(width: Int, height: Int) {\n val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)\n\n fun fill(c: Color) {\n val g = image.graphics\n g.color = c\n g.fillRect(0, 0, image.width, image.height)\n }\n\n fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())\n\n fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))\n\n fun colorWheel() {\n val centerX = image.width / 2\n val centerY = image.height / 2\n val radius = minOf(centerX, centerY)\n for (y in 0 until image.height) {\n val dy = (y - centerY).toDouble()\n for (x in 0 until image.width) {\n val dx = (x - centerX).toDouble()\n val dist = sqrt(dx * dx + dy * dy)\n if (dist <= radius) {\n val theta = atan2(dy, dx)\n val hue = (theta + PI) / (2.0 * PI)\n val rgb = Color.HSBtoRGB(hue.toFloat(), 1.0f, 1.0f)\n setPixel(x, y, Color(rgb))\n }\n }\n }\n }\n}\n\nfun main(args: Array<String>) {\n val bbs = BasicBitmapStorage(480, 480)\n with (bbs) {\n fill(Color.white)\n colorWheel()\n val cwFile = File(\"Color_wheel.png\")\n ImageIO.write(image, \"png\", cwFile)\n }\n}\n", "language": "Kotlin" }, { "code": "local function hsv_to_rgb (h, s, v) -- values in ranges: [0, 360], [0, 1], [0, 1]\n local r = math.min (math.max (3*math.abs (((h )/180)%2-1)-1, 0), 1)\n local g = math.min (math.max (3*math.abs (((h -120)/180)%2-1)-1, 0), 1)\n local b = math.min (math.max (3*math.abs (((h +120)/180)%2-1)-1, 0), 1)\n local k1 = v*(1-s)\n local k2 = v - k1\n return k1+k2*r, k1+k2*g, k1+k2*b -- values in ranges: [0, 1], [0, 1], [0, 1]\nend\n\nfunction love.load()\n local w, h, r = 256, 256, 128-0.5\n local cx, cy = w/2, h/2\n canvas = love.graphics.newCanvas ()\n love.graphics.setCanvas(canvas)\n for x = 0, w do\n for y = 0, h do\n local dx, dy = x-cx, y-cy\n if dx*dx + dy*dy <= r*r then\n local h = math.deg(math.atan2(dy, dx))\n local s = (dx*dx + dy*dy)^0.5/r\n local v = 1\n love.graphics.setColor (hsv_to_rgb (h, s, v))\n love.graphics.points (x, y)\n end\n end\n end\n love.graphics.setCanvas()\nend\n\nfunction love.draw()\n love.graphics.setColor (1,1,1)\n love.graphics.draw (canvas)\nend\n", "language": "Lua" }, { "code": "Module Check {\n \\\\ we use an internal object for Math functions (here for Atan2)\n Declare Math Math\n Const tau=2*Pi, Center=2\n \\\\ change console size, and center it ( using ;) to current monitor\n Window 12, 800*twipsX,600*twipsY;\n \\\\ actual size maybe less (so can fit text exactly)\n Double ' Double height characters\n Report Center, \"Color wheel\"\n Normal ' restore to normal\n Atan2=Lambda Math (a, b) ->{\n Method Math, \"Atan2\", a, b As ret\n =ret\n }\n \\\\ brightness=1 for this program\n hsb2rgb=Lambda (hue, sat) ->{\n If sat == 0 Then {\n = 255, 255, 255\n } Else {\n h=frac(hue+1)*6\n f = frac(h)\n p = Int((1-sat)*255 + 0.5)\n q = Int((1-sat*f)*255 + 0.5)\n t = Int((1-sat*(1-f))*255 + 0.5)\n Select Case Int(h)\n Case 1\n = q, 255, p\n Case 2\n = p, 255, t\n Case 3\n = p, q, 255\n Case 4\n = t, p, 255\n Case 5\n = 255, p, q\n Else Case\n = 255, t, p\n End Select\n }\n }\n Let OffsetX=X.twips/2-128*TwipsX, OffsetY=Y.twips/2-128*TwipsY\n \\\\ a pixel has a size of TwipsX x TwipsY\n OffsetX=(OffsetX div TwipsX)*TwipsX\n OffsetY=(OffsetY div TwipsY)*TwipsY\n \\\\ We set hsb2rgb, OffsetX, OffsetY as closures to PrintPixel\n \\\\ We send to stack the R G B values using Stack ! array\n \\\\ hsb2rgb() return an array of values\n \\\\ we pop these values using Number\n PrintPixel = Lambda hsb2rgb, OffsetX, OffsetY (x,y, theta, sat) -> {\n Stack ! hsb2rgb(theta,sat)\n PSet Color(number, number, number), x*TwipsX+offsetX, y*TwipsY+offsetY\n }\n \\\\ set Atan2, tau as closures to HueCircle\n \\\\ we can rotate/flip the wheel by changing signs in Atan2() and\n \\\\ by changing order of arguments (dx,dy) or (dy,dx). 8 combinations\n HueCircle= Lambda Atan2, tau (PrintPixel) -> {\n Let c_width=256, c_height=256\n Let cx=c_width/2, cy=c_height/2\n Let radius=If(cx<=cy->cx, cy)\n c_width--\n c_height--\n dy=-cy\n For y=0 To c_height {\n dy++ : dy2=dy*dy : dx=-cx\n For x=0 To c_width {\n dx++ : dist=Sqrt(dx^2+dy2)\n If dist>radius Then continue\n Call PrintPixel(x,y, Atan2(dx, -dy)/tau, dist/radius)\n }\n }\n }\n Call HueCircle(PrintPixel)\n Scr$=\"\" ' we use this string to load an image\n Move 0,0\n \\\\ scale.x, scale.y are twips height and width, of current layer\n Copy scale.x, scale.y to Scr$\n Clipboard Scr$ ' save window to clipboard\n}\nCheck\n", "language": "M2000-Interpreter" }, { "code": "r = 100;\nImage[Table[\n If[x^2 + y^2 <= r^2,\n angle = Mod[ArcTan[N@x, y]/(2 Pi), 1];\n List @@ RGBColor[Hue[angle, Sqrt[x^2 + y^2]/N[r], 1.0]]\n ,\n {1, 1, 1}\n ], {x, -r, r}, {y, -r, r}]\n ]\n", "language": "Mathematica" }, { "code": "import math\n\nimport imageman\n\n#---------------------------------------------------------------------------------------------------\n\nfunc hsvToRgb(h, s, v: float): ColorRGBU =\n ## Convert HSV values to RGB values.\n\n let hp = h / 60\n let c = s * v\n let x = c * (1 - abs(hp mod 2 - 1))\n let m = v - c\n var r, g, b = 0.0\n if hp <= 1:\n r = c\n g = x\n elif hp <= 2:\n r = x\n g = c\n elif hp <= 3:\n g = c\n b = x\n elif hp <= 4:\n g = x\n b= c\n elif hp <= 5:\n r = x\n b = c\n else:\n r = c\n b = x\n r += m\n g += m\n b += m\n result = ColorRGBU [byte(r * 255), byte(g * 255), byte(b * 255)]\n\n#---------------------------------------------------------------------------------------------------\n\nfunc buildColorWheel(image: var Image) =\n ## Build a color wheel into the image.\n\n const Margin = 10\n let diameter = min(image.w, image.h) - 2 * Margin\n let xOffset = (image.w - diameter) div 2\n let yOffset = (image.h - diameter) div 2\n let radius = diameter / 2\n\n for x in 0..diameter:\n let rx = x.toFloat - radius\n for y in 0..diameter:\n let ry = y.toFloat - radius\n let r = hypot(rx, ry) / radius\n if r > 1: continue\n let a = 180 + arctan2(ry, -rx).radToDeg()\n image[x + xOffset, y + yOffset] = hsvToRgb(a, r, 1)\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nconst\n Side = 400\n Output = \"color_wheel.png\"\n\nvar image = initImage[ColorRGBU](Side, Side)\nimage.buildColorWheel()\n\nimage.savePNG(Output, compression = 9)\n", "language": "Nim" }, { "code": "use Imager;\nuse Math::Complex qw(cplx i pi);\n\nmy ($width, $height) = (300, 300);\nmy $center = cplx($width/2, $height/2);\n\nmy $img = Imager->new(xsize => $width,\n ysize => $height);\n\nforeach my $y (0 .. $height - 1) {\n foreach my $x (0 .. $width - 1) {\n\n my $vec = $center - $x - $y * i;\n my $mag = 2 * abs($vec) / $width;\n my $dir = (pi + atan2($vec->Re, $vec->Im)) / (2 * pi);\n\n $img->setpixel(x => $x, y => $y,\n color => {hsv => [360 * $dir, $mag, $mag < 1 ? 1 : 0]});\n }\n}\n\n$img->write(file => 'color_wheel.png');\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Colour_wheel.exw\n -- =============================\n --\n -- Note: Made non-resizeable since maximising this is far too slow.\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">title</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"Colour wheel\"</span>\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas</span>\n <span style=\"color: #004080;\">cdCanvas</span> <span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cdcanvas</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">redraw_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000080;font-style:italic;\">/*posx*/</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">/*posy*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetIntInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"DRAWSIZE\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasActivate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">radius</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">min</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">cx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">cy</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">w</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">h</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">rx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">ry</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">y</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">cy</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sqrt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">rx</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">rx</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">ry</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">ry</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">radius</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\"><=</span> <span style=\"color: #000000;\">1.0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">hue</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">((</span><span style=\"color: #7060A8;\">atan2</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ry</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">rx</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #004600;\">PI</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1.0</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">2.0</span>\n <span style=\"color: #7060A8;\">cdCanvasPixel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">hsv_to_rgb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hue</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">cdCanvasFlush</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">map_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cdcanvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_IUP</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cddbuffer</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_DBUFFER</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cdcanvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasSetBackground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_WHITE</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasSetForeground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_MAGENTA</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">canvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"RASTERSIZE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"300x300\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"MAP_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"map_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`TITLE=\"%s\",RESIZE=NO`</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">title</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"ACTION\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"redraw_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupShowXY</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">IUP_CENTER</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">IUP_CENTER</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "To draw the color wheel:\n Start with the red color.\n Turn right 80 points.\n Loop.\n If the user clicks on the screen, break.\n Move to the center of the screen.\n Draw a line 2 inches long.\n Refresh the screen.\n Change the current hue by 10 points.\n Turn right 10 points.\n Add 1 to a count.\n If the count is 384, break. \\ Plain English uses a circle divided into 384 degrees\n Repeat.\n Start in the middle of the screen facing north minus 80 points.\n Use medium-sized letters.\n Write \"RED......YELLOW.....GREEN......CYAN......BLUE.....MAGENTA......\" with the white pen 2-1/4 inches from the screen's center.\n Refresh the screen.\n Shut down.\n", "language": "Plain-English" }, { "code": "size(300, 300);\nbackground(0);\nfloat radius = min(width, height) / 2.0;\nfloat cx = width / 2;\nfloat cy = width / 2;\nfor (int x = 0; x < width; x++) {\n for (int y = 0; y < width; y++) {\n float rx = x - cx;\n float ry = y - cy;\n float s = sqrt(sq(rx) + sq(ry)) / radius;\n if (s <= 1.0) {\n float h = ((atan2(ry, rx) / PI) + 1.0) / 2.0;\n colorMode(HSB);\n color c = color(int(h * 255), int(s * 255), 255);\n set(x, y, c);\n }\n }\n}\n", "language": "Processing" }, { "code": "size(300, 300)\nbackground(0)\nradius = min(width, height) / 2.0\ncx, cy = width / 2, width / 2\nfor x in range(width):\n for y in range(height):\n rx = x - cx\n ry = y - cy\n s = sqrt(rx ** 2 + ry ** 2) / radius\n if s <= 1.0:\n h = ((atan2(ry, rx) / PI) + 1.0) / 2.0\n colorMode(HSB)\n c = color(int(h * 255), int(s * 255), 255)\n set(x, y, c) # note set() used as Processing set() not as Python set()\n", "language": "Processing-Python-mode" }, { "code": "from PIL import Image\nimport colorsys\nimport math\n\nif __name__ == \"__main__\":\n\n im = Image.new(\"RGB\", (300,300))\n radius = min(im.size)/2.0\n cx, cy = im.size[0]/2, im.size[1]/2\n pix = im.load()\n\n for x in range(im.width):\n for y in range(im.height):\n rx = x - cx\n ry = y - cy\n s = (rx ** 2.0 + ry ** 2.0) ** 0.5 / radius\n if s <= 1.0:\n h = ((math.atan2(ry, rx) / math.pi) + 1.0) / 2.0\n rgb = colorsys.hsv_to_rgb(h, s, 1.0)\n pix[x,y] = tuple([int(round(c*255.0)) for c in rgb])\n\n im.show()\n", "language": "Python" }, { "code": "#lang racket\n\n(require racket/draw\n colors)\n\n(define DIM 500)\n(define target (make-bitmap DIM DIM))\n(define dc (new bitmap-dc% [bitmap target]))\n(define radius 200)\n(define center (/ DIM 2))\n\n(define (atan2 y x) (if (= 0 y x) 0 (atan y x)))\n\n(for* ([x (in-range DIM)]\n [y (in-range DIM)]\n [rx (in-value (- x center))]\n [ry (in-value (- y center))]\n [s (in-value (/ (sqrt (+ (sqr rx) (sqr ry))) radius))]\n #:when (<= s 1))\n (define h (* 0.5 (+ 1 (/ (atan2 ry rx) pi))))\n (send dc set-pen (hsv->color (hsv (if (= 1 h) 0 h) s 1)) 1 'solid)\n (send dc draw-point x y))\n\ntarget\n", "language": "Racket" }, { "code": "use Image::PNG::Portable;\n\nmy ($w, $h) = 300, 300;\n\nmy $out = Image::PNG::Portable.new: :width($w), :height($h);\n\nmy $center = $w/2 + $h/2*i;\n\ncolor-wheel($out);\n\n$out.write: 'Color-wheel-perl6.png';\n\nsub color-wheel ( $png ) {\n ^$w .race.map: -> $x {\n for ^$h -> $y {\n my $vector = $center - $x - $y*i;\n my $magnitude = $vector.abs * 2 / $w;\n my $direction = ( π + atan2( |$vector.reals ) ) / τ;\n $png.set: $x, $y, |hsv2rgb( $direction, $magnitude, $magnitude < 1 );\n }\n }\n}\n\nsub hsv2rgb ( $h, $s, $v ){\n my $c = $v * $s;\n my $x = $c * (1 - abs( (($h*6) % 2) - 1 ) );\n my $m = $v - $c;\n (do given $h {\n when 0..^1/6 { $c, $x, 0 }\n when 1/6..^1/3 { $x, $c, 0 }\n when 1/3..^1/2 { 0, $c, $x }\n when 1/2..^2/3 { 0, $x, $c }\n when 2/3..^5/6 { $x, 0, $c }\n when 5/6..1 { $c, 0, $x }\n } ).map: ((*+$m) * 255).Int\n}\n", "language": "Raku" }, { "code": "#===================================================================#\n# Sample: Color Wheel\n# Author: Gal Zsolt, Bert Mariani, Ilir Liburn & Mahmoud Fayed\n#===================================================================#\n\nload \"guilib.ring\"\n\nxWidth = 400\nyHeight = 400\n\nMyApp = new qapp\n{\n win1 = new qwidget()\n { setwindowtitle(\"ColorWheel-FastDraw\")\n setgeometry(500,150,xWidth,yHeight)\n\n Canvas = new qlabel(win1)\n { ### daVinci paints the MonaLisa on the Canvas\n MonaLisa = new qPixMap2( xWidth, yHeight)\n color = new qcolor(){ setrgb(255,255,255,0) }\n pen = new qpen() { setwidth(1) }\n MonaLisa.fill(color)\n\n daVinci = new qpainter()\n { begin(MonaLisa)\n #endpaint() ### This will Stop the Painting. For Animation comment it out\n }\n\n setPixMap(MonaLisa)\n }\n\n show()\n }\n\n ColorWheel()\n exec()\n}\n\n//=====================\n\nFunc colorWheel\n\n #=====================================================================#\n ? \"Start Processing...\"\n t1 = clock()\n ? \"Clock : \" + t1\n #=====================================================================#\n\n aList = []\n pi = 3.14159265359\n diameter = pi * 2\n radius = yHeight / 2\n v = 1 // value/brightness 1 to 100 1=bright 0=dark\n\n for i = 1 to xWidth\n iradius = i - radius\n p = pow( iradius, 2)\n\n for j = 1 to yHeight\n\n h = (atan2( iradius, j-radius ) + pi ) / diameter // hue/color 1 to 360\n s = sqrt( p + pow( j-radius, 2)) / radius // saturation/intensity 1 to 100\n\n if s <= 1 and h <= 1\n aList + [i,j,h,s,v,1]\n ok\n\n next\n next\n\n #=====================================================================#\n ? \"Start drawing...\"\n t2 = clock()\n ? \"Clock : \" + t2\n #=====================================================================#\n\n daVinci.drawHSVFList(aList)\n Canvas.setPixMap(MonaLisa)\n\n #=====================================================================#\n ? \"Done...\"\n t3 = clock()\n ? \"Clock : \" + t3\n #=====================================================================#\n ? \"Processing Time: \" + ( (t2-t1)/ClocksPerSecond() ) + \" seconds \"\n ? \"Drawing Time: \" + ( (t3-t2)/ClocksPerSecond() ) + \" seconds \"\n ? \"Total Time: \" + ( (t3-t1)/ClocksPerSecond() ) + \" seconds \"\n #=====================================================================#\n\n return\n\n//==================\n", "language": "Ring" }, { "code": "def settings\n size(300, 300)\nend\n\ndef setup\n sketch_title 'Color Wheel'\n background(0)\n radius = width / 2.0\n center = width / 2\n grid(width, height) do |x, y|\n rx = x - center\n ry = y - center\n sat = Math.hypot(rx, ry) / radius\n if sat <= 1.0\n hue = ((Math.atan2(ry, rx) / PI) + 1) / 2.0\n color_mode(HSB)\n col = color((hue * 255).to_i, (sat * 255).to_i, 255)\n set(x, y, col)\n end\n end\nend\n", "language": "Ruby" }, { "code": "' -----------------------------------\n' color wheel\n' -----------------------------------\nglobal pi\npi = 22 / 7\nsteps = 1\n\ngraphic #g, 525, 525\n\n\nfor x =0 to 525 step steps\n for y =0 to 525 step steps\n angle = atan2(y - 250, x - 250) * 360 / 2 / pi ' full degrees....\n sector = int(angle / 60) ' 60 degree sectors (0 to 5)\n slope = (angle mod 60) /60 * 255 ' 1 degree sectors.\n\n if sector = 0 then col$ = \"255 \"; str$( int( slope)); \" 0\"\n if sector = 1 then col$ = str$(int(256 - slope)); \" 255 0\"\n if sector = 2 then col$ = \"0 255 \"; str$( int( slope))\n if sector = 3 then col$ = \"0 \"; str$( int( 256 -slope)); \" 255\"\n if sector = 4 then col$ = str$(int(slope)); \" 0 255\"\n if sector = 5 then col$ = \"255 0 \"; str$( int( 256 -slope))\n\n red = val( word$( col$, 1))\n grn = val( word$( col$, 2))\n blu = val( word$( col$, 3))\n p = ((x -270)^2 +(y -270)^2)^0.5 / 250\n r = min(255,p * red)\n g = min(255,p * grn)\n b = min(255,p * blu)\n if p > 1 then #g \"color white\" else #g color(r,g,b)\n #g \"set \"; x; \" \"; y\n next y\nnext x\nrender #g\nend\n\nfunction atan2(y,x)\nif (x = 0) and (y <> 0) then\n r$ = \"Y\"\n if y > 0 then atan2 = pi /2\n if y < 0 then atan2 = 3 * pi /2\nend if\n\nif y = 0 and (x <> 0) then\n r$ = \"Y\"\n if x > 0 then atan2 = 0\n if x < 0 then atan2 = pi\nend if\n\nIf r$ <> \"Y\" then\n if x = 0 and y = 0 then\n atan2 = 0\n else\n baseAngle = atn(abs(y) / abs(x))\n if x > 0 then\n if y > 0 then atan2 = baseAngle\n If y < 0 then atan2 = 2 * pi - baseAngle\n end if\n if x < 0 then\n If y > 0 then atan2 = pi - baseAngle\n If y < 0 then atan2 = pi + baseAngle\n end if\n end if\nend if\nend function\n", "language": "Run-BASIC" }, { "code": "// [dependencies]\n// image = \"0.23\"\n\nuse image::error::ImageResult;\nuse image::{Rgb, RgbImage};\n\nfn hsv_to_rgb(h: f64, s: f64, v: f64) -> Rgb<u8> {\n let hp = h / 60.0;\n let c = s * v;\n let x = c * (1.0 - (hp % 2.0 - 1.0).abs());\n let m = v - c;\n let mut r = 0.0;\n let mut g = 0.0;\n let mut b = 0.0;\n if hp <= 1.0 {\n r = c;\n g = x;\n } else if hp <= 2.0 {\n r = x;\n g = c;\n } else if hp <= 3.0 {\n g = c;\n b = x;\n } else if hp <= 4.0 {\n g = x;\n b = c;\n } else if hp <= 5.0 {\n r = x;\n b = c;\n } else {\n r = c;\n b = x;\n }\n r += m;\n g += m;\n b += m;\n Rgb([(r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8])\n}\n\nfn write_color_wheel(filename: &str, width: u32, height: u32) -> ImageResult<()> {\n let mut image = RgbImage::new(width, height);\n let margin = 10;\n let diameter = std::cmp::min(width, height) - 2 * margin;\n let xoffset = (width - diameter) / 2;\n let yoffset = (height - diameter) / 2;\n let radius = diameter as f64 / 2.0;\n for x in 0..=diameter {\n let rx = x as f64 - radius;\n for y in 0..=diameter {\n let ry = y as f64 - radius;\n let r = ry.hypot(rx) / radius;\n if r > 1.0 {\n continue;\n }\n let a = 180.0 + ry.atan2(-rx).to_degrees();\n image.put_pixel(x + xoffset, y + yoffset, hsv_to_rgb(a, r, 1.0));\n }\n }\n image.save(filename)\n}\n\nfn main() {\n match write_color_wheel(\"color_wheel.png\", 400, 400) {\n Ok(()) => {}\n Err(error) => eprintln!(\"{}\", error),\n }\n}\n", "language": "Rust" }, { "code": "require('Imager')\n\nvar (width, height) = (300, 300)\nvar center = Complex(width/2 , height/2)\n\nvar img = %O<Imager>.new(xsize => width, ysize => height)\n\nfor y=(^height), x=(^width) {\n var vector = (center - x - y.i)\n var magnitude = (vector.abs * 2 / width)\n var direction = ((Num.pi + atan2(vector.real, vector.imag)) / Num.tau)\n img.setpixel(x => x, y => y,\n color => Hash(hsv => [360*direction, magnitude, magnitude < 1 ? 1 : 0])\n )\n}\n\nimg.write(file => 'color_wheel.png')\n", "language": "Sidef" }, { "code": "' Runs on iOS\nGET SCREEN SIZE sw,sh\nxmax=0.45*3/7*(sw+sh)\nx0=sw/2!y0=sh/2\ntwopi=2*3.1415926\nGRAPHICS\nGRAPHICS CLEAR\nDIM triX(1000), triY(1000)\ntriX(0)=x0 ! triY(0)=y0\nsteps=INT(1^2*360)+1\ndAngle=twopi/steps\ndAngle2=dAngle/2\nREFRESH OFF\nFOR i=0 TO steps-1\n pal(i/steps+TintOffset)\n ANGLE=i*dAngle\n FILL COLOR pal.r,pal.g,pal.b\n DRAW COLOR pal.r,pal.g,pal.b\n x=x0+(xmax-radius)*COS(ANGLE)\n y=y0-(xmax-radius)*SIN(ANGLE)\n k=0\n FOR j=-dAngle2 TO dAngle2 STEP 0.02\n k+=1\n triX(k)=x0+xmax*COS(ANGLE+j)\n triY(k)=y0-xmax*SIN(ANGLE+j)\n NEXT j\n k+=1\n triX(k)=x0+xmax*COS(ANGLE+dAngle2)\n triY(k)=y0-xmax*SIN(ANGLE+dAngle2)\n DRAW POLY triX,triY COUNT k+1\n FILL POLY triX,triY COUNT k+1\nNEXT i\nREFRESH ON\nEND\n\nDEF pal(tint)\ntint=tint*360\nh=(tint%360)/60 ! f=FRACT(h) ! z=1-f ! ic=FLOOR(h)+1\nON ic GOTO s1,s2,s3,s4,s5,s6\n s1: r=1 ! g=f ! b=0 ! GOTO done\n s2: r=z ! g=1 ! b=0 ! GOTO done\n s3: r=0 ! g=1 ! b=f ! GOTO done\n s4: r=0 ! g=z ! b=1 ! GOTO done\n s5: r=f ! g=0 ! b=1 ! GOTO done\n s6: r=1 ! g=0 ! b=z ! done:\nEND DEF\n", "language": "Smart-BASIC" }, { "code": "public class Example: Gtk.Application {\n private Gtk.ApplicationWindow window;\n private Gtk.DrawingArea drawing_area;\n public Example() {\n Object(application_id: \"my.application\", flags: ApplicationFlags.FLAGS_NONE);\n this.activate.connect(() => {\n window = new Gtk.ApplicationWindow(this);\n drawing_area = new Gtk.DrawingArea();\n drawing_area.set_draw_func(draw_circle);\n window.set_child(drawing_area);\n window.present();\n });\n }\n\n private void draw_circle(Gtk.DrawingArea area, Cairo.Context cr, int width, int height) {\n int centerx = width / 2;\n int centery = height / 2;\n double anglestep = 1.0 / width;\n for (float theta = (float) 0.0; theta < 360; theta += (float) 0.1) {\n float r;\n float g;\n float b;\n Gtk.hsv_to_rgb(theta / (float) 360.0, 1, 1, out r, out g, out b);\n cr.set_source_rgb(r, g, b);\n cr.line_to(centerx, centery);\n cr.arc(centerx, centery, ((double) width) / 2.2, GLib.Math.PI * 2 * theta / 360.0, anglestep);\n cr.line_to(centerx, centery);\n cr.stroke();\n }\n }\n\n public static int main(string[] argv) {\n var app = new Example();\n return app.run(argv);\n }\n}\n", "language": "Vala" }, { "code": "Option explicit\n\nClass ImgClass\n Private ImgL,ImgH,ImgDepth,bkclr,loc,tt\n private xmini,xmaxi,ymini,ymaxi,dirx,diry\n public ImgArray() 'rgb in 24 bit mode, indexes to palette in 8 bits\n private filename\n private Palette,szpal\n\n public property get xmin():xmin=xmini:end property\n public property get ymin():ymin=ymini:end property\n public property get xmax():xmax=xmaxi:end property\n public property get ymax():ymax=ymaxi:end property\n public property let depth(x)\n if x<>8 and x<>32 then err.raise 9\n Imgdepth=x\n end property\n\n public sub set0 (x0,y0) 'sets the new origin (default tlc). The origin does'nt work if ImgArray is accessed directly\n if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9\n xmini=-x0\n ymini=-y0\n xmaxi=xmini+imgl-1\n ymaxi=ymini+imgh-1\n end sub\n\n 'constructor\n Public Default Function Init(name,w,h,orient,dep,bkg,mipal)\n 'offx, offy posicion de 0,0. si ofx+ , x se incrementa de izq a der, si offy+ y se incrementa de abajo arriba\n dim i,j\n ImgL=w\n ImgH=h\n tt=timer\n loc=getlocale\n ' not useful as we are not using SetPixel and accessing ImgArray directly\n set0 0,0 'origin blc positive up and right\n redim imgArray(ImgL-1,ImgH-1)\n bkclr=bkg\n if bkg<>0 then\n for i=0 to ImgL-1\n for j=0 to ImgH-1\n imgarray(i,j)=bkg\n next\n next\n end if\n Select Case orient\n Case 1: dirx=1 : diry=1\n Case 2: dirx=-1 : diry=1\n Case 3: dirx=-1 : diry=-1\n Case 4: dirx=1 : diry=-1\n End select\n filename=name\n ImgDepth =dep\n 'load user palette if provided\n if imgdepth=8 then\n loadpal(mipal)\n end if\n set init=me\n end function\n\n private sub loadpal(mipale)\n if isarray(mipale) Then\n palette=mipale\n szpal=UBound(mipale)+1\n Else\n szpal=256\n 'Default palette recycled from ATARI\n 'removed\n\n, not relevant\n End if\n End Sub\n\n\n 'class termination writes it to a BMP file and displays it\n 'if an error happens VBS terminates the class before exiting so the BMP is displayed the same\n Private Sub Class_Terminate\n\n if err<>0 then wscript.echo \"Error \" & err.number\n wscript.echo \"copying image to bmp file\"\n savebmp\n wscript.echo \"opening \" & filename & \" with your default bmp viewer\"\n CreateObject(\"Shell.Application\").ShellExecute filename\n wscript.echo timer-tt & \" iseconds\"\n End Sub\n\n function long2wstr( x) 'falta muy poco!!!\n dim k1,k2,x1\n k1= (x and &hffff&)' or (&H8000& And ((X And &h8000&)<>0)))\n k2=((X And &h7fffffff&) \\ &h10000&) Or (&H8000& And (x<0))\n long2wstr=chrw(k1) & chrw(k2)\n end function\n\n function int2wstr(x)\n int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))\n End Function\n\n\n Public Sub SaveBMP\n 'Save the picture to a bmp file\n Dim s,ostream, x,y,loc\n\n const hdrs=54 '14+40\n dim bms:bms=ImgH* 4*(((ImgL*imgdepth\\8)+3)\\4) 'bitmap size including padding\n dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0\n\n with CreateObject(\"ADODB.Stream\") 'auxiliary ostream, it creates an UNICODE with bom stream in memory\n .Charset = \"UTF-16LE\" 'o \"UTF16-BE\"\n .Type = 2' adTypeText\n .open\n\n 'build a header\n 'bmp header: VBSCript does'nt have records nor writes binary values to files, so we use strings of unicode chars!!\n 'BMP header\n .writetext ChrW(&h4d42) ' 0 \"BM\" 4d42\n .writetext long2wstr(hdrs+palsize+bms) ' 2 fiesize\n .writetext long2wstr(0) ' 6 reserved\n .writetext long2wstr (hdrs+palsize) '10 image offset\n 'InfoHeader\n .writetext long2wstr(40) '14 infoheader size\n .writetext long2wstr(Imgl) '18 image length\n .writetext long2wstr(imgh) '22 image width\n .writetext int2wstr(1) '26 planes\n .writetext int2wstr(imgdepth) '28 clr depth (bpp)\n .writetext long2wstr(&H0) '30 compression used 0= NOCOMPR\n\n .writetext long2wstr(bms) '34 imgsize\n .writetext long2wstr(&Hc4e) '38 bpp hor\n .writetext long2wstr(&hc43) '42 bpp vert\n .writetext long2wstr(szpal) '46 colors in palette\n .writetext long2wstr(&H0) '50 important clrs 0=all\n\n 'write bitmap\n 'precalc data for orientation\n Dim x1,x2,y1,y2\n If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1\n If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1\n\n Select Case imgdepth\n\n Case 32\n For y=y1 To y2 step diry\n For x=x1 To x2 Step dirx\n 'writelong fic, Pixel(x,y)\n .writetext long2wstr(Imgarray(x,y))\n Next\n Next\n\n Case 8\n 'palette\n For x=0 to szpal-1\n .writetext long2wstr(palette(x)) '52\n Next\n 'image\n dim pad:pad=ImgL mod 4\n For y=y1 to y2 step diry\n For x=x1 To x2 step dirx*2\n .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))\n Next\n 'line padding\n if pad and 1 then .writetext chrw(ImgArray(x2,y))\n if pad >1 then .writetext chrw(0)\n Next\n\n Case Else\n WScript.Echo \"ColorDepth not supported : \" & ImgDepth & \" bits\"\n End Select\n\n 'use a second stream to save to file starting past the BOM the first ADODB.Stream has added\n Dim outf:Set outf= CreateObject(\"ADODB.Stream\")\n outf.Type = 1 ' adTypeBinary\n outf.Open\n .position=2 'remove bom (1 wchar)\n .CopyTo outf\n .close\n outf.savetofile filename,2 'adSaveCreateOverWrite\n outf.close\n end with\n End Sub\nend class\n\n\n\nfunction hsv2rgb( Hue, Sat, Value) 'hue 0-360 0-ro 120-ver 240-az ,sat 0-100,value 0-100\n dim Angle, Radius,Ur,Vr,Wr,Rdim\n dim r,g,b, rgb\n Angle = (Hue-150) *0.01745329251994329576923690768489\n Ur = Value * 2.55\n Radius = Ur * tan(Sat *0.01183199)\n Vr = Radius * cos(Angle) *0.70710678 'sqrt(1/2)\n Wr = Radius * sin(Angle) *0.40824829 'sqrt(1/6)\n r = (Ur - Vr - Wr)\n g = (Ur + Vr - Wr)\n b = (Ur + Wr + Wr)\n\n 'clamp values\n if r >255 then\n Rdim = (Ur - 255) / (Vr + Wr)\n r = 255\n g = Ur + (Vr - Wr) * Rdim\n b = Ur + 2 * Wr * Rdim\n elseif r < 0 then\n Rdim = Ur / (Vr + Wr)\n r = 0\n g = Ur + (Vr - Wr) * Rdim\n b = Ur + 2 * Wr * Rdim\n end if\n\n if g >255 then\n Rdim = (255 - Ur) / (Vr - Wr)\n r = Ur - (Vr + Wr) * Rdim\n g = 255\n b = Ur + 2 * Wr * Rdim\n elseif g<0 then\n Rdim = -Ur / (Vr - Wr)\n r = Ur - (Vr + Wr) * Rdim\n g = 0\n b = Ur + 2 * Wr * Rdim\n end if\n if b>255 then\n Rdim = (255 - Ur) / (Wr + Wr)\n r = Ur - (Vr + Wr) * Rdim\n g = Ur + (Vr - Wr) * Rdim\n b = 255\n elseif b<0 then\n Rdim = -Ur / (Wr + Wr)\n r = Ur - (Vr + Wr) * Rdim\n g = Ur + (Vr - Wr) * Rdim\n b = 0\n end If\n 'b lowest byte, red highest byte\n hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)\nend function\n\nfunction ang(col,row)\n 'if col =0 then if row>0 then ang=0 else ang=180:exit function\n if col =0 then\n if row<0 then ang=90 else ang=270 end if\n else\n if col>0 then\n ang=atn(-row/col)*57.2957795130\n else\n ang=(atn(row/-col)*57.2957795130)+180\n end if\n end if\n ang=(ang+360) mod 360\nend function\n\n\nDim X,row,col,fn,tt,hr,sat,row2\nconst h=160\nconst w=160\nconst rad=159\nconst r2=25500\ntt=timer\nfn=CreateObject(\"Scripting.FileSystemObject\").GetSpecialFolder(2)& \"\\testwchr.bmp\"\nSet X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)\n\nx.set0 w,h\n'wscript.echo x.xmax, x.xmin\n\nfor row=x.xmin+1 to x.xmax\n row2=row*row\n hr=int(Sqr(r2-row2))\n For col=hr To 159\n Dim a:a=((col\\16 +row\\16) And 1)* &hffffff\n x.imgArray(col+160,row+160)=a\n x.imgArray(-col+160,row+160)=a\n next\n for col=-hr to hr\n sat=100-sqr(row2+col*col)/rad *50\n ' wscript.echo c,r\n x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)\n next\n 'script.echo row\n next\nSet X = Nothing\n", "language": "VBScript" }, { "code": "import \"graphics\" for Canvas, Color\nimport \"dome\" for Window\nimport \"random\" for Random\n\nclass Game {\n static init() {\n Window.title = \"Color Wheel\"\n __width = 640\n __height = 640\n Window.resize(__width, __height)\n Canvas.resize(__width, __height)\n colorWheel()\n }\n\n static colorWheel() {\n var cx = (__width/2).floor\n var cy = (__height/2).floor\n var r = (cx < cy) ? cx : cy\n for (y in 0...__height) {\n var dy = y - cy\n for (x in 0...__width) {\n var dx = x - cx\n var dist = (dx*dx + dy*dy).sqrt\n if (dist <= r) {\n var theta = dy.atan(dx)\n var h = (theta + Num.pi) / Num.pi * 180\n var col = Color.hsv(h, dist/r, 1)\n Canvas.pset(x, y, col)\n }\n }\n }\n }\n\n static update() {}\n\n static draw(alpha) {}\n}\n", "language": "Wren" }, { "code": "def Radius = 480/2;\nreal Hue, Sat, Dist, I, F, P, Q, T;\nreal XX, YY, RR, GG, BB;\nint X, Y, R, G, B;\ndef Pi = 3.141592654;\ndef V = 1.; \\Value\n[SetVid($112); \\640x480x24 graphics\nfor Y:= -Radius to Radius do\n for X:= -Radius to Radius do\n [XX:= float(X);\n YY:= float(Y);\n Dist:= sqrt(XX*XX + YY*YY);\n if Dist <= float(Radius) then\n [Sat:= Dist/float(Radius); \\0 >= Sat <= 1\n Hue:= ATan2(YY, XX); \\-Pi >= Hue <= Pi\n if Hue < 0. then Hue:= Hue + 2.*Pi;\n Hue:= Hue * 180./Pi; \\radians to degrees\n Hue:= Hue / 60.; \\0 >= Hue < 6\n I:= Floor(Hue); \\integer part of Hue\n F:= Hue - I; \\fractional part of Hue\n P:= 1. - Sat;\n Q:= 1. - Sat*F;\n T:= 1. - Sat*(1.-F);\n case fix(I) of\n 0: [RR:= V; GG:= T; BB:= P];\n 1: [RR:= Q; GG:= V; BB:= P];\n 2: [RR:= P; GG:= V; BB:= T];\n 3: [RR:= P; GG:= Q; BB:= V];\n 4: [RR:= T; GG:= P; BB:= V];\n 5: [RR:= V; GG:= P; BB:= Q]\n other [exit 1];\n R:= fix(RR*255.);\n G:= fix(GG*255.);\n B:= fix(BB*255.);\n Point(X+Radius, Radius-Y, R<<16+G<<8+B);\n ];\n ];\n]\n", "language": "XPL0" }, { "code": "var w=300,h=300,out=PPM(w,h);\ncolorWheel(out);\nout.writeJPGFile(\"colorWheel.zkl.jpg\");\n\nfcn colorWheel(ppm){\n zero,R:=ppm.w/2, zero;\n foreach x,y in (w,h){\n v,hue:=(x - zero).toFloat().toPolar(y - zero);\n if(v<=R){ // only render in the circle\n if((hue = hue.toDeg())<0) hue+=360; // (-pi..pi] to [0..2pi)\n s:=v/R; // scale saturation zero at center to 1 at edge\n ppm[x,y]=hsv2rgb(hue,1.0,s);\n }\n }\n}\n\nfcn hsv2rgb(hue,v,s){ // 0<=H<360, 0<=v(brightness)<=1, 0<=saturation<=1\n // --> 24 bit RGB each R,G,B in [0..255]\n to24bit:=fcn(r,g,b,m){\n r,g,b=((r+m)*255).toInt(),((g+m)*255).toInt(),((b+m)*255).toInt();\n r*0x10000 + g*0x100 + b\n };\n c:=v*s;\n x:=c*(1.0 - (hue.toFloat()/60%2 - 1).abs());\n m:=v - c;\n if (0 <=hue< 60) return(to24bit(c, x, 0.0,m));\n else if(60 <=hue<120) return(to24bit(x, c, 0.0,m));\n else if(120<=hue<180) return(to24bit(0.0,c, x, m));\n else if(180<=hue<240) return(to24bit(0.0,x, c, m));\n else if(240<=hue<300) return(to24bit(x, 0.0,c, m));\n else return(to24bit(c, 0.0,x, m));\n}\n", "language": "Zkl" } ]
Color-wheel
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Colorful_numbers\n", "language": "00-META" }, { "code": "A '''colorful number''' is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.\n\n\n;E.G.\n\n24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840\n\nEvery product is unique.\n\n\n2346 is '''not''' a colorful number. 2, 3, 4, '''6''', (2×3)'''6''', (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144\n\nThe product '''6''' is repeated.\n\n\nSingle digit numbers '''are''' considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.\n\n\n;Task\n\n* Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.\n* Use that routine to find all of the colorful numbers less than 100.\n* Use that routine to find the largest possible colorful number.\n\n\n;Stretch\n\n* Find and display the count of colorful numbers in each order of magnitude.\n* Find and show the total count of '''all''' colorful numbers.\n\n\n''Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.''\n\n", "language": "00-TASK" }, { "code": "V largest = [0]\n\nF iscolorful(n)\n I n C 0.<10\n R 1B\n V dig = String(n).map(c -> Int(c))\n I 1 C dig | 0 C dig | dig.len > Set(dig).len\n R 0B\n V products = Array(Set(dig))\n L(i) 0 .< dig.len\n L(j) i + 2 .. dig.len\n V p = product(dig[i .< j])\n I p C products\n R 0B\n products.append(p)\n\n :largest[0] = max(n, :largest[0])\n R 1B\n\nprint(‘Colorful numbers for 1:25, 26:50, 51:75, and 76:100:’)\nL(i) (1.<101).step(25)\n L(j) 25\n I iscolorful(i + j)\n print(f:‘{commatize(i + j): 5}’, end' ‘’)\n print()\n\nV csum = 0\nL(i) 8\n V j = I i == 0 {0} E 10 ^ i\n V k = 10 ^ (i + 1) - 1\n V n = sum((j .. k).map(x -> Int(iscolorful(x))))\n csum += n\n print(‘The count of colorful numbers between ’j‘ and ’k‘ is ’n‘.’)\n\nprint(‘The largest possible colorful number is ’largest[0]‘.’)\nprint(‘The total number of colorful numbers is ’csum‘.’)\n", "language": "11l" }, { "code": "BEGIN # find colourful numbers: numbers where the product of every sub-group #\n # of digits is uniue ( non-negative numbers only ) #\n # note that (as stated in the task) for multi-digit numbers, the #\n # digits 0 and 1 cannot appear #\n\n # returns TRUE if n is colourful, FALSE otherswise #\n PROC is colourful = ( INT n )BOOL:\n IF n < 0 THEN FALSE\n ELIF n < 10 THEN TRUE\n ELSE\n # more than 1 digit - must teat the digits and digit groups #\n INT v := n;\n # table to hold the digits and groups, as 0 and 1 can't #\n # appear, there will be at most 8 digits so at most 36 groups #\n [ 1 : 46 ]INT dg;\n # split and count the digits #\n [ 0 : 9 ]INT d count;\n INT s end := 0; # position of the last single digit in dg #\n FOR i FROM LWB d count TO UPB d count DO d count[ i ] := 0 OD;\n BOOL unique := TRUE;\n WHILE v > 0 AND unique DO\n INT d = v MOD 10;\n dg[ s end +:= 1 ] := d;\n unique := 1 = ( d count[ d ] +:= 1 );\n v OVERAB 10\n OD;\n IF unique THEN unique := d count[ 0 ] + d count[ 1 ] = 0 FI;\n # form the group products, stopping if one is non-unique #\n INT dg pos := s end;\n FOR group width FROM 2 TO s end WHILE unique DO\n FOR group start TO ( s end + 1 ) - group width WHILE unique DO\n INT product := 1;\n INT g pos := group start - 1;\n FOR i TO group width DO product *:= dg[ g pos +:= 1 ] OD;\n dg[ dg pos +:= 1 ] := product;\n FOR i TO dg pos - 1 WHILE unique DO\n unique := dg[ i ] /= dg[ dg pos ]\n OD\n OD\n OD;\n unique\n FI # is colourful # ;\n\n # show the colourful numbers under 100 #\n print( ( \"Colourful numbers less than 100:\", newline ) );\n INT c count := 0;\n FOR i FROM 0 TO 99 DO\n IF is colourful( i ) THEN\n print( ( whole( i, -3 ) ) );\n IF ( c count +:= 1 ) MOD 11 = 0 THEN print( ( newline ) ) FI\n FI\n OD;\n print( ( newline ) );\n # find the largest colourful number #\n INT max colourful := 0;\n FOR i FROM 98765432 BY -1 WHILE max colourful = 0 DO\n IF is colourful( i ) THEN\n max colourful := i\n FI\n OD;\n print( ( \"The largest colourful number is: \", whole( max colourful, 0 ), newline ) );\n # show the number of colourful numbers by order of magnitude #\n INT p10 := 10;\n c count := 0;\n INT t count := 0;\n FOR i FROM 0 TO max colourful DO\n IF i = p10 THEN\n print( ( \"Colourful numbers below \", whole( p10, -10 ), \": \", whole( c count, 0 ), newline ) );\n t count +:= c count;\n c count := 0;\n p10 *:= 10\n FI;\n IF is colourful( i ) THEN\n c count +:= 1\n FI\n OD;\n print( ( \"Colourful numbers below \", whole( p10, -10 ), \": \", whole( c count, 0 ), newline ) );\n print( ( \"Total number of colourful numbers : \", whole( t count + c count, 0 ), newline ) )\nEND\n", "language": "ALGOL-68" }, { "code": "(*\n This observes the task requirement that colorful numbers be identified using a test handler,\n but uses the information regarding 1s and 0s and some logic to skip obvious non-starters\n and save a few minutes' running time. Since multiplication is commutative, every number's\n \"colorful\" status is the same as its reverse's. Working up from 0, the lower number of each\n mirrored colorful pair is met first and its reverse derived. If the largest reversed number\n obtained so far is actually reached, it's the last colorful number at that magnitude. The\n search either end there or jumps to the lowest number worth trying at the next level.\n*)\non isColorful(n)\n if ((n > 98765432) or (n < 0) or (n mod 1 > 0)) then return false\n set products to {n mod 10}\n repeat while (n > 9)\n set n to n div 10\n set digit to n mod 10\n if ((digit < 2) or (digit is in products)) then return false\n set end of products to digit\n end repeat\n set nDigits to (count products)\n repeat with i from 1 to (nDigits - 1)\n set prod to products's item i\n repeat with j from (i + 1) to nDigits\n set prod to prod * (products's item j)\n if (prod is in products) then return false\n set end of products to prod\n end repeat\n end repeat\n\n return true\nend isColorful\n\non join(lst, delim)\n set astid to AppleScript's text item delimiters\n set AppleScript's text item delimiters to delim\n set txt to lst as text\n set AppleScript's text item delimiters to astid\n return txt\nend join\n\non task()\n set colorfuls to {}\n set counter to 0\n set counts to {}\n set magnitude to 1 -- 10 ^ (number of digits - 1).\n set largestReverse to 9 -- Largest reverse of a single-digit number!\n set n to 0\n repeat\n if (isColorful(n)) then\n if (n < 100) then set end of colorfuls to text -3 thru -1 of (\" \" & n)\n set counter to counter + 1\n if (n = largestReverse) then\n set end of counts to counter\n set counter to 0\n set magnitude to magnitude * 10\n if (magnitude > 98765432) then exit repeat\n set n to 2.3456789 * magnitude div 1 - 1\n else\n set temp to n\n set |reverse| to temp mod 10\n repeat while (temp > 9)\n set temp to temp div 10\n set |reverse| to |reverse| * 10 + temp mod 10\n end repeat\n if (|reverse| > largestReverse) then set largestReverse to |reverse|\n end if\n end if\n if (n mod 10 = 9) then\n set n to n + 3\n else\n set n to n + 1\n end if\n end repeat\n\n set output to {\"The colorful numbers below 100:\"}\n repeat with i from 1 to 66 by 11\n set end of output to join(colorfuls's items i thru (i + 10), \"\")\n end repeat\n set end of output to linefeed & \"The largest colorful number is \" & largestReverse\n set counter to counts's beginning\n set end of output to linefeed & \"The number of them with 1 digit is \" & counter\n repeat with i from 2 to (count counts)\n set end of output to \"The number with \" & i & \" digits is \" & (counts's item i)\n set counter to counter + (counts's item i)\n end repeat\n set end of output to \"The total number overall is \" & counter\n return join(output, linefeed)\nend task\n\ntask()\n", "language": "AppleScript" }, { "code": "\"The colorful numbers below 100:\n 0 1 2 3 4 5 6 7 8 9 23\n 24 25 26 27 28 29 32 34 35 36 37\n 38 39 42 43 45 46 47 48 49 52 53\n 54 56 57 58 59 62 63 64 65 67 68\n 69 72 73 74 75 76 78 79 82 83 84\n 85 86 87 89 92 93 94 95 96 97 98\n\nThe largest colorful number is 98746253\n\nThe number of them with 1 digit is 10\nThe number with 2 digits is 56\nThe number with 3 digits is 328\nThe number with 4 digits is 1540\nThe number with 5 digits is 5514\nThe number with 6 digits is 13956\nThe number with 7 digits is 21596\nThe number with 8 digits is 14256\nThe total number overall is 57256\"\n", "language": "AppleScript" }, { "code": "on isColorful(n)\n if ((n > 98765432) or (n < 0) or (n mod 1 > 0)) then return false\n set products to {n mod 10}\n repeat while (n > 9)\n set n to n div 10\n set digit to n mod 10\n if ((digit < 2) or (digit is in products)) then return false\n set end of products to digit\n end repeat\n set nDigits to (count products)\n repeat with i from 1 to (nDigits - 1)\n set prod to products's item i\n repeat with j from (i + 1) to nDigits\n set prod to prod * (products's item j)\n if (prod is in products) then return false\n set end of products to prod\n end repeat\n end repeat\n\n return true\nend isColorful\n\non join(lst, delim)\n set astid to AppleScript's text item delimiters\n set AppleScript's text item delimiters to delim\n set txt to lst as text\n set AppleScript's text item delimiters to astid\n return txt\nend join\n\non task()\n set colorfuls to {}\n repeat with n from 0 to 100\n if (isColorful(n)) then set end of colorfuls to (\" \" & n)'s text -3 thru -1\n end repeat\n\n script cc\n property used : {false, false, false, false, false, false, false, false, false, false}\n property counts : {0, 0, 0, 0, 0, 0, 0, 0}\n property largest : 0\n\n on count_colourful(taken, x, n)\n set used's item x to true\n if (isColorful(n)) then\n set ln to 1\n repeat until ((10 ^ ln) > n)\n set ln to ln + 1\n end repeat\n set counts's item ln to (counts's item ln) + 1\n if (n > largest) then set largest to n\n end if\n if (taken < 9) then\n repeat with digit from 2 to 9\n set dx to digit + 1\n if (not used's item dx) then\n count_colourful(taken + 1, dx, n * 10 + digit)\n end if\n end repeat\n end if\n set used's item x to false\n end count_colourful\n end script\n repeat with digit from 0 to 9\n cc's count_colourful(((digit < 2) as integer) * 8 + 1, digit + 1, digit)\n end repeat\n\n set output to {\"The colorful numbers below 100:\"}\n repeat with i from 1 to 66 by 11\n set end of output to join(colorfuls's items i thru (i + 10), \"\")\n end repeat\n set end of output to linefeed & \"The largest colorful number is \" & cc's largest\n set counter to cc's counts's beginning\n set end of output to linefeed & \"The number of them with 1 digit is \" & counter\n repeat with i from 2 to (count cc's counts)\n set end of output to \"The number with \" & i & \" digits is \" & (cc's counts's item i)\n set counter to counter + (cc's counts's item i)\n end repeat\n set end of output to \"The total number overall is \" & counter\n return join(output, linefeed)\nend task\n\ntask()\n", "language": "AppleScript" }, { "code": "#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool colorful(int n) {\n // A colorful number cannot be greater than 98765432.\n if (n < 0 || n > 98765432)\n return false;\n int digit_count[10] = {};\n int digits[8] = {};\n int num_digits = 0;\n for (int m = n; m > 0; m /= 10) {\n int d = m % 10;\n if (n > 9 && (d == 0 || d == 1))\n return false;\n if (++digit_count[d] > 1)\n return false;\n digits[num_digits++] = d;\n }\n // Maximum number of products is (8 x 9) / 2.\n int products[36] = {};\n for (int i = 0, product_count = 0; i < num_digits; ++i) {\n for (int j = i, p = 1; j < num_digits; ++j) {\n p *= digits[j];\n for (int k = 0; k < product_count; ++k) {\n if (products[k] == p)\n return false;\n }\n products[product_count++] = p;\n }\n }\n return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n if (taken == 0) {\n for (int d = 0; d < 10; ++d) {\n used[d] = true;\n count_colorful(d < 2 ? 9 : 1, d, 1);\n used[d] = false;\n }\n } else {\n if (colorful(n)) {\n ++count[digits - 1];\n if (n > largest)\n largest = n;\n }\n if (taken < 9) {\n for (int d = 2; d < 10; ++d) {\n if (!used[d]) {\n used[d] = true;\n count_colorful(taken + 1, n * 10 + d, digits + 1);\n used[d] = false;\n }\n }\n }\n }\n}\n\nint main() {\n setlocale(LC_ALL, \"\");\n\n clock_t start = clock();\n\n printf(\"Colorful numbers less than 100:\\n\");\n for (int n = 0, count = 0; n < 100; ++n) {\n if (colorful(n))\n printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n }\n\n count_colorful(0, 0, 0);\n printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n int total = 0;\n for (int d = 0; d < 8; ++d) {\n printf(\"%d %'d\\n\", d + 1, count[d]);\n total += count[d];\n }\n printf(\"\\nTotal: %'d\\n\", total);\n\n clock_t end = clock();\n printf(\"\\nElapsed time: %f seconds\\n\",\n (end - start + 0.0) / CLOCKS_PER_SEC);\n return 0;\n}\n", "language": "C" }, { "code": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<uint32_t> count(8, 0);\nstd::vector<bool> used(10, false);\nuint32_t largest = 0;\n\nbool is_colorful(const uint32_t& number) {\n\tif ( number > 98'765'432 ) {\n\t\treturn false;\n\t}\n\n\tstd::vector<uint32_t> digit_count(10, 0);\n\tstd::vector<uint32_t> digits(8, 0);\n\tuint32_t number_digits = 0;\n\n\tfor ( uint32_t i = number; i > 0; i /= 10 ) {\n\t\tuint32_t digit = i % 10;\n\t\tif ( number > 9 && ( digit == 0 || digit == 1 ) ) {\n\t\t\treturn false;\n\t\t}\n\t\tif ( ++digit_count[digit] > 1 ) {\n\t\t\treturn false;\n\t\t}\n\t\tdigits[number_digits++] = digit;\n\t}\n\n\tstd::vector<uint32_t> products(36, 0);\n\tfor ( uint32_t i = 0, product_count = 0; i < number_digits; ++i ) {\n\t\tfor ( uint32_t j = i, product = 1; j < number_digits; ++j ) {\n\t\t\tproduct *= digits[j];\n\t\t\tfor ( uint32_t k = 0; k < product_count; ++k ) {\n\t\t\t\tif ( products[k] == product ) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tproducts[product_count++] = product;\n\t\t}\n\t}\n\treturn true;\n}\n\nvoid count_colorful(const uint32_t& taken, const uint32_t& number, const uint32_t& digits) {\n\tif ( taken == 0 ) {\n\t\tfor ( uint32_t digit = 0; digit < 10; ++digit ) {\n\t\t\tused[digit] = true;\n\t\t\tcount_colorful(digit < 2 ? 9 : 1, digit, 1);\n\t\t\tused[digit] = false;\n\t\t}\n\t} else {\n\t\tif ( is_colorful(number) ) {\n\t\t\t++count[digits - 1];\n\t\t\tif ( number > largest ) {\n\t\t\t\tlargest = number;\n\t\t\t}\n\t\t}\n\t\tif ( taken < 9 ) {\n\t\t\tfor ( uint32_t digit = 2; digit < 10; ++digit ) {\n\t\t\t\tif ( ! used[digit] ) {\n\t\t\t\t\tused[digit] = true;\n\t\t\t\t\tcount_colorful(taken + 1, number * 10 + digit, digits + 1);\n\t\t\t\t\tused[digit] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main() {\n\tstd::cout << \"Colorful numbers less than 100:\" << std::endl;\n\tfor ( uint32_t number = 0, count = 0; number < 100; ++number ) {\n\t\tif ( is_colorful(number) ) {\n\t\t\tstd::cout << std::setw(2) << number << ( ++count % 10 == 0 ? \"\\n\" : \" \");\n\t\t}\n\t}\n\tstd::cout << \"\\n\" << std::endl;\n\n\tcount_colorful(0, 0, 0);\n\tstd::cout << \"Count of colorful numbers by number of digits:\" << std::endl;\n\tuint32_t total = 0;\n\tfor ( uint32_t digit = 0; digit < 8; ++digit ) {\n\t\tstd::cout << digit + 1 << \": \" << count[digit] << std::endl;\n\t\ttotal += count[digit];\n\t}\n\tstd::cout << std::endl;\n\n\tstd::cout << \"The largest possible colorful number is: \" << largest << \"\\n\" << std::endl;\n\tstd::cout << \"The total number of colorful numbers is: \" << total << std::endl;\n}\n", "language": "C++" }, { "code": "procedure ShowColorfulNumbers(Memo: TMemo);\nvar I,P,Cnt,OldCnt,Start,Stop: integer;\nvar S: string;\nvar Largest: integer;\n\n\n\tfunction IsColorful(N: integer): boolean;\n\tvar IA: TIntegerDynArray;\n\tvar PList: TList;\n\tvar I,J,D,P: integer;\n\tbegin\n\tPList:=TList.Create;\n\ttry\n\tResult:=False;\n\tGetDigits(N,IA);\n\t{Number of digits at a time}\n\tfor D:=1 to Length(IA) do\n\t {For all digits in number}\n\t for I:=High(IA) downto D-1 do\n\t\tbegin\n\t\tP:=1;\n\t\t{Product of digits in a group}\n\t\tfor J:=0 to D-1 do P:=P * IA[I-J];\n\t\t{Has it already been used}\n\t\tif PList.IndexOf(Pointer(P))>=0 then exit;\n\t\t{Store in list}\n\t\tPList.Add(Pointer(P));\n\t\tend;\n\tResult:=True;\n\tfinally PList.Free; end;\n\tend;\n\n\nbegin\nCnt:=0; S:='';\nMemo.Line.Add('Colorful Number less than 100');\nfor I:=0 to 100-1 do\n if IsColorful(I) then\n \tbegin\n\tInc(Cnt);\n\tS:=S+Format('%7D',[I]);\n\tIf (Cnt mod 5)=0 then S:=S+CRLF;\n\tend;\nMemo.Lines.Add(S);\nMemo.Lines.Add('Count = '+IntToStr(Cnt));\nfor Largest:=98765432 downto 1 do\n if IsColorful(Largest) then break;\nMemo.Lines.Add('Largest Colorful Number = '+IntToStr(Largest));\n\nStart:=0; Stop:=9;\nCnt:=0; OldCnt:=0;\nfor P:=1 to 8 do\n\tbegin\n\tfor I:=Start to Stop do\n\t if IsColorful(I) then Inc(Cnt);\n\tMemo.Lines.Add(Format('Colorful Numbers from %10.0n to %10.0n: %5D', [Start+0.0,Stop+0.0,Cnt-OldCnt]));\n\tStart:=Stop+1;\n\tStop:=(Start*10)-1;\n\tOldCnt:=Cnt;\n\tend;\nfor I:=Stop+1 to Largest do\n if IsColorful(I) then Inc(Cnt);\nMemo.Lines.Add('Total All Colorful = '+IntToStr(Cnt));\nend;\n", "language": "Delphi" }, { "code": "func colorful n .\n len digcnt[] 10\n arrbase digcnt[] 0\n len digits[] 8\n m = n\n while m > 0\n d = m mod 10\n if n > 9 and d <= 1\n return 0\n .\n digcnt[d] += 1\n if digcnt[d] > 1\n return 0\n .\n ndigs += 1\n digits[ndigs] = d\n m = m div 10\n .\n len products[] 36\n for i to ndigs\n p = 1\n for j = i to ndigs\n p *= digits[j]\n for k to prodcnt\n if products[k] = p\n return 0\n .\n .\n prodcnt += 1\n products[prodcnt] = p\n .\n .\n return 1\n.\nlen cnt[] 8\nlen used[] 10\narrbase used[] 0\nlargest = 0\nproc cnt_colorful taken n digits . .\n if taken = 0\n for d = 0 to 9\n used[d] = 1\n h = 1\n if d < 2\n h = 9\n .\n cnt_colorful h d 1\n used[d] = 0\n .\n return\n .\n if colorful n = 1\n cnt[digits] += 1\n largest = higher largest n\n .\n if taken < 9\n for d = 2 to 9\n if used[d] = 0\n used[d] = 1\n cnt_colorful (taken + 1) (n * 10 + d) (digits + 1)\n used[d] = 0\n .\n .\n .\n.\nprint \"Colorful numbers less than 100:\"\nfor n = 0 to 99\n if colorful n = 1\n write n & \" \"\n .\n.\ncnt_colorful 0 0 0\nprint \"\\n\\nLargest colorful number:\" & largest\n#\nprint \"\\nCount of colorful numbers by number of digits:\\n\"\nfor d to 8\n print d & \" \" & cnt[d]\n total += cnt[d]\n.\nprint \"\\nTotal: \" & total\n", "language": "EasyLang" }, { "code": "USING: assocs grouping grouping.extras io kernel literals math\nmath.combinatorics math.ranges prettyprint project-euler.common\nsequences sequences.extras sets ;\n\nCONSTANT: digits $[ 2 9 [a..b] ]\n\n: (colorful?) ( seq -- ? )\n all-subseqs [ product ] map all-unique? ;\n\n: colorful? ( n -- ? )\n [ t ] [ number>digits (colorful?) ] if-zero ;\n\n: table. ( seq cols -- )\n [ \"\" pad-groups ] keep group simple-table. ;\n\n: (oom-count) ( n -- count )\n digits swap <k-permutations> [ (colorful?) ] count ;\n\n: oom-count ( n -- count )\n dup 1 = [ drop 10 ] [ (oom-count) ] if ;\n\n\"Colorful numbers under 100:\" print\n100 <iota> [ colorful? ] filter 10 table. nl\n\n\"Largest colorful number:\" print\ndigits <permutations> [ (colorful?) ] find-last nip digits>number . nl\n\n\"Count of colorful numbers by number of digits:\" print\n8 [1..b] [ oom-count ] zip-with dup .\n\"Total: \" write values sum .\n", "language": "Factor" }, { "code": "{$IFDEF FPC}\n {$mode Delphi}\n {$Optimization ON,All}\n {$Coperators ON}\n{$ENDIF}\n{$IFDEF WINDOWS}\n {$APPTYPE CONSOLE}\n{$ENDIF}\nuses\n sysutils;\nconst\n EightFak = 1*2*3*4*5*6*7*8;\ntype\n tDgt = Int8;\n tpDgt = pInt8;\n tDgtfield = array[0..7] of tdgt;\n tpDgtfield = ^tDgtfield;\n\n tPermfield = tDgtfield;\n tAllPermDigits = array[0..EightFak] of tDgtfield;\n tMarkNotColorful = array[0..EightFak-1] of byte;\n\n tDat = Uint32;\n tusedMultiples = array[0..8*9 DIV 2-2] of tDat;\n\nvar\n AllPermDigits :tAllPermDigits;\n MarkNotColorful:tMarkNotColorful;\n permcnt,\n totalCntColorFul,CntColorFul : Int32;\n\nprocedure PermLex(n: Int32;StartVal:Int8);\nvar\n Perm : tPermField;\n k,j : Int32;\n temp: tDgt;\n pDat :tpDgt;\nbegin\n For j := 0 to n-1 do\n Perm[j]:= j+StartVal;\n\n permcnt := 0;\n dec(n);\n repeat\n AllPermDigits[permcnt] := Perm;\n inc(permcnt);\n k := N-1;\n pDat := @Perm[k];\n while (pDat[0]> pDat[1]) And (k >=Low(Perm) ) do\n begin\n dec(pDat);\n dec(k);\n end;\n\n if k >= Low(Perm) then\n begin\n j := N;\n pDat := @Perm[j];\n temp := Perm[k];\n while (temp > pDat[0]) And (J >K) do\n begin\n dec(j);\n dec(pDat);\n end;\n\n Perm[k] := pDat[0];\n pDat[0] := temp;\n j := N;\n pDat := @Perm[j];\n Inc(k);\n\n while j>k do\n begin\n temp := pDat[0];\n pDat[0] := Perm[k];\n Perm[k] := temp;\n\n dec(j);\n dec(pDat);\n inc(k);\n end;\n end\n else\n break;\n until false;\nend;\n\nprocedure OutNum(const num:tPermfield;dgtCnt: Int32);\nvar\n i : integer;\nBegin\n For i := 0 to dgtcnt-1 do\n write(num[i]);\n writeln;\nend;\n\nfunction isAlreadyExisting(var uM :tusedMultiples; maxIdx : Int32;dat :tDat):boolean;\nvar\n I : Int32;\nbegin\n if maxIdx >= 0 then\n begin\n i := maxIdx;\n repeat\n if dat = uM[i] then\n EXIT(true);\n Dec(i);\n until i <0;\n end;\n uM[maxIdx+1]:= dat;\n result := false;\nend;\n\nfunction CalcValue(pDgtfield : tpDgtfield;TestDgtCnt:Int32):int32;\nbegin\n result := 1;\n repeat\n result *=pDgtfield[TestDgtCnt];\n dec(TestDgtCnt);\n until TestDgtCnt <0;\nend;\n\nfunction isCheckColorful(dgtCnt: NativeInt;idx:Int32):boolean;\nvar\n usedMultiples : tusedMultiples;\n pDgtfield : ^tDgtfield;\n TestDgtCnt,StartIdx,value,maxIdx : Int32;\nbegin\n //needn't to test product of all digits.It's a singular max value\n dec(dgtCnt);\n pDgtfield := @AllPermDigits[idx];\n maxIdx := -1;\n\n //multiples of TestDgtCnt digits next to one another\n For TestDgtCnt := 0 to dgtCnt do\n begin\n For StartIdx := 0 to dgtCnt-TestDgtCnt do\n begin\n value := CalcValue(@pDgtfield[StartIdx],TestDgtCnt);\n// value := 1; For l := 0 to TestDgtCnt do value *=pDgtfield[StartIdx+l];\n if isAlreadyExisting(usedMultiples,maxIdx,value) then\n EXIT(false);\n inc(MaxIdx);\n end;\n end;\n inc(totalCntColorFul);\n inc(CntColorFul);\n result := true;\nend;\n\nprocedure CheckDgtCnt(dgtCnt,delta:Int32);\nvar\n i,j : int32;\nbegin\n i := 0;\n CntColorFul := 0;\n if dgtCnt = 1 then\n CntColorFul := 2;//0,1\n\n if delta = 1 then\n begin\n For i := i to EightFak-1 do\n IF (MarkNotColorful[i]=0) AND not isCheckColorful(dgtCnt,i)then\n MarkNotColorful[i] := dgtcnt;\n end\n else\n Begin\n if dgtcnt<3 then\n //always colorful\n begin\n repeat\n isCheckColorful(dgtCnt,i);\n inc(i,delta);\n until i>EightFak-1;\n end\n else\n begin\n repeat\n IF (MarkNotColorful[i]=0) AND not isCheckColorful(dgtCnt,i) then\n begin\n //mark a range as not colorful\n j := i+delta-1;\n repeat\n MarkNotColorful[j] := dgtcnt;\n dec(j);\n until j < i;\n end;\n inc(i,delta);\n until i>EightFak-1;\n end;\n end;\nend;\n\nvar\n T0 : Int64;\n i,j,delta: INteger;\nBegin\n T0 := GetTickCount64;\n PermLex(8,2);\n //takes ~1 ms til here\n delta := 15;\n writeln('First colorful numbers less than 100');\n For i := 0 to 9 do\n Begin\n write(i:4);\n dec(delta);\n end;\n For i := 2 to 9 do\n For j := 2 to 9 do\n if j<> i then\n begin\n //write(i:3,j);\n dec(delta);\n if delta = 0 then\n begin\n delta:= 15;\n Writeln;\n end;\n end;\n writeln;\n writeln;\n Writeln(' digits count of colorful numbers');\n totalCntColorFul := 2;//0,1,\n delta := EightFak-1;\n delta := (delta+1) DIV 8;\n j := 7;\n repeat\n CheckDgtCnt(8-j,delta);\n writeln(8-j:10,CntColorFul:10);\n if j = 0 then\n BREAK;\n delta := delta DIV j;\n dec(j);\n until false;\n Writeln;\n Writeln('Total number of colorful numbers: ',totalCntColorFul);\n Write('Highest Value :');\n For i := High(AllPermDigits) downto low(AllPermDigits) do\n if MarkNotColorful[i] = 0 then\n Begin\n OutNum(AllPermDigits[i],8);\n BREAK;\n end;\n\n Writeln('Runtime in ms ',GetTickCount64-T0);\nend.\n", "language": "Free-Pascal-Lazarus" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"rcu\"\n \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n if n < 0 {\n return false\n }\n if n < 10 {\n return true\n }\n digits := rcu.Digits(n, 10)\n for _, d := range digits {\n if d == 0 || d == 1 {\n return false\n }\n }\n set := make(map[int]bool)\n for _, d := range digits {\n set[d] = true\n }\n dc := len(digits)\n if len(set) < dc {\n return false\n }\n for k := 2; k <= dc; k++ {\n for i := 0; i <= dc-k; i++ {\n prod := 1\n for j := i; j <= i+k-1; j++ {\n prod *= digits[j]\n }\n if ok := set[prod]; ok {\n return false\n }\n set[prod] = true\n }\n }\n return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n if taken == 0 {\n for digit := 0; digit < 10; digit++ {\n dx := digit + 1\n used[dx] = true\n t := 1\n if digit < 2 {\n t = 9\n }\n countColorful(t, string(digit+48))\n used[dx] = false\n }\n } else {\n nn, _ := strconv.Atoi(n)\n if isColorful(nn) {\n ln := len(n)\n count[ln]++\n if nn > largest {\n largest = nn\n }\n }\n if taken < 9 {\n for digit := 2; digit < 10; digit++ {\n dx := digit + 1\n if !used[dx] {\n used[dx] = true\n countColorful(taken+1, n+string(digit+48))\n used[dx] = false\n }\n }\n }\n }\n}\n\nfunc main() {\n var cn []int\n for i := 0; i < 100; i++ {\n if isColorful(i) {\n cn = append(cn, i)\n }\n }\n fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n for i := 0; i < len(cn); i++ {\n fmt.Printf(\"%2d \", cn[i])\n if (i+1)%10 == 0 {\n fmt.Println()\n }\n }\n\n countColorful(0, \"\")\n fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n fmt.Println(rcu.Commatize(largest))\n\n fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n pow := 10\n for dc := 1; dc < len(count); dc++ {\n cdc := rcu.Commatize(count[dc])\n pc := 100 * float64(count[dc]) / float64(pow)\n fmt.Printf(\" %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n if pow == 10 {\n pow = 90\n } else {\n pow *= 10\n }\n }\n\n sum := 0\n for _, c := range count {\n sum += c\n }\n fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n", "language": "Go" }, { "code": "import Data.List ( nub )\nimport Data.List.Split ( divvy )\nimport Data.Char ( digitToInt )\n\nisColourful :: Integer -> Bool\nisColourful n\n |n >= 0 && n <= 10 = True\n |n > 10 && n < 100 = ((length s) == (length $ nub s)) &&\n (not $ any (\\c -> elem c \"01\") s)\n |n >= 100 = ((length s) == (length $ nub s)) && (not $ any (\\c -> elem c \"01\") s)\n && ((length products) == (length $ nub products))\n where\n s :: String\n s = show n\n products :: [Int]\n products = map (\\p -> (digitToInt $ head p) * (digitToInt $ last p))\n $ divvy 2 1 s\n\nsolution1 :: [Integer]\nsolution1 = filter isColourful [0 .. 100]\n\nsolution2 :: Integer\nsolution2 = head $ filter isColourful [98765432, 98765431 ..]\n", "language": "Haskell" }, { "code": " colorful=: {{(-:~.);<@(*/\\)\\. 10 #.inv y}}\"0\n I.colorful i.100\n0 1 2 3 4 5 6 7 8 9 23 24 25 26 27 28 29 32 34 35 36 37 38 39 42 43 45 46 47 48 49 52 53 54 56 57 58 59 62 63 64 65 67 68 69 72 73 74 75 76 78 79 82 83 84 85 86 87 89 92 93 94 95 96 97 98\n C=: I.colorful <.i.1e8\n >./C\n98746253\n (~.,. #/.~) 10 <.@^. C\n__ 1\n 0 9\n 1 56\n 2 328\n 3 1540\n 4 5514\n 5 13956\n 6 21596\n 7 14256\n #C\n57256\n", "language": "J" }, { "code": "public class ColorfulNumbers {\n private int count[] = new int[8];\n private boolean used[] = new boolean[10];\n private int largest = 0;\n\n public static void main(String[] args) {\n System.out.printf(\"Colorful numbers less than 100:\\n\");\n for (int n = 0, count = 0; n < 100; ++n) {\n if (isColorful(n))\n System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n }\n\n ColorfulNumbers c = new ColorfulNumbers();\n\n System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n int total = 0;\n for (int d = 0; d < 8; ++d) {\n System.out.printf(\"%d %,d\\n\", d + 1, c.count[d]);\n total += c.count[d];\n }\n System.out.printf(\"\\nTotal: %,d\\n\", total);\n }\n\n private ColorfulNumbers() {\n countColorful(0, 0, 0);\n }\n\n public static boolean isColorful(int n) {\n // A colorful number cannot be greater than 98765432.\n if (n < 0 || n > 98765432)\n return false;\n int digit_count[] = new int[10];\n int digits[] = new int[8];\n int num_digits = 0;\n for (int m = n; m > 0; m /= 10) {\n int d = m % 10;\n if (n > 9 && (d == 0 || d == 1))\n return false;\n if (++digit_count[d] > 1)\n return false;\n digits[num_digits++] = d;\n }\n // Maximum number of products is (8 x 9) / 2.\n int products[] = new int[36];\n for (int i = 0, product_count = 0; i < num_digits; ++i) {\n for (int j = i, p = 1; j < num_digits; ++j) {\n p *= digits[j];\n for (int k = 0; k < product_count; ++k) {\n if (products[k] == p)\n return false;\n }\n products[product_count++] = p;\n }\n }\n return true;\n }\n\n private void countColorful(int taken, int n, int digits) {\n if (taken == 0) {\n for (int d = 0; d < 10; ++d) {\n used[d] = true;\n countColorful(d < 2 ? 9 : 1, d, 1);\n used[d] = false;\n }\n } else {\n if (isColorful(n)) {\n ++count[digits - 1];\n if (n > largest)\n largest = n;\n }\n if (taken < 9) {\n for (int d = 2; d < 10; ++d) {\n if (!used[d]) {\n used[d] = true;\n countColorful(taken + 1, n * 10 + d, digits + 1);\n used[d] = false;\n }\n }\n }\n }\n }\n}\n", "language": "Java" }, { "code": "# Uncomment for gojq\n# def _nwise($n):\n# def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;\n# n;\n\ndef lpad($len): tostring | ($len - length) as $l | (\" \" * $l)[:$l] + .;\n\n# Generate a stream of the permutations of the input array.\ndef permutations:\n if length == 0 then []\n else\n range(0;length) as $i\n | [.[$i]] + (del(.[$i])|permutations)\n end ;\n", "language": "Jq" }, { "code": "def isColorful:\n def digits: [tostring | explode[] | [.] | implode | tonumber];\n\n if . < 0 then false\n elif . < 10 then true\n else . as $n\n | digits as $digits\n | if any($digits[]; . == 0 or . == 1) then false\n else ($digits|unique) as $set\n | ($digits|length) as $dc\n | if ($set|length) < $dc then false\n else label $out\n | foreach range(2; $dc) as $k ({$set};\n foreach range(0; $dc-$k+1) as $i (.;\n (reduce range($i; $i+$k) as $j (1; . * $digits[$j])) as $prod\n | if .set|index($prod) then .return = 0, break $out\n else .set += [$prod]\n\t end ;\n\t . );\n\t select(.return) ) // null\n | if .return == 0 then false else true end\n end\n end\n end;\n\n# Emit a stream of colorfuls in range(a;b)\ndef colorfuls(a;b):\n range(a;b) | select(isColorful);\n", "language": "Jq" }, { "code": "def task($n):\n [colorfuls(0; $n)]\n | \"The \\(length) colorful numbers less than \\($n) are:\",\n (_nwise($10) | map(lpad(4)) | join(\" \")) ;\n\ndef largestColorful:\n [[range(2;10)] | permutations | join(\"\") | tonumber | select(isColorful)] | max;\n\n# Emit a JSON object giving the counts by number of digits\ndef classifyColorful:\n def nonTrivialCandidates:\n [range(2; 10)]\n | range(1; 9) as $length\n | combinations($length)\n | join(\"\")\n | tonumber;\n reduce (0,1,nonTrivialCandidates) as $i ({};\n if $i|isColorful\n then .[$i|tostring|length|tostring] += 1\n else .\n end);\n\ntask(100),\n\"\",\n\"The largest possible colorful number is \\(largestColorful).\"\n\"\",\n\"The counts of colorful numbers by number of digits are:\",\n(classifyColorful\n | (., \"\\nTotal: \\([.[]]|add)\"))\n", "language": "Jq" }, { "code": "largest = 0\n\nfunction iscolorful(n, base=10)\n 0 <= n < 10 && return true\n dig = digits(n, base=base)\n (1 in dig || 0 in dig || !allunique(dig)) && return false\n products = Set(dig)\n for i in 2:length(dig), j in 1:length(dig)-i+1\n p = prod(dig[j:j+i-1])\n p in products && return false\n push!(products, p)\n end\n if n > largest\n global largest = n\n end\n return true\nend\n\nfunction testcolorfuls()\n println(\"Colorful numbers for 1:25, 26:50, 51:75, and 76:100:\")\n for i in 1:100\n iscolorful(i) && print(rpad(i, 5))\n i % 25 == 0 && println()\n end\n csum = 0\n for i in 0:7\n j, k = i == 0 ? 0 : 10^i, 10^(i+1) - 1\n n = count(i -> iscolorful(i), j:k)\n csum += n\n println(\"The count of colorful numbers between $j and $k is $n.\")\n end\n println(\"The largest possible colorful number is $largest.\")\n println(\"The total number of colorful numbers is $csum.\")\nend\n\ntestcolorfuls()\n", "language": "Julia" }, { "code": "ClearAll[ColorfulNumberQ]\nColorfulNumberQ[n_Integer?NonNegative] := Module[{digs, parts},\n If[n > 98765432,\n False\n ,\n digs = IntegerDigits[n];\n parts = Partition[digs, #, 1] & /@ Range[1, Length[digs]];\n parts //= Catenate;\n parts = Times @@@ parts;\n DuplicateFreeQ[parts]\n ]\n ]\nMulticolumn[Select[Range[99], ColorfulNumberQ], Appearance -> \"Horizontal\"]\n\nsel = Union[FromDigits /@ Catenate[Permutations /@ Subsets[Range[2, 9], {1, \\[Infinity]}]]];\nsel = Join[sel, {0, 1}];\ncns = Select[sel, ColorfulNumberQ];\n\nMax[cns]\n\nTally[IntegerDigits/*Length /@ cns] // Grid\n\nLength[cns]\n", "language": "Mathematica" }, { "code": "import std/[math, intsets, strformat]\n\nfunc digits(n: Natural): seq[int] =\n ## Return the digits of \"n\" in reverse order.\n var n = n\n while true:\n result.add n mod 10\n n = n div 10\n if n == 0: break\n\nvar largest = 0\n\nproc isColorful(n: Natural): bool =\n ## Return true if \"n\" is colorful.\n if n in 0..9: return true\n let digSeq = n.digits\n var digSet: set[0..9]\n for d in digSeq:\n if d <= 1 or d in digSet:\n return false\n digSet.incl d\n var products = digSeq.toIntSet()\n for i in 0..<digSeq.high:\n for j in (i + 1)..digSeq.high:\n let p = prod(digSeq.toOpenArray(i, j))\n if p in products:\n return false\n products.incl p\n if n > largest: largest = n\n result = true\n\necho \"Colorful numbers for 1:25, 26:50, 51:75, and 76:100:\"\nfor i in countup(1, 100, 25):\n for j in 0..24:\n if isColorful(i + j):\n stdout.write &\"{i + j: 5}\"\n echo()\n\necho()\nvar csum = 0\nfor i in 0..7:\n let j = if i == 0: 0 else: 10^i\n let k = 10^(i+1) - 1\n var n = 0\n for x in j..k:\n if x.isColorful: inc n\n inc csum, n\n echo &\"The count of colorful numbers between {j} and {k} is {n}.\"\n\necho()\necho &\"The largest possible colorful number is {largest}.\"\necho &\"The total number of colorful numbers is {csum}.\"\n", "language": "Nim" }, { "code": "use strict;\nuse warnings;\nuse feature 'say';\nuse enum qw(False True);\nuse List::Util <max uniqint product>;\nuse Algorithm::Combinatorics qw(combinations permutations);\n\nsub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\\K/\\n/gr }\n\nsub is_colorful {\n my($n) = @_;\n return True if 0 <= $n and $n <= 9;\n return False if $n =~ /0|1/ or $n < 0;\n my @digits = split '', $n;\n return False unless @digits == uniqint @digits;\n my @p;\n for my $w (0 .. @digits) {\n push @p, map { product @digits[$_ .. $_+$w] } 0 .. @digits-$w-1;\n return False unless @p == uniqint @p\n }\n True\n}\n\nsay \"Colorful numbers less than 100:\\n\" . table 10, grep { is_colorful $_ } 0..100;\n\nmy $largest = 98765432;\n1 while not is_colorful --$largest;\nsay \"Largest magnitude colorful number: $largest\\n\";\n\nmy $total= 10;\nmap { is_colorful(join '', @$_) and $total++ } map { permutations $_ } combinations [2..9], $_ for 2..8;\nsay \"Total colorful numbers: $total\";\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">colourful</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">digits</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_sub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">'0'</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">ud</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">unique</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">digits</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ln</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">digits</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ud</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]<=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ud</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">ln</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">ln</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">ln</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">prod</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">product</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">digits</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">prod</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ud</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">ud</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">prod</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">apply</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">,{{</span><span style=\"color: #008000;\">\"%2d\"</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">colourful</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"The %d colourful numbers less than 100 are:\\n%s\\n\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cn</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #7060A8;\">join_by</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cn</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">)})</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">used</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">largestcn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">count_colourful</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">taken</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">taken</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">digit</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'0'</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #008000;\">'9'</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">dx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">digit</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #008000;\">'0'</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">used</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #000000;\">count_colourful</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">digit</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #008000;\">'2'</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">digit</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">used</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">nn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">to_integer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">colourful</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nn</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ln</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ln</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">nn</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">largestcn</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">largestcn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">nn</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">taken</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">9</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">digit</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'2'</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #008000;\">'9'</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">dx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">digit</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #008000;\">'0'</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">used</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">used</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #000000;\">count_colourful</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">taken</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">digit</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">used</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n <span style=\"color: #000000;\">count_colourful</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"The largest possible colourful number is: %,d\\n\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">largestcn</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">pow</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">10</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">dc</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" %d digit colourful number count: %,6d - %7.3f%%\\n\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">dc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">dc</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">dc</span><span style=\"color: #0000FF;\">]/</span><span style=\"color: #000000;\">pow</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">pow</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pow</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">90</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">pow</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\nTotal colourful numbers: %,d\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "colorful_number(N) =>\n N < 10 ;\n (X = N.to_string,\n X.len <= 8,\n not membchk('0',X),\n not membchk('1',X),\n distinct(X),\n [prod(S.map(to_int)) : S in findall(S,(append(_,S,_,X),S != [])) ].distinct).\n\ndistinct(L) =>\n L.len == L.remove_dups.len.\n", "language": "Picat" }, { "code": "main =>\n Colorful = [N : N in 0..100, colorful_number(N)],\n Len = Colorful.len,\n foreach({C,I} in zip(Colorful,1..Len))\n printf(\"%2d%s\",C, cond(I mod 10 == 0, \"\\n\",\" \"))\n end,\n nl,\n println(len=Len)\n", "language": "Picat" }, { "code": "main =>\n N = 98765431,\n Found = false,\n while (Found == false)\n if colorful_number(N) then\n println(N),\n Found := true\n end,\n N := N - 1\n end.\n", "language": "Picat" }, { "code": "main =>\n TotalC = 0,\n foreach(I in 1..8)\n C = 0,\n printf(\"Digits %d: \", I),\n foreach(N in lb(I)..ub(I))\n if colorful_number(N) then\n C := C + 1\n end\n end,\n println(C),\n TotalC := TotalC + C\n end,\n println(total=TotalC),\n nl.\n\n% Lower and upper bounds.\n% For N=3: lb=123 and ub=987\nlb(N) = cond(N < 2, 0, [I.to_string : I in 1..N].join('').to_int).\nub(N) = [I.to_string : I in 9..-1..9-N+1].join('').to_int.\n", "language": "Picat" }, { "code": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n if 0 <= n < 10:\n return True\n dig = [int(c) for c in str(n)]\n if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n return False\n products = list(set(dig))\n for i in range(len(dig)):\n for j in range(i+2, len(dig)+1):\n p = prod(dig[i:j])\n if p in products:\n return False\n products.append(p)\n\n largest[0] = max(n, largest[0])\n return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n for j in range(25):\n if iscolorful(i + j):\n print(f'{i + j: 5,}', end='')\n print()\n\ncsum = 0\nfor i in range(8):\n j = 0 if i == 0 else 10**i\n k = 10**(i+1) - 1\n n = sum(iscolorful(x) for x in range(j, k+1))\n csum += n\n print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n", "language": "Python" }, { "code": "sub is-colorful (Int $n) {\n return True if 0 <= $n <= 9;\n return False if $n.contains(0) || $n.contains(1) || $n < 0;\n my @digits = $n.comb;\n my %sums = @digits.Bag;\n return False if %sums.values.max > 1;\n for 2..@digits -> $group {\n @digits.rotor($group => 1 - $group).map: { %sums{ [×] $_ }++ }\n return False if %sums.values.max > 1;\n }\n True\n}\n\nput \"Colorful numbers less than 100:\\n\" ~ (^100).hyper.grep( &is-colorful).batch(10)».fmt(\"%2d\").join: \"\\n\";\n\nmy ($start, $total) = 23456789, 10;\n\nprint \"\\nLargest magnitude colorful number: \";\n.put and last if .Int.&is-colorful for $start.flip … $start;\n\n\nput \"\\nCount of colorful numbers for each order of magnitude:\\n\" ~\n \"1 digit colorful number count: $total - 100%\";\n\nfor 2..8 {\n put \"$_ digit colorful number count: \",\n my $c = +(flat $start.comb.combinations($_).map: {.permutations».join».Int}).hyper.grep( &is-colorful ),\n \" - {($c / (exp($_,10) - exp($_-1,10) ) * 100).round(.001)}%\";\n $total += $c;\n}\n\nsay \"\\nTotal colorful numbers: $total\";\n", "language": "Raku" }, { "code": "def colorful?(ar)\n products = []\n (1..ar.size).all? do |chunk_size|\n ar.each_cons(chunk_size) do |chunk|\n product = chunk.inject(&:*)\n return false if products.include?(product)\n products << product\n end\n end\nend\n\nbelow100 = (0..100).select{|n| colorful?(n.digits)}\nputs \"The colorful numbers less than 100 are:\", below100.join(\" \"), \"\"\nputs \"Largest colorful number: #{(98765432.downto(1).detect{|n| colorful?(n.digits) })}\", \"\"\n\ntotal = 0\n(1..8).each do |numdigs|\n digits = (numdigs == 1 ? (0..9).to_a : (2..9).to_a)\n count = digits.permutation(numdigs).count{|perm| colorful?(perm)}\n puts \"#{numdigs} digit colorful numbers count: #{count}\"\n total += count\nend\n\nputs \"\\nTotal colorful numbers: #{total}\"\n", "language": "Ruby" }, { "code": "use core::cmp::max;\nuse std::collections::HashSet;\n\nfn to_digits(mut n: u64, base: u64) -> Vec<u64> {\n if n == 0 {\n return [0].to_vec();\n }\n let mut v: Vec<u64> = Vec::new();\n while n > 0 {\n let d = n % base;\n n /= base;\n v.push(d);\n }\n return v;\n}\n\nfn is_colorful(n: u64) -> bool {\n if &n > &9 {\n let dig: Vec<u64> = to_digits(n, 10);\n if dig.contains(&1) || dig.contains(&0) {\n return false;\n }\n let mut products: HashSet<u64> = HashSet::new();\n for i in 0..dig.len() {\n if products.contains(&dig[i]) {\n return false;\n }\n products.insert(dig[i]);\n }\n for i in 0..dig.len() {\n for j in i+2..dig.len()+1 {\n let p: u64 = (dig[i..j]).iter().product();\n if products.contains(&p) {\n return false;\n }\n products.insert(p);\n }\n }\n }\n return true;\n}\n\nfn main() {\n println!(\"Colorful numbers for 1:25, 26:50, 51:75, and 76:100:\");\n for i in (1..101).step_by(25) {\n for j in 0..25 {\n if is_colorful(i + j) {\n print!(\"{:5}\", i + j);\n }\n }\n println!();\n }\n println!();\n\n let mut csum: u64 = 0;\n let mut largest: u64 = 0;\n let mut n: u64;\n for i in 0..8 {\n let j: u64 = { if i == 0 { 0 } else { 10_u64.pow(i) } };\n let k: u64 = 10_u64.pow(i + 1) - 1;\n n = 0;\n for x in j..k+1 {\n if is_colorful(x) {\n largest = max(largest, x);\n n += 1;\n }\n }\n println!(\"The count of colorful numbers within the interval [{j}, {k}] is {n}.\");\n csum += n;\n }\n println!(\"The largest possible colorful number is {largest}.\");\n println!(\"The total number of colorful numbers is {csum}.\")\n}\n", "language": "Rust" }, { "code": "import \"./math\" for Int, Nums\nimport \"./set\" for Set\nimport \"./fmt\" for Fmt\n\nvar isColorful = Fn.new { |n|\n if (n < 0) return false\n if (n < 10) return true\n var digits = Int.digits(n)\n if (digits.contains(0) || digits.contains(1)) return false\n var set = Set.new(digits)\n var dc = digits.count\n if (set.count < dc) return false\n for (k in 2..dc) {\n for (i in 0..dc-k) {\n var prod = 1\n for (j in i..i+k-1) prod = prod * digits[j]\n if (set.contains(prod)) return false\n set.add(prod)\n }\n }\n return true\n}\n\nvar count = List.filled(9, 0)\nvar used = List.filled(11, false)\nvar largest = 0\n\nvar countColorful // recursive\ncountColorful = Fn.new { |taken, n|\n if (taken == 0) {\n for (digit in 0..9) {\n var dx = digit + 1\n used[dx] = true\n countColorful.call((digit < 2) ? 9 : 1, String.fromByte(digit + 48))\n used[dx] = false\n }\n } else {\n var nn = Num.fromString(n)\n if (isColorful.call(nn)) {\n var ln = n.count\n count[ln] = count[ln] + 1\n if (nn > largest) largest = nn\n }\n if (taken < 9) {\n for (digit in 2..9) {\n var dx = digit + 1\n if (!used[dx]) {\n used[dx] = true\n countColorful.call(taken + 1, n + String.fromByte(digit + 48))\n used[dx] = false\n }\n }\n }\n }\n}\n\nvar cn = (0..99).where { |i| isColorful.call(i) }.toList\nSystem.print(\"The %(cn.count) colorful numbers less than 100 are:\")\nFmt.tprint(\"$2d\", cn, 10)\n\ncountColorful.call(0, \"\")\nSystem.print(\"\\nThe largest possible colorful number is:\")\nFmt.print(\"$,d\\n\", largest)\n\nSystem.print(\"Count of colorful numbers for each order of magnitude:\")\nvar pow = 10\nfor (dc in 1...count.count) {\n Fmt.print(\" $d digit colorful number count: $,6d - $7.3f\\%\", dc, count[dc], 100 * count[dc] / pow)\n pow = (pow == 10) ? 90 : pow * 10\n}\n\nFmt.print(\"\\nTotal colorful numbers: $,d\", Nums.sum(count))\n", "language": "Wren" }, { "code": "func IPow(A, B); \\A^B\nint A, B, T, I;\n[T:= 1;\nfor I:= 1 to B do T:= T*A;\nreturn T;\n];\n\nfunc Colorful(N); \\Return 'true' if N is a colorful number\nint N, Digits, R, I, J, Prod;\ndef Size = 9*8*7*6*5*4*3*2 + 1;\nchar Used(Size), Num(10);\n[if N < 10 then return true; \\single digit number is colorful\nFillMem(Used, false, 10); \\digits must be unique\nDigits:= 0;\nrepeat N:= N/10; \\slice digits off N\n R:= rem(0);\n if N=1 or R=0 or R=1 then return false;\n if Used(R) then return false;\n Used(R):= true; \\digits must be unique\n Num(Digits):= R;\n Digits:= Digits+1;\nuntil N = 0;\nFillMem(Used+10, false, Size-10); \\products must be unique\nfor I:= 0 to Digits-2 do\n [Prod:= Num(I);\n for J:= I+1 to Digits-1 do\n [Prod:= Prod * Num(J);\n if Used(Prod) then return false;\n Used(Prod):= true;\n ];\n ];\nreturn true;\n];\n\nint Count, N, Power, Total;\n[Text(0, \"Colorful numbers less than 100:\n\");\nCount:= 0;\nfor N:= 0 to 99 do\n if Colorful(N) then\n [IntOut(0, N);\n Count:= Count+1;\n if rem(Count/10) then ChOut(0, 9\\tab\\) else CrLf(0);\n ];\nText(0, \"\n\nLargest magnitude colorful number: \");\nN:= 98_765_432;\nloop [if Colorful(N) then quit;\n N:= N-1;\n ];\nIntOut(0, N);\nText(0, \"\n\nCount of colorful numbers for each order of magnitude:\n\");\nTotal:= 0;\nfor Power:= 1 to 8 do\n [Count:= if Power=1 then 1 else 0;\n for N:= IPow(10, Power-1) to IPow(10, Power)-1 do\n if Colorful(N) then Count:= Count+1;\n IntOut(0, Power);\n Text(0, \" digit colorful number count: \");\n IntOut(0, Count);\n CrLf(0);\n Total:= Total + Count;\n ];\nText(0, \"\nTotal colorful numbers: \");\nIntOut(0, Total);\nCrLf(0);\n]\n", "language": "XPL0" } ]
Colorful-numbers
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Colour_bars/Display\n", "language": "00-META" }, { "code": ";Task:\nDisplay a series of vertical color bars across the width of the display. \n\nThe color bars should either use:\n:::* &nbsp; the system palette, &nbsp; or \n:::* &nbsp; the sequence of colors: \n::::::* &nbsp; black\n::::::* &nbsp; red\n::::::* &nbsp; green\n::::::* &nbsp; blue\n::::::* &nbsp; magenta\n::::::* &nbsp; cyan\n::::::* &nbsp; yellow\n::::::* &nbsp; white\n<br>\n\n", "language": "00-TASK" }, { "code": "lda #0\ntax\ntay ;clear regs\n\n;video ram on Easy6502 is four pages ranging from $0200-$0500\n\nloop:\nsta $0200,x\nsta $0220,x\nsta $0240,x\nsta $0260,x\nsta $0280,x\nsta $02A0,x\nsta $02C0,x\nsta $02E0,x\n\nsta $0300,x\nsta $0320,x\nsta $0340,x\nsta $0360,x\nsta $0380,x\nsta $03A0,x\nsta $03C0,x\nsta $03E0,x\n\nsta $0400,x\nsta $0420,x\nsta $0440,x\nsta $0460,x\nsta $0480,x\nsta $04A0,x\nsta $04C0,x\nsta $04E0,x\n\nsta $0500,x\nsta $0520,x\nsta $0540,x\nsta $0560,x\nsta $0580,x\nsta $05A0,x\nsta $05C0,x\nsta $05E0,x\n\ninx\ntxa ;effectively increment A\ncpx #$20 ;32 columns of video memory\nbeq exit\njmp loop\nexit:\nbrk ;on easy6502 this terminates a program.\n", "language": "6502-Assembly" }, { "code": "PROC Main()\n BYTE\n i,\n CH=$02FC, ;Internal hardware value for last key pressed\n PALNTSC=$D014, ;To check if PAL or NTSC system is used\n PCOLR0=$02C0,PCOLR1=$02C1,\n PCOLR2=$02C2,PCOLR3=$02C3,\n COLOR0=$02C4,COLOR1=$02C5,\n COLOR2=$02C6,COLOR3=$02C7,\n COLOR4=$02C8\n\n Graphics(10)\n PCOLR0=$04 ;gray\n PCOLR1=$00 ;black\n IF PALNTSC=15 THEN\n PCOLR2=$42 ;red for NTSC\n PCOLR3=$C6 ;green for NTSC\n COLOR0=$84 ;blue for NTSC\n COLOR1=$66 ;magenta for NTSC\n COLOR2=$A6 ;cyan for NTSC\n COLOR3=$FC ;yellow for NTSC\n ELSE\n PCOLR2=$22 ;red for PAL\n PCOLR3=$B6 ;green for PAL\n COLOR0=$74 ;blue for PAL\n COLOR1=$48 ;magenta for PAL\n COLOR2=$96 ;cyan for PAL\n COLOR3=$EC ;yellow for PAL\n FI\n COLOR4=$0F ;white\n\n FOR i=0 TO 79\n DO\n Color=i/10+1\n Plot(i,0)\n DrawTo(i,191)\n OD\n\n DO UNTIL CH#$FF OD\n CH=$FF\nRETURN\n", "language": "Action-" }, { "code": "package {\n\n import flash.display.Sprite;\n import flash.events.Event;\n\n public class ColourBars extends Sprite {\n\n public function ColourBars():void {\n if (stage) init();\n else addEventListener(Event.ADDED_TO_STAGE, init);\n }\n\n private function init(e:Event = null):void {\n\n var colours:Array = [ 0x000000, 0xFF0000, 0x00FF00, 0x0000FF, 0xFF00FF, 0x00FFFF, 0xFFFF00, 0xFFFFFF ];\n var w:Number = stage.stageWidth / 8, h:Number = stage.stageHeight;\n var x:Number = 0, i:uint, c:uint;\n\n for ( i = 0; i < 8; i++ ) {\n c = colours[i];\n graphics.beginFill(c);\n graphics.drawRect(w * i, 0, w, h);\n }\n\n }\n\n }\n\n}\n", "language": "ActionScript" }, { "code": "with SDL.Video.Windows.Makers;\nwith SDL.Video.Renderers.Makers;\nwith SDL.Video.Palettes;\nwith SDL.Events.Events;\nwith SDL.Events.Keyboards;\n\nprocedure Colour_Bars_Display is\n use type SDL.Events.Event_Types;\n use SDL.C;\n\n Colours : constant array (0 .. 7) of SDL.Video.Palettes.Colour :=\n ((0, 0, 0, 255), (255, 0, 0, 255),\n (0, 255, 0, 255), (0, 0, 255, 255),\n (255, 0, 255, 255), (0, 255, 255, 255),\n (255, 255, 0, 255), (255, 255, 255, 255));\n Window : SDL.Video.Windows.Window;\n Renderer : SDL.Video.Renderers.Renderer;\n Event : SDL.Events.Events.Events;\n Bar_Width : int;\nbegin\n if not SDL.Initialise (Flags => SDL.Enable_Screen) then\n return;\n end if;\n\n SDL.Video.Windows.Makers.Create (Win => Window,\n Title => \"\",\n Position => SDL.Natural_Coordinates'(0, 0),\n Size => SDL.Positive_Sizes'(0, 0),\n Flags => SDL.Video.Windows.Full_Screen_Desktop);\n SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);\n\n Bar_Width := Window.Get_Size.Width / 8;\n for A in Colours'Range loop\n Renderer.Set_Draw_Colour (Colour => Colours (A));\n Renderer.Fill (Rectangle => (X => SDL.C.int (A) * Bar_Width, Y => 0,\n Width => Bar_Width,\n Height => Window.Get_Size.Height));\n end loop;\n Window.Update_Surface;\n\n Wait_Loop : loop\n while SDL.Events.Events.Poll (Event) loop\n exit Wait_Loop when Event.Common.Event_Type = SDL.Events.Keyboards.Key_Down;\n end loop;\n delay 0.050;\n end loop Wait_Loop;\n Window.Finalize;\n SDL.Finalise;\nend Colour_Bars_Display;\n", "language": "Ada" }, { "code": "SCREEN 1,320,200,5,1\nWINDOW 2,\"Color bars\",(0,10)-(297,186),15,1\nFOR a=0 TO 300\n LINE (a,0)-(a,186),(a+10)/10\nNEXT\nloop: GOTO loop\n", "language": "AmigaBASIC" }, { "code": "1 DATA1,12,6,3,14,13,15\n2 HOME : GR : FOR I = 1 TO 7\n3 READ C(I) : NEXT\n4 FOR I = 0 TO 39\n5 COLOR= C(I / 5)\n6 VLIN 0,39 AT I : NEXT\n", "language": "Applesoft-BASIC" }, { "code": "#SingleInstance, Force\n#NoEnv\nSetBatchLines, -1\n\n; Uncomment if Gdip.ahk is not in your standard library\n;#Include, Gdip.ahk\n\n; Start gdi+\nIf !pToken := Gdip_Startup()\n{\n message =\n ( LTrim\n gdiplus error!, Gdiplus failed to start.\n Please ensure you have gdiplus on your system.\n )\n MsgBox, 48, %message%\n ExitApp\n}\nOnExit, Exit\n\n; Set the width and height we want as our drawing area, to draw everything in.\n; This will be the dimensions of our bitmap\nWidth := A_ScreenWidth, Height := A_ScreenHeight\n\n; Create a layered window\n; (+E0x80000 : must be used for UpdateLayeredWindow to work!)\n; that is always on top (+AlwaysOnTop), has no taskbar entry or caption\nGui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop\n\n; Show the window\nGui, 1: Show, NA\n\n; Get a handle to this window we have created in order to update it later\nhwnd1 := WinExist()\n\n; Create a gdi bitmap with width and height of what we are going to\n; draw into it. This is the entire drawing area for everything\nhbm := CreateDIBSection(Width, Height)\n\n; Get a device context compatible with the screen\nhdc := CreateCompatibleDC()\n\n; Select the bitmap into the device context\nobm := SelectObject(hdc, hbm)\n\n; Get a pointer to the graphics of the bitmap, for use with drawing functions\nG := Gdip_GraphicsFromHDC(hdc)\n\n; ARGB = Transparency, Red, Green, Blue\nColors := \"0xFF000000,0xFFFF0000,0xFF00FF00,0xFF0000FF\"\nColors .= \",0xFFFF00FF,0xFF00FFFF,0xFFFFFF00,0xFFFFFFFF\"\n; This list ^ is Black, Red, Green, Blue, Magenta, Cyan, Yellow, White\nStringSplit Colors, Colors, `,\nw := Width // Colors0\nLoop % Colors0\n{\n ; Create a brush to draw a rectangle\n pBrush := Gdip_BrushCreateSolid(Colors%A_Index%)\n\n ; Fill the graphics of the bitmap with a rectangle using the brush created\n Gdip_FillRectangle(G, pBrush, w*(A_Index-1), 0, w, height)\n\n ; Delete the brush as it is no longer needed and wastes memory\n Gdip_DeleteBrush(pBrush)\n}\n; Update the specified window we have created (hwnd1) with a handle to our\n; bitmap (hdc), specifying the x,y,w,h we want it positioned on our screen\n; So this will position our gui at (0,0) with the Width and\n; Height specified earlier\nUpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)\n\n\n; Select the object back into the hdc\nSelectObject(hdc, obm)\n\n; Now the bitmap may be deleted\nDeleteObject(hbm)\n\n; Also the device context related to the bitmap may be deleted\nDeleteDC(hdc)\n\n; The graphics may now be deleted\nGdip_DeleteGraphics(G)\nReturn\n\n;#######################################################################\n\nGuiEscape:\nExit:\n; gdi+ may now be shutdown on exiting the program\nGdip_Shutdown(pToken)\nExitApp\nReturn\n", "language": "AutoHotkey" }, { "code": "BEGIN {\n nrcolors = 8\n\n for (height=0; height<20; height++) {\n for (width=0; width<nrcolors; width++) {\n # print (ANSI) basic color and amount of spaces\n printf(\"\\033[%dm%*s\", width + 40, 64 / nrcolors, \" \")\n }\n\n # reset color and print newline\n printf(\"\\033[0m\\n\")\n }\n}\n", "language": "AWK" }, { "code": " SW_MAXIMIZE = 3\n SYS \"ShowWindow\", @hwnd%, SW_MAXIMIZE\n VDU 26\n\n W% = @vdu%!208 / 4\n H% = @vdu%!212 * 2\n\n COLOUR 1,9\n COLOUR 2,10\n COLOUR 3,12\n COLOUR 4,13\n COLOUR 5,14\n COLOUR 6,11\n COLOUR 7,15\n\n FOR C% = 0 TO 7\n GCOL C%\n RECTANGLE FILL C%*W%, 0, W%, H%\n NEXT\n", "language": "BBC-BASIC" }, { "code": "<v%\"P\": <<*\"(2\"\nv_:\"P\"/\"[\"39*,, :55+/68v\nv,,,\";1H\" ,+*86%+55 ,+*<\n73654210v,,\\,,,*93\"[4m\"<\n>$:55+%#v_:1-\"P\"%55+/3g^\n39*,,,~@>48*,1-:#v_$\"m[\"\n", "language": "Befunge" }, { "code": "#include<conio.h>\n\n#define COLOURS 8\n\nint main()\n{\n\tint colour=0,i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\ttextbackground(BLACK); //8 colour constants are defined\n\tclrscr();\n\t\n\tfor(colour=0;colour<COLOURS;colour++)\n\t{\n\t\tgetch(); //waits for a key hit\n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1);\n\t\ttextbackground(colour);\n\t\tfor(j=0;j<MAXROW;j++){\n\t\t\tfor(i=0;i<MAXCOL/COLOURS;i++){\n\t\t\t\tcprintf(\" \");\n\t\t\t}\n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1+j);\n\t\t}\n\t}\n\n\tgetch();\n\ttextbackground(BLACK);\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include<graphics.h>\n#include<conio.h>\n\nint main()\n{\n\tint d=DETECT,m,maxX,maxY,maxColours,i;\n\tinitgraph(&d,&m,\"c:/turboc3/bgi\");\n\tmaxX = getmaxx();\n\tmaxY = getmaxy();\n\tmaxColours = getmaxcolor();\n\n\tfor(i=0;i<maxColours;i++)\n\t{\n\t\tsetfillstyle(SOLID_FILL,i);\n\t\tbar(i*maxX/maxColours,0,(i+1)*maxX/maxColours,maxY);\n\t}\n\n\tgetch();\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "language": "C" }, { "code": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n MyWidget( ) ;\n\nprotected :\n void paintEvent( QPaintEvent * ) ;\nprivate :\n int width ;\n int height ;\n const int colornumber ;\n} ;\n#endif\n", "language": "C++" }, { "code": "#include <QtGui>\n#include \"colorbars.h\"\n\nMyWidget::MyWidget( ) :\n width( 640 ) ,\n height( 240 ) ,\n colornumber( 8 ) {\n setGeometry( 0, 0 , width , height ) ;\n}\n\nvoid MyWidget::paintEvent ( QPaintEvent * ) {\n int rgbtriplets[ ] = { 0 , 0 , 0 , 255 , 0 , 0 , 0 , 255 , 0 ,\n 0 , 0 , 255 , 255 , 0 , 255 , 0 , 255 , 255 , 255 , 255 , 0 ,\n 255 , 255 , 255 } ;\n QPainter myPaint( this ) ;\n int rectwidth = width / colornumber ; //width of one rectangle\n int xstart = 1 ; //x coordinate of the first rectangle\n int offset = -1 ; //to allow for ++offset to define the red value even in the first run of the loop below\n for ( int i = 0 ; i < colornumber ; i++ ) {\n QColor rectColor ;\n rectColor.setRed( rgbtriplets[ ++offset ] ) ;\n rectColor.setGreen( rgbtriplets[ ++offset ] ) ;\n rectColor.setBlue( rgbtriplets[ ++offset ] ) ;\n myPaint.fillRect( xstart , 0 , rectwidth , height - 1 , rectColor ) ;\n xstart += rectwidth + 1 ;\n }\n}\n", "language": "C++" }, { "code": "#include <QApplication>\n#include \"colorbars.h\"\n\nint main( int argc, char * argv[ ] ) {\n QApplication app( argc , argv ) ;\n MyWidget window ;\n window.setWindowTitle( QApplication::translate( \"colorslides\" , \"color slides demonstration\" ) ) ;\n window.show( ) ;\n return app.exec( ) ;\n}\n", "language": "C++" }, { "code": "100 rem Colour bars/Display\n110 graphics 0 : graphics cls\n120 for i = 0 to 7\n130 read r,g,b\n140 graphics color r,g,b\n150 for j = 0 to 79\n160 x = i*80+j\n170 graphics moveto x,0\n180 graphics lineto x,399\n190 next j\n200 next i\n500 data 0,0,0 : rem black\n510 data 100,0,0 : rem red\n520 data 0,100,0 : rem green\n530 data 0,0,100 : rem blue\n540 data 100,0,100 : rem magenta\n550 data 0,100,100 : rem cyan\n560 data 100,100,0 : rem yellow\n570 data 100,100,100 : rem white\n", "language": "Chipmunk-Basic" }, { "code": " IDENTIFICATION DIVISION.\n PROGRAM-ID. terminal-colour-bars.\n\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 width PIC 9(3).\n 01 height PIC 9(3).\n\n 01 interval PIC 9(3).\n\n 01 colours-area.\n 03 colour-values.\n 05 FILLER PIC 9 VALUE 0. *> Black\n 05 FILLER PIC 9 VALUE 4. *> Red\n 05 FILLER PIC 9 VALUE 2. *> Green\n 05 FILLER PIC 9 VALUE 1. *> Blue\n 05 FILLER PIC 9 VALUE 5. *> Magneta\n 05 FILLER PIC 9 VALUE 3. *> Cyan\n 05 FILLER PIC 9 VALUE 6. *> Yellow\n 05 FILLER PIC 9 VALUE 7. *> White\n\n 03 colour-table REDEFINES colour-values.\n 05 colours PIC 9 OCCURS 8 TIMES INDEXED BY colour-index.\n\n 01 i PIC 9(3).\n 01 j PIC 9(3).\n\n PROCEDURE DIVISION.\n ACCEPT width FROM COLUMNS\n ACCEPT height FROM LINES\n DIVIDE width BY 8 GIVING interval\n\n PERFORM VARYING i FROM 1 BY 1 UNTIL height < i\n PERFORM VARYING j FROM 1 BY 1 UNTIL width < j\n COMPUTE colour-index = (j / interval) + 1\n\n IF 8 < colour-index\n SET colour-index TO 8\n END-IF\n\n *> Some colours come a bit darker than they\n *> should, with the yellow being orange and the white\n *> being light-grey.\n DISPLAY SPACE AT LINE i COLUMN j\n WITH BACKGROUND-COLOR colours (colour-index)\n END-PERFORM\n END-PERFORM\n\n ACCEPT i *> Prevent ncurses returning to console immediately.\n\n GOBACK\n .\n", "language": "COBOL" }, { "code": "5 rem color bars program\n10 print chr$(147);:dim co(17):c=1\n20 read co(c):if co(c)>0 then c=c+1:goto 20\n25 sp$=\" \":h=22:c=c-1:rem sp$=5 spaces\n30 for r=1 to c step int(c/2)\n40 for h=1 to 10\n50 for b=r to (r+int(c/2))-1\n60 print chr$(18);chr$(co(b));sp$;\n70 next b\n75 rem check if palette is only 8 (vic-20).\n76 rem if so, we need to fill the last two spaces.\n80 if c<=8 then print \" \";\n90 next h:next r\n100 get k$:if k$=\"\" then 100\n110 end\n280 rem because the control codes for color are non-sequential,\n285 rem we put them into a sequential array for use\n300 data 144,5,28,159,156,30,31,158\n305 rem omit or rem the next line for vic-20\n310 data 129,149,150,151,152,153,154,155\n320 data 0:rem data terminato\n", "language": "Commodore-BASIC" }, { "code": "unit Colour_barsDisplay;\n\ninterface\n\nuses\n Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms;\n\ntype\n TfmColourBar = class(TForm)\n procedure FormPaint(Sender: TObject);\n procedure FormResize(Sender: TObject);\n private\n { Private declarations }\n public\n { Public declarations }\n end;\n\nvar\n fmColourBar: TfmColourBar;\n Colors: array of TColor = [clblack, clred, clgreen, clblue, clFuchsia, clAqua,\n clyellow, clwhite];\n\nimplementation\n\n{$R *.dfm}\n\nprocedure TfmColourBar.FormPaint(Sender: TObject);\nvar\n w, h, i: Integer;\n r: TRect;\nbegin\n w := ClientWidth div length(Colors);\n h := ClientHeight;\n r := Rect(0, 0, w, h);\n\n with Canvas do\n for i := 0 to High(Colors) do\n begin\n Brush.Color := Colors[i];\n FillRect(r);\n r.Offset(w, 0);\n end;\nend;\n\nprocedure TfmColourBar.FormResize(Sender: TObject);\nbegin\n Invalidate;\nend;\nend.\n", "language": "Delphi" }, { "code": "object fmColourBar: TfmColourBar\n Caption = 'fmColourBar'\n OldCreateOrder = False\n OnPaint = FormPaint\n OnResize = FormResize\nend\n", "language": "Delphi" }, { "code": "col[] = [ 000 900 090 009 909 099 990 999 ]\nw = 100 / len col[]\nfor i = 1 to len col[]\n color col[i]\n move w * (i - 1) 0\n rect w 100\n.\n", "language": "EasyLang" }, { "code": "USING: accessors colors.constants kernel math sequences ui\nui.gadgets ui.gadgets.tracks ui.pens.solid ;\nIN: rosetta-code.colour-bars-display\n\n: colors ( -- ) [\nhorizontal <track>\n{\n COLOR: black\n COLOR: red\n COLOR: green\n COLOR: blue\n COLOR: magenta\n COLOR: cyan\n COLOR: yellow\n COLOR: white\n}\n[ <solid> gadget new swap >>interior ] map\ndup length recip\n[ track-add ] curry each\n{ 640 480 } >>pref-dim\n\"bars\" open-window\n] with-ui ;\nMAIN: colors\n", "language": "Factor" }, { "code": "\\ Color Bars for TI-99 CAMEL99 Forth\n\nNEEDS HCHAR FROM DSK1.GRAFIX \\ TMS9918 control lexicon\nNEEDS CHARSET FROM DSK1.CHARSET \\ restores default character data\nNEEDS ENUM FROM DSK1.ENUM \\ add simple enumerator to Forth\n\n\\ Name TI-99 colors\n1 ENUM CLR ENUM BLK ENUM MGRN ENUM LGRN\n ENUM BLU ENUM LBLU ENUM RED ENUM CYAN\n ENUM MRED ENUM LRED ENUM YEL ENUM LYEL\n ENUM GRN ENUM MAG ENUM GRY ENUM WHT\nDROP\n\n\\ square character data\nHEX\nCREATE SQUARE FFFF , FFFF , FFFF , FFFF ,\n\nDECIMAL\n: COLOR-BARS ( -- )\n 24 0 DO\n\\ col row char wid\n\\ --- --- ---- ---\n 2 I 88 4 HCHAR\n 6 I 96 4 HCHAR\n 10 I 104 4 HCHAR\n 14 I 112 4 HCHAR\n 18 I 120 4 HCHAR\n 22 I 128 4 HCHAR\n 26 I 136 4 HCHAR\n LOOP ;\n\nDECIMAL\n: DEFCHARS ( pattern first last -- )\n 1+ SWAP ?DO DUP I CHARDEF 8 +LOOP DROP ;\n\n: SET-COLORS ( -- )\n\\ charset fg bg\n\\ ------- -- --\n 88 SET# GRY CLR COLOR\n 96 SET# YEL CLR COLOR\n 104 SET# CYAN CLR COLOR\n 112 SET# GRN CLR COLOR\n 120 SET# MAG CLR COLOR\n 128 SET# RED CLR COLOR\n 136 SET# BLU CLR COLOR\n 144 SET# BLK CLR COLOR ;\n\n\\ restore characters and colors\n: DEFAULTS\n 8 SCREEN\n 4 19 BLK CLR COLORS\n CLEAR\n CHARSET ;\n\n: BARS\n CLEAR BLK SCREEN\n SET-COLORS\n SQUARE 88 152 DEFCHARS\n COLOR-BARS\n BEGIN ?TERMINAL UNTIL\n DEFAULTS\n;\n\nCR .( Done. Type BARS to run)\n", "language": "Forth" }, { "code": "' FB 1.05.0 Win64\n\n' Draw the color bars on an 80 x 25 console using the system palette of 16 colors\n' i.e. 5 columns per color\nWidth 80, 25\nShell \"cls\"\nLocate ,, 0 '' turn cursor off\nFor clr As UInteger = 0 To 15\n Color 0, clr\n For row As Integer = 1 to 25\n Locate row, clr * 5 + 1\n Print Space(5);\n Next row\nNext clr\n\nSleep\n' restore default settings\nLocate ,, 1 '' turn cursor on\nColor 7, 0 '' white text on black background\n", "language": "FreeBASIC" }, { "code": "void local fn DoIt\n long index, x = 0\n CFArrayRef colors = @[fn ColorBlack,fn ColorRed,\n fn ColorGreen,fn ColorBlue,fn ColorMagenta,\n fn ColorCyan,fn ColorYellow,fn ColorWhite]\n\n window 1, @\"Color bars/Display\", (0,0,480,270), NSWindowStyleMaskTitled\n\n pen -1\n for index = 0 to len(colors) - 1\n rect fill (x,0,60,270), colors[index]\n x += 60\n next\nend fn\n\nfn DoIt\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Form_Open()\nDim iColour As Integer[] = [Color.Black, Color.red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.white]\nDim hPanel As Panel\nDim siCount As Short\n\nWith Me\n .Arrangement = Arrange.Horizontal\n .Height = 300\n .Width = 400\nEnd With\n\nFor siCount = 0 To 6\n hpanel = New Panel(Me)\n hpanel.Expand = True\n hpanel.H = 500\n HPanel.Background = iColour[siCount]\nNext\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n \"000000\", // black\n \"FF0000\", // red\n \"00FF00\", // green\n \"0000FF\", // blue\n \"FF00FF\", // magenta\n \"00FFFF\", // cyan\n \"FFFF00\", // yellow\n \"FFFFFF\", // white\n}\n\nfunc drawBars(dc *gg.Context) {\n w := float64(dc.Width() / len(colors))\n h := float64(dc.Height())\n for i := range colors {\n dc.SetHexColor(colors[i])\n dc.DrawRectangle(w*float64(i), 0, w, h)\n dc.Fill()\n }\n}\n\nfunc main() {\n dc := gg.NewContext(400, 400)\n drawBars(dc)\n dc.SavePNG(\"color_bars.png\")\n}\n", "language": "Go" }, { "code": "#!/usr/bin/env stack\n-- stack --resolver lts-7.0 --install-ghc runghc --package vty -- -threaded\n\nimport Graphics.Vty\n\ncolorBars :: Int -> [(Int, Attr)] -> Image\ncolorBars h bars = horizCat $ map colorBar bars\n where colorBar (w, attr) = charFill attr ' ' w h\n\nbarWidths :: Int -> Int -> [Int]\nbarWidths nBars totalWidth = map barWidth [0..nBars-1]\n where fracWidth = fromIntegral totalWidth / fromIntegral nBars\n barWidth n =\n let n' = fromIntegral n :: Double\n in floor ((n' + 1) * fracWidth) - floor (n' * fracWidth)\n\nbarImage :: Int -> Int -> Image\nbarImage w h = colorBars h $ zip (barWidths nBars w) attrs\n where attrs = map color2attr colors\n nBars = length colors\n colors = [black, brightRed, brightGreen, brightBlue, brightMagenta, brightCyan, brightYellow, brightWhite]\n color2attr c = Attr Default Default (SetTo c)\n\nmain :: IO ()\nmain = do\n cfg <- standardIOConfig\n vty <- mkVty cfg\n let output = outputIface vty\n bounds <- displayBounds output\n let showBars (w,h) = do\n let img = barImage w h\n pic = picForImage img\n update vty pic\n e <- nextEvent vty\n case e of\n EvResize w' h' -> showBars (w',h')\n _ -> return ()\n showBars bounds\n shutdown vty\n", "language": "Haskell" }, { "code": "-- Before you can install the SFML Haskell library, you need to install\n-- the CSFML C library. (For example, \"brew install csfml\" on OS X.)\n\n-- This program runs in fullscreen mode.\n-- Press any key or mouse button to exit.\n\nimport Control.Exception\nimport SFML.Graphics\nimport SFML.SFResource\nimport SFML.Window hiding (width, height)\n\nwithResource :: SFResource a => IO a -> (a -> IO b) -> IO b\nwithResource acquire = bracket acquire destroy\n\nwithResources :: SFResource a => IO [a] -> ([a] -> IO b) -> IO b\nwithResources acquire = bracket acquire (mapM_ destroy)\n\ncolors :: [Color]\ncolors = [black, red, green, magenta, cyan, yellow, white]\n\nmakeBar :: (Float, Float) -> (Color, Int) -> IO RectangleShape\nmakeBar (barWidth, height) (c, i) = do\n bar <- err $ createRectangleShape\n setPosition bar $ Vec2f (fromIntegral i * barWidth) 0\n setSize bar $ Vec2f barWidth height\n setFillColor bar c\n return bar\n\nbarSize :: VideoMode -> (Float, Float)\nbarSize (VideoMode w h _ ) = ( fromIntegral w / fromIntegral (length colors)\n , fromIntegral h )\n\nloop :: RenderWindow -> [RectangleShape] -> IO ()\nloop wnd bars = do\n mapM_ (\\x -> drawRectangle wnd x Nothing) bars\n display wnd\n evt <- waitEvent wnd\n case evt of\n Nothing -> return ()\n Just SFEvtClosed -> return ()\n Just (SFEvtKeyPressed {}) -> return ()\n Just (SFEvtMouseButtonPressed {}) -> return ()\n _ -> loop wnd bars\n\nmain :: IO ()\nmain = do\n vMode <- getDesktopMode\n let wStyle = [SFFullscreen]\n withResource (createRenderWindow vMode \"color bars\" wStyle Nothing) $\n \\wnd -> withResources (mapM (makeBar $ barSize vMode) $ zip colors [0..]) $\n \\bars -> loop wnd bars\n", "language": "Haskell" }, { "code": "link graphics,printf\n\nprocedure main() # generalized colour bars\n DrawTestCard(Simple_TestCard())\n WDone()\nend\n\nprocedure DrawTestCard(TC)\n size := sprintf(\"size=%d,%d\",TC.width,TC.height)\n &window := TC.window := open(TC.id,\"g\",\"bg=black\",size) |\n stop(\"Unable to open window\")\n\n every R := TC.bands[r := 1 to *TC.bands -1] do\n every C := R.bars[c := 1 to *R.bars - 1] do {\n\t Fg(R.bars[c].colour)\n\t FillRectangle( C.left, R.top,\n\t\t R.bars[c+1].left-C.left, TC.bands[r+1].top-R.top )\n\t }\n return TC\nend\n\nrecord testcard(window,id,width,height,bands)\nrecord band(top,bars)\nrecord bar(left,colour)\n\nprocedure Simple_TestCard() #: return structure simple testcard\n return testcard(,\"Simple Test Card\",width := 800,height := 600,\n\t\t [ band( 1, [ bar( 1, \"black\"),\n\t\t\t\t bar(114, \"red\"),\n\t\t\t\t bar(228, \"green\"),\n\t\t\t\t bar(342, \"blue\"),\n bar(456, \"magenta\"),\n bar(570, \"cyan\"),\n bar(684, \"yellow\"),\n bar(width) ] ),\n\t\t band(height) ])\nend\n", "language": "Icon" }, { "code": "procedure SMPTE_TestCard() #: return structure with 480i(ish) testcard\n return testcard(,\"SMPTE TV Test Card\",width := 672,height := 504,\n\t\t [ band( 1, [ bar( 1, \"#c0c0c0\"),\n\t\t\t\t bar( 95, \"#c0c000\"),\n \t \t\t bar(191, \"#00c0c0\"),\n\t\t\t\t bar(288, \"#00c000\"),\n\t\t\t\t bar(383, \"#c000c0\"),\n\t\t\t\t bar(480, \"#c00000\"),\n\t\t\t\t bar(575, \"#0000c0\"),\n\t\t\t\t bar(width) ] ),\n\t\t band(335, [ bar( 1, \"#0000c0\"),\n\t\t\t\t bar( 95, \"#131313\"),\n\t\t\t\t bar(191, \"#c000c0\"),\n\t\t\t\t bar(288, \"#131313\"),\n\t\t\t\t bar(383, \"#00c0c0\"),\n\t\t\t\t bar(480, \"#131313\"),\n\t\t\t\t bar(575, \"#c0c0c0\"),\n\t\t\t bar(width) ] ),\n\t\t band(378, [ bar( 1, \"#00214c\"),\n\t\t\t\t bar(120, \"#ffffff\"),\n\t\t\t\t bar(240, \"#32006a\"),\n\t\t\t\t bar(360, \"#131313\"),\n\t\t\t\t bar(480, \"#090909\"),\n\t\t\t\t bar(512, \"#131313\"),\n\t\t\t\t bar(544, \"#1d1d1d\"),\n\t\t\t\t bar(576, \"#131313\"),\n\t\t\t\t bar(width) ] ),\n\t\t\tband(height) ])\nend\n", "language": "Icon" }, { "code": "100 GRAPHICS LORES 16\n110 SET PALETTE BLACK,RED,GREEN,BLUE,MAGENTA,CYAN,YELLOW,WHITE\n120 FOR I=1 TO 7\n130 CALL BAR(I)\n140 NEXT\n150 DEF BAR(C)\n160 SET INK C\n170 PLOT C*160,0;C*160,719;C*160+152,719;C*160+152,0;C*160,0\n180 PLOT C*160+16,16,PAINT\n190 END DEF\n", "language": "IS-BASIC" }, { "code": " load 'viewmat'\n size=: 2{.\".wd'qm' NB. J6\n size=: getscreenwh_jgtk_ '' NB. J7\n 'rgb'viewmat (|.size){. (>.&.(%&160)|.size)$ 20# 256#.255*#:i.8\n", "language": "J" }, { "code": "import java.awt.Color;\nimport java.awt.Graphics;\n\nimport javax.swing.JFrame;\n\npublic class ColorFrame extends JFrame {\n\tpublic ColorFrame(int width, int height) {\n\t\tthis.setDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tthis.setSize(width, height);\n\t\tthis.setVisible(true);\n\t}\n\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tColor[] colors = { Color.black, Color.red, Color.green, Color.blue,\n\t\t\t\tColor.pink, Color.CYAN, Color.yellow, Color.white };\n\n\t\tfor (int i = 0; i < colors.length; i++) {\n\t\t\tg.setColor(colors[i]);\n\t\t\tg.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth()\n\t\t\t\t\t/ colors.length, this.getHeight());\n\t\t}\n\t}\n\n\tpublic static void main(String args[]) {\n\t\tnew ColorFrame(200, 200);\n\t}\n}\n", "language": "Java" }, { "code": "using Images\n\ncolors = [colorant\"black\", colorant\"red\", colorant\"green\", colorant\"darkblue\",\n colorant\"purple\", colorant\"blue\", colorant\"yellow\", colorant\"white\"]\nwcol = 60 # width of each color bar\nh, w = 150, wcol * length(colors) + 1\nimg = Matrix{RGB{N0f8}}(h, w);\nfor (j, col) in zip(1:wcol:w, colors)\n img[:, j:j+wcol] = col\nend\nsave(\"data/colourbars.jpg\", img)\n", "language": "Julia" }, { "code": "import java.awt.Color\nimport java.awt.Graphics\nimport javax.swing.JFrame\n\nclass ColorFrame(width: Int, height: Int): JFrame() {\n init {\n defaultCloseOperation = EXIT_ON_CLOSE\n setSize(width, height)\n isVisible = true\n }\n\n override fun paint(g: Graphics) {\n val colors = listOf(Color.black, Color.red, Color.green, Color.blue,\n\t\t Color.pink, Color.cyan, Color.yellow, Color.white)\n val size = colors.size\n for (i in 0 until size) {\n g.color = colors[i]\n g.fillRect(width / size * i, 0, width / size, height)\n }\n }\n}\n\nfun main(args: Array<String>) {\n ColorFrame(400, 400)\n}\n", "language": "Kotlin" }, { "code": "nomainwin\ncolors$=\"black red green blue pink cyan yellow white\"\nWindowWidth=DisplayWidth:WindowHeight=DisplayHeight\nUpperLeftX=1:UpperLeftY=1\nbarWidth=DisplayWidth/8\ngraphicbox #main.g, 0,0,DisplayWidth,DisplayHeight\nopen \"\" for window_popup as #main\n#main \"trapclose [quit]\"\n#main.g \"down; setfocus; when characterInput [quit]\"\n#main.g \"when leftButtonUp [quit]\"\n#main.g \"size \";barWidth\n\nfor x = barWidth/2 to DisplayWidth step barWidth\n i=i+1\n if i>8 then i=1\n col$=word$(colors$,i)\n #main.g \"color \";col$;\"; line \";x;\" 0 \";x;\" \";DisplayHeight\nnext\nwait\n[quit] close #main:end\n", "language": "Liberty-BASIC" }, { "code": "10 MODE 0:BORDER 23\n20 FOR x=0 TO 15\n30 ORIGIN x*40,0\n40 FOR z=0 TO 39 STEP 4:MOVE z,0:DRAW z,400,x:NEXT z\n50 NEXT x\n60 CALL &bb06 ' wait for key press\n", "language": "Locomotive-Basic" }, { "code": "local nw = require(\"nw\")\nlocal app = nw:app()\nlocal cw, ch = 320, 240\nlocal win = app:window(cw, ch, \"Color Bars\", false)\nlocal colors = {{0,0,0}, {1,0,0}, {0,1,0}, {0,0,1}, {1,0,1}, {0,1,1}, {1,1,0}, {1,1,1}}\nlocal unpack = unpack or table.unpack -- polyfill 5.2 vs 5.3\nfunction win:repaint()\n local cr = win:bitmap():cairo()\n for i = 1, #colors do\n cr:rectangle((i-1)*cw/#colors, 0, cw/#colors, ch)\n cr:rgb(unpack(colors[i]))\n cr:fill()\n end\nend\nwin:show()\napp:run()\n", "language": "Lua" }, { "code": "Module Checkit {\n Module Bars {\n barwidth=x.twips div 8\n barheight=y.twips\n barcolors=(0,#ff0000,#00ff00, #0000ff, #FF00FF, #00ffff, #ffff00, #ffffff)\n For i=0 to 7\n Move i*barwidth, 0\n \\\\ gradient fill. Here second color are the same as first color\n Fill barwidth, barheight, array(barcolors, i), array(barcolors, i)\n Next i\n }\n \\\\ first draw on console\n Call Bars\n Declare Form1 Form\n Layer Form1 {\n window 12, 10000,8000;\n \\\\ now draw on Form1 layer, above console, in a window\n Call Bars\n }\n Method Form1, \"Show\", 1 ' open modal\n Declare Form1 Nothing\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "with(plottools):\nplots:-display([rectangle([0, 0], [.3, 2.1], color = black), rectangle([.3, 0], [.6, 2.1], color = red), rectangle([.6, 0], [.9, 2.1], color = green), rectangle([.9, 0], [1.2, 2.1], color = magenta), rectangle([1.2, 0], [1.5, 2.1], color = cyan), rectangle([1.5, 0], [1.8, 2.1], color = white), rectangle([1.8, 0], [2.1, 2.1], color = yellow)])\n", "language": "Maple" }, { "code": "ArrayPlot[\n ConstantArray[{Black, Red, Green, Blue, Magenta, Cyan, Yellow,\n White}, 5]]\n", "language": "Mathematica" }, { "code": "import gintro/[glib, gobject, gtk, gio, cairo]\n\nconst\n Width = 400\n Height = 300\n\n#---------------------------------------------------------------------------------------------------\n\nproc draw(area: DrawingArea; context: Context) =\n ## Draw the color bars.\n\n const Colors = [[0.0, 0.0, 0.0], [255.0, 0.0, 0.0],\n [0.0, 255.0, 0.0], [0.0, 0.0, 255.0],\n [255.0, 0.0, 255.0], [0.0, 255.0, 255.0],\n [255.0, 255.0, 0.0], [255.0, 255.0, 255.0]]\n\n const\n RectWidth = float(Width div Colors.len)\n RectHeight = float(Height)\n\n var x = 0.0\n for color in Colors:\n context.rectangle(x, 0, RectWidth, RectHeight)\n context.setSource(color)\n context.fill()\n x += RectWidth\n\n#---------------------------------------------------------------------------------------------------\n\nproc onDraw(area: DrawingArea; context: Context; data: pointer): bool =\n ## Callback to draw/redraw the drawing area contents.\n\n area.draw(context)\n result = true\n\n#---------------------------------------------------------------------------------------------------\n\nproc activate(app: Application) =\n ## Activate the application.\n\n let window = app.newApplicationWindow()\n window.setSizeRequest(Width, Height)\n window.setTitle(\"Color bars\")\n\n # Create the drawing area.\n let area = newDrawingArea()\n window.add(area)\n\n # Connect the \"draw\" event to the callback to draw the spiral.\n discard area.connect(\"draw\", ondraw, pointer(nil))\n\n window.showAll()\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nlet app = newApplication(Application, \"Rosetta.ColorBars\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n", "language": "Nim" }, { "code": "open Graphics\n\nlet round x =\n int_of_float (floor (x +. 0.5))\n\nlet () =\n open_graph \"\";\n let cols = size_x () in\n let rows = size_y () in\n let colors = [| black; red; green; blue; magenta; cyan; yellow; white |] in\n let n = Array.length colors in\n let bar_width = (float cols) /. (float n) in\n Array.iteri (fun i color ->\n let x1 = bar_width *. (float i) in\n let x2 = bar_width *. (float (succ i)) in\n set_color color;\n fill_rect (round x1) 0 (round x2) rows;\n ) colors;\n ignore (read_key ());\n;;\n", "language": "OCaml" }, { "code": "use strict;\nuse warnings;\nuse GD;\n\nmy %colors = (\nwhite => [255,255,255], red => [255, 0, 0], green => [ 0,255, 0], blue => [ 0, 0,255],\nmagenta => [255, 0,255], yellow => [255,255, 0], cyan => [ 0,255,255], black => [ 0, 0, 0]);\n\nmy $start = 0;\nmy $barwidth = 160 / 8;\nmy $image = GD::Image->new( 160 , 100 );\n\nfor my $rgb ( values %colors ) {\n $image->filledRectangle( $start * $barwidth , 0 , $start * $barwidth +\n\t $barwidth - 1 , 99 , $image->colorAllocate( @$rgb ) );\n $start++ ;\n}\nopen ( DISPLAY , \">\" , \"bars.png\" ) or die;\nbinmode DISPLAY;\nprint DISPLAY $image->png;\nclose DISPLAY;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">-- demo\\rosetta\\Colour_bars.exw</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">colours</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #004600;\">CD_BLACK</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_RED</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_GREEN</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_BLUE</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_MAGENTA</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_CYAN</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_YELLOW</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_WHITE</span><span style=\"color: #0000FF;\">}</span>\n\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas</span>\n <span style=\"color: #004080;\">cdCanvas</span> <span style=\"color: #000000;\">cdcanvas</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">redraw_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000080;font-style:italic;\">/*posx*/</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">/*posy*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetIntInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"DRAWSIZE\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">lc</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">colours</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasActivate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cdcanvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">lc</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">w</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">((</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)/(</span><span style=\"color: #000000;\">lc</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">cdCanvasSetForeground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cdcanvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">colours</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #7060A8;\">cdCanvasBox</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cdcanvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">w</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">cdCanvasFlush</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cdcanvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">canvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"redraw_cb\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"RASTERSIZE=600x400\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- initial size</span>\n <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`TITLE=\"Colour bars\"`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupMap</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cdcanvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_IUP</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"RASTERSIZE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- release the minimum limitation</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\n$colors = array(array( 0, 0, 0), // black\n array(255, 0, 0), // red\n array( 0, 255, 0), // green\n array( 0, 0, 255), // blue\n array(255, 0, 255), // magenta\n array( 0, 255, 255), // cyan\n array(255, 255, 0), // yellow\n array(255, 255, 255)); // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT', 480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n imagefilledrectangle($image, $position * BARWIDTH, 0,\n $position * BARWIDTH + BARWIDTH - 1,\n HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n", "language": "PHP" }, { "code": "<?php\n$colors = array(\n \"000000\", // black\n \"FF0000\", // red\n \"00FF00\", // green\n \"0000FF\", // blue\n \"FF00FF\", // magenta\n \"00FFFF\", // cyan\n \"FFFF00\", // yellow\n \"FFFFFF\", // white\n );\n\necho '<table style=\"border: 1px solid black; border-spacing: 0;\"><tr>';\nforeach ($colors as $color) {\n echo '<td style=\"background-color: #'.$color.'; height: 100px; width: 20px;\"></td>';\n}\necho '</tr></table>';\n", "language": "PHP" }, { "code": "(call 'clear)\n\n(let Width (in '(tput cols) (read))\n (do (in '(tput lines) (read))\n (for B (range 0 7)\n (call 'tput 'setab B)\n (space (/ Width 8)) )\n (prinl) ) )\n\n(call 'tput 'sgr0) # reset\n", "language": "PicoLisp" }, { "code": "To run:\nStart up.\nClear the screen.\nDivide the screen width by 8 giving a bar width.\nMake a bar with 0 and 0 and the bar width and the screen's bottom.\nDraw the color bars using the bar.\nRefresh the screen.\nWait for the escape key.\nShut down.\n\nTo divide the screen width by a number giving a width:\nPut the screen's right into the width.\nDivide the width by the number.\n\nA bar is a box.\n\nTo draw a bar using a color and move it over:\nDraw and fill the bar with the color.\nMove the bar right the bar's width.\n\nTo draw the color bars using a bar:\nDraw the bar using the black color and move it over.\nDraw the bar using the red color and move it over.\nDraw the bar using the green color and move it over.\nDraw the bar using the blue color and move it over.\nDraw the bar using the magenta color and move it over.\nDraw the bar using the cyan color and move it over.\nDraw the bar using the yellow color and move it over.\nDraw and fill the bar using the white color.\n", "language": "Plain-English" }, { "code": "[string[]]$colors = \"Black\" , \"DarkBlue\" , \"DarkGreen\" , \"DarkCyan\",\n \"DarkRed\" , \"DarkMagenta\", \"DarkYellow\", \"Gray\",\n \"DarkGray\", \"Blue\" , \"Green\" , \"Cyan\",\n \"Red\" , \"Magenta\" , \"Yellow\" , \"White\"\n\nfor ($i = 0; $i -lt 64; $i++)\n{\n for ($j = 0; $j -lt $colors.Count; $j++)\n {\n Write-Host (\" \" * 12) -BackgroundColor $colors[$j] -NoNewline\n }\n\n Write-Host\n}\n", "language": "PowerShell" }, { "code": "fullScreen();\nnoStroke();\ncolor[] cs = {\n color(0), // black\n color(255,0,0), // red\n color(0,255,0), // green\n color(255,0,255), // magenta\n color(0,255,255), // cyan\n color(255,255,0), // yellow\n color(255) // white\n};\nfor(int i=0; i<7; i++) {\n fill(cs[i]);\n rect(i*width/8,0,width/8,height);\n}\n", "language": "Processing" }, { "code": "Dim color(7)\ncolor(0) = RGB($00, $00, $00) ;black\ncolor(1) = RGB($FF, $00, $00) ;red\ncolor(2) = RGB($00, $FF, $00) ;green\ncolor(3) = RGB($00, $00, $FF) ;blue\ncolor(4) = RGB($FF, $00, $FF) ;magenta\ncolor(5) = RGB($00, $FF, $FF) ;cyan\ncolor(6) = RGB($FF, $FF, $00) ;yellow\ncolor(7) = RGB($FF, $FF, $FF) ;white\n\nIf Not InitKeyboard(): End: EndIf ;can't init keyboard\nIf Not InitSprite(): End: EndIf ;can't init sprite/screen library\nIf Not ExamineDesktops(): End: EndIf ;can't retrieve information about desktop\n\nheight = DesktopHeight(0)\nwidth = DesktopWidth(0)\ndepth = DesktopDepth(0)\nIf OpenScreen(width, height, depth, \"Press ENTER to exit\")\n StartDrawing(ScreenOutput())\n For c = 0 To 7\n Box((width * c) / 8, 0, width / 8, height, color(c))\n Next\n StopDrawing()\n FlipBuffers()\n\n Repeat\n Delay(10)\n ExamineKeyboard()\n Until KeyboardPushed(#PB_Key_Escape) Or KeyboardPushed(#PB_Key_Return)\n CloseScreen()\nEndIf\n", "language": "PureBasic" }, { "code": "DataSection\n ;Black, Red, Green, Blue, Magenta, Cyan, Yellow, White\n Data.i 0, 12, 10, 9, 13, 11, 14, 15\nEndDataSection\n\nDim colors(7)\nFor c = 0 To 7\n Read.i colors(c)\nNext\n\nIf OpenConsole()\n ;The console display is 80 columns wide by 25 rows\n For r = 0 To 24\n For c = 0 To 7\n ConsoleColor(colors(c), colors(c))\n Print(Space(80 / 8))\n Next\n Next\n EnableGraphicalConsole(1)\n ConsoleLocate(0, 0)\n\n ConsoleTitle(\"Press ENTER to exit\"): Input()\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": "#!/usr/bin/env python\n#vertical coloured stripes in window in Python 2.7.1\n\nfrom livewires import *\n\nhoriz=640; vert=480\nbegin_graphics(width=horiz,height=vert,title=\"v_stripes\",background=Colour.black)\nNameColors=[\"black\",\"red\",\"green\",\"dark_blue\",\"purple\",\"blue\",\"yellow\",\"white\"]\nstepik=horiz/len(NameColors)\n\nfor index,each in enumerate(NameColors):\n\tExcStrng=\"set_colour(Colour.\"+each+\")\"\n\texec ExcStrng\n\tbox(index*stepik,0,(index+1)*stepik,vert,filled=1)\n\nwhile keys_pressed() != ['x']: # press x key to terminate program\n\tpass\n\nend_graphics()\n", "language": "Python" }, { "code": "pal <- c(\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\")\npar(mar = rep(0, 4))\nimage(matrix(1:8), col = pal, axes = FALSE)\n", "language": "R" }, { "code": "#lang racket/gui\n\n(define-values [W H] (get-display-size #t))\n\n(define colors\n '(\"Black\" \"Red\" \"Green\" \"Blue\" \"Magenta\" \"Cyan\" \"Yellow\" \"White\"))\n\n(define (paint-pinstripe canvas dc)\n (send dc set-pen \"black\" 0 'transparent)\n (for ([x (in-range 0 W (/ W (length colors)))] [c colors])\n (send* dc (set-brush c 'solid) (draw-rectangle x 0 W H))))\n\n(define full-frame%\n (class frame%\n (define/override (on-subwindow-char r e)\n (when (eq? 'escape (send e get-key-code))\n (send this show #f)))\n (super-new\n [label \"Color bars\"] [width W] [height H]\n [style '(no-caption no-resize-border hide-menu-bar no-system-menu)])\n (define c (new canvas% [parent this] [paint-callback paint-pinstripe]))\n (send this show #t)))\n\n(void (new full-frame%))\n", "language": "Racket" }, { "code": "my ($x,$y) = 1280, 720;\n\nmy @colors = map -> $r, $g, $b { Buf.new: |(($r, $g, $b) xx $x div 8) },\n 0, 0, 0,\n 255, 0, 0,\n 0, 255, 0,\n 0, 0, 255,\n 255, 0, 255,\n 0, 255, 255,\n 255, 255, 0,\n 255, 255, 255;\n\nmy $img = open \"colorbars.ppm\", :w orelse die \"Can't create colorbars.ppm: $_\";\n\n$img.print: qq:to/EOH/;\n P6\n # colorbars.ppm\n $x $y\n 255\n EOH\n\nfor ^$y {\n for ^@colors -> $h {\n $img.write: @colors[$h];\n }\n}\n\n$img.close;\n", "language": "Raku" }, { "code": "/*REXX program displays eight colored vertical bars on a full screen. */\nparse value scrsize() with sd sw . /*the screen depth and width. */\nbarWidth=sw%8 /*calculate the bar width. */\n_.=copies('db'x, barWidth) /*the bar, full width. */\n_.8=left(_.,barWidth-1) /*the last bar width, less one. */\n $ = x2c('1b5b73') || x2c(\"1b5b313b33376d\") /* the preamble, and the header. */\nhdr.1 = x2c('1b5b303b33306d') /* \" color black. */\nhdr.2 = x2c('1b5b313b33316d') /* \" color red. */\nhdr.3 = x2c('1b5b313b33326d') /* \" color green. */\nhdr.4 = x2c('1b5b313b33346d') /* \" color blue. */\nhdr.5 = x2c('1b5b313b33356d') /* \" color magenta. */\nhdr.6 = x2c('1b5b313b33366d') /* \" color cyan. */\nhdr.7 = x2c('1b5b313b33336d') /* \" color yellow. */\nhdr.8 = x2c('1b5b313b33376d') /* \" color white. */\n tail = x2c('1b5b751b5b303b313b33363b34303b306d') /* \" epilogue, and the trailer.*/\n /* [↓] last bar width is shrunk. */\n do j=1 for 8 /*build the line, color by color. */\n $=$ || hdr.j || _.j /*append the color header + bar. */\n end /*j*/ /* [↑] color order is the list. */\n /* [↓] the tail is overkill. */\n$=$ || tail /*append the epilogue (trailer). */\n /* [↓] show full screen of bars. */\n do k=1 for sd /*SD = screen depth (from above). */\n say $ /*have REXX display line of bars. */\n end /*k*/ /* [↑] Note: SD could be zero. */\n /*stick a fork in it, we're done. */\n", "language": "REXX" }, { "code": "load \"guilib.ring\"\n\nnew qapp\n {\n win1 = new qwidget() {\n setwindowtitle(\"drawing using qpainter\")\n setwinicon(self,\"C:\\Ring\\bin\\image\\browser.png\")\n setgeometry(100,100,500,600)\n label1 = new qlabel(win1) {\n setgeometry(10,10,400,400)\n settext(\"\")\n }\n new qpushbutton(win1) {\n setgeometry(200,400,100,30)\n settext(\"draw\")\n setclickevent(\"draw()\")\n }\n show()\n }\n exec()\n }\n\nfunc draw\n p1 = new qpicture()\n color = new qcolor() {\n setrgb(0,0,255,255)\n }\n pen = new qpen() {\n setcolor(color)\n setwidth(1)\n }\n new qpainter() {\n begin(p1)\n setpen(pen)\n\n //Black, Red, Green, Blue, Magenta, Cyan, Yellow, White\n\n for n = 1 to 8\n color2 = new qcolor(){\n switch n\n on 1 r=0 g=0 b=0\n on 2 r=255 g=0 b=0\n on 3 r=0 g=255 b=0\n on 4 r=0 g=0 b=255\n on 5 r=255 g=0 b=255\n on 6 r=0 g=255 b=255\n on 7 r=255 g=255 b=0\n on 8 r=255 g=255 b=255\n off\n setrgb(r,g,b,255)\n }\n mybrush = new qbrush() {setstyle(1) setcolor(color2)}\n setbrush(mybrush)\n drawrect(n*25,25,25,70)\n next\n\n endpaint()\n }\n label1 { setpicture(p1) show() }\n", "language": "Ring" }, { "code": "# Array of web colors black, red, green, blue, magenta, cyan, yellow, white\nPALETTE = %w[#000000 #ff0000 #00ff00 #0000ff #ff00ff #00ffff #ffffff].freeze\n\ndef settings\n full_screen\nend\n\ndef setup\n PALETTE.each_with_index do |col, idx|\n fill color(col)\n rect(idx * width / 8, 0, width / 8, height)\n end\nend\n", "language": "Ruby" }, { "code": "colors$ = \"black,red,green,blue,magenta,cyan,yellow,white\"\nhtml \"<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=4><tr height=70>\"\nfor i = 1 to 8\n html \"<td width=20 bgcolor='\";word$(colors$,i,\",\");\"'</td>\"\nnext i\nhtml \"</tr></table>\"\n", "language": "Run-BASIC" }, { "code": "use pixels::{Pixels, SurfaceTexture}; // 0.2.0\nuse winit::event::*; // 0.24.0\nuse winit::event_loop::{ControlFlow, EventLoop};\nuse winit::window::{Fullscreen, WindowBuilder};\n\nfn main() {\n let event_loop = EventLoop::new();\n let window = WindowBuilder::new()\n .with_title(\"Colour Bars\")\n .with_decorations(false)\n .with_fullscreen(Some(Fullscreen::Borderless(None)))\n .build(&event_loop).unwrap();\n let size = window.inner_size();\n let texture = SurfaceTexture::new(size.width, size.height, &window);\n let mut image_buffer = Pixels::new(8, 1, texture).unwrap();\n let frame = image_buffer.get_frame();\n frame.copy_from_slice(&[\n 0x00, 0x00, 0x00, 0xFF, // black\n 0xFF, 0x00, 0x00, 0xFF, // red\n 0x00, 0xFF, 0x00, 0xFF, // green\n 0x00, 0x00, 0xFF, 0xFF, // blue\n 0xFF, 0x00, 0xFF, 0xFF, // magenta\n 0x00, 0xFF, 0xFF, 0xFF, // cyan\n 0xFF, 0xFF, 0x00, 0xFF, // yellow\n 0xFF, 0xFF, 0xFF, 0xFF, // white\n ]);\n\n image_buffer.render().unwrap();\n\n event_loop.run(move |ev, _, flow| {\n match ev {\n Event::WindowEvent {\n event: WindowEvent::KeyboardInput { input, .. }, ..\n } => {\n if input.virtual_keycode == Some(VirtualKeyCode::Escape) {\n *flow = ControlFlow::Exit;\n }\n }\n Event::RedrawRequested(_) | Event::WindowEvent {\n event: WindowEvent::Focused(true), ..\n } => {\n image_buffer.render().unwrap();\n }\n _ => {}\n }\n });\n}\n", "language": "Rust" }, { "code": "import java.awt.Color\nimport scala.swing._\n\nclass ColorBars extends Component {\n override def paintComponent(g:Graphics2D)={\n val colors=List(Color.BLACK, Color.RED, Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN, Color.YELLOW, Color.WHITE)\n val colCount=colors.size\n val deltaX=size.width.toDouble/colCount\n for(x <- 0 until colCount){\n val startX=(deltaX*x).toInt\n val endX=(deltaX*(x+1)).toInt\n g.setColor(colors(x))\n g.fillRect(startX, 0, endX-startX, size.height)\n }\n }\n}\n", "language": "Scala" }, { "code": "new MainFrame(){\n title=\"Color bars\"\n visible=true\n preferredSize=new Dimension(640, 320)\n contents=new ColorBars()\n}\n", "language": "Scala" }, { "code": "require('GD');\n\nvar colors = Hash.new(\n white => [255, 255, 255],\n red => [255, 0, 0],\n green => [0, 255, 0],\n blue => [0, 0, 255],\n magenta => [255, 0, 255],\n yellow => [255, 255, 0],\n cyan => [0, 255, 255],\n black => [0, 0, 0],\n );\n\nvar barwidth = 160/8;\nvar image = %s'GD::Image'.new(160, 100);\nvar start = 0;\n\ncolors.values.each { |rgb|\n var paintcolor = image.colorAllocate(rgb...);\n image.filledRectangle(start * barwidth, 0, start*barwidth + barwidth - 1, 99, paintcolor);\n start++;\n};\n\n%f'colorbars.png'.open('>:raw').print(image.png);\n", "language": "Sidef" }, { "code": "FOR I=0 TO 7\n READ R,G,B\n GFILL I*50,0,I*50+49,239,RGB(R,G,B)\nNEXT\nREPEAT UNTIL BUTTON(0) AND #B\n\nDATA 0,0,0\nDATA 255,0,0\nDATA 0,255,0\nDATA 0,0,255\nDATA 255,0,255\nDATA 0,255,255\nDATA 255,255,0\nDATA 255,255,255\n", "language": "SmileBASIC" }, { "code": "package require Tcl 8.5\npackage require Tk 8.5\n\nwm attributes . -fullscreen 1\npack [canvas .c -highlightthick 0] -fill both -expand 1\nset colors {black red green blue magenta cyan yellow white}\n\nfor {set x 0} {$x < [winfo screenwidth .c]} {incr x 8} {\n .c create rectangle $x 0 [expr {$x+7}] [winfo screenheight .c] \\\n -fill [lindex $colors 0] -outline {}\n set colors [list {*}[lrange $colors 1 end] [lindex $colors 0]]\n}\n", "language": "Tcl" }, { "code": "100 REM SMPTE Format Color Bars\n110 REM with 400 Hz reference tone\n120 CALL CLEAR\n130 CALL SCREEN(2)\n140 CALL COLOR(8,15,1)\n150 CALL COLOR(9,11,1)\n160 CALL COLOR(10,8,1)\n170 CALL COLOR(11,13,1)\n180 CALL COLOR(12,14,1)\n190 CALL COLOR(13,10,1)\n200 CALL COLOR(14,5,1)\n210 CALL COLOR(15,2,1)\n220 CALL COLOR(16,16,1)\n230 GOSUB 510\n240 REM color bars\n250 CALL VCHAR(1,3,88,96)\n260 CALL VCHAR(1,7,96,96)\n270 CALL VCHAR(1,11,104,96)\n280 CALL VCHAR(1,15,112,96)\n290 CALL VCHAR(1,19,120,96)\n300 CALL VCHAR(1,23,128,96)\n310 CALL VCHAR(1,27,136,96)\n320 REM BLACK BAR\n330 CALL HCHAR(19,1,144,224)\n340 REM WHITE BOX\n350 FOR I=19 TO 24\n360 CALL HCHAR(I,8,152,6)\n370 NEXT I\n410 REM SMPTE Complementary boxes\n420 CALL HCHAR(18,3,136,4)\n430 CALL HCHAR(18,7,144,4)\n440 CALL HCHAR(18,11,120,4)\n450 CALL HCHAR(18,15,144,4)\n460 CALL HCHAR(18,19,104,4)\n470 CALL HCHAR(18,23,144,4)\n480 CALL HCHAR(18,27,88,4)\n490 CALL SOUND(3000,400,12)\n500 GOTO 490\n510 SQUARE$=\"FFFFFFFFFFFFFFFF\"\n520 FOR I = 88 TO 152 STEP 8\n530 CALL CHAR(I,SQUARE$)\n540 NEXT I\n590 RETURN\n", "language": "TI-BASIC" }, { "code": "#!/bin/sh\nclear\nWIDTH=`tput cols`\nHEIGHT=`tput lines`\nNUMBARS=8\nBARWIDTH=`expr $WIDTH / $NUMBARS`\n\nl=\"1\" # Set the line counter to 1\nwhile [ \"$l\" -lt $HEIGHT ]; do\n b=\"0\" # Bar counter\n while [ \"$b\" -lt $NUMBARS ]; do\n tput setab $b\n s=\"0\"\n while [ \"$s\" -lt $BARWIDTH ]; do\n echo -n \" \"\n s=`expr $s + 1`\n done\n b=`expr $b + 1`\n done\n echo # newline\n l=`expr $l + 1`\ndone\n\ntput sgr0 # reset\n", "language": "UNIX-Shell" }, { "code": "( uxnasm color-bars.tal color-bars.rom && uxnemu color-bars.rom )\n\n|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1\n|20 @Screen &vector $2 &width $2 &height $2 &auto $1 &pad $1 &x $2 &y $2 &addr $2 &pixel $1 &sprite $1\n\n|0100\n ( set 4 color theme\n rgb\n color0: 000 - black\n color1: f00 - red\n color2: 0f0 - green\n color3: 00f - blue )\n #0f00 .System/r DEO2\n #00f0 .System/g DEO2\n #000f .System/b DEO2\n\n ( store bars width )\n .Screen/width DEI2 #0004 DIV2 ,&quarter STR2\n ( set starting position )\n #0000 .Screen/y DEO2\n\n ( draw bars )\n #00\n &loop\n #00 OVR [ LIT2 &quarter $2 ] MUL2\n .Screen/x DEO2\n DUP #80 ORA .Screen/pixel DEO\n INC DUP #04 NEQ ?&loop\nBRK\n", "language": "Uxntal" }, { "code": "import \"graphics\" for Canvas, Color\nimport \"dome\" for Window\n\nclass Game {\n static init() {\n Window.title = \"Color bars\"\n __width = 400\n __height = 400\n Canvas.resize(__width, __height)\n Window.resize(__width, __height)\n var colors = [\n Color.hex(\"000000\"), // black\n Color.hex(\"FF0000\"), // red\n Color.hex(\"00FF00\"), // green\n Color.hex(\"0000FF\"), // blue\n Color.hex(\"FF00FF\"), // magenta\n Color.hex(\"00FFFF\"), // cyan\n Color.hex(\"FFFF00\"), // yellow\n Color.hex(\"FFFFFF\") // white\n ]\n drawBars(colors)\n }\n\n static drawBars(colors) {\n var w = __width / colors.count\n var h = __height\n for (i in 0...colors.count) {\n Canvas.rectfill(w*i, 0, w, h, colors[i])\n }\n }\n\n static update() {}\n\n static draw(dt) {}\n}\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes; \\intrinsic code declarations\nint W, X0, X1, Y, C;\n[SetVid($13); \\320x200x8 graphics\nW:= 320/8; \\width of color bar (pixels)\nfor C:= 0 to 8-1 do\n [X0:= W*C; X1:= X0+W-1;\n for Y:= 0 to 200-1 do\n [Move(X0, Y); Line(X1, Y, C)];\n ];\nC:= ChIn(1); \\wait for keystroke\nSetVid(3); \\restore normal text mode\n]\n", "language": "XPL0" }, { "code": "10 REM The ZX Spectrum display is 32 columns wide, so we have 8 columns of 4 spaces\n20 FOR r=0 TO 20: REM There are 21 rows\n30 FOR c=0 TO 7: REM We use the native colour sequence here\n40 PAPER c: REM set the background colour for the spaces to be printed\n50 PRINT \" \";: REM four spaces, the semicolon prevents newline\n60 NEXT c\n70 REM at this point the cursor has wrapped, so we don't need a newline\n80 NEXT r\n", "language": "ZX-Spectrum-Basic" } ]
Colour-bars-Display
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Colour_pinstripe/Printer\n", "language": "00-META" }, { "code": "The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.\n\nAfter the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).\n\nNote that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.\n\nOptionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.\n\n", "language": "00-TASK" }, { "code": "with Ada.Text_IO;\n\nwith PDF_Out;\n\nprocedure Color_Pinstripe_Printer\nis\n use PDF_Out;\n\n package Point_IO\n is new Ada.Text_Io.Float_IO (Real);\n\n procedure Pinstripe (Doc : in out Pdf_Out_File;\n Line_Width : Real;\n Line_Height : Real;\n Screen_Width : Real;\n Y : Real)\n is\n type Color_Range is (Blck, Red, Green, Blue, Magenta, Cyan, Yellow, White);\n Colors : constant array (Color_Range) of Color_Type\n := (Blck => (0.0, 0.0, 0.0), Red => (1.0, 0.0, 0.0),\n Green => (0.0, 1.0, 0.0), Blue => (0.0, 0.0, 1.0),\n Magenta => (1.0, 0.0, 1.0), Cyan => (0.0, 1.0, 1.0),\n Yellow => (1.0, 1.0, 0.0), White => (1.0, 1.0, 1.0));\n Col : Color_Range := Color_Range'First;\n\n Count : constant Natural\n := Natural (Real'Floor (Screen_Width / Line_Width));\n Corner : constant Point := (Doc.Left_Margin, Doc.Bottom_Margin);\n Corner_Box : constant Point := Corner + (10.0, 10.0);\n Corner_Text : constant Point := Corner_Box + (10.0, 10.0);\n Light_Gray : constant Color_Type := (0.9, 0.9, 0.9);\n Image : String (1 .. 4);\n begin\n -- Pinstripes\n for A in 0 .. Count loop\n Doc.Color (Colors (Col));\n Doc.Draw (What => Corner +\n Rectangle'(X_Min => Real (A) * Line_Width,\n Y_Min => Y,\n Width => Line_Width,\n Height => Line_Height),\n Rendering => Fill);\n Col := (if Col = Color_Range'Last\n then Color_Range'First\n else Color_Range'Succ (Col));\n end loop;\n\n -- Box\n Doc.Stroking_Color (Black);\n Doc.Color (Light_Gray);\n Doc.Line_Width (3.0);\n Doc.Draw (What => Corner_Box + (0.0, Y, 150.0, 26.0),\n Rendering => Fill_Then_Stroke);\n -- Text\n Doc.Color (Black);\n Doc.Text_Rendering_Mode (Fill);\n Point_Io.Put (Image, Line_Width, Aft => 1, Exp => 0);\n Doc.Put_XY (Corner_Text.X, Corner_Text.Y + Y,\n Image & \" point color pinstripe\");\n end Pinstripe;\n\n Doc : PDF_Out_File;\nbegin\n Doc.Create (\"color-pinstripe.pdf\");\n Doc.Page_Setup (A4_Portrait);\n Doc.Margins (Margins_Type'(Left => Cm_2_5,\n others => One_cm));\n declare\n Width : constant Real\n := A4_Portrait.Width - Doc.Left_Margin - Doc.Right_Margin;\n Height : constant Real\n := A4_Portrait.Height - Doc.Top_Margin - Doc.Bottom_Margin;\n begin\n for Point in 1 .. 11 loop\n Pinstripe (Doc,\n Line_Width => Real (Point),\n Line_Height => One_Inch,\n Screen_Width => Width,\n Y => Height - Real (Point) * One_Inch);\n end loop;\n end;\n Doc.Close;\nend Color_Pinstripe_Printer;\n", "language": "Ada" }, { "code": " PD_RETURNDC = 256\n _LOGPIXELSY = 90\n\n DIM pd{lStructSize%, hwndOwner%, hDevMode%, hDevNames%, \\\n \\ hdc%, flags%, nFromPage{l&,h&}, nToPage{l&,h&}, \\\n \\ nMinPage{l&,h&}, nMaxPage{l&,h&}, nCopies{l&,h&}, \\\n \\ hInstance%, lCustData%, lpfnPrintHook%, lpfnSetupHook%, \\\n \\ lpPrintTemplateName%, lpSetupTemplateName%, \\\n \\ hPrintTemplate%, hSetupTemplate%}\n pd.lStructSize% = DIM(pd{})\n pd.hwndOwner% = @hwnd%\n pd.flags% = PD_RETURNDC\n\n SYS \"PrintDlg\", pd{} TO ok%\n IF ok%=0 THEN QUIT\n SYS \"DeleteDC\", @prthdc%\n @prthdc% = pd.hdc%\n *MARGINS 0,0,0,0\n\n dx% = @vdu%!236-@vdu%!232\n dy% = @vdu%!244-@vdu%!240\n SYS \"GetDeviceCaps\", @prthdc%, _LOGPIXELSY TO dpi%\n\n DIM rc{l%,t%,r%,b%}\n DIM colour%(7)\n colour%() = &000000, &0000FF, &00FF00, &FF0000, \\\n \\ &FF00FF, &FFFF00, &00FFFF, &FFFFFF\n\n VDU 2,1,32,3\n pitch% = 1\n FOR y% = 0 TO dy% STEP dpi%\n col% = 0\n FOR x% = 0 TO dx%-pitch% STEP pitch%\n rc.l% = x% : rc.r% = x% + pitch%\n rc.t% = y% : rc.b% = y% + dpi%\n SYS \"CreateSolidBrush\", colour%(col% MOD 8) TO brush%\n SYS \"FillRect\", @prthdc%, rc{}, brush%\n SYS \"DeleteObject\", brush%\n col% += 1\n NEXT\n pitch% += 1\n NEXT y%\n VDU 2,1,12,3\n", "language": "BBC-BASIC" }, { "code": "Dim As String exename\n#ifdef __FB_WIN32__\n exename = \"mspaint.exe /pt\"\n#endif\n#ifdef __FB_LINUX__\n exename = \"lp -o media=A4 \"\n#endif\n\nDim As Uinteger ps, col, h, w, x, y1, y2\n\n' (A4) # 595 x 842 dots\nw = 842 : h = 595\n' create display size window, 8bit color (palette), no frame\nScreenres w, h, 8,, 8\n\nh \\= 7 : y2 = h -1\n\nFor ps = 1 To 7\n col = 0\n For x = 0 To (w - ps -1) Step ps\n Line (x, y1) - (x + ps -1, y2), col, bf\n col = (col +1) And 255\n Next x\n y1 += h : y2 += h\nNext ps\n\nDim As String filename = \"color_pinstripe.bmp\"\nIf Bsave(filename, 0) <> 0 Then\n Cls: Print \"Error saving: \"; fileName : Sleep\nElse\n Dim As Integer result = Exec(exename, filename)\n If result = -1 Then Print \"Error running \"; exename : Sleep\nEnd If\nEnd\n", "language": "FreeBASIC" }, { "code": "include \"NSLog.incl\"\n\nvoid local fn BuildWindow\n CGRect r = { 0, 0, 612, 791 } // U.S. Letter Portrait\n long i, j, colorCount, bars = 612\n CGFloat y = 0.0, w = 1\n CFArrayRef colors = @[¬\n fn ColorBlack,¬\n fn ColorRed,¬\n fn ColorGreen,¬\n fn ColorBlue,¬\n fn ColorMagenta,¬\n fn ColorCyan,¬\n fn ColorYellow,¬\n fn ColorWhite]\n\n window 1, @\"Color Pinstripe Printer Page [U.S. Letter Portrait]\", r\n\n pen -1\n for j = 1 to 4\n r = fn CGRectMake( 0, y, w, 197.75 )\n colorCount = 0\n for i = 0 to bars - 1\n rect fill r, colors[colorCount]\n r.origin.x += w\n colorCount++\n if colorCount == 8 then colorCount = 0\n next\n bars = bars << 1\n y += 197.75 : w++\n next\nend fn\n\nfn BuildWindow\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport (\n \"github.com/fogleman/gg\"\n \"log\"\n \"os/exec\"\n \"runtime\"\n)\n\nvar palette = [8]string{\n \"000000\", // black\n \"FF0000\", // red\n \"00FF00\", // green\n \"0000FF\", // blue\n \"FF00FF\", // magenta\n \"00FFFF\", // cyan\n \"FFFF00\", // yellow\n \"FFFFFF\", // white\n}\n\nfunc pinstripe(dc *gg.Context) {\n w := dc.Width()\n h := dc.Height() / 7\n for b := 1; b <= 11; b++ {\n for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n dc.SetHexColor(palette[ci%8])\n y := h * (b - 1)\n dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))\n dc.Fill()\n }\n }\n}\n\nfunc main() {\n dc := gg.NewContext(842, 595)\n pinstripe(dc)\n fileName := \"color_pinstripe.png\"\n dc.SavePNG(fileName)\n var cmd *exec.Cmd\n if runtime.GOOS == \"windows\" {\n cmd = exec.Command(\"mspaint\", \"/pt\", fileName)\n } else {\n cmd = exec.Command(\"lp\", fileName)\n }\n if err := cmd.Run(); err != nil {\n log.Fatal(err)\n }\n}\n", "language": "Go" }, { "code": "using Colors, FileIO\n\nconst colors = [colorant\"black\", colorant\"red\", colorant\"green\", colorant\"blue\",\n colorant\"magenta\", colorant\"cyan\", colorant\"yellow\", colorant\"white\"]\n\nfunction getnumberwithprompt(prompt, t::Type)\n s = \"\"\n while (x = tryparse(t, s)) == nothing\n print(\"\\n\", prompt, \": -> \")\n s = strip(readline())\n end\n return x\nend\n\nfunction colorstripepng(filename)\n dpi = getnumberwithprompt(\"Printer DPI (dots per inch)\", Int)\n pwidth, plength = getnumberwithprompt(\"Printer width (inches)\", Float64), 10\n imgwidth, imgheight = Int(round(pwidth * dpi)), plength * dpi\n img = fill(colorant\"black\", imgheight, imgwidth)\n\n for row in 1:imgheight\n stripenum, stripewidth, colorindex = 1, div(row, dpi) + 1, 1\n for col in 1:imgwidth\n img[row, col] = colors[colorindex]\n if (stripenum += 1) % stripewidth == 0\n colorindex = mod1(colorindex + 1, length(colors))\n end\n end\n end\n save(filename, img)\nend\n\ncolorstripepng(\"temp.png\")\nrun(`print temp.png`) # the run statement may need to be set up for the installed device\n", "language": "Julia" }, { "code": "import gintro/[glib, gobject, gtk, gio, cairo]\n\nconst Colors = [[0.0, 0.0, 0.0], [255.0, 0.0, 0.0],\n [0.0, 255.0, 0.0], [0.0, 0.0, 255.0],\n [255.0, 0.0, 255.0], [0.0, 255.0, 255.0],\n [255.0, 255.0, 0.0], [255.0, 255.0, 255.0]]\n\n#---------------------------------------------------------------------------------------------------\n\nproc beginPrint(op: PrintOperation; printContext: PrintContext; data: pointer) =\n ## Process signal \"begin_print\", that is set the number of pages to print.\n op.setNPages(1)\n\n#---------------------------------------------------------------------------------------------------\n\nproc drawPage(op: PrintOperation; printContext: PrintContext; pageNum: int; data: pointer) =\n ## Draw a page.\n\n let context = printContext.getCairoContext()\n let lineHeight = printContext.height / 4\n\n var y = 0.0\n for lineWidth in [1.0, 2.0, 3.0, 4.0]:\n context.setLineWidth(lineWidth)\n var x = 0.0\n var colorIndex = 0\n while x < printContext.width:\n context.setSource(Colors[colorIndex])\n context.moveTo(x, y)\n context.lineTo(x, y + lineHeight)\n context.stroke()\n colorIndex = (colorIndex + 1) mod Colors.len\n x += lineWidth\n y += lineHeight\n\n#---------------------------------------------------------------------------------------------------\n\nproc activate(app: Application) =\n ## Activate the application.\n\n # Launch a print operation.\n let op = newPrintOperation()\n op.connect(\"begin_print\", beginPrint, pointer(nil))\n op.connect(\"draw_page\", drawPage, pointer(nil))\n\n # Run the print dialog.\n discard op.run(printDialog)\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nlet app = newApplication(Application, \"Rosetta.ColorPinstripe\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n", "language": "Nim" }, { "code": "(phixonline)--><!--\n", "language": "Phix" }, { "code": "(load \"@lib/ps.l\")\n\n# Using circular lists for an endless supply of colors\n# (black red green blue magenta cyan yellow white)\n(setq\n Red (0 100 0 0 100 0 100 100 .)\n Green (0 0 100 0 0 100 100 100 .)\n Blue (0 0 0 100 100 100 0 100 .) )\n\n(call 'lpr\n (pdf \"pinstripes\"\n (a4) # 595 x 842 dots\n (let (I 0 Step 1)\n (for X 595\n (color (car Red) (car Green) (car Blue)\n (vline X 0 842) )\n (when (= Step (inc 'I))\n (zero I)\n (pop 'Red)\n (pop 'Green)\n (pop 'Blue) )\n (when (=0 (% X 72)) # 1 inch\n (zero I)\n (inc 'Step) ) ) )\n (page) ) )\n", "language": "PicoLisp" }, { "code": "from turtle import *\nfrom PIL import Image\nimport time\nimport subprocess\n\n\"\"\"\n\nOnly works on Windows. Assumes that you have Ghostscript\ninstalled and in your path.\n\nhttps://www.ghostscript.com/download/gsdnld.html\n\nHard coded to 100 pixels per inch.\n\n\"\"\"\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\nscreen = getscreen()\n\n# width and height in pixels\n# aspect ratio for 11 by 8.5 paper\n\ninch_width = 11.0\ninch_height = 8.5\n\npixels_per_inch = 100\n\npix_width = int(inch_width*pixels_per_inch)\npix_height = int(inch_height*pixels_per_inch)\n\nscreen.setup (width=pix_width, height=pix_height, startx=0, starty=0)\n\nscreen.screensize(pix_width,pix_height)\n\n# center is 0,0\n\n# get coordinates of the edges\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nbottom_edge = -screen.window_height()//2\n\ntop_edge = screen.window_height()//2\n\n# draw quickly\n\nscreen.delay(0)\nscreen.tracer(5)\n\nfor inch in range(int(inch_width)-1):\n line_width = inch + 1\n pensize(line_width)\n colornum = 0\n\n min_x = left_edge + (inch * pixels_per_inch)\n max_x = left_edge + ((inch+1) * pixels_per_inch)\n\n for y in range(bottom_edge,top_edge,line_width):\n penup()\n pencolor(colors[colornum])\n colornum = (colornum + 1) % len(colors)\n setposition(min_x,y)\n pendown()\n setposition(max_x,y)\n\nscreen.getcanvas().postscript(file=\"striped.eps\")\n\n# convert to jpeg\n# won't work without Ghostscript.\n\nim = Image.open(\"striped.eps\")\nim.save(\"striped.jpg\")\n\n# Got idea from http://rosettacode.org/wiki/Colour_pinstripe/Printer#Go\n\nsubprocess.run([\"mspaint\", \"/pt\", \"striped.jpg\"])\n", "language": "Python" }, { "code": "#lang racket/gui\n\n(define parts 4)\n\n(define dc (new printer-dc%))\n(send* dc (start-doc \"Colour Pinstripe\") (start-page))\n\n(define-values [W H] (send dc get-size))\n(define parts 4)\n(define colors\n '(\"Black\" \"Red\" \"Green\" \"Blue\" \"Magenta\" \"Cyan\" \"Yellow\" \"White\"))\n(send dc set-pen \"black\" 0 'transparent)\n(send dc set-brush \"black\" 'solid)\n(define H* (round (/ H parts)))\n(for ([row parts])\n (define Y (* row H*))\n (for ([X (in-range 0 W (add1 row))] [c (in-cycle colors)])\n (send dc set-brush c 'solid)\n (send dc draw-rectangle X Y (add1 row) H*)))\n\n(send* dc (end-page) (end-doc))\n", "language": "Racket" }, { "code": "unit sub MAIN ($dpi = 300, $size = 'letter');\n\nmy $filename = './Color-pinstripe-printer-perl6.png';\n\nmy %paper = (\n 'letter' => { :width(8.5), :height(11.0) }\n 'A4' => { :width(8.2677), :height(11.6929)}\n);\n\nmy ($w, $h) = %paper{$size}<width height> »*» $dpi;\n\n# ROYGBIVK\nmy @color = (1,0,0),(1,.598,0),(1,1,0),(0,1,0),(0,0,1),(.294,0,.51),(.58,0,.827),(0,0,0);\n\nmy $gap = floor $w % ($dpi * +@color) / 2;\n\nmy $rows = (1, * * 2 … * > $dpi).elems;\n\nmy $height = $dpi;\n\nuse Cairo;\n\nmy @colors = @color.map: { Cairo::Pattern::Solid.new.create(|$_) };\n\ngiven Cairo::Image.create(Cairo::FORMAT_ARGB32, $w, $h) -> $image {\n given Cairo::Context.new($image) {\n my Cairo::Pattern::Solid $bg .= create(1,1,1);\n .rectangle(0, 0, $w, $h);\n .pattern($bg);\n .fill;\n $bg.destroy;\n\n my $y = $gap;\n for ^$rows -> $row {\n my $x = $gap;\n my $width = $dpi / (2 ** $row);\n for @colors -> $this {\n my $v = 0;\n while $v++ < (2 ** ($row - 1)) {\n given Cairo::Context.new($image) -> $block {\n $block.rectangle($x, $y, $width, $height);\n $block.pattern($this);\n $block.fill;\n $block.destroy;\n }\n $x += $width;\n $x += $width if $row;\n }\n }\n $y += $height;\n }\n }\n $image.write_png($filename);\n}\n\n# Uncomment next line if you actually want to print it\n#run('lp', $filename)\n", "language": "Raku" }, { "code": "package require Tk\n# Allocate a temporary drawing surface\ncanvas .c\n# The cycle of colors we want to use\nset colors {black red green blue magenta cyan yellow white}\n# Draw the output we want\nfor {set y 0;set dx 1} {$y < 11*72} {incr y 72;incr dx} {\n for {set x 0;set c 0} {$x < 8.5*72} {incr x $dx;incr c} {\n\t.c create rectangle $x $y [expr {$x+$dx+1}] [expr {$y+73}] \\\n\t -fill [lindex $colors [expr {$c%[llength $colors]}]] -outline {}\n }\n}\n# Send postscript to default printer, scaled 1 pixel -> 1 point\nexec lp - << [.c postscript -height $y -width $x -pageheight $y -pagewidth $x]\n# Explicit exit; no GUI desired\nexit\n", "language": "Tcl" }, { "code": "import \"graphics\" for Canvas, Color, ImageData\nimport \"dome\" for Window\nimport \"plugin\" for Plugin\n\nPlugin.load(\"printer\")\n\nimport \"printer\" for Printer\n\nclass Main {\n construct new() {\n Window.title = \"Color pinstripe - printer\"\n _width = 842\n _height = 595\n Canvas.resize(_width, _height)\n Window.resize(_width, _height)\n var colors = [\n Color.hex(\"000000\"), // black\n Color.hex(\"FF0000\"), // red\n Color.hex(\"00FF00\"), // green\n Color.hex(\"0000FF\"), // blue\n Color.hex(\"FF00FF\"), // magenta\n Color.hex(\"00FFFF\"), // cyan\n Color.hex(\"FFFF00\"), // yellow\n Color.hex(\"FFFFFF\") // white\n ]\n pinstripe(colors)\n }\n\n pinstripe(colors) {\n var w = _width\n var h = (_height/7).floor\n for (b in 1..11) {\n var x = 0\n var ci = 0\n while (x < w) {\n var y = h * (b - 1)\n Canvas.rectfill(x, y, b, h, colors[ci%8])\n x = x + b\n ci = ci + 1\n }\n }\n }\n\n init() {\n var img = ImageData.create(\"color_pinstripe\", _width, _height)\n for (x in 0..._width) {\n for (y in 0..._height) img.pset(x, y, Canvas.pget(x, y))\n }\n img.saveToFile(\"color_pinstripe.png\")\n Printer.printFile(\"color_pinstripe.png\")\n }\n\n update() {}\n\n draw(alpha) {}\n}\n\nvar Game = Main.new()\n", "language": "Wren" } ]
Colour-pinstripe-Printer
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Combinations\nnote: Discrete math\n", "language": "00-META" }, { "code": ";Task:\nGiven non-negative integers &nbsp; <big> '''m''' </big> &nbsp; and &nbsp; <big> '''n'''</big>, &nbsp; generate all size &nbsp; <big> '''m''' </big> &nbsp; [http://mathworld.wolfram.com/Combination.html combinations] &nbsp; of the integers from &nbsp; <big> '''0'''</big> &nbsp; (zero) &nbsp; to &nbsp; <big> '''n-1''' </big> &nbsp; in sorted order &nbsp; (each combination is sorted and the entire table is sorted).\n\n\n;Example:\n<big>'''3'''</big> &nbsp; comb &nbsp; <big> '''5''' </big> &nbsp; &nbsp; is:\n 0 1 2\n 0 1 3\n 0 1 4\n 0 2 3\n 0 2 4\n 0 3 4\n 1 2 3\n 1 2 4\n 1 3 4\n 2 3 4\n\nIf it is more \"natural\" in your language to start counting from &nbsp; <big> '''1'''</big> &nbsp; (unity) instead of &nbsp; <big> '''0'''</big> &nbsp; (zero), \n<br>the combinations can be of the integers from &nbsp; <big> '''1'''</big> &nbsp; to &nbsp; <big> '''n'''. </big> \n\n\n;See also:\n{{Template:Combinations and permutations}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F comb(arr, k)\n I k == 0\n R [[Int]()]\n\n [[Int]] result\n L(x) arr\n V i = L.index\n L(suffix) comb(arr[i+1..], k-1)\n result [+]= x [+] suffix\n\n R result\n\nprint(comb([0, 1, 2, 3, 4], 3))\n", "language": "11l" }, { "code": "* Combinations 26/05/2016\nCOMBINE CSECT\n USING COMBINE,R13 base register\n B 72(R15) skip savearea\n DC 17F'0' savearea\n STM R14,R12,12(R13) prolog\n ST R13,4(R15) \"\n ST R15,8(R13) \"\n LR R13,R15 \"\n SR R3,R3 clear\n LA R7,C @c(1)\n LH R8,N v=n\nLOOPI1 STC R8,0(R7) do i=1 to n; c(i)=n-i+1\n LA R7,1(R7) @c(i)++\n BCT R8,LOOPI1 next i\nLOOPBIG LA R10,PG big loop {------------------\n LH R1,N n\n LA R7,C-1(R1) @c(i)\n LH R6,N i=n\nLOOPI2 IC R3,0(R7) do i=n to 1 by -1; r2=c(i)\n XDECO R3,PG+80 edit c(i)\n MVC 0(2,R10),PG+90 output c(i)\n LA R10,3(R10) @pgi=@pgi+3\n BCTR R7,0 @c(i)--\n BCT R6,LOOPI2 next i\n XPRNT PG,80 print buffer\n LA R7,C @c(1)\n LH R8,M v=m\n LA R6,1 i=1\nLOOPI3 LR R1,R6 do i=1 by 1; r1=i\n IC R3,0(R7) c(i)\n CR R3,R8 while c(i)>=m-i+1\n BL ELOOPI3 leave i\n CH R6,N if i>=n\n BNL ELOOPBIG exit loop\n BCTR R8,0 v=v-1\n LA R7,1(R7) @c(i)++\n LA R6,1(R6) i=i+1\n B LOOPI3 next i\nELOOPI3 LR R1,R6 i\n LA R4,C-1(R1) @c(i)\n IC R3,0(R4) c(i)\n LA R3,1(R3) c(i)+1\n STC R3,0(R4) c(i)=c(i)+1\n BCTR R7,0 @c(i)--\nLOOPI4 CH R6,=H'2' do i=i to 2 by -1\n BL ELOOPI4 leave i\n IC R3,1(R7) c(i)\n LA R3,1(R3) c(i)+1\n STC R3,0(R7) c(i-1)=c(i)+1\n BCTR R7,0 @c(i)--\n BCTR R6,0 i=i-1\n B LOOPI4 next i\nELOOPI4 B LOOPBIG big loop }------------------\nELOOPBIG L R13,4(0,R13) epilog\n LM R14,R12,12(R13) \"\n XR R15,R15 \"\n BR R14 exit\nM DC H'5' <=input\nN DC H'3' <=input\nC DS 64X array of 8 bit integers\nPG DC CL92' ' buffer\n YREGS\n END COMBINE\n", "language": "360-Assembly" }, { "code": "(defun comb (m n (i . 0))\n (cond ((zerop m) '(()))\n ((eq i n) '())\n (t (append\n (mapc '(lambda (rest) (cons i rest))\n (comb (sub1 m) n (add1 i)))\n (comb m n (add1 i))))))\n\n(defun append (a b)\n (cond ((null a) b)\n (t (cons (car a) (append (cdr a) b)))))\n\n(map print (comb 3 5))\n", "language": "Acornsoft-Lisp" }, { "code": "PROC PrintComb(BYTE ARRAY c BYTE len)\n BYTE i\n\n Put('()\n FOR i=0 TO len-1\n DO\n IF i>0 THEN Put(',) FI\n PrintB(c(i))\n OD\n Put(')) PutE()\nRETURN\n\nBYTE FUNC Increasing(BYTE ARRAY c BYTE len)\n BYTE i\n\n IF len<2 THEN RETURN (1) FI\n\n FOR i=0 TO len-2\n DO\n IF c(i)>=c(i+1) THEN\n RETURN (0)\n FI\n OD\nRETURN (1)\n\nBYTE FUNC NextComb(BYTE ARRAY c BYTE n,k)\n INT pos,i\n\n DO\n pos=k-1\n DO\n c(pos)==+1\n IF c(pos)<n THEN\n EXIT\n ELSE\n pos==-1\n IF pos<0 THEN RETURN (0) FI\n FI\n FOR i=pos+1 TO k-1\n DO\n c(i)=c(pos)\n OD\n OD\n UNTIL Increasing(c,k)\n OD\nRETURN (1)\n\nPROC Comb(BYTE n,k)\n BYTE ARRAY c(10)\n BYTE i\n\n IF k>n THEN\n Print(\"Error! k is greater than n.\")\n Break()\n FI\n\n FOR i=0 TO k-1\n DO\n c(i)=i\n OD\n\n DO\n PrintComb(c,k)\n UNTIL NextComb(c,n,k)=0\n OD\nRETURN\n\nPROC Main()\n Comb(5,3)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Test_Combinations is\n generic\n type Integers is range <>;\n package Combinations is\n type Combination is array (Positive range <>) of Integers;\n procedure First (X : in out Combination);\n procedure Next (X : in out Combination);\n procedure Put (X : Combination);\n end Combinations;\n\n package body Combinations is\n procedure First (X : in out Combination) is\n begin\n X (1) := Integers'First;\n for I in 2..X'Last loop\n X (I) := X (I - 1) + 1;\n end loop;\n end First;\n procedure Next (X : in out Combination) is\n begin\n for I in reverse X'Range loop\n if X (I) < Integers'Val (Integers'Pos (Integers'Last) - X'Last + I) then\n X (I) := X (I) + 1;\n for J in I + 1..X'Last loop\n X (J) := X (J - 1) + 1;\n end loop;\n return;\n end if;\n end loop;\n raise Constraint_Error;\n end Next;\n procedure Put (X : Combination) is\n begin\n for I in X'Range loop\n Put (Integers'Image (X (I)));\n end loop;\n end Put;\n end Combinations;\n\n type Five is range 0..4;\n package Fives is new Combinations (Five);\n use Fives;\n\n X : Combination (1..3);\nbegin\n First (X);\n loop\n Put (X); New_Line;\n Next (X);\n end loop;\nexception\n when Constraint_Error =>\n null;\nend Test_Combinations;\n", "language": "Ada" }, { "code": "type Five is range 0..4;\n", "language": "Ada" }, { "code": "# -*- coding: utf-8 -*- #\n\nCOMMENT REQUIRED BY \"prelude_combinations_generative.a68\"\n MODE COMBDATA = ~;\nPROVIDES:\n# COMBDATA*=~* #\n# comb*=~ list* #\nEND COMMENT\n\nMODE COMBDATALIST = REF[]COMBDATA;\nMODE COMBDATALISTYIELD = PROC(COMBDATALIST)VOID;\n\nPROC comb gen combinations = (INT m, COMBDATALIST list, COMBDATALISTYIELD yield)VOID:(\n CASE m IN\n # case 1: transpose list #\n FOR i TO UPB list DO yield(list[i]) OD\n OUT\n [m + LWB list - 1]COMBDATA out;\n INT index out := 1;\n FOR i TO UPB list DO\n COMBDATA first = list[i];\n # FOR COMBDATALIST sub recombination IN # comb gen combinations(m - 1, list[i+1:] #) DO (#,\n ## (COMBDATALIST sub recombination)VOID:(\n out[LWB list ] := first;\n out[LWB list+1:] := sub recombination;\n yield(out)\n # OD #))\n OD\n ESAC\n);\n\nSKIP\n", "language": "ALGOL-68" }, { "code": "#!/usr/bin/a68g --script #\n# -*- coding: utf-8 -*- #\n\nCO REQUIRED BY \"prelude_combinations.a68\" CO\n MODE COMBDATA = INT;\n#PROVIDES:#\n# COMBDATA~=INT~ #\n# comb ~=int list ~#\nPR READ \"prelude_combinations.a68\" PR;\n\nFORMAT data fmt = $g(0)$;\n\nmain:(\n INT m = 3;\n FORMAT list fmt = $\"(\"n(m-1)(f(data fmt)\",\")f(data fmt)\")\"$;\n FLEX[0]COMBDATA test data list := (1,2,3,4,5);\n# FOR COMBDATALIST recombination data IN # comb gen combinations(m, test data list #) DO (#,\n## (COMBDATALIST recombination)VOID:(\n printf ((list fmt, recombination, $l$))\n# OD # ))\n)\n", "language": "ALGOL-68" }, { "code": "on comb(n, k)\n set c to {}\n repeat with i from 1 to k\n set end of c to i's contents\n end repeat\n set r to {c's contents}\n repeat while my next_comb(c, k, n)\n set end of r to c's contents\n end repeat\n return r\nend comb\n\non next_comb(c, k, n)\n set i to k\n set c's item i to (c's item i) + 1\n repeat while (i > 1 and c's item i ≥ n - k + 1 + i)\n set i to i - 1\n set c's item i to (c's item i) + 1\n end repeat\n if (c's item 1 > n - k + 1) then return false\n repeat with i from i + 1 to k\n set c's item i to (c's item (i - 1)) + 1\n end repeat\n return true\nend next_comb\n\nreturn comb(5, 3)\n", "language": "AppleScript" }, { "code": "{{1, 2, 3}, {1, 2, 4}, {1, 2, 5}, {1, 3, 4}, {1, 3, 5}, {1, 4, 5}, {2, 3, 4}, {2, 3, 5}, {2, 4, 5}, {3, 4, 5}}\n", "language": "AppleScript" }, { "code": "----------------------- COMBINATIONS ---------------------\n\n-- comb :: Int -> [a] -> [[a]]\non comb(n, lst)\n if 1 > n then\n {{}}\n else\n if not isNull(lst) then\n set {h, xs} to uncons(lst)\n\n map(cons(h), ¬\n comb(n - 1, xs)) & comb(n, xs)\n else\n {}\n end if\n end if\nend comb\n\n--------------------------- TEST -------------------------\non run\n\n intercalate(linefeed, ¬\n map(unwords, comb(3, enumFromTo(0, 4))))\n\nend run\n\n-------------------- GENERIC FUNCTIONS -------------------\n\n-- cons :: a -> [a] -> [a]\non cons(x)\n script\n on |λ|(xs)\n {x} & xs\n end |λ|\n end script\nend cons\n\n-- enumFromTo :: Int -> Int -> [Int]\non enumFromTo(m, n)\n if m ≤ n then\n set lst to {}\n repeat with i from m to n\n set end of lst to i\n end repeat\n lst\n else\n {}\n end if\nend enumFromTo\n\n-- intercalate :: Text -> [Text] -> Text\non intercalate(strText, lstText)\n set {dlm, my text item delimiters} to {my text item delimiters, strText}\n set strJoined to lstText as text\n set my text item delimiters to dlm\n return strJoined\nend intercalate\n\n-- isNull :: [a] -> Bool\non isNull(xs)\n if class of xs is string then\n xs = \"\"\n else\n xs = {}\n end if\nend isNull\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n-- uncons :: [a] -> Maybe (a, [a])\non uncons(xs)\n set lng to length of xs\n if lng > 0 then\n if class of xs is string then\n set cs to text items of xs\n {item 1 of cs, rest of cs}\n else\n {item 1 of xs, rest of xs}\n end if\n else\n missing value\n end if\nend uncons\n\n-- unwords :: [String] -> String\non unwords(xs)\n intercalate(space, xs)\nend unwords\n", "language": "AppleScript" }, { "code": "print.lines combine.by:3 @0..4\n", "language": "Arturo" }, { "code": "MsgBox % Comb(1,1)\nMsgBox % Comb(3,3)\nMsgBox % Comb(3,2)\nMsgBox % Comb(2,3)\nMsgBox % Comb(5,3)\n\nComb(n,t) { ; Generate all n choose t combinations of 1..n, lexicographically\n IfLess n,%t%, Return\n Loop %t%\n c%A_Index% := A_Index\n i := t+1, c%i% := n+1\n\n Loop {\n Loop %t%\n i := t+1-A_Index, c .= c%i% \" \"\n c .= \"`n\" ; combinations in new lines\n j := 1, i := 2\n Loop\n If (c%j%+1 = c%i%)\n c%j% := j, ++j, ++i\n Else Break\n If (j > t)\n Return c\n c%j% += 1\n }\n}\n", "language": "AutoHotkey" }, { "code": "BEGIN {\n\t## Default values for r and n (Choose 3 from pool of 5). Can\n\t## alternatively be set on the command line:-\n\t## awk -v r=<number of items being chosen> -v n=<how many to choose from> -f <scriptname>\n\tif (length(r) == 0) r = 3\n\tif (length(n) == 0) n = 5\n\n\tfor (i=1; i <= r; i++) { ## First combination of items:\n\t\tA[i] = i\n\t\tif (i < r ) printf i OFS\n\t\telse print i}\n\n\t## While 1st item is less than its maximum permitted value...\n\twhile (A[1] < n - r + 1) {\n\t\t## loop backwards through all items in the previous\n\t\t## combination of items until an item is found that is\n\t\t## less than its maximum permitted value:\n\t\tfor (i = r; i >= 1; i--) {\n\t\t\t## If the equivalently positioned item in the\n\t\t\t## previous combination of items is less than its\n\t\t\t## maximum permitted value...\n\t\t\tif (A[i] < n - r + i) {\n\t\t\t\t## increment the current item by 1:\n\t\t\t\tA[i]++\n\t\t\t\t## Save the current position-index for use\n\t\t\t\t## outside this \"for\" loop:\n\t\t\t\tp = i\n\t\t\t\tbreak}}\n\t\t## Put consecutive numbers in the remainder of the array,\n\t\t## counting up from position-index p.\n\t\tfor (i = p + 1; i <= r; i++) A[i] = A[i - 1] + 1\n\n\t\t## Print the current combination of items:\n\t\tfor (i=1; i <= r; i++) {\n\t\t\tif (i < r) printf A[i] OFS\n\t\t\telse print A[i]}}\n\texit}\n", "language": "AWK" }, { "code": "input \"Enter n comb m. \", n\ninput m\n\noutstr$ = \"\"\ncall iterate (outstr$, 0, m-1, n-1)\nend\n\nsubroutine iterate (curr$, start, stp, depth)\n\tfor i = start to stp\n\t\tif depth = 0 then print curr$ + \" \" + string(i)\n\t\tcall iterate (curr$ + \" \" + string(i), i+1, stp, depth-1)\n\tnext i\nend subroutine\n", "language": "BASIC256" }, { "code": " INSTALL @lib$+\"SORTLIB\"\n sort% = FN_sortinit(0,0)\n\n M% = 3\n N% = 5\n\n C% = FNfact(N%)/(FNfact(M%)*FNfact(N%-M%))\n DIM s$(C%)\n PROCcomb(M%, N%, s$())\n\n CALL sort%, s$(0)\n FOR I% = 0 TO C%-1\n PRINT s$(I%)\n NEXT\n END\n\n DEF PROCcomb(C%, N%, s$())\n LOCAL I%, U%\n FOR U% = 0 TO 2^N%-1\n IF FNbits(U%) = C% THEN\n s$(I%) = FNlist(U%)\n I% += 1\n ENDIF\n NEXT\n ENDPROC\n\n DEF FNbits(U%)\n LOCAL N%\n WHILE U%\n N% += 1\n U% = U% AND (U%-1)\n ENDWHILE\n = N%\n\n DEF FNlist(U%)\n LOCAL N%, s$\n WHILE U%\n IF U% AND 1 s$ += STR$(N%) + \" \"\n N% += 1\n U% = U% >> 1\n ENDWHILE\n = s$\n\n DEF FNfact(N%)\n IF N%<=1 THEN = 1 ELSE = N%*FNfact(N%-1)\n", "language": "BBC-BASIC" }, { "code": "Cmat←{⊑𝕨∊0‿𝕩?≍↕𝕨;0⊸∾˘⊸∾´1+(𝕨-1‿0)𝕊¨𝕩-1} # Recursive\nCmat1←{k←⌽↕d←𝕩¬𝕨⋄∾⌽{k∾˘¨∾˜`1+𝕩}⍟𝕨d↑↓1‿0⥊0} # Roger Hui\n", "language": "BQN" }, { "code": "┌─\n╵ 0 1 2\n 0 1 3\n 0 1 4\n 0 2 3\n 0 2 4\n 0 3 4\n 1 2 3\n 1 2 4\n 1 3 4\n 2 3 4\n ┘\n", "language": "BQN" }, { "code": "(comb=\n bvar combination combinations list m n pat pvar var\n. !arg:(?m.?n)\n & ( pat\n = ?\n & !combinations (.!combination):?combinations\n & ~\n )\n & :?list:?combination:?combinations\n & whl\n ' ( !m+-1:~<0:?m\n & chu$(utf$a+!m):?var\n & glf$('(%@?.$var)):(=?pvar)\n & '(? ()$pvar ()$pat):(=?pat)\n & glf$('(!.$var)):(=?bvar)\n & ( '$combination:(=)\n & '$bvar:(=?combination)\n | '($bvar ()$combination):(=?combination)\n )\n )\n & whl\n ' (!n+-1:~<0:?n&!n !list:?list)\n & !list:!pat\n | !combinations);\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n\n/* Type marker stick: using bits to indicate what's chosen. The stick can't\n * handle more than 32 items, but the idea is there; at worst, use array instead */\ntypedef unsigned long marker;\nmarker one = 1;\n\nvoid comb(int pool, int need, marker chosen, int at)\n{\n\tif (pool < need + at) return; /* not enough bits left */\n\n\tif (!need) {\n\t\t/* got all we needed; print the thing. if other actions are\n\t\t * desired, we could have passed in a callback function. */\n\t\tfor (at = 0; at < pool; at++)\n\t\t\tif (chosen & (one << at)) printf(\"%d \", at);\n\t\tprintf(\"\\n\");\n\t\treturn;\n\t}\n\t/* if we choose the current item, \"or\" (|) the bit to mark it so. */\n\tcomb(pool, need - 1, chosen | (one << at), at + 1);\n\tcomb(pool, need, chosen, at + 1); /* or don't choose it, go to next */\n}\n\nint main()\n{\n\tcomb(5, 3, 0, 0);\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <stdio.h>\n\nvoid comb(int m, int n, unsigned char *c)\n{\n\tint i;\n\tfor (i = 0; i < n; i++) c[i] = n - i;\n\n\twhile (1) {\n\t\tfor (i = n; i--;)\n\t\t\tprintf(\"%d%c\", c[i], i ? ' ': '\\n');\n\n\t\t/* this check is not strictly necessary, but if m is not close to n,\n\t\t it makes the whole thing quite a bit faster */\n\t\ti = 0;\n\t\tif (c[i]++ < m) continue;\n\n\t\tfor (; c[i] >= m - i;) if (++i >= n) return;\n\t\tfor (c[i]++; i; i--) c[i-1] = c[i] + 1;\n\t}\n}\n\nint main()\n{\n\tunsigned char buf[100];\n\tcomb(5, 3, buf);\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nvoid comb(int N, int K)\n{\n std::string bitmask(K, 1); // K leading 1's\n bitmask.resize(N, 0); // N-K trailing 0's\n\n // print integers and permute bitmask\n do {\n for (int i = 0; i < N; ++i) // [0..N-1] integers\n {\n if (bitmask[i]) std::cout << \" \" << i;\n }\n std::cout << std::endl;\n } while (std::prev_permutation(bitmask.begin(), bitmask.end()));\n}\n\nint main()\n{\n comb(5, 3);\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\n\npublic class Program\n{\n public static IEnumerable<int[]> Combinations(int m, int n)\n {\n int[] result = new int[m];\n Stack<int> stack = new Stack<int>();\n stack.Push(0);\n\n while (stack.Count > 0)\n {\n int index = stack.Count - 1;\n int value = stack.Pop();\n\n while (value < n)\n {\n result[index++] = ++value;\n stack.Push(value);\n\n if (index == m)\n {\n yield return result;\n break;\n }\n }\n }\n }\n\n static void Main()\n {\n foreach (int[] c in Combinations(3, 5))\n {\n Console.WriteLine(string.Join(\",\", c));\n Console.WriteLine();\n }\n }\n}\n", "language": "C-sharp" }, { "code": "using System;\nusing System.Collections.Generic;\n\npublic class Program\n{\n public static IEnumerable<int[]> FindCombosRec(int[] buffer, int done, int begin, int end)\n {\n for (int i = begin; i < end; i++)\n {\n buffer[done] = i;\n\n if (done == buffer.Length - 1)\n yield return buffer;\n else\n foreach (int[] child in FindCombosRec(buffer, done+1, i+1, end))\n yield return child;\n }\n }\n\n public static IEnumerable<int[]> FindCombinations(int m, int n)\n {\n return FindCombosRec(new int[m], 0, 0, n);\n }\n\n static void Main()\n {\n foreach (int[] c in FindCombinations(3, 5))\n {\n for (int i = 0; i < c.Length; i++)\n {\n Console.Write(c[i] + \" \");\n }\n Console.WriteLine();\n }\n }\n}\n", "language": "C-sharp" }, { "code": "using System;\nclass Combinations\n{\n static int k = 3, n = 5;\n static int [] buf = new int [k];\n\n static void Main()\n {\n rec(0, 0);\n }\n\n static void rec(int ind, int begin)\n {\n for (int i = begin; i < n; i++)\n {\n buf [ind] = i;\n if (ind + 1 < k) rec(ind + 1, buf [ind] + 1);\n else Console.WriteLine(string.Join(\",\", buf));\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(defn combinations\n \"If m=1, generate a nested list of numbers [0,n)\n If m>1, for each x in [0,n), and for each list in the recursion on [x+1,n), cons the two\"\n [m n]\n (letfn [(comb-aux\n\t [m start]\n\t (if (= 1 m)\n\t (for [x (range start n)]\n\t (list x))\n\t (for [x (range start n)\n\t\t xs (comb-aux (dec m) (inc x))]\n\t (cons x xs))))]\n (comb-aux m 0)))\n\n(defn print-combinations\n [m n]\n (doseq [line (combinations m n)]\n (doseq [n line]\n (printf \"%s \" n))\n (printf \"%n\")))\n", "language": "Clojure" }, { "code": "(defn combinations\n \"Generate the combinations of n elements from a list of [0..m)\"\n [m n]\n (let [xs (range m)]\n (loop [i (int 0) res #{#{}}]\n (if (== i n)\n res\n (recur (+ 1 i)\n (set (for [x xs r res\n :when (not-any? #{x} r)]\n (conj r x))))))))\n", "language": "Clojure" }, { "code": "% generate the size-M combinations from 0 to n-1\ncombinations = iter (m, n: int) yields (sequence[int])\n if m<=n then\n state: array[int] := array[int]$predict(1, m)\n for i: int in int$from_to(0, m-1) do\n array[int]$addh(state, i)\n end\n\n i: int := m\n while i>0 do\n yield (sequence[int]$a2s(state))\n i := m\n while i>0 do\n state[i] := state[i] + 1\n for j: int in int$from_to(i,m-1) do\n state[j+1] := state[j] + 1\n end\n if state[i] < n-(m-i) then break end\n i := i - 1\n end\n end\n end\nend combinations\n\n% print a combination\nprint_comb = proc (s: stream, comb: sequence[int])\n for i: int in sequence[int]$elements(comb) do\n stream$puts(s, int$unparse(i) || \" \")\n end\nend print_comb\n\nstart_up = proc ()\n po: stream := stream$primary_output()\n for comb: sequence[int] in combinations(3, 5) do\n print_comb(po, comb)\n stream$putl(po, \"\")\n end\nend start_up\n", "language": "CLU" }, { "code": "combinations = (n, p) ->\n return [ [] ] if p == 0\n i = 0\n combos = []\n combo = []\n while combo.length < p\n if i < n\n combo.push i\n i += 1\n else\n break if combo.length == 0\n i = combo.pop() + 1\n\n if combo.length == p\n combos.push clone combo\n i = combo.pop() + 1\n combos\n\nclone = (arr) -> (n for n in arr)\n\nN = 5\nfor i in [0..N]\n console.log \"------ #{N} #{i}\"\n for combo in combinations N, i\n console.log combo\n", "language": "CoffeeScript" }, { "code": "(defun map-combinations (m n fn)\n \"Call fn with each m combination of the integers from 0 to n-1 as a list. The list may be destroyed after fn returns.\"\n (let ((combination (make-list m)))\n (labels ((up-from (low)\n (let ((start (1- low)))\n (lambda () (incf start))))\n (mc (curr left needed comb-tail)\n (cond\n ((zerop needed)\n (funcall fn combination))\n ((= left needed)\n (map-into comb-tail (up-from curr))\n (funcall fn combination))\n (t\n (setf (first comb-tail) curr)\n (mc (1+ curr) (1- left) (1- needed) (rest comb-tail))\n (mc (1+ curr) (1- left) needed comb-tail)))))\n (mc 0 n m combination))))\n", "language": "Common-Lisp" }, { "code": "(defun comb (m list fn)\n (labels ((comb1 (l c m)\n\t\t (when (>= (length l) m)\n\t\t (if (zerop m) (return-from comb1 (funcall fn c)))\n\t\t (comb1 (cdr l) c m)\n\t\t (comb1 (cdr l) (cons (first l) c) (1- m)))))\n (comb1 list nil m)))\n\n(comb 3 '(0 1 2 3 4 5) #'print)\n", "language": "Common-Lisp" }, { "code": "(defun next-combination (n a)\n (let ((k (length a)) m)\n (loop for i from 1 do\n (when (> i k) (return nil))\n (when (< (aref a (- k i)) (- n i))\n (setf m (aref a (- k i)))\n (loop for j from i downto 1 do\n (incf m)\n (setf (aref a (- k j)) m))\n (return t)))))\n\n(defun all-combinations (n k)\n (if (or (< k 0) (< n k)) '()\n (let ((a (make-array k)))\n (loop for i below k do (setf (aref a i) i))\n (loop collect (coerce a 'list) while (next-combination n a)))))\n\n(defun map-combinations (n k fun)\n (if (and (>= k 0) (>= n k))\n (let ((a (make-array k)))\n (loop for i below k do (setf (aref a i) i))\n (loop do (funcall fun (coerce a 'list)) while (next-combination n a)))))\n\n; all-combinations returns a list of lists\n\n> (all-combinations 4 3)\n((0 1 2) (0 1 3) (0 2 3) (1 2 3))\n\n; map-combinations applies a function to each combination\n\n> (map-combinations 6 4 #'print)\n(0 1 2 3)\n(0 1 2 4)\n(0 1 2 5)\n(0 1 3 4)\n(0 1 3 5)\n(0 1 4 5)\n(0 2 3 4)\n(0 2 3 5)\n(0 2 4 5)\n(0 3 4 5)\n(1 2 3 4)\n(1 2 3 5)\n(1 2 4 5)\n(1 3 4 5)\n(2 3 4 5)\n", "language": "Common-Lisp" }, { "code": "def comb(m, n)\n (0...n).to_a.each_combination(m) { |p| puts(p) }\nend\n", "language": "Crystal" }, { "code": "[0, 1, 2]\n[0, 1, 3]\n[0, 1, 4]\n[0, 2, 3]\n[0, 2, 4]\n[0, 3, 4]\n[1, 2, 3]\n[1, 2, 4]\n[1, 3, 4]\n[2, 3, 4]\n", "language": "Crystal" }, { "code": "T[][] comb(T)(in T[] arr, in int k) pure nothrow {\n if (k == 0) return [[]];\n typeof(return) result;\n foreach (immutable i, immutable x; arr)\n foreach (suffix; arr[i + 1 .. $].comb(k - 1))\n result ~= x ~ suffix;\n return result;\n}\n\nvoid main() {\n import std.stdio;\n [0, 1, 2, 3].comb(2).writeln;\n}\n", "language": "D" }, { "code": "import std.stdio, std.algorithm, std.range;\n\nimmutable(int)[][] comb(immutable int[] s, in int m) pure nothrow @safe {\n if (!m) return [[]];\n if (s.empty) return [];\n return s[1 .. $].comb(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].comb(m);\n}\n\nvoid main() {\n 4.iota.array.comb(2).writeln;\n}\n", "language": "D" }, { "code": "module combinations3;\n\nimport std.traits: Unqual;\n\nstruct Combinations(T, bool copy=true) {\n Unqual!T[] pool, front;\n size_t r, n;\n bool empty = false;\n size_t[] indices;\n size_t len;\n bool lenComputed = false;\n\n this(T[] pool_, in size_t r_) pure nothrow @safe {\n this.pool = pool_.dup;\n this.r = r_;\n this.n = pool.length;\n if (r > n)\n empty = true;\n indices.length = r;\n foreach (immutable i, ref ini; indices)\n ini = i;\n front.length = r;\n foreach (immutable i, immutable idx; indices)\n front[i] = pool[idx];\n }\n\n @property size_t length() /*logic_const*/ pure nothrow @nogc {\n static size_t binomial(size_t n, size_t k) pure nothrow @safe @nogc\n in {\n assert(n > 0, \"binomial: n must be > 0.\");\n } body {\n if (k < 0 || k > n)\n return 0;\n if (k > (n / 2))\n k = n - k;\n size_t result = 1;\n foreach (size_t d; 1 .. k + 1) {\n result *= n;\n n--;\n result /= d;\n }\n return result;\n }\n\n if (!lenComputed) {\n // Set cache.\n len = binomial(n, r);\n lenComputed = true;\n }\n return len;\n }\n\n void popFront() pure nothrow @safe {\n if (!empty) {\n bool broken = false;\n size_t pos = 0;\n foreach_reverse (immutable i; 0 .. r) {\n pos = i;\n if (indices[i] != i + n - r) {\n broken = true;\n break;\n }\n }\n if (!broken) {\n empty = true;\n return;\n }\n indices[pos]++;\n foreach (immutable j; pos + 1 .. r)\n indices[j] = indices[j - 1] + 1;\n static if (copy)\n front = new Unqual!T[front.length];\n foreach (immutable i, immutable idx; indices)\n front[i] = pool[idx];\n }\n }\n}\n\nCombinations!(T, copy) combinations(bool copy=true, T)\n (T[] items, in size_t k)\nin {\n assert(items.length, \"combinations: items can't be empty.\");\n} body {\n return typeof(return)(items, k);\n}\n\n// Compile with -version=combinations3_main to run main.\nversion(combinations3_main)\nvoid main() {\n import std.stdio, std.array, std.algorithm;\n [1, 2, 3, 4].combinations!false(2).array.writeln;\n [1, 2, 3, 4].combinations!true(2).array.writeln;\n [1, 2, 3, 4].combinations(2).map!(x => x).writeln;\n}\n", "language": "D" }, { "code": "module combinations4;\nimport std.stdio, std.algorithm, std.conv;\n\nulong choose(int n, int k) nothrow\nin {\n assert(n >= 0 && k >= 0, \"choose: no negative input.\");\n} body {\n static ulong[][] cache;\n\n if (n < k)\n return 0;\n else if (n == k)\n return 1;\n while (n >= cache.length)\n cache ~= [1UL]; // = choose(m, 0);\n auto kmax = min(k, n - k);\n while(kmax >= cache[n].length) {\n immutable h = cache[n].length;\n cache[n] ~= choose(n - 1, h - 1) + choose(n - 1, h);\n }\n\n return cache[n][kmax];\n}\n\nint largestV(in int p, in int q, in long r) nothrow\nin {\n assert(p > 0 && q >= 0 && r >= 0, \"largestV: no negative input.\");\n} body {\n auto v = p - 1;\n while (choose(v, q) > r)\n v--;\n return v;\n}\n\nstruct Comb {\n immutable int n, m;\n\n @property size_t length() const /*nothrow*/ {\n return to!size_t(choose(n, m));\n }\n\n int[] opIndex(in size_t idx) const {\n if (m < 0 || n < 0)\n return [];\n if (idx >= length)\n throw new Exception(\"Out of bound\");\n ulong x = choose(n, m) - 1 - idx;\n int a = n, b = m;\n auto res = new int[m];\n foreach (i; 0 .. m) {\n a = largestV(a, b, x);\n x = x - choose(a, b);\n b = b - 1;\n res[i] = n - 1 - a;\n }\n return res;\n }\n\n int opApply(int delegate(ref int[]) dg) const {\n int[] yield;\n\n foreach (i; 0 .. length) {\n yield = this[i];\n if (dg(yield))\n break;\n }\n\n return 0;\n }\n\n static auto On(T)(in T[] arr, in int m) {\n auto comb = Comb(arr.length, m);\n\n return new class {\n @property size_t length() const /*nothrow*/ {\n return comb.length;\n }\n\n int opApply(int delegate(ref T[]) dg) const {\n auto yield = new T[m];\n\n foreach (c; comb) {\n foreach (idx; 0 .. m)\n yield[idx] = arr[c[idx]];\n if (dg(yield))\n break;\n }\n\n return 0;\n }\n };\n }\n}\n\n\nversion(combinations4_main)\n void main() {\n foreach (c; Comb.On([1, 2, 3], 2))\n writeln(c);\n }\n", "language": "D" }, { "code": "def combinations(m, range) {\n return if (m <=> 0) { [[]] } else {\n def combGenerator {\n to iterate(f) {\n for i in range {\n for suffix in combinations(m.previous(), range & (int > i)) {\n f(null, [i] + suffix)\n }\n }\n }\n }\n }\n}\n", "language": "E" }, { "code": "n = 5\nm = 3\nlen result[] m\n#\nproc combinations pos val . .\n if pos <= m\n for i = val to n - m\n result[pos] = pos + i\n combinations pos + 1 i\n .\n else\n print result[]\n .\n.\ncombinations 1 0\n", "language": "EasyLang" }, { "code": ";;\n;; using the native (combinations) function\n(lib 'list)\n(combinations (iota 5) 3)\n→ ((0 1 2) (0 1 3) (0 1 4) (0 2 3) (0 2 4) (0 3 4) (1 2 3) (1 2 4) (1 3 4) (2 3 4))\n;;\n;; using an iterator\n;;\n(lib 'sequences)\n(take (combinator (iota 5) 3) #:all)\n→ ((0 1 2) (0 1 3) (0 1 4) (0 2 3) (0 2 4) (0 3 4) (1 2 3) (1 2 4) (1 3 4) (2 3 4))\n;;\n;; defining a function\n;;\n(define (combine lst p) (cond\n [(null? lst) null]\n [(< (length lst) p) null]\n [(= (length lst) p) (list lst)]\n [(= p 1) (map list lst)]\n [else (append\n (map cons (circular-list (first lst)) (combine (rest lst) (1- p)))\n (combine (rest lst) p))]))\n\n(combine (iota 5) 3)\n → ((0 1 2) (0 1 3) (0 1 4) (0 2 3) (0 2 4) (0 3 4) (1 2 3) (1 2 4) (1 3 4) (2 3 4))\n", "language": "EchoLisp" }, { "code": "(define $comb\n (lambda [$n $xs]\n (match-all xs (list integer)\n [(loop $i [1 ,n] <join _ <cons $a_i ...>> _) a])))\n\n(test (comb 3 (between 0 4)))\n", "language": "Egison" }, { "code": "class\n\tCOMBINATIONS\n\ncreate\n\tmake\n\nfeature\n\n\tmake (n, k: INTEGER)\n\t\trequire\n\t\t\tn_positive: n > 0\n\t\t\tk_positive: k > 0\n\t\t\tk_smaller_equal: k <= n\n\t\tdo\n\t\t\tcreate set.make\n\t\t\tset.extend (\"\")\n\t\t\tcreate sol.make\n\t\t\tsol := solve (set, k, n - k)\n\t\t\tsol := convert_solution (n, sol)\n\t\tensure\n\t\t\tcorrect_num_of_sol: num_of_comb (n, k) = sol.count\n\t\tend\n\n\tsol: LINKED_LIST [STRING]\n\nfeature {None}\n\n\tset: LINKED_LIST [STRING]\n\n\tconvert_solution (n: INTEGER; solution: LINKED_LIST [STRING]): LINKED_LIST [STRING]\n\t\t\t-- strings of 'k' digits between 1 and 'n'\n\t\tlocal\n\t\t\ti, j: INTEGER\n\t\t\ttemp: STRING\n\t\tdo\n\t\t\tcreate temp.make (n)\n\t\t\tfrom\n\t\t\t\ti := 1\n\t\t\tuntil\n\t\t\t\ti > solution.count\n\t\t\tloop\n\t\t\t\tfrom\n\t\t\t\t\tj := 1\n\t\t\t\tuntil\n\t\t\t\t\tj > n\n\t\t\t\tloop\n\t\t\t\t\tif solution [i].at (j) = '1' then\n\t\t\t\t\t\ttemp.append (j.out)\n\t\t\t\t\tend\n\t\t\t\t\tj := j + 1\n\t\t\t\tend\n\t\t\t\tsolution [i].deep_copy (temp)\n\t\t\t\ttemp.wipe_out\n\t\t\t\ti := i + 1\n\t\t\tend\n\t\t\tResult := solution\n\t\tend\n\n\tsolve (seta: LINKED_LIST [STRING]; one, zero: INTEGER): LINKED_LIST [STRING]\n\t\t\t-- list of strings with a number of 'one' 1s and 'zero' 0, standig for wether the corresponing digit is taken or not.\n\t\tlocal\n\t\t\tnew_P1, new_P0: LINKED_LIST [STRING]\n\t\tdo\n\t\t\tcreate new_P1.make\n\t\t\tcreate new_P0.make\n\t\t\tif one > 0 then\n\t\t\t\tnew_P1.deep_copy (seta)\n\t\t\t\tacross\n\t\t\t\t\tnew_P1 as P1\n\t\t\t\tloop\n\t\t\t\t\tnew_P1.item.append (\"1\")\n\t\t\t\tend\n\t\t\t\tnew_P1 := solve (new_P1, one - 1, zero)\n\t\t\tend\n\t\t\tif zero > 0 then\n\t\t\t\tnew_P0.deep_copy (seta)\n\t\t\t\tacross\n\t\t\t\t\tnew_P0 as P0\n\t\t\t\tloop\n\t\t\t\t\tnew_P0.item.append (\"0\")\n\t\t\t\tend\n\t\t\t\tnew_P0 := solve (new_P0, one, zero - 1)\n\t\t\tend\n\t\t\tif one = 0 and zero = 0 then\n\t\t\t\tResult := seta\n\t\t\telse\n\t\t\t\tcreate Result.make\n\t\t\t\tResult.fill (new_p0)\n\t\t\t\tResult.fill (new_p1)\n\t\t\tend\n\t\tend\n\n\tnum_of_comb (n, k: INTEGER): INTEGER\n\t\t\t-- number of 'k' sized combinations out of 'n'.\n\t\tlocal\n\t\t\tupper, lower, m, l: INTEGER\n\t\tdo\n\t\t\tupper := 1\n\t\t\tlower := 1\n\t\t\tm := n\n\t\t\tl := k\n\t\t\tfrom\n\t\t\tuntil\n\t\t\t\tm < n - k + 1\n\t\t\tloop\n\t\t\t\tupper := m * upper\n\t\t\t\tlower := l * lower\n\t\t\t\tm := m - 1\n\t\t\t\tl := l - 1\n\t\t\tend\n\t\t\tResult := upper // lower\n\t\tend\n\nend\n", "language": "Eiffel" }, { "code": "class\n\tAPPLICATION\n\ncreate\n\tmake\n\nfeature\n\n\tmake\n\t\tdo\n\t\t\tcreate comb.make (5, 3)\n\t\t\tacross\n\t\t\t\tcomb.sol as ar\n\t\t\tloop\n\t\t\t\tio.put_string (ar.item.out + \"%T\")\n\t\t\tend\n\t\tend\n\n\tcomb: COMBINATIONS\n\nend\n", "language": "Eiffel" }, { "code": "import system'routines;\nimport extensions;\nimport extensions'routines;\n\nconst int M = 3;\nconst int N = 5;\n\nNumbers(n)\n{\n ^ Array.allocate(n).populate::(int n => n)\n}\n\npublic program()\n{\n var numbers := Numbers(N);\n Combinator.new(M, numbers).forEach::(row)\n {\n console.printLine(row.toString())\n };\n\n console.readChar()\n}\n", "language": "Elena" }, { "code": "defmodule RC do\n def comb(0, _), do: [[]]\n def comb(_, []), do: []\n def comb(m, [h|t]) do\n (for l <- comb(m-1, t), do: [h|l]) ++ comb(m, t)\n end\nend\n\n{m, n} = {3, 5}\nlist = for i <- 1..n, do: i\nEnum.each(RC.comb(m, list), fn x -> IO.inspect x end)\n", "language": "Elixir" }, { "code": "(defun comb-recurse (m n n-max)\n (cond ((zerop m) '(()))\n ((= n-max n) '())\n (t (append (mapcar #'(lambda (rest) (cons n rest))\n (comb-recurse (1- m) (1+ n) n-max))\n (comb-recurse m (1+ n) n-max)))))\n\n(defun comb (m n)\n (comb-recurse m 0 n))\n\n(comb 3 5)\n", "language": "Emacs-Lisp" }, { "code": "-module(comb).\n-compile(export_all).\n\ncomb(0,_) ->\n [[]];\ncomb(_,[]) ->\n [];\ncomb(N,[H|T]) ->\n [[H|L] || L <- comb(N-1,T)]++comb(N,T).\n", "language": "Erlang" }, { "code": "-module(comb).\n-export([combinations/2]).\n\ncombinations(K, List) ->\n lists:last(all_combinations(K, List)).\n\nall_combinations(K, List) ->\n lists:foldr(\n fun(X, Next) ->\n Sub = lists:sublist(Next, length(Next) - 1),\n Step = [[]] ++ [[[X|S] || S <- L] || L <- Sub],\n lists:zipwith(fun lists:append/2, Step, Next)\n end, [[[]]] ++ lists:duplicate(K, []), List).\n", "language": "Erlang" }, { "code": "PROGRAM COMBINATIONS\n\nCONST M_MAX=3,N_MAX=5\n\nDIM COMBINATION[M_MAX],STACK[100,1]\n\nPROCEDURE GENERATE(M)\n LOCAL I\n IF (M>M_MAX) THEN\n FOR I=1 TO M_MAX DO\n PRINT(COMBINATION[I];\" \";)\n END FOR\n PRINT\n ELSE\n FOR N=1 TO N_MAX DO\n IF ((M=1) OR (N>COMBINATION[M-1])) THEN\n COMBINATION[M]=N\n ! --- PUSH STACK -----------\n STACK[SP,0]=M STACK[SP,1]=N\n SP=SP+1\n ! --------------------------\n\n GENERATE(M+1)\n\n ! --- POP STACK ------------\n SP=SP-1\n M=STACK[SP,0] N=STACK[SP,1]\n ! --------------------------\n END IF\n END FOR\n END IF\nEND PROCEDURE\n\nBEGIN\n GENERATE(1)\nEND PROGRAM\n", "language": "ERRE" }, { "code": "let choose m n =\n let rec fC prefix m from = seq {\n let rec loopFor f = seq {\n match f with\n | [] -> ()\n | x::xs ->\n yield (x, fC [] (m-1) xs)\n yield! loopFor xs\n }\n if m = 0 then yield prefix\n else\n for (i, s) in loopFor from do\n for x in s do\n yield prefix@[i]@x\n }\n fC [] m [0..(n-1)]\n\n[<EntryPoint>]\nlet main argv =\n choose 3 5\n |> Seq.iter (printfn \"%A\")\n 0\n", "language": "F-Sharp" }, { "code": "USING: math.combinatorics prettyprint ;\n\n5 iota 3 all-combinations .\n", "language": "Factor" }, { "code": "{ \"a\" \"b\" \"c\" } 2 all-combinations .\n", "language": "Factor" }, { "code": "program Combinations\n use iso_fortran_env\n implicit none\n\n type comb_result\n integer, dimension(:), allocatable :: combs\n end type comb_result\n\n type(comb_result), dimension(:), pointer :: r\n integer :: i, j\n\n call comb(5, 3, r)\n do i = 0, choose(5, 3) - 1\n do j = 2, 0, -1\n write(*, \"(I4, ' ')\", advance=\"no\") r(i)%combs(j)\n end do\n deallocate(r(i)%combs)\n write(*,*) \"\"\n end do\n deallocate(r)\n\ncontains\n\n function choose(n, k, err)\n integer :: choose\n integer, intent(in) :: n, k\n integer, optional, intent(out) :: err\n\n integer :: imax, i, imin, ie\n\n ie = 0\n if ( (n < 0 ) .or. (k < 0 ) ) then\n write(ERROR_UNIT, *) \"negative in choose\"\n choose = 0\n ie = 1\n else\n if ( n < k ) then\n choose = 0\n else if ( n == k ) then\n choose = 1\n else\n imax = max(k, n-k)\n imin = min(k, n-k)\n choose = 1\n do i = imax+1, n\n choose = choose * i\n end do\n do i = 2, imin\n choose = choose / i\n end do\n end if\n end if\n if ( present(err) ) err = ie\n end function choose\n\n subroutine comb(n, k, co)\n integer, intent(in) :: n, k\n type(comb_result), dimension(:), pointer, intent(out) :: co\n\n integer :: i, j, s, ix, kx, hm, t\n integer :: err\n\n hm = choose(n, k, err)\n if ( err /= 0 ) then\n nullify(co)\n return\n end if\n\n allocate(co(0:hm-1))\n do i = 0, hm-1\n allocate(co(i)%combs(0:k-1))\n end do\n do i = 0, hm-1\n ix = i; kx = k\n do s = 0, n-1\n if ( kx == 0 ) exit\n t = choose(n-(s+1), kx-1)\n if ( ix < t ) then\n co(i)%combs(kx-1) = s\n kx = kx - 1\n else\n ix = ix - t\n end if\n end do\n end do\n\n end subroutine comb\n\nend program Combinations\n", "language": "Fortran" }, { "code": "program combinations\n\n implicit none\n integer, parameter :: m_max = 3\n integer, parameter :: n_max = 5\n integer, dimension (m_max) :: comb\n character (*), parameter :: fmt = '(i0' // repeat (', 1x, i0', m_max - 1) // ')'\n\n call gen (1)\n\ncontains\n\n recursive subroutine gen (m)\n\n implicit none\n integer, intent (in) :: m\n integer :: n\n\n if (m > m_max) then\n write (*, fmt) comb\n else\n do n = 1, n_max\n if ((m == 1) .or. (n > comb (m - 1))) then\n comb (m) = n\n call gen (m + 1)\n end if\n end do\n end if\n\n end subroutine gen\n\nend program combinations\n", "language": "Fortran" }, { "code": "sub iterate( byval curr as string, byval start as uinteger,_\n byval stp as uinteger, byval depth as uinteger )\n dim as uinteger i\n for i = start to stp\n if depth = 0 then\n print curr + \" \" + str(i)\n end if\n iterate( curr+\" \"+str(i), i+1, stp, depth-1 )\n next i\n return\nend sub\n\ndim as uinteger m, n\ninput \"Enter n comb m. \", n, m\ndim as string outstr = \"\"\niterate outstr, 0, m-1, n-1\n", "language": "Fortran" }, { "code": "# Built-in\nCombinations([1 .. n], m);\n\nCombinations([1 .. 5], 3);\n# [ [ 1, 2, 3 ], [ 1, 2, 4 ], [ 1, 2, 5 ], [ 1, 3, 4 ], [ 1, 3, 5 ],\n# [ 1, 4, 5 ], [ 2, 3, 4 ], [ 2, 3, 5 ], [ 2, 4, 5 ], [ 3, 4, 5 ] ]\n", "language": "GAP" }, { "code": "5!3 >>> ,,\\\n\n$$(5!3) give all combinations of 3 out of 5\n$$(>>>) sorted up,\n$$(,,\\) printed with crlf delimiters.\n", "language": "Glee" }, { "code": "Result:\n1 2 3\n1 2 4\n1 2 5\n1 3 4\n1 3 5\n1 4 5\n2 3 4\n2 3 5\n2 4 5\n3 4 5\n", "language": "Glee" }, { "code": "package main\n\nimport (\n \"fmt\"\n)\n\nfunc main() {\n comb(5, 3, func(c []int) {\n fmt.Println(c)\n })\n}\n\nfunc comb(n, m int, emit func([]int)) {\n s := make([]int, m)\n last := m - 1\n var rc func(int, int)\n rc = func(i, next int) {\n for j := next; j < n; j++ {\n s[i] = j\n if i == last {\n emit(s)\n } else {\n rc(i+1, j+1)\n }\n }\n return\n }\n rc(0, 0)\n}\n", "language": "Go" }, { "code": "def comb\ncomb = { m, list ->\n def n = list.size()\n m == 0 ?\n [[]] :\n (0..(n-m)).inject([]) { newlist, k ->\n def sublist = (k+1 == n) ? [] : list[(k+1)..<n]\n newlist += comb(m-1, sublist).collect { [list[k]] + it }\n }\n}\n", "language": "Groovy" }, { "code": "def csny = [ \"Crosby\", \"Stills\", \"Nash\", \"Young\" ]\nprintln \"Choose from ${csny}\"\n(0..(csny.size())).each { i -> println \"Choose ${i}:\"; comb(i, csny).each { println it }; println() }\n", "language": "Groovy" }, { "code": "def comb0 = { m, n -> comb(m, (0..<n)) }\n", "language": "Groovy" }, { "code": "println \"Choose out of 5 (zero-based):\"\n(0..3).each { i -> println \"Choose ${i}:\"; comb0(i, 5).each { println it }; println() }\n", "language": "Groovy" }, { "code": "def comb1 = { m, n -> comb(m, (1..n)) }\n", "language": "Groovy" }, { "code": "println \"Choose out of 5 (one-based):\"\n(0..3).each { i -> println \"Choose ${i}:\"; comb1(i, 5).each { println it }; println() }\n", "language": "Groovy" }, { "code": "comb :: Int -> [a] -> [[a]]\ncomb 0 _ = [[]]\ncomb _ [] = []\ncomb m (x:xs) = map (x:) (comb (m-1) xs) ++ comb m xs\n", "language": "Haskell" }, { "code": "import Data.List (tails)\n\ncomb :: Int -> [a] -> [[a]]\ncomb 0 _ = [[]]\ncomb m l = [x:ys | x:xs <- tails l, ys <- comb (m-1) xs]\n", "language": "Haskell" }, { "code": "comb0 m n = comb m [0..n-1]\n", "language": "Haskell" }, { "code": "comb1 m n = comb m [1..n]\n", "language": "Haskell" }, { "code": "import Data.List (sort, subsequences)\ncomb m n = sort . filter ((==m) . length) $ subsequences [0..n-1]\n", "language": "Haskell" }, { "code": "comb m n = filter ((==m . length) $ filterM (const [True, False]) [0..n-1]\n", "language": "Haskell" }, { "code": "comb :: Int -> [a] -> [[a]]\ncomb m xs = combsBySize xs !! m\n where\n combsBySize = foldr f ([[]] : repeat [])\n f x next =\n zipWith\n (<>)\n (fmap (x :) <$> ([] : next))\n next\n\nmain :: IO ()\nmain = print $ comb 3 [0 .. 4]\n", "language": "Haskell" }, { "code": "procedure main()\nreturn combinations(3,5,0)\nend\n\nprocedure combinations(m,n,z) # demonstrate combinations\n/z := 1\n\nwrite(m,\" combinations of \",n,\" integers starting from \",z)\nevery put(L := [], z to n - 1 + z by 1) # generate list of n items from z\nwrite(\"Intial list\\n\",list2string(L))\nwrite(\"Combinations:\")\nevery write(list2string(lcomb(L,m)))\nend\n\nprocedure list2string(L) # helper function\nevery (s := \"[\") ||:= \" \" || (!L|\"]\")\nreturn s\nend\n\nlink lists\n", "language": "Icon" }, { "code": "procedure lcomb(L,i)\t\t\t#: list combinations\n local j\n\n if i < 1 then fail\n suspend if i = 1 then [!L]\n else [L[j := 1 to *L - i + 1]] ||| lcomb(L[j + 1:0],i - 1)\n\nend\n", "language": "Icon" }, { "code": "100 PROGRAM \"Combinat.bas\"\n110 LET MMAX=3:LET NMAX=5\n120 NUMERIC COMB(0 TO MMAX)\n130 CALL GENERATE(1)\n140 DEF GENERATE(M)\n150 NUMERIC N,I\n160 IF M>MMAX THEN\n170 FOR I=1 TO MMAX\n180 PRINT COMB(I);\n190 NEXT\n200 PRINT\n220 ELSE\n230 FOR N=0 TO NMAX-1\n240 IF M=1 OR N>COMB(M-1) THEN\n250 LET COMB(M)=N\n260 CALL GENERATE(M+1)\n270 END IF\n280 NEXT\n290 END IF\n300 END DEF\n", "language": "IS-BASIC" }, { "code": "require'stats'\n", "language": "J" }, { "code": " 3 comb 5\n0 1 2\n0 1 3\n0 1 4\n0 2 3\n0 2 4\n0 3 4\n1 2 3\n1 2 4\n1 3 4\n2 3 4\n", "language": "J" }, { "code": "comb1=: dyad define\n c=. 1 {.~ - d=. 1+y-x\n z=. i.1 0\n for_j. (d-1+y)+/&i.d do. z=. (c#j) ,. z{~;(-c){.&.><i.{.c=. +/\\.c end.\n)\n", "language": "J" }, { "code": "comb2=: dyad define\n d =. 1 + y - x\n k =. >: |. i. d\n z =. < \\. |. i. d\n for. i.x-1 do.\n z=. , each /\\. k ,. each z\n k =. 1 + k\n end.\n ;{.z\n)\n", "language": "J" }, { "code": "combr=: dyad define M.\n if. (x>:y)+.0=x do. i.(x<:y),x else. (0,.x combr&.<: y),1+x combr y-1 end.\n)\n", "language": "J" }, { "code": " combr=: dyad define\n if.(x=#y) +. x=1 do.\n y\n else.\n (({.y) ,. (x-1) combr (}.y)) , (x combr }.y)\n end.\n)\n", "language": "J" }, { "code": "combb=: (#~ ((-:/:~)>/:~-:\\:~)\"1)@(# #: [: i. ^~)\n", "language": "J" }, { "code": "import java.util.Collections;\nimport java.util.LinkedList;\n\npublic class Comb{\n\n public static void main(String[] args){\n System.out.println(comb(3,5));\n }\n\n public static String bitprint(int u){\n String s= \"\";\n for(int n= 0;u > 0;++n, u>>= 1)\n if((u & 1) > 0) s+= n + \" \";\n return s;\n }\n\n public static int bitcount(int u){\n int n;\n for(n= 0;u > 0;++n, u&= (u - 1));//Turn the last set bit to a 0\n return n;\n }\n\n public static LinkedList<String> comb(int c, int n){\n LinkedList<String> s= new LinkedList<String>();\n for(int u= 0;u < 1 << n;u++)\n if(bitcount(u) == c) s.push(bitprint(u));\n Collections.sort(s);\n return s;\n }\n}\n", "language": "Java" }, { "code": "function bitprint(u) {\n var s=\"\";\n for (var n=0; u; ++n, u>>=1)\n if (u&1) s+=n+\" \";\n return s;\n}\nfunction bitcount(u) {\n for (var n=0; u; ++n, u=u&(u-1));\n return n;\n}\nfunction comb(c,n) {\n var s=[];\n for (var u=0; u<1<<n; u++)\n if (bitcount(u)==c)\n s.push(bitprint(u))\n return s.sort();\n}\ncomb(3,5)\n", "language": "JavaScript" }, { "code": "function combinations(arr, k){\n var i,\n subI,\n ret = [],\n sub,\n next;\n for(i = 0; i < arr.length; i++){\n if(k === 1){\n ret.push( [ arr[i] ] );\n }else{\n sub = combinations(arr.slice(i+1, arr.length), k-1);\n for(subI = 0; subI < sub.length; subI++ ){\n next = sub[subI];\n next.unshift(arr[i]);\n ret.push( next );\n }\n }\n }\n return ret;\n}\ncombinations([0,1,2,3,4], 3);\n// produces: [[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]\n\ncombinations([\"Crosby\", \"Stills\", \"Nash\", \"Young\"], 3);\n// produces: [[\"Crosby\", \"Stills\", \"Nash\"], [\"Crosby\", \"Stills\", \"Young\"], [\"Crosby\", \"Nash\", \"Young\"], [\"Stills\", \"Nash\", \"Young\"]]\n", "language": "JavaScript" }, { "code": "(function () {\n\n function comb(n, lst) {\n if (!n) return [[]];\n if (!lst.length) return [];\n\n var x = lst[0],\n xs = lst.slice(1);\n\n return comb(n - 1, xs).map(function (t) {\n return [x].concat(t);\n }).concat(comb(n, xs));\n }\n\n\n // [m..n]\n function range(m, n) {\n return Array.apply(null, Array(n - m + 1)).map(function (x, i) {\n return m + i;\n });\n }\n\n return comb(3, range(0, 4))\n\n .map(function (x) {\n return x.join(' ');\n }).join('\\n');\n\n})();\n", "language": "JavaScript" }, { "code": "(function (n) {\n\n // n -> [a] -> [[a]]\n function comb(n, lst) {\n if (!n) return [[]];\n if (!lst.length) return [];\n\n var x = lst[0],\n xs = lst.slice(1);\n\n return comb(n - 1, xs).map(function (t) {\n return [x].concat(t);\n }).concat(comb(n, xs));\n }\n\n // f -> f\n function memoized(fn) {\n m = {};\n return function (x) {\n var args = [].slice.call(arguments),\n strKey = args.join('-');\n\n v = m[strKey];\n if ('u' === (typeof v)[0])\n m[strKey] = v = fn.apply(null, args);\n return v;\n }\n }\n\n // [m..n]\n function range(m, n) {\n return Array.apply(null, Array(n - m + 1)).map(function (x, i) {\n return m + i;\n });\n }\n\n var fnMemoized = memoized(comb),\n lstRange = range(0, 4);\n\n return fnMemoized(n, lstRange)\n\n .map(function (x) {\n return x.join(' ');\n }).join('\\n');\n\n})(3);\n", "language": "JavaScript" }, { "code": "0 1 2\n0 1 3\n0 1 4\n0 2 3\n0 2 4\n0 3 4\n1 2 3\n1 2 4\n1 3 4\n2 3 4\n", "language": "JavaScript" }, { "code": "(() => {\n 'use strict';\n\n // ------------------ COMBINATIONS -------------------\n\n // combinations :: Int -> [a] -> [[a]]\n const combinations = n =>\n xs => {\n const comb = n => xs => {\n return 1 > n ? [\n []\n ] : 0 === xs.length ? (\n []\n ) : (() => {\n const\n h = xs[0],\n tail = xs.slice(1);\n return comb(n - 1)(tail)\n .map(cons(h))\n .concat(comb(n)(tail));\n })()\n };\n return comb(n)(xs);\n };\n\n // ---------------------- TEST -----------------------\n const main = () =>\n show(\n combinations(3)(\n enumFromTo(0)(4)\n )\n );\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // cons :: a -> [a] -> [a]\n const cons = x =>\n // A list constructed from the item x,\n // followed by the existing list xs.\n xs => [x].concat(xs);\n\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => !isNaN(m) ? (\n Array.from({\n length: 1 + n - m\n }, (_, i) => m + i)\n ) : enumFromTo_(m)(n);\n\n\n // show :: a -> String\n const show = (...x) =>\n JSON.stringify.apply(\n null, x.length > 1 ? [x[0], null, x[1]] : x\n );\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "(() => {\n 'use strict';\n\n // ------------------ COMBINATIONS -------------------\n\n // comb :: Int -> Int -> [[Int]]\n const comb = m =>\n n => combinations(m)(\n enumFromTo(0)(n - 1)\n );\n\n // combinations :: Int -> [a] -> [[a]]\n const combinations = k =>\n xs => sort(\n filter(xs => k === xs.length)(\n subsequences(xs)\n )\n );\n\n // --------------------- TEST ---------------------\n const main = () =>\n show(\n comb(3)(5)\n );\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // cons :: a -> [a] -> [a]\n const cons = x =>\n // A list constructed from the item x,\n // followed by the existing list xs.\n xs => [x].concat(xs);\n\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => !isNaN(m) ? (\n Array.from({\n length: 1 + n - m\n }, (_, i) => m + i)\n ) : enumFromTo_(m)(n);\n\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = p =>\n // The elements of xs which match\n // the predicate p.\n xs => [...xs].filter(p);\n\n\n // list :: StringOrArrayLike b => b -> [a]\n const list = xs =>\n // xs itself, if it is an Array,\n // or an Array derived from xs.\n Array.isArray(xs) ? (\n xs\n ) : Array.from(xs || []);\n\n\n // show :: a -> String\n const show = x =>\n // JSON stringification of a JS value.\n JSON.stringify(x)\n\n\n // sort :: Ord a => [a] -> [a]\n const sort = xs => list(xs).slice()\n .sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));\n\n\n // subsequences :: [a] -> [[a]]\n // subsequences :: String -> [String]\n const subsequences = xs => {\n const\n // nonEmptySubsequences :: [a] -> [[a]]\n nonEmptySubsequences = xxs => {\n if (xxs.length < 1) return [];\n const [x, xs] = [xxs[0], xxs.slice(1)];\n const f = (r, ys) => cons(ys)(cons(cons(x)(ys))(r));\n return cons([x])(nonEmptySubsequences(xs)\n .reduceRight(f, []));\n };\n return ('string' === typeof xs) ? (\n cons('')(nonEmptySubsequences(xs.split(''))\n .map(x => ''.concat.apply('', x)))\n ) : cons([])(nonEmptySubsequences(xs));\n };\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "function combinations(k, arr, prefix = []) {\n if (prefix.length == 0) arr = [...Array(arr).keys()];\n if (k == 0) return [prefix];\n return arr.flatMap((v, i) =>\n combinations(k - 1, arr.slice(i + 1), [...prefix, v])\n );\n}\n", "language": "JavaScript" }, { "code": "def combination(r):\n if r > length or r < 0 then empty\n elif r == length then .\n else ( [.[0]] + (.[1:]|combination(r-1))),\n ( .[1:]|combination(r))\n end;\n\n# select r integers from the set (0 .. n-1)\ndef combinations(n;r): [range(0;n)] | combination(r);\n", "language": "Jq" }, { "code": "using Combinatorics\nn = 4\nm = 3\nfor i in combinations(0:n,m)\n println(i')\nend\n", "language": "Julia" }, { "code": "##############################\n# COMBINATIONS OF 3 OUT OF 5 #\n##############################\n\n# Set n and m\nm = 5\nn = 3\n\n# Prepare the boundary of the calculation. Only m - n numbers are changing in each position.\nmax_n = m - n\n\n#Prepare an array for result\nresult = zeros(Int64, n)\n\nfunction combinations(pos, val) # n, max_n and result are visible in the function\n for i = val:max_n # from current value to the boundary\n result[pos] = pos + i # fill the position of result\n if pos < n # if combination isn't complete,\n combinations(pos+1, i) # go to the next position\n else\n println(result) # combination is complete, print it\n end\n end\nend\n\ncombinations(1, 0)\nend\n", "language": "Julia" }, { "code": "using Base.Iterators\n\nfunction bitmask(u, max_size)\n res = BitArray(undef, max_size)\n res.chunks[1] = u%UInt64\n res\nend\n\nfunction combinations(input_collection::Vector{T}, choice_size::Int)::Vector{Vector{T}} where T\n num_elements = length(input_collection)\n size_filter(x) = Iterators.filter(y -> count_ones(y) == choice_size, x)\n bitmask_map(x) = Iterators.map(y -> bitmask(y, num_elements), x)\n getindex_map(x) = Iterators.map(y -> input_collection[y], x)\n\n UnitRange(0, (2^num_elements)-1) |>\n size_filter |>\n bitmask_map |>\n getindex_map |>\n collect\nend\n", "language": "Julia" }, { "code": "comb:{[n;k]\n f:{:[k=#x; :,x; :,/_f' x,'(1+*|x) _ !n]}\n :,/f' !n\n}\n", "language": "K" }, { "code": "class Combinations(val m: Int, val n: Int) {\n private val combination = IntArray(m)\n\n init {\n generate(0)\n }\n\n private fun generate(k: Int) {\n if (k >= m) {\n for (i in 0 until m) print(\"${combination[i]} \")\n println()\n }\n else {\n for (j in 0 until n)\n if (k == 0 || j > combination[k - 1]) {\n combination[k] = j\n generate(k + 1)\n }\n }\n }\n}\n\nfun main(args: Array<String>) {\n Combinations(3, 5)\n}\n", "language": "Kotlin" }, { "code": "import java.util.LinkedList\n\ninline fun <reified T> combinations(arr: Array<T>, m: Int) = sequence {\n val n = arr.size\n val result = Array(m) { arr[0] }\n val stack = LinkedList<Int>()\n stack.push(0)\n while (stack.isNotEmpty()) {\n var resIndex = stack.size - 1;\n var arrIndex = stack.pop()\n\n while (arrIndex < n) {\n result[resIndex++] = arr[arrIndex++]\n stack.push(arrIndex)\n\n if (resIndex == m) {\n yield(result.toList())\n break\n }\n }\n }\n}\n\nfun main() {\n val n = 5\n val m = 3\n combinations((1..n).toList().toTypedArray(), m).forEach { println(it.joinToString(separator = \" \")) }\n}\n", "language": "Kotlin" }, { "code": "{def comb\n {def comb.r\n {lambda {:m :n :N}\n {if {= :m 0}\n then {A.new {A.new}}\n else {if {= :n :N}\n then {A.new}\n else {A.concat\n {A.map {{lambda {:n :rest} {A.addfirst! :n :rest}} :n}\n {comb.r {- :m 1} {+ :n 1} :N}}\n {comb.r :m {+ :n 1} :N}}}}}}\n {lambda {:m :n}\n {comb.r :m 0 :n}}}\n-> comb\n\n{comb 3 5}\n-> [[0,1,2],[0,1,3],[0,1,4],[0,2,3],[0,2,4],[0,3,4],\n [1,2,3],[1,2,4],[1,3,4],[2,3,4]]\n", "language": "Lambdatalk" }, { "code": "import std\n\n// combi is an itertor that solves the Combinations problem for iota arrays as stated\n\ndef combi(m, n, f):\n let c = map(n): _\n\n while true:\n f(c)\n var i = n-1\n c[i] = c[i] + 1\n if c[i] > m - 1:\n while c[i] >= m - n + i:\n i -= 1\n if i < 0: return\n c[i] = c[i] + 1\n while i < n-1:\n c[i+1] = c[i] + 1\n i += 1\n\ncombi(5, 3): print(_)\n", "language": "Lobster" }, { "code": "import std\n\n// comba solves the general problem for any values in an input array\n\ndef comba<T>(arr: [T], k) -> [[T]]:\n let ret = []\n for(arr.length) i:\n if k == 1:\n ret.push([arr[i]])\n else:\n let sub = comba(arr.slice(i+1, -1), k-1)\n for(sub) next:\n next.insert(0, arr[i])\n ret.push(next)\n return ret\n\nprint comba([0,1,2,3,4], 3)\nprint comba([\"Crosby\", \"Stills\", \"Nash\", \"Young\"], 3)\n// Of course once could use combi to index the input array instead\nvar s = \"\"\ncombi(4, 3): s += (map(_) i: [\"Crosby\", \"Stills\", \"Nash\", \"Young\"][i]) + \" \"\nprint s\n", "language": "Lobster" }, { "code": "to comb :n :list\n if :n = 0 [output [[]]]\n if empty? :list [output []]\n output sentence map [sentence first :list ?] comb :n-1 bf :list ~\n comb :n bf :list\nend\nprint comb 3 [0 1 2 3 4]\n", "language": "Logo" }, { "code": "function map(f, a, ...) if a then return f(a), map(f, ...) end end\nfunction incr(k) return function(a) return k > a and a or a+1 end end\nfunction combs(m, n)\n if m * n == 0 then return {{}} end\n local ret, old = {}, combs(m-1, n-1)\n for i = 1, n do\n for k, v in ipairs(old) do ret[#ret+1] = {i, map(incr(i), unpack(v))} end\n end\n return ret\nend\n\nfor k, v in ipairs(combs(3, 5)) do print(unpack(v)) end\n", "language": "Lua" }, { "code": "Module Checkit {\n Global a$\n Document a$\n Module Combinations (m as long, n as long){\n Module Level (n, s, h) {\n If n=1 then {\n while Len(s) {\n Print h, car(s)\n ToClipBoard()\n s=cdr(s)\n }\n } Else {\n While len(s) {\n call Level n-1, cdr(s), cons(h, car(s))\n s=cdr(s)\n }\n }\n Sub ToClipBoard()\n local m=each(h)\n Local b$=\"\"\n While m {\n b$+=If$(Len(b$)<>0->\" \",\"\")+Format$(\"{0::-10}\",Array(m))\n }\n b$+=If$(Len(b$)<>0->\" \",\"\")+Format$(\"{0::-10}\",Array(s,0))+{\n }\n a$<=b$ ' assign to global need <=\n End Sub\n }\n If m<1 or n<1 then Error\n s=(,)\n for i=0 to n-1 {\n s=cons(s, (i,))\n }\n Head=(,)\n Call Level m, s, Head\n }\n Clear a$\n Combinations 3, 5\n ClipBoard a$\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "Module StepByStep {\n Function CombinationsStep (a, nn) {\n c1=lambda (&f, &a) ->{\n =car(a) : a=cdr(a) : f=len(a)=0\n }\n m=len(a)\n c=c1\n n=m-nn+1\n p=2\n while m>n {\n c1=lambda c2=c,n=p, z=(,) (&f, &m) ->{\n if len(z)=0 then z=cdr(m)\n =cons(car(m),c2(&f, &z))\n if f then z=(,) : m=cdr(m) : f=len(m)+len(z)<n\n }\n c=c1\n p++\n m--\n }\n =lambda c, a (&f) -> {\n =c(&f, &a)\n }\n }\n k=false\n StepA=CombinationsStep((1, 2, 3, 4,5), 3)\n while not k {\n Print StepA(&k)\n }\n k=false\n StepA=CombinationsStep((0, 1, 2, 3, 4), 3)\n while not k {\n Print StepA(&k)\n }\n k=false\n StepA=CombinationsStep((\"A\", \"B\", \"C\", \"D\",\"E\"), 3)\n while not k {\n Print StepA(&k)\n }\n k=false\n StepA=CombinationsStep((\"CAT\", \"DOG\", \"BAT\"), 2)\n while not k {\n Print StepA(&k)\n }\n}\nStepByStep\n", "language": "M2000-Interpreter" }, { "code": "divert(-1)\ndefine(`set',`define(`$1[$2]',`$3')')\ndefine(`get',`defn(`$1[$2]')')\ndefine(`setrange',`ifelse(`$3',`',$2,`define($1[$2],$3)`'setrange($1,\n incr($2),shift(shift(shift($@))))')')\ndefine(`for',\n `ifelse($#,0,``$0'',\n `ifelse(eval($2<=$3),1,\n `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')\ndefine(`show',\n `for(`k',0,decr($1),`get(a,k) ')')\n\ndefine(`chklim',\n `ifelse(get(`a',$3),eval($2-($1-$3)),\n `chklim($1,$2,decr($3))',\n `set(`a',$3,incr(get(`a',$3)))`'for(`k',incr($3),decr($2),\n `set(`a',k,incr(get(`a',decr(k))))')`'nextcomb($1,$2)')')\ndefine(`nextcomb',\n `show($1)\nifelse(eval(get(`a',0)<$2-$1),1,\n `chklim($1,$2,decr($1))')')\ndefine(`comb',\n `for(`j',0,decr($1),`set(`a',j,j)')`'nextcomb($1,$2)')\ndivert\n\ncomb(3,5)\n", "language": "M4" }, { "code": "> combinat:-choose( 5, 3 );\n[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5],\n\n [2, 4, 5], [3, 4, 5]]\n", "language": "Maple" }, { "code": "combinations[n_Integer, m_Integer]/;m>= 0:=Union[Sort /@ Permutations[Range[0, n - 1], {m}]]\n", "language": "Mathematica" }, { "code": "Subsets[Range[5], {2}]\n", "language": "Mathematica" }, { "code": ">> nchoosek((0:4),3)\n\nans =\n\n 0 1 2\n 0 1 3\n 0 1 4\n 0 2 3\n 0 2 4\n 0 3 4\n 1 2 3\n 1 2 4\n 1 3 4\n 2 3 4\n", "language": "MATLAB" }, { "code": "next_comb(n, p, a) := block(\n [a: copylist(a), i: p],\n if a[1] + p = n + 1 then return(und),\n while a[i] - i >= n - p do i: i - 1,\n a[i]: a[i] + 1,\n for j from i + 1 thru p do a[j]: a[j - 1] + 1,\n a\n)$\n\ncombinations(n, p) := block(\n [a: makelist(i, i, 1, p), v: [ ]],\n while a # 'und do (v: endcons(a, v), a: next_comb(n, p, a)),\n v\n)$\n\ncombinations(5, 3);\n/* [[1, 2, 3],\n [1, 2, 4],\n [1, 2, 5],\n [1, 3, 4],\n [1, 3, 5],\n [1, 4, 5],\n [2, 3, 4],\n [2, 3, 5],\n [2, 4, 5],\n [3, 4, 5]] */\n", "language": "Maxima" }, { "code": "MODULE Combinations;\nFROM STextIO IMPORT\n WriteString, WriteLn;\nFROM SWholeIO IMPORT\n WriteInt;\n\nCONST\n MMax = 3;\n NMax = 5;\n\nVAR\n Combination: ARRAY [0 .. MMax] OF CARDINAL;\n\nPROCEDURE Generate(M: CARDINAL);\nVAR\n N, I: CARDINAL;\nBEGIN\n IF (M > MMax) THEN\n FOR I := 1 TO MMax DO\n WriteInt(Combination[I], 1);\n WriteString(' ');\n END;\n WriteLn;\n ELSE\n FOR N := 1 TO NMax DO\n IF (M = 1) OR (N > Combination[M - 1]) THEN\n Combination[M] := N;\n Generate(M + 1);\n END\n END\n END\nEND Generate;\n\nBEGIN\n Generate(1);\nEND Combinations.\n", "language": "Modula-2" }, { "code": "iterator comb(m, n: int): seq[int] =\n var c = newSeq[int](n)\n for i in 0 ..< n: c[i] = i\n\n block outer:\n while true:\n yield c\n\n var i = n - 1\n inc c[i]\n if c[i] <= m - 1: continue\n\n while c[i] >= m - n + i:\n dec i\n if i < 0: break outer\n inc c[i]\n while i < n-1:\n c[i+1] = c[i] + 1\n inc i\n\nfor i in comb(5, 3):\n echo i\n", "language": "Nim" }, { "code": "iterator combinations(m: int, n: int): seq[int] =\n\n var result = newSeq[int](n)\n var stack = newSeq[int]()\n stack.add 0\n\n while stack.len > 0:\n var index = stack.high\n var value = stack.pop()\n\n while value < m:\n result[index] = value\n inc value\n inc index\n stack.add value\n\n if index == n:\n yield result\n break\n\nfor i in combinations(5, 3):\n echo i\n", "language": "Nim" }, { "code": "let combinations m n =\n let rec c = function\n | (0,_) -> [[]]\n | (_,0) -> []\n | (p,q) -> List.append\n (List.map (List.cons (n-q)) (c (p-1, q-1)))\n (c (p , q-1))\n in c (m , n)\n\n\nlet () =\n let rec print_list = function\n | [] -> print_newline ()\n | hd :: tl -> print_int hd ; print_string \" \"; print_list tl\n in List.iter print_list (combinations 3 5)\n", "language": "OCaml" }, { "code": "nchoosek([0:4], 3)\n", "language": "Octave" }, { "code": "define variable r as integer no-undo extent 3.\ndefine variable m as integer no-undo initial 5.\ndefine variable n as integer no-undo initial 3.\ndefine variable max_n as integer no-undo.\n\nmax_n = m - n.\n\nfunction combinations returns logical (input pos as integer, input val as integer):\n define variable i as integer no-undo.\n do i = val to max_n:\n r[pos] = pos + i.\n\tif pos lt n then\n\t\tcombinations(pos + 1, i).\n\telse\n\t \tmessage r[1] - 1 r[2] - 1 r[3] - 1.\n end.\nend function.\n\ncombinations(1, 0).\n", "language": "OpenEdge-Progress" }, { "code": "declare\n fun {Comb M N}\n proc {CombScript Comb}\n %% Comb is a subset of [0..N-1]\n Comb = {FS.var.upperBound {List.number 0 N-1 1}}\n %% Comb has cardinality M\n {FS.card Comb M}\n %% enumerate all possibilities\n {FS.distribute naive [Comb]}\n end\n in\n %% Collect all solutions and convert to lists\n {Map {SearchAll CombScript} FS.reflect.upperBoundList}\n end\nin\n {Inspect {Comb 3 5}}\n", "language": "Oz" }, { "code": "Crv ( k, v, d ) = {\n if( d == k,\n print ( vecextract( v , \"2..-2\" ) )\n ,\n for( i = v[ d + 1 ] + 1, #v,\n v[ d + 2 ] = i;\n Crv( k, v, d + 1 ) ));\n}\n\ncombRV( n, k ) = Crv ( k, vector( n, X, X-1), 0 );\n", "language": "PARI-GP" }, { "code": "Cr ( c, z, b, n, k ) = {\n if( z < b, print1( c, \" \" );\n if( n>0, Cr( c+1, z , b* k \\n, n-1, k - 1 ))\n ,\n if( n>0, Cr( c+1, z-b, b*(n-k)\\n, n-1, k ))\n );\n}\n\ncombR( n, k ) = {\n local(\n bnk = binomial( n, k ),\n b11 = bnk * k \\ n ); \\\\binomial( n-1, k-1 )\n for( z = 0, bnk - 1,\n Cr( 1, z, b11, n-1, k-1 );\n print\n );\n}\n", "language": "PARI-GP" }, { "code": "Ci( z, b, n, k ) = { local( c = 1 );\n n--; k--;\n while( k >= 0 ,\n if( z < b,\n print1(c, \" \");\n c++;\n if( n > 0,\n b = b*k \\ n);\n n--; k--;\n ,\n c++;\n z -= b;\n b = b*(n-k)\\n;\n n--\n )\n );\n\tprint;\n}\n\ncombI( n, k ) = {\n local( bnk = binomial( n, k ),\n b11 = bnk * k \\ n ); \\\\ binomial( n-1, k-1 )\n for( z = 0, bnk - 1,\n Ci(z, b11, n, k ) );\n}\n", "language": "PARI-GP" }, { "code": "Program Combinations;\n\nconst\n m_max = 3;\n n_max = 5;\nvar\n combination: array [0..m_max] of integer;\n\n procedure generate(m: integer);\n var\n n, i: integer;\n begin\n if (m > m_max) then\n begin\n for i := 1 to m_max do\n write (combination[i], ' ');\n writeln;\n end\n else\n for n := 1 to n_max do\n if ((m = 1) or (n > combination[m-1])) then\n begin\n combination[m] := n;\n generate(m + 1);\n end;\n end;\n\nbegin\n generate(1);\nend.\n", "language": "Pascal" }, { "code": "use ntheory qw/forcomb/;\nforcomb { print \"@_\\n\" } 5,3\n", "language": "Perl" }, { "code": "use Algorithm::Combinatorics qw/combinations/;\nmy @c = combinations( [0..4], 3 );\nprint \"@$_\\n\" for @c;\n", "language": "Perl" }, { "code": "use Algorithm::Combinatorics qw/combinations/;\nmy $iter = combinations([0..4],3);\nwhile (my $c = $iter->next) {\n print \"@$c\\n\";\n}\n", "language": "Perl" }, { "code": "use perl5i::2;\n\n# ----------------------------------------\n# generate combinations of length $n consisting of characters\n# from the sorted set @set, using each character once in a\n# combination, with sorted strings in sorted order.\n#\n# Returns a list of array references, each containing one combination.\n#\nfunc combine($n, @set) {\n return unless @set;\n return map { [ $_ ] } @set if $n == 1;\n\n my ($head) = shift @set;\n my @result = combine( $n-1, @set );\n for my $subarray ( @result ) {\n $subarray->unshift( $head );\n }\n return ( @result, combine( $n, @set ) );\n}\n\nsay @$_ for combine( 3, ('a'..'e') );\n", "language": "Perl5i" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">comb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">pool</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">needed</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">done</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">chosen</span><span style=\"color: #0000FF;\">={})</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">needed</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000080;font-style:italic;\">-- got a full set</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">chosen</span> <span style=\"color: #000080;font-style:italic;\">-- (or use a routine_id, result arg, or whatever)</span>\n <span style=\"color: #008080;\">return</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">done</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">needed</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">pool</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span> <span style=\"color: #000080;font-style:italic;\">-- cannot fulfil\n -- get all combinations with and without the next item:</span>\n <span style=\"color: #000000;\">done</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">comb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pool</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">needed</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">done</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">chosen</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">done</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">comb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pool</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">needed</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">done</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">chosen</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">comb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">combinations</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"12345\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">','</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": " <?php\n\n$a=array(1,2,3,4,5);\n$k=3;\n$n=5;\n$c=array_splice($a, $k);\n$b=array_splice($a, 0, $k);\n$j=$k-1;\nprint_r($b);\n\n while (1) {\n\t\n \t\t$m=array_search($b[$j]+1,$c);\n \t if ($m!==false) {\n\t \t$c[$m]-=1;\n \t$b[$j]=$b[$j]+1;\n \tprint_r($b);\t\n }\n \tif ($b[$k-1]==$n) {\n\t $i=$k-1;\n\t while ($i >= 0) {\n\n\t \t\tif ($i == 0 && $b[$i] == $n-$k+1) break 2;\n\t\n \t\t $m=array_search($b[$i]+1,$c);\n\t\t if ($m!==false) {\n\t\t \t $c[$m]=$c[$m]-1;\n\t\t\t $b[$i]=$b[$i]+1;\n\n\t\t\t$g=$i;\n\t\twhile ($g != $k-1) {\n\t\t\tarray_unshift ($c, $b[$g+1]);\n\t\t\t$b[$g+1]=$b[$g]+1;\n\t\t\t$g++;\n\t\t\t}\n\t\t\t$c=array_diff($c,$b);\n\t\t\tprint_r($b);\n\t\t \t break;\n \t\t\t }\n\t \t$i--;\n\t\n\t\t}\n\t\n\t}\n\t\n\n}\n\n?>\n", "language": "PHP" }, { "code": "<?php\n\nfunction combinations_set($set = [], $size = 0) {\n if ($size == 0) {\n return [[]];\n }\n\n if ($set == []) {\n return [];\n }\n\n\n $prefix = [array_shift($set)];\n\n $result = [];\n\n foreach (combinations_set($set, $size-1) as $suffix) {\n $result[] = array_merge($prefix, $suffix);\n }\n\n foreach (combinations_set($set, $size) as $next) {\n $result[] = $next;\n }\n\n return $result;\n}\n\nfunction combination_integer($n, $m) {\n return combinations_set(range(0, $n-1), $m);\n}\n\nassert(combination_integer(5, 3) == [\n [0, 1, 2],\n [0, 1, 3],\n [0, 1, 4],\n [0, 2, 3],\n [0, 2, 4],\n [0, 3, 4],\n [1, 2, 3],\n [1, 2, 4],\n [1, 3, 4],\n [2, 3, 4]\n]);\n\necho \"3 comb 5:\\n\";\nforeach (combination_integer(5, 3) as $combination) {\n echo implode(\", \", $combination), \"\\n\";\n}\n", "language": "PHP" }, { "code": "go =>\n % Integers 1..K\n N = 3,\n K = 5,\n printf(\"comb1(3,5): %w\\n\", comb1(N,K)),\n nl.\n\n% Recursive (numbers)\ncomb1(M,N) = comb1_(M, 1..N).\ncomb1_(0, _X) = [[]].\ncomb1_(_M, []) = [].\ncomb1_(M, [X|Xs]) = [ [X] ++ Xs2 : Xs2 in comb1_(M-1, Xs) ] ++ comb1_(M, Xs).\n", "language": "Picat" }, { "code": "comb2(K, N) = sort([[J : J in I] : I in power_set(1..N), I.length == K]).\n", "language": "Picat" }, { "code": "go3 =>\n L = \"abcde\",\n printf(\"comb3(%d,%w): %w\\n\",3,L,comb3(3,L)).\n\ncomb3(M, List) = [ [List[P[I]] : I in 1..P.length] : P in comb1(M,List.length)].\n", "language": "Picat" }, { "code": "(de comb (M Lst)\n (cond\n ((=0 M) '(NIL))\n ((not Lst))\n (T\n (conc\n (mapcar\n '((Y) (cons (car Lst) Y))\n (comb (dec M) (cdr Lst)) )\n (comb M (cdr Lst)) ) ) ) )\n\n(comb 3 (1 2 3 4 5))\n", "language": "PicoLisp" }, { "code": "define comb(n, m);\n lvars ress = [];\n define do_combs(l, m, el_lst);\n lvars i;\n if m = 0 then\n cons(rev(el_lst), ress) -> ress;\n else\n for i from l to n - m do\n do_combs(i + 1, m - 1, cons(i, el_lst));\n endfor;\n endif;\n enddefine;\n do_combs(0, m, []);\n rev(ress);\nenddefine;\n\ncomb(5, 3) ==>\n", "language": "Pop11" }, { "code": "$source = @'\n using System;\n using System.Collections.Generic;\n\n namespace Powershell\n {\n public class CSharp\n {\n public static IEnumerable<int[]> Combinations(int m, int n)\n {\n int[] result = new int[m];\n Stack<int> stack = new Stack<int>();\n stack.Push(0);\n\n while (stack.Count > 0) {\n int index = stack.Count - 1;\n int value = stack.Pop();\n\n while (value < n) {\n result[index++] = value++;\n stack.Push(value);\n if (index == m) {\n yield return result;\n break;\n }\n }\n }\n }\n }\n }\n'@\n\nAdd-Type -TypeDefinition $source -Language CSharp\n\n[Powershell.CSharp]::Combinations(3,5) | Format-Wide {$_} -Column 3 -Force\n", "language": "PowerShell" }, { "code": ":- use_module(library(clpfd)).\n\ncomb_clpfd(L, M, N) :-\n length(L, M),\n L ins 1..N,\n chain(L, #<),\n label(L).\n", "language": "Prolog" }, { "code": "comb_Prolog(L, M, N) :-\n length(L, M),\n fill(L, 1, N).\n\nfill([], _, _).\n\nfill([H | T], Min, Max) :-\n between(Min, Max, H),\n H1 is H + 1,\n fill(T, H1, Max).\n", "language": "Prolog" }, { "code": ":- use_module(library(clpfd)).\ncomb_lstcomp(N, M, V) :-\n\tV <- {L\t& length(L, N), L ins 1..M & all_distinct(L), chain(L, #<), label(L)}.\n", "language": "Prolog" }, { "code": "comb m n = comb m (0..n-1) with\n comb 0 _ = [[]];\n comb _ [] = [];\n comb m (x:xs) = [x:xs | xs = comb (m-1) xs] + comb m xs;\nend;\n\ncomb 3 5;\n", "language": "Pure" }, { "code": "Procedure.s Combinations(amount, choose)\n NewList comb.s()\n ; all possible combinations with {amount} Bits\n For a = 0 To 1 << amount\n count = 0\n ; count set bits\n For x = 0 To amount\n If (1 << x)&a\n count + 1\n EndIf\n Next\n ; if set bits are equal to combination length\n ; we generate a String representing our combination and add it to list\n If count = choose\n string$ = \"\"\n For x = 0 To amount\n If (a >> x)&1\n ; replace x by x+1 to start counting with 1\n String$ + Str(x) + \" \"\n EndIf\n Next\n AddElement(comb())\n comb() = string$\n EndIf\n Next\n ; now we sort our list and format it for output as string\n SortList(comb(), #PB_Sort_Ascending)\n ForEach comb()\n out$ + \", [ \" + comb() + \"]\"\n Next\n ProcedureReturn Mid(out$, 3)\nEndProcedure\n\nDebug Combinations(5, 3)\n", "language": "PureBasic" }, { "code": "fun combos<a>(lst :: List<a>, size :: Number) -> List<List<a>>:\n # return all subsets of lst of a certain size,\n # maintaining the original ordering of the list\n\n # Let's handle a bunch of degenerate cases up front\n # to be defensive...\n if lst.length() < size:\n # return an empty list if size is too big\n [list:]\n else if lst.length() == size:\n # combos([list: 1,2,3,4]) == list[list: 1,2,3,4]]\n [list: lst]\n else if size == 1:\n # combos(list: 5, 9]) == list[[list: 5], [list: 9]]\n lst.map(lam(elem): [list: elem] end)\n else:\n # The main resursive step here is to consider\n # all the combinations of the list that have the\n # first element (aka head) and then those that don't\n # don't.\n cases(List) lst:\n | empty => [list:]\n | link(head, rest) =>\n # All the subsets of our list either include the\n # first element of the list (aka head) or they don't.\n with-head-combos = combos(rest, size - 1).map(\n lam(combo):\n link(head, combo) end\n )\n without-head-combos = combos(rest, size)\n with-head-combos._plus(without-head-combos)\n end\n end\nwhere:\n # define semantics for the degenerate cases, although\n # maybe we should just make some of these raise errors\n combos([list:], 0) is [list: [list:]]\n combos([list:], 1) is [list:]\n combos([list: \"foo\"], 1) is [list: [list: \"foo\"]]\n combos([list: \"foo\"], 2) is [list:]\n\n # test the normal stuff\n lst = [list: 1, 2, 3]\n combos(lst, 1) is [list:\n [list: 1],\n [list: 2],\n [list: 3]\n ]\n combos(lst, 2) is [list:\n [list: 1, 2],\n [list: 1, 3],\n [list: 2, 3]\n ]\n combos(lst, 3) is [list:\n [list: 1, 2, 3]\n ]\n\n # remember the 10th row of Pascal's Triangle? :)\n lst10 = [list: 1,2,3,4,5,6,7,8,9,10]\n combos(lst10, 3).length() is 120\n combos(lst10, 4).length() is 210\n combos(lst10, 5).length() is 252\n combos(lst10, 6).length() is 210\n combos(lst10, 7).length() is 120\n\n # more sanity checks...\n for each(sublst from combos(lst10, 6)):\n sublst.length() is 6\n end\n\n for each(sublst from combos(lst10, 9)):\n sublst.length() is 9\n end\nend\n\nfun int-combos(n :: Number, m :: Number) -> List<List<Number>>:\n doc: \"return all lists of size m containing distinct, ordered nonnegative ints < n\"\n lst = range(0, n)\n combos(lst, m)\nwhere:\n int-combos(5, 5) is [list: [list: 0,1,2,3,4]]\n int-combos(3, 2) is [list:\n [list: 0, 1],\n [list: 0, 2],\n [list: 1, 2]\n ]\nend\n\nfun display-3-comb-5-for-rosetta-code():\n # The very concrete nature of this function is driven\n # by the web page from Rosetta Code. We want to display\n # output similar to the top of this page:\n #\n # https://rosettacode.org/wiki/Combinations\n results = int-combos(5, 3)\n for each(lst from results):\n print(lst.join-str(\" \"))\n end\nend\n\ndisplay-3-comb-5-for-rosetta-code()\n", "language": "Pyret" }, { "code": ">>> from itertools import combinations\n>>> list(combinations(range(5),3))\n[(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]\n", "language": "Python" }, { "code": "def comb(m, lst):\n if m == 0: return [[]]\n return [[x] + suffix for i, x in enumerate(lst)\n for suffix in comb(m - 1, lst[i + 1:])]\n", "language": "Python" }, { "code": ">>> comb(3, range(5))\n[[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]\n", "language": "Python" }, { "code": "def comb(m, s):\n if m == 0: return [[]]\n if s == []: return []\n return [s[:1] + a for a in comb(m-1, s[1:])] + comb(m, s[1:])\n\nprint comb(3, range(5))\n", "language": "Python" }, { "code": "def comb(m, s):\n if m == 1: return [[x] for x in s]\n if m == len(s): return [s]\n return [s[:1] + a for a in comb(m-1, s[1:])] + comb(m, s[1:])\n", "language": "Python" }, { "code": "SUB iterate (curr$, start, stp, depth)\n FOR i = start TO stp\n IF depth = 0 THEN PRINT curr$ + \" \" + STR$(i)\n CALL iterate(curr$ + \" \" + STR$(i), i + 1, stp, depth - 1)\n NEXT i\nEND SUB\n\nINPUT \"Enter n comb m. \", n, m\n\noutstr$ = \"\"\nCALL iterate(outstr$, 0, m - 1, n - 1)\nEND\n", "language": "QBasic" }, { "code": " [ 0 swap\n [ dup 0 != while\n dup 1 & if\n [ dip 1+ ]\n 1 >> again ]\n drop ] is bits ( n --> n )\n\n [ [] unrot\n bit times\n [ i bits\n over = if\n [ dip\n [ i join ] ] ]\n drop ] is combnums ( n n --> [ )\n\n [ [] 0 rot\n [ dup 0 != while\n dup 1 & if\n [ dip\n [ dup dip join ] ]\n dip 1+\n 1 >>\n again ]\n 2drop ] is makecomb ( n --> [ )\n\n [ over 0 = iff\n [ 2drop [] ] done\n combnums\n [] swap witheach\n [ makecomb\n nested join ] ] is comb ( n n --> [ )\n\n [ behead swap witheach max ] is largest ( [ --> n )\n\n [ 0 rot witheach\n [ [ dip [ over * ] ] + ]\n nip ] is comborder ( [ n --> n )\n\n [ dup [] != while\n sortwith\n [ 2dup join\n largest 1+ dup dip\n [ comborder swap ]\n comborder < ] ] is sortcombs ( [ --> [ )\n\n 3 5 comb\n sortcombs\n witheach [ witheach [ echo sp ] cr ]\n", "language": "Quackery" }, { "code": " [ stack ] is comb.stack\n [ stack ] is comb.items\n [ stack ] is comb.required\n [ stack ] is comb.result\n\n [ 1 - comb.items put\n 1+ comb.required put\n 0 comb.stack put\n [] comb.result put\n [ comb.required share\n comb.stack size = if\n [ comb.result take\n comb.stack behead\n drop nested join\n comb.result put ]\n comb.stack take\n dup comb.items share\n = iff\n [ drop\n comb.stack size 1 > iff\n [ 1 comb.stack tally ] ]\n else\n [ dup comb.stack put\n 1+ comb.stack put ]\n comb.stack size 1 = until ]\n comb.items release\n comb.required release\n comb.result take ] is comb ( n n --> )\n\n 3 5 comb\n witheach [ witheach [ echo sp ] cr ]\n", "language": "Quackery" }, { "code": " [ dup size dip\n [ witheach\n [ over swap peek swap ] ]\n nip pack ] is arrange ( [ [ --> [ )\n\n ' [ 10 20 30 40 50 ]\n 3 5 comb\n witheach\n [ dip dup arrange\n witheach [ echo sp ]\n cr ]\n drop\n cr\n $ \"zero one two three four\" nest$\n ' [ 4 3 1 0 1 4 3 ] arrange\n witheach [ echo$ sp ]\n", "language": "Quackery" }, { "code": "print(combn(0:4, 3))\n", "language": "R" }, { "code": "r <- combn(0:4, 3)\nfor(i in 1:choose(5,3)) print(r[,i])\n", "language": "R" }, { "code": "(define sublists\n (match-lambda**\n [(0 _) '(())]\n [(_ '()) '()]\n [(m (cons x xs)) (append (map (curry cons x) (sublists (- m 1) xs))\n (sublists m xs))]))\n\n(define (combinations n m)\n (sublists n (range m)))\n", "language": "Racket" }, { "code": ".say for combinations(5,3);\n", "language": "Raku" }, { "code": "sub combinations(Int $n, Int $k) {\n return ([],) unless $k;\n return if $k > $n || $n <= 0;\n my @c = ^$k;\n gather loop {\n take [@c];\n next if @c[$k-1]++ < $n-1;\n my $i = $k-2;\n $i-- while $i >= 0 && @c[$i] >= $n-($k-$i);\n last if $i < 0;\n @c[$i]++;\n while ++$i < $k { @c[$i] = @c[$i-1] + 1; }\n }\n}\n.say for combinations(5,3);\n", "language": "Raku" }, { "code": "/*REXX program displays combination sets for X things taken Y at a time. */\nParse Arg things size chars . /* get optional arguments from the command line */\nIf things='?' Then Do\n Say 'rexx combi things size characters'\n Say ' defaults: 5 3 123456789...'\n Say 'example rexx combi , , xyzuvw'\n Say 'size<0 shows only the number of possible combinations'\n Exit\n End\nIf things==''|things==\",\" Then things=5 /* No things specified? Then use default*/\nIf size=='' |size==\",\" Then size=3 /* No size specified? Then use default*/\nIf chars==''|chars==\",\" Then /* No chars specified? Then Use default*/\n chars='123456789abcdefghijklmnopqrstuvwxyz'||,\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'||,\n \"~!@#chars%^&*()_+`{}|[]\\:;<>?,./¦++++±==˜·\" /*some extended chars */\n\nshow_details=sign(size) /* -1: Don't show details */\nsize=abs(size)\nIf things<size Then\n Call exit 'Not enough things ('things') for size ('size').'\nSay '------------' things 'things taken' size 'times at a time:'\nSay '------------' combn(things,size) 'combinations.'\nExit /* stick a fork in it, we're all */\n/*-------------------------------------------------------------------------------*/\ncombn: Procedure Expose chars show_details\n Parse Arg things,size\n thingsp=things+1\n thingsm=thingsp-size\n index.=0\n If things=0|size=0 Then\n Return 'no'\n Do i=1 For size\n index.i=i\n End\n done=0\n Do combi=1 By 1 Until done\n combination=''\n Do d=1 To size\n combination=combination substr(chars,index.d,1)\n End\n If show_details=1 Then\n Say combination\n index.size=index.size+1\n If index.size==thingsp Then\n done=.combn(size-1)\n End\n Return combi\n/*---------------------------------------------------------------------------------*/\n.combn: Procedure Expose index. size thingsm\n Parse Arg d\n--Say '.combn' d thingsm show()\n If d==0 Then\n Return 1\n p=index.d\n Do u=d To size\n index.u=p+1\n If index.u==thingsm+u Then\n Return .combn(u-1)\n p=index.u\n End\n Return 0\n\nshow:\n list=''\n Do k=1 To size\n list=list index.k\n End\n Return list\n\nexit:\n Say '*****error*****' arg(1)\n Exit 13\n", "language": "REXX" }, { "code": "/*REXX program displays combination sets for X things taken Y at a time. */\nParse Arg things size characters\nIf things='?' Then Do\n Say 'rexx combi2 things size characters'\n Say ' defaults: 5 3 123456789...'\n Say 'example rexx combi2 , , xyzuvw'\n Say 'size<0 shows only the number of possible combinations'\n Exit\n End\nIf things==''|things==\",\" Then things=5 /* No things specified? Then use default*/\nIf size=='' |size==\",\" Then size=3 /* No size specified? Then use default*/\nNumeric Digits 20\nshow=sign(size)\nsize=abs(size)\nIf things<size Then\n Call exit 'Not enough things ('things') for size ('size').' Say '----------' things 'things taken' size 'at a time:'\nn=2**things-1\nnc=0\nDo u=1 to n\n nc=nc+combinations(u)\n End\nSay '------------' nc 'combinations.'\nExit\ncombinations: Procedure Expose things size characters show\n Parse Arg u\n nc=0\n bu=x2b(d2x(u))\n bu1=space(translate(bu,' ',0),0)\n If length(bu1)=size Then Do\n ub=reverse(bu)\n res=''\n Do i=1 To things\n If characters<>'' then\n c=substr(characters,i,1)\n Else\n c=i\n If substr(ub,i,1)=1 Then res=res c\n End\n If show=1 then\n Say res\n Return 1\n End\n Else\n Return 0\nexit:\n Say '*****error*****' arg(1)\n Exit 13\n", "language": "REXX" }, { "code": "# Project : Combinations\n\nn = 5\nk = 3\ntemp = []\ncomb = []\nnum = com(n, k)\nwhile true\n temp = []\n for n = 1 to 3\n tm = random(4) + 1\n add(temp, tm)\n next\n bool1 = (temp[1] = temp[2]) and (temp[1] = temp[3]) and (temp[2] = temp[3])\n bool2 = (temp[1] < temp[2]) and (temp[2] < temp[3])\n if not bool1 and bool2\n add(comb, temp)\n ok\n for p = 1 to len(comb) - 1\n for q = p + 1 to len(comb)\n if (comb[p][1] = comb[q][1]) and (comb[p][2] = comb[q][2]) and (comb[p][3] = comb[q][3])\n del(comb, p)\n ok\n next\n next\n if len(comb) = num\n exit\n ok\nend\ncomb = sortfirst(comb, 1)\nsee showarray(comb) + nl\n\nfunc com(n, k)\n res1 = 1\n for n1 = n - k + 1 to n\n res1 = res1 * n1\n next\n res2 = 1\n for n2 = 1 to k\n res2 = res2 * n2\n next\n res3 = res1/res2\n return res3\n\nfunc showarray(vect)\n svect = \"\"\n for nrs = 1 to len(vect)\n svect = \"[\" + vect[nrs][1] + \" \" + vect[nrs][2] + \" \" + vect[nrs][3] + \"]\" + nl\n see svect\n next\n\nFunc sortfirst(alist, ind)\n aList = sort(aList,ind)\n for n = 1 to len(alist)-1\n for m= n + 1 to len(aList)\n if alist[n][1] = alist[m][1] and alist[m][2] < alist[n][2]\n temp = alist[n]\n alist[n] = alist[m]\n alist[m] = temp\n ok\n next\n next\n for n = 1 to len(alist)-1\n for m= n + 1 to len(aList)\n if alist[n][1] = alist[m][1] and alist[n][2] = alist[m][2] and alist[m][3] < alist[n][3]\n temp = alist[n]\n alist[n] = alist[m]\n alist[m] = temp\n ok\n next\n next\n return aList\n", "language": "Ring" }, { "code": "def comb(m, n)\n (0...n).to_a.combination(m).to_a\nend\n\ncomb(3, 5) # => [[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]\n", "language": "Ruby" }, { "code": "sub iterate curr$, start, stp, depth\n for i = start to stp\n if depth = 0 then print curr$ + \" \" + str$(i)\n call iterate curr$ + \" \" + str$(i), i+1, stp, depth-1\n next i\nend sub\n\ninput \"Enter n comb m. \"; n, m\noutstr$ = \"\"\ncall iterate outstr$, 0, m-1, n-1\nend\n", "language": "Run-BASIC" }, { "code": "fn comb<T: std::fmt::Default>(arr: &[T], n: uint) {\n let mut incl_arr: ~[bool] = std::vec::from_elem(arr.len(), false);\n comb_intern(arr, n, incl_arr, 0);\n}\n\nfn comb_intern<T: std::fmt::Default>(arr: &[T], n: uint, incl_arr: &mut [bool], index: uint) {\n if (arr.len() < n + index) { return; }\n if (n == 0) {\n let mut it = arr.iter().zip(incl_arr.iter()).filter_map(|(val, incl)|\n if (*incl) { Some(val) } else { None }\n );\n for val in it { print!(\"{} \", *val); }\n print(\"\\n\");\n return;\n }\n\n incl_arr[index] = true;\n comb_intern(arr, n-1, incl_arr, index+1);\n incl_arr[index] = false;\n\n comb_intern(arr, n, incl_arr, index+1);\n}\n\nfn main() {\n let arr1 = ~[1, 2, 3, 4, 5];\n comb(arr1, 3);\n\n let arr2 = ~[\"A\", \"B\", \"C\", \"D\", \"E\"];\n comb(arr2, 3);\n}\n", "language": "Rust" }, { "code": "struct Combo<T> {\n data_len: usize,\n chunk_len: usize,\n min: usize,\n mask: usize,\n data: Vec<T>,\n}\n\nimpl<T: Clone> Combo<T> {\n fn new(chunk_len: i32, data: Vec<T>) -> Self {\n let d_len = data.len();\n let min = 2usize.pow(chunk_len as u32) - 1;\n let max = 2usize.pow(d_len as u32) - 2usize.pow((d_len - chunk_len as usize) as u32);\n\n Combo {\n data_len: d_len,\n chunk_len: chunk_len as usize,\n min: min,\n mask: max,\n data: data,\n }\n }\n\n fn get_chunk(&self) -> Vec<T> {\n let b = format!(\"{:01$b}\", self.mask, self.data_len);\n b\n .chars()\n .enumerate()\n .filter(|&(_, e)| e == '1')\n .map(|(i, _)| self.data[i].clone())\n .collect()\n }\n}\n\nimpl<T: Clone> Iterator for Combo<T> {\n type Item = Vec<T>;\n fn next(&mut self) -> Option<Self::Item> {\n while self.mask >= self.min {\n if self.mask.count_ones() == self.chunk_len as u32 {\n let res = self.get_chunk();\n self.mask -= 1;\n return Some(res);\n }\n self.mask -= 1;\n }\n None\n }\n}\n\nfn main() {\n let v1 = vec![1, 2, 3, 4, 5];\n let combo = Combo::new(3, v1);\n for c in combo.into_iter() {\n println!(\"{:?}\", c);\n }\n\n let v2 = vec!(\"A\", \"B\", \"C\", \"D\", \"E\");\n let combo = Combo::new(3, v2);\n for c in combo.into_iter() {\n println!(\"{:?}\", c);\n }\n}\n", "language": "Rust" }, { "code": "fn comb<T>(slice: &[T], k: usize) -> Vec<Vec<T>>\nwhere\n T: Copy,\n{\n // If k == 1, return a vector containing a vector for each element of the slice.\n if k == 1 {\n return slice.iter().map(|x| vec![*x]).collect::<Vec<Vec<T>>>();\n }\n // If k is exactly the slice length, return the slice inside a vector.\n if k == slice.len() {\n return vec![slice.to_vec()];\n }\n\n // Make a vector from the first element + all combinations of k - 1 elements of the rest of the slice.\n let mut result = comb(&slice[1..], k - 1)\n .into_iter()\n .map(|x| [&slice[..1], x.as_slice()].concat())\n .collect::<Vec<Vec<T>>>();\n\n // Extend this last vector with the all the combinations of k elements after from index 1 onward.\n result.extend(comb(&slice[1..], k));\n // Return final vector.\n return result;\n}\n", "language": "Rust" }, { "code": "implicit def toComb(m: Int) = new AnyRef {\n def comb(n: Int) = recurse(m, List.range(0, n))\n private def recurse(m: Int, l: List[Int]): List[List[Int]] = (m, l) match {\n case (0, _) => List(Nil)\n case (_, Nil) => Nil\n case _ => (recurse(m - 1, l.tail) map (l.head :: _)) ::: recurse(m, l.tail)\n }\n}\n", "language": "Scala" }, { "code": " def combs[A](n: Int, l: List[A]): Iterator[List[A]] = n match {\n case _ if n < 0 || l.lengthCompare(n) < 0 => Iterator.empty\n case 0 => Iterator(List.empty)\n case n => l.tails.flatMap({\n case Nil => Nil\n case x :: xs => combs(n - 1, xs).map(x :: _)\n })\n }\n", "language": "Scala" }, { "code": " def combs[A](n: Int, xs: List[A]): Stream[List[A]] =\n combsBySize(xs)(n)\n\n def combsBySize[A](xs: List[A]): Stream[Stream[List[A]]] = {\n val z: Stream[Stream[List[A]]] = Stream(Stream(List())) ++ Stream.continually(Stream.empty)\n xs.toStream.foldRight(z)((a, b) => zipWith[Stream[List[A]]](_ ++ _, f(a, b), b))\n }\n\n def zipWith[A](f: (A, A) => A, as: Stream[A], bs: Stream[A]): Stream[A] = (as, bs) match {\n case (Stream.Empty, _) => Stream.Empty\n case (_, Stream.Empty) => Stream.Empty\n case (a #:: as, b #:: bs) => f(a, b) #:: zipWith(f, as, bs)\n }\n\n def f[A](x: A, xsss: Stream[Stream[List[A]]]): Stream[Stream[List[A]]] =\n Stream.empty #:: xsss.map(_.map(x :: _))\n", "language": "Scala" }, { "code": "scala>(0 to 4).combinations(3).toList\nres0: List[scala.collection.immutable.IndexedSeq[Int]] = List(Vector(0, 1, 2), Vector(0, 1, 3), Vector(0, 1, 4), Vector(0, 2, 3), Vector(0, 2, 4), Vector(0, 3, 4), Vector(1, 2, 3), Vector(1, 2, 4), Vector(1, 3, 4), Vector(2, 3, 4))\n", "language": "Scala" }, { "code": "(define (comb m lst)\n (cond ((= m 0) '(()))\n ((null? lst) '())\n (else (append (map (lambda (y) (cons (car lst) y))\n (comb (- m 1) (cdr lst)))\n (comb m (cdr lst))))))\n\n(comb 3 '(0 1 2 3 4))\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst type: combinations is array array integer;\n\nconst func combinations: comb (in array integer: arr, in integer: k) is func\n result\n var combinations: combResult is combinations.value;\n local\n var integer: x is 0;\n var integer: i is 0;\n var array integer: suffix is 0 times 0;\n begin\n if k = 0 then\n combResult := 1 times 0 times 0;\n else\n for x key i range arr do\n for suffix range comb(arr[succ(i) ..], pred(k)) do\n combResult &:= [] (x) & suffix;\n end for;\n end for;\n end if;\n end func;\n\nconst proc: main is func\n local\n var array integer: aCombination is 0 times 0;\n var integer: element is 0;\n begin\n for aCombination range comb([] (0, 1, 2, 3, 4), 3) do\n for element range aCombination do\n write(element lpad 3);\n end for;\n writeln;\n end for;\n end func;\n", "language": "Seed7" }, { "code": "print({0..4} npow 3);\n", "language": "SETL" }, { "code": "combinations(5, 3, {|*c| say c })\n", "language": "Sidef" }, { "code": "func combine(n, set) {\n\n set.len || return []\n n == 1 && return set.map{[_]}\n\n var (head, result)\n head = set.shift\n result = combine(n-1, [set...])\n\n for subarray in result {\n subarray.prepend(head)\n }\n\n result + combine(n, set)\n}\n\ncombine(3, @^5).each {|c| say c }\n", "language": "Sidef" }, { "code": "func forcomb(callback, n, k) {\n\n if (k == 0) {\n callback([])\n return()\n }\n\n if (k<0 || k>n || n==0) {\n return()\n }\n\n var c = @^k\n\n loop {\n callback([c...])\n c[k-1]++ < n-1 && next\n var i = k-2\n while (i>=0 && c[i]>=(n-(k-i))) {\n --i\n }\n i < 0 && break\n c[i]++\n while (++i < k) {\n c[i] = c[i-1]+1\n }\n }\n\n return()\n}\n\nforcomb({|c| say c }, 5, 3)\n", "language": "Sidef" }, { "code": "(0 to: 4) combinations: 3 atATimeDo: [ :x | Transcript cr; show: x printString].\n\n\"output on Transcript:\n#(0 1 2)\n#(0 1 3)\n#(0 1 4)\n#(0 2 3)\n#(0 2 4)\n#(0 3 4)\n#(1 2 3)\n#(1 2 4)\n#(1 3 4)\n#(2 3 4)\"\n", "language": "Smalltalk" }, { "code": "[reverse subSet(5,3,i)$SGCF for i in 0..binomial(5,3)-1]\n\n [[0,1,2], [0,1,3], [0,2,3], [1,2,3], [0,1,4], [0,2,4], [1,2,4], [0,3,4],\n [1,3,4], [2,3,4]]\n Type: List(List(Integer))\n", "language": "SPAD" }, { "code": "#!/usr/local/bin/spar\npragma annotate( summary, \"combinations\" )\n @( description, \"Given non-negative integers m and n, generate all size m\" )\n @( description, \"combinations of the integers from 0 to n-1 in sorted\" )\n @( description, \"order (each combination is sorted and the entire table\" )\n @( description, \"is sorted\" )\n @( see_also, \"http://rosettacode.org/wiki/Combinations\" )\n @( author, \"Ken O. Burtch\" );\n\npragma restriction( no_external_commands );\n\nprocedure combinations is\n number_of_items : constant natural := 3;\n max_item_value : constant natural := 5;\n\n -- get_first_combination\n -- return the first combination (e.g. 0,1,2 for 3 items)\n\n function get_first_combination return string is\n c : string;\n begin\n for i in 1..number_of_items loop\n c := @ & strings.image( natural( i-1 ) );\n end loop;\n return c;\n end get_first_combination;\n\n -- get_last_combination\n -- return the highest value (e.g. 4,4,4 for 3 items\n -- with a maximum value of 5).\n\n function get_last_combination return string is\n c : string;\n begin\n for i in 1..number_of_items loop\n c := @ & strings.image( max_item_value-1 );\n end loop;\n return c;\n end get_last_combination;\n\n combination : string := get_first_combination;\n last_combination : constant string := get_last_combination;\n\n item : natural; -- a number from the combination\n bad : boolean; -- true if we know a value is too big\n s : string; -- a temp string for deleting leading space\n\nbegin\n put_line( combination );\n while combination /= last_combination loop\n\n -- the combination is 3 numbers with leading spaces\n -- so the field positions start at 2 (1 is a null string)\n\n for i in reverse 1..number_of_items loop\n item := numerics.value( strings.field( combination, i+1, ' ') );\n if item < max_item_value-1 then\n item := @+1;\n s := strings.image( item );\n s := strings.delete( s, 1, 1 );\n strings.replace( combination, i+1, s, ' ' );\n bad := false;\n for j in i+1..number_of_items loop\n item := numerics.value( strings.field( combination, j, ' ') );\n if item < max_item_value-1 then\n item := @+1;\n s := strings.image( item );\n s := strings.delete( s, 1, 1 );\n strings.replace( combination, j+1, s, ' ' );\n else\n bad;\n end if;\n end loop;\n exit;\n end if;\n end loop;\n if not bad then\n put_line( combination );\n end if;\n end loop;\nend combinations;\n", "language": "SparForte" }, { "code": "fun comb (0, _ ) = [[]]\n | comb (_, [] ) = []\n | comb (m, x::xs) = map (fn y => x :: y) (comb (m-1, xs)) @\n comb (m, xs)\n;\ncomb (3, [0,1,2,3,4]);\n", "language": "Standard-ML" }, { "code": "program combin\ntempfile cp\ntempvar k\ngen `k'=1\nquietly save \"`cp'\"\nrename `1' `1'1\nforv i=2/`2' {\n\tjoinby `k' using \"`cp'\"\n\trename `1' `1'`i'\n\tquietly drop if `1'`i'<=`1'`=`i'-1'\n}\nsort `1'*\nend\n", "language": "Stata" }, { "code": ". set obs 5\n. gen a=_n\n. combin a 3\n. list\n\n +--------------+\n | a1 a2 a3 |\n |--------------|\n 1. | 1 2 3 |\n 2. | 1 2 4 |\n 3. | 1 2 5 |\n 4. | 1 3 4 |\n 5. | 1 3 5 |\n |--------------|\n 6. | 1 4 5 |\n 7. | 2 3 4 |\n 8. | 2 3 5 |\n 9. | 2 4 5 |\n 10. | 3 4 5 |\n +--------------+\n", "language": "Stata" }, { "code": "function combinations(n,k) {\n\ta = J(comb(n,k),k,.)\n\tu = 1..k\n\tfor (i=1; 1; i++) {\n\t\ta[i,.] = u\n\t\tfor (j=k; j>0; j--) {\n\t\t\tif (u[j]-j<n-k) break\n\t\t}\n\t\tif (j<1) return(a)\n\t\tu[j..k] = u[j]+1..u[j]+1+k-j\n\t}\n}\n\ncombinations(5,3)\n", "language": "Stata" }, { "code": "func addCombo(prevCombo: [Int], var pivotList: [Int]) -> [([Int], [Int])] {\n\n return (0..<pivotList.count)\n .map {\n _ -> ([Int], [Int]) in\n (prevCombo + [pivotList.removeAtIndex(0)], pivotList)\n }\n}\nfunc combosOfLength(n: Int, m: Int) -> [[Int]] {\n\n return [Int](1...m)\n .reduce([([Int](), [Int](0..<n))]) {\n (accum, _) in\n accum.flatMap(addCombo)\n }.map {\n $0.0\n }\n}\n\nprintln(combosOfLength(5, 3))\n", "language": "Swift" }, { "code": "proc comb {m n} {\n set set [list]\n for {set i 0} {$i < $n} {incr i} {lappend set $i}\n return [combinations $set $m]\n}\nproc combinations {list size} {\n if {$size == 0} {\n return [list [list]]\n }\n set retval {}\n for {set i 0} {($i + $size) <= [llength $list]} {incr i} {\n set firstElement [lindex $list $i]\n set remainingElements [lrange $list [expr {$i + 1}] end]\n foreach subset [combinations $remainingElements [expr {$size - 1}]] {\n lappend retval [linsert $subset 0 $firstElement]\n }\n }\n return $retval\n}\n\ncomb 3 5 ;# ==> {0 1 2} {0 1 3} {0 1 4} {0 2 3} {0 2 4} {0 3 4} {1 2 3} {1 2 4} {1 3 4} {2 3 4}\n", "language": "Tcl" }, { "code": "(defun comb-n-m (n m)\n (comb (range* 0 n) m))\n\n(put-line `3 comb 5 = @(comb-n-m 5 3)`)\n", "language": "TXR" }, { "code": "choices = ^(iota@r,~&l); leql@a^& ~&al?\\&! ~&arh2fabt2RDfalrtPXPRT\n", "language": "Ursala" }, { "code": "#import std\n#import nat\n\ncombinations = @rlX choices^|(iota,~&); -< @p nleq+ ==-~rh\n", "language": "Ursala" }, { "code": "#cast %nLL\n\nexample = combinations(3,5)\n", "language": "Ursala" }, { "code": "[comb [m lst] let\n [ [m zero?] [[[]]]\n [lst null?] [[]]\n [true] [m pred lst rest comb [lst first swap cons] map\n m lst rest comb concat]\n ] when].\n", "language": "V" }, { "code": "[comb\n [ [pop zero?] [pop pop [[]]]\n [null?] [pop pop []]\n [true] [ [m lst : [m pred lst rest comb [lst first swap cons] map\n m lst rest comb concat]] view i ]\n ] when].\n", "language": "V" }, { "code": "[comb\n [2dup [a b : a b a b] view].\n [2pop pop pop].\n\n [ [pop zero?] [2pop [[]]]\n [null?] [2pop []]\n [true] [2dup [pred] dip uncons swapd comb [cons] map popd rollup rest comb concat]\n ] when].\n", "language": "V" }, { "code": "Option Explicit\nOption Base 0\n'Option Base 1\n\nPrivate ArrResult\n\nSub test()\n 'compute\n Main_Combine 5, 3\n\n 'return\n Dim j As Long, i As Long, temp As String\n For i = LBound(ArrResult, 1) To UBound(ArrResult, 1)\n temp = vbNullString\n For j = LBound(ArrResult, 2) To UBound(ArrResult, 2)\n temp = temp & \" \" & ArrResult(i, j)\n Next\n Debug.Print temp\n Next\n Erase ArrResult\nEnd Sub\n\nPrivate Sub Main_Combine(M As Long, N As Long)\nDim MyArr, i As Long\n ReDim MyArr(M - 1)\n If LBound(MyArr) > 0 Then ReDim MyArr(M) 'Case Option Base 1\n For i = LBound(MyArr) To UBound(MyArr)\n MyArr(i) = i\n Next i\n i = IIf(LBound(MyArr) > 0, N, N - 1)\n ReDim ArrResult(i, LBound(MyArr))\n Combine MyArr, N, LBound(MyArr), LBound(MyArr)\n ReDim Preserve ArrResult(UBound(ArrResult, 1), UBound(ArrResult, 2) - 1)\n 'In VBA Excel we can use Application.Transpose instead of personal Function Transposition\n ArrResult = Transposition(ArrResult)\nEnd Sub\n\nPrivate Sub Combine(MyArr As Variant, Nb As Long, Deb As Long, Ind As Long)\nDim i As Long, j As Long, N As Long\n For i = Deb To UBound(MyArr, 1)\n ArrResult(Ind, UBound(ArrResult, 2)) = MyArr(i)\n N = IIf(LBound(ArrResult, 1) = 0, Nb - 1, Nb)\n If Ind = N Then\n ReDim Preserve ArrResult(UBound(ArrResult, 1), UBound(ArrResult, 2) + 1)\n For j = LBound(ArrResult, 1) To UBound(ArrResult, 1)\n ArrResult(j, UBound(ArrResult, 2)) = ArrResult(j, UBound(ArrResult, 2) - 1)\n Next j\n Else\n Call Combine(MyArr, Nb, i + 1, Ind + 1)\n End If\n Next i\nEnd Sub\n\nPrivate Function Transposition(ByRef MyArr As Variant) As Variant\nDim T, i As Long, j As Long\n ReDim T(LBound(MyArr, 2) To UBound(MyArr, 2), LBound(MyArr, 1) To UBound(MyArr, 1))\n For i = LBound(MyArr, 1) To UBound(MyArr, 1)\n For j = LBound(MyArr, 2) To UBound(MyArr, 2)\n T(j, i) = MyArr(i, j)\n Next j\n Next i\n Transposition = T\n Erase T\nEnd Function\n", "language": "VBA" }, { "code": "Private Sub comb(ByVal pool As Integer, ByVal needed As Integer, Optional ByVal done As Integer = 0, Optional ByVal chosen As Variant)\n If needed = 0 Then '-- got a full set\n For Each x In chosen: Debug.Print x;: Next x\n Debug.Print\n Exit Sub\n End If\n If done + needed > pool Then Exit Sub '-- cannot fulfil\n '-- get all combinations with and without the next item:\n done = done + 1\n Dim tmp As Variant\n tmp = chosen\n If IsMissing(chosen) Then\n ReDim tmp(1)\n Else\n ReDim Preserve tmp(UBound(chosen) + 1)\n End If\n tmp(UBound(tmp)) = done\n comb pool, needed - 1, done, tmp\n comb pool, needed, done, chosen\nEnd Sub\n\nPublic Sub main()\n comb 5, 3\nEnd Sub\n", "language": "VBA" }, { "code": "Function Dec2Bin(n)\n\tq = n\n\tDec2Bin = \"\"\n\tDo Until q = 0\n\t\tDec2Bin = CStr(q Mod 2) & Dec2Bin\n\t\tq = Int(q / 2)\n\tLoop\n\tDec2Bin = Right(\"00000\" & Dec2Bin,6)\nEnd Function\n\nSub Combination(n,k)\n\tDim arr()\n\tReDim arr(n-1)\n\tFor h = 0 To n-1\n\t\tarr(h) = h + 1\n\tNext\n\tSet list = CreateObject(\"System.Collections.Arraylist\")\n\tFor i = 1 To 2^n\n\t\tbin = Dec2Bin(i)\n\t\tc = 0\n\t\ttmp_combo = \"\"\n\t\tIf Len(Replace(bin,\"0\",\"\")) = k Then\n\t\t\tFor j = Len(bin) To 1 Step -1\n\t\t\t\tIf CInt(Mid(bin,j,1)) = 1 Then\n\t\t\t\t\ttmp_combo = tmp_combo & arr(c) & \",\"\n\t\t\t\tEnd If\n\t\t\t\tc = c + 1\n\t\t\tNext\n\t\t\tlist.Add Mid(tmp_combo,1,(k*2)-1)\n\t\tEnd If\n\tNext\n\tlist.Sort\n\tFor l = 0 To list.Count-1\n\t\tWScript.StdOut.Write list(l)\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Sub\n\n'Testing with n = 5 / k = 3\nCall Combination(5,3)\n", "language": "VBScript" }, { "code": "import \"./perm\" for Comb\n\nvar fib = Fiber.new { Comb.generate((0..4).toList, 3) }\nwhile (true) {\n var c = fib.call()\n if (!c) return\n System.print(c)\n}\n", "language": "Wren" }, { "code": "PROGRAM\t\"Combinations\"\nVERSION\t\"0.0000\"\n\nDECLARE FUNCTION Entry ()\nDECLARE FUNCTION iterate (curr$, start, stp, depth)\n\nFUNCTION Entry ()\nn = 3\nm = 5\noutstr$ = \"\"\niterate(outstr$, 0, m - 1, n - 1)\n\nEND FUNCTION\n\nFUNCTION iterate (curr$, start, stp, depth)\n FOR i = start TO stp\n IF depth = 0 THEN PRINT curr$ + \" \" + STR$(i)\n iterate(curr$ + \" \" + STR$(i), i + 1, stp, depth - 1)\n NEXT i\n RETURN\nEND FUNCTION\nEND PROGRAM\n", "language": "XBasic" }, { "code": "code ChOut=8, CrLf=9, IntOut=11;\ndef M=3, N=5;\nint A(N-1);\n\nproc Combos(D, S); \\Display all size M combinations of N in sorted order\nint D, S; \\depth of recursion, starting value of N\nint I;\n[if D<M then \\depth < size\n for I:= S to N-1 do\n [A(D):= I;\n Combos(D+1, I+1);\n ]\nelse [for I:= 0 to M-1 do\n [IntOut(0, A(I)); ChOut(0, ^ )];\n CrLf(0);\n ];\n];\n\nCombos(0, 0)\n", "language": "XPL0" }, { "code": "fcn comb(k,seq){\t// no repeats, seq is finite\n seq=seq.makeReadOnly();\t// because I append to parts of seq\n fcn(k,seq){\n if(k<=0) return(T(T));\n if(not seq) return(T);\n self.fcn(k-1,seq[1,*]).pump(List,seq[0,1].extend)\n\t .extend(self.fcn(k,seq[1,*]));\n }(k,seq);\n}\n", "language": "Zkl" }, { "code": "comb(3,\"abcde\".split(\"\")).apply(\"concat\")\n", "language": "Zkl" } ]
Combinations
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Combinations_and_permutations\nnote: Probability and statistics\n", "language": "00-META" }, { "code": ";Task:\nImplement the [[wp:Combination|combination]] &nbsp; <big> (<sup>n</sup>C<sub>k</sub>) </big> &nbsp; and [[wp:Permutation|permutation]] &nbsp; <big> (<sup>n</sup>P<sub>k</sub>) </big> &nbsp; operators in the target language:\n\n:::* <math>^n\\operatorname C_k =\\binom nk = \\frac{n(n-1)\\ldots(n-k+1)}{k(k-1)\\dots1} </math>\n\n:::* <math>^n\\operatorname P_k = n\\cdot(n-1)\\cdot(n-2)\\cdots(n-k+1)</math>\n\n<br>\nSee the Wikipedia articles for a more detailed description.\n\n'''To test''', generate and print examples of:\n* &nbsp; A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.\n* &nbsp; A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic.<br> This 'floating point' code could be implemented using an approximation, e.g., by calling the [[Gamma function]].\n\n\n;Related task:\n* &nbsp; [[Evaluate binomial coefficients]]\n\n{{Template:Combinations and permutations}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F perm(=n, p)\n BigInt r = 1\n V k = n - p\n L n > k\n r *= n--\n R r\n\nF comb(n, =k)\n V r = perm(n, k)\n L k > 0\n r I/= k--\n R r\n\nL(i) 1..11\n print(‘P(12,’i‘) = ’perm(12, i))\nL(i) (10.<60).step(10)\n print(‘C(60,’i‘) = ’comb(60, i))\n", "language": "11l" }, { "code": "# -*- coding: utf-8 -*- #\n\nCOMMENT REQUIRED by \"prelude_combinations_and_permutations.a68\" CO\n MODE CPINT = #LONG# ~;\n MODE CPOUT = #LONG# ~; # the answer, can be REAL #\n MODE CPREAL = ~; # the answer, can be REAL #\n PROC cp fix value error = (#REF# CPARGS args)BOOL: ~;\n#PROVIDES:#\n# OP C = (CP~,CP~)CP~: ~ #\n# OP P = (CP~,CP~)CP~: ~ #\nEND COMMENT\n\nMODE CPARGS = STRUCT(CHAR name, #REF# CPINT n,k);\n\nPRIO C = 8, P = 8; # should be 7.5, a priority between *,/ and **,SHL,SHR etc #\n\n# I suspect there is a more reliable way of doing this using the Gamma Function approx #\n\nOP P = (CPINT n, r)CPOUT: (\n IF n < r ORF r < 0 THEN IF NOT cp fix value error(CPARGS(\"P\",n,r)) THEN stop FI FI;\n CPOUT out := 1;\n# basically nPk = (n-r+1)(n-r+2)...(n-2)(n-1)n = n!/(n-r)! #\n FOR i FROM n-r+1 TO n DO out *:= i OD;\n out\n);\n\nOP P = (CPREAL n, r)CPREAL: # 'ln gamma' requires GSL library #\n exp(ln gamma(n+1)-ln gamma(n-r+1));\n\n# basically nPk = (n-r+1)(n-r+2)...(n-2)(n-1)n = n!/(n-r)! #\nCOMMENT # alternate slower version #\nOP P = (CPREAL n, r)CPREAL: ( # alternate slower version #\n IF n < r ORF r < 0 THEN IF NOT cp fix value error(CPARGS(\"P\",ENTIER n,ENTIER r)) THEN stop FI FI;\n CPREAL out := 1;\n# basically nPk = (n-r+1)(n-r+2)...(n-2)(n-1)n = n!/(n-r)! #\n CPREAL i := n-r+1;\n WHILE i <= n DO\n out*:= i;\n# a crude check for underflow #\n IF i = i + 1 THEN IF NOT cp fix value error(CPARGS(\"P\",ENTIER n,ENTIER r)) THEN stop FI FI;\n i+:=1\n OD;\n out\n);\nEND COMMENT\n\n# basically C(n,r) = nCk = nPk/r! = n!/(n-r)!/r! #\nOP C = (CPINT n, r)CPOUT: (\n IF n < r ORF r < 0 THEN IF NOT cp fix value error((\"C\",n,r)) THEN stop FI FI;\n CPINT largest = ( r > n - r | r | n - r );\n CPINT smallest = n - largest;\n CPOUT out := 1;\n INT smaller fact := 2;\n FOR larger fact FROM largest+1 TO n DO\n# try and prevent overflow, p.s. there must be a smarter way to do this #\n# Problems: loop stalls when 'smaller fact' is a largeish co prime #\n out *:= larger fact;\n WHILE smaller fact <= smallest ANDF out MOD smaller fact = 0 DO\n out OVERAB smaller fact;\n smaller fact +:= 1\n OD\n OD;\n out # EXIT with: n P r OVER r P r #\n);\n\nOP C = (CPREAL n, CPREAL r)CPREAL: # 'ln gamma' requires GSL library #\n exp(ln gamma(n+1)-ln gamma(n-r+1)-ln gamma(r+1));\n\n# basically C(n,r) = nCk = nPk/r! = n!/(n-r)!/r! #\nCOMMENT # alternate slower version #\nOP C = (CPREAL n, REAL r)CPREAL: (\n IF n < r ORF r < 0 THEN IF NOT cp fix value error((\"C\",ENTIER n,ENTIER r)) THEN stop FI FI;\n CPREAL largest = ( r > n - r | r | n - r );\n CPREAL smallest = n - largest;\n CPREAL out := 1;\n REAL smaller fact := 2;\n REAL larger fact := largest+1;\n WHILE larger fact <= n DO # todo: check underflow here #\n# try and prevent overflow, p.s. there must be a smarter way to do this #\n out *:= larger fact;\n WHILE smaller fact <= smallest ANDF out > smaller fact DO\n out /:= smaller fact;\n smaller fact +:= 1\n OD;\n larger fact +:= 1\n OD;\n out # EXIT with: n P r OVER r P r #\n);\nEND COMMENT\n\nSKIP\n", "language": "ALGOL-68" }, { "code": "#!/usr/bin/a68g --script #\n# -*- coding: utf-8 -*- #\n\nCO REQUIRED by \"prelude_combinations_and_permutations.a68\" CO\n MODE CPINT = #LONG# INT;\n MODE CPOUT = #LONG# INT; # the answer, can be REAL #\n MODE CPREAL = REAL; # the answer, can be REAL #\n PROC cp fix value error = (#REF# CPARGS args)BOOL: (\n putf(stand error, ($\"Value error: \"g(0)gg(0)\"arg out of range\"l$,\n n OF args, name OF args, k OF args));\n FALSE # unfixable #\n );\n#PROVIDES:#\n# OP C = (CP~,CP~)CP~: ~ #\n# OP P = (CP~,CP~)CP~: ~ #\nPR READ \"prelude_combinations_and_permutations.a68\" PR;\n\nprintf($\"A sample of Permutations from 1 to 12:\"l$);\nFOR i FROM 4 BY 1 TO 12 DO\n INT first = i - 2,\n second = i - ENTIER sqrt(i);\n printf(($g(0)\" P \"g(0)\" = \"g(0)$, i, first, i P first, $\", \"$));\n printf(($g(0)\" P \"g(0)\" = \"g(0)$, i, second, i P second, $l$))\nOD;\n\nprintf($l\"A sample of Combinations from 10 to 60:\"l$);\nFOR i FROM 10 BY 10 TO 60 DO\n INT first = i - 2,\n second = i - ENTIER sqrt(i);\n printf(($\"(\"g(0)\" C \"g(0)\") = \"g(0)$, i, first, i C first, $\", \"$));\n printf(($\"(\"g(0)\" C \"g(0)\") = \"g(0)$, i, second, i C second, $l$))\nOD;\n\nprintf($l\"A sample of Permutations from 5 to 15000:\"l$);\nFOR i FROM 5 BY 10 TO 150 DO\n REAL r = i,\n first = r - 2,\n second = r - ENTIER sqrt(r);\n printf(($g(0)\" P \"g(0)\" = \"g(-real width,real width-5,-1)$, r, first, r P first, $\", \"$));\n printf(($g(0)\" P \"g(0)\" = \"g(-real width,real width-5,-1)$, r, second, r P second, $l$))\nOD;\n\nprintf($l\"A sample of Combinations from 10 to 190:\"l$);\nFOR i FROM 100 BY 100 TO 1000 DO\n REAL r = i,\n first = r - 2,\n second = r - ENTIER sqrt(r);\n printf(($\"(\"g(0)\" C \"g(0)\") = \"g(0,1)$, r, first, r C first, $\", \"$));\n printf(($\"(\"g(0)\" C \"g(0)\") = \"g(0,1)$, r, second, r C second, $l$))\nOD\n", "language": "ALGOL-68" }, { "code": "printPermutations: function [s,b][\n print [\n \"P(\" ++ (to :string s) ++ \", \" ++ (to :string b) ++ \") = \"\n permutate.count.by:b @1..s\n ]\n]\n\nprintCombinations: function [s,b][\n print [\n \"C(\" ++ (to :string s) ++ \", \" ++ (to :string b) ++ \") = \"\n combine.count.by:b @1..s\n ]\n]\n\nprintPermutations 4 2\nprintPermutations 5 3\nprintPermutations 6 4\nprintPermutations 7 5\nprintPermutations 8 6\nprintPermutations 9 7\nprintPermutations 10 8\nprintPermutations 11 9\nprintPermutations 12 10\n\nprintCombinations 10 8\nprintCombinations 20 18\nprintCombinations 30 28\nprintCombinations 40 38\nprintCombinations 50 48\nprintCombinations 60 58\n\nprintPermutations 340 230\nprintPermutations 12503 150\n\nprintCombinations 180 40\nprintCombinations 970 730\n", "language": "Arturo" }, { "code": " ( C\n = n k coef\n . !arg:(?n,?k)\n & (!n+-1*!k:<!k:?k|)\n & 1:?coef\n & whl\n ' ( !k:>0\n & !coef*!n*!k^-1:?coef\n & !k+-1:?k\n & !n+-1:?n\n )\n & !coef\n )\n& ( compileBinomialFunctionThatDoesFloatingPointCalculations\n =\n . new\n $ ( UFP\n ,\n ' ( (s.n) (s.k)\n . \"**************************************************************\n *** Notice the difference between the following four lines ***\n *** of code and the much shorter (!n+-1*!k:<!k:?k|) in ***\n *** function C above. UFP grammar is simpler than usual ***\n *** Bracmat grammar. UFP code is therefore less terse. ***\n **************************************************************\"\n & !n+-1*!k:?n-k\n & ( !n-k:<!k&!n-k:?k\n |\n )\n & 1:?coef\n & whl\n ' ( !k:>0\n & !coef*!n*!k^-1:?coef\n & !k+-1:?k\n & !n+-1:?n\n )\n & !coef\n )\n )\n )\n& compileBinomialFunctionThatDoesFloatingPointCalculations$\n : ?binom\n& ( P\n = n k result\n . !arg:(?n,?k)\n & !n+-1*!k:?k\n & 1:?result\n & whl\n ' ( !n:>!k\n & !n*!result:?result\n & !n+-1:?n\n )\n & !result\n )\n& ( compilePermutationFunctionThatDoesFloatingPointCalculations\n =\n . new\n $ ( UFP\n ,\n ' ( (s.n) (s.k)\n . !n+-1*!k:?k\n & 1:?result\n & whl\n ' ( !n:>!k\n & !n*!result:?result\n & !n+-1:?n\n )\n & !result\n )\n )\n )\n& compilePermutationFunctionThatDoesFloatingPointCalculations$\n : ?permu\n& 0:?i\n& whl\n ' ( 1+!i:~>12:?i\n & div$(!i.3):?k\n & out$(!i P !k \"=\" P$(!i,!k))\n )\n& 0:?i\n& whl\n ' ( 10+!i:~>60:?i\n & div$(!i.3):?k\n & out$(!i Cn !k \"= \" C$(!i,!k))\n & out$(!i Cf !k \"=\" (binom..go)$(!i,!k))\n )\n& ( displayBig\n =\n . @(!arg:?show [50 ? [?length)\n & !show \"... (\" !length+-50 \" more digits)\"\n | !arg\n )\n& 5 50 500 1000 5000 15000:?is\n& whl\n ' ( !is:%?i ?is\n & div$(!i.3):?k\n & out\n $ ( str\n $ (!i \" Pn \" !k \" = \" displayBig$(P$(!i,!k)))\n )\n & out\n $ ( str\n $ (!i \" Pf \" !k \" = \" (permu..go)$(!i,!k))\n )\n )\n& 0:?i\n& whl\n ' ( 100+!i:~>1000:?i\n & div$(!i.3):?k\n & out\n $ ( str\n $ (!i \" Cn \" !k \" = \" displayBig$(C$(!i,!k)))\n )\n & out\n $ ( str\n $ (!i \" Cf \" !k \" = \" (binom..go)$(!i,!k))\n )\n )\n& all done;\n", "language": "Bracmat" }, { "code": "#include <gmp.h>\n\nvoid perm(mpz_t out, int n, int k)\n{\n\tmpz_set_ui(out, 1);\n\tk = n - k;\n\twhile (n > k) mpz_mul_ui(out, out, n--);\n}\n\nvoid comb(mpz_t out, int n, int k)\n{\n\tperm(out, n, k);\n\twhile (k) mpz_divexact_ui(out, out, k--);\n}\n\nint main(void)\n{\n\tmpz_t x;\n\tmpz_init(x);\n\n\tperm(x, 1000, 969);\n\tgmp_printf(\"P(1000,969) = %Zd\\n\", x);\n\n\tcomb(x, 1000, 969);\n\tgmp_printf(\"C(1000,969) = %Zd\\n\", x);\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n\nusing namespace boost::multiprecision;\n\nmpz_int p(uint n, uint p) {\n mpz_int r = 1;\n mpz_int k = n - p;\n while (n > k)\n r *= n--;\n return r;\n}\n\nmpz_int c(uint n, uint k) {\n mpz_int r = p(n, k);\n while (k)\n r /= k--;\n return r;\n}\n\nint main() {\n for (uint i = 1u; i < 12u; i++)\n std::cout << \"P(12,\" << i << \") = \" << p(12u, i) << std::endl;\n for (uint i = 10u; i < 60u; i += 10u)\n std::cout << \"C(60,\" << i << \") = \" << c(60u, i) << std::endl;\n\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Numerics;\n\nclass CombinationsAndPermutations\n{\n\tpublic static void Main(string[] args)\n\t{\n\t\tConsole.WriteLine(double.MaxValue);\n\t\tConsole.WriteLine(\"A sample of permutations from 1 to 12 with exact Integer arithmetic:\");\n\t\tfor (int n = 1; n <= 12; n++)\n\t\t{\n\t\t\tint k = n / 2;\n\t\t\tConsole.WriteLine($\"{n} P {k} = {Permutation(n, k)}\");\n\t\t}\n\n\t\tConsole.WriteLine();\n\t\tConsole.WriteLine(\"A sample of combinations from 10 to 60 with exact Integer arithmetic:\");\n\t\tfor (int n = 10; n <= 60; n += 5)\n\t\t{\n\t\t\tint k = n / 2;\n\t\t\tConsole.WriteLine($\"{n} C {k} = {Combination(n, k)}\");\n\t\t}\n\n\t\tConsole.WriteLine();\n\t\tConsole.WriteLine(\"A sample of permutations from 5 to 15000 displayed in floating point arithmetic:\");\n\t\tConsole.WriteLine($\"{5} P {2} = {Display(Permutation(5, 2), 50)}\");\n\t\tfor (int n = 1000; n <= 15000; n += 1000)\n\t\t{\n\t\t\tint k = n / 2;\n\t\t\tConsole.WriteLine($\"{n} P {k} = {Display(Permutation(n, k), 50)}\");\n\t\t}\n\n\t\tConsole.WriteLine();\n\t\tConsole.WriteLine(\"A sample of combinations from 100 to 1000 displayed in floating point arithmetic:\");\n\t\tfor (int n = 100; n <= 1000; n += 100)\n\t\t{\n\t\t\tint k = n / 2;\n\t\t\tConsole.WriteLine($\"{n} C {k} = {Display(Combination(n, k), 50)}\");\n\t\t}\n\t}\n\n\tprivate static string Display(BigInteger val, int precision)\n\t{\n\t\tstring s = val.ToString();\n\t\t// Ensure that we don't try to take a substring longer than what's available.\n\t\tint actualPrecision = Math.Min(precision, s.Length - 1); // Adjusted to ensure it doesn't exceed string length\n\t\tSystem.Text.StringBuilder sb = new System.Text.StringBuilder();\n\t\tif (s.Length > 1) // Check if the string has more than one character\n\t\t{\n\t\t\tsb.Append(s.Substring(0, 1));\n\t\t\tsb.Append(\".\");\n\t\t\tsb.Append(s.Substring(1, actualPrecision-1));\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// If the string is only one digit, no need to insert a decimal point.\n\t\t\tsb.Append(s);\n\t\t}\n\n\t\tsb.Append(\" * 10^\");\n\t\tsb.Append(s.Length - 1);\n\t\treturn sb.ToString();\n\t}\n\n\tpublic static BigInteger Combination(int n, int k)\n\t{\n\t\t// Select value with smallest intermediate results\n\t\t// combination(n, k) = combination(n, n-k)\n\t\tif (n - k < k)\n\t\t{\n\t\t\tk = n - k;\n\t\t}\n\n\t\tBigInteger result = Permutation(n, k);\n\t\twhile (k > 0)\n\t\t{\n\t\t\tresult = result / k;\n\t\t\tk--;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tpublic static BigInteger Permutation(int n, int k)\n\t{\n\t\tBigInteger result = BigInteger.One;\n\t\tfor (int i = n; i >= n - k + 1; i--)\n\t\t{\n\t\t\tresult = result * i;\n\t\t}\n\n\t\treturn result;\n\t}\n}\n", "language": "C-sharp" }, { "code": "(defun combinations (n k)\n (cond ((or (< n k) (< k 0) (< n 0)) 0)\n\t((= k 0) 1)\n\t(t (do* ((i 1 (1+ i))\n\t\t (m n (1- m))\n\t\t (a m (* a m))\n\t\t (b i (* b i)))\n\t ((= i k) (/ a b))))))\n\n(defun permutations (n k)\n (cond ((or (< n k) (< k 0) (< n 0)) 0)\n\t((= k 0) 1)\n\t(t (do* ((i 1 (1+ i))\n\t\t (m n (1- m))\n\t\t (a m (* a m)))\n\t ((= i k) a)))))\n", "language": "Common-Lisp" }, { "code": "require \"big\"\ninclude Math\n\nstruct Int\n\n def permutation(k)\n (self-k+1..self).product(1.to_big_i)\n end\n\n def combination(k)\n self.permutation(k) // (1..k).product(1.to_big_i)\n end\n\n def big_permutation(k)\n exp(lgamma_plus(self) - lgamma_plus(self-k))\n end\n\n def big_combination(k)\n exp( lgamma_plus(self) - lgamma_plus(self - k) - lgamma_plus(k))\n end\n\n private def lgamma_plus(n)\n lgamma(n+1) #lgamma is the natural log of gamma\n end\n\nend\n\np 12.permutation(9) #=> 79833600\np 12.big_permutation(9) #=> 79833600.00000021\np 60.combination(53) #=> 386206920\np 145.big_permutation(133) #=> 1.6801459655817956e+243\np 900.big_combination(450) #=> 2.247471882064647e+269\np 1000.big_combination(969) #=> 7.602322407770517e+58\np 15000.big_permutation(73) #=> 6.004137561717704e+304\n#That's about the maximum of Float:\np 15000.big_permutation(74) #=> Infinity\n#Fixnum has no maximum:\np 15000.permutation(74) #=> 896237613852967826239917238565433149353074416025197784301593335243699358040738127950872384197159884905490054194835376498534786047382445592358843238688903318467070575184552953997615178973027752714539513893159815472948987921587671399790410958903188816684444202526779550201576117111844818124800000000000000000000\n", "language": "Crystal" }, { "code": "import std.stdio, std.mathspecial, std.range, std.algorithm,\n std.bigint, std.conv;\n\nenum permutation = (in uint n, in uint k) pure =>\n reduce!q{a * b}(1.BigInt, iota(n - k + 1, n + 1));\n\nenum combination = (in uint n, in uint k) pure =>\n n.permutation(k) / reduce!q{a * b}(1.BigInt, iota(1, k + 1));\n\nenum bigPermutation = (in uint n, in uint k) =>\n exp(logGamma(n + 1) - logGamma(n - k + 1));\n\nenum bigCombination = (in uint n, in uint k) =>\n exp(logGamma(n + 1) - logGamma(n - k + 1) - logGamma(k + 1));\n\nvoid main() {\n 12.permutation(9).writeln;\n 12.bigPermutation(9).writeln;\n 60.combination(53).writeln;\n 145.bigPermutation(133).writeln;\n 900.bigCombination(450).writeln;\n 1_000.bigCombination(969).writeln;\n 15_000.bigPermutation(73).writeln;\n 15_000.bigPermutation(1185).writeln;\n writefln(\"%(%s\\\\\\n%)\", 15_000.permutation(74).text.chunks(50));\n}\n", "language": "D" }, { "code": "func perm x y .\n z = 1\n for i = x - y + 1 to x\n z *= i\n .\n return z\n.\nfunc fact x .\n z = 1\n for i = 2 to x\n z *= i\n .\n return z\n.\nfunc comb x y .\n if x - y < y\n y = x - y\n .\n return perm x y / fact y\n.\n#\ne = 2.7182818284590452354\nfunc log n .\n return log10 n / log10 e\n.\nfunc lstirling n .\n if n < 10\n return lstirling (n + 1) - log (n + 1)\n .\n return 0.5 * log (2 * pi * n) + n * log (n / e + 1 / (12 * e * n))\n.\nfunc$ tolog v .\n h = v div log 10\n return pow e (v - h * log 10) & \"e\" & h\n.\nfunc$ permf n k .\n return tolog (lstirling n - lstirling (n - k))\n.\nfunc$ combf n k .\n return tolog (lstirling n - lstirling (n - k) - lstirling k)\n.\nprint \"=> Exact results:\"\nfor n = 1 to 12\n p = n div 3\n print \"P(\" & n & \",\" & p & \")=\" & perm n p\n.\n#\n# double has 53 bits for integer\n#\nfor n = 10 step 10 to 50\n p = n div 3\n print \"C(\" & n & \",\" & p & \")=\" & comb n p\n.\n#\nprint \"\"\nprint \"=> Floating point approximations:\"\nfor n in [ 5 50 500 1000 5000 15000 ]\n p = n div 3\n print \"P(\" & n & \",\" & p & \")=\" & permf n p\n.\nfor n = 100 step 100 to 1000\n p = n div 3\n print \"C(\" & n & \",\" & p & \")=\" & combf n p\n.\n", "language": "EasyLang" }, { "code": ";; rename native functions according to task\n(define-syntax-rule (Cnk n k) (Cnp n k))\n(define-syntax-rule (Ank n k) (Anp n k))\n\n\n(Cnk 10 1)\n → 10\n(lib 'bigint) ;; no floating point needed : use large integers\n\n(Cnk 100 10)\n → 17310309456440\n(Cnk 1000 42)\n → 297242911333923795640059429176065863139989673213703918037987737481286092000\n(Ank 10 10)\n → 3628800\n(factorial 10)\n → 3628800\n(Ank 666 42)\n → 1029024198692120734765388598788124551227594950478035495578451793852872815678512303375588360\n1398831219998720000000000000\n", "language": "EchoLisp" }, { "code": "defmodule Combinations_permutations do\n def perm(n, k), do: product(n - k + 1 .. n)\n\n def comb(n, k), do: div( perm(n, k), product(1 .. k) )\n\n defp product(a..b) when a>b, do: 1\n defp product(list), do: Enum.reduce(list, 1, fn n, acc -> n * acc end)\n\n def test do\n IO.puts \"\\nA sample of permutations from 1 to 12:\"\n Enum.each(1..12, &show_perm(&1, div(&1, 3)))\n IO.puts \"\\nA sample of combinations from 10 to 60:\"\n Enum.take_every(10..60, 10) |> Enum.each(&show_comb(&1, div(&1, 3)))\n IO.puts \"\\nA sample of permutations from 5 to 15000:\"\n Enum.each([5,50,500,1000,5000,15000], &show_perm(&1, div(&1, 3)))\n IO.puts \"\\nA sample of combinations from 100 to 1000:\"\n Enum.take_every(100..1000, 100) |> Enum.each(&show_comb(&1, div(&1, 3)))\n end\n\n defp show_perm(n, k), do: show_gen(n, k, \"perm\", &perm/2)\n\n defp show_comb(n, k), do: show_gen(n, k, \"comb\", &comb/2)\n\n defp show_gen(n, k, strfun, fun), do:\n IO.puts \"#{strfun}(#{n}, #{k}) = #{show_big(fun.(n, k), 40)}\"\n\n defp show_big(n, limit) do\n strn = to_string(n)\n if String.length(strn) < limit do\n strn\n else\n {shown, hidden} = String.split_at(strn, limit)\n \"#{shown}... (#{String.length(hidden)} more digits)\"\n end\n end\nend\n\nCombinations_permutations.test\n", "language": "Elixir" }, { "code": "-module(combinations_permutations).\n\n-export([test/0]).\n\nperm(N, K) ->\n product(lists:seq(N - K + 1, N)).\n\ncomb(N, K) ->\n perm(N, K) div product(lists:seq(1, K)).\n\nproduct(List) ->\n lists:foldl(fun(N, Acc) -> N * Acc end, 1, List).\n\ntest() ->\n io:format(\"\\nA sample of permutations from 1 to 12:\\n\"),\n [show_perm({N, N div 3}) || N <- lists:seq(1, 12)],\n io:format(\"\\nA sample of combinations from 10 to 60:\\n\"),\n [show_comb({N, N div 3}) || N <- lists:seq(10, 60, 10)],\n io:format(\"\\nA sample of permutations from 5 to 15000:\\n\"),\n [show_perm({N, N div 3}) || N <- [5,50,500,1000,5000,15000]],\n io:format(\"\\nA sample of combinations from 100 to 1000:\\n\"),\n [show_comb({N, N div 3}) || N <- lists:seq(100, 1000, 100)],\n ok.\n\nshow_perm({N, K}) ->\n show_gen(N, K, \"perm\", fun perm/2).\n\nshow_comb({N, K}) ->\n show_gen(N, K, \"comb\", fun comb/2).\n\nshow_gen(N, K, StrFun, Fun) ->\n io:format(\"~s(~p, ~p) = ~s\\n\",[StrFun, N, K, show_big(Fun(N, K), 40)]).\n\nshow_big(N, Limit) ->\n StrN = integer_to_list(N),\n case length(StrN) < Limit of\n true ->\n StrN;\n false ->\n {Shown, Hidden} = lists:split(Limit, StrN),\n io_lib:format(\"~s... (~p more digits)\", [Shown, length(Hidden)])\n end.\n", "language": "Erlang" }, { "code": "USING: math.combinatorics prettyprint ;\n\n1000 10 nCk . ! 263409560461970212832400\n1000 10 nPk . ! 955860613004397508326213120000\n", "language": "Factor" }, { "code": "Function PermBig(x As Long, y As Long) As ULongint\n Dim As Long i\n Dim As Longint z = 1\n For i = x - y + 1 To x\n z = z * i\n Next i\n Return (z)\nEnd Function\n\nFunction FactBig(x As Long) As ULongint\n Dim As Long i\n Dim As Longint z = 1\n For i = 2 To x\n z = z * i\n Next i\n Return (z)\nEnd Function\n\nFunction CombBig(Byval x As Long, Byval y As Long) As Double\n If y > x Then\n Return (0)\n Elseif x = y Then\n Return (1)\n Else\n If x - y < y Then y = x - y\n Return (PermBig(x, y) / FactBig(y))\n End If\nEnd Function\n\nDim As Long i, j\nPrint \"-- Long Integer - Permutations - from 1 to 12\"\nFor i = 1 To 12\n For j = 1 To i\n Print \"P(\" & i & \",\" & j & \")=\" & Str(PermBig(i, j)) & \" \";\n Next j\n Print \"\"\nNext i\n\nPrint Chr(10) & \"-- Float integer - Combinations from 10 to 60\"\nFor i = 10 To 60 Step 10\n For j = 1 To i Step i \\ 5\n Print \"C(\" & i & \",\" & j & \")=\" & Str(CombBig(i, j)) & \" \";\n Next j\n Print \"\"\nNext i\n\nPrint Chr(10) & \"-- Float integer - Permutations from 5000 to 15000\"\nFor i = 5000 To 15000 Step 5000\n For j = 10 To 50 Step 20\n Print \"P(\" & i & \",\" & j & \")=\" & Str(PermBig(i, j)) & \" \";\n Next j\n Print \"\"\nNext i\n\nPrint Chr(10) & \"-- Float integer - Combinations from 200 to 1000\"\nFor i = 200 To 1000 Step 200\n For j = 20 To 100 Step 20\n Print \"C(\" & i & \",\" & j & \")=\" & Str(CombBig(i, j)) & \" \";\n Next j\n Print \"\"\nNext i\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tvar n, p int64\n\tfmt.Printf(\"A sample of permutations from 1 to 12:\\n\")\n\tfor n = 1; n < 13; n++ {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 10 to 60:\\n\")\n\tfor n = 10; n < 61; n += 10 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of permutations from 5 to 15000:\\n\")\n\tnArr := [...]int64{5, 50, 500, 1000, 5000, 15000}\n\tfor _, n = range nArr {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 100 to 1000:\\n\")\n\tfor n = 100; n < 1001; n += 100 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n}\n\nfunc fact(n *big.Int) *big.Int {\n\tif n.Sign() < 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tr := big.NewInt(1)\n\ti := big.NewInt(2)\n\tfor i.Cmp(n) < 1 {\n\t\tr.Mul(r, i)\n\t\ti.Add(i, big.NewInt(1))\n\t}\n\treturn r\n}\n\nfunc perm(n, k *big.Int) *big.Int {\n\tr := fact(n)\n\tr.Div(r, fact(n.Sub(n, k)))\n\treturn r\n}\n\nfunc comb(n, r *big.Int) *big.Int {\n\tif r.Cmp(n) == 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tif r.Cmp(n) == 0 {\n\t\treturn big.NewInt(1)\n\t}\n\tc := fact(n)\n\tden := fact(n.Sub(n, r))\n\tden.Mul(den, fact(r))\n\tc.Div(c, den)\n\treturn c\n}\n", "language": "Go" }, { "code": "perm :: Integer -> Integer -> Integer\nperm n k = product [n-k+1..n]\n\ncomb :: Integer -> Integer -> Integer\ncomb n k = perm n k `div` product [1..k]\n\nmain :: IO ()\nmain = do\n let showBig maxlen b =\n let st = show b\n stlen = length st\n in if stlen < maxlen then st else take maxlen st ++ \"... (\" ++ show (stlen-maxlen) ++ \" more digits)\"\n\n let showPerm pr =\n putStrLn $ \"perm(\" ++ show n ++ \",\" ++ show k ++ \") = \" ++ showBig 40 (perm n k)\n where n = fst pr\n k = snd pr\n\n let showComb pr =\n putStrLn $ \"comb(\" ++ show n ++ \",\" ++ show k ++ \") = \" ++ showBig 40 (comb n k)\n where n = fst pr\n k = snd pr\n\n putStrLn \"A sample of permutations from 1 to 12:\"\n mapM_ showPerm [(n, n `div` 3) | n <- [1..12] ]\n\n putStrLn \"\"\n putStrLn \"A sample of combinations from 10 to 60:\"\n mapM_ showComb [(n, n `div` 3) | n <- [10,20..60] ]\n\n putStrLn \"\"\n putStrLn \"A sample of permutations from 5 to 15000:\"\n mapM_ showPerm [(n, n `div` 3) | n <- [5,50,500,1000,5000,15000] ]\n\n putStrLn \"\"\n putStrLn \"A sample of combinations from 100 to 1000:\"\n mapM_ showComb [(n, n `div` 3) | n <- [100,200..1000] ]\n", "language": "Haskell" }, { "code": "procedure main()\n write(\"P(4,2) = \",P(4,2))\n write(\"P(8,2) = \",P(8,2))\n write(\"P(10,8) = \",P(10,8))\n write(\"C(10,8) = \",C(10,8))\n write(\"C(20,8) = \",C(20,8))\n write(\"C(60,58) = \",C(60,58))\n write(\"P(1000,10) = \",P(1000,10))\n write(\"P(1000,20) = \",P(1000,20))\n write(\"P(15000,2) = \",P(15000,2))\n write(\"C(1000,10) = \",C(1000,10))\n write(\"C(1000,999) = \",C(1000,999))\n write(\"C(1000,1000) = \",C(1000,1000))\n write(\"C(15000,14998) = \",C(15000,14998))\nend\n\nprocedure C(n,k)\n every (d:=1) *:= 2 to k\n return P(n,k)/d\nend\n\nprocedure P(n,k)\n every (p:=1) *:= (n-k+1) to n\n return p\nend\n", "language": "Icon" }, { "code": "C=: !\nP=: (%&!&x:~ * <:)\"0\n", "language": "J" }, { "code": " P table 1+i.12\n┌──┬─────────────────────────────────────────────────────────────┐\n│P │1 2 3 4 5 6 7 8 9 10 11 12│\n├──┼─────────────────────────────────────────────────────────────┤\n│ 1│1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600│\n│ 2│0 1 3 12 60 360 2520 20160 181440 1814400 19958400 239500800│\n│ 3│0 0 1 4 20 120 840 6720 60480 604800 6652800 79833600│\n│ 4│0 0 0 1 5 30 210 1680 15120 151200 1663200 19958400│\n│ 5│0 0 0 0 1 6 42 336 3024 30240 332640 3991680│\n│ 6│0 0 0 0 0 1 7 56 504 5040 55440 665280│\n│ 7│0 0 0 0 0 0 1 8 72 720 7920 95040│\n│ 8│0 0 0 0 0 0 0 1 9 90 990 11880│\n│ 9│0 0 0 0 0 0 0 0 1 10 110 1320│\n│10│0 0 0 0 0 0 0 0 0 1 11 132│\n│11│0 0 0 0 0 0 0 0 0 0 1 12│\n│12│0 0 0 0 0 0 0 0 0 0 0 1│\n└──┴─────────────────────────────────────────────────────────────┘\n\n C table 10+10*i.6x\n┌──┬─────────────────────────────────────────────────────────────────┐\n│C │10 20 30 40 50 60│\n├──┼─────────────────────────────────────────────────────────────────┤\n│10│ 1 184756 30045015 847660528 10272278170 75394027566│\n│20│ 0 1 30045015 137846528820 47129212243960 4191844505805495│\n│30│ 0 0 1 847660528 47129212243960 118264581564861424│\n│40│ 0 0 0 1 10272278170 4191844505805495│\n│50│ 0 0 0 0 1 75394027566│\n│60│ 0 0 0 0 0 1│\n└──┴─────────────────────────────────────────────────────────────────┘\n\n 5 P 100\n7.77718e155\n 100 P 200\n8.45055e216\n 300 P 400\n2.09224e254\n 700 P 800\n3.18349e287\n\n 5 C 100\n75287520\n 100 C 200\n9.05485e58\n 300 C 400\n2.24185e96\n 700 C 800\n3.41114e129\n", "language": "J" }, { "code": "import java.math.BigInteger;\n\npublic class CombinationsAndPermutations {\n\n public static void main(String[] args) {\n System.out.println(Double.MAX_VALUE);\n System.out.println(\"A sample of permutations from 1 to 12 with exact Integer arithmetic:\");\n for ( int n = 1 ; n <= 12 ; n++ ) {\n int k = n / 2;\n System.out.printf(\"%d P %d = %s%n\", n, k, permutation(n, k));\n }\n\n System.out.println();\n System.out.println(\"A sample of combinations from 10 to 60 with exact Integer arithmetic:\");\n for ( int n = 10 ; n <= 60 ; n += 5 ) {\n int k = n / 2;\n System.out.printf(\"%d C %d = %s%n\", n, k, combination(n, k));\n }\n\n System.out.println();\n System.out.println(\"A sample of permutations from 5 to 15000 displayed in floating point arithmetic:\");\n System.out.printf(\"%d P %d = %s%n\", 5, 2, display(permutation(5, 2), 50));\n for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {\n int k = n / 2;\n System.out.printf(\"%d P %d = %s%n\", n, k, display(permutation(n, k), 50));\n }\n\n System.out.println();\n System.out.println(\"A sample of combinations from 100 to 1000 displayed in floating point arithmetic:\");\n for ( int n = 100 ; n <= 1000 ; n += 100 ) {\n int k = n / 2;\n System.out.printf(\"%d C %d = %s%n\", n, k, display(combination(n, k), 50));\n }\n\n }\n\n private static String display(BigInteger val, int precision) {\n String s = val.toString();\n precision = Math.min(precision, s.length());\n StringBuilder sb = new StringBuilder();\n sb.append(s.substring(0, 1));\n sb.append(\".\");\n sb.append(s.substring(1, precision));\n sb.append(\" * 10^\");\n sb.append(s.length()-1);\n return sb.toString();\n }\n\n public static BigInteger combination(int n, int k) {\n // Select value with smallest intermediate results\n // combination(n, k) = combination(n, n-k)\n if ( n-k < k ) {\n k = n-k;\n }\n BigInteger result = permutation(n, k);\n while ( k > 0 ) {\n result = result.divide(BigInteger.valueOf(k));\n k--;\n }\n return result;\n }\n\n public static BigInteger permutation(int n, int k) {\n BigInteger result = BigInteger.ONE;\n for ( int i = n ; i >= n-k+1 ; i-- ) {\n result = result.multiply(BigInteger.valueOf(i));\n }\n return result;\n }\n\n}\n", "language": "Java" }, { "code": "def permutation(k): . as $n\n | reduce range($n-k+1; 1+$n) as $i (1; . * $i);\n\ndef combination(k): . as $n\n | if k > ($n/2) then combination($n-k)\n else reduce range(0; k) as $i (1; (. * ($n - $i)) / ($i + 1))\n end;\n\n# natural log of n!\ndef log_factorial: (1+.) | tgamma | log;\n\ndef log_permutation(k):\n (log_factorial - ((.-k) | log_factorial));\n\ndef log_combination(k):\n (log_factorial - ((. - k)|log_factorial) - (k|log_factorial));\n\ndef big_permutation(k): log_permutation(k) | exp;\n\ndef big_combination(k): log_combination(k) | exp;\n", "language": "Jq" }, { "code": "function Base.binomial{T<:FloatingPoint}(n::T, k::T)\n exp(lfact(n) - lfact(n - k) - lfact(k))\nend\n\nfunction Base.factorial{T<:FloatingPoint}(n::T, k::T)\n exp(lfact(n) - lfact(k))\nend\n\n⊞{T<:Real}(n::T, k::T) = binomial(n, k)\n⊠{T<:Real}(n::T, k::T) = factorial(n, n-k)\n", "language": "Julia" }, { "code": "function picknk{T<:Integer}(lo::T, hi::T)\n n = rand(lo:hi)\n k = rand(1:n)\n return (n, k)\nend\n\nnsamp = 10\n\nprint(\"Tests of the combinations (⊞) and permutations (⊠) operators for \")\nprintln(\"integer values.\")\nprintln()\nlo, hi = 1, 12\nprint(nsamp, \" samples of n ⊠ k with n in [\", lo, \", \", hi, \"] \")\nprintln(\"and k in [1, n].\")\nfor i in 1:nsamp\n (n, k) = picknk(lo, hi)\n println(@sprintf \" %2d ⊠ %2d = %18d\" n k n ⊠ k)\nend\n\nlo, hi = 10, 60\nprintln()\nprint(nsamp, \" samples of n ⊞ k with n in [\", lo, \", \", hi, \"] \")\nprintln(\"and k in [1, n].\")\nfor i in 1:nsamp\n (n, k) = picknk(lo, hi)\n println(@sprintf \" %2d ⊞ %2d = %18d\" n k n ⊞ k)\nend\n\nprintln()\nprint(\"Tests of the combinations (⊞) and permutations (⊠) operators for \")\nprintln(\"(big) float values.\")\nprintln()\nlo, hi = 5, 15000\nprint(nsamp, \" samples of n ⊠ k with n in [\", lo, \", \", hi, \"] \")\nprintln(\"and k in [1, n].\")\nfor i in 1:nsamp\n (n, k) = picknk(lo, hi)\n n = BigFloat(n)\n k = BigFloat(k)\n println(@sprintf \" %7.1f ⊠ %7.1f = %10.6e\" n k n ⊠ k)\nend\n\nlo, hi = 100, 1000\nprintln()\nprint(nsamp, \" samples of n ⊞ k with n in [\", lo, \", \", hi, \"] \")\nprintln(\"and k in [1, n].\")\nfor i in 1:nsamp\n (n, k) = picknk(lo, hi)\n n = BigFloat(n)\n k = BigFloat(k)\n println(@sprintf \" %7.1f ⊞ %7.1f = %10.6e\" n k n ⊞ k)\nend\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nimport java.math.BigInteger\n\nfun perm(n: Int, k: Int): BigInteger {\n require(n > 0 && k >= 0)\n return (n - k + 1 .. n).fold(BigInteger.ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }\n}\n\nfun comb(n: Int, k: Int): BigInteger {\n require(n > 0 && k >= 0)\n val fact = (2..k).fold(BigInteger.ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }\n return perm(n, k) / fact\n}\n\nfun main(args: Array<String>) {\n println(\"A sample of permutations from 1 to 12:\")\n for (n in 1..12) System.out.printf(\"%2d P %-2d = %d\\n\", n, n / 3, perm(n, n / 3))\n\n println(\"\\nA sample of combinations from 10 to 60:\")\n for (n in 10..60 step 10) System.out.printf(\"%2d C %-2d = %d\\n\", n, n / 3, comb(n, n / 3))\n\n println(\"\\nA sample of permutations from 5 to 15000:\")\n val na = intArrayOf(5, 50, 500, 1000, 5000, 15000)\n for (n in na) {\n val k = n / 3\n val s = perm(n, k).toString()\n val l = s.length\n val e = if (l <= 40) \"\" else \"... (${l - 40} more digits)\"\n System.out.printf(\"%5d P %-4d = %s%s\\n\", n, k, s.take(40), e)\n }\n\n println(\"\\nA sample of combinations from 100 to 1000:\")\n for (n in 100..1000 step 100) {\n val k = n / 3\n val s = comb(n, k).toString()\n val l = s.length\n val e = if (l <= 40) \"\" else \"... (${l - 40} more digits)\"\n System.out.printf(\"%4d C %-3d = %s%s\\n\", n, k, s.take(40), e)\n }\n}\n", "language": "Kotlin" }, { "code": "-- Helper function to display results in scientific notation corrected\nfunction eshow(x)\n local e = math.floor(x / math.log(10))\n local exponentiated = math.exp(x - e * math.log(10))\n -- Corrected format specifier from %.8Fe%+d to %.8e, and manually constructing the scientific notation if needed\n return string.format(\"%.8e\", exponentiated) .. \"e\" .. tostring(e)\nend\n\n-- The rest of the functions remain the same\n\n-- Define the factorial function for permutations\nfunction P(n, k)\n local x = 1\n for i = n - k + 1, n do\n x = x * i\n end\n return x\nend\n\n-- Define the function for big permutations using logarithms\nfunction P_big(n, k)\n local x = 0\n for i = n - k + 1, n do\n x = x + math.log(i)\n end\n return eshow(x)\nend\n\n-- Define the combinations function\nfunction C(n, k)\n local x = 1\n for i = 1, k do\n x = x * (n - i + 1) / i\n end\n return x\nend\n\n-- Define the function for big combinations using logarithms\nfunction C_big(n, k)\n local x = 0\n for i = 1, k do\n x = x + math.log(n - i + 1) - math.log(i)\n end\n return math.exp(x)\nend\n\n-- Function to showcase the calculations\nfunction showoff(text, code, fname, ...)\n local n = {...}\n print(\"\\nA sample of \" .. text .. \" from \" .. n[1] .. \" to \" .. n[#n] .. \"\")\n for _, v in ipairs(n) do\n local k = math.floor(v / 3)\n print(v, fname .. \" \" .. k .. \" = \", code(v, k))\n end\nend\n\n-- Examples of usage\nshowoff(\"Permutations\", P, \"P\", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)\nshowoff(\"Combinations\", C, \"C\", 10, 20, 30, 40, 50, 60)\nshowoff(\"Permutations\", P_big, \"P\", 5, 50, 500, 1000, 5000, 15000)\nshowoff(\"Combinations\", C_big, \"C\", 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000)\n", "language": "Lua" }, { "code": "Module PermComb {\n Form 80, 50\n perm=lambda (x,y) ->{\n def i,z\n z=1\n For i=x-y+1 to x :z*=i:next i\n =z\n }\n fact=lambda (x) ->{\n def i,z\n z=1\n For i=2 to x :z*=i:next i\n =z\n }\n comb=lambda (x as decimal, y as decimal) ->{\n If y>x then {\n =0\n } else.if x=y then {\n =1\n } else {\n if x-y<y then y=x-y\n def decimal i, z=1, ym\n ym=y\n For i=x to x-y+1\n z*=i\n z=z/ym\n ym-- : if ym<1 then ym=1@\n next i\n =round(z,0)\n\n }\n }\n Document Doc$\n WriteLn(\"-- Permutations - from 1 to 12\")\n For i=1 to 12\n l$=\"\" : For j=1 to i : l$+= format$(\"P({0},{1})={2} \",i, j,perm(i, j)) :next j\n Writetext(l$)\n next i\n WriteLn(\"-- Combinations from 10 to 60\")\n For i=10 to 60 step 10\n l$=\"\" : For j=1 to i step i div 5 : l$+= format$(\"C({0},{1})={2} \",i, j,comb(i, j)) :next j\n Writetext(l$)\n Next i\n WriteLn(\"-- Permutations from 5000 to 15000\")\n For i=5000 to 15000 step 5000\n l$=\"\" : For j=10 to 70 step 20: l$+= format$(\"P({0},{1})={2} \",i, j,perm(i, j)) :next j\n Writetext(l$)\n Next i\n WriteLn(\"-- Combinations from 200 to 1000\")\n For i=200 to 1000 step 200\n l$=\"\" : For j=20 to 100 step 20: l$+= format$(\"C({0},{1})={2} \",i, j,comb(i, j)) :next j\n Writetext(l$)\n Next i\n ClipBoard Doc$\n Sub WriteText(a$)\n doc$=a$+{\n }\n Report a$\n End Sub\n Sub WriteLn(a$)\n doc$=a$+{\n }\n Print a$\n End Sub\n}\nPermComb\n", "language": "M2000-Interpreter" }, { "code": "comb := proc (n::integer, k::integer)\n return factorial(n)/(factorial(k)*factorial(n-k));\nend proc;\nperm := proc (n::integer, k::integer)\n return factorial(n)/factorial(n-k);\nend proc;\n", "language": "Maple" }, { "code": "ClearAll[Combination,Permutation]\nCombination[n_,k_]:=Binomial[n,k]\nPermutation[n_,k_]:=Binomial[n,k]k!\n\nTableForm[Array[Permutation,{12,12}],TableHeadings->{Range[12],Range[12]}]\nTableForm[Array[Combination,{6,6},{{10,60},{10,60}}],TableHeadings->{Range[10,60,10],Range[10,60,10]}]\n{Row[{#,\"P\",#-2},\" \"],N@Permutation[#,#-2]}&/@{5,1000,5000,10000,15000}//Grid\n{Row[{#,\"C\",#/2},\" \"],N@Combination[#,#/2]}&/@Range[100,1000,100]//Grid\n", "language": "Mathematica" }, { "code": "Permutation[200000, 100000]\n", "language": "Mathematica" }, { "code": "import bigints\n\nproc perm(n, k: int32): BigInt =\n result = initBigInt 1\n var\n k = n - k\n n = n\n while n > k:\n result *= n\n dec n\n\nproc comb(n, k: int32): BigInt =\n result = perm(n, k)\n var k = k\n while k > 0:\n result = result div k\n dec k\n\necho \"P(1000, 969) = \", perm(1000, 969)\necho \"C(1000, 969) = \", comb(1000, 969)\n", "language": "Nim" }, { "code": "sample(f,a,b)=for(i=1,4, my(n1=random(b-a)+a,n2=random(b-a)+a); [n1,n2]=[max(n1,n2),min(n1,n2)]; print(n1\", \"n2\": \"f(n1,n2)))\npermExact(m,n)=factorback([m-n+1..m]);\ncombExact=binomial;\npermApprox(m,n)=exp(lngamma(m+1)-lngamma(m-n+1));\ncombApprox(m,n)=exp(lngamma(m+1)-lngamma(n+1)-lngamma(m-n+1));\n\nsample(permExact, 1, 12);\nsample(combExact, 10, 60);\nsample(permApprox, 5, 15000);\nsample(combApprox, 100, 1000);\n", "language": "PARI-GP" }, { "code": "use strict;\nuse warnings;\n\nshowoff( \"Permutations\", \\&P, \"P\", 1 .. 12 );\nshowoff( \"Combinations\", \\&C, \"C\", map $_*10, 1..6 );\nshowoff( \"Permutations\", \\&P_big, \"P\", 5, 50, 500, 1000, 5000, 15000 );\nshowoff( \"Combinations\", \\&C_big, \"C\", map $_*100, 1..10 );\n\nsub showoff {\n\tmy ($text, $code, $fname, @n) = @_;\n\tprint \"\\nA sample of $text from $n[0] to $n[-1]\\n\";\n\tfor my $n ( @n ) {\n\t\tmy $k = int( $n / 3 );\n\t\tprint $n, \" $fname $k = \", $code->($n, $k), \"\\n\";\n\t}\n}\n\nsub P {\n\tmy ($n, $k) = @_;\n\tmy $x = 1;\n\t$x *= $_ for $n - $k + 1 .. $n ;\n\t$x;\n}\n\nsub P_big {\n\tmy ($n, $k) = @_;\n\tmy $x = 0;\n\t$x += log($_) for $n - $k + 1 .. $n ;\n\teshow($x);\n}\n\nsub C {\n\tmy ($n, $k) = @_;\n\tmy $x = 1;\n\t$x *= ($n - $_ + 1) / $_ for 1 .. $k;\n\t$x;\n}\n\nsub C_big {\n\tmy ($n, $k) = @_;\n\tmy $x = 0;\n\t$x += log($n - $_ + 1) - log($_) for 1 .. $k;\n\texp($x);\n}\n\nsub eshow {\n\tmy ($x) = @_;\n\tmy $e = int( $x / log(10) );\n\tsprintf \"%.8Fe%+d\", exp($x - $e * log(10)), $e;\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">P</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">factorial</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #7060A8;\">factorial</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">C</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">P</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #7060A8;\">factorial</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">lstirling</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">lstirling</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #7060A8;\">log</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">log</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #004600;\">PI</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">log</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #004600;\">E</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">/(</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #004600;\">E</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">P_approx</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">lstirling</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">lstirling</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">C_approx</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">lstirling</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">lstirling</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">lstirling</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">to_s</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">e</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #7060A8;\">log</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%.9ge%d\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">E</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">log</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)),</span><span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- Test code</span>\n\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"=&gt; Exact results:\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">12</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"P(%d,%d) = %d\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">P</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">60</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"C(%d,%d) = %d\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">C</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"=&gt; Floating point approximations:\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">50</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">500</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1000</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5000</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">15000</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"P(%d,%d) = %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">to_s</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">P_approx</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">))})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">100</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1000</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">100</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"C(%d,%d) = %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">to_s</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">C_approx</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">))})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "from __future__ import print_function\n\nfrom scipy.misc import factorial as fact\nfrom scipy.misc import comb\n\ndef perm(N, k, exact=0):\n return comb(N, k, exact) * fact(k, exact)\n\nexact=True\nprint('Sample Perms 1..12')\nfor N in range(1, 13):\n k = max(N-2, 1)\n print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\\n')\n\nprint('\\n\\nSample Combs 10..60')\nfor N in range(10, 61, 10):\n k = N-2\n print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\\n')\n\nexact=False\nprint('\\n\\nSample Perms 5..1500 Using FP approximations')\nfor N in [5, 15, 150, 1500, 15000]:\n k = N-2\n print('%iP%i =' % (N, k), perm(N, k, exact))\n\nprint('\\nSample Combs 100..1000 Using FP approximations')\nfor N in range(100, 1001, 100):\n k = N-2\n print('%iC%i =' % (N, k), comb(N, k, exact))\n", "language": "Python" }, { "code": "perm <- function(n, k) choose(n, k) * factorial(k)\nprint(perm(seq(from = 3, to = 12, by = 3), seq(from = 2, to = 8, by = 2)))\nprint(choose(seq(from = 10, to = 60, by = 10), seq(from = 3, to = 18, by = 3)))\nprint(perm(seq(from = 1500, to = 15000, by = 1500), seq(from = 55, to = 100, by = 5)))\nprint(choose(seq(from = 100, to = 1000, by = 150), seq(from = 70, to = 100, by = 5)))\n", "language": "R" }, { "code": "#lang racket\n(require math)\n(define C binomial)\n(define P permutations)\n\n(C 1000 10) ; -> 263409560461970212832400\n(P 1000 10) ; -> 955860613004397508326213120000\n", "language": "Racket" }, { "code": "multi P($n, $k) { [*] $n - $k + 1 .. $n }\nmulti C($n, $k) { P($n, $k) / [*] 1 .. $k }\n\nsub lstirling(\\n) {\n n < 10 ?? lstirling(n+1) - log(n+1) !!\n .5*log(2*pi*n)+ n*log(n/e+1/(12*e*n))\n}\n\nrole Logarithm {\n method gist {\n\tmy $e = (self/10.log).Int;\n\tsprintf \"%.8fE%+d\", exp(self - $e*10.log), $e;\n }\n}\nmulti P($n, $k, :$float!) {\n (lstirling($n) - lstirling($n -$k))\n but Logarithm\n}\nmulti C($n, $k, :$float!) {\n (lstirling($n) - lstirling($n -$k) - lstirling($k))\n but Logarithm\n}\n\nsay \"Exact results:\";\nfor 1..12 -> $n {\n my $p = $n div 3;\n say \"P($n, $p) = \", P($n, $p);\n}\n\nfor 10, 20 ... 60 -> $n {\n my $p = $n div 3;\n say \"C($n, $p) = \", C($n, $p);\n}\n\nsay '';\nsay \"Floating point approximations:\";\nfor 5, 50, 500, 1000, 5000, 15000 -> $n {\n my $p = $n div 3;\n say \"P($n, $p) = \", P($n, $p, :float);\n}\n\nfor 100, 200 ... 1000 -> $n {\n my $p = $n div 3;\n say \"C($n, $p) = \", C($n, $p, :float);\n}\n", "language": "Raku" }, { "code": "/*REXX program compute and displays a sampling of combinations and permutations. */\nnumeric digits 100 /*use 100 decimal digits of precision. */\n\n do j=1 for 12; _= /*show all permutations from 1 ──► 12.*/\n do k=1 for j /*step through all J permutations. */\n _=_ 'P('j\",\"k')='perm(j,k)\" \" /*add an extra blank between numbers. */\n end /*k*/\n say strip(_) /*show the permutations horizontally. */\n end /*j*/\nsay /*display a blank line for readability.*/\n do j=10 to 60 by 10; _= /*show some combinations 10 ──► 60. */\n do k= 1 to j by j%5 /*step through some combinations. */\n _=_ 'C('j\",\"k')='comb(j,k)\" \" /*add an extra blank between numbers. */\n end /*k*/\n say strip(_) /*show the combinations horizontally. */\n end /*j*/\nsay /*display a blank line for readability.*/\nnumeric digits 20 /*force floating point for big numbers.*/\n\n do j=5 to 15000 by 1000; _= /*show a few permutations, big numbers.*/\n do k=1 to j for 5 by j%10 /*step through some J permutations. */\n _=_ 'P('j\",\"k')='perm(j,k)\" \" /*add an extra blank between numbers. */\n end /*k*/\n say strip(_) /*show the permutations horizontally. */\n end /*j*/\nsay /*display a blank line for readability.*/\n do j=100 to 1000 by 100; _= /*show a few combinations, big numbers.*/\n do k= 1 to j by j%5 /*step through some combinations. */\n _=_ 'C('j\",\"k')='comb(j,k)\" \" /*add an extra blank between numbers. */\n end /*k*/\n say strip(_) /*show the combinations horizontally. */\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nperm: procedure; parse arg x,y; call .combPerm; return _\n.combPerm: _=1; do j=x-y+1 to x; _=_*j; end; return _\n!: procedure; parse arg x; !=1; do j=2 to x; !=!*j; end; return !\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncomb: procedure; parse arg x,y /*arguments: X things, Y at-a-time.*/\n if y >x then return 0 /*oops-say, an error, too big a chunk.*/\n if x =y then return 1 /*X things are the same as chunk size.*/\n if x-y <y then y=x - y /*switch things around for speed. */\n call .combPerm /*call subroutine to do heavy lifting. */\n return _ / !(y) /*just perform one last division. */\n", "language": "REXX" }, { "code": "include Math\n\nclass Integer\n\n def permutation(k)\n (self-k+1 .. self).inject( :*)\n end\n\n def combination(k)\n self.permutation(k) / (1 .. k).inject( :*)\n end\n\n def big_permutation(k)\n exp( lgamma_plus(self) - lgamma_plus(self -k))\n end\n\n def big_combination(k)\n exp( lgamma_plus(self) - lgamma_plus(self - k) - lgamma_plus(k))\n end\n\n private\n def lgamma_plus(n)\n lgamma(n+1)[0] #lgamma is the natural log of gamma\n end\n\nend\n\np 12.permutation(9) #=> 79833600\np 12.big_permutation(9) #=> 79833600.00000021\np 60.combination(53) #=> 386206920\np 145.big_permutation(133) #=> 1.6801459655817956e+243\np 900.big_combination(450) #=> 2.247471882064647e+269\np 1000.big_combination(969) #=> 7.602322407770517e+58\np 15000.big_permutation(73) #=> 6.004137561717704e+304\n#That's about the maximum of Float:\np 15000.big_permutation(74) #=> Infinity\n#Fixnum has no maximum:\np 15000.permutation(74) #=> 896237613852967826239917238565433149353074416025197784301593335243699358040738127950872384197159884905490054194835376498534786047382445592358843238688903318467070575184552953997615178973027752714539513893159815472948987921587671399790410958903188816684444202526779550201576117111844818124800000000000000000000\n", "language": "Ruby" }, { "code": "(1..60).to_a.combination(53).size #=> 386206920\n", "language": "Ruby" }, { "code": "fn perm(n: f64, k: f64) -> f64 {\n let mut result: f64 = 1.0;\n let mut i: f64 = 0.0;\n\n while i < k {\n result *= n - i;\n i += 1.0;\n }\n\n result\n}\n\nfn comb(n: f64, k: f64) -> f64 {\n perm(n, k) / perm(k, k)\n}\n\nfn main() {\n const P: f64 = 12.0;\n const C: f64 = 60.0;\n\n let mut j: f64 = 1.0;\n let mut k: f64 = 10.0;\n\n while j < P {\n println!(\"P({},{}) = {}\", P, j, perm(P, j).floor());\n j += 1.0;\n }\n\n while k < C {\n println!(\"C({},{}) = {}\", C, k, comb(C, k).floor());\n k += 10.0;\n }\n\n}\n", "language": "Rust" }, { "code": "(define (combinations n k)\n (do ((i 0 (+ 1 i))\n (res 1 (/ (* res (- n i))\n (- k i))))\n ((= i k) res)))\n\n(define (permutations n k)\n (do ((i 0 (+ 1 i))\n (res 1 (* res (- n i))))\n ((= i k) res)))\n\n(display \"P(4,2) = \") (display (permutations 4 2)) (newline)\n(display \"P(8,2) = \") (display (permutations 8 2)) (newline)\n(display \"P(10,8) = \") (display (permutations 10 8)) (newline)\n(display \"C(10,8) = \") (display (combinations 10 8)) (newline)\n(display \"C(20,8) = \") (display (combinations 20 8)) (newline)\n(display \"C(60,58) = \") (display (combinations 60 58)) (newline)\n(display \"P(1000,10) = \") (display (permutations 1000 10)) (newline)\n(display \"P(1000,20) = \") (display (permutations 1000 20)) (newline)\n(display \"P(15000,2) = \") (display (permutations 15000 3)) (newline)\n(display \"C(1000,10) = \") (display (combinations 1000 10)) (newline)\n(display \"C(1000,999) = \") (display (combinations 1000 999)) (newline)\n(display \"C(1000,1000) = \") (display (combinations 1000 1000)) (newline)\n(display \"C(15000,14998) = \") (display (combinations 15000 14998)) (newline)\n", "language": "Scheme" }, { "code": "func P(n, k) { n! / ((n-k)!) }\nfunc C(n, k) { binomial(n, k) }\n\nclass Logarithm(value) {\n method to_s {\n var e = int(value/10.log)\n \"%.8fE%+d\" % (exp(value - e*10.log), e)\n }\n}\n\nfunc lstirling(n) {\n n < 10 ? (lstirling(n+1) - log(n+1))\n  : (0.5*log(2*Num.pi*n) + n*log(n/Num.e + 1/(12*Num.e*n)))\n}\n\nfunc P_approx(n, k) {\n Logarithm((lstirling(n) - lstirling(n -k)))\n}\n\nfunc C_approx(n, k) {\n Logarithm((lstirling(n) - lstirling(n -k) - lstirling(k)))\n}\n\nsay \"=> Exact results:\"\nfor n (1..12) {\n var p = n//3\n say \"P(#{n}, #{p}) = #{P(n, p)}\"\n}\n\nfor n (10..60 `by` 10) {\n var p = n//3\n say \"C(#{n}, #{p}) = #{C(n, p)}\"\n}\n\nsay '';\nsay \"=> Floating point approximations:\"\nfor n ([5, 50, 500, 1000, 5000, 15000]) {\n var p = n//3\n say \"P(#{n}, #{p}) = #{P_approx(n, p)}\"\n}\n\nfor n (100..1000 `by` 100) {\n var p = n//3\n say \"C(#{n}, #{p}) = #{C_approx(n, p)}\"\n}\n", "language": "Sidef" }, { "code": "real scalar comb1(n, k) {\n\treturn(exp(lnfactorial(n)-lnfactorial(k)-lnfactorial(n-k)))\n}\n\nreal scalar perm(n, k) {\n\treturn(exp(lnfactorial(n)-lnfactorial(n-k)))\n}\n", "language": "Stata" }, { "code": "import BigInt\n\nfunc permutations(n: Int, k: Int) -> BigInt {\n let l = n - k + 1\n\n guard l <= n else {\n return 1\n }\n\n return (l...n).reduce(BigInt(1), { $0 * BigInt($1) })\n}\n\nfunc combinations(n: Int, k: Int) -> BigInt {\n let fact = {() -> BigInt in\n guard k > 1 else {\n return 1\n }\n\n return (2...k).map({ BigInt($0) }).reduce(1, *)\n }()\n\n return permutations(n: n, k: k) / fact\n}\n\nprint(\"Sample of permutations from 1 to 12\")\n\nfor i in 1...12 {\n print(\"\\(i) P \\(i / 3) = \\(permutations(n: i, k: i / 3))\")\n}\n\nprint(\"\\nSample of combinations from 10 to 60\")\n\nfor i in stride(from: 10, through: 60, by: 10) {\n print(\"\\(i) C \\(i / 3) = \\(combinations(n: i, k: i / 3))\")\n}\n\nprint(\"\\nSample of permutations from 5 to 15,000\")\n\nfor i in [5, 50, 500, 1000, 5000, 15000] {\n let k = i / 3\n let res = permutations(n: i, k: k).description\n let extra = res.count > 40 ? \"... (\\(res.count - 40) more digits)\" : \"\"\n\n print(\"\\(i) P \\(k) = \\(res.prefix(40))\\(extra)\")\n}\n\nprint(\"\\nSample of combinations from 100 to 1000\")\n\nfor i in stride(from: 100, through: 1000, by: 100) {\n let k = i / 3\n let res = combinations(n: i, k: k).description\n let extra = res.count > 40 ? \"... (\\(res.count - 40) more digits)\" : \"\"\n\n print(\"\\(i) C \\(k) = \\(res.prefix(40))\\(extra)\")\n}\n", "language": "Swift" }, { "code": "# Exact integer versions\nproc tcl::mathfunc::P {n k} {\n set t 1\n for {set i $n} {$i > $n-$k} {incr i -1} {\n\tset t [expr {$t * $i}]\n }\n return $t\n}\nproc tcl::mathfunc::C {n k} {\n set t [P $n $k]\n for {set i $k} {$i > 1} {incr i -1} {\n\tset t [expr {$t / $i}]\n }\n return $t\n}\n\n# Floating point versions using the Gamma function\npackage require math\nproc tcl::mathfunc::lnGamma n {math::ln_Gamma $n}\nproc tcl::mathfunc::fP {n k} {\n expr {exp(lnGamma($n+1) - lnGamma($n-$k+1))}\n}\nproc tcl::mathfunc::fC {n k} {\n expr {exp(lnGamma($n+1) - lnGamma($n-$k+1) - lnGamma($k+1))}\n}\n", "language": "Tcl" }, { "code": "# Using the exact integer versions\nputs \"A sample of Permutations from 1 to 12:\"\nfor {set i 4} {$i <= 12} {incr i} {\n set ii [expr {$i - 2}]\n set iii [expr {$i - int(sqrt($i))}]\n puts \"$i P $ii = [expr {P($i,$ii)}], $i P $iii = [expr {P($i,$iii)}]\"\n}\nputs \"A sample of Combinations from 10 to 60:\"\nfor {set i 10} {$i <= 60} {incr i 10} {\n set ii [expr {$i - 2}]\n set iii [expr {$i - int(sqrt($i))}]\n puts \"$i C $ii = [expr {C($i,$ii)}], $i C $iii = [expr {C($i,$iii)}]\"\n}\n# Using the approximate floating point versions\nputs \"A sample of Permutations from 5 to 15000:\"\nfor {set i 5} {$i <= 150} {incr i 10} {\n set ii [expr {$i - 2}]\n set iii [expr {$i - int(sqrt($i))}]\n puts \"$i P $ii = [expr {fP($i,$ii)}], $i P $iii = [expr {fP($i,$iii)}]\"\n}\nputs \"A sample of Combinations from 100 to 1000:\"\nfor {set i 100} {$i <= 1000} {incr i 100} {\n set ii [expr {$i - 2}]\n set iii [expr {$i - int(sqrt($i))}]\n puts \"$i C $ii = [expr {fC($i,$ii)}], $i C $iii = [expr {fC($i,$iii)}]\"\n}\n", "language": "Tcl" }, { "code": "' Combinations and permutations - vbs - 10/04/2017\ndim i,j\nWscript.StdOut.WriteLine \"-- Long Integer - Permutations - from 1 to 12\"\nfor i=1 to 12\n\tfor j=1 to i\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & perm(i,j) & \" \"\n\tnext 'j\n\tWscript.StdOut.WriteLine \"\"\nnext 'i\nWscript.StdOut.WriteLine \"-- Float integer - Combinations from 10 to 60\"\nfor i=10 to 60 step 10\n\tfor j=1 to i step i\\5\n\t\tWscript.StdOut.Write \"C(\" & i & \",\" & j & \")=\" & comb(i,j) & \" \"\n\tnext 'j\n\tWscript.StdOut.WriteLine \"\"\nnext 'i\nWscript.StdOut.WriteLine \"-- Float integer - Permutations from 5000 to 15000\"\nfor i=5000 to 15000 step 5000\n\tfor j=10 to 70 step 20\n\t\tWscript.StdOut.Write \"C(\" & i & \",\" & j & \")=\" & perm(i,j) & \" \"\n\tnext 'j\n\tWscript.StdOut.WriteLine \"\"\nnext 'i\nWscript.StdOut.WriteLine \"-- Float integer - Combinations from 200 to 1000\"\nfor i=200 to 1000 step 200\n\tfor j=20 to 100 step 20\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & comb(i,j) & \" \"\n\tnext 'j\n\tWscript.StdOut.WriteLine \"\"\nnext 'i\n\nfunction perm(x,y)\n\tdim i,z\n\tz=1\n\tfor i=x-y+1 to x\n\t\tz=z*i\n\tnext 'i\n\tperm=z\nend function 'perm\n\t\nfunction fact(x)\n\tdim i,z\n\tz=1\n\tfor i=2 to x\n\t\tz=z*i\n\tnext 'i\n\tfact=z\nend function 'fact\n\nfunction comb(byval x,byval y)\n\tif y>x then\n\t\tcomb=0\n\telseif x=y then\n\t\tcomb=1\n\telse\n\t\tif x-y<y then y=x-y\n\t\tcomb=perm(x,y)/fact(y)\n\tend if\nend function 'comb\n", "language": "VBScript" }, { "code": "' Combinations and permutations - 10/04/2017\nImports System.Numerics 'BigInteger\nModule CombPermRc\n\n Sub Main()\n Dim i, j As Long\n For i = 1 To 12\n For j = 1 To i\n Console.Write(\"P(\" & i & \",\" & j & \")=\" & PermBig(i, j).ToString & \" \")\n Next j\n Console.WriteLine(\"\")\n Next i\n Console.WriteLine(\"--\")\n For i = 10 To 60 Step 10\n For j = 1 To i Step i \\ 5\n Console.Write(\"C(\" & i & \",\" & j & \")=\" & CombBig(i, j).ToString & \" \")\n Next j\n Console.WriteLine(\"\")\n Next i\n Console.WriteLine(\"--\")\n For i = 5000 To 15000 Step 5000\n For j = 4000 To 5000 Step 1000\n Console.Write(\"P(\" & i & \",\" & j & \")=\" & PermBig(i, j).ToString(\"E\") & \" \")\n Next j\n Console.WriteLine(\"\")\n Next i\n Console.WriteLine(\"--\")\n For i = 5000 To 15000 Step 5000\n For j = 4000 To 5000 Step 1000\n Console.Write(\"C(\" & i & \",\" & j & \")=\" & CombBig(i, j).ToString(\"E\") & \" \")\n\n Next j\n Console.WriteLine(\"\")\n Next i\n Console.WriteLine(\"--\")\n i = 5000 : j = 4000\n Console.WriteLine(\"C(\" & i & \",\" & j & \")=\" & CombBig(i, j).ToString)\n End Sub 'Main\n\n Function PermBig(x As Long, y As Long) As BigInteger\n Dim i As Long, z As BigInteger\n z = 1\n For i = x - y + 1 To x\n z = z * i\n Next i\n Return (z)\n End Function 'PermBig\n\n Function FactBig(x As Long) As BigInteger\n Dim i As Long, z As BigInteger\n z = 1\n For i = 2 To x\n z = z * i\n Next i\n Return (z)\n End Function 'FactBig\n\n Function CombBig(ByVal x As Long, ByVal y As Long) As BigInteger\n If y > x Then\n Return (0)\n ElseIf x = y Then\n Return (1)\n Else\n If x - y < y Then y = x - y\n Return (PermBig(x, y) / FactBig(y))\n End If\n End Function 'CombBig\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./big\" for BigInt\nimport \"./fmt\" for Fmt\nimport \"./iterate\" for Stepped\n\nvar perm = Fn.new { |n, k|\n if (n <= 0 || k < 0) Fiber.abort(\"Invalid argument(s).\")\n if (k == 0) return BigInt.one\n return (n-k+1..n).reduce(BigInt.one) { |acc, i| acc * BigInt.new(i) }\n}\n\nvar comb = Fn.new { |n, k|\n if (n <= 0 || k < 0) Fiber.abort(\"Invalid argument(s).\")\n var fact = BigInt.one\n if (k > 1) fact = (2..k).reduce(BigInt.one) { |acc, i| acc * BigInt.new(i) }\n return perm.call(n, k) / fact\n}\n\nSystem.print(\"A sample of permutations from 1 to 12:\")\nfor (n in 1..12) Fmt.print(\"$2d P $-2d = $i\", n, (n/3).floor, perm.call(n, (n/3).floor))\n\nSystem.print(\"\\nA sample of combinations from 10 to 60:\")\nfor (n in Stepped.new(10..60, 10)) {\n Fmt.print(\"$2d C $-2d = $i\", n, (n/3).floor, comb.call(n, (n/3).floor))\n}\n\nSystem.print(\"\\nA sample of permutations from 5 to 15000:\")\nvar na = [5, 50, 500, 1000, 5000, 15000]\nfor (n in na) {\n var k = (n/3).floor\n var s = perm.call(n, k).toString\n var l = s.count\n var e = (l <= 40) ? \"\" : \"... (%(l - 40) more digits)\"\n Fmt.print(\"$5d P $-4d = $s$s\", n, k, s.take(40).join(), e)\n}\n\nSystem.print(\"\\nA sample of combinations from 100 to 1000:\")\nfor (n in Stepped.new(100..1000, 100)) {\n var k = (n/3).floor\n var s = comb.call(n, k).toString\n var l = s.count\n var e = (l <= 40) ? \"\" : \"... (%(l - 40) more digits)\"\n Fmt.print(\"$4d C $-3d = $s$s\", n, k, s.take(40).join(), e)\n}\n", "language": "Wren" }, { "code": " const std = @import(\"std\");\n const num = f64;\n\n pub fn perm(n: num, k: num) num {\n var result: num = 1;\n var i: num = 0;\n while (i < k) : (i += 1) {\n result *= n - i;\n }\n return result;\n }\n\n pub fn comb(n: num, k: num) num {\n return perm(n, k) / perm(k, k);\n }\n\n pub fn main() !void {\n var stdout = std.io.getStdOut().writer();\n\n const p: num = 12;\n const c: num = 60;\n var j: num = 1;\n var k: num = 10;\n\n while (j < p) : (j += 1) {\n try stdout.print(\"P({d},{d}) = {d}\\n\", .{ p, j, @floor(perm(p, j)) });\n }\n\n while (k < c) : (k += 10) {\n try stdout.print(\"C({d},{d}) = {d}\\n\", .{ c, k, @floor(comb(c, k)) });\n }\n }\n", "language": "Zig" } ]
Combinations-and-permutations
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Comma_quibbling\n", "language": "00-META" }, { "code": "Comma quibbling is a task originally set by Eric Lippert in his [http://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx blog].\n\n\n;Task:\n\nWrite a function to generate a string output which is the concatenation of input words from a list/sequence where:\n# An input of no words produces the output string of just the two brace characters \"{}\".\n# An input of just one word, e.g. [\"ABC\"], produces the output string of the word inside the two braces, e.g. \"{ABC}\".\n# An input of two words, e.g. [\"ABC\", \"DEF\"], produces the output string of the two words inside the two braces with the words separated by the string \" and \", e.g. \"{ABC and DEF}\".\n# An input of three or more words, e.g. [\"ABC\", \"DEF\", \"G\", \"H\"], produces the output string of all but the last word separated by \", \" with the last word separated by \" and \" and all within braces; e.g. \"{ABC, DEF, G and H}\".\n\n<br>\nTest your function with the following series of inputs showing your output here on this page:\n* [] # (No input words).\n* [\"ABC\"]\n* [\"ABC\", \"DEF\"]\n* [\"ABC\", \"DEF\", \"G\", \"H\"]\n\n<br>\nNote: Assume words are non-empty strings of uppercase characters for this task.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F quibble(words)\n R S words.len\n 0\n ‘{}’\n 1\n ‘{’words[0]‘}’\n E\n ‘{’words[0.<(len)-1].join(‘, ’)‘ and ’words.last‘}’\n\nprint(quibble([‘’] * 0))\nprint(quibble([‘ABC’]))\nprint(quibble([‘ABC’, ‘DEF’]))\nprint(quibble([‘ABC’, ‘DEF’, ‘G’, ‘H’]))\n", "language": "11l" }, { "code": "* Comma quibbling 13/03/2017\nCOMMAQUI CSECT\n USING COMMAQUI,R13 base register\n B 72(R15) skip savearea\n DC 17F'0' savearea\n STM R14,R12,12(R13) save previous context\n ST R13,4(R15) link backward\n ST R15,8(R13) link forward\n LR R13,R15 set addressability\n LA R6,1 i=1\n DO WHILE=(C,R6,LE,=A(N)) do i=1 to hbound(t)\n LR R1,R6 i\n SLA R1,5 *32\n LA R2,T-32 @t(0)\n AR R1,R2 @t(i)\n MVC S1,0(R1) s1=t(i)\n MVC S2,=CL32'{' s2='{'\n LA R8,S2+1 s2ins=1\n MVC I2,=F'0' i2=0\n LA R7,1 j=1\n DO WHILE=(C,R7,LE,=A(L'T)) do j=1 to length(t)\n LA R1,S1 @s1\n BCTR R1,0 @s1-1\n AR R1,R7 @s1-1+j\n MVC CJ,0(R1) cj=mid(s1,j,1)\n CLI CJ,C' ' if cj=' '\n BE EXITJ then goto exitj\n IF CLI,CJ,EQ,C',' THEN if cj=\",\" then\n MVC 0(2,R8),=C', ' s2=s2||\", \"\n LA R8,2(R8) s2ins=s2ins+2\n LR R0,R8 s2ins\n LA R1,S2+1 @s2+1\n SR R0,R1 len(s2)-1\n ST R0,I2 i2=len(s2)-1\n ELSE , else\n MVC 0(1,R8),CJ s2=s2||cj\n LA R8,1(R8) s2ins=s2ins+1\n ENDIF , endif\n LA R7,1(R7) j++\n ENDDO , enddo j\nEXITJ MVI 0(R8),C'}' s2=s2||\"}\"\n LA R8,1(R8) s2ins=s2ins+1\n L R0,I2 i2\n IF LTR,R0,NZ,R0 THEN if i2<>0 then\n MVC S2B,S2 s2b=mid(s2,1,i2-1)\n LA R1,S2B-1 @s2b-1\n A R1,I2 +i2\n MVC 0(5,R1),=C' and ' s2b||\" and \"\n LA R1,5(R1) +5\n LA R2,S2+1 @s2+1\n A R2,I2 +i2\n LR R3,R8 s2ins\n LA R0,S2+1 @s2+1\n SR R3,R0 s2ins-(@s2+1)\n S R3,I2 -i2\n BCTR R3,0 -1\n EX R3,XMVC s2b||=mid(s2,i2+2)\n MVC S2,S2B s2=mid(s2,1,i2-1)||\" and \"||mid(s2,i2+2)\n ENDIF , endif\n XPRNT S2,L'S2 print s2\n LA R6,1(R6) i++\n ENDDO , enddo i\n L R13,4(0,R13) restore previous savearea pointer\n LM R14,R12,12(R13) restore previous context\n XR R15,R15 rc=0\n BR R14 exit\nXMVC MVC 0(0,R1),0(R2) mvc @r1,@r2\nN EQU (TEND-T)/L'T items of t\nT DC CL32' ',CL32'ABC',CL32'ABC,DEF',CL32'ABC,DEF,G,H'\nTEND DS 0C\nI2 DS F\nS1 DS CL(L'T)\nS2 DS CL(L'T)\nS2B DS CL(L'T)\nCJ DS CL1\n YREGS\n END COMMAQUI\n", "language": "360-Assembly" }, { "code": "\t\torg\t100h\n\t\tjmp\tdemo\n\t\t;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\t\t;; Given a list of strings in HL, and a pointer in DE, write\n\t\t;; the resulting string starting at DE.\nquibble:\tmvi\ta,'{'\t\t; Write the first {,\n\t\tstax\td\n\t\tinx \td\t\t; And increment the pointer\n\t\tpush\th\t\t; Keep start of list\n\t\tcall\tstrseqlen\t; Get length of list\n\t\tpop\th\t\t; Restore start of list\n\t\txra\ta\t\t; Is the list empty?\n\t\tora\tb\n\t\tjz\tquibend\t\t; If empty list, we're done.\nquibcopy:\tcall\tstrcpy\t\t; Copy current string into output\n\t\tinx\th\t\t; Advance input pointer to next string\n\t\tdcr\tb\t\t; Decrement counter\n\t\tjz\tquibend\t\t; If zero, that was the last string\n\t\tpush\th\t\t; Push input pointer\n\t\tmov\ta,b\t\t; Is the counter 1 now?\n\t\tcpi\t1\n\t\tlxi\th,quibcomma \t; Add a comma and space,\n\t\tjnz\tquibsep\t\t; unless the counter was 1,\n\t\tlxi\th,quiband\t; then use \" and \"\nquibsep:\tcall\tstrcpy\t\t; Copy the separator into the output\n\t\tpop\th\t\t; Restore the input pointer\n\t\tjmp\tquibcopy\t; Do the next string in the list\nquibend:\tmvi\ta,'}'\t\t; Write the final '}'\n\t\tstax\td\n\t\tinx\td\n\t\tmvi\ta,'$'\t\t; And write a string terminator\n\t\tstax \td\n\t\tret\nquibcomma:\tdb\t', $'\nquiband:\tdb\t' and $'\t\n\t\t;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\t\t;; Copy the string under HL to DE until the terminator $.\n\t\t;; The terminator is not copied; HL and DE are left one byte\n\t\t;; beyond the last byte copied.\nstrcpy:\t\tmov\ta,m\t\t; Get byte from input\n\t\tcpi\t'$'\t\t; Are we at the end?\n\t\trz\t\t\t; Then stop.\n\t\tstax\td\t\t; Otherwise, store byte at output\n\t\tinx\th\t\t; Increment the pointers\n\t\tinx\td\n\t\tjmp\tstrcpy\t\t; Copy next byte.\n\t\t;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\t\t;; Return in B the amount of strings in the string list in HL\nstrseqlen:\tmvi\ta,'$'\t\t; String end\n\t\tmvi\tb,0\t\t; String counter\ncount:\t\tcmp \tm\t\t; Empty string?\n\t\trz\t\t\t; Then we're done\n\t\tinr\tb\t\t; Otherwise, we have a string\nstrsrch:\tcmp\tm\t\t; Find the end of the string\n\t\tinx \th\n\t\tjnz\tstrsrch\n\t\tjmp\tcount\t\t\n\t\t;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\t\t;; Demo code: run 'quibble' on the examples\ndemo:\t\tmvi\tc,4\t\t; Four examples\n\t\tlxi\th,examples\t; Pointer to first example\nexample:\tpush\tb\t\t; Push example count\n\t\tlxi\td,buffer\t; Into the buffer,\n\t\tcall\tquibble\t\t; write the output of comma-quibbling\n\t\tinx\th\t\t; Point to next example\n\t\tpush\th\t\t; Save pointer to next example\n\t\tlxi\td,buffer\t; Write the output to the console\n\t\tmvi\tc,9\n\t\tcall\t5\n\t\tlxi\td,newline\t; Write a newline to the console\n\t\tmvi\tc,9\n\t\tcall\t5\n\t\tpop\th\t\t; Restore example pointer\n\t\tpop\tb\t\t; Restore example counter\n\t\tdcr\tc\t\t; If not zero,\n\t\tjnz \texample\t\t; do the next example.\n\t\tret\nnewline:\tdb\t10,13,'$'\t\t\t\t\nexamples:\tdb\t'$'\n\t\tdb\t'ABC$$'\n\t\tdb\t'ABC$DEF$$'\n\t\tdb\t'ABC$DEF$G$H$$'\nbuffer:\n", "language": "8080-Assembly" }, { "code": "HOW TO RETURN quibble words:\n PUT \"\" IN result\n PUT #words IN remaining\n FOR word IN words:\n PUT result^word IN result\n PUT remaining-1 IN remaining\n IF remaining = 1: PUT result^\" and \" IN result\n IF remaining > 1: PUT result^\", \" IN result\n RETURN \"{\" ^ result ^ \"}\"\n\nPUT {} IN tests\nINSERT {} IN tests\nINSERT {[1]: \"ABC\"} IN tests\nINSERT {[1]: \"ABC\"; [2]: \"DEF\"} IN tests\nINSERT {[1]: \"ABC\"; [2]: \"DEF\"; [3]: \"G\"; [4]: \"H\"} IN tests\nFOR test IN tests:\n WRITE quibble test/\n", "language": "ABC" }, { "code": "(defun examples ()\n (map '(lambda (words) (printc (quibble words)))\n '(() (ABC) (ABC DEF) (ABC DEF G H))))\n\n(defun quibble (words)\n (implode (list '{ (quibbles words) '})))\n\n(defun quibbles (words)\n (implode (conjunction words)))\n\n(defun conjunction (words)\n (cond ((null words)\n '())\n ((null (cdr words))\n words)\n ((null (cddr words))\n (list (car words) '! and! (cadr words)))\n (t\n (cons (car words)\n (cons ',! (conjunction (cdr words)))))))\n", "language": "Acornsoft-Lisp" }, { "code": "DEFINE PTR=\"CARD\"\n\nPROC Append(CHAR ARRAY text,suffix)\n BYTE POINTER srcPtr,dstPtr\n BYTE len\n\n len=suffix(0)\n IF text(0)+len>255 THEN\n len=255-text(0)\n FI\n IF len THEN\n srcPtr=suffix+1\n dstPtr=text+text(0)+1\n MoveBlock(dstPtr,srcPtr,len)\n text(0)==+suffix(0)\n FI\nRETURN\n\nPROC Quibble(PTR ARRAY items INT count CHAR ARRAY result)\n INT i\n\n result(0)=0\n Append(result,\"(\")\n FOR i=0 TO count-1\n DO\n Append(result,items(i))\n IF i=count-2 THEN\n Append(result,\" and \")\n ELSEIF i<count-2 THEN\n Append(result,\", \")\n FI\n OD\n Append(result,\")\")\nRETURN\n\nPROC Test(PTR ARRAY items BYTE count)\n CHAR ARRAY result(256)\n\n Quibble(items,count,result)\n PrintE(result)\nRETURN\n\nPROC Main()\n PTR ARRAY items(5)\n\n Test(items,0)\n\n items(0)=\"ABC\"\n Test(items,1)\n\n items(1)=\"DEF\"\n Test(items,2)\n\n items(2)=\"G\"\n Test(items,3)\n\n items(3)=\"H\"\n Test(items,4)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO, Ada.Command_Line; use Ada.Command_Line;\n\nprocedure Comma_Quibble is\n\nbegin\n case Argument_Count is\n when 0 => Ada.Text_IO.Put_Line(\"{}\");\n when 1 => Ada.Text_IO.Put_Line(\"{\" & Argument(1) & \"}\");\n when others =>\n\t Ada.Text_IO.Put(\"{\");\n\t for I in 1 .. Argument_Count-2 loop\n\t Ada.Text_IO.Put(Argument(I) & \", \");\n\t end loop;\n\t Ada.Text_IO.Put(Argument(Argument_Count-1) & \" and \" &\n\t\t Argument(Argument_Count) & \"}\");\n end case;\nend Comma_Quibble;\n", "language": "Ada" }, { "code": "# returns a string ( assumed to be of space-separated words ) with the words #\n# separated by \", \", except for the last which is separated from the rest by #\n# \" and \". The list is enclosed by braces #\nPROC to list = ( STRING words ) STRING:\n BEGIN\n # count the number of words #\n INT word count := 0;\n BOOL in word := FALSE;\n FOR char pos FROM LWB words TO UPB words\n DO\n IF NOT is upper( words[ char pos ] )\n THEN\n # not an upper-case letter, possibly a word has been ended #\n in word := FALSE\n ELSE\n # not a delimitor, possibly the start of a word #\n IF NOT in word\n THEN\n # we are starting a new word #\n word count +:= 1;\n in word := TRUE\n FI\n FI\n OD;\n\n # format the result #\n STRING result := \"{\";\n in word := FALSE;\n INT word number := 0;\n FOR char pos FROM LWB words TO UPB words\n DO\n IF NOT is upper( words[ char pos ] )\n THEN\n # not an upper-case letter, possibly a word has been ended #\n in word := FALSE\n ELSE\n # not a delimitor, possibly the start of a word #\n IF NOT in word\n THEN\n # we are starting a new word #\n word number +:= 1;\n in word := TRUE;\n IF word number > 1\n THEN\n # second or subsequent word - need a separator #\n result +:= IF word number = word count\n THEN # final word #\n \" and \"\n ELSE # non-final word #\n \", \"\n FI\n FI\n FI;\n # add the character to the result #\n result +:= words[ char pos ]\n FI\n OD;\n\n result + \"}\"\n END # to list # ;\n\n\n # procedure to test the to list PROC #\n PROC test to list = ( STRING words ) VOID:\n print( ( ( words\n + \": \"\n + to list( words )\n )\n , newline\n )\n );\n\n # test the to list PROC #\n test to list( \"\" );\n test to list( \"ABC\" );\n test to list( \"ABC DEF\" );\n test to list( \"ABC DEF G H\" )\n", "language": "ALGOL-68" }, { "code": "begin\n\n % returns a list of the words contained in wordString, separated by \", \", %\n % except for the last which is separated from the rest by \" and \". %\n % The words are enclosed by braces %\n string(256) procedure toList ( string(256) value words ) ;\n begin\n string(256) list;\n integer wordCount, wordNumber, listPos;\n logical inWord;\n\n % returns true if ch is an upper-case letter, false otherwise %\n % assumes the letters are consecutive in the character set %\n % (as in ascii) would not be correct if the character set was %\n % ebcdic (as in the original implementations of Algol W) %\n logical procedure isUpper ( string(1) value ch ) ; ch >= \"A\" and ch <= \"Z\" ;\n\n % adds a character to the result %\n procedure addChar( string(1) value ch ) ;\n begin\n list( listPos // 1 ) := ch;\n listPos := listPos + 1;\n end addChar ;\n\n % adds a string to the result %\n procedure addString( string(256) value str\n ; integer value len\n ) ;\n for strPos := 0 until len - 1 do addChar( str( strPos // 1 ) );\n\n % count the number of words %\n\n wordCount := 0;\n inWord := false;\n for charPos := 0 until 255\n do begin\n if isUpper( words( charPos // 1 ) ) then begin\n % not an upper-case letter, possibly a word has been ended %\n inWord := false\n end\n else begin\n % not a delimitor, possibly the start of a word %\n if not inWord then begin\n % we are starting a new word %\n wordCount := wordCount + 1;\n inWord := true\n end if_not_inWord\n end\n end for_charPos;\n\n % format the result %\n\n list := \"\";\n listPos := 0;\n inWord := false;\n wordNumber := 0;\n\n addChar( \"{\" );\n\n for charPos := 0 until 255\n do begin\n if not isUpper( words( charPos // 1 ) ) then begin\n % not an upper-case letter, possibly a word has been ended %\n inWord := false\n end\n else begin\n % not a delimitor, possibly the start of a word %\n if not inWord then begin\n % we are starting a new word %\n wordNumber := wordNumber + 1;\n inWord := true;\n if wordNumber > 1 then begin\n % second or subsequent word - need a separator %\n if wordNumber = wordCount then addString( \" and \", 5 ) % final word %\n else addString( \", \", 2 ) % non-final word %\n end\n end;\n % add the character to the result %\n addChar( words( charPos // 1 ) )\n end\n end for_charPos ;\n\n addChar( \"}\" );\n\n list\n end toList ;\n\n\n % procedure to test the toList procedure %\n procedure testToList ( string(256) value words ) ;\n begin\n string(256) list;\n list := toList( words );\n write( s_w := 0\n , words( 0 // 32 )\n , \": \"\n , list( 0 // 32 )\n )\n end testToList ;\n\n % test the toList procedure %\n testToList( \"\" );\n testToList( \"ABC\" );\n testToList( \"ABC DEF\" );\n testToList( \"ABC DEF G H\" );\n\nend.\n", "language": "ALGOL-W" }, { "code": "quibble ← 1⌽'}{',(∊⊢,¨2↓(' and ' ''),⍨(⊂', ')⍴⍨⍴)\n", "language": "APL" }, { "code": "-- quibble :: [String] -> String\non quibble(xs)\n if length of xs > 1 then\n set applyCommas to ¬\n compose([curry(my intercalate)'s |λ|(\", \"), my |reverse|, my tail])\n\n intercalate(\" and \", ap({applyCommas, my head}, {|reverse|(xs)}))\n else\n concat(xs)\n end if\nend quibble\n\n-- TEST -----------------------------------------------------------------------\non run\n script braces\n on |λ|(x)\n \"{\" & x & \"}\"\n end |λ|\n end script\n\n unlines(map(compose({braces, quibble}), ¬\n append({{}, {\"ABC\"}, {\"ABC\", \"DEF\"}, {\"ABC\", \"DEF\", \"G\", \"H\"}}, ¬\n map(|words|, ¬\n {\"One two three four\", \"Me myself I\", \"Jack Jill\", \"Loner\"}))))\nend run\n\n\n-- GENERIC FUNCTIONS ----------------------------------------------------------\n\n-- A list of functions applied to a list of arguments\n-- (<*> | ap) :: [(a -> b)] -> [a] -> [b]\non ap(fs, xs)\n set {intFs, intXs} to {length of fs, length of xs}\n set lst to {}\n repeat with i from 1 to intFs\n tell mReturn(item i of fs)\n repeat with j from 1 to intXs\n set end of lst to |λ|(contents of (item j of xs))\n end repeat\n end tell\n end repeat\n return lst\nend ap\n\n-- (++) :: [a] -> [a] -> [a]\non append(xs, ys)\n xs & ys\nend append\n\n-- compose :: [(a -> a)] -> (a -> a)\non compose(fs)\n script\n on |λ|(x)\n script\n on |λ|(a, f)\n mReturn(f)'s |λ|(a)\n end |λ|\n end script\n\n foldr(result, x, fs)\n end |λ|\n end script\nend compose\n\n-- concat :: [[a]] -> [a] | [String] -> String\non concat(xs)\n script append\n on |λ|(a, b)\n a & b\n end |λ|\n end script\n\n if length of xs > 0 and class of (item 1 of xs) is string then\n set unit to \"\"\n else\n set unit to {}\n end if\n foldl(append, unit, xs)\nend concat\n\n-- curry :: (Script|Handler) -> Script\non curry(f)\n script\n on |λ|(a)\n script\n on |λ|(b)\n |λ|(a, b) of mReturn(f)\n end |λ|\n end script\n end |λ|\n end script\nend curry\n\n-- foldl :: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n-- foldr :: (a -> b -> a) -> a -> [b] -> a\non foldr(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from lng to 1 by -1\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldr\n\n-- head :: [a] -> a\non head(xs)\n if length of xs > 0 then\n item 1 of xs\n else\n missing value\n end if\nend head\n\n-- intercalate :: Text -> [Text] -> Text\non intercalate(strText, lstText)\n set {dlm, my text item delimiters} to {my text item delimiters, strText}\n set strJoined to lstText as text\n set my text item delimiters to dlm\n return strJoined\nend intercalate\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n-- |reverse| :: [a] -> [a]\non |reverse|(xs)\n if class of xs is text then\n (reverse of characters of xs) as text\n else\n reverse of xs\n end if\nend |reverse|\n\n-- tail :: [a] -> [a]\non tail(xs)\n if length of xs > 1 then\n items 2 thru -1 of xs\n else\n {}\n end if\nend tail\n\n-- unlines :: [String] -> String\non unlines(xs)\n intercalate(linefeed, xs)\nend unlines\n\n-- words :: String -> [String]\non |words|(s)\n words of s\nend |words|\n", "language": "AppleScript" }, { "code": "quibble: $[sequence :block][\n if? 0 = size sequence\n -> return \"{}\"\n\n if? 1 = size sequence\n -> return ~\"{|sequence\\0|}\"\n\n last: pop 'sequence\n return ~« {|join.with: \", \" sequence| and |last|}\n]\n\nsentences: [\n\t[]\n\t[\"ABC\"]\n\t[\"ABC\" \"DEF\"]\n\t[\"ABC\" \"DEF\" \"G\" \"H\"]\n]\n\nloop sentences 'sentence [\n\tprint quibble sentence\n]\n", "language": "Arturo" }, { "code": "fun quibble(s):\n let result = s.join(' and ').replace(|| and ||, \", \", length(s) - 1)\n return \"{ $result }\"\n\nlet s = [\n []\n [\"ABC\"]\n [\"ABC\", \"DEF\"]\n [\"ABC\", \"DEF\", \"G\", \"H\"]\n]\n\nfor i in s:\n print(quibble i)\n", "language": "Astro" }, { "code": "MsgBox % quibble([])\nMsgBox % quibble([\"ABC\"])\nMsgBox % quibble([\"ABC\", \"DEF\"])\nMsgBox % quibble([\"ABC\", \"DEF\", \"G\", \"H\"])\n\nquibble(d) {\n\ts:=\"\"\n\tfor i, e in d\n\t{\n\t\tif (i<d.MaxIndex()-1)\n\t\t\ts:= s . e . \", \"\n\t\telse if (i=d.MaxIndex()-1)\n\t\t\ts:= s . e . \" and \"\n\t\telse\n\t\t\ts:= s . e\n\t}\n\treturn \"{\" . s . \"}\"\n}\n", "language": "AutoHotkey" }, { "code": "function quibble(a, n, i, s) {\n\tfor (i = 1; i < n - 1; i++) s = s a[i] \", \"\n\ti = n - 1; if (i > 0) s = s a[i] \" and \"\n\tif (n > 0) s = s a[n]\n\treturn \"{\" s \"}\"\n}\n\nBEGIN {\n\tprint quibble(a, 0)\n\tn = split(\"ABC\", b); print quibble(b, n)\n\tn = split(\"ABC DEF\", c); print quibble(c, n)\n\tn = split(\"ABC DEF G H\", d); print quibble(d, n)\n}\n", "language": "AWK" }, { "code": "@echo off\nsetlocal enabledelayedexpansion\n\n::THE MAIN THING...\necho.\nset inp=[]\ncall :quibble\nset inp=[\"ABC\"]\ncall :quibble\nset inp=[\"ABC\",\"DEF\"]\ncall :quibble\nset inp=[\"ABC\",\"DEF\",\"G\",\"H\"]\ncall :quibble\necho.\npause\nexit /b\n::/THE MAIN THING...\n\n::THE FUNCTION\n:quibble\nset cont=0\nset proc=%inp:[=%\nset proc=%proc:]=%\n\nfor %%x in (%proc%) do (\n\tset /a cont+=1\n\tset x=%%x\n\tset str!cont!=!x:\"=!\n)\nset /a bef=%cont%-1\nset output=%str1%\nif %cont%==2 (set output=%str1% and %str2%)\nif %cont% gtr 2 (\n\tfor /l %%y in (2,1,%bef%) do (\n\t\tset output=!output!^, !str%%y!\n\t)\n\tset output=!output! and !str%cont%!\n)\necho {!output!}\ngoto :EOF\n::/THE FUNCTION\n", "language": "Batch-File" }, { "code": "get \"libhdr\"\n\n// Add a character to the end of a string\nlet addch(s, ch) be\n$( s%0 := s%0 + 1\n s%(s%0) := ch\n$)\n// Add s2 to the end of s1\nand adds(s1, s2) be\n for i = 1 to s2%0 do\n addch(s1, s2%i)\n\n// Comma quibbling on strs, which should be a 0-terminated\n// vector of string pointers.\nlet quibble(strs, buf) = valof\n$( buf%0 := 0\n addch(buf, '{')\n until !strs = 0 do\n $( addch(buf, '\"')\n adds(buf, !strs)\n addch(buf, '\"')\n unless strs!1 = 0\n test strs!2 = 0\n then adds(buf, \" and \")\n else adds(buf, \", \")\n strs := strs + 1\n $)\n addch(buf, '}')\n resultis buf\n$)\n\nlet start() be\n$( let words = vec 4\n let buf = vec 63\n\n words!0 := 0\n writef(\"%S*N\", quibble(words, buf))\n\n words!0 := \"ABC\" ; words!1 := 0\n writef(\"%S*N\", quibble(words, buf))\n\n words!1 := \"DEF\" ; words!2 := 0\n writef(\"%S*N\", quibble(words, buf))\n\n words!2 := \"G\" ; words!3 := \"H\" ; words!4 := 0\n writef(\"%S*N\", quibble(words, buf))\n$)\n", "language": "BCPL" }, { "code": "( :?L1\n& ABC:?L2\n& ABC DEF:?L3\n& ABC DEF G H:?L4\n& L1 L2 L3 L4:?names\n& ( quibble\n = w\n . !arg:%?w (% %:?arg)\n & !w \", \" quibble$!arg\n | !arg:%?w %?arg&!w \" and \" quibble$!arg\n | !arg\n )\n& (concat=.str$(\"{\" quibble$!arg \"}\"))\n& whl\n ' (!names:%?name ?names&out$(!name concat$!!name))\n);\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\nchar *quib(const char **strs, size_t size)\n{\n\n size_t len = 3 + ((size > 1) ? (2 * size + 1) : 0);\n size_t i;\n\n for (i = 0; i < size; i++)\n len += strlen(strs[i]);\n\n char *s = malloc(len * sizeof(*s));\n if (!s)\n {\n perror(\"Can't allocate memory!\\n\");\n exit(EXIT_FAILURE);\n }\n\n strcpy(s, \"{\");\n switch (size) {\n case 0: break;\n case 1: strcat(s, strs[0]);\n break;\n default: for (i = 0; i < size - 1; i++)\n {\n strcat(s, strs[i]);\n if (i < size - 2)\n strcat(s, \", \");\n else\n strcat(s, \" and \");\n }\n strcat(s, strs[i]);\n break;\n }\n strcat(s, \"}\");\n return s;\n}\n\nint main(void)\n{\n const char *test[] = {\"ABC\", \"DEF\", \"G\", \"H\"};\n char *s;\n\n for (size_t i = 0; i < 5; i++)\n {\n s = quib(test, i);\n printf(\"%s\\n\", s);\n free(s);\n }\n return EXIT_SUCCESS;\n}\n", "language": "C" }, { "code": "#include <iostream>\n\ntemplate<class T>\nvoid quibble(std::ostream& o, T i, T e) {\n o << \"{\";\n if (e != i) {\n T n = i++;\n const char* more = \"\";\n while (e != i) {\n o << more << *n;\n more = \", \";\n n = i++;\n }\n o << (*more?\" and \":\"\") << *n;\n }\n o << \"}\";\n}\n\nint main(int argc, char** argv) {\n char const* a[] = {\"ABC\",\"DEF\",\"G\",\"H\"};\n for (int i=0; i<5; i++) {\n quibble(std::cout, a, a+i);\n std::cout << std::endl;\n }\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Linq;\n\nnamespace CommaQuibbling\n{\n internal static class Program\n {\n #region Static Members\n\tprivate static string Quibble(string[] input)\n\t{\n return\n String.Format(\"{{{0}}}\",\n String.Join(\"\",\n input.Reverse().Zip(\n new [] { \"\", \" and \" }.Concat(Enumerable.Repeat(\", \", int.MaxValue)),\n (x, y) => x + y).Reverse()));\n\t}\n\n\n private static void Main()\n {\n Console.WriteLine( Quibble( new string[] {} ) );\n Console.WriteLine( Quibble( new[] {\"ABC\"} ) );\n Console.WriteLine( Quibble( new[] {\"ABC\", \"DEF\"} ) );\n Console.WriteLine( Quibble( new[] {\"ABC\", \"DEF\", \"G\", \"H\"} ) );\n\n Console.WriteLine( \"< Press Any Key >\" );\n Console.ReadKey();\n }\n\n #endregion\n }\n}\n", "language": "C-sharp" }, { "code": "(defn quibble [sq]\n (let [sep (if (pos? (count sq)) \" and \" \"\")]\n (apply str\n (concat \"{\" (interpose \", \" (butlast sq)) [sep (last sq)] \"}\"))))\n\n; Or, using clojure.pprint's cl-format, which implements common lisp's format:\n(defn quibble-f [& args]\n (clojure.pprint/cl-format nil \"{~{~a~#[~; and ~:;, ~]~}}\" args))\n\n(def test\n #(doseq [sq [[]\n [\"ABC\"]\n [\"ABC\", \"DEF\"]\n [\"ABC\", \"DEF\", \"G\", \"H\"]]]\n ((comp println %) sq)))\n\n(test quibble)\n(test quibble-f)\n", "language": "Clojure" }, { "code": "quibble = proc (words: array[string]) returns (string)\n out: string := \"{\"\n last: int := array[string]$high(words)\n\n for i: int in array[string]$indexes(words) do\n out := out || words[i]\n if i < last-1 then\n out := out || \", \"\n elseif i = last-1 then\n out := out || \" and \"\n end\n end\n return(out || \"}\")\nend quibble\n\nstart_up = proc ()\n as = array[string]\n aas = array[as]\n po: stream := stream$primary_output()\n\n testcases: aas := aas$\n [as$[],\n as$[\"ABC\"],\n as$[\"ABC\",\"DEF\"],\n as$[\"ABC\",\"DEF\",\"G\",\"H\"]]\n\n for testcase: as in aas$elements(testcases) do\n stream$putl(po, quibble(testcase))\n end\nend start_up\n", "language": "CLU" }, { "code": " >>SOURCE FORMAT IS FREE\nIDENTIFICATION DIVISION.\nPROGRAM-ID. comma-quibbling-test.\n\nENVIRONMENT DIVISION.\nCONFIGURATION SECTION.\nREPOSITORY.\n FUNCTION comma-quibbling\n .\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01 strs-area.\n 03 strs-len PIC 9.\n 03 strs PIC X(5)\n OCCURS 0 TO 9 TIMES\n DEPENDING ON strs-len.\n\nPROCEDURE DIVISION.\n MOVE \"ABC\" TO strs (1)\n MOVE \"DEF\" TO strs (2)\n MOVE \"G\" TO strs (3)\n MOVE \"H\" TO strs (4)\n\n PERFORM VARYING strs-len FROM 0 BY 1 UNTIL strs-len > 4\n DISPLAY FUNCTION comma-quibbling(strs-area)\n END-PERFORM\n .\nEND PROGRAM comma-quibbling-test.\n\n\nIDENTIFICATION DIVISION.\nFUNCTION-ID. comma-quibbling.\n\nDATA DIVISION.\nLOCAL-STORAGE SECTION.\n01 i PIC 9.\n\n01 num-extra-words PIC 9.\n\nLINKAGE SECTION.\n01 strs-area.\n 03 strs-len PIC 9.\n 03 strs PIC X(5)\n OCCURS 0 TO 9 TIMES\n DEPENDING ON strs-len.\n\n01 str PIC X(50).\n\nPROCEDURE DIVISION USING strs-area RETURNING str.\n EVALUATE strs-len\n WHEN ZERO\n MOVE \"{}\" TO str\n GOBACK\n\n WHEN 1\n MOVE FUNCTION CONCATENATE(\"{\", FUNCTION TRIM(strs (1)), \"}\")\n TO str\n GOBACK\n END-EVALUATE\n\n MOVE FUNCTION CONCATENATE(FUNCTION TRIM(strs (strs-len - 1)),\n \" and \", FUNCTION TRIM(strs (strs-len)), \"}\")\n TO str\n\n IF strs-len > 2\n SUBTRACT 2 FROM strs-len GIVING num-extra-words\n PERFORM VARYING i FROM num-extra-words BY -1 UNTIL i = 0\n MOVE FUNCTION CONCATENATE(FUNCTION TRIM(strs (i)), \", \", str)\n TO str\n END-PERFORM\n END-IF\n\n MOVE FUNCTION CONCATENATE(\"{\", str) TO str\n .\nEND FUNCTION comma-quibbling.\n", "language": "COBOL" }, { "code": "quibble = ([most..., last]) ->\n '{' +\n (most.join ', ') +\n (if most.length then ' and ' else '') +\n (last or '') +\n '}'\n\nconsole.log quibble(s) for s in [ [], [\"ABC\"], [\"ABC\", \"DEF\"],\n [\"ABC\", \"DEF\", \"G\", \"H\" ] ]\n", "language": "CoffeeScript" }, { "code": "100 DIM A$(3)\n110 FOR TC=1 TO 4\n120 : READ A: IF A=0 THEN 160\n130 : FOR I=0 TO A-1\n140 : READ A$(I)\n150 : NEXT I\n160 : GOSUB 200\n170 : PRINT CQ$\n180 NEXT TC\n190 END\n200 CQ$=\"[\"\n210 IF A < 1 THEN 290\n220 CQ$ = CQ$ + A$(0)\n230 IF A < 2 THEN 290\n240 IF A < 3 THEN 280\n250 FOR I=1 TO A - 2\n260 : CQ$ = CQ$ + \", \" + A$(I)\n270 NEXT I\n280 CQ$ = CQ$ + \" AND \" + A$(A - 1)\n290 CQ$ = CQ$ + \"]\"\n300 RETURN\n310 DATA 0\n320 DATA 1, ABC\n330 DATA 2, ABC, DEF\n340 DATA 4, ABC, DEF, G, H\n", "language": "Commodore-BASIC" }, { "code": "(defun quibble (&rest args)\n (format t \"{~{~a~#[~; and ~:;, ~]~}}\" args))\n\n(quibble)\n(quibble \"ABC\")\n(quibble \"ABC\" \"DEF\")\n(quibble \"ABC\" \"DEF\" \"G\" \"H\")\n", "language": "Common-Lisp" }, { "code": "include \"cowgol.coh\";\n\nsub quibble(words: [[uint8]],\n length: intptr,\n buf: [uint8]):\n (out: [uint8]) is\n sub append(s: [uint8]) is\n while [s] != 0 loop\n [buf] := [s];\n buf := @next buf;\n s := @next s;\n end loop;\n end sub;\n\n out := buf;\n\n append(\"{\");\n while length > 0 loop\n append([words]);\n words := @next words;\n case length is\n when 1: break;\n when 2: append(\" and \");\n when else: append(\", \");\n end case;\n length := length - 1;\n end loop;\n append(\"}\");\n\n [buf] := 0;\nend sub;\n\nvar w1: [uint8][] := {};\nvar w2: [uint8][] := {\"ABC\"};\nvar w3: [uint8][] := {\"ABC\",\"DEF\"};\nvar w4: [uint8][] := {\"ABC\",\"DEF\",\"G\",\"H\"};\n\nprint(quibble(&w1[0], @sizeof w1, LOMEM)); print_nl();\nprint(quibble(&w2[0], @sizeof w2, LOMEM)); print_nl();\nprint(quibble(&w3[0], @sizeof w3, LOMEM)); print_nl();\nprint(quibble(&w4[0], @sizeof w4, LOMEM)); print_nl();\n", "language": "Cowgol" }, { "code": "import std.stdio, std.string;\n\nstring quibbler(in string[] seq) pure /*nothrow*/ {\n if (seq.length <= 1)\n return format(\"{%-(%s, %)}\", seq);\n else\n return format(\"{%-(%s, %) and %s}\", seq[0 .. $-1], seq[$-1]);\n}\n\nvoid main() {\n //foreach (immutable test; [[],\n foreach (const test; [[],\n [\"ABC\"],\n [\"ABC\", \"DEF\"],\n [\"ABC\", \"DEF\", \"G\", \"H\"]])\n test.quibbler.writeln;\n}\n", "language": "D" }, { "code": "import std.stdio, std.string, std.algorithm, std.conv, std.array;\n\nenum quibbler = (in string[] a) pure =>\n \"{%-(%s and %)}\".format(a.length < 2 ? a :\n [a[0 .. $-1].join(\", \"), a.back]);\n\nvoid main() {\n [[], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]]\n .map!quibbler.writeln;\n}\n", "language": "D" }, { "code": "[(q)uibble: main entry point. print brackets, calling n in between if stack not\n empty.]sx\n[ [{]n z 0 !=n [}]pR ]sq\n\n[(n)onempty: if more than 1 item, call m. then print top of stack.]sx\n[ z 1 !=m n ]sn\n\n[(m)ore: call f to flip stack into r register, call p to print most of it,\n then pop the last item back onto the main stack so it's there to be printed\n after we return]sx\n[ lfx lpx Lr ]sm\n\n[(f)lip: utility routine to reverse the stack into the r register]sx\n[ Sr z 0 !=f ]sf\n\n[(p)rint: get next item from stack in r register and print it. If there are\n more than 2 items left on the register stack (which never drops below one\n item), print a comma (c) and recurse. If there are exactly two items left,\n print \" and \" (a) and return.]sx\n[ Lr n 2 yr >c 2 yr =a 2 yr >p]sp\n\n[(c)omma: utility routine to print a comma followed by a space]sx\n[ [, ]n ]sc\n\n[(a)and: utility routine to print \" and \"]sx\n[ [ and ]n ]sa\n\n[run tests]sx\nlqx\n[ABC] lqx\n[ABC] [DEF] lqx\n[ABC] [DEF] [G] [H] lqx\n", "language": "Dc" }, { "code": "$ list = \"[]\"\n$ gosub comma_quibbling\n$ write sys$output return_string\n$\n$ list = \"[\"\"ABC\"\"]\"\n$ gosub comma_quibbling\n$ write sys$output return_string\n$\n$ list = \"[\"\"ABC\"\", \"\"DEF\"\"]\"\n$ gosub comma_quibbling\n$ write sys$output return_string\n$\n$ list = \"[\"\"ABC\"\", \"\"DEF\"\", \"\"G\"\", \"\"H\"\"]\"\n$ gosub comma_quibbling\n$ write sys$output return_string\n$\n$ exit\n$\n$ comma_quibbling:\n$ list = list - \"[\" - \"]\"\n$ return_string = \"{}\"\n$ if list .eqs. \"\" then $ return\n$ return_string = \"{\" + f$element( 0, \",\", list ) - \"\"\"\" - \"\"\"\"\n$ if f$locate( \",\", list ) .eq. f$length( list ) then $ goto done2\n$ i = 1\n$ loop:\n$ word = f$element( i, \",\", list ) - \"\"\"\" - \"\"\"\"\n$ if word .eqs. \",\" then $ goto done1\n$ return_string = return_string - \"^\" + \"^,\" + word\n$ i = i + 1\n$ goto loop\n$ done1:\n$ return_string = f$element( 0, \"^\", return_string ) + \" and\" + ( f$element( 1, \"^\", return_string ) - \",\" )\n$ done2:\n$ return_string = return_string + \"}\"\n$ return\n", "language": "DCL" }, { "code": "func$ tolist s$ .\n s$[] = strsplit s$ \" \"\n r$ = \"{\"\n n = len s$[]\n for i = 1 to n - 2\n r$ &= s$[i] & \", \"\n .\n if n > 0\n if n > 1\n r$ &= s$[n - 1] & \" and \"\n .\n r$ &= s$[n]\n .\n r$ &= \"}\"\n return r$\n.\nprint tolist \"\"\nprint tolist \"ABC\"\nprint tolist \"ABC DEF\"\nprint tolist \"ABC DEF G H\"\n", "language": "EasyLang" }, { "code": "(lib 'match)\n\n(define (quibble words)\n (match words\n [ null \"{}\"]\n [ (a) (format \"{ %a }\" a)]\n [ (a b) (format \"{ %a and %a }\" a b)]\n [( a ... b c) (format \"{ %a %a and %a }\" (for/string ([w a]) (string-append w \", \")) b c)]\n [else 'bad-input]))\n\n\n;; output\n\n (for ([t '(() (\"ABC\") (\"ABC\" \"DEF\") (\"ABC\" \"DEF\" \"G\" \"H\"))])\n (writeln t '----> (quibble t)))\n\nnull ----> \"{}\"\n(\"ABC\") ----> \"{ ABC }\"\n(\"ABC\" \"DEF\") ----> \"{ ABC and DEF }\"\n(\"ABC\" \"DEF\" \"G\" \"H\") ----> \"{ ABC, DEF, G and H }\"\n", "language": "EchoLisp" }, { "code": "class\n\tAPPLICATION\n\ncreate\n\tmake\n\nfeature\n\n\t\tmake\n\t\t\t-- Test of the feature comma_quibbling.\n\t\tlocal\n\t\t\tl: LINKED_LIST [STRING]\n\t\tdo\n\t\t\tcreate l.make\n\t\t\tio.put_string (comma_quibbling (l) + \"%N\")\n\t\t\tl.extend (\"ABC\")\n\t\t\tio.put_string (comma_quibbling (l) + \"%N\")\n\t\t\tl.extend (\"DEF\")\n\t\t\tio.put_string (comma_quibbling (l) + \"%N\")\n\t\t\tl.extend (\"G\")\n\t\t\tl.extend (\"H\")\n\t\t\tio.put_string (comma_quibbling (l) + \"%N\")\n\t\tend\n\n\tcomma_quibbling (l: LINKED_LIST [STRING]): STRING\n\t\t\t-- Elements of 'l' seperated by a comma or an and where appropriate.\n\t\trequire\n\t\t\tl_not_void: l /= Void\n\t\tdo\n\t\t\tcreate Result.make_empty\n\t\t\tResult.extend ('{')\n\t\t\tif l.is_empty then\n\t\t\t\tResult.append (\"}\")\n\t\t\telseif l.count = 1 then\n\t\t\t\tResult.append (l [1] + \"}\")\n\t\t\telse\n\t\t\t\tResult.append (l [1])\n\t\t\t\tacross\n\t\t\t\t\t2 |..| (l.count - 1) as c\n\t\t\t\tloop\n\t\t\t\t\tResult.append (\", \" + l [c.item])\n\t\t\t\tend\n\t\t\t\tResult.append (\" and \" + l [l.count] + \"}\")\n\t\t\tend\n\t\tend\n\nend\n", "language": "Eiffel" }, { "code": "defmodule RC do\n def generate( list ), do: \"{#{ generate_content(list) }}\"\n\n defp generate_content( [] ), do: \"\"\n defp generate_content( [x] ), do: x\n defp generate_content( [x1, x2] ), do: \"#{x1} and #{x2}\"\n defp generate_content( xs ) do\n [last, second_to_last | t] = Enum.reverse( xs )\n with_commas = for x <- t, do: x <> \",\"\n Enum.join(Enum.reverse([last, \"and\", second_to_last | with_commas]), \" \")\n end\nend\n\nEnum.each([[], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]], fn list ->\n IO.inspect RC.generate(list)\nend)\n", "language": "Elixir" }, { "code": "-module( comma_quibbling ).\n\n-export( [task/0] ).\n\ntask() -> [generate(X) || X <- [[], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]]].\n\n\n\ngenerate( List ) -> \"{\" ++ generate_content(List) ++ \"}\".\n\ngenerate_content( [] ) -> \"\";\ngenerate_content( [X] ) -> X;\ngenerate_content( [X1, X2] ) -> string:join( [X1, \"and\", X2], \" \" );\ngenerate_content( Xs ) ->\n\t[Last, Second_to_last | T] = lists:reverse( Xs ),\n\tWith_commas = [X ++ \",\" || X <- T],\n\tstring:join(lists:reverse([Last, \"and\", Second_to_last | With_commas]), \" \").\n", "language": "Erlang" }, { "code": "let quibble list =\n let rec inner = function\n | [] -> \"\"\n | [x] -> x\n | [x;y] -> sprintf \"%s and %s\" x y\n | h::t -> sprintf \"%s, %s\" h (inner t)\n sprintf \"{%s}\" (inner list)\n\n// test interactively\nquibble []\nquibble [\"ABC\"]\nquibble [\"ABC\"; \"DEF\"]\nquibble [\"ABC\"; \"DEF\"; \"G\"]\nquibble [\"ABC\"; \"DEF\"; \"G\"; \"H\"]\n", "language": "F-Sharp" }, { "code": "> quibble [];;\nval it : string = \"{}\"\n> quibble [\"ABC\"];;\nval it : string = \"{ABC}\"\n> quibble [\"ABC\"; \"DEF\"];;\nval it : string = \"{ABC and DEF}\"\n> quibble [\"ABC\"; \"DEF\"; \"G\"];;\nval it : string = \"{ABC, DEF and G}\"\n> quibble [\"ABC\"; \"DEF\"; \"G\"; \"H\"];;\nval it : string = \"{ABC, DEF, G and H}\"\n", "language": "F-Sharp" }, { "code": "let quibble quibbler quibblee = Seq.zip quibblee quibbler //Sorry, just too good a line to miss, back in my Latin classes\n", "language": "F-Sharp" }, { "code": "let fN n = quibble (List.mapi(fun n _->match n with 0->\"\" |1-> \" and \" |_->\", \") n |> List.rev) n\nprintf \"{\"; fN [\"ABC\"; \"DEF\"; \"G\"; \"H\"] |> Seq.iter(fun(n,g)->printf \"%s%s\" n g); printfn\"}\"\nprintf \"{\"; fN [\"ABC\"; \"DEF\"; \"G\"] |> Seq.iter(fun(n,g)->printf \"%s%s\" n g); printfn\"}\"\nprintf \"{\"; fN [\"ABC\"; \"DEF\"] |> Seq.iter(fun(n,g)->printf \"%s%s\" n g); printfn\"}\"\nprintf \"{\"; fN [\"ABC\"] |> Seq.iter(fun(n,g)->printf \"%s%s\" n g); printfn\"}\"\nprintf \"{\"; fN [] |> Seq.iter(fun(n,g)->printf \"%s%s\" n g); printfn\"}\"\n", "language": "F-Sharp" }, { "code": "USING: inverse qw sequences ;\n\n: (quibble) ( seq -- seq' )\n {\n { [ { } ] [ \"\" ] }\n { [ 1array ] [ ] }\n { [ 2array ] [ \" and \" glue ] }\n [ unclip swap (quibble) \", \" glue ]\n } switch ;\n\n: quibble ( seq -- str ) (quibble) \"{%s}\" sprintf ;\n\n{ } qw{ ABC } qw{ ABC DEF } qw{ ABC DEF G H }\n[ quibble print ] 4 napply\n", "language": "Factor" }, { "code": ": read bl parse ;\n: not-empty? ( c-addr u -- c-addr u true | false ) ?dup-if true else drop false then ;\n: third-to-last 2rot ;\n: second-to-last 2swap ;\n\n: quibble\n\t.\" {\"\n\tread read begin read not-empty? while third-to-last type .\" , \" repeat\n\tsecond-to-last not-empty? if type then\n\tnot-empty? if .\" and \" type then\n\t.\" }\" cr ;\n\t\nquibble\nquibble ABC\nquibble ABC DEF\nquibble ABC DEF G H\n", "language": "Forth" }, { "code": " SUBROUTINE QUIBBLE(TEXT,OXFORDIAN)\t!Punctuates a list with commas and stuff.\n CHARACTER*(*) TEXT\t!The text, delimited by spaces.\n LOGICAL OXFORDIAN\t!Just so.\n INTEGER IST(6),LST(6)\t!Start and stop positions.\n INTEGER N,L,I\t\t!Counters.\n INTEGER L1,L2\t\t!Fingers for the scan.\n INTEGER MSG\t\t!Output unit.\n COMMON /IODEV/MSG\t!Share.\nChop the text into words.\n N = 0\t\t!No words found.\n L = LEN(TEXT)\t!Multiple trailing spaces - no worries.\n L2 = 0\t\t!Syncopation: where the previous chomp ended.\n 10 L1 = L2\t\t!Thus, where a fresh scan should follow.\n 11 L1 = L1 + 1\t\t!Advance one.\n IF (L1.GT.L) GO TO 20\t\t!Finished yet?\n IF (TEXT(L1:L1).LE.\" \") GO TO 11\t!No. Skip leading spaces.\n L2 = L1\t\t\t!Righto, L1 is the first non-blank.\n 12 L2 = L2 + 1\t\t!Scan through the non-blanks.\n IF (L2.GT.L) GO TO 13\t!Is it safe to look?\n IF (TEXT(L2:L2).GT.\" \") GO TO 12\t!Yes. Speed through non-blanks.\n 13 N = N + 1\t\t\t!Righto, a word is found in TEXT(L1:L2 - 1)\n IST(N) = L1\t\t!So, recall its first character.\n LST(N) = L2 - 1\t\t!And its last.\n IF (L2.LT.L) GO TO 10\t!Perhaps more text follows.\nComma time...\n 20 WRITE (MSG,21) \"{\"\t!Start the output.\n 21 FORMAT (A,$)\t\t!The $, obviously, specifies that the line is not finished.\n DO I = 1,N\t\t!Step through the texts, there possibly being none.\n IF (I.GT.1) THEN\t\t!If there has been a predecessor, supply separators.\n IF (I.LT.N) THEN\t\t\t!Up to the last two, it's easy.\n WRITE (MSG,21) \", \"\t\t\t!Always just a comma.\n ELSE IF (OXFORDIAN) THEN\t\t!But after the penultimate item, what?\n WRITE (MSG,21) \", and \"\t\t\t!Supply the comma omitted above: a double-power separator.\n ELSE\t\t\t\t!One fewer comma, with possible ambiguity arising.\n WRITE (MSG,21) \" and \"\t\t\t!A single separator.\n END IF\t\t\t\t!So much for the style.\n END IF\t\t\t!Enough with the separation.\n WRITE (MSG,21) TEXT(IST(I):LST(I))\t!The text at last!\n END DO\t\t\t!On to the next text.\n WRITE (MSG,\"('}')\")\t!End the line, marking the end of the text.\n END\t\t!That was fun.\n\n PROGRAM ENCOMMA\t!Punctuate a list with commas.\n CHARACTER*(666) TEXT\t!Holds the text. Easily long enough.\n INTEGER KBD,MSG,INF\t!Now for some messing.\n COMMON /IODEV/MSG,KBD\t!Pass the word.\n KBD = 5\t!Standard input.\n MSG = 6\t!Standard output.\n INF = 10\t!Suitable for a disc file.\n OPEN (INF,FILE=\"List.txt\",ACTION = \"READ\")\t!Attach one.\n\n 10 WRITE (MSG,11) \"To insert commas into lists...\"\t!Announce.\n 11 FORMAT (A)\t\t\t!Just the text.\n 12 READ (INF,11,END = 20) TEXT\t!Grab the text, with trailing spaces to fill out TEXT.\n CALL QUIBBLE(TEXT,.FALSE.)\t!One way to quibble.\n GO TO 12\t\t\t\t!Try for another.\n\n 20 REWIND (INF)\t\t\t!Back to the start of the file.\n WRITE (MSG,11)\t\t\t!Set off a bit.\n WRITE (MSG,11) \"Oxford style...\"\t!Announce the proper style.\n 21 READ (INF,11,END = 30) TEXT\t!Grab the text.\n CALL QUIBBLE(TEXT,.TRUE.)\t\t!The other way to quibble.\n GO TO 21\t\t\t\t!Have another try.\n\nClosedown\n 30 END\t!All files are closed by exiting.\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nSub Split(s As String, sep As String, result() As String)\n Dim As Integer i, j, count = 0\n Dim temp As String\n Dim As Integer position(Len(s) + 1)\n position(0) = 0\n For i = 0 To Len(s) - 1\n For j = 0 To Len(sep) - 1\n If s[i] = sep[j] Then\n count += 1\n position(count) = i + 1\n End If\n Next j\n Next i\n position(count + 1) = Len(s) + 1\n Redim result(count)\n For i = 1 To count + 1\n result(i - 1) = Mid(s, position(i - 1) + 1, position(i) - position(i - 1) - 1)\n Next\nEnd Sub\n\nFunction CommaQuibble(s As String) As String\n Dim i As Integer\n Dim As String result\n Dim As String words()\n s = Trim(s, Any \"[]\"\"\")\n ' Now remove internal quotes\n Split s, \"\"\"\", words()\n s = \"\"\n For i = 0 To UBound(words)\n s &= words(i)\n Next\n ' Now split 's' using the comma as separator\n Erase words\n Split s, \",\", words()\n ' And re-assemble the string in the desired format\n result = \"{\"\n For i = 0 To UBound(words)\n If i = 0 Then\n result &= words(i)\n ElseIf i = UBound(words) Then\n result &= \" and \" & words(i)\n Else\n result &= \", \" + words(i)\n EndIf\n Next\n Return result & \"}\"\nEnd Function\n\n' As 3 of the strings contain embedded quotes these need to be doubled in FB\nPrint CommaQuibble(\"[]\")\nPrint CommaQuibble(\"[\"\"ABC\"\"]\")\nPrint CommaQuibble(\"[\"\"ABC\"\",\"\"DEF\"\"]\")\nPrint CommaQuibble(\"[\"\"ABC\"\",\"\"DEF\"\",\"\"G\"\",\"\"H\"\"]\")\nPrint\nPrint \"Press any key to quit the program\"\nSleep\n", "language": "FreeBASIC" }, { "code": "quibble[enum] :=\n{\n list = toArray[enum] // This makes it work on any enumerating expression\n size = length[list]\n if size >= 2\n return \"{\" + join[\", \", first[list, size-1]] + \" and \" + last[list] + \"}\"\n else\n return \"{\" + join[\"\", list] + \"}\"\n}\n\ndata = [[], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]]\nfor line = data\n println[quibble[line]]\n", "language": "Frink" }, { "code": "include \"NSLog.incl\"\n\nlocal fn CommaQuibber( string as CFStringRef ) as CFStringRef\n CFStringRef tempStr\n NSUInteger i\n\n tempStr = fn StringByReplacingOccurrencesOfString( string, @\"[\", @\"\" )\n tempStr = fn StringByReplacingOccurrencesOfString( tempStr, @\"]\", @\"\" )\n tempStr = fn StringByReplacingOccurrencesOfString( tempStr, @\" \", @\"\" )\n tempStr = fn StringByReplacingOccurrencesOfString( tempStr, @\"\\\"\", @\"\" )\n\n CFMutableStringRef quibStr = fn MutableStringWithCapacity(0)\n\n CFArrayRef arr = fn StringComponentsSeparatedByString( tempStr, @\",\" )\n NSUInteger count = len(arr)\n select switch ( count )\n case 0 : MutableStringSetString( quibStr, @\"{}\" ) : break\n case 1 : MutableStringSetString( quibStr, fn StringWithFormat( @\"{%@}\", arr[0] ) ) : break\n case 2 : MutableStringSetString( quibStr, fn StringWithFormat( @\"{%@ and %@}\", arr[0], arr[1] ) ) : break\n case else\n MutableStringAppendFormat( quibStr, @\"{\" )\n for i = 0 to count -1\n if ( i != count -1 )\n MutableStringAppendFormat( quibStr, @\"%@, \", arr[i] )\n else\n MutableStringAppendFormat( quibStr, @\"and %@}\", arr[i] )\n end if\n next\n end select\nend fn = quibStr\n\nNSLog( @\"%@\", fn CommaQuibber( @\"[]\" ) )\nNSLog( @\"%@\", fn CommaQuibber( @\"[\\\"ABC\\\"]\" ) )\nNSLog( @\"%@\", fn CommaQuibber( @\"[\\\"ABC\\\", \\\"DEF\\\"]\" ) )\nNSLog( @\"%@\", fn CommaQuibber( @\"[\\\"ABC\\\", \\\"DEF\\\", \\\"G\\\", \\\"H\\\"]\" ) )\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "local fn CommaQuibbler( s as CFArrayRef ) as CFStringRef\n CFStringRef result = NULL\n\n select ( len(s) )\n case 0: exit fn = @\"{}\"\n case 1: exit fn = fn StringWithFormat( @\"{%@}\", s[0] )\n case 2: exit fn = fn StringWithFormat( @\"{%@ and %@}\", s[0], s[1] )\n case else\n result = fn StringWithFormat( @\"{%@}\", fn ArrayComponentsJoinedByString( s, @\", \" ) )\n CFRange lastComma = fn StringRangeOfStringWithOptions( result, @\",\", NSBackwardsSearch )\n result = fn StringByReplacingCharactersInRange( result, lastComma, @\" and\" )\n end select\nend fn = result\n\nprint fn CommaQuibbler( @[] )\nprint fn CommaQuibbler( @[@\"ABC\"] )\nprint fn CommaQuibbler( @[@\"ABC\", @\"DEF\"] )\nprint fn CommaQuibbler( @[@\"ABC\", @\"DEF\", @\"G\", @\"H\"] )\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\nDim sInput As String[] = [\"\", \"ABC\", \"ABC DEF\", \"ABC DEF G H\"]\nDim sTemp As String\n\nFor Each sTemp In sInput\n Print sTemp & \" = \";\n sTemp = Replace(sTemp, \" \", \",\")\n If RInStr(sTemp, \",\") > 0 Then\n sTemp = Mid(sTemp, 1, RInStr(sTemp, \",\") - 1) & \" and \" & Mid(sTemp, RInStr(sTemp, \",\") + 1)\n End If\n sTemp = \"{\" & sTemp & \"}\"\n Print sTemp\nNext\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc q(s []string) string {\n switch len(s) {\n case 0:\n return \"{}\"\n case 1:\n return \"{\" + s[0] + \"}\"\n case 2:\n return \"{\" + s[0] + \" and \" + s[1] + \"}\"\n default:\n return \"{\" +\n strings.Join(s[:len(s)-1], \", \") +\n \" and \" +\n s[len(s)-1] +\n \"}\"\n }\n}\n\nfunc main() {\n fmt.Println(q([]string{}))\n fmt.Println(q([]string{\"ABC\"}))\n fmt.Println(q([]string{\"ABC\", \"DEF\"}))\n fmt.Println(q([]string{\"ABC\", \"DEF\", \"G\", \"H\"}))\n}\n", "language": "Go" }, { "code": "def commaQuibbling = { it.size() < 2 ? \"{${it.join(', ')}}\" : \"{${it[0..-2].join(', ')} and ${it[-1]}}\" }\n", "language": "Groovy" }, { "code": "['{}': [], '{ABC}': ['ABC'], '{ABC and DEF}': ['ABC', 'DEF'], '{ABC, DEF, G and H}': ['ABC', 'DEF', 'G', 'H']].each { expected, input ->\n println \"Verifying commaQuibbling($input) == $expected\"\n assert commaQuibbling(input) == expected\n}\n", "language": "Groovy" }, { "code": "quibble ws = \"{\" ++ quibbles ws ++ \"}\"\n where quibbles [] = \"\"\n quibbles [a] = a\n quibbles [a,b] = a ++ \" and \" ++ b\n quibbles (a:bs) = a ++ \", \" ++ quibbles bs\n\nmain = mapM_ (putStrLn . quibble) $\n [[], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]] ++\n (map words [\"One two three four\", \"Me myself I\", \"Jack Jill\", \"Loner\" ])\n", "language": "Haskell" }, { "code": "import Data.List (intercalate)\n\n--------------------- COMMA QUIBBLING --------------------\n\nquibble :: [String] -> String\nquibble ws@(_ : _ : _) =\n intercalate\n \" and \"\n ( [intercalate \", \" . reverse . tail, head]\n <*> [reverse ws]\n )\nquibble xs = concat xs\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n mapM_ (putStrLn . (`intercalate` [\"{\", \"}\"]) . quibble) $\n [[], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]]\n <> ( words\n <$> [ \"One two three four\",\n \"Me myself I\",\n \"Jack Jill\",\n \"Loner\"\n ]\n )\n", "language": "Haskell" }, { "code": "procedure main()\n every write(quibble([] | [\"ABC\"] | [\"ABC\",\"DEF\"] | [\"ABC\",\"DEF\",\"G\",\"H\"]))\nend\n\nprocedure quibble(A)\n join := s := \"\"\n while s := pull(A)||join||s do join := if *join = 0 then \" and \" else \", \"\n return \"{\"||s||\"}\"\nend\n", "language": "Icon" }, { "code": "quibLast2=: ' and ' joinstring (2 -@<. #) {. ]\nwithoutLast2=: ([: # _2&}.) {. ]\nquibble=: '{', '}' ,~ ', ' joinstring withoutLast2 , <@quibLast2\n", "language": "J" }, { "code": " Tests=: (<<<3){(i.5)<@{.\"0 1;:'ABC DEF G H'\n quibble every Tests\n{}\n{ABC}\n{ABC and DEF}\n{ABC, DEF, G and H}\n", "language": "J" }, { "code": "commaand=: 1 ;@}.&, ] ,.~ 1 |.!.(<' and ') (<', ')\"0\nquibble=: '{','}',~ commaand\n", "language": "J" }, { "code": "public class Quibbler {\n\n\tpublic static String quibble(String[] words) {\n\t\tString qText = \"{\";\n\t\tfor(int wIndex = 0; wIndex < words.length; wIndex++) {\n\t\t\tqText += words[wIndex] + (wIndex == words.length-1 ? \"\" :\n\t\t\t\t\t\t wIndex == words.length-2 ? \" and \" :\n\t\t\t\t\t\t \", \";\n\t\t}\n\t\tqText += \"}\";\n\t\treturn qText;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(quibble(new String[]{}));\n\t\tSystem.out.println(quibble(new String[]{\"ABC\"}));\n\t\tSystem.out.println(quibble(new String[]{\"ABC\", \"DEF\"}));\n\t\tSystem.out.println(quibble(new String[]{\"ABC\", \"DEF\", \"G\"}));\n\t\tSystem.out.println(quibble(new String[]{\"ABC\", \"DEF\", \"G\", \"H\"}));\n\t}\n}\n", "language": "Java" }, { "code": "function quibble(words) {\n return \"{\" +\n words.slice(0, words.length-1).join(\",\") +\n (words.length > 1 ? \" and \" : \"\") +\n (words[words.length-1] || '') +\n \"}\";\n}\n\n[[], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]].forEach(\n function(s) {\n console.log(quibble(s));\n }\n);\n", "language": "JavaScript" }, { "code": "(() => {\n 'use strict';\n\n // ----------------- COMMA QUIBBLING -----------------\n\n // quibble :: [String] -> String\n const quibble = xs =>\n 1 < xs.length ? (\n intercalate(' and ')(\n ap([\n compose(\n intercalate(', '),\n reverse,\n tail\n ),\n head\n ])([reverse(xs)])\n )\n ) : concat(xs);\n\n\n // ---------------------- TEST -----------------------\n const main = () =>\n unlines(\n map(compose(x => '{' + x + '}', quibble))(\n append([\n [],\n [\"ABC\"],\n [\"ABC\", \"DEF\"],\n [\"ABC\", \"DEF\", \"G\", \"H\"]\n ])(\n map(words)([\n \"One two three four\",\n \"Me myself I\",\n \"Jack Jill\",\n \"Loner\"\n ])\n )\n ));\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // ap (<*>) :: [(a -> b)] -> [a] -> [b]\n const ap = fs =>\n // The sequential application of each of a list\n // of functions to each of a list of values.\n // apList([x => 2 * x, x => 20 + x])([1, 2, 3])\n // -> [2, 4, 6, 21, 22, 23]\n xs => fs.flatMap(f => xs.map(f));\n\n\n // append (++) :: [a] -> [a] -> [a]\n const append = xs =>\n // A list defined by the\n // concatenation of two others.\n ys => xs.concat(ys);\n\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n // A function defined by the right-to-left\n // composition of all the functions in fs.\n fs.reduce(\n (f, g) => x => f(g(x)),\n x => x\n );\n\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs => (\n ys => 0 < ys.length ? (\n ys.every(Array.isArray) ? (\n []\n ) : ''\n ).concat(...ys) : ys\n )(xs);\n\n\n // head :: [a] -> a\n const head = xs => (\n ys => ys.length ? (\n ys[0]\n ) : undefined\n )(list(xs));\n\n\n // intercalate :: String -> [String] -> String\n const intercalate = s =>\n // The concatenation of xs\n // interspersed with copies of s.\n xs => xs.join(s);\n\n\n // list :: StringOrArrayLike b => b -> [a]\n const list = xs =>\n // xs itself, if it is an Array,\n // or an Array derived from xs.\n Array.isArray(xs) ? (\n xs\n ) : Array.from(xs || []);\n\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f =>\n // The list obtained by applying f\n // to each element of xs.\n // (The image of xs under f).\n xs => [...xs].map(f);\n\n\n // reverse :: [a] -> [a]\n const reverse = xs =>\n 'string' !== typeof xs ? (\n xs.slice(0).reverse()\n ) : xs.split('').reverse().join('');\n\n\n // tail :: [a] -> [a]\n const tail = xs =>\n // A new list consisting of all\n // items of xs except the first.\n xs.slice(1);\n\n\n // unlines :: [String] -> String\n const unlines = xs =>\n // A single string formed by the intercalation\n // of a list of strings with the newline character.\n xs.join('\\n');\n\n\n // words :: String -> [String]\n const words = s =>\n // List of space-delimited sub-strings.\n s.split(/\\s+/);\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "function quibble(words) {\n var words2 = words.join()\n\n var words3 = [...words2].reverse().join('');\n var res = words3.replace(\",\", \" dna \");\n var words4 = [...res].reverse().join('');\n\n return '{'+words4+'}';\n}\n", "language": "JavaScript" }, { "code": "def quibble:\n if length == 0 then \"\"\n elif length == 1 then .[0]\n else (.[0:length-1] | join(\", \")) + \" and \" + .[length-1]\n end\n | \"{\" + . + \"}\";\n", "language": "Jq" }, { "code": "( [], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]) | quibble\n", "language": "Jq" }, { "code": "jq -n -r -f Comma_quibbling.jq\n{}\n{ABC}\n{ABC and DEF}\n{ABC, DEF, G and H}\n", "language": "Jq" }, { "code": "function quibble(arr::Array)\n if isempty(arr) rst = \"\" else rst = \"$(arr[end])\" end\n if length(arr) > 1 rst = join(arr[1:end-1], \", \") * \" and \" * rst end\n return \"{\" * rst * \"}\"\nend\n\n@show quibble([])\n@show quibble([\"ABC\"])\n@show quibble([\"ABC\", \"DEF\"])\n@show quibble([\"ABC\", \"DEF\", \"G\", \"H\"])\n", "language": "Julia" }, { "code": "// version 1.0.6\n\nfun commaQuibble(s: String): String {\n val t = s.trim('[', ']').replace(\" \", \"\").replace(\"\\\"\", \"\")\n val words = t.split(',')\n val sb = StringBuilder(\"{\")\n for (i in 0 until words.size) {\n sb.append(when (i) {\n 0 -> \"\"\n words.lastIndex -> \" and \"\n else -> \", \"\n })\n sb.append(words[i])\n }\n return sb.append(\"}\").toString()\n}\n\nfun main(args: Array<String>) {\n val inputs = arrayOf(\n \"\"\"[]\"\"\",\n \"\"\"[\"ABC\"]\"\"\",\n \"\"\"[\"ABC\", \"DEF\"]\"\"\",\n \"\"\"[\"ABC\", \"DEF\", \"G\", \"H\"]\"\"\"\n )\n for (input in inputs) println(\"${input.padEnd(24)} -> ${commaQuibble(input)}\")\n}\n", "language": "Kotlin" }, { "code": "fp.quibble = (&words) -> {\n\t$len $= @&words\n\t\n\t$output = \\{\\e\n\t\n\t$i\n\trepeat($[i], $len) {\n\t\t$output += &words[$i] ||| ($i == -|$len?\\e:($i == $len - 2?\\sand\\s:\\,\\s))\n\t}\n\t\n\t$output += \\}\\e\n\t\n\treturn $output\n}\n\nfn.println(fp.quibble(fn.arrayOf()))\nfn.println(fp.quibble(fn.arrayOf(ABC)))\nfn.println(fp.quibble(fn.arrayOf(ABC, DEF)))\nfn.println(fp.quibble(fn.arrayOf(ABC, DEF, G, H)))\n", "language": "Lang" }, { "code": "#!/usr/bin/lasso9\n\nlocal(collection =\n\tarray(\n\t\tarray,\n\t\tarray(\"ABC\"),\n\t\tarray(\"ABC\", \"DEF\"),\n\t\tarray(\"ABC\", \"DEF\", \"G\", \"H\")\n\t)\n)\n\nwith words in #collection do {\n\tif(#words -> size > 1) => {\n\t\tlocal(last = #words -> last)\n\t\t#words -> removelast\n\t\tstdoutnl('{' + #words -> join(', ') + ' and ' + #last'}')\n\telse(#words -> size == 1)\n\t\tstdoutnl('{' + #words -> first + '}')\n\telse\n\t\tstdoutnl('{}')\n\t}\n\n}\n", "language": "Lasso" }, { "code": "do\n read in$\n if in$ =\"END\" then wait\n w =wordCount( in$)\n select case w\n case 0\n o$ =\"{}\"\n case 1\n o$ =\"{\" +in$ +\"}\"\n case 2\n o$ =\"{\" +word$( in$, 1) +\" and \" +word$( in$, 2) +\"}\"\n case else\n o$ =\"{\"\n o$ =o$ +word$( in$, 1)\n for k =2 to w -1\n o$ =o$ +\", \" +word$( in$, k)\n next k\n o$ =o$ +\" and \" +word$( in$, w) +\"}\"\n end select\n if w =1 then\n print \"'\"; in$; \"'\"; \" held \"; w; \" word. \"; tab( 30); o$\n else\n print \"'\"; in$; \"'\"; \" held \"; w; \" words. \"; tab( 30); o$\n end if\n loop until 0\n\n wait\n\n function wordCount( IN$)\n wordCount =1\n for i =1 to len( IN$)\n if mid$( IN$, i, 1) =\" \" then wordCount =wordCount +1\n next i\n end function\n\n end\n\n data \"\" 'No input words.\n data \"ABC\" 'One input word.\n data \"ABC DEF\" 'Two words.\n data \"ABC DEF G\" 'Three words.\n data \"ABC DEF G H\" 'Four words.\n\n data \"END\" 'Sentinel for EOD.\n", "language": "Liberty-BASIC" }, { "code": "to join :delimiter :list [:result []]\n output cond [\n [ [empty? :list] :result ]\n [ [empty? :result] (join :delimiter butfirst :list first :list) ]\n [ else (join :delimiter butfirst :list\n (word :result :delimiter first :list)) ]\n ]\nend\n\nto quibble :list\n local \"length\n make \"length count :list\n make \"text (\n ifelse [:length <= 2] [\n (join \"\\ and\\ :list)\n ] [\n (join \"\\ and\\ (sentence join \",\\ butlast :list last :list))\n ])\n output ifelse [empty? :text] \"\\{\\} [(word \"\\{ :text \"\\})]\nend\n\nforeach [ [] [ABC] [ABC DEF] [ABC DEF G H] ] [\n print quibble ?\n]\n\nbye\n", "language": "Logo" }, { "code": "function quibble (strTab)\n local outString, join = \"{\"\n for strNum = 1, #strTab do\n if strNum == #strTab then\n join = \"\"\n elseif strNum == #strTab - 1 then\n join = \" and \"\n else\n join = \", \"\n end\n outString = outString .. strTab[strNum] .. join\n end\n return outString .. '}'\nend\n\nlocal testCases = {\n {},\n {\"ABC\"},\n {\"ABC\", \"DEF\"},\n {\"ABC\", \"DEF\", \"G\", \"H\"}\n}\nfor _, input in pairs(testCases) do print(quibble(input)) end\n", "language": "Lua" }, { "code": "Module Checkit {\n function f$ {\n what$=mid$(trim$(letter$),2)\n what$=Left$(what$, len(what$)-1)\n flush ' erase any argument from stack\n Data param$(what$)\n m=stack.size\n document resp$=\"{\"\n if m>2 then {\n shift m-1, 2 ' get last two as first two\n push letter$+\" and \"+letter$\n m-- ' one less\n shiftback m ' move to last position\n }\n while not empty {\n resp$=letter$+if$(not empty->\", \", \"\")\n }\n =resp$+\"}\"\n\n }\n \\\\ we use ? for Print\n ? f$({[]})\n ? f$({[\"ABC\"]})\n ? f$({[\"ABC\", \"DEF\"]})\n ? f$({[\"ABC\",\"DEF\", \"G\", \"H\"]})\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "Module Checkit {\n function f$ {\n what$=filter$(trim$(letter$), chr$(34))\n what$=Mid$(what$, 2, len(what$)-2)\n count=Len(what$)-Len(filter$(what$,\",\"))\n if count>2 then m=rinstr(what$, \", \") : insert m, 2 what$=\" and \"\n =\"{\"+what$+\"}\"\n }\n ? f$({[]})\n ? f$({[\"ABC\"]})\n ? f$({[\"ABC\", \"DEF\"]})\n ? f$({[\"ABC\",\"DEF\", \"G\", \"H\"]})\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "Module Checkit {\n function f$(ar) {\n flush\n Data ! ar\n m=stack.size\n document resp$=\"{\"\n if m>2 then {\n shift m-1, 2 ' get last two as first two\n push letter$+\" and \"+letter$\n m-- ' one less\n shiftback m ' move to last position\n }\n while not empty {\n resp$=letter$+if$(not empty->\", \", \"\")\n }\n =resp$+\"}\"\n }\n ? f$((,))\n ? f$((\"ABC\",))\n ? f$((\"ABC\", \"DEF\"))\n ? f$((\"ABC\",\"DEF\", \"G\", \"H\"))\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "Quibble := proc( los )\n uses StringTools;\n Fence( proc()\n if los = [] then\n \"\"\n elif numelems( los ) = 1 then\n los[ 1 ]\n else\n cat( Join( los[ 1 .. -2 ], \", \" ), \" and \", los[ -1 ] )\n end if\n end(), \"{\", \"}\" )\nend proc:\n", "language": "Maple" }, { "code": "> Quibble([]);\n \"{}\"\n\n> Quibble( [ \"ABC\" ] );\n \"{ABC}\"\n\n> Quibble( [ \"ABC\", \"DEF\" ] );\n \"{ABC and DEF}\"\n\n> Quibble( [\"ABC\", \"DEF\", \"G\", \"H\"] );\n \"{ABC, DEF, G and H}\"\n", "language": "Maple" }, { "code": "quibble[words___] :=\n ToString@{StringJoin@@\n Replace[Riffle[{words}, \", \"],\n {most__, \", \", last_} -> {most, \" and \", last}]}\n", "language": "Mathematica" }, { "code": "function r = comma_quibbling(varargin)\n\tif isempty(varargin)\n\t\tr = '';\n\telseif length(varargin)==1;\n\t\tr = varargin{1};\n\telse\n\t\tr = [varargin{end-1},' and ', varargin{end}];\n\t\tfor k=length(varargin)-2:-1:1,\n\t\t\tr = [varargin{k}, ', ', r];\n\t\tend\n\tend\nend;\n", "language": "MATLAB" }, { "code": "fn separate words: =\n(\n\tif words == unsupplied or words == undefined or classof words != array then return \"{}\"\n\t\telse\n\t\t(\n\t\t\tlocal toReturn = \"{\"\n\t\t\tlocal pos = 1\n\t\t\twhile pos <= words.count do\n\t\t\t(\n\t\t\t\tif pos == 1 then (append toReturn words[pos]; pos+=1)\n\t\t\t\telse\n\t\t\t\t(\t\n\t\t\t\t\tif pos <= words.count-1 then (append toReturn (\", \"+words[pos]); pos+=1)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tappend toReturn (\" and \" + words[pos])\n\t\t\t\t\t\t\tpos +=1\n\t\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t)\n\t\t\treturn (toReturn+\"}\")\n\t\t)\n)\n", "language": "MAXScript" }, { "code": "separate words:#()\n\"{}\"\nseparate words:#(\"ABC\")\n\"{ABC}\"\nseparate words:#(\"ABC\",\"DEF\")\n\"{ABC and DEF}\"\nseparate words:#(\"ABC\",\"DEF\",\"G\",\"H\")\n\"{ABC, DEF, G and H}\"\n", "language": "MAXScript" }, { "code": "main :: [sys_message]\nmain = [Stdout (show test ++ \": {\" ++ quibble test ++ \"}\\n\") | test <- tests]\n\ntests :: [[[char]]]\ntests = [ [],\n [\"ABC\"],\n [\"ABC\",\"DEF\"],\n [\"ABC\",\"DEF\",\"G\",\"H\"] ]\n\nquibble :: [[char]]->[char]\nquibble [] = []\nquibble [word] = word\nquibble [word1,word2] = word1 ++ \" and \" ++ word2\nquibble (word:words) = word ++ \", \" ++ quibble words\n", "language": "Miranda" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\nrunSample(arg)\nreturn\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod quibble(arg) public static\n parse arg '[' lst ']'\n lst = lst.changestr('\"', '').space(1)\n lc = lst.lastpos(',')\n if lc > 0 then\n lst = lst.insert('and', lc).overlay(' ', lc)\n return '{'lst'}'\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod runSample(arg) private static\n lists = ['[]', - -- {}\n '[\"ABC\"]', - -- {ABC}\n '[\"ABC\", \"DEF\"]', - -- {ABC and DEF}\n '[\"ABC\", \"DEF\", \"G\", \"H\"]'] -- {ABC, DEF, G and H}\n loop lst over lists\n say lst.right(30) ':' quibble(lst)\n end lst\n return\n", "language": "NetRexx" }, { "code": "proc commaQuibble(s: openArray[string]): string =\n result = \"\"\n for i, c in s:\n if i > 0: result.add (if i < s.high: \", \" else: \" and \")\n result.add c\n result = \"{\" & result & \"}\"\n\nvar s = @[@[], @[\"ABC\"], @[\"ABC\", \"DEF\"], @[\"ABC\", \"DEF\", \"G\", \"H\"]]\nfor i in s:\n echo commaQuibble(i)\n", "language": "Nim" }, { "code": "MODULE CommaQuibbling;\nIMPORT\n NPCT:Args,\n Strings,\n Out;\n\nVAR\n str: ARRAY 256 OF CHAR;\n\n PROCEDURE Do(VAR s: ARRAY OF CHAR);\n VAR\n aux: ARRAY 128 OF CHAR;\n i,params: LONGINT;\n BEGIN\n params := Args.Number() - 1;\n CASE params OF\n 0:\n COPY(\"{}\",s)\n |1:\n Args.At(1,aux);\n Strings.Append(\"{\",s);\n Strings.Append(aux,s);\n Strings.Append(\"}\",s);\n ELSE\n Strings.Append(\"{\",s);\n FOR i := 1 TO params - 1 DO\n Args.At(i,aux);\n Strings.Append(aux,s);\n IF i # params - 1 THEN\n Strings.Append(\", \",s)\n ELSE\n Strings.Append(\" and \", s)\n END\n END;\n Args.At(params,aux);\n Strings.Append(aux,s);\n Strings.Append(\"}\",s)\n END;\n\n END Do;\n\nBEGIN\n Do(str);\n Out.String(\":> \");Out.String(str);Out.Ln\nEND CommaQuibbling.\n", "language": "Oberon" }, { "code": "class Quibbler {\n function : Quibble(words : String[]) ~ String {\n text := \"{\";\n\n each(i : words) {\n text += words[i];\n if(i < words->Size() - 2) {\n text += \", \";\n }\n else if(i = words->Size() - 2) {\n text += \" and \";\n };\n };\n text += \"}\";\n\n return text;\n }\n\n function : Main(args : String[]) ~ Nil {\n words := String->New[0];\n Quibble(words)->PrintLine();\n\n words := [\"ABC\"];\n Quibble(words)->PrintLine();\n\n words := [\"ABC\", \"DEF\"];\n Quibble(words)->PrintLine();\n\n words := [\"ABC\", \"DEF\", \"G\", \"H\"];\n Quibble(words)->PrintLine();\n }\n}\n", "language": "Objeck" }, { "code": "open Printf\n\nlet quibble list =\n let rec aux = function\n | a :: b :: c :: d :: rest -> a ^ \", \" ^ aux (b :: c :: d :: rest)\n | [a; b; c] -> sprintf \"%s, %s and %s}\" a b c\n | [a; b] -> sprintf \"%s and %s}\" a b\n | [a] -> sprintf \"%s}\" a\n | [] -> \"}\" in\n \"{\" ^ aux list\n\nlet test () =\n [[];\n [\"ABC\"];\n [\"ABC\"; \"DEF\"];\n [\"ABC\"; \"DEF\"; \"G\"; \"H\"]]\n |> List.iter (fun list -> print_endline (quibble list))\n", "language": "OCaml" }, { "code": "open Core\n\nlet quibble = function\n | [| |] -> \"{}\"\n | [| a |] -> sprintf \"{%s}\" a\n | array ->\n let last, rest = Array.last array, Array.slice array 0 (-1) in\n sprintf \"{%s and %s}\" (String.concat_array ~sep:\", \" rest) last\n\nlet test () =\n [[||];\n [|\"ABC\"|];\n [|\"ABC\"; \"DEF\"|];\n [|\"ABC\"; \"DEF\"; \"G\"; \"H\"|]]\n |> List.iter ~f:(fun list -> print_endline (quibble list))\n", "language": "OCaml" }, { "code": ": quibbing(l) -- string\n| i s |\n StringBuffer new \"{\" <<\n l size dup 1- ->s loop: i [\n l at(i) <<\n i s < ifTrue: [ \", \" << continue ]\n i s == ifTrue: [ \" and \" << ]\n ]\n \"}\" << dup freeze ;\n", "language": "Oforth" }, { "code": "(define (quibble . args)\n (display \"{\")\n (let loop ((args args))\n (unless (null? args) (begin\n (display (car args))\n (cond\n ((= 1 (length args)) #t)\n ((= 2 (length args))\n (display \" and \"))\n (else\n (display \", \")))\n (loop (cdr args)))))\n (print \"}\"))\n\n; testing =>\n(quibble)\n(quibble \"ABC\")\n(quibble \"ABC\" \"DEF\")\n(quibble \"ABC\" \"DEF\" \"G\" \"H\")\n", "language": "Ol" }, { "code": "comma(v)={\n if(#v==0, return(\"{}\"));\n if(#v==1, return(Str(\"{\"v[1]\"}\")));\n my(s=Str(\"{\",v[1]));\n for(i=2,#v-1,s=Str(s,\", \",v[i]));\n Str(s,\" and \",v[#v],\"}\")\n};\ncomma([])\ncomma([\"ABC\"])\ncomma([\"ABC\", \"DEF\"])\ncomma([\"ABC\", \"DEF\", \"G\", \"H\"])\n", "language": "PARI-GP" }, { "code": "program CommaQuibbling;\n\nuses\n SysUtils,\n Classes,\n StrUtils;\n\nconst\n OuterBracket =['[', ']'];\n\ntype\n\n{$IFNDEF FPC}\n SizeInt = LongInt;\n{$ENDIF}\n\n\n\n { TCommaQuibble }\n\n TCommaQuibble = class(TStringList)\n private\n function GetCommaquibble: string;\n procedure SetCommaQuibble(AValue: string);\n public\n property CommaQuibble: string read GetCommaquibble write SetCommaQuibble;\n end;\n\n{$IFNDEF FPC} // Delphi support\n\nfunction WordPosition(const N: Integer; const S: string; const WordDelims:\n TSysCharSet): SizeInt;\nvar\n PS, P, PE: PChar;\n Count: Integer;\nbegin\n Result := 0;\n Count := 0;\n PS := PChar(pointer(S));\n PE := PS + Length(S);\n P := PS;\n while (P < PE) and (Count <> N) do\n begin\n while (P < PE) and (P^ in WordDelims) do\n inc(P);\n if (P < PE) then\n inc(Count);\n if (Count <> N) then\n while (P < PE) and not (P^ in WordDelims) do\n inc(P)\n else\n Result := (P - PS) + 1;\n end;\nend;\n\nfunction ExtractWordPos(N: Integer; const S: string; const WordDelims:\n TSysCharSet; out Pos: Integer): string;\nvar\n i, j, l: SizeInt;\nbegin\n j := 0;\n i := WordPosition(N, S, WordDelims);\n if (i > High(Integer)) then\n begin\n Result := '';\n Pos := -1;\n Exit;\n end;\n Pos := i;\n if (i <> 0) then\n begin\n j := i;\n l := Length(S);\n while (j <= l) and not (S[j] in WordDelims) do\n inc(j);\n end;\n SetLength(Result, j - i);\n if ((j - i) > 0) then\n Result := copy(S, i, j - i);\nend;\n\nfunction ExtractWord(N: Integer; const S: string; const WordDelims: TSysCharSet):\n string; inline;\nvar\n i: SizeInt;\nbegin\n Result := ExtractWordPos(N, S, WordDelims, i);\nend;\n{$ENDIF}\n\n{ TCommaQuibble }\n\nprocedure TCommaQuibble.SetCommaQuibble(AValue: string);\nbegin\n AValue := ExtractWord(1, AValue, OuterBracket);\n commatext := AValue;\nend;\n\nfunction TCommaQuibble.GetCommaquibble: string;\nvar\n x: Integer;\n Del: string;\nbegin\n result := '';\n Del := ', ';\n for x := 0 to Count - 1 do\n begin\n result := result + Strings[x];\n if x = Count - 2 then\n Del := ' and '\n else if x = Count - 1 then\n Del := '';\n result := result + Del;\n end;\n result := '{' + result + '}';\nend;\n\nconst\n TestData: array[0..7] of string = ('[]', '[\"ABC\"]', '[\"ABC\", \"DEF\"]',\n '[\"ABC\", \"DEF\", \"G\", \"H\"]', '', '\"ABC\"', '\"ABC\", \"DEF\"', '\"ABC\", \"DEF\", \"G\", \"H\"');\n\nvar\n Quibble: TCommaQuibble;\n TestString: string;\n\nbegin\n Quibble := TCommaQuibble.Create;\n\n for TestString in TestData do\n begin\n Quibble.CommaQuibble := TestString;\n writeln(Quibble.CommaQuibble);\n end;\nend.\n", "language": "Pascal" }, { "code": "sub comma_quibbling :prototype(@) {\n return \"{$_}\" for\n @_ < 2 ? \"@_\" :\n join(', ', @_[0..@_-2]) . ' and ' . $_[-1];\n}\n\nprint comma_quibbling(@$_), \"\\n\" for\n [], [qw(ABC)], [qw(ABC DEF)], [qw(ABC DEF G H)];\n", "language": "Perl" }, { "code": "use 5.01;\nsub comma_quibbling {\n my $last = pop // '';\n return '{'. (@_ ? (join ', ', @_).' and '.$last : $last).'}';\n}\n\nsay for map {comma_quibbling(@$_)}\n [], [qw(ABC)], [qw(ABC DEF)], [qw(ABC DEF G H)];\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">quibble</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">)>=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">[-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">..-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">[-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]&</span><span style=\"color: #008000;\">\" and \"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">[-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #008000;\">\"{\"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\", \"</span><span style=\"color: #0000FF;\">)&</span><span style=\"color: #008000;\">\"}\"</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ABC\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ABC\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"DEF\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ABC\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"DEF\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"G\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"H\"</span><span style=\"color: #0000FF;\">}}</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">quibble</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\n\nfunction quibble($arr) {\n\n switch (count($arr)) {\n\n case 0:\n return '{}';\n\n case 1:\n return \"{{$arr[0]}}\";\n\n default:\n $left = implode(', ', array_slice($arr, 0, -1));\n $right = array_slice($arr, -1)[0];\n return \"{{$left} and {$right}}\";\n\n }\n\n}\n\n\n$tests = [\n [],\n [\"ABC\"],\n [\"ABC\", \"DEF\"],\n [\"ABC\", \"DEF\", \"G\", \"H\"]\n];\n\nforeach ($tests as $test) {\n echo quibble($test) . PHP_EOL;\n}\n?>\n", "language": "PHP" }, { "code": "(for L '([] [\"ABC\"] [\"ABC\", \"DEF\"] [\"ABC\", \"DEF\", \"G\", \"H\"])\n (let H (head -1 L)\n (prinl\n \"{\"\n (glue \", \" H)\n (and H \" and \")\n (last L)\n \"}\" ) ) )\n", "language": "PicoLisp" }, { "code": "*process or(!);\n quib: Proc Options(main);\n /*********************************************************************\n * 06.10.2013 Walter Pachl\n *********************************************************************/\n put Edit*process or(!);\n quib: Proc Options(main);\n /*********************************************************************\n * 06.10.2013 Walter Pachl\n * 07.10.2013 -\"- change \"Oxford comma\" to and\n *********************************************************************/\n put Edit(quibbling(''))(Skip,a);\n put Edit(quibbling('ABC'))(Skip,a);\n put Edit(quibbling('ABC DEF'))(Skip,a);\n put Edit(quibbling('ABC DEF G H'))(Skip,a);\n return;\n\n quibbling: proc(s) Returns(Char(100) Var);\n Dcl s Char(*);\n Dcl result Char(100) Var Init('');\n Dcl word(10) Char(100) Var;\n Dcl (wi,p) Bin Fixed(31);\n If s='' Then result='';\n Else Do;\n Do wi=1 By 1 While(s^='');\n p=index(s,' ');\n if p=0 Then Do;\n word(wi)=s;\n s='';\n End;\n Else Do;\n word(wi)=left(s,p-1);\n s=substr(s,p+1);\n End;\n end;\n wn=wi-1;\n result=word(1);\n Do i=2 To wn-1;\n result=result!!', '!!word(i);\n End;\n If wn>1 Then\n result=result!!' and '!!word(wn);\n End;\n Return('{'!!result!!'}');\n End;\n End;\n", "language": "PL-I" }, { "code": "100H:\n\n/* COPY A STRING (MINUS TERMINATOR), RETURNS LENGTH (MINUS TERMINATOR) */\nCOPY$STR: PROCEDURE(SRC, DST) ADDRESS;\n DECLARE (SRC, DST) ADDRESS;\n DECLARE (SCH BASED SRC, DCH BASED DST) BYTE;\n DECLARE L ADDRESS;\n L = 0;\n DO WHILE SCH <> '$';\n DCH = SCH;\n SRC = SRC + 1;\n DST = DST + 1;\n L = L + 1;\n END;\n RETURN L;\nEND COPY$STR;\n\n/* QUIBBLE GIVEN ARRAY OF $-TERMINATED STRINGS, STORE RESULT IN BUFR */\nQUIBBLE: PROCEDURE(WORDS, BUFR) ADDRESS;\n DECLARE (WORDS, BUFR, ADR) ADDRESS;\n DECLARE (WORD BASED WORDS, WPTR) ADDRESS;\n DECLARE (WCHAR BASED WPTR, BCHAR BASED BUFR) BYTE;\n\n /* BRACES AND LOWERCASE LETTERS ARE NOT WITHIN PL/M CHARSET */\n DECLARE LBRACE LITERALLY '123', RBRACE LITERALLY '125';\n DECLARE ANDSTR DATA (32,97,110,100,32,'$');\n\n ADR = BUFR;\n BCHAR = LBRACE;\n BUFR = BUFR + 1;\n DO WHILE WORD <> 0;\n BUFR = BUFR + COPY$STR(WORD, BUFR);\n WORDS = WORDS + 2;\n IF WORD <> 0 THEN\n IF WORD(1) <> 0 THEN\n BUFR = BUFR + COPY$STR(.', $', BUFR);\n ELSE\n BUFR = BUFR + COPY$STR(.ANDSTR, BUFR);\n END;\n BCHAR = RBRACE;\n BUFR = BUFR + 1;\n BCHAR = '$';\n RETURN ADR;\nEND QUIBBLE;\n\n/* --- CP/M OUTPUT AND TESTING --- */\nBDOS: PROCEDURE(FUNC, ARG); /* MAKE CP/M SYSTEM CALL */\n DECLARE FUNC BYTE, ARG ADDRESS;\n GO TO 5;\nEND BDOS;\n\nDECLARE BDOS$EXIT LITERALLY '0', /* EXIT TO CP/M */\n BDOS$PUTS LITERALLY '9'; /* PRINT STRING */\n\nPUTS: PROCEDURE(S);\n DECLARE S ADDRESS;\n CALL BDOS(BDOS$PUTS, S);\n CALL BDOS(BDOS$PUTS, .(13,10,'$'));\nEND PUTS;\n\n/* ARRAY WITH INITIALLY NO CONTENTS */\nDECLARE ARR (5) ADDRESS INITIAL (0,0,0,0,0);\n\nCALL PUTS(QUIBBLE(.ARR, .MEMORY)); /* NO STRINGS */\nARR(0) = .'ABC$';\nCALL PUTS(QUIBBLE(.ARR, .MEMORY)); /* ABC */\nARR(1) = .'DEF$';\nCALL PUTS(QUIBBLE(.ARR, .MEMORY)); /* ABC AND DEF */\nARR(2) = .'G$';\nARR(3) = .'H$';\nCALL PUTS(QUIBBLE(.ARR, .MEMORY)); /* ABC, DEF, G AND H */\n\nCALL BDOS(BDOS$EXIT, 0);\nEOF\n", "language": "PL-M" }, { "code": "To quibble four words:\nAdd \"ABC\" to some string things.\nAdd \"DEF\" to the string things.\nAdd \"G\" to the string things.\nAdd \"H\" to the string things.\nQuibble the string things.\n\nTo quibble one word:\nAdd \"ABC\" to some string things.\nQuibble the string things.\n\nTo quibble some string things:\nQuibble the string things giving a string.\nDestroy the string things.\nWrite the string on the console.\n\nTo quibble some string things giving a string:\nAppend \"{\" to the string.\nPut the string things' count into a count.\nIf the count is 0, append \"}\" to the string; exit.\nGet a string thing from the string things.\nIf the count is 1, append the string thing's string then \"}\" to the string; exit.\nLoop.\nIf a counter is past the count minus 2, append the string thing's string then \" and \" then the string thing's next's string then \"}\" to the string; exit.\nAppend the string thing's string then \", \" to the string.\nPut the string thing's next into the string thing.\nRepeat.\n\nTo quibble two words:\nAdd \"ABC\" to some string things.\nAdd \"DEF\" to the string things.\nQuibble the string things.\n\nTo quibble zero words:\nQuibble some string things.\n\nTo run:\nStart up.\nQuibble zero words.\nQuibble one word.\nQuibble two words.\nQuibble four words.\nWait for the escape key.\nShut down.\n", "language": "Plain-English" }, { "code": "function Out-Quibble\n{\n [OutputType([string])]\n Param\n (\n # Zero or more strings.\n [Parameter(Mandatory=$false, Position=0)]\n [AllowEmptyString()]\n [string[]]\n $Text = \"\"\n )\n\n # If not null or empty...\n if ($Text)\n {\n # Remove empty strings from the array.\n $text = \"$Text\".Split(\" \", [StringSplitOptions]::RemoveEmptyEntries)\n }\n else\n {\n return \"{}\"\n }\n\n # Build a format string.\n $outStr = \"\"\n for ($i = 0; $i -lt $text.Count; $i++)\n {\n $outStr += \"{$i}, \"\n }\n $outStr = $outStr.TrimEnd(\", \")\n\n # If more than one word, insert \" and\" at last comma position.\n if ($text.Count -gt 1)\n {\n $cIndex = $outStr.LastIndexOf(\",\")\n $outStr = $outStr.Remove($cIndex,1).Insert($cIndex,\" and\")\n }\n\n # Output the formatted string.\n \"{\" + $outStr -f $text + \"}\"\n}\n", "language": "PowerShell" }, { "code": "Out-Quibble\nOut-Quibble \"ABC\"\nOut-Quibble \"ABC\", \"DEF\"\nOut-Quibble \"ABC\", \"DEF\", \"G\", \"H\"\n", "language": "PowerShell" }, { "code": "$file = @'\n\nABC\nABC, DEF\nABC, DEF, G, H\n'@ -split [Environment]::NewLine\n\nforeach ($line in $file)\n{\n Out-Quibble -Text ($line -split \", \")\n}\n", "language": "PowerShell" }, { "code": "words_series(Words, Bracketed) :-\n words_serialized(Words, Serialized),\n atomics_to_string([\"{\",Serialized,\"}\"], Bracketed).\n\nwords_serialized([], \"\").\nwords_serialized([Word], Word) :- !.\nwords_serialized(Words, Serialized) :-\n append(Rest, [Last], Words), %% Splits the list of *Words* into the *Last* word and the *Rest*\n atomics_to_string(Rest, \", \", WithCommas),\n atomics_to_string([WithCommas, \" and \", Last], Serialized).\n\n\n\ntest :-\n forall( member(Words, [[], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]]),\n ( words_series(Words, Series),\n format('~w ~15|=> ~w~n', [Words, Series]))\n ).\n", "language": "Prolog" }, { "code": "?- test.\n[] => {}\n[ABC] => {ABC}\n[ABC,DEF] => {ABC and DEF}\n[ABC,DEF,G,H] => {ABC, DEF, G and H}\ntrue.\n", "language": "Prolog" }, { "code": "EnableExplicit\n\nProcedure.s CommaQuibble(Input$)\n Protected i, count\n Protected result$, word$\n Input$ = RemoveString(Input$, \"[\")\n Input$ = RemoveString(Input$, \"]\")\n Input$ = RemoveString(Input$, #DQUOTE$)\n count = CountString(Input$, \",\") + 1\n result$ = \"{\"\n For i = 1 To count\n word$ = StringField(Input$, i, \",\")\n If i = 1\n result$ + word$\n ElseIf Count = i\n result$ + \" and \" + word$\n Else\n result$ + \", \" + word$\n EndIf\n Next\n ProcedureReturn result$ + \"}\"\nEndProcedure\n\nIf OpenConsole()\n ; As 3 of the strings contain embedded quotes these need to be escaped with '\\' and the whole string preceded by '~'\n PrintN(CommaQuibble(\"[]\"))\n PrintN(CommaQuibble(~\"[\\\"ABC\\\"]\"))\n PrintN(CommaQuibble(~\"[\\\"ABC\\\",\\\"DEF\\\"]\"))\n PrintN(CommaQuibble(~\"[\\\"ABC\\\",\\\"DEF\\\",\\\"G\\\",\\\"H\\\"]\"))\n PrintN(\"\")\n PrintN(\"Press any key to close the console\")\n Repeat: Delay(10) : Until Inkey() <> \"\"\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": ">>> def strcat(sequence):\n return '{%s}' % ', '.join(sequence)[::-1].replace(',', 'dna ', 1)[::-1]\n\n>>> for seq in ([], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]):\n print('Input: %-24r -> Output: %r' % (seq, strcat(seq)))\n\n\t\nInput: [] -> Output: '{}'\nInput: ['ABC'] -> Output: '{ABC}'\nInput: ['ABC', 'DEF'] -> Output: '{ABC and DEF}'\nInput: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}'\n>>>\n", "language": "Python" }, { "code": "def commaQuibble(s):\n return '{%s}' % ' and '.join(s).replace(' and ', ', ', len(s) - 2)\n\nfor seq in ([], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]):\n\tprint('Input: %-24r -> Output: %r' % (seq, commaQuibble(seq)))\n", "language": "Python" }, { "code": ">>> def quibble(s):\n return ('{' +\n (', '.join(s[:-1]) + ' and ' if len(s) > 1 else '') +\n\t (s[-1] if s else '') +\n\t '}')\n\n>>> for seq in ([], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]):\n\tprint('Input: %-24r -> Output: %r' % (seq, quibble(seq)))\n\n\t\nInput: [] -> Output: '{}'\nInput: ['ABC'] -> Output: '{ABC}'\nInput: ['ABC', 'DEF'] -> Output: '{ABC and DEF}'\nInput: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}'\n>>>\n", "language": "Python" }, { "code": "[ swap join join ] is glue ( [ [ [ --> [ )\n\n[ [ dup size\n dup 0 = iff\n [ 2drop [] ] done\n dup 1 = iff\n [ drop unpack ] done\n 2 = iff\n [ unpack $ ' and ' glue ] done\n behead swap recurse $ ', ' glue ]\n $ '{' swap join $ '}' join ] is quibble ( [ --> $ )\n\n[] quibble echo$ cr\n$ 'ABC' nest$ quibble echo$ cr\n$ 'ABC DEF' nest$ quibble echo$ cr\n$ 'ABC DEF G H' nest$ quibble echo$\n", "language": "Quackery" }, { "code": "quib <- function(vect)\n{\n #The task does not consider empty strings to be words, so we remove them immediately.\n #We could also remove non-upper-case characters, but the tasks gives off the impression that the user will do that.\n vect <- vect[nchar(vect) != 0]\n len <- length(vect)\n allButLastWord <- if(len >= 2) paste0(vect[seq_len(len - 1)], collapse = \", \") else \"\"\n paste0(\"{\", if(nchar(allButLastWord) == 0) vect else paste0(allButLastWord, \" and \", vect[len]), \"}\")\n}\nquib(character(0)) #R has several types of empty string, e.g. character(0), \"\", and c(\"\", \"\", \"\").\nquib(\"\")\nquib(\" \")\nquib(c(\"\", \"\"))\nquib(rep(\"\", 10))\nquib(\"ABC\")\nquib(c(\"ABC\", \"\"))\nquib(c(\"ABC\", \"DEF\"))\nquib(c(\"ABC\", \"DEF\", \"G\", \"H\"))\nquib(c(\"ABC\", \"DEF\", \"G\", \"H\", \"I\", \"J\", \"\"))\n", "language": "R" }, { "code": "(define (quibbling words)\n (define (sub-quibbling words)\n (match words\n ['() \"\"]\n [(list a) a]\n [(list a b) (format \"~a and ~a\" a b)]\n [(list a b ___) (format \"~a, ~a\" a (sub-quibbling b))]))\n (format \"{~a}\" (sub-quibbling words)))\n\n(for ((input '([] [\"ABC\"] [\"ABC\" \"DEF\"] [\"ABC\" \"DEF\" \"G\" \"H\"])))\n (printf \"~s\\t->\\t~a~%\" input (quibbling input)))\n", "language": "Racket" }, { "code": "sub comma-quibbling(@A) {\n <{ }>.join: @A < 2 ?? @A !! \"@A[0..*-2].join(', ') and @A[*-1]\";\n}\n\nsay comma-quibbling($_) for\n [], [<ABC>], [<ABC DEF>], [<ABC DEF G H>];\n", "language": "Raku" }, { "code": "Rebol []\n\ncomma-quibbling: func [block] [\n rejoin [\n \"^{\"\n\n to-string use [s] [\n s: copy block\n s: next s\n forskip s 2 [insert s either tail? next s [\" and \"] [\", \"]]\n s: head s\n ]\n\n \"^}\"\n ]\n]\n\nforeach t [[] [ABC] [ABC DEF] [ABC DEF G H]] [print comma-quibbling t]\n", "language": "REBOL" }, { "code": "Rebol []\n\n; builds string instead of using an intermediate block\n\ncomma-quibbling: func [block /oxford /local s length] [\n length: length? block\n rejoin [\n \"^{\"\n\n either length < 2 [to-string block] [\n s: to-string block/1\n for n 2 (length - 1) 1 [repend s [\", \" pick block n]]\n if all [oxford (length > 2)] [append s \",\"]\n repend s [\" and \" last block]\n ]\n\n \"^}\"\n ]\n]\n\ntest: [[] [ABC] [ABC DEF] [ABC DEF G H]]\nforeach t test [print comma-quibbling t]\nprint \"Now with Oxford comma\"\nforeach t test [print comma-quibbling/oxford t]\n", "language": "REBOL" }, { "code": "$ENTRY Go {\n = <Prout <Quibble>>\n <Prout <Quibble ('ABC')>>\n <Prout <Quibble ('ABC') ('DEF')>>\n <Prout <Quibble ('ABC') ('DEF') ('G') ('H')>>;\n};\n\nQuibble {\n e.X = '{' <Quibble1 e.X> '}';\n};\n\nQuibble1 {\n = ;\n (e.Word) = e.Word;\n (e.Word1) (e.Word2) = e.Word1 ' and ' e.Word2;\n (e.Word) e.Words = e.Word ', ' <Quibble1 e.Words>;\n};\n", "language": "Refal" }, { "code": "say quibbling('')\nsay quibbling('ABC')\nsay quibbling('ABC DEF')\nsay quibbling('ABC DEF G H')\nexit\n\nquibbling: procedure\n parse arg list\n Select\n When list='' Then result=''\n When words(list)=1 then result=word(list,1)\n Otherwise result=translate(strip(subword(list,1,words(list)-1)),',',' '),\n 'and' word(list,words(list))\n End\n Return '{'result'}'\n", "language": "REXX" }, { "code": "say quibbling('')\nsay quibbling('ABC')\nsay quibbling('ABC DEF')\nsay quibbling('ABC DEF G H')\nexit\nquibbling:\n parse arg list\n If list='' Then result=''\n Else Do\n Do wi=1 By 1 while list<>''\n Parse Var list word.wi ' ' list\n End\n wn=wi-1\n result=word.1\n Do wi=2 To wn-1\n result=result', 'word.wi\n End\n If wn>1 Then\n result=result 'and' word.wn\n End\n Return '{'result'}'\n", "language": "REXX" }, { "code": "/* Rexx */\n\ni_ = 0\ni_ = i_ + 1; lists.0 = i_; lists.i_ = '[]'\ni_ = i_ + 1; lists.0 = i_; lists.i_ = '[\"ABC\"]'\ni_ = i_ + 1; lists.0 = i_; lists.i_ = '[\"ABC\", ''DEF'']'\ni_ = i_ + 1; lists.0 = i_; lists.i_ = '[ABC, DEF, G, H]'\n\nsay\ndo i_ = 1 to lists.0\n list = lists.i_\n say right(list, 30) ':' quibbling03(list)\n end i_\nexit\n\nquibbling03:\nprocedure\n parse arg '[' lst ']'\n lst = changestr('\"', changestr(\"'\", lst, ''), '') /* remove double & single quotes */\n lc = lastpos(',', lst)\n if lc > 0 then\n lst = overlay(' ', insert('and', lst, lc), lc)\n lst = space(lst, 1) -- remove extra spaces\n return '{'lst'}'\n", "language": "REXX" }, { "code": "# Project : Comma Quibbling\n\ntext = list(4)\ntext[1] = \"{}\"\ntext[2] = \"ABC\"\ntext[3] = \"ABC,DEF\"\ntext[4] = \"ABC,DEF,G,H\"\ncomma(text)\n\nfunc comma(text)\n listtext = []\n for n = 1 to 4\n listtext = str2list(substr(text[n], \",\", nl))\n if n = 2\n see \"{\" + list2str(listtext) + \"}\" + nl\n loop\n ok\n if len(listtext) = 1\n see \"{}\" + nl\n loop\n ok\n str = \"{\"\n for m = 1 to len(listtext)-1\n if len(listtext) = 2\n str = str + listtext[m] + \" \"\n else\n str = str + listtext[m] + \", \"\n ok\n next\n if len(listtext) = 2\n str = left(str, len(str)-1)\n else\n str = left(str, len(str)-2)\n ok\n if len(listtext) = 2\n str = str + \" \" + listtext[len(listtext)] + \"}\"\n else\n str = str + \" and \" + listtext[len(listtext)] + \"}\"\n ok\n see str + nl\n next\n", "language": "Ring" }, { "code": "def comma_quibbling(a)\n %w<{ }>.join(a.length < 2 ? a.first :\n \"#{a[0..-2].join(', ')} and #{a[-1]}\")\nend\n\n[[], %w<ABC>, %w<ABC DEF>, %w<ABC DEF G H>].each do |a|\n puts comma_quibbling(a)\nend\n", "language": "Ruby" }, { "code": "wrds$ = \"[]\n[\"\"ABC\"\"]\n[\"\"ABC\"\", \"\"DEF\"\"]\n[\"\"ABC\"\", \"\"DEF\"\", \"\"G\"\", \"\"H\"\"]\n\"\nwhile word$(wrds$,j+1,chr$(13)) <> \"\"\n a$ = word$(wrds$,j+1,chr$(13))\n print a$;\" ==> \";\n a$ = \"{\"+mid$(a$,2,len(a$)-2)+\"}\"\n j = j + 1\n for i = len(a$) to 1 step -1\n if mid$(a$,i,1) = \",\" then\n a$ = left$(a$,i-1) + \" and \" + mid$(a$,i+2)\n exit for\n end if\n next i\n print a$\nWEND\n", "language": "Run-BASIC" }, { "code": "fn quibble(seq: &[&str]) -> String {\n match seq.len() {\n 0 => \"{}\".to_string(),\n 1 => format!(\"{{{}}}\", seq[0]),\n _ => {\n format!(\"{{{} and {}}}\",\n seq[..seq.len() - 1].join(\", \"),\n seq.last().unwrap())\n }\n }\n}\n\nfn main() {\n println!(\"{}\", quibble(&[]));\n println!(\"{}\", quibble(&[\"ABC\"]));\n println!(\"{}\", quibble(&[\"ABC\", \"DEF\"]));\n println!(\"{}\", quibble(&[\"ABC\", \"DEF\", \"G\", \"H\"]));\n}\n", "language": "Rust" }, { "code": "def quibble( s:List[String] ) = s match {\n case m if m.isEmpty => \"{}\"\n case m if m.length < 3 => m.mkString(\"{\", \" and \", \"}\")\n case m => \"{\" + m.init.mkString(\", \") + \" and \" + m.last + \"}\"\n}\n\n// A little test...\n{\n println( quibble( List() ) )\n println( quibble( List(\"ABC\") ) )\n println( quibble( List(\"ABC\",\"DEF\") ) )\n println( quibble( List(\"ABC\",\"DEF\",\"G\",\"H\") ) )\n}\n", "language": "Scala" }, { "code": "(define (quibble . args)\n (display \"{\")\n (do ((rem args (cdr rem)))\n ((null? rem) (display \"}\\n\"))\n (display (car rem))\n (cond ((= 1 (length rem)) )\n ((= 2 (length rem))\n (display \" and \"))\n (else\n (display \", \")))))\n\n(quibble)\n(quibble \"ABC\")\n(quibble \"ABC\" \"DEF\")\n(quibble \"ABC\" \"DEF\" \"G\" \"H\")\n", "language": "Scheme" }, { "code": "s/#.*$//g\ny/[/{/\ny/]/}/\ns/\"//g\ns/ [A-Z][A-Z]*}/ and&/g\ns/, and/ and/\n", "language": "Sed" }, { "code": "[] # (No input words).\n[\"ABC\"]\n[\"ABC\", \"DEF\"]\n[\"ABC\", \"DEF\", \"G\", \"H\"]\n", "language": "Sed" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst func string: quibble (in array string: input) is func\n result\n var string: quibble is \"{\";\n begin\n case length(input) of\n when {0}: quibble &:= \"}\";\n when {1}: quibble &:= input[1] & \"}\";\n otherwise: quibble &:= join(input[.. pred(length(input))], \", \") &\n \" and \" & input[length(input)] & \"}\";\n end case;\n end func;\n\nconst proc: main is func\n begin\n writeln(quibble(0 times \"\"));\n writeln(quibble([] (\"ABC\")));\n writeln(quibble([] (\"ABC\", \"DEF\")));\n writeln(quibble([] (\"ABC\", \"DEF\", \"G\", \"H\")));\n end func;\n", "language": "Seed7" }, { "code": "Quibble [] // (No input words).\nQuibble [\"ABC\"]\nQuibble [\"ABC\", \"DEF\"]\nQuibble [\"ABC\", \"DEF\", \"G\", \"H\"]\n\nto Quibble with wordList\n\tif the number of items in wordList is ...\n\t\t... 0 then put \"{}\"\n\t\t... 1 then put \"{\" & item 1 of wordList & \"}\"\n\t\t... else put \"{\" & (items first to penultimate of wordList) joined by \", \" & \" and \" & the last item of wordlist & \"}\"\n\tend if\nend Quibble\n", "language": "SenseTalk" }, { "code": "program comma_quibbling;\n tests := [\n [],\n [\"ABC\"],\n [\"ABC\",\"DEF\"],\n [\"ABC\",\"DEF\",\"G\",\"H\"]\n ];\n\n loop for t in tests do\n print(t, \"=\", quibble(t));\n end loop;\n\n proc quibble(words);\n ret := '{';\n loop while words /= [] do\n word fromb words;\n ret +:= word;\n case of\n (#words = 1):\n ret +:= \" and \";\n (#words > 1):\n ret +:= \", \";\n end case;\n end loop;\n return ret + '}';\n end proc;\nend program;\n", "language": "SETL" }, { "code": "func comma_quibbling(words) {\n '{' + ([words.first(-1).join(', ')]-[''] + [words.last] -> join(' and ')) + '}'\n}\n\n[<>, <ABC>, <ABC DEF>, <ABC DEF G H>].each { |w|\n say comma_quibbling(w)\n}\n", "language": "Sidef" }, { "code": "local\n fun quib [] = \"\"\n | quib [x] = x\n | quib [x0,x1] = x0 ^ \" and \" ^ x1\n | quib (x::xs) = x ^ \", \" ^ quib xs\nin\n fun quibble xs = \"{\" ^ quib xs ^ \"}\"\nend\n\n(* Tests: *)\nval t_quibble_0 = quibble [] = \"{}\"\nval t_quibble_1 = quibble [\"ABC\"] = \"{ABC}\"\nval t_quibble_2 = quibble [\"ABC\", \"DEF\"] = \"{ABC and DEF}\"\nval t_quibble_3 = quibble [\"ABC\", \"DEF\", \"G\", \"H\"] = \"{ABC, DEF, G and H}\"\n", "language": "Standard-ML" }, { "code": "let inputs = [[], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]]\n\nfunc quibbling(var words:[String]) {\n if words.count == 0 {\n println(\"{}\")\n } else if words.count == 1 {\n println(\"{\\(words[0])}\")\n } else if words.count == 2 {\n println(\"{\\(words[0]) and \\(words[1])}\")\n } else {\n var output = \"{\"\n while words.count != 2 {\n output += words.removeAtIndex(0) + \", \"\n }\n output += \"\\(words.removeAtIndex(0)) and \\(words.removeAtIndex(0))}\"\n\n println(output)\n }\n}\n\nfor word in inputs {\n quibbling(word)\n}\n", "language": "Swift" }, { "code": "proc commaQuibble {lst} {\n return \\{[join [lreplace $lst end-1 end [join [lrange $lst end-1 end] \" and \"]] \", \"]\\}\n}\n\nforeach input { {} {\"ABC\"} {\"ABC\" \"DEF\"} {\"ABC\" \"DEF\" \"G\" \"H\"} } {\n puts [commaQuibble $input]\n}\n", "language": "Tcl" }, { "code": "(defun quib (list)\n (tree-bind (: last . lead) (reverse list)\n `{@{(nreverse lead) \", \"}@(if lead \" and \")@last}`))\n", "language": "TXR" }, { "code": "Tests ← {{}\n {\"ABC\"}\n {\"ABC\" \"DEF\"}\n {\"ABC\" \"DEF\" \"G\" \"H\"}}\nJam ← ◇⊂◇⊂:□\nQuibble ← |1 ⟨\"\"◌|°□⊢|Jam\" and \"°⊟|Quibble⊂⊃(□Jam\", \"°⊟↙2)(↘2)⟩↧3⧻.\nWrap ← ⊂⊂\"{\" : \"}\" Quibble\n⍚(&pWrap) Tests\n", "language": "Uiua" }, { "code": "quibble() {\n printf '{'\n while (( $# > 2 )); do\n printf '%s, ' \"$1\"\n shift\n done\n if (( $# )); then\n printf '%s' \"$1\"\n shift\n fi\n if (( $# )); then\n printf ' and %s' \"$1\"\n fi\n printf '%s\\n' '}'\n}\n", "language": "UNIX-Shell" }, { "code": "quibble() {\n printf '{'\n while [ $# -gt 2 ]; do\n printf '%s, ' \"$1\"\n shift\n done\n if [ $# -gt 0 ]; then\n printf '%s' \"$1\"\n shift\n fi\n if [ $# -gt 0 ]; then\n printf ' and %s' \"$1\"\n fi\n printf '%s\\n' '}'\n}\n", "language": "UNIX-Shell" }, { "code": "quibble() {\n printf '{'\n if (( $# > 1 )) printf '%s and ' ${(j:, :)@[1,-2]}\n printf '%s}\\n' $@[-1]\n}\n", "language": "UNIX-Shell" }, { "code": "quibble\nquibble ABC\nquibble ABC DEF\nquibble ABC DEF G H\n", "language": "UNIX-Shell" }, { "code": "fn q(s []string) string {\n match s.len {\n 0 {\n return '{}'\n }\n 1 {\n return '{${s[0]}}'\n }\n 2 {\n return '{${s[0]} and ${s[1]}}'\n }\n else{\n return '{${s[0..s.len-1].join(', ')} and ${s[s.len-1]}}'\n }\n }\n}\n\nfn main(){\n println(q([]))\n println(q(['ABC']))\n println(q(['ABC','DEF']))\n println(q(['ABC','DEF','G','H']))\n}\n", "language": "V-(Vlang)" }, { "code": "Option Explicit\n\nSub Main()\n Debug.Print Quibbling(\"\")\n Debug.Print Quibbling(\"ABC\")\n Debug.Print Quibbling(\"ABC, DEF\")\n Debug.Print Quibbling(\"ABC, DEF, G, H\")\n Debug.Print Quibbling(\"ABC, DEF, G, H, IJKLM, NO, PQRSTUV\")\nEnd Sub\n\nPrivate Function Quibbling(MyString As String) As String\nDim s As String, n As Integer\n s = \"{\" & MyString & \"}\": n = InStrRev(s, \",\")\n If n > 0 Then s = Left(s, n - 1) & \" and \" & Right(s, Len(s) - (n + 1))\n Quibbling = s\nEnd Function\n", "language": "VBA" }, { "code": "Function Quibble(s)\n\tarr = Split(s,\",\")\n\tIf s = \"\" Then\n\t\tQuibble = \"{}\"\n\tElseIf UBound(arr) = 0 Then\n\t\tQuibble = \"{\" & arr(0) & \"}\"\n\tElse\n\t\tQuibble = \"{\"\n\t\tFor i = 0 To UBound(arr)\n\t\t\tIf i = UBound(arr) - 1 Then\n\t\t\t\tQuibble = Quibble & arr(i) & \" and \" & arr(i + 1) & \"}\"\n\t\t\t\tExit For\n\t\t\tElse\n\t\t\t\tQuibble = Quibble & arr(i) & \", \"\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\nWScript.StdOut.Write Quibble(\"\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write Quibble(\"ABC\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write Quibble(\"ABC,DEF\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write Quibble(\"ABC,DEF,G,H\")\nWScript.StdOut.WriteLine\n", "language": "VBScript" }, { "code": "Option Explicit On\nOption Infer On\nOption Strict On\n\nModule Program\n Function FormatEnumerable(source As IEnumerable(Of String)) As String\n Dim res As New Text.StringBuilder(\"{\")\n\n Using en = source.GetEnumerator()\n Dim moreThanOne As Boolean = False\n Dim nxt = If(en.MoveNext(), en.Current, String.Empty)\n\n Do While en.MoveNext()\n If moreThanOne Then res.Append(\", \")\n moreThanOne = True\n\n res.Append(nxt)\n nxt = en.Current\n Loop\n\n Dim lastItem = If(moreThanOne, \" and \", \"\") & nxt\n Return res.ToString() & lastItem & \"}\"\n End Using\n End Function\n\n Function FormatArray(source As String()) As String\n Select Case source.Length\n Case 0 : Return \"{}\"\n Case 1 : Return \"{\" & source(0) & \"}\"\n Case Else : Return \"{\" & String.Join(\", \", source.Take(source.Length - 1)) & \" and \" & source(source.Length - 1) & \"}\"\n End Select\n End Function\n\n Sub Main()\n Dim cases As String()() = {Array.Empty(Of String), New String() {\"ABC\"}, New String() {\"ABC\", \"DEF\"}, New String() {\"ABC\", \"DEF\", \"G\", \"H\"}}\n For Each c In cases\n Console.WriteLine(FormatArray(c))\n Console.WriteLine(FormatEnumerable(c))\n Next\n End Sub\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "var quibbling = Fn.new { |w|\n var c = w.count\n if (c == 0) return \"{}\"\n if (c == 1) return \"{%(w[0])}\"\n if (c == 2) return \"{%(w[0]) and %(w[1])}\"\n return \"{%(w[0..-2].join(\", \")) and %(w[-1])}\"\n}\n\nvar words = [ [], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"] ]\nfor (w in words) System.print(quibbling.call(w))\n", "language": "Wren" }, { "code": "func task(a:array){\n\tset x:string=\"\";\n\tforeach(k,v as a){\n\t\tset out:string=\"\";\n\t\tif ((k==(?a-2))&((?a)>1)){out=\" and \"}elif(k!=(?a-1)){out=\", \"}\n\t\tx+=v+out;del out;\n\t}\n\tsend \"{\"+x+\"}\";\n}\n\nlog(task([]));\nlog(task([\"ABC\"]));\nlog(task([\"ABC\",\"DEF\"]));\nlog(task([\"ABC\",\"DEF\",\"GHI\"]));\n", "language": "XBS" }, { "code": "(defun quibble (inputs &optional oxford-comma)\n (define final\n (if (and (caddr inputs) oxford-comma)\n \", and \"\n \" and \" ) )\n (defun comma-quibble (words)\n (cond\n ((null words) \"\")\n ((null (cdr words)) (car words))\n (t (begin\n (string-append (car words)\n (if (caddr words)\n (string-append \", \" (comma-quibble (cdr words)))\n (string-append final (cadr words))) ) ) ) ) )\n (string-append \"{\" (comma-quibble inputs) \"}\") )\n\n; test cases:\n(print (quibble '())) ; empty list\n(print (quibble '(\"ABC\")))\n(print (quibble '(\"ABC\" \"DEF\")))\n(print (quibble '(\"ABC\" \"DEF\" \"G\" \"H\")))\n\n(newline)\n\n; test cases using the Oxford comma:\n(print (quibble '() t))\n(print (quibble '(\"ABC\") t))\n(print (quibble '(\"ABC\" \"DEF\") t))\n(print (quibble '(\"ABC\" \"DEF\" \"G\" \"H\") t))\n", "language": "XLISP" }, { "code": "include c:\\cxpl\\codes;\n\nproc Quibble(N, S);\nint N, S;\nint I;\n[ChOut(0, ^{);\nfor I:= 0 to N-1 do\n [Text(0, S(I));\n if I<N-2 then Text(0, \", \");\n if I=N-2 then Text(0, \" and \");\n ];\nChOut(0, ^});\n];\n\nint I;\nfor I:= 0 to 4 do\n if I#3 then [Quibble(I, [\"ABC\", \"DEF\", \"G\", \"H\"]); CrLf(0)]\n", "language": "XPL0" }, { "code": "fcn quib(list){ text:=(\"{\"+list.toString(*)[2,-1]+\"}\").replace(\"\\\"\",\"\");\n if(list.len()<2) text;\n else{\n z:=(text=text.replace(\",\",\", \")).rfind(\",\");\n String(text[0,z],\" and \",text[z+2,*])\n }\n}\n", "language": "Zkl" }, { "code": "10 DATA 0\n20 DATA 1,\"ABC\"\n30 DATA 2,\"ABC\",\"DEF\"\n40 DATA 4,\"ABC\",\"DEF\",\"G\",\"H\"\n50 FOR n=10 TO 40 STEP 10\n60 RESTORE n: GO SUB 1000\n70 NEXT n\n80 STOP\n1000 REM quibble\n1010 LET s$=\"\"\n1020 READ j\n1030 IF j=0 THEN GO TO 1100\n1040 FOR i=1 TO j\n1050 READ a$\n1060 LET s$=s$+a$\n1070 IF (i+1)=j THEN LET s$=s$+\" and \": GO TO 1090\n1080 IF (i+1)<j THEN LET s$=s$+\", \"\n1090 NEXT i\n1100 PRINT \"{\";s$;\"}\"\n1110 RETURN\n", "language": "ZX-Spectrum-Basic" } ]
Comma-quibbling
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Command-line_arguments\n", "language": "00-META" }, { "code": "{{selection|Short Circuit|Console Program Basics}} [[Category:Basic language learning]][[Category:Programming environment operations]][[Category:Initialization]]Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]].\n\nSee also [[Program name]].\n\nFor parsing command line arguments intelligently, see [[Parsing command-line arguments]].\n\nExample command line:\n\n myprogram -c \"alpha beta\" -h \"gamma\"\n\n", "language": "00-TASK" }, { "code": ":start:\nprint(‘Program name: ’:argv[0])\nprint(\"Arguments:\\n\":argv[1..].join(\"\\n\"))\n", "language": "11l" }, { "code": "putch:\tequ\t2\t; CP/M syscall to print character\nputs:\tequ\t9\t; CP/M syscall to print $-terminated string\narglen:\tequ\t80h\t; Length of argument\nargmt:\tequ\t81h\t; Argument string\nfcb1:\tequ\t5Ch\t; FCBs\nfcb2:\tequ\t6Ch\n\torg\t100h\n\t;;;\tPrint all argument(s) as given\n\tlxi\td,cmdln\t; Print 'Command line: '\n\tmvi\tc,puts\n\tcall\t5\n\tlda\targlen\t; Retrieve the length of the argument\n\tlxi\th,argmt\t; Pointer to argument string\n\tcall\tplstr\t\n\t;;;\tCP/M also assumes that the first two words on the command\n\t;;;\tline are filenames, and prepares two FCBs with the filenames\n\t;;;\tin them. If there are no filenames, they will be blank.\n\tlxi\td,file1\t; Print the first one\n\tmvi\tc,puts\n\tcall\t5\n\tmvi\ta,11\t; Filenames are 8+3 characters long and padded with\n\tlxi\th,fcb1+1\t; spaces\n\tcall\tplstr\n\tlxi\td,file2\t; Print the second one\n\tmvi\tc,puts\n\tcall\t5\n\tmvi\ta,11\n\tlxi\th,fcb2+1\n\t; ... fall through - on small systems saving bytes is a virtue\n\t;;;\tThis subroutine prints a length-A string in HL.\nplstr:\tana\ta\t; If A=0, print nothing.\n\trz\n\tpush\tpsw\t; Save A and HL registers on the stack\n\tpush\th\t; (CP/M syscalls clobber all registers)\n\tmov\te,m\t; Print character under HL\n\tmvi\tc,putch\n\tcall\t5\n\tpop\th\t; Restore A and HL registers\n\tpop\tpsw\n\tinx\th\t; Increment string pointer\n\tdcr\ta\t; Decrement character counter\n\tjnz\tplstr\t; Print next character if not zero\n\tret\ncmdln:\tdb\t'Command line: $'\nfile1:\tdb\t13,10,'File 1: $'\nfile2:\tdb\t13,10,'File 2: $'\n", "language": "8080-Assembly" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program commandLine64.s */\n/************************************/\n/* Constantes */\n/************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n/************************************/\n/* Initialized data */\n/************************************/\n.data\nszCarriageReturn: .asciz \"\\n\"\n/************************************/\n/* UnInitialized data */\n/************************************/\n.bss\n.align 4\n/************************************/\n/* code section */\n/************************************/\n.text\n.global main\nmain: // entry of program\n mov fp,sp // fp <- start address\n ldr x4,[fp] // number of Command line arguments\n add x5,fp,#8 // first parameter address\n mov x2,#0 // init loop counter\n1:\n ldr x0,[x5,x2,lsl #3] // string address parameter\n bl affichageMess // display string\n ldr x0,qAdrszCarriageReturn\n bl affichageMess // display carriage return\n add x2,x2,#1 // increment counter\n cmp x2,x4 // number parameters ?\n blt 1b // loop\n\n100: // standard end of the program\n mov x0, #0 // return code\n mov x8,EXIT\n svc 0 // perform the system call\n\nqAdrszCarriageReturn: .quad szCarriageReturn\n\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "with Ada.Command_line; use Ada.Command_Line;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Print_Commands is\nbegin\n -- The number of command line arguments is retrieved from the function Argument_Count\n -- The actual arguments are retrieved from the function Argument\n -- The program name is retrieved from the function Command_Name\n Put(Command_Name & \" \");\n for Arg in 1..Argument_Count loop\n Put(Argument(Arg) & \" \");\n end loop;\n New_Line;\nend Print_Commands;\n", "language": "Ada" }, { "code": "with Ada.Wide_Wide_Text_IO;\n\nwith League.Application;\nwith League.Strings;\n\nprocedure Main is\nbegin\n for J in 1 .. League.Application.Arguments.Length loop\n Ada.Wide_Wide_Text_IO.Put_Line\n (League.Application.Arguments.Element (J).To_Wide_Wide_String);\n end loop;\nend Main;\n", "language": "Ada" }, { "code": "foreach arg in args {\n println (\"arg: \" + arg)\n}\n", "language": "Aikido" }, { "code": "integer i;\n\ni = 0;\nwhile (i < argc()) {\n o_text(argv(i));\n o_byte('\\n');\n i += 1;\n}\n", "language": "Aime" }, { "code": "main:(\n FOR i TO argc DO\n printf(($\"the argument #\"g(-0)\" is \"gl$, i, argv(i)))\n OD\n)\n", "language": "ALGOL-68" }, { "code": "#defn main(_V_,_N_) #RAND, main:, V#RNDV=1,_V_={#VOID}, \\\n _N_=0,totalarg,mov(_N_), \\\n LOOPGETARG_#RNDV:, {[ V#RNDV ]},push(_V_),++V#RNDV,\\\n {_N_,V#RNDV},jle(LOOPGETARG_#RNDV),clear(V#RNDV)\n", "language": "Amazing-Hopper" }, { "code": "#include <hopper.h>\n\nmain(argv, argc)\n {\"This program named: \"},[1]get(argv),println\n for(i=2, {i}lethan(argc),++i)\n {\"Argument #\",i,\" = \"}[i]get(argv),println\n next\nexit(0)\n", "language": "Amazing-Hopper" }, { "code": "#include <hopper.h>\n\nmain:\n total arg, argc=0,mov(argc)\n {\"This program named: \",[&1]},println\n i=2\n __CNT_ARGS__:\n {\"Argumento #\",i,\" = \",[&i]}println\n ++i,{argc,i}jle(__CNT_ARGS__)\nexit(0)\n", "language": "Amazing-Hopper" }, { "code": "#include <hopper.h>\n\nmain(argv, argc)\n i=2\n #hl{\n print( \"This program named: \",argv[1],\"\\n\")\n while( i <= argc )\n print(\"Argument #\",i,\" = \",argv[i],\"\\n\")\n i += 1\n wend\n }\nexit(0)\n", "language": "Amazing-Hopper" }, { "code": "#include <natural.h>\n#include <hopper.h>\n\nmain:\n get total arguments, and remember as 'total arguments'.\n remember (\"This program named: \"),\n now remember ( argument '1' ), and print with a new line.\n secondly, declare 'i', take '2', and store in 'i'\n do while ( variable 'i' is less or equal than 'total arguments', \\\n consider this ( {\"Argument #\",i,\" = \"} );\\\n remember ( argument 'i' ); put a new line and print it; finally increment 'i' ).\nexit(0)\n", "language": "Amazing-Hopper" }, { "code": "#!/usr/bin/env osascript\n-- Print first argument\non run argv\n return (item 1 of argv)\nend run\n", "language": "AppleScript" }, { "code": "/* ARM assembly Raspberry PI */\n/* program commandLine.s */\n\n/* Constantes */\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n/* Initialized data */\n.data\nszCarriageReturn: .asciz \"\\n\"\n\n/* UnInitialized data */\n.bss\n.align 4\n\n/* code section */\n.text\n.global main\nmain: @ entry of program\n push {fp,lr} @ saves registers\n add fp,sp,#8 @ fp <- start address\n ldr r4,[fp] @ number of Command line arguments\n add r5,fp,#4 @ first parameter address\n mov r2,#0 @ init loop counter\nloop:\n ldr r0,[r5,r2,lsl #2] @ string address parameter\n bl affichageMess @ display string\n ldr r0,iAdrszCarriageReturn\n bl affichageMess @ display carriage return\n add r2,#1 @ increment counter\n cmp r2,r4 @ number parameters ?\n blt loop @ loop\n\n100: @ standard end of the program\n mov r0, #0 @ return code\n pop {fp,lr} @restaur registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\n\niAdrszCarriageReturn: .int szCarriageReturn\n\n\n/******************************************************************/\n/* display text with size calculation */\n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index\n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop\n @ so here r2 contains the length of the message\n mov r1,r0 @ address message in r1\n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\"\n svc #0 @ call systeme\n pop {r0,r1,r2,r7,lr} @ restaur 2 registres\n bx lr @ return\n", "language": "ARM-Assembly" }, { "code": "loop arg 'a [\n\tprint a\n]\n", "language": "Arturo" }, { "code": "Loop %0% ; number of parameters\n params .= %A_Index% . A_Space\nIf params !=\n MsgBox, %0% parameters were passed:`n`n %params%\nElse\n Run, %A_AhkPath% \"%A_ScriptFullPath%\" -c \"\\\"alpha beta\\\"\" -h \"\\\"gamma\\\"\"\n", "language": "AutoHotkey" }, { "code": "#!/usr/bin/awk -f\n\nBEGIN {\n print \"There are \" ARGC \"command line parameters\"\n for(l=1; l<ARGC; l++) {\n print \"Argument \" l \" is \" ARGV[l]\n }\n}\n", "language": "AWK" }, { "code": "babel -i Larry Mo Curly\n", "language": "Babel" }, { "code": "argv prn !\n", "language": "Babel" }, { "code": "argv prs !\n", "language": "Babel" }, { "code": "argv 1 ith say !\n", "language": "Babel" }, { "code": "' Command line arguments including program name\nPRINT \"Entire command line: \", ARGUMENT$\n\nSPLIT ARGUMENT$ BY \" \" TO cli$ SIZE args\nPRINT \"Skip program name:\";\nFOR i = 1 TO args - 1\n PRINT \" \" & cli$[i];\nNEXT\nPRINT\n", "language": "BaCon" }, { "code": "PRINT \"args: '\"; COMMAND$; \"'\"\n", "language": "BASIC" }, { "code": "DIM i AS INTEGER\n\nPRINT COMMAND$\n\nPRINT \"This program is named \"; COMMAND$(0)\ni = 1\nDO WHILE(LEN(COMMAND$(i)))\n PRINT \"The argument \"; i; \" is \"; COMMAND$(i)\n i = i + 1\nLOOP\n\nFOR i = 0 TO __FB_ARGC__ - 1\n PRINT \"arg \"; i; \" = '\"; *__FB_ARGV__[i]; \"'\"\nNEXT i\n", "language": "BASIC" }, { "code": "@echo off\nsetlocal enabledelayedexpansion\n\nset Count=0\n:loop\nif not \"%1\"==\"\" (\n set /a count+=1\n set parameter[!count!]=%1\n shift\n goto loop\n)\n\nfor /l %%a in (1,1,%count%) do (\n echo !parameter[%%a]!\n)\n", "language": "Batch-File" }, { "code": "::args2.cmd\n@echo off\nsetlocal enabledelayedexpansion\nset fn=%~f0\nset p0=%~0\nset p*=%*\nset /a c=1\n:loop\nif @%1==@ goto done\n\tset p%c%=%~1\n\tset /a c=c+1\n\tshift\n\tgoto loop\n:done\nset /a c=c-1\nset p#=%c%\necho fn=%fn%\necho p0=%p0%\necho p*=%p*%\necho p#=%p#%\nfor /l %%i in (1,1,%p#%) do (\n\techo p%%i=!p%%i!\n)\n", "language": "Batch-File" }, { "code": ">args2 foo \"bar baz\" quux\nfn=d:\\bin\\args2.cmd\np0=args2\np*=foo \"bar baz\" quux\np#=3\np1=foo\np2=bar baz\np3=quux\n", "language": "Batch-File" }, { "code": "PRINT @cmd$\n", "language": "BBC-BASIC" }, { "code": "global _start\n\n: syscall ( num:eax -- result:eax | rcx ) syscall ;\n\n: exit ( status:edi -- noret ) 60 syscall ;\n: bye ( -- noret ) 0 exit ;\n: die ( err:eax -- noret ) neg exit ;\n\n: unwrap ( result:eax -- value:eax ) dup 0 cmp ' die xl ;\n: ordie ( result -- ) unwrap drop ;\n\n1 const stdout\n\n: write ( buf:esi len:edx fd:edi -- ) 1 syscall ordie ;\n: print ( buf len -- ) stdout write ;\n\n: newline ( -- ) s\" \\n\" print ;\n: println ( buf len -- ) print newline ;\n\n: find0 ( start:rsi -- end:rsi ) lodsb 0 cmp latest xne ;\n: cstrlen ( str:rdi -- len:rsi ) dup find0 swap sub dec ;\n: cstr>str ( cstr:rdx -- str:rsi len:rdx ) dup cstrlen xchg ;\n\n: print-arg ( arg -- ) cstr>str println ;\n\n: _start ( rsp -- noret ) dup @ swap\n: print-args ( argc:rcx argv:rsp -- noret )\n\t8 add @ print-arg latest loop\n\tbye\n;\n", "language": "Blue" }, { "code": "•Show •args\n", "language": "BQN" }, { "code": "whl'(arg$:?a&out$(str$(\"next arg=\" !a)))\n", "language": "Bracmat" }, { "code": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n int i;\n (void) printf(\"This program is named %s.\\n\", argv[0]);\n for (i = 1; i < argc; ++i)\n (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n return EXIT_SUCCESS;\n}\n", "language": "C" }, { "code": "#include <iostream>\n\nint main(int argc, const char* argv[]) {\n std::cout << \"This program is named \" << argv[0] << '\\n'\n << \"There are \" << argc - 1 << \" arguments given.\\n\";\n for (int i = 1; i < argc; ++i)\n std::cout << \"The argument #\" << i << \" is \" << argv[i] << '\\n';\n}\n", "language": "C++" }, { "code": "using System;\n\nnamespace RosettaCode {\n class Program {\n static void Main(string[] args) {\n for (int i = 0; i < args.Length; i++)\n Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n }\n }\n}\n", "language": "C-sharp" }, { "code": "using System;\n\nnamespace RosettaCode {\n class Program {\n static void Main() {\n string[] args = Environment.GetCommandLineArgs();\n for (int i = 0; i < args.Length; i++)\n Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n }\n }\n}\n", "language": "C-sharp" }, { "code": "import std::io;\n\nfn void main(String[] args)\n{\n io::printfn(\"This program is named %s.\", args[0]);\n for (int i = 1; i < args.len; i++)\n {\n io::printfn(\"the argument #%d is %s\\n\", i, args[i]);\n }\n}\n", "language": "C3" }, { "code": "import ArgEnv\n\nStart = getCommandLine\n", "language": "Clean" }, { "code": "(dorun (map println *command-line-args*))\n", "language": "Clojure" }, { "code": "% This program needs to be merged with PCLU's \"useful.lib\",\n% where get_argv lives.\n%\n% pclu -merge $CLUHOME/lib/useful.lib -compile cmdline.clu\n\nstart_up = proc ()\n po: stream := stream$primary_output()\n\n args: sequence[string] := get_argv()\n\n for arg: string in sequence[string]$elements(args) do\n stream$putl(po, \"arg: \" || arg)\n end\nend start_up\n", "language": "CLU" }, { "code": " IDENTIFICATION DIVISION.\n PROGRAM-ID. accept-all-args.\n\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 args PIC X(50).\n\n PROCEDURE DIVISION.\n main-line.\n ACCEPT args FROM COMMAND-LINE\n DISPLAY args\n\n GOBACK\n .\n", "language": "COBOL" }, { "code": " IDENTIFICATION DIVISION.\n PROGRAM-ID. accept-args-one-at-a-time.\n\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 arg PIC X(50) VALUE SPACES.\n\n PROCEDURE DIVISION.\n ACCEPT arg FROM ARGUMENT-VALUE\n PERFORM UNTIL arg = SPACES\n DISPLAY arg\n MOVE SPACES TO arg\n ACCEPT arg FROM ARGUMENT-VALUE\n END-PERFORM\n\n GOBACK\n .\n", "language": "COBOL" }, { "code": " *>Created By Zwiegnet 8/19/2004\n\n IDENTIFICATION DIVISION.\n PROGRAM-ID. arguments.\n\n ENVIRONMENT DIVISION.\n\n DATA DIVISION.\n\n\n WORKING-STORAGE SECTION.\n\n 01 command1 PIC X(50).\n 01 command2 PIC X(50).\n 01 command3 PIC X(50).\n\n\n PROCEDURE DIVISION.\n\n PERFORM GET-ARGS.\n\n *> Display Usage for Failed Checks\n ARGUSAGE.\n display \"Usage: <command1> <command2> <command3>\"\n STOP RUN.\n\n *> Evaluate Arguments\n GET-ARGS.\n ACCEPT command1 FROM ARGUMENT-VALUE\n IF command1 = SPACE OR LOW-VALUES THEN\n PERFORM ARGUSAGE\n ELSE\n INSPECT command1 REPLACING ALL SPACES BY LOW-VALUES\n\n\n ACCEPT command2 from ARGUMENT-VALUE\n IF command2 = SPACE OR LOW-VALUES THEN\n PERFORM ARGUSAGE\n ELSE\n INSPECT command2 REPLACING ALL SPACES BY LOW-VALUES\n\n\n ACCEPT command3 from ARGUMENT-VALUE\n IF command3 = SPACE OR LOW-VALUES THEN\n PERFORM ARGUSAGE\n ELSE\n INSPECT command3 REPLACING ALL SPACES BY LOW-VALUES\n\n\n\n *> Display Final Output\n display command1 \" \" command2 \" \" command3\n\n\n STOP RUN.\n\n.\n", "language": "COBOL" }, { "code": "console.log arg for arg in process.argv\n", "language": "CoffeeScript" }, { "code": "(defun argv ()\n (or\n #+clisp (ext:argv)\n #+sbcl sb-ext:*posix-argv*\n #+abcl ext:*command-line-argument-list*\n #+clozure (ccl::command-line-arguments)\n #+gcl si:*command-args*\n #+ecl (loop for i from 0 below (si:argc) collect (si:argv i))\n #+cmu extensions:*command-line-strings*\n #+allegro (sys:command-line-arguments)\n #+lispworks sys:*line-arguments-list*\n nil))\n", "language": "Common-Lisp" }, { "code": "include \"cowgol.coh\";\ninclude \"argv.coh\";\n\nArgvInit();\nvar i: uint8 := 0;\n\nloop\n var arg := ArgvNext();\n if arg == 0 as [uint8] then break; end if;\n i := i + 1;\n print_i8(i);\n print(\": '\");\n print(arg);\n print(\"'\\n\");\nend loop;\n", "language": "Cowgol" }, { "code": "void main(in string[] args) {\n import std.stdio;\n\n foreach (immutable i, arg; args[1 .. $])\n writefln(\"#%2d : %s\", i + 1, arg);\n}\n", "language": "D" }, { "code": "main(List<String> args) {\n for(var arg in args)\n print(arg);\n}\n", "language": "Dart" }, { "code": "$ i = 1\n$ loop:\n$ write sys$output \"the value of P''i' is \", p'i\n$ i = i + 1\n$ if i .le. 8 then $ goto loop\n", "language": "DCL" }, { "code": "// The program name and the directory it was called from are in\n// param[0] , so given the axample of myprogram -c \"alpha beta\" -h \"gamma\"\n\n for x := 0 to paramcount do\n writeln('param[',x,'] = ',param[x]);\n\n// will yield ( assuming windows and the c drive as the only drive) :\n\n// param[0] = c:\\myprogram\n// param[1] = -c\n// param[2] = alpha beta\n// param[3] = -h\n// param[4] = gamma\n", "language": "Delphi" }, { "code": "\\util.g\n\nproc nonrec main() void:\n *char par;\n word i;\n i := 0;\n while par := GetPar(); par ~= nil do\n i := i + 1;\n writeln(i:3, \": '\", par, \"'\")\n od\ncorp\n", "language": "Draco" }, { "code": "interp.getArgs()\n", "language": "E" }, { "code": "class\n APPLICATION\ninherit\n ARGUMENTS\ncreate\n make\nfeature {NONE} -- Initialization\n make\n -- Print values for arguments with options 'c' and 'h'.\n do\n print (\"Command line argument value for option 'c' is: \")\n print (separate_character_option_value ('c') + \"%N\")\n print (\"Command line argument value for option 'h' is: \")\n print (separate_character_option_value ('h') + \"%N\")\n io.read_line -- Keep console window open\n end\nend\n", "language": "Eiffel" }, { "code": "import system'routines;\nimport extensions;\n\npublic program()\n{\n program_arguments.forEvery::(int i)\n { console.printLine(\"Argument \",i,\" is \",program_arguments[i]) }\n}\n", "language": "Elena" }, { "code": "#!/usr/bin/env elixir\nIO.puts 'Arguments:'\nEnum.map(System.argv(),&IO.puts(&1))\n", "language": "Elixir" }, { "code": "$ ./show-args.exs a b=2 --3 -4\nArguments:\na\nb=2\n--3\n-4\n", "language": "Elixir" }, { "code": "(while argv\n (message \"Argument: %S\" (pop argv)))\n", "language": "Emacs-Lisp" }, { "code": "3> init:get_arguments().\n", "language": "Erlang" }, { "code": "[{root,[\"/usr/erlang/erl5.5\"]},\n{progname,[\"erl\"]},\n{home,[\"/home/me\"]},\n{c,[\"alpha beta\"]},\n{h,[\"gamma\"]}]\n", "language": "Erlang" }, { "code": "4> init:get_argument(h).\n{ok,[[\"gamma\"]]}\n5> init:get_argument(c).\n{ok,[[\"alpha beta\"]]}\n", "language": "Erlang" }, { "code": "constant cmd = command_line()\nprintf(1,\"Interpreter/executable name: %s\\n\",{cmd[1]})\nprintf(1,\"Program file name: %s\\n\",{cmd[2]})\nif length(cmd)>2 then\n puts(1,\"Command line arguments:\\n\")\n for i = 3 to length(cmd) do\n printf(1,\"#%d : %s\\n\",{i,cmd[i]})\n end for\nend if\n", "language": "Euphoria" }, { "code": "#light\n[<EntryPoint>]\nlet main args =\n Array.iter (fun x -> printfn \"%s\" x) args\n 0\n", "language": "F-Sharp" }, { "code": "ARGV each: |a| {\n a println # print each given command line argument\n}\n", "language": "Fancy" }, { "code": "class Main\n{\n public static Void main (Str[] args)\n {\n echo (\"command-line args are: \" + args)\n }\n}\n", "language": "Fantom" }, { "code": "\\ args.f: print each command line argument on a separate line\n: main\n argc @ 0 do i arg type cr loop ;\n\nmain bye\n", "language": "Forth" }, { "code": "$ gforth args.f alpha \"beta gamma\" delta\ngforth\nargs.f\nalpha\nbeta gamma\ndelta\n$\n", "language": "Forth" }, { "code": "program command_line_arguments\n\n implicit none\n integer, parameter :: len_max = 256\n integer :: i , nargs\n character (len_max) :: arg\n\n nargs = command_argument_count()\n !nargs = iargc()\n do i = 0, nargs\n call get_command_argument (i, arg)\n !call getarg (i, arg)\n write (*, '(a)') trim (arg)\n end do\n\nend program command_line_arguments\n", "language": "Fortran" }, { "code": "> ./a.out -c \"alpha beta\" -h \"gamma\"\n./a.out\n-c\nalpha beta\n-h\ngamma\n", "language": "Fortran" }, { "code": "Program listArguments(input, output, stdErr);\n\nVar\n i: integer;\nBegin\n writeLn('program was called from: ',paramStr(0));\n For i := 1 To paramCount() Do\n Begin\n writeLn('argument',i:2,' : ', paramStr(i));\n End;\nEnd.\n", "language": "Free-Pascal-Lazarus" }, { "code": "' FB 1.05.0 Win64\n\n' Program (myprogram.exe) invoke as follows:\n' myprogram -c \"alpha beta\" -h \"gamma\"\n\nPrint \"The program was invoked like this => \"; Command(0) + \" \" + Command(-1)\nPrint\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "println[ARGS]\n", "language": "Frink" }, { "code": "println( args )\n", "language": "FunL" }, { "code": "PUBLIC SUB main()\n DIM l AS Integer\n DIM numparms AS Integer\n DIM parm AS String\n numparms = Application.Args.Count\n FOR l = 0 TO numparms - 1\n parm = Application.Args[l]\n PRINT l; \" : \"; parm\n NEXT\nEND\n", "language": "Gambas" }, { "code": "[indent=4]\n/*\n Command line arguments, in Genie\n\n valac commandLine.gs\n ./commandLine sample arguments 'four in total here, including args 0'\n*/\n\ninit\n\n // Output the number of arguments\n print \"%d command line argument(s):\", args.length\n\n // Enumerate all command line arguments\n for s in args\n print s\n\n // to reiterate, args[0] is the command\n if args[0] is not null\n print \"\\nWith Genie, args[0] is the command: %s\", args[0]\n", "language": "Genie" }, { "code": "λ 'as. impmapM (λ 'a. print qq{Argument: §(a)\\n}) as\n", "language": "Global-Script" }, { "code": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "language": "Go" }, { "code": "println args\n", "language": "Groovy" }, { "code": "PROCEDURE Main()\n\n LOCAL i\n\n FOR i := 1 TO PCount()\n ? \"argument\", hb_ntos( i ), \"=\", hb_PValue( i )\n NEXT\n\n RETURN\n", "language": "Harbour" }, { "code": "import System\nmain = getArgs >>= print\n", "language": "Haskell" }, { "code": "DO i = 2, 100 ! 1 is HicEst.exe\n EDIT(Text=$CMD_LINE, SePaRators='-\"', ITeM=i, IF ' ', EXit, ENDIF, Parse=cmd, GetPosition=position)\n IF(position > 0) WRITE(Messagebox) cmd\nENDDO\n", "language": "HicEst" }, { "code": "procedure main(arglist)\nevery write(!arglist)\nend\n", "language": "Icon" }, { "code": "System args foreach(a, a println)\n", "language": "Io" }, { "code": "System programArguments each(println)\n", "language": "Ioke" }, { "code": " ARGV\n", "language": "J" }, { "code": "fn main(arguments: [String]) {\n println(\"{}\", arguments)\n}\n", "language": "Jakt" }, { "code": "public static void main(String[] args)\n", "language": "Java" }, { "code": "myprogram -c \"alpha beta\" -h \"gamma\"\n", "language": "Java" }, { "code": "public class Arguments {\n public static void main(String[] args) {\n System.out.println(\"There are \" + args.length + \" arguments given.\");\n for(int i = 0; i < args.length; i++)\n System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n }\n}\n", "language": "Java" }, { "code": "process.argv.forEach((val, index) => {\n console.log(`${index}: ${val}`);\n});\n", "language": "JavaScript" }, { "code": "var objArgs = WScript.Arguments;\nfor (var i = 0; i < objArgs.length; i++)\n WScript.Echo(objArgs.Item(i));\n", "language": "JavaScript" }, { "code": "import System;\nvar argv:String[] = Environment.GetCommandLineArgs();\nfor (var i in argv)\n print(argv[i]);\n", "language": "JavaScript" }, { "code": "for (var i = 0; i < arguments.length; i++)\n print(arguments[i]);\n", "language": "JavaScript" }, { "code": "#!/usr/bin/joy\n\nargv rest put.\n", "language": "Joy" }, { "code": "{\n \"positional\": [\n \"a\",\n \"b\"\n ],\n \"named\": {}\n}\n", "language": "Jq" }, { "code": "#!/usr/local/bin/jsish\nputs(Info.argv0());\nputs(console.args);\n", "language": "Jsish" }, { "code": "using Printf\n\nprog = Base.basename(Base.source_path())\n\nprintln(prog, \"'s command-line arguments are:\")\nfor s in ARGS\n println(\" \", s)\nend\n", "language": "Julia" }, { "code": ".p'.a\n", "language": "Klong" }, { "code": "fun main(args: Array<String>) {\n println(\"There are \" + args.size + \" arguments given.\")\n args.forEachIndexed { i, a -> println(\"The argument #${i+1} is $a and is at index $i\") }\n}\n", "language": "Kotlin" }, { "code": "$ele\nforeach($[ele], &LANG_ARGS) {\n fn.println($ele)\n}\n", "language": "Lang" }, { "code": "$ lang cmdarg.lang -- 2 abc test text\n", "language": "Lang" }, { "code": "#!/usr/bin/lasso9\n\niterate($argv) => {\n stdoutnl(\"Argument \" + loop_count + \": \" + loop_value)\n}\n", "language": "Lasso" }, { "code": "$ lasso9 arguments.lasso -c \"alpha beta\" -h \"gamma\"\nArgument 1: arguments.lasso\nArgument 2: -c\nArgument 3: alpha beta\nArgument 4: -h\nArgument 5: gamma\n", "language": "Lasso" }, { "code": "$ ./bin/lfe -pa ebin/ -c \"alpha beta\" -h \"gamma\"\n", "language": "LFE" }, { "code": "> (: init get_arguments)\n(#(root (\"/opt/erlang/r15b03\"))\n #(progname (\"erl\"))\n #(home (\"/Users/oubiwann\"))\n #(user (\"lfe_boot\"))\n #(pa (\"ebin/\"))\n #(c (\"alpha beta\"))\n #(h (\"gamma\")))\n", "language": "LFE" }, { "code": "> (: init get_argument 'c)\n#(ok ((\"alpha beta\")))\n> (: init get_argument 'h)\n#(ok ((\"gamma\")))\n", "language": "LFE" }, { "code": "print CommandLine$\n", "language": "Liberty-BASIC" }, { "code": "put the commandline\n-- \"-c alpha beta -h gamma\"\n", "language": "Lingo" }, { "code": "put getCommandLineArgs()\n-- [\"-c\", \"alpha beta\", \"-h\", \"gamma\"]\n", "language": "Lingo" }, { "code": "show :COMMAND.LINE\n[arg1 arg2 arg3]\n", "language": "Logo" }, { "code": "argc , nl # number of arguments (including command itself)\n0 # argument\ndup arg dup 0 = || ,t 1 + repeat\ndrop\n", "language": "LSE64" }, { "code": "print( \"Program name:\", arg[0] )\n\nprint \"Arguments:\"\nfor i = 1, #arg do\n print( i,\" \", arg[i] )\nend\n", "language": "Lua" }, { "code": "Module Checkit {\n Document a$ = {\n Module Global A {\n Show\n Read a$=\"nothing\", x=0\n Print a$, x\n A$=Key$\n }\n A: End\n }\n Dir temporary$\n Save.doc a$, \"program.gsb\"\n \\\\ open if gsb extension is register to m2000.exe\n Win quote$(dir$+\"program.gsb\")\n \\\\ +txt is a switch for interpreter to use string comparison as text (not binary)\n \\\\ so we can send switches and commands before the program loading\n Win appdir$+\"m2000.exe\", quote$(dir$+\"program.gsb +txt : Data {Hello}, 100\")\n \\\\ no coma after name (we can use \"program.gsb\" for names with spaces)\n Use program.gsb \"From Use statement\", 200\n \\\\ delete file\n Wait 5000\n Dos \"del \"+quote$(dir$+\"program.gsb\");\n \\\\ open directory\n Rem : Win temporary$\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "#!/usr/local/bin/MathematicaScript -script\n$CommandLine\n", "language": "Mathematica" }, { "code": ":- module cmd_line_args.\n:- interface.\n\n:- import_module io.\n:- pred main(io::di, io::uo) is det.\n\n:- implementation.\n:- import_module int, list, string.\n\nmain(!IO) :-\n io.progname(\"\", ProgName, !IO),\n io.format(\"This program is named %s.\\n\", [s(ProgName)], !IO),\n io.command_line_arguments(Args, !IO),\n list.foldl2(print_arg, Args, 1, _, !IO).\n\n:- pred print_arg(string::in, int::in, int::out, io::di, io::uo) is det.\n\nprint_arg(Arg, ArgNum, ArgNum + 1, !IO) :-\n io.format(\"the argument #%d is %s\\n\", [i(ArgNum), s(Arg)], !IO).\n", "language": "Mercury" }, { "code": "args\n", "language": "Min" }, { "code": "argv IS $1\nargc IS $0\ni IS $2\n\n LOC #100\nMain LOC @\n SETL i,1 % i = 1\nLoop CMP $3,argc,2 % argc < 2 ?\n BN $3,1F % then jump to end\n XOR $255,$255,$255 % clear $255\n 8ADDU $255,i,argv % i*8 + argv\n LDOU $255,$255,0 % argv[i]\n TRAP 0,Fputs,StdOut % write the argument\n GETA $255,NewLine % add a newline\n TRAP 0,Fputs,StdOut\n INCL i,1 % increment index\n SUB argc,argc,1 % argc--\n BP argc,Loop % argc > 0? then Loop\n1H LOC @\n XOR $255,$255,$255 % exit(0)\n TRAP 0,Halt,0\n\nNewLine BYTE #a,0\n", "language": "MMIX" }, { "code": "MODULE try;\n\nFROM Arguments IMPORT GetArgs, ArgTable, GetEnv;\nFROM InOut IMPORT WriteCard, WriteLn, WriteString;\n\nVAR count, item : SHORTCARD;\n storage : ArgTable;\n\nBEGIN\n GetArgs (count, storage);\n WriteString ('Count ='); WriteCard (count, 4); WriteLn;\n item := 0;\n REPEAT\n WriteCard (item, 4);\n WriteString (' : ');\n WriteString (storage^ [item]^);\n WriteLn;\n INC (item)\n UNTIL item = count\nEND try.\n", "language": "Modula-2" }, { "code": "jan@Beryllium:~/modula/test$ try jantje zag eens pruimen hangen\nCount = 6\n 0 : try\n 1 : jantje\n 2 : zag\n 3 : eens\n 4 : pruimen\n 5 : hangen\n", "language": "Modula-2" }, { "code": "MODULE Args EXPORTS Main;\n\nIMPORT IO, Params;\n\nBEGIN\n IO.Put(Params.Get(0) & \"\\n\");\n IF Params.Count > 1 THEN\n FOR i := 1 TO Params.Count - 1 DO\n IO.Put(Params.Get(i) & \"\\n\");\n END;\n END;\nEND Args.\n", "language": "Modula-3" }, { "code": "//\n// command-line arguments\n//\n\n// output all arguments\nfor i in range(0, len(args) - 1)\n\tprintln args[i]\nend\n", "language": "Nanoquery" }, { "code": "/* command line arguments, neko */\nvar argc = $asize($loader.args)\n\n/* Display count and arguments, indexed from 0, no script name included */\n$print(\"There are \", argc, \" arguments\\n\")\n\nvar arg = 0\nwhile arg < argc $print($loader.args[arg ++= 1], \"\\n\")\n", "language": "Neko" }, { "code": "using System;\nusing System.Console;\n\nmodule CLArgs\n{\n Main(args : array[string]) : void\n {\n foreach (arg in args) Write($\"$arg \"); // using the array passed to Main(), everything after the program name\n Write(\"\\n\");\n\n def cl_args = Environment.GetCommandLineArgs(); // also gets program name\n foreach (cl_arg in cl_args) Write($\"$cl_arg \");\n }\n}\n", "language": "Nemerle" }, { "code": "/* NetRexx */\n-- sample arguments: -c \"alpha beta\" -h \"gamma\"\nsay \"program arguments:\" arg\n", "language": "NetRexx" }, { "code": "import os\necho \"program name: \", getAppFilename()\necho \"Arguments:\"\nfor arg in commandLineParams():\n echo arg\n", "language": "Nim" }, { "code": "def main [...argv] {\n\t$argv | print\n}\n", "language": "Nu" }, { "code": "MODULE CommandLineArguments;\nIMPORT\n NPCT:Args,\n Out := NPCT:Console;\n\nBEGIN\n Out.String(\"Args number: \");Out.Int(Args.Number(),0);Out.Ln;\n Out.String(\"0.- : \");Out.String(Args.AsString(0));Out.Ln;\n Out.String(\"1.- : \");Out.String(Args.AsString(1));Out.Ln;\n Out.String(\"2.- : \");Out.String(Args.AsString(2));Out.Ln;\n Out.String(\"3.- : \");Out.String(Args.AsString(3));Out.Ln;\n Out.String(\"4.-: \");Out.String(Args.AsString(4));Out.Ln\nEND CommandLineArguments.\n", "language": "Oberon" }, { "code": "class Line {\n function : Main(args : String[]) ~ Nil {\n each(i : args) {\n args[i]->PrintLine();\n };\n }\n}\n", "language": "Objeck" }, { "code": "NSArray *args = [[NSProcessInfo processInfo] arguments];\nNSLog(@\"This program is named %@.\", [args objectAtIndex:0]);\nNSLog(@\"There are %d arguments.\", [args count] - 1);\nfor (i = 1; i < [args count]; ++i){\n NSLog(@\"the argument #%d is %@\", i, [args objectAtIndex:i]);\n}\n", "language": "Objective-C" }, { "code": "let () =\n Printf.printf \"This program is named %s.\\n\" Sys.argv.(0);\n for i = 1 to Array.length Sys.argv - 1 do\n Printf.printf \"the argument #%d is %s\\n\" i Sys.argv.(i)\n done\n", "language": "OCaml" }, { "code": "(* default values *)\nlet somebool = ref false\nlet somestr = ref \"\"\nlet someint = ref 0\n\nlet usage = \"usage: \" ^ Sys.argv.(0) ^ \" [-b] [-s string] [-d int]\"\n\nlet speclist = [\n (\"-b\", Arg.Set somebool, \": set somebool to true\");\n (\"-s\", Arg.Set_string somestr, \": what follows -s sets some string\");\n (\"-d\", Arg.Set_int someint, \": some int parameter\");\n ]\n\nlet () =\n (* Read the arguments *)\n Arg.parse\n speclist\n (fun x -> raise (Arg.Bad (\"Bad argument : \" ^ x)))\n usage;\n Printf.printf \" %b %d '%s'\\n\" !somebool !someint !somestr\n", "language": "OCaml" }, { "code": "package main\n\nimport \"core:os\"\nimport \"core:fmt\"\n\nmain :: proc() {\n fmt.println(os.args)\n}\n\n// Run: ./program -c \"alpha beta\" -h \"gamma\"\n// Output: [\"./program\", \"-c\", \"alpha beta\", \"-h\", \"gamma\"]\n", "language": "Odin" }, { "code": "System.Args println\n", "language": "Oforth" }, { "code": "functor\nimport Application System\ndefine\n ArgList = {Application.getArgs plain}\n {ForAll ArgList System.showInfo}\n {Application.exit 0}\nend\n", "language": "Oz" }, { "code": "functor\nimport Application System\ndefine\n ArgSpec =\n record(\n c(type:string single %% option \"--c\" expects a string, may only occur once,\n\toptional:false char:&c) %% is not optional and has a shortcut \"-c\"\n\t\n h(type:string single %% option \"--h\" expects a string, may only occur once,\n\tdefault:\"default h\" %% is optional and has a default value if not given\n\tchar:&h) %% and has a shortcut \"-h\"\n )\n Args = {Application.getArgs ArgSpec}\n {System.showInfo Args.c}\n {System.showInfo Args.h}\n {Application.exit 0}\nend\n", "language": "Oz" }, { "code": "my @params = @ARGV;\nmy $params_size = @ARGV;\nmy $second = $ARGV[1];\nmy $fifth = $ARGV[4];\n", "language": "Perl" }, { "code": "use Getopt::Long;\nGetOptions (\n 'help|h' => \\my $help,\n 'verbose|v' => \\my $verbose,\n);\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">cmd</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">command_line</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">cmd</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">cmd</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">cmd</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Compiled executable name: %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">cmd</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]})</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Interpreted (using %s) source name: %s\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cmd</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cmd</span><span style=\"color: #0000FF;\">)></span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Command line arguments:\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cmd</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"#%d : %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cmd</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "language": "PHP" }, { "code": "main(ARGS) =>\n println(ARGS).\nmain(_) => true.\n", "language": "Picat" }, { "code": "#!/usr/bin/picolisp /usr/lib/picolisp/lib.l\n\n(de c ()\n (prinl \"Got 'c': \" (opt)) )\n\n(de h ()\n (prinl \"Got 'h': \" (opt)) )\n\n(load T)\n(bye)\n", "language": "PicoLisp" }, { "code": "/* The entire command line except the command word itself is passed */\n/* to the parameter variable in PL/I. */\nprogram: procedure (command_line) options (main);\n declare command_line character (100) varying;\n\n...\n\nend program;\n", "language": "PL-I" }, { "code": "lvars arg;\nfor arg in poparglist do\n printf(arg, '->%s<-\\n');\nendfor;\n", "language": "Pop11" }, { "code": "? \"args: '\"; COMMAND$; \"'\"\n", "language": "PowerBASIC" }, { "code": "'these two both return ALL args\n? COMMAND$\n? COMMAND$(0)\n\nDO WHILE(LEN(COMMAND$(i)))\n PRINT \"The argument \"; i; \" is \"; COMMAND$(i)\n i = i + 1\nLOOP\n", "language": "PowerBASIC" }, { "code": "$i = 0\nforeach ($s in $args) {\n Write-Host Argument (++$i) is $s\n}\n", "language": "PowerShell" }, { "code": ":-\n current_prolog_flag(os_argv, Args),\n write(Args).\n", "language": "Prolog" }, { "code": ":-\n current_prolog_flag(argv, Args),\n write(Args).\n", "language": "Prolog" }, { "code": "using system;\n\nprintf \"There are %d command line argumants\\n\" argc;\nputs \"They are \" $$ map (puts) argv;\n", "language": "Pure" }, { "code": "If OpenConsole()\n Define n=CountProgramParameters()\n PrintN(\"Reading all parameters\")\n While n\n PrintN(ProgramParameter())\n n-1\n Wend\n Print(#CRLF$+\"Press Enter\")\n Input()\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": "If OpenConsole()\n Define n\n PrintN(\"Reading specific pameters\")\n For n=0 To CountProgramParameters()\n PrintN(ProgramParameter(n))\n Next\n Print(#CRLF$+\"Press Enter\")\n Input()\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "language": "Python" }, { "code": "R CMD BATCH --vanilla --slave '--args a=1 b=c(2,5,6)' test.r test.out\n", "language": "R" }, { "code": "# Read the commandline arguments\nargs <- (commandArgs(TRUE))\n\n# args is now a list of character vectors\n# First check to see if any arguments were passed,\n# then evaluate each argument.\nif (length(args)==0) {\n print(\"No arguments supplied.\")\n # Supply default values\n a <- 1\n b <- c(1,1,1)\n} else {\n for (i in 1:length(args)) {\n eval(parse(text=args[[i]]))\n }\n}\nprint(a*2)\nprint(b*3)\n", "language": "R" }, { "code": "#lang racket\n(current-command-line-arguments)\n", "language": "Racket" }, { "code": "#lang racket\n\n(for ([arg (current-command-line-arguments)]) (displayln arg))\n", "language": "Racket" }, { "code": "# with arguments supplied\n$ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3 5\n8\n\n# missing argument:\n$ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3\nUsage:\n-e '...' x y\n", "language": "Raku" }, { "code": "PRINT \"This program is named \"; Command$(0)\nFOR i=1 TO CommandCount\n PRINT \"The argument \"; i; \" is \"; Command$(i)\nNEXT i\n", "language": "RapidQ" }, { "code": "ARGS print\n\nstack (6 items)\n 0 => \"raven\"\n 1 => \"myprogram\"\n 2 => \"-c\"\n 3 => \"alpha beta\"\n 4 => \"-h\"\n 5 => \"gamma\"\n", "language": "Raven" }, { "code": "Function Run(args() as String) As Integer\n For each arg As String In args\n Stdout.WriteLine(arg)\n Next\nEnd Function\n", "language": "REALbasic" }, { "code": "say 'command arguments:'\nsay arg(1)\n", "language": "REXX" }, { "code": "parse arg aaa /*get the arguments. */\n /*another version: */\n /* aaa=arg(1) */\nsay 'command arguments:'\nsay aaa\n\nopts='' /*placeholder for options. */\ndata='' /*placeholder for data. */\n\n do j=1 to words(aaa)\n x=word(aaa,j)\n if left(x,1)=='-' then opts=opts x /*Option? Then add to opts.*/\n else data=data x /*Must be data. Add to data.*/\n end\n\n /*the above process adds a leading blank to OPTS and DATA*/\n\nopts=strip(opts,'L') /*strip leading blanks. */\ndata=strip(data,'l') /*strip leading blanks. */\nsay\nsay 'options='opts\nsay ' data='data\n", "language": "REXX" }, { "code": "see copy(\"=\",30) + nl\nsee \"Command Line Parameters\" + nl\nsee \"Size : \" + len(sysargv) + nl\nsee sysargv\nsee copy(\"=\",30) + nl\nfor x = 1 to len(sysargv)\n see x + nl\nnext\n", "language": "Ring" }, { "code": "#! /usr/bin/env ruby\np ARGV\n", "language": "Ruby" }, { "code": "use std::env;\n\nfn main(){\n let args: Vec<_> = env::args().collect();\n println!(\"{:?}\", args);\n}\n", "language": "Rust" }, { "code": "./program -c \"alpha beta\" -h \"gamma\"\n[\"./program\", \"-c\", \"alpha beta\", \"-h\", \"gamma\"]\n", "language": "Rust" }, { "code": "variable a;\nforeach a (__argv)\n print(a);\n", "language": "S-lang" }, { "code": "class MAIN is\n main(args:ARRAY{STR}) is\n loop\n #OUT + args.elt! + \"\\n\";\n end;\n end;\nend;\n", "language": "Sather" }, { "code": "object CommandLineArguments extends App {\n println(s\"Received the following arguments: + ${args.mkString(\"\", \", \", \".\")}\")\n}\n", "language": "Scala" }, { "code": "println(s\"Received the following arguments: + ${argv.mkString(\"\", \", \", \".\")}\")\n", "language": "Scala" }, { "code": " (define (main args)\n (for-each (lambda (arg) (display arg) (newline)) args))\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst proc: main is func\n local\n var integer: i is 0;\n begin\n writeln(\"This program is named \" <& name(PROGRAM) <& \".\");\n for i range 1 to length(argv(PROGRAM)) do\n writeln(\"The argument #\" <& i <& \" is \" <& argv(PROGRAM)[i]);\n end for;\n end func;\n", "language": "Seed7" }, { "code": "say ARGV;\n", "language": "Sidef" }, { "code": "StartupArguments do: [| :arg | inform: arg]\n", "language": "Slate" }, { "code": "(display sys-args)\n", "language": "Slope" }, { "code": "(1 to: Smalltalk getArgc) do: [ :i |\n (Smalltalk getArgv: i) displayNl\n]\n", "language": "Smalltalk" }, { "code": "Smalltalk commandLineArguments printCR.\nSmalltalk commandLineArguments do:[:each | each printCR]\n", "language": "Smalltalk" }, { "code": "#!/usr/local/bin/spar\npragma annotate( summary, \"printargs\" )\n @( description, \"Retrieve the list of command-line arguments given to the program.\" )\n @( description, \"Example command line: \" )\n @( description, \"myprogram -c 'alpha beta' -h 'gamma'\" )\n @( category, \"tutorials\" )\n @( author, \"Ken O. Burtch\" )\n @( see_also, \"http://rosettacode.org/wiki/Command-line_arguments\" );\npragma license( unrestricted );\n\npragma software_model( nonstandard );\npragma restriction( no_external_commands );\n\nprocedure printargs is\nbegin\n put_line( \"The command is '\" & command_line.command_name & \"'\" );\n for Arg in 1..command_line.argument_count loop\n put( \"Argument\" ) @ (Arg ) @ ( \" is '\" ) @\n ( command_line.argument(Arg) ) @ (\"'\");\n new_line;\n end loop;\nend printargs;\n", "language": "SparForte" }, { "code": "print (\"This program is named \" ^ CommandLine.name () ^ \".\\n\");\nval args = CommandLine.arguments ();\nArray.appi\n (fn (i, x) => print (\"the argument #\" ^ Int.toString (i+1) ^ \" is \" ^ x ^ \"\\n\"))\n (Array.fromList args);\n", "language": "Standard-ML" }, { "code": "let args = Process.arguments\nprintln(\"This program is named \\(args[0]).\")\nprintln(\"There are \\(args.count-1) arguments.\")\nfor i in 1..<args.count {\n println(\"the argument #\\(i) is \\(args[i])\")\n}\n", "language": "Swift" }, { "code": "println(\"This program is named \\(String.fromCString(Process.unsafeArgv[0])!).\")\nprintln(\"There are \\(Process.argc-1) arguments.\")\nfor i in 1 ..< Int(Process.argc) {\n println(\"the argument #\\(i) is \\(String.fromCString(Process.unsafeArgv[i])!)\")\n}\n", "language": "Swift" }, { "code": "println(\"This program is named \\(String.fromCString(C_ARGV[0])!).\")\nprintln(\"There are \\(C_ARGC-1) arguments.\")\nfor i in 1 ..< Int(C_ARGC) {\n println(\"the argument #\\(i) is \\(String.fromCString(C_ARGV[i])!)\")\n}\n", "language": "Swift" }, { "code": "$ARGS -> !OUT::write\n", "language": "Tailspin" }, { "code": "if { $argc > 1 } {\n puts [lindex $argv 1]\n}\n", "language": "Tcl" }, { "code": "[ arglist array.get type cr ] is show-arg\n[ dup . char: = emit space ] is #=\n1 #args [ i #= show-arg ] countedLoop\n", "language": "Toka" }, { "code": "#lang transd\n\nMainModule: {\n\t_start: (λ\n (textout \"Number of arguments: \" @numArgs\n \"\\nArgument list: \" @progArgs)\n )\n}\n", "language": "Transd" }, { "code": "@(next :args)\n@(collect)\n@arg\n@(end)\n@(output)\nMy args are: {@(rep)@arg, @(last)@arg@(end)}\n@(end)\n", "language": "TXR" }, { "code": "(tree-case *args*\n ((a b c) (put-line \"got three args, thanks!\"))\n (else (put-line `usage: @(ldiff *full-args* *args*) <arg1> <arg2> <arg3>`)))\n", "language": "TXR" }, { "code": "WHOLELIST=\"$@\"\n", "language": "UNIX-Shell" }, { "code": "SECOND=$2\nFIFTH=$5\n", "language": "UNIX-Shell" }, { "code": "#\n# command-line arguments\n#\n\n# output all arguments\nfor (decl int i) (< i (size args)) (inc i)\n out args<i> endl console\nend for\n", "language": "Ursa" }, { "code": "#import std\n\n#executable ('parameterized','')\n\nclarg = <.file$[contents: --<''>+ _option%LP]>+ ~command.options\n", "language": "Ursala" }, { "code": "$stack puts\n\n./args.v a b c\n=[args.v a b c]\n", "language": "V" }, { "code": "import os\n\nfn main() {\n\tfor i, x in os.args[1..] {\n\t\tprintln(\"the argument #$i is $x\")\n\t}\n}\n", "language": "V-(Vlang)" }, { "code": "'Command line arguments can be accessed all together by\n\nFor Each arg In Wscript.Arguments\n Wscript.Echo \"arg=\", arg\nNext\n\n'You can access only the named arguments such as /arg:value\n\nFor Each arg In Wscript.Arguments.Named\n Wscript.Echo \"name=\", arg, \"value=\", Wscript.Arguments.Named(arg)\nNext\n\n'Or just the unnamed arguments\n\nFor Each arg In Wscript.Arguments.Unnamed\n Wscript.Echo \"arg=\", arg\nNext\n", "language": "VBScript" }, { "code": "Sub Main\n MsgBox Command$\nEnd Sub\n", "language": "Visual-Basic" }, { "code": "Sub Main(ByVal args As String())\n For Each token In args\n Console.WriteLine(token)\n Next\nEnd Sub\n", "language": "Visual-Basic-.NET" }, { "code": "import \"os\" for Process\n\nSystem.print(Process.arguments)\n", "language": "Wren" }, { "code": "int C;\n[loop [C:= ChIn(8);\n if C = \\EOF\\$1A then quit;\n ChOut(0, C);\n ];\nCrLf(0);\n]\n", "language": "XPL0" }, { "code": "System.argv.println();\nvm.arglist.println();\n", "language": "Zkl" } ]
Command-line-arguments
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Commatizing_numbers\nnote: Arithmetic operations\n", "language": "00-META" }, { "code": "''Commatizing'' &nbsp; numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string.\n\n\n;Task:\nWrite a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some\nother characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. \n\nSome of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines.\n\nThe number may be part of a larger (non-numeric) string such as:\n::::* &nbsp; «US$1744 millions» &nbsp; &nbsp; &nbsp; ──or──\n::::* &nbsp; ±25000 motes.\n\n<br>\nThe string may possibly ''not'' have a number suitable for commatizing, so it should be untouched and ''no error generated''.\n\nIf any argument (option) is invalid, nothing is changed and no error ''need be'' generated (quiet execution, no fail execution). &nbsp; Error message generation is optional.\n\nThe exponent part of a number is never commatized. &nbsp; The following string isn't suitable for commatizing: &nbsp; 9.7e+12000\n\nLeading zeroes are never commatized. &nbsp; The string &nbsp; 0000000005714.882 &nbsp; after commatization is: &nbsp; 0000000005,714.882\n\nAny &nbsp; ''period'' &nbsp; (<big><b>.</b></big>) &nbsp; in a number is assumed to be a &nbsp; ''decimal point''.\n\nThe original string is never changed &nbsp; ''except'' &nbsp; by the addition of commas &nbsp; [or whatever character(s) is/are used for insertion], if at all.\n\nTo wit, the following should be preserved:\n\n::* &nbsp; leading signs ('''+''', '''-''') &nbsp; &nbsp; &nbsp; ── even superfluous signs\n::* &nbsp; leading/trailing/embedded blanks, tabs, and other whitespace \n::* &nbsp; the case (upper/lower) of the exponent indicator, e.g.: &nbsp; 4.8903d-002\n\n<br>\nAny exponent character(s) should be supported:\n::::::* &nbsp; 1247e12\n::::::* &nbsp; 57256.1D-4\n::::::* &nbsp; 4444^60\n::::::* &nbsp; 7500<b>∙</b>10**35\n::::::* &nbsp; 8500x10**35\n::::::* &nbsp; 9500↑35\n::::::* &nbsp; +55000↑3\n::::::* &nbsp; 1000**100\n::::::* &nbsp; 2048²\n::::::* &nbsp; 4096<sup>32</sup>\n::::::* &nbsp; 10000pow(pi)\n\n<br>Numbers may be terminated with any non-digit character, including subscripts and/or superscript: &nbsp; 4142135624<sup>3</sup> &nbsp; or &nbsp; 7320509076<sub>(base 24)</sub>.\n\nThe character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters. &nbsp; The default is the comma (<big>''','''</big>) character.\n\nThe &nbsp; ''period length'' &nbsp; can be specified &nbsp; (sometimes referred to as \"thousands\" or \"thousands separators\"). &nbsp; The &nbsp; ''period length'' &nbsp; can be defined as the length (or number) of the decimal digits between commas. &nbsp; The default period length is &nbsp; <big>3</big>.\n\n::: E.G.: &nbsp; in this example, the &nbsp; ''period length'' &nbsp; is five: &nbsp; 56789,12340,14148\n\nThe location of where to start the scanning for the target field (the numeric part) should be able to be specified. &nbsp; The default is &nbsp; <big>1</big>.\n\nThe character strings below may be placed in a file (and read) or stored as simple strings within the program.\n\n\n;Strings to be used as a minimum:\nThe value of &nbsp; pi &nbsp; (expressed in base 10) &nbsp; should be separated with blanks every &nbsp; '''5''' &nbsp; places past the decimal point,\n<br>the Zimbabwe dollar amount should use a decimal point for the \"comma\" separator:\n\n:* &nbsp; pi=3.14159265358979323846264338327950288419716939937510582097494459231\n:* &nbsp; The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\n:* &nbsp; \"-in Aus$+1411.8millions\"\n:* &nbsp; ===US$0017440 millions=== (in 2000 dollars)\n:* &nbsp; 123.e8000 is pretty big.\n:* &nbsp; The land area of the earth is 57268900(29% of the surface) square miles.\n:* &nbsp; Ain't no numbers in this here words, nohow, no way, Jose.\n:* &nbsp; James was never known as 0000000007\n:* &nbsp; Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\n:* &nbsp; ␢␢␢$-140000±100 millions.\n:* &nbsp; 6/9/1946 was a good year for some.\n<br>where the penultimate string has three leading blanks &nbsp; (real blanks are to be used).\n\n\n;Also see:\n* The Wiki entry: &nbsp; [http://en.wikipedia.org/wiki/Eddington_number (sir) Arthur Eddington's number of protons in the universe]. <br><br>\n\n", "language": "00-TASK" }, { "code": "F commatize(s, period = 3, sep = ‘,’)\n V m = re:‘(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)’.search(s)\n I !m\n R s\n\n V match = m.group()\n V splits = match.split(‘.’)\n\n V ip = splits[0]\n I ip.len > period\n V inserted = 0\n L(i) ((ip.len - 1) % period + 1 .< ip.len).step(period)\n ip = ip[0 .< i + inserted]‘’sep‘’ip[i + inserted ..]\n inserted += sep.len\n\n I splits.len > 1\n V dp = splits[1]\n I dp.len > period\n L(i) ((dp.len - 1) I/ period * period .< period - 1).step(-period)\n dp = dp[0 .< i]‘’sep‘’dp[i..]\n ip ‘’= ‘.’dp\n\n R s[0 .< m.start()]‘’ip‘’s[m.end()..]\n\nV tests = [‘123456789.123456789’,\n ‘.123456789’,\n ‘57256.1D-4’,\n ‘pi=3.14159265358979323846264338327950288419716939937510582097494459231’,\n ‘The author has two Z$100000000000000 Zimbabwe notes (100 trillion).’,\n ‘-in Aus$+1411.8millions’,\n ‘===US$0017440 millions=== (in 2000 dollars)’,\n ‘123.e8000 is pretty big.’,\n ‘The land area of the earth is 57268900(29% of the surface) square miles.’,\n ‘Ain't no numbers in this here words, nohow, no way, Jose.’,\n ‘James was never known as 0000000007’,\n ‘Arthur Eddington wrote: I believe there are ’\"\"\n ‘15747724136275002577605653961181555468044717914527116709366231425076185631031296’\"\"\n ‘ protons in the universe.’,\n ‘ $-140000±100 millions.’,\n ‘6/9/1946 was a good year for some.’]\n\nprint(commatize(tests[0], period' 2, sep' ‘*’))\nprint(commatize(tests[1], period' 3, sep' ‘-’))\nprint(commatize(tests[2], period' 4, sep' ‘__’))\nprint(commatize(tests[3], period' 5, sep' ‘ ’))\nprint(commatize(tests[4], sep' ‘.’))\n\nL(test) tests[5..]\n print(commatize(test))\n", "language": "11l" }, { "code": "# returns text commatized according to the rules of the task and the #\n# period, location and separator paramters #\nPROC commatize = ( STRING text, INT location, INT period, STRING separator )STRING:\n IF STRING str := text[ AT 1 ];\n # handle the options #\n INT start position := IF location = 0 THEN 1 ELSE location FI;\n INT period length := IF period = 0 THEN 3 ELSE period FI;\n STRING separator string := IF separator = \"\" THEN \",\" ELSE separator FI;\n period length < 1 OR start position < 1 OR start position > UPB str\n THEN\n # invalid parameters - return the text unchanged #\n text\n ELIF # attempt to find a non-zero digit #\n INT number pos := start position;\n WHILE IF number pos > UPB str\n THEN FALSE\n ELSE str[ number pos ] < \"1\" OR str[ number pos ] > \"9\"\n FI\n DO\n number pos +:= 1\n OD;\n number pos > UPB str\n THEN # no digits in the string - return the text unchanged #\n text\n ELSE # have at least one digit #\n STRING result := str[ 1 : number pos - 1 ];\n # find the final digit #\n INT number end := number pos;\n WHILE IF number end >= UPB str\n THEN FALSE\n ELSE str[ number end + 1 ] >= \"0\" AND str[ number end + 1 ] <= \"9\"\n FI\n DO\n number end +:= 1\n OD;\n # copy the digits commatizing as required #\n INT digit count := ( number end - number pos ) + 1;\n WHILE digit count > 1 DO\n result +:= str[ number pos ];\n number pos +:= 1;\n digit count -:= 1;\n IF digit count MOD period length = 0 THEN\n # need a comma after this digit #\n result +:= separator string\n FI\n OD;\n # final digit and the rest of the string #\n result +:= str[ number pos : ];\n result\n FI # commatize # ;\n\n# modes and operators to allow us to specify optional parameters to the #\n# commatizing procedure #\nMODE COMMATIZINGOPTIONS = STRUCT( STRING text, INT location, INT period, STRING separator );\nPRIO LOCATION = 9;\nOP LOCATION = ( STRING text, INT location )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text, location, 0, \"\" );\nPRIO PERIOD = 9;\nOP PERIOD = ( STRING text, INT period )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text, 0, period, \"\" );\nPRIO SEPARATOR = 9;\nOP SEPARATOR = ( STRING text, CHAR separator )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text, 0, 0, separator );\nOP SEPARATOR = ( STRING text, STRING separator )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text, 0, 0, separator );\nOP LOCATION = ( COMMATIZINGOPTIONS opts, INT location )COMMATIZINGOPTIONS:\n COMMATIZINGOPTIONS( text OF opts, location, period OF opts, separator OF opts );\nOP PERIOD = ( COMMATIZINGOPTIONS opts, INT period )COMMATIZINGOPTIONS:\n COMMATIZINGOPTIONS( text OF opts, location OF opts, period, separator OF opts );\nOP SEPARATOR = ( COMMATIZINGOPTIONS opts, CHAR separator )COMMATIZINGOPTIONS:\n COMMATIZINGOPTIONS( text OF opts, location OF opts, period OF opts, separator );\nOP SEPARATOR = ( COMMATIZINGOPTIONS opts, STRING separator )COMMATIZINGOPTIONS:\n COMMATIZINGOPTIONS( text OF opts, location OF opts, period OF opts, separator );\nOP COMMATIZE = ( STRING text )STRING: commatize( text, 0, 0, \"\" );\nOP COMMATIZE = ( COMMATIZINGOPTIONS opts )STRING:\n commatize( text OF opts, location OF opts, period OF opts, separator OF opts );\n\n# test the commatization procedure and operators #\nprint( ( COMMATIZE( \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\" PERIOD 5 SEPARATOR \" \" LOCATION 6 ),\n newline ) );\nprint( ( COMMATIZE( \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\" SEPARATOR \".\" ), newline ) );\nprint( ( COMMATIZE \"\"\"-in Aus$+1411.8millions\"\"\", newline ) );\nprint( ( COMMATIZE \"===US$0017440 millions=== (in 2000 dollars)\", newline ) );\nprint( ( COMMATIZE \"123.e8000 is pretty big.\", newline ) );\nprint( ( COMMATIZE \"The land area of the earth is 57268900(29% of the surface) square miles.\", newline ) );\nprint( ( COMMATIZE \"Ain't no numbers in this here words, nohow, no way, Jose.\", newline ) );\nprint( ( COMMATIZE \"James was never known as 0000000007\", newline ) );\nprint( ( COMMATIZE \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\",\n newline ) );\nprint( ( COMMATIZE \" $-140000±100 millions.\", newline ) );\nprint( ( COMMATIZE \"6/9/1946 was a good year for some.\", newline ) )\n", "language": "ALGOL-68" }, { "code": "static string[] inputs = {\n\t\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n\t\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n\t\"\\\"-in Aus$+1411.8millions\\\"\",\n\t\"===US$0017440 millions=== (in 2000 dollars)\"\n};\n\nvoid Main()\n{\n\tinputs.Select(s => Commatize(s, 0, 3, \",\"))\n .ToList()\n .ForEach(Console.WriteLine);\n}\n\nstring Commatize(string text, int startPosition, int interval, string separator)\n{\n\tvar matches = Regex.Matches(text.Substring(startPosition), \"[0-9]*\");\n\tvar x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList();\n\treturn string.Join(\"\", x);\n}\n\n\nstring Commatize(Match match, int interval, string separator, string original)\n{\n\tif (match.Length <= interval)\n\t\treturn original.Substring(match.Index,\n match.Index == original.Length ? 0 : Math.Max(match.Length, 1));\n\t\n\treturn string.Join(separator, match.Value.Split(interval));\n}\n\npublic static class Extension\n{\n\tpublic static string[] Split(this string source, int interval)\n\t{\n\t\treturn SplitImpl(source, interval).ToArray();\n\t}\n\t\n\tstatic IEnumerable<string>SplitImpl(string source, int interval)\n\t{\n\t\tfor\t(int i = 1; i < source.Length; i++)\n\t\t{\n\t\t\tif (i % interval != 0) continue;\n\t\t\t\n\t\t\tyield return source.Substring(i - interval, interval);\n\t\t}\n\t}\n}\n", "language": "C-sharp" }, { "code": "import std.stdio, std.regex, std.range;\n\nauto commatize(in char[] txt, in uint start=0, in uint step=3,\n in string ins=\",\") @safe\nin {\n assert(step > 0);\n} body {\n if (start > txt.length || step > txt.length)\n return txt;\n\n // First number may begin with digit or decimal point. Exponents ignored.\n enum decFloField = ctRegex!(\"[0-9]*\\\\.[0-9]+|[0-9]+\");\n\n auto matchDec = matchFirst(txt[start .. $], decFloField);\n if (!matchDec)\n return txt;\n\n // Within a decimal float field:\n // A decimal integer field to commatize is positive and not after a point.\n enum decIntField = ctRegex!(\"(?<=\\\\.)|[1-9][0-9]*\");\n // A decimal fractional field is preceded by a point, and is only digits.\n enum decFracField = ctRegex!(\"(?<=\\\\.)[0-9]+\");\n\n return txt[0 .. start] ~ matchDec.pre ~ matchDec.hit\n .replace!(m => m.hit.retro.chunks(step).join(ins).retro)(decIntField)\n .replace!(m => m.hit.chunks(step).join(ins))(decFracField)\n ~ matchDec.post;\n}\n\nunittest {\n // An attempted solution may have one or more of the following errors:\n // ignoring a number that has only zero before its decimal point\n assert(\"0.0123456\".commatize == \"0.012,345,6\");\n // commatizing numbers other than the first\n assert(\"1000 2.3000\".commatize == \"1,000 2.3000\");\n // only commatizing in one direction from the decimal point\n assert(\"0001123.456789\".commatize == \"0001,123.456,789\");\n // detecting prefixes such as \"Z$\" requires detecting other prefixes\n assert(\" NZ$300000\".commatize == \" NZ$300,000\");\n // detecting a decimal field that isn't attached to the first number\n assert(\" 2600 and .0125\".commatize == \" 2,600 and .0125\");\n // ignoring the start value, or confusing base 0 (used here) with base 1\n assert(\"1 77000\".commatize(1) == \"1 77,000\");\n // ignoring a number that begins with a point, or treating it as integer\n assert(\" .0104004\".commatize == \" .010,400,4\");\n}\n\nvoid main() {\n \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\"\n .commatize(0, 5, \" \").writeln;\n \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\"\n .commatize(0, 3, \".\").writeln;\n foreach (const line; \"commatizing_numbers_using_defaults.txt\".File.byLine)\n line.commatize.writeln;\n}\n", "language": "D" }, { "code": "program Commatizing_numbers;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils,\n System.RegularExpressions,\n system.StrUtils;\n\nconst\n PATTERN = '(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)';\n TESTS: array[0..13] of string = ('123456789.123456789', '.123456789',\n '57256.1D-4', 'pi=3.14159265358979323846264338327950288419716939937510582097494459231',\n 'The author has two Z$100000000000000 Zimbabwe notes (100 trillion).',\n '-in Aus$+1411.8millions', '===US$0017440 millions=== (in 2000 dollars)',\n '123.e8000 is pretty big.',\n 'The land area of the earth is 57268900(29% of the surface) square miles.',\n 'Ain''t no numbers in this here words, nohow, no way, Jose.',\n 'James was never known as 0000000007',\n 'Arthur Eddington wrote: I believe there are ' +\n '15747724136275002577605653961181555468044717914527116709366231425076185631031296' +\n ' protons in the universe.', ' $-140000±100 millions.',\n '6/9/1946 was a good year for some.');\n\nvar\n regex: TRegEx;\n\nfunction Commatize(s: string; startIndex, period: integer; sep: string): string;\nvar\n m: TMatch;\n s1, ip, pi, dp: string;\n splits: TArray<string>;\n i: integer;\nbegin\n regex := TRegEx.Create(PATTERN);\n\n if (startIndex < 0) or (startIndex >= s.Length) or (period < 1) or (sep.IsEmpty) then\n exit(s);\n m := regex.Match(s.Substring(startIndex, s.Length));\n if not m.Success then\n exit(s);\n\n s1 := m.Groups[0].Value;\n splits := s1.Split(['.']);\n\n ip := splits[0];\n\n if ip.Length > period then\n begin\n pi := ReverseString(ip);\n i := ((ip.Length - 1) div period) * period;\n\n while i >= period do\n begin\n pi := pi.Substring(0, i) + sep + pi.Substring(i);\n i := i - period;\n end;\n ip := ReverseString(pi);\n end;\n\n if s1.Contains('.') then\n begin\n dp := splits[1];\n if dp.Length > period then\n begin\n i := ((dp.Length - 1) div period) * period;\n while i >= period do\n begin\n dp := dp.Substring(0, i) + sep + dp.Substring(i);\n i := i - period;\n end;\n end;\n ip := ip + '.' + dp;\n end;\n Result := s.Substring(0, startIndex) + s.Substring(startIndex).Replace(s1, ip, []);\nend;\n\nvar\n i: integer;\n\nbegin\n Writeln(commatize(TESTS[0], 0, 2, '*'));\n Writeln(commatize(TESTS[1], 0, 3, '-'));\n Writeln(commatize(TESTS[2], 0, 4, '__'));\n Writeln(commatize(TESTS[3], 0, 5, ' '));\n Writeln(commatize(TESTS[4], 0, 3, '.'));\n for i := 5 to High(TESTS) do\n Writeln(commatize(TESTS[i], 0, 3, ','));\n readln;\nend.\n", "language": "Delphi" }, { "code": "USING: accessors grouping io kernel math regexp sequences\nsplitting strings unicode ;\n\n: numeric ( str -- new-str )\n R/ [1-9][0-9]*/ first-match >string ;\n\n: commas ( numeric-str period separator -- str )\n [ reverse ] [ group ] [ reverse join reverse ] tri* ;\n\n: (commatize) ( text from period separator -- str )\n [ cut dup numeric dup ] 2dip commas replace append ;\n\n: commatize* ( text from period separator -- str )\n reach [ digit? ] any? [ (commatize) ] [ 3drop ] if ;\n\n: commatize ( text -- str ) 0 3 \",\" commatize* ;\n\n\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\"\n5 5 \" \" commatize* print\n\n\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\"\n0 3 \".\" commatize* print\n\n{\n \"\\\"-in Aus$+1411.8millions\\\"\"\n \"===US$0017440 millions=== (in 2000 dollars)\"\n \"123.e8000 is pretty big.\"\n \"The land area of the earth is 57268900(29% of the surface) square miles.\"\n \"Ain't no numbers in this here words, nohow, no way, Jose.\"\n \"James was never known as 0000000007\"\n \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\"\n \" $-140000±100 millions.\"\n \"6/9/1946 was a good year for some.\"\n} [ commatize print ] each\n", "language": "Factor" }, { "code": "Sub commatize(s As String, sep As String = \",\", start As Byte = 1, paso As Byte = 3)\n Dim As Integer l = Len(s)\n For i As Integer = start To l\n If Asc(Mid(s, i, 1)) >= Asc(\"1\") And Asc(Mid(s, i, 1)) <= Asc(\"9\") Then\n For j As Integer =i+1 To l+1\n If j>l Then\n For k As Integer = j-1-paso To i Step -paso\n s = Mid(s, 1, k) + sep + Mid(s, k+1, l-k+1)\n l = Len(s)\n Next k\n Exit For\n Else\n If (Asc(Mid(s, j, 1)) < Asc(\"0\") Or Asc(Mid(s, j, 1)) > Asc(\"9\")) Then\n For k As Integer = j-1-paso To i Step -paso\n s = Mid(s, 1, k) + sep + Mid(s, k+1, l-k+1)\n l = Len(s)\n Next k\n Exit For\n End If\n End If\n Next j\n Exit For\n End If\n Next i\n Print s\nEnd Sub\n\ncommatize(\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\" \",6,5)\ncommatize(\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\".\")\ncommatize(\"\\'-in Aus$+1411.8millions\\'\",\",\")\ncommatize(\"===US$0017440 millions=== (in 2000 dollars)\")\ncommatize(\"123.e8000 is pretty big.\")\ncommatize(\"The land area of the earth is 57268900(29% of the surface) square miles.\")\ncommatize(\"Ain't no numbers in this here words, nohow, no way, Jose.\")\ncommatize(\"James was never known as 0000000007\")\ncommatize(\"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\")\ncommatize(\" $-140000±100 millions.\")\ncommatize(\"6/9/1946 was a good year for some.\")\n\nSleep\n", "language": "FreeBASIC" }, { "code": "local fn commatize( s as Str255, sep as Str255, start as long, stp as long )\n\n if sep[0] == 0 then sep = \",\"\n if start == 0 then start = 1\n if stp == 0 then stp = 3\n\n long i, j, k, l = len$(s)\n\n for i = start to l\n if ( asc( mid$( s, i, 1 ) ) >= asc(\"1\") and asc( mid$( s, i, 1) ) <= asc(\"9\") )\n for j = i + 1 to l + 1\n if ( j > l )\n for k = j - 1 - stp to i step -stp\n s = mid$( s, 1, k ) + sep + mid$( s, k + 1, l - k + 1 )\n l = len$(s)\n next k\n exit for\n else\n if ( asc( mid$( s, j, 1 ) ) < asc(\"0\") or asc( mid$( s, j, 1 ) ) > asc(\"9\") )\n for k = j - 1 - stp to i step -stp\n s = mid$( s, 1, k ) + sep + mid$( s, k + 1, l - k + 1 )\n l = len$(s)\n next k\n exit for\n end if\n end if\n next j\n exit for\n end if\n next i\n print s\nend fn\n\nwindow 1\n\nfn commatize(\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\" , \" \" , 6, 5 )\nfn commatize(\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\" , \".\" , 0, 0 )\nfn commatize(\"\\'-in Aus$+1411.8millions\\'\" , \",\" , 0, 0 )\nfn commatize(\"===US$0017440 millions=== (in 2000 dollars)\" , \"\" , 0, 0 )\nfn commatize(\"123.e8000 is pretty big.\" , \"\" , 0, 0 )\nfn commatize(\"The land area of the earth is 57268900(29% of the surface) square miles.\" , \"\" , 0, 0 )\nfn commatize(\"Ain't no numbers in this here words, nohow, no way, Jose.\" , \"\" , 0, 0 )\nfn commatize(\"James was never known as 0000000007\" , \"\" , 0, 0 )\nfn commatize(\"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\", \",\", 0, 0 )\nfn commatize(\" $-140000±100 millions.\" , \"\" , 0, 0 )\nfn commatize(\"6/9/1946 was a good year for some.\" , \"\" , 0, 0 )\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"regexp\"\n \"strings\"\n)\n\nvar reg = regexp.MustCompile(`(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)`)\n\nfunc reverse(s string) string {\n r := []rune(s)\n for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n r[i], r[j] = r[j], r[i]\n }\n return string(r)\n}\n\nfunc commatize(s string, startIndex, period int, sep string) string {\n if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == \"\" {\n return s\n }\n m := reg.FindString(s[startIndex:]) // this can only contain ASCII characters\n if m == \"\" {\n return s\n }\n splits := strings.Split(m, \".\")\n ip := splits[0]\n if len(ip) > period {\n pi := reverse(ip)\n for i := (len(ip) - 1) / period * period; i >= period; i -= period {\n pi = pi[:i] + sep + pi[i:]\n }\n ip = reverse(pi)\n }\n if strings.Contains(m, \".\") {\n dp := splits[1]\n if len(dp) > period {\n for i := (len(dp) - 1) / period * period; i >= period; i -= period {\n dp = dp[:i] + sep + dp[i:]\n }\n }\n ip += \".\" + dp\n }\n return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)\n}\n\nfunc main() {\n tests := [...]string{\n \"123456789.123456789\",\n \".123456789\",\n \"57256.1D-4\",\n \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n \"-in Aus$+1411.8millions\",\n \"===US$0017440 millions=== (in 2000 dollars)\",\n \"123.e8000 is pretty big.\",\n \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n \"James was never known as 0000000007\",\n \"Arthur Eddington wrote: I believe there are \" +\n \"15747724136275002577605653961181555468044717914527116709366231425076185631031296\" +\n \" protons in the universe.\",\n \" $-140000±100 millions.\",\n \"6/9/1946 was a good year for some.\",\n }\n fmt.Println(commatize(tests[0], 0, 2, \"*\"))\n fmt.Println(commatize(tests[1], 0, 3, \"-\"))\n fmt.Println(commatize(tests[2], 0, 4, \"__\"))\n fmt.Println(commatize(tests[3], 0, 5, \" \"))\n fmt.Println(commatize(tests[4], 0, 3, \".\"))\n for _, test := range tests[5:] {\n fmt.Println(commatize(test, 0, 3, \",\"))\n }\n}\n", "language": "Go" }, { "code": "#!/usr/bin/env runhaskell\n\nimport Control.Monad (forM_)\nimport Data.Char (isDigit)\nimport Data.List (intercalate)\nimport Data.Maybe (fromMaybe)\n\n{-\nI use the suffix \"2\" in identifiers in place of the more conventional\nprime (single quote character), because Rosetta Code's syntax highlighter\nstill doesn't handle primes in identifiers correctly.\n-}\n\nisDigitOrPeriod :: Char -> Bool\nisDigitOrPeriod '.' = True\nisDigitOrPeriod c = isDigit c\n\nchopUp :: Int -> String -> [String]\nchopUp _ [] = []\nchopUp by str\n | by < 1 = [str] -- invalid argument, leave string unchanged\n | otherwise = let (pfx, sfx) = splitAt by str\n in pfx : chopUp by sfx\n\naddSeps :: String -> Char -> Int -> (String -> String) -> String\naddSeps str sep by rev =\n let (leading, number) = span (== '0') str\n number2 = rev $ intercalate [sep] $ chopUp by $ rev number\n in leading ++ number2\n\nprocessNumber :: String -> Char -> Int -> String\nprocessNumber str sep by =\n let (beforeDecimal, rest) = span isDigit str\n (decimal, afterDecimal) = splitAt 1 rest\n beforeDecimal2 = addSeps beforeDecimal sep by reverse\n afterDecimal2 = addSeps afterDecimal sep by id\n in beforeDecimal2 ++ decimal ++ afterDecimal2\n\ncommatize2 :: String -> Char -> Int -> String\ncommatize2 [] _ _ = []\ncommatize2 str sep by =\n let (pfx, sfx) = break isDigitOrPeriod str\n (number, sfx2) = span isDigitOrPeriod sfx\n in pfx ++ processNumber number sep by ++ sfx2\n\ncommatize :: String -> Maybe Char -> Maybe Int -> String\ncommatize str sep by = commatize2 str (fromMaybe ',' sep) (fromMaybe 3 by)\n\ninput :: [(String, Maybe Char, Maybe Int)]\ninput =\n [ (\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", Just ' ', Just 5)\n , (\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", Just '.', Nothing)\n , (\"\\\"-in Aus$+1411.8millions\\\"\", Nothing, Nothing)\n , (\"===US$0017440 millions=== (in 2000 dollars)\", Nothing, Nothing)\n , (\"123.e8000 is pretty big.\", Nothing, Nothing)\n , (\"The land area of the earth is 57268900(29% of the surface) square miles.\", Nothing, Nothing)\n , (\"Ain't no numbers in this here words, nohow, no way, Jose.\", Nothing, Nothing)\n , (\"James was never known as 0000000007\", Nothing, Nothing)\n , (\"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\", Nothing, Nothing)\n , (\" $-140000±100 millions.\", Nothing, Nothing)\n , (\"6/9/1946 was a good year for some.\", Nothing, Nothing)\n ]\n\nmain :: IO ()\nmain =\n forM_ input $ \\(str, by, sep) -> do\n putStrLn str\n putStrLn $ commatize str by sep\n putStrLn \"\"\n", "language": "Haskell" }, { "code": "require'regex'\ncommatize=:3 :0\"1 L:1 0\n (i.0) commatize y\n:\nNB. deal with all those rules about options\n opts=. boxopen x\n char=. (#~ ' '&=@{.@(0&#)@>) opts\n num=. ;opts-.char\n delim=. 0 {:: char,<','\n 'begin period'=. _1 0+2{.num,(#num)}.1 3\nNB. initialize\n prefix=. begin {.y\n text=. begin }. y\nNB. process\n 'start len'=. ,'[1-9][0-9]*' rxmatch text\n if.0=len do. y return. end.\n number=. (start,:len) [;.0 text\n numb=. (>:period|<:#number){.number\n fixed=. numb,;delim&,each (-period)<\\ (#numb)}.number\n prefix,(start{.text),fixed,(start+len)}.text\n)\n", "language": "J" }, { "code": " (5;5;' ') commatize 'pi=3.14159265358979323846264338327950288419716939937510582097494459231'\npi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231\n '.' commatize 'The author has two Z$100000000000000 Zimbabwe notes (100 trillion).'\nThe author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).\n commatize '-in Aus$+1411.8millions'\n-in Aus$+1,411.8millions\n commatize '===US$0017440 millions=== (in 2000 dollars)'\n===US$0017,440 millions=== (in 2000 dollars)\n commatize '123.e8000 is pretty big.'\n123.e8000 is pretty big.\n commatize 'The land area of the earth is 57268900(29% of the surface) square miles.'\nThe land area of the earth is 57,268,900(29% of the surface) square miles.\n commatize 'Ain''t no numbers in this here words, nohow, no way, Jose.'\nAin't no numbers in this here words, nohow, no way, Jose.\n commatize 'James was never known as 0000000007'\nJames was never known as 0000000007\n commatize 'Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.'\nArthur Eddington wrote: I believe there are 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.\n commatize ' $-140000±100 millions.'\n $-140,000±100 millions.\n commatize '6/9/1946 was a good year for some.'\n6/9/1946 was a good year for some.\n", "language": "J" }, { "code": "import java.io.File;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class CommatizingNumbers {\n\n public static void main(String[] args) throws Exception {\n commatize(\"pi=3.14159265358979323846264338327950288419716939937510582\"\n + \"097494459231\", 6, 5, \" \");\n\n commatize(\"The author has two Z$100000000000000 Zimbabwe notes (100 \"\n + \"trillion).\", 0, 3, \".\");\n\n try (Scanner sc = new Scanner(new File(\"input.txt\"))) {\n while(sc.hasNext())\n commatize(sc.nextLine());\n }\n }\n\n static void commatize(String s) {\n commatize(s, 0, 3, \",\");\n }\n\n static void commatize(String s, int start, int step, String ins) {\n if (start < 0 || start > s.length() || step < 1 || step > s.length())\n return;\n\n Matcher m = Pattern.compile(\"([1-9][0-9]*)\").matcher(s.substring(start));\n StringBuffer result = new StringBuffer(s.substring(0, start));\n\n if (m.find()) {\n StringBuilder sb = new StringBuilder(m.group(1)).reverse();\n for (int i = step; i < sb.length(); i += step)\n sb.insert(i++, ins);\n m.appendReplacement(result, sb.reverse().toString());\n }\n\n System.out.println(m.appendTail(result));\n }\n}\n", "language": "Java" }, { "code": "def commatize($s; $start; $step; $sep):\n\n def isExponent($c): \"eEdDpP^∙x↑*⁰¹²³⁴⁵⁶⁷⁸⁹\" | index($c);\n def rev: explode|reverse|implode;\n def addSeps($n; $dp):\n { $n, lz: \"\" }\n | if ($dp|not) and ($n|startswith(\"0\")) and $n != \"0\"\n then .k = ($n|sub(\"^0*\";\"\"))\n | if (.k == \"\") then .k = \"0\" else . end\n | .lz = \"0\" * (($n|length) - (.k|length))\n | .n = .k\n else .\n end\n | if $dp\n then .n |= rev # reverse if after decimal point\n else .\n end\n | .i = (.n|length) - $step\n | until (.i < 1;\n .n = .n[: .i] + $sep + .n[.i :]\n | .i += - $step )\n | if $dp\n then .n |= rev # reverse again\n else .\n end\n | .lz + .n;\n\n { acc: $s[:$start],\n n: \"\",\n dp: false }\n | label $out\n | foreach (range($start; $s|length), null) as $j (.;\n if $j == null then .emit = true\n else $s[$j:$j+1] as $x\n | ($x | explode[0]) as $c\n | if ($c >= 48 and $c <= 57)\n then .n += $x\n | if $j == (($s|length)-1)\n then if (.acc != \"\" and isExponent(.acc[-1:]))\n then .acc = $s\n else .acc += addSeps(.n; .dp)\n end\n else .\n end\n elif .n != \"\"\n then if (.acc != \"\" and isExponent(.acc[-1:]))\n then .acc = $s\n | .emit=true | ., break $out\n elif $x != \".\"\n then .acc += addSeps(.n; .dp) + $s[$j:]\n | .emit=true | ., break $out\n else .acc += addSeps(.n; .dp) + $x\n | .dp = true\n | .n = \"\"\n end\n else .acc += $x\n end\n end )\n | select(.emit)\n | $s, .acc, \"\"\n;\n\n# Input: the string to be commatized\ndef commatize:\n commatize(.; 0; 3; \",\");\n\ndef defaults: [\n \"\\\"-in Aus$+1411.8millions\\\"\",\n \"===US$0017440 millions=== (in 2000 dollars)\",\n \"123.e8000 is pretty big.\",\n \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n \"James was never known as 0000000007\",\n \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\",\n \" $-140000±100 millions.\",\n \"6/9/1946 was a good year for some.\"\n];\n\ndef exercise:\n commatize(\"123456789.123456789\"; 0; 2; \"*\"),\n commatize(\".123456789\"; 0; 3; \"-\"),\n commatize(\"57256.1D-4\"; 0; 4; \"__\"),\n commatize(\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\"; 0; 5; \" \"),\n commatize(\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\"; 0; 3; \".\"),\n\n (defaults[] | commatize) ;\n\nexercise\n", "language": "Jq" }, { "code": "input = [\n [\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", \" \", 5],\n [raw\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", \".\"],\n [raw\"-in Aus$+1411.8millions\"],\n [raw\"===US$0017440 millions=== (in 2000 dollars)\"],\n [\"123.e8000 is pretty big.\"],\n [\"The land area of the earth is 57268900(29% of the surface) square miles.\"],\n [\"Ain\\'t no numbers in this here words, nohow, no way, Jose.\"],\n [\"James was never known as 0000000007\"],\n [\"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\"],\n [raw\" $-140000±100 millions.\"],\n [\"6/9/1946 was a good year for some.\"]]\n\nfunction commatize(tst)\n grouping = (length(tst) == 3) ? tst[3] : 3\n sep = (length(tst) > 1) ? tst[2] : \",\"\n rmend(s) = replace(s, Regex(\"$sep\\\\Z\") =>\"\")\n greg = Regex(\".{$grouping}\")\n cins(str) = reverse(rmend(replace(reverse(str), greg => s -> s * sep)))\n mat = match(Regex(\"(?<![eE\\\\/])([1-9]\\\\d{$grouping,})\"), tst[1])\n if mat != nothing\n return replace(tst[1], mat.match => cins)\n end\n return tst[1]\nend\n\nfor tst in input\n println(commatize(tst))\nend\n", "language": "Julia" }, { "code": "// version 1.1.4-3\n\nval r = Regex(\"\"\"(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)\"\"\")\n\nfun String.commatize(startIndex: Int = 0, period: Int = 3, sep: String = \",\"): String {\n if ((startIndex !in 0 until this.length) || period < 1 || sep == \"\") return this\n val m = r.find(this, startIndex)\n if (m == null) return this\n val splits = m.value.split('.')\n var ip = splits[0]\n if (ip.length > period) {\n val sb = StringBuilder(ip.reversed())\n for (i in (ip.length - 1) / period * period downTo period step period) {\n sb.insert(i, sep)\n }\n ip = sb.toString().reversed()\n }\n if ('.' in m.value) {\n var dp = splits[1]\n if (dp.length > period) {\n val sb2 = StringBuilder(dp)\n for (i in (dp.length - 1) / period * period downTo period step period) {\n sb2.insert(i, sep)\n }\n dp = sb2.toString()\n }\n ip += \".\" + dp\n }\n return this.take(startIndex) + this.drop(startIndex).replaceFirst(m.value, ip)\n}\n\nfun main(args: Array<String>) {\n val tests = arrayOf(\n \"123456789.123456789\",\n \".123456789\",\n \"57256.1D-4\",\n \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n \"-in Aus$+1411.8millions\",\n \"===US$0017440 millions=== (in 2000 dollars)\",\n \"123.e8000 is pretty big.\",\n \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n \"James was never known as 0000000007\",\n \"Arthur Eddington wrote: I believe there are \" +\n \"15747724136275002577605653961181555468044717914527116709366231425076185631031296\" +\n \" protons in the universe.\",\n \" $-140000±100 millions.\",\n \"6/9/1946 was a good year for some.\"\n )\n\n println(tests[0].commatize(period = 2, sep = \"*\"))\n println(tests[1].commatize(period = 3, sep = \"-\"))\n println(tests[2].commatize(period = 4, sep = \"__\"))\n println(tests[3].commatize(period = 5, sep = \" \"))\n println(tests[4].commatize(sep = \".\"))\n for (test in tests.drop(5)) println(test.commatize())\n}\n", "language": "Kotlin" }, { "code": "import re\nimport strutils\n\nlet r = re\"(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)\"\n\n#---------------------------------------------------------------------------------------------------\n\nproc commatize(str: string; startIndex = 0; period = 3; sep = \",\"): string =\n\n result = str\n var dp, ip = \"\"\n\n if startIndex notin 0..str.high : return\n\n # Extract first number (if any).\n let (lowBound, highBound) = str.findBounds(r, startIndex)\n if lowBound < 0: return\n let match = str[lowBound..highBound]\n let splits = match.split('.')\n\n # Process integer part.\n ip = splits[0]\n if ip.len > period:\n var inserted = 0\n for i in countup(ip.high mod period + 1, ip.high, period):\n ip.insert(sep, i + inserted)\n inserted += sep.len\n\n # Process decimal part.\n if '.' in match:\n dp = splits[1]\n if dp.len > period:\n for i in countdown(dp.high div period * period, period, period):\n dp.insert(sep, i)\n ip &= '.' & dp\n\n # Replace the number by its \"commatized\" version.\n result[lowBound..highBound] = ip\n\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nconst Tests = [\n \"123456789.123456789\",\n \".123456789\",\n \"57256.1D-4\",\n \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n \"-in Aus$+1411.8millions\",\n \"===US$0017440 millions=== (in 2000 dollars)\",\n \"123.e8000 is pretty big.\",\n \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n \"James was never known as 0000000007\",\n \"Arthur Eddington wrote: I believe there are \" &\n \"15747724136275002577605653961181555468044717914527116709366231425076185631031296\" &\n \" protons in the universe.\",\n \" $-140000±100 millions.\",\n \"6/9/1946 was a good year for some.\"]\n\n\necho Tests[0].commatize(period = 2, sep = \"*\")\necho Tests[1].commatize(period = 3, sep = \"-\")\necho Tests[2].commatize(period = 4, sep = \"__\")\necho Tests[3].commatize(period = 5, sep = \" \")\necho Tests[4].commatize(sep = \".\")\n\nfor n in 5..Tests.high:\n echo Tests[n].commatize()\n", "language": "Nim" }, { "code": "@input = (\n ['pi=3.14159265358979323846264338327950288419716939937510582097494459231', ' ', 5],\n ['The author has two Z$100000000000000 Zimbabwe notes (100 trillion).', '.'],\n ['-in Aus$+1411.8millions'],\n ['===US$0017440 millions=== (in 2000 dollars)'],\n ['123.e8000 is pretty big.'],\n ['The land area of the earth is 57268900(29% of the surface) square miles.'],\n ['Ain\\'t no numbers in this here words, nohow, no way, Jose.'],\n ['James was never known as 0000000007'],\n ['Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.'],\n [' $-140000±100 millions.'],\n ['5/9/1946 was a good year for some.']\n);\n\nfor $i (@input) {\n $old = @$i[0];\n $new = commatize(@$i);\n printf(\"%s\\n%s\\n\\n\", $old, $new) if $old ne $new;\n}\n\nsub commatize {\n my($str,$sep,$by) = @_;\n $sep = ',' unless $sep;\n $by = 3 unless $by;\n\n $str =~ s/ # matching rules:\n (?<![eE\\/]) # not following these characters\n ([1-9]\\d{$by,}) # leading non-zero digit, minimum number of digits required\n /c_ins($1,$by,$sep)/ex; # substitute matched text with subroutine output\n return $str;\n}\n\nsub c_ins {\n my($s,$by,$sep) = @_;\n ($c = reverse $s) =~ s/(.{$by})/$1$sep/g;\n $c =~ s/$sep$//;\n return reverse $c;\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">commatize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">sep</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">\",\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">start</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">step</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">start</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #008000;\">\"123456789\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #008000;\">\"0123456789\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">step</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">i</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">step</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">sep</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">commatize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">commatize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\".\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">commatize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\\\"-in Aus$+1411.8millions\\\"\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">commatize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"===US$0017440 millions=== (in 2000 dollars)\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">commatize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"123.e8000 is pretty big.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">commatize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"The land area of the earth is 57268900(29% of the surface) square miles.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">commatize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Ain't no numbers in this here words, nohow, no way, Jose.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">commatize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"James was never known as 0000000007\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">commatize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">commatize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\" $-140000±100 millions.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">commatize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"6/9/1946 was a good year for some.\"</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "import re as RegEx\n\n\ndef Commatize( _string, _startPos=0, _periodLen=3, _separator=\",\" ):\n\toutString = \"\"\n\tstrPos = 0\n\tmatches = RegEx.findall( \"[0-9]*\", _string )\n\n\tfor match in matches[:-1]:\n\t\tif not match:\n\t\t\toutString += _string[ strPos ]\n\t\t\tstrPos += 1\n\t\telse:\n\t\t\tif len(match) > _periodLen:\n\t\t\t\tleadIn = match[:_startPos]\n\t\t\t\tperiods = [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]\n\t\t\t\toutString += leadIn + _separator.join( periods )\n\t\t\telse:\n\t\t\t\toutString += match\n\n\t\t\tstrPos += len( match )\n\n\treturn outString\n\n\n\nprint ( Commatize( \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", 0, 5, \" \" ) )\nprint ( Commatize( \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", 0, 3, \".\" ))\nprint ( Commatize( \"\\\"-in Aus$+1411.8millions\\\"\" ))\nprint ( Commatize( \"===US$0017440 millions=== (in 2000 dollars)\" ))\nprint ( Commatize( \"123.e8000 is pretty big.\" ))\nprint ( Commatize( \"The land area of the earth is 57268900(29% of the surface) square miles.\" ))\nprint ( Commatize( \"Ain't no numbers in this here words, nohow, no way, Jose.\" ))\nprint ( Commatize( \"James was never known as 0000000007\" ))\nprint ( Commatize( \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\" ))\nprint ( Commatize( \"␢␢␢$-140000±100 millions.\" ))\nprint ( Commatize( \"6/9/1946 was a good year for some.\" ))\n", "language": "Python" }, { "code": "#lang racket\n(require (only-in srfi/13 [string-reverse gnirts]))\n\n;; returns a string with the \"comma\"s inserted every step characters from the RIGHT of n.\n;; because of the right handedness of this, there is a lot of reversal going on\n(define ((insert-commas comma step) n)\n (define px (pregexp (format \".{1,~a}\" step)))\n (string-join (add-between (reverse (map gnirts (regexp-match* px (gnirts n)))) comma) \"\"))\n\n(define (commatize s #:start (start 0) #:comma (comma \",\") #:step (step 3))\n (define ins-comms (insert-commas comma step)) ; specific to our comma and step\n\n (define split-into-numbers\n (match-lambda\n [(regexp\n #px\"^([^1-9]*)([1-9][0-9.]*)(\\\\S*)(.*)$\" ; see below for description of bits\n (list _ ; the whole match\n (app split-into-numbers pre) ; recur on left\n num ; the number bit before any exponent or other\n ; interestingness\n post-number ; from exponent to the first space\n (app split-into-numbers post))) ; recur on right\n (define skip (substring num 0 start))\n (match-define\n (regexp #px\"^(.*?)(\\\\..*)?$\"\n (list _ ; whole match\n (app ins-comms n) ; the bit that gets the commas added\n (or (? string? d) ; if it matches, then the raw string is in d\n (and #f (app (lambda (f) \"\") d))))) ; if (...)? doesn't match it returns\n ; #f which we thunk to an empty string\n (substring num start)) ; do the match on the unskipped bit\n (string-append pre skip n d post-number post)] ; stitch it back together\n [else else])) ; if it doesn't match leave as is\n\n ;; kick it off\n (split-into-numbers s))\n\n(module+ test\n (require tests/eli-tester)\n\n (test\n (commatize \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\"\n #:start 6 #:comma \" \" #:step 5)\n =>\"pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231\"\n\n (commatize \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\" #:comma \".\")\n =>\"The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).\"\n\n (commatize \"-in Aus$+1411.8millions\")\n =>\"-in Aus$+1,411.8millions\"\n\n (commatize \"===US$0017440 millions=== (in 2000 dollars)\")\n =>\"===US$0017,440 millions=== (in 2,000 dollars)\"\n\n (commatize \"123.e8000 is pretty big.\")\n =>\"123.e8000 is pretty big.\"\n\n (commatize \"The land area of the earth is 57268900(29% of the surface) square miles.\")\n =>\"The land area of the earth is 57,268,900(29% of the surface) square miles.\"\n\n (commatize \"Ain't no numbers in this here words, nohow, no way, Jose.\")\n =>\"Ain't no numbers in this here words, nohow, no way, Jose.\"\n\n (commatize \"James was never known as 0000000007\")\n =>\"James was never known as 0000000007\"\n\n (commatize \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\")\n =>\"Arthur Eddington wrote: I believe there are 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.\"\n\n (commatize \" $-140000±100 millions.\")\n\n =>\" $-140,000±100 millions.\"\n (commatize \"6/9/1946 was a good year for some.\")\n =>\"6/9/1946 was a good year for some.\"))\n", "language": "Racket" }, { "code": "for ('pi=3.14159265358979323846264338327950288419716939937510582097494459231', {:6at, :5by, :ins(' ')}),\n ('The author has two Z$100000000000000 Zimbabwe notes (100 trillion).', {:ins<.>}),\n '-in Aus$+1411.8millions',\n '===US$0017440 millions=== (in 2000 dollars)',\n '123.e8000 is pretty big.',\n 'The land area of the earth is 57268900(29% of the surface) square miles.',\n 'Ain\\'t no numbers in this here words, nohow, no way, Jose.',\n 'James was never known as 0000000007',\n 'Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.',\n ' $-140000±100 millions.',\n '6/9/1946 was a good year for some.'\n {\n say \"Before: \", .[0];\n say \" After: \", .[1] ?? .[0].&commatize( |.[1] ) !! .&commatize;\n }\n\nsub commatize($s, :$at = 0, :$ins = ',', :$by = 3) {\n $s.subst: :continue($at), :1st, / <[1..9]> <[0..9]>* /,\n *.flip.comb(/<{ \".**1..$by\" }>/).join($ins).flip;\n}\n", "language": "Raku" }, { "code": "/*REXX program adds commas (or other chars) to a string or a number within a string.*/\n@. =\[email protected]= \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\"\[email protected]= \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\"\[email protected]= \"-in Aus$+1411.8millions\"\[email protected]= \"===US$0017440 millions=== (in 2000 dollars)\"\[email protected]= \"123.e8000 is pretty big.\"\[email protected]= \"The land area of the earth is 57268900(29% of the surface) square miles.\"\[email protected]= \"Ain't no numbers in this here words, nohow, no way, Jose.\"\[email protected]= \"James was never known as 0000000007\"\[email protected]= \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\"\[email protected]= \" $-140000±100 millions.\"\[email protected]= \"6/9/1946 was a good year for some.\"\n\n do i=1 while @.i\\==''; if i\\==1 then say /*process each string.*/\n say 'before──►'@.i /*show the before str.*/\n if i==1 then say ' after──►'comma(@.i, 'blank', 5, , 6) /* p=5, start=6. */\n if i==2 then say ' after──►'comma(@.i, \".\") /*comma=decimal point.*/\n if i>2 then say ' after──►'comma(@.i) /*use the defaults. */\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncomma: procedure; parse arg x,sep,period,times,start /*obtain true case arguments.*/\n arg ,sepU /* \" uppercase 2nd arg. */\n bla= ' ' /*literal to hold a \"blank\".*/\n sep= word(sep ',', 1) /*define comma (string/char.)*/\n if sepU=='BLANK' then sep= bla /*allow the use of 'BLANK'. */\n period= word(period 3, 1) /*defined \"period\" to be used*/\n times= word(times 999999999, 1) /*limits # changes to be made*/\n start= word(start 1 , 1) /*where to start commatizing.*/\n /* [↓] various error tests. */\n if \\datatype(period, 'W') | , /*test for a whole number. */\n \\datatype(times , 'W') | , /* \" \" \" \" \" */\n \\datatype(start , 'W') | , /* \" \" \" \" \" */\n start <1 | , /*start can't be less then 1.*/\n arg() >5 then return x /*# of args can't be > 5. */\n /* [↑] some arg is invalid. */\n op= period /*save the original period. */\n period= abs(period) /*use the absolute value. */\n n= x'.9' /*a literal string for end. */\n digs= 123456789 /*the legal digits for start.*/\n digsz= 1234567890 /* \" \" \" \" fin. */\n digszp= 1234567890. /* \" \" \" \" fin. */\n /* [↓] note: no zero in digs*/\n if op<0 then do /*Negative? Treat as chars. */\n beg= start /*begin at the start. */\n L= length(x) /*obtain the length of X. */\n fin= L - verify( reverse(x), bla) + 1 /*find the ending of the num.*/\n end /* [↑] find number ending. */\n else do /*Positive? Treat as numbers*/\n beg= verify(n, digs, \"M\",start) /*find beginning of number. */\n v2=max(verify(n, digszp,'M',start),1) /*end of the usable number. */\n fin=verify(n, digsz, , v2) -period -1 /*adjust the ending (fin). */\n end /* [↑] find ending of number*/\n #= 0 /*the count of changes made. */\n if beg>0 & fin>0 then /* [↓] process TIMES times*/\n do j=fin to beg by -period while #<times\n x= insert(sep, x, j) /*insert a comma into string.*/\n #= # + 1 /*bump the count of changes. */\n end /*j*/ /*(maybe no changes are made)*/\n return x /*return the commatized str. */\n", "language": "REXX" }, { "code": "import java.io.File\nimport java.util.Scanner\nimport java.util.regex.Pattern\n\nobject CommatizingNumbers extends App {\n\n def commatize(s: String): Unit = commatize(s, 0, 3, \",\")\n\n def commatize(s: String, start: Int, step: Int, ins: String): Unit = {\n if (start >= 0 && start <= s.length && step >= 1 && step <= s.length) {\n val m = Pattern.compile(\"([1-9][0-9]*)\").matcher(s.substring(start))\n val result = new StringBuffer(s.substring(0, start))\n if (m.find) {\n val sb = new StringBuilder(m.group(1)).reverse\n for (i <- step until sb.length by step) sb.insert(i, ins)\n m.appendReplacement(result, sb.reverse.toString)\n }\n println(m.appendTail(result))\n }\n }\n\n commatize(\"pi=3.14159265358979323846264338327950288419716939937510582\" + \"097494459231\", 6, 5, \" \")\n commatize(\"The author has two Z$100000000000000 Zimbabwe notes (100 \" + \"trillion).\", 0, 3, \".\")\n\n val sc = new Scanner(new File(\"input.txt\"))\n while (sc.hasNext) commatize(sc.nextLine)\n}\n", "language": "Scala" }, { "code": "import Foundation\n\nextension String {\n private static let commaReg = try! NSRegularExpression(pattern: \"(\\\\.[0-9]+|[1-9]([0-9]+)?(\\\\.[0-9]+)?)\")\n\n public func commatize(start: Int = 0, period: Int = 3, separator: String = \",\") -> String {\n guard separator != \"\" else {\n return self\n }\n\n let sep = Array(separator)\n let startIdx = index(startIndex, offsetBy: start)\n let matches = String.commaReg.matches(in: self, range: NSRange(startIdx..., in: self))\n\n guard !matches.isEmpty else {\n return self\n }\n\n let fullMatch = String(self[Range(matches.first!.range(at: 0), in: self)!])\n let splits = fullMatch.components(separatedBy: \".\")\n var ip = splits[0]\n\n if ip.count > period {\n var builder = Array(ip.reversed())\n\n for i in stride(from: (ip.count - 1) / period * period, through: period, by: -period) {\n builder.insert(contentsOf: sep, at: i)\n }\n\n ip = String(builder.reversed())\n }\n\n if fullMatch.contains(\".\") {\n var dp = splits[1]\n\n if dp.count > period {\n var builder = Array(dp)\n\n for i in stride(from: (dp.count - 1) / period * period, through: period, by: -period) {\n builder.insert(contentsOf: sep, at: i)\n }\n\n dp = String(builder)\n }\n\n ip += \".\" + dp\n }\n\n return String(prefix(start)) + String(dropFirst(start)).replacingOccurrences(of: fullMatch, with: ip)\n }\n}\n\nlet tests = [\n \"123456789.123456789\",\n \".123456789\",\n \"57256.1D-4\",\n \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n \"-in Aus$+1411.8millions\",\n \"===US$0017440 millions=== (in 2000 dollars)\",\n \"123.e8000 is pretty big.\",\n \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n \"James was never known as 0000000007\",\n \"Arthur Eddington wrote: I believe there are \" +\n \"15747724136275002577605653961181555468044717914527116709366231425076185631031296\" +\n \" protons in the universe.\",\n \" $-140000±100 millions.\",\n \"6/9/1946 was a good year for some.\"\n]\n\nprint(tests[0].commatize(period: 2, separator: \"*\"))\nprint(tests[1].commatize(period: 3, separator: \"-\"))\nprint(tests[2].commatize(period: 4, separator: \"__\"))\nprint(tests[3].commatize(period: 5, separator: \" \"))\nprint(tests[4].commatize(separator: \".\"))\n\nfor testCase in tests.dropFirst(5) {\n print(testCase.commatize())\n}\n", "language": "Swift" }, { "code": "Public Sub commatize(s As String, Optional sep As String = \",\", Optional start As Integer = 1, Optional step As Integer = 3)\n Dim l As Integer: l = Len(s)\n For i = start To l\n If Asc(Mid(s, i, 1)) >= Asc(\"1\") And Asc(Mid(s, i, 1)) <= Asc(\"9\") Then\n For j = i + 1 To l + 1\n If j > l Then\n For k = j - 1 - step To i Step -step\n s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n l = Len(s)\n Next k\n Exit For\n Else\n If (Asc(Mid(s, j, 1)) < Asc(\"0\") Or Asc(Mid(s, j, 1)) > Asc(\"9\")) Then\n For k = j - 1 - step To i Step -step\n s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n l = Len(s)\n Next k\n Exit For\n End If\n End If\n Next j\n Exit For\n End If\n Next i\n Debug.Print s\n End Sub\nPublic Sub main()\n commatize \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", \" \", 6, 5\n commatize \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", \".\"\n commatize \"\"\"-in Aus$+1411.8millions\"\"\"\n commatize \"===US$0017440 millions=== (in 2000 dollars)\"\n commatize \"123.e8000 is pretty big.\"\n commatize \"The land area of the earth is 57268900(29% of the surface) square miles.\"\n commatize \"Ain't no numbers in this here words, nohow, no way, Jose.\"\n commatize \"James was never known as 0000000007\"\n commatize \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\"\n commatize \" $-140000±100 millions.\"\n commatize \"6/9/1946 was a good year for some.\"\nEnd Sub\n", "language": "VBA" }, { "code": "function commatize( s , sep, start , stp )\n\n if sep =\"\" then sep = \",\"\n if start =\"\" then start = 1\n if stp =\"\" then stp = 3\n\n Dim i, j, k, l\n l = len(s)\n\n for i = start to l\n if ( asc( mid( s, i, 1 ) ) >= asc(\"1\") and asc( mid( s, i, 1) ) <= asc(\"9\") ) then\n for j = i + 1 to l + 1\n if ( j > l ) then\n for k = j - 1 - stp to i step -stp\n s = mid( s, 1, k ) + sep + mid( s, k + 1, l - k + 1 )\n l = len(s)\n next 'k\n exit for\n else\n if ( asc( mid( s, j, 1 ) ) < asc(\"0\") or asc( mid( s, j, 1 ) ) > asc(\"9\") ) then\n for k = j - 1 - stp to i step -stp\n s = mid( s, 1, k ) + sep + mid( s, k + 1, l - k + 1 )\n l = len(s)\n Next ' k\n exit for\n end if\n end if\n next 'j\n exit for\n end if\n next '\n commatize=S\nend function\n\nwscript.echo commatize(\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\" , \" \" , 6, 5 )\nwscript.echo commatize(\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\" , \".\" , \"\", \"\" )\nwscript.echo commatize(\"\\'-in Aus$+1411.8millions\\'\" , \",\" , \"\", \"\" )\nwscript.echo commatize(\"===US$0017440 millions=== (in 2000 dollars)\" , \"\" , \"\", \"\" )\nwscript.echo commatize(\"123.e8000 is pretty big.\" , \"\" , \"\", \"\" )\nwscript.echo commatize(\"The land area of the earth is 57268900(29% of the surface) square miles.\" , \"\" , \"\", \"\" )\nwscript.echo commatize(\"Ain't no numbers in this here words, nohow, no way, Jose.\" , \"\" , \"\", \"\" )\nwscript.echo commatize(\"James was never known as 0000000007\" , \"\" , \"\", \"\" )\nwscript.echo commatize(\"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\", \",\", \"\", \"\" )\nwscript.echo commatize(\" $-140000±100 millions.\" , \"\" , \"\", \"\" )\nwscript.echo commatize(\"6/9/1946 was a good year for some.\" , \"\" , \"\", \"\" )\n", "language": "VBScript" }, { "code": "var commatize = Fn.new { |s, start, step, sep|\n var addSeps = Fn.new { |n, dp|\n var lz = \"\"\n if (!dp && n.startsWith(\"0\") && n != \"0\") {\n var k = n.trimStart(\"0\")\n if (k == \"\") k = \"0\"\n lz = \"0\" * (n.count - k.count)\n n = k\n }\n if (dp) n = n[-1..0] // invert if after decimal point\n var i = n.count - step\n while (i >= 1) {\n n = n[0...i] + sep + n[i..-1]\n i = i - step\n }\n if (dp) n = n[-1..0] // invert back\n return lz + n\n }\n\n var t = s.toList\n var isExponent = Fn.new { |c| \"eEdDpP^∙x↑*⁰¹²³⁴⁵⁶⁷⁸⁹\".contains(c) }\n var acc = (start == 0) ? \"\" : t.toList[0...start].join()\n var n = \"\"\n var dp = false\n for (j in start...t.count) {\n var c = t[j].codePoints[0]\n if (c >= 48 && c <= 57) {\n n = n + t[j]\n if (j == t.count-1) {\n if (acc != \"\" && isExponent.call(acc[-1])) {\n acc = s\n } else {\n acc = acc + addSeps.call(n, dp)\n }\n }\n } else if (n != \"\") {\n if (acc != \"\" && isExponent.call(acc[-1])) {\n acc = s\n break\n } else if (t[j] != \".\") {\n acc = acc + addSeps.call(n, dp) + t[j..-1].join()\n break\n } else {\n acc = acc + addSeps.call(n, dp) + t[j]\n dp = true\n n = \"\"\n }\n } else {\n acc = acc + t[j]\n }\n }\n\n System.print(s)\n System.print(acc)\n System.print()\n}\n\n// special version of the above which uses defaults for start, step and sep.\nvar commatize2 = Fn.new { |s| commatize.call(s, 0, 3, \",\") }\n\ncommatize.call(\"123456789.123456789\", 0, 2, \"*\")\ncommatize.call(\".123456789\", 0, 3, \"-\")\ncommatize.call(\"57256.1D-4\", 0, 4, \"__\")\ncommatize.call(\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", 0, 5, \" \")\ncommatize.call(\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", 0, 3, \".\")\n\nvar defaults = [\n \"\\\"-in Aus$+1411.8millions\\\"\",\n \"===US$0017440 millions=== (in 2000 dollars)\",\n \"123.e8000 is pretty big.\",\n \"The land area of the earth is 57268900(29\\% of the surface) square miles.\",\n \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n \"James was never known as 0000000007\",\n \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\",\n \" $-140000±100 millions.\",\n \"6/9/1946 was a good year for some.\"\n]\n\ndefaults.each { |d| commatize2.call(d) }\n", "language": "Wren" } ]
Commatizing-numbers
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Compare_a_list_of_strings\n", "language": "00-META" }, { "code": ";Task:\nGiven a &nbsp; [[wp:List_(abstract_data_type)|list]] &nbsp; of arbitrarily many strings, show how to:\n\n* &nbsp; test if they are all lexically '''equal'''\n* &nbsp; test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n<br>\nEach of those two tests should result in a single true or false value, which could be used as the condition of an &nbsp; <code> if </code> &nbsp; statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name &nbsp; <code>strings</code>, &nbsp; and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), &nbsp; with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, &nbsp; but if it does then please add a note to make that clear to readers.\n\n<i>If you need further guidance/clarification, &nbsp; see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, &nbsp; and [[#Raku]] for a solution that gets away with simply using a built-in language feature. </i>\n\n\n{{Template:Strings}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "L(strings_s) [‘AA AA AA AA’, ‘AA ACB BB CC’]\n V strings = strings_s.split(‘ ’)\n print(strings)\n print(all(zip(strings, strings[1..]).map(a -> a[0] == a[1])))\n print(all(zip(strings, strings[1..]).map(a -> a[0] < a[1])))\n print()\n", "language": "11l" }, { "code": "* Compare a list of strings 31/01/2017\nCOMPLIST CSECT\n USING COMPLIST,R13 base register\n B 72(R15) skip savearea\n DC 17F'0' savearea\n STM R14,R12,12(R13) prolog\n ST R13,4(R15) \" <-\n ST R15,8(R13) \" ->\n LR R13,R15 \" addressability\n MVC SNAME,=C'ABC'\n LA R1,SNAME\n LA R2,ABC\n BAL R14,TEST call test('ABC',abc)\n MVC SNAME,=C'AAA'\n LA R1,SNAME\n LA R2,AAA\n BAL R14,TEST call test('AAA',aaa)\n MVC SNAME,=C'ACB'\n LA R1,SNAME\n LA R2,ACB\n BAL R14,TEST call test('ACB',acb)\n L R13,4(0,R13) epilog\n LM R14,R12,12(R13) \" restore\n XR R15,R15 \" rc=0\n BR R14 exit\n*------- ---- test(name,xlist) -----------------------\nTEST MVC NAME,0(R1) store argument #1\n MVC XLIST(6),0(R2) store argument #2\n MVI ALLEQ,X'01' alleq=true\n MVI INCRE,X'01' incre=true\n LA R6,1 i=1\nLOOPI LA R2,NXLIST hbound(xlist)\n BCTR R2,0 -1\n CR R6,R2 do i to hbound(xlist)-1\n BH ELOOPI\n MVC XBOOL,ALLEQ\n OC XBOOL,INCRE or\n CLI XBOOL,X'01' and while alleq or incre\n BNE ELOOPI\n LA R2,1(R6) i+1\n SLA R2,1 *2\n LA R3,XLIST-2(R2) @xlist(i+1)\n LR R1,R6 i\n SLA R1,1 *2\n LA R4,XLIST-2(R1) @xlist(i)\n CLC 0(2,R3),0(R4) if xlist(i+1)=xlist(i)\n BNE SEL1B\n MVI INCRE,X'00' incre=false\n B SEL1END\nSEL1B CLC 0(2,R3),0(R4) if xlist(i+1)<xlist(i)\n BNL SEL1OTH\n MVI INCRE,X'00' incre=false\n MVI ALLEQ,X'00' alleq=false\n B SEL1END\nSEL1OTH MVI ALLEQ,X'00' alleq=false\nSEL1END LA R6,1(R6) i=i+1\n B LOOPI\nELOOPI CLI ALLEQ,X'01' if alleq\n BNE SEL2B\n MVC TXT,=CL40'all elements are equal'\n B SEL2END\nSEL2B CLI INCRE,X'01' if incre\n BNE SEL2OTH\n MVC TXT,=CL40'elements are in increasing order'\n B SEL2END\nSEL2OTH MVC TXT,=CL40'neither equal nor in increasing order'\nSEL2END MVI PG,C' '\n MVC PG+1(79),PG clear buffer\n MVC PG(3),NAME\n MVC PG+3(3),=C' : '\n MVC PG+6(40),TXT\n XPRNT PG,L'PG\n BR R14 return to caller\n* ---- ----------------------------------------\nSNAME DS CL3\nABC DC CL2'AA',CL2'BB',CL2'CC'\nAAA DC CL2'AA',CL2'AA',CL2'AA'\nACB DC CL2'AA',CL2'CC',CL2'BB'\nNAME DS CL3\nXLIST DS 3CL2\nNXLIST EQU (*-XLIST)/L'XLIST\nALLEQ DS X\nINCRE DS X\nTXT DS CL40\nXBOOL DS X\nPG DS CL80\n YREGS\n END COMPLIST\n", "language": "360-Assembly" }, { "code": "DEFINE PTR=\"CARD\"\n\nBYTE FUNC AreEqual(PTR ARRAY a BYTE len)\n INT i\n\n FOR i=1 TO len-1\n DO\n IF SCompare(a(0),a(i))#0 THEN\n RETURN (0)\n FI\n OD\nRETURN (1)\n\nBYTE FUNC IsAscendingOrder(PTR ARRAY a BYTE len)\n INT i\n\n FOR i=1 TO len-1\n DO\n IF SCompare(a(i-1),a(i))>=0 THEN\n RETURN (0)\n FI\n OD\nRETURN (1)\n\nPROC Test(PTR ARRAY a BYTE len)\n INT i\n\n Print(\"Input array: [\")\n FOR i=0 TO len-1\n DO\n Print(a(i))\n IF i<len-1 THEN\n Put(32)\n FI\n OD\n PrintE(\"]\")\n\n IF AreEqual(a,len) THEN\n PrintE(\"All strings are lexically equal.\")\n ELSE\n PrintE(\"Not all strings are lexically equal.\")\n FI\n\n IF IsAscendingOrder(a,len) THEN\n PrintE(\"The list is in strict ascending order.\")\n ELSE\n PrintE(\"The list is not in strict ascending order.\")\n FI\n PutE()\nRETURN\n\nPROC Main()\n PTR ARRAY a1(4),a2(4),a3(4),a4(1)\n\n a1(0)=\"aaa\" a1(1)=\"aaa\" a1(2)=\"aaa\" a1(3)=\"aaa\"\n Test(a1,4)\n\n a2(0)=\"aaa\" a2(1)=\"aab\" a2(2)=\"aba\" a2(3)=\"baa\"\n Test(a2,4)\n\n a3(0)=\"aaa\" a3(1)=\"aab\" a3(2)=\"aba\" a3(3)=\"aba\"\n Test(a3,4)\n\n a4(0)=\"aaa\"\n Test(a4,1)\nRETURN\n", "language": "Action-" }, { "code": " package String_Vec is new Ada.Containers.Indefinite_Vectors\n (Index_Type => Positive, Element_Type => String);\n\n use type String_Vec.Vector;\n", "language": "Ada" }, { "code": " function All_Are_The_Same(Strings: String_Vec.Vector) return Boolean is\n begin\n for Idx in Strings.First_Index .. Strings.Last_Index-1 loop\n\t if Strings(Idx) /= Strings(Idx+1) then\n\t return False;\n\t end if;\n end loop;\n return True;\n end All_Are_The_Same;\n", "language": "Ada" }, { "code": " function Strictly_Ascending(Strings: String_Vec.Vector) return Boolean is\n begin\n for Idx in Strings.First_Index+1 .. Strings.Last_Index loop\n\t if Strings(Idx-1) >= Strings(Idx) then\n\t return False;\n\t end if;\n end loop;\n return True;\n end Strictly_Ascending;\n", "language": "Ada" }, { "code": "Put_Line(Boolean'Image(All_Are_The_Same(Strings)) & \", \" &\n Boolean'Image(Strictly_Ascending(Strings)));\n", "language": "Ada" }, { "code": "[]STRING list1 = (\"AA\",\"BB\",\"CC\");\n[]STRING list2 = (\"AA\",\"AA\",\"AA\");\n[]STRING list3 = (\"AA\",\"CC\",\"BB\");\n[]STRING list4 = (\"AA\",\"ACB\",\"BB\",\"CC\");\n[]STRING list5 = (\"single_element\");\n\n[][]STRING all lists to test = (list1, list2, list3, list4, list5);\n\nPROC equal = ([]STRING list) BOOL:\n BEGIN\n BOOL ok := TRUE;\n FOR i TO UPB list - 1 WHILE ok DO\n ok := list[i] = list[i+1]\n OD;\n ok\n END;\n\nPROC less than = ([]STRING list) BOOL:\n BEGIN\n BOOL ok := TRUE;\n FOR i TO UPB list - 1 WHILE ok DO\n ok := list[i] < list[i + 1]\n OD;\n ok\n END;\n\nFOR i TO UPB all lists to test DO\n []STRING list = all lists to test[i];\n print ((\"list:\", (STRING s; FOR i TO UPB list DO s +:= \" \" + list[i] OD; s), new line));\n IF equal (list) THEN\n print ((\"...is lexically equal\", new line))\n ELSE\n print ((\"...is not lexically equal\", new line))\n FI;\n IF less than (list) THEN\n print ((\"...is in strict ascending order\", new line))\n ELSE\n print ((\"...is not in strict ascending order\", new line))\n FI\nOD\n", "language": "ALGOL-68" }, { "code": " % returns true if all elements of the string array a are equal, false otherwise %\n % As Algol W procedures cannot determine the bounds of an array, the bounds %\n % must be specified in lo and hi %\n logical procedure allStringsEqual ( string(256) array a ( * )\n ; integer value lo, hi\n ) ;\n begin\n logical same;\n integer listPos;\n same := true;\n listPos := lo + 1;\n while same and listPos <= hi do begin\n same := a( lo ) = a( listPos );\n listPos := listPos + 1\n end;\n same\n end allStringsEqual ;\n\n % returns true if the elements of the string array a are in ascending order, %\n % false otherwise %\n % As Algol W procedures cannot determine the bounds of an array, the bounds %\n % must be specified in lo and hi %\n logical procedure ascendingOrder ( string(256) array a ( * )\n ; integer value lo, hi\n ) ;\n begin\n logical ordered;\n integer listPos;\n ordered := true;\n listPos := lo + 1;\n while ordered and listPos <= hi do begin\n ordered := a( listPos - 1 ) < a( listPos );\n listPos := listPos + 1\n end;\n ordered\n end ascendingOrder ;\n", "language": "ALGOL-W" }, { "code": "-- allEqual :: [String] -> Bool\non allEqual(xs)\n _and(zipWith(my _equal, xs, rest of xs))\nend allEqual\n\n-- azSorted :: [String] -> Bool\non azSorted(xs)\n _and(zipWith(my azBeforeOrSame, xs, rest of xs))\nend azSorted\n\n-- _equal :: a -> a -> Bool\non _equal(a, b)\n a = b\nend _equal\n\n-- azBefore :: String -> String -> Bool\non azBeforeOrSame(a, b)\n a ≥ b\nend azBeforeOrSame\n\n-- _and :: [a] -> Bool\non _and(xs)\n foldr(_equal, true, xs)\nend _and\n\n\n-- TEST\non run\n set lstA to [\"isiZulu\", \"isiXhosa\", \"isiNdebele\", \"Xitsonga\", \"Tshivenda\", ¬\n \"Setswana\", \"Sesotho sa Leboa\", \"Sesotho\", \"English\", \"Afrikaans\"]\n\n set lstB to [\"Afrikaans\", \"English\", \"Sesotho\", \"Sesotho sa Leboa\", \"Setswana\", ¬\n \"Tshivenda\", \"Xitsonga\", \"isiNdebele\", \"isiXhosa\", \"isiZulu\"]\n\n set lstC to [\"alpha\", \"alpha\", \"alpha\", \"alpha\", \"alpha\", \"alpha\", \"alpha\", ¬\n \"alpha\", \"alpha\", \"alpha\"]\n\n\n {allEqual:map(allEqual, [lstA, lstB, lstC]), azSorted:map(azSorted, [lstA, lstB, lstC])}\n\n -- > {allEqual:{false, false, true}, azSorted:{false, true, true}}\nend run\n\n\n\n-- GENERIC FUNCTIONS\n\n-- foldr :: (a -> b -> a) -> a -> [b] -> a\non foldr(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from lng to 1 by -1\n set v to lambda(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldr\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to lambda(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\non zipWith(f, xs, ys)\n set nx to length of xs\n set ny to length of ys\n if nx < 1 or ny < 1 then\n {}\n else\n set lng to cond(nx < ny, nx, ny)\n set lst to {}\n tell mReturn(f)\n repeat with i from 1 to lng\n set end of lst to lambda(item i of xs, item i of ys)\n end repeat\n return lst\n end tell\n end if\nend zipWith\n\n-- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b)\non cond(bool, f, g)\n if bool then\n f\n else\n g\n end if\nend cond\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property lambda : f\n end script\n end if\nend mReturn\n", "language": "AppleScript" }, { "code": "allEqual?: function [lst] -> 1 = size unique lst\nascending?: function [lst] -> lst = sort lst\n\nlists: [\n [\"abc\" \"abc\" \"abc\"]\n [\"abc\" \"abd\" \"abc\"]\n [\"abc\" \"abd\" \"abe\"]\n [\"abc\" \"abe\" \"abd\"]\n]\n\nloop lists 'l [\n print [\"list:\" l]\n print [\"allEqual?\" allEqual? l]\n print [\"ascending?\" ascending? l \"\\n\"]\n]\n", "language": "Arturo" }, { "code": "# syntax: GAWK -f COMPARE_A_LIST_OF_STRINGS.AWK\nBEGIN {\n main(\"AA,BB,CC\")\n main(\"AA,AA,AA\")\n main(\"AA,CC,BB\")\n main(\"AA,ACB,BB,CC\")\n main(\"single_element\")\n exit(0)\n}\nfunction main(list, arr,i,n,test1,test2) {\n test1 = 1 # elements are identical\n test2 = 1 # elements are in ascending order\n n = split(list,arr,\",\")\n printf(\"\\nlist:\")\n for (i=1; i<=n; i++) {\n printf(\" %s\",arr[i])\n if (i > 1) {\n if (arr[i-1] != arr[i]) {\n test1 = 0 # elements are not identical\n }\n if (arr[i-1] >= arr[i]) {\n test2 = 0 # elements are not in ascending order\n }\n }\n }\n printf(\"\\n%d\\n%d\\n\",test1,test2)\n}\n", "language": "AWK" }, { "code": "AllEq ← ⍋≡⍒\nAsc ← ¬∘AllEq∧∧≡⊢\n\n•Show AllEq ⟨\"AA\", \"AA\", \"AA\", \"AA\"⟩\n•Show Asc ⟨\"AA\", \"AA\", \"AA\", \"AA\"⟩\n\n•Show AllEq ⟨\"AA\", \"ACB\", \"BB\", \"CC\"⟩\n•Show Asc ⟨\"AA\", \"ACB\", \"BB\", \"CC\"⟩\n", "language": "BQN" }, { "code": "1\n0\n0\n1\n", "language": "BQN" }, { "code": " (test1=first.~(!arg:%@?first ? (%@:~!first) ?))\n& (test2=x.~(!arg:? %@?x (%@:~>!x) ?))\n", "language": "Bracmat" }, { "code": "( ( lstA\n . isiZulu\n isiXhosa\n isiNdebele\n Xitsonga\n Tshivenda\n Setswana\n \"Sesotho sa Leboa\"\n Sesotho\n English\n Afrikaans\n )\n ( lstB\n . Afrikaans\n English\n Sesotho\n \"Sesotho sa Leboa\"\n Setswana\n Tshivenda\n Xitsonga\n isiNdebele\n isiXhosa\n isiZulu\n )\n ( lstC\n . alpha\n alpha\n alpha\n alpha\n alpha\n alpha\n alpha\n alpha\n alpha\n alpha\n )\n : ?lists\n& map\n $ ( (\n = name list\n . !arg:(?name.?list)\n & out\n $ ( test1\n !name\n (test1$!list&succeeds|fails)\n )\n & out\n $ ( test2\n !name\n (test2$!list&succeeds|fails)\n )\n )\n . !lists\n )\n)\n", "language": "Bracmat" }, { "code": ":import std/String .\n\nall-eq? [land? (zip-with eq? 0 (tail 0))]\n\nall-gt? [land? (zip-with lt? 0 (tail 0))]\n\n# --- tests ---\n\nlist-a \"abc\" : (\"abc\" : {}(\"abc\"))\n\nlist-b \"abc\" : (\"def\" : {}(\"ghi\"))\n\n:test (all-eq? list-a) ([[1]])\n:test (all-eq? list-b) ([[0]])\n:test (all-gt? list-a) ([[0]])\n:test (all-gt? list-b) ([[1]])\n", "language": "Bruijn" }, { "code": "#include <stdbool.h>\n#include <string.h>\n\nstatic bool\nstrings_are_equal(const char **strings, size_t nstrings)\n{\n for (size_t i = 1; i < nstrings; i++)\n if (strcmp(strings[0], strings[i]) != 0)\n return false;\n return true;\n}\n\nstatic bool\nstrings_are_in_ascending_order(const char **strings, size_t nstrings)\n{\n for (size_t i = 1; i < nstrings; i++)\n if (strcmp(strings[i - 1], strings[i]) >= 0)\n return false;\n return true;\n}\n", "language": "C" }, { "code": "#include <algorithm>\n#include <string>\n\n// Bug: calling operator++ on an empty collection invokes undefined behavior.\nstd::all_of( ++(strings.begin()), strings.end(),\n [&](std::string a){ return a == strings.front(); } ) // All equal\n\nstd::is_sorted( strings.begin(), strings.end(),\n [](std::string a, std::string b){ return !(b < a); }) ) // Strictly ascending\n", "language": "C++" }, { "code": "public static (bool lexicallyEqual, bool strictlyAscending) CompareAListOfStrings(List<string> strings) =>\n strings.Count < 2 ? (true, true) :\n (\n strings.Distinct().Count() < 2,\n Enumerable.Range(1, strings.Count - 1).All(i => string.Compare(strings[i-1], strings[i]) < 0)\n );\n", "language": "C-sharp" }, { "code": ";; Checks if all items in strings list are equal (returns true if list is empty)\n(every?\t(fn [[a nexta]] (= a nexta)) (map vector strings (rest strings))))\n\n;; Checks strings list is in ascending order (returns true if list is empty)\n(every?\t(fn [[a nexta]] (<= (compare a nexta) 0)) (map vector strings (rest strings))))\n", "language": "Clojure" }, { "code": " identification division.\n program-id. CompareLists.\n\n data division.\n working-storage section.\n 78 MAX-ITEMS value 3.\n 77 i pic 9(2).\n 01 the-list.\n 05 list-items occurs MAX-ITEMS.\n 10 list-item pic x(3).\n 01 results.\n 05 filler pic 9(1).\n 88 equal-strings value 1 when set to false is 0.\n 05 filler pic 9(1).\n 88 ordered-strings value 1 when set to false is 0.\n\n procedure division.\n main.\n move \"AA BB CC\" to the-list\n perform check-list\n move \"AA AA AA\" to the-list\n perform check-list\n move \"AA CC BB\" to the-list\n perform check-list\n move \"AA ACBBB CC\" to the-list\n perform check-list\n move \"AA\" to the-list\n perform check-list\n stop run\n .\n check-list.\n display \"list:\"\n set equal-strings to true\n set ordered-strings to true\n perform varying i from 1 by 1 until i > MAX-ITEMS\n if list-item(i) <> spaces\n display function trim(list-item(i)), \" \" no advancing\n if i < MAX-ITEMS and list-item(i + 1) <> spaces\n if list-item(i + 1) <> list-item(i)\n set equal-strings to false\n end-if\n if list-item(i + 1) <= list-item(i)\n set ordered-strings to false\n end-if\n end-if\n end-if\n end-perform\n display \" \"\n if equal-strings\n display \"... is lexically equal\"\n else\n display \"... is not lexically equal\"\n end-if\n if ordered-strings\n display \"... is in strict ascending order\"\n else\n display \"... is not in strict ascending order\"\n end-if\n display \" \"\n .\n", "language": "COBOL" }, { "code": "(defun strings-equal-p (strings)\n (null (remove (first strings) (rest strings) :test #'string=)))\n\n(defun strings-ascending-p (strings)\n (loop for string1 = (first strings) then string2\n for string2 in (rest strings)\n always (string-lessp string1 string2)))\n", "language": "Common-Lisp" }, { "code": "void main() {\n import std.stdio, std.algorithm, std.range, std.string;\n\n foreach (const strings; [\"AA AA AA AA\", \"AA ACB BB CC\"].map!split) {\n strings.writeln;\n strings.zip(strings.dropOne).all!(ab => ab[0] == ab[1]).writeln;\n strings.zip(strings.dropOne).all!(ab => ab[0] < ab[1]).writeln;\n writeln;\n }\n}\n", "language": "D" }, { "code": "program Compare_a_list_of_strings;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils;\n\ntype\n // generic alias for use helper. The \"TArray<string>\" will be work too\n TListString = TArray<string>;\n\n TListStringHelper = record helper for TListString\n function AllEqual: boolean;\n function AllLessThan: boolean;\n function ToString: string;\n end;\n\n{ TListStringHelper }\n\nfunction TListStringHelper.AllEqual: boolean;\nbegin\n Result := True;\n if Length(self) < 2 then\n exit;\n\n var first := self[0];\n for var i := 1 to High(self) do\n if self[i] <> first then\n exit(False);\nend;\n\nfunction TListStringHelper.AllLessThan: boolean;\nbegin\n Result := True;\n if Length(self) < 2 then\n exit;\n\n var last := self[0];\n for var i := 1 to High(self) do\n begin\n if not (last < self[i]) then\n exit(False);\n last := self[i];\n end;\nend;\n\nfunction TListStringHelper.ToString: string;\nbegin\n Result := '[';\n Result := Result + string.join(', ', self);\n Result := Result + ']';\nend;\n\nvar\n lists: TArray<TArray<string>>;\n\nbegin\n lists := [['a'], ['a', 'a'], ['a', 'b']];\n\n for var list in lists do\n begin\n writeln(list.ToString);\n writeln('Is AllEqual: ', list.AllEqual);\n writeln('Is AllLessThan: ', list.AllLessThan, #10);\n end;\n\n readln;\nend.\n", "language": "Delphi" }, { "code": "func isSorted(xs) {\n var prev\n for x in xs {\n if prev && !(x > prev) {\n return false\n }\n prev = x\n }\n true\n}\n\nfunc isEqual(xs) {\n var prev\n for x in xs {\n if prev && x != prev {\n return false\n }\n prev = x\n }\n true\n}\n", "language": "Dyalect" }, { "code": "proc test s$[] . .\n ident = 1\n ascend = 1\n for i = 2 to len s$[]\n h = strcmp s$[i] s$[i - 1]\n if h <> 0\n ident = 0\n .\n if h <= 0\n ascend = 0\n .\n .\n print s$[]\n if ident = 1\n print \"all equal\"\n .\n if ascend = 1\n print \"ascending\"\n .\n print \"\"\n.\ntest [ \"AA\" \"BB\" \"CC\" ]\ntest [ \"AA\" \"AA\" \"AA\" ]\ntest [ \"AA\" \"CC\" \"BB\" ]\ntest [ \"AA\" \"ACB\" \"BB\" \"CC\" ]\ntest [ \"single_element\" ]\n", "language": "EasyLang" }, { "code": "import system'collections;\nimport system'routines;\nimport extensions;\n\nextension helper\n{\n isEqual()\n = nil == self.seekEach(self.FirstMember, (n,m => m != n));\n\n isAscending()\n {\n var former := self.enumerator();\n var later := self.enumerator();\n\n later.next();\n\n ^ nil == former.zipBy(later, (prev,next => next <= prev )).seekEach::(b => b)\n }\n}\n\ntestCases\n = new string[][]{\n new string[]{\"AA\",\"BB\",\"CC\"},\n new string[]{\"AA\",\"AA\",\"AA\"},\n new string[]{\"AA\",\"CC\",\"BB\"},\n new string[]{\"AA\",\"ACB\",\"BB\",\"CC\"},\n new string[]{\"single_element\"}};\n\npublic program()\n{\n testCases.forEach::(list)\n {\n console.printLine(list.asEnumerable(),\" all equal - \",list.isEqual());\n console.printLine(list.asEnumerable(),\" ascending - \",list.isAscending())\n };\n\n console.readChar()\n}\n", "language": "Elena" }, { "code": "defmodule RC do\n def compare_strings(strings) do\n {length(Enum.uniq(strings))<=1, strict_ascending(strings)}\n end\n\n defp strict_ascending(strings) when length(strings) <= 1, do: true\n defp strict_ascending([first, second | _]) when first >= second, do: false\n defp strict_ascending([_, second | rest]), do: strict_ascending([second | rest])\nend\n\nlists = [ ~w(AA AA AA AA), ~w(AA ACB BB CC), ~w(AA CC BB), [], [\"XYZ\"] ]\nEnum.each(lists, fn list ->\n IO.puts \"#{inspect RC.compare_strings(list)}\\t<= #{inspect list} \"\nend)\n", "language": "Elixir" }, { "code": "-module(compare_strings).\n\n-export([all_equal/1,all_incr/1]).\n\nall_equal(Strings) ->\n\tall_fulfill(fun(S1,S2) -> S1 == S2 end,Strings).\n\nall_incr(Strings) ->\n\tall_fulfill(fun(S1,S2) -> S1 < S2 end,Strings).\n\nall_fulfill(Fun,Strings) ->\n\tlists:all(fun(X) -> X end,lists:zipwith(Fun, lists:droplast(Strings), tl(Strings)) ).\n", "language": "Erlang" }, { "code": "let allEqual strings = Seq.isEmpty strings || Seq.forall (fun x -> x = Seq.head strings) (Seq.tail strings)\nlet ascending strings = Seq.isEmpty strings || Seq.forall2 (fun x y -> x < y) strings (Seq.tail strings)\n", "language": "F-Sharp" }, { "code": "let (!) f s = Seq.isEmpty s || Seq.forall2 f s (Seq.tail s)\n", "language": "F-Sharp" }, { "code": "let allEqual = !(=)\nlet ascending = !(<)\n", "language": "F-Sharp" }, { "code": "USE: grouping\nall-equal?\n", "language": "Factor" }, { "code": "USING: grouping math.order ;\n[ before? ] monotonic?\n", "language": "Factor" }, { "code": "\\ linked list of strings creators\n: ,\" ( -- ) [CHAR] \" WORD c@ 1+ ALLOT ; \\ Parse input stream until \" and write into next available memory\n: [[ ( -- ) 0 C, ; \\ begin a list. write a 0 into next memory byte (null string)\n: ]] ( -- ) [[ ; \\ end list with same null string\n\n: nth ( n list -- addr) swap 0 do count + loop ; \\ return address of the Nth item in a list\n\n: items ( list -- n ) \\ return the number of items in a list\n 0 >R\n BEGIN\n COUNT + DUP\n R> 1+ >R\n 0= UNTIL\n DROP\n R> 1- ;\n\n: compare$ ( $1 $2 -- -n|0|n ) count rot count compare ; \\ compare is an ANS Forth word. returns 0 if $1=$2\n\n: compare[] ( list n1 n2 -- flag) \\ compare items n1 and n2 in list\n ROT dup >R nth ( -- $1)\n swap r> nth ( -- $1 $2)\n compare$ ;\n\n\\ create our lexical operators\n: LEX= ( list -- flag)\n 0 \\ place holder for the flag\n over items 1\n DO\n over I I 1+ compare[] + \\ we sum the comparison results on the stack\n LOOP\n nip 0= ;\n\n: LEX< ( list -- flag)\n 0 \\ place holder for the flag\n over items 1\n DO\n over I I 1+ compare[] 0< NOT +\n LOOP\n nip 0= ;\n\n\\ make some lists\ncreate strings [[ ,\" ENTRY 4\" ,\" ENTRY 3\" ,\" ENTRY 2\" ,\" ENTRY 1\" ]]\ncreate strings2 [[ ,\" the same\" ,\" the same\" ,\" the same\" ]]\ncreate strings3 [[ ,\" AAA\" ,\" BBB\" ,\" CCC\" ,\" DDD\" ]]\n", "language": "Forth" }, { "code": ": test-equality ( string node -- new-string bad? )\n over count \\ -- string node adr cnt\n rot .line @ count compare ;\n\n: test-ascending ( string node -- new-string bad? )\n .line @ >r\n count r@ count compare -1 <> \\ -- bad?\n r> swap ;\n\n: test-seq { seq 'test -- flag } \\ 'TEST picture: string node -- new-string bad?\n seq length 2 < if true exit then\n seq .line @ seq 2nd 'test find-node\n nip 0= ;\n", "language": "Forth" }, { "code": " INTEGER MANY,LONG\n PARAMETER (LONG = 6,MANY = 4)\t!Adjust to suit.\n CHARACTER*(LONG) STRINGS(MANY)\t!A list of text strings.\n STRINGS(1) = \"Fee\"\n STRINGS(2) = \"Fie\"\n STRINGS(3) = \"Foe\"\n STRINGS(4) = \"Fum\"\n IF (ALL(STRINGS(1:MANY - 1) .LT. STRINGS(2:MANY))) THEN\n WRITE (6,*) MANY,\" strings: strictly increasing in order.\"\n ELSE\n WRITE (6,*) MANY,\" strings: not strictly increasing in order.\"\n END IF\n IF (ALL(STRINGS(1:MANY - 1) .EQ. STRINGS(2:MANY))) THEN\n WRITE (6,*) MANY,\" strings: all equal.\"\n ELSE\n WRITE (6,*) MANY,\" strings: not all equal.\"\n END IF\n END\n", "language": "Fortran" }, { "code": " character (len=12) :: surname\n", "language": "Fortran" }, { "code": "program compare_char_list\n implicit none\n character(len=6), allocatable, dimension(:) :: ss\n integer :: many\n ss = [\"Fee\",\"Fie\",\"Foe\",\"Fum\"]\n many = size(ss)\n if (all(ss(1:many - 1) .lt. ss(2:many))) then\n write (*,*) many,\" strings: strictly increasing in order.\"\n else\n write (*,*) many,\" strings: not strictly increasing in order.\"\n end if\n if (all(ss(1:many - 1) .eq. ss(2:many))) then\n write (*,*) many,\" strings: all equal.\"\n else\n write (*,*) many,\" strings: not all equal.\"\n end if\nend program compare_char_list\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nFunction AllEqual(strings() As String) As Boolean\n Dim length As Integer = UBound(strings) - LBound(strings) + 1\n If length < 2 Then Return False\n For i As Integer = LBound(strings) + 1 To UBound(strings)\n If strings(i - 1) <> strings(i) Then Return False\n Next\n Return True\nEnd Function\n\nFunction AllAscending(strings() As String) As Boolean\n Dim length As Integer = UBound(strings) - LBound(strings) + 1\n If length < 2 Then Return False\n For i As Integer = LBound(strings) + 1 To UBound(strings)\n If strings(i - 1) >= strings(i) Then Return False\n Next\n Return True\nEnd Function\n", "language": "FreeBASIC" }, { "code": "local fn ListObjectsAreIdentical( array as CFArrayRef ) as BOOL\n BOOL result = NO\n\n CFSetRef set = fn SetWithArray( array )\n result = ( fn SetCount( set ) <= 1 )\nend fn = result\n\nlocal fn ListIsInLexicalOrder( array as CFArrayRef ) as BOOL\n BOOL result = NO\n\n CFArrayRef sortedArray = fn ArraySortedArrayUsingSelector( array, @\"compare:\" )\n result = fn ArrayIsEqual( array, sortedArray )\nend fn = result\n\nvoid local fn ListTest\n long i\n\n CFArrayRef listA = @[@\"aaa\", @\"aaa\", @\"aaa\", @\"aaa\"]\n CFArrayRef listB = @[@\"aaa\", @\"aab\", @\"aba\", @\"baa\"]\n CFArrayRef listC = @[@\"caa\", @\"aab\", @\"aca\", @\"abc\"]\n CFArrayRef lists = @[listA, listB, listC]\n\n for i = 0 to 2\n CFArrayRef temp = lists[i]\n printf @\"Input array elements: %@ %@ %@ %@\", temp[0], temp[1], temp[2], temp[3]\n if ( fn ListObjectsAreIdentical( temp ) )\n printf @\"List elements are lexically equal.\"\n else\n printf @\"List elements not lexically equal.\"\n end if\n if ( fn ListIsInLexicalOrder( temp ) == YES )\n printf @\"List elements are in ascending order.\"\n else\n printf @\"List elements not in ascending order.\"\n end if\n CFArrayRef sorted = fn ArraySortedArrayUsingSelector( temp, @\"compare:\" )\n printf @\"List elements sorted in ascending order: %@ %@ %@ %@\", sorted[0], sorted[1], sorted[2], sorted[3]\n print\n next\nend fn\n\nfn ListTest\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package cmp\n\nfunc AllEqual(strings []string) bool {\n\tfor _, s := range strings {\n\t\tif s != strings[0] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc AllLessThan(strings []string) bool {\n\tfor i := 1; i < len(strings); i++ {\n\t\tif !(strings[i - 1] < s) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n", "language": "Go" }, { "code": "var list = {\"a\", \"b\", \"c\", \"d\"}\n\nvar isHomogeneous = list.toSet().Count < 2\nvar isOrderedSet = list.toSet().order().toList() == list\n", "language": "Gosu" }, { "code": "allEqual :: Eq a => [a] -> Bool\nallEqual xs = and $ zipWith (==) xs (tail xs)\n\nallIncr :: Ord a => [a] -> Bool\nallIncr xs = and $ zipWith (<) xs (tail xs)\n", "language": "Haskell" }, { "code": "allEqual\n :: Eq a\n => [a] -> Bool\nallEqual [] = True\nallEqual (h:t) = foldl (\\a x -> a && x == h) True t\n\nallIncreasing\n :: Ord a\n => [a] -> Bool\nallIncreasing [] = True\nallIncreasing (h:t) = fst $ foldl (\\(a, x) y -> (a && x < y, y)) (True, h) t\n", "language": "Haskell" }, { "code": "allEq\n :: Eq a\n => [a] -> Bool\nallEq [] = True\nallEq (h:t) =\n null . snd $\n until\n (\\(x, xs) -> null xs || x /= head xs)\n (\\(_, x:xs) -> (x, xs))\n (h, t)\n\nallInc\n :: Ord a\n => [a] -> Bool\nallInc [] = True\nallInc (h:t) =\n null . snd $\n until\n (\\(x, xs) -> null xs || x >= head xs)\n (\\(_, x:xs) -> (x, xs))\n (h, t)\n", "language": "Haskell" }, { "code": "#\n# list-compare.icn\n#\nlink fullimag\n\nprocedure main()\n L1 := [\"aa\"]\n L2 := [\"aa\", \"aa\", \"aa\"]\n L3 := [\"\", \"aa\", \"ab\", \"ac\"]\n L4 := [\"aa\", \"bb\", \"cc\"]\n L5 := [\"cc\", \"bb\", \"aa\"]\n\n every L := (L1 | L2 | L3 | L4 | L5) do {\n writes(fullimage(L))\n writes(\": equal \")\n writes(if allequal(L) then \"true\" else \"false\")\n writes(\", ascending \")\n write(if ascending(L) then \"true\" else \"false\")\n }\nend\n\n# test for all identical\nprocedure allequal(L)\n if *L < 2 then return\n a := L[1]\n every b := L[2 to *L] do {\n if a ~== b then fail\n a := b\n }\n return\nend\n\n# test for strictly ascending\nprocedure ascending(L)\n if *L < 2 then return\n a := L[1]\n every b := L[2 to *L] do {\n if a >>= b then fail\n a := b\n }\n return\nend\n", "language": "Icon" }, { "code": " allEq =: 1 = +/@~: NB. or 1 = #@:~. or -: 1&|. or }.-:}:\n", "language": "J" }, { "code": " asc =: /: -: i.@# NB. or -: (/:~) etc.\n", "language": "J" }, { "code": "boolean allEqual(String[] strings) {\n String stringA = strings[0];\n for (String string : strings) {\n if (!string.equals(stringA))\n return false;\n }\n return true;\n}\n", "language": "Java" }, { "code": "boolean isAscending(String[] strings) {\n String previous = strings[0];\n int index = 0;\n for (String string : strings) {\n if (index++ == 0)\n continue;\n if (string.compareTo(previous) < 0)\n return false;\n previous = string;\n }\n return true;\n}\n", "language": "Java" }, { "code": "import java.util.Arrays;\n\npublic class CompareListOfStrings {\n\n public static void main(String[] args) {\n String[][] arr = {{\"AA\", \"AA\", \"AA\", \"AA\"}, {\"AA\", \"ACB\", \"BB\", \"CC\"}};\n for (String[] a : arr) {\n System.out.println(Arrays.toString(a));\n System.out.println(Arrays.stream(a).distinct().count() < 2);\n System.out.println(Arrays.equals(Arrays.stream(a).distinct().sorted().toArray(), a));\n }\n }\n}\n", "language": "Java" }, { "code": "function allEqual(a) {\n var out = true, i = 0;\n while (++i<a.length) {\n out = out && (a[i-1] === a[i]);\n } return out;\n}\n\nfunction azSorted(a) {\n var out = true, i = 0;\n while (++i<a.length) {\n out = out && (a[i-1] < a[i]);\n } return out;\n}\n\nvar e = ['AA', 'AA', 'AA', 'AA'], s = ['AA', 'ACB', 'BB', 'CC'], empty = [], single = ['AA'];\nconsole.log(allEqual(e)); // true\nconsole.log(allEqual(s)); // false\nconsole.log(allEqual(empty)); // true\nconsole.log(allEqual(single)); // true\nconsole.log(azSorted(e)); // false\nconsole.log(azSorted(s)); // true\nconsole.log(azSorted(empty)); // true\nconsole.log(azSorted(single)); // true\n", "language": "JavaScript" }, { "code": "(() => {\n 'use strict';\n\n // allEqual :: [String] -> Bool\n let allEqual = xs => and(zipWith(equal, xs, xs.slice(1))),\n\n // azSorted :: [String] -> Bool\n azSorted = xs => and(zipWith(azBefore, xs, xs.slice(1))),\n\n // equal :: a -> a -> Bool\n equal = (a, b) => a === b,\n\n // azBefore :: String -> String -> Bool\n azBefore = (a, b) => a.toLowerCase() <= b.toLowerCase();\n\n\n // GENERIC\n\n // and :: [Bool] -> Bool\n let and = xs => xs.reduceRight((a, x) => a && x, true),\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n zipWith = (f, xs, ys) => {\n let ny = ys.length;\n return (xs.length <= ny ? xs : xs.slice(0, ny))\n .map((x, i) => f(x, ys[i]));\n };\n\n\n // TEST\n\n let lists = [\n ['isiZulu', 'isiXhosa', 'isiNdebele', 'Xitsonga',\n 'Tshivenda', 'Setswana', 'Sesotho sa Leboa', 'Sesotho',\n 'English', 'Afrikaans'\n ],\n ['Afrikaans', 'English', 'isiNdebele', 'isiXhosa',\n 'isiZulu', 'Sesotho', 'Sesotho sa Leboa', 'Setswana',\n 'Tshivenda', 'Xitsonga',\n ],\n ['alpha', 'alpha', 'alpha', 'alpha', 'alpha', 'alpha',\n 'alpha', 'alpha', 'alpha', 'alpha', 'alpha', 'alpha'\n ]\n ];\n\n return {\n allEqual: lists.map(allEqual),\n azSorted: lists.map(azSorted)\n };\n\n})();\n", "language": "JavaScript" }, { "code": "{\n \"allEqual\": [\n false,\n false,\n true\n ],\n \"azSorted\": [\n false,\n true,\n true\n ]\n}\n", "language": "JavaScript" }, { "code": "# Are the strings all equal?\ndef lexically_equal:\n . as $in\n | reduce range(0;length-1) as $i\n (true; if . then $in[$i] == $in[$i + 1] else false end);\n\n# Are the strings in strictly ascending order?\ndef lexically_ascending:\n . as $in\n | reduce range(0;length-1) as $i\n (true; if . then $in[$i] < $in[$i + 1] else false end);\n", "language": "Jq" }, { "code": "[] | lexically_equal #=> true\n", "language": "Jq" }, { "code": "[\"a\", \"ab\"] | lexically_ascending #=> true\n", "language": "Jq" }, { "code": "/* Compare list of strings, in Jsish */\nfunction allEqual(a) {\n var out = true, i = 0;\n while (++i<a.length) {\n out = out && (a[i-1] === a[i]);\n } return out;\n}\n\nfunction allAscending(a) {\n var out = true, i = 0;\n while (++i<a.length) {\n out = out && (a[i-1] < a[i]);\n } return out;\n}\n\nif (allEqual(strings)) puts(\"strings array all equal\");\nelse puts(\"strings array not all equal\");\n\nif (allAscending(strings)) puts(\"strings array in strict ascending order\");\nelse puts(\"strings array not in strict ascending order\");\n", "language": "Jsish" }, { "code": "allequal(arr::AbstractArray) = isempty(arr) || all(x -> x == first(arr), arr)\n\ntest = [[\"RC\", \"RC\", \"RC\"], [\"RC\", \"RC\", \"Rc\"], [\"RA\", \"RB\", \"RC\"],\n [\"RC\"], String[], ones(Int64, 4), 1:4]\n\nfor v in test\n println(\"\\n# Testing $v:\")\n println(\"The elements are $(\"not \" ^ !allequal(v))all equal.\")\n println(\"The elements are $(\"not \" ^ !issorted(v))strictly increasing.\")\nend\n", "language": "Julia" }, { "code": " {:[2>#x;1;&/=:'x]}:([\"test\" \"test\" \"test\"])\n1\n {:[2>#x;1;&/<:'x]}:([\"bar\" \"baz\" \"foo\"])\n1\n", "language": "Klong" }, { "code": "// version 1.0.6\n\nfun areEqual(strings: Array<String>): Boolean {\n if (strings.size < 2) return true\n return (1 until strings.size).all { strings[it] == strings[it - 1] }\n}\n\nfun areAscending(strings: Array<String>): Boolean {\n if (strings.size < 2) return true\n return (1 until strings.size).all { strings[it] > strings[it - 1] }\n}\n\n// The strings are given in the command line arguments\n\nfun main(args: Array<String>) {\n println(\"The strings are : ${args.joinToString()}\")\n if (areEqual(args)) println(\"They are all equal\")\n else if (areAscending(args)) println(\"They are in strictly ascending order\")\n else println(\"They are neither equal nor in ascending order\")\n}\n", "language": "Kotlin" }, { "code": "{def allsame\n {def allsame.r\n {lambda {:s :n :i}\n {if {= :i :n}\n then true\n else {if {not {W.equal? {A.get :i :s} {A.get 0 :s}}}\n then false\n else {allsame.r :s :n {+ :i 1}} }}}}\n {lambda {:s}\n {allsame.r :s {- {A.length :s} 1} 0} }}\n-> allsame\n\n{def strict_order\n {def strict_order.r\n {lambda {:s :n :i}\n {if {= :i :n}\n then true\n else {if {W.inforequal? {A.get :i :s} {A.get {- :i 1} :s}}\n then false\n else {strict_order.r :s :n {+ :i 1}}}} }}\n {lambda {:s}\n {if {= {A.length :s} 1}\n then true\n else {strict_order.r :s {A.length :s} 1} }}}\n-> strict_order\n\n{S.map allsame\n {A.new AA BB CC}\n {A.new AA AA AA}\n {A.new AA CC BB}\n {A.new AA ACB BB CC}\n {A.new single}\n} -> false true false false true\n\n{S.map strict_order\n {A.new AA BB CC}\n {A.new AA AA AA}\n {A.new AA CC BB}\n {A.new AA ACB BB CC}\n {A.new single}\n} -> true false false true true\n", "language": "Lambdatalk" }, { "code": "function identical(t_str)\n _, fst = next(t_str)\n if fst then\n for _, i in pairs(t_str) do\n if i ~= fst then return false end\n end\n end\n return true\nend\n\nfunction ascending(t_str)\n prev = false\n for _, i in ipairs(t_str) do\n if prev and prev >= i then return false end\n prev = i\n end\n return true\nend\n\nfunction check(str)\n t_str = {}\n for i in string.gmatch(str, \"[%a_]+\") do\n table.insert(t_str, i)\n end\n str = str .. \": \"\n if not identical(t_str) then str = str .. \"not \" end\n str = str .. \"identical and \"\n if not ascending(t_str) then str = str .. \"not \" end\n print(str .. \"ascending.\")\nend\n\ncheck(\"ayu dab dog gar panda tui yak\")\ncheck(\"oy oy oy oy oy oy oy oy oy oy\")\ncheck(\"somehow somewhere sometime\")\ncheck(\"Hoosiers\")\ncheck(\"AA,BB,CC\")\ncheck(\"AA,AA,AA\")\ncheck(\"AA,CC,BB\")\ncheck(\"AA,ACB,BB,CC\")\ncheck(\"single_element\")\n", "language": "Lua" }, { "code": "Module CheckIt {\n Function Equal(Strings){\n k=Each(Strings, 2, -1)\n a$=Array$(Strings, 0)\n =True\n While k {\n =False\n if a$<>array$(k) then exit\n =True\n }\n }\n Function LessThan(Strings){\n =True\n if len(Strings)<2 then exit\n k=Each(Strings, 2)\n a$=Array$(Strings, 0)\n While k {\n =False\n if a$>=array$(k) then exit\n a$=array$(k)\n =True\n }\n }\n\n Print Equal((\"alfa\",\"alfa\",\"alfa\", \"alfa\"))=True\n Print Equal((\"alfa\",))=True\n Dim A$(10)=\"alfa\"\n Print Equal(A$())=True\n Print Equal((\"alfa1\",\"alfa2\",\"alfa3\", \"alfa4\"))=False\n\n Print LessThan((\"alfa1\",\"alfa2\",\"alfa3\", \"alfa4\"))=True\n Print LessThan((\"alfa1\",))=true\n alfa$=Lambda$ k=1 ->{=String$(\"*\", k) : k++}\n Dim A$(20)<<alfa$()\n Print LessThan(A$())=True\n A$(5)=\"\"\n Print LessThan(A$())=False\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "lexEqual := proc(lst)\n\tlocal i:\n\tfor i from 2 to numelems(lst) do\n\t\tif lst[i-1] <> lst[i] then return false: fi:\n\tod:\n\treturn true:\nend proc:\nlexAscending := proc(lst)\n\tlocal i:\n\tfor i from 2 to numelems(lst) do\n\t\tif StringTools:-Compare(lst[i],lst[i-1]) then return false: fi:\n\tod:\n\treturn true:\nend proc:\ntst := [\"abc\",\"abc\",\"abc\",\"abc\",\"abc\"]:\nlexEqual(tst):\nlexAscending(tst):\n", "language": "Maple" }, { "code": "-- define list of list of strings (nested vector of vectors of strings)\n-- Mathcad vectors are single column arrays.\n-- The following notation is for convenience in writing arrays in text form.\n-- Mathcad array input is normally via Mathcad's array operator or via one of the\n-- array-builder functions, such as stack or augment.\n-- \",\" between vector elements indicates a new row.\n-- \" \" between vector elements indicates a new column.\n\nlist:=[\"AA\",\"AA\",\"AA\"],[\"AA\",\"BB\",\"CC\"],[\"AA\",\"CC\",\"BB\"],[\"CC\",\"BB\",\"AA\"],[\"AA\",\"ACB\",\"BB\",\"CC\"],[\"AA\"]]\n\n-- define functions head and rest that return the first value in a list (vector)\n-- and the list excluding the first element, respectively.\n\nhead(v):=if(IsArray(v),v[0,v)\nrest(v):=if(rows(v)>1,submatrix(v,1,rows(v)-1,0,0),0)\n\n-- define a function oprel that iterates through a list (vector) applying a comparison operator op to each pair of elements at the top of the list.\n-- Returns immediately with false (0) if a comparison fails.\n\noprel(op,lst,val):=if(op(val,head(lst)),if(rows(lst)>1,oprel(op,rest(lst),head(lst)),1),0)\n\noprel(op,lst):=if(rows(lst)>1,oprel(op,rest(lst),head(lst)),1)\n\n-- define a set of boolean comparison functions\n-- transpose represents Mathcad's transpose operator\n-- vectorize represents Mathcad's vectorize operator\n\neq(a,b):=a=b (transpose(vectorize(oprel,list))) = [1 0 0 0 0 1] -- equal\nlt(a,b):=a<b (transpose(vectorize(oprel,list))) = [0 1 0 0 1 1] -- ascending\n\n-- oprel, eq and lt also work with numeric values\n\nlist:=[11,11,11],[11,22,33],[11,33,22],[33,22,11],[11,132,22,33],[11]]\n", "language": "Mathcad" }, { "code": "data1 = {\"aaa\", \"aaa\", \"aab\"};\nApply[Equal, data]\nOrderedQ[data]\n", "language": "Mathematica" }, { "code": "alist = {'aa', 'aa', 'aa'}\nall(strcmp(alist,alist{1}))\n", "language": "MATLAB" }, { "code": "// a function to test if a list of strings are equal\ndef stringsEqual(stringList)\n\t// if the list is empty, return true\n\tif (len(stringList) = 0)\n\t\treturn true\n\tend\n\n\t// otherwise get the first value and check for equality\n\ttoCompare = stringList[0]\n\tequal = true\n\tfor (i = 1) (equal && (i < len(stringList))) (i = i + 1)\n\t\tequal = (toCompare = stringList[i])\n\tend for\n\n\n\t// return whether the strings are equal or not\n\treturn equal\nend\n\n// a function to test if a list of strings are are less than each other\ndef stringsLessThan(stringList)\n\t// if the list is empty, return true\n\tif (len(stringList) = 0)\n\t\treturn true\n\tend\n\n\t// otherwise get the first value and check for less than\n\ttoCompare = stringList[0]\n\tlessThan = true\n\tfor (i = 1) (lessThan && (i < len(stringList))) (i = i + 1)\n\t\tlessThan = (toCompare < stringList[i])\n\t\ttoCompare = stringList[i]\n\tend for\n\n\t// return whether the string were less than each other or not\n\treturn lessThan\nend\n", "language": "Nanoquery" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\nrunSample(arg)\nreturn\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod isEqual(list = Rexx[]) public static binary returns boolean\n state = boolean (1 == 1) -- default to true\n loop ix = 1 while ix < list.length\n state = list[ix - 1] == list[ix]\n if \\state then leave ix\n end ix\n return state\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod isAscending(list = Rexx[]) public static binary returns boolean\n state = boolean (1 == 1) -- default to true\n loop ix = 1 while ix < list.length\n state = list[ix - 1] << list[ix]\n if \\state then leave ix\n end ix\n return state\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod runSample(arg) private static\n\n samples = [ -\n ['AA', 'BB', 'CC'] -\n , ['AA', 'AA', 'AA'] -\n , ['AA', 'CC', 'BB'] -\n , ['single_element'] -\n ]\n\n loop ix = 0 while ix < samples.length\n sample = samples[ix]\n if isEqual(sample) then eq = 'elements are identical'\n else eq = 'elements are not identical'\n if isAscending(sample) then asc = 'elements are in ascending order'\n else asc = 'elements are not in ascending order'\n say 'List:' Arrays.toString(sample)\n say ' 'eq\n say ' 'asc\n end ix\n return\n", "language": "NetRexx" }, { "code": "func allEqual(s: openArray[string]): bool =\n\n for i in 1..s.high:\n if s[i] != s[0]:\n return false\n result = true\n\nfunc ascending(s: openArray[string]): bool =\n\n for i in 1..s.high:\n if s[i] <= s[i - 1]:\n return false\n result = true\n\ndoAssert allEqual([\"abc\", \"abc\", \"abc\"])\ndoAssert not allEqual([\"abc\", \"abd\", \"abc\"])\n\ndoAssert ascending([\"abc\", \"abd\", \"abe\"])\ndoAssert not ascending([\"abc\", \"abe\", \"abd\"])\n\ndoAssert allEqual([\"abc\"])\ndoAssert ascending([\"abc\"])\n", "language": "Nim" }, { "code": "import sequtils\n\nfunc allEqual(s: openArray[string]): bool =\n allIt(s, it == s[0])\n\ndoAssert allEqual([\"abc\", \"abc\", \"abc\"])\ndoAssert not allEqual([\"abc\", \"abd\", \"abc\"])\ndoAssert allEqual([\"abc\"])\n", "language": "Nim" }, { "code": "open List;;\n\nlet analyze cmp l =\n let rec analyze' l prevs =\n match l with\n [] -> true\n | [s] -> cmp prevs s\n | s::rest -> (cmp prevs s) && (analyze' rest s)\n in analyze' (List.tl l) (List.hd l)\n;;\n\nlet isEqual = analyze (=) ;;\nlet isAscending = analyze (<) ;;\n\nlet test sample =\n List.iter print_endline sample;\n if (isEqual sample)\n then (print_endline \"elements are identical\")\n else (print_endline \"elements are not identical\");\n if (isAscending sample)\n\t then print_endline \"elements are in ascending order\"\n else print_endline \"elements are not in ascending order\";;\n\n\nlet lasc = [\"AA\";\"BB\";\"CC\";\"EE\"];;\nlet leq = [\"AA\";\"AA\";\"AA\";\"AA\"];;\nlet lnoasc = [\"AA\";\"BB\";\"EE\";\"CC\"];;\n\nList.iter test [lasc;leq;lnoasc];;\n", "language": "OCaml" }, { "code": ": lexEqual asSet size 1 <= ;\n: lexCmp(l) l l right( l size 1- ) zipWith(#<) and ;\n", "language": "Oforth" }, { "code": "/* REXX ---------------------------------------------------------------\n* 28.06.2014 Walter Pachl\n*--------------------------------------------------------------------*/\nCall test 'ABC',.list~of('AA','BB','CC')\nCall test 'AAA',.list~of('AA','AA','AA')\nCall test 'ACB',.list~of('AA','CC','BB')\nExit\n\ntest: Procedure\nUse Arg name,list\nall_equal=1\nincreasing=1\nDo i=0 To list~items-2\n i1=i+1\n Select\n When list[i1]==list[i] Then increasing=0\n When list[i1]<<list[i] Then Do\n all_equal=0\n increasing=0\n End\n When list[i1]>>list[i] Then all_equal=0\n End\n End\nSelect\n When all_equal Then\n Say 'List' name': all elements are equal'\n When increasing Then\n Say 'List' name': elements are in increasing order'\n Otherwise\n Say 'List' name': neither equal nor in increasing order'\n End\nReturn\n", "language": "OoRexx" }, { "code": "allEqual(strings)=#Set(strings)<2\ninOrder(strings)=Set(strings)==strings\n", "language": "PARI-GP" }, { "code": "allEqual(strings)=for(i=2,#strings,if(strings[i]!=strings[i-1], return(0))); 1\ninOrder(strings)=for(i=2,#strings,if(strings[i]>strings[i-1], return(0))); 1\n", "language": "PARI-GP" }, { "code": "use List::Util 1.33 qw(all);\n\nall { $strings[0] eq $strings[$_] } 1..$#strings # All equal\nall { $strings[$_-1] lt $strings[$_] } 1..$#strings # Strictly ascending\n", "language": "Perl" }, { "code": "join(\"\\0\", @strings) =~ /^ ( [^\\0]*+ ) (?: \\0 \\1 )* $/x # All equal\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">allsame</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">strict_order</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]<=</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%-22V allsame:%5t, strict_order:%5t\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">allsame</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">strict_order</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #008000;\">\"AA\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"BB\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"CC\"</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #008000;\">\"AA\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"AA\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"AA\"</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #008000;\">\"AA\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"CC\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"BB\"</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #008000;\">\"AA\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ACB\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"BB\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"CC\"</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #008000;\">\"single_element\"</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "include ..\\Utilitys.pmt\n\n( \"alpha\" \"beta\" \"gamma\" \"delta\" \"epsilon\" \"zeta\"\n \"eta\" \"theta\" \"iota\" \"kappa\" \"lambda\" \"mu\" )\n\ndup dup sort ==\t/# put 0 (false) in the pile, indicating that they are not in ascending order #/\n\ndrop\t/# discard the result #/\n\ndup len swap 1 get rot repeat == /# put 0 (false) in the pile, indicating that they are not repeated strings #/\n", "language": "Phixmonti" }, { "code": "main =>\n Lists = [[\"AA\",\"BB\",\"CC\"],\n [\"AA\",\"AA\",\"AA\"],\n [\"AA\",\"CC\",\"BB\"],\n [\"AA\",\"ACB\",\"BB\",\"CC\"],\n [\"single_element\"],\n []],\n foreach(L in Lists)\n Same = all_same(L).cond(true,false),\n Sorted = sorted(L).cond(true,false),\n printf(\"%-18w all_same:%-5w sorted:%-5w\\n\",L,Same,Sorted)\n end.\n\nall_same([]).\nall_same([_]).\nall_same([A,B|Rest]) :-\n A == B,\n all_same([B|Rest]).\n", "language": "Picat" }, { "code": "(= \"AA\" \"AA\" \"AA\")\n-> T\n(= \"AA\" \"AA\" \"Aa\")\n-> NIL\n(< \"AA\" \"AA\")\n-> NIL\n(< \"AA\" \"Aa\")\n-> T\n(< \"1\" \"A\" \"B\" \"Z\" \"c\" )\n-> T\n(> \"A\" \"B\" \"Z\" \"C\")\n-> NIL\n", "language": "PicoLisp" }, { "code": "(de same (List)\n (apply = List))\n\n(de sorted (List)\n (apply < List))\n\n(de sorted-backwards (List)\n (apply > List))\n\n(same '(\"AA\" \"AA\" \"AA\"))\n-> T\n", "language": "PicoLisp" }, { "code": "*process source xref attributes or(!);\n /*--------------------------------------------------------------------\n * 01.07.2014 Walter Pachl\n *-------------------------------------------------------------------*/\n clist: Proc Options(main);\n Dcl (hbound) Builtin;\n Dcl sysprint Print;\n Dcl abc(3) Char(2) Init('AA','BB','CC');\n Dcl aaa(3) Char(2) Init('AA','AA','AA');\n Dcl acb(3) Char(2) Init('AA','CC','BB');\n Call test('ABC',ABC);\n Call test('AAA',AAA);\n Call test('ACB',ACB);\n\n test: Procedure(name,x);\n Dcl name Char(*);\n Dcl x(*) Char(*);\n Dcl (all_equal,increasing) Bit(1) Init('1'b);\n Dcl (i,i1) Bin Fixed(31);\n Dcl txt Char(50) Var;\n Do i=1 To hbound(x)-1 While(all_equal ! increasing);\n i1=i+1;\n Select;\n When(x(i1)=x(i)) increasing='0'b;\n When(x(i1)<x(i)) Do;\n increasing='0'b;\n all_equal='0'b;\n End;\n Otherwise /* x(i1)>x(i) */\n all_equal='0'b;\n End;\n End;\n Select;\n When(all_equal) txt='all elements are equal';\n When(increasing) txt='elements are in increasing order';\n Otherwise txt='neither equal nor in increasing order';\n End;\n Put Skip List(name!!': '!!txt);\n End;\n End;\n", "language": "PL-I" }, { "code": "To decide if some string things are lexically equal:\nIf the string things are empty, say yes.\nGet a string thing from the string things.\nPut the string thing's string into a canonical string.\nLoop.\nIf the string thing is nil, say yes.\nIf the string thing's string is not the canonical string, say no.\nPut the string thing's next into the string thing.\nRepeat.\n\nTo decide if some string things are in ascending order:\nIf the string things' count is less than 2, say yes.\nGet a string thing from the string things.\nPut the string thing's next into the string thing.\nLoop.\nIf the string thing is nil, say yes.\nIf the string thing's string is less than the string thing's previous' string, say no.\nPut the string thing's next into the string thing.\nRepeat.\n", "language": "Plain-English" }, { "code": "function IsAscending ( [string[]]$Array ) { ( 0..( $Array.Count - 2 ) ).Where{ $Array[$_] -le $Array[$_+1] }.Count -eq $Array.Count - 1 }\nfunction IsEqual ( [string[]]$Array ) { ( 0..( $Array.Count - 2 ) ).Where{ $Array[$_] -eq $Array[$_+1] }.Count -eq $Array.Count - 1 }\n\nIsAscending 'A', 'B', 'B', 'C'\nIsAscending 'A', 'C', 'B', 'C'\nIsAscending 'A', 'A', 'A', 'A'\n\nIsEqual 'A', 'B', 'B', 'C'\nIsEqual 'A', 'C', 'B', 'C'\nIsEqual 'A', 'A', 'A', 'A'\n", "language": "PowerShell" }, { "code": "los([\"AA\",\"BB\",\"CC\"]).\nlos([\"AA\",\"AA\",\"AA\"]).\nlos([\"AA\",\"CC\",\"BB\"]).\nlos([\"AA\",\"ACB\",\"BB\",\"CC\"]).\nlos([\"single_element\"]).\n\nlexically_equal(S,S,S).\nin_order(G,L,G) :- compare(<,L,G).\n\ntest_list(List) :-\n List = [L|T],\n write('for list '), write(List), nl,\n (foldl(lexically_equal, T, L, _)\n -> writeln('The items in the list ARE lexically equal')\n ; writeln('The items in the list are NOT lexically equal')),\n (foldl(in_order, T, L, _)\n -> writeln('The items in the list ARE in ascending order')\n ; writeln('The items in the list are NOT in ascending order')),\n nl.\n\ntest :- forall(los(List), test_list(List)).\n", "language": "Prolog" }, { "code": "EnableExplicit\nDataSection\n Data.s ~\"AA\\tAA\\tAA\\nAA\\tBB\\tCC\\nAA\\tCC\\tBB\\nAA\\tACB\\tBB\\tCC\\nsingel_element\"\nEndDataSection\n\nMacro PassFail(PF)\n If PF : PrintN(\"Pass\") : Else : PrintN(\"Fail\") : EndIf\nEndMacro\n\nMacro ProcRec(Proc)\n Define tf1$,tf2$ : Static chk.b : chk=#True\n tf1$=StringField(s$,c,tz$) : tf2$=StringField(s$,c+1,tz$)\n If Len(tf2$) : Proc(s$,tz$,c+1) : EndIf\nEndMacro\n\nProcedure.b IsStringsEqual(s$,tz$=~\"\\t\",c.i=1)\n ProcRec(IsStringsEqual)\n chk & Bool(tf1$=tf2$ Or tf2$=\"\")\n ProcedureReturn chk\nEndProcedure\n\nProcedure.b IsStringsAscending(s$,tz$=~\"\\t\",c.i=1)\n ProcRec(IsStringsAscending)\n chk & Bool(tf1$<tf2$ Or tf2$=\"\")\n ProcedureReturn chk\nEndProcedure\n\nDefine t$,sf$,c.i,i.i,PF.b\nRead.s t$ : c=CountString(t$,~\"\\n\")\nOpenConsole(\"Compare a list of Strings\")\nFor i=1 To c+1\n sf$=StringField(t$,i,~\"\\n\")\n PrintN(\"List : \"+sf$)\n Print(\"Lexical test : \") : PassFail(IsStringsEqual(sf$))\n Print(\"Ascending test : \") : PassFail(IsStringsAscending(sf$))\n PrintN(\"\")\nNext\nInput()\n", "language": "PureBasic" }, { "code": "all(a == nexta for a, nexta in zip(strings, strings[1:])) # All equal\nall(a < nexta for a, nexta in zip(strings, strings[1:])) # Strictly ascending\n\nlen(set(strings)) == 1 # Concise all equal\nsorted(strings, reverse=True) == strings # Concise (but not particularly efficient) ascending\n", "language": "Python" }, { "code": "from operator import (eq, lt)\n\n\nxs = [\"alpha\", \"beta\", \"gamma\", \"delta\", \"epsilon\", \"zeta\",\n \"eta\", \"theta\", \"iota\", \"kappa\", \"lambda\", \"mu\"]\n\nys = [\"alpha\", \"beta\", \"gamma\", \"delta\", \"epsilon\", \"zeta\",\n \"eta\", \"theta\", \"iota\", \"kappa\", \"lambda\", \"mu\"]\n\naz = sorted(xs)\n\nprint (\n all(map(eq, xs, ys)),\n\n all(map(lt, xs, xs[1:])),\n\n all(map(lt, az, az[1:]))\n)\n", "language": "Python" }, { "code": " [ [ true swap\n dup size 1 > while\n behead swap\n witheach\n [ over != if\n [ dip not conclude ] ] ]\n drop ] is allthesame ( [ --> b )\n\n [ [ true swap\n dup size 1 > while\n behead swap\n witheach\n [ tuck $> if\n [ dip not conclude ] ] ]\n drop ] is allinorder ( [ --> b )\n", "language": "Quackery" }, { "code": "all(strings == strings[1])\nall(strings == sort(strings))\n", "language": "R" }, { "code": "manyStrings=list(\n \"a\",\n c(\"a\", \"b\", \"c\"),\n c(\"a\", \"c\", \"b\"),\n c(\"A\", \"A\"),\n c(\"a\", \"A\"),\n c(123, \"A\", \"Aaron\", \"beryllium\", \"z\"),\n c(123, \"A\", \"z\", \"Aaron\", \"beryllium\", \"z\")\n)\n\nfor (strings in manyStrings) {\n print(strings)\n print(all(strings == strings[1]))\n print(all(strings == sort(strings)))\n}\n", "language": "R" }, { "code": "\"a\"\nTRUE\nTRUE\n\"a\" \"b\" \"c\"\nFALSE\nTRUE\n\"a\" \"c\" \"b\"\nFALSE\nFALSE\n\"A\" \"A\"\nTRUE\nTRUE\n\"a\" \"A\"\nFALSE\nTRUE\n\"123\" \"A\" \"Aaron\" \"beryllium\" \"z\"\nFALSE\nTRUE\n\"123\" \"A\" \"z\" \"Aaron\" \"beryllium\" \"z\"\nFALSE\nFALSE\n", "language": "R" }, { "code": "#lang racket/base\n(define ((list-stringX? stringX?) strs)\n (or (null? strs) (null? (cdr strs)) (apply stringX? strs)))\n(define list-string=? (list-stringX? string=?))\n(define list-string<? (list-stringX? string<?))\n\n(module+ test\n (require tests/eli-tester)\n (test\n (list-string=? '()) => #t\n (list-string=? '(\"a\")) => #t\n (list-string=? '(\"a\" \"a\")) => #t\n (list-string=? '(\"a\" \"a\" \"a\")) => #t\n (list-string=? '(\"b\" \"b\" \"a\")) => #f)\n\n (test\n (list-string<? '()) => #t\n (list-string<? '(\"a\")) => #t\n (list-string<? '(\"a\" \"b\")) => #t\n (list-string<? '(\"a\" \"a\")) => #f\n (list-string<? '(\"a\" \"b\" \"a\")) => #f\n (list-string<? '(\"a\" \"b\" \"c\")) => #t))\n", "language": "Racket" }, { "code": "[eq] @strings # All equal\n[lt] @strings # Strictly ascending\n", "language": "Raku" }, { "code": "Red []\n\nlist1: [\"asdf\" \"Asdf\" \"asdf\"]\nlist2: [\"asdf\" \"bsdf\" \"asdf\"]\nlist3: [\"asdf\" \"asdf\" \"asdf\"]\n\nall-equal?: func [list][ 1 = length? unique/case list ]\nsorted?: func [list][ list == sort/case copy list ] ;; sort without copy would modify list !\n\nprint all-equal? list1\nprint sorted? list1\n\nprint all-equal? list2\nprint sorted? list2\n\nprint all-equal? list3\nprint sorted? list3\n", "language": "Red" }, { "code": "/* REXX ---------------------------------------------------------------\n* 28.06.2014 Walter Pachl\n*--------------------------------------------------------------------*/\nCall mklist 'ABC','AA','BB','CC'\nCall test 'ABC'\nCall mklist 'AAA','AA','AA','AA'\nCall mklist 'ACB','AA','CC','BB'\nCall test 'AAA'\nCall test 'ACB'\nExit\n\nmklist:\n list=arg(1)\n do i=1 by 1 To arg()-1\n call value list'.'i,arg(i+1)\n End\n Call value list'.0',i-1\n Return\n\ntest:\nParse Arg list\nall_equal=1\nincreasing=1\nDo i=1 To value(list'.0')-1 While all_equal | increasing\n i1=i+1\n Select\n When value(list'.i1')==value(list'.i') Then increasing=0\n When value(list'.i1')<<value(list'.i') Then Do\n all_equal=0\n increasing=0\n End\n When value(list'.i1')>>value(list'.i') Then all_equal=0\n End\n End\nSelect\n When all_equal Then\n Say 'List' value(list)': all elements are equal'\n When increasing Then\n Say 'List' value(list)': elements are in increasing order'\n Otherwise\n Say 'List' value(list)': neither equal nor in increasing order'\n End\nReturn\n", "language": "REXX" }, { "code": "/*REXX program compares a list of (character) strings for: equality, all ascending. */\[email protected]= 'ayu dab dog gar panda tui yak' /*seven strings: they're all ascending.*/\[email protected]= 'oy oy oy oy oy oy oy oy oy oy' /* ten strings: all equal. */\[email protected]= 'somehow somewhere sometime' /*three strings: ¬equal, ¬ascending.*/\[email protected]= 'Hoosiers' /*only a single string is defined. */\[email protected]= /*Null. That is, no strings here. */\n do j=1 for 5; say; say /* [↓] traipse through all the lists. */\n say center(' '@.j, 50, \"═\") /*display a centered title/header. */\n if ifEqual( @.j) then say 'strings are all equal.'\n if ifAscend(@.j) then say 'strings are ascending.'\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nifEqual: procedure; parse arg strings /*set STRINGS to a string in the list*/\n do k=2 to words(strings) /*scan the strings in the list. */\n if word(strings,k)\\==word(strings,k-1) then return 0 /*string=prev? */\n end /*k*/ /* [↑] 0=false, [↓] 1=true. */\n return 1 /*indicate that all strings are equal. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nifAscend: procedure; parse arg strings /*set STRINGS to a string in the list*/\n do k=2 to words(strings) /*scan the strings in the list. */\n if word(strings,k)<<=word(strings,k-1) then return 0 /*string>prev? */\n end /*k*/ /* [↑] 0=false, [↓] 1=true. */\n return 1 /*indicate that strings are ascending. */\n", "language": "REXX" }, { "code": "/*REXX program compares a list of strings for: equality, all ascending. */\[email protected]= 'ayu dab dog gar panda tui yak' /*seven strings: they're all ascending.*/\[email protected]= 'oy oy oy oy oy oy oy oy oy oy' /* ten strings: all equal. */\[email protected]= 'somehow somewhere sometime' /*three strings: ¬equal, ¬ascending.*/\[email protected]= 'Hoosiers' /*only a single string is defined. */\[email protected]= /*Null. That is, no strings here. */\n#= 5; do j=1 for #; say; say /* [↓] traipse through all the lists. */\n say center(' '@.j, 50, \"═\") /*display a centered title/header. */\n if cStr(@.j, 'Equal' ) then say \" The strings are all equal.\"\n if cStr(@.j, 'Ascending') then say \" The strings are ascending.\"\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncStr: procedure; parse arg x; arg , how 2 /*set X to list; get 1st char of arg #2*/\n do k=2 to words(x) /*scan the strings in the list. */\n if how=='E' then if word(x,k) \\== word(x,k-1) then return 0 /*¬=prev.?*/\n if how=='A' then if word(x,k) <<= word(x,k-1) then return 0 /*≤ prev.?*/\n end /*k*/ /* [↓] 1=true. [↑] 0=false. */\n return 1 /*indicate strings have true comparison*/\n", "language": "REXX" }, { "code": "strings.uniq.one? # all equal?\nstrings == strings.uniq.sort # ascending?\n", "language": "Ruby" }, { "code": "strings.all?{|str| str == strings.first} # all equal?\nstrings.each_cons(2).all?{|str1, str2| str1 < str2} # ascending?\n", "language": "Ruby" }, { "code": "fn strings_are_equal(seq: &[&str]) -> bool {\n match seq {\n &[] | &[_] => true,\n &[x, y, ref tail @ ..] if x == y => strings_are_equal(&[&[y], tail].concat()),\n _ => false\n }\n}\n\nfn asc_strings(seq: &[&str]) -> bool {\n match seq {\n &[] | &[_] => true,\n &[x, y, ref tail @ ..] if x < y => asc_strings(&[&[y], tail].concat()),\n _ => false\n }\n}\n", "language": "Rust" }, { "code": "define equal_sl(sarr)\n{\n variable n = length(sarr), a0, i;\n if (n < 2) return 1;\n\n a0 = sarr[0];\n _for i (1, length(sarr)-1, 1)\n if (sarr[i] != a0) return 0;\n\n return 1;\n}\ndefine ascending_sl(sarr) {\n variable n = length(sarr), a0, i;\n if (n < 2) return 1;\n\n _for i (0, length(sarr)-2, 1)\n if (sarr[i] >= sarr[i+1]) return 0;\n\n return 1;\n}\n\n\ndefine equal_ai(sarr) {\n if (length(sarr) < 2) return 1;\n variable s0 = sarr[0];\n return all(sarr[[1:]] == s0);\n}\n\ndefine ascending_ai(sarr) {\n variable la = length(sarr);\n if (la < 2) return 1;\n return all(sarr[[0:la-2]] < sarr[[1:la-1]]);\n}\n\ndefine atest(a) {\n () = printf(\"\\n\");\n print(a);\n\n () = printf(\"equal_sl=%d, ascending_sl=%d\\n\",\n equal_sl(a), ascending_sl(a));\n () = printf(\"equal_ai=%d, ascending_ai=%d\\n\",\n equal_ai(a), ascending_ai(a));\n}\n\natest([\"AA\",\"BB\",\"CC\"]);\natest([\"AA\",\"AA\",\"AA\"]);\natest([\"AA\",\"CC\",\"BB\"]);\natest([\"AA\",\"ACB\",\"BB\",\"CC\"]);\natest([\"single_element\"]);\natest(NULL);\n", "language": "S-lang" }, { "code": "def strings_are_equal(seq:List[String]):Boolean = seq match {\n case Nil => true\n case s::Nil => true\n case el1 :: el2 :: tail => el1==el2 && strings_are_equal(el2::tail)\n}\n\ndef asc_strings(seq:List[String]):Boolean = seq match {\n case Nil => true\n case s::Nil => true\n case el1 :: el2 :: tail => el1.compareTo(el2) < 0\n}\n", "language": "Scala" }, { "code": "(define (compare-strings fn strs)\n (or (null? strs) ; returns #t on empty list\n (null? (cdr strs)) ; returns #t on list of size 1\n (do ((fst strs (cdr fst))\n (snd (cdr strs) (cdr snd)))\n ((or (null? snd)\n (not (fn (car fst) (car snd))))\n (null? snd))))) ; returns #t if the snd list is empty, meaning all comparisons are exhausted\n\n(compare-strings string=? strings) ; test for all equal\n(compare-strings string<? strings) ; test for in ascending order\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst func boolean: allTheSame (in array string: strings) is func\n result\n var boolean: allTheSame is TRUE;\n local\n var integer: index is 0;\n begin\n for index range 2 to length(strings) until not allTheSame do\n if strings[pred(index)] <> strings[index] then\n allTheSame := FALSE;\n end if;\n end for;\n end func;\n\nconst func boolean: strictlyAscending (in array string: strings) is func\n result\n var boolean: strictlyAscending is TRUE;\n local\n var integer: index is 0;\n begin\n for index range 2 to length(strings) until not strictlyAscending do\n if strings[pred(index)] >= strings[index] then\n strictlyAscending := FALSE;\n end if;\n end for;\n end func;\n", "language": "Seed7" }, { "code": "analyze [\"AA\",\"BB\",\"CC\"]\nanalyze [\"AA\",\"AA\",\"AA\"]\nanalyze [\"AA\",\"CC\",\"BB\"]\nanalyze [\"AA\",\"ACB\",\"BB\",\"CC\"]\nanalyze [\"single_element\"]\n\nto analyze aList\n\tput \"List: \" & aList\n\tput \" \" & (if allEqual(aList) then \"IS\" else \"Is NOT\") && \"all equal\"\n\tput \" \" & (if isAscending(aList) then \"IS\" else \"Is NOT\") && \"strictly ascending\"\nend analyze\n\nto handle allEqual strings\n\treturn the number of items in the unique items of strings is less than 2\nend allEqual\n\nto handle isAscending strings\n\trepeat with n = 2 to the number of items in strings\n\t\tif item n of strings isn't more than item n-1 of strings then\n\t\t\treturn False\n\t\tend if\n\tend repeat\n\treturn True\nend isAscending\n", "language": "SenseTalk" }, { "code": "1..arr.end -> all{ arr[0] == arr[_] } # all equal\n1..arr.end -> all{ arr[_-1] < arr[_] } # strictly ascending\n", "language": "Sidef" }, { "code": "arr.uniq.len == 1 # all equal\narr == arr.uniq.sort # strictly ascending\n", "language": "Sidef" }, { "code": "// matcher testing if the array contains anything not equal to the first element\ntemplates allEqual\n when <[](..1)> do 1 !\n when <[<~=$(1)>]> do 0 !\n otherwise 1 !\nend allEqual\n\ntemplates strictAscending\n def a: $;\n 1 -> #\n when <$a::length..> do 1 !\n when <?($a($) <..~$a($+1)>)> do $ + 1 -> #\n otherwise 0 !\nend strictAscending\n\n// Of course we could just use the same kind of loop for equality\ntemplates strictEqual\n def a: $;\n 1 -> #\n when <$a::length..> do 1 !\n when <?($a($) <=$a($+1)>)> do $ + 1 -> #\n otherwise 0 !\nend strictEqual\n", "language": "Tailspin" }, { "code": "tcl::mathop::eq {*}$strings;\t\t# All values string-equal\ntcl::mathop::< {*}$strings;\t\t# All values in strict order\n", "language": "Tcl" }, { "code": "#lang transd\n\nMainModule: {\n _start: (λ\n (for v in [[\"aa\",\"ab\",\"ad\",\"ae\"],[\"ab\",\"ab\",\"ab\",\"ab\"]] do\n (lout :boolalpha v)\n (lout (not (any v (λ (ret (neq @it (get v 0)))))))\n (lout (not (any Range(in: v 1 -0)\n (λ (ret (leq @it (get v (- @idx 1))))))) \"\\n\")\n )\n )\n}\n", "language": "Transd" }, { "code": "fn all_equal(strings []string) bool {\n\tfor s in strings {\n\t\tif s != strings[0] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfn all_less_than(strings []string) bool {\n\tfor i := 1; i < strings.len(); i++ {\n\t\tif !(strings[i - 1] < s) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n", "language": "V-(Vlang)" }, { "code": "Private Function IsEqualOrAscending(myList) As String\nDim i&, boolEqual As Boolean, boolAsc As Boolean\n\n On Error Resume Next\n If UBound(myList) > 0 Then\n If Err.Number > 0 Then\n IsEqualOrAscending = \"Error \" & Err.Number & \" : Empty array\"\n On Error GoTo 0\n Exit Function\n Else\n For i = 1 To UBound(myList)\n If myList(i) <> myList(i - 1) Then boolEqual = True\n If myList(i) <= myList(i - 1) Then boolAsc = True\n Next\n End If\n End If\n IsEqualOrAscending = \"List : \" & Join(myList, \",\") & \", IsEqual : \" & (Not boolEqual) & \", IsAscending : \" & Not boolAsc\nEnd Function\n", "language": "VBA" }, { "code": "Sub Main()\nDim List\n Debug.Print IsEqualOrAscending(Array(\"AA\", \"BB\", \"CC\"))\n Debug.Print IsEqualOrAscending(Array(\"AA\", \"AA\", \"AA\"))\n Debug.Print IsEqualOrAscending(Array(\"AA\", \"CC\", \"BB\"))\n Debug.Print IsEqualOrAscending(Array(\"AA\", \"ACB\", \"BB\", \"CC\"))\n Debug.Print IsEqualOrAscending(Array(\"single_element\"))\n Debug.Print IsEqualOrAscending(Array(\"AA\", \"BB\", \"BB\"))\n 'test with Empty Array :\n Debug.Print IsEqualOrAscending(List)\nEnd Sub\n", "language": "VBA" }, { "code": "Function string_compare(arr)\n\tlexical = \"Pass\"\n\tascending = \"Pass\"\n\tFor i = 0 To UBound(arr)\n\t\tIf i+1 <= UBound(arr) Then\n\t\t\tIf arr(i) <> arr(i+1) Then\n\t\t\t\tlexical = \"Fail\"\n\t\t\tEnd If\n\t\t\tIf arr(i) >= arr(i+1) Then\n\t\t\t\tascending = \"Fail\"\n\t\t\tEnd If\n\t\tEnd If\t\n\tNext\n\tstring_compare = \"List: \" & Join(arr,\",\") & vbCrLf &_\n\t\t\t\t\t \"Lexical Test: \" & lexical & vbCrLf &_\n\t\t\t\t\t \"Ascending Test: \" & ascending & vbCrLf\nEnd Function\n\nWScript.StdOut.WriteLine string_compare(Array(\"AA\",\"BB\",\"CC\"))\nWScript.StdOut.WriteLine string_compare(Array(\"AA\",\"AA\",\"AA\"))\nWScript.StdOut.WriteLine string_compare(Array(\"AA\",\"CC\",\"BB\"))\nWScript.StdOut.WriteLine string_compare(Array(\"AA\",\"ACB\",\"BB\",\"CC\"))\nWScript.StdOut.WriteLine string_compare(Array(\"FF\"))\n", "language": "VBScript" }, { "code": "import \"./sort\" for Sort\n\nvar areEqual = Fn.new { |strings|\n if (strings.count < 2) return true\n return (1...strings.count).all { |i| strings[i] == strings[i-1] }\n}\n\nvar areAscending = Fn.new { |strings| Sort.isSorted(strings) }\n\nvar a = [\"a\", \"a\", \"a\"]\nvar b = [\"a\", \"b\", \"c\"]\nvar c = [\"a\", \"a\", \"b\"]\nvar d = [\"a\", \"d\", \"c\"]\nSystem.print(\"%(a) are all equal : %(areEqual.call(a))\")\nSystem.print(\"%(b) are ascending : %(areAscending.call(b))\")\nSystem.print(\"%(c) are all equal : %(areEqual.call(c))\")\nSystem.print(\"%(d) are ascending : %(areAscending.call(d))\")\n", "language": "Wren" }, { "code": "include xpllib; \\For StrCmp\n\nfunc AreAllEqual(Strings, Size);\nint Strings, Size, I;\n[for I:= 1 to Size-1 do\n if StrCmp(Strings(I), Strings(0)) # 0 then return false;\nreturn true;\n];\n\nfunc AreAscending(Strings, Size;\nint Strings, Size, I;\n[for I:= 1 to Size-1 do\n if StrCmp(Strings(I-1), Strings(I)) >= 0 then return false;\nreturn true;\n];\n\nint A, B, C, D;\n[A:= [\"a\", \"a\", \"a\"];\n B:= [\"a\", \"b\", \"c\"];\n C:= [\"a\", \"a\", \"b\"];\n D:= [\"a\", \"d\", \"c\"];\nText(0, if AreAllEqual (A, 3) then \"true\" else \"false\"); CrLf(0);\nText(0, if AreAscending(B, 3) then \"true\" else \"false\"); CrLf(0);\nText(0, if AreAllEqual (C, 3) then \"true\" else \"false\"); CrLf(0);\nText(0, if AreAscending(D, 3) then \"true\" else \"false\"); CrLf(0);\n]\n", "language": "XPL0" }, { "code": "Proc allsame\n Parameters long liste\n var int result = 1\n var int cnt = GetCount(liste)\n Case cnt == 0 : Return 0\n Case cnt == 1 : Return 1\n WhileLoop 1, cnt-1\n If GetString$(liste,&loop - 1) <> GetString$(liste,&loop)\n result = 0\n BREAK\n EndIf\n EndWhile\n Return result\nEndProc\n\nProc strict_order\n Parameters long liste\n var int result = 1\n var int cnt = GetCount(liste)\n Case cnt == 0 : Return 0\n Case cnt == 1 : Return 1\n WhileLoop 1, cnt-1\n If GetString$(liste,&loop) <= GetString$(liste,&loop - 1)\n result = 0\n BREAK\n EndIf\n EndWhile\n Return result\nEndProc\n\ncls\ndeclare string s[4]\ns[0] = \"AA,BB,CC\"\ns[1] = \"AA,AA,AA\"\ns[2] = \"AA,CC,BB\"\ns[3] = \"AA,ACB,BB,CC\"\ns[4] = \"single_element\"\n\nWhileLoop 0,4\n ClearList 0\n Move(\"StrToList\",s[&loop],\",\")\n Print \"list:\",s[&loop]\n Print \"...is \" + if(allsame(0), \"\", \"not \") + \"lexically equal\"\n Print \"...is \" + if(strict_order(0), \"\", \"not \") + \"in strict ascending order\"\nEndWhile\n\nClearList 0\nWaitKey\nend\n", "language": "XProfan" }, { "code": "fcn allEQ(strings){ (not strings.filter1('!=(strings[0]))) }\nfcn monoUp(strings){\n strings.len()<2 or\n strings.reduce(fcn(a,b){ if(a>=b) return(Void.Stop,False); b }).toBool()\n}\n", "language": "Zkl" }, { "code": "allEQ(T(\"AA\")).println(); //True\nallEQ(T(\"AA\",\"AA\",\"AA\",\"AA\")).println(); //True\nallEQ(T(\"A\", \"AA\",\"AA\",\"AA\")).println(); //False\n\nmonoUp(T(\"a\")).println(); //True\nmonoUp(T(\"a\",\"aa\",\"aaa\",\"aaaa\")).println(); //True\nmonoUp(T(\"a\",\"aa\",\"aaa\",\"aaa\")).println(); //False\nmonoUp(T(\"a\",\"b\",\"c\",\"cc\")).println(); //True\n", "language": "Zkl" }, { "code": "module CompareStrings;\ntype\n\tVector = array * of string;\nvar\n\tv,w: Vector;\n\ti: integer;\n\tall,ascending: boolean;\nbegin\n\tv := new Vector(3);\n\tv[0] := \"uno\";\n\tv[1] := \"uno\";\n\tv[2] := \"uno\";\n\n\tall := true;\n\tfor i := 1 to len(v) - 1 do\n\t\tall := all & (v[i - 1] = v[i]);\n\tend;\n\n\tw := new Vector(3);\n\tw[0] := \"abc\";\n\tw[1] := \"bcd\";\n\tw[2] := \"cde\";\n\tv := w;\n\tascending := true;\n\tfor i := 1 to len(v) - 1 do\n\t\tascending := ascending & (v[i - 1] <= v[i])\n\tend;\n\n\twrite(\"all equals?: \");writeln(all);\n\twrite(\"ascending?: \");writeln(ascending)\nend CompareStrings.\n", "language": "Zonnon" }, { "code": "10 FOR j=160 TO 200 STEP 10\n20 RESTORE j\n30 READ n\n40 LET test1=1: LET test2=1\n50 FOR i=1 TO n\n60 READ a$\n70 PRINT a$;\" \";\n80 IF i=1 THEN GO TO 110\n90 IF p$<>a$ THEN LET test1=0\n100 IF p$>=a$ THEN LET test2=0\n110 LET p$=a$\n120 NEXT i\n130 PRINT 'test1'test2\n140 NEXT j\n150 STOP\n160 DATA 3,\"AA\",\"BB\",\"CC\"\n170 DATA 3,\"AA\",\"AA\",\"AA\"\n180 DATA 3,\"AA\",\"CC\",\"BB\"\n190 DATA 4,\"AA\",\"ACB\",\"BB\",\"CC\"\n200 DATA 1,\"single_element\"\n", "language": "ZX-Spectrum-Basic" } ]
Compare-a-list-of-strings
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Compare_length_of_two_strings\nnote: String manipulation\n", "language": "00-META" }, { "code": "{{basic data operation}}\n[[Category: String manipulation]]\n[[Category:Simple]]\n\n;Task:\nGiven two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first.\n\nMeasure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it.\n\n;Extra credit:\nGiven more than two strings:\n<br>list = [\"abcd\",\"123456789\",\"abcdef\",\"1234567\"]\n<br>Show the strings in descending length order.\n{{Strings}}\n<br><br>\n", "language": "00-TASK" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program complength64.s */\n\n/************************************/\n/* Constantes */\n/************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeConstantesARM64.inc\"\n\n/************************************/\n/* structures */\n/************************************/\n .struct 0\nlist_string: // string address\n .struct list_string + 8\nlist_length: // string length\n .struct list_length + 8\nlist_end:\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessResult: .asciz \"@ length : @\\n\"\nszCarriageReturn: .asciz \"\\n\"\nszLibSort: .asciz \"\\nAfter sort\\n\"\nszString1: .asciz \"abcd\"\nszString2: .asciz \"123456789\"\nszString3: .asciz \"abcdef\"\nszString4: .asciz \"1234567\"\n\n.align 4\ntabStrings: .quad szString1 // string address array\n .quad 0\n .quad szString2\n .quad 0\n .quad szString3\n .quad 0\n .quad szString4\n .quad 0\n.equ NBTABSTRINGS, (. - tabStrings) / list_end // compute items number\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\nsZoneConv: .skip 24\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: // entry of program\n ldr x4,qAdrtabStrings // string array address\n mov x5,#0 // indice\n mov x6,#list_end // structure size\n1: // item loop\n madd x3,x5,x6,x4 // compute item address\n ldr x0,[x3,#list_string] // load string address\n bl stringRoutine // length string compute\n str x0,[x3,#list_length] // store result in array\n add x5,x5,#1 // increment indice\n cmp x5,#NBTABSTRINGS // end ?\n blt 1b // no -> loop\n\n mov x0,x4 // string array address\n mov x1,#0 // first item\n mov x2,#NBTABSTRINGS // item number\n bl insertionSort // sort\n\n ldr x0,qAdrszLibSort\n bl affichageMess\n mov x0,x4 // string array address\n mov x5,#0 // indice\n mov x6,#list_end\n2: // item loop\n madd x3,x5,x6,x4\n ldr x0,[x3,#list_string]\n bl stringRoutine // use same routine for display result after sort\n add x5,x5,#1\n cmp x5,#NBTABSTRINGS // end ?\n blt 2b // no -> loop\n\n100: // standard end of the program\n mov x0, #0 // return code\n mov x8,EXIT\n svc #0 // perform the system call\n\nqAdrszCarriageReturn: .quad szCarriageReturn\nqAdrszMessResult: .quad szMessResult\nqAdrsZoneConv: .quad sZoneConv\nqAdrtabStrings: .quad tabStrings\nqAdrszLibSort: .quad szLibSort\n/***************************************************/\n/* string exec */\n/***************************************************/\n// x0 contains string address\n// x0 return length\nstringRoutine:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n mov x3,x0 // save string address\n mov x1,x0\n ldr x0,qAdrszMessResult\n bl strInsertAtCharInc // insert string in result message\n mov x2,x0 // save new message address\n mov x0,x3 // restaur string address\n bl stringlength // compute length\n mov x3,x0\n ldr x1,qAdrsZoneConv\n bl conversion10 // call decimal conversion\n mov x0,x2\n ldr x1,qAdrsZoneConv // insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess // display result message\n mov x0,x3\n100:\n ldp x2,x3,[sp],16 // restaur registers\n ldp x1,lr,[sp],16 // restaur registers\n ret\n/***************************************************/\n/* compute string length */\n/***************************************************/\n// x0 contains string address\nstringlength:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n mov x1,#-1 // init counter\n1: // loop\n add x1,x1,#1 // increment counter\n ldrb w2,[x0,x1] // load byte string\n cmp w2,#0 // zero final ?\n bne 1b // no -> loop\n mov x0,x1 // return length\n100:\n ldp x2,x3,[sp],16 // restaur registers\n ldp x1,lr,[sp],16 // restaur registers\n ret\n\n/******************************************************************/\n/* insertion sort */\n/******************************************************************/\n/* x0 contains the address of table */\n/* x1 contains the first element */\n/* x2 contains the number of element */\ninsertionSort:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n stp x4,x5,[sp,-16]! // save registers\n stp x6,x7,[sp,-16]! // save registers\n stp x8,x9,[sp,-16]! // save registers\n stp x10,x11,[sp,-16]! // save registers\n mov x6,x0\n mov x7,#list_end\n add x3,x1,#1 // start index i\n1: // start loop\n madd x8,x7,x3,x6\n ldr x10,[x8,#list_length] // load value A[i]\n ldr x0,[x8,#list_string] // load string address A[i]\n sub x5,x3,#1 // index j\n2:\n madd x9,x7,x5,x6\n ldr x4,[x9,#list_length] // load value A[j]\n cmp x4,x10 // compare value\n bge 3f\n add x5,x5,#1 // increment index j\n madd x8,x7,x5,x6\n str x4,[x8,#list_length] // store value A[j+1]\n ldr x4,[x9,#list_string] // load string address\n str x4,[x8,#list_string] // store string address\n subs x5,x5,#2 // j = i - 1\n cmp x5,x1 // compare with first item\n bge 2b // loop if j >= first item\n3:\n add x5,x5,#1 // increment index j\n madd x9,x7,x5,x6\n str x10,[x9,#list_length] // store value A[i] in A[j+1]\n str x0,[x9,#list_string] // and store string address\n add x3,x3,#1 // increment index i\n cmp x3,x2 // end ?\n blt 1b // no -> loop\n\n100:\n ldp x10,x11,[sp],16 // restaur registers\n ldp x8,x9,[sp],16 // restaur registers\n ldp x6,x7,[sp],16 // restaur registers\n ldp x4,x5,[sp],16 // restaur registers\n ldp x2,x3,[sp],16 // restaur registers\n ldp x1,lr,[sp],16 // restaur registers\n ret\n\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "with ada.command_line, ada.containers.indefinite_vectors, ada.text_io;\nprocedure compare_lengths is\n package string_vector is new ada.containers.indefinite_vectors\n (index_type => Positive, element_type => String);\n\n function \"<\" (left, right : String) return Boolean is\n begin\n return left'length > right'length;\n end \"<\";\n\n package string_vector_sorting is new string_vector.generic_sorting;\n list : string_vector.Vector;\nbegin\n for i in 1 .. ada.command_line.argument_count loop\n list.append (ada.command_line.argument (i));\n end loop;\n string_vector_sorting.sort (list);\n for elem of list loop\n ada.text_io.put_line (elem'length'image & \": \" & elem);\n end loop;\nend compare_lengths;\n", "language": "Ada" }, { "code": "BEGIN # compare string lengths #\n # returns the length of s using the builtin UPB and LWB operators #\n OP LENGTH = ( STRING s )INT: ( UPB s + 1 ) - LWB s;\n # prints s and its length #\n PROC print string = ( STRING s )VOID:\n print( ( \"\"\"\", s, \"\"\" has length: \", whole( LENGTH s, 0 ), \" bytes.\", newline ) );\n STRING shorter = \"short\";\n STRING not shorter = \"longer\";\n IF LENGTH shorter > LENGTH not shorter THEN print string( shorter ) FI;\n print string( not shorter );\n IF LENGTH shorter <= LENGTH not shorter THEN print string( shorter ) FI\nEND\n", "language": "ALGOL-68" }, { "code": " sv ← 'defg' 'hijklm' 'abc' 'abcd'\n ⍉(⍴¨sv[⍒sv]),[0.5]sv[⍒sv]\n 6 hijklm\n 4 defg\n 4 abcd\n 3 abc\n", "language": "APL" }, { "code": "/* ARM assembly Raspberry PI or android 32 bits */\n/* program complength.s */\n\n/* REMARK 1 : this program use routines in a include file\n see task Include a file language arm assembly\n for the routine affichageMess conversion10\n see at end of this program the instruction include */\n\n/* for constantes see task include a file in arm assembly */\n/************************************/\n/* Constantes */\n/************************************/\n.include \"../constantes.inc\"\n/************************************/\n/* structures */\n/************************************/\n .struct 0\nlist_string: @ string address\n .struct list_string + 4\nlist_length: @ string length\n .struct list_length + 4\nlist_end:\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessResult: .asciz \"@ length : @\\n\"\nszCarriageReturn: .asciz \"\\n\"\nszLibSort: .asciz \"\\nAfter sort\\n\"\nszString1: .asciz \"abcd\"\nszString2: .asciz \"123456789\"\nszString3: .asciz \"abcdef\"\nszString4: .asciz \"1234567\"\n\n.align 4\ntabStrings: .int szString1 @ string address array\n .int 0\n .int szString2\n .int 0\n .int szString3\n .int 0\n .int szString4\n .int 0\n.equ NBTABSTRINGS, (. - tabStrings) / list_end @ compute items number\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\nsZoneConv: .skip 24\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: @ entry of program\n ldr r4,iAdrtabStrings @ string array address\n mov r5,#0 @ indice\n mov r6,#list_end @ structure size\n1: @ item loop\n mla r3,r5,r6,r4 @ compute item address\n ldr r0,[r3,#list_string] @ load string address\n bl stringRoutine @ length string compute\n str r0,[r3,#list_length] @ store result in array\n add r5,#1 @ increment indice\n cmp r5,#NBTABSTRINGS @ end ?\n blt 1b @ no -> loop\n\n mov r0,r4 @ string array address\n mov r1,#0 @ first item\n mov r2,#NBTABSTRINGS @ item number\n bl insertionSort @ sort\n\n ldr r0,iAdrszLibSort\n bl affichageMess\n mov r0,r4 @ string array address\n mov r5,#0 @ indice\n mov r6,#list_end\n2: @ item loop\n mla r3,r5,r6,r4\n ldr r0,[r3,#list_string]\n bl stringRoutine @ use same routine for display result after sort\n add r5,#1\n cmp r5,#NBTABSTRINGS @ end ?\n blt 2b @ no -> loop\n\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrszCarriageReturn: .int szCarriageReturn\niAdrszMessResult: .int szMessResult\niAdrsZoneConv: .int sZoneConv\niAdrtabStrings: .int tabStrings\niAdrszLibSort: .int szLibSort\n/***************************************************/\n/* string exec */\n/***************************************************/\n// r0 contains string address\n// r0 return length\nstringRoutine:\n push {r1-r3,lr} @ save registers\n mov r3,r0 @ save string address\n mov r1,r0\n ldr r0,iAdrszMessResult\n bl strInsertAtCharInc @ insert string in result message\n mov r2,r0 @ save new message address\n mov r0,r3 @ restaur string address\n bl stringlength @ compute length\n mov r3,r0\n ldr r1,iAdrsZoneConv\n bl conversion10 @ call decimal conversion\n mov r0,r2\n ldr r1,iAdrsZoneConv @ insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess @ display result message\n mov r0,r3\n100:\n pop {r1-r3,pc} @ restaur registers\n/***************************************************/\n/* compute string length */\n/***************************************************/\n// r0 contains string address\nstringlength:\n push {r1-r2,lr} @ save registers\n mov r1,#-1 @ init counter\n1: @ loop\n add r1,#1 @ increment counter\n ldrb r2,[r0,r1] @ load byte string\n cmp r2,#0 @ zero final ?\n bne 1b @ no -> loop\n mov r0,r1 @ return length\n100:\n pop {r1-r2,pc} @ restaur registers\n/******************************************************************/\n/* insertion sort */\n/******************************************************************/\n/* r0 contains the address of table */\n/* r1 contains the first element */\n/* r2 contains the number of element */\ninsertionSort:\n push {r1-r10,lr} @ save registers\n mov r6,r0\n mov r7,#list_end\n add r3,r1,#1 @ start index i\n1: @ start loop\n mla r8,r7,r3,r6\n ldr r10,[r8,#list_length] @ load value A[i]\n ldr r0,[r8,#list_string] @ load string address A[i]\n sub r5,r3,#1 @ index j\n2:\n mla r9,r7,r5,r6\n ldr r4,[r9,#list_length] @ load value A[j]\n cmp r4,r10 @ compare value\n bge 3f\n add r5,#1 @ increment index j\n mla r8,r7,r5,r6\n str r4,[r8,#list_length] @ store value A[j+1]\n ldr r4,[r9,#list_string] @ load string address\n str r4,[r8,#list_string] @ store string address\n subs r5,#2 @ j = i - 1\n cmp r5,r1 @ compare with first item\n bge 2b @ loop if j >= first item\n3:\n add r5,#1 @ increment index j\n mla r9,r7,r5,r6\n str r10,[r9,#list_length] @ store value A[i] in A[j+1]\n str r0,[r9,#list_string] @ and store string address\n add r3,#1 @ increment index i\n cmp r3,r2 @ end ?\n blt 1b @ no -> loop\n\n100:\n pop {r1-r10,lr}\n bx lr\n\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n.include \"../affichage.inc\"\n", "language": "ARM-Assembly" }, { "code": "sortByLength: function [strs][\n map sort.descending.by:'v\n map strs 'str -> #[s: str, v: size str]\n 'z -> z\\s\n]\n\nA: \"I am string\"\nB: \"I am string too\"\n\nsA: size A\nsB: size B\n\nif? sA < sB ->\n print [\"string ->\" A \"(\" sA \") is smaller than string ->\" B \"(\" sB \")\"]\nelse [\n if? sA > sB ->\n print [\"string ->\" A \"(\" sA \") is larger than string ->\" B \"(\" sB \")\"]\n else ->\n print [\"string ->\" A \"(\" sA \") and string ->\" B \"(\" sB \") are of equal length\"]\n]\n\nprint [\"sorted strings (by length):\" sortByLength [\"abcd\" \"123456789\" \"abcdef\" \"1234567\"]]\n", "language": "Arturo" }, { "code": "string A, B, t = '\\t';\n\nvoid comp(string A, string B) {\n if (length(A) >= length(B)) {\n write(A+t, length(A));\n write(B+t, length(B));\n } else {\n write(B+t, length(B));\n write(A+t, length(A));\n }\n}\n\ncomp(\"abcd\", \"123456789\");\n", "language": "Asymptote" }, { "code": "list := [\"abcd\",\"123456789\",\"abcdef\",\"1234567\"]\n\nsorted := []\nfor i, s in list\n sorted[0-StrLen(s), s] := s\nfor l, obj in sorted\n{\n i := A_Index\n for s, v in obj\n {\n if (i = 1)\n result .= \"\"\"\" s \"\"\" has length \" 0-l \" and is the longest string.`n\"\n else if (i < sorted.Count())\n result .= \"\"\"\"s \"\"\" has length \" 0-l \" and is neither the longest nor the shortest string.`n\"\n else\n result .= \"\"\"\"s \"\"\" has length \" 0-l \" and is the shorted string.`n\"\n }\n}\nMsgBox % result\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f COMPARE_LENGTH_OF_TWO_STRINGS.AWK\nBEGIN {\n main(\"abcd\",\"123456789\")\n main(\"longer\",\"short\")\n main(\"hello\",\"world\")\n exit(0)\n}\nfunction main(Sa,Sb, La,Lb) {\n La = length(Sa)\n Lb = length(Sb)\n if (La > Lb) {\n printf(\"a>b\\n%3d %s\\n%3d %s\\n\\n\",La,Sa,Lb,Sb)\n }\n else if (La < Lb) {\n printf(\"a<b\\n%3d %s\\n%3d %s\\n\\n\",Lb,Sb,La,Sa)\n }\n else {\n printf(\"a=b\\n%3d %s\\n%3d %s\\n\\n\",Lb,Sb,La,Sa)\n }\n}\n", "language": "AWK" }, { "code": "subroutine comp(A$, B$)\n if length(A$) >= length(B$) then\n print A$, length(A$)\n print B$, length(B$)\n else\n print B$, length(B$)\n print A$, length(A$)\n end if\nend subroutine\n\ncall comp(\"abcd\", \"123456789\")\n", "language": "BASIC256" }, { "code": "Compare ← >·(⍒⊑¨)⊸⊏≠⊸⋈¨\n\n•Show Compare ⟨\"hello\", \"person\"⟩\n•Show Compare ⟨\"abcd\", \"123456789\", \"abcdef\", \"1234567\"⟩\n", "language": "BQN" }, { "code": "┌─\n╵ 6 \"person\"\n 5 \"hello\"\n ┘\n┌─\n╵ 9 \"123456789\"\n 7 \"1234567\"\n 6 \"abcdef\"\n 4 \"abcd\"\n ┘\n", "language": "BQN" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint cmp(const int* a, const int* b)\n{\n return *b - *a; // reverse sort!\n}\n\nvoid compareAndReportStringsLength(const char* strings[], const int n)\n{\n if (n > 0)\n {\n char* has_length = \"has length\";\n char* predicate_max = \"and is the longest string\";\n char* predicate_min = \"and is the shortest string\";\n char* predicate_ave = \"and is neither the longest nor the shortest string\";\n\n int* si = malloc(2 * n * sizeof(int));\n if (si != NULL)\n {\n for (int i = 0; i < n; i++)\n {\n si[2 * i] = strlen(strings[i]);\n si[2 * i + 1] = i;\n }\n qsort(si, n, 2 * sizeof(int), cmp);\n\n int max = si[0];\n int min = si[2 * (n - 1)];\n\n for (int i = 0; i < n; i++)\n {\n int length = si[2 * i];\n char* string = strings[si[2 * i + 1]];\n char* predicate;\n if (length == max)\n predicate = predicate_max;\n else if (length == min)\n predicate = predicate_min;\n else\n predicate = predicate_ave;\n printf(\"\\\"%s\\\" %s %d %s\\n\",\n string, has_length, length, predicate);\n }\n\n free(si);\n }\n else\n {\n fputs(\"unable allocate memory buffer\", stderr);\n }\n }\n}\n\nint main(int argc, char* argv[])\n{\n char* list[] = { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n\n compareAndReportStringsLength(list, 4);\n\n return EXIT_SUCCESS;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <list>\n\nusing namespace std;\n\nbool cmp(const string& a, const string& b)\n{\n return b.length() < a.length(); // reverse sort!\n}\n\nvoid compareAndReportStringsLength(list<string> listOfStrings)\n{\n if (!listOfStrings.empty())\n {\n char Q = '\"';\n string has_length(\" has length \");\n string predicate_max(\" and is the longest string\");\n string predicate_min(\" and is the shortest string\");\n string predicate_ave(\" and is neither the longest nor the shortest string\");\n\n list<string> ls(listOfStrings); // clone to avoid side-effects\n ls.sort(cmp);\n int max = ls.front().length();\n int min = ls.back().length();\n\n for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)\n {\n int length = s->length();\n string* predicate;\n if (length == max)\n predicate = &predicate_max;\n else if (length == min)\n predicate = &predicate_min;\n else\n predicate = &predicate_ave;\n\n cout << Q << *s << Q << has_length << length << *predicate << endl;\n }\n }\n}\n\nint main(int argc, char* argv[])\n{\n list<string> listOfStrings{ \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n compareAndReportStringsLength(listOfStrings);\n\n return EXIT_SUCCESS;\n}\n", "language": "C++" }, { "code": "void WriteSorted(string[] strings)\n{\n\tvar sorted = strings.OrderByDescending(x => x.Length);\n\tforeach(var s in sorted) Console.WriteLine($\"{s.Length}: {s}\");\n}\nWriteSorted(new string[] { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" });\n", "language": "C-sharp" }, { "code": "bundle agent __main__\n{\n vars:\n \"strings\" slist => { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n\n \"sorted[$(with)]\"\n string => \"$(strings)\",\n with => string_length( \"$(strings)\" );\n\n \"sort_idx\" slist => reverse( sort( getindices( \"sorted\" ), lex ) );\n\n reports:\n \"'$(sorted[$(sort_idx)])' is $(sort_idx) characters in length.\";\n}\n", "language": "CFEngine" }, { "code": "0 REM ROSETTACODE.ORG\n1 REM COMPARE LENGTH OF TWO STRINGS\n2 REM GIVEN TWO STRINGS OF DIFFERENT\n3 REM LENGTH, DETERMINE WHICH STRING IS\n4 REM LONGER OR SHORTER.\n5 REM PRINT BOTH STRINGS AND THEIR\n6 REM LENGTH, ONE ON EACH LINE. PRINT\n7 REM THE LONGER ONE FIRST.\n8 REM\n9 REM ********************************\n10 REM\n20 REM PRINT CHR$(14): REM CHANGE TO LOWER/UPPER CASE CHAR SET\n30 GOSUB 200: REM 1 - COMPARE LENGTH OF 2 STRINGS\n40 GOSUB 300: REM 2- MORE THAN 2 STRINGS\n50 END\n200 PRINT\"*** (1) TWO STRINGS ***\"\n210 A$ = \"SHORT STRING\"\n220 B$ = \"LONGER STRING\"\n230 A = LEN(A$)\n240 B = LEN(B$)\n250 IF A>B THEN PRINT A$;\" (\";A;\")\": PRINT B$;\" (\";B;\")\"\n260 IF A<=B THEN PRINT B$;\" (\";B;\")\": PRINT A$;\" (\";A;\")\"\n270 PRINT: PRINT\n280 RETURN\n300 PRINT\"*** (2) MORE THAN 2 STRINGS***\"\n310 DIM C$(100)\n320 N = 0\n330 READ A$\n340 IF A$ = \"$$$\" THEN 400\n350 N = N+1\n360 C$(N) = A$\n370 IF N = 100 THEN 400\n380 GOTO 330\n390 REM SORT THE STRINGS\n400 FOR J=1 TO N-1\n410 FOR I=1 TO N-J\n420 IF LEN(C$(I)) < LEN(C$(I+1)) THEN A$=C$(I): C$(I)=C$(I+1): C$(I+1)=A$\n430 NEXT\n440 NEXT\n450 REM PRINT OUT THE STRINGS\n460 FOR I=1 TO N\n470 PRINT C$(I);\" (\";LEN(C$(I));\")\"\n480 NEXT\n490 PRINT: PRINT\n500 RETURN\n1000 DATA \"DOES SHE LIVE IN PARIS?\"\n1010 DATA \"HE DOESN'T TEACH MATH\"\n1020 DATA \"CATS HATE WATER\"\n1030 DATA \"SHE DOESN'T STUDY GERMAN ON MONDAY\"\n1040 DATA \"EVERY CHILD LIKES AN ICE CREAM\"\n1050 DATA \"THE EARTH IS SPHERICAL\"\n1060 DATA \"THE COURSE STARTS NEXT SUNDAY\"\n1070 DATA \"SHE SWIMS EVERY MORNING\"\n1080 DATA \"I LIKE TEA\"\n1090 DATA \"WE SEE THEM EVERY WEEK\"\n1100 DATA \"$$$\"\n", "language": "Commodore-BASIC" }, { "code": "(defun sort-and-print-strings (strings)\n (dolist (s (sort (copy-list strings) #'> :key #'length))\n (format t \"~A ~A~%\" (length s) s)))\n\n(sort-and-print-strings '(\"Lisp\" \"stands\" \"for\" \"List\" \"Processing\"))\n", "language": "Common-Lisp" }, { "code": "var SA1: array [0..1] of string = ('Very Long String','short string');\nvar SA2: array [0..11] of string = ('Like','sands','through','the','hourglass',\n\t\t\t\t 'these','are','the','days','of','our','lives');\n\nfunction Compare(P1,P2: pointer): integer;\n{Compare for quick sort}\nbegin\nResult:=Length(PString(P2)^)-Length(PString(P1)^);\nend;\n\n\nprocedure ShowStringLengths(SA: array of string; Memo: TMemo);\n{Sort strings by length and display string and length}\nvar List: TList;\nvar I: integer;\nvar S: string;\nbegin\nList:=TList.Create;\ntry\nfor I:=0 to High(SA) do\n List.Add(@SA[I]);\nList.Sort(Compare);\nfor I:=0 to List.Count-1 do\n\tbegin\n\tS:=PString(List[I])^;\n\tMemo.Lines.Add(IntToStr(Length(S))+': '+S);\n\tend;\nfinally List.Free; end;\nend;\n\n\nprocedure SortedStringLists(Memo: TMemo);\n{Test two different string arrays}\nbegin\nMemo.Lines.Add('Two word test: ');\nMemo.Lines.Add('');\nShowStringLengths(SA1,Memo);\nMemo.Lines.Add('');\nMemo.Lines.Add('Twelve word test: ');\nMemo.Lines.Add('');\nShowStringLengths(SA2,Memo);\nend;\n", "language": "Delphi" }, { "code": "proc scmp a$ b$ . .\n if len a$ < len b$\n swap a$ b$\n .\n print a$ & \" - \" & len a$\n print b$ & \" - \" & len b$\n print \"\"\n.\nscmp \"Easy\" \"Language\"\nscmp \"Rosetta\" \"Code\"\n", "language": "EasyLang" }, { "code": "List list = text[\"abcd\",\"123456789\",\"abcdef\",\"1234567\", \"Привет, мир\"]\n^|this solves the task doing the comparison by using the diamond operator|^\nfun comparator = int by text a, text b do return b.length <> a.length end\nList sorted = list.sort(comparator)\nwriteLine(\"text\".padEnd(15, \" \") + \"units\".padStart(6, \" \") + \"bytes\".padStart(6, \" \"))\nfor each text value in sorted\n writeLine(value.padEnd(15, \" \") +\n (text!value.length).padStart(6, \" \") +\n\t^|conversion from text to blob uses utf8 encoding|^\n (text!(blob!value).length).padStart(6, \" \"))\nend\n", "language": "EMal" }, { "code": "USING: formatting io kernel qw sequences sorting ;\n\n: .length ( str -- ) dup length \"%u has length %d\\n\" printf ;\n\n\"I am a string\" \"I am a string too\"\n[ longer .length ] [ shorter .length ] 2bi nl\n\nqw{ abcd 123456789 abcdef 1234567 } dup [ length ] inv-sort-with\n\"%u sorted by descending length:\\n%u\\n\" printf\n", "language": "Factor" }, { "code": ": say dup . .\" : \" type ;\n: comp-strings\n 2 pick over\n > if 2swap then\n cr say cr say cr\n;\n", "language": "Forth" }, { "code": "program demo_sort_indexed\nimplicit none\n\n call print_sorted_by_length( [character(len=20) :: \"shorter\",\"longer\"] )\n call print_sorted_by_length( [character(len=20) :: \"abcd\",\"123456789\",\"abcdef\",\"1234567\"] )\n call print_sorted_by_length( [character(len=20) :: 'the','quick','brown','fox','jumps','over','the','lazy','dog'])\n\ncontains\n\nsubroutine print_sorted_by_length(list)\ncharacter(len=*) :: list(:)\ninteger :: i\n\n list(sort_int(len_trim(list)))=list ! sort by length from small to large\n write(*,'(i9,1x,a)')(len_trim(list(i)), list(i),i=size(list),1,-1)! print from last to first\n write(*,*)\n\nend subroutine print_sorted_by_length\n\nfunction sort_int(input) result(counts) ! **very** inefficient mini index sort\ninteger :: input(:), counts(size(input)), i\n counts=[(count(input(i) > input)+count(input(i) == input(:i)),i=1, size(input) )]\nend function sort_int\n\nend program demo_sort_indexed\n", "language": "Fortran" }, { "code": "sub comp( A as string, B as string )\n if len(A)>=len(B) then\n print A, len(A)\n print B, len(B)\n else\n print B, len(B)\n print A, len(A)\n end if\nend sub\n\ncomp( \"abcd\", \"123456789\" )\n", "language": "FreeBASIC" }, { "code": "local fn MyArraySortFunction( obj1 as CFTypeRef, obj2 as CFTypeRef, context as ptr ) as NSComparisonResult\n NSComparisonResult result = NSOrderedDescending\n if len(obj1) >= len(obj2) then result = NSOrderedAscending\nend fn = result\n\nvoid local fn DoIt\n CFStringRef string1 = @\"abcd\", string2 = @\"abcdef\", s\n\n if len(string1) >= len(string2)\n print string1,len(string1)\n print string2,len(string2)\n else\n print string2,len(string2)\n print string1,len(string1)\n end if\n\n print\n text ,,,,, 85\n\n CFArrayRef strings = @[@\"abcd\",@\"123456789\",@\"abcdef\",@\"1234567\"]\n strings = fn ArraySortedArrayUsingFunction( strings, @fn MyArraySortFunction, NULL )\n for s in strings\n print s,len(s)\n next\nend fn\n\nwindow 1\n\nfn DoIt\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\n\n Compare(\"abcd\", \"123456789\")\n\nEnd\n\nSub Compare(A As String, B As String)\n\n If Len(A) >= Len(B) Then\n Print A, Len(A)\n Print B, Len(B)\n Else\n Print B, Len(B)\n Print A, Len(A)\n End If\n\nEnd Sub\n", "language": "Gambas" }, { "code": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t// If no command-line arguments are specified when running the program, use example data\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t// First argument, os.Args[0], is program name. Command-line arguments start from 1\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n// Variadic function that takes any number of string arguments for comparison\nfunc compareStrings(strings ...string) {\n\t// \"strings\" slice is sorted in place\n\t// sort.SliceStable keeps strings in their original order when elements are of equal length (unlike sort.Slice)\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n", "language": "Go" }, { "code": "comparisonFunction := func(i, j int) bool {\n\treturn len(strings[i]) > len(strings[j])\n}\n\nsort.SliceStable(strings, comparisonFunction)\n", "language": "Go" }, { "code": "10 'SAVE \"SSTRING\",A\n20 ' Length of a group of strings\n30 OPTION BASE 1\n40 DIM SSTRING$(10)\n50 I=0: J=1\n60 ' Begin of program cycle\n70 CLS\n80 PRINT \"This program shows the length of up to 10 captured strings.\"\n90 PRINT \"Enter an empty string to finish anytime.\"\n100 PRINT\n110 ' Do\n120 PRINT \"Capture the string\";STR$(J);\": \";\n130 INPUT \"\", SSTRING$(J)\n140 IF SSTRING$(J)=\"\" THEN 180 ' Exit Do\n150 IF J>1 THEN GOSUB 280 ' Autosort\n160 J = J + 1\n170 IF J < 11 THEN 110 ' Loop\n180 ' Show results\n190 CLS\n200 J = J - 1\n210 IF J<1 THEN PRINT \"You entered no strings.\": GOTO 260\n220 PRINT \"You entered\";J;\"strings. Lengths are as follows:\"\n230 FOR I=1 TO J\n240 PRINT USING \"##. &: ## chars.\"; I;SSTRING$(I);LEN(SSTRING$(I))\n250 NEXT I\n260 PRINT: PRINT \"End of program execution.\"\n270 END\n280 ' Autosort subroutine\n290 I=J\n300 WHILE I>1\n310 IF LEN(SSTRING$(I)) > LEN(SSTRING$(I-1)) THEN SWAP SSTRING$(I), SSTRING$(I-1)\n320 I=I-1\n330 WEND\n340 RETURN\n", "language": "GW-BASIC" }, { "code": "PROCEDURE Main()\n\tLOCAL s1 := \"The long string\"\n\tLOCAL s2 := \"The short string\"\n\tLOCAL a := { s1, s2 }\n\tLOCAL s3\n\n\t? s3 := \"Here is how you can print the longer string first using Harbour language\"\n\t?\n\t? \"-------------------------------------------\"\n\tPrintTheLongerFirst( a )\n\t\n\ta := hb_ATokens( s3, \" \" )\n\t? \"-------------------------------------------\"\n\tPrintTheLongerFirst( a )\n\t? \"-------------------------------------------\"\t\n\tRETURN\n\nFUNCTION PrintTheLongerFirst( a )\n\tLOCAL n, tmp\n\ta := ASort( a,,, {|x,y| Len(x) > Len(y) } )\n\tn:= Len( a[1] )\n\tAEval( a, { |e| tmp := n-Len(e), Qout( e, Space(tmp) + ;\n\t hb_strFormat( \"(length = %d chars)\", Len(e) ) ) } )\n\tRETURN NIL\n", "language": "Harbour" }, { "code": "task s1 s2 = do\n let strs = if length s1 > length s2 then [s1, s2] else [s2, s1]\n mapM_ (\\s -> putStrLn $ show (length s) ++ \"\\t\" ++ show s) strs\n", "language": "Haskell" }, { "code": "import qualified Data.Text as T\n\ntaskT s1 s2 = do\n let strs = if T.length s1 > T.length s2 then [s1, s2] else [s2, s1]\n mapM_ (\\s -> putStrLn $ show (T.length s) ++ \"\\t\" ++ show s) strs\n", "language": "Haskell" }, { "code": " NB. solution\nchars=: 9&u:@>\nlongestFirst=: \\: #@chars\nlengthAndString=: ([:\":@,.#@chars),.' ',.chars\n\n NB. `Haruno-umi Hinemosu-Notari Notarikana'\n NB. Spring ocean ; Swaying gently ; All day long.\n\n lengthAndString longestFirst '春の海';'ひねもすのたり';'のたりかな'\n7 ひねもすのたり\n5 のたりかな\n3 春の海\n lengthAndString longestFirst '1234567';'abcd';'123456789';'abcdef'\n9 123456789\n7 1234567\n6 abcdef\n4 abcd\n", "language": "J" }, { "code": "import java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.List;\n", "language": "Java" }, { "code": "void printCompare(String stringA, String stringB) {\n if (stringA.length() > stringB.length()) {\n System.out.printf(\"%d %s%n\", stringA.length(), stringA);\n System.out.printf(\"%d %s%n\", stringB.length(), stringB);\n } else {\n System.out.printf(\"%d %s%n\", stringB.length(), stringB);\n System.out.printf(\"%d %s%n\", stringA.length(), stringA);\n }\n}\n\nvoid printDescending(String... strings) {\n List<String> list = new ArrayList<>(List.of(strings));\n list.sort(Comparator.comparingInt(String::length).reversed());\n for (String string : list)\n System.out.printf(\"%d %s%n\", string.length(), string);\n}\n", "language": "Java" }, { "code": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n public static void main(String[] args) {\n String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n String[] strings = args.length > 0 ? args : list;\n\n compareAndReportStringsLength(strings);\n }\n\n /**\n * Compare and report strings length to System.out.\n *\n * @param strings an array of strings\n */\n public static void compareAndReportStringsLength(String[] strings) {\n compareAndReportStringsLength(strings, System.out);\n }\n\n /**\n * Compare and report strings length.\n *\n * @param strings an array of strings\n * @param stream the output stream to write results\n */\n public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n if (strings.length > 0) {\n strings = strings.clone();\n final String QUOTE = \"\\\"\";\n Arrays.sort(strings, Comparator.comparing(String::length));\n int min = strings[0].length();\n int max = strings[strings.length - 1].length();\n for (int i = strings.length - 1; i >= 0; i--) {\n int length = strings[i].length();\n String predicate;\n if (length == max) {\n predicate = \"is the longest string\";\n } else if (length == min) {\n predicate = \"is the shortest string\";\n } else {\n predicate = \"is neither the longest nor the shortest string\";\n }\n //@todo: StringBuilder may be faster\n stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n + \" and \" + predicate);\n }\n }\n }\n}\n", "language": "Java" }, { "code": "/**\n * Compare and report strings lengths.\n *\n * @param {Element} input - a TextArea DOM element with input\n * @param {Element} output - a TextArea DOM element for output\n */\nfunction compareStringsLength(input, output) {\n\n // Safe defaults.\n //\n output.value = \"\";\n let output_lines = [];\n\n // Split input into an array of lines.\n //\n let strings = input.value.split(/\\r\\n|\\r|\\n/g);\n\n // Is strings array empty?\n //\n if (strings && strings.length > 0) {\n\n // Remove leading and trailing spaces.\n //\n for (let i = 0; i < strings.length; i++)\n strings[i] = strings[i].trim();\n\n // Sort by lengths.\n //\n strings.sort((a, b) => a.length - b.length);\n\n // Remove empty strings.\n //\n while (strings[0] == \"\")\n strings.shift();\n\n // Check if any strings remain.\n //\n if (strings && strings.length > 0) {\n\n // Get min and max length of strings.\n //\n const min = strings[0].length;\n const max = strings[strings.length - 1].length;\n\n // Build output verses - longest strings first.\n //\n for (let i = strings.length - 1; i >= 0; i--) {\n let length = strings[i].length;\n let predicate;\n if (length == max) {\n predicate = \"is the longest string\";\n } else if (length == min) {\n predicate = \"is the shortest string\";\n } else {\n predicate = \"is neither the longest nor the shortest string\";\n }\n output_lines.push(`\"${strings[i]}\" has length ${length} and ${predicate}\\n`);\n }\n\n // Send all lines from output_lines array to an TextArea control.\n //\n output.value = output_lines.join('');\n }\n }\n}\n\ndocument.getElementById(\"input\").value = \"abcd\\n123456789\\nabcdef\\n1234567\";\ncompareStringsLength(input, output);\n", "language": "JavaScript" }, { "code": "<html>\n\n<head>\n <style>\n div {\n margin-top: 4ch;\n margin-bottom: 4ch;\n }\n\n label {\n display: block;\n margin-bottom: 1ch;\n }\n\n textarea {\n display: block;\n }\n\n input {\n display: block;\n margin-top: 4ch;\n margin-bottom: 4ch;\n }\n </style>\n</head>\n\n<body>\n <main>\n <form>\n <div>\n <label for=\"input\">Input:\n </label>\n <textarea rows=\"20\" cols=\"80\" id=\"input\"></textarea>\n </div>\n <input type=\"button\" value=\"press to compare strings\" onclick=\"compareStringsLength(input, output);\">\n </input>\n <div>\n <label for=\"output\">Output:\n </label>\n <textarea rows=\"20\" cols=\"80\" id=\"output\"></textarea>\n </div>\n </form>\n </main>\n <script src=\"stringlensort.js\"></script>\n</body>\n\n</html>\n", "language": "JavaScript" }, { "code": "def s1: \"longer\";\ndef s2: \"shorter😀\";\n\n[s1,s2]\n| sort_by(length)\n| reverse[]\n| \"\\\"\\(.)\\\" has length (codepoints) \\(length) and utf8 byte length \\(utf8bytelength).\"\n", "language": "Jq" }, { "code": "s = \"niño\"\nprintln(\"Position Char Bytes\\n==============================\")\nfor (i, c) in enumerate(s)\n println(\"$i $c $(sizeof(c))\")\nend\n", "language": "Julia" }, { "code": "println(\"Position Codeunit Bytes\\n==============================\")\nfor (i, c) in enumerate(codeunits(s))\n println(\"$i $(string(c, base=16)) $(sizeof(c))\")\nend\n", "language": "Julia" }, { "code": "julia> s[4]\nERROR: StringIndexError: invalid index [4], valid nearby indices [3]=>'ñ', [5]=>'o'\n", "language": "Julia" }, { "code": "length(\"ñññ\") < length(\"nnnn\") # true, and the usual meaning of length of a String\n\nlength(codeunits(\"ñññ\")) > length(codeunits(\"nnnn\")) # true as well\n", "language": "Julia" }, { "code": "{def L.new\n {lambda {:s}\n {if {S.empty? {S.rest :s}}\n then {P.new {S.first :s} nil}\n else {P.new {S.first :s} {L.new {S.rest :s}}}}}}\n-> L.new\n\n{def L.disp\n {lambda {:l}\n {if {W.equal? :l nil}\n then\n else {br} {W.length {P.left :l}} : {P.left :l}\n {L.disp {P.right :l}}}}}\n-> L.disp\n", "language": "Lambdatalk" }, { "code": "{def B {L.new abcd 123456789 abcdef 1234567}}\n-> B\n\n{L.disp {B}}\n->\n 4 : abcd\n 9 : 123456789\n 6 : abcdef\n 7 : 1234567\n", "language": "Lambdatalk" }, { "code": "{def L.sort\n {lambda {:filter :l}\n {if {W.equal? :l nil}\n then nil\n else {L.insert {P.left :l} :filter\n {L.sort :filter {P.right :l}}}}}}\n-> L.sort\n\n{def L.insert\n {lambda {:x :filter :l}\n {if {W.equal? :l nil}\n then {P.new :x nil}\n else {if {:filter :x {P.left :l}}\n then {P.new :x :l}\n else {P.new {P.left :l}\n {L.insert :x :filter {P.right :l}}}}}}}\n-> L.insert\n", "language": "Lambdatalk" }, { "code": "{def filter\n {lambda {:a :b}\n {> {W.length :a} {W.length :b}}}}\n-> filter\n", "language": "Lambdatalk" }, { "code": "{L.disp {L.sort filter {B}}}\n->\n 9 : 123456789\n 7 : 1234567\n 6 : abcdef\n 4 : abcd\n", "language": "Lambdatalk" }, { "code": "function test(list)\n table.sort(list, function(a,b) return #a > #b end)\n for _,s in ipairs(list) do print(#s, s) end\nend\ntest{\"abcd\", \"123456789\", \"abcdef\", \"1234567\"}\n", "language": "Lua" }, { "code": "list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\nReverse@SortBy[list, StringLength] // TableForm\n", "language": "Mathematica" }, { "code": "// Simple version\nprint \"Simple version:\"\ns2 = \"This is the first string.\"\ns1 = \"This is string number two.\"\n\nif s1.len > s2.len then\n\tprint s1.len + \": \" + s1\n\tprint s2.len + \": \" + s2\nelse\n\tprint s2.len + \": \" + s2\n\tprint s1.len + \": \" + s1\nend if\n\n// Extra credit. More than 2 strings\nstrings = [\"qwerty\", \"abc\", \"#FFFFFFFF\", \"255,255,255,255\", \"3.14159\"]\npairs = []\nfor string in strings\n\tpairs.push([string, string.len])\nend for\n// sort by index descending\npairs.sort(1, false)\nprint\nprint \"Extra credit:\"\nfor pair in pairs\n\tprint pair[1] + \": \" + pair[0]\nend for\n", "language": "MiniScript" }, { "code": "100 LET A$ = \"abcd\"\n110 LET B$ = \"123456789\"\n120 GOSUB 140\n130 END\n140 REM SUB comp(A$, B$)\n150 IF LEN(A$) >= LEN(B$) THEN PRINT A$,LEN(A$) : PRINT B$,LEN(B$)\n180 IF LEN(A$) < LEN(B$) THEN PRINT B$,LEN(B$) : PRINT A$,LEN(A$)\n220 RETURN\n", "language": "MSX-Basic" }, { "code": "import strformat, unicode\n\nconst\n S1 = \"marche\"\n S2 = \"marché\"\n\necho &\"“{S2}”, byte length = {S2.len}, code points: {S2.toRunes.len}\"\necho &\"“{S1}”, byte length = {S1.len}, code points: {S1.toRunes.len}\"\n", "language": "Nim" }, { "code": "let () =\n [\"abcd\"; \"123456789\"; \"abcdef\"; \"1234567\"]\n |> List.rev_map (fun s -> String.length s, s)\n |> List.sort (Fun.flip compare)\n |> List.iter (fun (l, s) -> Printf.printf \"%u %s\\n\" l s)\n", "language": "OCaml" }, { "code": "program compareLengthOfStrings(output);\n\nconst\n\tspecimenA = 'RosettaCode';\n\tspecimenB = 'Pascal';\n\tspecimenC = 'Foobar';\n\tspecimenD = 'Pascalish';\n\ntype\n\tspecimen = (A, B, C, D);\n\tspecimens = set of specimen value [];\n\nconst\n\tspecimenMinimum = A;\n\tspecimenMaximum = D;\n\nvar\n\t{ the explicit range min..max serves as a safeguard to update max const }\n\tlist: array[specimenMinimum..specimenMaximum] of string(24)\n\t\tvalue [A: specimenA; B: specimenB; C: specimenC; D: specimenD];\n\tlengthRelationship: array[specimen] of specimens;\n\nprocedure analyzeLengths;\nvar\n\tleft, right: specimen;\nbegin\n\tfor left := specimenMinimum to specimenMaximum do\n\tbegin\n\t\tfor right := specimenMinimum to specimenMaximum do\n\t\tbegin\n\t\t\tif length(list[left]) < length(list[right]) then\n\t\t\tbegin\n\t\t\t\tlengthRelationship[right] := lengthRelationship[right] + [right]\n\t\t\tend\n\t\tend\n\tend\nend;\n\nprocedure printSortedByLengths;\nvar\n\ti: ord(specimenMinimum)..ord(specimenMaximum);\n\ts: specimen;\nbegin\n\t{ first the string longer than all other strings }\n\t{ lastly print the string not longer than any other string }\n\tfor i := ord(specimenMaximum) downto ord(specimenMinimum) do\n\tbegin\n\t\t{ for demonstration purposes: iterate over a set }\n\t\tfor s in [specimenMinimum..specimenMaximum] do\n\t\tbegin\n\t\t\t{ card returns the cardinality (\"population count\") }\n\t\t\tif card(lengthRelationship[s]) = i then\n\t\t\tbegin\n\t\t\t\twriteLn(length(list[s]):8, ' ', list[s])\n\t\t\tend\n\t\tend\n\tend\nend;\n\nbegin\n\tanalyzeLengths;\n\tprintSortedByLengths\nend.\n", "language": "Pascal" }, { "code": "#!/usr/bin/perl\n\nuse strict; # https://rosettacode.org/wiki/Compare_length_of_two_strings\nuse warnings;\n\nfor ( 'shorter thelonger', 'abcd 123456789 abcdef 1234567' )\n {\n print \"\\nfor strings => $_\\n\";\n printf \"length %d: %s\\n\", length(), $_\n for sort { length $b <=> length $a } split;\n }\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">list</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"abcd\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"123456789\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"abcdef\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"1234567\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #000000;\">lens</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">apply</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">list</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">tags</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">reverse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">custom_sort</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lens</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lens</span><span style=\"color: #0000FF;\">))))</span>\n <span style=\"color: #7060A8;\">papply</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #008000;\">\"%s (length %d)\\n\"</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #7060A8;\">columnize</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #7060A8;\">extract</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">list</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tags</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #7060A8;\">extract</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lens</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tags</span><span style=\"color: #0000FF;\">)})})</span>\n<!--\n", "language": "Phix" }, { "code": "/# Rosetta Code problem: http://rosettacode.org/wiki/Compare_length_of_two_strings\nby Galileo, 10/2022 #/\n\ninclude ..\\Utilitys.pmt\n\ndef getlen len swap 2 tolist enddef\n\n( \"abcd\" \"123456789\" \"abcdef\" \"1234567\" ) getid getlen map\n\nsort reverse lprint\n", "language": "Phixmonti" }, { "code": "<?php\n\n\nfunction retrieveStrings()\n{\n if (isset($_POST['input'])) {\n $strings = explode(\"\\n\", $_POST['input']);\n } else {\n $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n }\n return $strings;\n}\n\n\nfunction setInput()\n{\n echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n $strings = retrieveStrings();\n\n // Remove empty strings\n //\n $strings = array_map('trim', $strings);\n $strings = array_filter($strings);\n\n if (!empty($strings)) {\n usort($strings, function ($a, $b) {\n return strlen($b) - strlen($a);\n });\n $max_len = strlen($strings[0]);\n $min_len = strlen($strings[count($strings) - 1]);\n foreach ($strings as $s) {\n $length = strlen($s);\n if ($length == $max_len) {\n $predicate = \"is the longest string\";\n } elseif ($length == $min_len) {\n $predicate = \"is the shortest string\";\n } else {\n $predicate = \"is neither the longest nor the shortest string\";\n }\n echo \"$s has length $length and $predicate\\n\";\n }\n }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <style>\n div {\n margin-top: 4ch;\n margin-bottom: 4ch;\n }\n\n label {\n display: block;\n margin-bottom: 1ch;\n }\n\n textarea {\n display: block;\n }\n\n input {\n display: block;\n margin-top: 4ch;\n margin-bottom: 4ch;\n }\n </style>\n</head>\n\n\n<body>\n <main>\n <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n <div>\n <label for=\"input\">Input:\n </label>\n <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n </label>\n </div>\n <input type=\"submit\" value=\"press to compare strings\">\n </input>\n <div>\n <label for=\"Output\">Output:\n </label>\n <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n </div>\n </form>\n </main>\n</body>\n\n</html>\n", "language": "PHP" }, { "code": " declare (S1, S2) character (20) varying; /* 11 Aug 2022 */\n get (S1, S2);\n if length(S1) > length(S2) then\n put (length(S1), S1);\n else\n put (length(S2), S2);\n", "language": "PL-I" }, { "code": "Procedure comp(A.s, B.s)\n If Len(A) >= Len(B)\n PrintN(A + #TAB$ + Str(Len(A)))\n PrintN(B + #TAB$ + Str(Len(B)))\n Else\n PrintN(B + #TAB$ + Str(Len(B)))\n PrintN(A + #TAB$ + Str(Len(A)))\n EndIf\nEndProcedure\n\nOpenConsole()\ncomp(\"abcd\", \"123456789\")\nInput()\nCloseConsole()\n", "language": "PureBasic" }, { "code": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n", "language": "Python" }, { "code": "\"\"\"\nAn example code for the task \"Compare length of two strings\" (Rosseta Code).\n\nThis example code can handle not only strings, but any objects.\n\"\"\"\n\n\ndef _(message):\n \"\"\"Translate: an placeholder for i18n and l10n gettext or similar.\"\"\"\n return message\n\n\ndef compare_and_report_length(*objects, sorted_=True, reverse=True):\n \"\"\"\n For objects given as parameters it prints which of them are the longest.\n\n So if the parameters are strings, then the strings are printed, their\n lengths and classification as the longest, shortest or average length.\n\n Note that for N > 0 such objects (e.g., strings, bytes, lists) it is\n possible that exactly M > 0 of them will be of the maximum length, K > 0 of\n them will be of the minimum length. In particular, it is possible that all\n objects will be exactly the same length. So we assume that if an object has\n both the maximum and minimum length, it is referred to as a string with the\n maximum length.\n\n Args:\n *objects (object): Any objects with defined length.\n sorted_ (bool, optional): If sorted_ is False then objects are not\n sorted. Defaults to True.\n reverse (bool, optional): If reverse is True and sorted_ is True\n objects are sorted in the descending order. If reverse is False\n and sorted_ is True objects are sorted in the ascending order.\n Defaults to True.\n\n Returns:\n None.\n \"\"\"\n lengths = list(map(len, objects))\n max_length = max(lengths)\n min_length = min(lengths)\n lengths_and_objects = zip(lengths, objects)\n\n # Longer phrases make translations into other natural languages easier.\n #\n has_length = _('has length')\n if all(isinstance(obj, str) for obj in objects):\n predicate_max = _('and is the longest string')\n predicate_min = _('and is the shortest string')\n predicate_ave = _('and is neither the longest nor the shortest string')\n else:\n predicate_max = _('and is the longest object')\n predicate_min = _('and is the shortest object')\n predicate_ave = _('and is neither the longest nor the shortest object')\n\n if sorted_:\n lengths_and_objects = sorted(lengths_and_objects, reverse=reverse)\n\n for length, obj in lengths_and_objects:\n if length == max_length:\n predicate = predicate_max\n elif length == min_length:\n predicate = predicate_min\n else:\n predicate = predicate_ave\n print(obj, has_length, length, predicate)\n\n\nA = 'I am string'\nB = 'I am string too'\nLIST = [\"abcd\", \"123456789\", \"abcdef\", \"1234567\"]\n\n\nprint('Two strings')\nprint()\ncompare_and_report_length(A, B)\nprint()\n\nprint('A list of strings')\nprint()\ncompare_and_report_length(*LIST)\nprint()\n", "language": "Python" }, { "code": "Dim Words(1 To 4) As String\nDim Lengths As Integer, Index As Integer, Position As Integer, Done As String, Index2 As Integer\n' inititialization\nWords(1) = \"abcd\"\nWords(2) = \"123456789\"\nWords(3) = \"abcdef\"\nWords(4) = \"1234567\"\n\nPrint \" Word Length\"\nFor Index2 = 1 To 4 Step 1\n Lengths = 0\n Position = 0\n For Index = 1 To 4 Step 1\n If Lengths < Len(Words(Index)) And InStr(Done, Words(Index) + \" \") = 0 Then\n Lengths = Len(Words(Index))\n Position = Index\n End If\n Next Index\n Done = Done + Words(Position) + \" /@/\"\n Print Words(Position), Len(Words(Position))\nNext Index2\n", "language": "QB64" }, { "code": "SUB comp(A$, B$)\n IF LEN(A$) >= LEN(B$) THEN\n PRINT A$, LEN(A$)\n PRINT B$, LEN(B$)\n ELSE\n PRINT B$, LEN(B$)\n PRINT A$, LEN(A$)\n END IF\nEND SUB\n\nCALL comp(\"abcd\", \"123456789\")\nEND\n", "language": "QBasic" }, { "code": " $ \"A short string of\"\n $ \"A slightly longer string of\"\n\n 2dup size dip size > if swap\n dup echo$ sp size echo say \" characters.\" cr\n dup echo$ sp size echo say \" characters.\" cr cr\n\n ' [ $ \"From troubles of the world I turn to ducks,\"\n $ \"Beautiful comical things\"\n $ \"Sleeping or curled\"\n $ \"Their heads beneath white wings\"\n $ \"By water cool,\"\n $ \"Or finding curious things\"\n $ \"To eat in various mucks\"\n $ \"Beneath the pool,\" ]\n [] swap witheach [ do nested join ]\n\n sortwith [ size dip size < ]\n witheach [ echo$ cr ]\n", "language": "Quackery" }, { "code": "#lang racket\n\n(define strings '(\"abcd\" \"123456789\" \"abcdef\" \"1234567\"))\n\n(for ([i (sort strings > #:key string-length)])\n (printf \"'~a' is length ~a~n\" i (string-length i)))\n", "language": "Racket" }, { "code": "say 'Strings (👨‍👩‍👧‍👦, 🤔🇺🇸, BOGUS!) sorted: \"longest\" first:';\nsay \"$_: characters:{.chars}, Unicode code points:{.codes}, UTF-8 bytes:{.encode('UTF8').bytes}, UTF-16 bytes:{.encode('UTF16').bytes}\" for <👨‍👩‍👧‍👦 BOGUS! 🤔🇺🇸>.sort: -*.chars;\n", "language": "Raku" }, { "code": "/* REXX */\nlist = '\"abcd\",\"123456789\",\"abcdef\",\"1234567\"'\nDo i=1 By 1 While list>''\n Parse Var list s.i ',' list\n s.i=strip(s.i,,'\"')\n End\nn=i-1\nDo While n>1\n max=0\n Do i=1 To n\n If length(s.i)>max Then Do\n k=i\n max=length(s.i)\n End\n End\n Call o s.k\n If k<n Then\n s.k=s.n\n n=n-1\n End\nCall o s.1\nExit\no:\nSay length(arg(1)) arg(1)\nReturn\n", "language": "REXX" }, { "code": "see \"working...\" + nl\n\nlist = [\"abcd\",\"123456789\"]\nif len(list[1]) > len(list[2])\n first = list[1]\n second = list[2]\nelse\n first = list[2]\n second = list[1]\nok\n\nsee \"Compare length of two strings:\" + nl\nsee \"\" + first + \" len = \" + len(first) + nl + second + \" len = \" + len(second) + nl\nsee \"done...\" + nl\n", "language": "Ring" }, { "code": "see \"working...\" + nl\n\nlenList = []\nlist = [\"abcd\",\"123456789\",\"abcdef\",\"1234567\"]\nfor n = 1 to len(list)\n len = len(list[n])\n add(lenList,[len,n])\nnext\n\nlenList = sort(lenList,1)\nlenList = reverse(lenList)\n\nsee \"Compare length of strings in descending order:\" + nl\nfor n = 1 to len(lenList)\n see \"\" + list[lenList[n][2]] + \" len = \" + lenList[n][1] + nl\nnext\nsee \"done...\" + nl\n", "language": "Ring" }, { "code": "a, b = \"Given two strings\", \"of different length\"\n[a,b].sort_by{|s| - s.size }.each{|s| puts s + \" (size: #{s.size})\"}\n\nlist = [\"abcd\",\"123456789\",\"abcdef\",\"1234567\"]\nputs list.sort_by{|s|- s.size}\n", "language": "Ruby" }, { "code": "sub comp A$, B$\n if len(A$) >= len(B$) then\n print A$; chr$(9); len(A$)\n print B$; chr$(9); len(B$)\n else\n print B$; chr$(9); len(B$)\n print A$; chr$(9); len(A$)\n end if\nend sub\n\ncall comp \"abcd\", \"123456789\"\n", "language": "Run-BASIC" }, { "code": "fn compare_and_report<T: ToString>(string1: T, string2: T) -> String {\n let strings = [string1.to_string(), string2.to_string()];\n let difference = strings[0].len() as i32 - strings[1].len() as i32;\n if difference == 0 { // equal\n format!(\"\\\"{}\\\" and \\\"{}\\\" are of equal length, {}\", strings[0], strings[1], strings[0].len())\n } else if difference > 1 { // string1 > string2\n format!(\"\\\"{}\\\" has length {} and is the longest\\n\\\"{}\\\" has length {} and is the shortest\", strings[0], strings[0].len(), strings[1], strings[1].len())\n } else { // string2 > string1\n format!(\"\\\"{}\\\" has length {} and is the longest\\n\\\"{}\\\" has length {} and is the shortest\", strings[1], strings[1].len(), strings[0], strings[0].len())\n }\n}\n\nfn main() {\n println!(\"{}\", compare_and_report(\"a\", \"b\"));\n println!(\"\\n{}\", compare_and_report(\"cd\", \"e\"));\n println!(\"\\n{}\", compare_and_report(\"f\", \"gh\"));\n}\n", "language": "Rust" }, { "code": "object Example extends App {\n val strings = Array(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n compareAndReportStringsLength(strings)\n\n def compareAndReportStringsLength(strings: Array[String]): Unit = {\n if (strings.nonEmpty) {\n val Q = '\"'\n val hasLength = \" has length \"\n val predicateMax = \" and is the longest string\"\n val predicateMin = \" and is the shortest string\"\n val predicateAve = \" and is neither the longest nor the shortest string\"\n\n val sortedStrings = strings.sortBy(-_.length)\n val maxLength = sortedStrings.head.length\n val minLength = sortedStrings.last.length\n\n sortedStrings.foreach { str =>\n val length = str.length\n val predicate = length match {\n case `maxLength` => predicateMax\n case `minLength` => predicateMin\n case _ => predicateAve\n }\n println(s\"$Q$str$Q$hasLength$length$predicate\")\n }\n }\n }\n}\n", "language": "Scala" }, { "code": "#lang transd\n\nMainModule: {\n v: [\"abcd\",\"123456789\",\"abcdef\",\"1234567\"],\n\n\t_start: (λ\n (for s in (sort v (λ l String() r String()\n (ret (< (size r) (size l))))) do\n (lout width: 10 s \" : \" (size s) \" code points\") )\n )\n}\n", "language": "Transd" }, { "code": "SUB comp(A$, B$)\n IF LEN(A$) >= LEN(B$) THEN\n PRINT A$, LEN(A$)\n PRINT B$, LEN(B$)\n ELSE\n PRINT B$, LEN(B$)\n PRINT A$, LEN(A$)\n END IF\nEND SUB\n\nCALL comp(\"abcd\", \"123456789\")\nEND\n", "language": "True-BASIC" }, { "code": "// Compare lenth of two strings, in V\n// Tectonics: v run compare-length-of-two-strings.v\nmodule main\n\n// starts here\npub fn main() {\n mut strs := [\"abcd\",\"123456789\"]\n println(\"Given: $strs\")\n strs.sort_by_len()\n for i := strs.len-1; i >= 0; i-- {\n println(\"${strs[i]}: with length ${strs[i].len}\")\n }\n\n // more than 2 strings. note = vs :=, := for definition, = for assignment\n strs = [\"abcd\",\"123456789\",\"abcdef\",\"1234567\"]\n println(\"\\nGiven: $strs\")\n strs.sort_by_len()\n for i := strs.len-1; i >= 0; i-- {\n println(\"${strs[i]}: with length ${strs[i].len}\")\n }\n}\n", "language": "V-(Vlang)" }, { "code": "import \"./upc\" for Graphemes\n\nvar printCounts = Fn.new { |s1, s2, c1, c2|\n var l1 = (c1 > c2) ? [s1, c1] : [s2, c2]\n var l2 = (c1 > c2) ? [s2, c2] : [s1, c1]\n System.print( \"%(l1[0]) : length %(l1[1])\")\n System.print( \"%(l2[0]) : length %(l2[1])\\n\")\n}\n\nvar codepointCounts = Fn.new { |s1, s2|\n var c1 = s1.count\n var c2 = s2.count\n System.print(\"Comparison by codepoints:\")\n printCounts.call(s1, s2, c1, c2)\n}\n\nvar byteCounts = Fn.new { |s1, s2|\n var c1 = s1.bytes.count\n var c2 = s2.bytes.count\n System.print(\"Comparison by bytes:\")\n printCounts.call(s1, s2, c1, c2)\n}\n\nvar graphemeCounts = Fn.new { |s1, s2|\n var c1 = Graphemes.clusterCount(s1)\n var c2 = Graphemes.clusterCount(s2)\n System.print(\"Comparison by grapheme clusters:\")\n printCounts.call(s1, s2, c1, c2)\n}\n\nfor (pair in [ [\"nino\", \"niño\"], [\"👨‍👩‍👧‍👦\", \"🤔🇺🇸\"] ]) {\n codepointCounts.call(pair[0], pair[1])\n byteCounts.call(pair[0], pair[1])\n graphemeCounts.call(pair[0], pair[1])\n}\n\nvar list = [\"abcd\", \"123456789\", \"abcdef\", \"1234567\"]\nSystem.write(\"Sorting in descending order by length in codepoints:\\n%(list) -> \")\nlist.sort { |a, b| a.count > b.count }\nSystem.print(list)\n", "language": "Wren" }, { "code": "PROGRAM\t\"Compare length of two strings\"\nVERSION\t\"0.0000\"\n\nDECLARE FUNCTION Entry ()\nDECLARE FUNCTION comp (A$, B$)\n\n\nFUNCTION Entry ()\n comp(\"abcd\", \"123456789\")\nEND FUNCTION\n\nFUNCTION comp (A$, B$)\n IF LEN(A$) >= LEN(B$) THEN\n PRINT A$, LEN(A$)\n PRINT B$, LEN(B$)\n ELSE\n PRINT B$, LEN(B$)\n PRINT A$, LEN(A$)\n END IF\nEND FUNCTION\nEND PROGRAM\n", "language": "XBasic" }, { "code": "string 0; \\use zero-terminated string convention\n\nfunc StrLen(A); \\Return number of characters in an ASCIIZ string\nchar A;\nint I;\nfor I:= 0 to -1>>1 do\n if A(I) = 0 then return I;\n\nchar List;\nint M, N, SN, Len, Max;\n[List:= [\"abcd\",\"123456789\",\"abcdef\",\"1234567\"];\nfor M:= 0 to 3 do\n [Max:= 0;\n for N:= 0 to 3 do\n [Len:= StrLen(@List(N,0));\n if Len > Max then [Max:= Len; SN:= N];\n ];\n Text(0, @List(SN,0));\n Text(0, \" length is \"); IntOut(0, StrLen(@List(SN,0))); CrLf(0);\n List(SN, 0):= 0; \\truncate largest string\n ];\n]\n", "language": "XPL0" }, { "code": "sub comp(A$, B$)\n if len(A$) >= len(B$) then\n print A$, chr$(9), len(A$)\n print B$, chr$(9), len(B$)\n else\n print B$, chr$(9), len(B$)\n print A$, chr$(9), len(A$)\n end if\nend sub\n\ncomp(\"abcd\", \"123456789\")\n", "language": "Yabasic" }, { "code": "Terminator equ 0 ;null terminator\nPrintChar equ &BB5A ;Amstrad CPC BIOS call, prints accumulator to screen as an ASCII character.\n\n org &8000\n\n\tld hl,String1\n\tld de,String2\n\tcall CompareStringLengths\n\t\n\tjp nc, Print_HL_First\n\t\tex de,hl\nPrint_HL_First:\n\tpush bc\n\t\tpush hl\n\t\t\tcall PrintString\n\t\tpop hl\n\t\tpush hl\n\t\t\tld a,' '\n\t\t\tcall PrintChar\n\t\t\tcall getStringLength\n\t\t\tld a,b\n\t\t\tcall ShowHex_NoLeadingZeroes\n\t\t\tcall NewLine\n\t\tpop hl\n\tpop bc\n\t\n\tex de,hl\n\tpush bc\n\t\tpush hl\n\t\t\tcall PrintString\n\t\tpop hl\n\t\tpush hl\n\t\t\tld a,' '\n\t\t\tcall PrintChar\n\t\t\tcall getStringLength\n\t\t\tld a,b\n\t\t\tcall ShowHex_NoLeadingZeroes\n\t\t\tcall NewLine\n\t\tpop hl\n\tpop bc\t\nReturnToBasic:\n\tRET\n\nString1:\n\tbyte \"Hello\",Terminator\nString2:\n\tbyte \"Goodbye\",Terminator\n\n;;;;;; RELEVANT SUBROUTINES - PRINTSTRING AND NEWLINE CREATED BY KEITH S. OF CHIBIAKUMAS\nCompareStringLengths:\n\t;HL = string 1\n\t;DE = string 2\n\t;CLOBBERS A,B,C\n\tpush hl\n\tpush de\n\tex de,hl\n\tcall GetStringLength\n\tld b,c\n\t\n\tex de,hl\n\tcall GetStringLength\n\tld a,b\n\tcp c\n\tpop de\n\tpop hl\n\tret\n\t;returns carry set if HL < DE, zero set if equal, zero & carry clear if HL >= DE\n\t;returns len(DE) in C, and len(HL) in B.\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\nGetStringLength:\n\t\tld b,0\nloop_getStringLength:\n\t\tld a,(hl)\n\t\tcp Terminator\n\t\tret z\n\t\tinc hl\n\t\tinc b\n\t\tjr loop_getStringLength\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\nNewLine:\n\tpush af\n\tld a,13\t\t;Carriage return\n\tcall PrintChar\n\tld a,10\t\t;Line Feed\n\tcall PrintChar\n\tpop af\n\tret\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\nPrintString:\n\tld a,(hl)\t\n\tcp Terminator\n\tret z\n\tinc hl\n\tcall PrintChar\n\tjr PrintString\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\nShowHex_NoLeadingZeroes:\n;useful for printing values where leading zeroes don't make sense,\n; \tsuch as money etc.\n\tpush af\n\t\tand %11110000\n\t\tifdef gbz80 ;game boy\n\t\t\tswap a\n\t\telse ;zilog z80\n\t\t\trrca\n\t\t\trrca\n\t\t\trrca\n\t\t\trrca\n\t\tendif\n\t\tor a\n\t\tcall nz,PrintHexChar\n\t\t;if top nibble of A is zero, don't print it.\n\tpop af\n\tand %00001111\n\tor a\n\tret z\t;if bottom nibble of A is zero, don't print it!\n\tjp PrintHexChar\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\nPrintHexChar:\n\tor a\t ;Clear Carry Flag\n\tdaa\n\tadd a,&F0\n\tadc a,&40 ;This sequence converts a 4-bit hex digit to its ASCII equivalent.\n\tjp PrintChar\n", "language": "Z80-Assembly" } ]
Compare-length-of-two-strings
[ { "code": "---\ncategory:\n- Sorting\nfrom: http://rosettacode.org/wiki/Compare_sorting_algorithms'_performance\nnote: Sorting Algorithms\n", "language": "00-META" }, { "code": "{{Sorting Algorithm}}\n\nMeasure a relative performance of sorting algorithms implementations.\n\nPlot '''execution time vs. input sequence length''' dependencies for various implementation of sorting algorithm and different input sequence types ([[#Figures: log2( time in microseconds ) vs. log2( sequence length )|example figures]]). \n\nConsider three type of input sequences:\n:* &nbsp; ones: sequence of all ''1'''s. &nbsp; Example: {1, 1, 1, 1, 1}\n:* &nbsp; range: ascending sequence, i.e. already sorted. &nbsp; Example: {1, 2, 3, 10, 15}\n:* &nbsp; shuffled range: sequence with elements randomly distributed. &nbsp; Example: {5, 3, 9, 6, 8}\n\n\nConsider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm).\n\nFor example, consider [[Bubble Sort]], [[Insertion sort]], [[Quicksort]] or/and implementations of Quicksort with different pivot selection mechanisms. &nbsp; Where possible, use existing implementations.\n\nPreliminary subtask:\n:* &nbsp; [[Bubble Sort]], [[Insertion sort]], [[Quicksort]], [[Radix sort]], [[Shell sort]]\n:* &nbsp; [[Query Performance]]\n:* &nbsp; [[Write float arrays to a text file]]\n:* &nbsp; [[Plot x, y arrays]]\n:* &nbsp; [[Polynomial Fitting]]\n\n\nGeneral steps:\n:# &nbsp; Define sorting routines to be considered.\n:# &nbsp; Define appropriate sequence generators and write timings.\n:# &nbsp; Plot timings.\n:# &nbsp; What conclusions about relative performance of the sorting routines could be made based on the plots?\n<br><br>\n\n", "language": "00-TASK" }, { "code": "; BUGGY - FIX\n\n#Persistent\n#SingleInstance OFF\nSetBatchLines, -1\nSortMethods := \"Bogo,Bubble,Cocktail,Counting,Gnome,Insertion,Merge,Permutation,Quick,Selection,Shell,BuiltIn\"\nGui, Add, Edit, vInput, numbers,separated,by,commas,without,spaces,afterwards\nLoop, PARSE, SortMethods, `,\n\tGui, Add, CheckBox, v%A_LoopField%, %A_LoopField% Sort\nGui, Add, Button, gTest, Test!\nGui, Show,, SortTest!\nReturn\nTest:\nSplashTextOn,,, Test Commencing\nSleep 2500\nSplashTextOff\nGui, +OwnDialogs\nGui, Submit, NoHide\nLoop, PARSE, SortMethods, `,\n{\n\tIf (%A_LoopField%)\n\t{\n\t\tDllCall(\"QueryPerformanceCounter\", \"Int64 *\", %A_LoopField%Begin)\n\t\t%A_LoopField%Out := %A_LoopField%Sort(Input)\n\t\tDllCall(\"QueryPerformanceCounter\", \"Int64 *\", %A_LoopField%Time)\n\t\t%A_LoopField%End := %A_LoopField%Begin + %A_LoopField%Time\n\t\t%A_LoopField%Time -= %A_LoopField%Begin\n\t}\n}\nTime := \"\"\nLoop, PARSE, SortMethods, `,\n\tIf (%A_LoopField%)\n\t\tTime .= A_LoopField . \" Sort: \" . %A_LoopField%Time . \"`t`t\" . %A_LoopField%Out . \"`r`n\"\nMsgBox,, Results!, %Time%\nReturn\n\n\n\n; Sorting funtions (Bogo, Bubble, Cocktail, Counting, Gnome, Insertion, Merge, Permutation, Quick, Selection, Shell, BuiltIn):\n\nBogoSort(var)\n{\n\tsorted := 1\n\tLoop, Parse, var\n\t{\n\t\tcurrent := A_LoopField\n\t\trest := SubStr(var, A_Index)\n\t\tLoop, Parse, rest\n\t\t{\n\t\t\tIf (current > A_LoopField)\n\t\t\tsorted := 0\n\t\t}\n\t}\n\tWhile !sorted {\n\t\tsorted := 1\n\t\tLoop, Parse, var, `,\n\t\t{\n\t\t\tcurrent := A_LoopField\n\t\t\trest := SubStr(var, A_Index)\n\t\t\tLoop, Parse, rest, `,\n\t\t\t{\n\t\t\t\tIf (current > A_LoopField)\n\t\t\t\tsorted := 0\n\t\t\t}\n\t\t}\n\n\t\tSort, var, D`, Random\n\t}\n\tReturn var\n}\n\nBubbleSort(var)\n{\n\tStringSplit, array, var, `,\n\thasChanged = 1\n\tsize := array0\n\tWhile hasChanged\n\t{\n\t\thasChanged = 0\n\t\tLoop, % (size - 1)\n\t\t{\n\t\t\ti := array%A_Index%\n\t\t\taj := A_Index + 1\n\t\t\tj := array%aj%\n\t\t\tIf (j < i)\n\t\t\t{\n\t\t\t\ttemp := array%A_Index%\n\t\t\t\tarray%A_Index% := array%aj%\n\t\t\t\tarray%aj% := temp\n\t\t\t\thasChanged = 1\n\t\t\t}\n\t\t}\n\t}\n\tLoop, % size\n\tsorted .= \",\" . array%A_Index%\n\tReturn substr(sorted,2)\n}\n\nCocktailSort(var)\n{\n\tStringSplit array, var, `,\n\ti0 := 1, i1 := array0\n\tLoop\n\t{\n\t\tChanged =\n\t\tLoop % i1-- -i0 {\n\t\t\tj := i0+A_Index, i := j-1\n\t\t\tIf (array%j% < array%i%)\n\t\t\t\tt := array%i%, array%i% := array%j%, array%j% := t\n\t\t\t\t,Changed = 1\n\t\t}\n\t\tIfEqual Changed,, Break\n\t\tLoop % i1-i0++\n\t\t{\n\t\t\ti := i1-A_Index, j := i+1\n\t\t\tIf (array%j% < array%i%)\n\t\t\tt := array%i%, array%i% := array%j%, array%j% := t\n\t\t\t,Changed = 1\n\t\t}\n\t\tIfEqual Changed,, Break\n\t}\n\tLoop % array0\n\t\tsorted .= \",\" . array%A_Index%\n\tReturn SubStr(sorted,2)\n}\n\nCountingSort(var)\n{\n\tmax := min := substr(var, 1, instr(var, \",\"))\n\tLoop, parse, var, `,\n\t{\n\t\tIf (A_LoopField > max)\n\t\t\tmax := A_LoopField\n\n\t\tElse If (A_LoopField < min)\n\t\t\tmin := A_LoopField\n\t}\n\tLoop % max-min+1\n\t\ti := A_Index-1, a%i% := 0\n\tLoop, Parse, var, `,\n\t\ti := A_LoopField-min, a%i%++\n\tLoop % max-min+1\n\t{\n\t\ti := A_Index-1, v := i+min\n\t\tLoop % a%i%\n\t\t\tt .= \",\" v\n\t}\n\tReturn SubStr(t,2)\n}\n\nGnomeSort(var) {\n\tStringSplit, a, var, `,\n\ti := 2, j := 3\n\tWhile i <= a0 {\n\t\tu := i-1\n\t\tIf (a%u% < a%i%)\n\t\t\ti := j, j := j+1\n\t\tElse {\n\t\t\tt := a%u%, a%u% := a%i%, a%i% := t\n\t\t\tIf (--i = 1)\n\t\t\t\ti := j, j++\n\t\t}\n\t}\n\tLoop % a0\n\tsorted .= \",\" . a%A_Index%\n\tReturn SubStr(sorted,2)\n}\n\nInsertionSort(var) {\n\tStringSplit, a, var, `,\n\tLoop % a0-1 {\n\t\ti := A_Index+1, v := a%i%, j := i-1\n\t\tWhile j>0 and a%j%>v\n\t\t\tu := j+1, a%u% := a%j%, j--\n\t\tu := j+1, a%u% := v\n\t}\n\tLoop % a0\n\tsorted .= \",\" . a%A_Index%\n\tReturn SubStr(sorted,2)\n}\n\n\nMergeSort(var) {\n\tStringReplace, t, var, `,,, UseErrorLevel\n\tL := ((t = \"\") ? 0 : ErrorLevel+1)\n\tIf (2 > L)\n\t\tReturn var\n\tStringGetPos, p, var, `,, % \"L\" L//2\n\tlist0 := MergeSort(SubStr(var,1,p))\n\tlist1 := MergeSort(SubStr(var,p+2))\n\tIf (list0 = \"\")\n\t\tReturn list1\n\tElse If (list1 = \"\")\n\t\tReturn list0\n\tlist := list0\n\ti0 := (p0 := InStr(list,\",\",0,i:=p0+1)) ? SubStr(list,i,p0-i) : SubStr(list,i)\n\tlist := list1\n\ti1 := (p1 := InStr(list,\",\",0,i:=p1+1)) ? SubStr(list,i,p1-i) : SubStr(list,i)\n\tLoop {\n\t\ti := i0>i1\n\t\tlist .= \",\" i%i%\n\t\tIf (p%i%) {\n\t\t\tlist := list%i%\n\t\t\ti%i% := (p%i% := InStr(list,\",\",0,i:=p%i%+1)) ? SubStr(list,i,p%i%-i) : SubStr(list,i)\n\t\t}\n\t\tElse {\n\t\t\ti ^= 1\n\t\t\trtv := SubStr(list \",\" i%i% (p%i% ? \",\" SubStr(list%i%,p%i%+1) : \"\"), 2)\n\t\t}\n\t}\n\tReturn rtv\n}\n\nPermutationSort(var) {\n\tstatic a:=\"a\",v:=\"v\"\n\tStringSplit, a, var, `,\n\tv0 := a0\n\tLoop %v0%\n\t\tv%A_Index% := A_Index\n\tunsorted := 0\n\tLoop % %a%0-1 {\n\t\ti := %v%%A_Index%, j := A_Index+1, j := %v%%j%\n\t\tIf (%a%%i% > %a%%j%)\n\t\t\tunSorted := 1\n\t}\n\tWhile unSorted {\n\t\ti := %v%0, i1 := i-1\n\t\tWhile %v%%i1% >= %v%%i% {\n\t\t\t--i, --i1\n\t\t\tIfLess i1,1, Return 1\n\t\t}\n\t\tj := %v%0\n\t\tWhile %v%%j% <= %v%%i1%\n\t\t\t--j\n\t\tt := %v%%i1%, %v%%i1% := %v%%j%, %v%%j% := t, j := %v%0\n\t\tWhile i < j\n\t\t\tt := %v%%i%, %v%%i% := %v%%j%, %v%%j% := t, ++i, --j\n\t\tunsorted := 0\n\t\tLoop % %a%0-1 {\n\t\t\ti := %v%%A_Index%, j := A_Index+1, j := %v%%j%\n\t\t\tIf (%a%%i% > %a%%j%)\n\t\t\t\tunSorted := 1\n\t\t}\n\t}\n\tLoop % a0\n\t\ti := v%A_Index%, sorted .= \",\" . a%i%\n\tReturn SubStr(sorted,2)\n}\n\nQuickSort(var)\n{\n\tStringSplit, list, var, `,\n\tIf (list0 <= 1)\n\t\tReturn list\n\tpivot := list1\n\tLoop, Parse, var, `,\n\t{\n\t\tIf (A_LoopField < pivot)\n\t\t\tless .= \",\" . A_LoopField\n\t\tElse If (A_LoopField > pivot)\n\t\t\tmore .= \",\" . A_LoopField\n\t\tElse\n\t\t\tpivotlist .= \",\" . A_LoopField\n\t}\n\tless := QuickSort(substr(less,2))\n\tmore := QuickSort(substr(more,2))\n\tReturn substr(less,2) . pivotList . more\n}\n\nSelectionSort(var) {\n\tStringSplit, a, var, `,\n\tLoop % a0-1 {\n\t\ti := A_Index, mn := a%i%, j := m := i\n\t\tLoop % a0-i {\n\t\t\tj++\n\t\t\tIf (a%j% < mn)\n\t\t\t\tmn := a%j%, m := j\n\t\t}\n\t\tt := a%i%, a%i% := a%m%, a%m% := t\n\t}\n\tLoop % a0\n\t\tsorted .= \",\" . a%A_Index%\n\tReturn SubStr(sorted,2)\n}\n\nShellSort(var) {\n\tStringSplit, a, var, `,\n\tinc := a0\n\tWhile inc:=round(inc/2.2)\n\t\tLoop % a0-inc {\n\t\t\ti := A_Index+inc, t := a%i%, j := i, k := j-inc\n\t\t\tWhile j > inc && a%k% > t\n\t\t\t\ta%j% := a%k%, j := k, k -= inc\n\t\t\ta%j% := t\n\t\t}\n\tLoop % a0\n\t\ts .= \",\" . a%A_Index%\n\tReturn SubStr(s,2)\n}\n\nBuiltInSort(var) {\n\tSort, var, N D`,\n\tReturn var\n}\n", "language": "AutoHotkey" }, { "code": " HIMEM = PAGE + 2000000\n INSTALL @lib$+\"SORTLIB\"\n INSTALL @lib$+\"TIMERLIB\"\n Sort% = FN_sortinit(0,0)\n Timer% = FN_ontimer(1000, PROCtimer, 1)\n\n PRINT \"Array size:\", 1000, 10000, 100000\n @% = &2020A\n\n FOR patt% = 1 TO 4\n CASE patt% OF\n WHEN 1: PRINT '\"Data set to all ones:\"\n WHEN 2: PRINT '\"Data ascending sequence:\"\n WHEN 3: PRINT '\"Data randomly shuffled:\"\n WHEN 4: PRINT '\"Data descending sequence:\"\n ENDCASE\n\n FOR type% = 1 TO 6\n CASE type% OF\n WHEN 1: PRINT \"Internal (lib)\";\n WHEN 2: PRINT \"Quicksort \";\n WHEN 3: PRINT \"Radix sort \";\n WHEN 4: PRINT \"Shellsort \";\n WHEN 5: PRINT \"Bubblesort \";\n WHEN 6: PRINT \"Insertion sort\";\n ENDCASE\n\n FOR power% = 3 TO 5\n PROCsorttest(patt%, type%, 10^power%)\n NEXT\n PRINT\n\n NEXT type%\n NEXT patt%\n END\n\n DEF PROCsorttest(patt%, type%, size%)\n LOCAL a%(), C%, I%\n DIM a%(size%-1)\n\n CASE patt% OF\n WHEN 1: a%() = 1 : a%() = 1\n WHEN 2: FOR I% = 0 TO size%-1 : a%(I%) = I% : NEXT\n WHEN 3: FOR I% = 0 TO size%-1 : a%(I%) = I% : NEXT\n C% = RND(-123456) : REM Seed\n FOR I% = size% TO 2 STEP -1 : SWAP a%(I%-1),a%(RND(I%)-1) : NEXT\n WHEN 4: FOR I% = 0 TO size%-1 : a%(I%) = size%-1-I% : NEXT\n ENDCASE\n\n Start% = TIME\n ON ERROR LOCAL PRINT , \" >100.00\" ; : ENDPROC\n CASE type% OF\n WHEN 1: C% = size% : CALL Sort%, a%(0)\n WHEN 2: PROCquicksort(a%(), 0, size%)\n WHEN 3: PROCradixsort(a%(), size%, 10)\n WHEN 4: PROCshellsort(a%(), size%)\n WHEN 5: PROCbubblesort(a%(), size%)\n WHEN 6: PROCinsertionsort(a%(), size%)\n ENDCASE\n PRINT , (TIME - Start%)/100;\n\n FOR I% = 0 TO size%-2\n IF a%(I%) > a%(I%+1) ERROR 100, \"Sort failed!\"\n NEXT\n ENDPROC\n\n DEF PROCtimer\n Start% += 0\n IF (TIME - Start%) > 10000 ERROR 111, \"\"\n ENDPROC\n\n DEF PROCbubblesort(a%(), n%)\n LOCAL i%, l%\n REPEAT\n l% = 0\n FOR i% = 1 TO n%-1\n IF a%(i%-1) > a%(i%) THEN\n SWAP a%(i%-1),a%(i%)\n l% = i%\n ENDIF\n NEXT\n n% = l%\n UNTIL l% = 0\n ENDPROC\n\n DEF PROCinsertionsort(a%(), n%)\n LOCAL i%, j%, t%\n FOR i% = 1 TO n%-1\n t% = a%(i%)\n j% = i%\n WHILE j%>0 AND t%<a%(ABS(j%-1))\n a%(j%) = a%(j%-1)\n j% -= 1\n ENDWHILE\n a%(j%) = t%\n NEXT\n ENDPROC\n\n DEF PROCquicksort(a%(), s%, n%)\n LOCAL l%, p%, r%, t%\n IF n% < 2 THEN ENDPROC\n t% = s% + n% - 1\n l% = s%\n r% = t%\n p% = a%((l% + r%) DIV 2)\n REPEAT\n WHILE a%(l%) < p% l% += 1 : ENDWHILE\n WHILE a%(r%) > p% r% -= 1 : ENDWHILE\n IF l% <= r% THEN\n SWAP a%(l%), a%(r%)\n l% += 1\n r% -= 1\n ENDIF\n UNTIL l% > r%\n IF s% < r% PROCquicksort(a%(), s%, r% - s% + 1)\n IF l% < t% PROCquicksort(a%(), l%, t% - l% + 1 )\n ENDPROC\n\n DEF PROCshellsort(a%(), n%)\n LOCAL h%, i%, j%, k%\n h% = n%\n WHILE h%\n IF h% = 2 h% = 1 ELSE h% DIV= 2.2\n FOR i% = h% TO n% - 1\n k% = a%(i%)\n j% = i%\n WHILE j% >= h% AND k% < a%(ABS(j% - h%))\n a%(j%) = a%(j% - h%)\n j% -= h%\n ENDWHILE\n a%(j%) = k%\n NEXT\n ENDWHILE\n ENDPROC\n\n DEF PROCradixsort(a%(), n%, r%)\n LOCAL d%, e%, i%, l%, m%, b%(), bucket%()\n DIM b%(DIM(a%(),1)), bucket%(r%-1)\n FOR i% = 0 TO n%-1\n IF a%(i%) < l% l% = a%(i%)\n IF a%(i%) > m% m% = a%(i%)\n NEXT\n a%() -= l%\n m% -= l%\n e% = 1\n WHILE m% DIV e%\n bucket%() = 0\n FOR i% = 0 TO n%-1\n bucket%(a%(i%) DIV e% MOD r%) += 1\n NEXT\n FOR i% = 1 TO r%-1\n bucket%(i%) += bucket%(i% - 1)\n NEXT\n FOR i% = n%-1 TO 0 STEP -1\n d% = a%(i%) DIV e% MOD r%\n bucket%(d%) -= 1\n b%(bucket%(d%)) = a%(i%)\n NEXT\n a%() = b%()\n e% *= r%\n ENDWHILE\n a%() += l%\n ENDPROC\n", "language": "BBC-BASIC" }, { "code": "#ifndef _CSEQUENCE_H\n#define _CSEQUENCE_H\n#include <stdlib.h>\n\nvoid setfillconst(double c);\nvoid fillwithconst(double *v, int n);\nvoid fillwithrrange(double *v, int n);\nvoid shuffledrange(double *v, int n);\n#endif\n", "language": "C" }, { "code": "#include \"csequence.h\"\n\nstatic double fill_constant;\n\nvoid setfillconst(double c)\n{\n fill_constant = c;\n}\n\nvoid fillwithconst(double *v, int n)\n{\n while( --n >= 0 ) v[n] = fill_constant;\n}\n\nvoid fillwithrrange(double *v, int n)\n{\n int on = n;\n while( --on >= 0 ) v[on] = n - on;\n}\n\nvoid shuffledrange(double *v, int n)\n{\n int on = n;\n fillwithrrange(v, n);\n while( --n >= 0 ) {\n int r = rand() % on;\n double t = v[n];\n v[n] = v[r];\n v[r] = t;\n }\n}\n", "language": "C" }, { "code": "#ifndef _WRITETIMINGS_H\n#define _WRITETIMINGS_H\n#include \"sorts.h\"\n#include \"csequence.h\"\n#include \"timeit.h\"\n\n/* we repeat the same MEANREPEAT times, and get the mean; this *should*\n give \"better\" results ... */\n#define MEANREPEAT 10.0\n#define BUFLEN 128\n#define MAKEACTION(ALGO) \\\n int action_ ## ALGO (int size) {\t\t\t\t\\\n ALGO ## _sort(tobesorted, size);\t\t\t\t\\\n return 0; }\n#define MAKEPIECE(N) { #N , action_ ## N }\n\nint action_bubble(int size);\nint action_shell(int size);\nint action_quick(int size);\nint action_insertion(int size);\nint action_merge(int size);\nint doublecompare( const void *a, const void *b );\nint action_qsort(int size);\nint get_the_longest(int *a);\n\nstruct testpiece\n{\n const char *name;\n int (*action)(int);\n};\ntypedef struct testpiece testpiece_t;\n\nstruct seqdef\n{\n const char *name;\n void (*seqcreator)(double *, int);\n};\ntypedef struct seqdef seqdef_t;\n#endif\n", "language": "C" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n\n#include \"writetimings.h\"\n\ndouble *tobesorted = NULL;\nconst char *bname = \"data_\";\nconst char *filetempl = \"%s%s_%s.dat\";\nint datlengths[] = {100, 200, 300, 500, 1000, 5000, 10000, 50000, 100000};\n\ntestpiece_t testpieces[] =\n{\n// MAKEPIECE(bubble),\n MAKEPIECE(shell),\n MAKEPIECE(merge),\n MAKEPIECE(insertion),\n MAKEPIECE(quick),\n MAKEPIECE(qsort),\n { NULL, NULL }\n};\n\nseqdef_t seqdefs[] =\n{\n { \"c1\", fillwithconst },\n { \"rr\", fillwithrrange },\n { \"sr\", shuffledrange },\n { NULL, NULL }\n};\n\n\nMAKEACTION(bubble)\nMAKEACTION(insertion)\nMAKEACTION(quick)\nMAKEACTION(shell)\n\nint action_merge(int size)\n{\n double *res = merge_sort(tobesorted, size);\n free(res); /* unluckly this affects performance */\n return 0;\n}\n\nint doublecompare( const void *a, const void *b )\n{\n if ( *(const double *)a < *(const double *)b ) return -1;\n else return *(const double *)a > *(const double *)b;\n}\nint action_qsort(int size)\n{\n qsort(tobesorted, size, sizeof(double), doublecompare);\n return 0;\n}\n\nint get_the_longest(int *a)\n{\n int r = *a;\n while( *a > 0 ) {\n if ( *a > r ) r = *a;\n a++;\n }\n return r;\n}\n\n\nint main()\n{\n int i, j, k, z, lenmax;\n char buf[BUFLEN];\n FILE *out;\n double thetime;\n\n lenmax = get_the_longest(datlengths);\n printf(\"Bigger data set has %d elements\\n\", lenmax);\n tobesorted = malloc(sizeof(double)*lenmax);\n if ( tobesorted == NULL ) return 1;\n\n setfillconst(1.0);\n\n for(i=0; testpieces[i].name != NULL; i++) {\n for(j=0; seqdefs[j].name != NULL; j++) {\n snprintf(buf, BUFLEN, filetempl, bname, testpieces[i].name,\n\t seqdefs[j].name);\n out = fopen(buf, \"w\");\n if ( out == NULL ) goto severe;\n printf(\"Producing data for sort '%s', created data type '%s'\\n\",\n\t testpieces[i].name, seqdefs[j].name);\n for(k=0; datlengths[k] > 0; k++) {\n\tprintf(\"\\tNumber of elements: %d\\n\", datlengths[k]);\n\tthetime = 0.0;\n\tseqdefs[j].seqcreator(tobesorted, datlengths[k]);\n\tfprintf(out, \"%d \", datlengths[k]);\n\tfor(z=0; z < MEANREPEAT; z++) {\n\t thetime += time_it(testpieces[i].action, datlengths[k]);\n\t}\n\tthetime /= MEANREPEAT;\n\tfprintf(out, \"%.8lf\\n\", thetime);\n }\n fclose(out);\n }\n }\nsevere:\n free(tobesorted);\n return 0;\n}\n", "language": "C" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include \"polifitgsl.h\"\n\n#define MAXNUMOFDATA 100\n\ndouble x[MAXNUMOFDATA], y[MAXNUMOFDATA];\ndouble cf[2];\n\nint main()\n{\n int i, nod;\n int r;\n\n for(i=0; i < MAXNUMOFDATA; i++)\n {\n r = scanf(\"%lf %lf\\n\", &x[i], &y[i]);\n if ( (r == EOF) || (r < 2) ) break;\n x[i] = log10(x[i]);\n y[i] = log10(y[i]);\n }\n nod = i;\n\n polynomialfit(nod, 2, x, y, cf);\n printf(\"C0 = %lf\\nC1 = %lf\\n\", cf[0], cf[1]);\n\n return 0;\n}\n", "language": "C" }, { "code": "import std.stdio, std.algorithm, std.container, std.datetime,\n std.random, std.typetuple;\n\nimmutable int[] allOnes, sortedData, randomData;\n\nstatic this() { // Initialize global Arrays.\n immutable size_t arraySize = 10_000;\n\n allOnes = new int[arraySize];\n //allOnes[] = 1;\n foreach (ref d; allOnes)\n d = 1;\n\n sortedData = new int[arraySize];\n foreach (immutable i, ref d; sortedData)\n d = i;\n\n randomData = new int[arraySize];\n foreach (ref d; randomData)\n d = uniform(0, int.max);\n}\n\n// BubbleSort:\n\nvoid bubbleSort(T)(T[] list) {\n for (int i = list.length - 1; i > 0; i--)\n for (int j = i -1; j >= 0; j--)\n if (list[i] < list[j])\n swap(list[i], list[j]);\n}\n\nvoid allOnesBubble() {\n auto data = allOnes.dup;\n data.bubbleSort;\n assert(data.isSorted);\n}\n\nvoid sortedBubble() {\n auto data = sortedData.dup;\n data.bubbleSort;\n assert(data.isSorted);\n}\n\nvoid randomBubble() {\n auto data = randomData.dup;\n data.bubbleSort;\n assert(data.isSorted);\n}\n\n// InsertionSort:\n\nvoid insertionSort(T)(T[] list) {\n foreach (immutable i, currElem; list) {\n size_t j = i;\n for (; j > 0 && currElem < list[j - 1]; j--)\n list[j] = list[j - 1];\n list[j] = currElem;\n }\n}\n\nvoid allOnesInsertion() {\n auto data = allOnes.dup;\n data.insertionSort;\n assert(data.isSorted);\n}\n\nvoid sortedInsertion() {\n auto data = sortedData.dup;\n data.insertionSort;\n assert(data.isSorted);\n}\n\nvoid randomInsertion() {\n auto data = randomData.dup;\n data.insertionSort;\n assert(data.isSorted);\n}\n\n// HeapSort:\n\nvoid heapSort(T)(T[] data) {\n auto h = data.heapify;\n while (!h.empty)\n h.removeFront;\n}\n\nvoid allOnesHeap() {\n auto data = allOnes.dup;\n data.heapSort;\n assert(data.isSorted);\n}\n\nvoid sortedHeap() {\n auto data = sortedData.dup;\n data.heapSort;\n assert(data.isSorted);\n}\n\nvoid randomHeap() {\n auto data = randomData.dup;\n data.heapSort;\n assert(data.isSorted);\n}\n\n// Built-in sort:\n\nvoid allOnesBuiltIn() {\n auto data = allOnes.dup;\n data.sort!q{a < b};\n assert(data.isSorted);\n}\n\nvoid sortedBuiltIn() {\n auto data = sortedData.dup;\n data.sort!q{a < b};\n assert(data.isSorted);\n}\n\nvoid randomBuiltIn() {\n auto data = randomData.dup;\n data.sort!q{a < b};\n assert(data.isSorted);\n}\n\nstatic void show(in TickDuration[4u] r) {\n alias args = TypeTuple!(\"usecs\", int);\n writefln(\" Bubble Sort: %10d\", r[0].to!args);\n writefln(\" Insertion Sort: %10d\", r[1].to!args);\n writefln(\" Heap Sort: %10d\", r[3].to!args);\n writefln(\" Built-in Sort: %10d\", r[2].to!args);\n}\n\nvoid main() {\n enum nRuns = 100;\n writeln(\"Timings in microseconds:\");\n\n writeln(\" Testing against all ones:\");\n nRuns.benchmark!(allOnesBubble, allOnesInsertion,\n allOnesHeap, allOnesBuiltIn).show;\n\n writeln(\"\\n Testing against sorted data.\");\n nRuns.benchmark!(sortedBubble, sortedInsertion,\n sortedHeap, sortedBuiltIn).show;\n\n writeln(\"\\n Testing against random data.\");\n nRuns.benchmark!(randomBubble, randomInsertion,\n randomHeap, randomBuiltIn).show;\n}\n", "language": "D" }, { "code": "-module( compare_sorting_algorithms ).\n\n-export( [task/0] ).\n\ntask() ->\n\tNs = [100, 1000, 10000],\n\tLists = [{\"ones\", fun list_of_ones/1, Ns}, {\"ranges\", fun list_of_ranges/1, Ns}, {\"reversed_ranges\", fun list_of_reversed_ranges/1, Ns}, {\"shuffleds\", fun list_of_shuffleds/1, Ns}],\n\tSorts = [{bubble_sort, fun bubble_sort:list/1}, {insertion_sort, fun sort:insertion/1}, {iquick_sort, fun quicksort:qsort/1}],\n\tResults = [time_list(X, Sorts) || X <- Lists],\n\t[file:write_file(X++\".png\", egd_chart:graph(Y, [{x_label, \"log N\"}, {y_label, \"log ms\"}])) || {X, Y} <- Results].\n\n\nlist_of_ones( N ) -> [1 || _X <- lists:seq(1, N)].\nlist_of_ranges( N ) -> [X || X <- lists:seq(1, N)].\nlist_of_reversed_ranges( N ) -> lists:reverse( list_of_ranges(N) ).\nlist_of_shuffleds( N ) -> [random:uniform(N) || _X <- lists:seq(1, N)].\n\ntime_list( {List, List_fun, Values}, Sorts ) ->\n\tResults = [{Sort, time_sort(Sort_fun, List_fun, Values)} || {Sort, Sort_fun} <- Sorts],\n\t{List, Results}.\n\ntime_sort( Sort_fun, List_fun, Values ) ->\n\t[time(Sort_fun, List_fun, X) || X <- Values].\n\ntime( Fun, List_fun, N ) ->\n\t{Time, _Result} = timer:tc( fun() -> Fun( List_fun(N) ) end ),\n\t{math:log10(N), math:log10(Time)}.\n", "language": "Erlang" }, { "code": "#Macro sort_1(sortname)\n Rset buffer, #sortname\n Print buffer;\n copy_array(rev(), sort())\n t1 = Timer\n sortname(sort())\n t2 = Timer - t1\n Print Using \" ###.###&\"; t2; \" sec\";\n copy_array(ran(), sort())\n t1 = Timer\n sortname(sort())\n t2 = Timer - t1\n Print Using \" ###.###&\"; t2; \" sec\";\n t1 = Timer\n sortname(sort())\n t2 = Timer - t1\n Print Using \" ###.###&\"; t2; \" sec\";\n copy_array(eq(), sort())\n t1 = Timer\n sortname(sort())\n t2 = Timer - t1\n Print Using \" ###.###&\"; t2; \" sec\"\n#EndMacro\n\n#Macro sort_2(sortname)\n Rset buffer, #sortname\n Print buffer;\n copy_array(rev(), sort())\n t1 = Timer\n sortname(sort(), Lbound(sort), Ubound(sort))\n t2 = Timer - t1\n Print Using \" ###.###&\"; t2; \" sec\";\n copy_array(ran(), sort())\n t1 = Timer\n sortname(sort(), Lbound(sort), Ubound(sort))\n t2 = Timer - t1\n Print Using \" ###.###&\"; t2; \" sec\";\n t1 = Timer\n sortname(sort(), Lbound(sort), Ubound(sort))\n t2 = Timer - t1\n Print Using \" ###.###&\"; t2; \" sec\";\n copy_array(eq(),sort())\n t1 = Timer\n sortname(sort(), Lbound(sort), Ubound(sort))\n t2 = Timer - t1\n Print Using \" ###.###&\"; t2; \" sec\"\n#EndMacro\n\n\nSub bubbleSort(array() As Double)\n Dim As Integer i, lb = Lbound(array), ub = Ubound(array)\n\n For p1 As Uinteger = 0 To ub - 1\n For p2 As Uinteger = p1 + 1 To ub\n 'change >= to > , don't swap if they are equal\n If (array(p1)) > (array(p2)) Then Swap array(p1), array(p2)\n Next p2\n Next p1\n For i = lb To ub - 1\n If array(i) > array(i + 1) Then Beep\n Next\nEnd Sub\n\nSub exchangeSort(array() As Double)\n Dim As Uinteger i, j, min, ub = Ubound(array)\n For i = 0 To ub\n min = i\n For j = i+1 To ub\n If (array(j) < array(min)) Then min = j\n Next j\n If min > i Then Swap array(i), array(min)\n Next i\nEnd Sub\n\nSub insertionSort(array() As Double)\n Dim As Uinteger ub = Ubound(array)\n Dim As Uinteger i, j, temp, temp2\n\n For i = 1 To ub\n temp = array(i)\n temp2 = temp\n j = i\n While j >= 1 Andalso array(j-1) > temp2\n array(j) = array(j - 1)\n j -= 1\n Wend\n array(j) = temp\n Next i\nEnd Sub\n\nSub siftdown(hs() As Double, inicio As Ulong, final As Ulong)\n Dim As Ulong root = inicio\n Dim As Long lb = Lbound(hs)\n\n While root * 2 + 1 <= final\n Dim As Ulong child = root * 2 + 1\n If (child + 1 <= final) Andalso (hs(lb + child) < hs(lb + child + 1)) Then child += 1\n If hs(lb + root) < hs(lb + child) Then\n Swap hs(lb + root), hs(lb + child)\n root = child\n Else\n Return\n End If\n Wend\nEnd Sub\nSub heapSort(array() As Double)\n Dim As Long lb = Lbound(array)\n\n Dim As Ulong count = Ubound(array) - lb + 1\n Dim As Long inicio = (count - 2) \\ 2\n Dim As Ulong final = count - 1\n\n While inicio >= 0\n siftdown(array(), inicio, final)\n inicio -= 1\n Wend\n\n While final > 0\n Swap array(lb + final), array(lb)\n final -= 1\n siftdown(array(), 0, final)\n Wend\nEnd Sub\n\nSub shellSort(array() As Double)\n Dim As Uinteger lb = Lbound(array), ub = Ubound(array)\n Dim As Uinteger i, inc = ub - lb\n Dim As Boolean done\n\n Do\n inc = Int(inc / 2.2)\n If inc < 1 Then inc = 1\n\n Do\n done = false\n For i = lb To ub - inc\n ' reemplace \"<\" con \">\" para ordenación descendente\n If array(i) > array(i + inc) Then\n Swap array(i), array(i + inc)\n done = true\n End If\n Next i\n Loop Until done = false\n Loop Until inc = 1\nEnd Sub\n\nSub quickSort(array() As Double, l As Integer, r As Integer)\n Dim As Uinteger size = r - l +1\n If size < 2 Then Exit Sub\n\n Dim As Integer i = l, j = r\n Dim As Double pivot = array(l + size \\ 2)\n\n Do\n While array(i) < pivot\n i += 1\n Wend\n While pivot < array(j)\n j -= 1\n Wend\n If i <= j Then\n Swap array(i), array(j)\n i += 1\n j -= 1\n End If\n Loop Until i > j\n\n If l < j Then quickSort(array(), l, j)\n If i < r Then quickSort(array(), i, r)\nEnd Sub\n\nSub rapidSort (array()As Double, inicio As Integer, final As Integer)\n Dim As Integer n, wert, nptr, arr, rep\n Dim As Integer LoVal = array(inicio), HiVal = array(final)\n For n = inicio To final\n If LoVal> array(n) Then LoVal = array(n)\n If HiVal< array(n) Then HiVal = array(n)\n Next\n Redim SortArray(LoVal To HiVal) As Double\n For n = inicio To final\n wert = array(n)\n SortArray(wert) += 1\n Next\n nptr = inicio-1\n For arr = LoVal To HiVal\n rep = SortArray(arr)\n For n = 1 To rep\n nptr += 1\n array(nptr) = arr\n Next\n Next\n Erase SortArray\nEnd Sub\n\nSub copy_array(s() As Double, d() As Double)\n For x As Integer = Lbound(s) To Ubound(s)\n d(x) = s(x)\n Next\nEnd Sub\n\n\nDim As Integer x, max = 1e5\nDim As Double t1, t2, ran(0 To max), sort(0 To max), rev(0 To max), eq(0 To max)\nDim As String buffer = Space(14)\n\nCls\n' fill ran() with random numbers and eq() with same number\nFor x = 0 To max\n ran(x) = Rnd\n rev(x) = ran(x) ' make reverse array equal to random array\n eq(x) = 1/3\nNext x\n\nFor x = Lbound(rev) To (Ubound(rev) \\ 2)\n Swap rev(x), rev(Ubound(rev) - x)\nNext x\n\nPrint !\"Test times in sec\\nArray size =\"; max\nPrint !\"\\n *Reversed* *Random* *Sorted* *All ones*\"\n\nsort_1(bubbleSort)\nsort_1(exchangeSort)\nsort_1(insertionSort)\nsort_1(heapSort)\nsort_1(shellSort)\nsort_2(quickSort)\nsort_2(rapidSort)\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"log\"\n \"math/rand\"\n \"testing\"\n \"time\"\n\n \"github.com/gonum/plot\"\n \"github.com/gonum/plot/plotter\"\n \"github.com/gonum/plot/plotutil\"\n \"github.com/gonum/plot/vg\"\n)\n\n// Step 1, sort routines.\n// These functions are copied without changes from the RC tasks Bubble Sort,\n// Insertion sort, and Quicksort.\n\nfunc bubblesort(a []int) {\n for itemCount := len(a) - 1; ; itemCount-- {\n hasChanged := false\n for index := 0; index < itemCount; index++ {\n if a[index] > a[index+1] {\n a[index], a[index+1] = a[index+1], a[index]\n hasChanged = true\n }\n }\n if hasChanged == false {\n break\n }\n }\n}\n\nfunc insertionsort(a []int) {\n for i := 1; i < len(a); i++ {\n value := a[i]\n j := i - 1\n for j >= 0 && a[j] > value {\n a[j+1] = a[j]\n j = j - 1\n }\n a[j+1] = value\n }\n}\n\nfunc quicksort(a []int) {\n var pex func(int, int)\n pex = func(lower, upper int) {\n for {\n switch upper - lower {\n case -1, 0:\n return\n case 1:\n if a[upper] < a[lower] {\n a[upper], a[lower] = a[lower], a[upper]\n }\n return\n }\n bx := (upper + lower) / 2\n b := a[bx]\n lp := lower\n up := upper\n outer:\n for {\n for lp < upper && !(b < a[lp]) {\n lp++\n }\n for {\n if lp > up {\n break outer\n }\n if a[up] < b {\n break\n }\n up--\n }\n a[lp], a[up] = a[up], a[lp]\n lp++\n up--\n }\n if bx < lp {\n if bx < lp-1 {\n a[bx], a[lp-1] = a[lp-1], b\n }\n up = lp - 2\n } else {\n if bx > lp {\n a[bx], a[lp] = a[lp], b\n }\n up = lp - 1\n lp++\n }\n if up-lower < upper-lp {\n pex(lower, up)\n lower = lp\n } else {\n pex(lp, upper)\n upper = up\n }\n }\n }\n pex(0, len(a)-1)\n}\n\n// Step 2.0 sequence routines. 2.0 is the easy part. 2.5, timings, follows.\n\nfunc ones(n int) []int {\n s := make([]int, n)\n for i := range s {\n s[i] = 1\n }\n return s\n}\n\nfunc ascending(n int) []int {\n s := make([]int, n)\n v := 1\n for i := 0; i < n; {\n if rand.Intn(3) == 0 {\n s[i] = v\n i++\n }\n v++\n }\n return s\n}\n\nfunc shuffled(n int) []int {\n return rand.Perm(n)\n}\n\n// Steps 2.5 write timings, and 3 plot timings are coded together.\n// If write means format and output human readable numbers, step 2.5\n// is satisfied with the log output as the program runs. The timings\n// are plotted immediately however for step 3, not read and parsed from\n// any formated output.\nconst (\n nPts = 7 // number of points per test\n inc = 1000 // data set size increment per point\n)\n\nvar (\n p *plot.Plot\n sortName = []string{\"Bubble sort\", \"Insertion sort\", \"Quicksort\"}\n sortFunc = []func([]int){bubblesort, insertionsort, quicksort}\n dataName = []string{\"Ones\", \"Ascending\", \"Shuffled\"}\n dataFunc = []func(int) []int{ones, ascending, shuffled}\n)\n\nfunc main() {\n rand.Seed(time.Now().Unix())\n var err error\n p, err = plot.New()\n if err != nil {\n log.Fatal(err)\n }\n p.X.Label.Text = \"Data size\"\n p.Y.Label.Text = \"microseconds\"\n p.Y.Scale = plot.LogScale{}\n p.Y.Tick.Marker = plot.LogTicks{}\n p.Y.Min = .5 // hard coded to make enough room for legend\n\n for dx, name := range dataName {\n s, err := plotter.NewScatter(plotter.XYs{})\n if err != nil {\n log.Fatal(err)\n }\n s.Shape = plotutil.DefaultGlyphShapes[dx]\n p.Legend.Add(name, s)\n }\n for sx, name := range sortName {\n l, err := plotter.NewLine(plotter.XYs{})\n if err != nil {\n log.Fatal(err)\n }\n l.Color = plotutil.DarkColors[sx]\n p.Legend.Add(name, l)\n }\n for sx := range sortFunc {\n bench(sx, 0, 1) // for ones, a single timing is sufficient.\n bench(sx, 1, 5) // ascending and shuffled have some randomness though,\n bench(sx, 2, 5) // so average timings on 5 different random sets.\n }\n\n if err := p.Save(5*vg.Inch, 5*vg.Inch, \"comp.png\"); err != nil {\n log.Fatal(err)\n }\n}\n\nfunc bench(sx, dx, rep int) {\n log.Println(\"bench\", sortName[sx], dataName[dx], \"x\", rep)\n pts := make(plotter.XYs, nPts)\n sf := sortFunc[sx]\n for i := range pts {\n x := (i + 1) * inc\n // to avoid timing sequence creation, create sequence before timing\n // then just copy the data inside the timing loop. copy time should\n // be the same regardless of sequence data.\n s0 := dataFunc[dx](x) // reference sequence\n s := make([]int, x) // working copy\n var tSort int64\n for j := 0; j < rep; j++ {\n tSort += testing.Benchmark(func(b *testing.B) {\n for i := 0; i < b.N; i++ {\n copy(s, s0)\n sf(s)\n }\n }).NsPerOp()\n }\n tSort /= int64(rep)\n log.Println(x, \"items\", tSort, \"ns\") // step 2.5, write timings\n pts[i] = struct{ X, Y float64 }{float64(x), float64(tSort) * .001}\n }\n pl, ps, err := plotter.NewLinePoints(pts) // step 3, plot timings\n if err != nil {\n log.Fatal(err)\n }\n pl.Color = plotutil.DarkColors[sx]\n ps.Color = plotutil.DarkColors[sx]\n ps.Shape = plotutil.DefaultGlyphShapes[dx]\n p.Add(pl, ps)\n}\n", "language": "Go" }, { "code": "import Data.Time.Clock\nimport Data.List\n\ntype Time = Integer\ntype Sorter a = [a] -> [a]\n\n-- Simple timing function (in microseconds)\ntimed :: IO a -> IO (a, Time)\ntimed prog = do\n t0 <- getCurrentTime\n x <- prog\n t1 <- x `seq` getCurrentTime\n return (x, ceiling $ 1000000 * diffUTCTime t1 t0)\n\n-- testing sorting algorithm on a given set\ntest :: [a] -> Sorter a -> IO [(Int, Time)]\ntest set srt = mapM (timed . run) ns\n where\n ns = take 15 $ iterate (\\x -> (x * 5) `div` 3) 10\n run n = pure $ length $ srt (take n set)\n\n-- sample sets\nconstant = repeat 1\n\npresorted = [1..]\n\nrandom = (`mod` 100) <$> iterate step 42\n where\n step x = (x * a + c) `mod` m\n (a, c, m) = (1103515245, 12345, 2^31-1)\n", "language": "Haskell" }, { "code": "-- Naive quick sort\nqsort :: Ord a => Sorter a\nqsort [] = []\nqsort (h:t) = qsort (filter (< h) t) ++ [h] ++ qsort (filter (>= h) t)\n\n-- Bubble sort\nbsort :: Ord a => Sorter a\nbsort s = case _bsort s of\n t | t == s -> t\n | otherwise -> bsort t\n where _bsort (x:x2:xs) | x > x2 = x2:_bsort (x:xs)\n | otherwise = x :_bsort (x2:xs)\n _bsort s = s\n\n-- Insertion sort\nisort :: Ord a => Sorter a\nisort = foldr insert []\n", "language": "Haskell" }, { "code": "-- chart appears to be logarithmic scale on both axes\nbarChart :: Char -> [(Int, Time)] -> [String]\nbarChart ch lst = bar . scale <$> lst\n where\n scale (x,y) = (x, round $ (3*) $ log $ fromIntegral y)\n bar (x,y) = show x ++ \"\\t\" ++ replicate y ' ' ++ [ch]\n\nover :: String -> String -> String\nover s1 s2 = take n $ zipWith f (pad s1) (pad s2)\n where\n f ' ' c = c\n f c ' ' = c\n f y _ = y\n pad = (++ repeat ' ')\n n = length s1 `max` length s2\n\ncomparison :: Ord a => [Sorter a] -> [Char] -> [a] -> IO ()\ncomparison sortings chars set = do\n results <- mapM (test set) sortings\n let charts = zipWith barChart chars results\n putStrLn $ replicate 50 '-'\n mapM_ putStrLn $ foldl1 (zipWith over) charts\n putStrLn $ replicate 50 '-'\n let times = map (fromInteger . snd) <$> results\n let ratios = mean . zipWith (flip (/)) (head times) <$> times\n putStrLn \"Comparing average time ratios:\"\n mapM_ putStrLn $ zipWith (\\r s -> [s] ++ \": \" ++ show r) ratios chars\n where\n mean lst = sum lst / genericLength lst\n\nmain = do\n putStrLn \"comparing on list of ones\"\n run ones\n putStrLn \"\\ncomparing on presorted list\"\n run seqn\n putStrLn \"\\ncomparing on shuffled list\"\n run rand\n where\n run = comparison [sort, isort, qsort, bsort] \"siqb\"\n", "language": "Haskell" }, { "code": "NB. extracts from other rosetta code projects\nts=: 6!:2, 7!:2@]\nradix =: 3 : 0\n256 radix y\n:\na=. #{. z =. x #.^:_1 y\ne=. (-a) {.\"0 b =. i.x\nx#.1{::(<:@[;([: ; (b, {\"1) <@}./. e,]))&>/^:a [ z;~a-1\nNB. , ([: ; (b, {:\"1) <@(}:\"1@:}.)/. e,])^:(#{.z) y,.z\n)\nbubble=: (([ (<. , >.) {.@]) , }.@])/^:_\ninsertion=:((>: # ]) , [ , < #])/\nsel=: 1 : 'x # ['\nquick=: 3 : 0\n if. 1 >: #y do. y\n else.\n e=. y{~?#y\n (quick y <sel e),(y =sel e),quick y >sel e\n end.\n)\ngaps =: [: }: 1 (1+3*])^:(> {:)^:a:~ #\ninsert =: (I.~ {. ]) , [ , ] }.~ I.~\ngapinss =: #@] {. ,@|:@(] insert//.~ #@] $ i.@[)\nshell =: [: ; gapinss &.>/@(< ,~ ]&.>@gaps)\nbuiltin =: /:~\n\n\n\nNB. characterization of the sorting algorithms.\n\nsorts =: bubble`insertion`shell`quick`radix`builtin\ngenerators =: #&1`(i.@-)`(?.~) NB. data generators\n\nround =: [: <. 1r2&+\n\nll =: (<_1 0)&{ NB. verb to extract lower left which holds ln data length\nlc =: (<_1 1)&{ NB. verb to fetch lower center which holds most recent time\n\nNB. maximum_time characterize ln_start_size\nNB. characterize returns a rank 4 matrix with successive indexes for\nNB. algorithm, input arrangement, max number of tests in group, length time space\ncharacterize =: 4 : 0\n max_time =. x\n start =. 1 3{.<:y\n for_sort. sorts do.\n for_generator. generators do. NB. limit time and paging prevention\n t =: }. (, (, [: ts '[email protected] ([email protected])' , \":@round@^)@>:@ll) ^: ((lc < max_time\"_) *. ll < 17\"_) ^:_ start\n if. generator -: {.generators do.\n g =. ,:t\n else.\n g =. g,t\n end.\n end.\n if. sort -: {.sorts do.\n s =. ,:g\n else.\n s =. s,g\n end.\n end.\n)\n\nNB. character cell graphics\n\nNB. From j phrases 10E. Approximation\nd3=: 1&,.@[ %.~ ]\tNB. a and b such that y is approx. a + b*x\n\nNB. domain and range 0 to 14.\nD=:14\n\nplot =: 1 : '(=/ round@(u&.(*&(D%<:y))))i.y' NB. function plot size\npoints =: 4 : '1(<\"1|:|.round y*D%~<:x)}0$~2#x' NB. size points x,:y\n\nshow =: [: |. [: '0'&~:@{:} ' ' ,: \":\n\nplt =: 3 : 0\n30 plt y NB. default size 30\n:\nn =. >:i.-# experiments =. <@(#~\"1 (0&<)@{.)\"2 y\npts =. n +./ .*x&points@>experiments\ncoef =. d3/@>experiments\n(_*pts) + n +./ .*1 0 2|:coef&(p.\"1) plot x\n)\n", "language": "J" }, { "code": "function swap(a, i, j){\n var t = a[i]\n a[i] = a[j]\n a[j] = t\n}\n\n// Heap Sort\n\nfunction heap_sort(a){\n var n = a.length\n\n function heapify(i){\n var t = a[i]\n while (true){\n var l = 2 * i + 1, r = l + 1\n var m = r < n ? (a[l] > a[r] ? l : r) : (l < n ? l : i)\n if (m != i && a[m] > t){\n a[i] = a[m]\n i = m\n }\n else{\n break\n }\n }\n a[i] = t;\n }\n\n for (let i = Math.floor(n / 2) - 1; i >= 0; i--){\n heapify(i)\n }\n\n for (let i = n - 1; i >= 1; i--){\n swap(a, 0, i)\n n--\n heapify(0)\n }\n}\n\n// Merge Sort\n\nfunction merge_sort(a){\n var b = new Array(a.length)\n\n function rec(l, r){\n if (l < r){\n var m = Math.floor((l + r) / 2)\n rec(l, m)\n rec(m + 1, r)\n\n var i = l, j = m + 1, k = 0;\n\n while (i <= m && j <= r) b[k++] = (a[i] > a[j] ? a[j++] : a[i++])\n while (j <= r) b[k++] = a[j++]\n while (i <= m) b[k++] = a[i++]\n\n for (k = l; k <= r; k++){\n a[k] = b[k - l]\n }\n }\n }\n\n rec(0, a.length-1)\n}\n\n// Quick Sort\n\nfunction quick_sort(a){\n function rec(l, r){\n if (l < r){\n var p = a[l + Math.floor((r - l + 1)*Math.random())]\n\n var i = l, j = l, k = r\n while (j <= k){\n if (a[j] < p){\n swap(a, i++, j++)\n }\n else if (a[j] > p){\n swap(a, j, k--)\n }\n else{\n j++\n }\n }\n\n rec(l, i - 1)\n rec(k + 1, r)\n }\n }\n\n rec(0, a.length - 1)\n}\n\n// Shell Sort\n\nfunction shell_sort(a){\n var n = a.length\n var gaps = [100894, 44842, 19930, 8858, 3937, 1750, 701, 301, 132, 57, 23, 10, 4, 1]\n\n for (let x of gaps){\n for (let i = x; i < n; i++){\n var t = a[i], j;\n for (j = i; j >= x && a[j - x] > t; j -= x){\n a[j] = a[j - x];\n }\n a[j] = t;\n }\n }\n}\n\n// Comb Sort (+ Insertion sort optimization)\n\nfunction comb_sort(a){\n var n = a.length\n\n for (let x = n; x >= 10; x = Math.floor(x / 1.3)){\n for (let i = 0; i + x < n; i++){\n if (a[i] > a[i + x]){\n swap(a, i, i + x)\n }\n }\n }\n\n for (let i = 1; i < n; i++){\n var t = a[i], j;\n for (j = i; j > 0 && a[j - 1] > t; j--){\n a[j] = a[j - 1]\n }\n a[j] = t;\n }\n}\n\n// Test\n\nfunction test(f, g, e){\n var res = \"\"\n\n for (let n of e){\n var a = new Array(n)\n\n var s = 0\n for (let k = 0; k < 10; k++){\n for (let i = 0; i < n; i++){\n a[i] = g(i)\n }\n\n var start = Date.now()\n f(a)\n\n s += Date.now() - start\n }\n\n res += Math.round(s / 10) + \"\\t\"\n }\n\n return res\n}\n\n// Main\n\nvar e = [5000, 10000, 100000, 500000, 1000000, 2000000]\n\nvar sOut = \"Test times in ms\\n\\nElements\\t\" + e.join(\"\\t\") + \"\\n\\n\"\n\nsOut += \"*All ones*\\n\"\nsOut += \"heap_sort\\t\" + test(heap_sort, (x => 1), e) + \"\\n\"\nsOut += \"quick_sort\\t\" + test(quick_sort, (x => 1), e) + \"\\n\"\nsOut += \"merge_sort\\t\" + test(merge_sort, (x => 1), e) + \"\\n\"\nsOut += \"shell_sort\\t\" + test(shell_sort, (x => 1), e) + \"\\n\"\nsOut += \"comb_sort\\t\" + test(comb_sort, (x => 1), e) + \"\\n\\n\"\n\nsOut += \"*Sorted*\\n\"\nsOut += \"heap_sort\\t\" + test(heap_sort, (x => x), e) + \"\\n\"\nsOut += \"quick_sort\\t\" + test(quick_sort, (x => x), e) + \"\\n\"\nsOut += \"merge_sort\\t\" + test(merge_sort, (x => x), e) + \"\\n\"\nsOut += \"shell_sort\\t\" + test(shell_sort, (x => x), e) + \"\\n\"\nsOut += \"comb_sort\\t\" + test(comb_sort, (x => x), e) + \"\\n\\n\"\n\nsOut += \"*Random*\\n\"\nsOut += \"heap_sort\\t\" + test(heap_sort, (x => Math.random()), e) + \"\\n\"\nsOut += \"quick_sort\\t\" + test(quick_sort, (x => Math.random()), e) + \"\\n\"\nsOut += \"merge_sort\\t\" + test(merge_sort, (x => Math.random()), e) + \"\\n\"\nsOut += \"shell_sort\\t\" + test(shell_sort, (x => Math.random()), e) + \"\\n\"\nsOut += \"comb_sort\\t\" + test(comb_sort, (x => Math.random()), e) + \"\\n\"\n\nconsole.log(sOut)\n", "language": "JavaScript" }, { "code": "function comparesorts(tosort)\n a = shuffle([\"i\", \"m\", \"q\"])\n iavg = mavg = qavg = 0.0\n for c in a\n if c == \"i\"\n iavg = sum(i -> @elapsed(sort(tosort, alg=InsertionSort)), 1:100) / 100.0\n elseif c == \"m\"\n mavg = sum(i -> @elapsed(sort(tosort, alg=MergeSort)), 1:100) / 100.0\n elseif c == \"q\"\n qavg = sum(i -> @elapsed(sort(tosort, alg=QuickSort)), 1:100) / 100.0\n end\n end\n iavg, mavg, qavg\nend\n\nallones = fill(1, 40000)\nsequential = collect(1:40000)\nrandomized = collect(shuffle(1:40000))\n\ncomparesorts(allones)\ncomparesorts(allones)\niavg, mavg, qavg = comparesorts(allones)\nprintln(\"Average sort times for 40000 ones:\")\nprintln(\"\\tinsertion sort:\\t$iavg\\n\\tmerge sort:\\t$mavg\\n\\tquick sort\\t$qavg\")\n\ncomparesorts(sequential)\ncomparesorts(sequential)\niavg, mavg, qavg = comparesorts(sequential)\nprintln(\"Average sort times for 40000 presorted:\")\nprintln(\"\\tinsertion sort:\\t$iavg\\n\\tmerge sort:\\t$mavg\\n\\tquick sort\\t$qavg\")\n\ncomparesorts(randomized)\ncomparesorts(randomized)\niavg, mavg, qavg = comparesorts(randomized)\nprintln(\"Average sort times for 40000 randomized:\")\nprintln(\"\\tinsertion sort:\\t$iavg\\n\\tmerge sort:\\t$mavg\\n\\tquick sort\\t$qavg\")\n", "language": "Julia" }, { "code": "// Version 1.2.31\n\nimport java.util.Random\nimport kotlin.system.measureNanoTime\n\ntypealias Sorter = (IntArray) -> Unit\n\nval rand = Random()\n\nfun onesSeq(n: Int) = IntArray(n) { 1 }\n\nfun ascendingSeq(n: Int) = shuffledSeq(n).sorted().toIntArray()\n\nfun shuffledSeq(n: Int) = IntArray(n) { 1 + rand.nextInt(10 * n) }\n\nfun bubbleSort(a: IntArray) {\n var n = a.size\n do {\n var n2 = 0\n for (i in 1 until n) {\n if (a[i - 1] > a[i]) {\n val tmp = a[i]\n a[i] = a[i - 1]\n a[i - 1] = tmp\n n2 = i\n }\n }\n n = n2\n } while (n != 0)\n}\n\nfun insertionSort(a: IntArray) {\n for (index in 1 until a.size) {\n val value = a[index]\n var subIndex = index - 1\n while (subIndex >= 0 && a[subIndex] > value) {\n a[subIndex + 1] = a[subIndex]\n subIndex--\n }\n a[subIndex + 1] = value\n }\n}\n\nfun quickSort(a: IntArray) {\n fun sorter(first: Int, last: Int) {\n if (last - first < 1) return\n val pivot = a[first + (last - first) / 2]\n var left = first\n var right = last\n while (left <= right) {\n while (a[left] < pivot) left++\n while (a[right] > pivot) right--\n if (left <= right) {\n val tmp = a[left]\n a[left] = a[right]\n a[right] = tmp\n left++\n right--\n }\n }\n if (first < right) sorter(first, right)\n if (left < last) sorter(left, last)\n }\n sorter(0, a.lastIndex)\n}\n\nfun radixSort(a: IntArray) {\n val tmp = IntArray(a.size)\n for (shift in 31 downTo 0) {\n tmp.fill(0)\n var j = 0\n for (i in 0 until a.size) {\n val move = (a[i] shl shift) >= 0\n val toBeMoved = if (shift == 0) !move else move\n if (toBeMoved)\n tmp[j++] = a[i]\n else {\n a[i - j] = a[i]\n }\n }\n for (i in j until tmp.size) tmp[i] = a[i - j]\n for (i in 0 until a.size) a[i] = tmp[i]\n }\n}\n\nval gaps = listOf(701, 301, 132, 57, 23, 10, 4, 1) // Marcin Ciura's gap sequence\n\nfun shellSort(a: IntArray) {\n for (gap in gaps) {\n for (i in gap until a.size) {\n val temp = a[i]\n var j = i\n while (j >= gap && a[j - gap] > temp) {\n a[j] = a[j - gap]\n j -= gap\n }\n a[j] = temp\n }\n }\n}\n\nfun main(args: Array<String>) {\n val runs = 10\n val lengths = listOf(1, 10, 100, 1_000, 10_000, 100_000)\n val sorts = listOf<Sorter>(\n ::bubbleSort, ::insertionSort, ::quickSort, ::radixSort, ::shellSort\n )\n\n /* allow JVM to compile sort functions before timings start */\n for (sort in sorts) sort(intArrayOf(1))\n\n val sortTitles = listOf(\"Bubble\", \"Insert\", \"Quick \", \"Radix \", \"Shell \")\n val seqTitles = listOf(\"All Ones\", \"Ascending\", \"Shuffled\")\n val totals = List(seqTitles.size) { List(sorts.size) { LongArray(lengths.size) } }\n for ((k, n) in lengths.withIndex()) {\n val seqs = listOf(onesSeq(n), ascendingSeq(n), shuffledSeq(n))\n repeat(runs) {\n for (i in 0 until seqs.size) {\n for (j in 0 until sorts.size) {\n val seq = seqs[i].copyOf()\n totals[i][j][k] += measureNanoTime { sorts[j](seq) }\n }\n }\n }\n }\n println(\"All timings in micro-seconds\\n\")\n print(\"Sequence length\")\n for (len in lengths) print(\"%8d \".format(len))\n println(\"\\n\")\n for (i in 0 until seqTitles.size) {\n println(\" ${seqTitles[i]}:\")\n for (j in 0 until sorts.size) {\n print(\" ${sortTitles[j]} \")\n for (k in 0 until lengths.size) {\n val time = totals[i][j][k] / runs / 1_000\n print(\"%8d \".format(time))\n }\n println()\n }\n println(\"\\n\")\n }\n}\n", "language": "Kotlin" }, { "code": "ClearAll[BubbleSort,ShellSort]\nBubbleSort[in_List]:=Module[{x=in,l=Length[in],swapped},swapped=True;\n While[swapped,swapped=False;\n Do[If[x[[i]]>x[[i+1]],x[[{i,i+1}]]//=Reverse;\n swapped=True;],{i,l-1}];];\nx]\nShellSort[lst_]:=Module[{list=lst,incr,temp,i,j},incr=Round[Length[list]/2];\n While[incr>0,For[i=incr+1,i<=Length[list],i++,temp=list[[i]];j=i;\n While[(j>=(incr+1))&&(list[[j-incr]]>temp),list[[j]]=list[[j-incr]];j=j-incr;];\n list[[j]]=temp;];\n If[incr==2,incr=1,incr=Round[incr/2.2]]];list\n]\n\ntimes=Table[\n arr=ConstantArray[1,n];\n t1={{n,AbsoluteTiming[BubbleSort[arr];][[1]]},{n,AbsoluteTiming[ShellSort[arr];][[1]]}};\n arr=Sort[RandomInteger[{10^6},n]];\n t2={{n,AbsoluteTiming[BubbleSort[arr];][[1]]},{n,AbsoluteTiming[ShellSort[arr];][[1]]}};\n arr=RandomInteger[{10^6},n];\n t3={{n,AbsoluteTiming[BubbleSort[arr];][[1]]},{n,AbsoluteTiming[ShellSort[arr];][[1]]}};\n {t1,t2,t3}\n,\n {n,2^Range[13]}\n];\n\nListLogLogPlot[Transpose@times[[All,1]],PlotLegends->{\"Bubble\",\"Shell\"},PlotLabel->\"Ones\"]\nListLogLogPlot[Transpose@times[[All,2]],PlotLegends->{\"Bubble\",\"Shell\"},PlotLabel->\"Ascending integers\"]\nListLogLogPlot[Transpose@times[[All,3]],PlotLegends->{\"Bubble\",\"Shell\"},PlotLabel->\"Shuffled\"]\n", "language": "Mathematica" }, { "code": "import algorithm\nimport random\nimport sequtils\nimport times\n\n\n####################################################################################################\n# Data.\n\nproc oneSeq(n: int): seq[int] = repeat(1, n)\n\n#---------------------------------------------------------------------------------------------------\n\nproc shuffledSeq(n: int): seq[int] =\n result.setLen(n)\n for item in result.mitems: item = rand(1..(10 * n))\n\n#---------------------------------------------------------------------------------------------------\n\nproc ascendingSeq(n: int): seq[int] = sorted(shuffledSeq(n))\n\n\n####################################################################################################\n# Algorithms.\n\nfunc bubbleSort(a: var openArray[int]) {.locks: \"unknown\".} =\n var n = a.len\n while true:\n var n2 = 0\n for i in 1..<n:\n if a[i - 1] > a[i]:\n swap a[i], a[i - 1]\n n2 = i\n n = n2\n if n == 0: break\n\n#---------------------------------------------------------------------------------------------------\n\nfunc insertionSort(a: var openArray[int]) {.locks: \"unknown\".} =\n for index in 1..a.high:\n let value = a[index]\n var subIndex = index - 1\n while subIndex >= 0 and a[subIndex] > value:\n a[subIndex + 1] = a[subIndex]\n dec subIndex\n a[subIndex + 1] = value\n\n#---------------------------------------------------------------------------------------------------\n\nfunc quickSort(a: var openArray[int]) {.locks: \"unknown\".} =\n\n func sorter(a: var openArray[int]; first, last: int) =\n if last - first < 1: return\n let pivot = a[first + (last - first) div 2]\n var left = first\n var right = last\n while left <= right:\n while a[left] < pivot: inc left\n while a[right] > pivot: dec right\n if left <= right:\n swap a[left], a[right]\n inc left\n dec right\n if first < right: a.sorter(first, right)\n if left < last: a.sorter(left, last)\n\n a.sorter(0, a.high)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc radixSort(a: var openArray[int]) {.locks: \"unknown\".} =\n\n var tmp = newSeq[int](a.len)\n\n for shift in countdown(63, 0):\n for item in tmp.mitems: item = 0\n var j = 0\n for i in 0..a.high:\n let move = a[i] shl shift >= 0\n let toBeMoved = if shift == 0: not move else: move\n if toBeMoved:\n tmp[j] = a[i]\n inc j\n else:\n a[i - j] = a[i]\n for i in j..tmp.high: tmp[i] = a[i - j]\n for i in 0..a.high: a[i] = tmp[i]\n\n#---------------------------------------------------------------------------------------------------\n\nfunc shellSort(a: var openArray[int]) {.locks: \"unknown\".} =\n\n const Gaps = [701, 301, 132, 57, 23, 10, 4, 1]\n\n for gap in Gaps:\n for i in gap..a.high:\n let temp = a[i]\n var j = i\n while j >= gap and a[j - gap] > temp:\n a[j] = a[j - gap]\n dec j, gap\n a[j] = temp\n\n#---------------------------------------------------------------------------------------------------\n\nfunc standardSort(a: var openArray[int]) =\n a.sort()\n\n\n####################################################################################################\n# Main code.\n\nimport strformat\n\nconst\n\n Runs = 10\n Lengths = [1, 10, 100, 1_000, 10_000, 100_000]\n\n Sorts = [bubbleSort, insertionSort, quickSort, radixSort, shellSort, standardSort]\n\nconst\n SortTitles = [\"Bubble\", \"Insert\", \"Quick \", \"Radix \", \"Shell \", \"Standard\"]\n SeqTitles = [\"All Ones\", \"Ascending\", \"Shuffled\"]\n\nvar totals: array[SeqTitles.len, array[Sorts.len, array[Lengths.len, Duration]]]\n\nrandomize()\n\nfor k, n in Lengths:\n let seqs = [oneSeq(n), ascendingSeq(n), shuffledSeq(n)]\n for _ in 1..Runs:\n for i, s in seqs:\n for j, sort in Sorts:\n var s = s\n let t0 = getTime()\n s.sort()\n totals[i][j][k] += getTime() - t0\n\necho \"All timings in microseconds\\n\"\nstdout.write \"Sequence length \"\nfor length in Lengths:\n stdout.write &\"{length:6d} \"\necho '\\n'\nfor i in 0..SeqTitles.high:\n echo &\" {SeqTitles[i]}:\"\n for j in 0..Sorts.high:\n stdout.write &\" {SortTitles[j]:8s} \"\n for k in 0..Lengths.high:\n let time = totals[i][j][k].inMicroseconds div Runs\n stdout.write &\"{time:8d} \"\n echo \"\"\n echo '\\n'\n", "language": "Nim" }, { "code": "-->\n <span style=\"color: #000080;font-style:italic;\">-- demo\\rosetta\\Compare_sorting_algorithms.exw</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">XQS</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">01</span> <span style=\"color: #000080;font-style:italic;\">-- (set to 1 to exclude quick_sort and shell_sort from ones)</span>\n\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">tabs</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">plot</span>\n <span style=\"color: #004080;\">Ihandles</span> <span style=\"color: #000000;\">plots</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">quick_sort2</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">x</span> <span style=\"color: #000080;font-style:italic;\">-- already sorted (trivial case)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">mid</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">((</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">midn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">midval</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">mid</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">left</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span> <span style=\"color: #000000;\">right</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">mid</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">xi</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">compare</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xi</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">midval</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">left</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">left</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">xi</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">right</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">right</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">xi</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">midn</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">quick_sort2</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">left</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">midval</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">midn</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #000000;\">quick_sort2</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">right</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">quick_sort</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">qstack</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">((</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">))</span> <span style=\"color: #000080;font-style:italic;\">-- create a stack</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">first</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">last</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">stackptr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">first</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">last</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">pivot</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">last</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">first</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">sj</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">I</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">first</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">J</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">last</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">si</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">I</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">pivot</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">I</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">sj</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">J</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">sj</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">pivot</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">J</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">I</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">J</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">I</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">J</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">sj</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">I</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">J</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">J</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">I</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">I</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">sj</span>\n <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">J</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">si</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">I</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">J</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">I</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">J</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">I</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">last</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">qstack</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">stackptr</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">I</span>\n <span style=\"color: #000000;\">qstack</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">stackptr</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">last</span>\n <span style=\"color: #000000;\">stackptr</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">last</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">J</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">stackptr</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">stackptr</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #000000;\">first</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">qstack</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">stackptr</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">last</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">qstack</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">stackptr</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">s</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">radixSortn</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">buckets</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">({},</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">digit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]/</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)),</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">digit</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">digit</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">len</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">radixSortn</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">split_by_sign</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">buckets</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{},{}}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">si</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],-</span><span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">buckets</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">radix_sort</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- NB this is an integer-only sort</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">mins</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">min</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">passes</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">log10</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mins</span><span style=\"color: #0000FF;\">))))+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">mins</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">buckets</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">split_by_sign</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">reverse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">sq_uminus</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">radixSortn</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">passes</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">radixSortn</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">passes</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]&</span><span style=\"color: #000000;\">buckets</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">radixSortn</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">passes</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">s</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">shell_sort</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">gap</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">gap</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">gap</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">temp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">j</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">gap</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">temp</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">gap</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">j</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">gap</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">gap</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">temp</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">gap</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">gap</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">s</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">shell_sort2</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">last</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">gap</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">last</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">TRUE</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">first</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">gap</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">first</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">last</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">xi</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">j</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">gap</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">TRUE</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">xj</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">xi</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">xj</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">j</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gap</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">gap</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">xj</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">gap</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">j</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">gap</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">xi</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">gap</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">x</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">gap</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">gap</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">3.5</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">siftDown</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">last</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">root</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">last</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">child</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">child</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">last</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">child</span><span style=\"color: #0000FF;\">]<</span><span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">child</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">child</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">]>=</span><span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">child</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">tmp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">child</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">child</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tmp</span>\n <span style=\"color: #000000;\">root</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">child</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">arr</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">heapify</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">arr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">siftDown</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">arr</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">heap_sort</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">last</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">arr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">heapify</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">last</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">last</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">tmp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">last</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">last</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tmp</span>\n <span style=\"color: #000000;\">last</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">arr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">siftDown</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">arr</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">last</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">arr</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">builtins</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #7060A8;\">sort</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">enum</span> <span style=\"color: #000000;\">ONES</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">SORTED</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">RANDOM</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">REVERSE</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">4</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tabtitles</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ones\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"sorted\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"random\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"reverse\"</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">tabidx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">3</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">STEP</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">tr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">name</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">rid</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">routine_id</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">name</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">name</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">rid</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">tr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"quick_sort\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">tr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"quick_sort2\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">tr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"radix_sort\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">tr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"shell_sort\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">tr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"shell_sort2\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">tr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"heap_sort\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">tr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"sort\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">-- builtin</span>\n <span style=\"color: #0000FF;\">}</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">results</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">({},</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)),</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tabtitles</span><span style=\"color: #0000FF;\">))</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">dsdx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)),</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tabtitles</span><span style=\"color: #0000FF;\">))</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ds_index</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">idle_action_cb</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">best</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- fastest last</span>\n <span style=\"color: #000000;\">besti</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- 1..length(tests) </span>\n <span style=\"color: #000000;\">bestt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- 1..length(tabtitles)</span>\n <span style=\"color: #000000;\">len</span>\n <span style=\"color: #000080;font-style:italic;\">--\n -- Search for something to do, active/visible tab first.\n -- Any result set of length 0 -&gt; just do one.\n -- Of all result sets&lt;8, pick the lowest [$].\n --</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">todo</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">tabidx</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tabtitles</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">tabidx</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">todo</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tabtitles</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ti</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">todo</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">results</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">len</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">results</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">best</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #000000;\">besti</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">i</span>\n <span style=\"color: #000000;\">bestt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">ti</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">8</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">best</span><span style=\"color: #0000FF;\">=-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">best</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">results</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][$])</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">best</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">results</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][$]</span>\n <span style=\"color: #000000;\">besti</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">i</span>\n <span style=\"color: #000000;\">bestt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">ti</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">besti</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">best</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000080;font-style:italic;\">-- cop out if it is getting too slow</span>\n <span style=\"color: #000000;\">besti</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">besti</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">STEP</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">XQS</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">bestt</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">ONES</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">1000</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">100000</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">len</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">results</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">bestt</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">besti</span><span style=\"color: #0000FF;\">])+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">STEP</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">test</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">bestt</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">ONES</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">):</span>\n <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">bestt</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">SORTED</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">):</span>\n <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">bestt</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">RANDOM</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">shuffle</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">)):</span>\n <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">bestt</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">REVERSE</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">reverse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">)):</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">))))</span>\n <span style=\"color: #000000;\">ds_index</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">dsdx</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">bestt</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">besti</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">check</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">call_func</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">besti</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">],{</span><span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span>\n <span style=\"color: #000080;font-style:italic;\">-- if check!=sort(test) then ?9/0 end if</span>\n <span style=\"color: #000000;\">plot</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">plots</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">bestt</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #7060A8;\">IupPlotInsert</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">ds_index</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">len</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">results</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">bestt</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">besti</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">results</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">bestt</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">besti</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"REDRAW\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #7060A8;\">progress</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">bestt</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">results</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">bestt</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">progress</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">results</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">bestt</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Compare sorting algorithms %s\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">sprint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">progress</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_CONTINUE</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Compare sorting algorithms (all done, idle)\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_IGNORE</span> <span style=\"color: #000080;font-style:italic;\">-- all done, remove callback</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">cb_idle_action</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"idle_action_cb\"</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">tabchange_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*self*/</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*new_tab*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">tabidx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tabs</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUEPOS\"</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">plot</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">plots</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">tabidx</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span><span style=\"color: #0000FF;\">;</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n\n <span style=\"color: #000000;\">plots</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tabtitles</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">XQS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000080;font-style:italic;\">-- results[ONES][1] = repeat(0,8)</span>\n <span style=\"color: #000000;\">results</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ONES</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">plot</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupPlot</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"MENUITEMPROPERTIES\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"YES\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TABTITLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tabtitles</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"GRID\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"YES\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"MARGINLEFT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"50\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"MARGINBOTTOM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"40\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"LEGEND\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"YES\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"LEGENDPOS\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TOPLEFT\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- IupSetAttribute(plot,\"AXS_YSCALE\",\"LOG10\")\n -- IupSetAttribute(plot,\"AXS_XSCALE\",\"LOG10\")</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">IupPlotBegin</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">dsdx</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupPlotEnd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"DS_NAME\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">plots</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">plots</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">tabs</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupTabs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">plots</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tabs</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"TABCHANGE_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"tabchange_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tabs</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"RASTERSIZE=800x480\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"Compare sorting algorithms\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tabs</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"VALUEPOS\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">tabidx</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetGlobalFunction</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"IDLE_ACTION\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cb_idle_action</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "def builtinsort(x):\n x.sort()\n\ndef partition(seq, pivot):\n low, middle, up = [], [], []\n for x in seq:\n if x < pivot:\n low.append(x)\n elif x == pivot:\n middle.append(x)\n else:\n up.append(x)\n return low, middle, up\nimport random\ndef qsortranpart(seq):\n size = len(seq)\n if size < 2: return seq\n low, middle, up = partition(seq, random.choice(seq))\n return qsortranpart(low) + middle + qsortranpart(up)\n", "language": "Python" }, { "code": "def ones(n):\n return [1]*n\n\ndef reversedrange(n):\n return reversed(range(n))\n\ndef shuffledrange(n):\n x = range(n)\n random.shuffle(x)\n return x\n", "language": "Python" }, { "code": "def write_timings(npoints=10, maxN=10**4, sort_functions=(builtinsort,insertion_sort, qsort),\n sequence_creators = (ones, range, shuffledrange)):\n Ns = range(2, maxN, maxN//npoints)\n for sort in sort_functions:\n for make_seq in sequence_creators:\n Ts = [usec(sort, (make_seq(n),)) for n in Ns]\n writedat('%s-%s-%d-%d.xy' % (sort.__name__, make_seq.__name__, len(Ns), max(Ns)), Ns, Ts)\n", "language": "Python" }, { "code": "import operator\nimport numpy, pylab\ndef plotdd(dictplotdict):\n \"\"\"See ``plot_timings()`` below.\"\"\"\n symbols = ('o', '^', 'v', '<', '>', 's', '+', 'x', 'D', 'd',\n '1', '2', '3', '4', 'h', 'H', 'p', '|', '_')\n colors = list('bgrcmyk') # split string on distinct characters\n for npoints, plotdict in dictplotdict.iteritems():\n for ttle, lst in plotdict.iteritems():\n pylab.hold(False)\n for i, (label, polynom, x, y) in enumerate(sorted(lst,key=operator.itemgetter(0))):\n pylab.plot(x, y, colors[i % len(colors)] + symbols[i % len(symbols)], label='%s %s' % (polynom, label))\n pylab.hold(True)\n y = numpy.polyval(polynom, x)\n pylab.plot(x, y, colors[i % len(colors)], label= '_nolegend_')\n pylab.legend(loc='upper left')\n pylab.xlabel(polynom.variable)\n pylab.ylabel('log2( time in microseconds )')\n pylab.title(ttle, verticalalignment='bottom')\n figname = '_%(npoints)03d%(ttle)s' % vars()\n pylab.savefig(figname+'.png')\n pylab.savefig(figname+'.pdf')\n print figname\n", "language": "Python" }, { "code": "import collections, itertools, glob, re\nimport numpy\ndef plot_timings():\n makedict = lambda: collections.defaultdict(lambda: collections.defaultdict(list))\n df = makedict()\n ds = makedict()\n # populate plot dictionaries\n for filename in glob.glob('*.xy'):\n m = re.match(r'([^-]+)-([^-]+)-(\\d+)-(\\d+)\\.xy', filename)\n print filename\n assert m, filename\n funcname, seqname, npoints, maxN = m.groups()\n npoints, maxN = int(npoints), int(maxN)\n a = numpy.fromiter(itertools.imap(float, open(filename).read().split()), dtype='f')\n Ns = a[::2] # sequences lengths\n Ts = a[1::2] # corresponding times\n assert len(Ns) == len(Ts) == npoints\n assert max(Ns) <= maxN\n #\n logsafe = numpy.logical_and(Ns>0, Ts>0)\n Ts = numpy.log2(Ts[logsafe])\n Ns = numpy.log2(Ns[logsafe])\n coeffs = numpy.polyfit(Ns, Ts, deg=1)\n poly = numpy.poly1d(coeffs, variable='log2(N)')\n #\n df[npoints][funcname].append((seqname, poly, Ns, Ts))\n ds[npoints][seqname].append((funcname, poly, Ns, Ts))\n # actual plotting\n plotdd(df)\n plotdd(ds) # see ``plotdd()`` above\n", "language": "Python" }, { "code": "sort_functions = [\n builtinsort, # see implementation above\n insertion_sort, # see [[Insertion sort]]\n insertion_sort_lowb, # ''insertion_sort'', where sequential search is replaced\n # by lower_bound() function\n qsort, # see [[Quicksort]]\n qsortranlc, # ''qsort'' with randomly choosen ''pivot''\n # and the filtering via list comprehension\n qsortranpart, # ''qsortranlc'' with filtering via ''partition'' function\n qsortranpartis, # ''qsortranpart'', where for a small input sequence lengths\n ] # ''insertion_sort'' is called\nif __name__==\"__main__\":\n import sys\n sys.setrecursionlimit(10000)\n write_timings(npoints=100, maxN=1024, # 1 <= N <= 2**10 an input sequence length\n sort_functions=sort_functions,\n sequence_creators = (ones, range, shuffledrange))\n plot_timings()\n", "language": "Python" }, { "code": "# 20221114 Raku programming solution\n\nmy ($rounds,$size) = 3, 2000;\nmy @allones = 1 xx $size;\nmy @sequential = 1 .. $size;\nmy @randomized = @sequential.roll xx $size;\n\nsub insertion_sort ( @a is copy ) { # rosettacode.org/wiki/Sorting_algorithms/Insertion_sort#Raku\n for 1 .. @a.end -> \\k {\n loop (my ($j,\\value)=k-1,@a[k];$j>-1&&@a[$j]>value;$j--) {@a[$j+1]=@a[$j]}\n @a[$j+1] = value;\n }\n return @a;\n}\n\nsub merge_sort ( @a ) { # rosettacode.org/wiki/Sorting_algorithms/Merge_sort#Raku\n return @a if @a <= 1;\n\n my $m = @a.elems div 2;\n my @l = merge_sort @a[ 0 ..^ $m ];\n my @r = merge_sort @a[ $m ..^ @a ];\n\n return flat @l, @r if @l[*-1] !after @r[0];\n return flat gather {\n take @l[0] before @r[0] ?? @l.shift !! @r.shift\n while @l and @r;\n take @l, @r;\n }\n}\n\nsub quick-sort(@data) { # andrewshitov.com/2019/06/23/101-quick-sort-in-perl-6/\n return @data if @data.elems <= 1;\n\n my ($pivot,@left, @right) = @data[0];\n\n for @data[1..*] -> $x { $x < $pivot ?? push @left, $x !! push @right, $x }\n\n return flat(quick-sort(@left), $pivot, quick-sort(@right));\n}\n\nsub comparesorts($rounds, @tosort) {\n my ( $iavg, $mavg, $qavg, $t );\n\n for (<i m q> xx $rounds).flat.pick(*) -> \\sort_type {\n given sort_type {\n when 'i' { $t = now ; insertion_sort @tosort ; $iavg += now - $t }\n when 'm' { $t = now ; merge_sort @tosort ; $mavg += now - $t }\n\t when 'q' { $t = now ; quick-sort @tosort ; $qavg += now - $t }\n }\n }\n return $iavg, $mavg, $qavg »/» $rounds\n}\n\nfor <ones presorted randomized>Z(@allones,@sequential,@randomized) -> ($t,@d) {\n say \"Average sort times for $size $t:\";\n { say \"\\tinsertion sort\\t$_[0]\\n\\tmerge sort\\t$_[1]\\n\\tquick sort\\t$_[2]\" }(comparesorts $rounds,@d)\n}\n", "language": "Raku" }, { "code": "/*REXX pgm compares various sorts for 3 types of input sequences: ones/ascending/random.*/\nparse arg ranges start# seed . /*obtain optional arguments from the CL*/\nif ranges=='' | ranges==\",\" then ranges= 5 /*Not Specified? Then use the default.*/\nif start#=='' | start#==\",\" then start#= 250 /* \" \" \" \" \" \" */\nif seed=='' | seed==\",\" then seed= 1946 /*use a repeatable seed for RANDOM BIF*/\nif datatype(seed, 'W') then call random ,,seed /*Specified? Then use as a RANDOM seed*/\nkinds= 3; hdr=; #= start# /*hardcoded/fixed number of datum kinds*/\n do ra=1 for ranges\n hdr= hdr || center( commas(#) \"numbers\", 25)'│' /*(top) header for the output title.*/\n do ki=1 for kinds\n call gen@@ #, ki\n call set@; call time 'R'; call bubble #; bubble.ra.ki= format(time(\"E\"),,2)\n call set@; call time 'R'; call cocktail #; cocktail.ra.ki= format(time(\"E\"),,2)\n call set@; call time 'R'; call cocktailSB #; cocktailSB.ra.ki= format(time(\"E\"),,2)\n call set@; call time 'R'; call comb #; comb.ra.ki= format(time(\"E\"),,2)\n call set@; call time 'R'; call exchange #; exchange.ra.ki= format(time(\"E\"),,2)\n call set@; call time 'R'; call gnome #; gnome.ra.ki= format(time(\"E\"),,2)\n call set@; call time 'R'; call heap #; heap.ra.ki= format(time(\"E\"),,2)\n call set@; call time 'R'; call insertion #; insertion.ra.ki= format(time(\"E\"),,2)\n call set@; call time 'R'; call merge #; merge.ra.ki= format(time(\"E\"),,2)\n call set@; call time 'R'; call pancake #; pancake.ra.ki= format(time(\"E\"),,2)\n call set@; call time 'R'; call quick #; quick.ra.ki= format(time(\"E\"),,2)\n call set@; call time 'R'; call radix #; radix.ra.ki= format(time(\"E\"),,2)\n call set@; call time 'R'; call selection #; selection.ra.ki= format(time(\"E\"),,2)\n call set@; call time 'R'; call shell #; shell.ra.ki= format(time(\"E\"),,2)\n end /*ki*/\n #= # + # /*double # elements.*/\n end /*ra*/\nsay; say; say /*say blank sep line*/\nsay center(' ', 11 ) \"│\"left(hdr, length(hdr)-1)\"│\" /*replace last char.*/\n reps= ' allONES ascend random │' /*build a title bar.*/\nxreps= copies( center(reps, length(reps)), ranges) /*replicate ranges. */\ncreps= left(xreps, length(xreps)-1)\"│\" /*replace last char.*/\nsay center('sort type', 11 ) \"│\"creps; Lr= length(reps)\n xcreps= copies( left('', Lr-1, '─')\"┼\", ranges)\nsay center('' , 12, '─')\"┼\"left(xcreps, length(xcreps)-1)\"┤\"\ncall show 'bubble' /* ◄──── show results for bubble sort.*/\ncall show 'cocktail' /* ◄──── \" \" \" cocktail \" */\ncall show 'cocktailSB' /*+Shifting Bounds*/ /* ◄──── \" \" \" cocktailSB \" */\ncall show 'comb' /* ◄──── \" \" \" comb \" */\ncall show 'exchange' /* ◄──── \" \" \" exchange \" */\ncall show 'gnome' /* ◄──── \" \" \" gnome \" */\ncall show 'heap' /* ◄──── \" \" \" heap \" */\ncall show 'insertion' /* ◄──── \" \" \" insertion \" */\ncall show 'merge' /* ◄──── \" \" \" merge \" */\ncall show 'pancake' /* ◄──── \" \" \" pancake \" */\ncall show 'quick' /* ◄──── \" \" \" quick \" */\ncall show 'radix' /* ◄──── \" \" \" radix \" */\ncall show 'selection' /* ◄──── \" \" \" shell \" */\ncall show 'shell' /* ◄──── \" \" \" shell \" */\nsay translate(center('' , 12, '─')\"┴\"left(xcreps, length(xcreps)-1)\"┘\", '┴', \"┼\")\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncommas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?\ninOrder: parse arg n; do j=1 for n-1; k= j+1; if @.j>@.k then return 0; end; return 1\nset@: @.=; do a=1 for #; @.a= @@.a; end; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ngen@@: procedure expose @@.; parse arg n,kind; nn= min(n, 100000) /*1e5≡REXX's max.*/\n do j=1 for nn; select\n when kind==1 then @@.j= 1 /*all ones. */\n when kind==2 then @@.j= j /*ascending.*/\n when kind==3 then @@.j= random(, nn) /*random. */\n end /*select*/\n end /*j*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nshow: parse arg aa; _= left(aa, 11) \"│\"\n do ra=1 for ranges\n do ki=1 for kinds\n _= _ right( value(aa || . || ra || . || ki), 7, ' ')\n end /*k*/\n _= _ \"│\"\n end /*r*/; say _; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nbubble: procedure expose @.; parse arg n /*N: is the number of @ elements. */\n do m=n-1 by -1 until ok; ok=1 /*keep sorting @ array until done.*/\n do j=1 for m; k=j+1; if @.j<[email protected] then iterate /*elements in order? */\n [email protected]; @[email protected]; @.k=_; ok=0 /*swap 2 elements; flag as not done.*/\n end /*j*/\n end /*m*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncocktail: procedure expose @.; parse arg N; nn= N-1 /*N: is number of items. */\n do until done; done= 1\n do j=1 for nn; jp= j+1\n if @.j>@.jp then do; done=0; [email protected]; @[email protected]; @.jp=_; end\n end /*j*/\n if done then leave /*No swaps done? Finished.*/\n do k=nn for nn by -1; kp= k+1\n if @.k>@.kp then do; done=0; [email protected]; @[email protected]; @.kp=_; end\n end /*k*/\n end /*until*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncocktailsb: procedure expose @.; parse arg N /*N: is number of items. */\n end$= N - 1; beg$= 1\n do while beg$ <= end$\n beg$$= end$; end$$= beg$\n do j=beg$ to end$; jp= j + 1\n if @.j>@.jp then do; [email protected]; @[email protected]; @.jp=_; end$$=j; end\n end /*j*/\n end$= end$$ - 1\n do k=end$ to beg$ by -1; kp= k + 1\n if @.k>@.kp then do; [email protected]; @[email protected]; @.kp=_; beg$$=k; end\n end /*k*/\n beg$= beg$$ + 1\n end /*while*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncomb: procedure expose @.; parse arg n /*N: is the number of @ elements. */\n g= n-1 /*G: is the gap between the sort COMBs*/\n do until g<=1 & done; done= 1 /*assume sort is done (so far). */\n g= g * 0.8 % 1 /*equivalent to: g= trunc( g / 1.25) */\n if g==0 then g= 1 /*handle case of the gap is too small. */\n do j=1 until $>=n; $= j + g /*$: a temporary index (pointer). */\n if @.j>@.$ then do; _= @.j; @.j= @.$; @.$= _; done= 0; end\n end /*j*/ /* [↑] swap two elements in the array.*/\n end /*until*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nexchange: procedure expose @.; parse arg n 1 h /*both N and H have the array size.*/\n do while h>1; h= h % 2\n do i=1 for n-h; j= i; k= h+i\n do while @.k<@.j\n _= @.j; @.j= @.k; @.k= _; if h>=j then leave; j= j-h; k= k-h\n end /*while @.k<@.j*/\n end /*i*/\n end /*while h>1*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ngnome: procedure expose @.; parse arg n; k= 2 /*N: is number items. */\n do j=3 while k<=n; p= k - 1 /*P: is previous item.*/\n if @.p<<[email protected] then do; k= j; iterate; end /*order is OK so far. */\n _= @.p; @.p= @.k; @.k= _ /*swap two @ entries. */\n k= k - 1; if k==1 then k= j; else j= j-1 /*test for 1st index. */\n end /*j*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nheap: procedure expose @.; arg n; do j=n%2 by -1 to 1; call heapS j,n; end /*j*/\n do n=n by -1 to 2; _= @.1; @.1= @.n; @.n= _; call heapS 1,n-1\n end /*n*/; return /* [↑] swap two elements; and shuffle.*/\n\nheapS: procedure expose @.; parse arg i,n; $= @.i /*obtain parent.*/\n do while i+i<=n; j= i+i; k= j+1; if k<=n then if @.k>@.j then j= k\n if $>[email protected] then leave; @.i= @.j; i= j\n end /*while*/; @.i= $; return /*define lowest.*/\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ninsertion: procedure expose @.; parse arg n\n do i=2 to n; $= @.i; do j=i-1 by -1 to 1 while @.j>$\n _= j + 1; @._= @.j\n end /*j*/\n _= j + 1; @._= $\n end /*i*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nmerge: procedure expose @. !.; parse arg n, L; if L=='' then do; !.=; L= 1; end\n if n==1 then return; h= L + 1\n if n==2 then do; if @.L>@.h then do; [email protected]; @[email protected]; @.L=_; end; return; end\n m= n % 2 /* [↑] handle case of two items.*/\n call merge n-m, L+m /*divide items to the left ···*/\n call merger m, L, 1 /* \" \" \" \" right ···*/\n i= 1; j= L + m\n do k=L while k<j /*whilst items on right exist ···*/\n if j==L+n | !.i<[email protected] then do; @.k= !.i; i= i + 1; end\n else do; @.k= @.j; j= j + 1; end\n end /*k*/; return\n\nmerger: procedure expose @. !.; parse arg n,L,T\n if n==1 then do; !.T= @.L; return; end\n if n==2 then do; h= L + 1; q= T + 1; !.q= @.L; !.T= @.h; return; end\n m= n % 2 /* [↑] handle case of two items.*/\n call merge m, L /*divide items to the left ···*/\n call merger n-m, L+m, m+T /* \" \" \" \" right ···*/\n i= L; j= m + T\n do k=T while k<j /*whilst items on left exist ···*/\n if j==T+n | @.i<=!.j then do; !.k= @.i; i= i + 1; end\n else do; !.k= !.j; j= j + 1; end\n end /*k*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\npancake: procedure expose @.; parse arg n .; if inOrder(n) then return\n do n=n by -1 for n-1\n != @.1; ?= 1; do j=2 to n; if @.j<=! then iterate\n != @.j; ?= j\n end /*j*/\n call panFlip ?; call panFlip n\n end /*n*/; return\n\npanFlip: parse arg y; do i=1 for (y+1)%2; yi=y-i+1; [email protected]; @[email protected]; @.yi=_; end; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nquick: procedure expose @.; a.1=1; parse arg b.1; $= 1 /*access @.; get #; define pivot.*/\n if inOrder(b.1) then return\n do while $\\==0; L= a.$; t= b.$; $= $-1; if t<2 then iterate\n H= L+t-1; ?= L+t%2\n if @.H<@.L then if @.?<@.H then do; [email protected]; @[email protected]; end\n else if @.?>@.L then [email protected]\n else do; p=@.?; @[email protected]; end\n else if @.?<@.L then [email protected]\n else if @.?>@.H then do; [email protected]; @[email protected]; end\n else do; p=@.?; @[email protected]; end\n j= L+1; k=h\n do forever\n do j=j while j<k & @.j<=p; end /*a tinie─tiny loop.*/\n do k=k by -1 while j<k & @.k>=p; end /*another \" \" */\n if j>=k then leave /*segment finished? */\n _= @.j; @.j= @.k; @.k= _ /*swap J&K elements.*/\n end /*forever*/\n $= $+1; k= j-1; @.L= @.k; @.k= p\n if j<=? then do; a.$= j; b.$= H-j+1; $= $+1; a.$= L; b.$= k-L; end\n else do; a.$= L; b.$= k-L; $= $+1; a.$= j; b.$= H-j+1; end\n end /*while $¬==0*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nradix: procedure expose @.; parse arg size,w; mote= c2d(' '); #= 1; !.#._n= size\n!.#._b= 1; if w=='' then w= 8\n!.#._i= 1; do i=1 for size; [email protected]; @.i= right(abs(y), w, 0); if y<0 then @.i= '-'@.i\n end /*i*/ /* [↑] negative case.*/\n\n do while #\\==0; ctr.= 0; L= 'ffff'x; low= !.#._b; n= !.#._n; $= !.#._i; H=\n #= #-1 /* [↑] is the radix. */\n do j=low for n; parse var @.j =($) _ +1; ctr._= ctr._ + 1\n if ctr._==1 & _\\=='' then do; if _<<L then L=_; if _>>H then H=_\n end /* ↑↑ */\n end /*j*/ /* └┴─────◄─── << is a strict comparison.*/\n _= /* ┌──◄─── >> \" \" \" \" */\n if L>>H then iterate /*◄─────┘ */\n if L==H & ctr._==0 then do; #= #+1; !.#._b= low; !.#._n= n; !.#._i= $+1; iterate\n end\n L= c2d(L); H= c2d(H); ?= ctr._ + low; top._= ?; ts= mote\n max= L\n do k=L to H; _= d2c(k, 1); c= ctr._ /* [↓] swap 2 item radices.*/\n if c>ts then parse value c k with ts max; ?= ?+c; top._= ?\n end /*k*/\n piv= low /*set PIVot to the low part of the sort*/\n do while piv<low+n\n it= @.piv\n do forever; parse var it =($) _ +1; c= top._ -1\n if piv>=c then leave; top._= c; ?= @.c; @.c= it; it= ?\n end /*forever*/\n top._= piv; @.piv= it; piv= piv + ctr._\n end /*while piv<low+n */\n i= max\n do until i==max; _= d2c(i, 1); i= i+1; if i>H then i= L; d= ctr._\n if d<=mote then do; if d<2 then iterate; b= top._\n do k=b+1 for d-1; q= @.k\n do j=k-1 by -1 to b while q<<@.j; jp= j+1; @.jp= @.j\n end /*j*/\n jp= j+1; @.jp= q\n end /*k*/\n iterate\n end\n #= #+1; !.#._b= top._; !.#._n= d; !.#._i= $ + 1\n end /*until i==max*/\n end /*while #\\==0 */\n#= 0 /* [↓↓↓] handle neg. and pos. arrays. */\n do i=size by -1 for size; if @.i>=0 then iterate; #= #+1; @@.#= @.i\n end /*i*/\n do j=1 for size; if @.j>=0 then do; #= #+1; @@.#= @.j; end; @.j= @@.j+0\n end /*j*/ /* [↑↑↑] combine 2 lists into 1 list. */\nreturn\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nselection: procedure expose @.; parse arg n\n do j=1 for n-1; _= @.j; p= j\n do k=j+1 to n; if @.k>=_ then iterate\n _= @.k; p= k /*this item is out─of─order, swap later*/\n end /*k*/\n if p==j then iterate /*if the same, the order of items is OK*/\n _= @.j; @.j= @.p; @.p= /*swap 2 items that're out─of─sequence.*/\n end /*j*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nshell: procedure expose @.; parse arg N /*obtain the N from the argument list*/\n i= N % 2 /*% is integer division in REXX. */\n do while i\\==0\n do j=i+1 to N; k= j; p= k-i /*P: previous item*/\n _= @.j\n do while k>=i+1 & @.p>_; @.k= @.p; k= k-i; p= k-i\n end /*while k≥i+1*/\n @.k= _\n end /*j*/\n if i==2 then i= 1\n else i= i * 5 % 11\n end /*while i¬==0*/; return\n", "language": "REXX" }, { "code": "class Array\n def radix_sort(base=10) # negative value is inapplicable.\n ary = dup\n rounds = (Math.log(ary.max)/Math.log(base)).ceil\n rounds.times do |i|\n buckets = Array.new(base){[]}\n base_i = base**i\n ary.each do |n|\n digit = (n/base_i) % base\n buckets[digit] << n\n end\n ary = buckets.flatten\n end\n ary\n end\n\n def quick_sort\n return self if size <= 1\n pivot = sample\n g = group_by{|x| x<=>pivot}\n g.default = []\n g[-1].quick_sort + g[0] + g[1].quick_sort\n end\n\n def shell_sort\n inc = size / 2\n while inc > 0\n (inc...size).each do |i|\n value = self[i]\n while i >= inc and self[i - inc] > value\n self[i] = self[i - inc]\n i -= inc\n end\n self[i] = value\n end\n inc = (inc == 2 ? 1 : (inc * 5.0 / 11).to_i)\n end\n self\n end\n\n def insertion_sort\n (1...size).each do |i|\n value = self[i]\n j = i - 1\n while j >= 0 and self[j] > value\n self[j+1] = self[j]\n j -= 1\n end\n self[j+1] = value\n end\n self\n end\n\n def bubble_sort\n (1...size).each do |i|\n (0...size-i).each do |j|\n self[j], self[j+1] = self[j+1], self[j] if self[j] > self[j+1]\n end\n end\n self\n end\nend\n\ndata_size = [1000, 10000, 100000, 1000000]\ndata = []\ndata_size.each do |size|\n ary = *1..size\n data << [ [1]*size, ary, ary.shuffle, ary.reverse ]\nend\ndata = data.transpose\n\ndata_type = [\"set to all ones\", \"ascending sequence\", \"randomly shuffled\", \"descending sequence\"]\nprint \"Array size: \"\nputs data_size.map{|size| \"%9d\" % size}.join\n\ndata.each_with_index do |arys,i|\n puts \"\\nData #{data_type[i]}:\"\n [:sort, :radix_sort, :quick_sort, :shell_sort, :insertion_sort, :bubble_sort].each do |m|\n printf \"%20s \", m\n flag = true\n arys.each do |ary|\n if flag\n t0 = Time.now\n ary.dup.send(m)\n printf \" %7.3f\", (t1 = Time.now - t0)\n flag = false if t1 > 2\n else\n print \" --.---\"\n end\n end\n puts\n end\nend\n", "language": "Ruby" }, { "code": "class Array {\n method radix_sort(base=10) {\n var rounds = ([self.minmax].map{.abs}.max.ilog(base) + 1)\n for i in (0..rounds) {\n var buckets = (2*base -> of {[]})\n var base_i = base**i\n for n in self {\n var digit = idiv(n, base_i)%base\n digit += base if (0 <= n)\n buckets[digit].append(n)\n }\n self = buckets.flat\n }\n return self\n }\n\n func merge(left, right) {\n var result = []\n while (left && right) {\n result << [right,left].min_by{.first}.shift\n }\n result + left + right\n }\n\n method merge_sort {\n var len = self.len\n len < 2 && return self\n\n var (left, right) = self.part(len>>1)\n\n left = left.merge_sort\n right = right.merge_sort\n\n merge(left, right)\n }\n\n method quick_sort {\n self.len < 2 && return self\n var p = self.rand # to avoid the worst cases\n var g = self.group_by {|x| x <=> p }\n (g{-1} \\\\ []).quick_sort + (g{0} \\\\ []) + (g{1} \\\\ []).quick_sort\n }\n\n method shell_sort {\n var h = self.len\n while (h >>= 1) {\n range(h, self.end).each { |i|\n var k = self[i]\n var j\n for (j = i; (j >= h) && (k < self[j - h]); j -= h) {\n self[j] = self[j - h]\n }\n self[j] = k\n }\n }\n return self\n }\n\n method insertion_sort {\n { |i|\n var j = i\n var k = self[i+1]\n while ((j >= 0) && (k < self[j])) {\n self[j+1] = self[j]\n j--\n }\n self[j+1] = k\n } * self.end\n return self\n }\n\n method bubble_sort {\n loop {\n var swapped = false\n { |i|\n if (self[i] > self[i+1]) {\n self[i, i+1] = self[i+1, i]\n swapped = true\n }\n } << ^self.end\n swapped || break\n }\n return self\n }\n}\n\nvar data_size = [1e2, 1e3, 1e4, 1e5]\nvar data = []\ndata_size.each {|size|\n var ary = @(1..size)\n data << [size.of(1), ary, ary.shuffle, ary.reverse]\n}\n\ndata = data.transpose\n\nvar data_type = [\"set to all ones\", \"ascending sequence\",\n \"randomly shuffled\", \"descending sequence\"]\nprint(\"Array size: \")\nsay data_size.map{|size| \"%9d\" % size}.join\n\ndata.each_kv {|i, arys|\n say \"\\nData #{data_type[i]}:\"\n [:sort, :radix_sort, :quick_sort, :merge_sort,\n :shell_sort, :insertion_sort, :bubble_sort].each {|m|\n printf(\"%20s \", m)\n var timeout = false\n arys.each {|ary|\n if (!timeout) {\n var t0 = Time.micro\n ary.clone.(m)\n printf(\" %7.3f\", (var t1 = (Time.micro - t0)))\n timeout = true if (t1 > 1.5)\n }\n else {\n print(\" --.---\")\n }\n }\n say ''\n }\n}\n", "language": "Sidef" }, { "code": "###############################################################################\n# measure and plot times\npackage require Tk\npackage require struct::list\nnamespace path ::tcl::mathfunc\n\nproc create_log10_plot {title xlabel ylabel xs ys labels shapes colours} {\n set w [toplevel .[clock clicks]]\n wm title $w $title\n pack [canvas $w.c -background white]\n pack [canvas $w.legend -background white]\n update\n plot_log10 $w.c $w.legend $title $xlabel $ylabel $xs $ys $labels $shapes $colours\n $w.c config -scrollregion [$w.c bbox all]\n update\n}\n\nproc plot_log10 {canvas legend title xlabel ylabel xs ys labels shapes colours} {\n global xfac yfac\n set log10_xs [map {_ {log10 $_}} $xs]\n foreach series $ys {\n lappend log10_ys [map {_ {log10 $_}} $series]\n }\n set maxx [max {*}$log10_xs]\n set yvalues [lsort -real [struct::list flatten $log10_ys]]\n set firstInf [lsearch $yvalues Inf]\n set maxy [lindex $yvalues [expr {$firstInf == -1 ? [llength $yvalues] - 1 : $firstInf - 1}]]\n\n set xfac [expr {[winfo width $canvas] * 0.8/$maxx}]\n set yfac [expr {[winfo height $canvas] * 0.8/$maxy}]\n\n scale $canvas x 0 $maxx $xfac \"log10($xlabel)\"\n scale $canvas y 0 $maxy $yfac \"log10($ylabel)\" $maxx $xfac\n\n $legend create text 30 0 -text $title -anchor nw\n set count 1\n foreach series $log10_ys shape $shapes colour $colours label $labels {\n plotxy $canvas $log10_xs $series $shape $colour\n legenditem $legend [incr count] $shape $colour $label\n }\n}\n\nproc map {lambda list} {\n set res [list]\n foreach item $list {lappend res [apply $lambda $item]}\n return $res\n}\n\nproc legenditem {legend pos shape colour label} {\n set y [expr {$pos * 15}]\n $shape $legend 20 $y -fill $colour\n $legend create text 30 $y -text $label -anchor w\n}\n\n# The actual plotting engine\nproc plotxy {canvas _xs _ys shape colour} {\n global xfac yfac\n foreach x $_xs y $_ys {\n if {$y < Inf} {\n lappend xs $x\n lappend ys $y\n }\n }\n set coords [list]\n foreach x $xs y $ys {\n set coord_x [expr {$x*$xfac}]\n set coord_y [expr {-$y*$yfac}]\n $shape $canvas $coord_x $coord_y -fill $colour\n lappend coords $coord_x $coord_y\n }\n $canvas create line $coords -smooth true\n}\n# Rescales the contents of the given canvas\nproc scale {canvas direction from to fac label {other_to 0} {other_fac 0}} {\n set f [expr {$from*$fac}]\n set t [expr {$to*$fac}]\n switch -- $direction {\n x {\n set f [expr {$from * $fac}]\n set t [expr {$to * $fac}]\n # create x-axis\n $canvas create line $f 0 $t 0\n $canvas create text $f 0 -anchor nw -text $from\n $canvas create text $t 0 -anchor n -text [format \"%.1f\" $to]\n $canvas create text [expr {($f+$t)/2}] 0 -anchor n -text $label\n\n }\n y {\n set f [expr {$from * -$fac}]\n set t [expr {$to * -$fac}]\n # create y-axis\n $canvas create line 0 $f 0 $t\n $canvas create text 0 $f -anchor se -text $from\n $canvas create text 0 $t -anchor e -text [format \"%.1f\" $to]\n $canvas create text 0 [expr {($f+$t)/2}] -anchor e -text $label\n # create gridlines\n set xmax [expr {$other_to * $other_fac}]\n for {set i 1} {$i < $to} {incr i} {\n set y [expr {$i * -$fac}]\n $canvas create line 0 $y $xmax $y -dash .\n }\n }\n }\n}\n# Helper to make points, which are otherwise not a native item type\nproc dot {canvas x y args} {\n set id [$canvas create oval [expr {$x-3}] [expr {$y-3}] \\\n [expr {$x+3}] [expr {$y+3}]]\n $canvas itemconfigure $id {*}$args\n}\nproc square {canvas x y args} {\n set id [$canvas create rectangle [expr {$x-3}] [expr {$y-3}] \\\n [expr {$x+3}] [expr {$y+3}]]\n $canvas itemconfigure $id {*}$args\n}\nproc cross {canvas x y args} {\n set l1 [$canvas create line [expr {$x-3}] $y [expr {$x+3}] $y]\n set l2 [$canvas create line $x [expr {$y-3}] $x [expr {$y+3}]]\n $canvas itemconfigure $l1 {*}$args\n $canvas itemconfigure $l2 {*}$args\n}\nproc x {canvas x y args} {\n set l1 [$canvas create line [expr {$x-3}] [expr {$y-3}] [expr {$x+3}] [expr {$y+3}]]\n set l2 [$canvas create line [expr {$x+3}] [expr {$y-3}] [expr {$x-3}] [expr {$y+3}]]\n $canvas itemconfigure $l1 {*}$args\n $canvas itemconfigure $l2 {*}$args\n}\nproc triangleup {canvas x y args} {\n set id [$canvas create polygon $x [expr {$y-4}] \\\n [expr {$x+4}] [expr {$y+4}] \\\n [expr {$x-4}] [expr {$y+4}]]\n $canvas itemconfigure $id {*}$args\n}\nproc triangledown {canvas x y args} {\n set id [$canvas create polygon $x [expr {$y+4}] \\\n [expr {$x+4}] [expr {$y-4}] \\\n [expr {$x-4}] [expr {$y-4}]]\n $canvas itemconfigure $id {*}$args\n}\n\nwm withdraw .\n\n#####################################################################\n# list creation procedures\nproc ones n {\n lrepeat $n 1\n}\nproc reversed n {\n while {[incr n -1] >= 0} {\n lappend result $n\n }\n return $result\n}\nproc random n {\n for {set i 0} {$i < $n} {incr i} {\n lappend result [expr {int($n * rand())}]\n }\n return $result\n}\n\nset algorithms {lsort quicksort shellsort insertionsort bubblesort mergesort}\nset sizes {1 10 100 1000 10000 100000}\nset types {ones reversed random}\nset shapes {dot square cross triangleup triangledown x}\nset colours {red blue black brown yellow black}\n\n# create some lists to be used by all sorting algorithms\narray set lists {}\nforeach size $sizes {\n foreach type $types {\n set lists($type,$size) [$type $size]\n }\n}\n\nset runs 10\n\n# header\nfconfigure stdout -buffering none\nputs -nonewline [format \"%-16s\" \"list length:\"]\nforeach size $sizes {\n puts -nonewline [format \" %10d\" $size]\n}\nputs \"\"\n\n# perform the sort timings and output results\nforeach type $types {\n puts \"\\nlist type: $type\"\n set times [list]\n foreach algo $algorithms {\n set errs [list]\n set thesetimes [list]\n $algo {} ;# call it once to ensure it's compiled\n\n puts -nonewline [format \" %-13s\" $algo]\n foreach size $sizes {\n # some implementations are just too slow\n if {$type ne \"ones\" && (\n ($algo eq \"insertionsort\" && $size > 10000) ||\n ($algo eq \"bubblesort\" && $size > 1000))\n } {\n set time Inf\n } else {\n # OK, do it\n if {[catch {time [list $algo $lists($type,$size)] $runs} result] != 0} {\n set time Inf\n lappend errs $result\n } else {\n set time [lindex [split $result] 0]\n }\n }\n lappend thesetimes $time\n puts -nonewline [format \" %10s\" $time]\n }\n puts \"\"\n if {[llength $errs] > 0} {\n puts [format \" %s\" [join $errs \"\\n \"]]\n }\n lappend times $thesetimes\n }\n create_log10_plot \"Sorting a '$type' list\" size time $sizes $times $algorithms $shapes $colours\n}\nputs \"\\ntimes in microseconds, average of $runs runs\"\n", "language": "Tcl" }, { "code": "import \"random\" for Random\nimport \"./sort\" for Sort\nimport \"./fmt\" for Fmt\n\nvar rand = Random.new()\n\nvar onesSeq = Fn.new { |n| List.filled(n, 1) }\n\nvar shuffledSeq = Fn.new { |n|\n var seq = List.filled(n, 0)\n for (i in 0...n) seq[i] = 1 + rand.int(10 * n)\n return seq\n}\n\nvar ascendingSeq = Fn.new { |n|\n var seq = shuffledSeq.call(n)\n seq.sort()\n return seq\n}\n\nvar bubbleSort = Fn.new { |a|\n var n = a.count\n while (true) {\n var n2 = 0\n for (i in 1...n) {\n if (a[i - 1] > a[i]) {\n a.swap(i, i - 1)\n n2 = i\n }\n }\n n = n2\n if (n == 0) break\n }\n}\n\n// counting sort of 'a' according to the digit represented by 'exp'\nvar countSort = Fn.new { |a, exp|\n var n = a.count\n var output = [0] * n\n var count = [0] * 10\n for (i in 0...n) {\n var t = (a[i]/exp).truncate % 10\n count[t] = count[t] + 1\n }\n for (i in 1..9) count[i] = count[i] + count[i-1]\n for (i in n-1..0) {\n var t = (a[i]/exp).truncate % 10\n output[count[t] - 1] = a[i]\n count[t] = count[t] - 1\n }\n for (i in 0...n) a[i] = output[i]\n}\n\n// sorts 'a' in place\nvar radixSort = Fn.new { |a|\n // check for negative elements\n var min = a.reduce { |m, i| (i < m) ? i : m }\n // if there are any, increase all elements by -min\n if (min < 0) (0...a.count).each { |i| a[i] = a[i] - min }\n // now get the maximum to know number of digits\n var max = a.reduce { |m, i| (i > m) ? i : m }\n // do counting sort for each digit\n var exp = 1\n while ((max/exp).truncate > 0) {\n countSort.call(a, exp)\n exp = exp * 10\n }\n // if there were negative elements, reduce all elements by -min\n if (min < 0) (0...a.count).each { |i| a[i] = a[i] + min }\n}\n\nvar measureTime = Fn.new { |sort, seq|\n var start = System.clock\n sort.call(seq)\n return ((System.clock - start) * 1e6).round // microseconds\n}\n\nvar runs = 10\nvar lengths = [1, 10, 100, 1000, 10000, 50000]\nvar sorts = [\n bubbleSort,\n Fn.new { |a| Sort.insertion(a) },\n Fn.new { |a| Sort.quick(a) },\n radixSort,\n Fn.new { |a| Sort.shell(a) }\n]\n\nvar sortTitles = [\"Bubble\", \"Insert\", \"Quick \", \"Radix \", \"Shell \"]\nvar seqTitles = [\"All Ones\", \"Ascending\", \"Shuffled\"]\nvar totals = List.filled(seqTitles.count, null)\nfor (i in 0...totals.count) {\n totals[i] = List.filled(sorts.count, null)\n for (j in 0...sorts.count) totals[i][j] = List.filled(lengths.count, 0)\n}\nvar k = 0\nfor (n in lengths) {\n var seqs = [onesSeq.call(n), ascendingSeq.call(n), shuffledSeq.call(n)]\n for (r in 0...runs) {\n for (i in 0...seqs.count) {\n for (j in 0...sorts.count) {\n var seq = seqs[i].toList\n totals[i][j][k] = totals[i][j][k] + measureTime.call(sorts[j], seq)\n }\n }\n }\n k = k + 1\n}\nSystem.print(\"All timings in microseconds\\n\")\nSystem.write(\"Sequence length\")\nfor (len in lengths) Fmt.write(\"$8d \", len)\nSystem.print(\"\\n\")\nfor (i in 0...seqTitles.count) {\n System.print(\" %(seqTitles[i]):\")\n for (j in 0...sorts.count) {\n System.write(\" %(sortTitles[j]) \")\n for (k in 0...lengths.count) {\n var time = (totals[i][j][k] / runs).round\n Fmt.write(\"$8d \", time)\n }\n System.print()\n }\n System.print(\"\\n\")\n}\n", "language": "Wren" } ]
Compare-sorting-algorithms-performance
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Compiler/AST_interpreter\n", "language": "00-META" }, { "code": "AST interpreter\n\nAn AST interpreter interprets an [https://en.wikipedia.org/wiki/Abstract_syntax_tree Abstract Syntax Tree (AST)]\nproduced by a [[Compiler/syntax_analyzer|Syntax Analyzer]].\n\n{{task heading}}\n\nTake the AST output from the Syntax analyzer [[Compiler/syntax_analyzer|task]], and interpret it as appropriate.\nRefer to the [[Compiler/syntax_analyzer|Syntax analyzer task]] for details of the AST.\n\n;Loading the AST from the syntax analyzer is as simple as (pseudo code):\n\n<syntaxhighlight lang=\"python\">def load_ast()\n line = readline()\n # Each line has at least one token\n line_list = tokenize the line, respecting double quotes\n\n text = line_list[0] # first token is always the node type\n\n if text == \";\" # a terminal node\n return NULL\n\n node_type = text # could convert to internal form if desired\n\n # A line with two tokens is a leaf node\n # Leaf nodes are: Identifier, Integer, String\n # The 2nd token is the value\n if len(line_list) > 1\n return make_leaf(node_type, line_list[1])\n\n left = load_ast()\n right = load_ast()\n return make_node(node_type, left, right)</syntaxhighlight>\n\n; The interpreter algorithm is relatively simple:\n\n<syntaxhighlight lang=\"python\">interp(x)\n if x == NULL return NULL\n elif x.node_type == Integer return x.value converted to an integer\n elif x.node_type == Ident return the current value of variable x.value\n elif x.node_type == String return x.value\n elif x.node_type == Assign\n globals[x.left.value] = interp(x.right)\n return NULL\n elif x.node_type is a binary operator return interp(x.left) operator interp(x.right)\n elif x.node_type is a unary operator, return return operator interp(x.left)\n elif x.node_type == If\n if (interp(x.left)) then interp(x.right.left)\n else interp(x.right.right)\n return NULL\n elif x.node_type == While\n while (interp(x.left)) do interp(x.right)\n return NULL\n elif x.node_type == Prtc\n print interp(x.left) as a character, no newline\n return NULL\n elif x.node_type == Prti\n print interp(x.left) as an integer, no newline\n return NULL\n elif x.node_type == Prts\n print interp(x.left) as a string, respecting newlines (\"\\n\")\n return NULL\n elif x.node_type == Sequence\n interp(x.left)\n interp(x.right)\n return NULL\n else\n error(\"unknown node type\")</syntaxhighlight>\n\nNotes:\n\nBecause of the simple nature of our tiny language, Semantic analysis is not needed.\n\nYour interpreter should use C like division semantics, for both division and modulus. For division of positive operands, only the non-fractional portion of the result should be returned. In other words, the result should be truncated towards 0.\n\nThis means, for instance, that 3 / 2 should result in 1.\n\nFor division when one of the operands is negative, the result should be truncated towards 0.\n\nThis means, for instance, that 3 / -2 should result in -1.\n\n; Test program\n\n{| class=\"wikitable\"\n|-\n! prime.t\n! lex &lt;prime.t \t&#124; parse &#124; interp\n|-\n| style=\"vertical-align:top\" |\n<syntaxhighlight lang=\"c\">/*\n Simple prime number generator\n */\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n k=3;\n p=1;\n n=n+2;\n while ((k*k<=n) && (p)) {\n p=n/k*k!=n;\n k=k+2;\n }\n if (p) {\n print(n, \" is prime\\n\");\n count = count + 1;\n }\n}\nprint(\"Total primes found: \", count, \"\\n\"); </syntaxhighlight>\n\n| style=\"vertical-align:top\" |\n<b><pre>\n3 is prime\n5 is prime\n7 is prime\n11 is prime\n13 is prime\n17 is prime\n19 is prime\n23 is prime\n29 is prime\n31 is prime\n37 is prime\n41 is prime\n43 is prime\n47 is prime\n53 is prime\n59 is prime\n61 is prime\n67 is prime\n71 is prime\n73 is prime\n79 is prime\n83 is prime\n89 is prime\n97 is prime\n101 is prime\nTotal primes found: 26\n</pre></b>\n\n|}\n\n; Additional examples\n\nYour solution should pass all the test cases above and the additional tests found '''[[Compiler/Sample_programs|Here]]'''.\n\n{{task heading|Reference}}\n\nThe C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* [[Compiler/lexical_analyzer|Lexical Analyzer task]]\n* [[Compiler/syntax_analyzer|Syntax Analyzer task]]\n* [[Compiler/code_generator|Code Generator task]]\n* [[Compiler/virtual_machine_interpreter|Virtual Machine Interpreter task]]\n\n<hr>\n__TOC__\n\n", "language": "00-TASK" }, { "code": "begin % AST interpreter %\n % parse tree nodes %\n record node( integer type\n ; reference(node) left, right\n ; integer iValue % nString/nIndentifier number or nInteger value %\n );\n integer nIdentifier, nString, nInteger, nSequence, nIf, nPrtc, nPrts\n , nPrti, nWhile, nAssign, nNegate, nNot, nMultiply\n , nDivide, nMod, nAdd, nSubtract, nLess, nLessEqual\n , nGreater, nGreaterEqual, nEqual, nNotEqual, nAnd, nOr\n ;\n string(14) array ndName ( 1 :: 25 );\n integer MAX_NODE_TYPE;\n % string literals and identifiers - uses a linked list - a hash table might be better... %\n string(1) array text ( 0 :: 4095 );\n integer textNext, TEXT_MAX;\n record textElement ( integer start, length; reference(textElement) next );\n reference(textElement) idList, stList;\n % memory - identifiers hold indexes to locations here %\n integer array data ( 1 :: 4096 );\n\n % returns a new node with left and right branches %\n reference(node) procedure opNode ( integer value opType; reference(node) value opLeft, opRight ) ; begin\n node( opType, opLeft, opRight, 0 )\n end opNode ;\n\n % returns a new operand node %\n reference(node) procedure operandNode ( integer value opType, opValue ) ; begin\n node( opType, null, null, opValue )\n end operandNode ;\n\n % reports an error and stops %\n procedure rtError( string(80) value message ); begin\n integer errorPos;\n write( s_w := 0, \"**** Runtime error \" );\n errorPos := 0;\n while errorPos < 80 and message( errorPos // 1 ) not = \".\" do begin\n writeon( s_w := 0, message( errorPos // 1 ) );\n errorPos := errorPos + 1\n end while_not_at_end_of_message ;\n writeon( s_w := 0, \".\" );\n assert( false )\n end rtError ;\n\n % reads a node from standard input %\n reference(node) procedure readNode ; begin\n reference(node) resultNode;\n\n % parses a string from line and stores it in a string in the text array %\n % - if it is not already present in the specified textElement list. %\n % returns the position of the string in the text array %\n integer procedure readString ( reference(textElement) value result txList; string(1) value terminator ) ; begin\n string(256) str;\n integer sLen, sPos, ePos;\n logical found;\n reference(textElement) txPos, txLastPos;\n % get the text of the string %\n str := \" \";\n sLen := 0;\n str( sLen // 1 ) := line( lPos // 1 );\n sLen := sLen + 1;\n lPos := lPos + 1;\n while lPos <= 255 and line( lPos // 1 ) not = terminator do begin\n str( sLen // 1 ) := line( lPos // 1 );\n sLen := sLen + 1;\n lPos := lPos + 1\n end while_more_string ;\n if lPos > 255 then rtError( \"Unterminated String in node file.\" );\n % attempt to find the text in the list of strings/identifiers %\n txLastPos := txPos := txList;\n found := false;\n ePos := 0;\n while not found and txPos not = null do begin\n ePos := ePos + 1;\n found := ( length(txPos) = sLen );\n sPos := 0;\n while found and sPos < sLen do begin\n found := str( sPos // 1 ) = text( start(txPos) + sPos );\n sPos := sPos + 1\n end while_not_found ;\n txLastPos := txPos;\n if not found then txPos := next(txPos)\n end while_string_not_found ;\n if not found then begin\n % the string/identifier is not in the list - add it %\n ePos := ePos + 1;\n if txList = null then txList := textElement( textNext, sLen, null )\n else next(txLastPos) := textElement( textNext, sLen, null );\n if textNext + sLen > TEXT_MAX then rtError( \"Text space exhausted.\" )\n else begin\n for cPos := 0 until sLen - 1 do begin\n text( textNext ) := str( cPos // 1 );\n textNext := textNext + 1\n end for_cPos\n end\n end if_not_found ;\n ePos\n end readString ;\n\n % gets an integer from the line - no checks for valid digits %\n integer procedure readInteger ; begin\n integer n;\n n := 0;\n while line( lPos // 1 ) not = \" \" do begin\n n := ( n * 10 ) + ( decode( line( lPos // 1 ) ) - decode( \"0\" ) );\n lPos := lPos + 1\n end while_not_end_of_integer ;\n n\n end readInteger ;\n\n string(256) line;\n string(16) name;\n integer lPos, tPos, ndType;\n tPos := lPos := 0;\n readcard( line );\n % get the node type name %\n while line( lPos // 1 ) = \" \" do lPos := lPos + 1;\n name := \"\";\n while lPos < 256 and line( lPos // 1 ) not = \" \" do begin\n name( tPos // 1 ) := line( lPos // 1 );\n lPos := lPos + 1;\n tPos := tPos + 1\n end while_more_name ;\n % determine the node type %\n ndType := 1;\n resultNode := null;\n if name not = \";\" then begin\n % not a null node %\n while ndType <= MAX_NODE_TYPE and name not = ndName( ndType ) do ndType := ndType + 1;\n if ndType > MAX_NODE_TYPE then rtError( \"Malformed node.\" );\n % handle the additional parameter for identifier/string/integer, or sub-nodes for operator nodes %\n if ndType = nInteger or ndType = nIdentifier or ndType = nString then begin\n while line( lPos // 1 ) = \" \" do lPos := lPos + 1;\n if ndType = nInteger then resultNode := operandNode( ndType, readInteger )\n else if ndType = nIdentifier then resultNode := operandNode( ndType, readString( idList, \" \" ) )\n else % ndType = nString % resultNode := operandNode( ndType, readString( stList, \"\"\"\" ) )\n end\n else begin\n % operator node %\n reference(node) leftNode;\n leftNode := readNode;\n resultNode := opNode( ndType, leftNode, readNode )\n end\n end if_non_null_node ;\n resultNode\n end readNode ;\n\n % interprets the specified node and returns the value %\n integer procedure eval ( reference(node) value n ) ; begin\n integer v;\n\n % prints a string from text, escape sequences are interpreted %\n procedure writeOnText( reference(textElement) value txHead; integer value txNumber ) ;\n begin\n reference(textElement) txPos;\n integer count;\n txPos := txHead;\n count := 1;\n while count < txNumber and txPos not = null do begin\n txPos := next(txPos);\n count := count + 1\n end while_text_element_not_found ;\n if txPos = null then rtError( \"INTERNAL ERROR: text not found.\" )\n else begin\n % found the text - output it, handling escape sequences %\n integer cPos;\n cPos := 1; % start from 1 to skip over the leading \" %\n while cPos < length(txPos) do begin\n string(1) ch;\n ch := text( start(txPos) + cPos );\n if ch not = \"\\\" then writeon( s_w := 0, ch )\n else begin\n % escaped character %\n cPos := cPos + 1;\n if cPos > length(txPos) then rtError( \"String terminates with \"\"\\\"\".\" )\n else begin\n ch := text( start(txPos) + cPos );\n if ch = \"n\" then % newline % write()\n else writeon( s_w := 0, ch )\n end\n end;\n cPos := cPos + 1\n end while_not_end_of_string\n end\n end writeOnText ;\n\n % returns 1 if val is true, 0 otherwise %\n integer procedure booleanResult ( logical value val ) ; begin\n if val then 1 else 0\n end booleanResult ;\n\n v := 0;\n\n if n = null then v := 0\n else if type(n) = nIdentifier then v := data( iValue(n) )\n else if type(n) = nString then v := iValue(n)\n else if type(n) = nInteger then v := iValue(n)\n else if type(n) = nSequence then begin\n % sequence - evaluate and discard the left branch and return the right branch %\n v := eval( left(n) );\n v := eval( right(n) )\n end\n else if type(n) = nIf then % if-else % begin\n if eval( left(n) ) not = 0 then v := eval( left(right(n)) )\n else v := eval( right(right(n)) );\n v := 0\n end\n else if type(n) = nPrtc then % print character % writeon( s_w := 0, code( eval( left(n) ) ) )\n else if type(n) = nPrts then % print string % writeOnText( stList, eval( left(n) ) )\n else if type(n) = nPrti then % print integer % writeon( s_w := 0, i_w := 1, eval( left(n) ) )\n else if type(n) = nWhile then % while-loop % begin\n while eval( left(n) ) not = 0 do v := eval( right(n) );\n v := 0\n end\n else if type(n) = nAssign then % assignment % data( iValue(left(n)) ) := eval( right(n) )\n else if type(n) = nNegate then % unary - % v := - eval( left(n) )\n else if type(n) = nNot then % unary not % v := booleanResult( eval( left(n) ) = 0 )\n else if type(n) = nMultiply then % multiply % v := eval( left(n) ) * eval( right(n) )\n else if type(n) = nDivide then % division % begin\n integer lv, rv;\n lv := eval( left(n) );\n rv := eval( right(n) );\n if rv = 0 then rtError( \"Division by 0.\" )\n else v := lv div rv\n end\n else if type(n) = nMod then % modulo % begin\n integer lv, rv;\n lv := eval( left(n) );\n rv := eval( right(n) );\n if rv = 0 then rtError( \"Right operand of % is 0.\" )\n else v := lv rem rv\n end\n else if type(n) = nAdd then % addition % v := eval( left(n) ) + eval( right(n) )\n else if type(n) = nSubtract then % subtraction % v := eval( left(n) ) - eval( right(n) )\n else if type(n) = nLess then % less-than % v := booleanResult( eval( left(n) ) < eval( right(n) ) )\n else if type(n) = nLessEqual then % less or equal % v := booleanResult( eval( left(n) ) <= eval( right(n) ) )\n else if type(n) = nGreater then % greater-than % v := booleanResult( eval( left(n) ) > eval( right(n) ) )\n else if type(n) = nGreaterEqual then % greater or eq % v := booleanResult( eval( left(n) ) >= eval( right(n) ) )\n else if type(n) = nEqual then % test equal % v := booleanResult( eval( left(n) ) = eval( right(n) ) )\n else if type(n) = nNotEqual then % not-equal % v := booleanResult( eval( left(n) ) not = eval( right(n) ) )\n else if type(n) = nAnd then % boolean \"and\" % begin\n v := eval( left(n) );\n if v not = 0 then v := eval( right(n) )\n end\n else if type(n) = nOr then % boolean \"or\" % begin\n v := eval( left(n) );\n if v = 0 then v := eval( right(n) );\n end\n else % unknown node % begin\n rtError( \"Unknown node type in eval.\" )\n end;\n v\n end eval ;\n\n nIdentifier := 1; ndName( nIdentifier ) := \"Identifier\"; nString := 2; ndName( nString ) := \"String\";\n nInteger := 3; ndName( nInteger ) := \"Integer\"; nSequence := 4; ndName( nSequence ) := \"Sequence\";\n nIf := 5; ndName( nIf ) := \"If\"; nPrtc := 6; ndName( nPrtc ) := \"Prtc\";\n nPrts := 7; ndName( nPrts ) := \"Prts\"; nPrti := 8; ndName( nPrti ) := \"Prti\";\n nWhile := 9; ndName( nWhile ) := \"While\"; nAssign := 10; ndName( nAssign ) := \"Assign\";\n nNegate := 11; ndName( nNegate ) := \"Negate\"; nNot := 12; ndName( nNot ) := \"Not\";\n nMultiply := 13; ndName( nMultiply ) := \"Multiply\"; nDivide := 14; ndName( nDivide ) := \"Divide\";\n nMod := 15; ndName( nMod ) := \"Mod\"; nAdd := 16; ndName( nAdd ) := \"Add\";\n nSubtract := 17; ndName( nSubtract ) := \"Subtract\"; nLess := 18; ndName( nLess ) := \"Less\";\n nLessEqual := 19; ndName( nLessEqual ) := \"LessEqual\" ; nGreater := 20; ndName( nGreater ) := \"Greater\";\n nGreaterEqual := 21; ndName( nGreaterEqual ) := \"GreaterEqual\"; nEqual := 22; ndName( nEqual ) := \"Equal\";\n nNotEqual := 23; ndName( nNotEqual ) := \"NotEqual\"; nAnd := 24; ndName( nAnd ) := \"And\";\n nOr := 25; ndName( nOr ) := \"Or\";\n MAX_NODE_TYPE := 25; TEXT_MAX := 4095; textNext := 0;\n stList := idList := null;\n\n % parse the output from the syntax analyser and intetrpret parse tree %\n eval( readNode )\nend.\n", "language": "ALGOL-W" }, { "code": "(* The Rosetta Code AST interpreter in ATS2.\n\n This implementation reuses the AST loader of my Code Generator\n implementation. *)\n\n(* Usage: gen [INPUTFILE [OUTPUTFILE]]\n If INPUTFILE or OUTPUTFILE is \"-\" or missing, then standard input\n or standard output is used, respectively. *)\n\n(* Note: you might wish to add code to catch exceptions and print nice\n messages. *)\n\n(*------------------------------------------------------------------*)\n\n#define ATS_DYNLOADFLAG 0\n\n#include \"share/atspre_staload.hats\"\nstaload UN = \"prelude/SATS/unsafe.sats\"\n\n#define NIL list_vt_nil ()\n#define :: list_vt_cons\n\n%{^\n/* alloca(3) is needed for ATS exceptions. */\n#include <alloca.h>\n%}\n\nexception internal_error of ()\nexception bad_ast_node_type of string\nexception premature_end_of_input of ()\nexception bad_number_field of string\nexception missing_identifier_field of ()\nexception bad_quoted_string of string\n\n(* Some implementations that are likely missing from the prelude. *)\nimplement g0uint2uint<sizeknd, ullintknd> x = $UN.cast x\nimplement g0uint2uint<ullintknd, sizeknd> x = $UN.cast x\nimplement g0uint2int<ullintknd, llintknd> x = $UN.cast x\nimplement g0int2uint<llintknd, sizeknd> x = $UN.cast x\nimplement g0int2int<llintknd, intknd> x = $UN.cast x\n\n(*------------------------------------------------------------------*)\n\nextern fn {}\nskip_characters$skipworthy (c : char) :<> bool\n\nfn {}\nskip_characters {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n :<> [j : int | i <= j; j <= n]\n size_t j =\n let\n fun\n loop {k : int | i <= k; k <= n}\n .<n - k>.\n (k : size_t k)\n :<> [j : int | k <= j; j <= n]\n size_t j =\n if string_is_atend (s, k) then\n k\n else if ~skip_characters$skipworthy (s[k]) then\n k\n else\n loop (succ k)\n in\n loop i\n end\n\nfn\nskip_whitespace {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n :<> [j : int | i <= j; j <= n]\n size_t j =\n let\n implement\n skip_characters$skipworthy<> c =\n isspace c\n in\n skip_characters<> (s, i)\n end\n\nfn\nskip_nonwhitespace {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n :<> [j : int | i <= j; j <= n]\n size_t j =\n let\n implement\n skip_characters$skipworthy<> c =\n ~isspace c\n in\n skip_characters<> (s, i)\n end\n\nfn\nskip_nonquote {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n :<> [j : int | i <= j; j <= n]\n size_t j =\n let\n implement\n skip_characters$skipworthy<> c =\n c <> '\"'\n in\n skip_characters<> (s, i)\n end\n\nfn\nskip_to_end {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n :<> [j : int | i <= j; j <= n]\n size_t j =\n let\n implement\n skip_characters$skipworthy<> c =\n true\n in\n skip_characters<> (s, i)\n end\n\n(*------------------------------------------------------------------*)\n\nfn\nsubstring_equals {n : int}\n {i, j : nat | i <= j; j <= n}\n (s : string n,\n i : size_t i,\n j : size_t j,\n t : string)\n :<> bool =\n let\n val m = strlen t\n in\n if j - i <> m then\n false (* The substring is the wrong length. *)\n else\n let\n val p_s = ptrcast s\n and p_t = ptrcast t\n in\n 0 = $extfcall (int, \"strncmp\",\n ptr_add<char> (p_s, i), p_t, m)\n end\n end\n\n(*------------------------------------------------------------------*)\n\ndatatype node_type_t =\n| NullNode\n| Identifier\n| String\n| Integer\n| Sequence\n| If\n| Prtc\n| Prts\n| Prti\n| While\n| Assign\n| Negate\n| Not\n| Multiply\n| Divide\n| Mod\n| Add\n| Subtract\n| Less\n| LessEqual\n| Greater\n| GreaterEqual\n| Equal\n| NotEqual\n| And\n| Or\n\n#define ARBITRARY_NODE_ARG 1234\n\ndatatype ast_node_t =\n| ast_node_t_nil\n| ast_node_t_nonnil of node_contents_t\nwhere node_contents_t =\n @{\n node_type = node_type_t,\n node_arg = ullint,\n node_left = ast_node_t,\n node_right = ast_node_t\n }\n\nfn\nget_node_type {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n : [j : int | i <= j; j <= n]\n @(node_type_t,\n size_t j) =\n let\n val i_start = skip_whitespace (s, i)\n val i_end = skip_nonwhitespace (s, i_start)\n\n macdef eq t =\n substring_equals (s, i_start, i_end, ,(t))\n\n val node_type =\n if eq \";\" then\n NullNode\n else if eq \"Identifier\" then\n Identifier\n else if eq \"String\" then\n String\n else if eq \"Integer\" then\n Integer\n else if eq \"Sequence\" then\n Sequence\n else if eq \"If\" then\n If\n else if eq \"Prtc\" then\n Prtc\n else if eq \"Prts\" then\n Prts\n else if eq \"Prti\" then\n Prti\n else if eq \"While\" then\n While\n else if eq \"Assign\" then\n Assign\n else if eq \"Negate\" then\n Negate\n else if eq \"Not\" then\n Not\n else if eq \"Multiply\" then\n Multiply\n else if eq \"Divide\" then\n Divide\n else if eq \"Mod\" then\n Mod\n else if eq \"Add\" then\n Add\n else if eq \"Subtract\" then\n Subtract\n else if eq \"Less\" then\n Less\n else if eq \"LessEqual\" then\n LessEqual\n else if eq \"Greater\" then\n Greater\n else if eq \"GreaterEqual\" then\n GreaterEqual\n else if eq \"Equal\" then\n Equal\n else if eq \"NotEqual\" then\n NotEqual\n else if eq \"And\" then\n And\n else if eq \"Or\" then\n Or\n else\n let\n val s_bad =\n strnptr2string\n (string_make_substring (s, i_start, i_end - i_start))\n in\n $raise bad_ast_node_type s_bad\n end\n in\n @(node_type, i_end)\n end\n\nfn\nget_unsigned {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n : [j : int | i <= j; j <= n]\n @(ullint,\n size_t j) =\n let\n val i = skip_whitespace (s, i)\n val [j : int] j = skip_nonwhitespace (s, i)\n in\n if j = i then\n $raise bad_number_field \"\"\n else\n let\n fun\n loop {k : int | i <= k; k <= j}\n (k : size_t k,\n v : ullint)\n : ullint =\n if k = j then\n v\n else\n let\n val c = s[k]\n in\n if ~isdigit c then\n let\n val s_bad =\n strnptr2string\n (string_make_substring (s, i, j - i))\n in\n $raise bad_number_field s_bad\n end\n else\n let\n val digit = char2int1 c - char2int1 '0'\n val () = assertloc (0 <= digit)\n in\n loop (succ k, (g1i2u 10 * v) + g1i2u digit)\n end\n end\n in\n @(loop (i, g0i2u 0), j)\n end\n end\n\nfn\nget_identifier\n {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n : [j : int | i <= j; j <= n]\n @(string,\n size_t j) =\n let\n val i = skip_whitespace (s, i)\n val j = skip_nonwhitespace (s, i)\n in\n if i = j then\n $raise missing_identifier_field ()\n else\n let\n val ident =\n strnptr2string (string_make_substring (s, i, j - i))\n in\n @(ident, j)\n end\n end\n\nfn\nget_quoted_string\n {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n : [j : int | i <= j; j <= n]\n @(string,\n size_t j) =\n let\n val i = skip_whitespace (s, i)\n in\n if string_is_atend (s, i) then\n $raise bad_quoted_string \"\"\n else if s[i] <> '\"' then\n let\n val j = skip_to_end (s, i)\n val s_bad =\n strnptr2string (string_make_substring (s, i, j - i))\n in\n $raise bad_quoted_string s_bad\n end\n else\n let\n val j = skip_nonquote (s, succ i)\n in\n if string_is_atend (s, j) then\n let\n val s_bad =\n strnptr2string (string_make_substring (s, i, j - i))\n in\n $raise bad_quoted_string s_bad\n end\n else\n let\n val quoted_string =\n strnptr2string\n (string_make_substring (s, i, succ j - i))\n in\n @(quoted_string, succ j)\n end\n end\n end\n\nfn\ncollect_string\n {n : int}\n (str : string,\n strings : &list_vt (string, n) >> list_vt (string, m))\n : #[m : int | m == n || m == n + 1]\n [str_num : nat | str_num <= m]\n size_t str_num =\n (* This implementation uses ‘list_vt’ instead of ‘list’, so\n appending elements to the end of the list will be both efficient\n and safe. It would also have been reasonable to build a ‘list’\n backwards and then make a reversed copy. *)\n let\n fun\n find_or_extend\n {i : nat | i <= n}\n .<n - i>.\n (strings1 : &list_vt (string, n - i)\n >> list_vt (string, m),\n i : size_t i)\n : #[m : int | m == n - i || m == n - i + 1]\n [j : nat | j <= n]\n size_t j =\n case+ strings1 of\n | ~ NIL =>\n let (* The string is not there. Extend the list. *)\n prval () = prop_verify {i == n} ()\n in\n strings1 := (str :: NIL);\n i\n end\n | @ (head :: tail) =>\n if head = str then\n let (* The string is found. *)\n prval () = fold@ strings1\n in\n i\n end\n else\n let (* Continue looking. *)\n val j = find_or_extend (tail, succ i)\n prval () = fold@ strings1\n in\n j\n end\n\n prval () = lemma_list_vt_param strings\n val n = i2sz (length strings)\n and j = find_or_extend (strings, i2sz 0)\n in\n j\n end\n\nfn\nload_ast (inpf : FILEref,\n idents : &List_vt string >> _,\n strings : &List_vt string >> _)\n : ast_node_t =\n let\n fun\n recurs (idents : &List_vt string >> _,\n strings : &List_vt string >> _)\n : ast_node_t =\n if fileref_is_eof inpf then\n $raise premature_end_of_input ()\n else\n let\n val s = strptr2string (fileref_get_line_string inpf)\n prval () = lemma_string_param s (* String length >= 0. *)\n\n val i = i2sz 0\n val @(node_type, i) = get_node_type (s, i)\n in\n case+ node_type of\n | NullNode () => ast_node_t_nil ()\n | Integer () =>\n let\n val @(number, _) = get_unsigned (s, i)\n in\n ast_node_t_nonnil\n @{\n node_type = node_type,\n node_arg = number,\n node_left = ast_node_t_nil,\n node_right = ast_node_t_nil\n }\n end\n | Identifier () =>\n let\n val @(ident, _) = get_identifier (s, i)\n val arg = collect_string (ident, idents)\n in\n ast_node_t_nonnil\n @{\n node_type = node_type,\n node_arg = g0u2u arg,\n node_left = ast_node_t_nil,\n node_right = ast_node_t_nil\n }\n end\n | String () =>\n let\n val @(quoted_string, _) = get_quoted_string (s, i)\n val arg = collect_string (quoted_string, strings)\n in\n ast_node_t_nonnil\n @{\n node_type = node_type,\n node_arg = g0u2u arg,\n node_left = ast_node_t_nil,\n node_right = ast_node_t_nil\n }\n end\n | _ =>\n let\n val node_left = recurs (idents, strings)\n val node_right = recurs (idents, strings)\n in\n ast_node_t_nonnil\n @{\n node_type = node_type,\n node_arg = g1i2u ARBITRARY_NODE_ARG,\n node_left = node_left,\n node_right = node_right\n }\n end\n end\n in\n recurs (idents, strings)\n end\n\n(*------------------------------------------------------------------*)\n\nmacdef void_value = 0LL\n\nfn\nbool2llint (b : bool)\n :<> llint =\n if b then 1LL else 0LL\n\nfun\ndequote_into_array\n {p : addr}\n {n : int | 2 <= n}\n {i : nat | i <= n - 1}\n {j : int | 1 <= j; j <= n - 1}\n .<n + 1 - j>.\n (pf : !array_v (char, p, n - 1) |\n p : ptr p,\n n : size_t n,\n i : size_t i,\n s : string n,\n j : size_t j)\n : void =\n if (j <> pred n) * (succ i < pred n) then\n let\n macdef t = !p\n in\n if s[j] = '\\\\' then\n begin\n if succ j = pred n then\n $raise bad_quoted_string s\n else if s[succ j] = 'n' then\n begin\n t[i] := '\\n';\n dequote_into_array (pf | p, n, succ i, s, j + i2sz 2)\n end\n else if s[succ j] = '\\\\' then\n begin\n t[i] := '\\\\';\n dequote_into_array (pf | p, n, succ i, s, j + i2sz 2)\n end\n else\n $raise bad_quoted_string s\n end\n else\n begin\n t[i] := s[j];\n dequote_into_array (pf | p, n, succ i, s, succ j)\n end\n end\n\nfn\ndequote {n : int}\n (s : string n)\n : string =\n let\n val n = strlen s\n prval [n : int] EQINT () = eqint_make_guint n\n\n val () = assertloc (i2sz 2 <= n)\n\n val () = assertloc (s[0] = '\"')\n and () = assertloc (s[pred n] = '\"')\n\n val @(pf, pfgc | p) = array_ptr_alloc<char> (pred n)\n val () = array_initize_elt<char> (!p, pred n, '\\0')\n val () = dequote_into_array (pf | p, n, i2sz 0, s, i2sz 1)\n val retval = strptr2string (string0_copy ($UN.cast{string} p))\n val () = array_ptr_free (pf, pfgc | p)\n in\n retval\n end\n\nfn\nfill_string_pool (string_pool : arrszref string,\n strings : List string)\n : void =\n let\n #define NIL list_nil ()\n #define :: list_cons\n\n fun\n loop {n : nat}\n .<n>.\n (strings : list (string, n),\n i : size_t)\n : void =\n case+ strings of\n | NIL => ()\n | head :: tail =>\n begin\n string_pool[i] := dequote (g1ofg0 head);\n loop (tail, succ i)\n end\n\n prval () = lemma_list_param strings\n in\n loop (strings, i2sz 0)\n end\n\nfn\ninterpret_ast (outf : FILEref,\n ast : ast_node_t,\n datasize : size_t,\n strings : List string)\n : llint =\n let\n prval () = lemma_list_param strings\n val num_strings = i2sz (length strings)\n\n val data = arrszref_make_elt<llint> (datasize, void_value)\n and string_pool = arrszref_make_elt<string> (num_strings, \"\")\n\n val () = fill_string_pool (string_pool, strings)\n\n fnx\n traverse (ast : ast_node_t)\n : llint =\n case+ ast of\n | ast_node_t_nil () => void_value\n | ast_node_t_nonnil contents =>\n begin\n case- contents.node_type of\n | NullNode () => $raise internal_error ()\n\n | If () => if_then contents\n | While () => while_do contents\n\n | Sequence () =>\n let\n val _ = traverse contents.node_left\n val _ = traverse contents.node_right\n in\n void_value\n end\n\n | Assign () =>\n let\n val- ast_node_t_nonnil contents1 = contents.node_left\n val i = contents1.node_arg\n val x = traverse contents.node_right\n in\n data[i] := x;\n void_value\n end\n\n | Identifier () => data[contents.node_arg]\n\n | Integer () => g0u2i (contents.node_arg)\n | String () => g0u2i (contents.node_arg)\n\n | Prtc () =>\n let\n val i = traverse contents.node_left\n in\n fprint! (outf, int2char0 (g0i2i i));\n void_value\n end\n | Prti () =>\n let\n val i = traverse contents.node_left\n in\n fprint! (outf, i);\n void_value\n end\n | Prts () =>\n let\n val i = traverse contents.node_left\n in\n fprint! (outf, string_pool[i]);\n void_value\n end\n\n | Negate () => unary_op (g0int_neg, contents)\n | Not () =>\n unary_op (lam x => bool2llint (iseqz x), contents)\n\n | Multiply () => binary_op (g0int_mul, contents)\n | Divide () => binary_op (g0int_div, contents)\n | Mod () => binary_op (g0int_mod, contents)\n | Add () => binary_op (g0int_add, contents)\n | Subtract () => binary_op (g0int_sub, contents)\n | Less () =>\n binary_op (lam (x, y) => bool2llint (x < y), contents)\n | LessEqual () =>\n binary_op (lam (x, y) => bool2llint (x <= y), contents)\n | Greater () =>\n binary_op (lam (x, y) => bool2llint (x > y), contents)\n | GreaterEqual () =>\n binary_op (lam (x, y) => bool2llint (x >= y), contents)\n | Equal () =>\n binary_op (lam (x, y) => bool2llint (x = y), contents)\n | NotEqual () =>\n binary_op (lam (x, y) => bool2llint (x <> y), contents)\n | And () =>\n binary_op (lam (x, y) =>\n bool2llint ((isneqz x) * (isneqz y)),\n contents)\n | Or () =>\n binary_op (lam (x, y) =>\n bool2llint ((isneqz x) + (isneqz y)),\n contents)\n end\n and\n if_then (contents : node_contents_t)\n : llint =\n case- (contents.node_right) of\n | ast_node_t_nonnil contents1 =>\n let\n val condition = (contents.node_left)\n and true_branch = (contents1.node_left)\n and false_branch = (contents1.node_right)\n\n val branch =\n if isneqz (traverse condition) then\n true_branch\n else\n false_branch\n\n val _ = traverse branch\n in\n void_value\n end\n and\n while_do (contents : node_contents_t)\n : llint =\n let\n val condition = contents.node_left\n and body = contents.node_right\n\n fun\n loop () : void =\n if isneqz (traverse condition) then\n let\n val _ = traverse body\n in\n loop ()\n end\n in\n loop ();\n void_value\n end\n and\n unary_op (operation : llint -> llint,\n contents : node_contents_t)\n : llint =\n let\n val x = traverse contents.node_left\n in\n operation x\n end\n and\n binary_op (operation : (llint, llint) -> llint,\n contents : node_contents_t)\n : llint =\n let\n val x = traverse contents.node_left\n val y = traverse contents.node_right\n in\n x \\operation y\n end\n in\n traverse ast\n end\n\n(*------------------------------------------------------------------*)\n\nfn\nmain_program (inpf : FILEref,\n outf : FILEref)\n : int =\n let\n var idents : List_vt string = NIL\n var strings : List_vt string = NIL\n\n val ast = load_ast (inpf, idents, strings)\n\n prval () = lemma_list_vt_param idents\n val datasize = i2sz (length idents)\n val () = free idents\n\n val strings = list_vt2t strings\n\n val _ = interpret_ast (outf, ast, datasize, strings)\n in\n 0\n end\n\nimplement\nmain (argc, argv) =\n let\n val inpfname =\n if 2 <= argc then\n $UN.cast{string} argv[1]\n else\n \"-\"\n val outfname =\n if 3 <= argc then\n $UN.cast{string} argv[2]\n else\n \"-\"\n val inpf =\n if (inpfname : string) = \"-\" then\n stdin_ref\n else\n fileref_open_exn (inpfname, file_mode_r)\n\n val outf =\n if (outfname : string) = \"-\" then\n stdout_ref\n else\n fileref_open_exn (outfname, file_mode_w)\n in\n main_program (inpf, outf)\n end\n\n(*------------------------------------------------------------------*)\n", "language": "ATS" }, { "code": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdarg.h>\n#include <ctype.h>\n\n#define da_dim(name, type) type *name = NULL; \\\n int _qy_ ## name ## _p = 0; \\\n int _qy_ ## name ## _max = 0\n#define da_rewind(name) _qy_ ## name ## _p = 0\n#define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n#define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n#define da_len(name) _qy_ ## name ## _p\n#define da_add(name) do {da_redim(name); _qy_ ## name ## _p++;} while (0)\n\ntypedef enum {\n nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While,\n nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq,\n nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or\n} NodeType;\n\ntypedef struct Tree Tree;\nstruct Tree {\n NodeType node_type;\n Tree *left;\n Tree *right;\n int value;\n};\n\n// dependency: Ordered by NodeType, must remain in same order as NodeType enum\n\nstruct {\n char *enum_text;\n NodeType node_type;\n} atr[] = {\n {\"Identifier\" , nd_Ident, }, {\"String\" , nd_String, },\n {\"Integer\" , nd_Integer,}, {\"Sequence\" , nd_Sequence,},\n {\"If\" , nd_If, }, {\"Prtc\" , nd_Prtc, },\n {\"Prts\" , nd_Prts, }, {\"Prti\" , nd_Prti, },\n {\"While\" , nd_While, }, {\"Assign\" , nd_Assign, },\n {\"Negate\" , nd_Negate, }, {\"Not\" , nd_Not, },\n {\"Multiply\" , nd_Mul, }, {\"Divide\" , nd_Div, },\n {\"Mod\" , nd_Mod, }, {\"Add\" , nd_Add, },\n {\"Subtract\" , nd_Sub, }, {\"Less\" , nd_Lss, },\n {\"LessEqual\" , nd_Leq, }, {\"Greater\" , nd_Gtr, },\n {\"GreaterEqual\", nd_Geq, }, {\"Equal\" , nd_Eql, },\n {\"NotEqual\" , nd_Neq, }, {\"And\" , nd_And, },\n {\"Or\" , nd_Or, },\n};\n\nFILE *source_fp;\nda_dim(string_pool, const char *);\nda_dim(global_names, const char *);\nda_dim(global_values, int);\n\nvoid error(const char *fmt, ... ) {\n va_list ap;\n char buf[1000];\n\n va_start(ap, fmt);\n vsprintf(buf, fmt, ap);\n printf(\"error: %s\\n\", buf);\n exit(1);\n}\n\nTree *make_node(NodeType node_type, Tree *left, Tree *right) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->left = left;\n t->right = right;\n return t;\n}\n\nTree *make_leaf(NodeType node_type, int value) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->value = value;\n return t;\n}\n\nint interp(Tree *x) { /* interpret the parse tree */\n if (!x) return 0;\n switch(x->node_type) {\n case nd_Integer: return x->value;\n case nd_Ident: return global_values[x->value];\n case nd_String: return x->value;\n\n case nd_Assign: return global_values[x->left->value] = interp(x->right);\n case nd_Add: return interp(x->left) + interp(x->right);\n case nd_Sub: return interp(x->left) - interp(x->right);\n case nd_Mul: return interp(x->left) * interp(x->right);\n case nd_Div: return interp(x->left) / interp(x->right);\n case nd_Mod: return interp(x->left) % interp(x->right);\n case nd_Lss: return interp(x->left) < interp(x->right);\n case nd_Gtr: return interp(x->left) > interp(x->right);\n case nd_Leq: return interp(x->left) <= interp(x->right);\n case nd_Eql: return interp(x->left) == interp(x->right);\n case nd_Neq: return interp(x->left) != interp(x->right);\n case nd_And: return interp(x->left) && interp(x->right);\n case nd_Or: return interp(x->left) || interp(x->right);\n case nd_Negate: return -interp(x->left);\n case nd_Not: return !interp(x->left);\n\n case nd_If: if (interp(x->left))\n interp(x->right->left);\n else\n interp(x->right->right);\n return 0;\n\n case nd_While: while (interp(x->left))\n interp(x->right);\n return 0;\n\n case nd_Prtc: printf(\"%c\", interp(x->left));\n return 0;\n case nd_Prti: printf(\"%d\", interp(x->left));\n return 0;\n case nd_Prts: printf(\"%s\", string_pool[interp(x->left)]);\n return 0;\n\n case nd_Sequence: interp(x->left);\n interp(x->right);\n return 0;\n\n default: error(\"interp: unknown tree type %d\\n\", x->node_type);\n }\n return 0;\n}\n\nvoid init_in(const char fn[]) {\n if (fn[0] == '\\0')\n source_fp = stdin;\n else {\n source_fp = fopen(fn, \"r\");\n if (source_fp == NULL)\n error(\"Can't open %s\\n\", fn);\n }\n}\n\nNodeType get_enum_value(const char name[]) {\n for (size_t i = 0; i < sizeof(atr) / sizeof(atr[0]); i++) {\n if (strcmp(atr[i].enum_text, name) == 0) {\n return atr[i].node_type;\n }\n }\n error(\"Unknown token %s\\n\", name);\n return -1;\n}\n\nchar *read_line(int *len) {\n static char *text = NULL;\n static int textmax = 0;\n\n for (*len = 0; ; (*len)++) {\n int ch = fgetc(source_fp);\n if (ch == EOF || ch == '\\n') {\n if (*len == 0)\n return NULL;\n break;\n }\n if (*len + 1 >= textmax) {\n textmax = (textmax == 0 ? 128 : textmax * 2);\n text = realloc(text, textmax);\n }\n text[*len] = ch;\n }\n text[*len] = '\\0';\n return text;\n}\n\nchar *rtrim(char *text, int *len) { // remove trailing spaces\n for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n ;\n\n text[*len] = '\\0';\n return text;\n}\n\nint fetch_string_offset(char *st) {\n int len = strlen(st);\n st[len - 1] = '\\0';\n ++st;\n char *p, *q;\n p = q = st;\n\n while ((*p++ = *q++) != '\\0') {\n if (q[-1] == '\\\\') {\n if (q[0] == 'n') {\n p[-1] = '\\n';\n ++q;\n } else if (q[0] == '\\\\') {\n ++q;\n }\n }\n }\n\n for (int i = 0; i < da_len(string_pool); ++i) {\n if (strcmp(st, string_pool[i]) == 0) {\n return i;\n }\n }\n da_add(string_pool);\n int n = da_len(string_pool) - 1;\n string_pool[n] = strdup(st);\n return da_len(string_pool) - 1;\n}\n\nint fetch_var_offset(const char *name) {\n for (int i = 0; i < da_len(global_names); ++i) {\n if (strcmp(name, global_names[i]) == 0)\n return i;\n }\n da_add(global_names);\n int n = da_len(global_names) - 1;\n global_names[n] = strdup(name);\n da_append(global_values, 0);\n return n;\n}\n\nTree *load_ast() {\n int len;\n char *yytext = read_line(&len);\n yytext = rtrim(yytext, &len);\n\n // get first token\n char *tok = strtok(yytext, \" \");\n\n if (tok[0] == ';') {\n return NULL;\n }\n NodeType node_type = get_enum_value(tok);\n\n // if there is extra data, get it\n char *p = tok + strlen(tok);\n if (p != &yytext[len]) {\n int n;\n for (++p; isspace(*p); ++p)\n ;\n switch (node_type) {\n case nd_Ident: n = fetch_var_offset(p); break;\n case nd_Integer: n = strtol(p, NULL, 0); break;\n case nd_String: n = fetch_string_offset(p); break;\n default: error(\"Unknown node type: %s\\n\", p);\n }\n return make_leaf(node_type, n);\n }\n\n Tree *left = load_ast();\n Tree *right = load_ast();\n return make_node(node_type, left, right);\n}\n\nint main(int argc, char *argv[]) {\n init_in(argc > 1 ? argv[1] : \"\");\n\n Tree *x = load_ast();\n interp(x);\n\n return 0;\n}\n", "language": "C" }, { "code": " >>SOURCE FORMAT IS FREE\nidentification division.\n*> this code is dedicated to the public domain\n*> (GnuCOBOL) 2.3-dev.0\nprogram-id. astinterpreter.\nenvironment division.\nconfiguration section.\nrepository. function all intrinsic.\ndata division.\nworking-storage section.\n01 program-name pic x(32) value spaces global.\n01 input-name pic x(32) value spaces global.\n01 input-status pic xx global.\n\n01 ast-record global.\n 03 ast-type pic x(14).\n 03 ast-value pic x(48).\n 03 filler redefines ast-value.\n 05 asl-left pic 999.\n 05 asl-right pic 999.\n\n01 error-record pic x(64) value spaces global.\n\n01 loadstack global.\n 03 l pic 99 value 0.\n 03 l-lim pic 99 value 64.\n 03 load-entry occurs 64.\n 05 l-node pic x(14).\n 05 l-left pic 999.\n 05 l-right pic 999.\n 05 l-link pic 999.\n\n01 abstract-syntax-tree global.\n 03 t pic 999 value 0.\n 03 t1 pic 999.\n 03 n1 pic 999.\n 03 t-lim pic 999 value 998.\n 03 filler occurs 998.\n 05 leaf.\n 07 leaf-type pic x(14).\n 07 leaf-value pic x(48).\n 05 node redefines leaf.\n 07 node-type pic x(14).\n 07 node-left pic 999.\n 07 node-right pic 999.\n\n\n01 interpreterstack global.\n 03 stack1 pic 99 value 2.\n 03 stack2 pic 99 value 1.\n 03 stack-lim pic 99 value 32.\n 03 stack-entry occurs 32.\n 05 stack-source pic 99.\n 05 stack usage binary-int.\n\n01 variables global.\n 03 v pic 99.\n 03 v-max pic 99 value 0.\n 03 v-lim pic 99 value 16.\n 03 filler occurs 16.\n 05 variable-value binary-int.\n 05 variable-name pic x(48).\n\n01 strings global.\n 03 s pic 99.\n 03 s-max pic 99 value 0.\n 03 s-lim pic 99 value 16.\n 03 filler occurs 16 value spaces.\n 05 string-value pic x(48).\n\n01 string-fields global.\n 03 string-length pic 99.\n 03 string1 pic 99.\n 03 length1 pic 99.\n 03 count1 pic 99.\n\n01 display-fields global.\n 03 display-number pic -(9)9.\n 03 display-pending pic x value 'n'.\n 03 character-value.\n 05 character-number usage binary-char.\n\nprocedure division chaining program-name.\nstart-astinterpreter.\n call 'loadast'\n if program-name <> spaces\n call 'readinput' *> close the input-file\n end-if\n >>d perform print-ast\n call 'runast' using t\n if display-pending = 'y'\n display space\n end-if\n stop run\n .\nprint-ast.\n call 'printast' using t\n display 'ast:' upon syserr\n display 't=' t\n perform varying t1 from 1 by 1 until t1 > t\n if leaf-type(t1) = 'Identifier' or 'Integer' or 'String'\n display t1 space trim(leaf-type(t1)) space trim(leaf-value(t1)) upon syserr\n else\n display t1 space node-left(t1) space node-right(t1) space trim(node-type(t1))\n upon syserr\n end-if\n end-perform\n .\n\nidentification division.\nprogram-id. runast common recursive.\ndata division.\nworking-storage section.\n01 word-length constant as length of binary-int.\nlinkage section.\n01 n pic 999.\nprocedure division using n.\nstart-runast.\n if n = 0\n exit program\n end-if\n evaluate node-type(n)\n when 'Integer'\n perform push-stack\n move numval(leaf-value(n)) to stack(stack1)\n when 'Identifier'\n perform get-variable-index\n perform push-stack\n move v to stack-source(stack1)\n move variable-value(v) to stack(stack1)\n when 'String'\n perform get-string-index\n perform push-stack\n move s to stack-source(stack1)\n when 'Assign'\n call 'runast' using node-left(n)\n call 'runast' using node-right(n)\n move stack-source(stack2) to v\n move stack(stack1) to variable-value(v)\n perform pop-stack\n perform pop-stack\n when 'If'\n call 'runast' using node-left(n)\n move node-right(n) to n1\n if stack(stack1) <> 0\n call 'runast' using node-left(n1)\n else\n call 'runast' using node-right(n1)\n end-if\n perform pop-stack\n when 'While'\n call 'runast' using node-left(n)\n perform until stack(stack1) = 0\n perform pop-stack\n call 'runast' using node-right(n)\n call 'runast' using node-left(n)\n end-perform\n perform pop-stack\n when 'Add'\n perform get-values\n add stack(stack1) to stack(stack2)\n perform pop-stack\n when 'Subtract'\n perform get-values\n subtract stack(stack1) from stack(stack2)\n perform pop-stack\n when 'Multiply'\n perform get-values\n multiply stack(stack1) by stack(stack2)\n perform pop-stack\n when 'Divide'\n perform get-values\n divide stack(stack1) into stack(stack2)\n perform pop-stack\n when 'Mod'\n perform get-values\n move mod(stack(stack2),stack(stack1)) to stack(stack2)\n perform pop-stack\n when 'Less'\n perform get-values\n if stack(stack2) < stack(stack1)\n move 1 to stack(stack2)\n else\n move 0 to stack(stack2)\n end-if\n perform pop-stack\n when 'Greater'\n perform get-values\n if stack(stack2) > stack(stack1)\n move 1 to stack(stack2)\n else\n move 0 to stack(stack2)\n end-if\n perform pop-stack\n when 'LessEqual'\n perform get-values\n if stack(stack2) <= stack(stack1)\n move 1 to stack(stack2)\n else\n move 0 to stack(stack2)\n end-if\n perform pop-stack\n when 'GreaterEqual'\n perform get-values\n if stack(stack2) >= stack(stack1)\n move 1 to stack(stack2)\n else\n move 0 to stack(stack2)\n end-if\n perform pop-stack\n when 'Equal'\n perform get-values\n if stack(stack2) = stack(stack1)\n move 1 to stack(stack2)\n else\n move 0 to stack(stack2)\n end-if\n perform pop-stack\n when 'NotEqual'\n perform get-values\n if stack(stack2) <> stack(stack1)\n move 1 to stack(stack2)\n else\n move 0 to stack(stack2)\n end-if\n perform pop-stack\n when 'And'\n perform get-values\n call \"CBL_AND\" using stack(stack1) stack(stack2) by value word-length\n perform pop-stack\n when 'Or'\n perform get-values\n call \"CBL_OR\" using stack(stack1) stack(stack2) by value word-length\n perform pop-stack\n when 'Not'\n call 'runast' using node-left(n)\n if stack(stack1) = 0\n move 1 to stack(stack1)\n else\n move 0 to stack(stack1)\n end-if\n when 'Negate'\n call 'runast' using node-left(n)\n compute stack(stack1) = - stack(stack1)\n when 'Prtc'\n call 'runast' using node-left(n)\n move stack(stack1) to character-number\n display character-value with no advancing\n move 'y' to display-pending\n perform pop-stack\n when 'Prti'\n call 'runast' using node-left(n)\n move stack(stack1) to display-number\n display trim(display-number) with no advancing\n move 'y' to display-pending\n perform pop-stack\n when 'Prts'\n call 'runast' using node-left(n)\n move stack-source(stack1) to s\n move length(trim(string-value(s))) to string-length\n move 2 to string1\n compute length1 = string-length - 2\n perform until string1 >= string-length\n move 0 to count1\n inspect string-value(s)(string1:length1)\n tallying count1 for characters before initial '\\' *> ' (workaround Rosetta Code highlighter problem)\n evaluate true\n when string-value(s)(string1 + count1 + 1:1) = 'n' *> \\n\n display string-value(s)(string1:count1)\n move 'n' to display-pending\n compute string1 = string1 + 2 + count1\n compute length1 = length1 - 2 - count1\n when string-value(s)(string1 + count1 + 1:1) = '\\' *> \\\\ '\n display string-value(s)(string1:count1 + 1) with no advancing\n move 'y' to display-pending\n compute string1 = string1 + 2 + count1\n compute length1 = length1 - 2 - count1\n when other\n display string-value(s)(string1:count1) with no advancing\n move 'y' to display-pending\n add count1 to string1\n subtract count1 from length1\n end-evaluate\n end-perform\n perform pop-stack\n when 'Sequence'\n call 'runast' using node-left(n)\n call 'runast' using node-right(n)\n when other\n string 'in astinterpreter unknown node type ' node-type(n) into error-record\n call 'reporterror'\n end-evaluate\n exit program\n .\npush-stack.\n if stack1 >= s-lim\n string 'in astinterpreter at ' n ' stack overflow' into error-record\n call 'reporterror'\n end-if\n add 1 to stack1 stack2\n initialize stack-entry(stack1)\n .\npop-stack.\n if stack1 < 2\n string 'in astinterpreter at ' n ' stack underflow ' into error-record\n call 'reporterror'\n end-if\n subtract 1 from stack1 stack2\n .\nget-variable-index.\n perform varying v from 1 by 1 until v > v-max\n or variable-name(v) = leaf-value(n)\n continue\n end-perform\n if v > v-max\n if v-max = v-lim\n string 'in astinterpreter number of variables exceeds ' v-lim into error-record\n call 'reporterror'\n end-if\n move v to v-max\n move leaf-value(n) to variable-name(v)\n move 0 to variable-value(v)\n end-if\n .\nget-string-index.\n perform varying s from 1 by 1 until s > s-max\n or string-value(s) = leaf-value(n)\n continue\n end-perform\n if s > s-max\n if s-max = s-lim\n string 'in astinterpreter number of strings exceeds ' s-lim into error-record\n call 'reporterror'\n end-if\n move s to s-max\n move leaf-value(n) to string-value(s)\n end-if\n .\nget-values.\n call 'runast' using node-left(n)\n call 'runast' using node-right(n)\n .\nend program runast.\n\nidentification division.\nprogram-id. loadast common recursive.\nprocedure division.\nstart-loadast.\n if l >= l-lim\n string 'in astinterpreter loadast l exceeds ' l-lim into error-record\n call 'reporterror'\n end-if\n add 1 to l\n call 'readinput'\n evaluate true\n when ast-record = ';'\n when input-status = '10'\n move 0 to return-code\n when ast-type = 'Identifier'\n when ast-type = 'Integer'\n when ast-type = 'String'\n call 'makeleaf' using ast-type ast-value\n move t to return-code\n when ast-type = 'Sequence'\n move ast-type to l-node(l)\n call 'loadast'\n move return-code to l-left(l)\n call 'loadast'\n move t to l-right(l)\n call 'makenode' using l-node(l) l-left(l) l-right(l)\n move t to return-code\n when other\n move ast-type to l-node(l)\n call 'loadast'\n move return-code to l-left(l)\n call 'loadast'\n move return-code to l-right(l)\n call 'makenode' using l-node(l) l-left(l) l-right(l)\n move t to return-code\n end-evaluate\n subtract 1 from l\n .\nend program loadast.\n\nidentification division.\nprogram-id. makenode common.\ndata division.\nlinkage section.\n01 parm-type any length.\n01 parm-l-left pic 999.\n01 parm-l-right pic 999.\nprocedure division using parm-type parm-l-left parm-l-right.\nstart-makenode.\n if t >= t-lim\n string 'in astinterpreter makenode t exceeds ' t-lim into error-record\n call 'reporterror'\n end-if\n add 1 to t\n move parm-type to node-type(t)\n move parm-l-left to node-left(t)\n move parm-l-right to node-right(t)\n .\nend program makenode.\n\nidentification division.\nprogram-id. makeleaf common.\ndata division.\nlinkage section.\n01 parm-type any length.\n01 parm-value pic x(48).\nprocedure division using parm-type parm-value.\nstart-makeleaf.\n add 1 to t\n if t >= t-lim\n string 'in astinterpreter makeleaf t exceeds ' t-lim into error-record\n call 'reporterror'\n end-if\n move parm-type to leaf-type(t)\n move parm-value to leaf-value(t)\n .\nend program makeleaf.\n\nidentification division.\nprogram-id. printast common recursive.\ndata division.\nlinkage section.\n01 n pic 999.\nprocedure division using n.\nstart-printast.\n if n = 0\n display ';' upon syserr\n exit program\n end-if\n display leaf-type(n) upon syserr\n evaluate leaf-type(n)\n when 'Identifier'\n when 'Integer'\n when 'String'\n display leaf-type(n) space trim(leaf-value(n)) upon syserr\n when other\n display node-type(n) upon syserr\n call 'printast' using node-left(n)\n call 'printast' using node-right(n)\n end-evaluate\n .\nend program printast.\n\nidentification division.\nprogram-id. readinput common.\nenvironment division.\ninput-output section.\nfile-control.\n select input-file assign using input-name\n status is input-status\n organization is line sequential.\ndata division.\nfile section.\nfd input-file.\n01 input-record pic x(64).\nprocedure division.\nstart-readinput.\n if program-name = spaces\n move '00' to input-status\n accept ast-record on exception move '10' to input-status end-accept\n exit program\n end-if\n if input-name = spaces\n string program-name delimited by space '.ast' into input-name\n open input input-file\n if input-status = '35'\n string 'in astinterpreter ' trim(input-name) ' not found' into error-record\n call 'reporterror'\n end-if\n end-if\n read input-file into ast-record\n evaluate input-status\n when '00'\n continue\n when '10'\n close input-file\n when other\n string 'in astinterpreter ' trim(input-name) ' unexpected input-status: ' input-status\n into error-record\n call 'reporterror'\n end-evaluate\n .\nend program readinput.\n\nprogram-id. reporterror common.\nprocedure division.\nstart-reporterror.\nreport-error.\n display error-record upon syserr\n stop run with error status -1\n .\nend program reporterror.\nend program astinterpreter.\n", "language": "COBOL" }, { "code": "CREATE BUF 0 , \\ single-character look-ahead buffer\n: PEEK BUF @ 0= IF KEY BUF ! THEN BUF @ ;\n: GETC PEEK 0 BUF ! ;\n: SPACE? DUP BL = SWAP 9 14 WITHIN OR ;\n: >SPACE BEGIN PEEK SPACE? WHILE GETC DROP REPEAT ;\n: DIGIT? 48 58 WITHIN ;\n: GETINT >SPACE 0\n BEGIN PEEK DIGIT?\n WHILE GETC [CHAR] 0 - SWAP 10 * + REPEAT ;\n: GETNAM >SPACE PAD 1+\n BEGIN PEEK SPACE? INVERT\n WHILE GETC OVER C! CHAR+\n REPEAT PAD TUCK - 1- PAD C! ;\n: GETSTR ( -- c-addr u)\n HERE >R 0 >SPACE GETC DROP \\ skip leading \"\n BEGIN GETC DUP [CHAR] \" <> WHILE C, 1+ REPEAT\n DROP R> SWAP ;\n: \\TYPE BEGIN DUP 0> WHILE\n OVER C@ [CHAR] \\ = IF\n 1- >R CHAR+ R>\n OVER C@ [CHAR] n = IF CR ELSE\n OVER C@ [CHAR] \\ = IF [CHAR] \\ EMIT THEN THEN\n ELSE OVER C@ EMIT THEN 1- >R CHAR+ R> REPEAT\n DROP DROP ;\n: . S>D SWAP OVER DABS <# #S ROT SIGN #> TYPE ;\n\n: CONS ( v l -- l) HERE >R SWAP , , R> ;\n: HEAD ( l -- v) @ ;\n: TAIL ( l -- l) CELL+ @ ;\nCREATE GLOBALS 0 ,\n: DECLARE ( c-addr -- a-addr) HERE TUCK\n OVER C@ CHAR+ DUP ALLOT CMOVE HERE SWAP 0 ,\n GLOBALS @ CONS GLOBALS ! ;\n: LOOKUP ( c-addr -- a-addr) DUP COUNT GLOBALS @ >R\n BEGIN R@ 0<>\n WHILE R@ HEAD COUNT 2OVER COMPARE 0=\n IF 2DROP DROP R> HEAD DUP C@ CHAR+ + EXIT\n THEN R> TAIL >R\n REPEAT\n 2DROP RDROP DECLARE ;\n\nDEFER GETAST\n: >Identifier GETNAM LOOKUP 0 ;\n: >Integer GETINT 0 ;\n: >String GETSTR ;\n: >; 0 0 ;\n: NODE ( xt left right -- addr) HERE >R , , , R> ;\nCREATE BUF' 12 ALLOT\n: PREPEND ( c-addr c -- c-addr) BUF' 1+ C!\n COUNT DUP 1+ BUF' C! BUF' 2 + SWAP CMOVE BUF' ;\n: HANDLER ( c-addr -- xt) [CHAR] $ PREPEND FIND\n 0= IF .\" No handler for AST node '\" COUNT TYPE .\" '\" THEN ;\n: READER ( c-addr -- xt t | f)\n [CHAR] > PREPEND FIND DUP 0= IF NIP THEN ;\n: READ ( c-addr -- left right) READER\n IF EXECUTE ELSE GETAST GETAST THEN ;\n: (GETAST) GETNAM DUP HANDLER SWAP READ NODE ;\n' (GETAST) IS GETAST\n\n: INTERP DUP 2@ ROT [ 2 CELLS ]L + @ EXECUTE ;\n: $; DROP DROP ;\n: $Identifier ( l r -- a-addr) DROP @ ;\n: $Integer ( l r -- n) DROP ;\n: $String ( l r -- c-addr u) ( noop) ;\n: $Prtc ( l r --) DROP INTERP EMIT ;\n: $Prti ( l r --) DROP INTERP . ;\n: $Prts ( l r --) DROP INTERP \\TYPE ;\n: $Not ( l r --) DROP INTERP 0= ;\n: $Negate ( l r --) DROP INTERP NEGATE ;\n: $Sequence ( l r --) SWAP INTERP INTERP ;\n: $Assign ( l r --) SWAP CELL+ @ >R INTERP R> ! ;\n: $While ( l r --)\n >R BEGIN DUP INTERP WHILE R@ INTERP REPEAT RDROP DROP ;\n: $If ( l r --) SWAP INTERP 0<> IF CELL+ THEN @ INTERP ;\n: $Subtract ( l r -- n) >R INTERP R> INTERP - ;\n: $Add >R INTERP R> INTERP + ;\n: $Mod >R INTERP R> INTERP MOD ;\n: $Multiply >R INTERP R> INTERP * ;\n: $Divide >R INTERP S>D R> INTERP SM/REM SWAP DROP ;\n: $Less >R INTERP R> INTERP < ;\n: $LessEqual >R INTERP R> INTERP <= ;\n: $Greater >R INTERP R> INTERP > ;\n: $GreaterEqual >R INTERP R> INTERP >= ;\n: $Equal >R INTERP R> INTERP = ;\n: $NotEqual >R INTERP R> INTERP <> ;\n: $And >R INTERP IF R> INTERP 0<> ELSE RDROP 0 THEN ;\n: $Or >R INTERP IF RDROP -1 ELSE R> INTERP 0<> THEN ;\n\nGETAST INTERP\n", "language": "Forth" }, { "code": "!!!\n!!! An implementation of the Rosetta Code interpreter task:\n!!! https://rosettacode.org/wiki/Compiler/AST_interpreter\n!!!\n!!! The implementation is based on the published pseudocode.\n!!!\n\nmodule compiler_type_kinds\n use, intrinsic :: iso_fortran_env, only: int32\n use, intrinsic :: iso_fortran_env, only: int64\n\n implicit none\n private\n\n ! Synonyms.\n integer, parameter, public :: size_kind = int64\n integer, parameter, public :: length_kind = size_kind\n integer, parameter, public :: nk = size_kind\n\n ! Synonyms for character capable of storing a Unicode code point.\n integer, parameter, public :: unicode_char_kind = selected_char_kind ('ISO_10646')\n integer, parameter, public :: ck = unicode_char_kind\n\n ! Synonyms for integers capable of storing a Unicode code point.\n integer, parameter, public :: unicode_ichar_kind = int32\n integer, parameter, public :: ick = unicode_ichar_kind\n\n ! Synonyms for integers in the runtime code.\n integer, parameter, public :: runtime_int_kind = int64\n integer, parameter, public :: rik = runtime_int_kind\nend module compiler_type_kinds\n\nmodule helper_procedures\n use, non_intrinsic :: compiler_type_kinds, only: nk, ck\n\n implicit none\n private\n\n public :: new_storage_size\n public :: next_power_of_two\n public :: isspace\n\n character(1, kind = ck), parameter :: horizontal_tab_char = char (9, kind = ck)\n character(1, kind = ck), parameter :: linefeed_char = char (10, kind = ck)\n character(1, kind = ck), parameter :: vertical_tab_char = char (11, kind = ck)\n character(1, kind = ck), parameter :: formfeed_char = char (12, kind = ck)\n character(1, kind = ck), parameter :: carriage_return_char = char (13, kind = ck)\n character(1, kind = ck), parameter :: space_char = ck_' '\n\ncontains\n\n elemental function new_storage_size (length_needed) result (size)\n integer(kind = nk), intent(in) :: length_needed\n integer(kind = nk) :: size\n\n ! Increase storage by orders of magnitude.\n\n if (2_nk**32 < length_needed) then\n size = huge (1_nk)\n else\n size = next_power_of_two (length_needed)\n end if\n end function new_storage_size\n\n\n elemental function next_power_of_two (x) result (y)\n integer(kind = nk), intent(in) :: x\n integer(kind = nk) :: y\n\n !\n ! It is assumed that no more than 64 bits are used.\n !\n ! The branch-free algorithm is that of\n ! https://archive.is/nKxAc#RoundUpPowerOf2\n !\n ! Fill in bits until one less than the desired power of two is\n ! reached, and then add one.\n !\n\n y = x - 1\n y = ior (y, ishft (y, -1))\n y = ior (y, ishft (y, -2))\n y = ior (y, ishft (y, -4))\n y = ior (y, ishft (y, -8))\n y = ior (y, ishft (y, -16))\n y = ior (y, ishft (y, -32))\n y = y + 1\n end function next_power_of_two\n\n elemental function isspace (ch) result (bool)\n character(1, kind = ck), intent(in) :: ch\n logical :: bool\n\n bool = (ch == horizontal_tab_char) .or. &\n & (ch == linefeed_char) .or. &\n & (ch == vertical_tab_char) .or. &\n & (ch == formfeed_char) .or. &\n & (ch == carriage_return_char) .or. &\n & (ch == space_char)\n end function isspace\n\nend module helper_procedures\n\nmodule string_buffers\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, intrinsic :: iso_fortran_env, only: int64\n use, non_intrinsic :: compiler_type_kinds, only: nk, ck, ick\n use, non_intrinsic :: helper_procedures\n\n implicit none\n private\n\n public :: strbuf_t\n public :: skip_whitespace\n public :: skip_non_whitespace\n public :: skip_whitespace_backwards\n public :: at_end_of_line\n\n type :: strbuf_t\n integer(kind = nk), private :: len = 0\n !\n ! ‘chars’ is made public for efficient access to the individual\n ! characters.\n !\n character(1, kind = ck), allocatable, public :: chars(:)\n contains\n procedure, pass, private :: ensure_storage => strbuf_t_ensure_storage\n procedure, pass :: to_unicode_full_string => strbuf_t_to_unicode_full_string\n procedure, pass :: to_unicode_substring => strbuf_t_to_unicode_substring\n procedure, pass :: length => strbuf_t_length\n procedure, pass :: set => strbuf_t_set\n procedure, pass :: append => strbuf_t_append\n generic :: to_unicode => to_unicode_full_string\n generic :: to_unicode => to_unicode_substring\n generic :: assignment(=) => set\n end type strbuf_t\n\ncontains\n\n function strbuf_t_to_unicode_full_string (strbuf) result (s)\n class(strbuf_t), intent(in) :: strbuf\n character(:, kind = ck), allocatable :: s\n\n !\n ! This does not actually ensure that the string is valid Unicode;\n ! any 31-bit ‘character’ is supported.\n !\n\n integer(kind = nk) :: i\n\n allocate (character(len = strbuf%len, kind = ck) :: s)\n do i = 1, strbuf%len\n s(i:i) = strbuf%chars(i)\n end do\n end function strbuf_t_to_unicode_full_string\n\n function strbuf_t_to_unicode_substring (strbuf, i, j) result (s)\n !\n ! ‘Extreme’ values of i and j are allowed, as shortcuts for ‘from\n ! the beginning’, ‘up to the end’, or ‘empty substring’.\n !\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i, j\n character(:, kind = ck), allocatable :: s\n\n !\n ! This does not actually ensure that the string is valid Unicode;\n ! any 31-bit ‘character’ is supported.\n !\n\n integer(kind = nk) :: i1, j1\n integer(kind = nk) :: n\n integer(kind = nk) :: k\n\n i1 = max (1_nk, i)\n j1 = min (strbuf%len, j)\n n = max (0_nk, (j1 - i1) + 1_nk)\n\n allocate (character(n, kind = ck) :: s)\n do k = 1, n\n s(k:k) = strbuf%chars(i1 + (k - 1_nk))\n end do\n end function strbuf_t_to_unicode_substring\n\n elemental function strbuf_t_length (strbuf) result (n)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk) :: n\n\n n = strbuf%len\n end function strbuf_t_length\n\n subroutine strbuf_t_ensure_storage (strbuf, length_needed)\n class(strbuf_t), intent(inout) :: strbuf\n integer(kind = nk), intent(in) :: length_needed\n\n integer(kind = nk) :: len_needed\n integer(kind = nk) :: new_size\n type(strbuf_t) :: new_strbuf\n\n len_needed = max (length_needed, 1_nk)\n\n if (.not. allocated (strbuf%chars)) then\n ! Initialize a new strbuf%chars array.\n new_size = new_storage_size (len_needed)\n allocate (strbuf%chars(1:new_size))\n else if (ubound (strbuf%chars, 1) < len_needed) then\n ! Allocate a new strbuf%chars array, larger than the current\n ! one, but containing the same characters.\n new_size = new_storage_size (len_needed)\n allocate (new_strbuf%chars(1:new_size))\n new_strbuf%chars(1:strbuf%len) = strbuf%chars(1:strbuf%len)\n call move_alloc (new_strbuf%chars, strbuf%chars)\n end if\n end subroutine strbuf_t_ensure_storage\n\n subroutine strbuf_t_set (dst, src)\n class(strbuf_t), intent(inout) :: dst\n class(*), intent(in) :: src\n\n integer(kind = nk) :: n\n integer(kind = nk) :: i\n\n select type (src)\n type is (character(*, kind = ck))\n n = len (src, kind = nk)\n call dst%ensure_storage(n)\n do i = 1, n\n dst%chars(i) = src(i:i)\n end do\n dst%len = n\n type is (character(*))\n n = len (src, kind = nk)\n call dst%ensure_storage(n)\n do i = 1, n\n dst%chars(i) = src(i:i)\n end do\n dst%len = n\n class is (strbuf_t)\n n = src%len\n call dst%ensure_storage(n)\n dst%chars(1:n) = src%chars(1:n)\n dst%len = n\n class default\n error stop\n end select\n end subroutine strbuf_t_set\n\n subroutine strbuf_t_append (dst, src)\n class(strbuf_t), intent(inout) :: dst\n class(*), intent(in) :: src\n\n integer(kind = nk) :: n_dst, n_src, n\n integer(kind = nk) :: i\n\n select type (src)\n type is (character(*, kind = ck))\n n_dst = dst%len\n n_src = len (src, kind = nk)\n n = n_dst + n_src\n call dst%ensure_storage(n)\n do i = 1, n_src\n dst%chars(n_dst + i) = src(i:i)\n end do\n dst%len = n\n type is (character(*))\n n_dst = dst%len\n n_src = len (src, kind = nk)\n n = n_dst + n_src\n call dst%ensure_storage(n)\n do i = 1, n_src\n dst%chars(n_dst + i) = src(i:i)\n end do\n dst%len = n\n class is (strbuf_t)\n n_dst = dst%len\n n_src = src%len\n n = n_dst + n_src\n call dst%ensure_storage(n)\n dst%chars((n_dst + 1):n) = src%chars(1:n_src)\n dst%len = n\n class default\n error stop\n end select\n end subroutine strbuf_t_append\n\n function skip_whitespace (strbuf, i) result (j)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n integer(kind = nk) :: j\n\n logical :: done\n\n j = i\n done = .false.\n do while (.not. done)\n if (at_end_of_line (strbuf, j)) then\n done = .true.\n else if (.not. isspace (strbuf%chars(j))) then\n done = .true.\n else\n j = j + 1\n end if\n end do\n end function skip_whitespace\n\n function skip_non_whitespace (strbuf, i) result (j)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n integer(kind = nk) :: j\n\n logical :: done\n\n j = i\n done = .false.\n do while (.not. done)\n if (at_end_of_line (strbuf, j)) then\n done = .true.\n else if (isspace (strbuf%chars(j))) then\n done = .true.\n else\n j = j + 1\n end if\n end do\n end function skip_non_whitespace\n\n function skip_whitespace_backwards (strbuf, i) result (j)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n integer(kind = nk) :: j\n\n logical :: done\n\n j = i\n done = .false.\n do while (.not. done)\n if (j == -1) then\n done = .true.\n else if (.not. isspace (strbuf%chars(j))) then\n done = .true.\n else\n j = j - 1\n end if\n end do\n end function skip_whitespace_backwards\n\n function at_end_of_line (strbuf, i) result (bool)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n logical :: bool\n\n bool = (strbuf%length() < i)\n end function at_end_of_line\n\nend module string_buffers\n\nmodule reading_one_line_from_a_stream\n use, intrinsic :: iso_fortran_env, only: input_unit\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, non_intrinsic :: compiler_type_kinds, only: nk, ck, ick\n use, non_intrinsic :: string_buffers\n\n implicit none\n private\n\n ! get_line_from_stream: read an entire input line from a stream into\n ! a strbuf_t.\n public :: get_line_from_stream\n\n character(1, kind = ck), parameter :: linefeed_char = char (10, kind = ck)\n\n ! The following is correct for Unix and its relatives.\n character(1, kind = ck), parameter :: newline_char = linefeed_char\n\ncontains\n\n subroutine get_line_from_stream (unit_no, eof, no_newline, strbuf)\n integer, intent(in) :: unit_no\n logical, intent(out) :: eof ! End of file?\n logical, intent(out) :: no_newline ! There is a line but it has no\n ! newline? (Thus eof also must\n ! be .true.)\n class(strbuf_t), intent(inout) :: strbuf\n\n character(1, kind = ck) :: ch\n\n strbuf = ''\n call get_ch (unit_no, eof, ch)\n do while (.not. eof .and. ch /= newline_char)\n call strbuf%append (ch)\n call get_ch (unit_no, eof, ch)\n end do\n no_newline = eof .and. (strbuf%length() /= 0)\n end subroutine get_line_from_stream\n\n subroutine get_ch (unit_no, eof, ch)\n !\n ! Read a single code point from the stream.\n !\n ! Currently this procedure simply inputs ‘ASCII’ bytes rather than\n ! Unicode code points.\n !\n integer, intent(in) :: unit_no\n logical, intent(out) :: eof\n character(1, kind = ck), intent(out) :: ch\n\n integer :: stat\n character(1) :: c = '*'\n\n eof = .false.\n\n if (unit_no == input_unit) then\n call get_input_unit_char (c, stat)\n else\n read (unit = unit_no, iostat = stat) c\n end if\n\n if (stat < 0) then\n ch = ck_'*'\n eof = .true.\n else if (0 < stat) then\n write (error_unit, '(\"Input error with status code \", I0)') stat\n stop 1\n else\n ch = char (ichar (c, kind = ick), kind = ck)\n end if\n end subroutine get_ch\n\n!!!\n!!! If you tell gfortran you want -std=f2008 or -std=f2018, you likely\n!!! will need to add also -fall-intrinsics or -U__GFORTRAN__\n!!!\n!!! The first way, you get the FGETC intrinsic. The latter way, you\n!!! get the C interface code that uses getchar(3).\n!!!\n#ifdef __GFORTRAN__\n\n subroutine get_input_unit_char (c, stat)\n !\n ! The following works if you are using gfortran.\n !\n ! (FGETC is considered a feature for backwards compatibility with\n ! g77. However, I know of no way to reconfigure input_unit as a\n ! Fortran 2003 stream, for use with ordinary ‘read’.)\n !\n character, intent(inout) :: c\n integer, intent(out) :: stat\n\n call fgetc (input_unit, c, stat)\n end subroutine get_input_unit_char\n\n#else\n\n subroutine get_input_unit_char (c, stat)\n !\n ! An alternative implementation of get_input_unit_char. This\n ! actually reads input from the C standard input, which might not\n ! be the same as input_unit.\n !\n use, intrinsic :: iso_c_binding, only: c_int\n character, intent(inout) :: c\n integer, intent(out) :: stat\n\n interface\n !\n ! Use getchar(3) to read characters from standard input. This\n ! assumes there is actually such a function available, and that\n ! getchar(3) does not exist solely as a macro. (One could write\n ! one’s own getchar() if necessary, of course.)\n !\n function getchar () result (c) bind (c, name = 'getchar')\n use, intrinsic :: iso_c_binding, only: c_int\n integer(kind = c_int) :: c\n end function getchar\n end interface\n\n integer(kind = c_int) :: i_char\n\n i_char = getchar ()\n !\n ! The C standard requires that EOF have a negative value. If the\n ! value returned by getchar(3) is not EOF, then it will be\n ! representable as an unsigned char. Therefore, to check for end\n ! of file, one need only test whether i_char is negative.\n !\n if (i_char < 0) then\n stat = -1\n else\n stat = 0\n c = char (i_char)\n end if\n end subroutine get_input_unit_char\n\n#endif\n\nend module reading_one_line_from_a_stream\n\nmodule ast_reader\n\n !\n ! The AST will be read into an array. Perhaps that will improve\n ! locality, compared to storing the AST as many linked heap nodes.\n !\n ! In any case, implementing the AST this way is an interesting\n ! problem.\n !\n\n use, intrinsic :: iso_fortran_env, only: input_unit\n use, intrinsic :: iso_fortran_env, only: output_unit\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, non_intrinsic :: compiler_type_kinds, only: nk, ck, ick, rik\n use, non_intrinsic :: helper_procedures, only: next_power_of_two\n use, non_intrinsic :: helper_procedures, only: new_storage_size\n use, non_intrinsic :: string_buffers\n use, non_intrinsic :: reading_one_line_from_a_stream\n\n implicit none\n private\n\n public :: symbol_table_t\n public :: interpreter_ast_node_t\n public :: interpreter_ast_t\n public :: read_ast\n\n integer, parameter, public :: node_Nil = 0\n integer, parameter, public :: node_Identifier = 1\n integer, parameter, public :: node_String = 2\n integer, parameter, public :: node_Integer = 3\n integer, parameter, public :: node_Sequence = 4\n integer, parameter, public :: node_If = 5\n integer, parameter, public :: node_Prtc = 6\n integer, parameter, public :: node_Prts = 7\n integer, parameter, public :: node_Prti = 8\n integer, parameter, public :: node_While = 9\n integer, parameter, public :: node_Assign = 10\n integer, parameter, public :: node_Negate = 11\n integer, parameter, public :: node_Not = 12\n integer, parameter, public :: node_Multiply = 13\n integer, parameter, public :: node_Divide = 14\n integer, parameter, public :: node_Mod = 15\n integer, parameter, public :: node_Add = 16\n integer, parameter, public :: node_Subtract = 17\n integer, parameter, public :: node_Less = 18\n integer, parameter, public :: node_LessEqual = 19\n integer, parameter, public :: node_Greater = 20\n integer, parameter, public :: node_GreaterEqual = 21\n integer, parameter, public :: node_Equal = 22\n integer, parameter, public :: node_NotEqual = 23\n integer, parameter, public :: node_And = 24\n integer, parameter, public :: node_Or = 25\n\n type :: symbol_table_element_t\n character(:, kind = ck), allocatable :: str\n end type symbol_table_element_t\n\n type :: symbol_table_t\n integer(kind = nk), private :: len = 0_nk\n type(symbol_table_element_t), allocatable, private :: symbols(:)\n contains\n procedure, pass, private :: ensure_storage => symbol_table_t_ensure_storage\n procedure, pass :: look_up_index => symbol_table_t_look_up_index\n procedure, pass :: look_up_name => symbol_table_t_look_up_name\n procedure, pass :: length => symbol_table_t_length\n generic :: look_up => look_up_index\n generic :: look_up => look_up_name\n end type symbol_table_t\n\n type :: interpreter_ast_node_t\n integer :: node_variety\n integer(kind = rik) :: int ! Runtime integer or symbol index.\n character(:, kind = ck), allocatable :: str ! String value.\n\n ! The left branch begins at the next node. The right branch\n ! begins at the address of the left branch, plus the following.\n integer(kind = nk) :: right_branch_offset\n end type interpreter_ast_node_t\n\n type :: interpreter_ast_t\n integer(kind = nk), private :: len = 0_nk\n type(interpreter_ast_node_t), allocatable, public :: nodes(:)\n contains\n procedure, pass, private :: ensure_storage => interpreter_ast_t_ensure_storage\n end type interpreter_ast_t\n\ncontains\n\n subroutine symbol_table_t_ensure_storage (symtab, length_needed)\n class(symbol_table_t), intent(inout) :: symtab\n integer(kind = nk), intent(in) :: length_needed\n\n integer(kind = nk) :: len_needed\n integer(kind = nk) :: new_size\n type(symbol_table_t) :: new_symtab\n\n len_needed = max (length_needed, 1_nk)\n\n if (.not. allocated (symtab%symbols)) then\n ! Initialize a new symtab%symbols array.\n new_size = new_storage_size (len_needed)\n allocate (symtab%symbols(1:new_size))\n else if (ubound (symtab%symbols, 1) < len_needed) then\n ! Allocate a new symtab%symbols array, larger than the current\n ! one, but containing the same symbols.\n new_size = new_storage_size (len_needed)\n allocate (new_symtab%symbols(1:new_size))\n new_symtab%symbols(1:symtab%len) = symtab%symbols(1:symtab%len)\n call move_alloc (new_symtab%symbols, symtab%symbols)\n end if\n end subroutine symbol_table_t_ensure_storage\n\n elemental function symbol_table_t_length (symtab) result (len)\n class(symbol_table_t), intent(in) :: symtab\n integer(kind = nk) :: len\n\n len = symtab%len\n end function symbol_table_t_length\n\n function symbol_table_t_look_up_index (symtab, symbol_name) result (index)\n class(symbol_table_t), intent(inout) :: symtab\n character(*, kind = ck), intent(in) :: symbol_name\n integer(kind = rik) :: index\n\n !\n ! This implementation simply stores the symbols sequentially into\n ! an array. Obviously, for large numbers of symbols, one might\n ! wish to do something more complex.\n !\n ! Standard Fortran does not come, out of the box, with a massive\n ! runtime library for doing such things. They are, however, no\n ! longer nearly as challenging to implement in Fortran as they\n ! used to be.\n !\n\n integer(kind = nk) :: i\n\n i = 1\n index = 0\n do while (index == 0)\n if (i == symtab%len + 1) then\n ! The symbol is new and must be added to the table.\n i = symtab%len + 1\n if (huge (1_rik) < i) then\n ! Symbol indices are assumed to be storable as runtime\n ! integers.\n write (error_unit, '(\"There are more symbols than can be handled.\")')\n stop 1\n end if\n call symtab%ensure_storage(i)\n symtab%len = i\n allocate (symtab%symbols(i)%str, source = symbol_name)\n index = int (i, kind = rik)\n else if (symtab%symbols(i)%str == symbol_name) then\n index = int (i, kind = rik)\n else\n i = i + 1\n end if\n end do\n end function symbol_table_t_look_up_index\n\n function symbol_table_t_look_up_name (symtab, index) result (symbol_name)\n class(symbol_table_t), intent(inout) :: symtab\n integer(kind = rik), intent(in) :: index\n character(:, kind = ck), allocatable :: symbol_name\n\n !\n ! This is the reverse of symbol_table_t_look_up_index: given an\n ! index, it finds the symbol’s name.\n !\n\n if (index < 1 .or. symtab%len < index) then\n ! In correct code, this branch should never be reached.\n error stop\n else\n allocate (symbol_name, source = symtab%symbols(index)%str)\n end if\n end function symbol_table_t_look_up_name\n\n subroutine interpreter_ast_t_ensure_storage (ast, length_needed)\n class(interpreter_ast_t), intent(inout) :: ast\n integer(kind = nk), intent(in) :: length_needed\n\n integer(kind = nk) :: len_needed\n integer(kind = nk) :: new_size\n type(interpreter_ast_t) :: new_ast\n\n len_needed = max (length_needed, 1_nk)\n\n if (.not. allocated (ast%nodes)) then\n ! Initialize a new ast%nodes array.\n new_size = new_storage_size (len_needed)\n allocate (ast%nodes(1:new_size))\n else if (ubound (ast%nodes, 1) < len_needed) then\n ! Allocate a new ast%nodes array, larger than the current one,\n ! but containing the same nodes.\n new_size = new_storage_size (len_needed)\n allocate (new_ast%nodes(1:new_size))\n new_ast%nodes(1:ast%len) = ast%nodes(1:ast%len)\n call move_alloc (new_ast%nodes, ast%nodes)\n end if\n end subroutine interpreter_ast_t_ensure_storage\n\n subroutine read_ast (unit_no, strbuf, ast, symtab)\n integer, intent(in) :: unit_no\n type(strbuf_t), intent(inout) :: strbuf\n type(interpreter_ast_t), intent(inout) :: ast\n type(symbol_table_t), intent(inout) :: symtab\n\n logical :: eof\n logical :: no_newline\n integer(kind = nk) :: after_ast_address\n\n symtab%len = 0\n ast%len = 0\n call build_subtree (1_nk, after_ast_address)\n\n contains\n\n recursive subroutine build_subtree (here_address, after_subtree_address)\n integer(kind = nk), value :: here_address\n integer(kind = nk), intent(out) :: after_subtree_address\n\n integer :: node_variety\n integer(kind = nk) :: i, j\n integer(kind = nk) :: left_branch_address\n integer(kind = nk) :: right_branch_address\n\n ! Get a line from the parser output.\n call get_line_from_stream (unit_no, eof, no_newline, strbuf)\n\n if (eof) then\n call ast_error\n else\n ! Prepare to store a new node.\n call ast%ensure_storage(here_address)\n ast%len = here_address\n\n ! What sort of node is it?\n i = skip_whitespace (strbuf, 1_nk)\n j = skip_non_whitespace (strbuf, i)\n node_variety = strbuf_to_node_variety (strbuf, i, j - 1)\n\n ast%nodes(here_address)%node_variety = node_variety\n\n select case (node_variety)\n case (node_Nil)\n after_subtree_address = here_address + 1\n case (node_Identifier)\n i = skip_whitespace (strbuf, j)\n j = skip_non_whitespace (strbuf, i)\n ast%nodes(here_address)%int = &\n & strbuf_to_symbol_index (strbuf, i, j - 1, symtab)\n after_subtree_address = here_address + 1\n case (node_String)\n i = skip_whitespace (strbuf, j)\n j = skip_whitespace_backwards (strbuf, strbuf%length())\n ast%nodes(here_address)%str = strbuf_to_string (strbuf, i, j)\n after_subtree_address = here_address + 1\n case (node_Integer)\n i = skip_whitespace (strbuf, j)\n j = skip_non_whitespace (strbuf, i)\n ast%nodes(here_address)%int = strbuf_to_int (strbuf, i, j - 1)\n after_subtree_address = here_address + 1\n case default\n ! The node is internal, and has left and right branches.\n ! The left branch will start at left_branch_address; the\n ! right branch will start at left_branch_address +\n ! right_side_offset.\n left_branch_address = here_address + 1\n ! Build the left branch.\n call build_subtree (left_branch_address, right_branch_address)\n ! Build the right_branch.\n call build_subtree (right_branch_address, after_subtree_address)\n ast%nodes(here_address)%right_branch_offset = &\n & right_branch_address - left_branch_address\n end select\n\n end if\n end subroutine build_subtree\n\n end subroutine read_ast\n\n function strbuf_to_node_variety (strbuf, i, j) result (node_variety)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i, j\n integer :: node_variety\n\n !\n ! This function has not been optimized in any way, unless the\n ! Fortran compiler can optimize it.\n !\n ! Something like a ‘radix tree search’ could be done on the\n ! characters of the strbuf. Or a perfect hash function. Or a\n ! binary search. Etc.\n !\n\n if (j == i - 1) then\n call ast_error\n else\n select case (strbuf%to_unicode(i, j))\n case (ck_\";\")\n node_variety = node_Nil\n case (ck_\"Identifier\")\n node_variety = node_Identifier\n case (ck_\"String\")\n node_variety = node_String\n case (ck_\"Integer\")\n node_variety = node_Integer\n case (ck_\"Sequence\")\n node_variety = node_Sequence\n case (ck_\"If\")\n node_variety = node_If\n case (ck_\"Prtc\")\n node_variety = node_Prtc\n case (ck_\"Prts\")\n node_variety = node_Prts\n case (ck_\"Prti\")\n node_variety = node_Prti\n case (ck_\"While\")\n node_variety = node_While\n case (ck_\"Assign\")\n node_variety = node_Assign\n case (ck_\"Negate\")\n node_variety = node_Negate\n case (ck_\"Not\")\n node_variety = node_Not\n case (ck_\"Multiply\")\n node_variety = node_Multiply\n case (ck_\"Divide\")\n node_variety = node_Divide\n case (ck_\"Mod\")\n node_variety = node_Mod\n case (ck_\"Add\")\n node_variety = node_Add\n case (ck_\"Subtract\")\n node_variety = node_Subtract\n case (ck_\"Less\")\n node_variety = node_Less\n case (ck_\"LessEqual\")\n node_variety = node_LessEqual\n case (ck_\"Greater\")\n node_variety = node_Greater\n case (ck_\"GreaterEqual\")\n node_variety = node_GreaterEqual\n case (ck_\"Equal\")\n node_variety = node_Equal\n case (ck_\"NotEqual\")\n node_variety = node_NotEqual\n case (ck_\"And\")\n node_variety = node_And\n case (ck_\"Or\")\n node_variety = node_Or\n case default\n call ast_error\n end select\n end if\n end function strbuf_to_node_variety\n\n function strbuf_to_symbol_index (strbuf, i, j, symtab) result (int)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i, j\n type(symbol_table_t), intent(inout) :: symtab\n integer(kind = rik) :: int\n\n if (j == i - 1) then\n call ast_error\n else\n int = symtab%look_up(strbuf%to_unicode (i, j))\n end if\n end function strbuf_to_symbol_index\n\n function strbuf_to_int (strbuf, i, j) result (int)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i, j\n integer(kind = rik) :: int\n\n integer :: stat\n character(:, kind = ck), allocatable :: str\n\n if (j < i) then\n call ast_error\n else\n allocate (character(len = (j - i) + 1_nk, kind = ck) :: str)\n str = strbuf%to_unicode (i, j)\n read (str, *, iostat = stat) int\n if (stat /= 0) then\n call ast_error\n end if\n end if\n end function strbuf_to_int\n\n function strbuf_to_string (strbuf, i, j) result (str)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i, j\n character(:, kind = ck), allocatable :: str\n\n character(1, kind = ck), parameter :: linefeed_char = char (10, kind = ck)\n character(1, kind = ck), parameter :: backslash_char = char (92, kind = ck)\n\n ! The following is correct for Unix and its relatives.\n character(1, kind = ck), parameter :: newline_char = linefeed_char\n\n integer(kind = nk) :: k\n integer(kind = nk) :: count\n\n if (strbuf%chars(i) /= ck_'\"' .or. strbuf%chars(j) /= ck_'\"') then\n call ast_error\n else\n ! Count how many characters are needed.\n count = 0\n k = i + 1\n do while (k < j)\n count = count + 1\n if (strbuf%chars(k) == backslash_char) then\n k = k + 2\n else\n k = k + 1\n end if\n end do\n\n allocate (character(len = count, kind = ck) :: str)\n\n count = 0\n k = i + 1\n do while (k < j)\n if (strbuf%chars(k) == backslash_char) then\n if (k == j - 1) then\n call ast_error\n else\n select case (strbuf%chars(k + 1))\n case (ck_'n')\n count = count + 1\n str(count:count) = newline_char\n case (backslash_char)\n count = count + 1\n str(count:count) = backslash_char\n case default\n call ast_error\n end select\n k = k + 2\n end if\n else\n count = count + 1\n str(count:count) = strbuf%chars(k)\n k = k + 1\n end if\n end do\n end if\n end function strbuf_to_string\n\n subroutine ast_error\n !\n ! It might be desirable to give more detail.\n !\n write (error_unit, '(\"The AST input seems corrupted.\")')\n stop 1\n end subroutine ast_error\n\nend module ast_reader\n\nmodule ast_interpreter\n use, intrinsic :: iso_fortran_env, only: input_unit\n use, intrinsic :: iso_fortran_env, only: output_unit\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, non_intrinsic :: compiler_type_kinds\n use, non_intrinsic :: ast_reader\n\n implicit none\n private\n\n public :: value_t\n public :: variable_table_t\n public :: nil_value\n public :: interpret_ast_node\n\n integer, parameter, public :: v_Nil = 0\n integer, parameter, public :: v_Integer = 1\n integer, parameter, public :: v_String = 2\n\n type :: value_t\n integer :: tag = v_Nil\n integer(kind = rik) :: int_val = -(huge (1_rik))\n character(:, kind = ck), allocatable :: str_val\n end type value_t\n\n type :: variable_table_t\n type(value_t), allocatable :: vals(:)\n contains\n procedure, pass :: initialize => variable_table_t_initialize\n end type variable_table_t\n\n ! The canonical nil value.\n type(value_t), parameter :: nil_value = value_t ()\n\ncontains\n\n elemental function int_value (int_val) result (val)\n integer(kind = rik), intent(in) :: int_val\n type(value_t) :: val\n\n val%tag = v_Integer\n val%int_val = int_val\n end function int_value\n\n elemental function str_value (str_val) result (val)\n character(*, kind = ck), intent(in) :: str_val\n type(value_t) :: val\n\n val%tag = v_String\n allocate (val%str_val, source = str_val)\n end function str_value\n\n subroutine variable_table_t_initialize (vartab, symtab)\n class(variable_table_t), intent(inout) :: vartab\n type(symbol_table_t), intent(in) :: symtab\n\n allocate (vartab%vals(1:symtab%length()), source = nil_value)\n end subroutine variable_table_t_initialize\n\n recursive subroutine interpret_ast_node (outp, ast, symtab, vartab, address, retval)\n integer, intent(in) :: outp\n type(interpreter_ast_t), intent(in) :: ast\n type(symbol_table_t), intent(in) :: symtab\n type(variable_table_t), intent(inout) :: vartab\n integer(kind = nk) :: address\n type(value_t), intent(inout) :: retval\n\n integer(kind = rik) :: variable_index\n type(value_t) :: val1, val2, val3\n\n select case (ast%nodes(address)%node_variety)\n\n case (node_Nil)\n retval = nil_value\n\n case (node_Integer)\n retval = int_value (ast%nodes(address)%int)\n\n case (node_Identifier)\n variable_index = ast%nodes(address)%int\n retval = vartab%vals(variable_index)\n\n case (node_String)\n retval = str_value (ast%nodes(address)%str)\n\n case (node_Assign)\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val1)\n variable_index = ast%nodes(left_branch (address))%int\n vartab%vals(variable_index) = val1\n retval = nil_value\n\n case (node_Multiply)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n call multiply (val1, val2, val3)\n retval = val3\n\n case (node_Divide)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n call divide (val1, val2, val3)\n retval = val3\n\n case (node_Mod)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n call pseudo_remainder (val1, val2, val3)\n retval = val3\n\n case (node_Add)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n call add (val1, val2, val3)\n retval = val3\n\n case (node_Subtract)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n call subtract (val1, val2, val3)\n retval = val3\n\n case (node_Less)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n call less_than (val1, val2, val3)\n retval = val3\n\n case (node_LessEqual)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n call less_than_or_equal_to (val1, val2, val3)\n retval = val3\n\n case (node_Greater)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n call greater_than (val1, val2, val3)\n retval = val3\n\n case (node_GreaterEqual)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n call greater_than_or_equal_to (val1, val2, val3)\n retval = val3\n\n case (node_Equal)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n call equal_to (val1, val2, val3)\n retval = val3\n\n case (node_NotEqual)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n call not_equal_to (val1, val2, val3)\n retval = val3\n\n case (node_Negate)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n retval = int_value (-(rik_cast (val1, ck_'unary ''-''')))\n\n case (node_Not)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n retval = int_value (bool2int (rik_cast (val1, ck_'unary ''!''') == 0_rik))\n\n case (node_And)\n ! For similarity to C, we make this a ‘short-circuiting AND’,\n ! which is really a branching construct rather than a binary\n ! operation.\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n if (rik_cast (val1, ck_'''&&''') == 0_rik) then\n retval = int_value (0_rik)\n else\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n retval = int_value (bool2int (rik_cast (val2, ck_'''&&''') /= 0_rik))\n end if\n\n case (node_Or)\n ! For similarity to C, we make this a ‘short-circuiting OR’,\n ! which is really a branching construct rather than a binary\n ! operation.\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n if (rik_cast (val1, ck_'''||''') /= 0_rik) then\n retval = int_value (1_rik)\n else\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n retval = int_value (bool2int (rik_cast (val2, ck_'''||''') /= 0_rik))\n end if\n\n case (node_If)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n if (rik_cast (val1, ck_'''if-else'' construct') /= 0_rik) then\n call interpret_ast_node (outp, ast, symtab, vartab, &\n & left_branch (right_branch (address)), &\n & val2)\n else\n call interpret_ast_node (outp, ast, symtab, vartab, &\n & right_branch (right_branch (address)), &\n & val2)\n end if\n retval = nil_value\n\n case (node_While)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n do while (rik_cast (val1, ck_'''while'' construct') /= 0_rik)\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n end do\n retval = nil_value\n\n case (node_Prtc)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n write (outp, '(A1)', advance = 'no') &\n & char (rik_cast (val1, ck_'''putc'''), kind = ck)\n retval = nil_value\n\n case (node_Prti, node_Prts)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n select case (val1%tag)\n case (v_Integer)\n write (outp, '(I0)', advance = 'no') val1%int_val\n case (v_String)\n write (outp, '(A)', advance = 'no') val1%str_val\n case (v_Nil)\n write (outp, '(\"(no value)\")', advance = 'no')\n case default\n error stop\n end select\n retval = nil_value\n\n case (node_Sequence)\n call interpret_ast_node (outp, ast, symtab, vartab, left_branch (address), val1)\n call interpret_ast_node (outp, ast, symtab, vartab, right_branch (address), val2)\n retval = nil_value\n\n case default\n write (error_unit, '(\"unknown node type\")')\n stop 1\n\n end select\n\n contains\n\n elemental function left_branch (here_addr) result (left_addr)\n integer(kind = nk), intent(in) :: here_addr\n integer(kind = nk) :: left_addr\n\n left_addr = here_addr + 1\n end function left_branch\n\n elemental function right_branch (here_addr) result (right_addr)\n integer(kind = nk), intent(in) :: here_addr\n integer(kind = nk) :: right_addr\n\n right_addr = here_addr + 1 + ast%nodes(here_addr)%right_branch_offset\n end function right_branch\n\n end subroutine interpret_ast_node\n\n subroutine multiply (x, y, z)\n type(value_t), intent(in) :: x, y\n type(value_t), intent(out) :: z\n\n character(*, kind = ck), parameter :: op = ck_'*'\n\n z = int_value (rik_cast (x, op) * rik_cast (y, op))\n end subroutine multiply\n\n subroutine divide (x, y, z)\n type(value_t), intent(in) :: x, y\n type(value_t), intent(out) :: z\n\n character(*, kind = ck), parameter :: op = ck_'/'\n\n ! Fortran integer division truncates towards zero, as C’s does.\n z = int_value (rik_cast (x, op) / rik_cast (y, op))\n end subroutine divide\n\n subroutine pseudo_remainder (x, y, z)\n type(value_t), intent(in) :: x, y\n type(value_t), intent(out) :: z\n\n !\n ! I call this ‘pseudo-remainder’ because I consider ‘remainder’ to\n ! mean the *non-negative* remainder in A = (B * Quotient) +\n ! Remainder. See https://doi.org/10.1145%2F128861.128862\n !\n ! The pseudo-remainder gives the actual remainder, if both\n ! operands are positive.\n !\n\n character(*, kind = ck), parameter :: op = ck_'binary ''%'''\n\n ! Fortran’s MOD intrinsic, when given integer arguments, works\n ! like C ‘%’.\n z = int_value (mod (rik_cast (x, op), rik_cast (y, op)))\n end subroutine pseudo_remainder\n\n subroutine add (x, y, z)\n type(value_t), intent(in) :: x, y\n type(value_t), intent(out) :: z\n\n character(*, kind = ck), parameter :: op = ck_'binary ''+'''\n\n z = int_value (rik_cast (x, op) + rik_cast (y, op))\n end subroutine add\n\n subroutine subtract (x, y, z)\n type(value_t), intent(in) :: x, y\n type(value_t), intent(out) :: z\n\n character(*, kind = ck), parameter :: op = ck_'binary ''-'''\n\n z = int_value (rik_cast (x, op) - rik_cast (y, op))\n end subroutine subtract\n\n subroutine less_than (x, y, z)\n type(value_t), intent(in) :: x, y\n type(value_t), intent(out) :: z\n\n character(*, kind = ck), parameter :: op = ck_'binary ''<'''\n\n z = int_value (bool2int (rik_cast (x, op) < rik_cast (y, op)))\n end subroutine less_than\n\n subroutine less_than_or_equal_to (x, y, z)\n type(value_t), intent(in) :: x, y\n type(value_t), intent(out) :: z\n\n character(*, kind = ck), parameter :: op = ck_'binary ''<='''\n\n z = int_value (bool2int (rik_cast (x, op) <= rik_cast (y, op)))\n end subroutine less_than_or_equal_to\n\n subroutine greater_than (x, y, z)\n type(value_t), intent(in) :: x, y\n type(value_t), intent(out) :: z\n\n character(*, kind = ck), parameter :: op = ck_'binary ''>'''\n\n z = int_value (bool2int (rik_cast (x, op) > rik_cast (y, op)))\n end subroutine greater_than\n\n subroutine greater_than_or_equal_to (x, y, z)\n type(value_t), intent(in) :: x, y\n type(value_t), intent(out) :: z\n\n character(*, kind = ck), parameter :: op = ck_'binary ''>='''\n\n z = int_value (bool2int (rik_cast (x, op) >= rik_cast (y, op)))\n end subroutine greater_than_or_equal_to\n\n subroutine equal_to (x, y, z)\n type(value_t), intent(in) :: x, y\n type(value_t), intent(out) :: z\n\n character(*, kind = ck), parameter :: op = ck_'binary ''=='''\n\n z = int_value (bool2int (rik_cast (x, op) == rik_cast (y, op)))\n end subroutine equal_to\n\n subroutine not_equal_to (x, y, z)\n type(value_t), intent(in) :: x, y\n type(value_t), intent(out) :: z\n\n character(*, kind = ck), parameter :: op = ck_'binary ''!='''\n\n z = int_value (bool2int (rik_cast (x, op) /= rik_cast (y, op)))\n end subroutine not_equal_to\n\n function rik_cast (val, operation_name) result (i_val)\n class(*), intent(in) :: val\n character(*, kind = ck), intent(in) :: operation_name\n integer(kind = rik) :: i_val\n\n select type (val)\n class is (value_t)\n if (val%tag == v_Integer) then\n i_val = val%int_val\n else\n call type_error (operation_name)\n end if\n type is (integer(kind = rik))\n i_val = val\n class default\n call type_error (operation_name)\n end select\n end function rik_cast\n\n elemental function bool2int (bool) result (int)\n logical, intent(in) :: bool\n integer(kind = rik) :: int\n\n if (bool) then\n int = 1_rik\n else\n int = 0_rik\n end if\n end function bool2int\n\n subroutine type_error (operation_name)\n character(*, kind = ck), intent(in) :: operation_name\n\n write (error_unit, '(\"type error in \", A)') operation_name\n stop 1\n end subroutine type_error\n\nend module ast_interpreter\n\nprogram Interp\n use, intrinsic :: iso_fortran_env, only: input_unit\n use, intrinsic :: iso_fortran_env, only: output_unit\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, non_intrinsic :: compiler_type_kinds\n use, non_intrinsic :: string_buffers\n use, non_intrinsic :: ast_reader\n use, non_intrinsic :: ast_interpreter\n\n implicit none\n\n integer, parameter :: inp_unit_no = 100\n integer, parameter :: outp_unit_no = 101\n\n integer :: arg_count\n character(200) :: arg\n integer :: inp\n integer :: outp\n\n type(strbuf_t) :: strbuf\n type(interpreter_ast_t) :: ast\n type(symbol_table_t) :: symtab\n type(variable_table_t) :: vartab\n type(value_t) :: retval\n\n arg_count = command_argument_count ()\n if (3 <= arg_count) then\n call print_usage\n else\n if (arg_count == 0) then\n inp = input_unit\n outp = output_unit\n else if (arg_count == 1) then\n call get_command_argument (1, arg)\n inp = open_for_input (trim (arg))\n outp = output_unit\n else if (arg_count == 2) then\n call get_command_argument (1, arg)\n inp = open_for_input (trim (arg))\n call get_command_argument (2, arg)\n outp = open_for_output (trim (arg))\n end if\n\n call read_ast (inp, strbuf, ast, symtab)\n if (1 <= ubound (ast%nodes, 1)) then\n call vartab%initialize(symtab)\n call interpret_ast_node (outp, ast, symtab, vartab, 1_nk, retval)\n end if\n end if\n\ncontains\n\n function open_for_input (filename) result (unit_no)\n character(*), intent(in) :: filename\n integer :: unit_no\n\n integer :: stat\n\n open (unit = inp_unit_no, file = filename, status = 'old', &\n & action = 'read', access = 'stream', form = 'unformatted', &\n & iostat = stat)\n if (stat /= 0) then\n write (error_unit, '(\"Error: failed to open \", 1A, \" for input\")') filename\n stop 1\n end if\n unit_no = inp_unit_no\n end function open_for_input\n\n function open_for_output (filename) result (unit_no)\n character(*), intent(in) :: filename\n integer :: unit_no\n\n integer :: stat\n\n open (unit = outp_unit_no, file = filename, action = 'write', iostat = stat)\n if (stat /= 0) then\n write (error_unit, '(\"Error: failed to open \", 1A, \" for output\")') filename\n stop 1\n end if\n unit_no = outp_unit_no\n end function open_for_output\n\n subroutine print_usage\n character(200) :: progname\n\n call get_command_argument (0, progname)\n write (output_unit, '(\"Usage: \", 1A, \" [INPUT_FILE [OUTPUT_FILE]]\")') &\n & trim (progname)\n end subroutine print_usage\n\nend program Interp\n", "language": "Fortran" }, { "code": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"log\"\n \"os\"\n \"strconv\"\n \"strings\"\n)\n\ntype NodeType int\n\nconst (\n ndIdent NodeType = iota\n ndString\n ndInteger\n ndSequence\n ndIf\n ndPrtc\n ndPrts\n ndPrti\n ndWhile\n ndAssign\n ndNegate\n ndNot\n ndMul\n ndDiv\n ndMod\n ndAdd\n ndSub\n ndLss\n ndLeq\n ndGtr\n ndGeq\n ndEql\n ndNeq\n ndAnd\n ndOr\n)\n\ntype Tree struct {\n nodeType NodeType\n left *Tree\n right *Tree\n value int\n}\n\n// dependency: Ordered by NodeType, must remain in same order as NodeType enum\ntype atr struct {\n enumText string\n nodeType NodeType\n}\n\nvar atrs = []atr{\n {\"Identifier\", ndIdent},\n {\"String\", ndString},\n {\"Integer\", ndInteger},\n {\"Sequence\", ndSequence},\n {\"If\", ndIf},\n {\"Prtc\", ndPrtc},\n {\"Prts\", ndPrts},\n {\"Prti\", ndPrti},\n {\"While\", ndWhile},\n {\"Assign\", ndAssign},\n {\"Negate\", ndNegate},\n {\"Not\", ndNot},\n {\"Multiply\", ndMul},\n {\"Divide\", ndDiv},\n {\"Mod\", ndMod},\n {\"Add\", ndAdd},\n {\"Subtract\", ndSub},\n {\"Less\", ndLss},\n {\"LessEqual\", ndLeq},\n {\"Greater\", ndGtr},\n {\"GreaterEqual\", ndGeq},\n {\"Equal\", ndEql},\n {\"NotEqual\", ndNeq},\n {\"And\", ndAnd},\n {\"Or\", ndOr},\n}\n\nvar (\n stringPool []string\n globalNames []string\n globalValues = make(map[int]int)\n)\n\nvar (\n err error\n scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc btoi(b bool) int {\n if b {\n return 1\n }\n return 0\n}\n\nfunc itob(i int) bool {\n if i == 0 {\n return false\n }\n return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { // interpret the parse tree\n if x == nil {\n return 0\n }\n switch x.nodeType {\n case ndInteger:\n return x.value\n case ndIdent:\n return globalValues[x.value]\n case ndString:\n return x.value\n case ndAssign:\n n := interp(x.right)\n globalValues[x.left.value] = n\n return n\n case ndAdd:\n return interp(x.left) + interp(x.right)\n case ndSub:\n return interp(x.left) - interp(x.right)\n case ndMul:\n return interp(x.left) * interp(x.right)\n case ndDiv:\n return interp(x.left) / interp(x.right)\n case ndMod:\n return interp(x.left) % interp(x.right)\n case ndLss:\n return btoi(interp(x.left) < interp(x.right))\n case ndGtr:\n return btoi(interp(x.left) > interp(x.right))\n case ndLeq:\n return btoi(interp(x.left) <= interp(x.right))\n case ndEql:\n return btoi(interp(x.left) == interp(x.right))\n case ndNeq:\n return btoi(interp(x.left) != interp(x.right))\n case ndAnd:\n return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n case ndOr:\n return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n case ndNegate:\n return -interp(x.left)\n case ndNot:\n if interp(x.left) == 0 {\n return 1\n }\n return 0\n case ndIf:\n if interp(x.left) != 0 {\n interp(x.right.left)\n } else {\n interp(x.right.right)\n }\n return 0\n case ndWhile:\n for interp(x.left) != 0 {\n interp(x.right)\n }\n return 0\n case ndPrtc:\n fmt.Printf(\"%c\", interp(x.left))\n return 0\n case ndPrti:\n fmt.Printf(\"%d\", interp(x.left))\n return 0\n case ndPrts:\n fmt.Print(stringPool[interp(x.left)])\n return 0\n case ndSequence:\n interp(x.left)\n interp(x.right)\n return 0\n default:\n reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n }\n return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n for _, atr := range atrs {\n if atr.enumText == name {\n return atr.nodeType\n }\n }\n reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n return -1\n}\n\nfunc fetchStringOffset(s string) int {\n var d strings.Builder\n s = s[1 : len(s)-1]\n for i := 0; i < len(s); i++ {\n if s[i] == '\\\\' && (i+1) < len(s) {\n if s[i+1] == 'n' {\n d.WriteByte('\\n')\n i++\n } else if s[i+1] == '\\\\' {\n d.WriteByte('\\\\')\n i++\n }\n } else {\n d.WriteByte(s[i])\n }\n }\n s = d.String()\n for i := 0; i < len(stringPool); i++ {\n if s == stringPool[i] {\n return i\n }\n }\n stringPool = append(stringPool, s)\n return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n for i := 0; i < len(globalNames); i++ {\n if globalNames[i] == name {\n return i\n }\n }\n globalNames = append(globalNames, name)\n return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n var nodeType NodeType\n var s string\n if scanner.Scan() {\n line := strings.TrimRight(scanner.Text(), \" \\t\")\n tokens := strings.Fields(line)\n first := tokens[0]\n if first[0] == ';' {\n return nil\n }\n nodeType = getEnumValue(first)\n le := len(tokens)\n if le == 2 {\n s = tokens[1]\n } else if le > 2 {\n idx := strings.Index(line, `\"`)\n s = line[idx:]\n }\n }\n check(scanner.Err())\n if s != \"\" {\n var n int\n switch nodeType {\n case ndIdent:\n n = fetchVarOffset(s)\n case ndInteger:\n n, err = strconv.Atoi(s)\n check(err)\n case ndString:\n n = fetchStringOffset(s)\n default:\n reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n }\n return makeLeaf(nodeType, n)\n }\n left := loadAst()\n right := loadAst()\n return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n ast, err := os.Open(\"ast.txt\")\n check(err)\n defer ast.Close()\n scanner = bufio.NewScanner(ast)\n x := loadAst()\n interp(x)\n}\n", "language": "Go" }, { "code": "outbuf=: ''\nemit=:{{\n outbuf=: outbuf,y\n if.LF e. outbuf do.\n ndx=. outbuf i:LF\n echo ndx{.outbuf\n outbuf=: }.ndx}.outbuf\n end.\n}}\n\nload_ast=: {{\n 'node_types node_values'=: 2{.|:(({.,&<&<}.@}.)~ i.&' ');._2 y\n 1{::0 load_ast ''\n:\n node_type=. x{::node_types\n if. node_type-:,';' do. x;a: return.end.\n node_value=. x{::node_values\n if. -.''-:node_value do.x;<node_type make_leaf node_value return.end.\n 'x left'=.(x+1) load_ast''\n 'x right'=.(x+1) load_ast''\n x;<node_type make_node left right\n}}\n\nmake_leaf=: ;\ntyp=: 0&{::\nval=: left=: 1&{::\nright=: 2&{::\nmake_node=: {{m;n;<y}}\nid2var=: 'var_',rplc&('z';'zz';'_';'_z')\n\ninterp=:{{\n if.y-:'' do.'' return.end.\n V=. val y\n W=. ;2}.y\n select.typ y\n case.'Integer'do._\".V\n case.'String'do.rplc&('\\\\';'\\';'\\n';LF) V-.'\"'\n case.'Identifier'do.\".id2var V\n case.'Assign'do.''[(id2var left V)=: interp W\n case.'Multiply'do.V *&interp W\n case.'Divide'do.V (*&* * <.@%&|)&interp W\n case.'Mod'do.V (*&* * |~&|)&interp W\n case.'Add'do.V +&interp W\n case.'Subtract'do.V -&interp W\n case.'Negate'do.-interp V\n case.'Less'do.V <&interp W\n case.'LessEqual'do.V <:&interp W\n case.'Greater'do.V >&interp W\n case.'GreaterEqual'do.V >&interp W\n case.'Equal'do.V =&interp W\n case.'NotEqual'do.V ~:&interp W\n case.'Not'do.0=interp V\n case.'And'do.V *.&interp W\n case.'Or' do.V +.&interp W\n case.'If'do.if.interp V do.interp left W else.interp right W end.''\n case.'While'do.while.interp V do.interp W end.''\n case.'Prtc'do.emit u:interp V\n case.'Prti'do.emit rplc&'_-'\":interp V\n case.'Prts'do.emit interp V\n case.'Sequence'do.\n interp V\n interp W\n ''\n case.do.error'unknown node type ',typ y\n end.\n}}\n", "language": "J" }, { "code": "primes=:{{)n\n/*\n Simple prime number generator\n */\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n k=3;\n p=1;\n n=n+2;\n while ((k*k<=n) && (p)) {\n p=n/k*k!=n;\n k=k+2;\n }\n if (p) {\n print(n, \" is prime\\n\");\n count = count + 1;\n }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n}}\n\n ast_interp syntax lex primes\n3 is prime\n5 is prime\n7 is prime\n11 is prime\n13 is prime\n17 is prime\n19 is prime\n23 is prime\n29 is prime\n31 is prime\n37 is prime\n41 is prime\n43 is prime\n47 is prime\n53 is prime\n59 is prime\n61 is prime\n67 is prime\n71 is prime\n73 is prime\n79 is prime\n83 is prime\n89 is prime\n97 is prime\n101 is prime\nTotal primes found: 26\n", "language": "J" }, { "code": "import java.util.Scanner;\nimport java.io.File;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\nclass Interpreter {\n\tstatic Map<String, Integer> globals = new HashMap<>();\n\tstatic Scanner s;\n\tstatic List<Node> list = new ArrayList<>();\n\tstatic Map<String, NodeType> str_to_nodes = new HashMap<>();\n\n\tstatic class Node {\n\t\tpublic NodeType nt;\n\t\tpublic Node left, right;\n\t\tpublic String value;\n\t\t\n\t\tNode() {\n\t\t\tthis.nt = null;\n\t\t\tthis.left = null;\n\t\t\tthis.right = null;\n\t\t\tthis.value = null;\n\t\t}\n\t\tNode(NodeType node_type, Node left, Node right, String value) {\n\t\t\tthis.nt = node_type;\n\t\t\tthis.left = left;\n\t\t\tthis.right = right;\n\t\t\tthis.value = value;\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left, Node right) {\n\t\t\treturn new Node(nodetype, left, right, \"\");\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left) {\n\t\t\treturn new Node(nodetype, left, null, \"\");\n\t\t}\n\t\tpublic static Node make_leaf(NodeType nodetype, String value) {\n\t\t\treturn new Node(nodetype, null, null, value);\n\t\t}\n\t}\n\tstatic enum NodeType {\n\t\tnd_None(\";\"), nd_Ident(\"Identifier\"), nd_String(\"String\"), nd_Integer(\"Integer\"),\n\t\tnd_Sequence(\"Sequence\"), nd_If(\"If\"),\n\t\tnd_Prtc(\"Prtc\"), nd_Prts(\"Prts\"), nd_Prti(\"Prti\"), nd_While(\"While\"),\n\t\tnd_Assign(\"Assign\"), nd_Negate(\"Negate\"), nd_Not(\"Not\"), nd_Mul(\"Multiply\"), nd_Div(\"Divide\"),\n\t\tnd_Mod(\"Mod\"), nd_Add(\"Add\"),\n\t\tnd_Sub(\"Subtract\"), nd_Lss(\"Less\"), nd_Leq(\"LessEqual\"),\n\t\tnd_Gtr(\"Greater\"), nd_Geq(\"GreaterEqual\"), nd_Eql(\"Equal\"), nd_Neq(\"NotEqual\"), nd_And(\"And\"), nd_Or(\"Or\");\n\t\t\n\t\tprivate final String name;\n\t\t\n\t\tNodeType(String name) {\tthis.name = name; }\n\t\t\n\t\t@Override\n\t\tpublic String toString() { return this.name; }\n\t}\n\tstatic String str(String s) {\n\t\tString result = \"\";\n\t\tint i = 0;\n\t\ts = s.replace(\"\\\"\", \"\");\n\t\twhile (i < s.length()) {\n\t\t\tif (s.charAt(i) == '\\\\' && i + 1 < s.length()) {\n\t\t\t\tif (s.charAt(i + 1) == 'n') {\n\t\t\t\t\tresult += '\\n';\n\t\t\t\t\ti += 2;\n\t\t\t\t} else if (s.charAt(i) == '\\\\') {\n\t\t\t\t\tresult += '\\\\';\n\t\t\t\t\ti += 2;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresult += s.charAt(i);\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tstatic boolean itob(int i) {\n\t\treturn i != 0;\n\t}\n\tstatic int btoi(boolean b) {\n\t\treturn b ? 1 : 0;\n\t}\n\tstatic int fetch_var(String name) {\n\t\tint result;\n\t\tif (globals.containsKey(name)) {\n\t\t\tresult = globals.get(name);\n\t\t} else {\n\t\t\tglobals.put(name, 0);\n\t\t\tresult = 0;\n\t\t}\n\t\treturn result;\t\t\n\t}\n\tstatic Integer interpret(Node n) throws Exception {\n\t\tif (n == null) {\n\t\t\treturn 0;\n\t\t}\n\t\tswitch (n.nt) {\n\t\t\tcase nd_Integer:\n\t\t\t\treturn Integer.parseInt(n.value);\n\t\t\tcase nd_Ident:\n\t\t\t\treturn fetch_var(n.value);\n\t\t\tcase nd_String:\n\t\t\t\treturn 1;//n.value;\n\t\t\tcase nd_Assign:\n\t\t\t\tglobals.put(n.left.value, interpret(n.right));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Add:\n\t\t\t\treturn interpret(n.left) + interpret(n.right);\n\t\t\tcase nd_Sub:\n\t\t\t\treturn interpret(n.left) - interpret(n.right);\n\t\t\tcase nd_Mul:\n\t\t\t\treturn interpret(n.left) * interpret(n.right);\n\t\t\tcase nd_Div:\n\t\t\t\treturn interpret(n.left) / interpret(n.right);\n\t\t\tcase nd_Mod:\n\t\t\t\treturn interpret(n.left) % interpret(n.right);\n\t\t\tcase nd_Lss:\n\t\t\t\treturn btoi(interpret(n.left) < interpret(n.right));\n\t\t\tcase nd_Leq:\n\t\t\t\treturn btoi(interpret(n.left) <= interpret(n.right));\n\t\t\tcase nd_Gtr:\n\t\t\t\treturn btoi(interpret(n.left) > interpret(n.right));\n\t\t\tcase nd_Geq:\n\t\t\t\treturn btoi(interpret(n.left) >= interpret(n.right));\n\t\t\tcase nd_Eql:\n\t\t\t\treturn btoi(interpret(n.left) == interpret(n.right));\n\t\t\tcase nd_Neq:\n\t\t\t\treturn btoi(interpret(n.left) != interpret(n.right));\n\t\t\tcase nd_And:\n\t\t\t\treturn btoi(itob(interpret(n.left)) && itob(interpret(n.right)));\n\t\t\tcase nd_Or:\n\t\t\t\treturn btoi(itob(interpret(n.left)) || itob(interpret(n.right)));\n\t\t\tcase nd_Not:\n\t\t\t\tif (interpret(n.left) == 0) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tcase nd_Negate:\n\t\t\t\treturn -interpret(n.left);\n\t\t\tcase nd_If:\n\t\t\t\tif (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right.left);\n\t\t\t\t} else {\n\t\t\t\t\tinterpret(n.right.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_While:\n\t\t\t\twhile (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prtc:\n\t\t\t\tSystem.out.printf(\"%c\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prti:\n\t\t\t\tSystem.out.printf(\"%d\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prts:\n\t\t\t\tSystem.out.print(str(n.left.value));//interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Sequence:\n\t\t\t\tinterpret(n.left);\n\t\t\t\tinterpret(n.right);\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception(\"Error: '\" + n.nt + \"' found, expecting operator\");\n\t\t}\n\t}\n\tstatic Node load_ast() throws Exception {\n\t\tString command, value;\n\t\tString line;\n\t\tNode left, right;\n\t\t\n\t\twhile (s.hasNext()) {\n\t\t\tline = s.nextLine();\n\t\t\tvalue = null;\n\t\t\tif (line.length() > 16) {\n\t\t\t\tcommand = line.substring(0, 15).trim();\n\t\t\t\tvalue = line.substring(15).trim();\n\t\t\t} else {\n\t\t\t\tcommand = line.trim();\n\t\t\t}\n\t\t\tif (command.equals(\";\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!str_to_nodes.containsKey(command)) {\n\t\t\t\tthrow new Exception(\"Command not found: '\" + command + \"'\");\n\t\t\t}\n\t\t\tif (value != null) {\n\t\t\t\treturn Node.make_leaf(str_to_nodes.get(command), value);\n\t\t\t}\n\t\t\tleft = load_ast(); right = load_ast();\n\t\t\treturn Node.make_node(str_to_nodes.get(command), left, right);\n\t\t}\n\t\treturn null; // for the compiler, not needed\n\t}\n\tpublic static void main(String[] args) {\n\t\tNode n;\n\n\t\tstr_to_nodes.put(\";\", NodeType.nd_None);\n\t\tstr_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n\t\tstr_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n\t\tstr_to_nodes.put(\"String\", NodeType.nd_String);\n\t\tstr_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n\t\tstr_to_nodes.put(\"If\", NodeType.nd_If);\n\t\tstr_to_nodes.put(\"While\", NodeType.nd_While);\n\t\tstr_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n\t\tstr_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n\t\tstr_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n\t\tstr_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n\t\tstr_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n\t\tstr_to_nodes.put(\"Not\", NodeType.nd_Not);\n\t\tstr_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n\t\tstr_to_nodes.put(\"Divide\", NodeType.nd_Div);\n\t\tstr_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n\t\tstr_to_nodes.put(\"Add\", NodeType.nd_Add);\n\t\tstr_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n\t\tstr_to_nodes.put(\"Less\", NodeType.nd_Lss);\n\t\tstr_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n\t\tstr_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n\t\tstr_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n\t\tstr_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n\t\tstr_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n\t\tstr_to_nodes.put(\"And\", NodeType.nd_And);\n\t\tstr_to_nodes.put(\"Or\", NodeType.nd_Or);\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttry {\n\t\t\t\ts = new Scanner(new File(args[0]));\n\t\t\t\tn = load_ast();\n\t\t\t\tinterpret(n);\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"Ex: \"+e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n}\n", "language": "Java" }, { "code": "struct Anode\n node_type::String\n left::Union{Nothing, Anode}\n right::Union{Nothing, Anode}\n value::Union{Nothing, String}\nend\n\nmake_leaf(t, v) = Anode(t, nothing, nothing, v)\nmake_node(t, l, r) = Anode(t, l, r, nothing)\n\nconst OP2 = Dict(\"Multiply\" => \"*\", \"Divide\" => \"/\", \"Mod\" => \"%\", \"Add\" => \"+\", \"Subtract\" => \"-\",\n \"Less\" => \"<\", \"Greater\" => \">\", \"LessEqual\" => \"<=\", \"GreaterEqual\" => \">=\",\n \"Equal\" => \"==\", \"NotEqual\" => \"!=\", \"And\" => \"&&\", \"Or\" => \"||\")\nconst OP1 = Dict(\"Not\" => \"!\", \"Minus\" => \"-\")\n\ntobool(i::Bool) = i\ntobool(i::Int) = (i != 0)\ntobool(s::String) = eval(Symbol(s)) != 0\n\nconst stac = Vector{Any}()\n\nfunction call2(op, x, y)\n if op in [\"And\", \"Or\"]\n x, y = tobool(x), tobool(y)\n end\n eval(Meta.parse(\"push!(stac, $(x) $(OP2[op]) $(y))\"))\n return Int(floor(pop!(stac)))\nend\n\ncall1(op, x) = (if op in [\"Not\"] x = tobool(x) end; eval(Meta.parse(\"$(OP1[op]) $(x)\")))\nevalpn(op, x, y = nothing) = (haskey(OP2, op) ? call2(op, x, y) : call1(op, x))\n\nfunction load_ast(io)\n line = strip(readline(io))\n line_list = filter(x -> x != nothing, match(r\"(?:(\\w+)\\s+(\\d+|\\w+|\\\".*\\\")|(\\w+|;))\", line).captures)\n text = line_list[1]\n if text == \";\"\n return nothing\n end\n node_type = text\n if length(line_list) > 1\n return make_leaf(line_list[1], line_list[2])\n end\n left = load_ast(io)\n right = load_ast(io)\n return make_node(line_list[1], left, right)\nend\n\nfunction interp(x)\n if x == nothing return nothing\n elseif x.node_type == \"Integer\" return parse(Int, x.value)\n elseif x.node_type == \"Identifier\" return \"_\" * x.value\n elseif x.node_type == \"String\" return replace(replace(x.value, \"\\\"\" => \"\"), \"\\\\n\" => \"\\n\")\n elseif x.node_type == \"Assign\" s = \"$(interp(x.left)) = $(interp(x.right))\"; eval(Meta.parse(s)); return nothing\n elseif x.node_type in keys(OP2) return evalpn(x.node_type, interp(x.left), interp(x.right))\n elseif x.node_type in keys(OP1) return evalpn(x.node_type, interp(x.left))\n elseif x.node_type == \"If\" tobool(eval(interp(x.left))) ? interp(x.right.left) : interp(x.right.right); return nothing\n elseif x.node_type == \"While\" while tobool(eval(interp(x.left))) interp(x.right) end; return nothing\n elseif x.node_type == \"Prtc\" print(Char(eval(interp(x.left)))); return nothing\n elseif x.node_type == \"Prti\" s = interp(x.left); print((i = tryparse(Int, s)) == nothing ? eval(Symbol(s)) : i); return nothing\n elseif x.node_type == \"Prts\" print(eval(interp(x.left))); return nothing\n elseif x.node_type == \"Sequence\" interp(x.left); interp(x.right); return nothing\n else\n throw(\"unknown node type: $x\")\n end\nend\n\nconst testparsed = \"\"\"\nSequence\nSequence\nSequence\nSequence\nSequence\n;\nAssign\nIdentifier count\nInteger 1\nAssign\nIdentifier n\nInteger 1\nAssign\nIdentifier limit\nInteger 100\nWhile\nLess\nIdentifier n\nIdentifier limit\nSequence\nSequence\nSequence\nSequence\nSequence\n;\nAssign\nIdentifier k\nInteger 3\nAssign\nIdentifier p\nInteger 1\nAssign\nIdentifier n\nAdd\nIdentifier n\nInteger 2\nWhile\nAnd\nLessEqual\nMultiply\nIdentifier k\nIdentifier k\nIdentifier n\nIdentifier p\nSequence\nSequence\n;\nAssign\nIdentifier p\nNotEqual\nMultiply\nDivide\nIdentifier n\nIdentifier k\nIdentifier k\nIdentifier n\nAssign\nIdentifier k\nAdd\nIdentifier k\nInteger 2\nIf\nIdentifier p\nIf\nSequence\nSequence\n;\nSequence\nSequence\n;\nPrti\nIdentifier n\n;\nPrts\nString \\\" is prime\\\\n\\\"\n;\nAssign\nIdentifier count\nAdd\nIdentifier count\nInteger 1\n;\nSequence\nSequence\nSequence\n;\nPrts\nString \\\"Total primes found: \\\"\n;\nPrti\nIdentifier count\n;\nPrts\nString \\\"\\\\n\\\"\n; \"\"\"\n\nconst lio = IOBuffer(testparsed)\n\ninterp(load_ast(lio))\n", "language": "Julia" }, { "code": "import os, strutils, streams, tables\n\nimport ast_parser\n\ntype\n\n ValueKind = enum valNil, valInt, valString\n\n # Representation of a value.\n Value = object\n case kind: ValueKind\n of valNil: nil\n of valInt: intVal: int\n of valString: stringVal: string\n\n # Range of binary operators.\n BinaryOperator = range[nMultiply..nOr]\n\n# Table of variables.\nvar variables: Table[string, Value]\n\ntype RunTimeError = object of CatchableError\n\n#---------------------------------------------------------------------------------------------------\n\ntemplate newInt(val: typed): Value =\n ## Create an integer value.\n Value(kind: valInt, intVal: val)\n\n#---------------------------------------------------------------------------------------------------\n\nproc interp(node: Node): Value =\n ## Interpret code starting at \"node\".\n\n if node.isNil:\n return Value(kind: valNil)\n\n case node.kind\n\n of nInteger:\n result = Value(kind: valInt, intVal: node.intVal)\n\n of nIdentifier:\n if node.name notin variables:\n raise newException(RunTimeError, \"Variable {node.name} is not initialized.\")\n result = variables[node.name]\n\n of nString:\n result = Value(kind: valString, stringVal: node.stringVal)\n\n of nAssign:\n variables[node.left.name] = interp(node.right)\n\n of nNegate:\n result = newInt(-interp(node.left).intVal)\n\n of nNot:\n result = newInt(not interp(node.left).intVal)\n\n of BinaryOperator.low..BinaryOperator.high:\n\n let left = interp(node.left)\n let right = interp(node.right)\n\n case BinaryOperator(node.kind)\n of nMultiply:\n result = newInt(left.intVal * right.intVal)\n of nDivide:\n result = newInt(left.intVal div right.intVal)\n of nMod:\n result = newInt(left.intVal mod right.intVal)\n of nAdd:\n result = newInt(left.intVal + right.intVal)\n of nSubtract:\n result = newInt(left.intVal - right.intVal)\n of nLess:\n result = newInt(ord(left.intVal < right.intVal))\n of nLessEqual:\n result = newInt(ord(left.intVal <= right.intVal))\n of nGreater:\n result = newInt(ord(left.intVal > right.intVal))\n of nGreaterEqual:\n result = newInt(ord(left.intVal >= right.intVal))\n of nEqual:\n result = newInt(ord(left.intVal == right.intVal))\n of nNotEqual:\n result = newInt(ord(left.intVal != right.intVal))\n of nAnd:\n result = newInt(left.intVal and right.intVal)\n of nOr:\n result = newInt(left.intVal or right.intVal)\n\n of nIf:\n if interp(node.left).intVal != 0:\n discard interp(node.right.left)\n else:\n discard interp(node.right.right)\n\n of nWhile:\n while interp(node.left).intVal != 0:\n discard interp(node.right)\n\n of nPrtc:\n stdout.write(chr(interp(node.left).intVal))\n\n of nPrti:\n stdout.write(interp(node.left).intVal)\n\n of nPrts:\n stdout.write(interp(node.left).stringVal)\n\n of nSequence:\n discard interp(node.left)\n discard interp(node.right)\n\n#---------------------------------------------------------------------------------------------------\n\nimport re\n\nproc loadAst(stream: Stream): Node =\n ## Load a linear AST and build a binary tree.\n\n let line = stream.readLine().strip()\n if line.startsWith(';'):\n return nil\n\n var fields = line.split(' ', 1)\n let kind = parseEnum[NodeKind](fields[0])\n if kind in {nIdentifier, nString, nInteger}:\n if fields.len < 2:\n raise newException(ValueError, \"Missing value field for \" & fields[0])\n else:\n fields[1] = fields[1].strip()\n case kind\n of nIdentifier:\n return Node(kind: nIdentifier, name: fields[1])\n of nString:\n str = fields[1].replacef(re\"([^\\\\])(\\\\n)\", \"$1\\n\").replace(r\"\\\\\", r\"\\\").replace(\"\\\"\", \"\")\n return Node(kind: nString, stringVal: str)\n of nInteger:\n return Node(kind: nInteger, intVal: parseInt(fields[1]))\n else:\n if fields.len > 1:\n raise newException(ValueError, \"Extra field for \" & fields[0])\n\n let left = stream.loadAst()\n let right = stream.loadAst()\n result = newNode(kind, left, right)\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nvar stream: Stream\nvar toClose = false\n\nif paramCount() < 1:\n stream = newFileStream(stdin)\nelse:\n stream = newFileStream(paramStr(1))\n toClose = true\n\nlet ast = loadAst(stream)\nif toClose: stream.close()\n\ndiscard ast.interp()\n", "language": "Nim" }, { "code": "#!/usr/bin/perl\n\nuse strict; # interpreter.pl - execute a flatAST\nuse warnings; # http://www.rosettacode.org/wiki/Compiler/AST_interpreter\nuse integer;\n\nmy %variables;\n\ntree()->run;\n\nsub tree\n {\n my $line = <> // die \"incomplete tree\\n\";\n (local $_, my $arg) = $line =~ /^(\\w+|;)\\s+(.*)/ or die \"bad input $line\";\n /String/ ? bless [$arg =~ tr/\"\"//dr =~ s/\\\\(.)/$1 eq 'n' ? \"\\n\" : $1/ger], $_ :\n /Identifier|Integer/ ? bless [ $arg ], $_ :\n /;/ ? bless [], 'Null' :\n bless [ tree(), tree() ], $_;\n }\n\nsub Add::run { $_[0][0]->run + $_[0][1]->run }\nsub And::run { $_[0][0]->run && $_[0][1]->run }\nsub Assign::run { $variables{$_[0][0][0]} = $_[0][1]->run }\nsub Divide::run { $_[0][0]->run / $_[0][1]->run }\nsub Equal::run { $_[0][0]->run == $_[0][1]->run ? 1 : 0 }\nsub Greater::run { $_[0][0]->run > $_[0][1]->run ? 1 : 0 }\nsub GreaterEqual::run { $_[0][0]->run >= $_[0][1]->run ? 1 : 0 }\nsub Identifier::run { $variables{$_[0][0]} // 0 }\nsub If::run { $_[0][0]->run ? $_[0][1][0]->run : $_[0][1][1]->run }\nsub Integer::run { $_[0][0] }\nsub Less::run { $_[0][0]->run < $_[0][1]->run ? 1 : 0 }\nsub LessEqual::run { $_[0][0]->run <= $_[0][1]->run ? 1 : 0 }\nsub Mod::run { $_[0][0]->run % $_[0][1]->run }\nsub Multiply::run { $_[0][0]->run * $_[0][1]->run }\nsub Negate::run { - $_[0][0]->run }\nsub Not::run { $_[0][0]->run ? 0 : 1 }\nsub NotEqual::run { $_[0][0]->run != $_[0][1]->run ? 1 : 0 }\nsub Null::run {}\nsub Or::run { $_[0][0]->run || $_[0][1]->run }\nsub Prtc::run { print chr $_[0][0]->run }\nsub Prti::run { print $_[0][0]->run }\nsub Prts::run { print $_[0][0][0] }\nsub Sequence::run { $_->run for $_[0]->@* }\nsub Subtract::run { $_[0][0]->run - $_[0][1]->run }\nsub While::run { $_[0][1]->run while $_[0][0]->run }\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Compiler\\interp.exw\n -- ================================\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">parse</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">vars</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span>\n <span style=\"color: #000000;\">vals</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">var_idx</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">inode</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">inode</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #000000;\">tk_Identifier</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">ident</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">inode</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ident</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">vars</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">vars</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">vars</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ident</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">vals</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">vals</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">vars</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">n</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #004600;\">NULL</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ntype</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">t2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">t3</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">]:</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">ntype</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Sequence</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_assign</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">vals</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">var_idx</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Identifier</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">vals</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">var_idx</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)]</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Integer</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">t2</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_String</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">t2</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_lt</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\"><</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_add</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_sub</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_while</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Prints</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Printi</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_putc</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%c\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_and</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_or</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_le</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\"><=</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_ge</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">>=</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_ne</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">!=</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_gt</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_mul</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_div</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">trunc</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_mod</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_if</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t3</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)?</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)])</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_not</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_neg</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">error</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"unknown node type\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">NULL</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cl</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">open_files</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cl</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">toks</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">lex</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">parse</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">interp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">close_files</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000080;font-style:italic;\">--main(command_line())</span>\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"primes.c\"</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "from __future__ import print_function\nimport sys, shlex, operator\n\nnd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \\\nnd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \\\nnd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25)\n\nall_syms = {\n \"Identifier\" : nd_Ident, \"String\" : nd_String,\n \"Integer\" : nd_Integer, \"Sequence\" : nd_Sequence,\n \"If\" : nd_If, \"Prtc\" : nd_Prtc,\n \"Prts\" : nd_Prts, \"Prti\" : nd_Prti,\n \"While\" : nd_While, \"Assign\" : nd_Assign,\n \"Negate\" : nd_Negate, \"Not\" : nd_Not,\n \"Multiply\" : nd_Mul, \"Divide\" : nd_Div,\n \"Mod\" : nd_Mod, \"Add\" : nd_Add,\n \"Subtract\" : nd_Sub, \"Less\" : nd_Lss,\n \"LessEqual\" : nd_Leq, \"Greater\" : nd_Gtr,\n \"GreaterEqual\": nd_Geq, \"Equal\" : nd_Eql,\n \"NotEqual\" : nd_Neq, \"And\" : nd_And,\n \"Or\" : nd_Or}\n\ninput_file = None\nglobals = {}\n\n#*** show error and exit\ndef error(msg):\n print(\"%s\" % (msg))\n exit(1)\n\nclass Node:\n def __init__(self, node_type, left = None, right = None, value = None):\n self.node_type = node_type\n self.left = left\n self.right = right\n self.value = value\n\n#***\ndef make_node(oper, left, right = None):\n return Node(oper, left, right)\n\n#***\ndef make_leaf(oper, n):\n return Node(oper, value = n)\n\n#***\ndef fetch_var(var_name):\n n = globals.get(var_name, None)\n if n == None:\n globals[var_name] = n = 0\n return n\n\n#***\ndef interp(x):\n global globals\n\n if x == None: return None\n elif x.node_type == nd_Integer: return int(x.value)\n elif x.node_type == nd_Ident: return fetch_var(x.value)\n elif x.node_type == nd_String: return x.value\n\n elif x.node_type == nd_Assign:\n globals[x.left.value] = interp(x.right)\n return None\n elif x.node_type == nd_Add: return interp(x.left) + interp(x.right)\n elif x.node_type == nd_Sub: return interp(x.left) - interp(x.right)\n elif x.node_type == nd_Mul: return interp(x.left) * interp(x.right)\n # use C like division semantics\n # another way: abs(x) / abs(y) * cmp(x, 0) * cmp(y, 0)\n elif x.node_type == nd_Div: return int(float(interp(x.left)) / interp(x.right))\n elif x.node_type == nd_Mod: return int(float(interp(x.left)) % interp(x.right))\n elif x.node_type == nd_Lss: return interp(x.left) < interp(x.right)\n elif x.node_type == nd_Gtr: return interp(x.left) > interp(x.right)\n elif x.node_type == nd_Leq: return interp(x.left) <= interp(x.right)\n elif x.node_type == nd_Geq: return interp(x.left) >= interp(x.right)\n elif x.node_type == nd_Eql: return interp(x.left) == interp(x.right)\n elif x.node_type == nd_Neq: return interp(x.left) != interp(x.right)\n elif x.node_type == nd_And: return interp(x.left) and interp(x.right)\n elif x.node_type == nd_Or: return interp(x.left) or interp(x.right)\n elif x.node_type == nd_Negate: return -interp(x.left)\n elif x.node_type == nd_Not: return not interp(x.left)\n\n elif x.node_type == nd_If:\n if (interp(x.left)):\n interp(x.right.left)\n else:\n interp(x.right.right)\n return None\n\n elif x.node_type == nd_While:\n while (interp(x.left)):\n interp(x.right)\n return None\n\n elif x.node_type == nd_Prtc:\n print(\"%c\" % (interp(x.left)), end='')\n return None\n\n elif x.node_type == nd_Prti:\n print(\"%d\" % (interp(x.left)), end='')\n return None\n\n elif x.node_type == nd_Prts:\n print(interp(x.left), end='')\n return None\n\n elif x.node_type == nd_Sequence:\n interp(x.left)\n interp(x.right)\n return None\n else:\n error(\"error in code generator - found %d, expecting operator\" % (x.node_type))\n\ndef str_trans(srce):\n dest = \"\"\n i = 0\n srce = srce[1:-1]\n while i < len(srce):\n if srce[i] == '\\\\' and i + 1 < len(srce):\n if srce[i + 1] == 'n':\n dest += '\\n'\n i += 2\n elif srce[i + 1] == '\\\\':\n dest += '\\\\'\n i += 2\n else:\n dest += srce[i]\n i += 1\n\n return dest\n\ndef load_ast():\n line = input_file.readline()\n line_list = shlex.split(line, False, False)\n\n text = line_list[0]\n\n value = None\n if len(line_list) > 1:\n value = line_list[1]\n if value.isdigit():\n value = int(value)\n\n if text == \";\":\n return None\n node_type = all_syms[text]\n if value != None:\n if node_type == nd_String:\n value = str_trans(value)\n\n return make_leaf(node_type, value)\n left = load_ast()\n right = load_ast()\n return make_node(node_type, left, right)\n\n#*** main driver\ninput_file = sys.stdin\nif len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], \"r\", 4096)\n except IOError as e:\n error(0, 0, \"Can't open %s\" % sys.argv[1])\n\nn = load_ast()\ninterp(n)\n", "language": "Python" }, { "code": "######################################################################\n#\n# The Rosetta Code AST interpreter in Ratfor 77.\n#\n#\n# In FORTRAN 77 and therefore in Ratfor 77, there is no way to specify\n# that a value should be put on a call stack. Therefore there is no\n# way to implement recursive algorithms in Ratfor 77 (although see the\n# Ratfor for the \"syntax analyzer\" task, where a recursive language is\n# implemented *in* Ratfor). Thus we cannot simply follow the\n# recursive pseudocode, and instead use non-recursive algorithms.\n#\n# How to deal with FORTRAN 77 input is another problem. I use\n# formatted input, treating each line as an array of type\n# CHARACTER--regrettably of no more than some predetermined, finite\n# length. It is a very simple method and presents no significant\n# difficulties, aside from the restriction on line length of the\n# input.\n#\n# Output is a bigger problem. If one uses gfortran, \"advance='no'\" is\n# available, but not if one uses f2c. The method employed here is to\n# construct the output in lines--regrettably, again, of fixed length.\n#\n#\n# On a POSIX platform, the program can be compiled with f2c and run\n# somewhat as follows:\n#\n# ratfor77 interp-in-ratfor.r > interp-in-ratfor.f\n# f2c -C -Nc80 interp-in-ratfor.f\n# cc interp-in-ratfor.c -lf2c\n# ./a.out < compiler-tests/primes.ast\n#\n# With gfortran, a little differently:\n#\n# ratfor77 interp-in-ratfor.r > interp-in-ratfor.f\n# gfortran -fcheck=all -std=legacy interp-in-ratfor.f\n# ./a.out < compiler-tests/primes.ast\n#\n#\n# I/O is strictly from default input and to default output, which, on\n# POSIX systems, usually correspond respectively to standard input and\n# standard output. (I did not wish to have to deal with unit numbers;\n# these are now standardized in ISO_FORTRAN_ENV, but that is not\n# available in FORTRAN 77.)\n#\n#---------------------------------------------------------------------\n\n# Some parameters you may wish to modify.\n\ndefine(LINESZ, 256) # Size of an input line.\ndefine(OUTLSZ, 1024) # Size of an output line.\ndefine(STRNSZ, 4096) # Size of the string pool.\ndefine(NODSSZ, 4096) # Size of the nodes pool.\ndefine(STCKSZ, 4096) # Size of stacks.\ndefine(MAXVAR, 256) # Maximum number of variables.\n\n#---------------------------------------------------------------------\n\ndefine(NEWLIN, 10) # The Unix newline character (ASCII LF).\ndefine(DQUOTE, 34) # The double quote character.\ndefine(BACKSL, 92) # The backslash character.\n\n#---------------------------------------------------------------------\n\ndefine(NODESZ, 3)\ndefine(NNEXTF, 1) # Index for next-free.\ndefine(NTAG, 1) # Index for the tag.\n # For an internal node --\ndefine(NLEFT, 2) # Index for the left node.\ndefine(NRIGHT, 3) # Index for the right node.\n # For a leaf node --\ndefine(NITV, 2) # Index for the string pool index.\ndefine(NITN, 3) # Length of the value.\n\ndefine(NIL, -1) # Nil node.\n\ndefine(RGT, 10000)\ndefine(STAGE2, 20000)\n\n# The following all must be less than RGT.\ndefine(NDID, 0)\ndefine(NDSTR, 1)\ndefine(NDINT, 2)\ndefine(NDSEQ, 3)\ndefine(NDIF, 4)\ndefine(NDPRTC, 5)\ndefine(NDPRTS, 6)\ndefine(NDPRTI, 7)\ndefine(NDWHIL, 8)\ndefine(NDASGN, 9)\ndefine(NDNEG, 10)\ndefine(NDNOT, 11)\ndefine(NDMUL, 12)\ndefine(NDDIV, 13)\ndefine(NDMOD, 14)\ndefine(NDADD, 15)\ndefine(NDSUB, 16)\ndefine(NDLT, 17)\ndefine(NDLE, 18)\ndefine(NDGT, 19)\ndefine(NDGE, 20)\ndefine(NDEQ, 21)\ndefine(NDNE, 22)\ndefine(NDAND, 23)\ndefine(NDOR, 24)\n\n#---------------------------------------------------------------------\n\nfunction issp (c)\n\n # Is a character a space character?\n\n implicit none\n\n character c\n logical issp\n\n integer ic\n\n ic = ichar (c)\n issp = (ic == 32 || (9 <= ic && ic <= 13))\nend\n\nfunction skipsp (str, i, imax)\n\n # Skip past spaces in a string.\n\n implicit none\n\n character str(*)\n integer i\n integer imax\n integer skipsp\n\n logical issp\n\n logical done\n\n skipsp = i\n done = .false.\n while (!done)\n {\n if (imax <= skipsp)\n done = .true.\n else if (!issp (str(skipsp)))\n done = .true.\n else\n skipsp = skipsp + 1\n }\nend\n\nfunction skipns (str, i, imax)\n\n # Skip past non-spaces in a string.\n\n implicit none\n\n character str(*)\n integer i\n integer imax\n integer skipns\n\n logical issp\n\n logical done\n\n skipns = i\n done = .false.\n while (!done)\n {\n if (imax <= skipns)\n done = .true.\n else if (issp (str(skipns)))\n done = .true.\n else\n skipns = skipns + 1\n }\nend\n\nfunction trimrt (str, n)\n\n # Find the length of a string, if one ignores trailing spaces.\n\n implicit none\n\n character str(*)\n integer n\n integer trimrt\n\n logical issp\n\n logical done\n\n trimrt = n\n done = .false.\n while (!done)\n {\n if (trimrt == 0)\n done = .true.\n else if (!issp (str(trimrt)))\n done = .true.\n else\n trimrt = trimrt - 1\n }\nend\n\n#---------------------------------------------------------------------\n\nsubroutine addstq (strngs, istrng, src, i0, n0, i, n)\n\n # Add a quoted string to the string pool.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character src(*) # Source string.\n integer i0, n0 # Index and length in source string.\n integer i, n # Index and length in string pool.\n\n integer j\n logical done\n\n1000 format ('attempt to treat an unquoted string as a quoted string')\n\n if (src(i0) != char (DQUOTE) || src(i0 + n0 - 1) != char (DQUOTE))\n {\n write (*, 1000)\n stop\n }\n\n i = istrng\n\n n = 0\n j = i0 + 1\n done = .false.\n while (j != i0 + n0 - 1)\n if (i == STRNSZ)\n {\n write (*, '(''string pool exhausted'')')\n stop\n }\n else if (src(j) == char (BACKSL))\n {\n if (j == i0 + n0 - 1)\n {\n write (*, '(''incorrectly formed quoted string'')')\n stop\n }\n if (src(j + 1) == 'n')\n strngs(istrng) = char (NEWLIN)\n else if (src(j + 1) == char (BACKSL))\n strngs(istrng) = src(j + 1)\n else\n {\n write (*, '(''unrecognized escape sequence'')')\n stop\n }\n istrng = istrng + 1\n n = n + 1\n j = j + 2\n }\n else\n {\n strngs(istrng) = src(j)\n istrng = istrng + 1\n n = n + 1\n j = j + 1\n }\nend\n\nsubroutine addstu (strngs, istrng, src, i0, n0, i, n)\n\n # Add an unquoted string to the string pool.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character src(*) # Source string.\n integer i0, n0 # Index and length in source string.\n integer i, n # Index and length in string pool.\n\n integer j\n\n if (STRNSZ < istrng + (n0 - 1))\n {\n write (*, '(''string pool exhausted'')')\n stop\n }\n for (j = 0; j < n0; j = j + 1)\n strngs(istrng + j) = src(i0 + j)\n i = istrng\n n = n0\n istrng = istrng + n0\nend\n\nsubroutine addstr (strngs, istrng, src, i0, n0, i, n)\n\n # Add a string (possibly given as a quoted string) to the string\n # pool.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character src(*) # Source string.\n integer i0, n0 # Index and length in source string.\n integer i, n # Index and length in string pool.\n\n if (n0 == 0)\n {\n i = 0\n n = 0\n }\n else if (src(i0) == char (DQUOTE))\n call addstq (strngs, istrng, src, i0, n0, i, n)\n else\n call addstu (strngs, istrng, src, i0, n0, i, n)\nend\n\n#---------------------------------------------------------------------\n\nsubroutine push (stack, sp, i)\n\n implicit none\n\n integer stack(STCKSZ)\n integer sp # Stack pointer.\n integer i # Value to push.\n\n if (sp == STCKSZ)\n {\n write (*, '(''stack overflow in push'')')\n stop\n }\n stack(sp) = i\n sp = sp + 1\nend\n\nfunction pop (stack, sp)\n\n implicit none\n\n integer stack(STCKSZ)\n integer sp # Stack pointer.\n integer pop\n\n if (sp == 1)\n {\n write (*, '(''stack underflow in pop'')')\n stop\n }\n sp = sp - 1\n pop = stack(sp)\nend\n\nfunction nstack (sp)\n\n implicit none\n\n integer sp # Stack pointer.\n integer nstack\n\n nstack = sp - 1 # Current cardinality of the stack.\nend\n\n#---------------------------------------------------------------------\n\nsubroutine initnd (nodes, frelst)\n\n # Initialize the nodes pool.\n\n implicit none\n\n integer nodes (NODESZ, NODSSZ)\n integer frelst # Head of the free list.\n\n integer i\n\n for (i = 1; i < NODSSZ; i = i + 1)\n nodes(NNEXTF, i) = i + 1\n nodes(NNEXTF, NODSSZ) = NIL\n frelst = 1\nend\n\nsubroutine newnod (nodes, frelst, i)\n\n # Get the index for a new node taken from the free list.\n\n integer nodes (NODESZ, NODSSZ)\n integer frelst # Head of the free list.\n integer i # Index of the new node.\n\n integer j\n\n if (frelst == NIL)\n {\n write (*, '(''nodes pool exhausted'')')\n stop\n }\n i = frelst\n frelst = nodes(NNEXTF, frelst)\n for (j = 1; j <= NODESZ; j = j + 1)\n nodes(j, i) = 0\nend\n\nsubroutine frenod (nodes, frelst, i)\n\n # Return a node to the free list.\n\n integer nodes (NODESZ, NODSSZ)\n integer frelst # Head of the free list.\n integer i # Index of the node to free.\n\n nodes(NNEXTF, i) = frelst\n frelst = i\nend\n\nfunction strtag (str, i, n)\n\n implicit none\n\n character str(*)\n integer i, n\n integer strtag\n\n character*16 s\n integer j\n\n for (j = 0; j < 16; j = j + 1)\n if (j < n)\n s(j + 1 : j + 1) = str(i + j)\n else\n s(j + 1 : j + 1) = ' '\n\n if (s == \"Identifier \")\n strtag = NDID\n else if (s == \"String \")\n strtag = NDSTR\n else if (s == \"Integer \")\n strtag = NDINT\n else if (s == \"Sequence \")\n strtag = NDSEQ\n else if (s == \"If \")\n strtag = NDIF\n else if (s == \"Prtc \")\n strtag = NDPRTC\n else if (s == \"Prts \")\n strtag = NDPRTS\n else if (s == \"Prti \")\n strtag = NDPRTI\n else if (s == \"While \")\n strtag = NDWHIL\n else if (s == \"Assign \")\n strtag = NDASGN\n else if (s == \"Negate \")\n strtag = NDNEG\n else if (s == \"Not \")\n strtag = NDNOT\n else if (s == \"Multiply \")\n strtag = NDMUL\n else if (s == \"Divide \")\n strtag = NDDIV\n else if (s == \"Mod \")\n strtag = NDMOD\n else if (s == \"Add \")\n strtag = NDADD\n else if (s == \"Subtract \")\n strtag = NDSUB\n else if (s == \"Less \")\n strtag = NDLT\n else if (s == \"LessEqual \")\n strtag = NDLE\n else if (s == \"Greater \")\n strtag = NDGT\n else if (s == \"GreaterEqual \")\n strtag = NDGE\n else if (s == \"Equal \")\n strtag = NDEQ\n else if (s == \"NotEqual \")\n strtag = NDNE\n else if (s == \"And \")\n strtag = NDAND\n else if (s == \"Or \")\n strtag = NDOR\n else if (s == \"; \")\n strtag = NIL\n else\n {\n write (*, '(''unrecognized input line: '', A16)') s\n stop\n }\nend\n\nsubroutine readln (strngs, istrng, tag, iarg, narg)\n\n # Read a line of the AST input.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n integer tag # The node tag or NIL.\n integer iarg # Index of an argument in the string pool.\n integer narg # Length of an argument in the string pool.\n\n integer trimrt\n integer strtag\n integer skipsp\n integer skipns\n\n character line(LINESZ)\n character*20 fmt\n integer i, j, n\n\n # Read a line of text as an array of characters.\n write (fmt, '(''('', I10, ''A)'')') LINESZ\n read (*, fmt) line\n\n n = trimrt (line, LINESZ)\n\n i = skipsp (line, 1, n + 1)\n j = skipns (line, i, n + 1)\n tag = strtag (line, i, j - i)\n\n i = skipsp (line, j, n + 1)\n call addstr (strngs, istrng, line, i, (n + 1) - i, iarg, narg)\nend\n\nfunction hasarg (tag)\n\n implicit none\n\n integer tag\n logical hasarg\n\n hasarg = (tag == NDID || tag == NDINT || tag == NDSTR)\nend\n\nsubroutine rdast (strngs, istrng, nodes, frelst, iast)\n\n # Read in the AST. A non-recursive algorithm is used.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n integer nodes (NODESZ, NODSSZ) # Nodes pool.\n integer frelst # Head of the free list.\n integer iast # Index of root node of the AST.\n\n integer nstack\n integer pop\n logical hasarg\n\n integer stack(STCKSZ)\n integer sp # Stack pointer.\n integer tag, iarg, narg\n integer i, j, k\n\n sp = 1\n\n call readln (strngs, istrng, tag, iarg, narg)\n if (tag == NIL)\n iast = NIL\n else\n {\n call newnod (nodes, frelst, i)\n iast = i\n nodes(NTAG, i) = tag\n nodes(NITV, i) = 0\n nodes(NITN, i) = 0\n if (hasarg (tag))\n {\n nodes(NITV, i) = iarg\n nodes(NITN, i) = narg\n }\n else\n {\n call push (stack, sp, i + RGT)\n call push (stack, sp, i)\n while (nstack (sp) != 0)\n {\n j = pop (stack, sp)\n k = mod (j, RGT)\n call readln (strngs, istrng, tag, iarg, narg)\n if (tag == NIL)\n i = NIL\n else\n {\n call newnod (nodes, frelst, i)\n nodes(NTAG, i) = tag\n if (hasarg (tag))\n {\n nodes(NITV, i) = iarg\n nodes(NITN, i) = narg\n }\n else\n {\n call push (stack, sp, i + RGT)\n call push (stack, sp, i)\n }\n }\n if (j == k)\n nodes(NLEFT, k) = i\n else\n nodes(NRIGHT, k) = i\n }\n }\n }\nend\n\n#---------------------------------------------------------------------\n\nsubroutine flushl (outbuf, noutbf)\n\n # Flush a line from the output buffer.\n\n implicit none\n\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n\n character*20 fmt\n integer i\n\n if (noutbf == 0)\n write (*, '()')\n else\n {\n write (fmt, 1000) noutbf\n1000 format ('(', I10, 'A)')\n write (*, fmt) (outbuf(i), i = 1, noutbf)\n noutbf = 0\n }\nend\n\nsubroutine wrtchr (outbuf, noutbf, ch)\n\n # Write a character to output.\n\n implicit none\n\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n character ch # The character to output.\n\n # This routine silently truncates anything that goes past the buffer\n # boundary.\n\n if (ch == char (NEWLIN))\n call flushl (outbuf, noutbf)\n else if (noutbf < OUTLSZ)\n {\n noutbf = noutbf + 1\n outbuf(noutbf) = ch\n }\nend\n\nsubroutine wrtstr (outbuf, noutbf, str, i, n)\n\n # Write a substring to output.\n\n implicit none\n\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n character str(*) # The string from which to output.\n integer i, n # Index and length of the substring.\n\n integer j\n\n for (j = 0; j < n; j = j + 1)\n call wrtchr (outbuf, noutbf, str(i + j))\nend\n\nsubroutine wrtint (outbuf, noutbf, ival)\n\n # Write a non-negative integer to output.\n\n implicit none\n\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n integer ival # The non-negative integer to print.\n\n integer skipsp\n\n character*40 buf\n integer i\n\n # Using \"write\" probably is the slowest way one could think of to do\n # this, but people do formatted output all the time, anyway. :) The\n # reason, of course, is that output tends to be slow anyway.\n write (buf, '(I40)') ival\n for (i = skipsp (buf, 1, 41); i <= 40; i = i + 1)\n call wrtchr (outbuf, noutbf, buf(i:i))\nend\n\n#---------------------------------------------------------------------\n\ndefine(VARSZ, 3)\ndefine(VNAMEI, 1) # Variable name's index in the string pool.\ndefine(VNAMEN, 2) # Length of the name.\ndefine(VVALUE, 3) # Variable's value.\n\nfunction fndvar (vars, numvar, strngs, istrng, i0, n0)\n\n implicit none\n\n integer vars(VARSZ, MAXVAR) # Variables.\n integer numvar # Number of variables.\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n integer i0, n0 # Index and length in the string pool.\n integer fndvar # The location of the variable.\n\n integer j, k\n integer i, n\n logical done1\n logical done2\n\n j = 1\n done1 = .false.\n while (!done1)\n if (j == numvar + 1)\n done1 = .true.\n else if (n0 == vars(VNAMEN, j))\n {\n k = 0\n done2 = .false.\n while (!done2)\n if (n0 <= k)\n done2 = .true.\n else if (strngs(i0 + k) == strngs(vars(VNAMEI, j) + k))\n k = k + 1\n else\n done2 = .true.\n if (k < n0)\n j = j + 1\n else\n {\n done2 = .true.\n done1 = .true.\n }\n }\n else\n j = j + 1\n\n if (j == numvar + 1)\n {\n if (numvar == MAXVAR)\n {\n write (*, '(''too many variables'')')\n stop\n }\n numvar = numvar + 1\n call addstu (strngs, istrng, strngs, i0, n0, i, n)\n vars(VNAMEI, numvar) = i\n vars(VNAMEN, numvar) = n\n vars(VVALUE, numvar) = 0\n fndvar = numvar\n }\n else\n fndvar = j\nend\n\nfunction strint (strngs, i, n)\n\n # Convert a string to a non-negative integer.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer i, n\n integer strint\n\n integer j\n\n strint = 0\n for (j = 0; j < n; j = j + 1)\n strint = (10 * strint) + (ichar (strngs(i + j)) - ichar ('0'))\nend\n\nfunction logl2i (u)\n\n # Convert LOGICAL to INTEGER.\n\n implicit none\n\n logical u\n integer logl2i\n\n if (u)\n logl2i = 1\n else\n logl2i = 0\nend\n\nsubroutine run (vars, numvar, _\n strngs, istrng, _\n nodes, frelst, _\n outbuf, noutbf, iast)\n\n # Run (interpret) the AST. The algorithm employed is non-recursive.\n\n implicit none\n\n integer vars(VARSZ, MAXVAR) # Variables.\n integer numvar # Number of variables.\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n integer nodes (NODESZ, NODSSZ) # Nodes pool.\n integer frelst # Head of the free list.\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n integer iast # Root node of the AST.\n\n integer fndvar\n integer logl2i\n integer nstack\n integer pop\n integer strint\n\n integer dstack(STCKSZ) # Data stack.\n integer idstck # Data stack pointer.\n integer xstack(STCKSZ) # Execution stack.\n integer ixstck # Execution stack pointer.\n integer i\n integer i0, n0\n integer tag\n integer ivar\n integer ival1, ival2\n integer inode1, inode2\n\n idstck = 1\n ixstck = 1\n call push (xstack, ixstck, iast)\n while (nstack (ixstck) != 0)\n {\n i = pop (xstack, ixstck)\n if (i == NIL)\n tag = NIL\n else\n tag = nodes(NTAG, i)\n if (tag == NIL)\n continue\n else if (tag == NDSEQ)\n {\n if (nodes(NRIGHT, i) != NIL)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n if (nodes(NLEFT, i) != NIL)\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDID)\n {\n # Push the value of a variable.\n i0 = nodes(NITV, i)\n n0 = nodes(NITN, i)\n ivar = fndvar (vars, numvar, strngs, istrng, i0, n0)\n call push (dstack, idstck, vars(VVALUE, ivar))\n }\n else if (tag == NDINT)\n {\n # Push the value of an integer literal.\n i0 = nodes(NITV, i)\n n0 = nodes(NITN, i)\n call push (dstack, idstck, strint (strngs, i0, n0))\n }\n else if (tag == NDNEG)\n {\n # Evaluate the argument and prepare to negate it.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDNEG + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDNEG + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # Negate the evaluated argument.\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, -ival1)\n }\n else if (tag == NDNOT)\n {\n # Evaluate the argument and prepare to NOT it.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDNOT + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDNOT + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # NOT the evaluated argument.\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, logl2i (ival1 == 0))\n }\n else if (tag == NDAND)\n {\n # Evaluate the arguments and prepare to AND them.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDAND + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDAND + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # AND the evaluated arguments.\n ival2 = pop (dstack, idstck)\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, _\n logl2i (ival1 != 0 && ival2 != 0))\n }\n else if (tag == NDOR)\n {\n # Evaluate the arguments and prepare to OR them.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDOR + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDOR + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # OR the evaluated arguments.\n ival2 = pop (dstack, idstck)\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, _\n logl2i (ival1 != 0 || ival2 != 0))\n }\n else if (tag == NDADD)\n {\n # Evaluate the arguments and prepare to add them.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDADD + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDADD + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # Add the evaluated arguments.\n ival2 = pop (dstack, idstck)\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, ival1 + ival2)\n }\n else if (tag == NDSUB)\n {\n # Evaluate the arguments and prepare to subtract them.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDSUB + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDSUB + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # Subtract the evaluated arguments.\n ival2 = pop (dstack, idstck)\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, ival1 - ival2)\n }\n else if (tag == NDMUL)\n {\n # Evaluate the arguments and prepare to multiply them.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDMUL + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDMUL + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # Multiply the evaluated arguments.\n ival2 = pop (dstack, idstck)\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, ival1 * ival2)\n }\n else if (tag == NDDIV)\n {\n # Evaluate the arguments and prepare to compute the quotient\n # after division.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDDIV + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDDIV + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # Divide the evaluated arguments.\n ival2 = pop (dstack, idstck)\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, ival1 / ival2)\n }\n else if (tag == NDMOD)\n {\n # Evaluate the arguments and prepare to compute the\n # remainder after division.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDMOD + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDMOD + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # MOD the evaluated arguments.\n ival2 = pop (dstack, idstck)\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, mod (ival1, ival2))\n }\n else if (tag == NDEQ)\n {\n # Evaluate the arguments and prepare to test their equality.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDEQ + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDEQ + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # Test for equality.\n ival2 = pop (dstack, idstck)\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, logl2i (ival1 == ival2))\n }\n else if (tag == NDNE)\n {\n # Evaluate the arguments and prepare to test their\n # inequality.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDNE + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDNE + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # Test for inequality.\n ival2 = pop (dstack, idstck)\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, logl2i (ival1 != ival2))\n }\n else if (tag == NDLT)\n {\n # Evaluate the arguments and prepare to test their\n # order.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDLT + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDLT + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # Do the test.\n ival2 = pop (dstack, idstck)\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, logl2i (ival1 < ival2))\n }\n else if (tag == NDLE)\n {\n # Evaluate the arguments and prepare to test their\n # order.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDLE + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDLE + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # Do the test.\n ival2 = pop (dstack, idstck)\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, logl2i (ival1 <= ival2))\n }\n else if (tag == NDGT)\n {\n # Evaluate the arguments and prepare to test their\n # order.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDGT + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDGT + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # Do the test.\n ival2 = pop (dstack, idstck)\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, logl2i (ival1 > ival2))\n }\n else if (tag == NDGE)\n {\n # Evaluate the arguments and prepare to test their\n # order.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDGE + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDGE + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # Do the test.\n ival2 = pop (dstack, idstck)\n ival1 = pop (dstack, idstck)\n call push (dstack, idstck, logl2i (ival1 >= ival2))\n }\n else if (tag == NDASGN)\n {\n # Prepare a new node to do the actual assignment.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDASGN + STAGE2\n nodes(NITV, inode1) = nodes(NITV, nodes(NLEFT, i))\n nodes(NITN, inode1) = nodes(NITN, nodes(NLEFT, i))\n call push (xstack, ixstck, inode1)\n # Evaluate the expression.\n call push (xstack, ixstck, nodes(NRIGHT, i))\n }\n else if (tag == NDASGN + STAGE2)\n {\n # Do the actual assignment, and free the STAGE2 node.\n i0 = nodes(NITV, i)\n n0 = nodes(NITN, i)\n call frenod (nodes, frelst, i)\n ival1 = pop (dstack, idstck)\n ivar = fndvar (vars, numvar, strngs, istrng, i0, n0)\n vars(VVALUE, ivar) = ival1\n }\n else if (tag == NDIF)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDIF + STAGE2\n # The \"then\" and \"else\" clauses, respectively:\n nodes(NLEFT, inode1) = nodes(NLEFT, nodes(NRIGHT, i))\n nodes(NRIGHT, inode1) = nodes(NRIGHT, nodes(NRIGHT, i))\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDIF + STAGE2)\n {\n inode1 = nodes(NLEFT, i) # \"Then\" clause.\n inode2 = nodes(NRIGHT, i) # \"Else\" clause.\n call frenod (nodes, frelst, i)\n ival1 = pop (dstack, idstck)\n if (ival1 != 0)\n call push (xstack, ixstck, inode1)\n else if (inode2 != NIL)\n call push (xstack, ixstck, inode2)\n }\n else if (tag == NDWHIL)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDWHIL + STAGE2\n nodes(NLEFT, inode1) = nodes(NRIGHT, i) # Loop body.\n nodes(NRIGHT, inode1) = i # Top of loop.\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDWHIL + STAGE2)\n {\n inode1 = nodes(NLEFT, i) # Loop body.\n inode2 = nodes(NRIGHT, i) # Top of loop.\n call frenod (nodes, frelst, i)\n ival1 = pop (dstack, idstck)\n if (ival1 != 0)\n {\n call push (xstack, ixstck, inode2) # Top of loop.\n call push (xstack, ixstck, inode1) # The body.\n }\n }\n else if (tag == NDPRTS)\n {\n # Print a string literal. (String literals occur only--and\n # always--within Prts nodes; therefore one need not devise a\n # way push strings to the stack.)\n i0 = nodes(NITV, nodes(NLEFT, i))\n n0 = nodes(NITN, nodes(NLEFT, i))\n call wrtstr (outbuf, noutbf, strngs, i0, n0)\n }\n else if (tag == NDPRTC)\n {\n # Evaluate the argument and prepare to print it.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDPRTC + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDPRTC + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # Print the evaluated argument.\n ival1 = pop (dstack, idstck)\n call wrtchr (outbuf, noutbf, char (ival1))\n }\n else if (tag == NDPRTI)\n {\n # Evaluate the argument and prepare to print it.\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDPRTI + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDPRTI + STAGE2)\n {\n # Free the STAGE2 node.\n call frenod (nodes, frelst, i)\n # Print the evaluated argument.\n ival1 = pop (dstack, idstck)\n call wrtint (outbuf, noutbf, ival1)\n }\n }\nend\n\n#---------------------------------------------------------------------\n\nprogram interp\n\n implicit none\n\n integer vars(VARSZ, MAXVAR) # Variables.\n integer numvar # Number of variables.\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n integer nodes (NODESZ, NODSSZ) # Nodes pool.\n integer frelst # Head of the free list.\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n integer iast # Root node of the AST.\n\n numvar = 0\n istrng = 1\n noutbf = 0\n\n call initnd (nodes, frelst)\n call rdast (strngs, istrng, nodes, frelst, iast)\n\n call run (vars, numvar, _\n strngs, istrng, _\n nodes, frelst, _\n outbuf, noutbf, iast)\n\n if (noutbf != 0)\n call flushl (outbuf, noutbf)\nend\n\n######################################################################\n", "language": "RATFOR" }, { "code": "package xyz.hyperreal.rosettacodeCompiler\n\nimport scala.collection.mutable\nimport scala.io.Source\n\nobject ASTInterpreter {\n\n def fromStdin = fromSource(Source.stdin)\n\n def fromString(src: String) = fromSource(Source.fromString(src))\n\n def fromSource(s: Source) = {\n val lines = s.getLines\n\n def load: Node =\n if (!lines.hasNext)\n TerminalNode\n else\n lines.next.split(\" +\", 2) match {\n case Array(name, value) => LeafNode(name, value)\n case Array(\";\") => TerminalNode\n case Array(name) => BranchNode(name, load, load)\n }\n\n val vars = new mutable.HashMap[String, Any]\n\n def interpInt(n: Node) = interp(n).asInstanceOf[Int]\n\n def interpBoolean(n: Node) = interp(n).asInstanceOf[Boolean]\n\n def interp(n: Node): Any =\n n match {\n case TerminalNode => null\n case LeafNode(\"Identifier\", name) =>\n vars get name match {\n case None =>\n vars(name) = 0\n 0\n case Some(v) => v\n }\n case LeafNode(\"Integer\", \"'\\\\n'\") => '\\n'.toInt\n case LeafNode(\"Integer\", \"'\\\\\\\\'\") => '\\\\'.toInt\n case LeafNode(\"Integer\", value: String) if value startsWith \"'\" => value(1).toInt\n case LeafNode(\"Integer\", value: String) => value.toInt\n case LeafNode(\"String\", value: String) => unescape(value.substring(1, value.length - 1))\n case BranchNode(\"Assign\", LeafNode(_, name), exp) => vars(name) = interp(exp)\n case BranchNode(\"Sequence\", l, r) => interp(l); interp(r)\n case BranchNode(\"Prts\" | \"Prti\", a, _) => print(interp(a))\n case BranchNode(\"Prtc\", a, _) => print(interpInt(a).toChar)\n case BranchNode(\"Add\", l, r) => interpInt(l) + interpInt(r)\n case BranchNode(\"Subtract\", l, r) => interpInt(l) - interpInt(r)\n case BranchNode(\"Multiply\", l, r) => interpInt(l) * interpInt(r)\n case BranchNode(\"Divide\", l, r) => interpInt(l) / interpInt(r)\n case BranchNode(\"Mod\", l, r) => interpInt(l) % interpInt(r)\n case BranchNode(\"Negate\", a, _) => -interpInt(a)\n case BranchNode(\"Less\", l, r) => interpInt(l) < interpInt(r)\n case BranchNode(\"LessEqual\", l, r) => interpInt(l) <= interpInt(r)\n case BranchNode(\"Greater\", l, r) => interpInt(l) > interpInt(r)\n case BranchNode(\"GreaterEqual\", l, r) => interpInt(l) >= interpInt(r)\n case BranchNode(\"Equal\", l, r) => interpInt(l) == interpInt(r)\n case BranchNode(\"NotEqual\", l, r) => interpInt(l) != interpInt(r)\n case BranchNode(\"And\", l, r) => interpBoolean(l) && interpBoolean(r)\n case BranchNode(\"Or\", l, r) => interpBoolean(l) || interpBoolean(r)\n case BranchNode(\"Not\", a, _) => !interpBoolean(a)\n case BranchNode(\"While\", l, r) => while (interpBoolean(l)) interp(r)\n case BranchNode(\"If\", cond, BranchNode(\"If\", yes, no)) => if (interpBoolean(cond)) interp(yes) else interp(no)\n }\n\n interp(load)\n }\n\n abstract class Node\n case class BranchNode(name: String, left: Node, right: Node) extends Node\n case class LeafNode(name: String, value: String) extends Node\n case object TerminalNode extends Node\n\n}\n", "language": "Scala" }, { "code": "package xyz.hyperreal\n\nimport java.io.ByteArrayOutputStream\n\npackage object rosettacodeCompiler {\n\n val escapes = \"\\\\\\\\b|\\\\\\\\f|\\\\\\\\t|\\\\\\\\r|\\\\\\\\n|\\\\\\\\\\\\\\\\|\\\\\\\\\\\"\" r\n\n def unescape(s: String) =\n escapes.replaceAllIn(s, _.matched match {\n case \"\\\\b\" => \"\\b\"\n case \"\\\\f\" => \"\\f\"\n case \"\\\\t\" => \"\\t\"\n case \"\\\\r\" => \"\\r\"\n case \"\\\\n\" => \"\\n\"\n case \"\\\\\\\\\" => \"\\\\\"\n case \"\\\\\\\"\" => \"\\\"\"\n })\n\n def capture(thunk: => Unit) = {\n val buf = new ByteArrayOutputStream\n\n Console.withOut(buf)(thunk)\n buf.toString\n }\n\n}\n", "language": "Scala" }, { "code": "(import (scheme base)\n (scheme file)\n (scheme process-context)\n (scheme write)\n (only (srfi 13) string-delete string-index string-trim))\n\n;; Mappings from operation symbols to internal procedures.\n;; We define operations appropriate to virtual machine:\n;; e.g. division must return an int, not a rational\n;; boolean values are treated as numbers: 0 is false, other is true\n(define *unary-ops*\n (list (cons 'Negate (lambda (a) (- a)))\n (cons 'Not (lambda (a) (if (zero? a) 1 0)))))\n(define *binary-ops*\n (let ((number-comp (lambda (op) (lambda (a b) (if (op a b) 1 0)))))\n (list (cons 'Add +)\n (cons 'Subtract -)\n (cons 'Multiply *)\n (cons 'Divide (lambda (a b) (truncate (/ a b)))) ; int division\n (cons 'Mod modulo)\n (cons 'Less (number-comp <))\n (cons 'Greater (number-comp >))\n (cons 'LessEqual (number-comp <=))\n (cons 'GreaterEqual (number-comp >=))\n (cons 'Equal (lambda (a b) (if (= a b) 1 0)))\n (cons 'NotEqual (lambda (a b) (if (= a b) 0 1)))\n (cons 'And (lambda (a b) ; make \"and\" work on numbers\n (if (and (not (zero? a)) (not (zero? b))) 1 0)))\n (cons 'Or (lambda (a b) ; make \"or\" work on numbers\n (if (or (not (zero? a)) (not (zero? b))) 1 0))))))\n\n;; Read AST from given filename\n;; - return as an s-expression\n(define (read-code filename)\n (define (read-expr)\n (let ((line (string-trim (read-line))))\n (if (string=? line \";\")\n '()\n (let ((space (string-index line #\\space)))\n (if space\n (list (string->symbol (string-trim (substring line 0 space)))\n (string-trim (substring line space (string-length line))))\n (list (string->symbol line) (read-expr) (read-expr)))))))\n ;\n (with-input-from-file\n filename\n (lambda ()\n (read-expr))))\n\n;; interpret AST provided as an s-expression\n(define run-program\n (let ((env '())) ; env is an association list for variable names\n (lambda (expr)\n (define (tidy-string str)\n (string-delete ; remove any quote marks\n #\\\" ; \" (to appease Rosetta code's syntax highlighter)\n (list->string\n (let loop ((chars (string->list str))) ; replace newlines, obeying \\\\n\n (cond ((< (length chars) 2) ; finished list\n chars)\n ((and (>= (length chars) 3) ; preserve \\\\n\n (char=? #\\\\ (car chars))\n (char=? #\\\\ (cadr chars))\n (char=? #\\n (cadr (cdr chars))))\n (cons (car chars)\n (cons (cadr chars)\n (cons (cadr (cdr chars))\n (loop (cdr (cdr (cdr chars))))))))\n ((and (char=? #\\\\ (car chars)) ; replace \\n with newline\n (char=? #\\n (cadr chars)))\n (cons #\\newline (loop (cdr (cdr chars)))))\n (else ; keep char and look further\n (cons (car chars) (loop (cdr chars)))))))))\n ; define some more meaningful names for fields\n (define left cadr)\n (define right (lambda (x) (cadr (cdr x))))\n ;\n (if (null? expr)\n '()\n (case (car expr) ; interpret AST from the head node\n ((Integer)\n (string->number (left expr)))\n ((Identifier)\n (let ((val (assq (string->symbol (left expr)) env)))\n (if val\n (cdr val)\n (error \"Variable not in environment\"))))\n ((String)\n (left expr))\n ((Assign)\n (set! env (cons (cons (string->symbol (left (left expr)))\n (run-program (right expr)))\n env)))\n ((Add Subtract Multiply Divide Mod\n Less Greater LessEqual GreaterEqual Equal NotEqual\n And Or)\n (let ((binop (assq (car expr) *binary-ops*)))\n (if binop\n ((cdr binop) (run-program (left expr))\n (run-program (right expr)))\n (error \"Could not find binary operator\"))))\n ((Negate Not)\n (let ((unaryop (assq (car expr) *unary-ops*)))\n (if unaryop\n ((cdr unaryop) (run-program (left expr)))\n (error \"Could not find unary operator\"))))\n ((If)\n (if (not (zero? (run-program (left expr)))) ; 0 means false\n (run-program (left (right expr)))\n (run-program (right (right expr))))\n '())\n ((While)\n (let loop ()\n (unless (zero? (run-program (left expr)))\n (run-program (right expr))\n (loop)))\n '())\n ((Prtc)\n (display (integer->char (run-program (left expr))))\n '())\n ((Prti)\n (display (run-program (left expr)))\n '())\n ((Prts)\n (display (tidy-string (run-program (left expr))))\n '())\n ((Sequence)\n (run-program (left expr))\n (run-program (right expr))\n '())\n (else\n (error \"Unknown node type\")))))))\n\n;; read AST from file and interpret, from filename passed on command line\n(if (= 2 (length (command-line)))\n (run-program (read-code (cadr (command-line))))\n (display \"Error: pass an ast filename\\n\"))\n", "language": "Scheme" }, { "code": "import \"./dynamic\" for Enum, Struct, Tuple\nimport \"./fmt\" for Conv\nimport \"./ioutil\" for FileUtil\n\nvar nodes = [\n \"Ident\",\n \"String\",\n \"Integer\",\n \"Sequence\",\n \"If\",\n \"Prtc\",\n \"Prts\",\n \"Prti\",\n \"While\",\n \"Assign\",\n \"Negate\",\n \"Not\",\n \"Mul\",\n \"Div\",\n \"Mod\",\n \"Add\",\n \"Sub\",\n \"Lss\",\n \"Leq\",\n \"Gtr\",\n \"Geq\",\n \"Eql\",\n \"Neq\",\n \"And\",\n \"Or\"\n]\n\nvar Node = Enum.create(\"Node\", nodes)\n\nvar Tree = Struct.create(\"Tree\", [\"nodeType\", \"left\", \"right\", \"value\"])\n\n// dependency: Ordered by Node value, must remain in same order as Node enum\nvar Atr = Tuple.create(\"Atr\", [\"enumText\", \"nodeType\"])\n\nvar atrs = [\n Atr.new(\"Identifier\", Node.Ident),\n Atr.new(\"String\", Node.String),\n Atr.new(\"Integer\", Node.Integer),\n Atr.new(\"Sequence\", Node.Sequence),\n Atr.new(\"If\", Node.If),\n Atr.new(\"Prtc\", Node.Prtc),\n Atr.new(\"Prts\", Node.Prts),\n Atr.new(\"Prti\", Node.Prti),\n Atr.new(\"While\", Node.While),\n Atr.new(\"Assign\", Node.Assign),\n Atr.new(\"Negate\", Node.Negate),\n Atr.new(\"Not\", Node.Not),\n Atr.new(\"Multiply\", Node.Mul),\n Atr.new(\"Divide\", Node.Div),\n Atr.new(\"Mod\", Node.Mod),\n Atr.new(\"Add\", Node.Add),\n Atr.new(\"Subtract\", Node.Sub),\n Atr.new(\"Less\", Node.Lss),\n Atr.new(\"LessEqual\", Node.Leq),\n Atr.new(\"Greater\", Node.Gtr),\n Atr.new(\"GreaterEqual\", Node.Geq),\n Atr.new(\"Equal\", Node.Eql),\n Atr.new(\"NotEqual\", Node.Neq),\n Atr.new(\"And\", Node.And),\n Atr.new(\"Or\", Node.Or),\n]\n\nvar stringPool = []\nvar globalNames = []\nvar globalValues = {}\n\nvar reportError = Fn.new { |msg| Fiber.abort(\"error : %(msg)\") }\n\nvar makeNode = Fn.new { |nodeType, left, right| Tree.new(nodeType, left, right, 0) }\n\nvar makeLeaf = Fn.new { |nodeType, value| Tree.new(nodeType, null, null, value) }\n\n// interpret the parse tree\nvar interp // recursive function\ninterp = Fn.new { |x|\n if (!x) return 0\n var nt = x.nodeType\n if (nt == Node.Integer) return x.value\n if (nt == Node.Ident) return globalValues[x.value]\n if (nt == Node.String) return x.value\n if (nt == Node.Assign) {\n var n = interp.call(x.right)\n globalValues[x.left.value] = n\n return n\n }\n if (nt == Node.Add) return interp.call(x.left) + interp.call(x.right)\n if (nt == Node.Sub) return interp.call(x.left) - interp.call(x.right)\n if (nt == Node.Mul) return interp.call(x.left) * interp.call(x.right)\n if (nt == Node.Div) return (interp.call(x.left) / interp.call(x.right)).truncate\n if (nt == Node.Mod) return interp.call(x.left) % interp.call(x.right)\n if (nt == Node.Lss) return Conv.btoi(interp.call(x.left) < interp.call(x.right))\n if (nt == Node.Gtr) return Conv.btoi(interp.call(x.left) > interp.call(x.right))\n if (nt == Node.Leq) return Conv.btoi(interp.call(x.left) <= interp.call(x.right))\n if (nt == Node.Eql) return Conv.btoi(interp.call(x.left) == interp.call(x.right))\n if (nt == Node.Neq) return Conv.btoi(interp.call(x.left) != interp.call(x.right))\n if (nt == Node.And) return Conv.btoi(Conv.itob(interp.call(x.left)) && Conv.itob(interp.call(x.right)))\n if (nt == Node.Or) return Conv.btoi(Conv.itob(interp.call(x.left)) || Conv.itob(interp.call(x.right)))\n if (nt == Node.Negate) return -interp.call(x.left)\n if (nt == Node.Not) return (interp.call(x.left) == 0) ? 1 : 0\n if (nt == Node.If) {\n if (interp.call(x.left) != 0) {\n interp.call(x.right.left)\n } else {\n interp.call(x.right.right)\n }\n return 0\n }\n if (nt == Node.While) {\n while (interp.call(x.left) != 0) interp.call(x.right)\n return 0\n }\n if (nt == Node.Prtc) {\n System.write(String.fromByte(interp.call(x.left)))\n return 0\n }\n if (nt == Node.Prti) {\n System.write(interp.call(x.left))\n return 0\n }\n if (nt == Node.Prts) {\n System.write(stringPool[interp.call(x.left)])\n return 0\n }\n if (nt == Node.Sequence) {\n interp.call(x.left)\n interp.call(x.right)\n return 0\n }\n reportError.call(\"interp: unknown tree type %(x.nodeType)\")\n}\n\nvar getEnumValue = Fn.new { |name|\n for (atr in atrs) {\n if (atr.enumText == name) return atr.nodeType\n }\n reportError.call(\"Unknown token %(name)\")\n}\n\nvar fetchStringOffset = Fn.new { |s|\n var d = \"\"\n s = s[1...-1]\n var i = 0\n while (i < s.count) {\n if (s[i] == \"\\\\\" && (i+1) < s.count) {\n if (s[i+1] == \"n\") {\n d = d + \"\\n\"\n i = i + 1\n } else if (s[i+1] == \"\\\\\") {\n d = d + \"\\\\\"\n i = i + 1\n }\n } else {\n d = d + s[i]\n }\n i = i + 1\n }\n s = d\n for (i in 0...stringPool.count) {\n if (s == stringPool[i]) return i\n }\n stringPool.add(s)\n return stringPool.count - 1\n}\n\nvar fetchVarOffset = Fn.new { |name|\n for (i in 0...globalNames.count) {\n if (globalNames[i] == name) return i\n }\n globalNames.add(name)\n return globalNames.count - 1\n}\n\nvar lines = []\nvar lineCount = 0\nvar lineNum = 0\n\nvar loadAst // recursive function\nloadAst = Fn.new {\n var nodeType = 0\n var s = \"\"\n if (lineNum < lineCount) {\n var line = lines[lineNum].trimEnd(\" \\t\")\n lineNum = lineNum + 1\n var tokens = line.split(\" \").where { |s| s != \"\" }.toList\n var first = tokens[0]\n if (first[0] == \";\") return null\n nodeType = getEnumValue.call(first)\n var le = tokens.count\n if (le == 2) {\n s = tokens[1]\n } else if (le > 2) {\n var idx = line.indexOf(\"\\\"\")\n s = line[idx..-1]\n }\n }\n if (s != \"\") {\n var n\n if (nodeType == Node.Ident) {\n n = fetchVarOffset.call(s)\n } else if (nodeType == Node.Integer) {\n n = Num.fromString(s)\n } else if (nodeType == Node.String) {\n n = fetchStringOffset.call(s)\n } else {\n reportError.call(\"Unknown node type: %(s)\")\n }\n return makeLeaf.call(nodeType, n)\n }\n var left = loadAst.call()\n var right = loadAst.call()\n return makeNode.call(nodeType, left, right)\n}\n\nlines = FileUtil.readLines(\"ast.txt\")\nlineCount = lines.count\nvar x = loadAst.call()\ninterp.call(x)\n", "language": "Wren" }, { "code": "const std = @import(\"std\");\n\npub const ASTInterpreterError = error{OutOfMemory};\n\npub const ASTInterpreter = struct {\n output: std.ArrayList(u8),\n globals: std.StringHashMap(NodeValue),\n\n const Self = @This();\n\n pub fn init(allocator: std.mem.Allocator) Self {\n return ASTInterpreter{\n .output = std.ArrayList(u8).init(allocator),\n .globals = std.StringHashMap(NodeValue).init(allocator),\n };\n }\n\n // Returning `NodeValue` from this function looks suboptimal and this should\n // probably be a separate type.\n pub fn interp(self: *Self, tree: ?*Tree) ASTInterpreterError!?NodeValue {\n if (tree) |t| {\n switch (t.typ) {\n .sequence => {\n _ = try self.interp(t.left);\n _ = try self.interp(t.right);\n },\n .assign => try self.globals.put(\n t.left.?.value.?.string,\n (try self.interp(t.right)).?,\n ),\n .identifier => return self.globals.get(t.value.?.string).?,\n .kw_while => {\n while ((try self.interp(t.left)).?.integer != 0) {\n _ = try self.interp(t.right);\n }\n },\n .kw_if => {\n const condition = (try self.interp(t.left)).?.integer;\n if (condition == 1) {\n _ = try self.interp(t.right.?.left);\n } else {\n _ = try self.interp(t.right.?.right);\n }\n },\n .less => return NodeValue{ .integer = try self.binOp(less, t.left, t.right) },\n .less_equal => return NodeValue{ .integer = try self.binOp(less_equal, t.left, t.right) },\n .greater => return NodeValue{ .integer = try self.binOp(greater, t.left, t.right) },\n .greater_equal => return NodeValue{ .integer = try self.binOp(greater_equal, t.left, t.right) },\n .add => return NodeValue{ .integer = try self.binOp(add, t.left, t.right) },\n .subtract => return NodeValue{ .integer = try self.binOp(sub, t.left, t.right) },\n .multiply => return NodeValue{ .integer = try self.binOp(mul, t.left, t.right) },\n .divide => return NodeValue{ .integer = try self.binOp(div, t.left, t.right) },\n .mod => return NodeValue{ .integer = try self.binOp(mod, t.left, t.right) },\n .equal => return NodeValue{ .integer = try self.binOp(equal, t.left, t.right) },\n .not_equal => return NodeValue{ .integer = try self.binOp(not_equal, t.left, t.right) },\n .bool_and => return NodeValue{ .integer = try self.binOp(@\"and\", t.left, t.right) },\n .bool_or => return NodeValue{ .integer = try self.binOp(@\"or\", t.left, t.right) },\n .negate => return NodeValue{ .integer = -(try self.interp(t.left)).?.integer },\n .not => {\n const arg = (try self.interp(t.left)).?.integer;\n const result: i32 = if (arg == 0) 1 else 0;\n return NodeValue{ .integer = result };\n },\n .prts => _ = try self.out(\"{s}\", .{(try self.interp(t.left)).?.string}),\n .prti => _ = try self.out(\"{d}\", .{(try self.interp(t.left)).?.integer}),\n .prtc => _ = try self.out(\"{c}\", .{@as(u8, @intCast((try self.interp(t.left)).?.integer))}),\n .string => return t.value,\n .integer => return t.value,\n .unknown => {\n std.debug.print(\"\\nINTERP: UNKNOWN {}\\n\", .{t});\n std.os.exit(1);\n },\n }\n }\n\n return null;\n }\n\n pub fn out(self: *Self, comptime format: []const u8, args: anytype) ASTInterpreterError!void {\n try self.output.writer().print(format, args);\n }\n\n fn binOp(\n self: *Self,\n comptime func: fn (a: i32, b: i32) i32,\n a: ?*Tree,\n b: ?*Tree,\n ) ASTInterpreterError!i32 {\n return func(\n (try self.interp(a)).?.integer,\n (try self.interp(b)).?.integer,\n );\n }\n\n fn less(a: i32, b: i32) i32 {\n return @intFromBool(a < b);\n }\n fn less_equal(a: i32, b: i32) i32 {\n return @intFromBool(a <= b);\n }\n fn greater(a: i32, b: i32) i32 {\n return @intFromBool(a > b);\n }\n fn greater_equal(a: i32, b: i32) i32 {\n return @intFromBool(a >= b);\n }\n fn equal(a: i32, b: i32) i32 {\n return @intFromBool(a == b);\n }\n fn not_equal(a: i32, b: i32) i32 {\n return @intFromBool(a != b);\n }\n fn add(a: i32, b: i32) i32 {\n return a + b;\n }\n fn sub(a: i32, b: i32) i32 {\n return a - b;\n }\n fn mul(a: i32, b: i32) i32 {\n return a * b;\n }\n fn div(a: i32, b: i32) i32 {\n return @divTrunc(a, b);\n }\n fn mod(a: i32, b: i32) i32 {\n return @mod(a, b);\n }\n fn @\"or\"(a: i32, b: i32) i32 {\n return @intFromBool((a != 0) or (b != 0));\n }\n fn @\"and\"(a: i32, b: i32) i32 {\n return @intFromBool((a != 0) and (b != 0));\n }\n};\n\npub fn main() !void {\n var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);\n defer arena.deinit();\n const allocator = arena.allocator();\n\n var arg_it = try std.process.argsWithAllocator(allocator);\n _ = arg_it.next() orelse unreachable; // program name\n const file_name = arg_it.next();\n // We accept both files and standard input.\n var file_handle = blk: {\n if (file_name) |file_name_delimited| {\n const fname: []const u8 = file_name_delimited;\n break :blk try std.fs.cwd().openFile(fname, .{});\n } else {\n break :blk std.io.getStdIn();\n }\n };\n defer file_handle.close();\n const input_content = try file_handle.readToEndAlloc(allocator, std.math.maxInt(usize));\n\n var string_pool = std.ArrayList([]const u8).init(allocator);\n const ast = try loadAST(allocator, input_content, &string_pool);\n var ast_interpreter = ASTInterpreter.init(allocator);\n _ = try ast_interpreter.interp(ast);\n const result: []const u8 = ast_interpreter.output.items;\n _ = try std.io.getStdOut().write(result);\n}\n\npub const NodeType = enum {\n unknown,\n identifier,\n string,\n integer,\n sequence,\n kw_if,\n prtc,\n prts,\n prti,\n kw_while,\n assign,\n negate,\n not,\n multiply,\n divide,\n mod,\n add,\n subtract,\n less,\n less_equal,\n greater,\n greater_equal,\n equal,\n not_equal,\n bool_and,\n bool_or,\n\n const from_string_map = std.ComptimeStringMap(NodeType, .{\n .{ \"UNKNOWN\", .unknown },\n .{ \"Identifier\", .identifier },\n .{ \"String\", .string },\n .{ \"Integer\", .integer },\n .{ \"Sequence\", .sequence },\n .{ \"If\", .kw_if },\n .{ \"Prtc\", .prtc },\n .{ \"Prts\", .prts },\n .{ \"Prti\", .prti },\n .{ \"While\", .kw_while },\n .{ \"Assign\", .assign },\n .{ \"Negate\", .negate },\n .{ \"Not\", .not },\n .{ \"Multiply\", .multiply },\n .{ \"Divide\", .divide },\n .{ \"Mod\", .mod },\n .{ \"Add\", .add },\n .{ \"Subtract\", .subtract },\n .{ \"Less\", .less },\n .{ \"LessEqual\", .less_equal },\n .{ \"Greater\", .greater },\n .{ \"GreaterEqual\", .greater_equal },\n .{ \"Equal\", .equal },\n .{ \"NotEqual\", .not_equal },\n .{ \"And\", .bool_and },\n .{ \"Or\", .bool_or },\n });\n\n pub fn fromString(str: []const u8) NodeType {\n return from_string_map.get(str).?;\n }\n};\n\npub const NodeValue = union(enum) {\n integer: i32,\n string: []const u8,\n};\n\npub const Tree = struct {\n left: ?*Tree,\n right: ?*Tree,\n typ: NodeType = .unknown,\n value: ?NodeValue = null,\n\n fn makeNode(allocator: std.mem.Allocator, typ: NodeType, left: ?*Tree, right: ?*Tree) !*Tree {\n const result = try allocator.create(Tree);\n result.* = Tree{ .left = left, .right = right, .typ = typ };\n return result;\n }\n\n fn makeLeaf(allocator: std.mem.Allocator, typ: NodeType, value: ?NodeValue) !*Tree {\n const result = try allocator.create(Tree);\n result.* = Tree{ .left = null, .right = null, .typ = typ, .value = value };\n return result;\n }\n};\n\nconst LoadASTError = error{OutOfMemory} || std.fmt.ParseIntError;\n\nfn loadAST(\n allocator: std.mem.Allocator,\n str: []const u8,\n string_pool: *std.ArrayList([]const u8),\n) LoadASTError!?*Tree {\n var line_it = std.mem.split(u8, str, \"\\n\");\n return try loadASTHelper(allocator, &line_it, string_pool);\n}\n\nfn loadASTHelper(\n allocator: std.mem.Allocator,\n line_it: *std.mem.SplitIterator(u8, std.mem.DelimiterType.sequence),\n string_pool: *std.ArrayList([]const u8),\n) LoadASTError!?*Tree {\n if (line_it.next()) |line| {\n var tok_it = std.mem.tokenize(u8, line, \" \");\n const tok_str = tok_it.next().?;\n if (tok_str[0] == ';') return null;\n\n const node_type = NodeType.fromString(tok_str);\n const pre_iteration_index = tok_it.index;\n\n if (tok_it.next()) |leaf_value| {\n const node_value = blk: {\n switch (node_type) {\n .integer => break :blk NodeValue{ .integer = try std.fmt.parseInt(i32, leaf_value, 10) },\n .identifier => break :blk NodeValue{ .string = leaf_value },\n .string => {\n tok_it.index = pre_iteration_index;\n const str = tok_it.rest();\n var string_literal = try std.ArrayList(u8).initCapacity(allocator, str.len);\n var escaped = false;\n // Truncate double quotes\n for (str[1 .. str.len - 1]) |ch| {\n if (escaped) {\n escaped = false;\n switch (ch) {\n 'n' => try string_literal.append('\\n'),\n '\\\\' => try string_literal.append('\\\\'),\n else => unreachable,\n }\n } else {\n switch (ch) {\n '\\\\' => escaped = true,\n else => try string_literal.append(ch),\n }\n }\n }\n try string_pool.append(string_literal.items);\n break :blk NodeValue{ .string = string_literal.items };\n },\n else => unreachable,\n }\n };\n return try Tree.makeLeaf(allocator, node_type, node_value);\n }\n\n const left = try loadASTHelper(allocator, line_it, string_pool);\n const right = try loadASTHelper(allocator, line_it, string_pool);\n return try Tree.makeNode(allocator, node_type, left, right);\n } else {\n return null;\n }\n}\n", "language": "Zig" }, { "code": "const{ var _n=-1; var[proxy]N=fcn{ _n+=1 }; } // enumerator\nconst FETCH=N, STORE=N, PUSH=N, ADD=N, SUB=N, MUL=N, DIV=N, MOD=N,\n LT=N, GT=N, LE=N, GE=N, EQ=N, NE=N,\n AND=N, OR=N, NEG=N, NOT=N,\n JMP=N, JZ=N, PRTC=N, PRTS=N, PRTI=N, HALT=N;\nconst nd_String=N, nd_Sequence=N, nd_If=N, nd_While=N;\nvar [const]\n all_syms=Dictionary(\n \"Identifier\" ,FETCH, \"String\" ,nd_String,\n \"Integer\" ,PUSH, \"Sequence\" ,nd_Sequence,\n \"If\" ,nd_If, \"Prtc\" ,PRTC,\n \"Prts\" ,PRTS, \"Prti\" ,PRTI,\n \"While\" ,nd_While, \"Assign\" ,STORE,\n \"Negate\" ,NEG, \"Not\" ,NOT,\n \"Multiply\" ,MUL, \"Divide\" ,DIV,\n \"Mod\" ,MOD, \"Add\" ,ADD,\n \"Subtract\" ,SUB, \"Less\" ,LT,\n \"LessEqual\" ,LE, \"Greater\" ,GT,\n \"GreaterEqual\",GE, \"Equal\" ,EQ,\n \"NotEqual\" ,NE, \"And\" ,AND,\n \"Or\" ,OR,\t \"halt\"\t,HALT),\n bops=Dictionary(ADD,'+, SUB,'-, MUL,'*, DIV,'/, MOD,'%,\n\t\t LT,'<, GT,'>, LE,'<=, GE,'>=, NE,'!=, EQ,'==, NE,'!=);\n\nclass Node{\n fcn init(_node_type, _value, _left=Void, _right=Void){\n var type=_node_type, left=_left, right=_right, value=_value;\n }\n}\n\nfcn runNode(node){\n var vars=Dictionary(); // fcn local static var\n if(Void==node) return();\n switch(node.type){\n case(PUSH,nd_String){ return(node.value) }\n case(FETCH){ return(vars[node.value]) }\n case(STORE){ vars[node.left.value]=runNode(node.right); return(Void); }\n case(nd_If){\n if(runNode(node.left)) runNode(node.right.left);\n\t else runNode(node.right.right);\n }\n case(nd_While)\n { while(runNode(node.left)){ runNode(node.right) } return(Void) }\n case(nd_Sequence){ runNode(node.left); runNode(node.right); return(Void) }\n case(PRTC) { print(runNode(node.left).toAsc()) }\n case(PRTI,PRTS) { print(runNode(node.left)) }\n case(NEG) { return(-runNode(node.left)) }\n case(NOT) { return(not runNode(node.left)) }\n case(AND) { return(runNode(node.left) and runNode(node.right)) }\n case(OR) { return(runNode(node.left) or runNode(node.right)) }\n else{\n\t if(op:=bops.find(node.type))\n\t return(op(runNode(node.left),runNode(node.right)));\n\t else throw(Exception.AssertionError(\n\t \"Unknown node type: %d\".fmt(node.type)))\n }\n }\n Void\n}\n", "language": "Zkl" }, { "code": "fcn load_ast(file){\n line:=file.readln().strip();\t\t// one or two tokens\n if(line[0]==\";\") return(Void);\n parts,type,value := line.split(),parts[0],parts[1,*].concat(\" \");\n type=all_syms[type];\n if(value){\n try{ value=value.toInt() }catch{}\n if(type==nd_String) value=value[1,-1].replace(\"\\\\n\",\"\\n\");\n return(Node(type,value));\n }\n left,right := load_ast(file),load_ast(file);\n Node(type,Void,left,right)\n}\n", "language": "Zkl" }, { "code": "ast:=load_ast(File(vm.nthArg(0)));\nrunNode(ast);\n", "language": "Zkl" } ]
Compiler-AST-interpreter
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Compiler/code_generator\n", "language": "00-META" }, { "code": "Code Generator\n\nA code generator translates the output of the syntax analyzer and/or semantic analyzer\ninto lower level code, either assembly, object, or virtual.\n\n", "language": "00-TASK" }, { "code": "# RC Compiler code generator #\nCOMMENT\n this writes a .NET IL assembler source to standard output.\n If the output is stored in a file called \"rcsample.il\",\n it could be compiled the command:\n ilasm /opt /out:rcsample.exe rcsample.il\n (Note ilasm may not be in the PATH by default(\n\n Note: The generated IL is *very* naive\nCOMMENT\n\n# parse tree nodes #\nMODE NODE = STRUCT( INT type, REF NODE left, right, INT value );\nINT nidentifier = 1, nstring = 2, ninteger = 3, nsequence = 4, nif = 5, nprtc = 6, nprts = 7\n , nprti = 8, nwhile = 9, nassign = 10, nnegate = 11, nnot = 12, nmultiply = 13, ndivide = 14\n , nmod = 15, nadd = 16, nsubtract = 17, nless = 18, nlessequal = 19, ngreater = 20\n , ngreaterequal = 21, nequal = 22, nnotequal = 23, nand = 24, nor = 25\n ;\n# op codes #\nINT ofetch = 1, ostore = 2, opush = 3, oadd = 4, osub = 5, omul = 6, odiv = 7, omod = 8\n , olt = 9, ogt = 10, ole = 11, oge = 12, oeq = 13, one = 14, oand = 15, oor = 16\n , oneg = 17, onot = 18, ojmp = 19, ojz = 20, oprtc = 21, oprts = 22, oprti = 23, opushstr = 24\n ;\n[]INT ndop\n= ( -1 , -1 , -1 , -1 , -1 , -1 , -1\n , -1 , -1 , -1 , oneg , -1 , omul , odiv\n , omod , oadd , osub , olt , -1 , ogt\n , -1 , oeq , -1 , oand , oor\n ) ;\n[]STRING ndname\n= ( \"Identifier\" , \"String\" , \"Integer\" , \"Sequence\" , \"If\" , \"Prtc\" , \"Prts\"\n , \"Prti\" , \"While\" , \"Assign\" , \"Negate\" , \"Not\" , \"Multiply\" , \"Divide\"\n , \"Mod\" , \"Add\" , \"Subtract\" , \"Less\" , \"LessEqual\" , \"Greater\"\n , \"GreaterEqual\" , \"Equal\" , \"NotEqual\" , \"And\" , \"Or\"\n ) ;\n[]STRING opname\n= ( \"ldloc \", \"stloc \", \"ldc.i4 \", \"add \", \"sub \", \"mul \", \"div \", \"rem \"\n , \"clt \", \"cgt \", \"?le \", \"?ge \", \"ceq \", \"?ne \", \"and \", \"or \"\n , \"neg \", \"?not \", \"br \", \"brfalse\", \"?prtc \", \"?prts \", \"?prti \", \"ldstr \"\n ) ;\n# string and identifier arrays - a hash table might be better... #\nINT max string number = 1024;\n[ 0 : max string number ]STRING identifiers, strings;\nFOR s pos FROM 0 TO max string number DO\n identifiers[ s pos ] := \"\";\n strings [ s pos ] := \"\"\nOD;\n# label number for label generation #\nINT next label number := 0;\n# returns the next free label number #\nPROC new label = INT: next label number +:= 1;\n\n# returns a new node with left and right branches #\nPROC op node = ( INT op type, REF NODE left, right )REF NODE: HEAP NODE := NODE( op type, left, right, 0 );\n# returns a new operand node #\nPROC operand node = ( INT op type, value )REF NODE: HEAP NODE := NODE( op type, NIL, NIL, value );\n\n# reports an error and stops #\nPROC gen error = ( STRING message )VOID:\n BEGIN\n print( ( message, newline ) );\n stop\n END # gen error # ;\n\n# reads a node from standard input #\nPROC read node = REF NODE:\n BEGIN\n REF NODE result := NIL;\n\n # parses a string from line and stores it in a string in the text array #\n # - if it is not already present in the specified textElement list. #\n # returns the position of the string in the text array #\n PROC read string = ( REF[]STRING text list, CHAR terminator )INT:\n BEGIN\n # get the text of the string #\n STRING str := line[ l pos ];\n l pos +:= 1;\n WHILE IF l pos <= UPB line THEN line[ l pos ] /= terminator ELSE FALSE FI DO\n str +:= line[ l pos ];\n l pos +:= 1\n OD;\n IF l pos > UPB line THEN gen error( \"Unterminated String in node file: (\" + line + \").\" ) FI;\n # attempt to find the text in the list of strings/identifiers #\n INT t pos := LWB text list;\n BOOL found := FALSE;\n INT result := LWB text list - 1;\n FOR t pos FROM LWB text list TO UPB text list WHILE NOT found DO\n IF found := text list[ t pos ] = str THEN\n # found the string #\n result := t pos\n ELIF text list[ t pos ] = \"\" THEN\n # have an empty slot for ther string #\n found := TRUE;\n text list[ t pos ] := str;\n result := t pos\n FI\n OD;\n IF NOT found THEN gen error( \"Out of string space.\" ) FI;\n result\n END # read string # ;\n # gets an integer from the line - no checks for valid digits #\n PROC read integer = INT:\n BEGIN\n INT n := 0;\n WHILE line[ l pos ] /= \" \" DO\n ( n *:= 10 ) +:= ( ABS line[ l pos ] - ABS \"0\" );\n l pos +:= 1\n OD;\n n\n END # read integer # ;\n\n STRING line, name;\n INT l pos := 1, nd type := -1;\n read( ( line, newline ) );\n line +:= \" \";\n # get the node type name #\n WHILE line[ l pos ] = \" \" DO l pos +:= 1 OD;\n name := \"\";\n WHILE IF l pos > UPB line THEN FALSE ELSE line[ l pos ] /= \" \" FI DO\n name +:= line[ l pos ];\n l pos +:= 1\n OD;\n # determine the node type #\n nd type := LWB nd name;\n IF name /= \";\" THEN\n # not a null node #\n WHILE IF nd type <= UPB nd name THEN name /= nd name[ nd type ] ELSE FALSE FI DO nd type +:= 1 OD;\n IF nd type > UPB nd name THEN gen error( \"Malformed node: (\" + line + \").\" ) FI;\n # handle the additional parameter for identifier/string/integer, or sub-nodes for operator nodes #\n IF nd type = ninteger OR nd type = nidentifier OR nd type = nstring THEN\n WHILE line[ l pos ] = \" \" DO l pos +:= 1 OD;\n IF nd type = ninteger THEN result := operand node( nd type, read integer )\n ELIF nd type = nidentifier THEN result := operand node( nd type, read string( identifiers, \" \" ) )\n ELSE # nd type = nString # result := operand node( nd type, read string( strings, \"\"\"\" ) )\n FI\n ELSE\n # operator node #\n REF NODE left node = read node;\n result := op node( nd type, left node, read node )\n FI\n FI;\n result\n END # read node # ;\n\n# returns a formatted op code for code generation #\nPROC operation = ( INT op code )STRING: \" \" + op name[ op code ] + \" \";\n# defines the specified label #\nPROC define label = ( INT label number )VOID: print( ( \"lbl_\", whole( label number, 0 ), \":\", newline ) );\n# generates code to load a string value #\nPROC gen load string = ( INT value )VOID:\n BEGIN\n print( ( operation( opushstr ), \" \", strings[ value ], \"\"\"\", newline ) )\n END # push string # ;\n# generates code to load a constant value #\nPROC gen load constant = ( INT value )VOID: print( ( operation( opush ), \" \", whole( value, 0 ), newline ) );\n# generates an operation acting on an address #\nPROC gen data op = ( INT op, address )VOID: print( ( operation( op ), \" l_\", identifiers[ address ], newline ) );\n# generates a nullary operation #\nPROC gen op 0 = ( INT op )VOID: print( ( operation( op ), newline ) );\n# generates a \"not\" instruction sequence #\nPROC gen not = VOID:\n BEGIN\n gen load constant( 0 );\n print( ( operation( oeq ), newline ) )\n END # gen not # ;\n# generates a negated condition #\nPROC gen not op = ( INT op, REF NODE n )VOID:\n BEGIN\n gen( left OF n );\n gen( right OF n );\n gen op 0( op );\n gen not\n END # gen not op # ;\n# generates a jump operation #\nPROC gen jump = ( INT op, label )VOID: print( ( operation( op ), \" lbl_\", whole( label, 0 ), newline ) );\n# generates code to output something to System.Console.Out #\nPROC gen output = ( REF NODE n, STRING output type )VOID:\n BEGIN\n print( ( \" call \" ) );\n print( ( \"class [mscorlib]System.IO.TextWriter [mscorlib]System.Console::get_Out()\", newline ) );\n gen( left OF n );\n print( ( \" callvirt \" ) );\n print( ( \"instance void [mscorlib]System.IO.TextWriter::Write(\", output type, \")\", newline ) )\n END # gen output # ;\n\n# generates the code header - assembly info, namespace, class and start of the Main method #\nPROC code header = VOID:\n BEGIN\n print( ( \".assembly extern mscorlib { auto }\", newline ) );\n print( ( \".assembly RccSample {}\", newline ) );\n print( ( \".module RccSample.exe\", newline ) );\n print( ( \".namespace Rcc.Sample\", newline ) );\n print( ( \"{\", newline ) );\n print( ( \" .class public auto ansi Program extends [mscorlib]System.Object\", newline ) );\n print( ( \" {\", newline ) );\n print( ( \" .method public static void Main() cil managed\", newline ) );\n print( ( \" {\", newline ) );\n print( ( \" .entrypoint\", newline ) );\n # output the local variables #\n BOOL have locals := FALSE;\n STRING local prefix := \" .locals init (int32 l_\";\n FOR s pos FROM LWB identifiers TO UPB identifiers WHILE identifiers[ s pos ] /= \"\" DO\n print( ( local prefix, identifiers[ s pos ], newline ) );\n local prefix := \" ,int32 l_\";\n have locals := TRUE\n OD;\n IF have locals THEN\n # there were some local variables defined - output the terminator #\n print( ( \" )\", newline ) )\n FI\n END # code header # ;\n\n# generates code for the node n #\nPROC gen = ( REF NODE n )VOID:\n IF n IS REF NODE( NIL ) THEN # null node #\n SKIP\n ELIF type OF n = nidentifier THEN # load identifier #\n gen data op( ofetch, value OF n )\n ELIF type OF n = nstring THEN # load string #\n gen load string( value OF n )\n ELIF type OF n = ninteger THEN # load integer #\n gen load constant( value OF n )\n ELIF type OF n = nsequence THEN # list #\n gen( left OF n );\n gen( right OF n )\n ELIF type OF n = nif THEN # if-else #\n INT else label := new label;\n gen( left OF n );\n gen jump( ojz, else label );\n gen( left OF right OF n );\n IF right OF right OF n IS REF NODE( NIL ) THEN\n # no \"else\" part #\n define label( else label )\n ELSE\n # have an \"else\" part #\n INT end if label := new label;\n gen jump( ojmp, end if label );\n define label( else label );\n gen( right OF right OF n );\n define label( end if label )\n FI\n ELIF type OF n = nwhile THEN # while-loop #\n INT loop label := new label;\n INT exit label := new label;\n define label( loop label );\n gen( left OF n );\n gen jump( ojz, exit label );\n gen( right OF n );\n gen jump( ojmp, loop label );\n define label( exit label )\n ELIF type OF n = nassign THEN # assignment #\n gen( right OF n );\n gen data op( ostore, value OF left OF n )\n ELIF type OF n = nnot THEN # bolean not #\n gen( left OF n );\n gen not\n ELIF type OF n = ngreaterequal THEN # compare >= #\n gen not op( olt, n )\n ELIF type OF n = nnotequal THEN # compare not = #\n gen not op( oeq, n )\n ELIF type OF n = nlessequal THEN # compare <= #\n gen not op( ogt, n )\n ELIF type OF n = nprts THEN # print string #\n gen output( n, \"string\" )\n ELIF type OF n = nprtc THEN # print character #\n gen output( n, \"char\" )\n ELIF type OF n = nprti THEN # print integer #\n gen output( n, \"int32\" )\n ELSE # everything else #\n gen( left OF n );\n gen( right OF n ); # right will be null for a unary op so no code will be generated #\n print( ( operation( ndop( type OF n ) ), newline ) )\n FI # gen # ;\n\n# generates the code trailer - return instruction, end of Main method, end of class and end of namespace #\nPROC code trailer = VOID:\n BEGIN\n print( ( \" ret\", newline ) );\n print( ( \" } // Main method\", newline ) );\n print( ( \" } // Program class\", newline ) );\n print( ( \"} // Rcc.Sample namespace\", newline ) )\n END # code trailer # ;\n\n# parse the output from the syntax analyser and generate code from the parse tree #\nREF NODE code = read node;\ncode header;\ngen( code );\ncode trailer\n", "language": "ALGOL-68" }, { "code": "begin % code generator %\n % parse tree nodes %\n record node( integer type\n ; reference(node) left, right\n ; integer iValue % nString/nIndentifier number or nInteger value %\n );\n integer nIdentifier, nString, nInteger, nSequence, nIf, nPrtc, nPrts\n , nPrti, nWhile, nAssign, nNegate, nNot, nMultiply\n , nDivide, nMod, nAdd, nSubtract, nLess, nLessEqual\n , nGreater, nGreaterEqual, nEqual, nNotEqual, nAnd, nOr\n ;\n string(14) array ndName ( 1 :: 25 );\n integer array nOp ( 1 :: 25 );\n integer MAX_NODE_TYPE;\n % string literals and identifiers - uses a linked list - a hash table might be better... %\n string(1) array text ( 0 :: 4095 );\n integer textNext, TEXT_MAX;\n record textElement ( integer start, length; reference(textElement) next );\n reference(textElement) idList, stList;\n % op codes %\n integer oFetch, oStore, oPush\n , oAdd, oSub, oMul, oDiv, oMod, oLt, oGt, oLe, oGe, oEq, oNe\n , oAnd, oOr, oNeg, oNot, oJmp, oJz, oPrtc, oPrts, oPrti, oHalt\n ;\n string(6) array opName ( 1 :: 24 );\n % code - although this is intended to be byte code, as we are going to output %\n % an assembler source, we use integers for convenience %\n % labelLocations are: - ( referencing location + 1 ) if they have been referenced but not defined yet, %\n % zero if they are unreferenced and undefined, %\n % ( referencing location + 1 ) if they are defined %\n integer array byteCode ( 0 :: 4095 );\n integer array labelLocation( 1 :: 4096 );\n integer nextLocation, MAX_LOCATION, nextLabelNumber, MAX_LABEL_NUMBER;\n\n % returns a new node with left and right branches %\n reference(node) procedure opNode ( integer value opType; reference(node) value opLeft, opRight ) ; begin\n node( opType, opLeft, opRight, 0 )\n end opNode ;\n\n % returns a new operand node %\n reference(node) procedure operandNode ( integer value opType, opValue ) ; begin\n node( opType, null, null, opValue )\n end operandNode ;\n\n % reports an error and stops %\n procedure genError( string(80) value message ); begin\n integer errorPos;\n write( s_w := 0, \"**** Code generation error: \" );\n errorPos := 0;\n while errorPos < 80 and message( errorPos // 1 ) not = \".\" do begin\n writeon( s_w := 0, message( errorPos // 1 ) );\n errorPos := errorPos + 1\n end while_not_at_end_of_message ;\n writeon( s_w := 0, \".\" );\n assert( false )\n end genError ;\n\n % reads a node from standard input %\n reference(node) procedure readNode ; begin\n reference(node) resultNode;\n\n % parses a string from line and stores it in a string in the text array %\n % - if it is not already present in the specified textElement list. %\n % returns the position of the string in the text array %\n integer procedure readString ( reference(textElement) value result txList; string(1) value terminator ) ; begin\n string(256) str;\n integer sLen, sPos, ePos;\n logical found;\n reference(textElement) txPos, txLastPos;\n % get the text of the string %\n str := \" \";\n sLen := 0;\n str( sLen // 1 ) := line( lPos // 1 );\n sLen := sLen + 1;\n lPos := lPos + 1;\n while lPos <= 255 and line( lPos // 1 ) not = terminator do begin\n str( sLen // 1 ) := line( lPos // 1 );\n sLen := sLen + 1;\n lPos := lPos + 1\n end while_more_string ;\n if lPos > 255 then genError( \"Unterminated String in node file.\" );\n % attempt to find the text in the list of strings/identifiers %\n txLastPos := txPos := txList;\n found := false;\n ePos := 0;\n while not found and txPos not = null do begin\n ePos := ePos + 1;\n found := ( length(txPos) = sLen );\n sPos := 0;\n while found and sPos < sLen do begin\n found := str( sPos // 1 ) = text( start(txPos) + sPos );\n sPos := sPos + 1\n end while_not_found ;\n txLastPos := txPos;\n if not found then txPos := next(txPos)\n end while_string_not_found ;\n if not found then begin\n % the string/identifier is not in the list - add it %\n ePos := ePos + 1;\n if txList = null then txList := textElement( textNext, sLen, null )\n else next(txLastPos) := textElement( textNext, sLen, null );\n if textNext + sLen > TEXT_MAX then genError( \"Text space exhausted.\" )\n else begin\n for cPos := 0 until sLen - 1 do begin\n text( textNext ) := str( cPos // 1 );\n textNext := textNext + 1\n end for_cPos\n end\n end if_not_found ;\n ePos\n end readString ;\n\n % gets an integer from the line - no checks for valid digits %\n integer procedure readInteger ; begin\n integer n;\n n := 0;\n while line( lPos // 1 ) not = \" \" do begin\n n := ( n * 10 ) + ( decode( line( lPos // 1 ) ) - decode( \"0\" ) );\n lPos := lPos + 1\n end while_not_end_of_integer ;\n n\n end readInteger ;\n\n string(256) line;\n string(16) name;\n integer lPos, tPos, ndType;\n tPos := lPos := 0;\n readcard( line );\n % get the node type name %\n while line( lPos // 1 ) = \" \" do lPos := lPos + 1;\n name := \"\";\n while lPos < 256 and line( lPos // 1 ) not = \" \" do begin\n name( tPos // 1 ) := line( lPos // 1 );\n lPos := lPos + 1;\n tPos := tPos + 1\n end while_more_name ;\n % determine the node type %\n ndType := 1;\n resultNode := null;\n if name not = \";\" then begin\n % not a null node %\n while ndType <= MAX_NODE_TYPE and name not = ndName( ndType ) do ndType := ndType + 1;\n if ndType > MAX_NODE_TYPE then genError( \"Malformed node.\" );\n % handle the additional parameter for identifier/string/integer, or sub-nodes for operator nodes %\n if ndType = nInteger or ndType = nIdentifier or ndType = nString then begin\n while line( lPos // 1 ) = \" \" do lPos := lPos + 1;\n if ndType = nInteger then resultNode := operandNode( ndType, readInteger )\n else if ndType = nIdentifier then resultNode := operandNode( ndType, readString( idList, \" \" ) )\n else % ndType = nString % resultNode := operandNode( ndType, readString( stList, \"\"\"\" ) )\n end\n else begin\n % operator node %\n reference(node) leftNode;\n leftNode := readNode;\n resultNode := opNode( ndType, leftNode, readNode )\n end\n end if_non_null_node ;\n resultNode\n end readNode ;\n\n % returns the next free label number %\n integer procedure newLabel ; begin\n nextLabelNumber := nextLabelNumber + 1;\n if nextLabelNumber > MAX_LABEL_NUMBER then genError( \"Program too complex\" );\n nextLabelNumber\n end newLabel ;\n\n % defines the specified label to be at the next location %\n procedure defineLabel ( integer value labelNumber ) ; begin\n if labelLocation( labelNumber ) > 0 then genError( \"Label already defined\" )\n else begin\n % this is the first definition of the label, define it and if it has already been referenced, fill in the reference %\n integer currValue;\n currValue := labelLocation( labelNumber );\n labelLocation( labelNumber ) := nextLocation + 1; % we store pc + 1 to ensure the label location is positive %\n if currValue < 0 then % already referenced % byteCode( - ( currValue + 1 ) ) := labelLocation( labelNumber )\n end\n end defineLabel ;\n\n % stores a byte in the code %\n procedure genByte ( integer value byteValue ) ; begin\n if nextLocation > MAX_LOCATION then genError( \"Program too large\" );\n byteCode( nextLocation ) := byteValue;\n nextLocation := nextLocation + 1\n end genByte ;\n\n % stores an integer in the code %\n procedure genInteger ( integer value integerValue ) ; begin\n % we are storing the bytes of the code in separate integers for convenience %\n genByte( integerValue ); genByte( 0 ); genByte( 0 ); genByte( 0 )\n end genInteger ;\n\n % generates an operation acting on an address %\n procedure genDataOp ( integer value opCode, address ) ; begin\n genByte( opCode );\n genInteger( address )\n end genDataOp ;\n\n % generates a nullary operation %\n procedure genOp0 ( integer value opCode ) ; begin\n genByte( opCode )\n end genOp0 ;\n\n % generates a unary/binary operation %\n procedure genOp ( reference(node) value n ) ; begin\n gen( left(n) );\n gen( right(n) ); % right will be null for a unary op so no code will be generated %\n genByte( nOp( type(n) ) )\n end genOp ;\n\n % generates a jump operation %\n procedure genJump ( integer value opCode, labelNumber ) ; begin\n genByte( opCode );\n % if the label is not defined yet - set it's location to the negative of the referencing location %\n % so it can be resolved later %\n if labelLocation( labelNumber ) = 0 then labelLocation( labelNumber ) := - ( nextLocation + 1 );\n genInteger( labelLocation( labelNumber ) )\n end genJump ;\n\n % generates code for the node n %\n procedure gen ( reference(node) value n ) ; begin\n\n if n = null then % empty node % begin end\n else if type(n) = nIdentifier then genDataOp( oFetch, iValue(n) )\n else if type(n) = nString then genDataOp( oPush, iValue(n) - 1 )\n else if type(n) = nInteger then genDataOp( oPush, iValue(n) )\n else if type(n) = nSequence then begin\n gen( left(n) );\n gen( right(n) )\n end\n else if type(n) = nIf then % if-else % begin\n integer elseLabel;\n elseLabel := newLabel;\n gen( left(n) );\n genJump( oJz, elseLabel );\n gen( left( right(n) ) );\n if right(right(n)) = null then % no \"else\" part % defineLabel( elseLabel )\n else begin\n % have an \"else\" part %\n integer endIfLabel;\n endIfLabel := newLabel;\n genJump( oJmp, endIfLabel );\n defineLabel( elseLabel );\n gen( right(right(n)) );\n defineLabel( endIfLabel )\n end\n end\n else if type(n) = nWhile then % while-loop % begin\n integer loopLabel, exitLabel;\n loopLabel := newLabel;\n exitLabel := newLabel;\n defineLabel( loopLabel );\n gen( left(n) );\n genJump( oJz, exitLabel );\n gen( right(n) );\n genJump( oJmp, loopLabel );\n defineLabel( exitLabel )\n end\n else if type(n) = nAssign then % assignment % begin\n gen( right( n ) );\n genDataOp( oStore, iValue(left(n)) )\n end\n else genOp( n )\n end gen ;\n\n % outputs the generated code to standard output %\n procedure emitCode ; begin\n\n % counts the number of elements in a text element list %\n integer procedure countElements ( reference(textElement) value txHead ) ; begin\n integer count;\n reference(textElement) txPos;\n count := 0;\n txPos := txHead;\n while txPos not = null do begin\n count := count + 1;\n txPos := next(txPos)\n end while_txPos_not_null ;\n count\n end countElements ;\n\n integer pc, op;\n reference(textElement) txPos;\n\n % code header %\n write( i_w := 1, s_w := 0\n , \"Datasize: \", countElements( idList )\n , \" Strings: \", countElements( stList )\n );\n % output the string literals %\n txPos := stList;\n while txPos not = null do begin\n integer cPos;\n write( \"\"\"\" );\n cPos := 1; % start from 1 to skip over the leading \" %\n while cPos < length(txPos) do begin\n writeon( s_w := 0, text( start(txPos) + cPos ) );\n cPos := cPos + 1\n end while_not_end_of_string ;\n writeon( s_w := 0, \"\"\"\" );\n txPos := next(txPos)\n end while_not_at_end_of_literals ;\n\n % code body %\n pc := 0;\n while pc < nextLocation do begin\n op := byteCode( pc );\n write( i_w := 4, s_w := 0, pc, \" \", opName( op ) );\n pc := pc + 1;\n if op = oFetch or op = oStore then begin\n % data load/store - add the address in square brackets %\n writeon( i_w := 1, s_w := 0, \"[\", byteCode( pc ) - 1, \"]\" );\n pc := pc + 4\n end\n else if op = oPush then begin\n % push constant - add the constant %\n writeon( i_w := 1, s_w := 0, byteCode( pc ) );\n pc := pc + 4\n end\n else if op = oJmp or op = oJz then begin\n % jump - show the relative address in brackets and the absolute address %\n writeon( i_w := 1, s_w := 0, \"(\", ( byteCode( pc ) - 1 ) - pc, \") \", byteCode( pc ) - 1 );\n pc := pc + 4\n end\n end while_pc_lt_nextLocation\n end emitCode ;\n\n oFetch := 1; opName( oFetch ) := \"fetch\"; oStore := 2; opName( oStore ) := \"store\"; oPush := 3; opName( oPush ) := \"push\";\n oAdd := 4; opName( oAdd ) := \"add\"; oSub := 5; opName( oSub ) := \"sub\"; oMul := 6; opName( oMul ) := \"mul\";\n oDiv := 7; opName( oDiv ) := \"div\"; oMod := 8; opName( oMod ) := \"mod\"; oLt := 9; opName( oLt ) := \"lt\";\n oGt := 10; opName( oGt ) := \"gt\"; oLe := 11; opName( oLe ) := \"le\"; oGe := 12; opName( oGe ) := \"ge\";\n oEq := 13; opName( oEq ) := \"eq\"; oNe := 14; opName( oNe ) := \"ne\"; oAnd := 15; opName( oAnd ) := \"and\";\n oOr := 16; opName( oOr ) := \"or\"; oNeg := 17; opName( oNeg ) := \"neg\"; oNot := 18; opName( oNot ) := \"not\";\n oJmp := 19; opName( oJmp ) := \"jmp\"; oJz := 20; opName( oJz ) := \"jz\"; oPrtc := 21; opName( oPrtc ) := \"prtc\";\n oPrts := 22; opName( oPrts ) := \"prts\"; oPrti := 23; opName( oPrti ) := \"prti\"; oHalt := 24; opName( oHalt ) := \"halt\";\n\n nIdentifier := 1; ndName( nIdentifier ) := \"Identifier\"; nString := 2; ndName( nString ) := \"String\";\n nInteger := 3; ndName( nInteger ) := \"Integer\"; nSequence := 4; ndName( nSequence ) := \"Sequence\";\n nIf := 5; ndName( nIf ) := \"If\"; nPrtc := 6; ndName( nPrtc ) := \"Prtc\";\n nPrts := 7; ndName( nPrts ) := \"Prts\"; nPrti := 8; ndName( nPrti ) := \"Prti\";\n nWhile := 9; ndName( nWhile ) := \"While\"; nAssign := 10; ndName( nAssign ) := \"Assign\";\n nNegate := 11; ndName( nNegate ) := \"Negate\"; nNot := 12; ndName( nNot ) := \"Not\";\n nMultiply := 13; ndName( nMultiply ) := \"Multiply\"; nDivide := 14; ndName( nDivide ) := \"Divide\";\n nMod := 15; ndName( nMod ) := \"Mod\"; nAdd := 16; ndName( nAdd ) := \"Add\";\n nSubtract := 17; ndName( nSubtract ) := \"Subtract\"; nLess := 18; ndName( nLess ) := \"Less\";\n nLessEqual := 19; ndName( nLessEqual ) := \"LessEqual\"; nGreater := 20; ndName( nGreater ) := \"Greater\";\n nGreaterEqual := 21; ndName( nGreaterEqual ) := \"GreaterEqual\"; nEqual := 22; ndName( nEqual ) := \"Equal\";\n nNotEqual := 23; ndName( nNotEqual ) := \"NotEqual\"; nAnd := 24; ndName( nAnd ) := \"And\";\n nOr := 25; ndName( nOr ) := \"Or\";\n MAX_NODE_TYPE := 25; TEXT_MAX := 4095; textNext := 0;\n stList := idList := null;\n for nPos := 1 until MAX_NODE_TYPE do nOp( nPos ) := -1;\n nOp( nPrtc ) := oPrtc; nOp( nPrts ) := oPrts; nOp( nPrti ) := oPrti; nOp( nNegate ) := oNeg; nOp( nNot ) := oNot;\n nOp( nMultiply ) := oMul; nOp( nDivide ) := oDiv; nOp( nMod ) := oMod; nOp( nAdd ) := oAdd; nOp( nSubtract ) := oSub;\n nOp( nLess ) := oLt; nOp( nLessEqual ) := oLe; nOp( nGreater ) := oGt; nOp( nGreaterEqual ) := oGe; nOp( nEqual ) := oEq;\n nOp( nNotEqual ) := oNe; nOp( nAnd ) := oAnd; nOp( nOr ) := oOr;\n nextLocation := 0; MAX_LOCATION := 4095;\n for pc := 0 until MAX_LOCATION do byteCode( pc ) := 0;\n nextLabelNumber := 0; MAX_LABEL_NUMBER := 4096;\n for lPos := 1 until MAX_LABEL_NUMBER do labelLocation( lPos ) := 0;\n\n % parse the output from the syntax analyser and generate code from the parse tree %\n gen( readNode );\n genOp0( oHalt );\n emitCode\nend.\n", "language": "ALGOL-W" }, { "code": "(* The Rosetta Code code generator in ATS2. *)\n\n(* Usage: gen [INPUTFILE [OUTPUTFILE]]\n If INPUTFILE or OUTPUTFILE is \"-\" or missing, then standard input\n or standard output is used, respectively. *)\n\n(* Note: you might wish to add code to catch exceptions and print nice\n messages. *)\n\n(*------------------------------------------------------------------*)\n\n#define ATS_DYNLOADFLAG 0\n\n#include \"share/atspre_staload.hats\"\nstaload UN = \"prelude/SATS/unsafe.sats\"\n\n#define NIL list_vt_nil ()\n#define :: list_vt_cons\n\n%{^\n/* alloca(3) is needed for ATS exceptions. */\n#include <alloca.h>\n%}\n\nexception internal_error of ()\nexception bad_ast_node_type of string\nexception premature_end_of_input of ()\nexception bad_number_field of string\nexception missing_identifier_field of ()\nexception bad_quoted_string of string\n\n(* Some implementations that are likely missing from the prelude. *)\nimplement\ng0uint2int<sizeknd, llintknd> x =\n $UN.cast x\nimplement\ng0uint2uint<sizeknd, ullintknd> x =\n $UN.cast x\nimplement\ng0uint2int<ullintknd, llintknd> x =\n $UN.cast x\n\n(*------------------------------------------------------------------*)\n\nextern fn {}\nskip_characters$skipworthy (c : char) :<> bool\n\nfn {}\nskip_characters {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n :<> [j : int | i <= j; j <= n]\n size_t j =\n let\n fun\n loop {k : int | i <= k; k <= n}\n .<n - k>.\n (k : size_t k)\n :<> [j : int | k <= j; j <= n]\n size_t j =\n if string_is_atend (s, k) then\n k\n else if ~skip_characters$skipworthy (string_get_at (s, k)) then\n k\n else\n loop (succ k)\n in\n loop i\n end\n\nfn\nskip_whitespace {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n :<> [j : int | i <= j; j <= n]\n size_t j =\n let\n implement\n skip_characters$skipworthy<> c =\n isspace c\n in\n skip_characters<> (s, i)\n end\n\nfn\nskip_nonwhitespace {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n :<> [j : int | i <= j; j <= n]\n size_t j =\n let\n implement\n skip_characters$skipworthy<> c =\n ~isspace c\n in\n skip_characters<> (s, i)\n end\n\nfn\nskip_nonquote {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n :<> [j : int | i <= j; j <= n]\n size_t j =\n let\n implement\n skip_characters$skipworthy<> c =\n c <> '\"'\n in\n skip_characters<> (s, i)\n end\n\nfn\nskip_to_end {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n :<> [j : int | i <= j; j <= n]\n size_t j =\n let\n implement\n skip_characters$skipworthy<> c =\n true\n in\n skip_characters<> (s, i)\n end\n\n(*------------------------------------------------------------------*)\n\nfn\nsubstring_equals {n : int}\n {i, j : nat | i <= j; j <= n}\n (s : string n,\n i : size_t i,\n j : size_t j,\n t : string)\n :<> bool =\n let\n val m = strlen t\n in\n if j - i <> m then\n false (* The substring is the wrong length. *)\n else\n let\n val p_s = ptrcast s\n and p_t = ptrcast t\n in\n 0 = $extfcall (int, \"strncmp\",\n ptr_add<char> (p_s, i), p_t, m)\n end\n end\n\n(*------------------------------------------------------------------*)\n\ndatatype node_type_t =\n| NullNode\n| Identifier\n| String\n| Integer\n| Sequence\n| If\n| Prtc\n| Prts\n| Prti\n| While\n| Assign\n| Negate\n| Not\n| Multiply\n| Divide\n| Mod\n| Add\n| Subtract\n| Less\n| LessEqual\n| Greater\n| GreaterEqual\n| Equal\n| NotEqual\n| And\n| Or\n\n#define ARBITRARY_NODE_ARG 1234\n\ndatatype ast_node_t =\n| ast_node_t_nil\n| ast_node_t_nonnil of node_contents_t\nwhere node_contents_t =\n @{\n node_type = node_type_t,\n node_arg = ullint,\n node_left = ast_node_t,\n node_right = ast_node_t\n }\n\nfn\nget_node_type {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n : [j : int | i <= j; j <= n]\n @(node_type_t,\n size_t j) =\n let\n val i_start = skip_whitespace (s, i)\n val i_end = skip_nonwhitespace (s, i_start)\n\n macdef eq t =\n substring_equals (s, i_start, i_end, ,(t))\n\n val node_type =\n if eq \";\" then\n NullNode\n else if eq \"Identifier\" then\n Identifier\n else if eq \"String\" then\n String\n else if eq \"Integer\" then\n Integer\n else if eq \"Sequence\" then\n Sequence\n else if eq \"If\" then\n If\n else if eq \"Prtc\" then\n Prtc\n else if eq \"Prts\" then\n Prts\n else if eq \"Prti\" then\n Prti\n else if eq \"While\" then\n While\n else if eq \"Assign\" then\n Assign\n else if eq \"Negate\" then\n Negate\n else if eq \"Not\" then\n Not\n else if eq \"Multiply\" then\n Multiply\n else if eq \"Divide\" then\n Divide\n else if eq \"Mod\" then\n Mod\n else if eq \"Add\" then\n Add\n else if eq \"Subtract\" then\n Subtract\n else if eq \"Less\" then\n Less\n else if eq \"LessEqual\" then\n LessEqual\n else if eq \"Greater\" then\n Greater\n else if eq \"GreaterEqual\" then\n GreaterEqual\n else if eq \"Equal\" then\n Equal\n else if eq \"NotEqual\" then\n NotEqual\n else if eq \"And\" then\n And\n else if eq \"Or\" then\n Or\n else\n let\n val s_bad =\n strnptr2string\n (string_make_substring (s, i_start, i_end - i_start))\n in\n $raise bad_ast_node_type s_bad\n end\n in\n @(node_type, i_end)\n end\n\nfn\nget_unsigned {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n : [j : int | i <= j; j <= n]\n @(ullint,\n size_t j) =\n let\n val i = skip_whitespace (s, i)\n val [j : int] j = skip_nonwhitespace (s, i)\n in\n if j = i then\n $raise bad_number_field \"\"\n else\n let\n fun\n loop {k : int | i <= k; k <= j}\n (k : size_t k,\n v : ullint)\n : ullint =\n if k = j then\n v\n else\n let\n val c = string_get_at (s, k)\n in\n if ~isdigit c then\n let\n val s_bad =\n strnptr2string\n (string_make_substring (s, i, j - i))\n in\n $raise bad_number_field s_bad\n end\n else\n let\n val digit = char2int1 c - char2int1 '0'\n val () = assertloc (0 <= digit)\n in\n loop (succ k, (g1i2u 10 * v) + g1i2u digit)\n end\n end\n in\n @(loop (i, g0i2u 0), j)\n end\n end\n\nfn\nget_identifier\n {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n : [j : int | i <= j; j <= n]\n @(string,\n size_t j) =\n let\n val i = skip_whitespace (s, i)\n val j = skip_nonwhitespace (s, i)\n in\n if i = j then\n $raise missing_identifier_field ()\n else\n let\n val ident =\n strnptr2string (string_make_substring (s, i, j - i))\n in\n @(ident, j)\n end\n end\n\nfn\nget_quoted_string\n {n : int}\n {i : nat | i <= n}\n (s : string n,\n i : size_t i)\n : [j : int | i <= j; j <= n]\n @(string,\n size_t j) =\n let\n val i = skip_whitespace (s, i)\n in\n if string_is_atend (s, i) then\n $raise bad_quoted_string \"\"\n else if string_get_at (s, i) <> '\"' then\n let\n val j = skip_to_end (s, i)\n val s_bad =\n strnptr2string (string_make_substring (s, i, j - i))\n in\n $raise bad_quoted_string s_bad\n end\n else\n let\n val j = skip_nonquote (s, succ i)\n in\n if string_is_atend (s, j) then\n let\n val s_bad =\n strnptr2string (string_make_substring (s, i, j - i))\n in\n $raise bad_quoted_string s_bad\n end\n else\n let\n val quoted_string =\n strnptr2string\n (string_make_substring (s, i, succ j - i))\n in\n @(quoted_string, succ j)\n end\n end\n end\n\nfn\ncollect_string\n {n : int}\n (str : string,\n strings : &list_vt (string, n) >> list_vt (string, m))\n : #[m : int | m == n || m == n + 1]\n [str_num : nat | str_num <= m]\n size_t str_num =\n (* This implementation uses ‘list_vt’ instead of ‘list’, so\n appending elements to the end of the list will be both efficient\n and safe. It would also have been reasonable to build a ‘list’\n backwards and then make a reversed copy. *)\n let\n fun\n find_or_extend\n {i : nat | i <= n}\n .<n - i>.\n (strings1 : &list_vt (string, n - i)\n >> list_vt (string, m),\n i : size_t i)\n : #[m : int | m == n - i || m == n - i + 1]\n [j : nat | j <= n]\n size_t j =\n case+ strings1 of\n | ~ NIL =>\n let (* The string is not there. Extend the list. *)\n prval () = prop_verify {i == n} ()\n in\n strings1 := (str :: NIL);\n i\n end\n | @ (head :: tail) =>\n if head = str then\n let (* The string is found. *)\n prval () = fold@ strings1\n in\n i\n end\n else\n let (* Continue looking. *)\n val j = find_or_extend (tail, succ i)\n prval () = fold@ strings1\n in\n j\n end\n\n prval () = lemma_list_vt_param strings\n val n = i2sz (length strings)\n and j = find_or_extend (strings, i2sz 0)\n in\n j\n end\n\nfn\nload_ast (inpf : FILEref,\n idents : &List_vt string >> _,\n strings : &List_vt string >> _)\n : ast_node_t =\n let\n fun\n recurs (idents : &List_vt string >> _,\n strings : &List_vt string >> _)\n : ast_node_t =\n if fileref_is_eof inpf then\n $raise premature_end_of_input ()\n else\n let\n val s = strptr2string (fileref_get_line_string inpf)\n prval () = lemma_string_param s (* String length >= 0. *)\n\n val i = i2sz 0\n val @(node_type, i) = get_node_type (s, i)\n in\n case+ node_type of\n | NullNode () => ast_node_t_nil ()\n | Integer () =>\n let\n val @(number, _) = get_unsigned (s, i)\n in\n ast_node_t_nonnil\n @{\n node_type = node_type,\n node_arg = number,\n node_left = ast_node_t_nil,\n node_right = ast_node_t_nil\n }\n end\n | Identifier () =>\n let\n val @(ident, _) = get_identifier (s, i)\n val arg = collect_string (ident, idents)\n in\n ast_node_t_nonnil\n @{\n node_type = node_type,\n node_arg = g0u2u arg,\n node_left = ast_node_t_nil,\n node_right = ast_node_t_nil\n }\n end\n | String () =>\n let\n val @(quoted_string, _) = get_quoted_string (s, i)\n val arg = collect_string (quoted_string, strings)\n in\n ast_node_t_nonnil\n @{\n node_type = node_type,\n node_arg = g0u2u arg,\n node_left = ast_node_t_nil,\n node_right = ast_node_t_nil\n }\n end\n | _ =>\n let\n val node_left = recurs (idents, strings)\n val node_right = recurs (idents, strings)\n in\n ast_node_t_nonnil\n @{\n node_type = node_type,\n node_arg = g1i2u ARBITRARY_NODE_ARG,\n node_left = node_left,\n node_right = node_right\n }\n end\n end\n in\n recurs (idents, strings)\n end\n\nfn\nprint_strings {n : int}\n (outf : FILEref,\n strings : !list_vt (string, n))\n : void =\n let\n fun\n loop {m : nat}\n .<m>.\n (strings1 : !list_vt (string, m)) :\n void =\n case+ strings1 of\n | NIL => ()\n | head :: tail =>\n begin\n fprintln! (outf, head);\n loop tail\n end\n\n prval () = lemma_list_vt_param strings\n in\n loop strings\n end\n\n(*------------------------------------------------------------------*)\n\n#define ARBITRARY_INSTRUCTION_ARG 1234\n#define ARBITRARY_JUMP_ARG 123456789\n\ntypedef instruction_t =\n @{\n address = ullint,\n opcode = string,\n arg = llint\n }\n\ntypedef code_t = ref instruction_t\n\nvtypedef pjump_t (p : addr) =\n (instruction_t @ p,\n instruction_t @ p -<lin,prf> void |\n ptr p)\nvtypedef pjump_t = [p : addr] pjump_t p\n\nfn\nadd_instruction (opcode : string,\n arg : llint,\n size : uint,\n code : &List0_vt code_t >> List1_vt code_t,\n pc : &ullint >> _)\n : void =\n let\n val instr =\n @{\n address = pc,\n opcode = opcode,\n arg = arg\n }\n in\n code := (ref instr :: code);\n pc := pc + g0u2u size\n end\n\nfn\nadd_jump (opcode : string,\n code : &List0_vt code_t >> List1_vt code_t,\n pc : &ullint >> _)\n : pjump_t =\n let\n val instr =\n @{\n address = pc,\n opcode = opcode,\n arg = g1i2i ARBITRARY_JUMP_ARG\n }\n val ref_instr = ref instr\n in\n code := (ref_instr :: code);\n pc := pc + g0u2u 5U;\n ref_vtakeout ref_instr\n end\n\nfn\nfill_jump (pjump : pjump_t,\n address : ullint)\n : void =\n let\n val @(pf, fpf | p) = pjump\n val instr0 = !p\n val jump_offset : llint =\n let\n val from = succ (instr0.address)\n and to = address\n in\n if from <= to then\n g0u2i (to - from)\n else\n ~g0u2i (from - to)\n end\n val instr1 =\n @{\n address = instr0.address,\n opcode = instr0.opcode,\n arg = jump_offset\n }\n val () = !p := instr1\n prval () = fpf pf\n in\n end\n\nfn\nadd_filled_jump (opcode : string,\n address : ullint,\n code : &List0_vt code_t >> List1_vt code_t,\n pc : &ullint >> _)\n : void =\n let\n val pjump = add_jump (opcode, code, pc)\n in\n fill_jump (pjump, address)\n end\n\nfn\ngenerate_code (ast : ast_node_t)\n : List_vt code_t =\n let\n fnx\n traverse (ast : ast_node_t,\n code : &List0_vt code_t >> _,\n pc : &ullint >> _)\n : void =\n (* Generate the code by consing a list. *)\n case+ ast of\n | ast_node_t_nil () => ()\n | ast_node_t_nonnil contents =>\n begin\n case+ contents.node_type of\n | NullNode () => $raise internal_error ()\n\n | If () => if_then (contents, code, pc)\n | While () => while_do (contents, code, pc)\n\n | Sequence () => sequence (contents, code, pc)\n | Assign () => assign (contents, code, pc)\n\n | Identifier () => immediate (\"fetch\", contents, code, pc)\n | Integer () => immediate (\"push\", contents, code, pc)\n | String () => immediate (\"push\", contents, code, pc)\n\n | Prtc () => unary_op (\"prtc\", contents, code, pc)\n | Prti () => unary_op (\"prti\", contents, code, pc)\n | Prts () => unary_op (\"prts\", contents, code, pc)\n | Negate () => unary_op (\"neg\", contents, code, pc)\n | Not () => unary_op (\"not\", contents, code, pc)\n\n | Multiply () => binary_op (\"mul\", contents, code, pc)\n | Divide () => binary_op (\"div\", contents, code, pc)\n | Mod () => binary_op (\"mod\", contents, code, pc)\n | Add () => binary_op (\"add\", contents, code, pc)\n | Subtract () => binary_op (\"sub\", contents, code, pc)\n | Less () => binary_op (\"lt\", contents, code, pc)\n | LessEqual () => binary_op (\"le\", contents, code, pc)\n | Greater () => binary_op (\"gt\", contents, code, pc)\n | GreaterEqual () => binary_op (\"ge\", contents, code, pc)\n | Equal () => binary_op (\"eq\", contents, code, pc)\n | NotEqual () => binary_op (\"ne\", contents, code, pc)\n | And () => binary_op (\"and\", contents, code, pc)\n | Or () => binary_op (\"or\", contents, code, pc)\n end\n and\n if_then (contents : node_contents_t,\n code : &List0_vt code_t >> _,\n pc : &ullint >> _)\n : void =\n case- (contents.node_right) of\n | ast_node_t_nonnil contents1 =>\n let\n val condition = (contents.node_left)\n and true_branch = (contents1.node_left)\n and false_branch = (contents1.node_right)\n\n (* Generate code to evaluate the condition. *)\n val () = traverse (condition, code, pc);\n\n (* Generate a conditional jump. Where it goes to will be\n filled in later. *)\n val pjump = add_jump (\"jz\", code, pc)\n\n (* Generate code for the true branch. *)\n val () = traverse (true_branch, code, pc);\n in\n case+ false_branch of\n | ast_node_t_nil () =>\n begin (* There is no false branch. *)\n (* Fill in the conditional jump to come here. *)\n fill_jump (pjump, pc)\n end\n | ast_node_t_nonnil _ =>\n let (* There is a false branch. *)\n (* Generate an unconditional jump. Where it goes to will\n be filled in later. *)\n val pjump1 = add_jump (\"jmp\", code, pc)\n\n (* Fill in the conditional jump to come here. *)\n val () = fill_jump (pjump, pc)\n\n (* Generate code for the false branch. *)\n val () = traverse (false_branch, code, pc);\n\n (* Fill in the unconditional jump to come here. *)\n val () = fill_jump (pjump1, pc)\n in\n end\n end\n and\n while_do (contents : node_contents_t,\n code : &List0_vt code_t >> _,\n pc : &ullint >> _)\n : void =\n (* I would prefer to implement ‘while’ by putting the\n conditional jump at the end, and jumping to it to get into\n the loop. However, we need to generate not the code of our\n choice, but the reference result. The reference result has\n the conditional jump at the top. *)\n let\n (* Where to jump from the bottom of the loop. *)\n val loop_top_address = pc\n\n (* Generate code to evaluate the condition. *)\n val () = traverse (contents.node_left, code, pc)\n\n (* Generate a conditional jump. It will be filled in later to\n go past the end of the loop. *)\n val pjump = add_jump (\"jz\", code, pc)\n\n (* Generate code for the loop body. *)\n val () = traverse (contents.node_right, code, pc)\n\n (* Generate a jump to the top of the loop. *)\n val () = add_filled_jump (\"jmp\", loop_top_address, code, pc)\n\n (* Fill in the conditional jump to come here. *)\n val () = fill_jump (pjump, pc)\n in\n end\n and\n sequence (contents : node_contents_t,\n code : &List0_vt code_t >> _,\n pc : &ullint >> _)\n : void =\n begin\n traverse (contents.node_left, code, pc);\n traverse (contents.node_right, code, pc)\n end\n and\n assign (contents : node_contents_t,\n code : &List0_vt code_t >> _,\n pc : &ullint >> _)\n : void =\n case- contents.node_left of\n | ast_node_t_nonnil ident_contents =>\n let\n val variable_no = ident_contents.node_arg\n in\n traverse (contents.node_right, code, pc);\n add_instruction (\"store\", g0u2i variable_no, 5U, code, pc)\n end\n and\n immediate (opcode : string,\n contents : node_contents_t,\n code : &List0_vt code_t >> _,\n pc : &ullint >> _)\n : void =\n add_instruction (opcode, g0u2i (contents.node_arg), 5U,\n code, pc)\n and\n unary_op (opcode : string,\n contents : node_contents_t,\n code : &List0_vt code_t >> _,\n pc : &ullint >> _)\n : void =\n begin\n traverse (contents.node_left, code, pc);\n add_instruction (opcode, g0i2i ARBITRARY_INSTRUCTION_ARG, 1U,\n code, pc)\n end\n and\n binary_op (opcode : string,\n contents : node_contents_t,\n code : &List0_vt code_t >> _,\n pc : &ullint >> _)\n : void =\n begin\n traverse (contents.node_left, code, pc);\n traverse (contents.node_right, code, pc);\n add_instruction (opcode, g0i2i ARBITRARY_INSTRUCTION_ARG, 1U,\n code, pc)\n end\n\n var code : List_vt code_t = NIL\n var pc : ullint = g0i2u 0\n in\n traverse (ast, code, pc);\n add_instruction (\"halt\", g0i2i ARBITRARY_INSTRUCTION_ARG, 1U,\n code, pc);\n\n (* The code is a cons-list, in decreasing-address order, so\n reverse it to put the instructions in increasing-address\n order. *)\n list_vt_reverse code\n end\n\nfn\nprint_code (outf : FILEref,\n code : !List_vt code_t)\n : void =\n let\n fun\n loop {n : nat}\n .<n>.\n (code : !list_vt (code_t, n))\n : void =\n case+ code of\n | NIL => ()\n | ref_instr :: tail =>\n let\n val @{\n address = address,\n opcode = opcode,\n arg = arg\n } = !ref_instr\n in\n fprint! (outf, address, \" \");\n fprint! (outf, opcode);\n if opcode = \"push\" then\n fprint! (outf, \" \", arg)\n else if opcode = \"fetch\" || opcode = \"store\" then\n fprint! (outf, \" [\", arg, \"]\")\n else if opcode = \"jmp\" || opcode = \"jz\" then\n begin\n fprint! (outf, \" (\", arg, \") \");\n if arg < g1i2i 0 then\n let\n val offset : ullint = g0i2u (~arg)\n val () = assertloc (offset <= succ address)\n in\n fprint! (outf, succ address - offset)\n end\n else\n let\n val offset : ullint = g0i2u arg\n in\n fprint! (outf, succ address + offset)\n end\n end;\n fprintln! (outf);\n loop tail\n end\n\n prval () = lemma_list_vt_param code\n in\n loop code\n end\n\n(*------------------------------------------------------------------*)\n\nfn\nmain_program (inpf : FILEref,\n outf : FILEref)\n : int =\n let\n var idents : List_vt string = NIL\n var strings : List_vt string = NIL\n\n val ast = load_ast (inpf, idents, strings)\n val code = generate_code ast\n\n val () = fprintln! (outf, \"Datasize: \", length idents,\n \" Strings: \", length strings)\n val () = print_strings (outf, strings)\n val () = print_code (outf, code)\n\n val () = free idents\n and () = free strings\n and () = free code\n in\n 0\n end\n\nimplement\nmain (argc, argv) =\n let\n val inpfname =\n if 2 <= argc then\n $UN.cast{string} argv[1]\n else\n \"-\"\n val outfname =\n if 3 <= argc then\n $UN.cast{string} argv[2]\n else\n \"-\"\n val inpf =\n if (inpfname : string) = \"-\" then\n stdin_ref\n else\n fileref_open_exn (inpfname, file_mode_r)\n\n val outf =\n if (outfname : string) = \"-\" then\n stdout_ref\n else\n fileref_open_exn (outfname, file_mode_w)\n in\n main_program (inpf, outf)\n end\n\n(*------------------------------------------------------------------*)\n", "language": "ATS" }, { "code": "function error(msg) {\n printf(\"%s\\n\", msg)\n exit(1)\n}\n\nfunction bytes_to_int(bstr, i, sum) {\n sum = 0\n for (i=word_size-1; i>=0; i--) {\n sum *= 256\n sum += code[bstr+i]\n }\n return sum\n}\n\nfunction make_node(oper, left, right, value) {\n node_type [next_free_node_index] = oper\n node_left [next_free_node_index] = left\n node_right[next_free_node_index] = right\n node_value[next_free_node_index] = value\n return next_free_node_index ++\n}\n\nfunction make_leaf(oper, n) {\n return make_node(oper, 0, 0, n)\n}\n\nfunction emit_byte(x) {\n code[next_free_code_index++] = x\n}\n\nfunction emit_word(x, i) {\n for (i=0; i<word_size; i++) {\n emit_byte(int(x)%256);\n x = int(x/256)\n }\n}\n\nfunction emit_word_at(at, n, i) {\n for (i=0; i<word_size; i++) {\n code[at+i] = int(n)%256\n n = int(n/256)\n }\n}\n\nfunction hole( t) {\n t = next_free_code_index\n emit_word(0)\n return t\n}\n\nfunction fetch_var_offset(name, n) {\n if (name in globals) {\n n = globals[name]\n } else {\n globals[name] = globals_n\n n = globals_n\n globals_n += 1\n }\n return n\n}\n\nfunction fetch_string_offset(the_string, n) {\n n = string_pool[the_string]\n if (n == \"\") {\n string_pool[the_string] = string_n\n n = string_n\n string_n += 1\n }\n return n\n}\n\nfunction code_gen(x, n, p1, p2) {\n if (x == 0) {\n return\n } else if (node_type[x] == \"nd_Ident\") {\n emit_byte(FETCH)\n n = fetch_var_offset(node_value[x])\n emit_word(n)\n } else if (node_type[x] == \"nd_Integer\") {\n emit_byte(PUSH)\n emit_word(node_value[x])\n } else if (node_type[x] == \"nd_String\") {\n emit_byte(PUSH)\n n = fetch_string_offset(node_value[x])\n emit_word(n)\n } else if (node_type[x] == \"nd_Assign\") {\n n = fetch_var_offset(node_value[node_left[x]])\n code_gen(node_right[x])\n emit_byte(STORE)\n emit_word(n)\n } else if (node_type[x] == \"nd_If\") {\n code_gen(node_left[x]) # expr\n emit_byte(JZ) # if false, jump\n p1 = hole() # make room for jump dest\n code_gen(node_left[node_right[x]]) # if true statements\n if (node_right[node_right[x]] != 0) {\n emit_byte(JMP) # jump over else statements\n p2 = hole()\n }\n emit_word_at(p1, next_free_code_index - p1)\n if (node_right[node_right[x]] != 0) {\n code_gen(node_right[node_right[x]]) # else statements\n emit_word_at(p2, next_free_code_index - p2)\n }\n } else if (node_type[x] == \"nd_While\") {\n p1 =next_free_code_index\n code_gen(node_left[x])\n emit_byte(JZ)\n p2 = hole()\n code_gen(node_right[x])\n emit_byte(JMP) # jump back to the top\n emit_word(p1 - next_free_code_index)\n emit_word_at(p2, next_free_code_index - p2)\n } else if (node_type[x] == \"nd_Sequence\") {\n code_gen(node_left[x])\n code_gen(node_right[x])\n } else if (node_type[x] == \"nd_Prtc\") {\n code_gen(node_left[x])\n emit_byte(PRTC)\n } else if (node_type[x] == \"nd_Prti\") {\n code_gen(node_left[x])\n emit_byte(PRTI)\n } else if (node_type[x] == \"nd_Prts\") {\n code_gen(node_left[x])\n emit_byte(PRTS)\n } else if (node_type[x] in operators) {\n code_gen(node_left[x])\n code_gen(node_right[x])\n emit_byte(operators[node_type[x]])\n } else if (node_type[x] in unary_operators) {\n code_gen(node_left[x])\n emit_byte(unary_operators[node_type[x]])\n } else {\n error(\"error in code generator - found '\" node_type[x] \"', expecting operator\")\n }\n}\n\nfunction code_finish() {\n emit_byte(HALT)\n}\n\nfunction list_code() {\n printf(\"Datasize: %d Strings: %d\\n\", globals_n, string_n)\n # Make sure that arrays are sorted by value in ascending order.\n PROCINFO[\"sorted_in\"] = \"@val_str_asc\"\n # This is a dependency on GAWK.\n for (k in string_pool)\n print(k)\n pc = 0\n while (pc < next_free_code_index) {\n printf(\"%4d \", pc)\n op = code[pc]\n pc += 1\n if (op == FETCH) {\n x = bytes_to_int(pc)\n printf(\"fetch [%d]\\n\", x);\n pc += word_size\n } else if (op == STORE) {\n x = bytes_to_int(pc)\n printf(\"store [%d]\\n\", x);\n pc += word_size\n } else if (op == PUSH) {\n x = bytes_to_int(pc)\n printf(\"push %d\\n\", x);\n pc += word_size\n } else if (op == ADD) { print(\"add\")\n } else if (op == SUB) { print(\"sub\")\n } else if (op == MUL) { print(\"mul\")\n } else if (op == DIV) { print(\"div\")\n } else if (op == MOD) { print(\"mod\")\n } else if (op == LT) { print(\"lt\")\n } else if (op == GT) { print(\"gt\")\n } else if (op == LE) { print(\"le\")\n } else if (op == GE) { print(\"ge\")\n } else if (op == EQ) { print(\"eq\")\n } else if (op == NE) { print(\"ne\")\n } else if (op == AND) { print(\"and\")\n } else if (op == OR) { print(\"or\")\n } else if (op == NEG) { print(\"neg\")\n } else if (op == NOT) { print(\"not\")\n } else if (op == JMP) {\n x = bytes_to_int(pc)\n printf(\"jmp (%d) %d\\n\", x, pc + x);\n pc += word_size\n } else if (op == JZ) {\n x = bytes_to_int(pc)\n printf(\"jz (%d) %d\\n\", x, pc + x);\n pc += word_size\n } else if (op == PRTC) { print(\"prtc\")\n } else if (op == PRTI) { print(\"prti\")\n } else if (op == PRTS) { print(\"prts\")\n } else if (op == HALT) { print(\"halt\")\n } else { error(\"list_code: Unknown opcode '\" op \"'\")\n }\n } # while pc\n}\n\nfunction load_ast( line, line_list, text, n, node_type, value, left, right) {\n getline line\n n=split(line, line_list)\n text = line_list[1]\n if (text == \";\")\n return 0\n node_type = all_syms[text]\n if (n > 1) {\n value = line_list[2]\n for (i=3;i<=n;i++)\n value = value \" \" line_list[i]\n if (value ~ /^[0-9]+$/)\n value = int(value)\n return make_leaf(node_type, value)\n }\n left = load_ast()\n right = load_ast()\n return make_node(node_type, left, right)\n}\n\nBEGIN {\n all_syms[\"Identifier\" ] = \"nd_Ident\"\n all_syms[\"String\" ] = \"nd_String\"\n all_syms[\"Integer\" ] = \"nd_Integer\"\n all_syms[\"Sequence\" ] = \"nd_Sequence\"\n all_syms[\"If\" ] = \"nd_If\"\n all_syms[\"Prtc\" ] = \"nd_Prtc\"\n all_syms[\"Prts\" ] = \"nd_Prts\"\n all_syms[\"Prti\" ] = \"nd_Prti\"\n all_syms[\"While\" ] = \"nd_While\"\n all_syms[\"Assign\" ] = \"nd_Assign\"\n all_syms[\"Negate\" ] = \"nd_Negate\"\n all_syms[\"Not\" ] = \"nd_Not\"\n all_syms[\"Multiply\" ] = \"nd_Mul\"\n all_syms[\"Divide\" ] = \"nd_Div\"\n all_syms[\"Mod\" ] = \"nd_Mod\"\n all_syms[\"Add\" ] = \"nd_Add\"\n all_syms[\"Subtract\" ] = \"nd_Sub\"\n all_syms[\"Less\" ] = \"nd_Lss\"\n all_syms[\"LessEqual\" ] = \"nd_Leq\"\n all_syms[\"Greater\" ] = \"nd_Gtr\"\n all_syms[\"GreaterEqual\"] = \"nd_Geq\"\n all_syms[\"Equal\" ] = \"nd_Eql\"\n all_syms[\"NotEqual\" ] = \"nd_Neq\"\n all_syms[\"And\" ] = \"nd_And\"\n all_syms[\"Or\" ] = \"nd_Or\"\n\n FETCH=1; STORE=2; PUSH=3; ADD=4; SUB=5; MUL=6;\n DIV=7; MOD=8; LT=9; GT=10; LE=11; GE=12;\n EQ=13; NE=14; AND=15; OR=16; NEG=17; NOT=18;\n JMP=19; JZ=20; PRTC=21; PRTS=22; PRTI=23; HALT=24;\n\n operators[\"nd_Lss\"] = LT\n operators[\"nd_Gtr\"] = GT\n operators[\"nd_Leq\"] = LE\n operators[\"nd_Geq\"] = GE\n operators[\"nd_Eql\"] = EQ\n operators[\"nd_Neq\"] = NE\n operators[\"nd_And\"] = AND\n operators[\"nd_Or\" ] = OR\n operators[\"nd_Sub\"] = SUB\n operators[\"nd_Add\"] = ADD\n operators[\"nd_Div\"] = DIV\n operators[\"nd_Mul\"] = MUL\n operators[\"nd_Mod\"] = MOD\n\n unary_operators[\"nd_Negate\"] = NEG\n unary_operators[\"nd_Not\" ] = NOT\n\n next_free_node_index = 1\n next_free_code_index = 0\n globals_n = 0\n string_n = 0\n word_size = 4\n input_file = \"-\"\n\n if (ARGC > 1)\n input_file = ARGV[1]\n n = load_ast()\n code_gen(n)\n code_finish()\n list_code()\n}\n", "language": "AWK" }, { "code": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdarg.h>\n#include <stdint.h>\n#include <ctype.h>\n\ntypedef unsigned char uchar;\n\ntypedef enum {\n nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While,\n nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq,\n nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or\n} NodeType;\n\ntypedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND,\n OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT\n} Code_t;\n\ntypedef uchar code;\n\ntypedef struct Tree {\n NodeType node_type;\n struct Tree *left;\n struct Tree *right;\n char *value;\n} Tree;\n\n#define da_dim(name, type) type *name = NULL; \\\n int _qy_ ## name ## _p = 0; \\\n int _qy_ ## name ## _max = 0\n\n#define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n\n#define da_rewind(name) _qy_ ## name ## _p = 0\n\n#define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n#define da_len(name) _qy_ ## name ## _p\n#define da_add(name) do {da_redim(name); _qy_ ## name ## _p++;} while (0)\n\nFILE *source_fp, *dest_fp;\nstatic int here;\nda_dim(object, code);\nda_dim(globals, const char *);\nda_dim(string_pool, const char *);\n\n// dependency: Ordered by NodeType, must remain in same order as NodeType enum\nstruct {\n char *enum_text;\n NodeType node_type;\n Code_t opcode;\n} atr[] = {\n {\"Identifier\" , nd_Ident, -1 },\n {\"String\" , nd_String, -1 },\n {\"Integer\" , nd_Integer, -1 },\n {\"Sequence\" , nd_Sequence, -1 },\n {\"If\" , nd_If, -1 },\n {\"Prtc\" , nd_Prtc, -1 },\n {\"Prts\" , nd_Prts, -1 },\n {\"Prti\" , nd_Prti, -1 },\n {\"While\" , nd_While, -1 },\n {\"Assign\" , nd_Assign, -1 },\n {\"Negate\" , nd_Negate, NEG},\n {\"Not\" , nd_Not, NOT},\n {\"Multiply\" , nd_Mul, MUL},\n {\"Divide\" , nd_Div, DIV},\n {\"Mod\" , nd_Mod, MOD},\n {\"Add\" , nd_Add, ADD},\n {\"Subtract\" , nd_Sub, SUB},\n {\"Less\" , nd_Lss, LT },\n {\"LessEqual\" , nd_Leq, LE },\n {\"Greater\" , nd_Gtr, GT },\n {\"GreaterEqual\", nd_Geq, GE },\n {\"Equal\" , nd_Eql, EQ },\n {\"NotEqual\" , nd_Neq, NE },\n {\"And\" , nd_And, AND},\n {\"Or\" , nd_Or, OR },\n};\n\nvoid error(const char *fmt, ... ) {\n va_list ap;\n char buf[1000];\n\n va_start(ap, fmt);\n vsprintf(buf, fmt, ap);\n va_end(ap);\n printf(\"error: %s\\n\", buf);\n exit(1);\n}\n\nCode_t type_to_op(NodeType type) {\n return atr[type].opcode;\n}\n\nTree *make_node(NodeType node_type, Tree *left, Tree *right) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->left = left;\n t->right = right;\n return t;\n}\n\nTree *make_leaf(NodeType node_type, char *value) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->value = strdup(value);\n return t;\n}\n\n/*** Code generator ***/\n\nvoid emit_byte(int c) {\n da_append(object, (uchar)c);\n ++here;\n}\n\nvoid emit_int(int32_t n) {\n union {\n int32_t n;\n unsigned char c[sizeof(int32_t)];\n } x;\n\n x.n = n;\n\n for (size_t i = 0; i < sizeof(x.n); ++i) {\n emit_byte(x.c[i]);\n }\n}\n\nint hole() {\n int t = here;\n emit_int(0);\n return t;\n}\n\nvoid fix(int src, int dst) {\n *(int32_t *)(object + src) = dst-src;\n}\n\nint fetch_var_offset(const char *id) {\n for (int i = 0; i < da_len(globals); ++i) {\n if (strcmp(id, globals[i]) == 0)\n return i;\n }\n da_add(globals);\n int n = da_len(globals) - 1;\n globals[n] = strdup(id);\n return n;\n}\n\nint fetch_string_offset(const char *st) {\n for (int i = 0; i < da_len(string_pool); ++i) {\n if (strcmp(st, string_pool[i]) == 0)\n return i;\n }\n da_add(string_pool);\n int n = da_len(string_pool) - 1;\n string_pool[n] = strdup(st);\n return n;\n}\n\nvoid code_gen(Tree *x) {\n int p1, p2, n;\n\n if (x == NULL) return;\n switch (x->node_type) {\n case nd_Ident:\n emit_byte(FETCH);\n n = fetch_var_offset(x->value);\n emit_int(n);\n break;\n case nd_Integer:\n emit_byte(PUSH);\n emit_int(atoi(x->value));\n break;\n case nd_String:\n emit_byte(PUSH);\n n = fetch_string_offset(x->value);\n emit_int(n);\n break;\n case nd_Assign:\n n = fetch_var_offset(x->left->value);\n code_gen(x->right);\n emit_byte(STORE);\n emit_int(n);\n break;\n case nd_If:\n code_gen(x->left); // if expr\n emit_byte(JZ); // if false, jump\n p1 = hole(); // make room for jump dest\n code_gen(x->right->left); // if true statements\n if (x->right->right != NULL) {\n emit_byte(JMP);\n p2 = hole();\n }\n fix(p1, here);\n if (x->right->right != NULL) {\n code_gen(x->right->right);\n fix(p2, here);\n }\n break;\n case nd_While:\n p1 = here;\n code_gen(x->left); // while expr\n emit_byte(JZ); // if false, jump\n p2 = hole(); // make room for jump dest\n code_gen(x->right); // statements\n emit_byte(JMP); // back to the top\n fix(hole(), p1); // plug the top\n fix(p2, here); // plug the 'if false, jump'\n break;\n case nd_Sequence:\n code_gen(x->left);\n code_gen(x->right);\n break;\n case nd_Prtc:\n code_gen(x->left);\n emit_byte(PRTC);\n break;\n case nd_Prti:\n code_gen(x->left);\n emit_byte(PRTI);\n break;\n case nd_Prts:\n code_gen(x->left);\n emit_byte(PRTS);\n break;\n case nd_Lss: case nd_Gtr: case nd_Leq: case nd_Geq: case nd_Eql: case nd_Neq:\n case nd_And: case nd_Or: case nd_Sub: case nd_Add: case nd_Div: case nd_Mul:\n case nd_Mod:\n code_gen(x->left);\n code_gen(x->right);\n emit_byte(type_to_op(x->node_type));\n break;\n case nd_Negate: case nd_Not:\n code_gen(x->left);\n emit_byte(type_to_op(x->node_type));\n break;\n default:\n error(\"error in code generator - found %d, expecting operator\\n\", x->node_type);\n }\n}\n\nvoid code_finish() {\n emit_byte(HALT);\n}\n\nvoid list_code() {\n fprintf(dest_fp, \"Datasize: %d Strings: %d\\n\", da_len(globals), da_len(string_pool));\n for (int i = 0; i < da_len(string_pool); ++i)\n fprintf(dest_fp, \"%s\\n\", string_pool[i]);\n\n code *pc = object;\n\n again: fprintf(dest_fp, \"%5d \", (int)(pc - object));\n switch (*pc++) {\n case FETCH: fprintf(dest_fp, \"fetch [%d]\\n\", *(int32_t *)pc);\n pc += sizeof(int32_t); goto again;\n case STORE: fprintf(dest_fp, \"store [%d]\\n\", *(int32_t *)pc);\n pc += sizeof(int32_t); goto again;\n case PUSH : fprintf(dest_fp, \"push %d\\n\", *(int32_t *)pc);\n pc += sizeof(int32_t); goto again;\n case ADD : fprintf(dest_fp, \"add\\n\"); goto again;\n case SUB : fprintf(dest_fp, \"sub\\n\"); goto again;\n case MUL : fprintf(dest_fp, \"mul\\n\"); goto again;\n case DIV : fprintf(dest_fp, \"div\\n\"); goto again;\n case MOD : fprintf(dest_fp, \"mod\\n\"); goto again;\n case LT : fprintf(dest_fp, \"lt\\n\"); goto again;\n case GT : fprintf(dest_fp, \"gt\\n\"); goto again;\n case LE : fprintf(dest_fp, \"le\\n\"); goto again;\n case GE : fprintf(dest_fp, \"ge\\n\"); goto again;\n case EQ : fprintf(dest_fp, \"eq\\n\"); goto again;\n case NE : fprintf(dest_fp, \"ne\\n\"); goto again;\n case AND : fprintf(dest_fp, \"and\\n\"); goto again;\n case OR : fprintf(dest_fp, \"or\\n\"); goto again;\n case NOT : fprintf(dest_fp, \"not\\n\"); goto again;\n case NEG : fprintf(dest_fp, \"neg\\n\"); goto again;\n case JMP : fprintf(dest_fp, \"jmp (%d) %d\\n\",\n *(int32_t *)pc, (int32_t)(pc + *(int32_t *)pc - object));\n pc += sizeof(int32_t); goto again;\n case JZ : fprintf(dest_fp, \"jz (%d) %d\\n\",\n *(int32_t *)pc, (int32_t)(pc + *(int32_t *)pc - object));\n pc += sizeof(int32_t); goto again;\n case PRTC : fprintf(dest_fp, \"prtc\\n\"); goto again;\n case PRTI : fprintf(dest_fp, \"prti\\n\"); goto again;\n case PRTS : fprintf(dest_fp, \"prts\\n\"); goto again;\n case HALT : fprintf(dest_fp, \"halt\\n\"); break;\n default:error(\"listcode:Unknown opcode %d\\n\", *(pc - 1));\n }\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n if (fn[0] == '\\0')\n *fp = std;\n else if ((*fp = fopen(fn, mode)) == NULL)\n error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nNodeType get_enum_value(const char name[]) {\n for (size_t i = 0; i < sizeof(atr) / sizeof(atr[0]); i++) {\n if (strcmp(atr[i].enum_text, name) == 0) {\n return atr[i].node_type;\n }\n }\n error(\"Unknown token %s\\n\", name);\n return -1;\n}\n\nchar *read_line(int *len) {\n static char *text = NULL;\n static int textmax = 0;\n\n for (*len = 0; ; (*len)++) {\n int ch = fgetc(source_fp);\n if (ch == EOF || ch == '\\n') {\n if (*len == 0)\n return NULL;\n break;\n }\n if (*len + 1 >= textmax) {\n textmax = (textmax == 0 ? 128 : textmax * 2);\n text = realloc(text, textmax);\n }\n text[*len] = ch;\n }\n text[*len] = '\\0';\n return text;\n}\n\nchar *rtrim(char *text, int *len) { // remove trailing spaces\n for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n ;\n\n text[*len] = '\\0';\n return text;\n}\n\nTree *load_ast() {\n int len;\n char *yytext = read_line(&len);\n yytext = rtrim(yytext, &len);\n\n // get first token\n char *tok = strtok(yytext, \" \");\n\n if (tok[0] == ';') {\n return NULL;\n }\n NodeType node_type = get_enum_value(tok);\n\n // if there is extra data, get it\n char *p = tok + strlen(tok);\n if (p != &yytext[len]) {\n for (++p; isspace(*p); ++p)\n ;\n return make_leaf(node_type, p);\n }\n\n Tree *left = load_ast();\n Tree *right = load_ast();\n return make_node(node_type, left, right);\n}\n\nint main(int argc, char *argv[]) {\n init_io(&source_fp, stdin, \"r\", argc > 1 ? argv[1] : \"\");\n init_io(&dest_fp, stdout, \"wb\", argc > 2 ? argv[2] : \"\");\n\n code_gen(load_ast());\n code_finish();\n list_code();\n\n return 0;\n}\n", "language": "C" }, { "code": " >>SOURCE FORMAT IS FREE\nidentification division.\n*> this code is dedicated to the public domain\n*> (GnuCOBOL) 2.3-dev.0\nprogram-id. generator.\nenvironment division.\nconfiguration section.\nrepository. function all intrinsic.\ndata division.\nworking-storage section.\n01 program-name pic x(32) value spaces global.\n01 input-name pic x(32) value spaces global.\n01 input-status pic xx global.\n\n01 ast-record global.\n 03 ast-type pic x(14).\n 03 ast-value pic x(48).\n 03 filler redefines ast-value.\n 05 asl-left pic 999.\n 05 asl-right pic 999.\n\n01 error-record pic x(64) value spaces global.\n\n01 loadstack global.\n 03 l pic 99 value 0.\n 03 l-lim pic 99 value 64.\n 03 load-entry occurs 64.\n 05 l-node pic x(14).\n 05 l-left pic 999.\n 05 l-right pic 999.\n 05 l-link pic 999.\n\n01 abstract-syntax-tree global.\n 03 t pic 999 value 0.\n 03 t1 pic 999.\n 03 t-lim pic 999 value 998.\n 03 filler occurs 998.\n 05 p1 pic 999.\n 05 p2 pic 999.\n 05 p3 pic 999.\n 05 n1 pic 999.\n 05 leaf.\n 07 leaf-type pic x(14).\n 07 leaf-value pic x(48).\n 05 node redefines leaf.\n 07 node-type pic x(14).\n 07 node-left pic 999.\n 07 node-right pic 999.\n\n01 opcodes global.\n 03 opFETCH pic x value x'00'.\n 03 opSTORE pic x value x'01'.\n 03 opPUSH pic x value x'02'.\n 03 opADD pic x value x'03'.\n 03 opSUB pic x value x'04'.\n 03 opMUL pic x value x'05'.\n 03 opDIV pic x value x'06'.\n 03 opMOD pic x value x'07'.\n 03 opLT pic x value x'08'.\n 03 opGT pic x value x'09'.\n 03 opLE pic x value x'0A'.\n 03 opGE pic x value x'0B'.\n 03 opEQ pic x value x'0C'.\n 03 opNE pic x value x'0D'.\n 03 opAND pic x value x'0E'.\n 03 opOR pic x value x'0F'.\n 03 opNEG pic x value x'10'.\n 03 opNOT pic x value x'11'.\n 03 opJMP pic x value x'13'.\n 03 opJZ pic x value x'14'.\n 03 opPRTC pic x value x'15'.\n 03 opPRTS pic x value x'16'.\n 03 opPRTI pic x value x'17'.\n 03 opHALT pic x value x'18'.\n\n01 variables global.\n 03 v pic 99.\n 03 v-max pic 99 value 0.\n 03 v-lim pic 99 value 16.\n 03 variable-entry occurs 16 pic x(48).\n\n01 strings global.\n 03 s pic 99.\n 03 s-max pic 99 value 0.\n 03 s-lim pic 99 value 16.\n 03 string-entry occurs 16 pic x(48).\n\n01 generated-code global.\n 03 c pic 999 value 1.\n 03 c1 pic 999.\n 03 c-lim pic 999 value 512.\n 03 kode pic x(512).\n\nprocedure division chaining program-name.\nstart-generator.\n call 'loadast'\n if program-name <> spaces\n call 'readinput' *> close input-file\n end-if\n >>d perform print-ast\n call 'codegen' using t\n call 'emitbyte' using opHALT\n >>d call 'showhex' using kode c\n call 'listcode'\n stop run\n .\nprint-ast.\n call 'printast' using t\n display 'ast:' upon syserr\n display 't=' t\n perform varying t1 from 1 by 1 until t1 > t\n if leaf-type(t1) = 'Identifier' or 'Integer' or 'String'\n display t1 space trim(leaf-type(t1)) space trim(leaf-value(t1)) upon syserr\n else\n display t1 space node-left(t1) space node-right(t1) space trim(node-type(t1))\n upon syserr\n end-if\n end-perform\n .\nidentification division.\nprogram-id. codegen common recursive.\ndata division.\nworking-storage section.\n01 r pic ---9.\nlinkage section.\n01 n pic 999.\nprocedure division using n.\nstart-codegen.\n if n = 0\n exit program\n end-if\n >>d display 'at 'c ' node=' space n space node-type(n) upon syserr\n evaluate node-type(n)\n when 'Identifier'\n call 'emitbyte' using opFetch\n call 'variableoffset' using leaf-value(n)\n call 'emitword' using v '0'\n when 'Integer'\n call 'emitbyte' using opPUSH\n call 'emitword' using leaf-value(n) '0'\n when 'String'\n call 'emitbyte' using opPUSH\n call 'stringoffset' using leaf-value(n)\n call 'emitword' using s '0'\n when 'Assign'\n call 'codegen' using node-right(n)\n call 'emitbyte' using opSTORE\n move node-left(n) to n1(n)\n call 'variableoffset' using leaf-value(n1(n))\n call 'emitword' using v '0'\n when 'If'\n call 'codegen' using node-left(n) *> conditional expr\n call 'emitbyte' using opJZ *> jump to false path or exit\n move c to p1(n)\n call 'emitword' using '0' '0'\n move node-right(n) to n1(n) *> true path\n call 'codegen' using node-left(n1(n))\n if node-right(n1(n)) <> 0 *> there is a false path\n call 'emitbyte' using opJMP *> jump past false path\n move c to p2(n)\n call 'emitword' using '0' '0'\n compute r = c - p1(n) *> fill in jump to false path\n call 'emitword' using r p1(n)\n call 'codegen' using node-right(n1(n)) *> false path\n compute r = c - p2(n) *> fill in jump to exit\n call 'emitword' using r p2(n)\n else\n compute r = c - p1(n)\n call 'emitword' using r p1(n) *> fill in jump to exit\n end-if\n when 'While'\n move c to p3(n) *> save address of while start\n call 'codegen' using node-left(n) *> conditional expr\n call 'emitbyte' using opJZ *> jump to exit\n move c to p2(n)\n call 'emitword' using '0' '0'\n call 'codegen' using node-right(n) *> while body\n call 'emitbyte' using opJMP *> jump to while start\n compute r = p3(n) - c\n call 'emitword' using r '0'\n compute r = c - p2(n) *> fill in jump to exit\n call 'emitword' using r p2(n)\n when 'Sequence'\n call 'codegen' using node-left(n)\n call 'codegen' using node-right(n)\n when 'Prtc'\n call 'codegen' using node-left(n)\n call 'emitbyte' using opPRTC\n when 'Prti'\n call 'codegen' using node-left(n)\n call 'emitbyte' using opPRTI\n when 'Prts'\n call 'codegen' using node-left(n)\n call 'emitbyte' using opPRTS\n when 'Less'\n call 'codegen' using node-left(n)\n call 'codegen' using node-right(n)\n call 'emitbyte' using opLT\n when 'Greater'\n call 'codegen' using node-left(n)\n call 'codegen' using node-right(n)\n call 'emitbyte' using opGT\n when 'LessEqual'\n call 'codegen' using node-left(n)\n call 'codegen' using node-right(n)\n call 'emitbyte' using opLE\n when 'GreaterEqual'\n call 'codegen' using node-left(n)\n call 'codegen' using node-right(n)\n call 'emitbyte' using opGE\n when 'Equal'\n call 'codegen' using node-left(n)\n call 'codegen' using node-right(n)\n call 'emitbyte' using opEQ\n when 'NotEqual'\n call 'codegen' using node-left(n)\n call 'codegen' using node-right(n)\n call 'emitbyte' using opNE\n when 'And'\n call 'codegen' using node-left(n)\n call 'codegen' using node-right(n)\n call 'emitbyte' using opAND\n when 'Or'\n call 'codegen' using node-left(n)\n call 'codegen' using node-right(n)\n call 'emitbyte' using opOR\n when 'Subtract'\n call 'codegen' using node-left(n)\n call 'codegen' using node-right(n)\n call 'emitbyte' using opSUB\n when 'Add'\n call 'codegen' using node-left(n)\n call 'codegen' using node-right(n)\n call 'emitbyte' using opADD\n when 'Divide'\n call 'codegen' using node-left(n)\n call 'codegen' using node-right(n)\n call 'emitbyte' using opDIV\n when 'Multiply'\n call 'codegen' using node-left(n)\n call 'codegen' using node-right(n)\n call 'emitbyte' using opMUL\n when 'Mod'\n call 'codegen' using node-left(n)\n call 'codegen' using node-right(n)\n call 'emitbyte' using opMOD\n when 'Negate'\n call 'codegen' using node-left(n)\n call 'emitbyte' using opNEG\n when 'Not'\n call 'codegen' using node-left(n)\n call 'emitbyte' using opNOT\n when other\n string 'in generator unknown node type: ' node-type(n) into error-record\n call 'reporterror'\n end-evaluate\n .\nend program codegen.\n\nidentification division.\nprogram-id. variableoffset common.\ndata division.\nlinkage section.\n01 variable-value pic x(48).\nprocedure division using variable-value.\nstart-variableoffset.\n perform varying v from 1 by 1\n until v > v-max\n or variable-entry(v) = variable-value\n continue\n end-perform\n if v > v-lim\n string 'in generator variable offset v exceeds ' v-lim into error-record\n call 'reporterror'\n end-if\n if v > v-max\n move v to v-max\n move variable-value to variable-entry(v)\n end-if\n .\nend program variableoffset.\n\nidentification division.\nprogram-id. stringoffset common.\ndata division.\nlinkage section.\n01 string-value pic x(48).\nprocedure division using string-value.\nstart-stringoffset.\n perform varying s from 1 by 1\n until s > s-max\n or string-entry(s) = string-value\n continue\n end-perform\n if s > s-lim\n string ' generator stringoffset s exceeds ' s-lim into error-record\n call 'reporterror'\n end-if\n if s > s-max\n move s to s-max\n move string-value to string-entry(s)\n end-if\n subtract 1 from s *> convert index to offset\n .\nend program stringoffset.\n\nidentification division.\nprogram-id. emitbyte common.\ndata division.\nlinkage section.\n01 opcode pic x.\nprocedure division using opcode.\nstart-emitbyte.\n if c >= c-lim\n string 'in generator emitbyte c exceeds ' c-lim into error-record\n call 'reporterror'\n end-if\n move opcode to kode(c:1)\n add 1 to c\n .\nend program emitbyte.\n\nidentification division.\nprogram-id. emitword common.\ndata division.\nworking-storage section.\n01 word-x.\n 03 word usage binary-int.\n01 loc pic 999.\nlinkage section.\n01 word-value any length.\n01 loc-value any length.\nprocedure division using word-value loc-value.\nstart-emitword.\n if c + length(word) > c-lim\n string 'in generator emitword exceeds ' c-lim into error-record\n call 'reporterror'\n end-if\n move numval(word-value) to word\n move numval(loc-value) to loc\n if loc = 0\n move word-x to kode(c:length(word))\n add length(word) to c\n else\n move word-x to kode(loc:length(word))\n end-if\n .\nend program emitword.\n\nidentification division.\nprogram-id. listcode common.\ndata division.\nworking-storage section.\n01 word-x.\n 03 word usage binary-int.\n01 address-display pic ---9.\n01 address-absolute pic zzz9.\n01 data-display pic -(9)9.\n01 v-display pic z9.\n01 s-display pic z9.\n01 c-display pic zzz9.\nprocedure division.\nstart-listcode.\n move v-max to v-display\n move s-max to s-display\n display 'Datasize: ' trim(v-display) space 'Strings: ' trim(s-display)\n\n perform varying s from 1 by 1\n until s > s-max\n display string-entry(s)\n end-perform\n\n move 1 to c1\n perform until c1 >= c\n compute c-display = c1 - 1\n display c-display space with no advancing\n evaluate kode(c1:1)\n when opFETCH\n add 1 to c1\n move kode(c1:4) to word-x\n compute address-display = word - 1\n display 'fetch [' trim(address-display) ']'\n add 3 to c1\n when opSTORE\n add 1 to c1\n move kode(c1:4) to word-x\n compute address-display = word - 1\n display 'store [' trim(address-display) ']'\n add 3 to c1\n when opPUSH\n add 1 to c1\n move kode(c1:4) to word-x\n move word to data-display\n display 'push ' trim(data-display)\n add 3 to c1\n when opADD display 'add'\n when opSUB display 'sub'\n when opMUL display 'mul'\n when opDIV display 'div'\n when opMOD display 'mod'\n when opLT display 'lt'\n when opGT display 'gt'\n when opLE display 'le'\n when opGE display 'ge'\n when opEQ display 'eq'\n when opNE display 'ne'\n when opAND display 'and'\n when opOR display 'or'\n when opNEG display 'neg'\n when opNOT display 'not'\n when opJMP\n move kode(c1 + 1:length(word)) to word-x\n move word to address-display\n compute address-absolute = c1 + word\n display 'jmp (' trim(address-display) ') ' trim(address-absolute)\n add length(word) to c1\n when opJZ\n move kode(c1 + 1:length(word)) to word-x\n move word to address-display\n compute address-absolute = c1 + word\n display 'jz (' trim(address-display) ') ' trim(address-absolute)\n add length(word) to c1\n when opPRTC display 'prtc'\n when opPRTI display 'prti'\n when opPRTS display 'prts'\n when opHALT display 'halt'\n when other\n string 'in generator unknown opcode ' kode(c1:1) into error-record\n call 'reporterror'\n end-evaluate\n add 1 to c1\n end-perform\n .\nend program listcode.\n\nidentification division.\nprogram-id. loadast common recursive.\nprocedure division.\nstart-loadast.\n if l >= l-lim\n string 'in generator loadast l exceeds ' l-lim into error-record\n call 'reporterror'\n end-if\n add 1 to l\n call 'readinput'\n evaluate true\n when ast-record = ';'\n when input-status = '10'\n move 0 to return-code\n when ast-type = 'Identifier'\n when ast-type = 'Integer'\n when ast-type = 'String'\n call 'makeleaf' using ast-type ast-value\n move t to return-code\n when ast-type = 'Sequence'\n move ast-type to l-node(l)\n call 'loadast'\n move return-code to l-left(l)\n call 'loadast'\n move t to l-right(l)\n call 'makenode' using l-node(l) l-left(l) l-right(l)\n move t to return-code\n when other\n move ast-type to l-node(l)\n call 'loadast'\n move return-code to l-left(l)\n call 'loadast'\n move return-code to l-right(l)\n call 'makenode' using l-node(l) l-left(l) l-right(l)\n move t to return-code\n end-evaluate\n subtract 1 from l\n .\nend program loadast.\n\nidentification division.\nprogram-id. printast common recursive.\ndata division.\nlinkage section.\n01 n pic 999.\nprocedure division using n.\nstart-printast.\n if n = 0\n display ';' upon syserr\n exit program\n end-if\n display leaf-type(n) upon syserr\n evaluate leaf-type(n)\n when 'Identifier'\n when 'Integer'\n when 'String'\n display leaf-type(n) space trim(leaf-value(n)) upon syserr\n when other\n display node-type(n) upon syserr\n call 'printast' using node-left(n)\n call 'printast' using node-right(n)\n end-evaluate\n .\nend program printast.\n\nidentification division.\nprogram-id. makenode common.\ndata division.\nlinkage section.\n01 parm-type any length.\n01 parm-l-left pic 999.\n01 parm-l-right pic 999.\nprocedure division using parm-type parm-l-left parm-l-right.\nstart-makenode.\n if t >= t-lim\n string 'in generator makenode t exceeds ' t-lim into error-record\n call 'reporterror'\n end-if\n add 1 to t\n move parm-type to node-type(t)\n move parm-l-left to node-left(t)\n move parm-l-right to node-right(t)\n .\nend program makenode.\n\nidentification division.\nprogram-id. makeleaf common.\ndata division.\nlinkage section.\n01 parm-type any length.\n01 parm-value pic x(48).\nprocedure division using parm-type parm-value.\nstart-makeleaf.\n add 1 to t\n if t >= t-lim\n string 'in generator makeleaf t exceeds ' t-lim into error-record\n call 'reporterror'\n end-if\n move parm-type to leaf-type(t)\n move parm-value to leaf-value(t)\n .\nend program makeleaf.\n\nidentification division.\nprogram-id. readinput common.\nenvironment division.\ninput-output section.\nfile-control.\n select input-file assign using input-name\n status is input-status\n organization is line sequential.\ndata division.\nfile section.\nfd input-file.\n01 input-record pic x(64).\nprocedure division.\nstart-readinput.\n if program-name = spaces\n move '00' to input-status\n accept ast-record on exception move '10' to input-status end-accept\n exit program\n end-if\n if input-name = spaces\n string program-name delimited by space '.ast' into input-name\n open input input-file\n if input-status = '35'\n string 'in generator ' trim(input-name) ' not found' into error-record\n call 'reporterror'\n end-if\n end-if\n read input-file into ast-record\n evaluate input-status\n when '00'\n continue\n when '10'\n close input-file\n when other\n string 'in generator ' trim(input-name) ' unexpected input-status: ' input-status\n into error-record\n call 'reporterror'\n end-evaluate\n .\nend program readinput.\n\nprogram-id. reporterror common.\nprocedure division.\nstart-reporterror.\nreport-error.\n display error-record upon syserr\n stop run with error status -1\n .\nend program reporterror.\n\nidentification division.\nprogram-id. showhex common.\n\ndata division.\nworking-storage section.\n01 hex.\n 03 filler pic x(32) value '000102030405060708090A0B0C0D0E0F'.\n 03 filler pic x(32) value '101112131415161718191A1B1C1D1E1F'.\n 03 filler pic x(32) value '202122232425262728292A2B2C2D2E2F'.\n 03 filler pic x(32) value '303132333435363738393A3B3C3D3E3F'.\n 03 filler pic x(32) value '404142434445464748494A4B4C4D4E4F'.\n 03 filler pic x(32) value '505152535455565758595A5B5C5D5E5F'.\n 03 filler pic x(32) value '606162636465666768696A6B6C6D6E6F'.\n 03 filler pic x(32) value '707172737475767778797A7B7C7D7E7F'.\n 03 filler pic x(32) value '808182838485868788898A8B8C8D8E8F'.\n 03 filler pic x(32) value '909192939495969798999A9B9C9D9E9F'.\n 03 filler pic x(32) value 'A0A1A2A3A4A5A6A7A8A9AAABACADAEAF'.\n 03 filler pic x(32) value 'B0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF'.\n 03 filler pic x(32) value 'C0C1C2C3C4C5C6C7C8C9CACBCCCDCECF'.\n 03 filler pic x(32) value 'D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF'.\n 03 filler pic x(32) value 'E0E1E2E3E4E5E6E7E8E9EAEBECEDEEEF'.\n 03 filler pic x(32) value 'F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF'.\n\n01 cdx pic 9999.\n01 bdx pic 999.\n01 byte-count pic 9.\n01 bytes-per-word pic 9 value 4.\n01 word-count pic 9.\n01 words-per-line pic 9 value 8.\n\nlinkage section.\n01 data-field any length.\n01 length-data-field pic 999.\n\nprocedure division using\n by reference data-field\n by reference length-data-field.\nstart-showhex.\n move 1 to byte-count\n move 1 to word-count\n perform varying cdx from 1 by 1\n until cdx > length-data-field\n compute bdx = 2 * ord(data-field(cdx:1)) - 1 end-compute\n display hex(bdx:2) with no advancing upon syserr\n add 1 to byte-count end-add\n if byte-count > bytes-per-word\n display ' ' with no advancing upon syserr\n move 1 to byte-count\n add 1 to word-count end-add\n end-if\n if word-count > words-per-line\n display ' ' upon syserr\n move 1 to word-count\n end-if\n end-perform\n if word-count <> 1\n or byte-count <> 1\n display ' ' upon syserr\n end-if\n display ' ' upon syserr\n goback\n .\nend program showhex.\nend program generator.\n", "language": "COBOL" }, { "code": "CREATE BUF 0 ,\n: PEEK BUF @ 0= IF KEY BUF ! THEN BUF @ ;\n: GETC PEEK 0 BUF ! ;\n: SPACE? DUP BL = SWAP 9 14 WITHIN OR ;\n: >SPACE BEGIN PEEK SPACE? WHILE GETC DROP REPEAT ;\n: DIGIT? 48 58 WITHIN ;\n: >Integer >SPACE 0\n BEGIN PEEK DIGIT?\n WHILE GETC [CHAR] 0 - SWAP 10 * + REPEAT ;\n: SKIP ( xt --)\n BEGIN PEEK OVER EXECUTE WHILE GETC DROP REPEAT DROP ;\n: WORD ( xt -- c-addr) DUP >R SKIP PAD 1+\n BEGIN PEEK R@ EXECUTE INVERT\n WHILE GETC OVER C! CHAR+\n REPEAT R> SKIP PAD TUCK - 1- PAD C! ;\n: INTERN ( c-addr -- c-addr)\n HERE TUCK OVER C@ CHAR+ DUP ALLOT CMOVE ;\n: \"? [CHAR] \" = ;\n: \"TYPE\" [CHAR] \" EMIT TYPE [CHAR] \" EMIT ;\n: . 0 .R ;\n: 3@ ( addr -- w3 w2 w1)\n [ 2 CELLS ]L + DUP @ SWAP CELL - DUP @ SWAP CELL - @ ;\n\nCREATE BUF' 12 ALLOT\n: PREPEND ( c-addr c -- c-addr) BUF' 1+ C!\n COUNT 10 MIN DUP 1+ BUF' C! BUF' 2 + SWAP CMOVE BUF' ;\n: >NODE ( c-addr -- n) [CHAR] $ PREPEND FIND\n IF EXECUTE ELSE .\" unrecognized node \" COUNT TYPE CR THEN ;\n: NODE ( n left right -- addr) HERE >R , , , R> ;\n\n: CONS ( a b l -- l) HERE >R , , , R> ;\n: FIRST ( l -- a) [ 2 CELLS ]L + @ ;\n: SECOND ( l -- b) CELL+ @ ;\n: C=? ( c-addr1 c-addr2 -- t|f) COUNT ROT COUNT COMPARE 0= ;\n: LOOKUP ( c-addr l -- n t | c-addr f)\n BEGIN DUP WHILE OVER OVER FIRST C=?\n IF NIP SECOND TRUE EXIT THEN @\n REPEAT DROP FALSE ;\n\nCREATE GLOBALS 0 , CREATE STRINGS 0 ,\n: DEPTH ( pool -- n) DUP IF SECOND 1+ THEN ;\n: FISH ( c-addr pool -- n pool') TUCK LOOKUP IF SWAP\n ELSE INTERN OVER DEPTH ROT OVER >R CONS R> SWAP THEN ;\n: >Identifier ['] SPACE? WORD GLOBALS @ FISH GLOBALS ! ;\n: >String ['] \"? WORD STRINGS @ FISH STRINGS ! ;\n: >; 0 ;\n: HANDLER [CHAR] @ PREPEND FIND DROP ;\n: READER ( c-addr -- xt t | f)\n [CHAR] > PREPEND FIND DUP 0= IF NIP THEN ;\nDEFER GETAST\n: READ ( c-addr -- right left) READER\n IF EXECUTE 0 ELSE GETAST GETAST THEN SWAP ;\n: (GETAST) ['] SPACE? WORD DUP HANDLER >R READ R> NODE ;\n' (GETAST) IS GETAST\n\nCREATE PC 0 ,\n: i32! ( n addr --)\n OVER $FF AND OVER C! 1+\n OVER 8 RSHIFT $FF AND OVER C! 1+\n OVER 16 RSHIFT $FF AND OVER C! 1+\n OVER 24 RSHIFT $FF AND OVER C! DROP DROP ;\n: i32, ( n --) HERE i32! 4 ALLOT 4 PC +! ;\n: i8, ( c --) C, 1 PC +! ;\n: i8@+ DUP 1+ SWAP C@ 1 PC +! ;\n: i32@+ ( addr -- addr+4 n)\n i8@+ >R i8@+ 8 LSHIFT R> OR >R\n i8@+ 16 LSHIFT R> OR >R i8@+ 24 LSHIFT R> OR ;\n\nCREATE #OPS 0 ,\n: OP: CREATE #OPS @ , 1 #OPS +! DOES> @ ;\nOP: fetch OP: store OP: push OP: jmp OP: jz\nOP: prtc OP: prti OP: prts OP: neg OP: not\nOP: add OP: sub OP: mul OP: div OP: mod\nOP: lt OP: gt OP: le OP: ge\nOP: eq OP: ne OP: and OP: or OP: halt\n\n: GEN ( ast --) 3@ EXECUTE ;\n: @; ( r l) DROP DROP ;\n: @Identifier fetch i8, i32, DROP ;\n: @Integer push i8, i32, DROP ;\n: @String push i8, i32, DROP ;\n: @Prtc GEN prtc i8, DROP ;\n: @Prti GEN prti i8, DROP ;\n: @Prts GEN prts i8, DROP ;\n: @Not GEN not i8, DROP ;\n: @Negate GEN neg i8, DROP ;\n: @Sequence GEN GEN ;\n: @Assign CELL+ @ >R GEN store i8, R> i32, ;\n: @While PC @ SWAP GEN jz i8, HERE >R 0 i32,\n SWAP GEN jmp i8, i32, PC @ R> i32! ;\n: @If GEN jz i8, HERE >R 0 i32,\n CELL+ DUP CELL+ @ DUP @ ['] @; = IF DROP @\n ELSE SWAP @ GEN jmp i8, HERE 0 i32, PC @ R> i32! >R\n THEN GEN PC @ R> i32! ;\n: BINARY >R GEN GEN R> i8, ;\n: @Subtract sub BINARY ; : @Add add BINARY ;\n: @Mod mod BINARY ; : @Multiply mul BINARY ;\n: @Divide div BINARY ;\n: @Less lt BINARY ; : @LessEqual le BINARY ;\n: @Greater gt BINARY ; : @GreaterEqual ge BINARY ;\n: @Equal eq BINARY ; : @NotEqual ne BINARY ;\n: @And and BINARY ; : @Or or BINARY ;\n\n: REVERSE ( l -- l') 0 SWAP\n BEGIN DUP WHILE TUCK DUP @ ROT ROT ! REPEAT DROP ;\n: .STRINGS STRINGS @ REVERSE BEGIN DUP\n WHILE DUP FIRST COUNT \"TYPE\" CR @ REPEAT DROP ;\n: .HEADER ( --)\n .\" Datasize: \" GLOBALS @ DEPTH . SPACE\n .\" Strings: \" STRINGS @ DEPTH . CR .STRINGS ;\n: GENERATE ( ast -- addr u)\n 0 PC ! HERE >R GEN halt i8, R> PC @ ;\n: ,\" [CHAR] \" PARSE TUCK HERE SWAP CMOVE ALLOT ;\nCREATE \"OPS\"\n,\" fetch store push jmp jz prtc prti prts \"\n,\" neg not add sub mul div mod lt \"\n,\" gt le ge eq ne and or halt \"\n: .i32 i32@+ . ;\n: .[i32] [CHAR] [ EMIT .i32 [CHAR] ] EMIT ;\n: .off [CHAR] ( EMIT PC @ >R i32@+ DUP R> - . [CHAR] ) EMIT\n SPACE . ;\nCREATE .INT ' .[i32] , ' .[i32] , ' .i32 , ' .off , ' .off ,\n: EMIT ( addr u --) >R 0 PC !\n BEGIN PC @ R@ <\n WHILE PC @ 5 .R SPACE i8@+\n DUP 6 * \"OPS\" + 6 TYPE\n DUP 5 < IF CELLS .INT + @ EXECUTE ELSE DROP THEN CR\n REPEAT DROP R> DROP ;\nGENERATE EMIT BYE\n", "language": "Forth" }, { "code": "module compiler_type_kinds\n use, intrinsic :: iso_fortran_env, only: int32\n use, intrinsic :: iso_fortran_env, only: int64\n\n implicit none\n private\n\n ! Synonyms.\n integer, parameter, public :: size_kind = int64\n integer, parameter, public :: length_kind = size_kind\n integer, parameter, public :: nk = size_kind\n\n ! Synonyms for character capable of storing a Unicode code point.\n integer, parameter, public :: unicode_char_kind = selected_char_kind ('ISO_10646')\n integer, parameter, public :: ck = unicode_char_kind\n\n ! Synonyms for integers capable of storing a Unicode code point.\n integer, parameter, public :: unicode_ichar_kind = int32\n integer, parameter, public :: ick = unicode_ichar_kind\n\n ! Synonyms for integers in the virtual machine or the interpreter’s\n ! runtime. (The Rosetta Code task says integers in the virtual\n ! machine are 32-bit, but there is nothing in the task that prevents\n ! us using 64-bit integers in the compiler and interpreter.)\n integer, parameter, public :: runtime_int_kind = int64\n integer, parameter, public :: rik = runtime_int_kind\nend module compiler_type_kinds\n\nmodule helper_procedures\n use, non_intrinsic :: compiler_type_kinds, only: nk, rik, ck\n\n implicit none\n private\n\n public :: new_storage_size\n public :: next_power_of_two\n\n public :: isspace\n public :: quoted_string\n\n public :: int32_to_vm_bytes\n public :: uint32_to_vm_bytes\n public :: int32_from_vm_bytes\n public :: uint32_from_vm_bytes\n\n character(1, kind = ck), parameter :: horizontal_tab_char = char (9, kind = ck)\n character(1, kind = ck), parameter :: linefeed_char = char (10, kind = ck)\n character(1, kind = ck), parameter :: vertical_tab_char = char (11, kind = ck)\n character(1, kind = ck), parameter :: formfeed_char = char (12, kind = ck)\n character(1, kind = ck), parameter :: carriage_return_char = char (13, kind = ck)\n character(1, kind = ck), parameter :: space_char = ck_' '\n\n ! The following is correct for Unix and its relatives.\n character(1, kind = ck), parameter :: newline_char = linefeed_char\n\n character(1, kind = ck), parameter :: backslash_char = char (92, kind = ck)\n\ncontains\n\n elemental function new_storage_size (length_needed) result (size)\n integer(kind = nk), intent(in) :: length_needed\n integer(kind = nk) :: size\n\n ! Increase storage by orders of magnitude.\n\n if (2_nk**32 < length_needed) then\n size = huge (1_nk)\n else\n size = next_power_of_two (length_needed)\n end if\n end function new_storage_size\n\n elemental function next_power_of_two (x) result (y)\n integer(kind = nk), intent(in) :: x\n integer(kind = nk) :: y\n\n !\n ! It is assumed that no more than 64 bits are used.\n !\n ! The branch-free algorithm is that of\n ! https://archive.is/nKxAc#RoundUpPowerOf2\n !\n ! Fill in bits until one less than the desired power of two is\n ! reached, and then add one.\n !\n\n y = x - 1\n y = ior (y, ishft (y, -1))\n y = ior (y, ishft (y, -2))\n y = ior (y, ishft (y, -4))\n y = ior (y, ishft (y, -8))\n y = ior (y, ishft (y, -16))\n y = ior (y, ishft (y, -32))\n y = y + 1\n end function next_power_of_two\n\n elemental function isspace (ch) result (bool)\n character(1, kind = ck), intent(in) :: ch\n logical :: bool\n\n bool = (ch == horizontal_tab_char) .or. &\n & (ch == linefeed_char) .or. &\n & (ch == vertical_tab_char) .or. &\n & (ch == formfeed_char) .or. &\n & (ch == carriage_return_char) .or. &\n & (ch == space_char)\n end function isspace\n\n function quoted_string (str) result (qstr)\n character(*, kind = ck), intent(in) :: str\n character(:, kind = ck), allocatable :: qstr\n\n integer(kind = nk) :: n, i, j\n\n ! Compute n = the size of qstr.\n n = 2_nk\n do i = 1_nk, len (str, kind = nk)\n select case (str(i:i))\n case (newline_char, backslash_char)\n n = n + 2\n case default\n n = n + 1\n end select\n end do\n\n allocate (character(n, kind = ck) :: qstr)\n\n ! Quote the string.\n qstr(1:1) = ck_'\"'\n j = 2_nk\n do i = 1_nk, len (str, kind = nk)\n select case (str(i:i))\n case (newline_char)\n qstr(j:j) = backslash_char\n qstr((j + 1):(j + 1)) = ck_'n'\n j = j + 2\n case (backslash_char)\n qstr(j:j) = backslash_char\n qstr((j + 1):(j + 1)) = backslash_char\n j = j + 2\n case default\n qstr(j:j) = str(i:i)\n j = j + 1\n end select\n end do\n if (j /= n) error stop ! Check code correctness.\n qstr(n:n) = ck_'\"'\n end function quoted_string\n\n subroutine int32_to_vm_bytes (n, bytes, i)\n integer(kind = rik), intent(in) :: n\n character(1), intent(inout) :: bytes(0:*)\n integer(kind = rik), intent(in) :: i\n\n !\n ! The virtual machine is presumed to be little-endian. Because I\n ! slightly prefer little-endian.\n !\n\n bytes(i) = achar (ibits (n, 0, 8))\n bytes(i + 1) = achar (ibits (n, 8, 8))\n bytes(i + 2) = achar (ibits (n, 16, 8))\n bytes(i + 3) = achar (ibits (n, 24, 8))\n end subroutine int32_to_vm_bytes\n\n subroutine uint32_to_vm_bytes (n, bytes, i)\n integer(kind = rik), intent(in) :: n\n character(1), intent(inout) :: bytes(0:*)\n integer(kind = rik), intent(in) :: i\n\n call int32_to_vm_bytes (n, bytes, i)\n end subroutine uint32_to_vm_bytes\n\n subroutine int32_from_vm_bytes (n, bytes, i)\n integer(kind = rik), intent(out) :: n\n character(1), intent(in) :: bytes(0:*)\n integer(kind = rik), intent(in) :: i\n\n !\n ! The virtual machine is presumed to be little-endian. Because I\n ! slightly prefer little-endian.\n !\n\n call uint32_from_vm_bytes (n, bytes, i)\n if (ibits (n, 31, 1) == 1) then\n ! Extend the sign bit.\n n = ior (n, not ((2_rik ** 32) - 1))\n end if\n end subroutine int32_from_vm_bytes\n\n subroutine uint32_from_vm_bytes (n, bytes, i)\n integer(kind = rik), intent(out) :: n\n character(1), intent(in) :: bytes(0:*)\n integer(kind = rik), intent(in) :: i\n\n !\n ! The virtual machine is presumed to be little-endian. Because I\n ! slightly prefer little-endian.\n !\n\n integer(kind = rik) :: n0, n1, n2, n3\n\n n0 = iachar (bytes(i), kind = rik)\n n1 = ishft (iachar (bytes(i + 1), kind = rik), 8)\n n2 = ishft (iachar (bytes(i + 2), kind = rik), 16)\n n3 = ishft (iachar (bytes(i + 3), kind = rik), 24)\n n = ior (n0, ior (n1, ior (n2, n3)))\n end subroutine uint32_from_vm_bytes\n\nend module helper_procedures\n\nmodule string_buffers\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, intrinsic :: iso_fortran_env, only: int64\n use, non_intrinsic :: compiler_type_kinds, only: nk, ck, ick\n use, non_intrinsic :: helper_procedures\n\n implicit none\n private\n\n public :: strbuf_t\n public :: skip_whitespace\n public :: skip_non_whitespace\n public :: skip_whitespace_backwards\n public :: at_end_of_line\n\n type :: strbuf_t\n integer(kind = nk), private :: len = 0\n !\n ! ‘chars’ is made public for efficient access to the individual\n ! characters.\n !\n character(1, kind = ck), allocatable, public :: chars(:)\n contains\n procedure, pass, private :: ensure_storage => strbuf_t_ensure_storage\n procedure, pass :: to_unicode_full_string => strbuf_t_to_unicode_full_string\n procedure, pass :: to_unicode_substring => strbuf_t_to_unicode_substring\n procedure, pass :: length => strbuf_t_length\n procedure, pass :: set => strbuf_t_set\n procedure, pass :: append => strbuf_t_append\n generic :: to_unicode => to_unicode_full_string\n generic :: to_unicode => to_unicode_substring\n generic :: assignment(=) => set\n end type strbuf_t\n\ncontains\n\n function strbuf_t_to_unicode_full_string (strbuf) result (s)\n class(strbuf_t), intent(in) :: strbuf\n character(:, kind = ck), allocatable :: s\n\n !\n ! This does not actually ensure that the string is valid Unicode;\n ! any 31-bit ‘character’ is supported.\n !\n\n integer(kind = nk) :: i\n\n allocate (character(len = strbuf%len, kind = ck) :: s)\n do i = 1, strbuf%len\n s(i:i) = strbuf%chars(i)\n end do\n end function strbuf_t_to_unicode_full_string\n\n function strbuf_t_to_unicode_substring (strbuf, i, j) result (s)\n !\n ! ‘Extreme’ values of i and j are allowed, as shortcuts for ‘from\n ! the beginning’, ‘up to the end’, or ‘empty substring’.\n !\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i, j\n character(:, kind = ck), allocatable :: s\n\n !\n ! This does not actually ensure that the string is valid Unicode;\n ! any 31-bit ‘character’ is supported.\n !\n\n integer(kind = nk) :: i1, j1\n integer(kind = nk) :: n\n integer(kind = nk) :: k\n\n i1 = max (1_nk, i)\n j1 = min (strbuf%len, j)\n n = max (0_nk, (j1 - i1) + 1_nk)\n\n allocate (character(n, kind = ck) :: s)\n do k = 1, n\n s(k:k) = strbuf%chars(i1 + (k - 1_nk))\n end do\n end function strbuf_t_to_unicode_substring\n\n elemental function strbuf_t_length (strbuf) result (n)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk) :: n\n\n n = strbuf%len\n end function strbuf_t_length\n\n subroutine strbuf_t_ensure_storage (strbuf, length_needed)\n class(strbuf_t), intent(inout) :: strbuf\n integer(kind = nk), intent(in) :: length_needed\n\n integer(kind = nk) :: len_needed\n integer(kind = nk) :: new_size\n type(strbuf_t) :: new_strbuf\n\n len_needed = max (length_needed, 1_nk)\n\n if (.not. allocated (strbuf%chars)) then\n ! Initialize a new strbuf%chars array.\n new_size = new_storage_size (len_needed)\n allocate (strbuf%chars(1:new_size))\n else if (ubound (strbuf%chars, 1) < len_needed) then\n ! Allocate a new strbuf%chars array, larger than the current\n ! one, but containing the same characters.\n new_size = new_storage_size (len_needed)\n allocate (new_strbuf%chars(1:new_size))\n new_strbuf%chars(1:strbuf%len) = strbuf%chars(1:strbuf%len)\n call move_alloc (new_strbuf%chars, strbuf%chars)\n end if\n end subroutine strbuf_t_ensure_storage\n\n subroutine strbuf_t_set (dst, src)\n class(strbuf_t), intent(inout) :: dst\n class(*), intent(in) :: src\n\n integer(kind = nk) :: n\n integer(kind = nk) :: i\n\n select type (src)\n type is (character(*, kind = ck))\n n = len (src, kind = nk)\n call dst%ensure_storage(n)\n do i = 1, n\n dst%chars(i) = src(i:i)\n end do\n dst%len = n\n type is (character(*))\n n = len (src, kind = nk)\n call dst%ensure_storage(n)\n do i = 1, n\n dst%chars(i) = src(i:i)\n end do\n dst%len = n\n class is (strbuf_t)\n n = src%len\n call dst%ensure_storage(n)\n dst%chars(1:n) = src%chars(1:n)\n dst%len = n\n class default\n error stop\n end select\n end subroutine strbuf_t_set\n\n subroutine strbuf_t_append (dst, src)\n class(strbuf_t), intent(inout) :: dst\n class(*), intent(in) :: src\n\n integer(kind = nk) :: n_dst, n_src, n\n integer(kind = nk) :: i\n\n select type (src)\n type is (character(*, kind = ck))\n n_dst = dst%len\n n_src = len (src, kind = nk)\n n = n_dst + n_src\n call dst%ensure_storage(n)\n do i = 1, n_src\n dst%chars(n_dst + i) = src(i:i)\n end do\n dst%len = n\n type is (character(*))\n n_dst = dst%len\n n_src = len (src, kind = nk)\n n = n_dst + n_src\n call dst%ensure_storage(n)\n do i = 1, n_src\n dst%chars(n_dst + i) = src(i:i)\n end do\n dst%len = n\n class is (strbuf_t)\n n_dst = dst%len\n n_src = src%len\n n = n_dst + n_src\n call dst%ensure_storage(n)\n dst%chars((n_dst + 1):n) = src%chars(1:n_src)\n dst%len = n\n class default\n error stop\n end select\n end subroutine strbuf_t_append\n\n function skip_whitespace (strbuf, i) result (j)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n integer(kind = nk) :: j\n\n logical :: done\n\n j = i\n done = .false.\n do while (.not. done)\n if (at_end_of_line (strbuf, j)) then\n done = .true.\n else if (.not. isspace (strbuf%chars(j))) then\n done = .true.\n else\n j = j + 1\n end if\n end do\n end function skip_whitespace\n\n function skip_non_whitespace (strbuf, i) result (j)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n integer(kind = nk) :: j\n\n logical :: done\n\n j = i\n done = .false.\n do while (.not. done)\n if (at_end_of_line (strbuf, j)) then\n done = .true.\n else if (isspace (strbuf%chars(j))) then\n done = .true.\n else\n j = j + 1\n end if\n end do\n end function skip_non_whitespace\n\n function skip_whitespace_backwards (strbuf, i) result (j)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n integer(kind = nk) :: j\n\n logical :: done\n\n j = i\n done = .false.\n do while (.not. done)\n if (j == -1) then\n done = .true.\n else if (.not. isspace (strbuf%chars(j))) then\n done = .true.\n else\n j = j - 1\n end if\n end do\n end function skip_whitespace_backwards\n\n function at_end_of_line (strbuf, i) result (bool)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n logical :: bool\n\n bool = (strbuf%length() < i)\n end function at_end_of_line\n\nend module string_buffers\n\nmodule reading_one_line_from_a_stream\n use, intrinsic :: iso_fortran_env, only: input_unit\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, non_intrinsic :: compiler_type_kinds, only: nk, ck, ick\n use, non_intrinsic :: string_buffers\n\n implicit none\n private\n\n ! get_line_from_stream: read an entire input line from a stream into\n ! a strbuf_t.\n public :: get_line_from_stream\n\n character(1, kind = ck), parameter :: linefeed_char = char (10, kind = ck)\n\n ! The following is correct for Unix and its relatives.\n character(1, kind = ck), parameter :: newline_char = linefeed_char\n\ncontains\n\n subroutine get_line_from_stream (unit_no, eof, no_newline, strbuf)\n integer, intent(in) :: unit_no\n logical, intent(out) :: eof ! End of file?\n logical, intent(out) :: no_newline ! There is a line but it has no\n ! newline? (Thus eof also must\n ! be .true.)\n class(strbuf_t), intent(inout) :: strbuf\n\n character(1, kind = ck) :: ch\n\n strbuf = ''\n call get_ch (unit_no, eof, ch)\n do while (.not. eof .and. ch /= newline_char)\n call strbuf%append (ch)\n call get_ch (unit_no, eof, ch)\n end do\n no_newline = eof .and. (strbuf%length() /= 0)\n end subroutine get_line_from_stream\n\n subroutine get_ch (unit_no, eof, ch)\n !\n ! Read a single code point from the stream.\n !\n ! Currently this procedure simply inputs ‘ASCII’ bytes rather than\n ! Unicode code points.\n !\n integer, intent(in) :: unit_no\n logical, intent(out) :: eof\n character(1, kind = ck), intent(out) :: ch\n\n integer :: stat\n character(1) :: c = '*'\n\n eof = .false.\n\n if (unit_no == input_unit) then\n call get_input_unit_char (c, stat)\n else\n read (unit = unit_no, iostat = stat) c\n end if\n\n if (stat < 0) then\n ch = ck_'*'\n eof = .true.\n else if (0 < stat) then\n write (error_unit, '(\"Input error with status code \", I0)') stat\n stop 1\n else\n ch = char (ichar (c, kind = ick), kind = ck)\n end if\n end subroutine get_ch\n\n!!!\n!!! If you tell gfortran you want -std=f2008 or -std=f2018, you likely\n!!! will need to add also -fall-intrinsics or -U__GFORTRAN__\n!!!\n!!! The first way, you get the FGETC intrinsic. The latter way, you\n!!! get the C interface code that uses getchar(3).\n!!!\n#ifdef __GFORTRAN__\n\n subroutine get_input_unit_char (c, stat)\n !\n ! The following works if you are using gfortran.\n !\n ! (FGETC is considered a feature for backwards compatibility with\n ! g77. However, I know of no way to reconfigure input_unit as a\n ! Fortran 2003 stream, for use with ordinary ‘read’.)\n !\n character, intent(inout) :: c\n integer, intent(out) :: stat\n\n call fgetc (input_unit, c, stat)\n end subroutine get_input_unit_char\n\n#else\n\n subroutine get_input_unit_char (c, stat)\n !\n ! An alternative implementation of get_input_unit_char. This\n ! actually reads input from the C standard input, which might not\n ! be the same as input_unit.\n !\n use, intrinsic :: iso_c_binding, only: c_int\n character, intent(inout) :: c\n integer, intent(out) :: stat\n\n interface\n !\n ! Use getchar(3) to read characters from standard input. This\n ! assumes there is actually such a function available, and that\n ! getchar(3) does not exist solely as a macro. (One could write\n ! one’s own getchar() if necessary, of course.)\n !\n function getchar () result (c) bind (c, name = 'getchar')\n use, intrinsic :: iso_c_binding, only: c_int\n integer(kind = c_int) :: c\n end function getchar\n end interface\n\n integer(kind = c_int) :: i_char\n\n i_char = getchar ()\n !\n ! The C standard requires that EOF have a negative value. If the\n ! value returned by getchar(3) is not EOF, then it will be\n ! representable as an unsigned char. Therefore, to check for end\n ! of file, one need only test whether i_char is negative.\n !\n if (i_char < 0) then\n stat = -1\n else\n stat = 0\n c = char (i_char)\n end if\n end subroutine get_input_unit_char\n\n#endif\n\nend module reading_one_line_from_a_stream\n\nmodule ast_reader\n\n !\n ! The AST will be read into an array. Perhaps that will improve\n ! locality, compared to storing the AST as many linked heap nodes.\n !\n ! In any case, implementing the AST this way is an interesting\n ! problem.\n !\n\n use, intrinsic :: iso_fortran_env, only: input_unit\n use, intrinsic :: iso_fortran_env, only: output_unit\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, non_intrinsic :: compiler_type_kinds, only: nk, ck, ick, rik\n use, non_intrinsic :: helper_procedures, only: next_power_of_two\n use, non_intrinsic :: helper_procedures, only: new_storage_size\n use, non_intrinsic :: string_buffers\n use, non_intrinsic :: reading_one_line_from_a_stream\n\n implicit none\n private\n\n public :: string_table_t\n public :: ast_node_t\n public :: ast_t\n public :: read_ast\n\n integer, parameter, public :: node_Nil = 0\n integer, parameter, public :: node_Identifier = 1\n integer, parameter, public :: node_String = 2\n integer, parameter, public :: node_Integer = 3\n integer, parameter, public :: node_Sequence = 4\n integer, parameter, public :: node_If = 5\n integer, parameter, public :: node_Prtc = 6\n integer, parameter, public :: node_Prts = 7\n integer, parameter, public :: node_Prti = 8\n integer, parameter, public :: node_While = 9\n integer, parameter, public :: node_Assign = 10\n integer, parameter, public :: node_Negate = 11\n integer, parameter, public :: node_Not = 12\n integer, parameter, public :: node_Multiply = 13\n integer, parameter, public :: node_Divide = 14\n integer, parameter, public :: node_Mod = 15\n integer, parameter, public :: node_Add = 16\n integer, parameter, public :: node_Subtract = 17\n integer, parameter, public :: node_Less = 18\n integer, parameter, public :: node_LessEqual = 19\n integer, parameter, public :: node_Greater = 20\n integer, parameter, public :: node_GreaterEqual = 21\n integer, parameter, public :: node_Equal = 22\n integer, parameter, public :: node_NotEqual = 23\n integer, parameter, public :: node_And = 24\n integer, parameter, public :: node_Or = 25\n\n type :: string_table_element_t\n character(:, kind = ck), allocatable :: str\n end type string_table_element_t\n\n type :: string_table_t\n integer(kind = nk), private :: len = 0_nk\n type(string_table_element_t), allocatable, private :: strings(:)\n contains\n procedure, pass, private :: ensure_storage => string_table_t_ensure_storage\n procedure, pass :: look_up_index => string_table_t_look_up_index\n procedure, pass :: look_up_string => string_table_t_look_up_string\n procedure, pass :: length => string_table_t_length\n generic :: look_up => look_up_index\n generic :: look_up => look_up_string\n end type string_table_t\n\n type :: ast_node_t\n integer :: node_variety\n\n ! Runtime integer, symbol index, or string index.\n integer(kind = rik) :: int\n\n ! The left branch begins at the next node. The right branch\n ! begins at the address of the left branch, plus the following.\n integer(kind = nk) :: right_branch_offset\n end type ast_node_t\n\n type :: ast_t\n integer(kind = nk), private :: len = 0_nk\n type(ast_node_t), allocatable, public :: nodes(:)\n contains\n procedure, pass, private :: ensure_storage => ast_t_ensure_storage\n end type ast_t\n\ncontains\n\n subroutine string_table_t_ensure_storage (table, length_needed)\n class(string_table_t), intent(inout) :: table\n integer(kind = nk), intent(in) :: length_needed\n\n integer(kind = nk) :: len_needed\n integer(kind = nk) :: new_size\n type(string_table_t) :: new_table\n\n len_needed = max (length_needed, 1_nk)\n\n if (.not. allocated (table%strings)) then\n ! Initialize a new table%strings array.\n new_size = new_storage_size (len_needed)\n allocate (table%strings(1:new_size))\n else if (ubound (table%strings, 1) < len_needed) then\n ! Allocate a new table%strings array, larger than the current\n ! one, but containing the same strings.\n new_size = new_storage_size (len_needed)\n allocate (new_table%strings(1:new_size))\n new_table%strings(1:table%len) = table%strings(1:table%len)\n call move_alloc (new_table%strings, table%strings)\n end if\n end subroutine string_table_t_ensure_storage\n\n elemental function string_table_t_length (table) result (len)\n class(string_table_t), intent(in) :: table\n integer(kind = nk) :: len\n\n len = table%len\n end function string_table_t_length\n\n function string_table_t_look_up_index (table, str) result (index)\n class(string_table_t), intent(inout) :: table\n character(*, kind = ck), intent(in) :: str\n integer(kind = rik) :: index\n\n !\n ! This implementation simply stores the strings sequentially into\n ! an array. Obviously, for large numbers of strings, one might\n ! wish to do something more complex.\n !\n ! Standard Fortran does not come, out of the box, with a massive\n ! runtime library for doing such things. They are, however, no\n ! longer nearly as challenging to implement in Fortran as they\n ! used to be.\n !\n\n integer(kind = nk) :: i\n\n i = 1\n index = 0\n do while (index == 0)\n if (i == table%len + 1) then\n ! The string is new and must be added to the table.\n i = table%len + 1\n if (huge (1_rik) < i) then\n ! String indices are assumed to be storable as runtime\n ! integers.\n write (error_unit, '(\"string_table_t capacity exceeded\")')\n stop 1\n end if\n call table%ensure_storage(i)\n table%len = i\n allocate (table%strings(i)%str, source = str)\n index = int (i, kind = rik)\n else if (table%strings(i)%str == str) then\n index = int (i, kind = rik)\n else\n i = i + 1\n end if\n end do\n end function string_table_t_look_up_index\n\n function string_table_t_look_up_string (table, index) result (str)\n class(string_table_t), intent(inout) :: table\n integer(kind = rik), intent(in) :: index\n character(:, kind = ck), allocatable :: str\n\n !\n ! This is the reverse of string_table_t_look_up_index: given an\n ! index, find the string.\n !\n\n if (index < 1 .or. table%len < index) then\n ! In correct code, this branch should never be reached.\n error stop\n else\n allocate (str, source = table%strings(index)%str)\n end if\n end function string_table_t_look_up_string\n\n subroutine ast_t_ensure_storage (ast, length_needed)\n class(ast_t), intent(inout) :: ast\n integer(kind = nk), intent(in) :: length_needed\n\n integer(kind = nk) :: len_needed\n integer(kind = nk) :: new_size\n type(ast_t) :: new_ast\n\n len_needed = max (length_needed, 1_nk)\n\n if (.not. allocated (ast%nodes)) then\n ! Initialize a new ast%nodes array.\n new_size = new_storage_size (len_needed)\n allocate (ast%nodes(1:new_size))\n else if (ubound (ast%nodes, 1) < len_needed) then\n ! Allocate a new ast%nodes array, larger than the current one,\n ! but containing the same nodes.\n new_size = new_storage_size (len_needed)\n allocate (new_ast%nodes(1:new_size))\n new_ast%nodes(1:ast%len) = ast%nodes(1:ast%len)\n call move_alloc (new_ast%nodes, ast%nodes)\n end if\n end subroutine ast_t_ensure_storage\n\n subroutine read_ast (unit_no, strbuf, ast, symtab, strtab)\n integer, intent(in) :: unit_no\n type(strbuf_t), intent(inout) :: strbuf\n type(ast_t), intent(inout) :: ast\n type(string_table_t), intent(inout) :: symtab\n type(string_table_t), intent(inout) :: strtab\n\n logical :: eof\n logical :: no_newline\n integer(kind = nk) :: after_ast_address\n\n ast%len = 0\n symtab%len = 0\n strtab%len = 0\n call build_subtree (1_nk, after_ast_address)\n\n contains\n\n recursive subroutine build_subtree (here_address, after_subtree_address)\n integer(kind = nk), value :: here_address\n integer(kind = nk), intent(out) :: after_subtree_address\n\n integer :: node_variety\n integer(kind = nk) :: i, j\n integer(kind = nk) :: left_branch_address\n integer(kind = nk) :: right_branch_address\n\n ! Get a line from the parser output.\n call get_line_from_stream (unit_no, eof, no_newline, strbuf)\n\n if (eof) then\n call ast_error\n else\n ! Prepare to store a new node.\n call ast%ensure_storage(here_address)\n ast%len = here_address\n\n ! What sort of node is it?\n i = skip_whitespace (strbuf, 1_nk)\n j = skip_non_whitespace (strbuf, i)\n node_variety = strbuf_to_node_variety (strbuf, i, j - 1)\n\n ast%nodes(here_address)%node_variety = node_variety\n\n select case (node_variety)\n case (node_Nil)\n after_subtree_address = here_address + 1\n case (node_Identifier)\n i = skip_whitespace (strbuf, j)\n j = skip_non_whitespace (strbuf, i)\n ast%nodes(here_address)%int = &\n & strbuf_to_symbol_index (strbuf, i, j - 1, symtab)\n after_subtree_address = here_address + 1\n case (node_String)\n i = skip_whitespace (strbuf, j)\n j = skip_whitespace_backwards (strbuf, strbuf%length())\n ast%nodes(here_address)%int = &\n & strbuf_to_string_index (strbuf, i, j, strtab)\n after_subtree_address = here_address + 1\n case (node_Integer)\n i = skip_whitespace (strbuf, j)\n j = skip_non_whitespace (strbuf, i)\n ast%nodes(here_address)%int = strbuf_to_int (strbuf, i, j - 1)\n after_subtree_address = here_address + 1\n case default\n ! The node is internal, and has left and right branches.\n ! The left branch will start at left_branch_address; the\n ! right branch will start at left_branch_address +\n ! right_side_offset.\n left_branch_address = here_address + 1\n ! Build the left branch.\n call build_subtree (left_branch_address, right_branch_address)\n ! Build the right_branch.\n call build_subtree (right_branch_address, after_subtree_address)\n ast%nodes(here_address)%right_branch_offset = &\n & right_branch_address - left_branch_address\n end select\n\n end if\n end subroutine build_subtree\n\n end subroutine read_ast\n\n function strbuf_to_node_variety (strbuf, i, j) result (node_variety)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i, j\n integer :: node_variety\n\n !\n ! This function has not been optimized in any way, unless the\n ! Fortran compiler can optimize it.\n !\n ! Something like a ‘radix tree search’ could be done on the\n ! characters of the strbuf. Or a perfect hash function. Or a\n ! binary search. Etc.\n !\n\n if (j == i - 1) then\n call ast_error\n else\n select case (strbuf%to_unicode(i, j))\n case (ck_\";\")\n node_variety = node_Nil\n case (ck_\"Identifier\")\n node_variety = node_Identifier\n case (ck_\"String\")\n node_variety = node_String\n case (ck_\"Integer\")\n node_variety = node_Integer\n case (ck_\"Sequence\")\n node_variety = node_Sequence\n case (ck_\"If\")\n node_variety = node_If\n case (ck_\"Prtc\")\n node_variety = node_Prtc\n case (ck_\"Prts\")\n node_variety = node_Prts\n case (ck_\"Prti\")\n node_variety = node_Prti\n case (ck_\"While\")\n node_variety = node_While\n case (ck_\"Assign\")\n node_variety = node_Assign\n case (ck_\"Negate\")\n node_variety = node_Negate\n case (ck_\"Not\")\n node_variety = node_Not\n case (ck_\"Multiply\")\n node_variety = node_Multiply\n case (ck_\"Divide\")\n node_variety = node_Divide\n case (ck_\"Mod\")\n node_variety = node_Mod\n case (ck_\"Add\")\n node_variety = node_Add\n case (ck_\"Subtract\")\n node_variety = node_Subtract\n case (ck_\"Less\")\n node_variety = node_Less\n case (ck_\"LessEqual\")\n node_variety = node_LessEqual\n case (ck_\"Greater\")\n node_variety = node_Greater\n case (ck_\"GreaterEqual\")\n node_variety = node_GreaterEqual\n case (ck_\"Equal\")\n node_variety = node_Equal\n case (ck_\"NotEqual\")\n node_variety = node_NotEqual\n case (ck_\"And\")\n node_variety = node_And\n case (ck_\"Or\")\n node_variety = node_Or\n case default\n call ast_error\n end select\n end if\n end function strbuf_to_node_variety\n\n function strbuf_to_symbol_index (strbuf, i, j, symtab) result (int)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i, j\n type(string_table_t), intent(inout) :: symtab\n integer(kind = rik) :: int\n\n if (j == i - 1) then\n call ast_error\n else\n int = symtab%look_up(strbuf%to_unicode (i, j))\n end if\n end function strbuf_to_symbol_index\n\n function strbuf_to_int (strbuf, i, j) result (int)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i, j\n integer(kind = rik) :: int\n\n integer :: stat\n character(:, kind = ck), allocatable :: str\n\n if (j < i) then\n call ast_error\n else\n allocate (character(len = (j - i) + 1_nk, kind = ck) :: str)\n str = strbuf%to_unicode (i, j)\n read (str, *, iostat = stat) int\n if (stat /= 0) then\n call ast_error\n end if\n end if\n end function strbuf_to_int\n\n function strbuf_to_string_index (strbuf, i, j, strtab) result (int)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i, j\n type(string_table_t), intent(inout) :: strtab\n integer(kind = rik) :: int\n\n if (j == i - 1) then\n call ast_error\n else\n int = strtab%look_up(strbuf_to_string (strbuf, i, j))\n end if\n end function strbuf_to_string_index\n\n function strbuf_to_string (strbuf, i, j) result (str)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i, j\n character(:, kind = ck), allocatable :: str\n\n character(1, kind = ck), parameter :: linefeed_char = char (10, kind = ck)\n character(1, kind = ck), parameter :: backslash_char = char (92, kind = ck)\n\n ! The following is correct for Unix and its relatives.\n character(1, kind = ck), parameter :: newline_char = linefeed_char\n\n integer(kind = nk) :: k\n integer(kind = nk) :: count\n\n if (strbuf%chars(i) /= ck_'\"' .or. strbuf%chars(j) /= ck_'\"') then\n call ast_error\n else\n ! Count how many characters are needed.\n count = 0\n k = i + 1\n do while (k < j)\n count = count + 1\n if (strbuf%chars(k) == backslash_char) then\n k = k + 2\n else\n k = k + 1\n end if\n end do\n\n allocate (character(len = count, kind = ck) :: str)\n\n count = 0\n k = i + 1\n do while (k < j)\n if (strbuf%chars(k) == backslash_char) then\n if (k == j - 1) then\n call ast_error\n else\n select case (strbuf%chars(k + 1))\n case (ck_'n')\n count = count + 1\n str(count:count) = newline_char\n case (backslash_char)\n count = count + 1\n str(count:count) = backslash_char\n case default\n call ast_error\n end select\n k = k + 2\n end if\n else\n count = count + 1\n str(count:count) = strbuf%chars(k)\n k = k + 1\n end if\n end do\n end if\n end function strbuf_to_string\n\n subroutine ast_error\n !\n ! It might be desirable to give more detail.\n !\n write (error_unit, '(\"The AST input seems corrupted.\")')\n stop 1\n end subroutine ast_error\n\nend module ast_reader\n\nmodule code_generation\n\n !\n ! First we generate code as if the virtual machine itself were part\n ! of this program. Then we disassemble the generated code.\n !\n ! Because we are targeting only the one output language, this seems\n ! an easy way to perform the task.\n !\n !\n ! A point worth noting: the virtual machine is a stack\n ! architecture.\n !\n ! Stack architectures have a long history. Burroughs famously\n ! preferred stack architectures for running Algol programs. See, for\n ! instance,\n ! https://en.wikipedia.org/w/index.php?title=Burroughs_large_systems&oldid=1068076420\n !\n\n use, intrinsic :: iso_fortran_env, only: input_unit\n use, intrinsic :: iso_fortran_env, only: output_unit\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, non_intrinsic :: compiler_type_kinds\n use, non_intrinsic :: helper_procedures\n use, non_intrinsic :: ast_reader\n\n implicit none\n private\n\n public :: generate_and_output_code\n public :: generate_code\n public :: output_code\n\n ! The virtual machine cannot handle integers of more than 32 bits,\n ! two’s-complement.\n integer(kind = rik), parameter :: vm_huge_negint = -(2_rik ** 31_rik)\n integer(kind = rik), parameter :: vm_huge_posint = (2_rik ** 31_rik) - 1_rik\n\n ! Arbitrarily chosen opcodes.\n integer, parameter :: opcode_nop = 0 ! I think there should be a nop\n ! opcode, to reserve space for\n ! later hand-patching. :)\n integer, parameter :: opcode_halt = 1 ! Does the ‘halt’ instruction\n ! apply brakes to the drum?\n integer, parameter :: opcode_add = 2\n integer, parameter :: opcode_sub = 3\n integer, parameter :: opcode_mul = 4\n integer, parameter :: opcode_div = 5\n integer, parameter :: opcode_mod = 6\n integer, parameter :: opcode_lt = 7\n integer, parameter :: opcode_gt = 8\n integer, parameter :: opcode_le = 9\n integer, parameter :: opcode_ge = 10\n integer, parameter :: opcode_eq = 11\n integer, parameter :: opcode_ne = 12\n integer, parameter :: opcode_and = 13\n integer, parameter :: opcode_or = 14\n integer, parameter :: opcode_neg = 15\n integer, parameter :: opcode_not = 16\n integer, parameter :: opcode_prtc = 17\n integer, parameter :: opcode_prti = 18\n integer, parameter :: opcode_prts = 19\n integer, parameter :: opcode_fetch = 20\n integer, parameter :: opcode_store = 21\n integer, parameter :: opcode_push = 22\n integer, parameter :: opcode_jmp = 23\n integer, parameter :: opcode_jz = 24\n\n character(8, kind = ck), parameter :: opcode_names(0:24) = &\n & (/ \"nop \", &\n & \"halt \", &\n & \"add \", &\n & \"sub \", &\n & \"mul \", &\n & \"div \", &\n & \"mod \", &\n & \"lt \", &\n & \"gt \", &\n & \"le \", &\n & \"ge \", &\n & \"eq \", &\n & \"ne \", &\n & \"and \", &\n & \"or \", &\n & \"neg \", &\n & \"not \", &\n & \"prtc \", &\n & \"prti \", &\n & \"prts \", &\n & \"fetch \", &\n & \"store \", &\n & \"push \", &\n & \"jmp \", &\n & \"jz \" /)\n\n type :: vm_code_t\n integer(kind = rik), private :: len = 0_rik\n character(1), allocatable :: bytes(:)\n contains\n procedure, pass, private :: ensure_storage => vm_code_t_ensure_storage\n procedure, pass :: length => vm_code_t_length\n end type vm_code_t\n\ncontains\n\n subroutine vm_code_t_ensure_storage (code, length_needed)\n class(vm_code_t), intent(inout) :: code\n integer(kind = nk), intent(in) :: length_needed\n\n integer(kind = nk) :: len_needed\n integer(kind = nk) :: new_size\n type(vm_code_t) :: new_code\n\n len_needed = max (length_needed, 1_nk)\n\n if (.not. allocated (code%bytes)) then\n ! Initialize a new code%bytes array.\n new_size = new_storage_size (len_needed)\n allocate (code%bytes(0:(new_size - 1)))\n else if (ubound (code%bytes, 1) < len_needed - 1) then\n ! Allocate a new code%bytes array, larger than the current one,\n ! but containing the same bytes.\n new_size = new_storage_size (len_needed)\n allocate (new_code%bytes(0:(new_size - 1)))\n new_code%bytes(0:(code%len - 1)) = code%bytes(0:(code%len - 1))\n call move_alloc (new_code%bytes, code%bytes)\n end if\n end subroutine vm_code_t_ensure_storage\n\n elemental function vm_code_t_length (code) result (len)\n class(vm_code_t), intent(in) :: code\n integer(kind = rik) :: len\n\n len = code%len\n end function vm_code_t_length\n\n subroutine generate_and_output_code (outp, ast, symtab, strtab)\n integer, intent(in) :: outp ! The unit to write the output to.\n type(ast_t), intent(in) :: ast\n type(string_table_t), intent(inout) :: symtab\n type(string_table_t), intent(inout) :: strtab\n\n type(vm_code_t) :: code\n integer(kind = rik) :: i_vm\n\n code%len = 0\n i_vm = 0_rik\n call generate_code (ast, 1_nk, i_vm, code)\n call output_code (outp, symtab, strtab, code)\n end subroutine generate_and_output_code\n\n subroutine generate_code (ast, i_ast, i_vm, code)\n type(ast_t), intent(in) :: ast\n integer(kind = nk), intent(in) :: i_ast ! Index in the ast array.\n integer(kind = rik), intent(inout) :: i_vm ! Address in the virtual machine.\n type(vm_code_t), intent(inout) :: code\n\n call traverse (i_ast)\n\n ! Generate a halt instruction.\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_halt)\n i_vm = i_vm + 1\n\n code%len = i_vm\n\n contains\n\n recursive subroutine traverse (i_ast)\n integer(kind = nk), intent(in) :: i_ast ! Index in the ast array.\n\n select case (ast%nodes(i_ast)%node_variety)\n\n case (node_Nil)\n continue\n\n case (node_Integer)\n block\n integer(kind = rik) :: int_value\n\n int_value = ast%nodes(i_ast)%int\n call ensure_integer_is_vm_compatible (int_value)\n call code%ensure_storage(i_vm + 5)\n code%bytes(i_vm) = achar (opcode_push)\n call int32_to_vm_bytes (int_value, code%bytes, i_vm + 1)\n i_vm = i_vm + 5\n end block\n\n case (node_Identifier)\n block\n integer(kind = rik) :: variable_index\n\n ! In the best Fortran tradition, we indexed the variables\n ! starting at one; however, the virtual machine starts them\n ! at zero. So subtract 1.\n variable_index = ast%nodes(i_ast)%int - 1\n\n call ensure_integer_is_vm_compatible (variable_index)\n call code%ensure_storage(i_vm + 5)\n code%bytes(i_vm) = achar (opcode_fetch)\n call uint32_to_vm_bytes (variable_index, code%bytes, i_vm + 1)\n i_vm = i_vm + 5\n end block\n\n case (node_String)\n block\n integer(kind = rik) :: string_index\n\n ! In the best Fortran tradition, we indexed the strings\n ! starting at one; however, the virtual machine starts them\n ! at zero. So subtract 1.\n string_index = ast%nodes(i_ast)%int - 1\n\n call ensure_integer_is_vm_compatible (string_index)\n call code%ensure_storage(i_vm + 5)\n code%bytes(i_vm) = achar (opcode_push)\n call uint32_to_vm_bytes (string_index, code%bytes, i_vm + 1)\n i_vm = i_vm + 5\n end block\n\n case (node_Assign)\n block\n integer(kind = nk) :: i_left, i_right\n integer(kind = rik) :: variable_index\n\n i_left = left_branch (i_ast)\n i_right = right_branch (i_ast)\n\n ! In the best Fortran tradition, we indexed the variables\n ! starting at one; however, the virtual machine starts them\n ! at zero. So subtract 1.\n variable_index = ast%nodes(i_left)%int - 1\n\n ! Create code to push the right side onto the stack\n call traverse (i_right)\n\n ! Create code to store that result into the variable on the\n ! left side.\n call ensure_node_variety (node_Identifier, ast%nodes(i_left)%node_variety)\n call ensure_integer_is_vm_compatible (variable_index)\n call code%ensure_storage(i_vm + 5)\n code%bytes(i_vm) = achar (opcode_store)\n call uint32_to_vm_bytes (variable_index, code%bytes, i_vm + 1)\n i_vm = i_vm + 5\n end block\n\n case (node_Multiply)\n call traverse (left_branch (i_ast))\n call traverse (right_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_mul)\n i_vm = i_vm + 1\n\n case (node_Divide)\n call traverse (left_branch (i_ast))\n call traverse (right_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_div)\n i_vm = i_vm + 1\n\n case (node_Mod)\n call traverse (left_branch (i_ast))\n call traverse (right_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_mod)\n i_vm = i_vm + 1\n\n case (node_Add)\n call traverse (left_branch (i_ast))\n call traverse (right_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_add)\n i_vm = i_vm + 1\n\n case (node_Subtract)\n call traverse (left_branch (i_ast))\n call traverse (right_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_sub)\n i_vm = i_vm + 1\n\n case (node_Less)\n call traverse (left_branch (i_ast))\n call traverse (right_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_lt)\n i_vm = i_vm + 1\n\n case (node_LessEqual)\n call traverse (left_branch (i_ast))\n call traverse (right_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_le)\n i_vm = i_vm + 1\n\n case (node_Greater)\n call traverse (left_branch (i_ast))\n call traverse (right_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_gt)\n i_vm = i_vm + 1\n\n case (node_GreaterEqual)\n call traverse (left_branch (i_ast))\n call traverse (right_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_ge)\n i_vm = i_vm + 1\n\n case (node_Equal)\n call traverse (left_branch (i_ast))\n call traverse (right_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_eq)\n i_vm = i_vm + 1\n\n case (node_NotEqual)\n call traverse (left_branch (i_ast))\n call traverse (right_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_ne)\n i_vm = i_vm + 1\n\n case (node_Negate)\n call ensure_node_variety (node_Nil, &\n & ast%nodes(right_branch (i_ast))%node_variety)\n call traverse (left_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_neg)\n i_vm = i_vm + 1\n\n case (node_Not)\n call ensure_node_variety (node_Nil, &\n & ast%nodes(right_branch (i_ast))%node_variety)\n call traverse (left_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_not)\n i_vm = i_vm + 1\n\n case (node_And)\n !\n ! This is not a short-circuiting AND and so differs from\n ! C. One would not notice the difference, except in side\n ! effects that (I believe) are not possible in our tiny\n ! language.\n !\n ! Even in a language such as Fortran that has actual AND and\n ! OR operators, an optimizer may generate short-circuiting\n ! code and so spoil one’s expectations for side\n ! effects. (Therefore gfortran may issue a warning if you\n ! call an unpure function within an .AND. or\n ! .OR. expression.)\n !\n ! A C equivalent to what we have our code generator doing\n ! (and to Fortran’s .AND. operator) might be something like\n !\n ! #define AND(a, b) ((!!(a)) * (!!(b)))\n !\n ! This macro takes advantage of the equivalence of AND to\n ! multiplication modulo 2. The ‘!!’ notations are a C idiom\n ! for converting values to 0 and 1.\n !\n call traverse (left_branch (i_ast))\n call traverse (right_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_and)\n i_vm = i_vm + 1\n\n case (node_Or)\n !\n ! This is not a short-circuiting OR and so differs from\n ! C. One would not notice the difference, except in side\n ! effects that (I believe) are not possible in our tiny\n ! language.\n !\n ! Even in a language such as Fortran that has actual AND and\n ! OR operators, an optimizer may generate short-circuiting\n ! code and so spoil one’s expectations for side\n ! effects. (Therefore gfortran may issue a warning if you\n ! call an unpure function within an .AND. or\n ! .OR. expression.)\n !\n ! A C equivalent to what we have our code generator doing\n ! (and to Fortran’s .OR. operator) might be something like\n !\n ! #define OR(a, b) (!( (!(a)) * (!(b)) ))\n !\n ! This macro takes advantage of the equivalence of AND to\n ! multiplication modulo 2, and the equivalence of OR(a,b) to\n ! !AND(!a,!b). One could instead take advantage of the\n ! equivalence of OR to addition modulo 2:\n !\n ! #define OR(a, b) ( ( (!!(a)) + (!!(b)) ) & 1 )\n !\n call traverse (left_branch (i_ast))\n call traverse (right_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_or)\n i_vm = i_vm + 1\n\n case (node_If)\n block\n integer(kind = nk) :: i_left, i_right\n integer(kind = nk) :: i_right_then_left, i_right_then_right\n logical :: there_is_an_else_clause\n integer(kind = rik) :: fixup_address1\n integer(kind = rik) :: fixup_address2\n integer(kind = rik) :: relative_address\n\n i_left = left_branch (i_ast)\n i_right = right_branch (i_ast)\n\n call ensure_node_variety (node_If, ast%nodes(i_right)%node_variety)\n\n i_right_then_left = left_branch (i_right)\n i_right_then_right = right_branch (i_right)\n\n there_is_an_else_clause = &\n & (ast%nodes(i_right_then_right)%node_variety /= node_Nil)\n\n ! Generate code for the predicate.\n call traverse (i_left)\n\n ! Generate a conditional jump over the predicate-true code.\n call code%ensure_storage(i_vm + 5)\n code%bytes(i_vm) = achar (opcode_jz)\n call int32_to_vm_bytes (0_rik, code%bytes, i_vm + 1)\n fixup_address1 = i_vm + 1\n i_vm = i_vm + 5\n\n ! Generate the predicate-true code.\n call traverse (i_right_then_left)\n\n if (there_is_an_else_clause) then\n ! Generate an unconditional jump over the predicate-true\n ! code.\n call code%ensure_storage(i_vm + 5)\n code%bytes(i_vm) = achar (opcode_jmp)\n call int32_to_vm_bytes (0_rik, code%bytes, i_vm + 1)\n fixup_address2 = i_vm + 1\n i_vm = i_vm + 5\n\n ! Fix up the conditional jump, so it jumps to the\n ! predicate-false code.\n relative_address = i_vm - fixup_address1\n call int32_to_vm_bytes (relative_address, code%bytes, fixup_address1)\n\n ! Generate the predicate-false code.\n call traverse (i_right_then_right)\n\n ! Fix up the unconditional jump, so it jumps past the\n ! predicate-false code.\n relative_address = i_vm - fixup_address2\n call int32_to_vm_bytes (relative_address, code%bytes, fixup_address2)\n else\n ! Fix up the conditional jump, so it jumps past the\n ! predicate-true code.\n relative_address = i_vm - fixup_address1\n call int32_to_vm_bytes (relative_address, code%bytes, fixup_address1)\n end if\n end block\n\n case (node_While)\n block\n\n !\n ! Note there is another common way to translate a\n ! while-loop which is to put (logically inverted) predicate\n ! code *after* the loop-body code, followed by a\n ! conditional jump to the start of the loop. You start the\n ! loop by unconditionally jumping to the predicate code.\n !\n ! If our VM had a ‘jnz’ instruction, that translation would\n ! almost certainly be slightly better than this one. Given\n ! that we do not have a ‘jnz’, the code would end up\n ! slightly enlarged; one would have to put ‘not’ before the\n ! ‘jz’ at the bottom of the loop.\n !\n\n integer(kind = nk) :: i_left, i_right\n integer(kind = rik) :: loop_address\n integer(kind = rik) :: fixup_address\n integer(kind = rik) :: relative_address\n\n i_left = left_branch (i_ast)\n i_right = right_branch (i_ast)\n\n ! Generate code for the predicate.\n loop_address = i_vm\n call traverse (i_left)\n\n ! Generate a conditional jump out of the loop.\n call code%ensure_storage(i_vm + 5)\n code%bytes(i_vm) = achar (opcode_jz)\n call int32_to_vm_bytes (0_rik, code%bytes, i_vm + 1)\n fixup_address = i_vm + 1\n i_vm = i_vm + 5\n\n ! Generate code for the loop body.\n call traverse (i_right)\n\n ! Generate an unconditional jump to the top of the loop.\n call code%ensure_storage(i_vm + 5)\n code%bytes(i_vm) = achar (opcode_jmp)\n relative_address = loop_address - (i_vm + 1)\n call int32_to_vm_bytes (relative_address, code%bytes, i_vm + 1)\n i_vm = i_vm + 5\n\n ! Fix up the conditional jump, so it jumps after the loop\n ! body.\n relative_address = i_vm - fixup_address\n call int32_to_vm_bytes (relative_address, code%bytes, fixup_address)\n end block\n\n case (node_Prtc)\n call ensure_node_variety (node_Nil, &\n & ast%nodes(right_branch (i_ast))%node_variety)\n call traverse (left_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_prtc)\n i_vm = i_vm + 1\n\n case (node_Prti)\n call ensure_node_variety (node_Nil, &\n & ast%nodes(right_branch (i_ast))%node_variety)\n call traverse (left_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_prti)\n i_vm = i_vm + 1\n\n case (node_Prts)\n call ensure_node_variety (node_Nil, &\n & ast%nodes(right_branch (i_ast))%node_variety)\n call traverse (left_branch (i_ast))\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode_prts)\n i_vm = i_vm + 1\n\n case (node_Sequence)\n call traverse (left_branch (i_ast))\n call traverse (right_branch (i_ast))\n\n case default\n call bad_ast\n\n end select\n\n code%len = i_vm\n\n end subroutine traverse\n\n elemental function left_branch (i_here) result (i_left)\n integer(kind = nk), intent(in) :: i_here\n integer(kind = nk) :: i_left\n\n i_left = i_here + 1\n end function left_branch\n\n elemental function right_branch (i_here) result (i_right)\n integer(kind = nk), intent(in) :: i_here\n integer(kind = nk) :: i_right\n\n i_right = i_here + 1 + ast%nodes(i_here)%right_branch_offset\n end function right_branch\n\n subroutine ensure_node_variety (expected_node_variety, found_node_variety)\n integer, intent(in) :: expected_node_variety\n integer, intent(in) :: found_node_variety\n if (expected_node_variety /= found_node_variety) call bad_ast\n end subroutine ensure_node_variety\n\n subroutine bad_ast\n call codegen_error_message\n write (error_unit, '(\"unexpected abstract syntax\")')\n stop 1\n end subroutine bad_ast\n\n end subroutine generate_code\n\n subroutine output_code (outp, symtab, strtab, code)\n integer, intent(in) :: outp ! The unit to write the output to.\n type(string_table_t), intent(inout) :: symtab\n type(string_table_t), intent(inout) :: strtab\n type(vm_code_t), intent(in) :: code\n\n call write_header (outp, symtab%length(), strtab%length())\n call write_strings (outp, strtab)\n call disassemble_instructions (outp, code)\n end subroutine output_code\n\n subroutine write_header (outp, data_size, strings_size)\n integer, intent(in) :: outp\n integer(kind = rik) :: data_size\n integer(kind = rik) :: strings_size\n\n call ensure_integer_is_vm_compatible (data_size)\n call ensure_integer_is_vm_compatible (strings_size)\n write (outp, '(\"Datasize: \", I0, \" Strings: \", I0)') data_size, strings_size\n end subroutine write_header\n\n subroutine write_strings (outp, strtab)\n integer, intent(in) :: outp\n type(string_table_t), intent(inout) :: strtab\n\n integer(kind = rik) :: i\n\n do i = 1_rik, strtab%length()\n write (outp, '(1A)') quoted_string (strtab%look_up(i))\n end do\n end subroutine write_strings\n\n subroutine disassemble_instructions (outp, code)\n integer, intent(in) :: outp\n type(vm_code_t), intent(in) :: code\n\n integer(kind = rik) :: i_vm\n integer :: opcode\n integer(kind = rik) :: n\n\n i_vm = 0_rik\n do while (i_vm /= code%length())\n call write_vm_code_address (outp, i_vm)\n opcode = iachar (code%bytes(i_vm))\n call write_vm_opcode (outp, opcode)\n select case (opcode)\n case (opcode_push)\n call int32_from_vm_bytes (n, code%bytes, i_vm + 1)\n call write_vm_int_literal (outp, n)\n i_vm = i_vm + 5\n case (opcode_fetch, opcode_store)\n call uint32_from_vm_bytes (n, code%bytes, i_vm + 1)\n call write_vm_data_address (outp, n)\n i_vm = i_vm + 5\n case (opcode_jmp, opcode_jz)\n call int32_from_vm_bytes (n, code%bytes, i_vm + 1)\n call write_vm_jump_address (outp, n, i_vm + 1)\n i_vm = i_vm + 5\n case default\n i_vm = i_vm + 1\n end select\n write (outp, '()', advance = 'yes')\n end do\n end subroutine disassemble_instructions\n\n subroutine write_vm_code_address (outp, i_vm)\n integer, intent(in) :: outp\n integer(kind = rik), intent(in) :: i_vm\n\n ! 10 characters is wide enough for any 32-bit unsigned number.\n write (outp, '(I10, 1X)', advance = 'no') i_vm\n end subroutine write_vm_code_address\n\n subroutine write_vm_opcode (outp, opcode)\n integer, intent(in) :: outp\n integer, intent(in) :: opcode\n\n character(8, kind = ck) :: opcode_name\n\n opcode_name = opcode_names(opcode)\n\n select case (opcode)\n case (opcode_push, opcode_fetch, opcode_store, opcode_jz, opcode_jmp)\n write (outp, '(1A)', advance = 'no') opcode_name(1:6)\n case default\n write (outp, '(1A)', advance = 'no') trim (opcode_name)\n end select\n end subroutine write_vm_opcode\n\n subroutine write_vm_int_literal (outp, n)\n integer, intent(in) :: outp\n integer(kind = rik), intent(in) :: n\n\n write (outp, '(I0)', advance = 'no') n\n end subroutine write_vm_int_literal\n\n subroutine write_vm_data_address (outp, i)\n integer, intent(in) :: outp\n integer(kind = rik), intent(in) :: i\n\n write (outp, '(\"[\", I0, \"]\")', advance = 'no') i\n end subroutine write_vm_data_address\n\n subroutine write_vm_jump_address (outp, relative_address, i_vm)\n integer, intent(in) :: outp\n integer(kind = rik), intent(in) :: relative_address\n integer(kind = rik), intent(in) :: i_vm\n\n write (outp, '(\" (\", I0, \") \", I0)', advance = 'no') &\n & relative_address, i_vm + relative_address\n end subroutine write_vm_jump_address\n\n subroutine ensure_integer_is_vm_compatible (n)\n integer(kind = rik), intent(in) :: n\n !\n ! It would seem desirable to check this in the syntax analyzer,\n ! instead, so line and column numbers can be given. But checking\n ! here will not hurt.\n !\n if (n < vm_huge_negint .or. vm_huge_posint < n) then\n call codegen_error_message\n write (error_unit, '(\"integer is too large for the virtual machine: \", I0)') n\n stop 1\n end if\n end subroutine ensure_integer_is_vm_compatible\n\n subroutine codegen_error_message\n write (error_unit, '(\"Code generation error: \")', advance = 'no')\n end subroutine codegen_error_message\n\nend module code_generation\n\nprogram gen\n use, intrinsic :: iso_fortran_env, only: input_unit\n use, intrinsic :: iso_fortran_env, only: output_unit\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, non_intrinsic :: compiler_type_kinds\n use, non_intrinsic :: string_buffers\n use, non_intrinsic :: ast_reader\n use, non_intrinsic :: code_generation\n\n implicit none\n\n integer, parameter :: inp_unit_no = 100\n integer, parameter :: outp_unit_no = 101\n\n integer :: arg_count\n character(200) :: arg\n integer :: inp\n integer :: outp\n\n type(strbuf_t) :: strbuf\n type(ast_t) :: ast\n type(string_table_t) :: symtab\n type(string_table_t) :: strtab\n\n arg_count = command_argument_count ()\n if (3 <= arg_count) then\n call print_usage\n else\n if (arg_count == 0) then\n inp = input_unit\n outp = output_unit\n else if (arg_count == 1) then\n call get_command_argument (1, arg)\n inp = open_for_input (trim (arg))\n outp = output_unit\n else if (arg_count == 2) then\n call get_command_argument (1, arg)\n inp = open_for_input (trim (arg))\n call get_command_argument (2, arg)\n outp = open_for_output (trim (arg))\n end if\n\n call read_ast (inp, strbuf, ast, symtab, strtab)\n call generate_and_output_code (outp, ast, symtab, strtab)\n end if\n\ncontains\n\n function open_for_input (filename) result (unit_no)\n character(*), intent(in) :: filename\n integer :: unit_no\n\n integer :: stat\n\n open (unit = inp_unit_no, file = filename, status = 'old', &\n & action = 'read', access = 'stream', form = 'unformatted', &\n & iostat = stat)\n if (stat /= 0) then\n write (error_unit, '(\"Error: failed to open \", 1A, \" for input\")') filename\n stop 1\n end if\n unit_no = inp_unit_no\n end function open_for_input\n\n function open_for_output (filename) result (unit_no)\n character(*), intent(in) :: filename\n integer :: unit_no\n\n integer :: stat\n\n open (unit = outp_unit_no, file = filename, action = 'write', iostat = stat)\n if (stat /= 0) then\n write (error_unit, '(\"Error: failed to open \", 1A, \" for output\")') filename\n stop 1\n end if\n unit_no = outp_unit_no\n end function open_for_output\n\n subroutine print_usage\n character(200) :: progname\n\n call get_command_argument (0, progname)\n write (output_unit, '(\"Usage: \", 1A, \" [INPUT_FILE [OUTPUT_FILE]]\")') &\n & trim (progname)\n end subroutine print_usage\n\nend program gen\n", "language": "Fortran" }, { "code": "package main\n\nimport (\n \"bufio\"\n \"encoding/binary\"\n \"fmt\"\n \"log\"\n \"os\"\n \"strconv\"\n \"strings\"\n)\n\ntype NodeType int\n\nconst (\n ndIdent NodeType = iota\n ndString\n ndInteger\n ndSequence\n ndIf\n ndPrtc\n ndPrts\n ndPrti\n ndWhile\n ndAssign\n ndNegate\n ndNot\n ndMul\n ndDiv\n ndMod\n ndAdd\n ndSub\n ndLss\n ndLeq\n ndGtr\n ndGeq\n ndEql\n ndNeq\n ndAnd\n ndOr\n)\n\ntype code = byte\n\nconst (\n fetch code = iota\n store\n push\n add\n sub\n mul\n div\n mod\n lt\n gt\n le\n ge\n eq\n ne\n and\n or\n neg\n not\n jmp\n jz\n prtc\n prts\n prti\n halt\n)\n\ntype Tree struct {\n nodeType NodeType\n left *Tree\n right *Tree\n value string\n}\n\n// dependency: Ordered by NodeType, must remain in same order as NodeType enum\ntype atr struct {\n enumText string\n nodeType NodeType\n opcode code\n}\n\nvar atrs = []atr{\n {\"Identifier\", ndIdent, 255},\n {\"String\", ndString, 255},\n {\"Integer\", ndInteger, 255},\n {\"Sequence\", ndSequence, 255},\n {\"If\", ndIf, 255},\n {\"Prtc\", ndPrtc, 255},\n {\"Prts\", ndPrts, 255},\n {\"Prti\", ndPrti, 255},\n {\"While\", ndWhile, 255},\n {\"Assign\", ndAssign, 255},\n {\"Negate\", ndNegate, neg},\n {\"Not\", ndNot, not},\n {\"Multiply\", ndMul, mul},\n {\"Divide\", ndDiv, div},\n {\"Mod\", ndMod, mod},\n {\"Add\", ndAdd, add},\n {\"Subtract\", ndSub, sub},\n {\"Less\", ndLss, lt},\n {\"LessEqual\", ndLeq, le},\n {\"Greater\", ndGtr, gt},\n {\"GreaterEqual\", ndGeq, ge},\n {\"Equal\", ndEql, eq},\n {\"NotEqual\", ndNeq, ne},\n {\"And\", ndAnd, and},\n {\"Or\", ndOr, or},\n}\n\nvar (\n stringPool []string\n globals []string\n object []code\n)\n\nvar (\n err error\n scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc nodeType2Op(nodeType NodeType) code {\n return atrs[nodeType].opcode\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n return &Tree{nodeType, nil, nil, value}\n}\n\n/*** Code generator ***/\n\nfunc emitByte(c code) {\n object = append(object, c)\n}\n\nfunc emitWord(n int) {\n bs := make([]byte, 4)\n binary.LittleEndian.PutUint32(bs, uint32(n))\n for _, b := range bs {\n emitByte(code(b))\n }\n}\n\nfunc emitWordAt(at, n int) {\n bs := make([]byte, 4)\n binary.LittleEndian.PutUint32(bs, uint32(n))\n for i := at; i < at+4; i++ {\n object[i] = code(bs[i-at])\n }\n}\n\nfunc hole() int {\n t := len(object)\n emitWord(0)\n return t\n}\n\nfunc fetchVarOffset(id string) int {\n for i := 0; i < len(globals); i++ {\n if globals[i] == id {\n return i\n }\n }\n globals = append(globals, id)\n return len(globals) - 1\n}\n\nfunc fetchStringOffset(st string) int {\n for i := 0; i < len(stringPool); i++ {\n if stringPool[i] == st {\n return i\n }\n }\n stringPool = append(stringPool, st)\n return len(stringPool) - 1\n}\n\nfunc codeGen(x *Tree) {\n if x == nil {\n return\n }\n var n, p1, p2 int\n switch x.nodeType {\n case ndIdent:\n emitByte(fetch)\n n = fetchVarOffset(x.value)\n emitWord(n)\n case ndInteger:\n emitByte(push)\n n, err = strconv.Atoi(x.value)\n check(err)\n emitWord(n)\n case ndString:\n emitByte(push)\n n = fetchStringOffset(x.value)\n emitWord(n)\n case ndAssign:\n n = fetchVarOffset(x.left.value)\n codeGen(x.right)\n emitByte(store)\n emitWord(n)\n case ndIf:\n codeGen(x.left) // if expr\n emitByte(jz) // if false, jump\n p1 = hole() // make room forjump dest\n codeGen(x.right.left) // if true statements\n if x.right.right != nil {\n emitByte(jmp)\n p2 = hole()\n }\n emitWordAt(p1, len(object)-p1)\n if x.right.right != nil {\n codeGen(x.right.right)\n emitWordAt(p2, len(object)-p2)\n }\n case ndWhile:\n p1 = len(object)\n codeGen(x.left) // while expr\n emitByte(jz) // if false, jump\n p2 = hole() // make room for jump dest\n codeGen(x.right) // statements\n emitByte(jmp) // back to the top\n emitWord(p1 - len(object)) // plug the top\n emitWordAt(p2, len(object)-p2) // plug the 'if false, jump'\n case ndSequence:\n codeGen(x.left)\n codeGen(x.right)\n case ndPrtc:\n codeGen(x.left)\n emitByte(prtc)\n case ndPrti:\n codeGen(x.left)\n emitByte(prti)\n case ndPrts:\n codeGen(x.left)\n emitByte(prts)\n case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,\n ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:\n codeGen(x.left)\n codeGen(x.right)\n emitByte(nodeType2Op(x.nodeType))\n case ndNegate, ndNot:\n codeGen(x.left)\n emitByte(nodeType2Op(x.nodeType))\n default:\n msg := fmt.Sprintf(\"error in code generator - found %d, expecting operator\\n\", x.nodeType)\n reportError(msg)\n }\n}\n\nfunc codeFinish() {\n emitByte(halt)\n}\n\nfunc listCode() {\n fmt.Printf(\"Datasize: %d Strings: %d\\n\", len(globals), len(stringPool))\n for _, s := range stringPool {\n fmt.Println(s)\n }\n pc := 0\n for pc < len(object) {\n fmt.Printf(\"%5d \", pc)\n op := object[pc]\n pc++\n switch op {\n case fetch:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n fmt.Printf(\"fetch [%d]\\n\", x)\n pc += 4\n case store:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n fmt.Printf(\"store [%d]\\n\", x)\n pc += 4\n case push:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n fmt.Printf(\"push %d\\n\", x)\n pc += 4\n case add:\n fmt.Println(\"add\")\n case sub:\n fmt.Println(\"sub\")\n case mul:\n fmt.Println(\"mul\")\n case div:\n fmt.Println(\"div\")\n case mod:\n fmt.Println(\"mod\")\n case lt:\n fmt.Println(\"lt\")\n case gt:\n fmt.Println(\"gt\")\n case le:\n fmt.Println(\"le\")\n case ge:\n fmt.Println(\"ge\")\n case eq:\n fmt.Println(\"eq\")\n case ne:\n fmt.Println(\"ne\")\n case and:\n fmt.Println(\"and\")\n case or:\n fmt.Println(\"or\")\n case neg:\n fmt.Println(\"neg\")\n case not:\n fmt.Println(\"not\")\n case jmp:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n fmt.Printf(\"jmp (%d) %d\\n\", x, int32(pc)+x)\n pc += 4\n case jz:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n fmt.Printf(\"jz (%d) %d\\n\", x, int32(pc)+x)\n pc += 4\n case prtc:\n fmt.Println(\"prtc\")\n case prti:\n fmt.Println(\"prti\")\n case prts:\n fmt.Println(\"prts\")\n case halt:\n fmt.Println(\"halt\")\n default:\n reportError(fmt.Sprintf(\"listCode: Unknown opcode %d\", op))\n }\n }\n}\n\nfunc getEnumValue(name string) NodeType {\n for _, atr := range atrs {\n if atr.enumText == name {\n return atr.nodeType\n }\n }\n reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n return -1\n}\n\nfunc loadAst() *Tree {\n var nodeType NodeType\n var s string\n if scanner.Scan() {\n line := strings.TrimRight(scanner.Text(), \" \\t\")\n tokens := strings.Fields(line)\n first := tokens[0]\n if first[0] == ';' {\n return nil\n }\n nodeType = getEnumValue(first)\n le := len(tokens)\n if le == 2 {\n s = tokens[1]\n } else if le > 2 {\n idx := strings.Index(line, `\"`)\n s = line[idx:]\n }\n }\n check(scanner.Err())\n if s != \"\" {\n return makeLeaf(nodeType, s)\n }\n left := loadAst()\n right := loadAst()\n return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n ast, err := os.Open(\"ast.txt\")\n check(err)\n defer ast.Close()\n scanner = bufio.NewScanner(ast)\n codeGen(loadAst())\n codeFinish()\n listCode()\n}\n", "language": "Go" }, { "code": "require'format/printf'\n\n(opcodes)=: opcodes=: ;:{{)n\n fetch store push add sub mul div mod lt gt le ge\n eq ne and or neg not jmp jz prtc prts prti halt\n}}-.LF\n\n(ndDisp)=: ndDisp=:;:{{)n\n Sequence Multiply Divide Mod Add Subtract Negate Less LessEqual Greater\n GreaterEqual Equal NotEqual Not And Or Prts Assign Prti x If x x x While\n x x Prtc x Identifier String Integer\n}}-.LF\n\nndDisp,.ndOps=:;: {{)n\n x mul div mod add sub neg lt le gt ge eq ne not and or\n x x x x x x x x x x x x x x x x\n}} -.LF\n\nload_ast=: {{\n 'node_types node_values'=: 2{.|:(({.,&<&<}.@}.)~ i.&' ');._2 y\n 1{::0 load_ast ''\n:\n node_type=. x{::node_types\n if. node_type-:,';' do. x;a: return.end.\n node_value=. x{::node_values\n if. -.''-:node_value do.x;<node_type make_leaf node_value return.end.\n 'x left'=.(x+1) load_ast''\n 'x right'=.(x+1) load_ast''\n x;<node_type make_node left right\n}}\n\nmake_leaf=: ;\nmake_node=: {{m;n;<y}}\ntyp=: 0&{::\nval=: left=: 1&{::\nright=: 2&{::\n\ngen_code=: {{\n if.y-:'' do.'' return.end.\n V=. val y\n W=. ;2}.y\n select.op=.typ y\n case.'Integer'do.gen_int _\".V [ gen_op push\n case.'String'do.gen_string V [ gen_op push\n case.'Identifier'do.gen_var V [ gen_op fetch\n case.'Assign'do.gen_var left V [ gen_op store [ gen_code W\n case.;:'Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or'do.\n gen_op op [ gen_code W [ gen_code V\n case.;:'Not Negate'do.\n gen_op op [ gen_code V\n case.'If'do.\n p1=. gen_int 0 [ gen_op jz [ gen_code V\n gen_code left W\n if.#right W do.\n p2=. gen_int 0 [ gen_op jmp\n gen_code right W [ p1 patch #object\n p2 patch #object\n else.\n p1 patch #object\n end.\n case.'While'do.\n p1=. #object\n p2=. gen_int 0 [ gen_op jz [ gen_code V\n gen_int p1 [ gen_op jmp [ gen_code W\n p2 patch #object\n case.'Prtc'do.gen_op prtc [ gen_code V\n case.'Prti'do.gen_op prti [ gen_code V\n case.'Prts'do.gen_op prts [ gen_code V\n case.'Sequence'do.\n gen_code W [ gen_code V\n case.do.error'unknown node type ',typ y\n end.\n}}\n\ngen_op=:{{\n arg=. boxopen y\n if. -.arg e. opcodes do.\n arg=. (ndDisp i. arg){ndOps\n end.\n assert. arg e. opcodes\n object=: object,opcodes i.arg\n}}\n\ngen_int=:{{\n if.#$y do.num=. _ \".y\n else.num=. y end.\n r=. #object\n object=: object,(4#256)#:num\n r\n}}\n\ngen_string=: {{\n strings=:~.strings,<y\n gen_int strings i.<y\n}}\n\ngen_var=: {{\n vars=:~.vars,<y\n gen_int vars i.<y\n}}\n\npatch=: {{ #object=: ((4#256)#:y) (x+i.4)} object }}\nerror=: {{echo y throw.}}\ngetint=: _2147483648+4294967296|2147483648+256#.]\n\nlist_code=: {{\n r=.'Datasize: %d Strings: %d\\n' sprintf vars;&#strings\n r=.r,;strings,each LF\n pc=. 0\n lim=.<:#object\n while.do.\n op=.(pc{object){::opcodes\n r=.r,'%5d %s'sprintf pc;op\n pc=. pc+1\n i=. getint (lim<.pc+i.4){object\n k=. 0\n select.op\n case.fetch;store do.k=.4[r=.r,' [%d]'sprintf i\n case.push do.k=.4[r=.r,' %d'sprintf i\n case.jmp;jz do.k=.4[r=.r,' (%d) %d'sprintf (i-pc);i\n case.halt do.r=.r,LF return.\n end.\n pc=.pc+k\n r=.r,LF\n end.\n}}\n\ngen=: {{\n object=:strings=:vars=:i.0\n gen_code load_ast y\n list_code gen_op halt\n}}\n", "language": "J" }, { "code": "count=:{{)n\ncount = 1;\nwhile (count < 10) {\n print(\"count is: \", count, \"\\n\");\n count = count + 1;\n}\n}}\n\n gen syntax lex count\nDatasize: 1 Strings: 2\n\"count is: \"\n\"\\n\"\n 0 push 1\n 5 store [0]\n 10 fetch [0]\n 15 push 10\n 20 lt\n 21 jz (43) 65\n 26 push 0\n 31 prts\n 32 fetch [0]\n 37 prti\n 38 push 1\n 43 prts\n 44 fetch [0]\n 49 push 1\n 54 add\n 55 store [0]\n 60 jmp (-51) 10\n 65 halt\n", "language": "J" }, { "code": "package codegenerator;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class CodeGenerator {\n final static int WORDSIZE = 4;\n\n static byte[] code = {};\n\n static Map<String, NodeType> str_to_nodes = new HashMap<>();\n static List<String> string_pool = new ArrayList<>();\n static List<String> variables = new ArrayList<>();\n static int string_count = 0;\n static int var_count = 0;\n\n static Scanner s;\n static NodeType[] unary_ops = {\n NodeType.nd_Negate, NodeType.nd_Not\n };\n static NodeType[] operators = {\n NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,\n NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,\n NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or\n };\n\n static enum Mnemonic {\n NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,\n JMP, JZ, PRTC, PRTS, PRTI, HALT\n }\n static class Node {\n public NodeType nt;\n public Node left, right;\n public String value;\n\n Node() {\n this.nt = null;\n this.left = null;\n this.right = null;\n this.value = null;\n }\n Node(NodeType node_type, Node left, Node right, String value) {\n this.nt = node_type;\n this.left = left;\n this.right = right;\n this.value = value;\n }\n public static Node make_node(NodeType nodetype, Node left, Node right) {\n return new Node(nodetype, left, right, \"\");\n }\n public static Node make_node(NodeType nodetype, Node left) {\n return new Node(nodetype, left, null, \"\");\n }\n public static Node make_leaf(NodeType nodetype, String value) {\n return new Node(nodetype, null, null, value);\n }\n }\n static enum NodeType {\n nd_None(\"\", Mnemonic.NONE), nd_Ident(\"Identifier\", Mnemonic.NONE), nd_String(\"String\", Mnemonic.NONE), nd_Integer(\"Integer\", Mnemonic.NONE), nd_Sequence(\"Sequence\", Mnemonic.NONE),\n nd_If(\"If\", Mnemonic.NONE),\n nd_Prtc(\"Prtc\", Mnemonic.NONE), nd_Prts(\"Prts\", Mnemonic.NONE), nd_Prti(\"Prti\", Mnemonic.NONE), nd_While(\"While\", Mnemonic.NONE),\n nd_Assign(\"Assign\", Mnemonic.NONE),\n nd_Negate(\"Negate\", Mnemonic.NEG), nd_Not(\"Not\", Mnemonic.NOT), nd_Mul(\"Multiply\", Mnemonic.MUL), nd_Div(\"Divide\", Mnemonic.DIV), nd_Mod(\"Mod\", Mnemonic.MOD), nd_Add(\"Add\", Mnemonic.ADD),\n nd_Sub(\"Subtract\", Mnemonic.SUB), nd_Lss(\"Less\", Mnemonic.LT), nd_Leq(\"LessEqual\", Mnemonic.LE),\n nd_Gtr(\"Greater\", Mnemonic.GT), nd_Geq(\"GreaterEqual\", Mnemonic.GE), nd_Eql(\"Equal\", Mnemonic.EQ),\n nd_Neq(\"NotEqual\", Mnemonic.NE), nd_And(\"And\", Mnemonic.AND), nd_Or(\"Or\", Mnemonic.OR);\n\n private final String name;\n private final Mnemonic m;\n\n NodeType(String name, Mnemonic m) {\n this.name = name;\n this.m = m;\n }\n Mnemonic getMnemonic() { return this.m; }\n\n @Override\n public String toString() { return this.name; }\n }\n static void appendToCode(int b) {\n code = Arrays.copyOf(code, code.length + 1);\n code[code.length - 1] = (byte) b;\n }\n static void emit_byte(Mnemonic m) {\n appendToCode(m.ordinal());\n }\n static void emit_word(int n) {\n appendToCode(n >> 24);\n appendToCode(n >> 16);\n appendToCode(n >> 8);\n appendToCode(n);\n }\n static void emit_word_at(int pos, int n) {\n code[pos] = (byte) (n >> 24);\n code[pos + 1] = (byte) (n >> 16);\n code[pos + 2] = (byte) (n >> 8);\n code[pos + 3] = (byte) n;\n }\n static int get_word(int pos) {\n int result;\n result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff) << 16) + ((code[pos + 2] & 0xff) << 8) + (code[pos + 3] & 0xff) ;\n\n return result;\n }\n static int fetch_var_offset(String name) {\n int n;\n n = variables.indexOf(name);\n if (n == -1) {\n variables.add(name);\n n = var_count++;\n }\n return n;\n }\n static int fetch_string_offset(String str) {\n int n;\n n = string_pool.indexOf(str);\n if (n == -1) {\n string_pool.add(str);\n n = string_count++;\n }\n return n;\n }\n static int hole() {\n int t = code.length;\n emit_word(0);\n return t;\n }\n static boolean arrayContains(NodeType[] a, NodeType n) {\n boolean result = false;\n for (NodeType test: a) {\n if (test.equals(n)) {\n result = true;\n break;\n }\n }\n return result;\n }\n static void code_gen(Node x) throws Exception {\n int n, p1, p2;\n if (x == null) return;\n\n switch (x.nt) {\n case nd_None: return;\n case nd_Ident:\n emit_byte(Mnemonic.FETCH);\n n = fetch_var_offset(x.value);\n emit_word(n);\n break;\n case nd_Integer:\n emit_byte(Mnemonic.PUSH);\n emit_word(Integer.parseInt(x.value));\n break;\n case nd_String:\n emit_byte(Mnemonic.PUSH);\n n = fetch_string_offset(x.value);\n emit_word(n);\n break;\n case nd_Assign:\n n = fetch_var_offset(x.left.value);\n code_gen(x.right);\n emit_byte(Mnemonic.STORE);\n emit_word(n);\n break;\n case nd_If:\n p2 = 0; // to avoid NetBeans complaining about 'not initialized'\n code_gen(x.left);\n emit_byte(Mnemonic.JZ);\n p1 = hole();\n code_gen(x.right.left);\n if (x.right.right != null) {\n emit_byte(Mnemonic.JMP);\n p2 = hole();\n }\n emit_word_at(p1, code.length - p1);\n if (x.right.right != null) {\n code_gen(x.right.right);\n emit_word_at(p2, code.length - p2);\n }\n break;\n case nd_While:\n p1 = code.length;\n code_gen(x.left);\n emit_byte(Mnemonic.JZ);\n p2 = hole();\n code_gen(x.right);\n emit_byte(Mnemonic.JMP);\n emit_word(p1 - code.length);\n emit_word_at(p2, code.length - p2);\n break;\n case nd_Sequence:\n code_gen(x.left);\n code_gen(x.right);\n break;\n case nd_Prtc:\n code_gen(x.left);\n emit_byte(Mnemonic.PRTC);\n break;\n case nd_Prti:\n code_gen(x.left);\n emit_byte(Mnemonic.PRTI);\n break;\n case nd_Prts:\n code_gen(x.left);\n emit_byte(Mnemonic.PRTS);\n break;\n default:\n if (arrayContains(operators, x.nt)) {\n code_gen(x.left);\n code_gen(x.right);\n emit_byte(x.nt.getMnemonic());\n } else if (arrayContains(unary_ops, x.nt)) {\n code_gen(x.left);\n emit_byte(x.nt.getMnemonic());\n } else {\n throw new Exception(\"Error in code generator! Found \" + x.nt + \", expecting operator.\");\n }\n }\n }\n static void list_code() throws Exception {\n int pc = 0, x;\n Mnemonic op;\n System.out.println(\"Datasize: \" + var_count + \" Strings: \" + string_count);\n for (String s: string_pool) {\n System.out.println(s);\n }\n while (pc < code.length) {\n System.out.printf(\"%4d \", pc);\n op = Mnemonic.values()[code[pc++]];\n switch (op) {\n case FETCH:\n x = get_word(pc);\n System.out.printf(\"fetch [%d]\", x);\n pc += WORDSIZE;\n break;\n case STORE:\n x = get_word(pc);\n System.out.printf(\"store [%d]\", x);\n pc += WORDSIZE;\n break;\n case PUSH:\n x = get_word(pc);\n System.out.printf(\"push %d\", x);\n pc += WORDSIZE;\n break;\n case ADD: case SUB: case MUL: case DIV: case MOD:\n case LT: case GT: case LE: case GE: case EQ: case NE:\n case AND: case OR: case NEG: case NOT:\n case PRTC: case PRTI: case PRTS: case HALT:\n System.out.print(op.toString().toLowerCase());\n break;\n case JMP:\n x = get_word(pc);\n System.out.printf(\"jmp (%d) %d\", x, pc + x);\n pc += WORDSIZE;\n break;\n case JZ:\n x = get_word(pc);\n System.out.printf(\"jz (%d) %d\", x, pc + x);\n pc += WORDSIZE;\n break;\n default:\n throw new Exception(\"Unknown opcode \" + code[pc] + \"@\" + (pc - 1));\n }\n System.out.println();\n }\n }\n static Node load_ast() throws Exception {\n String command, value;\n String line;\n Node left, right;\n\n while (s.hasNext()) {\n line = s.nextLine();\n value = null;\n if (line.length() > 16) {\n command = line.substring(0, 15).trim();\n value = line.substring(15).trim();\n } else {\n command = line.trim();\n }\n if (command.equals(\";\")) {\n return null;\n }\n if (!str_to_nodes.containsKey(command)) {\n throw new Exception(\"Command not found: '\" + command + \"'\");\n }\n if (value != null) {\n return Node.make_leaf(str_to_nodes.get(command), value);\n }\n left = load_ast(); right = load_ast();\n return Node.make_node(str_to_nodes.get(command), left, right);\n }\n return null; // for the compiler, not needed\n }\n public static void main(String[] args) {\n Node n;\n\n str_to_nodes.put(\";\", NodeType.nd_None);\n str_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n str_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n str_to_nodes.put(\"String\", NodeType.nd_String);\n str_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n str_to_nodes.put(\"If\", NodeType.nd_If);\n str_to_nodes.put(\"While\", NodeType.nd_While);\n str_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n str_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n str_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n str_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n str_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n str_to_nodes.put(\"Not\", NodeType.nd_Not);\n str_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n str_to_nodes.put(\"Divide\", NodeType.nd_Div);\n str_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n str_to_nodes.put(\"Add\", NodeType.nd_Add);\n str_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n str_to_nodes.put(\"Less\", NodeType.nd_Lss);\n str_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n str_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n str_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n str_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n str_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n str_to_nodes.put(\"And\", NodeType.nd_And);\n str_to_nodes.put(\"Or\", NodeType.nd_Or);\n\n if (args.length > 0) {\n try {\n s = new Scanner(new File(args[0]));\n n = load_ast();\n code_gen(n);\n emit_byte(Mnemonic.HALT);\n list_code();\n } catch (Exception e) {\n System.out.println(\"Ex: \"+e);//.getMessage());\n }\n }\n }\n}\n", "language": "Java" }, { "code": "import Base.show\n\nmutable struct Asm32\n offset::Int32\n code::String\n arg::Int32\n targ::Int32\nend\nAsm32(code, arg = 0) = Asm32(0, code, arg, 0)\n\nshow(io::IO, a::Asm32) = print(io, lpad(\"$(a.offset)\", 6), lpad(a.code, 8),\n a.targ > 0 ? (lpad(\"($(a.arg))\", 8) * lpad(\"$(a.targ)\", 4)) :\n (a.code in [\"store\", \"fetch\"] ? lpad(\"[$(a.arg)]\", 8) :\n (a.code in [\"push\"] ? lpad(\"$(a.arg)\", 8) : \"\")))\n\nconst ops32 = Dict{String,String}(\"Multiply\" => \"mul\", \"Divide\" => \"div\", \"Mod\" => \"mod\", \"Add\" => \"add\",\n \"Subtract\" => \"sub\", \"Less\" => \"lt\", \"Greater\" => \"gt\", \"LessEqual\" => \"le\", \"GreaterEqual\" => \"ge\",\n \"Equal\" => \"eq\", \"NotEqual\" => \"ne\", \"And\" => \"and\", \"or\" => \"or\", \"Not\" => \"not\", \"Minus\" => \"neg\",\n \"Prtc\" => \"prtc\", \"Prti\" => \"prti\", \"Prts\" => \"prts\")\n\nfunction compiletoasm(io)\n identifiers = Vector{String}()\n strings = Vector{String}()\n labels = Vector{Int}()\n\n function cpile(io, islefthandside = false)\n arr = Vector{Asm32}()\n jlabel() = (push!(labels, length(labels) + 1); labels[end])\n m = match(r\"^(\\w+|;)\\s*([\\d\\w\\\"\\\\ \\S]+)?\", strip(readline(io)))\n x, val = m == nothing ? Pair(\";\", 0) : m.captures\n if x == \";\" return arr\n elseif x == \"Assign\"\n lhs = cpile(io, true)\n rhs = cpile(io)\n append!(arr, rhs)\n append!(arr, lhs)\n if length(arr) > 100 exit() end\n elseif x == \"Integer\" push!(arr, Asm32(\"push\", parse(Int32, val)))\n elseif x == \"String\"\n if !(val in strings)\n push!(strings, val)\n end\n push!(arr, Asm32(\"push\", findfirst(x -> x == val, strings) - 1))\n elseif x == \"Identifier\"\n if !(val in identifiers)\n if !islefthandside\n throw(\"Identifier $val referenced before it is assigned\")\n end\n push!(identifiers, val)\n end\n push!(arr, Asm32(islefthandside ? \"store\" : \"fetch\", findfirst(x -> x == val, identifiers) - 1))\n elseif haskey(ops32, x)\n append!(arr, cpile(io))\n append!(arr, cpile(io))\n push!(arr, Asm32(ops32[x]))\n elseif x == \"If\"\n append!(arr, cpile(io))\n x, y = jlabel(), jlabel()\n push!(arr, Asm32(\"jz\", x))\n append!(arr, cpile(io))\n push!(arr, Asm32(\"jmp\", y))\n a = cpile(io)\n if length(a) < 1\n push!(a, Asm32(\"nop\", 0))\n end\n a[1].offset = x\n append!(arr, a)\n push!(arr, Asm32(y, \"nop\", 0, 0)) # placeholder\n elseif x == \"While\"\n x, y = jlabel(), jlabel()\n a = cpile(io)\n if length(a) < 1\n push!(a, Asm32(\"nop\", 0))\n end\n a[1].offset = x\n append!(arr, a)\n push!(arr, Asm32(\"jz\", y))\n append!(arr, cpile(io))\n push!(arr, Asm32(\"jmp\", x), Asm32(y, \"nop\", 0, 0))\n elseif x == \"Sequence\"\n append!(arr, cpile(io))\n append!(arr, cpile(io))\n else\n throw(\"unknown node type: $x\")\n end\n arr\n end\n\n # compile AST\n asmarr = cpile(io)\n push!(asmarr, Asm32(\"halt\"))\n # move address markers to working code and prune nop code\n for (i, acode) in enumerate(asmarr)\n if acode.code == \"nop\" && acode.offset != 0 && i < length(asmarr)\n asmarr[i + 1].offset = asmarr[i].offset\n end\n end\n filter!(x -> x.code != \"nop\", asmarr)\n # renumber offset column with actual offsets\n pos = 0\n jmps = Dict{Int, Int}()\n for acode in asmarr\n if acode.offset > 0\n jmps[acode.offset] = pos\n end\n acode.offset = pos\n pos += acode.code in [\"push\", \"store\", \"fetch\", \"jz\", \"jmp\"] ? 5 : 1\n end\n # fix up jump destinations\n for acode in asmarr\n if acode.code in [\"jz\", \"jmp\"]\n if haskey(jmps, acode.arg)\n acode.targ = jmps[acode.arg]\n acode.arg = acode.targ - acode.offset -1\n else\n throw(\"unknown jump location: $acode\")\n end\n end\n end\n # print Datasize and Strings header\n println(\"Datasize: $(length(identifiers)) Strings: $(length(strings))\\n\" *\n join(strings, \"\\n\") )\n # print assembly lines\n foreach(println, asmarr)\nend\n\nconst testAST = raw\"\"\"\nSequence\nSequence\n;\nAssign\nIdentifier count\nInteger 1\nWhile\nLess\nIdentifier count\nInteger 10\nSequence\nSequence\n;\nSequence\nSequence\nSequence\n;\nPrts\nString \"count is: \"\n;\nPrti\nIdentifier count\n;\nPrts\nString \"\\n\"\n;\nAssign\nIdentifier count\nAdd\nIdentifier count\nInteger 1 \"\"\"\n\niob = IOBuffer(testAST) # use an io buffer here for testing, but could use stdin instead of iob\n\ncompiletoasm(iob)\n", "language": "Julia" }, { "code": "Module CodeGenerator (s$){\n\tFunction code$(op$) {\n\t\t=format$(\"{0::-6} {1}\", pc, op$)\n\t\tpc++\n\t}\n\tFunction code2$(op$, n$) {\n\t\t=format$(\"{0::-6} {1} {2}\", pc, op$, n$)\n\t\tpc+=5\n\t}\n\tFunction code3$(op$,pc, st, ed) {\n\t\t=format$(\"{0::-6} {1} ({2}) {3}\", pc, op$, ed-st-1, ed)\n\t}\n\t\n\tEnum tok {\n\t\tgneg, gnot, gmul, gdiv, gmod, gadd, gle, gsub, glt\n\t\tgle, ggt, gge, geq, gne, gand, gor, gprtc, gprti, gprts,\n\t\tgif, gwhile, gAssign, gSeq, gstring, gidentifier, gint, gnone\n\t}\n\n\t\\\\ Inventories are lists with keys, or keys/data (key must be unique)\n\t\\\\ there is one type more the Invetory Queue which get same keys.\n\t\\\\ But here not used.\n\tInventory symb=\"Multiply\":=gmul, \"Divide\":=gdiv, \"Mod\":=gmod, \"Add\":=gadd\n\tAppend symb, \"Negate\":=gneg, \"Not\":=gnot,\"Less\":=glt,\"Subtract\":=gsub\n\tAppend symb, \"LessEqual\":=gle, \"Greater\":=ggt, \"GreaterEqual\":=gge, \"Sequence\":=gSeq\n\tAppend symb, \"Equal\":=geq, \"NotEqual\":=gne, \"And\":=gand, \"Or\":=gor, \"While\":=gwhile\n\tAppend symb, \"Prtc\":=gprtc,\"Prti\":=gprti,\"Prts\":=gprts, \"Assign\":=gAssign, \"If\":=gif\n\tAppend symb, \"String\":=gstring, \"Identifier\":=gidentifier, \"Integer\":=gint, \";\", gnone\n\n\tInventory DataSet\n\t\\\\ We set string as key. key maybe an empty string, a string or a number.\n\t\\\\ so we want eash string to saved one time only.\n\tInventory Strings\n\t\n\tConst nl$=chr$(13)+chr$(10), Ansi=3\n\tDef z$, lim, line$, newvar_ok, i=0\n\tDocument message$=nl$\n\tGlobal pc \\\\ functions have own scope, so we make it global, for this module, and childs.\n\n\tDim lines$()\n\ts$=filter$(s$,chr$(9)) \\\\ exclude tabs\n\tLines$()=piece$(s$,nl$) \\\\ break to lines\n\tlim=len(Lines$())\n\tFlush ' empty stack (there is a current stack of values which we use here)\n\t\n\tLoad_Ast()\n\tIf not stack.size=1 Then Flush : Error \"Ast not loaded\"\n\tAST=array \\\\ pop the array from stack\n\tDocument Assembly$, Header$\n\n\t\\\\ all lines of assembly goes to stack. Maybe not in right order.\n\t\\\\ Push statement push to top, Data statement push to bottom of stack\n\t\n\tCodeGenerator(Ast)\n\tData code$(\"halt\") ' append to end of stack\n\t\\\\ So now we get all data (letters) from stack\n\tWhile not empty\n\t\tAssembly$=letter$+nl$\n\tend while\n\t\\\\ So now we have to place them in order\n\tSort Assembly$\n\t\n\t\\\\ Let's make the header\n\tHeader$=format$(\"Datasize: {0} Strings: {1}\", Len(Dataset),Len(strings))\n\t\\\\ we use an iterator object, str^ is the counter, readonly, but Eval$() use it from object.\n\tstr=each(strings)\n\tWhile str\n\t\tHeader$=nl$+Eval$(str)\n\tEnd while\n\tAssembly$=nl$\n\t\\\\ insert to line 1 the Header\n\tInsert 1 Assembly$=Header$\n\t\\\\ Also we check for warnings\n\tIf len(message$)>2 then Assembly$=\"Warnings: \"+nl$+message$\n\t\\\\ So now we get a report\n\t\\\\ (at each 3/4 of window's lines, the printing stop and wait for user response, any key)\n\tReport Assembly$\n\tClipboard Assembly$\n\tSave.Doc Assembly$, \"code.t\", Ansi\n\tEnd\n\t\\\\ subs have 10000 limit for recursion but can be extended to 1000000 or more.\n\tSub CodeGenerator(t)\n\t\n\t\tIf len(t)=3 then\n\t\t\tselect case t#val(0)\n\t\t\tCase gSeq\n\t\t\t\tCodeGenerator(t#val(1)) : CodeGenerator(t#val(2))\n\t\t\tCase gwhile\n\t\t\t{\n\t\t\t\tlocal spc=pc\n\t\t\t\tCodeGenerator(t#val(1))\n\t\t\t\tlocal pc1=pc\n\t\t\t\tpc+=5 ' room for jz\n\t\t\t\tCodeGenerator(t#val(2))\n\t\t\t\tdata code3$(\"jz\",pc1, pc1, pc+5)\n\t\t\t\tdata code3$(\"jmp\",pc, pc, spc)\n\t\t\t\tpc+=5 ' room for jmp\n\t\t\t}\n\t\t\tCase gif\n\t\t\t{\n\t\t\t\tCodeGenerator(t#val(1))\n\t\t\t\tlocal pc1=pc, pc2\n\t\t\t\tpc+=5\n\t\t\t\tCodeGenerator(t#val(2)#val(1))\n\t\t\t\tIf len(t#val(2)#val(2))>0 then\n\t\t\t\t\tpc2=pc\n\t\t\t\t\tpc+=5\n\t\t\t\t\tdata code3$(\"jz\",pc1, pc1, pc)\n\t\t\t\t\tCodeGenerator(t#val(2)#val(2))\n\t\t\t\t\tdata code3$(\"jmp\",pc2, pc2, pc)\n\t\t\t\telse\n\t\t\t\t\tdata code3$(\"jz\",pc1, pc1, pc)\n\t\t\t\tend If\t\t\n\t\t\t}\n\t\t\tCase gAssign\n\t\t\t{\n\t\t\t\tCodeGenerator(t#val(2))\n\t\t\t\tlocal newvar_ok=true\n\t\t\t\tCodeGenerator(t#val(1))\n\t\t\t}\n\t\t\tcase gneg to gnot, gprtc to gprts\n\t\t\t\tCodeGenerator(t#val(1)) : data code$(mid$(eval$(t#val(0)),2))\n\t\t\tcase gmul to gor\n\t\t\t{\n\t\t\t\tCodeGenerator(t#val(1))\n\t\t\t\tCodeGenerator(t#val(2))\n\t\t\t\tdata code$(mid$(eval$(t#val(0)),2))\n\t\t\t}\n\t\t\tEnd select\n\t\tElse.if len(t)=2 then\n\t\t\tselect case t#val(0)\n\t\t\tCase gString\n\t\t\t{\n\t\t\t\tlocal spos\n\t\t\t\tIf exist(strings,t#val$(1)) then\n\t\t\t\t\tspos=eval(strings!)\n\t\t\t\telse\n\t\t\t\t\tappend strings, t#val$(1)\t\t\n\t\t\t\t\tspos=len(strings)-1\n\t\t\t\tend If\n\t\t\t\tPush code2$(\"push\",str$(spos,0))\n\t\t\t}\n\t\t\tCase gInt\n\t\t\t\tPush code2$(\"push\",t#val$(1), pc)\n\t\t\tCase gIdentifier\n\t\t\t{\n\t\t\t\tlocal ipos\n\t\t\t\tIf exist(dataset,t#val$(1)) then\n\t\t\t\t\tipos=Eval(dataset!) ' return position\n\t\t\t\telse.if newvar_ok then\n\t\t\t\t\tAppend dataset, t#val$(1)\n\t\t\t\t\tipos=len(dataset)-1\n\t\t\t\telse\n\t\t\t\t\tmessage$=\"Variable \"+t#val$(1)+\" not initialized\"+nl$\n\t\t\t\t\t\n\t\t\t\tend If\n\t\t\t\tIf newvar_ok then\n\t\t\t\t\tPush code2$(\"store\",\"[\"+str$(ipos, 0)+\"]\")\n\t\t\t\telse\n\t\t\t\t\tPush code2$(\"fetch\",\"[\"+str$(ipos, 0)+\"]\")\n\t\t\t\tend If\n\t\t\t}\n\t\t\tend select\n\t\tEnd If\n\tEnd Sub\n\tSub Load_Ast()\n\t\t\tIf i>=lim then Push (,) : exit sub\n\t\t\tdo\n\t\t\tline$=Trim$(lines$(i))\n\t\t\tI++\n\t\t\ttok$=piece$(line$,\" \")(0)\n\t\t\tuntil line$<>\"\" or i>=lim\n\t\t\tIf tok$=\"Identifier\" then\n\t\t\t\tPush (gidentifier,trim$(Mid$(line$,11)))\n\t\t\telse.if tok$=\"Integer\" then\n\t\t\t\tlong n=Val(Mid$(line$,8)) ' check overflow\n\t\t\t\tPush (gint, Trim$(Mid$(line$,8)))\n\t\t\telse.if tok$=\"String\" then\n\t\t\t\tPush (gstring,Trim$(Mid$(line$,7)))\n\t\t\telse.if tok$=\";\" then\n\t\t\t\tPush (,)\n\t\t\tElse\n\t\t\t\tlocal otok=symb(tok$)\n\t\t\t\tLoad_Ast()\n\t\t\t\tLoad_Ast()\n\t\t\t\tShift 2\n\t\t\t\tPush (otok,array, array)\n\t\t\tEnd If\n\tEnd Sub\n}\n\nCodeGenerator {\n\tSequence\n\tSequence\n\t;\n\tAssign\n\tIdentifier count\n\tInteger 1\n\tWhile\n\tLess\n\tIdentifier count\n\tInteger 10\n\tSequence\n\tSequence\n\t;\n\tSequence\n\tSequence\n\tSequence\n\t;\n\tPrts\n\tString \"count is: \"\n\t;\n\tPrti\n\tIdentifier count\n\t;\n\tPrts\n\tString \"\\n\"\n\t;\n\tAssign\n\tIdentifier count\n\tAdd\n\tIdentifier count\n\tInteger 1\n}\n", "language": "M2000-Interpreter" }, { "code": "import os, re, streams, strformat, strutils, tables, std/decls\n\ntype\n\n # AST node types.\n NodeKind = enum\n nIdentifier = \"Identifier\"\n nString = \"String\"\n nInteger = \"Integer\"\n nSequence = \"Sequence\"\n nIf = \"If\"\n nPrtc = \"Prtc\"\n nPrts = \"Prts\"\n nPrti = \"Prti\"\n nWhile = \"While\"\n nAssign = \"Assign\"\n nNegate = \"Negate\"\n nNot = \"Not\"\n nMultiply = \"Multiply\"\n nDivide = \"Divide\"\n nMod = \"Mod\"\n nAdd = \"Add\"\n nSubtract = \"Subtract\"\n nLess = \"Less\"\n nLessEqual = \"LessEqual\"\n nGreater = \"Greater\"\n nGreaterEqual = \"GreaterEqual\"\n nEqual = \"Equal\"\n nNotEqual = \"NotEqual\"\n nAnd = \"And\"\n nOr = \"Or\"\n\n # Ast node description.\n Node = ref object\n left: Node\n right: Node\n case kind: NodeKind\n of nString: stringVal: string\n of nInteger: intVal: int\n of nIdentifier: name: string\n else: nil\n\n # Virtual machine opcodes.\n OpCode = enum\n opFetch = \"fetch\"\n opStore = \"store\"\n opPush = \"push\"\n opJmp = \"jmp\"\n opJz = \"jz\"\n opAdd = \"add\"\n opSub = \"sub\"\n opMul = \"mul\"\n opDiv = \"div\"\n opMod = \"mod\"\n opLt = \"lt\"\n opgt = \"gt\"\n opLe = \"le\"\n opGe = \"ge\"\n opEq = \"eq\"\n opNe = \"ne\"\n opAnd = \"and\"\n opOr = \"or\"\n opNeg = \"neg\"\n opNot = \"not\"\n opPrtc = \"prtc\"\n opPrti = \"prti\"\n opPrts = \"prts\"\n opHalt = \"halt\"\n opInvalid = \"invalid\"\n\n # Code generator context.\n CodeGen = object\n address: int # Current address in code part.\n instr: seq[string] # List of instructions.\n vars: Table[string, int] # Mapping variable name -> variable index.\n strings: seq[string] # List of strings.\n\n # Node ranges.\n UnaryOpNode = range[nNegate..nNot]\n BinaryOpNode = range[nMultiply..nOr]\n PrintNode = range[nPrtc..nPrti]\n\n\nconst\n\n # Mapping unary operator Node -> OpCode.\n UnOp: array[UnaryOpNode, OpCode] = [opNeg, opNot]\n\n # Mapping binary operator Node -> OpCode.\n BinOp: array[BinaryOpNode, OpCode] = [opMul, opDiv, opMod, opAdd, opSub, opLt,\n opLe, opGt, opGe, opEq, opNe, opAnd, opOr]\n\n # Mapping print Node -> OpCode.\n PrintOp: array[PrintNode, OpCode] = [opPrtc, opPrts, opPrti]\n\n\n####################################################################################################\n# Code generator.\n\nproc genSimpleInst(gen: var CodeGen; opcode: OpCode) =\n ## Build a simple instruction (no operand).\n gen.instr.add &\"{gen.address:>5} {opcode}\"\n\n#---------------------------------------------------------------------------------------------------\n\nproc genMemInst(gen: var CodeGen; opcode: OpCode; memIndex: int) =\n ## Build a memory access instruction (opFetch, opStore).\n gen.instr.add &\"{gen.address:>5} {opcode:<5} [{memIndex}]\"\n\n#---------------------------------------------------------------------------------------------------\n\nproc genJumpInst(gen: var CodeGen; opcode: OpCode): int =\n ## Build a jump instruction. We use the letters X and Y as placeholders\n ## for the offset and the target address.\n result = gen.instr.len\n gen.instr.add &\"{gen.address:>5} {opcode:<5} (X) Y\"\n\n#---------------------------------------------------------------------------------------------------\n\nproc genPush(gen: var CodeGen; value: int) =\n ## Build a push instruction.\n gen.instr.add &\"{gen.address:>5} {opPush:<5} {value}\"\n\n#---------------------------------------------------------------------------------------------------\n\nproc updateJumpInst(gen: var CodeGen; index: int; jumpAddress, targetAddress: int) =\n ## Update the offset and the target address of a jump instruction.\n\n var instr {.byAddr.} = gen.instr[index]\n let offset = targetAddress - jumpAddress - 1\n for idx in countdown(instr.high, 0):\n case instr[idx]\n of 'Y':\n instr[idx..idx] = $targetAddress\n of 'X':\n instr[idx..idx] = $offset\n break\n else:\n discard\n\n#---------------------------------------------------------------------------------------------------\n\nproc process(gen: var CodeGen; node: Node) =\n ## Generate code for a node.\n\n if node.isNil: return\n\n case node.kind:\n\n of nInteger:\n gen.genPush(node.intVal)\n inc gen.address, 5\n\n of nIdentifier:\n if node.name notin gen.vars:\n gen.vars[node.name] = gen.vars.len\n gen.genMemInst(opFetch, gen.vars[node.name])\n inc gen.address, 5\n\n of nString:\n var index = gen.strings.find(node.stringVal)\n if index < 0:\n index = gen.strings.len\n gen.strings.add(node.stringVal)\n gen.genPush(index)\n inc gen.address, 5\n\n of nAssign:\n gen.process(node.right)\n if node.left.name notin gen.vars:\n gen.vars[node.left.name] = gen.vars.len\n gen.genMemInst(opStore, gen.vars[node.left.name])\n inc gen.address, 5\n\n of UnaryOpNode.low..UnaryOpNode.high:\n gen.process(node.left)\n gen.genSimpleInst(UnOp[node.kind])\n inc gen.address\n\n of BinaryOpNode.low..BinaryOpNode.high:\n gen.process(node.left)\n gen.process(node.right)\n gen.genSimpleInst(BinOp[node.kind])\n inc gen.address\n\n of PrintNode.low..PrintNode.high:\n gen.process(node.left)\n gen.genSimpleInst(PrintOp[node.kind])\n inc gen.address\n\n of nIf:\n # Generate condition expression.\n gen.process(node.left)\n # Generate jump if zero.\n let jzAddr = gen.address\n let jzInst = gen.genJumpInst(opJz)\n inc gen.address, 5\n # Generate then branch expression.\n gen.process(node.right.left)\n # If there is an \"else\" clause, generate unconditional jump\n var jmpAddr, jmpInst: int\n let hasElseClause = not node.right.right.isNil\n if hasElseClause:\n jmpAddr = gen.address\n jmpInst = gen.genJumpInst(opJmp)\n inc gen.address, 5\n # Update JZ offset.\n gen.updateJumpInst(jzInst, jzAddr, gen.address)\n # Generate else expression.\n if hasElseClause:\n gen.process(node.right.right)\n # Update JMP offset.\n gen.updateJumpInst(jmpInst, jmpAddr, gen.address)\n\n of nWhile:\n let condAddr = gen.address\n # Generate condition expression.\n gen.process(node.left)\n # Generate jump if zero.\n let jzAddr = gen.address\n let jzInst = gen.genJumpInst(opJz)\n inc gen.address, 5\n # Generate loop code.\n gen.process(node.right)\n # Generate unconditional jump.\n let jmpAddr = gen.address\n let jmpInst = gen.genJumpInst(opJmp)\n inc gen.address, 5\n # Update JMP offset.\n gen.updateJumpInst(jmpInst, jmpAddr, condAddr)\n # Update JZ offset.\n gen.updateJumpInst(jzInst, jzAddr, gen.address)\n\n of nSequence:\n gen.process(node.left)\n gen.process(node.right)\n\n#---------------------------------------------------------------------------------------------------\n\nproc run(gen: var CodeGen; ast: Node) =\n ## Run the code generator on the AST.\n\n # Process recursively the nodes.\n gen.process(ast)\n gen.genSimpleInst(opHalt) # Add a Halt operator at the end.\n\n # Output header.\n echo &\"Datasize: {gen.vars.len} Strings: {gen.strings.len}\"\n # Output strings.\n for s in gen.strings:\n echo s.escape().replace(\"\\\\x0A\", \"\\\\n\")\n # Output code.\n for inst in gen.instr:\n echo inst\n\n####################################################################################################\n# AST loader.\n\nproc newNode(kind: NodeKind; left: Node; right: Node = nil): Node =\n ## Create a new node with given left and right children.\n result = Node(kind: kind, left: left, right: right)\n\n#---------------------------------------------------------------------------------------------------\n\nproc loadAst(stream: Stream): Node =\n ## Load a linear AST and build a binary tree.\n\n let line = stream.readLine().strip()\n if line.startsWith(';'):\n return nil\n\n var fields = line.split(' ', 1)\n let kind = parseEnum[NodeKind](fields[0])\n if kind in {nIdentifier, nString, nInteger}:\n if fields.len < 2:\n raise newException(ValueError, \"Missing value field for \" & fields[0])\n else:\n fields[1] = fields[1].strip()\n case kind\n of nIdentifier:\n return Node(kind: nIdentifier, name: fields[1])\n of nString:\n let str = fields[1].replacef(re\"([^\\\\])(\\\\n)\", \"$1\\n\").replace(r\"\\\\\", r\"\\\").replace(\"\\\"\", \"\")\n return Node(kind: nString, stringVal: str)\n of nInteger:\n return Node(kind: nInteger, intVal: parseInt(fields[1]))\n else:\n if fields.len > 1:\n raise newException(ValueError, \"Extra field for \" & fields[0])\n\n let left = stream.loadAst()\n let right = stream.loadAst()\n result = newNode(kind, left, right)\n\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nvar stream: Stream\nvar toClose = false\nvar codegen: CodeGen\n\nif paramCount() < 1:\n stream = newFileStream(stdin)\nelse:\n stream = newFileStream(paramStr(1))\n toClose = true\n\nlet ast = loadAst(stream)\nif toClose: stream.close()\n\ncodegen.run(ast)\n", "language": "Nim" }, { "code": "#!/usr/bin/perl\n\nuse strict; # gen.pl - flatAST to stack machine code\nuse warnings; # http://www.rosettacode.org/wiki/Compiler/code_generator\n\nmy $stringcount = my $namecount = my $pairsym = my $pc = 0;\nmy (%strings, %names);\nmy %opnames = qw( Less lt LessEqual le Multiply mul Subtract sub Divide div\n GreaterEqual ge Equal eq Greater gt NotEqual ne Negate neg );\n\nsub tree\n {\n my ($A, $B) = ( '_' . ++$pairsym, '_' . ++$pairsym ); # labels for jumps\n my $line = <> // return '';\n (local $_, my $arg) = $line =~ /^(\\w+|;)\\s+(.*)/ or die \"bad input $line\";\n /Identifier/ ? \"fetch [@{[ $names{$arg} //= $namecount++ ]}]\\n\" :\n /Sequence/ ? tree() . tree() :\n /Integer/ ? \"push $arg\\n\" :\n /String/ ? \"push @{[ $strings{$arg} //= $stringcount++ ]}\\n\" :\n /Assign/ ? join '', reverse tree() =~ s/fetch/store/r, tree() :\n /While/ ? \"$A:\\n@{[ tree() ]}jz $B\\n@{[ tree() ]}jmp $A\\n$B:\\n\" :\n /If/ ? tree() . \"jz $A\\n@{[ !<> . # !<> skips second 'If'\n tree() ]}jmp $B\\n$A:\\n@{[ tree() ]}$B:\\n\" :\n /;/ ? '' :\n tree() . tree() . ($opnames{$_} // lc) . \"\\n\";\n }\n\n$_ = tree() . \"halt\\n\";\n\ns/^jmp\\s+(\\S+)\\n(_\\d+:\\n)\\1:\\n/$2/gm; # remove jmp next\ns/^(?=[a-z]\\w*(.*))/ # add locations\n (sprintf(\"%4d \", $pc), $pc += $1 ? 5 : 1)[0] /gem;\nmy %labels = /^(_\\d+):(?=(?:\\n_\\d+:)*\\n *(\\d+) )/gm; # pc addr of labels\ns/^ *(\\d+) j(?:z|mp) *\\K(_\\d+)$/ (@{[ # fix jumps\n $labels{$2} - $1 - 1]}) $labels{$2}/gm;\ns/^_\\d+.*\\n//gm; # remove labels\n\nprint \"Datasize: $namecount Strings: $stringcount\\n\";\nprint \"$_\\n\" for sort { $strings{$a} <=> $strings{$b} } keys %strings;\nprint;\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Compiler\\cgen.e\n -- ============================\n --\n -- The reusable part of cgen.exw\n --</span>\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span> <span style=\"color: #000080;font-style:italic;\">-- (machine code!)</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">parse</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">vars</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span>\n <span style=\"color: #000000;\">strings</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span>\n <span style=\"color: #000000;\">stringptrs</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">chain</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">global</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">var_idx</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">inode</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">inode</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #000000;\">tk_Identifier</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">ident</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">inode</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ident</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">vars</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">vars</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">vars</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ident</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">vars</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">n</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">string_idx</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">inode</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">inode</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #000000;\">tk_String</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">inode</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">strings</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">strings</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">strings</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">stringptrs</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">stringptrs</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">strings</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">n</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- note: must be kept precisely in sync with gen_rec!\n -- (relentlessly tested via estsize/actsize)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #004600;\">NULL</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n_type</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">node_type</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkNames</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">n_type</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Sequence</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_assign</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])+</span><span style=\"color: #000000;\">6</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Integer</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">5</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Identifier</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">6</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_String</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">5</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_while</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000080;font-style:italic;\">-- emit: @@:&lt;condition&gt;&lt;topjmp(@f)&gt;&lt;body&gt;&lt;tailjmp(@b)&gt;@@:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])+</span><span style=\"color: #000000;\">3</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #7060A8;\">body</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">stail</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">size</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">body</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">128</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">stop</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">body</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">stail</span> <span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">127</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">stop</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">body</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">stail</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_lt</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_le</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_ne</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_eq</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_gt</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_ge</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">10</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_and</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_or</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">15</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_add</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_sub</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">4</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_mul</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">5</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_div</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_mod</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">6</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_putc</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Printi</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Prints</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">5</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_if</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])+</span><span style=\"color: #000000;\">3</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #000000;\">tk_if</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">truesize</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">falsesize</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">elsejmp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">falsesize</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">falsesize</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">127</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">mainjmp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">truesize</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">elsejmp</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">127</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">mainjmp</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">truesize</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">elsejmp</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">falsesize</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_not</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">9</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_neg</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">size</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">4</span>\n <span style=\"color: #008080;\">else</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">size</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- the recursive part of code_gen</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #004600;\">NULL</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">initsize</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">estsize</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (test the gen_size function)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n_type</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">node_type</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkNames</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">n_type</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Sequence</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_assign</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">var_idx</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0o217</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o005</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">chain</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- pop [i]</span>\n <span style=\"color: #000000;\">chain</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">3</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Integer</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">0o150</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #7060A8;\">int_to_bytes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- push imm32</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_while</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000080;font-style:italic;\">-- emit: @@:&lt;condition&gt;&lt;topjmp(@f)&gt;&lt;body&gt;&lt;tailjmp(@b)&gt;@@:</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">looptop</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0o130</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- pop eax</span>\n <span style=\"color: #000000;\">0o205</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o300</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- test eax,eax</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">bodysize</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000080;font-style:italic;\">-- can we use short jumps?\n -- disclaimer: size calcs are not heavily tested; if in\n -- doubt reduce 128/7 by 8, and if that works\n -- then yep, you just found a boundary case.</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">stail</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">bodysize</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">looptop</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">128</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">offset</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">bodysize</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">stail</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">stop</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">offset</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">127</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">stop</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0o164</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">offset</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- jz (short) end</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0o017</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o204</span><span style=\"color: #0000FF;\">}&</span><span style=\"color: #7060A8;\">int_to_bytes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">offset</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- jz (long) end</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">offset</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">looptop</span><span style=\"color: #0000FF;\">-(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">stail</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">stail</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">0o353</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">offset</span> <span style=\"color: #000080;font-style:italic;\">-- jmp looptop (short)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">0o351</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #7060A8;\">int_to_bytes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">offset</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- jmp looptop (long)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_lt</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_le</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_gt</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_ge</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_ne</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_eq</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">xrm</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">tk_ne</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">xrm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0o225</span> <span style=\"color: #000080;font-style:italic;\">-- (#95)</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">tk_lt</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">xrm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0o234</span> <span style=\"color: #000080;font-style:italic;\">-- (#9C)</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">tk_ge</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">xrm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0o235</span> <span style=\"color: #000080;font-style:italic;\">-- (#9D)</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">tk_le</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">xrm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0o236</span> <span style=\"color: #000080;font-style:italic;\">-- (#9E)</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">tk_gt</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">xrm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0o237</span> <span style=\"color: #000080;font-style:italic;\">-- (#9F)</span>\n <span style=\"color: #008080;\">else</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">0o061</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o300</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- xor eax,eax</span>\n <span style=\"color: #000000;\">0o132</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- pop edx</span>\n <span style=\"color: #000000;\">0o131</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- pop ecx</span>\n <span style=\"color: #000000;\">0o071</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o321</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- cmp ecx,edx</span>\n <span style=\"color: #000000;\">0o017</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">xrm</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o300</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- setcc al</span>\n <span style=\"color: #000000;\">0o120</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- push eax</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_or</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_and</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">op</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">tk_or</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tk_and</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">op</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #000000;\">0o010</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">0o130</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- pop eax</span>\n <span style=\"color: #000000;\">0o131</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- pop ecx</span>\n <span style=\"color: #000000;\">0o205</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o300</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- test eax,eax</span>\n <span style=\"color: #000000;\">0o017</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o225</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o300</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- setne al</span>\n <span style=\"color: #000000;\">0o205</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o311</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- test ecx,ecx</span>\n <span style=\"color: #000000;\">0o017</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o225</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o301</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- setne cl</span>\n <span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o310</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- or/and al,cl</span>\n <span style=\"color: #000000;\">0o120</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- push eax</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_add</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_sub</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">op</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">tk_add</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tk_sub</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">op</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0o001</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">0o010</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">0o130</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- pop eax</span>\n <span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o004</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o044</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- add/or/and/sub [esp],eax</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_mul</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">0o131</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- pop ecx</span>\n <span style=\"color: #000000;\">0o130</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- pop eax</span>\n <span style=\"color: #000000;\">0o367</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o341</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- mul ecx</span>\n <span style=\"color: #000000;\">0o120</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- push eax</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_div</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_mod</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #7060A8;\">push</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0o120</span><span style=\"color: #0000FF;\">+(</span><span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">tk_mod</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">2</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">0o131</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- pop ecx</span>\n <span style=\"color: #000000;\">0o130</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- pop eax</span>\n <span style=\"color: #000000;\">0o231</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- cdq (eax -&gt; edx:eax)</span>\n <span style=\"color: #000000;\">0o367</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o371</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- idiv ecx</span>\n <span style=\"color: #7060A8;\">push</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- push eax|edx</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Identifier</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">var_idx</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0o377</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o065</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">chain</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- push [n]</span>\n <span style=\"color: #000000;\">chain</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">3</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_putc</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Printi</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Prints</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">tk_putc</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tk_Printi</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tk_Prints</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0o350</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">chain</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- call :printc/i/s</span>\n <span style=\"color: #000000;\">chain</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">3</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_String</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">string_idx</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0o150</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">chain</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- push RawStringPtr(string)</span>\n <span style=\"color: #000000;\">chain</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">3</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_if</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000080;font-style:italic;\">-- emit: &lt;condition&gt;&lt;mainjmp&gt;&lt;truepart&gt;[&lt;elsejmp&gt;&lt;falsepart&gt;]</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0o130</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- pop eax</span>\n <span style=\"color: #000000;\">0o205</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o300</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- test eax,eax</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #000000;\">tk_if</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">truesize</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">falsesize</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">gen_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">elsejmp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">falsesize</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">falsesize</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">127</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">offset</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">truesize</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">elsejmp</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">mainjmp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">offset</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">127</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">mainjmp</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0o164</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">offset</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- jz (short) else/end</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0o017</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o204</span><span style=\"color: #0000FF;\">}&</span><span style=\"color: #7060A8;\">int_to_bytes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">offset</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- jz (long) else/end</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">falsesize</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">offset</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">falsesize</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">elsejmp</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">0o353</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">offset</span> <span style=\"color: #000080;font-style:italic;\">-- jmp end if (short)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">0o351</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #7060A8;\">int_to_bytes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">offset</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- jmp end if (long)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_not</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0o132</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- pop edx</span>\n <span style=\"color: #000000;\">0o061</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o300</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- xor eax,eax</span>\n <span style=\"color: #000000;\">0o205</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o322</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- test edx,edx</span>\n <span style=\"color: #000000;\">0o017</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o224</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o300</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- setz al</span>\n <span style=\"color: #000000;\">0o120</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- push eax</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_neg</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0o130</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- pop eax</span>\n <span style=\"color: #000000;\">0o367</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o330</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- neg eax</span>\n <span style=\"color: #000000;\">0o120</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- push eax</span>\n <span style=\"color: #008080;\">else</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">error</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"error in code generator - found %d, expecting operator\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">actsize</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">initsize</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">estsize</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">actsize</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"9/0\"</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span> <span style=\"color: #000080;font-style:italic;\">-- (test gen_size)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">code_gen</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">--\n -- Generates proper machine code.\n --\n -- Example: i=10; print \"\\n\"; print i; print \"\\n\"\n -- Result in vars, strings, chain, code (declared above)\n -- where vars is: {\"i\"},\n -- strings is {\"\\n\"},\n -- code is { 0o150,#0A,#00,#00,#00, -- 1: push 10\n -- 0o217,0o005,0,1,1,0 -- 6: pop [i]\n -- 0o150,8,2,1,0, -- 12: push (\"\\n\")\n -- 0o350,13,3,3,0, -- 17: call :prints\n -- 0o377,0o065,18,1,1,0, -- 22: push [i]\n -- 0o350,24,3,2,0, -- 28: call :printi\n -- 0o150,29,2,1,0, -- 33: push (\"\\n\")\n -- 0o350,34,3,3,0, -- 38: call :prints\n -- 0o303} -- 43: ret\n -- and chain is 39 (-&gt;34-&gt;29-&gt;24-&gt;18-&gt;13-&gt;8-&gt;0)\n -- The chain connects all places where we need an actual address before\n -- the code is executed, with the byte after the link differentiating\n -- between var(1), string(2), and builtin(3), and the byte after that\n -- determining the instance of the given type - not that any of them\n -- are actually limited to a byte in the above intermediate form, and\n -- of course the trailing 0 of each {link,type,id,0} is just there to\n -- reserve the space we will need.\n --</span>\n <span style=\"color: #000000;\">gen_rec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">code</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o303</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- ret (0o303=#C3)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">builtins</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">VM</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">puts1</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span> <span style=\"color: #000080;font-style:italic;\">-- low-level console i/o routines</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">setbuiltins</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">printc</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">printi</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">prints</span>\n #ilASM{\n jmp :setbuiltins\n ::printc\n lea edi,[esp+4]\n mov esi,1\n call :%puts1ediesi -- (edi=raw text, esi=length)\n ret 4\n ::printi\n mov eax,[esp+4]\n push 0 -- no cr\n call :%putsint -- (nb limited to +/-9,999,999,999)\n ret 4\n ::prints\n mov edi,[esp+4]\n mov esi,[edi-12]\n call :%puts1ediesi -- (edi=raw text, esi=length)\n ret 4\n ::setbuiltins\n mov eax,:printc\n lea edi,[printc]\n call :%pStoreMint\n mov eax,:printi\n lea edi,[printi]\n call :%pStoreMint\n mov eax,:prints\n lea edi,[prints]\n call :%pStoreMint\n }\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">printc</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">printi</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">prints</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">builtin_names</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"printc\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"printi\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"prints\"</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">builtins</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">setbuiltins</span><span style=\"color: #0000FF;\">()</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">var_mem</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">code_mem</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">RawStringPtr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (based on IupRawStringPtr from pGUI.e)\n --\n -- Returns a raw string pointer for s, somewhat like allocate_string(s), but using the existing memory.\n -- NOTE: The return is only valid as long as the value passed as the parameter remains in existence.\n --</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">strings</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">]</span>\n #ilASM{\n mov eax,[s]\n lea edi,[res]\n shl eax,2\n call :%pStoreMint\n }\n <span style=\"color: #000000;\">stringptrs</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">fixup</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">var_mem</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">allocate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">vars</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mem_set</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">var_mem</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">vars</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">code_mem</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">allocate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">poke</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">chain</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #7060A8;\">this</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">chain</span>\n <span style=\"color: #000000;\">chain</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">this</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ftype</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">this</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">id</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">this</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">ftype</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000080;font-style:italic;\">-- vars</span>\n <span style=\"color: #7060A8;\">poke4</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">this</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">var_mem</span><span style=\"color: #0000FF;\">+(</span><span style=\"color: #000000;\">id</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000080;font-style:italic;\">-- strings</span>\n <span style=\"color: #7060A8;\">poke4</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">this</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">RawStringPtr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">id</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000080;font-style:italic;\">-- builtins</span>\n <span style=\"color: #7060A8;\">poke4</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">this</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">builtins</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">id</span><span style=\"color: #0000FF;\">]-(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">this</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n<!--\n", "language": "Phix" }, { "code": "(notonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Compiler\\cgen.exw\n -- ==============================\n --\n -- Generates 32-bit machine code (see note in vm.exw)\n --</span>\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span> <span style=\"color: #000080;font-style:italic;\">-- (machine code!)</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">cgen</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">get_var_name</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">addr</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">addr</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">var_mem</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">></span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">vars</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">vars</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">oh</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">fmt</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">args</span><span style=\"color: #0000FF;\">={})</span>\n <span style=\"color: #000080;font-style:italic;\">-- helper routine to display the octal/hex bytes just decoded,\n -- along with the code offset and the human-readable text.</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">args</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">fmt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fmt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">args</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">octhex</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">base</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">len</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #004080;\">integer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">oh</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000080;font-style:italic;\">-- all octal</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">oh</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">octhex</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">octhex</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"0o%03o\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">peek</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #000000;\">base</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">len</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">oh</span>\n <span style=\"color: #008080;\">else</span> <span style=\"color: #000080;font-style:italic;\">-- some octal and some hex</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">oh</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">oh</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">octhex</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">octhex</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"0o%03o\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">peek</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #000000;\">base</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">len</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">oh</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">oh</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">octhex</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">octhex</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"#%02x\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">peek</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #000000;\">base</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">len</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">oh</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">output_file</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%4d: %-30s %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">octhex</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\",\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">fmt</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">len</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">cccodes</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"o?\"</span> <span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"no?\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"b?\"</span> <span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ae?\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"z\"</span> <span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ne\"</span> <span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"be?\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"a?\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000080;font-style:italic;\">-- 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 ,</span>\n <span style=\"color: #008000;\">\"s?\"</span> <span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ns?\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"pe?\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"po?\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"l\"</span> <span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ge\"</span> <span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"le\"</span> <span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"g\"</span> <span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #000080;font-style:italic;\">-- 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">regs</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"eax\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ecx\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"edx\"</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- (others as/when needed)</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">decode</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000080;font-style:italic;\">-- for a much more complete (and better organised) disassembler, see p2asm.e</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- nb 0-based</span>\n <span style=\"color: #000000;\">opcode</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">xrm</span>\n\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">opcode</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">peek</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">xrm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">opcode</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o150</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">vaddr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">peek4s</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">vaddr</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">stringptrs</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">arg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">enquote</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">strings</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #0000FF;\">:</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">vaddr</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #008000;\">\"push %s\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">arg</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o217</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o377</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">opcode</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">0o217</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o377</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">op</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"pop\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"push\"</span><span style=\"color: #0000FF;\">}[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">xrm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">peek</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xrm</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">0o005</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o065</span><span style=\"color: #0000FF;\">})</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">addr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">peek4u</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #008000;\">\"%s [%s]\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">get_var_name</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">addr</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o061</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o071</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o205</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">opcode</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">0o061</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o071</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o205</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">op</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"xor\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"cmp\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"test\"</span><span style=\"color: #0000FF;\">}[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">xrm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">peek</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">and_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xrm</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o300</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">0o300</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">r1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">regs</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">and_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xrm</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o070</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">0o010</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">r2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">regs</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">and_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xrm</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o007</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s %s,%s\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">r1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">r2</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o017</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">xrm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">peek</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">xrm</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o224</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o225</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o234</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o235</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o236</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o237</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">cc</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">cccodes</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">and_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xrm</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o017</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">xrm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">peek</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">xrm</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0o300</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"set%s al\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">cc</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">xrm</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0o301</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"set%s cl\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">cc</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o204</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">offset</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">peek4s</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #008000;\">\"jz %d\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">offset</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o010</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o040</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">xrm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">peek</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">xrm</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0o310</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">lop</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"or\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"and\"</span><span style=\"color: #0000FF;\">}[</span><span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">opcode</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">0o010</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o040</span><span style=\"color: #0000FF;\">})]</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s al,cl\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">lop</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o120</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o122</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o130</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o131</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o132</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">op</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"push\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"pop\"</span><span style=\"color: #0000FF;\">}[</span><span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">and_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">opcode</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o070</span><span style=\"color: #0000FF;\">),{</span><span style=\"color: #000000;\">0o020</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o030</span><span style=\"color: #0000FF;\">})]</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">reg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">regs</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">and_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">opcode</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o007</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s %s\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">reg</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o231</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"cdq\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o164</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o353</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">jop</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">opcode</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0o164</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"jz\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"jmp\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">offset</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">peek1s</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #008000;\">\"%s %d\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">jop</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">offset</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o351</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">offset</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">peek4s</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #008000;\">\"jmp %d\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">offset</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o303</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ret\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o350</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">offset</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">peek4s</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">addr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">offset</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">5</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">addr</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">builtins</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #008000;\">\"call :%s\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">builtin_names</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">]})</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o001</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o041</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o051</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">opcode</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">0o001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o041</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o051</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">op</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"add\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"and\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"sub\"</span><span style=\"color: #0000FF;\">}[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">xrm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">peek</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">xrm</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o004</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">peek</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0o044</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s [esp],eax\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">0o367</span><span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000000;\">xrm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">peek</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">and_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xrm</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o300</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">0o300</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">and_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xrm</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o070</span><span style=\"color: #0000FF;\">),{</span><span style=\"color: #000000;\">0o030</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o040</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o070</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">op</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"neg\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"mul\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"idiv\"</span><span style=\"color: #0000FF;\">}[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">reg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">regs</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">and_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xrm</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0o007</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">pc</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">hxl</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s %s\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">reg</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"incomplete:\"</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">xrm</span><span style=\"color: #0000FF;\">=-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #0000FF;\">?{</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"0o%03o\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">opcode</span><span style=\"color: #0000FF;\">)}</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #0000FF;\">?{</span><span style=\"color: #000000;\">pc</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"0o%03o 0o%03o\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">opcode</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">xrm</span><span style=\"color: #0000FF;\">})}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cl</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">open_files</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cl</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">toks</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">lex</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">parse</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">code_gen</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">fixup</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">decode</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">free</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">var_mem</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">close_files</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000080;font-style:italic;\">--main(command_line())</span>\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"gcd.c\"</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "from __future__ import print_function\nimport sys, struct, shlex, operator\n\nnd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \\\nnd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \\\nnd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25)\n\nall_syms = {\n \"Identifier\" : nd_Ident, \"String\" : nd_String,\n \"Integer\" : nd_Integer, \"Sequence\" : nd_Sequence,\n \"If\" : nd_If, \"Prtc\" : nd_Prtc,\n \"Prts\" : nd_Prts, \"Prti\" : nd_Prti,\n \"While\" : nd_While, \"Assign\" : nd_Assign,\n \"Negate\" : nd_Negate, \"Not\" : nd_Not,\n \"Multiply\" : nd_Mul, \"Divide\" : nd_Div,\n \"Mod\" : nd_Mod, \"Add\" : nd_Add,\n \"Subtract\" : nd_Sub, \"Less\" : nd_Lss,\n \"LessEqual\" : nd_Leq, \"Greater\" : nd_Gtr,\n \"GreaterEqual\": nd_Geq, \"Equal\" : nd_Eql,\n \"NotEqual\" : nd_Neq, \"And\" : nd_And,\n \"Or\" : nd_Or}\n\nFETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, \\\nJMP, JZ, PRTC, PRTS, PRTI, HALT = range(24)\n\noperators = {nd_Lss: LT, nd_Gtr: GT, nd_Leq: LE, nd_Geq: GE, nd_Eql: EQ, nd_Neq: NE,\n nd_And: AND, nd_Or: OR, nd_Sub: SUB, nd_Add: ADD, nd_Div: DIV, nd_Mul: MUL, nd_Mod: MOD}\n\nunary_operators = {nd_Negate: NEG, nd_Not: NOT}\n\ninput_file = None\ncode = bytearray()\nstring_pool = {}\nglobals = {}\nstring_n = 0\nglobals_n = 0\nword_size = 4\n\n#*** show error and exit\ndef error(msg):\n print(\"%s\" % (msg))\n exit(1)\n\ndef int_to_bytes(val):\n return struct.pack(\"<i\", val)\n\ndef bytes_to_int(bstr):\n return struct.unpack(\"<i\", bstr)\n\nclass Node:\n def __init__(self, node_type, left = None, right = None, value = None):\n self.node_type = node_type\n self.left = left\n self.right = right\n self.value = value\n\n#***\ndef make_node(oper, left, right = None):\n return Node(oper, left, right)\n\n#***\ndef make_leaf(oper, n):\n return Node(oper, value = n)\n\n#***\ndef emit_byte(x):\n code.append(x)\n\n#***\ndef emit_word(x):\n s = int_to_bytes(x)\n for x in s:\n code.append(x)\n\ndef emit_word_at(at, n):\n code[at:at+word_size] = int_to_bytes(n)\n\ndef hole():\n t = len(code)\n emit_word(0)\n return t\n\n#***\ndef fetch_var_offset(name):\n global globals_n\n\n n = globals.get(name, None)\n if n == None:\n globals[name] = globals_n\n n = globals_n\n globals_n += 1\n return n\n\n#***\ndef fetch_string_offset(the_string):\n global string_n\n\n n = string_pool.get(the_string, None)\n if n == None:\n string_pool[the_string] = string_n\n n = string_n\n string_n += 1\n return n\n\n#***\ndef code_gen(x):\n if x == None: return\n elif x.node_type == nd_Ident:\n emit_byte(FETCH)\n n = fetch_var_offset(x.value)\n emit_word(n)\n elif x.node_type == nd_Integer:\n emit_byte(PUSH)\n emit_word(x.value)\n elif x.node_type == nd_String:\n emit_byte(PUSH)\n n = fetch_string_offset(x.value)\n emit_word(n)\n elif x.node_type == nd_Assign:\n n = fetch_var_offset(x.left.value)\n code_gen(x.right)\n emit_byte(STORE)\n emit_word(n)\n elif x.node_type == nd_If:\n code_gen(x.left) # expr\n emit_byte(JZ) # if false, jump\n p1 = hole() # make room for jump dest\n code_gen(x.right.left) # if true statements\n if (x.right.right != None):\n emit_byte(JMP) # jump over else statements\n p2 = hole()\n emit_word_at(p1, len(code) - p1)\n if (x.right.right != None):\n code_gen(x.right.right) # else statements\n emit_word_at(p2, len(code) - p2)\n elif x.node_type == nd_While:\n p1 = len(code)\n code_gen(x.left)\n emit_byte(JZ)\n p2 = hole()\n code_gen(x.right)\n emit_byte(JMP) # jump back to the top\n emit_word(p1 - len(code))\n emit_word_at(p2, len(code) - p2)\n elif x.node_type == nd_Sequence:\n code_gen(x.left)\n code_gen(x.right)\n elif x.node_type == nd_Prtc:\n code_gen(x.left)\n emit_byte(PRTC)\n elif x.node_type == nd_Prti:\n code_gen(x.left)\n emit_byte(PRTI)\n elif x.node_type == nd_Prts:\n code_gen(x.left)\n emit_byte(PRTS)\n elif x.node_type in operators:\n code_gen(x.left)\n code_gen(x.right)\n emit_byte(operators[x.node_type])\n elif x.node_type in unary_operators:\n code_gen(x.left)\n emit_byte(unary_operators[x.node_type])\n else:\n error(\"error in code generator - found %d, expecting operator\" % (x.node_type))\n\n#***\ndef code_finish():\n emit_byte(HALT)\n\n#***\ndef list_code():\n print(\"Datasize: %d Strings: %d\" % (len(globals), len(string_pool)))\n\n for k in sorted(string_pool, key=string_pool.get):\n print(k)\n\n pc = 0\n while pc < len(code):\n print(\"%4d \" % (pc), end='')\n op = code[pc]\n pc += 1\n if op == FETCH:\n x = bytes_to_int(code[pc:pc+word_size])[0]\n print(\"fetch [%d]\" % (x));\n pc += word_size\n elif op == STORE:\n x = bytes_to_int(code[pc:pc+word_size])[0]\n print(\"store [%d]\" % (x));\n pc += word_size\n elif op == PUSH:\n x = bytes_to_int(code[pc:pc+word_size])[0]\n print(\"push %d\" % (x));\n pc += word_size\n elif op == ADD: print(\"add\")\n elif op == SUB: print(\"sub\")\n elif op == MUL: print(\"mul\")\n elif op == DIV: print(\"div\")\n elif op == MOD: print(\"mod\")\n elif op == LT: print(\"lt\")\n elif op == GT: print(\"gt\")\n elif op == LE: print(\"le\")\n elif op == GE: print(\"ge\")\n elif op == EQ: print(\"eq\")\n elif op == NE: print(\"ne\")\n elif op == AND: print(\"and\")\n elif op == OR: print(\"or\")\n elif op == NEG: print(\"neg\")\n elif op == NOT: print(\"not\")\n elif op == JMP:\n x = bytes_to_int(code[pc:pc+word_size])[0]\n print(\"jmp (%d) %d\" % (x, pc + x));\n pc += word_size\n elif op == JZ:\n x = bytes_to_int(code[pc:pc+word_size])[0]\n print(\"jz (%d) %d\" % (x, pc + x));\n pc += word_size\n elif op == PRTC: print(\"prtc\")\n elif op == PRTI: print(\"prti\")\n elif op == PRTS: print(\"prts\")\n elif op == HALT: print(\"halt\")\n else: error(\"list_code: Unknown opcode %d\", (op));\n\ndef load_ast():\n line = input_file.readline()\n line_list = shlex.split(line, False, False)\n\n text = line_list[0]\n if text == \";\":\n return None\n node_type = all_syms[text]\n\n if len(line_list) > 1:\n value = line_list[1]\n if value.isdigit():\n value = int(value)\n return make_leaf(node_type, value)\n\n left = load_ast()\n right = load_ast()\n return make_node(node_type, left, right)\n\n#*** main driver\ninput_file = sys.stdin\nif len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], \"r\", 4096)\n except IOError as e:\n error(\"Can't open %s\" % sys.argv[1])\n\nn = load_ast()\ncode_gen(n)\ncode_finish()\nlist_code()\n", "language": "Python" }, { "code": "my %opnames = <\n Less lt LessEqual le Multiply mul Subtract sub NotEqual ne\n Divide div GreaterEqual ge Equal eq Greater gt Negate neg\n>;\n\nmy (@AST, %strings, %names);\nmy $string-count = my $name-count = my $pairsym = my $pc = 0;\n\nsub tree {\n my ($A, $B) = ( '_' ~ ++$pairsym, '_' ~ ++$pairsym );\n my $line = @AST.shift // return '';\n $line ~~ /^ $<instr> = (\\w+|';') [\\s+ $<arg> =(.*)]? / or die \"bad input $line\";\n given $<instr> {\n when 'Identifier' { \"fetch [{%names{$<arg>} //= $name-count++ }]\\n\" }\n when 'Sequence' { tree() ~ tree() }\n when 'Integer' { \"push $<arg>\\n\" }\n when 'String' { \"push { %strings{$<arg>} //= $string-count++ }\\n\" }\n when 'Assign' { join '', reverse (tree().subst( /fetch/, 'store')), tree() }\n when 'While' { \"$A:\\n{ tree() }jz $B\\n{ tree() }jmp $A\\n$B:\\n\" }\n when 'If' { tree() ~ \"jz $A\\n{ [email protected] ~ tree() }jmp $B\\n$A:\\n{ tree() }$B:\\n\" }\n when ';' { '' }\n default { tree() ~ tree() ~ (%opnames{$<instr>} // $<instr>.lc) ~ \"\\n\" }\n }\n}\n\n@AST = slurp('ast.txt').lines;\nmy $code = tree() ~ \"halt\\n\";\n\n$code ~~ s:g/^^ jmp \\s+ (\\S+) \\n ('_'\\d+:\\n) $0:\\n/$1/; # remove jmp next\n$code ~~ s:g/^^ (<[a..z]>\\w* (\\N+)? ) $$/{my $l=$pc.fmt(\"%4d \"); $pc += $0[0] ?? 5 !! 1; $l}$0/; # add locations\nmy %labels = ($code ~~ m:g/^^ ('_' \\d+) ':' \\n \\s* (\\d+)/)».Slip».Str; # pc addr of labels\n$code ~~ s:g/^^ \\s* (\\d+) \\s j[z|mp] \\s* <(('_'\\d+)/ ({%labels{$1} - $0 - 1}) %labels{$1}/; # fix jumps\n$code ~~ s:g/^^ '_'\\d+.*?\\n//; # remove labels\n\nsay \"Datasize: $name-count Strings: $string-count\\n\"\n ~ join('', %strings.keys.sort.reverse «~» \"\\n\")\n ~ $code;\n", "language": "Raku" }, { "code": "######################################################################\n#\n# The Rosetta Code code generator in Ratfor 77.\n#\n#\n# In FORTRAN 77 and therefore in Ratfor 77, there is no way to specify\n# that a value should be put on a call stack. Therefore there is no\n# way to implement recursive algorithms in Ratfor 77 (although see the\n# Ratfor for the \"syntax analyzer\" task, where a recursive language is\n# implemented *in* Ratfor). We are forced to use non-recursive\n# algorithms.\n#\n# How to deal with FORTRAN 77 input is another problem. I use\n# formatted input, treating each line as an array of type\n# CHARACTER--regrettably of no more than some predetermined, finite\n# length. It is a very simple method and presents no significant\n# difficulties, aside from the restriction on line length of the\n# input.\n#\n#\n# On a POSIX platform, the program can be compiled with f2c and run\n# somewhat as follows:\n#\n# ratfor77 gen-in-ratfor.r > gen-in-ratfor.f\n# f2c -C -Nc80 gen-in-ratfor.f\n# cc gen-in-ratfor.c -lf2c\n# ./a.out < compiler-tests/primes.ast\n#\n# With gfortran, a little differently:\n#\n# ratfor77 gen-in-ratfor.r > gen-in-ratfor.f\n# gfortran -fcheck=all -std=legacy gen-in-ratfor.f\n# ./a.out < compiler-tests/primes.ast\n#\n#\n# I/O is strictly from default input and to default output, which, on\n# POSIX systems, usually correspond respectively to standard input and\n# standard output. (I did not wish to have to deal with unit numbers;\n# these are now standardized in ISO_FORTRAN_ENV, but that is not\n# available in FORTRAN 77.)\n#\n#---------------------------------------------------------------------\n\n# Some parameters you may wish to modify.\n\ndefine(LINESZ, 256) # Size of an input line.\ndefine(OUTLSZ, 1024) # Size of an output line.\ndefine(STRNSZ, 4096) # Size of the string pool.\ndefine(NODSSZ, 4096) # Size of the nodes pool.\ndefine(STCKSZ, 4096) # Size of stacks.\ndefine(MAXVAR, 256) # Maximum number of variables.\ndefine(MAXSTR, 256) # Maximum number of strings.\ndefine(CODESZ, 16384) # Maximum size of a compiled program.\n\n#---------------------------------------------------------------------\n\ndefine(NEWLIN, 10) # The Unix newline character (ASCII LF).\ndefine(DQUOTE, 34) # The double quote character.\ndefine(BACKSL, 92) # The backslash character.\n\n#---------------------------------------------------------------------\n\ndefine(NODESZ, 3)\ndefine(NNEXTF, 1) # Index for next-free.\ndefine(NTAG, 1) # Index for the tag.\n # For an internal node --\ndefine(NLEFT, 2) # Index for the left node.\ndefine(NRIGHT, 3) # Index for the right node.\n # For a leaf node --\ndefine(NITV, 2) # Index for the string pool index.\ndefine(NITN, 3) # Length of the value.\n\ndefine(NIL, -1) # Nil node.\n\ndefine(RGT, 10000)\ndefine(STAGE2, 20000)\ndefine(STAGE3, 30000)\ndefine(STAGE4, 40000)\n\n# The following all must be less than RGT.\ndefine(NDID, 0)\ndefine(NDSTR, 1)\ndefine(NDINT, 2)\ndefine(NDSEQ, 3)\ndefine(NDIF, 4)\ndefine(NDPRTC, 5)\ndefine(NDPRTS, 6)\ndefine(NDPRTI, 7)\ndefine(NDWHIL, 8)\ndefine(NDASGN, 9)\ndefine(NDNEG, 10)\ndefine(NDNOT, 11)\ndefine(NDMUL, 12)\ndefine(NDDIV, 13)\ndefine(NDMOD, 14)\ndefine(NDADD, 15)\ndefine(NDSUB, 16)\ndefine(NDLT, 17)\ndefine(NDLE, 18)\ndefine(NDGT, 19)\ndefine(NDGE, 20)\ndefine(NDEQ, 21)\ndefine(NDNE, 22)\ndefine(NDAND, 23)\ndefine(NDOR, 24)\n\ndefine(OPHALT, 1)\ndefine(OPADD, 2)\ndefine(OPSUB, 3)\ndefine(OPMUL, 4)\ndefine(OPDIV, 5)\ndefine(OPMOD, 6)\ndefine(OPLT, 7)\ndefine(OPGT, 8)\ndefine(OPLE, 9)\ndefine(OPGE, 10)\ndefine(OPEQ, 11)\ndefine(OPNE, 12)\ndefine(OPAND, 13)\ndefine(OPOR, 14)\ndefine(OPNEG, 15)\ndefine(OPNOT, 16)\ndefine(OPPRTC, 17)\ndefine(OPPRTI, 18)\ndefine(OPPRTS, 19)\ndefine(OPFTCH, 20)\ndefine(OPSTOR, 21)\ndefine(OPPUSH, 22)\ndefine(OPJMP, 23)\ndefine(OPJZ, 24)\n\n#---------------------------------------------------------------------\n\nfunction issp (c)\n\n # Is a character a space character?\n\n implicit none\n\n character c\n logical issp\n\n integer ic\n\n ic = ichar (c)\n issp = (ic == 32 || (9 <= ic && ic <= 13))\nend\n\nfunction skipsp (str, i, imax)\n\n # Skip past spaces in a string.\n\n implicit none\n\n character str(*)\n integer i\n integer imax\n integer skipsp\n\n logical issp\n\n logical done\n\n skipsp = i\n done = .false.\n while (!done)\n {\n if (imax <= skipsp)\n done = .true.\n else if (!issp (str(skipsp)))\n done = .true.\n else\n skipsp = skipsp + 1\n }\nend\n\nfunction skipns (str, i, imax)\n\n # Skip past non-spaces in a string.\n\n implicit none\n\n character str(*)\n integer i\n integer imax\n integer skipns\n\n logical issp\n\n logical done\n\n skipns = i\n done = .false.\n while (!done)\n {\n if (imax <= skipns)\n done = .true.\n else if (issp (str(skipns)))\n done = .true.\n else\n skipns = skipns + 1\n }\nend\n\nfunction trimrt (str, n)\n\n # Find the length of a string, if one ignores trailing spaces.\n\n implicit none\n\n character str(*)\n integer n\n integer trimrt\n\n logical issp\n\n logical done\n\n trimrt = n\n done = .false.\n while (!done)\n {\n if (trimrt == 0)\n done = .true.\n else if (!issp (str(trimrt)))\n done = .true.\n else\n trimrt = trimrt - 1\n }\nend\n\n#---------------------------------------------------------------------\n\nsubroutine addstr (strngs, istrng, src, i0, n0, i, n)\n\n # Add a string to the string pool.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character src(*) # Source string.\n integer i0, n0 # Index and length in source string.\n integer i, n # Index and length in string pool.\n\n integer j\n\n if (STRNSZ < istrng + (n0 - 1))\n {\n write (*, '(''string pool exhausted'')')\n stop\n }\n if (n0 == 0)\n {\n i = 0\n n = 0\n }\n else\n {\n for (j = 0; j < n0; j = j + 1)\n strngs(istrng + j) = src(i0 + j)\n i = istrng\n n = n0\n istrng = istrng + n0\n }\nend\n\n#---------------------------------------------------------------------\n\nsubroutine push (stack, sp, i)\n\n implicit none\n\n integer stack(STCKSZ)\n integer sp # Stack pointer.\n integer i # Value to push.\n\n if (sp == STCKSZ)\n {\n write (*, '(''stack overflow in push'')')\n stop\n }\n stack(sp) = i\n sp = sp + 1\nend\n\nfunction pop (stack, sp)\n\n implicit none\n\n integer stack(STCKSZ)\n integer sp # Stack pointer.\n integer pop\n\n if (sp == 1)\n {\n write (*, '(''stack underflow in pop'')')\n stop\n }\n sp = sp - 1\n pop = stack(sp)\nend\n\nfunction nstack (sp)\n\n implicit none\n\n integer sp # Stack pointer.\n integer nstack\n\n nstack = sp - 1 # Current cardinality of the stack.\nend\n\n#---------------------------------------------------------------------\n\nsubroutine initnd (nodes, frelst)\n\n # Initialize the nodes pool.\n\n implicit none\n\n integer nodes (NODESZ, NODSSZ)\n integer frelst # Head of the free list.\n\n integer i\n\n for (i = 1; i < NODSSZ; i = i + 1)\n nodes(NNEXTF, i) = i + 1\n nodes(NNEXTF, NODSSZ) = NIL\n frelst = 1\nend\n\nsubroutine newnod (nodes, frelst, i)\n\n # Get the index for a new node taken from the free list.\n\n integer nodes (NODESZ, NODSSZ)\n integer frelst # Head of the free list.\n integer i # Index of the new node.\n\n integer j\n\n if (frelst == NIL)\n {\n write (*, '(''nodes pool exhausted'')')\n stop\n }\n i = frelst\n frelst = nodes(NNEXTF, frelst)\n for (j = 1; j <= NODESZ; j = j + 1)\n nodes(j, i) = 0\nend\n\nsubroutine frenod (nodes, frelst, i)\n\n # Return a node to the free list.\n\n integer nodes (NODESZ, NODSSZ)\n integer frelst # Head of the free list.\n integer i # Index of the node to free.\n\n nodes(NNEXTF, i) = frelst\n frelst = i\nend\n\nfunction strtag (str, i, n)\n\n implicit none\n\n character str(*)\n integer i, n\n integer strtag\n\n character*16 s\n integer j\n\n for (j = 0; j < 16; j = j + 1)\n if (j < n)\n s(j + 1 : j + 1) = str(i + j)\n else\n s(j + 1 : j + 1) = ' '\n\n if (s == \"Identifier \")\n strtag = NDID\n else if (s == \"String \")\n strtag = NDSTR\n else if (s == \"Integer \")\n strtag = NDINT\n else if (s == \"Sequence \")\n strtag = NDSEQ\n else if (s == \"If \")\n strtag = NDIF\n else if (s == \"Prtc \")\n strtag = NDPRTC\n else if (s == \"Prts \")\n strtag = NDPRTS\n else if (s == \"Prti \")\n strtag = NDPRTI\n else if (s == \"While \")\n strtag = NDWHIL\n else if (s == \"Assign \")\n strtag = NDASGN\n else if (s == \"Negate \")\n strtag = NDNEG\n else if (s == \"Not \")\n strtag = NDNOT\n else if (s == \"Multiply \")\n strtag = NDMUL\n else if (s == \"Divide \")\n strtag = NDDIV\n else if (s == \"Mod \")\n strtag = NDMOD\n else if (s == \"Add \")\n strtag = NDADD\n else if (s == \"Subtract \")\n strtag = NDSUB\n else if (s == \"Less \")\n strtag = NDLT\n else if (s == \"LessEqual \")\n strtag = NDLE\n else if (s == \"Greater \")\n strtag = NDGT\n else if (s == \"GreaterEqual \")\n strtag = NDGE\n else if (s == \"Equal \")\n strtag = NDEQ\n else if (s == \"NotEqual \")\n strtag = NDNE\n else if (s == \"And \")\n strtag = NDAND\n else if (s == \"Or \")\n strtag = NDOR\n else if (s == \"; \")\n strtag = NIL\n else\n {\n write (*, '(''unrecognized input line: '', A16)') s\n stop\n }\nend\n\nsubroutine readln (strngs, istrng, tag, iarg, narg)\n\n # Read a line of the AST input.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n integer tag # The node tag or NIL.\n integer iarg # Index of an argument in the string pool.\n integer narg # Length of an argument in the string pool.\n\n integer trimrt\n integer strtag\n integer skipsp\n integer skipns\n\n character line(LINESZ)\n character*20 fmt\n integer i, j, n\n\n # Read a line of text as an array of characters.\n write (fmt, '(''('', I10, ''A)'')') LINESZ\n read (*, fmt) line\n\n n = trimrt (line, LINESZ)\n\n i = skipsp (line, 1, n + 1)\n j = skipns (line, i, n + 1)\n tag = strtag (line, i, j - i)\n\n i = skipsp (line, j, n + 1)\n call addstr (strngs, istrng, line, i, (n + 1) - i, iarg, narg)\nend\n\nfunction hasarg (tag)\n\n implicit none\n\n integer tag\n logical hasarg\n\n hasarg = (tag == NDID || tag == NDINT || tag == NDSTR)\nend\n\nsubroutine rdast (strngs, istrng, nodes, frelst, iast)\n\n # Read in the AST. A non-recursive algorithm is used.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n integer nodes (NODESZ, NODSSZ) # Nodes pool.\n integer frelst # Head of the free list.\n integer iast # Index of root node of the AST.\n\n integer nstack\n integer pop\n logical hasarg\n\n integer stack(STCKSZ)\n integer sp # Stack pointer.\n integer tag, iarg, narg\n integer i, j, k\n\n sp = 1\n\n call readln (strngs, istrng, tag, iarg, narg)\n if (tag == NIL)\n iast = NIL\n else\n {\n call newnod (nodes, frelst, i)\n iast = i\n nodes(NTAG, i) = tag\n nodes(NITV, i) = 0\n nodes(NITN, i) = 0\n if (hasarg (tag))\n {\n nodes(NITV, i) = iarg\n nodes(NITN, i) = narg\n }\n else\n {\n call push (stack, sp, i + RGT)\n call push (stack, sp, i)\n while (nstack (sp) != 0)\n {\n j = pop (stack, sp)\n k = mod (j, RGT)\n call readln (strngs, istrng, tag, iarg, narg)\n if (tag == NIL)\n i = NIL\n else\n {\n call newnod (nodes, frelst, i)\n nodes(NTAG, i) = tag\n if (hasarg (tag))\n {\n nodes(NITV, i) = iarg\n nodes(NITN, i) = narg\n }\n else\n {\n call push (stack, sp, i + RGT)\n call push (stack, sp, i)\n }\n }\n if (j == k)\n nodes(NLEFT, k) = i\n else\n nodes(NRIGHT, k) = i\n }\n }\n }\nend\n\n#---------------------------------------------------------------------\n\nsubroutine flushl (outbuf, noutbf)\n\n # Flush a line from the output buffer.\n\n implicit none\n\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n\n character*20 fmt\n integer i\n\n if (noutbf == 0)\n write (*, '()')\n else\n {\n write (fmt, 1000) noutbf\n1000 format ('(', I10, 'A)')\n write (*, fmt) (outbuf(i), i = 1, noutbf)\n noutbf = 0\n }\nend\n\nsubroutine wrtchr (outbuf, noutbf, ch)\n\n # Write a character to output.\n\n implicit none\n\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n character ch # The character to output.\n\n # This routine silently truncates anything that goes past the buffer\n # boundary.\n\n if (ch == char (NEWLIN))\n call flushl (outbuf, noutbf)\n else if (noutbf < OUTLSZ)\n {\n noutbf = noutbf + 1\n outbuf(noutbf) = ch\n }\nend\n\nsubroutine wrtstr (outbuf, noutbf, str, i, n)\n\n # Write a substring to output.\n\n implicit none\n\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n character str(*) # The string from which to output.\n integer i, n # Index and length of the substring.\n\n integer j\n\n for (j = 0; j < n; j = j + 1)\n call wrtchr (outbuf, noutbf, str(i + j))\nend\n\nsubroutine wrtint (outbuf, noutbf, ival, colcnt)\n\n # Write a non-negative integer to output.\n\n implicit none\n\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n integer ival # The non-negative integer to print.\n integer colcnt # Column count, or zero for free format.\n\n integer skipsp\n\n character*40 buf\n integer i, j\n\n write (buf, '(I40)') ival\n i = skipsp (buf, 1, 41)\n if (0 < colcnt)\n for (j = 1; j < colcnt - (40 - i); j = j + 1)\n call wrtchr (outbuf, noutbf, ' ')\n while (i <= 40)\n {\n call wrtchr (outbuf, noutbf, buf(i:i))\n i = i + 1\n }\nend\n\n#---------------------------------------------------------------------\n\ndefine(VARSZ, 3)\ndefine(VNAMEI, 1) # Variable name's index in the string pool.\ndefine(VNAMEN, 2) # Length of the name.\ndefine(VVALUE, 3) # Variable's number in the VM's data pool.\n\nfunction fndvar (vars, numvar, strngs, istrng, i0, n0)\n\n implicit none\n\n integer vars(VARSZ, MAXVAR) # Variables.\n integer numvar # Number of variables.\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n integer i0, n0 # Index and length in the string pool.\n integer fndvar # The location of the variable.\n\n integer j, k\n integer i, n\n logical done1\n logical done2\n\n j = 1\n done1 = .false.\n while (!done1)\n if (j == numvar + 1)\n done1 = .true.\n else if (n0 == vars(VNAMEN, j))\n {\n k = 0\n done2 = .false.\n while (!done2)\n if (n0 <= k)\n done2 = .true.\n else if (strngs(i0 + k) == strngs(vars(VNAMEI, j) + k))\n k = k + 1\n else\n done2 = .true.\n if (k < n0)\n j = j + 1\n else\n {\n done2 = .true.\n done1 = .true.\n }\n }\n else\n j = j + 1\n\n if (j == numvar + 1)\n {\n if (numvar == MAXVAR)\n {\n write (*, '(''too many variables'')')\n stop\n }\n numvar = numvar + 1\n call addstr (strngs, istrng, strngs, i0, n0, i, n)\n vars(VNAMEI, numvar) = i\n vars(VNAMEN, numvar) = n\n vars(VVALUE, numvar) = numvar - 1\n fndvar = numvar\n }\n else\n fndvar = j\nend\n\ndefine(STRSZ, 3)\ndefine(STRI, 1) # String's index in this program's string pool.\ndefine(STRN, 2) # Length of the string.\ndefine(STRNO, 3) # String's number in the VM's string pool.\n\nfunction fndstr (strs, numstr, strngs, istrng, i0, n0)\n\n implicit none\n\n integer strs(STRSZ, MAXSTR) # Strings for the VM's string pool.\n integer numstr # Number of such strings.\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n integer i0, n0 # Index and length in the string pool.\n integer fndstr # The location of the string in the VM's string pool.\n\n integer j, k\n integer i, n\n logical done1\n logical done2\n\n j = 1\n done1 = .false.\n while (!done1)\n if (j == numstr + 1)\n done1 = .true.\n else if (n0 == strs(STRN, j))\n {\n k = 0\n done2 = .false.\n while (!done2)\n if (n0 <= k)\n done2 = .true.\n else if (strngs(i0 + k) == strngs(strs(STRI, j) + k))\n k = k + 1\n else\n done2 = .true.\n if (k < n0)\n j = j + 1\n else\n {\n done2 = .true.\n done1 = .true.\n }\n }\n else\n j = j + 1\n\n if (j == numstr + 1)\n {\n if (numstr == MAXSTR)\n {\n write (*, '(''too many string literals'')')\n stop\n }\n numstr = numstr + 1\n call addstr (strngs, istrng, strngs, i0, n0, i, n)\n strs(STRI, numstr) = i\n strs(STRN, numstr) = n\n strs(STRNO, numstr) = numstr - 1\n fndstr = numstr\n }\n else\n fndstr = j\nend\n\nfunction strint (strngs, i, n)\n\n # Convert a string to a non-negative integer.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer i, n\n integer strint\n\n integer j\n\n strint = 0\n for (j = 0; j < n; j = j + 1)\n strint = (10 * strint) + (ichar (strngs(i + j)) - ichar ('0'))\nend\n\nsubroutine put1 (code, ncode, i, opcode)\n\n # Store a 1-byte operation.\n\n implicit none\n\n integer code(0 : CODESZ - 1) # Generated code.\n integer ncode # Number of VM bytes in the code.\n integer i # Address to put the code at.\n integer opcode\n\n if (CODESZ - i < 1)\n {\n write (*, '(''address beyond the size of memory'')')\n stop\n }\n code(i) = opcode\n ncode = max (ncode, i + 1)\nend\n\nsubroutine put5 (code, ncode, i, opcode, ival)\n\n # Store a 5-byte operation.\n\n implicit none\n\n integer code(0 : CODESZ - 1) # Generated code.\n integer ncode # Number of VM bytes in the code.\n integer i # Address to put the code at.\n integer opcode\n integer ival # Immediate integer value.\n\n if (CODESZ - i < 5)\n {\n write (*, '(''address beyond the size of memory'')')\n stop\n }\n code(i) = opcode\n code(i + 1) = ival # Do not bother to break the integer into bytes.\n code(i + 2) = 0\n code(i + 3) = 0\n code(i + 4) = 0\n ncode = max (ncode, i + 5)\nend\n\nsubroutine compil (vars, numvar, _\n strs, numstr, _\n strngs, istrng, _\n nodes, frelst, _\n code, ncode, iast)\n\n # Compile the AST to virtual machine code. The algorithm employed is\n # non-recursive.\n\n implicit none\n\n integer vars(VARSZ, MAXVAR) # Variables.\n integer numvar # Number of variables.\n integer strs(STRSZ, MAXSTR) # Strings for the VM's string pool.\n integer numstr # Number of such strings.\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n integer nodes (NODESZ, NODSSZ) # Nodes pool.\n integer frelst # Head of the free list.\n integer code(0 : CODESZ - 1) # Generated code.\n integer ncode # Number of VM bytes in the code.\n integer iast # Root node of the AST.\n\n integer fndvar\n integer fndstr\n integer nstack\n integer pop\n integer strint\n\n integer xstack(STCKSZ) # Node stack.\n integer ixstck # Node stack pointer.\n integer i\n integer i0, n0\n integer tag\n integer ivar\n integer inode1, inode2, inode3\n integer addr1, addr2\n\n ixstck = 1\n call push (xstack, ixstck, iast)\n while (nstack (ixstck) != 0)\n {\n i = pop (xstack, ixstck)\n if (i == NIL)\n tag = NIL\n else\n tag = nodes(NTAG, i)\n if (tag == NIL)\n continue\n else if (tag < STAGE2)\n {\n if (tag == NDSEQ)\n {\n if (nodes(NRIGHT, i) != NIL)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n if (nodes(NLEFT, i) != NIL)\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDID)\n {\n # Fetch the value of a variable.\n i0 = nodes(NITV, i)\n n0 = nodes(NITN, i)\n ivar = fndvar (vars, numvar, strngs, istrng, i0, n0)\n ivar = vars(VVALUE, ivar)\n call put5 (code, ncode, ncode, OPFTCH, ivar)\n }\n else if (tag == NDINT)\n {\n # Push the value of an integer literal.\n i0 = nodes(NITV, i)\n n0 = nodes(NITN, i)\n call put5 (code, ncode, ncode, OPPUSH, _\n strint (strngs, i0, n0))\n }\n else if (tag == NDNEG)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDNEG + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDNOT)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDNOT + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDAND)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDAND + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDOR)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDOR + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDADD)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDADD + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDSUB)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDSUB + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDMUL)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDMUL + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDDIV)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDDIV + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDMOD)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDMOD + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDLT)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDLT + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDLE)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDLE + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDGT)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDGT + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDGE)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDGE + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDEQ)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDEQ + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDNE)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDNE + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDASGN)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDASGN + STAGE2\n nodes(NITV, inode1) = nodes(NITV, nodes(NLEFT, i))\n nodes(NITN, inode1) = nodes(NITN, nodes(NLEFT, i))\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NRIGHT, i))\n }\n else if (tag == NDPRTS)\n {\n i0 = nodes(NITV, nodes(NLEFT, i))\n n0 = nodes(NITN, nodes(NLEFT, i))\n ivar = fndstr (strs, numstr, strngs, istrng, i0, n0)\n ivar = strs(STRNO, ivar)\n call put5 (code, ncode, ncode, OPPUSH, ivar)\n call put1 (code, ncode, ncode, OPPRTS)\n }\n else if (tag == NDPRTC)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDPRTC + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDPRTI)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDPRTI + STAGE2\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDWHIL)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDWHIL + STAGE2\n nodes(NLEFT, inode1) = nodes(NRIGHT, i) # Loop body.\n nodes(NRIGHT, inode1) = ncode # Addr. of top of loop.\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n else if (tag == NDIF)\n {\n call newnod (nodes, frelst, inode1)\n nodes(NTAG, inode1) = NDIF + STAGE2\n # The \"then\" and \"else\" clauses, respectively:\n nodes(NLEFT, inode1) = nodes(NLEFT, nodes(NRIGHT, i))\n nodes(NRIGHT, inode1) = nodes(NRIGHT, nodes(NRIGHT, i))\n call push (xstack, ixstck, inode1)\n call push (xstack, ixstck, nodes(NLEFT, i))\n }\n }\n else\n {\n if (tag == NDNEG + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPNEG)\n }\n else if (tag == NDNOT + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPNOT)\n }\n else if (tag == NDAND + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPAND)\n }\n else if (tag == NDOR + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPOR)\n }\n else if (tag == NDADD + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPADD)\n }\n else if (tag == NDSUB + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPSUB)\n }\n else if (tag == NDMUL + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPMUL)\n }\n else if (tag == NDDIV + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPDIV)\n }\n else if (tag == NDMOD + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPMOD)\n }\n else if (tag == NDLT + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPLT)\n }\n else if (tag == NDLE + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPLE)\n }\n else if (tag == NDGT + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPGT)\n }\n else if (tag == NDGE + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPGE)\n }\n else if (tag == NDEQ + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPEQ)\n }\n else if (tag == NDNE + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPNE)\n }\n else if (tag == NDASGN + STAGE2)\n {\n i0 = nodes(NITV, i)\n n0 = nodes(NITN, i)\n call frenod (nodes, frelst, i)\n ivar = fndvar (vars, numvar, strngs, istrng, i0, n0)\n ivar = vars(VVALUE, ivar)\n call put5 (code, ncode, ncode, OPSTOR, ivar)\n }\n else if (tag == NDPRTC + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPPRTC)\n }\n else if (tag == NDPRTI + STAGE2)\n {\n call frenod (nodes, frelst, i)\n call put1 (code, ncode, ncode, OPPRTI)\n }\n else if (tag == NDWHIL + STAGE2)\n {\n inode1 = nodes(NLEFT, i) # Loop body.\n addr1 = nodes(NRIGHT, i) # Addr. of top of loop.\n call frenod (nodes, frelst, i)\n call put5 (code, ncode, ncode, OPJZ, 0)\n call newnod (nodes, frelst, inode2)\n nodes(NTAG, inode2) = NDWHIL + STAGE3\n nodes(NLEFT, inode2) = addr1 # Top of loop.\n nodes(NRIGHT, inode2) = ncode - 4 # Fixup address.\n call push (xstack, ixstck, inode2)\n call push (xstack, ixstck, inode1)\n }\n else if (tag == NDWHIL + STAGE3)\n {\n addr1 = nodes(NLEFT, i) # Top of loop.\n addr2 = nodes(NRIGHT, i) # Fixup address.\n call frenod (nodes, frelst, i)\n call put5 (code, ncode, ncode, OPJMP, addr1)\n code(addr2) = ncode\n }\n else if (tag == NDIF + STAGE2)\n {\n inode1 = nodes(NLEFT, i) # \"Then\" clause.\n inode2 = nodes(NRIGHT, i) # \"Else\" clause.\n call frenod (nodes, frelst, i)\n call put5 (code, ncode, ncode, OPJZ, 0)\n call newnod (nodes, frelst, inode3)\n nodes(NTAG, inode3) = NDIF + STAGE3\n nodes(NLEFT, inode3) = ncode - 4 # Fixup address.\n nodes(NRIGHT, inode3) = inode2 # \"Else\" clause.\n call push (xstack, ixstck, inode3)\n call push (xstack, ixstck, inode1)\n }\n else if (tag == NDIF + STAGE3)\n {\n addr1 = nodes(NLEFT, i) # Fixup address.\n inode1 = nodes(NRIGHT, i) # \"Else\" clause.\n call frenod (nodes, frelst, i)\n if (inode2 == NIL)\n code(addr1) = ncode\n else\n {\n call put5 (code, ncode, ncode, OPJMP, 0)\n addr2 = ncode - 4 # Another fixup address.\n code(addr1) = ncode\n call newnod (nodes, frelst, inode2)\n nodes(NTAG, inode2) = NDIF + STAGE4\n nodes(NLEFT, inode2) = addr2\n call push (xstack, ixstck, inode2)\n call push (xstack, ixstck, inode1)\n }\n }\n else if (tag == NDIF + STAGE4)\n {\n addr1 = nodes(NLEFT, i) # Fixup address.\n call frenod (nodes, frelst, i)\n code(addr1) = ncode\n }\n }\n }\n call put1 (code, ncode, ncode, OPHALT)\nend\n\nfunction opname (opcode)\n\n implicit none\n\n integer opcode\n character*8 opname\n\n if (opcode == OPHALT)\n opname = 'halt '\n else if (opcode == OPADD)\n opname = 'add '\n else if (opcode == OPSUB)\n opname = 'sub '\n else if (opcode == OPMUL)\n opname = 'mul '\n else if (opcode == OPDIV)\n opname = 'div '\n else if (opcode == OPMOD)\n opname = 'mod '\n else if (opcode == OPLT)\n opname = 'lt '\n else if (opcode == OPGT)\n opname = 'gt '\n else if (opcode == OPLE)\n opname = 'le '\n else if (opcode == OPGE)\n opname = 'ge '\n else if (opcode == OPEQ)\n opname = 'eq '\n else if (opcode == OPNE)\n opname = 'ne '\n else if (opcode == OPAND)\n opname = 'and '\n else if (opcode == OPOR)\n opname = 'or '\n else if (opcode == OPNEG)\n opname = 'neg '\n else if (opcode == OPNOT)\n opname = 'not '\n else if (opcode == OPPRTC)\n opname = 'prtc '\n else if (opcode == OPPRTI)\n opname = 'prti '\n else if (opcode == OPPRTS)\n opname = 'prts '\n else if (opcode == OPFTCH)\n opname = 'fetch '\n else if (opcode == OPSTOR)\n opname = 'store '\n else if (opcode == OPPUSH)\n opname = 'push '\n else if (opcode == OPJMP)\n opname = 'jmp '\n else if (opcode == OPJZ)\n opname = 'jz '\n else\n {\n write (*, '(''Unrecognized opcode: '', I5)') opcode\n stop\n }\nend\n\nsubroutine prprog (numvar, strs, numstr, strngs, istrng, _\n code, ncode, outbuf, noutbf)\n\n implicit none\n\n integer numvar # Number of variables.\n integer strs(STRSZ, MAXSTR) # Strings for the VM's string pool.\n integer numstr # Number of such strings.\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n integer code(0 : CODESZ - 1) # Generated code.\n integer ncode # Number of VM bytes in the code.\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n\n character*8 opname\n\n integer i0, n0\n integer i, j\n integer opcode\n character*8 name\n\n character buf(20)\n buf(1) = 'D'\n buf(2) = 'a'\n buf(3) = 't'\n buf(4) = 'a'\n buf(5) = 's'\n buf(6) = 'i'\n buf(7) = 'z'\n buf(8) = 'e'\n buf(9) = ':'\n buf(10) = ' '\n call wrtstr (outbuf, noutbf, buf, 1, 10)\n call wrtint (outbuf, noutbf, numvar, 0)\n buf(1) = ' '\n buf(2) = 'S'\n buf(3) = 't'\n buf(4) = 'r'\n buf(5) = 'i'\n buf(6) = 'n'\n buf(7) = 'g'\n buf(8) = 's'\n buf(9) = ':'\n buf(10) = ' '\n call wrtstr (outbuf, noutbf, buf, 1, 10)\n call wrtint (outbuf, noutbf, numstr, 0)\n call wrtchr (outbuf, noutbf, char (NEWLIN))\n\n for (i = 1; i <= numstr; i = i + 1)\n {\n i0 = strs(STRI, i)\n n0 = strs(STRN, i)\n call wrtstr (outbuf, noutbf, strngs, i0, n0)\n call wrtchr (outbuf, noutbf, char (NEWLIN))\n }\n\n i = 0\n while (i != ncode)\n {\n opcode = code(i)\n name = opname (opcode)\n call wrtint (outbuf, noutbf, i, 10)\n for (j = 1; j <= 2; j = j + 1)\n call wrtchr (outbuf, noutbf, ' ')\n for (j = 1; j <= 8; j = j + 1)\n {\n if (opcode == OPFTCH _\n || opcode == OPSTOR _\n || opcode == OPPUSH _\n || opcode == OPJMP _\n || opcode == OPJZ)\n call wrtchr (outbuf, noutbf, name(j:j))\n else if (name(j:j) != ' ')\n call wrtchr (outbuf, noutbf, name(j:j))\n }\n if (opcode == OPPUSH)\n {\n call wrtint (outbuf, noutbf, code(i + 1), 0)\n i = i + 5\n }\n else if (opcode == OPFTCH || opcode == OPSTOR)\n {\n call wrtchr (outbuf, noutbf, '[')\n call wrtint (outbuf, noutbf, code(i + 1), 0)\n call wrtchr (outbuf, noutbf, ']')\n i = i + 5\n }\n else if (opcode == OPJMP || opcode == OPJZ)\n {\n call wrtchr (outbuf, noutbf, '(')\n call wrtint (outbuf, noutbf, code(i + 1) - (i + 1), 0)\n call wrtchr (outbuf, noutbf, ')')\n call wrtchr (outbuf, noutbf, ' ')\n call wrtint (outbuf, noutbf, code(i + 1), 0)\n i = i + 5\n }\n else\n i = i + 1\n call wrtchr (outbuf, noutbf, char (NEWLIN))\n }\nend\n\n#---------------------------------------------------------------------\n\nprogram gen\n\n implicit none\n\n integer vars(VARSZ, MAXVAR) # Variables.\n integer numvar # Number of variables.\n integer strs(STRSZ, MAXSTR) # Strings for the VM's string pool.\n integer numstr # Number of such strings.\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n integer nodes (NODESZ, NODSSZ) # Nodes pool.\n integer frelst # Head of the free list.\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n integer code(0 : CODESZ - 1) # Generated code.\n integer ncode # Number of VM bytes in the code.\n integer iast # Root node of the AST.\n\n numvar = 0\n numstr = 0\n istrng = 1\n noutbf = 0\n ncode = 0\n\n call initnd (nodes, frelst)\n call rdast (strngs, istrng, nodes, frelst, iast)\n\n call compil (vars, numvar, strs, numstr, _\n strngs, istrng, nodes, frelst, _\n code, ncode, iast)\n call prprog (numvar, strs, numstr, strngs, istrng, _\n code, ncode, outbuf, noutbf)\n\n if (noutbf != 0)\n call flushl (outbuf, noutbf)\nend\n\n######################################################################\n", "language": "RATFOR" }, { "code": "package xyz.hyperreal.rosettacodeCompiler\n\nimport scala.collection.mutable.{ArrayBuffer, HashMap}\nimport scala.io.Source\n\nobject CodeGenerator {\n\n def fromStdin = fromSource(Source.stdin)\n\n def fromString(src: String) = fromSource(Source.fromString(src))\n\n def fromSource(ast: Source) = {\n val vars = new HashMap[String, Int]\n val strings = new ArrayBuffer[String]\n val code = new ArrayBuffer[String]\n var s: Stream[String] = ast.getLines.toStream\n\n def line =\n if (s.nonEmpty) {\n val n = s.head\n\n s = s.tail\n\n n.split(\" +\", 2) match {\n case Array(n) => n\n case a => a\n }\n } else\n sys.error(\"unexpected end of AST\")\n\n def variableIndex(name: String) =\n vars get name match {\n case None =>\n val idx = vars.size\n\n vars(name) = idx\n idx\n case Some(idx) => idx\n }\n\n def stringIndex(s: String) =\n strings indexOf s match {\n case -1 =>\n val idx = strings.length\n\n strings += s\n idx\n case idx => idx\n }\n\n var loc = 0\n\n def addSimple(inst: String) = {\n code += f\"$loc%4d $inst\"\n loc += 1\n }\n\n def addOperand(inst: String, operand: String) = {\n code += f\"$loc%4d $inst%-5s $operand\"\n loc += 5\n }\n\n def fixup(inst: String, idx: Int, at: Int) = code(idx) = f\"$at%4d $inst%-5s (${loc - at - 1}) $loc\"\n\n generate\n addSimple(\"halt\")\n println(s\"Datasize: ${vars.size} Strings: ${strings.length}\")\n\n for (s <- strings)\n println(s)\n\n println(code mkString \"\\n\")\n\n def generate: Unit =\n line match {\n case \"Sequence\" =>\n generate\n generate\n case \";\" =>\n case \"Assign\" =>\n val idx =\n line match {\n case Array(\"Identifier\", name: String) =>\n variableIndex(name)\n case l => sys.error(s\"expected identifier: $l\")\n }\n\n generate\n addOperand(\"store\", s\"[$idx]\")\n case Array(\"Identifier\", name: String) => addOperand(\"fetch\", s\"[${variableIndex(name)}]\")\n case Array(\"Integer\", n: String) => addOperand(\"push\", s\"$n\")\n case Array(\"String\", s: String) => addOperand(\"push\", s\"${stringIndex(s)}\")\n case \"If\" =>\n generate\n\n val cond = loc\n val condidx = code.length\n\n addOperand(\"\", \"\")\n s = s.tail\n generate\n\n if (s.head == \";\") {\n s = s.tail\n fixup(\"jz\", condidx, cond)\n } else {\n val jump = loc\n val jumpidx = code.length\n\n addOperand(\"\", \"\")\n fixup(\"jz\", condidx, cond)\n generate\n fixup(\"jmp\", jumpidx, jump)\n }\n case \"While\" =>\n val start = loc\n\n generate\n\n val cond = loc\n val condidx = code.length\n\n addOperand(\"\", \"\")\n generate\n addOperand(\"jmp\", s\"(${start - loc - 1}) $start\")\n fixup(\"jz\", condidx, cond)\n case op =>\n generate\n generate\n addSimple(\n op match {\n case \"Prti\" => \"prti\"\n case \"Prts\" => \"prts\"\n case \"Prtc\" => \"prtc\"\n case \"Add\" => \"add\"\n case \"Subtract\" => \"sub\"\n case \"Multiply\" => \"mul\"\n case \"Divide\" => \"div\"\n case \"Mod\" => \"mod\"\n case \"Less\" => \"lt\"\n case \"LessEqual\" => \"le\"\n case \"Greater\" => \"gt\"\n case \"GreaterEqual\" => \"ge\"\n case \"Equal\" => \"eq\"\n case \"NotEqual\" => \"ne\"\n case \"And\" => \"and\"\n case \"Or\" => \"or\"\n case \"Negate\" => \"neg\"\n case \"Not\" => \"not\"\n }\n )\n }\n }\n\n}\n", "language": "Scala" }, { "code": "(import (scheme base)\n (scheme file)\n (scheme process-context)\n (scheme write)\n (only (srfi 1) delete-duplicates list-index)\n (only (srfi 13) string-delete string-index string-trim))\n\n(define *names* '((Add add) (Subtract sub) (Multiply mul) (Divide div) (Mod mod)\n (Less lt) (Greater gt) (LessEqual le) (GreaterEqual ge)\n (Equal eq) (NotEqual ne) (And and) (Or or) (Negate neg)\n (Not not) (Prts prts) (Prti prti) (Prtc prtc)))\n\n(define (change-name name)\n (if (assq name *names*)\n (cdr (assq name *names*))\n (error \"Cannot find name\" name)))\n\n;; Read AST from given filename\n;; - return as an s-expression\n(define (read-code filename)\n (define (read-expr)\n (let ((line (string-trim (read-line))))\n (if (string=? line \";\")\n '()\n (let ((space (string-index line #\\space)))\n (if space\n (list (string->symbol (string-trim (substring line 0 space)))\n (string-trim (substring line space (string-length line))))\n (list (string->symbol line) (read-expr) (read-expr)))))))\n ;\n (with-input-from-file filename (lambda () (read-expr))))\n\n;; run a three-pass assembler\n(define (generate-code ast)\n (define new-address ; create a new unique address - for jump locations\n (let ((count 0))\n (lambda ()\n (set! count (+ 1 count))\n (string->symbol (string-append \"loc-\" (number->string count))))))\n ; define some names for fields\n (define left cadr)\n (define right (lambda (x) (cadr (cdr x))))\n ;\n (define (extract-values ast)\n (if (null? ast)\n (values '() '())\n (case (car ast)\n ((Integer)\n (values '() '()))\n ((Negate Not Prtc Prti Prts)\n (extract-values (left ast)))\n ((Assign Add Subtract Multiply Divide Mod Less Greater LessEqual GreaterEqual\n Equal NotEqual And Or If While Sequence)\n (let-values (((a b) (extract-values (left ast)))\n ((c d) (extract-values (right ast))))\n (values (delete-duplicates (append a c) string=?)\n (delete-duplicates (append b d) string=?))))\n ((String)\n (values '() (list (left ast))))\n ((Identifier)\n (values (list (left ast)) '())))))\n ;\n (let-values (((constants strings) (extract-values ast)))\n (define (constant-idx term)\n (list-index (lambda (s) (string=? s term)) constants))\n (define (string-idx term)\n (list-index (lambda (s) (string=? s term)) strings))\n ;\n (define (pass-1 ast asm) ; translates ast into a list of basic operations\n (if (null? ast)\n asm\n (case (car ast)\n ((Integer)\n (cons (list 'push (left ast)) asm))\n ((Identifier)\n (cons (list 'fetch (constant-idx (left ast))) asm))\n ((String)\n (cons (list 'push (string-idx (left ast))) asm))\n ((Assign)\n (cons (list 'store (constant-idx (left (left ast)))) (pass-1 (right ast) asm)))\n ((Add Subtract Multiply Divide Mod Less Greater LessEqual GreaterEqual\n Equal NotEqual And Or) ; binary operators\n (cons (change-name (car ast))\n (pass-1 (right ast) (pass-1 (left ast) asm))))\n ((Negate Not Prtc Prti Prts) ; unary operations\n (cons (change-name (car ast))\n (pass-1 (left ast) asm)))\n ((If)\n (let ((label-else (new-address))\n (label-end (new-address)))\n (if (null? (right (right ast)))\n (cons (list 'label label-end) ; label for end of if statement\n (pass-1 (left (right ast)) ; output the 'then block\n (cons (list 'jz label-end) ; jump to end when test is false\n (pass-1 (left ast) asm))))\n (cons (list 'label label-end) ; label for end of if statement\n (pass-1 (right (right ast)) ; output the 'else block\n (cons (list 'label label-else)\n (cons (list 'jmp label-end) ; jump past 'else, after 'then\n (pass-1 (left (right ast)) ; output the 'then block\n (cons (list 'jz label-else) ; jumpt to else when false\n (pass-1 (left ast) asm))))))))))\n ((While)\n (let ((label-test (new-address))\n (label-end (new-address)))\n (cons (list 'label label-end) ; introduce a label for end of while block\n (cons (list 'jmp label-test) ; jump back to repeat test\n (pass-1 (right ast) ; output the block\n (cons (list 'jz label-end) ; test failed, jump around block\n (pass-1 (left ast) ; output the test\n (cons (list 'label label-test) ; introduce a label for test\n asm))))))))\n ((Sequence)\n (pass-1 (right ast) (pass-1 (left ast) asm)))\n (else\n \"Unknown token type\"))))\n ;\n (define (pass-2 asm) ; adds addresses and fills in jump locations\n (define (fill-addresses)\n (let ((addr 0))\n (map (lambda (instr)\n (let ((res (cons addr instr)))\n (unless (eq? (car instr) 'label)\n (set! addr (+ addr (if (= 1 (length instr)) 1 5))))\n res))\n asm)))\n ;\n (define (extract-labels asm)\n (let ((labels '()))\n (for-each (lambda (instr)\n (when (eq? (cadr instr) 'label)\n (set! labels (cons (cons (cadr (cdr instr)) (car instr))\n labels))))\n asm)\n labels))\n ;\n (define (add-jump-locations asm labels rec)\n (cond ((null? asm)\n (reverse rec))\n ((eq? (cadr (car asm)) 'label) ; ignore the labels\n (add-jump-locations (cdr asm) labels rec))\n ((memq (cadr (car asm)) '(jmp jz)) ; replace labels with addresses for jumps\n (add-jump-locations (cdr asm)\n labels\n (cons (list (car (car asm)) ; previous address\n (cadr (car asm)) ; previous jump type\n (cdr (assq (cadr (cdar asm)) labels))) ; actual address\n rec)))\n (else\n (add-jump-locations (cdr asm) labels (cons (car asm) rec)))))\n ;\n (let ((asm+addr (fill-addresses)))\n (add-jump-locations asm+addr (extract-labels asm+addr) '())))\n ;\n (define (output-instruction instr)\n (display (number->string (car instr))) (display #\\tab)\n (display (cadr instr)) (display #\\tab)\n (case (cadr instr)\n ((fetch store)\n (display \"[\") (display (number->string (cadr (cdr instr)))) (display \"]\\n\"))\n ((jmp jz)\n (display\n (string-append \"(\"\n (number->string (- (cadr (cdr instr)) (car instr) 1))\n \")\"))\n (display #\\tab)\n (display (number->string (cadr (cdr instr)))) (newline))\n ((push)\n (display (cadr (cdr instr))) (newline))\n (else\n (newline))))\n ; generate the code and output to stdout\n (display\n (string-append \"Datasize: \"\n (number->string (length constants))\n \" Strings: \"\n (number->string (length strings))))\n (newline)\n (for-each (lambda (str) (display str) (newline))\n strings)\n (for-each output-instruction\n (pass-2 (reverse (cons (list 'halt) (pass-1 ast '())))))))\n\n;; read AST from file and output code to stdout\n(if (= 2 (length (command-line)))\n (generate-code (read-code (cadr (command-line))))\n (display \"Error: pass an ast filename\\n\"))\n", "language": "Scheme" }, { "code": "import \"./dynamic\" for Enum, Struct, Tuple\nimport \"./crypto\" for Bytes\nimport \"./fmt\" for Fmt\nimport \"./ioutil\" for FileUtil\n\nvar nodes = [\n \"Ident\",\n \"String\",\n \"Integer\",\n \"Sequence\",\n \"If\",\n \"Prtc\",\n \"Prts\",\n \"Prti\",\n \"While\",\n \"Assign\",\n \"Negate\",\n \"Not\",\n \"Mul\",\n \"Div\",\n \"Mod\",\n \"Add\",\n \"Sub\",\n \"Lss\",\n \"Leq\",\n \"Gtr\",\n \"Geq\",\n \"Eql\",\n \"Neq\",\n \"And\",\n \"Or\"\n]\n\nvar Node = Enum.create(\"Node\", nodes)\n\nvar codes = [\n \"fetch\",\n \"store\",\n \"push\",\n \"add\",\n \"sub\",\n \"mul\",\n \"div\",\n \"mod\",\n \"lt\",\n \"gt\",\n \"le\",\n \"ge\",\n \"eq\",\n \"ne\",\n \"and\",\n \"or\",\n \"neg\",\n \"not\",\n \"jmp\",\n \"jz\",\n \"prtc\",\n \"prts\",\n \"prti\",\n \"halt\"\n]\n\nvar Code = Enum.create(\"Code\", codes)\n\nvar Tree = Struct.create(\"Tree\", [\"nodeType\", \"left\", \"right\", \"value\"])\n\n// dependency: Ordered by Node value, must remain in same order as Node enum\nvar Atr = Tuple.create(\"Atr\", [\"enumText\", \"nodeType\", \"opcode\"])\n\nvar atrs = [\n Atr.new(\"Identifier\", Node.Ident, 255),\n Atr.new(\"String\", Node.String, 255),\n Atr.new(\"Integer\", Node.Integer, 255),\n Atr.new(\"Sequence\", Node.Sequence, 255),\n Atr.new(\"If\", Node.If, 255),\n Atr.new(\"Prtc\", Node.Prtc, 255),\n Atr.new(\"Prts\", Node.Prts, 255),\n Atr.new(\"Prti\", Node.Prti, 255),\n Atr.new(\"While\", Node.While, 255),\n Atr.new(\"Assign\", Node.Assign, 255),\n Atr.new(\"Negate\", Node.Negate, Code.neg),\n Atr.new(\"Not\", Node.Not, Code.not),\n Atr.new(\"Multiply\", Node.Mul, Code.mul),\n Atr.new(\"Divide\", Node.Div, Code.div),\n Atr.new(\"Mod\", Node.Mod, Code.mod),\n Atr.new(\"Add\", Node.Add, Code.add),\n Atr.new(\"Subtract\", Node.Sub, Code.sub),\n Atr.new(\"Less\", Node.Lss, Code.lt),\n Atr.new(\"LessEqual\", Node.Leq, Code.le),\n Atr.new(\"Greater\", Node.Gtr, Code.gt),\n Atr.new(\"GreaterEqual\", Node.Geq, Code.ge),\n Atr.new(\"Equal\", Node.Eql, Code.eq),\n Atr.new(\"NotEqual\", Node.Neq, Code.ne),\n Atr.new(\"And\", Node.And, Code.and),\n Atr.new(\"Or\", Node.Or, Code.or),\n]\n\nvar stringPool = []\nvar globals = []\nvar object = []\n\nvar reportError = Fn.new { |msg| Fiber.abort(\"error : %(msg)\") }\n\nvar nodeToOp = Fn.new { |nodeType| atrs[nodeType].opcode }\n\nvar makeNode = Fn.new { |nodeType, left, right| Tree.new(nodeType, left, right, \"\") }\n\nvar makeLeaf = Fn.new { |nodeType, value| Tree.new(nodeType, null, null, value) }\n\n/* Code generator */\n\nvar emitByte = Fn.new { |c| object.add(c) }\n\nvar emitWord = Fn.new { |n|\n var bs = Bytes.fromIntLE(n)\n for (b in bs) emitByte.call(b)\n}\n\nvar emitWordAt = Fn.new { |at, n|\n var bs = Bytes.fromIntLE(n)\n for (i in at...at+4) object[i] = bs[i-at]\n}\n\nvar hole = Fn.new {\n var t = object.count\n emitWord.call(0)\n return t\n}\n\nvar fetchVarOffset = Fn.new { |id|\n for (i in 0...globals.count) {\n if (globals[i] == id) return i\n }\n globals.add(id)\n return globals.count - 1\n}\n\nvar fetchStringOffset = Fn.new { |st|\n for (i in 0...stringPool.count) {\n if (stringPool[i] == st) return i\n }\n stringPool.add(st)\n return stringPool.count - 1\n}\n\nvar binOpNodes = [\n Node.Lss, Node.Gtr, Node.Leq, Node.Geq, Node.Eql, Node.Neq,\n Node.And, Node.Or, Node.Sub, Node.Add, Node.Div, Node.Mul, Node.Mod\n]\n\nvar codeGen // recursive function\ncodeGen = Fn.new { |x|\n if (!x) return\n var n\n var p1\n var p2\n var nt = x.nodeType\n if (nt == Node.Ident) {\n emitByte.call(Code.fetch)\n n = fetchVarOffset.call(x.value)\n emitWord.call(n)\n } else if (nt == Node.Integer) {\n emitByte.call(Code.push)\n n = Num.fromString(x.value)\n emitWord.call(n)\n } else if (nt == Node.String) {\n emitByte.call(Code.push)\n n = fetchStringOffset.call(x.value)\n emitWord.call(n)\n } else if (nt == Node.Assign) {\n n = fetchVarOffset.call(x.left.value)\n codeGen.call(x.right)\n emitByte.call(Code.store)\n emitWord.call(n)\n } else if (nt == Node.If) {\n codeGen.call(x.left) // if expr\n emitByte.call(Code.jz) // if false, jump\n p1 = hole.call() // make room forjump dest\n codeGen.call(x.right.left) // if true statements\n if (x.right.right) {\n emitByte.call(Code.jmp)\n p2 = hole.call()\n }\n emitWordAt.call(p1, object.count-p1)\n if (x.right.right) {\n codeGen.call(x.right.right)\n emitWordAt.call(p2, object.count-p2)\n }\n } else if (nt == Node.While) {\n p1 = object.count\n codeGen.call(x.left) // while expr\n emitByte.call(Code.jz) // if false, jump\n p2 = hole.call() // make room for jump dest\n codeGen.call(x.right) // statements\n emitByte.call(Code.jmp) // back to the top\n emitWord.call(p1 - object.count) // plug the top\n emitWordAt.call(p2, object.count-p2) // plug the 'if false, jump'\n } else if (nt == Node.Sequence) {\n codeGen.call(x.left)\n codeGen.call(x.right)\n } else if (nt == Node.Prtc) {\n codeGen.call(x.left)\n emitByte.call(Code.prtc)\n } else if (nt == Node.Prti) {\n codeGen.call(x.left)\n emitByte.call(Code.prti)\n } else if (nt == Node.Prts) {\n codeGen.call(x.left)\n emitByte.call(Code.prts)\n } else if (binOpNodes.contains(nt)) {\n codeGen.call(x.left)\n codeGen.call(x.right)\n emitByte.call(nodeToOp.call(x.nodeType))\n } else if (nt == Node.negate || nt == Node.Not) {\n codeGen.call(x.left)\n emitByte.call(nodeToOp.call(x.nodeType))\n } else {\n var msg = \"error in code generator - found %(x.nodeType) expecting operator\"\n reportError.call(msg)\n }\n}\n\n// Converts the 4 bytes starting at object[pc] to an unsigned 32 bit integer\n// and thence to a signed 32 bit integer\nvar toInt32LE = Fn.new { |pc|\n var x = Bytes.toIntLE(object[pc...pc+4])\n if (x >= 2.pow(31)) x = x - 2.pow(32)\n return x\n}\n\nvar codeFinish = Fn.new { emitByte.call(Code.halt) }\n\nvar listCode = Fn.new {\n Fmt.print(\"Datasize: $d Strings: $d\", globals.count, stringPool.count)\n for (s in stringPool) System.print(s)\n var pc = 0\n while (pc < object.count) {\n Fmt.write(\"$5d \", pc)\n var op = object[pc]\n pc = pc + 1\n if (op == Code.fetch) {\n var x = toInt32LE.call(pc)\n Fmt.print(\"fetch [$d]\", x)\n pc = pc + 4\n } else if (op == Code.store) {\n var x = toInt32LE.call(pc)\n Fmt.print(\"store [$d]\", x)\n pc = pc + 4\n } else if (op == Code.push) {\n var x = toInt32LE.call(pc)\n Fmt.print(\"push $d\", x)\n pc = pc + 4\n } else if (op == Code.add) {\n System.print(\"add\")\n } else if (op == Code.sub) {\n System.print(\"sub\")\n } else if (op == Code.mul) {\n System.print(\"mul\")\n } else if (op == Code.div) {\n System.print(\"div\")\n } else if (op == Code.mod) {\n System.print(\"mod\")\n } else if (op == Code.lt) {\n System.print(\"lt\")\n } else if (op == Code.gt) {\n System.print(\"gt\")\n } else if (op == Code.le) {\n System.print(\"le\")\n } else if (op == Code.ge) {\n System.print(\"ge\")\n } else if (op == Code.eq) {\n System.print(\"eq\")\n } else if (op == Code.ne) {\n System.print(\"ne\")\n } else if (op == Code.and) {\n System.print(\"and\")\n } else if (op == Code.or) {\n System.print(\"or\")\n } else if (op == Code.neg) {\n System.print(\"neg\")\n } else if (op == Code.not) {\n System.print(\"not\")\n } else if (op == Code.jmp) {\n var x = toInt32LE.call(pc)\n Fmt.print(\"jmp ($d) $d\", x, pc+x)\n pc = pc + 4\n } else if (op == Code.jz) {\n var x = toInt32LE.call(pc)\n Fmt.print(\"jz ($d) $d\", x, pc+x)\n pc = pc + 4\n } else if (op == Code.prtc) {\n System.print(\"prtc\")\n } else if (op == Code.prti){\n System.print(\"prti\")\n } else if (op == Code.prts) {\n System.print(\"prts\")\n } else if (op == Code.halt) {\n System.print(\"halt\")\n } else {\n reportError.call(\"listCode: Unknown opcode %(op)\")\n }\n }\n}\n\nvar getEnumValue = Fn.new { |name|\n for (atr in atrs) {\n if (atr.enumText == name) return atr.nodeType\n }\n reportError.call(\"Unknown token %(name)\")\n}\n\nvar lines = []\nvar lineCount = 0\nvar lineNum = 0\n\nvar loadAst // recursive function\nloadAst = Fn.new {\n var nodeType = 0\n var s = \"\"\n if (lineNum < lineCount) {\n var line = lines[lineNum].trimEnd(\" \\t\")\n lineNum = lineNum + 1\n var tokens = line.split(\" \").where { |s| s != \"\" }.toList\n var first = tokens[0]\n if (first[0] == \";\") return null\n nodeType = getEnumValue.call(first)\n var le = tokens.count\n if (le == 2) {\n s = tokens[1]\n } else if (le > 2) {\n var idx = line.indexOf(\"\\\"\")\n s = line[idx..-1]\n }\n }\n if (s != \"\") return makeLeaf.call(nodeType, s)\n var left = loadAst.call()\n var right = loadAst.call()\n return makeNode.call(nodeType, left, right)\n}\n\nlines = FileUtil.readLines(\"ast.txt\")\nlineCount = lines.count\ncodeGen.call(loadAst.call())\ncodeFinish.call()\nlistCode.call()\n", "language": "Wren" }, { "code": "const std = @import(\"std\");\n\npub const CodeGeneratorError = error{OutOfMemory};\n\npub const CodeGenerator = struct {\n allocator: std.mem.Allocator,\n string_pool: std.ArrayList([]const u8),\n globals: std.ArrayList([]const u8),\n bytecode: std.ArrayList(u8),\n\n const Self = @This();\n const word_size = @sizeOf(i32);\n\n pub fn init(\n allocator: std.mem.Allocator,\n string_pool: std.ArrayList([]const u8),\n globals: std.ArrayList([]const u8),\n ) Self {\n return CodeGenerator{\n .allocator = allocator,\n .string_pool = string_pool,\n .globals = globals,\n .bytecode = std.ArrayList(u8).init(allocator),\n };\n }\n\n pub fn gen(self: *Self, ast: ?*Tree) CodeGeneratorError!void {\n try self.genH(ast);\n try self.emitHalt();\n }\n\n // Helper function to allow recursion.\n pub fn genH(self: *Self, ast: ?*Tree) CodeGeneratorError!void {\n if (ast) |t| {\n switch (t.typ) {\n .sequence => {\n try self.genH(t.left);\n try self.genH(t.right);\n },\n .kw_while => {\n const condition_address = self.currentAddress();\n try self.genH(t.left);\n try self.emitByte(.jz);\n const condition_address_hole = self.currentAddress();\n try self.emitHole();\n try self.genH(t.right);\n try self.emitByte(.jmp);\n try self.emitInt(condition_address);\n self.insertInt(condition_address_hole, self.currentAddress());\n },\n .kw_if => {\n try self.genH(t.left);\n try self.emitByte(.jz);\n const condition_address_hole = self.currentAddress();\n try self.emitHole();\n try self.genH(t.right.?.left);\n if (t.right.?.right) |else_tree| {\n try self.emitByte(.jmp);\n const else_address_hole = self.currentAddress();\n try self.emitHole();\n const else_address = self.currentAddress();\n try self.genH(else_tree);\n self.insertInt(condition_address_hole, else_address);\n self.insertInt(else_address_hole, self.currentAddress());\n } else {\n self.insertInt(condition_address_hole, self.currentAddress());\n }\n },\n .assign => {\n try self.genH(t.right);\n try self.emitByte(.store);\n try self.emitInt(self.fetchGlobalsOffset(t.left.?.value.?.string));\n },\n .prts => {\n try self.genH(t.left);\n try self.emitByte(.prts);\n },\n .prti => {\n try self.genH(t.left);\n try self.emitByte(.prti);\n },\n .prtc => {\n try self.genH(t.left);\n try self.emitByte(.prtc);\n },\n .string => {\n try self.emitByte(.push);\n try self.emitInt(self.fetchStringsOffset(t.value.?.string));\n },\n .integer => {\n try self.emitByte(.push);\n try self.emitInt(t.value.?.integer);\n },\n .identifier => {\n try self.emitByte(.fetch);\n try self.emitInt(self.fetchGlobalsOffset(t.value.?.string));\n },\n .negate, .not => {\n try self.genH(t.left);\n try self.emitByte(Op.fromNodeType(t.typ).?);\n },\n .add,\n .multiply,\n .subtract,\n .divide,\n .mod,\n .less,\n .less_equal,\n .greater,\n .greater_equal,\n .equal,\n .not_equal,\n .bool_and,\n .bool_or,\n => try self.genBinOp(t),\n .unknown => {\n std.debug.print(\"\\nINTERP: UNKNOWN {}\\n\", .{t.typ});\n std.os.exit(1);\n },\n }\n }\n }\n\n fn genBinOp(self: *Self, tree: *Tree) CodeGeneratorError!void {\n try self.genH(tree.left);\n try self.genH(tree.right);\n try self.emitByte(Op.fromNodeType(tree.typ).?);\n }\n\n fn emitByte(self: *Self, op: Op) CodeGeneratorError!void {\n try self.bytecode.append(@enumToInt(op));\n }\n\n fn emitInt(self: *Self, n: i32) CodeGeneratorError!void {\n var n_var = n;\n var n_bytes = @ptrCast(*[4]u8, &n_var);\n for (n_bytes) |byte| {\n try self.bytecode.append(byte);\n }\n }\n\n // Holes are later populated via `insertInt` because they can't be known when\n // we populate the bytecode array sequentially.\n fn emitHole(self: *Self) CodeGeneratorError!void {\n try self.emitInt(std.math.maxInt(i32));\n }\n\n // Populates the \"hole\" produced by `emitHole`.\n fn insertInt(self: *Self, address: i32, n: i32) void {\n var i: i32 = 0;\n var n_var = n;\n var n_bytes = @ptrCast(*[4]u8, &n_var);\n while (i < word_size) : (i += 1) {\n self.bytecode.items[@intCast(usize, address + i)] = n_bytes[@intCast(usize, i)];\n }\n }\n\n fn emitHalt(self: *Self) CodeGeneratorError!void {\n try self.bytecode.append(@enumToInt(Op.halt));\n }\n\n fn currentAddress(self: Self) i32 {\n return @intCast(i32, self.bytecode.items.len);\n }\n\n fn fetchStringsOffset(self: Self, str: []const u8) i32 {\n for (self.string_pool.items) |string, idx| {\n if (std.mem.eql(u8, string, str)) {\n return @intCast(i32, idx);\n }\n }\n unreachable;\n }\n\n fn fetchGlobalsOffset(self: Self, str: []const u8) i32 {\n for (self.globals.items) |global, idx| {\n if (std.mem.eql(u8, global, str)) {\n return @intCast(i32, idx);\n }\n }\n unreachable;\n }\n\n pub fn print(self: Self) ![]u8 {\n var result = std.ArrayList(u8).init(self.allocator);\n var writer = result.writer();\n try writer.print(\n \"Datasize: {d} Strings: {d}\\n\",\n .{ self.globals.items.len, self.string_pool.items.len },\n );\n for (self.string_pool.items) |string| {\n try writer.print(\"{s}\\n\", .{string});\n }\n\n var pc: usize = 0;\n while (pc < self.bytecode.items.len) : (pc += 1) {\n try writer.print(\"{d:>5} \", .{pc});\n switch (@intToEnum(Op, self.bytecode.items[pc])) {\n .push => {\n try writer.print(\"push {d}\\n\", .{self.unpackInt(pc + 1)});\n pc += word_size;\n },\n .store => {\n try writer.print(\"store [{d}]\\n\", .{self.unpackInt(pc + 1)});\n pc += word_size;\n },\n .fetch => {\n try writer.print(\"fetch [{d}]\\n\", .{self.unpackInt(pc + 1)});\n pc += word_size;\n },\n .jz => {\n const address = self.unpackInt(pc + 1);\n try writer.print(\"jz ({d}) {d}\\n\", .{ address - @intCast(i32, pc) - 1, address });\n pc += word_size;\n },\n .jmp => {\n const address = self.unpackInt(pc + 1);\n try writer.print(\"jmp ({d}) {d}\\n\", .{ address - @intCast(i32, pc) - 1, address });\n pc += word_size;\n },\n else => try writer.print(\"{s}\\n\", .{Op.toString(@intToEnum(Op, self.bytecode.items[pc]))}),\n }\n }\n\n return result.items;\n }\n\n fn unpackInt(self: Self, pc: usize) i32 {\n const arg_ptr = @ptrCast(*[4]u8, self.bytecode.items[pc .. pc + word_size]);\n var arg_array = arg_ptr.*;\n const arg = @ptrCast(*i32, @alignCast(@alignOf(i32), &arg_array));\n return arg.*;\n }\n};\n\npub const Op = enum(u8) {\n fetch,\n store,\n push,\n add,\n sub,\n mul,\n div,\n mod,\n lt,\n gt,\n le,\n ge,\n eq,\n ne,\n @\"and\",\n @\"or\",\n neg,\n not,\n jmp,\n jz,\n prtc,\n prts,\n prti,\n halt,\n\n const from_node = std.enums.directEnumArray(NodeType, ?Op, 0, .{\n .unknown = null,\n .identifier = null,\n .string = null,\n .integer = null,\n .sequence = null,\n .kw_if = null,\n .prtc = null,\n .prts = null,\n .prti = null,\n .kw_while = null,\n .assign = null,\n .negate = .neg,\n .not = .not,\n .multiply = .mul,\n .divide = .div,\n .mod = .mod,\n .add = .add,\n .subtract = .sub,\n .less = .lt,\n .less_equal = .le,\n .greater = .gt,\n .greater_equal = .ge,\n .equal = .eq,\n .not_equal = .ne,\n .bool_and = .@\"and\",\n .bool_or = .@\"or\",\n });\n\n pub fn fromNodeType(node_type: NodeType) ?Op {\n return from_node[@enumToInt(node_type)];\n }\n\n const to_string = std.enums.directEnumArray(Op, []const u8, 0, .{\n .fetch = \"fetch\",\n .store = \"store\",\n .push = \"push\",\n .add = \"add\",\n .sub = \"sub\",\n .mul = \"mul\",\n .div = \"div\",\n .mod = \"mod\",\n .lt = \"lt\",\n .gt = \"gt\",\n .le = \"le\",\n .ge = \"ge\",\n .eq = \"eq\",\n .ne = \"ne\",\n .@\"and\" = \"and\",\n .@\"or\" = \"or\",\n .neg = \"neg\",\n .not = \"not\",\n .jmp = \"jmp\",\n .jz = \"jz\",\n .prtc = \"prtc\",\n .prts = \"prts\",\n .prti = \"prti\",\n .halt = \"halt\",\n });\n\n pub fn toString(self: Op) []const u8 {\n return to_string[@enumToInt(self)];\n }\n};\n\npub fn main() !void {\n var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);\n defer arena.deinit();\n const allocator = arena.allocator();\n\n var arg_it = std.process.args();\n _ = try arg_it.next(allocator) orelse unreachable; // program name\n const file_name = arg_it.next(allocator);\n // We accept both files and standard input.\n var file_handle = blk: {\n if (file_name) |file_name_delimited| {\n const fname: []const u8 = try file_name_delimited;\n break :blk try std.fs.cwd().openFile(fname, .{});\n } else {\n break :blk std.io.getStdIn();\n }\n };\n defer file_handle.close();\n const input_content = try file_handle.readToEndAlloc(allocator, std.math.maxInt(usize));\n\n var string_pool = std.ArrayList([]const u8).init(allocator);\n var globals = std.ArrayList([]const u8).init(allocator);\n const ast = try loadAST(allocator, input_content, &string_pool, &globals);\n var code_generator = CodeGenerator.init(allocator, string_pool, globals);\n try code_generator.gen(ast);\n const result: []const u8 = try code_generator.print();\n _ = try std.io.getStdOut().write(result);\n}\n\npub const NodeType = enum {\n unknown,\n identifier,\n string,\n integer,\n sequence,\n kw_if,\n prtc,\n prts,\n prti,\n kw_while,\n assign,\n negate,\n not,\n multiply,\n divide,\n mod,\n add,\n subtract,\n less,\n less_equal,\n greater,\n greater_equal,\n equal,\n not_equal,\n bool_and,\n bool_or,\n\n const from_string_map = std.ComptimeStringMap(NodeType, .{\n .{ \"UNKNOWN\", .unknown },\n .{ \"Identifier\", .identifier },\n .{ \"String\", .string },\n .{ \"Integer\", .integer },\n .{ \"Sequence\", .sequence },\n .{ \"If\", .kw_if },\n .{ \"Prtc\", .prtc },\n .{ \"Prts\", .prts },\n .{ \"Prti\", .prti },\n .{ \"While\", .kw_while },\n .{ \"Assign\", .assign },\n .{ \"Negate\", .negate },\n .{ \"Not\", .not },\n .{ \"Multiply\", .multiply },\n .{ \"Divide\", .divide },\n .{ \"Mod\", .mod },\n .{ \"Add\", .add },\n .{ \"Subtract\", .subtract },\n .{ \"Less\", .less },\n .{ \"LessEqual\", .less_equal },\n .{ \"Greater\", .greater },\n .{ \"GreaterEqual\", .greater_equal },\n .{ \"Equal\", .equal },\n .{ \"NotEqual\", .not_equal },\n .{ \"And\", .bool_and },\n .{ \"Or\", .bool_or },\n });\n\n pub fn fromString(str: []const u8) NodeType {\n return from_string_map.get(str).?;\n }\n};\n\npub const NodeValue = union(enum) {\n integer: i32,\n string: []const u8,\n};\n\npub const Tree = struct {\n left: ?*Tree,\n right: ?*Tree,\n typ: NodeType = .unknown,\n value: ?NodeValue = null,\n\n fn makeNode(allocator: std.mem.Allocator, typ: NodeType, left: ?*Tree, right: ?*Tree) !*Tree {\n const result = try allocator.create(Tree);\n result.* = Tree{ .left = left, .right = right, .typ = typ };\n return result;\n }\n\n fn makeLeaf(allocator: std.mem.Allocator, typ: NodeType, value: ?NodeValue) !*Tree {\n const result = try allocator.create(Tree);\n result.* = Tree{ .left = null, .right = null, .typ = typ, .value = value };\n return result;\n }\n};\n\nconst LoadASTError = error{OutOfMemory} || std.fmt.ParseIntError;\n\nfn loadAST(\n allocator: std.mem.Allocator,\n str: []const u8,\n string_pool: *std.ArrayList([]const u8),\n globals: *std.ArrayList([]const u8),\n) LoadASTError!?*Tree {\n var line_it = std.mem.split(u8, str, \"\\n\");\n return try loadASTHelper(allocator, &line_it, string_pool, globals);\n}\n\nfn loadASTHelper(\n allocator: std.mem.Allocator,\n line_it: *std.mem.SplitIterator(u8),\n string_pool: *std.ArrayList([]const u8),\n globals: *std.ArrayList([]const u8),\n) LoadASTError!?*Tree {\n if (line_it.next()) |line| {\n var tok_it = std.mem.tokenize(u8, line, \" \");\n const tok_str = tok_it.next().?;\n if (tok_str[0] == ';') return null;\n\n const node_type = NodeType.fromString(tok_str);\n const pre_iteration_index = tok_it.index;\n\n if (tok_it.next()) |leaf_value| {\n const node_value = blk: {\n switch (node_type) {\n .integer => break :blk NodeValue{ .integer = try std.fmt.parseInt(i32, leaf_value, 10) },\n .identifier => {\n var already_exists = false;\n for (globals.items) |global| {\n if (std.mem.eql(u8, global, leaf_value)) {\n already_exists = true;\n break;\n }\n }\n if (!already_exists) try globals.append(leaf_value);\n break :blk NodeValue{ .string = leaf_value };\n },\n .string => {\n tok_it.index = pre_iteration_index;\n const str = tok_it.rest();\n var already_exists = false;\n for (string_pool.items) |string| {\n if (std.mem.eql(u8, string, str)) {\n already_exists = true;\n break;\n }\n }\n if (!already_exists) try string_pool.append(str);\n break :blk NodeValue{ .string = str };\n },\n else => unreachable,\n }\n };\n return try Tree.makeLeaf(allocator, node_type, node_value);\n }\n\n const left = try loadASTHelper(allocator, line_it, string_pool, globals);\n const right = try loadASTHelper(allocator, line_it, string_pool, globals);\n return try Tree.makeNode(allocator, node_type, left, right);\n } else {\n return null;\n }\n}\n", "language": "Zig" }, { "code": "// This is a little endian machine\n\nconst WORD_SIZE=4;\nconst{ var _n=-1; var[proxy]N=fcn{ _n+=1 }; } // enumerator\nconst FETCH=N, STORE=N, PUSH=N, ADD=N, SUB=N, MUL=N, DIV=N, MOD=N,\n LT=N, GT=N, LE=N, GE=N, EQ=N, NE=N,\n AND=N, OR=N, NEG=N, NOT=N,\n JMP=N, JZ=N, PRTC=N, PRTS=N, PRTI=N, HALT=N;\nconst nd_String=N, nd_Sequence=N, nd_If=N, nd_While=N;\nvar all_syms=Dictionary(\n \"Identifier\" ,FETCH, \"String\" ,nd_String,\n \"Integer\" ,PUSH, \"Sequence\" ,nd_Sequence,\n \"If\" ,nd_If, \"Prtc\" ,PRTC,\n \"Prts\" ,PRTS, \"Prti\" ,PRTI,\n \"While\" ,nd_While, \"Assign\" ,STORE,\n \"Negate\" ,NEG, \"Not\" ,NOT,\n \"Multiply\" ,MUL, \"Divide\" ,DIV,\n \"Mod\" ,MOD, \"Add\" ,ADD,\n \"Subtract\" ,SUB, \"Less\" ,LT,\n \"LessEqual\" ,LE, \"Greater\" ,GT,\n \"GreaterEqual\",GE, \"Equal\" ,EQ,\n \"NotEqual\" ,NE, \"And\" ,AND,\n \"Or\" ,OR,\t\t\"halt\"\t ,HALT);\nvar binOps=T(LT,GT,LE,GE,EQ,NE, AND,OR, SUB,ADD,DIV,MUL,MOD),\n unaryOps=T(NEG,NOT);\n\nclass Node{\n fcn init(_node_type, _value, _left=Void, _right=Void){\n var type=_node_type, left=_left, right=_right, value=_value;\n }\n}\n\nvar vars=Dictionary(), strings=Dictionary(); // ( value:offset, ...)\nfcn doVar(value){\n var offset=-1; // fcn local static var\n offset=_doValue(value,vars,offset)\n}\nfcn doString(str){ str=str[1,-1];\t// str is \\\"text\\\"\n var offset=-1; // fcn local static var\n str=str.replace(\"\\\\n\",\"\\n\");\n offset=_doValue(str,strings,offset)\n}\nfcn _doValue(value,vars,offset){ //--> offset of value in vars\n if(Void!=(n:=vars.find(value))) return(n);\t// fetch existing value\n vars[value]=offset+=1;\t\t\t// store new value\n}\n\nfcn asm(node,code){\n if(Void==node) return(code);\n emitB:='wrap(n){ code.append(n) };\n emitW:='wrap(n){ code.append(n.toLittleEndian(WORD_SIZE)) }; // signed\n switch(node.type){\n case(FETCH) { emitB(FETCH); emitW(doVar(node.value)); }\n case(PUSH) { emitB(PUSH); emitW(node.value); }\n case(nd_String){ emitB(PUSH); emitW(doString(node.value)); }\n case(STORE){\n asm(node.right,code);\n\t emitB(STORE); emitW(doVar(node.left.value));\n }\n case(nd_If){\n\t asm(node.left,code);\t\t# expr\n\t emitB(JZ);\t\t\t# if false, jump\n\t p1,p2 := code.len(),0;\n\t emitW(0);\t\t\t# place holder for jump dest\n\t asm(node.right.left,code);\t# if true statements\n\t if (node.right.right!=Void){\n\t emitB(JMP);\t\t\t# jump over else statements\n\t p2=code.len();\n\t emitW(0);\n\t }\n\t code[p1,WORD_SIZE]=(code.len() - p1).toLittleEndian(WORD_SIZE);\n\t if(node.right.right!=Void){\n\t asm(node.right.right,code);\t# else statements\n\t code[p2,WORD_SIZE]=(code.len() - p2).toLittleEndian(WORD_SIZE)\n\t }\n }\n case(nd_While){\n\t p1:=code.len();\n\t asm(node.left,code);\n\t emitB(JZ);\n\t p2:=code.len();\n\t emitW(0);\t\t\t# place holder\n\t asm(node.right,code);\n\t emitB(JMP);\t\t\t# jump back to the top\n\t emitW(p1 - code.len());\n\t code[p2,WORD_SIZE]=(code.len() - p2).toLittleEndian(WORD_SIZE);\n }\n case(nd_Sequence){ asm(node.left,code); asm(node.right,code); }\n case(PRTC,PRTI,PRTS){ asm(node.left,code); emitB(node.type); }\n else{\n\t if(binOps.holds(node.type)){\n\t asm(node.left,code); asm(node.right,code);\n\t emitB(node.type);\n\t }\n\t else if(unaryOps.holds(node.type))\n\t { asm(node.left,code); emitB(node.type); }\n\t else throw(Exception.AssertionError(\n\t \"error in code generator - found %d, expecting operator\"\n\t .fmt(node.type)))\n }\n }\n code\n}\nfcn code_finish(code){\n code.append(HALT);\n // prepend the strings to the code,\n // using my magic [66,1 byte len,text], no trailing '\\0' needed\n idxs:=strings.pump(Dictionary(),\"reverse\");\n idxs.keys.sort().reverse().pump(Void,'wrap(n){\n text:=idxs[n];\n code.insert(0,66,text.len(),text);\n })\n}\n", "language": "Zkl" }, { "code": "fcn unasm(code){\n all_ops,nthString := all_syms.pump(Dictionary(),\"reverse\"),-1;\n println(\"Datasize: %d bytes, Strings: %d bytes\"\n .fmt(vars.len()*WORD_SIZE,strings.reduce(fcn(s,[(k,v)]){ s+k.len() },0)));\n word:='wrap(pc){ code.toLittleEndian(pc,WORD_SIZE,False) }; // signed\n pc:=0; while(pc<code.len()){\n op:=code[pc]; print(\"%4d: %2d \".fmt(pc,op));\n pc+=1;\n switch(op){\n case(66){\n\t n,str := code[pc], code[pc+=1,n].text;\n\t println(\"String #%d %3d \\\"%s\\\"\".fmt(nthString+=1,n,\n\t Compiler.Asm.quotify(str)));\n\t pc+=n;\n\t }\n case(FETCH,STORE,PUSH){\n\t println(\"%s [%d]\".fmt(all_ops[op],word(pc)));\n\t pc+=WORD_SIZE;\n\t }\n\t case(ADD,SUB,MUL,DIV,MOD,LT,GT,LE,GE,EQ,NE,AND,OR,NEG,NOT,\n\t PRTC,PRTI,PRTS,HALT){ println(all_ops[op]) }\n case(JMP){\n\t n:=word(pc);\n println(\"jmp (%d) %d\".fmt(n, pc + n));\n pc+=WORD_SIZE;\n\t }\n\t case(JZ){\n\t n:=word(pc);\n println(\"jz (%d) %d\".fmt(n, pc + n));\n pc+=WORD_SIZE;\n\t }\n\t else throw(Exception.AssertionError(\"Unknown opcode %d\".fmt(op)));\n }\n }\n}\n", "language": "Zkl" }, { "code": "fcn load_ast(file){\n line:=file.readln().strip();\t\t// one or two tokens\n if(line[0]==\";\") return(Void);\n parts,type,value := line.split(),parts[0],parts[1,*].concat(\" \");\n type=all_syms[type];\n if(value){\n try{ value=value.toInt() }catch{}\n return(Node(type,value));\n }\n left,right := load_ast(file),load_ast(file);\n Node(type,Void,left,right)\n}\n", "language": "Zkl" }, { "code": "ast:=load_ast(File(vm.nthArg(0)));\ncode:=asm(ast,Data());\ncode_finish(code);\nunasm(code);\nFile(\"code.bin\",\"wb\").write(code);\nprintln(\"Wrote %d bytes to code.bin\".fmt(code.len()));\n", "language": "Zkl" } ]
Compiler-code-generator
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Compiler/lexical_analyzer\n", "language": "00-META" }, { "code": "Lexical Analyzer\n\nDefinition from [https://en.wikipedia.org/wiki/Lexical_analysis Wikipedia]:\n\n: ''Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified \"meaning\"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though \"scanner\" is also used to refer to the first stage of a lexer).''\n\n{{task heading}}\n\nCreate a lexical analyzer for the simple programming language specified below. The\nprogram should read input from a file and/or stdin, and write output to a file and/or\nstdout. If the language being used has a lexer module/library/class, it would be great\nif two versions of the solution are provided: One without the lexer module, and one with.\n\n{{task heading|Input Specification}}\n\nThe simple programming language to be analyzed is more or less a subset of [[C]]. It supports the following tokens:\n\n;Operators\n\n:::{| class=\"wikitable\"\n|-\n! Name !! Common name !! Character sequence\n|-\n| <tt>Op_multiply</tt> || multiply || <tt>*</tt>\n|-\n| <tt>Op_divide</tt> || divide || <tt>/</tt>\n|-\n| <tt>Op_mod</tt> || mod || <tt>%</tt>\n|-\n| <tt>Op_add</tt> || plus || <tt>+</tt>\n|-\n| <tt>Op_subtract</tt> || minus || <tt>-</tt>\n|-\n| <tt>Op_negate</tt> || unary minus || <tt>-</tt>\n|-\n| <tt>Op_less</tt> || less than || <tt><</tt>\n|-\n| <tt>Op_lessequal</tt> || less than or equal || <tt><=</tt>\n|-\n| <tt>Op_greater</tt> || greater than || <tt>&gt;</tt>\n|-\n| <tt>Op_greaterequal</tt> || greater than or equal || <tt>&gt;=</tt>\n|-\n| <tt>Op_equal</tt> || equal || <tt>==</tt>\n|-\n| <tt>Op_notequal</tt> || not equal || <tt>&#33;=</tt>\n|-\n| <tt>Op_not</tt> || unary not || <tt>&#33;</tt>\n|-\n| <tt>Op_assign</tt> || assignment || <tt>=</tt>\n|-\n| <tt>Op_and</tt> || logical and || <tt>&amp;&amp;</tt>\n|-\n| <tt>Op_or</tt> || logical or || <tt>&brvbar;&brvbar;</tt>\n|}\n\n* The <code>-</code> token should always be interpreted as <tt>Op_subtract</tt> by the lexer. Turning some <tt>Op_subtract</tt> into <tt>Op_negate</tt> will be the job of the syntax analyzer, which is not part of this task.\n\n;Symbols\n\n:::{| class=\"wikitable\"\n|-\n! Name !! Common name !! Character\n|-\n| <tt>LeftParen</tt> || left parenthesis || <tt>(</tt>\n|-\n| <tt>RightParen</tt> || right parenthesis || <tt>)</tt>\n|-\n| <tt>LeftBrace</tt> || left brace || <tt>{</tt>\n|-\n| <tt>RightBrace</tt> || right brace || <tt>}</tt>\n|-\n| <tt>Semicolon</tt> || semi-colon || <tt>&#59;</tt>\n|-\n| <tt>Comma</tt> || comma || <tt>,</tt>\n|}\n\n;Keywords\n\n:::{| class=\"wikitable\"\n|-\n! Name || Character sequence\n|-\n| <tt>Keyword_if</tt> || <tt>if</tt>\n|-\n| <tt>Keyword_else</tt> || <tt>else</tt>\n|-\n| <tt>Keyword_while</tt> || <tt>while</tt>\n|-\n| <tt>Keyword_print</tt> || <tt>print</tt>\n|-\n| <tt>Keyword_putc</tt> || <tt>putc</tt>\n|}\n\n;Identifiers and literals\n\nThese differ from the the previous tokens, in that each occurrence of them has a value associated with it.\n\n:::{| class=\"wikitable\"\n|-\n! Name\n! Common name\n! Format description\n! Format regex\n! Value\n|-\n| <tt>Identifier</tt>\n| identifier\n| one or more letter/number/underscore characters, but not starting with a number\n| <code style=\"white-space:nowrap\">[_a-zA-Z][_a-zA-Z0-9]*</code>\n| as is\n|-\n| <tt>Integer</tt>\n| integer literal\n| one or more digits\n| <code>[0-9]+</code>\n| as is, interpreted as a number\n|-\n| <tt>Integer</tt>\n| char literal\n| exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes\n| <code><nowiki>'([^'\\n]|\\\\n|\\\\\\\\)'</nowiki></code>\n| the ASCII code point number of the character, e.g. 65 for <code>'A'</code> and 10 for <code>'\\n'</code>\n|-\n| <tt>String</tt>\n| string literal\n| zero or more characters (anything except newline or double quote), enclosed by double quotes\n| <code>\"[^\"\\n]*\"</code>\n| the characters without the double quotes and with escape sequences converted\n|}\n\n* For char and string literals, the <code>\\n</code> escape sequence is supported to represent a new-line character.\n* For char and string literals, to represent a backslash, use <code>\\\\</code>.\n* No other special sequences are supported. This means that:\n** Char literals cannot represent a single quote character (value 39).\n** String literals cannot represent strings containing double quote characters.\n\n;Zero-width tokens\n\n:::{| class=\"wikitable\"\n|-\n! Name || Location\n|-\n| <tt>End_of_input</tt> || when the end of the input stream is reached\n|}\n\n;White space\n\n* Zero or more whitespace characters, or comments enclosed in <code>/* ... */</code>, are allowed between any two tokens, with the exceptions noted below.\n* \"Longest token matching\" is used to resolve conflicts (e.g., in order to match '''<=''' as a single token rather than the two tokens '''<''' and '''=''').\n* Whitespace is ''required'' between two tokens that have an alphanumeric character or underscore at the edge.\n** This means: keywords, identifiers, and integer literals.\n** e.g. <code>ifprint</code> is recognized as an identifier, instead of the keywords <tt>if</tt> and <tt>print</tt>.\n** e.g. <code>42fred</code> is invalid, and neither recognized as a number nor an identifier.\n* Whitespace is ''not allowed'' inside of tokens (except for chars and strings where they are part of the value).\n** e.g. <code>& &</code> is invalid, and not interpreted as the <tt>&&</tt> operator.\n\nFor example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions:\n\n* <syntaxhighlight lang=\"c\">if ( p /* meaning n is prime */ ) {\n print ( n , \" \" ) ;\n count = count + 1 ; /* number of primes found so far */\n}</syntaxhighlight>\n* <syntaxhighlight lang=\"c\">if(p){print(n,\" \");count=count+1;}</syntaxhighlight>\n\n;Complete list of token names\n\n<pre>\nEnd_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract\nOp_negate Op_not Op_less Op_lessequal Op_greater Op_greaterequal\nOp_equal Op_notequal Op_assign Op_and Op_or Keyword_if\nKeyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen\nLeftBrace RightBrace Semicolon Comma Identifier Integer\nString\n</pre>\n\n{{task heading|Output Format}}\n\nThe program output should be a sequence of lines, each consisting of the following whitespace-separated fields:\n\n# the line number where the token starts\n# the column number where the token starts\n# the token name\n# the token value (only for <tt>Identifier</tt>, <tt>Integer</tt>, and <tt>String</tt> tokens)\n# the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement.\n<br>\n\nThis task is intended to be used as part of a pipeline, with the other compiler tasks - for example:\n<br><b>lex < hello.t | parse | gen | vm</b>\n\nOr possibly:\n<br><b>lex hello.t lex.out</b>\n<br><b>parse lex.out parse.out</b>\n<br><b>gen parse.out gen.out</b>\n<br><b>vm gen.out</b>\n\n<br>\nThis implies that the output of this task (the lexical analyzer) should be suitable as input to any of the [[Compiler/syntax_analyzer|Syntax Analyzer task]] programs.\n\n{{task heading|Diagnostics}}\n\nThe following error conditions should be caught:\n\n:::{| class=\"wikitable\"\n|-\n! Error\n! Example\n|-\n| Empty character constant\n| <code>&apos;&apos;</code>\n|-\n| Unknown escape sequence.\n| <code>\\r</code>\n|-\n| Multi-character constant.\n| <code>&apos;xx&apos;</code>\n|-\n| End-of-file in comment. Closing comment characters not found.\n|-\n| End-of-file while scanning string literal. Closing string character not found.\n|-\n| End-of-line while scanning string literal. Closing string character not found before end-of-line.\n|-\n| Unrecognized character.\n| <code>&#124;</code>\n|-\n| Invalid number. Starts like a number, but ends in non-numeric characters.\n| <code>123abc</code>\n|}\n\n{{task heading|Test Cases}}\n:{| class=\"wikitable\"\n|-\n! Input\n! Output\n|-\n| style=\"vertical-align:top\" |\nTest Case 1:\n<syntaxhighlight lang=\"c\">/*\n Hello world\n */\nprint(\"Hello, World!\\n\");</syntaxhighlight>\n\n| style=\"vertical-align:top\" |\n<b><pre>\n 4 1 Keyword_print\n 4 6 LeftParen\n 4 7 String \"Hello, World!\\n\"\n 4 24 RightParen\n 4 25 Semicolon\n 5 1 End_of_input\n</pre></b>\n\n|-\n| style=\"vertical-align:top\" |\nTest Case 2:\n<syntaxhighlight lang=\"c\">/*\n Show Ident and Integers\n */\nphoenix_number = 142857;\nprint(phoenix_number, \"\\n\");</syntaxhighlight>\n\n| style=\"vertical-align:top\" |\n<b><pre>\n 4 1 Identifier phoenix_number\n 4 16 Op_assign\n 4 18 Integer 142857\n 4 24 Semicolon\n 5 1 Keyword_print\n 5 6 LeftParen\n 5 7 Identifier phoenix_number\n 5 21 Comma\n 5 23 String \"\\n\"\n 5 27 RightParen\n 5 28 Semicolon\n 6 1 End_of_input\n</pre></b>\n\n|-\n| style=\"vertical-align:top\" |\nTest Case 3:\n<syntaxhighlight lang=\"c\">/*\n All lexical tokens - not syntactically correct, but that will\n have to wait until syntax analysis\n */\n/* Print */ print /* Sub */ -\n/* Putc */ putc /* Lss */ <\n/* If */ if /* Gtr */ >\n/* Else */ else /* Leq */ <=\n/* While */ while /* Geq */ >=\n/* Lbrace */ { /* Eq */ ==\n/* Rbrace */ } /* Neq */ !=\n/* Lparen */ ( /* And */ &&\n/* Rparen */ ) /* Or */ ||\n/* Uminus */ - /* Semi */ ;\n/* Not */ ! /* Comma */ ,\n/* Mul */ * /* Assign */ =\n/* Div */ / /* Integer */ 42\n/* Mod */ % /* String */ \"String literal\"\n/* Add */ + /* Ident */ variable_name\n/* character literal */ '\\n'\n/* character literal */ '\\\\'\n/* character literal */ ' '</syntaxhighlight>\n\n| style=\"vertical-align:top\" |\n<b><pre>\n 5 16 Keyword_print\n 5 40 Op_subtract\n 6 16 Keyword_putc\n 6 40 Op_less\n 7 16 Keyword_if\n 7 40 Op_greater\n 8 16 Keyword_else\n 8 40 Op_lessequal\n 9 16 Keyword_while\n 9 40 Op_greaterequal\n 10 16 LeftBrace\n 10 40 Op_equal\n 11 16 RightBrace\n 11 40 Op_notequal\n 12 16 LeftParen\n 12 40 Op_and\n 13 16 RightParen\n 13 40 Op_or\n 14 16 Op_subtract\n 14 40 Semicolon\n 15 16 Op_not\n 15 40 Comma\n 16 16 Op_multiply\n 16 40 Op_assign\n 17 16 Op_divide\n 17 40 Integer 42\n 18 16 Op_mod\n 18 40 String \"String literal\"\n 19 16 Op_add\n 19 40 Identifier variable_name\n 20 26 Integer 10\n 21 26 Integer 92\n 22 26 Integer 32\n 23 1 End_of_input\n</pre></b>\n\n|-\n| style=\"vertical-align:top\" |\nTest Case 4:\n<syntaxhighlight lang=\"c\">/*** test printing, embedded \\n and comments with lots of '*' ***/\nprint(42);\nprint(\"\\nHello World\\nGood Bye\\nok\\n\");\nprint(\"Print a slash n - \\\\n.\\n\");</syntaxhighlight>\n\n| style=\"vertical-align:top\" |\n<b><pre>\n 2 1 Keyword_print\n 2 6 LeftParen\n 2 7 Integer 42\n 2 9 RightParen\n 2 10 Semicolon\n 3 1 Keyword_print\n 3 6 LeftParen\n 3 7 String \"\\nHello World\\nGood Bye\\nok\\n\"\n 3 38 RightParen\n 3 39 Semicolon\n 4 1 Keyword_print\n 4 6 LeftParen\n 4 7 String \"Print a slash n - \\\\n.\\n\"\n 4 33 RightParen\n 4 34 Semicolon\n 5 1 End_of_input\n</pre></b>\n\n|}\n\n;Additional examples\nYour solution should pass all the test cases above and the additional tests found '''[[Compiler/Sample_programs|Here]]'''.\n\n\n{{task heading|Reference}}\nThe C and Python versions can be considered reference implementations.\n\n\n;Related Tasks\n* [[Compiler/syntax_analyzer|Syntax Analyzer task]]\n* [[Compiler/code_generator|Code Generator task]]\n* [[Compiler/virtual_machine_interpreter|Virtual Machine Interpreter task]]\n* [[Compiler/AST_interpreter|AST Interpreter task]]\n<hr>\n<br><br>\n\n", "language": "00-TASK" }, { "code": "with Ada.Text_IO, Ada.Streams.Stream_IO, Ada.Strings.Unbounded, Ada.Command_Line,\n Ada.Exceptions;\nuse Ada.Strings, Ada.Strings.Unbounded, Ada.Streams, Ada.Exceptions;\n\nprocedure Main is\n package IO renames Ada.Text_IO;\n\n package Lexer is\n type Token is (Op_multiply, Op_divide, Op_mod, Op_add, Op_subtract, Op_negate,\n Op_less, Op_lessequal, Op_greater, Op_greaterequal, Op_equal,\n Op_notequal, Op_not, Op_assign, Op_and, Op_or,\n\n LeftParen, RightParen, LeftBrace, RightBrace, Semicolon, Comma,\n\n Keyword_if, Keyword_else, Keyword_while, Keyword_print, Keyword_putc,\n Identifier, Token_Integer, Token_String, End_of_input,\n\n Empty_Char_Error, Invalid_Escape_Error, Multi_Char_Error, EOF_Comment_Error,\n EOF_String_Error, EOL_String_Error, Invalid_Char_Error, Invalid_Num_Error\n );\n\n subtype Operator is Token range Op_multiply .. Op_or;\n subtype Symbol is Token range Token'Succ(Operator'Last) .. Comma;\n subtype Keyword is Token range Token'Succ(Symbol'Last) .. Keyword_putc;\n subtype Error is Token range Empty_Char_Error .. Invalid_Num_Error;\n subtype Operator_or_Error is Token\n with Static_Predicate => Operator_or_Error in Operator | Error;\n\n subtype Whitespace is Character\n with Static_Predicate => Whitespace in ' ' | ASCII.HT | ASCII.CR | ASCII.LF;\n\n Lexer_Error : exception;\n Invalid_Escape_Code : constant Character := ASCII.NUL;\n\n procedure run(input : Stream_IO.File_Type);\n end Lexer;\n\n package body Lexer is\n use type Stream_IO.Count;\n\n procedure run(input : Stream_IO.File_Type) is\n type State is (State_Start, State_Identifier, State_Integer, State_Char, State_String,\n State_Comment);\n curr_state : State := State_Start;\n curr_char : Character;\n curr_col, curr_row, token_col, token_row : Positive := 1;\n token_text : Unbounded_String := Unbounded.Null_Unbounded_String;\n\n function look_ahead return Character is\n next_char : Character := ASCII.LF;\n begin\n if not Stream_IO.End_Of_File(input) then\n next_char := Character'Input(Stream_IO.Stream(input));\n Stream_IO.Set_Index(input, Stream_IO.Index(input) - 1);\n end if;\n return next_char;\n end look_ahead;\n\n procedure next_char is\n next : Character := Character'Input(Stream_IO.Stream(input));\n begin\n curr_col := curr_col + 1;\n if curr_char = ASCII.LF then\n curr_row := curr_row + 1;\n curr_col := 1;\n end if;\n curr_char := next;\n end next_char;\n\n procedure print_token(tok : Token; text : String := \"\") is\n procedure raise_error(text : String) is\n begin\n raise Lexer_Error with \"Error: \" & text;\n end;\n begin\n IO.Put(token_row'Image & ASCII.HT & token_col'Image & ASCII.HT);\n case tok is\n when Operator | Symbol | Keyword | End_of_input => IO.Put_Line(tok'Image);\n when Token_Integer => IO.Put_Line(\"INTEGER\" & ASCII.HT & text);\n when Token_String => IO.Put_Line(\"STRING\" & ASCII.HT & ASCII.Quotation & text & ASCII.Quotation);\n when Identifier => IO.Put_Line(tok'Image & ASCII.HT & text);\n when Empty_Char_Error => raise_error(\"empty character constant\");\n when Invalid_Escape_Error => raise_error(\"unknown escape sequence: \" & text);\n when Multi_Char_Error => raise_error(\"multi-character constant: \" & text);\n when EOF_Comment_Error => raise_error(\"EOF in comment\");\n when EOF_String_Error => raise_error(\"EOF in string\");\n when EOL_String_Error => raise_error(\"EOL in string\");\n when Invalid_Char_Error => raise_error(\"invalid character: \" & curr_char);\n when Invalid_Num_Error => raise_error(\"invalid number: \" & text);\n end case;\n end print_token;\n\n procedure lookahead_choose(determiner : Character; a, b : Operator_or_Error) is\n begin\n if look_ahead = determiner then\n print_token(a);\n next_char;\n else\n print_token(b);\n end if;\n end lookahead_choose;\n\n function to_escape_code(c : Character) return Character is\n begin\n case c is\n when 'n' => return ASCII.LF;\n when '\\' => return '\\';\n when others =>\n print_token(Invalid_Escape_Error, ASCII.Back_Slash & c);\n return Invalid_Escape_Code;\n end case;\n end to_escape_code;\n begin\n curr_char := Character'Input(Stream_IO.Stream(input));\n loop\n case curr_state is\n when State_Start =>\n token_col := curr_col;\n token_row := curr_row;\n case curr_char is\n when '*' => print_token(Op_multiply);\n when '/' =>\n if look_ahead = '*' then\n next_char;\n curr_state := State_Comment;\n else\n print_token(Op_divide);\n end if;\n when '%' => print_token(Op_mod);\n when '+' => print_token(Op_add);\n when '-' => print_token(Op_subtract);\n when '(' => print_token(LeftParen);\n when ')' => print_token(RightParen);\n when '{' => print_token(LeftBrace);\n when '}' => print_token(RightBrace);\n when ';' => print_token(Semicolon);\n when ',' => print_token(Comma);\n when '<' => lookahead_choose('=', Op_lessequal, Op_less);\n when '>' => lookahead_choose('=', Op_greaterequal, Op_greater);\n when '!' => lookahead_choose('=', Op_notequal, Op_not);\n when '=' => lookahead_choose('=', Op_equal, Op_assign);\n when '&' => lookahead_choose('&', Op_and, Invalid_Char_Error);\n when '|' => lookahead_choose('|', Op_or, Invalid_Char_Error);\n when 'a' .. 'z' | 'A' .. 'Z' | '_' =>\n Unbounded.Append(token_text, curr_char);\n curr_state := State_Identifier;\n when '0' .. '9' =>\n Unbounded.Append(token_text, curr_char);\n curr_state := State_Integer;\n when ''' => curr_state := State_Char;\n when ASCII.Quotation => curr_state := State_String;\n when Whitespace => null;\n when others => null;\n end case;\n next_char;\n\n when State_Identifier =>\n case curr_char is\n when 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' =>\n Unbounded.Append(token_text, curr_char);\n next_char;\n when others =>\n if token_text = \"if\" then\n print_token(Keyword_if);\n elsif token_text = \"else\" then\n print_token(Keyword_else);\n elsif token_text = \"while\" then\n print_token(Keyword_while);\n elsif token_text = \"print\" then\n print_token(Keyword_print);\n elsif token_text = \"putc\" then\n print_token(Keyword_putc);\n else\n print_token(Identifier, To_String(token_text));\n end if;\n Unbounded.Set_Unbounded_String(token_text, \"\");\n curr_state := State_Start;\n end case;\n\n when State_Integer =>\n case curr_char is\n when '0' .. '9' =>\n Unbounded.Append(token_text, curr_char);\n next_char;\n when 'a' .. 'z' | 'A' .. 'Z' | '_' =>\n print_token(Invalid_Num_Error, To_String(token_text));\n when others =>\n print_token(Token_Integer, To_String(token_text));\n Unbounded.Set_Unbounded_String(token_text, \"\");\n curr_state := State_Start;\n end case;\n\n when State_Char =>\n case curr_char is\n when ''' =>\n if Unbounded.Length(token_text) = 0 then\n print_token(Empty_Char_Error);\n elsif Unbounded.Length(token_text) = 1 then\n print_token(Token_Integer, Character'Pos(Element(token_text, 1))'Image);\n else\n print_token(Multi_Char_Error, To_String(token_text));\n end if;\n Set_Unbounded_String(token_text, \"\");\n curr_state := State_Start;\n when '\\' =>\n Unbounded.Append(token_text, to_escape_code(look_ahead));\n next_char;\n when others => Unbounded.Append(token_text, curr_char);\n end case;\n next_char;\n\n when State_String =>\n case curr_char is\n when ASCII.Quotation =>\n print_token(Token_String, To_String(token_text));\n Set_Unbounded_String(token_text, \"\");\n curr_state := State_Start;\n when '\\' =>\n if to_escape_code(look_ahead) /= Invalid_Escape_Code then\n Unbounded.Append(token_text, curr_char);\n end if;\n when ASCII.LF | ASCII.CR => print_token(EOL_String_Error);\n when others => Unbounded.Append(token_text, curr_char);\n end case;\n next_char;\n\n when State_Comment =>\n case curr_char is\n when '*' =>\n if look_ahead = '/' then\n next_char;\n curr_state := State_Start;\n end if;\n when others => null;\n end case;\n next_char;\n end case;\n end loop;\n exception\n when error : Stream_IO.End_Error =>\n if curr_state = State_String then\n print_token(EOF_String_Error);\n else\n print_token(End_of_input);\n end if;\n when error : Lexer.Lexer_Error => IO.Put_Line(Exception_Message(error));\n end run;\n end Lexer;\n\n source_file : Stream_IO.File_Type;\nbegin\n if Ada.Command_Line.Argument_Count < 1 then\n IO.Put_Line(\"usage: lex [filename]\");\n return;\n end if;\n Stream_IO.Open(source_file, Stream_IO.In_File, Ada.Command_Line.Argument(1));\n Lexer.run(source_file);\nexception\n when error : others => IO.Put_Line(\"Error: \" & Exception_Message(error));\nend Main;\n", "language": "Ada" }, { "code": "BEGIN\n # implement C-like getchar, where EOF and EOLn are \"characters\" (-1 and 10 resp.). #\n INT eof = -1, eoln = 10;\n BOOL eof flag := FALSE;\n STRING buf := \"\";\n INT col := 1;\n INT line := 0;\n on logical file end (stand in, (REF FILE f)BOOL: eof flag := TRUE);\n PROC getchar = INT:\n IF eof flag THEN eof\n ELIF col = UPB buf THEN col +:= 1; eoln\n ELIF col > UPB buf THEN IF line > 0 THEN read(newline) FI;\n line +:= 1;\n read(buf);\n IF eof flag THEN col := 1; eof\n ELSE col := 0; getchar\n FI\n ELSE col +:= 1; ABS buf[col]\n FI;\n PROC nextchar = INT: IF eof flag THEN eof ELIF col >= UPB buf THEN eoln ELSE ABS buf[col+1] FI;\n\n PROC is blank = (INT ch) BOOL: ch = 0 OR ch = 9 OR ch = 10 OR ch = 13 OR ch = ABS \" \";\n PROC is digit = (INT ch) BOOL: ch >= ABS \"0\" AND ch <= ABS \"9\";\n PROC is ident start = (INT ch) BOOL: ch >= ABS \"A\" AND ch <= ABS \"Z\" OR\n ch >= ABS \"a\" AND ch <= ABS \"z\" OR\n ch = ABS \"_\";\n PROC is ident = (INT ch) BOOL: is ident start(ch) OR is digit(ch);\n\n PROC ident or keyword = (INT start char) VOID:\n BEGIN\n STRING w := REPR start char;\n INT start col = col;\n WHILE is ident (next char) DO w +:= REPR getchar OD;\n IF w = \"if\" THEN output2(\"Keyword_if\", start col)\n ELIF w = \"else\" THEN output2(\"Keyword_else\", start col)\n ELIF w = \"while\" THEN output2(\"Keyword_while\", start col)\n ELIF w = \"print\" THEN output2(\"Keyword_print\", start col)\n ELIF w = \"putc\" THEN output2(\"Keyword_putc\", start col)\n ELSE output2(\"Identifier \" + w, start col)\n FI\n END;\n PROC char = VOID:\n BEGIN\n INT start col = col;\n INT ch := getchar;\n IF ch = ABS \"'\" THEN error(\"Empty character constant\")\n ELIF ch = ABS \"\\\" THEN ch := getchar;\n IF ch = ABS \"n\" THEN ch := 10\n ELIF ch = ABS \"\\\" THEN SKIP\n ELSE error(\"Unknown escape sequence. \\\" + REPR ch)\n FI\n FI;\n IF nextchar /= ABS \"'\" THEN error(\"Multi-character constant.\") FI;\n getchar;\n output2(\"Integer \" + whole(ch, 0), start col)\n END;\n PROC string = VOID:\n BEGIN\n INT start col = col;\n STRING s := \"\"\"\";\n WHILE INT ch := getchar; ch /= ABS \"\"\"\"\n DO\n IF ch = eoln THEN error(\"End-of-line while scanning string literal. Closing string character not found before end-of-line.\")\n ELIF ch = eof THEN error(\"End-of-file while scanning string literal. Closing string character not found.\")\n ELIF ch = ABS \"\\\" THEN s +:= REPR ch; ch := getchar;\n IF ch /= ABS \"\\\" AND ch /= ABS \"n\" THEN error(\"Unknown escape sequence. \\\" + REPR ch) FI;\n s +:= REPR ch\n ELSE s +:= REPR ch\n FI\n OD;\n output2(\"String \" + s + \"\"\"\", start col)\n END;\n PROC comment = VOID:\n BEGIN\n WHILE INT ch := getchar; NOT (ch = ABS \"*\" AND nextchar = ABS \"/\")\n DO IF ch = eof THEN error(\"End-of-file in comment. Closing comment characters not found.\") FI\n OD;\n getchar\n END;\n PROC number = (INT first digit) VOID:\n BEGIN\n INT start col = col;\n INT n := first digit - ABS \"0\";\n WHILE is digit (nextchar) DO\n INT u := getchar - ABS \"0\";\n IF LENG n * 10 + LENG u > max int THEN error(\"Integer too big\") FI;\n n := n * 10 + u\n OD;\n IF is ident start (nextchar) THEN error(\"Invalid number. Starts like a number, but ends in non-numeric characters.\") FI;\n output2(\"Integer \" + whole(n, 0), start col)\n END;\n\n PROC output = (STRING s) VOID: output2(s, col);\n PROC output2 = (STRING s, INT col) VOID: print((whole(line,-8), whole(col,-8), \" \", s, newline));\n\n PROC if follows = (CHAR second, STRING longer, shorter) VOID:\n IF nextchar = ABS second\n THEN output(longer); getchar\n ELSE output(shorter)\n FI;\n PROC error = (STRING s)VOID: (put(stand error, (\"At \", whole(line,0), \":\", whole(col,0), \" \", s, new line)); stop);\n PROC unrecognized = (INT char) VOID: error(\"Unrecognized character \" + REPR char);\n PROC double char = (INT first, STRING op) VOID:\n IF nextchar /= first THEN unrecognized(first)\n ELSE output2(op, col-1); getchar\n FI;\n\n WHILE INT ch := getchar; ch /= eof\n DO\n IF is blank(ch) THEN SKIP\n ELIF ch = ABS \"(\" THEN output(\"LeftParen\")\n ELIF ch = ABS \")\" THEN output(\"RightParen\")\n ELIF ch = ABS \"{\" THEN output(\"LeftBrace\")\n ELIF ch = ABS \"}\" THEN output(\"RightBrace\")\n ELIF ch = ABS \";\" THEN output(\"Semicolon\")\n ELIF ch = ABS \",\" THEN output(\"Comma\")\n ELIF ch = ABS \"*\" THEN output(\"Op_multiply\")\n ELIF ch = ABS \"/\" THEN IF next char = ABS \"*\" THEN comment\n ELSE output(\"Op_divide\")\n FI\n ELIF ch = ABS \"%\" THEN output(\"Op_mod\")\n ELIF ch = ABS \"+\" THEN output(\"Op_add\")\n ELIF ch = ABS \"-\" THEN output(\"Op_subtract\")\n ELIF ch = ABS \"<\" THEN if follows(\"=\", \"Op_lessequal\", \"Op_less\")\n ELIF ch = ABS \">\" THEN if follows(\"=\", \"Op_greaterequal\", \"Op_greater\")\n ELIF ch = ABS \"=\" THEN if follows(\"=\", \"Op_equal\", \"Op_assign\")\n ELIF ch = ABS \"!\" THEN if follows(\"=\", \"Op_notequal\", \"Op_not\")\n ELIF ch = ABS \"&\" THEN double char(ch, \"Op_and\")\n ELIF ch = ABS \"|\" THEN double char(ch, \"Op_or\")\n ELIF is ident start (ch) THEN ident or keyword (ch)\n ELIF ch = ABS \"\"\"\" THEN string\n ELIF ch = ABS \"'\" THEN char\n ELIF is digit(ch) THEN number(ch)\n ELSE unrecognized(ch)\n FI\n OD;\n output(\"End_Of_Input\")\nEND\n", "language": "ALGOL-68" }, { "code": "begin\n %lexical analyser %\n % Algol W strings are limited to 256 characters in length so we limit source lines %\n % and tokens to 256 characters %\n\n integer lineNumber, columnNumber;\n string(256) line;\n string(256) tkValue;\n integer tkType, tkLine, tkColumn, tkLength, tkIntegerValue;\n logical tkTooLong;\n string(1) currChar;\n string(1) newlineChar;\n\n integer LINE_WIDTH, MAX_TOKEN_LENGTH, MAXINTEGER_OVER_10, MAXINTEGER_MOD_10;\n integer tOp_multiply , tOp_divide , tOp_mod , tOp_add\n , tOp_subtract , tOp_negate , tOp_less , tOp_lessequal\n , tOp_greater , tOp_greaterequal , tOp_equal , tOp_notequal\n , tOp_not , tOp_assign , tOp_and , tOp_or\n , tLeftParen , tRightParen , tLeftBrace , tRightBrace\n , tSemicolon , tComma , tKeyword_if , tKeyword_else\n , tKeyword_while , tKeyword_print , tKeyword_putc , tIdentifier\n , tInteger , tString , tEnd_of_input , tComment\n ;\n\n string(16) array tkName ( 1 :: 32 );\n\n % reports an error %\n procedure lexError( string(80) value message ); begin\n integer errorPos;\n write( i_w := 1, s_w := 0, \"**** Error at(\", lineNumber, \",\", columnNumber, \"): \" );\n errorPos := 0;\n while errorPos < 80 and message( errorPos // 1 ) not = \".\" do begin\n writeon( s_w := 0, message( errorPos // 1 ) );\n errorPos := errorPos + 1\n end while_not_at_end_of_message ;\n writeon( s_w := 0, \".\" )\n end lexError ;\n\n % gets the next source character %\n procedure nextChar ; begin\n if columnNumber = LINE_WIDTH then begin\n currChar := newlineChar;\n columnNumber := columnNumber + 1\n end\n else if columnNumber > LINE_WIDTH then begin\n readcard( line );\n columnNumber := 1;\n if not XCPNOTED(ENDFILE) then lineNumber := lineNumber + 1;\n currChar := line( 0 // 1 )\n end\n else begin\n currChar := line( columnNumber // 1 );\n columnNumber := columnNumber + 1\n end\n end nextChar ;\n\n % gets the next token, returns the token type %\n integer procedure nextToken ; begin\n\n % returns true if currChar is in the inclusive range lowerValue to upperValue %\n % false otherwise %\n logical procedure range( string(1) value lowerValue, upperValue ) ; begin\n currChar >= lowerValue and currChar <= upperValue\n end range ;\n\n % returns true if the current character can start an identifier, false otherwise %\n logical procedure identifierStartChar ; begin\n currChar = \"_\" or range( \"a\", \"z\" ) or range( \"A\", \"Z\" )\n end identifierStartChar ;\n\n % add the current character to the token and get the next %\n procedure addAndNextChar ; begin\n if tkLength >= MAX_TOKEN_LENGTH then tkTooLong := true\n else begin\n tkValue( tkLength // 1 ) := currChar;\n tkLength := tkLength + 1\n end if_symbol_not_too_long ;\n nextChar\n end % addAndNextChar % ;\n\n % handle a single character token %\n procedure singleCharToken( integer value tokenType ) ; begin\n tkType := tokenType;\n nextChar\n end singleCharToken ;\n\n % handle a doubled character token: && or || %\n procedure doubleCharToken( integer value tokenType ) ; begin\n string(1) firstChar;\n firstChar := currChar;\n tkType := tokenType;\n nextChar;\n if currChar = firstChar then nextChar\n else % the character wasn't doubled % lexError( \"Unrecognised character.\" );\n end singleCharToken ;\n\n % handle an operator or operator= token %\n procedure opOrOpEqual( integer value opToken, opEqualToken ) ; begin\n tkType := opToken;\n nextChar;\n if currChar = \"=\" then begin\n % have operator= %\n tkType := opEqualToken;\n nextChar\n end if_currChar_is_equal ;\n end opOrOpEqual ;\n\n % handle a / operator or /* comment %\n procedure divideOrComment ; begin\n tkType := tOp_divide;\n nextChar;\n if currChar = \"*\" then begin\n % have a comment %\n logical moreComment;\n tkType := tComment;\n moreComment := true;\n while moreComment do begin\n nextChar;\n while currChar not = \"*\" and not XCPNOTED(ENDFILE) do nextChar;\n while currChar = \"*\" and not XCPNOTED(ENDFILE) do nextChar;\n moreComment := ( currChar not = \"/\" and not XCPNOTED(ENDFILE) )\n end while_more_comment ;\n if not XCPNOTED(ENDFILE)\n then nextChar\n else lexError( \"End-of-file in comment.\" )\n end if_currChar_is_star ;\n end divideOrComment ;\n\n % handle an indentifier or keyword %\n procedure identifierOrKeyword ; begin\n tkType := tIdentifier;\n while identifierStartChar or range( \"0\", \"9\" ) do addAndNextChar;\n % there are only 5 keywords, so we just test each in turn here %\n if tkValue = \"if\" then tkType := tKeyword_if\n else if tkValue = \"else\" then tkType := tKeyword_else\n else if tkValue = \"while\" then tkType := tKeyword_while\n else if tkValue = \"print\" then tkType := tKeyword_print\n else if tkValue = \"putc\" then tkType := tKeyword_putc;\n if tkType not = tIdentifier then tkValue := \"\";\n end identifierOrKeyword ;\n\n % handle an integer literal %\n procedure integerLiteral ; begin\n logical overflowed;\n integer digit;\n overflowed := false;\n tkType := tInteger;\n while range( \"0\", \"9\" ) do begin\n digit := ( decode( currChar ) - decode( \"0\" ) );\n if tkIntegerValue > MAXINTEGER_OVER_10 then overflowed := true\n else if tkIntegerValue = MAXINTEGER_OVER_10\n and digit > MAXINTEGER_MOD_10 then overflowed := true\n else begin\n tkIntegerValue := tkIntegerValue * 10;\n tkIntegerValue := tkIntegerValue + digit;\n end;\n nextChar\n end while_have_a_digit ;\n if overflowed then lexError( \"Number too large.\" );\n if identifierStartChar then lexError( \"Number followed by letter or underscore.\" );\n end integerLiteral ;\n\n % handle a char literal %\n procedure charLiteral ; begin\n nextChar;\n if currChar = \"'\" or currChar = newlineChar then lexError( \"Invalid character constant.\" )\n else if currChar = \"\\\" then begin\n % have an escape %\n nextChar;\n if currChar = \"n\" then currChar := newlineChar\n else if currChar not = \"\\\" then lexError( \"Unknown escape sequence.\" )\n end;\n tkType := tInteger;\n tkIntegerValue := decode( currChar );\n % should have a closing quoute next %\n nextChar;\n if currChar not = \"'\"\n then lexError( \"Multi-character constant.\" )\n else nextChar\n end charLiteral ;\n\n % handle a string literal %\n procedure stringLiteral ; begin\n tkType := tString;\n tkValue( 0 // 1 ) := currChar;\n tkLength := 1;\n nextChar;\n while currChar not = \"\"\"\" and currChar not = newlineChar and not XCPNOTED(ENDFILE) do addAndNextChar;\n if currChar = newlineChar then lexError( \"End-of-line while scanning string literal.\" )\n else if XCPNOTED(ENDFILE) then lexError( \"End-of-file while scanning string literal.\" )\n else % currChar must be \"\"\"\" % addAndNextChar\n end stringLiteral ;\n\n while begin\n % skip white space %\n while ( currChar = \" \" or currChar = newlineChar ) and not XCPNOTED(ENDFILE) do nextChar;\n % get the token %\n tkLine := lineNumber;\n tkColumn := columnNumber;\n tkValue := \"\";\n tkLength := 0;\n tkIntegerValue := 0;\n tkTooLong := false;\n if XCPNOTED(ENDFILE) then tkType := tEnd_of_input\n else if currChar = \"*\" then singleCharToken( tOp_multiply )\n else if currChar = \"/\" then divideOrComment\n else if currChar = \"%\" then singleCharToken( tOp_mod )\n else if currChar = \"+\" then singleCharToken( tOp_add )\n else if currChar = \"-\" then singleCharToken( tOp_subtract )\n else if currChar = \"<\" then opOrOpEqual( tOp_less, tOp_lessequal )\n else if currChar = \">\" then opOrOpEqual( tOp_greater, tOp_greaterequal )\n else if currChar = \"=\" then opOrOpEqual( tOp_assign, tOp_equal )\n else if currChar = \"!\" then opOrOpEqual( tOp_not, tOp_notequal )\n else if currChar = \"&\" then doubleCharToken( tOp_and )\n else if currChar = \"|\" then doubleCharToken( tOp_or )\n else if currChar = \"(\" then singleCharToken( tLeftParen )\n else if currChar = \")\" then singleCharToken( tRightParen )\n else if currChar = \"{\" then singleCharToken( tLeftBrace )\n else if currChar = \"}\" then singleCharToken( tRightBrace )\n else if currChar = \";\" then singleCharToken( tSemicolon )\n else if currChar = \",\" then singleCharToken( tComma )\n else if identifierStartChar then identifierOrKeyword\n else if range( \"0\", \"9\" ) then integerLiteral\n else if currChar = \"'\" then charLiteral\n else if currChar = \"\"\"\" then stringLiteral\n else begin\n lexError( \"Unrecognised character.\" );\n singleCharToken( tComment )\n end ;\n % continue until we get something other than a comment %\n tkType = tComment\n end do begin end;\n if tkTooLong then if tkType = tString\n then lexError( \"String literal too long.\" )\n else lexError( \"Identifier too long.\" );\n tkType\n end nextToken ;\n\n % outputs the current token %\n procedure writeToken ; begin\n write( i_w := 5, s_w := 2, tkLine, tkColumn, tkName( tkType ) );\n if tkType = tInteger then writeon( i_w := 11, tkIntegerValue )\n else if tkLength > 0 then begin\n writeon( \" \" );\n for tkPos := 0 until tkLength - 1 do writeon( s_w := 0, tkValue( tkPos // 1 ) );\n end\n end writeToken ;\n\n LINE_WIDTH := 256; MAXINTEGER_MOD_10 := MAXINTEGER rem 10;\n MAX_TOKEN_LENGTH := 256; MAXINTEGER_OVER_10 := MAXINTEGER div 10;\n newlineChar := code( 10 );\n tOp_multiply := 1; tkName( tOp_multiply ) := \"Op_multiply\";\n tOp_divide := 2; tkName( tOp_divide ) := \"Op_divide\";\n tOp_mod := 3; tkName( tOp_mod ) := \"Op_mod\";\n tOp_add := 4; tkName( tOp_add ) := \"Op_add\";\n tOp_subtract := 5; tkName( tOp_subtract ) := \"Op_subtract\";\n tOp_negate := 6; tkName( tOp_negate ) := \"Op_negate\";\n tOp_less := 7; tkName( tOp_less ) := \"Op_less\";\n tOp_lessequal := 8; tkName( tOp_lessequal ) := \"Op_lessequal\";\n tOp_greater := 9; tkName( tOp_greater ) := \"Op_greater\";\n tOp_greaterequal := 10; tkName( tOp_greaterequal ) := \"Op_greaterequal\";\n tOp_equal := 11; tkName( tOp_equal ) := \"Op_equal\";\n tOp_notequal := 12; tkName( tOp_notequal ) := \"Op_notequal\";\n tOp_not := 13; tkName( tOp_not ) := \"Op_not\";\n tOp_assign := 14; tkName( tOp_assign ) := \"Op_assign\";\n tOp_and := 15; tkName( tOp_and ) := \"Op_and\";\n tOp_or := 16; tkName( tOp_or ) := \"Op_or\";\n tLeftParen := 17; tkName( tLeftParen ) := \"LeftParen\";\n tRightParen := 18; tkName( tRightParen ) := \"RightParen\";\n tLeftBrace := 19; tkName( tLeftBrace ) := \"LeftBrace\";\n tRightBrace := 20; tkName( tRightBrace ) := \"RightBrace\";\n tSemicolon := 21; tkName( tSemicolon ) := \"Semicolon\";\n tComma := 22; tkName( tComma ) := \"Comma\";\n tKeyword_if := 23; tkName( tKeyword_if ) := \"Keyword_if\";\n tKeyword_else := 24; tkName( tKeyword_else ) := \"Keyword_else\";\n tKeyword_while := 25; tkName( tKeyword_while ) := \"Keyword_while\";\n tKeyword_print := 26; tkName( tKeyword_print ) := \"Keyword_print\";\n tKeyword_putc := 27; tkName( tKeyword_putc ) := \"Keyword_putc\";\n tIdentifier := 28; tkName( tIdentifier ) := \"Identifier\";\n tInteger := 29; tkName( tInteger ) := \"Integer\";\n tString := 30; tkName( tString ) := \"String\";\n tEnd_of_input := 31; tkName( tEnd_of_input ) := \"End_of_input\";\n tComment := 32; tkName( tComment ) := \"Comment\";\n\n % allow the program to continue after reaching end-of-file %\n ENDFILE := EXCEPTION( false, 1, 0, false, \"EOF\" );\n % ensure the first call to nextToken reads the first line %\n lineNumber := 0;\n columnNumber := LINE_WIDTH + 1;\n currChar := \" \";\n % get and print all tokens from standard input %\n while nextToken not = tEnd_of_input do writeToken;\n writeToken\nend.\n", "language": "ALGOL-W" }, { "code": "(********************************************************************)\n(* Usage: lex [INPUTFILE [OUTPUTFILE]]\n If INPUTFILE or OUTPUTFILE is \"-\" or missing, then standard input\n or standard output is used, respectively. *)\n\n#define ATS_DYNLOADFLAG 0\n\n#include \"share/atspre_staload.hats\"\nstaload UN = \"prelude/SATS/unsafe.sats\"\n\n#define NIL list_nil ()\n#define :: list_cons\n\n%{^\n/* alloca(3) is needed for ATS exceptions. */\n#include <alloca.h>\n%}\n\n(********************************************************************)\n\n#define NUM_TOKENS 31\n#define RESERVED_WORD_HASHTAB_SIZE 9\n\n#define TOKEN_ELSE 0\n#define TOKEN_IF 1\n#define TOKEN_PRINT 2\n#define TOKEN_PUTC 3\n#define TOKEN_WHILE 4\n#define TOKEN_MULTIPLY 5\n#define TOKEN_DIVIDE 6\n#define TOKEN_MOD 7\n#define TOKEN_ADD 8\n#define TOKEN_SUBTRACT 9\n#define TOKEN_NEGATE 10\n#define TOKEN_LESS 11\n#define TOKEN_LESSEQUAL 12\n#define TOKEN_GREATER 13\n#define TOKEN_GREATEREQUAL 14\n#define TOKEN_EQUAL 15\n#define TOKEN_NOTEQUAL 16\n#define TOKEN_NOT 17\n#define TOKEN_ASSIGN 18\n#define TOKEN_AND 19\n#define TOKEN_OR 20\n#define TOKEN_LEFTPAREN 21\n#define TOKEN_RIGHTPAREN 22\n#define TOKEN_LEFTBRACE 23\n#define TOKEN_RIGHTBRACE 24\n#define TOKEN_SEMICOLON 25\n#define TOKEN_COMMA 26\n#define TOKEN_IDENTIFIER 27\n#define TOKEN_INTEGER 28\n#define TOKEN_STRING 29\n#define TOKEN_END_OF_INPUT 30\n\ntypedef token_t =\n [i : int | TOKEN_ELSE <= i; i <= TOKEN_END_OF_INPUT]\n int i\ntypedef tokentuple_t = (token_t, String, ullint, ullint)\ntypedef token_names_vt = @[string][NUM_TOKENS]\n\nvtypedef reserved_words_vt =\n @[String][RESERVED_WORD_HASHTAB_SIZE]\nvtypedef reserved_word_tokens_vt =\n @[token_t][RESERVED_WORD_HASHTAB_SIZE]\n\nvtypedef lookups_vt =\n [p_toknames : addr]\n [p_wordtab : addr]\n [p_toktab : addr]\n @{\n pf_toknames = token_names_vt @ p_toknames,\n pf_wordtab = reserved_words_vt @ p_wordtab,\n pf_toktab = reserved_word_tokens_vt @ p_toktab |\n toknames = ptr p_toknames,\n wordtab = ptr p_wordtab,\n toktab = ptr p_toktab\n }\n\nfn\nreserved_word_lookup\n (s : String,\n lookups : !lookups_vt,\n line_no : ullint,\n column_no : ullint) : tokentuple_t =\n if string_length s < 2 then\n (TOKEN_IDENTIFIER, s, line_no, column_no)\n else\n let\n macdef wordtab = !(lookups.wordtab)\n macdef toktab = !(lookups.toktab)\n val hashval =\n g1uint_mod (g1ofg0 (char2ui s[0] + char2ui s[1]),\n g1i2u RESERVED_WORD_HASHTAB_SIZE)\n val token = toktab[hashval]\n in\n if token = TOKEN_IDENTIFIER || s <> wordtab[hashval] then\n (TOKEN_IDENTIFIER, s, line_no, column_no)\n else\n (token, s, line_no, column_no)\n end\n\n(********************************************************************)\n(* Input allows pushback into a buffer. *)\n\ntypedef ch_t =\n @{\n ichar = int,\n line_no = ullint,\n column_no = ullint\n }\n\ntypedef inp_t (n : int) =\n [0 <= n]\n @{\n file = FILEref,\n pushback = list (ch_t, n),\n line_no = ullint,\n column_no = ullint\n }\ntypedef inp_t = [n : int] inp_t n\n\nfn\nget_ch (inp : inp_t) : (ch_t, inp_t) =\n case+ (inp.pushback) of\n | NIL =>\n let\n val c = fileref_getc (inp.file)\n val ch =\n @{\n ichar = c,\n line_no = inp.line_no,\n column_no = inp.column_no\n }\n in\n if c = char2i '\\n' then\n let\n val inp =\n @{\n file = inp.file,\n pushback = inp.pushback,\n line_no = succ (inp.line_no),\n column_no = 1ULL\n }\n in\n (ch, inp)\n end\n else\n let\n val inp =\n @{\n file = inp.file,\n pushback = inp.pushback,\n line_no = inp.line_no,\n column_no = succ (inp.column_no)\n }\n in\n (ch, inp)\n end\n end\n | ch :: pushback =>\n let\n val inp =\n @{\n file = inp.file,\n pushback = pushback,\n line_no = inp.line_no,\n column_no = inp.column_no\n }\n in\n (ch, inp)\n end\n\nfn\npush_back_ch (ch : ch_t,\n inp : inp_t) : [n : pos] inp_t n =\n let\n prval _ = lemma_list_param (inp.pushback)\n in\n @{\n file = inp.file,\n pushback = ch :: (inp.pushback),\n line_no = inp.line_no,\n column_no = inp.column_no\n }\n end\n\n(********************************************************************)\n\nexception unterminated_comment of (ullint, ullint)\nexception unterminated_character_literal of (ullint, ullint)\nexception multicharacter_literal of (ullint, ullint)\nexception unterminated_string_literal of (ullint, ullint, bool)\nexception unsupported_escape of (ullint, ullint, int)\nexception invalid_integer_literal of (ullint, ullint, String)\nexception unexpected_character of (ullint, ullint, int)\n\nfn\nscan_comment (inp : inp_t,\n line_no : ullint,\n column_no : ullint) : inp_t =\n let\n fun\n loop (inp : inp_t) : inp_t =\n let\n val (ch, inp) = get_ch inp\n in\n if (ch.ichar) < 0 then\n $raise unterminated_comment (line_no, column_no)\n else if (ch.ichar) = char2i '*' then\n let\n val (ch1, inp) = get_ch inp\n in\n if (ch.ichar) < 0 then\n $raise unterminated_comment (line_no, column_no)\n else if (ch1.ichar) = char2i '/' then\n inp\n else\n loop inp\n end\n else\n loop inp\n end\n in\n loop inp\n end\n\nfn\nskip_spaces_and_comments (inp : inp_t) : [n : pos] inp_t n =\n let\n fun\n loop (inp : inp_t) : [n : pos] inp_t n =\n let\n val (ch, inp) = get_ch inp\n in\n if isspace (ch.ichar) then\n loop inp\n else if (ch.ichar) = char2i '/' then\n let\n val (ch1, inp) = get_ch inp\n in\n if (ch1.ichar) = char2i '*' then\n loop (scan_comment (inp, ch.line_no, ch.column_no))\n else\n let\n val inp = push_back_ch (ch1, inp)\n val inp = push_back_ch (ch, inp)\n in\n inp\n end\n end\n else\n push_back_ch (ch, inp)\n end\n in\n loop inp\n end\n\nfn\nreverse_list_to_string\n {m : int}\n (lst : list (char, m)) : string m =\n let\n fun\n fill_array {n : nat | n <= m} .<n>.\n (arr : &(@[char][m + 1]),\n lst : list (char, n),\n n : size_t n) : void =\n case+ lst of\n | NIL => ()\n | c :: tail =>\n begin\n arr[pred n] := c;\n fill_array (arr, tail, pred n)\n end\n\n prval _ = lemma_list_param lst\n val m : size_t m = i2sz (list_length lst)\n val (pf, pfgc | p) = array_ptr_alloc<char> (succ m)\n val _ = array_initize_elt<char> (!p, succ m, '\\0')\n val _ = fill_array (!p, lst, m)\n in\n $UN.castvwtp0 @(pf, pfgc | p)\n end\n\nextern fun {}\nsimple_scan$pred : int -> bool\nfun {}\nsimple_scan {u : nat}\n (lst : list (char, u),\n inp : inp_t) :\n [m : nat]\n [n : pos]\n (list (char, m), inp_t n) =\n let\n val (ch, inp) = get_ch inp\n in\n if simple_scan$pred (ch.ichar) then\n simple_scan<> (int2char0 (ch.ichar) :: lst, inp)\n else\n let\n val inp = push_back_ch (ch, inp)\n in\n (lst, inp)\n end\n end\n\nfn\nis_ident_start (c : int) :<> bool =\n isalpha (c) || c = char2i '_'\n\nfn\nis_ident_continuation (c : int) :<> bool =\n isalnum (c) || c = char2i '_'\n\nfn\nscan_identifier_or_reserved_word\n (inp : inp_t,\n lookups : !lookups_vt) :\n (tokentuple_t, [n : pos] inp_t n) =\n let\n val (ch, inp) = get_ch inp\n val _ = assertloc (is_ident_start (ch.ichar))\n\n implement simple_scan$pred<> c = is_ident_continuation c\n val (lst, inp) = simple_scan (int2char0 (ch.ichar) :: NIL, inp)\n\n val s = reverse_list_to_string lst\n val toktup =\n reserved_word_lookup (s, lookups, ch.line_no, ch.column_no)\n in\n (toktup, inp)\n end\n\nfn\nscan_integer_literal\n (inp : inp_t,\n lookups : !lookups_vt) :\n (tokentuple_t, [n : pos] inp_t n) =\n let\n val (ch, inp) = get_ch inp\n val _ = assertloc (isdigit (ch.ichar))\n\n implement simple_scan$pred<> c = is_ident_continuation c\n val (lst, inp) = simple_scan (int2char0 (ch.ichar) :: NIL, inp)\n\n val s = reverse_list_to_string lst\n\n fun\n check_they_are_all_digits\n {n : nat} .<n>.\n (lst : list (char, n)) : void =\n case+ lst of\n | NIL => ()\n | c :: tail =>\n if isdigit c then\n check_they_are_all_digits tail\n else\n $raise invalid_integer_literal (ch.line_no, ch.column_no, s)\n\n val _ = check_they_are_all_digits lst\n in\n ((TOKEN_INTEGER, s, ch.line_no, ch.column_no), inp)\n end\n\nfn\nichar2integer_literal (c : int) : String0 =\n let\n var buf = @[char][100] ('\\0')\n val _ = $extfcall (int, \"snprintf\", addr@ buf, i2sz 99, \"%d\", c)\n val s = string1_copy ($UN.castvwtp0{String0} buf)\n in\n strnptr2string s\n end\n\nfn\nscan_character_literal_without_checking_end (inp : inp_t) :\n (tokentuple_t, inp_t) =\n let\n val (ch, inp) = get_ch inp\n val _ = assertloc ((ch.ichar) = '\\'')\n\n val (ch1, inp) = get_ch inp\n in\n if (ch1.ichar) < 0 then\n $raise unterminated_character_literal (ch.line_no, ch.column_no)\n else if (ch1.ichar) = char2i '\\\\' then\n let\n val (ch2, inp) = get_ch inp\n in\n if (ch2.ichar) < 0 then\n $raise unterminated_character_literal (ch.line_no,\n ch.column_no)\n else if (ch2.ichar) = char2i 'n' then\n let\n val s = ichar2integer_literal (char2i '\\n')\n in\n ((TOKEN_INTEGER, s, ch.line_no, ch.column_no), inp)\n end\n else if (ch2.ichar) = char2i '\\\\' then\n let\n val s = ichar2integer_literal (char2i '\\\\')\n in\n ((TOKEN_INTEGER, s, ch.line_no, ch.column_no), inp)\n end\n else\n $raise unsupported_escape (ch1.line_no, ch1.column_no,\n ch2.ichar)\n end\n else\n let\n val s = ichar2integer_literal (ch1.ichar)\n in\n ((TOKEN_INTEGER, s, ch.line_no, ch.column_no), inp)\n end\n end\n\nfn\nscan_character_literal (inp : inp_t) : (tokentuple_t, inp_t) =\n let\n val (tok, inp) =\n scan_character_literal_without_checking_end inp\n val line_no = (tok.2)\n val column_no = (tok.3)\n\n fun\n check_end (inp : inp_t) : inp_t =\n let\n val (ch, inp) = get_ch inp\n in\n if (ch.ichar) = char2i '\\'' then\n inp\n else\n let\n fun\n loop_to_end (ch1 : ch_t,\n inp : inp_t) : inp_t =\n if (ch1.ichar) < 0 then\n $raise unterminated_character_literal (line_no,\n column_no)\n else if (ch1.ichar) = char2i '\\'' then\n $raise multicharacter_literal (line_no, column_no)\n else\n let\n val (ch1, inp) = get_ch inp\n in\n loop_to_end (ch1, inp)\n end\n\n val inp = loop_to_end (ch, inp)\n in\n inp\n end\n end\n\n val inp = check_end inp\n in\n (tok, inp)\n end\n\nfn\nscan_string_literal (inp : inp_t) : (tokentuple_t, inp_t) =\n let\n val (ch, inp) = get_ch inp\n val _ = assertloc ((ch.ichar) = '\"')\n\n fun\n scan {u : pos}\n (lst : list (char, u),\n inp : inp_t) :\n [m : pos] (list (char, m), inp_t) =\n let\n val (ch1, inp) = get_ch inp\n in\n if (ch1.ichar) < 0 then\n $raise unterminated_string_literal (ch.line_no,\n ch.column_no, false)\n else if (ch1.ichar) = char2i '\\n' then\n $raise unterminated_string_literal (ch.line_no,\n ch.column_no, true)\n else if (ch1.ichar) = char2i '\"' then\n (lst, inp)\n else if (ch1.ichar) <> char2i '\\\\' then\n scan (int2char0 (ch1.ichar) :: lst, inp)\n else\n let\n val (ch2, inp) = get_ch inp\n in\n if (ch2.ichar) = char2i 'n' then\n scan ('n' :: '\\\\' :: lst, inp)\n else if (ch2.ichar) = char2i '\\\\' then\n scan ('\\\\' :: '\\\\' :: lst, inp)\n else\n $raise unsupported_escape (ch1.line_no, ch1.column_no,\n ch2.ichar)\n end\n end\n\n val lst = '\"' :: NIL\n val (lst, inp) = scan (lst, inp)\n val lst = '\"' :: lst\n val s = reverse_list_to_string lst\n in\n ((TOKEN_STRING, s, ch.line_no, ch.column_no), inp)\n end\n\nfn\nget_next_token (inp : inp_t,\n lookups : !lookups_vt) : (tokentuple_t, inp_t) =\n let\n val inp = skip_spaces_and_comments inp\n val (ch, inp) = get_ch inp\n val ln = ch.line_no\n val cn = ch.column_no\n in\n if ch.ichar < 0 then\n ((TOKEN_END_OF_INPUT, \"\", ln, cn), inp)\n else\n case+ int2char0 (ch.ichar) of\n | ',' => ((TOKEN_COMMA, \",\", ln, cn), inp)\n | ';' => ((TOKEN_SEMICOLON, \";\", ln, cn), inp)\n | '\\(' => ((TOKEN_LEFTPAREN, \"(\", ln, cn), inp)\n | ')' => ((TOKEN_RIGHTPAREN, \")\", ln, cn), inp)\n | '\\{' => ((TOKEN_LEFTBRACE, \"{\", ln, cn), inp)\n | '}' => ((TOKEN_RIGHTBRACE, \"}\", ln, cn), inp)\n | '*' => ((TOKEN_MULTIPLY, \"*\", ln, cn), inp)\n | '/' => ((TOKEN_DIVIDE, \"/\", ln, cn), inp)\n | '%' => ((TOKEN_MOD, \"%\", ln, cn), inp)\n | '+' => ((TOKEN_ADD, \"+\", ln, cn), inp)\n | '-' => ((TOKEN_SUBTRACT, \"-\", ln, cn), inp)\n | '<' =>\n let\n val (ch1, inp) = get_ch inp\n in\n if (ch1.ichar) = char2i '=' then\n ((TOKEN_LESSEQUAL, \"<=\", ln, cn), inp)\n else\n let\n val inp = push_back_ch (ch1, inp)\n in\n ((TOKEN_LESS, \"<\", ln, cn), inp)\n end\n end\n | '>' =>\n let\n val (ch1, inp) = get_ch inp\n in\n if (ch1.ichar) = char2i '=' then\n ((TOKEN_GREATEREQUAL, \">=\", ln, cn), inp)\n else\n let\n val inp = push_back_ch (ch1, inp)\n in\n ((TOKEN_GREATER, \">\", ln, cn), inp)\n end\n end\n | '=' =>\n let\n val (ch1, inp) = get_ch inp\n in\n if (ch1.ichar) = char2i '=' then\n ((TOKEN_EQUAL, \"==\", ln, cn), inp)\n else\n let\n val inp = push_back_ch (ch1, inp)\n in\n ((TOKEN_ASSIGN, \"=\", ln, cn), inp)\n end\n end\n | '!' =>\n let\n val (ch1, inp) = get_ch inp\n in\n if (ch1.ichar) = char2i '=' then\n ((TOKEN_NOTEQUAL, \"!=\", ln, cn), inp)\n else\n let\n val inp = push_back_ch (ch1, inp)\n in\n ((TOKEN_NOT, \"!\", ln, cn), inp)\n end\n end\n | '&' =>\n let\n val (ch1, inp) = get_ch inp\n in\n if (ch1.ichar) = char2i '&' then\n ((TOKEN_AND, \"&&\", ln, cn), inp)\n else\n $raise unexpected_character (ch.line_no, ch.column_no,\n ch.ichar)\n end\n | '|' =>\n let\n val (ch1, inp) = get_ch inp\n in\n if (ch1.ichar) = char2i '|' then\n ((TOKEN_OR, \"||\", ln, cn), inp)\n else\n $raise unexpected_character (ch.line_no, ch.column_no,\n ch.ichar)\n end\n | '\"' =>\n let\n val inp = push_back_ch (ch, inp)\n in\n scan_string_literal inp\n end\n | '\\'' =>\n let\n val inp = push_back_ch (ch, inp)\n in\n scan_character_literal inp\n end\n | _ when isdigit (ch.ichar) =>\n let\n val inp = push_back_ch (ch, inp)\n in\n scan_integer_literal (inp, lookups)\n end\n | _ when is_ident_start (ch.ichar) =>\n let\n val inp = push_back_ch (ch, inp)\n in\n scan_identifier_or_reserved_word (inp, lookups)\n end\n | _ => $raise unexpected_character (ch.line_no, ch.column_no,\n ch.ichar)\n end\n\nfn\nfprint_ullint_rightjust (outf : FILEref,\n num : ullint) : void =\n if num < 10ULL then\n fprint! (outf, \" \", num)\n else if num < 100ULL then\n fprint! (outf, \" \", num)\n else if num < 1000ULL then\n fprint! (outf, \" \", num)\n else if num < 10000ULL then\n fprint! (outf, \" \", num)\n else\n fprint! (outf, num)\n\nfn\nprint_token (outf : FILEref,\n toktup : tokentuple_t,\n lookups : !lookups_vt) : void =\n let\n macdef toknames = !(lookups.toknames)\n val name = toknames[toktup.0]\n val str = (toktup.1)\n val line_no = (toktup.2)\n val column_no = (toktup.3)\n\n val _ = fprint_ullint_rightjust (outf, line_no)\n val _ = fileref_puts (outf, \" \")\n val _ = fprint_ullint_rightjust (outf, column_no)\n val _ = fileref_puts (outf, \" \")\n val _ = fileref_puts (outf, name)\n in\n begin\n case+ toktup.0 of\n | TOKEN_IDENTIFIER => fprint! (outf, \" \", str)\n | TOKEN_INTEGER => fprint! (outf, \" \", str)\n | TOKEN_STRING => fprint! (outf, \" \", str)\n | _ => ()\n end;\n\n fileref_putc (outf, '\\n')\n end\n\nfn\nscan_text (outf : FILEref,\n inp : inp_t,\n lookups : !lookups_vt) : void =\n let\n fun\n loop (inp : inp_t,\n lookups : !lookups_vt) : void =\n let\n val (toktup, inp) = get_next_token (inp, lookups)\n in\n print_token (outf, toktup, lookups);\n if toktup.0 <> TOKEN_END_OF_INPUT then\n loop (inp, lookups)\n end\n in\n loop (inp, lookups)\n end\n\n(********************************************************************)\n\nfn\nmain_program (inpf : FILEref,\n outf : FILEref) : int =\n let\n (* Using a simple Scheme program, I found the following perfect\n hash for the reserved words, using the sum of the first two\n characters as the hash value. *)\n var reserved_words =\n @[String][RESERVED_WORD_HASHTAB_SIZE]\n (\"if\", \"print\", \"else\", \"\", \"putc\", \"\", \"\", \"while\", \"\")\n var reserved_word_tokens =\n @[token_t][RESERVED_WORD_HASHTAB_SIZE]\n (TOKEN_IF, TOKEN_PRINT, TOKEN_ELSE, TOKEN_IDENTIFIER,\n TOKEN_PUTC, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER, TOKEN_WHILE,\n TOKEN_IDENTIFIER)\n\n var token_names =\n @[string][NUM_TOKENS]\n (\"Keyword_else\",\n \"Keyword_if\",\n \"Keyword_print\",\n \"Keyword_putc\",\n \"Keyword_while\",\n \"Op_multiply\",\n \"Op_divide\",\n \"Op_mod\",\n \"Op_add\",\n \"Op_subtract\",\n \"Op_negate\",\n \"Op_less\",\n \"Op_lessequal\",\n \"Op_greater\",\n \"Op_greaterequal\",\n \"Op_equal\",\n \"Op_notequal\",\n \"Op_not\",\n \"Op_assign\",\n \"Op_and\",\n \"Op_or\",\n \"LeftParen\",\n \"RightParen\",\n \"LeftBrace\",\n \"RightBrace\",\n \"Semicolon\",\n \"Comma\",\n \"Identifier\",\n \"Integer\",\n \"String\",\n \"End_of_input\")\n\n var lookups : lookups_vt =\n @{\n pf_toknames = view@ token_names,\n pf_wordtab = view@ reserved_words,\n pf_toktab = view@ reserved_word_tokens |\n toknames = addr@ token_names,\n wordtab = addr@ reserved_words,\n toktab = addr@ reserved_word_tokens\n }\n\n val inp =\n @{\n file = inpf,\n pushback = NIL,\n line_no = 1ULL,\n column_no = 1ULL\n }\n\n val _ = scan_text (outf, inp, lookups)\n\n val @{\n pf_toknames = pf_toknames,\n pf_wordtab = pf_wordtab,\n pf_toktab = pf_toktab |\n toknames = toknames,\n wordtab = wordtab,\n toktab = toktab\n } = lookups\n prval _ = view@ token_names := pf_toknames\n prval _ = view@ reserved_words := pf_wordtab\n prval _ = view@ reserved_word_tokens := pf_toktab\n in\n 0\n end\n\nmacdef lex_error = \"Lexical error: \"\n\nimplement\nmain (argc, argv) =\n let\n val inpfname =\n if 2 <= argc then\n $UN.cast{string} argv[1]\n else\n \"-\"\n val outfname =\n if 3 <= argc then\n $UN.cast{string} argv[2]\n else\n \"-\"\n in\n try\n let\n val inpf =\n if (inpfname : string) = \"-\" then\n stdin_ref\n else\n fileref_open_exn (inpfname, file_mode_r)\n\n val outf =\n if (outfname : string) = \"-\" then\n stdout_ref\n else\n fileref_open_exn (outfname, file_mode_w)\n in\n main_program (inpf, outf)\n end\n with\n | ~ unterminated_comment (line_no, column_no) =>\n begin\n fprintln! (stderr_ref, lex_error,\n \"unterminated comment starting at \",\n line_no, \":\", column_no);\n 1\n end\n | ~ unterminated_character_literal (line_no, column_no) =>\n begin\n fprintln! (stderr_ref, lex_error,\n \"unterminated character literal starting at \",\n line_no, \":\", column_no);\n 1\n end\n | ~ multicharacter_literal (line_no, column_no) =>\n begin\n fprintln! (stderr_ref, lex_error,\n \"unsupported multicharacter literal starting at \",\n line_no, \":\", column_no);\n 1\n end\n | ~ unterminated_string_literal (line_no, column_no,\n end_of_line) =>\n let\n val s =\n begin\n if end_of_line then\n \"end of line\"\n else\n \"end of input\"\n end : String\n in\n fprintln! (stderr_ref, lex_error,\n \"unterminated string literal (\", s,\n \") starting at \", line_no, \":\", column_no);\n 1\n end\n | ~ unsupported_escape (line_no, column_no, c) =>\n begin\n fprintln! (stderr_ref, lex_error,\n \"unsupported escape \\\\\",\n int2char0 c, \" starting at \",\n line_no, \":\", column_no);\n 1\n end\n | ~ invalid_integer_literal (line_no, column_no, s) =>\n begin\n fprintln! (stderr_ref, lex_error,\n \"invalid integer literal \", s,\n \" starting at \", line_no, \":\", column_no);\n 1\n end\n | ~ unexpected_character (line_no, column_no, c) =>\n begin\n fprintln! (stderr_ref, lex_error,\n \"unexpected character '\", int2char0 c,\n \"' at \", line_no, \":\", column_no);\n 1\n end\nend\n\n(********************************************************************)\n", "language": "ATS" }, { "code": "BEGIN {\n all_syms[\"tk_EOI\" ] = \"End_of_input\"\n all_syms[\"tk_Mul\" ] = \"Op_multiply\"\n all_syms[\"tk_Div\" ] = \"Op_divide\"\n all_syms[\"tk_Mod\" ] = \"Op_mod\"\n all_syms[\"tk_Add\" ] = \"Op_add\"\n all_syms[\"tk_Sub\" ] = \"Op_subtract\"\n all_syms[\"tk_Negate\" ] = \"Op_negate\"\n all_syms[\"tk_Not\" ] = \"Op_not\"\n all_syms[\"tk_Lss\" ] = \"Op_less\"\n all_syms[\"tk_Leq\" ] = \"Op_lessequal\"\n all_syms[\"tk_Gtr\" ] = \"Op_greater\"\n all_syms[\"tk_Geq\" ] = \"Op_greaterequal\"\n all_syms[\"tk_Eq\" ] = \"Op_equal\"\n all_syms[\"tk_Neq\" ] = \"Op_notequal\"\n all_syms[\"tk_Assign\" ] = \"Op_assign\"\n all_syms[\"tk_And\" ] = \"Op_and\"\n all_syms[\"tk_Or\" ] = \"Op_or\"\n all_syms[\"tk_If\" ] = \"Keyword_if\"\n all_syms[\"tk_Else\" ] = \"Keyword_else\"\n all_syms[\"tk_While\" ] = \"Keyword_while\"\n all_syms[\"tk_Print\" ] = \"Keyword_print\"\n all_syms[\"tk_Putc\" ] = \"Keyword_putc\"\n all_syms[\"tk_Lparen\" ] = \"LeftParen\"\n all_syms[\"tk_Rparen\" ] = \"RightParen\"\n all_syms[\"tk_Lbrace\" ] = \"LeftBrace\"\n all_syms[\"tk_Rbrace\" ] = \"RightBrace\"\n all_syms[\"tk_Semi\" ] = \"Semicolon\"\n all_syms[\"tk_Comma\" ] = \"Comma\"\n all_syms[\"tk_Ident\" ] = \"Identifier\"\n all_syms[\"tk_Integer\"] = \"Integer\"\n all_syms[\"tk_String\" ] = \"String\"\n\n ## single character only symbols\n symbols[\"{\" ] = \"tk_Lbrace\"\n symbols[\"}\" ] = \"tk_Rbrace\"\n symbols[\"(\" ] = \"tk_Lparen\"\n symbols[\")\" ] = \"tk_Rparen\"\n symbols[\"+\" ] = \"tk_Add\"\n symbols[\"-\" ] = \"tk_Sub\"\n symbols[\"*\" ] = \"tk_Mul\"\n symbols[\"%\" ] = \"tk_Mod\"\n symbols[\";\" ] = \"tk_Semi\"\n symbols[\",\" ] = \"tk_Comma\"\n\n key_words[\"if\" ] = \"tk_If\"\n key_words[\"else\" ] = \"tk_Else\"\n key_words[\"print\"] = \"tk_Print\"\n key_words[\"putc\" ] = \"tk_Putc\"\n key_words[\"while\"] = \"tk_While\"\n\n # Set up an array that emulates the ord() function.\n for(n=0;n<256;n++)\n ord[sprintf(\"%c\",n)]=n\n\n input_file = \"-\"\n if (ARGC > 1)\n input_file = ARGV[1]\n RS=FS=\"\" # read complete file into one line $0\n getline < input_file\n the_ch = \" \" # dummy first char - but it must be a space\n the_col = 0 # always points to the current character\n the_line = 1\n for (the_nf=1; ; ) {\n split(gettok(), t, SUBSEP)\n printf(\"%5s %5s %-14s\", t[2], t[3], all_syms[t[1]])\n if (t[1] == \"tk_Integer\") printf(\" %5s\\n\", t[4])\n else if (t[1] == \"tk_Ident\" ) printf(\" %s\\n\", t[4])\n else if (t[1] == \"tk_String\" ) printf(\" \\\"%s\\\"\\n\", t[4])\n else print(\"\")\n if (t[1] == \"tk_EOI\")\n break\n }\n}\n\n#*** show error and exit\nfunction error(line, col, msg) {\n print(line, col, msg)\n exit(1)\n}\n\n# get the next character from the input\nfunction next_ch() {\n the_ch = $the_nf\n the_nf ++\n the_col ++\n if (the_ch == \"\\n\") {\n the_line ++\n the_col = 0\n }\n return the_ch\n}\n\n#*** 'x' - character constants\nfunction char_lit(err_line, err_col) {\n n = ord[next_ch()] # skip opening quote\n if (the_ch == \"'\") {\n error(err_line, err_col, \"empty character constant\")\n } else if (the_ch == \"\\\\\") {\n next_ch()\n if (the_ch == \"n\")\n n = 10\n else if (the_ch == \"\\\\\")\n n = ord[\"\\\\\"]\n else\n error(err_line, err_col, \"unknown escape sequence \" the_ch)\n }\n if (next_ch() != \"'\")\n error(err_line, err_col, \"multi-character constant\")\n next_ch()\n return \"tk_Integer\" SUBSEP err_line SUBSEP err_col SUBSEP n\n}\n\n#*** process divide or comments\nfunction div_or_cmt(err_line, err_col) {\n if (next_ch() != \"*\")\n return \"tk_Div\" SUBSEP err_line SUBSEP err_col\n # comment found\n next_ch()\n while (1) {\n if (the_ch == \"*\") {\n if (next_ch() == \"/\") {\n next_ch()\n return gettok()\n } else if (the_ch == \"\") {\n error(err_line, err_col, \"EOF in comment\")\n }\n } else {\n next_ch()\n }\n }\n}\n\n#*** \"string\"\nfunction string_lit(start, err_line, err_col) {\n text = \"\"\n while (next_ch() != start) {\n if (the_ch == \"\")\n error(err_line, err_col, \"EOF while scanning string literal\")\n if (the_ch == \"\\n\")\n error(err_line, err_col, \"EOL while scanning string literal\")\n text = text the_ch\n }\n next_ch()\n return \"tk_String\" SUBSEP err_line SUBSEP err_col SUBSEP text\n}\n\n#*** handle identifiers and integers\nfunction ident_or_int(err_line, err_col) {\n is_number = 1\n text = \"\"\n while ((the_ch ~ /^[0-9a-zA-Z]+$/) || (the_ch == \"_\")) {\n text = text the_ch\n if (! (the_ch ~ /^[0-9]+$/))\n is_number = 0\n next_ch()\n }\n if (text == \"\")\n error(err_line, err_col, \"ident_or_int: unrecognized character: \" the_ch)\n if (text ~ /^[0-9]/) {\n if (! is_number)\n error(err_line, err_col, \"invalid number: \" text)\n n = text + 0\n return \"tk_Integer\" SUBSEP err_line SUBSEP err_col SUBSEP n\n }\n if (text in key_words)\n return key_words[text] SUBSEP err_line SUBSEP err_col\n return \"tk_Ident\" SUBSEP err_line SUBSEP err_col SUBSEP text\n}\n\n#*** look ahead for '>=', etc.\nfunction follow(expect, ifyes, ifno, err_line, err_col) {\n if (next_ch() == expect) {\n next_ch()\n return ifyes SUBSEP err_line SUBSEP err_col\n }\n if (ifno == tk_EOI)\n error(err_line, err_col, \"follow: unrecognized character: \" the_ch)\n return ifno SUBSEP err_line SUBSEP err_col\n}\n\n#*** return the next token type\nfunction gettok() {\n while (the_ch == \" \" || the_ch == \"\\n\" || the_ch == \"\\r\")\n next_ch()\n err_line = the_line\n err_col = the_col\n if (the_ch == \"\" ) return \"tk_EOI\" SUBSEP err_line SUBSEP err_col\n else if (the_ch == \"/\") return div_or_cmt(err_line, err_col)\n else if (the_ch == \"'\") return char_lit(err_line, err_col)\n else if (the_ch == \"<\") return follow(\"=\", \"tk_Leq\", \"tk_Lss\", err_line, err_col)\n else if (the_ch == \">\") return follow(\"=\", \"tk_Geq\", \"tk_Gtr\", err_line, err_col)\n else if (the_ch == \"=\") return follow(\"=\", \"tk_Eq\", \"tk_Assign\", err_line, err_col)\n else if (the_ch == \"!\") return follow(\"=\", \"tk_Neq\", \"tk_Not\", err_line, err_col)\n else if (the_ch == \"&\") return follow(\"&\", \"tk_And\", \"tk_EOI\", err_line, err_col)\n else if (the_ch == \"|\") return follow(\"|\", \"tk_Or\", \"tk_EOI\", err_line, err_col)\n else if (the_ch ==\"\\\"\") return string_lit(the_ch, err_line, err_col)\n else if (the_ch in symbols) {\n sym = symbols[the_ch]\n next_ch()\n return sym SUBSEP err_line SUBSEP err_col\n } else {\n return ident_or_int(err_line, err_col)\n }\n}\n", "language": "AWK" }, { "code": "#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <ctype.h>\n#include <string.h>\n#include <errno.h>\n#include <stdbool.h>\n#include <limits.h>\n\n#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))\n\n#define da_dim(name, type) type *name = NULL; \\\n int _qy_ ## name ## _p = 0; \\\n int _qy_ ## name ## _max = 0\n#define da_rewind(name) _qy_ ## name ## _p = 0\n#define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n#define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n#define da_len(name) _qy_ ## name ## _p\n\ntypedef enum {\n tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq,\n tk_Gtr, tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While,\n tk_Print, tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma,\n tk_Ident, tk_Integer, tk_String\n} TokenType;\n\ntypedef struct {\n TokenType tok;\n int err_ln, err_col;\n union {\n int n; /* value for constants */\n char *text; /* text for idents */\n };\n} tok_s;\n\nstatic FILE *source_fp, *dest_fp;\nstatic int line = 1, col = 0, the_ch = ' ';\nda_dim(text, char);\n\ntok_s gettok(void);\n\nstatic void error(int err_line, int err_col, const char *fmt, ... ) {\n char buf[1000];\n va_list ap;\n\n va_start(ap, fmt);\n vsprintf(buf, fmt, ap);\n va_end(ap);\n printf(\"(%d,%d) error: %s\\n\", err_line, err_col, buf);\n exit(1);\n}\n\nstatic int next_ch(void) { /* get next char from input */\n the_ch = getc(source_fp);\n ++col;\n if (the_ch == '\\n') {\n ++line;\n col = 0;\n }\n return the_ch;\n}\n\nstatic tok_s char_lit(int n, int err_line, int err_col) { /* 'x' */\n if (the_ch == '\\'')\n error(err_line, err_col, \"gettok: empty character constant\");\n if (the_ch == '\\\\') {\n next_ch();\n if (the_ch == 'n')\n n = 10;\n else if (the_ch == '\\\\')\n n = '\\\\';\n else error(err_line, err_col, \"gettok: unknown escape sequence \\\\%c\", the_ch);\n }\n if (next_ch() != '\\'')\n error(err_line, err_col, \"multi-character constant\");\n next_ch();\n return (tok_s){tk_Integer, err_line, err_col, {n}};\n}\n\nstatic tok_s div_or_cmt(int err_line, int err_col) { /* process divide or comments */\n if (the_ch != '*')\n return (tok_s){tk_Div, err_line, err_col, {0}};\n\n /* comment found */\n next_ch();\n for (;;) {\n if (the_ch == '*') {\n if (next_ch() == '/') {\n next_ch();\n return gettok();\n }\n } else if (the_ch == EOF)\n error(err_line, err_col, \"EOF in comment\");\n else\n next_ch();\n }\n}\n\nstatic tok_s string_lit(int start, int err_line, int err_col) { /* \"st\" */\n da_rewind(text);\n\n while (next_ch() != start) {\n if (the_ch == '\\n') error(err_line, err_col, \"EOL in string\");\n if (the_ch == EOF) error(err_line, err_col, \"EOF in string\");\n da_append(text, (char)the_ch);\n }\n da_append(text, '\\0');\n\n next_ch();\n return (tok_s){tk_String, err_line, err_col, {.text=text}};\n}\n\nstatic int kwd_cmp(const void *p1, const void *p2) {\n return strcmp(*(char **)p1, *(char **)p2);\n}\n\nstatic TokenType get_ident_type(const char *ident) {\n static struct {\n const char *s;\n TokenType sym;\n } kwds[] = {\n {\"else\", tk_Else},\n {\"if\", tk_If},\n {\"print\", tk_Print},\n {\"putc\", tk_Putc},\n {\"while\", tk_While},\n }, *kwp;\n\n return (kwp = bsearch(&ident, kwds, NELEMS(kwds), sizeof(kwds[0]), kwd_cmp)) == NULL ? tk_Ident : kwp->sym;\n}\n\nstatic tok_s ident_or_int(int err_line, int err_col) {\n int n, is_number = true;\n\n da_rewind(text);\n while (isalnum(the_ch) || the_ch == '_') {\n da_append(text, (char)the_ch);\n if (!isdigit(the_ch))\n is_number = false;\n next_ch();\n }\n if (da_len(text) == 0)\n error(err_line, err_col, \"gettok: unrecognized character (%d) '%c'\\n\", the_ch, the_ch);\n da_append(text, '\\0');\n if (isdigit(text[0])) {\n if (!is_number)\n error(err_line, err_col, \"invalid number: %s\\n\", text);\n n = strtol(text, NULL, 0);\n if (n == LONG_MAX && errno == ERANGE)\n error(err_line, err_col, \"Number exceeds maximum value\");\n return (tok_s){tk_Integer, err_line, err_col, {n}};\n }\n return (tok_s){get_ident_type(text), err_line, err_col, {.text=text}};\n}\n\nstatic tok_s follow(int expect, TokenType ifyes, TokenType ifno, int err_line, int err_col) { /* look ahead for '>=', etc. */\n if (the_ch == expect) {\n next_ch();\n return (tok_s){ifyes, err_line, err_col, {0}};\n }\n if (ifno == tk_EOI)\n error(err_line, err_col, \"follow: unrecognized character '%c' (%d)\\n\", the_ch, the_ch);\n return (tok_s){ifno, err_line, err_col, {0}};\n}\n\ntok_s gettok(void) { /* return the token type */\n /* skip white space */\n while (isspace(the_ch))\n next_ch();\n int err_line = line;\n int err_col = col;\n switch (the_ch) {\n case '{': next_ch(); return (tok_s){tk_Lbrace, err_line, err_col, {0}};\n case '}': next_ch(); return (tok_s){tk_Rbrace, err_line, err_col, {0}};\n case '(': next_ch(); return (tok_s){tk_Lparen, err_line, err_col, {0}};\n case ')': next_ch(); return (tok_s){tk_Rparen, err_line, err_col, {0}};\n case '+': next_ch(); return (tok_s){tk_Add, err_line, err_col, {0}};\n case '-': next_ch(); return (tok_s){tk_Sub, err_line, err_col, {0}};\n case '*': next_ch(); return (tok_s){tk_Mul, err_line, err_col, {0}};\n case '%': next_ch(); return (tok_s){tk_Mod, err_line, err_col, {0}};\n case ';': next_ch(); return (tok_s){tk_Semi, err_line, err_col, {0}};\n case ',': next_ch(); return (tok_s){tk_Comma,err_line, err_col, {0}};\n case '/': next_ch(); return div_or_cmt(err_line, err_col);\n case '\\'': next_ch(); return char_lit(the_ch, err_line, err_col);\n case '<': next_ch(); return follow('=', tk_Leq, tk_Lss, err_line, err_col);\n case '>': next_ch(); return follow('=', tk_Geq, tk_Gtr, err_line, err_col);\n case '=': next_ch(); return follow('=', tk_Eq, tk_Assign, err_line, err_col);\n case '!': next_ch(); return follow('=', tk_Neq, tk_Not, err_line, err_col);\n case '&': next_ch(); return follow('&', tk_And, tk_EOI, err_line, err_col);\n case '|': next_ch(); return follow('|', tk_Or, tk_EOI, err_line, err_col);\n case '\"' : return string_lit(the_ch, err_line, err_col);\n default: return ident_or_int(err_line, err_col);\n case EOF: return (tok_s){tk_EOI, err_line, err_col, {0}};\n }\n}\n\nvoid run(void) { /* tokenize the given input */\n tok_s tok;\n do {\n tok = gettok();\n fprintf(dest_fp, \"%5d %5d %.15s\",\n tok.err_ln, tok.err_col,\n &\"End_of_input Op_multiply Op_divide Op_mod Op_add \"\n \"Op_subtract Op_negate Op_not Op_less Op_lessequal \"\n \"Op_greater Op_greaterequal Op_equal Op_notequal Op_assign \"\n \"Op_and Op_or Keyword_if Keyword_else Keyword_while \"\n \"Keyword_print Keyword_putc LeftParen RightParen LeftBrace \"\n \"RightBrace Semicolon Comma Identifier Integer \"\n \"String \"\n [tok.tok * 16]);\n if (tok.tok == tk_Integer) fprintf(dest_fp, \" %4d\", tok.n);\n else if (tok.tok == tk_Ident) fprintf(dest_fp, \" %s\", tok.text);\n else if (tok.tok == tk_String) fprintf(dest_fp, \" \\\"%s\\\"\", tok.text);\n fprintf(dest_fp, \"\\n\");\n } while (tok.tok != tk_EOI);\n if (dest_fp != stdout)\n fclose(dest_fp);\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n if (fn[0] == '\\0')\n *fp = std;\n else if ((*fp = fopen(fn, mode)) == NULL)\n error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nint main(int argc, char *argv[]) {\n init_io(&source_fp, stdin, \"r\", argc > 1 ? argv[1] : \"\");\n init_io(&dest_fp, stdout, \"wb\", argc > 2 ? argv[2] : \"\");\n run();\n return 0;\n}\n", "language": "C" }, { "code": "#include <charconv> // std::from_chars\n#include <fstream> // file_to_string, string_to_file\n#include <functional> // std::invoke\n#include <iomanip> // std::setw\n#include <ios> // std::left\n#include <iostream>\n#include <map> // keywords\n#include <sstream>\n#include <string>\n#include <utility> // std::forward\n#include <variant> // TokenVal\n\nusing namespace std;\n\n// =====================================================================================================================\n// Machinery\n// =====================================================================================================================\nstring file_to_string (const string& path)\n{\n // Open file\n ifstream file {path, ios::in | ios::binary | ios::ate};\n if (!file) throw (errno);\n\n // Allocate string memory\n string contents;\n contents.resize(file.tellg());\n\n // Read file contents into string\n file.seekg(0);\n file.read(contents.data(), contents.size());\n\n return contents;\n}\n\nvoid string_to_file (const string& path, string contents)\n{\n ofstream file {path, ios::out | ios::binary};\n if (!file) throw (errno);\n\n file.write(contents.data(), contents.size());\n}\n\ntemplate <class F>\nvoid with_IO (string source, string destination, F&& f)\n{\n string input;\n\n if (source == \"stdin\") getline(cin, input);\n else input = file_to_string(source);\n\n string output = invoke(forward<F>(f), input);\n\n if (destination == \"stdout\") cout << output;\n else string_to_file(destination, output);\n}\n\n// Add escaped newlines and backslashes back in for printing\nstring sanitize (string s)\n{\n for (auto i = 0u; i < s.size(); ++i)\n {\n if (s[i] == '\\n') s.replace(i++, 1, \"\\\\n\");\n else if (s[i] == '\\\\') s.replace(i++, 1, \"\\\\\\\\\");\n }\n\n return s;\n}\n\nclass Scanner\n{\npublic:\n const char* pos;\n int line = 1;\n int column = 1;\n\n Scanner (const char* source) : pos {source} {}\n\n inline char peek () { return *pos; }\n\n void advance ()\n {\n if (*pos == '\\n') { ++line; column = 1; }\n else ++column;\n\n ++pos;\n }\n\n char next ()\n {\n advance();\n return peek();\n }\n\n void skip_whitespace ()\n {\n while (isspace(static_cast<unsigned char>(peek())))\n advance();\n }\n}; // class Scanner\n\n\n// =====================================================================================================================\n// Tokens\n// =====================================================================================================================\nenum class TokenName\n{\n OP_MULTIPLY, OP_DIVIDE, OP_MOD, OP_ADD, OP_SUBTRACT, OP_NEGATE,\n OP_LESS, OP_LESSEQUAL, OP_GREATER, OP_GREATEREQUAL, OP_EQUAL, OP_NOTEQUAL,\n OP_NOT, OP_ASSIGN, OP_AND, OP_OR,\n LEFTPAREN, RIGHTPAREN, LEFTBRACE, RIGHTBRACE, SEMICOLON, COMMA,\n KEYWORD_IF, KEYWORD_ELSE, KEYWORD_WHILE, KEYWORD_PRINT, KEYWORD_PUTC,\n IDENTIFIER, INTEGER, STRING,\n END_OF_INPUT, ERROR\n};\n\nusing TokenVal = variant<int, string>;\n\nstruct Token\n{\n TokenName name;\n TokenVal value;\n int line;\n int column;\n};\n\n\nconst char* to_cstring (TokenName name)\n{\n static const char* s[] =\n {\n \"Op_multiply\", \"Op_divide\", \"Op_mod\", \"Op_add\", \"Op_subtract\", \"Op_negate\",\n \"Op_less\", \"Op_lessequal\", \"Op_greater\", \"Op_greaterequal\", \"Op_equal\", \"Op_notequal\",\n \"Op_not\", \"Op_assign\", \"Op_and\", \"Op_or\",\n \"LeftParen\", \"RightParen\", \"LeftBrace\", \"RightBrace\", \"Semicolon\", \"Comma\",\n \"Keyword_if\", \"Keyword_else\", \"Keyword_while\", \"Keyword_print\", \"Keyword_putc\",\n \"Identifier\", \"Integer\", \"String\",\n \"End_of_input\", \"Error\"\n };\n\n return s[static_cast<int>(name)];\n}\n\n\nstring to_string (Token t)\n{\n ostringstream out;\n out << setw(2) << t.line << \" \" << setw(2) << t.column << \" \";\n\n switch (t.name)\n {\n case (TokenName::IDENTIFIER) : out << \"Identifier \" << get<string>(t.value); break;\n case (TokenName::INTEGER) : out << \"Integer \" << left << get<int>(t.value); break;\n case (TokenName::STRING) : out << \"String \\\"\" << sanitize(get<string>(t.value)) << '\"'; break;\n case (TokenName::END_OF_INPUT) : out << \"End_of_input\"; break;\n case (TokenName::ERROR) : out << \"Error \" << get<string>(t.value); break;\n default : out << to_cstring(t.name);\n }\n\n out << '\\n';\n\n return out.str();\n}\n\n\n// =====================================================================================================================\n// Lexer\n// =====================================================================================================================\nclass Lexer\n{\npublic:\n Lexer (const char* source) : s {source}, pre_state {s} {}\n\n bool has_more () { return s.peek() != '\\0'; }\n\n Token next_token ()\n {\n s.skip_whitespace();\n\n pre_state = s;\n\n switch (s.peek())\n {\n case '*' : return simply(TokenName::OP_MULTIPLY);\n case '%' : return simply(TokenName::OP_MOD);\n case '+' : return simply(TokenName::OP_ADD);\n case '-' : return simply(TokenName::OP_SUBTRACT);\n case '{' : return simply(TokenName::LEFTBRACE);\n case '}' : return simply(TokenName::RIGHTBRACE);\n case '(' : return simply(TokenName::LEFTPAREN);\n case ')' : return simply(TokenName::RIGHTPAREN);\n case ';' : return simply(TokenName::SEMICOLON);\n case ',' : return simply(TokenName::COMMA);\n case '&' : return expect('&', TokenName::OP_AND);\n case '|' : return expect('|', TokenName::OP_OR);\n case '<' : return follow('=', TokenName::OP_LESSEQUAL, TokenName::OP_LESS);\n case '>' : return follow('=', TokenName::OP_GREATEREQUAL, TokenName::OP_GREATER);\n case '=' : return follow('=', TokenName::OP_EQUAL, TokenName::OP_ASSIGN);\n case '!' : return follow('=', TokenName::OP_NOTEQUAL, TokenName::OP_NOT);\n case '/' : return divide_or_comment();\n case '\\'' : return char_lit();\n case '\"' : return string_lit();\n\n default : if (is_id_start(s.peek())) return identifier();\n if (is_digit(s.peek())) return integer_lit();\n return error(\"Unrecognized character '\", s.peek(), \"'\");\n\n case '\\0' : return make_token(TokenName::END_OF_INPUT);\n }\n }\n\n\nprivate:\n Scanner s;\n Scanner pre_state;\n static const map<string, TokenName> keywords;\n\n\n template <class... Args>\n Token error (Args&&... ostream_args)\n {\n string code {pre_state.pos, (string::size_type) s.column - pre_state.column};\n\n ostringstream msg;\n (msg << ... << forward<Args>(ostream_args)) << '\\n'\n << string(28, ' ') << \"(\" << s.line << \", \" << s.column << \"): \" << code;\n\n if (s.peek() != '\\0') s.advance();\n\n return make_token(TokenName::ERROR, msg.str());\n }\n\n\n inline Token make_token (TokenName name, TokenVal value = 0)\n {\n return {name, value, pre_state.line, pre_state.column};\n }\n\n\n Token simply (TokenName name)\n {\n s.advance();\n return make_token(name);\n }\n\n\n Token expect (char expected, TokenName name)\n {\n if (s.next() == expected) return simply(name);\n else return error(\"Unrecognized character '\", s.peek(), \"'\");\n }\n\n\n Token follow (char expected, TokenName ifyes, TokenName ifno)\n {\n if (s.next() == expected) return simply(ifyes);\n else return make_token(ifno);\n }\n\n\n Token divide_or_comment ()\n {\n if (s.next() != '*') return make_token(TokenName::OP_DIVIDE);\n\n while (s.next() != '\\0')\n {\n if (s.peek() == '*' && s.next() == '/')\n {\n s.advance();\n return next_token();\n }\n }\n\n return error(\"End-of-file in comment. Closing comment characters not found.\");\n }\n\n\n Token char_lit ()\n {\n int n = s.next();\n\n if (n == '\\'') return error(\"Empty character constant\");\n\n if (n == '\\\\') switch (s.next())\n {\n case 'n' : n = '\\n'; break;\n case '\\\\' : n = '\\\\'; break;\n default : return error(\"Unknown escape sequence \\\\\", s.peek());\n }\n\n if (s.next() != '\\'') return error(\"Multi-character constant\");\n\n s.advance();\n return make_token(TokenName::INTEGER, n);\n }\n\n\n Token string_lit ()\n {\n string text = \"\";\n\n while (s.next() != '\"')\n switch (s.peek())\n {\n case '\\\\' : switch (s.next())\n {\n case 'n' : text += '\\n'; continue;\n case '\\\\' : text += '\\\\'; continue;\n default : return error(\"Unknown escape sequence \\\\\", s.peek());\n }\n\n case '\\n' : return error(\"End-of-line while scanning string literal.\"\n \" Closing string character not found before end-of-line.\");\n\n case '\\0' : return error(\"End-of-file while scanning string literal.\"\n \" Closing string character not found.\");\n\n default : text += s.peek();\n }\n\n s.advance();\n return make_token(TokenName::STRING, text);\n }\n\n\n static inline bool is_id_start (char c) { return isalpha(static_cast<unsigned char>(c)) || c == '_'; }\n static inline bool is_id_end (char c) { return isalnum(static_cast<unsigned char>(c)) || c == '_'; }\n static inline bool is_digit (char c) { return isdigit(static_cast<unsigned char>(c)); }\n\n\n Token identifier ()\n {\n string text (1, s.peek());\n\n while (is_id_end(s.next())) text += s.peek();\n\n auto i = keywords.find(text);\n if (i != keywords.end()) return make_token(i->second);\n\n return make_token(TokenName::IDENTIFIER, text);\n }\n\n\n Token integer_lit ()\n {\n while (is_digit(s.next()));\n\n if (is_id_start(s.peek()))\n return error(\"Invalid number. Starts like a number, but ends in non-numeric characters.\");\n\n int n;\n\n auto r = from_chars(pre_state.pos, s.pos, n);\n if (r.ec == errc::result_out_of_range) return error(\"Number exceeds maximum value\");\n\n return make_token(TokenName::INTEGER, n);\n }\n}; // class Lexer\n\n\nconst map<string, TokenName> Lexer::keywords =\n{\n {\"else\", TokenName::KEYWORD_ELSE},\n {\"if\", TokenName::KEYWORD_IF},\n {\"print\", TokenName::KEYWORD_PRINT},\n {\"putc\", TokenName::KEYWORD_PUTC},\n {\"while\", TokenName::KEYWORD_WHILE}\n};\n\n\nint main (int argc, char* argv[])\n{\n string in = (argc > 1) ? argv[1] : \"stdin\";\n string out = (argc > 2) ? argv[2] : \"stdout\";\n\n with_IO(in, out, [](string input)\n {\n Lexer lexer {input.data()};\n\n string s = \"Location Token name Value\\n\"\n \"--------------------------------------\\n\";\n\n while (lexer.has_more()) s += to_string(lexer.next_token());\n return s;\n });\n}\n", "language": "C++" }, { "code": "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Collections.Generic;\n\n\nnamespace Rosetta {\n\n public enum TokenType {\n End_of_input, Op_multiply, Op_divide, Op_mod, Op_add, Op_subtract,\n Op_negate, Op_not, Op_less, Op_lessequal, Op_greater, Op_greaterequal,\n Op_equal, Op_notequal, Op_assign, Op_and, Op_or, Keyword_if,\n Keyword_else, Keyword_while, Keyword_print, Keyword_putc, LeftParen, RightParen,\n LeftBrace, RightBrace, Semicolon, Comma, Identifier, Integer, String, None\n }\n\n /// <summary>\n /// Storage class for tokens\n /// </summary>\n public class Token {\n public TokenType Type { get; set; }\n public int Line { get; set; }\n public int Position { get; set; }\n public string Value { get; set; }\n public override string ToString() {\n if (Type == TokenType.Integer || Type == TokenType.Identifier) {\n return String.Format(\"{0,-5} {1,-5} {2,-14} {3}\", Line, Position, Type.ToString(), Value);\n } else if (Type == TokenType.String) {\n return String.Format(\"{0,-5} {1,-5} {2,-14} \\\"{3}\\\"\", Line, Position, Type.ToString(), Value.Replace(\"\\n\", \"\\\\n\"));\n }\n return String.Format(\"{0,-5} {1,-5} {2,-14}\", Line, Position, Type.ToString());\n }\n }\n\n /// <summary>\n /// C# Example of Lexical scanner for Rosetta Compiler\n /// </summary>\n public class LexicalScanner {\n\n // character classes\n private const string _letters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_\";\n private const string _numbers = \"0123456789\";\n private const string _identifier = _letters + _numbers + \"_\";\n private const string _whitespace = \" \\t\\n\\r\";\n\n // mappings from string keywords to token type\n private Dictionary<string, TokenType> _keywordTokenTypeMap = new Dictionary<string, TokenType>() {\n { \"if\", TokenType.Keyword_if },\n { \"else\", TokenType.Keyword_else },\n { \"while\", TokenType.Keyword_while },\n { \"print\", TokenType.Keyword_print },\n { \"putc\", TokenType.Keyword_putc }\n };\n\n // mappings from simple operators to token type\n private Dictionary<string, TokenType> _operatorTokenTypeMap = new Dictionary<string, TokenType>() {\n { \"+\", TokenType.Op_add },\n { \"-\", TokenType.Op_subtract },\n { \"*\", TokenType.Op_multiply },\n { \"/\", TokenType.Op_divide },\n { \"%\", TokenType.Op_mod },\n { \"=\", TokenType.Op_assign },\n { \"<\", TokenType.Op_less },\n { \">\", TokenType.Op_greater },\n { \"!\", TokenType.Op_not },\n };\n\n private List<string> _keywords;\n private string _operators = \"+-*/%=<>!%\";\n\n private string _code;\n private List<Token> tokens = new List<Token>();\n\n private int _line = 1;\n private int _position = 1;\n\n public string CurrentCharacter {\n get {\n try {\n return _code.Substring(0, 1);\n } catch (ArgumentOutOfRangeException) {\n return \"\";\n }\n }\n }\n\n /// <summary>\n /// Lexical scanner initialiser\n /// </summary>\n /// <param name=\"code\">Code to be tokenised</param>\n public LexicalScanner (string code) {\n _code = code;\n _keywords = _keywordTokenTypeMap.Keys.ToList();\n }\n\n /// <summary>\n /// Advance the cursor forward given number of characters\n /// </summary>\n /// <param name=\"characters\">Number of characters to advance</param>\n private void advance(int characters=1) {\n try {\n // reset position when there is a newline\n if (CurrentCharacter == \"\\n\") {\n _position = 0;\n _line++;\n }\n\n _code = _code.Substring(characters, _code.Length - characters);\n _position += characters;\n } catch (ArgumentOutOfRangeException) {\n _code = \"\";\n }\n }\n\n /// <summary>\n /// Outputs error message to the console and exits\n /// </summary>\n /// <param name=\"message\">Error message to display to user</param>\n /// <param name=\"line\">Line error occurred on</param>\n /// <param name=\"position\">Line column that the error occurred at</param>\n public void error(string message, int line, int position) {\n // output error to the console and exit\n Console.WriteLine(String.Format(\"{0} @ {1}:{2}\", message, line, position));\n Environment.Exit(1);\n }\n\n /// <summary>\n /// Pattern matching using first & follow matching\n /// </summary>\n /// <param name=\"recogniseClass\">String of characters that identifies the token type\n /// or the exact match the be made if exact:true</param>\n /// <param name=\"matchClass\">String of characters to match against remaining target characters</param>\n /// <param name=\"tokenType\">Type of token the match represents.</param>\n /// <param name=\"notNextClass\">Optional class of characters that cannot follow the match</param>\n /// <param name=\"maxLen\">Optional maximum length of token value</param>\n /// <param name=\"exact\">Denotes whether recogniseClass represents an exact match or class match.\n /// Default: false</param>\n /// <param name=\"discard\">Denotes whether the token is kept or discarded. Default: false</param>\n /// <param name=\"offset\">Optiona line position offset to account for discarded tokens</param>\n /// <returns>Boolean indicating if a match was made </returns>\n public bool match(string recogniseClass, string matchClass, TokenType tokenType,\n string notNextClass=null, int maxLen=Int32.MaxValue, bool exact=false,\n bool discard=false, int offset=0) {\n\n // if we've hit the end of the file, there's no more matching to be done\n if (CurrentCharacter == \"\")\n return false;\n\n // store _current_ line and position so that our vectors point at the start\n // of each token\n int line = _line;\n int position = _position;\n\n // special case exact tokens to avoid needing to worry about backtracking\n if (exact) {\n if (_code.StartsWith(recogniseClass)) {\n if (!discard)\n tokens.Add(new Token() { Type = tokenType, Value = recogniseClass, Line = line, Position = position - offset});\n advance(recogniseClass.Length);\n return true;\n }\n return false;\n }\n\n // first match - denotes the token type usually\n if (!recogniseClass.Contains(CurrentCharacter))\n return false;\n\n string tokenValue = CurrentCharacter;\n advance();\n\n // follow match while we haven't exceeded maxLen and there are still characters\n // in the code stream\n while ((matchClass ?? \"\").Contains(CurrentCharacter) && tokenValue.Length <= maxLen && CurrentCharacter != \"\") {\n tokenValue += CurrentCharacter;\n advance();\n }\n\n // ensure that any incompatible characters are not next to the token\n // eg 42fred is invalid, and neither recognized as a number nor an identifier.\n // _letters would be the notNextClass\n if (notNextClass != null && notNextClass.Contains(CurrentCharacter))\n error(\"Unrecognised character: \" + CurrentCharacter, _line, _position);\n\n // only add tokens to the stack that aren't marked as discard - dont want\n // things like open and close quotes/comments\n if (!discard) {\n Token token = new Token() { Type = tokenType, Value = tokenValue, Line = line, Position = position - offset };\n tokens.Add(token);\n }\n\n return true;\n }\n\n /// <summary>\n /// Tokenise the input code\n /// </summary>\n /// <returns>List of Tokens</returns>\n public List<Token> scan() {\n\n while (CurrentCharacter != \"\") {\n // match whitespace\n match(_whitespace, _whitespace, TokenType.None, discard: true);\n\n // match integers\n match(_numbers, _numbers, TokenType.Integer, notNextClass:_letters);\n\n // match identifiers and keywords\n if (match(_letters, _identifier, TokenType.Identifier)) {\n Token match = tokens.Last();\n if (_keywords.Contains(match.Value))\n match.Type = _keywordTokenTypeMap[match.Value];\n }\n\n // match string similarly to comments without allowing newlines\n // this token doesn't get discarded though\n if (match(\"\\\"\", null, TokenType.String, discard:true)) {\n string value = \"\";\n int position = _position;\n while (!match(\"\\\"\", null, TokenType.String, discard:true)) {\n // not allowed newlines in strings\n if (CurrentCharacter == \"\\n\")\n error(\"End-of-line while scanning string literal. Closing string character not found before end-of-line\", _line, _position);\n // end of file reached before finding end of string\n if (CurrentCharacter == \"\")\n error(\"End-of-file while scanning string literal. Closing string character not found\", _line, _position);\n\n value += CurrentCharacter;\n\n // deal with escape sequences - we only accept newline (\\n)\n if (value.Length >= 2) {\n string lastCharacters = value.Substring(value.Length - 2, 2);\n if (lastCharacters[0] == '\\\\') {\n if (lastCharacters[1] != 'n') {\n error(\"Unknown escape sequence. \", _line, position);\n }\n value = value.Substring(0, value.Length - 2).ToString() + \"\\n\";\n }\n }\n\n advance();\n }\n tokens.Add(new Token() { Type = TokenType.String, Value = value, Line = _line, Position = position - 1});\n }\n\n // match string literals\n if (match(\"'\", null, TokenType.Integer, discard:true)) {\n int value;\n int position = _position;\n value = CurrentCharacter.ToCharArray()[0];\n advance();\n\n // deal with empty literals ''\n if (value == '\\'')\n error(\"Empty character literal\", _line, _position);\n\n // deal with escaped characters, only need to worry about \\n and \\\\\n // throw werror on any other\n if (value == '\\\\') {\n if (CurrentCharacter == \"n\") {\n value = '\\n';\n } else if (CurrentCharacter == \"\\\\\") {\n value = '\\\\';\n } else {\n error(\"Unknown escape sequence. \", _line, _position - 1);\n }\n advance();\n }\n\n // if we haven't hit a closing ' here, there are two many characters\n // in the literal\n if (!match(\"'\", null, TokenType.Integer, discard: true))\n error(\"Multi-character constant\", _line, _position);\n\n tokens.Add(new Rosetta.Token() { Type = TokenType.Integer, Value = value.ToString(), Line = _line, Position = position - 1 });\n }\n\n // match comments by checking for starting token, then advancing\n // until closing token is matched\n if (match(\"/*\", null, TokenType.None, exact: true, discard: true)) {\n while (!match(\"*/\", null, TokenType.None, exact: true, discard: true)) {\n // reached the end of the file without closing comment!\n if (CurrentCharacter == \"\")\n error(\"End-of-file in comment. Closing comment characters not found.\", _line, _position);\n advance();\n }\n continue;\n }\n\n // match complex operators\n match(\"<=\", null, TokenType.Op_lessequal, exact: true);\n match(\">=\", null, TokenType.Op_greaterequal, exact: true);\n match(\"==\", null, TokenType.Op_equal, exact: true);\n match(\"!=\", null, TokenType.Op_notequal, exact: true);\n match(\"&&\", null, TokenType.Op_and, exact: true);\n match(\"||\", null, TokenType.Op_or, exact: true);\n\n // match simple operators\n if (match(_operators, null, TokenType.None, maxLen:1)) {\n Token match = tokens.Last();\n match.Type = _operatorTokenTypeMap[match.Value];\n }\n\n // brackets, braces and separators\n match(\"(\", null, TokenType.LeftParen, exact: true);\n match(\")\", null, TokenType.RightParen, exact: true);\n match(\"{\", null, TokenType.LeftBrace, exact: true);\n match(\"}\", null, TokenType.RightBrace, exact: true);\n match(\";\", null, TokenType.Semicolon, exact: true);\n match(\",\", null, TokenType.Comma, exact: true);\n\n }\n\n // end of file token\n tokens.Add(new Rosetta.Token() { Type = TokenType.End_of_input, Line = _line, Position = _position });\n\n return tokens;\n }\n\n static void Main (string[] args) {\n StreamReader inputFile;\n\n // if we passed in a filename, read code from that, else\n // read code from stdin\n if (args.Length > 0) {\n string path = args[0];\n try {\n inputFile = new StreamReader(path);\n } catch (IOException) {\n inputFile = new StreamReader(Console.OpenStandardInput(8192));\n }\n } else {\n inputFile = new StreamReader(Console.OpenStandardInput(8192));\n }\n\n string code = inputFile.ReadToEnd();\n\n // strip windows line endings out\n code = code.Replace(\"\\r\", \"\");\n\n LexicalScanner scanner = new LexicalScanner(code);\n List<Token> tokens = scanner.scan();\n\n foreach(Token token in tokens) {\n Console.WriteLine(token.ToString());\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": " >>SOURCE FORMAT IS FREE\n*> this code is dedicated to the public domain\n*> (GnuCOBOL) 2.3-dev.0\nidentification division.\nprogram-id. lexer.\nenvironment division.\nconfiguration section.\nrepository. function all intrinsic.\ninput-output section.\nfile-control.\n select input-file assign using input-name\n status input-status\n organization line sequential.\ndata division.\n\nfile section.\nfd input-file.\n01 input-record pic x(98).\n\nworking-storage section.\n01 input-name pic x(32).\n01 input-status pic xx.\n01 input-length pic 99.\n\n01 output-name pic x(32) value spaces.\n01 output-status pic xx.\n01 output-record pic x(64).\n\n01 line-no pic 999 value 0.\n01 col-no pic 99.\n01 col-no-max pic 99.\n01 col-increment pic 9 value 1.\n01 start-col pic 99.\n01 outx pic 99.\n01 out-lim pic 99 value 48.\n\n01 output-line value spaces.\n 03 out-line pic zzzz9.\n 03 out-column pic zzzzzz9.\n 03 message-area.\n 05 filler pic xxx.\n 05 token pic x(16).\n 05 out-value pic x(48).\n 05 out-integer redefines out-value pic zzzzz9.\n 05 out-integer1 redefines out-value pic zzzzzz9. *> to match the python lexer\n\n01 error-record.\n 03 error-line pic zzzz9 value 0.\n 03 error-col pic zzzzzz9 value 0.\n 03 error-message pic x(68) value spaces.\n\n01 scan-state pic x(16) value spaces.\n01 current-character pic x.\n01 previous-character pic x.\n\nprocedure division chaining input-name.\nstart-lexer.\n if input-name <> spaces\n open input input-file\n if input-status = '35'\n string 'in lexer ' trim(input-name) ' not found' into error-message\n perform report-error\n end-if\n end-if\n perform read-input-file\n perform until input-status <> '00'\n add 1 to line-no\n move line-no to out-line\n move length(trim(input-record,trailing)) to col-no-max\n move 1 to col-no\n move space to previous-character\n perform until col-no > col-no-max\n move col-no to out-column\n move input-record(col-no:1) to current-character\n evaluate scan-state\n\n when 'identifier'\n if current-character >= 'A' and <= 'Z'\n or (current-character >= 'a' and <= 'z')\n or (current-character >= '0' and <= '9')\n or current-character = '_'\n perform increment-outx\n move current-character to out-value(outx:1)\n if col-no = col-no-max\n perform process-identifier\n end-if\n else\n perform process-identifier\n if current-character <> space\n move 0 to col-increment\n end-if\n end-if\n\n when 'integer'\n evaluate true\n when current-character >= '0' and <= '9'\n perform increment-outx\n move current-character to out-value(outx:1)\n if col-no = col-no-max\n move numval(out-value) to out-integer\n move 'Integer' to token\n end-if\n when current-character >= 'A' and <= 'Z'\n when current-character >= 'a' and <= 'z'\n move 'in lexer invalid integer' to error-message\n perform report-error\n when other\n if outx > 5\n move numval(out-value) to out-integer1 *> to match the python lexer\n else\n move numval(out-value) to out-integer\n end-if\n move 'Integer' to token\n if current-character <> space\n move 0 to col-increment\n end-if\n end-evaluate\n\n when 'comment'\n if previous-character = '*' and current-character = '/'\n move 'comment' to token\n end-if\n\n when 'quote'\n evaluate current-character also outx\n when '\"' also 0\n string 'in lexer empty string' into error-message\n perform report-error\n when '\"' also any\n perform increment-outx\n move current-character to out-value(outx:1)\n move 'String' to token\n when other\n if col-no = col-no-max\n string 'in lexer missing close quote' into error-message\n perform report-error\n else\n perform increment-outx\n move current-character to out-value(outx:1)\n end-if\n end-evaluate\n\n when 'character'\n evaluate current-character also outx\n when \"'\" also 0\n string 'in lexer empty character constant' into error-message\n perform report-error\n when \"'\" also 1\n subtract 1 from ord(out-value(1:1)) giving out-integer\n move 'Integer' to token\n when \"'\" also 2\n evaluate true\n when out-value(1:2) = '\\n'\n move 10 to out-integer\n when out-value(1:2) = '\\\\'\n subtract 1 from ord('\\') giving out-integer *> ' (workaround a Rosetta Code highlighter problem)\n when other\n string 'in lexer unknown escape sequence ' out-value(1:2)\n into error-message\n perform report-error\n end-evaluate\n move 'Integer' to token\n when \"'\" also any\n string 'in lexer multicharacter constant' into error-message\n perform report-error\n when other\n if col-no = col-no-max\n string 'in lexer missing close quote' into error-message\n perform report-error\n end-if\n perform increment-outx\n move current-character to out-value(outx:1)\n end-evaluate\n\n when 'and'\n evaluate previous-character also current-character\n when '&' also '&'\n move 'Op_and' to token\n when other\n string 'in lexer AND error' into error-message\n perform report-error\n end-evaluate\n\n when 'or'\n evaluate previous-character also current-character\n when '|' also '|'\n move 'Op_or' to token\n when other\n string 'in lexer OR error' into error-message\n perform report-error\n end-evaluate\n\n when 'ambiguous'\n evaluate previous-character also current-character\n when '/' also '*'\n move 'comment' to scan-state\n subtract 1 from col-no giving start-col\n when '/' also any\n move 'Op_divide' to token\n move 0 to col-increment\n\n when '=' also '='\n move 'Op_equal' to token\n when '=' also any\n move 'Op_assign' to token\n move 0 to col-increment\n\n when '<' also '='\n move 'Op_lessequal' to token\n when '<' also any\n move 'Op_less' to token\n move 0 to col-increment\n\n when '>' also '='\n move 'Op_greaterequal' to token\n when '>'also any\n move 'Op_greater' to token\n move 0 to col-increment\n\n when '!' also '='\n move 'Op_notequal' to token\n when '!' also any\n move 'Op_not' to token\n move 0 to col-increment\n\n when other\n display input-record\n string 'in lexer ' trim(scan-state)\n ' unknown character \"' current-character '\"'\n ' with previous character \"' previous-character '\"'\n into error-message\n perform report-error\n end-evaluate\n\n when other\n move col-no to start-col\n evaluate current-character\n when space\n continue\n when >= 'A' and <= 'Z'\n when >= 'a' and <= 'z'\n move 'identifier' to scan-state\n move 1 to outx\n move current-character to out-value\n when >= '0' and <= '9'\n move 'integer' to scan-state\n move 1 to outx\n move current-character to out-value\n when '&'\n move 'and' to scan-state\n when '|'\n move 'or' to scan-state\n when '\"'\n move 'quote' to scan-state\n move 1 to outx\n move current-character to out-value\n when \"'\"\n move 'character' to scan-state\n move 0 to outx\n when '{'\n move 'LeftBrace' to token\n when '}'\n move 'RightBrace' to token\n when '('\n move 'LeftParen' to token\n when ')'\n move 'RightParen' to token\n when '+'\n move 'Op_add' to token\n when '-'\n move 'Op_subtract' to token\n when '*'\n move 'Op_multiply' to token\n when '%'\n move 'Op_mod' to token\n when ';'\n move 'Semicolon' to token\n when ','\n move 'Comma' to token\n when '/'\n when '<'\n when '>'\n when '='\n when '='\n when '<'\n when '>'\n when '!'\n move 'ambiguous' to scan-state\n when other\n string 'in lexer unknown character \"' current-character '\"'\n into error-message\n perform report-error\n end-evaluate\n end-evaluate\n\n if token <> spaces\n perform process-token\n end-if\n\n move current-character to previous-character\n add col-increment to col-no\n move 1 to col-increment\n end-perform\n if scan-state = 'ambiguous'\n evaluate previous-character\n when '/'\n move 'Op_divide' to token\n perform process-token\n\n when '='\n move 'Op_assign' to token\n perform process-token\n\n when '<'\n move 'Op_less' to token\n perform process-token\n\n when '>'\n move 'Op_greater' to token\n perform process-token\n\n when '!'\n move 'Op_not' to token\n perform process-token\n\n when other\n string 'in lexer unresolved ambiguous\n \"' previous-character '\" at end of line'\n into error-message\n perform report-error\n end-evaluate\n end-if\n perform read-input-file\n end-perform\n\n evaluate true\n when input-status <> '10'\n string 'in lexer ' trim(input-name) ' invalid input status ' input-status\n into error-message\n perform report-error\n when scan-state = 'comment'\n string 'in lexer unclosed comment at end of input' into error-message\n perform report-error\n end-evaluate\n\n move 'End_of_input' to token\n move 1 to out-column\n move 1 to start-col\n add 1 to line-no\n perform process-token\n\n close input-file\n stop run\n .\nprocess-identifier.\n evaluate true\n when out-value = 'print'\n move 'Keyword_print' to token\n move spaces to out-value\n when out-value = 'while'\n move 'Keyword_while' to token\n move spaces to out-value\n when out-value = 'if'\n move 'Keyword_if' to token\n move spaces to out-value\n when out-value = 'else'\n move 'Keyword_else' to token\n move spaces to out-value\n when out-value = 'putc'\n move 'Keyword_putc' to token\n move spaces to out-value\n when other\n move 'Identifier' to token\n end-evaluate\n .\nincrement-outx.\n if outx >= out-lim\n string 'in lexer token value length exceeds ' out-lim into error-message\n perform report-error\n end-if\n add 1 to outx\n .\nprocess-token.\n if token <> 'comment'\n move start-col to out-column\n move line-no to out-line\n display output-line\n end-if\n move 0 to start-col\n move spaces to scan-state message-area\n .\nreport-error.\n move line-no to error-line\n move start-col to error-col\n display error-record\n close input-file\n stop run with error status -1\n .\nread-input-file.\n if input-name = spaces\n move '00' to input-status\n accept input-record on exception move '10' to input-status end-accept\n else\n read input-file\n end-if\n .\nend program lexer.\n", "language": "COBOL" }, { "code": "(defpackage #:lexical-analyzer\n (:use #:cl #:sb-gray)\n (:export #:main))\n\n(in-package #:lexical-analyzer)\n\n(defconstant +lex-symbols-package+ (or (find-package :lex-symbols)\n (make-package :lex-symbols)))\n\n(defclass counting-character-input-stream (fundamental-character-input-stream)\n ((stream :type stream :initarg :stream :reader stream-of)\n (line :type fixnum :initform 1 :accessor line-of)\n (column :type fixnum :initform 0 :accessor column-of)\n (prev-column :type (or null fixnum) :initform nil :accessor prev-column-of))\n (:documentation \"Character input stream that counts lines and columns.\"))\n\n(defmethod stream-read-char ((stream counting-character-input-stream))\n (let ((ch (read-char (stream-of stream) nil :eof)))\n (case ch\n (#\\Newline\n (incf (line-of stream))\n (setf (prev-column-of stream) (column-of stream)\n (column-of stream) 0))\n (t\n (incf (column-of stream))))\n ch))\n\n(defmethod stream-unread-char ((stream counting-character-input-stream) char)\n (unread-char char (stream-of stream))\n (case char\n (#\\Newline\n (decf (line-of stream))\n (setf (column-of stream) (prev-column-of stream)))\n (t\n (decf (column-of stream)))))\n\n(defstruct token\n (name nil :type symbol)\n (value nil :type t)\n (line nil :type fixnum)\n (column nil :type fixnum))\n\n(defun lexer-error (format-control &rest args)\n (apply #'error format-control args))\n\n(defun handle-divide-or-comment (stream char)\n (declare (ignore char))\n (case (peek-char nil stream t nil t)\n (#\\* (loop with may-end = nil\n initially (read-char stream t nil t)\n for ch = (read-char stream t nil t)\n until (and may-end (char= ch #\\/))\n do (setf may-end (char= ch #\\*))\n finally (return (read stream t nil t))))\n (t (make-token :name :op-divide :line (line-of stream) :column (column-of stream)))))\n\n(defun make-constant-handler (token-name)\n (lambda (stream char)\n (declare (ignore char))\n (make-token :name token-name :line (line-of stream) :column (column-of stream))))\n\n(defun make-this-or-that-handler (expect then &optional else)\n (lambda (stream char)\n (declare (ignore char))\n (let ((line (line-of stream))\n (column (column-of stream))\n (next (peek-char nil stream nil nil t)))\n (cond ((and expect (char= next expect))\n (read-char stream nil nil t)\n (make-token :name then :line line :column column))\n (else\n (make-token :name else :line line :column column))\n (t\n (lexer-error \"Unrecognized character '~A'\" next))))))\n\n(defun identifier? (symbol)\n (and (symbolp symbol)\n (not (keywordp symbol))\n (let ((name (symbol-name symbol)))\n (and (find (char name 0) \"_abcdefghijklmnopqrstuvwxyz\" :test #'char-equal)\n (or (< (length name) 2)\n (not (find-if-not (lambda (ch)\n (find ch \"_abcdefghijklmnopqrstuvwxyz0123456789\"\n :test #'char-equal))\n name :start 1)))))))\n\n(defun id->keyword (id line column)\n (case id\n (lex-symbols::|if| (make-token :name :keyword-if :line line :column column))\n (lex-symbols::|else| (make-token :name :keyword-else :line line :column column))\n (lex-symbols::|while| (make-token :name :keyword-while :line line :column column))\n (lex-symbols::|print| (make-token :name :keyword-print :line line :column column))\n (lex-symbols::|putc| (make-token :name :keyword-putc :line line :column column))\n (t nil)))\n\n(defun handle-identifier (stream char)\n (let ((*readtable* (copy-readtable)))\n (set-syntax-from-char char #\\z)\n (let ((line (line-of stream))\n (column (column-of stream)))\n (unread-char char stream)\n (let ((obj (read stream t nil t)))\n (if (identifier? obj)\n (or (id->keyword obj line column)\n (make-token :name :identifier :value obj :line line :column column))\n (lexer-error \"Invalid identifier name: ~A\" obj))))))\n\n(defun handle-integer (stream char)\n (let ((*readtable* (copy-readtable)))\n (set-syntax-from-char char #\\z)\n (let ((line (line-of stream))\n (column (column-of stream)))\n (unread-char char stream)\n (let ((obj (read stream t nil t)))\n (if (integerp obj)\n (make-token :name :integer :value obj :line line :column column)\n (lexer-error \"Invalid integer: ~A\" obj))))))\n\n(defun handle-char-literal (stream char)\n (declare (ignore char))\n (let* ((line (line-of stream))\n (column (column-of stream))\n (ch (read-char stream t nil t))\n (parsed (case ch\n (#\\' (lexer-error \"Empty character constant\"))\n (#\\Newline (lexer-error \"New line in character literal\"))\n (#\\\\ (let ((next-ch (read-char stream t nil t)))\n (case next-ch\n (#\\n #\\Newline)\n (#\\\\ #\\\\)\n (t (lexer-error \"Unknown escape sequence: \\\\~A\" next-ch)))))\n (t ch))))\n (if (char= #\\' (read-char stream t nil t))\n (make-token :name :integer :value (char-code parsed) :line line :column column)\n (lexer-error \"Only one character is allowed in character literal\"))))\n\n(defun handle-string (stream char)\n (declare (ignore char))\n (loop with result = (make-array 0 :element-type 'character :adjustable t :fill-pointer t)\n with line = (line-of stream)\n with column = (column-of stream)\n for ch = (read-char stream t nil t)\n until (char= ch #\\\")\n do (setf ch (case ch\n (#\\Newline (lexer-error \"New line in string\"))\n (#\\\\ (let ((next-ch (read-char stream t nil t)))\n (case next-ch\n (#\\n #\\Newline)\n (#\\\\ #\\\\)\n (t (lexer-error \"Unknown escape sequence: \\\\~A\" next-ch)))))\n (t ch)))\n (vector-push-extend ch result)\n finally (return (make-token :name :string :value result :line line :column column))))\n\n(defun make-lexer-readtable ()\n (let ((*readtable* (copy-readtable nil)))\n (setf (readtable-case *readtable*) :preserve)\n (set-syntax-from-char #\\\\ #\\z)\n (set-syntax-from-char #\\# #\\z)\n (set-syntax-from-char #\\` #\\z)\n\n ;; operators\n (set-macro-character #\\* (make-constant-handler :op-multiply))\n (set-macro-character #\\/ #'handle-divide-or-comment)\n (set-macro-character #\\% (make-constant-handler :op-mod))\n (set-macro-character #\\+ (make-constant-handler :op-add))\n (set-macro-character #\\- (make-constant-handler :op-subtract))\n (set-macro-character #\\< (make-this-or-that-handler #\\= :op-lessequal :op-less))\n (set-macro-character #\\> (make-this-or-that-handler #\\= :op-greaterequal :op-greater))\n (set-macro-character #\\= (make-this-or-that-handler #\\= :op-equal :op-assign))\n (set-macro-character #\\! (make-this-or-that-handler #\\= :op-notequal :op-not))\n (set-macro-character #\\& (make-this-or-that-handler #\\& :op-and))\n (set-macro-character #\\| (make-this-or-that-handler #\\| :op-or))\n\n ;; symbols\n (set-macro-character #\\( (make-constant-handler :leftparen))\n (set-macro-character #\\) (make-constant-handler :rightparen))\n (set-macro-character #\\{ (make-constant-handler :leftbrace))\n (set-macro-character #\\} (make-constant-handler :rightbrace))\n (set-macro-character #\\; (make-constant-handler :semicolon))\n (set-macro-character #\\, (make-constant-handler :comma))\n\n ;; identifiers & keywords\n (set-macro-character #\\_ #'handle-identifier t)\n (loop for ch across \"abcdefghijklmnopqrstuvwxyz\"\n do (set-macro-character ch #'handle-identifier t))\n (loop for ch across \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n do (set-macro-character ch #'handle-identifier t))\n\n ;; integers\n (loop for ch across \"0123456789\"\n do (set-macro-character ch #'handle-integer t))\n (set-macro-character #\\' #'handle-char-literal)\n\n ;; strings\n (set-macro-character #\\\" #'handle-string)\n\n *readtable*))\n\n(defun lex (stream)\n (loop with *readtable* = (make-lexer-readtable)\n with *package* = +lex-symbols-package+\n with eof = (gensym)\n with counting-stream = (make-instance 'counting-character-input-stream :stream stream)\n for token = (read counting-stream nil eof)\n until (eq token eof)\n do (format t \"~5D ~5D ~15A~@[ ~S~]~%\"\n (token-line token) (token-column token) (token-name token) (token-value token))\n finally (format t \"~5D ~5D ~15A~%\"\n (line-of counting-stream) (column-of counting-stream) :end-of-input)\n (close counting-stream)))\n\n(defun main ()\n (lex *standard-input*))\n", "language": "Common-Lisp" }, { "code": "#!/bin/env elixir\n# -*- elixir -*-\n\ndefmodule Lex do\n\n def main args do\n {inpf_name, outf_name, exit_status} =\n case args do\n [] -> {\"-\", \"-\", 0}\n [name] -> {name, \"-\", 0}\n [name1, name2] -> {name1, name2, 0}\n [name1, name2 | _] -> {name1, name2, usage_error()}\n end\n\n {inpf, outf, exit_status} =\n case {inpf_name, outf_name, exit_status} do\n {\"-\", \"-\", 0} -> {:stdio, :stdio, 0}\n {name1, \"-\", 0} ->\n {inpf, exit_status} = open_file(name1, [:read])\n {inpf, :stdio, exit_status}\n {\"-\", name2, 0} ->\n {outf, exit_status} = open_file(name2, [:write])\n {:stdio, outf, exit_status}\n {name1, name2, 0} ->\n {inpf, exit_status} = open_file(name1, [:read])\n if exit_status != 0 do\n {inpf, name2, exit_status}\n else\n {outf, exit_status} = open_file(name2, [:write])\n {inpf, outf, exit_status}\n end\n _ -> {inpf_name, outf_name, exit_status}\n end\n\n exit_status =\n case exit_status do\n 0 -> main_program inpf, outf\n _ -> exit_status\n end\n\n # Choose one.\n System.halt exit_status # Fast exit.\n #System.stop exit_status # Laborious cleanup.\n end\n\n def main_program inpf, outf do\n inp = make_inp inpf\n scan_text outf, inp\n exit_status = 0\n exit_status\n end\n\n def open_file name, rw do\n case File.open name, rw do\n {:ok, f} -> {f, 0}\n _ ->\n IO.write :stderr, \"Cannot open \"\n IO.write :stderr, name\n case rw do\n [:read] -> IO.puts \" for input\"\n [:write] -> IO.puts \" for output\"\n end\n {name, 1}\n end\n end\n\n def scan_text outf, inp do\n {toktup, inp} = get_next_token inp\n print_token outf, toktup\n case toktup do\n {\"End_of_input\", _, _, _} -> :ok\n _ -> scan_text outf, inp\n end\n end\n\n def print_token outf, {tok, arg, line_no, column_no} do\n IO.write outf, (String.pad_leading \"#{line_no}\", 5)\n IO.write outf, \" \"\n IO.write outf, (String.pad_leading \"#{column_no}\", 5)\n IO.write outf, \" \"\n IO.write outf, tok\n case tok do\n \"Identifier\" ->\n IO.write outf, \" \"\n IO.write outf, arg\n \"Integer\" ->\n IO.write outf, \" \"\n IO.write outf, arg\n \"String\" ->\n IO.write outf, \" \"\n IO.write outf, arg\n _ -> :ok\n end\n IO.puts outf, \"\"\n end\n\n###-------------------------------------------------------------------\n###\n### The token dispatcher.\n###\n\n def get_next_token inp do\n inp = skip_spaces_and_comments inp\n {ch, inp} = get_ch inp\n {chr, line_no, column_no} = ch\n ln = line_no\n cn = column_no\n case chr do\n :eof -> {{\"End_of_input\", \"\", ln, cn}, inp}\n \",\" -> {{\"Comma\", \",\", ln, cn}, inp}\n \";\" -> {{\"Semicolon\", \";\", ln, cn}, inp}\n \"(\" -> {{\"LeftParen\", \"(\", ln, cn}, inp}\n \")\" -> {{\"RightParen\", \")\", ln, cn}, inp}\n \"{\" -> {{\"LeftBrace\", \"{\", ln, cn}, inp}\n \"}\" -> {{\"RightBrace\", \"}\", ln, cn}, inp}\n \"*\" -> {{\"Op_multiply\", \"*\", ln, cn}, inp}\n \"/\" -> {{\"Op_divide\", \"/\", ln, cn}, inp}\n \"%\" -> {{\"Op_mod\", \"%\", ln, cn}, inp}\n \"+\" -> {{\"Op_add\", \"+\", ln, cn}, inp}\n \"-\" -> {{\"Op_subtract\", \"-\", ln, cn}, inp}\n \"<\" ->\n {ch1, inp} = get_ch inp\n {chr1, _, _} = ch1\n case chr1 do\n \"=\" -> {{\"Op_lessequal\", \"<=\", ln, cn}, inp}\n _ -> {{\"Op_less\", \"<\", ln, cn}, (push_back ch1, inp)}\n end\n \">\" ->\n {ch1, inp} = get_ch inp\n {chr1, _, _} = ch1\n case chr1 do\n \"=\" -> {{\"Op_greaterequal\", \">=\", ln, cn}, inp}\n _ -> {{\"Op_greater\", \">\", ln, cn}, (push_back ch1, inp)}\n end\n \"=\" ->\n {ch1, inp} = get_ch inp\n {chr1, _, _} = ch1\n case chr1 do\n \"=\" -> {{\"Op_equal\", \"==\", ln, cn}, inp}\n _ -> {{\"Op_assign\", \"=\", ln, cn}, (push_back ch1, inp)}\n end\n \"!\" ->\n {ch1, inp} = get_ch inp\n {chr1, _, _} = ch1\n case chr1 do\n \"=\" -> {{\"Op_notequal\", \"!=\", ln, cn}, inp}\n _ -> {{\"Op_not\", \"!\", ln, cn}, (push_back ch1, inp)}\n end\n \"&\" ->\n {ch1, inp} = get_ch inp\n {chr1, _, _} = ch1\n case chr1 do\n \"&\" -> {{\"Op_and\", \"&&\", ln, cn}, inp}\n _ -> unexpected_character ln, cn, chr\n end\n \"|\" ->\n {ch1, inp} = get_ch inp\n {chr1, _, _} = ch1\n case chr1 do\n \"|\" -> {{\"Op_or\", \"||\", ln, cn}, inp}\n _ -> unexpected_character ln, cn, chr\n end\n \"\\\"\" ->\n inp = push_back ch, inp\n scan_string_literal inp\n \"'\" ->\n inp = push_back ch, inp\n scan_character_literal inp\n _ ->\n cond do\n String.match? chr, ~r/^[[:digit:]]$/u ->\n inp = push_back ch, inp\n scan_integer_literal inp\n String.match? chr, ~r/^[[:alpha:]_]$/u ->\n inp = push_back ch, inp\n scan_identifier_or_reserved_word inp\n true -> unexpected_character ln, cn, chr\n end\n end\n end\n\n###-------------------------------------------------------------------\n###\n### Skipping past spaces and /* ... */ comments.\n###\n### Comments are treated exactly like a bit of whitespace. They never\n### make it to the dispatcher.\n###\n\n def skip_spaces_and_comments inp do\n {ch, inp} = get_ch inp\n {chr, line_no, column_no} = ch\n cond do\n chr == :eof -> push_back ch, inp\n String.match? chr, ~r/^[[:space:]]$/u ->\n skip_spaces_and_comments inp\n chr == \"/\" ->\n {ch1, inp} = get_ch inp\n case ch1 do\n {\"*\", _, _} ->\n inp = scan_comment inp, line_no, column_no\n skip_spaces_and_comments inp\n _ -> push_back ch, (push_back ch1, inp)\n end\n true -> push_back ch, inp\n end\n end\n\n def scan_comment inp, line_no, column_no do\n {ch, inp} = get_ch inp\n case ch do\n {:eof, _, _} -> unterminated_comment line_no, column_no\n {\"*\", _, _} ->\n {ch1, inp} = get_ch inp\n case ch1 do\n {:eof, _, _} -> unterminated_comment line_no, column_no\n {\"/\", _, _} -> inp\n _ -> scan_comment inp, line_no, column_no\n end\n _ -> scan_comment inp, line_no, column_no\n end\n end\n\n###-------------------------------------------------------------------\n###\n### Scanning of integer literals, identifiers, and reserved words.\n###\n### These three types of token are very similar to each other.\n###\n\n def scan_integer_literal inp do\n # Scan an entire word, not just digits. This way we detect\n # erroneous text such as \"23skidoo\".\n {line_no, column_no, inp} = get_position inp\n {word, inp} = scan_word inp\n if String.match? word, (~r/^[[:digit:]]+$/u) do\n {{\"Integer\", word, line_no, column_no}, inp}\n else\n invalid_integer_literal line_no, column_no, word\n end\n end\n\n def scan_identifier_or_reserved_word inp do\n # It is assumed that the first character is of the correct type,\n # thanks to the dispatcher.\n {line_no, column_no, inp} = get_position inp\n {word, inp} = scan_word inp\n tok =\n case word do\n \"if\" -> \"Keyword_if\"\n \"else\" -> \"Keyword_else\"\n \"while\" -> \"Keyword_while\"\n \"print\" -> \"Keyword_print\"\n \"putc\" -> \"Keyword_putc\"\n _ -> \"Identifier\"\n end\n {{tok, word, line_no, column_no}, inp}\n end\n\n def scan_word inp, word\\\\\"\" do\n {ch, inp} = get_ch inp\n {chr, _, _} = ch\n if String.match? chr, (~r/^[[:alnum:]_]$/u) do\n scan_word inp, (word <> chr)\n else\n {word, (push_back ch, inp)}\n end\n end\n\n def get_position inp do\n {ch, inp} = get_ch inp\n {_, line_no, column_no} = ch\n inp = push_back ch, inp\n {line_no, column_no, inp}\n end\n\n###-------------------------------------------------------------------\n###\n### Scanning of string literals.\n###\n### It is assumed that the first character is the opening quote, and\n### that the closing quote is the same character.\n###\n\n def scan_string_literal inp do\n {ch, inp} = get_ch inp\n {quote_mark, line_no, column_no} = ch\n {contents, inp} = scan_str_lit inp, ch\n {{\"String\", quote_mark <> contents <> quote_mark,\n line_no, column_no},\n inp}\n end\n\n def scan_str_lit inp, ch, contents\\\\\"\" do\n {quote_mark, line_no, column_no} = ch\n {ch1, inp} = get_ch inp\n {chr1, line_no1, column_no1} = ch1\n if chr1 == quote_mark do\n {contents, inp}\n else\n case chr1 do\n :eof -> eoi_in_string_literal line_no, column_no\n \"\\n\" -> eoln_in_string_literal line_no, column_no\n \"\\\\\" ->\n {ch2, inp} = get_ch inp\n {chr2, _, _} = ch2\n case chr2 do\n \"n\" -> scan_str_lit inp, ch, (contents <> \"\\\\n\")\n \"\\\\\" -> scan_str_lit inp, ch, (contents <> \"\\\\\\\\\")\n _ -> unsupported_escape line_no1, column_no1, chr2\n end\n _ -> scan_str_lit inp, ch, (contents <> chr1)\n end\n end\n end\n\n###-------------------------------------------------------------------\n###\n### Scanning of character literals.\n###\n### It is assumed that the first character is the opening quote, and\n### that the closing quote is the same character.\n###\n### The tedious part of scanning a character literal is distinguishing\n### between the kinds of lexical error. (One might wish to modify the\n### code to detect, as a distinct kind of error, end of line within a\n### character literal.)\n###\n\n def scan_character_literal inp do\n {ch, inp} = get_ch inp\n {_, line_no, column_no} = ch\n {ch1, inp} = get_ch inp\n {chr1, line_no1, column_no1} = ch1\n {intval, inp} =\n case chr1 do\n :eof -> unterminated_character_literal line_no, column_no\n \"\\\\\" ->\n {ch2, inp} = get_ch inp\n {chr2, _, _} = ch2\n case chr2 do\n :eof -> unterminated_character_literal line_no, column_no\n \"n\" -> {(:binary.first \"\\n\"), inp}\n \"\\\\\" -> {(:binary.first \"\\\\\"), inp}\n _ -> unsupported_escape line_no1, column_no1, chr2\n end\n _ -> {(:binary.first chr1), inp}\n end\n inp = check_character_literal_end inp, ch\n {{\"Integer\", \"#{intval}\", line_no, column_no}, inp}\n end\n\n def check_character_literal_end inp, ch do\n {chr, _, _} = ch\n {{chr1, _, _}, inp} = get_ch inp\n if chr1 == chr do\n inp\n else\n # Lexical error.\n find_char_lit_end inp, ch\n end\n end\n\n def find_char_lit_end inp, ch do\n {chr, line_no, column_no} = ch\n {{chr1, _, _}, inp} = get_ch inp\n if chr1 == chr do\n multicharacter_literal line_no, column_no\n else\n case chr1 do\n :eof -> unterminated_character_literal line_no, column_no\n _ -> find_char_lit_end inp, ch\n end\n end\n end\n\n###-------------------------------------------------------------------\n###\n### Character-at-a-time input, with unrestricted pushback, and with\n### line and column numbering.\n###\n\n def make_inp inpf do\n {inpf, [], 1, 1}\n end\n\n def get_ch {inpf, pushback, line_no, column_no} do\n case pushback do\n [head | tail] ->\n {head, {inpf, tail, line_no, column_no}}\n [] ->\n case IO.read(inpf, 1) do\n :eof ->\n {{:eof, line_no, column_no},\n {inpf, pushback, line_no, column_no}}\n {:error, _} ->\n {{:eof, line_no, column_no},\n {inpf, pushback, line_no, column_no}}\n chr ->\n case chr do\n \"\\n\" ->\n {{chr, line_no, column_no},\n {inpf, pushback, line_no + 1, 1}}\n _ ->\n {{chr, line_no, column_no},\n {inpf, pushback, line_no, column_no + 1}}\n end\n end\n end\n end\n\n def push_back ch, {inpf, pushback, line_no, column_no} do\n {inpf, [ch | pushback], line_no, column_no}\n end\n\n###-------------------------------------------------------------------\n###\n### Lexical and usage errors.\n###\n\n def unterminated_comment line_no, column_no do\n raise \"#{scriptname()}: unterminated comment at #{line_no}:#{column_no}\"\n end\n\n def invalid_integer_literal line_no, column_no, word do\n raise \"#{scriptname()}: invalid integer literal #{word} at #{line_no}:#{column_no}\"\n end\n\n def unsupported_escape line_no, column_no, chr do\n raise \"#{scriptname()}: unsupported escape \\\\#{chr} at #{line_no}:#{column_no}\"\n end\n\n def eoi_in_string_literal line_no, column_no do\n raise \"#{scriptname()}: end of input in string literal starting at #{line_no}:#{column_no}\"\n end\n\n def eoln_in_string_literal line_no, column_no do\n raise \"#{scriptname()}: end of line in string literal starting at #{line_no}:#{column_no}\"\n end\n\n def multicharacter_literal line_no, column_no do\n raise \"#{scriptname()}: unsupported multicharacter literal at #{line_no}:#{column_no}\"\n end\n\n def unterminated_character_literal line_no, column_no do\n raise \"#{scriptname()}: unterminated character literal starting at #{line_no}:#{column_no}\"\n end\n\n def unexpected_character line_no, column_no, chr do\n raise \"#{scriptname()}: unexpected character '#{chr}' at #{line_no}:#{column_no}\"\n end\n\n def usage_error() do\n IO.puts \"Usage: #{scriptname()} [INPUTFILE [OUTPUTFILE]]\"\n IO.puts \"If either of INPUTFILE or OUTPUTFILE is not present or is \\\"-\\\",\"\n IO.puts \"standard input or standard output is used, respectively.\"\n exit_status = 2\n exit_status\n end\n\n def scriptname() do\n Path.basename(__ENV__.file)\n end\n\n#---------------------------------------------------------------------\n\nend ## module Lex\n\nLex.main(System.argv)\n", "language": "Elixir" }, { "code": "#!/usr/bin/emacs --script\n;;\n;; The Rosetta Code lexical analyzer in GNU Emacs Lisp.\n;;\n;; Migrated from the ATS. However, Emacs Lisp is not friendly to the\n;; functional style of the ATS implementation; therefore the\n;; differences are vast.\n;;\n;; (A Scheme migration could easily, on the other hand, have been\n;; almost exact. It is interesting to contrast Lisp dialects and see\n;; how huge the differences are.)\n;;\n;; The script currently takes input only from standard input and\n;; writes the token stream only to standard output.\n;;\n\n(require 'cl-lib)\n\n;;; The type of a character, consisting of its code point and where it\n;;; occurred in the text.\n(cl-defstruct (ch_t (:constructor make-ch (ichar line-no column-no)))\n ichar line-no column-no)\n\n(defun ch-ichar (ch)\n (ch_t-ichar ch))\n\n(defun ch-line-no (ch)\n (ch_t-line-no ch))\n\n(defun ch-column-no (ch)\n (ch_t-column-no ch))\n\n;;; The type of an \"inputter\", consisting of an open file for the\n;;; text, a pushback buffer (which is an indefinitely deep stack of\n;;; ch_t), an input buffer for the current line, and a position in the\n;;; text.\n(cl-defstruct inp_t file pushback line line-no column-no)\n\n(defun make-inp (file)\n \"Initialize a new inp_t.\"\n (make-inp_t :file file\n :pushback '()\n :line \"\"\n :line-no 0\n :column-no 0))\n\n(defvar inp (make-inp t)\n \"A global inp_t.\")\n\n(defun get-ch ()\n \"Get a ch_t, either from the pushback buffer or from the input.\"\n (pcase (inp_t-pushback inp)\n (`(,ch . ,tail)\n ;; Emacs Lisp has only single value return, so the results come\n ;; back as a list rather than multiple values.\n (setq inp (make-inp_t :file (inp_t-file inp)\n :pushback tail\n :line (inp_t-line inp)\n :line-no (inp_t-line-no inp)\n :column-no (inp_t-column-no inp)))\n ch)\n ('()\n (let ((line (inp_t-line inp))\n (line-no (inp_t-line-no inp))\n (column-no (inp_t-column-no inp)))\n (when (string= line \"\")\n ;; Refill the buffer.\n (let ((text\n (condition-case nil (read-string \"\")\n nil (error 'eoi))))\n (if (eq text 'eoi)\n (setq line 'eoi)\n (setq line (format \"%s%c\" text ?\\n)))\n (setq line-no (1+ line-no))\n (setq column-no 1)))\n (if (eq line 'eoi)\n (progn\n (setq inp (make-inp_t :file (inp_t-file inp)\n :pushback (inp_t-pushback inp)\n :line line\n :line-no line-no\n :column-no column-no))\n (make-ch 'eoi line-no column-no))\n (let ((c (elt line 0))\n (line (substring line 1)))\n (setq inp (make-inp_t :file (inp_t-file inp)\n :pushback (inp_t-pushback inp)\n :line line\n :line-no line-no\n :column-no (1+ column-no)))\n (make-ch c line-no column-no)))))))\n\n(defun get-new-line (file)\n ;; Currently \"file\" is ignored and the input must be from stdin.\n (read-from-minibuffer \"\" :default 'eoi))\n\n(defun push-back (ch)\n \"Push back a ch_t.\"\n (setq inp (make-inp_t :file (inp_t-file inp)\n :pushback (cons ch (inp_t-pushback inp))\n :line (inp_t-line inp)\n :line-no (inp_t-line-no inp)\n :column-no (inp_t-column-no inp))))\n\n(defun get-position ()\n \"Return the line-no and column-no of the next ch_t to be\nreturned by get-ch, assuming there are no more pushbacks\nbeforehand.\"\n (let* ((ch (get-ch))\n (line-no (ch-line-no ch))\n (column-no (ch-column-no ch)))\n (push-back ch)\n (list line-no column-no)))\n\n(defun scan-text (outf)\n \"The main loop.\"\n (cl-loop for toktup = (get-next-token)\n do (print-token outf toktup)\n until (string= (elt toktup 0) \"End_of_input\")))\n\n(defun print-token (outf toktup)\n \"Print a token, along with its position and possibly an\nargument.\"\n ;; Currently outf is ignored, and the output goes to stdout.\n (pcase toktup\n (`(,tok ,arg ,line-no ,column-no)\n (princ (format \"%5d %5d %s\" line-no column-no tok))\n (pcase tok\n (\"Identifier\" (princ (format \" %s\\n\" arg)))\n (\"Integer\" (princ (format \" %s\\n\" arg)))\n (\"String\" (princ (format \" %s\\n\" arg)))\n (_ (princ \"\\n\"))))))\n\n(defun get-next-token ()\n \"The token dispatcher. Returns the next token, as a list along\nwith its argument and text position.\"\n (skip-spaces-and-comments)\n (let* ((ch (get-ch))\n (ln (ch-line-no ch))\n (cn (ch-column-no ch)))\n (pcase (ch-ichar ch)\n ('eoi (list \"End_of_input\" \"\" ln cn))\n (?, (list \"Comma\" \",\" ln cn))\n (?\\N{SEMICOLON} (list \"Semicolon\" \";\" ln cn))\n (?\\N{LEFT PARENTHESIS} (list \"LeftParen\" \"(\" ln cn))\n (?\\N{RIGHT PARENTHESIS} (list \"RightParen\" \")\" ln cn))\n (?{ (list \"LeftBrace\" \"{\" ln cn))\n (?} (list \"RightBrace\" \"}\" ln cn))\n (?* (list \"Op_multiply\" \"*\" ln cn))\n (?/ (list \"Op_divide\" \"/\" ln cn))\n (?% (list \"Op_mod\" \"%\" ln cn))\n (?+ (list \"Op_add\" \"+\" ln cn))\n (?- (list \"Op_subtract\" \"-\" ln cn))\n (?< (let ((ch1 (get-ch)))\n (pcase (ch-ichar ch1)\n (?= (list \"Op_lessequal\" \"<=\" ln cn))\n (_ (push-back ch1)\n (list \"Op_less\" \"<\" ln cn)))))\n (?> (let ((ch1 (get-ch)))\n (pcase (ch-ichar ch1)\n (?= (list \"Op_greaterequal\" \">=\" ln cn))\n (_ (push-back ch1)\n (list \"Op_greater\" \">\" ln cn)))))\n (?= (let ((ch1 (get-ch)))\n (pcase (ch-ichar ch1)\n (?= (list \"Op_equal\" \"==\" ln cn))\n (_ (push-back ch1)\n (list \"Op_assign\" \"=\" ln cn)))))\n (?! (let ((ch1 (get-ch)))\n (pcase (ch-ichar ch1)\n (?= (list \"Op_notequal\" \"!=\" ln cn))\n (_ (push-back ch1)\n (list \"Op_not\" \"!\" ln cn)))))\n (?& (let ((ch1 (get-ch)))\n (pcase (ch-ichar ch1)\n (?& (list \"Op_and\" \"&&\" ln cn))\n (_ (unexpected-character ln cn (get-ichar ch))))))\n (?| (let ((ch1 (get-ch)))\n (pcase (ch-ichar ch1)\n (?| (list \"Op_or\" \"||\" ln cn))\n (_ (unexpected-character ln cn (get-ichar ch))))))\n (?\\N{QUOTATION MARK} (push-back ch) (scan-string-literal))\n (?\\N{APOSTROPHE} (push-back ch) (scan-character-literal))\n ((pred digitp) (push-back ch) (scan-integer-literal))\n ((pred identifier-start-p)\n (progn\n (push-back ch)\n (scan-identifier-or-reserved-word)))\n (c (unexpected-character ln cn c)))))\n\n(defun skip-spaces-and-comments ()\n \"Skip spaces and comments. A comment is treated as equivalent\nto a run of spaces.\"\n (cl-loop for ch = (let ((ch1 (get-ch)))\n (pcase (ch-ichar ch1)\n (?/ (let* ((ch2 (get-ch))\n (line-no (ch-line-no ch1))\n (column-no (ch-column-no ch1))\n (position `(,line-no ,column-no)))\n (pcase (ch-ichar ch2)\n (?* (scan-comment position)\n (get-ch))\n (_ (push-back ch2)\n ch1))))\n (_ ch1)))\n while (spacep (ch-ichar ch))\n finally do (push-back ch)))\n\n(defun scan-comment (position)\n (cl-loop for ch = (get-ch)\n for done = (comment-done-p ch position)\n until done))\n\n(defun comment-done-p (ch position)\n (pcase (ch-ichar ch)\n ('eoi (apply 'unterminated-comment position))\n (?* (let ((ch1 (get-ch)))\n (pcase (ch-ichar ch1)\n ('eoi (apply 'unterminated-comment position))\n (?/ t)\n (_ nil))))\n (_ nil)))\n\n(defun scan-integer-literal ()\n \"Scan an integer literal, on the assumption that a digit has\nbeen seen and pushed back.\"\n (let* ((position (get-position))\n (lst (scan-word))\n (s (list-to-string lst)))\n (if (all-digits-p lst)\n `(\"Integer\" ,s . ,position)\n (apply 'illegal-integer-literal `(,@position , s)))))\n\n(defun scan-identifier-or-reserved-word ()\n \"Scan an identifier or reserved word, on the assumption that a\nlegal first character (for an identifier) has been seen and\npushed back.\"\n (let* ((position (get-position))\n (lst (scan-word))\n (s (list-to-string lst))\n (tok (pcase s\n (\"else\" \"Keyword_else\")\n (\"if\" \"Keyword_if\")\n (\"while\" \"Keyword_while\")\n (\"print\" \"Keyword_print\")\n (\"putc\" \"Keyword_putc\")\n (_ \"Identifier\"))))\n `(,tok ,s . ,position)))\n\n(defun scan-word ()\n (cl-loop for ch = (get-ch)\n while (identifier-continuation-p (ch-ichar ch))\n collect (ch-ichar ch)\n finally do (push-back ch)))\n\n(defun scan-string-literal ()\n \"Scan a string literal, on the assumption that a double quote\nhas been seen and pushed back.\"\n (let* ((ch (get-ch))\n (_ (cl-assert (= (ch-ichar ch) ?\\N{QUOTATION MARK})))\n (line-no (ch-line-no ch))\n (column-no (ch-column-no ch))\n (position `(,line-no ,column-no))\n (lst (scan-str-lit position))\n (lst `(?\\N{QUOTATION MARK} ,@lst ?\\N{QUOTATION MARK})))\n `(\"String\" ,(list-to-string lst) . ,position)))\n\n(defun scan-str-lit (position)\n (flatten\n (cl-loop for ch = (get-ch)\n until (= (ch-ichar ch) ?\\N{QUOTATION MARK})\n collect (process-str-lit-character\n (ch-ichar ch) position))))\n\n(defun process-str-lit-character (c position)\n ;; NOTE: This script might insert a newline before any eoi, so that\n ;; \"end-of-input-in-string-literal\" never actually occurs. It is a\n ;; peculiarity of the script's input mechanism.\n (pcase c\n ('eoi (apply 'end-of-input-in-string-literal position))\n (?\\n (apply 'end-of-line-in-string-literal position))\n (?\\\\ (let ((ch1 (get-ch)))\n (pcase (ch-ichar ch1)\n (?n '(?\\\\ ?n))\n (?\\\\ '(?\\\\ ?\\\\))\n (c (unsupported-escape (ch-line-no ch1)\n (ch-column-no ch1)\n c)))))\n (c c)))\n\n(defun scan-character-literal ()\n \"Scan a character literal, on the assumption that an ASCII\nsingle quote (that is, a Unicode APOSTROPHE) has been seen and\npushed back.\"\n (let* ((toktup (scan-character-literal-without-checking-end))\n (line-no (elt toktup 2))\n (column-no (elt toktup 3))\n (position (list line-no column-no)))\n (check-char-lit-end position)\n toktup))\n\n(defun check-char-lit-end (position)\n (let ((ch (get-ch)))\n (unless (and (integerp (ch-ichar ch))\n (= (ch-ichar ch) ?\\N{APOSTROPHE}))\n (push-back ch)\n (loop-to-char-lit-end position))))\n\n(defun loop-to-char-lit-end (position)\n (cl-loop for ch = (get-ch)\n until (or (eq (ch-ichar ch) 'eoi)\n (= (ch-ichar ch) ?\\N{APOSTROPHE}))\n finally do (if (eq (ch-ichar ch) 'eoi)\n (apply 'unterminated-character-literal\n position)\n (apply 'multicharacter-literal position))))\n\n(defun scan-character-literal-without-checking-end ()\n (let* ((ch (get-ch))\n (_ (cl-assert (= (ch-ichar ch) ?\\N{APOSTROPHE})))\n (line-no (ch-line-no ch))\n (column-no (ch-column-no ch))\n (position (list line-no column-no))\n (ch1 (get-ch)))\n (pcase (ch-ichar ch1)\n ('eoi (apply 'unterminated-character-literal position))\n (?\\\\ (let ((ch2 (get-ch)))\n (pcase (ch-ichar ch2)\n ('eoi (apply 'unterminated-character-literal position))\n (?n `(\"Integer\" ,(format \"%d\" ?\\n) . ,position))\n (?\\\\ `(\"Integer\" ,(format \"%d\" ?\\\\) . ,position))\n (c (unsupported-escape (ch-line-no ch1)\n (ch-column-no ch1)\n c)))))\n (c `(\"Integer\" ,(format \"%d\" c) . ,position)))))\n\n(defun spacep (c)\n (and (integerp c) (or (= c ?\\N{SPACE})\n (and (<= 9 c) (<= c 13)))))\n\n(defun digitp (c)\n (and (integerp c) (<= ?0 c) (<= c ?9)))\n\n(defun lowerp (c)\n ;; Warning: in EBCDIC, this kind of test for \"alphabetic\" is no\n ;; good. The letters are not contiguous.\n (and (integerp c) (<= ?a c) (<= c ?z)))\n\n(defun upperp (c)\n ;; Warning: in EBCDIC, this kind of test for \"alphabetic\" is no\n ;; good. The letters are not contiguous.\n (and (integerp c) (<= ?A c) (<= c ?Z)))\n\n(defun alphap (c)\n (or (lowerp c) (upperp c)))\n\n(defun identifier-start-p (c)\n (and (integerp c) (or (alphap c) (= c ?_))))\n\n(defun identifier-continuation-p (c)\n (and (integerp c) (or (alphap c) (= c ?_) (digitp c))))\n\n(defun all-digits-p (thing)\n (cl-loop for c in thing\n if (not (digitp c)) return nil\n finally return t))\n\n(defun list-to-string (lst)\n \"Convert a list of characters to a string.\"\n (apply 'string lst))\n\n(defun flatten (lst)\n \"Flatten nested lists. (The implementation is recursive and not\nfor very long lists.)\"\n (pcase lst\n ('() '())\n (`(,head . ,tail)\n (if (listp head)\n (append (flatten head) (flatten tail))\n (cons head (flatten tail))))))\n\n(defun unexpected-character (line-no column-no c)\n (error (format \"unexpected character '%c' at %d:%d\"\n c line-no column-no)))\n\n(defun unsupported-escape (line-no column-no c)\n (error (format \"unsupported escape \\\\%c at %d:%d\"\n c line-no column-no)))\n\n(defun illegal-integer-literal (line-no column-no s)\n (error (format \"illegal integer literal \\\"%s\\\" at %d:%d\"\n s line-no column-no)))\n\n(defun unterminated-character-literal (line-no column-no)\n (error (format \"unterminated character literal starting at %d:%d\"\n line-no column-no)))\n\n(defun multicharacter-literal (line-no column-no)\n (error (format\n \"unsupported multicharacter literal starting at %d:%d\"\n line-no column-no)))\n\n(defun end-of-input-in-string-literal (line-no column-no)\n (error (format \"end of input in string literal starting at %d:%d\"\n line-no column-no)))\n\n(defun end-of-line-in-string-literal (line-no column-no)\n (error (format \"end of line in string literal starting at %d:%d\"\n line-no column-no)))\n\n(defun unterminated-comment (line-no column-no)\n (error (format \"unterminated comment starting at %d:%d\"\n line-no column-no)))\n\n(defun main ()\n (setq inp (make-inp t))\n (scan-text t))\n\n(main)\n", "language": "Emacs-Lisp" }, { "code": "#!/bin/env escript\n%%%-------------------------------------------------------------------\n\n-record (inp_t, {inpf, pushback, line_no, column_no}).\n\nmain (Args) ->\n main_program (Args).\n\nmain_program ([]) ->\n scan_from_inpf_to_outf (\"-\", \"-\"),\n halt (0);\nmain_program ([Inpf_filename]) ->\n scan_from_inpf_to_outf (Inpf_filename, \"-\"),\n halt (0);\nmain_program ([Inpf_filename, Outf_filename]) ->\n scan_from_inpf_to_outf (Inpf_filename, Outf_filename),\n halt (0);\nmain_program ([_, _ | _]) ->\n ProgName = escript:script_name (),\n io:put_chars (standard_error, \"Usage: \"),\n io:put_chars (standard_error, ProgName),\n io:put_chars (standard_error, \" [INPUTFILE [OUTPUTFILE]]\\n\"),\n halt (1).\n\nscan_from_inpf_to_outf (\"-\", \"-\") ->\n scan_input (standard_io, standard_io);\nscan_from_inpf_to_outf (Inpf_filename, \"-\") ->\n case file:open (Inpf_filename, [read]) of\n {ok, Inpf} -> scan_input (Inpf, standard_io);\n _ -> open_failure (Inpf_filename, \"input\")\n end;\nscan_from_inpf_to_outf (\"-\", Outf_filename) ->\n case file:open (Outf_filename, [write]) of\n {ok, Outf} -> scan_input (standard_io, Outf);\n _ -> open_failure (Outf_filename, \"output\")\n end;\nscan_from_inpf_to_outf (Inpf_filename, Outf_filename) ->\n case file:open(Inpf_filename, [read]) of\n {ok, Inpf} ->\n case file:open (Outf_filename, [write]) of\n {ok, Outf} -> scan_input (Inpf, Outf);\n _ -> open_failure (Outf_filename, \"output\")\n end;\n _ -> open_failure (Inpf_filename, \"input\")\n end.\n\nopen_failure (Filename, ForWhat) ->\n ProgName = escript:script_name (),\n io:put_chars (standard_error, ProgName),\n io:put_chars (standard_error, \": failed to open \\\"\"),\n io:put_chars (standard_error, Filename),\n io:put_chars (standard_error, \"\\\" for \"),\n io:put_chars (standard_error, ForWhat),\n io:put_chars (standard_error, \"\\n\"),\n halt (1).\n\nscan_input (Inpf, Outf) ->\n scan_text (Outf, make_inp (Inpf)).\n\nscan_text (Outf, Inp) ->\n {TokTup, Inp1} = get_next_token (Inp),\n print_token (Outf, TokTup),\n case TokTup of\n {\"End_of_input\", _, _, _} -> ok;\n _ -> scan_text (Outf, Inp1)\n end.\n\nprint_token (Outf, {Tok, Arg, Line_no, Column_no}) ->\n S_line_no = erlang:integer_to_list (Line_no),\n S_column_no = erlang:integer_to_list (Column_no),\n io:put_chars (Outf, string:pad (S_line_no, 5, leading)),\n io:put_chars (Outf, \" \"),\n io:put_chars (Outf, string:pad (S_column_no, 5, leading)),\n io:put_chars (Outf, \" \"),\n io:put_chars (Outf, Tok),\n {Padding, Arg1} =\n case Tok of\n \"Identifier\" -> {\" \", Arg};\n \"Integer\" -> {\" \", Arg};\n \"String\" -> {\" \", Arg};\n _ -> {\"\", \"\"}\n end,\n io:put_chars (Outf, Padding),\n io:put_chars (Outf, Arg1),\n io:put_chars (\"\\n\").\n\n%%%-------------------------------------------------------------------\n%%%\n%%% The token dispatcher.\n%%%\n\nget_next_token (Inp) ->\n Inp00 = skip_spaces_and_comments (Inp),\n {Ch, Inp0} = get_ch (Inp00),\n {Char, Line_no, Column_no} = Ch,\n Ln = Line_no,\n Cn = Column_no,\n case Char of\n eof -> {{\"End_of_input\", \"\", Ln, Cn}, Inp0};\n \",\" -> {{\"Comma\", \",\", Ln, Cn}, Inp0};\n \";\" -> {{\"Semicolon\", \";\", Ln, Cn}, Inp0};\n \"(\" -> {{\"LeftParen\", \"(\", Ln, Cn}, Inp0};\n \")\" -> {{\"RightParen\", \")\", Ln, Cn}, Inp0};\n \"{\" -> {{\"LeftBrace\", \"{\", Ln, Cn}, Inp0};\n \"}\" -> {{\"RightBrace\", \"}\", Ln, Cn}, Inp0};\n \"*\" -> {{\"Op_multiply\", \"*\", Ln, Cn}, Inp0};\n \"/\" -> {{\"Op_divide\", \"/\", Ln, Cn}, Inp0};\n \"%\" -> {{\"Op_mod\", \"%\", Ln, Cn}, Inp0};\n \"+\" -> {{\"Op_add\", \"+\", Ln, Cn}, Inp0};\n \"-\" -> {{\"Op_subtract\", \"-\", Ln, Cn}, Inp0};\n \"<\" ->\n {Ch1, Inp1} = get_ch (Inp0),\n {Char1, _, _} = Ch1,\n case Char1 of\n \"=\" -> {{\"Op_lessequal\", \"<=\", Ln, Cn}, Inp1};\n _ -> {{\"Op_less\", \"<\", Ln, Cn}, push_back (Ch1, Inp1)}\n end;\n \">\" ->\n {Ch1, Inp1} = get_ch (Inp0),\n {Char1, _, _} = Ch1,\n case Char1 of\n \"=\" -> {{\"Op_greaterequal\", \">=\", Ln, Cn}, Inp1};\n _ -> {{\"Op_greater\", \">\", Ln, Cn}, push_back (Ch1, Inp1)}\n end;\n \"=\" ->\n {Ch1, Inp1} = get_ch (Inp0),\n {Char1, _, _} = Ch1,\n case Char1 of\n \"=\" -> {{\"Op_equal\", \"==\", Ln, Cn}, Inp1};\n _ -> {{\"Op_assign\", \"=\", Ln, Cn}, push_back (Ch1, Inp1)}\n end;\n \"!\" ->\n {Ch1, Inp1} = get_ch (Inp0),\n {Char1, _, _} = Ch1,\n case Char1 of\n \"=\" -> {{\"Op_notequal\", \"!=\", Ln, Cn}, Inp1};\n _ -> {{\"Op_not\", \"!\", Ln, Cn}, push_back (Ch1, Inp1)}\n end;\n \"&\" ->\n {Ch1, Inp1} = get_ch (Inp0),\n {Char1, _, _} = Ch1,\n case Char1 of\n \"&\" -> {{\"Op_and\", \"&&\", Ln, Cn}, Inp1};\n _ -> unexpected_character (Ln, Cn, Char)\n end;\n \"|\" ->\n {Ch1, Inp1} = get_ch (Inp0),\n {Char1, _, _} = Ch1,\n case Char1 of\n \"|\" -> {{\"Op_or\", \"||\", Ln, Cn}, Inp1};\n _ -> unexpected_character (Ln, Cn, Char)\n end;\n \"\\\"\" ->\n Inp1 = push_back (Ch, Inp0),\n scan_string_literal (Inp1);\n \"'\" ->\n Inp1 = push_back (Ch, Inp0),\n scan_character_literal (Inp1);\n _ ->\n case is_digit (Char) of\n true ->\n Inp1 = push_back (Ch, Inp0),\n scan_integer_literal (Inp1);\n false ->\n case is_alpha_or_underscore (Char) of\n true ->\n Inp1 = push_back (Ch, Inp0),\n scan_identifier_or_reserved_word (Inp1);\n false ->\n unexpected_character (Ln, Cn, Char)\n end\n end\n end.\n\n%%%-------------------------------------------------------------------\n%%%\n%%% Skipping past spaces and /* ... */ comments.\n%%%\n%%% Comments are treated exactly like a bit of whitespace. They never\n%%% make it to the dispatcher.\n%%%\n\nskip_spaces_and_comments (Inp) ->\n {Ch, Inp0} = get_ch (Inp),\n {Char, Line_no, Column_no} = Ch,\n case classify_char (Char) of\n eof -> push_back (Ch, Inp0);\n space -> skip_spaces_and_comments (Inp0);\n slash ->\n {Ch1, Inp1} = get_ch (Inp0),\n case Ch1 of\n {\"*\", _, _} ->\n Inp2 = scan_comment (Inp1, Line_no, Column_no),\n skip_spaces_and_comments (Inp2);\n _ -> push_back (Ch, (push_back (Ch1, Inp1)))\n end;\n other -> push_back (Ch, Inp0)\n end.\n\nclassify_char (Char) ->\n case Char of\n eof -> eof;\n \"/\" -> slash;\n _ -> case is_space (Char) of\n true -> space;\n false -> other\n end\n end.\n\nscan_comment (Inp, Line_no, Column_no) ->\n {Ch0, Inp0} = get_ch (Inp),\n case Ch0 of\n {eof, _, _} -> unterminated_comment (Line_no, Column_no);\n {\"*\", _, _} ->\n {Ch1, Inp1} = get_ch (Inp0),\n case Ch1 of\n {eof, _, _} ->\n unterminated_comment (Line_no, Column_no);\n {\"/\", _, _} -> Inp1;\n _ -> scan_comment (Inp1, Line_no, Column_no)\n end;\n _ -> scan_comment (Inp0, Line_no, Column_no)\n end.\n\nis_space (S) ->\n case re:run (S, \"^[[:space:]]+$\") of\n {match, _} -> true;\n _ -> false\n end.\n\n%%%-------------------------------------------------------------------\n%%%\n%%% Scanning of integer literals, identifiers, and reserved words.\n%%%\n%%% These three types of token are very similar to each other.\n%%%\n\nscan_integer_literal (Inp) ->\n %% Scan an entire word, not just digits. This way we detect\n %% erroneous text such as \"23skidoo\".\n {Line_no, Column_no, Inp1} = get_position (Inp),\n {Word, Inp2} = scan_word (Inp1),\n case is_digit (Word) of\n true -> {{\"Integer\", Word, Line_no, Column_no}, Inp2};\n false -> invalid_integer_literal (Line_no, Column_no, Word)\n end.\n\nscan_identifier_or_reserved_word (Inp) ->\n %% It is assumed that the first character is of the correct type,\n %% thanks to the dispatcher.\n {Line_no, Column_no, Inp1} = get_position (Inp),\n {Word, Inp2} = scan_word (Inp1),\n Tok =\n case Word of\n \"if\" -> \"Keyword_if\";\n \"else\" -> \"Keyword_else\";\n \"while\" -> \"Keyword_while\";\n \"print\" -> \"Keyword_print\";\n \"putc\" -> \"Keyword_putc\";\n _ -> \"Identifier\"\n end,\n {{Tok, Word, Line_no, Column_no}, Inp2}.\n\nscan_word (Inp) ->\n scan_word_loop (Inp, \"\").\n\nscan_word_loop (Inp, Word0) ->\n {Ch1, Inp1} = get_ch (Inp),\n {Char1, _, _} = Ch1,\n case is_alnum_or_underscore (Char1) of\n true -> scan_word_loop (Inp1, Word0 ++ Char1);\n false -> {Word0, push_back (Ch1, Inp1)}\n end.\n\nget_position (Inp) ->\n {Ch1, Inp1} = get_ch (Inp),\n {_, Line_no, Column_no} = Ch1,\n Inp2 = push_back (Ch1, Inp1),\n {Line_no, Column_no, Inp2}.\n\nis_digit (S) ->\n case re:run (S, \"^[[:digit:]]+$\") of\n {match, _} -> true;\n _ -> false\n end.\n\nis_alpha_or_underscore (S) ->\n case re:run (S, \"^[[:alpha:]_]+$\") of\n {match, _} -> true;\n _ -> false\n end.\n\nis_alnum_or_underscore (S) ->\n case re:run (S, \"^[[:alnum:]_]+$\") of\n {match, _} -> true;\n _ -> false\n end.\n\n%%%-------------------------------------------------------------------\n%%%\n%%% Scanning of string literals.\n%%%\n%%% It is assumed that the first character is the opening quote, and\n%%% that the closing quote is the same character.\n%%%\n\n\nscan_string_literal (Inp) ->\n {Ch1, Inp1} = get_ch (Inp),\n {Quote_mark, Line_no, Column_no} = Ch1,\n {Contents, Inp2} = scan_str_lit (Inp1, Ch1),\n Toktup = {\"String\", Quote_mark ++ Contents ++ Quote_mark,\n Line_no, Column_no},\n {Toktup, Inp2}.\n\nscan_str_lit (Inp, Ch) -> scan_str_lit_loop (Inp, Ch, \"\").\n\nscan_str_lit_loop (Inp, Ch, Contents) ->\n {Quote_mark, Line_no, Column_no} = Ch,\n {Ch1, Inp1} = get_ch (Inp),\n {Char1, Line_no1, Column_no1} = Ch1,\n case Char1 of\n Quote_mark -> {Contents, Inp1};\n eof -> eoi_in_string_literal (Line_no, Column_no);\n \"\\n\" -> eoln_in_string_literal (Line_no, Column_no);\n \"\\\\\" ->\n {Ch2, Inp2} = get_ch (Inp1),\n {Char2, _, _} = Ch2,\n case Char2 of\n \"n\" ->\n scan_str_lit_loop (Inp2, Ch, Contents ++ \"\\\\n\");\n \"\\\\\" ->\n scan_str_lit_loop (Inp2, Ch, Contents ++ \"\\\\\\\\\");\n _ ->\n unsupported_escape (Line_no1, Column_no1, Char2)\n end;\n _ -> scan_str_lit_loop (Inp1, Ch, Contents ++ Char1)\n end.\n\n%%%-------------------------------------------------------------------\n%%%\n%%% Scanning of character literals.\n%%%\n%%% It is assumed that the first character is the opening quote, and\n%%% that the closing quote is the same character.\n%%%\n%%% The tedious part of scanning a character literal is distinguishing\n%%% between the kinds of lexical error. (One might wish to modify the\n%%% code to detect, as a distinct kind of error, end of line within a\n%%% character literal.)\n%%%\n\nscan_character_literal (Inp) ->\n {Ch, Inp0} = get_ch (Inp),\n {_, Line_no, Column_no} = Ch,\n {Ch1, Inp1} = get_ch (Inp0),\n {Char1, Line_no1, Column_no1} = Ch1,\n {Intval, Inp3} =\n case Char1 of\n eof -> unterminated_character_literal (Line_no, Column_no);\n \"\\\\\" ->\n {Ch2, Inp2} = get_ch (Inp1),\n {Char2, _, _} = Ch2,\n case Char2 of\n eof -> unterminated_character_literal (Line_no,\n Column_no);\n \"n\" -> {char_to_code (\"\\n\"), Inp2};\n \"\\\\\" -> {char_to_code (\"\\\\\"), Inp2};\n _ -> unsupported_escape (Line_no1, Column_no1,\n Char2)\n end;\n _ -> {char_to_code (Char1), Inp1}\n end,\n Inp4 = check_character_literal_end (Inp3, Ch),\n {{\"Integer\", Intval, Line_no, Column_no}, Inp4}.\n\nchar_to_code (Char) ->\n %% Hat tip to https://archive.ph/BxZRS\n lists:flatmap (fun erlang:integer_to_list/1, Char).\n\ncheck_character_literal_end (Inp, Ch) ->\n {Char, _, _} = Ch,\n {{Char1, _, _}, Inp1} = get_ch (Inp),\n case Char1 of\n Char -> Inp1;\n _ -> find_char_lit_end (Inp1, Ch) % Handle a lexical error.\n end.\n\nfind_char_lit_end (Inp, Ch) ->\n %% There is a lexical error. Determine which kind it fits into.\n {Char, Line_no, Column_no} = Ch,\n {{Char1, _, _}, Inp1} = get_ch (Inp),\n case Char1 of\n Char -> multicharacter_literal (Line_no, Column_no);\n eof -> unterminated_character_literal (Line_no, Column_no);\n _ -> find_char_lit_end (Inp1, Ch)\n end.\n\n%%%-------------------------------------------------------------------\n%%%\n%%% Character-at-a-time input, with unrestricted pushback, and with\n%%% line and column numbering.\n%%%\n\nmake_inp (Inpf) ->\n #inp_t{inpf = Inpf,\n pushback = [],\n line_no = 1,\n column_no = 1}.\n\nget_ch (Inp) ->\n #inp_t{inpf = Inpf,\n pushback = Pushback,\n line_no = Line_no,\n column_no = Column_no} = Inp,\n case Pushback of\n [Ch | Tail] ->\n Inp1 = Inp#inp_t{pushback = Tail},\n {Ch, Inp1};\n [] ->\n case io:get_chars (Inpf, \"\", 1) of\n eof ->\n Ch = {eof, Line_no, Column_no},\n {Ch, Inp};\n {error, _} ->\n Ch = {eof, Line_no, Column_no},\n {Ch, Inp};\n Char ->\n case Char of\n \"\\n\" ->\n Ch = {Char, Line_no, Column_no},\n Inp1 = Inp#inp_t{line_no = Line_no + 1,\n column_no = 1},\n {Ch, Inp1};\n _ ->\n Ch = {Char, Line_no, Column_no},\n Inp1 =\n Inp#inp_t{column_no = Column_no + 1},\n {Ch, Inp1}\n end\n end\n end.\n\npush_back (Ch, Inp) ->\n Inp#inp_t{pushback = [Ch | Inp#inp_t.pushback]}.\n\n%%%-------------------------------------------------------------------\n\ninvalid_integer_literal (Line_no, Column_no, Word) ->\n error_abort (\"invalid integer literal \\\"\" ++\n Word ++ \"\\\" at \" ++\n integer_to_list (Line_no) ++ \":\" ++\n integer_to_list (Column_no)).\n\nunsupported_escape (Line_no, Column_no, Char) ->\n error_abort (\"unsupported escape \\\\\" ++\n Char ++ \" at \" ++\n integer_to_list (Line_no) ++ \":\" ++\n integer_to_list (Column_no)).\n\nunexpected_character (Line_no, Column_no, Char) ->\n error_abort (\"unexpected character '\" ++\n Char ++ \"' at \" ++\n integer_to_list (Line_no) ++ \":\" ++\n integer_to_list (Column_no)).\n\neoi_in_string_literal (Line_no, Column_no) ->\n error_abort (\"end of input in string literal starting at \" ++\n integer_to_list (Line_no) ++ \":\" ++\n integer_to_list (Column_no)).\n\neoln_in_string_literal (Line_no, Column_no) ->\n error_abort (\"end of line in string literal starting at \" ++\n integer_to_list (Line_no) ++ \":\" ++\n integer_to_list (Column_no)).\n\nunterminated_character_literal (Line_no, Column_no) ->\n error_abort (\"unterminated character literal starting at \" ++\n integer_to_list (Line_no) ++ \":\" ++\n integer_to_list (Column_no)).\n\nmulticharacter_literal (Line_no, Column_no) ->\n error_abort (\"unsupported multicharacter literal starting at \" ++\n integer_to_list (Line_no) ++ \":\" ++\n integer_to_list (Column_no)).\n\nunterminated_comment (Line_no, Column_no) ->\n error_abort (\"unterminated comment starting at \" ++\n integer_to_list (Line_no) ++ \":\" ++\n integer_to_list (Column_no)).\n\nerror_abort (Message) ->\n ProgName = escript:script_name (),\n io:put_chars (standard_error, ProgName),\n io:put_chars (standard_error, \": \"),\n io:put_chars (standard_error, Message),\n io:put_chars (standard_error, \"\\n\"),\n halt (1).\n\n%%%-------------------------------------------------------------------\n%%% Instructions to GNU Emacs --\n%%% local variables:\n%%% mode: erlang\n%%% erlang-indent-level: 3\n%%% end:\n%%%-------------------------------------------------------------------\n", "language": "Erlang" }, { "code": "include std/io.e\ninclude std/map.e\ninclude std/types.e\ninclude std/convert.e\n\nconstant true = 1, false = 0, EOF = -1\n\nenum tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq,\n tk_Gtr, tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While,\n tk_Print, tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma,\n tk_Ident, tk_Integer, tk_String\n\nconstant all_syms = {\"End_of_input\", \"Op_multiply\", \"Op_divide\", \"Op_mod\", \"Op_add\",\n \"Op_subtract\", \"Op_negate\", \"Op_not\", \"Op_less\", \"Op_lessequal\", \"Op_greater\",\n \"Op_greaterequal\", \"Op_equal\", \"Op_notequal\", \"Op_assign\", \"Op_and\", \"Op_or\",\n \"Keyword_if\", \"Keyword_else\", \"Keyword_while\", \"Keyword_print\", \"Keyword_putc\",\n \"LeftParen\", \"RightParen\", \"LeftBrace\", \"RightBrace\", \"Semicolon\", \"Comma\",\n \"Identifier\", \"Integer\", \"String\"}\n\ninteger input_file, the_ch = ' ', the_col = 0, the_line = 1\nsequence symbols\nmap key_words = new()\n\nprocedure error(sequence format, sequence data)\n printf(STDOUT, format, data)\n abort(1)\nend procedure\n\n-- get the next character from the input\nfunction next_ch()\n the_ch = getc(input_file)\n the_col += 1\n if the_ch = '\\n' then\n the_line += 1\n the_col = 0\n end if\n return the_ch\nend function\n\n-- 'x' - character constants\nfunction char_lit(integer err_line, integer err_col)\n integer n = next_ch() -- skip opening quote\n if the_ch = '\\'' then\n error(\"%d %d empty character constant\", {err_line, err_col})\n elsif the_ch = '\\\\' then\n next_ch()\n if the_ch = 'n' then\n n = 10\n elsif the_ch = '\\\\' then\n n = '\\\\'\n else\n error(\"%d %d unknown escape sequence \\\\%c\", {err_line, err_col, the_ch})\n end if\n end if\n if next_ch() != '\\'' then\n error(\"%d %d multi-character constant\", {err_line, err_col})\n end if\n next_ch()\n return {tk_Integer, err_line, err_col, n}\nend function\n\n-- process divide or comments\nfunction div_or_cmt(integer err_line, integer err_col)\n if next_ch() != '*' then\n return {tk_Div, err_line, err_col}\n end if\n\n -- comment found\n next_ch()\n while true do\n if the_ch = '*' then\n if next_ch() = '/' then\n next_ch()\n return get_tok()\n end if\n elsif the_ch = EOF then\n error(\"%d %d EOF in comment\", {err_line, err_col})\n else\n next_ch()\n end if\n end while\nend function\n\n-- \"string\"\nfunction string_lit(integer start, integer err_line, integer err_col)\n string text = \"\"\n\n while next_ch() != start do\n if the_ch = EOF then\n error(\"%d %d EOF while scanning string literal\", {err_line, err_col})\n end if\n if the_ch = '\\n' then\n error(\"%d %d EOL while scanning string literal\", {err_line, err_col})\n end if\n text &= the_ch\n end while\n\n next_ch()\n return {tk_String, err_line, err_col, text}\nend function\n\n-- handle identifiers and integers\nfunction ident_or_int(integer err_line, integer err_col)\n integer n, is_number = true\n string text = \"\"\n\n while t_alnum(the_ch) or the_ch = '_' do\n text &= the_ch\n if not t_digit(the_ch) then\n is_number = false\n end if\n next_ch()\n end while\n\n if length(text) = 0 then\n error(\"%d %d ident_or_int: unrecognized character: (%d) '%s'\", {err_line, err_col, the_ch, the_ch})\n end if\n\n if t_digit(text[1]) then\n if not is_number then\n error(\"%d %d invalid number: %s\", {err_line, err_col, text})\n end if\n n = to_integer(text)\n return {tk_Integer, err_line, err_col, n}\n end if\n\n if has(key_words, text) then\n return {get(key_words, text), err_line, err_col}\n end if\n\n return {tk_Ident, err_line, err_col, text}\nend function\n\n-- look ahead for '>=', etc.\nfunction follow(integer expect, integer ifyes, integer ifno, integer err_line, integer err_col)\n if next_ch() = expect then\n next_ch()\n return {ifyes, err_line, err_col}\n end if\n\n if ifno = tk_EOI then\n error(\"%d %d follow: unrecognized character: (%d)\", {err_line, err_col, the_ch})\n end if\n\n return {ifno, err_line, err_col}\nend function\n\n-- return the next token type\nfunction get_tok()\n while t_space(the_ch) do\n next_ch()\n end while\n\n integer err_line = the_line\n integer err_col = the_col\n\n switch the_ch do\n case EOF then return {tk_EOI, err_line, err_col}\n case '/' then return div_or_cmt(err_line, err_col)\n case '\\'' then return char_lit(err_line, err_col)\n\n case '<' then return follow('=', tk_Leq, tk_Lss, err_line, err_col)\n case '>' then return follow('=', tk_Geq, tk_Gtr, err_line, err_col)\n case '=' then return follow('=', tk_Eq, tk_Assign, err_line, err_col)\n case '!' then return follow('=', tk_Neq, tk_Not, err_line, err_col)\n case '&' then return follow('&', tk_And, tk_EOI, err_line, err_col)\n case '|' then return follow('|', tk_Or, tk_EOI, err_line, err_col)\n\n case '\"' then return string_lit(the_ch, err_line, err_col)\n case else\n integer sym = symbols[the_ch]\n if sym != tk_EOI then\n next_ch()\n return {sym, err_line, err_col}\n end if\n return ident_or_int(err_line, err_col)\n end switch\nend function\n\nprocedure init()\n put(key_words, \"else\", tk_Else)\n put(key_words, \"if\", tk_If)\n put(key_words, \"print\", tk_Print)\n put(key_words, \"putc\", tk_Putc)\n put(key_words, \"while\", tk_While)\n\n symbols = repeat(tk_EOI, 256)\n symbols['{'] = tk_Lbrace\n symbols['}'] = tk_Rbrace\n symbols['('] = tk_Lparen\n symbols[')'] = tk_Rparen\n symbols['+'] = tk_Add\n symbols['-'] = tk_Sub\n symbols['*'] = tk_Mul\n symbols['%'] = tk_Mod\n symbols[';'] = tk_Semi\n symbols[','] = tk_Comma\nend procedure\n\nprocedure main(sequence cl)\n sequence file_name\n\n input_file = STDIN\n if length(cl) > 2 then\n file_name = cl[3]\n input_file = open(file_name, \"r\")\n if input_file = -1 then\n error(\"Could not open %s\", {file_name})\n end if\n end if\n init()\n sequence t\n loop do\n t = get_tok()\n printf(STDOUT, \"%5d %5d %-8s\", {t[2], t[3], all_syms[t[1]]})\n switch t[1] do\n case tk_Integer then printf(STDOUT, \" %5d\\n\", {t[4]})\n case tk_Ident then printf(STDOUT, \" %s\\n\", {t[4]})\n case tk_String then printf(STDOUT, \" \\\"%s\\\"\\n\", {t[4]})\n case else printf(STDOUT, \"\\n\")\n end switch\n until t[1] = tk_EOI\n end loop\nend procedure\n\nmain(command_line())\n", "language": "Euphoria" }, { "code": "CREATE BUF 0 , \\ single-character look-ahead buffer\nCREATE COLUMN# 0 ,\nCREATE LINE# 1 ,\n\n: NEWLINE? ( c -- t|f) DUP 10 = SWAP 13 = OR ;\n: +IN ( c --)\n 1 SWAP NEWLINE?\n IF 0 COLUMN# ! LINE# ELSE COLUMN# THEN\n +! 0 BUF ! ;\n: PEEK BUF @ 0= IF STDIN KEY-FILE BUF ! THEN BUF @ ;\n: GETC PEEK DUP +IN ;\n: SKIP GETC DROP ;\n: .LOCATION 7 .R 4 .R SPACE ;\n: WHERE COLUMN# @ LINE# @ ;\n: .WHERE WHERE .LOCATION ;\n: .WHERE+ WHERE SWAP 1+ SWAP .LOCATION ;\n\n: EXPECT GETC OVER OVER =\n IF 2DROP\n ELSE CR .\" stdin:\" COLUMN# @ 0 LINE# @ 0\n <# #s #> TYPE .\" :\" <# #s #> TYPE .\" : \"\n .\" unexpected `\" EMIT .\" ', expecting `\" EMIT .\" '\" CR\n BYE\n THEN ;\n: EQ PEEK [CHAR] = = IF SKIP 2SWAP THEN\n .\" Op_\" TYPE CR 2DROP ;\n\nCREATE ESC 4 C, CHAR $ C, CHAR $ C, CHAR \\ C, 0 C,\n: ?ESC? CR .\" Unknown escape sequence `\\\" EMIT .\" '\" CR BYE ;\n: >ESC ESC 4 + C! ESC ;\n: $$\\n 10 ;\n: $$\\\\ [CHAR] \\ ;\n: ESCAPE DUP >ESC FIND IF NIP EXECUTE ELSE DROP ?ESC? THEN ;\n: ?ESCAPE DUP [CHAR] \\ = IF DROP GETC ESCAPE THEN ;\n: ?EOF DUP 4 = IF CR .\" End-of-file in string\" CR BYE THEN ;\n: ?EOL DUP NEWLINE?\n IF CR .\" End-of-line in string\" CR BYE THEN ;\n: STRING PAD\n BEGIN GETC ?EOF ?EOL DUP [CHAR] \" <>\n WHILE OVER C! CHAR+\n REPEAT DROP PAD TUCK - ;\n: \"TYPE\" [CHAR] \" EMIT TYPE [CHAR] \" EMIT ;\n\nCREATE TOKEN 4 C, CHAR $ C, CHAR $ C, 0 C, 0 C,\n: >HEX DUP 9 > IF 7 + THEN [CHAR] 0 + ;\n: HI! $F0 AND 2/ 2/ 2/ 2/ >HEX TOKEN 3 + C! ;\n: LO! $0F AND >HEX TOKEN 4 + C! ;\n: >TOKEN DUP HI! LO! TOKEN ;\n\n: ?EOF DUP 4 = IF CR .\" End-of-file in comment\" CR BYE THEN ;\n: $$2F PEEK [CHAR] * =\n IF SKIP\n BEGIN\n \tGETC ?EOF [CHAR] * =\n \tPEEK [CHAR] / = AND\n UNTIL SKIP\n ELSE .WHERE .\" Op_divide\" CR THEN ;\n: $$22 .WHERE .\" String \" STRING \"TYPE\" CR ;\n: $$27 .WHERE GETC ?ESCAPE .\" Integer \" . [CHAR] ' EXPECT CR ;\n: $$04 .WHERE .\" End_of_input\" CR BYE ;\n: $$2D .WHERE .\" Op_subtract\" CR ;\n: $$2B .WHERE .\" Op_add\" CR ;\n: $$25 .WHERE .\" Op_mod\" CR ;\n: $$2A .WHERE .\" Op_multiply\" CR ;\n: $$7B .WHERE .\" LeftBrace\" CR ;\n: $$7D .WHERE .\" RightBrace\" CR ;\n: $$2C .WHERE .\" Comma\" CR ;\n: $$29 .WHERE .\" RightParen\" CR ;\n: $$28 .WHERE .\" LeftParen\" CR ;\n: $$3B .WHERE .\" Semicolon\" CR ;\n: $$3D .WHERE s\" equal\" s\" assign\" EQ ;\n: $$21 .WHERE s\" notequal\" s\" not\" EQ ;\n: $$3C .WHERE s\" lessequal\" s\" less\" EQ ;\n: $$3E .WHERE s\" greaterequal\" s\" greater\" EQ ;\n: $$26 .WHERE [CHAR] & EXPECT .\" Op_and\" CR ;\n: $$7C .WHERE [CHAR] | EXPECT .\" Op_or\" CR ;\n: $$20 ; \\ space\n\nCREATE KEYWORD 0 C, CHAR $ C, CHAR $ C, 5 CHARS ALLOT\n: >KEYWORD DUP 2 + KEYWORD C!\n KEYWORD 3 + SWAP CMOVE KEYWORD ;\n: FIND-KW DUP 5 <=\n IF 2DUP >KEYWORD FIND\n IF TRUE 2SWAP 2DROP ELSE DROP FALSE THEN\n ELSE FALSE THEN ;\n\n: $$if .\" Keyword_if\" ;\n: $$else .\" Keyword_else\" ;\n: $$while .\" Keyword_while\" ;\n: $$print .\" Keyword_print\" ;\n: $$putc .\" Keyword_putc\" ;\n\n: DIGIT? 48 58 WITHIN ;\n: ALPHA? DUP 95 = SWAP\t\t \\ underscore?\n DUP 97 123 WITHIN SWAP\t \\ lower?\n 65 91 WITHIN OR OR ;\t \\ upper?\n: ALNUM? DUP DIGIT? SWAP ALPHA? OR ;\n: INTEGER 0\n BEGIN PEEK DIGIT?\n WHILE GETC [CHAR] 0 - SWAP 10 * +\n REPEAT ;\n: ?INTEGER? CR .\" Invalid number\" CR BYE ;\n: ?INTEGER PEEK ALPHA? IF ?INTEGER? THEN ;\n: DIGIT .WHERE+ .\" Integer \" INTEGER ?INTEGER . CR ;\n: NAME PAD\n BEGIN PEEK ALNUM?\n\t WHILE GETC OVER C! CHAR+\n\t REPEAT PAD TUCK - ;\n: IDENT .\" Identifier \" TYPE ;\n: ALPHA .WHERE+ NAME FIND-KW\n IF EXECUTE ELSE IDENT THEN CR ;\n: ?CHAR? CR .\" Character '\" EMIT .\" ' not recognized\" CR BYE ;\n: SPACE? DUP BL = SWAP 9 14 WITHIN OR ;\n: SKIP-SPACE BEGIN PEEK SPACE? WHILE SKIP REPEAT ;\n: CONSUME\n SKIP-SPACE\n PEEK DIGIT? IF DIGIT ELSE\n PEEK ALPHA? IF ALPHA ELSE\n PEEK >TOKEN FIND\n IF SKIP EXECUTE ELSE GETC ?CHAR? BYE THEN\n THEN THEN ;\n: TOKENIZE BEGIN CONSUME AGAIN ;\nTOKENIZE\n", "language": "Forth" }, { "code": "!!!\n!!! An implementation of the Rosetta Code lexical analyzer task:\n!!! https://rosettacode.org/wiki/Compiler/lexical_analyzer\n!!!\n!!! The C implementation was used as a reference on behavior, but was\n!!! not adhered to for the implementation.\n!!!\n\nmodule string_buffers\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, intrinsic :: iso_fortran_env, only: int64\n\n implicit none\n private\n\n public :: strbuf_t\n public :: strbuf_t_length_kind\n public :: strbuf_t_character_kind\n\n integer, parameter :: strbuf_t_length_kind = int64\n\n ! String buffers can handle Unicode.\n integer, parameter :: strbuf_t_character_kind = selected_char_kind ('ISO_10646')\n\n ! Private abbreviations.\n integer, parameter :: nk = strbuf_t_length_kind\n integer, parameter :: ck = strbuf_t_character_kind\n\n type :: strbuf_t\n integer(kind = nk), private :: len = 0\n !\n ! ‘chars’ is made public for efficient access to the individual\n ! characters.\n !\n character(1, kind = ck), allocatable, public :: chars(:)\n contains\n procedure, pass, private :: ensure_storage => strbuf_t_ensure_storage\n procedure, pass :: to_unicode => strbuf_t_to_unicode\n procedure, pass :: length => strbuf_t_length\n procedure, pass :: set => strbuf_t_set\n procedure, pass :: append => strbuf_t_append\n generic :: assignment(=) => set\n end type strbuf_t\n\ncontains\n\n function strbuf_t_to_unicode (strbuf) result (s)\n class(strbuf_t), intent(in) :: strbuf\n character(:, kind = ck), allocatable :: s\n\n !\n ! This does not actually ensure that the string is valid Unicode;\n ! any 31-bit ‘character’ is supported.\n !\n\n integer(kind = nk) :: i\n\n allocate (character(len = strbuf%len, kind = ck) :: s)\n do i = 1, strbuf%len\n s(i:i) = strbuf%chars(i)\n end do\n end function strbuf_t_to_unicode\n\n elemental function strbuf_t_length (strbuf) result (n)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk) :: n\n\n n = strbuf%len\n end function strbuf_t_length\n\n elemental function next_power_of_two (x) result (y)\n integer(kind = nk), intent(in) :: x\n integer(kind = nk) :: y\n\n !\n ! It is assumed that no more than 64 bits are used.\n !\n ! The branch-free algorithm is that of\n ! https://archive.is/nKxAc#RoundUpPowerOf2\n !\n ! Fill in bits until one less than the desired power of two is\n ! reached, and then add one.\n !\n\n y = x - 1\n y = ior (y, ishft (y, -1))\n y = ior (y, ishft (y, -2))\n y = ior (y, ishft (y, -4))\n y = ior (y, ishft (y, -8))\n y = ior (y, ishft (y, -16))\n y = ior (y, ishft (y, -32))\n y = y + 1\n end function next_power_of_two\n\n elemental function new_storage_size (length_needed) result (size)\n integer(kind = nk), intent(in) :: length_needed\n integer(kind = nk) :: size\n\n ! Increase storage by orders of magnitude.\n\n if (2_nk**32 < length_needed) then\n size = huge (1_nk)\n else\n size = next_power_of_two (length_needed)\n end if\n end function new_storage_size\n\n subroutine strbuf_t_ensure_storage (strbuf, length_needed)\n class(strbuf_t), intent(inout) :: strbuf\n integer(kind = nk), intent(in) :: length_needed\n\n integer(kind = nk) :: new_size\n type(strbuf_t) :: new_strbuf\n\n if (.not. allocated (strbuf%chars)) then\n ! Initialize a new strbuf%chars array.\n new_size = new_storage_size (length_needed)\n allocate (strbuf%chars(1:new_size))\n else if (ubound (strbuf%chars, 1) < length_needed) then\n ! Allocate a new strbuf%chars array, larger than the current\n ! one, but containing the same characters.\n new_size = new_storage_size (length_needed)\n allocate (new_strbuf%chars(1:new_size))\n new_strbuf%chars(1:strbuf%len) = strbuf%chars(1:strbuf%len)\n call move_alloc (new_strbuf%chars, strbuf%chars)\n end if\n end subroutine strbuf_t_ensure_storage\n\n subroutine strbuf_t_set (dst, src)\n class(strbuf_t), intent(inout) :: dst\n class(*), intent(in) :: src\n\n integer(kind = nk) :: n\n integer(kind = nk) :: i\n\n select type (src)\n type is (character(*, kind = ck))\n n = len (src, kind = nk)\n call dst%ensure_storage(n)\n do i = 1, n\n dst%chars(i) = src(i:i)\n end do\n dst%len = n\n type is (character(*))\n n = len (src, kind = nk)\n call dst%ensure_storage(n)\n do i = 1, n\n dst%chars(i) = src(i:i)\n end do\n dst%len = n\n class is (strbuf_t)\n n = src%len\n call dst%ensure_storage(n)\n dst%chars(1:n) = src%chars(1:n)\n dst%len = n\n class default\n error stop\n end select\n end subroutine strbuf_t_set\n\n subroutine strbuf_t_append (dst, src)\n class(strbuf_t), intent(inout) :: dst\n class(*), intent(in) :: src\n\n integer(kind = nk) :: n_dst, n_src, n\n integer(kind = nk) :: i\n\n select type (src)\n type is (character(*, kind = ck))\n n_dst = dst%len\n n_src = len (src, kind = nk)\n n = n_dst + n_src\n call dst%ensure_storage(n)\n do i = 1, n_src\n dst%chars(n_dst + i) = src(i:i)\n end do\n dst%len = n\n type is (character(*))\n n_dst = dst%len\n n_src = len (src, kind = nk)\n n = n_dst + n_src\n call dst%ensure_storage(n)\n do i = 1, n_src\n dst%chars(n_dst + i) = src(i:i)\n end do\n dst%len = n\n class is (strbuf_t)\n n_dst = dst%len\n n_src = src%len\n n = n_dst + n_src\n call dst%ensure_storage(n)\n dst%chars((n_dst + 1):n) = src%chars(1:n_src)\n dst%len = n\n class default\n error stop\n end select\n end subroutine strbuf_t_append\n\nend module string_buffers\n\nmodule lexical_analysis\n use, intrinsic :: iso_fortran_env, only: input_unit\n use, intrinsic :: iso_fortran_env, only: output_unit\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, intrinsic :: iso_fortran_env, only: int32\n use, non_intrinsic :: string_buffers\n\n implicit none\n private\n\n public :: lexer_input_t\n public :: lexer_output_t\n public :: run_lexer\n\n integer, parameter :: input_file_unit_no = 100\n integer, parameter :: output_file_unit_no = 101\n\n ! Private abbreviations.\n integer, parameter :: nk = strbuf_t_length_kind\n integer, parameter :: ck = strbuf_t_character_kind\n\n ! Integers large enough for a Unicode code point. Unicode code\n ! points (and UCS-4) have never been allowed to go higher than\n ! 7FFFFFFF, and are even further restricted now.\n integer, parameter :: ichar_kind = int32\n\n character(1, kind = ck), parameter :: horizontal_tab_char = char (9, kind = ck)\n character(1, kind = ck), parameter :: linefeed_char = char (10, kind = ck)\n character(1, kind = ck), parameter :: vertical_tab_char = char (11, kind = ck)\n character(1, kind = ck), parameter :: formfeed_char = char (12, kind = ck)\n character(1, kind = ck), parameter :: carriage_return_char = char (13, kind = ck)\n character(1, kind = ck), parameter :: space_char = ck_' '\n\n ! The following is correct for Unix and its relatives.\n character(1, kind = ck), parameter :: newline_char = linefeed_char\n\n character(1, kind = ck), parameter :: backslash_char = char (92, kind = ck)\n\n character(*, kind = ck), parameter :: newline_intstring = ck_'10'\n character(*, kind = ck), parameter :: backslash_intstring = ck_'92'\n\n integer, parameter :: tk_EOI = 0\n integer, parameter :: tk_Mul = 1\n integer, parameter :: tk_Div = 2\n integer, parameter :: tk_Mod = 3\n integer, parameter :: tk_Add = 4\n integer, parameter :: tk_Sub = 5\n integer, parameter :: tk_Negate = 6\n integer, parameter :: tk_Not = 7\n integer, parameter :: tk_Lss = 8\n integer, parameter :: tk_Leq = 9\n integer, parameter :: tk_Gtr = 10\n integer, parameter :: tk_Geq = 11\n integer, parameter :: tk_Eq = 12\n integer, parameter :: tk_Neq = 13\n integer, parameter :: tk_Assign = 14\n integer, parameter :: tk_And = 15\n integer, parameter :: tk_Or = 16\n integer, parameter :: tk_If = 17\n integer, parameter :: tk_Else = 18\n integer, parameter :: tk_While = 19\n integer, parameter :: tk_Print = 20\n integer, parameter :: tk_Putc = 21\n integer, parameter :: tk_Lparen = 22\n integer, parameter :: tk_Rparen = 23\n integer, parameter :: tk_Lbrace = 24\n integer, parameter :: tk_Rbrace = 25\n integer, parameter :: tk_Semi = 26\n integer, parameter :: tk_Comma = 27\n integer, parameter :: tk_Ident = 28\n integer, parameter :: tk_Integer = 29\n integer, parameter :: tk_String = 30\n\n character(len = 16), parameter :: token_names(0:30) = &\n & (/ \"End_of_input \", \"Op_multiply \", \"Op_divide \", \"Op_mod \", \"Op_add \", &\n & \"Op_subtract \", \"Op_negate \", \"Op_not \", \"Op_less \", \"Op_lessequal \", &\n & \"Op_greater \", \"Op_greaterequal \", \"Op_equal \", \"Op_notequal \", \"Op_assign \", &\n & \"Op_and \", \"Op_or \", \"Keyword_if \", \"Keyword_else \", \"Keyword_while \", &\n & \"Keyword_print \", \"Keyword_putc \", \"LeftParen \", \"RightParen \", \"LeftBrace \", &\n & \"RightBrace \", \"Semicolon \", \"Comma \", \"Identifier \", \"Integer \", &\n & \"String \" /)\n\n type :: token_t\n integer :: token_no\n\n ! Our implementation stores the value of a tk_Integer as a\n ! string. The C reference implementation stores it as an int.\n character(:, kind = ck), allocatable :: val\n\n integer(nk) :: line_no\n integer(nk) :: column_no\n end type token_t\n\n type :: lexer_input_t\n logical, private :: using_input_unit = .true.\n integer, private :: unit_no = -(huge (1))\n integer(kind = nk) :: line_no = 1\n integer(kind = nk) :: column_no = 0\n integer, private :: unget_count = 0\n\n ! The maximum lookahead is 2, although I believe we are using\n ! only 1. In principle, the lookahead could be any finite number.\n character(1, kind = ck), private :: unget_buffer(1:2)\n logical, private :: unget_eof_buffer(1:2)\n\n ! Using the same strbuf_t multiple times reduces the need for\n ! reallocations. Putting that strbuf_t in the lexer_input_t is\n ! simply for convenience.\n type(strbuf_t), private :: strbuf\n\n contains\n !\n ! Note: There is currently no facility for closing one input and\n ! switching to another.\n !\n ! Note: There is currently no facility to decode inputs into\n ! Unicode codepoints. Instead, what happens is raw bytes of\n ! input get stored as strbuf_t_character_kind values. This\n ! behavior is adequate for ASCII inputs.\n !\n procedure, pass :: use_file => lexer_input_t_use_file\n procedure, pass :: get_next_ch => lexer_input_t_get_next_ch\n procedure, pass :: unget_ch => lexer_input_t_unget_ch\n procedure, pass :: unget_eof => lexer_input_t_unget_eof\n end type lexer_input_t\n\n type :: lexer_output_t\n integer, private :: unit_no = output_unit\n contains\n procedure, pass :: use_file => lexer_output_t_use_file\n procedure, pass :: output_token => lexer_output_t_output_token\n end type lexer_output_t\n\ncontains\n\n subroutine lexer_input_t_use_file (inputter, filename)\n class(lexer_input_t), intent(inout) :: inputter\n character(*), intent(in) :: filename\n\n integer :: stat\n\n inputter%using_input_unit = .false.\n inputter%unit_no = input_file_unit_no\n inputter%line_no = 1\n inputter%column_no = 0\n\n open (unit = input_file_unit_no, file = filename, status = 'old', &\n & action = 'read', access = 'stream', form = 'unformatted', &\n & iostat = stat)\n if (stat /= 0) then\n write (error_unit, '(\"Error: failed to open \", A, \" for input\")') filename\n stop 1\n end if\n end subroutine lexer_input_t_use_file\n\n!!!\n!!! If you tell gfortran you want -std=f2008 or -std=f2018, you likely\n!!! will need to add also -fall-intrinsics or -U__GFORTRAN__\n!!!\n!!! The first way, you get the FGETC intrinsic. The latter way, you\n!!! get the C interface code that uses getchar(3).\n!!!\n#ifdef __GFORTRAN__\n\n subroutine get_input_unit_char (c, stat)\n !\n ! The following works if you are using gfortran.\n !\n ! (FGETC is considered a feature for backwards compatibility with\n ! g77. However, I know of no way to reconfigure input_unit as a\n ! Fortran 2003 stream, for use with ordinary ‘read’.)\n !\n character, intent(inout) :: c\n integer, intent(out) :: stat\n\n call fgetc (input_unit, c, stat)\n end subroutine get_input_unit_char\n\n#else\n\n subroutine get_input_unit_char (c, stat)\n !\n ! An alternative implementation of get_input_unit_char. This\n ! actually reads input from the C standard input, which might not\n ! be the same as input_unit.\n !\n use, intrinsic :: iso_c_binding, only: c_int\n character, intent(inout) :: c\n integer, intent(out) :: stat\n\n interface\n !\n ! Use getchar(3) to read characters from standard input. This\n ! assumes there is actually such a function available, and that\n ! getchar(3) does not exist solely as a macro. (One could write\n ! one’s own getchar() if necessary, of course.)\n !\n function getchar () result (c) bind (c, name = 'getchar')\n use, intrinsic :: iso_c_binding, only: c_int\n integer(kind = c_int) :: c\n end function getchar\n end interface\n\n integer(kind = c_int) :: i_char\n\n i_char = getchar ()\n !\n ! The C standard requires that EOF have a negative value. If the\n ! value returned by getchar(3) is not EOF, then it will be\n ! representable as an unsigned char. Therefore, to check for end\n ! of file, one need only test whether i_char is negative.\n !\n if (i_char < 0) then\n stat = -1\n else\n stat = 0\n c = char (i_char)\n end if\n end subroutine get_input_unit_char\n\n#endif\n\n subroutine lexer_input_t_get_next_ch (inputter, eof, ch)\n class(lexer_input_t), intent(inout) :: inputter\n logical, intent(out) :: eof\n character(1, kind = ck), intent(inout) :: ch\n\n integer :: stat\n character(1) :: c = '*'\n\n if (0 < inputter%unget_count) then\n if (inputter%unget_eof_buffer(inputter%unget_count)) then\n eof = .true.\n else\n eof = .false.\n ch = inputter%unget_buffer(inputter%unget_count)\n end if\n inputter%unget_count = inputter%unget_count - 1\n else\n if (inputter%using_input_unit) then\n call get_input_unit_char (c, stat)\n else\n read (unit = inputter%unit_no, iostat = stat) c\n end if\n\n ch = char (ichar (c, kind = ichar_kind), kind = ck)\n\n if (0 < stat) then\n write (error_unit, '(\"Input error with status code \", I0)') stat\n stop 1\n else if (stat < 0) then\n eof = .true.\n ! The C reference code increases column number on end of file;\n ! therefore, so shall we.\n inputter%column_no = inputter%column_no + 1\n else\n eof = .false.\n if (ch == newline_char) then\n inputter%line_no = inputter%line_no + 1\n inputter%column_no = 0\n else\n inputter%column_no = inputter%column_no + 1\n end if\n end if\n end if\n end subroutine lexer_input_t_get_next_ch\n\n subroutine lexer_input_t_unget_ch (inputter, ch)\n class(lexer_input_t), intent(inout) :: inputter\n character(1, kind = ck), intent(in) :: ch\n\n if (ubound (inputter%unget_buffer, 1) <= inputter%unget_count) then\n write (error_unit, '(\"class(lexer_input_t) unget buffer overflow\")')\n stop 1\n else\n inputter%unget_count = inputter%unget_count + 1\n inputter%unget_buffer(inputter%unget_count) = ch\n inputter%unget_eof_buffer(inputter%unget_count) = .false.\n end if\n end subroutine lexer_input_t_unget_ch\n\n subroutine lexer_input_t_unget_eof (inputter)\n class(lexer_input_t), intent(inout) :: inputter\n\n if (ubound (inputter%unget_buffer, 1) <= inputter%unget_count) then\n write (error_unit, '(\"class(lexer_input_t) unget buffer overflow\")')\n stop 1\n else\n inputter%unget_count = inputter%unget_count + 1\n inputter%unget_buffer(inputter%unget_count) = ck_'*'\n inputter%unget_eof_buffer(inputter%unget_count) = .true.\n end if\n end subroutine lexer_input_t_unget_eof\n\n subroutine lexer_output_t_use_file (outputter, filename)\n class(lexer_output_t), intent(inout) :: outputter\n character(*), intent(in) :: filename\n\n integer :: stat\n\n outputter%unit_no = output_file_unit_no\n open (unit = output_file_unit_no, file = filename, action = 'write', iostat = stat)\n if (stat /= 0) then\n write (error_unit, '(\"Error: failed to open \", A, \" for output\")') filename\n stop 1\n end if\n end subroutine lexer_output_t_use_file\n\n subroutine lexer_output_t_output_token (outputter, token)\n class(lexer_output_t), intent(inout) :: outputter\n class(token_t), intent(in) :: token\n\n select case (token%token_no)\n case (tk_Integer, tk_Ident, tk_String)\n write (outputter%unit_no, '(1X, I20, 1X, I20, 1X, A, 1X, A)') &\n & token%line_no, token%column_no, &\n & token_names(token%token_no), token%val\n case default\n write (outputter%unit_no, '(1X, I20, 1X, I20, 1X, A)') &\n & token%line_no, token%column_no, &\n & trim (token_names(token%token_no))\n end select\n end subroutine lexer_output_t_output_token\n\n subroutine run_lexer (inputter, outputter)\n class(lexer_input_t), intent(inout) :: inputter\n class(lexer_output_t), intent(inout) :: outputter\n\n type(token_t) :: token\n\n token = get_token (inputter)\n do while (token%token_no /= tk_EOI)\n call outputter%output_token (token)\n token = get_token (inputter)\n end do\n call outputter%output_token (token)\n end subroutine run_lexer\n\n function get_token (inputter) result (token)\n class(lexer_input_t), intent(inout) :: inputter\n type(token_t) :: token\n\n logical :: eof\n character(1, kind = ck) :: ch\n\n call skip_spaces_and_comments (inputter, eof, ch, &\n & token%line_no, token%column_no)\n\n if (eof) then\n token%token_no = tk_EOI\n else\n select case (ch)\n case (ck_'{')\n token%token_no = tk_Lbrace\n case (ck_'}')\n token%token_no = tk_Rbrace\n case (ck_'(')\n token%token_no = tk_Lparen\n case (ck_')')\n token%token_no = tk_Rparen\n case (ck_'+')\n token%token_no = tk_Add\n case (ck_'-')\n token%token_no = tk_Sub\n case (ck_'*')\n token%token_no = tk_Mul\n case (ck_'%')\n token%token_no = tk_Mod\n case (ck_';')\n token%token_no = tk_Semi\n case (ck_',')\n token%token_no = tk_Comma\n case (ck_'/')\n token%token_no = tk_Div\n\n case (ck_\"'\")\n call read_character_literal\n\n case (ck_'<')\n call distinguish_operators (ch, ck_'=', tk_Leq, tk_Lss)\n case (ck_'>')\n call distinguish_operators (ch, ck_'=', tk_Geq, tk_Gtr)\n case (ck_'=')\n call distinguish_operators (ch, ck_'=', tk_Eq, tk_Assign)\n case (ck_'!')\n call distinguish_operators (ch, ck_'=', tk_Neq, tk_Not)\n case (ck_'&')\n call distinguish_operators (ch, ck_'&', tk_And, tk_EOI)\n case (ck_'|')\n call distinguish_operators (ch, ck_'|', tk_Or, tk_EOI)\n\n case (ck_'\"')\n call read_string_literal (ch, ch)\n\n case default\n if (isdigit (ch)) then\n call read_numeric_literal (ch)\n else if (isalpha_or_underscore (ch)) then\n call read_identifier_or_keyword (ch)\n else\n call start_error_message (inputter)\n write (error_unit, '(\"unrecognized character ''\", A, \"''\")') ch\n stop 1\n end if\n end select\n end if\n contains\n\n subroutine read_character_literal\n character(1, kind = ck) :: ch\n logical :: eof\n character(20, kind = ck) :: buffer\n\n token%token_no = tk_Integer\n\n call inputter%get_next_ch (eof, ch)\n if (eof) then\n call start_error_message (inputter)\n write (error_unit, '(\"end of input in character literal\")')\n stop 1\n else if (ch == ck_\"'\") then\n call start_error_message (inputter)\n write (error_unit, '(\"empty character literal\")')\n stop 1\n else if (ch == backslash_char) then\n call inputter%get_next_ch (eof, ch)\n if (eof) then\n call start_error_message (inputter)\n write (error_unit, '(\"end of input in character literal, after backslash\")')\n stop 1\n else if (ch == ck_'n') then\n allocate (token%val, source = newline_intstring)\n else if (ch == backslash_char) then\n allocate (token%val, source = backslash_intstring)\n else\n call start_error_message (inputter)\n write (error_unit, '(\"unknown escape sequence ''\", A, A, \"'' in character literal\")') &\n & backslash_char, ch\n stop 1\n end if\n call read_character_literal_close_quote\n else\n call read_character_literal_close_quote\n write (buffer, '(I0)') ichar (ch, kind = ichar_kind)\n allocate (token%val, source = trim (buffer))\n end if\n end subroutine read_character_literal\n\n subroutine read_character_literal_close_quote\n logical :: eof\n character(1, kind = ck) :: close_quote\n\n call inputter%get_next_ch (eof, close_quote)\n if (eof) then\n call start_error_message (inputter)\n write (error_unit, '(\"end of input in character literal\")')\n stop 1\n else if (close_quote /= ck_\"'\") then\n call start_error_message (inputter)\n write (error_unit, '(\"multi-character literal\")')\n stop 1\n end if\n end subroutine read_character_literal_close_quote\n\n subroutine distinguish_operators (first_ch, second_ch, &\n & token_no_if_second_ch, &\n & token_no_if_no_second_ch)\n character(1, kind = ck), intent(in) :: first_ch\n character(1, kind = ck), intent(in) :: second_ch\n integer, intent(in) :: token_no_if_second_ch\n integer, intent(in) :: token_no_if_no_second_ch\n\n character(1, kind = ck) :: ch\n logical :: eof\n\n call inputter%get_next_ch (eof, ch)\n if (eof) then\n call inputter%unget_eof\n token%token_no = token_no_if_no_second_ch\n else if (ch == second_ch) then\n token%token_no = token_no_if_second_ch\n else if (token_no_if_no_second_ch == tk_EOI) then\n call start_error_message (inputter)\n write (error_unit, '(\"unrecognized character ''\", A, \"''\")') first_ch\n stop 1\n else\n call inputter%unget_ch (ch)\n token%token_no = token_no_if_no_second_ch\n end if\n end subroutine distinguish_operators\n\n subroutine read_string_literal (opening_quote, closing_quote)\n character(1, kind = ck), intent(in) :: opening_quote\n character(1, kind = ck), intent(in) :: closing_quote\n\n character(1, kind = ck) :: ch\n logical :: done\n\n inputter%strbuf = opening_quote\n done = .false.\n do while (.not. done)\n call inputter%get_next_ch (eof, ch)\n if (eof) then\n call start_error_message (inputter)\n write (error_unit, '(\"end of input in string literal\")')\n stop 1\n else if (ch == closing_quote) then\n call inputter%strbuf%append(ch)\n done = .true.\n else if (ch == newline_char) then\n call start_error_message (inputter)\n write (error_unit, '(\"end of line in string literal\")')\n stop 1\n else\n call inputter%strbuf%append(ch)\n end if\n end do\n allocate (token%val, source = inputter%strbuf%to_unicode())\n token%token_no = tk_String\n end subroutine read_string_literal\n\n subroutine read_numeric_literal (first_ch)\n character(1, kind = ck), intent(in) :: first_ch\n\n character(1, kind = ck) :: ch\n\n token%token_no = tk_Integer\n\n inputter%strbuf = first_ch\n call inputter%get_next_ch (eof, ch)\n do while (isdigit (ch))\n call inputter%strbuf%append (ch)\n call inputter%get_next_ch (eof, ch)\n end do\n if (isalpha_or_underscore (ch)) then\n call start_error_message (inputter)\n write (error_unit, '(\"invalid numeric literal \"\"\", A, \"\"\"\")') &\n & inputter%strbuf%to_unicode()\n stop 1\n else\n call inputter%unget_ch (ch)\n allocate (token%val, source = inputter%strbuf%to_unicode())\n end if\n end subroutine read_numeric_literal\n\n subroutine read_identifier_or_keyword (first_ch)\n character(1, kind = ck), intent(in) :: first_ch\n\n character(1, kind = ck) :: ch\n\n inputter%strbuf = first_ch\n call inputter%get_next_ch (eof, ch)\n do while (isalnum_or_underscore (ch))\n call inputter%strbuf%append (ch)\n call inputter%get_next_ch (eof, ch)\n end do\n\n call inputter%unget_ch (ch)\n\n !\n ! The following is a handwritten ‘implicit radix tree’ search\n ! for keywords, first partitioning the set of keywords according\n ! to their lengths.\n !\n ! I did it this way for fun. One could, of course, write a\n ! program to generate code for such a search.\n !\n ! Perfect hashes are another method one could use.\n !\n ! The reference C implementation uses a binary search.\n !\n token%token_no = tk_Ident\n select case (inputter%strbuf%length())\n case (2)\n select case (inputter%strbuf%chars(1))\n case (ck_'i')\n select case (inputter%strbuf%chars(2))\n case (ck_'f')\n token%token_no = tk_If\n case default\n continue\n end select\n case default\n continue\n end select\n case (4)\n select case (inputter%strbuf%chars(1))\n case (ck_'e')\n select case (inputter%strbuf%chars(2))\n case (ck_'l')\n select case (inputter%strbuf%chars(3))\n case (ck_'s')\n select case (inputter%strbuf%chars(4))\n case (ck_'e')\n token%token_no = tk_Else\n case default\n continue\n end select\n case default\n continue\n end select\n case default\n continue\n end select\n case (ck_'p')\n select case (inputter%strbuf%chars(2))\n case (ck_'u')\n select case (inputter%strbuf%chars(3))\n case (ck_'t')\n select case (inputter%strbuf%chars(4))\n case (ck_'c')\n token%token_no = tk_Putc\n case default\n continue\n end select\n case default\n continue\n end select\n case default\n continue\n end select\n case default\n continue\n end select\n case (5)\n select case (inputter%strbuf%chars(1))\n case (ck_'p')\n select case (inputter%strbuf%chars(2))\n case (ck_'r')\n select case (inputter%strbuf%chars(3))\n case (ck_'i')\n select case (inputter%strbuf%chars(4))\n case (ck_'n')\n select case (inputter%strbuf%chars(5))\n case (ck_'t')\n token%token_no = tk_Print\n case default\n continue\n end select\n case default\n continue\n end select\n case default\n continue\n end select\n case default\n continue\n end select\n case (ck_'w')\n select case (inputter%strbuf%chars(2))\n case (ck_'h')\n select case (inputter%strbuf%chars(3))\n case (ck_'i')\n select case (inputter%strbuf%chars(4))\n case (ck_'l')\n select case (inputter%strbuf%chars(5))\n case (ck_'e')\n token%token_no = tk_While\n case default\n continue\n end select\n case default\n continue\n end select\n case default\n continue\n end select\n case default\n continue\n end select\n case default\n continue\n end select\n case default\n continue\n end select\n if (token%token_no == tk_Ident) then\n allocate (token%val, source = inputter%strbuf%to_unicode ())\n end if\n end subroutine read_identifier_or_keyword\n\n end function get_token\n\n subroutine skip_spaces_and_comments (inputter, eof, ch, line_no, column_no)\n !\n ! This procedure skips spaces and comments, and also captures the\n ! line and column numbers at the correct moment to indicate the\n ! start of a token.\n !\n class(lexer_input_t), intent(inout) :: inputter\n logical, intent(out) :: eof\n character(1, kind = ck), intent(inout) :: ch\n integer(kind = nk), intent(out) :: line_no\n integer(kind = nk), intent(out) :: column_no\n\n integer(kind = nk), parameter :: not_done = -(huge (1_nk))\n\n line_no = not_done\n do while (line_no == not_done)\n call inputter%get_next_ch (eof, ch)\n if (eof) then\n line_no = inputter%line_no\n column_no = inputter%column_no\n else if (ch == ck_'/') then\n line_no = inputter%line_no\n column_no = inputter%column_no\n call inputter%get_next_ch (eof, ch)\n if (eof) then\n call inputter%unget_eof\n ch = ck_'/'\n else if (ch /= ck_'*') then\n call inputter%unget_ch (ch)\n ch = ck_'/'\n else\n call read_to_end_of_comment\n line_no = not_done\n end if\n else if (.not. isspace (ch)) then\n line_no = inputter%line_no\n column_no = inputter%column_no\n end if\n end do\n\n contains\n\n subroutine read_to_end_of_comment\n logical :: done\n\n done = .false.\n do while (.not. done)\n call inputter%get_next_ch (eof, ch)\n if (eof) then\n call end_of_input_in_comment\n else if (ch == ck_'*') then\n call inputter%get_next_ch (eof, ch)\n if (eof) then\n call end_of_input_in_comment\n else if (ch == ck_'/') then\n done = .true.\n end if\n end if\n end do\n end subroutine read_to_end_of_comment\n\n subroutine end_of_input_in_comment\n call start_error_message (inputter)\n write (error_unit, '(\"end of input in comment\")')\n stop 1\n end subroutine end_of_input_in_comment\n\n end subroutine skip_spaces_and_comments\n\n subroutine start_error_message (inputter)\n class(lexer_input_t), intent(inout) :: inputter\n\n write (error_unit, '(\"Lexical error at \", I0, \".\", I0, \": \")', advance = 'no') &\n & inputter%line_no, inputter%column_no\n end subroutine start_error_message\n\n elemental function isspace (ch) result (bool)\n character(1, kind = ck), intent(in) :: ch\n logical :: bool\n\n bool = (ch == horizontal_tab_char) .or. &\n & (ch == linefeed_char) .or. &\n & (ch == vertical_tab_char) .or. &\n & (ch == formfeed_char) .or. &\n & (ch == carriage_return_char) .or. &\n & (ch == space_char)\n end function isspace\n\n elemental function isupper (ch) result (bool)\n character(1, kind = ck), intent(in) :: ch\n logical :: bool\n\n integer(kind = ichar_kind), parameter :: uppercase_A = ichar (ck_'A', kind = ichar_kind)\n integer(kind = ichar_kind), parameter :: uppercase_Z = ichar (ck_'Z', kind = ichar_kind)\n\n integer(kind = ichar_kind) :: i_ch\n\n i_ch = ichar (ch, kind = ichar_kind)\n bool = (uppercase_A <= i_ch .and. i_ch <= uppercase_Z)\n end function isupper\n\n elemental function islower (ch) result (bool)\n character(1, kind = ck), intent(in) :: ch\n logical :: bool\n\n integer(kind = ichar_kind), parameter :: lowercase_a = ichar (ck_'a', kind = ichar_kind)\n integer(kind = ichar_kind), parameter :: lowercase_z = ichar (ck_'z', kind = ichar_kind)\n\n integer(kind = ichar_kind) :: i_ch\n\n i_ch = ichar (ch, kind = ichar_kind)\n bool = (lowercase_a <= i_ch .and. i_ch <= lowercase_z)\n end function islower\n\n elemental function isalpha (ch) result (bool)\n character(1, kind = ck), intent(in) :: ch\n logical :: bool\n\n bool = isupper (ch) .or. islower (ch)\n end function isalpha\n\n elemental function isdigit (ch) result (bool)\n character(1, kind = ck), intent(in) :: ch\n logical :: bool\n\n integer(kind = ichar_kind), parameter :: zero = ichar (ck_'0', kind = ichar_kind)\n integer(kind = ichar_kind), parameter :: nine = ichar (ck_'9', kind = ichar_kind)\n\n integer(kind = ichar_kind) :: i_ch\n\n i_ch = ichar (ch, kind = ichar_kind)\n bool = (zero <= i_ch .and. i_ch <= nine)\n end function isdigit\n\n elemental function isalnum (ch) result (bool)\n character(1, kind = ck), intent(in) :: ch\n logical :: bool\n\n bool = isalpha (ch) .or. isdigit (ch)\n end function isalnum\n\n elemental function isalpha_or_underscore (ch) result (bool)\n character(1, kind = ck), intent(in) :: ch\n logical :: bool\n\n bool = isalpha (ch) .or. (ch == ck_'_')\n end function isalpha_or_underscore\n\n elemental function isalnum_or_underscore (ch) result (bool)\n character(1, kind = ck), intent(in) :: ch\n logical :: bool\n\n bool = isalnum (ch) .or. (ch == ck_'_')\n end function isalnum_or_underscore\n\nend module lexical_analysis\n\nprogram lex\n use, intrinsic :: iso_fortran_env, only: output_unit\n use, non_intrinsic :: lexical_analysis\n\n implicit none\n\n integer :: arg_count\n character(200) :: arg\n type(lexer_input_t) :: inputter\n type(lexer_output_t) :: outputter\n\n arg_count = command_argument_count ()\n if (3 <= arg_count) then\n call print_usage\n else if (arg_count == 0) then\n call run_lexer (inputter, outputter)\n else if (arg_count == 1) then\n call get_command_argument (1, arg)\n call inputter%use_file(trim (arg))\n call run_lexer (inputter, outputter)\n else if (arg_count == 2) then\n call get_command_argument (1, arg)\n call inputter%use_file(trim (arg))\n call get_command_argument (2, arg)\n call outputter%use_file(trim (arg))\n call run_lexer (inputter, outputter)\n end if\n\ncontains\n\n subroutine print_usage\n character(200) :: progname\n\n call get_command_argument (0, progname)\n write (output_unit, '(\"Usage: \", A, \" [INPUT_FILE [OUTPUT_FILE]]\")') &\n & trim (progname)\n end subroutine print_usage\n\nend program lex\n", "language": "Fortran" }, { "code": "enum Token_type\n tk_EOI\n tk_Mul\n tk_Div\n tk_Mod\n tk_Add\n tk_Sub\n tk_Negate\n tk_Not\n tk_Lss\n tk_Leq\n tk_Gtr\n tk_Geq\n tk_Eq\n tk_Neq\n tk_Assign\n tk_And\n tk_Or\n tk_If\n tk_Else\n tk_While\n tk_Print\n tk_Putc\n tk_Lparen\n tk_Rparen\n tk_Lbrace\n tk_Rbrace\n tk_Semi\n tk_Comma\n tk_Ident\n tk_Integer\n tk_String\nend enum\n\nconst NewLine = chr(10)\nconst DoubleQuote = chr(34)\nconst BackSlash = chr(92)\n\n' where we store keywords and variables\ntype Symbol\n s_name as string\n tok as Token_type\nend type\n\ndim shared symtab() as Symbol\n\ndim shared cur_line as string\ndim shared cur_ch as string\ndim shared line_num as integer\ndim shared col_num as integer\n\nfunction is_digit(byval ch as string) as long\n is_digit = ch >= \"0\" AndAlso ch <= \"9\"\nend function\n\nfunction is_alnum(byval ch as string) as long\n is_alnum = (ucase(ch) >= \"A\" AndAlso ucase(ch) <= \"Z\") OrElse is_digit(ch)\nend function\n\nsub error_msg(byval eline as integer, byval ecol as integer, byval msg as string)\n print \"(\"; eline; \":\"; ecol; \") \"; msg\n print : print \"Hit any to end program\"\n sleep\n system\nend sub\n\n' add an identifier to the symbol table\nfunction install(byval s_name as string, byval tok as Token_type) as integer\n dim n as integer = ubound(symtab) + 1\n redim preserve symtab(n)\n\n symtab(n).s_name = s_name\n symtab(n).tok = tok\n return n\nend function\n\n' search for an identifier in the symbol table\nfunction lookup(byval s_name as string) as integer\n dim i as integer\n\n for i = lbound(symtab) to ubound(symtab)\n if symtab(i).s_name = s_name then return i\n next\n return -1\nend function\n\nsub next_line() ' read the next line of input from the source file\n cur_line = \"\"\n cur_ch = \"\" ' empty cur_ch means end-of-file\n if eof(1) then exit sub\n line input #1, cur_line\n cur_line = cur_line + NewLine\n line_num += + 1\n col_num = 1\nend sub\n\nsub next_char() ' get the next char\n cur_ch = \"\"\n col_num += 1\n if col_num > len(cur_line) then next_line()\n if col_num <= len(cur_line) then cur_ch = mid(cur_line, col_num, 1)\nend sub\n\nfunction follow(byval err_line as integer, byval err_col as integer, byval expect as string, byval ifyes as Token_type, byval ifno as Token_type) as Token_type\n if cur_ch = expect then\n next_char()\n return ifyes\n end if\n if ifno = tk_eoi then error_msg(err_line, err_col, \"follow unrecognized character: \" + cur_ch)\n return ifno\nend function\n\nsub gettok(byref err_line as integer, byref err_col as integer, byref tok as Token_type, byref v as string)\n ' skip whitespace\n do while (cur_ch = \" \" or cur_ch = chr(9) or cur_ch = NewLine) and (cur_ch <> \"\")\n next_char()\n loop\n\n err_line = line_num\n err_col = col_num\n\n select case cur_ch\n case \"\": tok = tk_eoi: exit sub\n case \"{\": tok = tk_lbrace: next_char(): exit sub\n case \"}\": tok = tk_rbrace: next_char(): exit sub\n case \"(\": tok = tk_lparen: next_char(): exit sub\n case \")\": tok = tk_rparen: next_char(): exit sub\n case \"+\": tok = tk_add: next_char(): exit sub\n case \"-\": tok = tk_sub: next_char(): exit sub\n case \"*\": tok = tk_mul: next_char(): exit sub\n case \"%\": tok = tk_Mod: next_char(): exit sub\n case \";\": tok = tk_semi: next_char(): exit sub\n case \",\": tok = tk_comma: next_char(): exit sub\n case \"/\": ' div or comment\n next_char()\n if cur_ch <> \"*\" then\n tok = tk_div\n exit sub\n end if\n ' skip comments\n next_char()\n do\n if cur_ch = \"*\" then\n next_char()\n if cur_ch = \"/\" then\n next_char()\n gettok(err_line, err_col, tok, v)\n exit sub\n end if\n elseif cur_ch = \"\" then error_msg(err_line, err_col, \"EOF in comment\")\n else\n next_char()\n end if\n loop\n case \"'\": ' single char literals\n next_char()\n v = str(asc(cur_ch))\n if cur_ch = \"'\" then error_msg(err_line, err_col, \"empty character constant\")\n if cur_ch = BackSlash then\n next_char()\n if cur_ch = \"n\" then\n v = \"10\"\n elseif cur_ch = BackSlash then\n v = \"92\"\n else error_msg(err_line, err_col, \"unknown escape sequence: \" + cur_ch)\n end if\n end if\n next_char()\n if cur_ch <> \"'\" then error_msg(err_line, err_col, \"multi-character constant\")\n next_char()\n tok = tk_integer\n exit sub\n case \"<\": next_char(): tok = follow(err_line, err_col, \"=\", tk_Leq, tk_Lss): exit sub\n case \">\": next_char(): tok = follow(err_line, err_col, \"=\", tk_Geq, tk_Gtr): exit sub\n case \"!\": next_char(): tok = follow(err_line, err_col, \"=\", tk_Neq, tk_Not): exit sub\n case \"=\": next_char(): tok = follow(err_line, err_col, \"=\", tk_Eq, tk_Assign): exit sub\n case \"&\": next_char(): tok = follow(err_line, err_col, \"&\", tk_And, tk_EOI): exit sub\n case \"|\": next_char(): tok = follow(err_line, err_col, \"|\", tk_Or, tk_EOI): exit sub\n case DoubleQuote: ' string\n v = cur_ch\n next_char()\n do while cur_ch <> DoubleQuote\n if cur_ch = NewLine then error_msg(err_line, err_col, \"EOL in string\")\n if cur_ch = \"\" then error_msg(err_line, err_col, \"EOF in string\")\n v += cur_ch\n next_char()\n loop\n v += cur_ch\n next_char()\n tok = tk_string\n exit sub\n case else ' integers or identifiers\n dim is_number as boolean = is_digit(cur_ch)\n v = \"\"\n do while is_alnum(cur_ch) orelse cur_ch = \"_\"\n if not is_digit(cur_ch) then is_number = false\n v += cur_ch\n next_char()\n loop\n if len(v) = 0 then error_msg(err_line, err_col, \"unknown character: \" + cur_ch)\n if is_digit(mid(v, 1, 1)) then\n if not is_number then error_msg(err_line, err_col, \"invalid number: \" + v)\n tok = tk_integer\n exit sub\n end if\n dim as integer index = lookup(v)\n if index = -1 then\n tok = tk_ident\n else\n tok = symtab(index).tok\n end if\n exit sub\n end select\nend sub\n\nsub init_lex(byval filein as string)\n install(\"else\", tk_else)\n install(\"if\", tk_if)\n install(\"print\", tk_print)\n install(\"putc\", tk_putc)\n install(\"while\", tk_while)\n\n open filein for input as #1\n\n cur_line = \"\"\n line_num = 0\n col_num = 0\n next_char()\nend sub\n\nsub scanner()\n dim err_line as integer\n dim err_col as integer\n dim tok as Token_type\n dim v as string\n dim tok_list(tk_eoi to tk_string) as string\n\n tok_list(tk_EOI ) = \"End_of_input\"\n tok_list(tk_Mul ) = \"Op_multiply\"\n tok_list(tk_Div ) = \"Op_divide\"\n tok_list(tk_Mod ) = \"Op_mod\"\n tok_list(tk_Add ) = \"Op_add\"\n tok_list(tk_Sub ) = \"Op_subtract\"\n tok_list(tk_Negate ) = \"Op_negate\"\n tok_list(tk_Not ) = \"Op_not\"\n tok_list(tk_Lss ) = \"Op_less\"\n tok_list(tk_Leq ) = \"Op_lessequal\"\n tok_list(tk_Gtr ) = \"Op_greater\"\n tok_list(tk_Geq ) = \"Op_greaterequal\"\n tok_list(tk_Eq ) = \"Op_equal\"\n tok_list(tk_Neq ) = \"Op_notequal\"\n tok_list(tk_Assign ) = \"Op_assign\"\n tok_list(tk_And ) = \"Op_and\"\n tok_list(tk_Or ) = \"Op_or\"\n tok_list(tk_If ) = \"Keyword_if\"\n tok_list(tk_Else ) = \"Keyword_else\"\n tok_list(tk_While ) = \"Keyword_while\"\n tok_list(tk_Print ) = \"Keyword_print\"\n tok_list(tk_Putc ) = \"Keyword_putc\"\n tok_list(tk_Lparen ) = \"LeftParen\"\n tok_list(tk_Rparen ) = \"RightParen\"\n tok_list(tk_Lbrace ) = \"LeftBrace\"\n tok_list(tk_Rbrace ) = \"RightBrace\"\n tok_list(tk_Semi ) = \"Semicolon\"\n tok_list(tk_Comma ) = \"Comma\"\n tok_list(tk_Ident ) = \"Identifier\"\n tok_list(tk_Integer) = \"Integer\"\n tok_list(tk_String ) = \"String\"\n\n do\n gettok(err_line, err_col, tok, v)\n print using \"##### ##### \\ \" + BackSlash; err_line; err_col; tok_list(tok);\n if tok = tk_integer orelse tok = tk_ident orelse tok = tk_string then print \" \" + v;\n print\n loop until tok = tk_eoi\nend sub\n\nsub main()\n if command(1) = \"\" then print \"filename required\" : exit sub\n init_lex(command(1))\n scanner()\nend sub\n\nmain()\nprint : print \"Hit any to end program\"\nsleep\nsystem\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"log\"\n \"os\"\n)\n\ntype TokenType int\n\nconst (\n tkEOI TokenType = iota\n tkMul\n tkDiv\n tkMod\n tkAdd\n tkSub\n tkNegate\n tkNot\n tkLss\n tkLeq\n tkGtr\n tkGeq\n tkEq\n tkNeq\n tkAssign\n tkAnd\n tkOr\n tkIf\n tkElse\n tkWhile\n tkPrint\n tkPutc\n tkLparen\n tkRparen\n tkLbrace\n tkRbrace\n tkSemi\n tkComma\n tkIdent\n tkInteger\n tkString\n)\n\ntype Symbol struct {\n name string\n tok TokenType\n}\n\n// symbol table\nvar symtab []Symbol\n\nvar scanner *bufio.Scanner\n\nvar (\n curLine = \"\"\n curCh byte\n lineNum = 0\n colNum = 0\n)\n\nconst etx byte = 4 // used to signify EOI\n\nfunc isDigit(ch byte) bool {\n return ch >= '0' && ch <= '9'\n}\n\nfunc isAlnum(ch byte) bool {\n return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || isDigit(ch)\n}\n\nfunc errorMsg(eline, ecol int, msg string) {\n log.Fatalf(\"(%d:%d) %s\", eline, ecol, msg)\n}\n\n// add an identifier to the symbol table\nfunc install(name string, tok TokenType) {\n sym := Symbol{name, tok}\n symtab = append(symtab, sym)\n}\n\n// search for an identifier in the symbol table\nfunc lookup(name string) int {\n for i := 0; i < len(symtab); i++ {\n if symtab[i].name == name {\n return i\n }\n }\n return -1\n}\n\n// read the next line of input from the source file\nfunc nextLine() {\n if scanner.Scan() {\n curLine = scanner.Text()\n lineNum++\n colNum = 0\n if curLine == \"\" { // skip blank lines\n nextLine()\n }\n } else {\n err := scanner.Err()\n if err == nil { // EOF\n curCh = etx\n curLine = \"\"\n lineNum++\n colNum = 1\n } else {\n log.Fatal(err)\n }\n }\n}\n\n// get the next char\nfunc nextChar() {\n if colNum >= len(curLine) {\n nextLine()\n }\n if colNum < len(curLine) {\n curCh = curLine[colNum]\n colNum++\n }\n}\n\nfunc follow(eline, ecol int, expect byte, ifyes, ifno TokenType) TokenType {\n if curCh == expect {\n nextChar()\n return ifyes\n }\n if ifno == tkEOI {\n errorMsg(eline, ecol, \"follow unrecognized character: \"+string(curCh))\n }\n return ifno\n}\n\nfunc gettok() (eline, ecol int, tok TokenType, v string) {\n // skip whitespace\n for curCh == ' ' || curCh == '\\t' || curCh == '\\n' {\n nextChar()\n }\n eline = lineNum\n ecol = colNum\n switch curCh {\n case etx:\n tok = tkEOI\n return\n case '{':\n tok = tkLbrace\n nextChar()\n return\n case '}':\n tok = tkRbrace\n nextChar()\n return\n case '(':\n tok = tkLparen\n nextChar()\n return\n case ')':\n tok = tkRparen\n nextChar()\n return\n case '+':\n tok = tkAdd\n nextChar()\n return\n case '-':\n tok = tkSub\n nextChar()\n return\n case '*':\n tok = tkMul\n nextChar()\n return\n case '%':\n tok = tkMod\n nextChar()\n return\n case ';':\n tok = tkSemi\n nextChar()\n return\n case ',':\n tok = tkComma\n nextChar()\n return\n case '/': // div or comment\n nextChar()\n if curCh != '*' {\n tok = tkDiv\n return\n }\n // skip comments\n nextChar()\n for {\n if curCh == '*' {\n nextChar()\n if curCh == '/' {\n nextChar()\n eline, ecol, tok, v = gettok()\n return\n }\n } else if curCh == etx {\n errorMsg(eline, ecol, \"EOF in comment\")\n } else {\n nextChar()\n }\n }\n case '\\'': // single char literals\n nextChar()\n v = fmt.Sprintf(\"%d\", curCh)\n if curCh == '\\'' {\n errorMsg(eline, ecol, \"Empty character constant\")\n }\n if curCh == '\\\\' {\n nextChar()\n if curCh == 'n' {\n v = \"10\"\n } else if curCh == '\\\\' {\n v = \"92\"\n } else {\n errorMsg(eline, ecol, \"unknown escape sequence: \"+string(curCh))\n }\n }\n nextChar()\n if curCh != '\\'' {\n errorMsg(eline, ecol, \"multi-character constant\")\n }\n nextChar()\n tok = tkInteger\n return\n case '<':\n nextChar()\n tok = follow(eline, ecol, '=', tkLeq, tkLss)\n return\n case '>':\n nextChar()\n tok = follow(eline, ecol, '=', tkGeq, tkGtr)\n return\n case '!':\n nextChar()\n tok = follow(eline, ecol, '=', tkNeq, tkNot)\n return\n case '=':\n nextChar()\n tok = follow(eline, ecol, '=', tkEq, tkAssign)\n return\n case '&':\n nextChar()\n tok = follow(eline, ecol, '&', tkAnd, tkEOI)\n return\n case '|':\n nextChar()\n tok = follow(eline, ecol, '|', tkOr, tkEOI)\n return\n case '\"': // string\n v = string(curCh)\n nextChar()\n for curCh != '\"' {\n if curCh == '\\n' {\n errorMsg(eline, ecol, \"EOL in string\")\n }\n if curCh == etx {\n errorMsg(eline, ecol, \"EOF in string\")\n }\n v += string(curCh)\n nextChar()\n }\n v += string(curCh)\n nextChar()\n tok = tkString\n return\n default: // integers or identifiers\n isNumber := isDigit(curCh)\n v = \"\"\n for isAlnum(curCh) || curCh == '_' {\n if !isDigit(curCh) {\n isNumber = false\n }\n v += string(curCh)\n nextChar()\n }\n if len(v) == 0 {\n errorMsg(eline, ecol, \"unknown character: \"+string(curCh))\n }\n if isDigit(v[0]) {\n if !isNumber {\n errorMsg(eline, ecol, \"invalid number: \"+string(curCh))\n }\n tok = tkInteger\n return\n }\n index := lookup(v)\n if index == -1 {\n tok = tkIdent\n } else {\n tok = symtab[index].tok\n }\n return\n }\n}\n\nfunc initLex() {\n install(\"else\", tkElse)\n install(\"if\", tkIf)\n install(\"print\", tkPrint)\n install(\"putc\", tkPutc)\n install(\"while\", tkWhile)\n nextChar()\n}\n\nfunc process() {\n tokMap := make(map[TokenType]string)\n tokMap[tkEOI] = \"End_of_input\"\n tokMap[tkMul] = \"Op_multiply\"\n tokMap[tkDiv] = \"Op_divide\"\n tokMap[tkMod] = \"Op_mod\"\n tokMap[tkAdd] = \"Op_add\"\n tokMap[tkSub] = \"Op_subtract\"\n tokMap[tkNegate] = \"Op_negate\"\n tokMap[tkNot] = \"Op_not\"\n tokMap[tkLss] = \"Op_less\"\n tokMap[tkLeq] = \"Op_lessequal\"\n tokMap[tkGtr] = \"Op_greater\"\n tokMap[tkGeq] = \"Op_greaterequal\"\n tokMap[tkEq] = \"Op_equal\"\n tokMap[tkNeq] = \"Op_notequal\"\n tokMap[tkAssign] = \"Op_assign\"\n tokMap[tkAnd] = \"Op_and\"\n tokMap[tkOr] = \"Op_or\"\n tokMap[tkIf] = \"Keyword_if\"\n tokMap[tkElse] = \"Keyword_else\"\n tokMap[tkWhile] = \"Keyword_while\"\n tokMap[tkPrint] = \"Keyword_print\"\n tokMap[tkPutc] = \"Keyword_putc\"\n tokMap[tkLparen] = \"LeftParen\"\n tokMap[tkRparen] = \"RightParen\"\n tokMap[tkLbrace] = \"LeftBrace\"\n tokMap[tkRbrace] = \"RightBrace\"\n tokMap[tkSemi] = \"Semicolon\"\n tokMap[tkComma] = \"Comma\"\n tokMap[tkIdent] = \"Identifier\"\n tokMap[tkInteger] = \"Integer\"\n tokMap[tkString] = \"String\"\n\n for {\n eline, ecol, tok, v := gettok()\n fmt.Printf(\"%5d %5d %-16s\", eline, ecol, tokMap[tok])\n if tok == tkInteger || tok == tkIdent || tok == tkString {\n fmt.Println(v)\n } else {\n fmt.Println()\n }\n if tok == tkEOI {\n return\n }\n }\n}\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc main() {\n if len(os.Args) < 2 {\n fmt.Println(\"Filename required\")\n return\n }\n f, err := os.Open(os.Args[1])\n check(err)\n defer f.Close()\n scanner = bufio.NewScanner(f)\n initLex()\n process()\n}\n", "language": "Go" }, { "code": "import Control.Applicative hiding (many, some)\nimport Control.Monad.State.Lazy\nimport Control.Monad.Trans.Maybe (MaybeT, runMaybeT)\nimport Data.Char (isAsciiLower, isAsciiUpper, isDigit, ord)\nimport Data.Foldable (asum)\nimport Data.Functor (($>))\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Prelude hiding (lex)\nimport System.Environment (getArgs)\nimport System.IO\nimport Text.Printf\n\n\n-- Tokens --------------------------------------------------------------------------------------------------------------\ndata Val = IntVal Int -- value\n | TextVal String Text -- name value\n | SymbolVal String -- name\n | Skip\n | LexError String -- message\n\ndata Token = Token Val Int Int -- value line column\n\n\ninstance Show Val where\n show (IntVal value) = printf \"%-18s%d\\n\" \"Integer\" value\n show (TextVal \"String\" value) = printf \"%-18s%s\\n\" \"String\" (show $ T.unpack value) -- show escaped characters\n show (TextVal name value) = printf \"%-18s%s\\n\" name (T.unpack value)\n show (SymbolVal name ) = printf \"%s\\n\" name\n show (LexError msg ) = printf \"%-18s%s\\n\" \"Error\" msg\n show Skip = printf \"\"\n\ninstance Show Token where\n show (Token val line column) = printf \"%2d %2d %s\" line column (show val)\n\n\nprintTokens :: [Token] -> String\nprintTokens tokens =\n \"Location Token name Value\\n\" ++\n \"--------------------------------------\\n\" ++\n (concatMap show tokens)\n\n\n-- Tokenizers ----------------------------------------------------------------------------------------------------------\nmakeToken :: Lexer Val -> Lexer Token\nmakeToken lexer = do\n (t, l, c) <- get\n val <- lexer\n\n case val of\n Skip -> nextToken\n\n LexError msg -> do\n (_, l', c') <- get\n\n let code = T.unpack $ T.take (c' - c + 1) t\n let str = printf \"%s\\n%s(%d, %d): %s\" msg (replicate 27 ' ') l' c' code\n\n ch <- peek\n unless (ch == '\\0') $ advance 1\n\n return $ Token (LexError str) l c\n\n _ -> return $ Token val l c\n\n\nsimpleToken :: String -> String -> Lexer Val\nsimpleToken lexeme name = lit lexeme $> SymbolVal name\n\n\nmakeTokenizers :: [(String, String)] -> Lexer Val\nmakeTokenizers = asum . map (uncurry simpleToken)\n\n\nkeywords :: Lexer Val\nkeywords = makeTokenizers\n [(\"if\", \"Keyword_if\"), (\"else\", \"Keyword_else\"), (\"while\", \"Keyword_while\"),\n (\"print\", \"Keyword_print\"), (\"putc\", \"Keyword_putc\")]\n\n\noperators :: Lexer Val\noperators = makeTokenizers\n [(\"*\", \"Op_multiply\"), (\"/\", \"Op_divide\"), (\"%\", \"Op_mod\"), (\"+\", \"Op_add\"),\n (\"-\", \"Op_subtract\"), (\"<=\", \"Op_lessequal\"), (\"<\", \"Op_less\"), (\">=\", \"Op_greaterequal\"),\n (\">\", \"Op_greater\"), (\"==\", \"Op_equal\"), (\"!=\", \"Op_notequal\"), (\"!\", \"Op_not\"),\n (\"=\", \"Op_assign\"), (\"&&\", \"Op_and\"), (\"||\", \"Op_or\")]\n\n\nsymbols :: Lexer Val\nsymbols = makeTokenizers\n [(\"(\", \"LeftParen\"), (\")\", \"RightParen\"),\n (\"{\", \"LeftBrace\"), (\"}\", \"RightBrace\"),\n (\";\", \"Semicolon\"), (\",\", \"Comma\")]\n\n\nisIdStart :: Char -> Bool\nisIdStart ch = isAsciiLower ch || isAsciiUpper ch || ch == '_'\n\nisIdEnd :: Char -> Bool\nisIdEnd ch = isIdStart ch || isDigit ch\n\nidentifier :: Lexer Val\nidentifier = TextVal \"Identifier\" <$> lexeme\n where lexeme = T.cons <$> (one isIdStart) <*> (many isIdEnd)\n\n\ninteger :: Lexer Val\ninteger = do\n lexeme <- some isDigit\n next_ch <- peek\n\n if (isIdStart next_ch) then\n return $ LexError \"Invalid number. Starts like a number, but ends in non-numeric characters.\"\n else do\n let num = read (T.unpack lexeme) :: Int\n return $ IntVal num\n\n\ncharacter :: Lexer Val\ncharacter = do\n lit \"'\"\n str <- lookahead 3\n\n case str of\n (ch : '\\'' : _) -> advance 2 $> IntVal (ord ch)\n \"\\\\n'\" -> advance 3 $> IntVal 10\n \"\\\\\\\\'\" -> advance 3 $> IntVal 92\n ('\\\\' : ch : \"\\'\") -> advance 2 $> LexError (printf \"Unknown escape sequence \\\\%c\" ch)\n ('\\'' : _) -> return $ LexError \"Empty character constant\"\n _ -> advance 2 $> LexError \"Multi-character constant\"\n\n\nstring :: Lexer Val\nstring = do\n lit \"\\\"\"\n\n loop (T.pack \"\") =<< peek\n where loop t ch = case ch of\n '\\\\' -> do\n next_ch <- next\n\n case next_ch of\n 'n' -> loop (T.snoc t '\\n') =<< next\n '\\\\' -> loop (T.snoc t '\\\\') =<< next\n _ -> return $ LexError $ printf \"Unknown escape sequence \\\\%c\" next_ch\n\n '\"' -> next $> TextVal \"String\" t\n\n '\\n' -> return $ LexError $ \"End-of-line while scanning string literal.\" ++\n \" Closing string character not found before end-of-line.\"\n\n '\\0' -> return $ LexError $ \"End-of-file while scanning string literal.\" ++\n \" Closing string character not found.\"\n\n _ -> loop (T.snoc t ch) =<< next\n\n\nskipComment :: Lexer Val\nskipComment = do\n lit \"/*\"\n\n loop =<< peek\n where loop ch = case ch of\n '\\0' -> return $ LexError \"End-of-file in comment. Closing comment characters not found.\"\n\n '*' -> do\n next_ch <- next\n\n case next_ch of\n '/' -> next $> Skip\n _ -> loop next_ch\n\n _ -> loop =<< next\n\n\nnextToken :: Lexer Token\nnextToken = do\n skipWhitespace\n\n makeToken $ skipComment\n <|> keywords\n <|> identifier\n <|> integer\n <|> character\n <|> string\n <|> operators\n <|> symbols\n <|> simpleToken \"\\0\" \"End_of_input\"\n <|> (return $ LexError \"Unrecognized character.\")\n\n\nmain :: IO ()\nmain = do\n args <- getArgs\n (hin, hout) <- getIOHandles args\n\n withHandles hin hout $ printTokens . (lex nextToken)\n\n\n------------------------------------------------------------------------------------------------------------------------\n-- Machinery\n------------------------------------------------------------------------------------------------------------------------\n\n-- File handling -------------------------------------------------------------------------------------------------------\ngetIOHandles :: [String] -> IO (Handle, Handle)\ngetIOHandles [] = return (stdin, stdout)\n\ngetIOHandles [infile] = do\n inhandle <- openFile infile ReadMode\n return (inhandle, stdout)\n\ngetIOHandles (infile : outfile : _) = do\n inhandle <- openFile infile ReadMode\n outhandle <- openFile outfile WriteMode\n return (inhandle, outhandle)\n\n\nwithHandles :: Handle -> Handle -> (String -> String) -> IO ()\nwithHandles in_handle out_handle f = do\n contents <- hGetContents in_handle\n let contents' = contents ++ \"\\0\" -- adding \\0 simplifies treatment of EOF\n\n hPutStr out_handle $ f contents'\n\n unless (in_handle == stdin) $ hClose in_handle\n unless (out_handle == stdout) $ hClose out_handle\n\n\n-- Lexer ---------------------------------------------------------------------------------------------------------------\ntype LexerState = (Text, Int, Int) -- input line column\ntype Lexer = MaybeT (State LexerState)\n\n\nlexerAdvance :: Int -> LexerState -> LexerState\nlexerAdvance 0 ctx = ctx\n\nlexerAdvance 1 (t, l, c)\n | ch == '\\n' = (rest, l + 1, 1 )\n | otherwise = (rest, l, c + 1)\n where\n (ch, rest) = (T.head t, T.tail t)\n\nlexerAdvance n ctx = lexerAdvance (n - 1) $ lexerAdvance 1 ctx\n\n\nadvance :: Int -> Lexer ()\nadvance n = modify $ lexerAdvance n\n\n\npeek :: Lexer Char\npeek = gets $ \\(t, _, _) -> T.head t\n\n\nlookahead :: Int -> Lexer String\nlookahead n = gets $ \\(t, _, _) -> T.unpack $ T.take n t\n\n\nnext :: Lexer Char\nnext = advance 1 >> peek\n\n\nskipWhitespace :: Lexer ()\nskipWhitespace = do\n ch <- peek\n when (ch `elem` \" \\n\") (next >> skipWhitespace)\n\n\nlit :: String -> Lexer ()\nlit lexeme = do\n (t, _, _) <- get\n guard $ T.isPrefixOf (T.pack lexeme) t\n advance $ length lexeme\n\n\none :: (Char -> Bool) -> Lexer Char\none f = do\n ch <- peek\n guard $ f ch\n next\n return ch\n\n\nlexerMany :: (Char -> Bool) -> LexerState -> (Text, LexerState)\nlexerMany f (t, l, c) = (lexeme, (t', l', c'))\n where (lexeme, _) = T.span f t\n (t', l', c') = lexerAdvance (T.length lexeme) (t, l, c)\n\n\nmany :: (Char -> Bool) -> Lexer Text\nmany f = state $ lexerMany f\n\n\nsome :: (Char -> Bool) -> Lexer Text\nsome f = T.cons <$> (one f) <*> (many f)\n\n\nlex :: Lexer a -> String -> [a]\nlex lexer str = loop lexer (T.pack str, 1, 1)\n where loop lexer s\n | T.null txt = [t]\n | otherwise = t : loop lexer s'\n\n where (Just t, s') = runState (runMaybeT lexer) s\n (txt, _, _) = s'\n", "language": "Haskell" }, { "code": "#\n# The Rosetta Code lexical analyzer in Icon with co-expressions. Based\n# upon the ATS implementation.\n#\n# Usage: lex [INPUTFILE [OUTPUTFILE]]\n# If INPUTFILE or OUTPUTFILE is \"-\" or missing, then standard input\n# or standard output is used, respectively. *)\n#\n\n$define EOF -1\n\n$define TOKEN_ELSE 0\n$define TOKEN_IF 1\n$define TOKEN_PRINT 2\n$define TOKEN_PUTC 3\n$define TOKEN_WHILE 4\n$define TOKEN_MULTIPLY 5\n$define TOKEN_DIVIDE 6\n$define TOKEN_MOD 7\n$define TOKEN_ADD 8\n$define TOKEN_SUBTRACT 9\n$define TOKEN_NEGATE 10\n$define TOKEN_LESS 11\n$define TOKEN_LESSEQUAL 12\n$define TOKEN_GREATER 13\n$define TOKEN_GREATEREQUAL 14\n$define TOKEN_EQUAL 15\n$define TOKEN_NOTEQUAL 16\n$define TOKEN_NOT 17\n$define TOKEN_ASSIGN 18\n$define TOKEN_AND 19\n$define TOKEN_OR 20\n$define TOKEN_LEFTPAREN 21\n$define TOKEN_RIGHTPAREN 22\n$define TOKEN_LEFTBRACE 23\n$define TOKEN_RIGHTBRACE 24\n$define TOKEN_SEMICOLON 25\n$define TOKEN_COMMA 26\n$define TOKEN_IDENTIFIER 27\n$define TOKEN_INTEGER 28\n$define TOKEN_STRING 29\n$define TOKEN_END_OF_INPUT 30\n\nglobal whitespace\nglobal ident_start\nglobal ident_continuation\n\nprocedure main(args)\n local inpf, outf\n local pushback_buffer, inp, pushback\n\n initial {\n whitespace := ' \\t\\v\\f\\r\\n'\n ident_start := '_' ++ &letters\n ident_continuation := ident_start ++ &digits\n }\n\n inpf := &input\n outf := &output\n if 1 <= *args & args[1] ~== \"-\" then {\n inpf := open(args[1], \"rt\") |\n stop(\"cannot open \", args[1], \" for input\")\n }\n if 2 <= *args & args[2] ~== \"-\" then {\n outf := open(args[2], \"wt\") |\n stop(\"cannot open \", args[2], \" for output\")\n }\n\n pushback_buffer := []\n inp := create inputter(inpf, pushback_buffer)\n pushback := create repeat push(pushback_buffer, \\@&source)\n @pushback # The first invocation does nothing.\n\n scan_text(outf, inp, pushback)\nend\n\nprocedure scan_text(outf, inp, pushback)\n local ch\n\n while /ch | ch[1] ~=== EOF do {\n skip_spaces_and_comments(inp, pushback)\n ch := @inp\n if ch[1] === EOF then {\n print_token(outf, [TOKEN_END_OF_INPUT, \"\", ch[2], ch[3]])\n } else {\n ch @pushback\n print_token(outf, get_next_token(inp, pushback))\n }\n }\nend\n\nprocedure get_next_token(inp, pushback)\n local ch, ch1\n local ln, cn\n\n skip_spaces_and_comments(inp, pushback)\n ch := @inp\n ln := ch[2] # line number\n cn := ch[3] # column number\n case ch[1] of {\n \",\" : return [TOKEN_COMMA, \",\", ln, cn]\n \";\" : return [TOKEN_SEMICOLON, \";\", ln, cn]\n \"(\" : return [TOKEN_LEFTPAREN, \"(\", ln, cn]\n \")\" : return [TOKEN_RIGHTPAREN, \")\", ln, cn]\n \"{\" : return [TOKEN_LEFTBRACE, \"{\", ln, cn]\n \"}\" : return [TOKEN_RIGHTBRACE, \"}\", ln, cn]\n \"*\" : return [TOKEN_MULTIPLY, \"*\", ln, cn]\n \"/\" : return [TOKEN_DIVIDE, \"/\", ln, cn]\n \"%\" : return [TOKEN_MOD, \"%\", ln, cn]\n \"+\" : return [TOKEN_ADD, \"+\", ln, cn]\n \"-\" : return [TOKEN_SUBTRACT, \"-\", ln, cn]\n \"<\" : {\n ch1 := @inp\n if ch1[1] === \"=\" then {\n return [TOKEN_LESSEQUAL, \"<=\", ln, cn]\n } else {\n ch1 @pushback\n return [TOKEN_LESS, \"<\", ln, cn]\n }\n }\n \">\" : {\n ch1 := @inp\n if ch1[1] === \"=\" then {\n return [TOKEN_GREATEREQUAL, \">=\", ln, cn]\n } else {\n ch1 @pushback\n return [TOKEN_GREATER, \">\", ln, cn]\n }\n }\n \"=\" : {\n ch1 := @inp\n if ch1[1] === \"=\" then {\n return [TOKEN_EQUAL, \"==\", ln, cn]\n } else {\n ch1 @pushback\n return [TOKEN_ASSIGN, \"=\", ln, cn]\n }\n }\n \"!\" : {\n ch1 := @inp\n if ch1[1] === \"=\" then {\n return [TOKEN_NOTEQUAL, \"!=\", ln, cn]\n } else {\n ch1 @pushback\n return [TOKEN_NOT, \"!\", ln, cn]\n }\n }\n \"&\" : {\n ch1 := @inp\n if ch1[1] === \"&\" then {\n return [TOKEN_AND, \"&&\", ln, cn]\n } else {\n unexpected_character(ln, cn, ch)\n }\n }\n \"|\" : {\n ch1 := @inp\n if ch1[1] === \"|\" then {\n return [TOKEN_OR, \"||\", ln, cn]\n } else {\n unexpected_character(ln, cn, ch)\n }\n }\n \"\\\"\" : {\n ch @pushback\n return scan_string_literal(inp)\n }\n \"'\" : {\n ch @pushback\n return scan_character_literal(inp, pushback)\n }\n default : {\n if any(&digits, ch[1]) then {\n ch @pushback\n return scan_integer_literal(inp, pushback)\n } else if any(ident_start, ch[1]) then {\n ch @pushback\n return scan_identifier_or_reserved_word (inp, pushback)\n } else {\n unexpected_character(ln, cn, ch)\n }\n }\n }\nend\n\nprocedure scan_identifier_or_reserved_word(inp, pushback)\n local ch\n local s\n local line_no, column_no\n\n s := \"\"\n ch := @inp\n line_no := ch[2]\n column_no := ch[3]\n while EOF ~=== ch[1] & any(ident_continuation, ch[1]) do {\n s ||:= ch[1]\n ch := @inp\n }\n ch @pushback\n return reserved_word_lookup (s, line_no, column_no)\nend\n\nprocedure scan_integer_literal(inp, pushback)\n local ch\n local s\n local line_no, column_no\n\n s := \"\"\n ch := @inp\n line_no := ch[2]\n column_no := ch[3]\n while EOF ~=== ch[1] & any(ident_continuation, ch[1]) do {\n s ||:= ch[1]\n ch := @inp\n }\n ch @pushback\n not upto(~&digits, s) | invalid_integer_literal(line_no, column_no, s)\n return [TOKEN_INTEGER, s, line_no, column_no]\nend\n\nprocedure scan_character_literal(inp, pushback)\n local ch, ch1\n local close_quote\n local toktup\n local line_no, column_no\n\n ch := @inp # The opening quote.\n close_quote := ch[1] # Same as the opening quote.\n ch @pushback\n\n line_no := ch[2]\n column_no := ch[3]\n\n toktup := scan_character_literal_without_checking_end(inp)\n ch1 := @inp\n if ch1[1] ~=== close_quote then {\n repeat {\n case ch1[1] of {\n EOF : unterminated_character_literal(line_no, column_no)\n close_quote : multicharacter_literal(line_no, column_no)\n default : ch1 := @inp\n }\n }\n }\n return toktup\nend\n\nprocedure scan_character_literal_without_checking_end(inp)\n local ch, ch1, ch2\n\n ch := @inp # The opening quote.\n ch1 := @inp\n EOF ~=== ch1[1] | unterminated_character_literal(ch[2], ch[3])\n if ch1[1] == \"\\\\\" then {\n ch2 := @inp\n EOF ~=== ch2[1] | unterminated_character_literal(ch[2], ch[3])\n case ch2[1] of {\n \"n\" : return [TOKEN_INTEGER, string(ord(\"\\n\")), ch[2], ch[3]]\n \"\\\\\" : return [TOKEN_INTEGER, string(ord(\"\\\\\")), ch[2], ch[3]]\n default : unsupported_escape(ch1[2], ch1[3], ch2)\n }\n } else {\n return [TOKEN_INTEGER, string(ord(ch1[1])), ch[2], ch[3]]\n }\nend\n\nprocedure scan_string_literal(inp)\n local ch, ch1, ch2\n local line_no, column_no\n local close_quote\n local s\n local retval\n\n ch := @inp # The opening quote\n close_quote := ch[1] # Same as the opening quote.\n line_no := ch[2]\n column_no := ch[3]\n\n s := ch[1]\n until \\retval do {\n ch1 := @inp\n ch1[1] ~=== EOF |\n unterminated_string_literal (line_no, column_no,\n \"end of input\")\n ch1[1] ~== \"\\n\" |\n unterminated_string_literal (line_no, column_no,\n \"end of line\")\n if ch1[1] == close_quote then {\n retval := [TOKEN_STRING, s || close_quote, line_no, column_no]\n } else if ch1[1] ~== \"\\\\\" then {\n s ||:= ch1[1]\n } else {\n ch2 := @inp\n EOF ~=== ch2[1] | unsupported_escape(line_no, column_no, ch2)\n case ch2[1] of {\n \"n\" : s ||:= \"\\\\n\"\n \"\\\\\" : s ||:= \"\\\\\\\\\"\n default : unsupported_escape(line_no, column_no, ch2)\n }\n }\n }\n return retval\nend\n\nprocedure skip_spaces_and_comments(inp, pushback)\n local ch, ch1\n\n repeat {\n ch := @inp\n (EOF === ch[1]) & { ch @pushback; return }\n if not any(whitespace, ch[1]) then {\n (ch[1] == \"/\") | { ch @pushback; return }\n (ch1 := @inp) | { ch @pushback; return }\n (ch1[1] == \"*\") | { ch1 @pushback; ch @pushback; return }\n scan_comment(inp, ch[2], ch[3])\n }\n }\nend\n\nprocedure scan_comment(inp, line_no, column_no)\n local ch, ch1\n\n until (\\ch)[1] == \"*\" & (\\ch1)[1] == \"/\" do {\n ch := @inp\n (EOF === ch[1]) & unterminated_comment(line_no, column_no)\n if ch[1] == \"*\" then {\n ch1 := @inp\n (EOF === ch1[1]) & unterminated_comment(line_no, column_no)\n }\n }\n return\nend\n\nprocedure reserved_word_lookup(s, line_no, column_no)\n\n # Lookup is by an extremely simple perfect hash.\n\n static reserved_words\n static reserved_word_tokens\n local hashval, token, toktup\n\n initial {\n reserved_words := [\"if\", \"print\", \"else\",\n \"\", \"putc\", \"\",\n \"\", \"while\", \"\"]\n reserved_word_tokens :=\n [TOKEN_IF, TOKEN_PRINT, TOKEN_ELSE,\n TOKEN_IDENTIFIER, TOKEN_PUTC, TOKEN_IDENTIFIER,\n TOKEN_IDENTIFIER, TOKEN_WHILE, TOKEN_IDENTIFIER]\n }\n\n if *s < 2 then {\n toktup := [TOKEN_IDENTIFIER, s, line_no, column_no]\n } else {\n hashval := ((ord(s[1]) + ord(s[2])) % (*reserved_words)) + 1\n token := reserved_word_tokens[hashval]\n if token = TOKEN_IDENTIFIER | s ~== reserved_words[hashval] then {\n toktup := [TOKEN_IDENTIFIER, s, line_no, column_no]\n } else {\n toktup := [token, s, line_no, column_no]\n }\n }\n return toktup\nend\n\nprocedure print_token(outf, toktup)\n static token_names\n local s_line, s_column\n\n initial {\n token_names := [\"Keyword_else\",\n \"Keyword_if\",\n \"Keyword_print\",\n \"Keyword_putc\",\n \"Keyword_while\",\n \"Op_multiply\",\n \"Op_divide\",\n \"Op_mod\",\n \"Op_add\",\n \"Op_subtract\",\n \"Op_negate\",\n \"Op_less\",\n \"Op_lessequal\",\n \"Op_greater\",\n \"Op_greaterequal\",\n \"Op_equal\",\n \"Op_notequal\",\n \"Op_not\",\n \"Op_assign\",\n \"Op_and\",\n \"Op_or\",\n \"LeftParen\",\n \"RightParen\",\n \"LeftBrace\",\n \"RightBrace\",\n \"Semicolon\",\n \"Comma\",\n \"Identifier\",\n \"Integer\",\n \"String\",\n \"End_of_input\"]\n }\n\n /outf := &output\n s_line := string(toktup[3])\n s_column := string(toktup[4])\n writes(outf, right (s_line, max(5, *s_line)))\n writes(outf, \" \")\n writes(outf, right (s_column, max(5, *s_column)))\n writes(outf, \" \")\n writes(outf, token_names[toktup[1] + 1])\n case toktup[1] of {\n TOKEN_IDENTIFIER : writes(outf, \" \", toktup[2])\n TOKEN_INTEGER : writes(outf, \" \", toktup[2])\n TOKEN_STRING : writes(outf, \" \", toktup[2])\n }\n write(outf)\n return\nend\n\nprocedure inputter(inpf, pushback_buffer)\n local buffer\n local line_no, column_no\n local c\n\n buffer := \"\"\n line_no := 1\n column_no := 1\n\n repeat {\n buffer? {\n until *pushback_buffer = 0 & pos(0) do {\n if *pushback_buffer ~= 0 then {\n suspend pop(pushback_buffer)\n } else {\n c := move(1)\n suspend [c, line_no, column_no]\n if c == \"\\n\" then {\n line_no +:= 1\n column_no := 1\n } else {\n column_no +:= 1\n }\n }\n }\n }\n (buffer := reads(inpf, 2048)) |\n suspend [EOF, line_no, column_no]\n }\nend\n\nprocedure unterminated_comment(line_no, column_no)\n error(\"unterminated comment starting at \",\n line_no, \":\", column_no)\nend\n\nprocedure unexpected_character(line_no, column_no, ch)\n error(\"unexpected character '\", ch[1], \"' starting at \",\n line_no, \":\", column_no)\nend\n\nprocedure unterminated_string_literal (line_no, column_no, cause)\n error(\"unterminated string literal (\", cause, \") starting at \",\n line_no, \":\", column_no)\nend\n\nprocedure unsupported_escape (line_no, column_no, ch)\n if ch[1] === EOF then {\n error(\"unexpected \\\\ at end of input\",\n \" starting at \", line_no, \":\", column_no)\n } else {\n error(\"unsupported escape \\\\\", ch[1],\n \" starting at \", line_no, \":\", column_no)\n }\nend\n\nprocedure invalid_integer_literal(line_no, column_no, s)\n error(\"invalid integer literal \", s,\n \" starting at \", line_no, \":\", column_no)\nend\n\nprocedure unterminated_character_literal(line_no, column_no)\n error(\"unterminated character literal starting at \",\n line_no, \":\", column_no)\nend\n\nprocedure multicharacter_literal(line_no, column_no)\n error(\"unsupported multicharacter literal starting at \",\n line_no, \":\", column_no)\nend\n\nprocedure error(args[])\n write!([&errout] ||| args)\n exit(1)\nend\n\nprocedure max(x, y)\n return (if x < y then y else x)\nend\n", "language": "Icon" }, { "code": "symbols=:256#0\nch=: {{1 0+x[symbols=: x (a.i.y)} symbols}}\n'T0 token' =: 0 ch '%+-!(){};,<>=!|&'\n'L0 letter' =: 1 ch '_',,u:65 97+/i.26\n'D0 digit' =: 2 ch u:48+i.10\n'S0 space' =: 3 ch ' ',LF\n'C0 commen' =: 4 ch '/'\n'C1 comment'=: 5 ch '*'\n'q0 quote' =: 6 ch ''''\n'Q0 dquote' =: 7 ch '\"'\n\nwidth=: 1+>./symbols\ndefault=: ,:(1+i.width),every 2\nstates=:((1+i.width),every 1),width#default\nextend=: {{\n if.y>#states do.states=: y{.states,y#default\n end.states\n}}\npad=: {{if. 0=#y do.y=.#states end.y}}\nfunction=: {{ NB. x: before, m: op, n: symbol, y: after\n y[states=: (y,m) (<x,n)} extend 1+x>.y=.pad y\n}}\n{{for_op.y do.(op)=: op_index function end.0}};:'nop init start'\nall=: {{y=.pad y\n for_symbol.i.width do.\n x symbol nop y\n end.y\n}}\nany=: {{y=.pad y\n for_symbol.i.width do.\n x symbol start y\n end.y\n}}\n\nNB. identifiers and keywords\n L0 letter nop L0\n L0 digit nop L0\n\nNB. numbers\n D0 digit nop D0\n D0 letter nop D0\n\nNB. white space\n S0 space nop S0\n\nNB. comments\nC1=: C0 comment nop ''\nC2=: C1 all ''\n C2 all C2\nC3=: C2 commen nop ''\nC4=: C3 comment nop ''\n\nNB. quoted characters\nq1=: q0 any ''\n\nNB. strings\nQ1=: Q0 all ''\n Q1 all Q1\nQ2=: Q1 dquote nop ''\n Q0 dquote nop Q2\n\ntokenize=:{{\n tok=. (0;states;symbols);:y\n for_fix.cut'<= >= == != && ||'do.\n M=.;:;fix\n for_k.|.I.M E.tok do.\n tok=.(fix,<'') (0 1+k)} tok\n end.\n end.tok-.a:\n}}\n\n(tknames=:;: {{)n\n Op_multiply Op_divide Op_mod Op_add Op_subtract Op_less Op_lessequal\n Op_greater Op_greaterequal Op_equal Op_notequal Op_not Op_and Op_or\n Op_assign LeftParen RightParen Keyword_if LeftBrace Keyword_else\n RightBrace Keyword_while Semicolon Keyword_print Comma Keyword_putc\n}}-.LF)=: tkref=: tokenize '*/%+-<<=>>===!=!&&||=()if{else}while;print,putc'\nNB. the reference tokens here were arranged to avoid whitespace tokens\nNB. also, we reserve multiple token instances where a literal string\nNB. appears in different syntactic productions. Here, we only use the initial\nNB. instances -- the others will be used in the syntax analyzer which\nNB. uses the same tkref and tknames,\n\nshift=: |.!.0\nnumvals=: {{\n ndx=. I.(0<#@>y)**/@> y e.L:0 '0123456789'\n ({{\".y,'x'}}each ndx{y) ndx} y\n}}\nchrvals=: {{\n q=. y=<,''''\n s=. y=<,'\\'\n j=. I.(-.s)*(1&shift * _1&shift)q\n k=. I.(y e.;:'\\n')*(1 shift q)*(_2 shift q)*_1 shift s\n jvals=. a.i.L:0 j{y NB. not escaped\n kvals=. (k{s){<\"0 a.i.LF,'\\' NB. escaped\n (,a:,jvals,:a:) (,_1 0 1+/j)} (,a:,a:,kvals,:a:) (,_2 _1 0 1+/k)} y\n}}\n\nvalidstring=: ((1<#)*('\"'={.)*('\"'={:)*('\\'=])-:'\\n'&E.(+._1&shift)@+.'\\\\'&E.) every\n\nvalidid=: ((<,'\\')~:_1&|.) * (e.&tkref) < (e.&(u:I.symbols=letter)@{. * */@(e.&(u:I.symbols e.letter,digit))@}.) every\n\nlex=: {{\n lineref=.I.y=LF\n tokens=.(tokenize y),<,'_'\n offsets=.0,}:#@;\\tokens\n lines=. lineref I.offsets\n columns=. offsets-lines{0,lineref\n keep=. -.({.@> tokens)e.u:I.space=symbols\n names=. (<'End_of_input') _1} (tkref i.tokens) {(_3}.tknames),4#<'Error'\n unknown=. names=<'Error'\n values=. a: _1} unknown#inv numvals chrvals unknown#tokens\n names=. (<'Integer') (I.(values~:a:)*tokens~:values)} names\n names=. (<'String') (I.validstring tokens)} names\n names=. (<'Identifier') (I.validid tokens)} names\n names=. (<'End_of_input') _1} names\n comments=. '*/'&-:@(_2&{.)@> tokens\n whitespace=. (values=tokens) * e.&(' ',LF)@{.@> tokens\n keep=. (tokens~:<,'''')*-.comments+.whitespace+.unknown*a:=values\n keep&#each ((1+lines),.columns);<names,.values\n}}\n", "language": "J" }, { "code": "flex=: {{\n 'A B'=.y\n 'names values'=.|:\":each B\n (\":A),.' ',.names,.' ',.values\n}}@lex\n\ntestcase3=: {{)n\n/*\n All lexical tokens - not syntactically correct, but that will\n have to wait until syntax analysis\n */\n/* Print */ print /* Sub */ -\n/* Putc */ putc /* Lss */ <\n/* If */ if /* Gtr */ >\n/* Else */ else /* Leq */ <=\n/* While */ while /* Geq */ >=\n/* Lbrace */ { /* Eq */ ==\n/* Rbrace */ } /* Neq */ !=\n/* Lparen */ ( /* And */ &&\n/* Rparen */ ) /* Or */ ||\n/* Uminus */ - /* Semi */ ;\n/* Not */ ! /* Comma */ ,\n/* Mul */ * /* Assign */ =\n/* Div */ / /* Integer */ 42\n/* Mod */ % /* String */ \"String literal\"\n/* Add */ + /* Ident */ variable_name\n/* character literal */ '\\n'\n/* character literal */ '\\\\'\n/* character literal */ ' '\n}}\n\n flex testcase3\n 5 16 Keyword_print\n 5 40 Op_subtract\n 6 16 Keyword_putc\n 6 40 Op_less\n 7 16 Keyword_if\n 7 40 Op_greater\n 8 16 Keyword_else\n 8 40 Op_lessequal\n 9 16 Keyword_while\n 9 40 Op_greaterequal\n10 16 LeftBrace\n10 40 Op_equal\n11 16 RightBrace\n11 40 Op_notequal\n12 16 LeftParen\n12 40 Op_and\n13 16 RightParen\n13 40 Op_or\n14 16 Op_subtract\n14 40 Semicolon\n15 16 Op_not\n15 40 Comma\n16 16 Op_multiply\n16 40 Op_assign\n17 16 Op_divide\n17 40 Integer 42\n18 16 Op_mod\n18 40 String \"String literal\"\n19 16 Op_add\n19 40 Identifier variable_name\n20 28 Identifier 10\n21 28 Integer 92\n22 27 Integer 32\n23 1 End_of_input\n", "language": "J" }, { "code": "// Translated from python source\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class Lexer {\n private int line;\n private int pos;\n private int position;\n private char chr;\n private String s;\n\n Map<String, TokenType> keywords = new HashMap<>();\n\n static class Token {\n public TokenType tokentype;\n public String value;\n public int line;\n public int pos;\n Token(TokenType token, String value, int line, int pos) {\n this.tokentype = token; this.value = value; this.line = line; this.pos = pos;\n }\n @Override\n public String toString() {\n String result = String.format(\"%5d %5d %-15s\", this.line, this.pos, this.tokentype);\n switch (this.tokentype) {\n case Integer:\n result += String.format(\" %4s\", value);\n break;\n case Identifier:\n result += String.format(\" %s\", value);\n break;\n case String:\n result += String.format(\" \\\"%s\\\"\", value);\n break;\n }\n return result;\n }\n }\n\n static enum TokenType {\n End_of_input, Op_multiply, Op_divide, Op_mod, Op_add, Op_subtract,\n Op_negate, Op_not, Op_less, Op_lessequal, Op_greater, Op_greaterequal,\n Op_equal, Op_notequal, Op_assign, Op_and, Op_or, Keyword_if,\n Keyword_else, Keyword_while, Keyword_print, Keyword_putc, LeftParen, RightParen,\n LeftBrace, RightBrace, Semicolon, Comma, Identifier, Integer, String\n }\n\n static void error(int line, int pos, String msg) {\n if (line > 0 && pos > 0) {\n System.out.printf(\"%s in line %d, pos %d\\n\", msg, line, pos);\n } else {\n System.out.println(msg);\n }\n System.exit(1);\n }\n\n Lexer(String source) {\n this.line = 1;\n this.pos = 0;\n this.position = 0;\n this.s = source;\n this.chr = this.s.charAt(0);\n this.keywords.put(\"if\", TokenType.Keyword_if);\n this.keywords.put(\"else\", TokenType.Keyword_else);\n this.keywords.put(\"print\", TokenType.Keyword_print);\n this.keywords.put(\"putc\", TokenType.Keyword_putc);\n this.keywords.put(\"while\", TokenType.Keyword_while);\n\n }\n Token follow(char expect, TokenType ifyes, TokenType ifno, int line, int pos) {\n if (getNextChar() == expect) {\n getNextChar();\n return new Token(ifyes, \"\", line, pos);\n }\n if (ifno == TokenType.End_of_input) {\n error(line, pos, String.format(\"follow: unrecognized character: (%d) '%c'\", (int)this.chr, this.chr));\n }\n return new Token(ifno, \"\", line, pos);\n }\n Token char_lit(int line, int pos) {\n char c = getNextChar(); // skip opening quote\n int n = (int)c;\n if (c == '\\'') {\n error(line, pos, \"empty character constant\");\n } else if (c == '\\\\') {\n c = getNextChar();\n if (c == 'n') {\n n = 10;\n } else if (c == '\\\\') {\n n = '\\\\';\n } else {\n error(line, pos, String.format(\"unknown escape sequence \\\\%c\", c));\n }\n }\n if (getNextChar() != '\\'') {\n error(line, pos, \"multi-character constant\");\n }\n getNextChar();\n return new Token(TokenType.Integer, \"\" + n, line, pos);\n }\n Token string_lit(char start, int line, int pos) {\n String result = \"\";\n while (getNextChar() != start) {\n if (this.chr == '\\u0000') {\n error(line, pos, \"EOF while scanning string literal\");\n }\n if (this.chr == '\\n') {\n error(line, pos, \"EOL while scanning string literal\");\n }\n result += this.chr;\n }\n getNextChar();\n return new Token(TokenType.String, result, line, pos);\n }\n Token div_or_comment(int line, int pos) {\n if (getNextChar() != '*') {\n return new Token(TokenType.Op_divide, \"\", line, pos);\n }\n getNextChar();\n while (true) {\n if (this.chr == '\\u0000') {\n error(line, pos, \"EOF in comment\");\n } else if (this.chr == '*') {\n if (getNextChar() == '/') {\n getNextChar();\n return getToken();\n }\n } else {\n getNextChar();\n }\n }\n }\n Token identifier_or_integer(int line, int pos) {\n boolean is_number = true;\n String text = \"\";\n\n while (Character.isAlphabetic(this.chr) || Character.isDigit(this.chr) || this.chr == '_') {\n text += this.chr;\n if (!Character.isDigit(this.chr)) {\n is_number = false;\n }\n getNextChar();\n }\n\n if (text.equals(\"\")) {\n error(line, pos, String.format(\"identifer_or_integer unrecognized character: (%d) %c\", (int)this.chr, this.chr));\n }\n\n if (Character.isDigit(text.charAt(0))) {\n if (!is_number) {\n error(line, pos, String.format(\"invalid number: %s\", text));\n }\n return new Token(TokenType.Integer, text, line, pos);\n }\n\n if (this.keywords.containsKey(text)) {\n return new Token(this.keywords.get(text), \"\", line, pos);\n }\n return new Token(TokenType.Identifier, text, line, pos);\n }\n Token getToken() {\n int line, pos;\n while (Character.isWhitespace(this.chr)) {\n getNextChar();\n }\n line = this.line;\n pos = this.pos;\n\n switch (this.chr) {\n case '\\u0000': return new Token(TokenType.End_of_input, \"\", this.line, this.pos);\n case '/': return div_or_comment(line, pos);\n case '\\'': return char_lit(line, pos);\n case '<': return follow('=', TokenType.Op_lessequal, TokenType.Op_less, line, pos);\n case '>': return follow('=', TokenType.Op_greaterequal, TokenType.Op_greater, line, pos);\n case '=': return follow('=', TokenType.Op_equal, TokenType.Op_assign, line, pos);\n case '!': return follow('=', TokenType.Op_notequal, TokenType.Op_not, line, pos);\n case '&': return follow('&', TokenType.Op_and, TokenType.End_of_input, line, pos);\n case '|': return follow('|', TokenType.Op_or, TokenType.End_of_input, line, pos);\n case '\"': return string_lit(this.chr, line, pos);\n case '{': getNextChar(); return new Token(TokenType.LeftBrace, \"\", line, pos);\n case '}': getNextChar(); return new Token(TokenType.RightBrace, \"\", line, pos);\n case '(': getNextChar(); return new Token(TokenType.LeftParen, \"\", line, pos);\n case ')': getNextChar(); return new Token(TokenType.RightParen, \"\", line, pos);\n case '+': getNextChar(); return new Token(TokenType.Op_add, \"\", line, pos);\n case '-': getNextChar(); return new Token(TokenType.Op_subtract, \"\", line, pos);\n case '*': getNextChar(); return new Token(TokenType.Op_multiply, \"\", line, pos);\n case '%': getNextChar(); return new Token(TokenType.Op_mod, \"\", line, pos);\n case ';': getNextChar(); return new Token(TokenType.Semicolon, \"\", line, pos);\n case ',': getNextChar(); return new Token(TokenType.Comma, \"\", line, pos);\n\n default: return identifier_or_integer(line, pos);\n }\n }\n\n char getNextChar() {\n this.pos++;\n this.position++;\n if (this.position >= this.s.length()) {\n this.chr = '\\u0000';\n return this.chr;\n }\n this.chr = this.s.charAt(this.position);\n if (this.chr == '\\n') {\n this.line++;\n this.pos = 0;\n }\n return this.chr;\n }\n\n void printTokens() {\n Token t;\n while ((t = getToken()).tokentype != TokenType.End_of_input) {\n System.out.println(t);\n }\n System.out.println(t);\n }\n public static void main(String[] args) {\n if (args.length > 0) {\n try {\n\n File f = new File(args[0]);\n Scanner s = new Scanner(f);\n String source = \" \";\n while (s.hasNext()) {\n source += s.nextLine() + \"\\n\";\n }\n Lexer l = new Lexer(source);\n l.printTokens();\n } catch(FileNotFoundException e) {\n error(-1, -1, \"Exception: \" + e.getMessage());\n }\n } else {\n error(-1, -1, \"No args\");\n }\n }\n}\n", "language": "Java" }, { "code": "/*\n Token: type, value, line, pos\n*/\n\nconst TokenType = {\n Keyword_if: 1, Keyword_else: 2, Keyword_print: 3, Keyword_putc: 4, Keyword_while: 5,\n Op_add: 6, Op_and: 7, Op_assign: 8, Op_divide: 9, Op_equal: 10, Op_greater: 11,\n Op_greaterequal: 12, Op_less: 13, Op_Lessequal: 14, Op_mod: 15, Op_multiply: 16, Op_not: 17,\n Op_notequal: 18, Op_or: 19, Op_subtract: 20,\n Integer: 21, String: 22, Identifier: 23,\n Semicolon: 24, Comma: 25,\n LeftBrace: 26, RightBrace: 27,\n LeftParen: 28, RightParen: 29,\n End_of_input: 99\n}\n\nclass Lexer {\n constructor(source) {\n this.source = source\n this.pos = 1 // position in line\n this.position = 0 // position in source\n this.line = 1\n this.chr = this.source.charAt(0)\n this.keywords = {\n \"if\": TokenType.Keyword_if,\n \"else\": TokenType.Keyword_else,\n \"print\": TokenType.Keyword_print,\n \"putc\": TokenType.Keyword_putc,\n \"while\": TokenType.Keyword_while\n }\n }\n getNextChar() {\n this.pos++\n this.position++\n\n if (this.position >= this.source.length) {\n this.chr = undefined\n return this.chr\n }\n this.chr = this.source.charAt(this.position)\n if (this.chr === '\\n') {\n this.line++\n this.pos = 0\n }\n return this.chr\n }\n error(line, pos, message) {\n if (line > 0 && pos > 0) {\n console.log(message + \" in line \" + line + \", pos \" + pos + \"\\n\")\n } else {\n console.log(message)\n }\n process.exit(1)\n }\n follow(expect, ifyes, ifno, line, pos) {\n if (this.getNextChar() === expect) {\n this.getNextChar()\n return { type: ifyes, value: \"\", line, pos }\n }\n if (ifno === TokenType.End_of_input) {\n this.error(line, pos, \"follow: unrecognized character: (\" + this.chr.charCodeAt(0) + \") '\" + this.chr + \"'\")\n }\n return { type: ifno, value: \"\", line, pos }\n }\n div_or_comment(line, pos) {\n if (this.getNextChar() !== '*') {\n return { type: TokenType.Op_divide, value: \"/\", line, pos }\n }\n this.getNextChar()\n while (true) {\n if (this.chr === '\\u0000') {\n this.error(line, pos, \"EOF in comment\")\n } else if (this.chr === '*') {\n if (this.getNextChar() === '/') {\n this.getNextChar()\n return this.getToken()\n }\n } else {\n this.getNextChar()\n }\n }\n }\n char_lit(line, pos) {\n let c = this.getNextChar() // skip opening quote\n let n = c.charCodeAt(0)\n if (c === \"\\'\") {\n this.error(line, pos, \"empty character constant\")\n } else if (c === \"\\\\\") {\n c = this.getNextChar()\n if (c == \"n\") {\n n = 10\n } else if (c === \"\\\\\") {\n n = 92\n } else {\n this.error(line, pos, \"unknown escape sequence \\\\\" + c)\n }\n }\n if (this.getNextChar() !== \"\\'\") {\n this.error(line, pos, \"multi-character constant\")\n }\n this.getNextChar()\n return { type: TokenType.Integer, value: n, line, pos }\n }\n string_lit(start, line, pos) {\n let value = \"\"\n while (this.getNextChar() !== start) {\n if (this.chr === undefined) {\n this.error(line, pos, \"EOF while scanning string literal\")\n }\n if (this.chr === \"\\n\") {\n this.error(line, pos, \"EOL while scanning string literal\")\n }\n value += this.chr\n }\n this.getNextChar()\n return { type: TokenType.String, value, line, pos }\n }\n identifier_or_integer(line, pos) {\n let is_number = true\n let text = \"\"\n\n while (/\\w/.test(this.chr) || this.chr === '_') {\n text += this.chr\n if (!/\\d/.test(this.chr)) {\n is_number = false\n }\n this.getNextChar()\n }\n if (text === \"\") {\n this.error(line, pos, \"identifer_or_integer unrecopgnized character: follow: unrecognized character: (\" + this.chr.charCodeAt(0) + \") '\" + this.chr + \"'\")\n }\n\n if (/\\d/.test(text.charAt(0))) {\n if (!is_number) {\n this.error(line, pos, \"invaslid number: \" + text)\n }\n return { type: TokenType.Integer, value: text, line, pos }\n }\n\n if (text in this.keywords) {\n return { type: this.keywords[text], value: \"\", line, pos }\n }\n return { type: TokenType.Identifier, value: text, line, pos }\n }\n getToken() {\n let pos, line\n // Ignore whitespaces\n while (/\\s/.test(this.chr)) { this.getNextChar() }\n line = this.line; pos = this.pos\n switch (this.chr) {\n case undefined: return { type: TokenType.End_of_input, value: \"\", line: this.line, pos: this.pos }\n case \"/\": return this.div_or_comment(line, pos)\n case \"\\'\": return this.char_lit(line, pos)\n case \"\\\"\": return this.string_lit(this.chr, line, pos)\n\n case \"<\": return this.follow(\"=\", TokenType.Op_lessequal, TokenType.Op_less, line, pos)\n case \">\": return this.follow(\"=\", TokenType.Op_greaterequal, TokenType.Op_greater, line, pos)\n case \"=\": return this.follow(\"=\", TokenType.Op_equal, TokenType.Op_assign, line, pos)\n case \"!\": return this.follow(\"=\", TokenType.Op_notequal, TokenType.Op_not, line, pos)\n case \"&\": return this.follow(\"&\", TokenType.Op_and, TokenType.End_of_input, line, pos)\n case \"|\": return this.follow(\"|\", TokenType.Op_or, TokenType.End_of_input, line, pos)\n\n case \"{\": this.getNextChar(); return { type: TokenType.LeftBrace, value: \"{\", line, pos }\n case \"}\": this.getNextChar(); return { type: TokenType.RightBrace, value: \"}\", line, pos }\n case \"(\": this.getNextChar(); return { type: TokenType.LeftParen, value: \"(\", line, pos }\n case \")\": this.getNextChar(); return { type: TokenType.RightParen, value: \")\", line, pos }\n case \"+\": this.getNextChar(); return { type: TokenType.Op_add, value: \"+\", line, pos }\n case \"-\": this.getNextChar(); return { type: TokenType.Op_subtract, value: \"-\", line, pos }\n case \"*\": this.getNextChar(); return { type: TokenType.Op_multiply, value: \"*\", line, pos }\n case \"%\": this.getNextChar(); return { type: TokenType.Op_mod, value: \"%\", line, pos }\n case \";\": this.getNextChar(); return { type: TokenType.Semicolon, value: \";\", line, pos }\n case \",\": this.getNextChar(); return { type: TokenType.Comma, value: \",\", line, pos }\n\n default: return this.identifier_or_integer(line, pos)\n }\n }\n /*\n https://stackoverflow.com/questions/9907419/how-to-get-a-key-in-a-javascript-object-by-its-value\n */\n getTokenType(value) {\n return Object.keys(TokenType).find(key => TokenType[key] === value)\n }\n printToken(t) {\n let result = (\" \" + t.line).substr(t.line.toString().length)\n result += (\" \" + t.pos).substr(t.pos.toString().length)\n result += (\" \" + this.getTokenType(t.type) + \" \").substr(0, 16)\n switch (t.type) {\n case TokenType.Integer:\n result += \" \" + t.value\n break;\n case TokenType.Identifier:\n result += \" \" + t.value\n break;\n case TokenType.String:\n result += \" \\\"\"+ t.value + \"\\\"\"\n break;\n }\n console.log(result)\n }\n printTokens() {\n let t\n while ((t = this.getToken()).type !== TokenType.End_of_input) {\n this.printToken(t)\n }\n this.printToken(t)\n }\n}\nconst fs = require(\"fs\")\nfs.readFile(process.argv[2], \"utf8\", (err, data) => {\n l = new Lexer(data)\n l.printTokens()\n})\n", "language": "JavaScript" }, { "code": "struct Tokenized\n startline::Int\n startcol::Int\n name::String\n value::Union{Nothing, Int, String}\nend\n\nconst optokens = Dict(\"*\" => \"Op_multiply\", \"/\" => \"Op_divide\", \"%\" => \"Op_mod\", \"+\" => \"Op_add\",\n \"-\" => \"Op_subtract\", \"!\" => \"Op_not\", \"<\" => \"Op_less\", \"<=\" => \"Op_lessequal\",\n \">\" => \"Op_greater\", \">=\" => \"Op_greaterequal\", \"==\" => \"Op_equal\", \"!=\" => \"Op_notequal\",\n \"!\" => \"Op_not\", \"=\" => \"Op_assign\", \"&&\" => \"Op_and\", \"||\" => \"Op_or\")\n\nconst keywordtokens = Dict(\"if\" => \"Keyword_if\", \"else\" => \"Keyword_else\", \"while\" => \"Keyword_while\",\n \"print\" => \"Keyword_print\", \"putc\" => \"Keyword_putc\")\n\nconst symboltokens = Dict(\"(\" => \"LeftParen\", \")\" => \"RightParen\", \"{\" => \"LeftBrace\",\n \"}\" => \"RightBrace\", \";\" => \"Semicolon\", \",\" => \"Comma\")\n\nconst errors = [\"Empty character constant.\", \"Unknown escape sequence.\", \"Multi-character constant.\",\n \"End-of-file in comment. Closing comment characters not found.\",\n \"End-of-file while scanning string literal. Closing string character not found.\",\n \"End-of-line while scanning string literal. Closing string character not found before end-of-line.\",\n \"Unrecognized character.\", \"Invalid number. Starts like a number, but ends in non-numeric characters.\"]\n\nasws(s) = (nnl = length(findall(x->x=='\\n', s)); \" \" ^ (length(s) - nnl) * \"\\n\" ^ nnl)\ncomment2ws(t) = (while occursin(\"/*\", t) t = replace(t, r\"\\/\\* .+? (?: \\*\\/)\"xs => asws; count = 1) end; t)\nhasinvalidescapes(t) = ((m = match(r\"\\\\.\", t)) != nothing && m.match != \"\\\\\\\\\" && m.match != \"\\\\n\")\nhasemptycharconstant(t) = (match(r\"\\'\\'\", t) != nothing)\nhasmulticharconstant(t) = ((m = match(r\"\\'[^\\'][^\\']+\\'\", t)) != nothing && m.match != \"\\'\\\\\\\\\\'\" && m.match != \"\\'\\\\n\\'\")\nhasunbalancedquotes(t) = isodd(length(findall(x -> x == '\\\"', t)))\nhasunrecognizedchar(t) = match(r\"[^\\w\\s\\d\\*\\/\\%\\+\\-\\<\\>\\=\\!\\&\\|\\(\\)\\{\\}\\;\\,\\\"\\'\\\\]\", t) != nothing\n\nfunction throwiferror(line, n)\n if hasemptycharconstant(line)\n throw(\"Tokenizer error line $n: \" * errors[1])\n end\n if hasinvalidescapes(line)\n throw(\"Tokenizer error line $n: \" * errors[2])\n end\n if hasmulticharconstant(line)\n println(\"error at \", match(r\"\\'[^\\'][^\\']+\\'\", line).match)\n throw(\"Tokenizer error line $n: \" * errors[3])\n end\n if occursin(\"/*\", line)\n throw(\"Tokenizer error line $n: \" * errors[4])\n end\n if hasunrecognizedchar(line)\n throw(\"Tokenizer error line $n: \" * errors[7])\n end\nend\n\nfunction tokenize(txt)\n tokens = Vector{Tokenized}()\n txt = comment2ws(txt)\n lines = split(txt, \"\\n\")\n if hasunbalancedquotes(txt)\n throw(\"Tokenizer error: $(errors[5])\")\n end\n for (startline, line) in enumerate(lines)\n if strip(line) == \"\"\n continue\n end\n throwiferror(line, startline)\n lastc = Char(0)\n withintoken = 0\n for (startcol, c) in enumerate(line)\n if withintoken > 0\n withintoken -= 1\n continue\n elseif isspace(c[1])\n continue\n elseif (c == '=') && (startcol > 1) && ((c2 = line[startcol - 1]) in ['<', '>', '=', '!'])\n tokens[end] = Tokenized(startline, startcol - 1, optokens[c2 * c], nothing)\n elseif (c == '&') || (c == '|')\n if length(line) > startcol && line[startcol + 1] == c\n push!(tokens, Tokenized(startline, startcol, optokens[c * c], nothing))\n withintoken = 1\n else\n throw(\"Tokenizer error line $startline: $(errors[7])\")\n end\n elseif haskey(optokens, string(c))\n push!(tokens, Tokenized(startline, startcol, optokens[string(c)], nothing))\n elseif haskey(symboltokens, string(c))\n push!(tokens, Tokenized(startline, startcol, symboltokens[string(c)], nothing))\n elseif isdigit(c)\n integerstring = match(r\"^\\d+\", line[startcol:end]).match\n pastnumposition = startcol + length(integerstring)\n if (pastnumposition <= length(line)) && isletter(line[pastnumposition])\n throw(\"Tokenizer error line $startline: \" * errors[8])\n end\n i = parse(Int, integerstring)\n push!(tokens, Tokenized(startline, startcol, \"Integer\", i))\n withintoken = length(integerstring) - 1\n elseif c == Char(39) # single quote\n if (m = match(r\"([^\\\\\\'\\n]|\\\\n|\\\\\\\\)\\'\", line[startcol+1:end])) != nothing\n chs = m.captures[1]\n i = (chs == \"\\\\n\") ? Int('\\n') : (chs == \"\\\\\\\\\" ? Int('\\\\') : Int(chs[1]))\n push!(tokens, Tokenized(startline, startcol, \"Integer\", i))\n withintoken = length(chs) + 1\n else\n println(\"line $startline: bad match with \", line[startcol+1:end])\n end\n elseif c == Char(34) # double quote\n if (m = match(r\"([^\\\"\\n]+)\\\"\", line[startcol+1:end])) == nothing\n throw(\"Tokenizer error line $startline: $(errors[6])\")\n end\n litstring = m.captures[1]\n push!(tokens, Tokenized(startline, startcol, \"String\", \"\\\"$litstring\\\"\"))\n withintoken = length(litstring) + 1\n elseif (cols = findfirst(r\"[a-zA-Z]+\", line[startcol:end])) != nothing\n litstring = line[cols .+ startcol .- 1]\n if haskey(keywordtokens, string(litstring))\n push!(tokens, Tokenized(startline, startcol, keywordtokens[litstring], nothing))\n else\n litstring = match(r\"[_a-zA-Z0-9]+\", line[startcol:end]).match\n push!(tokens, Tokenized(startline, startcol, \"Identifier\", string(litstring)))\n end\n withintoken = length(litstring) - 1\n end\n lastc = c\n end\n end\n push!(tokens, Tokenized(length(lines), length(lines[end]) + 1, \"End_of_input\", nothing))\n tokens\nend\n\nconst test3txt = raw\"\"\"\n/*\n All lexical tokens - not syntactically correct, but that will\n have to wait until syntax analysis\n */\n/* Print */ print /* Sub */ -\n/* Putc */ putc /* Lss */ <\n/* If */ if /* Gtr */ >\n/* Else */ else /* Leq */ <=\n/* While */ while /* Geq */ >=\n/* Lbrace */ { /* Eq */ ==\n/* Rbrace */ } /* Neq */ !=\n/* Lparen */ ( /* And */ &&\n/* Rparen */ ) /* Or */ ||\n/* Uminus */ - /* Semi */ ;\n/* Not */ ! /* Comma */ ,\n/* Mul */ * /* Assign */ =\n/* Div */ / /* Integer */ 42\n/* Mod */ % /* String */ \"String literal\"\n/* Add */ + /* Ident */ variable_name\n/* character literal */ '\\n'\n/* character literal */ '\\\\'\n/* character literal */ ' '\n\"\"\"\n\nprintln(\"Line Col Name Value\")\nfor tok in tokenize(test3txt)\n println(lpad(tok.startline, 3), lpad(tok.startcol, 5), lpad(tok.name, 18), \" \", tok.value != nothing ? tok.value : \"\")\nend\n", "language": "Julia" }, { "code": "// Input: command line argument of file to process or console input. A two or\n// three character console input of digits followed by a new line will be\n// checked for an integer between zero and twenty-five to select a fixed test\n// case to run. Any other console input will be parsed.\n\n// Code based on the Java version found here:\n// https://rosettacode.org/mw/index.php?title=Compiler/lexical_analyzer&action=edit&section=22\n\n// Class to halt the parsing with an exception.\nclass ParsingFailed(message: String): Exception(message)\n\n// Enumerate class of tokens supported by this scanner.\nenum class TokenType {\n Tk_End_of_input, Op_multiply, Op_divide, Op_mod, Op_add, Op_subtract,\n Op_negate, Op_not, Op_less, Op_lessequal, Op_greater, Op_greaterequal,\n Op_equal, Op_notequal, Op_assign, Op_and, Op_or, Kw_if,\n Kw_else, Kw_while, Kw_print, Kw_putc, Sy_LeftParen, Sy_RightParen,\n Sy_LeftBrace, Sy_RightBrace, Sy_Semicolon, Sy_Comma, Tk_Identifier,\n Tk_Integer, Tk_String;\n\n override fun toString() =\n listOf(\"End_of_input\", \"Op_multiply\", \"Op_divide\", \"Op_mod\", \"Op_add\",\n \"Op_subtract\", \"Op_negate\", \"Op_not\", \"Op_less\", \"Op_lessequal\",\n \"Op_greater\", \"Op_greaterequal\", \"Op_equal\", \"Op_notequal\",\n \"Op_assign\", \"Op_and\", \"Op_or\", \"Keyword_if\", \"Keyword_else\",\n \"Keyword_while\", \"Keyword_print\", \"Keyword_putc\", \"LeftParen\",\n \"RightParen\", \"LeftBrace\", \"RightBrace\", \"Semicolon\", \"Comma\",\n \"Identifier\", \"Integer\", \"String\")[this.ordinal]\n} // TokenType\n\n// Data class of tokens returned by the scanner.\ndata class Token(val token: TokenType, val value: String, val line: Int,\n val pos: Int) {\n\n // Overridden method to display the token.\n override fun toString() =\n \"%5d %5d %-15s %s\".format(line, pos, this.token,\n when (this.token) {\n TokenType.Tk_Integer, TokenType.Tk_Identifier ->\n \" %s\".format(this.value)\n TokenType.Tk_String ->\n this.value.toList().joinToString(\"\", \" \\\"\", \"\\\"\") {\n when (it) {\n '\\t' ->\n \"\\\\t\"\n '\\n' ->\n \"\\\\n\"\n '\\u000b' ->\n \"\\\\v\"\n '\\u000c' ->\n \"\\\\f\"\n '\\r' ->\n \"\\\\r\"\n '\"' ->\n \"\\\\\\\"\"\n '\\\\' ->\n \"\\\\\"\n in ' '..'~' ->\n \"$it\"\n else ->\n \"\\\\u%04x\".format(it.code) } }\n else ->\n \"\" } )\n} // Token\n\n// Function to display an error message and halt the scanner.\nfun error(line: Int, pos: Int, msg: String): Nothing =\n throw ParsingFailed(\"(%d, %d) %s\\n\".format(line, pos, msg))\n\n// Class to process the source into tokens with properties of the\n// source string, the line number, the column position, the index\n// within the source string, the current character being processed,\n// and map of the keyword strings to the corresponding token type.\nclass Lexer(private val s: String) {\n private var line = 1\n private var pos = 1\n private var position = 0\n private var chr =\n if (s.isEmpty())\n ' '\n else\n s[0]\n private val keywords = mapOf<String, TokenType>(\n \"if\" to TokenType.Kw_if,\n \"else\" to TokenType.Kw_else,\n \"print\" to TokenType.Kw_print,\n \"putc\" to TokenType.Kw_putc,\n \"while\" to TokenType.Kw_while)\n\n // Method to retrive the next character from the source. Use null after\n // the end of our source.\n private fun getNextChar() =\n if (++this.position >= this.s.length) {\n this.pos++\n this.chr = '\\u0000'\n this.chr\n } else {\n this.pos++\n this.chr = this.s[this.position]\n when (this.chr) {\n '\\n' -> {\n this.line++\n this.pos = 0\n } // line\n '\\t' ->\n while (this.pos%8 != 1)\n this.pos++\n } // when\n this.chr\n } // if\n\n // Method to return the division token, skip the comment, or handle the\n // error.\n private fun div_or_comment(line: Int, pos: Int): Token =\n if (getNextChar() != '*')\n Token(TokenType.Op_divide, \"\", line, pos);\n else {\n getNextChar() // Skip comment start\n outer@\n while (true)\n when (this.chr) {\n '\\u0000' ->\n error(line, pos, \"Lexer: EOF in comment\");\n '*' ->\n if (getNextChar() == '/') {\n getNextChar() // Skip comment end\n break@outer\n } // if\n else ->\n getNextChar()\n } // when\n getToken()\n } // if\n\n // Method to verify a character literal. Return the token or handle the\n // error.\n private fun char_lit(line: Int, pos: Int): Token {\n var c = getNextChar() // skip opening quote\n when (c) {\n '\\'' ->\n error(line, pos, \"Lexer: Empty character constant\");\n '\\\\' ->\n c = when (getNextChar()) {\n 'n' ->\n 10.toChar()\n '\\\\' ->\n '\\\\'\n '\\'' ->\n '\\''\n else ->\n error(line, pos, \"Lexer: Unknown escape sequence '\\\\%c'\".\n format(this.chr)) }\n } // when\n if (getNextChar() != '\\'')\n error(line, pos, \"Lexer: Multi-character constant\")\n getNextChar() // Skip closing quote\n return Token(TokenType.Tk_Integer, c.code.toString(), line, pos)\n } // char_lit\n\n // Method to check next character to see whether it belongs to the token\n // we might be in the middle of. Return the correct token or handle the\n // error.\n private fun follow(expect: Char, ifyes: TokenType, ifno: TokenType,\n line: Int, pos: Int): Token =\n when {\n getNextChar() == expect -> {\n getNextChar()\n Token(ifyes, \"\", line, pos)\n } // matches\n ifno == TokenType.Tk_End_of_input ->\n error(line, pos,\n \"Lexer: %c expected: (%d) '%c'\".format(expect,\n this.chr.code, this.chr))\n else ->\n Token(ifno, \"\", line, pos)\n } // when\n\n // Method to verify a character string. Return the token or handle the\n // error.\n private fun string_lit(start: Char, line: Int, pos: Int): Token {\n var result = \"\"\n while (getNextChar() != start)\n when (this.chr) {\n '\\u0000' ->\n error(line, pos, \"Lexer: EOF while scanning string literal\")\n '\\n' ->\n error(line, pos, \"Lexer: EOL while scanning string literal\")\n '\\\\' ->\n when (getNextChar()) {\n '\\\\' ->\n result += '\\\\'\n 'n' ->\n result += '\\n'\n '\"' ->\n result += '\"'\n else ->\n error(line, pos, \"Lexer: Escape sequence unknown '\\\\%c'\".\n format(this.chr))\n } // when\n else ->\n result += this.chr\n } // when\n getNextChar() // Toss closing quote\n return Token(TokenType.Tk_String, result, line, pos)\n } // string_lit\n\n // Method to retrive an identifier or integer. Return the keyword\n // token, if the string matches one. Return the integer token,\n // if the string is all digits. Return the identifer token, if the\n // string is valid. Otherwise, handle the error.\n private fun identifier_or_integer(line: Int, pos: Int): Token {\n var is_number = true\n var text = \"\"\n while (this.chr in listOf('_')+('0'..'9')+('a'..'z')+('A'..'Z')) {\n text += this.chr\n is_number = is_number && this.chr in '0'..'9'\n getNextChar()\n } // while\n if (text.isEmpty())\n error(line, pos, \"Lexer: Unrecognized character: (%d) %c\".\n format(this.chr.code, this.chr))\n return when {\n text[0] in '0'..'9' ->\n if (!is_number)\n error(line, pos, \"Lexer: Invalid number: %s\".\n format(text))\n else {\n val max = Int.MAX_VALUE.toString()\n if (text.length > max.length || (text.length == max.length &&\n max < text))\n error(line, pos,\n \"Lexer: Number exceeds maximum value %s\".\n format(text))\n Token(TokenType.Tk_Integer, text, line, pos)\n } // if\n this.keywords.containsKey(text) ->\n Token(this.keywords[text]!!, \"\", line, pos)\n else ->\n Token(TokenType.Tk_Identifier, text, line, pos) }\n } // identifier_or_integer\n\n // Method to skip whitespace both C's and Unicode ones and retrive the next\n // token.\n private fun getToken(): Token {\n while (this.chr in listOf('\\t', '\\n', '\\u000b', '\\u000c', '\\r', ' ') ||\n this.chr.isWhitespace())\n getNextChar()\n val line = this.line\n val pos = this.pos\n return when (this.chr) {\n '\\u0000' ->\n Token(TokenType.Tk_End_of_input, \"\", line, pos)\n '/' ->\n div_or_comment(line, pos)\n '\\'' ->\n char_lit(line, pos)\n '<' ->\n follow('=', TokenType.Op_lessequal, TokenType.Op_less, line, pos)\n '>' ->\n follow('=', TokenType.Op_greaterequal, TokenType.Op_greater, line, pos)\n '=' ->\n follow('=', TokenType.Op_equal, TokenType.Op_assign, line, pos)\n '!' ->\n follow('=', TokenType.Op_notequal, TokenType.Op_not, line, pos)\n '&' ->\n follow('&', TokenType.Op_and, TokenType.Tk_End_of_input, line, pos)\n '|' ->\n follow('|', TokenType.Op_or, TokenType.Tk_End_of_input, line, pos)\n '\"' ->\n string_lit(this.chr, line, pos)\n '{' -> {\n getNextChar()\n Token(TokenType.Sy_LeftBrace, \"\", line, pos)\n } // open brace\n '}' -> {\n getNextChar()\n Token(TokenType.Sy_RightBrace, \"\", line, pos)\n } // close brace\n '(' -> {\n getNextChar()\n Token(TokenType.Sy_LeftParen, \"\", line, pos)\n } // open paren\n ')' -> {\n getNextChar()\n Token(TokenType.Sy_RightParen, \"\", line, pos)\n } // close paren\n '+' -> {\n getNextChar()\n Token(TokenType.Op_add, \"\", line, pos)\n } // plus\n '-' -> {\n getNextChar()\n Token(TokenType.Op_subtract, \"\", line, pos)\n } // dash\n '*' -> {\n getNextChar()\n Token(TokenType.Op_multiply, \"\", line, pos)\n } // asterisk\n '%' -> {\n getNextChar()\n Token(TokenType.Op_mod, \"\", line, pos)\n } // percent\n ';' -> {\n getNextChar()\n Token(TokenType.Sy_Semicolon, \"\", line, pos)\n } // semicolon\n ',' -> {\n getNextChar()\n Token(TokenType.Sy_Comma, \"\", line, pos)\n } // comma\n else ->\n identifier_or_integer(line, pos) }\n } // getToken\n\n // Method to parse and display tokens.\n fun printTokens() {\n do {\n val t: Token = getToken()\n println(t)\n } while (t.token != TokenType.Tk_End_of_input)\n } // printTokens\n} // Lexer\n\n\n// Function to test all good tests from the website and produce all of the\n// error messages this program supports.\nfun tests(number: Int) {\n\n // Function to generate test case 0 source: Hello World/Text.\n fun hello() {\n Lexer(\n\"\"\"/*\nHello world\n*/\nprint(\"Hello, World!\\n\");\n\"\"\").printTokens()\n } // hello\n\n // Function to generate test case 1 source: Phoenix Number.\n fun phoenix() {\n Lexer(\n\"\"\"/*\nShow Ident and Integers\n*/\nphoenix_number = 142857;\nprint(phoenix_number, \"\\n\");\"\"\").printTokens()\n } // phoenix\n\n // Function to generate test case 2 source: All Symbols.\n fun symbols() {\n Lexer(\n\"\"\"/*\n All lexical tokens - not syntactically correct, but that will\n have to wait until syntax analysis\n */\n/* Print */ print /* Sub */ -\n/* Putc */ putc /* Lss */ <\n/* If */ if /* Gtr */ >\n/* Else */ else /* Leq */ <=\n/* While */ while /* Geq */ >=\n/* Lbrace */ { /* Eq */ ==\n/* Rbrace */ } /* Neq */ !=\n/* Lparen */ ( /* And */ &&\n/* Rparen */ ) /* Or */ ||\n/* Uminus */ - /* Semi */ ;\n/* Not */ ! /* Comma */ ,\n/* Mul */ * /* Assign */ =\n/* Div */ / /* Integer */ 42\n/* Mod */ % /* String */ \"String literal\"\n/* Add */ + /* Ident */ variable_name\n/* character literal */ '\\n'\n/* character literal */ '\\\\'\n/* character literal */ ' '\"\"\").printTokens()\n } // symbols\n\n // Function to generate test case 3 source: Test Case 4.\n fun four() {\n Lexer(\n\"\"\"/*** test printing, embedded \\n and comments with lots of '*' ***/\nprint(42);\nprint(\"\\nHello World\\nGood Bye\\nok\\n\");\nprint(\"Print a slash n - \\\\n.\\n\");\"\"\").printTokens()\n } // four\n\n // Function to generate test case 4 source: Count.\n fun count() {\n Lexer(\n\"\"\"count = 1;\nwhile (count < 10) {\n print(\"count is: \", count, \"\\n\");\n count = count + 1;\n}\"\"\").printTokens()\n } // count\n\n // Function to generate test case 5 source: 100 Doors.\n fun doors() {\n Lexer(\n\"\"\"/* 100 Doors */\ni = 1;\nwhile (i * i <= 100) {\n print(\"door \", i * i, \" is open\\n\");\n i = i + 1;\n}\"\"\").printTokens()\n } // doors\n\n // Function to generate test case 6 source: Negative Tests.\n fun negative() {\n Lexer(\n\"\"\"a = (-1 * ((-1 * (5 * 15)) / 10));\nprint(a, \"\\n\");\nb = -a;\nprint(b, \"\\n\");\nprint(-b, \"\\n\");\nprint(-(1), \"\\n\");\"\"\").printTokens()\n } // negative\n\n // Function to generate test case 7 source: Deep.\n fun deep() {\n Lexer(\n\"\"\"print(---------------------------------+++5, \"\\n\");\nprint(((((((((3 + 2) * ((((((2))))))))))))), \"\\n\");\n \nif (1) { if (1) { if (1) { if (1) { if (1) { print(15, \"\\n\"); } } } } }\"\"\").printTokens()\n } // deep\n\n // Function to generate test case 8 source: Greatest Common Divisor.\n fun gcd() {\n Lexer(\n\"\"\"/* Compute the gcd of 1071, 1029: 21 */\n \na = 1071;\nb = 1029;\n \nwhile (b != 0) {\n new_a = b;\n b = a % b;\n a = new_a;\n}\nprint(a);\"\"\").printTokens()\n } // gcd\n\n // Function to generate test case 9 source: Factorial.\n fun factorial() {\n Lexer(\n\"\"\"/* 12 factorial is 479001600 */\n \nn = 12;\nresult = 1;\ni = 1;\nwhile (i <= n) {\n result = result * i;\n i = i + 1;\n}\nprint(result);\"\"\").printTokens()\n } // factorial\n\n // Function to generate test case 10 source: Fibonacci Sequence.\n fun fibonacci() {\n Lexer(\n\"\"\"/* fibonacci of 44 is 701408733 */\n \nn = 44;\ni = 1;\na = 0;\nb = 1;\nwhile (i < n) {\n w = a + b;\n a = b;\n b = w;\n i = i + 1;\n}\nprint(w, \"\\n\");\"\"\").printTokens()\n } // fibonacci\n\n // Function to generate test case 11 source: FizzBuzz.\n fun fizzbuzz() {\n Lexer(\n\"\"\"/* FizzBuzz */\ni = 1;\nwhile (i <= 100) {\n if (!(i % 15))\n print(\"FizzBuzz\");\n else if (!(i % 3))\n print(\"Fizz\");\n else if (!(i % 5))\n print(\"Buzz\");\n else\n print(i);\n \n print(\"\\n\");\n i = i + 1;\n}\"\"\").printTokens()\n } // fizzbuzz\n\n // Function to generate test case 12 source: 99 Bottles of Beer.\n fun bottles() {\n Lexer(\n\"\"\"/* 99 bottles */\nbottles = 99;\nwhile (bottles > 0) {\n print(bottles, \" bottles of beer on the wall\\n\");\n print(bottles, \" bottles of beer\\n\");\n print(\"Take one down, pass it around\\n\");\n bottles = bottles - 1;\n print(bottles, \" bottles of beer on the wall\\n\\n\");\n}\"\"\").printTokens()\n } // bottles\n\n // Function to generate test case 13 source: Primes.\n fun primes() {\n Lexer(\n\"\"\"/*\nSimple prime number generator\n*/\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n k=3;\n p=1;\n n=n+2;\n while ((k*k<=n) && (p)) {\n p=n/k*k!=n;\n k=k+2;\n }\n if (p) {\n print(n, \" is prime\\n\");\n count = count + 1;\n }\n}\nprint(\"Total primes found: \", count, \"\\n\");\"\"\").printTokens()\n } // primes\n\n // Function to generate test case 14 source: Ascii Mandelbrot.\n fun ascii() {\n Lexer(\n\"\"\"{\n/*\n This is an integer ascii Mandelbrot generator\n */\n left_edge = -420;\n right_edge = 300;\n top_edge = 300;\n bottom_edge = -300;\n x_step = 7;\n y_step = 15;\n\n max_iter = 200;\n\n y0 = top_edge;\n while (y0 > bottom_edge) {\n x0 = left_edge;\n while (x0 < right_edge) {\n y = 0;\n x = 0;\n the_char = ' ';\n i = 0;\n while (i < max_iter) {\n x_x = (x * x) / 200;\n y_y = (y * y) / 200;\n if (x_x + y_y > 800 ) {\n the_char = '0' + i;\n if (i > 9) {\n the_char = '@';\n }\n i = max_iter;\n }\n y = x * y / 100 + y0;\n x = x_x - y_y + x0;\n i = i + 1;\n }\n putc(the_char);\n x0 = x0 + x_step;\n }\n putc('\\n');\n y0 = y0 - y_step;\n }\n}\n\"\"\").printTokens()\n } // ascii\n\n when (number) {\n 0 ->\n hello()\n 1 ->\n phoenix()\n 2 ->\n symbols()\n 3 ->\n four()\n 4 ->\n count()\n 5 ->\n doors()\n 6 ->\n negative()\n 7 ->\n deep()\n 8 ->\n gcd()\n 9 ->\n factorial()\n 10 ->\n fibonacci()\n 11 ->\n fizzbuzz()\n 12 ->\n bottles()\n 13 ->\n primes()\n 14 ->\n ascii()\n 15 -> // Lexer: Empty character constant\n Lexer(\"''\").printTokens()\n 16 -> // Lexer: Unknown escape sequence\n Lexer(\"'\\\\x\").printTokens()\n 17 -> // Lexer: Multi-character constant\n Lexer(\"' \").printTokens()\n 18 -> // Lexer: EOF in comment\n Lexer(\"/*\").printTokens()\n 19 -> // Lexer: EOL in string\n Lexer(\"\\\"\\n\").printTokens()\n 20 -> // Lexer: EOF in string\n Lexer(\"\\\"\").printTokens()\n 21 -> // Lexer: Escape sequence unknown\n Lexer(\"\\\"\\\\x\").printTokens()\n 22 -> // Lexer: Unrecognized character\n Lexer(\"~\").printTokens()\n 23 -> // Lexer: invalid number\n Lexer(\"9a9\").printTokens()\n 24 -> // Lexer: Number exceeds maximum value\n Lexer(\"2147483648\\n9223372036854775808\").printTokens()\n 25 -> // Lexer: Operator expected\n Lexer(\"|.\").printTokens()\n else ->\n println(\"Invalid test number %d!\".format(number))\n } // when\n} // tests\n\n// Main function to check our source and read its data before parsing it.\n// With no source specified, run the test of all symbols.\nfun main(args: Array<String>) {\n try {\n val s =\n if (args.size > 0 && args[0].isNotEmpty()) // file on command line\n java.util.Scanner(java.io.File(args[0]))\n else // use the console\n java.util.Scanner(System.`in`)\n var source = \"\"\n while (s.hasNext())\n source += s.nextLine()+\n if (s.hasNext())\n \"\\n\"\n else\n \"\"\n if (args.size > 0 && args[0].isNotEmpty()) // file on command line\n Lexer(source).printTokens()\n else {\n val digits = source.filter { it in '0'..'9' }\n when {\n source.isEmpty() -> // nothing given\n tests(2)\n source.length in 1..2 && digits.length == source.length &&\n digits.toInt() in 0..25 ->\n tests(digits.toInt())\n else ->\n Lexer(source).printTokens()\n } // when\n } // if\n } catch(e: Throwable) {\n println(e.message)\n System.exit(1)\n } // try\n} // main\n", "language": "Kotlin" }, { "code": "-- module token_name (in a file \"token_name.lua\")\nlocal token_name = {\n ['*'] = 'Op_multiply',\n ['/'] = 'Op_divide',\n ['%'] = 'Op_mod',\n ['+'] = 'Op_add',\n ['-'] = 'Op_subtract',\n ['<'] = 'Op_less',\n ['<='] = 'Op_lessequal',\n ['>'] = 'Op_greater',\n ['>='] = 'Op_greaterequal',\n ['=='] = 'Op_equal',\n ['!='] = 'Op_notequal',\n ['!'] = 'Op_not',\n ['='] = 'Op_assign',\n ['&&'] = 'Op_and',\n ['||'] = 'Op_or',\n ['('] = 'LeftParen',\n [')'] = 'RightParen',\n ['{'] = 'LeftBrace',\n ['}'] = 'RightBrace',\n [';'] = 'Semicolon',\n [','] = 'Comma',\n ['if'] = 'Keyword_if',\n ['else'] = 'Keyword_else',\n ['while'] = 'Keyword_while',\n ['print'] = 'Keyword_print',\n ['putc'] = 'Keyword_putc',\n}\nreturn token_name\n", "language": "Lua" }, { "code": "-- module lpeg_token_finder\nlocal M = {} -- only items added to M will be public (via 'return M' at end)\nlocal table, concat = table, table.concat\nlocal error, tonumber = error, tonumber\n\nlocal lpeg = require 'lpeg' -- see http://www.inf.puc-rio.br/~roberto/lpeg/\nlocal token_name = require 'token_name'\n_ENV = {}\n\nlocal imports = 'P R S C Carg Cb Cc Cf Cg Cp Cs Ct Cmt V'\nfor w in imports:gmatch('%a+') do _ENV[w] = lpeg[w] end\n\n------------------- Define patterns to match tokens -----------------------\n\nalpha = R'az' + R'AZ' + P'_'\ndigit = R'09'\nalnum = alpha + digit\nspace = S' \\t\\r\\n'\n\nfunction ptok(text) return {name=token_name[text]} end\nop2c = C(P'<=' + P'>=' + P'==' + P'!=' + P'&&' + P'||') / ptok\nop1c = C(S'*/%+-<>!=') / ptok\nsymbol = C(S'(){};,') / ptok\n\nkeyword_or_identifier = C(alpha * alnum^0) / function(text)\n local name = token_name[text]\n return name and {name=name} or {name='Identifier', value=text}\nend\n\ninteger = C(digit^1) * -alpha / function(text)\n return {name='Integer', value=tonumber(text)}\nend\n\nCline = Carg(1) -- call to 'match' sets the first extra argument to source line number\n\nbad_escseq_err = Cmt(Cline, function (_,pos,line)\n error{err='bad_escseq', line=line, column=pos-1}\nend)\n\nesc_subst = {['\\\\'] = '\\\\', ['n'] = '\\n'}\nescseq = P'\\\\' * C(S'\\\\n' + bad_escseq_err) / esc_subst\n\nqchar = P\"'\" * ( C( P(1) - S\"'\\n\\\\\" ) + escseq ) * P\"'\" / function (text)\n return {name='Integer', value=text:byte()}\nend\n\nqstr = P'\"' * ( C((P(1) - S'\"\\n\\\\')^1) + escseq )^0 * P'\"' / function(...)\n return {name='String', value=concat{...}}\nend\n\nCtoken = symbol + op2c + op1c + keyword_or_identifier + integer + qstr + qchar\n\nunfinished_comment_err = Cmt(Cline * Cb('SOC'), function (_, pos, line, socpos)\n error{err='unfinished_comment', line=line, column=socpos}\nend)\ncommentstart = Cg(Cp() * P'/*', 'SOC')\ncommentrest = (P(1) - P'*/')^0 * (P'*/' + unfinished_comment_err)\ncomment = commentstart * commentrest\nmorecomment = Cg(Cp(), 'SOC') * commentrest\n\nws = (space^1 + comment)^0\n\nbad_token_err = Cmt(Cline, function (_, pos, line)\n error{err='invalid_token', line=line, column=pos}\nend)\n\ntokenpat = ws * Cline * Cp() * (C(-1) + Ctoken + bad_token_err) * Cp() /\n function (line, pos, token, nextpos)\n if pos == nextpos then -- at end of line; no token\n return nil\n else\n token.line, token.column = line, pos\n return token, nextpos\n end\n end\n\nclosecomment_tokenpat = morecomment * tokenpat\n\nfunction M.find_token(line, line_pos, line_number, in_comment)\n pattern = in_comment and closecomment_tokenpat or tokenpat\n return lpeg.match(pattern, line, line_pos, line_number)\nend\n\nreturn M\n", "language": "Lua" }, { "code": "-- module lexer\nlocal M = {} -- only items added to M will publicly available (via 'return M' at end)\nlocal string, io, coroutine, yield = string, io, coroutine, coroutine.yield\nlocal error, pcall, type = error, pcall, type\n\nlocal finder = require 'lpeg_token_finder'\n_ENV = {}\n\n-- produces a token iterator given a source line iterator\nfunction M.tokenize_lineiter(lineiter)\n local function fatal(err)\n local msgtext = {\n unfinished_comment = \"EOF inside comment started\",\n invalid_token = \"Invalid token\",\n bad_escseq = \"Invalid escape sequence\",\n }\n local fmt = \"LEX ERROR: %s at line %d, column %d\"\n error(string.format(fmt, msgtext[err.err], err.line, err.column))\n end\n\n return coroutine.wrap(function()\n local line_number = 0\n local line_pos\n local in_comment -- where unfinished comment started\n\n for line in lineiter do\n line_number = line_number + 1\n line_pos = 1\n\n local function scanline() -- yield current line's tokens\n repeat\n local token, pos =\n finder.find_token(line, line_pos, line_number, in_comment)\n if token then\n line_pos = pos\n in_comment = nil\n yield(token)\n end\n until token == nil\n end\n\n if line then\n local ok, err = pcall(scanline)\n if ok then\n in_comment = nil\n elseif type(err) == 'table' and err.err=='unfinished_comment' then\n if not(in_comment and err.column==1) then\n in_comment = err\n end\n elseif type(err) == 'table' then\n fatal(err)\n else\n error(err) -- some internal error\n end\n end\n end\n if in_comment then\n fatal(in_comment)\n else\n yield{name='End_of_input', line=line_number+1, column=1}\n end\n return nil\n end)\nend\n\n------------------- exports -----------------------------\n\nlexer = M.tokenize_lineiter\n\nfunction M.tokenize_file(filename)\n return lexer(io.lines(filename))\nend\n\nfunction M.tokenize_text(text)\n return lexer(text:gmatch('[^\\n]+'))\nend\n\n-- M._INTERNALS = _ENV\nreturn M\n", "language": "Lua" }, { "code": "lexer = require 'lexer'\nformat, gsub = string.format, string.gsub\n\nfunction printf(fmt, ...) print(format(fmt, ...)) end\n\nfunction stringrep(str)\n local subst = {['\\n'] = \"\\\\n\", ['\\\\'] = '\\\\\\\\'}\n return format('\"%s\"', gsub(str, '[\\n\\\\]', subst))\nend\n\nfunction display(text)\n for t in lexer.tokenize_text(text) do\n local value = (t.name=='String') and stringrep(t.value) or t.value or ''\n printf(\"%4d %3d %-15s %s\", t.line, t.column, t.name, value)\n end\nend\n\n----------------------- test cases from Rosetta spec ------------------------\ntesting = true\nif testing then\n-- test case 1\ndisplay[[\n/*\n Hello world\n */\nprint(\"Hello, World!\\n\");]]\nprint()\n\n-- test ercase 2\ndisplay[[\n/*\n Show Ident and Integers\n */\nphoenix_number = 142857;\nprint(phoenix_number, \"\\n\");]]\nprint()\n-- etc.\nend\n", "language": "Lua" }, { "code": "-- module basic_token_finder\nlocal M = {} -- only items added to M will be public (via 'return M' at end)\nlocal table, string = table, string\nlocal error, tonumber, select, assert = error, tonumber, select, assert\n\nlocal token_name = require 'token_name'\n_ENV = {}\n\nfunction next_token(line, pos, line_num) -- match a token at line,pos\n local function m(pat)\n from, to, capture = line:find(pat, pos)\n if from then\n pos = to + 1\n return capture\n end\n end\n\n local function ptok(str)\n return {name=token_name[str]}\n end\n\n local function op2c()\n local text = m'^([<>=!]=)' or m'^(&&)' or m'^(||)'\n if text then return ptok(text) end\n end\n\n local function op1c_or_symbol()\n local char = m'^([%*/%%%+%-<>!=%(%){};,])'\n if char then return ptok(char) end\n end\n\n local function keyword_or_identifier()\n local text = m'^([%a_][%w_]*)'\n if text then\n local name = token_name[text]\n return name and {name=name} or {name='Identifier', value=text}\n end\n end\n\n local function integer()\n local text = m'^(%d+)%f[^%w_]'\n if text then return {name='Integer', value=tonumber(text)} end\n end\n\n local subst = {['\\\\\\\\'] = '\\\\', ['\\\\n'] = '\\n'}\n\n local function qchar()\n local text = m\"^'([^\\\\])'\" or m\"^'(\\\\[\\\\n])'\"\n if text then\n local value = #text==1 and text:byte() or subst[text]:byte()\n return {name='Integer', value=value}\n end\n end\n\n local function qstr()\n local text = m'^\"([^\"\\n]*\\\\?)\"'\n if text then\n local value = text:gsub('()(\\\\.?)', function(at, esc)\n local replace = subst[esc]\n if replace then\n return replace\n else\n error{err='bad_escseq', line=line_num, column=pos+at-1}\n end\n end)\n return {name='String', value=value}\n end\n end\n\n local found = (op2c() or op1c_or_symbol() or\n keyword_or_identifier() or integer() or qchar() or qstr())\n if found then\n return found, pos\n end\nend\n\nfunction find_commentrest(line, pos, line_num, socpos)\n local sfrom, sto = line:find('%*%/', pos)\n if sfrom then\n return socpos, sto\n else\n error{err='unfinished_comment', line=line_num, column=socpos}\n end\nend\n\nfunction find_comment(line, pos, line_num)\n local sfrom, sto = line:find('^%/%*', pos)\n if sfrom then\n local efrom, eto = find_commentrest(line, sto+1, line_num, sfrom)\n return sfrom, eto\n end\nend\n\nfunction find_morecomment(line, pos, line_num)\n assert(pos==1)\n return find_commentrest(line, pos, line_num, pos)\nend\n\nfunction find_whitespace(line, pos, line_num)\n local spos = pos\n repeat\n local eto = select(2, line:find('^%s+', pos))\n if not eto then\n eto = select(2, find_comment(line, pos, line_num))\n end\n if eto then pos = eto + 1 end\n until not eto\n return spos, pos - 1\nend\n\nfunction M.find_token(line, pos, line_num, in_comment)\n local spos = pos\n if in_comment then\n pos = 1 + select(2, find_morecomment(line, pos, line_num))\n end\n pos = 1 + select(2, find_whitespace(line, pos, line_num))\n if pos > #line then\n return nil\n else\n local token, nextpos = next_token(line, pos, line_num)\n if token then\n token.line, token.column = line_num, pos\n return token, nextpos\n else\n error{err='invalid_token', line=line_num, column=pos}\n end\n end\nend\n\n-- M._ENV = _ENV\nreturn M\n", "language": "Lua" }, { "code": "Module lexical_analyzer {\n\ta$={/*\n\t All lexical tokens - not syntactically correct, but that will\n\t have to wait until syntax analysis\n\t */\n\t/* Print */ print /* Sub */ -\n\t/* Putc */ putc /* Lss */ <\n\t/* If */ if /* Gtr */ >\n\t/* Else */ else /* Leq */ <=\n\t/* While */ while /* Geq */ >=\n\t/* Lbrace */ { /* Eq */ ==\n\t/* Rbrace */ } /* Neq */ !=\n\t/* Lparen */ ( /* And */ &&\n\t/* Rparen */ ) /* Or */ ||\n\t/* Uminus */ - /* Semi */ ;\n\t/* Not */ ! /* Comma */ ,\n\t/* Mul */ * /* Assign */ =\n\t/* Div */ / /* Integer */ 42\n\t/* Mod */ % /* String */ \"String literal\"\n\t/* Add */ + /* Ident */ variable_name\n\t/* character literal */ '\\n'\n\t/* character literal */ '\\\\'\n\t/* character literal */ ' '\n\t}\n\tlim=Len(a$)\n\tLineNo=1\n\tColumnNo=1\n\tDocument Output$\n\tBuffer Scanner as Integer*lim\n\tReturn Scanner, 0:=a$\n\toffset=0\n\tbuffer1$=\"\"\n\tflag_rem=true\n\tAhead=lambda Scanner (a$, offset)->{\n\t\t=false\n\t\tTry {\n\t\t\t\\\\ second parameter is the offset in buffer units\n\t\t\t\\\\ third parameter is length in bytes\n\t\t\t=Eval$(Scanner, offset,2*len(a$))=a$\n\t\t}\n\t}\n\tAhead2=lambda Scanner (a$, offset)->{\n\t\t=false\n\t\tTry {\n\t\t\t=Eval$(Scanner, offset,2) ~ a$\n\t\t}\n\t}\n\tconst nl$=chr$(13)+chr$(10), quo$=\"\"\"\", er$=\"@\", Ansi=3\n\tTry {\n\t\tDo\n\t\tIf Ahead(\"/*\", offset) Then {\n\t\t\toffset+=2 : \tColumnNo+=2\n\t\t\tWhile not Ahead(\"*/\", offset)\n\t\t\t\tIf Ahead(nl$, offset) Then\n\t\t\t\t\tlineNo++: ColumnNo=1 : offset+=2\n\t\t\t\tElse\n\t\t\t\t\toffset++ : ColumnNo++\n\t\t\t\tEnd If\n\t\t\t\tif offset>lim then\n\t\t\t\t\tError \"End-of-file in comment. Closing comment characters not found\"+er$\n\t\t\t\tEnd if\n\t\t\tEnd While\n\t\t\toffset+=2 : ColumnNo+=2\n\t\t} Else.if Ahead(nl$, offset) Then{\n\t\t\tLineNo++: ColumnNo=1\n\t\t\toffset+=2\n\t\t} Else.if Ahead(quo$, offset) Then {\n\t\t\tOutput$=format$(\"{0::-10}{1::-10} \", LineNo, ColumnNo)\n\t\t\toffset++ : ColumnNo++\n\t\t\tstrin=offset\n\t\t\tWhile not Ahead(quo$, offset)\n\t\t\t\tIf Ahead(\"/\", offset) Then\n\t\t\t\t\toffset+=2 : ColumnNo+=2\n\t\t\t\telse\n\t\t\t\t\toffset++ : ColumnNo++\n\t\t\t\tEnd if\n\t\t\t\tcheckerror()\n\t\t\tEnd While\n\t\t\tOutput$=\"String \"+quote$(Eval$(Scanner, strin, (offset-strin)*2))+nl$\n\t\t\toffset++ : ColumnNo++\n\t\t} Else.if Ahead(\"'\", offset) Then {\n\t\t\tOutput$=format$(\"{0::-10}{1::-10} \", LineNo, ColumnNo)\n\t\t\toffset++ : ColumnNo++\n\t\t\tstrin=offset\n\t\t\tWhile not Ahead(\"'\", offset)\n\t\t\t\tIf Ahead(\"/\", offset) Then\n\t\t\t\t\toffset+=2 : ColumnNo+=2\n\t\t\t\telse\n\t\t\t\t\toffset++ : ColumnNo++\n\t\t\t\tEnd if\n\t\t\t\tcheckerror()\n\t\t\tEnd While\n\t\t\tlit$=format$(Eval$(Scanner, strin, (offset-strin)*2))\n\t\t\tselect case len(lit$)\n\t\t\tcase 1\n\t\t\t\tOutput$=\"Integer \"+str$(asc(lit$),0)+nl$\n\t\t\tcase >1\n\t\t\t\t{Error \"Multi-character constant.\"+er$}\n\t\t\tcase 0\n\t\t\t\t{Error \"Empty character constant.\"+er$}\n\t\t\tend select\n\t\t\toffset++ : ColumnNo++\n\t\t} Else.if Ahead2(\"[a-z]\", offset) Then {\n\t\t\tstrin=offset\n\t\t\tOutput$=format$(\"{0::-10}{1::-10} \", LineNo, ColumnNo)\n\t\t\toffset++ : ColumnNo++\n\t\t\tWhile Ahead2(\"[a-zA-Z0-9_]\", offset)\n\t\t\t\t\toffset++ : ColumnNo++\n\t\t\tEnd While\n\t\t\tKeywords(Eval$(Scanner, strin, (offset-strin)*2))\n\t\t} Else.if Ahead2(\"[0-9]\", offset) Then {\n\t\t\tstrin=offset\n\t\t\tOutput$=format$(\"{0::-10}{1::-10} Integer \", LineNo, ColumnNo)\n\t\t\toffset++ : ColumnNo++\n\t\t\tWhile Ahead2(\"[0-9]\", offset)\n\t\t\t\t\toffset++ : ColumnNo++\n\t\t\tEnd While\n\t\t\tif Ahead2(\"[a-zA-Z_]\", offset) then\n\t\t\t\t{Error \" Invalid number. Starts like a number, but ends in non-numeric characters.\"+er$}\n\t\t\telse\n\t\t\t\tOutput$=Eval$(Scanner, strin, (offset-strin)*2)+nl$\n\t\t\tend if\n\t\t} Else {\n\t\t\tSymbols(Eval$(Scanner, Offset, 2))\t\t\n\t\t\toffset++ : ColumnNo++\n\t\t}\n\t\tUntil offset>=lim\n\t}\n\ter1$=leftpart$(error$,er$)\n\tif er1$<>\"\" then\n\t\tPrint\n\t\tReport \"Error:\"+er1$\n\t\tOutput$=\"(Error)\"+nl$+\"Error:\"+er1$\n\telse\n\t\tOutput$=format$(\"{0::-10}{1::-10}\", LineNo, ColumnNo)+\" End_of_Input\"+nl$\n\tend if\n\tClipboard Output$\n\tSave.Doc Output$, \"lex.t\", Ansi\n\tdocument lex$\n\tLoad.Doc lex$,\"lex.t\", Ansi\n\tReport lex$\n\t\n\tSub Keywords(a$)\n\t\tselect case a$\n\t\tcase \"if\"\n\t\t\ta$=\"Keyword_if\"\n\t\tcase \"else\"\n\t\t\ta$=\"Keyword_else\"\n\t\tcase \"while\"\n\t\t\ta$=\"Keyword_while\"\n\t\tcase \"print\"\n\t\t\ta$=\"Keyword_print\"\n\t\tcase \"putc\"\n\t\t\ta$=\"Keyword_putc\"\n\t\telse case\n\t\t\ta$=\"Identifier \"+a$\n\t\tend select\n\t\tOutput$=a$+nl$\n\tEnd sub\n\tSub Symbols(a$)\n\t\tselect case a$\n\t\tcase \" \", chr$(9)\n\t\t\ta$=\"\"\n\t\tcase \"(\"\n\t\t\ta$=\"LeftParen\"\n\t\tcase \")\"\n\t\t\ta$=\"RightParen\"\n\t\tcase \"{\"\n\t\t\ta$=\"LeftBrace\"\n\t\tcase \"}\"\n\t\t\ta$=\"RightBrace\"\n\t\tcase \";\"\n\t\t\ta$=\"Semicolon\"\n\t\tcase \",\"\n\t\t\ta$=\"Comma\"\n\t\tcase \"*\"\n\t\t\ta$=\"Op_multiply\"\n\t\tcase \"/\"\n\t\t\ta$=\"Op_divide\"\n\t\tcase \"+\"\n\t\t\ta$=\"Op_add\"\n\t\tcase \"-\"\n\t\t\ta$=\"Op_subtract\"\n\t\tcase \"%\"\n\t\t\ta$=\"Op_mod\"\n\t\tcase \"<\"\n\t\t{\tif Ahead(\"=\", offset+1) Then\n\t\t\t\toffset++\n\t\t\t\ta$=\"Op_lessequal\"\n\t\t\t\tColumnNo++\n\t\t\telse\n\t\t\t\ta$=\"Op_less\"\n\t\t\tend if\n\t\t}\n\t\tcase \">\"\n\t\t{\tif Ahead(\"=\", offset+1) Then\n\t\t\t\toffset++\n\t\t\t\tColumnNo++\n\t\t\t\ta$=\"Op_greaterequal\"\n\t\t\telse\n\t\t\t\ta$=\"Op_greater\"\n\t\t\tend if\n\t\t}\n\t\tcase \"=\"\n\t\t{\tif Ahead(\"=\", offset+1) Then\n\t\t\t\toffset++\n\t\t\t\tColumnNo++\n\t\t\t\ta$=\"Op_equal\"\n\t\t\telse\n\t\t\t\ta$=\"Op_assign\"\n\t\t\tend if\n\t\t}\n\t\tcase \"!\"\n\t\t{\tif Ahead(\"=\", offset+1) Then\n\t\t\t\toffset++\n\t\t\t\tColumnNo++\n\t\t\t\ta$=\"Op_notequal\"\n\t\t\telse\n\t\t\t\ta$=\"Op_not\"\n\t\t\tend if\n\t\t}\n\t\tcase \"&\"\n\t\t{\tif Ahead(\"&\", offset+1) Then\n\t\t\t\toffset++\n\t\t\t\tColumnNo++\n\t\t\t\ta$=\"Op_and\"\n\t\t\telse\n\t\t\t\ta$=\"\"\n\t\t\tend if\n\t\t}\n\t\tcase \"|\"\n\t\t{\tif Ahead(\"|\", offset+1) Then\n\t\t\t\toffset++\n\t\t\t\tColumnNo++\n\t\t\t\ta$=\"Op_or\"\n\t\t\telse\n\t\t\t\ta$=\"\"\n\t\t\tend if\n\t\t}\n\t\telse case\n\t\t\t{Error \"Unrecognized character.\"+er$}\n\t\tend select\n\t\tif a$<>\"\" then\n\t\tOutput$=format$(\"{0::-10}{1::-10} \", LineNo, ColumnNo)+a$+nl$\n\t\tend if\n\tEnd Sub\n\tSub checkerror()\n\t\tif offset>lim then {\n\t\t\tError \"End-of-line while scanning string literal. Closing string character not found before end-of-line.\"+er$\n\t\t} else.if Ahead(nl$,offset) then {\n\t\t\tError \"End-of-file while scanning string literal. Closing string character not found.\"+er$\n\t\t}\n\tEnd Sub\n}\nlexical_analyzer\n", "language": "M2000-Interpreter" }, { "code": "% -*- mercury -*-\n%\n% Compile with maybe something like:\n% mmc -O4 --intermod-opt -E --make --warn-non-tail-recursion self-and-mutual lex\n%\n\n:- module lex.\n\n:- interface.\n:- import_module io.\n:- pred main(io::di, io::uo) is det.\n\n:- implementation.\n:- import_module char.\n:- import_module exception.\n:- import_module int.\n:- import_module list.\n:- import_module stack.\n:- import_module string.\n\n:- type token_t\n ---> token_ELSE\n ; token_IF\n ; token_PRINT\n ; token_PUTC\n ; token_WHILE\n ; token_MULTIPLY\n ; token_DIVIDE\n ; token_MOD\n ; token_ADD\n ; token_SUBTRACT\n ; token_NEGATE\n ; token_LESS\n ; token_LESSEQUAL\n ; token_GREATER\n ; token_GREATEREQUAL\n ; token_EQUAL\n ; token_NOTEQUAL\n ; token_NOT\n ; token_ASSIGN\n ; token_AND\n ; token_OR\n ; token_LEFTPAREN\n ; token_RIGHTPAREN\n ; token_LEFTBRACE\n ; token_RIGHTBRACE\n ; token_SEMICOLON\n ; token_COMMA\n ; token_IDENTIFIER\n ; token_INTEGER\n ; token_STRING\n ; token_END_OF_INPUT.\n\n:- type ch_t % The type of a fetched character.\n ---> {int, % A character or `eof', stored as an int.\n int, % The line number.\n int}. % The column number.\n\n:- type inp_t % The `inputter' type. Fetches one character.\n ---> inp_t(inpf :: text_input_stream,\n line_no :: int,\n column_no :: int,\n pushback :: stack(ch_t)).\n\n:- type toktup_t % The type of a scanned token with its argument.\n ---> {token_t, % The token kind.\n string, % An argument. (May or may not be meaningful.)\n int, % The starting line number.\n int}. % The starting column number.\n\nmain(!IO) :-\n command_line_arguments(Args, !IO),\n (\n if (Args = [])\n then (InpF_filename = \"-\",\n OutF_filename = \"-\",\n main_program(InpF_filename, OutF_filename, !IO))\n else if (Args = [F1])\n then (InpF_filename = F1,\n OutF_filename = \"-\",\n main_program(InpF_filename, OutF_filename, !IO))\n else if (Args = [F1, F2])\n then (InpF_filename = F1,\n OutF_filename = F2,\n main_program(InpF_filename, OutF_filename, !IO))\n else usage_error(!IO)\n ).\n\n:- pred main_program(string::in, string::in, io::di, io::uo) is det.\nmain_program(InpF_filename, OutF_filename, !IO) :-\n open_InpF(InpF, InpF_filename, !IO),\n open_OutF(OutF, OutF_filename, !IO),\n init(InpF, Inp0),\n scan_text(OutF, Inp0, _, !IO).\n\n:- pred open_InpF(text_input_stream::out, string::in,\n io::di, io::uo) is det.\nopen_InpF(InpF, InpF_filename, !IO) :-\n if (InpF_filename = \"-\")\n then (InpF = io.stdin_stream)\n else\n (\n open_input(InpF_filename, InpF_result, !IO),\n (\n if (InpF_result = ok(F))\n then (InpF = F)\n else throw(\"Error: cannot open \" ++ InpF_filename ++\n \" for input\")\n )\n ).\n\n:- pred open_OutF(text_output_stream::out, string::in,\n io::di, io::uo) is det.\nopen_OutF(OutF, OutF_filename, !IO) :-\n if (OutF_filename = \"-\")\n then (OutF = io.stdout_stream)\n else\n (\n open_output(OutF_filename, OutF_result, !IO),\n (\n if (OutF_result = ok(F))\n then (OutF = F)\n else throw(\"Error: cannot open \" ++ OutF_filename ++\n \" for output\")\n )\n ).\n\n:- pred usage_error(io::di, io::uo) is det.\nusage_error(!IO) :-\n progname(\"lex\", ProgName, !IO),\n (io.format(\"Usage: %s [INPUT_FILE [OUTPUT_FILE]]\\n\",\n [s(ProgName)], !IO)),\n (io.write_string(\"If INPUT_FILE is \\\"-\\\" or not present then standard input is used.\\n\",\n !IO)),\n (io.write_string(\"If OUTPUT_FILE is \\\"-\\\" or not present then standard output is used.\\n\",\n !IO)),\n set_exit_status(1, !IO).\n\n:- pred scan_text(text_output_stream::in, inp_t::in, inp_t::out,\n io::di, io::uo) is det.\nscan_text(OutF, !Inp, !IO) :-\n get_next_token(TokTup, !Inp, !IO),\n print_token(TokTup, OutF, !IO),\n {Tok, _, _, _} = TokTup,\n (\n if (Tok = token_END_OF_INPUT)\n then true\n else scan_text(OutF, !Inp, !IO)\n ).\n\n:- pred print_token(toktup_t::in, text_output_stream::in,\n io::di, io::uo) is det.\nprint_token(TokTup, OutF, !IO) :-\n {Tok, Arg, Line_no, Column_no} = TokTup,\n token_name(Tok) = TokName,\n (io.format(OutF, \"%5d %5d %s\",\n [i(Line_no), i(Column_no), s(TokName)],\n !IO)),\n (\n if (Tok = token_IDENTIFIER)\n then (io.format(OutF, \" %s\", [s(Arg)], !IO))\n else if (Tok = token_INTEGER)\n then (io.format(OutF, \" %s\", [s(Arg)], !IO))\n else if (Tok = token_STRING)\n then (io.format(OutF, \" %s\", [s(Arg)], !IO))\n else true\n ),\n (io.format(OutF, \"\\n\", [], !IO)).\n\n:- func token_name(token_t) = string is det.\n:- pred token_name(token_t::in, string::out) is det.\ntoken_name(Tok) = Str :- token_name(Tok, Str).\ntoken_name(token_ELSE, \"Keyword_else\").\ntoken_name(token_IF, \"Keyword_if\").\ntoken_name(token_PRINT, \"Keyword_print\").\ntoken_name(token_PUTC, \"Keyword_putc\").\ntoken_name(token_WHILE, \"Keyword_while\").\ntoken_name(token_MULTIPLY, \"Op_multiply\").\ntoken_name(token_DIVIDE, \"Op_divide\").\ntoken_name(token_MOD, \"Op_mod\").\ntoken_name(token_ADD, \"Op_add\").\ntoken_name(token_SUBTRACT, \"Op_subtract\").\ntoken_name(token_NEGATE, \"Op_negate\").\ntoken_name(token_LESS, \"Op_less\").\ntoken_name(token_LESSEQUAL, \"Op_lessequal\").\ntoken_name(token_GREATER, \"Op_greater\").\ntoken_name(token_GREATEREQUAL, \"Op_greaterequal\").\ntoken_name(token_EQUAL, \"Op_equal\").\ntoken_name(token_NOTEQUAL, \"Op_notequal\").\ntoken_name(token_NOT, \"Op_not\").\ntoken_name(token_ASSIGN, \"Op_assign\").\ntoken_name(token_AND, \"Op_and\").\ntoken_name(token_OR, \"Op_or\").\ntoken_name(token_LEFTPAREN, \"LeftParen\").\ntoken_name(token_RIGHTPAREN, \"RightParen\").\ntoken_name(token_LEFTBRACE, \"LeftBrace\").\ntoken_name(token_RIGHTBRACE, \"RightBrace\").\ntoken_name(token_SEMICOLON, \"Semicolon\").\ntoken_name(token_COMMA, \"Comma\").\ntoken_name(token_IDENTIFIER, \"Identifier\").\ntoken_name(token_INTEGER, \"Integer\").\ntoken_name(token_STRING, \"String\").\ntoken_name(token_END_OF_INPUT, \"End_of_input\").\n\n:- pred get_next_token(toktup_t::out, inp_t::in, inp_t::out,\n io::di, io::uo) is det.\nget_next_token(TokTup, !Inp, !IO) :-\n skip_spaces_and_comments(!Inp, !IO),\n get_ch(Ch, !Inp, !IO),\n {IChar, Line_no, Column_no} = Ch,\n LN = Line_no,\n CN = Column_no,\n (\n if (IChar = eof)\n then\n (\n TokTup = {token_END_OF_INPUT, \"\", LN, CN}\n )\n else\n (\n Char = det_from_int(IChar),\n (\n if (Char = (','))\n then (TokTup = {token_COMMA, \",\", LN, CN})\n else if (Char = (';'))\n then (TokTup = {token_SEMICOLON, \";\", LN, CN})\n else if (Char = ('('))\n then (TokTup = {token_LEFTPAREN, \"(\", LN, CN})\n else if (Char = (')'))\n then (TokTup = {token_RIGHTPAREN, \")\", LN, CN})\n else if (Char = ('{'))\n then (TokTup = {token_LEFTBRACE, \"{\", LN, CN})\n else if (Char = ('}'))\n then (TokTup = {token_RIGHTBRACE, \"}\", LN, CN})\n else if (Char = ('*'))\n then (TokTup = {token_MULTIPLY, \"*\", LN, CN})\n else if (Char = ('/'))\n then (TokTup = {token_DIVIDE, \"/\", LN, CN})\n else if (Char = ('%'))\n then (TokTup = {token_MOD, \"%\", LN, CN})\n else if (Char = ('+'))\n then (TokTup = {token_ADD, \"+\", LN, CN})\n else if (Char = ('-'))\n then (TokTup = {token_SUBTRACT, \"-\", LN, CN})\n else if (Char = ('<'))\n then\n (\n get_ch(Ch1, !Inp, !IO),\n Ch1 = {IChar1, _, _},\n (\n if (IChar1 = to_int('='))\n then\n (\n TokTup = {token_LESSEQUAL, \"<=\", LN, CN}\n )\n else\n (\n push_back(Ch1, !Inp),\n TokTup = {token_LESS, \"<\", LN, CN}\n )\n )\n )\n else if (Char = ('>'))\n then\n (\n get_ch(Ch1, !Inp, !IO),\n Ch1 = {IChar1, _, _},\n (\n if (IChar1 = to_int('='))\n then\n (\n TokTup = {token_GREATEREQUAL, \">=\", LN, CN}\n )\n else\n (\n push_back(Ch1, !Inp),\n TokTup = {token_GREATER, \">\", LN, CN}\n )\n )\n )\n else if (Char = ('='))\n then\n (\n get_ch(Ch1, !Inp, !IO),\n Ch1 = {IChar1, _, _},\n (\n if (IChar1 = to_int('='))\n then\n (\n TokTup = {token_EQUAL, \"==\", LN, CN}\n )\n else\n (\n push_back(Ch1, !Inp),\n TokTup = {token_ASSIGN, \"=\", LN, CN}\n )\n )\n )\n else if (Char = ('!'))\n then\n (\n get_ch(Ch1, !Inp, !IO),\n Ch1 = {IChar1, _, _},\n (\n if (IChar1 = to_int('='))\n then\n (\n TokTup = {token_NOTEQUAL, \"!=\", LN, CN}\n )\n else\n (\n push_back(Ch1, !Inp),\n TokTup = {token_NOT, \"!\", LN, CN}\n )\n )\n )\n else if (Char = ('&'))\n then\n (\n get_ch(Ch1, !Inp, !IO),\n Ch1 = {IChar1, _, _},\n (\n if (IChar1 = to_int('&'))\n then\n (\n TokTup = {token_AND, \"&&\", LN, CN}\n )\n else throw(\"Error: unexpected character '\" ++\n from_char(Char) ++ \"' at \" ++\n from_int(LN) ++ \":\" ++\n from_int(CN))\n )\n )\n else if (Char = ('|'))\n then\n (\n get_ch(Ch1, !Inp, !IO),\n Ch1 = {IChar1, _, _},\n (\n if (IChar1 = to_int('|'))\n then\n (\n TokTup = {token_OR, \"||\", LN, CN}\n )\n else throw(\"Error: unexpected character '\" ++\n from_char(Char) ++ \"' at \" ++\n from_int(LN) ++ \":\" ++\n from_int(CN))\n )\n )\n else if (Char = ('\"'))\n then\n (\n push_back(Ch, !Inp),\n scan_string_literal(TokTup, !Inp, !IO)\n )\n else if (Char = ('\\''))\n then\n (\n push_back(Ch, !Inp),\n scan_character_literal(TokTup, !Inp, !IO)\n )\n else if (is_alpha(Char))\n then\n (\n push_back(Ch, !Inp),\n scan_identifier_or_reserved_word(\n TokTup, !Inp, !IO)\n )\n else if (is_digit(Char))\n then\n (\n push_back(Ch, !Inp),\n scan_integer_literal(TokTup, !Inp, !IO)\n )\n else\n (\n throw(\"Error: unexpected character '\" ++\n from_char(Char) ++ \"' at \" ++\n from_int(LN) ++ \":\" ++\n from_int(CN))\n )\n )\n )\n ).\n\n\n:- pred skip_spaces_and_comments(inp_t::in, inp_t::out,\n io::di, io::uo) is det.\nskip_spaces_and_comments(!Inp, !IO) :-\n get_ch(Ch, !Inp, !IO),\n Ch = {IChar, _, _},\n (\n if (IChar = eof)\n then push_back(Ch, !Inp)\n else\n if (is_whitespace(det_from_int(IChar)))\n then skip_spaces_and_comments(!Inp, !IO)\n else if (IChar = to_int('/'))\n then\n (\n get_ch(Ch1, !Inp, !IO),\n Ch1 = {IChar1, Line_no, Column_no},\n (\n if (IChar1 = to_int('*'))\n then\n (\n scan_comment(Line_no, Column_no,\n !Inp, !IO),\n skip_spaces_and_comments(!Inp, !IO)\n )\n else\n (\n push_back(Ch1, !Inp),\n push_back(Ch, !Inp)\n )\n )\n )\n else push_back(Ch, !Inp)\n ).\n\n:- pred scan_comment(int::in, int::in, % line and column nos.\n inp_t::in, inp_t::out,\n io::di, io::uo) is det.\nscan_comment(Line_no, Column_no, !Inp, !IO) :-\n get_ch(Ch, !Inp, !IO),\n {IChar, _, _} = Ch,\n (\n if (IChar = eof)\n then throw(\"Error: unterminated comment \" ++\n \"starting at \" ++ from_int(Line_no) ++ \":\" ++\n from_int(Column_no))\n else\n (\n det_from_int(IChar) = Char,\n (\n if (Char = ('*'))\n then\n (\n get_ch(Ch1, !Inp, !IO),\n {IChar1, _, _} = Ch1,\n (\n if (IChar1 = to_int('/'))\n then true % End of comment has been reached.\n else\n (\n push_back(Ch1, !Inp),\n scan_comment(Line_no, Column_no, !Inp,\n !IO)\n )\n )\n )\n else scan_comment(Line_no, Column_no, !Inp, !IO)\n )\n )\n ).\n\n:- pred scan_character_literal(toktup_t::out,\n inp_t::in, inp_t::out,\n io::di, io::uo) is det.\nscan_character_literal(TokTup, !Inp, !IO) :-\n get_ch(Ch, !Inp, !IO),\n Ch = {OpenQuote, Line_no, Column_no},\n CloseQuote = OpenQuote,\n scan_char_lit_contents(CodePoint, Line_no, Column_no,\n !Inp, !IO),\n check_char_lit_end(CloseQuote, Line_no, Column_no, !Inp, !IO),\n Arg = from_int(CodePoint),\n TokTup = {token_INTEGER, Arg, Line_no, Column_no}.\n\n:- pred scan_char_lit_contents(int::out, int::in, int::in,\n inp_t::in, inp_t::out,\n io::di, io::uo) is det.\nscan_char_lit_contents(CodePoint, Line_no, Column_no,\n !Inp, !IO) :-\n get_ch(Ch1, !Inp, !IO),\n Ch1 = {IChar1, Line_no1, Column_no1},\n (\n if (IChar1 = eof)\n then throw(\"Error: end of input in character literal \" ++\n \"starting at \" ++ from_int(Line_no) ++ \":\" ++\n from_int(Column_no))\n else if (IChar1 = to_int('\\\\'))\n then\n (\n get_ch(Ch2, !Inp, !IO),\n Ch2 = {IChar2, _, _},\n (if (IChar2 = eof)\n then throw(\"Error: end of input in character literal \" ++\n \"starting at \" ++ from_int(Line_no) ++ \":\" ++\n from_int(Column_no))\n else if (IChar2 = to_int('n'))\n then (CodePoint = to_int('\\n'))\n else if (IChar2 = to_int('\\\\'))\n then (CodePoint = to_int('\\\\'))\n else throw(\"Error: unsupported escape \\\\\" ++\n from_char(det_from_int(IChar2)) ++\n \" at \" ++ from_int(Line_no1) ++\n \":\" ++ from_int(Column_no1))\n )\n )\n else (CodePoint = IChar1)\n ).\n\n:- pred check_char_lit_end(int::in, int::in, int::in,\n inp_t::in, inp_t::out,\n io::di, io::uo) is det.\ncheck_char_lit_end(CloseQuote, Line_no, Column_no, !Inp, !IO) :-\n get_ch(Ch1, !Inp, !IO),\n Ch1 = {IChar1, _, _},\n (\n if (IChar1 = CloseQuote)\n then true\n else find_bad_char_lit_end(CloseQuote, Line_no, Column_no,\n !Inp, !IO)\n ).\n\n:- pred find_bad_char_lit_end(int::in, int::in, int::in,\n inp_t::in, inp_t::out,\n io::di, io::uo) is det.\nfind_bad_char_lit_end(CloseQuote, Line_no, Column_no, !Inp, !IO) :-\n get_ch(Ch2, !Inp, !IO),\n Ch2 = {IChar2, _, _},\n (\n if (IChar2 = CloseQuote)\n then throw(\"Error: unsupported multicharacter literal \" ++\n \" at \" ++ from_int(Line_no) ++ \":\" ++\n from_int(Column_no))\n else if (IChar2 = eof)\n then throw(\"Error: end of input in character literal \" ++\n \" at \" ++ from_int(Line_no) ++ \":\" ++\n from_int(Column_no))\n else find_bad_char_lit_end(CloseQuote, Line_no, Column_no,\n !Inp, !IO)\n ).\n\n:- pred scan_string_literal(toktup_t::out,\n inp_t::in, inp_t::out,\n io::di, io::uo) is det.\nscan_string_literal(TokTup, !Inp, !IO) :-\n get_ch(Ch, !Inp, !IO),\n Ch = {OpenQuote, Line_no, Column_no},\n CloseQuote = OpenQuote,\n scan_string_lit_contents(\"\", Str, CloseQuote,\n Line_no, Column_no,\n !Inp, !IO),\n Arg = from_char(det_from_int(OpenQuote)) ++\n Str ++ from_char(det_from_int(CloseQuote)),\n TokTup = {token_STRING, Arg, Line_no, Column_no}.\n\n:- pred scan_string_lit_contents(string::in, string::out, int::in,\n int::in, int::in,\n inp_t::in, inp_t::out,\n io::di, io::uo) is det.\nscan_string_lit_contents(Str0, Str, CloseQuote, Line_no, Column_no,\n !Inp, !IO) :-\n get_ch(Ch1, !Inp, !IO),\n Ch1 = {IChar1, Line_no1, Column_no1},\n (\n if (IChar1 = CloseQuote)\n then (Str = Str0)\n else if (IChar1 = eof)\n then throw(\"Error: end of input in string literal \" ++\n \"starting at \" ++ from_int(Line_no) ++ \":\" ++\n from_int(Column_no))\n else if (IChar1 = to_int('\\n'))\n then throw(\"Error: end of line in string literal \" ++\n \"starting at \" ++ from_int(Line_no) ++ \":\" ++\n from_int(Column_no))\n else if (IChar1 = to_int('\\\\'))\n then\n (\n get_ch(Ch2, !Inp, !IO),\n Ch2 = {IChar2, _, _},\n (\n if (IChar2 = to_int('n'))\n then\n (\n Str1 = Str0 ++ \"\\\\n\",\n scan_string_lit_contents(Str1, Str, CloseQuote,\n Line_no, Column_no,\n !Inp, !IO)\n )\n else if (IChar2 = to_int('\\\\'))\n then\n (\n Str1 = Str0 ++ \"\\\\\\\\\",\n scan_string_lit_contents(Str1, Str, CloseQuote,\n Line_no, Column_no,\n !Inp, !IO)\n )\n else if (IChar2 = eof)\n then throw(\"Error: end of input in string literal \" ++\n \"starting at \" ++ from_int(Line_no) ++\n \":\" ++ from_int(Column_no))\n else if (IChar2 = to_int('\\n'))\n then throw(\"Error: end of line in string literal \" ++\n \"starting at \" ++ from_int(Line_no) ++\n \":\" ++ from_int(Column_no))\n else throw(\"Error: unsupported escape \\\\\" ++\n from_char(det_from_int(IChar2)) ++\n \" at \" ++ from_int(Line_no1) ++\n \":\" ++ from_int(Column_no1))\n )\n )\n else\n (\n Char1 = det_from_int(IChar1),\n Str1 = Str0 ++ from_char(Char1),\n scan_string_lit_contents(Str1, Str, CloseQuote,\n Line_no, Column_no, !Inp, !IO)\n )\n ).\n\n:- pred scan_identifier_or_reserved_word(toktup_t::out,\n inp_t::in, inp_t::out,\n io::di, io::uo) is det.\nscan_identifier_or_reserved_word(TokTup, !Inp, !IO) :-\n scan_integer_or_word(Str, Line_no, Column_no, !Inp, !IO),\n (\n if (Str = \"if\")\n then (TokTup = {token_IF, Str, Line_no, Column_no})\n else if (Str = \"else\")\n then (TokTup = {token_ELSE, Str, Line_no, Column_no})\n else if (Str = \"while\")\n then (TokTup = {token_WHILE, Str, Line_no, Column_no})\n else if (Str = \"print\")\n then (TokTup = {token_PRINT, Str, Line_no, Column_no})\n else if (Str = \"putc\")\n then (TokTup = {token_PUTC, Str, Line_no, Column_no})\n else (TokTup = {token_IDENTIFIER, Str, Line_no, Column_no})\n ).\n\n:- pred scan_integer_literal(toktup_t::out, inp_t::in, inp_t::out,\n io::di, io::uo) is det.\nscan_integer_literal(TokTup, !Inp, !IO) :-\n scan_integer_or_word(Str, Line_no, Column_no, !Inp, !IO),\n (\n if (not is_all_digits(Str))\n then throw(\"Error: not a valid integer literal: \" ++ Str)\n else (TokTup = {token_INTEGER, Str, Line_no, Column_no})\n ).\n\n:- pred scan_integer_or_word(string::out, int::out, int::out,\n inp_t::in, inp_t::out,\n io::di, io::uo) is det.\nscan_integer_or_word(Str, Line_no, Column_no, !Inp, !IO) :-\n get_ch({IChar, Line_no, Column_no}, !Inp, !IO),\n (\n if (IChar = eof)\n then throw(\"internal error\")\n else\n (\n Char = det_from_int(IChar),\n (if (not is_alnum_or_underscore(Char))\n then throw(\"internal error\")\n else scan_int_or_word(from_char(Char), Str, !Inp, !IO))\n )\n ).\n\n:- pred scan_int_or_word(string::in, string::out,\n inp_t::in, inp_t::out,\n io::di, io::uo) is det.\nscan_int_or_word(Str0, Str, !Inp, !IO) :-\n get_ch(CharTup, !Inp, !IO),\n {IChar, _, _} = CharTup,\n (\n if (IChar = eof)\n then\n (\n push_back(CharTup, !Inp),\n Str = Str0\n )\n else\n (\n Char = det_from_int(IChar),\n (\n if (not is_alnum_or_underscore(Char))\n then\n (\n push_back(CharTup, !Inp),\n Str = Str0\n )\n else scan_int_or_word(Str0 ++ from_char(Char), Str,\n !Inp, !IO)\n )\n )\n ).\n\n:- pred init(text_input_stream::in, inp_t::out) is det.\ninit(Inpf, Inp) :-\n Inp = inp_t(Inpf, 1, 1, init).\n\n\n:- pred get_ch(ch_t::out, inp_t::in, inp_t::out,\n io::di, io::uo) is det.\nget_ch(Ch, Inp0, Inp, !IO) :-\n if (pop(Ch1, Inp0^pushback, Pushback))\n then\n (\n Ch = Ch1,\n Inp = (Inp0^pushback := Pushback)\n )\n else\n (\n inp_t(Inpf, Line_no, Column_no, Pushback) = Inp0,\n read_char_unboxed(Inpf, Result, Char, !IO),\n (\n if (Result = ok)\n then\n (\n Ch = {to_int(Char), Line_no, Column_no},\n Inp =\n (if (Char = ('\\n'))\n then inp_t(Inpf, Line_no + 1, 1, Pushback)\n else inp_t(Inpf, Line_no, Column_no + 1, Pushback))\n )\n else\n (\n Ch = {eof, Line_no, Column_no},\n Inp = Inp0\n )\n )\n ).\n\n:- pred push_back(ch_t::in, inp_t::in, inp_t::out) is det.\npush_back(Ch, Inp0, Inp) :-\n Inp = (Inp0^pushback := push(Inp0^pushback, Ch)).\n\n:- func eof = int is det.\neof = -1.\n", "language": "Mercury" }, { "code": "import re, strformat, strutils\n\ntype\n TokenKind = enum\n tkUnknown = \"UNKNOWN_TOKEN\",\n tkMul = \"Op_multiply\",\n tkDiv = \"Op_divide\",\n tkMod = \"Op_mod\",\n tkAdd = \"Op_add\",\n tkSub = \"Op_subtract\",\n tkNeg = \"Op_negate\",\n tkLt = \"Op_less\",\n tkLte = \"Op_lessequal\",\n tkGt = \"Op_greater\",\n tkGte = \"Op_greaterequal\",\n tkEq = \"Op_equal\",\n tkNeq = \"Op_notequal\",\n tkNot = \"Op_not\",\n tkAsgn = \"Op_assign\",\n tkAnd = \"Op_and\",\n tkOr = \"Op_or\",\n tkLpar = \"LeftParen\",\n tkRpar = \"RightParen\",\n tkLbra = \"LeftBrace\",\n tkRbra = \"RightBrace\",\n tkSmc = \"Semicolon\",\n tkCom = \"Comma\",\n tkIf = \"Keyword_if\",\n tkElse = \"Keyword_else\",\n tkWhile = \"Keyword_while\",\n tkPrint = \"Keyword_print\",\n tkPutc = \"Keyword_putc\",\n tkId = \"Identifier\",\n tkInt = \"Integer\",\n tkChar = \"Integer\",\n tkStr = \"String\",\n tkEof = \"End_of_input\"\n\n Token = object\n kind: TokenKind\n value: string\n\n TokenAnn = object\n ## Annotated token with messages for compiler\n token: Token\n line, column: int\n\nproc getSymbols(table: openArray[(char, TokenKind)]): seq[char] =\n result = newSeq[char]()\n for ch, tokenKind in items(table):\n result.add ch\n\nconst\n tkSymbols = { # single-char tokens\n '*': tkMul,\n '%': tkMod,\n '+': tkAdd,\n '-': tkSub,\n '(': tkLpar,\n ')': tkRpar,\n '{': tkLbra,\n '}': tkRbra,\n ';': tkSmc,\n ',': tkCom,\n '/': tkDiv, # the comment case /* ... */ is handled in `stripUnimportant`\n }\n symbols = getSymbols(tkSymbols)\n\nproc findTokenKind(table: openArray[(char, TokenKind)]; needle: char):\n TokenKind =\n for ch, tokenKind in items(table):\n if ch == needle: return tokenKind\n tkUnknown\n\nproc stripComment(text: var string, lineNo, colNo: var int) =\n var matches: array[1, string]\n\n if match(text, re\"\\A(/\\*[\\s\\S]*?\\*/)\", matches):\n text = text[matches[0].len..^1]\n for s in matches[0]:\n if s == '\\n':\n inc lineNo\n colNo = 1\n else:\n inc colNo\n\nproc stripUnimportant(text: var string; lineNo, colNo: var int) =\n while true:\n if text.len == 0: return\n elif text[0] == '\\n':\n inc lineNo\n colNo = 1\n text = text[1..^1]\n elif text[0] == ' ':\n inc colNo\n text = text[1..^1]\n elif text.len >= 2 and text[0] == '/' and text[1] == '*':\n stripComment(text, lineNo, colNo)\n else: return\n\nproc lookAhead(ch1, ch2: char, tk1, tk2: TokenKind): (TokenKind, int) =\n if ch1 == ch2: (tk1, 2)\n else: (tk2, 1)\n\nproc consumeToken(text: var string; tkl: var int): Token =\n ## Return token removing it from the `text` and write its length to\n ## `tkl`. If the token can not be defined, return `tkUnknown` as a\n ## token, shrink text by 1 and write 1 to its length.\n\n var\n matches: array[1, string]\n tKind: TokenKind\n val: string\n\n if text.len == 0:\n (tKind, tkl) = (tkEof, 0)\n\n # Simple characters\n elif text[0] in symbols: (tKind, tkl) = (tkSymbols.findTokenKind(text[0]), 1)\n elif text[0] == '<': (tKind, tkl) = lookAhead(text[1], '=', tkLte, tkLt)\n elif text[0] == '>': (tKind, tkl) = lookAhead(text[1], '=', tkGte, tkGt)\n elif text[0] == '=': (tKind, tkl) = lookAhead(text[1], '=', tkEq, tkAsgn)\n elif text[0] == '!': (tKind, tkl) = lookAhead(text[1], '=', tkNeq, tkNot)\n elif text[0] == '&': (tKind, tkl) = lookAhead(text[1], '&', tkAnd, tkUnknown)\n elif text[0] == '|': (tKind, tkl) = lookAhead(text[1], '|', tkOr, tkUnknown)\n\n # Keywords\n elif match(text, re\"\\Aif\\b\"): (tKind, tkl) = (tkIf, 2)\n elif match(text, re\"\\Aelse\\b\"): (tKind, tkl) = (tkElse, 4)\n elif match(text, re\"\\Awhile\\b\"): (tKind, tkl) = (tkWhile, 5)\n elif match(text, re\"\\Aprint\\b\"): (tKind, tkl) = (tkPrint, 5)\n elif match(text, re\"\\Aputc\\b\"): (tKind, tkl) = (tkPutc, 4)\n\n # Literals and identifiers\n elif match(text, re\"\\A([0-9]+)\", matches):\n (tKind, tkl) = (tkInt, matches[0].len)\n val = matches[0]\n elif match(text, re\"\\A([_a-zA-Z][_a-zA-Z0-9]*)\", matches):\n (tKind, tkl) = (tkId, matches[0].len)\n val = matches[0]\n elif match(text, re\"\\A('(?:[^'\\n]|\\\\\\\\|\\\\n)')\", matches):\n (tKind, tkl) = (tkChar, matches[0].len)\n val = case matches[0]\n of r\"' '\": $ord(' ')\n of r\"'\\n'\": $ord('\\n')\n of r\"'\\\\'\": $ord('\\\\')\n else: $ord(matches[0][1]) # \"'a'\"[1] == 'a'\n elif match(text, re\"\\A(\"\"[^\"\"\\n]*\"\")\", matches):\n (tKind, tkl) = (tkStr, matches[0].len)\n val = matches[0]\n else: (tKind, tkl) = (tkUnknown, 1)\n\n text = text[tkl..^1]\n Token(kind: tKind, value: val)\n\nproc tokenize*(text: string): seq[TokenAnn] =\n result = newSeq[TokenAnn]()\n var\n lineNo, colNo: int = 1\n text = text\n token: Token\n tokenLength: int\n\n while text.len > 0:\n stripUnimportant(text, lineNo, colNo)\n token = consumeToken(text, tokenLength)\n result.add TokenAnn(token: token, line: lineNo, column: colNo)\n inc colNo, tokenLength\n\nproc output*(s: seq[TokenAnn]): string =\n var\n tokenKind: TokenKind\n value: string\n line, column: int\n\n for tokenAnn in items(s):\n line = tokenAnn.line\n column = tokenAnn.column\n tokenKind = tokenAnn.token.kind\n value = tokenAnn.token.value\n result.add(\n fmt\"{line:>5}{column:>7} {tokenKind:<15}{value}\"\n .strip(leading = false) & \"\\n\")\n\nwhen isMainModule:\n import os\n\n let input = if paramCount() > 0: readFile paramStr(1)\n else: readAll stdin\n\n echo input.tokenize.output\n", "language": "Nim" }, { "code": "import lexbase, streams\nfrom strutils import Whitespace\n\ntype\n TokenKind = enum\n tkInvalid = \"Invalid\",\n tkOpMultiply = \"Op_multiply\",\n tkOpDivide = \"Op_divide\",\n tkOpMod = \"Op_mod\",\n tkOpAdd = \"Op_add\",\n tkOpSubtract = \"Op_subtract\",\n tkOpLess = \"Op_less\",\n tkOpLessEqual = \"Op_lessequal\",\n tkOpGreater = \"Op_greater\",\n tkOpGreaterEqual = \"Op_greaterequal\",\n tkOpEqual = \"Op_equal\",\n tkOpNotEqual = \"Op_notequal\",\n tkOpNot = \"Op_not\",\n tkOpAssign = \"Op_assign\",\n tkOpAnd = \"Op_and\",\n tkOpOr = \"Op_or\",\n tkLeftParen = \"LeftParen\",\n tkRightParen = \"RightParen\",\n tkLeftBrace = \"LeftBrace\",\n tkRightBrace = \"RightBrace\",\n tkSemicolon = \"Semicolon\",\n tkComma = \"Comma\",\n tkKeywordIf = \"Keyword_if\",\n tkKeywordElse = \"Keyword_else\",\n tkKeywordWhile = \"Keyword_while\",\n tkKeywordPrint = \"Keyword_print\",\n tkKeywordPutc = \"Keyword_putc\",\n tkIdentifier = \"Identifier\",\n tkInteger = \"Integer\",\n tkString = \"String\",\n tkEndOfInput = \"End_of_input\"\n\n Lexer = object of BaseLexer\n kind: TokenKind\n token, error: string\n startPos: int\n\ntemplate setError(l: var Lexer; err: string): untyped =\n l.kind = tkInvalid\n if l.error.len == 0:\n l.error = err\n\nproc hasError(l: Lexer): bool {.inline.} =\n l.error.len > 0\n\nproc open(l: var Lexer; input: Stream) {.inline.} =\n lexbase.open(l, input)\n l.startPos = 0\n l.kind = tkInvalid\n l.token = \"\"\n l.error = \"\"\n\nproc handleNewLine(l: var Lexer) =\n case l.buf[l.bufpos]\n of '\\c': l.bufpos = l.handleCR l.bufpos\n of '\\n': l.bufpos = l.handleLF l.bufpos\n else: discard\n\nproc skip(l: var Lexer) =\n while true:\n case l.buf[l.bufpos]\n of Whitespace:\n if l.buf[l.bufpos] notin NewLines:\n inc l.bufpos\n else:\n handleNewLine l\n of '/':\n if l.buf[l.bufpos + 1] == '*':\n inc l.bufpos, 2\n while true:\n case l.buf[l.bufpos]\n of '*':\n if l.buf[l.bufpos + 1] == '/':\n inc l.bufpos, 2\n break\n else: inc l.bufpos\n of NewLines:\n handleNewLine l\n of EndOfFile:\n setError l, \"EOF reached in comment\"\n return\n else:\n inc l.bufpos\n else: break\n else: break\n\nproc handleSpecial(l: var Lexer): char =\n assert l.buf[l.bufpos] == '\\\\'\n inc l.bufpos\n case l.buf[l.bufpos]\n of 'n':\n l.token.add \"\\\\n\"\n result = '\\n'\n inc l.bufpos\n of '\\\\':\n l.token.add \"\\\\\\\\\"\n result = '\\\\'\n inc l.bufpos\n else:\n setError l, \"Unknown escape sequence: '\\\\\" & l.buf[l.bufpos] & \"'\"\n result = '\\0'\n\nproc handleChar(l: var Lexer) =\n assert l.buf[l.bufpos] == '\\''\n l.startPos = l.getColNumber l.bufpos\n l.kind = tkInvalid\n inc l.bufpos\n if l.buf[l.bufpos] == '\\\\':\n l.token = $ord(handleSpecial l)\n if hasError l: return\n elif l.buf[l.bufpos] == '\\'':\n setError l, \"Empty character constant\"\n return\n else:\n l.token = $ord(l.buf[l.bufpos])\n inc l.bufpos\n if l.buf[l.bufpos] == '\\'':\n l.kind = tkInteger\n inc l.bufpos\n else:\n setError l, \"Multi-character constant\"\n\nproc handleString(l: var Lexer) =\n assert l.buf[l.bufpos] == '\"'\n l.startPos = l.getColNumber l.bufpos\n l.token = \"\\\"\"\n inc l.bufpos\n while true:\n case l.buf[l.bufpos]\n of '\\\\':\n discard handleSpecial l\n if hasError l: return\n of '\"':\n l.kind = tkString\n add l.token, '\"'\n inc l.bufpos\n break\n of NewLines:\n setError l, \"EOL reached before end-of-string\"\n return\n of EndOfFile:\n setError l, \"EOF reached before end-of-string\"\n return\n else:\n add l.token, l.buf[l.bufpos]\n inc l.bufpos\n\nproc handleNumber(l: var Lexer) =\n assert l.buf[l.bufpos] in {'0'..'9'}\n l.startPos = l.getColNumber l.bufpos\n l.token = \"0\"\n while l.buf[l.bufpos] == '0': inc l.bufpos\n while true:\n case l.buf[l.bufpos]\n of '0'..'9':\n if l.token == \"0\":\n setLen l.token, 0\n add l.token, l.buf[l.bufpos]\n inc l.bufpos\n of 'a'..'z', 'A'..'Z', '_':\n setError l, \"Invalid number\"\n return\n else:\n l.kind = tkInteger\n break\n\nproc handleIdent(l: var Lexer) =\n assert l.buf[l.bufpos] in {'a'..'z'}\n l.startPos = l.getColNumber l.bufpos\n setLen l.token, 0\n while true:\n if l.buf[l.bufpos] in {'a'..'z', 'A'..'Z', '0'..'9', '_'}:\n add l.token, l.buf[l.bufpos]\n inc l.bufpos\n else:\n break\n l.kind = case l.token\n of \"if\": tkKeywordIf\n of \"else\": tkKeywordElse\n of \"while\": tkKeywordWhile\n of \"print\": tkKeywordPrint\n of \"putc\": tkKeywordPutc\n else: tkIdentifier\n\nproc getToken(l: var Lexer): TokenKind =\n l.kind = tkInvalid\n setLen l.token, 0\n skip l\n\n case l.buf[l.bufpos]\n of '*':\n l.kind = tkOpMultiply\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n of '/':\n l.kind = tkOpDivide\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n of '%':\n l.kind = tkOpMod\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n of '+':\n l.kind = tkOpAdd\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n of '-':\n l.kind = tkOpSubtract\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n of '<':\n l.kind = tkOpLess\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n if l.buf[l.bufpos] == '=':\n l.kind = tkOpLessEqual\n inc l.bufpos\n of '>':\n l.kind = tkOpGreater\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n if l.buf[l.bufpos] == '=':\n l.kind = tkOpGreaterEqual\n inc l.bufpos\n of '=':\n l.kind = tkOpAssign\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n if l.buf[l.bufpos] == '=':\n l.kind = tkOpEqual\n inc l.bufpos\n of '!':\n l.kind = tkOpNot\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n if l.buf[l.bufpos] == '=':\n l.kind = tkOpNotEqual\n inc l.bufpos\n of '&':\n if l.buf[l.bufpos + 1] == '&':\n l.kind = tkOpAnd\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos, 2\n else:\n setError l, \"Unrecognized character\"\n of '|':\n if l.buf[l.bufpos + 1] == '|':\n l.kind = tkOpOr\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos, 2\n else:\n setError l, \"Unrecognized character\"\n of '(':\n l.kind = tkLeftParen\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n of ')':\n l.kind = tkRightParen\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n of '{':\n l.kind = tkLeftBrace\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n of '}':\n l.kind = tkRightBrace\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n of ';':\n l.kind = tkSemicolon\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n of ',':\n l.kind = tkComma\n l.startPos = l.getColNumber l.bufpos\n inc l.bufpos\n of '\\'': handleChar l\n of '\"': handleString l\n of '0'..'9': handleNumber l\n of 'a'..'z', 'A'..'Z': handleIdent l\n of EndOfFile:\n l.startPos = l.getColNumber l.bufpos\n l.kind = tkEndOfInput\n else:\n setError l, \"Unrecognized character\"\n result = l.kind\n\nwhen isMainModule:\n import os, strformat\n proc main() =\n var l: Lexer\n if paramCount() < 1:\n open l, newFileStream stdin\n else:\n open l, newFileStream paramStr(1)\n while l.getToken notin {tkInvalid}:\n stdout.write &\"{l.lineNumber:5} {l.startPos + 1:5} {l.kind:<14}\"\n if l.kind in {tkIdentifier, tkInteger, tkString}:\n stdout.write &\" {l.token}\"\n stdout.write '\\n'\n if l.kind == tkEndOfInput:\n break\n if hasError l:\n echo &\"({l.lineNumber},{l.getColNumber l.bufpos + 1}) {l.error}\"\n main()\n", "language": "Nim" }, { "code": "import strutils\n\ntype\n\n TokenKind* = enum\n tokMult = \"Op_multiply\", tokDiv = \"Op_divide\", tokMod = \"Op_mod\",\n tokAdd = \"Op_add\", tokSub = \"Op_subtract\", tokLess = \"Op_less\",\n tokLessEq = \"Op_lessequal\", tokGreater = \"Op_greater\",\n tokGreaterEq = \"Op_greaterequal\", tokEq = \"Op_equal\",\n tokNotEq = \"Op_notequal\", tokNot = \"Op_not\", tokAssign = \"Op_assign\",\n tokAnd = \"Op_and\", tokOr = \"Op_or\"\n tokLPar = \"LeftParen\", tokRPar = \"RightParen\"\n tokLBrace = \"LeftBrace\", tokRBrace = \"RightBrace\"\n tokSemi = \"Semicolon\", tokComma = \"Comma\"\n tokIf = \"Keyword_if\", tokElse = \"Keyword_else\", tokWhile = \"Keyword_while\",\n tokPrint = \"Keyword_print\", tokPutc = \"Keyword_putc\"\n tokIdent = \"Identifier\", tokInt = \"Integer\", tokChar = \"Integer\",\n tokString = \"String\"\n tokEnd = \"End_of_input\"\n\n Token* = object\n ln*, col*: int\n case kind*: TokenKind\n of tokIdent: ident*: string\n of tokInt: intVal*: int\n of tokChar: charVal*: char\n of tokString: stringVal*: string\n else: discard\n\n Lexer* = object\n input: string\n pos: int\n ln, col: int\n\n LexicalError* = object of CatchableError\n ln*, col*: int\n\nproc error(lexer: var Lexer, message: string) =\n var err = newException(LexicalError, message)\n err.ln = lexer.ln\n err.col = lexer.col\n\ntemplate current: char =\n if lexer.pos < lexer.input.len: lexer.input[lexer.pos]\n else: '\\x00'\ntemplate get(n: int): string =\n if lexer.pos < lexer.input.len:\n lexer.input[min(lexer.pos, lexer.input.len)..\n min(lexer.pos + n - 1, lexer.input.len)]\n else: \"\"\n\ntemplate next() =\n inc(lexer.pos); inc(lexer.col)\n if current() == '\\n':\n inc(lexer.ln)\n lexer.col = 0\n elif current() == '\\r':\n lexer.col = 0\n\nproc skip(lexer: var Lexer) =\n while true:\n if current() in Whitespace:\n while current() in Whitespace:\n next()\n continue\n elif get(2) == \"/*\":\n next(); next()\n while get(2) != \"*/\":\n if current() == '\\x00':\n lexer.error(\"Unterminated comment\")\n next()\n next(); next()\n continue\n else: discard\n break\n\nproc charOrEscape(lexer: var Lexer): char =\n if current() != '\\\\':\n result = current()\n next()\n else:\n next()\n case current()\n of 'n': result = '\\n'\n of '\\\\': result = '\\\\'\n else: lexer.error(\"Unknown escape sequence '\\\\\" & current() & \"'\")\n next()\n\nproc next*(lexer: var Lexer): Token =\n let\n ln = lexer.ln\n col = lexer.col\n\n case current()\n of '*': result = Token(kind: tokMult); next()\n of '/': result = Token(kind: tokDiv); next()\n of '%': result = Token(kind: tokMod); next()\n of '+': result = Token(kind: tokAdd); next()\n of '-': result = Token(kind: tokSub); next()\n of '<':\n next()\n if current() == '=': result = Token(kind: tokLessEq)\n else: result = Token(kind: tokLess)\n of '>':\n next()\n if current() == '=':\n result = Token(kind: tokGreaterEq)\n next()\n else:\n result = Token(kind: tokGreater)\n of '=':\n next()\n if current() == '=':\n result = Token(kind: tokEq)\n next()\n else:\n result = Token(kind: tokAssign)\n of '!':\n next()\n if current() == '=':\n result = Token(kind: tokNotEq)\n next()\n else:\n result = Token(kind: tokNot)\n of '&':\n next()\n if current() == '&':\n result = Token(kind: tokAnd)\n next()\n else:\n lexer.error(\"'&&' expected\")\n of '|':\n next()\n if current() == '|':\n result = Token(kind: tokOr)\n next()\n else:\n lexer.error(\"'||' expected\")\n of '(': result = Token(kind: tokLPar); next()\n of ')': result = Token(kind: tokRPar); next()\n of '{': result = Token(kind: tokLBrace); next()\n of '}': result = Token(kind: tokRBrace); next()\n of ';': result = Token(kind: tokSemi); next()\n of ',': result = Token(kind: tokComma); next()\n of '\\'':\n next()\n if current() == '\\'': lexer.error(\"Empty character literal\")\n let ch = lexer.charOrEscape()\n if current() != '\\'':\n lexer.error(\"Character literal must contain a single character or \" &\n \"escape sequence\")\n result = Token(kind: tokChar, charVal: ch)\n next()\n of '0'..'9':\n var number = \"\"\n while current() in Digits:\n number.add(current())\n next()\n if current() in IdentStartChars:\n lexer.error(\"Integer literal ends in non-digit characters\")\n result = Token(kind: tokInt, intVal: parseInt(number))\n of '\"':\n next()\n var str = \"\"\n while current() notin {'\"', '\\x00', '\\n'}:\n str.add(lexer.charOrEscape())\n if current() == '\\x00':\n lexer.error(\"Unterminated string literal\")\n elif current() == '\\n':\n lexer.error(\"Line feed in string literal\")\n else:\n next()\n result = Token(kind: tokString, stringVal: str)\n of IdentStartChars:\n var ident = $current()\n next()\n while current() in IdentChars:\n ident.add(current())\n next()\n case ident\n of \"if\": result = Token(kind: tokIf)\n of \"else\": result = Token(kind: tokElse)\n of \"while\": result = Token(kind: tokWhile)\n of \"print\": result = Token(kind: tokPrint)\n of \"putc\": result = Token(kind: tokPutc)\n else: result = Token(kind: tokIdent, ident: ident)\n of '\\x00':\n result = Token(kind: tokEnd)\n else:\n lexer.error(\"Unexpected character: '\" & current() & \"'\")\n\n result.ln = ln\n result.col = col\n lexer.skip()\n\nproc peek*(lexer: var Lexer): Token =\n discard\n\nproc initLexer*(input: string): Lexer =\n result = Lexer(input: input, pos: 0, ln: 1, col: 1)\n result.skip()\n\nwhen isMainModule:\n let code = readAll(stdin)\n var\n lexer = initLexer(code)\n token: Token\n while true:\n token = lexer.next()\n stdout.write(token.ln, ' ', token.col, ' ', token.kind)\n case token.kind\n of tokInt: stdout.write(' ', token.intVal)\n of tokChar: stdout.write(' ', token.charVal.ord)\n of tokString: stdout.write(\" \\\"\", token.stringVal\n .replace(\"\\\\\", \"\\\\\\\\\")\n .replace(\"\\n\", \"\\\\n\"), '\"')\n of tokIdent: stdout.write(' ', token.ident)\n else: discard\n stdout.write('\\n')\n if token.kind == tokEnd:\n break\n", "language": "Nim" }, { "code": "# -*- ObjectIcon -*-\n#\n# The Rosetta Code lexical analyzer in Object Icon. Based upon the ATS\n# implementation.\n#\n# Usage: lex [INPUTFILE [OUTPUTFILE]]\n# If INPUTFILE or OUTPUTFILE is \"-\" or missing, then standard input\n# or standard output is used, respectively. *)\n#\n\nimport io\n\n$define EOF -1\n\n$define TOKEN_ELSE 0\n$define TOKEN_IF 1\n$define TOKEN_PRINT 2\n$define TOKEN_PUTC 3\n$define TOKEN_WHILE 4\n$define TOKEN_MULTIPLY 5\n$define TOKEN_DIVIDE 6\n$define TOKEN_MOD 7\n$define TOKEN_ADD 8\n$define TOKEN_SUBTRACT 9\n$define TOKEN_NEGATE 10\n$define TOKEN_LESS 11\n$define TOKEN_LESSEQUAL 12\n$define TOKEN_GREATER 13\n$define TOKEN_GREATEREQUAL 14\n$define TOKEN_EQUAL 15\n$define TOKEN_NOTEQUAL 16\n$define TOKEN_NOT 17\n$define TOKEN_ASSIGN 18\n$define TOKEN_AND 19\n$define TOKEN_OR 20\n$define TOKEN_LEFTPAREN 21\n$define TOKEN_RIGHTPAREN 22\n$define TOKEN_LEFTBRACE 23\n$define TOKEN_RIGHTBRACE 24\n$define TOKEN_SEMICOLON 25\n$define TOKEN_COMMA 26\n$define TOKEN_IDENTIFIER 27\n$define TOKEN_INTEGER 28\n$define TOKEN_STRING 29\n$define TOKEN_END_OF_INPUT 30\n\nglobal whitespace\nglobal ident_start\nglobal ident_continuation\n\nprocedure main(args)\n local inpf, outf\n local pushback_buffer, inp, pushback\n\n initial {\n whitespace := ' \\t\\v\\f\\r\\n'\n ident_start := '_' ++ &letters\n ident_continuation := ident_start ++ &digits\n }\n\n inpf := FileStream.stdin\n outf := FileStream.stdout\n if 1 <= *args & args[1] ~== \"-\" then {\n inpf := FileStream(args[1], FileOpt.RDONLY) | stop(&why)\n }\n if 2 <= *args & args[2] ~== \"-\" then {\n outf := FileStream(args[2], ior(FileOpt.WRONLY,\n FileOpt.TRUNC,\n FileOpt.CREAT)) | stop(&why)\n }\n\n pushback_buffer := []\n inp := create inputter(inpf, pushback_buffer)\n pushback := create repeat push(pushback_buffer, \\@&source)\n @pushback # The first invocation does nothing.\n\n scan_text(outf, inp, pushback)\nend\n\nprocedure scan_text(outf, inp, pushback)\n local ch\n\n while /ch | ch[1] ~=== EOF do {\n skip_spaces_and_comments(inp, pushback)\n ch := @inp\n if ch[1] === EOF then {\n print_token(outf, [TOKEN_END_OF_INPUT, \"\", ch[2], ch[3]])\n } else {\n ch @pushback\n print_token(outf, get_next_token(inp, pushback))\n }\n }\nend\n\nprocedure get_next_token(inp, pushback)\n local ch, ch1\n local ln, cn\n\n skip_spaces_and_comments(inp, pushback)\n ch := @inp\n ln := ch[2] # line number\n cn := ch[3] # column number\n case ch[1] of {\n \",\" : return [TOKEN_COMMA, \",\", ln, cn]\n \";\" : return [TOKEN_SEMICOLON, \";\", ln, cn]\n \"(\" : return [TOKEN_LEFTPAREN, \"(\", ln, cn]\n \")\" : return [TOKEN_RIGHTPAREN, \")\", ln, cn]\n \"{\" : return [TOKEN_LEFTBRACE, \"{\", ln, cn]\n \"}\" : return [TOKEN_RIGHTBRACE, \"}\", ln, cn]\n \"*\" : return [TOKEN_MULTIPLY, \"*\", ln, cn]\n \"/\" : return [TOKEN_DIVIDE, \"/\", ln, cn]\n \"%\" : return [TOKEN_MOD, \"%\", ln, cn]\n \"+\" : return [TOKEN_ADD, \"+\", ln, cn]\n \"-\" : return [TOKEN_SUBTRACT, \"-\", ln, cn]\n \"<\" : {\n ch1 := @inp\n if ch1[1] === \"=\" then {\n return [TOKEN_LESSEQUAL, \"<=\", ln, cn]\n } else {\n ch1 @pushback\n return [TOKEN_LESS, \"<\", ln, cn]\n }\n }\n \">\" : {\n ch1 := @inp\n if ch1[1] === \"=\" then {\n return [TOKEN_GREATEREQUAL, \">=\", ln, cn]\n } else {\n ch1 @pushback\n return [TOKEN_GREATER, \">\", ln, cn]\n }\n }\n \"=\" : {\n ch1 := @inp\n if ch1[1] === \"=\" then {\n return [TOKEN_EQUAL, \"==\", ln, cn]\n } else {\n ch1 @pushback\n return [TOKEN_ASSIGN, \"=\", ln, cn]\n }\n }\n \"!\" : {\n ch1 := @inp\n if ch1[1] === \"=\" then {\n return [TOKEN_NOTEQUAL, \"!=\", ln, cn]\n } else {\n ch1 @pushback\n return [TOKEN_NOT, \"!\", ln, cn]\n }\n }\n \"&\" : {\n ch1 := @inp\n if ch1[1] === \"&\" then {\n return [TOKEN_AND, \"&&\", ln, cn]\n } else {\n unexpected_character(ln, cn, ch)\n }\n }\n \"|\" : {\n ch1 := @inp\n if ch1[1] === \"|\" then {\n return [TOKEN_OR, \"||\", ln, cn]\n } else {\n unexpected_character(ln, cn, ch)\n }\n }\n \"\\\"\" : {\n ch @pushback\n return scan_string_literal(inp)\n }\n \"'\" : {\n ch @pushback\n return scan_character_literal(inp, pushback)\n }\n default : {\n if any(&digits, ch[1]) then {\n ch @pushback\n return scan_integer_literal(inp, pushback)\n } else if any(ident_start, ch[1]) then {\n ch @pushback\n return scan_identifier_or_reserved_word (inp, pushback)\n } else {\n unexpected_character(ln, cn, ch)\n }\n }\n }\nend\n\nprocedure scan_identifier_or_reserved_word(inp, pushback)\n local ch\n local s\n local line_no, column_no\n\n s := \"\"\n ch := @inp\n line_no := ch[2]\n column_no := ch[3]\n while EOF ~=== ch[1] & any(ident_continuation, ch[1]) do {\n s ||:= ch[1]\n ch := @inp\n }\n ch @pushback\n return reserved_word_lookup (s, line_no, column_no)\nend\n\nprocedure scan_integer_literal(inp, pushback)\n local ch\n local s\n local line_no, column_no\n\n s := \"\"\n ch := @inp\n line_no := ch[2]\n column_no := ch[3]\n while EOF ~=== ch[1] & any(ident_continuation, ch[1]) do {\n s ||:= ch[1]\n ch := @inp\n }\n ch @pushback\n not upto(~&digits, s) | invalid_integer_literal(line_no, column_no, s)\n return [TOKEN_INTEGER, s, line_no, column_no]\nend\n\nprocedure scan_character_literal(inp, pushback)\n local ch, ch1\n local close_quote\n local toktup\n local line_no, column_no\n\n ch := @inp # The opening quote.\n close_quote := ch[1] # Same as the opening quote.\n ch @pushback\n\n line_no := ch[2]\n column_no := ch[3]\n\n toktup := scan_character_literal_without_checking_end(inp)\n ch1 := @inp\n if ch1[1] ~=== close_quote then {\n repeat {\n case ch1[1] of {\n EOF : unterminated_character_literal(line_no, column_no)\n close_quote : multicharacter_literal(line_no, column_no)\n default : ch1 := @inp\n }\n }\n }\n return toktup\nend\n\nprocedure scan_character_literal_without_checking_end(inp)\n local ch, ch1, ch2\n\n ch := @inp # The opening quote.\n ch1 := @inp\n EOF ~=== ch1[1] | unterminated_character_literal(ch[2], ch[3])\n if ch1[1] == \"\\\\\" then {\n ch2 := @inp\n EOF ~=== ch2[1] | unterminated_character_literal(ch[2], ch[3])\n case ch2[1] of {\n \"n\" : return [TOKEN_INTEGER, string(ord(\"\\n\")), ch[2], ch[3]]\n \"\\\\\" : return [TOKEN_INTEGER, string(ord(\"\\\\\")), ch[2], ch[3]]\n default : unsupported_escape(ch1[2], ch1[3], ch2)\n }\n } else {\n return [TOKEN_INTEGER, string(ord(ch1[1])), ch[2], ch[3]]\n }\nend\n\nprocedure scan_string_literal(inp)\n local ch, ch1, ch2\n local line_no, column_no\n local close_quote\n local s\n local retval\n\n ch := @inp # The opening quote\n close_quote := ch[1] # Same as the opening quote.\n line_no := ch[2]\n column_no := ch[3]\n\n s := ch[1]\n until \\retval do {\n ch1 := @inp\n ch1[1] ~=== EOF |\n unterminated_string_literal (line_no, column_no,\n \"end of input\")\n ch1[1] ~== \"\\n\" |\n unterminated_string_literal (line_no, column_no,\n \"end of line\")\n if ch1[1] == close_quote then {\n retval := [TOKEN_STRING, s || close_quote, line_no, column_no]\n } else if ch1[1] ~== \"\\\\\" then {\n s ||:= ch1[1]\n } else {\n ch2 := @inp\n EOF ~=== ch2[1] | unsupported_escape(line_no, column_no, ch2)\n case ch2[1] of {\n \"n\" : s ||:= \"\\\\n\"\n \"\\\\\" : s ||:= \"\\\\\\\\\"\n default : unsupported_escape(line_no, column_no, ch2)\n }\n }\n }\n return retval\nend\n\nprocedure skip_spaces_and_comments(inp, pushback)\n local ch, ch1\n\n repeat {\n ch := @inp\n (EOF === ch[1]) & { ch @pushback; return }\n if not any(whitespace, ch[1]) then {\n (ch[1] == \"/\") | { ch @pushback; return }\n (ch1 := @inp) | { ch @pushback; return }\n (ch1[1] == \"*\") | { ch1 @pushback; ch @pushback; return }\n scan_comment(inp, ch[2], ch[3])\n }\n }\nend\n\nprocedure scan_comment(inp, line_no, column_no)\n local ch, ch1\n\n until (\\ch)[1] == \"*\" & (\\ch1)[1] == \"/\" do {\n ch := @inp\n (EOF === ch[1]) & unterminated_comment(line_no, column_no)\n if ch[1] == \"*\" then {\n ch1 := @inp\n (EOF === ch[1]) & unterminated_comment(line_no, column_no)\n }\n }\n return\nend\n\nprocedure reserved_word_lookup(s, line_no, column_no)\n\n # Lookup is by an extremely simple perfect hash.\n\n static reserved_words\n static reserved_word_tokens\n local hashval, token, toktup\n\n initial {\n reserved_words := [\"if\", \"print\", \"else\",\n \"\", \"putc\", \"\",\n \"\", \"while\", \"\"]\n reserved_word_tokens :=\n [TOKEN_IF, TOKEN_PRINT, TOKEN_ELSE,\n TOKEN_IDENTIFIER, TOKEN_PUTC, TOKEN_IDENTIFIER,\n TOKEN_IDENTIFIER, TOKEN_WHILE, TOKEN_IDENTIFIER]\n }\n\n if *s < 2 then {\n toktup := [TOKEN_IDENTIFIER, s, line_no, column_no]\n } else {\n hashval := ((ord(s[1]) + ord(s[2])) % (*reserved_words)) + 1\n token := reserved_word_tokens[hashval]\n if token = TOKEN_IDENTIFIER | s ~== reserved_words[hashval] then {\n toktup := [TOKEN_IDENTIFIER, s, line_no, column_no]\n } else {\n toktup := [token, s, line_no, column_no]\n }\n }\n return toktup\nend\n\nprocedure print_token(outf, toktup)\n static token_names\n local s_line, s_column\n\n initial {\n token_names := [\"Keyword_else\",\n \"Keyword_if\",\n \"Keyword_print\",\n \"Keyword_putc\",\n \"Keyword_while\",\n \"Op_multiply\",\n \"Op_divide\",\n \"Op_mod\",\n \"Op_add\",\n \"Op_subtract\",\n \"Op_negate\",\n \"Op_less\",\n \"Op_lessequal\",\n \"Op_greater\",\n \"Op_greaterequal\",\n \"Op_equal\",\n \"Op_notequal\",\n \"Op_not\",\n \"Op_assign\",\n \"Op_and\",\n \"Op_or\",\n \"LeftParen\",\n \"RightParen\",\n \"LeftBrace\",\n \"RightBrace\",\n \"Semicolon\",\n \"Comma\",\n \"Identifier\",\n \"Integer\",\n \"String\",\n \"End_of_input\"]\n }\n\n /outf := FileStream.stdout\n s_line := string(toktup[3])\n s_column := string(toktup[4])\n writes(outf, right (s_line, max(5, *s_line)))\n writes(outf, \" \")\n writes(outf, right (s_column, max(5, *s_column)))\n writes(outf, \" \")\n writes(outf, token_names[toktup[1] + 1])\n case toktup[1] of {\n TOKEN_IDENTIFIER : writes(outf, \" \", toktup[2])\n TOKEN_INTEGER : writes(outf, \" \", toktup[2])\n TOKEN_STRING : writes(outf, \" \", toktup[2])\n }\n write(outf)\n return\nend\n\nprocedure inputter(inpf, pushback_buffer)\n local buffer\n local line_no, column_no\n local c\n\n buffer := \"\"\n line_no := 1\n column_no := 1\n\n repeat {\n buffer? {\n until *pushback_buffer = 0 & pos(0) do {\n if *pushback_buffer ~= 0 then {\n suspend pop(pushback_buffer)\n } else {\n c := move(1)\n suspend [c, line_no, column_no]\n if c == \"\\n\" then {\n line_no +:= 1\n column_no := 1\n } else {\n column_no +:= 1\n }\n }\n }\n }\n (buffer := reads(inpf, 2048)) |\n suspend [EOF, line_no, column_no]\n }\nend\n\nprocedure unterminated_comment(line_no, column_no)\n error(\"unterminated comment starting at \",\n line_no, \":\", column_no)\nend\n\nprocedure unexpected_character(line_no, column_no, ch)\n error(\"unexpected character '\", ch[1], \"' starting at \",\n line_no, \":\", column_no)\nend\n\nprocedure unterminated_string_literal (line_no, column_no, cause)\n error(\"unterminated string literal (\", cause, \") starting at \",\n line_no, \":\", column_no)\nend\n\nprocedure unsupported_escape (line_no, column_no, ch)\n if ch[1] === EOF then {\n error(\"unexpected \\\\ at end of input\",\n \" starting at \", line_no, \":\", column_no)\n } else {\n error(\"unsupported escape \\\\\", ch[1],\n \" starting at \", line_no, \":\", column_no)\n }\nend\n\nprocedure invalid_integer_literal(line_no, column_no, s)\n error(\"invalid integer literal \", s,\n \" starting at \", line_no, \":\", column_no)\nend\n\nprocedure unterminated_character_literal(line_no, column_no)\n error(\"unterminated character literal starting at \",\n line_no, \":\", column_no)\nend\n\nprocedure multicharacter_literal(line_no, column_no)\n error(\"unsupported multicharacter literal starting at \",\n line_no, \":\", column_no)\nend\n\nprocedure error(args[])\n write!([FileStream.stderr] ||| args)\n exit(1)\nend\n", "language": "ObjectIcon" }, { "code": "(*------------------------------------------------------------------*)\n(* The Rosetta Code lexical analyzer, in OCaml. Based on the ATS. *)\n\n(* When you compare this code to the ATS code, please keep in mind\n that, although ATS has an ML-like syntax:\n\n * The type system is not the same at all.\n\n * Most ATS functions are not closures. Those that are will have\n special notations such as \"<cloref1>\" associated with them. *)\n\n(*------------------------------------------------------------------*)\n(* The following functions are compatible with ASCII. *)\n\nlet is_digit ichar =\n 48 <= ichar && ichar <= 57\n\nlet is_lower ichar =\n 97 <= ichar && ichar <= 122\n\nlet is_upper ichar =\n 65 <= ichar && ichar <= 90\n\nlet is_alpha ichar =\n is_lower ichar || is_upper ichar\n\nlet is_alnum ichar =\n is_digit ichar || is_alpha ichar\n\nlet is_ident_start ichar =\n is_alpha ichar || ichar = 95\n\nlet is_ident_continuation ichar =\n is_alnum ichar || ichar = 95\n\nlet is_space ichar =\n ichar = 32 || (9 <= ichar && ichar <= 13)\n\n(*------------------------------------------------------------------*)\n\nlet reverse_list_to_string lst =\n List.rev lst |> List.to_seq |> String.of_seq\n\n(*------------------------------------------------------------------*)\n(* Character input more like that of C. There are various advantages\n and disadvantages to this method, but key points in its favor are:\n (a) it is how character input is done in the original ATS code, (b)\n Unicode code points are 21-bit positive integers. *)\n\nlet eof = (-1)\n\nlet input_ichar channel =\n try\n int_of_char (input_char channel)\n with\n | End_of_file -> eof\n\n(*------------------------------------------------------------------*)\n\n(* The type of an input character. *)\n\nmodule Ch =\n struct\n type t =\n {\n ichar : int;\n line_no : int;\n column_no : int\n }\n end\n\n(*------------------------------------------------------------------*)\n(* Inputting with unlimited pushback, and with counting of lines and\n columns. *)\n\nmodule Inp =\n struct\n type t =\n {\n inpf : in_channel;\n pushback : Ch.t list;\n line_no : int;\n column_no : int\n }\n\n let of_in_channel inpf =\n { inpf = inpf;\n pushback = [];\n line_no = 1;\n column_no = 1\n }\n\n let get_ch inp =\n match inp.pushback with\n | ch :: tail ->\n (ch, {inp with pushback = tail})\n | [] ->\n let ichar = input_ichar inp.inpf in\n if ichar = int_of_char '\\n' then\n ({ ichar = ichar;\n line_no = inp.line_no;\n column_no = inp.column_no },\n { inp with line_no = inp.line_no + 1;\n column_no = 1 })\n else\n ({ ichar = ichar;\n line_no = inp.line_no;\n column_no = inp.column_no },\n { inp with column_no = inp.column_no + 1 })\n\n let push_back_ch ch inp =\n {inp with pushback = ch :: inp.pushback}\n end\n\n(*------------------------------------------------------------------*)\n(* Tokens, appearing in tuples with arguments, and with line and\n column numbers. The tokens are integers, so they can be used as\n array indices. *)\n\n(* (token, argument, line_no, column_no) *)\ntype toktup_t = int * string * int * int\n\nlet token_ELSE = 0\nlet token_IF = 1\nlet token_PRINT = 2\nlet token_PUTC = 3\nlet token_WHILE = 4\nlet token_MULTIPLY = 5\nlet token_DIVIDE = 6\nlet token_MOD = 7\nlet token_ADD = 8\nlet token_SUBTRACT = 9\nlet token_NEGATE = 10\nlet token_LESS = 11\nlet token_LESSEQUAL = 12\nlet token_GREATER = 13\nlet token_GREATEREQUAL = 14\nlet token_EQUAL = 15\nlet token_NOTEQUAL = 16\nlet token_NOT = 17\nlet token_ASSIGN = 18\nlet token_AND = 19\nlet token_OR = 20\nlet token_LEFTPAREN = 21\nlet token_RIGHTPAREN = 22\nlet token_LEFTBRACE = 23\nlet token_RIGHTBRACE = 24\nlet token_SEMICOLON = 25\nlet token_COMMA = 26\nlet token_IDENTIFIER = 27\nlet token_INTEGER = 28\nlet token_STRING = 29\nlet token_END_OF_INPUT = 30\n;;\n\n(* A *very* simple perfect hash for the reserved words. (Yes, this is\n overkill, except for demonstration of the principle.) *)\n\nlet reserved_words =\n [| \"if\"; \"print\"; \"else\"; \"\"; \"putc\"; \"\"; \"\"; \"while\"; \"\" |]\nlet reserved_word_tokens =\n [| token_IF; token_PRINT; token_ELSE; token_IDENTIFIER;\n token_PUTC; token_IDENTIFIER; token_IDENTIFIER; token_WHILE;\n token_IDENTIFIER |]\n\nlet reserved_word_lookup s line_no column_no =\n if String.length s < 2 then\n (token_IDENTIFIER, s, line_no, column_no)\n else\n let hashval = (int_of_char s.[0] + int_of_char s.[1]) mod 9 in\n let token = reserved_word_tokens.(hashval) in\n if token = token_IDENTIFIER || s <> reserved_words.(hashval) then\n (token_IDENTIFIER, s, line_no, column_no)\n else\n (token, s, line_no, column_no)\n\n(* Token to string lookup. *)\n\nlet token_names =\n [| \"Keyword_else\";\n \"Keyword_if\";\n \"Keyword_print\";\n \"Keyword_putc\";\n \"Keyword_while\";\n \"Op_multiply\";\n \"Op_divide\";\n \"Op_mod\";\n \"Op_add\";\n \"Op_subtract\";\n \"Op_negate\";\n \"Op_less\";\n \"Op_lessequal\";\n \"Op_greater\";\n \"Op_greaterequal\";\n \"Op_equal\";\n \"Op_notequal\";\n \"Op_not\";\n \"Op_assign\";\n \"Op_and\";\n \"Op_or\";\n \"LeftParen\";\n \"RightParen\";\n \"LeftBrace\";\n \"RightBrace\";\n \"Semicolon\";\n \"Comma\";\n \"Identifier\";\n \"Integer\";\n \"String\";\n \"End_of_input\" |]\n\nlet token_name token =\n token_names.(token)\n\n(*------------------------------------------------------------------*)\n\nexception Unterminated_comment of int * int\nexception Unterminated_character_literal of int * int\nexception Multicharacter_literal of int * int\nexception End_of_input_in_string_literal of int * int\nexception End_of_line_in_string_literal of int * int\nexception Unsupported_escape of int * int * int\nexception Invalid_integer_literal of int * int * string\nexception Unexpected_character of int * int * char\n\n(*------------------------------------------------------------------*)\n(* Skipping past spaces and comments. (A comment in the target\n language is, if you think about it, a kind of space.) *)\n\nlet scan_comment inp line_no column_no =\n let rec loop inp =\n let (ch, inp) = Inp.get_ch inp in\n if ch.ichar = eof then\n raise (Unterminated_comment (line_no, column_no))\n else if ch.ichar = int_of_char '*' then\n let (ch1, inp) = Inp.get_ch inp in\n if ch1.ichar = eof then\n raise (Unterminated_comment (line_no, column_no))\n else if ch1.ichar = int_of_char '/' then\n inp\n else\n loop inp\n else\n loop inp\n in\n loop inp\n\nlet skip_spaces_and_comments inp =\n let rec loop inp =\n let (ch, inp) = Inp.get_ch inp in\n if is_space ch.ichar then\n loop inp\n else if ch.ichar = int_of_char '/' then\n let (ch1, inp) = Inp.get_ch inp in\n if ch1.ichar = int_of_char '*' then\n scan_comment inp ch.line_no ch.column_no |> loop\n else\n let inp = Inp.push_back_ch ch1 inp in\n let inp = Inp.push_back_ch ch inp in\n inp\n else\n Inp.push_back_ch ch inp\n in\n loop inp\n\n(*------------------------------------------------------------------*)\n(* Integer literals, identifiers, and reserved words. *)\n\n(* In ATS the predicate for simple scan was supplied by template\n expansion, which (typically) produces faster code than passing a\n function or closure (although passing either of those could have\n been done). Here I pass the predicate as a function/closure. It is\n worth contrasting the methods. *)\nlet rec simple_scan pred lst inp =\n let (ch, inp) = Inp.get_ch inp in\n if pred ch.ichar then\n simple_scan pred (char_of_int ch.ichar :: lst) inp\n else\n (lst, Inp.push_back_ch ch inp)\n\n(* Demonstration of one way to make a new closure in OCaml. (In ATS,\n one might see things that look similar but are actually template\n operations.) *)\nlet simple_scan_iic = simple_scan is_ident_continuation\n\nlet scan_integer_literal inp =\n let (ch, inp) = Inp.get_ch inp in\n let _ = assert (is_digit ch.ichar) in\n let (lst, inp) = simple_scan_iic [char_of_int ch.ichar] inp in\n let s = reverse_list_to_string lst in\n if List.for_all (fun c -> is_digit (int_of_char c)) lst then\n ((token_INTEGER, s, ch.line_no, ch.column_no), inp)\n else\n raise (Invalid_integer_literal (ch.line_no, ch.column_no, s))\n\nlet scan_identifier_or_reserved_word inp =\n let (ch, inp) = Inp.get_ch inp in\n let _ = assert (is_ident_start ch.ichar) in\n let (lst, inp) = simple_scan_iic [char_of_int ch.ichar] inp in\n let s = reverse_list_to_string lst in\n let toktup = reserved_word_lookup s ch.line_no ch.column_no in\n (toktup, inp)\n\n(*------------------------------------------------------------------*)\n(* String literals. *)\n\nlet scan_string_literal inp =\n let (ch, inp) = Inp.get_ch inp in\n let _ = assert (ch.ichar = int_of_char '\"') in\n\n let rec scan lst inp =\n let (ch1, inp) = Inp.get_ch inp in\n if ch1.ichar = eof then\n raise (End_of_input_in_string_literal\n (ch.line_no, ch.column_no))\n else if ch1.ichar = int_of_char '\\n' then\n raise (End_of_line_in_string_literal\n (ch.line_no, ch.column_no))\n else if ch1.ichar = int_of_char '\"' then\n (lst, inp)\n else if ch1.ichar <> int_of_char '\\\\' then\n scan (char_of_int ch1.ichar :: lst) inp\n else\n let (ch2, inp) = Inp.get_ch inp in\n if ch2.ichar = int_of_char 'n' then\n scan ('n' :: '\\\\' :: lst) inp\n else if ch2.ichar = int_of_char '\\\\' then\n scan ('\\\\' :: '\\\\' :: lst) inp\n else\n raise (Unsupported_escape (ch1.line_no, ch1.column_no,\n ch2.ichar))\n in\n let lst = '\"' :: [] in\n let (lst, inp) = scan lst inp in\n let lst = '\"' :: lst in\n let s = reverse_list_to_string lst in\n ((token_STRING, s, ch.line_no, ch.column_no), inp)\n\n(*------------------------------------------------------------------*)\n(* Character literals. *)\n\nlet scan_character_literal_without_checking_end inp =\n let (ch, inp) = Inp.get_ch inp in\n let _ = assert (ch.ichar = int_of_char '\\'') in\n let (ch1, inp) = Inp.get_ch inp in\n if ch1.ichar = eof then\n raise (Unterminated_character_literal\n (ch.line_no, ch.column_no))\n else if ch1.ichar = int_of_char '\\\\' then\n let (ch2, inp) = Inp.get_ch inp in\n if ch2.ichar = eof then\n raise (Unterminated_character_literal\n (ch.line_no, ch.column_no))\n else if ch2.ichar = int_of_char 'n' then\n let s = (int_of_char '\\n' |> string_of_int) in\n ((token_INTEGER, s, ch.line_no, ch.column_no), inp)\n else if ch2.ichar = int_of_char '\\\\' then\n let s = (int_of_char '\\\\' |> string_of_int) in\n ((token_INTEGER, s, ch.line_no, ch.column_no), inp)\n else\n raise (Unsupported_escape\n (ch1.line_no, ch1.column_no, ch2.ichar))\n else\n let s = string_of_int ch1.ichar in\n ((token_INTEGER, s, ch.line_no, ch.column_no), inp)\n\nlet scan_character_literal inp =\n let (toktup, inp) =\n scan_character_literal_without_checking_end inp in\n let (_, _, line_no, column_no) = toktup in\n\n let check_end inp =\n let (ch, inp) = Inp.get_ch inp in\n if ch.ichar = int_of_char '\\'' then\n inp\n else\n let rec loop_to_end (ch1 : Ch.t) inp =\n if ch1.ichar = eof then\n raise (Unterminated_character_literal (line_no, column_no))\n else if ch1.ichar = int_of_char '\\'' then\n raise (Multicharacter_literal (line_no, column_no))\n else\n let (ch1, inp) = Inp.get_ch inp in\n loop_to_end ch1 inp\n in\n loop_to_end ch inp\n in\n let inp = check_end inp in\n (toktup, inp)\n\n(*------------------------------------------------------------------*)\n\nlet get_next_token inp =\n let inp = skip_spaces_and_comments inp in\n let (ch, inp) = Inp.get_ch inp in\n let ln = ch.line_no in\n let cn = ch.column_no in\n if ch.ichar = eof then\n ((token_END_OF_INPUT, \"\", ln, cn), inp)\n else\n match char_of_int ch.ichar with\n | ',' -> ((token_COMMA, \",\", ln, cn), inp)\n | ';' -> ((token_SEMICOLON, \";\", ln, cn), inp)\n | '(' -> ((token_LEFTPAREN, \"(\", ln, cn), inp)\n | ')' -> ((token_RIGHTPAREN, \")\", ln, cn), inp)\n | '{' -> ((token_LEFTBRACE, \"{\", ln, cn), inp)\n | '}' -> ((token_RIGHTBRACE, \"}\", ln, cn), inp)\n | '*' -> ((token_MULTIPLY, \"*\", ln, cn), inp)\n | '/' -> ((token_DIVIDE, \"/\", ln, cn), inp)\n | '%' -> ((token_MOD, \"%\", ln, cn), inp)\n | '+' -> ((token_ADD, \"+\", ln, cn), inp)\n | '-' -> ((token_SUBTRACT, \"-\", ln, cn), inp)\n | '<' ->\n let (ch1, inp) = Inp.get_ch inp in\n if ch1.ichar = int_of_char '=' then\n ((token_LESSEQUAL, \"<=\", ln, cn), inp)\n else\n let inp = Inp.push_back_ch ch1 inp in\n ((token_LESS, \"<\", ln, cn), inp)\n | '>' ->\n let (ch1, inp) = Inp.get_ch inp in\n if ch1.ichar = int_of_char '=' then\n ((token_GREATEREQUAL, \">=\", ln, cn), inp)\n else\n let inp = Inp.push_back_ch ch1 inp in\n ((token_GREATER, \">\", ln, cn), inp)\n | '=' ->\n let (ch1, inp) = Inp.get_ch inp in\n if ch1.ichar = int_of_char '=' then\n ((token_EQUAL, \"==\", ln, cn), inp)\n else\n let inp = Inp.push_back_ch ch1 inp in\n ((token_ASSIGN, \"=\", ln, cn), inp)\n | '!' ->\n let (ch1, inp) = Inp.get_ch inp in\n if ch1.ichar = int_of_char '=' then\n ((token_NOTEQUAL, \"!=\", ln, cn), inp)\n else\n let inp = Inp.push_back_ch ch1 inp in\n ((token_NOT, \"!\", ln, cn), inp)\n | '&' ->\n let (ch1, inp) = Inp.get_ch inp in\n if ch1.ichar = int_of_char '&' then\n ((token_AND, \"&&\", ln, cn), inp)\n else\n raise (Unexpected_character (ch.line_no, ch.column_no,\n char_of_int ch.ichar))\n | '|' ->\n let (ch1, inp) = Inp.get_ch inp in\n if ch1.ichar = int_of_char '|' then\n ((token_OR, \"||\", ln, cn), inp)\n else\n raise (Unexpected_character (ch.line_no, ch.column_no,\n char_of_int ch.ichar))\n | '\"' ->\n let inp = Inp.push_back_ch ch inp in\n scan_string_literal inp\n | '\\'' ->\n let inp = Inp.push_back_ch ch inp in\n scan_character_literal inp\n | _ when is_digit ch.ichar ->\n let inp = Inp.push_back_ch ch inp in\n scan_integer_literal inp\n | _ when is_ident_start ch.ichar ->\n let inp = Inp.push_back_ch ch inp in\n scan_identifier_or_reserved_word inp\n | _ -> raise (Unexpected_character (ch.line_no, ch.column_no,\n char_of_int ch.ichar))\n\nlet print_token outf toktup =\n let (token, arg, line_no, column_no) = toktup in\n let name = token_name token in\n let (padding, str) =\n match 0 with\n | _ when token = token_IDENTIFIER -> (\" \", arg)\n | _ when token = token_INTEGER -> (\" \", arg)\n | _ when token = token_STRING -> (\" \", arg)\n | _ -> (\"\", \"\")\n in\n Printf.fprintf outf \"%5d %5d %s%s%s\\n\"\n line_no column_no name padding str\n\nlet scan_text outf inp =\n let rec loop inp =\n let (toktup, inp) = get_next_token inp in\n begin\n print_token outf toktup;\n let (token, _, _, _) = toktup in\n if token <> token_END_OF_INPUT then\n loop inp\n end\n in\n loop inp\n\n(*------------------------------------------------------------------*)\n\nlet main () =\n let inpf_filename =\n if 2 <= Array.length Sys.argv then\n Sys.argv.(1)\n else\n \"-\"\n in\n let outf_filename =\n if 3 <= Array.length Sys.argv then\n Sys.argv.(2)\n else\n \"-\"\n in\n let inpf =\n if inpf_filename = \"-\" then\n stdin\n else\n open_in inpf_filename\n in\n let outf =\n if outf_filename = \"-\" then\n stdout\n else\n open_out outf_filename\n in\n let inp = Inp.of_in_channel inpf in\n scan_text outf inp\n;;\n\nmain ()\n\n(*------------------------------------------------------------------*)\n", "language": "OCaml" }, { "code": "(import (owl parse))\n\n(define (get-comment)\n (get-either\n (let-parses (\n (_ (get-imm #\\*))\n (_ (get-imm #\\/)))\n #true)\n (let-parses (\n (_ get-byte)\n (_ (get-comment)))\n #true)))\n\n(define get-whitespace\n (get-any-of\n (get-byte-if (lambda (x) (has? '(#\\tab #\\newline #\\space #\\return) x))) ; whitespace\n (let-parses ( ; comment\n (_ (get-imm #\\/))\n (_ (get-imm #\\*))\n (_ (get-comment)))\n #true)))\n\n(define get-operator\n (let-parses (\n (operator (get-any-of\n (get-word \"||\" 'Op_or)\n (get-word \"&&\" 'Op_and)\n (get-word \"!=\" 'Op_notequal)\n (get-word \"==\" 'Op_equal)\n (get-word \">=\" 'Op_greaterequal)\n (get-word \"<=\" 'Op_lessequal)\n\n (get-word \"=\" 'Op_assign)\n (get-word \"!\" 'Op_nop)\n (get-word \">\" 'Op_greater)\n (get-word \"<\" 'Op_less)\n (get-word \"-\" 'Op_subtract)\n (get-word \"+\" 'Op_add)\n (get-word \"%\" 'Op_mod)\n (get-word \"/\" 'Op_divide)\n (get-word \"*\" 'Op_multiply))))\n (cons 'operator operator)))\n\n(define get-symbol\n (let-parses (\n (symbol (get-any-of\n (get-word \"(\" 'LeftParen)\n (get-word \")\" 'RightParen)\n (get-word \"{\" 'LeftBrace)\n (get-word \"}\" 'RightBrace)\n (get-word \";\" 'Semicolon)\n (get-word \",\" 'Comma))))\n (cons 'symbol symbol)))\n\n(define get-keyword\n (let-parses (\n (keyword (get-any-of\n (get-word \"if\" 'Keyword_if)\n (get-word \"else\" 'Keyword_else)\n (get-word \"while\" 'Keyword_while)\n (get-word \"print\" 'Keyword_print)\n (get-word \"putc\" 'Keyword_putc))))\n (cons 'keyword keyword)))\n\n\n\n(define get-identifier\n (let-parses (\n (lead (get-byte-if (lambda (x) (or (<= #\\a x #\\z) (<= #\\A x #\\Z) (= x #\\_)))))\n (tail (get-greedy* (get-byte-if (lambda (x) (or (<= #\\a x #\\z) (<= #\\A x #\\Z) (= x #\\_) (<= #\\0 x #\\9)))))))\n (cons 'identifier (bytes->string (cons lead tail)))))\n\n(define get-integer\n (let-parses (\n (main (get-greedy+ (get-byte-if (lambda (x) (<= #\\0 x #\\9))))) )\n (cons 'integer (string->integer (bytes->string main)))))\n\n(define get-character\n (let-parses (\n (_ (get-imm #\\'))\n (char (get-any-of\n (get-word \"\\\\n\" #\\newline)\n (get-word \"\\\\\\\\\" #\\\\)\n (get-byte-if (lambda (x) (not (or (eq? x #\\') (eq? x #\\newline)))))))\n (_ (get-imm #\\')) )\n (cons 'character char)))\n\n(define get-string\n (let-parses (\n (_ (get-imm #\\\")) ;\"\n (data (get-greedy* (get-any-of\n (get-word \"\\\\n\" #\\newline)\n (get-word \"\\\\\\\\\" #\\\\) ;\\\"\n (get-byte-if (lambda (x) (not (or (eq? x #\\\") (eq? x #\\newline)))))))) ;\", newline\n (_ (get-imm #\\\")) ) ;\"\n (cons 'string (bytes->string data))))\n\n(define get-token\n (let-parses (\n (_ (get-greedy* get-whitespace))\n (token (get-any-of\n get-symbol\n get-keyword\n get-identifier\n get-operator\n get-integer\n get-character\n get-string\n )) )\n token))\n\n(define token-parser\n (let-parses (\n (tokens (get-greedy+ get-token))\n (_ (get-greedy* get-whitespace)))\n tokens))\n\n\n(define (translate source)\n (let ((stream (try-parse token-parser (str-iter source) #t)))\n (for-each print (car stream))\n (if (null? (cdr stream))\n (print 'End_of_input))))\n", "language": "Ol" }, { "code": "(define (translate source)\n (let ((stream (try-parse token-parser (str-iter source) #t)))\n (for-each print (car stream))\n (if (null? (force (cdr stream)))\n (print 'End_of_input))))\n", "language": "Ol" }, { "code": "(translate \"\n/*\n Hello world\n */\nprint(\\\"Hello, World!\\\\\\\\n\\\");\n\")\n", "language": "Ol" }, { "code": "(translate \"\n/*\n Show Ident and Integers\n */\nphoenix_number = 142857;\nprint(phoenix_number, \\\"\\\\\\\\n\\\");\n\")\n", "language": "Ol" }, { "code": "(translate \"\n/*\n All lexical tokens - not syntactically correct, but that will\n have to wait until syntax analysis\n */\n/* Print */ print /* Sub */ -\n/* Putc */ putc /* Lss */ <\n/* If */ if /* Gtr */ >\n/* Else */ else /* Leq */ <=\n/* While */ while /* Geq */ >=\n/* Lbrace */ { /* Eq */ ==\n/* Rbrace */ } /* Neq */ !=\n/* Lparen */ ( /* And */ &&\n/* Rparen */ ) /* Or */ ||\n/* Uminus */ - /* Semi */ ;\n/* Not */ ! /* Comma */ ,\n/* Mul */ * /* Assign */ =\n/* Div */ / /* Integer */ 42\n/* Mod */ % /* String */ \\\"String literal\\\"\n/* Add */ + /* Ident */ variable_name\n/* character literal */ '\\\\n'\n/* character literal */ '\\\\\\\\'\n/* character literal */ ' '\n\")\n", "language": "Ol" }, { "code": "(translate \"\n/*** test printing, embedded \\\\\\\\n and comments with lots of '*' ***/\nprint(42);\nprint(\\\"\\\\\\\\nHello World\\\\\\\\nGood Bye\\\\\\\\nok\\\\\\\\n\\\");\nprint(\\\"Print a slash n - \\\\\\\\\\\\\\\\n.\\\\\\\\n\\\");\n\")\n", "language": "Ol" }, { "code": "#!/usr/bin/env perl\n\nuse strict;\nuse warnings;\nno warnings 'once';\n\n\n#----- Definition of the language to be lexed -----#\n\nmy @tokens = (\n # Name | Format | Value #\n # -------------- |----------------------|-------------#\n ['Op_multiply' , '*' , ],\n ['Op_divide' , '/' , ],\n ['Op_mod' , '%' , ],\n ['Op_add' , '+' , ],\n ['Op_subtract' , '-' , ],\n ['Op_lessequal' , '<=' , ],\n ['Op_less' , '<' , ],\n ['Op_greaterequal', '>=' , ],\n ['Op_greater' , '>' , ],\n ['Op_equal' , '==' , ],\n ['Op_assign' , '=' , ],\n ['Op_not' , '!' , ],\n ['Op_notequal' , '!=' , ],\n ['Op_and' , '&&' , ],\n ['Op_or' , '||' , ],\n ['Keyword_else' , qr/else\\b/ , ],\n ['Keyword_if' , qr/if\\b/ , ],\n ['Keyword_while' , qr/while\\b/ , ],\n ['Keyword_print' , qr/print\\b/ , ],\n ['Keyword_putc' , qr/putc\\b/ , ],\n\n ['LeftParen' , '(' , ],\n ['RightParen' , ')' , ],\n ['LeftBrace' , '{' , ],\n ['RightBrace' , '}' , ],\n ['Semicolon' , ';' , ],\n ['Comma' , ',' , ],\n\n ['Identifier' , qr/[_a-z][_a-z0-9]*/i, \\&raw ],\n ['Integer' , qr/[0-9]+\\b/ , \\&raw ],\n ['Integer' , qr/'([^']*)(')?/ , \\&char_val ],\n ['String' , qr/\"([^\"]*)(\")?/ , \\&string_raw],\n\n ['End_of_input' , qr/$/ , ],\n);\n\nmy $comment = qr/\\/\\* .+? (?: \\*\\/ | $ (?{die \"End-of-file in comment\\n\"}) )/xs;\nmy $whitespace = qr/(?: \\s | $comment)*/x;\nmy $unrecognized = qr/\\w+ | ./x;\n\n#| Returns the value of a matched char literal, or dies if it is invalid\nsub char_val {\n my $str = string_val();\n die \"Multiple characters\\n\" if length $str > 1;\n die \"No character\\n\" if length $str == 0;\n ord $str;\n}\n\n#| Returns the value of a matched string literal, or dies if it is invalid\nsub string_val {\n my ($str, $end) = ($1, $2);\n die \"End-of-file\\n\" if not defined $end;\n die \"End-of-line\\n\" if $str =~ /\\n/;\n $str =~ s/\\\\(.)/\n $1 eq 'n' ? \"\\n\"\n : $1 eq '\\\\' ? $1\n : $1 eq $end ? $1\n : die \"Unknown escape sequence \\\\$1\\n\"\n /rge;\n}\n\n#| Returns the source string of a matched literal\nsub raw { $& }\n\n#| Returns the source string of a matched string literal, or dies if invalid\nsub string_raw {\n string_val(); # Just for the error handling side-effects\n $&;\n}\n\n\n#----- Lexer \"engine\" -----#\n\n# Construct the scanner regex:\n\nmy $tokens =\n join \"|\",\n map {\n my $format = $tokens[$_][1];\n \"\\n\".(ref $format ? $format : quotemeta $format).\" (*MARK:$_) \";\n } 0..$#tokens;\n\nmy $regex = qr/\n \\G (?| $whitespace \\K (?| $tokens )\n | $whitespace? \\K ($unrecognized) (*MARK:!) )\n/x;\n\n\n# Run the lexer:\n\nmy $input = do { local $/ = undef; <STDIN> };\nmy $pos = 0;\nmy $linecol = linecol_accumulator();\n\nwhile ($input =~ /$regex/g) {\n # Get the line and column number\n my ($line, $col) = $linecol->(substr $input, $pos, $-[0] - $pos);\n $pos = $-[0];\n\n # Get the token type that was identified by the scanner regex\n my $type = $main::REGMARK;\n die \"Unrecognized token $1 at line $line, col $col\\n\" if $type eq '!';\n my ($name, $evaluator) = @{$tokens[$type]}[0, 2];\n\n # Get the token value\n my $value;\n if ($evaluator) {\n eval { $value = $evaluator->() };\n if ($@) { chomp $@; die \"$@ in $name at line $line, col $col\\n\" }\n }\n\n # Print the output line\n print \"$line\\t$col\\t$name\".($value ? \"\\t$value\" : '').\"\\n\";\n}\n\n#| Returns a closure, which can be fed a string one piece at a time and gives\n#| back the cumulative line and column number each time\nsub linecol_accumulator {\n my ($line, $col) = (1, 1);\n sub {\n my $str = shift;\n my @lines = split \"\\n\", $str, -1;\n my ($l, $c) = @lines ? (@lines - 1, length $lines[-1]) : (0, 0);\n if ($l) { $line += $l; $col = 1 + $c }\n else { $col += $c }\n ($line, $col)\n }\n}\n", "language": "Perl" }, { "code": "#!/usr/bin/perl\n\nuse strict; # lex.pl - source to tokens\nuse warnings; # http://www.rosettacode.org/wiki/Compiler/lexical_analyzer\nno warnings qw(qw);\n\nmy %keywords = map { $_, \"Keyword_$_\" } qw( while print if else putc );\nmy %tokens = qw[ ; Semicolon ( LeftParen ) RightParen { LeftBrace } RightBrace\n + Op_add - Op_subtract * Op_multiply % Op_mod = Op_assign >= Op_greaterequal\n != Op_notequal == Op_equal ! Op_not < Op_less <= Op_lessequal > Op_greater\n , Comma && Op_and || Op_or ];\n\nlocal $_ = join '', <>;\n\nwhile( /\\G (?|\n \\s+ (?{ undef })\n | \\d+[_a-zA-Z]\\w* (?{ die \"invalid mixed number $&\\n\" })\n | \\d+ (?{ \"Integer $&\" })\n | \\w+ (?{ $keywords{$&} || \"Identifier $&\" })\n | ( [-;(){}+*%,] | [=!<>]=? | && | \\|\\| )\n (?{ $tokens{$1} })\n | \\/ (?{ 'Op_divide' }) (?: \\* (?: [\\s\\S]*?\\*\\/ (?{ undef }) |\n (?{ die \"End-of-file in comment\\n\" }) ) )?\n | \"[^\"\\n]*\" (?{ \"String $&\" })\n | \" (?{ die \"unterminated string\\n\" })\n | '' (?{ die \"empty character constant\\n\" })\n | '([^\\n\\\\])' (?{ 'Integer ' . ord $1 })\n | '\\\\n' (?{ 'Integer 10' })\n | '\\\\\\\\' (?{ 'Integer 92' })\n | ' (?{ die \"unterminated or bad character constant\\n\" }) #'\n | . (?{ die \"invalid character $&\\n\" })\n ) /gcx )\n {\n defined $^R and printf \"%5d %7d %s\\n\",\n 1 + $` =~ tr/\\n//, 1 + length $` =~ s/.*\\n//sr, $^R;\n }\nprintf \"%5d %7d %s\\n\", 1 + tr/\\n//, 1, 'End_of_input';\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Compiler\\core.e\n -- ============================\n --\n -- Standard declarations and routines used by lex.exw, parse.exw, cgen.exw, and interp.exw\n -- (included in distribution as above, which contains some additional sanity checks)\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">EOF</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">STDIN</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">STDOUT</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">enum</span> <span style=\"color: #000000;\">NONE</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">UNARY</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">BINARY</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">type</span> <span style=\"color: #000000;\">nary</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">NONE</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">UNARY</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">BINARY</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">type</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tkNames</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #000080;font-style:italic;\">-- eg/ie {\"Op_multiply\",\"Op_divide\",..}</span>\n <span style=\"color: #008080;\">global</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">precedences</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">global</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">narys</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #000080;font-style:italic;\">-- NONE/UNARY/BINARY</span>\n <span style=\"color: #008080;\">global</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">operators</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #000080;font-style:italic;\">-- eg/ie {\"*\",\"/\",\"+\",\"-\",\"&lt;\",\"&lt;=\",..}</span>\n <span style=\"color: #008080;\">global</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">opcodes</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #000080;font-style:italic;\">-- idx to tkNames, matching operators</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">KEYWORDS</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">new_dict</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #000080;font-style:italic;\">-- eg/ie {\"if\"=&gt;idx to tkNames}</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">enum</span> <span style=\"color: #000000;\">OPERATOR</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">DIGIT</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">LETTER</span> <span style=\"color: #000080;font-style:italic;\">-- character classes</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">charmap</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">255</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">charmap</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #008000;\">'0'</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #008000;\">'9'</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">DIGIT</span>\n <span style=\"color: #000000;\">charmap</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #008000;\">'A'</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #008000;\">'Z'</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">LETTER</span>\n <span style=\"color: #000000;\">charmap</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #008000;\">'a'</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #008000;\">'z'</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">LETTER</span>\n <span style=\"color: #000000;\">charmap</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #008000;\">'_'</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">LETTER</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">tkName</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nary</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">NONE</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">precedence</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">tkNames</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tkNames</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">narys</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">narys</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">precedences</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">precedences</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">precedence</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tkNames</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nary</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">precedence</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkName</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">precedence</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">operators</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">operators</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">opcodes</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">opcodes</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">charmap</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">OPERATOR</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">tkKw</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">keyword</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkName</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">putd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">keyword</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">KEYWORDS</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">constant</span>\n <span style=\"color: #000000;\">tk_EOI</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkName</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"End_of_input\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--1</span>\n <span style=\"color: #000000;\">tk_mul</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_multiply\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"*\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">BINARY</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">13</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--2</span>\n <span style=\"color: #000000;\">tk_div</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_divide\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"/\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">BINARY</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">13</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--3</span>\n <span style=\"color: #000000;\">tk_mod</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_mod\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"%\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">BINARY</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">13</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--4</span>\n <span style=\"color: #000000;\">tk_add</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_add\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"+\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">BINARY</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--5</span>\n <span style=\"color: #000000;\">tk_sub</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_subtract\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"-\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">BINARY</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--6</span>\n <span style=\"color: #000000;\">tk_neg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkName</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_negate\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">UNARY</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">14</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--7</span>\n <span style=\"color: #000000;\">tk_not</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_not\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"!\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">UNARY</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">14</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--8</span>\n <span style=\"color: #000000;\">tk_lt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_less\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"&lt;\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">BINARY</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--9</span>\n <span style=\"color: #000000;\">tk_le</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_lessequal\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"&lt;=\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">BINARY</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--10</span>\n <span style=\"color: #000000;\">tk_gt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_greater\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"&gt;\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">BINARY</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--11</span>\n <span style=\"color: #000000;\">tk_ge</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_greaterequal\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"&gt;=\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">BINARY</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--12</span>\n <span style=\"color: #000000;\">tk_eq</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_equal\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"==\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">BINARY</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--13</span>\n <span style=\"color: #000000;\">tk_ne</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_notequal\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"!=\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">BINARY</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--14</span>\n <span style=\"color: #000000;\">tk_assign</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_assign\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"=\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">NONE</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--15</span>\n <span style=\"color: #000000;\">tk_and</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_and\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"&&\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">BINARY</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--16</span>\n <span style=\"color: #000000;\">tk_or</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Op_or\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"||\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">BINARY</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--17</span>\n <span style=\"color: #000000;\">tk_if</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkKw</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Keyword_if\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"if\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--18</span>\n <span style=\"color: #000000;\">tk_else</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkKw</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Keyword_else\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"else\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--19</span>\n <span style=\"color: #000000;\">tk_while</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkKw</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Keyword_while\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"while\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--20</span>\n <span style=\"color: #000000;\">tk_print</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkKw</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Keyword_print\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"print\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--21</span>\n <span style=\"color: #000000;\">tk_putc</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkKw</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Keyword_putc\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"putc\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--22</span>\n <span style=\"color: #000000;\">tk_LeftParen</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"LeftParen\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"(\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">NONE</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--23</span>\n <span style=\"color: #000000;\">tk_RightParen</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"RightParen\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\")\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">NONE</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--24</span>\n <span style=\"color: #000000;\">tk_LeftBrace</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"LeftBrace\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"{\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">NONE</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--25</span>\n <span style=\"color: #000000;\">tk_RightBrace</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"RightBrace\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"}\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">NONE</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--26</span>\n <span style=\"color: #000000;\">tk_Semicolon</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Semicolon\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\";\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">NONE</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--27</span>\n <span style=\"color: #000000;\">tk_Comma</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkOp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Comma\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\",\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">NONE</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--28</span>\n <span style=\"color: #000000;\">tk_Identifier</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkName</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Identifier\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--29</span>\n <span style=\"color: #000000;\">tk_Integer</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkName</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Integer\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--30</span>\n <span style=\"color: #000000;\">tk_String</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkName</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"String\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--31</span>\n <span style=\"color: #000000;\">tk_Sequence</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkName</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Sequence\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--32</span>\n <span style=\"color: #000000;\">tk_Prints</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkName</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"tk_Prints\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">--33</span>\n <span style=\"color: #000000;\">tk_Printi</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tkName</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"tk_Printi\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">--34</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">input_file</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">STDIN</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">output_file</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">STDOUT</span>\n\n <span style=\"color: #008080;\">type</span> <span style=\"color: #000000;\">strint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">o</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004080;\">string</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">o</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #004080;\">integer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">o</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">type</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #000000;\">strint</span> <span style=\"color: #000000;\">tok_line</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- save of line/col at the start of</span>\n <span style=\"color: #000000;\">tok_col</span> <span style=\"color: #000080;font-style:italic;\">-- token/comment, for result/errors</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">oneline</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">errfmt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"Line %s column %s:\\n%s%s\"</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">errline</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">oneline</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">substitute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">trim</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">oneline</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\r\\n\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">'\\t'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">padding</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tok_col</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%s\\n%s^ \"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">oneline</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">padding</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">error</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">args</span><span style=\"color: #0000FF;\">={})</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">args</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">args</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">el</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">oneline</span><span style=\"color: #0000FF;\">)?</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">errline</span><span style=\"color: #0000FF;\">())</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #004080;\">integer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tok_line</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">tok_line</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tok_line</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #004080;\">integer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tok_col</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">tok_col</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tok_col</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">STDOUT</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">errfmt</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">tok_line</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tok_col</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">el</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">wait_key</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">abort</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">js_io</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span> <span style=\"color: #000080;font-style:italic;\">-- fake file i/o for running under pwa/p2js</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">open_file</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">file_name</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">mode</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">fn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">JS</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">js_open</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">file_name</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">:</span><span style=\"color: #7060A8;\">open</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">file_name</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">mode</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">STDOUT</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"Could not open %s\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">file_name</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">wait_key</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">abort</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">fn</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">open_files</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cl</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cl</span><span style=\"color: #0000FF;\">)></span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">input_file</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">open_file</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cl</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #008000;\">\"r\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cl</span><span style=\"color: #0000FF;\">)></span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">output_file</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">open_file</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cl</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #008000;\">\"w\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">close_files</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">input_file</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">STDIN</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">close</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input_file</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">output_file</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">STDOUT</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">close</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">output_file</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">enquote</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">`\"%s\"`</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">substitute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\\\n\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">unquote</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #008000;\">'\\\"'</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[$]!=</span><span style=\"color: #008000;\">'\\\"'</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">substitute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">..-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #008000;\">\"\\\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">s</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Compiler\\js_io.e\n -- =============================\n --\n -- Fake file i/o for running under pwa/p2js in a browser\n -- Does not cover the human readable reload parts of extra.e\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">known_files</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">kfc</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">columnize</span><span style=\"color: #0000FF;\">({</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"test3.c\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\"\"\n /*\n All lexical tokens - not syntactically correct, but that will\n have to wait until syntax analysis\n */\n /* Print */ print /* Sub */ -\n /* Putc */ putc /* Lss */ &lt;\n /* If */ if /* Gtr */ &gt;\n /* Else */ else /* Leq */ &lt;=\n /* While */ while /* Geq */ &gt;=\n /* Lbrace */ { /* Eq */ ==\n /* Rbrace */ } /* Neq */ !=\n /* Lparen */ ( /* And */ &&\n /* Rparen */ ) /* Or */ ||\n /* Uminus */ - /* Semi */ ;\n /* Not */ ! /* Comma */ ,\n /* Mul */ * /* Assign */ =\n /* Div */ / /* Integer */ 42\n /* Mod */ % /* String */ \"String literal\"\n /* Add */ + /* Ident */ variable_name\n /* character literal */ '\\n'\n /* character literal **/ '\\\\'\n /* character literal */ ' '\n \"\"\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"test4.c\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\"\"\n /*** test printing, embedded \\n and comments with lots of '*' ***/\n print(42);\n print(\"\\nHello World\\nGood Bye\\nok\\n\");\n print(\"Print a slash n - \\\\n.\\n\");\n \"\"\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"primes.c\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\"\"\n /*\n Simple prime number generator\n */\n count = 1;\n n = 1;\n limit = 100;\n while (n &lt; limit) {\n k=3;\n p=1;\n n=n+2;\n while ((k*k&lt;=n) && (p)) {\n p=n/k*k!=n;\n k=k+2;\n }\n if (p) {\n print(n, \" is prime\\n\");\n count = count + 1;\n }\n }\n print(\"Total primes found: \", count, \"\\n\");\n \"\"\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"gcd.c\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\"\"\n /* Compute the gcd of 1071, 1029: 21 */\n\n a = 1071;\n b = 1029;\n\n while (b != 0) {\n new_a = b;\n b = a % b;\n a = new_a;\n }\n print(a);\n \"\"\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"Header.h\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\"\"\n #define area(h, w) h * w\n \"\"\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"Source.t\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\"\"\n #include \"Header.h\"\n #define width 5\n #define height 6\n area = #area(height, width)#;\n \"\"\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)}})</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">linenos</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">known_files</span><span style=\"color: #0000FF;\">))</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">js_open</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">filename</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">fn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">filename</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">known_files</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">assert</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">linenos</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">fn</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">js_gets</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">lineno</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">linenos</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">]+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">lineno</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">kfc</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">linenos</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">lineno</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">kfc</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">lineno</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">EOF</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\\\rosetta\\\\Compiler\\\\lex.e\n -- ==============================\n --\n -- The reusable part of lex.exw\n -- This is only kept separate from core.e for consistency with later modules.</span>\n\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">core</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">line</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">col</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">eof</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">error</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%s in %s literal\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">EOF</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"EOF\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"EOL\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">col</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">oneline</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">EOF</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">EOF</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">col</span><span style=\"color: #0000FF;\">></span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">oneline</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">line</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">col</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #000000;\">oneline</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">JS</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">js_gets</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input_file</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">:</span><span style=\"color: #7060A8;\">gets</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input_file</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">oneline</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">col</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">ch</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- for pwa/p2js (JavaScript *really* dislikes tabs in strings):\n --constant whitespace = \" \\t\\r\\n\\x0B\\xA0\"</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">whitespace</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'\\t'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'\\r'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'\\n'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">#0B</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">#A0</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #000080;font-style:italic;\">-- (0x0B is Vertical Tab, 0xA0 is Non-breaking space)</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">skipspacesandcomments</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">whitespace</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'/'</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">col</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">oneline</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">oneline</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">col</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #008000;\">'*'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">tok_line</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">line</span> <span style=\"color: #000080;font-style:italic;\">-- (in case of EOF error)</span>\n <span style=\"color: #000000;\">tok_col</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">col</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #000080;font-style:italic;\">-- (can be EOF)</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #000080;font-style:italic;\">-- ( \"\" )</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'*'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'/'</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">EOF</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">error</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"EOF in comment\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">escape_char</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #000080;font-style:italic;\">-- (discard the '\\\\')</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'n'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">'\\n'</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'\\\\'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">'\\\\'</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">EOF</span>\n <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'\\n'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">eof</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">error</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">`unknown escape sequence \\%c`</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">ch</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">char_lit</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">startch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span> <span style=\"color: #000080;font-style:italic;\">-- (skip opening quote, save res)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">startch</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">error</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"empty character constant\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'\\\\'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">escape_char</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"character\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">EOF</span>\n <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'\\n'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">eof</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"character\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">startch</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">error</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"multi-character constant\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">tk_Integer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">string_lit</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">startch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">ch</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">text</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #000000;\">startch</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">EOF</span>\n <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'\\n'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">eof</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"string\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'\\\\'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">escape_char</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"string\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">text</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">ch</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">tk_String</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">text</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">get_op</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000080;font-style:italic;\">-- sequence operator = {ch}</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">operator</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">ch</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">charmap</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">OPERATOR</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">operator</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">operators</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000080;font-style:italic;\">-- (^ ie/eg merge \"&gt;=\", but not \");\")</span>\n <span style=\"color: #000000;\">operator</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">ch</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">operator</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">operators</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">error</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"unknown operator\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">opcodes</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- (0 unused)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">get_int</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">charmap</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">DIGIT</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">10</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #008000;\">'0'</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">charmap</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">LETTER</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">error</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"invalid number\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">tk_Integer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">get_ident</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">text</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">charmap</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">],{</span><span style=\"color: #000000;\">LETTER</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">DIGIT</span><span style=\"color: #0000FF;\">})</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">text</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">ch</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next_ch</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">keyword</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">getd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">text</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">KEYWORDS</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">keyword</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #004600;\">NULL</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">keyword</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- (0 unused)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">tk_Identifier</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">text</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">get_token</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">skipspacesandcomments</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">tok_line</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">line</span>\n <span style=\"color: #000000;\">tok_col</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">col</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">ch</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">EOF</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">tk_EOI</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- (0 unused)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008000;\"><nowiki>'\\''</nowiki></span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">char_lit</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008000;\">'\"'</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">string_lit</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">charmap</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">OPERATOR</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">get_op</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">DIGIT</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">get_int</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">LETTER</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">get_ident</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">else</span> <span style=\"color: #000000;\">error</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"unrecognized character: (%d)\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">global</span> <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">lex</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">toks</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">tok</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">v</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">tok</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">tk_EOI</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">tok</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">get_token</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">toks</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">toks</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">tok_line</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tok_col</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tok</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">toks</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n<!--\n", "language": "Phix" }, { "code": "-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Compiler\\extra.e\n -- =============================\n --\n -- Routines to reload human-readable files (deviation from task requirement)\n --</span>\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span> <span style=\"color: #000080;font-style:italic;\">-- (file i/o)\n\n --The following can be used to load .lex files, as created by lex.exw:\n -- (in place of the existing get_tok() in parse.e)</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">get_tok</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">line</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">trim</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">gets</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input_file</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tok</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">limit</span><span style=\"color: #0000FF;\">:=</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">no_empty</span><span style=\"color: #0000FF;\">:=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tok</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">tkNames</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">tok</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">k</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">tok</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n\n <span style=\"color: #000080;font-style:italic;\">--The following can be used to load .ast files, as created by parse.exw:\n -- (in place of the existing lex()/parse() pairs in cgen.exw and interp.exw)</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">load_ast</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">line</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">trim</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">gets</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input_file</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000080;font-style:italic;\">-- Each line has at least one token</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">node</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">limit</span><span style=\"color: #0000FF;\">:=</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">no_empty</span><span style=\"color: #0000FF;\">:=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">node_type</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">node</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">node_type</span> <span style=\"color: #0000FF;\">==</span> <span style=\"color: #008000;\">\";\"</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000080;font-style:italic;\">-- a terminal node</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">NULL</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n_type</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">node_type</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tkNames</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- A line with two tokens is a leaf node\n -- Leaf nodes are: Identifier, Integer, String\n -- The 2nd token is the value</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">node</span><span style=\"color: #0000FF;\">)></span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">node</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">n_type</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">tk_Integer</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">node</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">to_integer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">node</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">tk_String</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">node</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">unquote</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">node</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">node</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">left</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">load_ast</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">right</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">load_ast</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">n_type</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">left</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">right</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Compiler\\lex.exw\n -- =============================\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">lex</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cl</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">open_files</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cl</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">toks</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">lex</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">tok</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">v</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">toks</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">tok_line</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tok_col</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tok</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">toks</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">tok</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Identifier</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">v</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\" %s\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_Integer</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">v</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\" %5d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">tk_String</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">v</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\" %s\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">enquote</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">else</span> <span style=\"color: #000000;\">v</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">output_file</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"%5d %5d %-10s%s\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">tok_line</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tok_col</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tkNames</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">tok</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">close_files</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000080;font-style:italic;\">--main(command_line())</span>\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"test4.c\"</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "/*\n Test harness for the analyzer, not needed if we are actually using the output.\n*/\nload_file(File, Input) :-\n\tread_file_to_codes(File, Codes, []),\n\tmaplist(char_code, Chars, Codes),\n\tatom_chars(Input,Chars).\n\ntest_file(File) :-\n\tload_file(File, Input),\n\ttester(Input).\n\ntester(S) :-\n\tatom_chars(S,Chars),\n\ttokenize(Chars,L),\n\tmaplist(print_tok, L),\n\t!.\n\nprint_tok(L) :-\n\tL =.. [Op,Line,Pos],\n\tformat('~d\\t~d\\t~p~n', [Line,Pos,Op]).\nprint_tok(string(Value,Line,Pos)) :-\n\tformat('~d\\t~d\\tstring\\t\\t\"~w\"~n', [Line,Pos,Value]).\t\nprint_tok(identifier(Value,Line,Pos)) :-\n\tformat('~d\\t~d\\tidentifier\\t~p~n', [Line,Pos,Value]).\t\nprint_tok(integer(Value,Line,Pos)) :-\n\tformat('~d\\t~d\\tinteger\\t\\t~p~n', [Line,Pos,Value]).\t\n\n\n/*\n\tTokenize\n\t\n\trun the input over a DCG to get out the tokens.\n\t\n\tIn - a list of chars to tokenize\n\tTokens = a list of tokens (excluding spaces).\n*/\ntokenize(In,RelTokens) :-\n\tnewline_positions(In,1,NewLines),\n\ttokenize(In,[0|NewLines],1,1,Tokens),\n\tcheck_for_exceptions(Tokens),\n\texclude(token_name(space),Tokens,RelTokens).\n\ntokenize([],NewLines,Pos,LineNo,[end_of_input(LineNo,Offset)]) :-\n\tposition_offset(NewLines,Pos,Offset).\ntokenize(In,NewLines,Pos,LineNo,Out) :-\n\tposition_offset(NewLines,Pos,Offset),\n\tphrase(tok(Tok,TokLen,LineNo,Offset),In,T),\n\t(\n\t\tTok = [] -> Out = Toks\n\t\t; Out = [Tok|Toks]\n\t),\n\tPos1 is Pos + TokLen,\n\tupdate_line_no(LineNo,NewLines,Pos1,NewLineNo,NewNewLines),\n\ttokenize(T,NewNewLines,Pos1,NewLineNo,Toks).\n\t\nupdate_line_no(LNo,[L],_,LNo,[L]).\nupdate_line_no(LNo,[L,Nl|T],Pos,LNo,[L,Nl|T]) :-\n\tPos =< Nl.\nupdate_line_no(LNo,[_,Nl|T],Pos,LNo2,Nlines) :-\n\tPos > Nl,\n\tsucc(LNo,LNo1),\n\tupdate_line_no(LNo1,[Nl|T],Pos,LNo2,Nlines).\n\nposition_offset([Line|_],Pos,Offset) :- Offset is Pos - Line.\t\n\t\ntoken_name(Name,Tok) :- functor(Tok,Name,_).\t\n\n% Get a list of all the newlines and their position in the data\n% This is used to create accurate row/column numbers. \t\nnewline_positions([],N,[N]).\nnewline_positions(['\\n'|T],N,[N|Nt]) :- succ(N,N1), newline_positions(T,N1,Nt).\nnewline_positions([C|T],N,Nt) :- dif(C,'\\n'), succ(N,N1), newline_positions(T,N1,Nt).\t\n\t\n% The tokenizer can tokenize some things that it shouldn't, deal with them here. \t\ncheck_for_exceptions([]). % all ok\ncheck_for_exceptions([op_divide(L,P),op_multiply(_,_)|_]) :-\n\tformat(atom(Error), 'Unclosed comment at line ~d,~d', [L,P]),\n\tthrow(Error).\ncheck_for_exceptions([integer(_,L,P),identifier(_,_,_)|_]) :-\n\tformat(atom(Error), 'Invalid identifier at line ~d,~d', [L,P]),\n\tthrow(Error).\t\ncheck_for_exceptions([_|T]) :- check_for_exceptions(T).\t\n\n\n/*\n\tA set of helper DCGs for the more complicated token types\n*/\t\n:- set_prolog_flag(double_quotes, chars).\n\nidentifier(I) --> c_types(I,csym).\nidentifier(['_']) --> ['_'].\nidentifier([]) --> [].\n\ninteger_(I,L) --> c_types(N,digit), { number_codes(I,N), length(N,L) }.\n\n% get a sequence of characters of the same type (https://www.swi-prolog.org/pldoc/doc_for?object=char_type/2)\nc_types([C|T],Type) --> c_type(C,Type), c_types(T,Type).\nc_types([C],Type) --> c_type(C,Type).\nc_type(C,Type) --> [C],{ char_type(C,Type) }.\n\nanything([]) --> [].\nanything([A|T]) --> [A], anything(T).\n\nstring_([]) --> [].\nstring_([A|T]) --> [A], { dif(A,'\\n') }, string_(T).\n\n\n/*\n\tThe token types are all handled by the tok DCG, order of predicates is important here.\n*/\t\n% comment\ntok([],CLen,_,_) --> \"/*\", anything(A), \"*/\", { length(A,Len), CLen is Len + 4 }.\n\n% toks\ntok(op_and(L,P),2,L,P) --> \"&&\".\ntok(op_or(L,P),2,L,P) --> \"||\".\ntok(op_lessequal(L,P),2,L,P) --> \"<=\".\ntok(op_greaterequal(L,P),2,L,P) --> \">=\".\ntok(op_greaterequal(L,P),2,L,P) --> \">=\".\ntok(op_equal(L,P),2,L,P) --> \"==\".\ntok(op_notequal(L,P),2,L,P) --> \"!=\".\ntok(op_assign(L,P),1,L,P) --> \"=\".\ntok(op_multiply(L,P),1,L,P) --> \"*\".\ntok(op_divide(L,P),1,L,P) --> \"/\".\ntok(op_mod(L,P),1,L,P) --> \"%\".\ntok(op_add(L,P),1,L,P) --> \"+\".\ntok(op_subtract(L,P),1,L,P) --> \"-\".\ntok(op_negate(L,P),1,L,P) --> \"-\".\ntok(op_less(L,P),1,L,P) --> \"<\".\ntok(op_greater(L,P),1,L,P) --> \">\".\ntok(op_not(L,P),1,L,P) --> \"!\".\n\n% symbols\ntok(left_paren(L,P),1,L,P) --> \"(\".\ntok(right_paren(L,P),1,L,P) --> \")\".\ntok(left_brace(L,P),1,L,P) --> \"{\".\ntok(right_brace(L,P),1,L,P) --> \"}\".\ntok(semicolon(L,P),1,L,P) --> \";\".\ntok(comma(L,P),1,L,P) --> \",\".\n\n% keywords\ntok(keyword_if(L,P),2,L,P) --> \"if\".\ntok(keyword_else(L,P),4,L,P) --> \"else\".\ntok(keyword_while(L,P),5,L,P) --> \"while\".\ntok(keyword_print(L,P),5,L,P) --> \"print\".\ntok(keyword_putc(L,P),4,L,P) --> \"putc\".\n\n% identifier and literals\ntok(identifier(I,L,P),Len,L,P) --> c_type(S,csymf), identifier(T), { atom_chars(I,[S|T]), length([S|T],Len) }.\ntok(integer(V,L,P),Len,L,P) --> integer_(V,Len).\ntok(integer(I,L,P),4,L,P) --> \"'\\\\\\\\'\", { char_code('\\\\', I) }.\ntok(integer(I,L,P),4,L,P) --> \"'\\\\n'\", { char_code('\\n', I) }.\ntok(integer(I,L,P),3,L,P) --> ['\\''], [C], ['\\''], { dif(C,'\\n'), dif(C,'\\''), char_code(C,I) }.\ntok(string(S,L,P),SLen,L,P) --> ['\"'], string_(A),['\"'], { atom_chars(S,A), length(A,Len), SLen is Len + 2 }.\n\n% spaces\ntok(space(L,P),Len,L,P) --> c_types(S,space), { length(S,Len) }.\n\n% anything else is an error\ntok(_,_,L,P) --> { format(atom(Error), 'Invalid token at line ~d,~d', [L,P]), throw(Error) }.\n", "language": "Prolog" }, { "code": "from __future__ import print_function\nimport sys\n\n# following two must remain in the same order\n\ntk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, \\\ntk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, \\\ntk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident, \\\ntk_Integer, tk_String = range(31)\n\nall_syms = [\"End_of_input\", \"Op_multiply\", \"Op_divide\", \"Op_mod\", \"Op_add\", \"Op_subtract\",\n \"Op_negate\", \"Op_not\", \"Op_less\", \"Op_lessequal\", \"Op_greater\", \"Op_greaterequal\",\n \"Op_equal\", \"Op_notequal\", \"Op_assign\", \"Op_and\", \"Op_or\", \"Keyword_if\",\n \"Keyword_else\", \"Keyword_while\", \"Keyword_print\", \"Keyword_putc\", \"LeftParen\",\n \"RightParen\", \"LeftBrace\", \"RightBrace\", \"Semicolon\", \"Comma\", \"Identifier\",\n \"Integer\", \"String\"]\n\n# single character only symbols\nsymbols = { '{': tk_Lbrace, '}': tk_Rbrace, '(': tk_Lparen, ')': tk_Rparen, '+': tk_Add, '-': tk_Sub,\n '*': tk_Mul, '%': tk_Mod, ';': tk_Semi, ',': tk_Comma }\n\nkey_words = {'if': tk_If, 'else': tk_Else, 'print': tk_Print, 'putc': tk_Putc, 'while': tk_While}\n\nthe_ch = \" \" # dummy first char - but it must be a space\nthe_col = 0\nthe_line = 1\ninput_file = None\n\n#*** show error and exit\ndef error(line, col, msg):\n print(line, col, msg)\n exit(1)\n\n#*** get the next character from the input\ndef next_ch():\n global the_ch, the_col, the_line\n\n the_ch = input_file.read(1)\n the_col += 1\n if the_ch == '\\n':\n the_line += 1\n the_col = 0\n return the_ch\n\n#*** 'x' - character constants\ndef char_lit(err_line, err_col):\n n = ord(next_ch()) # skip opening quote\n if the_ch == '\\'':\n error(err_line, err_col, \"empty character constant\")\n elif the_ch == '\\\\':\n next_ch()\n if the_ch == 'n':\n n = 10\n elif the_ch == '\\\\':\n n = ord('\\\\')\n else:\n error(err_line, err_col, \"unknown escape sequence \\\\%c\" % (the_ch))\n if next_ch() != '\\'':\n error(err_line, err_col, \"multi-character constant\")\n next_ch()\n return tk_Integer, err_line, err_col, n\n\n#*** process divide or comments\ndef div_or_cmt(err_line, err_col):\n if next_ch() != '*':\n return tk_Div, err_line, err_col\n\n # comment found\n next_ch()\n while True:\n if the_ch == '*':\n if next_ch() == '/':\n next_ch()\n return gettok()\n elif len(the_ch) == 0:\n error(err_line, err_col, \"EOF in comment\")\n else:\n next_ch()\n\n#*** \"string\"\ndef string_lit(start, err_line, err_col):\n global the_ch\n text = \"\"\n\n while next_ch() != start:\n if len(the_ch) == 0:\n error(err_line, err_col, \"EOF while scanning string literal\")\n if the_ch == '\\n':\n error(err_line, err_col, \"EOL while scanning string literal\")\n if the_ch == '\\\\':\n next_ch()\n if the_ch != 'n':\n error(err_line, err_col, \"escape sequence unknown \\\\%c\" % the_ch)\n the_ch = '\\n'\n text += the_ch\n\n next_ch()\n return tk_String, err_line, err_col, text\n\n#*** handle identifiers and integers\ndef ident_or_int(err_line, err_col):\n is_number = True\n text = \"\"\n\n while the_ch.isalnum() or the_ch == '_':\n text += the_ch\n if not the_ch.isdigit():\n is_number = False\n next_ch()\n\n if len(text) == 0:\n error(err_line, err_col, \"ident_or_int: unrecognized character: (%d) '%c'\" % (ord(the_ch), the_ch))\n\n if text[0].isdigit():\n if not is_number:\n error(err_line, err_col, \"invalid number: %s\" % (text))\n n = int(text)\n return tk_Integer, err_line, err_col, n\n\n if text in key_words:\n return key_words[text], err_line, err_col\n\n return tk_Ident, err_line, err_col, text\n\n#*** look ahead for '>=', etc.\ndef follow(expect, ifyes, ifno, err_line, err_col):\n if next_ch() == expect:\n next_ch()\n return ifyes, err_line, err_col\n\n if ifno == tk_EOI:\n error(err_line, err_col, \"follow: unrecognized character: (%d) '%c'\" % (ord(the_ch), the_ch))\n\n return ifno, err_line, err_col\n\n#*** return the next token type\ndef gettok():\n while the_ch.isspace():\n next_ch()\n\n err_line = the_line\n err_col = the_col\n\n if len(the_ch) == 0: return tk_EOI, err_line, err_col\n elif the_ch == '/': return div_or_cmt(err_line, err_col)\n elif the_ch == '\\'': return char_lit(err_line, err_col)\n elif the_ch == '<': return follow('=', tk_Leq, tk_Lss, err_line, err_col)\n elif the_ch == '>': return follow('=', tk_Geq, tk_Gtr, err_line, err_col)\n elif the_ch == '=': return follow('=', tk_Eq, tk_Assign, err_line, err_col)\n elif the_ch == '!': return follow('=', tk_Neq, tk_Not, err_line, err_col)\n elif the_ch == '&': return follow('&', tk_And, tk_EOI, err_line, err_col)\n elif the_ch == '|': return follow('|', tk_Or, tk_EOI, err_line, err_col)\n elif the_ch == '\"': return string_lit(the_ch, err_line, err_col)\n elif the_ch in symbols:\n sym = symbols[the_ch]\n next_ch()\n return sym, err_line, err_col\n else: return ident_or_int(err_line, err_col)\n\n#*** main driver\ninput_file = sys.stdin\nif len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], \"r\", 4096)\n except IOError as e:\n error(0, 0, \"Can't open %s\" % sys.argv[1])\n\nwhile True:\n t = gettok()\n tok = t[0]\n line = t[1]\n col = t[2]\n\n print(\"%5d %5d %-14s\" % (line, col, all_syms[tok]), end='')\n\n if tok == tk_Integer: print(\" %5d\" % (t[3]))\n elif tok == tk_Ident: print(\" %s\" % (t[3]))\n elif tok == tk_String: print(' \"%s\"' % (t[3]))\n else: print(\"\")\n\n if tok == tk_EOI:\n break\n", "language": "Python" }, { "code": "dim shared source as string, the_ch as string, tok as string, toktyp as string\ndim shared line_n as integer, col_n as integer, text_p as integer, err_line as integer, err_col as integer, errors as integer\n\ndeclare function isalnum&(s as string)\ndeclare function isalpha&(s as string)\ndeclare function isdigit&(s as string)\ndeclare sub divide_or_comment\ndeclare sub error_exit(line_n as integer, col_n as integer, msg as string)\ndeclare sub follow(c as string, typ2 as string, typ1 as string)\ndeclare sub nextch\ndeclare sub nexttok\ndeclare sub read_char_lit\ndeclare sub read_ident\ndeclare sub read_number\ndeclare sub read_string\n\nconst c_integer = \"Integer\", c_ident = \"Identifier\", c_string = \"String\"\n\ndim out_fn as string, out_tok as string\n\nif command$(1) = \"\" then print \"Expecting a filename\": end\nopen command$(1) for binary as #1\nsource = space$(lof(1))\nget #1, 1, source\nclose #1\n\nout_fn = command$(2): if out_fn <> \"\" then open out_fn for output as #1\n\nline_n = 1: col_n = 0: text_p = 1: the_ch = \" \"\n\ndo\n call nexttok\n select case toktyp\n case c_integer, c_ident, c_string: out_tok = tok\n case else: out_tok = \"\"\n end select\n if out_fn = \"\" then\n print err_line, err_col, toktyp, out_tok\n else\n print #1, err_line, err_col, toktyp, out_tok\n end if\nloop until errors or tok = \"\"\nif out_fn <> \"\" then close #1\nend\n\n' get next tok, toktyp\nsub nexttok\n toktyp = \"\"\n restart: err_line = line_n: err_col = col_n: tok = the_ch\n select case the_ch\n case \" \", chr$(9), chr$(10): call nextch: goto restart\n case \"/\": call divide_or_comment: if tok = \"\" then goto restart\n\n case \"%\": call nextch: toktyp = \"Op_mod\"\n case \"(\": call nextch: toktyp = \"LeftParen\"\n case \")\": call nextch: toktyp = \"RightParen\"\n case \"*\": call nextch: toktyp = \"Op_multiply\"\n case \"+\": call nextch: toktyp = \"Op_add\"\n case \",\": call nextch: toktyp = \"Comma\"\n case \"-\": call nextch: toktyp = \"Op_subtract\"\n case \";\": call nextch: toktyp = \"Semicolon\"\n case \"{\": call nextch: toktyp = \"LeftBrace\"\n case \"}\": call nextch: toktyp = \"RightBrace\"\n\n case \"&\": call follow(\"&\", \"Op_and\", \"\")\n case \"|\": call follow(\"|\", \"Op_or\", \"\")\n case \"!\": call follow(\"=\", \"Op_notequal\", \"Op_not\")\n case \"<\": call follow(\"=\", \"Op_lessequal\", \"Op_less\")\n case \"=\": call follow(\"=\", \"Op_equal\", \"Op_assign\")\n case \">\": call follow(\"=\", \"Op_greaterequal\", \"Op_greater\")\n\n case chr$(34): call read_string\n case chr$(39): call read_char_lit\n\n case \"\": toktyp = \"End_of_input\"\n\n case else\n if isdigit&(the_ch) then\n call read_number\n elseif isalpha&(the_ch) then\n call read_ident\n else\n call nextch\n end if\n end select\nend sub\n\nsub follow(c as string, if_both as string, if_one as string)\n call nextch\n if the_ch = c then\n tok = tok + the_ch\n call nextch\n toktyp = if_both\n else\n if if_one = \"\" then call error_exit(line_n, col_n, \"Expecting \" + c): exit sub\n toktyp = if_one\n end if\nend sub\n\nsub read_string\n toktyp = c_string\n call nextch\n do\n tok = tok + the_ch\n select case the_ch\n case chr$(10): call error_exit(line_n, col_n, \"EOL in string\"): exit sub\n case \"\": call error_exit(line_n, col_n, \"EOF in string\"): exit sub\n case chr$(34): call nextch: exit sub\n case else: call nextch\n end select\n loop\nend sub\n\nsub read_char_lit\n toktyp = c_integer\n call nextch\n if the_ch = chr$(39) then\n call error_exit(err_line, err_col, \"Empty character constant\"): exit sub\n end if\n\n if the_ch = \"\\\" then\n call nextch\n if the_ch = \"n\" then\n tok = \"10\"\n elseif the_ch = \"\\\" then\n tok = \"92\"\n else\n call error_exit(line_n, col_n, \"Unknown escape sequence:\" + the_ch): exit sub\n end if\n else\n tok = ltrim$(str$(asc(the_ch)))\n end if\n\n call nextch\n if the_ch <> chr$(39) then\n call error_exit(line_n, col_n, \"Multi-character constant\"): exit sub\n end if\n call nextch\nend sub\n\nsub divide_or_comment\n call nextch\n if the_ch <> \"*\" then\n toktyp = \"Op_divide\"\n else ' skip comments\n tok = \"\"\n call nextch\n do\n if the_ch = \"*\" then\n call nextch\n if the_ch = \"/\" then\n call nextch\n exit sub\n end if\n elseif the_ch = \"\" then\n call error_exit(line_n, col_n, \"EOF in comment\"): exit sub\n else\n call nextch\n end if\n loop\n end if\nend sub\n\nsub read_ident\n do\n call nextch\n if not isalnum&(the_ch) then exit do\n tok = tok + the_ch\n loop\n select case tok\n case \"else\": toktyp = \"keyword_else\"\n case \"if\": toktyp = \"keyword_if\"\n case \"print\": toktyp = \"keyword_print\"\n case \"putc\":: toktyp = \"keyword_putc\"\n case \"while\": toktyp = \"keyword_while\"\n case else: toktyp = c_ident\n end select\nend sub\n\nsub read_number\n toktyp = c_integer\n do\n call nextch\n if not isdigit&(the_ch) then exit do\n tok = tok + the_ch\n loop\n\n if isalpha&(the_ch) then\n call error_exit(err_line, err_col, \"Bogus number: \" + tok + the_ch): exit sub\n end if\nend sub\n\nfunction isalpha&(s as string)\n dim c as string\n c = left$(s, 1)\n isalpha& = c <> \"\" and instr(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_\", c) > 0\nend function\n\nfunction isdigit&(s as string)\n dim c as string\n c = left$(s, 1)\n isdigit& = c <> \"\" and instr(\"0123456789\", c) > 0\nend function\n\nfunction isalnum&(s as string)\n dim c as string\n c = left$(s, 1)\n isalnum& = c <> \"\" and instr(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\", c) > 0\nend function\n\n' get next char - fold cr/lf into just lf\nsub nextch\n the_ch = \"\"\n col_n = col_n + 1\n if text_p > len(source) then exit sub\n\n the_ch = mid$(source, text_p, 1)\n text_p = text_p + 1\n\n if the_ch = chr$(13) then\n the_ch = chr$(10)\n if text_p <= len(source) then\n if mid$(source, text_p, 1) = chr$(10) then\n text_p = text_p + 1\n end if\n end if\n end if\n\n if the_ch = chr$(10) then\n line_n = line_n + 1\n col_n = 0\n end if\n\nend sub\n\nsub error_exit(line_n as integer, col_n as integer, msg as string)\n errors = -1\n print line_n, col_n, msg\n end\nend sub\n", "language": "QB64" }, { "code": "#lang racket\n(require parser-tools/lex)\n\n(define-lex-abbrevs\n [letter (union (char-range #\\a #\\z) (char-range #\\A #\\Z))]\n [digit (char-range #\\0 #\\9)]\n [underscore #\\_]\n [identifier (concatenation (union letter underscore)\n (repetition 0 +inf.0 (union letter digit underscore)))]\n [integer (repetition 1 +inf.0 digit)]\n [char-content (char-complement (char-set \"'\\n\"))]\n [char-literal (union (concatenation #\\' char-content #\\')\n \"'\\\\n'\" \"'\\\\\\\\'\")]\n [string-content (union (char-complement (char-set \"\\\"\\n\")))]\n [string-literal (union (concatenation #\\\" (repetition 0 +inf.0 string-content) #\\\")\n \"\\\"\\\\n\\\"\" \"\\\"\\\\\\\\\\\"\")]\n [keyword (union \"if\" \"else\" \"while\" \"print\" \"putc\")]\n [operator (union \"*\" \"/\" \"%\" \"+\" \"-\" \"-\"\n \"<\" \"<=\" \">\" \">=\" \"==\" \"!=\"\n \"!\" \"=\" \"&&\" \"||\")]\n [symbol (union \"(\" \")\" \"{\" \"}\" \";\" \",\")]\n [comment (concatenation \"/*\" (complement (concatenation any-string \"*/\" any-string)) \"*/\")])\n\n(define operators-ht\n (hash \"*\" 'Op_multiply \"/\" 'Op_divide \"%\" 'Op_mod \"+\" 'Op_add \"-\" 'Op_subtract\n \"<\" 'Op_less \"<=\" 'Op_lessequal \">\" 'Op_greater \">=\" 'Op_greaterequal \"==\" 'Op_equal\n \"!=\" 'Op_notequal \"!\" 'Op_not \"=\" 'Op_assign \"&&\" 'Op_and \"||\" 'Op_or))\n\n(define symbols-ht\n (hash \"(\" 'LeftParen \")\" 'RightParen\n \"{\" 'LeftBrace \"}\" 'RightBrace\n \";\" 'Semicolon \",\" 'Comma))\n\n(define (lexeme->keyword l) (string->symbol (~a \"Keyword_\" l)))\n(define (lexeme->operator l) (hash-ref operators-ht l))\n(define (lexeme->symbol l) (hash-ref symbols-ht l))\n(define (lexeme->char l) (match l\n [\"'\\\\\\\\'\" #\\\\]\n [\"'\\\\n'\" #\\newline]\n [_ (string-ref l 1)]))\n\n(define (token name [value #f])\n (cons name (if value (list value) '())))\n\n(define (lex ip)\n (port-count-lines! ip)\n (define my-lexer\n (lexer-src-pos\n [integer (token 'Integer (string->number lexeme))]\n [char-literal (token 'Integer (char->integer (lexeme->char lexeme)))]\n [string-literal (token 'String lexeme)]\n [keyword (token (lexeme->keyword lexeme))]\n [operator (token (lexeme->operator lexeme))]\n [symbol (token (lexeme->symbol lexeme))]\n [comment #f]\n [whitespace #f]\n [identifier (token 'Identifier lexeme)]\n [(eof) (token 'End_of_input)]))\n (define (next-token) (my-lexer ip))\n next-token)\n\n(define (string->tokens s)\n (port->tokens (open-input-string s)))\n\n(define (port->tokens ip)\n (define next-token (lex ip))\n (let loop ()\n (match (next-token)\n [(position-token t (position offset line col) _)\n (set! col (+ col 1)) ; output is 1-based\n (match t\n [#f (loop)] ; skip whitespace/comments\n [(list 'End_of_input) (list (list line col 'End_of_input))]\n [(list name value) (cons (list line col name value) (loop))]\n [(list name) (cons (list line col name) (loop))]\n [_ (error)])])))\n\n(define test1 #<<TEST\n/*\n Hello world\n */\nprint(\"Hello, World!\\n\");\n\nTEST\n)\n\n(define test2 #<<TEST\n/*\n Show Ident and Integers\n */\nphoenix_number = 142857;\nprint(phoenix_number, \"\\n\");\n\nTEST\n )\n\n(define test3 #<<TEST\n/*\n All lexical tokens - not syntactically correct, but that will\n have to wait until syntax analysis\n */\n/* Print */ print /* Sub */ -\n/* Putc */ putc /* Lss */ <\n/* If */ if /* Gtr */ >\n/* Else */ else /* Leq */ <=\n/* While */ while /* Geq */ >=\n/* Lbrace */ { /* Eq */ ==\n/* Rbrace */ } /* Neq */ !=\n/* Lparen */ ( /* And */ &&\n/* Rparen */ ) /* Or */ ||\n/* Uminus */ - /* Semi */ ;\n/* Not */ ! /* Comma */ ,\n/* Mul */ * /* Assign */ =\n/* Div */ / /* Integer */ 42\n/* Mod */ % /* String */ \"String literal\"\n/* Add */ + /* Ident */ variable_name\n/* character literal */ '\\n'\n/* character literal */ '\\\\'\n/* character literal */ ' '\nTEST\n )\n\n(define test4 #<<TEST\n/*** test printing, embedded \\n and comments with lots of '*' ***/\nprint(42);\nprint(\"\\nHello World\\nGood Bye\\nok\\n\");\nprint(\"Print a slash n - \\\\n.\\n\");\nTEST\n )\n\n(define test5 #<<TEST\ncount = 1;\nwhile (count < 10) {\n print(\"count is: \", count, \"\\n\");\n count = count + 1;\n}\nTEST\n )\n\n(define (display-tokens ts)\n (for ([t ts])\n (for ([x t])\n (display x) (display \"\\t\\t\"))\n (newline)))\n\n\"TEST 1\"\n(display-tokens (string->tokens test1))\n\"TEST 2\"\n(display-tokens (string->tokens test2))\n\"TEST 3\"\n(display-tokens (string->tokens test3))\n\"TEST 4\"\n(display-tokens (string->tokens test4))\n\"TEST 5\"\n(display-tokens (string->tokens test5))\n", "language": "Racket" }, { "code": "grammar tiny_C {\n rule TOP { ^ <.whitespace>? <tokens> + % <.whitespace> <.whitespace> <eoi> }\n\n rule whitespace { [ <comment> + % <ws> | <ws> ] }\n\n token comment { '/*' ~ '*/' .*? }\n\n token tokens {\n [\n | <operator> { make $/<operator>.ast }\n | <keyword> { make $/<keyword>.ast }\n | <symbol> { make $/<symbol>.ast }\n | <identifier> { make $/<identifier>.ast }\n | <integer> { make $/<integer>.ast }\n | <char> { make $/<char>.ast }\n | <string> { make $/<string>.ast }\n | <error>\n ]\n }\n\n proto token operator {*}\n token operator:sym<*> { '*' { make 'Op_multiply' } }\n token operator:sym</> { '/'<!before '*'> { make 'Op_divide' } }\n token operator:sym<%> { '%' { make 'Op_mod' } }\n token operator:sym<+> { '+' { make 'Op_add' } }\n token operator:sym<-> { '-' { make 'Op_subtract' } }\n token operator:sym('<='){ '<=' { make 'Op_lessequal' } }\n token operator:sym('<') { '<' { make 'Op_less' } }\n token operator:sym('>='){ '>=' { make 'Op_greaterequal'} }\n token operator:sym('>') { '>' { make 'Op_greater' } }\n token operator:sym<==> { '==' { make 'Op_equal' } }\n token operator:sym<!=> { '!=' { make 'Op_notequal' } }\n token operator:sym<!> { '!' { make 'Op_not' } }\n token operator:sym<=> { '=' { make 'Op_assign' } }\n token operator:sym<&&> { '&&' { make 'Op_and' } }\n token operator:sym<||> { '||' { make 'Op_or' } }\n\n proto token keyword {*}\n token keyword:sym<if> { 'if' { make 'Keyword_if' } }\n token keyword:sym<else> { 'else' { make 'Keyword_else' } }\n token keyword:sym<putc> { 'putc' { make 'Keyword_putc' } }\n token keyword:sym<while> { 'while' { make 'Keyword_while' } }\n token keyword:sym<print> { 'print' { make 'Keyword_print' } }\n\n proto token symbol {*}\n token symbol:sym<(> { '(' { make 'LeftParen' } }\n token symbol:sym<)> { ')' { make 'RightParen' } }\n token symbol:sym<{> { '{' { make 'LeftBrace' } }\n token symbol:sym<}> { '}' { make 'RightBrace' } }\n token symbol:sym<;> { ';' { make 'Semicolon' } }\n token symbol:sym<,> { ',' { make 'Comma' } }\n\n token identifier { <[_A..Za..z]><[_A..Za..z0..9]>* { make 'Identifier ' ~ $/ } }\n token integer { <[0..9]>+ { make 'Integer ' ~ $/ } }\n\n token char {\n '\\'' [<-[']> | '\\n' | '\\\\\\\\'] '\\''\n { make 'Char_Literal ' ~ $/.subst(\"\\\\n\", \"\\n\").substr(1, *-1).ord }\n }\n\n token string {\n '\"' <-[\"\\n]>* '\"' #'\n {\n make 'String ' ~ $/;\n note 'Error: Unknown escape sequence.' and exit if (~$/ ~~ m:r/ <!after <[\\\\]>>[\\\\<-[n\\\\]>]<!before <[\\\\]>> /);\n }\n }\n\n token eoi { $ { make 'End_of_input' } }\n\n token error {\n | '\\'''\\'' { note 'Error: Empty character constant.' and exit }\n | '\\'' <-[']> ** {2..*} '\\'' { note 'Error: Multi-character constant.' and exit }\n | '/*' <-[*]>* $ { note 'Error: End-of-file in comment.' and exit }\n | '\"' <-[\"]>* $ { note 'Error: End-of-file in string.' and exit }\n | '\"' <-[\"]>*? \\n { note 'Error: End of line in string.' and exit } #'\n }\n}\n\nsub parse_it ( $c_code ) {\n my $l;\n my @pos = gather for $c_code.lines>>.chars.kv -> $line, $v {\n take [ $line + 1, $_ ] for 1 .. ($v+1); # v+1 for newline\n $l = $line+2;\n }\n @pos.push: [ $l, 1 ]; # capture eoi\n\n for flat $c_code<tokens>.list, $c_code<eoi> -> $m {\n say join \"\\t\", @pos[$m.from].fmt('%3d'), $m.ast;\n }\n}\n\nmy $tokenizer = tiny_C.parse(@*ARGS[0].IO.slurp);\nparse_it( $tokenizer );\n", "language": "Raku" }, { "code": "######################################################################\n#\n# The Rosetta Code scanner in Ratfor 77.\n#\n#\n# How to deal with FORTRAN 77 input is a problem. I use formatted\n# input, treating each line as an array of type CHARACTER--regrettably\n# of no more than some predetermined, finite length. It is a very\n# simple method and presents no significant difficulties, aside from\n# the restriction on line length of the input.\n#\n#\n# On a POSIX platform, the program can be compiled with f2c and run\n# somewhat as follows:\n#\n# ratfor77 lex-in-ratfor.r > lex-in-ratfor.f\n# f2c -C -Nc40 lex-in-ratfor.f\n# cc -O lex-in-ratfor.c -lf2c\n# ./a.out < compiler-tests/primes.t\n#\n# With gfortran, a little differently:\n#\n# ratfor77 lex-in-ratfor.r > lex-in-ratfor.f\n# gfortran -O2 -fcheck=all -std=legacy lex-in-ratfor.f\n# ./a.out < compiler-tests/primes.t\n#\n#\n# I/O is strictly from default input and to default output, which, on\n# POSIX systems, usually correspond respectively to standard input and\n# standard output. (I did not wish to have to deal with unit numbers;\n# these are now standardized in ISO_FORTRAN_ENV, but that is not\n# available in FORTRAN 77.)\n#\n#---------------------------------------------------------------------\n\n# Some parameters you may with to modify.\n\ndefine(LINESZ, 256) # Size of an input line.\ndefine(OUTLSZ, 512) # Size of an output line.\ndefine(PSHBSZ, 10) # Size of the character pushback buffer.\ndefine(STRNSZ, 4096) # Size of the string pool.\n\n#---------------------------------------------------------------------\n\ndefine(EOF, -1)\ndefine(NEWLIN, 10) # Unix newline (the LF control character).\ndefine(BACKSL, 92) # ASCII backslash.\n\ndefine(ILINNO, 1) # Line number's index.\ndefine(ICOLNO, 2) # Column number's index.\n\ndefine(CHRSZ, 3) # See ILINNO and ICOLNO above.\ndefine(ICHRCD, 3) # Character code's index.\n\ndefine(TOKSZ, 5) # See ILINNO and ICOLNO above.\ndefine(ITOKNO, 3) # Token number's index.\ndefine(IARGIX, 4) # Index of the string pool index.\ndefine(IARGLN, 5) # Index of the string length.\n\ndefine(TKELSE, 0)\ndefine(TKIF, 1)\ndefine(TKPRNT, 2)\ndefine(TKPUTC, 3)\ndefine(TKWHIL, 4)\ndefine(TKMUL, 5)\ndefine(TKDIV, 6)\ndefine(TKMOD, 7)\ndefine(TKADD, 8)\ndefine(TKSUB, 9)\ndefine(TKNEG, 10)\ndefine(TKLT, 11)\ndefine(TKLE, 12)\ndefine(TKGT, 13)\ndefine(TKGE, 14)\ndefine(TKEQ, 15)\ndefine(TKNE, 16)\ndefine(TKNOT, 17)\ndefine(TKASGN, 18)\ndefine(TKAND, 19)\ndefine(TKOR, 20)\ndefine(TKLPAR, 21)\ndefine(TKRPAR, 22)\ndefine(TKLBRC, 23)\ndefine(TKRBRC, 24)\ndefine(TKSEMI, 25)\ndefine(TKCMMA, 26)\ndefine(TKID, 27)\ndefine(TKINT, 28)\ndefine(TKSTR, 29)\ndefine(TKEOI, 30)\n\ndefine(LOC10, 1) # Location of \"10\" in the string pool.\ndefine(LOC92, 3) # Location of \"92\" in the string pool.\n\n#---------------------------------------------------------------------\n\nsubroutine addstr (strngs, istrng, src, i0, n0, i, n)\n\n # Add a string to the string pool.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character src(*) # Source string.\n integer i0, n0 # Index and length in source string.\n integer i, n # Index and length in string pool.\n\n integer j\n\n if (STRNSZ < istrng + (n0 - 1))\n {\n write (*, '(''string pool exhausted'')')\n stop\n }\n for (j = 0; j < n0; j = j + 1)\n strngs(istrng + j) = src(i0 + j)\n i = istrng\n n = n0\n istrng = istrng + n0\nend\n\nsubroutine cpystr (strngs, i, n, dst, i0)\n\n # Copy a string from the string pool to an output string.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer i, n # Index and length in string pool.\n character dst(OUTLSZ) # Destination string.\n integer i0 # Index within destination string.\n\n integer j\n\n if (i0 < 1 || OUTLSZ < i0 + (n - 1))\n {\n write (*, '(''string boundary exceeded'')')\n stop\n }\n for (j = 0; j < n; j = j + 1)\n dst(i0 + j) = strngs(i + j)\nend\n\n#---------------------------------------------------------------------\n\nsubroutine getchr (line, linno, colno, pushbk, npshbk, chr)\n\n # Get a character, with its line number and column number.\n\n implicit none\n\n character line(LINESZ) # Input buffer.\n integer linno, colno # Current line and column numbers.\n integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer.\n integer npshbk # Number of characters pushed back.\n integer chr(CHRSZ)\n\n # End of file is indicated (as in C) by a negative \"char code\"\n # called \"EOF\".\n\n character*20 fmt\n integer stat\n integer chr1(CHRSZ)\n\n if (0 < npshbk)\n {\n chr(ICHRCD) = pushbk(ICHRCD, npshbk)\n chr(ILINNO) = pushbk(ILINNO, npshbk)\n chr(ICOLNO) = pushbk(ICOLNO, npshbk)\n npshbk = npshbk - 1\n }\n else if (colno <= LINESZ)\n {\n chr(ICHRCD) = ichar (line(colno))\n chr(ILINNO) = linno\n chr(ICOLNO) = colno\n colno = colno + 1\n }\n else\n {\n # Return a newline character.\n chr(ICHRCD) = NEWLIN\n chr(ILINNO) = linno\n chr(ICOLNO) = colno\n\n # Fetch a new line.\n linno = linno + 1\n colno = 1\n\n # Read a line of text as an array of characters.\n write (fmt, '(''('', I10, ''A1)'')') LINESZ\n read (*, fmt, iostat = stat) line\n\n if (stat != 0)\n {\n # If end of file has been reached, push an EOF.\n chr1(ICHRCD) = EOF\n chr1(ILINNO) = linno\n chr1(ICOLNO) = colno\n call pshchr (pushbk, npshbk, chr1)\n }\n }\nend\n\nsubroutine pshchr (pushbk, npshbk, chr)\n\n # Push back a character.\n\n implicit none\n\n integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer.\n integer npshbk # Number of characters pushed back.\n integer chr(CHRSZ)\n\n if (PSHBSZ <= npshbk)\n {\n write (*, '(''pushback buffer overfull'')')\n stop\n }\n npshbk = npshbk + 1\n pushbk(ICHRCD, npshbk) = chr(ICHRCD)\n pushbk(ILINNO, npshbk) = chr(ILINNO)\n pushbk(ICOLNO, npshbk) = chr(ICOLNO)\nend\n\nsubroutine getpos (line, linno, colno, pushbk, npshbk, ln, cn)\n\n # Get the position of the next character.\n\n implicit none\n\n character line(LINESZ) # Input buffer.\n integer linno, colno # Current line and column numbers.\n integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer.\n integer npshbk # Number of characters pushed back.\n integer ln, cn # The line and column nos. returned.\n\n integer chr(CHRSZ)\n\n call getchr (line, linno, colno, pushbk, npshbk, chr)\n ln = chr(ILINNO)\n cn = chr(ICOLNO)\n call pshchr (pushbk, npshbk, chr)\nend\n\n#---------------------------------------------------------------------\n\nfunction isspc (c)\n\n # Is c character code for a space?\n\n implicit none\n\n integer c\n logical isspc\n\n #\n # The following is correct for ASCII: 32 is the SPACE character, and\n # 9 to 13 are control characters commonly regarded as spaces.\n #\n # In Unicode these are all code points for spaces, but so are others\n # besides.\n #\n isspc = (c == 32 || (9 <= c && c <= 13))\nend\n\nfunction isdgt (c)\n\n # Is c character code for a digit?\n\n implicit none\n\n integer c\n logical isdgt\n\n isdgt = (ichar ('0') <= c && c <= ichar ('9'))\nend\n\nfunction isalph (c)\n\n # Is c character code for a letter?\n\n implicit none\n\n integer c\n logical isalph\n\n #\n # The following is correct for ASCII and Unicode, but not for\n # EBCDIC.\n #\n isalph = (ichar ('a') <= c && c <= ichar ('z')) _\n || (ichar ('A') <= c && c <= ichar ('Z'))\nend\n\nfunction isid0 (c)\n\n # Is c character code for the start of an identifier?\n\n implicit none\n\n integer c\n logical isid0\n\n logical isalph\n\n isid0 = isalph (c) || c == ichar ('_')\nend\n\nfunction isid1 (c)\n\n # Is c character code for the continuation of an identifier?\n\n implicit none\n\n integer c\n logical isid1\n\n logical isalph\n logical isdgt\n\n isid1 = isalph (c) || isdgt (c) || c == ichar ('_')\nend\n\n#---------------------------------------------------------------------\n\nfunction trimlf (str, n)\n\n # \"Trim left\" leading spaces.\n\n implicit none\n\n character str(*) # The string to \"trim\".\n integer n # The length.\n integer trimlf # The index of the first non-space\n # character, or n + 1.\n\n logical isspc\n\n integer j\n logical done\n\n j = 1\n done = .false.\n while (!done)\n {\n if (j == n + 1)\n done = .true.\n else if (!isspc (ichar (str(j))))\n done = .true.\n else\n j = j + 1\n }\n trimlf = j\nend\n\nfunction trimrt (str, n)\n\n # \"Trim right\" trailing spaces.\n\n implicit none\n\n character str(*) # The string to \"trim\".\n integer n # The length including trailing spaces.\n integer trimrt # The length without trailing spaces.\n\n logical isspc\n\n integer j\n logical done\n\n j = n\n done = .false.\n while (!done)\n {\n if (j == 0)\n done = .true.\n else if (!isspc (ichar (str(j))))\n done = .true.\n else\n j = j - 1\n }\n trimrt = j\nend\n\n#---------------------------------------------------------------------\n\nsubroutine toknam (tokno, str, i)\n\n # Copy a token name to the character array str, starting at i.\n\n implicit none\n\n integer tokno\n character str(*)\n integer i\n integer j\n\n character*16 names(0:30)\n character*16 nm\n\n data names / \"Keyword_else \", _\n \"Keyword_if \", _\n \"Keyword_print \", _\n \"Keyword_putc \", _\n \"Keyword_while \", _\n \"Op_multiply \", _\n \"Op_divide \", _\n \"Op_mod \", _\n \"Op_add \", _\n \"Op_subtract \", _\n \"Op_negate \", _\n \"Op_less \", _\n \"Op_lessequal \", _\n \"Op_greater \", _\n \"Op_greaterequal \", _\n \"Op_equal \", _\n \"Op_notequal \", _\n \"Op_not \", _\n \"Op_assign \", _\n \"Op_and \", _\n \"Op_or \", _\n \"LeftParen \", _\n \"RightParen \", _\n \"LeftBrace \", _\n \"RightBrace \", _\n \"Semicolon \", _\n \"Comma \", _\n \"Identifier \", _\n \"Integer \", _\n \"String \", _\n \"End_of_input \" /\n\n nm = names(tokno)\n for (j = 0; j < 16; j = j + 1)\n str(i + j) = nm(1 + j : 1 + j)\nend\n\nsubroutine intstr (str, i, n, x)\n\n # Convert a positive integer to a substring.\n\n implicit none\n\n character str(*) # Destination string.\n integer i, n # Index and length of the field.\n integer x # The positive integer to represent.\n\n integer j\n integer y\n\n if (x == 0)\n {\n for (j = 0; j < n - 1; j = j + 1)\n str(i + j) = ' '\n str(i + j) = '0'\n }\n else\n {\n y = x\n for (j = n - 1; 0 <= j; j = j - 1)\n {\n if (y == 0)\n str(i + j) = ' '\n else\n {\n str(i + j) = char (mod (y, 10) + ichar ('0'))\n y = y / 10\n }\n }\n }\nend\n\nsubroutine prttok (strngs, tok)\n\n # Print a token.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer tok(TOKSZ) # The token.\n\n integer trimrt\n\n character line(OUTLSZ)\n character*20 fmt\n integer i, n\n integer tokno\n\n for (i = 1; i <= OUTLSZ; i = i + 1)\n line(i) = ' '\n\n call intstr (line, 1, 10, tok(ILINNO))\n call intstr (line, 12, 10, tok(ICOLNO))\n\n tokno = tok(ITOKNO)\n call toknam (tokno, line, 25)\n if (tokno == TKID || tokno == TKINT || tokno == TKSTR)\n {\n i = tok(IARGIX)\n n = tok(IARGLN)\n call cpystr (strngs, i, n, line, 45)\n }\n\n n = trimrt (line, OUTLSZ)\n write (fmt, '(''('', I10, ''A)'')') n\n write (*, fmt) (line(i), i = 1, n)\nend\n\n#---------------------------------------------------------------------\n\nsubroutine wrtpos (ln, cn)\n\n implicit none\n\n integer ln, cn\n\n write (*, 1000) ln, cn\n1000 format ('At line ', I5, ', column ' I5)\nend\n\n#---------------------------------------------------------------------\n\nsubroutine utcmnt (ln, cn)\n\n implicit none\n\n integer ln, cn\n\n call wrtpos (ln, cn)\n write (*, '(''Unterminated comment'')')\n stop\nend\n\nsubroutine skpcmt (line, linno, colno, pushbk, npshbk, ln, cn)\n\n # Skip to the end of a comment.\n\n implicit none\n\n character line(LINESZ) # Input buffer.\n integer linno, colno # Current line and column numbers.\n integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer.\n integer npshbk # Number of characters pushed back.\n integer ln, cn # Line and column of start of comment.\n\n integer chr(CHRSZ)\n logical done\n\n done = .false.\n while (!done)\n {\n call getchr (line, linno, colno, pushbk, npshbk, chr)\n if (chr(ICHRCD) == ichar ('*'))\n {\n call getchr (line, linno, colno, pushbk, npshbk, chr)\n if (chr(ICHRCD) == ichar ('/'))\n done = .true.\n else if (chr(ICHRCD) == EOF)\n call utcmnt (ln, cn)\n }\n else if (chr(ICHRCD) == EOF)\n call utcmnt (ln, cn)\n }\nend\n\nsubroutine skpspc (line, linno, colno, pushbk, npshbk)\n\n # Skip spaces and comments.\n\n implicit none\n\n character line(LINESZ) # Input buffer.\n integer linno, colno # Current line and column numbers.\n integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer.\n integer npshbk # Number of characters pushed back.\n\n logical isspc\n\n integer chr(CHRSZ)\n integer chr1(CHRSZ)\n integer ln, cn\n logical done\n\n done = .false.\n while (!done)\n {\n call getchr (line, linno, colno, pushbk, npshbk, chr)\n if (!isspc (chr(ICHRCD)))\n {\n if (chr(ICHRCD) != ichar ('/'))\n {\n call pshchr (pushbk, npshbk, chr)\n done = .true.\n }\n else\n {\n call getchr (line, linno, colno, pushbk, npshbk, chr1)\n if (chr1(ICHRCD) != ichar ('*'))\n {\n call pshchr (pushbk, npshbk, chr1)\n call pshchr (pushbk, npshbk, chr)\n done = .true.\n }\n else\n {\n ln = chr(ILINNO)\n cn = chr(ICOLNO)\n call skpcmt (line, linno, colno, pushbk, npshbk, _\n ln, cn)\n }\n }\n }\n }\nend\n\n#---------------------------------------------------------------------\n\nsubroutine rwdlkp (strngs, istrng, src, i0, n0, ln, cn, tok)\n\n # Reserved word lookup\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character src(*) # The source string.\n integer i0, n0 # Index and length of the substring.\n integer ln, cn # Line and column number\n # to associate with the token.\n integer tok(TOKSZ) # The output token.\n\n integer tokno\n integer i, n\n\n tokno = TKID\n\n if (n0 == 2)\n {\n if (src(i0) == 'i' && src(i0 + 1) == 'f')\n tokno = TKIF\n }\n else if (n0 == 4)\n {\n if (src(i0) == 'e' && src(i0 + 1) == 'l' _\n && src(i0 + 2) == 's' && src(i0 + 3) == 'e')\n tokno = TKELSE\n else if (src(i0) == 'p' && src(i0 + 1) == 'u' _\n && src(i0 + 2) == 't' && src(i0 + 3) == 'c')\n tokno = TKPUTC\n }\n else if (n0 == 5)\n {\n if (src(i0) == 'p' && src(i0 + 1) == 'r' _\n && src(i0 + 2) == 'i' && src(i0 + 3) == 'n' _\n && src(i0 + 4) == 't')\n tokno = TKPRNT\n else if (src(i0) == 'w' && src(i0 + 1) == 'h' _\n && src(i0 + 2) == 'i' && src(i0 + 3) == 'l' _\n && src(i0 + 4) == 'e')\n tokno = TKWHIL\n }\n\n i = 0\n n = 0\n if (tokno == TKID)\n call addstr (strngs, istrng, src, i0, n0, i, n)\n\n tok(ITOKNO) = tokno\n tok(IARGIX) = i\n tok(IARGLN) = n\n tok(ILINNO) = ln\n tok(ICOLNO) = cn\nend\n\nsubroutine scnwrd (line, linno, colno, pushbk, npshbk, ln, cn, buf, n)\n\n # Scan characters that may represent an identifier, reserved word,\n # or integer literal.\n\n implicit none\n\n character line(LINESZ) # Input buffer.\n integer linno, colno # Current line and column numbers.\n integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer.\n integer npshbk # Number of characters pushed back.\n integer ln, cn # Line and column number of the start.\n character buf(LINESZ) # The output buffer.\n integer n # The length of the string collected.\n\n logical isid1\n\n integer chr(CHRSZ)\n\n n = 0\n call getchr (line, linno, colno, pushbk, npshbk, chr)\n ln = chr(ILINNO)\n cn = chr(ICOLNO)\n while (isid1 (chr(ICHRCD)))\n {\n n = n + 1\n buf(n) = char (chr(ICHRCD))\n call getchr (line, linno, colno, pushbk, npshbk, chr)\n }\n call pshchr (pushbk, npshbk, chr)\nend\n\nsubroutine scnidr (strngs, istrng, _\n line, linno, colno, pushbk, npshbk, _\n tok)\n\n # Scan an identifier or reserved word.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character line(LINESZ) # Input buffer.\n integer linno, colno # Current line and column numbers.\n integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer.\n integer npshbk # Number of characters pushed back.\n integer ln, cn # Line and column number of the start.\n integer tok(TOKSZ) # The output token.\n\n character buf(LINESZ)\n integer n\n\n call scnwrd (line, linno, colno, pushbk, npshbk, ln, cn, buf, n)\n call rwdlkp (strngs, istrng, buf, 1, n, ln, cn, tok)\nend\n\nsubroutine scnint (strngs, istrng, _\n line, linno, colno, pushbk, npshbk, _\n tok)\n\n # Scan a positive integer literal.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character line(LINESZ) # Input buffer.\n integer linno, colno # Current line and column numbers.\n integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer.\n integer npshbk # Number of characters pushed back.\n integer ln, cn # Line and column number of the start.\n integer tok(TOKSZ) # The output token.\n\n logical isdgt\n\n character buf(LINESZ)\n integer n0, n\n integer i, j, k\n character*80 fmt\n\n call scnwrd (line, linno, colno, pushbk, npshbk, ln, cn, buf, n0)\n for (j = 1; j <= n0; j = j + 1)\n if (!isdgt (ichar (buf(j))))\n {\n call wrtpos (ln, cn)\n write (fmt, 1000) n0\n1000 format ('(''Not a legal word: \"''', I10, 'A, ''\"'')')\n write (*, fmt) (buf(k), k = 1, n0)\n stop\n }\n\n call addstr (strngs, istrng, buf, 1, n0, i, n)\n\n tok(ITOKNO) = TKINT\n tok(IARGIX) = i\n tok(IARGLN) = n\n tok(ILINNO) = ln\n tok(ICOLNO) = cn\nend\n\nsubroutine utclit (ln, cn)\n\n implicit none\n\n integer ln, cn\n\n call wrtpos (ln, cn)\n write (*, '(''Unterminated character literal'')')\n stop\nend\n\nsubroutine scnch1 (strngs, istrng, _\n line, linno, colno, pushbk, npshbk, _\n tok)\n\n # Scan a character literal, without yet checking that the literal\n # ends correctly.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character line(LINESZ) # Input buffer.\n integer linno, colno # Current line and column numbers.\n integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer.\n integer npshbk # Number of characters pushed back.\n integer tok(TOKSZ) # The output token.\n\n integer trimlf\n\n integer bufsz\n parameter (bufsz = 40)\n\n integer chr(CHRSZ)\n integer chr1(CHRSZ)\n integer chr2(CHRSZ)\n integer ln, cn\n character buf(bufsz)\n integer i, j, n\n\n # Refetch the opening quote.\n call getchr (line, linno, colno, pushbk, npshbk, chr)\n ln = chr(ILINNO)\n cn = chr(ICOLNO)\n\n tok(ITOKNO) = TKINT\n tok(ILINNO) = ln\n tok(ICOLNO) = cn\n\n call getchr (line, linno, colno, pushbk, npshbk, chr1)\n if (chr1(ICHRCD) == EOF)\n call utclit (ln, cn)\n if (chr1(ICHRCD) == BACKSL)\n {\n call getchr (line, linno, colno, pushbk, npshbk, chr2)\n if (chr2(ICHRCD) == EOF)\n call utclit (ln, cn)\n else if (chr2(ICHRCD) == ichar ('n'))\n {\n tok(IARGIX) = LOC10 # \"10\" = code for Unix newline\n tok(IARGLN) = 2\n }\n else if (chr2(ICHRCD) == BACKSL)\n {\n tok(IARGIX) = LOC92 # \"92\" = code for backslash\n tok(IARGLN) = 2\n }\n else\n {\n call wrtpos (ln, cn)\n write (*, '(''Unsupported escape: '', 1A)') _\n char (chr2(ICHRCD))\n stop\n }\n }\n else\n {\n # Character codes are non-negative, so we can use intstr.\n call intstr (buf, 1, bufsz, chr1(ICHRCD))\n\n j = trimlf (buf, bufsz)\n call addstr (strngs, istrng, buf, j, bufsz - (j - 1), i, n)\n tok(IARGIX) = i\n tok(IARGLN) = n\n }\nend\n\nsubroutine scnch (strngs, istrng, _\n line, linno, colno, pushbk, npshbk, _\n tok)\n\n # Scan a character literal.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character line(LINESZ) # Input buffer.\n integer linno, colno # Current line and column numbers.\n integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer.\n integer npshbk # Number of characters pushed back.\n integer tok(TOKSZ) # The output token.\n\n integer ln, cn\n integer chr(CHRSZ)\n\n call getpos (line, linno, colno, pushbk, npshbk, ln, cn)\n call scnch1 (strngs, istrng, _\n line, linno, colno, pushbk, npshbk, _\n tok)\n call getchr (line, linno, colno, pushbk, npshbk, chr)\n if (chr(ICHRCD) != ichar (''''))\n {\n while (.true.)\n {\n if (chr(ICHRCD) == EOF)\n {\n call utclit (ln, cn)\n stop\n }\n else if (chr(ICHRCD) == ichar (''''))\n {\n call wrtpos (ln, cn)\n write (*, '(''Unsupported multicharacter literal'')')\n stop\n }\n call getchr (line, linno, colno, pushbk, npshbk, chr)\n }\n }\nend\n\nsubroutine scnstr (strngs, istrng, _\n line, linno, colno, pushbk, npshbk, _\n tok)\n\n # Scan a string literal.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character line(LINESZ) # Input buffer.\n integer linno, colno # Current line and column numbers.\n integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer.\n integer npshbk # Number of characters pushed back.\n integer tok(TOKSZ) # The output token.\n\n integer ln, cn\n integer chr1(CHRSZ)\n integer chr2(CHRSZ)\n character buf(LINESZ + 10) # Enough space, with some room to spare.\n integer n0\n integer i, n\n\n call getchr (line, linno, colno, pushbk, npshbk, chr1)\n ln = chr1(ILINNO)\n cn = chr1(ICOLNO)\n\n tok(ITOKNO) = TKSTR\n tok(ILINNO) = ln\n tok(ICOLNO) = cn\n\n n0 = 1\n buf(n0) = '\"'\n\n call getchr (line, linno, colno, pushbk, npshbk, chr1)\n while (chr1(ICHRCD) != ichar ('\"'))\n {\n # Our input method always puts a NEWLIN before EOF, and so this\n # test is redundant, unless someone changes the input method.\n if (chr1(ICHRCD) == EOF || chr1(ICHRCD) == NEWLIN)\n {\n call wrtpos (ln, cn)\n write (*, '(''Unterminated string literal'')')\n stop\n }\n if (chr1(ICHRCD) == BACKSL)\n {\n call getchr (line, linno, colno, pushbk, npshbk, chr2)\n if (chr2(ICHRCD) == ichar ('n'))\n {\n n0 = n0 + 1\n buf(n0) = char (BACKSL)\n n0 = n0 + 1\n buf(n0) = 'n'\n }\n else if (chr2(ICHRCD) == BACKSL)\n {\n n0 = n0 + 1\n buf(n0) = char (BACKSL)\n n0 = n0 + 1\n buf(n0) = char (BACKSL)\n }\n else\n {\n call wrtpos (chr1(ILINNO), chr1(ICOLNO))\n write (*, '(''Unsupported escape sequence'')')\n stop\n }\n }\n else\n {\n n0 = n0 + 1\n buf(n0) = char (chr1(ICHRCD))\n }\n call getchr (line, linno, colno, pushbk, npshbk, chr1)\n }\n n0 = n0 + 1\n buf(n0) = '\"'\n\n call addstr (strngs, istrng, buf, 1, n0, i, n)\n tok(IARGIX) = i\n tok(IARGLN) = n\nend\n\nsubroutine unxchr (chr)\n\n implicit none\n\n integer chr(CHRSZ)\n\n call wrtpos (chr(ILINNO), chr(ICOLNO))\n write (*, 1000) char (chr(ICHRCD))\n1000 format ('Unexpected character ''', A1, '''')\n stop\nend\n\nsubroutine scntok (strngs, istrng, _\n line, linno, colno, pushbk, npshbk, _\n tok)\n\n # Scan a token.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character line(LINESZ) # Input buffer.\n integer linno, colno # Current line and column numbers.\n integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer.\n integer npshbk # Number of characters pushed back.\n integer tok(TOKSZ) # The output token.\n\n logical isdgt\n logical isid0\n\n integer chr(CHRSZ)\n integer chr1(CHRSZ)\n integer ln, cn\n\n call getchr (line, linno, colno, pushbk, npshbk, chr)\n ln = chr(ILINNO)\n cn = chr(ICOLNO)\n tok(ILINNO) = ln\n tok(ICOLNO) = cn\n tok(IARGIX) = 0\n tok(IARGLN) = 0\n if (chr(ICHRCD) == ichar (','))\n tok(ITOKNO) = TKCMMA\n else if (chr(ICHRCD) == ichar (';'))\n tok(ITOKNO) = TKSEMI\n else if (chr(ICHRCD) == ichar ('('))\n tok(ITOKNO) = TKLPAR\n else if (chr(ICHRCD) == ichar (')'))\n tok(ITOKNO) = TKRPAR\n else if (chr(ICHRCD) == ichar ('{'))\n tok(ITOKNO) = TKLBRC\n else if (chr(ICHRCD) == ichar ('}'))\n tok(ITOKNO) = TKRBRC\n else if (chr(ICHRCD) == ichar ('*'))\n tok(ITOKNO) = TKMUL\n else if (chr(ICHRCD) == ichar ('/'))\n tok(ITOKNO) = TKDIV\n else if (chr(ICHRCD) == ichar ('%'))\n tok(ITOKNO) = TKMOD\n else if (chr(ICHRCD) == ichar ('+'))\n tok(ITOKNO) = TKADD\n else if (chr(ICHRCD) == ichar ('-'))\n tok(ITOKNO) = TKSUB\n else if (chr(ICHRCD) == ichar ('<'))\n {\n call getchr (line, linno, colno, pushbk, npshbk, chr1)\n if (chr1(ICHRCD) == ichar ('='))\n tok(ITOKNO) = TKLE\n else\n {\n call pshchr (pushbk, npshbk, chr1)\n tok(ITOKNO) = TKLT\n }\n }\n else if (chr(ICHRCD) == ichar ('>'))\n {\n call getchr (line, linno, colno, pushbk, npshbk, chr1)\n if (chr1(ICHRCD) == ichar ('='))\n tok(ITOKNO) = TKGE\n else\n {\n call pshchr (pushbk, npshbk, chr1)\n tok(ITOKNO) = TKGT\n }\n }\n else if (chr(ICHRCD) == ichar ('='))\n {\n call getchr (line, linno, colno, pushbk, npshbk, chr1)\n if (chr1(ICHRCD) == ichar ('='))\n tok(ITOKNO) = TKEQ\n else\n {\n call pshchr (pushbk, npshbk, chr1)\n tok(ITOKNO) = TKASGN\n }\n }\n else if (chr(ICHRCD) == ichar ('!'))\n {\n call getchr (line, linno, colno, pushbk, npshbk, chr1)\n if (chr1(ICHRCD) == ichar ('='))\n tok(ITOKNO) = TKNE\n else\n {\n call pshchr (pushbk, npshbk, chr1)\n tok(ITOKNO) = TKNOT\n }\n }\n else if (chr(ICHRCD) == ichar ('&'))\n {\n call getchr (line, linno, colno, pushbk, npshbk, chr1)\n if (chr1(ICHRCD) == ichar ('&'))\n tok(ITOKNO) = TKAND\n else\n call unxchr (chr)\n }\n else if (chr(ICHRCD) == ichar ('|'))\n {\n call getchr (line, linno, colno, pushbk, npshbk, chr1)\n if (chr1(ICHRCD) == ichar ('|'))\n tok(ITOKNO) = TKOR\n else\n call unxchr (chr)\n }\n else if (chr(ICHRCD) == ichar ('\"'))\n {\n call pshchr (pushbk, npshbk, chr)\n call scnstr (strngs, istrng, _\n line, linno, colno, pushbk, npshbk, _\n tok)\n }\n else if (chr(ICHRCD) == ichar (''''))\n {\n call pshchr (pushbk, npshbk, chr)\n call scnch (strngs, istrng, _\n line, linno, colno, pushbk, npshbk, _\n tok)\n }\n else if (isdgt (chr(ICHRCD)))\n {\n call pshchr (pushbk, npshbk, chr)\n call scnint (strngs, istrng, _\n line, linno, colno, pushbk, npshbk, _\n tok)\n }\n else if (isid0 (chr(ICHRCD)))\n {\n call pshchr (pushbk, npshbk, chr)\n call scnidr (strngs, istrng, _\n line, linno, colno, pushbk, npshbk, _\n tok)\n }\n else\n call unxchr (chr)\nend\n\nsubroutine scntxt (strngs, istrng, _\n line, linno, colno, pushbk, npshbk)\n\n # Scan the text and print the token stream.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character line(LINESZ) # Input buffer.\n integer linno, colno # Current line and column numbers.\n integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer.\n integer npshbk # Number of characters pushed back.\n\n integer chr(CHRSZ)\n integer tok(TOKSZ)\n\n chr(ICHRCD) = ichar ('x')\n while (chr(ICHRCD) != EOF)\n {\n call skpspc (line, linno, colno, pushbk, npshbk)\n call getchr (line, linno, colno, pushbk, npshbk, chr)\n if (chr(ICHRCD) != EOF)\n {\n call pshchr (pushbk, npshbk, chr)\n call scntok (strngs, istrng, _\n line, linno, colno, pushbk, npshbk, _\n tok)\n call prttok (strngs, tok)\n }\n }\n tok(ITOKNO) = TKEOI\n tok(ILINNO) = chr(ILINNO)\n tok(ICOLNO) = chr(ICOLNO)\n tok(IARGIX) = 0\n tok(IARGLN) = 0\n call prttok (strngs, tok)\nend\n\n#---------------------------------------------------------------------\n\nprogram lex\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character line(LINESZ) # Input buffer.\n integer linno, colno # Current line and column numbers.\n integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer.\n integer npshbk # Number of characters pushed back.\n\n integer i, n\n\n istrng = 1\n\n # Locate \"10\" (newline) at 1 in the string pool.\n line(1) = '1'\n line(2) = '0'\n call addstr (strngs, istrng, line, 1, 2, i, n)\n if (i != 1 && n != 2)\n {\n write (*, '(''internal error'')')\n stop\n }\n\n # Locate \"92\" (backslash) at 3 in the string pool.\n line(1) = '9'\n line(2) = '2'\n call addstr (strngs, istrng, line, 1, 2, i, n)\n if (i != 3 && n != 2)\n {\n write (*, '(''internal error'')')\n stop\n }\n\n linno = 0\n colno = LINESZ + 1 # This will trigger a READ.\n npshbk = 0\n\n call scntxt (strngs, istrng, line, linno, colno, pushbk, npshbk)\nend\n\n######################################################################\n", "language": "RATFOR" }, { "code": "package xyz.hyperreal.rosettacodeCompiler\n\nimport scala.io.Source\nimport scala.util.matching.Regex\n\nobject LexicalAnalyzer {\n private val EOT = '\\u0004'\n\n val symbols =\n Map(\n \"*\" -> \"Op_multiply\",\n \"/\" -> \"Op_divide\",\n \"%\" -> \"Op_mod\",\n \"+\" -> \"Op_add\",\n \"-\" -> \"Op_minus\",\n \"<\" -> \"Op_less\",\n \"<=\" -> \"Op_lessequal\",\n \">\" -> \"Op_greater\",\n \">=\" -> \"Op_greaterequal\",\n \"==\" -> \"Op_equal\",\n \"!=\" -> \"Op_notequal\",\n \"!\" -> \"Op_not\",\n \"=\" -> \"Op_assign\",\n \"&&\" -> \"Op_and\",\n \"¦¦\" -> \"Op_or\",\n \"(\" -> \"LeftParen\",\n \")\" -> \"RightParen\",\n \"{\" -> \"LeftBrace\",\n \"}\" -> \"RightBrace\",\n \";\" -> \"Semicolon\",\n \",\" -> \"Comma\"\n )\n\n val keywords =\n Map(\n \"if\" -> \"Keyword_if\",\n \"else\" -> \"Keyword_else\",\n \"while\" -> \"Keyword_while\",\n \"print\" -> \"Keyword_print\",\n \"putc\" -> \"Keyword_putc\"\n )\n val alpha = ('a' to 'z' toSet) ++ ('A' to 'Z')\n val numeric = '0' to '9' toSet\n val alphanumeric = alpha ++ numeric\n val identifiers = StartRestToken(\"Identifier\", alpha + '_', alphanumeric + '_')\n val integers = SimpleToken(\"Integer\", numeric, alpha, \"alpha characters may not follow right after a number\")\n\n val characters =\n DelimitedToken(\"Integer\",\n '\\'',\n \"[^'\\\\n]|\\\\\\\\n|\\\\\\\\\\\\\\\\\" r,\n \"invalid character literal\",\n \"unclosed character literal\")\n\n val strings =\n DelimitedToken(\"String\", '\"', \"[^\\\"\\\\n]*\" r, \"invalid string literal\", \"unclosed string literal\")\n\n def apply =\n new LexicalAnalyzer(4, symbols, keywords, \"End_of_input\", identifiers, integers, characters, strings)\n\n abstract class Token\n case class StartRestToken(name: String, start: Set[Char], rest: Set[Char]) extends Token\n case class SimpleToken(name: String, chars: Set[Char], exclude: Set[Char], excludeError: String) extends Token\n case class DelimitedToken(name: String, delimiter: Char, pattern: Regex, patternError: String, unclosedError: String)\n extends Token\n}\n\nclass LexicalAnalyzer(tabs: Int,\n symbols: Map[String, String],\n keywords: Map[String, String],\n endOfInput: String,\n identifier: LexicalAnalyzer.Token,\n tokens: LexicalAnalyzer.Token*) {\n\n import LexicalAnalyzer._\n\n private val symbolStartChars = symbols.keys map (_.head) toSet\n private val symbolChars = symbols.keys flatMap (_.toList) toSet\n private var curline: Int = _\n private var curcol: Int = _\n\n def fromStdin = fromSource(Source.stdin)\n\n def fromString(src: String) = fromSource(Source.fromString(src))\n\n def fromSource(ast: Source) = {\n curline = 1\n curcol = 1\n\n var s = (ast ++ Iterator(EOT)) map (new Chr(_)) toStream\n\n tokenize\n\n def token(name: String, first: Chr) = println(f\"${first.line}%5d ${first.col}%6d $name\")\n\n def value(name: String, v: String, first: Chr) = println(f\"${first.line}%5d ${first.col}%6d $name%-14s $v\")\n\n def until(c: Char) = {\n val buf = new StringBuilder\n\n def until: String =\n if (s.head.c == EOT || s.head.c == c)\n buf.toString\n else {\n buf += getch\n until\n }\n\n until\n }\n\n def next = s = s.tail\n\n def getch = {\n val c = s.head.c\n\n next\n c\n }\n\n def consume(first: Char, cs: Set[Char]) = {\n val buf = new StringBuilder\n\n def consume: String =\n if (s.head.c == EOT || !cs(s.head.c))\n buf.toString\n else {\n buf += getch\n consume\n }\n\n buf += first\n consume\n }\n\n def comment(start: Chr): Unit = {\n until('*')\n\n if (s.head.c == EOT || s.tail.head.c == EOT)\n sys.error(s\"unclosed comment ${start.at}\")\n else if (s.tail.head.c != '/') {\n next\n comment(start)\n } else {\n next\n next\n }\n }\n\n def recognize(t: Token): Option[(String, String)] = {\n val first = s\n\n next\n\n t match {\n case StartRestToken(name, start, rest) =>\n if (start(first.head.c))\n Some((name, consume(first.head.c, rest)))\n else {\n s = first\n None\n }\n case SimpleToken(name, chars, exclude, excludeError) =>\n if (chars(first.head.c)) {\n val m = consume(first.head.c, chars)\n\n if (exclude(s.head.c))\n sys.error(s\"$excludeError ${s.head.at}\")\n else\n Some((name, m))\n } else {\n s = first\n None\n }\n case DelimitedToken(name, delimiter, pattern, patternError, unclosedError) =>\n if (first.head.c == delimiter) {\n val m = until(delimiter)\n\n if (s.head.c != delimiter)\n sys.error(s\"$unclosedError ${first.head.at}\")\n else if (pattern.pattern.matcher(m).matches) {\n next\n Some((name, s\"$delimiter$m$delimiter\"))\n } else\n sys.error(s\"$patternError ${s.head.at}\")\n } else {\n s = first\n None\n }\n }\n }\n\n def tokenize: Unit =\n if (s.head.c == EOT)\n token(endOfInput, s.head)\n else {\n if (s.head.c.isWhitespace)\n next\n else if (s.head.c == '/' && s.tail.head.c == '*')\n comment(s.head)\n else if (symbolStartChars(s.head.c)) {\n val first = s.head\n val buf = new StringBuilder\n\n while (!symbols.contains(buf.toString) && s.head.c != EOT && symbolChars(s.head.c)) buf += getch\n\n while (symbols.contains(buf.toString :+ s.head.c) && s.head.c != EOT && symbolChars(s.head.c)) buf += getch\n\n symbols get buf.toString match {\n case Some(name) => token(name, first)\n case None => sys.error(s\"unrecognized symbol: '${buf.toString}' ${first.at}\")\n }\n } else {\n val first = s.head\n\n recognize(identifier) match {\n case None =>\n find(0)\n\n @scala.annotation.tailrec\n def find(t: Int): Unit =\n if (t == tokens.length)\n sys.error(s\"unrecognized character ${first.at}\")\n else\n recognize(tokens(t)) match {\n case None => find(t + 1)\n case Some((name, v)) => value(name, v, first)\n }\n case Some((name, ident)) =>\n keywords get ident match {\n case None => value(name, ident, first)\n case Some(keyword) => token(keyword, first)\n }\n }\n }\n\n tokenize\n }\n }\n\n private class Chr(val c: Char) {\n val line = curline\n val col = curcol\n\n if (c == '\\n') {\n curline += 1\n curcol = 1\n } else if (c == '\\r')\n curcol = 1\n else if (c == '\\t')\n curcol += tabs - (curcol - 1) % tabs\n else\n curcol += 1\n\n def at = s\"[${line}, ${col}]\"\n\n override def toString: String = s\"<$c, $line, $col>\"\n }\n\n}\n", "language": "Scala" }, { "code": "(import (scheme base)\n (scheme char)\n (scheme file)\n (scheme process-context)\n (scheme write))\n\n(define *symbols* (list (cons #\\( 'LeftParen)\n (cons #\\) 'RightParen)\n (cons #\\{ 'LeftBrace)\n (cons #\\} 'RightBrace)\n (cons #\\; 'Semicolon)\n (cons #\\, 'Comma)\n (cons #\\* 'Op_multiply)\n (cons #\\/ 'Op_divide)\n (cons #\\% 'Op_mod)\n (cons #\\+ 'Op_add)\n (cons #\\- 'Op_subtract)))\n\n(define *keywords* (list (cons 'if 'Keyword_if)\n (cons 'else 'Keyword_else)\n (cons 'while 'Keyword_while)\n (cons 'print 'Keyword_print)\n (cons 'putc 'Keyword_putc)))\n\n;; return list of tokens from current port\n(define (read-tokens)\n ; information on position in input\n (define line 1)\n (define col 0)\n (define next-char #f)\n ; get char, updating line/col posn\n (define (get-next-char)\n (if (char? next-char) ; check for returned character\n (let ((c next-char))\n (set! next-char #f)\n c)\n (let ((c (read-char)))\n (cond ((and (not (eof-object? c))\n (char=? c #\\newline))\n (set! col 0)\n (set! line (+ 1 line))\n (get-next-char))\n (else\n (set! col (+ 1 col))\n c)))))\n (define (push-char c)\n (set! next-char c))\n ; step over any whitespace or comments\n (define (skip-whitespace+comment)\n (let loop ()\n (let ((c (get-next-char)))\n (cond ((eof-object? c)\n '())\n ((char-whitespace? c) ; ignore whitespace\n (loop))\n ((char=? c #\\/) ; check for comments\n (if (char=? (peek-char) #\\*) ; found start of comment\n (begin ; eat comment\n (get-next-char)\n (let m ((c (get-next-char)))\n (cond ((eof-object? c)\n (error \"End of file in comment\"))\n ((and (char=? c #\\*)\n (char=? (peek-char) #\\/))\n (get-next-char)) ; eat / and end\n (else\n (m (get-next-char)))))\n (loop)) ; continue looking for whitespace / more comments\n (push-char #\\/))) ; not comment, so put / back and return\n (else ; return to stream, as not a comment or space char\n (push-char c))))))\n ; read next token from input\n (define (next-token)\n (define (read-string) ; returns string value along with \" \" marks\n (let loop ((chars '(#\\\"))) ; \" (needed to appease Rosetta code's highlighter)\n (cond ((eof-object? (peek-char))\n (error \"End of file while scanning string literal.\"))\n ((char=? (peek-char) #\\newline)\n (error \"End of line while scanning string literal.\"))\n ((char=? (peek-char) #\\\") ; \"\n (get-next-char) ; consume the final quote\n (list->string (reverse (cons #\\\" chars)))) ; \" highlighter)\n (else\n (loop (cons (get-next-char) chars))))))\n (define (read-identifier initial-c) ; returns identifier as a Scheme symbol\n (do ((chars (list initial-c) (cons c chars))\n (c (get-next-char) (get-next-char)))\n ((or (eof-object? c) ; finish when hit end of file\n (not (or (char-numeric? c) ; or a character not permitted in an identifier\n (char-alphabetic? c)\n (char=? c #\\_))))\n (push-char c) ; return last character to stream\n (string->symbol (list->string (reverse chars))))))\n (define (read-number initial-c) ; returns integer read as a Scheme integer\n (let loop ((res (digit-value initial-c))\n (c (get-next-char)))\n (cond ((char-alphabetic? c)\n (error \"Invalid number - ends in alphabetic chars\"))\n ((char-numeric? c)\n (loop (+ (* res 10) (digit-value c))\n (get-next-char)))\n (else\n (push-char c) ; return non-number to stream\n res))))\n ; select op symbol based on if there is a following = sign\n (define (check-eq-extend start-line start-col opeq op)\n (if (char=? (peek-char) #\\=)\n (begin (get-next-char) ; consume it\n (list start-line start-col opeq))\n (list start-line start-col op)))\n ;\n (let* ((start-line line) ; save start position of tokens\n (start-col col)\n (c (get-next-char)))\n (cond ((eof-object? c)\n (list start-line start-col 'End_of_input))\n ((char-alphabetic? c) ; read an identifier\n (let ((id (read-identifier c)))\n (if (assq id *keywords*) ; check if identifier is a keyword\n (list start-line start-col (cdr (assq id *keywords*)))\n (list start-line start-col 'Identifier id))))\n ((char-numeric? c) ; read a number\n (list start-line start-col 'Integer (read-number c)))\n (else\n (case c\n ((#\\( #\\) #\\{ #\\} #\\; #\\, #\\* #\\/ #\\% #\\+ #\\-)\n (list start-line start-col (cdr (assq c *symbols*))))\n ((#\\<)\n (check-eq-extend start-line start-col 'Op_lessequal 'Op_less))\n ((#\\>)\n (check-eq-extend start-line start-col 'Op_greaterequal 'Op_greater))\n ((#\\=)\n (check-eq-extend start-line start-col 'Op_equal 'Op_assign))\n ((#\\!)\n (check-eq-extend start-line start-col 'Op_notequal 'Op_not))\n ((#\\& #\\|)\n (if (char=? (peek-char) c) ; looks for && or ||\n (begin (get-next-char) ; consume second character if valid\n (list start-line start-col\n (if (char=? c #\\&) 'Op_and 'Op_or)))\n (push-char c)))\n ((#\\\") ; \"\n (list start-line start-col 'String (read-string)))\n ((#\\')\n (let* ((c1 (get-next-char))\n (c2 (get-next-char)))\n (cond ((or (eof-object? c1)\n (eof-object? c2))\n (error \"Incomplete character constant\"))\n ((char=? c1 #\\')\n (error \"Empty character constant\"))\n ((and (char=? c2 #\\') ; case of single character\n (not (char=? c1 #\\\\)))\n (list start-line start-col 'Integer (char->integer c1)))\n ((and (char=? c1 #\\\\) ; case of escaped character\n (char=? (peek-char) #\\'))\n (get-next-char) ; consume the ending '\n (cond ((char=? c2 #\\n)\n (list start-line start-col 'Integer 10))\n ((char=? c2 #\\\\)\n (list start-line start-col 'Integer (char->integer c2)))\n (else\n (error \"Unknown escape sequence\"))))\n (else\n (error \"Multi-character constant\")))))\n (else\n (error \"Unrecognised character\")))))))\n ;\n (let loop ((tokens '())) ; loop, ignoring space/comments, while reading tokens\n (skip-whitespace+comment)\n (let ((tok (next-token)))\n (if (eof-object? (peek-char)) ; check if at end of input\n (reverse (cons tok tokens))\n (loop (cons tok tokens))))))\n\n(define (lexer filename)\n (with-input-from-file filename\n (lambda () (read-tokens))))\n\n;; output tokens to stdout, tab separated\n;; line number, column number, token type, optional value\n(define (display-tokens tokens)\n (for-each\n (lambda (token)\n (display (list-ref token 0))\n (display #\\tab) (display (list-ref token 1))\n (display #\\tab) (display (list-ref token 2))\n (when (= 4 (length token))\n (display #\\tab) (display (list-ref token 3)))\n (newline))\n tokens))\n\n;; read from filename passed on command line\n(if (= 2 (length (command-line)))\n (display-tokens (lexer (cadr (command-line))))\n (display \"Error: provide program filename\\n\"))\n", "language": "Scheme" }, { "code": "(*------------------------------------------------------------------*)\n(* The Rosetta Code lexical analyzer, in Standard ML. Based on the ATS\n and the OCaml. The intended compiler is Mlton or Poly/ML; there is\n a tiny difference near the end of the file, depending on which\n compiler is used. *)\n\n(*------------------------------------------------------------------*)\n(* The following functions are compatible with ASCII. *)\n\nfun\nis_digit ichar =\n48 <= ichar andalso ichar <= 57\n\nfun\nis_lower ichar =\n97 <= ichar andalso ichar <= 122\n\nfun\nis_upper ichar =\n65 <= ichar andalso ichar <= 90\n\nfun\nis_alpha ichar =\nis_lower ichar orelse is_upper ichar\n\nfun\nis_alnum ichar =\nis_digit ichar orelse is_alpha ichar\n\nfun\nis_ident_start ichar =\nis_alpha ichar orelse ichar = 95\n\nfun\nis_ident_continuation ichar =\nis_alnum ichar orelse ichar = 95\n\nfun\nis_space ichar =\nichar = 32 orelse (9 <= ichar andalso ichar <= 13)\n\n(*------------------------------------------------------------------*)\n(* Character input more like that of C. There are various advantages\n and disadvantages to this method, but key points in its favor are:\n (a) it is how character input is done in the original ATS code, (b)\n Unicode code points are 21-bit positive integers. *)\n\nval eof = ~1\n\nfun\ninput_ichar inpf =\ncase TextIO.input1 inpf of\n NONE => eof\n | SOME c => Char.ord c\n\n(*------------------------------------------------------------------*)\n\n(* The type of an input character. *)\n\nstructure Ch =\nstruct\n\ntype t = {\n ichar : int,\n line_no : int,\n column_no : int\n}\n\nend\n\n(*------------------------------------------------------------------*)\n(* Inputting with unlimited pushback, and with counting of lines and\n columns. *)\n\nstructure Inp =\nstruct\n\ntype t = {\n inpf : TextIO.instream,\n pushback : Ch.t list,\n line_no : int,\n column_no : int\n}\n\nfun\nof_instream inpf =\n{\n inpf = inpf,\n pushback = [],\n line_no = 1,\n column_no = 1\n} : t\n\nfun\nget_ch ({ inpf = inpf,\n pushback = pushback,\n line_no = line_no,\n column_no = column_no } : t) =\ncase pushback of\n ch :: tail =>\n let\n val inp = { inpf = inpf,\n pushback = tail,\n line_no = line_no,\n column_no = column_no }\n in\n (ch, inp)\n end\n | [] =>\n let\n val ichar = input_ichar inpf\n val ch = { ichar = ichar,\n line_no = line_no,\n column_no = column_no }\n in\n if ichar = Char.ord #\"\\n\" then\n let\n val inp = { inpf = inpf,\n pushback = [],\n line_no = line_no + 1,\n column_no = 1 }\n in\n (ch, inp)\n end\n else\n let\n val inp = { inpf = inpf,\n pushback = [],\n line_no = line_no,\n column_no = column_no + 1 }\n in\n (ch, inp)\n end\n end\n\nfun\npush_back_ch (ch, inp : t) =\n{\n inpf = #inpf inp,\n pushback = ch :: #pushback inp,\n line_no = #line_no inp,\n column_no = #column_no inp\n}\n\nend\n\n(*------------------------------------------------------------------*)\n(* Tokens, appearing in tuples with arguments, and with line and\n column numbers. The tokens are integers, so they can be used as\n array indices. *)\n\nval token_ELSE = 0\nval token_IF = 1\nval token_PRINT = 2\nval token_PUTC = 3\nval token_WHILE = 4\nval token_MULTIPLY = 5\nval token_DIVIDE = 6\nval token_MOD = 7\nval token_ADD = 8\nval token_SUBTRACT = 9\nval token_NEGATE = 10\nval token_LESS = 11\nval token_LESSEQUAL = 12\nval token_GREATER = 13\nval token_GREATEREQUAL = 14\nval token_EQUAL = 15\nval token_NOTEQUAL = 16\nval token_NOT = 17\nval token_ASSIGN = 18\nval token_AND = 19\nval token_OR = 20\nval token_LEFTPAREN = 21\nval token_RIGHTPAREN = 22\nval token_LEFTBRACE = 23\nval token_RIGHTBRACE = 24\nval token_SEMICOLON = 25\nval token_COMMA = 26\nval token_IDENTIFIER = 27\nval token_INTEGER = 28\nval token_STRING = 29\nval token_END_OF_INPUT = 30\n\n(* A *very* simple perfect hash for the reserved words. (Yes, this is\n overkill, except for demonstration of the principle.) *)\n\nval reserved_words =\n Vector.fromList [\"if\", \"print\", \"else\",\n \"\", \"putc\", \"\",\n \"\", \"while\", \"\"]\nval reserved_word_tokens =\n Vector.fromList [token_IF, token_PRINT, token_ELSE,\n token_IDENTIFIER, token_PUTC, token_IDENTIFIER,\n token_IDENTIFIER, token_WHILE, token_IDENTIFIER]\n\nfun\nreserved_word_lookup (s, line_no, column_no) =\nif (String.size s) < 2 then\n (token_IDENTIFIER, s, line_no, column_no)\nelse\n let\n val hashval =\n (Char.ord (String.sub (s, 0)) +\n Char.ord (String.sub (s, 1)))\n mod 9\n val token = Vector.sub (reserved_word_tokens, hashval)\n in\n if token = token_IDENTIFIER orelse\n s <> Vector.sub (reserved_words, hashval) then\n (token_IDENTIFIER, s, line_no, column_no)\n else\n (token, s, line_no, column_no)\n end\n\n(* Token to string lookup. *)\n\nval token_names =\n Vector.fromList\n [\"Keyword_else\",\n \"Keyword_if\",\n \"Keyword_print\",\n \"Keyword_putc\",\n \"Keyword_while\",\n \"Op_multiply\",\n \"Op_divide\",\n \"Op_mod\",\n \"Op_add\",\n \"Op_subtract\",\n \"Op_negate\",\n \"Op_less\",\n \"Op_lessequal\",\n \"Op_greater\",\n \"Op_greaterequal\",\n \"Op_equal\",\n \"Op_notequal\",\n \"Op_not\",\n \"Op_assign\",\n \"Op_and\",\n \"Op_or\",\n \"LeftParen\",\n \"RightParen\",\n \"LeftBrace\",\n \"RightBrace\",\n \"Semicolon\",\n \"Comma\",\n \"Identifier\",\n \"Integer\",\n \"String\",\n \"End_of_input\"]\n\nfun\ntoken_name token =\n Vector.sub (token_names, token)\n\n(*------------------------------------------------------------------*)\n\nexception Unterminated_comment of int * int\nexception Unterminated_character_literal of int * int\nexception Multicharacter_literal of int * int\nexception End_of_input_in_string_literal of int * int\nexception End_of_line_in_string_literal of int * int\nexception Unsupported_escape of int * int * char\nexception Invalid_integer_literal of int * int * string\nexception Unexpected_character of int * int * char\n\n(*------------------------------------------------------------------*)\n(* Skipping past spaces and comments. (In the Rosetta Code tiny\n language, a comment, if you think about it, is a kind of space.) *)\n\nfun\nscan_comment (inp, line_no, column_no) =\nlet\n fun\n loop inp =\n let\n val (ch, inp) = Inp.get_ch inp\n in\n if #ichar ch = eof then\n raise Unterminated_comment (line_no, column_no)\n else if #ichar ch = Char.ord #\"*\" then\n let\n val (ch1, inp) = Inp.get_ch inp\n in\n if #ichar ch1 = eof then\n raise Unterminated_comment (line_no, column_no)\n else if #ichar ch1 = Char.ord #\"/\" then\n inp\n else\n loop inp\n end\n else\n loop inp\n end\nin\n loop inp\nend\n\nfun\nskip_spaces_and_comments inp =\nlet\n fun\n loop inp =\n let\n val (ch, inp) = Inp.get_ch inp\n in\n if is_space (#ichar ch) then\n loop inp\n else if #ichar ch = Char.ord #\"/\" then\n let\n val (ch1, inp) = Inp.get_ch inp\n in\n if #ichar ch1 = Char.ord #\"*\" then\n loop (scan_comment (inp, #line_no ch, #column_no ch))\n else\n let\n val inp = Inp.push_back_ch (ch1, inp)\n val inp = Inp.push_back_ch (ch, inp)\n in\n inp\n end\n end\n else\n Inp.push_back_ch (ch, inp)\n end\nin\n loop inp\nend\n\n(*------------------------------------------------------------------*)\n(* Integer literals, identifiers, and reserved words. *)\n\nfun\nscan_word (lst, inp) =\nlet\n val (ch, inp) = Inp.get_ch inp\nin\n if is_ident_continuation (#ichar ch) then\n scan_word (Char.chr (#ichar ch) :: lst, inp)\n else\n (lst, Inp.push_back_ch (ch, inp))\nend\n\nfun\nscan_integer_literal inp =\nlet\n val (ch, inp) = Inp.get_ch inp\n val (lst, inp) = scan_word ([Char.chr (#ichar ch)], inp)\n val s = String.implode (List.rev lst)\nin\n if List.all (fn c => is_digit (Char.ord c)) lst then\n ((token_INTEGER, s, #line_no ch, #column_no ch), inp)\n else\n raise Invalid_integer_literal (#line_no ch, #column_no ch, s)\nend\n\nfun\nscan_identifier_or_reserved_word inp =\nlet\n val (ch, inp) = Inp.get_ch inp\n val (lst, inp) = scan_word ([Char.chr (#ichar ch)], inp)\n val s = String.implode (List.rev lst)\n val toktup = reserved_word_lookup (s, #line_no ch, #column_no ch)\nin\n (toktup, inp)\nend\n\n(*------------------------------------------------------------------*)\n(* String literals. *)\n\nfun\nscan_string_literal inp =\nlet\n val (ch, inp) = Inp.get_ch inp\n\n fun\n scan (lst, inp) =\n let\n val (ch1, inp) = Inp.get_ch inp\n in\n if #ichar ch1 = eof then\n raise End_of_input_in_string_literal\n (#line_no ch, #column_no ch)\n else if #ichar ch1 = Char.ord #\"\\n\" then\n raise End_of_line_in_string_literal\n (#line_no ch, #column_no ch)\n else if #ichar ch1 = Char.ord #\"\\\"\" then\n (lst, inp)\n else if #ichar ch1 <> Char.ord #\"\\\\\" then\n scan (Char.chr (#ichar ch1) :: lst, inp)\n else\n let\n val (ch2, inp) = Inp.get_ch inp\n in\n if #ichar ch2 = Char.ord #\"n\" then\n scan (#\"n\" :: #\"\\\\\" :: lst, inp)\n else if #ichar ch2 = Char.ord #\"\\\\\" then\n scan (#\"\\\\\" :: #\"\\\\\" :: lst, inp)\n else if #ichar ch2 = eof then\n raise End_of_input_in_string_literal\n (#line_no ch, #column_no ch)\n else if #ichar ch2 = Char.ord #\"\\n\" then\n raise End_of_line_in_string_literal\n (#line_no ch, #column_no ch)\n else\n raise Unsupported_escape (#line_no ch1, #column_no ch1,\n Char.chr (#ichar ch2))\n end\n end\n\n val lst = #\"\\\"\" :: []\n val (lst, inp) = scan (lst, inp)\n val lst = #\"\\\"\" :: lst\n val s = String.implode (List.rev lst)\nin\n ((token_STRING, s, #line_no ch, #column_no ch), inp)\nend\n\n(*------------------------------------------------------------------*)\n(* Character literals. *)\n\nfun\nscan_character_literal_without_checking_end inp =\nlet\n val (ch, inp) = Inp.get_ch inp\n val (ch1, inp) = Inp.get_ch inp\nin\n if #ichar ch1 = eof then\n raise Unterminated_character_literal\n (#line_no ch, #column_no ch)\n else if #ichar ch1 = Char.ord #\"\\\\\" then\n let\n val (ch2, inp) = Inp.get_ch inp\n in\n if #ichar ch2 = eof then\n raise Unterminated_character_literal\n (#line_no ch, #column_no ch)\n else if #ichar ch2 = Char.ord #\"n\" then\n let\n val s = Int.toString (Char.ord #\"\\n\")\n in\n ((token_INTEGER, s, #line_no ch, #column_no ch), inp)\n end\n else if #ichar ch2 = Char.ord #\"\\\\\" then\n let\n val s = Int.toString (Char.ord #\"\\\\\")\n in\n ((token_INTEGER, s, #line_no ch, #column_no ch), inp)\n end\n else\n raise Unsupported_escape (#line_no ch1, #column_no ch1,\n Char.chr (#ichar ch2))\n end\n else\n let\n val s = Int.toString (#ichar ch1)\n in\n ((token_INTEGER, s, #line_no ch, #column_no ch), inp)\n end\nend\n\nfun\nscan_character_literal inp =\nlet\n val (toktup, inp) =\n scan_character_literal_without_checking_end inp\n val (_, _, line_no, column_no) = toktup\n\n fun\n check_end inp =\n let\n val (ch, inp) = Inp.get_ch inp\n in\n if #ichar ch = Char.ord #\"'\" then\n inp\n else\n let\n fun\n loop_to_end (ch1 : Ch.t, inp) =\n if #ichar ch1 = eof then\n raise Unterminated_character_literal (line_no, column_no)\n else if #ichar ch1 = Char.ord #\"'\" then\n raise Multicharacter_literal (line_no, column_no)\n else\n let\n val (ch1, inp) = Inp.get_ch inp\n in\n loop_to_end (ch1, inp)\n end\n in\n loop_to_end (ch, inp)\n end\n end\n\n val inp = check_end inp\nin\n (toktup, inp)\nend\n\n(*------------------------------------------------------------------*)\n\nfun\nget_next_token inp =\nlet\n val inp = skip_spaces_and_comments inp\n val (ch, inp) = Inp.get_ch inp\n val ln = #line_no ch\n val cn = #column_no ch\nin\n if #ichar ch = eof then\n ((token_END_OF_INPUT, \"\", ln, cn), inp)\n else\n case Char.chr (#ichar ch) of\n #\",\" => ((token_COMMA, \",\", ln, cn), inp)\n | #\";\" => ((token_SEMICOLON, \";\", ln, cn), inp)\n | #\"(\" => ((token_LEFTPAREN, \"(\", ln, cn), inp)\n | #\")\" => ((token_RIGHTPAREN, \")\", ln, cn), inp)\n | #\"{\" => ((token_LEFTBRACE, \"{\", ln, cn), inp)\n | #\"}\" => ((token_RIGHTBRACE, \"}\", ln, cn), inp)\n | #\"*\" => ((token_MULTIPLY, \"*\", ln, cn), inp)\n | #\"/\" => ((token_DIVIDE, \"/\", ln, cn), inp)\n | #\"%\" => ((token_MOD, \"%\", ln, cn), inp)\n | #\"+\" => ((token_ADD, \"+\", ln, cn), inp)\n | #\"-\" => ((token_SUBTRACT, \"-\", ln, cn), inp)\n | #\"<\" =>\n let\n val (ch1, inp) = Inp.get_ch inp\n in\n if #ichar ch1 = Char.ord #\"=\" then\n ((token_LESSEQUAL, \"<=\", ln, cn), inp)\n else\n let\n val inp = Inp.push_back_ch (ch1, inp)\n in\n ((token_LESS, \"<\", ln, cn), inp)\n end\n end\n | #\">\" =>\n let\n val (ch1, inp) = Inp.get_ch inp\n in\n if #ichar ch1 = Char.ord #\"=\" then\n ((token_GREATEREQUAL, \">=\", ln, cn), inp)\n else\n let\n val inp = Inp.push_back_ch (ch1, inp)\n in\n ((token_GREATER, \">\", ln, cn), inp)\n end\n end\n | #\"=\" =>\n let\n val (ch1, inp) = Inp.get_ch inp\n in\n if #ichar ch1 = Char.ord #\"=\" then\n ((token_EQUAL, \"==\", ln, cn), inp)\n else\n let\n val inp = Inp.push_back_ch (ch1, inp)\n in\n ((token_ASSIGN, \"=\", ln, cn), inp)\n end\n end\n | #\"!\" =>\n let\n val (ch1, inp) = Inp.get_ch inp\n in\n if #ichar ch1 = Char.ord #\"=\" then\n ((token_NOTEQUAL, \"!=\", ln, cn), inp)\n else\n let\n val inp = Inp.push_back_ch (ch1, inp)\n in\n ((token_NOT, \"!\", ln, cn), inp)\n end\n end\n | #\"&\" =>\n let\n val (ch1, inp) = Inp.get_ch inp\n in\n if #ichar ch1 = Char.ord #\"&\" then\n ((token_AND, \"&&\", ln, cn), inp)\n else\n raise Unexpected_character (#line_no ch, #column_no ch,\n Char.chr (#ichar ch))\n end\n | #\"|\" =>\n let\n val (ch1, inp) = Inp.get_ch inp\n in\n if #ichar ch1 = Char.ord #\"|\" then\n ((token_OR, \"||\", ln, cn), inp)\n else\n raise Unexpected_character (#line_no ch, #column_no ch,\n Char.chr (#ichar ch))\n end\n | #\"\\\"\" =>\n let\n val inp = Inp.push_back_ch (ch, inp)\n in\n scan_string_literal inp\n end\n | #\"'\" =>\n let\n val inp = Inp.push_back_ch (ch, inp)\n in\n scan_character_literal inp\n end\n | _ =>\n if is_digit (#ichar ch) then\n let\n val inp = Inp.push_back_ch (ch, inp)\n in\n scan_integer_literal inp\n end\n else if is_ident_start (#ichar ch) then\n let\n val inp = Inp.push_back_ch (ch, inp)\n in\n scan_identifier_or_reserved_word inp\n end\n else\n raise Unexpected_character (#line_no ch, #column_no ch,\n Char.chr (#ichar ch))\nend\n\nfun\noutput_integer_rightjust (outf, num) =\n(if num < 10 then\n TextIO.output (outf, \" \")\n else if num < 100 then\n TextIO.output (outf, \" \")\n else if num < 1000 then\n TextIO.output (outf, \" \")\n else if num < 10000 then\n TextIO.output (outf, \" \")\n else\n ();\n TextIO.output (outf, Int.toString num))\n\nfun\nprint_token (outf, toktup) =\nlet\n val (token, arg, line_no, column_no) = toktup\n val name = token_name token\n val (padding, str) =\n if token = token_IDENTIFIER then\n (\" \", arg)\n else if token = token_INTEGER then\n (\" \", arg)\n else if token = token_STRING then\n (\" \", arg)\n else(\"\", \"\")\nin\n output_integer_rightjust (outf, line_no);\n TextIO.output (outf, \" \");\n output_integer_rightjust (outf, column_no);\n TextIO.output (outf, \" \");\n TextIO.output (outf, name);\n TextIO.output (outf, padding);\n TextIO.output (outf, str);\n TextIO.output (outf, \"\\n\")\nend\n\nfun\nscan_text (outf, inp) =\nlet\n fun\n loop inp =\n let\n val (toktup, inp) = get_next_token inp\n in\n (print_token (outf, toktup);\n let\n val (token, _, _, _) = toktup\n in\n if token <> token_END_OF_INPUT then\n loop inp\n else\n ()\n end)\n end\nin\n loop inp\nend\n\n(*------------------------------------------------------------------*)\n\nfun\nmain () =\nlet\n val args = CommandLine.arguments ()\n val (inpf_filename, outf_filename) =\n case args of\n [] => (\"-\", \"-\")\n | name :: [] => (name, \"-\")\n | name1 :: name2 :: _ => (name1, name2)\n val inpf =\n if inpf_filename = \"-\" then\n TextIO.stdIn\n else\n TextIO.openIn inpf_filename\n handle\n (IO.Io _) =>\n (TextIO.output (TextIO.stdErr, \"Failure opening \\\"\");\n TextIO.output (TextIO.stdErr, inpf_filename);\n TextIO.output (TextIO.stdErr, \"\\\" for input\\n\");\n OS.Process.exit OS.Process.failure)\n val outf =\n if outf_filename = \"-\" then\n TextIO.stdOut\n else\n TextIO.openOut outf_filename\n handle\n (IO.Io _) =>\n (TextIO.output (TextIO.stdErr, \"Failure opening \\\"\");\n TextIO.output (TextIO.stdErr, outf_filename);\n TextIO.output (TextIO.stdErr, \"\\\" for output\\n\");\n OS.Process.exit OS.Process.failure)\n val inp = Inp.of_instream inpf\nin\n scan_text (outf, inp)\nend\nhandle Unterminated_comment (line_no, column_no) =>\n (TextIO.output (TextIO.stdErr, \": unterminated comment \");\n TextIO.output (TextIO.stdErr, \"starting at \");\n TextIO.output (TextIO.stdErr, Int.toString line_no);\n TextIO.output (TextIO.stdErr, \":\");\n TextIO.output (TextIO.stdErr, Int.toString column_no);\n TextIO.output (TextIO.stdErr, \"\\n\");\n OS.Process.exit OS.Process.failure)\n | Unterminated_character_literal (line_no, column_no) =>\n (TextIO.output (TextIO.stdErr, \": unterminated character \");\n TextIO.output (TextIO.stdErr, \"literal starting at \");\n TextIO.output (TextIO.stdErr, Int.toString line_no);\n TextIO.output (TextIO.stdErr, \":\");\n TextIO.output (TextIO.stdErr, Int.toString column_no);\n TextIO.output (TextIO.stdErr, \"\\n\");\n OS.Process.exit OS.Process.failure)\n | Multicharacter_literal (line_no, column_no) =>\n (TextIO.output (TextIO.stdErr, \": unsupported multicharacter\");\n TextIO.output (TextIO.stdErr, \" literal starting at \");\n TextIO.output (TextIO.stdErr, Int.toString line_no);\n TextIO.output (TextIO.stdErr, \":\");\n TextIO.output (TextIO.stdErr, Int.toString column_no);\n TextIO.output (TextIO.stdErr, \"\\n\");\n OS.Process.exit OS.Process.failure)\n | End_of_input_in_string_literal (line_no, column_no) =>\n (TextIO.output (TextIO.stdErr, \": end of input in string\");\n TextIO.output (TextIO.stdErr, \" literal starting at \");\n TextIO.output (TextIO.stdErr, Int.toString line_no);\n TextIO.output (TextIO.stdErr, \":\");\n TextIO.output (TextIO.stdErr, Int.toString column_no);\n TextIO.output (TextIO.stdErr, \"\\n\");\n OS.Process.exit OS.Process.failure)\n | End_of_line_in_string_literal (line_no, column_no) =>\n (TextIO.output (TextIO.stdErr, \": end of line in string\");\n TextIO.output (TextIO.stdErr, \" literal starting at \");\n TextIO.output (TextIO.stdErr, Int.toString line_no);\n TextIO.output (TextIO.stdErr, \":\");\n TextIO.output (TextIO.stdErr, Int.toString column_no);\n TextIO.output (TextIO.stdErr, \"\\n\");\n OS.Process.exit OS.Process.failure)\n | Unsupported_escape (line_no, column_no, c) =>\n (TextIO.output (TextIO.stdErr, CommandLine.name ());\n TextIO.output (TextIO.stdErr, \": unsupported escape \\\\\");\n TextIO.output (TextIO.stdErr, Char.toString c);\n TextIO.output (TextIO.stdErr, \" at \");\n TextIO.output (TextIO.stdErr, Int.toString line_no);\n TextIO.output (TextIO.stdErr, \":\");\n TextIO.output (TextIO.stdErr, Int.toString column_no);\n TextIO.output (TextIO.stdErr, \"\\n\");\n OS.Process.exit OS.Process.failure)\n | Invalid_integer_literal (line_no, column_no, str) =>\n (TextIO.output (TextIO.stdErr, CommandLine.name ());\n TextIO.output (TextIO.stdErr, \": invalid integer literal \");\n TextIO.output (TextIO.stdErr, str);\n TextIO.output (TextIO.stdErr, \" at \");\n TextIO.output (TextIO.stdErr, Int.toString line_no);\n TextIO.output (TextIO.stdErr, \":\");\n TextIO.output (TextIO.stdErr, Int.toString column_no);\n TextIO.output (TextIO.stdErr, \"\\n\");\n OS.Process.exit OS.Process.failure)\n | Unexpected_character (line_no, column_no, c) =>\n (TextIO.output (TextIO.stdErr, CommandLine.name ());\n TextIO.output (TextIO.stdErr, \": unexpected character '\");\n TextIO.output (TextIO.stdErr, Char.toString c);\n TextIO.output (TextIO.stdErr, \"' at \");\n TextIO.output (TextIO.stdErr, Int.toString line_no);\n TextIO.output (TextIO.stdErr, \":\");\n TextIO.output (TextIO.stdErr, Int.toString column_no);\n TextIO.output (TextIO.stdErr, \"\\n\");\n OS.Process.exit OS.Process.failure);\n\n(*------------------------------------------------------------------*)\n(* For the Mlton compiler, include the following. For Poly/ML, comment\n it out. *)\nmain ();\n\n(*------------------------------------------------------------------*)\n(* Instructions for GNU Emacs. *)\n\n(* local variables: *)\n(* mode: sml *)\n(* sml-indent-level: 2 *)\n(* sml-indent-args: 2 *)\n(* end: *)\n(*------------------------------------------------------------------*)\n", "language": "Standard-ML" }, { "code": "import \"./dynamic\" for Enum, Struct, Tuple\nimport \"./str\" for Char\nimport \"./fmt\" for Fmt\nimport \"./ioutil\" for FileUtil\nimport \"os\" for Process\n\nvar tokens = [\n \"EOI\",\n \"Mul\",\n \"Div\",\n \"Mod\",\n \"Add\",\n \"Sub\",\n \"Negate\",\n \"Not\",\n \"Lss\",\n \"Leq\",\n \"Gtr\",\n \"Geq\",\n \"Eq\",\n \"Neq\",\n \"Assign\",\n \"And\",\n \"Or\",\n \"If\",\n \"Else\",\n \"While\",\n \"Print\",\n \"Putc\",\n \"Lparen\",\n \"Rparen\",\n \"Lbrace\",\n \"Rbrace\",\n \"Semi\",\n \"Comma\",\n \"Ident\",\n \"Integer\",\n \"String\"\n]\n\nvar Token = Enum.create(\"Token\", tokens)\n\nvar TokData = Struct.create(\"TokData\", [\"eline\", \"ecol\", \"tok\", \"v\"])\n\nvar Symbol = Tuple.create(\"Symbol\", [\"name\", \"tok\"])\n\n// symbol table\nvar symtab = []\n\nvar curLine = \"\"\nvar curCh = \"\"\nvar lineNum = 0\nvar colNum = 0\nvar etx = 4 // used to signify EOI\n\nvar lines = []\nvar lineCount = 0\n\nvar errorMsg = Fn.new { |eline, ecol, msg| Fiber.abort(\"(%(eline):%(ecol)) %(msg)\") }\n\n// add an identifier to the symbpl table\nvar install = Fn.new { |name, tok|\n var sym = Symbol.new(name, tok)\n symtab.add(sym)\n}\n\n// search for an identifier in the symbol table\nvar lookup = Fn.new { |name|\n for (i in 0...symtab.count) {\n if (symtab[i].name == name) return i\n }\n return -1\n}\n\n// read the next line of input from the source file\nvar nextLine // recursive function\nnextLine = Fn.new {\n if (lineNum == lineCount) {\n curCh = etx\n curLine = \"\"\n colNum = 1\n return\n }\n curLine = lines[lineNum]\n lineNum = lineNum + 1\n colNum = 0\n if (curLine == \"\") nextLine.call() // skip blank lines\n}\n\n// get the next char\nvar nextChar = Fn.new {\n if (colNum >= curLine.count) nextLine.call()\n if (colNum < curLine.count) {\n curCh = curLine[colNum]\n colNum = colNum + 1\n }\n}\n\nvar follow = Fn.new { |eline, ecol, expect, ifyes, ifno|\n if (curCh == expect) {\n nextChar.call()\n return ifyes\n }\n if (ifno == Token.EOI) {\n errorMsg.call(eline, ecol, \"follow unrecognized character: \" + curCh)\n }\n return ifno\n}\n\nvar getTok // recursive function\ngetTok = Fn.new {\n // skip whitespace\n while (curCh == \" \" || curCh == \"\\t\" || curCh == \"\\n\") nextChar.call()\n var td = TokData.new(lineNum, colNum, 0, \"\")\n if (curCh == etx) {\n td.tok = Token.EOI\n return td\n }\n if (curCh == \"{\") {\n td.tok = Token.Lbrace\n nextChar.call()\n return td\n }\n if (curCh == \"}\") {\n td.tok = Token.Rbrace\n nextChar.call()\n return td\n }\n if (curCh == \"(\") {\n td.tok = Token.Lparen\n nextChar.call()\n return td\n }\n if (curCh == \")\") {\n td.tok = Token.Rparen\n nextChar.call()\n return td\n }\n if (curCh == \"+\") {\n td.tok = Token.Add\n nextChar.call()\n return td\n }\n if (curCh == \"-\") {\n td.tok = Token.Sub\n nextChar.call()\n return td\n }\n if (curCh == \"*\") {\n td.tok = Token.Mul\n nextChar.call()\n return td\n }\n if (curCh == \"\\%\") {\n td.tok = Token.Mod\n nextChar.call()\n return td\n }\n if (curCh == \";\") {\n td.tok = Token.Semi\n nextChar.call()\n return td\n }\n if (curCh == \",\") {\n td.tok = Token.Comma\n nextChar.call()\n return td\n }\n if (curCh == \"'\") { // single char literals\n nextChar.call()\n td.v = curCh.bytes[0].toString\n if (curCh == \"'\") {\n errorMsg.call(td.eline, td.ecol, \"Empty character constant\")\n }\n if (curCh == \"\\\\\") {\n nextChar.call()\n if (curCh == \"n\") {\n td.v = \"10\"\n } else if (curCh == \"\\\\\") {\n td.v = \"92\"\n } else {\n errorMsg.call(td.eline, td.ecol, \"unknown escape sequence: \"+ curCh)\n }\n }\n nextChar.call()\n if (curCh != \"'\") {\n errorMsg.call(td.eline, td.ecol, \"multi-character constant\")\n }\n nextChar.call()\n td.tok = Token.Integer\n return td\n }\n if (curCh == \"<\") {\n nextChar.call()\n td.tok = follow.call(td.eline, td.ecol, \"=\", Token.Leq, Token.Lss)\n return td\n }\n if (curCh == \">\") {\n nextChar.call()\n td.tok = follow.call(td.eline, td.ecol, \"=\", Token.Geq, Token.Gtr)\n return td\n }\n if (curCh == \"!\") {\n nextChar.call()\n td.tok = follow.call(td.eline, td.ecol, \"=\", Token.Neq, Token.Not)\n return td\n }\n if (curCh == \"=\") {\n nextChar.call()\n td.tok = follow.call(td.eline, td.ecol, \"=\", Token.Eq, Token.Assign)\n return td\n }\n if (curCh == \"&\") {\n nextChar.call()\n td.tok = follow.call(td.eline, td.ecol, \"&\", Token.And, Token.EOI)\n return td\n }\n if (curCh == \"|\") {\n nextChar.call()\n td.tok = follow.call(td.eline, td.ecol, \"|\", Token.Or, Token.EOI)\n return td\n }\n if (curCh == \"\\\"\") { // string\n td.v = curCh\n nextChar.call()\n while (curCh != \"\\\"\") {\n if (curCh == \"\\n\") {\n errorMsg.call(td.eline, td.ecol, \"EOL in string\")\n }\n if (curCh == etx) {\n errorMsg.call(td.eline, td.ecol, \"EOF in string\")\n }\n td.v = td.v + curCh\n nextChar.call()\n }\n td.v = td.v + curCh\n nextChar.call()\n td.tok = Token.String\n return td\n }\n if (curCh == \"/\") { // div or comment\n nextChar.call()\n if (curCh != \"*\") {\n td.tok = Token.Div\n return td\n }\n // skip comments\n nextChar.call()\n while (true) {\n if (curCh == \"*\") {\n nextChar.call()\n if (curCh == \"/\") {\n nextChar.call()\n return getTok.call()\n }\n } else if (curCh == etx) {\n errorMsg.call(td.eline, td.ecol, \"EOF in comment\")\n } else {\n nextChar.call()\n }\n }\n }\n //integers or identifiers\n var isNumber = Char.isDigit(curCh)\n td.v = \"\"\n while (Char.isAsciiAlphaNum(curCh) || curCh == \"_\") {\n if (!Char.isDigit(curCh)) isNumber = false\n td.v = td.v + curCh\n nextChar.call()\n }\n if (td.v.count == 0) {\n errorMsg.call(td.eline, td.ecol, \"unknown character: \" + curCh)\n }\n if (Char.isDigit(td.v[0])) {\n if (!isNumber) {\n errorMsg.call(td.eline, td.ecol, \"invalid number: \" + curCh)\n }\n td.tok = Token.Integer\n return td\n }\n var index = lookup.call(td.v)\n td.tok = (index == -1) ? Token.Ident : symtab[index].tok\n return td\n}\n\nvar initLex = Fn.new {\n install.call(\"else\", Token.Else)\n install.call(\"if\", Token.If)\n install.call(\"print\", Token.Print)\n install.call(\"putc\", Token.Putc)\n install.call(\"while\", Token.While)\n nextChar.call()\n}\n\nvar process = Fn.new {\n var tokMap = {}\n tokMap[Token.EOI] = \"End_of_input\"\n tokMap[Token.Mul] = \"Op_multiply\"\n tokMap[Token.Div] = \"Op_divide\"\n tokMap[Token.Mod] = \"Op_mod\"\n tokMap[Token.Add] = \"Op_add\"\n tokMap[Token.Sub] = \"Op_subtract\"\n tokMap[Token.Negate] = \"Op_negate\"\n tokMap[Token.Not] = \"Op_not\"\n tokMap[Token.Lss] = \"Op_less\"\n tokMap[Token.Leq] = \"Op_lessequal\"\n tokMap[Token.Gtr] = \"Op_greater\"\n tokMap[Token.Geq] = \"Op_greaterequal\"\n tokMap[Token.Eq] = \"Op_equal\"\n tokMap[Token.Neq] = \"Op_notequal\"\n tokMap[Token.Assign] = \"Op_assign\"\n tokMap[Token.And] = \"Op_and\"\n tokMap[Token.Or] = \"Op_or\"\n tokMap[Token.If] = \"Keyword_if\"\n tokMap[Token.Else] = \"Keyword_else\"\n tokMap[Token.While] = \"Keyword_while\"\n tokMap[Token.Print] = \"Keyword_print\"\n tokMap[Token.Putc] = \"Keyword_putc\"\n tokMap[Token.Lparen] = \"LeftParen\"\n tokMap[Token.Rparen] = \"RightParen\"\n tokMap[Token.Lbrace] = \"LeftBrace\"\n tokMap[Token.Rbrace] = \"RightBrace\"\n tokMap[Token.Semi] = \"Semicolon\"\n tokMap[Token.Comma] = \"Comma\"\n tokMap[Token.Ident] = \"Identifier\"\n tokMap[Token.Integer] = \"Integer\"\n tokMap[Token.String] = \"String\"\n\n while (true) {\n var td = getTok.call()\n Fmt.write(\"$5d $5d $-16s\", td.eline, td.ecol, tokMap[td.tok])\n if (td.tok == Token.Integer || td.tok == Token.Ident || td.tok == Token.String) {\n System.print(td.v)\n } else {\n System.print()\n }\n if (td.tok == Token.EOI) return\n }\n}\n\nvar args = Process.arguments\nif (args.count == 0) {\n System.print(\"Filename required\")\n return\n}\n\nlines = FileUtil.readLines(args[0])\nlineCount = lines.count\ninitLex.call()\nprocess.call()\n", "language": "Wren" }, { "code": "const std = @import(\"std\");\n\npub const TokenType = enum {\n unknown,\n multiply,\n divide,\n mod,\n add,\n subtract,\n negate,\n less,\n less_equal,\n greater,\n greater_equal,\n equal,\n not_equal,\n not,\n assign,\n bool_and,\n bool_or,\n left_paren,\n right_paren,\n left_brace,\n right_brace,\n semicolon,\n comma,\n kw_if,\n kw_else,\n kw_while,\n kw_print,\n kw_putc,\n identifier,\n integer,\n string,\n eof,\n\n // More efficient implementation can be done with `std.enums.directEnumArray`.\n pub fn toString(self: @This()) []const u8 {\n return switch (self) {\n .unknown => \"UNKNOWN\",\n .multiply => \"Op_multiply\",\n .divide => \"Op_divide\",\n .mod => \"Op_mod\",\n .add => \"Op_add\",\n .subtract => \"Op_subtract\",\n .negate => \"Op_negate\",\n .less => \"Op_less\",\n .less_equal => \"Op_lessequal\",\n .greater => \"Op_greater\",\n .greater_equal => \"Op_greaterequal\",\n .equal => \"Op_equal\",\n .not_equal => \"Op_notequal\",\n .not => \"Op_not\",\n .assign => \"Op_assign\",\n .bool_and => \"Op_and\",\n .bool_or => \"Op_or\",\n .left_paren => \"LeftParen\",\n .right_paren => \"RightParen\",\n .left_brace => \"LeftBrace\",\n .right_brace => \"RightBrace\",\n .semicolon => \"Semicolon\",\n .comma => \"Comma\",\n .kw_if => \"Keyword_if\",\n .kw_else => \"Keyword_else\",\n .kw_while => \"Keyword_while\",\n .kw_print => \"Keyword_print\",\n .kw_putc => \"Keyword_putc\",\n .identifier => \"Identifier\",\n .integer => \"Integer\",\n .string => \"String\",\n .eof => \"End_of_input\",\n };\n }\n};\n\npub const TokenValue = union(enum) {\n intlit: i32,\n string: []const u8,\n};\n\npub const Token = struct {\n line: usize,\n col: usize,\n typ: TokenType = .unknown,\n value: ?TokenValue = null,\n};\n\n// Error conditions described in the task.\npub const LexerError = error{\n EmptyCharacterConstant,\n UnknownEscapeSequence,\n MulticharacterConstant,\n EndOfFileInComment,\n EndOfFileInString,\n EndOfLineInString,\n UnrecognizedCharacter,\n InvalidNumber,\n};\n\npub const Lexer = struct {\n content: []const u8,\n line: usize,\n col: usize,\n offset: usize,\n start: bool,\n\n const Self = @This();\n\n pub fn init(content: []const u8) Lexer {\n return Lexer{\n .content = content,\n .line = 1,\n .col = 1,\n .offset = 0,\n .start = true,\n };\n }\n\n pub fn buildToken(self: Self) Token {\n return Token{ .line = self.line, .col = self.col };\n }\n\n pub fn buildTokenT(self: Self, typ: TokenType) Token {\n return Token{ .line = self.line, .col = self.col, .typ = typ };\n }\n\n pub fn curr(self: Self) u8 {\n return self.content[self.offset];\n }\n\n // Alternative implementation is to return `Token` value from `next()` which is\n // arguably more idiomatic version.\n pub fn next(self: *Self) ?u8 {\n // We use `start` in order to make the very first invocation of `next()` to return\n // the very first character. It should be possible to avoid this variable.\n if (self.start) {\n self.start = false;\n } else {\n const newline = self.curr() == '\\n';\n self.offset += 1;\n if (newline) {\n self.col = 1;\n self.line += 1;\n } else {\n self.col += 1;\n }\n }\n if (self.offset >= self.content.len) {\n return null;\n } else {\n return self.curr();\n }\n }\n\n pub fn peek(self: Self) ?u8 {\n if (self.offset + 1 >= self.content.len) {\n return null;\n } else {\n return self.content[self.offset + 1];\n }\n }\n\n fn divOrComment(self: *Self) LexerError!?Token {\n var result = self.buildToken();\n if (self.peek()) |peek_ch| {\n if (peek_ch == '*') {\n _ = self.next(); // peeked character\n while (self.next()) |ch| {\n if (ch == '*') {\n if (self.peek()) |next_ch| {\n if (next_ch == '/') {\n _ = self.next(); // peeked character\n return null;\n }\n }\n }\n }\n return LexerError.EndOfFileInComment;\n }\n }\n result.typ = .divide;\n return result;\n }\n\n fn identifierOrKeyword(self: *Self) !Token {\n var result = self.buildToken();\n const init_offset = self.offset;\n while (self.peek()) |ch| : (_ = self.next()) {\n switch (ch) {\n '_', 'a'...'z', 'A'...'Z', '0'...'9' => {},\n else => break,\n }\n }\n const final_offset = self.offset + 1;\n\n if (std.mem.eql(u8, self.content[init_offset..final_offset], \"if\")) {\n result.typ = .kw_if;\n } else if (std.mem.eql(u8, self.content[init_offset..final_offset], \"else\")) {\n result.typ = .kw_else;\n } else if (std.mem.eql(u8, self.content[init_offset..final_offset], \"while\")) {\n result.typ = .kw_while;\n } else if (std.mem.eql(u8, self.content[init_offset..final_offset], \"print\")) {\n result.typ = .kw_print;\n } else if (std.mem.eql(u8, self.content[init_offset..final_offset], \"putc\")) {\n result.typ = .kw_putc;\n } else {\n result.typ = .identifier;\n result.value = TokenValue{ .string = self.content[init_offset..final_offset] };\n }\n\n return result;\n }\n\n fn string(self: *Self) !Token {\n var result = self.buildToken();\n result.typ = .string;\n const init_offset = self.offset;\n while (self.next()) |ch| {\n switch (ch) {\n '\"' => break,\n '\\n' => return LexerError.EndOfLineInString,\n '\\\\' => {\n switch (self.peek() orelse return LexerError.EndOfFileInString) {\n 'n', '\\\\' => _ = self.next(), // peeked character\n else => return LexerError.UnknownEscapeSequence,\n }\n },\n else => {},\n }\n } else {\n return LexerError.EndOfFileInString;\n }\n const final_offset = self.offset + 1;\n result.value = TokenValue{ .string = self.content[init_offset..final_offset] };\n return result;\n }\n\n /// Choose either `ifyes` or `ifno` token type depending on whether the peeked\n /// character is `by`.\n fn followed(self: *Self, by: u8, ifyes: TokenType, ifno: TokenType) Token {\n var result = self.buildToken();\n if (self.peek()) |ch| {\n if (ch == by) {\n _ = self.next(); // peeked character\n result.typ = ifyes;\n } else {\n result.typ = ifno;\n }\n } else {\n result.typ = ifno;\n }\n return result;\n }\n\n /// Raise an error if there's no next `by` character but return token with `typ` otherwise.\n fn consecutive(self: *Self, by: u8, typ: TokenType) LexerError!Token {\n const result = self.buildTokenT(typ);\n if (self.peek()) |ch| {\n if (ch == by) {\n _ = self.next(); // peeked character\n return result;\n } else {\n return LexerError.UnrecognizedCharacter;\n }\n } else {\n return LexerError.UnrecognizedCharacter;\n }\n }\n\n fn integerLiteral(self: *Self) LexerError!Token {\n var result = self.buildTokenT(.integer);\n const init_offset = self.offset;\n while (self.peek()) |ch| {\n switch (ch) {\n '0'...'9' => _ = self.next(), // peeked character\n '_', 'a'...'z', 'A'...'Z' => return LexerError.InvalidNumber,\n else => break,\n }\n }\n const final_offset = self.offset + 1;\n result.value = TokenValue{\n .intlit = std.fmt.parseInt(i32, self.content[init_offset..final_offset], 10) catch {\n return LexerError.InvalidNumber;\n },\n };\n return result;\n }\n\n // This is a beautiful way of how Zig allows to remove bilerplate and at the same time\n // to not lose any error completeness guarantees.\n fn nextOrEmpty(self: *Self) LexerError!u8 {\n return self.next() orelse LexerError.EmptyCharacterConstant;\n }\n\n fn integerChar(self: *Self) LexerError!Token {\n var result = self.buildTokenT(.integer);\n switch (try self.nextOrEmpty()) {\n '\\'', '\\n' => return LexerError.EmptyCharacterConstant,\n '\\\\' => {\n switch (try self.nextOrEmpty()) {\n 'n' => result.value = TokenValue{ .intlit = '\\n' },\n '\\\\' => result.value = TokenValue{ .intlit = '\\\\' },\n else => return LexerError.EmptyCharacterConstant,\n }\n switch (try self.nextOrEmpty()) {\n '\\'' => {},\n else => return LexerError.MulticharacterConstant,\n }\n },\n else => {\n result.value = TokenValue{ .intlit = self.curr() };\n switch (try self.nextOrEmpty()) {\n '\\'' => {},\n else => return LexerError.MulticharacterConstant,\n }\n },\n }\n return result;\n }\n};\n\npub fn lex(allocator: std.mem.Allocator, content: []u8) !std.ArrayList(Token) {\n var tokens = std.ArrayList(Token).init(allocator);\n var lexer = Lexer.init(content);\n while (lexer.next()) |ch| {\n switch (ch) {\n ' ' => {},\n '*' => try tokens.append(lexer.buildTokenT(.multiply)),\n '%' => try tokens.append(lexer.buildTokenT(.mod)),\n '+' => try tokens.append(lexer.buildTokenT(.add)),\n '-' => try tokens.append(lexer.buildTokenT(.subtract)),\n '<' => try tokens.append(lexer.followed('=', .less_equal, .less)),\n '>' => try tokens.append(lexer.followed('=', .greater_equal, .greater)),\n '=' => try tokens.append(lexer.followed('=', .equal, .assign)),\n '!' => try tokens.append(lexer.followed('=', .not_equal, .not)),\n '(' => try tokens.append(lexer.buildTokenT(.left_paren)),\n ')' => try tokens.append(lexer.buildTokenT(.right_paren)),\n '{' => try tokens.append(lexer.buildTokenT(.left_brace)),\n '}' => try tokens.append(lexer.buildTokenT(.right_brace)),\n ';' => try tokens.append(lexer.buildTokenT(.semicolon)),\n ',' => try tokens.append(lexer.buildTokenT(.comma)),\n '&' => try tokens.append(try lexer.consecutive('&', .bool_and)),\n '|' => try tokens.append(try lexer.consecutive('|', .bool_or)),\n '/' => {\n if (try lexer.divOrComment()) |token| try tokens.append(token);\n },\n '_', 'a'...'z', 'A'...'Z' => try tokens.append(try lexer.identifierOrKeyword()),\n '\"' => try tokens.append(try lexer.string()),\n '0'...'9' => try tokens.append(try lexer.integerLiteral()),\n '\\'' => try tokens.append(try lexer.integerChar()),\n else => {},\n }\n }\n try tokens.append(lexer.buildTokenT(.eof));\n\n return tokens;\n}\n\npub fn main() !void {\n var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);\n defer arena.deinit();\n const allocator = arena.allocator();\n\n var arg_it = std.process.args();\n _ = try arg_it.next(allocator) orelse unreachable; // program name\n const file_name = arg_it.next(allocator);\n // We accept both files and standard input.\n var file_handle = blk: {\n if (file_name) |file_name_delimited| {\n const fname: []const u8 = try file_name_delimited;\n break :blk try std.fs.cwd().openFile(fname, .{});\n } else {\n break :blk std.io.getStdIn();\n }\n };\n defer file_handle.close();\n const input_content = try file_handle.readToEndAlloc(allocator, std.math.maxInt(usize));\n\n const tokens = try lex(allocator, input_content);\n const pretty_output = try tokenListToString(allocator, tokens);\n _ = try std.io.getStdOut().write(pretty_output);\n}\n\nfn tokenListToString(allocator: std.mem.Allocator, token_list: std.ArrayList(Token)) ![]u8 {\n var result = std.ArrayList(u8).init(allocator);\n var w = result.writer();\n for (token_list.items) |token| {\n const common_args = .{ token.line, token.col, token.typ.toString() };\n if (token.value) |value| {\n const init_fmt = \"{d:>5}{d:>7} {s:<15}\";\n switch (value) {\n .string => |str| _ = try w.write(try std.fmt.allocPrint(\n allocator,\n init_fmt ++ \"{s}\\n\",\n common_args ++ .{str},\n )),\n .intlit => |i| _ = try w.write(try std.fmt.allocPrint(\n allocator,\n init_fmt ++ \"{d}\\n\",\n common_args ++ .{i},\n )),\n }\n } else {\n _ = try w.write(try std.fmt.allocPrint(allocator, \"{d:>5}{d:>7} {s}\\n\", common_args));\n }\n }\n return result.items;\n}\n", "language": "Zig" } ]
Compiler-lexical-analyzer
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter\n", "language": "00-META" }, { "code": "Virtual Machine Interpreter\n\nA virtual machine implements a computer in software.\n\n{{task heading}}\n\nWrite a virtual machine interpreter. This interpreter should be able to run virtual\nassembly language programs created via the [[Compiler/code_generator|task]]. This is a\nbyte-coded, 32-bit word stack based virtual machine.\n\nThe program should read input from a file and/or stdin, and write output to a file and/or\nstdout.\n\nInput format:\n\nGiven the following program:\n\n count = 1;\n while (count < 10) {\n print(\"count is: \", count, \"\\n\");\n count = count + 1;\n }\n\nThe output from the [[Compiler/code_generator|Code generator]] is a virtual assembly code program:\n\n{| class=\"wikitable\"\n|-\n! Output from gen, input to VM\n|-\n\n| style=\"vertical-align:top\" |\n<b><pre>Datasize: 1 Strings: 2\n\"count is: \"\n\"\\n\"\n 0 push 1\n 5 store [0]\n 10 fetch [0]\n 15 push 10\n 20 lt\n 21 jz (43) 65\n 26 push 0\n 31 prts\n 32 fetch [0]\n 37 prti\n 38 push 1\n 43 prts\n 44 fetch [0]\n 49 push 1\n 54 add\n 55 store [0]\n 60 jmp (-51) 10\n 65 halt</pre></b>\n|}\n\nThe first line of the input specifies the datasize required and the number of constant\nstrings, in the order that they are reference via the code.\n\nThe data can be stored in a separate array, or the data can be stored at the beginning of\nthe stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if\nreferenced at address 2.\n\nIf there are one or more constant strings, they come next. The code refers to these\nstrings by their index. The index starts at 0. So if there are 3 strings, and the code\nwants to reference the 3rd string, 2 will be used.\n\nNext comes the actual virtual assembly code. The first number is the code address of that\ninstruction. After that is the instruction mnemonic, followed by optional operands,\ndepending on the instruction.\n\nRegisters:\n\nsp:\n the stack pointer - points to the next top of stack. The stack is a 32-bit integer\n array.\n\npc:\n the program counter - points to the current instruction to be performed. The code is an\n array of bytes.\n\nData:\n data\n string pool\n\nInstructions:\n\nEach instruction is one byte. The following instructions also have a 32-bit integer\noperand:\n\n fetch [index]\n\nwhere index is an index into the data array.\n\n store [index]\n\nwhere index is an index into the data array.\n\n push n\n\nwhere value is a 32-bit integer that will be pushed onto the stack.\n\n jmp (n) addr\n\nwhere (n) is a 32-bit integer specifying the distance between the current location and the\ndesired location. addr is an unsigned value of the actual code address.\n\n jz (n) addr\n\nwhere (n) is a 32-bit integer specifying the distance between the current location and the\ndesired location. addr is an unsigned value of the actual code address.\n\nThe following instructions do not have an operand. They perform their operation directly\nagainst the stack:\n\nFor the following instructions, the operation is performed against the top two entries in\nthe stack:\n\n add\n sub\n mul\n div\n mod\n lt\n gt\n le\n ge\n eq\n ne\n and\n or\n\nFor the following instructions, the operation is performed against the top entry in the\nstack:\n\n neg\n not\n\nPrint the word at stack top as a character.\n\n prtc\n\nPrint the word at stack top as an integer.\n\n prti\n\nStack top points to an index into the string pool. Print that entry.\n\n prts\n\nUnconditional stop.\n\n halt\n\n; A simple example virtual machine:\n\n<syntaxhighlight lang=\"python\">def run_vm(data_size)\n int stack[data_size + 1000]\n set stack[0..data_size - 1] to 0\n int pc = 0\n while True:\n op = code[pc]\n pc += 1\n\n if op == FETCH:\n stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);\n pc += word_size\n elif op == STORE:\n stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();\n pc += word_size\n elif op == PUSH:\n stack.append(bytes_to_int(code[pc:pc+word_size])[0]);\n pc += word_size\n elif op == ADD: stack[-2] += stack[-1]; stack.pop()\n elif op == SUB: stack[-2] -= stack[-1]; stack.pop()\n elif op == MUL: stack[-2] *= stack[-1]; stack.pop()\n elif op == DIV: stack[-2] /= stack[-1]; stack.pop()\n elif op == MOD: stack[-2] %= stack[-1]; stack.pop()\n elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop()\n elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop()\n elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop()\n elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop()\n elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop()\n elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop()\n elif op == NEG: stack[-1] = -stack[-1]\n elif op == NOT: stack[-1] = not stack[-1]\n elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0]\n elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]\n elif op == PRTC: print stack[-1] as a character; stack.pop()\n elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop()\n elif op == PRTI: print stack[-1] as an integer; stack.pop()\n elif op == HALT: break</syntaxhighlight>\n\n; Additional examples\n\nYour solution should pass all the test cases above and the additional tests found '''[[Compiler/Sample_programs|Here]]'''.\n\n{{task heading|Reference}}\n\nThe C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* [[Compiler/lexical_analyzer|Lexical Analyzer task]]\n* [[Compiler/syntax_analyzer|Syntax Analyzer task]]\n* [[Compiler/code_generator|Code Generator task]]\n* [[Compiler/AST_interpreter|AST Interpreter task]]\n\n<hr>\n__TOC__\n\n", "language": "00-TASK" }, { "code": "--\n-- The Rosetta Code Virtual Machine, in Ada.\n--\n-- It is assumed the platform on which this program is run\n-- has two's-complement integers. (Otherwise one could modify\n-- the vmint_to_vmsigned and vmsigned_to_vmint functions. But\n-- the chances your binary integers are not two's-complement\n-- seem pretty low.)\n--\n\nwith Ada.Characters.Handling; use Ada.Characters.Handling;\nwith Ada.Command_Line; use Ada.Command_Line;\n\nwith Ada.Strings.Unbounded; use Ada.Strings.Unbounded;\nwith Ada.Strings.Unbounded.Text_IO; use Ada.Strings.Unbounded.Text_IO;\n\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams;\n\nwith Ada.Unchecked_Conversion;\n\nprocedure VM\nis\n bad_vm : exception;\n vm_limit_exceeded : exception;\n vm_runtime_error : exception;\n\n status : Exit_Status;\n input_file_name : Unbounded_String;\n output_file_name : Unbounded_String;\n input_file : File_Type;\n output_file : File_Type;\n\n-- Some limits of this implementation. You can adjust these to taste.\n strings_size : constant := 2_048;\n stack_size : constant := 2_048;\n data_size : constant := 2_048;\n code_size : constant := 32_768;\n\n type byte is mod 16#100#;\n type vmint is mod 16#1_0000_0000#;\n subtype vmsigned is Integer range -2_147_483_648 .. 2_147_483_647;\n\n op_halt : constant byte := 0;\n op_add : constant byte := 1;\n op_sub : constant byte := 2;\n op_mul : constant byte := 3;\n op_div : constant byte := 4;\n op_mod : constant byte := 5;\n op_lt : constant byte := 6;\n op_gt : constant byte := 7;\n op_le : constant byte := 8;\n op_ge : constant byte := 9;\n op_eq : constant byte := 10;\n op_ne : constant byte := 11;\n op_and : constant byte := 12;\n op_or : constant byte := 13;\n op_neg : constant byte := 14;\n op_not : constant byte := 15;\n op_prtc : constant byte := 16;\n op_prti : constant byte := 17;\n op_prts : constant byte := 18;\n op_fetch : constant byte := 19;\n op_store : constant byte := 20;\n op_push : constant byte := 21;\n op_jmp : constant byte := 22;\n op_jz : constant byte := 23;\n\n strings : array (0 .. strings_size - 1) of Unbounded_String;\n stack : array (0 .. stack_size - 1) of vmint;\n data : array (0 .. data_size - 1) of vmint;\n code : array (0 .. code_size) of byte;\n sp : vmint;\n pc : vmint;\n\n output_stream : Stream_Access;\n\n function vmsigned_to_vmint is new Ada.Unchecked_Conversion\n (Source => vmsigned, Target => vmint);\n\n function vmint_to_vmsigned is new Ada.Unchecked_Conversion\n (Source => vmint, Target => vmsigned);\n\n function twos_complement\n (x : in vmint)\n return vmint\n is\n begin\n return (not x) + 1;\n end twos_complement;\n\n function vmint_to_digits\n (x : in vmint)\n return Unbounded_String\n is\n s : Unbounded_String;\n z : vmint;\n begin\n if x = 0 then\n s := To_Unbounded_String (\"0\");\n else\n s := To_Unbounded_String (\"\");\n z := x;\n while z /= 0 loop\n s := Character'Val ((z rem 10) + Character'Pos ('0')) & s;\n z := z / 10;\n end loop;\n end if;\n return s;\n end vmint_to_digits;\n\n function digits_to_vmint\n (s : in String)\n return vmint\n is\n zero : constant Character := '0';\n zero_pos : constant Integer := Character'Pos (zero);\n retval : vmint;\n begin\n if s'Length < 1 then\n raise bad_vm with \"expected a numeric literal\";\n end if;\n retval := 0;\n for i in s'Range loop\n if Is_Decimal_Digit (s (i)) then\n retval :=\n (10 * retval) + vmint (Character'Pos (s (i)) - zero_pos);\n else\n raise bad_vm with \"expected a decimal digit\";\n end if;\n end loop;\n return retval;\n end digits_to_vmint;\n\n function string_to_vmint\n (s : in String)\n return vmint\n is\n retval : vmint;\n begin\n if s'Length < 1 then\n raise bad_vm with \"expected a numeric literal\";\n end if;\n if s (s'First) = '-' then\n if s'Length < 2 then\n raise bad_vm with \"expected a numeric literal\";\n end if;\n retval :=\n twos_complement (digits_to_vmint (s (s'First + 1 .. s'Last)));\n else\n retval := digits_to_vmint (s);\n end if;\n return retval;\n end string_to_vmint;\n\n procedure parse_header\n (s : in String;\n data_count : out vmint;\n strings_count : out vmint)\n is\n i : Positive;\n j : Positive;\n begin\n i := s'First;\n while i <= s'Last and then not Is_Decimal_Digit (s (i)) loop\n i := i + 1;\n end loop;\n\n j := i;\n while j <= s'Last and then Is_Decimal_Digit (s (j)) loop\n j := j + 1;\n end loop;\n\n data_count := digits_to_vmint (s (i .. j - 1));\n\n i := j;\n while i <= s'Last and then not Is_Decimal_Digit (s (i)) loop\n i := i + 1;\n end loop;\n\n j := i;\n while j <= s'Last and then Is_Decimal_Digit (s (j)) loop\n j := j + 1;\n end loop;\n\n strings_count := digits_to_vmint (s (i .. j - 1));\n end parse_header;\n\n function parse_string_literal\n (s : in String)\n return Unbounded_String\n is\n t : Unbounded_String;\n i : Positive;\n\n --\n -- A little trick to get around mistaken highlighting on the\n -- Rosetta Code site.\n --\n quote_string : constant String := \"\"\"\";\n quote : constant Character := quote_string (1);\n\n begin\n t := To_Unbounded_String (\"\");\n\n i := s'First;\n while i <= s'Last and then s (i) /= quote loop\n i := i + 1;\n end loop;\n\n if s'Last < i or else s (i) /= quote then\n raise bad_vm with \"expected a '\"\"'\";\n end if;\n\n i := i + 1;\n while i <= s'Last and then s (i) /= quote loop\n if s (i) /= '\\' then\n Append (t, s (i));\n i := i + 1;\n elsif s'Last < i + 1 then\n raise bad_vm with \"truncated string literal\";\n elsif s (i + 1) = 'n' then\n Append (t, Character'Val (10));\n i := i + 2;\n elsif s (i + 1) = '\\' then\n Append (t, '\\');\n i := i + 2;\n else\n raise bad_vm with \"unsupported escape sequence\";\n end if;\n end loop;\n\n return t;\n end parse_string_literal;\n\n function name_to_opcode\n (s : in String)\n return byte\n is\n retval : byte;\n begin\n if s = \"halt\" then\n retval := op_halt;\n elsif s = \"add\" then\n retval := op_add;\n elsif s = \"sub\" then\n retval := op_sub;\n elsif s = \"mul\" then\n retval := op_mul;\n elsif s = \"div\" then\n retval := op_div;\n elsif s = \"mod\" then\n retval := op_mod;\n elsif s = \"lt\" then\n retval := op_lt;\n elsif s = \"gt\" then\n retval := op_gt;\n elsif s = \"le\" then\n retval := op_le;\n elsif s = \"ge\" then\n retval := op_ge;\n elsif s = \"eq\" then\n retval := op_eq;\n elsif s = \"ne\" then\n retval := op_ne;\n elsif s = \"and\" then\n retval := op_and;\n elsif s = \"or\" then\n retval := op_or;\n elsif s = \"neg\" then\n retval := op_neg;\n elsif s = \"not\" then\n retval := op_not;\n elsif s = \"prtc\" then\n retval := op_prtc;\n elsif s = \"prti\" then\n retval := op_prti;\n elsif s = \"prts\" then\n retval := op_prts;\n elsif s = \"fetch\" then\n retval := op_fetch;\n elsif s = \"store\" then\n retval := op_store;\n elsif s = \"push\" then\n retval := op_push;\n elsif s = \"jmp\" then\n retval := op_jmp;\n elsif s = \"jz\" then\n retval := op_jz;\n else\n raise bad_vm with (\"unexpected opcode name\");\n end if;\n return retval;\n end name_to_opcode;\n\n procedure parse_instruction\n (s : in String;\n address : out vmint;\n opcode : out byte;\n arg : out vmint)\n is\n i : Positive;\n j : Positive;\n begin\n i := s'First;\n while i <= s'Last and then not Is_Decimal_Digit (s (i)) loop\n i := i + 1;\n end loop;\n\n j := i;\n while j <= s'Last and then Is_Decimal_Digit (s (j)) loop\n j := j + 1;\n end loop;\n\n address := digits_to_vmint (s (i .. j - 1));\n\n i := j;\n while i <= s'Last and then not Is_Letter (s (i)) loop\n i := i + 1;\n end loop;\n\n j := i;\n while j <= s'Last and then Is_Letter (s (j)) loop\n j := j + 1;\n end loop;\n\n opcode := name_to_opcode (s (i .. j - 1));\n\n i := j;\n while i <= s'Last and then Is_Space (s (i)) loop\n i := i + 1;\n end loop;\n\n if s'Last < i then\n arg := 0;\n else\n if not Is_Decimal_Digit (s (i)) and then s (i) /= '-' then\n i := i + 1;\n end if;\n j := i;\n while j <= s'Last\n and then (Is_Decimal_Digit (s (j)) or else s (j) = '-')\n loop\n j := j + 1;\n end loop;\n arg := string_to_vmint (s (i .. j - 1));\n end if;\n end parse_instruction;\n\n procedure read_and_parse_header\n (data_count : out vmint;\n strings_count : out vmint)\n is\n line : Unbounded_String;\n begin\n Get_Line (Current_Input, line);\n parse_header (To_String (line), data_count, strings_count);\n end read_and_parse_header;\n\n procedure read_parse_and_store_strings\n (strings_count : in vmint)\n is\n line : Unbounded_String;\n begin\n if strings_count /= 0 then\n if strings_size < strings_count then\n raise vm_limit_exceeded with \"strings limit exceeded\";\n end if;\n for i in 0 .. strings_count - 1 loop\n Get_Line (Current_Input, line);\n strings (Integer (i)) :=\n parse_string_literal (To_String (line));\n end loop;\n end if;\n end read_parse_and_store_strings;\n\n function opcode_takes_arg\n (opcode : in byte)\n return Boolean\n is\n retval : Boolean;\n begin\n if opcode = op_fetch then\n retval := True;\n elsif opcode = op_store then\n retval := True;\n elsif opcode = op_push then\n retval := True;\n elsif opcode = op_jmp then\n retval := True;\n elsif opcode = op_jz then\n retval := True;\n else\n retval := False;\n end if;\n return retval;\n end opcode_takes_arg;\n\n procedure read_parse_and_store_instructions\n is\n line : Unbounded_String;\n address : vmint;\n opcode : byte;\n arg : vmint;\n j : Positive;\n begin\n while not End_Of_File (Current_Input) loop\n Get_Line (Current_Input, line);\n\n j := 1;\n while j <= Length (line) and then Is_Space (Element (line, j))\n loop\n j := j + 1;\n end loop;\n\n if j <= Length (line) then\n parse_instruction (To_String (line), address, opcode, arg);\n if opcode_takes_arg (opcode) then\n if code_size - 4 <= address then\n raise vm_limit_exceeded with \"code space limit exceeded\";\n end if;\n code (Integer (address)) := opcode;\n --\n -- Little-endian storage.\n --\n code (Integer (address) + 1) := byte (arg and 16#FF#);\n code (Integer (address) + 2) :=\n byte ((arg / 16#100#) and 16#FF#);\n code (Integer (address) + 3) :=\n byte ((arg / 16#1_0000#) and 16#FF#);\n code (Integer (address) + 4) :=\n byte ((arg / 16#100_0000#) and 16#FF#);\n else\n if code_size <= address then\n raise vm_limit_exceeded with \"code space limit exceeded\";\n end if;\n code (Integer (address)) := opcode;\n end if;\n end if;\n end loop;\n end read_parse_and_store_instructions;\n\n procedure read_parse_and_store_program\n is\n data_count : vmint;\n strings_count : vmint;\n begin\n read_and_parse_header (data_count, strings_count);\n read_parse_and_store_strings (strings_count);\n read_parse_and_store_instructions;\n end read_parse_and_store_program;\n\n procedure pop_value\n (x : out vmint)\n is\n begin\n if sp = 0 then\n raise vm_runtime_error with \"stack underflow\";\n end if;\n sp := sp - 1;\n x := stack (Integer (sp));\n end pop_value;\n\n procedure push_value\n (x : in vmint)\n is\n begin\n if stack_size <= sp then\n raise vm_runtime_error with \"stack overflow\";\n end if;\n stack (Integer (sp)) := x;\n sp := sp + 1;\n end push_value;\n\n procedure get_value\n (x : out vmint)\n is\n begin\n if sp = 0 then\n raise vm_runtime_error with \"stack underflow\";\n end if;\n x := stack (Integer (sp) - 1);\n end get_value;\n\n procedure put_value\n (x : in vmint)\n is\n begin\n if sp = 0 then\n raise vm_runtime_error with \"stack underflow\";\n end if;\n stack (Integer (sp) - 1) := x;\n end put_value;\n\n procedure fetch_value\n (i : in vmint;\n x : out vmint)\n is\n begin\n if data_size <= i then\n raise vm_runtime_error with \"data boundary exceeded\";\n end if;\n x := data (Integer (i));\n end fetch_value;\n\n procedure store_value\n (i : in vmint;\n x : in vmint)\n is\n begin\n if data_size <= i then\n raise vm_runtime_error with \"data boundary exceeded\";\n end if;\n data (Integer (i)) := x;\n end store_value;\n\n procedure immediate_value\n (x : out vmint)\n is\n b0, b1, b2, b3 : vmint;\n begin\n if code_size - 4 <= pc then\n raise vm_runtime_error with \"code boundary exceeded\";\n end if;\n --\n -- Little-endian order.\n --\n b0 := vmint (code (Integer (pc)));\n b1 := vmint (code (Integer (pc) + 1));\n b2 := vmint (code (Integer (pc) + 2));\n b3 := vmint (code (Integer (pc) + 3));\n x :=\n b0 + (16#100# * b1) + (16#1_0000# * b2) + (16#100_0000# * b3);\n end immediate_value;\n\n procedure machine_add\n is\n x, y : vmint;\n begin\n pop_value (y);\n get_value (x);\n put_value (x + y);\n end machine_add;\n\n procedure machine_sub\n is\n x, y : vmint;\n begin\n pop_value (y);\n get_value (x);\n put_value (x - y);\n end machine_sub;\n\n procedure machine_mul\n is\n x, y : vmint;\n begin\n pop_value (y);\n get_value (x);\n put_value\n (vmsigned_to_vmint\n (vmint_to_vmsigned (x) * vmint_to_vmsigned (y)));\n end machine_mul;\n\n procedure machine_div\n is\n x, y : vmint;\n begin\n pop_value (y);\n get_value (x);\n put_value\n (vmsigned_to_vmint\n (vmint_to_vmsigned (x) / vmint_to_vmsigned (y)));\n end machine_div;\n\n procedure machine_mod\n is\n x, y : vmint;\n begin\n pop_value (y);\n get_value (x);\n put_value\n (vmsigned_to_vmint\n (vmint_to_vmsigned (x) rem vmint_to_vmsigned (y)));\n end machine_mod;\n\n procedure machine_lt\n is\n x, y : vmint;\n begin\n pop_value (y);\n get_value (x);\n if vmint_to_vmsigned (x) < vmint_to_vmsigned (y) then\n put_value (1);\n else\n put_value (0);\n end if;\n end machine_lt;\n\n procedure machine_gt\n is\n x, y : vmint;\n begin\n pop_value (y);\n get_value (x);\n if vmint_to_vmsigned (x) > vmint_to_vmsigned (y) then\n put_value (1);\n else\n put_value (0);\n end if;\n end machine_gt;\n\n procedure machine_le\n is\n x, y : vmint;\n begin\n pop_value (y);\n get_value (x);\n if vmint_to_vmsigned (x) <= vmint_to_vmsigned (y) then\n put_value (1);\n else\n put_value (0);\n end if;\n end machine_le;\n\n procedure machine_ge\n is\n x, y : vmint;\n begin\n pop_value (y);\n get_value (x);\n if vmint_to_vmsigned (x) >= vmint_to_vmsigned (y) then\n put_value (1);\n else\n put_value (0);\n end if;\n end machine_ge;\n\n procedure machine_eq\n is\n x, y : vmint;\n begin\n pop_value (y);\n get_value (x);\n if x = y then\n put_value (1);\n else\n put_value (0);\n end if;\n end machine_eq;\n\n procedure machine_ne\n is\n x, y : vmint;\n begin\n pop_value (y);\n get_value (x);\n if x /= y then\n put_value (1);\n else\n put_value (0);\n end if;\n end machine_ne;\n\n procedure machine_and\n is\n x, y : vmint;\n begin\n pop_value (y);\n get_value (x);\n if x /= 0 and y /= 0 then\n put_value (1);\n else\n put_value (0);\n end if;\n end machine_and;\n\n procedure machine_or\n is\n x, y : vmint;\n begin\n pop_value (y);\n get_value (x);\n if x /= 0 or y /= 0 then\n put_value (1);\n else\n put_value (0);\n end if;\n end machine_or;\n\n procedure machine_neg\n is\n x : vmint;\n begin\n get_value (x);\n put_value (twos_complement (x));\n end machine_neg;\n\n procedure machine_not\n is\n x : vmint;\n begin\n get_value (x);\n if x = 0 then\n put_value (1);\n else\n put_value (0);\n end if;\n end machine_not;\n\n procedure machine_prtc\n is\n x : vmint;\n begin\n pop_value (x);\n Character'Write (output_stream, Character'Val (x));\n end machine_prtc;\n\n procedure machine_prti\n is\n x : vmint;\n begin\n pop_value (x);\n if 16#7FFF_FFFF# < x then\n Character'Write (output_stream, '-');\n String'Write\n (output_stream,\n To_String (vmint_to_digits (twos_complement (x))));\n else\n String'Write (output_stream, To_String (vmint_to_digits (x)));\n end if;\n end machine_prti;\n\n procedure machine_prts\n is\n k : vmint;\n begin\n pop_value (k);\n if strings_size <= k then\n raise vm_runtime_error with \"strings boundary exceeded\";\n end if;\n String'Write (output_stream, To_String (strings (Integer (k))));\n end machine_prts;\n\n procedure machine_fetch\n is\n k : vmint;\n x : vmint;\n begin\n immediate_value (k);\n fetch_value (k, x);\n push_value (x);\n pc := pc + 4;\n end machine_fetch;\n\n procedure machine_store\n is\n k : vmint;\n x : vmint;\n begin\n immediate_value (k);\n pop_value (x);\n store_value (k, x);\n pc := pc + 4;\n end machine_store;\n\n procedure machine_push\n is\n x : vmint;\n begin\n immediate_value (x);\n push_value (x);\n pc := pc + 4;\n end machine_push;\n\n procedure machine_jmp\n is\n offset : vmint;\n begin\n immediate_value (offset);\n pc := pc + offset;\n end machine_jmp;\n\n procedure machine_jz\n is\n x : vmint;\n offset : vmint;\n begin\n pop_value (x);\n if x = 0 then\n immediate_value (offset);\n pc := pc + offset;\n else\n pc := pc + 4;\n end if;\n end machine_jz;\n\n procedure machine_step\n (halt : out Boolean)\n is\n opcode : byte;\n op_div_4, op_rem_4 : byte;\n begin\n if code_size <= pc then\n raise vm_runtime_error with \"code boundary exceeded\";\n end if;\n opcode := code (Integer (pc));\n pc := pc + 1;\n halt := False;\n op_div_4 := opcode / 4;\n op_rem_4 := opcode rem 4;\n if op_div_4 = 0 then\n if op_rem_4 = 0 then\n halt := True;\n elsif op_rem_4 = 1 then\n machine_add;\n elsif op_rem_4 = 2 then\n machine_sub;\n else\n machine_mul;\n end if;\n elsif op_div_4 = 1 then\n if op_rem_4 = 0 then\n machine_div;\n elsif op_rem_4 = 1 then\n machine_mod;\n elsif op_rem_4 = 2 then\n machine_lt;\n else\n machine_gt;\n end if;\n elsif op_div_4 = 2 then\n if op_rem_4 = 0 then\n machine_le;\n elsif op_rem_4 = 1 then\n machine_ge;\n elsif op_rem_4 = 2 then\n machine_eq;\n else\n machine_ne;\n end if;\n elsif op_div_4 = 3 then\n if op_rem_4 = 0 then\n machine_and;\n elsif op_rem_4 = 1 then\n machine_or;\n elsif op_rem_4 = 2 then\n machine_neg;\n else\n machine_not;\n end if;\n elsif op_div_4 = 4 then\n if op_rem_4 = 0 then\n machine_prtc;\n elsif op_rem_4 = 1 then\n machine_prti;\n elsif op_rem_4 = 2 then\n machine_prts;\n else\n machine_fetch;\n end if;\n elsif op_div_4 = 5 then\n if op_rem_4 = 0 then\n machine_store;\n elsif op_rem_4 = 1 then\n machine_push;\n elsif op_rem_4 = 2 then\n machine_jmp;\n else\n machine_jz;\n end if;\n else\n -- Treat anything unrecognized as equivalent to a halt.\n halt := True;\n end if;\n end machine_step;\n\n procedure machine_continue\n is\n halt : Boolean;\n begin\n halt := False;\n while not halt loop\n machine_step (halt);\n end loop;\n end machine_continue;\n\n procedure machine_run\n is\n begin\n sp := 0;\n pc := 0;\n for i in data'Range loop\n data (i) := 0;\n end loop;\n machine_continue;\n end machine_run;\n\nbegin\n status := 0;\n\n input_file_name := To_Unbounded_String (\"-\");\n\n if Argument_Count = 0 then\n null;\n elsif Argument_Count = 1 then\n input_file_name := To_Unbounded_String (Argument (1));\n else\n Put (\"Usage: \");\n Put (Command_Name);\n Put_Line (\" [INPUTFILE]\");\n Put (\"If either INPUTFILE is missing or \"\"-\"\",\");\n Put_Line (\" standard input is used.\");\n Put_Line (\"Output is always to standard output.\");\n status := 1;\n end if;\n\n if status = 0 then\n if input_file_name /= \"-\" then\n Open (input_file, In_File, To_String (input_file_name));\n Set_Input (input_file);\n end if;\n\n output_stream := Stream (Current_Output);\n read_parse_and_store_program;\n machine_run;\n\n if input_file_name /= \"-\" then\n Set_Input (Standard_Input);\n Close (input_file);\n end if;\n end if;\n\n Set_Exit_Status (status);\nend VM;\n", "language": "Ada" }, { "code": "integer n, pc, sp;\nfile f;\ntext s;\nindex code, Data;\nlist l, stack, strings;\n\nf.affix(argv(1));\n\nf.list(l, 0);\n\nn = atoi(l[-1]);\nwhile (n) {\n f.lead(s);\n strings.append(erase(s, -1, 0));\n n -= 1;\n}\n\nwhile (f.list(l, 0) ^ -1) {\n code.put(atoi(lf_x_text(l)), l);\n}\n\npc = sp = 0;\nwhile (1) {\n l = code[pc];\n s = l[0];\n if (s == \"jz\") {\n if (lb_pick(stack)) {\n isk_greater(code, pc, pc);\n } else {\n pc = atoi(l[-1]);\n }\n } elif (s == \"jmp\") {\n pc = atoi(l[-1]);\n } else {\n if (s == \"push\") {\n lb_push(stack, atoi(l[1]));\n } elif (s == \"fetch\") {\n lb_push(stack, Data[atoi(erase(l[1], -1, 0))]);\n } elif (s == \"neg\") {\n stack[-1] = -stack[-1];\n } elif (s == \"not\") {\n stack[-1] = !stack[-1];\n } elif (s == \"halt\") {\n break;\n } else {\n n = lb_pick(stack);\n if (s == \"store\") {\n Data[atoi(erase(l[1], -1, 0))] = n;\n } elif (s == \"add\") {\n stack[-1] = stack[-1] + n;\n } elif (s == \"sub\") {\n stack[-1] = stack[-1] - n;\n } elif (s == \"mul\") {\n stack[-1] = stack[-1] * n;\n } elif (s == \"div\") {\n stack[-1] = stack[-1] / n;\n } elif (s == \"mod\") {\n stack[-1] = stack[-1] % n;\n } elif (s == \"lt\") {\n stack[-1] = stack[-1] < n;\n } elif (s == \"gt\") {\n stack[-1] = stack[-1] > n;\n } elif (s == \"le\") {\n stack[-1] = stack[-1] <= n;\n } elif (s == \"ge\") {\n stack[-1] = stack[-1] >= n;\n } elif (s == \"eq\") {\n stack[-1] = stack[-1] == n;\n } elif (s == \"ne\") {\n stack[-1] = stack[-1] != n;\n } elif (s == \"and\") {\n stack[-1] = stack[-1] && n;\n } elif (s == \"or\") {\n stack[-1] = stack[-1] || n;\n } elif (s == \"prtc\") {\n o_byte(n);\n } elif (s == \"prti\") {\n o_(n);\n } elif (s == \"prts\") {\n o_(strings[n]);\n } else {\n }\n }\n\n isk_greater(code, pc, pc);\n }\n}\n", "language": "Aime" }, { "code": "begin % virtual machine interpreter %\n % string literals %\n string(256) array stringValue ( 0 :: 256 );\n integer array stringLength ( 0 :: 256 );\n integer MAX_STRINGS;\n % op codes %\n integer oFetch, oStore, oPush\n , oAdd, oSub, oMul, oDiv, oMod, oLt, oGt, oLe, oGe, oEq, oNe\n , oAnd, oOr, oNeg, oNot, oJmp, oJz, oPrtc, oPrts, oPrti, oHalt\n ;\n string(6) array opName ( 1 :: 24 );\n integer OP_MAX;\n % code %\n string(1) array byteCode ( 0 :: 4096 );\n integer nextLocation, MAX_LOCATION;\n % data %\n integer array data ( 0 :: 4096 );\n integer dataSize, MAX_DATA, MAX_STACK;\n % tracing %\n logical trace;\n\n % reports an error and stops %\n procedure rtError( string(80) value message ); begin\n integer errorPos;\n write( s_w := 0, \"**** Runtime error: \" );\n errorPos := 0;\n while errorPos < 80 and message( errorPos // 1 ) not = \".\" do begin\n writeon( s_w := 0, message( errorPos // 1 ) );\n errorPos := errorPos + 1\n end while_not_at_end_of_message ;\n writeon( s_w := 0, \".\" );\n assert( false )\n end genError ;\n\n oFetch := 1; opName( oFetch ) := \"fetch\"; oStore := 2; opName( oStore ) := \"store\"; oPush := 3; opName( oPush ) := \"push\";\n oAdd := 4; opName( oAdd ) := \"add\"; oSub := 5; opName( oSub ) := \"sub\"; oMul := 6; opName( oMul ) := \"mul\";\n oDiv := 7; opName( oDiv ) := \"div\"; oMod := 8; opName( oMod ) := \"mod\"; oLt := 9; opName( oLt ) := \"lt\";\n oGt := 10; opName( oGt ) := \"gt\"; oLe := 11; opName( oLe ) := \"le\"; oGe := 12; opName( oGe ) := \"ge\";\n oEq := 13; opName( oEq ) := \"eq\"; oNe := 14; opName( oNe ) := \"ne\"; oAnd := 15; opName( oAnd ) := \"and\";\n oOr := 16; opName( oOr ) := \"or\"; oNeg := 17; opName( oNeg ) := \"neg\"; oNot := 18; opName( oNot ) := \"not\";\n oJmp := 19; opName( oJmp ) := \"jmp\"; oJz := 20; opName( oJz ) := \"jz\"; oPrtc := 21; opName( oPrtc ) := \"prtc\";\n oPrts := 22; opName( oPrts ) := \"prts\"; oPrti := 23; opName( oPrti ) := \"prti\"; oHalt := 24; opName( oHalt ) := \"halt\";\n OP_MAX := oHalt;\n\n trace := false;\n MAX_STACK := 256;\n MAX_LOCATION := 4096;\n for pc := 0 until MAX_LOCATION do byteCode( pc ) := code( 0 );\n MAX_DATA := 4096;\n for dPos := 0 until MAX_DATA do data( dPos ) := 0;\n MAX_STRINGS := 256;\n for sPos := 0 until MAX_STRINGS do begin\n stringValue( sPos ) := \" \";\n stringLength( sPos ) := 0\n end for_sPos ;\n\n % load thge output from syntaxc analyser %\n begin % readCode %\n\n % skips spaces on the source line %\n procedure skipSpaces ; begin\n while line( lPos // 1 ) = \" \" do lPos := lPos + 1\n end skipSpaces ;\n\n % parses a string from line and stores it in the string literals table %\n procedure readString ( integer value stringNumber ) ; begin\n string(256) str;\n integer sLen;\n str := \" \";\n sLen := 0;\n lPos := lPos + 1; % skip the opening double-quote %\n while lPos <= 255 and line( lPos // 1 ) not = \"\"\"\" do begin\n str( sLen // 1 ) := line( lPos // 1 );\n sLen := sLen + 1;\n lPos := lPos + 1\n end while_more_string ;\n if lPos > 255 then rtError( \"Unterminated String.\" );\n % store the string %\n stringValue( stringNumber ) := str;\n stringLength( stringNumber ) := sLen\n end readString ;\n\n % gets an integer from the line - checks for valid digits %\n integer procedure readInteger ; begin\n integer n;\n skipSpaces;\n n := 0;\n while line( lPos // 1 ) >= \"0\" and line( lPos // 1 ) <= \"9\" do begin\n n := ( n * 10 ) + ( decode( line( lPos // 1 ) ) - decode( \"0\" ) );\n lPos := lPos + 1\n end while_not_end_of_integer ;\n n\n end readInteger ;\n\n % reads the next line from standard input %\n procedure readALine ; begin\n lPos := 0;\n readcard( line );\n if trace then write( s_w := 0, \">> \", line( 0 // 32 ) )\n end readALine ;\n\n % loads an instruction from the current source line %\n procedure loadCodeFromLine ; begin\n integer pc, opCode, operand, oPos;\n string(256) op;\n logical haveOperand;\n % get the code location %\n pc := readInteger;\n if pc > MAX_LOCATION then rtError( \"Code too large.\" );\n % get the opCode %\n skipSpaces;\n oPos := 0;\n op := \" \";\n while lPos <= 255 and line( lPos // 1 ) not = \" \" do begin\n op( oPos // 1 ) := line( lPos // 1 );\n oPos := oPos + 1;\n lPos := lPos + 1\n end while_more_opName ;\n % lookup the op code %\n opCode := 0;\n oPos := 1;\n while oPos <= OP_MAX and opCode = 0 do begin\n if opName( oPos ) = op then opCode := oPos\n else oPos := oPos + 1\n end while_op_not_found ;\n if opCode = 0 then rtError( \"Unknown op code.\" );\n % get the operand if there is one %\n operand := 0;\n haveOperand := false;\n if opCode = oFetch or opCode = oStore then begin\n % fetch or store - operand is enclosed in square brackets %\n skipSpaces;\n if line( lPos // 1 ) not = \"[\" then rtError( \"\"\"[\"\" expected after fetch/store.\" );\n lPos := lPos + 1;\n operand := readInteger;\n if operand > dataSize then rtError( \"fetch/store address out of range.\" );\n haveOperand := true\n end\n else if opCode = oPush then begin\n % push integer literal instruction %\n operand := readInteger;\n haveOperand := true\n end\n else if opCode = oJmp or opCode = oJz then begin\n % jump - the operand is the relative address enclosed in parenthesis %\n % followed by the absolute address - we use the absolute address so %\n % the opewrand will be >= 0 %\n skipSpaces;\n if line( lPos // 1 ) not = \"(\" then rtError( \"\"\"(\"\" expected after jmp/jz.\" );\n lPos := lPos + 1;\n if line( lPos // 1 ) = \"-\" then % negative relative address % lPos := lPos + 1;\n operand := readInteger;\n if line( lPos // 1 ) not = \")\" then rtError( \"\"\")\"\" expected after jmp/jz.\" );\n lPos := lPos + 1;\n operand := readInteger;\n haveOperand := true\n end if_various_opcodes ;\n % store the code %\n byteCode( pc ) := code( opCode );\n if haveOperand then begin\n % have an operand for the op code %\n if ( pc + 4 ) > MAX_LOCATION then rtError( \"Code too large.\" );\n for oPos := 1 until 4 do begin\n pc := pc + 1;\n byteCode( pc ) := code( operand rem 256 );\n operand := operand div 256;\n end for_oPos\n end if_have_operand ;\n end loadCodeFromLine ;\n\n string(256) line;\n string(16) name;\n integer lPos, tPos, stringCount;\n\n % allow us to detect EOF %\n ENDFILE := EXCEPTION( false, 1, 0, false, \"EOF\" );\n\n % first line should be \"Datasize: d Strings: s\" where d = number variables %\n % and s = number of strings %\n readALine;\n if line = \"trace\" then begin\n % extension - run in trace mode %\n trace := true;\n readALine\n end if_line_eq_trace ;\n if XCPNOTED(ENDFILE) then rtError( \"Empty program file.\" );\n if line( 0 // 10 ) not = \"Datasize: \" then rtError( \"Header line missing.\" );\n lPos := 10;\n dataSize := readInteger;\n if dataSize > MAX_DATA then rtError( \"Datasize too large.\" );\n skipSpaces;\n if line( lPos // 9 ) not = \"Strings: \" then rtError( \"\"\"Strings: \"\" missing on header line.\" );\n lPos := lPos + 9;\n stringCount := readInteger;\n if stringCount > MAX_STRINGS then rtError( \"Too many strings.\" );\n % read the string table %\n for stringNumber := 0 until stringCount - 1 do begin\n string(256) str;\n integer sLen, sPos;\n readALine;\n if XCPNOTED(ENDFILE) then rtError( \"End-of-file in string table.\" );\n if line( lPos // 1 ) not = \"\"\"\" then rtError( \"String literal expected.\" );\n str := \" \";\n sLen := 0;\n lPos := lPos + 1; % skip the opening double-quote %\n while lPos <= 255 and line( lPos // 1 ) not = \"\"\"\" do begin\n str( sLen // 1 ) := line( lPos // 1 );\n sLen := sLen + 1;\n lPos := lPos + 1\n end while_more_string ;\n if lPos > 255 then rtError( \"Unterminated String.\" );\n % store the string %\n stringValue( stringNumber ) := str;\n stringLength( stringNumber ) := sLen\n end for_sPos ;\n % read the code %\n readALine;\n while not XCPNOTED(ENDFILE) do begin\n if line not = \" \" then loadCodeFromLine;\n readALine\n end while_not_eof\n end;\n % run the program %\n begin\n integer pc, opCode, operand, sp;\n integer array st ( 0 :: MAX_STACK );\n logical halted;\n % prints a string from the string pool, escape sequences are interpreted %\n procedure writeOnString( integer value stringNumber ) ;\n begin\n integer cPos, sLen;\n string(256) text;\n if stringNumber < 0 or stringNumber > MAX_STRINGS then rtError( \"Invalid string number.\" );\n cPos := 0;\n sLen := stringLength( stringNumber );\n text := stringValue( stringNumber );\n while cPos < stringLength( stringNumber ) do begin\n string(1) ch;\n ch := text( cPos // 1 );\n if ch not = \"\\\" then writeon( s_w := 0, ch )\n else begin\n % escaped character %\n cPos := cPos + 1;\n if cPos > sLen then rtError( \"String terminates with \"\"\\\"\".\" );\n ch := text( cPos // 1 );\n if ch = \"n\" then % newline % write()\n else writeon( s_w := 0, ch )\n end;\n cPos := cPos + 1\n end while_not_end_of_string\n end writeOnString ;\n\n pc := 0;\n sp := -1;\n halted := false;\n while not halted do begin;\n % get the next op code and operand %\n opCode := decode( byteCode( pc ) );\n pc := pc + 1;\n operand := 0;\n if opCode = oFetch or opCode = oStore or opCode = oPush or opCode = oJmp or opCode = oJz then begin\n % this opCode has an operand %\n pc := pc + 4;\n for bPos := 1 until 4 do begin\n operand := ( operand * 256 ) + decode( byteCode( pc - bPos ) );\n end for_bPos\n end if_opCode_with_an_operand ;\n if trace then begin\n write( i_w:= 1, s_w := 0, pc, \" op(\", opCode, \"): \", opName( opCode ), \" \", operand );\n write()\n end if_trace ;\n % interpret the instruction %\n if opCode = oFetch then begin sp := sp + 1; st( sp ) := data( operand ) end\n else if opCode = oStore then begin data( operand ) := st( sp ); sp := sp - 1 end\n else if opCode = oPush then begin sp := sp + 1; st( sp ) := operand end\n else if opCode = oHalt then halted := true\n else if opCode = oJmp then pc := operand\n else if oPCode = oJz then begin\n if st( sp ) = 0 then pc := operand;\n sp := sp - 1\n end\n else if opCode = oPrtc then begin writeon( i_w := 1, s_w := 0, code( st( sp ) ) ); sp := sp - 1 end\n else if opCode = oPrti then begin writeon( i_w := 1, s_w := 0, st( sp ) ); sp := sp - 1 end\n else if opCode = oPrts then begin writeonString( st( sp ) ); sp := sp - 1 end\n else if opCode = oNeg then st( sp ) := - st( sp )\n else if opCode = oNot then st( sp ) := ( if st( sp ) = 0 then 1 else 0 )\n else begin\n operand := st( sp );\n sp := sp - 1;\n if opCode = oAdd then st( sp ) := st( sp ) + operand\n else if opCode = oSub then st( sp ) := st( sp ) - operand\n else if opCode = oMul then st( sp ) := st( sp ) * operand\n else if opCode = oDiv then st( sp ) := st( sp ) div operand\n else if opCode = oMod then st( sp ) := st( sp ) rem operand\n else if opCode = oLt then st( sp ) := if st( sp ) < operand then 1 else 0\n else if opCode = oGt then st( sp ) := if st( sp ) > operand then 1 else 0\n else if opCode = oLe then st( sp ) := if st( sp ) <= operand then 1 else 0\n else if opCode = oGe then st( sp ) := if st( sp ) >= operand then 1 else 0\n else if opCode = oEq then st( sp ) := if st( sp ) = operand then 1 else 0\n else if opCode = oNe then st( sp ) := if st( sp ) not = operand then 1 else 0\n else if opCode = oAnd then st( sp ) := if st( sp ) not = 0 and operand not = 0 then 1 else 0\n else if opCode = oOr then st( sp ) := if st( sp ) not = 0 or operand not = 0 then 1 else 0\n else rtError( \"Unknown opCode.\" )\n end if_various_opCodes\n end while_not_halted\n end\nend.\n", "language": "ALGOL-W" }, { "code": "(*\n Usage: vm [INPUTFILE [OUTPUTFILE]]\n If INPUTFILE or OUTPUTFILE is \"-\" or missing, then standard input\n or standard output is used, respectively.\n\n The Rosetta Code virtual machine task in ATS2 (also known as\n Postiats).\n\n Some implementation notes:\n\n * Values are stored as uint32, and it is checked that uint32\n really is 32 bits, two’s-complement. Addition and subtraction\n are allowed to roll around, and so can be done without casting\n to int32. (The C standard specifies that unsigned integer values\n will roll around, rather than signal an overflow.)\n\n * Where it matters, the uint32 are stored in little-endian\n order. I have *not* optimized the code for x86/AMD64 (which are\n little-endian and also can address unaligned data).\n\n * Here I am often writing out code instead of using some library\n function. Partly this is to improve code safety (proof at\n compile-time that buffers are not overrun, proof of loop\n termination, etc.). Partly this is because I do not feel like\n using the C library (or ATS interfaces to it) all that much.\n\n * I am using linear types and so forth, because I think it\n interesting to do so. It is unnecessary to use a garbage\n collector, because there (hopefully) are no memory leaks. (Not\n that we couldn’t simply let memory leak, for this little program\n with no REPL.)\n\n*)\n\n#define ATS_EXTERN_PREFIX \"rosettacode_vm_\"\n#define ATS_DYNLOADFLAG 0 (* No initialization is needed. *)\n\n#include \"share/atspre_define.hats\"\n#include \"share/atspre_staload.hats\"\n\nstaload UN = \"prelude/SATS/unsafe.sats\"\n\n#define NIL list_vt_nil ()\n#define :: list_vt_cons\n\n(* The stack has a fixed size but is very large. (Alternatively, one\ncould make the stack double in size whenever it overflows. Design\noptions such as using a linked list for the stack come with a\nperformance penalty.) *)\n#define VMSTACK_SIZE 65536\nmacdef vmstack_size = (i2sz VMSTACK_SIZE)\n\n(* In this program, exceptions are not meant to be caught, unless\n the catcher terminates the program. Linear types and\n general exception-catching do not go together well. *)\nexception bad_vm of string\nexception vm_runtime_error of string\n\n(********************************************************************)\n(* *)\n(* Some string functions that are safe against buffer overruns. *)\n(* *)\n\nfn\nskip_whitespace {n, i : int | 0 <= i; i <= n}\n (s : string n,\n n : size_t n,\n i : size_t i) :\n [j : int | i <= j; j <= n]\n size_t j =\n let\n fun\n loop {k : int | i <= k; k <= n} .<n - k>.\n (k : size_t k) :\n [j : int | i <= j; j <= n]\n size_t j =\n if k = n then\n k\n else if isspace (s[k]) then\n loop (succ k)\n else\n k\n in\n loop (i)\n end\n\nfn\nskip_non_whitespace {n, i : int | 0 <= i; i <= n}\n (s : string n,\n n : size_t n,\n i : size_t i) :\n [j : int | i <= j; j <= n]\n size_t j =\n let\n fun\n loop {k : int | i <= k; k <= n} .<n - k>.\n (k : size_t k) :\n [j : int | i <= j; j <= n]\n size_t j =\n if k = n then\n k\n else if isspace (s[k]) then\n k\n else\n loop (succ k)\n in\n loop (i)\n end\n\nfn\nsubstr_equal {n, i, j : int | 0 <= i; i <= j; j <= n}\n {m : int | 0 <= m}\n (s : string n,\n i : size_t i,\n j : size_t j,\n t : string m) : bool =\n (* Is s[i .. j-1] equal to t? *)\n let\n val m = string_length t\n in\n if m <> j - i then\n false\n else\n let\n fun\n loop {k : int | 0 <= k; k <= m} .<m - k>.\n (k : size_t k) : bool =\n if k = m then\n true\n else if s[i + k] <> t[k] then\n false\n else\n loop (succ k)\n in\n loop (i2sz 0)\n end\n end\n\n(********************************************************************)\n(* *)\n(* vmint = 32-bit two’s-complement numbers. *)\n(* *)\n\nstadef vmint_kind = uint32_kind\ntypedef vmint = uint32\n\nextern castfn i2vm : int -<> vmint\nextern castfn u2vm : uint -<> vmint\nextern castfn byte2vm : byte -<> vmint\n\nextern castfn vm2i : vmint -<> int\nextern castfn vm2sz : vmint -<> size_t\nextern castfn vm2byte : vmint -<> byte\n\n%{^\n\n/*\n * The ATS prelude might not have C implementations of all the\n * operations we would like to have, so here are some.\n */\n\ntypedef uint32_t vmint_t;\n\nATSinline() vmint_t\nrosettacode_vm_g0uint_add_vmint (vmint_t x, vmint_t y)\n{\n return (x + y);\n}\n\nATSinline() vmint_t\nrosettacode_vm_g0uint_sub_vmint (vmint_t x, vmint_t y)\n{\n return (x - y);\n}\n\nATSinline() int\nrosettacode_vm_g0uint_eq_vmint (vmint_t x, vmint_t y)\n{\n return (x == y);\n}\n\nATSinline() int\nrosettacode_vm_g0uint_neq_vmint (vmint_t x, vmint_t y)\n{\n return (x != y);\n}\n\nATSinline() vmint_t\nrosettacode_vm_g0uint_equality_vmint (vmint_t x, vmint_t y)\n{\n return (vmint_t) (x == y);\n}\n\nATSinline() vmint_t\nrosettacode_vm_g0uint_inequality_vmint (vmint_t x, vmint_t y)\n{\n return (vmint_t) (x != y);\n}\n\nATSinline() vmint_t\nrosettacode_vm_g0uint_signed_lt_vmint (vmint_t x, vmint_t y)\n{\n return (vmint_t) ((int32_t) x < (int32_t) y);\n}\n\nATSinline() vmint_t\nrosettacode_vm_g0uint_signed_gt_vmint (vmint_t x, vmint_t y)\n{\n return (vmint_t) ((int32_t) x > (int32_t) y);\n}\n\nATSinline() vmint_t\nrosettacode_vm_g0uint_signed_lte_vmint (vmint_t x, vmint_t y)\n{\n return (vmint_t) ((int32_t) x <= (int32_t) y);\n}\n\nATSinline() vmint_t\nrosettacode_vm_g0uint_signed_gte_vmint (vmint_t x, vmint_t y)\n{\n return (vmint_t) ((int32_t) x >= (int32_t) y);\n}\n\nATSinline() vmint_t\nrosettacode_vm_g0uint_signed_mul_vmint (vmint_t x, vmint_t y)\n{\n return (vmint_t) ((int32_t) x * (int32_t) y);\n}\n\nATSinline() vmint_t\nrosettacode_vm_g0uint_signed_div_vmint (vmint_t x, vmint_t y)\n{\n return (vmint_t) ((int32_t) x / (int32_t) y);\n}\n\nATSinline() vmint_t\nrosettacode_vm_g0uint_signed_mod_vmint (vmint_t x, vmint_t y)\n{\n return (vmint_t) ((int32_t) x % (int32_t) y);\n}\n\nATSinline() vmint_t\nrosettacode_vm_g0uint_logical_not_vmint (vmint_t x)\n{\n return (vmint_t) (!x);\n}\n\nATSinline() vmint_t\nrosettacode_vm_g0uint_logical_and_vmint (vmint_t x, vmint_t y)\n{\n return (vmint_t) ((!!x) * (!!y));\n}\n\nATSinline() vmint_t\nrosettacode_vm_g0uint_logical_or_vmint (vmint_t x, vmint_t y)\n{\n return (vmint_t) (1 - ((!x) * (!y)));\n}\n\n%}\n\nextern fn g0uint_add_vmint (x : vmint, y : vmint) :<> vmint = \"mac#%\"\nextern fn g0uint_sub_vmint (x : vmint, y : vmint) :<> vmint = \"mac#%\"\nextern fn g0uint_eq_vmint (x : vmint, y : vmint) :<> bool = \"mac#%\"\nextern fn g0uint_neq_vmint (x : vmint, y : vmint) :<> bool = \"mac#%\"\n\nimplement g0uint_add<vmint_kind> (x, y) = g0uint_add_vmint (x, y)\nimplement g0uint_sub<vmint_kind> (x, y) = g0uint_sub_vmint (x, y)\nimplement g0uint_eq<vmint_kind> (x, y) = g0uint_eq_vmint (x, y)\nimplement g0uint_neq<vmint_kind> (x, y) = g0uint_neq_vmint (x, y)\n\nextern fn\ng0uint_signed_mul_vmint (x : vmint, y : vmint) :<> vmint = \"mac#%\"\nextern fn\ng0uint_signed_div_vmint (x : vmint, y : vmint) :<> vmint = \"mac#%\"\nextern fn\ng0uint_signed_mod_vmint (x : vmint, y : vmint) :<> vmint = \"mac#%\"\nextern fn\ng0uint_equality_vmint (x : vmint, y : vmint) :<> vmint = \"mac#%\"\nextern fn\ng0uint_inequality_vmint (x : vmint, y : vmint) :<> vmint = \"mac#%\"\nextern fn\ng0uint_signed_lt_vmint (x : vmint, y : vmint) :<> vmint = \"mac#%\"\nextern fn\ng0uint_signed_gt_vmint (x : vmint, y : vmint) :<> vmint = \"mac#%\"\nextern fn\ng0uint_signed_lte_vmint (x : vmint, y : vmint) :<> vmint = \"mac#%\"\nextern fn\ng0uint_signed_gte_vmint (x : vmint, y : vmint) :<> vmint = \"mac#%\"\nextern fn\ng0uint_logical_not_vmint (x : vmint) :<> vmint = \"mac#%\"\nextern fn\ng0uint_logical_and_vmint (x : vmint, y : vmint) :<> vmint = \"mac#%\"\nextern fn\ng0uint_logical_or_vmint (x : vmint, y : vmint) :<> vmint = \"mac#%\"\n\noverload signed_mul with g0uint_signed_mul_vmint\noverload signed_div with g0uint_signed_div_vmint\noverload signed_mod with g0uint_signed_mod_vmint\noverload equality with g0uint_equality_vmint\noverload inequality with g0uint_inequality_vmint\noverload signed_lt with g0uint_signed_lt_vmint\noverload signed_gt with g0uint_signed_gt_vmint\noverload signed_lte with g0uint_signed_lte_vmint\noverload signed_gte with g0uint_signed_gte_vmint\noverload logical_not with g0uint_logical_not_vmint\noverload logical_and with g0uint_logical_and_vmint\noverload logical_or with g0uint_logical_or_vmint\n\nfn {}\ntwos_complement (x : vmint) :<>\n vmint =\n (~x) + i2vm 1\n\nfn\nensure_that_vmint_is_suitable () : void =\n {\n val _ = assertloc (u2vm (0xFFFFFFFFU) + u2vm 1U = u2vm 0U)\n val _ = assertloc (u2vm 0U - u2vm 1U = u2vm (0xFFFFFFFFU))\n val _ = assertloc (i2vm (~1234) = twos_complement (i2vm 1234))\n }\n\nfn\nparse_digits {n, i, j : int | 0 <= i; i <= j; j <= n}\n (s : string n,\n i : size_t i,\n j : size_t j) :\n vmint =\n let\n val bad_integer = \"Bad integer.\"\n fun\n loop {k : int | i <= k; k <= j} .<j - k>.\n (k : size_t k,\n x : vmint) : vmint =\n if k = j then\n x\n else if ~isdigit (s[k]) then\n $raise bad_vm (bad_integer)\n else\n (* The result is allowed to overflow freely. *)\n loop (succ k, (i2vm 10 * x) + i2vm (char2i s[k] - char2i '0'))\n in\n if j = i then\n $raise bad_vm (bad_integer)\n else\n loop (i, i2vm 0)\n end\n\nfn\nparse_integer {n, i, j : int | 0 <= i; i <= j; j <= n}\n (s : string n,\n i : size_t i,\n j : size_t j) :\n vmint =\n let\n val bad_integer = \"Bad integer.\"\n in\n if j = i then\n $raise bad_vm (bad_integer)\n else if j = succ i && ~isdigit (s[i]) then\n $raise bad_vm (bad_integer)\n else if s[i] <> '-' then\n parse_digits (s, i, j)\n else if succ i = j then\n $raise bad_vm (bad_integer)\n else\n twos_complement (parse_digits (s, succ i, j))\n end\n\n(********************************************************************)\n(* *)\n(* A linear array type for elements of vmint, byte, etc. *)\n(* *)\n\nvtypedef vmarray_vt (t : t@ype+, n : int, p : addr) =\n @{\n pf = @[t][n] @ p,\n pfgc = mfree_gc_v p |\n n = size_t n,\n p = ptr p\n }\nvtypedef vmarray_vt (t : t@ype+, n : int) =\n [p : addr] vmarray_vt (t, n, p)\n\nfn {t : t@ype}\nvmarray_vt_alloc {n : int}\n (n : size_t n,\n fill : t) :\n [p : addr | null < p]\n vmarray_vt (t, n, p) =\n let\n val @(pf, pfgc | p) = array_ptr_alloc<t> (n)\n val _ = array_initize_elt (!p, n, fill)\n in\n @{\n pf = pf,\n pfgc = pfgc |\n n = n,\n p = p\n }\n end\n\nfn {t : t@ype}\nvmarray_vt_free {n : int}\n {p : addr}\n (arr : vmarray_vt (t, n, p)) :\n void =\n let\n val @{\n pf = pf,\n pfgc = pfgc |\n n = n,\n p = p\n } = arr\n in\n array_ptr_free (pf, pfgc | p)\n end\n\nfn {t : t@ype}\nvmarray_vt_fill {n : int}\n {p : addr}\n (arr : !vmarray_vt (t, n, p),\n fill : t) :\n void =\n array_initize_elt (!(arr.p), (arr.n), fill)\n\nfn {t : t@ype}\n {tk : tkind}\nvmarray_vt_get_at_g1int {n, i : int | 0 <= i; i < n}\n (arr : !vmarray_vt (t, n),\n i : g1int (tk, i)) :\n t =\n array_get_at (!(arr.p), i)\n\nfn {t : t@ype}\n {tk : tkind}\nvmarray_vt_get_at_g1uint {n, i : int | 0 <= i; i < n}\n (arr : !vmarray_vt (t, n),\n i : g1uint (tk, i)) :\n t =\n array_get_at (!(arr.p), i)\n\noverload [] with vmarray_vt_get_at_g1int\noverload [] with vmarray_vt_get_at_g1uint\n\nfn {t : t@ype}\n {tk : tkind}\nvmarray_vt_set_at_g1int {n, i : int | 0 <= i; i < n}\n (arr : !vmarray_vt (t, n),\n i : g1int (tk, i),\n x : t) :\n void =\n array_set_at (!(arr.p), i, x)\n\nfn {t : t@ype}\n {tk : tkind}\nvmarray_vt_set_at_g1uint {n, i : int | 0 <= i; i < n}\n (arr : !vmarray_vt (t, n),\n i : g1uint (tk, i),\n x : t) :\n void =\n array_set_at (!(arr.p), i, x)\n\noverload [] with vmarray_vt_set_at_g1int\noverload [] with vmarray_vt_set_at_g1uint\n\nfn {t : t@ype}\nvmarray_vt_length {n : int}\n (arr : !vmarray_vt (t, n)) :<>\n size_t n =\n arr.n\n\n(********************************************************************)\n(* *)\n(* Storage for the strings section. *)\n(* *)\n\nvtypedef vmstring_vt (n : int, p : addr) =\n @{\n (* A vmstring_vt is NUL-terminated, and thus there is [n + 1]\n instead of [n] in the following declaration. *)\n pf = @[char][n + 1] @ p,\n pfgc = mfree_gc_v p |\n length = size_t n,\n p = ptr p\n }\nvtypedef vmstring_vt (n : int) = [p : addr] vmstring_vt (n, p)\nvtypedef vmstring_vt = [n : int | 0 <= n] vmstring_vt (n)\n\nvtypedef vmstrings_section_vt (n : int, p : addr) =\n @{\n pf = @[vmstring_vt][n] @ p,\n pfgc = mfree_gc_v p |\n n = size_t n,\n p = ptr p\n }\nvtypedef vmstrings_section_vt (n : int) =\n [p : addr] vmstrings_section_vt (n, p)\n\nfn {t : t@ype}\nvmstrings_section_vt_length {n : int}\n (arr : !vmstrings_section_vt (n)) :<>\n size_t n =\n arr.n\n\nfn\nvmstring_vt_free {n : int}\n {p : addr}\n (s : vmstring_vt (n, p)) :\n void =\n array_ptr_free (s.pf, s.pfgc | s.p)\n\nfn\nvmstrings_section_vt_free {n : int}\n {p : addr}\n (strings : vmstrings_section_vt (n, p)) :\n void =\n {\n fun\n free_the_strings {n : int | 0 <= n}\n {p : addr} .<n>.\n (pf : !(@[vmstring_vt][n] @ p) >>\n @[vmstring_vt?][n] @ p |\n n : size_t n,\n p : ptr p) : void =\n if n = 0 then\n {\n prval _ = pf :=\n array_v_unnil_nil {vmstring_vt, vmstring_vt?} pf\n }\n else\n {\n prval @(pf_element, pf_rest) = array_v_uncons pf\n val _ = vmstring_vt_free (!p)\n val p_next = ptr_succ<vmstring_vt> (p)\n val _ = free_the_strings (pf_rest | pred n, p_next)\n prval _ = pf := array_v_cons (pf_element, pf_rest)\n }\n\n val @{\n pf = pf,\n pfgc = pfgc |\n n = n,\n p = p\n } = strings\n prval _ = lemma_g1uint_param n\n val _ = free_the_strings (pf | n, p)\n val _ = array_ptr_free (pf, pfgc | p)\n }\n\nfn\nquoted_string_length {n : int | 0 <= n}\n (s : string n,\n n : size_t n) :\n [m : int | 0 <= m; m <= n - 2]\n size_t m =\n let\n val bad_quoted_string = \"Bad quoted string.\"\n\n fun\n loop {i : int | 1 <= i; i <= n - 1}\n {j : int | 0 <= j; j <= i - 1} .<n - i>.\n (i : size_t i,\n j : size_t j) :\n [k : int | 0 <= k; k <= n - 2]\n size_t k =\n if i = pred n then\n j\n else if s[i] <> '\\\\' then\n loop (succ i, succ j)\n else if succ i = pred n then\n $raise bad_vm (bad_quoted_string)\n else if s[succ i] = 'n' || s[succ i] = '\\\\' then\n loop (succ (succ i), succ j)\n else\n $raise bad_vm (bad_quoted_string)\n in\n if n < i2sz 2 then\n $raise bad_vm (bad_quoted_string)\n else if s[0] <> '\"' then\n $raise bad_vm (bad_quoted_string)\n else if s[pred n] <> '\"' then\n $raise bad_vm (bad_quoted_string)\n else\n loop (i2sz 1, i2sz 0)\n end\n\nfn\ndequote_string {m, n : int | 0 <= m; m <= n - 2}\n (s : string n,\n n : size_t n,\n t : !vmstring_vt m) :\n void =\n let\n fun\n loop {i : int | 1 <= i; i <= n - 1}\n {j : int | 0 <= j; j <= i - 1} .<n - i>.\n (t : !vmstring_vt m,\n i : size_t i,\n j : size_t j) : void =\n let\n macdef t_str = !(t.p)\n in\n if i = pred n then\n ()\n else if (t.length) < j then\n assertloc (false)\n else if s[i] <> '\\\\' then\n begin\n t_str[j] := s[i];\n loop (t, succ i, succ j)\n end\n else if succ i = pred n then\n assertloc (false)\n else if s[succ i] = 'n' then\n begin\n t_str[j] := '\\n';\n loop (t, succ (succ i), succ j)\n end\n else\n begin\n t_str[j] := s[succ i];\n loop (t, succ (succ i), succ j)\n end\n end\n in\n loop (t, i2sz 1, i2sz 0)\n end\n\nfn\nread_vmstrings {strings_size : int}\n {strings_addr : addr}\n (pf_strings :\n !(@[vmstring_vt?][strings_size] @ strings_addr) >>\n @[vmstring_vt][strings_size] @ strings_addr |\n f : FILEref,\n strings_size : size_t strings_size,\n strings : ptr strings_addr) :\n void =\n let\n prval _ = lemma_g1uint_param strings_size\n\n fun\n loop {k : int | 0 <= k; k <= strings_size} .<strings_size - k>.\n (lst : list_vt (vmstring_vt, k),\n k : size_t k) :\n list_vt (vmstring_vt, strings_size) =\n if k = strings_size then\n list_vt_reverse (lst)\n else\n let\n val bad_quoted_string = \"Bad quoted string.\"\n val line = fileref_get_line_string (f)\n val s = $UN.strptr2string (line)\n val n = string_length s\n val str_length = quoted_string_length (s, n)\n val (pf, pfgc | p) =\n array_ptr_alloc<char> (succ str_length)\n val _ = array_initize_elt (!p, succ str_length, '\\0')\n val vmstring =\n @{\n pf = pf,\n pfgc = pfgc |\n length = str_length,\n p = p\n }\n in\n dequote_string (s, n, vmstring);\n free line;\n loop (vmstring :: lst, succ k)\n end\n\n val lst = loop (NIL, i2sz 0)\n in\n array_initize_list_vt<vmstring_vt>\n (!strings, sz2i strings_size, lst)\n end\n\nfn\nvmstrings_section_vt_read {strings_size : int}\n (f : FILEref,\n strings_size : size_t strings_size) :\n [p : addr]\n vmstrings_section_vt (strings_size, p) =\n let\n val @(pf, pfgc | p) = array_ptr_alloc<vmstring_vt> strings_size\n val _ = read_vmstrings (pf | f, strings_size, p)\n in\n @{\n pf = pf,\n pfgc = pfgc |\n n = strings_size,\n p = p\n }\n end\n\nfn\nvmstring_fprint {n, i : int | i < n}\n (f : FILEref,\n strings : !vmstrings_section_vt n,\n i : size_t i) :\n void =\n {\n\n (*\n * The following code does some ‘unsafe’ tricks. For instance, it\n * is assumed each stored string is NUL-terminated.\n *)\n\n fn\n print_it (str : !vmstring_vt) : void =\n fileref_puts (f, $UN.cast{string} (str.p))\n\n prval _ = lemma_g1uint_param i\n val p_element = array_getref_at (!(strings.p), i)\n val @(pf_element | p_element) =\n $UN.castvwtp0\n {[n : int; p : addr] @(vmstring_vt @ p | ptr p)}\n (p_element)\n val _ = print_it (!p_element)\n prval _ = $UN.castview0{void} pf_element\n }\n\n(********************************************************************)\n(* *)\n(* vm_vt: the dataviewtype for a virtual machine. *)\n(* *)\n\ndatavtype instruction_vt =\n| instruction_vt_1 of (byte)\n| instruction_vt_5 of (byte, byte, byte, byte, byte)\n\n#define OPCODE_COUNT 24\n\n#define OP_HALT 0x0000 // 00000\n#define OP_ADD 0x0001 // 00001\n#define OP_SUB 0x0002 // 00010\n#define OP_MUL 0x0003 // 00011\n#define OP_DIV 0x0004 // 00100\n#define OP_MOD 0x0005 // 00101\n#define OP_LT 0x0006 // 00110\n#define OP_GT 0x0007 // 00111\n#define OP_LE 0x0008 // 01000\n#define OP_GE 0x0009 // 01001\n#define OP_EQ 0x000A // 01010\n#define OP_NE 0x000B // 01011\n#define OP_AND 0x000C // 01100\n#define OP_OR 0x000D // 01101\n#define OP_NEG 0x000E // 01110\n#define OP_NOT 0x000F // 01111\n#define OP_PRTC 0x0010 // 10000\n#define OP_PRTI 0x0011 // 10001\n#define OP_PRTS 0x0012 // 10010\n#define OP_FETCH 0x0013 // 10011\n#define OP_STORE 0x0014 // 10100\n#define OP_PUSH 0x0015 // 10101\n#define OP_JMP 0x0016 // 10110\n#define OP_JZ 0x0017 // 10111\n\n#define REGISTER_PC 0\n#define REGISTER_SP 1\n#define MAX_REGISTER REGISTER_SP\n\nvtypedef vm_vt (strings_size : int,\n strings_addr : addr,\n code_size : int,\n code_addr : addr,\n data_size : int,\n data_addr : addr,\n stack_size : int,\n stack_addr : addr) =\n @{\n strings = vmstrings_section_vt (strings_size, strings_addr),\n code = vmarray_vt (byte, code_size, code_addr),\n data = vmarray_vt (vmint, data_size, data_addr),\n stack = vmarray_vt (vmint, stack_size, stack_addr),\n registers = vmarray_vt (vmint, MAX_REGISTER + 1)\n }\n\nvtypedef vm_vt (strings_size : int,\n code_size : int,\n data_size : int,\n stack_size : int) =\n [strings_addr : addr]\n [code_addr : addr]\n [data_addr : addr]\n [stack_addr : addr]\n vm_vt (strings_size, strings_addr,\n code_size, code_addr,\n data_size, data_addr,\n stack_size, stack_addr)\n\nvtypedef vm_vt =\n [strings_size : int]\n [code_size : int]\n [data_size : int]\n [stack_size : int]\n vm_vt (strings_size, code_size, data_size, stack_size)\n\nfn\nvm_vt_free (vm : vm_vt) :\n void =\n let\n val @{\n strings = strings,\n code = code,\n data = data,\n stack = stack,\n registers = registers\n } = vm\n in\n vmstrings_section_vt_free strings;\n vmarray_vt_free<byte> code;\n vmarray_vt_free<vmint> data;\n vmarray_vt_free<vmint> stack;\n vmarray_vt_free<vmint> registers\n end\n\nfn\nopcode_name_to_byte {n, i, j : int | 0 <= i; i <= j; j <= n}\n (arr : &(@[String0][OPCODE_COUNT]),\n str : string n,\n i : size_t i,\n j : size_t j) :\n byte =\n let\n fun\n loop {k : int | 0 <= k; k <= OPCODE_COUNT} .<OPCODE_COUNT - k>.\n (arr : &(@[String0][OPCODE_COUNT]),\n k : int k) : byte =\n if k = OPCODE_COUNT then\n $raise bad_vm (\"Unrecognized opcode name.\")\n else if substr_equal (str, i, j, arr[k]) then\n i2byte k\n else\n loop (arr, succ k)\n in\n loop (arr, 0)\n end\n\nfn {}\nvmint_byte0 (i : vmint) :<>\n byte =\n vm2byte (i land (u2vm 0xFFU))\n\nfn {}\nvmint_byte1 (i : vmint) :<>\n byte =\n vm2byte ((i >> 8) land (u2vm 0xFFU))\n\nfn {}\nvmint_byte2 (i : vmint) :<>\n byte =\n vm2byte ((i >> 16) land (u2vm 0xFFU))\n\nfn {}\nvmint_byte3 (i : vmint) :<>\n byte =\n vm2byte (i >> 24)\n\nfn\nparse_instruction {n : int | 0 <= n}\n (arr : &(@[String0][OPCODE_COUNT]),\n line : string n) :\n instruction_vt =\n let\n val bad_instruction = \"Bad VM instruction.\"\n val n = string_length (line)\n val i = skip_whitespace (line, n, i2sz 0)\n\n (* Skip the address field*)\n val i = skip_non_whitespace (line, n, i)\n\n val i = skip_whitespace (line, n, i)\n val j = skip_non_whitespace (line, n, i)\n val opcode = opcode_name_to_byte (arr, line, i, j)\n\n val start_of_argument = j\n\n fn\n finish_push () :\n instruction_vt =\n let\n val i1 = skip_whitespace (line, n, start_of_argument)\n val j1 = skip_non_whitespace (line, n, i1)\n val arg = parse_integer (line, i1, j1)\n in\n (* Little-endian storage. *)\n instruction_vt_5 (opcode, vmint_byte0 arg, vmint_byte1 arg,\n vmint_byte2 arg, vmint_byte3 arg)\n end\n\n fn\n finish_fetch_or_store () :\n instruction_vt =\n let\n val i1 = skip_whitespace (line, n, start_of_argument)\n val j1 = skip_non_whitespace (line, n, i1)\n in\n if j1 - i1 < i2sz 3 then\n $raise bad_vm (bad_instruction)\n else if line[i1] <> '\\[' || line[pred j1] <> ']' then\n $raise bad_vm (bad_instruction)\n else\n let\n val arg = parse_integer (line, succ i1, pred j1)\n in\n (* Little-endian storage. *)\n instruction_vt_5 (opcode, vmint_byte0 arg, vmint_byte1 arg,\n vmint_byte2 arg, vmint_byte3 arg)\n end\n end\n\n fn\n finish_jmp_or_jz () :\n instruction_vt =\n let\n val i1 = skip_whitespace (line, n, start_of_argument)\n val j1 = skip_non_whitespace (line, n, i1)\n in\n if j1 - i1 < i2sz 3 then\n $raise bad_vm (bad_instruction)\n else if line[i1] <> '\\(' || line[pred j1] <> ')' then\n $raise bad_vm (bad_instruction)\n else\n let\n val arg = parse_integer (line, succ i1, pred j1)\n in\n (* Little-endian storage. *)\n instruction_vt_5 (opcode, vmint_byte0 arg, vmint_byte1 arg,\n vmint_byte2 arg, vmint_byte3 arg)\n end\n end\n in\n case+ byte2int0 opcode of\n | OP_PUSH => finish_push ()\n | OP_FETCH => finish_fetch_or_store ()\n | OP_STORE => finish_fetch_or_store ()\n | OP_JMP => finish_jmp_or_jz ()\n | OP_JZ => finish_jmp_or_jz ()\n | _ => instruction_vt_1 (opcode)\n end\n\nfn\nread_instructions (f : FILEref,\n arr : &(@[String0][OPCODE_COUNT])) :\n (List_vt (instruction_vt), Size_t) =\n (* Read the instructions from the input, producing a list of\n instruction_vt objects, and also calculating the total\n number of bytes in the instructions. *)\n let\n fun\n loop (arr : &(@[String0][OPCODE_COUNT]),\n lst : List_vt (instruction_vt),\n bytes_needed : Size_t) :\n @(List_vt (instruction_vt), Size_t) =\n if fileref_is_eof f then\n @(list_vt_reverse lst, bytes_needed)\n else\n let\n val line = fileref_get_line_string (f)\n in\n if fileref_is_eof f then\n begin\n free line;\n @(list_vt_reverse lst, bytes_needed)\n end\n else\n let\n val instruction =\n parse_instruction (arr, $UN.strptr2string line)\n val _ = free line\n prval _ = lemma_list_vt_param lst\n in\n case+ instruction of\n | instruction_vt_1 _ =>\n loop (arr, instruction :: lst, bytes_needed + i2sz 1)\n | instruction_vt_5 _ =>\n loop (arr, instruction :: lst, bytes_needed + i2sz 5)\n end\n end\n in\n loop (arr, NIL, i2sz 0)\n end\n\nfn\nlist_of_instructions_to_code {bytes_needed : int}\n (lst : List_vt (instruction_vt),\n bytes_needed : size_t bytes_needed) :\n [bytes_needed : int]\n vmarray_vt (byte, bytes_needed) =\n (* This routine consumes and destroys lst. *)\n let\n fun\n loop {n : int | 0 <= n} .<n>.\n (code : &vmarray_vt (byte, bytes_needed),\n lst : list_vt (instruction_vt, n),\n i : Size_t) : void =\n case+ lst of\n | ~ NIL => ()\n | ~ head :: tail =>\n begin\n case head of\n | ~ instruction_vt_1 (byte1) =>\n let\n val _ = assertloc (i < bytes_needed)\n in\n code[i] := byte1;\n loop (code, tail, i + i2sz 1)\n end\n | ~ instruction_vt_5 (byte1, byte2, byte3, byte4, byte5) =>\n let\n val _ = assertloc (i + i2sz 4 < bytes_needed)\n in\n code[i] := byte1;\n code[i + i2sz 1] := byte2;\n code[i + i2sz 2] := byte3;\n code[i + i2sz 3] := byte4;\n code[i + i2sz 4] := byte5;\n loop (code, tail, i + i2sz 5)\n end\n end\n\n var code = vmarray_vt_alloc<byte> (bytes_needed, i2byte OP_HALT)\n\n prval _ = lemma_list_vt_param lst\n prval _ = lemma_g1uint_param bytes_needed\n val _ = loop (code, lst, i2sz 0)\n in\n code\n end\n\nfn\nread_and_parse_code (f : FILEref,\n arr : &(@[String0][OPCODE_COUNT])) :\n [bytes_needed : int]\n vmarray_vt (byte, bytes_needed) =\n let\n val @(instructions, bytes_needed) = read_instructions (f, arr)\n in\n list_of_instructions_to_code (instructions, bytes_needed)\n end\n\nfn\nparse_header_line {n : int | 0 <= n}\n (line : string n) :\n @(vmint, vmint) =\n let\n val bad_vm_header_line = \"Bad VM header line.\"\n val n = string_length (line)\n val i = skip_whitespace (line, n, i2sz 0)\n val j = skip_non_whitespace (line, n, i)\n val _ = if ~substr_equal (line, i, j, \"Datasize:\") then\n $raise bad_vm (bad_vm_header_line)\n val i = skip_whitespace (line, n, j)\n val j = skip_non_whitespace (line, n, i)\n val data_size = parse_integer (line, i, j)\n val i = skip_whitespace (line, n, j)\n val j = skip_non_whitespace (line, n, i)\n val _ = if ~substr_equal (line, i, j, \"Strings:\") then\n $raise bad_vm (bad_vm_header_line)\n val i = skip_whitespace (line, n, j)\n val j = skip_non_whitespace (line, n, i)\n val strings_size = parse_integer (line, i, j)\n in\n @(data_size, strings_size)\n end\n\nfn\nread_vm (f : FILEref,\n opcode_names_arr : &(@[String0][OPCODE_COUNT])) :\n vm_vt =\n let\n val line = fileref_get_line_string (f)\n\n val @(data_size, strings_size) =\n parse_header_line ($UN.strptr2string line)\n\n val _ = free line\n\n val [data_size : int] data_size =\n g1ofg0 (vm2sz data_size)\n val [strings_size : int] strings_size =\n g1ofg0 (vm2sz strings_size)\n\n prval _ = lemma_g1uint_param data_size\n prval _ = lemma_g1uint_param strings_size\n\n prval _ = prop_verify {0 <= data_size} ()\n prval _ = prop_verify {0 <= strings_size} ()\n\n val strings = vmstrings_section_vt_read (f, strings_size)\n val code = read_and_parse_code (f, opcode_names_arr)\n val data = vmarray_vt_alloc<vmint> (data_size, i2vm 0)\n val stack = vmarray_vt_alloc<vmint> (vmstack_size, i2vm 0)\n val registers = vmarray_vt_alloc<vmint> (i2sz (MAX_REGISTER + 1),\n i2vm 0)\n in\n @{\n strings = strings,\n code = code,\n data = data,\n stack = stack,\n registers = registers\n }\n end\n\nfn {}\npop (vm : &vm_vt) :\n vmint =\n let\n macdef registers = vm.registers\n macdef stack = vm.stack\n val sp_before = registers[REGISTER_SP]\n in\n if sp_before = i2vm 0 then\n $raise vm_runtime_error (\"Stack underflow.\")\n else\n let\n val sp_after = sp_before - i2vm 1\n val _ = registers[REGISTER_SP] := sp_after\n val i = g1ofg0 (vm2sz sp_after)\n\n (* What follows is a runtime assertion that the upper stack\n boundary is not gone past, even though it certainly will\n not. This is necessary (assuming one does not use something\n such as $UN.prop_assert) because the stack pointer is a\n vmint, whose bounds cannot be proven at compile time.\n\n If you comment out the assertloc, the program will not pass\n typechecking.\n\n Compilers for many other languages will just insert such\n checks willy-nilly, leading programmers to turn off such\n instrumentation in the very code they provide to users.\n\n One might be tempted to use Size_t instead for the stack\n pointer, but what if the instruction set were later\n augmented with ways to read from or write into the stack\n pointer? *)\n val _ = assertloc (i < vmarray_vt_length stack)\n in\n stack[i]\n end\n end\n\nfn {}\npush (vm : &vm_vt,\n x : vmint) :\n void =\n let\n macdef registers = vm.registers\n macdef stack = vm.stack\n val sp_before = registers[REGISTER_SP]\n val i = g1ofg0 (vm2sz sp_before)\n in\n if vmarray_vt_length stack <= i then\n $raise vm_runtime_error (\"Stack overflow.\")\n else\n let\n val sp_after = sp_before + i2vm 1\n in\n registers[REGISTER_SP] := sp_after;\n stack[i] := x\n end\n end\n\nfn {}\nfetch_data (vm : &vm_vt,\n index : vmint) :\n vmint =\n let\n macdef data = vm.data\n val i = g1ofg0 (vm2sz index)\n in\n if vmarray_vt_length data <= i then\n $raise vm_runtime_error (\"Fetch from outside the data section.\")\n else\n data[i]\n end\n\nfn {}\nstore_data (vm : &vm_vt,\n index : vmint,\n x : vmint) :\n void =\n let\n macdef data = vm.data\n val i = g1ofg0 (vm2sz index)\n in\n if vmarray_vt_length data <= i then\n $raise vm_runtime_error (\"Store to outside the data section.\")\n else\n data[i] := x\n end\n\nfn {}\nget_argument (vm : &vm_vt) :\n vmint =\n let\n macdef code = vm.code\n macdef registers = vm.registers\n val pc = registers[REGISTER_PC]\n val i = g1ofg0 (vm2sz pc)\n in\n if vmarray_vt_length code <= i + i2sz 4 then\n $raise (vm_runtime_error\n (\"The program counter is out of bounds.\"))\n else\n let\n (* The data is stored little-endian. *)\n val byte0 = byte2vm code[i]\n val byte1 = byte2vm code[i + i2sz 1]\n val byte2 = byte2vm code[i + i2sz 2]\n val byte3 = byte2vm code[i + i2sz 3]\n in\n (byte0) lor (byte1 << 8) lor (byte2 << 16) lor (byte3 << 24)\n end\n end\n\nfn {}\nskip_argument (vm : &vm_vt) :\n void =\n let\n macdef registers = vm.registers\n val pc = registers[REGISTER_PC]\n in\n registers[REGISTER_PC] := pc + i2vm 4\n end\n\nextern fun {}\nunary_operation$inner : vmint -<> vmint\nfn {}\nunary_operation (vm : &vm_vt) :\n void =\n let\n macdef registers = vm.registers\n macdef stack = vm.stack\n val sp = registers[REGISTER_SP]\n val i = g1ofg0 (vm2sz (sp))\n prval _ = lemma_g1uint_param i\n in\n if i = i2sz 0 then\n $raise vm_runtime_error (\"Stack underflow.\")\n else\n let\n val _ = assertloc (i < vmarray_vt_length stack)\n\n (* The actual unary operation is inserted here during\n template expansion. *)\n val result = unary_operation$inner<> (stack[i - 1])\n in\n stack[i - 1] := result\n end\n end\n\nextern fun {}\nbinary_operation$inner : (vmint, vmint) -<> vmint\nfn {}\nbinary_operation (vm : &vm_vt) :\n void =\n let\n macdef registers = vm.registers\n macdef stack = vm.stack\n val sp_before = registers[REGISTER_SP]\n val i = g1ofg0 (vm2sz (sp_before))\n prval _ = lemma_g1uint_param i\n in\n if i <= i2sz 1 then\n $raise vm_runtime_error (\"Stack underflow.\")\n else\n let\n val _ = registers[REGISTER_SP] := sp_before - i2vm 1\n val _ = assertloc (i < vmarray_vt_length stack)\n\n (* The actual binary operation is inserted here during\n template expansion. *)\n val result =\n binary_operation$inner<> (stack[i - 2], stack[i - 1])\n in\n stack[i - 2] := result\n end\n end\n\nfn {}\nuop_neg (vm : &vm_vt) :\n void =\n let\n implement {}\n unary_operation$inner (x) =\n twos_complement x\n in\n unary_operation (vm)\n end\n\nfn {}\nuop_not (vm : &vm_vt) :\n void =\n let\n implement {}\n unary_operation$inner (x) =\n logical_not x\n in\n unary_operation (vm)\n end\n\nfn {}\nbinop_add (vm : &vm_vt) :\n void =\n let\n implement {}\n binary_operation$inner (x, y) =\n x + y\n in\n binary_operation (vm)\n end\n\nfn {}\nbinop_sub (vm : &vm_vt) :\n void =\n let\n implement {}\n binary_operation$inner (x, y) =\n x - y\n in\n binary_operation (vm)\n end\n\nfn {}\nbinop_mul (vm : &vm_vt) :\n void =\n let\n implement {}\n binary_operation$inner (x, y) =\n x \\signed_mul y\n in\n binary_operation (vm)\n end\n\nfn {}\nbinop_div (vm : &vm_vt) :\n void =\n let\n implement {}\n binary_operation$inner (x, y) =\n x \\signed_div y\n in\n binary_operation (vm)\n end\n\nfn {}\nbinop_mod (vm : &vm_vt) :\n void =\n let\n implement {}\n binary_operation$inner (x, y) =\n x \\signed_mod y\n in\n binary_operation (vm)\n end\n\nfn {}\nbinop_eq (vm : &vm_vt) :\n void =\n let\n implement {}\n binary_operation$inner (x, y) =\n x \\equality y\n in\n binary_operation (vm)\n end\n\nfn {}\nbinop_ne (vm : &vm_vt) :\n void =\n let\n implement {}\n binary_operation$inner (x, y) =\n x \\inequality y\n in\n binary_operation (vm)\n end\n\nfn {}\nbinop_lt (vm : &vm_vt) :\n void =\n let\n implement {}\n binary_operation$inner (x, y) =\n x \\signed_lt y\n in\n binary_operation (vm)\n end\n\nfn {}\nbinop_gt (vm : &vm_vt) :\n void =\n let\n implement {}\n binary_operation$inner (x, y) =\n x \\signed_gt y\n in\n binary_operation (vm)\n end\n\nfn {}\nbinop_le (vm : &vm_vt) :\n void =\n let\n implement {}\n binary_operation$inner (x, y) =\n x \\signed_lte y\n in\n binary_operation (vm)\n end\n\nfn {}\nbinop_ge (vm : &vm_vt) :\n void =\n let\n implement {}\n binary_operation$inner (x, y) =\n x \\signed_gte y\n in\n binary_operation (vm)\n end\n\nfn {}\nbinop_and (vm : &vm_vt) :\n void =\n let\n implement {}\n binary_operation$inner (x, y) =\n x \\logical_and y\n in\n binary_operation (vm)\n end\n\nfn {}\nbinop_or (vm : &vm_vt) :\n void =\n let\n implement {}\n binary_operation$inner (x, y) =\n x \\logical_or y\n in\n binary_operation (vm)\n end\n\nfn {}\ndo_push (vm : &vm_vt) :\n void =\n let\n val arg = get_argument (vm)\n in\n push (vm, arg);\n skip_argument (vm)\n end\n\nfn {}\ndo_fetch (vm : &vm_vt) :\n void =\n let\n val i = get_argument (vm)\n val x = fetch_data (vm, i)\n in\n push (vm, x);\n skip_argument (vm)\n end\n\nfn {}\ndo_store (vm : &vm_vt) :\n void =\n let\n val i = get_argument (vm)\n val x = pop (vm)\n in\n store_data (vm, i, x);\n skip_argument (vm)\n end\n\nfn {}\ndo_jmp (vm : &vm_vt) :\n void =\n let\n macdef registers = vm.registers\n val arg = get_argument (vm)\n val pc = registers[REGISTER_PC]\n in\n registers[REGISTER_PC] := pc + arg\n end\n\nfn {}\ndo_jz (vm : &vm_vt) :\n void =\n let\n val x = pop (vm)\n in\n if x = i2vm 0 then\n do_jmp (vm)\n else\n skip_argument (vm)\n end\n\nfn {}\ndo_prtc (f_output : FILEref,\n vm : &vm_vt) :\n void =\n let\n val x = pop (vm)\n in\n fileref_putc (f_output, vm2i x)\n end\n\nfn {}\ndo_prti (f_output : FILEref,\n vm : &vm_vt) :\n void =\n let\n val x = pop (vm)\n in\n fprint! (f_output, vm2i x)\n end\n\nfn {}\ndo_prts (f_output : FILEref,\n vm : &vm_vt) :\n void =\n let\n val i = g1ofg0 (vm2sz (pop (vm)))\n in\n if vmstrings_section_vt_length (vm.strings) <= i then\n $raise vm_runtime_error (\"String index out of bounds.\")\n else\n vmstring_fprint (f_output, vm.strings, i)\n end\n\nfn\nvm_step (f_output : FILEref,\n vm : &vm_vt,\n machine_halt : &bool,\n bad_opcode : &bool) :\n void =\n let\n macdef code = vm.code\n macdef registers = vm.registers\n\n val pc = registers[REGISTER_PC]\n\n val i = g1ofg0 (vm2sz (pc))\n prval _ = lemma_g1uint_param i\n in\n if vmarray_vt_length (code) <= i then\n $raise (vm_runtime_error\n (\"The program counter is out of bounds.\"))\n else\n let\n val _ = registers[REGISTER_PC] := pc + i2vm 1\n\n val opcode = code[i]\n val u_opcode = byte2uint0 opcode\n in\n (* Dispatch by bifurcation on the bit pattern of the\n opcode. This method is logarithmic in the number\n of opcode values. *)\n machine_halt := false;\n bad_opcode := false;\n if (u_opcode land (~(0x1FU))) = 0U then\n begin\n if (u_opcode land 0x10U) = 0U then\n begin\n if (u_opcode land 0x08U) = 0U then\n begin\n if (u_opcode land 0x04U) = 0U then\n begin\n if (u_opcode land 0x02U) = 0U then\n begin\n if (u_opcode land 0x01U) = 0U then\n (* OP_HALT *)\n machine_halt := true\n else\n binop_add (vm)\n end\n else\n begin\n if (u_opcode land 0x01U) = 0U then\n binop_sub (vm)\n else\n binop_mul (vm)\n end\n end\n else\n begin\n if (u_opcode land 0x02U) = 0U then\n begin\n if (u_opcode land 0x01U) = 0U then\n binop_div (vm)\n else\n binop_mod (vm)\n end\n else\n begin\n if (u_opcode land 0x01U) = 0U then\n binop_lt (vm)\n else\n binop_gt (vm)\n end\n end\n end\n else\n begin\n if (u_opcode land 0x04U) = 0U then\n begin\n if (u_opcode land 0x02U) = 0U then\n begin\n if (u_opcode land 0x01U) = 0U then\n binop_le (vm)\n else\n binop_ge (vm)\n end\n else\n begin\n if (u_opcode land 0x01U) = 0U then\n binop_eq (vm)\n else\n binop_ne (vm)\n end\n end\n else\n begin\n if (u_opcode land 0x02U) = 0U then\n begin\n if (u_opcode land 0x01U) = 0U then\n binop_and (vm)\n else\n binop_or (vm)\n end\n else\n begin\n if (u_opcode land 0x01U) = 0U then\n uop_neg (vm)\n else\n uop_not (vm)\n end\n end\n end\n end\n else\n begin\n if (u_opcode land 0x08U) = 0U then\n begin\n if (u_opcode land 0x04U) = 0U then\n begin\n if (u_opcode land 0x02U) = 0U then\n begin\n if (u_opcode land 0x01U) = 0U then\n do_prtc (f_output, vm)\n else\n do_prti (f_output, vm)\n end\n else\n begin\n if (u_opcode land 0x01U) = 0U then\n do_prts (f_output, vm)\n else\n do_fetch (vm)\n end\n end\n else\n begin\n if (u_opcode land 0x02U) = 0U then\n begin\n if (u_opcode land 0x01U) = 0U then\n do_store (vm)\n else\n do_push (vm)\n end\n else\n begin\n if (u_opcode land 0x01U) = 0U then\n do_jmp (vm)\n else\n do_jz (vm)\n end\n end\n end\n else\n bad_opcode := true\n end\n end\n else\n bad_opcode := true\n end\n end\n\nfn\nvm_continue (f_output : FILEref,\n vm : &vm_vt) :\n void =\n let\n fun\n loop (vm : &vm_vt,\n machine_halt : &bool,\n bad_opcode : &bool) : void =\n if ~machine_halt && ~bad_opcode then\n begin\n vm_step (f_output, vm, machine_halt, bad_opcode);\n loop (vm, machine_halt, bad_opcode)\n end\n\n var machine_halt : bool = false\n var bad_opcode : bool = false\n in\n loop (vm, machine_halt, bad_opcode);\n if bad_opcode then\n $raise vm_runtime_error (\"Unrecognized opcode at runtime.\")\n end\n\nfn\nvm_initialize (vm : &vm_vt) :\n void =\n let\n macdef data = vm.data\n macdef registers = vm.registers\n in\n vmarray_vt_fill (data, i2vm 0);\n registers[REGISTER_PC] := i2vm 0;\n registers[REGISTER_SP] := i2vm 0\n end\n\n\nfn\nvm_run (f_output : FILEref,\n vm : &vm_vt) :\n void =\n begin\n vm_initialize (vm);\n vm_continue (f_output, vm)\n end\n\n(********************************************************************)\n\nimplement\nmain0 (argc, argv) =\n {\n val inpfname =\n if 2 <= argc then\n $UN.cast{string} argv[1]\n else\n \"-\"\n val outfname =\n if 3 <= argc then\n $UN.cast{string} argv[2]\n else\n \"-\"\n\n val inpf =\n if (inpfname : string) = \"-\" then\n stdin_ref\n else\n fileref_open_exn (inpfname, file_mode_r)\n\n val outf =\n if (outfname : string) = \"-\" then\n stdout_ref\n else\n fileref_open_exn (outfname, file_mode_w)\n\n (* The following order must match that established by\n OP_HALT, OP_ADD, OP_SUB, etc. *)\n var opcode_order =\n @[String0][OPCODE_COUNT] (\"halt\", // 00000 bit pattern\n \"add\", // 00001\n \"sub\", // 00010\n \"mul\", // 00011\n \"div\", // 00100\n \"mod\", // 00101\n \"lt\", // 00110\n \"gt\", // 00111\n \"le\", // 01000\n \"ge\", // 01001\n \"eq\", // 01010\n \"ne\", // 01011\n \"and\", // 01100\n \"or\", // 01101\n \"neg\", // 01110\n \"not\", // 01111\n \"prtc\", // 10000\n \"prti\", // 10001\n \"prts\", // 10010\n \"fetch\", // 10011\n \"store\", // 10100\n \"push\", // 10101\n \"jmp\", // 10110\n \"jz\") // 10111\n\n val _ = ensure_that_vmint_is_suitable ()\n var vm = read_vm (inpf, opcode_order)\n val _ = vm_run (outf, vm)\n val _ = vm_vt_free vm\n }\n\n(********************************************************************)\n", "language": "ATS" }, { "code": "function error(msg) {\n printf(\"%s\\n\", msg)\n exit(1)\n}\n\nfunction bytes_to_int(bstr, i, sum) {\n sum = 0\n for (i=word_size-1; i>=0; i--) {\n sum *= 256\n sum += code[bstr+i]\n }\n return sum\n}\n\nfunction emit_byte(x) {\n code[next_free_code_index++] = x\n}\n\nfunction emit_word(x, i) {\n for (i=0; i<word_size; i++) {\n emit_byte(int(x)%256);\n x = int(x/256)\n }\n}\n\nfunction run_vm(data_size) {\n sp = data_size + 1\n pc = 0\n while (1) {\n op = code[pc++]\n if (op == FETCH) {\n stack[sp++] = stack[bytes_to_int(pc)]\n pc += word_size\n } else if (op == STORE) {\n stack[bytes_to_int(pc)] = stack[--sp]\n pc += word_size\n } else if (op == PUSH) {\n stack[sp++] = bytes_to_int(pc)\n pc += word_size\n } else if (op == ADD ) { stack[sp-2] += stack[sp-1]; sp--\n } else if (op == SUB ) { stack[sp-2] -= stack[sp-1]; sp--\n } else if (op == MUL ) { stack[sp-2] *= stack[sp-1]; sp--\n } else if (op == DIV ) { stack[sp-2] = int(stack[sp-2] / stack[sp-1]); sp--\n } else if (op == MOD ) { stack[sp-2] %= stack[sp-1]; sp--\n } else if (op == LT ) { stack[sp-2] = stack[sp-2] < stack[sp-1]; sp--\n } else if (op == GT ) { stack[sp-2] = stack[sp-2] > stack[sp-1]; sp--\n } else if (op == LE ) { stack[sp-2] = stack[sp-2] <= stack[sp-1]; sp--\n } else if (op == GE ) { stack[sp-2] = stack[sp-2] >= stack[sp-1]; sp--\n } else if (op == EQ ) { stack[sp-2] = stack[sp-2] == stack[sp-1]; sp--\n } else if (op == NE ) { stack[sp-2] = stack[sp-2] != stack[sp-1]; sp--\n } else if (op == AND ) { stack[sp-2] = stack[sp-2] && stack[sp-1]; sp--\n } else if (op == OR ) { stack[sp-2] = stack[sp-2] || stack[sp-1]; sp--\n } else if (op == NEG ) { stack[sp-1] = - stack[sp-1]\n } else if (op == NOT ) { stack[sp-1] = ! stack[sp-1]\n } else if (op == JMP ) { pc += bytes_to_int(pc)\n } else if (op == JZ ) { if (stack[--sp]) { pc += word_size } else { pc += bytes_to_int(pc) }\n } else if (op == PRTC) { printf(\"%c\", stack[--sp])\n } else if (op == PRTS) { printf(\"%s\", string_pool[stack[--sp]])\n } else if (op == PRTI) { printf(\"%d\", stack[--sp])\n } else if (op == HALT) { break\n }\n } # while\n}\n\nfunction str_trans(srce, dest, i) {\n dest = \"\"\n for (i=1; i <= length(srce); ) {\n if (substr(srce, i, 1) == \"\\\\\" && i < length(srce)) {\n if (substr(srce, i+1, 1) == \"n\") {\n dest = dest \"\\n\"\n i += 2\n } else if (substr(srce, i+1, 1) == \"\\\\\") {\n dest = dest \"\\\\\"\n i += 2\n }\n } else {\n dest = dest substr(srce, i, 1)\n i += 1\n }\n }\n return dest\n}\n\nfunction load_code( n, i) {\n getline line\n if (line == \"\")\n error(\"empty line\")\n n=split(line, line_list)\n data_size = line_list[2]\n n_strings = line_list[4]\n for (i=0; i<n_strings; i++) {\n getline line\n gsub(/\\n/, \"\", line)\n gsub(/\"/ , \"\", line)\n string_pool[i] = str_trans(line)\n }\n while (getline) {\n offset = int($1)\n instr = $2\n opcode = code_map[instr]\n if (opcode == \"\")\n error(\"Unknown instruction \" instr \" at \" offset)\n emit_byte(opcode)\n if (opcode == JMP || opcode == JZ) {\n p = int($4)\n emit_word(p - (offset + 1))\n } else if (opcode == PUSH) {\n value = int($3)\n emit_word(value)\n } else if (opcode == FETCH || opcode == STORE) {\n gsub(/\\[/, \"\", $3)\n gsub(/\\]/, \"\", $3)\n value = int($3)\n emit_word(value)\n }\n }\n return data_size\n}\n\nBEGIN {\n code_map[\"fetch\"] = FETCH = 1\n code_map[\"store\"] = STORE = 2\n code_map[\"push\" ] = PUSH = 3\n code_map[\"add\" ] = ADD = 4\n code_map[\"sub\" ] = SUB = 5\n code_map[\"mul\" ] = MUL = 6\n code_map[\"div\" ] = DIV = 7\n code_map[\"mod\" ] = MOD = 8\n code_map[\"lt\" ] = LT = 9\n code_map[\"gt\" ] = GT = 10\n code_map[\"le\" ] = LE = 11\n code_map[\"ge\" ] = GE = 12\n code_map[\"eq\" ] = EQ = 13\n code_map[\"ne\" ] = NE = 14\n code_map[\"and\" ] = AND = 15\n code_map[\"or\" ] = OR = 16\n code_map[\"neg\" ] = NEG = 17\n code_map[\"not\" ] = NOT = 18\n code_map[\"jmp\" ] = JMP = 19\n code_map[\"jz\" ] = JZ = 20\n code_map[\"prtc\" ] = PRTC = 21\n code_map[\"prts\" ] = PRTS = 22\n code_map[\"prti\" ] = PRTI = 23\n code_map[\"halt\" ] = HALT = 24\n\n next_free_node_index = 1\n next_free_code_index = 0\n word_size = 4\n input_file = \"-\"\n if (ARGC > 1)\n input_file = ARGV[1]\n data_size = load_code()\n run_vm(data_size)\n}\n", "language": "AWK" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <string.h>\n#include <stdint.h>\n#include <ctype.h>\n\n#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))\n\n#define da_dim(name, type) type *name = NULL; \\\n int _qy_ ## name ## _p = 0; \\\n int _qy_ ## name ## _max = 0\n\n#define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n\n#define da_rewind(name) _qy_ ## name ## _p = 0\n\n#define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n\ntypedef unsigned char uchar;\ntypedef uchar code;\n\ntypedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND,\n OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT\n} Code_t;\n\ntypedef struct Code_map {\n char *text;\n Code_t op;\n} Code_map;\n\nCode_map code_map[] = {\n {\"fetch\", FETCH},\n {\"store\", STORE},\n {\"push\", PUSH },\n {\"add\", ADD },\n {\"sub\", SUB },\n {\"mul\", MUL },\n {\"div\", DIV },\n {\"mod\", MOD },\n {\"lt\", LT },\n {\"gt\", GT },\n {\"le\", LE },\n {\"ge\", GE },\n {\"eq\", EQ },\n {\"ne\", NE },\n {\"and\", AND },\n {\"or\", OR },\n {\"neg\", NEG },\n {\"not\", NOT },\n {\"jmp\", JMP },\n {\"jz\", JZ },\n {\"prtc\", PRTC },\n {\"prts\", PRTS },\n {\"prti\", PRTI },\n {\"halt\", HALT },\n};\n\nFILE *source_fp;\nda_dim(object, code);\n\nvoid error(const char *fmt, ... ) {\n va_list ap;\n char buf[1000];\n\n va_start(ap, fmt);\n vsprintf(buf, fmt, ap);\n va_end(ap);\n printf(\"error: %s\\n\", buf);\n exit(1);\n}\n\n/*** Virtual Machine interpreter ***/\nvoid run_vm(const code obj[], int32_t data[], int g_size, char **string_pool) {\n int32_t *sp = &data[g_size + 1];\n const code *pc = obj;\n\n again:\n switch (*pc++) {\n case FETCH: *sp++ = data[*(int32_t *)pc]; pc += sizeof(int32_t); goto again;\n case STORE: data[*(int32_t *)pc] = *--sp; pc += sizeof(int32_t); goto again;\n case PUSH: *sp++ = *(int32_t *)pc; pc += sizeof(int32_t); goto again;\n case ADD: sp[-2] += sp[-1]; --sp; goto again;\n case SUB: sp[-2] -= sp[-1]; --sp; goto again;\n case MUL: sp[-2] *= sp[-1]; --sp; goto again;\n case DIV: sp[-2] /= sp[-1]; --sp; goto again;\n case MOD: sp[-2] %= sp[-1]; --sp; goto again;\n case LT: sp[-2] = sp[-2] < sp[-1]; --sp; goto again;\n case GT: sp[-2] = sp[-2] > sp[-1]; --sp; goto again;\n case LE: sp[-2] = sp[-2] <= sp[-1]; --sp; goto again;\n case GE: sp[-2] = sp[-2] >= sp[-1]; --sp; goto again;\n case EQ: sp[-2] = sp[-2] == sp[-1]; --sp; goto again;\n case NE: sp[-2] = sp[-2] != sp[-1]; --sp; goto again;\n case AND: sp[-2] = sp[-2] && sp[-1]; --sp; goto again;\n case OR: sp[-2] = sp[-2] || sp[-1]; --sp; goto again;\n case NEG: sp[-1] = -sp[-1]; goto again;\n case NOT: sp[-1] = !sp[-1]; goto again;\n case JMP: pc += *(int32_t *)pc; goto again;\n case JZ: pc += (*--sp == 0) ? *(int32_t *)pc : (int32_t)sizeof(int32_t); goto again;\n case PRTC: printf(\"%c\", sp[-1]); --sp; goto again;\n case PRTS: printf(\"%s\", string_pool[sp[-1]]); --sp; goto again;\n case PRTI: printf(\"%d\", sp[-1]); --sp; goto again;\n case HALT: break;\n default: error(\"Unknown opcode %d\\n\", *(pc - 1));\n }\n}\n\nchar *read_line(int *len) {\n static char *text = NULL;\n static int textmax = 0;\n\n for (*len = 0; ; (*len)++) {\n int ch = fgetc(source_fp);\n if (ch == EOF || ch == '\\n') {\n if (*len == 0)\n return NULL;\n break;\n }\n if (*len + 1 >= textmax) {\n textmax = (textmax == 0 ? 128 : textmax * 2);\n text = realloc(text, textmax);\n }\n text[*len] = ch;\n }\n text[*len] = '\\0';\n return text;\n}\n\nchar *rtrim(char *text, int *len) { // remove trailing spaces\n for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n ;\n\n text[*len] = '\\0';\n return text;\n}\n\nchar *translate(char *st) {\n char *p, *q;\n if (st[0] == '\"') // skip leading \" if there\n ++st;\n p = q = st;\n\n while ((*p++ = *q++) != '\\0') {\n if (q[-1] == '\\\\') {\n if (q[0] == 'n') {\n p[-1] = '\\n';\n ++q;\n } else if (q[0] == '\\\\') {\n ++q;\n }\n }\n if (q[0] == '\"' && q[1] == '\\0') // skip trialing \" if there\n ++q;\n }\n\n return st;\n}\n\n/* convert an opcode string into its byte value */\nint findit(const char text[], int offset) {\n for (size_t i = 0; i < sizeof(code_map) / sizeof(code_map[0]); i++) {\n if (strcmp(code_map[i].text, text) == 0)\n return code_map[i].op;\n }\n error(\"Unknown instruction %s at %d\\n\", text, offset);\n return -1;\n}\n\nvoid emit_byte(int c) {\n da_append(object, (uchar)c);\n}\n\nvoid emit_int(int32_t n) {\n union {\n int32_t n;\n unsigned char c[sizeof(int32_t)];\n } x;\n\n x.n = n;\n\n for (size_t i = 0; i < sizeof(x.n); ++i) {\n emit_byte(x.c[i]);\n }\n}\n\n/*\nDatasize: 5 Strings: 3\n\" is prime\\n\"\n\"Total primes found: \"\n\"\\n\"\n 154 jmp (-73) 82\n 164 jz (32) 197\n 175 push 0\n 159 fetch [4]\n 149 store [3]\n */\n\n/* Load code into global array object, return the string pool and data size */\nchar **load_code(int *ds) {\n int line_len, n_strings;\n char **string_pool;\n char *text = read_line(&line_len);\n text = rtrim(text, &line_len);\n\n strtok(text, \" \"); // skip \"Datasize:\"\n *ds = atoi(strtok(NULL, \" \")); // get actual data_size\n strtok(NULL, \" \"); // skip \"Strings:\"\n n_strings = atoi(strtok(NULL, \" \")); // get number of strings\n\n string_pool = malloc(n_strings * sizeof(char *));\n for (int i = 0; i < n_strings; ++i) {\n text = read_line(&line_len);\n text = rtrim(text, &line_len);\n text = translate(text);\n string_pool[i] = strdup(text);\n }\n\n for (;;) {\n int len;\n\n text = read_line(&line_len);\n if (text == NULL)\n break;\n text = rtrim(text, &line_len);\n\n int offset = atoi(strtok(text, \" \")); // get the offset\n char *instr = strtok(NULL, \" \"); // get the instruction\n int opcode = findit(instr, offset);\n emit_byte(opcode);\n char *operand = strtok(NULL, \" \");\n\n switch (opcode) {\n case JMP: case JZ:\n operand++; // skip the '('\n len = strlen(operand);\n operand[len - 1] = '\\0'; // remove the ')'\n emit_int(atoi(operand));\n break;\n case PUSH:\n emit_int(atoi(operand));\n break;\n case FETCH: case STORE:\n operand++; // skip the '['\n len = strlen(operand);\n operand[len - 1] = '\\0'; // remove the ']'\n emit_int(atoi(operand));\n break;\n }\n }\n return string_pool;\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n if (fn[0] == '\\0')\n *fp = std;\n else if ((*fp = fopen(fn, mode)) == NULL)\n error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nint main(int argc, char *argv[]) {\n init_io(&source_fp, stdin, \"r\", argc > 1 ? argv[1] : \"\");\n int data_size;\n char **string_pool = load_code(&data_size);\n int data[1000 + data_size];\n run_vm(object, data, data_size, string_pool);\n}\n", "language": "C" }, { "code": " >>SOURCE FORMAT IS FREE\nidentification division.\n*> this code is dedicated to the public domain\n*> (GnuCOBOL) 2.3-dev.0\nprogram-id. vminterpreter.\nenvironment division.\nconfiguration section.\nrepository. function all intrinsic.\ninput-output section.\nfile-control.\n select input-file assign using input-name\n status is input-status\n organization is line sequential.\ndata division.\n\nfile section.\nfd input-file.\n01 input-record pic x(64).\n\nworking-storage section.\n01 program-name pic x(32).\n01 input-name pic x(32).\n01 input-status pic xx.\n\n01 error-record pic x(64) value spaces global.\n\n01 v-max pic 99.\n01 parameters.\n 03 offset pic 999.\n 03 opcode pic x(8).\n 03 parm0 pic x(16).\n 03 parm1 pic x(16).\n 03 parm2 pic x(16).\n\n01 opcodes.\n 03 opFETCH pic x value x'00'.\n 03 opSTORE pic x value x'01'.\n 03 opPUSH pic x value x'02'.\n 03 opADD pic x value x'03'.\n 03 opSUB pic x value x'04'.\n 03 opMUL pic x value x'05'.\n 03 opDIV pic x value x'06'.\n 03 opMOD pic x value x'07'.\n 03 opLT pic x value x'08'.\n 03 opGT pic x value x'09'.\n 03 opLE pic x value x'0A'.\n 03 opGE pic x value x'0B'.\n 03 opEQ pic x value x'0C'.\n 03 opNE pic x value x'0D'.\n 03 opAND pic x value x'0E'.\n 03 opOR pic x value x'0F'.\n 03 opNEG pic x value x'10'.\n 03 opNOT pic x value x'11'.\n 03 opJMP pic x value x'13'.\n 03 opJZ pic x value x'14'.\n 03 opPRTC pic x value x'15'.\n 03 opPRTS pic x value x'16'.\n 03 opPRTI pic x value x'17'.\n 03 opHALT pic x value x'18'.\n\n01 filler.\n 03 s pic 99.\n 03 s-max pic 99 value 0.\n 03 s-lim pic 99 value 16.\n 03 filler occurs 16.\n 05 string-length pic 99.\n 05 string-entry pic x(48).\n\n01 filler.\n 03 v pic 99.\n 03 v-lim pic 99 value 16.\n 03 variables occurs 16 usage binary-int.\n\n01 generated-code global.\n 03 c pic 999 value 1.\n 03 pc pic 999.\n 03 c-lim pic 999 value 512.\n 03 kode pic x(512).\n\n01 filler.\n 03 stack1 pic 999 value 2.\n 03 stack2 pic 999 value 1.\n 03 stack-lim pic 999 value 998.\n 03 stack occurs 998 usage binary-int.\n\n01 display-definitions global.\n 03 ascii-character.\n 05 numeric-value usage binary-char.\n 03 display-integer pic -(9)9.\n 03 word-x.\n 05 word usage binary-int.\n 03 word-length pic 9.\n 03 string1 pic 99.\n 03 length1 pic 99.\n 03 count1 pic 99.\n 03 display-pending pic x.\n\nprocedure division.\nstart-vminterpreter.\n display 1 upon command-line *> get arg(1)\n accept program-name from argument-value\n move length(word) to word-length\n perform load-code\n perform run-code\n stop run\n .\nrun-code.\n move 1 to pc\n perform until pc >= c\n evaluate kode(pc:1)\n when opFETCH\n perform push-stack\n move kode(pc + 1:word-length) to word-x\n add 1 to word *> convert offset to subscript\n move variables(word) to stack(stack1)\n add word-length to pc\n when opPUSH\n perform push-stack\n move kode(pc + 1:word-length) to word-x\n move word to stack(stack1)\n add word-length to pc\n when opNEG\n compute stack(stack1) = -stack(stack1)\n when opNOT\n if stack(stack1) = 0\n move 1 to stack(stack1)\n else\n move 0 to stack(stack1)\n end-if\n when opJMP\n move kode(pc + 1:word-length) to word-x\n move word to pc\n when opHALT\n if display-pending = 'Y'\n display space\n end-if\n exit perform\n when opJZ\n if stack(stack1) = 0\n move kode(pc + 1:word-length) to word-x\n move word to pc\n else\n add word-length to pc\n end-if\n perform pop-stack\n when opSTORE\n move kode(pc + 1:word-length) to word-x\n add 1 to word *> convert offset to subscript\n move stack(stack1) to variables(word)\n add word-length to pc\n perform pop-stack\n when opADD\n add stack(stack1) to stack(stack2)\n perform pop-stack\n when opSUB\n subtract stack(stack1) from stack(stack2)\n perform pop-stack\n when opMUL\n multiply stack(stack1) by stack(stack2)\n *>rounded mode nearest-toward-zero *> doesn't match python\n perform pop-stack\n when opDIV\n divide stack(stack1) into stack(stack2)\n *>rounded mode nearest-toward-zero *> doesn't match python\n perform pop-stack\n when opMOD\n move mod(stack(stack2),stack(stack1)) to stack(stack2)\n perform pop-stack\n when opLT\n if stack(stack2) < stack(stack1)\n move 1 to stack(stack2)\n else\n move 0 to stack(stack2)\n end-if\n perform pop-stack\n when opGT\n if stack(stack2) > stack(stack1)\n move 1 to stack(stack2)\n else\n move 0 to stack(stack2)\n end-if\n perform pop-stack\n when opLE\n if stack(stack2) <= stack(stack1)\n move 1 to stack(stack2)\n else\n move 0 to stack(stack2)\n end-if\n perform pop-stack\n when opGE\n if stack(stack2) >= stack(stack1)\n move 1 to stack(stack2)\n else\n move 0 to stack(stack2)\n end-if\n perform pop-stack\n when opEQ\n if stack(stack2) = stack(stack1)\n move 1 to stack(stack2)\n else\n move 0 to stack(stack2)\n end-if\n perform pop-stack\n when opNE\n if stack(stack2) <> stack(stack1)\n move 1 to stack(stack2)\n else\n move 0 to stack(stack2)\n end-if\n perform pop-stack\n when opAND\n call \"CBL_AND\" using stack(stack1) stack(stack2) by value word-length\n perform pop-stack\n when opOR\n call \"CBL_OR\" using stack(stack1) stack(stack2) by value word-length\n perform pop-stack\n when opPRTC\n move stack(stack1) to numeric-value\n if numeric-value = 10\n display space\n move 'N' to display-pending\n else\n display ascii-character with no advancing\n move 'Y' to display-pending\n end-if\n perform pop-stack\n when opPRTS\n add 1 to word *> convert offset to subscript\n move 1 to string1\n move string-length(word) to length1\n perform until string1 > string-length(word)\n move 0 to count1\n inspect string-entry(word)(string1:length1)\n tallying count1 for characters before initial '\\' *> ' workaround code highlighter problem\n evaluate true\n when string-entry(word)(string1 + count1 + 1:1) = 'n' *> \\n\n display string-entry(word)(string1:count1)\n move 'N' to display-pending\n compute string1 = string1 + 2 + count1\n compute length1 = length1 - 2 - count1\n when string-entry(word)(string1 + count1 + 1:1) = '\\' *> ' \\\\\n display string-entry(word)(string1:count1 + 1) with no advancing\n move 'Y' to display-pending\n compute string1 = string1 + 2 + count1\n compute length1 = length1 - 2 - count1\n when other\n display string-entry(word)(string1:count1) with no advancing\n move 'Y' to display-pending\n add count1 to string1\n subtract count1 from length1\n end-evaluate\n end-perform\n perform pop-stack\n when opPRTI\n move stack(stack1) to display-integer\n display trim(display-integer) with no advancing\n move 'Y' to display-pending\n perform pop-stack\n end-evaluate\n add 1 to pc\n end-perform\n .\npush-stack.\n if stack1 >= stack-lim\n string 'in vminterpreter at ' pc ' stack overflow at ' stack-lim into error-record\n perform report-error\n end-if\n add 1 to stack1 stack2\n >>d display ' push at ' pc space stack1 space stack2\n .\npop-stack.\n if stack1 < 2\n string 'in vminterpreter at ' pc ' stack underflow' into error-record\n perform report-error\n end-if\n >>d display ' pop at ' pc space stack1 space stack2\n subtract 1 from stack1 stack2\n .\nload-code.\n perform read-input\n if input-status <> '00'\n string 'in vminterpreter no input data' into error-record\n perform report-error\n end-if\n\n unstring input-record delimited by all spaces into parm1 v-max parm2 s-max\n if v-max > v-lim\n string 'in vminterpreter datasize exceeds ' v-lim into error-record\n perform report-error\n end-if\n if s-max > s-lim\n string 'in vminterpreter number of strings exceeds ' s-lim into error-record\n perform report-error\n end-if\n\n perform read-input\n perform varying s from 1 by 1 until s > s-max\n or input-status <> '00'\n compute string-length(s) string-length(word) = length(trim(input-record)) - 2\n move input-record(2:string-length(word)) to string-entry(s)\n perform read-input\n end-perform\n if s <= s-max\n string 'in vminterpreter not all strings found' into error-record\n perform report-error\n end-if\n\n perform until input-status <> '00'\n initialize parameters\n unstring input-record delimited by all spaces into\n parm0 offset opcode parm1 parm2\n evaluate opcode\n when 'fetch'\n call 'emitbyte' using opFETCH\n call 'emitword' using parm1\n when 'store'\n call 'emitbyte' using opSTORE\n call 'emitword' using parm1\n when 'push'\n call 'emitbyte' using opPUSH\n call 'emitword' using parm1\n when 'add' call 'emitbyte' using opADD\n when 'sub' call 'emitbyte' using opSUB\n when 'mul' call 'emitbyte' using opMUL\n when 'div' call 'emitbyte' using opDIV\n when 'mod' call 'emitbyte' using opMOD\n when 'lt' call 'emitbyte' using opLT\n when 'gt' call 'emitbyte' using opGT\n when 'le' call 'emitbyte' using opLE\n when 'ge' call 'emitbyte' using opGE\n when 'eq' call 'emitbyte' using opEQ\n when 'ne' call 'emitbyte' using opNE\n when 'and' call 'emitbyte' using opAND\n when 'or' call 'emitbyte' using opOR\n when 'not' call 'emitbyte' using opNOT\n when 'neg' call 'emitbyte' using opNEG\n when 'jmp'\n call 'emitbyte' using opJMP\n call 'emitword' using parm2\n when 'jz'\n call 'emitbyte' using opJZ\n call 'emitword' using parm2\n when 'prtc' call 'emitbyte' using opPRTC\n when 'prts' call 'emitbyte' using opPRTS\n when 'prti' call 'emitbyte' using opPRTI\n when 'halt' call 'emitbyte' using opHALT\n when other\n string 'in vminterpreter unknown opcode ' trim(opcode) ' at ' offset into error-record\n perform report-error\n end-evaluate\n perform read-input\n end-perform\n .\nread-input.\n if program-name = spaces\n move '00' to input-status\n accept input-record on exception move '10' to input-status end-accept\n exit paragraph\n end-if\n if input-name = spaces\n string program-name delimited by space '.gen' into input-name\n open input input-file\n if input-status <> '00'\n string 'in vminterpreter ' trim(input-name) ' file open status ' input-status\n into error-record\n perform report-error\n end-if\n end-if\n read input-file into input-record\n evaluate input-status\n when '00'\n continue\n when '10'\n close input-file\n when other\n string 'in vminterpreter unexpected input-status: ' input-status into error-record\n perform report-error\n end-evaluate\n .\nreport-error.\n display error-record upon syserr\n stop run with error status -1\n .\nidentification division.\nprogram-id. emitbyte.\ndata division.\nlinkage section.\n01 opcode pic x.\nprocedure division using opcode.\nstart-emitbyte.\n if c >= c-lim\n string 'in vminterpreter emitbyte c exceeds ' c-lim into error-record\n call 'reporterror'\n end-if\n move opcode to kode(c:1)\n add 1 to c\n .\nend program emitbyte.\n\nidentification division.\nprogram-id. emitword.\ndata division.\nworking-storage section.\n01 word-temp pic x(8).\nlinkage section.\n01 word-value any length.\nprocedure division using word-value.\nstart-emitword.\n if c + word-length >= c-lim\n string 'in vminterpreter emitword c exceeds ' c-lim into error-record\n call 'reporterror'\n end-if\n move word-value to word-temp\n inspect word-temp converting '[' to ' '\n inspect word-temp converting ']' to ' '\n move numval(trim(word-temp)) to word\n move word-x to kode(c:word-length)\n add word-length to c\n .\nend program emitword.\n\nend program vminterpreter.\n", "language": "COBOL" }, { "code": "#!/bin/sh\n#|-*- mode:lisp -*-|#\n#|\nexec ros -Q -- $0 \"$@\"\n|#\n(progn ;;init forms\n (ros:ensure-asdf)\n #+quicklisp(ql:quickload '() :silent t)\n )\n\n(defpackage :ros.script.vm.3858678051\n (:use :cl))\n(in-package :ros.script.vm.3858678051)\n\n;;;\n;;; The Rosetta Code Virtual Machine, in Common Lisp.\n;;;\n;;; Notes:\n;;;\n;;; * I have tried not to use foreign types or similar means of\n;;; optimization.\n;;;\n;;; * Integers are stored in the VM's executable memory in\n;;; big-endian order. Not because I prefer it, but because I do\n;;; not want to get myself into a little-endian rut.\n;;;\n\n(require \"cl-ppcre\")\n(require \"trivia\")\n\n;;; Yes, I could compute how much memory is needed, or I could assume\n;;; that the instructions are in address order. However, for *this*\n;;; implementation I am going to use a large fixed-size memory and use\n;;; the address fields of instructions to place the instructions.\n(defconstant executable-memory-size 65536\n \"The size of memory for executable code, in 8-bit words.\")\n\n;;; Similarly, I am going to have fixed size data and stack memory.\n(defconstant data-memory-size 2048\n \"The size of memory for stored data, in 32-bit words.\")\n(defconstant stack-memory-size 2048\n \"The size of memory for the stack, in 32-bit words.\")\n\n;;; And so I am going to have specialized types for the different\n;;; kinds of memory the platform contains. Also for its \"word\" and\n;;; register types.\n(deftype word ()\n '(unsigned-byte 32))\n(deftype register ()\n '(simple-array word (1)))\n(deftype executable-memory ()\n `(simple-array (unsigned-byte 8) ,(list executable-memory-size)))\n(deftype data-memory ()\n `(simple-array word ,(list data-memory-size)))\n(deftype stack-memory ()\n `(simple-array word ,(list stack-memory-size)))\n\n(defconstant re-blank-line\n (ppcre:create-scanner \"^\\\\s*$\"))\n\n(defconstant re-parse-instr-1\n (ppcre:create-scanner \"^\\\\s*(\\\\d+)\\\\s*(.*\\\\S)\"))\n\n(defconstant re-parse-instr-2\n (ppcre:create-scanner \"(?i)^(\\\\S+)\\\\s*(.*)\"))\n\n(defconstant re-parse-instr-3\n (ppcre:create-scanner \"^[[(]?([0-9-]+)\"))\n\n(defconstant opcode-names\n #(\"halt\"\n \"add\"\n \"sub\"\n \"mul\"\n \"div\"\n \"mod\"\n \"lt\"\n \"gt\"\n \"le\"\n \"ge\"\n \"eq\"\n \"ne\"\n \"and\"\n \"or\"\n \"neg\"\n \"not\"\n \"prtc\"\n \"prti\"\n \"prts\"\n \"fetch\"\n \"store\"\n \"push\"\n \"jmp\"\n \"jz\"))\n\n(defun blank-line-p (s)\n (not (not (ppcre:scan re-blank-line s))))\n\n(defun opcode-from-name (s)\n (position-if (lambda (name)\n (string= s name))\n opcode-names))\n\n(defun create-executable-memory ()\n (coerce (make-list executable-memory-size\n :initial-element (opcode-from-name \"halt\"))\n 'executable-memory))\n\n(defun create-data-memory ()\n (coerce (make-list data-memory-size :initial-element 0)\n 'data-memory))\n\n(defun create-stack-memory ()\n (coerce (make-list stack-memory-size :initial-element 0)\n 'stack-memory))\n\n(defun create-register ()\n (coerce (make-list 1 :initial-element 0) 'register))\n\n(defstruct machine\n (sp (create-register) :type register) ; Stack pointer.\n (ip (create-register) :type register) ; Instruction pointer (same\n ; thing as program counter).\n (code (create-executable-memory) :type executable-memory)\n (data (create-data-memory) :type data-memory)\n (stack (create-stack-memory) :type stack-memory)\n (strings nil)\n output *standard-output*)\n\n(defun insert-instruction (memory instr)\n (declare (type executable-memory memory))\n (trivia:match instr\n ((list address opcode arg)\n (let ((instr-size (if arg 5 1)))\n (unless (<= (+ address instr-size) executable-memory-size)\n (warn \"the VM's executable memory size is exceeded\")\n (uiop:quit 1))\n (setf (elt memory address) opcode)\n (when arg\n ;; Big-endian order.\n (setf (elt memory (+ address 1)) (ldb (byte 8 24) arg))\n (setf (elt memory (+ address 2)) (ldb (byte 8 16) arg))\n (setf (elt memory (+ address 3)) (ldb (byte 8 8) arg))\n (setf (elt memory (+ address 4)) (ldb (byte 8 0) arg)))))))\n\n(defun load-executable-memory (memory instr-lst)\n (declare (type executable-memory memory))\n (loop for instr in instr-lst\n do (insert-instruction memory instr)))\n\n(defun parse-instruction (s)\n (if (blank-line-p s)\n nil\n (let* ((strings (nth-value 1 (ppcre:scan-to-strings\n re-parse-instr-1 s)))\n (address (parse-integer (elt strings 0)))\n (split (nth-value 1 (ppcre:scan-to-strings\n re-parse-instr-2 (elt strings 1))))\n (opcode-name (string-downcase (elt split 0)))\n (opcode (opcode-from-name opcode-name))\n (arguments (elt split 1))\n (has-arg (trivia:match opcode-name\n ((or \"fetch\" \"store\" \"push\" \"jmp\" \"jz\") t)\n (_ nil))))\n (if has-arg\n (let* ((argstr-lst\n (nth-value 1 (ppcre:scan-to-strings\n re-parse-instr-3 arguments)))\n (argstr (elt argstr-lst 0)))\n `(,address ,opcode ,(parse-integer argstr)))\n `(,address ,opcode ())))))\n\n(defun read-instructions (inpf)\n (loop for line = (read-line inpf nil 'eoi)\n until (eq line 'eoi)\n for instr = (parse-instruction line)\n when instr collect instr))\n\n(defun read-datasize-and-strings-count (inpf)\n (let ((line (read-line inpf)))\n (multiple-value-bind (_whole-match strings)\n ;; This is a permissive implementation.\n (ppcre:scan-to-strings\n \"(?i)^\\\\s*Datasize\\\\s*:\\\\s*(\\\\d+)\\\\s*Strings\\\\s*:\\\\s*(\\\\d+)\"\n line)\n (declare (ignore _whole-match))\n `(,(parse-integer (elt strings 0))\n ,(parse-integer (elt strings 1))))))\n\n(defun parse-string-literal (s)\n ;; This is a permissive implementation, but only in that it skips\n ;; any leading space. It does not check carefully for outright\n ;; mistakes.\n (let* ((s (ppcre:regex-replace \"^\\\\s*\" s \"\"))\n (quote-mark (elt s 0))\n (i 1)\n (lst\n (loop until (char= (elt s i) quote-mark)\n collect (let ((c (elt s i)))\n (if (char= c #\\\\)\n (let ((c0 (trivia:match (elt s (1+ i))\n (#\\n #\\newline)\n (c1 c1))))\n (setq i (+ i 2))\n c0)\n (progn\n (setq i (1+ i))\n c))))))\n (coerce lst 'string)))\n\n(defun read-string-literals (inpf strings-count)\n (loop for i from 1 to strings-count\n collect (parse-string-literal (read-line inpf))))\n\n(defun open-inpf (inpf-filename)\n (if (string= inpf-filename \"-\")\n *standard-input*\n (open inpf-filename :direction :input)))\n\n(defun open-outf (outf-filename)\n (if (string= outf-filename \"-\")\n *standard-output*\n (open outf-filename :direction :output\n :if-exists :overwrite\n :if-does-not-exist :create)))\n\n(defun word-signbit-p (x)\n \"True if and only if the sign bit is set.\"\n (declare (type word x))\n (/= 0 (logand x #x80000000)))\n\n(defun word-add (x y)\n \"Addition with overflow freely allowed.\"\n (declare (type word x))\n (declare (type word y))\n (coerce (logand (+ x y) #xFFFFFFFF) 'word))\n\n(defun word-neg (x)\n \"The two's complement.\"\n (declare (type word x))\n (word-add (logxor x #xFFFFFFFF) 1))\n\n(defun word-sub (x y)\n \"Subtraction with overflow freely allowed.\"\n (declare (type word x))\n (declare (type word y))\n (word-add x (word-neg y)))\n\n(defun word-mul (x y)\n \"Signed multiplication.\"\n (declare (type word x))\n (declare (type word y))\n (let ((x<0 (word-signbit-p x))\n (y<0 (word-signbit-p y)))\n (let ((abs-x (if x<0 (word-neg x) x))\n (abs-y (if y<0 (word-neg y) y)))\n (let* ((abs-xy (the word\n (logand (* abs-x abs-y) #xFFFFFFFF))))\n (if x<0\n (if y<0 abs-xy (word-neg abs-xy))\n (if y<0 (word-neg abs-xy) abs-xy))))))\n\n(defun word-div (x y)\n \"The quotient after signed integer division with truncation towards\nzero.\"\n (declare (type word x))\n (declare (type word y))\n (let ((x<0 (word-signbit-p x))\n (y<0 (word-signbit-p y)))\n (let ((abs-x (if x<0 (word-neg x) x))\n (abs-y (if y<0 (word-neg y) y)))\n (let* ((abs-x/y (the word\n (logand (floor abs-x abs-y) #xFFFFFFFF))))\n (if x<0\n (if y<0 abs-x/y (word-neg abs-x/y))\n (if y<0 (word-neg abs-x/y) abs-x/y))))))\n\n(defun word-mod (x y)\n \"The remainder after signed integer division with truncation towards\nzero.\"\n (declare (type word x))\n (declare (type word y))\n (let ((x<0 (word-signbit-p x))\n (y<0 (word-signbit-p y)))\n (let ((abs-x (if x<0 (word-neg x) x))\n (abs-y (if y<0 (word-neg y) y)))\n (let* ((abs-x%y (the word\n (logand (nth-value 1 (floor abs-x abs-y))\n #xFFFFFFFF))))\n (if x<0 (word-neg abs-x%y) abs-x%y)))))\n\n(defun b2i (b)\n (declare (type boolean b))\n (if b 1 0))\n\n(defun word-lt (x y)\n \"Signed comparison: is x less than y?\"\n (declare (type word x))\n (declare (type word y))\n (let ((x<0 (word-signbit-p x))\n (y<0 (word-signbit-p y)))\n (b2i (if x<0\n (if y<0 (< x y) t)\n (if y<0 nil (< x y))))))\n\n(defun word-le (x y)\n \"Signed comparison: is x less than or equal to y?\"\n (declare (type word x))\n (declare (type word y))\n (let ((x<0 (word-signbit-p x))\n (y<0 (word-signbit-p y)))\n (b2i (if x<0\n (if y<0 (<= x y) t)\n (if y<0 nil (<= x y))))))\n\n(defun word-gt (x y)\n \"Signed comparison: is x greater than y?\"\n (declare (type word x))\n (declare (type word y))\n (let ((x<0 (word-signbit-p x))\n (y<0 (word-signbit-p y)))\n (b2i (if x<0\n (if y<0 (> x y) nil)\n (if y<0 t (> x y))))))\n\n(defun word-ge (x y)\n \"Signed comparison: is x greater than or equal to y?\"\n (declare (type word x))\n (declare (type word y))\n (let ((x<0 (word-signbit-p x))\n (y<0 (word-signbit-p y)))\n (b2i (if x<0\n (if y<0 (>= x y) nil)\n (if y<0 t (>= x y))))))\n\n(defun word-eq (x y)\n \"Is x equal to y?\"\n (declare (type word x))\n (declare (type word y))\n (b2i (= x y)))\n\n(defun word-ne (x y)\n \"Is x not equal to y?\"\n (declare (type word x))\n (declare (type word y))\n (b2i (/= x y)))\n\n(defun word-cmp (x)\n \"The logical complement.\"\n (declare (type word x))\n (b2i (= x 0)))\n\n(defun word-and (x y)\n \"The logical conjunction.\"\n (declare (type word x))\n (declare (type word y))\n (b2i (and (/= x 0) (/= y 0))))\n\n(defun word-or (x y)\n \"The logical disjunction.\"\n (declare (type word x))\n (declare (type word y))\n (b2i (or (/= x 0) (/= y 0))))\n\n(defun unop (stack sp operation)\n \"Perform a unary operation on the stack.\"\n (declare (type stack-memory stack))\n (declare (type register sp))\n (declare (type (function (word) word) operation))\n (let ((i (elt sp 0)))\n (unless (<= 1 i)\n (warn \"stack underflow\")\n (uiop:quit 1))\n (let ((x (elt stack (1- i))))\n (setf (elt stack (1- i)) (funcall operation x)))))\n\n(defun binop (stack sp operation)\n \"Perform a binary operation on the stack.\"\n (declare (type stack-memory stack))\n (declare (type register sp))\n (declare (type (function (word word) word) operation))\n (let ((i (elt sp 0)))\n (unless (<= 2 i)\n (warn \"stack underflow\")\n (uiop:quit 1))\n (let ((x (elt stack (- i 2)))\n (y (elt stack (1- i))))\n (setf (elt stack (- i 2)) (funcall operation x y)))\n (setf (elt sp 0) (1- i))))\n\n(defun jri (code ip)\n \"Jump relative immediate.\"\n (declare (type executable-memory code))\n (declare (type register ip))\n ;; Big-endian order.\n (let ((j (elt ip 0)))\n (unless (<= (+ j 4) executable-memory-size)\n (warn \"address past end of executable memory\")\n (uiop:quit 1))\n (let* ((offset (elt code (+ j 3)))\n (offset (dpb (elt code (+ j 2)) (byte 8 8) offset))\n (offset (dpb (elt code (+ j 1)) (byte 8 16) offset))\n (offset (dpb (elt code j) (byte 8 24) offset)))\n (setf (elt ip 0) (word-add j offset)))))\n\n(defun jriz (stack sp code ip)\n \"Jump relative immediate, if zero.\"\n (declare (type stack-memory stack))\n (declare (type register sp))\n (declare (type executable-memory code))\n (declare (type register ip))\n (let ((i (elt sp 0)))\n (unless (<= 1 i)\n (warn \"stack underflow\")\n (uiop:quit 1))\n (let ((x (elt stack (1- i))))\n (setf (elt sp 0) (1- i))\n (if (= x 0)\n (jri code ip)\n (setf (elt ip 0) (+ (elt ip 0) 4))))))\n\n(defun get-immediate-value (code ip)\n (declare (type executable-memory code))\n (declare (type register ip))\n ;; Big-endian order.\n (let ((j (elt ip 0)))\n (unless (<= (+ j 4) executable-memory-size)\n (warn \"address past end of executable memory\")\n (uiop:quit 1))\n (let* ((x (elt code (+ j 3)))\n (x (dpb (elt code (+ j 2)) (byte 8 8) x))\n (x (dpb (elt code (+ j 1)) (byte 8 16) x))\n (x (dpb (elt code j) (byte 8 24) x)))\n (setf (elt ip 0) (+ j 4))\n x)))\n\n(defun pushi (stack sp code ip)\n \"Push-immediate a value from executable memory onto the stack.\"\n (declare (type stack-memory stack))\n (declare (type register sp))\n (declare (type executable-memory code))\n (declare (type register ip))\n (let ((i (elt sp 0)))\n (unless (< i stack-memory-size)\n (warn \"stack overflow\")\n (uiop:quit 1))\n (setf (elt stack i) (get-immediate-value code ip))\n (setf (elt sp 0) (1+ i))))\n\n(defun fetch (stack sp code ip data)\n \"Fetch data to the stack, using the storage location given in\nexecutable memory.\"\n (declare (type stack-memory stack))\n (declare (type register sp))\n (declare (type executable-memory code))\n (declare (type register ip))\n (declare (type data-memory data))\n (let ((i (elt sp 0)))\n (unless (< i stack-memory-size)\n (warn \"stack overflow\")\n (uiop:quit 1))\n (let* ((k (get-immediate-value code ip))\n (x (elt data k)))\n (setf (elt stack i) x)\n (setf (elt sp 0) (1+ i)))))\n\n(defun pop-one (stack sp)\n (let ((i (elt sp 0)))\n (unless (<= 1 i)\n (warn \"stack underflow\")\n (uiop:quit 1))\n (let* ((x (elt stack (1- i))))\n (setf (elt sp 0) (1- i))\n x)))\n\n(defun store (stack sp code ip data)\n \"Store data from the stack, using the storage location given in\nexecutable memory.\"\n (declare (type stack-memory stack))\n (declare (type register sp))\n (declare (type executable-memory code))\n (declare (type register ip))\n (declare (type data-memory data))\n (let ((i (elt sp 0)))\n (unless (<= 1 i)\n (warn \"stack underflow\")\n (uiop:quit 1))\n (let ((k (get-immediate-value code ip))\n (x (pop-one stack sp)))\n (setf (elt data k) x))))\n\n(defun prti (stack sp outf)\n \"Print the top value of the stack, as a signed decimal value.\"\n (declare (type stack-memory stack))\n (declare (type register sp))\n (let* ((n (pop-one stack sp))\n (n<0 (word-signbit-p n)))\n (if n<0\n (format outf \"-~D\" (word-neg n))\n (format outf \"~D\" n))))\n\n(defun prtc (stack sp outf)\n \"Print the top value of the stack, as a character.\"\n (declare (type stack-memory stack))\n (declare (type register sp))\n (let* ((c (pop-one stack sp)))\n (format outf \"~C\" (code-char c))))\n\n(defun prts (stack sp strings outf)\n \"Print the string specified by the top of the stack.\"\n (declare (type stack-memory stack))\n (declare (type register sp))\n (let* ((k (pop-one stack sp))\n (s (elt strings k)))\n (format outf \"~A\" s)))\n\n(defmacro defun-machine-binop (op)\n (let ((machine-op (read-from-string\n (concatenate 'string \"machine-\" (string op))))\n (word-op (read-from-string\n (concatenate 'string \"word-\" (string op)))))\n `(defun ,machine-op (mach)\n (declare (type machine mach))\n (binop (machine-stack mach)\n (machine-sp mach)\n #',word-op))))\n\n(defmacro defun-machine-unop (op)\n (let ((machine-op (read-from-string\n (concatenate 'string \"machine-\" (string op))))\n (word-op (read-from-string\n (concatenate 'string \"word-\" (string op)))))\n `(defun ,machine-op (mach)\n (declare (type machine mach))\n (unop (machine-stack mach)\n (machine-sp mach)\n #',word-op))))\n\n(defun-machine-binop \"add\")\n(defun-machine-binop \"sub\")\n(defun-machine-binop \"mul\")\n(defun-machine-binop \"div\")\n(defun-machine-binop \"mod\")\n(defun-machine-binop \"lt\")\n(defun-machine-binop \"gt\")\n(defun-machine-binop \"le\")\n(defun-machine-binop \"ge\")\n(defun-machine-binop \"eq\")\n(defun-machine-binop \"ne\")\n(defun-machine-binop \"and\")\n(defun-machine-binop \"or\")\n\n(defun-machine-unop \"neg\")\n(defun machine-not (mach)\n (declare (type machine mach))\n (unop (machine-stack mach)\n (machine-sp mach)\n #'word-cmp))\n\n(defun machine-prtc (mach)\n (declare (type machine mach))\n (prtc (machine-stack mach)\n (machine-sp mach)\n (machine-output mach)))\n\n(defun machine-prti (mach)\n (declare (type machine mach))\n (prti (machine-stack mach)\n (machine-sp mach)\n (machine-output mach)))\n\n(defun machine-prts (mach)\n (declare (type machine mach))\n (prts (machine-stack mach)\n (machine-sp mach)\n (machine-strings mach)\n (machine-output mach)))\n\n(defun machine-fetch (mach)\n (declare (type machine mach))\n (fetch (machine-stack mach)\n (machine-sp mach)\n (machine-code mach)\n (machine-ip mach)\n (machine-data mach)))\n\n(defun machine-store (mach)\n (declare (type machine mach))\n (store (machine-stack mach)\n (machine-sp mach)\n (machine-code mach)\n (machine-ip mach)\n (machine-data mach)))\n\n(defun machine-push (mach)\n (declare (type machine mach))\n (pushi (machine-stack mach)\n (machine-sp mach)\n (machine-code mach)\n (machine-ip mach)))\n\n(defun machine-jmp (mach)\n (declare (type machine mach))\n (jri (machine-code mach)\n (machine-ip mach)))\n\n(defun machine-jz (mach)\n (declare (type machine mach))\n (jriz (machine-stack mach)\n (machine-sp mach)\n (machine-code mach)\n (machine-ip mach)))\n\n(defun get-opcode (mach)\n (declare (type machine mach))\n (let ((code (machine-code mach))\n (ip (machine-ip mach)))\n (let ((j (elt ip 0)))\n (unless (< j executable-memory-size)\n (warn \"address past end of executable memory\")\n (uiop:quit 1))\n (let ((opcode (elt code j)))\n (setf (elt ip 0) (1+ j))\n opcode))))\n\n(defun run-instruction (mach opcode)\n (declare (type machine mach))\n (declare (type fixnum opcode))\n (let ((op-mod-4 (logand opcode #x3))\n (op-div-4 (ash opcode -2)))\n (trivia:match op-div-4\n (0 (trivia:match op-mod-4\n (1 (machine-add mach))\n (2 (machine-sub mach))\n (3 (machine-mul mach))))\n (1 (trivia:match op-mod-4\n (0 (machine-div mach))\n (1 (machine-mod mach))\n (2 (machine-lt mach))\n (3 (machine-gt mach))))\n (2 (trivia:match op-mod-4\n (0 (machine-le mach))\n (1 (machine-ge mach))\n (2 (machine-eq mach))\n (3 (machine-ne mach))))\n (3 (trivia:match op-mod-4\n (0 (machine-and mach))\n (1 (machine-or mach))\n (2 (machine-neg mach))\n (3 (machine-not mach))))\n (4 (trivia:match op-mod-4\n (0 (machine-prtc mach))\n (1 (machine-prti mach))\n (2 (machine-prts mach))\n (3 (machine-fetch mach))))\n (5 (trivia:match op-mod-4\n (0 (machine-store mach))\n (1 (machine-push mach))\n (2 (machine-jmp mach))\n (3 (machine-jz mach)))))))\n\n(defun run-vm (mach)\n (declare (type machine mach))\n (let ((opcode-for-halt (the fixnum (opcode-from-name \"halt\")))\n (opcode-for-add (the fixnum (opcode-from-name \"add\")))\n (opcode-for-jz (the fixnum (opcode-from-name \"jz\"))))\n (loop for opcode = (the fixnum (get-opcode mach))\n until (= opcode opcode-for-halt)\n do (progn (when (or (< opcode opcode-for-add)\n (< opcode-for-jz opcode))\n (warn \"unsupported opcode\")\n (uiop:quit 1))\n (run-instruction mach opcode)))))\n\n(defun usage-error ()\n (princ \"Usage: vm [INPUTFILE [OUTPUTFILE]]\" *standard-output*)\n (terpri *standard-output*)\n (princ \"If either INPUTFILE or OUTPUTFILE is \\\"-\\\", the respective\"\n *standard-output*)\n (princ \" standard I/O is used.\" *standard-output*)\n (terpri *standard-output*)\n (uiop:quit 1))\n\n(defun get-filenames (argv)\n (trivia:match argv\n ((list) '(\"-\" \"-\"))\n ((list inpf-filename) `(,inpf-filename \"-\"))\n ((list inpf-filename outf-filename) `(,inpf-filename\n ,outf-filename))\n (_ (usage-error))))\n\n(defun main (&rest argv)\n (let* ((filenames (get-filenames argv))\n (inpf-filename (car filenames))\n (inpf (open-inpf inpf-filename))\n (outf-filename (cadr filenames))\n (outf (open-outf outf-filename))\n\n (sizes (read-datasize-and-strings-count inpf))\n (datasize (car sizes))\n (strings-count (cadr sizes))\n (strings (read-string-literals inpf strings-count))\n (instructions (read-instructions inpf))\n ;; We shall remain noncommittal about how strings are stored\n ;; on the hypothetical machine.\n (strings (coerce strings 'simple-vector))\n\n (mach (make-machine :strings strings\n :output outf)))\n\n (unless (<= datasize data-memory-size)\n (warn \"the VM's data memory size is exceeded\")\n (uiop:quit 1))\n\n (load-executable-memory (machine-code mach) instructions)\n (run-vm mach)\n\n (unless (string= inpf-filename \"-\")\n (close inpf))\n (unless (string= outf-filename \"-\")\n (close outf))\n\n (uiop:quit 0)))\n\n;;; vim: set ft=lisp lisp:\n", "language": "Common-Lisp" }, { "code": "//\n// The Rosetta Code Virtual Machine in D.\n//\n// This code was migrated from an implementation in ATS. I have tried\n// to keep it possible to compare the two languages easily, although\n// in some cases the demonstration of \"low level\" techniques in ATS\n// (such as avoiding memory leaks that might require garbage\n// collection), or the use of linked lists as intermediate storage, or\n// other such matters, seemed inappropriate to duplicate in D\n// programming.\n//\n// (For example: in ATS, using a fully built linked list to initialize\n// an array solves typechecking issues that simply do not exist in D's\n// type system.)\n//\n\nimport std.ascii;\nimport std.conv;\nimport std.stdint;\nimport std.stdio;\nimport std.string;\nimport std.typecons;\n\nenum Op {\n HALT = 0x0000, // 00000\n ADD = 0x0001, // 00001\n SUB = 0x0002, // 00010\n MUL = 0x0003, // 00011\n DIV = 0x0004, // 00100\n MOD = 0x0005, // 00101\n LT = 0x0006, // 00110\n GT = 0x0007, // 00111\n LE = 0x0008, // 01000\n GE = 0x0009, // 01001\n EQ = 0x000A, // 01010\n NE = 0x000B, // 01011\n AND = 0x000C, // 01100\n OR = 0x000D, // 01101\n NEG = 0x000E, // 01110\n NOT = 0x000F, // 01111\n PRTC = 0x0010, // 10000\n PRTI = 0x0011, // 10001\n PRTS = 0x0012, // 10010\n FETCH = 0x0013, // 10011\n STORE = 0x0014, // 10100\n PUSH = 0x0015, // 10101\n JMP = 0x0016, // 10110\n JZ = 0x0017 // 10111\n}\n\nconst string[] opcodeOrder =\n [\"halt\", // 00000 bit pattern\n \"add\", // 00001\n \"sub\", // 00010\n \"mul\", // 00011\n \"div\", // 00100\n \"mod\", // 00101\n \"lt\", // 00110\n \"gt\", // 00111\n \"le\", // 01000\n \"ge\", // 01001\n \"eq\", // 01010\n \"ne\", // 01011\n \"and\", // 01100\n \"or\", // 01101\n \"neg\", // 01110\n \"not\", // 01111\n \"prtc\", // 10000\n \"prti\", // 10001\n \"prts\", // 10010\n \"fetch\", // 10011\n \"store\", // 10100\n \"push\", // 10101\n \"jmp\", // 10110\n \"jz\"]; // 10111\n\nenum Register {\n PC = 0,\n SP = 1,\n MAX = SP\n}\n\nalias vmint = uint32_t;\n\nclass VM {\n string[] strings;\n ubyte[] code;\n vmint[] data;\n vmint[] stack;\n vmint[Register.MAX + 1] registers;\n}\n\nclass BadVMException : Exception\n{\n this(string msg, string file = __FILE__, size_t line = __LINE__)\n {\n super(msg, file, line);\n }\n}\n\nclass VMRuntimeException : Exception\n{\n this(string msg, string file = __FILE__, size_t line = __LINE__)\n {\n super(msg, file, line);\n }\n}\n\nvmint\ntwosComplement (vmint x)\n{\n // This computes the negative of x, if x is regarded as signed.\n pragma(inline);\n return (~x) + vmint(1U);\n}\n\nvmint\nadd (vmint x, vmint y)\n{\n // This works whether x or y is regarded as unsigned or signed.\n pragma(inline);\n return x + y;\n}\n\nvmint\nsub (vmint x, vmint y)\n{\n // This works whether x or y is regarded as unsigned or signed.\n pragma(inline);\n return x - y;\n}\n\nvmint\nequality (vmint x, vmint y)\n{\n pragma(inline);\n return vmint(x == y);\n}\n\nvmint\ninequality (vmint x, vmint y)\n{\n pragma(inline);\n return vmint(x != y);\n}\n\nvmint\nsignedLt (vmint x, vmint y)\n{\n pragma(inline);\n return vmint(int32_t(x) < int32_t(y));\n}\n\nvmint\nsignedGt (vmint x, vmint y)\n{\n pragma(inline);\n return vmint(int32_t(x) > int32_t(y));\n}\n\nvmint\nsignedLte (vmint x, vmint y)\n{\n pragma(inline);\n return vmint(int32_t(x) <= int32_t(y));\n}\n\nvmint\nsignedGte (vmint x, vmint y)\n{\n pragma(inline);\n return vmint(int32_t(x) >= int32_t(y));\n}\n\nvmint\nsignedMul (vmint x, vmint y)\n{\n pragma(inline);\n return vmint(int32_t(x) * int32_t(y));\n}\n\nvmint\nsignedDiv (vmint x, vmint y)\n{\n pragma(inline);\n return vmint(int32_t(x) / int32_t(y));\n}\n\nvmint\nsignedMod (vmint x, vmint y)\n{\n pragma(inline);\n return vmint(int32_t(x) % int32_t(y));\n}\n\nvmint\nlogicalNot (vmint x)\n{\n pragma(inline);\n return vmint(!x);\n}\n\nvmint\nlogicalAnd (vmint x, vmint y)\n{\n pragma(inline);\n return vmint((!!x) * (!!y));\n}\n\nvmint\nlogicalOr (vmint x, vmint y)\n{\n pragma(inline);\n return (vmint(1) - vmint((!x) * (!y)));\n}\n\nvmint\nparseDigits (string s, size_t i, size_t j)\n{\n const badInteger = \"bad integer\";\n\n if (j == i)\n throw new BadVMException (badInteger);\n auto x = vmint(0);\n for (size_t k = i; k < j; k += 1)\n if (!isDigit (s[k]))\n throw new BadVMException (badInteger);\n else\n // The result is allowed to overflow freely.\n x = (vmint(10) * x) + vmint(s[k] - '0');\n return x;\n}\n\nvmint\nparseInteger (string s, size_t i, size_t j)\n{\n const badInteger = \"bad integer\";\n\n vmint retval;\n if (j == i)\n throw new BadVMException (badInteger);\n else if (j == i + vmint(1) && !isDigit (s[i]))\n throw new BadVMException (badInteger);\n else if (s[i] != '-')\n retval = parseDigits (s, i, j);\n else if (j == i + vmint(1))\n throw new BadVMException (badInteger);\n else\n retval = twosComplement (parseDigits (s, i + vmint(1), j));\n return retval;\n}\n\nsize_t\nskipWhitespace (string s, size_t n, size_t i)\n{\n while (i < n && isWhite (s[i]))\n i += 1;\n return i;\n}\n\nsize_t\nskipNonwhitespace (string s, size_t n, size_t i)\n{\n while (i < n && !isWhite (s[i]))\n i += 1;\n return i;\n}\n\nbool\nsubstrEqual (string s, size_t i, size_t j, string t)\n{\n // Is s[i .. j-1] equal to t?\n\n auto retval = false;\n auto m = t.length;\n if (m == j - i)\n {\n auto k = size_t(0);\n while (k < m && s[i + k] == t[k])\n k += 1;\n retval = (k == m);\n }\n return retval;\n}\n\nstring\ndequoteString (string s, size_t n)\n{\n const badQuotedString = \"bad quoted string\";\n\n string t = \"\";\n s = strip(s);\n if (s.length < 2 || s[0] != '\"' || s[$ - 1] != '\"')\n throw new BadVMException (badQuotedString);\n auto i = 1;\n while (i < s.length - 1)\n if (s[i] != '\\\\')\n {\n t ~= s[i];\n i += 1;\n }\n else if (i + 1 == s.length - 1)\n throw new BadVMException (badQuotedString);\n else if (s[i + 1] == 'n')\n {\n t ~= '\\n';\n i += 2;\n }\n else if (s[i + 1] == '\\\\')\n {\n t ~= '\\\\';\n i += 2;\n }\n else\n throw new BadVMException (badQuotedString);\n return t;\n}\n\nstring[]\nreadStrings (File f, size_t stringsSize)\n{\n const badQuotedString = \"Bad quoted string.\";\n\n string[] strings;\n strings.length = stringsSize;\n for (size_t k = 0; k < stringsSize; k += 1)\n {\n auto line = f.readln();\n strings[k] = dequoteString (line, line.length);\n }\n return strings;\n}\n\nubyte\nopcodeNameTo_ubyte (string str, size_t i, size_t j)\n{\n size_t k = 0;\n while (k < opcodeOrder.length &&\n !substrEqual (str, i, j, opcodeOrder[k]))\n k += 1;\n if (k == opcodeOrder.length)\n throw new BadVMException (\"unrecognized opcode name\");\n return to!ubyte(k);\n}\n\nubyte\nvmintByte0 (vmint i)\n{\n return (i & 0xFF);\n}\n\nubyte\nvmintByte1 (vmint i)\n{\n return ((i >> 8) & 0xFF);\n}\n\nubyte\nvmintByte2 (vmint i)\n{\n return ((i >> 16) & 0xFF);\n}\n\nubyte\nvmintByte3 (vmint i)\n{\n return (i >> 24);\n}\n\nubyte[]\nparseInstruction (string line)\n{\n const bad_instruction = \"bad VM instruction\";\n\n const n = line.length;\n auto i = skipWhitespace (line, n, 0);\n\n // Skip the address field.\n i = skipNonwhitespace (line, n, i);\n\n i = skipWhitespace (line, n, i);\n auto j = skipNonwhitespace (line, n, i);\n auto opcode = opcodeNameTo_ubyte (line, i, j);\n\n auto startOfArgument = j;\n\n ubyte[] finishPush ()\n {\n const i1 = skipWhitespace (line, n, startOfArgument);\n const j1 = skipNonwhitespace (line, n, i1);\n const arg = parseInteger (line, i1, j1);\n // Little-endian storage.\n return [opcode, vmintByte0 (arg), vmintByte1 (arg),\n vmintByte2 (arg), vmintByte3 (arg)];\n }\n\n ubyte[] finishFetchOrStore ()\n {\n const i1 = skipWhitespace (line, n, startOfArgument);\n const j1 = skipNonwhitespace (line, n, i1);\n if (j1 - i1 < 3 || line[i1] != '[' || line[j1 - 1] != ']')\n throw new BadVMException (bad_instruction);\n const arg = parseInteger (line, i1 + 1, j1 - 1);\n // Little-endian storage.\n return [opcode, vmintByte0 (arg), vmintByte1 (arg),\n vmintByte2 (arg), vmintByte3 (arg)];\n }\n\n ubyte[] finishJmpOrJz ()\n {\n const i1 = skipWhitespace (line, n, startOfArgument);\n const j1 = skipNonwhitespace (line, n, i1);\n if (j1 - i1 < 3 || line[i1] != '(' || line[j1 - 1] != ')')\n throw new BadVMException (bad_instruction);\n const arg = parseInteger (line, i1 + 1, j1 - 1);\n // Little-endian storage.\n return [opcode, vmintByte0 (arg), vmintByte1 (arg),\n vmintByte2 (arg), vmintByte3 (arg)];\n }\n\n ubyte[] retval;\n switch (opcode)\n {\n case Op.PUSH:\n retval = finishPush ();\n break;\n case Op.FETCH:\n case Op.STORE:\n retval = finishFetchOrStore ();\n break;\n case Op.JMP:\n case Op.JZ:\n retval = finishJmpOrJz ();\n break;\n default:\n retval = [opcode];\n break;\n }\n\n return retval;\n}\n\nubyte[]\nreadCode (File f)\n{\n // Read the instructions from the input, producing an array of\n // array of instruction bytes.\n ubyte[] code = [];\n auto line = f.readln();\n while (line !is null)\n {\n code ~= parseInstruction (line);\n line = f.readln();\n }\n return code;\n}\n\nvoid\nparseHeaderLine (string line, ref size_t dataSize,\n ref size_t stringsSize)\n{\n const bad_vm_header_line = \"bad VM header line\";\n\n const n = line.length;\n auto i = skipWhitespace (line, n, 0);\n auto j = skipNonwhitespace (line, n, i);\n if (!substrEqual (line, i, j, \"Datasize:\"))\n throw new BadVMException (bad_vm_header_line);\n i = skipWhitespace (line, n, j);\n j = skipNonwhitespace (line, n, i);\n dataSize = parseInteger (line, i, j);\n i = skipWhitespace (line, n, j);\n j = skipNonwhitespace (line, n, i);\n if (!substrEqual (line, i, j, \"Strings:\"))\n throw new BadVMException (bad_vm_header_line);\n i = skipWhitespace (line, n, j);\n j = skipNonwhitespace (line, n, i);\n stringsSize = parseInteger (line, i, j);\n}\n\nVM\nreadVM (File f)\n{\n const line = f.readln();\n\n size_t dataSize;\n size_t stringsSize;\n parseHeaderLine (line, dataSize, stringsSize);\n\n VM vm = new VM();\n vm.strings = readStrings (f, stringsSize);\n vm.code = readCode (f);\n vm.data.length = dataSize;\n vm.stack.length = 65536; // A VERY big stack, MUCH bigger than is\n // \"reasonable\" for this VM. The same size\n // as in the ATS, however.\n vm.registers[Register.PC] = vmint(0);\n vm.registers[Register.SP] = vmint(0);\n\n return vm;\n}\n\nvmint\npop (VM vm)\n{\n pragma(inline);\n const spBefore = vm.registers[Register.SP];\n if (spBefore == 0)\n throw new VMRuntimeException (\"stack underflow\");\n const spAfter = spBefore - vmint(1);\n vm.registers[Register.SP] = spAfter;\n return vm.stack[spAfter];\n}\n\nvoid\npush (VM vm, vmint x)\n{\n pragma(inline);\n const spBefore = vm.registers[Register.SP];\n if (vm.stack.length <= spBefore)\n throw new VMRuntimeException (\"stack overflow\");\n vm.stack[spBefore] = x;\n const spAfter = spBefore + vmint(1);\n vm.registers[Register.SP] = spAfter;\n}\n\nvmint\nfetchData (VM vm, vmint index)\n{\n pragma(inline);\n if (vm.data.length <= index)\n throw new VMRuntimeException\n (\"fetch from outside the data section\");\n return vm.data[index];\n}\n\nvoid\nstoreData (VM vm, vmint index, vmint x)\n{\n pragma(inline);\n if (vm.data.length <= index)\n throw new VMRuntimeException\n (\"store to outside the data section\");\n vm.data[index] = x;\n}\n\nvmint\ngetArgument (VM vm)\n{\n pragma(inline);\n auto pc = vm.registers[Register.PC];\n if (vm.code.length <= pc + vmint(4))\n throw new VMRuntimeException\n (\"the program counter is out of bounds\");\n // The data is stored little-endian.\n const byte0 = vmint (vm.code[pc]);\n const byte1 = vmint (vm.code[pc + vmint(1)]);\n const byte2 = vmint (vm.code[pc + vmint(2)]);\n const byte3 = vmint (vm.code[pc + vmint(3)]);\n return (byte0) | (byte1 << 8) | (byte2 << 16) | (byte3 << 24);\n}\n\nvoid\nskipArgument (VM vm)\n{\n pragma(inline);\n vm.registers[Register.PC] += vmint(4);\n}\n\n//\n// The string mixins below are going to do for us *some* of what the\n// ATS template system did for us. The two methods hardly resemble\n// each other, but both can be used to construct function definitions\n// at compile time.\n//\n\ntemplate\nUnaryOperation (alias name, alias func)\n{\n const char[] UnaryOperation =\n \"void \" ~\n name ~ \" (VM vm)\n {\n pragma(inline);\n const sp = vm.registers[Register.SP];\n if (sp == vmint(0))\n throw new VMRuntimeException (\\\"stack underflow\\\");\n const x = vm.stack[sp - vmint(1)];\n const z = \" ~ func ~ \" (x);\n vm.stack[sp - vmint(1)] = z;\n }\";\n}\n\ntemplate\nBinaryOperation (alias name, alias func)\n{\n const char[] BinaryOperation =\n \"void \" ~\n name ~ \" (VM vm)\n {\n pragma(inline);\n const spBefore = vm.registers[Register.SP];\n if (spBefore <= vmint(1))\n throw new VMRuntimeException (\\\"stack underflow\\\");\n const spAfter = spBefore - vmint(1);\n vm.registers[Register.SP] = spAfter;\n const x = vm.stack[spAfter - vmint(1)];\n const y = vm.stack[spAfter];\n const z = \" ~ func ~ \"(x, y);\n vm.stack[spAfter - vmint(1)] = z;\n }\";\n}\n\nmixin (UnaryOperation!(\"uopNeg\", \"twosComplement\"));\nmixin (UnaryOperation!(\"uopNot\", \"logicalNot\"));\n\nmixin (BinaryOperation!(\"binopAdd\", \"add\"));\nmixin (BinaryOperation!(\"binopSub\", \"sub\"));\nmixin (BinaryOperation!(\"binopMul\", \"signedMul\"));\nmixin (BinaryOperation!(\"binopDiv\", \"signedDiv\"));\nmixin (BinaryOperation!(\"binopMod\", \"signedMod\"));\nmixin (BinaryOperation!(\"binopEq\", \"equality\"));\nmixin (BinaryOperation!(\"binopNe\", \"inequality\"));\nmixin (BinaryOperation!(\"binopLt\", \"signedLt\"));\nmixin (BinaryOperation!(\"binopGt\", \"signedGt\"));\nmixin (BinaryOperation!(\"binopLe\", \"signedLte\"));\nmixin (BinaryOperation!(\"binopGe\", \"signedGte\"));\nmixin (BinaryOperation!(\"binopAnd\", \"logicalAnd\"));\nmixin (BinaryOperation!(\"binopOr\", \"logicalOr\"));\n\nvoid\ndoPush (VM vm)\n{\n pragma(inline);\n const arg = getArgument (vm);\n push (vm, arg);\n skipArgument (vm);\n}\n\nvoid\ndoFetch (VM vm)\n{\n pragma(inline);\n const i = getArgument (vm);\n const x = fetchData (vm, i);\n push (vm, x);\n skipArgument (vm);\n}\n\nvoid\ndoStore (VM vm)\n{\n pragma(inline);\n const i = getArgument (vm);\n const x = pop (vm);\n storeData (vm, i, x);\n skipArgument (vm);\n}\n\nvoid\ndoJmp (VM vm)\n{\n pragma(inline);\n const arg = getArgument (vm);\n vm.registers[Register.PC] += arg;\n}\n\nvoid\ndoJz (VM vm)\n{\n pragma(inline);\n const x = pop (vm);\n if (x == vmint(0))\n doJmp (vm);\n else\n skipArgument (vm);\n}\n\nvoid\ndoPrtc (File fOut, VM vm)\n{\n const x = pop (vm);\n fOut.write (to!char(x));\n}\n\nvoid\ndoPrti (File fOut, VM vm)\n{\n const x = pop (vm);\n fOut.write (int32_t(x));\n}\n\nvoid\ndoPrts (File fOut, VM vm)\n{\n const i = pop (vm);\n if (vm.strings.length <= i)\n throw new VMRuntimeException (\"string index out of bounds\");\n fOut.write (vm.strings[i]);\n}\n\nvoid\nvmStep (File fOut, VM vm, ref bool machineHalt, ref bool badOpcode)\n{\n const pc = vm.registers[Register.PC];\n if (vm.code.length <= pc)\n throw new VMRuntimeException\n (\"the program counter is out of bounds\");\n vm.registers[Register.PC] = pc + vmint(1);\n const opcode = vm.code[pc];\n const uOpcode = uint(opcode);\n\n // Dispatch by bifurcation on the bit pattern of the opcode. This\n // method is logarithmic in the number of opcode values.\n\n machineHalt = false;\n badOpcode = false;\n if ((uOpcode & (~0x1FU)) == 0U)\n {\n if ((uOpcode & 0x10U) == 0U)\n {\n if ((uOpcode & 0x08U) == 0U)\n {\n if ((uOpcode & 0x04U) == 0U)\n {\n if ((uOpcode & 0x02U) == 0U)\n {\n if ((uOpcode & 0x01U) == 0U)\n machineHalt = true;\n else\n binopAdd (vm);\n }\n else\n {\n if ((uOpcode & 0x01U) == 0U)\n binopSub (vm);\n else\n binopMul (vm);\n }\n }\n else\n {\n if ((uOpcode & 0x02U) == 0U)\n {\n if ((uOpcode & 0x01U) == 0U)\n binopDiv (vm);\n else\n binopMod (vm);\n }\n else\n {\n if ((uOpcode & 0x01U) == 0U)\n binopLt (vm);\n else\n binopGt (vm);\n }\n }\n }\n else\n {\n if ((uOpcode & 0x04U) == 0U)\n {\n if ((uOpcode & 0x02U) == 0U)\n {\n if ((uOpcode & 0x01U) == 0U)\n binopLe (vm);\n else\n binopGe (vm);\n }\n else\n {\n if ((uOpcode & 0x01U) == 0U)\n binopEq (vm);\n else\n binopNe (vm);\n }\n }\n else\n {\n if ((uOpcode & 0x02U) == 0U)\n {\n if ((uOpcode & 0x01U) == 0U)\n binopAnd (vm);\n else\n binopOr (vm);\n }\n else\n {\n if ((uOpcode & 0x01U) == 0U)\n uopNeg (vm);\n else\n uopNot (vm);\n }\n }\n }\n }\n else\n {\n if ((uOpcode & 0x08U) == 0U)\n {\n if ((uOpcode & 0x04U) == 0U)\n {\n if ((uOpcode & 0x02U) == 0U)\n {\n if ((uOpcode & 0x01U) == 0U)\n doPrtc (fOut, vm);\n else\n doPrti (fOut, vm);\n }\n else\n {\n if ((uOpcode & 0x01U) == 0U)\n doPrts (fOut, vm);\n else\n doFetch (vm);\n }\n }\n else\n {\n if ((uOpcode & 0x02U) == 0U)\n {\n if ((uOpcode & 0x01U) == 0U)\n doStore (vm);\n else\n doPush (vm);\n }\n else\n {\n if ((uOpcode & 0x01U) == 0U)\n doJmp (vm);\n else\n doJz (vm);\n }\n }\n }\n else\n badOpcode = true;\n }\n }\n else\n badOpcode = true;\n}\n\nvoid\nvmContinue (File fOut, VM vm)\n{\n auto machineHalt = false;\n auto badOpcode = false;\n while (!machineHalt && !badOpcode)\n vmStep (fOut, vm, machineHalt, badOpcode);\n if (badOpcode)\n throw new VMRuntimeException (\"unrecognized opcode at runtime\");\n}\n\nvoid\nvmInitialize (VM vm)\n{\n foreach (ref x; vm.data)\n x = vmint(0);\n vm.registers[Register.PC] = vmint(0);\n vm.registers[Register.SP] = vmint(0);\n}\n\nvoid\nvmRun (File fOut, VM vm)\n{\n vmInitialize (vm);\n vmContinue (fOut, vm);\n}\n\nvoid\nensure_that_vmint_is_suitable ()\n{\n // Try to guarantee that vmint is exactly 32 bits, and that it\n // allows overflow in either direction.\n assert (vmint(0xFFFFFFFFU) + vmint(1U) == vmint(0U));\n assert (vmint(0U) - vmint(1U) == vmint(0xFFFFFFFFU));\n assert (vmint(-1234) == twosComplement (vmint(1234)));\n}\n\nint\nmain (char[][] args)\n{\n auto inpFilename = \"-\";\n auto outFilename = \"-\";\n if (2 <= args.length)\n inpFilename = to!string (args[1]);\n if (3 <= args.length)\n outFilename = to!string (args[2]);\n\n auto inpF = stdin;\n if (inpFilename != \"-\")\n inpF = File (inpFilename, \"r\");\n auto vm = readVM (inpF);\n if (inpFilename != \"-\")\n inpF.close();\n\n auto outF = stdout;\n if (outFilename != \"-\")\n outF = File (outFilename, \"w\");\n ensure_that_vmint_is_suitable ();\n vmRun (outF, vm);\n if (outFilename != \"-\")\n outF.close();\n\n return 0;\n}\n", "language": "D" }, { "code": "CREATE BUF 0 , \\ single-character look-ahead buffer\n: PEEK BUF @ 0= IF KEY BUF ! THEN BUF @ ;\n: GETC PEEK 0 BUF ! ;\n: SPACE? DUP BL = SWAP 9 14 WITHIN OR ;\n: >SPACE BEGIN PEEK SPACE? WHILE GETC DROP REPEAT ;\n: DIGIT? 48 58 WITHIN ;\n: >INT ( -- n) >SPACE 0\n BEGIN PEEK DIGIT?\n WHILE GETC [CHAR] 0 - SWAP 10 * + REPEAT ;\nCREATE A 0 ,\n: C@A ( -- c) A @ C@ ;\n: C@A+ ( -- c) C@A 1 CHARS A +! ;\n: C!A+ ( c --) A @ C! 1 CHARS A +! ;\n: WORD ( -- c-addr) >SPACE PAD 1+ A !\n BEGIN PEEK SPACE? INVERT WHILE GETC C!A+ REPEAT\n >SPACE PAD A @ OVER - 1- PAD C! ;\n: >STRING ( -- c-addr) >SPACE GETC DROP PAD 1+ A !\n BEGIN PEEK [CHAR] \" <> WHILE GETC C!A+ REPEAT\n GETC DROP PAD A @ OVER - 1- PAD C! ;\n: \\INTERN ( c-addr -- c-addr) HERE >R A ! C@A+ DUP C,\n BEGIN DUP WHILE C@A+\n DUP [CHAR] \\ = IF DROP -1 R@ +! C@A+\n [CHAR] n = IF 10 ELSE [CHAR] \\ THEN\n THEN C, 1-\n REPEAT DROP R> ;\n: . 0 .R ;\n\nCREATE DATA 0 ,\nCREATE STRINGS 0 ,\n: >DATA HERE DATA !\n WORD DROP >INT 4 * BEGIN DUP WHILE 0 C, 1- REPEAT DROP ;\n: >STRINGS HERE STRINGS !\n WORD DROP >INT DUP >R CELLS ALLOT\n 0 BEGIN DUP R@ < WHILE\n DUP CELLS >STRING \\INTERN STRINGS @ ROT + ! 1+\n REPEAT R> DROP DROP ;\n: >HEADER >DATA >STRINGS ;\n: i32! ( n addr --)\n OVER $FF AND OVER C! 1+\n OVER 8 RSHIFT $FF AND OVER C! 1+\n OVER 16 RSHIFT $FF AND OVER C! 1+\n SWAP 24 RSHIFT $FF AND SWAP C! ;\n: i32@ ( addr -- n) >R \\ This is kinda slow... hmm\n R@ C@\n R@ 1 + C@ 8 LSHIFT OR\n R@ 2 + C@ 16 LSHIFT OR\n R> 3 + C@ 24 LSHIFT OR\n DUP $7FFFFFFF AND SWAP $80000000 AND - ; \\ sign extend\n: i32, ( n --) HERE 4 ALLOT i32! ;\n: i32@+ ( -- n) A @ i32@ A @ 4 + A ! ;\nCREATE BYTECODE 0 ,\n: @fetch i32@+ 4 * DATA @ + i32@ ;\n: @store i32@+ 4 * DATA @ + i32! ;\n: @jmp i32@+ BYTECODE @ + A ! ;\n: @jz IF 4 A +! ELSE @jmp THEN ;\n: @prts CELLS STRINGS @ + @ COUNT TYPE ;\n: @div >R S>D R> SM/REM SWAP DROP ;\nCREATE OPS\n' @fetch , ' @store , ' i32@+ , ' @jmp , ' @jz ,\n' EMIT , ' . , ' @prts , ' NEGATE , ' 0= ,\n' + , ' - , ' * , ' @div , ' MOD ,\n' < , ' > , ' <= , ' >= ,\n' = , ' <> , ' AND , ' OR , ' BYE ,\nCREATE #OPS 0 ,\n: OP: CREATE #OPS @ , 1 #OPS +! DOES> @ ;\nOP: fetch OP: store OP: push OP: jmp OP: jz\nOP: prtc OP: prti OP: prts OP: neg OP: not\nOP: add OP: sub OP: mul OP: div OP: mod\nOP: lt OP: gt OP: le OP: ge\nOP: eq OP: ne OP: and OP: or OP: halt\n: >OP WORD FIND\n 0= IF .\" Unrecognized opcode\" ABORT THEN EXECUTE ;\n: >i32 >INT i32, ;\n: >[i32] GETC DROP >i32 GETC DROP ;\n: >OFFSET WORD DROP ( drop relative offset) >i32 ;\nCREATE >PARAM ' >[i32] DUP , , ' >i32 , ' >OFFSET DUP , ,\n: >BYTECODE HERE >R\n BEGIN >INT DROP >OP >R R@ C,\n R@ 5 < IF R@ CELLS >PARAM + @ EXECUTE THEN\n R> halt = UNTIL R> BYTECODE ! ;\n: RUN BYTECODE @ A !\n BEGIN C@A+ CELLS OPS + @ EXECUTE AGAIN ;\n>HEADER >BYTECODE RUN\n", "language": "Forth" }, { "code": "module compiler_type_kinds\n use, intrinsic :: iso_fortran_env, only: int32\n use, intrinsic :: iso_fortran_env, only: int64\n\n implicit none\n private\n\n ! Synonyms.\n integer, parameter, public :: size_kind = int64\n integer, parameter, public :: length_kind = size_kind\n integer, parameter, public :: nk = size_kind\n\n ! Synonyms for character capable of storing a Unicode code point.\n integer, parameter, public :: unicode_char_kind = selected_char_kind ('ISO_10646')\n integer, parameter, public :: ck = unicode_char_kind\n\n ! Synonyms for integers capable of storing a Unicode code point.\n integer, parameter, public :: unicode_ichar_kind = int32\n integer, parameter, public :: ick = unicode_ichar_kind\n\n ! Synonyms for integers in the virtual machine or the interpreter’s\n ! runtime. (The Rosetta Code task says integers in the virtual\n ! machine are 32-bit, but there is nothing in the task that prevents\n ! us using 64-bit integers in the compiler and interpreter.)\n integer, parameter, public :: runtime_int_kind = int64\n integer, parameter, public :: rik = runtime_int_kind\nend module compiler_type_kinds\n\nmodule helpers\n use, non_intrinsic :: compiler_type_kinds, only: nk, rik, ck\n\n implicit none\n private\n\n public :: new_storage_size\n public :: next_power_of_two\n\n public :: isspace\n public :: quoted_string\n\n public :: int32_to_vm_bytes\n public :: uint32_to_vm_bytes\n public :: int32_from_vm_bytes\n public :: uint32_from_vm_bytes\n\n public :: bool2int\n\n character(1, kind = ck), parameter, public :: horizontal_tab_char = char (9, kind = ck)\n character(1, kind = ck), parameter, public :: linefeed_char = char (10, kind = ck)\n character(1, kind = ck), parameter, public :: vertical_tab_char = char (11, kind = ck)\n character(1, kind = ck), parameter, public :: formfeed_char = char (12, kind = ck)\n character(1, kind = ck), parameter, public :: carriage_return_char = char (13, kind = ck)\n character(1, kind = ck), parameter, public :: space_char = ck_' '\n\n ! The following is correct for Unix and its relatives.\n character(1, kind = ck), parameter, public :: newline_char = linefeed_char\n\n character(1, kind = ck), parameter, public :: backslash_char = char (92, kind = ck)\n\ncontains\n\n elemental function new_storage_size (length_needed) result (size)\n integer(kind = nk), intent(in) :: length_needed\n integer(kind = nk) :: size\n\n ! Increase storage by orders of magnitude.\n\n if (2_nk**32 < length_needed) then\n size = huge (1_nk)\n else\n size = next_power_of_two (length_needed)\n end if\n end function new_storage_size\n\n elemental function next_power_of_two (x) result (y)\n integer(kind = nk), intent(in) :: x\n integer(kind = nk) :: y\n\n !\n ! It is assumed that no more than 64 bits are used.\n !\n ! The branch-free algorithm is that of\n ! https://archive.is/nKxAc#RoundUpPowerOf2\n !\n ! Fill in bits until one less than the desired power of two is\n ! reached, and then add one.\n !\n\n y = x - 1\n y = ior (y, ishft (y, -1))\n y = ior (y, ishft (y, -2))\n y = ior (y, ishft (y, -4))\n y = ior (y, ishft (y, -8))\n y = ior (y, ishft (y, -16))\n y = ior (y, ishft (y, -32))\n y = y + 1\n end function next_power_of_two\n\n elemental function isspace (ch) result (bool)\n character(1, kind = ck), intent(in) :: ch\n logical :: bool\n\n bool = (ch == horizontal_tab_char) .or. &\n & (ch == linefeed_char) .or. &\n & (ch == vertical_tab_char) .or. &\n & (ch == formfeed_char) .or. &\n & (ch == carriage_return_char) .or. &\n & (ch == space_char)\n end function isspace\n\n function quoted_string (str) result (qstr)\n character(*, kind = ck), intent(in) :: str\n character(:, kind = ck), allocatable :: qstr\n\n integer(kind = nk) :: n, i, j\n\n ! Compute n = the size of qstr.\n n = 2_nk\n do i = 1_nk, len (str, kind = nk)\n select case (str(i:i))\n case (newline_char, backslash_char)\n n = n + 2\n case default\n n = n + 1\n end select\n end do\n\n allocate (character(n, kind = ck) :: qstr)\n\n ! Quote the string.\n qstr(1:1) = ck_'\"'\n j = 2_nk\n do i = 1_nk, len (str, kind = nk)\n select case (str(i:i))\n case (newline_char)\n qstr(j:j) = backslash_char\n qstr((j + 1):(j + 1)) = ck_'n'\n j = j + 2\n case (backslash_char)\n qstr(j:j) = backslash_char\n qstr((j + 1):(j + 1)) = backslash_char\n j = j + 2\n case default\n qstr(j:j) = str(i:i)\n j = j + 1\n end select\n end do\n if (j /= n) error stop ! Check code correctness.\n qstr(n:n) = ck_'\"'\n end function quoted_string\n\n subroutine int32_to_vm_bytes (n, bytes, i)\n integer(kind = rik), intent(in) :: n\n character(1), intent(inout) :: bytes(0:*)\n integer(kind = rik), intent(in) :: i\n\n !\n ! The virtual machine is presumed to be little-endian. Because I\n ! slightly prefer little-endian.\n !\n\n bytes(i) = achar (ibits (n, 0, 8))\n bytes(i + 1) = achar (ibits (n, 8, 8))\n bytes(i + 2) = achar (ibits (n, 16, 8))\n bytes(i + 3) = achar (ibits (n, 24, 8))\n end subroutine int32_to_vm_bytes\n\n subroutine uint32_to_vm_bytes (n, bytes, i)\n integer(kind = rik), intent(in) :: n\n character(1), intent(inout) :: bytes(0:*)\n integer(kind = rik), intent(in) :: i\n\n call int32_to_vm_bytes (n, bytes, i)\n end subroutine uint32_to_vm_bytes\n\n subroutine int32_from_vm_bytes (n, bytes, i)\n integer(kind = rik), intent(out) :: n\n character(1), intent(in) :: bytes(0:*)\n integer(kind = rik), intent(in) :: i\n\n !\n ! The virtual machine is presumed to be little-endian. Because I\n ! slightly prefer little-endian.\n !\n\n call uint32_from_vm_bytes (n, bytes, i)\n if (ibits (n, 31, 1) == 1) then\n ! Extend the sign bit.\n n = ior (n, not ((2_rik ** 32) - 1))\n end if\n end subroutine int32_from_vm_bytes\n\n subroutine uint32_from_vm_bytes (n, bytes, i)\n integer(kind = rik), intent(out) :: n\n character(1), intent(in) :: bytes(0:*)\n integer(kind = rik), intent(in) :: i\n\n !\n ! The virtual machine is presumed to be little-endian. Because I\n ! slightly prefer little-endian.\n !\n\n integer(kind = rik) :: n0, n1, n2, n3\n\n n0 = iachar (bytes(i), kind = rik)\n n1 = ishft (iachar (bytes(i + 1), kind = rik), 8)\n n2 = ishft (iachar (bytes(i + 2), kind = rik), 16)\n n3 = ishft (iachar (bytes(i + 3), kind = rik), 24)\n n = ior (n0, ior (n1, ior (n2, n3)))\n end subroutine uint32_from_vm_bytes\n\n elemental function bool2int (bool) result (int)\n logical, intent(in) :: bool\n integer(kind = rik) :: int\n\n if (bool) then\n int = 1_rik\n else\n int = 0_rik\n end if\n end function bool2int\n\nend module helpers\n\nmodule string_buffers\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, intrinsic :: iso_fortran_env, only: int64\n use, non_intrinsic :: compiler_type_kinds, only: nk, ck, ick\n use, non_intrinsic :: helpers\n\n implicit none\n private\n\n public :: strbuf_t\n public :: skip_whitespace\n public :: skip_non_whitespace\n public :: skip_whitespace_backwards\n public :: at_end_of_line\n\n type :: strbuf_t\n integer(kind = nk), private :: len = 0\n !\n ! ‘chars’ is made public for efficient access to the individual\n ! characters.\n !\n character(1, kind = ck), allocatable, public :: chars(:)\n contains\n procedure, pass, private :: ensure_storage => strbuf_t_ensure_storage\n procedure, pass :: to_unicode_full_string => strbuf_t_to_unicode_full_string\n procedure, pass :: to_unicode_substring => strbuf_t_to_unicode_substring\n procedure, pass :: length => strbuf_t_length\n procedure, pass :: set => strbuf_t_set\n procedure, pass :: append => strbuf_t_append\n generic :: to_unicode => to_unicode_full_string\n generic :: to_unicode => to_unicode_substring\n generic :: assignment(=) => set\n end type strbuf_t\n\ncontains\n\n function strbuf_t_to_unicode_full_string (strbuf) result (s)\n class(strbuf_t), intent(in) :: strbuf\n character(:, kind = ck), allocatable :: s\n\n !\n ! This does not actually ensure that the string is valid Unicode;\n ! any 31-bit ‘character’ is supported.\n !\n\n integer(kind = nk) :: i\n\n allocate (character(len = strbuf%len, kind = ck) :: s)\n do i = 1, strbuf%len\n s(i:i) = strbuf%chars(i)\n end do\n end function strbuf_t_to_unicode_full_string\n\n function strbuf_t_to_unicode_substring (strbuf, i, j) result (s)\n !\n ! ‘Extreme’ values of i and j are allowed, as shortcuts for ‘from\n ! the beginning’, ‘up to the end’, or ‘empty substring’.\n !\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i, j\n character(:, kind = ck), allocatable :: s\n\n !\n ! This does not actually ensure that the string is valid Unicode;\n ! any 31-bit ‘character’ is supported.\n !\n\n integer(kind = nk) :: i1, j1\n integer(kind = nk) :: n\n integer(kind = nk) :: k\n\n i1 = max (1_nk, i)\n j1 = min (strbuf%len, j)\n n = max (0_nk, (j1 - i1) + 1_nk)\n\n allocate (character(n, kind = ck) :: s)\n do k = 1, n\n s(k:k) = strbuf%chars(i1 + (k - 1_nk))\n end do\n end function strbuf_t_to_unicode_substring\n\n elemental function strbuf_t_length (strbuf) result (n)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk) :: n\n\n n = strbuf%len\n end function strbuf_t_length\n\n subroutine strbuf_t_ensure_storage (strbuf, length_needed)\n class(strbuf_t), intent(inout) :: strbuf\n integer(kind = nk), intent(in) :: length_needed\n\n integer(kind = nk) :: len_needed\n integer(kind = nk) :: new_size\n type(strbuf_t) :: new_strbuf\n\n len_needed = max (length_needed, 1_nk)\n\n if (.not. allocated (strbuf%chars)) then\n ! Initialize a new strbuf%chars array.\n new_size = new_storage_size (len_needed)\n allocate (strbuf%chars(1:new_size))\n else if (ubound (strbuf%chars, 1) < len_needed) then\n ! Allocate a new strbuf%chars array, larger than the current\n ! one, but containing the same characters.\n new_size = new_storage_size (len_needed)\n allocate (new_strbuf%chars(1:new_size))\n new_strbuf%chars(1:strbuf%len) = strbuf%chars(1:strbuf%len)\n call move_alloc (new_strbuf%chars, strbuf%chars)\n end if\n end subroutine strbuf_t_ensure_storage\n\n subroutine strbuf_t_set (dst, src)\n class(strbuf_t), intent(inout) :: dst\n class(*), intent(in) :: src\n\n integer(kind = nk) :: n\n integer(kind = nk) :: i\n\n select type (src)\n type is (character(*, kind = ck))\n n = len (src, kind = nk)\n call dst%ensure_storage(n)\n do i = 1, n\n dst%chars(i) = src(i:i)\n end do\n dst%len = n\n type is (character(*))\n n = len (src, kind = nk)\n call dst%ensure_storage(n)\n do i = 1, n\n dst%chars(i) = src(i:i)\n end do\n dst%len = n\n class is (strbuf_t)\n n = src%len\n call dst%ensure_storage(n)\n dst%chars(1:n) = src%chars(1:n)\n dst%len = n\n class default\n error stop\n end select\n end subroutine strbuf_t_set\n\n subroutine strbuf_t_append (dst, src)\n class(strbuf_t), intent(inout) :: dst\n class(*), intent(in) :: src\n\n integer(kind = nk) :: n_dst, n_src, n\n integer(kind = nk) :: i\n\n select type (src)\n type is (character(*, kind = ck))\n n_dst = dst%len\n n_src = len (src, kind = nk)\n n = n_dst + n_src\n call dst%ensure_storage(n)\n do i = 1, n_src\n dst%chars(n_dst + i) = src(i:i)\n end do\n dst%len = n\n type is (character(*))\n n_dst = dst%len\n n_src = len (src, kind = nk)\n n = n_dst + n_src\n call dst%ensure_storage(n)\n do i = 1, n_src\n dst%chars(n_dst + i) = src(i:i)\n end do\n dst%len = n\n class is (strbuf_t)\n n_dst = dst%len\n n_src = src%len\n n = n_dst + n_src\n call dst%ensure_storage(n)\n dst%chars((n_dst + 1):n) = src%chars(1:n_src)\n dst%len = n\n class default\n error stop\n end select\n end subroutine strbuf_t_append\n\n function skip_whitespace (strbuf, i) result (j)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n integer(kind = nk) :: j\n\n logical :: done\n\n j = i\n done = .false.\n do while (.not. done)\n if (at_end_of_line (strbuf, j)) then\n done = .true.\n else if (.not. isspace (strbuf%chars(j))) then\n done = .true.\n else\n j = j + 1\n end if\n end do\n end function skip_whitespace\n\n function skip_non_whitespace (strbuf, i) result (j)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n integer(kind = nk) :: j\n\n logical :: done\n\n j = i\n done = .false.\n do while (.not. done)\n if (at_end_of_line (strbuf, j)) then\n done = .true.\n else if (isspace (strbuf%chars(j))) then\n done = .true.\n else\n j = j + 1\n end if\n end do\n end function skip_non_whitespace\n\n function skip_whitespace_backwards (strbuf, i) result (j)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n integer(kind = nk) :: j\n\n logical :: done\n\n j = i\n done = .false.\n do while (.not. done)\n if (j == -1) then\n done = .true.\n else if (.not. isspace (strbuf%chars(j))) then\n done = .true.\n else\n j = j - 1\n end if\n end do\n end function skip_whitespace_backwards\n\n function at_end_of_line (strbuf, i) result (bool)\n class(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n logical :: bool\n\n bool = (strbuf%length() < i)\n end function at_end_of_line\n\nend module string_buffers\n\nmodule reading_one_line_from_a_stream\n use, intrinsic :: iso_fortran_env, only: input_unit\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, non_intrinsic :: compiler_type_kinds, only: nk, ck, ick\n use, non_intrinsic :: string_buffers\n\n implicit none\n private\n\n ! get_line_from_stream: read an entire input line from a stream into\n ! a strbuf_t.\n public :: get_line_from_stream\n\n character(1, kind = ck), parameter :: linefeed_char = char (10, kind = ck)\n\n ! The following is correct for Unix and its relatives.\n character(1, kind = ck), parameter :: newline_char = linefeed_char\n\ncontains\n\n subroutine get_line_from_stream (unit_no, eof, no_newline, strbuf)\n integer, intent(in) :: unit_no\n logical, intent(out) :: eof ! End of file?\n logical, intent(out) :: no_newline ! There is a line but it has no\n ! newline? (Thus eof also must\n ! be .true.)\n class(strbuf_t), intent(inout) :: strbuf\n\n character(1, kind = ck) :: ch\n\n strbuf = ''\n call get_ch (unit_no, eof, ch)\n do while (.not. eof .and. ch /= newline_char)\n call strbuf%append (ch)\n call get_ch (unit_no, eof, ch)\n end do\n no_newline = eof .and. (strbuf%length() /= 0)\n end subroutine get_line_from_stream\n\n subroutine get_ch (unit_no, eof, ch)\n !\n ! Read a single code point from the stream.\n !\n ! Currently this procedure simply inputs ‘ASCII’ bytes rather than\n ! Unicode code points.\n !\n integer, intent(in) :: unit_no\n logical, intent(out) :: eof\n character(1, kind = ck), intent(out) :: ch\n\n integer :: stat\n character(1) :: c = '*'\n\n eof = .false.\n\n if (unit_no == input_unit) then\n call get_input_unit_char (c, stat)\n else\n read (unit = unit_no, iostat = stat) c\n end if\n\n if (stat < 0) then\n ch = ck_'*'\n eof = .true.\n else if (0 < stat) then\n write (error_unit, '(\"Input error with status code \", I0)') stat\n stop 1\n else\n ch = char (ichar (c, kind = ick), kind = ck)\n end if\n end subroutine get_ch\n\n!!!\n!!! If you tell gfortran you want -std=f2008 or -std=f2018, you likely\n!!! will need to add also -fall-intrinsics or -U__GFORTRAN__\n!!!\n!!! The first way, you get the FGETC intrinsic. The latter way, you\n!!! get the C interface code that uses getchar(3).\n!!!\n#ifdef __GFORTRAN__\n\n subroutine get_input_unit_char (c, stat)\n !\n ! The following works if you are using gfortran.\n !\n ! (FGETC is considered a feature for backwards compatibility with\n ! g77. However, I know of no way to reconfigure input_unit as a\n ! Fortran 2003 stream, for use with ordinary ‘read’.)\n !\n character, intent(inout) :: c\n integer, intent(out) :: stat\n\n call fgetc (input_unit, c, stat)\n end subroutine get_input_unit_char\n\n#else\n\n subroutine get_input_unit_char (c, stat)\n !\n ! An alternative implementation of get_input_unit_char. This\n ! actually reads input from the C standard input, which might not\n ! be the same as input_unit.\n !\n use, intrinsic :: iso_c_binding, only: c_int\n character, intent(inout) :: c\n integer, intent(out) :: stat\n\n interface\n !\n ! Use getchar(3) to read characters from standard input. This\n ! assumes there is actually such a function available, and that\n ! getchar(3) does not exist solely as a macro. (One could write\n ! one’s own getchar() if necessary, of course.)\n !\n function getchar () result (c) bind (c, name = 'getchar')\n use, intrinsic :: iso_c_binding, only: c_int\n integer(kind = c_int) :: c\n end function getchar\n end interface\n\n integer(kind = c_int) :: i_char\n\n i_char = getchar ()\n !\n ! The C standard requires that EOF have a negative value. If the\n ! value returned by getchar(3) is not EOF, then it will be\n ! representable as an unsigned char. Therefore, to check for end\n ! of file, one need only test whether i_char is negative.\n !\n if (i_char < 0) then\n stat = -1\n else\n stat = 0\n c = char (i_char)\n end if\n end subroutine get_input_unit_char\n\n#endif\n\nend module reading_one_line_from_a_stream\n\nmodule vm_reader\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, non_intrinsic :: compiler_type_kinds\n use, non_intrinsic :: helpers\n use, non_intrinsic :: string_buffers\n use, non_intrinsic :: reading_one_line_from_a_stream\n\n implicit none\n private\n\n public :: vm_code_t\n public :: vm_t\n public :: read_vm\n\n !\n ! Arbitrarily chosen opcodes.\n !\n ! I think there should be a no-operation ‘nop’ opcode, to reserve\n ! space for later hand-patching. :)\n !\n integer, parameter, public :: opcode_nop = 0\n integer, parameter, public :: opcode_halt = 1\n integer, parameter, public :: opcode_add = 2\n integer, parameter, public :: opcode_sub = 3\n integer, parameter, public :: opcode_mul = 4\n integer, parameter, public :: opcode_div = 5\n integer, parameter, public :: opcode_mod = 6\n integer, parameter, public :: opcode_lt = 7\n integer, parameter, public :: opcode_gt = 8\n integer, parameter, public :: opcode_le = 9\n integer, parameter, public :: opcode_ge = 10\n integer, parameter, public :: opcode_eq = 11\n integer, parameter, public :: opcode_ne = 12\n integer, parameter, public :: opcode_and = 13\n integer, parameter, public :: opcode_or = 14\n integer, parameter, public :: opcode_neg = 15\n integer, parameter, public :: opcode_not = 16\n integer, parameter, public :: opcode_prtc = 17\n integer, parameter, public :: opcode_prti = 18\n integer, parameter, public :: opcode_prts = 19\n integer, parameter, public :: opcode_fetch = 20\n integer, parameter, public :: opcode_store = 21\n integer, parameter, public :: opcode_push = 22\n integer, parameter, public :: opcode_jmp = 23\n integer, parameter, public :: opcode_jz = 24\n\n character(8, kind = ck), parameter, public :: opcode_names(0:24) = &\n & (/ \"nop \", &\n & \"halt \", &\n & \"add \", &\n & \"sub \", &\n & \"mul \", &\n & \"div \", &\n & \"mod \", &\n & \"lt \", &\n & \"gt \", &\n & \"le \", &\n & \"ge \", &\n & \"eq \", &\n & \"ne \", &\n & \"and \", &\n & \"or \", &\n & \"neg \", &\n & \"not \", &\n & \"prtc \", &\n & \"prti \", &\n & \"prts \", &\n & \"fetch \", &\n & \"store \", &\n & \"push \", &\n & \"jmp \", &\n & \"jz \" /)\n\n type :: vm_code_t\n integer(kind = rik), private :: len = 0_rik\n character(1), allocatable :: bytes(:)\n contains\n procedure, pass, private :: ensure_storage => vm_code_t_ensure_storage\n procedure, pass :: length => vm_code_t_length\n end type vm_code_t\n\n type :: vm_t\n integer(kind = rik), allocatable :: string_boundaries(:)\n character(:, kind = ck), allocatable :: strings\n character(1), allocatable :: data(:)\n character(1), allocatable :: stack(:)\n type(vm_code_t) :: code\n integer(kind = rik) :: sp = 0_rik\n integer(kind = rik) :: pc = 0_rik\n end type vm_t\n\ncontains\n\n subroutine vm_code_t_ensure_storage (code, length_needed)\n class(vm_code_t), intent(inout) :: code\n integer(kind = nk), intent(in) :: length_needed\n\n integer(kind = nk) :: len_needed\n integer(kind = nk) :: new_size\n type(vm_code_t) :: new_code\n\n len_needed = max (length_needed, 1_nk)\n\n if (.not. allocated (code%bytes)) then\n ! Initialize a new code%bytes array.\n new_size = new_storage_size (len_needed)\n allocate (code%bytes(0:(new_size - 1)))\n else if (ubound (code%bytes, 1) < len_needed - 1) then\n ! Allocate a new code%bytes array, larger than the current one,\n ! but containing the same bytes.\n new_size = new_storage_size (len_needed)\n allocate (new_code%bytes(0:(new_size - 1)))\n new_code%bytes(0:(code%len - 1)) = code%bytes(0:(code%len - 1))\n call move_alloc (new_code%bytes, code%bytes)\n end if\n end subroutine vm_code_t_ensure_storage\n\n elemental function vm_code_t_length (code) result (len)\n class(vm_code_t), intent(in) :: code\n integer(kind = rik) :: len\n\n len = code%len\n end function vm_code_t_length\n\n subroutine read_vm (inp, strbuf, vm)\n integer, intent(in) :: inp\n type(strbuf_t), intent(inout) :: strbuf\n type(vm_t), intent(out) :: vm\n\n integer(kind = rik) :: data_size\n integer(kind = rik) :: number_of_strings\n\n ! Read the header.\n call read_datasize_and_number_of_strings (inp, strbuf, data_size, number_of_strings)\n\n ! Allocate storage for data_size 32-bit numbers. Initialize them\n ! to zero, for no better reason than that C initializes global\n ! variables to zero.\n allocate (vm%data(0_rik:(4_rik * (data_size - 1))), source = achar (0))\n\n ! Allocate storage for indices/bounds of the strings to be loaded\n ! into the string storage space.\n allocate (vm%string_boundaries(0_rik:number_of_strings))\n\n ! Fill the strings storage and the string boundaries array.\n call read_strings (inp, strbuf, number_of_strings, vm)\n\n ! Read the program instructions.\n call read_code (inp, strbuf, vm)\n\n ! Allocate a stack. Let us say that the stack size must be a\n ! multiple of 4, and is fixed at 65536 = 4**8 bytes. Pushing a\n ! 32-bit integer increases the stack pointer by 4, popping\n ! decreases it by 4.\n allocate (vm%stack(0_rik:(4_rik ** 8)))\n end subroutine read_vm\n\n subroutine read_datasize_and_number_of_strings (inp, strbuf, data_size, number_of_strings)\n integer, intent(in) :: inp\n type(strbuf_t), intent(inout) :: strbuf\n integer(kind = rik), intent(out) :: data_size\n integer(kind = rik), intent(out) :: number_of_strings\n\n logical :: eof\n logical :: no_newline\n integer(kind = nk) :: i, j\n character(:, kind = ck), allocatable :: data_size_str\n character(:, kind = ck), allocatable :: number_of_strings_str\n integer :: stat\n\n call get_line_from_stream (inp, eof, no_newline, strbuf)\n if (eof) call bad_vm_assembly\n\n i = skip_whitespace (strbuf, 1_nk)\n i = skip_datasize_keyword (strbuf, i)\n i = skip_whitespace (strbuf, i)\n i = skip_specific_character (strbuf, i, ck_':')\n i = skip_whitespace (strbuf, i)\n j = skip_non_whitespace (strbuf, i)\n if (j == i) call bad_vm_assembly\n allocate (data_size_str, source = strbuf%to_unicode (i, j - 1))\n\n i = skip_whitespace(strbuf, j)\n i = skip_strings_keyword (strbuf, i)\n i = skip_whitespace (strbuf, i)\n i = skip_specific_character (strbuf, i, ck_':')\n i = skip_whitespace (strbuf, i)\n j = skip_non_whitespace (strbuf, i)\n if (j == i) call bad_vm_assembly\n allocate (number_of_strings_str, source = strbuf%to_unicode (i, j - 1))\n\n read (data_size_str, *, iostat = stat) data_size\n if (stat /= 0) call bad_vm_assembly\n read (number_of_strings_str, *, iostat = stat) number_of_strings\n if (stat /= 0) call bad_vm_assembly\n end subroutine read_datasize_and_number_of_strings\n\n subroutine read_strings (inp, strbuf, number_of_strings, vm)\n integer, intent(in) :: inp\n type(strbuf_t), intent(inout) :: strbuf\n integer(kind = rik), intent(in) :: number_of_strings\n type(vm_t), intent(inout) :: vm\n\n type(strbuf_t) :: strings_temporary\n integer(kind = rik) :: i\n\n vm%string_boundaries(0) = 0_rik\n do i = 0_rik, number_of_strings - 1\n call read_one_string (inp, strbuf, strings_temporary)\n vm%string_boundaries(i + 1) = strings_temporary%length()\n end do\n allocate (vm%strings, source = strings_temporary%to_unicode())\n end subroutine read_strings\n\n subroutine read_one_string (inp, strbuf, strings_temporary)\n integer, intent(in) :: inp\n type(strbuf_t), intent(inout) :: strbuf\n type(strbuf_t), intent(inout) :: strings_temporary\n\n logical :: eof\n logical :: no_newline\n integer(kind = nk) :: i\n logical :: done\n\n call get_line_from_stream (inp, eof, no_newline, strbuf)\n if (eof) call bad_vm_assembly\n i = skip_whitespace (strbuf, 1_nk)\n i = skip_specific_character (strbuf, i, ck_'\"')\n done = .false.\n do while (.not. done)\n if (i == strbuf%length() + 1) call bad_vm_assembly\n if (strbuf%chars(i) == ck_'\"') then\n done = .true.\n else if (strbuf%chars(i) == backslash_char) then\n if (i == strbuf%length()) call bad_vm_assembly\n select case (strbuf%chars(i + 1))\n case (ck_'n')\n call strings_temporary%append(newline_char)\n case (backslash_char)\n call strings_temporary%append(backslash_char)\n case default\n call bad_vm_assembly\n end select\n i = i + 2\n else\n call strings_temporary%append(strbuf%chars(i))\n i = i + 1\n end if\n end do\n end subroutine read_one_string\n\n subroutine read_code (inp, strbuf, vm)\n integer, intent(in) :: inp\n type(strbuf_t), intent(inout) :: strbuf\n type(vm_t), intent(inout) :: vm\n\n logical :: eof\n logical :: no_newline\n\n call get_line_from_stream (inp, eof, no_newline, strbuf)\n do while (.not. eof)\n call parse_instruction (strbuf, vm%code)\n call get_line_from_stream (inp, eof, no_newline, strbuf)\n end do\n end subroutine read_code\n\n subroutine parse_instruction (strbuf, code)\n type(strbuf_t), intent(in) :: strbuf\n type(vm_code_t), intent(inout) :: code\n\n integer(kind = nk) :: i, j\n integer :: stat\n\n integer :: opcode\n integer(kind = rik) :: i_vm\n integer(kind = rik) :: arg\n\n character(8, kind = ck) :: opcode_name_str\n character(:, kind = ck), allocatable :: i_vm_str\n character(:, kind = ck), allocatable :: arg_str\n\n i = skip_whitespace (strbuf, 1_nk)\n j = skip_non_whitespace (strbuf, i)\n if (j == i) call bad_vm_assembly\n allocate (i_vm_str, source = strbuf%to_unicode(i, j - 1))\n read (i_vm_str, *, iostat = stat) i_vm\n if (stat /= 0) call bad_vm_assembly\n\n i = skip_whitespace (strbuf, j)\n j = skip_non_whitespace (strbuf, i)\n opcode_name_str = ck_' '\n opcode_name_str(1:(j - i)) = strbuf%to_unicode(i, j - 1)\n opcode = findloc (opcode_names, opcode_name_str, 1) - 1\n if (opcode == -1) call bad_vm_assembly\n\n select case (opcode)\n\n case (opcode_push)\n call code%ensure_storage(i_vm + 5)\n code%bytes(i_vm) = achar (opcode)\n i = skip_whitespace (strbuf, j)\n j = skip_non_whitespace (strbuf, i)\n if (j == i) call bad_vm_assembly\n allocate (arg_str, source = strbuf%to_unicode(i, j - 1))\n read (arg_str, *, iostat = stat) arg\n if (stat /= 0) call bad_vm_assembly\n call int32_to_vm_bytes (arg, code%bytes, i_vm + 1)\n code%len = max (code%len, i_vm + 5)\n\n case (opcode_fetch, opcode_store)\n call code%ensure_storage(i_vm + 5)\n code%bytes(i_vm) = achar (opcode)\n i = skip_whitespace (strbuf, j)\n i = skip_specific_character (strbuf, i, ck_'[')\n i = skip_whitespace (strbuf, i)\n j = skip_non_whitespace (strbuf, i)\n if (j == i) call bad_vm_assembly\n if (strbuf%chars(j - 1) == ck_']') j = j - 1\n allocate (arg_str, source = strbuf%to_unicode(i, j - 1))\n read (arg_str, *, iostat = stat) arg\n if (stat /= 0) call bad_vm_assembly\n call uint32_to_vm_bytes (arg, code%bytes, i_vm + 1)\n code%len = max (code%len, i_vm + 5)\n\n case (opcode_jmp, opcode_jz)\n call code%ensure_storage(i_vm + 5)\n code%bytes(i_vm) = achar (opcode)\n call code%ensure_storage(i_vm + 5)\n code%bytes(i_vm) = achar (opcode)\n i = skip_whitespace (strbuf, j)\n i = skip_specific_character (strbuf, i, ck_'(')\n i = skip_whitespace (strbuf, i)\n j = skip_non_whitespace (strbuf, i)\n if (j == i) call bad_vm_assembly\n if (strbuf%chars(j - 1) == ck_')') j = j - 1\n allocate (arg_str, source = strbuf%to_unicode(i, j - 1))\n read (arg_str, *, iostat = stat) arg\n if (stat /= 0) call bad_vm_assembly\n call int32_to_vm_bytes (arg, code%bytes, i_vm + 1)\n code%len = max (code%len, i_vm + 5)\n\n case default\n call code%ensure_storage(i_vm + 1)\n code%bytes(i_vm) = achar (opcode)\n code%len = max (code%len, i_vm + 1)\n end select\n\n end subroutine parse_instruction\n\n function skip_datasize_keyword (strbuf, i) result (j)\n type(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n integer(kind = nk) :: j\n\n j = skip_specific_character (strbuf, i, ck_'D')\n j = skip_specific_character (strbuf, j, ck_'a')\n j = skip_specific_character (strbuf, j, ck_'t')\n j = skip_specific_character (strbuf, j, ck_'a')\n j = skip_specific_character (strbuf, j, ck_'s')\n j = skip_specific_character (strbuf, j, ck_'i')\n j = skip_specific_character (strbuf, j, ck_'z')\n j = skip_specific_character (strbuf, j, ck_'e')\n end function skip_datasize_keyword\n\n function skip_strings_keyword (strbuf, i) result (j)\n type(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n integer(kind = nk) :: j\n\n j = skip_specific_character (strbuf, i, ck_'S')\n j = skip_specific_character (strbuf, j, ck_'t')\n j = skip_specific_character (strbuf, j, ck_'r')\n j = skip_specific_character (strbuf, j, ck_'i')\n j = skip_specific_character (strbuf, j, ck_'n')\n j = skip_specific_character (strbuf, j, ck_'g')\n j = skip_specific_character (strbuf, j, ck_'s')\n end function skip_strings_keyword\n\n function skip_specific_character (strbuf, i, ch) result (j)\n type(strbuf_t), intent(in) :: strbuf\n integer(kind = nk), intent(in) :: i\n character(1, kind = ck), intent(in) :: ch\n integer(kind = nk) :: j\n\n if (strbuf%length() < i) call bad_vm_assembly\n if (strbuf%chars(i) /= ch) call bad_vm_assembly\n j = i + 1\n end function skip_specific_character\n\n subroutine bad_vm_assembly\n write (error_unit, '(\"The input is not a correct virtual machine program.\")')\n stop 1\n end subroutine bad_vm_assembly\n\nend module vm_reader\n\nmodule vm_runner\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, non_intrinsic :: compiler_type_kinds\n use, non_intrinsic :: helpers\n use, non_intrinsic :: vm_reader\n\n implicit none\n private\n\n public :: run_vm\n\ncontains\n\n subroutine run_vm (outp, vm)\n integer, intent(in) :: outp\n type(vm_t), intent(inout) :: vm\n\n logical :: done\n integer :: opcode\n\n vm%sp = 0\n vm%pc = 0\n done = .false.\n do while (.not. done)\n if (vm%pc < 0 .or. vm%code%length() <= vm%pc) call pc_error\n opcode = iachar (vm%code%bytes(vm%pc))\n vm%pc = vm%pc + 1\n select case (opcode)\n case (opcode_nop)\n continue\n case (opcode_halt)\n done = .true.\n case (opcode_add)\n call alu_add (vm)\n case (opcode_sub)\n call alu_sub (vm)\n case (opcode_mul)\n call alu_mul (vm)\n case (opcode_div)\n call alu_div (vm)\n case (opcode_mod)\n call alu_mod (vm)\n case (opcode_lt)\n call alu_lt (vm)\n case (opcode_gt)\n call alu_gt (vm)\n case (opcode_le)\n call alu_le (vm)\n case (opcode_ge)\n call alu_ge (vm)\n case (opcode_eq)\n call alu_eq (vm)\n case (opcode_ne)\n call alu_ne (vm)\n case (opcode_and)\n call alu_and (vm)\n case (opcode_or)\n call alu_or (vm)\n case (opcode_neg)\n call alu_neg (vm)\n case (opcode_not)\n call alu_not (vm)\n case (opcode_prtc)\n call prtc (outp, vm)\n case (opcode_prti)\n call prti (outp, vm)\n case (opcode_prts)\n call prts (outp, vm)\n case (opcode_fetch)\n call fetch_int32 (vm)\n case (opcode_store)\n call store_int32 (vm)\n case (opcode_push)\n call push_int32 (vm)\n case (opcode_jmp)\n call jmp (vm)\n case (opcode_jz)\n call jz (vm)\n case default\n write (error_unit, '(\"VM opcode unrecognized: \", I0)') opcode\n stop 1\n end select\n end do\n end subroutine run_vm\n\n subroutine push_int32 (vm)\n type(vm_t), intent(inout) :: vm\n\n !\n ! Push the 32-bit integer data at pc to the stack, then increment\n ! pc by 4.\n !\n\n if (ubound (vm%stack, 1) < vm%sp) then\n write (error_unit, '(\"VM stack overflow\")')\n stop 1\n end if\n if (vm%code%length() <= vm%pc + 4) call pc_error\n vm%stack(vm%sp:(vm%sp + 3)) = vm%code%bytes(vm%pc:(vm%pc + 3))\n vm%sp = vm%sp + 4\n vm%pc = vm%pc + 4\n end subroutine push_int32\n\n subroutine fetch_int32 (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: i\n integer(kind = rik) :: x\n\n if (vm%code%length() <= vm%pc + 4) call pc_error\n call uint32_from_vm_bytes (i, vm%code%bytes, vm%pc)\n vm%pc = vm%pc + 4\n\n if (ubound (vm%data, 1) < i * 4) then\n write (error_unit, '(\"VM data access error\")')\n stop 1\n end if\n call int32_from_vm_bytes (x, vm%data, i * 4)\n\n if (ubound (vm%stack, 1) < vm%sp) then\n write (error_unit, '(\"VM stack overflow\")')\n stop 1\n end if\n call int32_to_vm_bytes (x, vm%stack, vm%sp)\n vm%sp = vm%sp + 4\n end subroutine fetch_int32\n\n subroutine store_int32 (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: i\n integer(kind = rik) :: x\n\n if (vm%code%length() <= vm%pc + 4) call pc_error\n call uint32_from_vm_bytes (i, vm%code%bytes, vm%pc)\n vm%pc = vm%pc + 4\n\n call ensure_there_is_enough_stack_data (vm, 4_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 4)\n vm%sp = vm%sp - 4\n\n if (ubound (vm%data, 1) < i * 4) then\n write (error_unit, '(\"VM data access error\")')\n stop 1\n end if\n call int32_to_vm_bytes (x, vm%data, i * 4)\n end subroutine store_int32\n\n subroutine jmp (vm)\n type(vm_t), intent(inout) :: vm\n\n !\n ! Add the 32-bit data at pc to pc itself.\n !\n\n integer(kind = rik) :: x\n\n if (vm%code%length() <= vm%pc + 4) call pc_error\n call int32_from_vm_bytes (x, vm%code%bytes, vm%pc)\n vm%pc = vm%pc + x\n end subroutine jmp\n\n subroutine jz (vm)\n type(vm_t), intent(inout) :: vm\n\n !\n ! Conditionally add the 32-bit data at pc to pc itself.\n !\n\n integer(kind = rik) :: x\n\n call ensure_there_is_enough_stack_data (vm, 4_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 4)\n vm%sp = vm%sp - 4\n if (x == 0) then\n if (vm%code%length() <= vm%pc + 4) call pc_error\n call int32_from_vm_bytes (x, vm%code%bytes, vm%pc)\n vm%pc = vm%pc + x\n else\n vm%pc = vm%pc + 4\n end if\n end subroutine jz\n\n subroutine alu_neg (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x\n\n call ensure_there_is_enough_stack_data (vm, 4_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 4)\n x = -x\n call int32_to_vm_bytes (x, vm%stack, vm%sp - 4)\n end subroutine alu_neg\n\n subroutine alu_not (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x\n\n call ensure_there_is_enough_stack_data (vm, 4_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 4)\n x = bool2int (x == 0_rik)\n call int32_to_vm_bytes (x, vm%stack, vm%sp - 4)\n end subroutine alu_not\n\n subroutine alu_add (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x, y, z\n\n call ensure_there_is_enough_stack_data (vm, 8_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 8)\n call int32_from_vm_bytes (y, vm%stack, vm%sp - 4)\n z = x + y\n call int32_to_vm_bytes (z, vm%stack, vm%sp - 8)\n vm%sp = vm%sp - 4\n end subroutine alu_add\n\n subroutine alu_sub (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x, y, z\n\n call ensure_there_is_enough_stack_data (vm, 8_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 8)\n call int32_from_vm_bytes (y, vm%stack, vm%sp - 4)\n z = x - y\n call int32_to_vm_bytes (z, vm%stack, vm%sp - 8)\n vm%sp = vm%sp - 4\n end subroutine alu_sub\n\n subroutine alu_mul (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x, y, z\n\n call ensure_there_is_enough_stack_data (vm, 8_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 8)\n call int32_from_vm_bytes (y, vm%stack, vm%sp - 4)\n z = x * y\n call int32_to_vm_bytes (z, vm%stack, vm%sp - 8)\n vm%sp = vm%sp - 4\n end subroutine alu_mul\n\n subroutine alu_div (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x, y, z\n\n call ensure_there_is_enough_stack_data (vm, 8_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 8)\n call int32_from_vm_bytes (y, vm%stack, vm%sp - 4)\n z = x / y ! This works like ‘/’ in C.\n call int32_to_vm_bytes (z, vm%stack, vm%sp - 8)\n vm%sp = vm%sp - 4\n end subroutine alu_div\n\n subroutine alu_mod (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x, y, z\n\n call ensure_there_is_enough_stack_data (vm, 8_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 8)\n call int32_from_vm_bytes (y, vm%stack, vm%sp - 4)\n z = mod (x, y) ! This works like ‘%’ in C.\n call int32_to_vm_bytes (z, vm%stack, vm%sp - 8)\n vm%sp = vm%sp - 4\n end subroutine alu_mod\n\n subroutine alu_lt (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x, y, z\n\n call ensure_there_is_enough_stack_data (vm, 8_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 8)\n call int32_from_vm_bytes (y, vm%stack, vm%sp - 4)\n z = bool2int (x < y)\n call int32_to_vm_bytes (z, vm%stack, vm%sp - 8)\n vm%sp = vm%sp - 4\n end subroutine alu_lt\n\n subroutine alu_gt (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x, y, z\n\n call ensure_there_is_enough_stack_data (vm, 8_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 8)\n call int32_from_vm_bytes (y, vm%stack, vm%sp - 4)\n z = bool2int (x > y)\n call int32_to_vm_bytes (z, vm%stack, vm%sp - 8)\n vm%sp = vm%sp - 4\n end subroutine alu_gt\n\n subroutine alu_le (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x, y, z\n\n call ensure_there_is_enough_stack_data (vm, 8_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 8)\n call int32_from_vm_bytes (y, vm%stack, vm%sp - 4)\n z = bool2int (x <= y)\n call int32_to_vm_bytes (z, vm%stack, vm%sp - 8)\n vm%sp = vm%sp - 4\n end subroutine alu_le\n\n subroutine alu_ge (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x, y, z\n\n call ensure_there_is_enough_stack_data (vm, 8_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 8)\n call int32_from_vm_bytes (y, vm%stack, vm%sp - 4)\n z = bool2int (x >= y)\n call int32_to_vm_bytes (z, vm%stack, vm%sp - 8)\n vm%sp = vm%sp - 4\n end subroutine alu_ge\n\n subroutine alu_eq (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x, y, z\n\n call ensure_there_is_enough_stack_data (vm, 8_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 8)\n call int32_from_vm_bytes (y, vm%stack, vm%sp - 4)\n z = bool2int (x == y)\n call int32_to_vm_bytes (z, vm%stack, vm%sp - 8)\n vm%sp = vm%sp - 4\n end subroutine alu_eq\n\n subroutine alu_ne (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x, y, z\n\n call ensure_there_is_enough_stack_data (vm, 8_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 8)\n call int32_from_vm_bytes (y, vm%stack, vm%sp - 4)\n z = bool2int (x /= y)\n call int32_to_vm_bytes (z, vm%stack, vm%sp - 8)\n vm%sp = vm%sp - 4\n end subroutine alu_ne\n\n subroutine alu_and (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x, y, z\n\n call ensure_there_is_enough_stack_data (vm, 8_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 8)\n call int32_from_vm_bytes (y, vm%stack, vm%sp - 4)\n z = bool2int (x /= 0 .and. y /= 0)\n call int32_to_vm_bytes (z, vm%stack, vm%sp - 8)\n vm%sp = vm%sp - 4\n end subroutine alu_and\n\n subroutine alu_or (vm)\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x, y, z\n\n call ensure_there_is_enough_stack_data (vm, 8_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 8)\n call int32_from_vm_bytes (y, vm%stack, vm%sp - 4)\n z = bool2int (x /= 0 .or. y /= 0)\n call int32_to_vm_bytes (z, vm%stack, vm%sp - 8)\n vm%sp = vm%sp - 4\n end subroutine alu_or\n\n subroutine ensure_there_is_enough_stack_data (vm, n)\n type(vm_t), intent(in) :: vm\n integer(kind = rik), intent(in) :: n\n\n if (vm%sp < n) then\n write (error_unit, '(\"VM stack underflow\")')\n stop 1\n end if\n end subroutine ensure_there_is_enough_stack_data\n\n subroutine prtc (outp, vm)\n integer, intent(in) :: outp\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x\n\n call ensure_there_is_enough_stack_data (vm, 4_rik)\n call uint32_from_vm_bytes (x, vm%stack, vm%sp - 4)\n write (outp, '(A1)', advance = 'no') char (x, kind = ck)\n vm%sp = vm%sp - 4\n end subroutine prtc\n\n subroutine prti (outp, vm)\n integer, intent(in) :: outp\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x\n\n call ensure_there_is_enough_stack_data (vm, 4_rik)\n call int32_from_vm_bytes (x, vm%stack, vm%sp - 4)\n write (outp, '(I0)', advance = 'no') x\n vm%sp = vm%sp - 4\n end subroutine prti\n\n subroutine prts (outp, vm)\n integer, intent(in) :: outp\n type(vm_t), intent(inout) :: vm\n\n integer(kind = rik) :: x\n integer(kind = rik) :: i, j\n\n call ensure_there_is_enough_stack_data (vm, 4_rik)\n call uint32_from_vm_bytes (x, vm%stack, vm%sp - 4)\n if (ubound (vm%string_boundaries, 1) - 1 < x) then\n write (error_unit, '(\"VM string boundary error\")')\n stop 1\n end if\n i = vm%string_boundaries(x)\n j = vm%string_boundaries(x + 1)\n write (outp, '(A)', advance = 'no') vm%strings((i + 1):j)\n vm%sp = vm%sp - 4\n end subroutine prts\n\n subroutine pc_error\n write (error_unit, '(\"VM program counter error\")')\n stop 1\n end subroutine pc_error\n\nend module vm_runner\n\nprogram vm\n use, intrinsic :: iso_fortran_env, only: input_unit\n use, intrinsic :: iso_fortran_env, only: output_unit\n use, intrinsic :: iso_fortran_env, only: error_unit\n use, non_intrinsic :: compiler_type_kinds\n use, non_intrinsic :: string_buffers\n use, non_intrinsic :: vm_reader\n use, non_intrinsic :: vm_runner\n\n implicit none\n\n integer, parameter :: inp_unit_no = 100\n integer, parameter :: outp_unit_no = 101\n\n integer :: arg_count\n character(200) :: arg\n integer :: inp\n integer :: outp\n\n arg_count = command_argument_count ()\n if (3 <= arg_count) then\n call print_usage\n else\n if (arg_count == 0) then\n inp = input_unit\n outp = output_unit\n else if (arg_count == 1) then\n call get_command_argument (1, arg)\n inp = open_for_input (trim (arg))\n outp = output_unit\n else if (arg_count == 2) then\n call get_command_argument (1, arg)\n inp = open_for_input (trim (arg))\n call get_command_argument (2, arg)\n outp = open_for_output (trim (arg))\n end if\n\n block\n type(strbuf_t) :: strbuf\n type(vm_t) :: vm\n\n call read_vm (inp, strbuf, vm)\n call run_vm (outp, vm)\n end block\n end if\n\ncontains\n\n function open_for_input (filename) result (unit_no)\n character(*), intent(in) :: filename\n integer :: unit_no\n\n integer :: stat\n\n open (unit = inp_unit_no, file = filename, status = 'old', &\n & action = 'read', access = 'stream', form = 'unformatted', &\n & iostat = stat)\n if (stat /= 0) then\n write (error_unit, '(\"Error: failed to open \", 1A, \" for input\")') filename\n stop 1\n end if\n unit_no = inp_unit_no\n end function open_for_input\n\n function open_for_output (filename) result (unit_no)\n character(*), intent(in) :: filename\n integer :: unit_no\n\n integer :: stat\n\n open (unit = outp_unit_no, file = filename, action = 'write', iostat = stat)\n if (stat /= 0) then\n write (error_unit, '(\"Error: failed to open \", 1A, \" for output\")') filename\n stop 1\n end if\n unit_no = outp_unit_no\n end function open_for_output\n\n subroutine print_usage\n character(200) :: progname\n\n call get_command_argument (0, progname)\n write (output_unit, '(\"Usage: \", 1A, \" [INPUT_FILE [OUTPUT_FILE]]\")') &\n & trim (progname)\n end subroutine print_usage\n\nend program vm\n", "language": "Fortran" }, { "code": "package main\n\nimport (\n \"bufio\"\n \"encoding/binary\"\n \"fmt\"\n \"log\"\n \"math\"\n \"os\"\n \"strconv\"\n \"strings\"\n)\n\ntype code = byte\n\nconst (\n fetch code = iota\n store\n push\n add\n sub\n mul\n div\n mod\n lt\n gt\n le\n ge\n eq\n ne\n and\n or\n neg\n not\n jmp\n jz\n prtc\n prts\n prti\n halt\n)\n\nvar codeMap = map[string]code{\n \"fetch\": fetch,\n \"store\": store,\n \"push\": push,\n \"add\": add,\n \"sub\": sub,\n \"mul\": mul,\n \"div\": div,\n \"mod\": mod,\n \"lt\": lt,\n \"gt\": gt,\n \"le\": le,\n \"ge\": ge,\n \"eq\": eq,\n \"ne\": ne,\n \"and\": and,\n \"or\": or,\n \"neg\": neg,\n \"not\": not,\n \"jmp\": jmp,\n \"jz\": jz,\n \"prtc\": prtc,\n \"prts\": prts,\n \"prti\": prti,\n \"halt\": halt,\n}\n\nvar (\n err error\n scanner *bufio.Scanner\n object []code\n stringPool []string\n)\n\nfunc reportError(msg string) {\n log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc btoi(b bool) int32 {\n if b {\n return 1\n }\n return 0\n}\n\nfunc itob(i int32) bool {\n if i != 0 {\n return true\n }\n return false\n}\n\nfunc emitByte(c code) {\n object = append(object, c)\n}\n\nfunc emitWord(n int) {\n bs := make([]byte, 4)\n binary.LittleEndian.PutUint32(bs, uint32(n))\n for _, b := range bs {\n emitByte(code(b))\n }\n}\n\n/*** Virtual Machine interpreter ***/\nfunc runVM(dataSize int) {\n stack := make([]int32, dataSize+1)\n pc := int32(0)\n for {\n op := object[pc]\n pc++\n switch op {\n case fetch:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n stack = append(stack, stack[x])\n pc += 4\n case store:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n ln := len(stack)\n stack[x] = stack[ln-1]\n stack = stack[:ln-1]\n pc += 4\n case push:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n stack = append(stack, x)\n pc += 4\n case add:\n ln := len(stack)\n stack[ln-2] += stack[ln-1]\n stack = stack[:ln-1]\n case sub:\n ln := len(stack)\n stack[ln-2] -= stack[ln-1]\n stack = stack[:ln-1]\n case mul:\n ln := len(stack)\n stack[ln-2] *= stack[ln-1]\n stack = stack[:ln-1]\n case div:\n ln := len(stack)\n stack[ln-2] = int32(float64(stack[ln-2]) / float64(stack[ln-1]))\n stack = stack[:ln-1]\n case mod:\n ln := len(stack)\n stack[ln-2] = int32(math.Mod(float64(stack[ln-2]), float64(stack[ln-1])))\n stack = stack[:ln-1]\n case lt:\n ln := len(stack)\n stack[ln-2] = btoi(stack[ln-2] < stack[ln-1])\n stack = stack[:ln-1]\n case gt:\n ln := len(stack)\n stack[ln-2] = btoi(stack[ln-2] > stack[ln-1])\n stack = stack[:ln-1]\n case le:\n ln := len(stack)\n stack[ln-2] = btoi(stack[ln-2] <= stack[ln-1])\n stack = stack[:ln-1]\n case ge:\n ln := len(stack)\n stack[ln-2] = btoi(stack[ln-2] >= stack[ln-1])\n stack = stack[:ln-1]\n case eq:\n ln := len(stack)\n stack[ln-2] = btoi(stack[ln-2] == stack[ln-1])\n stack = stack[:ln-1]\n case ne:\n ln := len(stack)\n stack[ln-2] = btoi(stack[ln-2] != stack[ln-1])\n stack = stack[:ln-1]\n case and:\n ln := len(stack)\n stack[ln-2] = btoi(itob(stack[ln-2]) && itob(stack[ln-1]))\n stack = stack[:ln-1]\n case or:\n ln := len(stack)\n stack[ln-2] = btoi(itob(stack[ln-2]) || itob(stack[ln-1]))\n stack = stack[:ln-1]\n case neg:\n ln := len(stack)\n stack[ln-1] = -stack[ln-1]\n case not:\n ln := len(stack)\n stack[ln-1] = btoi(!itob(stack[ln-1]))\n case jmp:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n pc += x\n case jz:\n ln := len(stack)\n v := stack[ln-1]\n stack = stack[:ln-1]\n if v != 0 {\n pc += 4\n } else {\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n pc += x\n }\n case prtc:\n ln := len(stack)\n fmt.Printf(\"%c\", stack[ln-1])\n stack = stack[:ln-1]\n case prts:\n ln := len(stack)\n fmt.Printf(\"%s\", stringPool[stack[ln-1]])\n stack = stack[:ln-1]\n case prti:\n ln := len(stack)\n fmt.Printf(\"%d\", stack[ln-1])\n stack = stack[:ln-1]\n case halt:\n return\n default:\n reportError(fmt.Sprintf(\"Unknown opcode %d\\n\", op))\n }\n }\n}\n\nfunc translate(s string) string {\n var d strings.Builder\n for i := 0; i < len(s); i++ {\n if s[i] == '\\\\' && (i+1) < len(s) {\n if s[i+1] == 'n' {\n d.WriteByte('\\n')\n i++\n } else if s[i+1] == '\\\\' {\n d.WriteByte('\\\\')\n i++\n }\n } else {\n d.WriteByte(s[i])\n }\n }\n return d.String()\n}\n\nfunc loadCode() int {\n var dataSize int\n firstLine := true\n for scanner.Scan() {\n line := strings.TrimRight(scanner.Text(), \" \\t\")\n if len(line) == 0 {\n if firstLine {\n reportError(\"empty line\")\n } else {\n break\n }\n }\n lineList := strings.Fields(line)\n if firstLine {\n dataSize, err = strconv.Atoi(lineList[1])\n check(err)\n nStrings, err := strconv.Atoi(lineList[3])\n check(err)\n for i := 0; i < nStrings; i++ {\n scanner.Scan()\n s := strings.Trim(scanner.Text(), \"\\\"\\n\")\n stringPool = append(stringPool, translate(s))\n }\n firstLine = false\n continue\n }\n offset, err := strconv.Atoi(lineList[0])\n check(err)\n instr := lineList[1]\n opCode, ok := codeMap[instr]\n if !ok {\n reportError(fmt.Sprintf(\"Unknown instruction %s at %d\", instr, opCode))\n }\n emitByte(opCode)\n switch opCode {\n case jmp, jz:\n p, err := strconv.Atoi(lineList[3])\n check(err)\n emitWord(p - offset - 1)\n case push:\n value, err := strconv.Atoi(lineList[2])\n check(err)\n emitWord(value)\n case fetch, store:\n value, err := strconv.Atoi(strings.Trim(lineList[2], \"[]\"))\n check(err)\n emitWord(value)\n }\n }\n check(scanner.Err())\n return dataSize\n}\n\nfunc main() {\n codeGen, err := os.Open(\"codegen.txt\")\n check(err)\n defer codeGen.Close()\n scanner = bufio.NewScanner(codeGen)\n runVM(loadCode())\n}\n", "language": "Go" }, { "code": "# -*- Icon -*-\n#\n# The Rosetta Code virtual machine in Icon. Migrated from the\n# ObjectIcon.\n#\n# See https://rosettacode.org/wiki/Compiler/virtual_machine_interpreter\n#\n\nrecord VirtualMachine(code, global_data, strings, stack, pc)\n\nglobal opcode_names\nglobal opcode_values\nglobal op_halt\nglobal op_add\nglobal op_sub\nglobal op_mul\nglobal op_div\nglobal op_mod\nglobal op_lt\nglobal op_gt\nglobal op_le\nglobal op_ge\nglobal op_eq\nglobal op_ne\nglobal op_and\nglobal op_or\nglobal op_neg\nglobal op_not\nglobal op_prtc\nglobal op_prti\nglobal op_prts\nglobal op_fetch\nglobal op_store\nglobal op_push\nglobal op_jmp\nglobal op_jz\n\nglobal whitespace_chars\n\nprocedure main(args)\n local f_inp, f_out\n local vm\n\n whitespace_chars := ' \\t\\n\\r\\f\\v'\n initialize_opcodes()\n\n if 3 <= *args then {\n write(\"Usage: \", &progname, \" [INPUT_FILE [OUTPUT_FILE]]\")\n exit(1)\n }\n\n if 1 <= *args then {\n f_inp := open(args[1], \"r\") | {\n write(&errout, \"Failed to open \", args[1], \" for reading.\")\n exit(1)\n }\n } else {\n f_inp := &input\n }\n\n if 2 <= *args then {\n f_out := open(args[2], \"w\") | {\n write(&errout, \"Failed to open \", args[2], \" for writing.\")\n exit(1)\n }\n } else {\n f_out := &output\n }\n\n vm := VirtualMachine()\n read_assembly_code(f_inp, vm)\n run_vm(f_out, vm)\nend\n\nprocedure initialize_opcodes()\n local i\n\n opcode_names :=\n [\"halt\", \"add\", \"sub\", \"mul\", \"div\",\n \"mod\", \"lt\", \"gt\", \"le\", \"ge\",\n \"eq\", \"ne\", \"and\", \"or\", \"neg\",\n \"not\", \"prtc\", \"prti\", \"prts\", \"fetch\",\n \"store\", \"push\", \"jmp\", \"jz\"]\n\n opcode_values := table()\n every i := 1 to *opcode_names do\n opcode_values[opcode_names[i]] := char(i)\n\n op_halt := opcode_values[\"halt\"]\n op_add := opcode_values[\"add\"]\n op_sub := opcode_values[\"sub\"]\n op_mul := opcode_values[\"mul\"]\n op_div := opcode_values[\"div\"]\n op_mod := opcode_values[\"mod\"]\n op_lt := opcode_values[\"lt\"]\n op_gt := opcode_values[\"gt\"]\n op_le := opcode_values[\"le\"]\n op_ge := opcode_values[\"ge\"]\n op_eq := opcode_values[\"eq\"]\n op_ne := opcode_values[\"ne\"]\n op_and := opcode_values[\"and\"]\n op_or := opcode_values[\"or\"]\n op_neg := opcode_values[\"neg\"]\n op_not := opcode_values[\"not\"]\n op_prtc := opcode_values[\"prtc\"]\n op_prti := opcode_values[\"prti\"]\n op_prts := opcode_values[\"prts\"]\n op_fetch := opcode_values[\"fetch\"]\n op_store := opcode_values[\"store\"]\n op_push := opcode_values[\"push\"]\n op_jmp := opcode_values[\"jmp\"]\n op_jz := opcode_values[\"jz\"]\nend\n\nprocedure int2bytes (n)\n local bytes\n\n # The VM is little-endian.\n\n bytes := \"****\"\n bytes[1] := char (iand(n, 16rFF))\n bytes[2] := char(iand(ishift(n, -8), 16rFF))\n bytes[3] := char(iand(ishift(n, -16), 16rFF))\n bytes[4] := char(iand(ishift(n, -24), 16rFF))\n return bytes\nend\n\nprocedure bytes2int(bytes, i)\n local n0, n1, n2, n3, n\n\n # The VM is little-endian.\n\n n0 := ord(bytes[i])\n n1 := ishift(ord(bytes[i + 1]), 8)\n n2 := ishift(ord(bytes[i + 2]), 16)\n n3 := ishift(ord(bytes[i + 3]), 24)\n n := ior (n0, ior (n1, ior (n2, n3)))\n\n # Do not forget to extend the sign bit.\n return (if n3 <= 16r7F then n else ior(n, icom(16rFFFFFFFF)))\nend\n\nprocedure read_assembly_code(f, vm)\n local data_size, number_of_strings\n local line, ch\n local i\n local address\n local opcode\n\n # Read the header line.\n line := read(f) | bad_vm()\n line ? {\n tab(many(whitespace_chars))\n tab(match(\"Datasize\")) | bad_vm()\n tab(many(whitespace_chars))\n tab(any(':')) | bad_vm()\n tab(many(whitespace_chars))\n data_size :=\n integer(tab(many(&digits))) | bad_vm()\n tab(many(whitespace_chars))\n tab(match(\"Strings\")) | bad_vm()\n tab(many(whitespace_chars))\n tab(any(':')) | bad_vm()\n tab(many(whitespace_chars))\n number_of_strings :=\n integer(tab(many(&digits))) | bad_vm()\n }\n\n # Read the strings.\n vm.strings := list(number_of_strings)\n every i := 1 to number_of_strings do {\n vm.strings[i] := \"\"\n line := read(f) | bad_vm()\n line ? {\n tab(many(whitespace_chars))\n tab(any('\"')) | bad_vm()\n while ch := tab(any(~'\"')) do {\n if ch == '\\\\' then {\n ch := tab(any('n\\\\')) | bad_vm()\n vm.strings[i] ||:=\n (if (ch == \"n\") then \"\\n\" else \"\\\\\")\n } else {\n vm.strings[i] ||:= ch\n }\n }\n }\n }\n\n # Read the code.\n vm.code := \"\"\n while line := read(f) do {\n line ? {\n tab(many(whitespace_chars))\n address := integer(tab(many(&digits))) | bad_vm()\n tab(many(whitespace_chars))\n opcode := tab(many(~whitespace_chars)) | bad_vm()\n vm.code ||:= opcode_values[opcode]\n case opcode of {\n \"push\": {\n tab(many(whitespace_chars))\n vm.code ||:=\n int2bytes(integer(tab(many(&digits)))) |\n int2bytes(integer(tab(any('-')) ||\n tab(many(&digits)))) |\n bad_vm()\n }\n \"fetch\" | \"store\": {\n tab(many(whitespace_chars))\n tab(any('[')) | bad_vm()\n tab(many(whitespace_chars))\n vm.code ||:=\n int2bytes(integer(tab(many(&digits)))) |\n bad_vm()\n tab(many(whitespace_chars))\n tab(any(']')) | bad_vm()\n }\n \"jmp\" | \"jz\": {\n tab(many(whitespace_chars))\n tab(any('(')) | bad_vm()\n tab(many(whitespace_chars))\n vm.code ||:=\n int2bytes(integer(tab(many(&digits)))) |\n int2bytes(integer(tab(any('-')) ||\n tab(many(&digits)))) |\n bad_vm()\n tab(many(whitespace_chars))\n tab(any(')')) | bad_vm()\n tab(many(whitespace_chars))\n tab(many(&digits)) | bad_vm()\n }\n default: {\n # Do nothing\n }\n }\n }\n }\n\n # Create a global data area.\n vm.global_data := list(data_size, &null)\n\n initialize_vm(vm)\nend\n\nprocedure run_vm(f_out, vm)\n initialize_vm(vm)\n continue_vm(f_out, vm)\nend\n\nprocedure continue_vm(f_out, vm)\n while vm.code[vm.pc] ~== op_halt do\n step_vm(f_out, vm)\nend\n\nprocedure step_vm(f_out, vm)\n local opcode\n\n opcode := vm.code[vm.pc]\n vm.pc +:= 1\n case opcode of {\n op_add: binop(vm, \"+\")\n op_sub: binop(vm, \"-\")\n op_mul: binop(vm, \"*\")\n op_div: binop(vm, \"/\")\n op_mod: binop(vm, \"%\")\n op_lt: comparison(vm, \"<\")\n op_gt: comparison(vm, \">\")\n op_le: comparison(vm, \"<=\")\n op_ge: comparison(vm, \">=\")\n op_eq: comparison(vm, \"=\")\n op_ne: comparison(vm, \"~=\")\n op_and: logical_and(vm)\n op_or: logical_or(vm)\n op_neg: negate(vm)\n op_not: logical_not(vm)\n op_prtc: printc(f_out, vm)\n op_prti: printi(f_out, vm)\n op_prts: prints(f_out, vm)\n op_fetch: fetch_global(vm)\n op_store: store_global(vm)\n op_push: push_argument(vm)\n op_jmp: jump(vm)\n op_jz: jump_if_zero(vm)\n default: bad_opcode()\n }\nend\n\nprocedure negate(vm)\n vm.stack[1] := -vm.stack[1]\nend\n\nprocedure binop(vm, func)\n vm.stack[2] := func(vm.stack[2], vm.stack[1])\n pop(vm.stack)\nend\n\nprocedure comparison(vm, func)\n vm.stack[2] := (if func(vm.stack[2], vm.stack[1]) then 1 else 0)\n pop(vm.stack)\nend\n\nprocedure logical_and(vm)\n vm.stack[2] :=\n (if vm.stack[2] ~= 0 & vm.stack[1] ~= 0 then 1 else 0)\n pop(vm.stack)\nend\n\nprocedure logical_or(vm)\n vm.stack[2] :=\n (if vm.stack[2] ~= 0 | vm.stack[1] ~= 0 then 1 else 0)\n pop(vm.stack)\nend\n\nprocedure logical_not(vm)\n vm.stack[1] := (if vm.stack[1] ~= 0 then 0 else 1)\nend\n\nprocedure printc(f_out, vm)\n writes(f_out, char(pop(vm.stack)))\nend\n\nprocedure printi(f_out, vm)\n writes(f_out, pop(vm.stack))\nend\n\nprocedure prints(f_out, vm)\n writes(f_out, vm.strings[pop(vm.stack) + 1])\nend\n\nprocedure fetch_global(vm)\n push(vm.stack, vm.global_data[get_argument(vm) + 1])\n vm.pc +:= 4\nend\n\nprocedure store_global(vm)\n vm.global_data[get_argument(vm) + 1] := pop(vm.stack)\n vm.pc +:= 4\nend\n\nprocedure push_argument(vm)\n push(vm.stack, get_argument(vm))\n vm.pc +:= 4\nend\n\nprocedure jump(vm)\n vm.pc +:= get_argument(vm)\nend\n\nprocedure jump_if_zero(vm)\n if pop(vm.stack) = 0 then\n vm.pc +:= get_argument(vm)\n else\n vm.pc +:= 4\nend\n\nprocedure get_argument(vm)\n return bytes2int(vm.code, vm.pc)\nend\n\nprocedure initialize_vm(vm)\n # The program counter starts at 1, for convenient indexing into\n # the code[] array. Icon indexing starts at 1 (for a *very* good\n # reason, but that’s a topic for another day).\n vm.pc := 1\n vm.stack := []\nend\n\nprocedure bad_vm()\n write(&errout, \"Bad VM.\")\n exit(1)\nend\n\nprocedure bad_opcode()\n write(&errout, \"Bad opcode.\")\n exit(1)\nend\n", "language": "Icon" }, { "code": "(opcodes)=: opcodes=: ;:{{)n\n fetch store push add sub mul div mod lt gt le ge\n eq ne and or neg not jmp jz prtc prts prti halt\n}}-.LF\n\nunpack=: {{\n lines=. <;._2 y\n 'ds0 ds s0 s'=.;:0{::lines\n assert.'Datasize:Strings:'-:ds0,s0\n vars=: (\".ds)#0\n strings=: rplc&('\\\\';'\\';'\\n';LF)L:0 '\"'-.L:0~(1+i.\".s){lines\n object=: ;xlate L:1 (;:'()[]') -.~L:1 ;:L:0 '-_' rplc~L:0 (1+\".s)}.lines\n outbuf=: stack=: i.0\n}}\n\nxlate=: {{\n if.2<#y do.\n (opcodes i. 1{y),(4#256)#:\".2{::y\n else.\n opcodes i. 1{y\n end.\n}}\n\nNB. ensure we maintain 32 bit signed int representation\nsignadj=: _2147483648+4294967296|2147483648+]\ngetint=: signadj@(256 #. ])\n\nPUSH=: {{ stack=:stack,signadj y }}\nPOP=: {{ (stack=: _1 }. stack) ] _1 { stack }}\nPOP2=: {{ (stack=: _2 }. stack) ] _2 {. stack }}\nemit=:{{\n outbuf=: outbuf,y\n if.LF e. outbuf do.\n ndx=. outbuf i:LF\n echo ndx{.outbuf\n outbuf=: }.ndx}.outbuf\n end.\n}}\n\nrun_vm=: {{\n unpack y\n stack=: i.pc=:0\n lim=. <:#object\n while.do.\n pc=: pc+1 [ op=: (pc { object){opcodes\n i=. getint (lim<.pc+i.4) { object\n k=. 0\n select.op\n case.fetch do. k=.4 [PUSH i{vars\n case.store do. k=.4 [vars=: (POP'') i} vars\n case.push do. k=.4 [PUSH i\n case.add do. PUSH +/POP2''\n case.sub do. PUSH -/POP2''\n case.mul do. PUSH */POP2''\n case.div do. PUSH<.%/POP2''\n case.mod do. PUSH |~/POP2''\n case.lt do. PUSH </POP2''\n case.le do. PUSH <:/POP2''\n case.eq do. PUSH =/POP2''\n case.ne do. PUSH ~:/POP2''\n case.ge do. PUSH >:/POP2''\n case.gt do. PUSH >/POP2''\n case.and do. PUSH */0~:POP2''\n case.or do. PUSH +./0~:POP2''\n case.neg do. PUSH -POP''\n case.not do. PUSH 0=POP''\n case.jmp do. k=. i\n case.jz do. k=. (0=POP''){4,i\n case.prtc do. emit u:POP''\n case.prts do. emit (POP''){::strings\n case.prti do. emit rplc&'_-'\":POP''\n case.halt do. if.#outbuf do.echo outbuf end.EMPTY return.\n end.\n pc=: pc+k\n end.\n}}\n", "language": "J" }, { "code": "count=:{{)n\ncount = 1;\nwhile (count < 10) {\n print(\"count is: \", count, \"\\n\");\n count = count + 1;\n}\n}}\n\n run_vm gen syntax lex count\ncount is: 1\ncount is: 2\ncount is: 3\ncount is: 4\ncount is: 5\ncount is: 6\ncount is: 7\ncount is: 8\ncount is: 9\n", "language": "J" }, { "code": "mutable struct VM32\n code::Vector{UInt8}\n stack::Vector{Int32}\n data::Vector{Int32}\n strings::Vector{String}\n offsets::Vector{Int32}\n lastargs::Vector{Int32}\n ip::Int32\n VM32() = new(Vector{UInt8}(), Vector{Int32}(), Vector{Int32}(),\n Vector{String}(), Vector{Int32}(), Vector{Int32}(), 1)\nend\n\nhalt, add, sub, mul, Div, mod, not, neg, and, or, lt, gt, le, ge, ne, eq, prts,\n prti, prtc, store, Fetch, push, jmp, jz = UInt8.(collect(1:24))\n\nfunction assemble(io)\n vm = VM32()\n header = readline(io)\n datasize, nstrings = match(r\"\\w+:\\s*(\\d+)\\s+\\w+:\\s*(\\d+)\", header).captures\n vm.data = zeros(Int32, parse(Int, datasize) + 4)\n for i in 1:parse(Int, nstrings)\n line = replace(strip(readline(io), ['\"', '\\n']), r\"\\\\.\" => x -> x[end] == 'n' ? \"\\n\" : string(x[end]))\n push!(vm.strings, line)\n end\n while !eof(io)\n line = readline(io)\n offset, op, arg1, arg2 = match(r\"(\\d+)\\s+(\\w+)\\s*(\\S+)?\\s*(\\S+)?\", line).captures\n op = op in [\"fetch\", \"div\"] ? uppercasefirst(op) : op\n push!(vm.code, eval(Symbol(op)))\n if arg1 != nothing\n v = parse(Int32, strip(arg1, ['[', ']', '(', ')']))\n foreach(x -> push!(vm.code, x), reinterpret(UInt8, [v]))\n end\n if arg2 != nothing\n push!(vm.lastargs, (x = tryparse(Int32, arg2)) == nothing ? 0 : x)\n end\n push!(vm.offsets, parse(Int32, offset))\n end\n vm\nend\n\nfunction runvm(vm)\n value() = (x = vm.ip; vm.ip += 4; reinterpret(Int32, vm.code[x:x+3])[1])\n tobool(x) = (x != 0)\n ops = Dict(\n halt => () -> exit(),\n add => () -> begin vm.stack[end-1] += vm.stack[end]; pop!(vm.stack); vm.stack[end] end,\n sub => () -> begin vm.stack[end-1] -= vm.stack[end]; pop!(vm.stack); vm.stack[end] end,\n mul => () -> begin vm.stack[end-1] *= vm.stack[end]; pop!(vm.stack); vm.stack[end] end,\n Div => () -> begin vm.stack[end-1] /= vm.stack[end]; pop!(vm.stack); vm.stack[end] end,\n mod => () -> begin vm.stack[end-1] %= vm.stack[1]; pop!(vm.stack); vm.stack[end] end,\n not => () -> vm.stack[end] = vm.stack[end] ? 0 : 1,\n neg => () -> vm.stack[end] = -vm.stack[end],\n and => () -> begin vm.stack[end-1] = tobool(vm.stack[end-1]) && tobool(vm.stack[end]) ? 1 : 0; pop!(vm.stack); vm.stack[end] end,\n or => () -> begin vm.stack[end-1] = tobool(vm.stack[end-1]) || tobool(vm.stack[end]) ? 1 : 0; pop!(vm.stack); vm.stack[end] end,\n lt => () -> begin x = (vm.stack[end-1] < vm.stack[end] ? 1 : 0); pop!(vm.stack); vm.stack[end] = x end,\n gt => () -> begin x = (vm.stack[end-1] > vm.stack[end] ? 1 : 0); pop!(vm.stack); vm.stack[end] = x end,\n le => () -> begin x = (vm.stack[end-1] <= vm.stack[end] ? 1 : 0); pop!(vm.stack); vm.stack[end] = x end,\n ge => () -> begin x = (vm.stack[end-1] >= vm.stack[end] ? 1 : 0); pop!(vm.stack); vm.stack[end] = x end,\n ne => () -> begin x = (vm.stack[end-1] != vm.stack[end] ? 1 : 0); pop!(vm.stack); vm.stack[end] = x end,\n eq => () -> begin x = (vm.stack[end-1] == vm.stack[end] ? 1 : 0); pop!(vm.stack); vm.stack[end] = x end,\n prts => () -> print(vm.strings[pop!(vm.stack) + 1]),\n prti => () -> print(pop!(vm.stack)),\n prtc => () -> print(Char(pop!(vm.stack))),\n store => () -> vm.data[value() + 1] = pop!(vm.stack),\n Fetch => () -> push!(vm.stack, vm.data[value() + 1]),\n push => () -> push!(vm.stack, value()),\n jmp => () -> vm.ip += value(),\n jz => () -> if pop!(vm.stack) == 0 vm.ip += value() else vm.ip += 4 end)\n vm.ip = 1\n while true\n op = vm.code[vm.ip]\n vm.ip += 1\n ops[op]()\n end\nend\n\nconst testasm = \"\"\"\nDatasize: 1 Strings: 2\n\"count is: \"\n\"\\\\n\"\n 0 push 1\n 5 store [0]\n 10 fetch [0]\n 15 push 10\n 20 lt\n 21 jz (43) 65\n 26 push 0\n 31 prts\n 32 fetch [0]\n 37 prti\n 38 push 1\n 43 prts\n 44 fetch [0]\n 49 push 1\n 54 add\n 55 store [0]\n 60 jmp (-51) 10\n 65 halt \"\"\"\n\nconst iob = IOBuffer(testasm)\nconst vm = assemble(iob)\nrunvm(vm)\n", "language": "Julia" }, { "code": "Module Virtual_Machine_Interpreter (a$){\n\t\\\\ function to extract string, replacing escape codes.\n\tFunction GetString$(a$) {\n\t\ts=instr(a$, chr$(34))\n\t\tm=rinstr(a$,chr$(34))-s\n\t\tif m>1 then\n\t\t\t\\\\ process escape codes\n\t\t\t=format$(mid$(a$, s+1, m-1))\n\t\telse\n\t\t\t=\"\"\n\t\tend if\n\t}\n\t\\\\ module to print a string to console using codes, 13, 10, 9\n\tModule printsrv (a$) {\n\t\tfor i=1 to len(a$)\n\t\t\tselect case chrcode(Mid$(a$,i,1))\n\t\t\tcase 13\n\t\t\t\tcursor 0\n\t\t\tcase 10\n\t\t\t\tcursor 0 : Print\n\t\t\tcase 9\n\t\t\t\tcursor ((pos+tab) div tab)*tab\n\t\t\telse case\n\t\t\t{\n\t\t\t\tm=pos :if pos>=width then Print : m=pos\n\t\t\t\tPrint Mid$(a$,i,1);\n\t\t\t\tif m<=width then cursor m+1\n\t\t\t}\n\t\t\tend select\n\t\tnext i\n\t}\n\tconst nl$=chr$(13)+chr$(10)\n\t\\\\ we can set starting value to any number n where 0<=n<=232\n\tenum op {\thalt_=232, add_, sub_, mul_, div_, mod_, not_, neg_, and_, or_, lt_,\n\t\t \tgt_, le_, ge_, ne_, eq_, prts_, prti_, prtc_, store_, fetch_, push_,\n\t\t\tjmp_, jz_\n \t}\n\tRem : Form 120, 60 ' change console width X height to run Ascii Mandlebrot examlpe\n\tReport \"Virtual Assembly Code:\"+{\n\t}+a$\n\tPrint \"Prepare Byte Code\"\n\t\n\t\\\\ get datasize\n\ta$=rightpart$(a$, \"Datasize:\")\n\tm=0\n\tdata_size=val(a$, \"int\", m)\n\ta$=mid$(a$, m)\n\t\\\\ make stack\n\tif data_size>0 then Buffer Clear stack_ as long*data_size\n\t\\\\ dim or redim buffer append 1000 long as is.\n\tBuffer stack_ as long*(1000+data_size)\n\t\\\\ get strings\n\ta$=rightpart$(a$, \"Strings:\")\n\tm=0\n\tstrings=val(a$, \"int\", m)\n\ta$=rightpart$(a$, nl$)\n\t\n\tif strings>0 then\n\t\tDim strings$(strings)\n\t\tfor i=0 to strings-1\n\t\t\tstrings$(i)=GetString$(leftpart$(a$, nl$))\n\t\t\ta$=rightpart$(a$, nl$)\n\t\tNext i\n\tEnd if\n\tbuffer clear code_ as byte*1000\n\tdo\n\t\tm=0\n\t\toffset=val(a$,\"int\", m)\n\t\tif m<0 then exit\n\t\ta$=mid$(a$,m)\n\t\tline$=trim$(leftpart$(a$,nl$))\n\t\tif line$=\"\" then line$=trim$(a$) else a$=trim$(rightpart$(a$, nl$))\n\t\top$=if$(instr(line$,\" \")>0->leftpart$(line$,\" \"), line$)\n\t\tif not valid(eval(op$+\"_\")) then exit\n\t\topc=eval(op$+\"_\")\n\t\tReturn code_, offset:=opc\n\t\tif opc>=store_ then\n\t\t\tline$=rightpart$(line$,\" \")\n\t\t\tselect case opc\n\t\t\tcase store_, fetch_\n\t\t\t\tReturn code_, offset+1:=val(rightpart$(leftpart$(line$,\"]\"),\"[\")) as long : offset+=4\n\t\t\tcase push_\n\t\t\t\tReturn code_, offset+1:=uint(val(line$)) as long : offset+=4\n\t\t\tcase jz_, jmp_\n\t\t\t\tReturn code_, offset+1:=val(rightpart$(line$,\")\")) as long : offset+=4\n\t\t\tend select\n\t\tend if\n\tAlways\n\tPrint \"Press any key\" : Push key$ : Drop\n\t\\\\ Prepare VM\n\tlet pc=0, sp=len(stack_) div 4\n\tdo {\n\t\tfunc=eval(code_, pc)\n\t\tpc++\n\t\tselect case func\n\t\tcase halt_\n\t\t\texit\n\t\tcase push_\n\t\t\tsp--:return stack_, sp:=eval(code_, pc as long):pc+=4\n\t\tcase jz_\n\t\t\tsp++: if eval(stack_, sp-1)=0 then pc=eval(code_, pc as long) else pc+=4\n\t\tcase jmp_\n\t\t\tpc=eval(code_, pc as long)\n\t\tcase fetch_\n\t\t\tsp--:Return stack_, sp:=eval(stack_, eval(code_, pc as long)):pc+=4\n\t\tcase store_\n\t\t\tReturn stack_, eval(code_, pc as long):=eval(stack_, sp):sp++:pc+=4\n\t\tcase add_\n\t\t\tReturn stack_, sp+1:=uint(sint(eval(stack_, sp+1))+sint(eval(stack_, sp))):sp++\n\t\tcase sub_\n\t\t\tReturn stack_, sp+1:=uint(sint(eval(stack_, sp+1))-sint(eval(stack_, sp))):sp++\n\t\tcase mul_\n\t\t\tReturn stack_, sp+1:=uint(sint(eval(stack_, sp+1))*sint(eval(stack_, sp))):sp++\n\t\tcase div_\n\t\t\tReturn stack_, sp+1:=uint(sint(eval(stack_, sp+1)) div sint(eval(stack_, sp))):sp++\n\t\tcase mod_\n\t\t\tReturn stack_, sp+1:=uint(sint(eval(stack_, sp+1)) mod sint(eval(stack_, sp))) :sp++\n\t\tcase not_\n\t\t\tReturn stack_, sp:=if(eval(stack_, sp)=0->uint(-1),0)\n\t\tcase neg_ \\\\ we can use neg(sint(value))+1 or uint(-sint(value))\n\t\t\tReturn stack_, sp:=uint(-sint(eval(stack_, sp)))\n\t\tcase and_\n\t\t\tReturn stack_, sp+1:=binary.and(eval(stack_, sp+1),eval(stack_, sp)):sp++\t\n\t\tcase or_\n\t\t\tReturn stack_, sp+1:=binary.or(eval(stack_, sp+1),eval(stack_, sp)):sp++\t\n\t\tcase lt_\n\t\t\tReturn stack_, sp+1:=uint(if(sint(eval(stack_, sp+1))<sint(eval(stack_, sp))->-1, 0)):sp++\n\t\tcase gt_\n\t\t\tReturn stack_, sp+1:=uint(if(sint(eval(stack_, sp+1))>sint(eval(stack_, sp))->-1, 0)):sp++\n\t\tcase le_\n\t\t\tReturn stack_, sp+1:=uint(if(sint(eval(stack_, sp+1))<=sint(eval(stack_, sp))->-1, 0)):sp++\n\t\tcase ge_\n\t\t\tReturn stack_, sp+1:=uint(if(sint(eval(stack_, sp+1))>=sint(eval(stack_, sp))->-1, 0)):sp++\n\t\tcase ne_\n\t\t\tReturn stack_, sp+1:=uint(if(eval(stack_, sp+1)<>eval(stack_, sp)->-1, 0)):sp++\n\t\tcase eq_\n\t\t\tReturn stack_, sp+1:=uint(if(eval(stack_, sp+1)=eval(stack_, sp)->-1, 0)):sp++\n\t\tcase prts_\n\t\t\tprintsrv strings$(eval(stack_,sp)):sp++\n\t\tcase prti_\n\t\t\tprintsrv str$(sint(eval(stack_,sp)),0):sp++\n\t\tcase prtc_\n\t\t\tprintsrv chrcode$(eval(stack_,sp)):sp++\n\t\telse case\n\t\t\tError \"Unkown op \"+str$(func)\n\t\tend select\t\t\t\n\t} always\n\tPrint \"done\"\n}\nVirtual_Machine_Interpreter {\nDatasize: 1 Strings: 2\n\"count is: \"\n\"\\n\"\n 0 push 1\n 5 store [0]\n 10 fetch [0]\n 15 push 10\n 20 lt\n 21 jz (43) 65\n 26 push 0\n 31 prts\n 32 fetch [0]\n 37 prti\n 38 push 1\n 43 prts\n 44 fetch [0]\n 49 push 1\n 54 add\n 55 store [0]\n 60 jmp (-51) 10\n 65 halt\n}\n", "language": "M2000-Interpreter" }, { "code": "Module Virtual_Machine_Interpreter (a$){\n\t\\\\ function to extract string, replacing escape codes.\n\tFunction GetString$(a$) {\n\t\ts=instr(a$, chr$(34))\n\t\tm=rinstr(a$,chr$(34))-s\n\t\tif m>1 then\n\t\t\t\\\\ process escape codes\n\t\t\t=format$(mid$(a$, s+1, m-1))\n\t\telse\n\t\t\t=\"\"\n\t\tend if\n\t}\n\t\\\\ module to print a string to console using codes, 13, 10, 9\n\tModule printsrv (a$) {\n\t\tfor i=1 to len(a$)\n\t\t\tselect case chrcode(Mid$(a$,i,1))\n\t\t\tcase 13\n\t\t\t\tcursor 0\n\t\t\tcase 10\n\t\t\t\tcursor 0 : Print\n\t\t\tcase 9\n\t\t\t\tcursor ((pos+tab) div tab)*tab\n\t\t\telse case\n\t\t\t{\n\t\t\t\tm=pos :if pos>=width then Print : m=pos\n\t\t\t\tPrint Mid$(a$,i,1);\n\t\t\t\tif m<=width then cursor m+1\n\t\t\t}\n\t\t\tend select\n\t\tnext i\n\t}\n\tconst nl$=chr$(13)+chr$(10)\n\t\\\\ we can set starting value to any number n where 0<=n<=232\n\tenum op {\thalt_=232, add_, sub_, mul_, div_, mod_, not_, neg_, and_, or_, lt_,\n\t\t \tgt_, le_, ge_, ne_, eq_, prts_, prti_, prtc_, store_, fetch_, push_,\n\t\t\tjmp_, jz_\n \t}\n \texit_now=false\n\tInventory func=halt_:=lambda->{exit_now=true}\n\tAppend func, push_:=lambda->{sp--:return stack_, sp:=eval(code_, pc as long):pc+=4}\n\tAppend func, jz_:=lambda->{\n\t\tsp++: if eval(stack_, sp-1)=0 then pc=eval(code_, pc as long) else pc+=4\n\t}\n\tAppend func, jmp_:=lambda->{pc=eval(code_, pc as long)}\n\tAppend func, fetch_:=lambda->{sp--:Return stack_, sp:=eval(stack_, eval(code_, pc as long)):pc+=4}\n\tAppend func, store_:=lambda->{Return stack_, eval(code_, pc as long):=eval(stack_, sp):sp++:pc+=4}\n\tAppend func, add_:=lambda->{Return stack_, sp+1:=uint(sint(eval(stack_, sp+1))+sint(eval(stack_, sp))):sp++}\n\tAppend func, sub_:=lambda->{Return stack_, sp+1:=uint(sint(eval(stack_, sp+1))-sint(eval(stack_, sp))):sp++}\n\tAppend func, mul_:=lambda->{Return stack_, sp+1:=uint(sint(eval(stack_, sp+1))*sint(eval(stack_, sp))):sp++}\n\tAppend func, div_:=lambda->{Return stack_, sp+1:=uint(sint(eval(stack_, sp+1)) div sint(eval(stack_, sp))):sp++}\n\tAppend func, mod_:=lambda->{Return stack_, sp+1:=uint(sint(eval(stack_, sp+1)) mod sint(eval(stack_, sp))) :sp++}\n\tAppend func, not_:=lambda->{Return stack_, sp:=if(eval(stack_, sp)=0->uint(-1),0)}\n\tAppend func, neg_:=lambda->{Return stack_, sp:=uint(-sint(eval(stack_, sp)))}\n\tAppend func, and_:=lambda->{Return stack_, sp+1:=binary.and(eval(stack_, sp+1),eval(stack_, sp)):sp++\t}\n\tAppend func, or_:=lambda->{Return stack_, sp+1:=binary.or(eval(stack_, sp+1),eval(stack_, sp)):sp++\t}\n\tAppend func, lt_:=lambda->{Return stack_, sp+1:=uint(if(sint(eval(stack_, sp+1))<sint(eval(stack_, sp))->-1, 0)):sp++}\n\tAppend func, gt_:=lambda->{Return stack_, sp+1:=uint(if(sint(eval(stack_, sp+1))>sint(eval(stack_, sp))->-1, 0)):sp++}\n\tAppend func, le_:=lambda->{Return stack_, sp+1:=uint(if(sint(eval(stack_, sp+1))<=sint(eval(stack_, sp))->-1, 0)):sp++}\n\tAppend func, ge_:=lambda->{Return stack_, sp+1:=uint(if(sint(eval(stack_, sp+1))>=sint(eval(stack_, sp))->-1, 0)):sp++}\n\tAppend func, ne_:=lambda->{Return stack_, sp+1:=uint(if(eval(stack_, sp+1)<>eval(stack_, sp)->-1, 0)):sp++}\n\tAppend func, eq_:=lambda->{Return stack_, sp+1:=uint(if(eval(stack_, sp+1)=eval(stack_, sp)->-1, 0)):sp++}\n\tAppend func, prts_:=lambda->{printsrv strings$(eval(stack_,sp)):sp++}\n\tAppend func, prti_:=lambda->{printsrv str$(sint(eval(stack_,sp)),0):sp++}\n\tAppend func, prtc_:=lambda->{printsrv chrcode$(eval(stack_,sp)):sp++}\n\tRem : Form 120, 60 ' change console width X height to run Ascii Mandlebrot examlpe\n\tReport \"Virtual Assembly Code:\"+{\n\t}+a$\n\tPrint \"Prepare Byte Code\"\n\n\t\\\\ get datasize\n\ta$=rightpart$(a$, \"Datasize:\")\n\tm=0\n\tdata_size=val(a$, \"int\", m)\n\ta$=mid$(a$, m)\n\t\\\\ make stack\n\tif data_size>0 then Buffer Clear stack_ as long*data_size\n\t\\\\ dim or redim buffer append 1000 long as is.\n\tBuffer stack_ as long*(1000+data_size)\n\t\\\\ get strings\n\ta$=rightpart$(a$, \"Strings:\")\n\tm=0\n\tstrings=val(a$, \"int\", m)\n\ta$=rightpart$(a$, nl$)\n\n\tif strings>0 then\n\t\tDim strings$(strings)\n\t\tfor i=0 to strings-1\n\t\t\tstrings$(i)=GetString$(leftpart$(a$, nl$))\n\t\t\ta$=rightpart$(a$, nl$)\n\t\tNext i\n\tEnd if\n\tbuffer clear code_ as byte*1000\n\tdo\n\t\tm=0\n\t\toffset=val(a$,\"int\", m)\n\t\tif m<0 then exit\n\t\ta$=mid$(a$,m)\n\t\tline$=trim$(leftpart$(a$,nl$))\n\t\tif line$=\"\" then line$=trim$(a$) else a$=trim$(rightpart$(a$, nl$))\n\t\top$=if$(instr(line$,\" \")>0->leftpart$(line$,\" \"), line$)\n\t\tif not valid(eval(op$+\"_\")) then exit\n\t\topc=eval(op$+\"_\")\n\t\tReturn code_, offset:=opc\n\t\tif opc>=store_ then\n\t\t\tline$=rightpart$(line$,\" \")\n\t\t\tselect case opc\n\t\t\tcase store_, fetch_\n\t\t\t\tReturn code_, offset+1:=val(rightpart$(leftpart$(line$,\"]\"),\"[\")) as long : offset+=4\n\t\t\tcase push_\n\t\t\t\tReturn code_, offset+1:=uint(val(line$)) as long : offset+=4\n\t\t\tcase jz_, jmp_\n\t\t\t\tReturn code_, offset+1:=val(rightpart$(line$,\")\")) as long : offset+=4\n\t\t\tend select\n\t\tend if\n\tAlways\n\tPrint \"Press any key\" : Push key$ : Drop\n\t\\\\ Prepare VM\n\tlet pc=0, sp=len(stack_) div 4\n\tdo\n\t\tb=func(eval(code_, pc))\n\t\tpc++\n\t\tcall local b()\n\tuntil exit_now\n\tPrint \"done\"\n}\nVirtual_Machine_Interpreter {\nDatasize: 1 Strings: 2\n\"count is: \"\n\"\\n\"\n 0 push 1\n 5 store [0]\n 10 fetch [0]\n 15 push 10\n 20 lt\n 21 jz (43) 65\n 26 push 0\n 31 prts\n 32 fetch [0]\n 37 prti\n 38 push 1\n 43 prts\n 44 fetch [0]\n 49 push 1\n 54 add\n 55 store [0]\n 60 jmp (-51) 10\n 65 halt\n}\n", "language": "M2000-Interpreter" }, { "code": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%\n%%% The Rosetta Code Virtual Machine, in Mercury.\n%%%\n%%% (This particular machine is arbitrarily chosen to be big-endian.)\n%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n:- module vm.\n\n:- interface.\n:- import_module io.\n:- pred main(io::di, io::uo) is det.\n\n:- implementation.\n:- import_module array.\n:- import_module bool.\n:- import_module char.\n:- import_module exception.\n:- import_module int.\n:- import_module int32.\n:- import_module list.\n:- import_module string.\n:- import_module uint.\n:- import_module uint8.\n:- import_module uint32.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%\n%%% uint32 operations.\n%%%\n\n:- func twos_cmp(uint32) = uint32.\n:- mode twos_cmp(in) = out is det.\n:- pragma inline(twos_cmp/1).\ntwos_cmp(U) = NegU :-\n (NegU = (\\U) + 1_u32).\n\n:- func unsigned_add(uint32, uint32) = uint32.\n:- mode unsigned_add(in, in) = out is det.\n:- pragma inline(unsigned_add/2).\nunsigned_add(U, V) = U_plus_V :-\n (U_plus_V = U + V).\n\n:- func unsigned_sub(uint32, uint32) = uint32.\n:- mode unsigned_sub(in, in) = out is det.\n:- pragma inline(unsigned_sub/2).\nunsigned_sub(U, V) = U_minus_V :-\n (U_minus_V = U - V).\n\n:- func signed_mul(uint32, uint32) = uint32.\n:- mode signed_mul(in, in) = out is det.\n:- pragma inline(signed_mul/2).\nsigned_mul(U, V) = UV :-\n UV = cast_from_int32(cast_from_uint32(U) * cast_from_uint32(V)).\n\n:- func signed_quot(uint32, uint32) = uint32.\n:- mode signed_quot(in, in) = out is det.\n:- pragma inline(signed_quot/2).\nsigned_quot(U, V) = U_quot_V :- % Truncation towards zero.\n U_quot_V = cast_from_int32(cast_from_uint32(U)\n // cast_from_uint32(V)).\n\n:- func signed_rem(uint32, uint32) = uint32.\n:- mode signed_rem(in, in) = out is det.\n:- pragma inline(signed_rem/2).\nsigned_rem(U, V) = U_rem_V :- % Truncation towards zero, sign of U.\n U_rem_V = cast_from_int32(cast_from_uint32(U)\n rem cast_from_uint32(V)).\n\n:- func signed_lt(uint32, uint32) = uint32.\n:- mode signed_lt(in, in) = out is det.\n:- pragma inline(signed_lt/2).\nsigned_lt(U, V) = U_lt_V :-\n if (int32.cast_from_uint32(U) < int32.cast_from_uint32(V))\n then (U_lt_V = 1_u32)\n else (U_lt_V = 0_u32).\n\n:- func signed_le(uint32, uint32) = uint32.\n:- mode signed_le(in, in) = out is det.\n:- pragma inline(signed_le/2).\nsigned_le(U, V) = U_le_V :-\n if (int32.cast_from_uint32(U) =< int32.cast_from_uint32(V))\n then (U_le_V = 1_u32)\n else (U_le_V = 0_u32).\n\n:- func signed_gt(uint32, uint32) = uint32.\n:- mode signed_gt(in, in) = out is det.\n:- pragma inline(signed_gt/2).\nsigned_gt(U, V) = U_gt_V :-\n U_gt_V = signed_lt(V, U).\n\n:- func signed_ge(uint32, uint32) = uint32.\n:- mode signed_ge(in, in) = out is det.\n:- pragma inline(signed_ge/2).\nsigned_ge(U, V) = U_ge_V :-\n U_ge_V = signed_le(V, U).\n\n:- func unsigned_eq(uint32, uint32) = uint32.\n:- mode unsigned_eq(in, in) = out is det.\n:- pragma inline(unsigned_eq/2).\nunsigned_eq(U, V) = U_eq_V :-\n if (U = V)\n then (U_eq_V = 1_u32)\n else (U_eq_V = 0_u32).\n\n:- func unsigned_ne(uint32, uint32) = uint32.\n:- mode unsigned_ne(in, in) = out is det.\n:- pragma inline(unsigned_ne/2).\nunsigned_ne(U, V) = U_ne_V :-\n if (U \\= V)\n then (U_ne_V = 1_u32)\n else (U_ne_V = 0_u32).\n\n:- func logical_cmp(uint32) = uint32.\n:- mode logical_cmp(in) = out is det.\n:- pragma inline(logical_cmp/1).\nlogical_cmp(U) = NotU :-\n if (U = 0_u32)\n then (NotU = 1_u32)\n else (NotU = 0_u32).\n\n:- func logical_and(uint32, uint32) = uint32.\n:- mode logical_and(in, in) = out is det.\n:- pragma inline(logical_and/2).\nlogical_and(U, V) = U_and_V :-\n if (U \\= 0_u32, V \\= 0_u32)\n then (U_and_V = 1_u32)\n else (U_and_V = 0_u32).\n\n:- func logical_or(uint32, uint32) = uint32.\n:- mode logical_or(in, in) = out is det.\n:- pragma inline(logical_or/2).\nlogical_or(U, V) = U_or_V :-\n if (U \\= 0_u32; V \\= 0_u32)\n then (U_or_V = 1_u32)\n else (U_or_V = 0_u32).\n\n:- pred to_bytes(uint32, uint8, uint8, uint8, uint8).\n:- mode to_bytes(in, out, out, out, out) is det.\n:- pragma inline(to_bytes/5).\nto_bytes(U, B3, B2, B1, B0) :-\n (B0 = cast_from_int(cast_to_int(U /\\ 0xFF_u32))),\n (B1 = cast_from_int(cast_to_int((U >> 8) /\\ 0xFF_u32))),\n (B2 = cast_from_int(cast_to_int((U >> 16) /\\ 0xFF_u32))),\n (B3 = cast_from_int(cast_to_int((U >> 24) /\\ 0xFF_u32))).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%\n%%% String operations.\n%%%\n\n:- pred digit_u32(char, uint32).\n:- mode digit_u32(in, out) is semidet.\ndigit_u32(('0'), 0_u32).\ndigit_u32(('1'), 1_u32).\ndigit_u32(('2'), 2_u32).\ndigit_u32(('3'), 3_u32).\ndigit_u32(('4'), 4_u32).\ndigit_u32(('5'), 5_u32).\ndigit_u32(('6'), 6_u32).\ndigit_u32(('7'), 7_u32).\ndigit_u32(('8'), 8_u32).\ndigit_u32(('9'), 9_u32).\n\n:- pred is_not_digit(char).\n:- mode is_not_digit(in) is semidet.\nis_not_digit(C) :-\n not is_digit(C).\n\n:- pred is_not_alnum_nor_minus(char).\n:- mode is_not_alnum_nor_minus(in) is semidet.\nis_not_alnum_nor_minus(C) :-\n not (is_alnum(C); C = ('-')).\n\n:- pred det_string_to_uint32(string, uint32).\n:- mode det_string_to_uint32(in, out) is det.\ndet_string_to_uint32(S, U) :-\n to_char_list(S) = CL,\n (if (det_string_to_uint32_loop(CL, 0_u32, U1))\n then (U = U1)\n else throw(\"cannot convert string to uint32\")).\n\n:- pred det_string_to_uint32_loop(list(char), uint32, uint32).\n:- mode det_string_to_uint32_loop(in, in, out) is semidet.\ndet_string_to_uint32_loop([], U0, U1) :- U1 = U0.\ndet_string_to_uint32_loop([C | Tail], U0, U1) :-\n digit_u32(C, Digit),\n det_string_to_uint32_loop(Tail, (U0 * 10_u32) + Digit, U1).\n\n:- pred det_signed_string_to_uint32(string, uint32).\n:- mode det_signed_string_to_uint32(in, out) is det.\ndet_signed_string_to_uint32(S, U) :-\n if prefix(S, \"-\")\n then (det_remove_prefix(\"-\", S, S1),\n det_string_to_uint32(S1, U1),\n U = twos_cmp(U1))\n else det_string_to_uint32(S, U).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%\n%%% Parsing the \"assembly\" language.\n%%%\n\n:- func opcode_halt = uint8.\n:- func opcode_add = uint8.\n:- func opcode_sub = uint8.\n:- func opcode_mul = uint8.\n:- func opcode_div = uint8.\n:- func opcode_mod = uint8.\n:- func opcode_lt = uint8.\n:- func opcode_gt = uint8.\n:- func opcode_le = uint8.\n:- func opcode_ge = uint8.\n:- func opcode_eq = uint8.\n:- func opcode_ne = uint8.\n:- func opcode_and = uint8.\n:- func opcode_or = uint8.\n:- func opcode_neg = uint8.\n:- func opcode_not = uint8.\n:- func opcode_prtc = uint8.\n:- func opcode_prti = uint8.\n:- func opcode_prts = uint8.\n:- func opcode_fetch = uint8.\n:- func opcode_store = uint8.\n:- func opcode_push = uint8.\n:- func opcode_jmp = uint8.\n:- func opcode_jz = uint8.\nopcode_halt = 0_u8.\nopcode_add = 1_u8.\nopcode_sub = 2_u8.\nopcode_mul = 3_u8.\nopcode_div = 4_u8.\nopcode_mod = 5_u8.\nopcode_lt = 6_u8.\nopcode_gt = 7_u8.\nopcode_le = 8_u8.\nopcode_ge = 9_u8.\nopcode_eq = 10_u8.\nopcode_ne = 11_u8.\nopcode_and = 12_u8.\nopcode_or = 13_u8.\nopcode_neg = 14_u8.\nopcode_not = 15_u8.\nopcode_prtc = 16_u8.\nopcode_prti = 17_u8.\nopcode_prts = 18_u8.\nopcode_fetch = 19_u8.\nopcode_store = 20_u8.\nopcode_push = 21_u8.\nopcode_jmp = 22_u8.\nopcode_jz = 23_u8.\n\n:- pred opcode(string, uint8).\n:- mode opcode(in, out) is semidet.\n%:- mode opcode(out, in) is semidet. <-- Not needed.\nopcode(\"halt\", opcode_halt).\nopcode(\"add\", opcode_add).\nopcode(\"sub\", opcode_sub).\nopcode(\"mul\", opcode_mul).\nopcode(\"div\", opcode_div).\nopcode(\"mod\", opcode_mod).\nopcode(\"lt\", opcode_lt).\nopcode(\"gt\", opcode_gt).\nopcode(\"le\", opcode_le).\nopcode(\"ge\", opcode_ge).\nopcode(\"eq\", opcode_eq).\nopcode(\"ne\", opcode_ne).\nopcode(\"and\", opcode_and).\nopcode(\"or\", opcode_or).\nopcode(\"neg\", opcode_neg).\nopcode(\"not\", opcode_not).\nopcode(\"prtc\", opcode_prtc).\nopcode(\"prti\", opcode_prti).\nopcode(\"prts\", opcode_prts).\nopcode(\"fetch\", opcode_fetch).\nopcode(\"store\", opcode_store).\nopcode(\"push\", opcode_push).\nopcode(\"jmp\", opcode_jmp).\nopcode(\"jz\", opcode_jz).\n\n:- pred parse_header(string, uint32, uint32).\n:- mode parse_header(in, out, out) is det.\nparse_header(S, Datasize, Strings_Count) :-\n % Split S on any non-digit characters, leaving a list of the two\n % runs of digits.\n if (words_separator(is_not_digit, S) = [S_Datasize, S_Strings])\n % Convert the runs of digits to uint32.\n then (det_string_to_uint32(S_Datasize, Datasize),\n det_string_to_uint32(S_Strings, Strings_Count))\n else throw(\"cannot parse the header\").\n\n:- pred parse_string_literal(string, string).\n:- mode parse_string_literal(in, out) is det.\nparse_string_literal(S0, S) :-\n % Strip leading/trailing space.\n S1 = strip(S0),\n % Remove the \" characters.\n det_remove_prefix(\"\\\"\", S1, S2),\n det_remove_suffix(S2, \"\\\"\") = S3,\n % Deal with \"\\\\\" and \"\\n\".\n replace_escapes(S3, S).\n\n:- pred replace_escapes(string, string).\n:- mode replace_escapes(in, out) is det.\nreplace_escapes(S0, S) :-\n CL0 = to_char_list(S0),\n replace_escapes(CL0, [], CL),\n S = from_rev_char_list(CL).\n\n:- pred replace_escapes(list(char), list(char), list(char)).\n:- mode replace_escapes(in, in, out) is det.\nreplace_escapes([], Dst0, Dst) :-\n Dst = Dst0.\nreplace_escapes([C | Tail], Dst0, Dst) :-\n if (C \\= ('\\\\'))\n then replace_escapes(Tail, [C | Dst0], Dst)\n else (if (Tail = [C1 | Tail1])\n then (if (C1 = ('n'))\n then replace_escapes(Tail1, [('\\n') | Dst0], Dst)\n else if (C1 = ('\\\\'))\n then replace_escapes(Tail1, [('\\\\') | Dst0], Dst)\n else throw(\"illegal escape sequence\"))\n else throw(\"truncated escape sequence\")).\n\n:- pred parse_instruction(string, {uint32, uint8, uint32}).\n:- mode parse_instruction(in, out) is det.\nparse_instruction(S, {Address, Opcode, Arg}) :-\n words_separator(is_not_alnum_nor_minus, S) = Lst,\n (if parse_instr_lst(Lst, {Addr, Op, A})\n then (Address = Addr, Opcode = Op, Arg = A)\n else throw(\"cannot parse instruction\")).\n\n:- pred parse_instr_lst(list(string), {uint32, uint8, uint32}).\n:- mode parse_instr_lst(in, out) is semidet.\nparse_instr_lst([S_Address, S_Opcode],\n {Address, Opcode, Arg}) :-\n det_string_to_uint32(S_Address, Address),\n opcode(S_Opcode, Opcode),\n Arg = 0_u32.\nparse_instr_lst([S_Address, S_Opcode, S_Arg | _],\n {Address, Opcode, Arg}) :-\n det_string_to_uint32(S_Address, Address),\n opcode(S_Opcode, Opcode),\n det_signed_string_to_uint32(S_Arg, Arg).\n\n:- pred parse_assembly((io.text_input_stream), uint32, uint32,\n array(string),\n list({uint32, uint8, uint32}),\n io, io).\n:- mode parse_assembly(in, out, out, out, out, di, uo) is det.\nparse_assembly(InpF, Datasize, Strings_Count, Strings,\n Instructions, !IO) :-\n read_line_as_string(InpF, Res, !IO),\n (if (Res = ok(Line))\n then (parse_header(Line, Datasize, Strings_Count),\n read_and_parse_strings(InpF, Strings_Count, Strings, !IO),\n read_and_parse_instructions(InpF, Instructions, !IO))\n else if (Res = eof)\n then throw(\"empty input\")\n else throw(\"read error\")).\n\n:- pred read_and_parse_strings((io.text_input_stream), uint32,\n array(string), io, io).\n:- mode read_and_parse_strings(in, in, out, di, uo) is det.\nread_and_parse_strings(InpF, Strings_Count, Strings, !IO) :-\n read_n_string_literals(InpF, Strings_Count, [], Lst, !IO),\n Strings = array(Lst).\n\n:- pred read_n_string_literals((io.text_input_stream), uint32,\n list(string), list(string),\n io, io).\n:- mode read_n_string_literals(in, in, in, out, di, uo) is det.\nread_n_string_literals(InpF, N, Lst0, Lst, !IO) :-\n if (N = 0_u32)\n then (Lst = reverse(Lst0))\n else (read_line_as_string(InpF, Res, !IO),\n (if (Res = ok(Line))\n then (parse_string_literal(Line, S),\n read_n_string_literals(InpF, N - 1_u32,\n [S | Lst0], Lst, !IO))\n else if (Res = eof)\n then throw(\"premature end of input\")\n else throw(\"read error\"))).\n\n:- pred read_and_parse_instructions((io.text_input_stream),\n list({uint32, uint8, uint32}),\n io, io).\n:- mode read_and_parse_instructions(in, out, di, uo) is det.\nread_and_parse_instructions(InpF, Instructions, !IO) :-\n read_all_instructions(InpF, [], Instructions, !IO).\n\n:- pred read_all_instructions((io.text_input_stream),\n list({uint32, uint8, uint32}),\n list({uint32, uint8, uint32}),\n io, io).\n:- mode read_all_instructions(in, in, out, di, uo) is det.\nread_all_instructions(InpF, Lst0, Lst, !IO) :-\n read_line_as_string(InpF, Res, !IO),\n (if (Res = eof)\n then (Lst = Lst0) % There is no need to reverse the list.\n else if (Res = ok(Line))\n then (strip(Line) = S,\n (if is_empty(S)\n then read_all_instructions(InpF, Lst0, Lst, !IO)\n else (parse_instruction(S, Instr),\n read_all_instructions(InpF, [Instr | Lst0], Lst,\n !IO))))\n else throw(\"read error\")).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%\n%%% Constructing the executable memory.\n%%%\n\n:- func greatest_address(list({uint32, uint8, uint32}),\n uint32) = uint32.\n:- mode greatest_address(in, in) = out is det.\ngreatest_address([], Min_Result) = Result :-\n Result = Min_Result.\ngreatest_address([{Addr, _, _} | Tail], Min_Result) = Result :-\n if (Min_Result < Addr)\n then (Result = greatest_address(Tail, Addr))\n else (Result = greatest_address(Tail, Min_Result)).\n\n:- pred executable_memory(list({uint32, uint8, uint32}),\n array(uint8)).\n:- mode executable_memory(in, out) is det.\nexecutable_memory(Instructions, Code) :-\n greatest_address(Instructions, 0_u32) = Addr,\n Code_Size = (Addr + 5_u32), % At least enough memory.\n init(cast_to_int(Code_Size), opcode_halt, Code0),\n fill_executable_memory(Instructions, Code0, Code).\n\n:- pred fill_executable_memory(list({uint32, uint8, uint32}),\n array(uint8), array(uint8)).\n:- mode fill_executable_memory(in, array_di, array_uo) is det.\nfill_executable_memory([], !Code) :- true.\nfill_executable_memory([Instr | Tail], !Code) :-\n Instr = {Address, Opcode, Arg},\n Addr = cast_to_int(Address),\n set(Addr, Opcode, !Code),\n (if (Opcode = opcode_fetch;\n Opcode = opcode_store;\n Opcode = opcode_push;\n Opcode = opcode_jmp;\n Opcode = opcode_jz)\n then (to_bytes(Arg, B3, B2, B1, B0),\n % Store the argument in big-endian order.\n set(Addr + 1, B3, !Code),\n set(Addr + 2, B2, !Code),\n set(Addr + 3, B1, !Code),\n set(Addr + 4, B0, !Code))\n else true),\n fill_executable_memory(Tail, !Code).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%e\n%%%\n%%% Executing the code.\n%%%\n\n:- pred machine_add(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_add(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_add/4).\nmachine_add(Stack0, Stack, SP0, SP) :-\n Result = unsigned_add(lookup(Stack0, cast_to_int(SP - 1_u32)),\n lookup(Stack0, cast_to_int(SP))),\n set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),\n SP = SP0 - 1_u32.\n\n:- pred machine_sub(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_sub(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_sub/4).\nmachine_sub(Stack0, Stack, SP0, SP) :-\n Result = unsigned_sub(lookup(Stack0, cast_to_int(SP - 1_u32)),\n lookup(Stack0, cast_to_int(SP))),\n set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),\n SP = SP0 - 1_u32.\n\n:- pred machine_mul(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_mul(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_mul/4).\nmachine_mul(Stack0, Stack, SP0, SP) :-\n Result = signed_mul(lookup(Stack0, cast_to_int(SP - 1_u32)),\n lookup(Stack0, cast_to_int(SP))),\n set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),\n SP = SP0 - 1_u32.\n\n:- pred machine_div(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_div(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_div/4).\nmachine_div(Stack0, Stack, SP0, SP) :-\n Result = signed_quot(lookup(Stack0, cast_to_int(SP - 1_u32)),\n lookup(Stack0, cast_to_int(SP))),\n set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),\n SP = SP0 - 1_u32.\n\n:- pred machine_mod(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_mod(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_mod/4).\nmachine_mod(Stack0, Stack, SP0, SP) :-\n Result = signed_rem(lookup(Stack0, cast_to_int(SP - 1_u32)),\n lookup(Stack0, cast_to_int(SP))),\n set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),\n SP = SP0 - 1_u32.\n\n:- pred machine_lt(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_lt(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_lt/4).\nmachine_lt(Stack0, Stack, SP0, SP) :-\n Result = signed_lt(lookup(Stack0, cast_to_int(SP - 1_u32)),\n lookup(Stack0, cast_to_int(SP))),\n set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),\n SP = SP0 - 1_u32.\n\n:- pred machine_le(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_le(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_le/4).\nmachine_le(Stack0, Stack, SP0, SP) :-\n Result = signed_le(lookup(Stack0, cast_to_int(SP - 1_u32)),\n lookup(Stack0, cast_to_int(SP))),\n set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),\n SP = SP0 - 1_u32.\n\n:- pred machine_gt(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_gt(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_gt/4).\nmachine_gt(Stack0, Stack, SP0, SP) :-\n Result = signed_gt(lookup(Stack0, cast_to_int(SP - 1_u32)),\n lookup(Stack0, cast_to_int(SP))),\n set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),\n SP = SP0 - 1_u32.\n\n:- pred machine_ge(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_ge(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_ge/4).\nmachine_ge(Stack0, Stack, SP0, SP) :-\n Result = signed_ge(lookup(Stack0, cast_to_int(SP - 1_u32)),\n lookup(Stack0, cast_to_int(SP))),\n set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),\n SP = SP0 - 1_u32.\n\n:- pred machine_eq(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_eq(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_eq/4).\nmachine_eq(Stack0, Stack, SP0, SP) :-\n Result = unsigned_eq(lookup(Stack0, cast_to_int(SP - 1_u32)),\n lookup(Stack0, cast_to_int(SP))),\n set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),\n SP = SP0 - 1_u32.\n\n:- pred machine_ne(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_ne(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_ne/4).\nmachine_ne(Stack0, Stack, SP0, SP) :-\n Result = unsigned_ne(lookup(Stack0, cast_to_int(SP - 1_u32)),\n lookup(Stack0, cast_to_int(SP))),\n set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),\n SP = SP0 - 1_u32.\n\n:- pred machine_and(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_and(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_and/4).\nmachine_and(Stack0, Stack, SP0, SP) :-\n Result = logical_and(lookup(Stack0, cast_to_int(SP - 1_u32)),\n lookup(Stack0, cast_to_int(SP))),\n set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),\n SP = SP0 - 1_u32.\n\n:- pred machine_or(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_or(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_or/4).\nmachine_or(Stack0, Stack, SP0, SP) :-\n Result = logical_or(lookup(Stack0, cast_to_int(SP - 1_u32)),\n lookup(Stack0, cast_to_int(SP))),\n set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),\n SP = SP0 - 1_u32.\n\n:- pred machine_neg(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_neg(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_neg/4).\nmachine_neg(Stack0, Stack, SP0, SP) :-\n SP = SP0,\n (I = uint32.cast_to_int(SP0)),\n Result = twos_cmp(lookup(Stack0, I - 1)),\n set(I - 1, Result, Stack0, Stack).\n\n:- pred machine_not(array(uint32), array(uint32), uint32, uint32).\n:- mode machine_not(array_di, array_uo, in, out) is det.\n:- pragma inline(machine_not/4).\nmachine_not(Stack0, Stack, SP0, SP) :-\n SP = SP0,\n (I = uint32.cast_to_int(SP0)),\n Result = logical_cmp(lookup(Stack0, I - 1)),\n set(I - 1, Result, Stack0, Stack).\n\n:- pred machine_prtc((io.text_output_stream),\n array(uint32), array(uint32),\n uint32, uint32, io, io).\n:- mode machine_prtc(in, array_di, array_uo, in, out,\n di, uo) is det.\nmachine_prtc(OutF, Stack0, Stack, SP0, SP, !IO) :-\n Stack = Stack0,\n (I = uint32.cast_to_int(SP0)),\n X = lookup(Stack0, I - 1),\n C = (char.det_from_int(uint32.cast_to_int(X))),\n (io.write_char(OutF, C, !IO)),\n SP = SP0 - 1_u32.\n\n:- pred machine_prti((io.text_output_stream),\n array(uint32), array(uint32),\n uint32, uint32, io, io).\n:- mode machine_prti(in, array_di, array_uo, in, out,\n di, uo) is det.\nmachine_prti(OutF, Stack0, Stack, SP0, SP, !IO) :-\n Stack = Stack0,\n (I = uint32.cast_to_int(SP0)),\n (X = int32.cast_from_uint32(lookup(Stack0, I - 1))),\n (io.write_int32(OutF, X, !IO)),\n SP = SP0 - 1_u32.\n\n:- pred machine_prts((io.text_output_stream),\n array(string),\n array(uint32), array(uint32),\n uint32, uint32, io, io).\n:- mode machine_prts(in, in, array_di, array_uo, in, out,\n di, uo) is det.\nmachine_prts(OutF, Strings, Stack0, Stack, SP0, SP, !IO) :-\n Stack = Stack0,\n (I = uint32.cast_to_int(SP0)),\n (K = uint32.cast_to_int(lookup(Stack0, I - 1))),\n S = lookup(Strings, K),\n (io.write_string(OutF, S, !IO)),\n SP = SP0 - 1_u32.\n\n:- func get_immediate(array(uint8), uint32) = uint32.\n:- mode get_immediate(in, in) = out is det.\n:- pragma inline(get_immediate/2).\nget_immediate(Code, IP) = Immediate_Value :-\n % Big-endian order.\n I = cast_to_int(IP),\n B3 = lookup(Code, I),\n B2 = lookup(Code, I + 1),\n B1 = lookup(Code, I + 2),\n B0 = lookup(Code, I + 3),\n Immediate_Value = from_bytes_be(B3, B2, B1, B0).\n\n:- pred machine_fetch(array(uint32), array(uint32),\n array(uint8), uint32, uint32,\n array(uint32), array(uint32),\n uint32, uint32).\n:- mode machine_fetch(array_di, array_uo, in, in, out,\n array_di, array_uo, in, out) is det.\n:- pragma inline(machine_fetch/9).\nmachine_fetch(Data0, Data, Code, IP0, IP, !Stack, SP0, SP) :-\n Data = Data0,\n K = get_immediate(Code, IP0),\n IP = IP0 + 4_u32,\n X = lookup(Data0, cast_to_int(K)),\n set(cast_to_int(SP0), X, !Stack),\n SP = SP0 + 1_u32.\n\n:- pred machine_store(array(uint32), array(uint32),\n array(uint8), uint32, uint32,\n array(uint32), array(uint32),\n uint32, uint32).\n:- mode machine_store(array_di, array_uo, in, in, out,\n array_di, array_uo, in, out) is det.\n:- pragma inline(machine_store/9).\nmachine_store(!Data, Code, IP0, IP, Stack0, Stack, SP0, SP) :-\n Stack = Stack0,\n K = get_immediate(Code, IP0),\n IP = IP0 + 4_u32,\n SP = SP0 - 1_u32,\n X = lookup(Stack0, cast_to_int(SP)),\n set(cast_to_int(K), X, !Data).\n\n:- pred machine_push(array(uint8), uint32, uint32,\n array(uint32), array(uint32),\n uint32, uint32).\n:- mode machine_push(in, in, out, array_di, array_uo, in, out) is det.\n:- pragma inline(machine_push/7).\nmachine_push(Code, IP0, IP, !Stack, SP0, SP) :-\n X = get_immediate(Code, IP0),\n IP = IP0 + 4_u32,\n set(cast_to_int(SP0), X, !Stack),\n SP = SP0 + 1_u32.\n\n:- pred machine_jmp(array(uint8), uint32, uint32).\n:- mode machine_jmp(in, in, out) is det.\n:- pragma inline(machine_jmp/3).\nmachine_jmp(Code, IP0, IP) :-\n Offset = get_immediate(Code, IP0),\n IP = unsigned_add(IP0, Offset).\n\n:- pred machine_jz(array(uint8), uint32, uint32,\n array(uint32), array(uint32),\n uint32, uint32).\n:- mode machine_jz(in, in, out, array_di, array_uo, in, out) is det.\n:- pragma inline(machine_jz/7).\nmachine_jz(Code, IP0, IP, Stack0, Stack, SP0, SP) :-\n Stack = Stack0,\n SP = SP0 - 1_u32,\n X = lookup(Stack0, cast_to_int(SP)),\n (if (X = 0_u32)\n then (Offset = get_immediate(Code, IP0),\n IP = unsigned_add(IP0, Offset))\n else (IP = IP0 + 4_u32)).\n\n:- pred run_one_instruction((io.text_output_stream),\n array(string),\n array(uint32), array(uint32),\n array(uint8), uint32, uint32,\n array(uint32), array(uint32),\n uint32, uint32, bool, io, io).\n:- mode run_one_instruction(in, in, array_di, array_uo,\n in, in, out, array_di, array_uo,\n in, out, out, di, uo) is det.\nrun_one_instruction(OutF, Strings, !Data,\n Code, IP0, IP, !Stack, !SP,\n Halt, !IO) :-\n %\n % In the following implementation, any unrecognized instruction\n % causes a HALT, just as an actual \"halt\" opcode would.\n %\n Opcode = lookup(Code, cast_to_int(IP0)),\n IP1 = IP0 + 1_u32,\n I = (Opcode >> 2),\n J = (Opcode /\\ 0x03_u8),\n (if (I = 0_u8)\n then (IP = IP1,\n (if (J = 0_u8)\n then (Halt = yes)\n else if (J = 1_u8)\n then (machine_add(!Stack, !SP),\n Halt = no)\n else if (J = 2_u8)\n then (machine_sub(!Stack, !SP),\n Halt = no)\n else (machine_mul(!Stack, !SP),\n Halt = no)))\n else if (I = 1_u8)\n then (Halt = no,\n IP = IP1,\n (if (J = 0_u8)\n then machine_div(!Stack, !SP)\n else if (J = 1_u8)\n then machine_mod(!Stack, !SP)\n else if (J = 2_u8)\n then machine_lt(!Stack, !SP)\n else machine_gt(!Stack, !SP)))\n else if (I = 2_u8)\n then (Halt = no,\n IP = IP1,\n (if (J = 0_u8)\n then machine_le(!Stack, !SP)\n else if (J = 1_u8)\n then machine_ge(!Stack, !SP)\n else if (J = 2_u8)\n then machine_eq(!Stack, !SP)\n else machine_ne(!Stack, !SP)))\n else if (I = 3_u8)\n then (Halt = no,\n IP = IP1,\n (if (J = 0_u8)\n then machine_and(!Stack, !SP)\n else if (J = 1_u8)\n then machine_or(!Stack, !SP)\n else if (J = 2_u8)\n then machine_neg(!Stack, !SP)\n else machine_not(!Stack, !SP)))\n else if (I = 4_u8)\n then (Halt = no,\n (if (J = 0_u8)\n then (machine_prtc(OutF, !Stack, !SP, !IO),\n IP = IP1)\n else if (J = 1_u8)\n then (machine_prti(OutF, !Stack, !SP, !IO),\n IP = IP1)\n else if (J = 2_u8)\n then (machine_prts(OutF, Strings, !Stack, !SP, !IO),\n IP = IP1)\n else machine_fetch(!Data, Code, IP1, IP, !Stack, !SP)))\n else if (I = 5_u8)\n then (Halt = no,\n (if (J = 0_u8)\n then machine_store(!Data, Code, IP1, IP, !Stack, !SP)\n else if (J = 1_u8)\n then machine_push(Code, IP1, IP, !Stack, !SP)\n else if (J = 2_u8)\n then machine_jmp(Code, IP1, IP)\n else machine_jz(Code, IP1, IP, !Stack, !SP)))\n else (Halt = yes, IP = IP1)).\n\n:- pred run_program((io.text_output_stream), array(string),\n array(uint32), array(uint32),\n array(uint8), uint32, uint32,\n array(uint32), array(uint32),\n uint32, uint32, io, io).\n:- mode run_program(in, in, array_di, array_uo,\n in, in, out, array_di, array_uo,\n in, out, di, uo) is det.\nrun_program(OutF, Strings, !Data, Code, !IP, !Stack, !SP, !IO) :-\n run_one_instruction(OutF, Strings, !Data, Code, !IP, !Stack, !SP,\n Halt, !IO),\n (if (Halt = yes)\n then true\n else run_program(OutF, Strings, !Data, Code, !IP, !Stack,\n !SP, !IO)).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n:- pred open_InpF(text_input_stream, string, io, io).\n:- mode open_InpF(out, in, di, uo) is det.\nopen_InpF(InpF, InpF_filename, !IO) :-\n if (InpF_filename = \"-\")\n then (InpF = io.stdin_stream)\n else (open_input(InpF_filename, InpF_result, !IO),\n (if (InpF_result = ok(F))\n then (InpF = F)\n else throw(\"Error: cannot open \" ++ InpF_filename ++\n \" for input\"))).\n\n:- pred open_OutF(text_output_stream, string, io, io).\n:- mode open_OutF(out, in, di, uo) is det.\nopen_OutF(OutF, OutF_filename, !IO) :-\n if (OutF_filename = \"-\")\n then (OutF = io.stdout_stream)\n else (open_output(OutF_filename, OutF_result, !IO),\n (if (OutF_result = ok(F))\n then (OutF = F)\n else throw(\"Error: cannot open \" ++ OutF_filename ++\n \" for output\"))).\n\n:- pred main_program(string, string, io, io).\n:- mode main_program(in, in, di, uo) is det.\nmain_program(InpF_filename, OutF_filename, !IO) :-\n open_InpF(InpF, InpF_filename, !IO),\n open_OutF(OutF, OutF_filename, !IO),\n parse_assembly(InpF, Datasize, _Strings_Count, Strings,\n Instructions, !IO),\n (if (InpF_filename = \"-\")\n then true\n else close_input(InpF, !IO)),\n executable_memory(Instructions, Code),\n init(cast_to_int(Datasize), 0_u32, Data0),\n init(2048, 0_u32, Stack0), % Stack is 2048 words.\n IP0 = 0_u32,\n SP0 = 0_u32,\n run_program(OutF, Strings, Data0, _Data, Code, IP0, _IP,\n Stack0, _Stack, SP0, _SP, !IO),\n (if (OutF_filename = \"-\")\n then true\n else close_output(OutF, !IO)).\n\n:- pred usage_error(io, io).\n:- mode usage_error(di, uo) is det.\nusage_error(!IO) :-\n progname(\"lex\", ProgName, !IO),\n (io.format(\"Usage: %s [INPUT_FILE [OUTPUT_FILE]]\\n\",\n [s(ProgName)], !IO)),\n (io.write_string(\n \"If INPUT_FILE is \\\"-\\\" or not present then standard input is used.\\n\",\n !IO)),\n (io.write_string(\n \"If OUTPUT_FILE is \\\"-\\\" or not present then standard output is used.\\n\",\n !IO)),\n set_exit_status(1, !IO).\n\nmain(!IO) :-\n command_line_arguments(Args, !IO),\n (if (Args = [])\n then (InpF_filename = \"-\",\n OutF_filename = \"-\",\n main_program(InpF_filename, OutF_filename, !IO))\n else if (Args = [F1])\n then (InpF_filename = F1,\n OutF_filename = \"-\",\n main_program(InpF_filename, OutF_filename, !IO))\n else if (Args = [F1, F2])\n then (InpF_filename = F1,\n OutF_filename = F2,\n main_program(InpF_filename, OutF_filename, !IO))\n else usage_error(!IO)).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Instructions for GNU Emacs--\n%%% local variables:\n%%% mode: mercury\n%%% prolog-indent-width: 2\n%%% end:\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "language": "Mercury" }, { "code": "import os, parseutils, strutils, strscans, strformat\n\ntype\n\n Value = int32\n BytesValue = array[4, byte]\n Address = int32\n\n OpCode = enum\n opFetch = \"fetch\"\n opStore = \"store\"\n opPush = \"push\"\n opJmp = \"jmp\"\n opJz = \"jz\"\n opAdd = \"add\"\n opSub = \"sub\"\n opMul = \"mul\"\n opDiv = \"div\"\n opMod = \"mod\"\n opLt = \"lt\"\n opgt = \"gt\"\n opLe = \"le\"\n opGe = \"ge\"\n opEq = \"eq\"\n opNe = \"ne\"\n opAnd = \"and\"\n opOr = \"or\"\n opNeg = \"neg\"\n opNot = \"not\"\n opPrtc = \"prtc\"\n opPrti = \"prti\"\n opPrts = \"prts\"\n opHalt = \"halt\"\n opInvalid = \"invalid\"\n\n # Virtual machine description.\n VM = object\n stack: seq[Value] # Evaluation stack.\n memory: seq[byte] # Memory to store program.\n data: seq[Value] # Data storage.\n strings: seq[string] # String storage.\n pc: Address # Program counter.\n\n # Exceptions.\n LoadingError = object of CatchableError\n RuntimeError = object of CatchableError\n\n\n####################################################################################################\n# Running program.\n\nproc checkStackLength(vm: VM; minLength: int) {.inline.} =\n ## Check that evaluation stack contains at least \"minLength\" elements.\n if vm.stack.len < minLength:\n raise newException(RuntimeError, &\"not enough operands on the stack (pc = {vm.pc}).\")\n\n#---------------------------------------------------------------------------------------------------\n\nproc getOperand(vm: var VM): Value =\n ## Get a 32 bits operand.\n\n type Union {.union.} = object\n value: Value\n bytes: BytesValue\n\n if vm.pc + 4 >= vm.memory.len:\n raise newException(RuntimeError, &\"out of memory (pc = {vm.pc}).\")\n\n var aux: Union\n let address = vm.pc + 1\n for idx in 0..3:\n aux.bytes[idx] = vm.memory[address + idx]\n result = aux.value\n\n#---------------------------------------------------------------------------------------------------\n\nproc run(vm: var VM) =\n ## Run a program loaded in VM memory.\n\n vm.pc = 0\n\n while true:\n\n if vm.pc notin 0..vm.memory.high:\n raise newException(RuntimeError, &\"out of memory (pc = {vm.pc}).\")\n\n let opcode = OpCode(vm.memory[vm.pc])\n case opcode\n\n of opFetch, opStore:\n let index = vm.getOperand()\n if index notin 0..vm.data.high:\n raise newException(RuntimeError, &\"wrong memory index (pc = {vm.pc}).\")\n if opcode == opFetch:\n vm.stack.add(vm.data[index])\n else:\n vm.checkStackLength(1)\n vm.data[index] = vm.stack.pop()\n inc vm.pc, 4\n\n of opPush:\n let value = vm.getOperand()\n vm.stack.add(value)\n inc vm.pc, 4\n\n of opJmp:\n let offset = vm.getOperand()\n inc vm.pc, offset\n\n of opJz:\n let offset = vm.getOperand()\n vm.checkStackLength(1)\n let value = vm.stack.pop()\n inc vm.pc, if value == 0: offset else: 4\n\n of opAdd..opOr:\n # Two operands instructions.\n vm.checkStackLength(2)\n let op2 = vm.stack.pop()\n let op1 = vm.stack.pop()\n case range[opAdd..opOr](opcode)\n of opAdd:\n vm.stack.add(op1 + op2)\n of opSub:\n vm.stack.add(op1 - op2)\n of opMul:\n vm.stack.add(op1 * op2)\n of opDiv:\n vm.stack.add(op1 div op2)\n of opMod:\n vm.stack.add(op1 mod op2)\n of opLt:\n vm.stack.add(Value(op1 < op2))\n of opgt:\n vm.stack.add(Value(op1 > op2))\n of opLe:\n vm.stack.add(Value(op1 <= op2))\n of opGe:\n vm.stack.add(Value(op1 >= op2))\n of opEq:\n vm.stack.add(Value(op1 == op2))\n of opNe:\n vm.stack.add(Value(op1 != op2))\n of opAnd:\n vm.stack.add(op1 and op2)\n of opOr:\n vm.stack.add(op1 or op2)\n\n of opNeg..opPrts:\n # One operand instructions.\n vm.checkStackLength(1)\n let op = vm.stack.pop()\n case range[opNeg..opPrts](opcode)\n of opNeg:\n vm.stack.add(-op)\n of opNot:\n vm.stack.add(not op)\n of opPrtc:\n stdout.write(chr(op))\n of opPrti:\n stdout.write(op)\n of opPrts:\n if op notin 0..vm.strings.high:\n raise newException(RuntimeError, &\"wrong string index (pc = {vm.pc}).\")\n stdout.write(vm.strings[op])\n\n of opHalt:\n break\n\n of opInvalid:\n discard # Not possible.\n\n inc vm.pc\n\n\n####################################################################################################\n# Loading assembly file.\n\nproc parseHeader(line: string): tuple[dataSize, stringCount: int] =\n ## Parse the header.\n\n if not line.scanf(\"Datasize: $s$i $sStrings: $i\", result.dataSize, result.stringCount):\n raise newException(LoadingError, \"Wrong header in code.\")\n\n#---------------------------------------------------------------------------------------------------\n\nimport re\n\nproc parseString(line: string; linenum: int): string =\n ## Parse a string.\n\n if not line.startsWith('\"'):\n raise newException(LoadingError, \"Line $1: incorrect string.\".format(linenum))\n # Can't use \"unescape\" as it is confused by \"\\\\n\" and \"\\n\".\n result = line.replacef(re\"([^\\\\])(\\\\n)\", \"$1\\n\").replace(r\"\\\\\", r\"\\\").replace(\"\\\"\", \"\")\n\n#---------------------------------------------------------------------------------------------------\n\nproc parseValue(line: string; linenum: int; pos: var int; msg: string): int32 =\n ## Parse an int32 value.\n\n var value: int\n\n pos += line.skipWhitespace(pos)\n let parsed = line.parseInt(value, pos)\n if parsed == 0:\n raise newException(LoadingError, \"Line $1: \".format(linenum) & msg)\n pos += parsed\n result = int32(value)\n\n#---------------------------------------------------------------------------------------------------\n\nproc parseOpcode(line: string; linenum: int; pos: var int): OpCode =\n ## Parse an opcode.\n\n var opstring: string\n\n pos += line.skipWhitespace(pos)\n let parsed = line.parseIdent(opstring, pos)\n if parsed == 0:\n raise newException(LoadingError, \"Line $1: opcode expected\".format(linenum))\n pos += parsed\n\n result = parseEnum[OpCode](opstring, opInvalid)\n if result == opInvalid:\n raise newException(LoadingError, \"Line $1: invalid opcode encountered\".format(linenum))\n\n#---------------------------------------------------------------------------------------------------\n\nproc parseMemoryIndex(line: string; linenum: int; pos: var int): int32 =\n ## Parse a memory index (int32 value between brackets).\n\n var memIndex: int\n\n pos += line.skipWhitespace(pos)\n let str = line.captureBetween('[', ']', pos)\n if str.parseInt(memIndex) == 0 or memIndex < 0:\n raise newException(LoadingError, \"Line $1: invalid memory index\".format(lineNum))\n pos += str.len + 2\n result = int32(memIndex)\n\n#---------------------------------------------------------------------------------------------------\n\nproc parseOffset(line: string; linenum: int; pos: var int): int32 =\n ## Parse an offset (int32 value between parentheses).\n\n var offset: int\n\n pos += line.skipWhitespace(pos)\n let str = line.captureBetween('(', ')', pos)\n if str.parseInt(offset) == 0:\n raise newException(LoadingError, \"Line $1: invalid offset\".format(linenum))\n pos += str.len + 2\n result = int32(offset)\n\n#---------------------------------------------------------------------------------------------------\n\nproc load(vm: var VM; code: string) =\n ## Load an assembly code into VM memory.\n\n # Analyze header.\n let lines = code.splitlines()\n let (dataSize, stringCount) = parseHeader(lines[0])\n vm.data.setLen(dataSize)\n vm.strings.setLen(stringCount)\n\n # Load strings.\n for idx in 1..stringCount:\n vm.strings[idx - 1] = lines[idx].parseString(idx + 1)\n\n # Load code.\n var pc: Address = 0\n for idx in (stringCount + 1)..lines.high:\n var pos = 0\n let line = lines[idx]\n if line.len == 0: continue\n\n # Process address.\n let address = line.parseValue(idx + 1, pos, \"address expected\")\n if address != pc:\n raise newException(LoadingError, \"Line $1: wrong address\".format(idx + 1))\n\n # Process opcode.\n let opcode = line.parseOpcode(idx + 1, pos)\n vm.memory.add(byte(opcode))\n\n # Process operand.\n case opcode\n\n of opFetch, opStore:\n # Find memory index.\n let memIndex = line.parseMemoryIndex(idx + 1, pos)\n vm.memory.add(cast[BytesValue](Value(memIndex)))\n inc pc, 5\n\n of opJmp, opJz:\n # Find offset.\n let offset = line.parseOffset(idx + 1, pos)\n vm.memory.add(cast[BytesValue](Value(offset)))\n # Find and check branch address.\n let branchAddress = line.parseValue(idx + 1, pos, \"branch address expected\")\n if branchAddress != pc + offset + 1:\n raise newException(LoadingError, \"Line $1: wrong branch address\".format(idx + 1))\n inc pc, 5\n\n of opPush:\n # Find value.\n let value = line.parseValue(idx + 1, pos, \"value expected\")\n vm.memory.add(cast[BytesValue](Value(value)))\n inc pc, 5\n\n else:\n inc pc\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nlet code = if paramCount() == 0: stdin.readAll() else: paramStr(1).readFile()\nvar vm: VM\n\nvm.load(code)\nvm.run()\n", "language": "Nim" }, { "code": "# -*- ObjectIcon -*-\n#\n# The Rosetta Code virtual machine in Object Icon.\n#\n# See https://rosettacode.org/wiki/Compiler/virtual_machine_interpreter\n#\n\nimport io\n\nprocedure main(args)\n local f_inp, f_out\n local vm\n\n if 3 <= *args then {\n write(\"Usage: \", &progname, \" [INPUT_FILE [OUTPUT_FILE]]\")\n exit(1)\n }\n\n if 1 <= *args then {\n f_inp := FileStream(args[1], FileOpt.RDONLY) | stop (&why)\n } else {\n f_inp := FileStream.stdin\n }\n f_inp := BufferStream(f_inp)\n\n if 2 <= *args then {\n f_out := FileStream(args[2], ior (FileOpt.WRONLY,\n FileOpt.TRUNC,\n FileOpt.CREAT)) | stop (&why)\n } else {\n f_out := FileStream.stdout\n }\n\n vm := VirtualMachine()\n vm.read_assembly_code(f_inp)\n vm.run(f_out)\nend\n\nprocedure int2bytes (n)\n local bytes\n\n # The VM is little-endian.\n\n bytes := \"****\"\n bytes[1] := char (iand(n, 16rFF))\n bytes[2] := char(iand(ishift(n, -8), 16rFF))\n bytes[3] := char(iand(ishift(n, -16), 16rFF))\n bytes[4] := char(iand(ishift(n, -24), 16rFF))\n return bytes\nend\n\nprocedure bytes2int(bytes, i)\n local n0, n1, n2, n3, n\n\n # The VM is little-endian.\n\n n0 := ord(bytes[i])\n n1 := ishift(ord(bytes[i + 1]), 8)\n n2 := ishift(ord(bytes[i + 2]), 16)\n n3 := ishift(ord(bytes[i + 3]), 24)\n n := ior (n0, ior (n1, ior (n2, n3)))\n\n # Do not forget to extend the sign bit.\n return (if n3 <= 16r7F then n else ior(n, icom(16rFFFFFFFF)))\nend\n\nclass OpcodeCollection()\n\n public static const opcode_names\n public static const opcode_values\n\n public static const op_halt\n public static const op_add\n public static const op_sub\n public static const op_mul\n public static const op_div\n public static const op_mod\n public static const op_lt\n public static const op_gt\n public static const op_le\n public static const op_ge\n public static const op_eq\n public static const op_ne\n public static const op_and\n public static const op_or\n public static const op_neg\n public static const op_not\n public static const op_prtc\n public static const op_prti\n public static const op_prts\n public static const op_fetch\n public static const op_store\n public static const op_push\n public static const op_jmp\n public static const op_jz\n\n private static init()\n local i\n\n opcode_names :=\n [\"halt\", \"add\", \"sub\", \"mul\", \"div\",\n \"mod\", \"lt\", \"gt\", \"le\", \"ge\",\n \"eq\", \"ne\", \"and\", \"or\", \"neg\",\n \"not\", \"prtc\", \"prti\", \"prts\", \"fetch\",\n \"store\", \"push\", \"jmp\", \"jz\"]\n\n opcode_values := table()\n every i := 1 to *opcode_names do\n opcode_values[opcode_names[i]] := char(i)\n\n op_halt := opcode_values[\"halt\"]\n op_add := opcode_values[\"add\"]\n op_sub := opcode_values[\"sub\"]\n op_mul := opcode_values[\"mul\"]\n op_div := opcode_values[\"div\"]\n op_mod := opcode_values[\"mod\"]\n op_lt := opcode_values[\"lt\"]\n op_gt := opcode_values[\"gt\"]\n op_le := opcode_values[\"le\"]\n op_ge := opcode_values[\"ge\"]\n op_eq := opcode_values[\"eq\"]\n op_ne := opcode_values[\"ne\"]\n op_and := opcode_values[\"and\"]\n op_or := opcode_values[\"or\"]\n op_neg := opcode_values[\"neg\"]\n op_not := opcode_values[\"not\"]\n op_prtc := opcode_values[\"prtc\"]\n op_prti := opcode_values[\"prti\"]\n op_prts := opcode_values[\"prts\"]\n op_fetch := opcode_values[\"fetch\"]\n op_store := opcode_values[\"store\"]\n op_push := opcode_values[\"push\"]\n op_jmp := opcode_values[\"jmp\"]\n op_jz := opcode_values[\"jz\"]\n\n return\n end\n\nend\n\nclass VirtualMachine(OpcodeCollection)\n\n public code\n public global_data\n public strings\n public stack\n public pc\n\n private static const whitespace_chars\n\n private static init()\n whitespace_chars := ' \\t\\n\\r\\f\\v'\n return\n end\n\n public read_assembly_code(f)\n local data_size, number_of_strings\n local line, ch\n local i\n local address\n local opcode\n\n # Read the header line.\n line := f.read() | bad_vm()\n line ? {\n tab(many(whitespace_chars))\n tab(match(\"Datasize\")) | bad_vm()\n tab(many(whitespace_chars))\n tab(any(':')) | bad_vm()\n tab(many(whitespace_chars))\n data_size :=\n integer(tab(many(&digits))) | bad_vm()\n tab(many(whitespace_chars))\n tab(match(\"Strings\")) | bad_vm()\n tab(many(whitespace_chars))\n tab(any(':')) | bad_vm()\n tab(many(whitespace_chars))\n number_of_strings :=\n integer(tab(many(&digits))) | bad_vm()\n }\n\n # Read the strings.\n strings := list(number_of_strings)\n every i := 1 to number_of_strings do {\n strings[i] := \"\"\n line := f.read() | bad_vm()\n line ? {\n tab(many(whitespace_chars))\n tab(any('\"')) | bad_vm()\n while ch := tab(any(~'\"')) do {\n if ch == '\\\\' then {\n ch := tab(any('n\\\\')) | bad_vm()\n strings[i] ||:=\n (if (ch == \"n\") then \"\\n\" else \"\\\\\")\n } else {\n strings[i] ||:= ch\n }\n }\n }\n }\n\n # Read the code.\n code := \"\"\n while line := f.read() do {\n line ? {\n tab(many(whitespace_chars))\n address := integer(tab(many(&digits))) | bad_vm()\n tab(many(whitespace_chars))\n opcode := tab(many(~whitespace_chars)) | bad_vm()\n code ||:= opcode_values[opcode]\n case opcode of {\n \"push\": {\n tab(many(whitespace_chars))\n code ||:=\n int2bytes(integer(tab(many(&digits)))) |\n int2bytes(integer(tab(any('-')) ||\n tab(many(&digits)))) |\n bad_vm()\n }\n \"fetch\" | \"store\": {\n tab(many(whitespace_chars))\n tab(any('[')) | bad_vm()\n tab(many(whitespace_chars))\n code ||:=\n int2bytes(integer(tab(many(&digits)))) |\n bad_vm()\n tab(many(whitespace_chars))\n tab(any(']')) | bad_vm()\n }\n \"jmp\" | \"jz\": {\n tab(many(whitespace_chars))\n tab(any('(')) | bad_vm()\n tab(many(whitespace_chars))\n code ||:=\n int2bytes(integer(tab(many(&digits)))) |\n int2bytes(integer(tab(any('-')) ||\n tab(many(&digits)))) |\n bad_vm()\n tab(many(whitespace_chars))\n tab(any(')')) | bad_vm()\n tab(many(whitespace_chars))\n tab(many(&digits)) | bad_vm()\n }\n default: {\n # Do nothing\n }\n }\n }\n }\n\n # Create a global data area.\n global_data := list(data_size, &null)\n\n initialize()\n\n return\n end\n\n public run(f_out)\n initialize()\n continue(f_out)\n return\n end\n\n public continue(f_out)\n while code[pc] ~== op_halt do\n step(f_out)\n end\n\n public step(f_out)\n local opcode\n\n opcode := code[pc]\n pc +:= 1\n case opcode of {\n op_add: binop(\"+\")\n op_sub: binop(\"-\")\n op_mul: binop(\"*\")\n op_div: binop(\"/\")\n op_mod: binop(\"%\")\n op_lt: comparison(\"<\")\n op_gt: comparison(\">\")\n op_le: comparison(\"<=\")\n op_ge: comparison(\">=\")\n op_eq: comparison(\"=\")\n op_ne: comparison(\"~=\")\n op_and: logical_and()\n op_or: logical_or()\n op_neg: negate()\n op_not: logical_not()\n op_prtc: printc(f_out)\n op_prti: printi(f_out)\n op_prts: prints(f_out)\n op_fetch: fetch_global()\n op_store: store_global()\n op_push: push_argument()\n op_jmp: jump()\n op_jz: jump_if_zero()\n default: bad_opcode()\n }\n end\n\n private negate()\n stack[1] := -stack[1]\n return\n end\n\n private binop(func)\n stack[2] := func(stack[2], stack[1])\n pop(stack)\n return\n end\n\n private comparison(func)\n stack[2] := (if func(stack[2], stack[1]) then 1 else 0)\n pop(stack)\n return\n end\n\n private logical_and()\n stack[2] := (if stack[2] ~= 0 & stack[1] ~= 0 then 1 else 0)\n pop(stack)\n return\n end\n\n private logical_or()\n stack[2] := (if stack[2] ~= 0 | stack[1] ~= 0 then 1 else 0)\n pop(stack)\n return\n end\n\n private logical_not()\n stack[1] := (if stack[1] ~= 0 then 0 else 1)\n return\n end\n\n private printc(f_out)\n /f_out := FileStream.stdout\n f_out.writes(char(pop(stack)))\n return\n end\n\n private printi(f_out)\n /f_out := FileStream.stdout\n f_out.writes(pop(stack))\n return\n end\n\n private prints(f_out)\n /f_out := FileStream.stdout\n f_out.writes(strings[pop(stack) + 1])\n return\n end\n\n private fetch_global()\n push(stack, global_data[get_argument() + 1])\n pc +:= 4\n return\n end\n\n private store_global()\n global_data[get_argument() + 1] := pop(stack)\n pc +:= 4\n return\n end\n\n private push_argument()\n push(stack, get_argument())\n pc +:= 4\n return\n end\n\n private jump()\n pc +:= get_argument()\n return\n end\n\n private jump_if_zero()\n if pop(stack) = 0 then\n pc +:= get_argument()\n else\n pc +:= 4\n return\n end\n\n private get_argument()\n return bytes2int(code, pc)\n end\n\n public initialize()\n # The program counter starts at 1, for convenient indexing into\n # the code[] array. Icon indexing starts at 1 (for a *very* good\n # reason, but that’s a topic for another day).\n pc := 1\n stack := []\n return\n end\n\n private bad_vm()\n write(FileStream.stderr, \"Bad VM.\")\n exit(1)\n end\n\n private bad_opcode()\n write(FileStream.stderr, \"Bad opcode.\")\n exit(1)\n end\nend\n", "language": "ObjectIcon" }, { "code": "#!/usr/bin/perl\n\n# http://www.rosettacode.org/wiki/Compiler/virtual_machine_interpreter\nuse strict; # vm.pl - run rosetta code\nuse warnings;\nuse integer;\n\nmy ($binary, $pc, @stack, @data) = ('', 0);\n\n<> =~ /Strings: (\\d+)/ or die \"bad header\";\nmy @strings = map <> =~ tr/\\n\"\"//dr =~ s/\\\\(.)/$1 eq 'n' ? \"\\n\" : $1/ger, 1..$1;\n\nsub value { unpack 'l', substr $binary, ($pc += 4) - 4, 4 }\n\nmy @ops = (\n [ halt => sub { exit } ],\n [ add => sub { $stack[-2] += pop @stack } ],\n [ sub => sub { $stack[-2] -= pop @stack } ],\n [ mul => sub { $stack[-2] *= pop @stack } ],\n [ div => sub { $stack[-2] /= pop @stack } ],\n [ mod => sub { $stack[-2] %= pop @stack } ],\n [ not => sub { $stack[-1] = $stack[-1] ? 0 : 1 } ],\n [ neg => sub { $stack[-1] = - $stack[-1] } ],\n [ and => sub { $stack[-2] &&= $stack[-1]; pop @stack } ],\n [ or => sub { $stack[-2] ||= $stack[-1]; pop @stack } ],\n [ lt => sub { $stack[-1] = $stack[-2] < pop @stack ? 1 : 0 } ],\n [ gt => sub { $stack[-1] = $stack[-2] > pop @stack ? 1 : 0 } ],\n [ le => sub { $stack[-1] = $stack[-2] <= pop @stack ? 1 : 0 } ],\n [ ge => sub { $stack[-1] = $stack[-2] >= pop @stack ? 1 : 0 } ],\n [ ne => sub { $stack[-1] = $stack[-2] != pop @stack ? 1 : 0 } ],\n [ eq => sub { $stack[-1] = $stack[-2] == pop @stack ? 1 : 0 } ],\n [ prts => sub { print $strings[pop @stack] } ],\n [ prti => sub { print pop @stack } ],\n [ prtc => sub { print chr pop @stack } ],\n [ store => sub { $data[value()] = pop @stack } ],\n [ fetch => sub { push @stack, $data[value()] // 0 } ],\n [ push => sub { push @stack, value() } ],\n [ jmp => sub { $pc += value() - 4 } ],\n [ jz => sub { $pc += pop @stack ? 4 : value() - 4 } ],\n );\nmy %op2n = map { $ops[$_][0], $_ } 0..$#ops; # map name to op number\n\nwhile(<>)\n {\n /^ *\\d+ +(\\w+)/ or die \"bad line $_\"; # format error\n $binary .= chr( $op2n{$1} // die \"$1 not defined\" ) . # op code\n (/\\((-?\\d+)\\)|(\\d+)]?$/ and pack 'l', $+); # 4 byte value\n }\n\n$ops[vec($binary, $pc++, 8)][1]->() while 1; # run it\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Compiler\\vm.exw\n -- ============================\n --\n -- Since we have generated executable machine code, the virtual machine, such as it is, is just\n -- the higher level implementations of printc/i/s, see setbuiltins() in cgen.e\n -- Otherwise the only difference between this and cgen.exw is call(code_mem) instead of decode().\n --\n -- A quick test (calculating fib(44) 10^6 times) suggests ~500 times faster than interp.exw -\n -- which is to be expected given that a single add instruction (1 clock) here is implemented as\n -- at least three (and quite possibly five!) resursive calls to interp() in the other.</span>\n\n <span style=\"color: #000000;\">format</span> <span style=\"color: #000000;\">PE32</span>\n <span style=\"color: #000080;font-style:italic;\">--format ELF32\n -- Note: cgen generates 32-bit machine code, which cannot be executed directly from a 64-bit interpreter.\n -- You can however, via the magic of either the above format directives, use a 64-bit version of\n -- Phix to compile this (just add a -c command line option) to a 32-bit executable, which can.\n -- It would not be particularly difficult to emit 32 or 64 bit code, but some source code files\n -- would, fairly obviously, then be very nearly twice as long, and a fair bit harder to read.</span>\n\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span> <span style=\"color: #000080;font-style:italic;\">-- (machine code!)</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">cgen</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cl</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">open_files</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cl</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">toks</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">lex</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">parse</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">code_gen</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">fixup</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">machine_bits</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #000000;\">32</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000080;font-style:italic;\">-- ^ as per note above</span>\n <span style=\"color: #000000;\">call</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">free</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">var_mem</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">code_mem</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">close_files</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000080;font-style:italic;\">--main(command_line())</span>\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"count.c\"</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%\n%%% The Rosetta Code Virtual Machine, for GNU Prolog.\n%%%\n%%% The following code uses GNU Prolog's extensions for global\n%%% variables.\n%%%\n%%% Usage: vm [INPUTFILE [OUTPUTFILE]]\n%%% The notation \"-\" means to use standard input or standard output.\n%%% Leaving out an argument is equivalent to specifying \"-\".\n%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nmake_and_run_machine(Input, Output) :-\n make_machine(Input),\n run_machine(Output).\n\nrun_machine(Output) :-\n repeat,\n next_instruction(Opcode, Arg),\n (Opcode == ('halt')\n -> true\n ; (run_instruction(Output, Opcode, Arg),\n fail % Backtracks to the 'repeat'.\n )).\n\nrun_instruction(Output, Opcode, Arg) :-\n (\n (Opcode == ('add'),\n pop_value(Y),\n pop_value(X),\n is(Z, X + Y),\n push_value(Z))\n ; (Opcode == ('sub'),\n pop_value(Y),\n pop_value(X),\n is(Z, X - Y),\n push_value(Z))\n ; (Opcode == ('mul'),\n pop_value(Y),\n pop_value(X),\n is(Z, X * Y),\n push_value(Z))\n ; (Opcode == ('div'),\n pop_value(Y),\n pop_value(X),\n is(Z, X // Y),\n push_value(Z))\n ; (Opcode == ('mod'),\n pop_value(Y),\n pop_value(X),\n is(Z, X rem Y),\n push_value(Z))\n ; (Opcode == ('lt'),\n pop_value(Y),\n pop_value(X),\n (X < Y -> Z = 1; Z = 0),\n push_value(Z))\n ; (Opcode == ('le'),\n pop_value(Y),\n pop_value(X),\n (X =< Y -> Z = 1; Z = 0),\n push_value(Z))\n ; (Opcode == ('gt'),\n pop_value(Y),\n pop_value(X),\n (X > Y -> Z = 1; Z = 0),\n push_value(Z))\n ; (Opcode == ('ge'),\n pop_value(Y),\n pop_value(X),\n (X >= Y -> Z = 1; Z = 0),\n push_value(Z))\n ; (Opcode == ('eq'),\n pop_value(Y),\n pop_value(X),\n (X =:= Y -> Z = 1; Z = 0),\n push_value(Z))\n ; (Opcode == ('ne'),\n pop_value(Y),\n pop_value(X),\n (X =\\= Y -> Z = 1; Z = 0),\n push_value(Z))\n ; (Opcode == ('and'),\n pop_value(Y),\n pop_value(X),\n ((X =\\= 0, Y =\\= 0) -> Z = 1; Z = 0),\n push_value(Z))\n ; (Opcode == ('or'),\n pop_value(Y),\n pop_value(X),\n ((X =\\= 0; Y =\\= 0) -> Z = 1; Z = 0),\n push_value(Z))\n ; (Opcode == ('neg'),\n pop_value(X),\n is(Z, -X),\n push_value(Z))\n ; (Opcode == ('not'),\n pop_value(X),\n (X =:= 0 -> Z = 1; Z = 0),\n push_value(Z))\n ; (Opcode == ('prtc'),\n pop_value(X),\n char_code(C, X),\n write(Output, C))\n ; (Opcode == ('prti'),\n pop_value(X),\n write(Output, X))\n ; (Opcode == ('prts'),\n pop_value(K),\n g_read(the_strings(K), S),\n write(Output, S))\n ; (Opcode == ('fetch'),\n g_read(the_data(Arg), X),\n push_value(X),\n skip_argument)\n ; (Opcode == ('store'),\n pop_value(X),\n g_assign(the_data(Arg), X),\n skip_argument)\n ; (Opcode == ('push'),\n push_value(Arg),\n skip_argument)\n ; (Opcode == ('jmp'),\n relative_jump(Arg))\n ; (Opcode == ('jz'),\n pop_value(X),\n (X =:= 0\n -> relative_jump(Arg)\n ; skip_argument))\n ).\n\nrelative_jump(Offset) :-\n g_read(the_program_counter, PC),\n is(PC1, PC + Offset),\n g_assign(the_program_counter, PC1).\n\nskip_argument :-\n g_read(the_program_counter, PC),\n is(PC1, PC + 4),\n g_assign(the_program_counter, PC1).\n\nnext_instruction(Opcode, Arg) :-\n g_read(the_program_counter, PC),\n is(PC1, PC + 1),\n g_assign(the_program_counter, PC1),\n g_read(the_code(PC), {Opcode, Arg}).\n\npush_value(X) :-\n g_read(the_stack_pointer, SP),\n is(SP1, SP + 1),\n g_assign(the_stack_pointer, SP1),\n g_assign(the_stack(SP), X).\n\npop_value(X) :-\n g_read(the_stack_pointer, SP),\n is(SP1, SP - 1),\n g_assign(the_stack_pointer, SP1),\n g_read(the_stack(SP1), X).\n\nmake_machine(Input) :-\n get_and_parse_the_header(Input, Datasize, Strings_Count),\n (Strings_Count =:= 0\n -> true\n ; get_and_parse_the_strings(Input, Strings_Count)),\n get_and_parse_the_instructions(Input),\n (Datasize =:= 0\n -> true\n ; g_assign(the_data, g_array(Datasize))),\n g_assign(the_stack, g_array(2048)),\n g_assign(the_stack_pointer, 0),\n g_assign(the_program_counter, 0).\n\nget_and_parse_the_header(Stream, Datasize, Strings_Count) :-\n get_line(Stream, Line, ('\\n')),\n parse_header(Line, Datasize, Strings_Count).\n\nget_and_parse_the_strings(Stream, Strings_Count) :-\n % Make 'the_strings' an array of the string literals.\n get_and_parse_the_strings(Stream, Strings_Count, Lst),\n g_assign(the_strings, g_array(Lst)).\nget_and_parse_the_strings(Stream, I, Lst) :-\n % Note: this implementation is non-tail recursive.\n (I == 0\n -> Lst = []\n ; (get_line(Stream, Line, ('\\n')),\n parse_string_literal(Line, S),\n is(I1, I - 1),\n get_and_parse_the_strings(Stream, I1, Lst1),\n Lst = [S | Lst1])).\n\nget_and_parse_the_instructions(Stream) :-\n get_and_parse_the_instructions(Stream, Lst),\n keysort(Lst, Lst1),\n last(Lst1, Addr_Max-_),\n is(Code_Size, Addr_Max + 5),\n g_assign(the_code, g_array(Code_Size, {('halt'), 0})),\n maplist(fill_instruction, Lst1).\nget_and_parse_the_instructions(Stream, Lst) :-\n get_and_parse_the_instructions(Stream, [], Lst).\nget_and_parse_the_instructions(Stream, Lst0, Lst) :-\n % This implementation is tail recursive. We consider the order of\n % the resulting list to be arbitrary.\n (get_line(Stream, Line, Terminal),\n drop_spaces(Line, S),\n (S = []\n -> (Terminal = end_of_file\n -> Lst = Lst0\n ; get_and_parse_the_instructions(Stream, Lst0, Lst))\n ; (parse_instruction(S, Address, Opcode, Arg),\n Instr = Address-{Opcode, Arg},\n (Terminal = end_of_file\n -> reverse([Instr | Lst0], Lst)\n ; get_and_parse_the_instructions(Stream, [Instr | Lst0],\n Lst))))).\n\nfill_instruction(Addr-Instr) :-\n g_assign(the_code(Addr), Instr).\n\nparse_header(Line, Datasize, Strings_Count) :-\n drop_nondigits(Line, Lst1),\n split_digits(Lst1, Datasize_Digits, Rest1),\n drop_nondigits(Rest1, Lst2),\n split_digits(Lst2, Strings_Digits, _Rest2),\n number_chars(Datasize, Datasize_Digits),\n number_chars(Strings_Count, Strings_Digits).\n\nparse_string_literal(Line, S) :-\n drop_spaces(Line, Lst1),\n Lst1 = ['\"' | Lst2],\n rework_escape_sequences(Lst2, Lst3),\n atom_chars(S, Lst3).\n\nrework_escape_sequences(Lst0, Lst) :-\n (Lst0 = [('\"') | _]\n -> Lst = []\n ; (Lst0 = [('\\\\'), ('n') | Tail1]\n -> (rework_escape_sequences(Tail1, Lst1),\n Lst = [('\\n') | Lst1])\n ; (Lst0 = [('\\\\'), ('\\\\') | Tail1]\n -> (rework_escape_sequences(Tail1, Lst1),\n Lst = [('\\\\') | Lst1])\n ; (Lst0 = [C | Tail1],\n rework_escape_sequences(Tail1, Lst1),\n Lst = [C | Lst1])))).\n\nparse_instruction(Line, Address, Opcode, Arg) :-\n drop_spaces(Line, Lst1),\n split_digits(Lst1, Address_Digits, Rest1),\n number_chars(Address, Address_Digits),\n drop_spaces(Rest1, Lst2),\n split_nonspaces(Lst2, Opcode_Chars, Rest2),\n atom_chars(Opcode, Opcode_Chars),\n drop_spaces(Rest2, Lst3),\n (Lst3 = []\n -> Arg = 0\n ; (Lst3 = [C | Rest3],\n (is_digit(C)\n -> (split_digits(Lst3, Arg_Chars, _),\n number_chars(Arg, Arg_Chars))\n ; (C = ('(')\n -> (split_before_char((')'), Rest3, Arg_Chars, _),\n number_chars(Arg, Arg_Chars))\n ; (C = ('['),\n split_before_char((']'), Rest3, Arg_Chars, _),\n number_chars(Arg, Arg_Chars)))))).\n\nis_space(C) :-\n (C = (' '); C = ('\\t'); C = ('\\n');\n C = ('\\v'); C = ('\\f'); C = ('\\r')).\n\nis_digit(C) :-\n (C = ('0'); C = ('1'); C = ('2'); C = ('3'); C = ('4');\n C = ('5'); C = ('6'); C = ('7'); C = ('8'); C = ('9')).\n\ndrop_spaces([], Lst) :-\n Lst = [].\ndrop_spaces([C | Tail], Lst) :-\n (is_space(C)\n -> drop_spaces(Tail, Lst)\n ; Lst = [C | Tail]).\n\ndrop_nondigits([], Lst) :-\n Lst = [].\ndrop_nondigits([C | Tail], Lst) :-\n (is_digit(C)\n -> Lst = [C | Tail]\n ; drop_nondigits(Tail, Lst)).\n\nsplit_nonspaces([], Word, Rest) :-\n (Word = [], Rest = []).\nsplit_nonspaces([C | Tail], Word, Rest) :-\n (is_space(C)\n -> (Word = [], Rest = [C | Tail])\n ; (split_nonspaces(Tail, Word1, Rest),\n Word = [C | Word1])).\n\nsplit_digits([], Digits, Rest) :-\n (Digits = [], Rest = []).\nsplit_digits([C | Tail], Digits, Rest) :-\n (is_digit(C)\n -> (split_digits(Tail, Digits1, Rest),\n Digits = [C | Digits1])\n ; (Digits = [], Rest = [C | Tail])).\n\nsplit_before_char(_, [], Before, After) :-\n (Before = [], After = []).\nsplit_before_char(C, [C1 | Rest], Before, After) :-\n (C = C1\n -> (Before = [], After = [C1 | Rest])\n ; (split_before_char(C, Rest, Before1, After),\n Before = [C1 | Before1])).\n\nget_line(Stream, Line, Terminal) :-\n % Reads a line of input as a list of characters. The character that\n % terminates the line is returned separately; it may be either '\\n'\n % or end_of_file.\n get_line_chars(Stream, [], Line, Terminal).\n\nget_line_chars(Stream, Chars0, Chars, Terminal) :-\n % Helper predicate for get_line.\n get_char(Stream, C),\n ((C = end_of_file; C = ('\\n'))\n -> (reverse(Chars0, Chars), Terminal = C)\n ; get_line_chars(Stream, [C | Chars0], Chars, Terminal)).\n\nmain(Args) :-\n (Args = []\n -> current_input(Input),\n current_output(Output),\n make_and_run_machine(Input, Output)\n ; (Args = [Inp_Name]\n -> (Inp_Name = ('-')\n -> main([])\n ; (open(Inp_Name, 'read', Input),\n current_output(Output),\n make_and_run_machine(Input, Output),\n close(Input)))\n ; (Args = [Inp_Name, Out_Name | _],\n (Inp_Name = ('-')\n -> (Out_Name = ('-')\n -> main([])\n ; (current_input(Input),\n open(Out_Name, 'write', Output),\n make_and_run_machine(Input, Output),\n close(Output)))\n ; (Out_Name = ('-')\n -> main([Inp_Name])\n ; (open(Inp_Name, 'read', Input),\n open(Out_Name, 'write', Output),\n make_and_run_machine(Input, Output),\n close(Input),\n close(Output))))))).\n\nmain :-\n argument_list(Args),\n main(Args).\n\n:- initialization(main).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Instructions for GNU Emacs--\n%%% local variables:\n%%% mode: prolog\n%%% prolog-indent-width: 2\n%%% end:\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "language": "Phix" }, { "code": "from __future__ import print_function\nimport sys, struct\n\nFETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, \\\nJMP, JZ, PRTC, PRTS, PRTI, HALT = range(24)\n\ncode_map = {\n \"fetch\": FETCH,\n \"store\": STORE,\n \"push\": PUSH,\n \"add\": ADD,\n \"sub\": SUB,\n \"mul\": MUL,\n \"div\": DIV,\n \"mod\": MOD,\n \"lt\": LT,\n \"gt\": GT,\n \"le\": LE,\n \"ge\": GE,\n \"eq\": EQ,\n \"ne\": NE,\n \"and\": AND,\n \"or\": OR,\n \"not\": NOT,\n \"neg\": NEG,\n \"jmp\": JMP,\n \"jz\": JZ,\n \"prtc\": PRTC,\n \"prts\": PRTS,\n \"prti\": PRTI,\n \"halt\": HALT\n}\n\ninput_file = None\ncode = bytearray()\nstring_pool = []\nword_size = 4\n\n#*** show error and exit\ndef error(msg):\n print(\"%s\" % (msg))\n exit(1)\n\ndef int_to_bytes(val):\n return struct.pack(\"<i\", val)\n\ndef bytes_to_int(bstr):\n return struct.unpack(\"<i\", bstr)\n\n#***\ndef emit_byte(x):\n code.append(x)\n\n#***\ndef emit_word(x):\n s = int_to_bytes(x)\n for x in s:\n code.append(x)\n\n#***\ndef run_vm(data_size):\n stack = [0 for i in range(data_size + 1)]\n pc = 0\n while True:\n op = code[pc]\n pc += 1\n\n if op == FETCH:\n stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);\n pc += word_size\n elif op == STORE:\n stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();\n pc += word_size\n elif op == PUSH:\n stack.append(bytes_to_int(code[pc:pc+word_size])[0]);\n pc += word_size\n elif op == ADD: stack[-2] += stack[-1]; stack.pop()\n elif op == SUB: stack[-2] -= stack[-1]; stack.pop()\n elif op == MUL: stack[-2] *= stack[-1]; stack.pop()\n # use C like division semantics\n elif op == DIV: stack[-2] = int(float(stack[-2]) / stack[-1]); stack.pop()\n elif op == MOD: stack[-2] = int(float(stack[-2]) % stack[-1]); stack.pop()\n elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop()\n elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop()\n elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop()\n elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop()\n elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop()\n elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop()\n elif op == NEG: stack[-1] = -stack[-1]\n elif op == NOT: stack[-1] = not stack[-1]\n elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0]\n elif op == JZ:\n if stack.pop():\n pc += word_size\n else:\n pc += bytes_to_int(code[pc:pc+word_size])[0]\n elif op == PRTC: print(\"%c\" % (stack[-1]), end=''); stack.pop()\n elif op == PRTS: print(\"%s\" % (string_pool[stack[-1]]), end=''); stack.pop()\n elif op == PRTI: print(\"%d\" % (stack[-1]), end=''); stack.pop()\n elif op == HALT: break\n\ndef str_trans(srce):\n dest = \"\"\n i = 0\n while i < len(srce):\n if srce[i] == '\\\\' and i + 1 < len(srce):\n if srce[i + 1] == 'n':\n dest += '\\n'\n i += 2\n elif srce[i + 1] == '\\\\':\n dest += '\\\\'\n i += 2\n else:\n dest += srce[i]\n i += 1\n\n return dest\n\n#***\ndef load_code():\n global string_pool\n\n line = input_file.readline()\n if len(line) == 0:\n error(\"empty line\")\n\n line_list = line.split()\n data_size = int(line_list[1])\n n_strings = int(line_list[3])\n\n for i in range(n_strings):\n string_pool.append(str_trans(input_file.readline().strip('\"\\n')))\n\n while True:\n line = input_file.readline()\n if len(line) == 0:\n break\n line_list = line.split()\n offset = int(line_list[0])\n instr = line_list[1]\n opcode = code_map.get(instr)\n if opcode == None:\n error(\"Unknown instruction %s at %d\" % (instr, offset))\n emit_byte(opcode)\n if opcode in [JMP, JZ]:\n p = int(line_list[3])\n emit_word(p - (offset + 1))\n elif opcode == PUSH:\n value = int(line_list[2])\n emit_word(value)\n elif opcode in [FETCH, STORE]:\n value = int(line_list[2].strip('[]'))\n emit_word(value)\n\n return data_size\n\n#*** main driver\ninput_file = sys.stdin\nif len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], \"r\", 4096)\n except IOError as e:\n error(0, 0, \"Can't open %s\" % sys.argv[1])\n\ndata_size = load_code()\nrun_vm(data_size)\n", "language": "Python" }, { "code": "#lang typed/racket\n;;;\n;;; The Rosetta Code Virtual Machine, in Typed Racket.\n;;;\n;;; Migrated from the Common Lisp.\n;;;\n\n;;; Yes, I could compute how much memory is needed, or I could assume\n;;; that the instructions are in address order. However, for *this*\n;;; implementation I am going to use a large fixed-size memory and use\n;;; the address fields of instructions to place the instructions.\n(: executable-memory-size Positive-Fixnum)\n(define executable-memory-size 65536)\n\n;;; Similarly, I am going to have fixed size data and stack memory.\n(: data-memory-size Positive-Fixnum)\n(define data-memory-size 2048)\n(: stack-memory-size Positive-Fixnum)\n(define stack-memory-size 2048)\n\n;;; And so I am going to have specialized types for the different\n;;; kinds of memory the platform contains. Also for its \"word\" and\n;;; register types.\n(define-type Word Nonnegative-Fixnum)\n(define-type Register (Boxof Word))\n(define-type Executable-Memory (Mutable-Vectorof Byte))\n(define-type Data-Memory (Mutable-Vectorof Word))\n(define-type Stack-Memory (Mutable-Vectorof Word))\n\n(define re-blank-line #px\"^\\\\s*$\")\n(define re-parse-instr-1 #px\"^\\\\s*(\\\\d+)\\\\s*(.*\\\\S)\")\n(define re-parse-instr-2 #px\"(?i:^(\\\\S+)\\\\s*(.*))\")\n(define re-parse-instr-3 #px\"^[[(]?([0-9-]+)\")\n(define re-header\n #px\"(?i:^\\\\s*Datasize\\\\s*:\\\\s*(\\\\d+)\\\\s*Strings\\\\s*:\\\\s*(\\\\d+))\")\n(define re-leading-spaces #px\"^\\\\s*\")\n\n(define opcode-names\n '(\"halt\"\n \"add\"\n \"sub\"\n \"mul\"\n \"div\"\n \"mod\"\n \"lt\"\n \"gt\"\n \"le\"\n \"ge\"\n \"eq\"\n \"ne\"\n \"and\"\n \"or\"\n \"neg\"\n \"not\"\n \"prtc\"\n \"prti\"\n \"prts\"\n \"fetch\"\n \"store\"\n \"push\"\n \"jmp\"\n \"jz\"))\n\n(: blank-line? (String -> Boolean))\n(define (blank-line? s)\n (not (not (regexp-match re-blank-line s))))\n\n(: opcode-from-name (String -> Byte))\n(define (opcode-from-name s)\n (let ((i (index-of opcode-names s)))\n (assert i)\n (cast i Byte)))\n\n(: create-executable-memory (-> Executable-Memory))\n(define (create-executable-memory)\n (make-vector executable-memory-size (opcode-from-name \"halt\")))\n\n(: create-data-memory (-> Data-Memory))\n(define (create-data-memory)\n (make-vector data-memory-size 0))\n\n(: create-stack-memory (-> Stack-Memory))\n(define (create-stack-memory)\n (make-vector stack-memory-size 0))\n\n(: create-register (-> Register))\n(define (create-register)\n (box 0))\n\n(struct machine\n ((sp : Register) ; Stack pointer.\n (ip : Register) ; Instruction pointer (that is, program counter).\n (code : Executable-Memory)\n (data : Data-Memory)\n (stack : Stack-Memory)\n (strings : (Immutable-Vectorof String))\n (output : Output-Port))\n #:type-name Machine\n #:constructor-name %make-machine)\n\n(: make-machine ((Immutable-Vectorof String) Output-Port -> Machine))\n(define (make-machine strings outf)\n (%make-machine (create-register)\n (create-register)\n (create-executable-memory)\n (create-data-memory)\n (create-stack-memory)\n strings\n outf))\n\n(define-type Instruction-Data (List Word Byte (U False Word)))\n\n(: insert-instruction (Executable-Memory Instruction-Data -> Void))\n(define (insert-instruction memory instr)\n (void\n (match instr\n ((list address opcode arg)\n (let ((instr-size (if arg 5 1)))\n (unless (<= (+ address instr-size) executable-memory-size)\n (raise-user-error\n \"the VM's executable memory size is exceeded\"))\n (vector-set! memory address opcode)\n (when arg\n ;; Big-endian order.\n (vector-set! memory (+ address 1)\n (bitwise-and (arithmetic-shift arg -24) #xFF))\n (vector-set! memory (+ address 2)\n (bitwise-and (arithmetic-shift arg -16) #xFF))\n (vector-set! memory (+ address 3)\n (bitwise-and (arithmetic-shift arg -8) #xFF))\n (vector-set! memory (+ address 4)\n (bitwise-and arg #xFF))))))))\n\n(: load-executable-memory (Executable-Memory\n (Listof Instruction-Data) ->\n Void))\n(define (load-executable-memory memory instr-lst)\n (let loop ((p instr-lst))\n (if (null? p)\n (void)\n (let ((instr (car p)))\n (insert-instruction memory (car p))\n (loop (cdr p))))))\n\n(: number->word (Number -> Word))\n(define (number->word n)\n (cast (bitwise-and (cast n Integer) #xFFFFFFFF) Word))\n\n(: string->word (String -> Word))\n(define (string->word s)\n (let ((n (string->number s)))\n (assert (number? n))\n (number->word n)))\n\n(: parse-instruction (String -> (U False Instruction-Data)))\n(define (parse-instruction s)\n (and (not (blank-line? s))\n (let* ((strings (cast (regexp-match re-parse-instr-1 s)\n (Listof String)))\n (address (cast (string->number (second strings))\n Word))\n (split (cast (regexp-match re-parse-instr-2\n (third strings))\n (Listof String)))\n (opcode-name (string-downcase (second split)))\n (opcode (opcode-from-name opcode-name))\n (arguments (third split))\n (has-arg? (match opcode-name\n ((or \"fetch\" \"store\" \"push\" \"jmp\" \"jz\") #t)\n (_ #f))))\n (if has-arg?\n (let* ((argstr-lst\n (cast (regexp-match re-parse-instr-3 arguments)\n (Listof String)))\n (argstr (second argstr-lst))\n (arg (string->word argstr)))\n `(,address ,opcode ,arg))\n `(,address ,opcode #f)))))\n\n(: read-instructions (Input-Port -> (Listof Instruction-Data)))\n(define (read-instructions inpf)\n (let loop ((line (read-line inpf))\n (lst (cast '() (Listof Instruction-Data))))\n (if (eof-object? line)\n (reverse lst)\n (let ((instr (parse-instruction line)))\n (loop (read-line inpf)\n (if instr\n (cons instr lst)\n lst))))))\n\n(: read-datasize-and-strings-count (Input-Port -> (Values Word Word)))\n(define (read-datasize-and-strings-count inpf)\n (let ((line (read-line inpf)))\n (unless (string? line)\n (raise-user-error \"empty input\"))\n ;; This is a permissive implementation.\n (let* ((strings (cast (regexp-match re-header line)\n (Listof String)))\n (datasize (string->word (second strings)))\n (strings-count (string->word (third strings))))\n (values datasize strings-count))))\n\n(: parse-string-literal (String -> String))\n(define (parse-string-literal s)\n ;; This is a permissive implementation, but only in that it skips\n ;; any leading space. It does not check carefully for outright\n ;; mistakes.\n (let* ((s (regexp-replace re-leading-spaces s \"\"))\n (quote-mark (string-ref s 0)))\n (let loop ((i 1)\n (lst (cast '() (Listof Char))))\n (if (char=? (string-ref s i) quote-mark)\n (list->string (reverse lst))\n (let ((c (string-ref s i)))\n (if (char=? c #\\\\)\n (let ((c0 (match (string-ref s (+ i 1))\n (#\\n #\\newline)\n (c1 c1))))\n (loop (+ i 2) (cons c0 lst)))\n (loop (+ i 1) (cons c lst))))))))\n\n(: read-string-literals (Input-Port Word -> (Listof String)))\n(define (read-string-literals inpf strings-count)\n (for/list ((i (in-range strings-count)))\n (let ((line (read-line inpf)))\n (begin (assert (string? line))\n (parse-string-literal line)))))\n\n(: open-inpf (String -> Input-Port))\n(define (open-inpf inpf-filename)\n (if (string=? inpf-filename \"-\")\n (current-input-port)\n (open-input-file inpf-filename)))\n\n(: open-outf (String -> Output-Port))\n(define (open-outf outf-filename)\n (if (string=? outf-filename \"-\")\n (current-output-port)\n (open-output-file outf-filename #:exists 'truncate)))\n\n(: word-signbit? (Word -> Boolean))\n(define (word-signbit? x)\n ;; True if and only if the sign bit is set.\n (not (zero? (bitwise-and x #x80000000))))\n\n(: word-add (Word Word -> Word))\n(define (word-add x y)\n ;; Addition with overflow freely allowed.\n (cast (bitwise-and (+ x y) #xFFFFFFFF) Word))\n\n(: word-neg (Word -> Word))\n(define (word-neg x)\n ;; The two's complement.\n (word-add (cast (bitwise-xor x #xFFFFFFFF) Word) 1))\n\n(: word-sub (Word Word -> Word))\n(define (word-sub x y)\n ;; Subtraction with overflow freely allowed.\n (word-add x (word-neg y)))\n\n(: word-mul (Word Word -> Word))\n(define (word-mul x y)\n ;; Signed multiplication.\n (let ((x<0 (word-signbit? x))\n (y<0 (word-signbit? y)))\n (let ((abs-x (if x<0 (word-neg x) x))\n (abs-y (if y<0 (word-neg y) y)))\n (let* ((abs-xy (cast (bitwise-and (* abs-x abs-y) #xFFFFFFFF)\n Word)))\n (if x<0\n (if y<0 abs-xy (word-neg abs-xy))\n (if y<0 (word-neg abs-xy) abs-xy))))))\n\n(: word-div (Word Word -> Word))\n(define (word-div x y)\n ;; The quotient after signed integer division with truncation\n ;; towards zero.\n (let ((x<0 (word-signbit? x))\n (y<0 (word-signbit? y)))\n (let ((abs-x (if x<0 (word-neg x) x))\n (abs-y (if y<0 (word-neg y) y)))\n (let* ((abs-x/y (cast (bitwise-and (quotient abs-x abs-y)\n #xFFFFFFFF)\n Word)))\n (if x<0\n (if y<0 abs-x/y (word-neg abs-x/y))\n (if y<0 (word-neg abs-x/y) abs-x/y))))))\n\n(: word-mod (Word Word -> Word))\n(define (word-mod x y)\n ;; The remainder after signed integer division with truncation\n ;; towards zero.\n (let ((x<0 (word-signbit? x))\n (y<0 (word-signbit? y)))\n (let ((abs-x (if x<0 (word-neg x) x))\n (abs-y (if y<0 (word-neg y) y)))\n (let* ((abs-x/y (cast (bitwise-and (remainder abs-x abs-y)\n #xFFFFFFFF)\n Word)))\n (if x<0\n (if y<0 abs-x/y (word-neg abs-x/y))\n (if y<0 (word-neg abs-x/y) abs-x/y))))))\n\n(: b2i (Boolean -> (U Zero One)))\n(define (b2i b)\n (if b 1 0))\n\n(: word-lt (Word Word -> Word))\n(define (word-lt x y)\n ;; Signed comparison: is x less than y?\n (let ((x<0 (word-signbit? x))\n (y<0 (word-signbit? y)))\n (b2i (if x<0\n (if y<0 (< x y) #t)\n (if y<0 #f (< x y))))))\n\n(: word-le (Word Word -> Word))\n(define (word-le x y)\n ;; Signed comparison: is x less than or equal to y?\n (let ((x<0 (word-signbit? x))\n (y<0 (word-signbit? y)))\n (b2i (if x<0\n (if y<0 (<= x y) #t)\n (if y<0 #f (<= x y))))))\n\n(: word-gt (Word Word -> Word))\n(define (word-gt x y)\n ;; Signed comparison: is x greater than y?\n (let ((x<0 (word-signbit? x))\n (y<0 (word-signbit? y)))\n (b2i (if x<0\n (if y<0 (> x y) #f)\n (if y<0 #t (> x y))))))\n\n(: word-ge (Word Word -> Word))\n(define (word-ge x y)\n ;; Signed comparison: is x greater than or equal to y?\n (let ((x<0 (word-signbit? x))\n (y<0 (word-signbit? y)))\n (b2i (if x<0\n (if y<0 (>= x y) #f)\n (if y<0 #t (>= x y))))))\n\n(: word-eq (Word Word -> Word))\n(define (word-eq x y)\n ;; Is x equal to y?\n (b2i (= x y)))\n\n(: word-ne (Word Word -> Word))\n(define (word-ne x y)\n ;; Is x not equal to y?\n (b2i (not (= x y))))\n\n(: word-cmp (Word -> Word))\n(define (word-cmp x)\n ;; The logical complement.\n (b2i (zero? x)))\n\n(: word-and (Word Word -> Word))\n(define (word-and x y)\n ;; The logical conjunction.\n (b2i (and (not (zero? x)) (not (zero? y)))))\n\n(: word-or (Word Word -> Word))\n(define (word-or x y)\n ;; The logical disjunction.\n (b2i (or (not (zero? x)) (not (zero? y)))))\n\n(: unop (Stack-Memory Register (Word -> Word) -> Void))\n(define (unop stack sp operation)\n ;; Perform a unary operation on the stack.\n (let ((i (unbox sp)))\n (unless (<= 1 i)\n (raise-user-error \"stack underflow\"))\n (let ((x (vector-ref stack (- i 1))))\n ;; Note how, in contrast to Common Lisp, \"operation\" is not in a\n ;; namespace separate from that of \"ordinary\" values, such as\n ;; numbers and strings. (Which way is \"better\" is a matter of\n ;; taste, and probably depends mostly on what \"functional\"\n ;; language one learnt first. Mine was Caml Light, so I prefer\n ;; the Scheme way. :) )\n (vector-set! stack (- i 1) (operation x)))))\n\n(: binop (Stack-Memory Register (Word Word -> Word) -> Void))\n(define (binop stack sp operation)\n ;; Perform a binary operation on the stack.\n (let ((i (unbox sp)))\n (unless (<= 2 i)\n (raise-user-error \"stack underflow\"))\n (let ((x (vector-ref stack (- i 2)))\n (y (vector-ref stack (- i 1))))\n (vector-set! stack (- i 2) (operation x y)))\n (set-box! sp (cast (- i 1) Word))))\n\n(: jri (Executable-Memory Register -> Void))\n(define (jri code ip)\n ;; Jump relative immediate.\n (let ((j (unbox ip)))\n (unless (<= (+ j 4) executable-memory-size)\n (raise-user-error \"address past end of executable memory\"))\n ;; Big-endian order.\n (let* ((offset (vector-ref code (+ j 3)))\n (offset (bitwise-ior\n (arithmetic-shift (vector-ref code (+ j 2)) 8)\n offset))\n (offset (bitwise-ior\n (arithmetic-shift (vector-ref code (+ j 1)) 16)\n offset))\n (offset (bitwise-ior\n (arithmetic-shift (vector-ref code j) 24)\n offset)))\n (set-box! ip (word-add j (cast offset Word))))))\n\n(: jriz (Stack-Memory Register Executable-Memory Register -> Void))\n(define (jriz stack sp code ip)\n ;; Jump relative immediate, if zero.\n (let ((i (unbox sp)))\n (unless (<= 1 i)\n (raise-user-error \"stack underflow\"))\n (let ((x (vector-ref stack (- i 1))))\n (set-box! sp (- i 1))\n (if (zero? x)\n (jri code ip)\n (let ((j (unbox ip)))\n (set-box! ip (cast (+ j 4) Word)))))))\n\n(: get-immediate-value (Executable-Memory Register -> Word))\n(define (get-immediate-value code ip)\n (let ((j (unbox ip)))\n (unless (<= (+ j 4) executable-memory-size)\n (raise-user-error \"address past end of executable memory\"))\n ;; Big-endian order.\n (let* ((x (vector-ref code (+ j 3)))\n (x (bitwise-ior\n (arithmetic-shift (vector-ref code (+ j 2)) 8)\n x))\n (x (bitwise-ior\n (arithmetic-shift (vector-ref code (+ j 1)) 16)\n x))\n (x (bitwise-ior\n (arithmetic-shift (vector-ref code j) 24)\n x)))\n (set-box! ip (cast (+ j 4) Word))\n (cast x Word))))\n\n(: pushi (Stack-Memory Register Executable-Memory Register -> Void))\n(define (pushi stack sp code ip)\n ;; Push-immediate a value from executable memory onto the stack.\n (let ((i (unbox sp)))\n (unless (< i stack-memory-size)\n (raise-user-error \"stack overflow\"))\n (vector-set! stack i (get-immediate-value code ip))\n (set-box! sp (cast (+ i 1) Word))))\n\n(: fetch (Stack-Memory\n Register Executable-Memory Register\n Data-Memory -> Void))\n(define (fetch stack sp code ip data)\n ;; Fetch data to the stack, using the storage location given in\n ;; executable memory.\n (let ((i (unbox sp)))\n (unless (< i stack-memory-size)\n (raise-user-error \"stack overflow\"))\n (let* ((k (get-immediate-value code ip))\n (x (vector-ref data k)))\n (vector-set! stack i x)\n (set-box! sp (cast (+ i 1) Word)))))\n\n(: pop-one (Stack-Memory Register -> Word))\n(define (pop-one stack sp)\n (let ((i (unbox sp)))\n (unless (<= 1 i)\n (raise-user-error \"stack underflow\"))\n (let* ((x (vector-ref stack (- i 1))))\n (set-box! sp (- i 1))\n x)))\n\n(: store (Stack-Memory\n Register Executable-Memory Register\n Data-Memory -> Void))\n(define (store stack sp code ip data)\n ;; Store data from the stack, using the storage location given in\n ;; executable memory.\n (let ((i (unbox sp)))\n (unless (<= 1 i)\n (raise-user-error \"stack underflow\"))\n (let ((k (get-immediate-value code ip))\n (x (pop-one stack sp)))\n (vector-set! data k x))))\n\n(: prti (Stack-Memory Register Output-Port -> Void))\n(define (prti stack sp outf)\n ;; Print the top value of the stack, as a signed decimal value.\n (let* ((n (pop-one stack sp))\n (n<0 (word-signbit? n)))\n (if n<0\n (begin (display \"-\" outf)\n (display (word-neg n) outf))\n (display n outf))))\n\n(: prtc (Stack-Memory Register Output-Port -> Void))\n(define (prtc stack sp outf)\n ;; Print the top value of the stack, as a character.\n (let ((c (pop-one stack sp)))\n (display (integer->char c) outf)))\n\n(: prts (Stack-Memory\n Register (Immutable-Vectorof String) Output-Port -> Void))\n(define (prts stack sp strings outf)\n ;; Print the string specified by the top of the stack.\n (let* ((k (pop-one stack sp))\n (s (vector-ref strings k)))\n (display s outf)))\n\n;;\n;; I have written macros in the standard R6RS fashion, with a lambda\n;; and syntax-case, so the examples may be widely illustrative. Racket\n;; supports this style, despite (purposely) not adhering to any Scheme\n;; standard.\n;;\n;; Some Schemes that do not provide syntax-case (CHICKEN, for\n;; instance) provide alternatives that may be quite different.\n;;\n;; R5RS and R7RS require only syntax-rules, which cannot do what we\n;; are doing here. (What we are doing is similar to using ## in a\n;; modern C macro, except that the pieces are not merely raw text, and\n;; they must be properly typed at every stage.)\n;;\n(define-syntax define-machine-binop\n (lambda (stx)\n (syntax-case stx ()\n ((_ op)\n (let* ((op^ (syntax->datum #'op))\n (machine-op (string-append \"machine-\" op^))\n (machine-op (string->symbol machine-op))\n (machine-op (datum->syntax stx machine-op))\n (word-op (string-append \"word-\" op^))\n (word-op (string->symbol word-op))\n (word-op (datum->syntax stx word-op)))\n #`(begin\n (: #,machine-op (Machine -> Void))\n (define (#,machine-op mach)\n (binop (machine-stack mach)\n (machine-sp mach)\n #,word-op))))))))\n\n(define-syntax define-machine-unop\n (lambda (stx)\n (syntax-case stx ()\n ((_ op)\n (let* ((op^ (syntax->datum #'op))\n (machine-op (string-append \"machine-\" op^))\n (machine-op (string->symbol machine-op))\n (machine-op (datum->syntax stx machine-op))\n (word-op (string-append \"word-\" op^))\n (word-op (string->symbol word-op))\n (word-op (datum->syntax stx word-op)))\n #`(begin\n (: #,machine-op (Machine -> Void))\n (define (#,machine-op mach)\n (unop (machine-stack mach)\n (machine-sp mach)\n #,word-op))))))))\n\n(define-machine-binop \"add\")\n(define-machine-binop \"sub\")\n(define-machine-binop \"mul\")\n(define-machine-binop \"div\")\n(define-machine-binop \"mod\")\n(define-machine-binop \"lt\")\n(define-machine-binop \"gt\")\n(define-machine-binop \"le\")\n(define-machine-binop \"ge\")\n(define-machine-binop \"eq\")\n(define-machine-binop \"ne\")\n(define-machine-binop \"and\")\n(define-machine-binop \"or\")\n\n(define-machine-unop \"neg\")\n\n(: machine-not (Machine -> Void))\n(define (machine-not mach)\n (unop (machine-stack mach)\n (machine-sp mach)\n word-cmp))\n\n(: machine-prtc (Machine -> Void))\n(define (machine-prtc mach)\n (prtc (machine-stack mach)\n (machine-sp mach)\n (machine-output mach)))\n\n(: machine-prti (Machine -> Void))\n(define (machine-prti mach)\n (prti (machine-stack mach)\n (machine-sp mach)\n (machine-output mach)))\n\n(: machine-prts (Machine -> Void))\n(define (machine-prts mach)\n (prts (machine-stack mach)\n (machine-sp mach)\n (machine-strings mach)\n (machine-output mach)))\n\n(: machine-fetch (Machine -> Void))\n(define (machine-fetch mach)\n (fetch (machine-stack mach)\n (machine-sp mach)\n (machine-code mach)\n (machine-ip mach)\n (machine-data mach)))\n\n(: machine-store (Machine -> Void))\n(define (machine-store mach)\n (store (machine-stack mach)\n (machine-sp mach)\n (machine-code mach)\n (machine-ip mach)\n (machine-data mach)))\n\n(: machine-push (Machine -> Void))\n(define (machine-push mach)\n (pushi (machine-stack mach)\n (machine-sp mach)\n (machine-code mach)\n (machine-ip mach)))\n\n(: machine-jmp (Machine -> Void))\n(define (machine-jmp mach)\n (jri (machine-code mach)\n (machine-ip mach)))\n\n(: machine-jz (Machine -> Void))\n(define (machine-jz mach)\n (jriz (machine-stack mach)\n (machine-sp mach)\n (machine-code mach)\n (machine-ip mach)))\n\n(: get-opcode (Machine -> Byte))\n(define (get-opcode mach)\n (let ((code (machine-code mach))\n (ip (machine-ip mach)))\n (let ((j (unbox ip)))\n (unless (< j executable-memory-size)\n (raise-user-error \"address past end of executable memory\"))\n (let ((opcode (vector-ref code j)))\n (set-box! ip (cast (+ j 1) Word))\n opcode))))\n\n(: run-instruction (Machine Byte -> Void))\n(define (run-instruction mach opcode)\n (let ((op-mod-4 (bitwise-and opcode #x3))\n (op-div-4 (arithmetic-shift opcode -2)))\n (match op-div-4\n (0 (match op-mod-4\n (1 (machine-add mach))\n (2 (machine-sub mach))\n (3 (machine-mul mach))))\n (1 (match op-mod-4\n (0 (machine-div mach))\n (1 (machine-mod mach))\n (2 (machine-lt mach))\n (3 (machine-gt mach))))\n (2 (match op-mod-4\n (0 (machine-le mach))\n (1 (machine-ge mach))\n (2 (machine-eq mach))\n (3 (machine-ne mach))))\n (3 (match op-mod-4\n (0 (machine-and mach))\n (1 (machine-or mach))\n (2 (machine-neg mach))\n (3 (machine-not mach))))\n (4 (match op-mod-4\n (0 (machine-prtc mach))\n (1 (machine-prti mach))\n (2 (machine-prts mach))\n (3 (machine-fetch mach))))\n (5 (match op-mod-4\n (0 (machine-store mach))\n (1 (machine-push mach))\n (2 (machine-jmp mach))\n (3 (machine-jz mach)))))))\n\n(: run-vm (Machine -> Void))\n(define (run-vm mach)\n (let ((opcode-for-halt (cast (opcode-from-name \"halt\") Byte))\n (opcode-for-add (cast (opcode-from-name \"add\") Byte))\n (opcode-for-jz (cast (opcode-from-name \"jz\") Byte)))\n (let loop ((opcode (get-opcode mach)))\n (unless (= opcode opcode-for-halt)\n (begin\n (when (or (< opcode opcode-for-add)\n (< opcode-for-jz opcode))\n (raise-user-error \"unsupported opcode\"))\n (run-instruction mach opcode)\n (loop (get-opcode mach)))))))\n\n(define (usage-error)\n (display \"Usage: vm [INPUTFILE [OUTPUTFILE]]\" (current-error-port))\n (newline (current-error-port))\n (display \"If either INPUTFILE or OUTPUTFILE is \\\"-\\\", the respective\"\n (current-error-port))\n (display \" standard I/O is used.\" (current-error-port))\n (newline (current-error-port))\n (exit 1))\n\n(: get-filenames (-> (Values String String)))\n(define (get-filenames)\n (match (current-command-line-arguments)\n ((vector) (values \"-\" \"-\"))\n ((vector inpf-filename)\n (values (cast inpf-filename String) \"-\"))\n ((vector inpf-filename outf-filename)\n (values (cast inpf-filename String)\n (cast outf-filename String)))\n (_ (usage-error)\n (values \"\" \"\"))))\n\n(let-values (((inpf-filename outf-filename) (get-filenames)))\n (let* ((inpf (open-inpf inpf-filename))\n (outf (open-outf outf-filename)))\n (let-values (((datasize strings-count)\n (read-datasize-and-strings-count inpf)))\n (let* ((strings\n (vector->immutable-vector\n (list->vector\n (read-string-literals inpf strings-count))))\n (instructions (read-instructions inpf))\n\n (mach (make-machine strings outf)))\n\n (unless (<= datasize data-memory-size)\n (raise-user-error\n \"the VM's data memory size is exceeded\"))\n\n (load-executable-memory (machine-code mach) instructions)\n (run-vm mach)\n\n (unless (string=? inpf-filename \"-\")\n (close-input-port inpf))\n (unless (string=? outf-filename \"-\")\n (close-output-port outf))\n\n (exit 0)))))\n", "language": "Racket" }, { "code": "my @CODE = q:to/END/.lines;\nDatasize: 3 Strings: 2\n\"count is: \"\n\"\\n\"\n 0 push 1\n 5 store [0]\n 10 fetch [0]\n 15 push 10\n 20 lt\n 21 jz (68) 65 # jump value adjusted\n 26 push 0\n 31 prts\n 32 fetch [0]\n 37 prti\n 38 push 1\n 43 prts\n 44 fetch [0]\n 49 push 1\n 54 add\n 55 store [0]\n 60 jmp (-87) 10 # jump value adjusted\n 65 halt\nEND\n\nmy (@stack, @strings, @data, $memory);\nmy $pc = 0;\n\n(@CODE.shift) ~~ /'Datasize:' \\s+ (\\d+) \\s+ 'Strings:' \\s+ (\\d+)/ or die \"bad header\";\nmy $w = $0; # 'wordsize' of op-codes and 'width' of data values\[email protected]: (my $s = @CODE.shift) eq '\"\\n\"' ?? \"\\n\" !! $s.subst(/'\"'/, '', :g) for 1..$1;\n\nsub value { substr($memory, ($pc += $w) - $w, $w).trim }\n\nmy %ops = (\n 'no-op' => sub { },\n 'add' => sub { @stack[*-2] += @stack.pop },\n 'sub' => sub { @stack[*-2] -= @stack.pop },\n 'mul' => sub { @stack[*-2] *= @stack.pop },\n 'div' => sub { @stack[*-2] /= @stack.pop },\n 'mod' => sub { @stack[*-2] %= @stack.pop },\n 'neg' => sub { @stack[*-1] = - @stack[*-1] },\n 'and' => sub { @stack[*-2] &&= @stack[*-1]; @stack.pop },\n 'or' => sub { @stack[*-2] ||= @stack[*-1]; @stack.pop },\n 'not' => sub { @stack[*-1] = @stack[*-1] ?? 0 !! 1 },\n 'lt' => sub { @stack[*-1] = @stack[*-2] < @stack.pop ?? 1 !! 0 },\n 'gt' => sub { @stack[*-1] = @stack[*-2] > @stack.pop ?? 1 !! 0 },\n 'le' => sub { @stack[*-1] = @stack[*-2] <= @stack.pop ?? 1 !! 0 },\n 'ge' => sub { @stack[*-1] = @stack[*-2] >= @stack.pop ?? 1 !! 0 },\n 'ne' => sub { @stack[*-1] = @stack[*-2] != @stack.pop ?? 1 !! 0 },\n 'eq' => sub { @stack[*-1] = @stack[*-2] == @stack.pop ?? 1 !! 0 },\n 'store' => sub { @data[&value] = @stack.pop },\n 'fetch' => sub { @stack.push: @data[&value] // 0 },\n 'push' => sub { @stack.push: value() },\n 'jmp' => sub { $pc += value() - $w },\n 'jz' => sub { $pc += @stack.pop ?? $w !! value() - $w },\n 'prts' => sub { print @strings[@stack.pop] },\n 'prti' => sub { print @stack.pop },\n 'prtc' => sub { print chr @stack.pop },\n 'halt' => sub { exit }\n);\n\nmy %op2n = %ops.keys.sort Z=> 0..*;\nmy %n2op = %op2n.invert;\n%n2op{''} = 'no-op';\n\nfor @CODE -> $_ {\n next unless /\\w/;\n /^ \\s* \\d+ \\s+ (\\w+)/ or die \"bad line $_\";\n $memory ~= %op2n{$0}.fmt(\"%{$w}d\");\n /'(' ('-'?\\d+) ')' | (\\d+) ']'? $/;\n $memory ~= $0 ?? $0.fmt(\"%{$w}d\") !! ' ' x $w;\n}\n\nloop {\n my $opcode = substr($memory, $pc, $w).trim;\n $pc += $w;\n %ops{%n2op{ $opcode }}();\n}\n", "language": "Raku" }, { "code": "######################################################################\n#\n# The Rosetta Code code virtual machine in Ratfor 77.\n#\n# The implementation assumes your FORTRAN compiler supports 1-byte\n# INTEGER*1 and 4-byte INTEGER*4. Integer storage will be\n# native-endian, achieved via EQUIVALENCE. (GNU Fortran and f2c both\n# should work.)\n#\n#\n# How to deal with FORTRAN 77 input is a problem. I use formatted\n# input, treating each line as an array of type CHARACTER--regrettably\n# of no more than some predetermined, finite length. It is a very\n# simple method and presents no significant difficulties, aside from\n# the restriction on line length of the input.\n#\n#\n# On a POSIX platform, the program can be compiled with f2c and run\n# somewhat as follows:\n#\n# ratfor77 vm-in-ratfor.r > vm-in-ratfor.f\n# f2c -C -Nc40 vm-in-ratfor.f\n# cc vm-in-ratfor.c -lf2c\n# ./a.out < compiler-tests/primes.vm\n#\n# With gfortran, a little differently:\n#\n# ratfor77 vm-in-ratfor.r > vm-in-ratfor.f\n# gfortran -fcheck=all -std=legacy vm-in-ratfor.f\n# ./a.out < compiler-tests/primes.vm\n#\n#\n# I/O is strictly from default input and to default output, which, on\n# POSIX systems, usually correspond respectively to standard input and\n# standard output. (I did not wish to have to deal with unit numbers;\n# these are now standardized in ISO_FORTRAN_ENV, but that is not\n# available in FORTRAN 77.)\n#\n#---------------------------------------------------------------------\n\n# Some parameters you may wish to modify.\n\ndefine(LINESZ, 256) # Size of an input line.\ndefine(OUTLSZ, 1024) # Size of an output line.\ndefine(STRNSZ, 4096) # Size of the string pool.\ndefine(STCKSZ, 4096) # Size of stacks.\ndefine(MAXVAR, 256) # Maximum number of variables.\ndefine(MAXSTR, 256) # Maximum number of strings.\ndefine(CODESZ, 16384) # Maximum size of a compiled program.\n\ndefine(STRSZ, 2) # Size of an entry in the VM strings array.\ndefine(STRI, 1) # Index of the string within strngs.\ndefine(STRN, 2) # Length of the string.\n\n#---------------------------------------------------------------------\n\ndefine(NEWLIN, 10) # The Unix newline character (ASCII LF).\ndefine(DQUOTE, 34) # The double quote character.\ndefine(BACKSL, 92) # The backslash character.\n\n#---------------------------------------------------------------------\n\ndefine(OPHALT, 1)\ndefine(OPADD, 2)\ndefine(OPSUB, 3)\ndefine(OPMUL, 4)\ndefine(OPDIV, 5)\ndefine(OPMOD, 6)\ndefine(OPLT, 7)\ndefine(OPGT, 8)\ndefine(OPLE, 9)\ndefine(OPGE, 10)\ndefine(OPEQ, 11)\ndefine(OPNE, 12)\ndefine(OPAND, 13)\ndefine(OPOR, 14)\ndefine(OPNEG, 15)\ndefine(OPNOT, 16)\ndefine(OPPRTC, 17)\ndefine(OPPRTI, 18)\ndefine(OPPRTS, 19)\ndefine(OPFTCH, 20)\ndefine(OPSTOR, 21)\ndefine(OPPUSH, 22)\ndefine(OPJMP, 23)\ndefine(OPJZ, 24)\n\n#---------------------------------------------------------------------\n\nfunction issp (c)\n\n # Is a character a space character?\n\n implicit none\n\n character c\n logical issp\n\n integer ic\n\n ic = ichar (c)\n issp = (ic == 32 || (9 <= ic && ic <= 13))\nend\n\nfunction isalph (c)\n\n # Is c character code for a letter?\n\n implicit none\n\n integer c\n logical isalph\n\n #\n # The following is correct for ASCII and Unicode, but not for\n # EBCDIC.\n #\n isalph = (ichar ('a') <= c && c <= ichar ('z')) _\n || (ichar ('A') <= c && c <= ichar ('Z'))\nend\n\nfunction isdgt (c)\n\n # Is c character code for a digit?\n\n implicit none\n\n integer c\n logical isdgt\n\n isdgt = (ichar ('0') <= c && c <= ichar ('9'))\nend\n\nfunction skipsp (str, i, imax)\n\n # Skip past spaces in a string.\n\n implicit none\n\n character str(*)\n integer i\n integer imax\n integer skipsp\n\n logical issp\n\n logical done\n\n skipsp = i\n done = .false.\n while (!done)\n {\n if (imax <= skipsp)\n done = .true.\n else if (!issp (str(skipsp)))\n done = .true.\n else\n skipsp = skipsp + 1\n }\nend\n\nfunction skipns (str, i, imax)\n\n # Skip past non-spaces in a string.\n\n implicit none\n\n character str(*)\n integer i\n integer imax\n integer skipns\n\n logical issp\n\n logical done\n\n skipns = i\n done = .false.\n while (!done)\n {\n if (imax <= skipns)\n done = .true.\n else if (issp (str(skipns)))\n done = .true.\n else\n skipns = skipns + 1\n }\nend\n\nfunction trimrt (str, n)\n\n # Find the length of a string, if one ignores trailing spaces.\n\n implicit none\n\n character str(*)\n integer n\n integer trimrt\n\n logical issp\n\n logical done\n\n trimrt = n\n done = .false.\n while (!done)\n {\n if (trimrt == 0)\n done = .true.\n else if (!issp (str(trimrt)))\n done = .true.\n else\n trimrt = trimrt - 1\n }\nend\n\nfunction skipal (str, i, imax)\n\n # Skip past alphabetic characters in a string.\n\n implicit none\n\n character str(*)\n integer i\n integer imax\n integer skipal\n\n logical isalph\n\n logical done\n\n skipal = i\n done = .false.\n while (!done)\n {\n if (imax <= skipal)\n done = .true.\n else if (!isalph (ichar (str(skipal))))\n done = .true.\n else\n skipal = skipal + 1\n }\nend\n\nfunction skipdg (str, i, imax)\n\n # Skip past digits in a string.\n\n implicit none\n\n character str(*)\n integer i\n integer imax\n integer skipdg\n\n logical isdgt\n\n logical done\n\n skipdg = i\n done = .false.\n while (!done)\n {\n if (imax <= skipdg)\n done = .true.\n else if (!isdgt (ichar (str(skipdg))))\n done = .true.\n else\n skipdg = skipdg + 1\n }\nend\n\nfunction skipnd (str, i, imax)\n\n # Skip past nondigits in a string.\n\n implicit none\n\n character str(*)\n integer i\n integer imax\n integer skipnd\n\n logical isdgt\n\n logical done\n\n skipnd = i\n done = .false.\n while (!done)\n {\n if (imax <= skipnd)\n done = .true.\n else if (isdgt (ichar (str(skipnd))))\n done = .true.\n else\n skipnd = skipnd + 1\n }\nend\n\nfunction skipd1 (str, i, imax)\n\n # Skip past digits and '-' in a string.\n\n implicit none\n\n character str(*)\n integer i\n integer imax\n integer skipd1\n\n logical isdgt\n\n logical done\n\n skipd1 = i\n done = .false.\n while (!done)\n {\n if (imax <= skipd1)\n done = .true.\n else if (!isdgt (ichar (str(skipd1))) && str(skipd1) != '-')\n done = .true.\n else\n skipd1 = skipd1 + 1\n }\nend\n\nfunction skipn1 (str, i, imax)\n\n # Skip past nondigits in a string, except '-'.\n\n implicit none\n\n character str(*)\n integer i\n integer imax\n integer skipn1\n\n logical isdgt\n\n logical done\n\n skipn1 = i\n done = .false.\n while (!done)\n {\n if (imax <= skipn1)\n done = .true.\n else if (isdgt (ichar (str(skipn1))) || str(skipn1) == '-')\n done = .true.\n else\n skipn1 = skipn1 + 1\n }\nend\n\nfunction tolowr (c)\n\n implicit none\n\n character c\n character tolowr\n\n integer ic\n\n # The following is correct for ASCII, and will work with Unicode\n # code points, but is incorrect for EBCDIC.\n\n ic = ichar (c)\n if (ichar ('A') <= ic && ic <= ichar ('Z'))\n ic = ic - ichar('A') + ichar('a')\n tolowr = char (ic)\nend\n\n#---------------------------------------------------------------------\n\nsubroutine addstq (strngs, istrng, src, i0, n0, i, n)\n\n # Add a quoted string to the string pool.\n\n implicit none\n\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n character src(*) # Source string.\n integer i0, n0 # Index and length in source string.\n integer i, n # Index and length in string pool.\n\n integer j\n logical done\n\n1000 format ('attempt to treat an unquoted string as a quoted string')\n\n if (src(i0) != char (DQUOTE) || src(i0 + n0 - 1) != char (DQUOTE))\n {\n write (*, 1000)\n stop\n }\n\n i = istrng\n\n n = 0\n j = i0 + 1\n done = .false.\n while (j != i0 + n0 - 1)\n if (i == STRNSZ)\n {\n write (*, '(''string pool exhausted'')')\n stop\n }\n else if (src(j) == char (BACKSL))\n {\n if (j == i0 + n0 - 1)\n {\n write (*, '(''incorrectly formed quoted string'')')\n stop\n }\n if (src(j + 1) == 'n')\n strngs(istrng) = char (NEWLIN)\n else if (src(j + 1) == char (BACKSL))\n strngs(istrng) = src(j + 1)\n else\n {\n write (*, '(''unrecognized escape sequence'')')\n stop\n }\n istrng = istrng + 1\n n = n + 1\n j = j + 2\n }\n else\n {\n strngs(istrng) = src(j)\n istrng = istrng + 1\n n = n + 1\n j = j + 1\n }\nend\n\n#---------------------------------------------------------------------\n\nsubroutine push (stack, sp, i)\n\n implicit none\n\n integer stack(STCKSZ)\n integer sp # Stack pointer.\n integer i # Value to push.\n\n if (sp == STCKSZ)\n {\n write (*, '(''stack overflow in push'')')\n stop\n }\n stack(sp) = i\n sp = sp + 1\nend\n\nfunction pop (stack, sp)\n\n implicit none\n\n integer stack(STCKSZ)\n integer sp # Stack pointer.\n integer pop\n\n if (sp == 1)\n {\n write (*, '(''stack underflow in pop'')')\n stop\n }\n sp = sp - 1\n pop = stack(sp)\nend\n\nfunction nstack (sp)\n\n implicit none\n\n integer sp # Stack pointer.\n integer nstack\n\n nstack = sp - 1 # Current cardinality of the stack.\nend\n\n#---------------------------------------------------------------------\n\nsubroutine flushl (outbuf, noutbf)\n\n # Flush a line from the output buffer.\n\n implicit none\n\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n\n character*20 fmt\n integer i\n\n if (noutbf == 0)\n write (*, '()')\n else\n {\n write (fmt, 1000) noutbf\n1000 format ('(', I10, 'A)')\n write (*, fmt) (outbuf(i), i = 1, noutbf)\n noutbf = 0\n }\nend\n\nsubroutine wrtchr (outbuf, noutbf, ch)\n\n # Write a character to output.\n\n implicit none\n\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n character ch # The character to output.\n\n # This routine silently truncates anything that goes past the buffer\n # boundary.\n\n if (ch == char (NEWLIN))\n call flushl (outbuf, noutbf)\n else if (noutbf < OUTLSZ)\n {\n noutbf = noutbf + 1\n outbuf(noutbf) = ch\n }\nend\n\nsubroutine wrtstr (outbuf, noutbf, str, i, n)\n\n # Write a substring to output.\n\n implicit none\n\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n character str(*) # The string from which to output.\n integer i, n # Index and length of the substring.\n\n integer j\n\n for (j = 0; j < n; j = j + 1)\n call wrtchr (outbuf, noutbf, str(i + j))\nend\n\nsubroutine wrtint (outbuf, noutbf, ival, colcnt)\n\n # Write an integer to output.\n\n implicit none\n\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n integer ival # The non-negative integer to print.\n integer colcnt # Column count, or zero for free format.\n\n integer skipsp\n\n character*40 buf\n integer i, j\n\n write (buf, '(I40)') ival\n i = skipsp (buf, 1, 41)\n if (0 < colcnt)\n for (j = 1; j < colcnt - (40 - i); j = j + 1)\n call wrtchr (outbuf, noutbf, ' ')\n while (i <= 40)\n {\n call wrtchr (outbuf, noutbf, buf(i:i))\n i = i + 1\n }\nend\n\n#---------------------------------------------------------------------\n\nfunction strnat (str, i, n)\n\n # Convert a string to a non-negative integer.\n\n implicit none\n\n character str(*)\n integer i, n\n integer strnat\n\n integer j\n\n strnat = 0\n for (j = 0; j < n; j = j + 1)\n strnat = (10 * strnat) + (ichar (str(i + j)) - ichar ('0'))\nend\n\nfunction strint (str, i, n)\n\n # Convert a string to an integer\n\n implicit none\n\n character str(*)\n integer i, n\n integer strint\n\n integer strnat\n\n if (str(i) == '-')\n strint = -strnat (str, i + 1, n - 1)\n else\n strint = strnat (str, i, n)\nend\n\n#---------------------------------------------------------------------\n\nsubroutine put1 (code, i, opcode)\n\n # Store a 1-byte operation.\n\n implicit none\n\n integer*1 code(0 : CODESZ - 1) # Byte code.\n integer i # Address to put the code at.\n integer*1 opcode\n\n if (CODESZ - i < 1)\n {\n write (*, '(''address beyond the size of memory'')')\n stop\n }\n code(i) = opcode\nend\n\nsubroutine put5 (code, i, opcode, ival)\n\n # Store a 5-byte operation.\n\n implicit none\n\n integer*1 code(0 : CODESZ - 1) # Byte code.\n integer i # Address to put the code at.\n integer*1 opcode #\n integer ival # Immediate integer value.\n\n integer*4 ival32\n integer*1 ival8(4)\n equivalence (ival32, ival8)\n\n if (CODESZ - i < 5)\n {\n write (*, '(''address beyond the size of memory'')')\n stop\n }\n code(i) = opcode\n\n # Native-endian storage.\n ival32 = ival\n code(i + 1) = ival8(1)\n code(i + 2) = ival8(2)\n code(i + 3) = ival8(3)\n code(i + 4) = ival8(4)\nend\n\nfunction getimm (code, i)\n\n # Get an immediate value from the code, at address i.\n\n implicit none\n\n integer*1 code(0 : CODESZ - 1) # Byte code.\n integer i # Address at which the integer resides.\n integer getimm # Immediate integer value.\n\n integer*4 ival32\n integer*1 ival8(4)\n equivalence (ival32, ival8)\n\n if (i < 0 || CODESZ <= i + 3)\n {\n write (*, '(''code address out of range'')')\n stop\n }\n\n # Native-endian storage.\n ival8(1) = code(i)\n ival8(2) = code(i + 1)\n ival8(3) = code(i + 2)\n ival8(4) = code(i + 3)\n getimm = ival32\nend\n\n#---------------------------------------------------------------------\n\nsubroutine rdhead (datsiz, strsiz)\n\n # Read the header line.\n\n implicit none\n\n integer datsiz\n integer strsiz\n\n integer skipnd\n integer skipdg\n integer strnat\n\n character line(LINESZ)\n character*20 fmt\n integer i1, j1, i2, j2\n\n # Read a line of text as an array of characters.\n write (fmt, '(''('', I10, ''A)'')') LINESZ\n read (*, fmt) line\n\n i1 = skipnd (line, 1, LINESZ + 1)\n j1 = skipdg (line, i1, LINESZ + 1)\n i2 = skipnd (line, j1, LINESZ + 1)\n j2 = skipdg (line, i2, LINESZ + 1)\n if (i1 == j1 || i2 == j2)\n {\n write (*, '(''bad header line'')')\n stop\n }\n datsiz = strnat (line, i1, j1 - i1)\n strsiz = strnat (line, i2, j2 - i2)\nend\n\nsubroutine rdstrs (strs, strsiz, strngs, istrng)\n\n implicit none\n\n integer strs(1:STRSZ, 0 : MAXSTR - 1)\n integer strsiz\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n\n integer trimrt\n integer skipsp\n\n character line(LINESZ)\n character*20 fmt\n integer j\n integer i, n\n integer i0, n0\n\n # Read lines of text as an array of characters.\n write (fmt, '(''('', I10, ''A)'')') LINESZ\n\n for (j = 0; j < strsiz; j = j + 1)\n {\n read (*, fmt) line\n n0 = trimrt (line, LINESZ)\n i0 = skipsp (line, 1, n0 + 1)\n if (i0 == n0 + 1)\n {\n write (*, '(''blank line where a string should be'')')\n stop\n }\n call addstq (strngs, istrng, line, i0, n0 - i0 + 1, i, n)\n strs(STRI, j) = i\n strs(STRN, j) = n\n }\nend\n\nfunction stropc (str, i, n)\n\n # Convert substring to an opcode.\n\n implicit none\n\n character str(*)\n integer i, n\n integer*1 stropc\n\n stropc = -1\n if (n == 2)\n {\n if (str(i) == 'l')\n {\n if (str(i + 1) == 't')\n stropc = OPLT\n else if (str(i + 1) == 'e')\n stropc = OPLE\n }\n else if (str(i) == 'g')\n {\n if (str(i + 1) == 't')\n stropc = OPGT\n else if (str(i + 1) == 'e')\n stropc = OPGE\n }\n else if (str(i) == 'e' && str(i + 1) == 'q')\n stropc = OPEQ\n else if (str(i) == 'n' && str(i + 1) == 'e')\n stropc = OPNE\n else if (str(i) == 'o' && str(i + 1) == 'r')\n stropc = OPOR\n else if (str(i) == 'j' && str(i + 1) == 'z')\n stropc = OPJZ\n }\n else if (n == 3)\n {\n if (str(i) == 'a')\n {\n if (str(i + 1) == 'd' && str(i + 2) == 'd')\n stropc = OPADD\n else if (str(i + 1) == 'n' && str(i + 2) == 'd')\n stropc = OPAND\n }\n else if (str(i) == 'm')\n {\n if (str(i + 1) == 'o' && str(i + 2) == 'd')\n stropc = OPMOD\n else if (str(i + 1) == 'u' && str(i + 2) == 'l')\n stropc = OPMUL\n }\n else if (str(i) == 'n')\n {\n if (str(i + 1) == 'e' && str(i + 2) == 'g')\n stropc = OPNEG\n else if (str(i + 1) == 'o' && str(i + 2) == 't')\n stropc = OPNOT\n }\n else if (str(i) == 's' && str(i + 1) == 'u' _\n && str(i + 2) == 'b')\n stropc = OPSUB\n else if (str(i) == 'd' && str(i + 1) == 'i' _\n && str(i + 2) == 'v')\n stropc = OPDIV\n else if (str(i) == 'j' && str(i + 1) == 'm' _\n && str(i + 2) == 'p')\n stropc = OPJMP\n }\n else if (n == 4)\n {\n if (str(i) == 'p')\n {\n if (str(i + 1) == 'r' && str(i + 2) == 't')\n {\n if (str(i + 3) == 'c')\n stropc = OPPRTC\n else if (str(i + 3) == 'i')\n stropc = OPPRTI\n else if (str(i + 3) == 's')\n stropc = OPPRTS\n }\n if (str(i + 1) == 'u' && str(i + 2) == 's' _\n && str(i + 3) == 'h')\n stropc = OPPUSH\n }\n else if (str(i) == 'h' && str(i + 1) == 'a' _\n && str(i + 2) == 'l' && str(i + 3) == 't')\n stropc = OPHALT\n }\n else if (n == 5)\n {\n if (str(i) == 'f' && str(i + 1) == 'e' && str(i + 2) == 't' _\n && str(i + 3) == 'c' && str(i + 4) == 'h')\n stropc = OPFTCH\n if (str(i) == 's' && str(i + 1) == 't' && str(i + 2) == 'o' _\n && str(i + 3) == 'r' && str(i + 4) == 'e')\n stropc = OPSTOR\n }\n if (stropc == -1)\n {\n write (*, '(''unrecognized opcode name'')')\n stop\n }\nend\n\nsubroutine rdops (code)\n\n # Read the opcodes and their immediate values.\n\n implicit none\n\n integer*1 code(0 : CODESZ - 1) # The byte code.\n\n integer trimrt\n integer skipsp\n integer skipal\n integer skipdg\n integer skipd1\n integer skipn1\n integer strnat\n integer strint\n integer*1 stropc\n character tolowr\n\n character line(LINESZ)\n character*20 fmt\n integer stat\n integer n\n integer j\n integer iaddr, jaddr # Address index and size.\n integer iopnm, jopnm # Opcode name index and size.\n integer iarg, jarg\n integer addr\n integer arg\n integer*1 opcode\n\n # Read lines of text as an array of characters.\n write (fmt, '(''('', I10, ''A)'')') LINESZ\n\n read (*, fmt, iostat = stat) line\n while (stat == 0)\n {\n n = trimrt (line, LINESZ)\n\n for (j = 1; j <= n; j = j + 1)\n line(j) = tolowr (line(j))\n\n iaddr = skipsp (line, 1, n + 1)\n jaddr = skipdg (line, iaddr, n + 1)\n addr = strnat (line, iaddr, jaddr - iaddr)\n\n iopnm = skipsp (line, jaddr, n + 1)\n jopnm = skipal (line, iopnm, n + 1)\n opcode = stropc (line, iopnm, jopnm - iopnm)\n\n if (opcode == OPPUSH || opcode == OPFTCH || opcode == OPSTOR _\n || opcode == OPJMP || opcode == OPJZ)\n {\n iarg = skipn1 (line, jopnm, n + 1)\n jarg = skipd1 (line, iarg, n + 1)\n arg = strint (line, iarg, jarg - iarg)\n call put5 (code, addr, opcode, arg)\n }\n else\n call put1 (code, addr, opcode)\n\n read (*, fmt, iostat = stat) line\n }\nend\n\nsubroutine rdcode (strs, strngs, istrng, code)\n\n # Read and parse the \"assembly\" code.\n\n implicit none\n\n integer strs(1:STRSZ, 0 : MAXSTR - 1)\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n integer*1 code(0 : CODESZ - 1) # The byte code.\n\n integer datsiz\n integer strsiz\n\n call rdhead (datsiz, strsiz)\n if (MAXVAR < datsiz)\n {\n write (*, '(''too many variables'')')\n stop\n }\n if (MAXSTR < strsiz)\n {\n write (*, '(''too many strings'')')\n stop\n }\n\n call rdstrs (strs, strsiz, strngs, istrng)\n call rdops (code)\nend\n\n#---------------------------------------------------------------------\n\nsubroutine stkbin (sp)\n\n implicit none\n\n integer sp\n\n if (sp < 3)\n {\n write (*, '(''stack underflow in binary operation'')')\n stop\n }\nend\n\nsubroutine stkun (sp)\n\n implicit none\n\n integer sp\n\n if (sp < 2)\n {\n write (*, '(''stack underflow in unary operation'')')\n stop\n }\nend\n\nfunction logl2i (b)\n\n implicit none\n\n logical b\n integer logl2i\n\n if (b)\n logl2i = 1\n else\n logl2i = 0\nend\n\nsubroutine rncode (strs, strngs, code, outbuf, noutbf)\n\n # Run the code.\n\n implicit none\n\n integer strs(1:STRSZ, 0 : MAXSTR - 1)\n character strngs(STRNSZ) # String pool.\n integer*1 code(0 : CODESZ - 1) # The byte code.\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n\n integer logl2i\n integer getimm\n integer pop\n\n integer stack(STCKSZ)\n integer data(0 : MAXVAR - 1)\n integer sp # Stack pointer.\n\n integer pc # Program counter.\n integer ip # Instruction pointer.\n equivalence (pc, ip) # LOL, use either name. :)\n\n integer i, n\n integer*1 opcode\n logical done\n\n sp = 1\n ip = 0\n\n done = .false.\n while (!done)\n {\n if (ip < 0 || CODESZ <= ip)\n {\n write (*, '(''code address out of range'')')\n stop\n }\n opcode = code(ip)\n ip = ip + 1\n if (opcode == OPADD)\n {\n call stkbin (sp)\n sp = sp - 1\n stack(sp - 1) = stack (sp - 1) + stack(sp)\n }\n else if (opcode == OPSUB)\n {\n call stkbin (sp)\n sp = sp - 1\n stack(sp - 1) = stack (sp - 1) - stack(sp)\n }\n else if (opcode == OPMUL)\n {\n call stkbin (sp)\n sp = sp - 1\n stack(sp - 1) = stack (sp - 1) * stack(sp)\n }\n else if (opcode == OPDIV)\n {\n call stkbin (sp)\n sp = sp - 1\n stack(sp - 1) = stack (sp - 1) / stack(sp)\n }\n else if (opcode == OPMOD)\n {\n call stkbin (sp)\n sp = sp - 1\n stack(sp - 1) = mod (stack (sp - 1), stack(sp))\n }\n else if (opcode == OPLT)\n {\n call stkbin (sp)\n sp = sp - 1\n stack(sp - 1) = logl2i (stack (sp - 1) < stack(sp))\n }\n else if (opcode == OPGT)\n {\n call stkbin (sp)\n sp = sp - 1\n stack(sp - 1) = logl2i (stack (sp - 1) > stack(sp))\n }\n else if (opcode == OPLE)\n {\n call stkbin (sp)\n sp = sp - 1\n stack(sp - 1) = logl2i (stack (sp - 1) <= stack(sp))\n }\n else if (opcode == OPGE)\n {\n call stkbin (sp)\n sp = sp - 1\n stack(sp - 1) = logl2i (stack (sp - 1) >= stack(sp))\n }\n else if (opcode == OPEQ)\n {\n call stkbin (sp)\n sp = sp - 1\n stack(sp - 1) = logl2i (stack (sp - 1) == stack(sp))\n }\n else if (opcode == OPNE)\n {\n call stkbin (sp)\n sp = sp - 1\n stack(sp - 1) = logl2i (stack (sp - 1) != stack(sp))\n }\n else if (opcode == OPAND)\n {\n call stkbin (sp)\n sp = sp - 1\n stack(sp - 1) = _\n logl2i (stack (sp - 1) != 0 && stack(sp) != 0)\n }\n else if (opcode == OPOR)\n {\n call stkbin (sp)\n sp = sp - 1\n stack(sp - 1) = _\n logl2i (stack (sp - 1) != 0 || stack(sp) != 0)\n }\n else if (opcode == OPNEG)\n {\n call stkun (sp)\n stack(sp - 1) = -stack(sp - 1)\n }\n else if (opcode == OPNOT)\n {\n call stkun (sp)\n stack(sp - 1) = logl2i (stack(sp - 1) == 0)\n }\n else if (opcode == OPPRTC)\n {\n call wrtchr (outbuf, noutbf, char (pop (stack, sp)))\n }\n else if (opcode == OPPRTI)\n {\n call wrtint (outbuf, noutbf, pop (stack, sp), 0)\n }\n else if (opcode == OPPRTS)\n {\n i = pop (stack, sp)\n if (i < 0 || MAXSTR <= i)\n {\n write (*, '(''string address out of range'')')\n stop\n }\n n = strs(STRN, i)\n i = strs(STRI, i)\n call wrtstr (outbuf, noutbf, strngs, i, n)\n }\n else if (opcode == OPFTCH)\n {\n i = getimm (code, ip)\n ip = ip + 4\n if (i < 0 || MAXVAR <= i)\n {\n write (*, '(''data address out of range'')')\n stop\n }\n call push (stack, sp, data(i))\n }\n else if (opcode == OPSTOR)\n {\n i = getimm (code, ip)\n ip = ip + 4\n if (i < 0 || MAXVAR <= i)\n {\n write (*, '(''data address out of range'')')\n stop\n }\n data(i) = pop (stack, sp)\n }\n else if (opcode == OPPUSH)\n {\n call push (stack, sp, getimm (code, ip))\n ip = ip + 4\n }\n else if (opcode == OPJMP)\n {\n ip = ip + getimm (code, ip)\n }\n else if (opcode == OPJZ)\n {\n if (pop (stack, sp) == 0)\n ip = ip + getimm (code, ip)\n else\n ip = ip + 4\n }\n else\n {\n # Halt on OPHALT or any unrecognized code.\n done = .true.\n }\n }\nend\n\n#---------------------------------------------------------------------\n\nprogram vm\n\n implicit none\n\n integer strs(1:STRSZ, 0 : MAXSTR - 1)\n character strngs(STRNSZ) # String pool.\n integer istrng # String pool's next slot.\n integer*1 code(0 : CODESZ - 1) # The byte code.\n character outbuf(OUTLSZ) # Output line buffer.\n integer noutbf # Number of characters in outbuf.\n\n integer j\n\n istrng = 1\n noutbf = 0\n\n for (j = 0; j < CODESZ; j = j + 1)\n code(j) = OPHALT\n\n call rdcode (strs, strngs, istrng, code)\n call rncode (strs, strngs, code, outbuf, noutbf)\n\n if (noutbf != 0)\n call flushl (outbuf, noutbf)\nend\n\n######################################################################\n", "language": "RATFOR" }, { "code": "package xyz.hyperreal.rosettacodeCompiler\n\nimport java.io.{BufferedReader, FileReader, Reader, StringReader}\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject VirtualMachine {\n\n private object Opcodes {\n val FETCH: Byte = 0\n val STORE: Byte = 1\n val PUSH: Byte = 2\n val JMP: Byte = 3\n val JZ: Byte = 4\n val ADD: Byte = 5\n val SUB: Byte = 6\n val MUL: Byte = 7\n val DIV: Byte = 8\n val MOD: Byte = 9\n val LT: Byte = 10\n val GT: Byte = 11\n val LE: Byte = 12\n val GE: Byte = 13\n val EQ: Byte = 14\n val NE: Byte = 15\n val AND: Byte = 16\n val OR: Byte = 17\n val NEG: Byte = 18\n val NOT: Byte = 19\n val PRTC: Byte = 20\n val PRTI: Byte = 21\n val PRTS: Byte = 22\n val HALT: Byte = 23\n }\n\n import Opcodes._\n\n private val HEADER_REGEX = \"Datasize: ([0-9]+) Strings: ([0-9]+)\" r\n private val STRING_REGEX = \"\\\"([^\\\"]*)\\\"\" r\n private val PUSH_REGEX = \" *[0-9]+ push +([0-9]+|'(?:[^'\\\\n]|\\\\\\\\n|\\\\\\\\\\\\\\\\)')\" r\n private val PRTS_REGEX = \" *[0-9]+ prts\" r\n private val PRTI_REGEX = \" *[0-9]+ prti\" r\n private val PRTC_REGEX = \" *[0-9]+ prtc\" r\n private val HALT_REGEX = \" *[0-9]+ halt\" r\n private val STORE_REGEX = \" *[0-9]+ store +\\\\[([0-9]+)\\\\]\" r\n private val FETCH_REGEX = \" *[0-9]+ fetch +\\\\[([0-9]+)\\\\]\" r\n private val LT_REGEX = \" *[0-9]+ lt\" r\n private val GT_REGEX = \" *[0-9]+ gt\" r\n private val LE_REGEX = \" *[0-9]+ le\" r\n private val GE_REGEX = \" *[0-9]+ ge\" r\n private val NE_REGEX = \" *[0-9]+ ne\" r\n private val EQ_REGEX = \" *[0-9]+ eq\" r\n private val JZ_REGEX = \" *[0-9]+ jz +\\\\((-?[0-9]+)\\\\) [0-9]+\" r\n private val ADD_REGEX = \" *[0-9]+ add\" r\n private val SUB_REGEX = \" *[0-9]+ sub\" r\n private val MUL_REGEX = \" *[0-9]+ mul\" r\n private val DIV_REGEX = \" *[0-9]+ div\" r\n private val MOD_REGEX = \" *[0-9]+ mod\" r\n private val AND_REGEX = \" *[0-9]+ and\" r\n private val OR_REGEX = \" *[0-9]+ or\" r\n private val NOT_REGEX = \" *[0-9]+ not\" r\n private val NEG_REGEX = \" *[0-9]+ neg\" r\n private val JMP_REGEX = \" *[0-9]+ jmp +\\\\((-?[0-9]+)\\\\) [0-9]+\" r\n\n def fromStdin = fromReader(Console.in)\n\n def fromFile(file: String) = fromReader(new FileReader(file))\n\n def fromString(src: String) = fromReader(new StringReader(src))\n\n def fromReader(r: Reader) = {\n val in = new BufferedReader(r)\n val vm =\n in.readLine match {\n case HEADER_REGEX(datasize, stringsize) =>\n val strings =\n for (_ <- 1 to stringsize.toInt)\n yield\n in.readLine match {\n case STRING_REGEX(s) => unescape(s)\n case null => sys.error(\"expected string constant but encountered end of input\")\n case s => sys.error(s\"expected string constant: $s\")\n }\n var line: String = null\n val code = new ArrayBuffer[Byte]\n\n def addShort(a: Int) = {\n code += (a >> 8).toByte\n code += a.toByte\n }\n\n def addInstIntOperand(opcode: Byte, operand: Int) = {\n code += opcode\n addShort(operand >> 16)\n addShort(operand)\n }\n\n def addInst(opcode: Byte, operand: String) = addInstIntOperand(opcode, operand.toInt)\n\n while ({ line = in.readLine; line ne null }) line match {\n case PUSH_REGEX(n) if n startsWith \"'\" =>\n addInstIntOperand(PUSH, unescape(n.substring(1, n.length - 1)).head)\n case PUSH_REGEX(n) => addInst(PUSH, n)\n case PRTS_REGEX() => code += PRTS\n case PRTI_REGEX() => code += PRTI\n case PRTC_REGEX() => code += PRTC\n case HALT_REGEX() => code += HALT\n case STORE_REGEX(idx) => addInst(STORE, idx)\n case FETCH_REGEX(idx) => addInst(FETCH, idx)\n case LT_REGEX() => code += LT\n case GT_REGEX() => code += GT\n case LE_REGEX() => code += LE\n case GE_REGEX() => code += GE\n case NE_REGEX() => code += NE\n case EQ_REGEX() => code += EQ\n case JZ_REGEX(disp) => addInst(JZ, disp)\n case ADD_REGEX() => code += ADD\n case SUB_REGEX() => code += SUB\n case MUL_REGEX() => code += MUL\n case DIV_REGEX() => code += DIV\n case MOD_REGEX() => code += MOD\n case AND_REGEX() => code += AND\n case OR_REGEX() => code += OR\n case NOT_REGEX() => code += NOT\n case NEG_REGEX() => code += NEG\n case JMP_REGEX(disp) => addInst(JMP, disp)\n }\n\n new VirtualMachine(code, datasize.toInt, strings)\n case _ => sys.error(\"expected header\")\n }\n\n in.close\n vm\n }\n\n}\n\nclass VirtualMachine(code: IndexedSeq[Byte], datasize: Int, strings: IndexedSeq[String]) {\n\n import VirtualMachine.Opcodes._\n\n var pc = 0\n val stack = new mutable.ArrayStack[Int]\n val data = new Array[Int](datasize)\n var running = false\n\n def getByte = {\n val byte = code(pc) & 0xFF\n\n pc += 1\n byte\n }\n\n def getShort = getByte << 8 | getByte\n\n def getInt = getShort << 16 | getShort\n\n def pushBoolean(b: Boolean) = stack push (if (b) 1 else 0)\n\n def popBoolean = if (stack.pop != 0) true else false\n\n def operator(f: (Int, Int) => Int) = {\n val y = stack.pop\n\n stack.push(f(stack.pop, y))\n }\n\n def relation(r: (Int, Int) => Boolean) = {\n val y = stack.pop\n\n pushBoolean(r(stack.pop, y))\n }\n\n def connective(c: (Boolean, Boolean) => Boolean) = pushBoolean(c(popBoolean, popBoolean))\n\n def execute: Unit =\n getByte match {\n case FETCH => stack push data(getInt)\n case STORE => data(getInt) = stack.pop\n case PUSH => stack push getInt\n case JMP => pc = pc + getInt\n case JZ => if (stack.pop == 0) pc = pc + getInt else pc += 4\n case ADD => operator(_ + _)\n case SUB => operator(_ - _)\n case MUL => operator(_ * _)\n case DIV => operator(_ / _)\n case MOD => operator(_ % _)\n case LT => relation(_ < _)\n case GT => relation(_ > _)\n case LE => relation(_ <= _)\n case GE => relation(_ >= _)\n case EQ => relation(_ == _)\n case NE => relation(_ != _)\n case AND => connective(_ && _)\n case OR => connective(_ || _)\n case NEG => stack push -stack.pop\n case NOT => pushBoolean(!popBoolean)\n case PRTC => print(stack.pop.toChar)\n case PRTI => print(stack.pop)\n case PRTS => print(strings(stack.pop))\n case HALT => running = false\n }\n\n def run = {\n pc = 0\n stack.clear\n running = true\n\n for (i <- data.indices) data(i) = 0\n\n while (running) execute\n }\n\n}\n", "language": "Scala" }, { "code": "package xyz.hyperreal\n\nimport java.io.ByteArrayOutputStream\n\npackage object rosettacodeCompiler {\n\n val escapes = \"\\\\\\\\b|\\\\\\\\f|\\\\\\\\t|\\\\\\\\r|\\\\\\\\n|\\\\\\\\\\\\\\\\|\\\\\\\\\\\"\" r\n\n def unescape(s: String) =\n escapes.replaceAllIn(s, _.matched match {\n case \"\\\\b\" => \"\\b\"\n case \"\\\\f\" => \"\\f\"\n case \"\\\\t\" => \"\\t\"\n case \"\\\\r\" => \"\\r\"\n case \"\\\\n\" => \"\\n\"\n case \"\\\\\\\\\" => \"\\\\\"\n case \"\\\\\\\"\" => \"\\\"\"\n })\n\n def capture(thunk: => Unit) = {\n val buf = new ByteArrayOutputStream\n\n Console.withOut(buf)(thunk)\n buf.toString\n }\n\n}\n", "language": "Scala" }, { "code": "(import (scheme base)\n (scheme char)\n (scheme file)\n (scheme process-context)\n (scheme write)\n (only (srfi 13) string-contains string-delete string-filter\n string-replace string-tokenize))\n\n(define *word-size* 4)\n\n;; Mappings from operation symbols to internal procedures.\n;; We define operations appropriate to virtual machine:\n;; e.g. division must return an int, not a rational\n;; boolean values are treated as numbers: 0 is false, other is true\n(define *unary-ops*\n (list (cons 'neg (lambda (a) (- a)))\n (cons 'not (lambda (a) (if (zero? a) 1 0)))))\n(define *binary-ops*\n (let ((number-comp (lambda (op) (lambda (a b) (if (op a b) 1 0)))))\n (list (cons 'add +)\n (cons 'sub -)\n (cons 'mul *)\n (cons 'div (lambda (a b) (truncate (/ a b)))) ; int division\n (cons 'mod modulo)\n (cons 'lt (number-comp <))\n (cons 'gt (number-comp >))\n (cons 'le (number-comp <=))\n (cons 'ge (number-comp >=))\n (cons 'eq (lambda (a b) (if (= a b) 1 0)))\n (cons 'ne (lambda (a b) (if (= a b) 0 1)))\n (cons 'and (lambda (a b) ; make \"and\" work on numbers\n (if (and (not (zero? a)) (not (zero? b))) 1 0)))\n (cons 'or (lambda (a b) ; make \"or\" work on numbers\n (if (or (not (zero? a)) (not (zero? b))) 1 0))))))\n\n;; read information from file, returning vectors for data and strings\n;; and a list of the code instructions\n(define (read-code filename)\n (define (setup-definitions str)\n (values ; return vectors for (data strings) of required size\n (make-vector (string->number (list-ref str 1)) #f)\n (make-vector (string->number (list-ref str 3)) #f)))\n (define (read-strings strings) ; read constant strings into data structure\n (define (replace-newlines chars) ; replace newlines, obeying \\\\n\n (cond ((< (length chars) 2) ; finished list\n chars)\n ((and (>= (length chars) 3) ; preserve \\\\n\n (char=? #\\\\ (car chars))\n (char=? #\\\\ (cadr chars))\n (char=? #\\n (cadr (cdr chars))))\n (cons (car chars)\n (cons (cadr chars)\n (cons (cadr (cdr chars))\n (replace-newlines (cdr (cdr (cdr chars))))))))\n ((and (char=? #\\\\ (car chars)) ; replace \\n with newline\n (char=? #\\n (cadr chars)))\n (cons #\\newline (replace-newlines (cdr (cdr chars)))))\n (else ; keep char and look further\n (cons (car chars) (replace-newlines (cdr chars))))))\n (define (tidy-string str) ; remove quotes, map newlines to actual newlines\n (list->string\n (replace-newlines\n (string->list\n (string-delete #\\\" str))))) ; \" (needed to satisfy rosettacode's scheme syntax highlighter)\n ;\n (do ((i 0 (+ i 1)))\n ((= i (vector-length strings)) )\n (vector-set! strings i (tidy-string (read-line)))))\n (define (read-code)\n (define (cleanup-code opn) ; tidy instructions, parsing numbers\n (let ((addr (string->number (car opn)))\n (instr (string->symbol (cadr opn))))\n (cond ((= 2 (length opn))\n (list addr instr))\n ((= 3 (length opn))\n (list addr\n instr\n (string->number\n (string-filter char-numeric? (list-ref opn 2)))))\n (else ; assume length 4, jump instructions\n (list addr instr (string->number (list-ref opn 3)))))))\n ;\n (let loop ((result '()))\n (let ((line (read-line)))\n (if (eof-object? line)\n (reverse (map cleanup-code result))\n (loop (cons (string-tokenize line) result))))))\n ;\n (with-input-from-file\n filename\n (lambda ()\n (let-values (((data strings)\n (setup-definitions (string-tokenize (read-line)))))\n (read-strings strings)\n (values data\n strings\n (read-code))))))\n\n;; run the virtual machine\n(define (run-program data strings code)\n (define (get-instruction n)\n (if (assq n code)\n (cdr (assq n code))\n (error \"Could not find instruction\")))\n ;\n (let loop ((stack '())\n (pc 0))\n (let ((op (get-instruction pc)))\n (case (car op)\n ((fetch)\n (loop (cons (vector-ref data (cadr op)) stack)\n (+ pc 1 *word-size*)))\n ((store)\n (vector-set! data (cadr op) (car stack))\n (loop (cdr stack)\n (+ pc 1 *word-size*)))\n ((push)\n (loop (cons (cadr op) stack)\n (+ pc 1 *word-size*)))\n ((add sub mul div mod lt gt le eq ne and or)\n (let ((instr (assq (car op) *binary-ops*)))\n (if instr\n (loop (cons ((cdr instr) (cadr stack) ; replace top two with result\n (car stack))\n (cdr (cdr stack)))\n (+ pc 1))\n (error \"Unknown binary operation\"))))\n ((neg not)\n (let ((instr (assq (car op) *unary-ops*)))\n (if instr\n (loop (cons ((cdr instr) (car stack)) ; replace top with result\n (cdr stack))\n (+ pc 1))\n (error \"Unknown unary operation\"))))\n ((jmp)\n (loop stack\n (cadr op)))\n ((jz)\n (loop (cdr stack)\n (if (zero? (car stack))\n (cadr op)\n (+ pc 1 *word-size*))))\n ((prtc)\n (display (integer->char (car stack)))\n (loop (cdr stack)\n (+ pc 1)))\n ((prti)\n (display (car stack))\n (loop (cdr stack)\n (+ pc 1)))\n ((prts)\n (display (vector-ref strings (car stack)))\n (loop (cdr stack)\n (+ pc 1)))\n ((halt)\n #t)))))\n\n;; create and run virtual machine from filename passed on command line\n(if (= 2 (length (command-line)))\n (let-values (((data strings code) (read-code (cadr (command-line)))))\n (run-program data strings code))\n (display \"Error: pass a .asm filename\\n\"))\n", "language": "Scheme" }, { "code": "import \"./dynamic\" for Enum\nimport \"./crypto\" for Bytes\nimport \"./fmt\" for Conv\nimport \"./ioutil\" for FileUtil\n\nvar codes = [\n \"fetch\",\n \"store\",\n \"push\",\n \"add\",\n \"sub\",\n \"mul\",\n \"div\",\n \"mod\",\n \"lt\",\n \"gt\",\n \"le\",\n \"ge\",\n \"eq\",\n \"ne\",\n \"and\",\n \"or\",\n \"neg\",\n \"not\",\n \"jmp\",\n \"jz\",\n \"prtc\",\n \"prts\",\n \"prti\",\n \"halt\"\n]\n\nvar Code = Enum.create(\"Code\", codes)\n\nvar codeMap = {\n \"fetch\": Code.fetch,\n \"store\": Code.store,\n \"push\": Code.push,\n \"add\": Code.add,\n \"sub\": Code.sub,\n \"mul\": Code.mul,\n \"div\": Code.div,\n \"mod\": Code.mod,\n \"lt\": Code.lt,\n \"gt\": Code.gt,\n \"le\": Code.le,\n \"ge\": Code.ge,\n \"eq\": Code.eq,\n \"ne\": Code.ne,\n \"and\": Code.and,\n \"or\": Code.or,\n \"neg\": Code.neg,\n \"not\": Code.not,\n \"jmp\": Code.jmp,\n \"jz\": Code.jz,\n \"prtc\": Code.prtc,\n \"prts\": Code.prts,\n \"prti\": Code.prti,\n \"halt\": Code.halt\n}\n\nvar object = []\nvar stringPool = []\n\nvar reportError = Fn.new { |msg| Fiber.abort(\"error : %(msg)\") }\n\nvar emitByte = Fn.new { |c| object.add(c) }\n\nvar emitWord = Fn.new { |n|\n var bs = Bytes.fromIntLE(n)\n for (b in bs) emitByte.call(b)\n}\n\n// Converts the 4 bytes starting at object[pc] to an unsigned 32 bit integer\n// and thence to a signed 32 bit integer\nvar toInt32LE = Fn.new { |pc|\n var x = Bytes.toIntLE(object[pc...pc+4])\n if (x >= 2.pow(31)) x = x - 2.pow(32)\n return x\n}\n\n/* Virtual Machine interpreter */\n\nvar runVM = Fn.new { |dataSize|\n var stack = List.filled(dataSize + 1, 0)\n var pc = 0\n while (true) {\n var op = object[pc]\n pc = pc + 1\n if (op == Code.fetch) {\n var x = toInt32LE.call(pc)\n stack.add(stack[x])\n pc = pc + 4\n } else if (op == Code.store) {\n var x = toInt32LE.call(pc)\n var ln = stack.count\n stack[x] = stack[ln-1]\n stack = stack[0...ln-1]\n pc = pc + 4\n } else if (op == Code.push) {\n var x = toInt32LE.call(pc)\n stack.add(x)\n pc = pc + 4\n } else if (op == Code.add) {\n var ln = stack.count\n stack[ln-2] = stack[ln-2] + stack[ln-1]\n stack = stack[0...ln-1]\n } else if (op == Code.sub) {\n var ln = stack.count\n stack[ln-2] = stack[ln-2] - stack[ln-1]\n stack = stack[0...ln-1]\n } else if (op == Code.mul) {\n var ln = stack.count\n stack[ln-2] = stack[ln-2] * stack[ln-1]\n stack = stack[0...ln-1]\n } else if (op == Code.div) {\n var ln = stack.count\n stack[ln-2] = (stack[ln-2] / stack[ln-1]).truncate\n stack = stack[0...ln-1]\n } else if (op == Code.mod) {\n var ln = stack.count\n stack[ln-2] = stack[ln-2] % stack[ln-1]\n stack = stack[0...ln-1]\n } else if (op == Code.lt) {\n var ln = stack.count\n stack[ln-2] = Conv.btoi(stack[ln-2] < stack[ln-1])\n stack = stack[0...ln-1]\n } else if (op == Code.gt) {\n var ln = stack.count\n stack[ln-2] = Conv.btoi(stack[ln-2] > stack[ln-1])\n stack = stack[0...ln-1]\n } else if (op == Code.le) {\n var ln = stack.count\n stack[ln-2] = Conv.btoi(stack[ln-2] <= stack[ln-1])\n stack = stack[0...ln-1]\n } else if (op == Code.ge) {\n var ln = stack.count\n stack[ln-2] = Conv.btoi(stack[ln-2] >= stack[ln-1])\n stack = stack[0...ln-1]\n } else if (op == Code.eq) {\n var ln = stack.count\n stack[ln-2] = Conv.btoi(stack[ln-2] == stack[ln-1])\n stack = stack[0...ln-1]\n } else if (op == Code.ne) {\n var ln = stack.count\n stack[ln-2] = Conv.btoi(stack[ln-2] != stack[ln-1])\n stack = stack[0...ln-1]\n } else if (op == Code.and) {\n var ln = stack.count\n stack[ln-2] = Conv.btoi(Conv.itob(stack[ln-2]) && Conv.itob(stack[ln-1]))\n stack = stack[0...ln-1]\n } else if (op == Code.or) {\n var ln = stack.count\n stack[ln-2] = Conv.btoi(Conv.itob(stack[ln-2]) || Conv.itob(stack[ln-1]))\n stack = stack[0...ln-1]\n } else if (op == Code.neg) {\n var ln = stack.count\n stack[ln-1] = -stack[ln-1]\n } else if (op == Code.not) {\n var ln = stack.count\n stack[ln-1] = Conv.btoi(!Conv.itob(stack[ln-1]))\n } else if (op == Code.jmp) {\n var x = toInt32LE.call(pc)\n pc = pc + x\n } else if (op == Code.jz) {\n var ln = stack.count\n var v = stack[ln-1]\n stack = stack[0...ln-1]\n if (v != 0) {\n pc = pc + 4\n } else {\n var x = toInt32LE.call(pc)\n pc = pc + x\n }\n } else if (op == Code.prtc) {\n var ln = stack.count\n System.write(String.fromByte(stack[ln-1]))\n stack = stack[0...ln-1]\n } else if (op == Code.prts) {\n var ln = stack.count\n System.write(stringPool[stack[ln-1]])\n stack = stack[0...ln-1]\n } else if (op == Code.prti) {\n var ln = stack.count\n System.write(stack[ln-1])\n stack = stack[0...ln-1]\n } else if (op == Code.halt) {\n return\n } else {\n reportError.call(\"Unknown opcode %(op)\")\n }\n }\n}\n\nvar translate = Fn.new { |s|\n var d = \"\"\n var i = 0\n while (i < s.count) {\n if (s[i] == \"\\\\\" && (i+1) < s.count) {\n if (s[i+1] == \"n\") {\n d = d + \"\\n\"\n i = i + 1\n } else if (s[i+1] == \"\\\\\") {\n d = d + \"\\\\\"\n i = i + 1\n }\n } else {\n d = d + s[i]\n }\n i = i + 1\n }\n return d\n}\n\nvar lines = []\nvar lineCount = 0\nvar lineNum = 0\n\nvar loadCode = Fn.new {\n var dataSize\n var firstLine = true\n while (lineNum < lineCount) {\n var line = lines[lineNum].trimEnd(\" \\t\")\n lineNum = lineNum + 1\n if (line.count == 0) {\n if (firstLine) {\n reportError.call(\"empty line\")\n } else {\n break\n }\n }\n var lineList = line.split(\" \").where { |s| s != \"\" }.toList\n if (firstLine) {\n dataSize = Num.fromString(lineList[1])\n var nStrings = Num.fromString(lineList[3])\n for (i in 0...nStrings) {\n var s = lines[lineNum].trim(\"\\\"\\n\")\n lineNum = lineNum + 1\n stringPool.add(translate.call(s))\n }\n firstLine = false\n continue\n }\n var offset = Num.fromString(lineList[0])\n var instr = lineList[1]\n var opCode = codeMap[instr]\n if (!opCode) {\n reportError.call(\"Unknown instruction %(instr) at %(opCode)\")\n }\n emitByte.call(opCode)\n if (opCode == Code.jmp || opCode == Code.jz) {\n var p = Num.fromString(lineList[3])\n emitWord.call(p - offset - 1)\n } else if (opCode == Code.push) {\n var value = Num.fromString(lineList[2])\n emitWord.call(value)\n } else if (opCode == Code.fetch || opCode == Code.store) {\n var value = Num.fromString(lineList[2].trim(\"[]\"))\n emitWord.call(value)\n }\n }\n return dataSize\n}\n\nlines = FileUtil.readLines(\"codegen.txt\")\nlineCount = lines.count\nrunVM.call(loadCode.call())\n", "language": "Wren" }, { "code": "const std = @import(\"std\");\n\npub const VirtualMachineError = error{OutOfMemory};\n\npub const VirtualMachine = struct {\n allocator: std.mem.Allocator,\n stack: [stack_size]i32,\n program: std.ArrayList(u8),\n sp: usize, // stack pointer\n pc: usize, // program counter\n string_pool: std.ArrayList([]const u8), // all the strings in the program\n globals: std.ArrayList(i32), // all the variables in the program, they are global\n output: std.ArrayList(u8), // Instead of outputting to stdout, we do it here for better testing.\n\n const Self = @This();\n const stack_size = 32; // Can be arbitrarily increased/decreased as long as we have enough.\n const word_size = @sizeOf(i32);\n\n pub fn init(\n allocator: std.mem.Allocator,\n program: std.ArrayList(u8),\n string_pool: std.ArrayList([]const u8),\n globals: std.ArrayList(i32),\n ) Self {\n return VirtualMachine{\n .allocator = allocator,\n .stack = [_]i32{std.math.maxInt(i32)} ** stack_size,\n .program = program,\n .sp = 0,\n .pc = 0,\n .string_pool = string_pool,\n .globals = globals,\n .output = std.ArrayList(u8).init(allocator),\n };\n }\n\n pub fn interp(self: *Self) VirtualMachineError!void {\n while (true) : (self.pc += 1) {\n switch (@intToEnum(Op, self.program.items[self.pc])) {\n .push => self.push(self.unpackInt()),\n .store => self.globals.items[@intCast(usize, self.unpackInt())] = self.pop(),\n .fetch => self.push(self.globals.items[@intCast(usize, self.unpackInt())]),\n .jmp => self.pc = @intCast(usize, self.unpackInt() - 1),\n .jz => {\n if (self.pop() == 0) {\n // -1 because `while` increases it with every iteration.\n // This doesn't allow to jump to location 0 because we use `usize` for `pc`,\n // just arbitrary implementation limitation.\n self.pc = @intCast(usize, self.unpackInt() - 1);\n } else {\n self.pc += word_size;\n }\n },\n .prts => try self.out(\"{s}\", .{self.string_pool.items[@intCast(usize, self.pop())]}),\n .prti => try self.out(\"{d}\", .{self.pop()}),\n .prtc => try self.out(\"{c}\", .{@intCast(u8, self.pop())}),\n .lt => self.binOp(lt),\n .le => self.binOp(le),\n .gt => self.binOp(gt),\n .ge => self.binOp(ge),\n .eq => self.binOp(eq),\n .ne => self.binOp(ne),\n .add => self.binOp(add),\n .mul => self.binOp(mul),\n .sub => self.binOp(sub),\n .div => self.binOp(div),\n .mod => self.binOp(mod),\n .@\"and\" => self.binOp(@\"and\"),\n .@\"or\" => self.binOp(@\"or\"),\n .not => self.push(@boolToInt(self.pop() == 0)),\n .neg => self.push(-self.pop()),\n .halt => break,\n }\n }\n }\n\n fn push(self: *Self, n: i32) void {\n self.sp += 1;\n self.stack[self.sp] = n;\n }\n\n fn pop(self: *Self) i32 {\n std.debug.assert(self.sp != 0);\n self.sp -= 1;\n return self.stack[self.sp + 1];\n }\n\n fn unpackInt(self: *Self) i32 {\n const arg_ptr = @ptrCast(*[4]u8, self.program.items[self.pc + 1 .. self.pc + 1 + word_size]);\n self.pc += word_size;\n var arg_array = arg_ptr.*;\n const arg = @ptrCast(*i32, @alignCast(@alignOf(i32), &arg_array));\n return arg.*;\n }\n\n pub fn out(self: *Self, comptime format: []const u8, args: anytype) VirtualMachineError!void {\n try self.output.writer().print(format, args);\n }\n\n fn binOp(self: *Self, func: fn (a: i32, b: i32) i32) void {\n const a = self.pop();\n const b = self.pop();\n // Note that arguments are in reversed order because this is how we interact with\n // push/pop operations of the stack.\n const result = func(b, a);\n self.push(result);\n }\n\n fn lt(a: i32, b: i32) i32 {\n return @boolToInt(a < b);\n }\n fn le(a: i32, b: i32) i32 {\n return @boolToInt(a <= b);\n }\n fn gt(a: i32, b: i32) i32 {\n return @boolToInt(a > b);\n }\n fn ge(a: i32, b: i32) i32 {\n return @boolToInt(a >= b);\n }\n fn eq(a: i32, b: i32) i32 {\n return @boolToInt(a == b);\n }\n fn ne(a: i32, b: i32) i32 {\n return @boolToInt(a != b);\n }\n fn add(a: i32, b: i32) i32 {\n return a + b;\n }\n fn sub(a: i32, b: i32) i32 {\n return a - b;\n }\n fn mul(a: i32, b: i32) i32 {\n return a * b;\n }\n fn div(a: i32, b: i32) i32 {\n return @divTrunc(a, b);\n }\n fn mod(a: i32, b: i32) i32 {\n return @mod(a, b);\n }\n fn @\"or\"(a: i32, b: i32) i32 {\n return @boolToInt((a != 0) or (b != 0));\n }\n fn @\"and\"(a: i32, b: i32) i32 {\n return @boolToInt((a != 0) and (b != 0));\n }\n};\n\npub fn main() !void {\n var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);\n defer arena.deinit();\n const allocator = arena.allocator();\n\n var arg_it = std.process.args();\n _ = try arg_it.next(allocator) orelse unreachable; // program name\n const file_name = arg_it.next(allocator);\n // We accept both files and standard input.\n var file_handle = blk: {\n if (file_name) |file_name_delimited| {\n const fname: []const u8 = try file_name_delimited;\n break :blk try std.fs.cwd().openFile(fname, .{});\n } else {\n break :blk std.io.getStdIn();\n }\n };\n defer file_handle.close();\n const input_content = try file_handle.readToEndAlloc(allocator, std.math.maxInt(usize));\n\n var string_pool = std.ArrayList([]const u8).init(allocator);\n var globals = std.ArrayList(i32).init(allocator);\n const bytecode = try loadBytecode(allocator, input_content, &string_pool, &globals);\n var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals);\n try vm.interp();\n const result: []const u8 = vm.output.items;\n _ = try std.io.getStdOut().write(result);\n}\n\npub const Op = enum(u8) {\n fetch,\n store,\n push,\n add,\n sub,\n mul,\n div,\n mod,\n lt,\n gt,\n le,\n ge,\n eq,\n ne,\n @\"and\",\n @\"or\",\n neg,\n not,\n jmp,\n jz,\n prtc,\n prts,\n prti,\n halt,\n\n const from_string = std.ComptimeStringMap(Op, .{\n .{ \"fetch\", .fetch },\n .{ \"store\", .store },\n .{ \"push\", .push },\n .{ \"add\", .add },\n .{ \"sub\", .sub },\n .{ \"mul\", .mul },\n .{ \"div\", .div },\n .{ \"mod\", .mod },\n .{ \"lt\", .lt },\n .{ \"gt\", .gt },\n .{ \"le\", .le },\n .{ \"ge\", .ge },\n .{ \"eq\", .eq },\n .{ \"ne\", .ne },\n .{ \"and\", .@\"and\" },\n .{ \"or\", .@\"or\" },\n .{ \"neg\", .neg },\n .{ \"not\", .not },\n .{ \"jmp\", .jmp },\n .{ \"jz\", .jz },\n .{ \"prtc\", .prtc },\n .{ \"prts\", .prts },\n .{ \"prti\", .prti },\n .{ \"halt\", .halt },\n });\n\n pub fn fromString(str: []const u8) Op {\n return from_string.get(str).?;\n }\n};\n\n// 100 lines of code to load serialized bytecode, eh\nfn loadBytecode(\n allocator: std.mem.Allocator,\n str: []const u8,\n string_pool: *std.ArrayList([]const u8),\n globals: *std.ArrayList(i32),\n) !std.ArrayList(u8) {\n var result = std.ArrayList(u8).init(allocator);\n var line_it = std.mem.split(u8, str, \"\\n\");\n while (line_it.next()) |line| {\n if (std.mem.indexOf(u8, line, \"halt\")) |_| {\n var tok_it = std.mem.tokenize(u8, line, \" \");\n const size = try std.fmt.parseInt(usize, tok_it.next().?, 10);\n try result.resize(size + 1);\n break;\n }\n }\n\n line_it.index = 0;\n const first_line = line_it.next().?;\n const strings_index = std.mem.indexOf(u8, first_line, \" Strings: \").?;\n const globals_size = try std.fmt.parseInt(usize, first_line[\"Datasize: \".len..strings_index], 10);\n const string_pool_size = try std.fmt.parseInt(usize, first_line[strings_index + \" Strings: \".len ..], 10);\n try globals.resize(globals_size);\n try string_pool.ensureTotalCapacity(string_pool_size);\n var string_cnt: usize = 0;\n while (string_cnt < string_pool_size) : (string_cnt += 1) {\n const line = line_it.next().?;\n var program_string = try std.ArrayList(u8).initCapacity(allocator, line.len);\n var escaped = false;\n // Skip double quotes\n for (line[1 .. line.len - 1]) |ch| {\n if (escaped) {\n escaped = false;\n switch (ch) {\n '\\\\' => try program_string.append('\\\\'),\n 'n' => try program_string.append('\\n'),\n else => {\n std.debug.print(\"unknown escape sequence: {c}\\n\", .{ch});\n std.os.exit(1);\n },\n }\n } else {\n switch (ch) {\n '\\\\' => escaped = true,\n else => try program_string.append(ch),\n }\n }\n }\n try string_pool.append(program_string.items);\n }\n while (line_it.next()) |line| {\n if (line.len == 0) break;\n\n var tok_it = std.mem.tokenize(u8, line, \" \");\n const address = try std.fmt.parseInt(usize, tok_it.next().?, 10);\n const op = Op.fromString(tok_it.next().?);\n result.items[address] = @enumToInt(op);\n switch (op) {\n .fetch, .store => {\n const index_bracketed = tok_it.rest();\n const index = try std.fmt.parseInt(i32, index_bracketed[1 .. index_bracketed.len - 1], 10);\n insertInt(&result, address + 1, index);\n },\n .push => {\n insertInt(&result, address + 1, try std.fmt.parseInt(i32, tok_it.rest(), 10));\n },\n .jmp, .jz => {\n _ = tok_it.next();\n insertInt(&result, address + 1, try std.fmt.parseInt(i32, tok_it.rest(), 10));\n },\n else => {},\n }\n }\n return result;\n}\n\nfn insertInt(array: *std.ArrayList(u8), address: usize, n: i32) void {\n const word_size = @sizeOf(i32);\n var i: usize = 0;\n var n_var = n;\n var n_bytes = @ptrCast(*[4]u8, &n_var);\n while (i < word_size) : (i += 1) {\n array.items[@intCast(usize, address + i)] = n_bytes[@intCast(usize, i)];\n }\n}\n", "language": "Zig" }, { "code": "// This is a little endian machine\nconst WORD_SIZE=4;\nconst{ var _n=-1; var[proxy]N=fcn{ _n+=1 } } // enumerator\nconst FETCH=N, STORE=N, PUSH=N, ADD=N, SUB=N, MUL=N, DIV=N, MOD=N,\n LT=N, GT=N, LE=N, GE=N, EQ=N, NE=N, AND=N, OR=N, NEG=N, NOT=N,\n JMP=N, JZ=N, PRTC=N, PRTS=N, PRTI=N, HALT=N;\n\nvar [const]\n bops=Dictionary(ADD,'+, SUB,'-, MUL,'*, DIV,'/, MOD,'%,\n\t\t LT,'<, GT,'>, LE,'<=, GE,'>=, NE,'!=, EQ,'==, NE,'!=),\n strings=List(); // filled in by the loader\n;\n\n // do a binary op\nfcn bop(stack,op){ a,b:=stack.pop(),stack.pop(); stack.append(bops[op](b,a)) }\n\nfcn run_vm(code,stackSz){\n stack,pc := List.createLong(stackSz,0), 0;\n while(True){\n op:=code[pc]; pc+=1;\n switch(op){\n case(FETCH){\n\t stack.append(stack[code.toLittleEndian(pc,WORD_SIZE,False)]);\n pc+=WORD_SIZE;\n\t }\n\t case(STORE){\n\t stack[code.toLittleEndian(pc,WORD_SIZE)]=stack.pop();\n\t pc+=WORD_SIZE;\n\t }\n case(PUSH){\n\t stack.append(code.toLittleEndian(pc,WORD_SIZE,False)); // signed\n\t pc+=WORD_SIZE;\n\t }\n\t case(ADD,SUB,MUL,DIV,MOD,LT,GT,LE,GE,EQ,NE) { bop(stack,op) }\n\t case(AND){ stack[-2] = stack[-2] and stack[-1]; stack.pop() }\n\t case(OR) { stack[-2] = stack[-2] or stack[-1]; stack.pop() }\n\t case(NEG){ stack[-1] = -stack[-1] }\n\t case(NOT){ stack[-1] = not stack[-1] }\n\t case(JMP){ pc+=code.toLittleEndian(pc,WORD_SIZE,False); } // signed\n\t case(JZ) {\n\t if(stack.pop()) pc+=WORD_SIZE;\n\t else pc+=code.toLittleEndian(pc,WORD_SIZE,False);\n\t }\n\t case(PRTC){ }\t// not implemented\n\t case(PRTS){ print(strings[stack.pop()]) }\n\t case(PRTI){ print(stack.pop()) }\n\t case(HALT){ break }\n\t else{ throw(Exception.AssertionError(\n\t\t\"Bad op code (%d) @%d\".fmt(op,pc-1))) }\n }\n }\n}\n\ncode:=File(vm.nthArg(0)).read();\t// binary code file\n // the string table is prepended to the code:\n // 66,1 byte len,text, no trailing '\\0' needed\nwhile(code[0]==66){\t// read the string table\n sz:=code[1];\n strings.append(code[2,sz].text);\n code.del(0,sz+2);\n}\nrun_vm(code,1000);\n", "language": "Zkl" } ]
Compiler-virtual-machine-interpreter
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k\n", "language": "00-META" }, { "code": "Find the composite numbers '''k''' in base 10, that have no single digit prime factors and whose prime factors are all a substring of '''k'''.\n\n\n;Task\n\n* Find and show here, on this page, the first ten elements of the sequence.\n\n\n\n;Stretch\n\n* Find and show the next ten elements.\n\n\n\n\n", "language": "00-TASK" }, { "code": "BEGIN # find composite k with no single digit factors whose factors are all substrings of k #\n # returns TRUE if the string representation of f is a substring of k str, FALSE otherwise #\n PROC is substring = ( STRING k str, INT f )BOOL:\n BEGIN\n STRING f str = whole( f, 0 );\n INT f len = ( UPB f str - LWB f str ) + 1;\n BOOL result := FALSE;\n INT f end := ( LWB k str + f len ) - 2;\n FOR f pos FROM LWB k str TO ( UPB k str + 1 ) - f len WHILE NOT result DO\n f end +:= 1;\n result := k str[ f pos : f end ] = f str\n OD;\n result\n END # is substring # ;\n # task #\n INT required numbers = 20;\n INT k count := 0;\n # k must be odd and > 9 #\n FOR k FROM 11 BY 2 WHILE k count < required numbers DO\n IF k MOD 3 /= 0 AND k MOD 5 /= 0 AND k MOD 7 /= 0 THEN\n # no single digit odd prime factors #\n BOOL is candidate := TRUE;\n STRING k str = whole( k, 0 );\n INT v := k;\n INT f count := 0;\n FOR f FROM 11 BY 2 TO ENTIER sqrt( k ) + 1 WHILE v > 1 AND is candidate DO\n IF v MOD f = 0 THEN\n # have a factor #\n is candidate := is substring( k str, f );\n IF is candidate THEN\n # the digits of f ae a substring of v #\n WHILE v OVERAB f;\n f count +:= 1;\n v MOD f = 0\n DO SKIP OD\n FI\n FI\n OD;\n IF is candidate AND ( f count > 1 OR ( v /= k AND v > 1 ) ) THEN\n # have a composite whose factors are up to the root are substrings #\n IF v > 1 THEN\n # there was a factor > the root #\n is candidate := is substring( k str, v )\n FI;\n IF is candidate THEN\n print( ( \" \", whole( k, -8 ) ) );\n k count +:= 1;\n IF k count MOD 10 = 0 THEN print( ( newline ) ) FI\n FI\n FI\n FI\n OD\nEND\n", "language": "ALGOL-68" }, { "code": "valid?: function [n][\n pf: factors.prime n\n every? pf 'f ->\n and? [contains? to :string n to :string f]\n [1 <> size digits f]\n]\n\ncnt: 0\ni: new 3\n\nwhile [cnt < 10][\n if and? [not? prime? i][valid? i][\n print i\n cnt: cnt + 1\n ]\n 'i + 2\n]\n", "language": "Arturo" }, { "code": "#include <stdio.h>\n#include <stdbool.h>\n\nbool is_substring(unsigned n, unsigned k) {\n unsigned startMatch = 0;\n\n for (unsigned pfx = k; n > 0; n /= 10) {\n if (pfx % 10 == n % 10) {\n pfx /= 10;\n if (startMatch == 0) startMatch = n;\n } else {\n pfx = k;\n if (startMatch != 0) n = startMatch;\n startMatch = 0;\n }\n\n if (pfx == 0) return true;\n }\n return false;\n}\n\nbool factors_are_substrings(unsigned n) {\n if (n%2==0 || n%3==0 || n%5==0 || n%7==0) return false;\n\n unsigned factor_count = 0;\n for (unsigned factor = 11, n_rest = n; factor <= n_rest; factor += 2) {\n if (n_rest % factor != 0) continue;\n while (n_rest % factor == 0) n_rest /= factor;\n if (!is_substring(n, factor)) return false;\n factor_count++;\n }\n return factor_count > 1;\n}\n\nint main(void) {\n unsigned amount = 10;\n for (unsigned n = 11; amount > 0; n += 2) {\n if (factors_are_substrings(n)) {\n printf(\"%u\\n\", n);\n amount--;\n }\n }\n return 0;\n}\n", "language": "C" }, { "code": "#include <algorithm>\n#include <cstdint>\n#include <iostream>\n#include <string>\n#include <unordered_set>\n#include <vector>\n\nstd::vector<uint32_t> primes;\n\nvoid sieve_primes(const uint32_t& limit) {\n\tstd::vector<bool> marked_prime(limit + 1, true);\n\n\tfor ( uint32_t p = 2; p * p <= limit; ++p ) {\n\t\tif ( marked_prime[p] ) {\n\t\t\tfor ( uint32_t i = p * p; i <= limit; i += p ) {\n\t\t\t\tmarked_prime[i] = false;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor ( uint32_t p = 2; p <= limit; ++p ) {\n\t\tif ( marked_prime[p] ) {\n\t\t\tprimes.emplace_back(p);\n\t\t}\n\t}\n}\n\nbool is_substring(const uint32_t& k, const uint32_t& factor) {\n\tconst std::string string_k = std::to_string(k);\n\tconst std::string string_factor = std::to_string(factor);\n\treturn string_k.find(string_factor) != std::string::npos;\n}\n\nint main() {\n\tsieve_primes(30'000'000);\n\n\tstd::unordered_set<uint32_t> distinct_factors;\n\tstd::vector<uint32_t> result;\n\tuint32_t k = 11 * 11;\n\n\twhile ( result.size() < 10 ) {\n\t\twhile ( k % 3 == 0 || k % 5 == 0 || k % 7 == 0 ) {\n\t\t\tk += 2;\n\t\t}\n\n\t\tdistinct_factors.clear();\n\t\tuint32_t copy_k = k;\n\t\tuint32_t index = 4;\n\n\t\twhile ( copy_k > 1 ) {\n\t\t\twhile ( copy_k % primes[index] == 0 ) {\n\t\t\t\tdistinct_factors.insert(primes[index]);\n\t\t\t\tcopy_k /= primes[index];\n\t\t\t}\n\t\t\tindex += 1;\n\t\t}\n\n\t\tif ( distinct_factors.size() > 1 ) {\n\t\t\tif ( std::all_of(distinct_factors.begin(), distinct_factors.end(),\n\t\t\t\t\t[&k](uint32_t factor) { return is_substring(k, factor); }) ) {\n\t\t\t\tresult.emplace_back(k);\n\t\t\t}\n\t\t}\n\n\t\tk += 2;\n\t}\n\n\tfor ( uint64_t i = 0; i < result.size(); ++i ) {\n\t\tstd::cout << result[i] << \" \";\n\t}\n\tstd::cout << std::endl;\n}\n", "language": "C++" }, { "code": "procedure MultidigitComposites(Memo: TMemo);\nvar I,Cnt: integer;\nvar IA: TIntegerDynArray;\nvar Sieve: TPrimeSieve;\n\n\n\tfunction MatchCriteria(N: integer): boolean;\n\t{Test N against Criteria}\n\tvar I,L: integer;\n\tvar SN,ST: string;\n\tbegin\n\tResult:=False;\n\t{No even numbers}\n\tif (N and 1)=0 then exit;\n\t{N can't be prime}\n\tif Sieve[N] then exit;\n\tI:=3;\n\tSN:=IntToStr(N);\n\trepeat\n\t\tbegin\n\t\t{Is it a factor }\n\t\tif (N mod I) = 0 then\n\t\t\tbegin\n\t\t\t{No one-digit numbers}\n\t\t\tif I<10 then exit;\n\t\t\t{Factor string must be found in N's string}\n\t\t\tST:=IntToStr(I);\n\t\t\tif Pos(ST,SN)<1 then exit;\n\t\t\tN:=N div I;\n\t\t\tend\n\t\telse I:=I+2;\n\t\tend\n\tuntil N<=1;\n\tResult:=True;\n\tend;\n\n\nbegin\nSieve:=TPrimeSieve.Create;\ntry\n{Create 30 million primes}\nSieve.Intialize(30000000);\nCnt:=0;\n{Smallest prime factor}\nI:=11*11;\nwhile I<High(integer) do\n\tbegin\n\t{Test if I matches criteria}\n\t if MatchCriteria(I) then\n\t\tbegin\n\t\tInc(Cnt);\n\t\tMemo.Lines.Add(IntToStr(Cnt)+' - '+FloatToStrF(I,ffNumber,18,0));\n\t\tif Cnt>=20 then break;\n\t\tend;\n\tInc(I,2);\n\tend;\nfinally Sieve.Free; end;\nend;\n", "language": "Delphi" }, { "code": "fastfunc isin n k .\n h = k\n while n > 0\n if h mod 10 = n mod 10\n h = h div 10\n if match = 0\n match = n\n .\n else\n h = k\n if match <> 0\n n = match\n .\n match = 0\n .\n if h = 0\n return 1\n .\n n = n div 10\n .\n return 0\n.\n\nfastfunc test n .\n if n mod 2 = 0 or n mod 3 = 0 or n mod 5 = 0 or n mod 7 = 0\n return 0\n .\n rest = n\n fact = 11\n while fact <= rest\n if rest mod fact = 0\n while rest mod fact = 0\n rest /= fact\n .\n if isin n fact = 0\n return 0\n .\n nfacts += 1\n .\n fact += 2\n if fact > sqrt n and nfacts = 0\n return 0\n .\n .\n if nfacts > 1\n return 1\n .\n return 0\n.\nn = 11\nwhile count < 10\n if test n = 1\n print n\n count += 1\n .\n n += 2\n.\n", "language": "EasyLang" }, { "code": "// Composite numbers k with no single digit factors whose factors are all substrings of k. Nigel Galloway: January 28th., 2022\nlet fG n g=let rec fN i g e l=match i<g,g=0L,i%10L=g%10L with (true,_,_)->false |(_,true,_)->true |(_,_,true)->fN(i/10L)(g/10L) e l |_->fN l e e (l/10L) in fN n g g (n/10L)\nlet fN(g:int64)=Open.Numeric.Primes.Prime.Factors g|>Seq.skip 1|>Seq.distinct|>Seq.forall(fun n->fG g n)\nSeq.unfold(fun n->Some(n|>List.filter(fun(n:int64)->not(Open.Numeric.Primes.Prime.Numbers.IsPrime &n) && fN n),n|>List.map((+)210L)))([1L..2L..209L]\n|>List.filter(fun n->n%3L>0L && n%5L>0L && n%7L>0L))|>Seq.concat|>Seq.skip 1|>Seq.take 20|>Seq.iter(printfn \"%d\")\n", "language": "F-Sharp" }, { "code": "program FacOfInt;\n// gets factors of consecutive integers fast\n// limited to 1.2e11\n{$IFDEF FPC}\n {$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$COPERATORS ON}\n{$ELSE}\n {$APPTYPE CONSOLE}\n{$ENDIF}\nuses\n sysutils,\n strutils //Numb2USA\n{$IFDEF WINDOWS},Windows{$ENDIF}\n ;\n//######################################################################\n//prime decomposition\nconst\n//HCN(86) > 1.2E11 = 128,501,493,120 count of divs = 4096 7 3 1 1 1 1 1 1 1\n HCN_DivCnt = 4096;\ntype\n tItem = Uint64;\n tDivisors = array [0..HCN_DivCnt] of tItem;\n tpDivisor = pUint64;\nconst\n //used odd size for test only\n SizePrDeFe = 32768;//*72 <= 64kb level I or 2 Mb ~ level 2 cache\ntype\n tdigits = array [0..31] of Uint32;\n //the first number with 11 different prime factors =\n //2*3*5*7*11*13*17*19*23*29*31 = 2E11\n //56 byte\n tprimeFac = packed record\n pfSumOfDivs,\n pfRemain : Uint64;\n pfDivCnt : Uint32;\n pfMaxIdx : Uint32;\n pfpotPrimIdx : array[0..9] of word;\n pfpotMax : array[0..11] of byte;\n end;\n tpPrimeFac = ^tprimeFac;\n\n tPrimeDecompField = array[0..SizePrDeFe-1] of tprimeFac;\n tPrimes = array[0..65535] of Uint32;\n\nvar\n {$ALIGN 8}\n SmallPrimes: tPrimes;\n {$ALIGN 32}\n PrimeDecompField :tPrimeDecompField;\n pdfIDX,pdfOfs: NativeInt;\n\nprocedure InitSmallPrimes;\n//get primes. #0..65535.Sieving only odd numbers\nconst\n MAXLIMIT = (821641-1) shr 1;\nvar\n pr : array[0..MAXLIMIT] of byte;\n p,j,d,flipflop :NativeUInt;\nBegin\n SmallPrimes[0] := 2;\n fillchar(pr[0],SizeOf(pr),#0);\n p := 0;\n repeat\n repeat\n p +=1\n until pr[p]= 0;\n j := (p+1)*p*2;\n if j>MAXLIMIT then\n BREAK;\n d := 2*p+1;\n repeat\n pr[j] := 1;\n j += d;\n until j>MAXLIMIT;\n until false;\n\n SmallPrimes[1] := 3;\n SmallPrimes[2] := 5;\n j := 3;\n d := 7;\n flipflop := (2+1)-1;//7+2*2,11+2*1,13,17,19,23\n p := 3;\n repeat\n if pr[p] = 0 then\n begin\n SmallPrimes[j] := d;\n inc(j);\n end;\n d += 2*flipflop;\n p+=flipflop;\n flipflop := 3-flipflop;\n until (p > MAXLIMIT) OR (j>High(SmallPrimes));\nend;\n\nfunction OutPots(pD:tpPrimeFac;n:NativeInt):Ansistring;\nvar\n s: String[31];\n chk,p,i: NativeInt;\nBegin\n str(n,s);\n result := Format('%15s : ',[Numb2USA(s)]);\n\n with pd^ do\n begin\n chk := 1;\n For n := 0 to pfMaxIdx-1 do\n Begin\n if n>0 then\n result += '*';\n p := SmallPrimes[pfpotPrimIdx[n]];\n chk *= p;\n str(p,s);\n result += s;\n i := pfpotMax[n];\n if i >1 then\n Begin\n str(pfpotMax[n],s);\n result += '^'+s;\n repeat\n chk *= p;\n dec(i);\n until i <= 1;\n end;\n\n end;\n p := pfRemain;\n If p >1 then\n Begin\n str(p,s);\n chk *= p;\n result += '*'+s;\n end;\n end;\nend;\n\nfunction CnvtoBASE(var dgt:tDigits;n:Uint64;base:NativeUint):NativeInt;\n//n must be multiple of base aka n mod base must be 0\nvar\n q,r: Uint64;\n i : NativeInt;\nBegin\n fillchar(dgt,SizeOf(dgt),#0);\n i := 0;\n n := n div base;\n result := 0;\n repeat\n r := n;\n q := n div base;\n r -= q*base;\n n := q;\n dgt[i] := r;\n inc(i);\n until (q = 0);\n //searching lowest pot in base\n result := 0;\n while (result<i) AND (dgt[result] = 0) do\n inc(result);\n inc(result);\nend;\n\nfunction IncByBaseInBase(var dgt:tDigits;base:NativeInt):NativeInt;\nvar\n q :NativeInt;\nBegin\n result := 0;\n q := dgt[result]+1;\n if q = base then\n repeat\n dgt[result] := 0;\n inc(result);\n q := dgt[result]+1;\n until q <> base;\n dgt[result] := q;\n result +=1;\nend;\n\nfunction SieveOneSieve(var pdf:tPrimeDecompField):boolean;\nvar\n dgt:tDigits;\n i,j,k,pr,fac,n,MaxP : Uint64;\nbegin\n n := pdfOfs;\n if n+SizePrDeFe >= sqr(SmallPrimes[High(SmallPrimes)]) then\n EXIT(FALSE);\n //init\n for i := 0 to SizePrDeFe-1 do\n begin\n with pdf[i] do\n Begin\n pfDivCnt := 1;\n pfSumOfDivs := 1;\n pfRemain := n+i;\n pfMaxIdx := 0;\n pfpotPrimIdx[0] := 0;\n pfpotMax[0] := 0;\n end;\n end;\n //first factor 2. Make n+i even\n i := (pdfIdx+n) AND 1;\n IF (n = 0) AND (pdfIdx<2) then\n i := 2;\n\n repeat\n with pdf[i] do\n begin\n j := BsfQWord(n+i);\n pfMaxIdx := 1;\n pfpotPrimIdx[0] := 0;\n pfpotMax[0] := j;\n pfRemain := (n+i) shr j;\n pfSumOfDivs := (Uint64(1) shl (j+1))-1;\n pfDivCnt := j+1;\n end;\n i += 2;\n until i >=SizePrDeFe;\n //i now index in SmallPrimes\n i := 0;\n maxP := trunc(sqrt(n+SizePrDeFe))+1;\n repeat\n //search next prime that is in bounds of sieve\n if n = 0 then\n begin\n repeat\n inc(i);\n pr := SmallPrimes[i];\n k := pr-n MOD pr;\n if k < SizePrDeFe then\n break;\n until pr > MaxP;\n end\n else\n begin\n repeat\n inc(i);\n pr := SmallPrimes[i];\n k := pr-n MOD pr;\n if (k = pr) AND (n>0) then\n k:= 0;\n if k < SizePrDeFe then\n break;\n until pr > MaxP;\n end;\n\n //no need to use higher primes\n if pr*pr > n+SizePrDeFe then\n BREAK;\n\n //j is power of prime\n j := CnvtoBASE(dgt,n+k,pr);\n repeat\n with pdf[k] do\n Begin\n pfpotPrimIdx[pfMaxIdx] := i;\n pfpotMax[pfMaxIdx] := j;\n pfDivCnt *= j+1;\n fac := pr;\n repeat\n pfRemain := pfRemain DIV pr;\n dec(j);\n fac *= pr;\n until j<= 0;\n pfSumOfDivs *= (fac-1)DIV(pr-1);\n inc(pfMaxIdx);\n k += pr;\n j := IncByBaseInBase(dgt,pr);\n end;\n until k >= SizePrDeFe;\n until false;\n\n //correct sum of & count of divisors\n for i := 0 to High(pdf) do\n Begin\n with pdf[i] do\n begin\n j := pfRemain;\n if j <> 1 then\n begin\n pfSumOFDivs *= (j+1);\n pfDivCnt *=2;\n end;\n end;\n end;\n result := true;\nend;\n\nfunction NextSieve:boolean;\nbegin\n dec(pdfIDX,SizePrDeFe);\n inc(pdfOfs,SizePrDeFe);\n result := SieveOneSieve(PrimeDecompField);\nend;\n\nfunction GetNextPrimeDecomp:tpPrimeFac;\nbegin\n if pdfIDX >= SizePrDeFe then\n if Not(NextSieve) then\n EXIT(NIL);\n result := @PrimeDecompField[pdfIDX];\n inc(pdfIDX);\nend;\n\nfunction Init_Sieve(n:NativeUint):boolean;\n//Init Sieve pdfIdx,pdfOfs are Global\nbegin\n pdfIdx := n MOD SizePrDeFe;\n pdfOfs := n-pdfIdx;\n result := SieveOneSieve(PrimeDecompField);\nend;\n\nvar\n s,pr : string[31];\n pPrimeDecomp :tpPrimeFac;\n\n T0:Int64;\n n,i,cnt : NativeUInt;\n checked : boolean;\nBegin\n InitSmallPrimes;\n\n T0 := GetTickCount64;\n cnt := 0;\n n := 0;\n Init_Sieve(n);\n repeat\n pPrimeDecomp:= GetNextPrimeDecomp;\n with pPrimeDecomp^ do\n begin\n //composite with smallest factor 11\n if (pfDivCnt>=4) AND (pfpotPrimIdx[0]>3) then\n begin\n str(n,s);\n for i := 0 to pfMaxIdx-1 do\n begin\n str(smallprimes[pfpotPrimIdx[i]],pr);\n checked := (pos(pr,s)>0);\n if Not(checked) then\n Break;\n end;\n if checked then\n begin\n //writeln(cnt:4,OutPots(pPrimeDecomp,n));\n if pfRemain >1 then\n begin\n str(pfRemain,pr);\n checked := (pos(pr,s)>0);\n end;\n if checked then\n begin\n inc(cnt);\n writeln(cnt:4,OutPots(pPrimeDecomp,n));\n end;\n end;\n end;\n end;\n inc(n);\n until n > 28118827;//10*1000*1000*1000+1;//\n T0 := GetTickCount64-T0;\n writeln('runtime ',T0/1000:0:3,' s');\nend.\n", "language": "Free-Pascal-Lazarus" }, { "code": "Function isSubstring(kStr As String, f As Integer) As Integer\n Dim As String fStr = Str(f)\n Dim As Integer fLen = Len(fStr)\n Dim As Integer result = 0\n Dim As Integer fEnd = Len(kStr) - fLen + 1\n For fPos As Integer = 1 To Len(kStr) - fLen + 1\n If Mid(kStr, fPos, fLen) = fStr Then\n result = -1\n Exit For\n End If\n Next fPos\n Return result\nEnd Function\n\nDim As Integer requiredNumbers = 20\nDim As Integer kCount = 0\nFor k As Integer = 11 To 99999999 Step 2\n If k Mod 3 <> 0 And k Mod 5 <> 0 And k Mod 7 <> 0 Then\n Dim As Integer isCandidate = -1\n Dim As String kStr = Str(k)\n Dim As Integer v = k\n Dim As Integer fCount = 0\n For f As Integer = 11 To Sqr(k) + 1\n If v Mod f = 0 Then\n isCandidate = isSubstring(kStr, f)\n If isCandidate Then\n While v Mod f = 0\n fCount += 1\n v \\= f\n Wend\n Else\n Exit For\n End If\n End If\n Next f\n If isCandidate And (fCount > 1 Or (v <> k And v > 1)) Then\n If v > 1 Then isCandidate = isSubstring(kStr, v)\n If isCandidate Then\n Print Using \"#######,###\"; k;\n kCount += 1\n If kCount Mod 10 = 0 Then Print\n End If\n End If\n End If\n If kCount >= requiredNumbers Then Exit For\nNext k\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"rcu\"\n \"strconv\"\n \"strings\"\n)\n\nfunc main() {\n count := 0\n k := 11 * 11\n var res []int\n for count < 20 {\n if k%3 == 0 || k%5 == 0 || k%7 == 0 {\n k += 2\n continue\n }\n factors := rcu.PrimeFactors(k)\n if len(factors) > 1 {\n s := strconv.Itoa(k)\n includesAll := true\n prev := -1\n for _, f := range factors {\n if f == prev {\n continue\n }\n fs := strconv.Itoa(f)\n if strings.Index(s, fs) == -1 {\n includesAll = false\n break\n }\n }\n if includesAll {\n res = append(res, k)\n count++\n }\n }\n k += 2\n }\n for _, e := range res[0:10] {\n fmt.Printf(\"%10s \", rcu.Commatize(e))\n }\n fmt.Println()\n for _, e := range res[10:20] {\n fmt.Printf(\"%10s \", rcu.Commatize(e))\n }\n fmt.Println()\n}\n", "language": "Go" }, { "code": " */2 3 5 7\n210\n #1+I.0=+/|:4 q:1+i.210\n48\n", "language": "J" }, { "code": " 2{._10 ]\\(#~ */\"1@((+./@(E. '0 ',])~&>)&:(\":&.>)q:))(#~ 1-1&p:)}.,(1+I.0=+/|:4 q:1+i.210)+/~210*i.2e5\n 15317 59177 83731 119911 183347 192413 1819231 2111317 2237411 3129361\n5526173 11610313 13436683 13731373 13737841 13831103 15813251 17692313 19173071 28118827\n", "language": "J" }, { "code": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.concurrent.ThreadLocalRandom;\n\npublic final class CompositeNumbersK {\n\n\tpublic static void main(String[] aArgs) {\n\t\tint k = 11 * 11;\n\t\tList<Integer> result = new ArrayList<Integer>();\n\t\twhile ( result.size() < 20 ) {\n\t\t while ( k % 3 == 0 || k % 5 == 0 || k % 7 == 0 ) {\n\t\t k += 2;\n\t\t }\n\t\t\n\t\t List<Integer> factors = primeFactors(k);\n \t if ( factors.size() > 1 ) {\n \t String stringK = String.valueOf(k);\n \t if ( factors.stream().allMatch( factor -> stringK.indexOf(String.valueOf(factor)) >= 0 ) ) {\n \t result.add(k);\n \t }\n \t }\n \t k += 2;\t\t\n\t\t}\n\t\t\n\t\tfor ( int i = 0; i < result.size(); i++ ) {\n\t\t\tSystem.out.print(String.format(\"%10d%s\", result.get(i), ( i == 9 || i == 19 ? \"\\n\" : \"\" )));\n\t\t}\n\t}\n\t\n\tprivate static List<Integer> primeFactors(int aK) {\t\t\n\t\tList<Integer> result = new ArrayList<Integer>();\n\t\tif ( aK <= 1 ) {\n\t\t\treturn result;\n\t\t}\n\t\t\n\t\tBigInteger bigK = BigInteger.valueOf(aK);\n\t\tif ( bigK.isProbablePrime(CERTAINTY_LEVEL) ) {\n\t\t\tresult.add(aK);\n\t\t\treturn result;\n\t\t}\n\t\t\n\t\tfinal int divisor = pollardsRho(bigK).intValueExact();\n\t\tresult.addAll(primeFactors(divisor));\n\t\tresult.addAll(primeFactors(aK / divisor));\n\t\tCollections.sort(result);\n\t\treturn result;\n\t}\t\t\n\t\n\tprivate static BigInteger pollardsRho(BigInteger aN) {\n\t\tfinal BigInteger constant = new BigInteger(aN.bitLength(), RANDOM);\n\t\tBigInteger x = new BigInteger(aN.bitLength(), RANDOM);\n\t\tBigInteger xx = x;\n\t\tBigInteger divisor = null;\n\t\t\n\t\tif ( aN.mod(BigInteger.TWO).signum() == 0 ) {\n\t\t\treturn BigInteger.TWO;\n\t\t}\n\t\t\n\t\tdo {\n\t\t\tx = x.multiply(x).mod(aN).add(constant).mod(aN);\n\t\t\txx = xx.multiply(xx).mod(aN).add(constant).mod(aN);\n\t\t\txx = xx.multiply(xx).mod(aN).add(constant).mod(aN);\n\t\t\tdivisor = x.subtract(xx).gcd(aN);\n\t\t} while ( divisor.compareTo(BigInteger.ONE) == 0 );\n\t\t\n\t\treturn divisor;\n\t}\t\n\t\n\tprivate static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();\n\tprivate static final int CERTAINTY_LEVEL = 10;\n\n}\n", "language": "Java" }, { "code": "using Lazy\nusing Primes\n\nfunction containsitsonlytwodigfactors(n)\n s = string(n)\n return !isprime(n) && all(t -> length(t) > 1 && contains(s, t), map(string, collect(keys(factor(n)))))\nend\n\nseq = @>> Lazy.range(2) filter(containsitsonlytwodigfactors)\n\nforeach(p -> print(lpad(last(p), 9), first(p) == 10 ? \"\\n\" : \"\"), enumerate(take(20, seq)))\n", "language": "Julia" }, { "code": "ClearAll[CompositeAndContainsPrimeFactor]\nCompositeAndContainsPrimeFactor[k_Integer] := Module[{id, pf},\n If[CompositeQ[k],\n pf = FactorInteger[k][[All, 1]];\n If[AllTrue[pf, GreaterThan[10]],\n id = IntegerDigits[k];\n AllTrue[pf, SequenceCount[id, IntegerDigits[#]] > 0 &]\n ,\n False\n ]\n ,\n False\n ]\n ]\nout = Select[Range[30000000], CompositeAndContainsPrimeFactor]\n", "language": "Mathematica" }, { "code": "import std/[strformat, strutils]\n\nconst Max = 80_000_000 # Maximal value for composite number.\n\n# Prime factors of odd numbers.\n# If a number is prime, its factor list is empty.\nvar factors: array[0..(Max - 3) div 2, seq[uint32]]\n\ntemplate primeFactors(n: Natural): seq[uint32] =\n factors[(n - 3) shr 1]\n\n# Build the list of factors.\nfor n in countup(3u32, Max div 11, 2):\n if primeFactors(n).len == 0:\n # \"n\" is prime.\n for k in countup(n + n + n, Max, 2 * n):\n primeFactors(k).add n\n\nconst N = 20 # Number of results.\nvar n = 11 * 11\nvar count = 0\nwhile count < N:\n if primeFactors(n).len > 0:\n let nStr = $n\n block Check:\n for f in primeFactors(n):\n if f < 11 or $f notin nStr: break Check\n inc count\n echo &\"{count:2}: {insertSep($n)}\"\n inc n, 2\n", "language": "Nim" }, { "code": "/* Returns a substring of str starting at s with length n */\nssubstr(str, s = 1, n = 0) = {\n my(vt = Vecsmall(str), ve, vr, vtn = #str, n1);\n if (vtn == 0, return(\"\"));\n if (s < 1 || s > vtn, return(str));\n n1 = vtn - s + 1; if (n == 0, n = n1); if (n > n1, n = n1);\n ve = vector(n, z, z - 1 + s); vr = vecextract(vt, ve); return(Strchr(vr));\n}\n\n/* Checks if subStr is a substring of mainStr */\nisSubstring(mainStr, subStr) = {\n mainLen = #Vecsmall(mainStr);\n subLen = #Vecsmall(subStr);\n for (startPos = 1, mainLen - subLen + 1,\n if (ssubstr(mainStr, startPos, subLen) == subStr,\n return(1); /* True: subStr found in mainStr */\n )\n );\n return(0); /* False: subStr not found */\n}\n\n/* Determines if a number's factors, all > 9, are substrings of its decimal representation */\ncontains_its_prime_factors_all_over_9(n) = {\n if (n < 10 || isprime(n), return(0)); /* Skip if n < 10 or n is prime */\n strn = Str(n); /* Convert n to string */\n pfacs = factor(n)[, 1]; /* Get unique prime factors of n */\n for (i = 1, #pfacs,\n if (pfacs[i] <= 9, return(0)); /* Skip factors ≤ 9 */\n if (!isSubstring(strn, Str(pfacs[i])), return(0)); /* Check if factor is a substring */\n );\n return(1); /* All checks passed */\n}\n\n/* Main loop to find and print numbers meeting the criteria */\n{\n found = 0; /* Counter for numbers found */\n for (n = 0, 30 * 10^6, /* Iterate from 0 to 30 million */\n if (contains_its_prime_factors_all_over_9(n),\n found += 1; /* Increment counter if n meets criteria */\n print1(n, \" \"); /* Print n followed by a space */\n if (found % 10 == 0, print(\"\")); /* Newline every 10 numbers */\n if (found == 20, break); /* Stop after finding 20 numbers */\n );\n );\n}\n", "language": "PARI-GP" }, { "code": " use strict;\nuse warnings;\nuse ntheory qw<is_prime factor gcd>;\n\nmy($values,$cnt);\nLOOP: for (my $k = 11; $k < 1E10; $k += 2) {\n next if 1 < gcd($k,2*3*5*7) or is_prime $k;\n map { next if index($k, $_) < 0 } factor $k;\n $values .= sprintf \"%10d\", $k;\n last LOOP if ++$cnt == 20;\n}\nprint $values =~ s/.{1,100}\\K/\\n/gr;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">limit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">JS</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">20</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">(),</span> <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">limit</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">gcd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">f</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">prime_factors</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)></span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">valid</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">match</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]),</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">valid</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">valid</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">apply</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">sprint</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"x\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">e</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%2d: %,10d = %-17s (%s)\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Total time:%s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">)})</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">limit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">JS</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">20</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">(),</span> <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">limit</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sqrt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)),</span> <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">f</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">3</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">valid</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">match</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">valid</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">k</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">/=</span> <span style=\"color: #000000;\">f</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">f</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">match</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">valid</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">valid</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">;</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">apply</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">prime_factors</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #7060A8;\">sprint</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"x\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">e</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%2d: %,10d = %-17s (%s)\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Total time:%s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">)})</span>\n<!--\n", "language": "Phix" }, { "code": "from sympy import isprime, factorint\n\ndef contains_its_prime_factors_all_over_7(n):\n if n < 10 or isprime(n):\n return False\n strn = str(n)\n pfacs = factorint(n).keys()\n return all(f > 9 and str(f) in strn for f in pfacs)\n\nfound = 0\nfor n in range(1_000_000_000):\n if contains_its_prime_factors_all_over_7(n):\n found += 1\n print(f'{n: 12,}', end = '\\n' if found % 10 == 0 else '')\n if found == 20:\n break\n", "language": "Python" }, { "code": "use Prime::Factor;\nuse Lingua::EN::Numbers;\n\nput (2..∞).hyper(:5000batch).map( {\n next if (1 < $_ gcd 210) || .is-prime || any .&prime-factors.map: -> $n { !.contains: $n };\n $_\n} )[^20].batch(10)».&comma».fmt(\"%10s\").join: \"\\n\";\n", "language": "Raku" }, { "code": "require 'prime'\n\ngenerator2357 = Enumerator.new do |y|\n gen23 = Prime::Generator23.new\n gen23.each {|n| y << n unless (n%5 == 0 || n%7 == 0) }\nend\n\nres = generator2357.lazy.select do |n|\n primes, exp = n.prime_division.transpose\n next if exp.sum < 2 #exclude primes\n s = n.to_s\n primes.all?{|pr| s.match?(-pr.to_s) }\nend\n\nres.take(10).each{|n| puts n}\n", "language": "Ruby" }, { "code": "use primes::{is_prime,factors_uniq};\n\n/// True if non-prime n's factors, all > 9, are all substrings of its representation in base 10\nfn contains_its_prime_factors_all_over_7(n: u64) -> bool {\n if n < 10 || is_prime(n) {\n return false;\n }\n let strn = &n.to_string();\n let pfacs = factors_uniq(n);\n return pfacs.iter().all(|f| f > &9 && strn.contains(&f.to_string()));\n}\n\nfn main() {\n let mut found = 0;\n // 20 of these < 30 million\n for n in 0..30_000_000 {\n if contains_its_prime_factors_all_over_7(n) {\n found += 1;\n print!(\"{:12}{}\", n, {if found % 10 == 0 {\"\\n\"} else {\"\"}});\n if found == 20 {\n break;\n }\n }\n }\n}\n", "language": "Rust" }, { "code": "def isComposite(num: Int): Boolean = {\n val numStr = num.toString\n def iter(n: Int, start: Int): Boolean = {\n val limit = math.sqrt(n).floor.toInt\n (start to limit by 2).dropWhile(n % _ > 0).headOption match {\n case Some(v) if v < 10 => false\n case Some(v) =>\n if (v == start || numStr.contains(v.toString)) iter(n / v, v)\n else false\n case None => n < num && numStr.contains(n.toString)\n }\n }\n iter(num, 3)\n}\n\ndef composites = Iterator.from(121, 2).filter(isComposite(_))\n\n@main def main = {\n val start = System.currentTimeMillis\n composites.take(20)\n .grouped(10)\n .foreach(grp => println(grp.map(\"%8d\".format(_)).mkString(\" \")))\n val time = System.currentTimeMillis - start\n println(s\"time elapsed: $time ms\")\n}\n", "language": "Scala" }, { "code": "var e = Enumerator({|f|\n\n var c = (9.primorial)\n var a = (1..c -> grep { .is_coprime(c) })\n\n loop {\n var n = a.shift\n\n a.push(n + c)\n n.is_composite || next\n\n f(n) if n.factor.all {|p| Str(n).contains(p) }\n }\n})\n\nvar count = 10\n\ne.each {|n|\n say n\n break if (--count <= 0)\n}\n", "language": "Sidef" }, { "code": "import \"./math\" for Int\nimport \"./seq\" for Lst\nimport \"./fmt\" for Fmt\n\nvar count = 0\nvar k = 11 * 11\nvar res = []\nwhile (count < 20) {\n if (k % 3 == 0 || k % 5 == 0 || k % 7 == 0) {\n k = k + 2\n continue\n }\n var factors = Int.primeFactors(k)\n if (factors.count > 1) {\n Lst.prune(factors)\n var s = k.toString\n var includesAll = true\n for (f in factors) {\n if (s.indexOf(f.toString) == -1) {\n includesAll = false\n break\n }\n }\n if (includesAll) {\n res.add(k)\n count = count + 1\n }\n }\n k = k + 2\n}\nFmt.print(\"$,10d\", res[0..9])\nFmt.print(\"$,10d\", res[10..19])\n", "language": "Wren" }, { "code": "include xpllib; \\for ItoA, StrFind and RlOutC\nint K, C;\n\nproc Factor; \\Show certain K factors\nint L, N, F, Q;\nchar SA(10), SB(10);\n[ItoA(K, SB);\nL:= sqrt(K); \\limit for speed\nN:= K; F:= 3;\nif (N&1) = 0 then return; \\reject if 2 is a factor\nloop [Q:= N/F;\n if rem(0) = 0 then \\found a factor, F\n [if F < 10 then return; \\reject if too small (3, 5, 7)\n ItoA(F, SA); \\reject if not a sub-string\n if StrFind(SB, SA) = 0 then return;\n N:= Q;\n if F>N then quit; \\all factors found\n ]\n else [F:= F+2; \\try next prime factor\n if F>L then\n [if N=K then return; \\reject prime K\n ItoA(N, SA); \\ (it's not composite)\n if StrFind(SB, SA) = 0 then return;\n quit; \\passed all restrictions\n ];\n ];\n ];\nFormat(9, 0);\nRlOutC(0, float(K));\nC:= C+1;\nif rem(C/10) = 0 then CrLf(0);\n];\n\n[C:= 0; \\initialize element counter\nK:= 11*11; \\must have at least two 2-digit composites\nrepeat Factor;\n K:= K+2; \\must be odd because all factors > 2 are odd primes\nuntil C >= 20;\n]\n", "language": "XPL0" } ]
Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Compound_data_type\nnote: rBasic language learning\n", "language": "00-META" }, { "code": "{{Data structure}}\n\n;Task:\nCreate a compound data type:\n <big> Point(x,y) </big>\n\n\nA compound data type is one that holds multiple independent values. \n\n\n;Related task:\n* &nbsp; [[Enumeration]]\n\n\n{{Template:See also lists}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "T Point\n Int x, y\n\n F (x, y)\n .x = x\n .y = y\n", "language": "11l" }, { "code": "MAX_POINT_OBJECTS = 64 ; define a constant\n\n .rsset $0400 ; reserve memory storage starting at address $0400\npoint_x .rs MAX_POINT_OBJECTS ; reserve 64 bytes for x-coordinates\npoint_y .rs MAX_POINT_OBJECTS ; reserve 64 bytes for y-coordinates\n", "language": "6502-Assembly" }, { "code": "MAX_POINT_OBJECTS equ 64\n\npoint_ram equ $0400\npoint_x equ point_ram\npoint_y equ point_ram+MAX_POINT_OBJECTS\n", "language": "6502-Assembly" }, { "code": "MAX_POINT_OBJECTS equ 64\n\npoint_ram equ $0400\npoint_x equ point_ram\npoint_y equ point_ram+MAX_POINT_OBJECTS\n\nLDX #3\nLDA point_x,x\nSTA $00\nLDA point_y,x\nSTA $01\n", "language": "6502-Assembly" }, { "code": "(defstructure point\n (x (:assert (rationalp x)))\n (y (:assert (rationalp y))))\n\n(assign p1 (make-point :x 1 :y 2))\n(point-x (@ p1)) ; Access the x value of the point\n(assign p1 (update-point (@ p1) :x 3)) ; Update the x value\n(point-x (@ p1))\n(point-p (@ p1)) ; Recognizer for points\n", "language": "ACL2" }, { "code": "INCLUDE \"D2:REAL.ACT\" ;from the Action! Tool Kit\n\nDEFINE REALPTR=\"CARD\"\nTYPE PointI=[INT x,y]\nTYPE PointR=[REALPTR rx,ry]\n\nPROC Main()\n PointI p1\n PointR p2\n REAL realx,realy\n\n Put(125) PutE() ;clear screen\n\n p1.x=123\n p1.y=4567\n\n ValR(\"12.34\",realx)\n ValR(\"5.6789\",realy)\n p2.rx=realx\n p2.ry=realy\n\n PrintF(\"Integer point p1=(%I,%I)%E\",p1.x,p1.y)\n\n Print(\"Real point p2=(\")\n PrintR(p2.rx) Print(\",\")\n PrintR(p2.ry) Print(\")\")\nRETURN\n", "language": "Action-" }, { "code": "package\n{\n public class Point\n {\n public var x:Number;\n public var y:Number;\n\n public function Point(x:Number, y:Number)\n {\n this.x = x;\n this.y = y;\n }\n }\n}\n", "language": "ActionScript" }, { "code": "type Point is tagged record\n X : Integer := 0;\n Y : Integer := 0;\nend record;\n", "language": "Ada" }, { "code": "type Point is record\n X : Integer := 0;\n Y : Integer := 0;\nend record;\n", "language": "Ada" }, { "code": "type Person (Gender : Gender_Type) is record\n Name : Name_String;\n Age : Natural;\n Weight : Float;\n Case Gender is\n when Male =>\n Beard_Length : Float;\n when Female =>\n null;\n end case;\nend record;\n", "language": "Ada" }, { "code": "MODE UNIONX = UNION(\n STRUCT(REAL r, INT i),\n INT,\n REAL,\n STRUCT(INT ii),\n STRUCT(REAL rr),\n STRUCT([]REAL r)\n);\n", "language": "ALGOL-68" }, { "code": "UNIONX data := 6.6;\nCASE data IN\n (INT i): printf(($\"r: \"gl$,i)),\n (REAL r): printf(($\"r: \"gl$,r)),\n (STRUCT(REAL r, INT i) s): printf(($\"r&i: \"2(g)l$,s)),\n (STRUCT([]REAL r) s): printf(($\"r: \"n(UPB r OF s)(g)l$,s))\nOUT\n printf($\"Other cases\"l$)\nESAC;\n", "language": "ALGOL-68" }, { "code": "MODE POINT = STRUCT(\n INT x,\n INT y\n);\n", "language": "ALGOL-68" }, { "code": "MODE PERSON = STRUCT(\n STRING name,\n REAL age,\n REAL weight,\n UNION (\n STRUCT (REAL beard length),\n VOID\n ) gender details\n);\n", "language": "ALGOL-68" }, { "code": "begin\n % create the compound data type %\n record Point( real x, y );\n % declare a Point variable %\n reference(Point) p;\n % assign a value to p %\n p := Point( 1, 0.5 );\n % access the fields of p - note Algol W uses x(p) where many languages would use p.x %\n write( x(p), y(p) )\nend.\n", "language": "ALGOL-W" }, { "code": "OBJECT point\n x, y\nENDOBJECT\n\nPROC main()\n DEF pt:PTR TO point,\n\n NEW pt\n -> Floats are also stored as integer types making\n -> the float conversion operator necessary.\n pt.x := !10.4\n pt.y := !3.14\n END pt\nENDPROC\n", "language": "AmigaE" }, { "code": "/* ARM assembly Raspberry PI */\n/* program structure.s */\n\n/************************************/\n/* Constantes */\n/************************************/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n/*******************************************/\n/* Structures */\n/********************************************/\n .struct 0\npoint_x: @ x coordinate\n .struct point_x + 4\npoint_y: @ y coordinate\n .struct point_y + 4\npoint_end: @ end structure point\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nsMessResult: .ascii \"value x : \"\nsMessValeur: .fill 11, 1, ' ' @ size => 11\nszCarriageReturn: .asciz \"\\n\"\n\n\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\nstPoint: .skip point_end @ reservation place in memory\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: @ entry of program\n ldr r1,iAdrstPoint\n mov r0,#5 @ x value\n str r0,[r1,#point_x]\n mov r0,#10 @ y value\n str r0,[r1,#point_y]\n @ display value\n ldr r2,iAdrstPoint\n ldr r0,[r2,#point_x]\n ldr r1,iAdrsMessValeur\n bl conversion10 @ call conversion decimal\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n\n\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrsMessValeur: .int sMessValeur\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsMessResult: .int sMessResult\niAdrstPoint: .int stPoint\n\n/******************************************************************/\n/* display text with size calculation */\n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index\n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop\n @ so here r2 contains the length of the message\n mov r1,r0 @ address message in r1\n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\"\n svc #0 @ call systeme\n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */\n bx lr @ return\n/******************************************************************/\n/* Converting a register to a decimal unsigned */\n/******************************************************************/\n/* r0 contains value and r1 address area */\n/* r0 return size of result (no zero final in area) */\n/* area size => 11 bytes */\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers\n mov r3,r1\n mov r2,#LGZONECAL\n\n1: @ start loop\n bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0\n subne r2,#1 @ else previous position\n bne 1b @ and loop\n @ and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n @ and move spaces in end on area\n mov r0,r4 @ result length\n mov r1,#' ' @ space\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n\n100:\n pop {r1-r4,lr} @ restaur registres\n bx lr @return\n\n/***************************************************/\n/* division par 10 unsigned */\n/***************************************************/\n/* r0 dividende */\n/* r0 quotient */\n/* r1 remainder */\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)\n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5\n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function\niMagicNumber: \t.int 0xCCCCCCCD\n", "language": "ARM-Assembly" }, { "code": "point: #[\n\tx: 10\n\ty: 20\n]\n\nprint point\n", "language": "Arturo" }, { "code": "typedef point (t : t@ype+) = @(t, t)\nval p : point double = (1.0, 3.0)\n", "language": "ATS" }, { "code": "datatype point (t : t@ype+) =\n| Point of (t, t)\nval p : point double = Point (1.0, 3.0)\n", "language": "ATS" }, { "code": "point := Object()\npoint.x := 1\npoint.y := 0\n", "language": "AutoHotkey" }, { "code": "BEGIN {\n\tp[\"x\"]=10\n\tp[\"y\"]=42\n\n\tz = \"ZZ\"\n\tp[ z ]=999\n\n\tp[ 4 ]=5\n\t\n\tfor (i in p) print( i, \":\", p[i] )\n}\n", "language": "AWK" }, { "code": "Lbl POINT\nr₂→{r₁}ʳ\nr₃→{r₁+2}ʳ\nr₁\nReturn\n", "language": "Axe" }, { "code": "POINT(L₁,5,10)\n", "language": "Axe" }, { "code": "TYPE Point\n x AS INTEGER\n y AS INTEGER\n END TYPE\n", "language": "BASIC" }, { "code": " DIM Point{x%, y%}\n", "language": "BBC-BASIC" }, { "code": "( ( Point\n = (x=)\n (y=)\n (new=.!arg:(?(its.x).?(its.y)))\n )\n& new$(Point,(3.4)):?pt\n& out$(!(pt..x) !(pt..y))\n { Show independcy by changing x, but not y }\n& 7:?(pt..x)\n& out$(!(pt..x) !(pt..y))\n);\n", "language": "Bracmat" }, { "code": "typedef struct Point\n{\n int x;\n int y;\n} Point;\n", "language": "C" }, { "code": "struct Point\n{\n int x;\n int y;\n};\n", "language": "C++" }, { "code": "struct Point\n{\n int x;\n int y;\n Point(int ax, int ay): x(ax), y(ax) {}\n};\n", "language": "C++" }, { "code": "template<typename Coordinate> struct point\n{\n Coordinate x, y;\n};\n\n// A point with integer coordinates\nPoint<int> point1 = { 3, 5 };\n\n// a point with floating point coordinates\nPoint<float> point2 = { 1.7, 3.6 };\n", "language": "C++" }, { "code": "struct Point\n{\n public int x, y;\n public Point(int x, int y) {\n this.x = x;\n this.y = y;\n }\n}\n", "language": "C-sharp" }, { "code": ":: Point = { x :: Int, y :: Int }\n", "language": "Clean" }, { "code": ":: Point a = Point a a // usage: (Point Int)\n", "language": "Clean" }, { "code": ":: Point :== (Int, Int)\n", "language": "Clean" }, { "code": "(defrecord Point [x y])\n", "language": "Clojure" }, { "code": "(def p (Point. 0 1))\n(assert (= 0 (:x p)))\n(assert (= 1 (:y p)))\n", "language": "Clojure" }, { "code": "% Definitions\npoint = struct[x, y: int]\nmutable_point = record[x, y: int]\n\n% Initialization\np: point := point${x: 10, y: 20}\nmp: mutable_point := mutable_point${x: 10, y: 20}\n", "language": "CLU" }, { "code": "foo := p.x\nbar := p.y\n", "language": "CLU" }, { "code": "mp.x := 30\nmp.y := 40\n", "language": "CLU" }, { "code": "foo := point$get_x(p)\nbar := point$get_y(p)\n", "language": "CLU" }, { "code": "mutable_point$set_x(mp, 30)\nmutable_point$set_y(mp, 40)\n", "language": "CLU" }, { "code": " DATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 Point.\n 05 x USAGE IS BINARY-SHORT.\n 05 y USAGE IS BINARY-SHORT.\n", "language": "COBOL" }, { "code": "# Lightweight JS objects (with CS sugar).\npoint =\n x: 5\n y: 3\n\nconsole.log point.x, point.y # 5 3\n\n# Heavier OO style\nclass Point\n constructor: (@x, @y) ->\n distance_from: (p2) ->\n dx = p2.x - @x\n dy = p2.y - @y\n Math.sqrt dx*dx + dy*dy\n\np1 = new Point(1, 6)\np2 = new Point(6, 18)\nconsole.log p1 # { x: 1, y: 6 }\nconsole.log p1.distance_from # [Function]\nconsole.log p1.distance_from p2 # 13\n", "language": "CoffeeScript" }, { "code": "CL-USER> (defstruct point (x 0) (y 0)) ;If not provided, x or y default to 0\nPOINT\n", "language": "Common-Lisp" }, { "code": "CL-USER> (setf a (make-point)) ;The default constructor using the default values for x and y\n#S(POINT :X 0 :Y 0)\nCL-USER> (setf b (make-point :x 5.5 :y #C(0 1))) ;Dynamic datatypes are the default\n#S(POINT :X 5.5 :Y #C(0 1)) ;y has been set to the imaginary number i (using the Common Lisp complex number data type)\nCL-USER> (point-x b) ;The default name for the accessor functions is structname-slotname\n5.5\nCL-USER> (point-y b)\n#C(0 1)\nCL-USER> (setf (point-y b) 3) ;The accessor is setfable\n3\nCL-USER> (point-y b)\n3\n", "language": "Common-Lisp" }, { "code": "struct Point(T)\n getter x : T\n getter y : T\n def initialize(@x, @y)\n end\nend\n\nputs Point(Int32).new 13, 12 #=> Point(Int32)(@x=13, @y=12)\n", "language": "Crystal" }, { "code": "void main() {\n // A normal POD struct\n // (if it's nested and it's not static then it has a hidden\n // field that points to the enclosing function):\n static struct Point {\n int x, y;\n }\n\n auto p1 = Point(10, 20);\n\n // It can also be parametrized on the coordinate type:\n static struct Pair(T) {\n T x, y;\n }\n\n // A pair with integer coordinates:\n auto p2 = Pair!int(3, 5);\n\n // A pair with floating point coordinates:\n auto p3 = Pair!double(3, 5);\n\n // Classes (static inner):\n static class PointClass {\n int x, y;\n this(int x_, int y_) {\n this.x = x_;\n this.y = y_;\n }\n }\n\n auto p4 = new PointClass(1, 2);\n\n // There are also library-defined tuples:\n import std.typecons;\n\n alias Tuple!(int,\"x\", int,\"y\") PointXY;\n\n auto p5 = PointXY(3, 5);\n\n // And even built-in \"type tuples\":\n import std.typetuple;\n\n alias TypeTuple!(int, 5) p6;\n\n static assert(is(p6[0] == int));\n static assert(p6[1] == 5);\n}\n", "language": "D" }, { "code": " TPoint = record\n X: Longint;\n Y: Longint;\n end;\n", "language": "Delphi" }, { "code": "use_namespace(rosettacode)_me();\n\nadd_struct(point)_arg(x,y);\n\nwith_point(point1)_arg(4,3);\n\n// Since no datatype is specified for the args any datatype can be passed\nwith_point(point2)_arg(0.033,👣);\n\nreset_namespace[];\n", "language": "Diego" }, { "code": "def makePoint(x, y) {\n def point {\n to getX() { return x }\n to getY() { return y }\n }\n return point\n}\n", "language": "E" }, { "code": "(lib 'struct)\n (struct Point (x y))\n (Point 3 4)\n → #<Point> (3 4)\n\n;; run-time type checking is possible\n(lib 'types)\n (struct Point (x y))\n (struct-type Point Number Number)\n (Point 3 4)\n (Point 3 'albert)\n❌ error: #number? : type-check failure : albert → 'Point:y'\n", "language": "EchoLisp" }, { "code": "type Maybe = None | Some a\n", "language": "Ela" }, { "code": "opentype Several = One | Two | Three\n\n//Add new constructor to an existing type\ndata Several = Four\n", "language": "Ela" }, { "code": "struct Point\n{\n int X : prop;\n\n int Y : prop;\n\n constructor new(int x, int y)\n {\n X := x;\n Y := y\n }\n}\n", "language": "Elena" }, { "code": "iex(1)> defmodule Point do\n...(1)> defstruct x: 0, y: 0\n...(1)> end\n{:module, Point, <<70, 79, 82, ...>>, %Point{x: 0, y: 0}}\niex(2)> origin = %Point{}\n%Point{x: 0, y: 0}\niex(3)> pa = %Point{x: 10, y: 20}\n%Point{x: 10, y: 20}\niex(4)> pa.x\n10\niex(5)> %Point{pa | y: 30}\n%Point{x: 10, y: 30}\niex(6)> %Point{x: px, y: py} = pa # pattern matching\n%Point{x: 10, y: 20}\niex(7)> px\n10\niex(8)> py\n20\n", "language": "Elixir" }, { "code": "--Compound Data type can hold multiple independent values\n--In Elm data can be compounded using List, Tuple, Record\n--In a List\npoint = [2,5]\n--This creates a list having x and y which are independent and can be accessed by List functions\n--Note that x and y must be of same data type\n\n--Tuple is another useful data type that stores different independent values\npoint = (3,4)\n--Here we can have multiple data types\npoint1 = (\"x\",\"y\")\npoint2 = (3,4.5)\n--The order of addressing matters\n--Using a Record is the best option\npoint = {x=3,y=4}\n--To access\npoint.x\npoint.y\n--Or Use it as a function\n.x point\n.y point\n--Also to alter the value\n{point | x=7}\n{point | y=2}\n{point | x=3,y=4}\n--Each time a new record is generated\n--END\n", "language": "Elm" }, { "code": "-module(records_test).\n-compile(export_all).\n\n-record(point,{x,y}).\n\ntest() ->\n P1 = #point{x=1.0,y=2.0}, % creates a new point record\n io:fwrite(\"X: ~f, Y: ~f~n\",[P1#point.x,P1#point.y]),\n P2 = P1#point{x=3.0}, % creates a new point record with x set to 3.0, y is copied from P1\n io:fwrite(\"X: ~f, Y: ~f~n\",[P2#point.x,P2#point.y]).\n", "language": "Erlang" }, { "code": "enum x, y\n\nsequence point = {0,0}\n\nprintf(1,\"x = %d, y = %3.3f\\n\",point)\n\npoint[x] = 'A'\npoint[y] = 53.42\n\nprintf(1,\"x = %d, y = %3.3f\\n\",point)\nprintf(1,\"x = %s, y = %3.3f\\n\",point)\n", "language": "Euphoria" }, { "code": "type Point = { x : int; y : int }\n\nlet points = [\n {x = 1; y = 1};\n {x = 5; y = 5} ]\n\nSeq.iter (fun p -> printfn \"%d,%d\" p.x p.y) points\n", "language": "F-Sharp" }, { "code": "TUPLE: point x y ;\n", "language": "Factor" }, { "code": "// define a class to contain the two fields\n// accessors to get/set the field values are automatically generated\nclass Point\n{\n Int x\n Int y\n}\n\nclass Main\n{\n public static Void main ()\n {\n // empty constructor, so x,y set to 0\n point1 := Point()\n // constructor uses with-block, to initialise values\n point2 := Point { x = 1; y = 2}\n echo (\"Point 1 = (\" + point1.x + \", \" + point1.y + \")\")\n echo (\"Point 2 = (\" + point2.x + \", \" + point2.y + \")\")\n }\n}\n", "language": "Fantom" }, { "code": ": pt>x ( point -- x ) ;\n: pt>y ( point -- y ) CELL+ ;\n: .pt ( point -- ) dup pt>x @ . pt>y @ . ; \\ or for this simple structure, 2@ . .\n\ncreate point 6 , 0 ,\n7 point pt>y !\n.pt \\ 6 7\n", "language": "Forth" }, { "code": "struct\n cell% field pt>x\n cell% field pt>y\nend-struct point%\n", "language": "Forth" }, { "code": "program typedemo\n type rational ! Type declaration\n integer :: numerator\n integer :: denominator\n end type rational\n\n type( rational ), parameter :: zero = rational( 0, 1 ) ! Variables initialized\n type( rational ), parameter :: one = rational( 1, 1 ) ! by constructor syntax\n type( rational ), parameter :: half = rational( 1, 2 )\n integer :: n, halfd, halfn\n type( rational ) :: &\n one_over_n(20) = (/ (rational( 1, n ), n = 1, 20) /) ! Array initialized with\n ! constructor inside\n ! implied-do array initializer\n integer :: oon_denoms(20)\n\n halfd = half%denominator ! field access with \"%\" delimiter\n halfn = half%numerator\n\n oon_denoms = one_over_n%denominator ! Access denominator field in every\n ! rational array element & store\nend program typedemo ! as integer array\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nType Point\n As Integer x, y\nEnd Type\n\nDim p As Point = (1, 2)\nDim p2 As Point = (3, 4)\nPrint p.x, p.y\nPrint p2.x, p2.y\nSleep\n", "language": "FreeBASIC" }, { "code": "CGRect r = {0, 0, 250, 100}\nprintf @\"x = %.f : y = %.f : width = %.f : height = %.f\", r.origin.x, r.origin.y, r.size.width, r.size.height\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "type point struct {\n x, y float64\n}\n", "language": "Go" }, { "code": "class Point {\n int x\n int y\n\n // Default values make this a 0-, 1-, and 2-argument constructor\n Point(int x = 0, int y = 0) { this.x = x; this.y = y }\n String toString() { \"{x:${x}, y:${y}}\" }\n}\n", "language": "Groovy" }, { "code": "// Default Construction with explicit property setting:\ndef p0 = new Point()\nassert 0 == p0.x\nassert 0 == p0.y\np0.x = 36\np0.y = -2\nassert 36 == p0.x\nassert -2 == p0.y\n\n// Direct Construction:\ndef p1 = new Point(36, -2)\nassert 36 == p1.x\nassert -2 == p1.y\n\ndef p2 = new Point(36)\nassert 36 == p2.x\nassert 0 == p2.y\n", "language": "Groovy" }, { "code": "// Explicit coersion from list with \"as\" keyword\ndef p4 = [36, -2] as Point\nassert 36 == p4.x\nassert -2 == p4.y\n\n// Explicit coersion from list with Java/C-style casting\np4 = (Point) [36, -2]\nprintln p4\nassert 36 == p4.x\nassert -2 == p4.y\n\n// Implicit coercion from list (by type of variable)\nPoint p6 = [36, -2]\nassert 36 == p6.x\nassert -2 == p6.y\n\nPoint p8 = [36]\nassert 36 == p8.x\nassert 0 == p8.y\n", "language": "Groovy" }, { "code": "// Direct map-based construction\ndef p3 = new Point([x: 36, y: -2])\nassert 36 == p3.x\nassert -2 == p3.y\n\n// Direct map-entry-based construction\np3 = new Point(x: 36, y: -2)\nassert 36 == p3.x\nassert -2 == p3.y\n\np3 = new Point(x: 36)\nassert 36 == p3.x\nassert 0 == p3.y\n\np3 = new Point(y: -2)\nassert 0 == p3.x\nassert -2 == p3.y\n\n// Explicit coercion from map with \"as\" keyword\ndef p5 = [x: 36, y: -2] as Point\nassert 36 == p5.x\nassert -2 == p5.y\n\n// Implicit coercion from map (by type of variable)\nPoint p7 = [x: 36, y: -2]\nassert 36 == p7.x\nassert -2 == p7.y\n\nPoint p9 = [y:-2]\nassert 0 == p9.x\nassert -2 == p9.y\n", "language": "Groovy" }, { "code": "p = (2,3)\n", "language": "Haskell" }, { "code": "record Point(x,y)\n", "language": "Icon" }, { "code": "point = {x: 6 , y: 0 }\npoint.y = 7\nprint, point\n;=> { 6 7}\n", "language": "IDL" }, { "code": " NB. Create a \"Point\" class\n coclass'Point'\n\n NB. Define its constructor\n create =: 3 : 0\n 'X Y' =: y\n )\n\n NB. Instantiate an instance (i.e. an object)\n cocurrent 'base'\n P =: 10 20 conew 'Point'\n\n NB. Interrogate its members\n X__P\n10\n Y__P\n20\n", "language": "J" }, { "code": "struct Point {\n x: i64\n y: i64\n}\n\nfn main() {\n println(\"{}\", Point(x: 3, y: 4))\n}\n", "language": "Jakt" }, { "code": "record Point(int x, int y) { }\n", "language": "Java" }, { "code": "Point point = new Point(1, 2);\nint x = point.x;\nint y = point.y;\n", "language": "Java" }, { "code": "public class Point\n{\n public int x, y;\n public Point() { this(0); }\n public Point(int x0) { this(x0,0); }\n public Point(int x0, int y0) { x = x0; y = y0; }\n\n public static void main(String args[])\n {\n Point point = new Point(1,2);\n System.out.println(\"x = \" + point.x );\n System.out.println(\"y = \" + point.y );\n }\n}\n", "language": "Java" }, { "code": "//using object literal syntax\nvar point = {x : 1, y : 2};\n\n//using constructor\nvar Point = function (x, y) {\n this.x = x;\n this.y = y;\n};\npoint = new Point(1, 2);\n\n//using ES6 class syntax\nclass Point {\n constructor(x, y) {\n this.x = x;\n this.y = y;\n }\n}\npoint = new Point(1, 2);\n", "language": "JavaScript" }, { "code": "{\"x\":1, \"y\":2}\n", "language": "Jq" }, { "code": "{\"x\":1, \"y\":2, type: \"Point\"}\n", "language": "Jq" }, { "code": "struct Point{T<:Real}\n x::T\n y::T\nend\n", "language": "Julia" }, { "code": "Base.:(==)(u::Point, v::Point) = u.x == v.x && u.y == v.y\nBase.:-(u::Point) = Point(-u.x, -u.y)\nBase.:+(u::Point, v::Point) = Point(u.x + v.x, u.y + v.y)\nBase.:-(u::Point, v::Point) = u + (-v)\n", "language": "Julia" }, { "code": "a, b, c = Point(1, 2), Point(3, 7), Point(2, 4)\n@show a b c\n@show a + b\n@show -a + b\n@show a - b\n@show a + b + c\n@show a == b\n@show a + a == c\n", "language": "Julia" }, { "code": "Var:Create(\n Point,\n Number x,\n Number y\n)\n", "language": "KonsolScript" }, { "code": "function main() {\n Var:Point point;\n}\n", "language": "KonsolScript" }, { "code": "data class Point(var x: Int, var y: Int)\n\nfun main(args: Array<String>) {\n val p = Point(1, 2)\n println(p)\n p.x = 3\n p.y = 4\n println(p)\n}\n", "language": "Kotlin" }, { "code": "1) a pair\n{def P {P.new 1 2}}\n-> P\n{P.left {P}}\n-> 1\n{P.right {P}}\n-> 2\n\n2) its Lispsish variant\n{def Q {cons 1 2}}\n-> Q\n{car {Q}}\n-> 1\n{cdr {Q}}\n-> 2\n\n3) as an array\n{def R {A.new 1 2}}\n-> R\n{A.first {R}}\n-> 1\n{A.last {R}}\n-> 2\n", "language": "Lambdatalk" }, { "code": "&Point = {\n\t$x\n\t$y\n}\n", "language": "Lang" }, { "code": "define Point => type {\n parent pair\n\n public onCreate(x,y) => {\n ..onCreate(#x=#y)\n }\n\n public x => .first\n public y => .second\n}\n\nlocal(point) = Point(33, 42)\n#point->x\n#point->y\n", "language": "Lasso" }, { "code": "(defrecord point\n x\n y)\n", "language": "LFE" }, { "code": "-- parent script \"MyPoint\"\nproperty x\nproperty y\non new (me, px, py)\n me.x = px\n me.y = py\n return me\nend\n", "language": "Lingo" }, { "code": "p = script(\"MyPoint\").new(23, 42)\nput p.x, p.y\n-- 23 42\n", "language": "Lingo" }, { "code": "-- in some movie script\non MyPoint (x, y)\n return script(\"MyPoint\").new(x, y)\nend\n", "language": "Lingo" }, { "code": "p = MyPoint(23, 42)\nput p.x, p.y\n-- 23 42\n", "language": "Lingo" }, { "code": "setpos [100 100] setpos [100 0] setpos [0 0]\nshow pos ; [0 0]\n", "language": "Logo" }, { "code": "until [(first mousepos) < 0] [ifelse button? [pendown] [penup] setpos mousepos]\n", "language": "Logo" }, { "code": "a = {x = 1; y = 2}\nb = {x = 3; y = 4}\nc = {\n x = a.x + b.x;\n y = a.y + b.y\n}\nprint(a.x, a.y) --> 1 2\nprint(c.x, c.y) --> 4 6\n", "language": "Lua" }, { "code": "cPoint = {} -- metatable (behaviour table)\nfunction newPoint(x, y) -- constructor\n local pointPrototype = {} -- prototype declaration\n function pointPrototype:getX() return x end -- public method\n function pointPrototype:getY() return y end -- public method\n function pointPrototype:getXY() return x, y end -- public method\n function pointPrototype:type() return \"point\" end -- public method\n return setmetatable(pointPrototype, cPoint) -- set behaviour and return the pointPrototype\nend--newPoint\n", "language": "Lua" }, { "code": "local oldtype = type; -- store original type function\nfunction type(v)\n local vType = oldtype(v)\n if (vType==\"table\" and v.type) then\n return v:type() -- bypass original type function if possible\n else\n return vType\n end--if vType==\"table\"\nend--type\n", "language": "Lua" }, { "code": "function cPoint.__add(op1, op2) -- add the x and y components\n if type(op1)==\"point\" and type(op2)==\"point\" then\n return newPoint(\n op1:getX()+op2:getX(),\n op1:getY()+op2:getY())\n end--if type(op1)\nend--cPoint.__add\nfunction cPoint.__sub(op1, op2) -- subtract the x and y components\n if (type(op1)==\"point\" and type(op2)==\"point\") then\n return newPoint(\n op1:getX()-op2:getX(),\n op1:getY()-op2:getY())\n end--if type(op1)\nend--cPoint.__sub\n", "language": "Lua" }, { "code": "a = newPoint(1, 2)\nb = newPoint(3, 4)\nc = a + b -- using __add behaviour\nprint(a:getXY()) --> 1 2\nprint(type(a)) --> point\nprint(c:getXY()) --> 4 6\nprint((a-b):getXY()) --> -2 -2 -- using __sub behaviour\n", "language": "Lua" }, { "code": "Point:= Record(x = 2,y = 4):\n\nPoint:-x;\nPoint:-y;\n", "language": "Maple" }, { "code": "In[1]:= a = point[2, 3]\n\nOut[1]= point[2, 3]\n\nIn[2]:= a[[2]]\n\nOut[2]= 3\n\nIn[3]:= a[[2]] = 4; a\n\nOut[3]= point[2, 4]\n", "language": "Mathematica" }, { "code": "p[x] = 2; p[y] = 3;\n", "language": "Mathematica" }, { "code": " point.x=3;\n point.y=4;\n", "language": "MATLAB" }, { "code": " point = [3,4];\n", "language": "MATLAB" }, { "code": "defstruct(point(x, y))$\n\np: new(point)$\n\nq: point(1, 2)$\n\np@x: 5$\n", "language": "Maxima" }, { "code": "struct myPoint (x, y)\nnewPoint = myPoint x:3 y:4\n", "language": "MAXScript" }, { "code": "newPoint = Point2 3 4\n", "language": "MAXScript" }, { "code": "Point = {}\nPoint.x = 0\nPoint.y = 0\n", "language": "MiniScript" }, { "code": "TYPE Point = RECORD\n x, y : INTEGER\nEND;\n", "language": "Modula-2" }, { "code": "VAR point : Point;\n...\npoint.x := 12;\npoint.y := 7;\n", "language": "Modula-2" }, { "code": "TYPE Point = RECORD\n x, y: INTEGER;\nEND;\n", "language": "Modula-3" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\nclass RCompoundDataType\n method main(args = String[]) public static\n pp = Point(2, 4)\n say pp\n return\n\nclass RCompoundDataType.Point -- inner class \"Point\"\n properties indirect -- have NetRexx create getters & setters\n x = Integer\n y = Integer\n\n method Point(x_ = 0, y_ = 0) public -- providing default values for x_ & y_ lets NetRexx generate intermediate constructors Point() & Point(x_)\n this.x = Integer(x_)\n this.y = Integer(y_)\n return\n\n method toString() public returns String\n res = 'X='getX()',Y='getY()\n return res\n", "language": "NetRexx" }, { "code": "type Point = tuple[x, y: int]\n\nvar p: Point = (12, 13)\nvar p2: Point = (x: 100, y: 200)\n", "language": "Nim" }, { "code": "MODULE Point;\nTYPE\n\tObject* = POINTER TO ObjectDesc;\n\tObjectDesc* = RECORD\n\t\tx-,y-: INTEGER;\n\tEND;\n\n\tPROCEDURE (p: Object) Init(x,y: INTEGER);\n\tBEGIN\n\t\tp.x := x; p.y := y\n\tEND Init;\n\n\tPROCEDURE New*(x,y: INTEGER): Object;\n\tVAR\n\t\tp: Object;\n\tBEGIN\n\t\tNEW(p);p.Init(x,y);RETURN p;\n\tEND New;\n\nEND Point.\n", "language": "Oberon" }, { "code": "class Point {\n @x : Int;\n @y : Int;\n\n New() {\n @x := 0;\n @y := 0;\n }\n\n New(x : Int, y : Int) {\n @x := x;\n @y := y;\n }\n\n New(p : Point) {\n @x := p->GetX();\n @y := p->GetY();\n }\n\n method : public : GetX() ~ Int {\n return @x;\n }\n\n method : public : GetY() ~ Int {\n return @y;\n }\n\n method : public : SetX(x : Int) ~ Nil {\n @x := x;\n }\n\n method : public : SetY(y : Int) ~ Nil {\n @y := y;\n }\n}\n", "language": "Objeck" }, { "code": "type tree = Empty\n | Leaf of int\n | Node of tree * tree\n\nlet t1 = Node (Leaf 1, Node (Leaf 2, Leaf 3))\n", "language": "OCaml" }, { "code": "type point = { x : int; y : int }\n", "language": "OCaml" }, { "code": "let p = { x = 4; y = 5 }\n", "language": "OCaml" }, { "code": "p.x (* evaluates to 4 *)\n", "language": "OCaml" }, { "code": "type mutable_point = { mutable x2 : int; mutable y2 : int }\n", "language": "OCaml" }, { "code": "let p2 = { x2 = 4; y2 = 5 } in\n p2.x2 <- 6;\n p2 (* evaluates to { x2 = 6; y2 = 5 } *)\n", "language": "OCaml" }, { "code": "let p = (2,3)\n", "language": "OCaml" }, { "code": "Object Class new: Point(x, y)\n", "language": "Oforth" }, { "code": "p = .point~new(3,4)\nsay \"x =\" p~x\nsay \"y =\" p~y\n\n::class point\n::method init\n expose x y\n use strict arg x = 0, y = 0 -- defaults to 0 for any non-specified coordinates\n\n::attribute x\n::attribute y\n", "language": "OoRexx" }, { "code": "def temp-table point\n field x as int\n field y as int\n .\n", "language": "OpenEdge-Progress" }, { "code": "'SHORT FORM\ntype point float x,y\n\n'FULL FORM\ntype point\n float x\n float y\nend type\n\npoint p\n\n'WITH DEFAULT VALUES\ntype point\n float x = 1.0\n float y = 1.0\nend type\n\npoint p = {} 'assigns the set of default values\n\n\nprint p.x \" \" p.y\n", "language": "OxygenBasic" }, { "code": "P = point(x:1 y:2)\n", "language": "Oz" }, { "code": "case P of point(x:X y:Y) then\n {Show X}\n {Show Y}\nend\n", "language": "Oz" }, { "code": "point.x=1;\npoint.y=2;\n", "language": "PARI-GP" }, { "code": "type point = record\n x, y: integer;\n end;\n", "language": "Pascal" }, { "code": "my @point = (3, 8);\n", "language": "Perl" }, { "code": "my %point = (\n x => 3,\n y => 8\n);\n", "language": "Perl" }, { "code": "package Point;\n\nuse strict;\nuse base 'Class::Struct'\n x => '$',\n y => '$',\n;\n\nmy $point = Point->new(x => 3, y => 8);\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">enum</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span>\n <span style=\"color: #008080;\">type</span> <span style=\"color: #000000;\">point</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004080;\">sequence</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">y</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #004080;\">atom</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #004080;\">atom</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">type</span>\n\n <span style=\"color: #000000;\">point</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">175</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3.375</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]*</span><span style=\"color: #000000;\">20</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"point p is \"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">p</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"p[x]:%g, p[y]:%g\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]})</span>\n <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #000080;font-style:italic;\">-- fine</span>\n <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"string\"</span> <span style=\"color: #000080;font-style:italic;\">-- run-time error (not pwa/p2js)</span>\n<!--\n", "language": "Phix" }, { "code": "-->\n <span style=\"color: #008080;\">class</span> <span style=\"color: #000000;\">point</span>\n <span style=\"color: #008080;\">public</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">class</span>\n\n <span style=\"color: #000000;\">point</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">new</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">175</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3.375</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">20</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"p.x:%g, p.y:%g\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #000080;font-style:italic;\">-- fine</span>\n <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">y</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"string\"</span> <span style=\"color: #000080;font-style:italic;\">-- run-time error</span>\n<!--\n", "language": "Phix" }, { "code": "# Using pack/unpack\n$point = pack(\"ii\", 1, 2);\n\n$u = unpack(\"ix/iy\", $point);\necho $x;\necho $y;\n\nlist($x,$y) = unpack(\"ii\", $point);\necho $x;\necho $y;\n", "language": "PHP" }, { "code": "# Using array\n$point = array('x' => 1, 'y' => 2);\n\nlist($x, $y) = $point;\necho $x, ' ', $y, \"\\n\";\n\n# or simply:\necho $point['x'], ' ', $point['y'], \"\\n\";\n", "language": "PHP" }, { "code": "# Using class\nclass Point {\n function __construct($x, $y) { $this->x = $x; $this->y = $y; }\n function __tostring() { return $this->x . ' ' . $this->y . \"\\n\"; }\n}\n$point = new Point(1, 2);\necho $point; # will call __tostring() in later releases of PHP 5.2; before that, it won't work so good.\n", "language": "PHP" }, { "code": "(class +Point)\n\n(dm T (X Y)\n (=: x X)\n (=: y Y) )\n\n(setq P (new '(+Point) 3 4))\n\n(show P)\n", "language": "PicoLisp" }, { "code": "class Point {\n int x, y;\n void create(int _x, int _y)\n {\n x = _x;\n y = _y;\n }\n}\n\nvoid main()\n{\n object point = Point(10, 20);\n write(\"%d %d\\n\", point->x, point->y);\n}\n", "language": "Pike" }, { "code": "define structure\n 1 point,\n 2 x float,\n 2 y float;\n", "language": "PL-I" }, { "code": "A cartesian point is a record with an x coord and a y coord.\n", "language": "Plain-English" }, { "code": "uses objectclass;\ndefine :class Point;\n slot x = 0;\n slot y = 0;\nenddefine;\n", "language": "Pop11" }, { "code": "class Point {\n [Int]$a\n [Int]$b\n Point() {\n $this.a = 0\n $this.b = 0\n }\n Point([Int]$a, [Int]$b) {\n $this.a = $a\n $this.b = $b\n }\n [Int]add() {return $this.a + $this.b}\n [Int]mul() {return $this.a * $this.b}\n}\n$p1 = [Point]::new()\n$p2 = [Point]::new(3,2)\n$p1.add()\n$p2.mul()\n", "language": "PowerShell" }, { "code": "point(10, 20).\n", "language": "Prolog" }, { "code": "?- point(X,Y).\nX = 10,\nY = 20.\n", "language": "Prolog" }, { "code": "person_location(person(name(N), age(A)), point(X, Y)).\n", "language": "Prolog" }, { "code": "Structure MyPoint\n x.i\n y.i\nEndStructure\n", "language": "PureBasic" }, { "code": "X, Y = 0, 1\np = (3, 4)\np = [3, 4]\n\nprint p[X]\n", "language": "Python" }, { "code": "class Point:\n def __init__(self, x=0, y=0):\n self.x = x\n self.y = y\n\np = Point()\nprint p.x\n", "language": "Python" }, { "code": "class MyObject(object): pass\npoint = MyObject()\npoint.x, point.y = 0, 1\n# objects directly instantiated from \"object()\" cannot be \"monkey patched\"\n# however this can generally be done to it's subclasses\n", "language": "Python" }, { "code": "pseudo_object = {'x': 1, 'y': 2}\n", "language": "Python" }, { "code": ">>> from collections import namedtuple\n>>> help(namedtuple)\nHelp on function namedtuple in module collections:\n\nnamedtuple(typename, field_names, verbose=False)\n Returns a new subclass of tuple with named fields.\n\n >>> Point = namedtuple('Point', 'x y')\n >>> Point.__doc__ # docstring for the new class\n 'Point(x, y)'\n >>> p = Point(11, y=22) # instantiate with positional args or keywords\n >>> p[0] + p[1] # indexable like a plain tuple\n 33\n >>> x, y = p # unpack like a regular tuple\n >>> x, y\n (11, 22)\n >>> p.x + p.y # fields also accessable by name\n 33\n >>> d = p._asdict() # convert to a dictionary\n >>> d['x']\n 11\n >>> Point(**d) # convert from a dictionary\n Point(x=11, y=22)\n >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields\n Point(x=100, y=22)\n\n>>>\n", "language": "Python" }, { "code": "Type Point\n x As Double\n y As Double\nEnd Type\n\nDim p As Point\np.x = 15.42\np.y = 2.412\n\nPrint p.x; p.y\n", "language": "QB64" }, { "code": " [ ' [ 0 0 ] ] is point ( --> [ )\n\n [ 0 ] is x ( --> n )\n\n [ 1 ] is y ( --> n )\n\n point\n dup x peek echo cr\n 99 swap y poke\n y peek echo cr\n", "language": "Quackery" }, { "code": " struct{\n item.0\n { item.1.0\n item.1.1\n { item.1.2.0\n item.1.2.1\n item.1.2.2\n item.1.2.3\n } item.1.2\n item.1.3\n } item.1\n item.2\n }struct mystruct\n", "language": "Quackery" }, { "code": " mystruct ( create new instance of a mystruct )\n dup echo cr ( this is what it looks like )\n 789 swap item.1.3 {poke} ( change one of the items )\n dup echo cr ( this is what it looks like now )\n item.1.3 {peek} echo cr ( retrieve the specified item )\n", "language": "Quackery" }, { "code": " [ witheach peek ] is {peek} ( { p --> x )\n\n [ dip dup\n witheach [ peek dup ]\n drop ] is depack ( { p --> * )\n\n [ reverse\n witheach\n [ dip swap poke ] ] is repack ( * p --> { )\n\n [ dup dip\n [ rot dip\n [ depack drop ] ]\n repack ] is {poke} ( x { p --> { )\n\n [ this ] is null ( --> [ )\n\n [ stack ] is {}.path ( --> s )\n protect {}.path\n\n [ stack ] is {}.struct ( --> s )\n protect {}.struct\n\n [ nextword dup\n $ \"\" = if\n [ $ \"Unexpected end of struct.\"\n message put\n bail ] ] is {}.checknext ( [ $ --> [ $ $ )\n\n [ dup $ \"{\" =\n over $ \"}\" = or\n swap $ \"}struct\" = or if\n [ $ \"Name missing after }.\"\n message put\n bail ] ] is {}.checkname ( [ $ $ --> [ $ )\n\n [ nested\n namenest take\n join\n namenest put\n ' [ ' ]\n {}.path share nested join\n actiontable take\n 1 stuff\n actiontable put ] is {}.addpath ( [ $ $ --> [ $ )\n\n [ nested\n namenest take\n join\n namenest put\n ' [ ' ]\n {}.struct share nested join\n actiontable take\n 1 stuff\n actiontable put ] is {}.addstruct ( [ $ $ --> [ $ )\n\n [ {}.path take\n dup -1 peek\n 1+\n swap -1 poke\n -1 join\n {}.path put\n [] {}.struct put ] is {}.{ ( [ $ --> [ $ )\n\n [ {}.struct size 3 < if\n [ $ \"Badly formed struct.\"\n message put bail ]\n trim {}.checknext\n dup {}.checkname\n {}.path take\n -1 split drop\n {}.path put\n {}.addpath\n {}.struct take\n {}.struct take\n swap nested join\n {}.struct put ] is {}.} ( [ $ --> [ $ )\n\n [ {}.path take\n dup -1 peek\n 1+\n swap -1 poke\n {}.path put\n {}.addpath\n {}.struct take\n ' [ null ] join\n {}.struct put ] is {}.name ( [ $ --> [ $ )\n\n [ trim {}.checknext\n {}.struct size\n 2 != if\n [ $ \"Badly formed struct.\"\n message put\n bail ]\n {}.addstruct ] is {}.}struct ( [ $ --> [ $ )\n\n [ ' [ -1 ] {}.path put\n [] {}.struct put\n [ trim {}.checknext\n dup $ \"{\" = iff\n [ drop {}.{ ] again\n dup $ \"}\" = iff\n [ drop {}.} ] again\n dup $ \"}struct\" = iff\n [ drop {}.}struct ] done\n {}.name again ]\n {}.struct release\n {}.path release ] builds struct{ ( [ $ --> [ $ )\n", "language": "Quackery" }, { "code": " struct{ x y }struct point\n point\n dup x {peek} echo cr\n 99 swap y {poke}\n y {peek} echo cr\n", "language": "Quackery" }, { "code": "mypoint <- list(x=3.4, y=6.7)\n# $x\n# [1] 3.4\n# $y\n# [1] 6.7\nmypoint$x # 3.4\n\nlist(a=1:10, b=\"abc\", c=runif(10), d=list(e=1L, f=TRUE))\n# $a\n# [1] 1 2 3 4 5 6 7 8 9 10\n# $b\n# [1] \"abc\"\n# $c\n# [1] 0.64862897 0.73669435 0.11138945 0.10408015 0.46843836 0.32351247\n# [7] 0.20528914 0.78512472 0.06139691 0.76937113\n# $d\n# $d$e\n# [1] 1\n# $d$f\n# [1] TRUE\n", "language": "R" }, { "code": "#lang racket\n(struct point (x y))\n", "language": "Racket" }, { "code": "#lang racket\n(define point% ; classes are suffixed with % by convention\n (class object%\n (super-new)\n (init-field x y)))\n", "language": "Racket" }, { "code": "my @point = 3, 8;\n\nmy Int @point = 3, 8; # or constrain to integer elements\n", "language": "Raku" }, { "code": "my %point = x => 3, y => 8;\n\nmy Int %point = x => 3, y => 8; # or constrain the hash to have integer values\n", "language": "Raku" }, { "code": "class Point { has Real ($.x, $.y) is rw; }\nmy Point $point .= new: x => 3, y => 8;\n", "language": "Raku" }, { "code": "my $s1 = set <a b c d>; # order is not preserved\nmy $s2 = set <c d e f>;\nsay $s1 (&) $s2; # OUTPUT«set(c, e)»\nsay $s1 ∩ $s2; # we also do Unicode\n", "language": "Raku" }, { "code": "x= -4.9\ny= 1.7\n\npoint=x y\n", "language": "REXX" }, { "code": "x= -4.1\ny= 1/4e21\n\npoint=x y\n\nbpoint=point\n\ngpoint=5.6 7.3e-12\n", "language": "REXX" }, { "code": "see new point {x=10 y=20} class point x y\n", "language": "Ring" }, { "code": "x: 10.000000\ny: 20.000000\n", "language": "Ring" }, { "code": "Point = Struct.new(:x,:y)\npt = Point.new(6,7)\nputs pt.x #=> 6\npt.y = 3\nputs pt #=> #<struct Point x=6, y=3>\n\n# The other way of accessing\npt = Point[2,3]\nputs pt[:x] #=> 2\npt['y'] = 5\nputs pt #=> #<struct Point x=2, y=5>\n\npt.each_pair{|member, value| puts \"#{member} : #{value}\"}\n #=> x : 2\n #=> y : 5\n", "language": "Ruby" }, { "code": " // Defines a generic struct where x and y can be of any type T\nstruct Point<T> {\n x: T,\n y: T,\n}\nfn main() {\n let p = Point { x: 1.0, y: 2.5 }; // p is of type Point<f64>\n println!(\"{}, {}\", p.x, p.y);\n}\n", "language": "Rust" }, { "code": "struct Point<T>(T, T);\nfn main() {\n let p = Point(1.0, 2.5);\n println!(\"{},{}\", p.0, p.1);\n}\n", "language": "Rust" }, { "code": " fn main() {\n let p = (0.0, 2.4);\n println!(\"{},{}\", p.0, p.1);\n}\n", "language": "Rust" }, { "code": "case class Point(x: Int = 0, y: Int = 0)\n\nval p = Point(1, 2)\nprintln(p.y) //=> 2\n", "language": "Scala" }, { "code": "(define-record-type point\n (make-point x y)\n point?\n (x point-x)\n (y point-y))\n", "language": "Scheme" }, { "code": "const type: Point is new struct\n var integer: x is 0;\n var integer: y is 0;\n end struct;\n", "language": "Seed7" }, { "code": "(datatype point\n X : number; Y : number;\n ====================\n [point X Y] : point;)\n", "language": "Shen" }, { "code": "(2+) (@p 1 2)\n(@p 1 2) : (number * number)\n", "language": "Shen" }, { "code": "struct Point {x, y};\nvar point = Point(1, 2);\nsay point.y; #=> 2\n", "language": "Sidef" }, { "code": "type mypoint\n embed\n integer x\n integer y\nend type\n", "language": "SIMPOL" }, { "code": "type mypoint\n embed\n integer x\n integer y\nend type\n\nfunction mypoint.new(mypoint me, integer x, integer y)\n me.x = x\n me.y = y\nend function me\n", "language": "SIMPOL" }, { "code": "\tdata('point(x,y)')\n\tp1 = point(10,20)\n\tp2 = point(10,40)\n\toutput = \"Point 1 (\" x(p1) \",\" y(p1) \")\"\n\toutput = \"Point 2 (\" x(p2) \",\" y(p2) \")\"\nend\n", "language": "SNOBOL4" }, { "code": "datatype tree = Empty\n | Leaf of int\n | Node of tree * tree\n\nval t1 = Node (Leaf 1, Node (Leaf 2, Leaf 3))\n", "language": "Standard-ML" }, { "code": "val p = (2,3)\n", "language": "Standard-ML" }, { "code": "val p = { x = 4, y = 5 }\n", "language": "Standard-ML" }, { "code": "mata\nstruct Point {\n\treal scalar x, y\n}\n\n// dumb example\nfunction test() {\n\tstruct Point scalar a\n\ta.x = 10\n\ta.y = 20\n\tprintf(\"%f\\n\",a.x+a.y)\n}\n\ntest()\n30\nend\n", "language": "Stata" }, { "code": "// Structure\nstruct Point {\n var x:Int\n var y:Int\n}\n\n// Tuple\ntypealias PointTuple = (Int, Int)\n\n// Class\nclass PointClass {\n var x:Int!\n var y:Int!\n\n init(x:Int, y:Int) {\n self.x = x\n self.y = y\n }\n}\n", "language": "Swift" }, { "code": "array set point {x 4 y 5}\nset point(y) 7\nputs \"Point is {$point(x),$point(y)}\"\n# => Point is {4,7}\n", "language": "Tcl" }, { "code": "set point [dict create x 4 y 5]\ndict set point y 7\nputs \"Point is {[dict get $point x],[dict get $point y]}\"\n", "language": "Tcl" }, { "code": "oo::class create Point {\n variable x y\n constructor {X Y} {set x $X;set y $Y}\n method x {args} {set x {*}$args}\n method y {args} {set y {*}$args}\n method show {} {return \"{$x,$y}\"}\n}\nPoint create point 4 5\npoint y 7\nputs \"Point is [point show]\"\n", "language": "Tcl" }, { "code": "#lang transd\n\n// If the Point type needs encapsulation and/or methods, it should be\n// implemented as class. Otherwise, the named tuple will do.\n\nclass Point: {\n x: Double(), y: Double(),\n @init: (λ _x Double() _y Double() (= x _x) (= y _y)),\n @to-String: (λ ss StringStream() (textout to: ss\n \"Point( x: \" x \"; y: \" y \" )\"))\n // ... other methods can be defined here ...\n}\n\nMainModule: {\n Point2: typealias(Tuple<Double Double>()),\n _start: (λ\n (with pt Point(2.5 3.7)\n (lout \"Class: \" pt)\n )\n (with pt Point2(2.5 3.7)\n (lout \"\\nNamed tuple: \" pt)\n )\n )\n}\n", "language": "Transd" }, { "code": "(defstruct point nil (x 0) (y 0))\n", "language": "TXR" }, { "code": "(defstruct point nil x y)\n", "language": "TXR" }, { "code": "(new point) ;; -> #S(point x 0 y 0)\n(new point x 1) ;; -> #S(point x 1 y 0)\n(new point x 1 y 1) ;; -> #S(point x 1 y 1)\n", "language": "TXR" }, { "code": "(defstruct (point x y) nil (x 0) (y 0))\n", "language": "TXR" }, { "code": "(new (point 3 4)) -> #S(point x 3 y 4)\n", "language": "TXR" }, { "code": "(defun displace-point-destructively (p delta)\n (inc p.x delta.x)\n (inc p.y delta.y))\n", "language": "TXR" }, { "code": "typeset -T Point=(\n typeset x\n typeset y\n)\nPoint p\np.x=1\np.y=2\necho $p\necho ${p.x} ${p.y}\nPoint q=(x=3 y=4)\necho ${q.x} ${q.y}\n", "language": "UNIX-Shell" }, { "code": "point=()\npoint.x=5\npoint.y=6\necho $point\necho ${point.x} ${point.y}\n", "language": "UNIX-Shell" }, { "code": "point :: x y\n", "language": "Ursala" }, { "code": "p = point[x: 'foo',y: 'bar']\n", "language": "Ursala" }, { "code": "f = point$[x: g,y: h]\n", "language": "Ursala" }, { "code": "t = ~x p\nu = ~y p\n", "language": "Ursala" }, { "code": "struct Point {\n x int\n y int\n}\n\n// main() declaration can be skipped in one file programs\n// we can define whether immutable or mutable by using the \"mut\" keyword\n\nmut p := Point{\n x: 10\n y: 20\n}\n\n// struct fields are accessed using a dot\n\nprintln(\"Value of p.x is: $p.x\")\nprintln(\"Show the struct:\\n $p\")\n\n// alternative literal syntax can be used for structs with 3 fields or fewer\n\np = Point{30, 40}\nassert p.x == 30\nprintln(\"Show the struct again after change:\\n $p\")\n", "language": "V-(Vlang)" }, { "code": "struct Point {\n int x;\n int y;\n}\n", "language": "Vala" }, { "code": "Type point\n x As Integer\n y As Integer\nEnd Type\n", "language": "VBA" }, { "code": "function MakePoint(x, y) \" 'Constructor'\n return {\"x\": a:x, \"y\": a:y}\nendfunction\n\nlet p1 = MakePoint(3, 2)\nlet p2 = MakePoint(-1, -4)\n\nechon \"Point 1: x = \" p1.x \", y = \" p1.y \"\\n\"\nechon \"Point 2: x = \" p2.x \", y = \" p2.y \"\\n\"\n", "language": "Vim-Script" }, { "code": "Structure Point\n Public X, Y As Integer\nEnd Structure\n", "language": "Visual-Basic-.NET" }, { "code": "Structure ImmutablePoint\n ReadOnly Property X As Integer\n ReadOnly Property Y As Integer\n\n Public Sub New(x As Integer, y As Integer)\n Me.X = x\n Me.Y = y\n End Sub\nEnd Structure\n", "language": "Visual-Basic-.NET" }, { "code": "class Point {\n construct new(x, y) {\n _x = x\n _y = y\n }\n x { _x }\n y { _y }\n\n // for illustration allow Points to be mutated\n x=(value) { _x = value }\n y=(value) { _y = value }\n\n toString { \"(%(_x), %(_y))\" }\n}\n\nvar p = Point.new(1, 2)\nSystem.print(p.toString)\n\n// mutate Point object\np.x = 2\np.y = 3\n// print without using the toString method\nSystem.printAll([\"(\", p.x, \", \", p.y, \")\"])\n", "language": "Wren" }, { "code": "<point x=\"20\" y=\"30\"/>\n\n<!-- context is a point node. The '@' prefix selects named attributes of the current node. -->\n<fo:block>Point = <xsl:value-of select=\"@x\"/>, <xsl:value-of select=\"@y\"/></fo:block>\n", "language": "XSLT" }, { "code": "<circle>\n <point>\n <x>20</x>\n <y>30</y>\n </point>\n <radius>10</radius>\n</circle>\n\n<!-- context is a circle node. Children are accessed using a path-like notation (hence the name \"XPath\"). -->\n", "language": "XSLT" }, { "code": "struct Point{\nchar x;\nchar y;\n}\n", "language": "Z80-Assembly" }, { "code": "struct Point myPoint;\nmyPoint.x = 3;\nmyPoint.y = 5;\n", "language": "Z80-Assembly" }, { "code": ";I'm arbitrarily choosing &1100 as the memory location of our Point variable.\nld hl,&1100\nld (hl),3\ninc hl\nld (hl),5\nret\n", "language": "Z80-Assembly" }, { "code": "class Point{ var x,y;\n fcn init(x,y){self.x=x.toFloat(); self.y=y.toFloat(); }\n fcn toString{ \"P(%f,%f)\".fmt(x,y) }\n fcn __opADD(P){} //+: add Point, constant or whatever\n //... __opEQ == etc\n}\nPoint(1,2).println() //-->P(1.000000,2.000000)\n", "language": "Zkl" }, { "code": "point:=T(1,2); points:=T( T(1,2), L(3,4) )\n", "language": "Zkl" }, { "code": "{ref,public} (* class *)\n\tPoint = object(ord,abs: integer)\n\tvar\n\t\t(* instance variables *)\n\t\t{public,immutable} x,y: integer;\n\n\t(* method *)\n\tprocedure {public} Ord():integer;\n\tbegin\n\t\treturn y\n\tend Ord;\n\n\t(* method *)\n\tprocedure {public} Abs():integer;\n\tbegin\n\t\treturn x\n\tend Abs;\n\n\t(* constructor *)\n\tbegin\n\t\tself.x := ord;\n\t\tself.y := abs;\n\tend Point;\n", "language": "Zonnon" } ]
Compound-data-type
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Conditional_structures\nnote: Control Structures\n", "language": "00-META" }, { "code": "{{Control Structures}} \n[[Category:Simple]]\n[[Category:Flow control]]\n\n;Task:\nList the ''conditional structures'' offered by a programming language. See [[wp:Conditional_(computer_programming)|Wikipedia: conditionals]] for descriptions.\n\nCommon conditional structures include '''if-then-else''' and '''switch'''.\n\nLess common are '''arithmetic if''', '''ternary operator''' and '''Hash-based conditionals'''.\n\n'''''Arithmetic if''' allows tight control over computed gotos, which optimizers have a hard time to figure out.''\n\n<br>\n\n", "language": "00-TASK" }, { "code": "I x == 0\n foo()\nE I x == 1\n bar()\nE\n baz()\n", "language": "11l" }, { "code": "S x\n 0\n foo()\n 1\n bar()\n E\n baz()\n", "language": "11l" }, { "code": "* Unconditional Branch or No Branch:\n B label Unconditional\n BR Rx \"\n NOP label No Operation\n NOPR Rx \"\n* After Compare Instructions\n BH label Branch on High\n BHR Rx \"\n BL label Branch on Low\n BLR Rx \"\n BE label Branch on Equal\n BER Rx \"\n BNH label Branch on Not High\n BNHR Rx \"\n BNL label Branch on Not Low\n BNLR Rx \"\n BNE label Branch on Not Equal\n BNER Rx \"\n* After Arithmetic Instructions:\n BP label Branch on Plus\n BPR Rx \"\n BM label Branch on Minus\n BMR Rx \"\n BZ label Branch on Zero\n BZR Rx \"\n BO label Branch on Overflow\n BOR Rx \"\n BNP label Branch on Not Plus\n BNPR Rx \"\n BNM label Branch on Not Minus\n BNMR Rx \"\n BNZ label Branch on Not Zero\n BNZR Rx \"\n BNO label Branch on No Overflow\n BNOR Rx \"\n* After Test Under Mask Instructions:\n BO label Branch if Ones\n BOR Rx \"\n BM label Branch if Mixed\n BMR Rx \"\n BZ label Branch if Zero\n BZR Rx \"\n BNO label Branch if Not Ones\n BNOR Rx \"\n BNM label Branch if Not Mixed\n BNMR Rx \"\n BNZ label Branch if Not Zero\n BNZR Rx \"\n", "language": "360-Assembly" }, { "code": " expression:\n opcode,op1,rel,op2\n opcode,op1,rel,op2,OR,opcode,op1,rel,op2\n opcode,op1,rel,op2,AND,opcode,op1,rel,op2\n opcode::=C,CH,CR,CLC,CLI,CLCL, LTR, CP,CE,CD,...\n rel::=EQ,NE,LT,LE,GT,GE, (fortran style)\n E,L,H,NE,NL,NH (assembler style)\n P (plus), M (minus) ,Z (zero) ,O (overflow)\n opcode::=CLM,TM\n rel::=O (ones),M (mixed) ,Z (zeros)\n\n* IF\n IF expression [THEN]\n ...\n ELSEIF expression [THEN]\n ...\n ELSE\n ...\n ENDIF\n\n IF C,R4,EQ,=F'10' THEN if r4=10 then\n MVI PG,C'A' pg='A'\n ELSEIF C,R4,EQ,=F'11' THEN elseif r4=11 then\n MVI PG,C'B' pg='B'\n ELSEIF C,R4,EQ,=F'12' THEN elseif r4=12 then\n MVI PG,C'C' pg='C'\n ELSE else\n MV PG,C'?' pg='?'\n ENDIF end if\n\n* SELECT\n SELECT expressionpart1\n WHEN expressionpart2a\n ...\n WHEN expressionpart2b\n ...\n OTHRWISE\n ...\n ENDSEL\n\t\t\n* example SELECT type 1\n SELECT CLI,HEXAFLAG,EQ select hexaflag=\n WHEN X'20' when x'20'\n MVI PG,C'<' pg='<'\n WHEN X'21' when x'21'\n MVI PG,C'!' pg='!'\n WHEN X'22' when x'21'\n MVI PG,C'>' pg='>'\n OTHRWISE otherwise\n MVI PG,C'?' pg='?'\n ENDSEL end select\n\n* example SELECT type 2\n SELECT select\n WHEN C,DELTA,LT,0 when delta<0\n MVC PG,=C'0 SOL' pg='0 SOL'\n WHEN C,DELTA,EQ,0 when delta=0\n MVC PG,=C'1 SOL'' pg='0 SOL'\n WHEN C,DELTA,GT,0 when delta>0\n MVC PG,=C'2 SOL'' pg='0 SOL'\n ENDSEL end select\n\n* CASE\n CASENTRY R4 select case r4\n CASE 1 case 1\n LA R5,1 r5=1\n CASE 3 case 3\n LA R5,2 r5=2\n CASE 5 case 5\n LA R5,3 r5=1\n CASE 7 case 7\n LA R5,4 r5=4\n ENDCASE end select\n", "language": "360-Assembly" }, { "code": "\t\tLDA #10\n\t\tCMP #11\n", "language": "6502-Assembly" }, { "code": "\t\tBNE \t\t;Branch on Not Equal - branch when the zero flag is set\n\t\tBEQ \t\t;Branch on EQual - branch when the zero flag is set.\n\t\t\t\t;The zero flag is set when the result of an operation is zero\n\n\t\tBMI \t\t;Branch on MInus\n\t\tBPL \t\t;Branch on PLus - branch when the sign flag is cleared/set.\n\t\t\t\t;The sign flag is set when the result of an instruction is a negative number\n\t\t\t\t;and cleared when the result is a positive number\n\n\t\tBVS \t\t;Branch on oVerflow Set\n\t\tBVC \t\t;Branch on oVerflow Cleared - branch when the overflow flag is cleared/set.\n\t\t\t\t;The overflow flag is set when the result of an addition/subtraction would\n\t\t\t\t;result in a number larger than 127 or smaller than -128\n\n\t\tBCS\t\t;Branch on Carry Set\n\t\tBCC\t\t;Branch on Carry Clear - branch when the carry flag is cleared/set.\n\t\t\t\t;The carry flag is set when an addition produced a carry and when\n\t\t\t\t;a subtraction produced a borrow and cleared if an addition/subtraction\n\t\t\t\t;does not produce a carry/borrow. The carry flag also holds bits\n\t\t\t\t;after shifts and rotates.\n", "language": "6502-Assembly" }, { "code": "\t\tLDA #200\n\t\tCMP Variable\n\t\tBEQ #3\t\t\t;if equal, skip ahead 3 bytes...\n\t\tCLC\t\t\t;if unequal, continue executing instructions\n\t\tADC #1\n\t\tSTA OtherVariable\t;\t\t\t\t...to here.\n", "language": "6502-Assembly" }, { "code": "\t\tLDX #100\nLoop:\t\t...do something\n\t\tDEX\n\t\tBNE Loop\n", "language": "6502-Assembly" }, { "code": "ReturnTable:\ndw foo-1 ;each is a label to a section of code that ends in an RTS\ndw bar-1\ndw baz-1\n\nReturnSpoof: ;assume execution arrived here via a JSR command.\nlda indexVariable ;contains the desired index into ReturnTable. 0 = foo, 1 = bar, 2 = baz.\nasl ;the data is word length so the index must be multiplied by 2.\ntax\n\nlda ReturnTable+1,x ;get the high byte of the return address.\npha\nlda ReturnTable,x ;get the low byte\npha\n\n; Now, the desired subroutine's address minus 1 is on top of the stack.\n; The RTS command will take this address and jump there. That routine's RTS command will act as the RTS from \"ReturnSpoof\",\n; bringing execution to the point just after ReturnSpoof was called.\n; If done properly, return spoofing will not corrupt the stack.\n\nRTS ;this \"RTS\" acts as a JMP to the address we just put on the stack.\n", "language": "6502-Assembly" }, { "code": "MOVE.L #$FFFFFF00,D0\nCMP.B #0,D0 ;equals zero, so zero flag is set.\nCMP.W #0,D0 ;doesn't equals zero, so zero flag is clear.\n", "language": "68000-Assembly" }, { "code": "BTST #7,D0 ;test bit 7 of D0, i.e. the leftmost bit in the rightmost byte.\nBNE goHere ;if that bit is 1, branch to \"goHere\"\nBEQ goThere ;if that bit is 0, branch to \"goThere\"\n", "language": "68000-Assembly" }, { "code": "CMP.L #3,D0 ;this works with any size operands, not just L.\nBNE doNothing\nADD.L #7,D0\ndoNothing:\n;rest of program\n", "language": "68000-Assembly" }, { "code": "SwitchCase:\nDC.L foo,bar,baz,default ;case 0, case 1, case 2, case 3. (Case 0,1,2 are the \"valid\" cases.)\n; D0 is the case selector variable (byte-sized)\ndoSwitchCase: ;this is a subroutine that gets called elsewhere.\nLEA SwitchCase,A0\n\n;this is our bounds check\nCMP.B #3,D0 ;is D0 > 3?\nBLS InBounds ;if not, keep going\nMOVE.B #3,D0 ;if it is, set it to 3.\n\n\nInBounds:\nLSL.W #2,D0 ;multiply by 4 to index into a table of longs\nMOVE.L (A0,D0),A0 ;deref the pointer and store the desired routine in A0\nMOVE.L A0,-(SP) ;push it onto the stack\nRTS ;\"return\" to the selected routine. If it ends in an RTS,\n ; that RTS will return to just after \"JSR doSwitchCase\"\n\n\nfoo:\n ;your code for this case goes here.\n rts\n\nbar:\n ;your code for this case goes here.\n rts\n\nbaz:\n ;your code for this case goes here.\n rts\n\ndefault:\n rts\n", "language": "68000-Assembly" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program condstr64.s */\n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n/*******************************************/\n/* Initialized data */\n/*******************************************/\n.data\nszMessTest1: .asciz \"The test 1 is equal.\\n\"\nszMessTest1N: .asciz \"The test 1 is not equal.\\n\"\nszMessTest1A: .asciz \"The test 1A is equal.\\n\"\nszMessTest1AN: .asciz \"The test 1A is not equal.\\n\"\nszMessTest2: .asciz \"The test 2 is equal.\\n\"\nszMessTest2N: .asciz \"The test 2 is not equal.\\n\"\nszMessTest3: .asciz \"The test 3 is <.\\n\"\nszMessTest3N: .asciz \"The test 3 is >.\\n\"\nszMessTest4: .asciz \"The test 4 is <=.\\n\"\nszMessTest4N: .asciz \"The test 4 is >.\\n\"\nszMessTest5: .asciz \"The test 5 is negative.\\n\"\nszMessTest5N: .asciz \"The test 5 is positive ou equal 0.\\n\"\nszMessTest6: .asciz \"Test 6 : carry is off.\\n\"\nszMessTest6N: .asciz \"Test 6 : carry is set.\\n\"\nszMessTest7: .asciz \"Test 7 : no overflow.\\n\"\nszMessTest7N: .asciz \"Test 7 : overflow.\\n\"\nszMessTest8: .asciz \"Test 8 : then.\\n\"\nszMessTest8N: .asciz \"Test 8 : else.\\n\"\nszMessResult: .asciz \"Test result = @ \\n\"\n/*******************************************/\n/* UnInitialized data */\n/*******************************************/\n.bss\nsZoneConv: .skip 30\n/*******************************************/\n/* code section */\n/*******************************************/\n.text\n.global main\nmain: // entry of program\n\n // classic test equal zero, not equal zero\n //mov x1,0 // comments\n mov x1,1 // or uncomments\n cmp x1,0 // structure if else\n bne 1f\n ldr x0,qAdrszMessTest1 // if equal\n b 2f\n1:\n ldr x0,qAdrszMessTest1N // else\n2:\n bl affichageMess\n\n mov x1,0 // comments\n //mov x1,1 // or uncomments\n cbnz x1,3f // other test and branch if not zero\n ldr x0,qAdrszMessTest1A\n b 4f\n3:\n ldr x0,qAdrszMessTest1AN\n4:\n bl affichageMess\n // test equal 5, not equal 5\n //mov x1,#5\n mov x1,10\n cmp x1,5\n bne 5f\n ldr x0,qAdrszMessTest2\n b 6f\n5:\n ldr x0,qAdrszMessTest2N\n6:\n bl affichageMess\n\n // test < 5, > 5 SIGNED\n mov x1,#-10\n //mov x1,#10\n cmp x1,#5\n bgt 7f\n ldr x0,qAdrszMessTest3\n b 8f\n7:\n ldr x0,qAdrszMessTest3N\n8:\n bl affichageMess\n\n // test < 5, > 5 UNSIGNED\n //mov x1,#-10\n mov x1,#2\n cmp x1,#5\n bhi 9f\n ldr x0,qAdrszMessTest4\n b 10f\n9:\n ldr x0,qAdrszMessTest4N\n10:\n bl affichageMess\n\n // test < 0, > 0\n mov x1,2\n subs x1,x1,5 // s --> flags\n bpl 11f\n ldr x0,qAdrszMessTest5\n b 12f\n11:\n ldr x0,qAdrszMessTest5N\n12:\n bl affichageMess\n\n // carry off carry on\n //mov x1,#-10 // for carry set\n //mov x1,#10 // for carry off\n mov x1,(2<<62) - 1 // for carry off\n adds x1,x1,20 // s --> flags\n bcs 13f\n ldr x0,qAdrszMessTest6 // carry clear\n b 14f\n13:\n ldr x0,qAdrszMessTest6N // carry set\n14:\n bl affichageMess\n\n // overflow off overflow on\n //mov x1,#-10 // for not overflow\n //mov x1,#10 // for not overflow\n mov x1,(2<<62) - 1 // for overflow\n adds x1,x1,20 // s --> flags\n bvs 15f\n ldr x0,qAdrszMessTest7 // overflow off\n b 16f\n15:\n ldr x0,qAdrszMessTest7N // overflow on\n16:\n bl affichageMess\n\n // other conditionnel test csel\n mov x2,-20\n mov x3,25\n mov x1,10 // for equal\n //mov x1,#20 // for else\n cmp x1,10\n csel x0,x2,x3,eq // if x1=10 x0 = x2 else x0 = x3\n ldr x1,qAdrsZoneConv\n bl conversion10S\n ldr x0,qAdrszMessResult\n ldr x1,qAdrsZoneConv\n bl strInsertAtCharInc // insert result at @ character\n bl affichageMess\n\n // other conditionnel test cset\n //mov x1,10 // for equal\n mov x1,20 // for else\n cmp x1,10\n cset x0,eq // if x1=10 x0 = 1 else x0 = 0\n ldr x1,qAdrsZoneConv\n bl conversion10S\n ldr x0,qAdrszMessResult\n ldr x1,qAdrsZoneConv\n bl strInsertAtCharInc // insert result at @ character\n bl affichageMess\n\n // other conditionnel test cinc\n mov x0,3\n mov x1,10 // for equal\n //mov x1,20 // for else\n cmp x1,10\n cinc x0,x0,eq // if x1=10 x0 = x0+1 else x0 = x0\n ldr x1,qAdrsZoneConv\n bl conversion10S\n ldr x0,qAdrszMessResult\n ldr x1,qAdrsZoneConv\n bl strInsertAtCharInc // insert result at @ character\n bl affichageMess\n\n // other conditionnel test csinc\n mov x0,3\n mov x2,6\n mov x3,11\n mov x1,10 // for equal\n //mov x1,20 // for else\n cmp x1,10\n csinc x0,x2,x3,ne // if x1<>10 x0 = x2 else x0 = x3 + 1\n ldr x1,qAdrsZoneConv\n bl conversion10S\n ldr x0,qAdrszMessResult\n ldr x1,qAdrsZoneConv\n bl strInsertAtCharInc // insert result at @ character\n bl affichageMess\n100: // standard end of the program\n mov x0,0 // return code\n mov x8,EXIT // request to exit program\n svc 0 // perform the system call\nqAdrszMessTest1: .quad szMessTest1\nqAdrszMessTest1N: .quad szMessTest1N\nqAdrszMessTest1A: .quad szMessTest1A\nqAdrszMessTest1AN: .quad szMessTest1AN\nqAdrszMessTest2: .quad szMessTest2\nqAdrszMessTest2N: .quad szMessTest2N\nqAdrszMessTest3: .quad szMessTest3\nqAdrszMessTest3N: .quad szMessTest3N\nqAdrszMessTest4: .quad szMessTest4\nqAdrszMessTest4N: .quad szMessTest4N\nqAdrszMessTest5: .quad szMessTest5\nqAdrszMessTest5N: .quad szMessTest5N\nqAdrszMessTest6: .quad szMessTest6\nqAdrszMessTest6N: .quad szMessTest6N\nqAdrszMessTest7: .quad szMessTest7\nqAdrszMessTest7N: .quad szMessTest7N\nqAdrszMessTest8: .quad szMessTest8\nqAdrszMessTest8N: .quad szMessTest8N\nqAdrszMessResult: .quad szMessResult\nqAdrsZoneConv: .quad sZoneConv\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "PROC Main()\n INT i\n\n FOR i=-1 TO 1\n DO\n IF i<0 THEN\n PrintF(\"%I is less than zero%E\",i)\n ELSEIF i>0 THEN\n PrintF(\"%I is greater than zero%E\",i)\n ELSE\n PrintF(\"%I is zero%E\",i)\n FI\n OD\nRETURN\n", "language": "Action-" }, { "code": "type Restricted is range 1..10;\nMy_Var : Restricted;\n\nif My_Var = 5 then\n -- do something\nelsif My_Var > 5 then\n -- do something\nelse\n -- do something\nend if;\n", "language": "Ada" }, { "code": "type Operation is (Add, Subtract, Multiply, Divide);\nOp : Operation;\nResult : Integer;\n-- we assume that A and B are inputs.\nResult := (if Op = Add then\n A + B\nelsif Op = Subtract then\n A - B\nelsif Op = Multiply then\n A * B\nelsif Op = Divide then\n A / B\n);\n", "language": "Ada" }, { "code": "Result := (case Op is\n Add => A + B,\n Subtract => A - B,\n Multiply => A * B,\n Divide => A / B\n);\n", "language": "Ada" }, { "code": "case Op of...\n", "language": "Ada" }, { "code": "type Days is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);\nToday : Days;\n\ncase Today is\n when Saturday | Sunday =>\n null;\n when Monday =>\n Compute_Starting_Balance;\n when Friday =>\n Compute_Ending_Balance;\n when others =>\n Accumulate_Sales;\nend case;\n", "language": "Ada" }, { "code": "case Today is\n when Monday =>\n Compute_Starting_Balance;\n when Friday =>\n Compute_Ending_Balance;\n when Tuesday .. Thursday =>\n Accumulate_Sales;\n -- ignore Saturday and Sunday\nend case;\n", "language": "Ada" }, { "code": "case Today is\n when Saturday | Sunday =>\n null; -- don't do anything, if Today is Saturday or Sunday\n when Monday =>\n Compute_Starting_Balance;\n when Friday =>\n Compute_Ending_Balance;\n when Tuesday .. Thursday =>\n Accumulate_Sales;\nend case;\n", "language": "Ada" }, { "code": "select\n accept first_entry;\n -- do something\n or accept second_entry;\n -- do something\n or terminate;\nend select;\n", "language": "Ada" }, { "code": "select\n My_Task.Start;\nor\n delay Timeout_Period;\nend select;\n", "language": "Ada" }, { "code": "var x = loggedin ? sessionid : -1\n", "language": "Aikido" }, { "code": "if (value > 40) {\n println (\"OK\")\n} elif (value < 20) {\n println (\"FAILED\")\n} else {\n println (\"RETRY\")\n}\n", "language": "Aikido" }, { "code": "switch (arg) {\ncase \"-d\":\ncase \"--debug\":\n debug = true\n break\ncase \"-f\":\n force = true\n break\ndefault:\n throw \"Unknown option \" + arg\n}\n\nswitch (value) {\ncase > 40:\n println (\"OK\")\n break\ncase < 20:\n println (\"FAILED\")\n break\ncase in 50..59:\n println (\"WIERD\")\n // fall through\ndefault:\n println (\"RETRY\")\n}\n", "language": "Aikido" }, { "code": "if (c1) {\n // first condition is true...\n} elif (c2) {\n // second condition is true...\n} elif (c3) {\n // third condition is true...\n} else {\n // none was true...\n}\n", "language": "Aime" }, { "code": " 'IF' I=1 'THEN' OUTINTEGER(1,I);\n\n 'IF' I<J 'THEN' OUTSTRING(1,'(' : I<J')')\n 'ELSE' OUTSTRING(1,'(' : I>=J')');\n\n 'IF' I>=J 'THEN' 'BEGIN'\n OUTSTRING(1,'(' I=')');\n OUTINTEGER(1,I)\n 'END'\n 'ELSE' 'BEGIN'\n OUTSTRING(1,'(' J=')');\n OUTINTEGER(1,J)\n 'END'\n", "language": "ALGOL-60" }, { "code": " 'SWITCH' TARGET:=L1,L2,L3;\n ...\n 'GOTO' TARGET(/J/);\n L1: OUTSTRING(1,'('AA')');\n L2: OUTSTRING(1,'('BB')');\n L3: OUTSTRING(1,'('CC')');\n", "language": "ALGOL-60" }, { "code": "begin\n integer a, b, c;\n\n a := 1; b := 2; c := 3;\n\n % algol W has the traditional Algol if-the-else statement %\n % there is no \"elseif\" contraction %\n if a = b\n then write( \"a = b\" )\n else if a = c\n then write( \"a = c\" )\n else write( \"a is \", a );\n\n % if-then-else can also be used in an expression %\n write( if a < 4 then \"lt 4\" else \"ge 4\" );\n\n % algol W also has a \"case\" statement, an integer expression is used to %\n % select the statement to execute. If the expression evaluates to 1, %\n % the first statement is executed, if 2, the second is executed etc. %\n % If the expression is less than 1 or greater than the number of %\n % statements, a run time error occurs %\n case a + b of\n begin write( \"a + b is one\" )\n ; write( \"a + b is two\" )\n ; write( \"a + b is three\" )\n ; write( \"a + b is four\" )\n end;\n\n % there is also an expression form of the case: %\n write( case c - a of ( \"one\", \"two\", \"three\", \"four\" ) )\n\nend.\n", "language": "ALGOL-W" }, { "code": "if: condition then: {\n // condition is true...\n} else: {\n // condition is false...\n}\n", "language": "AmbientTalk" }, { "code": "condition.ifTrue: { /* condition is true... */ } ifFalse: { /* condition is false... */ }\n", "language": "AmbientTalk" }, { "code": "IF condition\n -> if condition is true...\nELSEIF condition2\n -> else if condition2 is true...\nELSE\n -> if all other conditions are not true...\nENDIF\n", "language": "AmigaE" }, { "code": "IF condition THEN statement\n", "language": "AmigaE" }, { "code": "DEF c\nc := IF condition THEN 78 ELSE 19\n", "language": "AmigaE" }, { "code": "SELECT var\n CASE n1\n -> code\n CASE n2\n -> code\n DEFAULT\n -> no one of the previous case...\nENDSELECT\n", "language": "AmigaE" }, { "code": "SELECT max_possible_value OF var\n CASE n1\n -> code\n CASE n2 TO n3, n4\n -> more\n CASE n5 TO n6, n7 TO n8\n -> more...\n DEFAULT\n -> none of previous ones\nENDSELECT\n", "language": "AmigaE" }, { "code": "if (s == 'Hello World') {\n foo();\n} else if (s == 'Bye World') {\n bar();\n} else {\n deusEx();\n}\n", "language": "Apex" }, { "code": "if(obj != null && obj.foo()){\n aMethod();\n}\n", "language": "Apex" }, { "code": "if(obj != null & obj.foo()){\n aMethod();\n}\n", "language": "Apex" }, { "code": "s == 'Hello World' ? foo() : bar();\n", "language": "Apex" }, { "code": "if myVar is \"ok\" then return true\n\nset i to 0\nif i is 0 then\n return \"zero\"\nelse if i mod 2 is 0 then\n return \"even\"\nelse\n return \"odd\"\nend if\n", "language": "AppleScript" }, { "code": " 10 LET X = 1\n 20 IF X THEN PRINT \"X IS TRUE\"\n 30 IF NOT X THEN PRINT \"X IS FALSE\"\n 40 ON X GOSUB 100,200,300\n 50 ON X GOTO 300,200,100\n 100 PRINT \"APPLE\": RETURN\n 200 PRINT \"BANANA\": RETURN\n 300 PRINT \"CHERRY\"\n", "language": "Applesoft-BASIC" }, { "code": "/* ARM assembly Raspberry PI */\n/* program condstr.s */\n\n/* Constantes */\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n/* Initialized data */\n.data\nszMessTest1: .asciz \"The test 1 is equal.\\n\"\nszMessTest1N: .asciz \"The test 1 is not equal.\\n\"\nszMessTest2: .asciz \"The test 2 is equal.\\n\"\nszMessTest2N: .asciz \"The test 2 is not equal.\\n\"\nszMessTest3: .asciz \"The test 3 is <.\\n\"\nszMessTest3N: .asciz \"The test 3 is >.\\n\"\nszMessTest4: .asciz \"The test 4 is <=.\\n\"\nszMessTest4N: .asciz \"The test 4 is >.\\n\"\nszMessTest5: .asciz \"The test 5 is negative.\\n\"\nszMessTest5N: .asciz \"The test 5 is positive ou equal 0.\\n\"\nszMessTest6: .asciz \"Test 6 : carry is off.\\n\"\nszMessTest6N: .asciz \"Test 6 : carry is set.\\n\"\nszMessTest7: .asciz \"Test 7 : no overflow.\\n\"\nszMessTest7N: .asciz \"Test 7 : overflow.\\n\"\nszMessTest8: .asciz \"Test 8 : then.\\n\"\nszMessTest8N: .asciz \"Test 8 : else.\\n\"\n\n/* UnInitialized data */\n.bss\n\n/* code section */\n.text\n.global main\nmain: /* entry of program */\n push {fp,lr} /* saves 2 registers */\n\n @ test equal zero, not equal zero\n @movs r1,#0 @ comments\n movs r1,#1 @ @ s --> flags and uncomments\n ldreq r0,iAdrszMessTest1\n ldrne r0,iAdrszMessTest1N\n bl affichageMess\n\t\n @ test equal 5, not equal 5\n @mov r1,#5\n mov r1,#10\n cmp r1,#5\n ldreq r0,iAdrszMessTest2\n ldrne r0,iAdrszMessTest2N\n bl affichageMess\n\t\n @ test < 5, > 5 SIGNED\n mov r1,#-10\n @mov r1,#10\n cmp r1,#5\n ldrlt r0,iAdrszMessTest3\n ldrgt r0,iAdrszMessTest3N\n bl affichageMess\n\t\n @ test < 5, > 5 UNSIGNED\n @mov r1,#-10\n mov r1,#2\n cmp r1,#5\n ldrls r0,iAdrszMessTest4\n ldrhi r0,iAdrszMessTest4N\n bl affichageMess\n\t\n @ test < 0, > 0\n @movs r1,#-10\n movs r1,#2 @ s --> flags\n ldrmi r0,iAdrszMessTest5\n ldrpl r0,iAdrszMessTest5N\n bl affichageMess\n\t\n @ carry off carry on\n @mov r1,#-10 @ for carry set\n @mov r1,#10 @ for carry off\n mov r1,#(2<<30) - 1 @ for carry off\n adds r1,#20 @ s --> flags\n ldrcc r0,iAdrszMessTest6 @ carry clear\n ldrcs r0,iAdrszMessTest6N @ carry set\n bl affichageMess\n\n @ overflow off overflow on\n @mov r1,#-10 @ for not overflow\n @mov r1,#10 @ for not overflow\n mov r1,#(2<<30) - 1 @ for overflow\n adds r1,#20 @ s --> flags\n ldrvc r0,iAdrszMessTest7 @ overflow off\n ldrvs r0,iAdrszMessTest7N @ overflow on\n bl affichageMess\n\n @ other if then else\n mov r1,#5 @ for then\n @mov r1,#20 @ for else\n cmp r1,#10\n ble 1f @ less or equal\n @bge 1f @ greather or equal\n @else\n ldr r0,iAdrszMessTest8N @ overflow off\n bl affichageMess\n b 2f\n1: @ then\n ldr r0,iAdrszMessTest8 @ overflow off\n bl affichageMess\n2:\n\n100: /* standard end of the program */\n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\niAdrszMessTest1:\t\t.int szMessTest1\niAdrszMessTest1N:\t\t.int szMessTest1N\niAdrszMessTest2:\t\t.int szMessTest2\niAdrszMessTest2N:\t\t.int szMessTest2N\niAdrszMessTest3:\t\t.int szMessTest3\niAdrszMessTest3N:\t\t.int szMessTest3N\niAdrszMessTest4:\t\t.int szMessTest4\niAdrszMessTest4N:\t\t.int szMessTest4N\niAdrszMessTest5:\t\t.int szMessTest5\niAdrszMessTest5N:\t\t.int szMessTest5N\niAdrszMessTest6:\t\t.int szMessTest6\niAdrszMessTest6N:\t\t.int szMessTest6N\niAdrszMessTest7:\t\t.int szMessTest7\niAdrszMessTest7N:\t\t.int szMessTest7N\niAdrszMessTest8:\t\t.int szMessTest8\niAdrszMessTest8N:\t\t.int szMessTest8N\n/******************************************************************/\n/* display text with size calculation */\n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {fp,lr} \t\t\t/* save registres */\n push {r0,r1,r2,r7} \t\t/* save others registers */\n mov r2,#0 \t\t\t\t/* counter length */\n1: \t/* loop length calculation */\n ldrb r1,[r0,r2] \t\t\t/* read octet start position + index */\n cmp r1,#0 \t\t\t/* if 0 its over */\n addne r2,r2,#1 \t\t\t/* else add 1 in the length */\n bne 1b \t\t\t/* and loop */\n /* so here r2 contains the length of the message */\n mov r1,r0 \t\t\t/* address message in r1 */\n mov r0,#STDOUT \t\t/* code to write to the standard output Linux */\n mov r7, #WRITE /* code call system \"write\" */\n swi #0 /* call systeme */\n pop {r0,r1,r2,r7} \t\t/* restaur others registers */\n pop {fp,lr} \t\t\t\t/* restaur des 2 registres */\n bx lr\t \t\t\t/* return */\n", "language": "ARM-Assembly" }, { "code": "num: 2\n\nif? num=2 [\n\tprint \"yep, num is 2\"\n]\nelse [\n\tprint \"something went wrong...\"\n]\n", "language": "Arturo" }, { "code": "loop 1..5 'num [\n case [num]\n when? [<2] -> print [num \": it's less than 2\"]\n when? [=2] -> print [num \": it's 2!\"]\n when? [=3] -> print [num \": it's 3!\"]\n else -> print [num \": the number is too big\"]\n]\n", "language": "Arturo" }, { "code": "if x == 0:\n foo()\nelif x == 1:\n bar()\nelif x == 2:\n baz()\nelse:\n qux()\n\nmatch x:\n 0 => foo()\n 1 => bar()\n 2 => baz()\n _ => qux()\n\n(a) ? b : c\n", "language": "Astro" }, { "code": "x = 1\nIf x\n MsgBox, x is %x%\nElse If x > 1\n MsgBox, x is %x%\nElse\n MsgBox, x is %x%\n", "language": "AutoHotkey" }, { "code": "x = 2\ny = 1\nvar := x > y ? 2 : 3\nMsgBox, % var\n", "language": "AutoHotkey" }, { "code": "While (A_Index < 3) {\n MsgBox, %A_Index% is less than 3\n}\n", "language": "AutoHotkey" }, { "code": "If <expression> Then\n statements\n ...\n[ElseIf expression-n Then\n [elseif statements ... ]]\n ...\n[Else\n [else statements]\n ...\nEndIf\n", "language": "AutoIt" }, { "code": "Select\n Case <expression>\n statement1\n ...\n [Case\n statement2\n ...]\n [Case Else\n statementN\n ...]\nEndSelect\n", "language": "AutoIt" }, { "code": "Switch <expression>\n Case <value> [To <value>] [,<value> [To <value>] ...]\n statement1\n ...\n [Case <value> [To <value>] [,<value> [To <value>] ...]\n statement2\n ...]\n [Case Else\n statementN\n ...]\nEndSwitch\n", "language": "AutoIt" }, { "code": "If year = 1999 then [Print: \"Party!\";];\n\nIf someNumber > 5 then [Print: \"Too high!\";] else [Print: \"Adequate amount.\";];\n\nIf breed = \"Abyssinian\" then [score := 150;]\nelse if breed = \"Birman\" then [score := 70;]\nelse [score := 45;];\n\nUnless char = ¢X then [Print: \"character was not an x\";];\n", "language": "Avail" }, { "code": "Print: if result = 13 then [\"unlucky\"] else [\"safe\"];\n", "language": "Avail" }, { "code": "if(i<0) i=0; else i=42\n", "language": "AWK" }, { "code": "if(i<0) {\n i=0; j=1\n } else {\n i=42; j=2\n }\n", "language": "AWK" }, { "code": "i=(i<0? 0: 42)\n", "language": "AWK" }, { "code": "If 1\n YEP()\nEnd\n", "language": "Axe" }, { "code": "!If 1\n NOPE()\nEnd\n", "language": "Axe" }, { "code": "If 1\n YEP()\nElse\n NOPE()\nEnd\n", "language": "Axe" }, { "code": "If 1=0\n NOPE()\nElseIf 1=1\n YEP()\nElse\n NOPE()\nEnd\n", "language": "Axe" }, { "code": "If 1=0\n NOPE()\nElse!If 1=2\n YEP()\nElse\n NOPE()\nEnd\n", "language": "Axe" }, { "code": "\"foo\" \"bar\" 3 4 > sel <<\n", "language": "Babel" }, { "code": " {3 4 >}\n {\"foo\"}\n {\"bar\"}\n ifte\n <<\n", "language": "Babel" }, { "code": " ({3 4 >} {\"Three is greater than four\" }\n {3 3 >} {\"Three is greater than three\"}\n {3 2 >} {\"Three is greater than two\" }\n {3 1 >} {\"Three is greater than one\" })\n cond\n <<\n", "language": "Babel" }, { "code": "10 LET A%=1: REM A HAS A VALUE OF TRUE\n20 IF A% THEN PRINT \"A IS TRUE\"\n30 WE CAN OF COURSE USE EXPRESSIONS\n40 IF A%<>0 THEN PRINT \"A IS TRUE\"\n50 IF NOT(A%) THEN PRINT \"A IS FALSE\"\n60 REM SOME VERSIONS OF BASIC PROVIDE AN ELSE KEYWORD\n70 IF A% THEN PRINT \"A IS TRUE\" ELSE PRINT \"A IS FALSE\"\n", "language": "BASIC" }, { "code": "IF x = 0 THEN doSomething\nIF x < 0 THEN doSomething ELSE doOtherThing\n", "language": "BASIC" }, { "code": "IF x > 0 AND x < 10 THEN\n 'do stuff\nELSE IF x = 0 THEN\n 'do other stuff\nELSE\n 'do more stuff\nEND IF\n", "language": "BASIC" }, { "code": "IF aNumber THEN\n 'the number is not 0\nELSE\n 'the number is 0\nEND IF\n", "language": "BASIC" }, { "code": "SELECT CASE expression\nCASE 1\n 'do stuff\nCASE 2, 3\n 'do other stuff\nCASE 3.1 TO 9.9\n 'do this\nCASE IS >= 10\n 'do that\nCASE ELSE\n 'default case\nEND SELECT\n", "language": "BASIC" }, { "code": "10 INPUT \"Enter 1,2 or 3: \";v\n20 GOTO v * 100\n99 STOP\n100 PRINT \"Apple\"\n110 STOP\n200 PRINT \"Banana\"\n210 STOP\n300 PRINT \"Cherry\"\n310 STOP\n", "language": "BASIC" }, { "code": "10 REM while loop\n20 L=0\n30 WHILE L<5\n40 PRINT L\n50 L=L+1\n60 WEND\n70 REM repeat loop\n80 L=1\n90 REPEAT\n100 PRINT L\n110 L=L+1\n120 UNTIL L>5\n", "language": "BASIC" }, { "code": "for i = 0 to 1\n for j = 0 to 1\n print i\n print j\n if (i) then\n if (j) then\n print \"i is true j is true\"\n else\n print \"i is true j is false\"\n end if\n else\n if (j) then\n print \"i is false j is true\"\n else\n print \"i is false j is false\"\n end if\n end if\n next j\nnext i\n", "language": "BASIC256" }, { "code": "IF [NOT] ERRORLEVEL number command\nIF [NOT] string1==string2 command\nIF [NOT] EXIST filename command\nIF CMDEXTVERSION number command\nIF DEFINED variable command\nIF [/I] string1 compare-op string2 command\n where compare-op is:\n EQU - equal\n NEQ - not equal\n LSS - less than\n LEQ - less than or equal\n GTR - greater than\n GEQ - greater than or equal\n /I case insensitive string compares\n", "language": "Batch-File" }, { "code": "IF EXIST %filename% (\n del %filename%\n) ELSE (\n echo %filename% not found\n)\n", "language": "Batch-File" }, { "code": " REM Single-line IF ... THEN ... ELSE (ELSE clause is optional):\n IF condition% THEN statements ELSE statements\n\n REM Multi-line IF ... ENDIF (ELSE clause is optional):\n IF condition% THEN\n statements\n ELSE\n statements\n ENDIF\n\n REM CASE ... ENDCASE (OTHERWISE clause is optional):\n CASE expression OF\n WHEN value1: statements\n WHEN value2: statements\n ...\n OTHERWISE: statements\n ENDCASE\n\n REM ON ... GOTO (ELSE clause is optional):\n ON expression% GOTO dest1, dest2 ... ELSE statements\n\n REM ON ...GOSUB (ELSE clause is optional):\n ON expression% GOSUB dest1, dest2 ... ELSE statements\n\n REM ON ... PROC (ELSE clause is optional):\n ON expression% PROCone, PROCtwo ... ELSE statements\n", "language": "BBC-BASIC" }, { "code": "' lstack top value == 0 ? skip next instruction : don’t skip next instruction.\n\" lstack top value > 0 ? skip next instruction : don’t skip next instruction.\nK lstack top value == 2nd value ? skip next instruction : don’t skip next instruction.\nL lstack top value > 2nd value ? skip next instruction : don’t skip next instruction.\n", "language": "Beeswax" }, { "code": "_`Enter integer n:`T'p`n = 0`>N`Enter integer m:`T'p`m = 0`>` and `Kp`m = n`;\n >`n > 0`d >`m > 0`d >Lp`m > n`;\n >`m < n`;\n", "language": "Beeswax" }, { "code": "Enter integer n:\ni3\nn > 0\nEnter integer m:\ni0\nm = 0 and m < n\n", "language": "Beeswax" }, { "code": "v > \"X\",@ non-zero\n> & |\n > \"0\",@ zero\n", "language": "Befunge" }, { "code": "& #v_ \"0\",@ zero\n > \"X\",@ non-zero\n", "language": "Befunge" }, { "code": "if i % 2 == 0\n print(\"even\")\nelse\n print(\"odd\")\nend\n", "language": "Blz" }, { "code": "if (i == 0)\n return \"zero\";\nelif (i % 2)\n return \"odd\";\nelse\n return \"even\";\n", "language": "Bori" }, { "code": "If ← {𝕏⍟𝕎@}´ # Also Repeat\nIfElse ← {c‿T‿F: c◶F‿T@}\nWhile ← {𝕩{𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}𝕨@}´ # While 1‿{... to run forever\nDoWhile ← {𝕏@ ⋄ While 𝕨‿𝕩}´\nFor ← {I‿C‿P‿A: I@ ⋄ While⟨C,P∘A⟩}\n\n# Switch/case statements have many variations; these are a few\nMatch ← {𝕏𝕨}´\nSelect ← {(⊑𝕩)◶(1↓𝕩)@}\nSwitch ← {c←⊑𝕩 ⋄ m‿a←<˘⍉∘‿2⥊1↓𝕩 ⋄ (⊑a⊐C)◶m@}\nTest ← {fn←{C‿A𝕊e:C◶A‿E}´𝕩⋄Fn@}\n", "language": "BQN" }, { "code": "{\n a<b ? a+↩1 ; # If\n a<c ? c-↩1 ; # Else If\n a-↩2 # Else\n}\n", "language": "BQN" }, { "code": " 2+2:5\n & put$\"Strange, must check that Bracmat interpreter.\"\n & 0\n| put$\"That's what I thought.\"\n & Right\n", "language": "Bracmat" }, { "code": " 2+2\n: ( (<3|>5)\n & put$\"Not quite, must check that Bracmat interpreter.\"\n | (3|5)\n & put$\"Not far off, but must check that Bracmat interpreter some day.\"\n | ?\n & put$\"That's what I thought.\"\n )\n", "language": "Bracmat" }, { "code": "[.]\n", "language": "Brainf---" }, { "code": "+[.]\n", "language": "Brainf---" }, { "code": "+[.-]\n", "language": "Brainf---" }, { "code": "blsq ) 9 2.%{\"Odd\"\"Even\"}ch\n\"Odd\"\n", "language": "Burlesque" }, { "code": "blsq ) 9^^2.%{+.}if\n10\nblsq ) 10^^2.%{+.}if\n10\n", "language": "Burlesque" }, { "code": "blsq ) 10^^2.%{-.}\\/{+.}\\/ie\n11\nblsq ) 9^^2.%{-.}\\/{+.}\\/ie\n8\n", "language": "Burlesque" }, { "code": "blsq ) {\"Hate tomatos\" \"Like Bananas\" \"Hate Apples\"}{\"Tomato\" \"Banana\" \"Apple\"}\"Banana\"Fi!!\n\"Like Bananas\"\nblsq ) {\"Hate tomatos\" \"Like Bananas\" \"Hate Apples\"}{\"Tomato\" \"Banana\" \"Apple\"}\"Apple\"Fi!!\n\"Hate Apples\"\n", "language": "Burlesque" }, { "code": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n typedef ElseType type;\n};\n\n// example usage: select type based on size\nifthenelse<INT_MAX == 32767, // 16 bit int?\n long int, // in that case, we'll need a long int\n int> // otherwise an int will do\n ::type myvar; // define variable myvar with that type\n", "language": "C++" }, { "code": "if (condition)\n{\n // Some Task\n}\n\nif (condition)\n{\n // Some Task\n}\nelse if (condition2)\n{\n // Some Task\n}\nelse\n{\n // Some Task\n}\n", "language": "C-sharp" }, { "code": "// if condition is true var will be set to 1, else 2.\nint var = condition ? 1 : 2;\n", "language": "C-sharp" }, { "code": "switch (value)\n{\n case 1:\n // Some task\n break; // Breaks are required in C#.\n case 2:\n case 3:\n // Some task\n break;\n default: // If no other case is matched.\n // Some task\n break;\n}\n", "language": "C-sharp" }, { "code": "switch (value)\n{\n case 1:\n // Some task\n goto case 2; // will cause the code indicated in case 2 to be executed.\n case 2:\n // Some task\n break;\n case 3:\n // Some task\n break;\n default: // If no other case is matched.\n // Some task\n break;\n}\n", "language": "C-sharp" }, { "code": "if (3 < 5) echo '3 is less than 5'\nif ({ grep -q ^root: /etc/passwd }) echo 'passwd has root'\n", "language": "C-Shell" }, { "code": "if (4 >= 6) then\n\techo '4 is greater than or equal to 6'\nelse if (4 < 6) then\n\techo '4 is less than 6'\nelse\n\techo '4 compares not to 6'\nendif\n", "language": "C-Shell" }, { "code": "bool2int b = if b 1 0\n", "language": "Clean" }, { "code": "case 6 * 7 of\n 42 -> \"Correct\"\n _ -> \"Wrong\" // default, matches anything\n", "language": "Clean" }, { "code": "answer 42 = True\nanswer _ = False\n", "language": "Clean" }, { "code": "answer x\n | x == 42 = True\n | otherwise = False\n\ncase 6 * 7 of\n n | n < 0 -> \"Not even close\"\n 42 -> \"Correct\"\n // no default, could result in a run-time error\n", "language": "Clean" }, { "code": "IF x == 1\n SomeFunc1()\nELSEIF x == 2\n SomeFunc2()\nELSE\n SomeFunc()\nENDIF\n", "language": "Clipper" }, { "code": "DO CASE\nCASE x == 1\n SomeFunc1()\nCASE x == 2\n SomeFunc2()\nOTHERWISE\n SomeFunc()\nENDCASE\n", "language": "Clipper" }, { "code": "(if (= 1 1) :yes :no) ; returns :yes\n\n(if (= 1 2) :yes :no) ; returns :no\n\n(if (= 1 2) :yes) ; returns nil\n", "language": "Clojure" }, { "code": "(when x\n (print \"hello\")\n (println \" world\")\n 5) ; when x is logical true, prints \"hello world\" and returns 5; otherwise does nothing, returns nil\n", "language": "Clojure" }, { "code": "(cond\n (= 1 2) :no) ; returns nil\n\n(cond\n (= 1 2) :no\n (= 1 1) :yes) ; returns :yes\n", "language": "Clojure" }, { "code": "(cond\n (= 1 2) :no\n :else :yes) ; returns :yes\n", "language": "Clojure" }, { "code": "(condp < 3\n 4 :a ; cond equivalent would be (< 4 3) :a\n 3 :b\n 2 :c\n 1 :d) ; returns :c\n", "language": "Clojure" }, { "code": "(condp < 3\n 4 :a\n 3 :b\n :no-match) ; returns :no-match\n", "language": "Clojure" }, { "code": "(case 2\n 0 (println \"0\")\n 1 (println \"1\")\n 2 (println \"2\")) ; prints 2.\n", "language": "Clojure" }, { "code": "set(num 5)\n\nif(num GREATER 100)\n message(\"${num} is very large!\")\nelseif(num GREATER 10)\n message(\"${num} is large.\")\nelse()\n message(\"${num} is small.\")\n message(\"We might want a bigger number.\")\nendif()\n", "language": "CMake" }, { "code": "if condition-1\n imperative-statement-1\nelse\n imperative-statement-2\nend-if\n\nif condition-1\n if condition-a\n imperative-statement-1a\n else\n imperative-statement-1\n end-if\nelse\n if condition-a\n imperative-statement-2a\n else\n imperative-statement-2\n end-if\nend-if\n", "language": "COBOL" }, { "code": "evaluate identifier-1\nwhen 'good'\n good-imperative-statement\nwhen 'bad'\n bad-imperative-statement\nwhen 'ugly'\nwhen 'awful'\n ugly-or-awful-imperative-statement\nwhen other\n default-imperative-statement\nend-evaluate\n\nevaluate true\nwhen condition-1\n condition-1-imperative-statement\nwhen condition-2\n condition-2-imperative-statement\nwhen condition-3\n condition-3-imperative-statement\nwhen other\n default-condition-imperative-statement\nend-evaluate\n\nevaluate identifier-1 also identifier-2\nwhen 10 also 20\n one-is-10-and-two-is-20-imperative-statement\nwhen 11 also 30\n one-is-11-and-two-is-30-imperative-statement\nwhen 20 also any\n one-is-20-and-two-is-anything-imperative-statement\nwhen other\n default-imperative-statement\nend-evaluate\n", "language": "COBOL" }, { "code": "if n == 1\n console.log \"one\"\nelse if n == 2\n console.log \"two\"\nelse\n console.log \"other\"\n", "language": "CoffeeScript" }, { "code": "n = 1\n\nswitch n\n when 1\n console.log \"one\"\n when 2, 3\n console.log \"two or three\"\n else\n console.log \"other\"\n", "language": "CoffeeScript" }, { "code": "s = if condition then \"yup\" else \"nope\"\n\n# alternate form\ns = \\\n if condition\n then \"yup\"\n else \"nope\"\n", "language": "CoffeeScript" }, { "code": "<cfif x eq 3>\n do something\n<cfelseif x eq 4>\n do something else\n<cfelse>\n do something else\n</cfif>\n", "language": "ColdFusion" }, { "code": "<cfswitch expression=\"#x#\">\n <cfcase value=\"1\">\n do something\n </cfcase>\n <cfcase value=\"2\">\n do something\n </cfcase>\n <cfdefaultcase>\n do something\n </cfdefaultcase>\n</cfswitch>\n", "language": "ColdFusion" }, { "code": "IF condition THEN PRINT \"True\"\n", "language": "Comal" }, { "code": "IF condition THEN\n PRINT \"True\"\nELSE\n PRINT \"False\"\nENDIF\n", "language": "Comal" }, { "code": "IF choice=1 THEN\n PRINT \"One\"\nELIF choice=2 THEN\n PRINT \"Two\"\nELSE\n Print \"None of the above\"\n", "language": "Comal" }, { "code": "CASE choice OF\nWHEN 1\n PRINT \"One\"\nWHEN 2\n PRINT \"Two\"\nOTHERWISE\n PRINT \"Some other choice\"\nENDCASE\n", "language": "Comal" }, { "code": "(if (= val 42)\n \"That is the answer to life, the universe and everything\"\n \"Try again\") ; the else clause here is optional\n", "language": "Common-Lisp" }, { "code": "(cond ((= val 1) (print \"no\"))\n ((and (> val 3) (< val 6)) (print \"yes\"))\n ((> val 99) (print \"too far\"))\n (T (print \"no way, man!\")))\n", "language": "Common-Lisp" }, { "code": "if (condition)\n{\n // Some Task\n}\n\nif (condition)\n{\n // Some Task\n}\nelse if (condition2)\n{\n // Some Task\n}\nelse\n{\n // Some Task\n}\n", "language": "Crack" }, { "code": "// if condition is true var will be set to 1, else false.\nint var = condition ? 1 : 2;\n", "language": "Crack" }, { "code": "( condición ) si ( sentencias si verdadero ) entonces\n( condición ) si ( sentencias si verdadero ) sino ( sentencias si falso ) entonces\n", "language": "Curto" }, { "code": ": menor-que-diez ( n -- )\n 10 < si\n .\" Menor que 10\"\n sino\n .\" Mayor o igual a 10\"\n entonces ;\n", "language": "Curto" }, { "code": "void main() {\n enum int i = 5;\n\n // \"static if\" for various static checks:\n static if (i == 7) {\n // ...\n } else {\n //...\n }\n\n // is(T == U) checks if type T is U.\n static if (is(typeof(i) == int)) {\n // ...\n } else {\n // ...\n }\n\n // D switch is improved over C switch:\n switch (i) {\n case 0:\n break; // Silent fallthrough is forbidden.\n case 1:\n goto case; // Explicit fallthrough.\n case 2:\n // Empty cases don't require an explicit fallthrough.\n case 3:\n return;\n case 4, 5, 7: // Multiple cases.\n break;\n case 8: .. case 15: // Inclusive interval.\n goto case 3;\n default: // Default case is required.\n break;\n }\n\n enum Colors { yellow, blue, brown, green }\n immutable c = Colors.blue;\n\n // \"final switch\" is safer, for enums (and in future other values,\n // like Algebraic), because all cases must be present.\n // with() is handy to avoid repeating \"Colors.\" for each case.\n final switch (c) with (Colors) {\n case yellow: break;\n case blue: break;\n case brown, green: break;\n // case yellow: .. case brown: // Forbidden in final switches.\n // default: // Forbidden in final switches.\n }\n}\n", "language": "D" }, { "code": "a = 3\nif( a == 1 ){\n io.writeln( 'a == 1' )\n}else if( a== 3 ){\n io.writeln( 'a == 3' )\n}else{\n io.writeln( 'a is neither 1 nor 3' )\n}\n", "language": "Dao" }, { "code": "a = 3\nswitch( a ){\ncase 0: io.writeln( 'case 0' )\ncase 1, 2: io.writeln( 'case 1,2' )\ncase 3, 4, 5: io.writeln( 'case 3,4,5' )\ndefault: io.writeln( 'default' )\n}\n", "language": "Dao" }, { "code": "if (input.Field == \"Hello World\") {\n sVar = \"good\";\n} else if (input.Field == \"Bye World\") {\n sVar = \"bad\";\n} else {\n sVar = \"neutral\";\n}\n", "language": "Deluge" }, { "code": "if (condition)\n // Do thing, DM uses indentation for control flow.\n\nif (condition)\n // Do thing\n\nelse if (condition)\n // Do thing\n\nelse\n // Do thing\n", "language": "DM" }, { "code": "// x will be 1 if condition is a true value, 2 otherwise.\nvar/x = condition ? 1 : 2\n", "language": "DM" }, { "code": "switch (value)\n if (0)\n // Do thing if zero\n // DM does not have fall through of switch cases, so explicit break is not required.\n if (1, 2, 3)\n // Multiple values can be allowed by using commas\n\n if (10 to 20)\n // Ranges are also allowed.\n // Ranges include the bounds (10 and 20 here),\n // and are checked in order if there is potential for overlap.\n\n else\n // Fallback if nothing was matched.\n", "language": "DM" }, { "code": "if(a == b)\n{\n add()\n}\nelse if(a == c)\n less() //{}'s optional for one-liners\nelse\n{\n both()\n}\n", "language": "Dragon" }, { "code": "if (okay) {\n println(\"okay\")\n} else if (!okay) {\n println(\"not okay\")\n} else {\n println(\"not my day\")\n}\n", "language": "E" }, { "code": "println(okay.pick(\"okay\", \"not okay\"))\n", "language": "E" }, { "code": "okay.pick(fn {\n println(\"okay\")\n}, fn {\n println(\"not okay\")\n})()\n", "language": "E" }, { "code": "def expression := [\"+\", [1, 2]]\n\ndef value := switch (expression) {\n match [`+`, [a, b]] { a + b }\n match [`*`, [a, b]] { a * b }\n match [op, _] { throw(`unknown operator: $op`) }\n}\n", "language": "E" }, { "code": "i = randint 10\nif i mod 2 = 0\n print i & \" is divisible by 2\"\nelif i mod 3 = 0\n print i & \" is divisible by 3\"\nelse\n print i & \" is not divisible by 2 or 3\"\n.\n", "language": "EasyLang" }, { "code": "show_if_with_parenthesis = fn (Num) {\n if (Num == 1) {\n io.format(\"is one~n\")\n }\n else if (Num === 2) {\n io.format(\"is two~n\")\n }\n else {\n io.format(\"not one not two~n\")\n }\n}\n\nshow_if_without_parenthesis = fn (Num) {\n if Num == 1 {\n io.format(\"is one~n\")\n }\n else if Num === 2 {\n io.format(\"is two~n\")\n }\n else {\n io.format(\"not one not two~n\")\n }\n}\n\nshow_switch_with_parenthesis = fn (Num) {\n switch (Num) {\n case (1) {\n io.format(\"one!~n\")\n }\n case (2) {\n io.format(\"two!~n\")\n }\n else {\n io.format(\"else~n\")\n }\n }\n}\n\nshow_switch_without_parenthesis = fn (Num) {\n switch (Num) {\n case 1 {\n io.format(\"one!~n\")\n }\n case 2 {\n io.format(\"two!~n\")\n }\n else {\n io.format(\"else~n\")\n }\n }\n}\n\n@public\nrun = fn () {\n show_if_with_parenthesis(random.uniform(3))\n show_if_without_parenthesis(random.uniform(3))\n\n show_switch_with_parenthesis(random.uniform(3))\n show_switch_without_parenthesis(random.uniform(3))\n}\n", "language": "Efene" }, { "code": "if x < 0 then 0 else x\n", "language": "Ela" }, { "code": "getX x | x < 0 = 0\n | else = x\n", "language": "Ela" }, { "code": "force (x::xs) = x :: force xs\nforce [] = []\n", "language": "Ela" }, { "code": "force lst = match lst with\n x::xs = x :: force xs\n [] = []\n", "language": "Ela" }, { "code": "int i = 19\n^|if–then–else|^\nif i > 18\n writeLine(\"greater than 18\")\nelse\n writeLine(\"less or equal to 18\")\nend\n^|else if|^\nif i == 18 do writeLine(\"equal to 18\")\nelse if i < 18 do writeLine(\"less than 18\")\nelse do writeLine(\"greater than 18\")\nend\n^|when expression: just like iif in Visual Basic|^\nwriteLine(when(i > 18, \"greater than 18\", \"less or equal to 18\"))\n^|hash-based conditionals|^\nMap dispatch = int%fun[\n 18 => <|writeLine(\"equal to 18\"),\n 19 => <|writeLine(\"yeah, it's 19\")]\nif dispatch.has(i) do dispatch[i]() end\n", "language": "EMal" }, { "code": "case X of\n {N,M} when N > M -> M;\n {N,M} when N < M -> N;\n _ -> equal\nend.\n", "language": "Erlang" }, { "code": "{N,M} = X,\nif\n N > M -> M;\n N < M -> N;\n true -> equal\nend.\n", "language": "Erlang" }, { "code": "test({N,M}) when N > M -> M;\ntest({N,M}) when N < M -> N;\ntest(_) -> equal.\n", "language": "Erlang" }, { "code": "printfn \"%s\" (if 3<2 then \"3 is less than 2\" else \"3 is not less than 2\")\n", "language": "F-Sharp" }, { "code": "t 1 2 ? ! returns 1\n", "language": "Factor" }, { "code": "t [ 1 ] [ 2 ] if ! returns 1\n", "language": "Factor" }, { "code": "{ { [ t ] [ 1 ] } { [ f ] [ 2 ] } } cond ! returns 1\n", "language": "Factor" }, { "code": "t { { t [ 1 ] } { f [ 2 ] } } case ! returns 1\n", "language": "Factor" }, { "code": "t [ \"1\" print ] when ! prints 1\n", "language": "Factor" }, { "code": "f [ \"1\" print ] unless ! prints 1\n", "language": "Factor" }, { "code": "condition[body]?\n", "language": "FALSE" }, { "code": "$[\\true\\]?~[false]?\n", "language": "FALSE" }, { "code": "$[%true0~]?~[false]?\n", "language": "FALSE" }, { "code": "if: (x < y) then: {\n \"x < y!\" println # will only execute this block if x < y\n}\n", "language": "Fancy" }, { "code": "if: (x < y) then: {\n \"x < y!\" println # will only execute this block if x < y\n} else: {\n \"x not < y!\" println\n}\n", "language": "Fancy" }, { "code": "x < y if_true: {\n \"x < y!\" println # will only execute this block if x < y\n}\n", "language": "Fancy" }, { "code": "x < y if_false: {\n \"x not < y!\" println # will only execute this block if x >= y\n}\n", "language": "Fancy" }, { "code": "x < y if_true: {\n \"x < y!\" println\n} else: {\n \"x >= y!\" println\n}\n", "language": "Fancy" }, { "code": "x < y if_false: {\n \"x >= y!\"\n} else: {\n \"x < y!\" println\n}\n", "language": "Fancy" }, { "code": "{ \"x < y!\" println } if: (x < y) # analog, but postfix\n", "language": "Fancy" }, { "code": "{ \"x not < y!\" } unless: (x < y) # same here\n", "language": "Fancy" }, { "code": "( condition ) IF ( true statements ) THEN\n( condition ) IF ( true statements ) ELSE ( false statements ) THEN\n", "language": "Forth" }, { "code": "10 < IF .\" Less than 10\" ELSE .\" Greater than or equal to 10\" THEN\n", "language": "Forth" }, { "code": "( n -- ) CASE\n( integer ) OF ( statements ) ENDOF\n( integer ) OF ( statements ) ENDOF\n( default instructions )\nENDCASE\n", "language": "Forth" }, { "code": ": test-case ( n -- )\n CASE\n 0 OF .\" Zero!\" ENDOF\n 1 OF .\" One!\" ENDOF\n .\" Some other number!\"\n ENDCASE ;\n", "language": "Forth" }, { "code": ": switch\n CREATE ( default-xt [count-xts] count -- ) DUP , 0 DO , LOOP ,\n DOES> ( u -- ) TUCK @ MIN 1+ CELLS + @ EXECUTE ;\n\n :NONAME .\" Out of range!\" ;\n :NONAME .\" nine\" ;\n :NONAME .\" eight\" ;\n :NONAME .\" seven\" ;\n :NONAME .\" six\" ;\n :NONAME .\" five\" ;\n :NONAME .\" four\" ;\n :NONAME .\" three\" ;\n :NONAME .\" two\" ;\n :NONAME .\" one\" ;\n :NONAME .\" zero\" ;\n10 switch digit\n\n 8 digit \\ eight\n34 digit \\ Out of range!\n", "language": "Forth" }, { "code": ": CASE: ( <name>) CREATE ;\n\n\\ lookup execution token and compile\n: | ( <name> ) ' compile, ;\n\n: ;CASE ( n -- ) DOES> OVER + + @ EXECUTE ;\n\n : FOO .\" FOO\" ;\n : BAR .\" BAR\" ;\n : FIZZ .\" FIZZ\" ;\n : BUZZ .\" BUZZ\" ;\n\nCASE: SELECT ( n -- ) | FOO | BAR | FIZZ | BUZZ ;CASE\n\n\\ Usage: 3 SELECT\n", "language": "Forth" }, { "code": "if ( a .gt. 20.0 ) then\n q = q + a**2\nelse if ( a .ge. 0.0 ) then\n q = q + 2*a**3\nelse\n q = q - a\nend if\n", "language": "Fortran" }, { "code": "select case (i)\n case (21:) ! matches all integers greater than 20\n q = q + i**2\n case (0:20) ! matches all integers between 0 and 20 (inclusive)\n q = q + 2*i**3\n case default ! matches all other integers (negative in this particular case)\n q = q - I\nend select\n", "language": "Fortran" }, { "code": "! diffusion grid time step\nwhere (edge_type(1:n,1:m) == center)\n anew(1:n,1:m) = (a(1:n,1:m) + a(0:n-1,1:m) + a(2:n+1,1:m) + a(1:n,0:m-1) + a(1:n,2:m+1)) / 5\n\nelsewhere (edge_type(1:n,1:m) == left)\n anew(1:n,1:m) = (a(1:n,1:m) + 2*a(2:n+1,1:m) + a(1:n,0:m-1) + a(1:n,2:m+1)) / 5\n\nelsewhere (edge_type(1:n,1:m) == right)\n anew(1:n,1:m) = (a(1:n,1:m) + 2*a(0:n-1,1:m) + a(1:n,0:m-1) + a(1:n,2:m+1)) / 5\n\nelsewhere (edge_type(1:n,1:m) == top)\n anew(1:n,1:m) = (a(1:n,1:m) + a(0:n-1,1:m) + a(2:n+1,1:m) + 2*a(1:n,2:m+1)) / 5\n\nelsewhere (edge_type(1:n,1:m) == bottom)\n anew(1:n,1:m) = (a(1:n,1:m) + a(0:n-1,1:m) + a(2:n+1,1:m) + 2*a(1:n,0:m-1)) / 5\n\nelsewhere (edge_type(1:n,1:m) == left_top)\n anew(1:n,1:m) = (a(1:n,1:m) + 2*a(2:n+1,1:m) + 2*a(1:n,2:m+1)) / 5\n\nelsewhere (edge_type(1:n,1:m) == right_top)\n anew(1:n,1:m) = (a(1:n,1:m) + 2*a(0:n-1,1:m) + 2*a(1:n,2:m+1)) / 5\n\nelsewhere (edge_type(1:n,1:m) == left_bottom)\n anew(1:n,1:m) = (a(1:n,1:m) + 2*a(2:n+1,1:m) + 2*a(1:n,0:m-1)) / 5\n\nelsewhere (edge_type(1:n,1:m) == right_bottom)\n anew(1:n,1:m) = (a(1:n,1:m) + 2*a(0:n-1,1:m) + 2*a(1:n,0:m-1)) / 5\n\nelsewhere ! sink/source, does not change\n anew(1:n,1:m) = a(1:n,1:m)\nend where\n", "language": "Fortran" }, { "code": "Dim a As Integer = 1\nIf a = 1 Then\n sub1\nElseIf a = 2 Then\n sub2\nElse\n sub3\nEnd If\n", "language": "FreeBASIC" }, { "code": "Dim a As Integer = 1\nSelect Case a\n Case 1\n sub1\n Case 2\n sub2\n Case Else\n sub3\nEnd Select\n", "language": "FreeBASIC" }, { "code": "Dim b As Boolean = True\nDim i As Integer = IIf(b, 1, 2)\n", "language": "FreeBASIC" }, { "code": "Dim a As Integer = 1\nOn a Goto label1, label2\n", "language": "FreeBASIC" }, { "code": "Dim b As Boolean = True\nIf b Goto label\n", "language": "FreeBASIC" }, { "code": "Dim a As Integer = 1\nOn a Gosub label1, label2\n", "language": "FreeBASIC" }, { "code": "#DEFINE WORDSIZE 16\n#IF (WORDSIZE = 16)\n ' Do some some 16 bit stuff\n#ELSEIF (WORDSIZE = 32)\n ' Do some some 32 bit stuff\n#ELSE\n #ERROR WORDSIZE must be set to 16 or 32\n#ENDIF\n", "language": "FreeBASIC" }, { "code": "#DEFINE _DEBUG\n#IFDEF _DEBUG\n ' Special statements for debugging\n#ENDIF\n", "language": "FreeBASIC" }, { "code": "#IFNDEF _DEBUG\n #DEFINE _DEBUG\n#ENDIF\n", "language": "FreeBASIC" }, { "code": "set var 'Hello World'\nif test $var = 'Hello World'\n echo 'Welcome.'\nelse if test $var = 'Bye World'\n echo 'Bye.'\nelse\n echo 'Huh?'\nend\n", "language": "Friendly-interactive-shell" }, { "code": "switch actually\n case az\n echo The word is \"az\".\n case 'a*z'\n echo Begins with a and ends with z.\n case 'a*'\n echo Begins with a.\n case 'z*'\n echo Ends with z.\n case '*'\n echo Neither begins with a or ends with z.\nend\n", "language": "Friendly-interactive-shell" }, { "code": "if <condition> then <truebranch> else <falsebranch>\n", "language": "Futhark" }, { "code": "local fn DoIt\n long A = 7\n if A > 0 then print \"A is a positive number\" else print \"A is a negative number\"\n\n long B = -10\n if B > 0\n print \"B is a positive number\"\n else\n print \"B is a negative number\"\n end if\n\n long C = 99\n select (C)\n case C < 0\n print \"C is a negative number\"\n case C = 0\n print \"C is zero\"\n case C > 0\n print \"C is a positive number\"\n case else\n print \"C is unknown\"\n end select\n\n CFStringRef suitName, suitSymbol\n suitSymbol = @\"S\"\n select (suitSymbol)\n case @\"C\": suitName = @\"Clubs\"\n case @\"D\": suitName = @\"Diamonds\"\n case @\"H\": suitName = @\"Hearts\"\n case @\"S\": suitName = @\"Spades\"\n case else : suitName = @\"Unknown\"\n end select\n print suitName\nend fn\n\nfn Doit\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "if <condition> then\n <statements>\nelif <condition> then\n <statements>\nelse\n <statements>\nfi;\n", "language": "GAP" }, { "code": "if booleanExpression {\n statements\n}\n", "language": "Go" }, { "code": "treadmill: for {\n switch {\n case true:\n break treadmill\n }\n}\nfmt.Println(\"I'm off!\")\n", "language": "Go" }, { "code": "if booleanExpression {\n statements\n} else {\n other\n statements\n}\n", "language": "Go" }, { "code": "if booleanExpression1 {\n statements\n} else if booleanExpression2 {\n otherStatements\n}\n", "language": "Go" }, { "code": "if x := fetchSomething(); x > 0 {\n DoPos(x)\n} else {\n DoNeg(x)\n}\n", "language": "Go" }, { "code": "switch {\ncase booleanExpression1:\n statements\ncase booleanExpression2:\n other\n statements\ndefault:\n last\n resort\n statements\n}\n", "language": "Go" }, { "code": "switch expressionOfAnyType {\ncase value1:\n statements\ncase value2, value3, value4:\n other\n statements\n}\n", "language": "Go" }, { "code": "switch x := fetch(); {\ncase x == \"cheese\":\n statements\ncase otherBooleanExpression:\n other\n statements\n}\n", "language": "Go" }, { "code": "switch {\ncase booleanExpression1:\ndefault:\n statements\n preliminaryToOtherStatements\n fallthrough\ncase booleanExpression2:\n other\n statements\n}\n", "language": "Go" }, { "code": "for {\n switch {\n case true:\n break\n }\n fmt.Println(\"I want out!\")\n}\n", "language": "Go" }, { "code": "let x = if (1 < 2) {\n \":)\"\n} else { // The else clause is required here as x is a string\n \":(\"\n}\n\nif (2 > 3) {\n print(\"This should never execute.\")\n} // We can omit the else clause here\n\n// We use else if for chaining\nif (1 > 2) {\n print(\"1 is less than 2\")\n} else if (2 == 3) {\n print(\"2 is 3\")\n} else {\n print(\"This should always execute.\")\n}\n", "language": "Grain" }, { "code": "// A match statement more like the traditional switch statement\n// often seen in other languages.\nenum PizzaTopping { Cheese, Pepperoni, Peppers, Pineapple }\n\nlet topping = Peppers\n\nmatch (topping) {\n Cheese => print(\"Would it really be pizza without it?\"),\n Pepperoni => print(\"An instant classic.\"),\n Peppers => {\n // We can use a block for more expressions.\n print(\"For those who like to spice things up.\")\n },\n Pineapple => print(\"You do you.\")\n}\n", "language": "Grain" }, { "code": "enum Topping { Cheese, Pepperoni, Peppers, Pineapple }\nenum Menu { Pizza(Topping), Calzone(Topping) }\n\nlet item = Calzone(Peppers)\n\nmatch (item) {\n Calzone(topping) => {\n if (checkSpecials(topping)) {\n print(\"These are half off this week.\")\n } else {\n print(\"No current specials.\")\n }\n },\n _ => print(\"No current specials.\")\n}\n", "language": "Grain" }, { "code": "IF x == 1\n SomeFunc1()\nELSEIF x == 2\n SomeFunc2()\nELSE\n SomeFunc()\nENDIF\n", "language": "Harbour" }, { "code": "DO CASE\nCASE x == 1\n SomeFunc1()\nCASE x == 2\n SomeFunc2()\nOTHERWISE\n SomeFunc()\nENDCASE\n", "language": "Harbour" }, { "code": "SWITCH x\nCASE 1\n SomeFunc1()\n EXIT\nCASE 2\n SomeFunc2()\n EXIT\nOTHERWISE\n SomeFunc()\nENDSWITCH\n", "language": "Harbour" }, { "code": "fac x = if x==0 then\n 1\n else x * fac (x - 1)\n", "language": "Haskell" }, { "code": "fac x | x==0 = 1\n | x>0 = x * fac (x-1)\n", "language": "Haskell" }, { "code": "fac 0 = 1\nfac x = x * fac (x-1)\n", "language": "Haskell" }, { "code": "fac x = case x of 0 -> 1\n _ -> x * fac (x-1)\n", "language": "Haskell" }, { "code": "IF( a > 5 ) WRITE(Messagebox) a ! single line IF\n\nIF( a >= b ) THEN\n WRITE(Text=some_string) a, b\n ELSEIF(some_string > \"?\") THEN\n WRITE(ClipBoard) some_string\n ELSEIF( nonzero ) THEN\n WRITE(WINdowhandle=nnn) some_string\n ELSE\n WRITE(StatusBar) a, b, some_string\nENDIF\n", "language": "HicEst" }, { "code": "IF X THEN\n\t// do if X is not 0\nELSE\n\t// do if X is 0\nEND;\n", "language": "HPPPL" }, { "code": "CASE\n\tIF X == 1 THEN\n\t\t// do stuff if X equals 1\n\tEND\n\tIF X == 2 THEN\n\t\t// do stuff if X equals 1\n\tEND\n\tIF X == 3 THEN\n\t\t// do stuff if X equals 3\n\tEND\n\tDEFAULT\n\t\t// do other stuff\nEND;\n", "language": "HPPPL" }, { "code": "//'i' supports if, else, and else if\nsoftware {\n\ta = 3\n\n\tif a = 3\n\t\tprint(\"a = three\")\n\telse if a = 2\n\t\tprint(\"a = two\")\n\telse\n\t\tprint(\"a = \", a)\n\tend\n}\n", "language": "I" }, { "code": "if expr0 then\n expr1\nelse\n expr2\n", "language": "Icon" }, { "code": " expr0(expr1, expr2, expr3)\n", "language": "Icon" }, { "code": " 2(expr1, expr2, expr3)\n", "language": "Icon" }, { "code": " f(expr1)(g(expr2)(expr3,expr4,expr5))\n", "language": "Icon" }, { "code": "case expr0 of {\n expr1 : expr2\n expr3 : expr4\n default: expr5\n }\n", "language": "Icon" }, { "code": "case x of {\n f(x) | g(x) : expr2\n s(x) & t(x) : expr4\n default: expr5\n }\n", "language": "Icon" }, { "code": "{\n expr1\n expr2\n expr3\n}\n", "language": "Icon" }, { "code": "{expr1; expr2; expr3}\n", "language": "Icon" }, { "code": "write({1;2;3;4})\n", "language": "Icon" }, { "code": " expr1 | expr2 | expr3\n", "language": "Icon" }, { "code": " expr1 & expr2 & expr3\n", "language": "Icon" }, { "code": " (expr1, expr2, expr3)\n", "language": "Icon" }, { "code": "if a eq 5 then print, \"a equals five\" [else print, \"a is something else\"]\n", "language": "IDL" }, { "code": "if a eq 5 then begin\n ... some code here ...\nendif [else begin\n ... some other code here ...\nendelse]\n", "language": "IDL" }, { "code": "case <expression> of\n (choice-1): <command-1>\n [(choice-2): <command-2> [...]]\n [else: <command-else>]\nendcase\n", "language": "IDL" }, { "code": "switch <expression> of\n (choice-1): <command-1>\n [(choice-2): <command-2> [...]]\n [else: <command-else>]\nendswitch\n", "language": "IDL" }, { "code": "on_error label\n", "language": "IDL" }, { "code": "[short form]\nif N is 1, say \"one.\";\notherwise say \"not one.\";\n\n[block form]\nif N is 1:\n\tsay \"one.\";\notherwise if N is 2:\n\tsay \"two.\";\notherwise:\n\tsay \"not one or two.\";\n\n[short and long forms can be negated with \"unless\"]\nunless N is 1, say \"not one.\"\n", "language": "Inform-7" }, { "code": "if N is:\n\t-- 1: say \"one.\";\n\t-- 2: say \"two.\";\n\t-- otherwise: say \"not one or two.\";\n", "language": "Inform-7" }, { "code": "say \"[if N is 1]one[otherwise if N is 2]two[otherwise]three[end if].\";\nsay \"[unless N is odd]even.[end if]\";\n", "language": "Inform-7" }, { "code": "[a different color every time]\nsay \"[one of]red[or]blue[or]green[at random].\";\n\n[\"one\" the first time it's printed, \"two\" the second time, then \"three or more\" subsequently]\nsay \"[one of]one[or]two[or]three or more[stopping]\";\n\n[only appears once]\nsay \"[first time]Hello world![only]\";\n", "language": "Inform-7" }, { "code": "Number Factory is a room.\n\nNumber handling is a number based rulebook with default success.\n\nNumber handling for 1: say \"one.\"\nNumber handling for 2: say \"two.\"\nNumber handling for an even number (called N): say \"[N in words] (which is even).\"\nLast number handling rule: say \"other.\"\n\nWhen play begins:\n\tfollow the number handling rules for 2;\n\tfollow the number handling rules for 4;\n\tfollow the number handling rules for 5.\n", "language": "Inform-7" }, { "code": "theory Scratch\n imports Main\nbegin\n\ntext‹if-then-else›\nlemma \"(if True then 42 else 0) = 42\" by simp\n\ntext‹case statement with pattern matching, which evaluates to the True-case›\nlemma \"case [42] of\n Nil ⇒ False\n | [x] ⇒ True\n | x#xs ⇒ False\" by simp\n\ntext‹Loops are implemented via recursive functions›\nfun recurse :: \"nat ⇒ nat\" where\n \"recurse 0 = 0\"\n| \"recurse (Suc n) = recurse n\"\n\ntext‹The function always returns zero.›\nlemma \"recurse n = 0\" by(induction n) simp+\n\nend\n", "language": "Isabelle" }, { "code": "fn main() {\n let a = 5\n let b = 3\n\n // If/else/else-if\n if a > b {\n println(\"a > b\")\n } else if a < b {\n println(\"a < b\")\n } else {\n println(\"a = b\")\n }\n\n // Match\n match a {\n (..5) => {\n println(\"a < 5\")\n }\n 5 => {\n println(\"a == 5\")\n }\n else => {\n println(\"a > 5\")\n }\n }\n\n // Or equivalently\n println(match a {\n (..5) => \"a < 5\"\n 5 => \"a == 5\"\n else => \"a > 5\"\n })\n\n // Hash based\n let primality = [\n 1: false\n 2: false\n 3: true\n 4: false\n 5: true\n 6: false\n ]\n let a_is_prime = primality[a]\n println(\"a_is_prime = {}\", a_is_prime)\n}\n", "language": "Jakt" }, { "code": "if (s.equals(\"Hello World\")) {\n foo();\n} else if (s.equals(\"Bye World\"))\n bar(); // braces optional for one-liners\nelse {\n deusEx();\n}\n", "language": "Java" }, { "code": "if (obj != null && obj.foo()) {\n aMethod();\n}\n", "language": "Java" }, { "code": "if (obj != null & obj.foo()) {\n aMethod();\n}\n", "language": "Java" }, { "code": "s.equals(\"Hello World\") ? foo() : bar();\n", "language": "Java" }, { "code": "Object newValue = s.equals(\"Hello World\") ? a : b;\n", "language": "Java" }, { "code": "switch (c) {\n case 'a':\n foo();\n break;\n case 'b':\n bar();\n default:\n foobar();\n}\n", "language": "Java" }, { "code": "if (c == 'a') {\n foo();\n} else if (c == 'b') {\n bar();\n foobar();\n} else {\n foobar();\n}\n", "language": "Java" }, { "code": "int x = switch (c) {\n case 'a':\n foo();\n yield 1;\n case 'b':\n bar();\n default:\n foobar();\n yield 0;\n}\n", "language": "Java" }, { "code": "int y = switch (c) {\n case '1', '2' -> 1 // multiple cases can be on one line\n default -> { // use a block for multiple statements\n foobar();\n yield 0;\n }\n}\n", "language": "Java" }, { "code": "if( s == \"Hello World\" ) {\n foo();\n} else if( s == \"Bye World\" ) {\n bar();\n} else {\n deusEx();\n}\n", "language": "JavaScript" }, { "code": "switch(object) {\n case 1:\n one();\n break;\n case 2:\n case 3:\n case 4:\n twoThreeOrFour();\n break;\n case 5:\n five();\n break;\n default:\n everythingElse();\n}\n", "language": "JavaScript" }, { "code": "var num = window.obj ? obj.getNumber() : null;\n", "language": "JavaScript" }, { "code": "function takeWhile(lst, fnTest) {\n 'use strict';\n var varHead = lst.length ? lst[0] : null;\n\n return varHead ? (\n fnTest(varHead) ? [varHead].concat(\n takeWhile(lst.slice(1), fnTest)\n ) : []\n ) : [];\n}\n", "language": "JavaScript" }, { "code": " COND=(rcval,relop,step)\n relop is a relational opeator : EQ NE GT LT GE LE (= ¬= < > <= >=)\n", "language": "JCL" }, { "code": " if rcval relop step.rc then not execute the current step\n", "language": "JCL" }, { "code": "//STEP6 EXEC PGM=MYPROG,COND=(0,NE,STEP3)\n", "language": "JCL" }, { "code": " COND=((rcval1,relop1,step1),(rcval2,relop2,step2),...)\n", "language": "JCL" }, { "code": " if rcval1 relop1 step1.rc or rcval2 relop2 step2.rc or ... then not execute the current step\n", "language": "JCL" }, { "code": "//STEP6 EXEC PGM=MYPROG,COND=((4,LE,STEP1),(8,LE,STEP3))\n", "language": "JCL" }, { "code": "print(Template(\"\"\"{% for lang in [\"Jinja\", \"Python\", \"Swift\", \"Nim\"] %}\n {{ loop.index }}) {{ lang }}{% if loop.last %}.{% else %},{% endif %}\n {%- endfor %}\"\"\").render())\n", "language": "Jinja" }, { "code": "print(Template(\"\"\"{% for lang in [\"Jinja\", \"Python\", \"Swift\", \"Nim\"] %}\n {{ loop.index }}) {{ lang }}{{ \".\" if loop.last else \",\" }}\n {%- endfor %}\"\"\").render())\n", "language": "Jinja" }, { "code": "print(Template(\"\"\"{% for lang in [\"Jinja\", \"Python\", \"Swift\", \"Nim\"] %}\n {{ loop.index }}) {{ lang }}{{ loop.last and \".\" or \",\" }}\n {%- endfor %}\"\"\").render())\n", "language": "Jinja" }, { "code": "if cond then f else g end\n", "language": "Jq" }, { "code": "if cond then f elif cond1 then f1 .... else g end\n", "language": "Jq" }, { "code": "if empty then 2 else 3 end # produces no value\nif 1 then 2 else 3 end # produces 2\nif [false, false] then 2 else 3 end # produces 2\nif (true, true) then 2 else 3 end # produces a stream: 2, 2\n", "language": "Jq" }, { "code": "exp\n | if . == true then \"true\"\n elif . == false then \"false\"\n elif . == null then \"maybe\"\n elif type == \"string\" then .\n else error(\"unexpected value: \\(.)\")\n end\n", "language": "Jq" }, { "code": "function test(x, y)\n if x < y\n println(\"x is less than y\")\n elseif x > y\n println(\"x is greater than y\")\n else\n println(\"x is equal to y\")\n end\nend\n\njulia> test(1, 2)\nx is less than y\n\njulia> test(2, 1)\nx is greater than y\n\njulia> test(1, 1)\nx is equal to y\n", "language": "Julia" }, { "code": "a ? b : c\n", "language": "Julia" }, { "code": "if 1;\n $result = \"Execute\";\n\nif 0;\n $result = \"Ignored\";\n\nif 1; {\n $result = \"Block\";\n $result = \"Execute\";\n}\n\nif 0; {\n $result = \"Block\";\n $result = \"Ignored\";\n}\n\nif 1 == 1;\n $result = \"Execute\";\n\nif 1 < 2;\n $result = \"Execute\";\n\nif 1 <= 1;\n $result = \"Execute\";\n\nif 2 > 1;\n $result = \"Execute\";\n\nif 1 >= 1;\n $result = \"Execute\";\n\nif 1 != 2;\n $result = \"Execute\";\n\n$a = 1;\nif $a == 1;\n $result = \"Execute\";\n\nif $a == kabap.version;\n $result = \"Execute\";\n\nif 1 == \"1\";\n $result = \"Execute\";\n\nif 1 + 1 == 2;\n $result = \"Execute\";\n\nif 1;\n if 1; {\n if 1;\n if 1; {\n $result = \"Execute\";\n }\n }\n", "language": "Kabap" }, { "code": "?A>[The letter is larger than a|The letter is smaller than a]\n", "language": "Keg" }, { "code": "?![You did enter something]\n", "language": "Keg" }, { "code": "2?1>*# Returns 2 if the input is larger than 1\n", "language": "Keg" }, { "code": "// version 1.0.6\n\nfun main(args: Array<String>) {\n // conventional 'if/else if/else' statement\n if (args.isEmpty()) println(\"No arguments were supplied\")\n else if (args.size == 1) println(\"One argument was supplied\")\n else println(\"${args.size} arguments were supplied\")\n\n print(\"Enter an integer : \")\n val i = readLine()!!.toInt()\n\n // 'when' statement (similar to 'switch' in C family languages)\n when (i) {\n 0, 1 -> println(\"0 or 1\")\n in 2 .. 9 -> println(\"Between 2 and 9\")\n else -> println(\"Out of range\")\n }\n\n // both of these can be used as expressions as well as statements\n val s = if (i < 0) \"negative\" else \"non-negative\"\n println(\"$i is $s\")\n val t = when {\n i > 0 -> \"positive\"\n i == 0 -> \"zero\"\n else -> \"negative\"\n }\n println(\"$i is $t\")\n}\n", "language": "Kotlin" }, { "code": "{if true then yes else no}\n-> yes\n\n{def switch\n {lambda {:n}\n {if {< :n 0}\n then :n is negative\n else {if {> :n 0}\n then :n is positive\n else :n is zero}}}}\n\n{switch -12}\n-> -12 is negative\n{switch 12}\n-> 12 is positive\n{switch 0}\n-> 0 is zero\n", "language": "Lambdatalk" }, { "code": "if .x == 0 {\n ...\n} else if .x > 0 {\n val .y = 100\n ...\n} else {\n val .y = 70\n ...\n}\n", "language": "Langur" }, { "code": "if(.x > .y: ...; .x < .y: ...; /* else */ ...)\n", "language": "Langur" }, { "code": "if .x > .y: break\n", "language": "Langur" }, { "code": "switch .x, .y, .z {\n case true: ...\n # any are true\n case false, _: ...\n # .x == false\n case _, null, true: ...\n # .y == null or .z == true\n case xor _, true, true: ...\n # .y == true xor .z == true\n}\n\nswitch 0 {\n case .x, .y: ...\n # .x or .y equals 0\n ...\n}\n\nswitch[and] .x, .y, .z {\n case true: ...\n # all are true\n case false, _: ...\n # .x == false\n case _, null, true: ...\n # .y == null and .z == true\n}\n", "language": "Langur" }, { "code": "switch .x {\n case true:\n # implicit fallthrough\n case null: 0\n # no fallthrough\n default: 1\n}\n", "language": "Langur" }, { "code": "switch .x {\n case true:\n if .y > 100 {\n fallthrough\n } else {\n 120\n }\n case false: ...\n}\n", "language": "Langur" }, { "code": "switch(.x, .y, .z;\n true: ... ; # any are equal to true\n _, >= .z: ...; # .y >= .z\n ... ) # default\n", "language": "Langur" }, { "code": "BR or BRnzp ; unconditional branch, i.e.\n ; branch if (result < 0 || result == 0 || result > 0)\n ; ^ this is always true\n\nBRn ; branch if (result < 0)\nBRz ; branch if (result == 0)\nBRp ; branch if (result > 0)\n\n ; or any combination of these condition codes, e.g.\nBRnz ; branch if (result <= 0)\n", "language": "LC3-Assembly" }, { "code": ".orig x3000\nLD R1, x ; get x\nLD R2, y ; get y\nNOT R0, R2 ; R0 = ~y\nADD R0, R0, 1\t; R0 = -y\nADD R0, R0, R1\t; R0 = x - y\nBRZ BRANCH ; if (x == y) { go to BRANCH }\nLEA R0, nottaken\nPUTS ; else print \"Branch Not Taken!\"\nBR END\nBRANCH\nLEA R0, taken\nPUTS ; print \"Branch Taken!\"\nEND HALT\nx .fill 1\ny .fill 1\ntaken .stringz \"Branch Taken!\"\nnottaken .stringz \"Branch Not Taken!\"\n.end\n", "language": "LC3-Assembly" }, { "code": "if {$a > 10} {print \"code evaluated on true\"}\nif {$a > 10} {print \"again\"} {print \"code evaluated on false\"}\n", "language": "LIL" }, { "code": "+ n : INTEGER;\n\nn := 3;\n\n(n = 2).if {\n IO.put_string \"n is 2\\n\";\n}.elseif {n = 3} then {\n IO.put_string \"n is 3\\n\";\n}.elseif {n = 4} then {\n IO.put_string \"n is 4\\n\";\n} else {\n IO.put_string \"n is none of the above\\n\";\n};\n", "language": "Lisaac" }, { "code": "(n = 2).if_true { \"n is 2\\n\".print; };\n(n = 2).if_false { \"n is not 2\\n\".print; };\n", "language": "Lisaac" }, { "code": "+ n : INTEGER;\n\nn := 3;\nn\n.when 2 then {\n \"n is 2\\n\".print;\n}\n.when 3 then {\n \"n is 3\\n\".print;\n}\n.when 4 then {\n \"n is 4\\n\".print;\n};\n", "language": "Lisaac" }, { "code": "int a = 3;\n\n// if-then-else\nif (a == 2) {\n puts (\"a is 2\");\n} else if (a == 3) {\n puts (\"a is 3\");\n} else {\n puts(\"a is 4\");\n}\n\n// unless\nunless (a == 2) { // equivalent to if (a != 2)\n puts (\"a is 2\"); // It will print this line\n} else if (a == 3) {\n puts (\"a is 3\");\n} else {\n puts(\"a is 4\");\n}\n\n// switch\nswitch (a) {\n case 2:\n puts (\"a is 2\");\n break;\n case 3:\n puts (\"a is 3\");\n break;\n case 4:\n puts (\"a is 4\");\n break;\n default:\n puts(\"is neither\");\n}\n", "language": "Little" }, { "code": "if :x < 0 [make \"x 0 - :x]\n\nifelse emptyp :list [print [empty]] [print :list]\n", "language": "Logo" }, { "code": "to vowel? :letter\noutput case :letter [ [[a e i o u] \"true] [else \"false] ]\nend\nshow vowel? \"e\nshow vowel? \"x\n", "language": "Logo" }, { "code": "true\nfalse\n", "language": "Logo" }, { "code": "to mytest :arg1 :arg2\ntest :arg1 = :arg2\niftrue [print [Arguments are equal]]\niffalse [print [Arguments are not equal]]\nend\n", "language": "Logo" }, { "code": "t : \" true\" ,t\nf : \" false\" ,t\ntrue if t\nfalse ifnot f\ntrue ifelse t f\n", "language": "LSE64" }, { "code": "onetwo : drop \" Neither one nor two\" ,t # default declared first\nonetwo : dup 2 = then \" Two\" ,t\nonetwo : dup 1 = then \" One\" ,t\n", "language": "LSE64" }, { "code": "dup 0 = || ,t # avoid printing a null string\n", "language": "LSE64" }, { "code": "--if-then-elseif-then-else\nif a then\n b()\nelseif c then\n d()\nelse\n e()\nend\n\nfor var = start, _end, step do --note: end is a reserved word\n something()\nend\n\nfor var, var2, etc in iteratorfunction do\n something()\nend\n\nwhile somethingistrue() do\n something()\nend\n\nrepeat\n something()\nuntil somethingistrue()\n\ncases = {\nkey1 = dothis,\nkey2 = dothat,\nkey3 = dotheother\n}\n\ncases[key]() --equivalent to dothis(), dothat(), or dotheother() respectively\n", "language": "Lua" }, { "code": "if char == \"<\" then Prepend \"<\" acc else acc\n", "language": "Luna" }, { "code": "class JSON:\n ...\n def asText: case self of:\n JSONString t: t\n other: throw \"JSON.asText: not a text\"\n", "language": "Luna" }, { "code": "Module CheckIt {\n Read a\n If a>1 then {\n Print \"Top\"\n } else.if a>=-4 then {\n Print \"Middle\"\n } else {\n Print \"Bottom\"\n }\n}\nCheckIt 100\nCheckIt 0\nCheckIt -100\n\nModule CheckIt {\n Read a\n \\\\ using end if without blocks\n If a>1 then\n Print \"Top\"\n else.if a>=-4 then\n Print \"Middle\"\n else\n Print \"Bottom\"\n End If\n}\nCheckIt 100\nCheckIt 0\nCheckIt -100\n\nModule CheckIt {\n Read a\n \\\\ without use of END IF in one line\n If a>1 then Print \"Top\" else.if a>=-4 then Print \"Middle\" else Print \"Bottom\"\n}\nCheckIt 100\nCheckIt 0\nCheckIt -100\n", "language": "M2000-Interpreter" }, { "code": "Module Checkit {\n Read x\n Print If(x>100-> 100, x)\n}\nCheckit 30\nCheckit 300\n\n\\\\ we can use more than two expressions, if i is not in range then 0 returned\nModule Checkit {\n Read i,x\n Print If(i-> x*5, x*40, x*500)\n}\nCheckit 1, 20\nCheckit 2, 20\nCheckit 3, 20\n", "language": "M2000-Interpreter" }, { "code": "Module Checkit {\n def a\n Print type$(a)=\"Double\"\n b=(1,2,3,4)\n for i=1 to 3\n a=if(a->, b) ' this happen only one time, where a is a double, second time a is an object\n Print a ' print 3 values\n a++ ' add 1 to each value\n Print type$(a)=\"mArray\"\n Next i\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "Module CheckIt {\n Read a\n Select Case a\n Case >1\n {\n Print \"Top\"\n \\\\ need block if we have more than one line of code\n }\n Case >=-4\n Print \"Middle\"\n Else\n Print \"Bottom\"\n End Select\n}\nCheckIt 100\nCheckIt 0\nCheckIt -100\n\nModule CheckIt {\n Read a\n if a>-500 then\n Select Case a\n Case >1\n {\n Print \"Top\"\n \\\\ need block if we have more than one line of code\n }\n Case >=-4\n Print \"Middle\"\n Else Case \\\\ need ELSE CASE if Select Case is inside a IF END IF (WITHOUT BLOCK)\n Print \"Bottom\"\n End Select\n Else\n Print \"Out of range\"\n End if\n}\nCheckIt 100\nCheckIt 0\nCheckIt -100\nCheckIt -500\n", "language": "M2000-Interpreter" }, { "code": "x=10\nWhile x>0 {\n Print x\n x--\n}\nDo { ' se can use Repeat in place of Do\n x++\n Print x\n} Until x=10\n\n\\\\ without curly braces:\nx=10\nWhile x>0\n Print x\n x--\nEnd While\nDo\n x++\n Print x\nUntil x=10\n", "language": "M2000-Interpreter" }, { "code": "Module CheckIt {\n For i=1 to 10 {\n x=Random(1,2)\n {\n On x Goto alfa, beta\n alfa:\n Print \"ok1\"\n Exit\n beta:\n Print \"ok2\"\n Exit\n }\n Print \"End One\"\n\n x=Random(1,2)\n {\n On x Gosub alfa1, beta1\n Exit\n alfa1:\n Print \"ok1\"\n Return\n beta1:\n Print \"ok2\"\n Return\n }\n Print \"End\"\n }\n}\nCheckIt\n", "language": "M2000-Interpreter" }, { "code": "a$=\"123\"\nif a$ ~ \"12*\" then 1000\nalfa: ' only remarks here\nPrint \"print here, spaghetti code, marvelous\"\nExit\n1000 Print \"ok final\"\nGoto alfa\n", "language": "M2000-Interpreter" }, { "code": "Module Checkit {\n Rem : Dim beta(10) ' remove Rem to get error when call beta() without Gosub\n Rem : Gosub beta() ' remove again Rem and erase next line to use beta() correct\n 'beta()\n sub beta()\n local i\n for i=1 to 10\n alfa(i)\n next i\n end sub\n sub alfa(x)\n goto 100\n Print \"no print\"\n End Sub\n\n 100 Print \"ok this printed\", x\n Return\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "# make -f do.mk C=mycond if\nC=0\n\nif:\n -@expr $(C) >/dev/null && make -f do.mk true; exit 0\n -@expr $(C) >/dev/null || make -f do.mk false; exit 0\n\ntrue:\n @echo \"was true.\"\n\nfalse:\n @echo \"was false.\"\n", "language": "Make" }, { "code": "make -f do.mk if C=0\n> was false.\n\nmake -f do.mk if C=1\n> was true.\n", "language": "Make" }, { "code": "C=0\n\nif: true false\n\ntrue:\n @expr $(C) >/dev/null && exit 0 || exit 1\n @echo \"was true.\"\n\nfalse:\n @expr $(C) >/dev/null && exit 1 || exit 0\n @echo \"was false.\"\n", "language": "Make" }, { "code": "|make -f do.mk -s -k C=1\nwas true.\n*** Error code 1\n|make -f do.mk -s -k C=0\n*** Error code 1\nwas false.\n", "language": "Make" }, { "code": "A=\nB=\n\nifeq \"$(A)\" \"1\"\n B=true\nelse\n B=false\nendif\n\ndo:\n @echo $(A) .. $(B)\n", "language": "Make" }, { "code": "|gmake -f if.mk A=1\n1 .. true\n|gmake -f if.mk A=0\n0 .. false\n", "language": "Make" }, { "code": "if x > 0 then\n res := x;\nelse\n res := -x;\nend if;\n", "language": "Maple" }, { "code": "if x = 0 then\n res := y;\nelif y = 0 then\n res := x;\nelse\n res := sqrt(x^2+y^2);\nend if;\n", "language": "Maple" }, { "code": "if x == 1\n disp 'x==1';\nelseif x > 1\n disp 'x>1';\nelse\n disp 'x<1';\nend\n", "language": "MATLAB" }, { "code": "switch x\n case 1\n disp 'Hello';\n case 2\n disp 'World';\n otherwise\n disp 'Skynet Active';\nend\n", "language": "MATLAB" }, { "code": "if test1 then (...) elseif test2 then (...) else (...);\n", "language": "Maxima" }, { "code": "if x == 1 then\n(\n print \"one\"\n)\nelse if x == 2 then\n(\n print \"two\"\n)\nelse\n(\n print \"Neither one or two\"\n)\n", "language": "MAXScript" }, { "code": "case x of\n(\n 1: (print \"one\")\n 2: (print \"two\")\n default: (print \"Neither one or two\")\n)\n", "language": "MAXScript" }, { "code": "case of\n(\n (x == 1): (print \"one\")\n (x == 2): (print \"two\")\n default: (print \"Neither one or two\")\n)\n", "language": "MAXScript" }, { "code": "INT x;\nx:=0;\nIF x = 1 THEN\n ! Do something\nELSE\n ! Do something else\nENDIF;\n", "language": "MBS" }, { "code": "<COND (<==? .X 1> <PRINC \"one\">)\n (<==? .X 2> <PRINC \"two\">)\n (T <PRINC \"something else\">)>\n", "language": "MDL" }, { "code": ";\"Negate X if its value is less than 0\"\n<AND <L? .X 0> <SET X <- .X>>>\n\n;\"Print a message unless the quiet flag is set\"\n<OR .QUIET? <PRINC \"Finished\">>\n", "language": "MDL" }, { "code": "if conditionA:\n % do something\nelseif conditionB:\n % do something\n% more elseif, if needed...\nelse:\n % do this\nfi;\n", "language": "Metafont" }, { "code": "b := if a > 5: 3 + else: 2 - fi c;\n", "language": "Metafont" }, { "code": "(true) (\"I'm true\") (\"I'm false\") if ; If first quotation evaluates to true,\n ; evaluate second quotation.\n ; Otherwise, evaluate the third.\n\n(true) (\"I'm true\") when ; If without the false quotation.\n(true) (\"I'm false\") unless ; If without the true quotation.\n\n2 ( ; For each quotation inside the case\n ((3 >) (\"Greater than 3\" puts!)) ; quotation, evaluate the second\n ((3 <) (\"Smaller than 3\" puts!)) ; quotation if the first quotation\n ((true) (\"Exactly 3\" puts!)) ; evaluates to true. Otherwise, move\n) case ; on to the next one.\n", "language": "Min" }, { "code": "x = 42\nif x < 10 then\n print \"small\"\nelse if x < 20 then\n print \"small-ish\"\nelse if x > 100 then\n print \"large\"\nelse\n print \"just right\"\nend if\n", "language": "MiniScript" }, { "code": "x = 42\nif x < 50 then print \"small\" else print \"big\"\n", "language": "MiniScript" }, { "code": "isSmall = function(x)\n print \"checking smallness\"\n return x < 40\nend function\n\nisBig = function(x)\n print \"checking bigness\"\n return x > 60\nend function\n\nisSmall(10) or isBig(100)\n", "language": "MiniScript" }, { "code": "BEQ $t0,$t1,Label ;branch to label if $t0 = $t1. If not, fallthrough to the instruction after the delay slot.\nnop ;branch delay slot\n", "language": "MIPS-Assembly" }, { "code": "addu $t0,$t1 ;I'm going to branch based off this addition, but there's other things I want to do first.\nlw $t3,($t4)\nnop ;load delay slot\nBEQ $t0,$t1,Label\nnop ;branch delay slot\n", "language": "MIPS-Assembly" }, { "code": "BNEZ $t0,loop ;branch if $t0 is nonzero.\nsubiu $t0,1 ;this finishes at the same time the jumpback occurs.\n", "language": "MIPS-Assembly" }, { "code": "BGEU $t0,$t1,label ;branch if $t0 >= $t1, treating both as unsigned.\nNOP\nBLT $t7,$t3,label ;branch if $t7 < $t3, treating both as signed\nNOP\n", "language": "MIPS-Assembly" }, { "code": "switchExample:\n;this implementation assumes that all destinations end in jr ra, so you'll need to arrive here with JAL switchExample.\n;$t0 = index (must be a multiple of 4 or the program counter will jump to a location that's not guaranteed to properly return.)\nla cases,$t1\naddiu $t1,$t0 ;MIPS can't do variable indexed offsetting so we have to add the offset ourselves.\nlw $t8,($t1) ;dereference the pointer, $t8 contains the address we wish to \"call\"\nnop\njr $t8 ;jump to the selected destination.\nnop\n\ncases:\n.word foo\n.word bar\n.word baz\n\nfoo:\n;code goes here\njr ra\n\nbar:\n;code goes here\njr ra\n\nbaz:\n;code goes here\njr ra\n", "language": "MIPS-Assembly" }, { "code": "IF i = 1 THEN\n InOut.WriteString('One')\nELSIF i = 2 THEN\n InOut.WriteString('Two')\nELSIF i = 3 THEN\n InOut.WriteString('Three')\nELSE\n InOut.WriteString('Other')\nEND;\n", "language": "Modula-2" }, { "code": "CASE i OF\n 1 : InOut.WriteString('One')\n| 2 : InOut.WriteString('Two')\n| 3 : InOut.WriteString('Three')\nELSE\n InOut.WriteString('Other')\nEND\n", "language": "Modula-2" }, { "code": "IF Foo = TRUE THEN\n Bar();\nELSE\n Baz();\nEND;\n", "language": "Modula-3" }, { "code": "IF Foo = \"foo\" THEN\n Bar();\nELSIF Foo = \"bar\" THEN\n Baz();\nELSIF Foo = \"foobar\" THEN\n Quux();\nELSE\n Zeepf();\nEND;\n", "language": "Modula-3" }, { "code": "CASE Foo OF\n| 1 => IO.Put(\"One\\n\");\n| 2 => IO.Put(\"Two\\n\");\n| 3 => IO.Put(\"Three\\n\");\nELSE\n IO.Put(\"Something\\n\");\nEND;\n", "language": "Modula-3" }, { "code": "TYPECASE ref OF\n| NULL => IO.Put(\"Null\\n\");\n| CHAR => IO.Put(\"Char\\n\");\n| INTEGER => IO.Put(\"Integer\\n\");\nELSE\n IO.Put(\"Something\\n\");\nEND;\n", "language": "Modula-3" }, { "code": "che cosè var? # switch var\n minore di 0: # case var < 0\n ...\n maggiore di 0: # case var > 0\n ...\n o tarapia tapioco: # else (none of the previous cases)\n ...\ne velocità di esecuzione\n", "language": "Monicelli" }, { "code": "if(s == \"Hello World\")\n{\n foo();\n}\nelse if(s == \"Bye World\")\n bar();\nelse\n{\n baz();\n}\n", "language": "Morfa" }, { "code": "if(obj isnt null and obj.foo())\n doSomething();\n", "language": "Morfa" }, { "code": "var t = if(s == \"Hello World\") foo() else bar();\n", "language": "Morfa" }, { "code": "switch (num)\n {\n case (0)\n { /* empty case requires braces */ }\n case (1)\n { var one = \"one\"; result = one; }\n case (2,3) // case may contain a nonempty list of values\n result = \"a few\";\n default\n result = \"a lot\";\n }\n", "language": "Morfa" }, { "code": " IF A list-of-MUMPS-commands\n", "language": "MUMPS" }, { "code": " IF T DO SUBROUTINE\n ELSE DO SOMETHING\n", "language": "MUMPS" }, { "code": " IF T DO SUBROUTINE IF 1\n ELSE DO SOMETHING\n", "language": "MUMPS" }, { "code": " IF T DO\n . DO SUBROUTINE\n ELSE DO SOMETHING\n", "language": "MUMPS" }, { "code": " WRITE $SELECT(1=2:\"Unequal\",1=3:\"More unequal\",1:\"Who cares?\")\n", "language": "MUMPS" }, { "code": " SET:(1=1) SKY=\"Blue\"\n GOTO:ReallyGo LABEL\n QUIT:LoopDone\n WRITE:NotLastInSet \",\"\n", "language": "MUMPS" }, { "code": "if x = 0\n foo()\nelse if x = 1\n bar()\nelse if x = 2\n baz()\nelse\n boz()\nend\n", "language": "Nanoquery" }, { "code": "if (the_answer == 42) FindQuestion() else Foo();\nwhen (stock.price < buy_order) stock.Buy();\nunless (text < \"\") Write(text);\n", "language": "Nemerle" }, { "code": "match(x)\n{\n |1 => \"x is one\"\n |x when (x < 5) => \"x is less than five\"\n |_ => \"x is at least five\"\n}\n", "language": "Nemerle" }, { "code": "-- simple construct\nif logicalCondition then conditionWasTrue()\n else conditionWasFalse()\n\n-- multi-line is ok too\nif logicalCondition\nthen\n conditionWasTrue()\nelse\n conditionWasFalse()\n\n-- using block stuctures\nif logicalCondition then do\n conditionWasTrue()\n ...\n end\nelse do\n conditionWasFalse()\n ...\n end\n\n-- if/else if...\nif logicalCondition1 then do\n condition1WasTrue()\n ...\n end\nelse if logicalCondition2 then do\n condition2WasTrue()\n ...\n end\nelse do\n conditionsWereFalse()\n ...\n end\n", "language": "NetRexx" }, { "code": "-- simple construct\nselect\n when logicalCondition1 then condition1()\n when logicalCondition2 then condition2()\n otherwise conditionDefault()\n end\n\n-- set up a catch block to intercept missing OTHERWISE clause\ndo\n select\n when logicalCondition1 then condition1()\n when logicalCondition2 then condition2()\n end\ncatch ex1 = NoOtherwiseException\n ex1.printStackTrace()\nend\n", "language": "NetRexx" }, { "code": "-- simple construct\nselect case cc\n when 'A' then say 'the case is A'\n when 'B' then say 'the case is B'\n otherwise say 'selection not recognized'\n end\n", "language": "NetRexx" }, { "code": "select\n when cc == 'A' then ...\n when cc == 'B' then ...\n ...\n", "language": "NetRexx" }, { "code": "select label sl protect cc case cc\n when 'A' then do\n say 'the case is A'\n if logicalCondition then leave sl -- just to use the lable\n say '...'\n end\n when 'B' then do\n say 'the case is B'\n say '...'\n end\n otherwise\n say 'selection not recognized'\n say '...'\n catch exs = RuntimeException\n say 'Gronk!'\n exs.printStackTrace()\n finally\n say 'selection done'\n say 'TTFN'\n end sl\n", "language": "NetRexx" }, { "code": "(set 'x 1)\n(if (= x 1) (println \"is 1\"))\n", "language": "NewLISP" }, { "code": "(set 'x 0)\n(if (= x 1) (println \"is 1\") (println \"not 1\"))\n", "language": "NewLISP" }, { "code": "if x == 0:\n foo()\nelif x == 1:\n bar()\nelif x == 2:\n baz()\nelse:\n boz()\n", "language": "Nim" }, { "code": "case x\nof 0:\n foo()\nof 2,5,9:\n baz()\nof 10..20, 40..50:\n baz()\nelse: # All cases must be covered\n boz()\n", "language": "Nim" }, { "code": "a := GetValue();\nif(a < 5) {\n \"less than 5\"->PrintLine();\n}\nelse if(a > 5) {\n \"greater than 5\"->PrintLine();\n}\nelse {\n \"equal to 5\"->PrintLine();\n};\n", "language": "Objeck" }, { "code": "a := GetValue();\nselect(a) {\n label 5: {\n \"equal to 5\"->PrintLine();\n }\n\n label 7: {\n \"equal to 7\"->PrintLine();\n }\n\n other: {\n \"another value\"->PrintLine();\n }\n};\n", "language": "Objeck" }, { "code": "let condition = true\n\nif condition then\n 1 (* evaluate something *)\nelse\n 2 (* evaluate something *)\n", "language": "OCaml" }, { "code": "if condition then begin\n (); (* evaluate things for side effects *)\n 5\nend\nelse begin\n (); (* evaluate things for side effects *)\n 42\nend\n", "language": "OCaml" }, { "code": "match expression with\n| 0 -> () (* evaluate something *)\n| 1 -> () (* evaluate something *)\n| n when n mod 2 = 0 -> () (* evaluate something *)\n| _ -> () (* evaluate something *)\n", "language": "OCaml" }, { "code": "if (condition)\n % body\nendif\n\nif (condition)\n % body\nelse\n % otherwise body\nendif\n\nif (condition1)\n % body\nelseif (condition2)\n % body 2\nelse\n % otherwise body\nendif\n", "language": "Octave" }, { "code": "switch( expression )\n case label1\n % code for label1\n case label2\n % code for label2\n otherwise\n % none of the previous\nendswitch\n", "language": "Octave" }, { "code": "switch ( x )\n case 1\n disp(\"it is 1\");\n case { 5,6,7 }\n disp(\"it is 5, or 6 or 7\");\n otherwise\n disp(\"unknown!\");\nendswitch\n", "language": "Octave" }, { "code": "aBoolean ifTrue: [ ...]\naBoolean ifFalse: [ ... ]\naObject ifNull: [ ... ]\naObject ifNotNull: [ ... ]\naObject ifZero: [ ... ]\n", "language": "Oforth" }, { "code": "else: [ ... ]\n", "language": "Oforth" }, { "code": "Number virtual: sgn\n self isPositive\n ifTrue: [ self ==0 ifTrue: [ 0 ] else: [ 1 ] ]\n else: [ -1 ] ;\n", "language": "Oforth" }, { "code": "(if (= (* 2 2) 4)\n (print \"if-then: equal\"))\n(if (= (* 2 2) 6)\n (print \"if-then: should not be printed\"))\n; ==> if-then: equal\n", "language": "Ol" }, { "code": "(if (= (* 2 2) 4)\n (print \"if-then-else: equal\")\n (print \"if-then-else: non equal\"))\n; ==> if-then-else: equal\n\n(if (= (* 2 2) 6)\n (print \"if-then-else: equal\")\n (print \"if-then-else: non equal\"))\n; ==> if-then-else: non equal\n", "language": "Ol" }, { "code": "(when (= (* 2 2) 4)\n (print \"when: ..just do something..\")\n (print \"when: equal\"))\n; ==> when: ..just do something..\n; ==> when: equal\n\n(unless (= (* 2 2) 6)\n (print \"unless: ..just do something..\")\n (print \"unless: not equal\"))\n; ==> unless: ..just do something..\n; ==> unless: not equal\n", "language": "Ol" }, { "code": "(if (= (* 2 2) 4)\n (print \"if-then-else*: equal\")\nelse\n (print \"if-then-else*: ..just do something..\")\n (print \"if-then-else*: non equal\"))\n; ==> if-then-else*: equal\n\n(if (= (* 2 2) 4)\nthen\n (print \"if-then-else*: ..just do something..\")\n (print \"if-then-else*: equal\")\nelse\n (print \"if-then-else*: ..just do something..\")\n (print \"if-then-else*: non equal\"))\n; ==> if-then-else*: ..just do something..\n; ==> if-then-else*: equal\n\n(if (= (* 2 2) 4) ; same as `when`\nthen\n (print \"if-then-else*: ..just do something..\")\n (print \"if-then-else*: equal\"))\n; ==> if-then-else*: ..just do something..\n; ==> if-then-else*: equal\n", "language": "Ol" }, { "code": "(case (* 2 2)\n (3 ; exact number\n (print \"case: 3\"))\n (4 ; exact number\n (print \"case: 4\"))\n ((5 6 7) ; list of numbers\n (print \"case: 5 or 6 or 7\"))\n (else\n (print \"case: i don't know\")))\n; ==> case: 4\n\n; extended case with usable else\n(case (* 2 2)\n (3 ; exact number\n (print \"case: 3\"))\n (else => (lambda (num)\n (print \"case: real value is \" num))))\n; ==> case: real value is 4\n\n(case (* 2 2)\n (3 ; exact number\n (print \"case: 3\"))\n (else is num\n (print \"case: real value is \" num)))\n; ==> case: real value is 4\n\n; extended case with vectors\n(case ['selector 1 2 3]\n (['case1 x y]\n (print \"case: case1 \" x \", \" y))\n (['selector x y z]\n (print \"case: selector \" x \", \" y \", \" z))\n (else\n (print \"case: i don't know\")))\n; ==> case: selector 1, 2, 3\n", "language": "Ol" }, { "code": "(cond\n ((= (* 2 2) 4)\n (print \"cond: equal\"))\n ((= (* 2 2) 6)\n (print \"cond: not equal\"))\n (else\n (print \"cond: i don't know\")))\n; ==> cond: equal\n", "language": "Ol" }, { "code": "(define smart (case-lambda\n ((x)\n (print x \", -, -\"))\n ((x y)\n (print x \", \" y \", -\"))\n ((x y z)\n (print x \", \" y \", \" z))))\n(smart 1) ; ==> 1, -, -\n(smart 1 2) ; ==> 1, 2, -\n(smart 1 2 3) ; ==> 1, 2, 3\n", "language": "Ol" }, { "code": "if arg~isa(.string) & arg~left(1) == \"*\" then call processArg arg\n", "language": "OoRexx" }, { "code": "if arg~isa(.string), arg~left(1) == \"*\" then call processArg arg\n", "language": "OoRexx" }, { "code": "if y then x=6 /* Y must be either 0 or 1 */\n\n\nif t**2>u then x=y\n else x=-y\n\n\n\nif t**2>u then do j=1 to 10; say prime(j); end\n else x=-y\n\n\n\nif z>w+4 then do\n z=abs(z)\n say 'z='z\n end\n else do; z=0; say 'failed.'; end\n\n\n\nif x>y & c*d<sqrt(pz) |,\n substr(abc,4,1)=='@' then if z=0 then call punt\n else nop\n else if z<0 then z=-y\n", "language": "OoRexx" }, { "code": " /*the WHEN conditional operators are the same as */\n /*the IF conditional operators. */\n\n select\n when t<0 then z=abs(u)\n when t=0 & y=0 then z=0\n when t>0 then do\n y=sqrt(z)\n z=u**2\n end\n\n /*if control reaches this point and none of the WHENs */\n /*were satisfiied, a SYNTAX condition is raised (error).*/\n end\n", "language": "OoRexx" }, { "code": " select\n when a=='angel' then many='host'\n when a=='ass' | a=='donkey' then many='pace'\n when a=='crocodile' then many='bask'\n when a=='crow' then many='murder'\n when a=='lark' then many='ascension'\n when a=='quail' then many='bevy'\n when a=='wolf' then many='pack'\n otherwise say\n say '*** error! ***'\n say a \"isn't one of the known thingys.\"\n say\n exit 13\n end\n", "language": "OoRexx" }, { "code": "if a then b=c else b=d\n\nif a=0\n b=c\nelseif a<0\n b=d\nelse\n b=e\nend if\n\nselect case a\n case 'A'\n v=21\ncase 'B'\n v=22\ncase 1 to 64\n v=a+300\ncase else\n v=0\nend select\n", "language": "OxygenBasic" }, { "code": "proc {PrintParity X}\n if {IsEven X} then\n {Show even}\n elseif {IsOdd X} then\n {Show odd}\n else\n {Show 'should not happen'}\n end\nend\n", "language": "Oz" }, { "code": "fun {Max X Y}\n if X > Y then X else Y end\nend\n", "language": "Oz" }, { "code": "fun {Fac X}\n case X of 0 then 1\n [] _ then X * {Fac X-1}\n end\nend\n", "language": "Oz" }, { "code": "if(condition, do_if_true, do_if_false)\n", "language": "PARI-GP" }, { "code": "IF condition1 THEN\n procedure1\nELSE\n procedure3;\n\nIF condition1 THEN\n BEGIN\n procedure1;\n procedure2\n END\nELSE\n procedure3;\n\nIF condition1 THEN\n BEGIN\n procedure1;\n procedure2\n END\nELSE\n BEGIN\n procedure3;\n procedure4\n END;\n", "language": "Pascal" }, { "code": "case i of\n 1,4,9: { executed if i is 1, 4 or 9 }\n DoSomething;\n 11, 13 .. 17: { executed if i is 11, 13, 14, 15, 16 or 17 }\n DoSomethingElse;\n 42: { executed only if i is 42 }\n DoSomeOtherThing;\n else\n DoYetAnotherThing;\nend;\n", "language": "Pascal" }, { "code": "Case X of\n 'A' : statement ;\n 'B' : statement ;\n in ['C'..'W'] : statement ;\nelse\n Statement ;\nend;\n", "language": "Pascal" }, { "code": "if ($expression) {\n do_something;\n}\n", "language": "Perl" }, { "code": "# postfix conditional\ndo_something if $expression;\n", "language": "Perl" }, { "code": "if ($expression) {\n do_something;\n}\nelse {\n do_fallback;\n}\n", "language": "Perl" }, { "code": "if ($expression1) {\n do_something;\n}\nelsif ($expression2) {\n do_something_different;\n}\nelse {\n do_fallback;\n}\n", "language": "Perl" }, { "code": "$variable = $expression ? $value_for_true : $value_for_false;\n", "language": "Perl" }, { "code": "$condition and do_something; # equivalent to $condition ? do_something : $condition\n", "language": "Perl" }, { "code": "$condition or do_something; # equivalent to $condition ? $condition : do_something\n", "language": "Perl" }, { "code": "use feature \"switch\";\ngiven ($input) {\n when (0) { print 'input == 0'; }\n when ('coffee') { print 'input equal coffee'; }\n when ([1..9]) { print 'input between 1 and 9'; }\n when (/rats/) { print 'input matches rats'; }\n default { do_fallback; }\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">name</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">\"Pete\"</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000080;font-style:italic;\">-- do something</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">age</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">50</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000080;font-style:italic;\">-- do something</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">age</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">20</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000080;font-style:italic;\">-- do something</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000080;font-style:italic;\">-- do something</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n<!--\n", "language": "Phix" }, { "code": "-->\n <span style=\"color: #000000;\">somevar</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">flag<span style=\"color: #0000FF;\">?<span style=\"color: #000000;\">true_expr<span style=\"color: #0000FF;\">:<span style=\"color: #000000;\">false_expr<span style=\"color: #0000FF;\">)\n<!--\n", "language": "Phix" }, { "code": "-->\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">DEBUG<span style=\"color: #0000FF;\">=<span style=\"color: #004600;\">false</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">DEBUG</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">puts<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">1<span style=\"color: #0000FF;\">,<span style=\"color: #008000;\">\"debug is on\\n\"<span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform<span style=\"color: #0000FF;\">(<span style=\"color: #0000FF;\">)<span style=\"color: #0000FF;\">=<span style=\"color: #000000;\">WINDOWS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">puts<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">1<span style=\"color: #0000FF;\">,<span style=\"color: #008000;\">\"this is windows\\n\"<span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #7060A8;\">platform<span style=\"color: #0000FF;\">(<span style=\"color: #0000FF;\">)<span style=\"color: #0000FF;\">=<span style=\"color: #000000;\">LINUX</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">puts<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">1<span style=\"color: #0000FF;\">,<span style=\"color: #008000;\">\"this is linux\\n\"<span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if\n<!--\n", "language": "Phix" }, { "code": "-->\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">v</span> <span style=\"color: #000080;font-style:italic;\">/*with fallthrough*/</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">1<span style=\"color: #0000FF;\">,<span style=\"color: #000000;\">2<span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000080;font-style:italic;\">-- do something</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000080;font-style:italic;\">-- do something</span>\n <span style=\"color: #008080;\">fallthrough</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">4<span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000080;font-style:italic;\">-- do something</span>\n <span style=\"color: #008080;\">break</span>\n <span style=\"color: #008080;\">default<span style=\"color: #0000FF;\">:</span>\n <span style=\"color: #000080;font-style:italic;\">-- do something</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch\n<!--\n", "language": "Phix" }, { "code": "without js -- (but maybe, at some point, and obviously that is as custom verbatim JavaScript code instead of assembly code)\n#ilASM{\n [32]\n mov eax,[var]\n [64]\n mov rax,[var]\n [PE32]\n push eax -- uExitCode\n call \"kernel32.dll\",\"ExitProcess\"\n [PE64]\n mov rcx,rax -- uExitCode\n call \"kernel32.dll\",\"ExitProcess\"\n [ELF32]\n mov ebx,eax -- error_code (p1)\n mov eax,1 -- sys_exit(ebx=int error_code)\n int 0x80\n-- xor ebx,ebx -- (common requirement after int 0x80)\n [ELF64]\n mov rdi,rax -- error_code (p1)\n mov rax,60 -- sys_exit(rdi=int error_code)\n syscall\n []\n }\n", "language": "Phix" }, { "code": "var a = 5;\nif (a == 5) {\n doSomething();\n} else if (a > 0) {\n doSomethingElse();\n} else {\n error();\n}\n", "language": "PHL" }, { "code": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n //do something\n\nif ($foo == 3)\n //do something\nelse\n //do something else\n\nif ($foo != 0)\n{\n //do something\n}\nelse\n{\n //do another thing\n}\n\n?>\n", "language": "PHP" }, { "code": "<?php\n\nswitch ($i)\n{\n case \"apple\":\n echo \"i is apple\";\n break;\n\n case \"bar\":\n echo \"i is bar\";\n break;\n\n case \"cake\":\n echo \"i is cake\";\n break;\n}\n\n?>\n", "language": "PHP" }, { "code": "go =>\n N = 10,\n\n % \"direct\" test that will fail if not satisfied\n N < 14,\n\n % if/then/elseif/else\n if N < 14 then\n println(\"less than 14\")\n elseif N == 14 then\n println(\"is 14\")\n else\n println(\"not less than 14\")\n end,\n\n % From Prolog: (condition -> then ; else)\n ( N < 14 ->\n println(\"less than 14\")\n ;\n println(\"not less than 14\")\n ),\n\n % Ret = cond(condition, then, else)\n println(cond(N < 14, \"less than 14\", \"not less than 14\")),\n\n % as a predicate\n test_pred(N),\n\n % as condition in a function's head\n println(test_func(N)),\n\n println(ok), % all tests are ok\n\n nl.\n\n% as a predicate\ntest_pred(N) ?=>\n N < 14,\n println(\"less than 14\").\ntest_pred(N) =>\n N >= 14,\n println(\"not less than 14\").\n\n% condition in function head\ntest_func(N) = \"less than 14\", N < 14 => true.\ntest_func(_N) = \"not less than 14\" => true.\n", "language": "Picat" }, { "code": "(if (condition) # If the condition evaluates to non-NIL\n (then-do-this) # Then execute the following expression\n (else-do-that) # Else execute all other expressions\n (and-more) )\n\n(ifn (condition) # If the condition evaluates to NIL\n (then-do-this) # Then execute the following expression\n (else-do-that) # Else execute all other expressions\n (and-more) )\n", "language": "PicoLisp" }, { "code": "(when (condition) # If the condition evaluates to non-NIL\n (then-do-this) # Then execute tall following expressions\n (and-more) )\n\n(unless (condition) # If the condition evaluates to NIL\n (then-do-this) # Then execute all following expressions\n (and-more) )\n", "language": "PicoLisp" }, { "code": "(if2 (condition1) (condition2) # If both conditions evaluate to non-NIL\n (expression-both) # Then execute this expression\n (expression-first) # Otherwise this for the first\n (expression-second) # or this the second condition.\n (expression-none) # If both are NIL, all following expressions\n (and-more) )\n", "language": "PicoLisp" }, { "code": "(cond\n ((condition1) # If this condition evaluates to non-NIL\n (expression 1) # Execute these expression(s)\n (more 1) )\n ((condition2) # Otherwise, if this evaluates to non-NIL\n (expression 2) # Execute these expression(s)\n (more 2) )\n (T # If none evaluated to non-NIL\n (expression 1) # Execute these expression(s)\n (more 1) )\n\n(nond\n ((condition1) # If this condition evaluates to NIL\n (expression 1) # Execute these expression(s)\n (more 1) )\n ((condition2) # Otherwise, if this evaluates to NIL\n (expression 2) # Execute these expression(s)\n (more 2) )\n (NIL # If none evaluated to NIL\n (expression 1) # Execute these expression(s)\n (more 1) )\n", "language": "PicoLisp" }, { "code": "(case (expression) # Evaluate the expression\n (value1 # If it is equal to, or member of, 'value1'\n (do-this1) # Execute these expression(s)\n (do-that1) )\n (value2 # Else if it is equal to, or member of, 'value2\n (do-this2) # Execute these expression(s)\n (do-that2) )\n (T # Else execute final expression(s)\n (do-something-else) ) )\n", "language": "PicoLisp" }, { "code": "if condition_exp then unique_statement; else unique_statement;\n\nif condition_exp then\n unique_statement;\nelse\n unique_statement;\n\nif condition_exp\nthen do;\n list_of_statements;\nend;\nelse do;\n list_of_statements;\nend;\n", "language": "PL-I" }, { "code": "if condition_exp1 then\n statement_1;\nelse if condition_exp2 then\n statement_2;\nelse if condition_expN then\n statement_N;\nelse\n statement_E;\n\nif condition_exp1 then do;\n list_of_statements;\nend;\nelse if condition_exp2 then do;\n list_of_statements;\nend;\nelse if condition_expN then do;\n list_of_statements;\nend;\nelse do;\n list_of_statements;\nend;\n", "language": "PL-I" }, { "code": "select (i); /* select on value of variable */\n when (1,4,9)\n do;\n statement_s;\n end;\n\n when (11, 42)\n do;\n statement_s;\n end;\n\n other /* everything else */\n do;\n statement_s;\n end;\nend;\n", "language": "PL-I" }, { "code": "select; /* select first matching condition */\n when (i = 4)\n do;\n statement_s;\n end;\n\n when (this = that)\n do;\n statement_s;\n end;\n\n when (mystring = 'ABCDE')\n do;\n statement_s;\n end;\n\n other\n do;\n statement_s;\n end;\nend;\n", "language": "PL-I" }, { "code": "/* IF-THEN-ELSE - THE ELSE STATEMENT; PART IS OPTIONAL */\nIF COND THEN STATEMENT1; ELSE STATEMENT2;\n\n/* CAN BE CHAINED - THE ELSE STATEMENTX; PART IS STILL OPTIONAL */\nIF COND1 THEN STATEMENT1;\nELSE IF CONB2 THEN STATEMENT2;\nELSE IF CONB3 THEN STATEMENT3;\nELSE STATEMENTX;\n", "language": "PL-M" }, { "code": "/* CASE STATEMENT - EXECUTES STATEMENT0, STATEMENT1, ETC. */\n/* DEPENDING ON WHETHER EXPR EVALUATES TO 0, 1, ... */\n/* EXPR MUST BE IN RANGE OR THE PROGRAM WILL JUMP TO HYPERSPACE */\nDO CASE EXPR;\n STATEMENT0;\n STATEMENT1;\n ...\nEND;\n", "language": "PL-M" }, { "code": "If [a decider], [do something]; [do another thing].\n", "language": "Plain-English" }, { "code": "if condition then\n ;;; Action\nendif;\n", "language": "Pop11" }, { "code": "#_IF condition1\n/* Variant 1 */\n#_ELSEIF condition2\n/* Variant 2 */\n#_ELSE\n/* Variant 3 */\n#_ENDIF\n", "language": "Pop11" }, { "code": "if condition then\n ;;; Action1\nelse\n ;;; Alternative action\nendif;\n", "language": "Pop11" }, { "code": "if condition1 then\n ;;; Action1\nelseif condition2 then\n ;;; Action1\nelseif condition2 then\n ;;; Action2\nelseif condition3 then\n ;;; Action3\nelse\n ;;; Alternative action\nendif;\n", "language": "Pop11" }, { "code": "unless condition then /* Action */ endunless;\n", "language": "Pop11" }, { "code": "if not(condition) then /* Action */ endif;\n", "language": "Pop11" }, { "code": "if condition1 then\n ;;; Action1\nelseunless condition2 then\n ;;; Action2\nendif;\n ;;; Action2\nendif;\n", "language": "Pop11" }, { "code": "if condition1 then\n ;;; Action1\nelseif not(condition2) then\n ;;; Action2\nendif;\n", "language": "Pop11" }, { "code": "if x > 0 then 1 elseif x < 0 then -1 else 0 endif -> sign_x ;\n", "language": "Pop11" }, { "code": "switchon(x)\n case .isstring then printf('A1');\n notcase .isinteger then printf('A2');\n case = 2 orcase = 3 then printf('A3');\n case > 4 andcase < 15 then printf('A4');\n else printf('A5');\nendswitchon;\n", "language": "Pop11" }, { "code": "9 10 lt {(9 is less than 10) show} if\n", "language": "PostScript" }, { "code": "/a 5 lt {(yeah)} {(nope)} ifelse show\n", "language": "PostScript" }, { "code": "# standard if\nif (condition) {\n # ...\n}\n\n# if-then-else\nif (condition) {\n # ...\n} else {\n # ...\n}\n\n# if-then-elseif-else\nif (condition) {\n # ...\n} elseif (condition2) {\n # ...\n} else {\n # ...\n}\n", "language": "PowerShell" }, { "code": "# standard switch\nswitch ($var) {\n 1 { \"Value was 1\" }\n 2 { \"Value was 2\" }\n default { \"Value was something else\" }\n}\n\n# switch with wildcard matching\nswitch -Wildcard ($var) {\n \"a*\" { \"Started with a\" }\n \"*x\" { \"Ended with x\" }\n}\n\n# switch with regular expression matching\nswitch -Regex ($var) {\n \"[aeiou]\" { \"Contained a consonant\" }\n \"(.)\\1\" { \"Contained a character twice in a row\" }\n}\n\n# switch allows for scriptblocks too\nswitch ($var) {\n { $_ % 2 -eq 0 } { \"Number was even\" }\n { $_ -gt 100 } { \"Number was greater than 100\" }\n}\n\n# switch allows for handling a file\nswitch -Regex -File somefile.txt {\n \"\\d+\" { \"Line started with a number\" }\n \"\\s+\" { \"Line started with whitespace\" }\n}\n", "language": "PowerShell" }, { "code": "go :- write('Hello, World!'), nl.\n", "language": "Prolog" }, { "code": "fact(foo).\nfact(bar).\nfact(baz).\n\ngo :- fact(booger).\ngo :- fact(bar).\n", "language": "Prolog" }, { "code": "fact(X) :-\n ( X = foo\n ; X = bar\n ; X = baz ).\n\ngo :-\n ( fact(booger)\n ; fact(bar) ).\n", "language": "Prolog" }, { "code": "fact(X) :-\n ( X = bar -> write('You got me!'), nl\n ; write(X), write(' is not right!'), nl, fail ).\n\ngo :-\n ( fact(booger)\n ; fact(bar) ).\n", "language": "Prolog" }, { "code": "If a = 0\n Debug \"a = 0\"\n\nElseIf a > 0\n Debug \"a > 0\"\n\nElse\n Debug \"a < 0\"\n\nEndIf\n", "language": "PureBasic" }, { "code": "Variable = 2\n\nSelect Variable\n Case 0\n Debug \"Variable = 0\"\n\n Case 10, 11, 99\n Debug \"Variable is 10, 11 or 99\"\n\n Case 20 To 30\n Debug \"Variable >= 20 And Variable <= 30\"\n\n Default\n Debug \"Variable = something else...\"\nEndSelect\n", "language": "PureBasic" }, { "code": "CompilerIf #PB_Compiler_OS = #PB_OS_Linux And #PB_Compiler_Processor = #PB_Processor_x86\n Debug \"Compiled on x86 Linux\"\nCompilerElse\n Debug \"Compiled on something else\"\nCompilerEndIf\n", "language": "PureBasic" }, { "code": "CompilerSelect #PB_Compiler_OS\n CompilerCase #PB_OS_Linux\n Debug \"Compiled on Linux\"\n CompilerCase #PB_OS_Windows\n Debug \"Compiled on Windows\"\n CompilerCase #PB_OS_MacOS\n Debug \"Compiled on Mac OS\"\n CompilerDefault\n Debug \"Compiled on something else\"\nCompilerEndIf\n", "language": "PureBasic" }, { "code": "if x == 0:\n foo()\nelif x == 1:\n bar()\nelif x == 2:\n baz()\nelse:\n boz()\n", "language": "Python" }, { "code": "true_value if condition else false_value\n", "language": "Python" }, { "code": ">>> secret='foo'\n>>> print 'got it' if secret=='foo' else 'try again'\n'got it'\n", "language": "Python" }, { "code": ">>> secret = 'foo'\n>>> result = 'got it' if secret=='foo' else 'try again'\n>>> print result\n'got it'\n", "language": "Python" }, { "code": "dispatcher = dict()\ndispatcher[0]=foo # Not foo(): we bind the dictionary entry to the function's object,\n # NOT to the results returned by an invocation of the function\ndispatcher[1]=bar\ndispatcher[2]=baz # foo,bar, baz, and boz are defined functions.\n\n# Then later\nresults = dispatcher.get(x, boz)() # binding results to a name is optional\n# or with no \"default\" case:\nif x in dispatcher:\n results=dispatcher[x]()\n", "language": "Python" }, { "code": "# The above, but with a dict literal\ndispatcher = {\n 0: foo,\n 1: bar,\n 2: baz,\n}\n# ...\nresults = dispatcher.get(x, boz)()\n", "language": "Python" }, { "code": "# Or without the temp variable\n# (it's up to the reader to decide how \"pythonic\" this is or isn't)\nresults = {\n 0: foo,\n 1: bar,\n 2: baz,\n}.get(x, boz)()\n", "language": "Python" }, { "code": "Print \"QB64/Qbasic conditional structures\"\nDim k As String\nMenu 1\nView Print 13 To 23\nPrint \"A menu example using the many options of IF statement\"\nk = \" \"\n12: While k <> \"\"\n k = UCase$(Input$(1))\n If k = \"O\" GoTo O\n If k = \"F\" Then 22\n If k = \"S\" Then GoSub S: GoTo 12\n If k = \"C\" Then GoSub 4: GoTo 12\n If k = \"E\" Then GoSub 5: Exit While\nWend\nCls\nPrint \"the same menu example with Select Case\"\nSleep 2\nWhile k <> \"\"\n k = UCase$(Input$(1))\n\n Select Case k\n Case \"O\"\n Print \"You choose O\"\n Case \"F\"\n Print \"You choose F\"\n Case \"S\"\n Print \"You choose S\"\n Case \"C\"\n Print \"You choose C\"\n Case \"E\"\n Print \"You choose Exit\"\n _Delay 1\n Exit While\n Case Else\n Print \"Wrong choice\"\n End Select\nWend\nView Print\nCls\nMenu 2\nView Print 13 To 23\nPrint \"menu demonstration using ON value GOTO\"\nk = \" \"\nWhile k <> \"\"\n k = Input$(1)\n On Val(k) GOSUB 1, 2, 3, 4, 5\nWend\nEnd\n\n1:\nPrint \"Chosen O\"\nReturn\n\n2:\nPrint \"Chosen F\"\nReturn\n\n3:\nPrint \"Chosen S\"\nReturn\n\n4:\nPrint \"Chosen C\"\nReturn\n\n5:\nPrint \"Chosen E\"\nIf k = \"5\" Then End\nReturn\n\n\nO:\nPrint \"You choose O\"\nGoTo 12\n\n22:\nPrint \"You choose F\"\nGoTo 12\n\nS:\nPrint \"You choose S\"\nReturn\n\n\n\nSub Menu (Kind As Integer)\n Locate 7, 33: Color 3, 4\n Print \"Choose the item\"\n Color 7, 0\n Locate , 33\n If Kind = 1 Then Print \"Open a file\"; Else Print \"1) Open a file\";\n Color 14, 1\n Locate , 33\n If Kind = 1 Then Print \"O\" Else Print \"1\"\n Color 7, 0\n\n Locate , 33\n If Kind = 1 Then Print \"Find a file\"; Else Print \"2) Find a file\";\n Color 14, 1\n Locate , 33\n If Kind = 1 Then Print \"F\" Else Print \"2\"\n Color 7, 0\n\n Locate , 33\n If Kind = 1 Then Print \"Scan a file\"; Else Print \"3) Scan a file\";\n Color 14, 1\n Locate , 33\n If Kind = 1 Then Print \"S\" Else Print \"3\"\n Color 7, 0\n\n Locate , 33\n If Kind = 1 Then Print \"Copy a file\"; Else Print \"4) Copy a file\";\n Color 14, 1\n Locate , 33\n If Kind = 1 Then Print \"C\" Else Print \"4\"\n Color 7, 0\n\n Locate , 33\n If Kind = 1 Then Print \"Exit from Menu\"; Else Print \"5) Exit from Menu\";\n Color 14, 1\n Locate , 33\n If Kind = 1 Then Print \"E\" Else Print \"5\"\n Color 7, 0\n\nEnd Sub\n", "language": "QB64" }, { "code": "x <- 0\nif(x == 0) print(\"foo\")\nx <- 1\nif(x == 0) print(\"foo\")\nif(x == 0) print(\"foo\") else print(\"bar\")\n", "language": "R" }, { "code": "x <- 2\nswitch(x, print(\"Print if x == 1\"), print(\"Print if x == 2\"))\n", "language": "R" }, { "code": "x <- 3\nswitch(x, print(\"Print if x == 1\"), print(\"Print if x == 2\"))\nx <- 2.7\nswitch(x, print(\"Print if x == 1\"), print(\"Print if x == 2 or if there is rounding to 2\"))\n", "language": "R" }, { "code": "x <- \"match\"\nswitch(x, mat = 0, match = 10, other = 100, 1000)\nx <- \"ma\"\nswitch(x, mat = 0, match = 10, other = 100, 1000)\nx <- \"foo\"\nswitch(x, mat = 0, match = 10, other = 100, 1000)\n", "language": "R" }, { "code": "data <- c(1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0)\nifelse(data == 1, \"Yes\", \"No\")\n", "language": "R" }, { "code": "(if (< x 10)\n \"small\"\n \"big\")\n", "language": "Racket" }, { "code": "(when (< x 10)\n (define y (* x 10))\n (printf \"small\\n\"))\n", "language": "Racket" }, { "code": "(printf \"x is ~a\\n\"\n (cond [(< x 1) \"tiny\"]\n [(< x 10) \"small\"]\n [(< x 100) \"medium\"]\n [(< x 10000) \"big\"]\n [(< x 100000000) \"huge\"]\n [else \"gigantic\"]))\n", "language": "Racket" }, { "code": "(case x\n [(1) \"one\"]\n [(2) \"two\"]\n [(3) \"three\"]\n [(4) \"four\"]\n [(6 8) \"even\"]\n [(5 7 9) \"odd\"]\n [else \"something else\"])\n", "language": "Racket" }, { "code": "if won() -> $prize {\n say \"You won $prize.\";\n}\n", "language": "Raku" }, { "code": "given lc prompt(\"Done? \") {\n when 'yes' { return }\n when 'no' { next }\n default { say \"Please answer either yes or no.\" }\n}\n", "language": "Raku" }, { "code": "$expression ?? do_something !! do_fallback\n", "language": "Raku" }, { "code": ">> if 10 > 2 [print \"ten is bigger\"]\nten is bigger\n", "language": "Red" }, { "code": ">> either 3 > 2 [print \"Three larger\"][print \"Nope!\"]\nThree larger\n", "language": "Red" }, { "code": "n: 50\ncase [\n n < 10 [print \"small number\"]\n n < 100 [print \"medium number\"]\n n < 1000 [print \"large number\"]\n true [print \"none of these\"]\n]\n\nmedium number\n\n;CASE/ALL Prints all that are true\nn: 50\ncase/all [\n n < 10 [print \"small number\"]\n n < 100 [print \"medium number\"]\n n < 1000 [print \"large number\"]\n true [print \"none of these\"]\n]\n\nmedium number\nlarge number\nnone of these\n", "language": "Red" }, { "code": "switch \"india\" [\n \"a\" [print \"string\"]\n 23 [print \"integer\"]\n \"India\" [print \"The country India\"]\n]\n\nThe country India\n\nswitch/default \"U.S.\" [\n \"a\" [print \"string\"]\n 23 [print \"integer\"]\n \"India\" [print \"The country India\"]\n][\nprint \"no match\"\n]\n\nno match\n", "language": "Red" }, { "code": "condition [ true statements ] if\ncondition [ false statements ] -if\ncondition [ true statements ] [ false statements ] choose\n", "language": "Retro" }, { "code": ":foo (n-)\n #1 [ ( if quote evaluates to true ) ] case\n #2 [ ( if quote evaluates to true ) ] case\n #3 [ ( if quote evaluates to true ) ] case\n drop ( default action ) ;\n", "language": "Retro" }, { "code": "if y then @=6 /* Y must be either 0 or 1 */\n\nif t**2>u then x=y /*simple IF with THEN & ELSE. */\n else x=-y\n\nif t**2>u then do j=1 for 10; say prime(j); end /*THEN DO loop.*/\n else x=-y /*simple ELSE. */\n\nif z>w+4 then do /*THEN DO group.*/\n z=abs(z)\n say 'z='z\n end\n else do; z=0; say 'failed.'; end /*ELSE DO group.*/\n\nif x>y & c*d<sqrt(pz) |, /*this statement is continued [,]*/\n substr(abc,4,1)=='~' then if z=0 then call punt\n else nop /*NOP pairs up IF*/\n else if z<0 then z=-y /*alignment helps*/\n", "language": "REXX" }, { "code": " /*the WHEN conditional operators are the same as*/\n /*the IF conditional operators. */\n select\n when t<0 then z=abs(u)\n when t=0 & y=0 then z=0\n when t>0 then do\n y=sqrt(z)\n z=u**2\n end\n\n /*if control reaches here & none of the WHENs were*/\n /*satisfiied, a SYNTAX (error) condition is raised*/\n end /*1st select*/\n\n select\n when a=='angel' then many='host'\n when a=='ass' | a=='donkey' then many='pace'\n when a=='crocodile' then many='bask'\n when a=='crow' then many='murder'\n when a=='lark' then many='ascension'\n when a=='quail' then many='bevy'\n when a=='wolf' then many='pack'\n otherwise many='?'\n end /*2nd select*/ /* [↑] uses OTHERWISE as a catch-all.*/\n", "language": "REXX" }, { "code": " select\n when g=='angel' then many='host'\n when g=='ass' | g=='donkey' then many='pace'\n when g=='crocodile' then many='bask'\n when g=='crow' then many='murder'\n when g=='lark' then many='ascension'\n when g=='quail' then many='bevy'\n when g=='wolf' then many='pack'\n otherwise say\n say '*** error! ***'\n say g \"isn't one of the known thingys.\"\n say\n exit 13\n end /*select*/\n", "language": "REXX" }, { "code": "If[cond]\n|:\n Do Something[]\n:||:\n Do Something Else[]\n:|\n", "language": "Rhope" }, { "code": "If x == 1\n SomeFunc1()\nBut x == 2\n SomeFunc2()\nElse\n SomeFunc()\nOk\n", "language": "Ring" }, { "code": "Switch x\nOn 1\n SomeFunc1()\nOn 2\n SomeFunc2()\nOther\n SomeFunc()\nOff\n", "language": "Ring" }, { "code": "if (x==1)\n{\n // do something\n}\n", "language": "RLaB" }, { "code": "if (x==1)\n{\n // do something if x is 1\n y = const.pi;\nelse\n // do something if x is not 1\n y = sin(const.pi*(1-x)) / (1-x);\n}\n", "language": "RLaB" }, { "code": "if (x==1)\n{\n // do something if x is 1\n y = const.pi;\nelse if (x == 2)\n{\n // do something if x is 2\n y = sin(const.pi*(1-x)) / (1-x);\nelse\n // do something in all the other cases\n y = rand();\n}}\n", "language": "RLaB" }, { "code": "' Boolean Evaluations\n'\n' > Greater Than\n' < Less Than\n' >= Greater Than Or Equal To\n' <= Less Than Or Equal To\n' = Equal to\n\nx = 0\n\nif x = 0 then print \"Zero\"\n\n' --------------------------\n' if/then/else\nif x = 0 then\nprint \"Zero\"\nelse\nprint \"Nonzero\"\nend if\n\n' --------------------------\n' not\nif x then\nprint \"x has a value.\"\nend if\nif not(x) then\nprint \"x has no value.\"\nend if\n\n' --------------------------\n' if .. end if\nif x = 0 then\nprint \"Zero\"\ngoto [surprise]\nend if\nwait\n\nif x = 0 then goto [surprise]\nprint \"No surprise.\"\nwait\n\n[surprise]\nprint \"Surprise!\"\nwait\n\n' --------------------------\n' case numeric\nnum = 3\n\nselect case num\ncase 1\nprint \"one\"\n\ncase 2\nprint \"two\"\n\ncase 3\nprint \"three\"\n\ncase else\nprint \"other number\"\n\nend select\n\n' --------------------------\n' case character\nvar$=\"blue\"\n\nselect case var$\n\ncase \"red\"\nprint \"red\"\n\ncase \"green\"\nprint \"green\"\n\ncase else\nprint \"color unknown\"\n\nend select\n", "language": "Run-BASIC" }, { "code": "// This function will only be compiled if we are compiling on Linux\n#[cfg(target_os = \"linux\")]\nfn running_linux() {\n println!(\"This is linux\");\n}\n#[cfg(not(target_os = \"linux\"))]\nfn running_linux() {\n println!(\"This is not linux\");\n}\n\n// If we are on linux, we must be using glibc\n#[cfg_attr(target_os = \"linux\", target_env = \"gnu\")]\n// We must either be compiling for ARM or on a little endian machine that doesn't have 32-bit pointers pointers, on a\n// UNIX like OS and only if we are doing a test build\n#[cfg(all(\n any(target_arch = \"arm\", target_endian = \"little\"),\n not(target_pointer_width = \"32\"),\n unix,\n test\n ))]\nfn highly_specific_function() {}\n", "language": "Rust" }, { "code": "fn main() {\n if cfg!(target_os = \"linux\") {\n // Do something\n }\n}\n", "language": "Rust" }, { "code": "trait PrintType {\n fn print_type(&self);\n}\n\nimpl PrintType for char {\n fn print_type(&self) {\n println!(\"char\");\n }\n}\n\nimpl PrintType for f64 {\n fn print_type(&self) {\n println!(\"64-bit float\");\n }\n}\n\nfn prints_type_of_args<T, U>(arg1: &T, arg2: &U)\n where T: PrintType,\n U: PrintType\n{\n arg1.print_type();\n arg2.print_type();\n}\n\nfn main() {\n prints_type_of_args(&'a', &2.0);\n prints_type_of_args(&'a', &'b');\n}\n", "language": "Rust" }, { "code": "if some_conditional {\n do_stuff();\n} else if some_other_conditional {\n do_other_stuff();\n} else {\n destroy_humanity();\n}\n\n// If statements are also expressions and will yield the value of the last expression in each block\nlet x = if y > z { y + 1 } else { z * 4 };\n\n// Pattern matching may also be used\nstruct Point {\n x: i32,\n y: i32,\n}\nfn some_function(p: Option<Point>) {\n if let Some(Point { x: x_coord, y: y_coord }) = p {\n // Do something with x_coord and y_coord\n }\n}\n", "language": "Rust" }, { "code": "fn some_other_function(p: Option<Point>) {\n match p {\n Some(Point { x: 0, y: 0 }) => println!(\"Point is on origin\"),\n Some(Point { x: 0, y: _ }) | Some(Point { x: _, y: 0 }) => println!(\"Point is on an axis\"),\n Some(Point {x: a, y: b}) if a == b => println!(\"x and y are the same value\"),\n Some(Point {x: ref mut a, y: ref b}) if *a > 4 && *b < 2 => println!(\"we got a mutable reference to x-value and an immutable reference to y-value.\"),\n op @ Some(p) => println!(\"op is the Option<Point> while p is the contained Point\"),\n None => println!(\"We didn't get a point\"),\n }\n}\n", "language": "Rust" }, { "code": "fn prints_args_dynamic(arg1: &PrintType, arg2: &PrintType) {\n arg1.print_type();\n arg2.print_type();\n}\nfn main() {\n prints_args_dynamic(&'a', &2.0);\n prints_args_dynamic(&6.3,&'c');\n}\n", "language": "Rust" }, { "code": " if EXPR then\n -- CODE\n elsif EXPR then\n -- CODE\n else\n -- CODE\n end;\n", "language": "Sather" }, { "code": " case EXPR\n when EXPRL then\n -- CODE\n when EXPRL then\n -- CODE\n else\n -- CODE\n end;\n", "language": "Sather" }, { "code": " if (n == 12) \"twelve\" else \"not twelve\"\n\n today match {\n case Monday =>\n Compute_Starting_Balance;\n case Friday =>\n Compute_Ending_Balance;\n case Tuesday =>\n Accumulate_Sales\n case _ => {}\n }\n", "language": "Scala" }, { "code": "(if <test> <consequent> <alternate>)\n", "language": "Scheme" }, { "code": "(if <test> <consequent>)\n", "language": "Scheme" }, { "code": "(display\n (if (> 1 2)\n \"yes\"\n \"no\"))\n(newline)\n(display\n (if (> 1 2)\n (- 1 2)))\n(newline)\n", "language": "Scheme" }, { "code": "(cond <clause1> <clause2> ...)\n", "language": "Scheme" }, { "code": "(display\n (cond ((> 1 2) \"greater\")\n ((< 1 2) \"less\")))\n(newline)\n(display\n (cond ((> 1 1) \"greater\")\n ((< 1 1) \"less\")\n (else \"equal\")))\n(newline)\n", "language": "Scheme" }, { "code": "(case <key> <clause1> <clause2> ...)\n", "language": "Scheme" }, { "code": "(display\n (case (* 2 3)\n ((2 3 5 7) \"prime\")\n ((1 4 6 8 9) \"composite\")))\n(newline)\n(display\n (case (car (list c d))\n ((a e i o u) \"vowel\")\n ((w y) \"semivowel\")\n (else \"consonant\")))\n(newline)\n", "language": "Scheme" }, { "code": "if condition then\n statement\nend if;\n\nif condition then\n statement1\nelse\n statement2;\nend if;\n\nif condition1 then\n statement1\nelsif condition2 then\n statement2;\nend if;\n\nif condition1 then\n statement1\nelsif condition2 then\n statement2;\nelse\n statement3;\nend if;\n", "language": "Seed7" }, { "code": "case i of\n when {1, 4, 9}: # Executed if i is 1, 4 or 9\n statement1;\n when {11} | {13 .. 17}: # Executed if i is 11, 13, 14, 15, 16 or 17\n statement2;\n when {42}: # Executed only if i is 42\n statement3;\n otherwise:\n statement4;\nend case;\n", "language": "Seed7" }, { "code": "if x == 1\n foo()\nelse if x == 2\n bar()\nelse\n foobar()\nend if\n", "language": "SIMPOL" }, { "code": ".if(x == 1, \"hello\", \"world\")\n", "language": "SIMPOL" }, { "code": "BEGIN\n INTEGER i,j;\n i:=1; j:=2;\n OutText(\"i \");\n IF i=1 THEN OutInt(i,1);\n OutImage;\n OutInt(i,2); OutInt(j,2);\n IF i<j THEN OutText(\" : i<j\") ELSE OutText(\" : i>=j\");\n OutImage;\n IF i>=j THEN BEGIN\n OutText(\"i=\");\n OutInt(i,5)\n END\n ELSE BEGIN\n OutText(\"j=\");\n OutInt(j,5)\n END;\n OutImage\nEND\n", "language": "Simula" }, { "code": "BEGIN\n INTEGER i,j;\n SWITCH target:=L1,L2,L3;\n i:=1; j:=2;\n OutText(\"::\");\n GOTO target(j);\n L1: OutText(\"AA\");\n L2: OutText(\"BB\");\n L3: OutText(\"CC\");\n OutImage\nEND\n", "language": "Simula" }, { "code": "\"Conditionals in Slate are really messages sent to Boolean objects. Like Smalltalk. (But the compiler might optimize some cases)\"\n balance > 0\n ifTrue: [inform: 'still sitting pretty!'.]\n ifFalse: [inform: 'No money till payday!'.].\n", "language": "Slate" }, { "code": "c@(Net URLPathEncoder traits) convert\n[ | byte1 byte2 byte3 digit1 digit2|\n [c in isAtEnd] whileFalse:\n [byte1: c in next.\n byte1 caseOf: {\n $+ -> [c out nextPut: $\\s].\n $% -> [byte2: c in next.\n byte3: c in next.\n digit1: (byte2 toDigit: 16).\n digit2: (byte3 toDigit: 16).\n digit1 isNil \\/ [digit2 isNil] ifTrue: [error: 'Error reading hex sequence after %'].\n c out nextPut: (digit1 * 16 + digit2 as: c out elementType)].\n } otherwise: [c out nextPut: byte1].\n ].\n].\n", "language": "Slate" }, { "code": "[p isAtEnd] whileFalse: [p next evaluate]].\n", "language": "Slate" }, { "code": "(if [test] [consequent] [[alternate]])\n", "language": "Slope" }, { "code": "(define my-file (file-open-read \"my-file.txt\"))\n(if my-file (write (read-all my-file)) (! \"Could not open file\"))\n", "language": "Slope" }, { "code": "(case [value] (match-val expression)...)\n", "language": "Slope" }, { "code": "(case my-enum\n (string (do-string my-enum))\n (bool (do-bool my-enum))\n (proc (my-enum))\n (number (do-number my-enum))\n (else (! \"No match found in case\")))\n", "language": "Slope" }, { "code": "(cond ([test] [expression])...)\n", "language": "Slope" }, { "code": "(define my-num 123)\n(cond\n ((positive? my-num) 'positive)\n ((negative? my-num) 'negative)\n (else 'zero))\n", "language": "Slope" }, { "code": " balance > 0\n ifTrue: [Transcript cr; show: 'still sitting pretty!'.]\n ifFalse: [Transcript cr; show: 'No money till payday!'.].\n\n balance < 10 ifTrue:[ self goGetSomeMoney ].\n\n balance > 1000 ifTrue:[ self beHappy ].\n\n (balance < 10)\n ifFalse:[ self gotoHappyHour ]\n ifTrue:[ self noDrinksToday ].\n", "language": "Smalltalk" }, { "code": "abs := x > 0 ifTrue: [ x ] ifFalse: [ x negated ]\n", "language": "Smalltalk" }, { "code": "...\ntrueAction := [ ... do something ].\nfalseAction := [ ... do something else ...].\n...\nabs := x > 0 ifTrue:trueAction ifFalse:falseAction. \"3)\"\n", "language": "Smalltalk" }, { "code": "|x|\nx := 1.\nvalue :=\n x caseOf: {\n [1]->['one'].\n [2]->['two'].\n [3]->['three']\n }\n otherwise:['none of them'].\n", "language": "Smalltalk" }, { "code": "\tA = \"true\"\n* \"if-then-else\"\nif\tA \"true\"\t\t\t:s(goTrue)f(goFalse)\ngoTrue\toutput = \"A is TRUE\"\t\t:(fi)\ngoFalse\toutput = \"A is not TRUE\"\t:(fi)\nfi\n\n* \"switch\"\nswitch\t\tA (\"true\" | \"false\") . switch\t:s($(\"case\" switch))f(default)\ncasetrue\toutput = \"A is TRUE\"\t:(esac)\ncasefalse\toutput = \"A is FALSE\"\t:(esac)\ndefault\t\toutput = \"A is neither FALSE nor TRUE\"\nesac\nend\n", "language": "SNOBOL4" }, { "code": "$==?\\==zero=====!/==#\n \\==non zero==/\n", "language": "SNUSP" }, { "code": "var odd = 13;\nif odd % 2 != 0 {\n print(\"odd\");\n}\n", "language": "SNUSP" }, { "code": "var odd = 13;\nif odd % 2 != 0 {\n print(\"odd\");\n} else {\n print(\"even\");\n}\n", "language": "SNUSP" }, { "code": "var nodiv3 = 13;\nif nodiv3 % 3 == 0 {\n print(\"divisible by 3\");\n} else if nodiv3 % 3 == 1 {\n print(\"gives 1 remainder\");\n} else {\n print(\"gives 2 remainder\");\n}\n", "language": "SNUSP" }, { "code": "case when a then b else c end\n\ndeclare @n int\nset @n=124\nprint case when @n=123 then 'equal' else 'not equal' end\n\n--If/ElseIf expression\nset @n=5\nprint case when @n=3 then 'Three' when @n=4 then 'Four' else 'Other' end\n", "language": "SQL" }, { "code": "declare @n int\nset @n=123\nif @n=123\n BEGIN --begin/end needed if more than one statement inside\n print 'one two three'\n END\nELSE\n if @n=124 print 'one two four'\n else print 'other'\n", "language": "SQL" }, { "code": "01010000000000100000000000000000 -10 to c\n00000000000000110000000000000000 Test\n01110000000000000000000000000000 14 to CI\n", "language": "SSEM" }, { "code": "clear\nset obs 4\ngen a = cond(mod(_n, 2)==1, \"A\", \"B\")\nlist, noobs noheader\n\n +---+\n | A |\n | B |\n | A |\n | B |\n +---+\n", "language": "Stata" }, { "code": "program isprime\n\tsca n = `0'\n\tsca p = 1\n\tif n<5 {\n\t\tif n!=2 & n!=3 {\n\t\t\tsca p = 0\n\t\t}\n\t}\n\telse {\n\t\tif mod(n, 2)==0 {\n\t\t\tsca p = 0\n\t\t}\n\t\telse {\n\t\t\tsca k=3\n\t\t\twhile k*k<=n {\n\t\t\t\tif mod(n, k)==0 {\n\t\t\t\t\tsca p = 0\n\t\t\t\t\tcontinue, break\n\t\t\t\t}\n\t\t\t\tsca k = k+2\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif p {\n\t\tdi \"`n' is prime.\"\n\t}\n\telse {\n\t\tdi \"`n' is not prime.\"\n\t}\nend\n\nisprime `=10^12-11'\n999999999989 is prime.\n", "language": "Stata" }, { "code": "clear\nset obs 100\ncount\n 100\ncount if mod(_n, 3)==0\n 33\n", "language": "Stata" }, { "code": "function isprime(n) {\n\tif (n<5) return(n==2 | n==3)\n\telse if (mod(n, 2)==0) return(0)\n\telse {\n\t\tfor (k=3; k*k<=n; k=k+2) {\n\t\t\tif (mod(n, k)==0) return(0)\n\t\t}\n\t\treturn(1)\n\t}\n}\n\nisprime(10^12-11)\n 1\n", "language": "Stata" }, { "code": "function fib(n) {\n\treturn(n<2 ? n : fib(n-1)+fib(n-2))\n}\n\nfib(10)\n 55\n", "language": "Stata" }, { "code": "kama (kweli) {\n andika(\"statement\")\n} au (kweli /* condition */) {\n andika(\"statement\")\n} au (kweli /* condition */) {\n andika(\"statement\")\n} sivyo {\n andika(\"statement\")\n}\n", "language": "Swahili" }, { "code": "templates foo\n when <=0> do 'zero' -> !OUT::write\n when <..0> do\n 'negative ' -> !OUT::write\n -$ -> #\n when <?($ mod 2 <=0>)> do 'even' -> !OUT::write\n otherwise 'odd' -> !OUT::write\nend foo\n", "language": "Tailspin" }, { "code": "if {$foo == 3} {\n puts \"foo is three\"\n} elseif {$foo == 4} {\n puts \"foo is four\"\n} else {\n puts \"foo is neither three nor four\"\n}\n", "language": "Tcl" }, { "code": "set result [expr { $foo == 3 ? \"three\" : \"not three\" }]\n", "language": "Tcl" }, { "code": "switch -- $foo {\n 3 {puts \"foo is three\"}\n 4 {puts \"foo is four\"}\n default {puts \"foo is something else\"}\n}\n", "language": "Tcl" }, { "code": "if(a > b)\n println(a);\n", "language": "Tern" }, { "code": "if(a > b) {\n println(a);\n} else {\n println(b);\n}\n", "language": "Tern" }, { "code": "unless(a > b) {\n println(b);\n} else {\n println(a);\n}\n", "language": "Tern" }, { "code": "switch(a) {\n case 10:\n case 11:\n println(a);\n break;\n default:\n println(b);\n}\n", "language": "Tern" }, { "code": "If condition\nstatement\n", "language": "TI-83-BASIC" }, { "code": "If condition : statement\n", "language": "TI-83-BASIC" }, { "code": "If condition\nThen\nstatements\nEnd\n", "language": "TI-83-BASIC" }, { "code": "If condition\nThen\nstatements\nElse\nstatements\nEnd\n", "language": "TI-83-BASIC" }, { "code": "100 100 = [ .\" True\\n\" ] ifTrue\n100 200 = [ .\" True\\n\" ] ifTrue\n", "language": "Toka" }, { "code": "100 100 = [ .\" True\\n\" ] ifFalse\n100 200 = [ .\" True\\n\" ] ifFalse\n", "language": "Toka" }, { "code": "100 100 = [ .\" Equal\\n\" ] [ .\" Not Equal\\n\" ] ifTrueFalse\n100 200 = [ .\" Equal\\n\" ] [ .\" Not Equal\\n\" ] ifTrueFalse\n", "language": "Toka" }, { "code": "// numbers and objects\nif(%num == 1)\n{\n\tfoo();\n}\nelse if(%obj == MyObject.getID())\n{\n\tbar();\n}\nelse\n{\n\tdeusEx();\n}\n\n// strings\nif(%str $= \"Hello World\")\n{\n\tfoo();\n}\nelse if(%str $= \"Bye World\")\n{\n\tbar();\n}\nelse\n{\n\tdeusEx();\n}\n", "language": "TorqueScript" }, { "code": "// numbers and objects\nswitch(%num)\n{\n\tcase 1:\n\t\tone();\n\tcase 2:\n\t\ttwoThreeOrFour();\n\tcase 3:\n\t\ttwoThreeOrFour();\n\tcase 4:\n\t\ttwoThreeOrFour();\n\tcase 5:\n\t\tfive();\n\tcase MyObject.getID():\n\t\tanObject();\n\tdefault:\n\t\teverythingElse();\n}\n\n// strings\nswitch$(%str)\n{\n\tcase \"Hello\":\n\t\tarrival();\n\tcase \"Goodbye\":\n\t\tdeparture();\n\tdefault:\n\t\tsomethingElse();\n}\n", "language": "TorqueScript" }, { "code": "%formatted = %str @ ((getSubStr(%str,strLen(%str) - 1,1) $= \"s\") ? \"'\" : \"'s\");\n", "language": "TorqueScript" }, { "code": "#lang transd\n\nMainModule: {\n _start: (λ locals: b 1 c 0\n (textout (if b \"OK\" else \"NO\") \"\\n\")\n\n // switch/case emulation\n\n (textout (* 5\n (if (== b 0) 2\n elsif (== b 1) 5\n else 6)) \"\\n\")\n\n // example of using 'or' as a conditional construct\n\n (or (!= c 0) (textout \"c is 0\"))\n )\n}\n", "language": "Transd" }, { "code": "true [\"yes\" print] [\"no\" print] branch\n", "language": "Trith" }, { "code": "true [\"yes\" print] when\n", "language": "Trith" }, { "code": "false [\"no\" print] unless\n", "language": "Trith" }, { "code": "! IF-ELSEIF-ELSE-END IF\n! SELECT-CASE\n! ON GOTO, ON GOSUB\n\nIF expr_booleana THEN\n sentencia(s)\nEND IF\n\n\nIF expr_booleana1 THEN\n sentencia(s)\nELSEIF expr_booleana2 THEN\n sentencia(s)\nELSEIF expr_booleana3 THEN\n sentencia(s)\nELSE\n sentencia(s)\nEND IF\n\n\nSELECT CASE expr_booleana\nCASE 1\n sentencia(s)\nCASE 2\n sentencia(s)\nCASE ELSE\n sentencia(s)\nEND SELECT\n\n\nON expresión GOTO label1, label2 ELSE label3\n\n\nON expresión Gosub label1, label2 ELSE label3\n", "language": "True-BASIC" }, { "code": "$$ MODE TUSCRIPT\n\ncondition=\"c\"\nIF (condition==\"a\") THEN\n ---> do something\nELSEIF (condition==\"b\") THEN\n ---> do something\nELSE\n ---> do something\nENDIF\n", "language": "TUSCRIPT" }, { "code": "$$ MODE TUSCRIPT\n\ndays=\"Monday'Tuesday'Wednesday'Thursday'Friday'Saturday'Sunday\"\ndayofweek=DATE (today,day,month,year,number)\nday=SELECT (days,#dayofweek)\n\nSELECT day\nCASE \"Monday\"\n ---> do something\nCASE \"Saturday\",\"Sunday\"\n ---> do something\nDEFAULT\n ---> do something\nENDSELECT\n", "language": "TUSCRIPT" }, { "code": "@(choose :shortest x)\n@x:@y\n@(or)\n@x<--@y\n@(or)\n@x+@y\n@(end)\n", "language": "TXR" }, { "code": "@(all)\n@x:y@\n@z<-@w\n@(and)\n@(output)\nWe have a match: (x, y, z, w) = (@x, @y, @z, @w).\n@(end)\n@(end)\n", "language": "TXR" }, { "code": "@# match a line which contains some piece of text x\n@# after the rightmost occurence of : such that the same piece\n@# of text also occurs at the start of the line preceded by -->\n@(all)\n@*junk:@x\n@(and)\n-->@x@/.*/\n@(end)\n", "language": "TXR" }, { "code": "factorial : Nat -> Nat\nfactorial x =\n if x == 0 then 1\n else\n x * fac (Nat.drop x 1)\n", "language": "Unison" }, { "code": "if test 3 -lt 5; then echo '3 is less than 5'; fi\n", "language": "UNIX-Shell" }, { "code": "if test 4 -ge 6\nthen echo '4 is greater than or equal to 6'\nelif test 4 -lt 6\nthen echo '4 is less than 6'\nelse echo '4 compares not to 6'\nfi\n", "language": "UNIX-Shell" }, { "code": "case value in\n choicea)\n foo\n ;;\n choiceb)\n bar\n ;;\nesac\n", "language": "UNIX-Shell" }, { "code": "test 3 -lt 5 && echo '3 is less than 5'\ntest 4 -ge 6 || echo '4 is not greater than or equal to 6'\n", "language": "UNIX-Shell" }, { "code": "# This is a while loop\nl=1\nwhile [ l -le 5 ]; do\n echo $l\ndone\n\n# This is an until loop\nl=1\nuntil [ l -eq 5 ]; do\n echo $l\ndone\n", "language": "UNIX-Shell" }, { "code": "if energyLevel > 9000 { \"That's impossible!!!\" } else { \"Ok, I guess\" }\n", "language": "Ursalang" }, { "code": "if color == \"red\" { \"aaaaaah!\" }\nelse if color == \"blue\" { \"oooooh!\" }\nelse { \"eeeeeeee!\" }\n", "language": "Ursalang" }, { "code": "[true]\n ['is true' puts]\n ['is false' puts]\nifte\n\n=is true\n", "language": "V" }, { "code": "[true]\n ['is true' puts]\nif\n=is true\n", "language": "V" }, { "code": "3 [\n [1 =] [1 *]\n [2 =] [10 *]\n [3 =] [100 *]\n [4 =] [1000 *]\n] when\n\n=300\n", "language": "V" }, { "code": "true\n 1 2\nchoice\n\n=1\n\nfalse\n 1 2\nchoice\n\n=2\n", "language": "V" }, { "code": "if boolean_expression {\n statements\n}\n", "language": "V-(Vlang)" }, { "code": "if boolean_expression {\n statements\n} else {\n other\n statements\n}\n", "language": "V-(Vlang)" }, { "code": "if boolean_expression1 {\n statements\n} else if boolean_expression2 {\n otherStatements\n}\n", "language": "V-(Vlang)" }, { "code": "match true {\n boolean_expression1 {\n statements\n }\n boolean_expression2 {\n other\n statements\n }\n else {\n last\n resort\n statements\n }\n}\n", "language": "V-(Vlang)" }, { "code": "switch expression_of_any_type {\n value1 {\n statements\n }\n value2, value3, value4 {\n other\n statements\n }\n else {}\n}\n", "language": "V-(Vlang)" }, { "code": "Sub C_S_If()\nDim A$, B$\n\n A = \"Hello\"\n B = \"World\"\n 'test\n If A = B Then Debug.Print A & \" = \" & B\n 'other syntax\n If A = B Then\n Debug.Print A & \" = \" & B\n Else\n Debug.Print A & \" and \" & B & \" are differents.\"\n End If\n 'other syntax\n If A = B Then\n Debug.Print A & \" = \" & B\n Else: Debug.Print A & \" and \" & B & \" are differents.\"\n End If\n 'other syntax\n If A = B Then Debug.Print A & \" = \" & B _\n Else Debug.Print A & \" and \" & B & \" are differents.\"\n 'other syntax\n If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n", "language": "VBA" }, { "code": "Sub C_S_ElseIf()\nDim A$, B$\n\n A = \"Hello\"\n B = \"World\"\n 'test\n If A = B Then Debug.Print A & \" = \" & B\n 'other syntax\n If A = B Then\n Debug.Print A & \" = \" & B\n ElseIf A > B Then\n Debug.Print A & \" > \" & B\n Else\n Debug.Print A & \" < \" & B\n End If\nEnd Sub\n", "language": "VBA" }, { "code": "Sub C_S_Select_Case()\n'With Strings\nDim A$, C&\n\n A = \"Hello\"\n Select Case A\n Case \"World\"\n Debug.Print \"A = World\"\n Case \"Hello\"\n Debug.Print \"A = Hello\"\n Case Else\n Debug.Print \"You make a mistake\"\n End Select\n'With numerics\n C = 11\n Select Case C\n Case Is <= 10\n Debug.Print \"C <= 10\"\n Case Is < 20, Is > 10\n Debug.Print \"10 < C < 20\"\n Case Is >= 20\n Debug.Print \"C >= 20\"\n End Select\n'Select Case Boolean\n 'With Strings\n Select Case False\n Case A <> \"Hello\"\n Debug.Print \"A = Hello\"\n Case A Like \"*orl*\"\n Debug.Print \"A Not Like *orl*\"\n Case Else\n Debug.Print \"You make a mistake\"\n End Select 'return : \"A = Hello\"\n 'Other conditions's order\n Select Case False\n Case A Like \"*orl*\"\n Debug.Print \"A Not Like *orl*\"\n Case A <> \"Hello\"\n Debug.Print \"A = Hello\"\n Case Else\n Debug.Print \"You make a mistake\"\n End Select 'return : \"A Not Like *orl*\"\n 'With numerics\n Select Case True\n Case C <= 10\n Debug.Print \"C <= 10\"\n Case C < 20, C > 10\n Debug.Print \"10 < C < 20\"\n Case C >= 20\n Debug.Print \"C >= 20\"\n End Select\nEnd Sub\n", "language": "VBA" }, { "code": "Sub C_S_IIF()\n Dim myName\n myName = 2\n Debug.Print IIf(myName = 1, \"Bryan\", \"Justin\")\n 'return : Justin\nEnd Sub\n", "language": "VBA" }, { "code": "Sub C_S_Switch()\n Dim myName\n myName = 2\n Debug.Print Switch(myName = 1, \"Bryan\", myName = 2, \"Justin\", myName = 3, \"John\")\n 'return : Justin\nEnd Sub\n", "language": "VBA" }, { "code": "If condition1 Then\n statement\nEnd If\n\nIf condition1 Then\n statement\nElseIf condition2 Then\n statement\n...\nElseIf conditionN Then\n statement\nElse\n statement\nEnd If\n", "language": "VBScript" }, { "code": "If condition Then statement\n\nIf condition Then statement Else statement\n", "language": "VBScript" }, { "code": "Select Case Expression\n Case Value1: statement\n Case Value2: statement\n ...\n Case ValueN: statement\n Case Else: statement\nEnd Select\n\nSelect Case Expression\n Case Value1\n statements\n Case Value2\n statements\n ...\n Case ValueN\n statements\n Case Else\n statements\nEnd Select\n", "language": "VBScript" }, { "code": "@VAR a b = 1 2;\n\n// -------------------------------------------------------------------------------------\n// @IF verb (returns 0u0 = UNIT, if no then: or else: block is executed)\n// ======== (note: both then: and else: keywords are optional)\n\n@SAY \"@IF 1 \" ( @IF (a > b) then:{\"then:\"} else:{\"else:\"} );\n@SAY \"@IF 2 \" ( @IF (b > a) else:{\"else:\"} then:{\"then:\"} );\n@SAY \"@IF 3 \" ( @IF (a > b) then:{\"then:\"} );\n@SAY \"@IF 4 \" ( @IF (b > a) then:{\"then:\"} );\n@SAY \"@IF 5 \" ( @IF (a > b) else:{\"else:\"} );\n@SAY \"@IF 6 \" ( @IF (b > a) else:{\"else:\"} );\n@SAY \"@IF 7 \" ( @IF (b > a) );\n\n// ---------------------------------------------------------------------------------\n// ? verb (conditional operator)\n// ====== ( 1st block (TRUE) is required, 2nd block (FALSE) is optional)\n\n@SAY \"? 1 \" ( (a < b) ? {\"1st\"} {\"2nd\"} );\n@SAY \"? 2 \" ( (a > b) ? {\"1st\"} {\"2nd\"} );\n@SAY \"? 3 \" ( (a < b) ? {\"1st\"} );\n@SAY \"? 4 \" ( (a > b) ? {\"1st\"} );\n\n// -----------------------------------------------------------------------------------\n// @CASE verb\n// ==========\n//\n// - executes code block for first when: condition that evaluates to TRUE\n//\n// - normally, ends after running that code block\n//\n// - if no when: conditions are true, executes else: code block (if present)\n//\n// - can exit a when: block with @CONTINUE case: verb -- causes @CASE to continue\n// looking for more true when: blocks or the else: block\n\n@VAR n = 0;\n@LOOP times:3\n{\n @SAY ( \"n =\" n \" @CASE results:\"\n ( @CASE\n when:(n == 0) { \"n == 0(1)\" }\n when:(n == 0) { \"n == 0(2)\" }\n when:(n == 1) { \"n == 1(1)\"; @CONTINUE case: }\n when:(n == 1) { \"n == 1(2c)\" }\n else: { \"else\" }\n )\n )\n ;\n n++;\n};\n\n/] -----------------------------------------------------------------------\n\nOutput:\n\n@IF 1 else:\n@IF 2 then:\n@IF 3 0_u0\n@IF 4 then:\n@IF 5 else:\n@IF 6 0_u0\n@IF 7 0_u0\n? 1 1st\n? 2 2nd\n? 3 1st\n? 4 0_u0\nn = 0 @CASE results: n == 0(1)\nn = 1 @CASE results: n == 1(2c)\nn = 2 @CASE results: else\n", "language": "Verbexx" }, { "code": "if( expr_booleana ) command1;\nelse command2;\n", "language": "Verilog" }, { "code": "case( expr_booleana )\nvalor1: command1;\nvalor2: command2;\n...\ndefault: commandN;\nendcase\n", "language": "Verilog" }, { "code": "If condition Then\n statement\nEnd If\n\nIf condition Then\n statement\nElse\n statement\nEnd If\n\nIf condition1 Then\n statement\nElseIf condition2 Then\n statement\n...\nElseIf conditionN Then\n statement\nElse\n statement\nEnd If\n", "language": "Visual-Basic" }, { "code": "If condition Then statement\n\nIf condition Then statement Else statement\n", "language": "Visual-Basic" }, { "code": "Select Case Expression\n Case Value1: statement\n Case Value2: statement\n ...\n Case ValueN: statement\n Case Else: statement\nEnd Select\n\nSelect Case Expression\n Case Value1\n statements\n Case Value2\n statements\n ...\n Case ValueN\n statements\n Case Else\n statements\nEnd Select\n", "language": "Visual-Basic" }, { "code": "IIf(expr, then-value, else-value)\n", "language": "Visual-Basic" }, { "code": " myName = 2\n Debug.Print IIf(myName = 1, \"John\", \"Jack\")\n 'return : \"Jack\")\n", "language": "Visual-Basic" }, { "code": "Switch(expr-1, value-1[, expr-2, value-2 … [, expr-n,value-n]])\n", "language": "Visual-Basic" }, { "code": " myName = 2\n Debug.Print Switch(myName = 1, \"James\", myName = 2, \"Jacob\", myName = 3, \"Jeremy\")\n 'return : \"Jacob\"\n", "language": "Visual-Basic" }, { "code": "Dim result As String, a As String = \"pants\", b As String = \"glasses\"\n\nIf a = b Then\n result = \"passed\"\nElse\n result = \"failed\"\nEnd If\n", "language": "Visual-Basic-.NET" }, { "code": "Dim result As String, a As String = \"pants\", b As String = \"glasses\"\n\nIf a = b Then result = \"passed\" Else result = \"failed\"\n\nIf a = b Then\n result = \"passed\"\nElse : result = \"failed\"\nEnd If\n\nIf a = b Then : result = \"passed\"\nElse\n result = \"failed\"\nEnd If\n", "language": "Visual-Basic-.NET" }, { "code": "Dim result As String, a As String = \"pants\", b As String = \"glasses\"\n\nIf a = b Then\n result = \"passed\"\nElseIf a <> b Then\n result = \"failed\"\nElse\n result = \"impossible\"\nEnd If\n", "language": "Visual-Basic-.NET" }, { "code": "Dim result As String, a As String = \"pants\", b As String = \"glasses\"\n\nSelect Case a\n Case b\n result = \"match\"\n Case a : result = \"duh\"\n Case Else\n result = \"impossible\"\nEnd Select\n", "language": "Visual-Basic-.NET" }, { "code": "Imports Microsoft.VisualBasic\n\n...\n\nDim result As String = CType(IIf(\"pants\" = \"glasses\", \"passed\", \"failed\"), String) 'VB 1-8\n\nDim result As String = If(\"pants\" = \"glasses\", \"passed\", \"failed\") 'VB 9\n", "language": "Visual-Basic-.NET" }, { "code": "Imports Microsoft.VisualBasic\n\n...\n\nFunction IIf2(Of T)(ByVal condition As Boolean, ByVal truepart As T, ByVal falsepart As T) As T\n If condition Then Return truepart Else Return falsepart\nEnd Function\n\n...\n\nDim result As String = IIf2(\"pants\" = \"glasses\", \"passed\", \"failed\") ' type is inferred\n", "language": "Visual-Basic-.NET" }, { "code": "Dim result As String = If(\"pants\" = \"glasses\", \"passed\", \"failed\") ' type is inferred\n", "language": "Visual-Basic-.NET" }, { "code": "if(condition){\n result = 'met'\n}\nelse{\n result = 'not met'\n}\n", "language": "Vorpal" }, { "code": "<%>condition\n", "language": "Woma" }, { "code": "<$>condition\n", "language": "Woma" }, { "code": "condition = True\ncondition<?>print(condition)\n", "language": "Woma" }, { "code": "condition => success // failure\ncondition => success\ncondition // failure\n", "language": "Wrapl" }, { "code": "condition & success\n", "language": "Wrapl" }, { "code": "condition | failure\n", "language": "Wrapl" }, { "code": "for (b in [true, false]) {\n if (b) {\n System.print(true)\n } else {\n System.print(false)\n }\n\n // equivalent code using ternary operator\n System.print(b ? true : false)\n\n // equivalent code using && operator\n System.print(b && true)\n\n // equivalent code using || operator\n System.print(b || false)\n\n System.print()\n}\n", "language": "Wren" }, { "code": "if(i>1)\n DoSomething\n\nFailedSoContinueCodeExecution.\n", "language": "X86-Assembly" }, { "code": "cmp i, 1\njg _DoSomething\nFailedSoContinueCodeExecution\n", "language": "X86-Assembly" }, { "code": "if(i>1)\n DoSomething\nelse if(i<=1)\n DoSomethingElse\nFailedSoContinueCodeExecution\n", "language": "X86-Assembly" }, { "code": "cmp i, 1\njg _DoSomething\njle _DoSomethingElse\nFailedSoContinueCodeExecution\n", "language": "X86-Assembly" }, { "code": "if(i==1)\n DoSomething\nelse\n DoSomethingElse\nFailedSoContinueExecution\n", "language": "X86-Assembly" }, { "code": "cmp i, 1\nje _DoSomething\njne _DoSomethingElse\nFailedSoContinueExecution\n", "language": "X86-Assembly" }, { "code": "(if (eq s \"Rosetta Code\")\n \"The well-known programming chrestomathy site\"\n \"Some other website, maybe, I dunno\" )\n", "language": "XLISP" }, { "code": "(case s\n (\"Rosetta Code\" \"Ah yes, the chrestomathy site\")\n (\"Stack Overflow\" \"Oh dear me, having problems are you?\")\n (\"Github\" \"Say no more\")\n (else \"Sorry, never heard of it\") )\n", "language": "XLISP" }, { "code": "(cond\n ((eq s \"Rosetta Code\") \"Chrestomathy site\")\n ((> n 37) \"Some other appropriate value, presumably\")\n (t \"If you're seeing me, s wasn't equal to Rosetta Code and n must have been 37 or below\") )\n", "language": "XLISP" }, { "code": "<xsl:if test=\"condition\">\n <!-- executed if XPath expression evaluates to true -->\n</xsl:if>\n", "language": "XSLT" }, { "code": "<xsl:choose>\n <xsl:when test=\"condition1\">\n <!-- included if condition1 evaluates to true (like C `if`) -->\n </xsl:when>\n <xsl:when test=\"condition2\">\n <!-- included if all previous conditions evaluated to false and\n condition2 evaluates to true (like C `else if`) -->\n </xsl:when>\n <--\n ...\n -->\n <xsl:otherwise>\n <!-- included if all previous conditions evaluated to false\n (like C `else`) -->\n <!-- (The `otherwise` element is optional) -->\n </xsl:otherwise>\n</xsl:choose>\n", "language": "XSLT" }, { "code": "<xsl:if test=\"@attrib = 'foo'\">...</xsl:if>\n<xsl:if test=\"position() != last()\">...</xsl:if>\n<xsl:if test=\"not(false())\">...</xsl:if>\n\n<!-- Some XPath expressions must be escaped. -->\n<xsl:if test='contains(node, \"stuff\") and (position() &gt; first())'>...</xsl:if>\n\n<!-- The following two examples are synonymous because the test attribute is\n implicitly converted to boolean. -->\n<xsl:if test=\"boolean($expr)\">...</xsl:if>\n<xsl:if test=\"$expr\">...</xsl:if>\n", "language": "XSLT" }, { "code": "// if-then-endif, switch / end switch\n// on gosub, on goto\n// repeat / until, do / loop, while / end while\n\n\nif expr_booleana then\n sentencia(s)\nendif\n\n\nif expr_booleana sentencia(s)\n\n\nif expr_booleana1 then\n sentencia(s)\nelsif expr_booleana2\n sentencia(s)\nelsif expr_booleana3 then\n sentencia(s)\nelse\n sentencia(s)\nendif\n\n\nswitch expr_booleana\n case valor1\n sentencia(s)\n case valor2\n sentencia(s)\n default\n sentencia(s)\nend switch\n\n\non expresion gosub label1, label2\n sentencia(s)\nlabel label1\n sentencia(s)\nreturn\nlabel label2\n sentencia(s)\nreturn\n\n\non expresion goto label1, label2\n sentencia(s)\nlabel label1\n sentencia(s)\nlabel label2\n sentencia(s)\n\n\nrepeat\n sentencia(s)\nuntil valor1\n\n\ndo\n sentencia(s)\nloop\n\n\nwhile expr_booleana\n sentencia(s)\nend while\n", "language": "Yabasic" }, { "code": "char x;\nif (x == 20)\n{\n doThis();\n}\nelse\n{\n doThat();\n}\n", "language": "Z80-Assembly" }, { "code": "cp 20\njr nz,Else\n call doThis\n ;execution returns here after the call\n jr done\nElse:\n call doThat\ndone\n", "language": "Z80-Assembly" }, { "code": "if (x == 20)\n{\n DoSomething();\n}\n// rest of program\n", "language": "Z80-Assembly" }, { "code": "cp 20\ncall z,DoSomething\n;rest of program\n", "language": "Z80-Assembly" }, { "code": "ld a,(HL) ;switch (HL)\n cp 1 ;case (1)\n jr nz,+ ;branch to next colon (note: not all assemblers support this syntax)\n call HL_EQUALS_1\n:\n cp 2 ;case (2)\n jr nz,+ ;branch to next colon\n call HL_EQUALS_2\n:\n cp 50\n jr nz,+\n call HL_EQUALS_50\n:\n ;rest of program\n", "language": "Z80-Assembly" }, { "code": "ld a,(HL) ;switch (HL)\n cp 1 ;case (1)\n jr nz,+ ;branch to next lone colon\n call HL_EQUALS_1\n jr done ;You could also write \"jr +++\"\n:\n cp 2 ;case (2)\n jr nz,+ ;branch to next lone colon\n call HL_EQUALS_2\n jr done ;you could also write \"jr ++\"\n:\n cp 50\n jr nz,+\n call HL_EQUALS_50\n:\ndone:\n ;rest of program\n", "language": "Z80-Assembly" }, { "code": "Dispatch: ;remember, you need to CALL this address for it to work properly. Otherwise your program will most likely crash.\nadd a ;this is a table of 16-bit values, so multiply the index by 2.\nld a,(hl) ;get the low byte of the function addr. you wish to call\npush af\n inc hl\n ld a,(hl) ;get the high byte of the function addr. you wish to call\n ld H,a ;store the high byte in H\npop af\nld L,a ;store the low byte in L\njp (HL) ;now you've jumped to the desired function. Its RET will return execution to the instruction just after \"CALL Dispatch\"\n", "language": "Z80-Assembly" }, { "code": "const std = @import(\"std\");\nconst builtin = @import(\"builtin\");\n\nfn printOpenSource(comptime is_open_source: bool) !void {\n if (is_open_source) {\n try std.io.getStdOut().writer().writeAll(\"Open source.\\n\");\n } else {\n try std.io.getStdOut().writer().writeAll(\"No open source.\\n\");\n }\n}\nfn printYesOpenSource() !void {\n try std.io.getStdOut().writer().writeAll(\"Open source.\\n\");\n}\nfn printNoOpenSource() !void {\n try std.io.getStdOut().writer().writeAll(\"No open source.\\n\");\n}\nconst fnProto = switch (builtin.zig_backend) {\n .stage1 => fn () anyerror!void,\n else => *const fn () anyerror!void,\n};\nconst Vtable = struct {\n fnptrs: [2]fnProto,\n};\n\n// dynamic dispatch: logic(this function) + vtable + data\nfn printBySelectedType(data: bool, vtable: Vtable) !void {\n if (data) {\n try @call(.{}, vtable.fnptrs[0], .{});\n } else {\n try @call(.{}, vtable.fnptrs[1], .{});\n }\n}\n\npub fn main() !void {\n // if-else\n if (true) {\n std.debug.assert(true);\n } else {\n std.debug.assert(false);\n }\n // comptime switch\n const open_source = comptime switch (builtin.os.tag) {\n .freestanding => true,\n .linux => true,\n .macos => false,\n .windows => false,\n else => unreachable,\n };\n // conditional compilation\n std.debug.assert(builtin.zig_backend != .stage2_llvm);\n // static dispatch (more complex examples work typically via comptime enums)\n try printOpenSource(open_source);\n // dynamic dispatch (runtime attach function pointer)\n var vtable = Vtable{\n .fnptrs = undefined,\n };\n // runtime-attach function pointers (dynamic dispatch)\n vtable.fnptrs[0] = printYesOpenSource;\n vtable.fnptrs[1] = printNoOpenSource;\n try printBySelectedType(open_source, vtable);\n\n // TODO Arithmetic if once https://github.com/ziglang/zig/issues/8220 is finished\n}\n", "language": "Zig" }, { "code": "if (x) y else z;\nif(a)b else if (c) else d; etc\nx:=(if (a) b else c);\n\na and b or c // usually the same as if(a) b else c, beware if b evals to False\n\nswitch(x){\n case(1){...}\n case(\"2\"){...} // matches anything\n case(a)[fallthrough]{...} // no break, no break has to be explicit\n case(b){...}\n else {...} // case a C's default, has to be at the end\n}\n", "language": "Zkl" } ]
Conditional-structures
[ { "code": "---\ncategory:\n- Matrices\nfrom: http://rosettacode.org/wiki/Conjugate_transpose\n", "language": "00-META" }, { "code": "Suppose that a [[matrix]] <big><math>M</math></big> contains [[Arithmetic/Complex|complex numbers]]. Then the [[wp:conjugate transpose|conjugate transpose]] of <math>M</math> is a matrix <math>M^H</math> containing the [[complex conjugate]]s of the [[matrix transposition]] of <math>M</math>.\n\n::: <big><math>(M^H)_{ji} = \\overline{M_{ij}}</math></big>\n\n\nThis means that row <big><math>j</math></big>, column <big><math>i</math></big> of the conjugate transpose equals the \n<br>complex conjugate of row <big><math>i</math></big>, column <big><math>j</math></big> of the original matrix.\n\n\nIn the next list, <big><math>M</math></big> must also be a square matrix.\n\n* A [[wp:Hermitian matrix|Hermitian matrix]] equals its own conjugate transpose: <math>M^H = M</math>.\n* A [[wp:normal matrix|normal matrix]] is commutative in [[matrix multiplication|multiplication]] with its conjugate transpose: <math>M^HM = MM^H</math>.\n* A [[wp:unitary matrix|unitary matrix]] has its [[inverse matrix|inverse]] equal to its conjugate transpose: <math>M^H = M^{-1}</math>. <br> This is true [[wikt:iff|iff]] <math>M^HM = I_n</math> and iff <math>MM^H = I_n</math>, where <math>I_n</math> is the identity matrix.\n\n\n<br>\n;Task:\nGiven some matrix of complex numbers, find its conjugate transpose. \n\nAlso determine if the matrix is a:\n::* Hermitian matrix,\n::* normal matrix, or \n::* unitary matrix.\n\n\n;See also:\n* MathWorld entry: [http://mathworld.wolfram.com/ConjugateTranspose.html conjugate transpose]\n* MathWorld entry: [http://mathworld.wolfram.com/HermitianMatrix.html Hermitian matrix]\n* MathWorld entry: [http://mathworld.wolfram.com/NormalMatrix.html normal matrix]\n* MathWorld entry: [http://mathworld.wolfram.com/UnitaryMatrix.html unitary matrix]\n<br><br>\n\n", "language": "00-TASK" }, { "code": "-V eps = 1e-10\n\nF to_str(m)\n V r = ‘’\n L(row) m\n V i = L.index\n r ‘’= I i == 0 {‘[’} E ‘ ’\n L(val) row\n V j = L.index\n I j != 0\n r ‘’= ‘ ’\n r ‘’= ‘(#2.4, #2.4)’.format(val.real, val.imag)\n r ‘’= I i == m.len - 1 {‘]’} E \"\\n\"\n R r\n\nF conjugateTransposed(m)\n V r = [[0i] * m.len] * m.len\n L(i) 0 .< m.len\n L(j) 0 .< m.len\n r[j][i] = conjugate(m[i][j])\n R r\n\nF mmul(m1, m2)\n V r = [[0i] * m1.len] * m1.len\n L(i) 0 .< m1.len\n L(j) 0 .< m1.len\n L(k) 0 .< m1.len\n r[i][j] += m1[i][k] * m2[k][j]\n R r\n\nF isHermitian(m)\n L(i) 0 .< m.len\n L(j) 0 .< m.len\n I m[i][j] != conjugate(m[j][i])\n R 0B\n R 1B\n\nF isEqual(m1, m2)\n L(i) 0 .< m1.len\n L(j) 0 .< m1.len\n I m1[i][j] != m2[i][j]\n R 0B\n R 1B\n\nF isNormal(m)\n V h = conjugateTransposed(m)\n R isEqual(mmul(m, h), mmul(h, m))\n\nF isIdentity(m)\n L(i) 0 .< m.len\n L(j) 0 .< m.len\n I i == j\n I abs(m[i][j] - 1.0) > :eps\n R 0B\n E\n I abs(m[i][j]) > :eps\n R 0B\n R 1B\n\nF isUnitary(m)\n V h = conjugateTransposed(m)\n R isIdentity(mmul(m, h)) & isIdentity(mmul(h, m))\n\nF test(m)\n print(‘Matrix’)\n print(‘------’)\n print(to_str(m))\n print(‘’)\n print(‘Conjugate transposed’)\n print(‘--------------------’)\n print(to_str(conjugateTransposed(m)))\n print(‘’)\n print(‘Hermitian: ’(I isHermitian(m) {‘true’} E ‘false’))\n print(‘Normal: ’(I isNormal(m) {‘true’} E ‘false’))\n print(‘Unitary: ’(I isUnitary(m) {‘true’} E ‘false’))\n\nV M2 = [[3.0 + 0.0i, 2.0 + 1.0i],\n [2.0 - 1.0i, 1.0 + 0.0i]]\n\nV M3 = [[1.0 + 0.0i, 1.0 + 0.0i, 0.0 + 0.0i],\n [0.0 + 0.0i, 1.0 + 0.0i, 1.0 + 0.0i],\n [1.0 + 0.0i, 0.0 + 0.0i, 1.0 + 0.0i]]\n\nV SR2 = 1 / sqrt(2.0)\nV SR2i = SR2 * 1i\nV M4 = [[SR2 + 0.0i, SR2 + 0.0i, 0.0 + 0.0i],\n [0.0 + SR2i, 0.0 - SR2i, 0.0 + 0.0i],\n [0.0 + 0.0i, 0.0 + 0.0i, 0.0 + 1.0i]]\n\ntest(M2)\nprint(\"\\n\")\ntest(M3)\nprint(\"\\n\")\ntest(M4)\n", "language": "11l" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Complex_Text_IO; use Ada.Complex_Text_IO;\nwith Ada.Numerics.Complex_Types; use Ada.Numerics.Complex_Types;\nwith Ada.Numerics.Complex_Arrays; use Ada.Numerics.Complex_Arrays;\nprocedure ConTrans is\n subtype CM is Complex_Matrix;\n S2O2 : constant Float := 0.7071067811865;\n\n procedure Print (mat : CM) is begin\n for row in mat'Range(1) loop for col in mat'Range(2) loop\n Put(mat(row,col), Exp=>0, Aft=>4);\n end loop; New_Line; end loop;\n end Print;\n\n function almostzero(mat : CM; tol : Float) return Boolean is begin\n for row in mat'Range(1) loop for col in mat'Range(2) loop\n if abs(mat(row,col)) > tol then return False; end if;\n end loop; end loop;\n return True;\n end almostzero;\n\n procedure Examine (mat : CM) is\n CT : CM := Conjugate (Transpose(mat));\n isherm, isnorm, isunit : Boolean;\n begin\n isherm := almostzero(mat-CT, 1.0e-6);\n isnorm := almostzero(mat*CT-CT*mat, 1.0e-6);\n isunit := almostzero(CT-Inverse(mat), 1.0e-6);\n Print(mat);\n Put_Line(\"Conjugate transpose:\"); Print(CT);\n Put_Line(\"Hermitian?: \" & isherm'Img);\n Put_Line(\"Normal?: \" & isnorm'Img);\n Put_Line(\"Unitary?: \" & isunit'Img);\n end Examine;\n\n hmat : CM := ((3.0+0.0*i, 2.0+1.0*i), (2.0-1.0*i, 1.0+0.0*i));\n nmat : CM := ((1.0+0.0*i, 1.0+0.0*i, 0.0+0.0*i),\n (0.0+0.0*i, 1.0+0.0*i, 1.0+0.0*i),\n (1.0+0.0*i, 0.0+0.0*i, 1.0+0.0*i));\n umat : CM := ((S2O2+0.0*i, S2O2+0.0*i, 0.0+0.0*i),\n (0.0+S2O2*i, 0.0-S2O2*i, 0.0+0.0*i),\n (0.0+0.0*i, 0.0+0.0*i, 0.0+1.0*i));\nbegin\n Put_Line(\"hmat:\"); Examine(hmat); New_Line;\n Put_Line(\"nmat:\"); Examine(nmat); New_Line;\n Put_Line(\"umat:\"); Examine(umat);\nend ConTrans;\n", "language": "Ada" }, { "code": "BEGIN # find and classify the complex conjugate transpose of a complex matrix #\n # returns the conjugate transpose of m #\n OP CONJUGATETRANSPOSE = ( [,]COMPL m )[,]COMPL:\n BEGIN\n [ 2 LWB m : 2 UPB m, 1 LWB m : 1 UPB m ]COMPL result;\n FOR i FROM 1 LWB m TO 1 UPB m DO\n FOR j FROM 2 LWB m TO 2 UPB m DO\n result[ j, i ] := CONJ m[ i, j ]\n OD\n OD;\n result\n END # CONJUGATETRANSPOSE # ;\n # returns TRUE if m is an identity matrix, FALSE otherwise #\n OP ISIDENTITY = ( [,]COMPL m )BOOL:\n IF 1 LWB m /= 2 LWB m OR 1 UPB m /= 2 UPB m THEN\n # non-square matrix #\n FALSE\n ELSE\n # the matrix is square #\n # returns TRUE IF v - e is nearly 0, FALSE Otherwise #\n PROC nearly equal = ( COMPL v, REAL e )BOOL: ABS re OF v - e < 1e-14 AND ABS im OF v < 1e-14;\n BOOL result := TRUE;\n FOR i FROM 1 LWB m TO 1 UPB m WHILE result DO\n IF result := nearly equal( m[ i, i ], 1 ) THEN\n # the diagonal element is 1 - test the non-diagonals #\n FOR j FROM 1 LWB m TO 1 UPB m WHILE result DO\n IF i /= j THEN result := nearly equal( m[ i, j ], 0 ) FI\n OD\n FI\n OD;\n result\n FI # ISIDENTITY # ;\n # returns m multiplied by n #\n PRIO X = 7;\n OP X = ( [,]COMPL m, n )[,]COMPL:\n BEGIN\n [ 1 : 1 UPB m, 1 : 2 UPB n ]COMPL r;\n FOR i FROM 1 LWB m TO 1 UPB m DO\n FOR j FROM 2 LWB n TO 2 UPB n DO\n r[ i, j ] := 0;\n FOR k TO 2 UPB n DO\n r[ i, j ] +:= m[ i, k ] * n[ k, j ]\n OD\n OD\n OD;\n r\n END # X # ;\n # prints the complex matris m #\n PROC show matrix = ( [,]COMPL m )VOID:\n FOR i FROM 1 LWB m TO 1 UPB m DO\n print( ( \" \" ) );\n FOR j FROM 2 LWB m TO 2 UPB m DO\n print( ( \"( \", fixed( re OF m[ i, j ], -8, 4 )\n , \", \", fixed( im OF m[ i, j ], -8, 4 )\n , \"i )\"\n )\n )\n OD;\n print( ( newline ) )\n OD # show matrix # ;\n # display the matrix m, its conjugate transpose and whether it is Hermitian, Normal and Unitary #\n PROC show = ( [,]COMPL m )VOID:\n BEGIN\n [,]COMPL c = CONJUGATETRANSPOSE m;\n [,]COMPL cm = c X m;\n [,]COMPL mc = m X c;\n print( ( \"Matrix:\", newline ) );\n show matrix( m );\n print( ( \"Conjugate Transpose:\", newline ) );\n show matrix( c );\n BOOL is normal = cm = mc;\n BOOL is unitary = IF NOT is normal THEN FALSE\n ELSE ISIDENTITY mc\n FI;\n print( ( IF c = m THEN \"\" ELSE \"not \" FI, \"Hermitian; \"\n , IF is normal THEN \"\" ELSE \"not \" FI, \"Normal; \"\n , IF is unitary THEN \"\" ELSE \"not \" FI, \"Unitary\"\n , newline\n )\n );\n print( ( newline ) )\n END # show # ;\n # test some matrices for Hermitian, Normal and Unitary #\n show( ( ( ( 3.0000 I 0.0000 ), ( 2.0000 I 1.0000 ) )\n , ( ( 2.0000 I -1.0000 ), ( 1.0000 I 0.0000 ) )\n )\n );\n show( ( ( ( 1.0000 I 0.0000 ), ( 1.0000 I 0.0000 ), ( 0.0000 I 0.0000 ) )\n , ( ( 0.0000 I 0.0000 ), ( 1.0000 I 0.0000 ), ( 1.0000 I 0.0000 ) )\n , ( ( 1.0000 I 0.0000 ), ( 0.0000 I 0.0000 ), ( 1.0000 I 0.0000 ) )\n )\n );\n REAL rh = sqrt( 0.5 );\n show( ( ( ( rh I 0.0000 ), ( rh I 0.0000 ), ( 0.0000 I 0.0000 ) )\n , ( ( 0.0000 I rh ), ( 0.0000 I - rh ), ( 0.0000 I 0.0000 ) )\n , ( ( 0.0000 I 0.0000 ), ( 0.0000 I 0.0000 ), ( 0.0000 I 1.0000 ) )\n )\n )\nEND\n", "language": "ALGOL-68" }, { "code": "/* Uses C99 specified complex.h, complex datatype has to be defined and operation provided if used on non-C99 compilers */\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<complex.h>\n\ntypedef struct\n{\n int rows, cols;\n complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n int i, j;\n matrix b;\n\n b.rows = a.cols;\n b.cols = a.rows;\n\n b.z = malloc (b.rows * sizeof (complex *));\n\n for (i = 0; i < b.rows; i++)\n {\n b.z[i] = malloc (b.cols * sizeof (complex));\n for (j = 0; j < b.cols; j++)\n {\n b.z[i][j] = conj (a.z[j][i]);\n }\n }\n\n return b;\n}\n\nint\nisHermitian (matrix a)\n{\n int i, j;\n matrix b = transpose (a);\n\n if (b.rows == a.rows && b.cols == a.cols)\n {\n for (i = 0; i < b.rows; i++)\n {\n for (j = 0; j < b.cols; j++)\n {\n if (b.z[i][j] != a.z[i][j])\n return 0;\n }\n }\n }\n\n else\n return 0;\n\n return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n matrix c;\n int i, j;\n\n if (a.cols == b.rows)\n {\n c.rows = a.rows;\n c.cols = b.cols;\n\n c.z = malloc (c.rows * (sizeof (complex *)));\n\n for (i = 0; i < c.rows; i++)\n {\n c.z[i] = malloc (c.cols * sizeof (complex));\n c.z[i][j] = 0 + 0 * I;\n for (j = 0; j < b.cols; j++)\n {\n c.z[i][j] += a.z[i][j] * b.z[j][i];\n }\n }\n\n }\n\n return c;\n}\n\nint\nisNormal (matrix a)\n{\n int i, j;\n matrix a_ah, ah_a;\n\n if (a.rows != a.cols)\n return 0;\n\n a_ah = multiply (a, transpose (a));\n ah_a = multiply (transpose (a), a);\n\n for (i = 0; i < a.rows; i++)\n {\n for (j = 0; j < a.cols; j++)\n {\n if (a_ah.z[i][j] != ah_a.z[i][j])\n return 0;\n }\n }\n\n return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n matrix b;\n int i, j;\n if (isNormal (a) == 1)\n {\n b = multiply (a, transpose(a));\n\n for (i = 0; i < b.rows; i++)\n {\n for (j = 0; j < b.cols; j++)\n {\n if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n return 0;\n }\n }\n return 1;\n }\n return 0;\n}\n\n\nint\nmain ()\n{\n complex z = 3 + 4 * I;\n matrix a, aT;\n int i, j;\n printf (\"Enter rows and columns :\");\n scanf (\"%d%d\", &a.rows, &a.cols);\n\n a.z = malloc (a.rows * sizeof (complex *));\n printf (\"Randomly Generated Complex Matrix A is : \");\n for (i = 0; i < a.rows; i++)\n {\n printf (\"\\n\");\n a.z[i] = malloc (a.cols * sizeof (complex));\n for (j = 0; j < a.cols; j++)\n {\n a.z[i][j] = rand () % 10 + rand () % 10 * I;\n printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n }\n }\n\n aT = transpose (a);\n\n printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n for (i = 0; i < aT.rows; i++)\n {\n printf (\"\\n\");\n aT.z[i] = malloc (aT.cols * sizeof (complex));\n for (j = 0; j < aT.cols; j++)\n {\n aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n }\n }\n\n printf (\"\\n\\nComplex Matrix A %s hermitian\",\n isHermitian (a) == 1 ? \"is\" : \"is not\");\n printf (\"\\n\\nComplex Matrix A %s unitary\",\n isUnitary (a) == 1 ? \"is\" : \"is not\");\n printf (\"\\n\\nComplex Matrix A %s normal\",\n isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class complex_matrix {\npublic:\n using element_type = std::complex<scalar_type>;\n\n complex_matrix(size_t rows, size_t columns)\n : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n complex_matrix(size_t rows, size_t columns, element_type value)\n : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n complex_matrix(size_t rows, size_t columns,\n const std::initializer_list<std::initializer_list<element_type>>& values)\n : rows_(rows), columns_(columns), elements_(rows * columns) {\n assert(values.size() <= rows_);\n size_t i = 0;\n for (const auto& row : values) {\n assert(row.size() <= columns_);\n std::copy(begin(row), end(row), &elements_[i]);\n i += columns_;\n }\n }\n\n size_t rows() const { return rows_; }\n size_t columns() const { return columns_; }\n\n const element_type& operator()(size_t row, size_t column) const {\n assert(row < rows_);\n assert(column < columns_);\n return elements_[row * columns_ + column];\n }\n element_type& operator()(size_t row, size_t column) {\n assert(row < rows_);\n assert(column < columns_);\n return elements_[row * columns_ + column];\n }\n\n friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n a.elements_ == b.elements_;\n }\n\nprivate:\n size_t rows_;\n size_t columns_;\n std::vector<element_type> elements_;\n};\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,\n const complex_matrix<scalar_type>& b) {\n assert(a.columns() == b.rows());\n size_t arows = a.rows();\n size_t bcolumns = b.columns();\n size_t n = a.columns();\n complex_matrix<scalar_type> c(arows, bcolumns);\n for (size_t i = 0; i < arows; ++i) {\n for (size_t j = 0; j < n; ++j) {\n for (size_t k = 0; k < bcolumns; ++k)\n c(i, k) += a(i, j) * b(j, k);\n }\n }\n return c;\n}\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type>\nconjugate_transpose(const complex_matrix<scalar_type>& a) {\n size_t rows = a.rows(), columns = a.columns();\n complex_matrix<scalar_type> b(columns, rows);\n for (size_t i = 0; i < columns; i++) {\n for (size_t j = 0; j < rows; j++) {\n b(i, j) = std::conj(a(j, i));\n }\n }\n return b;\n}\n\ntemplate <typename scalar_type>\nstd::string to_string(const std::complex<scalar_type>& c) {\n std::ostringstream out;\n const int precision = 6;\n out << std::fixed << std::setprecision(precision);\n out << std::setw(precision + 3) << c.real();\n if (c.imag() > 0)\n out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n else if (c.imag() == 0)\n out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n else\n out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n return out.str();\n}\n\ntemplate <typename scalar_type>\nvoid print(std::ostream& out, const complex_matrix<scalar_type>& a) {\n size_t rows = a.rows(), columns = a.columns();\n for (size_t row = 0; row < rows; ++row) {\n for (size_t column = 0; column < columns; ++column) {\n if (column > 0)\n out << ' ';\n out << to_string(a(row, column));\n }\n out << '\\n';\n }\n}\n\ntemplate <typename scalar_type>\nbool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {\n if (matrix.rows() != matrix.columns())\n return false;\n return matrix == conjugate_transpose(matrix);\n}\n\ntemplate <typename scalar_type>\nbool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {\n if (matrix.rows() != matrix.columns())\n return false;\n auto c = conjugate_transpose(matrix);\n return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex<double>& a, double b) {\n constexpr double e = 1e-15;\n return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate <typename scalar_type>\nbool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {\n if (matrix.rows() != matrix.columns())\n return false;\n size_t rows = matrix.rows();\n for (size_t i = 0; i < rows; ++i) {\n for (size_t j = 0; j < rows; ++j) {\n if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n return false;\n }\n }\n return true;\n}\n\ntemplate <typename scalar_type>\nbool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {\n if (matrix.rows() != matrix.columns())\n return false;\n auto c = conjugate_transpose(matrix);\n auto p = product(c, matrix);\n return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate <typename scalar_type>\nvoid test(const complex_matrix<scalar_type>& matrix) {\n std::cout << \"Matrix:\\n\";\n print(std::cout, matrix);\n std::cout << \"Conjugate transpose:\\n\";\n print(std::cout, conjugate_transpose(matrix));\n std::cout << std::boolalpha;\n std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n using matrix = complex_matrix<double>;\n\n matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n {{2, -1}, {3, 0}, {0, 1}},\n {{4, 0}, {0, -1}, {1, 0}}});\n\n double n = std::sqrt(0.5);\n matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n {{0, -n}, {0, n}, {0, 0}},\n {{0, 0}, {0, 0}, {0, 1}}});\n\n matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n {{2, -1}, {4, 1}, {0, 0}},\n {{7, -5}, {1, -4}, {1, 0}}});\n\n test(matrix1);\n std::cout << '\\n';\n test(matrix2);\n std::cout << '\\n';\n test(matrix3);\n return 0;\n}\n", "language": "C++" }, { "code": "(defun matrix-multiply (m1 m2)\n (mapcar\n (lambda (row)\n (apply #'mapcar\n (lambda (&rest column)\n (apply #'+ (mapcar #'* row column))) m2)) m1))\n\n(defun identity-p (m &optional (tolerance 1e-6))\n \"Is m an identity matrix?\"\n (loop for row in m\n for r = 1 then (1+ r) do\n (loop for col in row\n for c = 1 then (1+ c) do\n (if (eql r c)\n (unless (< (abs (- col 1)) tolerance) (return-from identity-p nil))\n (unless (< (abs col) tolerance) (return-from identity-p nil)) )))\n T )\n\n(defun conjugate-transpose (m)\n (apply #'mapcar #'list (mapcar #'(lambda (r) (mapcar #'conjugate r)) m)) )\n\n(defun hermitian-p (m)\n (equalp m (conjugate-transpose m)))\n\n(defun normal-p (m)\n (let ((m* (conjugate-transpose m)))\n (equalp (matrix-multiply m m*) (matrix-multiply m* m)) ))\n\n(defun unitary-p (m)\n (identity-p (matrix-multiply m (conjugate-transpose m))) )\n", "language": "Common-Lisp" }, { "code": "import std.stdio, std.complex, std.math, std.range, std.algorithm,\n std.numeric;\n\nT[][] conjugateTranspose(T)(in T[][] m) pure nothrow @safe {\n auto r = new typeof(return)(m[0].length, m.length);\n foreach (immutable nr, const row; m)\n foreach (immutable nc, immutable c; row)\n r[nc][nr] = c.conj;\n return r;\n}\n\nbool isRectangular(T)(in T[][] M) pure nothrow @safe @nogc {\n return M.all!(row => row.length == M[0].length);\n}\n\nT[][] matMul(T)(in T[][] A, in T[][] B) pure nothrow /*@safe*/\nin {\n assert(A.isRectangular && B.isRectangular &&\n !A.empty && !B.empty && A[0].length == B.length);\n} body {\n auto result = new T[][](A.length, B[0].length);\n auto aux = new T[B.length];\n\n foreach (immutable j; 0 .. B[0].length) {\n foreach (immutable k, const row; B)\n aux[k] = row[j];\n foreach (immutable i, const ai; A)\n result[i][j] = dotProduct(ai, aux);\n }\n\n return result;\n}\n\n/// Check any number of complex matrices for equality within\n/// some bits of mantissa.\nbool areEqual(T)(in Complex!T[][][] matrices, in size_t nBits=20)\npure nothrow /*@safe*/ {\n static bool allSame(U)(in U[] v) pure nothrow @nogc {\n return v[1 .. $].all!(c => c == v[0]);\n }\n\n bool allNearSame(in Complex!T[] v) pure nothrow @nogc {\n auto v0 = v[0].Complex!T; // To avoid another cast.\n return v[1 .. $].all!(c => feqrel(v0.re, c.re) >= nBits &&\n feqrel(v0.im, c.im) >= nBits);\n }\n\n immutable x = matrices.map!(m => m.length).array;\n if (!allSame(x))\n return false;\n immutable y = matrices.map!(m => m[0].length).array;\n if (!allSame(y))\n return false;\n foreach (immutable s; 0 .. x[0])\n foreach (immutable t; 0 .. y[0])\n if (!allNearSame(matrices.map!(m => m[s][t]).array))\n return false;\n return true;\n}\n\nbool isHermitian(T)(in Complex!T[][] m, in Complex!T[][] ct)\npure nothrow /*@safe*/ {\n return [m, ct].areEqual;\n}\n\nbool isNormal(T)(in Complex!T[][] m, in Complex!T[][] ct)\npure nothrow /*@safe*/ {\n return [matMul(m, ct), matMul(ct, m)].areEqual;\n}\n\nauto complexIdentitymatrix(in size_t side) pure nothrow /*@safe*/ {\n return side.iota.map!(r => side.iota.map!(c => complex(r == c)).array).array;\n}\n\nbool isUnitary(T)(in Complex!T[][] m, in Complex!T[][] ct)\npure nothrow /*@safe*/ {\n immutable mct = matMul(m, ct);\n immutable ident = mct.length.complexIdentitymatrix;\n return [mct, matMul(ct, m), ident].areEqual;\n}\n\nvoid main() /*@safe*/ {\n alias C = complex;\n immutable x = 2 ^^ 0.5 / 2;\n\n immutable data = [[[C(3.0, 0.0), C(2.0, 1.0)],\n [C(2.0, -1.0), C(1.0, 0.0)]],\n\n [[C(1.0, 0.0), C(1.0, 0.0), C(0.0, 0.0)],\n [C(0.0, 0.0), C(1.0, 0.0), C(1.0, 0.0)],\n [C(1.0, 0.0), C(0.0, 0.0), C(1.0, 0.0)]],\n\n [[C(x, 0.0), C(x, 0.0), C(0.0, 0.0)],\n [C(0.0, -x), C(0.0, x), C(0.0, 0.0)],\n [C(0.0, 0.0), C(0.0, 0.0), C(0.0, 1.0)]]];\n\n foreach (immutable mat; data) {\n enum mFormat = \"[%([%(%1.3f, %)],\\n %)]]\";\n writefln(\"Matrix:\\n\" ~ mFormat, mat);\n immutable ct = conjugateTranspose(mat);\n \"Its conjugate transpose:\".writeln;\n writefln(mFormat, ct);\n writefln(\"Hermitian? %s.\", isHermitian(mat, ct));\n writefln(\"Normal? %s.\", isNormal(mat, ct));\n writefln(\"Unitary? %s.\\n\", isUnitary(mat, ct));\n }\n}\n", "language": "D" }, { "code": "import std.stdio, std.complex, std.math, std.range, std.algorithm,\n std.numeric, std.exception, std.traits;\n\n// alias CM(T) = Complex!T[][]; // Not yet useful.\n\nauto conjugateTranspose(T)(in Complex!T[][] m) pure nothrow /*@safe*/\nif (!hasIndirections!T) {\n return iota(m[0].length).map!(i => m.transversal(i).map!conj.array).array;\n}\n\nT[][] matMul(T)(immutable T[][] A, immutable T[][] B) pure nothrow /*@safe*/ {\n immutable Bt = B[0].length.iota.map!(i => B.transversal(i).array).array;\n return A.map!(a => Bt.map!(b => a.dotProduct(b)).array).array;\n}\n\n/// Check any number of complex matrices for equality within\n/// some bits of mantissa.\nbool areEqual(T)(in Complex!T[][][] matrices, in size_t nBits=20)\npure nothrow /*@safe*/ {\n static bool allSame(U)(in U[] v) pure nothrow @nogc @safe {\n return v[1 .. $].all!(c => c == v[0]);\n }\n\n bool allNearSame(in Complex!T[] v) pure nothrow @nogc @safe {\n auto v0 = v[0].Complex!T; // To avoid another cast.\n return v[1 .. $].all!(c => feqrel(v0.re, c.re) >= nBits &&\n feqrel(v0.im, c.im) >= nBits);\n }\n\n immutable x = matrices.map!(m => m.length).array;\n if (!allSame(x))\n return false;\n immutable y = matrices.map!(m => m[0].length).array;\n if (!allSame(y))\n return false;\n foreach (immutable s; 0 .. x[0])\n foreach (immutable t; 0 .. y[0])\n if (!allNearSame(matrices.map!(m => m[s][t]).array))\n return false;\n return true;\n}\n\nbool isHermitian(T)(in Complex!T[][] m, in Complex!T[][] ct)\npure nothrow /*@safe*/ {\n return [m, ct].areEqual;\n}\n\nbool isNormal(T)(immutable Complex!T[][] m, immutable Complex!T[][] ct)\npure nothrow /*@safe*/ {\n return [matMul(m, ct), matMul(ct, m)].areEqual;\n}\n\nauto complexIdentitymatrix(in size_t side) pure nothrow /*@safe*/ {\n return side.iota.map!(r => side.iota.map!(c => complex(r == c)).array).array;\n}\n\nbool isUnitary(T)(immutable Complex!T[][] m, immutable Complex!T[][] ct)\npure nothrow /*@safe*/ {\n immutable mct = matMul(m, ct);\n immutable ident = mct.length.complexIdentitymatrix;\n return [mct, matMul(ct, m), ident].areEqual;\n}\n\nvoid main() {\n alias C = complex;\n immutable x = 2 ^^ 0.5 / 2;\n\n foreach (/*immutable*/ const matrix;\n [[[C(3.0, 0.0), C(2.0, 1.0)],\n [C(2.0, -1.0), C(1.0, 0.0)]],\n\n [[C(1.0, 0.0), C(1.0, 0.0), C(0.0, 0.0)],\n [C(0.0, 0.0), C(1.0, 0.0), C(1.0, 0.0)],\n [C(1.0, 0.0), C(0.0, 0.0), C(1.0, 0.0)]],\n\n [[C(x, 0.0), C(x, 0.0), C(0.0, 0.0)],\n [C(0.0, -x), C(0.0, x), C(0.0, 0.0)],\n [C(0.0, 0.0), C(0.0, 0.0), C(0.0, 1.0)]]]) {\n immutable mat = matrix.assumeUnique; //*\n\n enum mFormat = \"[%([%(%1.3f, %)],\\n %)]]\";\n writefln(\"Matrix:\\n\" ~ mFormat, mat);\n immutable ct = conjugateTranspose(mat);\n \"Its conjugate transpose:\".writeln;\n writefln(mFormat, ct);\n writefln(\"Hermitian? %s.\", isHermitian(mat, ct));\n writefln(\"Normal? %s.\", isNormal(mat, ct));\n writefln(\"Unitary? %s.\\n\", isUnitary(mat, ct));\n }\n}\n", "language": "D" }, { "code": "// Conjugate transpose. Nigel Galloway: January 10th., 2022\nlet fN g=let g=g|>List.map(List.map(fun(n,g)->System.Numerics.Complex(n,g)))|>MathNet.Numerics.LinearAlgebra.MatrixExtensions.matrix in (g,g.ConjugateTranspose())\nlet fG n g=(MathNet.Numerics.LinearAlgebra.Matrix.inverse n-g)|>MathNet.Numerics.LinearAlgebra.Matrix.forall(fun(n:System.Numerics.Complex)->abs n.Real<1e-14&&abs n.Imaginary<1e-14)\nlet test=[fN [[(3.0,0.0);(2.0,1.0)];[(2.0,-1.0);(1.0,0.0)]];fN [[(1.0,0.0);(1.0,0.0);(0.0,0.0)];[(0.0,0.0);(1.0,0.0);(1.0,0.0)];[(1.0,0.0);(0.0,0.0);(1.0,0.0)]];fN [[(1.0/sqrt 2.0,0.0);(1.0/sqrt 2.0,0.0);(0.0,0.0)];[(0.0,1.0/sqrt 2.0);(0.0,-1.0/sqrt 2.0);(0.0,0.0)];[(0.0,0.0);(0.0,0.0);(0.0,1.0)]]]\ntest|>List.iter(fun(n,g)->printfn $\"Matrix\\n------\\n%A{n}\\nConjugate transposed\\n--------------------\\n%A{g}\\nIs hermitian: %A{n.IsHermitian()}\\nIs normal: %A{n*g=g*n}\\nIs unitary: %A{fG n g}\\n\")\n", "language": "F-Sharp" }, { "code": "USING: kernel math.functions math.matrices sequences ;\nIN: rosetta.hermitian\n\n: conj-t ( matrix -- conjugate-transpose )\n flip [ [ conjugate ] map ] map ;\n\n: hermitian-matrix? ( matrix -- ? )\n dup conj-t = ;\n\n: normal-matrix? ( matrix -- ? )\n dup conj-t [ m. ] [ swap m. ] 2bi = ;\n\n: unitary-matrix? ( matrix -- ? )\n [ dup conj-t m. ] [ length identity-matrix ] bi = ;\n", "language": "Factor" }, { "code": "program conjugate_transpose\n\n complex, dimension(3, 3) :: a\n integer :: i\n a = reshape((/ (i, i=1,9) /), shape(a))\n call characterize(a)\n a(:2,:2) = reshape((/cmplx(3,0),cmplx(2,-1),cmplx(2,1),cmplx(1,0)/),(/2,2/))\n call characterize(a(:2,:2))\n call characterize(cmplx(reshape((/1,0,1,1,1,0,0,1,1/),(/3,3/)),0))\n a(3,:) = (/cmplx(0,0), cmplx(0,0), cmplx(0,1)/)*sqrt(2.0)\n a(2,:) = (/cmplx(0,-1),cmplx(0,1),cmplx(0,0)/)\n a(1,:) = (/1,1,0/)\n a = a * sqrt(2.0)/2.0\n call characterize(a)\n\ncontains\n\n subroutine characterize(a)\n complex, dimension(:,:), intent(in) :: a\n integer :: i, j\n do i=1, size(a,1)\n print *,(a(i, j), j=1,size(a,1))\n end do\n print *,'Is Hermitian? ',HermitianQ(a)\n print *,'Is normal? ',NormalQ(a)\n print *,'Unitary? ',UnitaryQ(a)\n print '(/)'\n end subroutine characterize\n\n function ct(a) result(b) ! return the conjugate transpose of a matrix\n complex, dimension(:,:), intent(in) :: a\n complex, dimension(size(a,1),size(a,1)) :: b\n b = conjg(transpose(a))\n end function ct\n\n function identity(n) result(b) ! return identity matrix\n integer, intent(in) :: n\n real, dimension(n,n) :: b\n integer :: i\n b = 0\n do i=1, n\n b(i,i) = 1\n end do\n end function identity\n\n logical function HermitianQ(a)\n complex, dimension(:,:), intent(in) :: a\n HermitianQ = all(a .eq. ct(a))\n end function HermitianQ\n\n logical function NormalQ(a)\n complex, dimension(:,:), intent(in) :: a\n NormalQ = all(matmul(ct(a),a) .eq. matmul(a,ct(a)))\n end function NormalQ\n\n logical function UnitaryQ(a)\n ! if A inverse equals A star\n ! then multiplying each side by A should result in the identity matrix\n ! Thus show that A times A star is sufficiently close to I .\n complex, dimension(:,:), intent(in) :: a\n UnitaryQ = all(abs(matmul(a,ct(a)) - identity(size(a,1))) .lt. 1e-6)\n end function UnitaryQ\n\nend program conjugate_transpose\n", "language": "Fortran" }, { "code": "'complex type and operators for it\ntype complex\n real as double\n imag as double\nend type\n\noperator + ( a as complex, b as complex ) as complex\n dim as complex r\n r.real = a.real + b.real\n r.imag = a.imag + b.imag\n return r\nend operator\n\noperator * ( a as complex, b as complex ) as complex\n dim as complex r\n r.real = a.real*b.real - a.imag*b.imag\n r.imag = a.real*b.imag + b.real*a.imag\n return r\nend operator\n\noperator = ( a as complex, b as complex ) as boolean\n if not a.real = b.real then return false\n if not a.imag = b.imag then return false\n return true\nend operator\n\nfunction complex_conjugate( a as complex ) as complex\n dim as complex r\n r.real = a.real\n r.imag = -a.imag\n return r\nend function\n\n'matrix type and operations for it\n'reuses code from the matrix multiplication task\ntype Matrix\n dim as complex m( any , any )\n declare constructor ( )\n declare constructor ( byval x as uinteger )\nend type\n\nconstructor Matrix ( )\nend constructor\n\nconstructor Matrix ( byval x as uinteger )\n redim this.m( x - 1 , x - 1 )\nend constructor\n\noperator * ( byref a as Matrix , byref b as Matrix ) as Matrix\n dim as Matrix ret\n dim as uinteger i, j, k\n redim ret.m( ubound( a.m , 1 ) , ubound( a.m , 1 ) )\n for i = 0 to ubound( a.m , 1 )\n for j = 0 to ubound( b.m , 2 )\n for k = 0 to ubound( b.m , 1 )\n ret.m( i , j ) += a.m( i , k ) * b.m( k , j )\n next k\n next j\n next i\n return ret\nend operator\n\nfunction conjugate_transpose( byref a as Matrix ) as Matrix\n dim as Matrix ret\n dim as uinteger i, j\n redim ret.m( ubound( a.m , 1 ) , ubound( a.m , 1 ) )\n for i = 0 to ubound( a.m , 1 )\n for j = 0 to ubound( a.m , 2 )\n ret.m( i, j ) = complex_conjugate(a.m( j, i ))\n next j\n next i\n return ret\nend function\n\n'tests if matrices are unitary, hermitian, or normal\n\noperator = (byref a as Matrix, byref b as matrix) as boolean\n dim as integer i, j\n if ubound(a.m, 1) <> ubound(b.m, 1) then return false\n for i = 0 to ubound( a.m , 1 )\n for j = 0 to ubound( a.m , 2 )\n if not a.m(i,j)=b.m(i,j) then return false\n next j\n next i\n return true\nend operator\n\nfunction is_identity( byref a as Matrix ) as boolean\n dim as integer i, j\n for i = 0 to ubound( a.m , 1 )\n for j = 0 to ubound( a.m , 2 )\n if i = j and ( not a.m(i,j).real = 1.0 or not a.m(i,j).imag = 0.0 ) then return false\n if i <> j and ( not a.m(i,j).real = 0.0 or not a.m(i,j).imag = 0.0 ) then return false\n next j\n next i\n return true\nend function\n\nfunction is_hermitian( byref a as Matrix ) as boolean\n if a = conjugate_transpose(a) then return true\n return false\nend function\n\nfunction is_normal( byref a as Matrix ) as boolean\n dim as Matrix aa = conjugate_transpose(a)\n if a*aa = aa*a then return true else return false\nend function\n\nfunction is_unitary( byref a as Matrix ) as boolean\n dim as Matrix aa = conjugate_transpose(a)\n if not is_identity( a*aa ) or not is_identity( aa*a ) then return false\n return true\nend function\n\n'''now some example matrices\ndim as Matrix A = Matrix(2) 'an identity matrix\nA.m(0,0).real = 1.0 : A.m(0,0).imag = 0.0 : A.m(0,1).real = 0.0 : A.m(0,1).imag = 0.0\nA.m(1,0).real = 0.0 : A.m(1,0).imag = 0.0 : A.m(1,1).real = 1.0 : A.m(1,1).imag = 0.0\n\ndim as Matrix B = Matrix(2) 'a hermitian matrix\nB.m(0,0).real = 1.0 : B.m(0,0).imag = 0.0 : B.m(0,1).real = 1.0 : B.m(0,1).imag = -1.0\nB.m(1,0).real = 1.0 : B.m(1,0).imag = 1.0 : B.m(1,1).real = 1.0 : B.m(1,1).imag = 0.0\n\ndim as Matrix C = Matrix(2) 'a random matrix\nC.m(0,0).real = rnd : C.m(0,0).imag = rnd : C.m(0,1).real = rnd : C.m(0,1).imag = rnd\nC.m(1,0).real = rnd : C.m(1,0).imag = rnd : C.m(1,1).real = rnd : C.m(1,1).imag = rnd\n\nprint is_hermitian(A), is_normal(A), is_unitary(A)\nprint is_hermitian(B), is_normal(B), is_unitary(B)\nprint is_hermitian(C), is_normal(C), is_unitary(C)\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/cmplx\"\n)\n\n// a type to represent matrices\ntype matrix struct {\n ele []complex128\n cols int\n}\n\n// conjugate transpose, implemented here as a method on the matrix type.\nfunc (m *matrix) conjTranspose() *matrix {\n r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}\n rx := 0\n for _, e := range m.ele {\n r.ele[rx] = cmplx.Conj(e)\n rx += r.cols\n if rx >= len(r.ele) {\n rx -= len(r.ele) - 1\n }\n }\n return r\n}\n\n// program to demonstrate capabilites on example matricies\nfunc main() {\n show(\"h\", matrixFromRows([][]complex128{\n {3, 2 + 1i},\n {2 - 1i, 1}}))\n\n show(\"n\", matrixFromRows([][]complex128{\n {1, 1, 0},\n {0, 1, 1},\n {1, 0, 1}}))\n\n show(\"u\", matrixFromRows([][]complex128{\n {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},\n {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},\n {0, 0, 1i}}))\n}\n\nfunc show(name string, m *matrix) {\n m.print(name)\n ct := m.conjTranspose()\n ct.print(name + \"_ct\")\n\n fmt.Println(\"Hermitian:\", m.equal(ct, 1e-14))\n\n mct := m.mult(ct)\n ctm := ct.mult(m)\n fmt.Println(\"Normal:\", mct.equal(ctm, 1e-14))\n\n i := eye(m.cols)\n fmt.Println(\"Unitary:\", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))\n}\n\n// two constructors\nfunc matrixFromRows(rows [][]complex128) *matrix {\n m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}\n for rx, row := range rows {\n copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)\n }\n return m\n}\n\nfunc eye(n int) *matrix {\n r := &matrix{make([]complex128, n*n), n}\n n++\n for x := 0; x < len(r.ele); x += n {\n r.ele[x] = 1\n }\n return r\n}\n\n// print method outputs matrix to stdout\nfunc (m *matrix) print(heading string) {\n fmt.Print(\"\\n\", heading, \"\\n\")\n for e := 0; e < len(m.ele); e += m.cols {\n fmt.Printf(\"%6.3f \", m.ele[e:e+m.cols])\n fmt.Println()\n }\n}\n\n// equal method uses ε to allow for floating point error.\nfunc (a *matrix) equal(b *matrix, ε float64) bool {\n for x, aEle := range a.ele {\n if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||\n math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {\n return false\n }\n }\n return true\n}\n\n// mult method taken from matrix multiply task\nfunc (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {\n m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}\n for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {\n for m2r0 := 0; m2r0 < m2.cols; m2r0++ {\n for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {\n m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]\n m1x++\n }\n m3x++\n }\n }\n return m3\n}\n", "language": "Go" }, { "code": "import Data.Complex (Complex(..), conjugate)\nimport Data.List (transpose)\n\ntype Matrix a = [[a]]\n\nmain :: IO ()\nmain =\n mapM_\n (\\a -> do\n putStrLn \"\\nMatrix:\"\n mapM_ print a\n putStrLn \"Conjugate Transpose:\"\n mapM_ print (conjTranspose a)\n putStrLn $ \"Hermitian? \" ++ show (isHermitianMatrix a)\n putStrLn $ \"Normal? \" ++ show (isNormalMatrix a)\n putStrLn $ \"Unitary? \" ++ show (isUnitaryMatrix a))\n ([ [[3, 2 :+ 1], [2 :+ (-1), 1]]\n , [[1, 1, 0], [0, 1, 1], [1, 0, 1]]\n , [ [sqrt 2 / 2 :+ 0, sqrt 2 / 2 :+ 0, 0]\n , [0 :+ sqrt 2 / 2, 0 :+ (-sqrt 2 / 2), 0]\n , [0, 0, 0 :+ 1]\n ]\n ] :: [Matrix (Complex Double)])\n\nisHermitianMatrix, isNormalMatrix, isUnitaryMatrix\n :: RealFloat a\n => Matrix (Complex a) -> Bool\nisHermitianMatrix = mTest id conjTranspose\n\nisNormalMatrix = mTest mmct (mmul =<< conjTranspose)\n\nisUnitaryMatrix = mTest mmct (ident . length)\n\nmTest\n :: RealFloat a\n => (a2 -> Matrix (Complex a)) -> (a2 -> Matrix (Complex a)) -> a2 -> Bool\nmTest f g = (approxEqualMatrix . f) <*> g\n\nmmct\n :: RealFloat a\n => Matrix (Complex a) -> Matrix (Complex a)\nmmct = mmul <*> conjTranspose\n\napproxEqualMatrix\n :: (Fractional a, Ord a)\n => Matrix (Complex a) -> Matrix (Complex a) -> Bool\napproxEqualMatrix a b =\n length a == length b &&\n length (head a) == length (head b) &&\n and (zipWith approxEqualComplex (concat a) (concat b))\n where\n approxEqualComplex (rx :+ ix) (ry :+ iy) =\n abs (rx - ry) < eps && abs (ix - iy) < eps\n eps = 1e-14\n\nmmul\n :: Num a\n => Matrix a -> Matrix a -> Matrix a\nmmul a b =\n [ [ sum (zipWith (*) row column)\n | column <- transpose b ]\n | row <- a ]\n\nident\n :: Num a\n => Int -> Matrix a\nident size =\n [ [ fromIntegral $ div a b * div b a\n | a <- [1 .. size] ]\n | b <- [1 .. size] ]\n\nconjTranspose\n :: Num a\n => Matrix (Complex a) -> Matrix (Complex a)\nconjTranspose = map (map conjugate) . transpose\n", "language": "Haskell" }, { "code": " ct =: +@|: NB. Conjugate transpose (ct A is A_ct)\n", "language": "J" }, { "code": " X =: +/ . * NB. Matrix Multiply (x)\n\n HERMITIAN =: 3 2j1 ,: 2j_1 1\n (-: ct) HERMITIAN NB. A_ct = A\n1\n\n NORMAL =: 1 1 0 , 0 1 1 ,: 1 0 1\n ((X~ -: X) ct) NORMAL NB. A_ct x A = A x A_ct\n1\n\n UNITARY =: (-:%:2) * 1 1 0 , 0j_1 0j1 0 ,: 0 0 0j1 * %:2\n (ct -: %.) UNITARY NB. A_ct = A^-1\n1\n", "language": "J" }, { "code": " HERMITIAN;NORMAL;UNITARY\n+--------+-----+--------------------------+\n| 3 2j1|1 1 0| 0.707107 0.707107 0|\n|2j_1 1|0 1 1|0j_0.707107 0j0.707107 0|\n| |1 0 1| 0 0 0j1|\n+--------+-----+--------------------------+\n NB. In J, PjQ is P + Q*i and the 0.7071... is sqrt(2)\n\n hermitian=: -: ct\n normal =: (X~ -: X) ct\n unitary=: ct -: %.\n\n (hermitian,normal,unitary)&.>HERMITIAN;NORMAL;UNITARY\n+-----+-----+-----+\n|1 1 0|0 1 0|0 1 1|\n+-----+-----+-----+\n", "language": "J" }, { "code": "import java.util.Arrays;\nimport java.util.List;\n\npublic final class ConjugateTranspose {\n\n\tpublic static void main(String[] aArgs) {\t\t\n\t\tComplexMatrix one = new ComplexMatrix( new Complex[][] { { new Complex(0, 4), new Complex(-1, 1) },\n\t\t\t\t\t\t\t\t\t\t\t { new Complex(1, -1), new Complex(0, 4) } } );\t\t\n\n\t\tComplexMatrix two = new ComplexMatrix(\n\t\t\tnew Complex[][] { { new Complex(1, 0), new Complex(1, 1), new Complex(0, 2) },\n\t\t\t \t\t\t { new Complex(1, -1), new Complex(5, 0), new Complex(-3, 0) },\n\t\t\t\t\t\t\t { new Complex(0, -2), new Complex(-3, 0), new Complex(0, 0) } } );\n\n\t\tfinal double term = 1.0 / Math.sqrt(2.0);\n\t\tComplexMatrix three = new ComplexMatrix( new Complex[][] { { new Complex(term, 0), new Complex(term, 0) },\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t { new Complex(0, term), new Complex(0, -term) } } );\n\t\t\n\t\tList<ComplexMatrix> matricies = List.of( one, two, three );\n\t\tfor ( ComplexMatrix matrix : matricies ) {\n\t\t\tSystem.out.println(\"Matrix:\");\n\t\t\tmatrix.display();\n\t\t\tSystem.out.println(\"Conjugate transpose:\");\n\t\t\tmatrix.conjugateTranspose().display();\n\t\t\tSystem.out.println(\"Hermitian: \" + matrix.isHermitian());\n\t\t\tSystem.out.println(\"Normal: \" + matrix.isNormal());\n\t\t\tSystem.out.println(\"Unitary: \" + matrix.isUnitary() + System.lineSeparator());\n\t\t}\n\t}\n\n}\n\nfinal class ComplexMatrix {\n\t\n\tpublic ComplexMatrix(Complex[][] aData) {\n\t\trowCount = aData.length;\n colCount = aData[0].length;\n data = Arrays.stream(aData).map( row -> Arrays.copyOf(row, row.length) ).toArray(Complex[][]::new);\n\t}\n\t\n\tpublic ComplexMatrix multiply(ComplexMatrix aOther) {\n if ( colCount != aOther.rowCount ) {\n \tthrow new RuntimeException(\"Incompatible matrix dimensions.\");\n }\n Complex[][] newData = new Complex[rowCount][aOther.colCount];\n Arrays.stream(newData).forEach( row -> Arrays.fill(row, new Complex(0, 0)) );\n for ( int row = 0; row < rowCount; row++ ) {\n for ( int col = 0; col < aOther.colCount; col++ ) {\n for ( int k = 0; k < colCount; k++ ) {\n newData[row][col] = newData[row][col].add(data[row][k].multiply(aOther.data[k][col]));\n }\n }\n }\n return new ComplexMatrix(newData);\n }\n\n public ComplexMatrix conjugateTranspose() {\n \tif ( rowCount != colCount ) {\n \t\tthrow new IllegalArgumentException(\"Only applicable to a square matrix\");\n \t} \t\n \tComplex[][] newData = new Complex[colCount][rowCount];\n for ( int row = 0; row < rowCount; row++ ) {\n for ( int col = 0; col < colCount; col++ ) {\n newData[col][row] = data[row][col].conjugate();\n }\n }\n return new ComplexMatrix(newData);\n }\n\n public static ComplexMatrix identity(int aSize) {\n \tComplex[][] data = new Complex[aSize][aSize];\n for ( int row = 0; row < aSize; row++ ) {\n \tfor ( int col = 0; col < aSize; col++ ) {\n \t\tdata[row][col] = ( row == col ) ? new Complex(1, 0) : new Complex(0, 0);\n \t}\n }\n return new ComplexMatrix(data);\n }\n\n public boolean equals(ComplexMatrix aOther) { \t\n if ( aOther.rowCount != rowCount || aOther.colCount != colCount ) {\n \treturn false;\n }\n for ( int row = 0; row < rowCount; row++ ) {\n for ( int col = 0; col < colCount; col++ ) {\n \tif ( data[row][col].subtract(aOther.data[row][col]).modulus() > EPSILON ) {\n \treturn false;\n }\n }\n }\n return true;\n }\n\n public void display() {\n for ( int row = 0; row < rowCount; row++ ) {\n \tSystem.out.print(\"[\");\n for ( int col = 0; col < colCount - 1; col++ ) {\n System.out.print(data[row][col] + \", \");\n }\n System.out.println(data[row][colCount - 1] + \" ]\");\n }\n }\n\n public boolean isHermitian() {\n \treturn equals(conjugateTranspose());\n }\n\n public boolean isNormal() {\n \tComplexMatrix conjugateTranspose = conjugateTranspose();\n \treturn multiply(conjugateTranspose).equals(conjugateTranspose.multiply(this));\n }\n\n public boolean isUnitary() {\n \tComplexMatrix conjugateTranspose = conjugateTranspose();\n \treturn multiply(conjugateTranspose).equals(identity(rowCount)) &&\n \t\t conjugateTranspose.multiply(this).equals(identity(rowCount));\n }\n\n private final int rowCount;\n private final int colCount;\n private final Complex[][] data;\n\n private static final double EPSILON = 0.000_000_000_001;\n\t\n}\n\nfinal class Complex {\n\t\n\tpublic Complex(double aReal, double aImag) {\n\t\treal = aReal;\n\t\timag = aImag;\n\t}\t\t\n\t\n\tpublic Complex add(Complex aOther) {\n\t\treturn new Complex(real + aOther.real, imag + aOther.imag);\n\t}\n\t\n\tpublic Complex multiply(Complex aOther) {\n\t\treturn new Complex(real * aOther.real - imag * aOther.imag, real * aOther.imag + imag * aOther.real);\n\t}\n\t\n\tpublic Complex negate() {\n\t\treturn new Complex(-real, -imag);\n\t}\n\t\n\tpublic Complex subtract(Complex aOther) {\n\t\treturn this.add(aOther.negate());\n\t}\n\t\n\tpublic Complex conjugate() {\n\t\treturn new Complex(real, -imag);\n\t}\n\t\t\n\tpublic double modulus() {\n\t\treturn Math.hypot(real, imag);\n\t}\n\t\n\tpublic boolean equals(Complex aOther) {\n\t\treturn real == aOther.real && imag == aOther.imag;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\tString prefix = ( real < 0.0 ) ? \"\" : \" \";\n\t\tString realPart = prefix + String.format(\"%.3f\", real);\n\t\tString sign = ( imag < 0.0 ) ? \" - \" : \" + \";\n\t\treturn realPart + sign + String.format(\"%.3f\", Math.abs(imag)) + \"i\";\n\t}\n\t\n\tprivate final double real;\n\tprivate final double imag;\n\t\n}\t\n", "language": "Java" }, { "code": "# transpose/0 expects its input to be a rectangular matrix\n# (an array of equal-length arrays):\ndef transpose:\n if (.[0] | length) == 0 then []\n else [map(.[0])] + (map(.[1:]) | transpose)\n end ;\n", "language": "Jq" }, { "code": "# x must be real or complex, and ditto for y;\n# always return complex\ndef plus(x; y):\n if (x|type) == \"number\" then\n if (y|type) == \"number\" then [ x+y, 0 ]\n else [ x + y[0], y[1]]\n end\n elif (y|type) == \"number\" then plus(y;x)\n else [ x[0] + y[0], x[1] + y[1] ]\n end;\n\n# x must be real or complex, and ditto for y;\n# always return complex\ndef multiply(x; y):\n if (x|type) == \"number\" then\n if (y|type) == \"number\" then [ x*y, 0 ]\n else [x * y[0], x * y[1]]\n end\n elif (y|type) == \"number\" then multiply(y;x)\n else [ x[0] * y[0] - x[1] * y[1], x[0] * y[1] + x[1] * y[0]]\n end;\n\n# conjugate of a real or complex number\ndef conjugate:\n if type == \"number\" then [.,0]\n else [.[0], -(.[1]) ]\n end;\n", "language": "Jq" }, { "code": "# a and b are arrays of real/complex numbers\ndef dot_product(a; b):\n a as $a | b as $b\n | reduce range(0;$a|length) as $i\n (0; . as $s | plus($s; multiply($a[$i]; $b[$i]) ));\n", "language": "Jq" }, { "code": "# convert a matrix of mixed real/complex entries to all complex entries\ndef to_complex:\n def toc: if type == \"number\" then [.,0] else . end;\n map( map(toc) );\n\n# simple matrix pretty-printer\ndef pp(wide):\n def pad: tostring | (wide - length) * \" \" + .;\n def row: reduce .[] as $x (\"\"; . + ($x|pad));\n reduce .[] as $row (\"\"; . + \"\\n\\($row|row)\");\n\n# Matrix multiplication\n# A and B should both be real/complex matrices,\n# A being m by n, and B being n by p.\ndef matrix_multiply(A; B):\n A as $A | B as $B\n | ($B[0]|length) as $p\n | ($B|transpose) as $BT\n | reduce range(0; $A|length) as $i\n ([]; reduce range(0; $p) as $j\n (.; .[$i][$j] = dot_product( $A[$i]; $BT[$j] ) )) ;\n\n# Complex identity matrix of dimension n\ndef complex_identity(n):\n def indicator(i;n): [range(0;n)] | map( [0,0]) | .[i] = [1,0];\n reduce range(0; n) as $i ([]; . + [indicator( $i; n )] );\n\n# Approximate equality of two matrices\n# Are two real/complex matrices essentially equal\n# in the sense that the sum of the squared element-wise differences\n# is less than or equal to epsilon?\n# The two matrices must be conformal.\ndef approximately_equal(M; N; epsilon):\n def norm: multiply(. ; conjugate ) | .[0];\n def sqdiff( x; y): plus(x; multiply(y; -1)) | norm;\n reduce range(0;M|length) as $i\n (0; reduce range(0; M[0]|length) as $j\n (.; 0 + sqdiff( M[$i][$j]; N[$i][$j] ) ) ) <= epsilon;\n", "language": "Jq" }, { "code": "# (entries may be real and/or complex)\ndef conjugate_transpose:\n map( map(conjugate) ) | transpose;\n\n# A Hermitian matrix equals its own conjugate transpose\ndef is_hermitian:\n to_complex == conjugate_transpose;\n\n# A matrix is normal if it commutes multiplicatively\n# with its conjugate transpose\ndef is_normal:\n . as $M\n | conjugate_transpose as $H\n | matrix_multiply($H; $M) == matrix_multiply($H; $M);\n\n# A unitary matrix (U) has its inverse equal to its conjugate transpose (T)\n# i.e. U^-1 == T; NASC is I == UT == TU\ndef is_unitary:\n . as $M\n | conjugate_transpose as $H\n | complex_identity(length) as $I\n | approximately_equal( $I; matrix_multiply($H;$M); 1e-10)\n and approximately_equal( $I ; matrix_multiply($M;$H); 1e-10) ;\n", "language": "Jq" }, { "code": "def hermitian_example:\n [ [ 3, [2,1]],\n [[2,-1], 1 ] ];\n\ndef normal_example:\n [ [1, 1, 0],\n [0, 1, 1],\n [1, 0, 1] ];\n\ndef unitary_example:\n 0.707107\n | [ [ [., 0], [., 0], 0 ],\n [ [0, -.], [0, .], 0 ],\n [ 0, 0, [0,1] ] ];\n\ndef demo:\n hermitian_example\n | (\"Hermitian example:\", pp(8)),\n \"\",\n (\"Its conjugate transpose is:\", (to_complex | conjugate_transpose | pp(8))),\n \"\",\n \"Hermitian example: \\(hermitian_example | is_hermitian )\",\n \"\",\n \"Normal example: \\(normal_example | is_normal )\",\n \"\",\n \"Unitary example: \\(unitary_example | is_unitary)\"\n;\n\ndemo\n", "language": "Jq" }, { "code": "$ jq -r -c -n -f Conjugate_transpose.jq\nHermitian example:\n\n 3 [2,1]\n [2,-1] 1\n\nConjugate transpose:\n\n [3,-0] [2,1]\n [2,-1] [1,-0]\n\nHermitian example: true\n\nNormal example: true\n\nUnitary example: true\n", "language": "Jq" }, { "code": "A'\n", "language": "Julia" }, { "code": "ishermitian(A)\n", "language": "Julia" }, { "code": "eye(A) = A^0\nisnormal(A) = size(A,1) == size(A,2) && A'*A == A*A'\nisunitary(A) = size(A,1) == size(A,2) && A'*A == eye(A)\n", "language": "Julia" }, { "code": "// version 1.1.3\n\ntypealias C = Complex\ntypealias Vector = Array<C>\ntypealias Matrix = Array<Vector>\n\nclass Complex(val real: Double, val imag: Double) {\n\n operator fun plus(other: Complex) =\n Complex(this.real + other.real, this.imag + other.imag)\n\n operator fun times(other: Complex) =\n Complex(this.real * other.real - this.imag * other.imag,\n this.real * other.imag + this.imag * other.real)\n\n fun conj() = Complex(this.real, -this.imag)\n\n /* tolerable equality allowing for rounding of Doubles */\n infix fun teq(other: Complex) =\n Math.abs(this.real - other.real) <= 1e-14 &&\n Math.abs(this.imag - other.imag) <= 1e-14\n\n override fun toString() = \"${\"%.3f\".format(real)} \" + when {\n imag > 0.0 -> \"+ ${\"%.3f\".format(imag)}i\"\n imag == 0.0 -> \"+ 0.000i\"\n else -> \"- ${\"%.3f\".format(-imag)}i\"\n }\n}\n\nfun Matrix.conjTranspose(): Matrix {\n val rows = this.size\n val cols = this[0].size\n return Matrix(cols) { i -> Vector(rows) { j -> this[j][i].conj() } }\n}\n\noperator fun Matrix.times(other: Matrix): Matrix {\n val rows1 = this.size\n val cols1 = this[0].size\n val rows2 = other.size\n val cols2 = other[0].size\n require(cols1 == rows2)\n val result = Matrix(rows1) { Vector(cols2) { C(0.0, 0.0) } }\n for (i in 0 until rows1) {\n for (j in 0 until cols2) {\n for (k in 0 until rows2) {\n result[i][j] += this[i][k] * other[k][j]\n }\n }\n }\n return result\n}\n\n/* tolerable matrix equality using the same concept as for complex numbers */\ninfix fun Matrix.teq(other: Matrix): Boolean {\n if (this.size != other.size || this[0].size != other[0].size) return false\n for (i in 0 until this.size) {\n for (j in 0 until this[0].size) if (!(this[i][j] teq other[i][j])) return false\n }\n return true\n}\n\nfun Matrix.isHermitian() = this teq this.conjTranspose()\n\nfun Matrix.isNormal(): Boolean {\n val ct = this.conjTranspose()\n return (this * ct) teq (ct * this)\n}\n\nfun Matrix.isUnitary(): Boolean {\n val ct = this.conjTranspose()\n val prod = this * ct\n val ident = identityMatrix(prod.size)\n val prod2 = ct * this\n return (prod teq ident) && (prod2 teq ident)\n}\n\nfun Matrix.print() {\n val rows = this.size\n val cols = this[0].size\n for (i in 0 until rows) {\n for (j in 0 until cols) {\n print(this[i][j])\n print(if(j < cols - 1) \", \" else \"\\n\")\n }\n }\n println()\n}\n\nfun identityMatrix(n: Int): Matrix {\n require(n >= 1)\n val ident = Matrix(n) { Vector(n) { C(0.0, 0.0) } }\n for (i in 0 until n) ident[i][i] = C(1.0, 0.0)\n return ident\n}\n\nfun main(args: Array<String>) {\n val x = Math.sqrt(2.0) / 2.0\n val matrices = arrayOf(\n arrayOf(\n arrayOf(C(3.0, 0.0), C(2.0, 1.0)),\n arrayOf(C(2.0, -1.0), C(1.0, 0.0))\n ),\n arrayOf(\n arrayOf(C(1.0, 0.0), C(1.0, 0.0), C(0.0, 0.0)),\n arrayOf(C(0.0, 0.0), C(1.0, 0.0), C(1.0, 0.0)),\n arrayOf(C(1.0, 0.0), C(0.0, 0.0), C(1.0, 0.0))\n ),\n arrayOf(\n arrayOf(C(x, 0.0), C(x, 0.0), C(0.0, 0.0)),\n arrayOf(C(0.0, -x), C(0.0, x), C(0.0, 0.0)),\n arrayOf(C(0.0, 0.0), C(0.0, 0.0), C(0.0, 1.0))\n )\n )\n\n for (m in matrices) {\n println(\"Matrix:\")\n m.print()\n val mct = m.conjTranspose()\n println(\"Conjugate transpose:\")\n mct.print()\n println(\"Hermitian? ${mct.isHermitian()}\")\n println(\"Normal? ${mct.isNormal()}\")\n println(\"Unitary? ${mct.isUnitary()}\\n\")\n }\n}\n", "language": "Kotlin" }, { "code": "M:=<<3|2+I>,<2-I|1>>:\n\nwith(LinearAlgebra):\nIsNormal:=A->EqualEntries(A^%H.A,A.A^%H):\n\nM^%H;\nHermitianTranspose(M);\ntype(M,'Matrix'(hermitian));\nIsNormal(M);\nIsUnitary(M);\n", "language": "Maple" }, { "code": "NormalMatrixQ[a_List?MatrixQ] := Module[{b = Conjugate@Transpose@a},a.b === b.a]\nUnitaryQ[m_List?MatrixQ] := (Conjugate@[email protected] == IdentityMatrix@Length@m)\n\nm = {{1, 2I, 3}, {3+4I, 5, I}};\nm //MatrixForm\n->\n(1\t2I\t3\n3+4I\t5\tI)\n\nConjugateTranspose[m] //MatrixForm\n->\n(1\t3-4I\n-2I\t5\n3\t-I)\n\n{HermitianMatrixQ@#, NormalMatrixQ@#, UnitaryQ@#}&@m\n-> {False, False, False}\n", "language": "Mathematica" }, { "code": "import complex, strformat\n\ntype Matrix[M, N: static Positive] = array[M, array[N, Complex[float]]]\n\nconst Eps = 1e-10 # Tolerance used for float comparisons.\n\n\n####################################################################################################\n# Templates.\n\ntemplate `[]`(m: Matrix; i, j: Natural): Complex[float] =\n ## Allow to get value of an element using m[i, j] syntax.\n m[i][j]\n\ntemplate `[]=`(m: var Matrix; i, j: Natural; val: Complex[float]) =\n ## Allow to set value of an element using m[i, j] syntax.\n m[i][j] = val\n\n\n####################################################################################################\n# General operations.\n\nfunc `$`(m: Matrix): string =\n ## Return the string representation of a matrix using one line per row.\n\n for i, row in m:\n result.add(if i == 0: '[' else: ' ')\n for j, val in row:\n if j != 0: result.add(' ')\n result.add(&\"({val.re:7.4f}, {val.im:7.4f})\")\n result.add(if i == m.high: ']' else: '\\n')\n\n#---------------------------------------------------------------------------------------------------\n\nfunc conjugateTransposed[M, N: static int](m: Matrix[M, N]): Matrix[N, M] =\n ## Return the conjugate transpose of a matrix.\n\n for i in 0..<m.M:\n for j in 0..<m.N:\n result[j, i] = m[i, j].conjugate()\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `*`[M, K, N: static int](m1: Matrix[M, K]; m2: Matrix[K, N]): Matrix[M, N] =\n # Compute the product of two matrices.\n\n for i in 0..<M:\n for j in 0..<N:\n for k in 0..<K:\n result[i, j] = result[i, j] + m1[i, k] * m2[k, j]\n\n\n####################################################################################################\n# Properties.\n\nfunc isHermitian(m: Matrix): bool =\n ## Check if a matrix is hermitian.\n\n when m.M != m.N:\n {.error: \"hermitian test only allowed for square matrices\".}\n else:\n for i in 0..<m.M:\n for j in i..<m.N:\n if m[i, j] != m[j, i].conjugate:\n return false\n result = true\n\n#---------------------------------------------------------------------------------------------------\n\nfunc isNormal(m: Matrix): bool =\n ## Check if a matrix is normal.\n\n when m.M != m.N:\n {.error: \"normal test only allowed for square matrices\".}\n else:\n let h = m.conjugateTransposed\n result = m * h == h * m\n\n#---------------------------------------------------------------------------------------------------\n\nfunc isIdentity(m: Matrix): bool =\n ## Check if a matrix is the identity matrix.\n\n when m.M != m.N:\n {.error: \"identity test only allowed for square matrices\".}\n else:\n for i in 0..<m.M:\n for j in 0..<m.N:\n if i == j:\n if abs(m[i, j] - 1.0) > Eps:\n return false\n else:\n if abs(m[i, j]) > Eps:\n return false\n result = true\n\n#---------------------------------------------------------------------------------------------------\n\nfunc isUnitary(m: Matrix): bool =\n ## Check if a matrix is unitary.\n\n when m.M != m.N:\n {.error: \"unitary test only allowed for square matrices\".}\n else:\n let h = m.conjugateTransposed\n result = (m * h).isIdentity and (h * m).isIdentity\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nwhen isMainModule:\n\n import math\n\n proc test(m: Matrix) =\n echo \"\\n\"\n echo \"Matrix\"\n echo \"------\"\n echo m\n echo \"\"\n echo \"Conjugate transposed\"\n echo \"--------------------\"\n echo m.conjugateTransposed\n\n when m.M == m.N:\n # Only for squares matrices.\n echo \"\"\n echo \"Hermitian: \", m.isHermitian\n echo \"Normal: \", m.isNormal\n echo \"Unitary: \", m.isUnitary\n\n #-------------------------------------------------------------------------------------------------\n\n # Non square matrix.\n const M1: Matrix[2, 3] = [[1.0 + im 2.0, 3.0 + im 0.0, 2.0 + im 5.0],\n [3.0 - im 1.0, 2.0 + im 0.0, 0.0 + im 3.0]]\n\n # Square matrices.\n const M2: Matrix[2, 2] = [[3.0 + im 0.0, 2.0 + im 1.0],\n [2.0 - im 1.0, 1.0 + im 0.0]]\n\n const M3: Matrix[3, 3] = [[1.0 + im 0.0, 1.0 + im 0.0, 0.0 + im 0.0],\n [0.0 + im 0.0, 1.0 + im 0.0, 1.0 + im 0.0],\n [1.0 + im 0.0, 0.0 + im 0.0, 1.0 + im 0.0]]\n\n const SR2 = 1 / sqrt(2.0)\n const M4: Matrix[3, 3] = [[SR2 + im 0.0, SR2 + im 0.0, 0.0 + im 0.0],\n [0.0 + im SR2, 0.0 - im SR2, 0.0 + im 0.0],\n [0.0 + im 0.0, 0.0 + im 0.0, 0.0 + im 1.0]]\n\n test(M1)\n test(M2)\n test(M3)\n test(M4)\n", "language": "Nim" }, { "code": "conjtranspose(M)=conj(M~)\nisHermitian(M)=M==conj(M~)\nisnormal(M)=my(H=conj(M~));H*M==M*H\nisunitary(M)=M*conj(M~)==1\n", "language": "PARI-GP" }, { "code": "use strict;\nuse warnings;\nuse English;\nuse Math::Complex;\nuse Math::MatrixReal;\n\nmy @examples = (example1(), example2(), example3());\nforeach my $m (@examples) {\n print \"Starting matrix:\\n\", cmat_as_string($m), \"\\n\";\n my $m_ct = conjugate_transpose($m);\n print \"Its conjugate transpose:\\n\", cmat_as_string($m_ct), \"\\n\";\n print \"Is Hermitian? \", (cmats_are_equal($m, $m_ct) ? 'TRUE' : 'FALSE'), \"\\n\";\n my $product = $m_ct * $m;\n print \"Is normal? \", (cmats_are_equal($product, $m * $m_ct) ? 'TRUE' : 'FALSE'), \"\\n\";\n my $I = identity(($m->dim())[0]);\n print \"Is unitary? \", (cmats_are_equal($product, $I) ? 'TRUE' : 'FALSE'), \"\\n\";\n print \"\\n\";\n}\nexit 0;\n\nsub cmats_are_equal {\n my ($m1, $m2) = @ARG;\n my $max_norm = 1.0e-7;\n return abs($m1 - $m2) < $max_norm; # Math::MatrixReal overloads abs().\n}\n\n# Note that Math::Complex and Math::MatrixReal both overload '~', for\n# complex conjugates and matrix transpositions respectively.\nsub conjugate_transpose {\n my $m_T = ~ shift;\n my $result = $m_T->each(sub {~ $ARG[0]});\n return $result;\n}\n\nsub cmat_as_string {\n my $m = shift;\n my $n_rows = ($m->dim())[0];\n my @row_strings = map { q{[} . join(q{, }, $m->row($ARG)->as_list) . q{]} }\n (1 .. $n_rows);\n return join(\"\\n\", @row_strings);\n}\n\nsub identity {\n my $N = shift;\n my $m = Math::MatrixReal->new($N, $N);\n $m->one();\n return $m;\n}\n\nsub example1 {\n my $m = Math::MatrixReal->new(2, 2);\n $m->assign(1, 1, cplx(3, 0));\n $m->assign(1, 2, cplx(2, 1));\n $m->assign(2, 1, cplx(2, -1));\n $m->assign(2, 2, cplx(1, 0));\n return $m;\n}\n\nsub example2 {\n my $m = Math::MatrixReal->new(3, 3);\n $m->assign(1, 1, cplx(1, 0));\n $m->assign(1, 2, cplx(1, 0));\n $m->assign(1, 3, cplx(0, 0));\n $m->assign(2, 1, cplx(0, 0));\n $m->assign(2, 2, cplx(1, 0));\n $m->assign(2, 3, cplx(1, 0));\n $m->assign(3, 1, cplx(1, 0));\n $m->assign(3, 2, cplx(0, 0));\n $m->assign(3, 3, cplx(1, 0));\n return $m;\n}\n\nsub example3 {\n my $m = Math::MatrixReal->new(3, 3);\n $m->assign(1, 1, cplx(0.70710677, 0));\n $m->assign(1, 2, cplx(0.70710677, 0));\n $m->assign(1, 3, cplx(0, 0));\n $m->assign(2, 1, cplx(0, -0.70710677));\n $m->assign(2, 2, cplx(0, 0.70710677));\n $m->assign(2, 3, cplx(0, 0));\n $m->assign(3, 1, cplx(0, 0));\n $m->assign(3, 2, cplx(0, 0));\n $m->assign(3, 3, cplx(0, 1));\n return $m;\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">complex</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">m_print</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">complex_sprint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"[\"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #008000;\">\",\"</span><span style=\"color: #0000FF;\">)&</span><span style=\"color: #008000;\">\"]\"</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)&</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">conjugate_transpose</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">complex_conjugate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">m_unitary</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">act</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- note: a was normal and act = a*ct already</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">act</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">re</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">im</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">act</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000080;font-style:italic;\">-- round to nearest billionth\n -- (powers of 2 help the FPU out)</span>\n <span style=\"color: #000000;\">re</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">round</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">re</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1024</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">1024</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">1024</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">im</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">round</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">im</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1024</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">1024</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">1024</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">im</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">or</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">j</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">re</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">or</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">j</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">re</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">m_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">complex_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #7060A8;\">complex_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">ct</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">conjugate_transpose</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Original matrix:\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">m_print</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Conjugate transpose:\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">m_print</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ct</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- note: rounding similar to that in m_unitary may be rqd (in a similar\n -- loop in a new m_equal function) on these two equality tests,\n -- but as it is, all tests pass with the builtin = operator.</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Hermitian?: %t\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">ct</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (this one)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">act</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">m_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ct</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">cta</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">m_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ct</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">normal</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">act</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">cta</span> <span style=\"color: #000080;font-style:italic;\">-- (&this one)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Normal?: %t\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">normal</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Unitary?: %t\\n\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">normal</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">m_unitary</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">act</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sqrt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{{{</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}}},</span>\n\n <span style=\"color: #0000FF;\">{{{</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},{</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},{</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},{-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}}},</span>\n\n <span style=\"color: #0000FF;\">{{{</span><span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">}}},</span>\n\n <span style=\"color: #0000FF;\">{{{</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}}},</span>\n\n <span style=\"color: #0000FF;\">{{{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}}},</span>\n\n <span style=\"color: #0000FF;\">{{{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">}}}}</span>\n\n <span style=\"color: #7060A8;\">papply</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "test: procedure options (main); /* 1 October 2012 */\n declare n fixed binary;\n\n put ('Conjugate a complex square matrix.');\n put skip list ('What is the order of the matrix?:');\n get (n);\n begin;\n declare (M, MH, MM, MM_MMH, MM_MHM, IDENTITY)(n,n) fixed complex;\n declare i fixed binary;\n\n IDENTITY = 0; do i = 1 to n; IDENTITY(I,I) = 1; end;\n put skip list ('Please type the matrix:');\n get list (M);\n do i = 1 to n;\n put skip list (M(i,*));\n end;\n do i = 1 to n;\n MH(i,*) = conjg(M(*,i));\n end;\n put skip list ('The conjugate transpose is:');\n do i = 1 to n;\n put skip list (MH(i,*));\n end;\n if all(M=MH) then\n put skip list ('Matrix is Hermitian');\n call MMULT(M, MH, MM_MMH);\n call MMULT(MH, M, MM_MHM);\n\n if all(MM_MMH = MM_MHM) then\n put skip list ('Matrix is Normal');\n\n if all(ABS(MM_MMH - IDENTITY) < 0.0001) then\n put skip list ('Matrix is unitary');\n if all(ABS(MM_MHM - IDENTITY) < 0.0001) then\n put skip list ('Matrix is unitary');\n end;\n\nMMULT: procedure (M, MH, MM);\n declare (M, MH, MM)(*,*) fixed complex;\n declare (i, j, n) fixed binary;\n\n n = hbound(M,1);\n do i = 1 to n;\n do j = 1 to n;\n MM(i,j) = sum(M(i,*) * MH(*,j) );\n end;\n end;\nend MMULT;\nend test;\n", "language": "PL-I" }, { "code": "function conjugate-transpose($a) {\n $arr = @()\n if($a) {\n $n = $a.count - 1\n if(0 -lt $n) {\n $m = ($a | foreach {$_.count} | measure-object -Minimum).Minimum - 1\n if( 0 -le $m) {\n if (0 -lt $m) {\n $arr =@(0)*($m+1)\n foreach($i in 0..$m) {\n $arr[$i] = foreach($j in 0..$n) {@([System.Numerics.complex]::Conjugate($a[$j][$i]))}\n }\n } else {$arr = foreach($row in $a) {[System.Numerics.complex]::Conjugate($row[0])}}\n }\n } else {$arr = foreach($row in $a) {[System.Numerics.complex]::Conjugate($row[0])}}\n }\n $arr\n}\n\nfunction multarrays-complex($a, $b) {\n $c = @()\n if($a -and $b) {\n $n = $a.count - 1\n $m = $b[0].count - 1\n $c = @([System.Numerics.complex]::new(0,0))*($n+1)\n foreach ($i in 0..$n) {\n $c[$i] = foreach ($j in 0..$m) {\n [System.Numerics.complex]$sum = [System.Numerics.complex]::new(0,0)\n foreach ($k in 0..$n){$sum = [System.Numerics.complex]::Add($sum, ([System.Numerics.complex]::Multiply($a[$i][$k],$b[$k][$j])))}\n $sum\n }\n }\n }\n $c\n}\n\nfunction identity-complex($n) {\n if(0 -lt $n) {\n $array = @(0) * $n\n foreach ($i in 0..($n-1)) {\n $array[$i] = @([System.Numerics.complex]::new(0,0)) * $n\n $array[$i][$i] = [System.Numerics.complex]::new(1,0)\n }\n $array\n } else { @() }\n}\n\nfunction are-eq ($a,$b) { -not (Compare-Object $a $b -SyncWindow 0)}\n\nfunction show($a) {\n if($a) {\n 0..($a.Count - 1) | foreach{ if($a[$_]){\"$($a[$_])\"}else{\"\"} }\n }\n}\nfunction complex($a,$b) {[System.Numerics.complex]::new($a,$b)}\n\n$id2 = identity-complex 2\n$m = @(@((complex 2 7), (complex 9 -5)),@((complex 3 4), (complex 8 -6)))\n$hm = conjugate-transpose $m\n$mhm = multarrays-complex $m $hm\n$hmm = multarrays-complex $hm $m\n\"`$m =\"\nshow $m\n\"\"\n\"`$hm = conjugate-transpose `$m =\"\nshow $hm\n\"\"\n\"`$m * `$hm =\"\nshow $mhm\n\"\"\n\"`$hm * `$m =\"\nshow $hmm\n\"\"\n\"Hermitian? `$m = $(are-eq $m $hm)\"\n\"Normal? `$m = $(are-eq $mhm $hmm)\"\n\"Unitary? `$m = $((are-eq $id2 $hmm) -and (are-eq $id2 $mhm))\"\n", "language": "PowerShell" }, { "code": "def conjugate_transpose(m):\n return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n 'Complex Identity matrix'\n sz = range(size)\n m = [[0 + 0j for i in sz] for j in sz]\n for i in range(size):\n m[i][i] = 1 + 0j\n return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n first, rest = vector[0], vector[1:]\n return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n first, rest = vector[0], vector[1:]\n return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n 'Check any number of matrices for equality within eps'\n x = [len(m) for m in matrices]\n if not __allsame(x): return False\n y = [len(m[0]) for m in matrices]\n if not __allsame(y): return False\n for s in range(x[0]):\n for t in range(y[0]):\n if not __allnearsame([m[s][t] for m in matrices], eps): return False\n return True\n\n\ndef ishermitian(m, ct):\n return isequal([m, ct])\n\ndef isnormal(m, ct):\n return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n mct, ctm = mmul(m, ct), mmul(ct, m)\n mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n ident = mi(mctx)\n return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n print(comment)\n fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n width = max(max(len(f) for f in row) for row in fields)\n lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n print('\\n'.join(lines))\n\nif __name__ == '__main__':\n for matrix in [\n ((( 3.000+0.000j), (+2.000+1.000j)),\n (( 2.000-1.000j), (+1.000+0.000j))),\n\n ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)),\n (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)),\n (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)),\n (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)),\n (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n printm('\\nMatrix:', matrix)\n ct = conjugate_transpose(matrix)\n printm('Its conjugate transpose:', ct)\n print('Hermitian? %s.' % ishermitian(matrix, ct))\n print('Normal? %s.' % isnormal(matrix, ct))\n print('Unitary? %s.' % isunitary(matrix, ct))\n", "language": "Python" }, { "code": "#lang racket\n(require math)\n(define H matrix-hermitian)\n\n(define (normal? M)\n (define MH (H M))\n (equal? (matrix* MH M)\n (matrix* M MH)))\n\n(define (unitary? M)\n (define MH (H M))\n (and (matrix-identity? (matrix* MH M))\n (matrix-identity? (matrix* M MH))))\n\n(define (hermitian? M)\n (equal? (H M) M))\n", "language": "Racket" }, { "code": "(define M (matrix [[3.000+0.000i +2.000+1.000i]\n [2.000-1.000i +1.000+0.000i]]))\n(H M)\n(normal? M)\n(unitary? M)\n(hermitian? M)\n", "language": "Racket" }, { "code": "(array #[#[3.0-0.0i 2.0+1.0i] #[2.0-1.0i 1.0-0.0i]])\n#t\n#f\n#f\n", "language": "Racket" }, { "code": "for [ # Test Matrices\n [ 1, 1+i, 2i],\n [ 1-i, 5, -3],\n [0-2i, -3, 0]\n ],\n [\n [1, 1, 0],\n [0, 1, 1],\n [1, 0, 1]\n ],\n [\n [0.707 , 0.707, 0],\n [0.707i, 0-0.707i, 0],\n [0 , 0, i]\n ]\n -> @m {\n say \"\\nMatrix:\";\n @m.&say-it;\n my @t = @m».conj.&mat-trans;\n say \"\\nTranspose:\";\n @t.&say-it;\n say \"Is Hermitian?\\t{is-Hermitian(@m, @t)}\";\n say \"Is Normal?\\t{is-Normal(@m, @t)}\";\n say \"Is Unitary?\\t{is-Unitary(@m, @t)}\";\n }\n\nsub is-Hermitian (@m, @t, --> Bool) {\n so @m».Complex eqv @t».Complex\n }\n\nsub is-Normal (@m, @t, --> Bool) {\n so mat-mult(@m, @t)».Complex eqv mat-mult(@t, @m)».Complex\n}\n\nsub is-Unitary (@m, @t, --> Bool) {\n so mat-mult(@m, @t, 1e-3)».Complex eqv mat-ident(+@m)».Complex;\n}\n\nsub mat-trans (@m) { map { [ @m[*;$_] ] }, ^@m[0] }\n\nsub mat-ident ($n) { [ map { [ flat 0 xx $_, 1, 0 xx $n - 1 - $_ ] }, ^$n ] }\n\nsub mat-mult (@a, @b, \\ε = 1e-15) {\n my @p;\n for ^@a X ^@b[0] -> ($r, $c) {\n @p[$r][$c] += @a[$r][$_] * @b[$_][$c] for ^@b;\n @p[$r][$c].=round(ε); # avoid floating point math errors\n }\n @p\n}\n\nsub say-it (@array) { $_».fmt(\"%9s\").say for @array }\n", "language": "Raku" }, { "code": "/*REXX program performs a conjugate transpose on a complex square matrix. */\nparse arg N elements; if N==''|N==\",\" then N=3 /*Not specified? Then use the default.*/\nk= 0; do r=1 for N\n do c=1 for N; k= k+1; M.r.c= word( word(elements, k) 1, 1)\n end /*c*/\n end /*r*/\ncall showCmat 'M' ,N /*display a nicely formatted matrix. */\nidentity.= 0; do d=1 for N; identity.d.d= 1; end /*d*/\ncall conjCmat 'MH', \"M\" ,N /*conjugate the M matrix ───► MH */\ncall showCmat 'MH' ,N /*display a nicely formatted matrix. */\nsay 'M is Hermitian: ' word('no yes', isHermitian('M', \"MH\", N) + 1)\ncall multCmat 'M', 'MH', 'MMH', N /*multiple the two matrices together. */\ncall multCmat 'MH', 'M', 'MHM', N /* \" \" \" \" \" */\nsay ' M is Normal: ' word('no yes', isHermitian('MMH', \"MHM\", N) + 1)\nsay ' M is Unary: ' word('no yes', isUnary('M', N) + 1)\nsay 'MMH is Unary: ' word('no yes', isUnary('MMH', N) + 1)\nsay 'MHM is Unary: ' word('no yes', isUnary('MHM', N) + 1)\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncP: procedure; arg ',' c; return word( strip( translate(c, , 'IJ') ) 0, 1)\nrP: procedure; parse arg r ','; return word( r 0, 1) /*◄──maybe return a 0 ↑ */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nconjCmat: parse arg matX,matY,rows 1 cols; call normCmat matY, rows\n do r=1 for rows; _=\n do c=1 for cols; v= value(matY'.'r\".\"c)\n rP= rP(v); cP= -cP(v); call value matX'.'c\".\"r, rP','cP\n end /*c*/\n end /*r*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nisHermitian: parse arg matX,matY,rows 1 cols; call normCmat matX, rows\n call normCmat matY, rows\n do r=1 for rows; _=\n do c=1 for cols\n if value(matX'.'r\".\"c) \\= value(matY'.'r\".\"c) then return 0\n end /*c*/\n end /*r*/; return 1\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nisUnary: parse arg matX,rows 1 cols\n do r=1 for rows; _=\n do c=1 for cols; z= value(matX'.'r\".\"c); rP= rP(z); cP= cP(z)\n if abs( sqrt( rP(z) **2 + cP(z)**2) - (r==c)) >= .0001 then return 0\n end /*c*/\n end /*r*/; return 1\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nmultCmat: parse arg matA,matB,matT,rows 1 cols; call value matT'.', 0\n do r=1 for rows; _=\n do c=1 for cols\n do k=1 for cols; T= value(matT'.'r\".\"c); Tr= rP(T); Tc= cP(T)\n A= value(matA'.'r\".\"k); Ar= rP(A); Ac= cP(A)\n B= value(matB'.'k\".\"c); Br= rP(B); Bc= cP(B)\n Pr= Ar*Br - Ac*Bc; Pc= Ac*Br + Ar*Bc; Tr= Tr+Pr; Tc= Tc+Pc\n call value matT'.'r\".\"c,Tr','Tc\n end /*k*/\n end /*c*/\n end /*r*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nnormCmat: parse arg matN,rows 1 cols\n do r=1 to rows; _=\n do c=1 to cols; v= translate( value(matN'.'r\".\"c), , \"IiJj\")\n parse upper var v real ',' cplx\n if real\\=='' then real= real / 1\n if cplx\\=='' then cplx= cplx / 1; if cplx=0 then cplx=\n if cplx\\=='' then cplx= cplx\"j\"\n call value matN'.'r\".\"c, strip(real','cplx, \"T\", ',')\n end /*c*/\n end /*r*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nshowCmat: parse arg matX,rows,cols; if cols=='' then cols= rows; @@= left('', 6)\n say; say center('matrix' matX, 79, '─'); call normCmat matX, rows, cols\n do r=1 to rows; _=\n do c=1 to cols; _= _ @@ left( value(matX'.'r\".\"c), 9)\n end /*c*/\n say _\n end /*r*/; say; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric form; h=d+6\n numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_ % 2\n m.=9; do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/\n do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g\n", "language": "REXX" }, { "code": "require 'matrix'\n\n# Start with some matrix.\ni = Complex::I\nmatrix = Matrix[[i, 0, 0],\n [0, i, 0],\n [0, 0, i]]\n\n# Find the conjugate transpose.\n# Matrix#conjugate appeared in Ruby 1.9.2.\nconjt = matrix.conj.t # aliases for matrix.conjugate.tranpose\nprint 'conjugate tranpose: '; puts conjt\n\nif matrix.square?\n # These predicates appeared in Ruby 1.9.3.\n print 'Hermitian? '; puts matrix.hermitian?\n print ' normal? '; puts matrix.normal?\n print ' unitary? '; puts matrix.unitary?\nelse\n # Matrix is not square. These predicates would\n # raise ExceptionForMatrix::ErrDimensionMismatch.\n print 'Hermitian? false'\n print ' normal? false'\n print ' unitary? false'\nend\n", "language": "Ruby" }, { "code": "extern crate num; // crate for complex numbers\n\nuse num::complex::Complex;\nuse std::ops::Mul;\nuse std::fmt;\n\n\n#[derive(Debug, PartialEq)]\nstruct Matrix<f32> {\n grid: [[Complex<f32>; 2]; 2], // used to represent matrix\n}\n\n\nimpl Matrix<f32> { // implements a method call for calculating the conjugate transpose\n fn conjugate_transpose(&self) -> Matrix<f32> {\n Matrix {grid: [[self.grid[0][0].conj(), self.grid[1][0].conj()],\n [self.grid[0][1].conj(), self.grid[1][1].conj()]]}\n }\n}\n\nimpl Mul for Matrix<f32> { // implements '*' (multiplication) for the matrix\n type Output = Matrix<f32>;\n\n fn mul(self, other: Matrix<f32>) -> Matrix<f32> {\n Matrix {grid: [[self.grid[0][0]*other.grid[0][0] + self.grid[0][1]*other.grid[1][0],\n self.grid[0][0]*other.grid[0][1] + self.grid[0][1]*other.grid[1][1]],\n [self.grid[1][0]*other.grid[0][0] + self.grid[1][1]*other.grid[1][0],\n self.grid[1][0]*other.grid[1][0] + self.grid[1][1]*other.grid[1][1]]]}\n }\n}\n\nimpl Copy for Matrix<f32> {} // implemented to prevent 'moved value' errors in if statements below\nimpl Clone for Matrix<f32> {\n fn clone(&self) -> Matrix<f32> {\n *self\n }\n}\n\nimpl fmt::Display for Matrix<f32> { // implemented to make output nicer\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"({}, {})\\n({}, {})\", self.grid[0][0], self.grid[0][1], self.grid[1][0], self.grid[1][1])\n }\n}\n\nfn main() {\n let a = Matrix {grid: [[Complex::new(3.0, 0.0), Complex::new(2.0, 1.0)],\n [Complex::new(2.0, -1.0), Complex::new(1.0, 0.0)]]};\n\n let b = Matrix {grid: [[Complex::new(0.5, 0.5), Complex::new(0.5, -0.5)],\n [Complex::new(0.5, -0.5), Complex::new(0.5, 0.5)]]};\n\n test_type(a);\n test_type(b);\n}\n\nfn test_type(mat: Matrix<f32>) {\n let identity = Matrix {grid: [[Complex::new(1.0, 0.0), Complex::new(0.0, 0.0)],\n [Complex::new(0.0, 0.0), Complex::new(1.0, 0.0)]]};\n let mat_conj = mat.conjugate_transpose();\n\n println!(\"Matrix: \\n{}\\nConjugate transpose: \\n{}\", mat, mat_conj);\n\n if mat == mat_conj {\n println!(\"Hermitian?: TRUE\");\n } else {\n println!(\"Hermitian?: FALSE\");\n }\n\n if mat*mat_conj == mat_conj*mat {\n println!(\"Normal?: TRUE\");\n } else {\n println!(\"Normal?: FALSE\");\n }\n\n if mat*mat_conj == identity {\n println!(\"Unitary?: TRUE\");\n } else {\n println!(\"Unitary?: FALSE\");\n }\n}\n", "language": "Rust" }, { "code": "object ConjugateTranspose {\n\n case class Complex(re: Double, im: Double) {\n def conjugate(): Complex = Complex(re, -im)\n def +(other: Complex) = Complex(re + other.re, im + other.im)\n def *(other: Complex) = Complex(re * other.re - im * other.im, re * other.im + im * other.re)\n override def toString(): String = {\n if (im < 0) {\n s\"${re}${im}i\"\n } else {\n s\"${re}+${im}i\"\n }\n }\n }\n\n case class Matrix(val entries: Vector[Vector[Complex]]) {\n\n def *(other: Matrix): Matrix = {\n new Matrix(\n Vector.tabulate(entries.size, other.entries(0).size)((r, c) => {\n val rightRow = entries(r)\n val leftCol = other.entries.map(_(c))\n rightRow.zip(leftCol)\n .map{ case (x, y) => x * y } // multiply pair-wise\n .foldLeft(new Complex(0,0)){ case (x, y) => x + y } // sum over all\n })\n )\n }\n\n def conjugateTranspose(): Matrix = {\n new Matrix(\n Vector.tabulate(entries(0).size, entries.size)((r, c) => entries(c)(r).conjugate)\n )\n }\n\n def isHermitian(): Boolean = {\n this == conjugateTranspose()\n }\n\n def isNormal(): Boolean = {\n val ct = conjugateTranspose()\n this * ct == ct * this\n }\n\n def isIdentity(): Boolean = {\n val entriesWithIndexes = for (r <- 0 until entries.size; c <- 0 until entries(r).size) yield (r, c, entries(r)(c))\n entriesWithIndexes.forall { case (r, c, x) =>\n if (r == c) {\n x == Complex(1.0, 0.0)\n } else {\n x == Complex(0.0, 0.0)\n }\n }\n }\n\n def isUnitary(): Boolean = {\n (this * conjugateTranspose()).isIdentity()\n }\n\n override def toString(): String = {\n entries.map(\" \" + _.mkString(\"[\", \",\", \"]\")).mkString(\"[\\n\", \"\\n\", \"\\n]\")\n }\n\n }\n\n def main(args: Array[String]): Unit = {\n val m = new Matrix(\n Vector.fill(3, 3)(new Complex(Math.random() * 2 - 1.0, Math.random() * 2 - 1.0))\n )\n println(\"Matrix: \" + m)\n println(\"Conjugate Transpose: \" + m.conjugateTranspose())\n println(\"Hermitian: \" + m.isHermitian())\n println(\"Normal: \" + m.isNormal())\n println(\"Unitary: \" + m.isUnitary())\n }\n\n}\n", "language": "Scala" }, { "code": "func is_Hermitian (Array m, Array t) -> Bool { m == t }\n\nfunc mat_mult (Array a, Array b, Number ε = -3) {\n var p = []\n for r, c in (^a ~X ^b[0]) {\n for k in (^b) {\n p[r][c] := 0 += (a[r][k] * b[k][c]) -> round!(ε)\n }\n }\n return p\n}\n\nfunc mat_trans (Array m) {\n var r = []\n for i,j in (^m ~X ^m[0]) {\n r[j][i] = m[i][j]\n }\n return r\n}\n\nfunc mat_ident (Number n) {\n ^n -> map {|i|\n [i.of(0)..., 1, (n - i - 1).of(0)...]\n }\n}\n\nfunc is_Normal (Array m, Array t) -> Bool {\n mat_mult(m, t) == mat_mult(t, m)\n}\n\nfunc is_Unitary (Array m, Array t) -> Bool {\n mat_mult(m, t) == mat_ident(m.len)\n}\n\nfunc say_it (Array a) {\n a.each {|b|\n b.map { \"%9s\" % _ }.join(' ').say\n }\n}\n\n[\n [\n [ 1, 1+1i, 2i],\n [1-1i, 5, -3],\n [0-2i, -3, 0]\n ],\n [\n [1, 1, 0],\n [0, 1, 1],\n [1, 0, 1]\n ],\n [\n [0.707 , 0.707, 0],\n [0.707i, -0.707i, 0],\n [0 , 0, 1i]\n ]\n].each { |m|\n say \"\\nMatrix:\"\n say_it(m)\n var t = mat_trans(m.map{.map{.conj}})\n say \"\\nTranspose:\"\n say_it(t)\n say \"Is Hermitian?\\t#{is_Hermitian(m, t)}\"\n say \"Is Normal?\\t#{is_Normal(m, t)}\"\n say \"Is Unitary?\\t#{is_Unitary(m, t)}\"\n}\n", "language": "Sidef" }, { "code": "# Computes conjugate transpose of M\nlet conjTransp = function conjTransp(M) {\n\treturn map(range(sizeof M[0]), function(row) {\n\t\treturn map(range(sizeof M), function(col) {\n\t\t\treturn cplx_conj(M[col][row]);\n\t\t});\n\t});\n};\n\n# Helper for cplxMatMul\nlet cplxVecScalarMul = function cplxVecScalarMul(A, B, row, col) {\n\tvar M = { \"re\": 0.0, \"im\": 0.0 };\n\tlet N = sizeof A;\n\tfor (var i = 0; i < N; i++) {\n\t\tlet P = cplx_mul(A[row][i], B[i][col]);\n\t\tM = cplx_add(M, P);\n\t}\n\treturn M;\n};\n\n# Multiplies matrices A and B\n# A and B are assumed to be square and of the same size,\n# this condition is not checked.\nlet cplxMatMul = function cplxMatMul(A, B) {\n\tvar R = {};\n\tlet N = sizeof A;\n\tfor (var row = 0; row < N; row++) {\n\t\tR[row] = {};\n\t\tfor (var col = 0; col < N; col++) {\n\t\t\tR[row][col] = cplxVecScalarMul(A, B, row, col);\n\t\t}\n\t}\n\treturn R;\n};\n\n# Helper for creating an array representing a complex number\n# given its textual representation\nlet _ = function makeComplex(str) {\n\tlet sep = indexof(str, \"+\", 1);\n\tif sep < 0 {\n\t\tsep = indexof(str, \"-\", 1);\n\t}\n\tlet reStr = substrto(str, sep);\n\tlet imStr = substrfrom(str, sep);\n\treturn { \"re\": tofloat(reStr), \"im\": tofloat(imStr) };\n};\n\n# Formats a complex matrix\nlet printCplxMat = function printCplxMat(M) {\n\tforeach(M, function(i, row) {\n\t\tforeach(row, function(j, elem) {\n\t\t\tprintf(\" %.2f%+.2fi\", elem.re, elem.im);\n\t\t});\n\t\tprint();\n\t});\n};\n\n# A Hermitian matrix\nlet H = {\n\t{ _(\"3+0i\"), _(\"2+1i\") },\n\t{ _(\"2-1i\"), _(\"0+0i\") }\n};\n\n# A normal matrix\nlet N = {\n\t{ _(\"1+0i\"), _(\"1+0i\"), _(\"0+0i\") },\n\t{ _(\"0+0i\"), _(\"1+0i\"), _(\"1+0i\") },\n\t{ _(\"1+0i\"), _(\"0+0i\"), _(\"1+0i\") }\n};\n\n# A unitary matrix\nlet U = {\n\t{ _(\"0.70710678118+0i\"), _(\"0.70710678118+0i\"), _(\"0+0i\") },\n\t{ _(\"0-0.70710678118i\"), _(\"0+0.70710678118i\"), _(\"0+0i\") },\n\t{ _(\"0+0i\"), _(\"0+0i\"), _(\"0+1i\") }\n};\n\n\nprint(\"Hermitian matrix:\\nH = \");\nprintCplxMat(H);\nprint(\"H* = \");\nprintCplxMat(conjTransp(H));\nprint();\n\nprint(\"Normal matrix:\\nN = \");\nprintCplxMat(N);\nprint(\"N* = \");\nprintCplxMat(conjTransp(N));\nprint(\"N* x N = \");\nprintCplxMat(cplxMatMul(conjTransp(N), N));\nprint(\"N x N* = \");\nprintCplxMat(cplxMatMul(N, conjTransp(N)));\nprint();\n\nprint(\"Unitary matrix:\\nU = \");\nprintCplxMat(U);\nprint(\"U* = \");\nprintCplxMat(conjTransp(U));\nprint(\"U x U* = \");\nprintCplxMat(cplxMatMul(U, conjTransp(U)));\nprint();\n", "language": "Sparkling" }, { "code": ": a=1,2i\\3i,4\n\n: a\n 1 2\n +-----------+\n 1 | 1 2i |\n 2 | 3i 4 |\n +-----------+\n\n: a'\n 1 2\n +-------------+\n 1 | 1 -3i |\n 2 | -2i 4 |\n +-------------+\n\n: transposeonly(a)\n 1 2\n +-----------+\n 1 | 1 3i |\n 2 | 2i 4 |\n +-----------+\n\n: a*a'==a'*a\n 0\n\n: a'==a\n 0\n\n: a'*a==I(rows(a))\n 0\n", "language": "Stata" }, { "code": "package require struct::matrix\npackage require math::complexnumbers\n\nproc complexMatrix.equal {m1 m2 {epsilon 1e-14}} {\n if {[$m1 rows] != [$m2 rows] || [$m1 columns] != [$m2 columns]} {\n\treturn 0\n }\n # Compute the magnitude of the difference between two complex numbers\n set ceq [list apply {{epsilon a b} {\n\texpr {[mod [- $a $b]] < $epsilon}\n } ::math::complexnumbers} $epsilon]\n for {set i 0} {$i<[$m1 columns]} {incr i} {\n\tfor {set j 0} {$j<[$m1 rows]} {incr j} {\n\t if {![{*}$ceq [$m1 get cell $i $j] [$m2 get cell $i $j]]} {\n\t\treturn 0\n\t }\n\t}\n }\n return 1\n}\n\nproc complexMatrix.multiply {a b} {\n if {[$a columns] != [$b rows]} {\n error \"incompatible sizes\"\n }\n # Simplest to use a lambda in the complex NS\n set cpm {{sum a b} {\n\t+ $sum [* $a $b]\n } ::math::complexnumbers}\n set c0 [math::complexnumbers::complex 0.0 0.0]; # Complex zero\n set c [struct::matrix]\n $c add columns [$b columns]\n $c add rows [$a rows]\n for {set i 0} {$i < [$a rows]} {incr i} {\n for {set j 0} {$j < [$b columns]} {incr j} {\n set sum $c0\n\t foreach rv [$a get row $i] cv [$b get column $j] {\n\t\tset sum [apply $cpm $sum $rv $cv]\n }\n\t $c set cell $j $i $sum\n }\n }\n return $c\n}\n\nproc complexMatrix.conjugateTranspose {matrix} {\n set mat [struct::matrix]\n $mat = $matrix\n $mat transpose\n for {set c 0} {$c < [$mat columns]} {incr c} {\n\tfor {set r 0} {$r < [$mat rows]} {incr r} {\n\t set val [$mat get cell $c $r]\n\t $mat set cell $c $r [math::complexnumbers::conj $val]\n\t}\n }\n return $mat\n}\n", "language": "Tcl" }, { "code": "proc isHermitian {matrix {epsilon 1e-14}} {\n if {[$matrix rows] != [$matrix columns]} {\n\t# Must be square!\n\treturn 0\n }\n set cc [complexMatrix.conjugateTranspose $matrix]\n set result [complexMatrix.equal $matrix $cc $epsilon]\n $cc destroy\n return $result\n}\n\nproc isNormal {matrix {epsilon 1e-14}} {\n if {[$matrix rows] != [$matrix columns]} {\n\t# Must be square!\n\treturn 0\n }\n set mh [complexMatrix.conjugateTranspose $matrix]\n set mhm [complexMatrix.multiply $mh $matrix]\n set mmh [complexMatrix.multiply $matrix $mh]\n $mh destroy\n set result [complexMatrix.equal $mhm $mmh $epsilon]\n $mhm destroy\n $mmh destroy\n return $result\n}\n\nproc isUnitary {matrix {epsilon 1e-14}} {\n if {[$matrix rows] != [$matrix columns]} {\n\t# Must be square!\n\treturn 0\n }\n set mh [complexMatrix.conjugateTranspose $matrix]\n set mhm [complexMatrix.multiply $mh $matrix]\n set mmh [complexMatrix.multiply $matrix $mh]\n $mh destroy\n set result [complexMatrix.equal $mhm $mmh $epsilon]\n $mhm destroy\n if {$result} {\n\tset id [struct::matrix]\n\t$id = $matrix; # Just for its dimensions\n\tfor {set c 0} {$c < [$id columns]} {incr c} {\n\t for {set r 0} {$r < [$id rows]} {incr r} {\n\t\t$id set cell $c $r \\\n\t\t [math::complexnumbers::complex [expr {$c==$r}] 0]\n\t }\n\t}\n\tset result [complexMatrix.equal $mmh $id $epsilon]\n\t$id destroy\n }\n $mmh destroy\n return $result\n}\n", "language": "Tcl" }, { "code": "import \"./complex\" for Complex, CMatrix\nimport \"./fmt\" for Fmt\n\nvar cm1 = CMatrix.new(\n [\n [Complex.new(3), Complex.new(2, 1)],\n [Complex.new(2, -1), Complex.one ]\n ]\n)\nvar cm2 = CMatrix.fromReals([ [1, 1, 0], [0, 1, 1], [1, 0, 1] ])\nvar x = 2.sqrt/2\nvar cm3 = CMatrix.new(\n [\n [Complex.new(x), Complex.new(x), Complex.zero],\n [Complex.new(0, -x), Complex.new(0, x), Complex.zero],\n [Complex.zero, Complex.zero, Complex.imagOne]\n ]\n)\n\nfor (cm in [cm1, cm2, cm3]) {\n System.print(\"Matrix:\")\n Fmt.mprint(cm, 5, 3)\n System.print(\"\\nConjugate transpose:\")\n Fmt.mprint(cm.conjTranspose, 5, 3)\n System.print(\"\\nHermitian : %(cm.isHermitian)\")\n System.print(\"Normal : %(cm.isNormal)\")\n System.print(\"Unitary : %(cm.isUnitary)\")\n System.print()\n}\n\nSystem.print(\"For the final example if we use a tolerance of 1e-14:\")\nvar cm4 = cm3 * cm3.conjTranspose\nvar id = CMatrix.identity(3)\nSystem.print(\"Unitary : %(cm4.almostEquals(id))\")\n", "language": "Wren" } ]
Conjugate-transpose
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences\nnote: Prime Numbers\n", "language": "00-META" }, { "code": ";Task:\n<br><br>\nFind and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending.<br><br>\nDo the same for sequences of primes where the differences are strictly descending.\n<br><br>\nIn both cases, show the sequence for primes &nbsp; <big>&lt;</big> &nbsp; 1,000,000.\n<br><br>\nIf there are multiple sequences of the same length, only the first need be shown.\n\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F primes_upto(limit)\n V is_prime = [0B] * 2 [+] [1B] * (limit - 1)\n L(n) 0 .< Int(limit ^ 0.5 + 1.5)\n I is_prime[n]\n L(i) (n * n .. limit).step(n)\n is_prime[i] = 0B\n R enumerate(is_prime).filter((i, prime) -> prime).map((i, prime) -> i)\n\nV primelist = primes_upto(1'000'000)\n\nV listlen = primelist.len\n\nV pindex = 1\nV old_diff = -1\nV curr_list = [primelist[0]]\n[Int] longest_list\n\nL pindex < listlen\n\n V diff = primelist[pindex] - primelist[pindex - 1]\n I diff > old_diff\n curr_list.append(primelist[pindex])\n I curr_list.len > longest_list.len\n longest_list = curr_list\n E\n curr_list = [primelist[pindex - 1], primelist[pindex]]\n\n old_diff = diff\n pindex++\n\nprint(longest_list)\n\npindex = 1\nold_diff = -1\ncurr_list = [primelist[0]]\nlongest_list.drop()\n\nL pindex < listlen\n\n V diff = primelist[pindex] - primelist[pindex - 1]\n I diff < old_diff\n curr_list.append(primelist[pindex])\n I curr_list.len > longest_list.len\n longest_list = curr_list\n E\n curr_list = [primelist[pindex - 1], primelist[pindex]]\n\n old_diff = diff\n pindex++\n\nprint(longest_list)\n", "language": "11l" }, { "code": "BEGIN # find sequences of primes where the gaps between the elements #\n # are strictly ascending/descending #\n # reurns a list of primes up to n #\n PROC prime list = ( INT n )[]INT:\n BEGIN\n # sieve the primes to n #\n INT no = 0, yes = 1;\n [ 1 : n ]INT p;\n p[ 1 ] := no; p[ 2 ] := yes;\n FOR i FROM 3 BY 2 TO n DO p[ i ] := yes OD;\n FOR i FROM 4 BY 2 TO n DO p[ i ] := no OD;\n FOR i FROM 3 BY 2 TO ENTIER sqrt( n ) DO\n IF p[ i ] = yes THEN FOR s FROM i * i BY i + i TO n DO p[ s ] := no OD FI\n OD;\n # replace the sieve with a list #\n INT p pos := 0;\n FOR i TO n DO IF p[ i ] = yes THEN p[ p pos +:= 1 ] := i FI OD;\n p[ 1 : p pos ]\n END # prime list # ;\n # shos the results of a search #\n PROC show sequence = ( []INT primes, STRING seq name, INT seq start, seq length )VOID:\n BEGIN\n print( ( \" The longest sequence of primes with \"\n , seq name\n , \" differences contains \"\n , whole( seq length, 0 )\n , \" primes\"\n , newline\n , \" First such sequence (differences in brackets):\"\n , newline\n , \" \"\n )\n );\n print( ( whole( primes[ seq start ], 0 ) ) );\n FOR p FROM seq start + 1 TO seq start + ( seq length - 1 ) DO\n print( ( \" (\", whole( ABS( primes[ p ] - primes[ p - 1 ] ), 0 ), \") \", whole( primes[ p ], 0 ) ) )\n OD;\n print( ( newline ) )\n END # show seuence # ;\n # find the longest sequence of primes where the successive differences are ascending/descending #\n PROC find sequence = ( []INT primes, BOOL ascending, REF INT seq start, seq length )VOID:\n BEGIN\n seq start := seq length := 0;\n INT start diff = IF ascending THEN 0 ELSE UPB primes + 1 FI;\n FOR p FROM LWB primes TO UPB primes DO\n INT prev diff := start diff;\n INT length := 1;\n FOR s FROM p + 1 TO UPB primes\n WHILE INT diff = ABS ( primes[ s ] - primes[ s - 1 ] );\n IF ascending THEN diff > prev diff ELSE diff < prev diff FI\n DO\n length +:= 1;\n prev diff := diff\n OD;\n IF length > seq length THEN\n # found a longer sequence #\n seq length := length;\n seq start := p\n FI\n OD\n END # find sequence #;\n INT max number = 1 000 000;\n []INT primes = prime list( max number );\n INT asc length := 0;\n INT asc start := 0;\n INT desc length := 0;\n INT desc start := 0;\n find sequence( primes, TRUE, asc start, asc length );\n find sequence( primes, FALSE, desc start, desc length );\n # show the sequences #\n print( ( \"For primes up to \", whole( max number, 0 ), newline ) );\n show sequence( primes, \"ascending\", asc start, asc length );\n show sequence( primes, \"descending\", desc start, desc length )\nEND\n", "language": "ALGOL-68" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n\nbool *sieve(int limit) {\n int i, p;\n limit++;\n // True denotes composite, false denotes prime.\n bool *c = calloc(limit, sizeof(bool)); // all false by default\n c[0] = true;\n c[1] = true;\n for (i = 4; i < limit; i += 2) c[i] = true;\n p = 3; // Start from 3.\n while (true) {\n int p2 = p * p;\n if (p2 >= limit) break;\n for (i = p2; i < limit; i += 2 * p) c[i] = true;\n while (true) {\n p += 2;\n if (!c[p]) break;\n }\n }\n return c;\n}\n\nvoid longestSeq(int *primes, int pc, bool asc) {\n int i, j, d, pd = 0, lls = 1, lcs = 1;\n int longSeqs[25][10] = {{2}};\n int lsl[25] = {1};\n int currSeq[10] = {2};\n const char *dir = asc ? \"ascending\" : \"descending\";\n for (i = 1; i < pc; ++i) {\n d = primes[i] - primes[i-1];\n if ((asc && d <= pd) || (!asc && d >= pd)) {\n if (lcs > lsl[0]) {\n memcpy((void *)longSeqs[0], (void *)currSeq, lcs * sizeof(int));\n lsl[0] = lcs;\n lls = 1;\n } else if (lcs == lsl[0]) {\n memcpy((void *)longSeqs[lls], (void *)currSeq, lcs * sizeof(int));\n lsl[lls++] = lcs;\n }\n currSeq[0] = primes[i-1];\n currSeq[1] = primes[i];\n lcs = 2;\n } else {\n currSeq[lcs++] = primes[i];\n }\n pd = d;\n }\n if (lcs > lsl[0]) {\n memcpy((void *)longSeqs[0], (void *)currSeq, lcs * sizeof(int));\n lsl[0] = lcs;\n lls = 1;\n } else if (lcs == lsl[0]) {\n memcpy((void *)longSeqs[lls], (void *)currSeq, lcs * sizeof(int));\n lsl[lls++] = lcs;\n }\n printf(\"Longest run(s) of primes with %s differences is %d:\\n\", dir, lsl[0]);\n for (i = 0; i < lls; ++i) {\n int *ls = longSeqs[i];\n for (j = 0; j < lsl[i]-1; ++j) printf(\"%d (%d) \", ls[j], ls[j+1] - ls[j]);\n printf(\"%d\\n\", ls[lsl[i]-1]);\n }\n printf(\"\\n\");\n}\n\nint main() {\n const int limit = 999999;\n int i, j, pc = 0;\n bool *c = sieve(limit);\n for (i = 0; i < limit; ++i) {\n if (!c[i]) ++pc;\n }\n int *primes = (int *)malloc(pc * sizeof(int));\n for (i = 0, j = 0; i < limit; ++i) {\n if (!c[i]) primes[j++] = i;\n }\n free(c);\n printf(\"For primes < 1 million:\\n\");\n longestSeq(primes, pc, true);\n longestSeq(primes, pc, false);\n free(primes);\n return 0;\n}\n", "language": "C" }, { "code": "#include <cstdint>\n#include <iostream>\n#include <vector>\n#include <primesieve.hpp>\n\nvoid print_diffs(const std::vector<uint64_t>& vec) {\n for (size_t i = 0, n = vec.size(); i != n; ++i) {\n if (i != 0)\n std::cout << \" (\" << vec[i] - vec[i - 1] << \") \";\n std::cout << vec[i];\n }\n std::cout << '\\n';\n}\n\nint main() {\n std::cout.imbue(std::locale(\"\"));\n std::vector<uint64_t> asc, desc;\n std::vector<std::vector<uint64_t>> max_asc, max_desc;\n size_t max_asc_len = 0, max_desc_len = 0;\n uint64_t prime;\n const uint64_t limit = 1000000;\n for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) {\n size_t alen = asc.size();\n if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2])\n asc.erase(asc.begin(), asc.end() - 1);\n asc.push_back(prime);\n if (asc.size() >= max_asc_len) {\n if (asc.size() > max_asc_len) {\n max_asc_len = asc.size();\n max_asc.clear();\n }\n max_asc.push_back(asc);\n }\n size_t dlen = desc.size();\n if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2])\n desc.erase(desc.begin(), desc.end() - 1);\n desc.push_back(prime);\n if (desc.size() >= max_desc_len) {\n if (desc.size() > max_desc_len) {\n max_desc_len = desc.size();\n max_desc.clear();\n }\n max_desc.push_back(desc);\n }\n }\n std::cout << \"Longest run(s) of ascending prime gaps up to \" << limit << \":\\n\";\n for (const auto& v : max_asc)\n print_diffs(v);\n std::cout << \"\\nLongest run(s) of descending prime gaps up to \" << limit << \":\\n\";\n for (const auto& v : max_desc)\n print_diffs(v);\n return 0;\n}\n", "language": "C++" }, { "code": "using System.Linq;\nusing System.Collections.Generic;\nusing TG = System.Tuple<int, int>;\nusing static System.Console;\n\nclass Program\n{\n static void Main(string[] args)\n {\n const int mil = (int)1e6;\n foreach (var amt in new int[] { 1, 2, 6, 12, 18 })\n {\n int lmt = mil * amt, lg = 0, ng, d, ld = 0;\n var desc = new string[] { \"A\", \"\", \"De\" };\n int[] mx = new int[] { 0, 0, 0 },\n bi = new int[] { 0, 0, 0 },\n c = new int[] { 2, 2, 2 };\n WriteLine(\"For primes up to {0:n0}:\", lmt);\n var pr = PG.Primes(lmt).ToArray();\n for (int i = 0; i < pr.Length; i++)\n {\n ng = pr[i].Item2; d = ng.CompareTo(lg) + 1;\n if (ld == d)\n c[2 - d]++;\n else\n {\n if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; }\n c[d] = 2;\n }\n ld = d; lg = ng;\n }\n for (int r = 0; r <= 2; r += 2)\n {\n Write(\"{0}scending, found run of {1} consecutive primes:\\n {2} \",\n desc[r], mx[r] + 1, pr[bi[r]++].Item1);\n foreach (var itm in pr.Skip(bi[r]).Take(mx[r]))\n Write(\"({0}) {1} \", itm.Item2, itm.Item1); WriteLine(r == 0 ? \"\" : \"\\n\");\n }\n }\n }\n}\n\nclass PG\n{\n public static IEnumerable<TG> Primes(int lim)\n {\n bool[] flags = new bool[lim + 1];\n int j = 3, lj = 2;\n for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n if (!flags[j])\n {\n yield return new TG(j, j - lj);\n lj = j;\n for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true;\n }\n for (; j <= lim; j += 2)\n if (!flags[j])\n {\n yield return new TG(j, j - lj);\n lj = j;\n }\n }\n}\n", "language": "C-sharp" }, { "code": "procedure LongestAscendDescend(Memo: TMemo);\n{Find the longest Ascending and Descending sequences of primes}\nvar I: integer;\nvar Sieve: TPrimeSieve;\n\n\tprocedure FindLongestSequence(Ascend: boolean);\n\t{Find the longest sequence - Ascend controls}\n\t{ whether it ascending or descending}\n\tvar I,J,Count,BestCount,BestStart: integer;\n var S: string;\n\n\t\tfunction Compare(N1,N2: integer; Ascend: boolean): boolean;\n\t\t{Compare for ascending or descending}\n\t\tbegin\n\t\tif Ascend then Result:=N1>N2\n\t\telse Result:=N1<N2;\n\t\tend;\n\n\tbegin\n\tBestStart:=0; BestCount:=0;\n\t{Check all the primes in the sieve}\n\tfor I:=2 to High(Sieve.Primes)-1 do\n\t\tbegin\n\t\tJ:=I + 1;\n\t\tCount:= 1;\n\t\t{Count all the elements in the sequence}\n\t\twhile (j<=High(Sieve.Primes)) and\n\t\t Compare(Sieve.Primes[J]-Sieve.Primes[J-1],Sieve.Primes[J-1]-Sieve.Primes[j-2],Ascend) do\n\t\t\tbegin\n\t\t\tInc(Count);\n\t\t\tInc(J);\n\t\t\tend;\n\t\t{Save the info if it is the best so far}\n\t\tif Count > BestCount then\n\t\t\tbegin\n\t\t\tBestStart:=I-1;\n\t\t\tBestCount:= Count;\n\t\t\tend;\n\t\tend;\n\tMemo.Lines.Add('Count = '+IntToStr(BestCount+1));\n\t{Display the sequence}\n\tS:='[';\n\tfor I:=BestStart to BestStart+BestCount do\n\t\tbegin\n\t\tS:=S+IntToStr(Sieve.Primes[I]);\n\t\tif I<(BestStart+BestCount) then S:=S+' ('+IntToStr(Sieve.Primes[I+1]-Sieve.Primes[I])+') ';\n\t\tend;\n\tS:=S+']';\n\tMemo.Lines.Add(S);\n\tend;\n\n\n\nbegin\nSieve:=TPrimeSieve.Create;\ntry\n{Generate all primes below 1 million}\nSieve.Intialize(1000000);\n\nMemo.Lines.Add('The longest sequence of ascending primes');\nFindLongestSequence(True);\nMemo.Lines.Add('The longest sequence of ascending primes');\nFindLongestSequence(False);\nfinally Sieve.Free; end;\nend;\n", "language": "Delphi" }, { "code": "fastfunc nextprim num .\n repeat\n i = 2\n while i <= sqrt num and num mod i <> 0\n i += 1\n .\n until num mod i <> 0\n num += 1\n .\n return num\n.\nproc getseq dir . maxprim maxcnt .\n maxcnt = 0\n pri = 2\n repeat\n prev = pri\n pri = nextprim (pri + 1)\n until pri > 1000000\n d0 = d\n d = (pri - prev) * dir\n if d > d0\n cnt += 1\n else\n if cnt > maxcnt\n maxcnt = cnt\n maxprim = prim0\n .\n prim0 = prev\n cnt = 1\n .\n .\n.\nproc outseq pri max . .\n write pri & \" \"\n for i to max\n pri = nextprim (pri + 1)\n write pri & \" \"\n .\n print \"\"\n.\ngetseq 1 pri max\noutseq pri max\ngetseq -1 pri max\noutseq pri max\n", "language": "EasyLang" }, { "code": "// Longest ascending and decending sequences of difference between consecutive primes: Nigel Galloway. April 5th., 2021\nlet fN g fW=primes32()|>Seq.takeWhile((>)g)|>Seq.pairwise|>Seq.fold(fun(n,i,g)el->let w=fW el in match w>n with true->(w,el::i,g) |_->(w,[el],if List.length i>List.length g then i else g))(0,[],[])\nfor i in [1;2;6;12;18;100] do let _,_,g=fN(i*1000000)(fun(n,g)->g-n) in printfn \"Longest ascending upto %d000000->%d:\" i (g.Length+1); g|>List.rev|>List.iter(fun(n,g)->printf \"%d (%d) %d \" n (g-n) g); printfn \"\"\n let _,_,g=fN(i*1000000)(fun(n,g)->n-g) in printfn \"Longest decending upto %d000000->%d:\" i (g.Length+1); g|>List.rev|>List.iter(fun(n,g)->printf \"%d (%d) %d \" n (g-n) g); printfn \"\"\n", "language": "F-Sharp" }, { "code": "USING: arrays assocs formatting grouping io kernel literals math\nmath.primes math.statistics sequences sequences.extras\ntools.memory.private ;\n\n<< CONSTANT: limit 1,000,000 >>\n\nCONSTANT: primes $[ limit primes-upto ]\n\n: run ( n quot -- seq quot )\n [ primes ] [ <clumps> ] [ ] tri*\n '[ differences _ monotonic? ] ; inline\n\n: max-run ( quot -- n )\n 1 swap '[ 1 + dup _ run find drop ] loop 1 - ; inline\n\n: runs ( quot -- seq )\n [ max-run ] keep run filter ; inline\n\n: .run ( seq -- )\n dup differences [ [ commas ] map ] bi@\n [ \"(\" \")\" surround ] map 2array round-robin \" \" join print ;\n\n: .runs ( quot -- )\n [ runs ] keep [ < ] = \"rising\" \"falling\" ? limit commas\n \"Largest run(s) of %s gaps between primes less than %s:\\n\"\n printf [ .run ] each ; inline\n\n[ < ] [ > ] [ .runs nl ] bi@\n", "language": "Factor" }, { "code": "#define UPPER 1000000\n#include\"isprime.bas\"\n\ndim as uinteger champ = 0, record = 0, streak, i, j, n\n\n'first generate all the primes below UPPER\nredim as uinteger prime(1 to 2)\nprime(1) = 2 : prime(2) = 3\nfor i = 5 to UPPER step 2\n if isprime(i) then\n redim preserve prime(1 to ubound(prime) + 1)\n prime(ubound(prime)) = i\n end if\nnext i\nn = ubound(prime)\n\n'now look for the longest streak of ascending primes\nfor i = 2 to n-1\n j = i + 1\n streak = 1\n while j<=n andalso prime(j)-prime(j-1) > prime(j-1)-prime(j-2)\n streak += 1\n j+=1\n wend\n if streak > record then\n champ = i-1\n record = streak\n end if\nnext i\n\nprint \"The longest sequence of ascending primes (with their difference from the last one) is:\"\nfor i = champ+1 to champ+record\n print prime(i-1);\" (\";prime(i)-prime(i-1);\") \";\nnext i\nprint prime(i-1) : print\n'now for the descending ones\n\nrecord = 0 : champ = 0\nfor i = 2 to n-1\n j = i + 1\n streak = 1\n while j<=n andalso prime(j)-prime(j-1) < prime(j-1)-prime(j-2) 'identical to above, but for the inequality sign\n streak += 1\n j+=1\n wend\n if streak > record then\n champ = i-1\n record = streak\n end if\nnext i\n\nprint \"The longest sequence of descending primes (with their difference from the last one) is:\"\nfor i = champ+1 to champ+record\n print prime(i-1);\" (\";prime(i)-prime(i-1);\") \";\nnext i\nprint prime(i-1)\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"rcu\"\n)\n\nconst LIMIT = 999999\n\nvar primes = rcu.Primes(LIMIT)\n\nfunc longestSeq(dir string) {\n pd := 0\n longSeqs := [][]int{{2}}\n currSeq := []int{2}\n for i := 1; i < len(primes); i++ {\n d := primes[i] - primes[i-1]\n if (dir == \"ascending\" && d <= pd) || (dir == \"descending\" && d >= pd) {\n if len(currSeq) > len(longSeqs[0]) {\n longSeqs = [][]int{currSeq}\n } else if len(currSeq) == len(longSeqs[0]) {\n longSeqs = append(longSeqs, currSeq)\n }\n currSeq = []int{primes[i-1], primes[i]}\n } else {\n currSeq = append(currSeq, primes[i])\n }\n pd = d\n }\n if len(currSeq) > len(longSeqs[0]) {\n longSeqs = [][]int{currSeq}\n } else if len(currSeq) == len(longSeqs[0]) {\n longSeqs = append(longSeqs, currSeq)\n }\n fmt.Println(\"Longest run(s) of primes with\", dir, \"differences is\", len(longSeqs[0]), \":\")\n for _, ls := range longSeqs {\n var diffs []int\n for i := 1; i < len(ls); i++ {\n diffs = append(diffs, ls[i]-ls[i-1])\n }\n for i := 0; i < len(ls)-1; i++ {\n fmt.Print(ls[i], \" (\", diffs[i], \") \")\n }\n fmt.Println(ls[len(ls)-1])\n }\n fmt.Println()\n}\n\nfunc main() {\n fmt.Println(\"For primes < 1 million:\\n\")\n for _, dir := range []string{\"ascending\", \"descending\"} {\n longestSeq(dir)\n }\n}\n", "language": "Go" }, { "code": "import Data.Numbers.Primes (primes)\n\n-- generates consecutive subsequences defined by given equivalence relation\nconsecutives equiv = filter ((> 1) . length) . go []\n where\n go r [] = [r]\n go [] (h : t) = go [h] t\n go (y : ys) (h : t)\n | y `equiv` h = go (h : y : ys) t\n | otherwise = (y : ys) : go [h] t\n\n-- finds maximal values in a list and returns the first one\nmaximumBy g (h : t) = foldr f h t\n where\n f r x = if g r < g x then x else r\n\n-- the task implementation\ntask ord n = reverse $ p + s : p : (fst <$> rest)\n where\n (p, s) : rest =\n maximumBy length $\n consecutives (\\(_, a) (_, b) -> a `ord` b) $\n differences $\n takeWhile (< n) primes\n differences l = zip l $ zipWith (-) (tail l) l\n", "language": "Haskell" }, { "code": " ;{.(\\: #@>) tris <@~.@,;._1~ <:/ 2 -/\\ |: tris=: 3 ]\\ p: i. p:inv 1e6\n128981 128983 128987 128993 129001 129011 129023 129037\n ;{.(\\: #@>) tris <@~.@,;._1~ >:/ 2 -/\\ |: tris=: 3 ]\\ p: i. p:inv 1e6\n322171 322193 322213 322229 322237 322243 322247 322249\n", "language": "J" }, { "code": "import java.util.ArrayList;\nimport java.util.BitSet;\nimport java.util.List;\n\npublic final class ConsecutivePrimes {\n\n\tpublic static void main(String[] aArgs) {\n\t\tfinal int limit = 1_000_000;\n\t\tList<Integer> primes = listPrimeNumbers(limit);\n\t\t\n\t\tList<Integer> asc = new ArrayList<Integer>();\n\t\tList<Integer> desc = new ArrayList<Integer>();\n\t\tList<List<Integer>> maxAsc = new ArrayList<List<Integer>>();\n\t\tList<List<Integer>> maxDesc = new ArrayList<List<Integer>>();\n\t int maxAscSize = 0;\n\t int maxDescSize = 0;\n\t\n\t for ( int prime : primes ) {\n\t \t final int ascSize = asc.size();\n\t if ( ascSize > 1 && prime - asc.get(ascSize - 1) <= asc.get(ascSize - 1) - asc.get(ascSize - 2) ) {\n\t asc = new ArrayList<Integer>(asc.subList(ascSize - 1, asc.size()));\n\t }\t\n\t asc.add(prime);\n\t\n\t if ( asc.size() >= maxAscSize ) {\n\t if ( asc.size() > maxAscSize ) {\n\t maxAscSize = asc.size();\n\t maxAsc.clear();\n\t }\n\t maxAsc.add( new ArrayList<Integer>(asc) );\n\t }\n\t\n\t final int descSize = desc.size();\n\t if ( descSize > 1 && prime - desc.get(descSize - 1) >= desc.get(descSize - 1) - desc.get(descSize - 2) ) {\n\t desc = new ArrayList<Integer>(desc.subList(descSize - 1, desc.size()));\n\t }\n\t desc.add(prime);\n\t\n\t if ( desc.size() >= maxDescSize ) {\n\t if ( desc.size() > maxDescSize ) {\n\t maxDescSize = desc.size();\n\t maxDesc.clear();\n\t }\n\t maxDesc.add( new ArrayList<Integer>(desc) );\n\t }\n\t }\n\t\n\t System.out.println(\"Longest run(s) of ascending prime gaps up to \" + limit + \":\");\n\t for ( List<Integer> list : maxAsc ) {\n\t displayResult(list);\n\t }\n\t System.out.println();\n\t\n\t System.out.println(\"Longest run(s) of descending prime gaps up to \" + limit + \":\");\n\t for( List<Integer> list : maxDesc ) {\n\t displayResult(list);\n\t }\n\t}\n\t\n\tprivate static List<Integer> listPrimeNumbers(int aLimit) {\n\t\tBitSet sieve = new BitSet(aLimit + 1);\n\t\tsieve.set(2, aLimit + 1);\n\t\tfor ( int i = 2; i <= Math.sqrt(aLimit); i = sieve.nextSetBit(i + 1) ) {\n\t\t\tfor ( int j = i * i; j <= aLimit; j = j + i ) {\n\t\t\t\tsieve.clear(j);\n\t\t\t}\n\t\t}\n\t\t\n\t\tList<Integer> result = new ArrayList<Integer>(sieve.cardinality());\n\t\tfor ( int i = 2; i >= 0; i = sieve.nextSetBit(i + 1) ) {\n\t\t\tresult.add(i);\n\t\t}\n\t\treturn result;\n\t}\n\t\n\tprivate static void displayResult(List<Integer> aList) {\n\t\tfor ( int i = 0; i < aList.size(); i++ ) {\n\t if ( i > 0 ) {\n\t System.out.print(\" (\" + ( aList.get(i) - aList.get(i - 1) ) + \") \");\n\t }\n\t System.out.print(aList.get(i));\n\t }\n\t System.out.println();\n\t}\n\n}\n", "language": "Java" }, { "code": "# For streams of strings or of arrays or of numbers:\ndef add(s): reduce s as $x (null; .+$x);\n\n# Primes less than . // infinite\ndef primes:\n (. // infinite) as $n\n | if $n < 3 then empty\n else 2, (range(3; $n) | select(is_prime))\n end;\n", "language": "Jq" }, { "code": "# Input: null or limit+1\n# Output: informative strings\ndef longestSequences:\n [primes] as $primes\n | def longestSeq(direction):\n { pd: 0,\n longSeqs: [[2]],\n currSeq: [2] }\n | reduce range( 1; $primes|length) as $i (.;\n ($primes[$i] - $primes[$i-1]) as $d\n | if (direction == \"ascending\" and $d <= .pd) or (direction == \"descending\" and $d >= .pd)\n then if (.currSeq|length) > (.longSeqs[0]|length)\n then .longSeqs = [.currSeq]\n else if (.currSeq|length) == (.longSeqs[0]|length)\n then .longSeqs += [.currSeq]\n else .\n end\n end\n | .currSeq = [$primes[$i-1], $primes[$i]]\n else .currSeq += [$primes[$i]]\n end\n | .pd = $d\n )\n | if (.currSeq|length) > (.longSeqs[0]|length)\n then .longSeqs = [.currSeq]\n else if (.currSeq|length) == (.longSeqs[0]|length)\n then .longSeqs = .longSeqs + [.currSeq]\n else .\n end\n end\n\n | \"Longest run(s) of primes with \\(direction) differences is \\(.longSeqs[0]|length):\",\n (.longSeqs[] as $ls\n | add( range(1; $ls|length) | [$ls[.] - $ls[.-1]]) as $diffs\n | add( range(0; $ls|length-1) | \"\\($ls[.]) (\\($diffs[.])) \") + \"\\($ls[-1])\" );\n\n longestSeq(\"ascending\"), \"\", longestSeq(\"descending\");\n\n\"For primes < 1 million:\",\n ( 1E6 | longestSequences )\n", "language": "Jq" }, { "code": "using Primes\n\nfunction primediffseqs(maxnum = 1_000_000)\n mprimes = primes(maxnum)\n diffs = map(p -> mprimes[p[1] + 1] - p[2], enumerate(@view mprimes[begin:end-1]))\n incstart, decstart, bestinclength, bestdeclength = 1, 1, 0, 0\n for i in 1:length(diffs)-1\n foundinc, founddec = false, false\n for j in i+1:length(diffs)\n if !foundinc && diffs[j] <= diffs[j - 1]\n if (runlength = j - i) > bestinclength\n bestinclength, incstart = runlength, i\n end\n foundinc = true\n end\n if !founddec && diffs[j] >= diffs[j - 1]\n if (runlength = j - i) > bestdeclength\n bestdeclength, decstart = runlength, i\n end\n founddec = true\n end\n foundinc && founddec && break\n end\n end\n println(\"Ascending: \", mprimes[incstart:incstart+bestinclength], \" Diffs: \", diffs[incstart:incstart+bestinclength-1])\n println(\"Descending: \", mprimes[decstart:decstart+bestdeclength], \" Diffs: \", diffs[decstart:decstart+bestdeclength-1])\nend\n\nprimediffseqs()\n", "language": "Julia" }, { "code": "function findcps(primelist, fcmp)\n local currlist = {primelist[1]}\n local longlist, prevdiff = currlist, 0\n for i = 2, #primelist do\n local diff = primelist[i] - primelist[i-1]\n if fcmp(diff, prevdiff) then\n currlist[#currlist+1] = primelist[i]\n if #currlist > #longlist then\n longlist = currlist\n end\n else\n currlist = {primelist[i-1], primelist[i]}\n end\n prevdiff = diff\n end\n return longlist\nend\n\nprimegen:generate(nil, 1000000)\ncplist = findcps(primegen.primelist, function(a,b) return a>b end)\nprint(\"ASC (\"..#cplist..\"): [\"..table.concat(cplist, \" \")..\"]\")\ncplist = findcps(primegen.primelist, function(a,b) return a<b end)\nprint(\"DESC (\"..#cplist..\"): [\"..table.concat(cplist, \" \")..\"]\")\n", "language": "Lua" }, { "code": "prime = Prime[Range[PrimePi[10^6]]];\ns = Split[Differences[prime], Less];\nmax = Max[Length /@ s];\ndiffs = Select[s, Length/*EqualTo[max]];\nseqs = SequencePosition[Flatten[s], #, 1][[1]] & /@ diffs;\nTake[prime, # + {0, 1}] & /@ seqs\n\ns = Split[Differences[prime], Greater];\nmax = Max[Length /@ s];\ndiffs = Select[s, Length/*EqualTo[max]];\nseqs = SequencePosition[Flatten[s], #, 1][[1]] & /@ diffs;\nTake[prime, # + {0, 1}] & /@ seqs\n", "language": "Mathematica" }, { "code": "import math, strformat, sugar\n\nconst N = 1_000_000\n\n####################################################################################################\n# Erathostenes sieve.\n\nvar composite: array[2..N, bool] # Initialized to false i.e. prime.\n\nfor n in 2..int(sqrt(float(N))):\n if not composite[n]:\n for k in countup(n * n, N, n):\n composite[k] = true\n\nlet primes = collect(newSeq):\n for n in 2..N:\n if not composite[n]: n\n\n\n####################################################################################################\n# Longest sequences.\n\ntype Order {.pure.} = enum Ascending, Descending\n\nproc longestSeq(order: Order): seq[int] =\n ## Return the longest sequence for the given order.\n\n let ascending = order == Ascending\n var\n currseq: seq[int]\n prevPrime = 2\n diff = if ascending: 0 else: N\n\n for prime in primes:\n let nextDiff = prime - prevPrime\n if nextDiff != diff and nextDiff > diff == ascending:\n currseq.add prime\n else:\n if currseq.len > result.len:\n result = move(currseq)\n currseq = @[prevPrime, prime]\n diff = nextDiff\n prevPrime = prime\n\n if currseq.len > result.len:\n result = move(currseq)\n\n\nproc `$`(list: seq[int]): string =\n ## Return the representation of a list of primes with interleaved differences.\n var prevPrime: int\n for i, prime in list:\n if i != 0: result.add &\" ({prime - prevPrime}) \"\n result.addInt prime\n prevPrime = prime\n\necho \"For primes < 1000000.\\n\"\necho \"First longest sequence of consecutive primes with ascending differences:\"\necho longestSeq(Ascending)\necho()\necho \"First longest sequence of consecutive primes with descending differences:\"\necho longestSeq(Descending)\n", "language": "Nim" }, { "code": "showPrecPrimes(p, n)=\n{\n my(v=vector(n));\n v[n]=p;\n forstep(i=n-1,1,-1,\n v[i]=precprime(v[i+1]-1)\n );\n for(i=1,n, print1(v[i]\" \"));\n}\nlist(lim)=\n{\n my(p=3,asc,dec,ar,dr,arAt=3,drAt=3,last=2);\n forprime(q=5,lim,\n my(g=q-p);\n if(g<last,\n asc=0;\n if(desc++>dr,\n dr=desc;\n drAt=q\n )\n ,g>last,\n desc=0;\n if(asc++>ar,\n ar=asc;\n arAt=q\n )\n ,\n asc=desc=0\n );\n p=q;\n last=g\n );\n print(\"Descending differences:\");\n showPrecPrimes(drAt, dr+2);\n print(\"\\nAscending differences:\");\n showPrecPrimes(arAt, ar+2);\n}\nlist(10^6)\n", "language": "PARI-GP" }, { "code": "use strict;\nuse warnings;\nuse feature 'say';\nuse ntheory 'primes';\nuse List::AllUtils <indexes max>;\n\nmy $limit = 1000000;\nmy @primes = @{primes( $limit )};\n\nsub runs {\n my($op) = @_;\n my @diff = my $diff = my $run = 1;\n push @diff, map {\n my $next = $primes[$_] - $primes[$_ - 1];\n if ($op eq '>') { if ($next > $diff) { ++$run } else { $run = 1 } }\n else { if ($next < $diff) { ++$run } else { $run = 1 } }\n $diff = $next;\n $run\n } 1 .. $#primes;\n\n my @prime_run;\n my $max = max @diff;\n for my $r ( indexes { $_ == $max } @diff ) {\n push @prime_run, join ' ', map { $primes[$r - $_] } reverse 0..$max\n }\n @prime_run\n}\n\nsay \"Longest run(s) of ascending prime gaps up to $limit:\\n\" . join \"\\n\", runs('>');\nsay \"\\nLongest run(s) of descending prime gaps up to $limit:\\n\" . join \"\\n\", runs('<');\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">pn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- prime numb</span>\n <span style=\"color: #000000;\">lp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- last prime</span>\n <span style=\"color: #000000;\">lg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- last gap</span>\n <span style=\"color: #000000;\">pd</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #000080;font-style:italic;\">-- prev d</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #000080;font-style:italic;\">-- curr run [a,d]</span>\n <span style=\"color: #000000;\">mr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}}</span> <span style=\"color: #000080;font-style:italic;\">-- max runs \"\"</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">pn</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">get_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pn</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">gap</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">lp</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">compare</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">gap</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">lg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">1e6</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">d</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">2</span>\n <span style=\"color: #000000;\">cr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">pd</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">cr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]:</span><span style=\"color: #000000;\">lp</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">cr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]></span><span style=\"color: #000000;\">mr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">mr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">cr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">pn</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">pd</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">lp</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">lg</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">gap</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">run</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">mr</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">run</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">apply</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #7060A8;\">get_prime</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">g</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_sub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">..$],</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"longest %s run length %d: %v gaps: %v\\n\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #008000;\">\"ascending\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"descending\"</span><span style=\"color: #0000FF;\">}[</span><span style=\"color: #000000;\">run</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "from sympy import sieve\n\nprimelist = list(sieve.primerange(2,1000000))\n\nlistlen = len(primelist)\n\n# ascending\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n diff = primelist[pindex] - primelist[pindex-1]\n if diff > old_diff:\n curr_list.append(primelist[pindex])\n if len(curr_list) > len(longest_list):\n longest_list = curr_list\n else:\n curr_list = [primelist[pindex-1],primelist[pindex]]\n\n old_diff = diff\n pindex += 1\n\nprint(longest_list)\n\n# descending\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n diff = primelist[pindex] - primelist[pindex-1]\n if diff < old_diff:\n curr_list.append(primelist[pindex])\n if len(curr_list) > len(longest_list):\n longest_list = curr_list\n else:\n curr_list = [primelist[pindex-1],primelist[pindex]]\n\n old_diff = diff\n pindex += 1\n\nprint(longest_list)\n", "language": "Python" }, { "code": "use Math::Primesieve;\nuse Lingua::EN::Numbers;\n\nmy $sieve = Math::Primesieve.new;\n\nmy $limit = 1000000;\n\nmy @primes = $sieve.primes($limit);\n\nsub runs (&op) {\n my $diff = 1;\n my $run = 1;\n\n my @diff = flat 1, (1..^@primes).map: {\n my $next = @primes[$_] - @primes[$_ - 1];\n if &op($next, $diff) { ++$run } else { $run = 1 }\n $diff = $next;\n $run;\n }\n\n my $max = max @diff;\n my @runs = @diff.grep: * == $max, :k;\n\n @runs.map( {\n my @run = (0..$max).reverse.map: -> $r { @primes[$_ - $r] }\n flat roundrobin(@run».&comma, @run.rotor(2 => -1).map({[R-] $_})».fmt('(%d)'));\n } ).join: \"\\n\"\n}\n\nsay \"Longest run(s) of ascending prime gaps up to {comma $limit}:\\n\" ~ runs(&infix:«>»);\n\nsay \"\\nLongest run(s) of descending prime gaps up to {comma $limit}:\\n\" ~ runs(&infix:«<»);\n", "language": "Raku" }, { "code": "/*REXX program finds the longest sequence of consecutive primes where the differences */\n/*──────────── between the primes are strictly ascending; also for strictly descending.*/\nparse arg hi cols . /*obtain optional argument from the CL.*/\nif hi=='' | hi==\",\" then hi= 1000000 /* \" \" \" \" \" \" */\nif cols=='' | cols==\",\" then cols= 10 /* \" \" \" \" \" \" */\ncall genP /*build array of semaphores for primes.*/\nw= 10 /*width of a number in any column. */\ncall fRun 1; call show 1 /*find runs with ascending prime diffs.*/\ncall fRun 0; call show 0 /* \" \" \" descending \" \" */\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncommas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nfRun: parse arg ?; mxrun=0; seq.= /*max run length; lists of prime runs.*/\n /*search for consecutive primes < HI.*/\n do j=2 for #-2; cp= @.j; jn= j+1 /*CP: current prime; JN: next j */\n diff= @.jn - cp /*get difference between last 2 primes.*/\n cnt= 1; run= /*initialize the CNT and RUN. */\n do k= jn+1 to #-2; km= k-1 /*look for more primes in this run. */\n if ? then if @[email protected]<=diff then leave /*Diff. too small? Stop looking*/\n else nop\n else if @[email protected]>=diff then leave /* \" \" large? \" \" */\n run= run @.k; cnt= cnt+1 /*append a prime to the run; bump count*/\n diff= @.k - @.km /*calculate difference for next prime. */\n end /*k*/\n if cnt<=mxrun then iterate /*This run too short? Then keep looking*/\n mxrun= max(mxrun, cnt) /*define a new maximum run (seq) length*/\n seq.mxrun= cp @.jn run /*full populate the sequence (RUN). */\n end /*j*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ngenP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19 /*define low primes.*/\n #=8; sq.#= @.# ** 2 /*number of primes so far; prime sqiare*/\n /* [↓] generate more primes ≤ high.*/\n do j=@.#+2 by 2 to hi; parse var j '' -1 _ /*find odd primes from here on.*/\n if _==5 then iterate; if j// 3==0 then iterate /*J ÷ 5? J ÷ by 3? */\n if j// 7==0 then iterate; if j//11==0 then iterate /*\" \" 7? \" \" \" 11? */\n if j//13==0 then iterate; if j//17==0 then iterate /*\" \" 13? \" \" \" 17? */\n do k=8 while sq.k<=j /* [↓] divide by the known odd primes.*/\n if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */\n end /*k*/ /* [↑] only process numbers ≤ √ J */\n #= #+1; @.#= j; sq.#= j*j /*bump # of Ps; assign next P; P square*/\n end /*j*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nshow: parse arg ?; if ? then AorD= 'ascending' /*choose which literal for display.*/\n else AorD= 'descending' /* \" \" \" \" \" */\n title= ' longest run of consecutive primes whose differences between primes are' ,\n 'strictly' AorD \"and < \" commas(hi)\n say; say; say\n if cols>0 then say ' index │'center(title, 1 + cols*(w+1) )\n if cols>0 then say '───────┼'center(\"\" , 1 + cols*(w+1), '─')\n found= 0; idx= 1 /*initialize # of consecutive primes. */\n $= /*a list of consecutive primes (so far)*/\n do o=1 for words(seq.mxrun) /*show all consecutive primes in seq. */\n c= commas( word(seq.mxrun, o) ) /*obtain the next prime in the sequence*/\n found= found + 1 /*bump the number of consecutive primes*/\n if cols<=0 then iterate /*build the list (to be shown later)? */\n $= $ right(c, max(w, length(c) ) ) /*add a nice prime ──► list, allow big#*/\n if found//cols\\==0 then iterate /*have we populated a line of output? */\n say center(idx, 7)'│' substr($, 2) /*display what we have so far (cols). */\n idx= idx + cols; $= /*bump the index count for the output*/\n end /*o*/\n if $\\=='' then say center(idx, 7)\"│\" substr($, 2) /*maybe show residual output*/\n if cols>0 then say '───────┴'center(\"\" , 1 + cols*(w+1), '─')\n say; say commas(Cprimes) ' was the'title; return\n", "language": "REXX" }, { "code": "require \"prime\"\nlimit = 1_000_000\n\nputs \"First found longest run of ascending prime gaps up to #{limit}:\"\np Prime.each(limit).each_cons(2).chunk_while{|(i1,i2), (j1,j2)| j1-i1 < j2-i2 }.max_by(&:size).flatten.uniq\nputs \"\\nFirst found longest run of descending prime gaps up to #{limit}:\"\np Prime.each(limit).each_cons(2).chunk_while{|(i1,i2), (j1,j2)| j1-i1 > j2-i2 }.max_by(&:size).flatten.uniq\n", "language": "Ruby" }, { "code": "// [dependencies]\n// primal = \"0.3\"\n\nfn print_diffs(vec: &[usize]) {\n for i in 0..vec.len() {\n if i > 0 {\n print!(\" ({}) \", vec[i] - vec[i - 1]);\n }\n print!(\"{}\", vec[i]);\n }\n println!();\n}\n\nfn main() {\n let limit = 1000000;\n let mut asc = Vec::new();\n let mut desc = Vec::new();\n let mut max_asc = Vec::new();\n let mut max_desc = Vec::new();\n let mut max_asc_len = 0;\n let mut max_desc_len = 0;\n for p in primal::Sieve::new(limit)\n .primes_from(2)\n .take_while(|x| *x < limit)\n {\n let alen = asc.len();\n if alen > 1 && p - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2] {\n asc = asc.split_off(alen - 1);\n }\n asc.push(p);\n if asc.len() >= max_asc_len {\n if asc.len() > max_asc_len {\n max_asc_len = asc.len();\n max_asc.clear();\n }\n max_asc.push(asc.clone());\n }\n let dlen = desc.len();\n if dlen > 1 && p - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2] {\n desc = desc.split_off(dlen - 1);\n }\n desc.push(p);\n if desc.len() >= max_desc_len {\n if desc.len() > max_desc_len {\n max_desc_len = desc.len();\n max_desc.clear();\n }\n max_desc.push(desc.clone());\n }\n }\n println!(\"Longest run(s) of ascending prime gaps up to {}:\", limit);\n for v in max_asc {\n print_diffs(&v);\n }\n println!(\"\\nLongest run(s) of descending prime gaps up to {}:\", limit);\n for v in max_desc {\n print_diffs(&v);\n }\n}\n", "language": "Rust" }, { "code": "func runs(f, arr) {\n\n var run = 0\n var diff = 0\n var diffs = []\n\n arr.each_cons(2, {|p1,p2|\n var curr_diff = (p2 - p1)\n f(curr_diff, diff) ? ++run : (run = 1)\n diff = curr_diff\n diffs << run\n })\n\n var max = diffs.max\n var runs = []\n\n diffs.indices_by { _ == max }.each {|i|\n runs << arr.slice(i - max + 1, i + 1)\n }\n\n return runs\n}\n\nvar limit = 1e6\nvar primes = limit.primes\n\nsay \"Longest run(s) of ascending prime gaps up to #{limit.commify}:\"\nsay runs({|a,b| a > b }, primes).join(\"\\n\")\n\nsay \"\\nLongest run(s) of descending prime gaps up to #{limit.commify}:\"\nsay runs({|a,b| a < b }, primes).join(\"\\n\")\n", "language": "Sidef" }, { "code": "import \"./math\" for Int\n\nvar LIMIT = 999999\nvar primes = Int.primeSieve(LIMIT)\n\nvar longestSeq = Fn.new { |dir|\n var pd = 0\n var longSeqs = [[2]]\n var currSeq = [2]\n for (i in 1...primes.count) {\n var d = primes[i] - primes[i-1]\n if ((dir == \"ascending\" && d <= pd) || (dir == \"descending\" && d >= pd)) {\n if (currSeq.count > longSeqs[0].count) {\n longSeqs = [currSeq]\n } else if (currSeq.count == longSeqs[0].count) longSeqs.add(currSeq)\n currSeq = [primes[i-1], primes[i]]\n } else {\n currSeq.add(primes[i])\n }\n pd = d\n }\n if (currSeq.count > longSeqs[0].count) {\n longSeqs = [currSeq]\n } else if (currSeq.count == longSeqs[0].count) longSeqs.add(currSeq)\n System.print(\"Longest run(s) of primes with %(dir) differences is %(longSeqs[0].count):\")\n for (ls in longSeqs) {\n var diffs = []\n for (i in 1...ls.count) diffs.add(ls[i] - ls[i-1])\n for (i in 0...ls.count-1) System.write(\"%(ls[i]) (%(diffs[i])) \")\n System.print(ls[-1])\n }\n System.print()\n}\n\nSystem.print(\"For primes < 1 million:\\n\")\nfor (dir in [\"ascending\", \"descending\"]) longestSeq.call(dir)\n", "language": "Wren" }, { "code": "func IsPrime(N); \\Return 'true' if N > 2 is a prime number\nint N, I;\n[if (N&1) = 0 \\even number\\ then return false;\nfor I:= 3 to sqrt(N) do\n [if rem(N/I) = 0 then return false;\n I:= I+1;\n ];\nreturn true;\n];\n\nproc ShowSeq(Dir, Str); \\Show longest sequence of distances between primes\nint Dir, Str;\nint Count, MaxCount, N, P, P0, D, D0, I, AP(1000), MaxAP(1000);\n[Count:= 0; MaxCount:= 0;\nP0:= 2; D0:= 0; \\preceding prime and distance\nAP(Count):= P0; Count:= Count+1;\nfor N:= 3 to 1_000_000-1 do\n if IsPrime(N) then\n [P:= N; \\got a prime number\n D:= P - P0; \\distance from preceding prime\n if D*Dir > D0*Dir then\n [AP(Count):= P; Count:= Count+1;\n if Count > MaxCount then \\save best sequence\n [MaxCount:= Count;\n for I:= 0 to MaxCount-1 do\n MaxAP(I):= AP(I);\n ];\n ]\n else\n [Count:= 0; \\restart sequence\n AP(Count):= P0; Count:= Count+1; \\possible beginning\n AP(Count):= P; Count:= Count+1;\n ];\n P0:= P; D0:= D;\n ];\nText(0, \"Longest sequence of \"); Text(0, Str);\nText(0, \" distances between primes: \"); IntOut(0, MaxCount); CrLf(0);\nfor I:= 0 to MaxCount-2 do\n [IntOut(0, MaxAP(I));\n Text(0, \" (\");\n IntOut(0, MaxAP(I+1) - MaxAP(I));\n Text(0, \") \");\n ];\nIntOut(0, MaxAP(I)); CrLf(0);\n];\n\n[ShowSeq(+1, \"ascending\"); \\main\n ShowSeq(-1, \"descending\");\n]\n", "language": "XPL0" } ]
Consecutive-primes-with-ascending-or-descending-differences
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Constrained_random_points_on_a_circle\nnote: Probability and statistics\n", "language": "00-META" }, { "code": ";Task:\nGenerate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that <br><math>10 \\leq \\sqrt{ x^2 + y^2 } \\leq 15 </math>. <br>Then display/plot them. The outcome should be a \"fuzzy\" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.\n\nThere are several possible approaches to accomplish this. Here are two possible algorithms.\n\n1) Generate random pairs of integers and filter out those that don't satisfy this condition:\n:<math>10 \\leq \\sqrt{ x^2 + y^2 } \\leq 15 </math>.\n\n2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F print_circle(lo, hi, ndots)\n V canvas = [[0B] * (2*hi+1)] * (2*hi+1)\n V i = 0\n L i < ndots\n V x = random:(-hi..hi)\n V y = random:(-hi..hi)\n I x^2 + y^2 C lo^2 .. hi^2\n canvas[x + hi][y + hi] = 1B\n i++\n\n L(i) 0 .. 2*hi\n print(canvas[i].map(j -> I j {‘♦ ’} E ‘ ’).join(‘’))\n\nprint_circle(10, 15, 100)\n", "language": "11l" }, { "code": "PROC DrawCircle(BYTE rmin,rmax,max,x0,y0)\n BYTE count,limit\n INT x,y,r2,rmin2,rmax2\n\n limit=rmax*2+1\n rmin2=rmin*rmin\n rmax2=rmax*rmax\n count=0\n WHILE count<max\n DO\n x=Rand(limit) y=Rand(limit)\n x==-rmax y==-rmax\n r2=x*x+y*y\n IF r2>=rmin2 AND r2<=rmax2 THEN\n Plot(x+x0,y+y0)\n count==+1\n FI\n OD\nRETURN\n\nPROC Main()\n BYTE CH=$02FC,COLOR0=$02C4\n\n Graphics(5+16)\n Color=1\n COLOR0=$0C\n\n DrawCircle(10,15,100,40,24)\n\n DO UNTIL CH#$FF OD\n CH=$FF\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO;\nwith Ada.Numerics.Discrete_Random;\nprocedure Circle is\n -- extreme coordinate values are -15:0, 15:0, 0:-15, 0:15\n subtype Coordinate is Integer range -15 .. 15;\n type Point is record\n X, Y : Coordinate;\n end record;\n type Point_List is array (Positive range <>) of Point;\n\n function Acceptable (Position : Point) return Boolean is\n Squared_Sum : Natural := Position.X ** 2 + Position.Y ** 2;\n begin\n return 10 ** 2 <= Squared_Sum and Squared_Sum <= 15 ** 2;\n end Acceptable;\n\n -- first algorithm\n function Generate_Random_Points\n (Count : Positive := 100)\n return Point_List\n is\n package RNG is new Ada.Numerics.Discrete_Random (Coordinate);\n Generator : RNG.Generator;\n Next_Point : Point;\n Result : Point_List (1 .. Count);\n begin\n RNG.Reset (Generator);\n for N in Result'Range loop\n loop\n Next_Point.X := RNG.Random (Generator);\n Next_Point.Y := RNG.Random (Generator);\n exit when Acceptable (Next_Point);\n end loop;\n Result (N) := Next_Point;\n end loop;\n return Result;\n end Generate_Random_Points;\n\n -- second algorithm\n function Choose_Precalculated\n (Count : Positive := 100)\n return Point_List\n is\n subtype Possible_Points is Positive range 1 .. 404;\n package RNG is new Ada.Numerics.Discrete_Random (Possible_Points);\n Generator : RNG.Generator;\n Point_Pool : Point_List (Possible_Points);\n Next_Point : Point;\n Next_Index : Possible_Points := 1;\n Result : Point_List (1 .. Count);\n begin\n -- precalculate\n Precalculate : for X in Coordinate'Range loop\n Next_Point.X := X;\n for Y in Coordinate'Range loop\n Next_Point.Y := Y;\n if Acceptable (Next_Point) then\n Point_Pool (Next_Index) := Next_Point;\n exit Precalculate when Next_Index = Possible_Points'Last;\n Next_Index := Next_Index + 1;\n end if;\n end loop;\n end loop Precalculate;\n -- choose\n RNG.Reset (Generator);\n for N in Result'Range loop\n Result (N) := Point_Pool (RNG.Random (Generator));\n end loop;\n return Result;\n end Choose_Precalculated;\n\n procedure Print_Points (Points : Point_List) is\n Output_String : array (Coordinate, Coordinate) of Character :=\n (others => (others => ' '));\n begin\n for N in Points'Range loop\n Output_String (Points (N).X, Points (N).Y) := '*';\n end loop;\n for Line in Output_String'Range (2) loop\n for Column in Output_String'Range (1) loop\n Ada.Text_IO.Put (Output_String (Column, Line));\n end loop;\n Ada.Text_IO.New_Line;\n end loop;\n end Print_Points;\n\n My_Circle_Randomly : Point_List := Generate_Random_Points;\n My_Circle_Precalculated : Point_List := Choose_Precalculated;\nbegin\n Ada.Text_IO.Put_Line (\"Randomly generated:\");\n Print_Points (My_Circle_Randomly);\n Ada.Text_IO.Put_Line (\"Chosen from precalculated:\");\n Print_Points (My_Circle_Precalculated);\nend Circle;\n", "language": "Ada" }, { "code": "PROC clrscr = VOID:\n printf(($g\"[2J\"$,REPR 27)); # ansi.sys #\n\nPROC gotoxy = (INT x,y)VOID:\n printf(($g\"[\"g(0)\";\"g(0)\"H\"$,REPR 27, y,x)); # ansi.sys #\n\nMODE POINT = STRUCT(\n INT x,y\n);\n\nINT radius = 15;\nINT inside radius = 10;\n\nPOINT center = (radius+1, radius+1);\n\nFLEX[0]POINT set;\n\nPROC swap with last set = (INT position,INT where last set)VOID:\n(\n INT temp := x OF set[position];\n x OF set[position]:=x OF set[where last set];\n x OF set[where last set] := temp;\n\n temp := y OF set[position];\n y OF set[position]:=y OF set[where last set];\n y OF set[where last set] := temp\n);\n\nPROC create set = VOID:\n(\n set := HEAP[(2*radius+1)**2]POINT;\n INT x,y,i:=LWB set;\n\n FOR x FROM -radius TO radius DO\n FOR y FROM -radius TO radius DO\n IF sqrt(x*x+y*y)>=inside radius AND sqrt(x*x+y*y)<=radius THEN\n x OF set[i] := x;\n y OF set[i] := y;\n i+:=1\n FI\n OD\n OD;\n\n set:=set[:i-1]\n);\n\nPROC plot fuzzy set = (CHAR ch)VOID:\n(\n INT pos,i;\n\n TO UPB set DO\n pos := ENTIER(random * UPB set) + 1;\n\n gotoxy(x OF center + x OF set[pos],y OF center + y OF set[pos]);\n\n print(ch);\n\n swap with last set(pos,UPB set)\n\n OD\n);\n\nmain:\n(\n # srand((INT)time(NIL)); #\n\n clrscr;\n create set;\n plot fuzzy set(\"*\");\n gotoxy(2*radius+1, 2*radius+1);\n newline(stand in)\n)\n", "language": "ALGOL-68" }, { "code": "z=100 ; x = x-coord; y = y-coord; z = count; pBitmap = a pointer to the image; f = filename\n\npToken\t:= Gdip_Startup()\npBitmap := Gdip_CreateBitmap(31, 32)\n\nWhile z\n{\n\tRandom, x, -20, 20\n\tRandom, y, -20,20\n\tIf ( t := sqrt(x**2 + y**2) ) >= 10 && t <= 15\n\t\tGdip_SetPixel(pBitmap, x+15, y+16, 255<<24), z--\n}\n\nGdip_SaveBitmapToFile(pBitmap, f := A_ScriptDir \"\\ahk_fuzzycircle.png\")\nrun % f\n\nGdip_DisposeImage(pBitmap)\nGdip_Shutdown(pToken)\n", "language": "AutoHotkey" }, { "code": "graphsize 31, 31\n\nfor i = 1 to 100\n do\n\tx = int(rand * 30) - 15\n\ty = int(rand * 30) - 15\n\tr = sqr(x*x + y*y)\n until 10 <= r and r <= 15\n color rgb(255, 0, 0)\n plot(x+15, y+15)\nnext i\nend\n", "language": "BASIC256" }, { "code": " MODE 8\n ORIGIN 640, 512\n FOR i% = 1 TO 1000\n x% = RND(31)-16\n y% = RND(31)-16\n r = SQR(x%^2 + y%^2)\n IF r >= 10 IF r <= 15 PLOT x%*2, y%*2\n NEXT\n", "language": "BBC-BASIC" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n\ninline\nint randn(int m)\n{\n\tint rand_max = RAND_MAX - (RAND_MAX % m);\n\tint r;\n\twhile ((r = rand()) > rand_max);\n\treturn r / (rand_max / m);\n}\n\nint main()\n{\n\tint i, x, y, r2;\n\tunsigned long buf[31] = {0}; /* could just use 2d array */\n\n\tfor (i = 0; i < 100; ) {\n\t\tx = randn(31) - 15;\n\t\ty = randn(31) - 15;\n\t\tr2 = x * x + y * y;\n\t\tif (r2 >= 100 && r2 <= 225) {\n\t\t\tbuf[15 + y] |= 1 << (x + 15);\n\t\t\ti++;\n\t\t}\n\t}\n\n\tfor (y = 0; y < 31; y++) {\n\t\tfor (x = 0; x < 31; x++)\n\t\t\tprintf((buf[y] & 1 << x) ? \". \" : \" \");\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n", "language": "C" }, { "code": " . . . .\n . . .\n . . . .\n . . .\n . . . . .\n . . .\n . . .\n . .\n . .\n . .\n . .\n . . . .\n . . .\n\n .\n .\n\n . . .\n . . .\n . . .\n . . . .\n . . . . .\n . .\n . . . .\n . . . . . . .\n . . . .\n . . . . . . .\n . . . .\n .\n .\n", "language": "C" }, { "code": "#include <windows.h>\n#include <list>\n#include <iostream>\n\n//--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n//--------------------------------------------------------------------------------------------------\nclass point\n{\npublic:\n int x, y;\n point() { x = y = 0; }\n point( int a, int b ) { x = a; y = b; }\n void set( int a, int b ) { x = a; y = b; }\n};\n//--------------------------------------------------------------------------------------------------\nclass rndCircle\n{\npublic:\n void draw()\n {\n\tcreatePoints();\n\tdrawPoints();\n }\n\nprivate:\n void createPoints()\n {\n\tpoint pt;\n\tfor( int x = 0; x < 200; x++ )\n\t{\n\t int a, b, c;\n\t while( true )\n\t {\n\t\ta = rand() % 31 - 15;\n\t\tb = rand() % 31 - 15;\n\t\tc = a * a + b * b;\n\t\tif( c >= 100 && c <= 225 ) break;\n\t }\n\t pt.set( a, b );\n\t _ptList.push_back( pt );\n\t}\n }\n\n void drawPoints()\n {\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tfor( list<point>::iterator it = _ptList.begin(); it != _ptList.end(); it++ )\n\t SetPixel( dc, 300 + 10 * ( *it ).x, 300 + 10 * ( *it ).y, RGB( 255, 255, 0 ) );\n }\n\n list<point> _ptList;\n};\n//--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n srand( GetTickCount() );\n rndCircle c;\n c.draw();\n system( \"pause\" );\n return 0;\n}\n//--------------------------------------------------------------------------------------------------\n", "language": "C++" }, { "code": "using System;\nusing System.Diagnostics;\nusing System.Drawing;\n\nnamespace RosettaConstrainedRandomCircle\n{\n class Program\n {\n static void Main(string[] args)\n {\n var points = new Point[404];\n int i = 0;\n for (int y = -15; y <= 15; y++)\n for (int x = -15; x <= 15 && i < 404; x++)\n {\n var c = Math.Sqrt(x * x + y * y);\n if (10 <= c && c <= 15)\n {\n points[i++] = new Point(x, y);\n }\n }\n\n var bm = new Bitmap(600, 600);\n var g = Graphics.FromImage(bm);\n var brush = new SolidBrush(Color.Magenta);\n\n var r = new System.Random();\n for (int count = 0; count < 100; count++)\n {\n var p = points[r.Next(404)];\n g.FillEllipse(brush, new Rectangle(290 + 19 * p.X, 290 + 19 * p.Y, 10, 10));\n }\n const string filename = \"Constrained Random Circle.png\";\n bm.Save(filename);\n Process.Start(filename);\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(ns rosettacode.circle-random-points\n (:import [java.awt Color Graphics Dimension]\n [javax.swing JFrame JPanel]))\n\n(let [points (->> (for [x (range -15 16), y (range -15 16)\n\t\t\t:when (<= 10 (Math/hypot x y) 15)]\n\t\t [(+ x 15) (+ y 15)])\n\t\t shuffle\n\t\t (take 100))]\n (doto (JFrame.)\n (.add (doto (proxy [JPanel] []\n\t\t (paint [^Graphics g]\n (doseq [[x y] points]\n (.fillRect g (* 10 x) (* 10 y) 10 10))))\n\t (.setPreferredSize (Dimension. 310 310))))\n (.setResizable false)\n (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)\n .pack\n .show))\n", "language": "Clojure" }, { "code": " identification division.\n program-id. circle.\n environment division.\n input-output section.\n file-control.\n select plot-file assign \"circle.txt\".\n data division.\n file section.\n fd plot-file report plot.\n working-storage section.\n 1 binary.\n 2 seed pic 9(18).\n 2 x pic s9(4).\n 2 y pic s9(4).\n 2 i pic 9(4).\n 2 dot-count pic 9(4) value 0.\n 2 dot-count-save pic 9(4) value 0.\n 2 temp-points.\n 3 pic s9(4) occurs 2.\n 2 xy-table.\n 3 point-pair occurs 0 to 404 depending dot-count.\n 4 x-point pic s9(4).\n 4 y-point pic s9(4).\n 1 plot-table value all \"0\".\n 2 occurs 31.\n 3 dot pic 9 occurs 31.\n 1 cur-date-time.\n 2 yyyymmdd pic 9(8).\n 2 hh pic 9(2).\n 2 mm pic 9(2).\n 2 ss pic 9(2).\n 1 plot-work.\n 2 plot-item pic xb occurs 31.\n report section.\n rd plot.\n 1 plot-line type de.\n 2 line plus 1.\n 3 column is 1 source is plot-work pic x(62).\n procedure division.\n begin.\n perform compute-seed\n perform find-all-valid-points\n perform shuffle-point-pairs\n perform select-100-dots\n perform print-dots\n stop run\n .\n\n find-all-valid-points.\n perform varying x from -15 by 1 until x > +15\n perform varying y from -15 by 1 until y > +15\n if (function sqrt (x ** 2 + y ** 2))\n >= 10 and <= 15\n then\n move 1 to dot (x + 16 y + 16)\n add 1 to dot-count\n compute x-point (dot-count) = x + 16\n compute y-point (dot-count) = y + 16\n end-if\n end-perform\n end-perform\n display \"Total points: \" dot-count\n .\n\n shuffle-point-pairs.\n move dot-count to dot-count-save\n compute i = function random (seed) * dot-count + 1\n perform varying dot-count from dot-count by -1\n until dot-count < 2\n move point-pair (i) to temp-points\n move point-pair (dot-count) to point-pair (i)\n move temp-points to point-pair (dot-count)\n compute i = function random * dot-count + 1\n end-perform\n move dot-count-save to dot-count\n .\n\n select-100-dots.\n perform varying i from 1 by 1\n until i > 100\n compute x = x-point (i)\n compute y = y-point (i)\n move 2 to dot (x y)\n end-perform\n .\n\n print-dots.\n open output plot-file\n initiate plot\n perform varying y from 1 by 1 until y > 31\n move spaces to plot-work\n perform varying x from 1 by 1 until x > 31\n if dot (x y) = 2\n move \"o\" to plot-item (x)\n end-if\n end-perform\n generate plot-line\n end-perform\n terminate plot\n close plot-file\n .\n\n compute-seed.\n unstring function current-date into\n yyyymmdd hh mm ss\n compute seed =\n (function integer-of-date (yyyymmdd) * 86400)\n compute seed = seed\n + (hh * 3600) + (mm * 60) + ss\n compute seed = function mod (seed 32768)\n .\n\n end program circle.\n", "language": "COBOL" }, { "code": "NUM_POINTS = 100\nMIN_R = 10\nMAX_R = 15\n\nrandom_circle_points = ->\n rand_point = ->\n Math.floor (Math.random() * (MAX_R * 2 + 1) - MAX_R)\n\n points = {}\n cnt = 0\n while cnt < 100\n x = rand_point()\n y = rand_point()\n continue unless MIN_R * MIN_R <= x*x + y*y <= MAX_R * MAX_R\n points[\"#{x},#{y}\"] = true\n cnt += 1\n points\n\nplot = (points) ->\n range = [-1 * MAX_R .. MAX_R]\n for y in range\n s = ''\n for x in range\n s += if points[\"#{x},#{y}\"] then '*' else ' '\n console.log s\n\nplot random_circle_points()\n", "language": "CoffeeScript" }, { "code": "> coffee foo.coffee\n\n ** *\n * ** * *\n * * * *\n * ** *\n * * * *\n * *\n *\n * *\n ***\n ** **** *\n * *\n * *\n **\n *\n\n * **\n * * *\n **\n * * **\n * *\n * *\n * *\n * *\n ***\n *** * * * * *\n *** *\n * * * * *\n * * *\n", "language": "CoffeeScript" }, { "code": "(flet ((good-p (x y) (<= 100 (+ (* x x) (* y y)) 255)))\n (loop with x with y with cnt = 0\n\twith scr = (loop repeat 31 collect (loop repeat 31 collect \" \"))\n\twhile (< cnt 100)\n\tdo (when (good-p (- (setf x (random 31)) 15)\n\t\t\t (- (setf y (random 31)) 15))\n\t (setf (elt (elt scr y) x) \"@ \")\n\t (incf cnt))\n\tfinally (mapc #'(lambda (row) (format t \"~{~a~^~}~%\" row)) scr)))\n", "language": "Common-Lisp" }, { "code": "import std.stdio, std.random, std.math, std.complex;\n\nvoid main() {\n char[31][31] table = ' ';\n\n foreach (immutable _; 0 .. 100) {\n int x, y;\n do {\n x = uniform(-15, 16);\n y = uniform(-15, 16);\n } while(abs(12.5 - complex(x, y).abs) > 2.5);\n table[x + 15][y + 15] = '*';\n }\n\n writefln(\"%-(%s\\n%)\", table);\n}\n", "language": "D" }, { "code": "unit Main;\n\ninterface\n\nuses\n Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls;\n\ntype\n TForm1 = class(TForm)\n procedure FormCreate(Sender: TObject);\n procedure FormPaint(Sender: TObject);\n end;\n\nvar\n Form1: TForm1;\n Points: TArray<TPoint>;\n\nimplementation\n\n{$R *.dfm}\n\nprocedure TForm1.FormCreate(Sender: TObject);\nbegin\n ClientHeight := 600;\n ClientWidth := 600;\nend;\n\nprocedure TForm1.FormPaint(Sender: TObject);\nvar\n i: integer;\n p: TPoint;\n index: integer;\nbegin\n SetLength(Points, 404);\n i := 0;\n for var y := -15 to 15 do\n for var x := -15 to 15 do\n begin\n if i >= 404 then\n Break;\n var c := Sqrt(x * x + y * y);\n if (10 <= c) and (c <= 15) then\n begin\n inc(i);\n points[i] := TPoint.Create(x, y);\n end;\n end;\n var bm := TBitmap.create;\n bm.SetSize(600, 600);\n with bm.Canvas do\n begin\n Pen.Color := clRed;\n Brush.Color := clRed;\n Brush.Style := bsSolid;\n Randomize;\n\n for var count := 0 to 99 do\n begin\n repeat\n index := Random(404);\n p := points[index];\n until (not p.IsZero);\n points[index] := TPoint.Zero;\n\n var cx := 290 + 19 * p.X;\n var cy := 290 + 19 * p.Y;\n Ellipse(cx - 5, cy - 5, cx + 5, cy + 5);\n end;\n end;\n Canvas.Draw(0, 0, bm);\n bm.Free;\nend;\nend.\n", "language": "Delphi" }, { "code": "while cnt < 100\n x = randint 31 - 16\n y = randint 31 - 16\n r = sqrt (x * x + y * y)\n if 10 <= r and r <= 15\n cnt += 1\n move 50 + x * 2 50 + y * 2\n circle 1\n .\n.\n", "language": "EasyLang" }, { "code": "(lib 'math)\n(lib 'plot)\n\n(define (points (n 100) (radius 10) (rmin 10) (rmax 15) (x) (y))\n\t(plot-clear)\n\t(plot-x-minmax (- rmax))\n\t(plot-y-minmax( - rmax))\n\t\n\t(for [(i n)]\n\t(set! x (round (* (random -1) rmax)))\n\t(set! y (round (* (random -1) rmax)))\n\t#:when (in-interval? (pythagore x y) rmin rmax)\n\t;; add a little bit of randomness : dots color and radius\n\t(plot-fill-color (hsv->rgb (random) 0.9 0.9))\n\t(plot-circle x y (random radius)))\n\t(plot-edit))\n", "language": "EchoLisp" }, { "code": "defmodule Random do\n defp generate_point(0, _, _, set), do: set\n defp generate_point(n, f, condition, set) do\n point = {x,y} = {f.(), f.()}\n if x*x + y*y in condition and not point in set,\n do: generate_point(n-1, f, condition, MapSet.put(set, point)),\n else: generate_point(n, f, condition, set)\n end\n\n def circle do\n f = fn -> :rand.uniform(31) - 16 end\n points = generate_point(100, f, 10*10..15*15, MapSet.new)\n range = -15..15\n for x <- range do\n for y <- range do\n IO.write if {x,y} in points, do: \"x\", else: \" \"\n end\n IO.puts \"\"\n end\n end\nend\n\nRandom.circle\n", "language": "Elixir" }, { "code": "defmodule Constrain do\n def circle do\n range = -15..15\n r2 = 10*10..15*15\n all_points = for x <- range, y <- range, x*x+y*y in r2, do: {x,y}\n IO.puts \"Precalculate: #{length(all_points)}\"\n points = Enum.take_random(all_points, 100)\n Enum.each(range, fn x ->\n IO.puts Enum.map(range, fn y -> if {x,y} in points, do: \"o \", else: \" \" end)\n end)\n end\nend\n\nConstrain.circle\n", "language": "Elixir" }, { "code": "include std/console.e\n\nsequence validpoints = {}\nsequence discardedpoints = {}\nsequence rand100points = {}\natom coordresult\ninteger randindex\n\n--scan for all possible values. store discarded ones in another sequence, for extra reference.\nfor y = -15 to 15 do\n for x = -15 to 15 do\n\n coordresult = sqrt( x * x + y * y )\n\n if coordresult >= 10 and coordresult <= 15 then --if it would fall in the ring area\n validpoints &= {{x, y, coordresult}} --concatenate (add to the end) the coordinate pair x, y and the\n -- result into a subsequence of sequence validpoints\n else\n discardedpoints &= {{x, y, coordresult}} --else put it in the discarded sequence\n end if\n\n end for\nend for\n\nfor i = 1 to 100 label \"oneofhundred\" do --make 100 random coordinate pairs\n randindex = rand(length(validpoints) ) --random value from 1 to the number of 3 value subsequences in validpoints (the data)\n\n if length(rand100points) = 0 then --if rand100points sequence is empty, add the first subsequence to it.\n rand100points &= {validpoints[randindex]}\n\n else --if it isn't empty, then..\n for j = 1 to length(rand100points) do --loop through each \"data chunk\" in rand100points\n\n if equal(validpoints[randindex], rand100points[j]) = 1 then --if any are the same as the randomly chosen chunk in\n retry \"oneofhundred\" -- validpoints, then retry from one line below the \"oneofhundred\" loop without incrementing i.\n end if --the continue keyword would increment i instead.\n\n end for\n\n rand100points &= {validpoints[randindex]} --length of rand100points isnt 0 and no data chunks match ones that the program\n --already picked before, so add this subsequence chunk to rand100points.\n end if\n\nend for\n\nfor i = 1 to 32 do --32 lines\n printf(1,\"\\n\")\n for j = 1 to 32 label \"xscan\" do --32 characters on each line\n\n for k = 1 to length(rand100points) do --for every subsequence in this\n if rand100points[k][1]+16 = j and rand100points[k][2]+16 = i then --if the x and y coordinates in the picked points\n printf(1, 178) --(adjusted to minimum of 1,1) are at the same place as in the console output grid\n continue \"xscan\" --print a funny character and continue to the next \"xscan\"\n end if\n end for\n\n printf(1, 176) --if no picked points were there, print another funny character to represent a blank space\n\n end for\nend for\n\nprintf(1, \"\\nNumber of valid coordinate pairs %d :\", length(validpoints) )\nprintf(1, \"\\nNumber of discarded coordinate pairs : %d\", length(discardedpoints) )\nprintf(1, \"\\nNumber of randomly picked coordinate pairs : %d\\n\", length(rand100points) )\nany_key()\n", "language": "Euphoria" }, { "code": "for i = 1 to length(validpoints) do --simple each pixel output to screen surface\n dummy=pixelColor(surface,validpoints[i][1]+18,validpoints[i][2]+18,#AA0202FF) --i is index number of each subsequence 'chunk'.\n --index 1 is x, index 2 is y, inside that chunk.\nend for\n\nfor i = 1 to length(discardedpoints) do\n dummy=pixelColor(surface,discardedpoints[i][1]+18,discardedpoints[i][2]+52,#0202AAFF)\nend for\n\nfor i = 1 to length(rand100points) do\n dummy=pixelColor(surface,rand100points[i][1]+55,rand100points[i][2]+52,#02AA02FF)\nend for\n\ndummy=boxColor(surface,0,71,395,111,#232323FF) --background box\ndummy=stringColor(surface,0,73,sprintf(\"Number of valid coordinate pairs %d :\", length(validpoints) ),#AA0202FF)\n\ndummy=stringColor(surface,0,83,sprintf(\"Number of discarded coordinate pairs : %d\", length(discardedpoints) ),#0202AAFF)\n\ndummy=stringColor(surface,0,93,sprintf(\"Number of randomly picked coordinate pairs : %d\", length(rand100points) ),#02AA02FF)\n", "language": "Euphoria" }, { "code": "module CirclePoints =\n let main args =\n let rnd = new System.Random()\n let rand size = rnd.Next(size) - size/2\n let size = 30\n let gen n =\n let rec f (x,y) =\n let t = (int (sqrt (float (x*x + y*y)) ))\n if 10 <= t && t <= 15 then (x,y) else f (rand size, rand size)\n f (rand size, rand size)\n let plot = Array.init 100 (fun n -> gen n)\n for row in 0 .. size-1 do\n let chars = Array.create (size+1) ' '\n Array.choose (fun (x,y) -> if y = (row-size/2) then Some(x) else None) plot\n |> Array.iter (fun x -> chars.[x+size/2] <- 'o')\n printfn \"%s\" (new string(chars))\n 0\n\n#if INTERACTIVE\nCirclePoints.main fsi.CommandLineArgs\n#else\n[<EntryPoint>]\nlet main args = CirclePoints.main args\n#endif\n", "language": "F-Sharp" }, { "code": "USING: io kernel math.matrices math.order math.ranges\nmath.statistics math.vectors random sequences strings ;\n\nCHAR: X -15 15 [a,b] dup cartesian-product concat\n[ sum-of-squares 100 225 between? ] filter 100 sample\n[ 15 v+n ] map 31 31 32 <matrix> [ matrix-set-nths ] keep\n[ >string print ] each\n", "language": "Factor" }, { "code": "// Generate points in [min,max]^2 with constraint\nfunction random_point (min, max, constraint)\n [x, y] = [random(min, max), random(min, max)]\n return constraint(x, y) ? [x, y] : random_point(min, max, constraint)\nend\n\n// Generate point list\nin_circle = { x, y => 10**2 <= x**2 + y**2 and x**2 + y**2 <= 15**2 }\npoints = [].comp([0:100], {__ => random_point(-15, 15, in_circle)})\n\n// Show points\nfor i in [-15:16]\n for j in [-15:16]\n >> [i, j] in points ? \"x\" : \" \"\n end\n >\nend\n", "language": "Falcon" }, { "code": "#! /usr/bin/gforth\n\\ Constrained random points on a circle\n\nrequire random.fs\n\n\\ initialize the random number generator with a time-dependent seed\nutime drop seed !\n\n\\ generates a random integer in [-15,15]\n: random-coord ( -- n )\n 31 random 15 -\n;\n\n\\ generates a random point on the constrained circle\n: random-point ( -- x y )\n 0 0\n BEGIN\n 2drop\n random-coord random-coord\n 2dup dup * swap dup * +\n dup 100 >= swap 225 <= and\n UNTIL\n;\n\n31 31 * CONSTANT SIZE\nCREATE GRID SIZE cells allot GRID SIZE cells erase\n\n\\ get the address of point (x,y)\n: point-addr ( x y -- addr )\n 15 + 31 * + 15 + cells GRID +\n;\n\n\\ generate 100 random points and mark them in the grid\n: gen-points ( -- )\n 100 0 ?DO\n true random-point point-addr !\n LOOP\n;\n\n\\ prints the grid\n: print-grid ( -- )\n 16 -15 ?DO\n 16 -15 ?DO\n i j point-addr @\n IF\n 42\n ELSE\n 32\n THEN\n emit\n LOOP\n cr\n LOOP\n;\n\ngen-points print-grid\nbye\n", "language": "Forth" }, { "code": "program Constrained_Points\n implicit none\n\n integer, parameter :: samples = 100\n integer :: i, j, n, randpoint\n real :: r\n\n type points\n integer :: x, y\n end type\n\n type(points) :: set(500), temp\n\n! Create set of valid points\n n = 0\n do i = -15, 15\n do j = -15, 15\n if(sqrt(real(i*i + j*j)) >= 10.0 .and. sqrt(real(i*i + j*j)) <= 15.0) then\n n = n + 1\n set(n)%x = i\n set(n)%y = j\n end if\n end do\n end do\n\n! create 100 random points\n! Choose a random number between 1 and n inclusive and swap point at this index with point at index 1\n! Choose a random number between 2 and n inclusive and swap point at this index with point at index 2\n! Continue in this fashion until 100 points have been selected\n call random_seed\n do i = 1, samples\n call random_number(r)\n randpoint = r * (n + 1 - i) + i\n temp = set(i)\n set(i) = set(randpoint)\n set(randpoint) = temp\n end do\n\n! In order to facilitate printing sort random points into ascending order\n! sort x in ascending order\n do i = 2, samples\n j = i - 1\n temp = set(i)\n do while (j>=1 .and. set(j)%x > temp%x)\n set(j+1) = set(j)\n j = j - 1\n end do\n set(j+1) = temp\n end do\n\n! sort y in ascending order for same x\n do i = 2, samples\n j = i - 1\n temp = set(i)\n do while (j>=1 .and. set(j)%x == temp%x .and. set(j)%y > temp%y)\n set(j+1) = set(j)\n j = j - 1\n end do\n set(j+1) = temp\n end do\n\n! print circle\n write(*,\"(a,a)\", advance=\"no\") repeat(\" \", set(1)%y+15), \"*\"\n do i = 2, samples\n if(set(i)%x == set(i-1)%x) then\n write(*,\"(a,a)\", advance=\"no\") repeat(\" \", set(i)%y - set(i-1)%y-1), \"*\"\n else\n n = set(i)%x - set(i-1)%x\n do j = 1, n\n write(*,*)\n end do\n write(*,\"(a,a)\", advance=\"no\") repeat(\" \", set(i)%y+15), \"*\"\n end if\n end do\n\nend program\n", "language": "Fortran" }, { "code": "'Free Basic version .9\n\n#define Intrange(f,l) int(Rnd*(((l)+1)-(f))+(f))\n\nType pair\n As Integer x,y\nEnd Type\n\nOperator =(a As pair,b As pair) As Integer\nReturn a.x=b.x And a.y=b.y\nEnd Operator\n\nFunction NotInArray(a() As pair,n As pair) As Integer\n For z As Integer=Lbound(a) To Ubound(a)\n If a(z)=n Then Return 0\n Next z\n Return -1\nEnd Function\n\nRedim As pair pts(0)\nDim As Integer x,y,counter\nDo\n counter=counter+1\n x=IntRange(-20,20)\n y=IntRange(-20,20)\n var root=Sqr(x*x+y*y)\n If 10<= root And root<=15 Then\n If NotInArray(pts(),Type<pair>(x,y)) Then\n Redim Preserve pts(1 To Ubound(pts)+1)\n pts(Ubound(pts))=Type<pair>(x,y)\n End If\n End If\nLoop Until counter=100000\n\n'============== Plot to Console ======================\n\ndim as integer yres=hiword(width)\ndim as integer xres=loword(width)\n\n#define map(a,b,x,c,d) ((d)-(c))*((x)-(a))/((b)-(a))+(c)\n#define _X(num) int( map(0,xres,(num),0,loword(width)))\n#define _Y(num) int( map(0,yres,(num),0,hiword(width)))\n\ncounter=0\nFor n As Integer=Lbound(pts) To Ubound(pts)\n counter=counter+1\n if counter <=100 then\n var xpos=map(-20,20,pts(n).x,0,xres)\n var ypos=map(-20,20,pts(n).y,0,yres)\n locate _Y(ypos),_X(xpos)\n print \"*\"\n end if\nNext n\n\nprint\nlocate 1,1\nPrint \"Total number of points \"; counter\nprint \"Total number plotted \";100\nprint \"done\"\nSleep\n", "language": "FreeBASIC" }, { "code": "g = new graphics\n\ncount = 0\ndo\n{\n x = random[-15,15]\n y = random[-15,15]\n r = sqrt[x^2 + y^2]\n if 10 <= r and r <= 15\n {\n count = count + 1\n g.fillEllipseCenter[x,y,.3, .3]\n }\n} while count < 100\n\ng.show[]\n", "language": "Frink" }, { "code": "## Ring of random points 2/18/17 aev\nreset\nfn=\"RingRandPntsGnu\";\nttl=\"Ring of random points\"\nofn=fn.\".png\"; lim=1000;\nrandgp(top) = floor(rand(0)*top)\nset terminal png font arial 12 size 640,640\nset output ofn\nset title ttl font \"Arial:Bold,12\"\nunset key;\nset size square\nset parametric\nset xrange [-20:20]; set yrange [-20:20];\nset style line 1 lt rgb \"red\"\n$rring << EOD\nEOD\nset print $rring append\ndo for [i=1:lim] {\n x=randgp(30); y=randgp(30);\n r=sqrt(x**2+y**2);\n if (r>=10&&r<=15) \\\n {print x,\" \",y; print -x,\" \",-y;print x,\" \",-y; print -x,\" \",y;}\n}\nplot [0:2*pi] sin(t)*10,cos(t)*10, sin(t)*15,cos(t)*15 ls 1,\\\n$rring using 1:2 with points pt 7 ps 0.5 lc \"black\"\nset output\nunset print\n", "language": "Gnuplot" }, { "code": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\nconst (\n nPts = 100\n rMin = 10\n rMax = 15\n)\n\nfunc main() {\n rand.Seed(time.Now().Unix())\n span := rMax + 1 + rMax\n rows := make([][]byte, span)\n for r := range rows {\n rows[r] = bytes.Repeat([]byte{' '}, span*2)\n }\n u := 0 // count unique points\n min2 := rMin * rMin\n max2 := rMax * rMax\n for n := 0; n < nPts; {\n x := rand.Intn(span) - rMax\n y := rand.Intn(span) - rMax\n // x, y is the generated coordinate pair\n rs := x*x + y*y\n if rs < min2 || rs > max2 {\n continue\n }\n n++ // count pair as meeting condition\n r := y + rMax\n c := (x + rMax) * 2\n if rows[r][c] == ' ' {\n rows[r][c] = '*'\n u++\n }\n }\n for _, row := range rows {\n fmt.Println(string(row))\n }\n fmt.Println(u, \"unique points\")\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\nconst (\n nPts = 100\n rMin = 10\n rMax = 15\n)\n\nfunc main() {\n rand.Seed(time.Now().Unix())\n var poss []struct{ x, y int }\n min2 := rMin * rMin\n max2 := rMax * rMax\n for y := -rMax; y <= rMax; y++ {\n for x := -rMax; x <= rMax; x++ {\n if r2 := x*x + y*y; r2 >= min2 && r2 <= max2 {\n poss = append(poss, struct{ x, y int }{x, y})\n }\n }\n }\n fmt.Println(len(poss), \"possible points\")\n span := rMax + 1 + rMax\n rows := make([][]byte, span)\n for r := range rows {\n rows[r] = bytes.Repeat([]byte{' '}, span*2)\n }\n u := 0\n for n := 0; n < nPts; n++ {\n i := rand.Intn(len(poss))\n r := poss[i].y + rMax\n c := (poss[i].x + rMax) * 2\n if rows[r][c] == ' ' {\n rows[r][c] = '*'\n u++\n }\n }\n for _, row := range rows {\n fmt.Println(string(row))\n }\n fmt.Println(u, \"unique points\")\n}\n", "language": "Go" }, { "code": "import Data.List\nimport Control.Monad\nimport Control.Arrow\nimport Rosetta.Knuthshuffle\n\ntask = do\n let blanco = replicate (31*31) \" \"\n cs = sequence [[-15,-14..15],[-15,-14..15]] :: [[Int]]\n constraint = uncurry(&&).((<= 15*15) &&& (10*10 <=)). sum. map (join (*))\n-- select and randomize all circle points\n pts <- knuthShuffle $ filter constraint cs\n-- 'paint' first 100 randomized circle points on canvas\n let canvas = foldl (\\cs [x,y] -> replaceAt (31*(x+15)+y+15) \"/ \" cs ) blanco (take 100 pts)\n-- show canvas\n mapM_ (putStrLn.concat). takeWhile(not.null). unfoldr (Just . splitAt 31) $ canvas\n", "language": "Haskell" }, { "code": "(import\n math [sqrt]\n random [choice]\n matplotlib.pyplot :as plt)\n\n(setv possible-points\n (lfor\n x (range -15 16)\n y (range -15 16)\n :if (<= 10 (sqrt (+ (** x 2) (** y 2))) 15)\n\t [x y]))\n\n(setv [xs ys] (zip #* (map (fn [_] (choice possible-points)) (range 100))))\n ; We can't use random.sample because that samples without replacement.\n ; #* is also known as unpack-iterable\n(plt.plot xs ys \"bo\")\n(plt.show)\n", "language": "Hy" }, { "code": "link graphics\n\nprocedure main(A) # points, inside r, outside r in pixels - default to task values\n\nif \\A[1] == \"help\" then stop(\"Usage: plot #points inside-radius outside-radius\")\npoints := \\A[1] | 100\noutside := \\A[2] | 15\ninside := \\A[3] | 10\nif inside > outside then inside :=: outside\n\nwsize := integer(2.2*outside)\nwsize <:= 150\ncenter := wsize/2\n\nWOpen(\"size=\"||wsize||\",\"||wsize,\"bg=black\",\"fg=white\") | stop(\"Unable to open window\")\n\nuntil(points -:= 1) <= 0 do {\n x := ?(2*outside)-outside # random x\n y := ?(2*outside)-outside # and y\n if (inside <= integer(sqrt(x^2+y^2)) ) <= outside then\n DrawPoint(x + center,y + center)\n }\nWDone()\n\nend\n", "language": "Icon" }, { "code": "gen=: ({~ 100?#)bind((#~ 1=99 225 I.+/\"1@:*:),/,\"0/~i:15)\n", "language": "J" }, { "code": " '*' (<\"1]15+gen '')} 31 31$' '\n\n *\n *\n * * * * * *\n * * * * *\n * ***\n ** * * **\n * **\n * **\n * * * *\n * * **\n * ** **\n ** * ***\n * ** * *\n ** *\n * ** *\n ** *\n * ** *\n * *\n * *\n * *\n ** *\n * **\n *\n * * * *\n * ** * * *\n * *\n **\n * * *\n ** *\n", "language": "J" }, { "code": "import java.util.Random;\n\npublic class FuzzyCircle {\n\tstatic final Random rnd = new Random();\n\tpublic static void main(String[] args){\n\t\tchar[][] field = new char[31][31];\n\t\tfor(int i = 0; i < field.length; i++){\n\t\t\tfor(int j = 0; j < field[i].length; j++){\n\t\t\t\tfield[i][j] = ' ';\n\t\t\t}\n\t\t}\n\t\tint pointsInDisc = 0;\n\t\twhile(pointsInDisc < 100){\n\t\t\tint x = rnd.nextInt(31) - 15;\n\t\t\tint y = rnd.nextInt(31) - 15;\n\t\t\tdouble dist = Math.hypot(x, y);\n\t\t\tif(dist >= 10 && dist <= 15 && field[x + 15][y + 15] == ' '){\n\t\t\t\tfield[x + 15][y + 15] = 'X';\n\t\t\t\tpointsInDisc++;\n\t\t\t}\n\t\t}\n\t\tfor(char[] row:field){\n\t\t\tfor(char space:row){\n\t\t\t\tSystem.out.print(space);\n\t\t\t}\n\t\t\tSystem.out.println();\n\t\t}\n\t}\n}\n", "language": "Java" }, { "code": "<html><head><title>Circle</title></head>\n<body>\n<canvas id=\"cv\" width=\"320\" height=\"320\"></canvas>\n<script type=\"application/javascript\">\n\nvar cv = document.getElementById('cv');\nvar ctx = cv.getContext('2d');\n\nvar w = cv.width;\nvar h = cv.height;\n\n//draw circles\nctx.fillStyle = 'rgba(0, 255, 200, .3)';\nctx.strokeStyle = 'rgba(0,0,0,.1)';\nctx.beginPath();\nctx.arc(w/2, h/2, 150, 0, Math.PI*2, true);\nctx.arc(w/2, h/2, 100, 0, Math.PI*2, false);\nctx.closePath();\nctx.fill();\n\n// draw grids\nctx.beginPath();\nfor (var i = 10; i < w; i += 10) {\n\tctx.moveTo(i, 0);\n\tctx.lineTo(i, h);\n\tctx.moveTo(0, i);\n\tctx.lineTo(w, i);\n}\nctx.closePath();\nctx.stroke();\n\n//draw points\nctx.fillStyle = 'navy';\nvar pts = 0;\nwhile (pts < 100) {\n\tvar x = Math.floor(Math.random() * 31) - 15;\n\tvar y = Math.floor(Math.random() * 31) - 15;\n\tvar r = x * x + y * y;\n\tif (r < 100 || r > 225) continue;\n\tx = x * 10 + w/2;\n\ty = y * 10 + h/2;\n\tctx.fillRect(x - 2, y - 2, 4, 4);\n\tpts++;\n}\n\n</script></body></html>\n", "language": "JavaScript" }, { "code": "#!/bin/bash\n\n< /dev/random tr -cd '0-9' | fold -w 1 | jq -Mcnr '\n\n# Output: a PRN in range(0;$n) where $n is .\ndef prn:\n if . == 1 then 0\n else . as $n\n | (($n-1)|tostring|length) as $w\n | [limit($w; inputs)] | join(\"\") | tonumber\n | if . < $n then . else ($n | prn) end\n end;\n\ndef ss: map(.*.) | add;\n\n# Input: [x,y]\n# Emit . iff ss lies within the given bounds\ndef annulus($min; $max) : ss as $sum | select($min <= $sum and $sum <= $max);\n\nlimit(100;\n repeat([((30 | prn) - 15), ((30 | prn) - 15)]\n | select( annulus(100; 225)) ))\n| \"\\(.[0]) \\(.[1])\"\n' > rc-annulus.dat\n", "language": "Jq" }, { "code": "reset\nset terminal pngcairo\nset output 'rc-annulus.png'\nset xrange [-20:20]\nset yrange [-20:20]\nplot \"rc-annulus.dat\" with points pt 1\n", "language": "Jq" }, { "code": "function printcircle(lo::Integer, hi::Integer, ndots::Integer; pad::Integer = 2)\n canvas = falses(2hi + 1, 2hi + 1)\n i = 0\n while i < ndots\n x, y = rand(-hi:hi, 2)\n if lo ^ 2 - 1 < x ^ 2 + y ^ 2 < hi ^ 2 + 1\n canvas[x + hi + 1, y + hi + 1] = true\n i += 1\n end\n end\n # print\n for i in 1:(2hi + 1)\n row = map(j -> j ? \"\\u25cf \" : \" \", canvas[i, :])\n println(\" \" ^ pad, join(row))\n end\n return canvas\nend\n\nprintcircle(10, 15, 100)\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nfun main(args: Array<String>) {\n val r = java.util.Random()\n val points = Array(31) { CharArray(31) { ' ' } }\n var count = 0\n while (count < 100) {\n val x = r.nextInt(31) - 15\n val y = r.nextInt(31) - 15\n val h = x * x + y * y\n if (h in 100..225) {\n points[x + 15][y + 15] = 'o'\n count++\n }\n }\n for (i in 0..30) println(points[i].joinToString(\"\"))\n}\n", "language": "Kotlin" }, { "code": "{def circ\n {lambda {:cx :cy :r}\n {div {@ style=\"position:absolute;\n top: {- :cy :r}px; left: {- :cx :r}px;\n width: {* 2 :r}px; height: {* 2 :r}px;\n border: 1px solid #000; border-radius: :rpx;\"}} }}\n-> circ\n\n{def fuzzy_circle\n {lambda {:cx :cy :rmin :rmax :n}\n {circ :cx :cy :rmax}\n {circ :cx :cy :rmin}\n {S.map {{lambda {:cx :cy :rmin :rmax :i}\n {let { {:cx :cx} {:cy :cy}\n {:rmin :rmin} {:rmax :rmax}\n {:x {- {round {* {random} {* 2 :rmax}}} :rmax}}\n {:y {- {round {* {random} {* 2 :rmax}}} :rmax}}\n } {let { {:x {+ :cx :x }}\n {:y {+ :cy :y }}\n {:rr {+ {* :x :x} {* :y :y}}}\n {:r2min {* :rmin :rmin}}\n {:r2max {* :rmax :rmax}}\n } {if {or {< :rr :r2min} {> :rr :r2max}}\n then else {circ :x :y 2}}\n }}} :cx :cy :rmin :rmax}\n {S.serie 1 :n}} }}\n-> fuzzy_circle\n\n{fuzzy_circle 200 700 80 120 1000}\n-> plots 1000 dots between the circles r=80 and r=120 centered at [200,700]\n directly in the wiki page (out of any canvas or svg contexts) as it\n can be seen in http://lambdaway.free.fr/lambdawalks/?view=fuzzy_circle\n", "language": "Lambdatalk" }, { "code": "' RC Constrained Random Points on a Circle\n\nnomainwin\n\nWindowWidth =400\nWindowHeight =430\n\nopen \"Constrained Random Points on a Circle\" for graphics_nsb as #w\n\n#w \"trapclose [quit]\"\n#w \"down ; size 7 ; color red ; fill black\"\n\nfor i =1 to 1000\n do\n x =int( 30 *rnd( 1)) -15\n y =int( 30 *rnd( 1)) -15\n loop until IsInRange( x, y) =1\n #w \"set \"; 200 +10 *x; \" \"; 200 - 10 *y\nnext\n\nwait\n\nfunction IsInRange( x, y)\n z =sqr( x*x +y*y)\n if 10 <=z and z <=15 then IsInRange =1 else IsInRange =0\nend function\n\n[quit]\nclose #w\nend\n", "language": "Liberty-BASIC" }, { "code": "10 MODE 1:RANDOMIZE TIME\n20 FOR J=1 TO 100\n30 X=INT(RND*30-15)\n40 Y=INT(RND*30-15)\n50 D=X*X+Y*Y\n60 IF D<100 OR D>225 THEN GOTO 40\n70 PLOT 320+10*X,200+10*Y:LOCATE 1,1:PRINT J\n80 NEXT\n90 CALL &BB06 ' wait for key press\n", "language": "Locomotive-Basic" }, { "code": "t, n = {}, 0\nfor y=1,31 do t[y]={} for x=1,31 do t[y][x]=\" \" end end\nrepeat\n x, y = math.random(-15,15), math.random(-15,15)\n rsq = x*x + y*y\n if rsq>=100 and rsq<=225 and t[y+16][x+16]==\" \" then\n t[y+16][x+16], n = \"██\", n+1\n end\nuntil n==100\nfor y=1,31 do print(table.concat(t[y])) end\n", "language": "Lua" }, { "code": " a := table():\n i := 1:\n while i < 100 do\n ba := (rand(-15 .. 15))():\n bb := (rand(-15 .. 15))():\n b := evalf(sqrt(ba^2+bb^2)):\n if b <= 15 and b >= 10\n then a[i] := [ba, bb]:\n i := i+1:\n end if:\n end do:\n plots:-pointplot(convert(a,list));\n", "language": "Maple" }, { "code": "sample = Take[Cases[RandomInteger[{-15, 15}, {500, 2}], {x_, y_} /; 10 <= Sqrt[x^2 + y^2] <= 15], 100];\n\nShow[{RegionPlot[10 <= Sqrt[x^2 + y^2] <= 15, {x, -16, 16}, {y, -16, 16}, Axes -> True], ListPlot[sample]}]\n", "language": "Mathematica" }, { "code": "function [xCoordinates,yCoordinates] = randomDisc(numPoints)\n\n xCoordinates = [];\n yCoordinates = [];\n\n %Helper function that samples a random integer from the uniform\n %distribution between -15 and 15.\n function nums = randInt(n)\n nums = round((31*rand(n,1))-15.5);\n end\n\n n = numPoints;\n\n while n > 0\n\n x = randInt(n);\n y = randInt(n);\n\n norms = sqrt((x.^2) + (y.^2));\n inBounds = find((10 <= norms) & (norms <= 15));\n\n xCoordinates = [xCoordinates; x(inBounds)];\n yCoordinates = [yCoordinates; y(inBounds)];\n\n n = numPoints - numel(xCoordinates);\n end\n\n xCoordinates(numPoints+1:end) = [];\n yCoordinates(numPoints+1:end) = [];\n\nend\n", "language": "MATLAB" }, { "code": ">> [x,y] = randomDisc(100);\n>> plot(x,y,'.')\n", "language": "MATLAB" }, { "code": "randomDisc(numPoints):= block([p: []],\n local(goodp, random_int),\n goodp(x, y):=block([r: sqrt(x^2+y^2)],\n r>=10 and r<=15\n ),\n random_int():= block([m: 15], m - random(2*(m+1)-1)),\n while length(p)<numPoints do block (\n [x: random_int(), y : random_int()],\n if goodp(x, y) then (\n p: cons([x, y], p)\n )\n ),\n p)$\n\np: randomDisc(100)$\nplot2d(['discrete, p], ['style, 'points]);\n", "language": "Maxima" }, { "code": "import tables, math, complex, random\n\ntype Point = tuple[x, y: int]\n\nvar world = initCountTable[Point]()\nvar possiblePoints = newSeq[Point]()\n\nfor x in -15..15:\n for y in -15..15:\n if abs(complex(x.float, y.float)) in 10.0..15.0:\n possiblePoints.add((x,y))\n\nrandomize()\nfor i in 0..100: world.inc possiblePoints.sample\n\nfor x in -15..15:\n for y in -15..15:\n let key = (x, y)\n if key in world and world[key] > 0:\n stdout.write ' ' & $min(9, world[key])\n else:\n stdout.write \" \"\n echo \"\"\n", "language": "Nim" }, { "code": "let p x y =\n let d = sqrt(x ** 2.0 +. y ** 2.0) in\n 10.0 <= d && d <= 15.0\n\nlet () =\n Random.self_init();\n let rec aux i acc =\n if i >= 100 then acc else\n let x = (Random.float 40.0) -. 20.0\n and y = (Random.float 40.0) -. 20.0 in\n if (p x y)\n then aux (succ i) ((x,y)::acc)\n else aux i acc\n in\n let points = aux 0 [] in\n let g = Array.init 40 (fun _ -> String.make 40 ' ') in\n List.iter (fun (x,y) ->\n let x = (int_of_float x) + 20\n and y = (int_of_float y) + 20 in\n g.(y).[x] <- 'o'\n ) points;\n Array.iter print_endline g\n", "language": "OCaml" }, { "code": "crpc()={\n my(v=vector(404),t=0,i=0,vx=vy=vector(100));\n for(x=1,14,for(y=1,14,\n t=x^2+y^2;\n if(t>99&t<226,\n v[i++]=[x,y];\n v[i++]=[x,-y];\n v[i++]=[-x,y];\n v[i++]=[-x,-y]\n )\n ));\n for(x=10,15,\n v[i++]=[x,0];\n v[i++]=[-x,0];\n v[i++]=[0,x];\n v[i++]=[0,-x]\n );\n for(i=1,#vx,\n t=v[random(#v)+1];\n vx[i]=t[1];\n vy[i]=t[2];\n );\n plothraw(vx,vy)\n};\n", "language": "PARI-GP" }, { "code": "my @points;\nwhile (@points < 100) {\n my ($x, $y) = (int(rand(31))-15, int(rand(31)) - 15);\n my $r2 = $x*$x + $y*$y;\n next if $r2 < 100 || $r2 > 225;\n push @points, [$x, $y];\n}\n\nprint << 'HEAD';\n%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox 0 0 400 400\n200 200 translate 10 10 scale\n0 setlinewidth\n1 0 0 setrgbcolor\n0 0 10 0 360 arc stroke\n0 0 15 360 0 arcn stroke\n0 setgray\n/pt { .1 0 360 arc fill } def\nHEAD\n\nprint \"@$_ pt\\n\" for @points;\nprint \"%%EOF\";\n", "language": "Perl" }, { "code": "@range = -15..16;\n\nfor $x (@range) {\n for $y (@range) {\n $radius = sqrt $x**2 + $y**2;\n push @points, [$x,$y] if 10 <= $radius and $radius <= 15\n }\n}\n\npush @sample, @points[int rand @points] for 1..100;\npush @matrix, ' ' x @range for 1..@range;\nsubstr $matrix[15+$$_[1]], 15+$$_[0], 1, '*' for @sample;\nprint join(' ', split '', $_) . \"\\n\" for @matrix;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">screen</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">31</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">31</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">r</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">rand</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">31</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">y</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">rand</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">31</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sqrt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">15</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">screen</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">'x'</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">100</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">screen</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">))</span>\n<!--\n", "language": "Phix" }, { "code": "(let Area (make (do 31 (link (need 31 \" \"))))\n (use (X Y)\n (do 100\n (until\n (>=\n 15\n (sqrt\n (+\n (* (setq X (rand -15 15)) X)\n (* (setq Y (rand -15 15)) Y) ) )\n 10 ) )\n (set (nth Area (+ 16 X) (+ 16 Y)) \"#\") ) )\n (mapc prinl Area) )\n", "language": "PicoLisp" }, { "code": "constrain: procedure options (main);\n declare 1 point (100),\n 2 x fixed binary,\n 2 y fixed binary;\n declare (i, j, a, b, c) fixed binary;\n\n j = 0;\n do i = 1 to 100;\n a = 30*random()-15; b = 30*random()-15;\n c = sqrt(a**2 + b**2);\n if abs(c) >= 10 & abs(c) <= 15 then\n do; j = j + 1; x(j) = a; y(j) = b; end;\n end;\n\n /* PLOT */\n declare table(-15:15, -15:15) character (1);\n table = ' ';\n do i = 1 to j;\n table(x(i), y(i)) = '*';\n end;\n do i = -15 to 15;\n put skip;\n do j = -15 to 15;\n put edit (table(i,j)) (a);\n end;\n end;\nend constrain;\n", "language": "PL-I" }, { "code": "*process source attributed xref or(!);\n annulus: procedure options (main);\n /* version 1 does not handle (0/15) etc. this does. */\n /* we show 1000 points here */\n declare 1 point(10000),\n 2 x fixed binary,\n 2 y fixed binary;\n declare (i, j, a, b, a2, b2, c) fixed binary(31);\n j = 0;\n do i = 1 to 1000;\n r=rand(31); a=r-16;\n r=rand(31); b=r-16;\n a2=a*a;\n b2=b*b;\n c2=a2+b2;\n if c2>= 100 & c2 <= 225 then\n do; j = j + 1; x(j) = a; y(j) = b;\n /* put Edit(a,b,c)(3(F(3))); */ end;\n end;\n /* PLOT */\n declare table(-15:15, -15:15) character (2);\n table = ' ';\n do i = 1 to j;\n table(x(i), y(i)) = '*';\n end;\n do i = -15 to 15;\n put skip;\n do j = -15 to 15;\n put edit (table(i,j)) (a);\n end;\n end;\n\n rand: Proc(n) Returns(Bin Fixed(31));\n /*--------------------------------------------------------------------\n * Return a random integer between 1 and n\n *-------------------------------------------------------------------*/\n Dcl r Bin Float(31);\n Dcl (n,d) Bin Fixed(31);\n r=random();\n d=r*n+1;\n Return(d);\n End;\n End annulus;\n", "language": "PL-I" }, { "code": "$MinR2 = 10 * 10\n$MaxR2 = 15 * 15\n\n$Points = @{}\n\nWhile ( $Points.Count -lt 100 )\n {\n $X = Get-Random -Minimum -16 -Maximum 17\n $Y = Get-Random -Minimum -16 -Maximum 17\n $R2 = $X * $X + $Y * $Y\n\n If ( $R2 -ge $MinR2 -and $R2 -le $MaxR2 -and \"$X,$Y\" -notin $Points.Keys )\n {\n $Points += @{ \"$X,$Y\" = 1 }\n }\n }\n\nForEach ( $Y in -16..16 ) { ( -16..16 | ForEach { ( \" \", \"*\" )[[int]$Points[\"$_,$Y\"]] } ) -join '' }\n", "language": "PowerShell" }, { "code": ":- use_module(library(clpfd)).\n\ncircle :-\n\tbagof([X,Y], init(X,Y), BL),\n\tlength(BL, N),\n\tlength(L, 100),\n\tmaplist(choose(BL, N), L),\n\tdraw_circle(L).\n\n\n% point selection\nchoose(BL, N, V) :-\n\tI is random(N),\n\tnth0(I, BL, V).\n\n% to find all couples of numbers verifying\n% 100 <= x^2 + y^2 <= 225\ninit(X1, Y1) :-\n\tX in -15..15,\n\tY in -15..15,\n\tX*X + Y*Y #>= 100,\n\tX*X + Y*Y #=< 225,\n\tlabel([X,Y]),\n\tX1 is 10 * X + 200,\n\tY1 is 10 * Y + 200.\n\n\ndraw_circle(L) :-\n\tnew(D, window('Circle')),\n\tsend(D, size,size(400,400)),\n\tforall(member([X,Y], L),\n\t ( new(C, circle(4)),\n\t\t send(C, fill_pattern, colour(@default, 0, 0, 0)),\n\t\t send(C, center(point(X,Y))),\n\t\t send(D, display, C))),\n\tsend(D, open).\n", "language": "Prolog" }, { "code": "CreateImage(0,31,31)\nStartDrawing(ImageOutput(0))\n For i=1 To 100\n Repeat\n x=Random(30)-15\n y=Random(30)-15\n R.f=Sqr(x*x+y*y)\n Until 10<=R And R<=15\n Plot(x+15,y+15,#Red)\n Next\nStopDrawing()\n\nTitle$=\"PureBasic Plot\"\nFlags=#PB_Window_SystemMenu\nOpenWindow(0,#PB_Ignore,#PB_Ignore,ImageWidth(0),ImageHeight(0),Title$,Flags)\nImageGadget(0,0,0,ImageWidth(0),ImageHeight(0),ImageID(0))\nRepeat: Until WaitWindowEvent()=#PB_Event_CloseWindow\n", "language": "PureBasic" }, { "code": ">>> from collections import defaultdict\n>>> from random import choice\n>>> world = defaultdict(int)\n>>> possiblepoints = [(x,y) for x in range(-15,16)\n\t\t for y in range(-15,16)\n\t\t if 10 <= abs(x+y*1j) <= 15]\n>>> for i in range(100): world[choice(possiblepoints)] += 1\n\n>>> for x in range(-15,16):\n\tprint(''.join(str(min([9, world[(x,y)]])) if world[(x,y)] else ' '\n\t\t\t for y in range(-15,16)))\n\n\t\n\n 1 1\n 1 1\n 11 1 1 1 1\n 111 1 1211\n 1 2 1 1 11\n 1 11 21\n 1 1 11 1\n 1 2 1 1\n\n 1 2\n 1 1 1\n 1 1\n 2 11\n 1 1\n 1\n\n\n 1 1\n 1\n 2\n 1\n 1 1 1\n 1 2 1\n 1 3 11 2\n 11 1 1 1 2\n 1 1 2\n 1 1\n 1 1 1\n 2 2 1\n 1\n", "language": "Python" }, { "code": ">>> for i in range(1000): world[choice(possiblepoints)] += 1\n\n>>> for x in range(-15,16):\n\tprint(''.join(str(min([9, world[(x,y)]])) if world[(x,y)] else ' '\n\t\t\t for y in range(-15,16)))\n\n\t\n 2\n 41341421333\n 5133333131253 1\n 5231514 14214721 24\n 326 21222143234122322\n 54235153132123344125 22\n 32331432 2422 33\n 5453135 4144344\n 132595 323123\n 4 6353 432224\n 5 4323 3 5313\n 23214 41433\n 42454 33342\n 332 4 34314\n 142 1 35 53\n124211 53131\n 22221 152 4\n 22213 34562\n 654 4 4 212\n 24354 52232\n 544222 283323\n 411123 453325\n 251321 124332\n 2124134 2443226\n 2 113315 64324334\n 2412452 324 32121132363\n 4222434324635 5433\n 3113333123432112633\n 2131181233 424\n 47414232164\n 4\n", "language": "Python" }, { "code": " [ 0 31 of ] is grid ( --> [ )\n\n [ dup * ] is squared ( n --> n )\n\n [ squared swap squared +\n 10 squared 15 squared 1+\n within ] is inrange ( n n --> b )\n\n [ 32 random 16 -\n 32 random 16 -\n 2dup inrange not while\n 2drop again ] is randxy ( --> n n )\n\n [ 15 + swap 15 +\n dip [ 2dup peek ]\n bit | unrot poke ] is plot ( [ n n --> [ )\n\n [ witheach\n [ 31 times\n [ dup\n i^ bit & iff\n [ $ \"[]\" ]\n else\n [ $ \" \" ]\n echo$ ]\n drop\n cr ] ] is draw ( [ --> )\n\n [ grid\n swap times\n [ randxy plot ]\n draw ] is circle ( n --> )\n\n 100 circle\n", "language": "Quackery" }, { "code": "RMin <- 10\nRMax <- 15\nNPts <- 100\n\n# instead of a for loop, we generate what should be enough points\n# also take care to have enough range to avoid rounding inaccuracies\nnBlock <- NPts * ((RMax/RMin) ^ 2)\nnValid <- 0\nwhile (nValid < NPts) {\n\tX <- round(runif(nBlock, -RMax - 1, RMax + 1))\n\tY <- round(runif(nBlock, -RMax - 1, RMax + 1))\n\tR <- sqrt(X^2 + Y^2)\n\tValid <- ( (R >= RMin) & (R <= RMax) )\n\tnValid <- sum(Valid)\n\tnBlock <- 2 * nBlock\n}\nplot(X[Valid][1:NPts],Y[Valid][1:NPts], pch=19, cex=0.25, col=\"blue\",\n\txlab=\"x\",ylab=\"y\",main=\"Fuzzy circle\", xlim=c(-RMax,RMax), ylim=c(-RMax,RMax) )\n", "language": "R" }, { "code": "#lang racket\n\n(require plot plot/utils)\n\n(plot (points (for*/lists (result)\n ([_ (in-naturals)]\n #:break (= 100 (length result))\n [xy (in-value (v- (vector (random 31) (random 31))\n #(15 15)))]\n #:when (<= 10 (vmag xy) 15))\n xy)))\n", "language": "Racket" }, { "code": "my @range = -15..16;\n\nmy @points = gather for @range X @range -> ($x, $y) {\n take [$x,$y] if 10 <= sqrt($x*$x+$y*$y) <= 15\n}\nmy @samples = @points.roll(100); # or .pick(100) to get distinct points\n\n# format and print\nmy %matrix;\nfor @range X @range -> ($x, $y) { %matrix{$y}{$x} = ' ' }\n%matrix{.[1]}{.[0]} = '*' for @samples;\n%matrix{$_}{@range}.join(' ').say for @range;\n", "language": "Raku" }, { "code": "(say ~.map: { $_ // ' ' } for my @matrix) given do\n -> [$x, $y] { @matrix[$x][$y] = '*' } for pick 100, do\n for ^32 X ^32 -> ($x, $y) {\n [$x,$y] when 100..225 given [+] ($x,$y X- 15) X** 2;\n }\n", "language": "Raku" }, { "code": "/*REXX program generates 100 random points in an annulus: 10 ≤ √(x²≤y²) ≤ 15 */\nparse arg pts LO HI . /*obtain optional args from the C.L. */\nif pts=='' then pts= 100 /*Not specified? Then use the default.*/\nif LO=='' then LO= 10; LO2= LO**2 /*define a shortcut for squaring LO. */\nif HI=='' then HI= 15; HI2= HI**2 /* \" \" \" \" \" HI. */\n$=\n do x=-HI; xx= x*x /*generate all possible annulus points.*/\n if x>0 & xx>HI2 then leave /*end of annulus points generation ? */\n do y=-HI; s= xx + y*y\n if (y<0 & s>HI2) | s<LO2 then iterate\n if y>0 & s>HI2 then leave\n $= $ x','y /*add a point─set to the $ list. */\n end /*y*/\n end /*x*/\n #= words($); @.= /*def: plotchr; #pts; lines*/\n do pts; parse value word($, random(1,#)) with x ',' y /*get rand point in annulus*/\n @.y= overlay('☼', @.y, x+x + HI+HI + 1) /*put a plot char on a line*/\n end /*pts*/ /* [↑] maintain aspect ratio on X axis*/\n /*stick a fork in it, we're all done. */\n do y=-HI to HI; say @.y; end /*display the annulus to the terminal. */\n", "language": "REXX" }, { "code": "/* REXX ---------------------------------------------------------------\n* show 100 random points of an annulus with radius 10 to 15\n* 18.06.2014 Walter Pachl 'derived/simplified' from REXX version 1\n*--------------------------------------------------------------------*/\n Parse Arg points low high scale . /* allow parms from command line.*/\n If points=='' Then points=100 /* number of points */\n If low=='' Then low=10 /* inner radius */\n If high=='' Then high=15 /* outer radius */\n If scale=='' Then scale=2 /* horizontal scaling */\n low2=low**2\n high2=high**2\n /* first compute all possible points */\n point.=0\n Do x=-high To high\n x2=x*x\n Do y=-high To high\n y2=y*y\n s=x2+y2\n If s>=low2 &s<=high2 Then Do\n z=point.0+1\n point.z=x y\n point.0=z\n End\n End\n End\n plotchar='O'\n line.=''\n np=point.0 /* available points */\n Do j=1 To points /* pick the needed points */\n r=random(1,np)\n Parse Var point.r x y /* coordinates */\n line.y=overlay(plotchar,line.y,scale*(x+high)+1) /* put into line*/\n point.r=point.np /* replace taken point by last*/\n np=np-1 /* reduce available points */\n If np=0 Then Leave /* all possible points taken */\n End\n/* now draw the picture */\n Do y=-high To high\n Say line.y\n End\n", "language": "REXX" }, { "code": "/* REXX ---------------------------------------------------------------\n* 19.06.2014 Walter Pachl alternate algorithm\n* the idea: yl is a list of y coordinates which may have unused points\n* one of the y's is picked at random\n* Then we look for unused x coordinates in this line\n* we pick one at random or drop the y from yl if none is found\n* When yl becomes empty, all points are used and we stop\n*--------------------------------------------------------------------*/\nParse Arg n r rr scale\nIf r='' Then r=10\nIf rr='' Then rr=15\nIf n='' Then n=100\nIf scale='' Then scale=2\nr2=r*r\nrr2=rr*rr\nymin=0\nymax=rr*2\nol=''\npp.=0\nused.=0\nyl='' /* list of available y values */\nDo y=-rr To rr\n yl=yl y\n End\nDo Until pp.0=n /*look for the required points*/\n If yl='' Then Do /* no more points available */\n Say 'all points filled'\n Leave\n End\n yi=random(1,words(yl)) /* pick a y */\n y=word(yl,yi)\n y2=y*y\n p.=0\n Do x=0 To rr /* Loop through possible x's */\n x2=x*x\n xy2=x2+y2\n If xy2>=r2&xy2<=rr2 Then Do /* within the annulus */\n Call take x y\n Call take (-x) y\n End\n End\n If p.0>0 Then Do /* some x's found (or just 1) */\n xi=random(1,p.0) /* pick an x */\n z=pp.0+1\n pp.z=p.xi\n pp.0=z\n Parse Var pp.z xa ya\n used.xa.ya=1 /* remember it's taken */\n End\n Else Do /* no x for this y */\n yi=wordpos(y,yl) /* remove y from yl */\n Select\n When yi=1 Then yl=subword(yl,yi+1)\n When yi=words(yl) Then yl=subword(yl,1,yi-1)\n Otherwise yl=subword(yl,1,yi-1) subword(yl,yi+1)\n End\n End\n End\nline.='' /* empty the raster */\nDo i=1 To pp.0 /* place the points */\n Parse Var pp.i x y\n line.y=overlay('+',line.y,scale*(rr+x)+1)\n End\nDo y=-rr To rr /* show the result */\n Say line.y\n End\nsay pp.0 'points filled'\nExit\nReturn\n\ntake: Procedure Expose p. used. /* add x to p. if its not used*/\n Parse Arg x y\n If used.x.y=0 Then Do\n z=p.0+1\n p.z=x y\n p.0=z\n End\n Return\n", "language": "REXX" }, { "code": "load \"guilib.ring\"\n\nnew qapp\n {\n win1 = new qwidget() {\n setwindowtitle(\"drawing using qpainter\")\n setgeometry(100,100,500,500)\n label1 = new qlabel(win1) {\n setgeometry(10,10,400,400)\n settext(\"\")\n }\n new qpushbutton(win1) {\n setgeometry(200,400,100,30)\n settext(\"draw\")\n setclickevent(\"draw()\")\n }\n show()\n }\n exec()\n }\n\nfunc draw\n p1 = new qpicture()\n color = new qcolor() {\n setrgb(0,0,255,255)\n }\n pen = new qpen() {\n setcolor(color)\n setwidth(1)\n }\n new qpainter() {\n begin(p1)\n setpen(pen)\n\n for i = 1 to 1000\n x = random(31)-16\n y = random(31)-16\n r = sqrt (pow(x,2) + pow(y,2))\n if r >= 10 if r <= 15 drawpoint(x*2, y*2) ok ok\n next\n\n endpaint()\n }\n label1 { setpicture(p1) show() }\n", "language": "Ring" }, { "code": "points = (1..100).map do\n # choose a random radius and angle\n angle = rand * 2.0 * Math::PI\n rad = rand * 5.0 + 10.0\n # convert back from polar to cartesian coordinates\n [rad * Math::cos(angle), rad * Math::sin(angle)].map(&:round)\nend\n\n(-15..15).each do |row|\n puts (-15..15).map { |col| points.include?([row, col]) ? \"X\" : \" \" }.join\nend\n\nload 'raster_graphics.rb'\n\npixmap = Pixmap.new(321,321)\npixmap.draw_circle(Pixel.new(160,160),90,RGBColour::BLACK)\npixmap.draw_circle(Pixel.new(160,160),160,RGBColour::BLACK)\npoints.each {|(x,y)| pixmap[10*(x+16),10*(y+16)] = RGBColour::BLACK}\npngfile = __FILE__\npngfile[/\\.rb/] = \".png\"\npixmap.save_as_png(pngfile)\n", "language": "Ruby" }, { "code": "r2 = 10*10..15*15\nrange = (-15..15).to_a\npoints = range.product(range).select {|i,j| r2.cover?(i*i + j*j)}\n\nputs \"Precalculate: #{points.size}\"\npt = Hash.new(\" \")\npoints.sample(100).each{|ij| pt[ij] = \" o\"}\nputs range.map{|i| range.map{|j| pt[[i,j]]}.join}\n", "language": "Ruby" }, { "code": "w = 320\nh = 320\ndim canvas(w,h)\nfor pts = 1 to 1000\n x = (rnd(1) * 31) - 15\n y = (rnd(1) * 31) - 15\n r = x * x + y * y\n if (r > 100) and (r < 225) then\n x = int(x * 10 + w/2)\n y = int(y * 10 + h/2)\n canvas(x,y) = 1\n end if\nnext pts\n\n' -----------------------------\n' display the graphic\n' -----------------------------\ngraphic #g, w,h\nfor x = 1 to w\n for y = 1 to h\n if canvas(x,y) = 1 then #g \"color green ; set \"; x; \" \"; y else #g \"color blue ; set \"; x; \" \"; y\n next y\nnext x\nrender #g\n#g \"flush\"\n", "language": "Run-BASIC" }, { "code": "extern crate rand;\n\nuse rand::Rng;\n\nconst POINTS_N: usize = 100;\n\nfn generate_point<R: Rng>(rng: &mut R) -> (i32, i32) {\n loop {\n let x = rng.gen_range(-15, 16); // exclusive\n let y = rng.gen_range(-15, 16);\n\n let r2 = x * x + y * y;\n if r2 >= 100 && r2 <= 225 {\n return (x, y);\n }\n }\n}\n\nfn filtering_method<R: Rng>(rng: &mut R) {\n let mut rows = [[\" \"; 62]; 31];\n\n // Generate points\n for _ in 0..POINTS_N {\n let (x, y) = generate_point(rng);\n rows[(y + 15) as usize][(x + 15) as usize * 2] = \"*\";\n }\n\n // draw the points\n for row in &rows {\n println!(\"{}\", row.concat());\n }\n}\n\nfn precalculating_method<R: Rng>(rng: &mut R) {\n // Generate all possible points\n let mut possible_points = Vec::with_capacity(404);\n for y in -15..=15 {\n for x in -15..=15 {\n let r2 = x * x + y * y;\n if r2 >= 100 && r2 <= 225 {\n possible_points.push((x, y));\n }\n }\n }\n\n // A truncated Fisher-Yates shuffle\n let len = possible_points.len();\n for i in (len - POINTS_N..len).rev() {\n let j = rng.gen_range(0, i + 1);\n possible_points.swap(i, j);\n }\n\n // turn the selected points into \"pixels\"\n let mut rows = [[\" \"; 62]; 31];\n for &(x, y) in &possible_points[len - POINTS_N..] {\n rows[(y + 15) as usize][(x + 15) as usize * 2] = \"*\";\n }\n\n // draw the \"pixels\"\n for row in &rows {\n println!(\"{}\", row.concat());\n }\n}\n\nfn main() {\n let mut rng = rand::weak_rng();\n\n filtering_method(&mut rng);\n\n precalculating_method(&mut rng);\n}\n", "language": "Rust" }, { "code": "import java.awt.{ Color, geom,Graphics2D ,Rectangle}\nimport scala.math.hypot\nimport scala.swing.{MainFrame,Panel,SimpleSwingApplication}\nimport scala.swing.Swing.pair2Dimension\nimport scala.util.Random\n\nobject CirculairConstrainedRandomPoints extends SimpleSwingApplication {\n //min/max of display-x resp. y\n val dx0, dy0 = 30; val dxm, dym = 430\n val prefSizeX, prefSizeY = 480\n\n val palet = Map(\"b\" -> Color.blue, \"g\" -> Color.green, \"r\" -> Color.red, \"s\" -> Color.black)\n val cs = List((0, 0, 10, \"b\"), (0, 0, 15, \"g\")) //circle position and color\n val xmax, ymax = 20; val xmin, ymin = -xmax\n\n class Coord(x: Double, y: Double) {\n def dx = (((dxm - dx0) / 2 + x.toDouble / xmax * (dxm - dx0) / 2) + dx0).toInt\n def dy = (((dym - dy0) / 2 - y.toDouble / ymax * (dym - dy0) / 2) + dy0).toInt\n }\n\n object Coord {\n def apply(x: Double, y: Double) = new Coord(x, y)\n }\n\n //points:\n val points =\n new Iterator[Int] { val r = new Random;def next = r.nextInt(31) - 15; def hasNext = true }.toStream.\n zip(new Iterator[Int] { val r = new Random; def next = r.nextInt(31) - 15; def hasNext = true }.toStream).\n map { case (x, y) => (x, y, hypot(x, y)) }.filter { case (x, y, r) => r >= 10 && r <= 15 }.take(100).toSeq.\n map { case (x, y, r) => new Rectangle(Coord(x, y).dx - 2, Coord(x, y).dy - 2, 4, 4) }\n\n private def ui = new Panel {\n background = Color.white\n preferredSize = (prefSizeX, prefSizeY)\n\n class Circle(center: Coord, r: Double, val color: Color) {\n val dr = (Coord(r, 0).dx - pcentre.dx) * 2\n val dx = center.dx - dr / 2\n val dy = center.dy - dr / 2\n }\n\n object Circle {\n def apply(x: Double, y: Double, r: Double, color: Color) =\n new Circle(Coord(x, y), r, color)\n }\n\n val pcentre = Coord(0, 0)\n val pxmax = Coord(xmax, 0); val pxmin = Coord(xmin, 0)\n val pymax = Coord(0, ymax); val pymin = Coord(0, ymin)\n\n //axes:\n val a_path = new geom.GeneralPath\n a_path.moveTo(pxmin.dx, pxmin.dy); a_path.lineTo(pxmax.dx, pxmax.dy) //x-axis\n a_path.moveTo(pymin.dx, pymin.dy); a_path.lineTo(pymax.dx, pymax.dy) //y-axis\n\n //labeling:\n val labels = List(-20, -15, -10, -5, 5, 10, 15, 20)\n labels.foreach { x => { val p = Coord(x, 0); a_path.moveTo(p.dx, p.dy - 3); a_path.lineTo(p.dx, p.dy + 3) } }\n labels.foreach { y => { val p = Coord(0, y); a_path.moveTo(p.dx - 3, p.dy); a_path.lineTo(p.dx + 3, p.dy) } }\n val xlabels = labels.map(x => { val p = Coord(x, 0); Triple(x.toString, p.dx - 3, p.dy + 20) })\n val ylabels = labels.map(y => { val p = Coord(0, y); Triple(y.toString, p.dx - 20, p.dy + 5) })\n\n //circles:\n val circles = cs.map { case (x, y, r, c) => Circle(x, y, r, palet(c)) }\n\n override def paintComponent(g: Graphics2D) = {\n super.paintComponent(g)\n circles.foreach { c => { g.setColor(c.color); g.drawOval(c.dx, c.dy, c.dr, c.dr) } }\n g.setColor(palet(\"r\")); points.foreach(g.draw(_))\n g.setColor(palet(\"s\")); g.draw(a_path)\n xlabels.foreach { case (text, px, py) => g.drawString(text, px, py) }\n ylabels.foreach { case (text, px, py) => g.drawString(text, px, py) }\n }\n } // def ui\n\n def top = new MainFrame {\n title = \"Rosetta Code >>> Task: Constrained random points on a circle | Language: Scala\"\n contents = ui\n }\n}\n", "language": "Scala" }, { "code": "var points = []\nwhile (points.len < 100) {\n var (x, y) = 2.of{ 30.irand - 15 }...\n var r2 = (x**2 + y**2)\n if ((r2 >= 100) && (r2 <= 225)) {\n points.append([x, y])\n }\n}\n\nprint <<'HEAD'\n%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox 0 0 400 400\n200 200 translate 10 10 scale\n0 setlinewidth\n1 0 0 setrgbcolor\n0 0 10 0 360 arc stroke\n0 0 15 360 0 arcn stroke\n0 setgray\n/pt { .1 0 360 arc fill } def\nHEAD\n\npoints.each { |pt| say \"#{pt.join(' ')} pt\" }\nprint '%%EOF'\n", "language": "Sidef" }, { "code": "open XWindows ;\nopen Motif ;\n\nval plotWindow = fn coords => (* input list of int*int within 'dim' *)\nlet\n val dim = {tw=325,th=325} ;\n val shell = XtAppInitialise \"\" \"demo\" \"top\" [] [ XmNwidth (#tw dim), XmNheight (#th dim) ] ; (* single call only *)\n val main = XmCreateMainWindow shell \"main\" [ XmNmappedWhenManaged true ] ;\n val canvas = XmCreateDrawingArea main \"drawarea\" [ XmNwidth (#tw dim), XmNheight (#th dim) ] ;\n val usegc = DefaultGC (XtDisplay canvas) ;\n val put = fn (w,s,t)=> (\n XSetForeground usegc 0xfffffff ;\n XFillRectangle (XtWindow canvas) usegc (Area{x=0,y=0,w = #tw dim, h= #th dim}) ;\n\t\t XSetForeground usegc 0 ;\n XDrawPoints (XtWindow canvas) usegc ( List.map (fn (x,y)=>XPoint {x=x,y=y}) coords ) CoordModeOrigin ;\n\t\t t )\nin\n\n (\n XtSetCallbacks canvas [ (XmNexposeCallback , put) ] XmNarmCallback ;\n XtManageChild canvas ;\n XtManageChild main ;\n XtRealizeWidget shell\n )\n\nend;\n\nval urandomlist = fn seed => fn n =>\n(* put code from (www.rosettacode.org) wiki/Random_numbers#Standard_ML 'urandomlist' here\ninput : seed and number of drawings *)\nend;\n\nval normalizedPts = fn () => (* select ([0,1]*[0,1]) points in normalized bandwidth *)\n let\n val realseeds = ( 972.1 , 10009.3 ) ;\n val usum = fn (u,v) => u*(u-1.0) + v*(v-1.0) ;\n val lim = ( ~350.0/900.0, ~225.0/900.0 ) ; (* limits to usum *)\n val select = fn i => usum i <= #2 lim andalso usum i >= #1 lim ; (* select according to inequalities *)\n val uv = ListPair.zip ( urandomlist (#1 realseeds) 2500 , urandomlist (#2 realseeds) 2500 ) (* take 2500 couples *)\n in\n List.take ( List.filter select uv , 1000 )\nend ;\n", "language": "Standard-ML" }, { "code": "let nPoints = 100\n\nfunc generatePoint() -> (Int, Int) {\n while true {\n let x = Int.random(in: -15...16)\n let y = Int.random(in: -15...16)\n let r2 = x * x + y * y\n\n if r2 >= 100 && r2 <= 225 {\n return (x, y)\n }\n }\n}\n\nfunc filteringMethod() {\n var rows = [[String]](repeating: Array(repeating: \" \", count: 62), count: 31)\n\n for _ in 0..<nPoints {\n let (x, y) = generatePoint()\n\n rows[y + 15][x + 15 * 2] = \"*\"\n }\n\n for row in rows {\n print(row.joined())\n }\n}\n\nfunc precalculatingMethod() {\n var possiblePoints = [(Int, Int)]()\n\n for y in -15...15 {\n for x in -15...15 {\n let r2 = x * x + y * y\n\n if r2 >= 100 && r2 <= 225 {\n possiblePoints.append((x, y))\n }\n }\n }\n\n possiblePoints.shuffle()\n\n var rows = [[String]](repeating: Array(repeating: \" \", count: 62), count: 31)\n\n for (x, y) in possiblePoints {\n rows[y + 15][x + 15 * 2] = \"*\"\n }\n\n for row in rows {\n print(row.joined())\n }\n}\n\nprint(\"Filtering method:\")\nfilteringMethod()\n\nprint(\"Precalculating method:\")\nprecalculatingMethod()\n", "language": "Swift" }, { "code": "program main;\n\n bit [39:0] bitmap [40];\n\n class Point;\n rand bit signed [4:0] x;\n rand bit signed [4:0] y;\n\n constraint on_circle_edge {\n (10*10) <= (x*x + y*y);\n (x*x + y*y) <= (15*15);\n };\n\n function void do_point();\n randomize;\n bitmap[x+20][y+20] = 1;\n endfunction\n endclass\n\n initial begin\n Point p = new;\n repeat (100) p.do_point;\n foreach (bitmap[row]) $display( \"%b\", bitmap[row]);\n end\n\nendprogram\n", "language": "SystemVerilog" }, { "code": "package require Tcl 8.5\n\n# Generate random point at specified distance from the centre\nproc getPoint {range from to} {\n set r2 [expr {$range / 2}]\n set f2 [expr {$from ** 2}]\n set t2 [expr {$to ** 2}]\n while 1 {\n\tset x [expr {int($range * rand())}]\n\tset y [expr {int($range * rand())}]\n\tset d2 [expr {($x-$r2)**2 + ($y-$r2)**2}]\n\tif {$d2 >= $f2 && $d2 <= $t2} {\n\t return [list $y $x]\n\t}\n }\n}\n\n# Make somewhere to store the counters\nset ary [lrepeat 31 [lrepeat 31 0]]\n\n# Generate 100 random points\nfor {set i 0} {$i < 100} {incr i} {\n set location [getPoint 31 10 15]\n # Increment the counter for the point\n lset ary $location [expr {1 + [lindex $ary $location]}]\n}\n\n# Simple renderer\nforeach line $ary {\n foreach c $line {\n\tputs -nonewline [expr {$c == 0 ? \" \" : $c > 9 ? \"X\" : $c}]\n }\n puts \"\"\n}\n", "language": "Tcl" }, { "code": "import \"graphics\" for Canvas, Color\nimport \"dome\" for Window\nimport \"random\" for Random\n\nclass Game {\n static init() {\n Window.title = \"Constrained random points on a circle\"\n var width = 800\n var height = 800\n Window.resize(width, height)\n Canvas.resize(width, height)\n var rand = Random.new()\n var count = 0\n var max = 100 // set to 1000 to produce a much more pronounced annulus\n while (true) {\n var x = rand.int(-15, 16)\n var y = rand.int(-15, 16)\n var dist = (x*x + y*y).sqrt\n if (10 <= dist && dist <= 15) {\n // translate coordinates to fit in the window\n Canvas.circlefill((x + 16) * 25, (y + 16) * 25, 2, Color.white)\n count = count + 1\n if (count == max) break\n }\n }\n }\n\n static update() {}\n\n static draw(alpha) {}\n}\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes; \\intrinsic 'code' declarations\nint X, Y, C, R2;\n[SetVid($13); \\set 320x200x8 graphics mode\nC:= 0; \\initialize point counter\nrepeat X:= Ran(31)-15; \\range -15..+15\n Y:= Ran(31)-15;\n R2:= X*X + Y*Y;\n if R2>=10*10 & R2<=15*15 then\n [Point(X+160, Y+100, $F); C:= C+1];\nuntil C >= 100;\nC:= ChIn(1); \\wait for keystroke\nSetVid(3); \\restore normal text mode\n]\n", "language": "XPL0" }, { "code": "open window 100, 100\nclear window\n\nfor i = 1 to 100\n\trepeat\n\t\tx = ran(30)-15\n\t\ty = ran(30)-15\n\t\tr = sqr(x*x + y*y)\n\tuntil 10 <= r and r <= 15\n\tcolor 255, 0, 0\n\tdot x+15, y+15\nnext i\nend\n", "language": "Yabasic" }, { "code": "xy:=(0).walker(*).tweak(fcn{ // generate infinite random pairs (lazy)\n x:=(-15).random(16); y:=(-15).random(16);\n if(not (100<=(x*x + y*y)<=225)) Void.Skip else T(x,y)\n});\n\nconst N=31; // [-15..15] includes 0\narray:=(\" ,\"*N*N).split(\",\").copy(); // bunch of spaces (list)\n\nxy.walk(100).apply2(fcn([(x,y)],array){array[x+15 + N*(y+15)]=\"*\"},array);\nforeach n in ([0..30]){ array[n*N,30].concat().println(); }\n", "language": "Zkl" }, { "code": "10 FOR i=1 TO 1000\n20 LET x=RND*31-16\n30 LET y=RND*31-16\n40 LET r=SQR (x*x+y*y)\n50 IF (r>=10) AND (r<=15) THEN PLOT 127+x*2,88+y*2\n60 NEXT i\n", "language": "ZX-Spectrum-Basic" } ]
Constrained-random-points-on-a-circle
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Continued_fraction\n", "language": "00-META" }, { "code": "A number may be represented as a [[wp:Continued fraction|continued fraction]] (see [http://mathworld.wolfram.com/ContinuedFraction.html Mathworld] for more information) as follows:\n\n:<math>a_0 + \\cfrac{b_1}{a_1 + \\cfrac{b_2}{a_2 + \\cfrac{b_3}{a_3 + \\ddots}}}</math>\n\nThe task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:\n\nFor the square root of 2, use <math>a_0 = 1</math> then <math>a_N = 2</math>. <math>b_N</math> is always <math>1</math>.\n\n:<math>\\sqrt{2} = 1 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\ddots}}}</math>\n\nFor Napier's Constant, use <math>a_0 = 2</math>, then <math>a_N = N</math>. <math>b_1 = 1</math> then <math>b_N = N-1</math>.\n\n:<math>e = 2 + \\cfrac{1}{1 + \\cfrac{1}{2 + \\cfrac{2}{3 + \\cfrac{3}{4 + \\ddots}}}}</math>\n\nFor Pi, use <math>a_0 = 3</math> then <math>a_N = 6</math>. <math>b_N = (2N-1)^2</math>.\n\n:<math>\\pi = 3 + \\cfrac{1}{6 + \\cfrac{9}{6 + \\cfrac{25}{6 + \\ddots}}}</math>\n\n\n;See also:\n:* &nbsp; [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F calc(f_a, f_b, =n = 1000)\n V r = 0.0\n L n > 0\n r = f_b(n) / (f_a(n) + r)\n n--\n R f_a(0) + r\n\nprint(calc(n -> I n > 0 {2} E 1, n -> 1))\nprint(calc(n -> I n > 0 {n} E 2, n -> I n > 1 {n - 1} E 1))\nprint(calc(n -> I n > 0 {6} E 3, n -> (2 * n - 1) ^ 2))\n", "language": "11l" }, { "code": "INCLUDE \"D2:REAL.ACT\" ;from the Action! Tool Kit\n\nDEFINE PTR=\"CARD\"\nDEFINE JSR=\"$20\"\nDEFINE RTS=\"$60\"\n\nPROC CoeffA=*(INT n REAL POINTER res)\n [JSR $00 $00 ;JSR to address set by SetCoeffA\n RTS]\n\nPROC CoeffB=*(INT n REAL POINTER res)\n [JSR $00 $00 ;JSR to address set by SetCoeffB\n RTS]\n\nPROC SetCoeffA(PTR p)\n PTR addr\n\n addr=CoeffA+1 ;location of address of JSR\n PokeC(addr,p)\nRETURN\n\nPROC SetCoeffB(PTR p)\n PTR addr\n\n addr=CoeffB+1 ;location of address of JSR\n PokeC(addr,p)\nRETURN\n\nPROC Calc(PTR funA,funB INT count REAL POINTER res)\n INT i\n REAL a,b,tmp\n\n SetCoeffA(funA)\n SetCoeffB(funB)\n\n IntToReal(0,res)\n i=count\n WHILE i>0\n DO\n CoeffA(i,a)\n CoeffB(i,b)\n RealAdd(a,res,tmp)\n RealDiv(b,tmp,res)\n i==-1\n OD\n CoeffA(0,a)\n RealAdd(a,res,tmp)\n RealAssign(tmp,res)\nRETURN\n\nPROC sqrtA(INT n REAL POINTER res)\n IF n>0 THEN\n IntToReal(2,res)\n ELSE\n IntToReal(1,res)\n FI\nRETURN\n\nPROC sqrtB(INT n REAL POINTER res)\n IntToReal(1,res)\nRETURN\n\nPROC napierA(INT n REAL POINTER res)\n IF n>0 THEN\n IntToReal(n,res)\n ELSE\n IntToReal(2,res)\n FI\nRETURN\n\nPROC napierB(INT n REAL POINTER res)\n IF n>1 THEN\n IntToReal(n-1,res)\n ELSE\n IntToReal(1,res)\n FI\nRETURN\n\nPROC piA(INT n REAL POINTER res)\n IF n>0 THEN\n IntToReal(6,res)\n ELSE\n IntToReal(3,res)\n FI\nRETURN\n\nPROC piB(INT n REAL POINTER res)\n REAL tmp\n\n IntToReal(2*n-1,tmp)\n RealMult(tmp,tmp,res)\nRETURN\n\nPROC Main()\n REAL res\n\n Put(125) PutE() ;clear the screen\n\n Calc(sqrtA,sqrtB,50,res)\n Print(\" Sqrt2=\") PrintRE(res)\n\n Calc(napierA,napierB,50,res)\n Print(\"Napier=\") PrintRE(res)\n\n Calc(piA,piB,500,res)\n Print(\" Pi=\") PrintRE(res)\nRETURN\n", "language": "Action-" }, { "code": "generic\n type Scalar is digits <>;\n\n with function A (N : in Natural) return Natural;\n with function B (N : in Positive) return Natural;\nfunction Continued_Fraction (Steps : in Natural) return Scalar;\n", "language": "Ada" }, { "code": "function Continued_Fraction (Steps : in Natural) return Scalar is\n function A (N : in Natural) return Scalar is (Scalar (Natural'(A (N))));\n function B (N : in Positive) return Scalar is (Scalar (Natural'(B (N))));\n\n Fraction : Scalar := 0.0;\nbegin\n for N in reverse Natural range 1 .. Steps loop\n Fraction := B (N) / (A (N) + Fraction);\n end loop;\n return A (0) + Fraction;\nend Continued_Fraction;\n", "language": "Ada" }, { "code": "with Ada.Text_IO;\n\nwith Continued_Fraction;\n\nprocedure Test_Continued_Fractions is\n type Scalar is digits 15;\n\n package Square_Root_Of_2 is\n function A (N : in Natural) return Natural is (if N = 0 then 1 else 2);\n function B (N : in Positive) return Natural is (1);\n\n function Estimate is new Continued_Fraction (Scalar, A, B);\n end Square_Root_Of_2;\n\n package Napiers_Constant is\n function A (N : in Natural) return Natural is (if N = 0 then 2 else N);\n function B (N : in Positive) return Natural is (if N = 1 then 1 else N-1);\n\n function Estimate is new Continued_Fraction (Scalar, A, B);\n end Napiers_Constant;\n\n package Pi is\n function A (N : in Natural) return Natural is (if N = 0 then 3 else 6);\n function B (N : in Positive) return Natural is ((2 * N - 1) ** 2);\n\n function Estimate is new Continued_Fraction (Scalar, A, B);\n end Pi;\n\n package Scalar_Text_IO is new Ada.Text_IO.Float_IO (Scalar);\n use Ada.Text_IO, Scalar_Text_IO;\nbegin\n Put (Square_Root_Of_2.Estimate (200), Exp => 0); New_Line;\n Put (Napiers_Constant.Estimate (200), Exp => 0); New_Line;\n Put (Pi.Estimate (10000), Exp => 0); New_Line;\nend Test_Continued_Fractions;\n", "language": "Ada" }, { "code": "generic\n type Scalar is digits <>;\n\n with function A (N : in Natural) return Natural;\n with function B (N : in Positive) return Natural;\nfunction Continued_Fraction_Ada95 (Steps : in Natural) return Scalar;\n", "language": "Ada" }, { "code": "function Continued_Fraction_Ada95 (Steps : in Natural) return Scalar is\n function A (N : in Natural) return Scalar is\n begin\n return Scalar (Natural'(A (N)));\n end A;\n\n function B (N : in Positive) return Scalar is\n begin\n return Scalar (Natural'(B (N)));\n end B;\n\n Fraction : Scalar := 0.0;\nbegin\n for N in reverse Natural range 1 .. Steps loop\n Fraction := B (N) / (A (N) + Fraction);\n end loop;\n return A (0) + Fraction;\nend Continued_Fraction_Ada95;\n", "language": "Ada" }, { "code": "with Ada.Text_IO;\n\nwith Continued_Fraction_Ada95;\n\nprocedure Test_Continued_Fractions_Ada95 is\n type Scalar is digits 15;\n\n package Square_Root_Of_2 is\n function A (N : in Natural) return Natural;\n function B (N : in Positive) return Natural;\n\n function Estimate is new Continued_Fraction_Ada95 (Scalar, A, B);\n end Square_Root_Of_2;\n\n package body Square_Root_Of_2 is\n function A (N : in Natural) return Natural is\n begin\n if N = 0 then\n return 1;\n else\n return 2;\n end if;\n end A;\n\n function B (N : in Positive) return Natural is\n begin\n return 1;\n end B;\n end Square_Root_Of_2;\n\n package Napiers_Constant is\n function A (N : in Natural) return Natural;\n function B (N : in Positive) return Natural;\n\n function Estimate is new Continued_Fraction_Ada95 (Scalar, A, B);\n end Napiers_Constant;\n\n package body Napiers_Constant is\n function A (N : in Natural) return Natural is\n begin\n if N = 0 then\n return 2;\n else\n return N;\n end if;\n end A;\n\n function B (N : in Positive) return Natural is\n begin\n if N = 1 then\n return 1;\n else\n return N - 1;\n end if;\n end B;\n end Napiers_Constant;\n\n package Pi is\n function A (N : in Natural) return Natural;\n function B (N : in Positive) return Natural;\n\n function Estimate is new Continued_Fraction_Ada95 (Scalar, A, B);\n end Pi;\n\n package body Pi is\n function A (N : in Natural) return Natural is\n begin\n if N = 0 then\n return 3;\n else\n return 6;\n end if;\n end A;\n\n function B (N : in Positive) return Natural is\n begin\n return (2 * N - 1) ** 2;\n end B;\n end Pi;\n\n package Scalar_Text_IO is new Ada.Text_IO.Float_IO (Scalar);\n use Ada.Text_IO, Scalar_Text_IO;\nbegin\n Put (Square_Root_Of_2.Estimate (200), Exp => 0); New_Line;\n Put (Napiers_Constant.Estimate (200), Exp => 0); New_Line;\n Put (Pi.Estimate (10000), Exp => 0); New_Line;\nend Test_Continued_Fractions_Ada95;\n", "language": "Ada" }, { "code": "PROC cf = (INT steps, PROC (INT) INT a, PROC (INT) INT b) REAL:\nBEGIN\n REAL result;\n result := 0;\n FOR n FROM steps BY -1 TO 1 DO\n result := b(n) / (a(n) + result)\n OD;\n a(0) + result\nEND;\n\nPROC asqr2 = (INT n) INT: (n = 0 | 1 | 2);\nPROC bsqr2 = (INT n) INT: 1;\n\nPROC anap = (INT n) INT: (n = 0 | 2 | n);\nPROC bnap = (INT n) INT: (n = 1 | 1 | n - 1);\n\nPROC api = (INT n) INT: (n = 0 | 3 | 6);\nPROC bpi = (INT n) INT: (n = 1 | 1 | (2 * n - 1) ** 2);\n\nINT precision = 10000;\n\nprint ((\"Precision: \", precision, newline));\nprint ((\"Sqr(2): \", cf(precision, asqr2, bsqr2), newline));\nprint ((\"Napier: \", cf(precision, anap, bnap), newline));\nprint ((\"Pi: \", cf(precision, api, bpi)))\n", "language": "ALGOL-68" }, { "code": "calc: function [f, n][\n [a, b, temp]: 0.0\n\n loop n..1 'i [\n [a, b]: call f @[i]\n temp: b // a + temp\n ]\n [a, b]: call f @[0]\n return a + temp\n]\n\nsqrt2: function [n][\n (n > 0)? -> [2.0, 1.0] -> [1.0, 1.0]\n]\n\nnapier: function [n][\n a: (n > 0)? -> to :floating n -> 2.0\n b: (n > 1)? -> to :floating n-1 -> 1.0\n @[a, b]\n]\n\nPi: function [n][\n a: (n > 0)? -> 6.0 -> 3.0\n b: ((2 * to :floating n)-1) ^ 2\n @[a, b]\n]\n\nprint calc 'sqrt2 20\nprint calc 'napier 15\nprint calc 'Pi 10000\n", "language": "Arturo" }, { "code": "#include\n\"share/atspre_staload.hats\"\n//\n(* ****** ****** *)\n//\n(*\n** a coefficient function creates double values from in paramters\n*)\ntypedef coeff_f = int -> double\n//\n(*\n** a continued fraction is described by a record of two coefficent\n** functions a and b\n*)\ntypedef frac = @{a= coeff_f, b= coeff_f}\n//\n(* ****** ****** *)\n\nfun calc\n(\n f: frac, n: int\n) : double = let\n//\n(*\n** recursive definition of the approximation\n*)\nfun loop\n(\n n: int, r: double\n) : double =\n(\nif n = 0\n then f.a(0) + r\n else loop (n - 1, f.b(n) / (f.a(n) + r))\n// end of [if]\n)\n//\nin\n loop (n, 0.0)\nend // end of [calc]\n\n(* ****** ****** *)\n\nval sqrt2 = @{\n a= lam (n: int): double => if n = 0 then 1.0 else 2.0\n,\n b= lam (n: int): double => 1.0\n} (* end of [val] *)\n\nval napier = @{\n a= lam (n: int): double => if n = 0 then 2.0 else 1.0 * n\n,\n b= lam (n: int): double => if n = 1 then 1.0 else n - 1.0\n} (* end of [val] *)\n\nval pi = @{\n a= lam (n: int): double => if n = 0 then 3.0 else 6.0\n,\n b= lam (n: int): double => let val x = 2.0 * n - 1 in x * x end\n}\n\n(* ****** ****** *)\n\nimplement\nmain0 () =\n(\n println! (\"sqrt2 = \", calc(sqrt2, 100));\n println! (\"napier = \", calc(napier, 100));\n println! (\" pi = \", calc( pi , 100));\n) (* end of [main0] *)\n", "language": "ATS" }, { "code": "sqrt2_a(n) ; function definition is as simple as that\n{\nreturn n?2.0:1.0\n}\n\nsqrt2_b(n)\n{\nreturn 1.0\n}\n\nnapier_a(n)\n{\nreturn n?n:2.0\n}\n\nnapier_b(n)\n{\nreturn n>1.0?n-1.0:1.0\n}\n\npi_a(n)\n{\nreturn n?6.0:3.0\n}\n\npi_b(n)\n{\nreturn (2.0*n-1.0)**2.0 ; exponentiation operator\n}\n\ncalc(f,expansions)\n{\nr:=0,i:=expansions\n; A nasty trick: the names of the two coefficient functions are generated dynamically\n; a dot surrounded by spaces means string concatenation\nf_a:=f . \"_a\",f_b:=f . \"_b\"\n\nwhile i>0 {\n; You can see two dynamic function calls here\nr:=%f_b%(i)/(%f_a%(i)+r)\ni--\n}\n\nreturn %f_a%(0)+r\n}\n\nMsgbox, % \"sqrt 2 = \" . calc(\"sqrt2\", 1000) . \"`ne = \" . calc(\"napier\", 1000) . \"`npi = \" . calc(\"pi\", 1000)\n", "language": "AutoHotkey" }, { "code": "sqrt 2 = 1.414214\ne = 2.718282\npi = 3.141593\n", "language": "AutoHotkey" }, { "code": "sqrt 2 = 1.4142135623730951\ne = 2.7182818284590455\npi = 3.1415926533405418\n", "language": "AutoHotkey" }, { "code": "get(obj) == convergents(obj).1000 -- utility to extract the 1000th value\nget continuedFraction(1, repeating [1], repeating [2]) :: Float\nget continuedFraction(2, cons(1,[i for i in 1..]), [i for i in 1..]) :: Float\nget continuedFraction(3, [i^2 for i in 1.. by 2], repeating [6]) :: Float\n", "language": "Axiom" }, { "code": " (1) 1.4142135623 730950488\n Type: Float\n\n (2) 2.7182818284 590452354\n Type: Float\n\n (3) 3.1415926538 39792926\n Type: Float\n", "language": "Axiom" }, { "code": "cf(initial, a, b, n) ==\n n=1 => initial\n temp := 0\n for i in (n-1)..1 by -1 repeat\n temp := a.i/(b.i+temp)\n initial+temp\ncf(1, repeating [1], repeating [2], 1000) :: Float\ncf(2, cons(1,[i for i in 1..]), [i for i in 1..], 1000) :: Float\ncf(3, [i^2 for i in 1.. by 2], repeating [6], 1000) :: Float\n", "language": "Axiom" }, { "code": " *FLOAT64\n @% = &1001010\n\n PRINT \"SQR(2) = \" ; FNcontfrac(1, 1, \"2\", \"1\")\n PRINT \" e = \" ; FNcontfrac(2, 1, \"N\", \"N\")\n PRINT \" PI = \" ; FNcontfrac(3, 1, \"6\", \"(2*N+1)^2\")\n END\n\n REM a$ and b$ are functions of N\n DEF FNcontfrac(a0, b1, a$, b$)\n LOCAL N, expr$\n REPEAT\n N += 1\n expr$ += STR$(EVAL(a$)) + \"+\" + STR$(EVAL(b$)) + \"/(\"\n UNTIL LEN(expr$) > (65500 - N)\n = a0 + b1 / EVAL (expr$ + \"1\" + STRING$(N, \")\"))\n", "language": "BBC-BASIC" }, { "code": "/* calculate approximations for continued fractions */\n#include <stdio.h>\n\n/* kind of function that returns a series of coefficients */\ntypedef double (*coeff_func)(unsigned n);\n\n/* calculates the specified number of expansions of the continued fraction\n * described by the coefficient series f_a and f_b */\ndouble calc(coeff_func f_a, coeff_func f_b, unsigned expansions)\n{\n\tdouble a, b, r;\n\ta = b = r = 0.0;\n\n\tunsigned i;\n\tfor (i = expansions; i > 0; i--) {\n\t\ta = f_a(i);\n\t\tb = f_b(i);\n\t\tr = b / (a + r);\n\t}\n\ta = f_a(0);\n\n\treturn a + r;\n}\n\n/* series for sqrt(2) */\ndouble sqrt2_a(unsigned n)\n{\n\treturn n ? 2.0 : 1.0;\n}\n\ndouble sqrt2_b(unsigned n)\n{\n\treturn 1.0;\n}\n\n/* series for the napier constant */\ndouble napier_a(unsigned n)\n{\n\treturn n ? n : 2.0;\n}\n\ndouble napier_b(unsigned n)\n{\n\treturn n > 1.0 ? n - 1.0 : 1.0;\n}\n\n/* series for pi */\ndouble pi_a(unsigned n)\n{\n\treturn n ? 6.0 : 3.0;\n}\n\ndouble pi_b(unsigned n)\n{\n\tdouble c = 2.0 * n - 1.0;\n\n\treturn c * c;\n}\n\nint main(void)\n{\n\tdouble sqrt2, napier, pi;\n\n\tsqrt2 = calc(sqrt2_a, sqrt2_b, 1000);\n\tnapier = calc(napier_a, napier_b, 1000);\n\tpi = calc(pi_a, pi_b, 1000);\n\n\tprintf(\"%12.10g\\n%12.10g\\n%12.10g\\n\", sqrt2, napier, pi);\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\ntypedef std::tuple<double,double> coeff_t; // coefficients type\ntypedef coeff_t (*func_t)(int); // callback function type\n\ndouble calc(func_t func, int n)\n{\n double a, b, temp = 0;\n for (; n > 0; --n) {\n std::tie(a, b) = func(n);\n temp = b / (a + temp);\n }\n std::tie(a, b) = func(0);\n return a + temp;\n}\n\ncoeff_t sqrt2(int n)\n{\n return coeff_t(n > 0 ? 2 : 1, 1);\n}\n\ncoeff_t napier(int n)\n{\n return coeff_t(n > 0 ? n : 2, n > 1 ? n - 1 : 1);\n}\n\ncoeff_t pi(int n)\n{\n return coeff_t(n > 0 ? 6 : 3, (2 * n - 1) * (2 * n - 1));\n}\n\nint main()\n{\n std::streamsize old_prec = std::cout.precision(15); // set output digits\n std::cout\n << calc(sqrt2, 20) << '\\n'\n << calc(napier, 15) << '\\n'\n << calc(pi, 10000) << '\\n'\n << std::setprecision(old_prec); // reset precision\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\n\nnamespace ContinuedFraction {\n class Program {\n static double Calc(Func<int, int[]> f, int n) {\n double temp = 0.0;\n for (int ni = n; ni >= 1; ni--) {\n int[] p = f(ni);\n temp = p[1] / (p[0] + temp);\n }\n return f(0)[0] + temp;\n }\n\n static void Main(string[] args) {\n List<Func<int, int[]>> fList = new List<Func<int, int[]>>();\n fList.Add(n => new int[] { n > 0 ? 2 : 1, 1 });\n fList.Add(n => new int[] { n > 0 ? n : 2, n > 1 ? (n - 1) : 1 });\n fList.Add(n => new int[] { n > 0 ? 6 : 3, (int) Math.Pow(2 * n - 1, 2) });\n\n foreach (var f in fList) {\n Console.WriteLine(Calc(f, 200));\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "proc calc(f, n) {\n var r = 0.0;\n\n for k in 1..n by -1 {\n var v = f.pair(k);\n r = v(2) / (v(1) + r);\n }\n\n return f.pair(0)(1) + r;\n}\n\nrecord Sqrt2 {\n proc pair(n) {\n return (if n == 0 then 1 else 2,\n 1);\n }\n}\n\nrecord Napier {\n proc pair(n) {\n return (if n == 0 then 2 else n,\n if n == 1 then 1 else n - 1);\n }\n}\nrecord Pi {\n proc pair(n) {\n return (if n == 0 then 3 else 6,\n (2*n - 1)**2);\n }\n}\n\nconfig const n = 200;\nwriteln(calc(new Sqrt2(), n));\nwriteln(calc(new Napier(), n));\nwriteln(calc(new Pi(), n));\n", "language": "Chapel" }, { "code": "(defn cfrac\n [a b n]\n (letfn [(cfrac-iter [[x k]] [(+ (a k) (/ (b (inc k)) x)) (dec k)])]\n (ffirst (take 1 (drop (inc n) (iterate cfrac-iter [1 n]))))))\n\n(def sq2 (cfrac #(if (zero? %) 1.0 2.0) (constantly 1.0) 100))\n(def e (cfrac #(if (zero? %) 2.0 %) #(if (= 1 %) 1.0 (double (dec %))) 100))\n(def pi (cfrac #(if (zero? %) 3.0 6.0) #(let [x (- (* 2.0 %) 1.0)] (* x x)) 900000))\n", "language": "Clojure" }, { "code": " identification division.\n program-id. show-continued-fractions.\n\n environment division.\n configuration section.\n repository.\n function continued-fractions\n function all intrinsic.\n\n procedure division.\n fractions-main.\n\n display \"Square root 2 approximately : \"\n continued-fractions(\"sqrt-2-alpha\", \"sqrt-2-beta\", 100)\n display \"Napier constant approximately : \"\n continued-fractions(\"napier-alpha\", \"napier-beta\", 40)\n display \"Pi approximately : \"\n continued-fractions(\"pi-alpha\", \"pi-beta\", 10000)\n\n goback.\n end program show-continued-fractions.\n\n *> **************************************************************\n identification division.\n function-id. continued-fractions.\n\n data division.\n working-storage section.\n 01 alpha-function usage program-pointer.\n 01 beta-function usage program-pointer.\n 01 alpha usage float-long.\n 01 beta usage float-long.\n 01 running usage float-long.\n 01 i usage binary-long.\n\n linkage section.\n 01 alpha-name pic x any length.\n 01 beta-name pic x any length.\n 01 iterations pic 9 any length.\n 01 approximation usage float-long.\n\n procedure division using\n alpha-name beta-name iterations\n returning approximation.\n\n set alpha-function to entry alpha-name\n if alpha-function = null then\n display \"error: no \" alpha-name \" function\" upon syserr\n goback\n end-if\n set beta-function to entry beta-name\n if beta-function = null then\n display \"error: no \" beta-name \" function\" upon syserr\n goback\n end-if\n\n move 0 to alpha beta running\n perform varying i from iterations by -1 until i = 0\n call alpha-function using i returning alpha\n call beta-function using i returning beta\n compute running = beta / (alpha + running)\n end-perform\n call alpha-function using 0 returning alpha\n compute approximation = alpha + running\n\n goback.\n end function continued-fractions.\n\n *> ******************************\n identification division.\n program-id. sqrt-2-alpha.\n\n data division.\n working-storage section.\n 01 result usage float-long.\n\n linkage section.\n 01 iteration usage binary-long unsigned.\n\n procedure division using iteration returning result.\n if iteration equal 0 then\n move 1.0 to result\n else\n move 2.0 to result\n end-if\n\n goback.\n end program sqrt-2-alpha.\n\n *> ******************************\n identification division.\n program-id. sqrt-2-beta.\n\n data division.\n working-storage section.\n 01 result usage float-long.\n\n linkage section.\n 01 iteration usage binary-long unsigned.\n\n procedure division using iteration returning result.\n move 1.0 to result\n\n goback.\n end program sqrt-2-beta.\n\n *> ******************************\n identification division.\n program-id. napier-alpha.\n\n data division.\n working-storage section.\n 01 result usage float-long.\n\n linkage section.\n 01 iteration usage binary-long unsigned.\n\n procedure division using iteration returning result.\n if iteration equal 0 then\n move 2.0 to result\n else\n move iteration to result\n end-if\n\n goback.\n end program napier-alpha.\n\n *> ******************************\n identification division.\n program-id. napier-beta.\n\n data division.\n working-storage section.\n 01 result usage float-long.\n\n linkage section.\n 01 iteration usage binary-long unsigned.\n\n procedure division using iteration returning result.\n if iteration = 1 then\n move 1.0 to result\n else\n compute result = iteration - 1.0\n end-if\n\n goback.\n end program napier-beta.\n\n *> ******************************\n identification division.\n program-id. pi-alpha.\n\n data division.\n working-storage section.\n 01 result usage float-long.\n\n linkage section.\n 01 iteration usage binary-long unsigned.\n\n procedure division using iteration returning result.\n if iteration equal 0 then\n move 3.0 to result\n else\n move 6.0 to result\n end-if\n\n goback.\n end program pi-alpha.\n\n *> ******************************\n identification division.\n program-id. pi-beta.\n\n data division.\n working-storage section.\n 01 result usage float-long.\n\n linkage section.\n 01 iteration usage binary-long unsigned.\n\n procedure division using iteration returning result.\n compute result = (2 * iteration - 1) ** 2\n\n goback.\n end program pi-beta.\n", "language": "COBOL" }, { "code": "# Compute a continuous fraction of the form\n# a0 + b1 / (a1 + b2 / (a2 + b3 / ...\ncontinuous_fraction = (f) ->\n a = f.a\n b = f.b\n c = 1\n for n in [100000..1]\n c = b(n) / (a(n) + c)\n a(0) + c\n\n# A little helper.\np = (a, b) ->\n console.log a\n console.log b\n console.log \"---\"\n\ndo ->\n fsqrt2 =\n a: (n) -> if n is 0 then 1 else 2\n b: (n) -> 1\n p Math.sqrt(2), continuous_fraction(fsqrt2)\n\n fnapier =\n a: (n) -> if n is 0 then 2 else n\n b: (n) -> if n is 1 then 1 else n - 1\n p Math.E, continuous_fraction(fnapier)\n\n fpi =\n a: (n) ->\n return 3 if n is 0\n 6\n b: (n) ->\n x = 2*n - 1\n x * x\n p Math.PI, continuous_fraction(fpi)\n", "language": "CoffeeScript" }, { "code": "(defun estimate-continued-fraction (generator n)\n (let ((temp 0))\n (loop for n1 from n downto 1\n do (multiple-value-bind (a b)\n\t (funcall generator n1)\n\t (setf temp (/ b (+ a temp)))))\n (+ (funcall generator 0) temp)))\n\n(format t \"sqrt(2) = ~a~%\" (coerce (estimate-continued-fraction\n\t\t\t\t (lambda (n)\n\t\t\t\t (values (if (> n 0) 2 1) 1)) 20)\n\t\t\t\t 'double-float))\n(format t \"napier's = ~a~%\" (coerce (estimate-continued-fraction\n\t\t\t\t (lambda (n)\n\t\t\t\t (values (if (> n 0) n 2)\n\t\t\t\t\t (if (> n 1) (1- n) 1))) 15)\n\t\t\t\t 'double-float))\n\n(format t \"pi = ~a~%\" (coerce (estimate-continued-fraction\n\t\t\t (lambda (n)\n\t\t\t\t (values (if (> n 0) 6 3)\n\t\t\t\t\t (* (1- (* 2 n))\n\t\t\t\t\t (1- (* 2 n))))) 10000)\n\t\t\t 'double-float))\n", "language": "Common-Lisp" }, { "code": "import std.stdio, std.functional, std.traits;\n\nFP calc(FP, F)(in F fun, in int n) pure nothrow if (isCallable!F) {\n FP temp = 0;\n\n foreach_reverse (immutable ni; 1 .. n + 1) {\n immutable p = fun(ni);\n temp = p[1] / (FP(p[0]) + temp);\n }\n return fun(0)[0] + temp;\n}\n\nint[2] fSqrt2(in int n) pure nothrow {\n return [n > 0 ? 2 : 1, 1];\n}\n\nint[2] fNapier(in int n) pure nothrow {\n return [n > 0 ? n : 2, n > 1 ? (n - 1) : 1];\n}\n\nint[2] fPi(in int n) pure nothrow {\n return [n > 0 ? 6 : 3, (2 * n - 1) ^^ 2];\n}\n\nalias print = curry!(writefln, \"%.19f\");\n\nvoid main() {\n calc!real(&fSqrt2, 200).print;\n calc!real(&fNapier, 200).print;\n calc!real(&fPi, 200).print;\n}\n", "language": "D" }, { "code": "[20k 0 200 si [li lbx r li lax + / li 1 - dsi 0<:]ds:x 0 lax +]sf\n\n[[2q]s2[0<2 1]sa[R1]sb]sr # sqrt(2)\n[[R2q]s2[d 0=2]sa[R1q]s1[d 1=1 1-]sb]se # e\n[[3q]s3[0=3 6]sa[2*1-d*]sb]sp # pi\n\nc lex lfx p\nlrx lfx p\nlpx lfx p\n", "language": "Dc" }, { "code": "numfmt 8 0\nfunc calc_sqrt .\n n = 100\n sum = n\n while n >= 1\n a = 1\n if n > 1\n a = 2\n .\n b = 1\n sum = a + b / sum\n n -= 1\n .\n return sum\n.\nfunc calc_e .\n n = 100\n sum = n\n while n >= 1\n a = 2\n if n > 1\n a = n - 1\n .\n b = 1\n if n > 1\n b = n - 1\n .\n sum = a + b / sum\n n -= 1\n .\n return sum\n.\nfunc calc_pi .\n n = 100\n sum = n\n while n >= 1\n a = 3\n if n > 1\n a = 6\n .\n b = 2 * n - 1\n b *= b\n sum = a + b / sum\n n -= 1\n .\n return sum\n.\nprint calc_sqrt\nprint calc_e\nprint calc_pi\n", "language": "EasyLang" }, { "code": "defmodule CFrac do\n def compute([a | _], []), do: a\n def compute([a | as], [b | bs]), do: a + b/compute(as, bs)\n\n def sqrt2 do\n a = [1 | Stream.cycle([2]) |> Enum.take(1000)]\n b = Stream.cycle([1]) |> Enum.take(1000)\n IO.puts compute(a, b)\n end\n\n def exp1 do\n a = [2 | Stream.iterate(1, &(&1 + 1)) |> Enum.take(1000)]\n b = [1 | Stream.iterate(1, &(&1 + 1)) |> Enum.take(999)]\n IO.puts compute(a, b)\n end\n\n def pi do\n a = [3 | Stream.cycle([6]) |> Enum.take(1000)]\n b = 1..1000 |> Enum.map(fn k -> (2*k - 1)**2 end)\n IO.puts compute(a, b)\n end\nend\n", "language": "Elixir" }, { "code": "-module(continued).\n-compile([export_all]).\n\npi_a (0) -> 3;\npi_a (_N) -> 6.\n\npi_b (N) ->\n (2*N-1)*(2*N-1).\n\nsqrt2_a (0) ->\n 1;\nsqrt2_a (_N) ->\n 2.\n\nsqrt2_b (_N) ->\n 1.\n\nnappier_a (0) ->\n 2;\nnappier_a (N) ->\n N.\n\nnappier_b (1) ->\n 1;\nnappier_b (N) ->\n N-1.\n\ncontinued_fraction(FA,_FB,0) -> FA(0);\ncontinued_fraction(FA,FB,N) ->\n continued_fraction(FA,FB,N-1,FB(N)/FA(N)).\n\ncontinued_fraction(FA,_FB,0,Acc) -> FA(0) + Acc;\ncontinued_fraction(FA,FB,N,Acc) ->\n continued_fraction(FA,FB,N-1,FB(N)/ (FA(N) + Acc)).\n\ntest_pi (N) ->\n continued_fraction(fun pi_a/1,fun pi_b/1,N).\n\ntest_sqrt2 (N) ->\n continued_fraction(fun sqrt2_a/1,fun sqrt2_b/1,N).\n\ntest_nappier (N) ->\n continued_fraction(fun nappier_a/1,fun nappier_b/1,N).\n", "language": "Erlang" }, { "code": "29> continued:test_pi(1000).\n3.141592653340542\n30> continued:test_sqrt2(1000).\n1.4142135623730951\n31> continued:test_nappier(1000).\n2.7182818284590455\n", "language": "Erlang" }, { "code": "// I provide four functions:-\n// cf2S general purpose continued fraction to sequence of float approximations\n// cN2S Normal continued fractions (a-series always 1)\n// cfSqRt uses cf2S to calculate sqrt of float\n// π takes a sequence of b values returning the next until the list is exhausted after which it injects infinity\n// Nigel Galloway: December 19th., 2018\nlet cf2S α β=let n0,g1,n1,g2=β(),α(),β(),β()\n seq{let (Π:decimal)=g1/n1 in yield n0+Π; yield! Seq.unfold(fun(n,g,Π)->let a,b=α(),β() in let Π=Π*g/n in Some(n0+Π,(b+a/n,b+a/g,Π)))(g2+α()/n1,g2,Π)}\nlet cN2S = cf2S (fun()->1M)\nlet cfSqRt n=(cf2S (fun()->n-1M) (let mutable n=false in fun()->if n then 2M else (n<-true; 1M)))\nlet π n=let mutable π=n in (fun ()->match π with h::t->π<-t; h |_->9999999999999999999999999999M)\n", "language": "F-Sharp" }, { "code": "cfSqRt 2M |> Seq.take 10 |> Seq.pairwise |> Seq.iter(fun(n,g)->printfn \"%1.14f < √2 < %1.14f\" (min n g) (max n g))\n", "language": "F-Sharp" }, { "code": "cfSqRt 0.25M |> Seq.take 30 |> Seq.iter (printfn \"%1.14f\")\n", "language": "F-Sharp" }, { "code": "let aπ()=let mutable n=0M in (fun ()->n<-n+1M;let b=n+n-1M in b*b)\nlet bπ()=let mutable n=true in (fun ()->match n with true->n<-false;3M |_->6M)\ncf2S (aπ()) (bπ()) |> Seq.take 10 |> Seq.pairwise |> Seq.iter(fun(n,g)->printfn \"%1.14f < π < %1.14f\" (min n g) (max n g))\n", "language": "F-Sharp" }, { "code": "let pi = π [3M;7M;15M;1M;292M;1M;1M;1M;2M;1M;3M;1M;14M;2M;1M;1M;2M;2M;2M;2M]\ncN2S pi |> Seq.take 10 |> Seq.pairwise |> Seq.iter(fun(n,g)->printfn \"%1.14f < π < %1.14f\" (min n g) (max n g))\n", "language": "F-Sharp" }, { "code": "let ae()=let mutable n=0.5M in (fun ()->match n with 0.5M->n<-0M; 1M |_->n<-n+1M; n)\nlet be()=let mutable n=0.5M in (fun ()->match n with 0.5M->n<-0M; 2M |_->n<-n+1M; n)\ncf2S (ae()) (be()) |> Seq.take 10 |> Seq.pairwise |> Seq.iter(fun(n,g)->printfn \"%1.14f < e < %1.14f\" (min n g) (max n g))\n", "language": "F-Sharp" }, { "code": "let aπ()=let mutable n=0 in (fun ()->n<-n+1;-decimal(pown n 6))\nlet bπ()=let mutable n=0M in (fun ()->n<-n+1M; (2M*n-1M)*(17M*n*n-17M*n+5M))\ncf2S (aπ()) (bπ()) |>Seq.map(fun n->6M/n) |> Seq.take 10 |> Seq.pairwise |> Seq.iter(fun(n,g)->printfn \"%1.20f < p < %- 1.20f\" (min n g) (max n g));;\n", "language": "F-Sharp" }, { "code": "USING: arrays combinators io kernel locals math math.functions\n math.ranges prettyprint sequences ;\nIN: rosetta.cfrac\n\n! Every continued fraction must implement these two words.\nGENERIC: cfrac-a ( n cfrac -- a )\nGENERIC: cfrac-b ( n cfrac -- b )\n\n! square root of 2\nSINGLETON: sqrt2\nM: sqrt2 cfrac-a\n ! If n is 1, then a_n is 1, else a_n is 2.\n drop { { 1 [ 1 ] } [ drop 2 ] } case ;\nM: sqrt2 cfrac-b\n ! Always b_n is 1.\n 2drop 1 ;\n\n! Napier's constant\nSINGLETON: napier\nM: napier cfrac-a\n ! If n is 1, then a_n is 2, else a_n is n - 1.\n drop { { 1 [ 2 ] } [ 1 - ] } case ;\nM: napier cfrac-b\n ! If n is 1, then b_n is 1, else b_n is n - 1.\n drop { { 1 [ 1 ] } [ 1 - ] } case ;\n\nSINGLETON: pi\nM: pi cfrac-a\n ! If n is 1, then a_n is 3, else a_n is 6.\n drop { { 1 [ 3 ] } [ drop 6 ] } case ;\nM: pi cfrac-b\n ! Always b_n is (n * 2 - 1)^2.\n drop 2 * 1 - 2 ^ ;\n\n:: cfrac-estimate ( cfrac terms -- number )\n terms cfrac cfrac-a ! top = last a_n\n terms 1 - 1 [a,b] [ :> n\n n cfrac cfrac-b swap / ! top = b_n / top\n n cfrac cfrac-a + ! top = top + a_n\n ] each ;\n\n:: decimalize ( rational prec -- string )\n rational 1 /mod ! split whole, fractional parts\n prec 10^ * ! multiply fraction by 10 ^ prec\n [ >integer unparse ] bi@ ! convert digits to strings\n :> fraction\n \".\" ! push decimal point\n prec fraction length -\n dup 0 < [ drop 0 ] when\n \"0\" <repetition> concat ! push padding zeros\n fraction 4array concat ;\n\n<PRIVATE\n: main ( -- )\n \" Square root of 2: \" write\n sqrt2 50 cfrac-estimate 30 decimalize print\n \"Napier's constant: \" write\n napier 50 cfrac-estimate 30 decimalize print\n \" Pi: \" write\n pi 950 cfrac-estimate 10 decimalize print ;\nPRIVATE>\n\nMAIN: main\n", "language": "Factor" }, { "code": "fun pi (n:int) : (double*double) =>\n let a = match n with | 0 => 3.0 | _ => 6.0 endmatch in\n let b = pow(2.0 * n.double - 1.0, 2.0) in\n (a,b);\n\nfun sqrt_2 (n:int) : (double*double) =>\n let a = match n with | 0 => 1.0 | _ => 2.0 endmatch in\n let b = 1.0 in\n (a,b);\n\nfun napier (n:int) : (double*double) =>\n let a = match n with | 0 => 2.0 | _ => n.double endmatch in\n let b = match n with | 1 => 1.0 | _ => (n.double - 1.0) endmatch in\n (a,b);\n\nfun cf_iter (steps:int) (f:int -> double*double) = {\n var acc = 0.0;\n for var n in steps downto 0 do\n var a, b = f(n);\n acc = if (n > 0) then (b / (a + acc)) else (acc + a);\n done\n return acc;\n}\n\nprintln$ cf_iter 200 sqrt_2; // => 1.41421\nprintln$ cf_iter 200 napier; // => 2.71818\nprintln$ cf_iter 1000 pi; // => 3.14159\n", "language": "Felix" }, { "code": ": fsqrt2 1 s>f 0> if 2 s>f else fdup then ;\n: fnapier dup dup 1 > if 1- else drop 1 then s>f dup 1 < if drop 2 then s>f ;\n: fpi dup 2* 1- dup * s>f 0> if 6 else 3 then s>f ;\n ( n -- f1 f2)\n: cont.fraction ( xt n -- f)\n 1 swap 1+ 0 s>f \\ calculate for 1 .. n\n do i over execute frot f+ f/ -1 +loop\n 0 swap execute fnip f+ \\ calcucate for 0\n;\n", "language": "Forth" }, { "code": "module continued_fractions\n implicit none\n\n integer, parameter :: long = selected_real_kind(7,99)\n\n type continued_fraction\n integer :: a0, b1\n procedure(series), pointer, nopass :: a, b\n end type\n\n interface\n pure function series (n)\n integer, intent(in) :: n\n integer :: series\n end function\n end interface\n\ncontains\n\n pure function define_cf (a0,a,b1,b) result(x)\n integer, intent(in) :: a0\n procedure(series) :: a\n integer, intent(in), optional :: b1\n procedure(series), optional :: b\n type(continued_fraction) :: x\n x%a0 = a0\n x%a => a\n if ( present(b1) ) then\n x%b1 = b1\n else\n x%b1 = 1\n end if\n if ( present(b) ) then\n x%b => b\n else\n x%b => const_1\n end if\n end function define_cf\n\n pure integer function const_1(n)\n integer,intent(in) :: n\n const_1 = 1\n end function\n\n pure real(kind=long) function output(x,iterations)\n type(continued_fraction), intent(in) :: x\n integer, intent(in) :: iterations\n integer :: i\n output = x%a(iterations)\n do i = iterations-1,1,-1\n output = x%a(i) + (x%b(i+1) / output)\n end do\n output = x%a0 + (x%b1 / output)\n end function output\n\nend module continued_fractions\n\n\nprogram examples\n use continued_fractions\n\n type(continued_fraction) :: sqr2,napier,pi\n\n sqr2 = define_cf(1,a_sqr2)\n napier = define_cf(2,a_napier,1,b_napier)\n pi = define_cf(3,a=a_pi,b=b_pi)\n\n write (*,*) output(sqr2,10000)\n write (*,*) output(napier,10000)\n write (*,*) output(pi,10000)\n\ncontains\n\n pure integer function a_sqr2(n)\n integer,intent(in) :: n\n a_sqr2 = 2\n end function\n\n pure integer function a_napier(n)\n integer,intent(in) :: n\n a_napier = n\n end function\n\n pure integer function b_napier(n)\n integer,intent(in) :: n\n b_napier = n-1\n end function\n\n pure integer function a_pi(n)\n integer,intent(in) :: n\n a_pi = 6\n end function\n\n pure integer function b_pi(n)\n integer,intent(in) :: n\n b_pi = (2*n-1)*(2*n-1)\n end function\n\nend program examples\n", "language": "Fortran" }, { "code": "#define MAX 70000\n\nfunction sqrt2_a( n as uinteger ) as uinteger\n return iif(n,2,1)\nend function\n\nfunction sqrt2_b( n as uinteger ) as uinteger\n return 1\nend function\n\nfunction napi_a( n as uinteger ) as uinteger\n return iif(n,n,2)\nend function\n\nfunction napi_b( n as uinteger ) as uinteger\n return iif(n>1,n-1,1)\nend function\n\nfunction pi_a( n as uinteger ) as uinteger\n return iif(n,6,3)\nend function\n\nfunction pi_b( n as uinteger ) as uinteger\n return (2*n-1)^2\nend function\n\nfunction calc_contfrac( an as function (as uinteger) as uinteger, bn as function (as uinteger) as uinteger, byval iter as uinteger ) as double\n dim as double r\n dim as integer i\n for i = iter to 1 step -1\n r = bn(i)/(an(i)+r)\n next i\n return an(0)+r\nend function\n\nprint calc_contfrac( @sqrt2_a, @sqrt2_b, MAX )\nprint calc_contfrac( @napi_a, @napi_b, MAX )\nprint calc_contfrac( @pi_a, @pi_b, MAX )\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport \"fmt\"\n\ntype cfTerm struct {\n a, b int\n}\n\n// follows subscript convention of mathworld and WP where there is no b(0).\n// cf[0].b is unused in this representation.\ntype cf []cfTerm\n\nfunc cfSqrt2(nTerms int) cf {\n f := make(cf, nTerms)\n for n := range f {\n f[n] = cfTerm{2, 1}\n }\n f[0].a = 1\n return f\n}\n\nfunc cfNap(nTerms int) cf {\n f := make(cf, nTerms)\n for n := range f {\n f[n] = cfTerm{n, n - 1}\n }\n f[0].a = 2\n f[1].b = 1\n return f\n}\n\nfunc cfPi(nTerms int) cf {\n f := make(cf, nTerms)\n for n := range f {\n g := 2*n - 1\n f[n] = cfTerm{6, g * g}\n }\n f[0].a = 3\n return f\n}\n\nfunc (f cf) real() (r float64) {\n for n := len(f) - 1; n > 0; n-- {\n r = float64(f[n].b) / (float64(f[n].a) + r)\n }\n return r + float64(f[0].a)\n}\n\nfunc main() {\n fmt.Println(\"sqrt2:\", cfSqrt2(20).real())\n fmt.Println(\"nap: \", cfNap(20).real())\n fmt.Println(\"pi: \", cfPi(20).real())\n}\n", "language": "Go" }, { "code": "import java.util.function.Function\n\nimport static java.lang.Math.pow\n\nclass Test {\n static double calc(Function<Integer, Integer[]> f, int n) {\n double temp = 0\n\n for (int ni = n; ni >= 1; ni--) {\n Integer[] p = f.apply(ni)\n temp = p[1] / (double) (p[0] + temp)\n }\n return f.apply(0)[0] + temp\n }\n\n static void main(String[] args) {\n List<Function<Integer, Integer[]>> fList = new ArrayList<>()\n fList.add({ n -> [n > 0 ? 2 : 1, 1] })\n fList.add({ n -> [n > 0 ? n : 2, n > 1 ? (n - 1) : 1] })\n fList.add({ n -> [n > 0 ? 6 : 3, (int) pow(2 * n - 1, 2)] })\n\n for (Function<Integer, Integer[]> f : fList)\n System.out.println(calc(f, 200))\n }\n}\n", "language": "Groovy" }, { "code": "import Data.List (unfoldr)\nimport Data.Char (intToDigit)\n\n-- continued fraction represented as a (possibly infinite) list of pairs\nsqrt2, napier, myPi :: [(Integer, Integer)]\nsqrt2 = zip (1 : [2,2 ..]) [1,1 ..]\n\nnapier = zip (2 : [1 ..]) (1 : [1 ..])\n\nmyPi = zip (3 : [6,6 ..]) ((^ 2) <$> [1,3 ..])\n\n-- approximate a continued fraction after certain number of iterations\napproxCF\n :: (Integral a, Fractional b)\n => Int -> [(a, a)] -> b\napproxCF t = foldr (\\(a, b) z -> fromIntegral a + fromIntegral b / z) 1 . take t\n\n-- infinite decimal representation of a real number\ndecString\n :: RealFrac a\n => a -> String\ndecString frac = show i ++ '.' : decString_ f\n where\n (i, f) = properFraction frac\n decString_ = map intToDigit . unfoldr (Just . properFraction . (10 *))\n\nmain :: IO ()\nmain =\n mapM_\n (putStrLn .\n take 200 . decString . (approxCF 950 :: [(Integer, Integer)] -> Rational))\n [sqrt2, napier, myPi]\n", "language": "Haskell" }, { "code": "import Data.Ratio ((%), denominator, numerator)\nimport Data.Bool (bool)\n\n-- ignoring the task-given pi sequence: sucky convergence\n-- pie = zip (3:repeat 6) (map (^2) [1,3..])\npie = zip (0 : [1,3 ..]) (4 : map (^ 2) [1 ..])\n\nsqrt2 = zip (1 : repeat 2) (repeat 1)\n\nnapier = zip (2 : [1 ..]) (1 : [1 ..])\n\n-- truncate after n terms\ncf2rat n = foldr (\\(a, b) f -> (a % 1) + ((b % 1) / f)) (1 % 1) . take n\n\n-- truncate after error is at most 1/p\ncf2rat_p p s = f $ map ((\\i -> (cf2rat i s, cf2rat (1 + i) s)) . (2 ^)) [0 ..]\n where\n f ((x, y):ys)\n | abs (x - y) < (1 / fromIntegral p) = x\n | otherwise = f ys\n\n-- returns a decimal string of n digits after the dot; all digits should\n-- be correct (doesn't mean it's the best approximation! the decimal\n-- string is simply truncated to given digits: pi=3.141 instead of 3.142)\ncf2dec n = ratstr n . cf2rat_p (10 ^ n)\n where\n ratstr l a = show t ++ '.' : fracstr l n d\n where\n d = denominator a\n (t, n) = quotRem (numerator a) d\n fracstr 0 _ _ = []\n fracstr l n d = show t ++ fracstr (l - 1) n1 d\n where\n (t, n1) = quotRem (10 * n) d\n\nmain :: IO ()\nmain = mapM_ putStrLn [cf2dec 200 sqrt2, cf2dec 200 napier, cf2dec 200 pie]\n", "language": "Haskell" }, { "code": "$define EVAL_DEPTH 100\n\n# A generalized continued fraction, represented by two functions. Each\n# function maps from an index to a floating-point value.\nrecord continued_fraction (a, b)\n\nprocedure main ()\n writes (\" sqrt 2.0 = \")\n write (evaluate_continued_fraction (continued_fraction (sqrt2_a, sqrt2_b),\n EVAL_DEPTH))\n writes (\" e = \")\n write (evaluate_continued_fraction (continued_fraction (e_a, e_b),\n EVAL_DEPTH))\n writes (\" pi = \")\n write (evaluate_continued_fraction (continued_fraction (pi_a, pi_b),\n EVAL_DEPTH))\nend\n\nprocedure evaluate_continued_fraction (frac, depth)\n local i, retval\n retval := frac.a (depth)\n every i := depth to 1 by -1 do {\n retval := frac.a (i - 1) + (frac.b (i) / retval)\n }\n return retval\nend\n\nprocedure sqrt2_a (i)\n return (if i = 0 then 1.0 else 2.0)\nend\n\nprocedure sqrt2_b (i)\n return 1.0\nend\n\nprocedure e_a (i)\n return (if i = 0 then 2.0 else real (i))\nend\n\nprocedure e_b (i)\n return (if i = 1 then 1.0 else real (i - 1))\nend\n\nprocedure pi_a (i)\n return (if i = 0 then 3.0 else 6.0)\nend\n\nprocedure pi_b (i)\n return real (((2 * i) - 1)^2)\nend\n", "language": "Icon" }, { "code": " cfrac=: +`% / NB. Evaluate a list as a continued fraction\n\n sqrt2=: cfrac 1 1,200$2 1x\n pi=:cfrac 3, , ,&6\"0 *:<:+:>:i.100x\n e=: cfrac 2 1, , ,~\"0 >:i.100x\n\n NB. translate from fraction to decimal string\n NB. translated from factor\n dec =: (-@:[ (}.,'.',{.) \":@:<.@:(* 10x&^)~)\"0\n\n 100 10 100 dec sqrt2, pi, e\n1.4142135623730950488016887242096980785696718753769480731766797379907324784621205551109457595775322165\n3.1415924109\n2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274\n", "language": "J" }, { "code": "import static java.lang.Math.pow;\nimport java.util.*;\nimport java.util.function.Function;\n\npublic class Test {\n static double calc(Function<Integer, Integer[]> f, int n) {\n double temp = 0;\n\n for (int ni = n; ni >= 1; ni--) {\n Integer[] p = f.apply(ni);\n temp = p[1] / (double) (p[0] + temp);\n }\n return f.apply(0)[0] + temp;\n }\n\n public static void main(String[] args) {\n List<Function<Integer, Integer[]>> fList = new ArrayList<>();\n fList.add(n -> new Integer[]{n > 0 ? 2 : 1, 1});\n fList.add(n -> new Integer[]{n > 0 ? n : 2, n > 1 ? (n - 1) : 1});\n fList.add(n -> new Integer[]{n > 0 ? 6 : 3, (int) pow(2 * n - 1, 2)});\n\n for (Function<Integer, Integer[]> f : fList)\n System.out.println(calc(f, 200));\n }\n}\n", "language": "Java" }, { "code": "# \"first\" is the first triple, e.g. [1,a,b];\n# \"count\" specifies the number of terms to use.\ndef continued_fraction( first; next; count ):\n # input: [i, a, b]\n def cf:\n if .[0] == count then 0\n else next as $ab\n | .[1] + (.[2] / ($ab | cf))\n end ;\n first | cf;\n\n# \"first\" and \"next\" are as above;\n# if delta is 0 then continue until there is no detectable change.\ndef continued_fraction_delta(first; next; delta):\n def abs: if . < 0 then -. else . end;\n def cf:\n # state: [n, prev]\n .[0] as $n | .[1] as $prev\n | continued_fraction(first; next; $n+1) as $this\n | if $prev == null then [$n+1, $this] | cf\n elif delta <= 0 and ($prev == $this) then $this\n elif (($prev - $this)|abs) <= delta then $this\n else [$n+1, $this] | cf\n end;\n [2,null] | cf;\n", "language": "Jq" }, { "code": "\"Value : Direct : Continued Fraction\",\n \"2|sqrt : \\(2|sqrt) : \\(continued_fraction_delta( [1,1,1]; [.[0]+1, 2, 1]; 0))\",\n \"1|exp : \\(1|exp) : \\(2 + (1 / (continued_fraction_delta( [1,1,1]; [.[0]+1, .[1]+1, .[2]+1]; 0))))\",\n \"pi : \\(1|atan * 4) : \\(continued_fraction_delta( [1,3,1]; .[0]+1 | [., 6, ((2*. - 1) | (.*.))]; 1e-12)) (1e-12)\"\n", "language": "Jq" }, { "code": "$ jq -M -n -r -f Continued_fraction.jq\nValue : Direct : Continued Fraction\n2|sqrt : 1.4142135623730951 : 1.4142135623730951\n1|exp : 2.718281828459045 : 2.7182818284590455\npi : 3.141592653589793 : 3.1415926535892935 (1e-12)\n", "language": "Jq" }, { "code": "using .Iterators: countfrom, flatten, repeated, zip\nusing .MathConstants: ℯ\nusing Printf\n\nfunction cf(a₀, a, b = repeated(1))\n\tm = BigInt[a₀ 1; 1 0]\n for (aᵢ, bᵢ) ∈ zip(a, b)\n m *= [aᵢ 1; bᵢ 0]\n isapprox(m[1]/m[2], m[3]/m[4]; atol = 1e-12) && break\n end\n\tm[1]/m[2]\nend\n\nout((k, v)) = @printf \"%2s: %.12f ≈ %.12f\\n\" k v eval(k)\n\nforeach(out, (\n :(√2) => cf(1, repeated(2)),\n :ℯ => cf(2, countfrom(), flatten((1, countfrom()))),\n :π => cf(3, repeated(6), (k^2 for k ∈ countfrom(1, 2)))))\n", "language": "Julia" }, { "code": "cf::{[f g i];f::x;g::y;i::z;\n f(0)+z{i::i-1;g(i+1)%f(i+1)+x}:*0}\ncf({:[0=x;1;2]};{x;1};1000)\ncf({:[0=x;2;x]};{:[x>1;x-1;x]};1000)\ncf({:[0=x;3;6]};{((2*x)-1)^2};1000)\n", "language": "Klong" }, { "code": "// version 1.1.2\n\ntypealias Func = (Int) -> IntArray\n\nfun calc(f: Func, n: Int): Double {\n var temp = 0.0\n for (i in n downTo 1) {\n val p = f(i)\n temp = p[1] / (p[0] + temp)\n }\n return f(0)[0] + temp\n}\n\nfun main(args: Array<String>) {\n val pList = listOf<Pair<String, Func>>(\n \"sqrt(2)\" to { n -> intArrayOf(if (n > 0) 2 else 1, 1) },\n \"e \" to { n -> intArrayOf(if (n > 0) n else 2, if (n > 1) n - 1 else 1) },\n \"pi \" to { n -> intArrayOf(if (n > 0) 6 else 3, (2 * n - 1) * (2 * n - 1)) }\n )\n for (pair in pList) println(\"${pair.first} = ${calc(pair.second, 200)}\")\n}\n", "language": "Kotlin" }, { "code": "{def gcf\n {def gcf.rec\n {lambda {:f :n :r}\n {if {< :n 1}\n then {+ {car {:f 0}} :r}\n else {gcf.rec :f\n {- :n 1}\n {let { {:r :r}\n {:ab {:f :n}}\n } {/ {cdr :ab}\n {+ {car :ab} :r}} }}}}}\n {lambda {:f :n}\n {gcf.rec :f :n 0}}}\n\n{def phi\n {lambda {:n}\n {cons 1 1}}}\n\n{gcf phi 50}\n-> 1.618033988749895\n\n{def sqrt2\n {lambda {:n}\n {cons {if {> :n 0} then 2 else 1} 1}}}\n\n{gcf sqrt2 25}\n-> 1.4142135623730951\n\n{def napier\n {lambda {:n}\n {cons {if {> :n 0} then :n else 2} {if {> :n 1} then {- :n 1} else 1} }}}\n\n{gcf napier 20}\n-> 2.7182818284590455\n\n{def fpi\n {lambda {:n}\n {cons {if {> :n 0} then 6 else 3} {pow {- {* 2 :n} 1} 2} }}}\n\n{gcf fpi 500}\n-> 3.1415926 516017554\n// only 8 exact decimals for 500 iterations\n// A very very slow convergence.\n// Here is a quicker version without any obvious pattern\n\n{def pi\n {lambda {:n}\n {cons {A.get :n {A.new 3 7 15 1 292 1 1 1 2 1 3 1 14 2 1 1}} 1}}}\n\n{gcf pi 15}\n-> 3.1415926 53589793\n\n// Much quicker, 15 exact decimals after 15 iterations\n", "language": "Lambdatalk" }, { "code": "function calc(fa, fb, expansions)\n local a = 0.0\n local b = 0.0\n local r = 0.0\n local i = expansions\n while i > 0 do\n a = fa(i)\n b = fb(i)\n r = b / (a + r)\n i = i - 1\n end\n a = fa(0)\n return a + r\nend\n\nfunction sqrt2a(n)\n if n ~= 0 then\n return 2.0\n else\n return 1.0\n end\nend\n\nfunction sqrt2b(n)\n return 1.0\nend\n\nfunction napiera(n)\n if n ~= 0 then\n return n\n else\n return 2.0\n end\nend\n\nfunction napierb(n)\n if n > 1.0 then\n return n - 1.0\n else\n return 1.0\n end\nend\n\nfunction pia(n)\n if n ~= 0 then\n return 6.0\n else\n return 3.0\n end\nend\n\nfunction pib(n)\n local c = 2.0 * n - 1.0\n return c * c\nend\n\nfunction main()\n local sqrt2 = calc(sqrt2a, sqrt2b, 1000)\n local napier = calc(napiera, napierb, 1000)\n local pi = calc(pia, pib, 1000)\n print(sqrt2)\n print(napier)\n print(pi)\nend\n\nmain()\n", "language": "Lua" }, { "code": "contfrac:=n->evalf(Value(NumberTheory:-ContinuedFraction(n)));\ncontfrac(2^(0.5));\ncontfrac(Pi);\ncontfrac(exp(1));\n", "language": "Maple" }, { "code": "sqrt2=Function[n,{1,Transpose@{Array[2&,n],Array[1&,n]}}];\nnapier=Function[n,{2,Transpose@{Range[n],Prepend[Range[n-1],1]}}];\npi=Function[n,{3,Transpose@{Array[6&,n],Array[(2#-1)^2&,n]}}];\napprox=Function[l,\n\tN[Divide@@First@Fold[{{#2.#[[;;,1]],#2.#[[;;,2]]},#[[1]]}&,{{l[[2,1,1]]l[[1]]+l[[2,1,2]],l[[2,1,1]]},{l[[1]],1}},l[[2,2;;]]],10]];\nr2=approx/@{sqrt2@#,napier@#,pi@#}&@10000;r2//TableForm\n", "language": "Mathematica" }, { "code": "cfeval(x) := block([a, b, n, z], a: x[1], b: x[2], n: length(a), z: 0,\n for i from n step -1 thru 2 do z: b[i]/(a[i] + z), a[1] + z)$\n\ncf_sqrt2(n) := [cons(1, makelist(2, i, 2, n)), cons(0, makelist(1, i, 2, n))]$\n\ncf_e(n) := [cons(2, makelist(i, i, 1, n - 1)), append([0, 1], makelist(i, i, 1, n - 2))]$\n\ncf_pi(n) := [cons(3, makelist(6, i, 2, n)), cons(0, makelist((2*i - 1)^2, i, 1, n - 1))]$\n\ncfeval(cf_sqrt2(20)), numer; /* 1.414213562373097 */\n% - sqrt(2), numer; /* 1.3322676295501878*10^-15 */\n\ncfeval(cf_e(20)), numer; /* 2.718281828459046 */\n% - %e, numer; /* 4.4408920985006262*10^-16 */\n\ncfeval(cf_pi(20)), numer; /* 3.141623806667839 */\n% - %pi, numer; /* 3.115307804568701*10^-5 */\n\n\n/* convergence is much slower for pi */\nfpprec: 20$\nx: cfeval(cf_pi(10000))$\nbfloat(x - %pi); /* 2.4999999900104930006b-13 */\n", "language": "Maxima" }, { "code": "/* REXX ***************************************************************\n* Derived from REXX ... Derived from PL/I with a little \"massage\"\n* SQRT2= 1.41421356237309505 <- PL/I Result\n* 1.41421356237309504880168872421 <- NetRexx Result 30 digits\n* NAPIER= 2.71828182845904524\n* 2.71828182845904523536028747135\n* PI= 3.14159262280484695\n* 3.14159262280484694855146925223\n* 07.09.2012 Walter Pachl\n* 08.09.2012 Walter Pachl simplified (with the help of a friend)\n**********************************************************************/\noptions replace format comments java crossref savelog symbols\n class CFB public\n\nproperties static\n Numeric Digits 30\n Sqrt2 =1\n napier=2\n pi =3\n a =0\n b =0\n\nmethod main(args = String[]) public static\n Say 'SQRT2='.left(7) calc(sqrt2, 200)\n Say 'NAPIER='.left(7) calc(napier, 200)\n Say 'PI='.left(7) calc(pi, 200)\n Return\n\nmethod get_Coeffs(form,n) public static\n select\n when form=Sqrt2 Then do\n if n > 0 then a = 2; else a = 1\n b = 1\n end\n when form=Napier Then do\n if n > 0 then a = n; else a = 2\n if n > 1 then b = n - 1; else b = 1\n end\n when form=pi Then do\n if n > 0 then a = 6; else a = 3\n b = (2*n - 1)**2\n end\n end\n Return\n\nmethod calc(form,n) public static\n temp=0\n loop ni = n to 1 by -1\n Get_Coeffs(form,ni)\n temp = b/(a + temp)\n end\n Get_Coeffs(form,0)\n return (a + temp)\n", "language": "NetRexx" }, { "code": "proc calc(f: proc(n: int): tuple[a, b: float], n: int): float =\n var a, b, temp = 0.0\n for i in countdown(n, 1):\n (a, b) = f(i)\n temp = b / (a + temp)\n (a, b) = f(0)\n a + temp\n\nproc sqrt2(n: int): tuple[a, b: float] =\n if n > 0:\n (2.0, 1.0)\n else:\n (1.0, 1.0)\n\nproc napier(n: int): tuple[a, b: float] =\n let a = if n > 0: float(n) else: 2.0\n let b = if n > 1: float(n - 1) else: 1.0\n (a, b)\n\nproc pi(n: int): tuple[a, b: float] =\n let a = if n > 0: 6.0 else: 3.0\n let b = (2 * float(n) - 1) * (2 * float(n) - 1)\n (a, b)\n\necho calc(sqrt2, 20)\necho calc(napier, 15)\necho calc(pi, 10000)\n", "language": "Nim" }, { "code": "let pi = 3, fun n -> ((2*n-1)*(2*n-1), 6)\nand nap = 2, fun n -> (max 1 (n-1), n)\nand root2 = 1, fun n -> (1, 2) in\n\nlet eval (i,f) k =\n let rec frac n =\n let a, b = f n in\n float a /. (float b +.\n if n >= k then 0.0 else frac (n+1)) in\n float i +. frac 1 in\n\nPrintf.printf \"sqrt(2)\\t= %.15f\\n\" (eval root2 1000);\nPrintf.printf \"e\\t= %.15f\\n\" (eval nap 1000);\nPrintf.printf \"pi\\t= %.15f\\n\" (eval pi 1000);\n", "language": "OCaml" }, { "code": "back(v)=my(t=contfracpnqn(v));t[1,1]/t[2,1]*1.\nback(vector(100,i,2-(i==1)))\n", "language": "PARI-GP" }, { "code": "program ContFrac_console;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils;\n\ntype TCoeffFunction = function( n : integer) : extended;\n\n// Calculate continued fraction as a sum, working forwards.\n// Stop on reaching a term with absolute value less than epsilon,\n// or on reaching the maximum number of terms.\nprocedure CalcContFrac( a, b : TCoeffFunction;\n epsilon : extended;\n maxNrTerms : integer = 1000); // optional, with default\nvar\n n : integer;\n sum, term, u, v : extended;\n whyStopped : string;\nbegin\n sum := a(0);\n term := b(1)/a(1);\n v := a(1);\n n := 1;\n repeat\n sum := sum + term;\n inc(n);\n u := v;\n v := a(n) + b(n)/u;\n term := -term * b(n)/(u*v);\n until (Abs(term) < epsilon) or (n >= maxNrTerms);\n if n >= maxNrTerms then whyStopped := 'too many terms'\n else whyStopped := 'converged';\n WriteLn( SysUtils.Format( '%21.17f after %d terms (%s)',\n [sum, n, whyStopped]));\nend;\n\n//---------------- a and b for sqrt(2) ----------------\nfunction a_sqrt2( n : integer) : extended;\nbegin\n if n = 0 then result := 1\n else result := 2;\nend;\nfunction b_sqrt2( n : integer) : extended;\nbegin\n result := 1;\nend;\n\n//---------------- a snd b for e ----------------\nfunction a_e( n : integer) : extended;\nbegin\n if n = 0 then result := 2\n else result := n;\nend;\nfunction b_e( n : integer) : extended;\nbegin\n if n = 1 then result := 1\n else result := n - 1;\nend;\n\n//-------- Rosetta Code a and b for pi --------\nfunction a_pi( n : integer) : extended;\nbegin\n if n = 0 then result := 3\n else result := 6;\nend;\nfunction b_pi( n : integer) : extended;\nvar\n temp : extended;\nbegin\n temp := 2*n - 1;\n result := temp*temp;\nend;\n\n//-------- More efficient a and b for pi --------\nfunction a_pi_alt( n : integer) : extended;\nbegin\n if n = 0 then result := 0\n else result := 2*n - 1;\nend;\nfunction b_pi_alt( n : integer) : extended;\nvar\n temp : extended;\nbegin\n if n = 1 then\n result := 4\n else begin\n temp := n - 1;\n result := temp*temp;\n end;\nend;\n\n//---------------- Main routine ----------------\n// Unlike Free Pascal, Delphi does not require\n// an @ sign before the function names.\nbegin\n WriteLn( 'sqrt(2)');\n CalcContFrac( a_sqrt2, b_sqrt2, 1E-20);\n WriteLn( 'e');\n CalcContFrac( a_e, b_e, 1E-20);\n WriteLn( 'pi');\n CalcContFrac( a_pi, b_pi, 1E-20);\n WriteLn( 'pi (alternative formula)');\n CalcContFrac( a_pi_alt, b_pi_alt, 1E-20);\nend.\n", "language": "Pascal" }, { "code": "use strict;\nuse warnings;\nno warnings 'recursion';\nuse experimental 'signatures';\n\nsub continued_fraction ($a, $b, $n = 100) {\n $a->() + ($n and $b->() / continued_fraction($a, $b, $n-1));\n}\n\nprintf \"√2 ≈ %.9f\\n\", continued_fraction do { my $n; sub { $n++ ? 2 : 1 } }, sub { 1 };\nprintf \"e ≈ %.9f\\n\", continued_fraction do { my $n; sub { $n++ or 2 } }, do { my $n; sub { $n++ or 1 } };\nprintf \"π ≈ %.9f\\n\", continued_fraction do { my $n; sub { $n++ ? 6 : 3 } }, do { my $n; sub { (2*$n++ + 1)**2 } }, 1000;\nprintf \"π/2 ≈ %.9f\\n\", continued_fraction do { my $n; sub { 1/($n++ or 1) } }, sub { 1 }, 1000;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">precision</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">10000</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">continued_fraction</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">steps</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">precision</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">steps</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">b</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">sqr2</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">nap</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)}</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">pi</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)}</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Precision: %d\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">precision</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Sqr(2): %.10g\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">continued_fraction</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">sqr2</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Napier: %.10g\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">continued_fraction</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nap</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Pi: %.10g\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">continued_fraction</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pi</span><span style=\"color: #0000FF;\">)})</span>\n<!--\n", "language": "Phix" }, { "code": "go =>\n\n % square root 2\n continued_fraction(200, sqrt_2_ab, V1),\n printf(\"sqrt(2) = %w (diff: %0.15f)\\n\", V1, V1-sqrt(2)),\n\n % napier\n continued_fraction(200, napier_ab, V2),\n printf(\"e = %w (diff: %0.15f)\\n\", V2, V2-math.e),\n\n % pi\n continued_fraction(200, pi_ab, V3),\n printf(\"pi = %w (diff: %0.15f)\\n\", V3, V3-math.pi),\n % get a better precision\n continued_fraction(20000, pi_ab, V3b),\n printf(\"pi = %w (diff: %0.15f)\\n\", V3b, V3b-math.pi),\n nl.\n\ncontinued_fraction(N, Compute_ab, V) ?=>\n continued_fraction(N, Compute_ab, 0, V).\n\ncontinued_fraction(0, Compute_ab, Temp, V) ?=>\n call(Compute_ab, 0, A, _),\n V = A + Temp.\n\ncontinued_fraction(N, Compute_ab, Tmp, V) =>\n call(Compute_ab, N, A, B),\n Tmp1 = B / (A + Tmp),\n N1 = N - 1,\n continued_fraction(N1, Compute_ab, Tmp1, V).\n\n% definitions for square root of 2\nsqrt_2_ab(0, 1, 1).\nsqrt_2_ab(_, 2, 1).\n\n% definitions for napier\nnapier_ab(0, 2, _).\nnapier_ab(1, 1, 1).\nnapier_ab(N, N, V) :-\n\tV is N - 1.\n\n% definitions for pi\npi_ab(0, 3, _).\npi_ab(N, 6, V) :-\n\tV is (2 * N - 1)*(2 * N - 1).\n", "language": "Picat" }, { "code": "continued_fraction_it(Fun, N) = Ret =>\n Temp = 0.0,\n foreach(I in N..-1..1)\n [A,B] = apply(Fun,I),\n Temp := B / (A + Temp)\n end,\n F = apply(Fun,0),\n Ret = F[1] + Temp.\n\nfsqrt2(N) = [cond(N > 0, 2, 1),1].\nfnapier(N) = [cond(N > 0, N,2), cond(N>1,N-1,1)].\nfpi(N) = [cond(N>0,6,3), (2*N-1) ** 2].\n", "language": "Picat" }, { "code": "(scl 49)\n(de fsqrt2 (N A)\n (default A 1)\n (cond\n ((> A (inc N)) 2)\n (T\n (+\n (if (=1 A) 1.0 2.0)\n (*/ `(* 1.0 1.0) (fsqrt2 N (inc A))) ) ) ) )\n(de pi (N A)\n (default A 1)\n (cond\n ((> A (inc N)) 6.0)\n (T\n (+\n (if (=1 A) 3.0 6.0)\n (*/\n (* (** (dec (* 2 A)) 2) 1.0)\n 1.0\n (pi N (inc A)) ) ) ) ) )\n(de napier (N A)\n (default A 0)\n (cond\n ((> A N) (* A 1.0))\n (T\n (+\n (if (=0 A) 2.0 (* A 1.0))\n (*/\n (if (> 1 A) 1.0 (* A 1.0))\n 1.0\n (napier N (inc A)) ) ) ) ) )\n(prinl (format (fsqrt2 200) *Scl))\n(prinl (format (napier 200) *Scl))\n(prinl (format (pi 200) *Scl))\n", "language": "PicoLisp" }, { "code": "/* Version for SQRT(2) */\ntest: proc options (main);\n declare n fixed;\n\ndenom: procedure (n) recursive returns (float (18));\n declare n fixed;\n n = n + 1;\n if n > 100 then return (2);\n return (2 + 1/denom(n));\nend denom;\n\n put (1 + 1/denom(2));\n\nend test;\n", "language": "PL-I" }, { "code": "test: proc options (main);\n declare n fixed;\n\ndenom: procedure (n) recursive returns (float (18));\n declare n fixed;\n n = n + 1;\n if n > 100 then return (n);\n return (n + n/denom(n));\nend denom;\n\n put (2 + 1/denom(0));\n\nend test;\n", "language": "PL-I" }, { "code": "/* Derived from continued fraction in Wiki Ada program */\n\ncontinued_fractions: /* 6 Sept. 2012 */\n procedure options (main);\n declare (Sqrt2 initial (1), napier initial (2), pi initial (3)) fixed (1);\n\nGet_Coeffs: procedure (form, n, coefA, coefB);\n declare form fixed (1), n fixed, (coefA, coefB) float (18);\n\n select (form);\n when (Sqrt2) do;\n if n > 0 then coefA = 2; else coefA = 1;\n coefB = 1;\n end;\n when (Napier) do;\n if n > 0 then coefA = n; else coefA = 2;\n if n > 1 then coefB = n - 1; else coefB = 1;\n end;\n when (Pi) do;\n if n > 0 then coefA = 6; else coefA = 3;\n coefB = (2*n - 1)**2;\n end;\n end;\n end Get_Coeffs;\n\n Calc: procedure (form, n) returns (float (18));\n declare form fixed (1), n fixed;\n declare (A, B) float (18);\n declare Temp float (18) initial (0);\n declare ni fixed;\n\n do ni = n to 1 by -1;\n call Get_Coeffs (form, ni, A, B);\n Temp = B/(A + Temp);\n end;\n call Get_Coeffs (form, 0, A, B);\n return (A + Temp);\n end Calc;\n\n put edit ('SQRT2=', calc(sqrt2, 200)) (a(10), f(20,17));\n put skip edit ('NAPIER=', calc(napier, 200)) (a(10), f(20,17));\n put skip edit ('PI=', calc(pi, 99999)) (a(10), f(20,17));\n\nend continued_fractions;\n", "language": "PL-I" }, { "code": "continued_fraction :-\n\t% square root 2\n\tcontinued_fraction(200, sqrt_2_ab, V1),\n\tformat('sqrt(2) = ~w~n', [V1]),\n\n\t% napier\n\tcontinued_fraction(200, napier_ab, V2),\n\tformat('e = ~w~n', [V2]),\n\n\t% pi\n\tcontinued_fraction(200, pi_ab, V3),\n\tformat('pi = ~w~n', [V3]).\n\n\n% code for continued fractions\ncontinued_fraction(N, Compute_ab, V) :-\n\tcontinued_fraction(N, Compute_ab, 0, V).\n\ncontinued_fraction(0, Compute_ab, Temp, V) :-\n\tcall(Compute_ab, 0, A, _),\n\tV is A + Temp.\n\ncontinued_fraction(N, Compute_ab, Tmp, V) :-\n\tcall(Compute_ab, N, A, B),\n\tTmp1 is B / (A + Tmp),\n\tN1 is N - 1,\n\tcontinued_fraction(N1, Compute_ab, Tmp1, V).\n\n% specific codes for examples\n% definitions for square root of 2\nsqrt_2_ab(0, 1, 1).\nsqrt_2_ab(_, 2, 1).\n\n% definitions for napier\nnapier_ab(0, 2, _).\nnapier_ab(1, 1, 1).\nnapier_ab(N, N, V) :-\n\tV is N - 1.\n\n% definitions for pi\npi_ab(0, 3, _).\npi_ab(N, 6, V) :-\n\tV is (2 * N - 1)*(2 * N - 1).\n", "language": "Prolog" }, { "code": "from fractions import Fraction\nimport itertools\ntry: zip = itertools.izip\nexcept: pass\n\n# The Continued Fraction\ndef CF(a, b, t):\n terms = list(itertools.islice(zip(a, b), t))\n z = Fraction(1,1)\n for a, b in reversed(terms):\n z = a + b / z\n return z\n\n# Approximates a fraction to a string\ndef pRes(x, d):\n q, x = divmod(x, 1)\n res = str(q)\n res += \".\"\n for i in range(d):\n x *= 10\n q, x = divmod(x, 1)\n res += str(q)\n return res\n\n# Test the Continued Fraction for sqrt2\ndef sqrt2_a():\n yield 1\n for x in itertools.repeat(2):\n yield x\n\ndef sqrt2_b():\n for x in itertools.repeat(1):\n yield x\n\ncf = CF(sqrt2_a(), sqrt2_b(), 950)\nprint(pRes(cf, 200))\n#1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147\n\n\n# Test the Continued Fraction for Napier's Constant\ndef Napier_a():\n yield 2\n for x in itertools.count(1):\n yield x\n\ndef Napier_b():\n yield 1\n for x in itertools.count(1):\n yield x\n\ncf = CF(Napier_a(), Napier_b(), 950)\nprint(pRes(cf, 200))\n#2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901\n\n# Test the Continued Fraction for Pi\ndef Pi_a():\n yield 3\n for x in itertools.repeat(6):\n yield x\n\ndef Pi_b():\n for x in itertools.count(1,2):\n yield x*x\n\ncf = CF(Pi_a(), Pi_b(), 950)\nprint(pRes(cf, 10))\n#3.1415926532\n", "language": "Python" }, { "code": "from decimal import Decimal, getcontext\n\ndef calc(fun, n):\n temp = Decimal(\"0.0\")\n\n for ni in xrange(n+1, 0, -1):\n (a, b) = fun(ni)\n temp = Decimal(b) / (a + temp)\n\n return fun(0)[0] + temp\n\ndef fsqrt2(n):\n return (2 if n > 0 else 1, 1)\n\ndef fnapier(n):\n return (n if n > 0 else 2, (n - 1) if n > 1 else 1)\n\ndef fpi(n):\n return (6 if n > 0 else 3, (2 * n - 1) ** 2)\n\ngetcontext().prec = 50\nprint calc(fsqrt2, 200)\nprint calc(fnapier, 200)\nprint calc(fpi, 200)\n", "language": "Python" }, { "code": " [ $ \"bigrat.qky\" loadfile ] now!\n\n [ 1 min\n [ table\n [ 1 1 ]\n [ 2 1 ] ] do ] is sqrt2 ( n --> n/d )\n\n [ dup 2 min\n [ table\n [ drop 2 1 ]\n [ 1 ]\n [ dup 1 - ] ] do ] is napier ( n --> n/d )\n\n [ dup 1 min\n [ table\n [ drop 3 1 ]\n [ 2 * 1 - dup *\n 6 swap ] ] do ] is pi ( n --> n/d )\n\n [ ]'[ temp put\n 0 1\n rot times\n [ i 1+\n temp share do\n v+ 1/v ]\n 0 temp take do v+ ] is cf ( n --> n/d )\n\n 1000 cf sqrt2 10 point$ echo$ cr\n 1000 cf napier 10 point$ echo$ cr\n 1000 cf pi 10 point$ echo$ cr\n", "language": "Quackery" }, { "code": "#lang racket\n(define (calc cf n)\n (match/values (cf 0)\n [(a0 b0)\n (+ a0\n (for/fold ([t 0.0]) ([i (in-range (+ n 1) 0 -1)])\n (match/values (cf i)\n [(a b) (/ b (+ a t))])))]))\n\n(define (cf-sqrt i) (values (if (> i 0) 2 1) 1))\n(define (cf-napier i) (values (if (> i 0) i 2) (if (> i 1) (- i 1) 1)))\n(define (cf-pi i) (values (if (> i 0) 6 3) (sqr (- (* 2 i) 1))))\n\n(calc cf-sqrt 200)\n(calc cf-napier 200)\n(calc cf-pi 200)\n", "language": "Racket" }, { "code": "1.4142135623730951\n2.7182818284590455\n3.1415926839198063\n", "language": "Racket" }, { "code": "#lang racket\n(require math)\n(bf-precision 2048) ; in bits\n\n(define (calc cf n)\n (match/values (cf 0)\n [(a0 b0)\n (bf+ (bf a0)\n (for/fold ([t (bf 0)]) ([i (in-range (+ n 1) 0 -1)])\n (match/values (cf i)\n [(a b) (bf/ (bf b) (bf+ (bf a) t))])))]))\n\n(define (cf-sqrt i) (values (if (> i 0) 2 1) 1))\n(define (cf-napier i) (values (if (> i 0) i 2) (if (> i 1) (- i 1) 1)))\n(define (cf-pi i) (values (if (> i 0) 6 3) (sqr (- (* 2 i) 1))))\n\n(calc cf-sqrt 200)\n(calc cf-napier 200)\n(calc cf-pi 200)\n", "language": "Racket" }, { "code": "(bf #e1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358960036439214262599769155193770031712304888324413327207659690547583107739957489062466508437105234564161085482146113860092820802430986649987683947729823677905101453725898480737256099166805538057375451207262441039818826744940289448489312217214883459060818483750848688583833366310472320771259749181255428309841375829513581694269249380272698662595131575038315461736928338289219865139248048189188905788104310928762952913687232022557677738108337499350045588767581063729)\n(bf #e2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206955170276183860626133138458300075204493382656029760673711320070932870912744374704723624212700454495421842219077173525899689811474120614457405772696521446961165559468253835854362096088934714907384964847142748311021268578658461064714894910680584249490719358138073078291397044213736982988247857479512745588762993966446075)\n(bf #e3.14159268391980626493420192940831754203350026401337226640663040854412059241988978103217808449508253393479795573626200366332733859609651462659489470805432281782785922056335606047700127154963266242144951481397480765182268219697420028007903565511884267297358842935537138583640066772149177226656227031792115896439889412205871076985598822285367358003457939603015797225018209619662200081521930463480571130673429337524564941105654923909951299948539893933654293161126559643573974163405197696633200469475250152247413175932572922175467223988860975105100904322239324381097207835036465269418118204894206705789759765527734394105147)\n", "language": "Racket" }, { "code": "sub continued-fraction(:@a, :@b, Int :$n = 100)\n{\n my $x = @a[$n - 1];\n $x = @a[$_ - 1] + @b[$_] / $x for reverse 1 ..^ $n;\n $x;\n}\n\nprintf \"√2 ≈%.9f\\n\", continued-fraction(:a(1, |(2 xx *)), :b(Nil, |(1 xx *)));\nprintf \"e ≈%.9f\\n\", continued-fraction(:a(2, |(1 .. *)), :b(Nil, 1, |(1 .. *)));\nprintf \"π ≈%.9f\\n\", continued-fraction(:a(3, |(6 xx *)), :b(Nil, |((1, 3, 5 ... *) X** 2)));\n", "language": "Raku" }, { "code": "sub continued-fraction(@a, @b) {\n map { .(Inf) }, [\\o] map { @a[$_] + @b[$_] / * }, ^Inf\n}\n\nprintf \"√2 ≈ %.9f\\n\", continued-fraction((1, |(2 xx *)), (1 xx *))[10];\nprintf \"e ≈ %.9f\\n\", continued-fraction((2, |(1 .. *)), (1, |(1 .. *)))[10];\nprintf \"π ≈ %.9f\\n\", continued-fraction((3, |(6 xx *)), ((1, 3, 5 ... *) X** 2))[100];\n", "language": "Raku" }, { "code": "/*REXX program calculates and displays values of various continued fractions. */\nparse arg terms digs .\nif terms=='' | terms==\",\" then terms=500\nif digs=='' | digs==\",\" then digs=100\nnumeric digits digs /*use 100 decimal digits for display.*/\nb.=1 /*omitted ß terms are assumed to be 1.*/\n/*══════════════════════════════════════════════════════════════════════════════════════*/\na.=2; call tell '√2', cf(1)\n/*══════════════════════════════════════════════════════════════════════════════════════*/\na.=1; do N=2 by 2 to terms; a.N=2; end; call tell '√3', cf(1) /*also: 2∙sin(π/3) */\n/*══════════════════════════════════════════════════════════════════════════════════════*/\na.=2 /* ___ */\n do N=2 to 17 /*generalized √ N */\n b.=N-1; NN=right(N, 2); call tell 'gen √'NN, cf(1)\n end /*N*/\n/*══════════════════════════════════════════════════════════════════════════════════════*/\na.=2; b.=-1/2; call tell 'gen √ ½', cf(1)\n/*══════════════════════════════════════════════════════════════════════════════════════*/\n do j=1 for terms; a.j=j; if j>1 then b.j=a.p; p=j; end; call tell 'e', cf(2)\n/*══════════════════════════════════════════════════════════════════════════════════════*/\na.=1; call tell 'φ, phi', cf(1)\n/*══════════════════════════════════════════════════════════════════════════════════════*/\na.=1; do j=1 for terms; if j//2 then a.j=j; end; call tell 'tan(1)', cf(1)\n/*══════════════════════════════════════════════════════════════════════════════════════*/\n do j=1 for terms; a.j=2*j+1; end; call tell 'coth(1)', cf(1)\n/*══════════════════════════════════════════════════════════════════════════════════════*/\n do j=1 for terms; a.j=4*j+2; end; call tell 'coth(½)', cf(2) /*also: [e+1]÷[e-1] */\n/*══════════════════════════════════════════════════════════════════════════════════════*/\n terms=100000\na.=6; do j=1 for terms; b.j=(2*j-1)**2; end; call tell 'π, pi', cf(3)\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncf: procedure expose a. b. terms; parse arg C; !=0; numeric digits 9+digits()\n do k=terms by -1 for terms; d=a.k+!; !=b.k/d\n end /*k*/\n return !+C\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ntell: parse arg ?,v; $=left(format(v)/1,1+digits()); w=50 /*50 bytes of terms*/\n aT=; do k=1; _=space(aT a.k); if length(_)>w then leave; aT=_; end /*k*/\n bT=; do k=1; _=space(bT b.k); if length(_)>w then leave; bT=_; end /*k*/\n say right(?,8) \"=\" $ ' α terms='aT ...\n if b.1\\==1 then say right(\"\",12+digits()) ' ß terms='bT ...\n a=; b.=1; return /*only 50 bytes of α & ß terms ↑ are displayed. */\n", "language": "REXX" }, { "code": "/* REXX **************************************************************\n* Derived from PL/I with a little \"massage\"\n* SQRT2= 1.41421356237309505 <- PL/I Result\n* 1.41421356237309504880168872421 <- REXX Result 30 digits\n* NAPIER= 2.71828182845904524\n* 2.71828182845904523536028747135\n* PI= 3.14159262280484695\n* 3.14159262280484694855146925223\n* 06.09.2012 Walter Pachl\n**********************************************************************/\n Numeric Digits 30\n Parse Value '1 2 3 0 0' with Sqrt2 napier pi a b\n Say left('SQRT2=' ,10) calc(sqrt2, 200)\n Say left('NAPIER=',10) calc(napier, 200)\n Say left('PI=' ,10) calc(pi, 200)\n Exit\n\nGet_Coeffs: procedure Expose a b Sqrt2 napier pi\n Parse Arg form, n\n select\n when form=Sqrt2 Then do\n if n > 0 then a = 2; else a = 1\n b = 1\n end\n when form=Napier Then do\n if n > 0 then a = n; else a = 2\n if n > 1 then b = n - 1; else b = 1\n end\n when form=pi Then do\n if n > 0 then a = 6; else a = 3\n b = (2*n - 1)**2\n end\n end\n Return\n\nCalc: procedure Expose a b Sqrt2 napier pi\n Parse Arg form,n\n Temp=0\n do ni = n to 1 by -1\n Call Get_Coeffs form, ni\n Temp = B/(A + Temp)\n end\n call Get_Coeffs form, 0\n return (A + Temp)\n", "language": "REXX" }, { "code": "/* REXX *************************************************************\n* The task description specifies a continued fraction for pi\n* that gives a reasonable approximation.\n* Literature shows a better CF that yields pi with a precision of\n* 200 digits.\n* http://de.wikipedia.org/wiki/Kreiszahl\n* 1\n* pi = 3 + ------------------------\n* 1\n* 7 + --------------------\n* 1\n* 15 + ---------------\n* 1\n* 1 + -----------\n*\n* 292 + ...\n*\n* This program uses that CF and shows the first 50 digits\n* PI =3.1415926535897932384626433832795028841971693993751...\n* PIX=3.1415926535897932384626433832795028841971693993751...\n* 201 correct digits\n* 18.09.2012 Walter Pachl\n**********************************************************************/\n pi='3.1415926535897932384626433832795028841971'||,\n '693993751058209749445923078164062862089986280348'||,\n '253421170679821480865132823066470938446095505822'||,\n '317253594081284811174502841027019385211055596446'||,\n '229489549303819644288109756659334461284756482337'||,\n '867831652712019091456485669234603486104543266482'||,\n '133936072602491412737245870066063155881748815209'||,\n '209628292540917153643678925903600113305305488204'||,\n '665213841469519415116094330572703657595919530921'||,\n '861173819326117931051185480744623799627495673518'||,\n '857527248912279381830119491298336733624'\n Numeric Digits 1000\n al='7 15 1 292 1 1 1 2 1 3 1 14 2 1 1 2 2 2 2 1 84 2',\n '1 1 15 3 13 1 4 2 6 6 99 1 2 2 6 3 5 1 1 6 8 1 7 1 2',\n '3 7 1 2 1 1 12 1 1 1 3 1 1 8 1 1 2 1 6 1 1 5 2 2 3 1',\n '2 4 4 16 1 161 45 1 22 1 2 2 1 4 1 2 24 1 2 1 3 1 2',\n '1 1 10 2 5 4 1 2 2 8 1 5 2 2 26 1 4 1 1 8 2 42 2 1 7',\n '3 3 1 1 7 2 4 9 7 2 3 1 57 1 18 1 9 19 1 2 18 1 3 7',\n '30 1 1 1 3 3 3 1 2 8 1 1 2 1 15 1 2 13 1 2 1 4 1 12',\n '1 1 3 3 28 1 10 3 2 20 1 1 1 1 4 1 1 1 5 3 2 1 6 1 4'\n a.=3\n Do i=1 By 1 while al<>''\n Parse Var al a.i al\n End\n pix=calc(194)\n Do e=1 To length(pi)\n If substr(pix,e,1)<>substr(pi,e,1) Then Leave\n End\n Numeric Digits 50\n Say 'PI ='||(pi+0)||'...'\n Say 'PIX='||(pix+0)||'...'\n Say (e-1) 'correct digits'\n Exit\n\nGet_Coeffs: procedure Expose a b a.\n Parse Arg n\n a=a.n\n b=1\n Return\n\nCalc: procedure Expose a b a.\n Parse Arg n\n Temp=0\n do ni = n to 1 by -1\n Call Get_Coeffs ni\n Temp = B/(A + Temp)\n end\n call Get_Coeffs 0\n return (A + Temp)\n", "language": "REXX" }, { "code": "# Project : Continued fraction\n\nsee \"SQR(2) = \" + contfrac(1, 1, \"2\", \"1\") + nl\nsee \" e = \" + contfrac(2, 1, \"n\", \"n\") + nl\nsee \" PI = \" + contfrac(3, 1, \"6\", \"(2*n+1)^2\") + nl\n\nfunc contfrac(a0, b1, a, b)\n expr = \"\"\n n = 0\n while len(expr) < (700 - n)\n n = n + 1\n eval(\"temp1=\" + a)\n eval(\"temp2=\" + b)\n expr = expr + string(temp1) + char(43) + string(temp2) + \"/(\"\n end\n str = copy(\")\",n)\n eval(\"temp3=\" + expr + \"1\" + str)\n return a0 + b1 / temp3\n", "language": "Ring" }, { "code": "require 'bigdecimal'\n\n# square root of 2\nsqrt2 = Object.new\ndef sqrt2.a(n); n == 1 ? 1 : 2; end\ndef sqrt2.b(n); 1; end\n\n# Napier's constant\nnapier = Object.new\ndef napier.a(n); n == 1 ? 2 : n - 1; end\ndef napier.b(n); n == 1 ? 1 : n - 1; end\n\npi = Object.new\ndef pi.a(n); n == 1 ? 3 : 6; end\ndef pi.b(n); (2*n - 1)**2; end\n\n# Estimates the value of a continued fraction _cfrac_, to _prec_\n# decimal digits of precision. Returns a BigDecimal. _cfrac_ must\n# respond to _cfrac.a(n)_ and _cfrac.b(n)_ for integer _n_ >= 1.\ndef estimate(cfrac, prec)\n last_result = nil\n terms = prec\n\n loop do\n # Estimate continued fraction for _n_ from 1 to _terms_.\n result = cfrac.a(terms)\n (terms - 1).downto(1) do |n|\n a = BigDecimal cfrac.a(n)\n b = BigDecimal cfrac.b(n)\n digits = [b.div(result, 1).exponent + prec, 1].max\n result = a + b.div(result, digits)\n end\n result = result.round(prec)\n\n if result == last_result\n return result\n else\n # Double _terms_ and try again.\n last_result = result\n terms *= 2\n end\n end\nend\n\nputs estimate(sqrt2, 50).to_s('F')\nputs estimate(napier, 50).to_s('F')\nputs estimate(pi, 10).to_s('F')\n", "language": "Ruby" }, { "code": "use std::iter;\n\n// Calculating a continued fraction is quite easy with iterators, however\n// writing a proper iterator adapter is less so. We settle for a macro which\n// for most purposes works well enough.\n//\n// One limitation with this iterator based approach is that we cannot reverse\n// input iterators since they are not usually DoubleEnded. To circumvent this\n// we can collect the elements and then reverse them, however this isn't ideal\n// as we now have to store elements equal to the number of iterations.\n//\n// Another is that iterators cannot be resused once consumed, so it is often\n// required to make many clones of iterators.\nmacro_rules! continued_fraction {\n ($a:expr, $b:expr ; $iterations:expr) => (\n ($a).zip($b)\n .take($iterations)\n .collect::<Vec<_>>().iter()\n .rev()\n .fold(0 as f64, |acc: f64, &(x, y)| {\n x as f64 + (y as f64 / acc)\n })\n );\n\n ($a:expr, $b:expr) => (continued_fraction!($a, $b ; 1000));\n}\n\nfn main() {\n // Sqrt(2)\n let sqrt2a = (1..2).chain(iter::repeat(2));\n let sqrt2b = iter::repeat(1);\n println!(\"{}\", continued_fraction!(sqrt2a, sqrt2b));\n\n\n // Napier's Constant\n let napiera = (2..3).chain(1..);\n let napierb = (1..2).chain(1..);\n println!(\"{}\", continued_fraction!(napiera, napierb));\n\n\n // Pi\n let pia = (3..4).chain(iter::repeat(6));\n let pib = (1i64..).map(|x| (2 * x - 1).pow(2));\n println!(\"{}\", continued_fraction!(pia, pib));\n}\n", "language": "Rust" }, { "code": "object CF extends App {\n import Stream._\n val sqrt2 = 1 #:: from(2,0) zip from(1,0)\n val napier = 2 #:: from(1) zip (1 #:: from(1))\n val pi = 3 #:: from(6,0) zip (from(1,2) map {x=>x*x})\n\n // reference values, source: wikipedia\n val refPi = \"3.14159265358979323846264338327950288419716939937510\"\n val refNapier = \"2.71828182845904523536028747135266249775724709369995\"\n val refSQRT2 = \"1.41421356237309504880168872420969807856967187537694\"\n\n def calc(cf: Stream[(Int, Int)], numberOfIters: Int=200): BigDecimal = {\n (cf take numberOfIters toList).foldRight[BigDecimal](1)((a, z) => a._1+a._2/z)\n }\n\n def approx(cfV: BigDecimal, cfRefV: String): String = {\n val p: Pair[Char,Char] => Boolean = pair =>(pair._1==pair._2)\n ((cfV.toString+\" \"*34).substring(0,34) zip cfRefV.toString.substring(0,34))\n .takeWhile(p).foldRight[String](\"\")((a:Pair[Char,Char],z)=>a._1+z)\n }\n\n List((\"sqrt2\",sqrt2,50,refSQRT2),(\"napier\",napier,50,refNapier),(\"pi\",pi,3000,refPi)) foreach {t=>\n val (name,cf,iters,refV) = t\n val cfV = calc(cf,iters)\n println(name+\":\")\n println(\"ref value: \"+refV.substring(0,34))\n println(\"cf value: \"+(cfV.toString+\" \"*34).substring(0,34))\n println(\"precision: \"+approx(cfV,refV))\n println()\n }\n}\n", "language": "Scala" }, { "code": "object CFI extends App {\n import Stream._\n val sqrt2 = 1 #:: from(2,0) zip from(1,0)\n val napier = 2 #:: from(1) zip (1 #:: from(1))\n val pi = 3 #:: from(6,0) zip (from(1,2) map {x=>x*x})\n\n // reference values, source: wikipedia\n val refPi = \"3.14159265358979323846264338327950288419716939937510\"\n val refNapier = \"2.71828182845904523536028747135266249775724709369995\"\n val refSQRT2 = \"1.41421356237309504880168872420969807856967187537694\"\n\n def calc_i(cf: Stream[(Int, Int)], numberOfIters: Int=50): BigDecimal = {\n val cfl = cf take numberOfIters toList\n var z: BigDecimal = 1.0\n for (i <- 0 to cfl.size-1 reverse)\n z=cfl(i)._1+cfl(i)._2/z\n z\n }\n\n def approx(cfV: BigDecimal, cfRefV: String): String = {\n val p: Pair[Char,Char] => Boolean = pair =>(pair._1==pair._2)\n ((cfV.toString+\" \"*34).substring(0,34) zip cfRefV.toString.substring(0,34))\n .takeWhile(p).foldRight[String](\"\")((a:Pair[Char,Char],z)=>a._1+z)\n }\n\n List((\"sqrt2\",sqrt2,50,refSQRT2),(\"napier\",napier,50,refNapier),(\"pi\",pi,50000,refPi)) foreach {t=>\n val (name,cf,iters,refV) = t\n val cfV = calc_i(cf,iters)\n println(name+\":\")\n println(\"ref value: \"+refV.substring(0,34))\n println(\"cf value: \"+(cfV.toString+\" \"*34).substring(0,34))\n println(\"precision: \"+approx(cfV,refV))\n println()\n }\n}\n", "language": "Scala" }, { "code": "#!r6rs\n(import (rnrs base (6))\n (srfi :41 streams))\n\n(define nats (stream-cons 0 (stream-map (lambda (x) (+ x 1)) nats)))\n\n(define (build-stream fn) (stream-map fn nats))\n\n(define (stream-cycle s . S)\n (cond\n ((stream-null? (car S)) stream-null)\n (else (stream-cons (stream-car s)\n (apply stream-cycle (append S (list (stream-cdr s))))))))\n\n(define (cf-floor cf) (stream-car cf))\n(define (cf-num cf) (stream-car (stream-cdr cf)))\n(define (cf-denom cf) (stream-cdr (stream-cdr cf)))\n\n(define (cf-integer? x) (stream-null? (stream-cdr x)))\n\n(define (cf->real x)\n (let refine ((x x) (n 65536))\n (cond\n ((= n 0) +inf.0)\n ((cf-integer? x) (cf-floor x))\n (else (+ (cf-floor x)\n (/ (cf-num x)\n (refine (cf-denom x) (- n 1))))))))\n\n(define (real->cf x)\n (let-values (((integer-part fractional-part) (div-and-mod x 1)))\n (if (= fractional-part 0.0)\n (stream (exact integer-part))\n (stream-cons\n (exact integer-part)\n (stream-cons\n 1\n (real->cf (/ fractional-part)))))))\n\n\n(define sqrt2 (stream-cons 1 (stream-constant 1 2)))\n\n(define napier\n (stream-append (stream 2 1)\n (stream-cycle (stream-cdr nats) (stream-cdr nats))))\n\n(define pi\n (stream-cons 3\n (stream-cycle (build-stream (lambda (n) (expt (- (* 2 (+ n 1)) 1) 2)))\n (stream-constant 6))))\n", "language": "Scheme" }, { "code": "> (cf->real sqrt2)\n1.4142135623730951\n> (cf->real napier)\n2.7182818284590455\n> (cf->real pi)\n3.141592653589794\n", "language": "Scheme" }, { "code": "func continued_fraction(a, b, f, n = 1000, r = 1) {\n f(func (r) {\n r < n ? (a(r) / (b(r) + __FUNC__(r+1))) : 0\n }(r))\n}\n\nvar params = Hash(\n \"φ\" => [ { 1 }, { 1 }, { 1 + _ } ],\n \"√2\" => [ { 1 }, { 2 }, { 1 + _ } ],\n \"e\" => [ { _ }, { _ }, { 1 + 1/_ } ],\n \"π\" => [ { (2*_ - 1)**2 }, { 6 }, { 3 + _ } ],\n \"τ\" => [ { _**2 }, { 2*_ + 1 }, { 8 / (1 + _) } ],\n)\n\nfor k in (params.keys.sort) {\n printf(\"%2s ≈ %s\\n\", k, continued_fraction(params{k}...))\n}\n", "language": "Sidef" }, { "code": "extension BinaryInteger {\n @inlinable\n public func power(_ n: Self) -> Self {\n return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *)\n }\n}\n\npublic struct CycledSequence<WrappedSequence: Sequence> {\n private var seq: WrappedSequence\n private var iter: WrappedSequence.Iterator\n\n init(seq: WrappedSequence) {\n self.seq = seq\n self.iter = seq.makeIterator()\n }\n}\n\nextension CycledSequence: Sequence, IteratorProtocol {\n public mutating func next() -> WrappedSequence.Element? {\n if let ele = iter.next() {\n return ele\n } else {\n iter = seq.makeIterator()\n\n return iter.next()\n }\n }\n}\n\nextension Sequence {\n public func cycled() -> CycledSequence<Self> {\n return CycledSequence(seq: self)\n }\n}\n\npublic struct ChainedSequence<Element> {\n private var sequences: [AnySequence<Element>]\n private var iter: AnyIterator<Element>\n private var curSeq = 0\n\n init(chain: ChainedSequence) {\n self.sequences = chain.sequences\n self.iter = chain.iter\n self.curSeq = chain.curSeq\n }\n\n init<Seq: Sequence>(_ seq: Seq) where Seq.Element == Element {\n sequences = [AnySequence(seq)]\n iter = sequences[curSeq].makeIterator()\n }\n\n func chained<Seq: Sequence>(with seq: Seq) -> ChainedSequence where Seq.Element == Element {\n var res = ChainedSequence(chain: self)\n\n res.sequences.append(AnySequence(seq))\n\n return res\n }\n}\n\nextension ChainedSequence: Sequence, IteratorProtocol {\n public mutating func next() -> Element? {\n if let el = iter.next() {\n return el\n }\n\n curSeq += 1\n\n guard curSeq != sequences.endIndex else {\n return nil\n }\n\n iter = sequences[curSeq].makeIterator()\n\n return iter.next()\n }\n}\n\nextension Sequence {\n public func chained<Seq: Sequence>(with other: Seq) -> ChainedSequence<Element> where Seq.Element == Element {\n return ChainedSequence(self).chained(with: other)\n }\n}\n\nfunc continuedFraction<T: Sequence, V: Sequence>(\n _ seq1: T,\n _ seq2: V,\n iterations: Int = 1000\n) -> Double where T.Element: BinaryInteger, T.Element == V.Element {\n return zip(seq1, seq2).prefix(iterations).reversed().reduce(0.0, { Double($1.0) + (Double($1.1) / $0) })\n}\n\nlet sqrtA = [1].chained(with: [2].cycled())\nlet sqrtB = [1].cycled()\n\nprint(\"√2 ≈ \\(continuedFraction(sqrtA, sqrtB))\")\n\nlet napierA = [2].chained(with: 1...)\nlet napierB = [1].chained(with: 1...)\n\nprint(\"e ≈ \\(continuedFraction(napierA, napierB))\")\n\nlet piA = [3].chained(with: [6].cycled())\nlet piB = (1...).lazy.map({ (2 * $0 - 1).power(2) })\n\nprint(\"π ≈ \\(continuedFraction(piA, piB))\")\n", "language": "Swift" }, { "code": "import Foundation\n\nfunc calculate(n: Int, operation: (Int) -> [Int])-> Double {\n var tmp: Double = 0\n for ni in stride(from: n, to:0, by: -1) {\n var p = operation(ni)\n tmp = Double(p[1])/(Double(p[0]) + tmp);\n }\n return Double(operation(0)[0]) + tmp;\n}\n\nfunc sqrt (n: Int) -> [Int] {\n return [n > 0 ? 2 : 1, 1]\n}\n\nfunc napier (n: Int) -> [Int] {\n var res = [n > 0 ? n : 2, n > 1 ? (n - 1) : 1]\n return res\n}\n\nfunc pi(n: Int) -> [Int] {\n var res = [n > 0 ? 6 : 3, Int(pow(Double(2 * n - 1), 2))]\n return res\n}\nprint (calculate(n: 200, operation: sqrt));\nprint (calculate(n: 200, operation: napier));\nprint (calculate(n: 200, operation: pi));\n", "language": "Swift" }, { "code": "package require Tcl 8.6\n\n# Term generators; yield list of pairs\nproc r2 {} {\n yield {1 1}\n while 1 {yield {2 1}}\n}\nproc e {} {\n yield {2 1}\n while 1 {yield [list [incr n] $n]}\n}\nproc pi {} {\n set n 0; set a 3\n while 1 {\n\tyield [list $a [expr {(2*[incr n]-1)**2}]]\n\tset a 6\n }\n}\n\n# Continued fraction calculator\nproc cf {generator {termCount 50}} {\n # Get the chunk of terms we want to work with\n set terms [list [coroutine cf.c $generator]]\n while {[llength $terms] < $termCount} {\n\tlappend terms [cf.c]\n }\n rename cf.c {}\n\n # Merge the terms to compute the result\n set val 0.0\n foreach pair [lreverse $terms] {\n\tlassign $pair a b\n\tset val [expr {$a + $b/$val}]\n }\n return $val\n}\n\n# Demonstration\nputs [cf r2]\nputs [cf e]\nputs [cf pi 250]; # Converges more slowly\n", "language": "Tcl" }, { "code": "Public Const precision = 10000\nPrivate Function continued_fraction(steps As Integer, rid_a As String, rid_b As String) As Double\n Dim res As Double\n res = 0\n For n = steps To 1 Step -1\n res = Application.Run(rid_b, n) / (Application.Run(rid_a, n) + res)\n Next n\n continued_fraction = Application.Run(rid_a, 0) + res\nEnd Function\n\nFunction sqr2_a(n As Integer) As Integer\n sqr2_a = IIf(n = 0, 1, 2)\nEnd Function\n\nFunction sqr2_b(n As Integer) As Integer\n sqr2_b = 1\nEnd Function\n\nFunction nap_a(n As Integer) As Integer\n nap_a = IIf(n = 0, 2, n)\nEnd Function\n\nFunction nap_b(n As Integer) As Integer\n nap_b = IIf(n = 1, 1, n - 1)\nEnd Function\n\nFunction pi_a(n As Integer) As Integer\n pi_a = IIf(n = 0, 3, 6)\nEnd Function\n\nFunction pi_b(n As Integer) As Long\n pi_b = IIf(n = 1, 1, (2 * n - 1) ^ 2)\nEnd Function\n\nPublic Sub main()\n Debug.Print \"Precision:\", precision\n Debug.Print \"Sqr(2):\", continued_fraction(precision, \"sqr2_a\", \"sqr2_b\")\n Debug.Print \"Napier:\", continued_fraction(precision, \"nap_a\", \"nap_b\")\n Debug.Print \"Pi:\", continued_fraction(precision, \"pi_a\", \"pi_b\")\nEnd Sub\n", "language": "VBA" }, { "code": "Module Module1\n Function Calc(f As Func(Of Integer, Integer()), n As Integer) As Double\n Dim temp = 0.0\n For ni = n To 1 Step -1\n Dim p = f(ni)\n temp = p(1) / (p(0) + temp)\n Next\n Return f(0)(0) + temp\n End Function\n\n Sub Main()\n Dim fList = {\n Function(n As Integer) New Integer() {If(n > 0, 2, 1), 1},\n Function(n As Integer) New Integer() {If(n > 0, n, 2), If(n > 1, n - 1, 1)},\n Function(n As Integer) New Integer() {If(n > 0, 6, 3), Math.Pow(2 * n - 1, 2)}\n }\n\n For Each f In fList\n Console.WriteLine(Calc(f, 200))\n Next\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "var calc = Fn.new { |f, n|\n var t = 0\n for (i in n..1) {\n var p = f.call(i)\n t = p[1] / (p[0] + t)\n }\n return f.call(0)[0] + t\n}\n\nvar pList = [\n [\"sqrt(2)\", Fn.new { |n| [(n > 0) ? 2 : 1, 1] }],\n [\"e \", Fn.new { |n| [(n > 0) ? n : 2, (n > 1) ? n - 1 : 1] }],\n [\"pi \", Fn.new { |n| [(n > 0) ? 6 : 3, (2*n - 1) * (2*n - 1)] }]\n]\nfor (p in pList) System.print(\"%(p[0]) = %(calc.call(p[1], 200))\")\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes;\nint N;\nreal A, B, F;\n[Format(1, 15);\nA:= 2.0; B:= 1.0; N:= 16;\nIntOut(0, N); CrLf(0);\nF:= 0.0;\nwhile N>=1 do [F:= B/(A+F); N:= N-1];\nRlOut(0, 1.0+F); CrLf(0);\nRlOut(0, sqrt(2.0)); CrLf(0);\n\nN:= 13;\nIntOut(0, N); CrLf(0);\nF:= 0.0;\nwhile N>=2 do [F:= float(N-1)/(float(N)+F); N:= N-1];\nRlOut(0, 2.0 + 1.0/(1.0+F)); CrLf(0);\nRlOut(0, Exp(1.0)); CrLf(0);\n\nN:= 10000;\nIntOut(0, N); CrLf(0);\nF:= 0.0;\nwhile N>=1 do [F:= float(sq(2*N-1))/(6.0+F); N:= N-1];\nRlOut(0, 3.0+F); CrLf(0);\nRlOut(0, ACos(-1.0)); CrLf(0);\n]\n", "language": "XPL0" }, { "code": "fcn cf(fa,fb,a0){fcn(fa,fb,a0,n){\n a0 + [n..1,-1].reduce(\n 'wrap(p,n){ fb(n)/(fa(n)+p) },0.0) }.fp(fa,fb,a0)\n}\n", "language": "Zkl" }, { "code": "sqrt2:=cf((2.0).noop,(1.0).noop,1.0);\n sqrt2(200) : \"%.20e\".fmt(_).println();\nnap:=cf((0.0).create,fcn(n){ (n==1) and 1.0 or (n-1).toFloat() },2.0);\n println(nap(15) - (1.0).e);\npi:=cf((6.0).noop,fcn(n){ n=2*n-1; (n*n).toFloat() },3.0);\n println(pi(1000) - (1.0).pi);\n", "language": "Zkl" }, { "code": "10 LET a0=1: LET b1=1: LET a$=\"2\": LET b$=\"1\": PRINT \"SQR(2) = \";: GO SUB 1000\n20 LET a0=2: LET b1=1: LET a$=\"N\": LET b$=\"N\": PRINT \"e = \";: GO SUB 1000\n30 LET a0=3: LET b1=1: LET a$=\"6\": LET b$=\"(2*N+1)^2\": PRINT \"PI = \";: GO SUB 1000\n100 STOP\n1000 LET n=0: LET e$=\"\": LET p$=\"\"\n1010 LET n=n+1\n1020 LET e$=e$+STR$ VAL a$+\"+\"+STR$ VAL b$+\"/(\"\n1030 IF LEN e$<(4000-n) THEN GO TO 1010\n1035 FOR i=1 TO n: LET p$=p$+\")\": NEXT i\n1040 PRINT a0+b1/VAL (e$+\"1\"+p$)\n1050 RETURN\n", "language": "ZX-Spectrum-Basic" } ]
Continued-fraction
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number\n", "language": "00-META" }, { "code": "To understand this task in context please see [[Continued fraction arithmetic]]\n\nThe purpose of this task is to write a function <math>\\mathit{r2cf}(\\mathrm{int}</math> <math>N_1, \\mathrm{int}</math> <math>N_2)</math>, or <math>\\mathit{r2cf}(\\mathrm{Fraction}</math> <math>N)</math>, which will output a continued fraction assuming:\n:<math>N_1</math> is the numerator\n:<math>N_2</math> is the denominator\n \nThe function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.\n\nTo achieve this it must determine: the integer part; and remainder part, of <math>N_1</math> divided by <math>N_2</math>. It then sets <math>N_1</math> to <math>N_2</math> and <math>N_2</math> to the determined remainder part. It then outputs the determined integer part. It does this until <math>\\mathrm{abs}(N_2)</math> is zero.\n\nDemonstrate the function by outputing the continued fraction for:\n: 1/2\n: 3\n: 23/8\n: 13/11\n: 22/7\n: -151/77\n<math>\\sqrt 2</math> should approach <math>[1; 2, 2, 2, 2, \\ldots]</math> try ever closer rational approximations until boredom gets the better of you:\n: 14142,10000\n: 141421,100000\n: 1414214,1000000\n: 14142136,10000000\n\nTry :\n: 31,10\n: 314,100\n: 3142,1000\n: 31428,10000\n: 314285,100000\n: 3142857,1000000\n: 31428571,10000000\n: 314285714,100000000\n\nObserve how this rational number behaves differently to <math>\\sqrt 2</math> and convince yourself that, in the same way as <math>3.7</math> may be represented as <math>3.70</math> when an extra decimal place is required, <math>[3;7]</math> may be represented as <math>[3;7,\\infty]</math> when an extra term is required.\n\n", "language": "00-TASK" }, { "code": "F r2cf(=n1, =n2)\n [Int] r\n L n2 != 0\n (n1, V t1_n2) = (n2, divmod(n1, n2))\n n2 = t1_n2[1]\n r [+]= t1_n2[0]\n R r\n\nprint(r2cf(1, 2))\nprint(r2cf(3, 1))\nprint(r2cf(23, 8))\nprint(r2cf(13, 11))\nprint(r2cf(22, 7))\nprint(r2cf(14142, 10000))\nprint(r2cf(141421, 100000))\nprint(r2cf(1414214, 1000000))\nprint(r2cf(14142136, 10000000))\n", "language": "11l" }, { "code": "with ada.text_io; use ada.text_io;\nwith ada.strings; use ada.strings;\nwith ada.strings.fixed; use ada.strings.fixed;\n\nprocedure continued_fraction_from_rational is\n\n -- The following implementation of r2cf both modifies its arguments\n -- and returns a value.\n function r2cf (N1 : in out integer;\n N2 : in out integer)\n return integer\n is\n q, r : integer;\n begin\n -- We will use floor division, where the quotient is rounded\n -- towards negative infinity. Whenever the divisor is positive,\n -- this type of division gives a non-negative remainder.\n r := N1 mod N2;\n q := (N1 - r) / N2;\n\n N1 := N2;\n N2 := r;\n\n return q;\n end r2cf;\n\n procedure write_r2cf (N1 : in integer;\n N2 : in integer)\n is\n M1, M2 : integer;\n digit : integer;\n sep : integer;\n begin\n put (trim (integer'image (N1), left));\n put (\"/\");\n put (trim (integer'image (N2), left));\n put (\" => \");\n\n M1 := N1;\n M2 := N2;\n sep := 0;\n while M2 /= 0 loop\n digit := r2cf (M1, M2);\n if sep = 0 then\n put (\"[\");\n sep := 1;\n elsif sep = 1 then\n put (\"; \");\n sep := 2;\n else\n put (\", \");\n end if;\n put (trim (integer'image (digit), left));\n end loop;\n put_line (\"]\");\n end write_r2cf;\n\nbegin\n\n write_r2cf (1, 2);\n write_r2cf (3, 1);\n write_r2cf (23, 8);\n write_r2cf (13, 11);\n write_r2cf (22, 7);\n write_r2cf (-151, 77);\n\n write_r2cf (14142, 10000);\n write_r2cf (141421, 100000);\n write_r2cf (1414214, 1000000);\n write_r2cf (14142136, 10000000);\n\n write_r2cf (31, 10);\n write_r2cf (314, 100);\n write_r2cf (3142, 1000);\n write_r2cf (31428, 10000);\n write_r2cf (314285, 100000);\n write_r2cf (3142857, 1000000);\n write_r2cf (31428571, 10000000);\n write_r2cf (314285714, 100000000);\n\nend continued_fraction_from_rational;\n", "language": "Ada" }, { "code": "BEGIN # construct continued fraction representations of rational numbers #\n # Translated from the C sample #\n # Uses code from the Arithmetic/Rational task #\n\n # Code from the Arithmetic/Rational task #\n # ============================================================== #\n\n MODE FRAC = STRUCT( INT num #erator#, den #ominator#);\n\n PROC gcd = (INT a, b) INT: # greatest common divisor #\n (a = 0 | b |: b = 0 | a |: ABS a > ABS b | gcd(b, a MOD b) | gcd(a, b MOD a));\n\n PROC lcm = (INT a, b)INT: # least common multiple #\n a OVER gcd(a, b) * b;\n\n PRIO // = 9; # higher then the ** operator #\n OP // = (INT num, den)FRAC: ( # initialise and normalise #\n INT common = gcd(num, den);\n IF den < 0 THEN\n ( -num OVER common, -den OVER common)\n ELSE\n ( num OVER common, den OVER common)\n FI\n );\n\n OP + = (FRAC a, b)FRAC: (\n INT common = lcm(den OF a, den OF b);\n FRAC result := ( common OVER den OF a * num OF a + common OVER den OF b * num OF b, common );\n num OF result//den OF result\n );\n\n OP - = (FRAC a, b)FRAC: a + -b,\n * = (FRAC a, b)FRAC: (\n INT num = num OF a * num OF b,\n den = den OF a * den OF b;\n INT common = gcd(num, den);\n (num OVER common) // (den OVER common)\n );\n\n OP - = (FRAC frac)FRAC: (-num OF frac, den OF frac);\n\n # ============================================================== #\n # end code from the Arithmetic/Rational task #\n\n []FRAC examples = ( 1//2, 3//1, 23//8, 13//11, 22//7, -151//77 );\n []FRAC sqrt2 = ( 14142//10000, 141421//100000, 1414214//1000000, 14142136//10000000 );\n []FRAC pi = ( 31//10, 314//100, 3142//1000, 31428//10000\n , 314285//100000, 3142857//1000000, 31428571//10000000, 314285714//100000000\n );\n\n # returns the quotient of numerator over denominator and sets #\n # numerator and denominator to the next values for #\n # the continued fraction #\n PROC r2cf = ( REF INT numerator, REF INT denominator )INT:\n IF denominator = 0\n THEN 0\n ELSE INT quotient := numerator OVER denominator;\n INT prev numerator = numerator;\n numerator := denominator;\n denominator := prev numerator MOD denominator;\n\t quotient\n FI # r2cf # ;\n # shows the continued fractions for the elements of f seq #\n PROC show r2cf = ( STRING legend, []FRAC f seq )VOID:\n BEGIN\n print( ( legend ) );\n FOR i FROM LWB f seq TO UPB f seq DO\n INT num := num OF f seq[ i ];\n INT den := den OF f seq[ i ];\n print( ( newline, \"For N = \", whole( num , 0 ), \", D = \", whole( den , 0 ), \" :\" ) );\n WHILE den /= 0 DO\n print( ( \" \", whole( r2cf( num, den ), 0 ) ) )\n OD\n OD\n END # show r2cf # ;\n BEGIN # task #\n show r2cf( \"Running the examples :\", examples );\n\tprint( ( newline, newline ) );\n show r2cf( \"Running for root2 :\", sqrt2 );\n\tprint( ( newline, newline ) );\n\tshow r2cf( \"Running for pi :\", pi )\n END\nEND\n", "language": "ALGOL-68" }, { "code": "(*------------------------------------------------------------------*)\n\n#include \"share/atspre_staload.hats\"\n\n(*------------------------------------------------------------------*)\n(* First, let us implement a proper method of division of signed\n integers, in which the remainder is always non-negative. (I\n implement such division in my ats2-xprelude package at\n https://sourceforge.net/p/chemoelectric/ats2-xprelude and have\n copied the implementation from there.) *)\n\nextern fn {tk : tkind}\ng0int_eucliddivrem :\n (g0int tk, g0int tk) -<> @(g0int tk, g0int tk)\n\nimplement {tk}\ng0int_eucliddivrem (n, d) =\n let\n (* The C optimizer most likely will reduce these these two\n divisions to just one. They are simply synonyms for C '/' and\n '%', and perform division that rounds the quotient towards\n zero. *)\n val q0 = g0int_div (n, d)\n val r0 = g0int_mod (n, d)\n in\n (* The following calculation results in 'floor division', if the\n divisor is positive, or 'ceiling division', if the divisor is\n negative. This choice of method results in the remainder never\n being negative. *)\n if isgtez n then\n @(q0, r0)\n else if iseqz r0 then\n @(q0, r0)\n else if isltz d then\n @(succ q0, r0 - d)\n else\n @(pred q0, r0 + d)\n end\n\n(*------------------------------------------------------------------*)\n(* I implement the lazy evaluation by having r2cf explicitly create\n a thunk that returns the digits. *)\n\nfn {tk : tkind}\nstep (N1 : ref (g0int tk),\n N2 : ref (g0int tk))\n : g0int tk =\n let\n val @(q, r) = g0int_eucliddivrem (!N1, !N2)\n in\n !N1 := !N2;\n !N2 := r;\n q\n end\n\nfn {tk : tkind}\nr2cf (N1 : g0int tk,\n N2 : g0int tk)\n : () -<cloref1> Option (g0int tk) =\n let\n val N1 = ref<g0int tk> N1\n and N2 = ref<g0int tk> N2\n in\n lam () =>\n if iseqz !N2 then\n None ()\n else\n Some (step (N1, N2))\n end\n\n(*------------------------------------------------------------------*)\n\nfn {tk : tkind}\nprint_digits (f : () -<cloref1> Option (g0int tk))\n : void =\n let\n fun\n loop (sep : string)\n : void =\n case+ f () of\n | None () => println! (\"]\")\n | Some d =>\n begin\n print! sep;\n fprint_val<g0int tk> (stdout_ref, d);\n if sep = \"[\" then\n loop \"; \"\n else\n loop \", \"\n end\n in\n loop \"[\"\n end\n\nfn {tk : tkind}\nprint_continued_fraction\n (ratnum : @(g0int tk, g0int tk))\n : void =\n let\n val @(N1, N2) = ratnum\n in\n fprint_val<g0int tk> (stdout_ref, N1);\n print! \"/\";\n fprint_val<g0int tk> (stdout_ref, N2);\n print! \" => \";\n print_digits (r2cf<tk> (N1, N2))\n end\n\n(*------------------------------------------------------------------*)\n\nval test_cases =\n $list (@(1LL, 2LL),\n @(3LL, 1LL),\n @(23LL, 8LL),\n @(13LL, 11LL),\n @(22LL, 7LL),\n @(~151LL, 77LL), (* The numerator is negative. *)\n @(151LL, ~77LL), (* The denominator is negative. *)\n @(14142LL, 10000LL),\n @(141421LL, 100000LL),\n @(1414214LL, 1000000LL),\n @(14142136LL, 10000000LL),\n @(1414213562373095049LL, 1000000000000000000LL),\n @(31LL, 10LL),\n @(314LL, 100LL),\n @(3142LL, 1000LL),\n @(31428LL, 10000LL),\n @(314285LL, 100000LL),\n @(3142857LL, 1000000LL),\n @(31428571LL, 10000000LL),\n @(314285714LL, 100000000LL),\n @(3142857142857143LL, 1000000000000000LL),\n @(2200000000000000000LL, 700000000000000000LL),\n @(2200000000000000001LL, 700000000000000000LL),\n @(2200000000000000000LL, 700000000000000001LL))\n\nimplement\nmain0 () =\n let\n var p : List0 @(llint, llint)\n in\n println! ();\n print! (\"The continued fractions shown here are calculated by \");\n println! (\"'Euclidean division',\");\n println! (\"where the remainder is always non-negative:\");\n println! ();\n for (p := test_cases; ~list_is_nil p; p := list_tail p)\n print_continued_fraction<llintknd> (list_head p);\n println! ();\n println! (\"Note that [3; 6, 1] is equal to [3; 7].\");\n println! ()\n end\n\n(*------------------------------------------------------------------*)\n", "language": "ATS" }, { "code": "(*------------------------------------------------------------------*)\n(* A version that uses the ats2-xprelude package\n https://sourceforge.net/p/chemoelectric/ats2-xprelude\n\n With ats2-xprelude installed, you can run the program with\n something like:\n\n patscc -DATS_MEMALLOC_GCBDW `pkg-config --variable=PATSCCFLAGS ats2-xprelude` \\\n `pkg-config --cflags ats2-xprelude` -O2 -std=gnu2x \\\n continued-fraction-from-rational-2.dats \\\n `pkg-config --libs ats2-xprelude` -lgc -lm && ./a.out\n\n *)\n\n#include \"share/atspre_staload.hats\"\n#include \"xprelude/HATS/xprelude.hats\"\n\nstaload \"xprelude/SATS/exrat.sats\"\nstaload _ = \"xprelude/DATS/exrat.dats\"\n\nstaload \"xprelude/SATS/mpfr.sats\"\nstaload _ = \"xprelude/DATS/mpfr.dats\"\n\n(*------------------------------------------------------------------*)\n\nfn\nstep (ratnum : ref exrat,\n done : ref bool)\n : exrat =\n let\n (* Effectively we are doing the same thing as if we used integer\n floor division and the denominator were kept positive. *)\n val q = floor !ratnum\n val diff = !ratnum - q\n in\n if iseqz diff then\n begin\n !done := true;\n q\n end\n else\n begin\n !ratnum := reciprocal diff;\n q\n end\n end\n\nfn\nr2cf (ratnum : exrat)\n : () -<cloref1> Option exrat =\n let\n val ratnum = ref<exrat> ratnum\n and done = ref<bool> false\n in\n lam () =>\n if !done then\n None ()\n else\n Some (step (ratnum, done))\n end\n\n(*------------------------------------------------------------------*)\n\nfn\nprint_digits (f : () -<cloref1> Option exrat)\n : void =\n let\n fun\n loop (sep : string)\n : void =\n case+ f () of\n | None () => println! (\"]\")\n | Some d =>\n begin\n print! (sep, d);\n if sep = \"[\" then\n loop \"; \"\n else\n loop \", \"\n end\n in\n loop \"[\"\n end\n\nfn {tk : tkind}\nprint_continued_fraction\n (ratnum : exrat)\n : void =\n begin\n print! (ratnum, \" => \");\n print_digits (r2cf ratnum)\n end\n\n(*------------------------------------------------------------------*)\n\n(* The number of bits in the significand of an IEEE binary256\n floating point number. *)\n#define OCTUPLE_PREC 237\n\nimplement\nmain0 () =\n begin\n print_continued_fraction (exrat_make (1, 2));\n print_continued_fraction (exrat_make (3, 1));\n print_continued_fraction (exrat_make (23, 8));\n print_continued_fraction (exrat_make (13, 11));\n print_continued_fraction (exrat_make (22, 7));\n print_continued_fraction (exrat_make (~151, 77));\n let\n val sqrt2 : mpfr = mpfr_SQRT2 OCTUPLE_PREC\n val sqrt2 : exrat = g0f2f sqrt2\n in\n println! (\"Octuple precision sqrt2:\");\n print_continued_fraction sqrt2\n end;\n let\n val val_22_7 : mpfr =\n mpfr_make (\"22\", OCTUPLE_PREC) / mpfr_make (\"7\", OCTUPLE_PREC)\n val val_22_7 : exrat = g0f2f val_22_7\n in\n println! (\"Octuple precision 22/7:\");\n print_continued_fraction val_22_7\n end;\n end\n\n(*------------------------------------------------------------------*)\n", "language": "ATS" }, { "code": "(*------------------------------------------------------------------*)\n\n#include \"share/atspre_staload.hats\"\n\nstaload UN = \"prelude/SATS/unsafe.sats\"\n\n(*------------------------------------------------------------------*)\n(* Continued fractions as processes for generating terms. The terms\n are memoized and are accessed by their zero-based index. The terms\n are represented as any one of the signed integer types for which\n there is a typekind. *)\n\nabstype cf (tk : tkind) = ptr\n\ntypedef cf_generator (tk : tkind) =\n () -<cloref1> Option (g0int tk)\n\nextern fn {tk : tkind}\ncf_make :\n cf_generator tk -> cf tk\n\nextern fn {tk : tkind}\n {tki : tkind}\ncf_get_at_guint :\n {i : int}\n (&cf tk >> _, g1uint (tki, i)) -> Option (g0int tk)\n\nextern fn {tk : tkind}\n {tki : tkind}\ncf_get_at_gint :\n {i : nat}\n (&cf tk >> _, g1int (tki, i)) -> Option (g0int tk)\n\noverload cf_get_at with cf_get_at_guint\noverload cf_get_at with cf_get_at_gint\noverload [] with cf_get_at\n\nextern fn {tk : tkind}\ncf2string_max_terms\n (cf : &cf tk >> _,\n max_terms : size_t)\n : string\n\nextern fn {tk : tkind}\ncf2string_default_max_terms\n (cf : &cf tk >> _)\n : string\n\noverload cf2string with cf2string_max_terms\noverload cf2string with cf2string_default_max_terms\n\n(* - - - - - - - - - - - - - *)\n\nlocal\n\n typedef _cf (tk : tkind, terminated : bool, m : int, n : int) =\n [m <= n]\n '{\n terminated = bool terminated, (* No more terms? *)\n m = size_t m, (* The number of terms computed so far. *)\n n = size_t n, (* The size of memo storage.*)\n memo = arrayref (g0int tk, n), (* Memoized terms. *)\n gen = cf_generator tk (* A thunk to generate terms. *)\n }\n typedef _cf (tk : tkind, m : int) =\n [terminated : bool]\n [n : int | m <= n]\n _cf (tk, terminated, m, n)\n typedef _cf (tk : tkind) =\n [m : int]\n _cf (tk, m)\n\n fn {tk : tkind}\n _cf_get_more_terms\n {terminated : bool}\n {m : int}\n {n : int}\n {needed : int | m <= needed; needed <= n}\n (cf : _cf (tk, terminated, m, n),\n needed : size_t needed)\n : [m1 : int | m <= m1; m1 <= needed]\n [n1 : int | m1 <= n1]\n _cf (tk, m1 < needed, m1, n1) =\n let\n prval () = lemma_g1uint_param (cf.m)\n\n macdef memo = cf.memo\n\n fun\n loop {i : int | m <= i; i <= needed}\n .<needed - i>.\n (i : size_t i)\n : [m1 : int | m <= m1; m1 <= needed]\n [n1 : int | m1 <= n1]\n _cf (tk, m1 < needed, m1, n1) =\n if i = needed then\n '{\n terminated = false,\n m = needed,\n n = (cf.n),\n memo = memo,\n gen = (cf.gen)\n }\n else\n begin\n case+ (cf.gen) () of\n | None () =>\n '{\n terminated = true,\n m = i,\n n = (cf.n),\n memo = memo,\n gen = (cf.gen)\n }\n | Some term =>\n begin\n memo[i] := term;\n loop (succ i)\n end\n end\n in\n loop (cf.m)\n end\n\n fn {tk : tkind}\n _cf_update {terminated : bool}\n {m : int}\n {n : int | m <= n}\n {needed : int}\n (cf : _cf (tk, terminated, m, n),\n needed : size_t needed)\n : [terminated1 : bool]\n [m1 : int | m <= m1]\n [n1 : int | m1 <= n1]\n _cf (tk, terminated1, m1, n1) =\n let\n prval () = lemma_g1uint_param (cf.m)\n macdef memo = cf.memo\n macdef gen = cf.gen\n in\n if (cf.terminated) then\n cf\n else if needed <= (cf.m) then\n cf\n else if needed <= (cf.n) then\n _cf_get_more_terms<tk> (cf, needed)\n else\n let (* Provides about 50% more room than is needed. *)\n val n1 = needed + half needed\n val memo1 = arrayref_make_elt (n1, g0i2i 0)\n val () =\n let\n var i : [i : nat] size_t i\n in\n for (i := i2sz 0; i < (cf.m); i := succ i)\n memo1[i] := memo[i]\n end\n val cf1 =\n '{\n terminated = false,\n m = (cf.m),\n n = n1,\n memo = memo1,\n gen = (cf.gen)\n }\n in\n _cf_get_more_terms<tk> (cf1, needed)\n end\n end\n\nin (* local *)\n\n assume cf tk = _cf tk\n\n implement {tk}\n cf_make gen =\n let\n #ifndef CF_START_SIZE #then\n #define CF_START_SIZE 8\n #endif\n in\n '{\n terminated = false,\n m = i2sz 0,\n n = i2sz CF_START_SIZE,\n memo = arrayref_make_elt (i2sz CF_START_SIZE, g0i2i 0),\n gen = gen\n }\n end\n\n implement {tk} {tki}\n cf_get_at_guint {i} (cf, i) =\n let\n prval () = lemma_g1uint_param i\n val i : size_t i = g1u2u i\n val cf1 = _cf_update<tk> (cf, succ i)\n in\n cf := cf1;\n if i < (cf1.m) then\n Some (arrayref_get_at<g0int tk> (cf1.memo, i))\n else\n None ()\n end\n\n implement {tk} {tki}\n cf_get_at_gint (cf, i) =\n cf_get_at_guint<tk><sizeknd> (cf, g1i2u i)\n\nend (* local *)\n\nimplement {tk}\ncf2string_max_terms (cf, max_terms) =\n let\n fun\n loop (i : Size_t,\n cf : &cf tk >> _,\n sep : string,\n accum : string)\n : string =\n if i = max_terms then\n strptr2string (string_append (accum, \", ...]\"))\n else\n begin\n case+ cf[i] of\n | None () =>\n strptr2string (string_append (accum, \"]\"))\n | Some term =>\n let\n val term_str = tostring_val<g0int tk> term\n val accum =\n strptr2string (string_append (accum, sep, term_str))\n val sep = if sep = \"[\" then \"; \" else \", \"\n in\n loop (succ i, cf, sep, accum)\n end\n end\n in\n loop (i2sz 0, cf, \"[\", \"\")\n end\n\nimplement {tk}\ncf2string_default_max_terms cf =\n let\n #ifndef DEFAULT_CF_MAX_TERMS #then\n #define DEFAULT_CF_MAX_TERMS 20\n #endif\n in\n cf2string_max_terms (cf, i2sz DEFAULT_CF_MAX_TERMS)\n end\n\n(*------------------------------------------------------------------*)\n(* r2cf: transform a rational number to a continued fraction. *)\n\nextern fn {tk : tkind}\nr2cf :\n (g0int tk, g0int tk) -> cf tk\n\n(* - - - - - - - - - - - - - *)\n\nimplement {tk}\nr2cf (n, d) =\n let\n val n = ref<g0int tk> n\n val d = ref<g0int tk> d\n\n fn\n gen () :<cloref1> Option (g0int tk) =\n if iseqz !d then\n None ()\n else\n let\n (* The method of rounding the quotient seems unimportant,\n and so let us simply use the truncation towards zero\n that is native to C. *)\n val numer = !n\n and denom = !d\n val q = numer / denom\n and r = numer mod denom\n in\n !n := denom;\n !d := r;\n Some q\n end\n in\n cf_make gen\n end\n\n(*------------------------------------------------------------------*)\n\nval some_rationals =\n $list (@(1LL, 2LL),\n @(3LL, 1LL),\n @(23LL, 8LL),\n @(13LL, 11LL),\n @(22LL, 7LL),\n @(~151LL, 77LL),\n @(14142LL, 10000LL),\n @(141421LL, 100000LL),\n @(1414214LL, 1000000LL),\n @(14142136LL, 10000000LL),\n @(1414213562373095049LL, 1000000000000000000LL),\n @(31LL, 10LL),\n @(314LL, 100LL),\n @(3142LL, 1000LL),\n @(31428LL, 10000LL),\n @(314285LL, 100000LL),\n @(3142857LL, 1000000LL),\n @(31428571LL, 10000000LL),\n @(314285714LL, 100000000LL),\n @(3142857142857143LL, 1000000000000000LL))\n\nimplement\nmain0 () =\n let\n var p : List0 @(llint, llint)\n in\n for (p := some_rationals; ~list_is_nil p; p := list_tail p)\n let\n val @(n, d) = list_head<@(llint, llint)> p\n var cf = r2cf (n, d)\n in\n println! (n, \"/\", d, \" => \", cf2string cf)\n end\n end\n\n(*------------------------------------------------------------------*)\n", "language": "ATS" }, { "code": "(* Continued fractions as non-linear lazy lists (stream types).\n\n I avoid the shorthands stream_make_nil and stream_make_cons,\n so the thunk-making is visible. *)\n\n#include \"share/atspre_staload.hats\"\n\ntypedef cf (tk : tkind) = stream (g0int tk)\n\nextern fn {tk : tkind}\nr2cf : (g0int tk, g0int tk) -> cf tk\n\nextern fn {tk : tkind}\ncf2string : cf tk -> string\n\nimplement {tk}\nr2cf (n, d) =\n let\n fun\n recurs (n : g0int tk,\n d : g0int tk)\n : cf tk =\n if iseqz d then\n $delay stream_nil ()\n else\n let\n val q = n / d\n and r = n mod d\n in\n $delay stream_cons (q, recurs (d, r))\n end\n in\n recurs (n, d)\n end\n\nimplement {tk}\ncf2string cf =\n let\n val max_terms = 2000\n\n fun\n loop (i : intGte 0,\n cf : cf tk,\n slist : List0 string)\n : List0 string =\n (* One has to say \"!cf\" instead of just \"cf\", to force the lazy\n evaluation. If you simply wrote \"cf\", typechecking would\n fail. *)\n case+ !cf of\n | stream_nil () => list_cons (\"]\", slist)\n | stream_cons (term, cf) =>\n if i = max_terms then\n list_cons (\",...]\", slist)\n else\n let\n val sep_str =\n case+ i of\n | 0 => \"\"\n | 1 => \";\"\n | _ => \",\"\n val term_str = tostring_val<g0int tk> term\n val slist = list_cons (term_str,\n list_cons (sep_str, slist))\n in\n loop (succ i, cf, slist)\n end\n\n val slist = loop (0, cf, list_sing \"[\")\n val slist = list_vt2t (reverse slist)\n in\n strptr2string (stringlst_concat slist)\n end\n\nfn {tk : tkind}\nshow (n : g0int tk,\n d : g0int tk)\n : void =\n begin\n print! (tostring_val<g0int tk> n);\n print! \"/\";\n print! (tostring_val<g0int tk> d);\n print! \" => \";\n println! (cf2string<tk> (r2cf<tk> (n, d)))\n end\n\nimplement\nmain () =\n begin\n show<intknd> (1, 2);\n show<lintknd> (g0i2i 3, g0i2i 1);\n show<llintknd> (g0i2i 23, g0i2i 8);\n show (13, 11);\n show (22L, 11L);\n show (~151LL, 77LL);\n show (14142LL, 10000LL);\n show (141421LL, 100000LL);\n show (1414214LL, 1000000LL);\n show (14142136LL, 10000000LL);\n show (1414213562373095049LL, 1000000000000000000LL);\n show (31LL, 10LL);\n show (314LL, 100LL);\n show (3142LL, 1000LL);\n show (31428LL, 10000LL);\n show (314285LL, 100000LL);\n show (3142857LL, 1000000LL);\n show (31428571LL, 10000000LL);\n show (314285714LL, 100000000LL);\n show (3142857142857143LL, 1000000000000000LL);\n 0\n end;\n", "language": "ATS" }, { "code": "(* Continued fractions as linear lazy lists (stream_vt types).\n\n I use the shorthands stream_vt_make_nil and stream_vt_make_cons,\n rather than explicitly write \"$ldelay\". To see how the shorthands\n are implemented, see prelude/DATS/stream_vt.dats *)\n\n#include \"share/atspre_staload.hats\"\n\nvtypedef cf_vt (tk : tkind) = stream_vt (g0int tk)\n\nextern fn {tk : tkind}\nr2cf_vt : (g0int tk, g0int tk) -> cf_vt tk\n\n(* Note that cf_vt2strptr CONSUMES the stream. The stream will no\n longer exist.\n\n If you are using linear streams, I would imagine you might want to\n (for instance) convert to list_vt the parts you want to reuse. *)\nextern fn {tk : tkind}\ncf_vt2strptr : cf_vt tk -> Strptr1\n\nimplement {tk}\nr2cf_vt (n, d) =\n let\n typedef integer = g0int tk\n fun\n recurs (n : integer,\n d : integer)\n : cf_vt tk =\n if iseqz d then\n stream_vt_make_nil<integer> ()\n else\n let\n val q = n / d\n and r = n mod d\n in\n stream_vt_make_cons<integer> (q, recurs (d, r))\n end\n in\n recurs (n, d)\n end\n\nimplement {tk}\ncf_vt2strptr cf =\n let\n val max_terms = 2000\n\n typedef integer = g0int tk\n\n fun\n loop (i : intGte 0,\n cf : cf_vt tk,\n slist : List0_vt Strptr1)\n : List0_vt Strptr1 =\n let\n val cf_con = !cf (* Force evaluation. *)\n in\n case+ cf_con of\n | ~ stream_vt_nil () => list_vt_cons (copy \"]\", slist)\n | ~ stream_vt_cons (term, tail) =>\n if i = max_terms then\n let\n val slist = list_vt_cons (copy \",...]\", slist)\n in\n ~ tail;\n slist\n end\n else\n let\n val sep_str =\n copy ((case+ i of\n | 0 => \"\"\n | 1 => \";\"\n | _ => \",\") : string)\n val term_str = tostrptr_val<g0int tk> term\n val slist = list_vt_cons (term_str,\n list_vt_cons (sep_str, slist))\n in\n loop (succ i, tail, slist)\n end\n end\n\n val slist = loop (0, cf, list_vt_sing (copy \"[\"))\n val slist = reverse slist\n val s = strptrlst_concat slist\n val () = assertloc (isneqz s)\n in\n s\n end\n\nfn {tk : tkind}\nshow (n : g0int tk,\n d : g0int tk)\n : void =\n let\n val n_str = tostrptr_val<g0int tk> n\n and d_str = tostrptr_val<g0int tk> d\n and cf_str = cf_vt2strptr<tk> (r2cf_vt<tk> (n, d))\n in\n print! n_str;\n print! \"/\";\n print! d_str;\n print! \" => \";\n println! cf_str;\n strptr_free n_str;\n strptr_free d_str;\n strptr_free cf_str\n end\n\nimplement\nmain () =\n begin\n show<intknd> (1, 2);\n show<lintknd> (g0i2i 3, g0i2i 1);\n show<llintknd> (g0i2i 23, g0i2i 8);\n show (13, 11);\n show (22L, 11L);\n show (~151LL, 77LL);\n show (14142LL, 10000LL);\n show (141421LL, 100000LL);\n show (1414214LL, 1000000LL);\n show (14142136LL, 10000000LL);\n show (1414213562373095049LL, 1000000000000000000LL);\n show (31LL, 10LL);\n show (314LL, 100LL);\n show (3142LL, 1000LL);\n show (31428LL, 10000LL);\n show (314285LL, 100000LL);\n show (3142857LL, 1000000LL);\n show (31428571LL, 10000000LL);\n show (314285714LL, 100000000LL);\n show (3142857142857143LL, 1000000000000000LL);\n 0\n end;\n", "language": "ATS" }, { "code": "#include<stdio.h>\n\ntypedef struct{\n\tint num,den;\n\t}fraction;\n\nfraction examples[] = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}};\nfraction sqrt2[] = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}};\nfraction pi[] = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {31428571,10000000}, {314285714,100000000}};\n\nint r2cf(int *numerator,int *denominator)\n{\n\tint quotient=0,temp;\n\t\n\tif(denominator != 0)\n\t{\n\t\tquotient = *numerator / *denominator;\n\t\t\n\t\ttemp = *numerator;\n\t\t\n\t\t*numerator = *denominator;\n\t\t\n\t\t*denominator = temp % *denominator;\n\t}\n\t\n\treturn quotient;\n}\n\nint main()\n{\n\tint i;\n\t\n\tprintf(\"Running the examples :\");\n\t\n\tfor(i=0;i<sizeof(examples)/sizeof(fraction);i++)\n\t{\n\t\tprintf(\"\\nFor N = %d, D = %d :\",examples[i].num,examples[i].den);\n\t\t\n\t\twhile(examples[i].den != 0){\n\t\t\tprintf(\" %d \",r2cf(&examples[i].num,&examples[i].den));\n\t\t\t}\n\t}\n\t\n\tprintf(\"\\n\\nRunning for %c2 :\",251); /* 251 is the ASCII code for the square root symbol */\n\t\n\tfor(i=0;i<sizeof(sqrt2)/sizeof(fraction);i++)\n\t{\n\t\tprintf(\"\\nFor N = %d, D = %d :\",sqrt2[i].num,sqrt2[i].den);\n\t\t\n\t\twhile(sqrt2[i].den != 0){\n\t\t\tprintf(\" %d \",r2cf(&sqrt2[i].num,&sqrt2[i].den));\n\t\t\t}\n\t}\n\t\n\tprintf(\"\\n\\nRunning for %c :\",227); /* 227 is the ASCII code for Pi's symbol */\n\t\n\tfor(i=0;i<sizeof(pi)/sizeof(fraction);i++)\n\t{\n\t\tprintf(\"\\nFor N = %d, D = %d :\",pi[i].num,pi[i].den);\n\t\t\n\t\twhile(pi[i].den != 0){\n\t\t\tprintf(\" %d \",r2cf(&pi[i].num,&pi[i].den));\n\t\t\t}\n\t}\n\t\n\t\n\t\n\treturn 0;\n}\n\t\t\t\t\n", "language": "C" }, { "code": "#include <iostream>\n/* Interface for all Continued Fractions\n Nigel Galloway, February 9th., 2013.\n*/\nclass ContinuedFraction {\n\tpublic:\n\tvirtual const int nextTerm(){};\n\tvirtual const bool moreTerms(){};\n};\n/* Create a continued fraction from a rational number\n Nigel Galloway, February 9th., 2013.\n*/\nclass r2cf : public ContinuedFraction {\n\tprivate: int n1, n2;\n\tpublic:\n\tr2cf(const int numerator, const int denominator): n1(numerator), n2(denominator){}\n\tconst int nextTerm() {\n\t\tconst int thisTerm = n1/n2;\n\t\tconst int t2 = n2; n2 = n1 - thisTerm * n2; n1 = t2;\n\t\treturn thisTerm;\n\t}\n\tconst bool moreTerms() {return fabs(n2) > 0;}\n};\n/* Generate a continued fraction for sqrt of 2\n Nigel Galloway, February 9th., 2013.\n*/\nclass SQRT2 : public ContinuedFraction {\n\tprivate: bool first=true;\n\tpublic:\n\tconst int nextTerm() {if (first) {first = false; return 1;} else return 2;}\n\tconst bool moreTerms() {return true;}\n};\n", "language": "C++" }, { "code": "int main() {\n\tfor(r2cf n(1,2); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n\tstd::cout << std::endl;\n\tfor(r2cf n(3,1); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n\tstd::cout << std::endl;\n\tfor(r2cf n(23,8); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n\tstd::cout << std::endl;\n\tfor(r2cf n(13,11); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n\tstd::cout << std::endl;\n\tfor(r2cf n(22,7); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n\tstd::cout << std::endl;\n\tfor(r2cf cf(-151,77); cf.moreTerms(); std::cout << cf.nextTerm() << \" \");\n\tstd::cout << std::endl;\n\treturn 0;\n}\n", "language": "C++" }, { "code": "int main() {\n\tint i = 0;\n\tfor(SQRT2 n; i++ < 20; std::cout << n.nextTerm() << \" \");\n\tstd::cout << std::endl;\n\tfor(r2cf n(14142,10000); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n\tstd::cout << std::endl;\n\tfor(r2cf n(14142136,10000000); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n\tstd::cout << std::endl;\n\treturn 0;\n}\n", "language": "C++" }, { "code": "int main() {\n for(r2cf n(31,10); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n std::cout << std::endl;\n for(r2cf n(314,100); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n std::cout << std::endl;\n for(r2cf n(3142,1000); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n std::cout << std::endl;\n for(r2cf n(31428,10000); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n std::cout << std::endl;\n for(r2cf n(314285,100000); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n std::cout << std::endl;\n for(r2cf n(3142857,1000000); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n std::cout << std::endl;\n for(r2cf n(31428571,10000000); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n std::cout << std::endl;\n for(r2cf n(314285714,100000000); n.moreTerms(); std::cout << n.nextTerm() << \" \");\n std::cout << std::endl;\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n static IEnumerable<int> r2cf(int n1, int n2)\n {\n while (Math.Abs(n2) > 0)\n {\n int t1 = n1 / n2;\n int t2 = n2;\n n2 = n1 - t1 * n2;\n n1 = t2;\n yield return t1;\n }\n }\n\n static void spit(IEnumerable<int> f)\n {\n foreach (int n in f) Console.Write(\" {0}\", n);\n Console.WriteLine();\n }\n\n static void Main(string[] args)\n {\n spit(r2cf(1, 2));\n spit(r2cf(3, 1));\n spit(r2cf(23, 8));\n spit(r2cf(13, 11));\n spit(r2cf(22, 7));\n spit(r2cf(-151, 77));\n for (int scale = 10; scale <= 10000000; scale *= 10)\n {\n spit(r2cf((int)(Math.Sqrt(2) * scale), scale));\n }\n spit(r2cf(31, 10));\n spit(r2cf(314, 100));\n spit(r2cf(3142, 1000));\n spit(r2cf(31428, 10000));\n spit(r2cf(314285, 100000));\n spit(r2cf(3142857, 1000000));\n spit(r2cf(31428571, 10000000));\n spit(r2cf(314285714, 100000000));\n }\n}\n", "language": "C-sharp" }, { "code": "(defn r2cf [n d]\n (if-not (= d 0) (cons (quot n d) (lazy-seq (r2cf d (rem n d))))))\n\n; Example usage\n(def demo '((1 2)\n (3 1)\n (23 8)\n (13 11)\n (22 7)\n (-151 77)\n (14142 10000)\n (141421 100000)\n (1414214 1000000)\n (14142136 10000000)\n (31 10)\n (314 100)\n (3142 1000)\n (31428 10000)\n (314285 100000)\n (3142857 1000000)\n (31428571 10000000)\n (314285714 100000000)\n (3141592653589793 1000000000000000)))\n\n(doseq [inputs demo\n :let [outputs (r2cf (first inputs) (last inputs))]]\n (println inputs \";\" outputs))\n", "language": "Clojure" }, { "code": "(defun r2cf (n1 n2)\n (lambda ()\n (unless (zerop n2)\n (multiple-value-bind (t1 r)\n (floor n1 n2)\n (setf n1 n2 n2 r)\n t1))))\n\n;; Example usage\n\n(defun demo-generator (numbers)\n (let* ((n1 (car numbers))\n (n2 (cadr numbers))\n (gen (r2cf n1 n2)))\n (format t \"~S ; ~S~%\"\n `(r2cf ,n1 ,n2)\n (loop\n :for r = (funcall gen)\n :until (null r)\n :collect r))))\n\n(mapcar #'demo-generator\n '((1 2)\n (3 1)\n (23 8)\n (13 11)\n (22 7)\n (-151 77)\n (14142 10000)\n (141421 100000)\n (1414214 1000000)\n (14142136 10000000)\n (31 10)\n (314 100)\n (3142 1000)\n (31428 10000)\n (314285 100000)\n (3142857 1000000)\n (31428571 10000000)\n (314285714 100000000)\n (3141592653589793 1000000000000000)))\n", "language": "Common-Lisp" }, { "code": "import std.concurrency;\nimport std.stdio;\n\nstruct Pair {\n int first, second;\n}\n\nauto r2cf(Pair frac) {\n return new Generator!int({\n auto num = frac.first;\n auto den = frac.second;\n while (den != 0) {\n auto div = num / den;\n auto rem = num % den;\n num = den;\n den = rem;\n div.yield();\n }\n });\n}\n\nvoid iterate(Generator!int seq) {\n foreach(i; seq) {\n write(i, \" \");\n }\n writeln();\n}\n\nvoid main() {\n auto fracs = [\n Pair( 1, 2),\n Pair( 3, 1),\n Pair( 23, 8),\n Pair( 13, 11),\n Pair( 22, 7),\n Pair(-151, 77),\n ];\n foreach(frac; fracs) {\n writef(\"%4d / %-2d = \", frac.first, frac.second);\n frac.r2cf.iterate;\n }\n writeln;\n\n auto root2 = [\n Pair( 14_142, 10_000),\n Pair( 141_421, 100_000),\n Pair( 1_414_214, 1_000_000),\n Pair(14_142_136, 10_000_000),\n ];\n writeln(\"Sqrt(2) ->\");\n foreach(frac; root2) {\n writef(\"%8d / %-8d = \", frac.first, frac.second);\n frac.r2cf.iterate;\n }\n writeln;\n\n auto pi = [\n Pair( 31, 10),\n Pair( 314, 100),\n Pair( 3_142, 1_000),\n Pair( 31_428, 10_000),\n Pair( 314_285, 100_000),\n Pair( 3_142_857, 1_000_000),\n Pair( 31_428_571, 10_000_000),\n Pair(314_285_714, 100_000_000),\n ];\n writeln(\"Pi ->\");\n foreach(frac; pi) {\n writef(\"%9d / %-9d = \", frac.first, frac.second);\n frac.r2cf.iterate;\n }\n}\n", "language": "D" }, { "code": "function GetNextFraction(var N1,N2: integer): integer;\n{Get next step in fraction series}\nvar R: integer;\nbegin\nR:=FloorMod(N1, N2);\nResult:= FloorDiv(N1 - R , N2);\nN1 := N2;\nN2 := R;\nend;\n\nprocedure GetFractionList(N1,N2: integer; var IA: TIntegerDynArray);\n{Get list of continuous fraction values}\nvar M1, M2,F : integer;\nvar S: integer;\nbegin\nSetLength(IA,0);\nM1 := N1;\nM2 := N2;\nwhile M2<>0 do\n\tbegin\n\tF:=GetNextFraction(M1,M2);\n\tSetLength(IA,Length(IA)+1);\n\tIA[High(IA)]:=F;\n\tend;\nend;\n\n\nprocedure ShowConFraction(Memo: TMemo; N1,N2: integer);\n{Calculate and display continues fraction for Rational number N1/N2}\nvar I: integer;\nvar S: string;\nvar IA: TIntegerDynArray;\nbegin\nGetFractionList(N1,N2,IA);\nS:='[';\nfor I:=0 to High(IA) do\n\tbegin\n\tif I>0 then S:=S+', ';\n\tS:=S+IntToStr(IA[I]);\n\tend;\nS:=S+']';\nMemo.Lines.Add(Format('%10d / %10d --> ',[N1,N2])+S);\nend;\n\n\nprocedure ShowContinuedFractions(Memo: TMemo);\n{Show all continued fraction tests}\nbegin\nMemo.Lines.Add('Wikipedia Example');\nShowConFraction(Memo,415,93);\n\nMemo.Lines.Add('');\nMemo.Lines.Add('Rosetta Code Examples');\nShowConFraction(Memo,1, 2);\nShowConFraction(Memo,3, 1);\nShowConFraction(Memo,23, 8);\nShowConFraction(Memo,13, 11);\nShowConFraction(Memo,22, 7);\nShowConFraction(Memo,-151, 77);\n\n\nMemo.Lines.Add('');\nMemo.Lines.Add('Square Root of Two');\nShowConFraction(Memo,14142, 10000);\nShowConFraction(Memo,141421, 100000);\nShowConFraction(Memo,1414214, 1000000);\nShowConFraction(Memo,14142136, 10000000);\n\nMemo.Lines.Add('');\nMemo.Lines.Add('PI');\nShowConFraction(Memo,31, 10);\nShowConFraction(Memo,314, 100);\nShowConFraction(Memo,3142, 1000);\nShowConFraction(Memo,31428, 10000);\nShowConFraction(Memo,314285, 100000);\nShowConFraction(Memo,3142857, 1000000);\nShowConFraction(Memo,31428571, 10000000);\nShowConFraction(Memo,314285714, 100000000);\nend;\n", "language": "Delphi" }, { "code": " [Continued fractions from rationals.\n EDSAC program, Initial Orders 2.]\n\n [Memory usage:\n 56..109 Print subroutine, modified from the EDSAC library\n 110..146 Division subroutine for long positive integers\n 148..196 Continued fraction subroutine, as specified by Rosetta Code\n 200..260 Main routine\n 262.. List of rationals, variable number of items]\n\n [Define where to store the list of rationals.]\n T 45 K [store address in location 45;\n values are then accessed by code letter H (*)]\n P 262 F [<------ address here]\n [(*) Arbitrary choice. We could equally well use 46 and N, 47 and M, etc.]\n\n [Library subroutine R2. Reads positive integers during input of orders,\n and is then overwritten (so doesn't take up any memory).\n Negative numbers can be input by adding 2^35.\n Each integer is followed by 'F', except the last is followed by '#TZ'.]\n GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13Z\n T #H [Tell R2 the storage location defined above]\n\n [Rationals to be read by R2. First item is count, then num/den pairs.]\n 8F 1F2F 3F1F 33F8F 13F11F 22F7F 34359738217F77F\n 141421356F100000000F 314285714F100000000#TZ\n\n [----------------------------------------------------------------------\n Modification of library subroutine P7.\n Prints signed integer up to 10 digits, left-justified.\n 54 storage locations; working position 4D.\n Must be loaded at an even address.\n Input: Number is at 0D.]\n T 56 K\n GKA3FT42@A49@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@TF\n H17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@\n T31@A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFSFL8FT4DE39@\n\n [----------------------------------------------------------------------\n Division subroutine for long positive integers.\n 35-bit dividend and divisor (max 2^34 - 1)\n returning quotient and remainder.\n Input: dividend at 4D, divisor at 6D\n Output: remainder at 4D, quotient at 6D.\n Working locations 0D, 8D.]\n T 110 K\n G K\n A 3 F [plant link]\n T 35 @\n A 6 D [load divisor]\n U 8 D [save at 8D (6D is required for quotient)]\n [4] T D [initialize shifted divisor]\n A 4 D [load dividend]\n R D [shift 1 right]\n S D [shifted divisor > dividend/2 yet?]\n G 13 @ [yes, start subtraction]\n T 36 @ [no, clear acc]\n A D [shift divisor 1 more]\n L D\n E 4 @ [loop back (always, since acc >= 0)]\n [13] T 36 @ [clear acc]\n T 6 D [initialize quotient to 0]\n [15] A 4 D [load remainder (initially = dividend)]\n S D [trial subtraction]\n G 23 @ [skip if can't subtract]\n T 4 D [update remainder]\n A 6 D [load quotient]\n Y F [add 1 by rounding twice (*)]\n Y F\n T 6 D\n [23] T 36 @ [clear acc]\n A 8 D [load original divisor]\n S D [is shifted divisor back to original?]\n E 35 @ [yes, exit (with accumulator = 0,\n in accordance with EDSAC convention)]\n T 36 @ [no, clear acc]\n A D [shift divisor 1 right]\n R D\n T D\n A 6 D [shift quotient 1 left]\n L D\n T 6 D\n E 15 @ [loop back (always, since acc = 0)]\n [35] E F [return; order set up at runtime]\n [36] P F [junk word, to clear accumulator]\n\n [(*) This saves the bother of defining a double-word constant 1\n and making sure that it's at an even address.]\n\n [----------------------------------------------------------------------\n Subroutine for lazy evaluation of continued fraction.\n Must be loaded at an even address.\n Locations relative to start of subroutine:\n 0: Entry point\n 1: Flag, < 0 if c.f. is finished, >= 0 if there's another term\n 2, 3: Next term of c.f., provided the flag (location 1) is >= 0\n 4, 5: Caller places numerator here before first call\n 6, 7: Caller places denominator here before first call; must be > 0\n\n After setting up the numerator and denominator of the rational number,\n the caller should repeatedly call location 0, reading the result\n from location 1 and double location 2.\n Locations 4..7 are maintained by the subroutine and should not be changed\n by the caller until a new continued fraction is required.]\n\n T 46 K [place address of subroutine in location 46]\n P 148 F\n E 25 K [load the code below to that address (WWG page 18)]\n T N\n G K\n [0] G 8 @ [entry point]\n [1] P F [flag returned here]\n [2] P F P F [term returned here, if flag >= 0;\n also used as temporary store]\n [4] P F P F [caller puts numerator here]\n [6] P F P F [caller puts denominator here]\n [8] A 3 F [plant link]\n T 28 @\n S 6#@ [load negative of denominator]\n E 44 @ [if denom <= 0, no more terms]\n T F [clear acc]\n A 4#@ [load numerator]\n T 2#@ [save before overwriting]\n A 6#@ [load denominator]\n U 4#@ [make it numerator for next call]\n T 6 D [also to 6D for division]\n A 2#@ [load numerator]\n G 29 @ [special action if negative]\n T 4 D [to 4D for division]\n [21] A 21 @ [for return from next]\n G 110 F [call the above division subroutine]\n A 4 D [load remainder]\n T 6#@ [make it denominator for next call]\n A 6 D [load quotient]\n [26] T 2#@ [return it as next term]\n [27] T 1 @ [flag >= 0 means term is valid]\n [28] E F [exit with acc = 0]\n\n [Here if rational = -n/d where n, d > 0. Principle is:\n if n + d - 1 = qd + r then -n = -qd + (d - 1 - r)]\n [29] T 4 D [save numerator in 4D]\n S 6 D [acc := -den]\n Y F [add 1 by rounding twice]\n Y F\n T 2#@ [save (1 - den) for later]\n S 4 D [load abs(num)]\n S 2#@ [add (den - 1)]\n T 4 D [to 4D for division]\n [37] A 37 @ [for return from next]\n G 110 F [call the above division subroutine]\n S 2#@ [load (den - 1)]\n S 4 D [subtract remainder]\n T 6#@ [result is new denominator]\n S 6 D [load negated quotient]\n G 26 @ [join common code]\n\n [Here if there are no more terms of the c.f.]\n [44] T F [clear acc]\n A 8 @ [this is negative since 'A' = -4]\n G 27 @ [exit with negative flag]\n\n [----------------------------------------------------------------------\n Main routine]\n T 200 K\n G K\n [Variables]\n [0] P F [negative counter of continued fractions]\n [1] P F [character before term, first '=' then ',']\n [Constants]\n [2] P D [single-word 1]\n [3] A 2#H [order to load first numerator]\n [4] P 2 F [to inc addresses by 2]\n [5] # F [teleprinter figures shift]\n [6] X F [slash (in figures mode)]\n [7] V F [equals sign (in figures mode)]\n [8] N F [comma (in figures mode)]\n [9] ! F [space]\n [10] @ F [carriage return]\n [11] & F [line feed]\n [12] K4096 F [teleprinter null]\n\n [Enter with acc = 0]\n [13] O 5 @ [set teleprinter to figures]\n S H [negative of number of c.f.s]\n T @ [initialize counter]\n A 3 @ [initial load order]\n [17] U 22 @ [plant order to load numerator]\n A 4 @ [inc address by 2]\n T 28 @ [plant order to load denominator]\n A 7 @ [set to print '=' before first term]\n T 1 @\n\n [Demonstrate the subroutine above.\n Since its address was placed in location 46,\n we can use code letter N to refer to it.]\n [22] A #H [load numerator (order set up at runtime)]\n U 4#N [pass to subroutine]\n T D [also to 0D for printing]\n [25] A 25 @ [for return from print subroutine]\n G 56 F [print numerator]\n O 6 @ [followed by slash]\n [28] A #H [load denominator (order set up at runtime)]\n U 6#N [pass to subroutine]\n T D [also to 0D for printing]\n [31] A 31 @ [for return from print subroutine]\n G 56 F [print denominator]\n O 9 @ [followed by space]\n [34] A 34 @ [for return from subroutine]\n G N [call subroutine for next term]\n A 1 N [load flag]\n G 48 @ [if < 0, c.f. is finished, jump out]\n O 1 @ [print equals or comma]\n O 9 @ [print space]\n T F [clear acc]\n A 2#N [load term]\n T D [to 0D for printing]\n [43] A 43 @ [for return from print subroutine]\n G 56 F [print term; clears acc]\n A 8 @ [set to print ',' before subsequent terms]\n T 1 @\n E 34 @ [loop back for next term]\n\n [On to next continued fraction]\n [48] O 10 @ [print new line]\n O 11 @\n T F [clear acc]\n A @ [load negative count of c.f.s]\n A 2 @ [add 1]\n E 59 @ [exit if count = 0]\n T @ [store back]\n A 22 @ [order to load numerator]\n A 4 @ [inc address by 4 for next c.f.]\n A 4 @\n G 17 @ [loop back (always, since 'A' < 0)]\n\n [59] O 12 @ [print null to flush teleprinter buffer]\n Z F [stop]\n\n E 13 Z [define entry point]\n P F [acc = 0 on entry]\n", "language": "EDSAC-order-code" }, { "code": "let rec r2cf n d =\n if d = LanguagePrimitives.GenericZero then []\n else let q = n / d in q :: (r2cf d (n - q * d))\n\n[<EntryPoint>]\nlet main argv =\n printfn \"%A\" (r2cf 1 2)\n printfn \"%A\" (r2cf 3 1)\n printfn \"%A\" (r2cf 23 8)\n printfn \"%A\" (r2cf 13 11)\n printfn \"%A\" (r2cf 22 7)\n printfn \"%A\" (r2cf -151 77)\n printfn \"%A\" (r2cf 141 100)\n printfn \"%A\" (r2cf 1414 1000)\n printfn \"%A\" (r2cf 14142 10000)\n printfn \"%A\" (r2cf 141421 100000)\n printfn \"%A\" (r2cf 1414214 1000000)\n printfn \"%A\" (r2cf 14142136 10000000)\n 0\n", "language": "F-Sharp" }, { "code": "let rec rI2cf n d =\n if d = 0I then []\n else let q = n / d in (decimal)q :: (rI2cf d (n - q * d))\n", "language": "F-Sharp" }, { "code": "USING: formatting kernel lists lists.lazy math math.parser qw\nsequences ;\nIN: rosetta-code.cf-arithmetic\n\n: r2cf ( x -- lazy )\n [ >fraction [ /mod ] keep swap [ ] [ / ] if-zero nip ]\n lfrom-by [ integer? ] luntil [ >fraction /i ] lmap-lazy ;\n\n: main ( -- )\n qw{\n 1/2\n 3\n 23/8\n 13/11\n 22/7\n -151/77\n 14142/10000\n 141421/100000\n 1414214/1000000\n 14142136/10000000\n 31/10\n 314/100\n 3142/1000\n 31428/10000\n 314285/100000\n 3142857/1000000\n 31428571/10000000\n 314285714/100000000\n }\n [ dup string>number r2cf list>array \"%19s -> %u\\n\" printf ]\n each ;\n\nMAIN: main\n", "language": "Factor" }, { "code": ": r2cf ( num1 den1 -- num2 den2 ) swap over >r s>d r> sm/rem . ;\n\n: .r2cf ( num den -- )\n cr 2dup swap . .\" / \" . .\" : \"\n begin\n r2cf dup 0<> while\n repeat 2drop ;\n\n: r2cf-demo\n 1 2 .r2cf\n 3 1 .r2cf\n 23 8 .r2cf\n 13 11 .r2cf\n 22 7 .r2cf\n -151 77 .r2cf\n 14142 10000 .r2cf\n 141421 100000 .r2cf\n 1414214 1000000 .r2cf\n 14142136 10000000 .r2cf\n 31 10 .r2cf\n 314 100 .r2cf\n 3142 1000 .r2cf\n 31428 10000 .r2cf\n 314285 100000 .r2cf\n 3142857 1000000 .r2cf\n 31428571 10000000 .r2cf\n 314285714 100000000 .r2cf\n 3141592653589793 1000000000000000 .r2cf ;\nr2cf-demo\n", "language": "Forth" }, { "code": "program r2cf_demo\n implicit none\n\n call write_r2cf (1, 2)\n call write_r2cf (3, 1)\n call write_r2cf (23, 8)\n call write_r2cf (13, 11)\n call write_r2cf (22, 7)\n call write_r2cf (-151, 77)\n\n call write_r2cf (14142, 10000)\n call write_r2cf (141421, 100000)\n call write_r2cf (1414214, 1000000)\n call write_r2cf (14142136, 10000000)\n\n call write_r2cf (31, 10)\n call write_r2cf (314, 100)\n call write_r2cf (3142, 1000)\n call write_r2cf (31428, 10000)\n call write_r2cf (314285, 100000)\n call write_r2cf (3142857, 1000000)\n call write_r2cf (31428571, 10000000)\n call write_r2cf (314285714, 100000000)\n\ncontains\n\n ! This implementation of r2cf both modifies its arguments and\n ! returns a value.\n function r2cf (N1, N2) result (q)\n integer, intent(inout) :: N1, N2\n integer :: q\n\n integer r\n\n ! We will use floor division, where the quotient is rounded\n ! towards negative infinity. Whenever the divisor is positive,\n ! this type of division gives a non-negative remainder.\n r = modulo (N1, N2)\n q = (N1 - r) / N2\n\n N1 = N2\n N2 = r\n end function r2cf\n\n subroutine write_r2cf (N1, N2)\n integer, intent(in) :: N1, N2\n\n integer :: digit, M1, M2\n character(len = :), allocatable :: sep\n\n write (*, '(I0, \"/\", I0, \" => \")', advance = \"no\") N1, N2\n\n M1 = N1\n M2 = N2\n sep = \"[\"\n do while (M2 /= 0)\n digit = r2cf (M1, M2)\n write (*, '(A, I0)', advance = \"no\") sep, digit\n if (sep == \"[\") then\n sep = \"; \"\n else\n sep = \", \"\n end if\n end do\n write (*, '(\"]\")', advance = \"yes\")\n end subroutine write_r2cf\n\nend program r2cf_demo\n", "language": "Fortran" }, { "code": "'with some other constants\ndata 1,2, 21,7, 21,-7, 7,21, -7,21\ndata 23,8, 13,11, 22,7, 3035,5258, -151,-77\ndata -151,77, 77,151, 77,-151, -832040,1346269\ndata 63018038201,44560482149, 14142,10000\ndata 31,10, 314,100, 3142,1000, 31428,10000, 314285,100000\ndata 3142857,1000000, 31428571,10000000, 314285714,100000000\ndata 139755218526789,44485467702853\ndata 534625820200,196677847971, 0,0\n\nconst Inf = -(clngint(1) shl 63)\n\ntype frc\ndeclare sub init (byval a as longint, byval b as longint)\ndeclare function digit () as longint\n as longint n, d\nend type\n\n'member functions\nsub frc.init (byval a as longint, byval b as longint)\nif b < 0 then b = -b: a = -a\n n = a: d = b\nend sub\n\nfunction frc.digit as longint\ndim as longint q, r\ndigit = Inf\n\nif d then\n q = n \\ d\n r = n - q * d\n 'floordiv\n if r < 0 then q -= 1: r += d\n n = d: d = r\n\ndigit = q\nend if\nend function\n\n'main\ndim as longint a, b\ndim r2cf as frc\ndo\n print\n read a, b\n if b = 0 then exit do\n\n r2cf.init(a, b)\n do\n 'lazy evaluation\n a = r2cf.digit\n if a = Inf then exit do\n print a;\n loop\nloop\nsleep\nsystem\n", "language": "FreeBASIC" }, { "code": "package cf\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n// ContinuedFraction is a regular continued fraction.\ntype ContinuedFraction func() NextFn\n\n// NextFn is a function/closure that can return\n// a posibly infinite sequence of values.\ntype NextFn func() (term int64, ok bool)\n\n// String implements fmt.Stringer.\n// It formats a maximum of 20 values, ending the\n// sequence with \", ...\" if the sequence is longer.\nfunc (cf ContinuedFraction) String() string {\n\tvar buf strings.Builder\n\tbuf.WriteByte('[')\n\tsep := \"; \"\n\tconst maxTerms = 20\n\tnext := cf()\n\tfor n := 0; ; n++ {\n\t\tt, ok := next()\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tif n > 0 {\n\t\t\tbuf.WriteString(sep)\n\t\t\tsep = \", \"\n\t\t}\n\t\tif n >= maxTerms {\n\t\t\tbuf.WriteString(\"...\")\n\t\t\tbreak\n\t\t}\n\t\tfmt.Fprint(&buf, t)\n\t}\n\tbuf.WriteByte(']')\n\treturn buf.String()\n}\n\n// Sqrt2 is the continued fraction for √2, [1; 2, 2, 2, ...].\nfunc Sqrt2() NextFn {\n\tfirst := true\n\treturn func() (int64, bool) {\n\t\tif first {\n\t\t\tfirst = false\n\t\t\treturn 1, true\n\t\t}\n\t\treturn 2, true\n\t}\n}\n\n// Phi is the continued fraction for ϕ, [1; 1, 1, 1, ...].\nfunc Phi() NextFn {\n\treturn func() (int64, bool) { return 1, true }\n}\n\n// E is the continued fraction for e,\n// [2; 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12, ...].\nfunc E() NextFn {\n\tvar i int\n\treturn func() (int64, bool) {\n\t\ti++\n\t\tswitch {\n\t\tcase i == 1:\n\t\t\treturn 2, true\n\t\tcase i%3 == 0:\n\t\t\treturn int64(i/3) * 2, true\n\t\tdefault:\n\t\t\treturn 1, true\n\t\t}\n\t}\n}\n", "language": "Go" }, { "code": "package cf\n\nimport \"fmt\"\n\n// A Rat represents a quotient N/D.\ntype Rat struct {\n\tN, D int64\n}\n\n// String implements fmt.Stringer and returns a string\n// representation of `r` in the form \"N/D\" (even if D == 1).\nfunc (r Rat) String() string {\n\treturn fmt.Sprintf(\"%d/%d\", r.N, r.D)\n}\n\n// As ContinuedFraction returns a contined fraction representation of `r`.\nfunc (r Rat) AsContinuedFraction() ContinuedFraction { return r.CFTerms }\nfunc (r Rat) CFTerms() NextFn {\n\treturn func() (int64, bool) {\n\t\tif r.D == 0 {\n\t\t\treturn 0, false\n\t\t}\n\t\tq := r.N / r.D\n\t\tr.N, r.D = r.D, r.N-q*r.D\n\t\treturn q, true\n\t}\n}\n\n// Rosetta Code task explicitly asked for this function,\n// so here it is. We'll just use the types above instead.\nfunc r2cf(n1, n2 int64) ContinuedFraction { return Rat{n1, n2}.CFTerms }\n", "language": "Go" }, { "code": "package cf\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc Example_ConstructFromRational() {\n\tcases := [...]Rat{\n\t\t{1, 2},\n\t\t{3, 1},\n\t\t{23, 8},\n\t\t{13, 11},\n\t\t{22, 7},\n\t\t{-151, 77},\n\t}\n\tfor _, r := range cases {\n\t\tfmt.Printf(\"%7s = %s\\n\", r, r.AsContinuedFraction())\n\t}\n\n\tfor _, tc := range [...]struct {\n\t\tname string\n\t\tapprox float64\n\t\tcf ContinuedFraction\n\t\td1, d2 int64\n\t}{\n\t\t{\"√2\", math.Sqrt2, Sqrt2, 1e4, 1e8},\n\t\t{\"π\", math.Pi, nil, 10, 1e10},\n\t\t{\"ϕ\", math.Phi, Phi, 10, 1e5},\n\t\t{\"e\", math.E, E, 1e5, 1e9},\n\t} {\n\t\tfmt.Printf(\"\\nApproximating %s ≅ %v:\\n\", tc.name, tc.approx)\n\t\tfor d := tc.d1; d < tc.d2; d *= 10 {\n\t\t\tn := int64(math.Round(tc.approx * float64(d)))\n\t\t\tr := Rat{n, d}\n\t\t\tfmt.Println(r, \"=\", r.AsContinuedFraction())\n\t\t}\n\t\tif tc.cf != nil {\n\t\t\twid := int(math.Log10(float64(tc.d2)))*2 + 2 // ick\n\t\t\tfmt.Printf(\"%*s: %v\\n\", wid, \"Actual\", tc.cf)\n\t\t}\n\t}\n\n\t// Output:\n\t// [… commented output used by go test omitted for\n\t// Rosetta Code listing; it is the same as below …]\n}\n", "language": "Go" }, { "code": "import Data.Ratio ((%))\n\nreal2cf :: (RealFrac a, Integral b) => a -> [b]\nreal2cf x =\n let (i, f) = properFraction x\n in i :\n if f == 0\n then []\n else real2cf (1 / f)\n\nmain :: IO ()\nmain =\n mapM_\n print\n [ real2cf (13 % 11)\n , take 20 $ real2cf (sqrt 2)\n ]\n", "language": "Haskell" }, { "code": "procedure main ()\n write_r2cf (1, 2)\n write_r2cf (3, 1)\n write_r2cf (23, 8)\n write_r2cf (13, 11)\n write_r2cf (22, 7)\n write_r2cf (-151, 77)\n write_r2cf (14142, 10000)\n write_r2cf (141421, 100000)\n write_r2cf (1414214, 1000000)\n write_r2cf (14142136, 10000000)\n\n # Decimal expansion of sqrt(2): https://oeis.org/A002193\n write_r2cf (141421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157,\n 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)\n\n write_r2cf (31, 10)\n write_r2cf (314, 100)\n write_r2cf (3142, 1000)\n write_r2cf (31428, 10000)\n write_r2cf (314285, 100000)\n write_r2cf (3142857, 1000000)\n write_r2cf (31428571, 10000000)\n write_r2cf (314285714, 100000000)\n\n # 22/7 = 3 + 1/7 = 3 + 0.142857...\n write_r2cf (3142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857,\n 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)\nend\n\nprocedure write_r2cf (N1, N2)\n local sep, digit\n\n writes (N1, \"/\", N2, \" => \")\n sep := \"[\"\n every digit := r2cf (N1, N2) do {\n writes (sep, digit)\n sep := (if sep == \"[\" then \"; \" else \", \")\n }\n write (\"]\")\nend\n\nprocedure r2cf (N1, N2)\n local q, r\n while N2 ~= 0 do {\n # We will use Icon's native version of integer division, which\n # rounds quotients towards zero, and so may return a negative\n # remainder.\n q := N1 / N2\n r := N1 % N2\n N1 := N2\n N2 := r\n suspend q\n }\nend\n", "language": "Icon" }, { "code": "cf=: _1 1 ,@}. (, <.)@%@-/ ::]^:a:@(, <.)@(%&x:/)\n", "language": "J" }, { "code": " r2cf each 1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77\n┌───┬─┬─────┬─────┬───┬─────────────────────────────────┬─────────┐\n│0 2│3│2 1 7│1 5 2│3 7│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2│_2 25 1 2│\n└───┴─┴─────┴─────┴───┴─────────────────────────────────┴─────────┘\n", "language": "J" }, { "code": " cf each 1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77\n┌───┬─┬─────┬─────┬───┬─────────────────────────────────┬─────────┐\n│0 2│3│2 1 7│1 5 2│3 7│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2│_2 25 1 2│\n└───┴─┴─────┴─────┴───┴─────────────────────────────────┴─────────┘\n cf each 14142 10000;141421 100000;1414214 1000000;14142136 10000000\n┌──────────────────┬───────────────────────────┬────────────────────────────┬─────────────────────────────────┐\n│1 2 2 2 2 2 1 1 29│1 2 2 2 2 2 2 3 1 1 3 1 7 2│1 2 2 2 2 2 2 2 3 6 1 2 1 12│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2│\n└──────────────────┴───────────────────────────┴────────────────────────────┴─────────────────────────────────┘\n cf each 31 10;314 100;3142 1000;31428 10000;314285 100000;3142857 1000000;31428571 10000000;314285714 100000000\n┌────┬─────┬──────────┬───────┬────────┬──────────┬────────────┬───────────┐\n│3 10│3 7 7│3 7 23 1 2│3 7 357│3 7 2857│3 7 142857│3 7 476190 3│3 7 7142857│\n└────┴─────┴──────────┴───────┴────────┴──────────┴────────────┴───────────┘\n", "language": "J" }, { "code": " 3 7 =&((+ %)/) 3 7 _\n1\n", "language": "J" }, { "code": " _2 25 1 2 =&((+ %)/) _1 _1 _24 _1 _2\n1\n", "language": "J" }, { "code": "r2cf=:1 1{.\"1@}.({:,(0,{:)#:{.)^:(*@{:)^:a:\n", "language": "J" }, { "code": " ((\":@{.,'/',\":@{:),': ',\":@r2cf)@>1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77;14142 10000;141421 100000;1414214 1000000;14142136 10000000;31 10;314 100;3142 1000;31428 10000;314285 100000;3142857 1000000;31428571 10000000;314285714 100000000\n1/2: 0 2\n3/1: 3\n23/8: 2 1 7\n13/11: 1 5 2\n22/7: 3 7\n14142136/10000000: 1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2\n_151/77: _2 25 1 2\n14142/10000: 1 2 2 2 2 2 1 1 29\n141421/100000: 1 2 2 2 2 2 2 3 1 1 3 1 7 2\n1414214/1000000: 1 2 2 2 2 2 2 2 3 6 1 2 1 12\n14142136/10000000: 1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2\n31/10: 3 10\n314/100: 3 7 7\n3142/1000: 3 7 23 1 2\n31428/10000: 3 7 357\n314285/100000: 3 7 2857\n3142857/1000000: 3 7 142857\n31428571/10000000: 3 7 476190 3\n314285714/100000000: 3 7 7142857\n", "language": "J" }, { "code": "coclass'cf'\ncreate =: dyad def 'EMPTY [ N =: x , y'\ndestroy =: codestroy\nr2cf =: monad define\n if. 0 (= {:) N do. _ return. end.\n RV =. <.@:(%/) N\n N =: ({. , |/)@:|. N\n RV\n)\n\ncocurrent'base'\nCF =: conew'cf'\n\nUntil =: conjunction def 'u^:(-.@:v)^:_'\n\n(,. }.@:}:@:((,r2cf__CF)Until(_-:{:))@:(8[create__CF/)&.>)1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77\nNote 'Output'\n┌─────────────────┬─────────────────────────────────┐\n│1 2 │0 2 │\n├─────────────────┼─────────────────────────────────┤\n│3 1 │3 │\n├─────────────────┼─────────────────────────────────┤\n│23 8 │2 1 7 │\n├─────────────────┼─────────────────────────────────┤\n│13 11 │1 5 2 │\n├─────────────────┼─────────────────────────────────┤\n│22 7 │3 7 │\n├─────────────────┼─────────────────────────────────┤\n│14142136 10000000│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2│\n├─────────────────┼─────────────────────────────────┤\n│_151 77 │_2 25 1 2 │\n└─────────────────┴─────────────────────────────────┘\n)\n", "language": "J" }, { "code": "f =: 3 : 0\n a =. {.y\n b =. {:y\n out=. <. a%b\n while. b > 1 do.\n 'a b' =. b; b|a\n out=. out , <. a%b\n end.\n)\n f each 1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77\n┌───┬─┬─────┬─────┬───┬───────────────────────────────────┬─────────┐\n│0 2│3│2 1 7│1 5 2│3 7│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2 _│_2 25 1 2│\n└───┴─┴─────┴─────┴───┴───────────────────────────────────┴─────────┘\n", "language": "J" }, { "code": "r2cf=:3 :0\n 'n1 n2'=. y\n r=.''\n while.n2 do.\n 'n1 t1 n2'=. n2,(0,n2)#:n1\n r=.r,t1\n end.\n)\n", "language": "J" }, { "code": "import java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\npublic class ConstructFromRationalNumber {\n private static class R2cf implements Iterator<Integer> {\n private int num;\n private int den;\n\n R2cf(int num, int den) {\n this.num = num;\n this.den = den;\n }\n\n @Override\n public boolean hasNext() {\n return den != 0;\n }\n\n @Override\n public Integer next() {\n int div = num / den;\n int rem = num % den;\n num = den;\n den = rem;\n return div;\n }\n }\n\n private static void iterate(R2cf generator) {\n generator.forEachRemaining(n -> System.out.printf(\"%d \", n));\n System.out.println();\n }\n\n public static void main(String[] args) {\n List<Map.Entry<Integer, Integer>> fracs = List.of(\n Map.entry(1, 2),\n Map.entry(3, 1),\n Map.entry(23, 8),\n Map.entry(13, 11),\n Map.entry(22, 7),\n Map.entry(-151, 77)\n );\n for (Map.Entry<Integer, Integer> frac : fracs) {\n System.out.printf(\"%4d / %-2d = \", frac.getKey(), frac.getValue());\n iterate(new R2cf(frac.getKey(), frac.getValue()));\n }\n\n System.out.println(\"\\nSqrt(2) ->\");\n List<Map.Entry<Integer, Integer>> root2 = List.of(\n Map.entry( 14_142, 10_000),\n Map.entry( 141_421, 100_000),\n Map.entry( 1_414_214, 1_000_000),\n Map.entry(14_142_136, 10_000_000)\n );\n for (Map.Entry<Integer, Integer> frac : root2) {\n System.out.printf(\"%8d / %-8d = \", frac.getKey(), frac.getValue());\n iterate(new R2cf(frac.getKey(), frac.getValue()));\n }\n\n System.out.println(\"\\nPi ->\");\n List<Map.Entry<Integer, Integer>> pi = List.of(\n Map.entry( 31, 10),\n Map.entry( 314, 100),\n Map.entry( 3_142, 1_000),\n Map.entry( 31_428, 10_000),\n Map.entry( 314_285, 100_000),\n Map.entry( 3_142_857, 1_000_000),\n Map.entry( 31_428_571, 10_000_000),\n Map.entry(314_285_714, 100_000_000)\n );\n for (Map.Entry<Integer, Integer> frac : pi) {\n System.out.printf(\"%9d / %-9d = \", frac.getKey(), frac.getValue());\n iterate(new R2cf(frac.getKey(), frac.getValue()));\n }\n }\n}\n", "language": "Java" }, { "code": "# It'st most appropriate to define a Julia iterable object for this task\n# Julia doesn't have Python'st yield, the closest to it is produce/consume calls with Julia tasks\n# but for various reasons they don't work out for this task\n# This solution works with two integers, a Julia rational or a real\n\nmutable struct ContinuedFraction{T<:Integer}\n n1::T # numerator or real\n n2::T # denominator or 1 if real\n t1::T # generated coefficient\nend\n\n# Constructors for all possible input types\nContinuedFraction{T<:Integer}(n1::T, n2::T) = ContinuedFraction(n1, n2, 0)\nContinuedFraction(n::Rational) = ContinuedFraction(numerator(n), denominator(n))\nContinuedFraction(n::AbstractFloat) = ContinuedFraction(Rational(n))\n\n# Methods to make our object iterable\nBase.start(::ContinuedFraction) = nothing\n# Returns true if we've prepared the continued fraction\nBase.done(cf::ContinuedFraction, st) = cf.n2 == 0\n# Generates the next coefficient\nfunction Base.next(cf::ContinuedFraction, st)\n cf.n1, (cf.t1, cf.n2) = cf.n2, divrem(cf.n1, cf.n2)\n return cf.t1, nothing\nend\n\n# Tell Julia that this object always returns ints (all coeffs are integers)\nBase.eltype{T}(::Type{ContinuedFraction{T}}) = T\n\n# Overload the default collect function so that we can collect the first maxiter coeffs of infinite continued fractions\n# array slicing doesn't work as Julia crashes before the slicing due to our infinitely long array\nfunction Base.collect(itr::ContinuedFraction, maxiter::Integer = 100)\n r = Array{eltype(itr)}(maxiter)\n i = 1\n for v in itr\n r[i] = v\n i += 1\n if i > maxiter break end\n end\n return r[1:i-1]\nend\n\n# Test cases according to task description with outputs in comments\nprintln(collect(ContinuedFraction(1, 2))) # => [0, 2]\nprintln(collect(ContinuedFraction(3, 1))) # => [3]\nprintln(collect(ContinuedFraction(23, 8))) # => [2, 1, 7]\nprintln(collect(ContinuedFraction(13, 11))) # => [1, 5, 2]\nprintln(collect(ContinuedFraction(22, 7))) # => [3, 7]\nprintln(collect(ContinuedFraction(14142, 10000))) # => [1, 2, 2, 2, 2, 2, 1, 1, 29]\nprintln(collect(ContinuedFraction(141421, 100000))) # => [1, 2, 2, 2, 2, 2, 2, 3, 1, 1, 3, 1, 7, 2]\nprintln(collect(ContinuedFraction(1414214, 1000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 3, 6, 1, 2, 1, 12]\nprintln(collect(ContinuedFraction(14142136, 10000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 1, 2, 4, 1, 1, 2]\n\nprintln(collect(ContinuedFraction(13 // 11))) # => [1, 5, 2]\nprintln(collect(ContinuedFraction(√2), 20)) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]\n", "language": "Julia" }, { "code": "// version 1.1.2\n// compile with -Xcoroutines=enable flag from command line\n\nimport kotlin.coroutines.experimental.buildSequence\n\nfun r2cf(frac: Pair<Int, Int>) =\n buildSequence {\n var num = frac.first\n var den = frac.second\n while (Math.abs(den) != 0) {\n val div = num / den\n val rem = num % den\n num = den\n den = rem\n yield(div)\n }\n }\n\nfun iterate(seq: Sequence<Int>) {\n for (i in seq) print(\"$i \")\n println()\n}\n\nfun main(args: Array<String>) {\n val fracs = arrayOf(1 to 2, 3 to 1, 23 to 8, 13 to 11, 22 to 7, -151 to 77)\n for (frac in fracs) {\n print(\"${\"%4d\".format(frac.first)} / ${\"%-2d\".format(frac.second)} = \")\n iterate(r2cf(frac))\n }\n val root2 = arrayOf(14142 to 10000, 141421 to 100000,\n 1414214 to 1000000, 14142136 to 10000000)\n println(\"\\nSqrt(2) ->\")\n for (frac in root2) {\n print(\"${\"%8d\".format(frac.first)} / ${\"%-8d\".format(frac.second)} = \")\n iterate(r2cf(frac))\n }\n val pi = arrayOf(31 to 10, 314 to 100, 3142 to 1000, 31428 to 10000,\n 314285 to 100000, 3142857 to 1000000,\n 31428571 to 10000000, 314285714 to 100000000)\n println(\"\\nPi ->\")\n for (frac in pi) {\n print(\"${\"%9d\".format(frac.first)} / ${\"%-9d\".format(frac.second)} = \")\n iterate(r2cf(frac))\n }\n}\n", "language": "Kotlin" }, { "code": "divert(-1)\n\n# m4 is a recursive macro language with eager evaluation. Generally\n# there is no tail-call optimization. I shall define r2cf in a natural\n# way, rather than try to mimic call-by-reference or lazy evaluation.\n\ndefine(`r2cf',`$1/$2 => [_$0($1,$2,`')]')\ndefine(`_r2cf',\n `ifelse(eval($2 != 0),1,\n `$3eval($1 / $2)$0($2,eval($1 % $2),ifelse($3,,`; ',```,'' '))')')\n\ndivert`'dnl\ndnl\nr2cf(1, 2)\nr2cf(3, 1)\nr2cf(23, 8)\nr2cf(13, 11)\nr2cf(22, 7)\nr2cf(-151, 77)\ndnl\nr2cf(14142, 10000)\nr2cf(141421, 100000)\nr2cf(1414214, 1000000)\nr2cf(14142136, 10000000)\ndnl\nr2cf(31, 10)\nr2cf(314, 100)\nr2cf(3142, 1000)\nr2cf(31428, 10000)\nr2cf(314285, 100000)\nr2cf(3142857, 1000000)\nr2cf(31428571, 10000000)\nr2cf(314285714, 100000000)\n", "language": "M4" }, { "code": ".SILENT:\n.DEFAULT_GOAL := start-here\n\ndefine r2cf =\n\tM=`expr $(1)`; \\\n\tN=`expr $(2)`; \\\n\tprintf '%d/%d => ' $$M $$N; \\\n\tSEP='['; \\\n\twhile test $$N -ne 0; do \\\n\t\tprintf \"%s%d\" \"$$SEP\" `expr $$M '/' $$N`; \\\n\t\tif test \"$$SEP\" = '['; then SEP='; '; else SEP=', '; fi; \\\n\t\tR=`expr $$M '%' $$N`; \\\n\t\tM=$$N; \\\n\t\tN=$$R; \\\n\tdone; \\\n\tprintf ']\\n'\nendef\n\nstart-here:\n\t$(call r2cf, 1, 2)\n\t$(call r2cf, 3, 1)\n\t$(call r2cf, 23, 8)\n\t$(call r2cf, 13, 11)\n\t$(call r2cf, 22, 7)\n\t$(call r2cf, -151, 77)\n\n\t$(call r2cf, 14142, 10000)\n\t$(call r2cf, 141421, 100000)\n\t$(call r2cf, 1414214, 1000000)\n\t$(call r2cf, 14142136, 10000000)\n\n\t$(call r2cf, 31, 10)\n\t$(call r2cf, 314, 100)\n\t$(call r2cf, 3142, 1000)\n\t$(call r2cf, 31428, 10000)\n\t$(call r2cf, 314285, 100000)\n\t$(call r2cf, 3142857, 1000000)\n\t$(call r2cf, 31428571, 10000000)\n\t$(call r2cf, 314285714, 100000000)\n", "language": "Make" }, { "code": "ContinuedFraction[1/2]\nContinuedFraction[3]\nContinuedFraction[23/8]\nContinuedFraction[13/11]\nContinuedFraction[22/7]\nContinuedFraction[-151/77]\nContinuedFraction[14142/10000]\nContinuedFraction[141421/100000]\nContinuedFraction[1414214/1000000]\nContinuedFraction[14142136/10000000]\n", "language": "Mathematica" }, { "code": "%%%-------------------------------------------------------------------\n\n:- module continued_fraction_from_rational.\n\n:- interface.\n:- import_module io.\n:- pred main(io::di, io::uo) is det.\n\n:- implementation.\n:- import_module int.\n:- import_module list.\n:- import_module string.\n\n%%%-------------------------------------------------------------------\n%%%\n%%% ‘r2cf’ is a predicate, not a function. If it succeeds, it\n%%% calculates not only the next digit, but the next starting\n%%% fraction. If it fails, we are done.\n%%%\n\n:- pred r2cf(int::in, int::out, int::in, int::out, int::out)\n is semidet.\nr2cf(!N1, !N2, Digit) :-\n (Dividend = !.N1),\n (Divisor = !.N2),\n (Divisor \\= 0), % Fail if we have reached the end.\n (!:N1 = Divisor), % The next Dividend.\n (!:N2 = Dividend mod Divisor), % Floor division. The next divisor.\n (Digit = Dividend div Divisor). % Floor division. The next digit.\n\n%%%-------------------------------------------------------------------\n%%%\n%%% ‘r2cf_digits’ takes numerator and denominator of a rational\n%%% number, and returns a list of continued fraction digits.\n%%%\n\n:- func r2cf_digits(int, int) = list(int).\n:- pred r2cf_digits_loop(int::in, int::in,\n list(int)::in, list(int)::out) is det.\nr2cf_digits(N1, N2) = Digit_list :-\n r2cf_digits_loop(N1, N2, [], Digit_list).\nr2cf_digits_loop(N1, N2, !Digit_list) :-\n (if r2cf(N1, N1_next, N2, N2_next, Digit)\n then r2cf_digits_loop(N1_next, N2_next,\n [Digit | !.Digit_list],\n !:Digit_list)\n else (!:Digit_list = reverse(!.Digit_list))).\n\n%%%-------------------------------------------------------------------\n%%%\n%%% ‘print_cf’ prints a continued fraction nicely.\n%%%\n\n:- pred print_cf(list(int)::in, io::di, io::uo) is det.\n:- pred print_cf_loop(list(int)::in, string::in, io::di, io::uo)\n is det.\nprint_cf(Digit_list, !IO) :-\n print_cf_loop(Digit_list, \"[\", !IO).\nprint_cf_loop(Digit_list, Sep, !IO) :-\n (if (Digit_list = [Digit | More_digits])\n then (print(Sep, !IO),\n print(Digit, !IO),\n (if (Sep = \"[\")\n then print_cf_loop(More_digits, \"; \", !IO)\n else print_cf_loop(More_digits, \", \", !IO)))\n else print(\"]\", !IO)).\n\n%%%-------------------------------------------------------------------\n%%%\n%%% ‘example’ takes numerator and denominator of a rational number,\n%%% and prints a line of output.\n%%%\n\n:- pred example(int::in, int::in, io::di, io::uo) is det.\nexample(N1, N2, !IO) :-\n print(N1, !IO),\n print(\"/\", !IO),\n print(N2, !IO),\n print(\" => \", !IO),\n print_cf(r2cf_digits(N1, N2), !IO),\n nl(!IO).\n\n%%%-------------------------------------------------------------------\n\nmain(!IO) :-\n example(1, 2, !IO),\n example(3, 1, !IO),\n example(23, 8, !IO),\n example(13, 11, !IO),\n example(22, 7, !IO),\n example(-151, 77, !IO),\n example(14142, 10000, !IO),\n example(141421, 100000, !IO),\n example(1414214, 1000000, !IO),\n example(14142136, 10000000, !IO),\n example(31, 10, !IO),\n example(314, 100, !IO),\n example(3142, 1000, !IO),\n example(31428, 10000, !IO),\n example(314285, 100000, !IO),\n example(3142857, 1000000, !IO),\n example(31428571, 10000000, !IO),\n example(314285714, 100000000, !IO),\n true.\n\n%%%-------------------------------------------------------------------\n%%% local variables:\n%%% mode: mercury\n%%% prolog-indent-width: 2\n%%% end:\n", "language": "Mercury" }, { "code": "%%%-------------------------------------------------------------------\n\n:- module continued_fraction_from_rational_lazy.\n\n:- interface.\n:- import_module io.\n:- pred main(io::di, io::uo) is det.\n\n:- implementation.\n:- import_module exception.\n:- import_module integer. % Arbitrary-precision integers.\n:- import_module lazy. % Lazy evaluation.\n:- import_module list.\n:- import_module string.\n\n%% NOTE: There IS a \"rational\" module, for arbitrary-precision\n%% rational numbers, but I wrote this example for plain \"integer\"\n%% type. One could easily add \"rational\" support.\n\n%%%-------------------------------------------------------------------\n%%%\n%%% The following lazy list implementation is suggested in the Mercury\n%%% Library Reference.\n%%%\n\n:- type lazy_list(T)\n ---> lazy_list(lazy(list_cell(T))).\n\n:- type list_cell(T)\n ---> cons(T, lazy_list(T))\n ; nil.\n\n:- type cf == lazy_list(integer).\n\n%%%-------------------------------------------------------------------\n%%%\n%%% r2cf takes numerator and denominator of a fraction, and returns a\n%%% continued fraction as a lazy list of terms.\n%%%\n\n:- func r2cf(integer, integer) = cf.\nr2cf(Numerator, Denominator) = CF :-\n (if (Denominator = zero)\n then (CF = lazy_list(delay((func) = nil)))\n else (CF = lazy_list(delay(Cons)),\n ((func) = Cell :-\n (Cell = cons(Quotient, r2cf(Denominator, Remainder)),\n %% What follows is division with truncation towards zero.\n divide_with_rem(Numerator, Denominator,\n Quotient, Remainder))) = Cons)).\n\n%%%-------------------------------------------------------------------\n%%%\n%%% cf2string and cf2string_with_max_terms convert a continued\n%%% fraction to a printable string.\n%%%\n\n:- func cf2string(cf) = string.\ncf2string(CF) = cf2string_with_max_terms(CF, integer(1000)).\n\n:- func cf2string_with_max_terms(cf, integer) = string.\ncf2string_with_max_terms(CF, MaxTerms) = S :-\n S = cf2string_loop(CF, MaxTerms, zero, \"[\").\n\n:- func cf2string_loop(cf, integer, integer, string) = string.\ncf2string_loop(CF, MaxTerms, I, Accum) = S :-\n (CF = lazy_list(ValCell),\n force(ValCell) = Cell,\n (if (Cell = cons(Term, Tail))\n then (if (I = MaxTerms) then (S = Accum ++ \",...]\")\n else ((Separator = (if (I = zero) then \"\"\n else if (I = one) then \";\"\n else \",\")),\n TermStr = to_string(Term),\n S = cf2string_loop(Tail, MaxTerms, I + one,\n Accum ++ Separator ++ TermStr)))\n else (S = Accum ++ \"]\"))).\n\n%%%-------------------------------------------------------------------\n%%%\n%%% example takes a fraction, as a string, or as separate numerator\n%%% and denominator strings, and prints a line of output.\n%%%\n\n:- pred example(string::in, io::di, io::uo) is det.\n:- pred example(string::in, string::in, io::di, io::uo) is det.\nexample(Fraction, !IO) :-\n split_at_char(('/'), Fraction) = Split,\n (if (Split = [Numerator])\n then example_(Fraction, Numerator, \"1\", !IO)\n else if (Split = [Numerator, Denominator])\n then example_(Fraction, Numerator, Denominator, !IO)\n else throw(\"Not an integer or fraction: \\\"\" ++ Fraction ++ \"\\\"\")).\nexample(Numerator, Denominator, !IO) :-\n example_(Numerator ++ \"/\" ++ Denominator,\n Numerator, Denominator, !IO).\n\n:- pred example_(string::in, string::in, string::in, io::di, io::uo)\n is det.\nexample_(Fraction, Numerator, Denominator, !IO) :-\n (N = integer.det_from_string(Numerator)),\n (D = integer.det_from_string(Denominator)),\n print(Fraction, !IO),\n print(\" => \", !IO),\n print(cf2string(r2cf(N, D)), !IO),\n nl(!IO).\n\n%%%-------------------------------------------------------------------\n\nmain(!IO) :-\n example(\"1/2\", !IO),\n example(\"3\", !IO),\n example(\"23/8\", !IO),\n example(\"13/11\", !IO),\n example(\"22/7\", !IO),\n example(\"-151/77\", !IO),\n\n %% I made \"example\" overloaded, so it can take separate numerator\n %% and denominator strings.\n example(\"151\", \"-77\", !IO),\n\n example(\"14142/10000\", !IO),\n example(\"141421/100000\", !IO),\n example(\"1414214/1000000\", !IO),\n example(\"14142136/10000000\", !IO),\n\n %% Decimal expansion of sqrt(2): see https://oeis.org/A002193\n example(\"141421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157/100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\", !IO),\n\n example(\"31/10\", !IO),\n example(\"314/100\", !IO),\n example(\"3142/1000\", !IO),\n example(\"31428/10000\", !IO),\n example(\"314285/100000\", !IO),\n example(\"3142857/1000000\", !IO),\n example(\"31428571/10000000\", !IO),\n example(\"314285714/100000000\", !IO),\n\n %% Decimal expansion of pi: see https://oeis.org/A000796\n example(\"314159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214/100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\", !IO),\n\n true.\n\n%%%-------------------------------------------------------------------\n%%% local variables:\n%%% mode: mercury\n%%% prolog-indent-width: 2\n%%% end:\n", "language": "Mercury" }, { "code": "MODULE ConstructFromrationalNumber;\nFROM FormatString IMPORT FormatString;\nFROM Terminal IMPORT WriteString,WriteLn,ReadChar;\n\nTYPE R2cf = RECORD\n num,den : INTEGER;\nEND;\n\nPROCEDURE HasNext(self : R2cf) : BOOLEAN;\nBEGIN\n RETURN self.den # 0;\nEND HasNext;\n\nPROCEDURE Next(VAR self : R2cf) : INTEGER;\nVAR div,rem : INTEGER;\nBEGIN\n div := self.num / self.den;\n rem := self.num REM self.den;\n self.num := self.den;\n self.den := rem;\n RETURN div;\nEND Next;\n\nPROCEDURE Iterate(self : R2cf);\nVAR buf : ARRAY[0..64] OF CHAR;\nBEGIN\n WHILE HasNext(self) DO\n FormatString(\"%i \", buf, Next(self));\n WriteString(buf);\n END;\n WriteLn;\nEND Iterate;\n\nPROCEDURE Print(num,den : INTEGER);\nVAR frac : R2cf;\nVAR buf : ARRAY[0..64] OF CHAR;\nBEGIN\n FormatString(\"%9i / %-9i = \", buf, num, den);\n WriteString(buf);\n\n frac.num := num;\n frac.den := den;\n Iterate(frac);\nEND Print;\n\nVAR frac : R2cf;\nBEGIN\n Print(1,2);\n Print(3,1);\n Print(23,8);\n Print(13,11);\n Print(22,7);\n Print(-151,77);\n\n WriteLn;\n WriteString(\"Sqrt(2) ->\");\n WriteLn;\n Print(14142,10000);\n Print(141421,100000);\n Print(1414214,1000000);\n Print(14142136,10000000);\n\n WriteLn;\n WriteString(\"Pi ->\");\n WriteLn;\n Print(31,10);\n Print(314,100);\n Print(3142,1000);\n Print(31428,10000);\n Print(314285,100000);\n Print(3142857,1000000);\n Print(31428571,10000000);\n Print(314285714,100000000);\n\n ReadChar;\nEND ConstructFromrationalNumber.\n", "language": "Modula-2" }, { "code": "iterator r2cf*(n1, n2: int): int =\n var (n1, n2) = (n1, n2)\n while n2 != 0:\n yield n1 div n2\n n1 = n1 mod n2\n swap n1, n2\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nwhen isMainModule:\n\n from sequtils import toSeq\n\n for pair in [(1, 2), (3, 1), (23, 8), (13, 11), (22, 7), (-151, 77)]:\n echo pair, \" -> \", toSeq(r2cf(pair[0], pair[1]))\n\n echo \"\"\n for pair in [(14142, 10000), (141421, 100000), (1414214, 1000000), (14142136, 10000000)]:\n echo pair, \" -> \", toSeq(r2cf(pair[0], pair[1]))\n\n echo \"\"\n for pair in [(31,10), (314,100), (3142,1000), (31428,10000), (314285,100000),\n (3142857,1000000), (31428571,10000000), (314285714,100000000)]:\n echo pair, \" -> \", toSeq(r2cf(pair[0], pair[1]))\n", "language": "Nim" }, { "code": "apply(contfrac,[1/2,3,23/8,13/11,22/7,-151/77])\n", "language": "PARI-GP" }, { "code": "$|=1;\n\nsub rc2f {\n my($num, $den) = @_;\n return sub { return unless $den;\n my $q = int($num/$den);\n ($num, $den) = ($den, $num - $q*$den);\n $q; };\n}\n\nsub rcshow {\n my $sub = shift;\n print \"[\";\n my $n = $sub->();\n print \"$n\" if defined $n;\n print \"; $n\" while defined($n = $sub->());\n print \"]\\n\";\n}\n\nrcshow(rc2f(@$_))\n for ([1,2],[3,1],[23,8],[13,11],[22,7],[-151,77]);\nprint \"\\n\";\nrcshow(rc2f(@$_))\n for ([14142,10000],[141421,100000],[1414214,1000000],[14142136,10000000]);\nprint \"\\n\";\nrcshow(rc2f(314285714,100000000));\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">r2cf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">num</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">quot</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">quot</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">trunc</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">num</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">num</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">num</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">quot</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">quot</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">num</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">}}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Running %s :\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">num</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">quot</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">sep</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\";\"</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d/%d ==&gt; [\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">num</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">quot</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">num</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">}}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">r2cf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">num</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">quot</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">sep</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">sep</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\",\"</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"]\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">examples</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">23</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">13</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">22</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">151</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">77</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #000000;\">sqrt2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">14142</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10000</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">141421</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">100000</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1414214</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1000000</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">14142136</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10000000</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #000000;\">pi</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">31</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">314</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">3142</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1000</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">31428</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10000</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">314285</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">100000</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">3142857</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1000000</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">31428571</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10000000</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">314285714</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">100000000</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">3141592653589793</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1000000000000000</span><span style=\"color: #0000FF;\">}}</span>\n\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"the examples\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">examples</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"for sqrt(2)\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">sqrt2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"for pi\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">pi</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "def r2cf(n1,n2):\n while n2:\n n1, (t1, n2) = n2, divmod(n1, n2)\n yield t1\n\nprint(list(r2cf(1,2))) # => [0, 2]\nprint(list(r2cf(3,1))) # => [3]\nprint(list(r2cf(23,8))) # => [2, 1, 7]\nprint(list(r2cf(13,11))) # => [1, 5, 2]\nprint(list(r2cf(22,7))) # => [3, 7]\nprint(list(r2cf(14142,10000))) # => [1, 2, 2, 2, 2, 2, 1, 1, 29]\nprint(list(r2cf(141421,100000))) # => [1, 2, 2, 2, 2, 2, 2, 3, 1, 1, 3, 1, 7, 2]\nprint(list(r2cf(1414214,1000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 3, 6, 1, 2, 1, 12]\nprint(list(r2cf(14142136,10000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 1, 2, 4, 1, 1, 2]\n", "language": "Python" }, { "code": "def real2cf(x):\n while True:\n t1, f = divmod(x, 1)\n yield int(t1)\n if not f:\n break\n x = 1/f\n\nfrom fractions import Fraction\nfrom itertools import islice\n\nprint(list(real2cf(Fraction(13, 11)))) # => [1, 5, 2]\nprint(list(islice(real2cf(2 ** 0.5), 20))) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]\n", "language": "Python" }, { "code": " [ $ \"bigrat.qky\" loadfile ] now!\n\n [ [] unrot\n [ proper\n 2swap join unrot\n over 0 != while\n 1/v again ]\n 2drop ] is cf ( n/d --> [ )\n\n ' [ [ 1 2 ]\n [ 3 1 ]\n [ 23 8 ]\n [ 13 11 ]\n [ 22 7 ]\n [ -151 77 ]\n [ 14142 10000 ]\n [ 141421 100000 ]\n [ 1414214 1000000 ]\n [ 14142136 10000000 ]\n [ 31 10 ]\n [ 314 100 ]\n [ 3142 1000 ]\n [ 31428 10000 ]\n [ 314285 100000 ]\n [ 3142857 1000000 ]\n [ 31428571 10000000 ]\n [ 314285714 100000000 ] ]\n\n witheach\n [ do over echo say \"/\"\n dup echo\n say \" = \"\n cf echo cr ]\n", "language": "Quackery" }, { "code": "#lang racket\n\n(define ((r2cf n d))\n (or (zero? d)\n (let-values ([(q r) (quotient/remainder n d)])\n (set! n d)\n (set! d r)\n q)))\n\n(define (r->cf n d)\n (for/list ([i (in-producer (r2cf n d) #t)]) i))\n\n(define (real->cf x places)\n (define d (expt 10 places))\n (define n (exact-floor (* x d)))\n (r->cf n d))\n\n(map r->cf\n '(1 3 23 13 22 -151)\n '(2 1 8 11 7 77))\n(real->cf (sqrt 2) 10)\n(real->cf pi 10)\n", "language": "Racket" }, { "code": "sub r2cf(Rat $x is copy) {\n gather loop {\n\t$x -= take $x.floor;\n\tlast unless $x > 0;\n\t$x = 1 / $x;\n }\n}\n\nsay r2cf(.Rat) for <1/2 3 23/8 13/11 22/7 1.41 1.4142136>;\n", "language": "Raku" }, { "code": "sub r2cf(Rat $x is copy) { gather $x [R/]= 1 while ($x -= take $x.floor) > 0 }\n", "language": "Raku" }, { "code": "# This implementation assumes the I/O facilities of gfortran, and so\n# is not suited to f2c as the FORTRAN77 compiler.\n\nfunction r2cf (N1, N2)\n implicit none\n\n integer N1, N2\n integer r2cf\n\n integer r\n\n # We will use division with rounding towards zero, which is the\n # native integer division method of FORTRAN77.\n r2cf = N1 / N2\n r = mod (N1, N2)\n\n N1 = N2\n N2 = r\nend\n\nsubroutine wrr2cf (N1, N2) # Write r2cf results.\n implicit none\n\n integer N1, N2\n integer r2cf\n integer digit, M1, M2\n integer sep\n\n write (*, '(I0, \"/\", I0, \" => \")', advance = \"no\") N1, N2\n\n M1 = N1\n M2 = N2\n sep = 0\n while (M2 != 0)\n {\n digit = r2cf (M1, M2)\n if (sep == 0)\n {\n write (*, '(\"[\", I0)', advance = \"no\") digit\n sep = 1\n }\n else if (sep == 1)\n {\n write (*, '(\"; \", I0)', advance = \"no\") digit\n sep = 2\n }\n else\n {\n write (*, '(\", \", I0)', advance = \"no\") digit\n }\n }\n write (*, '(\"]\")', advance = \"yes\")\nend\n\nprogram demo\n implicit none\n\n call wrr2cf (1, 2)\n call wrr2cf (3, 1)\n call wrr2cf (23, 8)\n call wrr2cf (13, 11)\n call wrr2cf (22, 7)\n call wrr2cf (-151, 77)\n\n call wrr2cf (14142, 10000)\n call wrr2cf (141421, 100000)\n call wrr2cf (1414214, 1000000)\n call wrr2cf (14142136, 10000000)\n\n call wrr2cf (31, 10)\n call wrr2cf (314, 100)\n call wrr2cf (3142, 1000)\n call wrr2cf (31428, 10000)\n call wrr2cf (314285, 100000)\n call wrr2cf (3142857, 1000000)\n call wrr2cf (31428571, 10000000)\n call wrr2cf (314285714, 100000000)\nend\n", "language": "RATFOR" }, { "code": "/*REXX program converts a decimal or rational fraction to a continued fraction. */\nnumeric digits 230 /*determines how many terms to be gened*/\nsay ' 1/2 ──► CF: ' r2cf( '1/2' )\nsay ' 3 ──► CF: ' r2cf( 3 )\nsay ' 23/8 ──► CF: ' r2cf( '23/8' )\nsay ' 13/11 ──► CF: ' r2cf( '13/11' )\nsay ' 22/7 ──► CF: ' r2cf( '22/7 ' )\nsay ' ___'\nsay '───────── attempts at √ 2.'\nsay '14142/1e4 ──► CF: ' r2cf( '14142/1e4 ' )\nsay '141421/1e5 ──► CF: ' r2cf( '141421/1e5 ' )\nsay '1414214/1e6 ──► CF: ' r2cf( '1414214/1e6 ' )\nsay '14142136/1e7 ──► CF: ' r2cf( '14142136/1e7 ' )\nsay '141421356/1e8 ──► CF: ' r2cf( '141421356/1e8 ' )\nsay '1414213562/1e9 ──► CF: ' r2cf( '1414213562/1e9 ' )\nsay '14142135624/1e10 ──► CF: ' r2cf( '14142135624/1e10 ' )\nsay '141421356237/1e11 ──► CF: ' r2cf( '141421356237/1e11 ' )\nsay '1414213562373/1e12 ──► CF: ' r2cf( '1414213562373/1e12 ' )\nsay '√2 ──► CF: ' r2cf( sqrt(2) )\nsay\nsay '───────── an attempt at pi'\nsay 'pi ──► CF: ' r2cf( pi() )\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n$maxFact: procedure; parse arg x 1 _x,y; y=10**(digits()-1); b=0; h=1; a=1; g=0\n do while a<=y & g<=y; n=trunc(_x); _=a; a=n*a+b; b=_; _=g; g=n*g+h; h=_\n if n=_x | a/g=x then do; if a>y | g>y then iterate; b=a; h=g; leave; end\n _x=1/(_x-n); end; return b'/'h\n/*──────────────────────────────────────────────────────────────────────────────────────*/\npi: return 3.1415926535897932384626433832795028841971693993751058209749445923078164062862,\n || 089986280348253421170679821480865132823066470938446095505822317253594081284,\n || 811174502841027019385211055596446229489549303819644288109756659334461284756,\n || 48233786783165271 /* ··· should ≥ NUMERIC DIGITS */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nr2cf: procedure; parse arg g 1 s 2; $=; if s=='-' then g=substr(g, 2)\n else s=\n if pos(., g)\\==0 then do; if \\datatype(g, 'N') then call serr 'not numeric:' g\n g=$maxfact(g)\n end\n if pos('/', g)==0 then g=g\"/\"1\n parse var g n '/' d\n if \\datatype(n, 'W') then call serr \"a numerator isn't an integer:\" n\n if \\datatype(d, 'W') then call serr \"a denominator isn't an integer:\" d\n if d=0 then call serr 'a denominator is zero'\n n=abs(n) /*ensure numerator is positive. */\n do while d\\==0; _=d /*where the rubber meets the road*/\n $=$ s || (n%d) /*append another number to list. */\n d=n // d; n=_ /* % is int div, // is modulus.*/\n end /*while*/\n return strip($)\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nserr: say; say '***error***'; say; say arg(1); say; exit 13\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h=d+6; numeric form\n m.=9; numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2\n do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/\n do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/\n numeric digits d; return g/1\n", "language": "REXX" }, { "code": "# Generate a continued fraction from a rational number\n\ndef r2cf(n1,n2)\n while n2 > 0\n n1, (t1, n2) = n2, n1.divmod(n2)\n yield t1\n end\nend\n", "language": "Ruby" }, { "code": "[[1,2], [3,1], [23,8], [13,11], [22,7], [-151,77]].each do |n1,n2|\n print \"%10s : \" % \"#{n1} / #{n2}\"\n r2cf(n1,n2) {|n| print \"#{n} \"}\n puts\nend\n", "language": "Ruby" }, { "code": "(5..8).each do |digit|\n n2 = 10 ** (digit-1)\n n1 = (Math.sqrt(2) * n2).round\n print \"%-8s / %-8s : \" % [n1, n2]\n r2cf(n1,n2) {|n| print \"#{n} \"}\n puts\nend\n", "language": "Ruby" }, { "code": "a =[ [31,10],\n [314,100],\n [3142,1000],\n [31428,10000],\n [314285,100000],\n [3142857,1000000],\n [31428571,10000000],\n [314285714,100000000]\n ]\na.each do |n1,n2|\n print \"%-9s / %-9s : \" % [n1, n2]\n r2cf(n1,n2) {|n| print \"#{n} \"}\n puts\nend\n", "language": "Ruby" }, { "code": "struct R2cf {\n n1: i64,\n n2: i64\n}\n\n// This iterator generates the continued fraction representation from the\n// specified rational number.\nimpl Iterator for R2cf {\n type Item = i64;\n\n fn next(&mut self) -> Option<i64> {\n if self.n2 == 0 {\n None\n }\n else {\n let t1 = self.n1 / self.n2;\n let t2 = self.n2;\n self.n2 = self.n1 - t1 * t2;\n self.n1 = t2;\n Some(t1)\n }\n }\n}\n\nfn r2cf(n1: i64, n2: i64) -> R2cf {\n R2cf { n1: n1, n2: n2 }\n}\n\nmacro_rules! printcf {\n ($x:expr, $y:expr) => (println!(\"{:?}\", r2cf($x, $y).collect::<Vec<_>>()));\n}\n\nfn main() {\n printcf!(1, 2);\n printcf!(3, 1);\n printcf!(23, 8);\n printcf!(13, 11);\n printcf!(22, 7);\n printcf!(-152, 77);\n\n printcf!(14_142, 10_000);\n printcf!(141_421, 100_000);\n printcf!(1_414_214, 1_000_000);\n printcf!(14_142_136, 10_000_000);\n\n printcf!(31, 10);\n printcf!(314, 100);\n printcf!(3142, 1000);\n printcf!(31_428, 10_000);\n printcf!(314_285, 100_000);\n printcf!(3_142_857, 1_000_000);\n printcf!(31_428_571, 10_000_000);\n printcf!(314_285_714, 100_000_000);\n}\n", "language": "Rust" }, { "code": "; Create a terminating Continued Fraction generator for the given rational number.\n; Returns one term per call; returns #f when no more terms remaining.\n(define make-continued-fraction-gen\n (lambda (rat)\n (let ((num (numerator rat)) (den (denominator rat)))\n (lambda ()\n (if (= den 0)\n #f\n (let ((ret (quotient num den))\n (rem (modulo num den)))\n (set! num den)\n (set! den rem)\n ret))))))\n\n; Return the continued fraction representation of a rational number as a string.\n(define rat->cf-string\n (lambda (rat)\n (let* ((cf (make-continued-fraction-gen rat))\n (str (string-append \"[\" (format \"~a\" (cf))))\n (sep \";\"))\n (let loop ((term (cf)))\n (when term\n (set! str (string-append str (format \"~a ~a\" sep term)))\n (set! sep \",\")\n (loop (cf))))\n (string-append str \"]\"))))\n\n; Return the continued fraction representation of a rational number as a list of terms.\n(define rat->cf-list\n (lambda (rat)\n (let ((cf (make-continued-fraction-gen rat))\n (lst '()))\n (let loop ((term (cf)))\n (when term\n (set! lst (append lst (list term)))\n (loop (cf))))\n lst)))\n", "language": "Scheme" }, { "code": "(printf \"~%Basic examples:~%\")\n(for-each\n (lambda (rat)\n (printf \"~a = ~a~%\" rat (rat->cf-string rat))\n (printf \"~a : ~a~%\" rat (rat->cf-list rat)))\n '(1/2 3 23/8 13/11 22/7 -151/77 0))\n\n(printf \"~%Root2 approximations:~%\")\n(for-each\n (lambda (rat)\n (printf \"~a = ~a~%\" rat (rat->cf-string rat))\n (printf \"~a : ~a~%\" rat (rat->cf-list rat)))\n '(14142/10000 141421/100000 1414214/1000000 14142136/10000000 141421356237/100000000000))\n\n(printf \"~%Pi approximations:~%\")\n(for-each\n (lambda (rat)\n (printf \"~a = ~a~%\" rat (rat->cf-string rat))\n (printf \"~a : ~a~%\" rat (rat->cf-list rat)))\n '(31/10 314/100 3142/1000 31428/10000 314285/100000 3142857/1000000\n 31428571/10000000 314285714/100000000 31415926535898/10000000000000))\n", "language": "Scheme" }, { "code": "(cond-expand\n (r7rs)\n (chicken (import (r7rs))))\n\n(import (scheme base))\n(import (scheme case-lambda))\n(import (scheme write))\n(import (srfi 41))\n\n;;;-------------------------------------------------------------------\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;; The entirety of r2cf, two different ways ;;;;;;;;;;;;;;;;;;;;;;;;;\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n;; r2cf-VERSION1 works with integers. (Any floating-point number is\n;; first converted to exact rational.)\n(define (r2cf-VERSION1 fraction)\n (define-stream (recurs n d)\n (if (zero? d)\n stream-null\n (let-values (((q r) (floor/ n d)))\n (stream-cons q (recurs d r)))))\n (let ((fraction (exact fraction)))\n (recurs (numerator fraction) (denominator fraction))))\n\n;; r2cf-VERSION2 works directly with fractions. (Any floating-point\n;; number is first converted to exact rational.)\n(define (r2cf-VERSION2 fraction)\n (define-stream (recurs fraction)\n (let* ((quotient (floor fraction))\n (remainder (- fraction quotient)))\n (stream-cons quotient (if (zero? remainder)\n stream-null\n (recurs (/ remainder))))))\n (recurs (exact fraction)))\n\n;;(define r2cf r2cf-VERSION1)\n(define r2cf r2cf-VERSION2)\n\n;;;-------------------------------------------------------------------\n\n(define *max-terms* (make-parameter 20))\n\n(define cf2string\n (case-lambda\n ((cf) (cf2string cf (*max-terms*)))\n ((cf max-terms)\n (let loop ((i 0)\n (s \"[\")\n (strm cf))\n (if (stream-null? strm)\n (string-append s \"]\")\n (let ((term (stream-car strm))\n (tail (stream-cdr strm)))\n (if (= i max-terms)\n (string-append s \",...]\")\n (let ((separator (case i\n ((0) \"\")\n ((1) \";\")\n (else \",\")))\n (term-str (number->string term)))\n (loop (+ i 1)\n (string-append s separator term-str)\n tail)))))))))\n\n(define (show fraction)\n (parameterize ((*max-terms* 1000))\n (display fraction)\n (display \" => \")\n (display (cf2string (r2cf fraction)))\n (newline)))\n\n(show 1/2)\n(show 3)\n(show 23/8)\n(show 13/11)\n(show 22/11)\n(show -151/77)\n(show 14142/10000)\n(show 141421/100000)\n(show 1414214/1000000)\n(show 14142136/10000000)\n(show 1414213562373095049/1000000000000000000)\n\n;; Decimal expansion of sqrt(2): see https://oeis.org/A002193\n(show 141421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157/100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)\n\n(show 31/10)\n(show 314/100)\n(show 3142/1000)\n(show 31428/10000)\n(show 314285/100000)\n(show 3142857/1000000)\n(show 31428571/10000000)\n(show 314285714/100000000)\n(show 3142857142857143/1000000000000000)\n\n;; Decimal expansion of pi: see https://oeis.org/A000796\n(show 314159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214/100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)\n", "language": "Scheme" }, { "code": "(cond-expand\n (r7rs)\n (chicken (import (r7rs))))\n\n(import (scheme base))\n(import (scheme write))\n\n;;;-------------------------------------------------------------------\n\n(define (r2cf fraction consumer)\n (let* ((fraction (exact fraction)))\n (let loop ((n (numerator fraction))\n (d (denominator fraction))\n (consumer consumer))\n (if (zero? d)\n (call-with-current-continuation\n (lambda (kont) (consumer #f kont)))\n (let-values (((q r) (floor/ n d)))\n (loop d r (call-with-current-continuation\n (lambda (kont) (consumer q kont)))))))))\n\n(define (display-cf term producer)\n (display \"[\")\n (let loop ((term term)\n (producer producer)\n (separator \"\"))\n (if term\n (begin\n (display separator)\n (display term)\n (let-values (((term producer)\n (call-with-current-continuation producer)))\n (loop term producer\n (if (string=? separator \"\") \";\" \",\"))))\n (begin\n (display \"]\")\n (call-with-current-continuation producer)))))\n\n;;;-------------------------------------------------------------------\n\n(define (show fraction)\n (display fraction)\n (display \" => \")\n (r2cf fraction display-cf)\n (newline))\n\n(show 1/2)\n(show 3)\n(show 23/8)\n(show 13/11)\n(show 22/11)\n(show -151/77)\n(show 14142/10000)\n(show 141421/100000)\n(show 1414214/1000000)\n(show 14142136/10000000)\n(show 1414213562373095049/1000000000000000000)\n\n;; Decimal expansion of sqrt(2): see https://oeis.org/A002193\n(show 141421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157/100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)\n\n(show 31/10)\n(show 314/100)\n(show 3142/1000)\n(show 31428/10000)\n(show 314285/100000)\n(show 3142857/1000000)\n(show 31428571/10000000)\n(show 314285714/100000000)\n(show 3142857142857143/1000000000000000)\n\n;; Decimal expansion of pi: see https://oeis.org/A000796\n(show 314159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214/100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)\n", "language": "Scheme" }, { "code": "func r2cf(num, den) {\n func() {\n den || return nil\n var q = num//den\n (num, den) = (den, num - q*den)\n return q\n }\n}\n\nfunc showcf(f) {\n print \"[\"\n var n = f()\n print \"#{n}\" if defined(n)\n print \"; #{n}\" while defined(n = f())\n print \"]\\n\"\n}\n\n[\n [1/2, 3/1, 23/8, 13/11, 22/7, -151/77],\n [14142/10000, 141421/100000, 1414214/1000000, 14142136/10000000],\n [314285714/100000000],\n].each { |seq|\n seq.each { |r| showcf(r2cf(r.nude)) }\n print \"\\n\"\n}\n", "language": "Sidef" }, { "code": "package require Tcl 8.6\n\nproc r2cf {n1 {n2 1}} {\n # Convert a decimal fraction (e.g., 1.23) into a form we can handle\n if {$n1 != int($n1) && [regexp {\\.(\\d+)} $n1 -> suffix]} {\n\tset pow [string length $suffix]\n\tset n1 [expr {int($n1 * 10**$pow)}]\n\tset n2 [expr {$n2 * 10**$pow}]\n }\n # Construct the continued fraction as a coroutine that yields the digits in sequence\n coroutine cf\\#[incr ::cfcounter] apply {{n1 n2} {\n\tyield [info coroutine]\n\twhile {$n2 > 0} {\n\t yield [expr {$n1 / $n2}]\n\t set n2 [expr {$n1 % [set n1 $n2]}]\n\t}\n\treturn -code break\n }} $n1 $n2\n}\n", "language": "Tcl" }, { "code": "proc printcf {name cf} {\n puts -nonewline \"$name -> \"\n while 1 {\n\tputs -nonewline \"[$cf],\"\n }\n puts \"\\b \"\n}\n\nforeach {n1 n2} {\n 1 2\n 3 1\n 23 8\n 13 11\n 22 7\n -151 77\n 14142 10000\n 141421 100000\n 1414214 1000000\n 14142136 10000000\n 31 10\n 314 100\n 3142 1000\n 31428 10000\n 314285 100000\n 3142857 1000000\n 31428571 10000000\n 314285714 100000000\n 3141592653589793 1000000000000000\n} {\n printcf \"\\[$n1;$n2\\]\" [r2cf $n1 $n2]\n}\n", "language": "Tcl" }, { "code": "package require Tcl 8.6\n\n# General generator class based on coroutines\noo::class create Generator {\n constructor {} {\n\tcoroutine [namespace current]::coro my Apply\n }\n destructor {\n\tcatch {rename [namespace current]::coro {}}\n }\n method Apply {} {\n\tyield\n # Call the method (defined in subclasses) that actually produces values\n\tmy Produce\n\tmy destroy\n\treturn -code break\n }\n forward generate coro\n method unknown args {\n\tif {![llength $args]} {\n\t tailcall coro\n\t}\n\tnext {*}$args\n }\n\n # Various ways to get the sequence from the generator\n method collect {} {\n\tset result {}\n\twhile 1 {\n\t lappend result [my generate]\n\t}\n\treturn $result\n }\n method take {n {suffix \"\"}} {\n\tset result {}\n\tfor {set i 0} {$i < $n} {incr i} {\n\t lappend result [my generate]\n\t}\n\twhile {$suffix ne \"\"} {\n\t my generate\n\t lappend result $suffix\n\t break\n\t}\n\treturn $result\n }\n}\n\noo::class create R2CF {\n superclass Generator\n variable a b\n # The constructor converts other kinds of fraction (e.g., 1.23, 22/7) into a\n # form we can handle.\n constructor {n1 {n2 1}} {\n\tnext; # Delegate to superclass for coroutine management\n\tif {[regexp {(.*)/(.*)} $n1 -> a b]} {\n\t # Nothing more to do; assume we can ignore second argument here\n\t} elseif {$n1 != int($n1) && [regexp {\\.(\\d+)} $n1 -> suffix]} {\n\t set pow [string length $suffix]\n\t set a [expr {int($n1 * 10**$pow)}]\n\t set b [expr {$n2 * 10**$pow}]\n\t} else {\n\t set a $n1\n\t set b $n2\n\t}\n }\n # How to actually produce the values of the sequence\n method Produce {} {\n\twhile {$b > 0} {\n\t yield [expr {$a / $b}]\n\t set b [expr {$a % [set a $b]}]\n\t}\n }\n}\n\nproc printcf {name cf {take \"\"}} {\n if {$take ne \"\"} {\n\tset terms [$cf take $take \\u2026]\n } else {\n\tset terms [$cf collect]\n }\n puts [format \"%-15s-> %s\" $name [join $terms ,]]\n}\n\nforeach {n1 n2} {\n 1 2\n 3 1\n 23 8\n 13 11\n 22 7\n -151 77\n 14142 10000\n 141421 100000\n 1414214 1000000\n 14142136 10000000\n 31 10\n 314 100\n 3142 1000\n 31428 10000\n 314285 100000\n 3142857 1000000\n 31428571 10000000\n 314285714 100000000\n 3141592653589793 1000000000000000\n} {\n printcf \"\\[$n1;$n2\\]\" [R2CF new $n1 $n2]\n}\n# Demonstrate parsing of input in forms other than a direct pair of decimals\nprintcf \"1.5\" [R2CF new 1.5]\nprintcf \"23/7\" [R2CF new 23/7]\n", "language": "Tcl" }, { "code": "import \"./rat\" for Rat\nimport \"./fmt\" for Fmt\n\nvar toContFrac = Fn.new { |r|\n var a = r.num\n var b = r.den\n while (true) {\n Fiber.yield((a/b).truncate)\n var t = a % b\n a = b\n b = t\n if (a == 1) return\n }\n}\n\nvar groups = [\n [ [1, 2], [3, 1], [23, 8], [13, 11], [22, 7], [-151, 77] ],\n [ [14142, 1e4], [141421, 1e5], [1414214, 1e6], [14142136, 1e7] ],\n [ [31, 10], [314, 100], [3142, 1e3], [31428, 1e4], [314285, 1e5], [3142857, 1e6],\n [31428571, 1e7], [314285714,1e8]]\n]\n\nvar lengths = [ [4, 2], [8, 8], [9, 9] ]\nvar headings = [ \"Examples ->\", \"Sqrt(2) ->\", \"Pi ->\" ]\nvar i = 0\nfor (group in groups) {\n System.print(headings[i])\n for (pair in group) {\n Fmt.write(\"$*d / $*d = \", lengths[i][0], pair[0], -lengths[i][1], pair[1])\n var f = Fiber.new(toContFrac)\n var r = Rat.new(pair[0], pair[1])\n while (!f.isDone) {\n var d = f.call(r)\n if (d) System.write(\"%(d) \")\n }\n System.print()\n }\n System.print()\n i = i + 1\n}\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes;\nreal Val;\n\nproc R2CF(N1, N2, Lev); \\Output continued fraction for N1/N2\nint N1, N2, Lev;\nint Quot, Rem;\n[if Lev=0 then Val:= 0.0;\nQuot:= N1/N2;\nRem:= rem(0);\nIntOut(0, Quot);\nif Rem then [ChOut(0, if Lev then ^, else ^;); R2CF(N2, Rem, Lev+1)];\nVal:= Val + float(Quot); \\generate value from continued fraction\nif Lev then Val:= 1.0/Val;\n];\n\nint I, Data;\n[Data:= [1,2, 3,1, 23,8, 13,11, 22,7, 0];\nFormat(0, 15);\nI:= 0;\nwhile Data(I) do\n [IntOut(0, Data(I)); ChOut(0, ^/); IntOut(0, Data(I+1)); ChOut(0, 9\\tab\\);\n ChOut(0, ^[); R2CF(Data(I), Data(I+1), 0); ChOut(0, ^]); ChOut(0, 9\\tab\\);\n RlOut(0, Val); CrLf(0);\n I:= I+2];\n]\n", "language": "XPL0" }, { "code": "fcn r2cf(nom,dnom){ // -->Walker (iterator)\n Walker.tweak(fcn(state){\n nom,dnom:=state;\n if(dnom==0) return(Void.Stop);\n n,d:=nom.divr(dnom);\n state.clear(dnom,d);\n n\n }.fp(List(nom,dnom))) // partial application (light weight closure)\n}\n", "language": "Zkl" }, { "code": "fcn r2cf2(nom,dnom){ // -->Generator (heavy weight Walker)\n Utils.Generator(fcn(nom,dnom){\n while(dnom){\n\t n,d:=nom.divr(dnom); nom,dnom=dnom,d;\n\t vm.yield(n);\n }\n Void.Stop;\n },nom,dnom)\n}\n", "language": "Zkl" }, { "code": "foreach nom,dnom in (T(T(1,2), T(3,1), T(23,8), T(13,11), T(22,7),\n\tT(14142,10000), T(141421,100000), T(1414214,1000000),\n\tT(14142136,10000000))){\n r2cf(nom,dnom).walk(25).println(); // print up to 25 numbers\n}\n", "language": "Zkl" } ]
Continued-fraction-Arithmetic-Construct-from-rational-number
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Convert_decimal_number_to_rational\n", "language": "00-META" }, { "code": "The task is to write a program to transform a decimal number into a fraction in lowest terms.\n\nIt is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, [[wp:Repeating decimal|repeating decimals]] such as 1/3 = 0.333...\n\nBecause of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:\n* 67 / 74 = 0.9(054) = 0.9054054...\n* 14 / 27 = 0.(518) = 0.518518...\n\n<br>Acceptable output:\n\n* 0.9054054 → 4527027 / 5000000\n* 0.518518 → 259259 / 500000\n\n<br>Finite decimals are of course no problem:\n\n* 0.75 → 3 / 4 \n<br><br>\n\n", "language": "00-TASK" }, { "code": "T Rational\n Int numerator\n Int denominator\n\n F (numerator, denominator)\n .numerator = numerator\n .denominator = denominator\n\n F String()\n I .denominator == 1\n R String(.numerator)\n E\n R .numerator‘//’(.denominator)\n\nF rationalize(x, tol = 1e-12)\n V xx = x\n V flagNeg = xx < 0.0\n I flagNeg\n xx = -xx\n I xx < 1e-10\n R Rational(0, 1)\n I abs(xx - round(xx)) < tol\n R Rational(Int(xx), 1)\n V a = 0\n V b = 1\n V c = Int(ceil(xx))\n V d = 1\n V aux1 = 7FFF'FFFF I/ 2\n L c < aux1 & d < aux1\n V aux2 = (Float(a) + Float(c)) / (Float(b) + Float(d))\n I abs(xx - aux2) < tol\n L.break\n I xx > aux2\n a += c\n b += d\n E\n c += a\n d += b\n V g = gcd(a + c, b + d)\n I flagNeg\n R Rational(-(a + c) I/ g, (b + d) I/ g)\n E\n R Rational((a + c) I/ g, (b + d) I/ g)\n\nprint(rationalize(0.9054054054))\nprint(rationalize(0.9054054054, 0.0001))\nprint(rationalize(0.5185185185))\nprint(rationalize(0.5185185185, 0.0001))\nprint(rationalize(0.75))\nprint(rationalize(0.1428571428, 0.001))\nprint(rationalize(35.000))\nprint(rationalize(35.001))\nprint(rationalize(0.9))\nprint(rationalize(0.99))\nprint(rationalize(0.909))\nprint(rationalize(0.909, 0.001))\n", "language": "11l" }, { "code": "generic\n type Real is digits <>;\nprocedure Real_To_Rational(R: Real;\n Bound: Positive;\n Nominator: out Integer;\n Denominator: out Positive);\n", "language": "Ada" }, { "code": "procedure Real_To_Rational (R: Real;\n Bound: Positive;\n Nominator: out Integer;\n Denominator: out Positive) is\n Error: Real;\n Best: Positive := 1;\n Best_Error: Real := Real'Last;\nbegin\n if R = 0.0 then\n Nominator := 0;\n Denominator := 1;\n return;\n elsif R < 0.0 then\n Real_To_Rational(-R, Bound, Nominator, Denominator);\n Nominator := - Nominator;\n return;\n else\n for I in 1 .. Bound loop\n Error := abs(Real(I) * R - Real'Rounding(Real(I) * R));\n if Error < Best_Error then\n Best := I;\n Best_Error := Error;\n end if;\n end loop;\n end if;\n Denominator := Best;\n Nominator := Integer(Real'Rounding(Real(Denominator) * R));\n\nend Real_To_Rational;\n", "language": "Ada" }, { "code": "with Ada.Text_IO; With Real_To_Rational;\n\nprocedure Convert_Decimal_To_Rational is\n\n type My_Real is new Long_Float; -- change this for another \"Real\" type\n\n package FIO is new Ada.Text_IO.Float_IO(My_Real);\n procedure R2R is new Real_To_Rational(My_Real);\n\n Nom, Denom: Integer;\n R: My_Real;\n\nbegin\n loop\n Ada.Text_IO.New_Line;\n FIO.Get(R);\n FIO.Put(R, Fore => 2, Aft => 9, Exp => 0);\n exit when R = 0.0;\n for I in 0 .. 4 loop\n R2R(R, 10**I, Nom, Denom);\n Ada.Text_IO.Put(\" \" & Integer'Image(Nom) &\n \" /\" & Integer'Image(Denom));\n end loop;\n end loop;\nend Convert_Decimal_To_Rational;\n", "language": "Ada" }, { "code": "--------- RATIONAL APPROXIMATION TO DECIMAL NUMBER -------\n\n-- approxRatio :: Real -> Real -> Ratio\non approxRatio(epsilon, n)\n if {real, integer} contains (class of epsilon) and 0 < epsilon then\n -- Given\n set e to epsilon\n else\n -- Default\n set e to 1 / 10000\n end if\n\n script gcde\n on |λ|(e, x, y)\n script _gcd\n on |λ|(a, b)\n if b < e then\n a\n else\n |λ|(b, a mod b)\n end if\n end |λ|\n end script\n |λ|(abs(x), abs(y)) of _gcd\n end |λ|\n end script\n\n set c to |λ|(e, 1, n) of gcde\n Ratio((n div c), (1 div c))\nend approxRatio\n\n\n-- Ratio :: Int -> Int -> Ratio\non Ratio(n, d)\n {type:\"Ratio\", n:n, d:d}\nend Ratio\n\n\n-- showRatio :: Ratio -> String\non showRatio(r)\n (n of r as string) & \"/\" & (d of r as string)\nend showRatio\n\n\n--------------------------- TEST -------------------------\non run\n script ratioString\n -- Using a tolerance epsilon of 1/10000\n on |λ|(x)\n (x as string) & \" -> \" & showRatio(approxRatio(1.0E-4, x))\n end |λ|\n end script\n\n unlines(map(ratioString, ¬\n {0.9054054, 0.518518, 0.75}))\n\n -- 0.9054054 -> 67/74\n -- 0.518518 -> 14/27\n -- 0.75 -> 3/4\nend run\n\n\n-------------------- GENERIC FUNCTIONS -------------------\n\n-- abs :: Num -> Num\non abs(x)\n if 0 > x then\n -x\n else\n x\n end if\nend abs\n\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: First-class m => (a -> b) -> m (a -> b)\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n\n-- unlines :: [String] -> String\non unlines(xs)\n -- A single string formed by the intercalation\n -- of a list of strings with the newline character.\n set {dlm, my text item delimiters} to ¬\n {my text item delimiters, linefeed}\n set s to xs as text\n set my text item delimiters to dlm\n s\nend unlines\n", "language": "AppleScript" }, { "code": " Array := []\n inputbox, string, Enter Number\n stringsplit, string, string, .\n if ( string1 = 0 )\n string1 =\n loop, parse, string, .\n if A_index = 2\n loop, parse, A_loopfield\n Array[A_index] := A_loopfield, k := A_index\n if (k = 1)\n {\n numerator := Array[1]\n Denominator := 10\n goto label\n }\n Original1 := K\n To_rn := floor(k/2)\n M_M := k - To_rn\n Original2 := k - To_rn\n loop\n {\n loop, % To_rn\n\n {\n Check1 .= Array[k]\n Check2 .= Array[M_M]\n k--\n m_M--\n }\n if ( check1 = check2 )\n {\n ;~ process beginsTO check;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n loop, % To_rn\n nines .= 9\n loop, % k - TO_rn\n Zeroes .= 0\n loop % k - TO_rn\n Minus .= Array[A_index]\n loop % k\n Plus .= Array[A_index]\n if ( minus = \"\" )\n minus := 0\n Numerator := Plus - minus\n Denominator := Nines . Zeroes\n ;;;;;;;;;;;;;HCF\n goto, label\n }\n Check1 =\n check2 =\n k := Original1\n m_M := original2 + A_index\n TO_rn--\n if ( to_rn = 0 )\n {\n zeroes =\n loop % original1\n zeroes .= 0\n Denominator := 1 . zeroes\n numerator := string2\n goto, label\n }\n }\n esc::Exitapp\n label:\n Index := 2\n loop\n {\n\n if (mod(denominator, numerator) = 0 )\n HCF := numerator\n if ( index = floor(numerator/2) )\n break\n if ( mod(numerator, index) = 0 ) && ( mod(denominator, index) = 0 )\n {\n HCF = %index%\n index++\n }\n else\n index++\n }\n if ( HCF = \"\" )\n Ans := numerator \"/\" Denominator\n else\n Ans := floor(numerator/HCF) \"/\" floor(Denominator/HCF)\n MsgBox % String . \" -> \" . String1 . \" \" . Ans\n reload\n", "language": "AutoHotkey" }, { "code": "( ( exact\n = integerPart decimalPart z\n . @(!arg:?integerPart \".\" ?decimalPart)\n & !integerPart\n + ( @( !decimalPart\n : (? ((%@:~0) ?:?decimalPart)) [?z\n )\n & !decimalPart*10^(-1*!z)\n | 0\n )\n | !arg\n )\n& ( approximation\n = integerPart firstDecimals repeatingDecimals\n , x y z z-y x-y numerator denominator\n . @( !arg\n : ?integerPart\n \".\"\n [?x\n ?firstDecimals\n ?repeatingDecimals\n [?y\n !repeatingDecimals\n [?z\n )\n & !z+-1*!y:?z-y\n & !x+-1*!y:?x-y\n & 10:?numerator:?denominator\n & ( !z-y:0&0:?repeatingDecimals\n | 9:?denominator\n & whl\n ' ( !z+-1:>!y:?z\n & !numerator*10:?numerator\n & !denominator*10+9:?denominator\n )\n & @(!repeatingDecimals:? #?repeatingDecimals)\n )\n & ( @(!firstDecimals:? #?firstDecimals)\n | 0:?firstDecimals\n )\n & !integerPart\n + !firstDecimals*10^(!x-y+!z-y)\n + !numerator*!denominator^-1*!repeatingDecimals*10^!x-y\n )\n& \"0.9054054054\"\n \"0.5185185185\"\n \"0.75\"\n \"0.905405400\"\n \"0.1428571428\"\n \"35.000\"\n \"35.001\"\n \"0.00000000001\"\n \"0.000001000001\"\n \"0.9\"\n \"0.99\"\n \"0.909\"\n \"0.9090\"\n \"0.90909\"\n : ?decs\n& whl\n ' ( !decs:%?dec ?decs\n & approximation$!dec:?approx\n & out\n $ ( !dec\n \"=\"\n (exact$!dec:?precise)\n ( !approx:!precise&\n | str$(\"(approx. \" !approx \")\")\n )\n )\n )\n);\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <stdint.h>\n\n/* f : number to convert.\n * num, denom: returned parts of the rational.\n * md: max denominator value. Note that machine floating point number\n * has a finite resolution (10e-16 ish for 64 bit double), so specifying\n * a \"best match with minimal error\" is often wrong, because one can\n * always just retrieve the significand and return that divided by\n * 2**52, which is in a sense accurate, but generally not very useful:\n * 1.0/7.0 would be \"2573485501354569/18014398509481984\", for example.\n */\nvoid rat_approx(double f, int64_t md, int64_t *num, int64_t *denom)\n{\n\t/* a: continued fraction coefficients. */\n\tint64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 };\n\tint64_t x, d, n = 1;\n\tint i, neg = 0;\n\n\tif (md <= 1) { *denom = 1; *num = (int64_t) f; return; }\n\n\tif (f < 0) { neg = 1; f = -f; }\n\n\twhile (f != floor(f)) { n <<= 1; f *= 2; }\n\td = f;\n\n\t/* continued fraction and check denominator each step */\n\tfor (i = 0; i < 64; i++) {\n\t\ta = n ? d / n : 0;\n\t\tif (i && !a) break;\n\n\t\tx = d; d = n; n = x % n;\n\n\t\tx = a;\n\t\tif (k[1] * a + k[0] >= md) {\n\t\t\tx = (md - k[0]) / k[1];\n\t\t\tif (x * 2 >= a || k[1] >= md)\n\t\t\t\ti = 65;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\n\t\th[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];\n\t\tk[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];\n\t}\n\t*denom = k[1];\n\t*num = neg ? -h[1] : h[1];\n}\n\nint main()\n{\n\tint i;\n\tint64_t d, n;\n\tdouble f;\n\n\tprintf(\"f = %16.14f\\n\", f = 1.0/7);\n\tfor (i = 1; i <= 20000000; i *= 16) {\n\t\tprintf(\"denom <= %d: \", i);\n\t\trat_approx(f, i, &n, &d);\n\t\tprintf(\"%lld/%lld\\n\", n, d);\n\t}\n\n\tprintf(\"\\nf = %16.14f\\n\", f = atan2(1,1) * 4);\n\tfor (i = 1; i <= 20000000; i *= 16) {\n\t\tprintf(\"denom <= %d: \", i);\n\t\trat_approx(f, i, &n, &d);\n\t\tprintf(\"%lld/%lld\\n\", n, d);\n\t}\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "f = 0.14285714285714\ndenom <= 1: 0/1\ndenom <= 16: 1/7\ndenom <= 256: 1/7\ndenom <= 4096: 1/7\ndenom <= 65536: 1/7\ndenom <= 1048576: 1/7\ndenom <= 16777216: 1/7\n\nf = 3.14159265358979\ndenom <= 1: 3/1\ndenom <= 16: 22/7\ndenom <= 256: 355/113\ndenom <= 4096: 355/113\ndenom <= 65536: 104348/33215\ndenom <= 1048576: 3126535/995207\ndenom <= 16777216: 47627751/15160384\n", "language": "C" }, { "code": "#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <vector>\n\nclass Rational {\npublic:\n\tRational(const int64_t& numer, const uint64_t& denom) : numerator(numer), denominator(denom) { }\n\n\tRational negate() {\n\t\treturn Rational(-numerator, denominator);\n\t}\n\n\tstd::string to_string() {\n\t\treturn std::to_string(numerator) + \" / \" + std::to_string(denominator);\n\t}\n\nprivate:\n\tint64_t numerator;\n\tuint64_t denominator;\n};\n/**\n * Return a Rational such that its numerator / denominator = 'decimal', correct to dp decimal places,\n * where dp is minimum of 'decimal_places' and the number of decimal places in 'decimal'.\n */\nRational decimal_to_rational(double decimal, const uint32_t& decimal_places) {\n\tconst double epsilon = 1.0 / std::pow(10, decimal_places);\n\n\tconst bool negative = ( decimal < 0.0 );\n\tif ( negative ) {\n\t\tdecimal = -decimal;\n\t}\n\n\tif ( decimal < std::numeric_limits<double>::min() ) {\n\t\treturn Rational(0, 1);\n\t}\n\n\tif ( std::abs( decimal - std::round(decimal) ) < epsilon ) {\n\t\treturn Rational(std::round(decimal), 1);\n\t}\n\n\tuint64_t a = 0;\n\tuint64_t b = 1;\n\tuint64_t c = static_cast<uint64_t>(std::ceil(decimal));\n\tuint64_t d = 1;\n\tconst uint64_t auxiliary_1 = std::numeric_limits<uint64_t>::max() / 2;\n\n\twhile ( c < auxiliary_1 && d < auxiliary_1 ) {\n\t\tconst double auxiliary_2 = static_cast<double>( a + c ) / ( b + d );\n\n\t\tif ( std::abs(decimal - auxiliary_2) < epsilon ) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif ( decimal > auxiliary_2 ) {\n\t\t\ta = a + c;\n\t\t\tb = b + d;\n\t\t} else {\n\t\t\tc = a + c;\n\t\t\td = b + d;\n\t\t}\n\t}\n\n\tconst uint64_t divisor = std::gcd(( a + c ), ( b + d ));\n\tRational result(( a + c ) / divisor, ( b + d ) / divisor);\n\treturn ( negative ) ? result.negate() : result;\n}\n\nint main() {\n\tfor ( const double& decimal : { 3.1415926535, 0.518518, -0.75, 0.518518518518, -0.9054054054054, -0.0, 2.0 } ) {\n\t\tstd::cout << decimal_to_rational(decimal, 9).to_string() << std::endl;\n\t}\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Text;\n\nnamespace RosettaDecimalToFraction\n{\n public class Fraction\n {\n public Int64 Numerator;\n public Int64 Denominator;\n public Fraction(double f, Int64 MaximumDenominator = 4096)\n {\n /* Translated from the C version. */\n /* a: continued fraction coefficients. */\n Int64 a;\n var h = new Int64[3] { 0, 1, 0 };\n var k = new Int64[3] { 1, 0, 0 };\n Int64 x, d, n = 1;\n int i, neg = 0;\n\n if (MaximumDenominator <= 1)\n {\n Denominator = 1;\n Numerator = (Int64)f;\n return;\n }\n\n if (f < 0) { neg = 1; f = -f; }\n\n while (f != Math.Floor(f)) { n <<= 1; f *= 2; }\n d = (Int64)f;\n\n /* continued fraction and check denominator each step */\n for (i = 0; i < 64; i++)\n {\n a = (n != 0) ? d / n : 0;\n if ((i != 0) && (a == 0)) break;\n\n x = d; d = n; n = x % n;\n\n x = a;\n if (k[1] * a + k[0] >= MaximumDenominator)\n {\n x = (MaximumDenominator - k[0]) / k[1];\n if (x * 2 >= a || k[1] >= MaximumDenominator)\n i = 65;\n else\n break;\n }\n\n h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];\n k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];\n }\n Denominator = k[1];\n Numerator = neg != 0 ? -h[1] : h[1];\n }\n public override string ToString()\n {\n return string.Format(\"{0} / {1}\", Numerator, Denominator);\n }\n }\n class Program\n {\n static void Main(string[] args)\n {\n Console.OutputEncoding = UTF8Encoding.UTF8;\n foreach (double d in new double[] { 0.9054054, 0.518518, 0.75, 0.4285714, 0.833333,\n 0.90909, 3.14159265358979, 2.7182818284590451 })\n {\n var f = new Fraction(d, d >= 2 ? 65536 : 4096);\n Console.WriteLine(\"{0,20} → {1}\", d, f);\n\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "import std.stdio, std.math, std.string, std.typecons;\n\nalias Fraction = Tuple!(int,\"nominator\", uint,\"denominator\");\n\nFraction real2Rational(in real r, in uint bound) /*pure*/ nothrow {\n if (r == 0.0) {\n return Fraction(0, 1);\n } else if (r < 0.0) {\n auto result = real2Rational(-r, bound);\n result.nominator = -result.nominator;\n return result;\n } else {\n uint best = 1;\n real bestError = real.max;\n\n foreach (i; 1 .. bound + 1) {\n // round is not pure.\n immutable real error = abs(i * r - round(i * r));\n if (error < bestError) {\n best = i;\n bestError = error;\n }\n }\n\n return Fraction(cast(int)round(best * r), best);\n }\n}\n\nvoid main() {\n immutable tests = [ 0.750000000, 0.518518000, 0.905405400,\n 0.142857143, 3.141592654, 2.718281828,\n -0.423310825, 31.415926536];\n\n foreach (r; tests) {\n writef(\"%8.9f \", r);\n foreach (i; 0 .. 5)\n writef(\" %d/%d\", real2Rational(r, 10 ^^ i).tupleof);\n writeln();\n }\n}\n", "language": "D" }, { "code": "program Convert_decimal_number_to_rational;\n\n{$APPTYPE CONSOLE}\n\nuses\n Velthuis.BigRationals,\n Velthuis.BigDecimals;\n\nconst\n Tests: TArray<string> = ['0.9054054', '0.518518', '0.75'];\n\nvar\n Rational: BigRational;\n Decimal: BigDecimal;\n\nbegin\n for var test in Tests do\n begin\n Decimal := test;\n Rational := Decimal;\n Writeln(test, ' = ', Rational.ToString);\n end;\n Readln;\nend.\n", "language": "Delphi" }, { "code": "(exact->inexact 67/74)\n → 0.9054054054054054\n(inexact->exact 0.9054054054054054)\n → 67/74\n\n(rationalize 0.7978723404255319)\n → 75/94\n\n;; finding rational approximations of PI\n(for ((ε (in-range -1 -15 -1)))\n\t(writeln ( format \"precision:10^%d %t PI = %d\" ε\n (rationalize PI (expt 10 e)))))\n\t\n\"precision:10^-1 PI = 16/5\"\n\"precision:10^-2 PI = 22/7\" ;;🎩\n\"precision:10^-3 PI = 201/64\"\n\"precision:10^-4 PI = 333/106\"\n\"precision:10^-5 PI = 355/113\" ;; 🎩 🎩\n\"precision:10^-6 PI = 355/113\"\n\"precision:10^-7 PI = 75948/24175\"\n\"precision:10^-8 PI = 100798/32085\"\n\"precision:10^-9 PI = 103993/33102\"\n\"precision:10^-10 PI = 312689/99532\"\n\"precision:10^-11 PI = 833719/265381\"\n\"precision:10^-12 PI = 4272943/1360120\"\n\"precision:10^-13 PI = 5419351/1725033\"\n\"precision:10^-14 PI = 58466453/18610450\"\n", "language": "EchoLisp" }, { "code": "USING: kernel math.floating-point prettyprint ;\n\n0.9054054 0.518518 0.75 [ double>ratio . ] tri@\n", "language": "Factor" }, { "code": "\\ Brute force search, optimized to search only within integer bounds surrounding target\n\\ Forth 200x compliant\n\n: RealToRational ( float_target int_denominator_limit -- numerator denominator )\n {: f: thereal denlimit | realscale numtor denom neg? f: besterror f: temperror :}\n 0 to numtor\n 0 to denom\n 9999999e to besterror \\ very large error that will surely be improved upon\n thereal F0< to neg? \\ save sign for later\n thereal FABS to thereal\n\n thereal FTRUNC f>s 1+ to realscale \\ realscale helps set integer bounds around target\n\n denlimit 1+ 1 ?DO \\ search through possible denominators ( 1 to denlimit)\n\n I realscale * I realscale 1- * ?DO \\ search within integer limits bounding the real\n I s>f J s>f F/ \\ e.g. for 3.1419e search only between 3 and 4\n thereal F- FABS to temperror\n\n temperror besterror F< IF\n temperror to besterror I to numtor J to denom\n THEN\n LOOP\n\n LOOP\n\n neg? IF numtor NEGATE to numtor THEN\n\n numtor denom\n;\n(run)\n1.618033988e 100 RealToRational swap . . 144 89\n3.14159e 1000 RealToRational swap . . 355 113\n2.71828e 1000 RealToRational swap . . 1264 465\n0.9054054e 100 RealToRational swap . . 67 74\n", "language": "Forth" }, { "code": " MODULE PQ\t!Plays with some integer arithmetic.\n INTEGER MSG\t!Output unit number.\n CONTAINS\t\t!One good routine.\n INTEGER FUNCTION GCD(I,J)\t!Greatest common divisor.\n INTEGER I,J\t!Of these two integers.\n INTEGER N,M,R\t!Workers.\n N = MAX(I,J)\t!Since I don't want to damage I or J,\n M = MIN(I,J)\t!These copies might as well be the right way around.\n 1 R = MOD(N,M)\t\t!Divide N by M to get the remainder R.\n IF (R.GT.0) THEN\t!Remainder zero?\n N = M\t\t\t!No. Descend a level.\n M = R\t\t\t!M-multiplicity has been removed from N.\n IF (R .GT. 1) GO TO 1\t!No point dividing by one.\n END IF\t\t\t!If R = 0, M divides N.\n GCD = M\t\t\t!There we are.\n END FUNCTION GCD\t!Euclid lives on!\n\n SUBROUTINE RATIONAL10(X)!By contrast, this is rather crude.\n DOUBLE PRECISION X\t!The number.\n DOUBLE PRECISION R\t!Its latest rational approach.\n INTEGER P,Q\t\t!For R = P/Q.\n INTEGER F,WHACK\t!Assistants.\n PARAMETER (WHACK = 10**8)\t!The rescale...\n P = X*WHACK + 0.5\t!Multiply by WHACK/WHACK = 1 and round to integer.\n Q = WHACK\t\t!Thus compute X/1, sortof.\n F = GCD(P,Q)\t\t!Perhaps there is a common factor.\n P = P/F\t\t!Divide it out.\n Q = Q/F\t\t!For a proper rational number.\n R = DBLE(P)/DBLE(Q)\t!So, where did we end up?\n WRITE (MSG,1) P,Q,X - R,WHACK\t!Details.\n 1 FORMAT (\"x - \",I0,\"/\",I0,T28,\" = \",F18.14,\n 1 \" via multiplication by \",I0)\n END SUBROUTINE RATIONAL10\t!Enough of this.\n\n SUBROUTINE RATIONAL(X)\t!Use brute force in a different way.\n DOUBLE PRECISION X\t!The number.\n DOUBLE PRECISION R,E,BEST\t!Assistants.\n INTEGER P,Q\t\t!For R = P/Q.\n INTEGER TRY,F\t\t!Floundering.\n P = 1 + X\t!Prevent P = 0.\n Q = 1\t\t!So, X/1, sortof.\n BEST = X*6\t!A largeish value for the first try.\n DO TRY = 1,10000000\t!Pound away.\n R = DBLE(P)/DBLE(Q)\t\t!The current approximation.\n E = X - R\t\t\t!Deviation.\n IF (ABS(E) .LE. BEST) THEN\t!Significantly better than before?\n BEST = ABS(E)*0.125\t\t!Yes. Demand eightfold improvement to notice.\n F = GCD(P,Q)\t\t\t!We may land on a multiple.\n IF (BEST.LT.0.1D0) WRITE (MSG,1) P/F,Q/F,E\t!Skip early floundering.\n 1 FORMAT (\"x - \",I0,\"/\",I0,T28,\" = \",F18.14)\t!Try to align columns.\n IF (F.NE.1) WRITE (MSG,*) \"Common factor!\",F\t!A surprise!\n IF (E.EQ.0) EXIT\t\t\t!Perhaps we landed a direct hit?\n END IF\t\t\t!So much for possible announcements.\n IF (E.GT.0) THEN\t!Is R too small?\n P = P + CEILING(E*Q)\t!Yes. Make P bigger by the shortfall.\n ELSE IF (E .LT. 0) THEN\t!But perhaps R is too big?\n Q = Q + 1\t\t\t!If so, use a smaller interval.\n END IF\t\t!So much for adjustments.\n END DO\t\t!Try again.\n END SUBROUTINE RATIONAL\t!Limited integers, limited sense.\n\n SUBROUTINE RATIONALISE(X,WOT)\t!Run the tests.\n DOUBLE PRECISION X\t!The value.\n CHARACTER*(*) WOT\t!Some blather.\n WRITE (MSG,*) X,WOT\t!Explanations can help.\n CALL RATIONAL10(X)\t!Try a crude method.\n CALL RATIONAL(X)\t!Try a laborious method.\n WRITE (MSG,*)\t\t!Space off.\n END SUBROUTINE RATIONALISE\t!That wasn't much fun.\n END MODULE PQ\t!But computer time is cheap.\n\n PROGRAM APPROX\n USE PQ\n DOUBLE PRECISION PI,E\n MSG = 6\n WRITE (MSG,*) \"Rational numbers near to decimal values.\"\n WRITE (MSG,*)\n PI = 1\t\t!Thus get a double precision conatant.\n PI = 4*ATAN(PI)\t!That will determine the precision of ATAN.\n E = DEXP(1.0D0)\t!Rather than blabber on about 1 in double precision.\n CALL RATIONALISE(0.1D0,\"1/10 Repeating in binary..\")\n CALL RATIONALISE(3.14159D0,\"Pi approx.\")\n CALL RATIONALISE(PI,\"Pi approximated better.\")\n CALL RATIONALISE(E,\"e: rational approximations aren't much use.\")\n CALL RATIONALISE(10.15D0,\"Exact in decimal, recurring in binary.\")\n WRITE (MSG,*)\n WRITE (MSG,*) \"Variations on 67/74\"\n CALL RATIONALISE(0.9054D0,\"67/74 = 0·9(054) repeating in base 10\")\n CALL RATIONALISE(0.9054054D0,\"Two repeats.\")\n CALL RATIONALISE(0.9054054054D0,\"Three repeats.\")\n WRITE (MSG,*)\n WRITE (MSG,*) \"Variations on 14/27\"\n CALL RATIONALISE(0.518D0,\"14/27 = 0·(518) repeating in decimal.\")\n CALL RATIONALISE(0.519D0,\"Rounded.\")\n CALL RATIONALISE(0.518518D0,\"Two repeats, truncated.\")\n CALL RATIONALISE(0.518519D0,\"Two repeats, rounded.\")\n END\n", "language": "Fortran" }, { "code": "'' Written in FreeBASIC\n'' (no error checking, limited to 64-bit signed math)\ntype number as longint\n#define str2num vallng\n#define pow10(n) clngint(10 ^ (n))\n\nfunction gcd(a as number, b as number) as number\n if a = 0 then return b\n return gcd(b mod a, a)\nend function\n\n\nfunction parserational(n as const string) as string\n dim as string whole, dec, num, denom\n dim as number iwhole, idec, inum, idenom, igcd\n\n '' find positions of '.', '(' and ')' in code\n dim as integer dpos, r1pos, r2pos\n dpos = instr(n & \".\", \".\")\n r1pos = instr(n & \"(\", \"(\")\n r2pos = instr(n & \")\", \")\")\n\n '' extract sections of number (whole, decimal, repeated numerator), generate '999' denominator\n whole = left(n, dpos - 1)\n dec = mid(n, dpos + 1, r1pos - dpos - 1)\n num = mid(n, r1pos + 1, r2pos - r1pos - 1)\n denom = string(len(num), \"9\"): if denom = \"\" then denom = \"1\"\n\n '' parse sections to integer\n iwhole = str2num(whole)\n idec = str2num(dec)\n inum = str2num(num)\n idenom = str2num(denom)\n\n '' if whole was negative, decimal and repeated sections need to be negative too\n if left(ltrim(whole), 1) = \"-\" then idec = -idec: inum = -inum\n\n '' add decimal part to repeated fraction, and scale down\n inum += idec * idenom\n idenom *= pow10(len(dec))\n\n '' add integer part to fraction\n inum += iwhole * idenom\n\n '' simplify fraction\n igcd = abs(gcd(inum, idenom))\n if igcd <> 0 then\n inum \\= igcd\n idenom \\= igcd\n end if\n\n return inum & \" / \" & idenom & \" = \" & (inum / idenom)\n\nend function\n\ndata \"0.9(054)\", \"0.(518)\", \"-.12(345)\", \"\"\ndo\n dim as string n\n read n\n if n = \"\" then exit do\n print n & \":\", parserational(n)\nloop\n", "language": "FreeBASIC" }, { "code": "println[toRational[0.9054054]]\nprintln[toRational[0.518518]]\nprintln[toRational[0.75]]\n", "language": "Frink" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n for _, d := range []string{\"0.9054054\", \"0.518518\", \"0.75\"} {\n if r, ok := new(big.Rat).SetString(d); ok {\n fmt.Println(d, \"=\", r)\n } else {\n fmt.Println(d, \"invalid decimal number\")\n }\n }\n}\n", "language": "Go" }, { "code": "Number.metaClass.mixin RationalCategory\n\n[\n 0.9054054, 0.518518, 0.75, Math.E, -0.423310825, Math.PI, 0.111111111111111111111111\n].each{\n printf \"%30.27f %s\\n\", it, it as Rational\n}\n", "language": "Groovy" }, { "code": "Prelude> map (\\d -> Ratio.approxRational d 0.0001) [0.9054054, 0.518518, 0.75]\n[67 % 74,14 % 27,3 % 4]\nPrelude> [0.9054054, 0.518518, 0.75] :: [Rational]\n[4527027 % 5000000,259259 % 500000,3 % 4]\nPrelude> map (fst . head . Numeric.readFloat) [\"0.9054054\", \"0.518518\", \"0.75\"] :: [Rational]\n[4527027 % 5000000,259259 % 500000,3 % 4]\n", "language": "Haskell" }, { "code": " x: 0.9054054 0.518518 0.75 NB. find \"exact\" rational representation\n127424481939351r140737488355328 866492568306r1671094481399 3r4\n", "language": "J" }, { "code": " x: 0.9 0.5\n9r10 1r2\n x: 0.9054 0.5185\n4527r5000 1037r2000\n x: 0.9054054 0.5185185\n127424481939351r140737488355328 1037037r2000000\n x: 0.9054054054 0.5185185185\n5358191125333r5918002138463 6073341499873r11712872893031\n x: 0.9054054054054 0.5185185185185\n67r74 14r27\n x: 0.9054054054054054 0.5185185185185185\n67r74 14r27\n", "language": "J" }, { "code": " x:(!. 5e_11) 0.9054054054 0.5185185185\n67r74 14r27\n", "language": "J" }, { "code": " 0j10\": x:inv x: 0.9054054 0.518518 0.75 NB. invertible (shown to 10 decimal places)\n0.9054054000 0.5185180000 0.7500000000\n 0j10\": x:inv 67r74 42r81 3r4 NB. decimal representation (shown to 10 decimal places)\n0.9054054054 0.5185185185 0.7500000000\n x: x:inv 67r74 42r81 3r4 NB. invertible\n67r74 14r27 3r4\n", "language": "J" }, { "code": "double fractionToDecimal(String string) {\n int indexOf = string.indexOf(' ');\n int integer = 0;\n int numerator, denominator;\n if (indexOf != -1) {\n integer = Integer.parseInt(string.substring(0, indexOf));\n string = string.substring(indexOf + 1);\n }\n indexOf = string.indexOf('/');\n numerator = Integer.parseInt(string.substring(0, indexOf));\n denominator = Integer.parseInt(string.substring(indexOf + 1));\n return integer + ((double) numerator / denominator);\n}\n\nString decimalToFraction(double value) {\n String string = String.valueOf(value);\n string = string.substring(string.indexOf('.') + 1);\n int numerator = Integer.parseInt(string);\n int denominator = (int) Math.pow(10, string.length());\n int gcf = gcf(numerator, denominator);\n if (gcf != 0) {\n numerator /= gcf;\n denominator /= gcf;\n }\n int integer = (int) value;\n if (integer != 0)\n return \"%d %d/%d\".formatted(integer, numerator, denominator);\n return \"%d/%d\".formatted(numerator, denominator);\n}\n\nint gcf(int valueA, int valueB) {\n if (valueB == 0) return valueA;\n else return gcf(valueB, valueA % valueB);\n}\n", "language": "Java" }, { "code": "import org.apache.commons.math3.fraction.BigFraction;\n\npublic class Test {\n\n public static void main(String[] args) {\n double[] n = {0.750000000, 0.518518000, 0.905405400, 0.142857143,\n 3.141592654, 2.718281828, -0.423310825, 31.415926536};\n\n for (double d : n)\n System.out.printf(\"%-12s : %s%n\", d, new BigFraction(d, 0.00000002D, 10000));\n }\n}\n", "language": "Java" }, { "code": "(() => {\n \"use strict\";\n\n // ---------------- APPROXIMATE RATIO ----------------\n\n // approxRatio :: Real -> Real -> Ratio\n const approxRatio = epsilon =>\n n => {\n const\n c = gcdApprox(\n 0 < epsilon\n ? epsilon\n : (1 / 10000)\n )(1, n);\n\n return Ratio(\n Math.floor(n / c),\n Math.floor(1 / c)\n );\n };\n\n\n // gcdApprox :: Real -> (Real, Real) -> Real\n const gcdApprox = epsilon =>\n (x, y) => {\n const _gcd = (a, b) =>\n b < epsilon\n ? a\n : _gcd(b, a % b);\n\n return _gcd(Math.abs(x), Math.abs(y));\n };\n\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () =>\n // Using a tolerance of 1/10000\n [0.9054054, 0.518518, 0.75]\n .map(\n compose(\n showRatio,\n approxRatio(0.0001)\n )\n )\n .join(\"\\n\");\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n // A function defined by the right-to-left\n // composition of all the functions in fs.\n fs.reduce(\n (f, g) => x => f(g(x)),\n x => x\n );\n\n\n // Ratio :: Int -> Int -> Ratio\n const Ratio = (n, d) => ({\n type: \"Ratio\",\n n,\n d\n });\n\n\n // showRatio :: Ratio -> String\n const showRatio = nd =>\n `${nd.n.toString()}/${nd.d.toString()}`;\n\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "# include \"rational\"; # a reminder that r/2 and power/1 are required\n\n# Input: any JSON number, not only a decimal\n# Output: a rational, constructed using r/2\n# Requires power/1 (to take advantage of gojq's support for integer arithmetic)\n# and r/2 (for rational number constructor)\ndef number_to_r:\n\n # input: a decimal string\n # $in - either null or the original input\n # $e - the integer exponent of the original number, or 0\n def dtor($in; $e):\n index(\".\") as $ix\n | if $in and ($ix == null) then $in\n else (if $ix then sub(\"[.]\"; \"\") else . end | tonumber) as $n\n | (if $ix then ((length - ($ix+1)) - $e) else - $e end) as $p\n | if $p >= 0\n then r( $n; 10|power($p))\n else r( $n * (10|power(-$p)); 1)\n end\n end;\n\n . as $in\n | tostring\n | if (test(\"[Ee]\")|not) then dtor($in; 0)\n else capture(\"^(?<s>[^eE]*)[Ee](?<e>.*$)\")\n | (.e | if length > 0 then tonumber else 0 end) as $e\n | .s | dtor(null; $e)\n end ;\n", "language": "Jq" }, { "code": "0.9054054,\n0.518518,\n0.75,\n1e308\n| \"\\(.) → \\(number_to_r | rpp)\"\n", "language": "Jq" }, { "code": "rationalize(0.9054054)\nrationalize(0.518518)\nrationalize(0.75)\n", "language": "Julia" }, { "code": "function rat(x::AbstractFloat, tol::Real=eps(x))::Rational\n p, q, pp, qq = copysign(1,x), 0, 0, 1\n x, y = abs(x), 1.0\n r, a = modf(x)\n nt, t, tt = tol, 0.0, tol\n\n while r > nt # convergents of the continued fraction: np//nq = (p*a + pp) // (q*a + qq)\n np, nq = Int(a).*(p,q) .+ (pp,qq)\n p, pp, q, qq = np, p, nq, q\n\n x, y = y, r # instead of the inexact 1/r...\n a, r = divrem(x,y)\n\n t, tt = nt, t # maintain x = (p + (-1)^i * r) / q\n nt = a*t+tt\n end\n\n i = Int(cld(x-tt,y+t)) # find optimal semiconvergent: smallest i such that x-i*y < i*t+tt\n return (i*p+pp) // (i*q+qq)\nend\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nclass Rational(val num: Long, val den: Long) {\n override fun toString() = \"$num/$den\"\n}\n\nfun decimalToRational(d: Double): Rational {\n val ds = d.toString().trimEnd('0').trimEnd('.')\n val index = ds.indexOf('.')\n if (index == -1) return Rational(ds.toLong(), 1L)\n var num = ds.replace(\".\", \"\").toLong()\n var den = 1L\n for (n in 1..(ds.length - index - 1)) den *= 10L\n while (num % 2L == 0L && den % 2L == 0L) {\n num /= 2L\n den /= 2L\n }\n while (num % 5L == 0L && den % 5L == 0L) {\n num /= 5L\n den /= 5L\n }\n return Rational(num, den)\n}\n\nfun main(args: Array<String>) {\n val decimals = doubleArrayOf(0.9054054, 0.518518, 2.405308, .75, 0.0, -0.64, 123.0, -14.6)\n for (decimal in decimals)\n println(\"${decimal.toString().padEnd(9)} = ${decimalToRational(decimal)}\")\n}\n", "language": "Kotlin" }, { "code": "' Uses convention that one repeating sequence implies infinitely repeating sequence..\n' Non-recurring fractions are limited to nd number of digits in nuerator & denominator\n\nnd =3 ' suggest 3. 4 is slow. >4 is .......\ndo\n read x$\n data \"0.5\", \"0.1\", \"0.333\", \"1 /3\", \"0.33\", \"0.14159265\", \"2^-0.5\", \"0.1 +0.9*rnd(1)\"\n data \"0.142857142857\", \"int( 1000*rnd(1))/int( 1000*rnd(1))\",\"end\" ' always between 0 and 0.999999...\n if x$ =\"end\" then exit do\n print x$; \" is \";\n type$ =check$( x$)\n print type$;\n\n if type$ =\"recurring\" then\n x =val( mid$( x$, 3, ( len( x$) -2) /2))\n rep =( len( x$) -2) /2\n num =x\n den =10^rep -1\n gcd =gcd( num, den)\n print\n print \" Calculating exact fraction for \", recurring$( x); \" recurring & found\";\n print num /gcd; \" /\"; den /gcd\n print\n else ' non-recurring. Check numerators & denominators <1000\n x =eval( x$)\n print\n print \" Looking for fractions that are close to \"; using( \"#.############\", x); \" & found \";\n eps =10^nd\n for n = 1 to nd\n for i =1 to 10^n -1\n for j =i to 10^n -1\n fr =i /j\n if abs( x -fr) <eps then\n eps =abs( x -fr)\n 'print i; \" /\"; j; \" = \", using( \"##.############\", fr), \"with error +/-\"; using( \"###.#########\", eps /x *100); \" %\"\n ii =i: jj =j\n if eps =0 then exit for\n end if\n next j\n scan\n if eps =0 then exit for\n next i\n if eps =0 then exit for\n next n\n print ii; \" /\"; jj\n print\n end if\nloop until 0\n\nprint\nprint \"END.\"\n\nend\n\nfunction recurring$( x)\n recurring$ =\"0.\"\n do\n recurring$ =recurring$ +str$( x)\n loop until len( recurring$) >=14\nend function\n\nfunction gcd( a, b) ' thanks Uncle Ben..\n while b <>0\n t =b\n b =a mod b\n a =t\n wend\n gcd =a\nend function\n\nfunction check$( i$)\n check$ =\"non-recurring\"\n length =len( i$) -2 ' allow for the '0.'.\n if length /2 =int( length /2) then if mid$( i$, 3, length /2) =mid$( i$, 3 +length /2, length /2) then check$ =\"recurring\"\nend function\n", "language": "Liberty-BASIC" }, { "code": "for _,v in ipairs({ 0.9054054, 0.518518, 0.75, math.pi }) do\n local n, d, dmax, eps = 1, 1, 1e7, 1e-15\n while math.abs(n/d-v)>eps and d<dmax do d=d+1 n=math.floor(v*d) end\n print(string.format(\"%15.13f --> %d / %d\", v, n, d))\nend\n", "language": "Lua" }, { "code": "module Convert_decimal_number_to_rational{\n\tFunction Rational(numerator as decimal, denominator as decimal=1) {\n\t\tif denominator==0 then denominator=1\n\t\twhile frac(numerator)<>0 {\n\t\t\tnumerator*=10@\n\t\t\tdenominator*=10@\n\t\t}\n\t\tsgn=Sgn(numerator)*Sgn(denominator)\n\t\tdenominator<=abs(denominator)\n\t\tnumerator<=abs(numerator)*sgn\n\t\tgcd1=lambda (a as decimal, b as decimal) -> {\n\t\t\tif a<b then swap a,b\n\t\t\tg=a mod b\n\t\t\twhile g {a=b:b=g: g=a mod b}\n\t\t\t=abs(b)\n\t\t}\n\t\tgdcval=gcd1(abs(numerator), denominator)\n\t\tif gdcval<denominator and gdcval<>0 then\n\t\t\tdenominator/=gdcval\n\t\t\tnumerator/=gdcval\n\t\tend if\n\t\t=(numerator,denominator)\n\t}\n\t\n\tPrint Rational(0.9054054)#str$(\" / \")=\"4527027 / 5000000\" ' true\n\tPrint Rational(0.518518)#str$(\" / \")=\"259259 / 500000\" ' true\n\tPrint Rational(0.75)#str$(\" / \")=\"3 / 4\" ' true\n}\nConvert_decimal_number_to_rational\n", "language": "M2000-Interpreter" }, { "code": "> map( convert, [ 0.9054054, 0.518518, 0.75 ], 'rational', 'exact' );\n 4527027 259259\n [-------, ------, 3/4]\n 5000000 500000\n", "language": "Maple" }, { "code": "Map[Rationalize[#,0]&,{0.9054054,0.518518, 0.75} ]\n-> {4527027/5000000,259259/500000,3/4}\n", "language": "Mathematica" }, { "code": " [a,b]=rat(.75)\n [a,b]=rat(.518518)\n [a,b]=rat(.9054054)\n", "language": "MATLAB" }, { "code": "/*NetRexx program to convert decimal numbers to fractions *************\n* 16.08.2012 Walter Pachl derived from Rexx Version 2\n**********************************************************************/\noptions replace format comments java crossref savelog symbols\n Numeric Digits 10 /* use \"only\" 10 digs of precision */\n ratt('0.9054054054','67/74')\n ratt('0.5185185185','14/27')\n ratt('0.75' ,'3/4')\n ratt('0.905405400',' 693627417/766095958')\n ratt('0.9054054054','67/74')\n ratt('0.1428571428','1/7')\n ratt('35.000','35')\n ratt('35.001','35001/1000')\n ratt('0.00000000001','?')\n ratt('0.000001000001','1/999999')\n\nratt(0.9054054054,'1/3')\n\n\nmethod ratt(d = Rexx,fs = Rexx) public static\n fract=rat(d)\n Say ' 'd '->' fract\n Parse fract no '/' de\n If de='' Then x=no\n Else x=no/de\n If x<>d Then\n Say '> '||x 'is different'\n\nmethod rat(in, high='') public static\n/**********************************************************************\n* rat(number<,high) returns a fraction or an integer that is equal to\n* or approximately equal to number.\n* Nominator and denominator must not have more than high digits\n* 16.08.2012 Walter Pachl derived from Rexx Version 2\n**********************************************************************/\n if high=='' then\n high=10**(digits - 1) /* maximum nominator/denominator */\n x=in /* working copy */\n nom=0 /* start values nominator */\n den=1 /* denominator */\n tnom=1 /* temp nominator */\n tden=0 /* temp denominator */\n loop While tnom<=high & tden<=high /* nominator... not too large */\n n=x.trunc() /* take integer part of x */\n z=tnom; /* save temp nominator */\n tnom=n*tnom+nom; /* compute new temp nominator */\n nom=z /* assign nominator */\n z=tden; /* save temp denominator */\n tden=n*tden+den /* compute new temp denominato*/\n den=z /* assign denominator */\n if n=x | tnom/tden=in then do\n if tnom>high | tden>high then /* temp value(s) too large */\n Leave /* don't use them */\n nom=tnom /* otherwise take them as */\n den=tden /* final values */\n leave /* and end the loop */\n end\n x=1/(x-n) /* compute x for next round */\n end\n If den=1 Then Return nom /* an integer */\n Else Return nom'/'den /* otherwise a fraction */\n", "language": "NetRexx" }, { "code": "import math\nimport fenv\n\ntype\n Rational = object\n numerator: int\n denominator: int\n\nproc `$`(self: Rational): string =\n if self.denominator == 1:\n $self.numerator\n else:\n $self.numerator & \"//\" & $self.denominator\n\nfunc rationalize(x: float, tol: float = epsilon(float)): Rational =\n var xx = x\n let flagNeg = xx < 0.0\n if flagNeg:\n xx = -xx\n if xx < minimumPositiveValue(float):\n return Rational(numerator: 0, denominator: 1)\n if abs(xx - round(xx)) < tol:\n return Rational(numerator: int(round(xx)), denominator: 1)\n var a = 0\n var b = 1\n var c = int(ceil(xx))\n var d = 1\n var aux1 = high(int) div 2\n while c < aux1 and d < aux1:\n var aux2 = (float(a) + float(c)) / (float(b) + float(d))\n if abs(xx - aux2) < tol:\n break\n if xx > aux2:\n inc a, c\n inc b, d\n else:\n inc c, a\n inc d, b\n var gcd = gcd(a + c, b + d)\n if flagNeg:\n Rational(numerator: -(a + c) div gcd, denominator: (b + d) div gcd)\n else:\n Rational(numerator: (a + c) div gcd, denominator: (b + d) div gcd)\n\necho rationalize(0.9054054054)\necho rationalize(0.9054054054, 0.0001)\necho rationalize(0.5185185185)\necho rationalize(0.5185185185, 0.0001)\necho rationalize(0.75)\necho rationalize(0.1428571428, 0.001)\necho rationalize(35.000)\necho rationalize(35.001)\necho rationalize(0.9)\necho rationalize(0.99)\necho rationalize(0.909)\necho rationalize(0.909, 0.001)\n", "language": "Nim" }, { "code": "import rationals\n\necho toRational(0.9054054054)\necho toRational(0.5185185185)\necho toRational(0.75)\necho toRational(0.1428571428)\necho toRational(35.000)\necho toRational(35.001)\necho toRational(0.9)\necho toRational(0.99)\necho toRational(0.909)\n", "language": "Nim" }, { "code": "(print (exact #i0.9054054054))\n(print (exact #i0.5185185185))\n(print (exact #i0.75))\n(print (exact #i35.000))\n(print (exact #i35.001))\n(print (exact #i0.9))\n(print (exact #i0.99))\n(print (exact #i0.909))\n", "language": "Ol" }, { "code": "convert(x)={\n my(n=0);\n while(x-floor(x*10^n)/10^n!=0.,n++);\n floor(x*10^n)/10^n\n};\n", "language": "PARI-GP" }, { "code": "sub gcd {\n my ($m, $n) = @_;\n ($m, $n) = ($n, $m % $n) while $n;\n return $m\n}\n\nsub rat_machine {\n my $n = shift;\n my $denom = 1;\n while ($n != int $n) {\n # assuming the machine format is base 2, and multiplying\n # by 2 doesn't change the mantissa\n $n *= 2;\n\n # multiply denom by 2, ignoring (very) possible overflow\n $denom <<= 1;\n }\n if ($n) {\n my $g = gcd($n, $denom);\n $n /= $g;\n $denom /= $g;\n }\n return $n, $denom;\n}\n\n# helper, make continued fraction back into normal fraction\nsub get_denom {\n my ($num, $denom) = (1, pop @_);\n for (reverse @_) {\n ($num, $denom) = ($denom, $_ * $denom + $num);\n }\n wantarray ? ($num, $denom) : $denom\n}\n\nsub best_approx {\n my ($n, $limit) = @_;\n my ($denom, $neg);\n if ($n < 0) {\n $neg = 1;\n $n = -$n;\n }\n\n my $int = int($n);\n my ($num, $denom, @coef) = (1, $n - $int);\n\n # continued fraction, sort of\n while (1) {\n # make sure it terminates\n last if $limit * $denom < 1;\n my $i = int($num / $denom);\n\n # not the right way to get limit, but it works\n push @coef, $i;\n\n if (get_denom(@coef) > $limit) {\n pop @coef;\n last;\n }\n\n # we lose precision here, but c'est la vie\n ($num, $denom) = ($denom, $num - $i * $denom);\n }\n\n ($num, $denom) = get_denom @coef;\n $num += $denom * $int;\n\n return $neg ? -$num : $num, $denom;\n}\n\nsub rat_string {\n my $n = shift;\n my $denom = 1;\n my $neg;\n\n # trival xyz.0000 ... case\n $n =~ s/\\.0+$//;\n return $n, 1 unless $n =~ /\\./;\n\n if ($n =~ /^-/) {\n $neg = 1;\n $n =~ s/^-//;\n }\n\n # shift decimal point to the right till it's gone\n $denom *= 10 while $n =~ s/\\.(\\d)/$1\\./;\n $n =~ s/\\.$//;\n\n # removing leading zeros lest it looks like octal\n $n =~ s/^0*//;\n if ($n) {\n my $g = gcd($n, $denom);\n $n /= $g;\n $denom /= $g;\n }\n return $neg ? -$n : $n, $denom;\n}\n\nmy $limit = 1e8;\nmy $x = 3/8;\nprint \"3/8 = $x:\\n\";\nprintf \"machine: %d/%d\\n\", rat_machine $x;\nprintf \"string: %d/%d\\n\", rat_string $x;\nprintf \"approx below $limit: %d/%d\\n\", best_approx $x, $limit;\n\n$x = 137/4291;\nprint \"\\n137/4291 = $x:\\n\";\nprintf \"machine: %d/%d\\n\", rat_machine $x;\nprintf \"string: %d/%d\\n\", rat_string $x;\nprintf \"approx below $limit: %d/%d\\n\", best_approx $x, $limit;\n\n$x = sqrt(1/2);\nprint \"\\n1/sqrt(2) = $x\\n\";\nprintf \"machine: %d/%d\\n\", rat_machine $x;\nprintf \"string: %d/%d\\n\", rat_string $x;\nprintf \"approx below 10: %d/%d\\n\", best_approx $x, 10;\nprintf \"approx below 100: %d/%d\\n\", best_approx $x, 100;\nprintf \"approx below 1000: %d/%d\\n\", best_approx $x, 1000;\nprintf \"approx below 10000: %d/%d\\n\", best_approx $x, 10000;\nprintf \"approx below 100000: %d/%d\\n\", best_approx $x, 100000;\nprintf \"approx below $limit: %d/%d\\n\", best_approx $x, $limit;\n\n$x = -4 * atan2(1,1);\nprint \"\\n-Pi = $x\\n\";\nprintf \"machine: %d/%d\\n\", rat_machine $x;\nprintf \"string: %d/%d\\n\", rat_string $x;\n\nfor (map { 10 ** $_ } 1 .. 10) {\n printf \"approx below %g: %d / %d\\n\", $_, best_approx($x, $_)\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">decrat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">nom</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">denom</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #7060A8;\">assert</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #008000;\">\"0.\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #7060A8;\">assert</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #008000;\">'0'</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #008000;\">'9'</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">nom</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">nom</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">10</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #008000;\">'0'</span>\n <span style=\"color: #000000;\">denom</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #000000;\">10</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">sq_div</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">nom</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #7060A8;\">gcd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nom</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">denom</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">decrat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"0.9054054\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">decrat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"0.518518\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">decrat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"0.75\"</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "function asRational($val, $tolerance = 1.e-6)\n{\n if ($val == (int) $val) {\n // integer\n return $val;\n }\n\n $h1=1;\n $h2=0;\n $k1=0;\n $k2=1;\n $b = 1 / $val;\n\n do {\n $b = 1 / $b;\n $a = floor($b);\n $aux = $h1;\n $h1 = $a * $h1 + $h2;\n $h2 = $aux;\n $aux = $k1;\n $k1 = $a * $k1 + $k2;\n $k2 = $aux;\n $b = $b - $a;\n } while (abs($val-$h1/$k1) > $val * $tolerance);\n\n return $h1.'/'.$k1;\n}\n\necho asRational(1/5).\"\\n\"; // \"1/5\"\necho asRational(1/4).\"\\n\"; // \"1/4\"\necho asRational(1/3).\"\\n\"; // \"1/3\"\necho asRational(5).\"\\n\"; // \"5\"\n", "language": "PHP" }, { "code": "(size, fofl):\nConvert_Decimal_To_Rational: procedure options (main); /* 14 January 2014, from Ada */\n\nReal_To_Rational: procedure (R, Bound, Numerator, Denominator) recursive\n options (reorder);\n declare R float (18), Bound float,\n (Numerator, Denominator) fixed binary (31);\n declare Error float;\n declare Best fixed binary initial (1);\n declare Best_Error float initial (huge(error));\n declare I fixed binary (31);\n\n if R = 0 then\n do;\n Numerator = 0;\n Denominator = 1;\n return;\n end;\n else if R < 0 then\n do;\n call Real_To_Rational(-R, Bound, Numerator, Denominator);\n Numerator = -Numerator;\n return;\n end;\n else\n do I = 1 to Bound;\n Error = abs(I * R - trunc(I * R + sign(R)*0.5));\n if Error < Best_Error then\n do;\n Best = I;\n Best_Error = Error;\n end;\n end;\n\n Denominator = Best;\n Numerator = Denominator * R + sign(R) * 0.5;\n\nend Real_To_Rational;\n\n\n declare (Num, Denom) fixed binary (31);\n declare R float (18);\n declare I fixed BINARY;\n\n do R = 0.75, 0.25, 0.3333333, 0.518518000, 0.905405400,\n 0.142857143, 3.141592654, 2.718281828, -0.423310825,\n 31.415926536, 0;\n put skip edit(R) (f(13,9));\n do I = 0 to 4;\n call Real_to_Rational(R, 10**I, Num, Denom);\n put edit(' ' || trim(Num) || ' / ' || trim(Denom)) (a);\n end;\n end;\nend Convert_Decimal_To_Rational;\n", "language": "PL-I" }, { "code": "Procedure.i ggT(a.i, b.i)\n Define t.i : If a < b : Swap a, b : EndIf\n While a%b : t=a : a=b : b=t%a : Wend : ProcedureReturn b\nEndProcedure\n\nProcedure.s Dec2Rat(dn.d)\n Define nk$, gt.i, res$\n nk$=Trim(StringField(StrD(dn),2,\".\"),\"0\")\n gt=ggT(Val(nk$),Int(Pow(10.0,Len(nk$))))\n res$=Str(Val(nk$)/gt)+\"/\"+Str(Int(Pow(10.0,Len(nk$)))/gt)\n ProcedureReturn res$\nEndProcedure\n\nOpenConsole()\nDefine d.d\nRepeat\n Read.d d : If Not (d>0.0 And d<1.0) : Break : EndIf\n Print(LSet(StrD(d),15,\" \")+\" -> \"+#TAB$+Dec2Rat(d)+#CRLF$)\nForEver\nInput() : End\n\nDataSection\n Data.d 0.9054054,0.518518,0.75,0.0\nEndDataSection\n", "language": "PureBasic" }, { "code": ">>> from fractions import Fraction\n>>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100))\n\n0.9054054 67/74\n0.518518 14/27\n0.75 3/4\n>>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d))\n\n0.9054054 4527027/5000000\n0.518518 259259/500000\n0.75 3/4\n>>>\n", "language": "Python" }, { "code": "'''Approximate rationals from decimals'''\n\nfrom math import (floor, gcd)\nimport sys\n\n\n# approxRatio :: Float -> Float -> Ratio\ndef approxRatio(epsilon):\n '''The simplest rational approximation to\n n within the margin given by epsilon.\n '''\n def gcde(e, x, y):\n def _gcd(a, b):\n return a if b < e else _gcd(b, a % b)\n return _gcd(abs(x), abs(y))\n return lambda n: (lambda c=(\n gcde(epsilon if 0 < epsilon else (0.0001), 1, n)\n ): ratio(floor(n / c))(floor(1 / c)))()\n\n\n# main :: IO ()\ndef main():\n '''Conversions at different levels of precision.'''\n\n xs = [0.9054054, 0.518518, 0.75]\n print(\n fTable(__doc__ + ' (epsilon of 1/10000):\\n')(str)(\n lambda r: showRatio(r) + ' -> ' + repr(fromRatio(r))\n )(\n approxRatio(1 / 10000)\n )(xs)\n )\n print('\\n')\n\n e = minBound(float)\n print(\n fTable(__doc__ + ' (epsilon of ' + repr(e) + '):\\n')(str)(\n lambda r: showRatio(r) + ' -> ' + repr(fromRatio(r))\n )(\n approxRatio(e)\n )(xs)\n )\n\n\n# GENERIC -------------------------------------------------\n\n# fromRatio :: Ratio Int -> Float\ndef fromRatio(r):\n '''A floating point value derived from a\n a rational value.\n '''\n return r.get('numerator') / r.get('denominator')\n\n\n# minBound :: Bounded Type -> a\ndef minBound(t):\n '''Minimum value for a bounded type.'''\n maxsize = sys.maxsize\n float_infomin = sys.float_info.min\n return {\n int: (-maxsize - 1),\n float: float_infomin,\n bool: False,\n str: chr(0)\n }[t]\n\n\n# ratio :: Int -> Int -> Ratio Int\ndef ratio(n):\n '''Rational value constructed\n from a numerator and a denominator.\n '''\n def go(n, d):\n g = gcd(n, d)\n return {\n 'type': 'Ratio',\n 'numerator': n // g, 'denominator': d // g\n }\n return lambda d: go(n * signum(d), abs(d))\n\n\n# showRatio :: Ratio -> String\ndef showRatio(r):\n '''String representation of the ratio r.'''\n d = r.get('denominator')\n return str(r.get('numerator')) + (\n ' / ' + str(d) if 1 != d else ''\n )\n\n\n# signum :: Num -> Num\ndef signum(n):\n '''The sign of n.'''\n return -1 if 0 > n else (1 if 0 < n else 0)\n\n\n# DISPLAY -------------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "[ $ \"bigrat.qky\" loadfile ] now!\n\n [ dup echo$\n say \" is \"\n $->v drop\n dup 100 > if\n [ say \"approximately \"\n proper 100 round\n improper ]\n vulgar$ echo$\n say \".\" cr ] is task ( $ --> )\n\n$ \"0.9054054 0.518518 0.75\" nest$ witheach task\n", "language": "Quackery" }, { "code": "ratio<-function(decimal){\n denominator=1\n while(nchar(decimal*denominator)!=nchar(round(decimal*denominator))){\n denominator=denominator+1\n }\n str=paste(decimal*denominator,\"/\",sep=\"\")\n str=paste(str,denominator,sep=\"\")\n return(str)\n}\n", "language": "R" }, { "code": "#lang racket\n\n(inexact->exact 0.75) ; -> 3/4\n(exact->inexact 3/4) ; -> 0.75\n\n(exact->inexact 67/74) ; -> 0.9054054054054054\n(inexact->exact 0.9054054054054054) ;-> 8155166892806033/9007199254740992\n", "language": "Racket" }, { "code": "say .nude.join('/') for 0.9054054, 0.518518, 0.75;\n", "language": "Raku" }, { "code": "sub decimal_to_fraction ( Str $n, Int $rep_digits = 0 ) returns Str {\n my ( $int, $dec ) = ( $n ~~ /^ (\\d+) \\. (\\d+) $/ )».Str or die;\n\n my ( $numer, $denom ) = ( $dec, 10 ** $dec.chars );\n if $rep_digits {\n my $to_move = $dec.chars - $rep_digits;\n $numer -= $dec.substr(0, $to_move);\n $denom -= 10 ** $to_move;\n }\n\n my $rat = Rat.new( $numer.Int, $denom.Int ).nude.join('/');\n return $int > 0 ?? \"$int $rat\" !! $rat;\n}\n\nmy @a = ['0.9054', 3], ['0.518', 3], ['0.75', 0], | (^4).map({['12.34567', $_]});\nfor @a -> [ $n, $d ] {\n say \"$n with $d repeating digits = \", decimal_to_fraction( $n, $d );\n}\n", "language": "Raku" }, { "code": "/*REXX program converts a rational fraction [n/m] (or nnn.ddd) to it's lowest terms.*/\nnumeric digits 10 /*use ten decimal digits of precision. */\nparse arg orig 1 n.1 \"/\" n.2; if n.2='' then n.2=1 /*get the fraction.*/\nif n.1='' then call er 'no argument specified.'\n\n do j=1 for 2; if \\datatype(n.j, 'N') then call er \"argument isn't numeric:\" n.j\n end /*j*/ /* [↑] validate arguments: n.1 n.2 */\n\nif n.2=0 then call er \"divisor can't be zero.\" /*Whoa! We're dividing by zero ! */\nsay 'old =' space(orig) /*display the original fraction. */\nsay 'new =' rat(n.1/n.2) /*display the result ──► terminal. */\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ner: say; say '***error***'; say; say arg(1); say; exit 13\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nrat: procedure; parse arg x 1 _x,y; if y=='' then y = 10**(digits()-1)\n b=0; g=0; a=1; h=1 /* [↑] Y is the tolerance.*/\n do while a<=y & g<=y; n=trunc(_x)\n _=a; a=n*a+b; b=_\n _=g; g=n*g+h; h=_\n if n=_x | a/g=x then do; if a>y | g>y then iterate\n b=a; h=g; leave\n end\n _x=1/(_x-n)\n end /*while*/\n if h==1 then return b /*don't return number ÷ by 1.*/\n return b'/'h /*proper or improper fraction. */\n", "language": "REXX" }, { "code": "/*REXX program to convert decimal numbers to fractions ****************\n* 15.08.2012 Walter Pachl derived from above for readability\n* It took me time to understand :-) I need descriptive variable names\n* Output shows where the fraction only approximates the number\n* due to the limit (high) imposed on nominator and denominator\n**********************************************************************/\n Numeric Digits 10 /* use \"only\" 10 digs of precision */\n Call test '0.9054054054','67/74'\n Call test '0.5185185185','14/27'\n Call test '0.75' ,'3/4'\n Call test '0.905405400',' 693627417/766095958'\n Call test '0.9054054054','67/74'\n Call test '0.1428571428','1/7'\n Call test '35.000','35'\n Call test '35.001','35001/1000'\n Call test '0.00000000001','?'\n Call test '0.000001000001','1/999999'\n Exit\n\ntest:\n/**********************************************************************\n* Test driver for rat\n**********************************************************************/\n Parse Arg d,fs /* number and expected fraction */\n fh=rat(d) /* convert number to fracrion */\n Call o ' 'd fh\n If fh<>fs Then Call o ' not='fs\n interpret 'x='fh /* compute value of fraction */\n If x<>d Then /* not exactly equal to number */\n Call o '> '||x 'is different'\n Call o ' '\n Return\n\no: Say arg(1); Return\n\nrat: procedure\n/**********************************************************************\n* rat(number<,high) returns a fraction or an integer that is equal to\n* or approximately equal to number.\n* Nominator and denominator must not have more than high digits\n* 15.08.2012 Walter Pachl derived from Version 1\n**********************************************************************/\nparse arg in,high\n x=in /* working copy */\n if high=='' then\n high=10**(digits()-1) /* maximum nominator/denominator */\n nom=0 /* start values nominator */\n den=1 /* denominator */\n tnom=1 /* temp nominator */\n tden=0 /* temp denominator */\n do While tnom<=high & tden<=high /* nominator... not too large */\n n=trunc(x) /* take integer part of x */\n z=tnom; /* save temp nominator */\n tnom=n*tnom+nom; /* compute new temp nominator */\n nom=z /* assign nominator */\n z=tden; /* save temp denominator */\n tden=n*tden+den /* compute new temp denominato*/\n den=z /* assign denominator */\n if n=x | tnom/tden=in then do\n if tnom>high | tden>high then /* temp value(s) too large */\n Leave /* don't use them */\n nom=tnom /* otherwise take them as */\n den=tden /* final values */\n leave /* and end the loop */\n end\n x=1/(x-n) /* compute x for next round */\n end\n if den=1 then return nom /* denominator 1: integer */\n return nom'/'den /* otherwise a fraction */\n", "language": "REXX" }, { "code": "/* REXX ---------------------------------------------------------------\n* 13.02.2014 Walter Pachl\n* specify the number as xxx.yyy(pqr) pqr is the period\n* for the number xxx.yyypqrpqrpqrpqrpqr...\n*--------------------------------------------------------------------*/\nNumeric Digits 100\nCall test '5.55555','111111/20000'\nCall test '3','3'\nCall test '0.03','3/100'\nCall test '0.9(054)','67/74'\nCall test '0.(3)','1/3'\nCall test '5.28(571428)','37/7'\nCall test '5.28(571428)','38/7 (demonstrate error case)'\nCall test '0.(518)','14/27'\nCall test '0.75' ,'3/4'\nCall test '0.(142857)','1/7'\nCall test '0.1(428571)','1/7'\nCall test '35.000','35'\nCall test '35.001','35001/1000'\nCall test '0.00000000001','1/100000000000'\nCall test '0.000001000001','1000001/1000000000000'\nExit\ntest:\n Parse Arg z, soll\n zin=z\n If pos('(',z)=0 Then Do\n Parse Var z i '.' f\n z=i||f\n n=10**length(f)\n End\n Else Do\n lp=pos('(',z)-3\n rp=pos(')',z)-4\n x=space(translate(z,' ','()'),0)\n z1=x*10**lp\n Parse Var z1 z1 '.'\n z2=x*10**rp\n z=z2-z1\n n=10**rp-10**lp\n End\n dd=gcd(z,n)\n zz=z/dd\n nn=n/dd\n If nn=1 Then\n fract=zz\n Else\n fract=zz'/'nn\n If fract==soll Then\n tag='ok'\n Else\n tag='should be' soll\n say zin '=' fract tag\n Return\n\nGCD: procedure\n/**********************************************************************\n* Recursive procedure\n**********************************************************************/\nParse Arg a,b\nif b = 0 then return abs(a)\nreturn GCD(b,a//b)\n", "language": "REXX" }, { "code": "> '0.9054054 0.518518 0.75'.split.each { |d| puts \"%s %s\" % [d, Rational(d)] }\n0.9054054 4527027/5000000\n0.518518 259259/500000\n0.75 3/4\n=> [\"0.9054054\", \"0.518518\", \"0.75\"]\n", "language": "Ruby" }, { "code": "[0.9054054, 0.518518, 0.75].each { |f| puts \"#{f} #{f.rationalize(0.0001)}\" }\n# =>0.9054054 67/74\n# =>0.518518 14/27\n# =>0.75 3/4\n", "language": "Ruby" }, { "code": "extern crate rand;\nextern crate num;\n\nuse num::Integer;\nuse rand::Rng;\n\nfn decimal_to_rational (mut n : f64) -> [isize;2] {\n //Based on Farey sequences\n assert!(n.is_finite());\n let flag_neg = n < 0.0;\n if flag_neg { n = n*(-1.0) }\n if n < std::f64::MIN_POSITIVE { return [0,1] }\n if (n - n.round()).abs() < std::f64::EPSILON { return [n.round() as isize, 1] }\n let mut a : isize = 0;\n let mut b : isize = 1;\n let mut c : isize = n.ceil() as isize;\n let mut d : isize = 1;\n let aux1 = isize::max_value()/2;\n while c < aux1 && d < aux1 {\n let aux2 : f64 = (a as f64 + c as f64)/(b as f64 + d as f64);\n if (n - aux2).abs() < std::f64::EPSILON { break }\n if n > aux2 {\n a = a + c;\n b = b + d;\n } else {\n c = a + c;\n d = b + d;\n }\n }\n // Make sure that the fraction is irreducible\n let gcd = (a+c).gcd(&(b+d));\n if flag_neg { [-(a + c)/gcd, (b + d)/gcd] } else { [(a + c)/gcd, (b + d)/gcd] }\n}\n\n#[test]\nfn test1 () {\n // Test the function with 1_000_000 random decimal numbers\n let mut rng = rand::thread_rng();\n for _i in 1..1_000_000 {\n let number = rng.gen::<f64>();\n let result = decimal_to_rational(number);\n assert!((number - (result[0] as f64)/(result[1] as f64)).abs() < std::f64::EPSILON);\n assert!(result[0].gcd(&result[1]) == 1);\n }\n}\n\nfn main () {\n let mut rng = rand::thread_rng();\n for _i in 1..10 {\n let number = rng.gen::<f64>();\n let result = decimal_to_rational(number);\n if result[1] == 1 { println!(\"{} -> {}\", number, result[0]) } else { println!(\"{} -> {}/{}\", number, result[0], result[1]) }\n }\n for i in [-0.9054054, 0.518518, -0.75, 0.5185185185185185, -0.9054054054054054, 0.0, 1.0, 2.0].iter() {\n let result = decimal_to_rational(*i as f64);\n if result[1] == 1 { println!(\"{} = {}\",*i, result[0]) } else { println!(\"{} = {}/{}\", *i, result[0], result[1]) }\n }\n}\n", "language": "Rust" }, { "code": "import org.apache.commons.math3.fraction.BigFraction\n\nobject Number2Fraction extends App {\n val n = Array(0.750000000, 0.518518000, 0.905405400,\n 0.142857143, 3.141592654, 2.718281828, -0.423310825, 31.415926536)\n for (d <- n)\n println(f\"$d%-12s : ${new BigFraction(d, 0.00000002D, 10000)}%s\")\n}\n", "language": "Scala" }, { "code": "$ include \"seed7_05.s7i\";\n include \"bigrat.s7i\";\n\nconst proc: main is func\n begin\n writeln(bigRational parse \"0.9(054)\");\n writeln(bigRational parse \"0.(518)\");\n writeln(bigRational parse \"0.75\");\n writeln(bigRational parse \"3.(142857)\");\n writeln(bigRational parse \"0.(8867924528301)\");\n writeln(bigRational parse \"0.(846153)\");\n writeln(bigRational parse \"0.9054054\");\n writeln(bigRational parse \"0.518518\");\n writeln(bigRational parse \"0.14285714285714\");\n writeln(bigRational parse \"3.14159265358979\");\n writeln(bigRational parse \"2.718281828\");\n writeln(bigRational parse \"31.415926536\");\n writeln(bigRational parse \"0.000000000\");\n\n writeln;\n\n writeln(fraction(bigRational(\"0.9(054)\")));\n writeln(fraction(bigRational(\"0.(518)\")));\n writeln(fraction(bigRational(\"0.75\")));\n writeln(fraction(bigRational(\"3.(142857)\")));\n writeln(fraction(bigRational(\"0.(8867924528301)\")));\n writeln(fraction(bigRational(\"0.(846153)\")));\n writeln(fraction(bigRational(\"0.9054054\")));\n writeln(fraction(bigRational(\"0.518518\")));\n writeln(fraction(bigRational(\"0.14285714285714\")));\n writeln(fraction(bigRational(\"3.14159265358979\")));\n writeln(fraction(bigRational(\"2.718281828\")));\n writeln(fraction(bigRational(\"31.415926536\")));\n writeln(fraction(bigRational(\"0.000000000\")));\n end func;\n", "language": "Seed7" }, { "code": "say 0.75.as_frac #=> 3/4\nsay 0.518518.as_frac #=> 259259/500000\nsay 0.9054054.as_frac #=> 4527027/5000000\n", "language": "Sidef" }, { "code": "'0.9054054 0.518518 0.75'.split.each { |str|\n say Num(str).as_frac\n}\n", "language": "Sidef" }, { "code": "say 0.518518.rat_approx.as_frac #=> 14/27\nsay 0.9054054.rat_approx.as_frac #=> 67/74\n", "language": "Sidef" }, { "code": "#!/usr/bin/env tclsh\n\n proc dbl2frac {dbl {eps 0.000001}} {\n for {set den 1} {$den<1024} {incr den} {\n set num [expr {round($dbl*$den)}]\n if {abs(double($num)/$den - $dbl) < $eps} break\n }\n list $num $den\n }\n#-------------------- That's all... the rest is the test suite\nif {[file tail $argv0] eq [file tail [info script]]} {\n foreach {test -> expected} {\n\t{dbl2frac 0.518518} -> {42 81}\n\t{dbl2frac 0.75} -> {3 4}\n\t{dbl2frac 0.9054054} -> {67 74}\n } {\n\tcatch $test res\n\tif {$res ne $expected} {\n\t puts \"$test -> $res, expected $expected\"\n\t}\n }\n}\n", "language": "Tcl" }, { "code": "STO 0 // Decimal := User Input\n0 STO 1 // Denominator := 0\n*CP // RegT := 0\n1 SUM 1 // Denominator += 1\nRCL 1 * RCL 0 = Inv *Int // Find fractional part of Decimal * Denominator\nInv *x=t 0 6 // If it is nonzero loop back to instruction 6\nRCL 1 x<>t // Report denominator\nRCL 0 * RCL 1 = // Report numerator\nR/S // End\n", "language": "TI-SR-56" }, { "code": "struct Fraction {\n public long d;\n public long n;\n}\n\nFraction rat_approx(double f, long md) {\n long a;\n long[] h = {0, 1, 0};\n long[] k = {1, 0, 0};\n long x, d, n = 1;\n bool neg = false;\n if (md <= 1) return {1, (long)f};\n if (f < 0) {\n neg = true;\n f = -f;\n }\n while (f != Math.floor(f)) {\n n <<= 1;\n f *= 2;\n }\n d = (long)f;\n for (int i = 0; i < 64; i++) {\n a = (n != 0) ? d / n : 0;\n if (i != 0 && a == 0) break;\n x = d; d = n; n = x %n;\n x = a;\n if (k[1] * a + k[0] >= md) {\n x = (md - k[0]) / k[1];\n if (x * 2 >= a || k[1] >= md)\n i = 65;\n else\n break;\n }\n h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];\n k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];\n }\n return {k[1], neg ? -h[1] : h[1]};\n}\n\nvoid main() {\n double f;\n\n print(\"f = %16.14f\\n\", f = 1.0/7);\n for (int i = 1; i < 20000000; i *= 16) {\n print(\"denom <= %11d: \", i);\n var r = rat_approx(f, i);\n print(\"%11ld/%ld\\n\", r.n, r.d);\n }\n\n print(\"f = %16.14f\\n\", f = Math.atan2(1,1) * 4);\n for (int i = 1; i < 20000000; i *= 16) {\n print(\"denom <= %11d: \", i);\n var r = rat_approx(f, i);\n print(\"%11ld/%ld\\n\", r.n, r.d);\n }\n}\n", "language": "Vala" }, { "code": "Function Real2Rational(r As Double, bound As Long) As String\n\nIf r = 0 Then\n Real2Rational = \"0/1\"\nElseIf r < 0 Then\n Result = Real2Rational(-r, bound)\n Real2Rational = \"-\" & Result\nElse\n best = 1\n bestError = 1E+99\n For i = 1 To bound + 1\n currentError = Abs(i * r - Round(i * r))\n If currentError < bestError Then\n best = i\n bestError = currentError\n If bestError < 1 / bound Then GoTo SkipLoop\n End If\n Next i\nSkipLoop:\n Real2Rational = Round(best * r) & \"/\" & best\nEnd If\nEnd Function\n\nSub TestReal2Rational()\nDebug.Print \"0.75\" & \":\";\nFor i = 0 To 5\n Order = CDbl(10) ^ CDbl(i)\n Debug.Print \" \" & Real2Rational(0.75, CLng(Order));\nNext i\nDebug.Print\n\nDebug.Print \"0.518518\" & \":\";\nFor i = 0 To 5\n Order = CDbl(10) ^ CDbl(i)\n Debug.Print \" \" & Real2Rational(0.518518, CLng(Order));\nNext i\nDebug.Print\n\nDebug.Print \"0.9054054\" & \":\";\nFor i = 0 To 5\n Order = CDbl(10) ^ CDbl(i)\n Debug.Print \" \" & Real2Rational(0.9054054, CLng(Order));\nNext i\nDebug.Print\n\nDebug.Print \"0.142857143\" & \":\";\nFor i = 0 To 5\n Order = CDbl(10) ^ CDbl(i)\n Debug.Print \" \" & Real2Rational(0.142857143, CLng(Order));\nNext i\nDebug.Print\n\nDebug.Print \"3.141592654\" & \":\";\nFor i = 0 To 5\n Order = CDbl(10) ^ CDbl(i)\n Debug.Print \" \" & Real2Rational(3.141592654, CLng(Order));\nNext i\nDebug.Print\n\nDebug.Print \"2.718281828\" & \":\";\nFor i = 0 To 5\n Order = CDbl(10) ^ CDbl(i)\n Debug.Print \" \" & Real2Rational(2.718281828, CLng(Order));\nNext i\nDebug.Print\n\nDebug.Print \"-0.423310825\" & \":\";\nFor i = 0 To 5\n Order = CDbl(10) ^ CDbl(i)\n Debug.Print \" \" & Real2Rational(-0.423310825, CLng(Order));\nNext i\nDebug.Print\n\nDebug.Print \"31.415926536\" & \":\";\nFor i = 0 To 5\n Order = CDbl(10) ^ CDbl(i)\n Debug.Print \" \" & Real2Rational(31.415926536, CLng(Order));\nNext i\nEnd Sub\n", "language": "VBA" }, { "code": "import \"./rat\" for Rat\nimport \"./fmt\" for Fmt\n\nvar tests = [0.9054054, 0.518518, 0.75]\nfor (test in tests) {\n var r = Rat.fromFloat(test)\n System.print(\"%(Fmt.s(-9, test)) -> %(r)\")\n}\n", "language": "Wren" }, { "code": "fcn real2Rational(r,bound){\n if (r == 0.0) return(0,1);\n if (r < 0.0){\n result := real2Rational(-r, bound);\n return(-result[0],result[1]);\n } else {\n best,bestError := 1,(1.0).MAX;\n foreach i in ([1 .. bound + 1]){\n error := (r*i - (r*i).round()).abs();\n\t if (error < bestError) best,bestError = i,error;\n }\n return((r*best).round().toInt(),best);\n }\n}\n", "language": "Zkl" }, { "code": "tests := T(0.750000000, 0.518518000, 0.905405400,\n\t 0.142857143, 3.141592654, 2.718281828,\n\t -0.423310825, 31.415926536);\nforeach r in (tests) {\n print(\"%8.9f \".fmt(r));\n foreach i in (6)\n { print(\" %d/%d\".fmt(real2Rational(r,(10).pow(i)).xplode())) }\n println();\n}\n", "language": "Zkl" } ]
Convert-decimal-number-to-rational
[ { "code": "---\ncategory:\n- Date and time\nfrom: http://rosettacode.org/wiki/Convert_seconds_to_compound_duration\n", "language": "00-META" }, { "code": ";Task:\nWrite a function or program which:\n* &nbsp; takes a positive integer representing a duration in seconds as input (e.g., <code>100</code>), and\n* &nbsp; returns a string which shows the same duration decomposed into:\n:::* &nbsp; weeks,\n:::* &nbsp; days, \n:::* &nbsp; hours, \n:::* &nbsp; minutes, &nbsp; and \n:::* &nbsp; seconds.\n\nThis is detailed below (e.g., \"<code>2 hr, 59 sec</code>\").\n\n\nDemonstrate that it passes the following three test-cases:\n\n<p style=\"font-size:115%; margin:1em 0 0.5em 0\">'''''Test Cases'''''</p>\n\n:::::{| class=\"wikitable\"\n|-\n! input number\n! output string\n|-\n| 7259\n| <code style=\"background:#eee\">2 hr, 59 sec</code>\n|-\n| 86400\n| <code style=\"background:#eee\">1 d</code>\n|-\n| 6000000\n| <code style=\"background:#eee\">9 wk, 6 d, 10 hr, 40 min</code>\n|}\n\n<p style=\"font-size:115%; margin:1em 0 0.5em 0\">'''''Details'''''</p>\n\nThe following five units should be used:\n:::::{| class=\"wikitable\"\n|-\n! unit\n! suffix used in output\n! conversion\n|-\n| week\n| <code style=\"background:#eee\">wk</code>\n| 1 week = 7 days\n|-\n| day\n| <code style=\"background:#eee\">d</code>\n| 1 day = 24 hours\n|-\n| hour\n| <code style=\"background:#eee\">hr</code>\n| 1 hour = 60 minutes\n|-\n| minute\n| <code style=\"background:#eee\">min</code>\n| 1 minute = 60 seconds\n|-\n| second\n| <code style=\"background:#eee\">sec</code>\n| \n|}\n\nHowever, '''only''' include quantities with non-zero values in the output (e.g., return \"<code>1 d</code>\" and not \"<code>0 wk, 1 d, 0 hr, 0 min, 0 sec</code>\").\n\nGive larger units precedence over smaller ones as much as possible (e.g., return <code>2 min, 10 sec</code> and not <code>1 min, 70 sec</code> or <code>130 sec</code>)\n\nMimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).\n<hr style=\"margin:1em 0;\"/>\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F duration(=sec)\n [Int] t\n L(dm) [60, 60, 24, 7]\n Int m\n (sec, m) = (sec I/ dm, sec % dm)\n t.insert(0, m)\n t.insert(0, sec)\n R zip(t, [‘wk’, ‘d’, ‘hr’, ‘min’, ‘sec’]).filter(num_unit -> num_unit[0] > 0).map(num_unit -> num_unit[0]‘ ’num_unit[1]).join(‘, ’)\n\nprint(duration(7259))\nprint(duration(86400))\nprint(duration(6000000))\n", "language": "11l" }, { "code": "INCLUDE \"H6:REALMATH.ACT\"\nDEFINE PTR=\"CARD\"\n\nTYPE Time=[BYTE s,m,h,d,w]\nCARD ARRAY units(5)\n\nPROC Convert(REAL POINTER seconds Time POINTER t)\n BYTE ARRAY b,duration=[60 60 24 7]\n BYTE i\n REAL r,n\n\n b=t\n FOR i=0 TO 3\n DO\n IntToReal(duration(i),n)\n RealMod(seconds,n,r)\n b(i)=RealToInt(r)\n RealDivInt(seconds,n,r)\n RealAssign(r,seconds)\n OD\n b(4)=RealToInt(seconds)\nRETURN\n\nPROC PrintTime(Time POINTER t)\n INT i\n BYTE first,n\n BYTE ARRAY b\n\n b=t i=4 first=1\n WHILE i>=0\n DO\n n=b(i)\n IF n>0 THEN\n IF first=0 THEN\n Print(\", \")\n ELSE\n first=0\n FI\n PrintF(\"%B %S\",n,units(i))\n FI\n i==-1\n OD\nRETURN\n\nPROC Test(CHAR ARRAY s)\n REAL seconds\n Time t\n\n ValR(s,seconds)\n PrintR(seconds) Print(\" -> \")\n Convert(seconds,t)\n PrintTime(t) PutE()\nRETURN\n\nPROC Main()\n Put(125) PutE() ;clear the screen\n MathInit()\n units(0)=\"sec\" units(1)=\"min\"\n units(2)=\"hr\" units(3)=\"d\"\n units(4)=\"wk\"\n Test(\"7259\")\n Test(\"86400\")\n Test(\"6000000\")\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO;\n\nprocedure Convert is\n\n type Time is range 0 .. 10_000*356*20*60*60; -- at most 10_000 years\n subtype Valid_Duration is Time range 1 .. 10_000*356*20*60*60;\n type Units is (WK, D, HR, MIN, SEC);\n\n package IO renames Ada.Text_IO;\n\n Divide_By: constant array(Units) of Time := (1_000*53, 7, 24, 60, 60);\n Split: array(Units) of Time;\n No_Comma: Units;\n X: Time;\n\n Test_Cases: array(Positive range <>) of Valid_Duration :=\n (6, 60, 3659, 7_259, 86_400, 6_000_000, 6_001_200, 6_001_230, 600_000_000);\n\nbegin\n for Test_Case of Test_Cases loop\n IO.Put(Time'Image(Test_Case) & \" SECONDS =\");\n X := Test_Case;\n\t\n -- split X up into weeks, days, ..., seconds\n No_Comma := Units'First;\n for Unit in reverse Units loop -- Unit = SEC, ..., WK (in that order)\n\tSplit(Unit) := X mod Divide_By(Unit);\n\tX := X / Divide_By(Unit);\n\tif Unit > No_Comma and Split(Unit)>0 then\n\t No_Comma := Unit;\n\tend if;\n end loop;\n\t\n -- ouput weeks, days, ..., seconds\n for Unit in Units loop -- Unit = WK, .., SEC (in that order)\n\tif Split(Unit) > 0 then\n\t IO.Put(Time'Image(Split(Unit)) & \" \" & Units'Image(Unit) &\n\t\t (if No_Comma > Unit then \",\" else \"\"));\n\tend if;\n end loop;\n\n IO.New_Line;\n end loop;\nend Convert;\n", "language": "Ada" }, { "code": "# MODE to hold the compound duration #\nMODE DURATION = STRUCT( INT weeks, days, hours, minutes, seconds );\n\n# returns seconds converted to a DURATION #\nOP TODURATION = ( LONG INT seconds )DURATION:\n BEGIN\n LONG INT time := seconds;\n DURATION result := DURATION( 0, 0, 0, 0, 0 );\n seconds OF result := SHORTEN ( time MOD 60 );\n time OVERAB 60;\n minutes OF result := SHORTEN ( time MOD 60 );\n time OVERAB 60;\n hours OF result := SHORTEN ( time MOD 24 );\n time OVERAB 24;\n days OF result := SHORTEN ( time MOD 7 );\n time OVERAB 7;\n weeks OF result := SHORTEN time;\n result\n END # DURATION # ;# returns seconds converted to a DURATION #\nOP TODURATION = ( INT seconds )DURATION: TODURATION LENG seconds;\n\n# returns a readable form of the DURATION #\nOP TOSTRING = ( DURATION t )STRING:\n BEGIN\n STRING result := \"\";\n STRING separator := \"\";\n IF weeks OF t /= 0 THEN result +:= separator + whole( weeks OF t, 0 ) + \" wk\"; separator := \", \" FI;\n IF days OF t /= 0 THEN result +:= separator + whole( days OF t, 0 ) + \" d\"; separator := \", \" FI;\n IF hours OF t /= 0 THEN result +:= separator + whole( hours OF t, 0 ) + \" hr\"; separator := \", \" FI;\n IF minutes OF t /= 0 THEN result +:= separator + whole( minutes OF t, 0 ) + \" min\"; separator := \", \" FI;\n IF seconds OF t /= 0 THEN result +:= separator + whole( seconds OF t, 0 ) + \" sec\"; separator := \", \" FI;\n IF result = \"\"\n THEN\n # duration is 0 #\n result := \"0 sec\"\n FI;\n result\n END # TOSTRING # ;\n\n# test cases #\nprint( ( TOSTRING TODURATION 7259, newline ) );\nprint( ( TOSTRING TODURATION 86400, newline ) );\nprint( ( TOSTRING TODURATION 6000000, newline ) )\n", "language": "ALGOL-68" }, { "code": "begin\n % record structure to hold a compound duration %\n record Duration ( integer weeks, days, hours, minutes, seconds );\n\n % returns seconds converted to a Duration %\n reference(Duration) procedure toDuration( integer value secs ) ;\n begin\n integer time;\n reference(Duration) d;\n time := secs;\n d := Duration( 0, 0, 0, 0, 0 );\n seconds(d) := time rem 60;\n time := time div 60;\n minutes(d) := time rem 60;\n time := time div 60;\n hours(d) := time rem 24;\n time := time div 24;\n days(d) := time rem 7;\n time := time div 7;\n weeks(d) := time;\n d\n end toDuration ;\n\n % returns a readable form of the DURATION %\n string(80) procedure durationToString ( reference(Duration) value d ) ;\n begin\n % appends an element of the compound duration to text %\n procedure add ( integer value componentValue\n ; string(6) value componentName\n ; integer value nameLength\n ) ;\n begin\n string(9) vStr;\n integer v, vPos;\n if needSeparator then begin\n % must separate this component from the previous %\n text( textPos // 2 ) := \", \";\n textPos:= textPos + 2\n end if_needSepartator ;\n % add the value %\n % construct a string representaton of the value with the digits reversed %\n % as this routine isn't called if componentValue is 0 or -ve, we don't need to handle %\n % the componentVaue <= 0 case %\n v := componentValue;\n vStr := \"\";\n vPos := 0;\n while v > 0 do begin\n vStr( vPos // 1 ) := code( decode( \"0\" ) + ( v rem 10 ) );\n vPos := vPos + 1;\n v := v div 10\n end while_v_gt_0 ;\n % add the digits in the correct order %\n while vPos > 0 do begin\n vPos := vPos - 1;\n text( textPos // 1 ) := vStr( vPos // 1 );\n textPos := textPos + 1\n end while_vPos_gt_0 ;\n % add the component name %\n text( textPos // 6 ) := componentName;\n textPos := textPos + nameLength;\n % if there is another component, we'll need a separator %\n needSeparator := true\n end add ;\n\n string(80) text;\n logical needSeparator;\n integer textPos;\n textPos := 0;\n text := \"\";\n needSeparator := false;\n if weeks(d) not = 0 then add( weeks(d), \" wk\", 3 );\n if days(d) not = 0 then add( days(d), \" d\", 2 );\n if hours(d) not = 0 then add( hours(d), \" hr\", 3 );\n if minutes(d) not = 0 then add( minutes(d), \" min\", 4 );\n if seconds(d) not = 0 then add( seconds(d), \" sec\", 4 );\n if text = \"\" then begin\n % duration is 0 %\n text := \"0 sec\"\n end if_text_is_blank ;\n text\n end % durationToString % ;\n\n % test cases %\n write( durationToString( toDuration( 7259 ) ) );\n write( durationToString( toDuration( 86400 ) ) );\n write( durationToString( toDuration( 6000000 ) ) )\nend.\n", "language": "ALGOL-W" }, { "code": "duration←{\n names←'wk' 'd' 'hr' 'min' 'sec'\n parts←0 7 24 60 60⊤⍵\n fmt←⍕¨(parts≠0)/parts,¨names\n ¯2↓∊fmt,¨⊂', '\n}\n", "language": "APL" }, { "code": "-------------------- COMPOUND DURATIONS ------------------\n\n-- weekParts Int -> [Int]\non weekParts(intSeconds)\n unitParts(intSeconds, [missing value, 7, 24, 60, 60])\nend weekParts\n\n\n-- localCompoundDuration :: Int -> String\non localCompoundDuration(localNames, intSeconds)\n\n -- [String] -> (Int, String) -> [String]\n script formatted\n on |λ|(lstPair, a)\n set q to item 1 of lstPair\n if q > 0 then\n {(q as string) & space & item 2 of lstPair} & a\n else\n a\n end if\n end |λ|\n end script\n\n intercalate(\", \", ¬\n foldr(formatted, [], ¬\n zip(weekParts(intSeconds), localNames)))\nend localCompoundDuration\n\n------------------ INTEGER DECOMPOSITION -----------------\n\n-- unitParts :: Int -> [maybe Int] -> [Int]\non unitParts(intTotal, unitList)\n -- partList :: Record -> Int -> Record\n script partList\n on |λ|(x, a)\n set intRest to remaining of a\n\n if x is not missing value then\n set intMod to intRest mod x\n set d to x\n else\n set intMod to intRest\n set d to 1\n end if\n\n {remaining:(intRest - intMod) div d, parts:{intMod} & parts of a}\n end |λ|\n end script\n\n parts of foldr(partList, ¬\n {remaining:intTotal, parts:[]}, unitList)\nend unitParts\n\n--------------------------- TEST -------------------------\non run\n script angloNames\n on |λ|(n)\n (n as string) & \" -> \" & ¬\n localCompoundDuration([\"wk\", \"d\", \"hr\", \"min\", \"sec\"], n)\n end |λ|\n end script\n\n unlines(map(angloNames, [7259, 86400, 6000000]))\nend run\n\n\n-------------------- GENERIC FUNCTIONS -------------------\n\n-- foldr :: (a -> b -> b) -> b -> [a] -> b\non foldr(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from lng to 1 by -1\n set v to |λ|(item i of xs, v, i, xs)\n end repeat\n return v\n end tell\nend foldr\n\n\n-- intercalate :: String -> [String] -> String\non intercalate(delim, xs)\n set {dlm, my text item delimiters} to ¬\n {my text item delimiters, delim}\n set s to xs as text\n set my text item delimiters to dlm\n s\nend intercalate\n\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n -- The list obtained by applying f\n -- to each element of xs.\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n\n-- min :: Ord a => a -> a -> a\non min(x, y)\n if y < x then\n y\n else\n x\n end if\nend min\n\n\n-- mReturn :: First-class m => (a -> b) -> m (a -> b)\non mReturn(f)\n -- 2nd class handler function lifted into 1st class script wrapper.\n if script is class of f then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n\n-- unlines :: [String] -> String\non unlines(xs)\n -- A single string formed by the intercalation\n -- of a list of strings with the newline character.\n set {dlm, my text item delimiters} to ¬\n {my text item delimiters, linefeed}\n set s to xs as text\n set my text item delimiters to dlm\n s\nend unlines\n\n\n-- zip :: [a] -> [b] -> [(a, b)]\non zip(xs, ys)\n -- A list of step-wise pairs drawn from xs and ys\n -- up to the length of the shorter of those lists.\n set lng to min(length of xs, length of ys)\n set zs to {}\n repeat with i from 1 to lng\n set end of zs to {item i of xs, item i of ys}\n end repeat\n return zs\nend zip\n", "language": "AppleScript" }, { "code": "on secondsToCompoundDuration(sec)\n if ((sec's class is not integer) or (sec < 0)) then ¬\n error \"secondsToCompoundDuration() handler only accepts positive integers.\"\n -- The task description notwithstanding, return \"0 sec\" if the input is 0.\n if (sec = 0) then return \"0 sec\"\n -- Otherwise perform the described task.\n set units to {weeks, days, hours, minutes, 1}\n set suffixes to {\" wk, \", \" d, \", \" hr, \", \" min, \", \" sec, \"}\n set output to \"\"\n\n repeat with i from 1 to 5\n set unit to units's item i\n set unitValue to sec div unit\n if (unitValue > 0) then set output to output & unitValue & suffixes's item i\n set sec to sec mod unit\n if (sec = 0) then exit repeat\n end repeat\n\n return output's text 1 thru -3\nend secondsToCompoundDuration\n\nreturn secondsToCompoundDuration(7259) & linefeed & ¬\n secondsToCompoundDuration(86400) & linefeed & ¬\n secondsToCompoundDuration(6000000)\n", "language": "AppleScript" }, { "code": "\"2 hr, 59 sec\n1 d\n9 wk, 6 d, 10 hr, 40 min\"\n", "language": "AppleScript" }, { "code": "100 DATA604800,WK,86400,D,3600,HR,60,MIN,1,SEC\n110 FOR I = 0 TO 4\n120 READ M(I), U$(I)\n130 NEXT\n140 DATA7259,86400,6000000\n150 ON ERR GOTO 270\n160 READ S\n170 GOSUB 200\n180 PRINT S \" = \" S$\n190 GOTO 160\n\n200 N = S\n210 S$ = \"\"\n220 FOR I = 0 TO 4\n230 IF INT(N / M(I)) THEN S$ = S$ + MID$(\", \", 1, (LEN(S$) > 0) * 2) + STR$(INT(N / M(I))) + \" \" + U$(I)\n240 N = N - INT(N / M(I)) * M(I)\n250 NEXT I\n260 RETURN\n\n270 END\n", "language": "Applesoft-BASIC" }, { "code": "Units: [\" wk\", \" d\", \" hr\", \" min\", \" sec\"]\nQuantities: @[7 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60, 1]\n\ndurationString: function [d][\n dur: d\n idx: 0\n result: new []\n while [not? zero? dur][\n q: dur / Quantities\\[idx]\n if not? zero? q [\n dur: dur % Quantities\\[idx]\n 'result ++ ~{|q||Units\\[idx]|}\n ]\n idx: idx +1\n ]\n return join.with:\", \" result\n]\n\nloop [7259 86400 6000000] 't [\n print [t \"s => \" durationString t]\n]\n", "language": "Arturo" }, { "code": "duration(n){\n\tsec:=1, min:=60*sec, hr:=60*min, day:=24*hr, wk:=7*day\n\tw\t:=n//wk\t\t, n:=Mod(n,wk)\n\td\t:=n//day\t, n:=Mod(n,day)\n\th\t:=n//hr\t\t, n:=Mod(n,hr)\n\tm\t:=n//min\t, n:=Mod(n,min)\n\ts\t:=n\n\treturn trim((w?w \" wk, \":\"\") (d?d \" d, \":\"\") (h?h \" hr, \":\"\") (m?m \" min, \":\"\") (s?s \" sec\":\"\"),\", \")\n}\n", "language": "AutoHotkey" }, { "code": "data=\n(\n7259\n86400\n6000000\n)\n\nloop, parse, data, `n, `r\n\tres .= A_LoopField \"`t: \" duration(A_LoopField) \"`n\"\nMsgBox % res\nreturn\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f CONVERT_SECONDS_TO_COMPOUND_DURATION.AWK\nBEGIN {\n n = split(\"7259 86400 6000000 0 1 60 3600 604799 604800 694861\",arr,\" \")\n for (i=1; i<=n; i++) {\n printf(\"%9s %s\\n\",arr[i],howlong(arr[i]))\n }\n exit(0)\n}\nfunction howlong(seconds, n_day,n_hour,n_min,n_sec,n_week,str,x) {\n if (seconds >= (x = 60*60*24*7)) {\n n_week = int(seconds / x)\n seconds = seconds % x\n }\n if (seconds >= (x = 60*60*24)) {\n n_day = int(seconds / x)\n seconds = seconds % x\n }\n if (seconds >= (x = 60*60)) {\n n_hour = int(seconds / x)\n seconds = seconds % x\n }\n if (seconds >= (x = 60)) {\n n_min = int(seconds / x)\n seconds = seconds % x\n }\n n_sec = int(seconds)\n str = (n_week > 0) ? (str n_week \" wk, \") : str\n str = (n_day > 0) ? (str n_day \" d, \") : str\n str = (n_hour > 0) ? (str n_hour \" hr, \") : str\n str = (n_min > 0) ? (str n_min \" min, \") : str\n str = (n_sec > 0) ? (str n_sec \" sec\") : str\n sub(/, $/,\"\",str)\n return(str)\n}\n", "language": "AWK" }, { "code": "'--- SAY_TIME Convert seconds to compound duration\n'--- Weeks, days hours, minutes ,seconds\nSUB SAY_TIME(int sec)\n\n\tLOCAL week,day,hour,minute,second TYPE int\n\tweek = sec / 604800\n\tday = MOD(sec /86400,7)\n\thour = MOD(sec / 3600 ,24)\n\tminute = MOD(sec / 60 ,60)\n\tsecond = MOD(sec,60)\n\t\t\n\t\t\n\tIF week > 0 THEN\n\t\tPRINT STR$(week) & \" wk, \" TO p1$ SIZE 100\n\tEND IF\n\n\tIF day > 0 THEN\n\t\tPRINT STR$(day) & \" d, \" TO p2$ SIZE 100\n\tEND IF\n\n\tIF hour > 0 THEN\n\t\tPRINT STR$(hour) & \" h, \" TO p3$ SIZE 100\n\tEND IF\n\n\tIF minute > 0 THEN\n\t\tPRINT STR$(minute) & \" min, \" TO p4$ SIZE 100\n\tEND IF\n\n\tIF second > 0 THEN\n\t\tPRINT STR$(second) & \" sec \" TO p5$ SIZE 100\n\tEND IF\n\n\n\tPRINT p1$ ,p2$, p3$, p4$, p5$\nEND SUB\n\n'---result 9 wk, 6 d, 10 h, 40 min, 7 sec\nSAY_TIME(6000007)\n", "language": "BaCon" }, { "code": "@echo off\n::The Main Thing...\nfor %%d in (7259 86400 6000000) do call :duration %%d\nexit/b 0\n::/The Main Thing.\n\n::The Function...\n:duration\n\tset output=\n\tset /a \"wk=%1/604800,rem=%1%%604800\"\n\tif %wk% neq 0 set \"output= %wk% wk,\"\n\n\tset /a \"d=%rem%/86400,rem=%rem%%%86400\"\n\tif %d% neq 0 set \"output=%output% %d% d,\"\n\n\tset /a \"hr=%rem%/3600,rem=%rem%%%3600\"\n\tif %hr% neq 0 set \"output=%output% %hr% hr,\"\n\n\tset /a \"min=%rem%/60,rem=%rem%%%60\"\n\tif %min% neq 0 set \"output=%output% %min% min,\"\n\n\tif %rem% neq 0 set \"output=%output% %rem% sec,\"\n\n\tif %1 gtr 0 echo %1 sec = %output:~1,-1%\n\tgoto :EOF\n::/The Function.\n", "language": "Batch-File" }, { "code": "REM >compduration\nPRINT FN_convert(7259)\nPRINT FN_convert(86400)\nPRINT FN_convert(6000000)\nEND\n:\nDEF FN_convert(seconds%)\nLOCAL units%(), units$(), i%, unit%, compound$\nDIM units%(4)\nDIM units$(4)\nunits%() = 604800, 86400, 3600, 60, 1\nunits$() = \"wk\", \"d\", \"hr\", \"min\", \"sec\"\ncompound$ = \"\"\nFOR i% = 0 TO 4\n IF seconds% >= units%(i%) THEN\n unit% = seconds% DIV units%(i%)\n seconds% = seconds% MOD units%(i%)\n compound$ += STR$(unit%) + \" \" + units$(i%)\n IF i% < 4 AND seconds% > 0 THEN compound$ += \", \"\n ENDIF\nNEXT\n= compound$\n", "language": "BBC-BASIC" }, { "code": "#>%f# #>%f# #f%<##>%f#\npq\":X~7~ :X@~++8~8@:X:X@~-~4~.+~8@T_\n ## ## #### #`K0[`}`D2[`}BF3< <\n>{` wk, `>g?\"p{` d, `>g?\"p{` hr, `>g?\"p{` min, `>g\"b{` sec, `b\n > d > d > d > d\n", "language": "Beeswax" }, { "code": "&>:\"<\"%\\\"O{rq\"**+\\\"<\"/:\"<\"%\\\"r<|\":*+*5-\\v\nv-7*\"l~\"/7\\\"d\"\\%7:/*83\\+*:\"xD\"\\%*83:/\"<\"<\n> \\:! #v_v#-#<\",\",#$48*#<,#<.#<>#_:\"~\"%,v\n^_@#:$$< > .02g92p ^ ^!:/\"~\"<\n", "language": "Befunge" }, { "code": "/*\n * Program seconds2string, C89 version.\n *\n * Read input from argv[1] or stdin, write output to stdout.\n */\n\n#define _CRT_SECURE_NO_WARNINGS /* unlocks printf in Microsoft Visual Studio */\n\n#include <stdio.h>\n#include <stdlib.h>\n\n/*\n * Converting the number of seconds in a human-readable string.\n * It is worth noting that direct output to stdout would be even simpler.\n */\nchar* seconds2string(unsigned long seconds)\n{\n int i;\n\n const unsigned long s = 1;\n const unsigned long m = 60 * s;\n const unsigned long h = 60 * m;\n const unsigned long d = 24 * h;\n const unsigned long w = 7 * d;\n\n const unsigned long coeff[5] = { w, d, h, m, s };\n const char units[5][4] = { \"wk\", \"d\", \"hr\", \"min\", \"sec\" };\n\n static char buffer[256];\n char* ptr = buffer;\n\n for ( i = 0; i < 5; i++ )\n {\n unsigned long value;\n value = seconds / coeff[i];\n seconds = seconds % coeff[i];\n if ( value )\n {\n if ( ptr != buffer )\n ptr += sprintf(ptr, \", \");\n ptr += sprintf(ptr,\"%lu %s\",value,units[i]);\n }\n }\n\n return buffer;\n}\n\n/*\n * Main function for seconds2string program.\n */\nint main(int argc, char argv[])\n{\n unsigned long seconds;\n\n if ( (argc < 2) && scanf( \"%lu\", &seconds )\n || (argc >= 2) && sscanf( argv[1], \"%lu\", & seconds ) )\n {\n printf( \"%s\\n\", seconds2string(seconds) );\n return EXIT_SUCCESS;\n }\n\n return EXIT_FAILURE;\n}\n", "language": "C" }, { "code": "#include <inttypes.h> /* requires c99 */\n#include <stdbool.h> /* requires c99 */\n#include <stdio.h>\n#include <stdlib.h>\n\n#define N_EL 5\n\nuintmax_t sec_to_week(uintmax_t);\nuintmax_t sec_to_day(uintmax_t);\nuintmax_t sec_to_hour(uintmax_t);\nuintmax_t sec_to_min(uintmax_t);\n\nuintmax_t week_to_sec(uintmax_t);\nuintmax_t day_to_sec(uintmax_t);\nuintmax_t hour_to_sec(uintmax_t);\nuintmax_t min_to_sec(uintmax_t);\n\nchar *format_sec(uintmax_t);\n /* the primary function */\n\n\nint main(int argc, char *argv[])\n{\n uintmax_t input;\n char *a;\n\n if(argc<2) {\n printf(\"usage: %s #seconds\\n\", argv[0]);\n return 1;\n }\n input = strtoumax(argv[1],(void *)0, 10 /*base 10*/);\n if(input<1) {\n printf(\"Bad input: %s\\n\", argv[1]);\n printf(\"usage: %s #seconds\\n\", argv[0]);\n return 1;\n }\n printf(\"Number entered: %\" PRIuMAX \"\\n\", input);\n a = format_sec(input);\n printf(a);\n free(a);\n\n return 0;\n}\n\n/* note: must free memory\n * after using this function */\nchar *format_sec(uintmax_t input)\n{\n int i;\n bool first;\n uintmax_t weeks, days, hours, mins;\n /*seconds kept in input*/\n\n char *retval;\n FILE *stream;\n size_t size;\n uintmax_t *traverse[N_EL]={&weeks,&days,\n &hours,&mins,&input};\n char *labels[N_EL]={\"wk\",\"d\",\"hr\",\"min\",\"sec\"};\n\n weeks = sec_to_week(input);\n input = input - week_to_sec(weeks);\n\n days = sec_to_day(input);\n input = input - day_to_sec(days);\n\n hours = sec_to_hour(input);\n input = input - hour_to_sec(hours);\n\n mins = sec_to_min(input);\n input = input - min_to_sec(mins);\n /* input now has the remaining seconds */\n\n /* open stream */\n stream = open_memstream(&retval,&size);\n if(stream == 0) {\n fprintf(stderr,\"Unable to allocate memory\");\n return 0;\n }\n\n /* populate stream */\n first = true;\n for(i=0;i<N_EL;i++) {\n if ( *(traverse[i]) != 0 ) {\n if(!first) {\n fprintf(stream,\", %\" PRIuMAX \" %s\",\n *(traverse[i]), labels[i]);\n } else {\n fprintf(stream,\"%\" PRIuMAX \" %s\",\n *(traverse[i]), labels[i]);\n }\n fflush(stream);\n first=false;\n }\n }\n fprintf(stream,\"\\n\");\n fclose(stream);\n return retval;\n\n}\n\nuintmax_t sec_to_week(uintmax_t seconds)\n{\n return sec_to_day(seconds)/7;\n}\n\nuintmax_t sec_to_day(uintmax_t seconds)\n{\n return sec_to_hour(seconds)/24;\n}\n\nuintmax_t sec_to_hour(uintmax_t seconds)\n{\n return sec_to_min(seconds)/60;\n}\n\nuintmax_t sec_to_min(uintmax_t seconds)\n{\n return seconds/60;\n}\n\nuintmax_t week_to_sec(uintmax_t weeks)\n{\n return day_to_sec(weeks*7);\n}\n\nuintmax_t day_to_sec(uintmax_t days)\n{\n return hour_to_sec(days*24);\n}\n\nuintmax_t hour_to_sec(uintmax_t hours)\n{\n return min_to_sec(hours*60);\n}\n\nuintmax_t min_to_sec(uintmax_t minutes)\n{\n return minutes*60;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <vector>\n\nusing entry = std::pair<int, const char*>;\n\nvoid print(const std::vector<entry>& entries, std::ostream& out = std::cout)\n{\n bool first = true;\n for(const auto& e: entries) {\n if(!first) out << \", \";\n first = false;\n out << e.first << \" \" << e.second;\n }\n out << '\\n';\n}\n\nstd::vector<entry> convert(int seconds)\n{\n static const entry time_table[] = {\n {7*24*60*60, \"wk\"}, {24*60*60, \"d\"}, {60*60, \"hr\"}, {60, \"min\"}, {1, \"sec\"}\n };\n std::vector<entry> result;\n for(const auto& e: time_table) {\n int time = seconds / e.first;\n if(time != 0) result.emplace_back(time, e.second);\n seconds %= e.first;\n }\n return result;\n}\n\nint main()\n{\n std::cout << \" 7259 sec is \"; print(convert( 7259));\n std::cout << \" 86400 sec is \"; print(convert( 86400));\n std::cout << \"6000000 sec is \"; print(convert(6000000));\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ConvertSecondsToCompoundDuration\n{\n class Program\n {\n static void Main( string[] args )\n {\n foreach ( string arg in args )\n {\n int duration ;\n bool isValid = int.TryParse( arg , out duration ) ;\n\n if ( !isValid ) { Console.Error.WriteLine( \"ERROR: Not an integer: {0}\" , arg ) ; }\n if ( duration < 0 ) { Console.Error.WriteLine( \"ERROR: duration must be non-negative\" , arg ) ; }\n\n Console.WriteLine();\n Console.WriteLine( \"{0:#,##0} seconds ==> {1}\" , duration , FormatAsDuration(duration) ) ;\n\n }\n }\n\n private static string FormatAsDuration( int duration )\n {\n if ( duration < 0 ) throw new ArgumentOutOfRangeException(\"duration\") ;\n return string.Join( \", \" , GetDurationParts(duration) ) ;\n }\n\n private static IEnumerable<string> GetDurationParts( int duration )\n {\n var parts = new[]\n {\n new { Name=\"wk\" , Length = 7*24*60*60*1 , } ,\n new { Name=\"d\" , Length = 24*60*60*1 , } ,\n new { Name=\"h\" , Length = 60*60*1 , } ,\n new { Name=\"m\" , Length = 60*1 , } ,\n new { Name=\"s\" , Length = 1 , } ,\n } ;\n\n foreach ( var part in parts )\n {\n int n = Math.DivRem( duration , part.Length , out duration ) ;\n if ( n > 0 ) yield return string.Format( \"{0} {1}\" , n , part.Name ) ;\n }\n\n }\n\n }\n\n}\n", "language": "C-sharp" }, { "code": "private static string ConvertToCompoundDuration(int seconds)\n{\n if (seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds));\n if (seconds == 0) return \"0 sec\";\n\n TimeSpan span = TimeSpan.FromSeconds(seconds);\n int[] parts = {span.Days / 7, span.Days % 7, span.Hours, span.Minutes, span.Seconds};\n string[] units = {\" wk\", \" d\", \" hr\", \" min\", \" sec\"};\n\n return string.Join(\", \",\n from index in Enumerable.Range(0, units.Length)\n where parts[index] > 0\n select parts[index] + units[index]);\n}\n", "language": "C-sharp" }, { "code": "(require '[clojure.string :as string])\n\n(def seconds-in-minute 60)\n(def seconds-in-hour (* 60 seconds-in-minute))\n(def seconds-in-day (* 24 seconds-in-hour))\n(def seconds-in-week (* 7 seconds-in-day))\n\n(defn seconds->duration [seconds]\n (let [weeks ((juxt quot rem) seconds seconds-in-week)\n wk (first weeks)\n days ((juxt quot rem) (last weeks) seconds-in-day)\n d (first days)\n hours ((juxt quot rem) (last days) seconds-in-hour)\n hr (first hours)\n min (quot (last hours) seconds-in-minute)\n sec (rem (last hours) seconds-in-minute)]\n (string/join \", \"\n (filter #(not (string/blank? %))\n (conj []\n (when (> wk 0) (str wk \" wk\"))\n (when (> d 0) (str d \" d\"))\n (when (> hr 0) (str hr \" hr\"))\n (when (> min 0) (str min \" min\"))\n (when (> sec 0) (str sec \" sec\")))))))\n\n(seconds->duration 7259)\n(seconds->duration 86400)\n(seconds->duration 6000000)\n", "language": "Clojure" }, { "code": "duration = proc (s: int) returns (string)\n own units: array[string] := array[string]$[\"wk\",\"d\",\"hr\",\"min\",\"sec\"]\n own sizes: array[int] := array[int]$[2:7,24,60,60]\n\n d: string := \"\"\n r: int\n for i: int in int$from_to_by(5,1,-1) do\n begin\n r := s // sizes[i]\n s := s / sizes[i]\n end except when bounds:\n r := s\n end\n if r ~= 0 then\n d := \", \" || int$unparse(r) || \" \" || units[i] || d\n end\n end\n return(string$rest(d,3))\nend duration\n\nstart_up = proc ()\n po: stream := stream$primary_output()\n tests: array[int] := array[int]$[7259,86400,6000000]\n\n for test: int in array[int]$elements(tests) do\n stream$putl(po, int$unparse(test) || \" => \" || duration(test))\n end\nend start_up\n", "language": "CLU" }, { "code": " identification division.\n program-id. fmt-dura.\n data division.\n working-storage section.\n 1 input-seconds pic 9(8).\n 1 formatted-duration pic x(30) global.\n 1 fractions.\n 2 weeks pic z(3)9.\n 2 days pic z(3)9.\n 2 hours pic z(3)9.\n 2 minutes pic z(3)9.\n 2 seconds pic z(3)9.\n 1 .\n 2 weeks-str pic x(4) value \"wk\".\n 2 days-str pic x(4) value \"d\".\n 2 hours-str pic x(4) value \"hr\".\n 2 minutes-str pic x(4) value \"min\".\n 2 seconds-str pic x(4) value \"sec\".\n 1 work binary global.\n 2 str-pos pic 9(4).\n 2 chars-transferred pic 9(4).\n procedure division.\n begin.\n display \"Enter duration (seconds): \" no advancing\n accept input-seconds\n divide input-seconds by 60 giving input-seconds\n remainder seconds\n divide input-seconds by 60 giving input-seconds\n remainder minutes\n divide input-seconds by 24 giving input-seconds\n remainder hours\n divide input-seconds by 7 giving weeks\n remainder days\n move 1 to str-pos\n call \"fmt\" using weeks weeks-str\n call \"fmt\" using days days-str\n call \"fmt\" using hours hours-str\n call \"fmt\" using minutes minutes-str\n call \"fmt\" using seconds seconds-str\n display formatted-duration\n stop run\n .\n\n identification division.\n program-id. fmt.\n data division.\n working-storage section.\n 77 nothing pic x.\n linkage section.\n 1 formatted-value pic x(4).\n 1 duration-size pic x(4).\n procedure division using formatted-value duration-size.\n begin.\n if function numval (formatted-value) not = 0\n perform insert-comma-space\n unstring formatted-value delimited all space\n into nothing formatted-duration (str-pos:)\n count chars-transferred\n add chars-transferred to str-pos\n string space delimited size\n duration-size delimited space\n into formatted-duration pointer str-pos\n end-if\n exit program\n .\n\n insert-comma-space.\n if str-pos > 1\n move \", \" to formatted-duration (str-pos:)\n add 2 to str-pos\n end-if\n .\n end program fmt.\n end program fmt-dura.\n", "language": "COBOL" }, { "code": "10 REM CONVERT SECONDS TO COMPOUND DURATION\n20 REM ADAPTED FROM RUN BASIC VERSION\n30 REM ===============================================================\n40 PRINT CHR$(14)\n50 SEC = 7259\n60 GOSUB 1000\n70 SEC = 85400\n80 GOSUB 1000\n90 SEC = 6000000\n100 GOSUB 1000\n110 END\n120 REM ==============================================================\n1000 WK = INT(SEC/60/60/24/7)\n1010 DY = INT(SEC/60/60/24) - 7*WK\n1020 HR = INT(SEC/60/60) - 24*(DY+7*WK)\n1030 MN = INT(SEC/60) - 60*(HR+24*(DY+7*WK))\n1040 SC = SEC - 60*(MN+60*(HR+24*(DY+7*WK)))\n1050 PRINT SEC;\"SEC\" : PRINT \" =\";\n1055 F = 0\n1060 IF WK = 0 THEN 1080\n1070 PRINT WK;\"WK\"; : F = 1\n1080 IF DY = 0 THEN 1110\n1090 IF F THEN PRINT \",\";\n1100 PRINT DY;\"DY\"; : F = 1\n1110 IF HR = 0 THEN 1140\n1120 IF F THEN PRINT \",\";\n1130 PRINT HR;\"HR\"; : F = 1\n1140 IF MN = 0 THEN 1170\n1150 IF F THEN PRINT \",\";\n1160 PRINT MN;\"MIN\"; : F = 1\n1170 IF (SC > 0) AND F THEN PRINT \",\";SC;\"SEC\" : GOTO 1200\n1180 IF (SC = 0) AND F THEN 1200\n1190 PRINT SC;\"SEC\"\n1200 PRINT\n1210 RETURN\n", "language": "Commodore-BASIC" }, { "code": "(defconstant +seconds-in-minute* 60)\n(defconstant +seconds-in-hour* (* 60 +seconds-in-minute*))\n(defconstant +seconds-in-day* (* 24 +seconds-in-hour*))\n(defconstant +seconds-in-week* (* 7 +seconds-in-day*))\n\n(defun seconds->duration (seconds)\n (multiple-value-bind (weeks wk-remainder) (floor seconds +seconds-in-week*)\n (multiple-value-bind (days d-remainder) (floor wk-remainder +seconds-in-day*)\n (multiple-value-bind (hours hr-remainder) (floor d-remainder +seconds-in-hour*)\n (multiple-value-bind (minutes secs) (floor hr-remainder +seconds-in-minute*)\n (let ((chunks nil))\n (unless (zerop secs) (push (format nil \"~D sec\" secs) chunks))\n (unless (zerop minutes) (push (format nil \"~D min\" minutes) chunks))\n (unless (zerop hours) (push (format nil \"~D hr\" hours) chunks))\n (unless (zerop days) (push (format nil \"~D d\" days) chunks))\n (unless (zerop weeks) (push (format nil \"~D wk\" weeks) chunks))\n (format t \"~{~A~^, ~}~%\" chunks)))))))\n\n(seconds->duration 7259)\n(seconds->duration 86400)\n(seconds->duration 6000000)\n", "language": "Common-Lisp" }, { "code": "import std.stdio, std.conv, std.algorithm;\n\nimmutable uint SECSPERWEEK = 604_800;\nimmutable uint SECSPERDAY = 86_400;\nimmutable uint SECSPERHOUR = 3_600;\nimmutable uint SECSPERMIN = 60;\n\nstring ConvertSeconds(in uint seconds)\n{\n uint rem = seconds;\n\n uint weeks = rem / SECSPERWEEK;\n rem %= SECSPERWEEK;\n uint days = rem / SECSPERDAY;\n rem %= SECSPERDAY;\n uint hours = rem / SECSPERHOUR;\n rem %= SECSPERHOUR;\n uint mins = rem / SECSPERMIN;\n rem %= SECSPERMIN;\n\n string formatted = \"\";\n\n (weeks != 0) ? formatted ~= (weeks.to!string ~ \" wk, \") : formatted;\n (days != 0) ? formatted ~= (days.to!string ~ \" d, \") : formatted;\n (hours != 0) ? formatted ~= (hours.to!string ~ \" hr, \") : formatted;\n (mins != 0) ? formatted ~= (mins.to!string ~ \" min, \") : formatted;\n (rem != 0) ? formatted ~= (rem.to!string ~ \" sec\") : formatted;\n\n if (formatted.endsWith(\", \")) return formatted[0..$-2];\n\n return formatted;\n}\n\nvoid main()\n{\n 7_259.ConvertSeconds.writeln;\n 86_400.ConvertSeconds.writeln;\n 6_000_000.ConvertSeconds.writeln;\n}\n", "language": "D" }, { "code": "const TestData: array [0..2] of integer = (7259,86400,6000000);\n\nfunction SecondsToFormatDate(Sec: integer): string;\nvar DT: TDateTime;\nvar Weeks: integer;\nvar AYear, AMonth, ADay, AHour, AMinute, ASecond, AMilliSecond: Word;\nconst SecPerDay = 60 * 60 * 24;\nbegin\n{Convert seconds to Delphi TDateTime}\n{which is floating point days}\nDT:=Sec / SecPerDay;\n{Get weeks and subtract them off}\nWeeks:=Trunc(DT/7);\nDT:=DT - Weeks * 7;\n{Decode date}\nDecodeDateTime(DT,AYear, AMonth, ADay, AHour, AMinute, ASecond, AMilliSecond);\n{Compensate because TDateTime starts on Dec 30th 1899}\nif aDay<30 then aDay:=aDay + 1 else aDay:=aDay - 30;\nResult:='';\nif Weeks<>0 then Result:=Result+IntToStr(Weeks)+' wk, ';\nif ADay<>0 then Result:=Result+IntToStr(ADay)+' d, ';\nif AHour<>0 then Result:=Result+IntToStr(AHour)+' hr, ';\nif AMinute<>0 then Result:=Result+IntToStr(AMinute)+' min, ';\nif ASecond<>0 then Result:=Result+IntToStr(ASecond)+' sec, ';\nend;\n\nprocedure ShowFormatedDataTime(Memo: TMemo);\nvar I: integer;\nbegin\nfor I:=0 to High(TestData) do\nMemo.Lines.Add(IntToStr(TestData[I])+' = '+SecondsToFormatDate(TestData[I]));\nend;\n", "language": "Delphi" }, { "code": "func$ split sec .\n divs[] = [ 60 60 24 7 ]\n n$[] = [ \"sec\" \"min\" \"hr\" \"d\" \"wk\" ]\n len r[] 5\n for i = 1 to 4\n r[i] = sec mod divs[i]\n sec = sec div divs[i]\n .\n r[5] = sec\n for i = 5 downto 1\n if r[i] <> 0\n if s$ <> \"\"\n s$ &= \", \"\n .\n s$ &= r[i] & \" \" & n$[i]\n .\n .\n return s$\n.\nprint split 7259\nprint split 86400\nprint split 6000000\n", "language": "EasyLang" }, { "code": "defmodule Convert do\n @minute 60\n @hour @minute*60\n @day @hour*24\n @week @day*7\n @divisor [@week, @day, @hour, @minute, 1]\n\n def sec_to_str(sec) do\n {_, [s, m, h, d, w]} =\n Enum.reduce(@divisor, {sec,[]}, fn divisor,{n,acc} ->\n {rem(n,divisor), [div(n,divisor) | acc]}\n end)\n [\"#{w} wk\", \"#{d} d\", \"#{h} hr\", \"#{m} min\", \"#{s} sec\"]\n |> Enum.reject(fn str -> String.starts_with?(str, \"0\") end)\n |> Enum.join(\", \")\n end\nend\n\nEnum.each([7259, 86400, 6000000], fn sec ->\n :io.fwrite \"~10w sec : ~s~n\", [sec, Convert.sec_to_str(sec)]\nend)\n", "language": "Elixir" }, { "code": "-module(convert_seconds).\n\n-export([test/0]).\n\ntest() ->\n\tlists:map(fun convert/1, [7259, 86400, 6000000]),\n\tok.\n\nconvert(Seconds) ->\n\tio:format(\n\t\t\"~7s seconds = ~s\\n\",\n\t\t[integer_to_list(Seconds), compoundDuration(Seconds)] ).\n\n% Compound duration of t seconds. The argument is assumed to be positive.\ncompoundDuration(Seconds) ->\n\tintercalate(\n\t\t\", \",\n\t\tlists:map(\n\t\t\tfun({D,L}) -> io_lib:format(\"~p ~s\",[D, L]) end,\n\t\t\tcompdurs(Seconds) ) ).\n\n% Time broken down into non-zero durations and their labels.\ncompdurs(T) ->\n\tDs =\n\t\treduceBy(\n\t\t\tT,\n\t\t\tlists:map(\n\t\t\t\tfun(Dl) -> element(1,Dl) end,\n\t\t\t\ttl(durLabs()) ) ),\n\tlists:filter(\n\t\t\tfun(Dl) -> element(1,Dl) /= 0 end,\n\t\t\tlists:zip(\n\t\t\t\tDs,\n\t\t\t\tlists:map(\n\t\t\t\t\tfun(Dl) -> element(2,Dl) end,\n\t\t\t\t\tdurLabs() ) ) ).\n\n% Duration/label pairs.\ndurLabs() ->\n\t[\n\t\t{undefined, \"wk\"},\n\t\t{7, \"d\"},\n\t\t{24, \"hr\"},\n\t\t{60, \"min\"},\n\t\t{60, \"sec\"}\n\t].\n\nreduceBy(N, Xs) ->\n\t{N_, Ys} = mapaccumr(fun quotRem/2, N, Xs),\n\t[N_ | Ys].\n\nquotRem(X1, X2) ->\n\t{X1 div X2, X1 rem X2}.\n\n% **************************************************\n% Adapted from http://lpaste.net/edit/47875\n% **************************************************\n\nmapaccuml(_,I,[]) ->\n\t{I, []};\nmapaccuml(F,I,[H|T]) ->\n\t{Accum, NH} = F(I,H),\n\t{FAccum, NT} = mapaccuml(F,Accum,T),\n\t{FAccum, [NH | NT]}.\n\nmapaccumr(_,I,[]) ->\n\t{I, []};\nmapaccumr(F,I,L) ->\n\t{Acc, Ys} = mapaccuml(F,I,lists:reverse(L)),\n\t{Acc, lists:reverse(Ys)}.\n\n% **************************************************\n\n\n% **************************************************\n% Copied from https://github.com/tim/erlang-oauth/blob/master/src/oauth.erl\n% **************************************************\n\nintercalate(Sep, Xs) ->\n lists:concat(intersperse(Sep, Xs)).\n\nintersperse(_, []) ->\n [];\nintersperse(_, [X]) ->\n [X];\nintersperse(Sep, [X | Xs]) ->\n [X, Sep | intersperse(Sep, Xs)].\n\n% **************************************************\n", "language": "Erlang" }, { "code": "open System\n\nlet convert seconds =\n let span = TimeSpan.FromSeconds(seconds |> float)\n let (wk, day) = Math.DivRem(span.Days, 7)\n let parts =\n [(wk, \"wk\"); (day, \"day\"); (span.Hours, \"hr\"); (span.Minutes, \"min\"); (span.Seconds, \"sec\")]\n let result =\n List.foldBack (fun (n, u) acc ->\n (if n > 0 then n.ToString() + \" \" + u else \"\")\n + (if n > 0 && acc.Length > 0 then \", \" else \"\")\n + acc\n ) parts \"\"\n if result.Length > 0 then result else \"0 sec\"\n\n[<EntryPoint>]\nlet main argv =\n argv\n |> Seq.map (fun str -> let sec = UInt32.Parse str in (sec, convert sec))\n |> Seq.iter (fun (s, v) -> printfn \"%10i = %s\" s v)\n 0\n", "language": "F-Sharp" }, { "code": "USING: assocs io kernel math math.parser qw sequences\nsequences.generalizations ;\n\n: mod/ ( x y -- w z ) /mod swap ;\n\n: convert ( n -- seq )\n 60 mod/ 60 mod/ 24 mod/ 7 mod/ 5 narray reverse ;\n\n: .time ( n -- )\n convert [ number>string ] map qw{ wk d hr min sec } zip\n [ first \"0\" = ] reject [ \" \" join ] map \", \" join print ;\n\n7259 86400 6000000 [ .time ] tri@\n", "language": "Factor" }, { "code": "CREATE C 0 ,\n: ., C @ IF .\" , \" THEN 1 C ! ;\n: .TIME ( n --)\n [ 60 60 24 7 * * * ]L /MOD ?DUP-IF ., . .\" wk\" THEN\n [ 60 60 24 * * ]L /MOD ?DUP-IF ., . .\" d\" THEN\n [ 60 60 * ]L /MOD ?DUP-IF ., . .\" hr\" THEN\n [ 60 ]L /MOD ?DUP-IF ., . .\" min\" THEN\n ?DUP-IF ., . .\" sec\" THEN 0 C ! ;\n", "language": "Forth" }, { "code": " SUBROUTINE PROUST(T)\t!Remembrance of time passed.\n INTEGER T\t\t!The time, in seconds. Positive only, please.\n INTEGER NTYPES\t\t!How many types of time?\n PARAMETER (NTYPES = 5)\t!This should do.\n INTEGER USIZE(NTYPES)\t!Size of the time unit.\n CHARACTER*3 UNAME(NTYPES)!Name of the time unit.\n PARAMETER (USIZE = (/7*24*60*60, 24*60*60, 60*60, 60, 1/))\t!The compiler does some arithmetic.\n PARAMETER (UNAME = (/ \"wk\", \"d\", \"hr\",\"min\",\"sec\"/))\t!Approved names, with trailing spaces.\n CHARACTER*28 TEXT\t!A scratchpad.\n INTEGER I,L,N,S\t\t!Assistants.\n S = T\t\t\t!A copy I can mess with.\n L = 0\t\t\t!No text has been generated.\n DO I = 1,NTYPES\t\t!Step through the types to do so.\n N = S/USIZE(I)\t!Largest first.\n IF (N.GT.0) THEN\t!Above the waterline?\n S = S - N*USIZE(I)\t\t!Yes! Remove its contribution.\n IF (L.GT.0) THEN\t\t!Is this the first text to be rolled?\n L = L + 2\t\t\t\t!No.\n TEXT(L - 1:L) = \", \"\t\t!Cough forth some punctuation.\n END IF\t\t\t!Now ready for this count.\n WRITE (TEXT(L + 1:),1) N,UNAME(I)\t!Place, with the unit name.\n 1 FORMAT (I0,1X,A)\t\t!I0 means I only: variable-length, no leading spaces.\n L = LEN_TRIM(TEXT)\t\t!Find the last non-blank resulting.\n END IF\t\t\t!Since I'm not keeping track.\n END DO\t\t\t!On to the next unit.\nCast forth the result.\n WRITE (6,*) T,\">\",TEXT(1:L),\"<\"\t!With annotation.\n END\t\t\t!Simple enough with integers.\n\n PROGRAM MARCEL\t\t!Stir the cup.\n CALL PROUST(7259)\n CALL PROUST(7260)\n CALL PROUST(86400)\n CALL PROUST(6000000)\n CALL PROUST(0)\n CALL PROUST(-666)\n END\n", "language": "Fortran" }, { "code": "'FreeBASIC version 1.05 32/64 bit\n\nSub Show(m As Long)\n Dim As Long c(1 To 5)={604800,86400,3600,60,1}\n Dim As String g(1 To 5)={\" Wk\",\" d\",\" hr\",\" min\",\" sec\"},comma\n Dim As Long b(1 To 5),flag,m2=m\n Redim As Long s(0)\n For n As Long=1 To 5\n If m>=c(n) Then\n Do\n Redim Preserve s(Ubound(s)+1)\n s(Ubound(s))=c(n)\n m=m-c(n)\n Loop Until m<c(n)\n End If\n Next n\n For n As Long=1 To Ubound(s)\n For m As Long=1 To 5\n If s(n)=c(m) Then b(m)+=1\n Next m\n Next n\n Print m2;\" seconds = \";\n For n As Long=1 To 5\n If b(n) Then: comma=Iif(n<5 Andalso b(n+1),\",\",\" and\"):flag+=1\n If flag=1 Then comma=\"\"\n Print comma;b(n);g(n);\n End If\nNext\nPrint\nEnd Sub\n\n#define seconds\n\nShow 7259 seconds\nShow 86400 seconds\nShow 6000000 seconds\nsleep\n", "language": "FreeBASIC" }, { "code": "wk := week\nn = eval[input[\"Enter duration in seconds: \"]]\nres = n s -> [0, \"wk\", \"d\", \"hr\", \"min\", \"sec\", 0]\nres =~ %s/, 0[^,]+//g\nprintln[res]\n", "language": "Frink" }, { "code": "include \"NSLog.incl\"\n\nlocal fn CompoundDurationString( seconds as long ) as CFStringRef\n long s = 1, m = s * 60, h = m * 60, d = h * 24, w = d * 7\n long v(4) : v(0) = w : v(1) = d : v(2) = h : v(3) = m : v(4) = s\n long i, value\n CFArrayRef abbr = @[@\"wk\",@\"d\",@\"hr\",@\"min\",@\"sec\"]\n CFMutableStringRef string = fn MutableStringWithCapacity(0)\n\n for i = 0 to 4\n value = seconds / v(i)\n seconds = seconds mod v(i)\n if ( value )\n if ( len(string) ) then MutableStringAppendString( string, @\", \" )\n MutableStringAppendFormat( string, @\"%ld %@\", value, abbr[i] )\n end if\n next\nend fn = string\n\nNSLog(@\"%@\",fn CompoundDurationString(7259))\nNSLog(@\"%@\",fn CompoundDurationString(86400))\nNSLog(@\"%@\",fn CompoundDurationString(6000000))\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\nDim iInput As Integer[] = [7259, 86400, 6000000] 'Input details\nDim iChecks As Integer[] = [604800, 86400, 3600, 60] 'Weeks, days, hours, mins in seconds\nDim iTime As New Integer[5] 'To store wk, d, hr, min & sec\nDim iOriginal, iSec, iLoop As Integer 'Various integers\nDim sOrd As String[] = [\" wk\", \" d\", \" hr\", \" min\", \" sec\"] 'To add to the output string\nDim sOutput As String 'Output string\n\nFor Each iSec In iInput 'For each iInput\n iOriginal = iSec 'Store orginal value in seconds\n iTime[4] = iSec 'Store seconds in iTime[4]\n\n For iLoop = 0 To 3 'Loop through wk, d, hr, min & sec\n If iTime[4] >= iChecks[iLoop] Then 'Check if value is = to wk, d, hr, min\n iTime[iLoop] = Int(iTime[4] / iChecks[iLoop]) 'Put the correct value for wk, d, hr, min in iTime\n iTime[4] = iTime[4] - (iTime[iLoop] * iChecks[iLoop]) 'Remove the amount of seconds for wk, d, hr, min from iTime[4]\n Endif\n Next\n\n For iLoop = 0 To 4 'Loop through wk, d, hr, min & secs\n If iTime[iLoop] > 0 Then sOutput &= \", \" & Str(iTime[iLoop]) & sOrd[iLoop] 'Add comma and ordinal as needed\n Next\n\n If Left(sOutput, 2) = \", \" Then sOutput = Mid(sOutput, 3) 'Remove unnecessary \", \"\n sOutput = Format(Str(iOriginal), \"#######\") & \" Seconds = \" & sOutput 'Add original seconds to the output string\n Print sOutput 'Print sOutput string\n sOutput = \"\" 'Clear the sOutput string\n iTime = New Integer[5] 'Reset iTime[]\nNext\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc main(){\n\tfmt.Println(TimeStr(7259))\n\tfmt.Println(TimeStr(86400))\n\tfmt.Println(TimeStr(6000000))\n}\n\nfunc TimeStr(sec int)(res string){\n\twks, sec := sec / 604800,sec % 604800\n\tds, sec := sec / 86400, sec % 86400\n\thrs, sec := sec / 3600, sec % 3600\n\tmins, sec := sec / 60, sec % 60\n\tCommaRequired := false\n\tif wks != 0 {\n\t\tres += fmt.Sprintf(\"%d wk\",wks)\n\t\tCommaRequired = true\n\t}\n\tif ds != 0 {\n\t\tif CommaRequired {\n\t\t\tres += \", \"\n\t\t}\n\t\tres += fmt.Sprintf(\"%d d\",ds)\n\t\tCommaRequired = true\n\t}\n\tif hrs != 0 {\n\t\tif CommaRequired {\n\t\t\tres += \", \"\n\t\t}\n\t\tres += fmt.Sprintf(\"%d hr\",hrs)\n\t\tCommaRequired = true\n\t}\n\tif mins != 0 {\n\t\tif CommaRequired {\n\t\t\tres += \", \"\n\t\t}\n\t\tres += fmt.Sprintf(\"%d min\",mins)\n\t\tCommaRequired = true\n\t}\n\tif sec != 0 {\n\t\tif CommaRequired {\n\t\t\tres += \", \"\n\t\t}\n\t\tres += fmt.Sprintf(\"%d sec\",sec)\n\t}\n\treturn\n}\n", "language": "Go" }, { "code": "import Control.Monad (forM_)\nimport Data.List (intercalate, mapAccumR)\nimport System.Environment (getArgs)\nimport Text.Printf (printf)\nimport Text.Read (readMaybe)\n\nreduceBy :: Integral a => a -> [a] -> [a]\nn `reduceBy` xs = n' : ys where (n', ys) = mapAccumR quotRem n xs\n\n-- Duration/label pairs.\ndurLabs :: [(Integer, String)]\ndurLabs = [(undefined, \"wk\"), (7, \"d\"), (24, \"hr\"), (60, \"min\"), (60, \"sec\")]\n\n-- Time broken down into non-zero durations and their labels.\ncompdurs :: Integer -> [(Integer, String)]\ncompdurs t = let ds = t `reduceBy` (map fst $ tail durLabs)\n in filter ((/=0) . fst) $ zip ds (map snd durLabs)\n\n-- Compound duration of t seconds. The argument is assumed to be positive.\ncompoundDuration :: Integer -> String\ncompoundDuration = intercalate \", \" . map (uncurry $ printf \"%d %s\") . compdurs\n\nmain :: IO ()\nmain = do\n args <- getArgs\n forM_ args $ \\arg -> case readMaybe arg of\n Just n -> printf \"%7d seconds = %s\\n\" n (compoundDuration n)\n Nothing -> putStrLn $ \"Invalid number of seconds: \" ++ arg\n", "language": "Haskell" }, { "code": "import Data.List (intercalate, mapAccumR)\n\n---------------- COMPOUND DURATION STRINGS ---------------\n\ndurationString ::\n String ->\n String ->\n Int ->\n Int ->\n [String] ->\n Int ->\n String\ndurationString\n componentGap\n numberLabelGap\n daysPerWeek\n hoursPerDay\n xs\n n =\n intercalate\n componentGap\n ( foldr\n (timeTags numberLabelGap)\n []\n (zip (weekParts daysPerWeek hoursPerDay n) xs)\n )\n\ntimeTags :: String -> (Int, String) -> [String] -> [String]\ntimeTags numberLabelGap (n, s) xs\n | 0 < n = intercalate numberLabelGap [show n, s] : xs\n | otherwise = xs\n\nweekParts :: Int -> Int -> Int -> [Int]\nweekParts daysPerWeek hoursPerDay =\n snd\n . flip\n (mapAccumR byUnits)\n [0, daysPerWeek, hoursPerDay, 60, 60]\n\nbyUnits :: Int -> Int -> (Int, Int)\nbyUnits rest x = (quot (rest - m) u, m)\n where\n (u, m)\n | 0 < x = (x, rem rest x)\n | otherwise = (1, rest)\n\n--------------------------- TEST -------------------------\n\ntranslation :: String -> Int -> Int -> Int -> String\ntranslation local daysPerWeek hoursPerDay n =\n intercalate \" -> \" $\n [ show,\n durationString\n \", \"\n \" \"\n daysPerWeek\n hoursPerDay\n (words local)\n ]\n <*> [n]\n\nmain :: IO ()\nmain = do\n let names = \"wk d hr min sec\"\n let tests = [7259, 86400, 6000000]\n\n putStrLn \"Assuming 24 hrs per day:\"\n mapM_ (putStrLn . translation names 7 24) tests\n\n putStrLn \"\\nor, at 8 hours per day, 5 days per week:\"\n mapM_ (putStrLn . translation names 5 8) tests\n", "language": "Haskell" }, { "code": "100 PROGRAM \"Seconds.bas\"\n110 NUMERIC UN(1 TO 5),SEC,UNIT\n120 STRING T$(1 TO 5)*3\n130 LET UN(1)=604800:LET UN(2)=86400:LET UN(3)=3600:LET UN(4)=60:LET UN(5)=1\n140 LET T$(1)=\"wk\":LET T$(2)=\"d\":LET T$(3)=\"hr\":LET T$(4)=\"min\":LET T$(5)=\"sec\"\n150 INPUT PROMPT \"Duration in seconds: \":SEC\n160 PRINT SEC;\"sec =\";\n170 FOR I=1 TO 5\n180 IF SEC>=UN(I) THEN\n190 LET UNIT=INT(SEC/UN(I)):LET SEC=MOD(SEC,UN(I))\n200 PRINT UNIT;T$(I);\n210 IF I<4 AND SEC>0 THEN PRINT \",\";\n220 END IF\n230 NEXT\n240 PRINT\n", "language": "IS-BASIC" }, { "code": "fmtsecs=: verb define\n seq=. 0 7 24 60 60 #: y\n }: ;:inv ,(0 ~: seq) # (8!:0 seq) ,. <;.2'wk,d,hr,min,sec,'\n)\n", "language": "J" }, { "code": " fmtsecs 7259\n2 hr, 59 sec\n fmtsecs 86400\n1 d\n fmtsecs 6000000\n9 wk, 6 d, 10 hr, 40 min\n", "language": "J" }, { "code": "fn main() {\n for seconds in [\n 7259\n 86400\n 6000000\n ] {\n println(\"{}\", time_string(seconds))\n }\n}\n\nfn time_string(mut seconds: i64) throws -> String {\n mut result = \"\"\n\n mut minutes = seconds / 60\n seconds %= 60\n if seconds > 0 {\n result = format(\"{} sec\", seconds, result)\n }\n\n mut hours = minutes / 60\n minutes %= 60\n if minutes > 0 {\n result = format(match result {\n \"\" => \"{} min\"\n else => \"{} min, {}\"\n }, minutes, result)\n }\n\n mut days = hours / 24\n hours %= 24\n if hours > 0 {\n result = format(match result {\n \"\" => \"{} hr\"\n else => \"{} hr, {}\"\n }, hours, result)\n }\n\n mut weeks = days / 7\n days %= 7\n if days > 0 {\n result = format(match result {\n \"\" => \"{} d\"\n else => \"{} d, {}\"\n }, days, result)\n }\n if weeks > 0 {\n result = format(match result {\n \"\" => \"{} wk\"\n else => \"{} wk, {}\"\n }, weeks, result)\n }\n\n return result\n}\n", "language": "Jakt" }, { "code": "String duration(int seconds) {\n StringBuilder string = new StringBuilder();\n if (seconds >= 604_800 /* 1 wk */) {\n string.append(\"%,d wk\".formatted(seconds / 604_800));\n seconds %= 604_800;\n }\n if (seconds >= 86_400 /* 1 d */) {\n if (!string.isEmpty()) string.append(\", \");\n string.append(\"%d d\".formatted(seconds / 86_400));\n seconds %= 86_400;\n }\n if (seconds >= 3600 /* 1 hr */) {\n if (!string.isEmpty()) string.append(\", \");\n string.append(\"%d hr\".formatted(seconds / 3600));\n seconds %= 3600;\n }\n if (seconds >= 60 /* 1 min */) {\n if (!string.isEmpty()) string.append(\", \");\n string.append(\"%d min\".formatted(seconds / 60));\n seconds %= 60;\n }\n if (seconds > 0) {\n if (!string.isEmpty()) string.append(\", \");\n string.append(\"%d sec\".formatted(seconds));\n }\n return string.toString();\n}\n", "language": "Java" }, { "code": "public class CompoundDuration {\n\n public static void main(String[] args) {\n compound(7259);\n compound(86400);\n compound(6000_000);\n }\n\n private static void compound(long seconds) {\n StringBuilder sb = new StringBuilder();\n\n seconds = addUnit(sb, seconds, 604800, \" wk, \");\n seconds = addUnit(sb, seconds, 86400, \" d, \");\n seconds = addUnit(sb, seconds, 3600, \" hr, \");\n seconds = addUnit(sb, seconds, 60, \" min, \");\n addUnit(sb, seconds, 1, \" sec, \");\n\n sb.setLength(sb.length() > 2 ? sb.length() - 2 : 0);\n\n System.out.println(sb);\n }\n\n private static long addUnit(StringBuilder sb, long sec, long unit, String s) {\n long n;\n if ((n = sec / unit) > 0) {\n sb.append(n).append(s);\n sec %= (n * unit);\n }\n return sec;\n }\n}\n", "language": "Java" }, { "code": "(function () {\n 'use strict';\n\n // angloDuration :: Int -> String\n function angloDuration(intSeconds) {\n return zip(\n weekParts(intSeconds),\n ['wk', 'd', 'hr', 'min','sec']\n )\n .reduce(function (a, x) {\n return a.concat(x[0] ? (\n [(x[0].toString() + ' ' + x[1])]\n ) : []);\n }, [])\n .join(', ');\n }\n\n\n\n // weekParts :: Int -> [Int]\n function weekParts(intSeconds) {\n\n return [undefined, 7, 24, 60, 60]\n .reduceRight(function (a, x) {\n var intRest = a.remaining,\n intMod = isNaN(x) ? intRest : intRest % x;\n\n return {\n remaining:(intRest - intMod) / (x || 1),\n parts: [intMod].concat(a.parts)\n };\n }, {\n remaining: intSeconds,\n parts: []\n })\n .parts\n }\n\n // GENERIC ZIP\n\n // zip :: [a] -> [b] -> [(a,b)]\n function zip(xs, ys) {\n return xs.length === ys.length ? (\n xs.map(function (x, i) {\n return [x, ys[i]];\n })\n ) : undefined;\n }\n\n // TEST\n\n return [7259, 86400, 6000000]\n .map(function (intSeconds) {\n return intSeconds.toString() +\n ' -> ' + angloDuration(intSeconds);\n })\n .join('\\n');\n\n})();\n", "language": "JavaScript" }, { "code": "(() => {\n \"use strict\";\n\n // ---------------- COMPOUND DURATION ----------------\n\n // compoundDuration :: [String] -> Int -> String\n const compoundDuration = labels =>\n nSeconds => weekParts(nSeconds)\n .map((v, i) => [v, labels[i]])\n .reduce((a, x) =>\n a.concat(\n x[0] ? [\n `${x[0]} ${x[1] || \"?\"}`\n ] : []\n ), []\n )\n .join(\", \");\n\n\n // weekParts :: Int -> [Int]\n const weekParts = nSeconds => [0, 7, 24, 60, 60]\n .reduceRight((a, x) => {\n const\n r = a[0],\n mod = x !== 0 ? r % x : r;\n\n return [\n (r - mod) / (x || 1),\n [mod, ...a[1]]\n ];\n }, [nSeconds, []])[1];\n\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () => {\n const localNames = [\"wk\", \"d\", \"hr\", \"min\", \"sec\"];\n\n return [7259, 86400, 6E6]\n .map(nSeconds =>\n `${nSeconds} -> ${\n compoundDuration(localNames)(nSeconds)\n }`).join(\"\\n\");\n };\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "def seconds_to_time_string:\n def nonzero(text): floor | if . > 0 then \"\\(.) \\(text)\" else empty end;\n if . == 0 then \"0 sec\"\n else\n [(./60/60/24/7 | nonzero(\"wk\")),\n (./60/60/24 % 7 | nonzero(\"d\")),\n (./60/60 % 24 | nonzero(\"hr\")),\n (./60 % 60 | nonzero(\"min\")),\n (. % 60 | nonzero(\"sec\"))]\n | join(\", \")\n end;\n", "language": "Jq" }, { "code": "0, 7259, 86400, 6000000 | \"\\(.): \\(seconds_to_time_string)\"\n", "language": "Jq" }, { "code": "$ jq -r -n -f Convert_seconds_to_compound_duration.jq\n0: 0 sec\n7259: 2 hr, 59 sec\n86400: 1 d\n6000000: 9 wk, 6 d, 10 hr, 40 min\n", "language": "Jq" }, { "code": "# 1.x\nfunction duration(sec::Integer)::String\n t = Array{Int}([])\n for dm in (60, 60, 24, 7)\n sec, m = divrem(sec, dm)\n pushfirst!(t, m)\n end\n pushfirst!(t, sec)\n return join([\"$num$unit\" for (num, unit) in zip(t, [\"w\", \"d\", \"h\", \"m\", \"s\"]) if num > 0], \", \")\nend\n\n@show duration(7259)\n@show duration(86400)\n@show duration(6000000)\n", "language": "Julia" }, { "code": "F:{\", \"/\" \"/'+($x[s]),s:,&0<x}(\" \"\\\"wk d hr min sec\")!0 7 24 60 60\\\n", "language": "K" }, { "code": "F 100\n\"1 min, 40 sec\"\nF 7259\n\"2 hr, 59 sec\"\nF 86400\n\"1 d\"\nF 6000000\n\"9 wk, 6 d, 10 hr, 40 min\"\n", "language": "K" }, { "code": "fun compoundDuration(n: Int): String {\n if (n < 0) return \"\" // task doesn't ask for negative integers to be converted\n if (n == 0) return \"0 sec\"\n val weeks : Int\n val days : Int\n val hours : Int\n val minutes: Int\n val seconds: Int\n var divisor: Int = 7 * 24 * 60 * 60\n var rem : Int\n var result = \"\"\n\n weeks = n / divisor\n rem = n % divisor\n divisor /= 7\n days = rem / divisor\n rem %= divisor\n divisor /= 24\n hours = rem / divisor\n rem %= divisor\n divisor /= 60\n minutes = rem / divisor\n seconds = rem % divisor\n\n if (weeks > 0) result += \"$weeks wk, \"\n if (days > 0) result += \"$days d, \"\n if (hours > 0) result += \"$hours hr, \"\n if (minutes > 0) result += \"$minutes min, \"\n if (seconds > 0)\n result += \"$seconds sec\"\n else\n result = result.substring(0, result.length - 2)\n return result\n}\n\nfun main(args: Array<String>) {\n val durations = intArrayOf(0, 7, 84, 7259, 86400, 6000000)\n durations.forEach { println(\"$it\\t-> ${compoundDuration(it)}\") }\n}\n", "language": "Kotlin" }, { "code": "val .duration = fn(var .sec) {\n [\n fw/wk d hr min sec/,\n for[=[]] .dm in [7 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60] {\n _for ~= [.sec \\ .dm]\n .sec rem= .dm\n } ~ [.sec],\n ]\n}\n\nfor .seconds in [7259, 86400, 6000000] {\n val .dur = .duration(.seconds)\n write $\"\\.seconds:7; sec = \"\n writeln join \", \", for[=[]] .k of .dur[1] {\n if .dur[2][.k] != 0: _for ~= [$\"\\.dur[2][.k]; \\.dur[1][.k];\"]\n }\n}\n", "language": "Langur" }, { "code": "[start]\ninput \"Enter SECONDS: \"; seconds\nseconds=int(abs(seconds))\nif seconds=0 then print \"Program complete.\": end\nUnitsFound=0: LastFound$=\"\"\nyears=int(seconds/31449600): seconds=seconds mod 31449600\nif years then LastFound$=\"years\"\nweeks=int(seconds/604800): seconds=seconds mod 604800\nif weeks then LastFound$=\"weeks\"\ndays=int(seconds/86400): seconds=seconds mod 86400\nif days then LastFound$=\"days\"\nhours=int(seconds/3600): seconds=seconds mod 3600\nif hours then LastFound$=\"hours\"\nminutes=int(seconds/60): seconds=seconds mod 60\nif minutes then LastFound$=\"minutes\"\nif seconds then LastFound$=\"seconds\"\nselect case years\n case 0\n case 1: print years; \" year\";\n case else: print years; \" years\";\nend select\nselect case weeks\n case 0\n case 1\n if years then\n if LastFound$=\"weeks\" then print \" and \"; else print \", \";\n end if\n print weeks; \" week\";\n case else\n if years then\n if LastFound$=\"weeks\" then print \" and \"; else print \", \";\n end if\n print weeks; \" weeks\";\nend select\nselect case days\n case 0\n case 1\n if years or weeks then\n if LastFound$=\"days\" then print \" and \"; else print \", \";\n end if\n print days; \" day\";\n case else\n if years or weeks then\n if LastFound$=\"days\" then print \" and \"; else print \", \";\n end if\n print days; \" days\";\nend select\nselect case hours\n case 0\n case 1\n if years or weeks or days then\n if LastFound$=\"hours\" then print \" and \"; else print \", \";\n end if\n print hours; \" hour\";\n case else\n if years or weeks or days then\n if LastFound$=\"hours\" then print \" and \"; else print \", \";\n end if\n print hours; \" hours\";\nend select\nselect case minutes\n case 0\n case 1\n if years or weeks or days or hours then\n if LastFound$=\"minutes\" then print \" and \"; else print \", \";\n end if\n print minutes; \" minute\";\n case else\n if years or weeks or days or hours then\n if LastFound$=\"minutes\" then print \" and \"; else print \", \";\n end if\n print minutes; \" minutes\";\nend select\nselect case seconds\n case 0\n case 1\n if years or weeks or days or hours or minutes then\n if LastFound$=\"seconds\" then print \" and \"; else print \", \";\n end if\n print seconds; \" second\";\n case else\n if years or weeks or days or hours or minutes then\n if LastFound$=\"seconds\" then print \" and \"; else print \", \";\n end if\n print seconds; \" seconds\";\nend select\nprint\ngoto [start]\n", "language": "Liberty-BASIC" }, { "code": "function duration (secs)\n local units, dur = {\"wk\", \"d\", \"hr\", \"min\"}, \"\"\n for i, v in ipairs({604800, 86400, 3600, 60}) do\n if secs >= v then\n dur = dur .. math.floor(secs / v) .. \" \" .. units[i] .. \", \"\n secs = secs % v\n end\n end\n if secs == 0 then\n return dur:sub(1, -3)\n else\n return dur .. secs .. \" sec\"\n end\nend\n\nprint(duration(7259))\nprint(duration(86400))\nprint(duration(6000000))\n", "language": "Lua" }, { "code": "tim := proc (s) local weeks, days, hours, minutes, seconds;\n weeks := trunc((1/604800)*s);\n days := trunc((1/86400)*s)-7*weeks;\n hours := trunc((1/3600)*s)-24*days-168*weeks;\n minutes := trunc((1/60)*s)-60*hours-1440*days-10080*weeks;\n seconds := s-60*minutes-3600*hours-86400*days-604800*weeks;\nprintf(\"%s\", cat(`if`(0 < weeks, cat(weeks, \"wk, \"), NULL), `if`(0 < days, cat(days, \"d, \"), NULL), `if`(0 < hours, cat(hours, \"hr, \"), NULL), `if`(0 < minutes, cat(minutes, \"min, \"), NULL), `if`(0 < seconds, cat(seconds, \"sec\"), NULL)))\nend proc;\n", "language": "Maple" }, { "code": "compoundDuration[x_Integer] :=\n StringJoin @@ (Riffle[\n ToString /@ ((({Floor[x/604800],\n Mod[x, 604800]} /. {a_, b_} -> {a, Floor[b/86400],\n Mod[b, 86400]}) /. {a__, b_} -> {a, Floor[b/3600],\n Mod[b, 3600]}) /. {a__, b_} -> {a, Floor[b/60],\n Mod[b, 60]}), {\" wk, \", \" d, \", \" hr, \", \" min, \",\n \" sec\"}] //. {a___, \"0\", b_, c___} -> {a, c})\n\nGrid[Table[{n, \"secs =\",\n compoundDuration[n]}, {n, {7259, 86400, 6000000}}],\n Alignment -> {Left, Baseline}]\n", "language": "Mathematica" }, { "code": "from strutils import addSep\n\nconst\n Units = [\" wk\", \" d\", \" hr\", \" min\", \" sec\"]\n Quantities = [7 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60, 1]\n\n#---------------------------------------------------------------------------------------------------\n\nproc `$$`*(sec: int): string =\n ## Convert a duration in seconds to a friendly string.\n\n doAssert(sec > 0)\n\n var duration = sec\n var idx = 0\n while duration != 0:\n let q = duration div Quantities[idx]\n if q != 0:\n duration = duration mod Quantities[idx]\n result.addSep(\", \", 0)\n result.add($q & Units[idx])\n inc idx\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nwhen isMainModule:\n for sec in [7259, 86400, 6000000]:\n echo sec, \"s = \", $$sec\n", "language": "Nim" }, { "code": "import times\nfrom algorithm import reversed\nfrom strutils import addSep\n\nconst Units = [\" wk\", \" d\", \" hr\", \" min\", \" sec\"]\n\n#---------------------------------------------------------------------------------------------------\n\nproc `$$`*(sec: int): string =\n ## Convert a duration in seconds to a friendly string.\n ## Similar to `$` but with other conventions.\n\n doAssert(sec > 0)\n\n var duration = initDuration(seconds = sec)\n let parts = reversed(duration.toParts[Seconds..Weeks])\n\n for idx, part in parts:\n if part != 0:\n result.addSep(\", \", 0)\n result.add($part & Units[idx])\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nwhen isMainModule:\n for sec in [7259, 86400, 6000000]:\n echo sec, \"s = \", $$sec\n", "language": "Nim" }, { "code": "let divisors = [\n (max_int, \"wk\"); (* many wk = many wk *)\n (7, \"d\"); (* 7 d = 1 wk *)\n (24, \"hr\"); (* 24 hr = 1 d *)\n (60, \"min\"); (* 60 min = 1 hr *)\n (60, \"sec\") (* 60 sec = 1 min *)\n]\n\n\n(* Convert a number of seconds into a list of values for weeks, days, hours,\n * minutes and seconds, by dividing the number of seconds 'secs' successively by\n * the values contained in the list 'divisors' (taking them in reverse order).\n * Ex:\n * compute_duration 7259\n * returns\n * [(0, \"wk\"); (0, \"d\"); (2, \"hr\") (0, \"min\"); (59, \"sec\")]\n *)\nlet compute_duration secs =\n let rec doloop remain res = function\n | [] -> res\n | (n, s) :: ds -> doloop (remain / n) ((remain mod n, s) :: res) ds\n in\n doloop secs [] (List.rev divisors)\n\n\n(* Format nicely the list of values.\n * Ex:\n * pretty_print [(0, \"wk\"); (0, \"d\"); (2, \"hr\") (0, \"min\"); (59, \"sec\")]\n * returns\n * \"2 hr, 59 sec\"\n *\n * Intermediate steps:\n * 1. Keep only the pairs where duration is not 0\n * [(2, \"hr\"); (59, \"sec\")]\n * 2. Format each pair as a string\n * [\"2 hr\"; \"59 sec\"]\n * 3. Concatenate the strings separating them by a comma+space\n * \"2 hr, 59 sec\"\n *)\nlet pretty_print dur =\n List.filter (fun (d, _) -> d <> 0) dur\n |> List.map (fun (d, l) -> Printf.sprintf \"%d %s\" d l)\n |> String.concat \", \"\n\n\n(* Transform a number of seconds into the corresponding compound duration\n * string.\n * Not sure what to do with 0... *)\nlet compound = function\n | n when n > 0 -> compute_duration n |> pretty_print\n | n when n = 0 -> string_of_int 0 ^ \"...\"\n | _ -> invalid_arg \"Number of seconds must be positive\"\n\n\n(* Some testing... *)\nlet () =\n let test_cases = [\n (7259, \"2 hr, 59 sec\");\n (86400, \"1 d\");\n (6000000, \"9 wk, 6 d, 10 hr, 40 min\");\n (0, \"0...\");\n (3599, \"59 min, 59 sec\");\n (3600, \"1 hr\");\n (3601, \"1 hr, 1 sec\")\n ] in\n let testit (n, s) =\n let calc = compound n in\n Printf.printf \"[%s] %d seconds -> %s; expected: %s\\n\"\n (if calc = s then \"PASS\" else \"FAIL\")\n n calc s\n in\n List.iter testit test_cases\n", "language": "OCaml" }, { "code": "\\\\ Convert seconds to compound duration\n\\\\ 4/11/16 aev\nsecs2compdur(secs)={\nmy(us=[604800,86400,3600,60,1],ut=[\" wk, \",\" d, \",\" hr, \",\" min, \",\" sec\"],\n cd=[0,0,0,0,0],u,cdt=\"\");\nfor(i=1,5, u=secs\\us[i]; if(u==0, next, cd[i]=u; secs-=us[i]*cd[i]));\nfor(i=1,5, if(cd[i]==0, next, cdt=Str(cdt,cd[i],ut[i])));\nif(ssubstr(cdt,#cdt-1,1)==\",\", cdt=ssubstr(cdt,1,#cdt-2));\nreturn(cdt);\n}\n\n{\\\\ Required tests:\nprint(secs2compdur(7259));\nprint(secs2compdur(86400));\nprint(secs2compdur(6000000));\n}\n", "language": "PARI-GP" }, { "code": "program convertSecondsToCompoundDuration(output);\n\nconst\n\tsuffixUnitWeek = 'wk';\n\tsuffixUnitDay = 'd';\n\tsuffixUnitHour = 'hr'; { Use `'h'` to be SI-compatible. }\n\tsuffixUnitMinute = 'min';\n\tsuffixUnitSecond = 'sec'; { NB: Only `'s'` is SI-approved. }\n\t\n\tsuffixSeparator = ' '; { A non-breaking space would be appropriate. }\n\tquantitySeparator = ', ';\n\t\n\t{ Maximum expected length of `string` “12345 wk, 6 d, 7 hr, 8 min, 9 sec” }\n\ttimeSpanPrintedMaximumLength = 4 * length(quantitySeparator) +\n\t\t20 + length(suffixUnitWeek) + 1 + length(suffixUnitDay) +\n\t\t2 + length(suffixUnitHour) + 2 + length(suffixUnitMinute) +\n\t\t2 + length(suffixUnitSecond) + 5 * length(suffixSeparator);\n\t\n\t{ Units of time expressed in seconds. }\n\tminute = 60;\n\thour = 60 * minute;\n\tday = 24 * hour;\n\tweek = 7 * day;\n\ntype\n\twholeNumber = 0..maxInt;\n\tnaturalNumber = 1..maxInt;\n\t\n\tcanonicalTimeSpan = record\n\t\t\tweeks: wholeNumber;\n\t\t\tdays: 0..6;\n\t\t\thours: 0..23;\n\t\t\tminutes: 0..59;\n\t\t\tseconds: 0..59;\n\t\tend;\n\t\n\tstringFitForTimeSpan = string(timeSpanPrintedMaximumLength);\n\n{\n\t\\brief turns a time span expressed in seconds into a `canonicalTimeSpan`\n\t\\param duration the non-negative duration expressed in seconds\n\t\\return a `canonicalTimeSpan` representing \\param duration seconds\n}\nfunction getCanonicalTimeSpan(duration: wholeNumber): canonicalTimeSpan;\n\t{ Perform `div`ision and update `duration`. }\n\tfunction split(protected unit: naturalNumber): wholeNumber;\n\tbegin\n\t\tsplit := duration div unit;\n\t\tduration := duration mod unit\n\tend;\nvar\n\tresult: canonicalTimeSpan;\nbegin\n\twith result do\n\tbegin\n\t\tweeks := split(week);\n\t\tdays := split(day);\n\t\thours := split(hour);\n\t\tminutes := split(minute);\n\t\tseconds := duration\n\tend;\n\t{ In Pascal there needs to be _exactly_ one assignment to the }\n\t{ result variable bearing the same name as of the `function`. }\n\tgetCanonicalTimeSpan := result\nend;\n\n{\n\t\\brief turns a non-trivial duration into a string\n\t\\param n a positive duration expressed in seconds\n\t\\return \\param n expressed in some human-readable form\n}\nfunction timeSpanString(protected n: naturalNumber): stringFitForTimeSpan;\nconst\n\tqs = quantitySeparator;\nvar\n\tresult: stringFitForTimeSpan;\nbegin\n\twith getCanonicalTimeSpan(n) do\n\tbegin\n\t\t{ `:1` specifies the minimum-width. Omitting it would cause }\n\t\t{ the compiler to insert a vendor-defined default, e. g. 20. }\n\t\twriteStr(result, weeks:1, suffixSeparator, suffixUnitWeek);\n\t\t{ For strings, `:n` specifies the _exact_ width (padded with spaces). }\n\t\twriteStr(result, result:ord(weeks > 0) * length(result));\n\t\t\n\t\tif days > 0 then\n\t\tbegin\n\t\t\twriteStr(result, result, qs:ord(length(result) > 0) * length(qs),\n\t\t\t\tdays:1, suffixSeparator, suffixUnitDay);\n\t\tend;\n\t\tif hours > 0 then\n\t\tbegin\n\t\t\twriteStr(result, result, qs:ord(length(result) > 0) * length(qs),\n\t\t\t\thours:1, suffixSeparator, suffixUnitHour);\n\t\tend;\n\t\tif minutes > 0 then\n\t\tbegin\n\t\t\twriteStr(result, result, qs:ord(length(result) > 0) * length(qs),\n\t\t\t\tminutes:1, suffixSeparator, suffixUnitMinute);\n\t\tend;\n\t\tif seconds > 0 then\n\t\tbegin\n\t\t\twriteStr(result, result, qs:ord(length(result) > 0) * length(qs),\n\t\t\t\tseconds:1, suffixSeparator, suffixUnitSecond);\n\t\tend\n\tend;\n\ttimeSpanString := result\nend;\n\n{ === MAIN ============================================================= }\nbegin\n\twriteLn( 7259, ' seconds are “', timeSpanString(7259), '”');\n\twriteLn( 86400, ' seconds are “', timeSpanString(86400), '”');\n\twriteLn(6000000, ' seconds are “', timeSpanString(6000000), '”')\nend.\n", "language": "Pascal" }, { "code": "use strict;\nuse warnings;\n\nsub compound_duration {\n my $sec = shift;\n no warnings 'numeric';\n\n return join ', ', grep { $_ > 0 }\n int($sec/60/60/24/7) . \" wk\",\n int($sec/60/60/24) % 7 . \" d\",\n int($sec/60/60) % 24 . \" hr\",\n int($sec/60) % 60 . \" min\",\n int($sec) % 60 . \" sec\";\n}\n\nfor (7259, 86400, 6000000) {\n printf \"%7d sec = %s\\n\", $_, compound_duration($_)\n}\n", "language": "Perl" }, { "code": "use strict;\nuse warnings;\nuse Math::AnyNum 'polymod';\n\nsub compound_duration {\n my $seconds = shift;\n my @terms;\n\n my @durations = reverse polymod($seconds, 60, 60, 24, 7);\n my @timespans = <wk d hr min sec>;\n while (my $d = shift @durations, my $t = shift @timespans) {\n push @terms, \"$d $t\" if $d\n }\n join ', ', @terms\n}\n\nfor (<7259 86400 6000000 3380521>) {\n printf \"%7d sec = %s\\n\", $_, compound_duration($_)\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">7259</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">86400</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">6000000</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">timedate</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">6000000</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #7060A8;\">timedelta</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">days</span><span style=\"color: #0000FF;\">:=</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">hours</span><span style=\"color: #0000FF;\">:=</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">))</span>\n<!--\n", "language": "Phix" }, { "code": "(for Sec (7259 86400 6000000)\n (tab (-10 -30)\n Sec\n (glue \", \"\n (extract\n '((N Str)\n (when (gt0 (/ Sec N))\n (setq Sec (% Sec N))\n (pack @ \" \" Str) ) )\n (604800 86400 3600 60 1)\n '(\"wk\" \"d\" \"hr\" \"min\" \"sec\") ) ) ) )\n", "language": "PicoLisp" }, { "code": "/* Convert seconds to Compound Duration (weeks, days, hours, minutes, seconds). */\n\ncvt: procedure options (main);\t\t\t/* 5 August 2015 */\n declare interval float (15);\n declare (unit, i, q controlled) fixed binary;\n declare done bit (1) static initial ('0'b);\n declare name (5) character (4) varying static initial (' wk', ' d', ' hr', ' min', ' sec' );\n\n get (interval);\n put edit (interval, ' seconds = ') (f(10), a);\n if interval = 0 then do; put skip list ('0 sec'); stop; end;\n\n do unit = 60, 60, 24, 7;\n allocate q;\n q = mod(interval, unit);\n interval = interval / unit;\n end;\n allocate q; q = interval;\n do i = 1 to 5;\n if q > 0 then\n do;\n if done then put edit (', ') (a);\n put edit (trim(q), name(i)) (a, a); done = '1'b;\n end;\n if i < 5 then free q;\n end;\nend cvt;\n", "language": "PL-I" }, { "code": "function Get-Time\n{\n <#\n .SYNOPSIS\n Gets a time string in the form: # wk, # d, # hr, # min, # sec\n .DESCRIPTION\n Gets a time string in the form: # wk, # d, # hr, # min, # sec\n (Values of 0 are not displayed in the string.)\n\n Days, Hours, Minutes or Seconds in any combination may be used\n as well as Start and End dates.\n\n When used with the -AsObject switch an object containing properties\n similar to a System.TimeSpan object is returned.\n .INPUTS\n DateTime or Int32\n .OUTPUTS\n String or PSCustomObject\n .EXAMPLE\n Get-Time -Seconds 7259\n .EXAMPLE\n Get-Time -Days 31 -Hours 4 -Minutes 8 -Seconds 16\n .EXAMPLE\n Get-Time -Days 31 -Hours 4 -Minutes 8 -Seconds 16 -AsObject\n .EXAMPLE\n Get-Time -Start 3/10/2016 -End 1/20/2017\n .EXAMPLE\n Get-Time -Start (Get-Date) -End (Get-Date).AddSeconds(6000000)\n #>\n [CmdletBinding(DefaultParameterSetName='Date')]\n Param\n (\n # Start date\n [Parameter(Mandatory=$false, ParameterSetName='Date',\n Position=0)]\n [datetime]\n $Start = (Get-Date),\n\n # End date\n [Parameter(Mandatory=$false, ParameterSetName='Date',\n Position=1)]\n [datetime]\n $End = (Get-Date),\n\n # Days in the time span\n [Parameter(Mandatory=$false, ParameterSetName='Time')]\n [int]\n $Days = 0,\n\n # Hours in the time span\n [Parameter(Mandatory=$false, ParameterSetName='Time')]\n [int]\n $Hours = 0,\n\n # Minutes in the time span\n [Parameter(Mandatory=$false, ParameterSetName='Time')]\n [int]\n $Minutes = 0,\n\n # Seconds in the time span\n [Parameter(Mandatory=$false, ParameterSetName='Time')]\n [int]\n $Seconds = 0,\n\n [switch]\n $AsObject\n )\n\n Begin\n {\n [PSCustomObject]$timeObject = \"PSCustomObject\" |\n Select-Object -Property Weeks,RemainingDays,\n Days,Hours,Minutes,Seconds,Milliseconds,Ticks,\n TotalDays,TotalHours,TotalMinutes,TotalSeconds,TotalMilliseconds\n [int]$remainingDays = 0\n [int]$weeks = 0\n\n [string[]]$timeString = @()\n }\n Process\n {\n switch ($PSCmdlet.ParameterSetName)\n {\n 'Date' { $timeSpan = New-TimeSpan -Start $Start -End $End }\n 'Time' { $timeSpan = New-TimeSpan -Days $Days -Hours $Hours -Minutes $Minutes -Seconds $Seconds }\n }\n\n $weeks = [System.Math]::DivRem($timeSpan.Days, 7, [ref]$remainingDays)\n\n $timeObject.Weeks = $weeks\n $timeObject.RemainingDays = $remainingDays\n $timeObject.Days = $timeSpan.Days\n $timeObject.Hours = $timeSpan.Hours\n $timeObject.Minutes = $timeSpan.Minutes\n $timeObject.Seconds = $timeSpan.Seconds\n $timeObject.Milliseconds = $timeSpan.Milliseconds\n $timeObject.Ticks = $timeSpan.Ticks\n $timeObject.TotalDays = $timeSpan.TotalDays\n $timeObject.TotalHours = $timeSpan.TotalHours\n $timeObject.TotalMinutes = $timeSpan.TotalMinutes\n $timeObject.TotalSeconds = $timeSpan.TotalSeconds\n $timeObject.TotalMilliseconds = $timeSpan.TotalMilliseconds\n }\n End\n {\n if ($AsObject) { return $timeObject }\n\n if ($timeObject.Weeks) { $timeString += \"$($timeObject.Weeks) wk\" }\n if ($timeObject.RemainingDays) { $timeString += \"$($timeObject.RemainingDays) d\" }\n if ($timeObject.Hours) { $timeString += \"$($timeObject.Hours) hr\" }\n if ($timeObject.Minutes) { $timeString += \"$($timeObject.Minutes) min\" }\n if ($timeObject.Seconds) { $timeString += \"$($timeObject.Seconds) sec\" }\n\n return ($timeString -join \", \")\n }\n}\n", "language": "PowerShell" }, { "code": ":- use_module(library(clpfd)).\n\n% helper to perform the operation with just a number.\ncompound_time(N) :-\n times(N, R),\n format('~p: ', N),\n write_times(R).\n\n% write out the results in the 'special' format.\nwrite_times([[Tt, Val]|T]) :-\n dif(T, []),\n format('~w ~w, ', [Val, Tt]),\n write_times(T).\nwrite_times([[Tt, Val]|[]]) :-\n format('~w ~w~n', [Val, Tt]).\n\n\n% this predicate is the main predicate, it takes either N\n% or a list of split values to get N, or both.\ntimes(N, R) :-\n findall(T, time_type(T,_), TTs),\n times(TTs, N, R).\n\n% do the split, if there is a 1 or greater add to a list of results.\ntimes([], _, []).\ntimes([Tt|T], N, Rest) :-\n time_type(Tt, Div),\n Val #= N // Div,\n Val #< 1,\n times(T, N, Rest).\ntimes([Tt|T], N, [[Tt,Val]|Rest]) :-\n time_type(Tt, Div),\n Val #= N // Div,\n Val #>= 1,\n Rem #= N mod Div,\n times(T, Rem, Rest).\n\n\n% specifify the different time split types\ntime_type(wk, 60 * 60 * 24 * 7).\ntime_type(d, 60 * 60 * 24).\ntime_type(hr, 60 * 60).\ntime_type(min, 60).\ntime_type(sec, 1).\n", "language": "Prolog" }, { "code": "EnableExplicit\n\nProcedure.s ConvertSeconds(NbSeconds)\n Protected weeks, days, hours, minutes, seconds\n Protected divisor, remainder\n Protected duration$ = \"\"\n divisor = 7 * 24 * 60 * 60 ; seconds in a week\n weeks = NbSeconds / divisor\n remainder = NbSeconds % divisor\n divisor / 7 ; seconds in a day\n days = remainder / divisor\n remainder % divisor\n divisor / 24 ; seconds in an hour\n hours = remainder / divisor\n remainder % divisor\n divisor / 60 ; seconds in a minute\n minutes = remainder / divisor\n seconds = remainder % divisor\n\n If weeks > 0\n duration$ + Str(weeks) + \" wk, \"\n EndIf\n\n If days > 0\n duration$ + Str(days) + \" d, \"\n EndIf\n\n If hours > 0\n duration$ + Str(hours) + \" hr, \"\n EndIf\n\n If minutes > 0\n duration$ + Str(minutes) + \" min, \"\n EndIf\n\n If seconds > 0\n duration$ + Str(seconds) + \" sec\"\n EndIf\n\n If Right(duration$, 2) = \", \"\n duration$ = Mid(duration$, 0, Len(duration$) - 2)\n EndIf\n\n ProcedureReturn duration$\nEndProcedure\n\nIf OpenConsole()\n PrintN(ConvertSeconds(7259))\n PrintN(ConvertSeconds(86400))\n PrintN(ConvertSeconds(6000000))\n PrintN(\"\")\n PrintN(\"Press any key to close the console\")\n Repeat: Delay(10) : Until Inkey() <> \"\"\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": ">>> def duration(seconds):\n\tt= []\n\tfor dm in (60, 60, 24, 7):\n\t\tseconds, m = divmod(seconds, dm)\n\t\tt.append(m)\n\tt.append(seconds)\n\treturn ', '.join('%d %s' % (num, unit)\n\t\t\t for num, unit in zip(t[::-1], 'wk d hr min sec'.split())\n\t\t\t if num)\n\n>>> for seconds in [7259, 86400, 6000000]:\n\tprint(\"%7d sec = %s\" % (seconds, duration(seconds)))\n\n\t\n 7259 sec = 2 hr, 59 sec\n 86400 sec = 1 d\n6000000 sec = 9 wk, 6 d, 10 hr, 40 min\n>>>\n", "language": "Python" }, { "code": ">>> def duration(seconds, _maxweeks=99999999999):\n return ', '.join('%d %s' % (num, unit)\n\t\t for num, unit in zip([(seconds // d) % m\n\t\t\t\t\t for d, m in ((604800, _maxweeks),\n (86400, 7), (3600, 24),\n (60, 60), (1, 60))],\n\t\t\t\t\t ['wk', 'd', 'hr', 'min', 'sec'])\n\t\t if num)\n\n>>> for seconds in [7259, 86400, 6000000]:\n\tprint(\"%7d sec = %s\" % (seconds, duration(seconds)))\n\n\t\n 7259 sec = 2 hr, 59 sec\n 86400 sec = 1 d\n6000000 sec = 9 wk, 6 d, 10 hr, 40 min\n>>>\n", "language": "Python" }, { "code": "'''Compound duration'''\n\nfrom functools import reduce\nfrom itertools import chain\n\n\n# compoundDurationFromUnits :: [Num] -> [String] -> Num -> [(Num, String)]\ndef compoundDurationFromUnits(qs):\n '''A list of compound string representions of a number n of time units,\n in terms of the multiples given in qs, and the labels given in ks.\n '''\n return lambda ks: lambda n: list(\n chain.from_iterable(map(\n lambda v, k: [(v, k)] if 0 < v else [],\n mapAccumR(\n lambda a, x: divmod(a, x) if 0 < x else (1, a)\n )(n)(qs)[1],\n ks\n ))\n )\n\n\n# --------------------------TEST---------------------------\n# main :: IO ()\ndef main():\n '''Tests of various durations, with a\n particular set of units and labels.\n '''\n\n print(\n fTable('Compound durations from numbers of seconds:\\n')(str)(\n quoted(\"'\")\n )(\n lambda n: ', '.join([\n str(v) + ' ' + k for v, k in\n compoundDurationFromUnits([0, 7, 24, 60, 60])(\n ['wk', 'd', 'hr', 'min', 'sec']\n )(n)\n ])\n )([7259, 86400, 6000000])\n )\n\n\n# -------------------------GENERIC-------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\ndef mapAccumR(f):\n '''A tuple of an accumulation and a list derived by a combined\n map and fold, with accumulation from right to left.\n '''\n def go(a, x):\n acc, y = f(a[0], x)\n return (acc, [y] + a[1])\n return lambda acc: lambda xs: (\n reduce(go, reversed(xs), (acc, []))\n )\n\n\n# quoted :: Char -> String -> String\ndef quoted(c):\n '''A string flanked on both sides\n by a specified quote character.\n '''\n return lambda s: c + s + c\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": " [ ' [ 60 60 24 7 ]\n witheach [ /mod swap ]\n $ \"\"\n ' [ $ \" wk, \" $ \" d, \"\n $ \" hr, \" $ \" min, \"\n $ \" sec, \" ]\n witheach\n [ do rot dup iff\n [ number$\n swap join join ]\n else 2drop ]\n -2 split drop ] is duration$ ( n--> $ )\n\n ' [ 7259 86400 6000000 ]\n witheach\n [ dup echo\n say \" seconds is \"\n duration$ echo$\n say \".\" cr ]\n", "language": "Quackery" }, { "code": "#lang racket/base\n(require racket/string\n racket/list)\n\n(define (seconds->compound-durations s)\n (define-values (w d.h.m.s)\n (for/fold ((prev-q s) (rs (list))) ((Q (in-list (list 60 60 24 7))))\n (define-values (q r) (quotient/remainder prev-q Q))\n (values q (cons r rs))))\n (cons w d.h.m.s))\n\n(define (maybe-suffix v n)\n (and (positive? v)\n (format \"~a ~a\" v n)))\n\n(define (seconds->compound-duration-string s)\n (string-join (filter-map maybe-suffix\n (seconds->compound-durations s)\n '(\"wk\" \"d\" \"hr\" \"min\" \"sec\"))\n \", \"))\n\n(module+ test\n (require rackunit)\n (check-equal? (seconds->compound-durations 7259) (list 0 0 2 0 59))\n (check-equal? (seconds->compound-durations 86400) (list 0 1 0 0 0))\n (check-equal? (seconds->compound-durations 6000000) (list 9 6 10 40 0))\n\n (check-equal? (seconds->compound-duration-string 7259) \"2 hr, 59 sec\")\n (check-equal? (seconds->compound-duration-string 86400) \"1 d\")\n (check-equal? (seconds->compound-duration-string 6000000) \"9 wk, 6 d, 10 hr, 40 min\"))\n\n;; Tim Brown 2015-07-21\n", "language": "Racket" }, { "code": "sub compound-duration ($seconds) {\n ($seconds.polymod(60, 60, 24, 7) Z <sec min hr d wk>)\n .grep(*[0]).reverse.join(\", \")\n}\n\n# Demonstration:\n\nfor 7259, 86400, 6000000 {\n say \"{.fmt: '%7d'} sec = {compound-duration $_}\";\n}\n", "language": "Raku" }, { "code": "/* REXX ---------------------------------------------------------------\n* Format seconds into a time string\n*--------------------------------------------------------------------*/\nCall test 7259 ,'2 hr, 59 sec'\nCall test 86400 ,'1 d'\nCall test 6000000 ,'9 wk, 6 d, 10 hr, 40 min'\nCall test 123.50 ,'2 min, 3.5 sec'\nCall test 123.00 ,'2 min, 3 sec'\nCall test 0.00 ,'0 sec'\nExit\n\ntest:\n Parse arg secs,xres\n res=sec2ct(secs)\n Say res\n If res<>xres Then Say '**ERROR**'\n Return\n\nsec2ct:\nParse Arg s\n/*\nm=s%60; s=s//60\nh=m%60; m=m//60\nd=h%24; h=h//24\nw=d%7; d=d//7\n*/\nIf s=0 Then Return '0 sec'\nParse Value split(s,60) with m s\nParse Value split(m,60) with h m\nParse Value split(h,24) with d h\nParse Value split(d, 7) with w d\nol=''\nIf w>0 Then ol=ol w 'wk,'\nIf d>0 Then ol=ol d 'd,'\nIf h>0 Then ol=ol h 'hr,'\nIf m>0 Then ol=ol m 'min,'\nIf s>0 Then ol=ol (s/1) 'sec'\nol=strip(ol)\nol=strip(ol,,',')\nReturn ol\n\nsplit: Procedure\n Parse Arg what,how\n a=what%how\n b=what//how\n Return a b\n", "language": "REXX" }, { "code": "/*rexx program demonstrates how to convert a number of seconds to bigger time units.*/\nparse arg @; if @='' then @=7259 86400 6000000 /*Not specified? Then use the default.*/\n\n do j=1 for words(@); z= word(@, j) /* [↓] process each number in the list*/\n say right(z, 25) 'seconds: ' convSec(z) /*convert a number to bigger time units*/\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nconvSec: parse arg x /*obtain a number from the argument. */\n w= timeU( 60*60*24*7, 'wk' ) /*obtain number of weeks (if any). */\n d= timeU( 60*60*24 , 'd' ) /* \" \" \" days \" \" */\n h= timeU( 60*60 , 'hr' ) /* \" \" \" hours \" \" */\n m= timeU( 60 , 'min' ) /* \" \" \" minutes \" \" */\n s= timeU( 1 , 'sec' ) /* \" \" \" seconds \" \" */\n if x\\==0 then s=word(s 0, 1) + x 'sec' /*handle fractional (residual) seconds.*/\n $=strip(space(w d h m s),,\",\"); if $=='' then z= 0 \"sec\" /*handle 0 sec.*/\n return $\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ntimeU: parse arg u,$; _= x%u; if _==0 then return ''; x= x - _*u; return _ $\",\"\n", "language": "REXX" }, { "code": "sec = 6000005\nweek = floor(sec/60/60/24/7)\nif week > 0 see sec\n see \" seconds is \" + week + \" weeks \" ok\nday = floor(sec/60/60/24) % 7\nif day > 0 see day\n see \" days \" ok\nhour = floor(sec/60/60) % 24\nif hour > 0 see hour\n see \" hours \" ok\nminute = floor(sec/60) % 60\nif minute > 0 see minute\n see \" minutes \" ok\nsecond = sec % 60\nif second > 0 see second\n see \" seconds\" + nl ok\n", "language": "Ring" }, { "code": "MINUTE = 60\nHOUR = MINUTE*60\nDAY = HOUR*24\nWEEK = DAY*7\n\ndef sec_to_str(sec)\n w, rem = sec.divmod(WEEK)\n d, rem = rem.divmod(DAY)\n h, rem = rem.divmod(HOUR)\n m, s = rem.divmod(MINUTE)\n units = [\"#{w} wk\", \"#{d} d\", \"#{h} h\", \"#{m} min\", \"#{s} sec\"]\n units.reject{|str| str.start_with?(\"0\")}.join(\", \")\nend\n\n[7259, 86400, 6000000].each{|t| puts \"#{t}\\t: #{sec_to_str(t)}\"}\n", "language": "Ruby" }, { "code": "sec = 6000005\nweek\t= int(sec/60/60/24/7)\nday\t= int(sec/60/60/24) mod 7\nhour\t= int(sec/60/60) mod 24\nminute\t= int(sec/60) mod 60\nsecond\t= sec mod 60\n\nprint sec;\" seconds is \";\nif week > 0 then print week;\" weeks \";\nif day > 0 then print day;\" days \";\nif hour > 0 then print hour;\" hours \";\nif minute > 0 then print minute;\" minutes \";\nif second > 0 then print second;\" seconds\"\n", "language": "Run-BASIC" }, { "code": "use std::fmt;\n\n\nstruct CompoundTime {\n w: usize,\n d: usize,\n h: usize,\n m: usize,\n s: usize,\n}\n\nmacro_rules! reduce {\n ($s: ident, $(($from: ident, $to: ident, $factor: expr)),+) => {{\n $(\n $s.$to += $s.$from / $factor;\n $s.$from %= $factor;\n )+\n }}\n}\n\nimpl CompoundTime {\n #[inline]\n fn new(w: usize, d: usize, h: usize, m: usize, s: usize) -> Self{\n CompoundTime { w: w, d: d, h: h, m: m, s: s, }\n }\n\n #[inline]\n fn balance(&mut self) {\n reduce!(self, (s, m, 60), (m, h, 60),\n (h, d, 24), (d, w, 7));\n }\n}\n\nimpl fmt::Display for CompoundTime {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"{}w {}d {}h {}m {}s\",\n self.w, self.d, self.h, self.m, self.s)\n }\n}\n\nfn main() {\n let mut ct = CompoundTime::new(0,3,182,345,2412);\n println!(\"Before: {}\", ct);\n ct.balance();\n println!(\"After: {}\", ct);\n}\n", "language": "Rust" }, { "code": "//Converting Seconds to Compound Duration\n\nobject seconds{\n\tdef main( args:Array[String] ){\n\t\t\n\t\tprintln(\"Enter the no.\")\n\t\tval input = scala.io.StdIn.readInt()\n\t\t\n\t\tvar week_r:Int = input % 604800\n\t\tvar week:Int = (input - week_r)/604800\n\t\t\n\t\tvar day_r:Int = week_r % 86400\n\t\tvar day:Int = (week_r - day_r)/86400\n\t\t\n\t\tvar hour_r:Int = day_r % 3600\n\t\tvar hour:Int = (day_r - hour_r)/3600\n\t\t\n\t\tvar minute_r:Int = hour_r % 60\n\t\tvar minute:Int = (hour_r - minute_r)/60\n\t\t\n\t\tvar sec:Int = minute_r % 60\n\t\t\n\t\tprintln(\"Week = \" + week)\n\t\tprintln(\"Day = \" + day)\n\t\tprintln(\"Hour = \" + hour)\n\t\tprintln(\"Minute = \" + minute)\n\t\tprintln(\"Second = \" + sec)\n\t}\n}\n", "language": "Scala" }, { "code": "(import (scheme base)\n (scheme write)\n (srfi 1)\n (only (srfi 13) string-join))\n\n(define *seconds-in-minute* 60)\n(define *seconds-in-hour* (* 60 *seconds-in-minute*))\n(define *seconds-in-day* (* 24 *seconds-in-hour*))\n(define *seconds-in-week* (* 7 *seconds-in-day*))\n\n(define (seconds->duration seconds)\n (define (format val unit)\n (if (zero? val) \"\" (string-append (number->string val) \" \" unit)))\n (let*-values (((weeks wk-remainder) (floor/ seconds *seconds-in-week*))\n ((days dy-remainder) (floor/ wk-remainder *seconds-in-day*))\n ((hours hr-remainder) (floor/ dy-remainder *seconds-in-hour*))\n ((minutes mn-remainder) (floor/ hr-remainder *seconds-in-minute*)))\n (string-join (delete \"\"\n (list (format weeks \"wk\")\n (format days \"d\")\n (format hours \"hr\")\n (format minutes \"min\")\n (format mn-remainder \"sec\"))\n string=?) \", \")))\n\n(display (seconds->duration 7259)) (newline)\n(display (seconds->duration 86400)) (newline)\n(display (seconds->duration 6000000)) (newline)\n", "language": "Scheme" }, { "code": "func polymod(n, *divs) {\n gather {\n divs.each { |i|\n var m = take(n % i)\n (n -= m) /= i\n }\n take(n)\n }\n}\n\nfunc compound_duration(seconds) {\n (polymod(seconds, 60, 60, 24, 7) ~Z <sec min hr d wk>).grep { |a|\n a[0] > 0\n }.reverse.map{.join(' ')}.join(', ')\n}\n\n[7259, 86400, 6000000].each { |s|\n say \"#{'%7d' % s} sec = #{compound_duration(s)}\"\n}\n", "language": "Sidef" }, { "code": "local\n fun fmtNonZero (0, _, list) = list\n | fmtNonZero (n, s, list) = Int.toString n ^ \" \" ^ s :: list\n fun divModHead (_, []) = []\n | divModHead (d, head :: tail) = head div d :: head mod d :: tail\nin\n fun compoundDuration seconds =\n let\n val digits = foldl divModHead [seconds] [60, 60, 24, 7]\n and units = [\"wk\", \"d\", \"hr\", \"min\", \"sec\"]\n in\n String.concatWith \", \" (ListPair.foldr fmtNonZero [] (digits, units))\n end\nend\n\nval () = app (fn s => print (compoundDuration s ^ \"\\n\")) [7259, 86400, 6000000]\n", "language": "Standard-ML" }, { "code": "func duration (_ secs:Int) -> String {\n if secs <= 0 { return \"\" }\n let units = [(604800,\"wk\"), (86400,\"d\"), (3600,\"hr\"), (60,\"min\")]\n var secs = secs\n var result = \"\"\n for (period, unit) in units {\n if secs >= period {\n result += \"\\(secs/period) \\(unit), \"\n secs = secs % period\n }\n }\n if secs == 0 {\n result.removeLast(2) // remove \", \"\n } else {\n result += \"\\(secs) sec\"\n }\n return result\n}\n\nprint(duration(7259))\nprint(duration(86400))\nprint(duration(6000000))\n", "language": "Swift" }, { "code": "proc sec2str {i} {\n set factors {\n sec 60\n min 60\n hr 24\n d 7\n wk Inf\n }\n set result \"\"\n foreach {label max} $factors {\n if {$i >= $max} {\n set r [expr {$i % $max}]\n set i [expr {$i / $max}]\n if {$r} {\n lappend result \"$r $label\"\n }\n } else {\n if {$i > 0} {\n lappend result \"$i $label\"\n }\n break\n }\n }\n join [lreverse $result] \", \"\n}\n\nproc check {cmd res} {\n set r [uplevel 1 $cmd]\n if {$r eq $res} {\n puts \"Ok! $cmd \\t = $res\"\n } else {\n puts \"ERROR: $cmd = $r \\t expected $res\"\n }\n}\n\ncheck {sec2str 7259} {2 hr, 59 sec}\ncheck {sec2str 86400} {1 d}\ncheck {sec2str 6000000} {9 wk, 6 d, 10 hr, 40 min}\n", "language": "Tcl" }, { "code": "import stdlib.*;\nimport stdlib.stdin.*;\nimport stdlib.math.*;\n\nexported func main() {\n\tforeach testCase in [#][\n\t\t7259,\n\t\t86400,\n\t\t6000000,\n\t] {\n\t\ttestCase.timeString().println();\n\t}\n}\n\nfunc timeString(seconds int) str {\n\tresult = \"\";\n\n\tminutes = seconds / 60;\n\tset seconds = seconds.mod(60);\n\tif seconds > 0 {\n\t\tset result = seconds.str() + \" sec\";\n\t}\n\n\thours = minutes / 60;\n\tset minutes = minutes.mod(60);\n\tif minutes > 0 {\n\t\tset result = minutes.str() + if result != \"\" {\n\t\t\t\" min, \" + result\n\t\t} else {\n\t\t\t\" min\"\n\t\t};\n\t}\n\n\tdays = hours / 24;\n\tset hours = hours.mod(24);\n\tif hours > 0 {\n\t\tset result = hours.str() + if result != \"\" {\n\t\t\t\" hr, \" + result\n\t\t} else {\n\t\t\t\" hr\"\n\t\t};\n\t}\n\n\tweeks = days / 7;\n\tset days = days.mod(7);\n\tif days > 0 {\n\t\tset result = days.str() + if result != \"\" {\n\t\t\t\" d, \" + result\n\t\t} else {\n\t\t\t\" d\"\n\t\t};\n\t}\n\tif weeks > 0 {\n\t\tset result = weeks.str() + if result != \"\" {\n\t\t\t\" wk, \" + result\n\t\t} else {\n\t\t\t\" wk\"\n\t\t};\n\t}\n\n\treturn result;\n}\n", "language": "Vale" }, { "code": "Private Function compound_duration(ByVal seconds As Long) As String\n minutes = 60\n hours = 60 * minutes\n days_ = 24 * hours\n weeks = 7 * days_\n Dim out As String\n w = seconds \\ weeks\n seconds = seconds - w * weeks\n d = seconds \\ days_\n seconds = seconds - d * days_\n h = seconds \\ hours\n seconds = seconds - h * hours\n m = seconds \\ minutes\n s = seconds Mod minutes\n out = IIf(w > 0, w & \" wk, \", \"\") & _\n IIf(d > 0, d & \" d, \", \"\") & _\n IIf(h > 0, h & \" hr, \", \"\") & _\n IIf(m > 0, m & \" min, \", \"\") & _\n IIf(s > 0, s & \" sec\", \"\")\n If Right(out, 2) = \", \" Then\n compound_duration = Left(out, Len(out) - 2)\n Else\n compound_duration = out\n End If\nEnd Function\n\nPublic Sub cstcd()\n Debug.Print compound_duration(7259)\n Debug.Print compound_duration(86400)\n Debug.Print compound_duration(6000000)\nEnd Sub\n", "language": "VBA" }, { "code": "Function compound_duration(n)\n\tDo Until n = 0\n\t\tIf n >= 604800 Then\n\t\t\twk = Int(n/604800)\n\t\t\tn = n-(604800*wk)\n\t\t\tcompound_duration = compound_duration & wk & \" wk\"\n\t\tEnd If\n\t\tIf n >= 86400 Then\n\t\t\td = Int(n/86400)\n\t\t\tn = n-(86400*d)\n\t\t\tIf wk > 0 Then compound_duration = compound_duration & \", \" End If\n\t\t\tcompound_duration = compound_duration & d & \" d\"\n\t\tEnd If\n\t\tIf n >= 3600 Then\n\t\t\thr = Int(n/3600)\n\t\t\tn = n-(3600*hr)\n\t\t\tIf d > 0 Then compound_duration = compound_duration & \", \" End If\n\t\t\tcompound_duration = compound_duration & hr & \" hr\"\n\t\tEnd If\n\t\tIf n >= 60 Then\n\t\t\tmin = Int(n/60)\n\t\t\tn = n-(60*min)\n\t\t\tIf hr > 0 Then compound_duration = compound_duration & \", \" End If\n\t\t\tcompound_duration = compound_duration & min & \" min\"\n\t\tEnd If\n\t\tIf n > 0 Then\n\t\t\tIf min > 0 Then compound_duration = compound_duration & \", \" End If\n\t\t\tcompound_duration = compound_duration & \", \" & n & \" sec\"\n\t\t\tn = 0\n\t\tEnd If\n\tLoop\nEnd Function\n\n'validating the function\nWScript.StdOut.WriteLine compound_duration(7259)\nWScript.StdOut.WriteLine compound_duration(86400)\nWScript.StdOut.WriteLine compound_duration(6000000)\n", "language": "VBScript" }, { "code": "var duration = Fn.new { |s|\n if (s < 1) return \"0 sec\"\n var dur = \"\"\n var divs = [7, 24, 60, 60, 1]\n var units = [\"wk\", \"d\", \"hr\", \"min\", \"sec\"]\n var t = divs.reduce { |prod, div| prod * div }\n for (i in 0...divs.count) {\n var u = (s/t).floor\n if (u > 0) {\n dur = dur + \"%(u) %(units[i]), \"\n s = s % t\n }\n t = t / divs[i]\n }\n if (dur.endsWith(\", \")) dur = dur[0..-3]\n return dur\n}\n\nfor (s in [7259, 86400, 6000000]) System.print(duration.call(s))\n", "language": "Wren" }, { "code": "char Str(80);\nfunc Duration(Sec); \\Convert seconds to compound duration\nint Sec, Amt, Unit, DoComma, I, Quot;\n[Amt:= [7*24*60*60, 24*60*60, 60*60, 60, 1];\nUnit:= [\" wk\", \" d\", \" hr\", \" min\", \" sec\"];\nDoComma:= false;\nfor I:= 0 to 4 do\n [Quot:= Sec/Amt(I);\n Sec:= rem(0);\n if Quot # 0 then\n [if DoComma then Text(8, \", \");\n DoComma:= true;\n IntOut(8, Quot);\n Text(8, Unit(I));\n ];\n ];\nChOut(8, $0D); ChOut(8, $8A); \\terminating CR+LF\nI:= 0;\nloop [Str(I):= ChIn(8);\n if Str(I) >= $80 then return Str;\n I:= I+1;\n ];\n];\n\n[Text(0, Duration(7259));\n Text(0, Duration(86400));\n Text(0, Duration(6_000_000));\n]\n", "language": "XPL0" }, { "code": "fcn toWDHMS(sec){ //-->(wk,d,h,m,s)\n r,b:=List(),0;\n foreach u in (T(60,60,24,7)){\n sec,b=sec.divr(u); // aka divmod\n r.append(b);\n }\n r.append(sec).reverse()\n}\n", "language": "Zkl" }, { "code": "fcn toWDHMS(sec){ //-->(wk,d,h,m,s)\n T(60,60,24,7).reduce(fcn(n,u,r){ n,u=n.divr(u); r.append(u); n },\n sec,r:=List()):r.append(_).reverse();\n}\n", "language": "Zkl" }, { "code": "units:=T(\" wk\",\" d\",\" hr\",\" min\",\" sec\");\nforeach s in (T(7259,86400,6000000)){\n toWDHMS(s).zip(units).pump(List,fcn([(t,u)]){ t and String(t,u) or \"\" })\n .filter().concat(\", \").println();\n}\n", "language": "Zkl" }, { "code": "10 LET m=60: LET h=60*m: LET d=h*24: LET w=d*7\n20 DATA 10,7259,86400,6000000,0,1,60,3600,604799,604800,694861\n30 READ n\n40 FOR i=1 TO n\n50 READ s\n60 LET nweek=0: LET nday=0: LET nhour=0: LET nmin=0: LET nsec=0: LET s$=\"\"\n70 PRINT s;\" = \";\n80 IF s>=w THEN LET nweek=INT (s/w): LET s=FN m(s,w)\n90 IF s>=d THEN LET nday=INT (s/d): LET s=FN m(s,d)\n100 IF s>=h THEN LET nhour=INT (s/h): LET s=FN m(s,h)\n110 IF s>=m THEN LET nmin=INT (s/m): LET s=FN m(s,m)\n120 LET nsec=INT (s)\n130 IF nweek>0 THEN LET s$=s$+STR$ nweek+\" wk, \"\n140 IF nday>0 THEN LET s$=s$+STR$ nday+\" d, \"\n150 IF nhour>0 THEN LET s$=s$+STR$ nhour+\" hr, \"\n160 IF nmin>0 THEN LET s$=s$+STR$ nmin+\" min, \"\n170 IF nsec>0 THEN LET s$=s$+STR$ nsec+\" sec\"\n180 IF s$<>\"\" THEN IF s$(LEN s$-1)=\",\" THEN LET s$=s$( TO LEN s$-2)\n190 PRINT s$\n200 NEXT i\n210 STOP\n220 DEF FN m(a,b)=a-INT (a/b)*b\n", "language": "ZX-Spectrum-Basic" } ]
Convert-seconds-to-compound-duration
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Convex_hull\nnote: geometry\n", "language": "00-META" }, { "code": "Find the points which form a [[wp:Convex hull|convex hull]] from a set of arbitrary two dimensional points.\n\nFor example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).\n<br><br>\n;See also\n* [https://www.youtube.com/watch?v=wRTGDig3jx8 Convex Hull (youtube)]\n* http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F orientation(p, q, r)\n V val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)\n I val == 0\n R 0\n R I val > 0 {1} E 2\n\nF calculateConvexHull(points)\n [(Int, Int)] result\n\n I points.len < 3\n R points\n\n V indexMinX = 0\n L(p) points\n V i = L.index\n I p.x < points[indexMinX].x\n indexMinX = i\n\n V p = indexMinX\n V q = 0\n\n L\n result.append(points[p])\n\n q = (p + 1) % points.len\n\n L(i) 0 .< points.len\n I orientation(points[p], points[i], points[q]) == 2\n q = i\n\n p = q\n I p == indexMinX\n L.break\n\n R result\n\nV points = [(16, 3),\n (12, 17),\n (0, 6),\n (-4, -6),\n (16, 6),\n (16, -7),\n (17, -4),\n (5, 19),\n (19, -8),\n (3, 16),\n (12, 13),\n (3, -4),\n (17, 5),\n (-3, 15),\n (-3, -9),\n (0, 11),\n (-9, -3),\n (-4, -2),\n (12, 10)]\n\nV hull = calculateConvexHull(points)\nL(i) hull\n print(i)\n", "language": "11l" }, { "code": "DEFINE POINTSIZE=\"4\"\nTYPE PointI=[INT x,y]\n\nCARD FUNC GetAddr(INT ARRAY points BYTE index)\nRETURN (points+POINTSIZE*index)\n\nBYTE FUNC GetMinXIndex(INT ARRAY points BYTE pLen)\n PointI POINTER p\n BYTE i,index\n INT minX\n\n p=GetAddr(points,0)\n minX=p.x\n index=0\n FOR i=1 TO pLen-1\n DO\n p=GetAddr(points,i)\n IF p.x<minX THEN\n minX=p.x\n index=i\n FI\n OD\nRETURN (index)\n\nBYTE FUNC Orientation(PointI POINTER p,q,r)\n INT v\n v=(q.y-p.y)*(r.x-q.x)\n v==-(q.x-p.x)*(r.y-q.y)\n\n IF v=0 THEN\n RETURN (0)\n ELSEIF v>0 THEN\n RETURN (1)\n FI\nRETURN (2)\n\nPROC ConvexHull(INT ARRAY points BYTE pLen\n INT ARRAY res BYTE POINTER resLen)\n PointI POINTER pSrc,pDst,p1,p2,p3\n BYTE minIndex,i,p,q\n\n IF pLen<3 THEN\n resLen^=pLen\n MoveBlock(res,points,pLen*POINTSIZE)\n RETURN\n FI\n\n resLen^=0\n minIndex=GetMinXIndex(points,pLen)\n p=minIndex q=0\n DO\n pSrc=GetAddr(points,p)\n pDst=GetAddr(res,resLen^)\n pDst.x=pSrc.x\n pDst.y=pSrc.y\n resLen^==+1\n\n q=(p+1) MOD pLen\n FOR i=0 TO pLen-1\n DO\n p1=GetAddr(points,p)\n p2=GetAddr(points,i)\n p3=GetAddr(points,q)\n IF Orientation(p1,p2,p3)=2 THEN\n q=i\n FI\n OD\n p=q\n UNTIL p=minIndex\n OD\nRETURN\n\nPROC PrintPoints(INT ARRAY points BYTE len)\n PointI POINTER p\n BYTE i\n\n FOR i=0 TO len-1\n DO\n p=GetAddr(points,i)\n PrintF(\"(%I,%I) \",p.x,p.y)\n OD\nRETURN\n\nPROC Main()\n INT ARRAY points=[\n 16 3 12 17 0 6 65532 65530\n 16 6 16 65529 17 65532 5 19\n 19 65528 3 16 12 13 3 65532\n 17 5 65533 15 65533 65527\n 0 11 65527 65533 65532 65534\n 12 10]\n INT ARRAY result(38)\n BYTE pLen=[19],rlen\n\n ConvexHull(points,pLen,result,@rlen)\n\n PrintE(\"Points:\")\n PrintPoints(points,pLen)\n PutE() PutE()\n PrintE(\"Convex hull:\")\n PrintPoints(result,rLen)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO;\nwith Ada.Containers.Vectors;\n\nprocedure Convex_Hull is\n\n type Point is record\n X, Y : Integer;\n end record;\n\n package Point_Vectors is\n new Ada.Containers.Vectors (Index_Type => Positive,\n Element_Type => Point);\n use Point_Vectors;\n\n function Find_Convex_Hull (Vec : in Vector) return Vector is\n\n function Counter_Clock_Wise (A, B, C : in Point) return Boolean is\n ((B.X - A.X) * (C.Y - A.Y) > (B.Y - A.Y) * (C.X - A.X));\n\n function Less_Than (Left, Right : Point) return Boolean is\n (Left.X < Right.X);\n\n package Sorter is\n new Point_Vectors.Generic_Sorting (Less_Than);\n\n Sorted : Vector := Vec;\n Result : Vector := Empty_vector;\n use type Ada.Containers.Count_Type;\n begin\n if Vec = Empty_Vector then\n return Empty_Vector;\n end if;\n\n Sorter.Sort (Sorted);\n\n -- Lower hull\n for Index in Sorted.First_Index .. Sorted.Last_Index loop\n while\n Result.Length >= 2 and then\n not Counter_Clock_Wise (Result (Result.Last_Index - 1),\n Result (Result.Last_Index),\n Sorted (Index))\n loop\n Result.Delete_Last;\n end loop;\n Result.Append (Sorted (Index));\n end loop;\n\n -- Upper hull\n declare\n T : constant Ada.Containers.Count_Type := Result.Length + 1;\n begin\n for Index in reverse Sorted.First_Index .. Sorted.Last_Index loop\n while\n Result.Length >= T and then\n not Counter_Clock_Wise (Result (Result.Last_Index - 1),\n Result (Result.Last_Index),\n Sorted (Index))\n loop\n Result.Delete_Last;\n end loop;\n Result.Append (Sorted (Index));\n end loop;\n end;\n\n Result.Delete_Last;\n return Result;\n end Find_Convex_Hull;\n\n procedure Show (Vec : in Vector) is\n use Ada.Text_IO;\n begin\n Put (\"[ \");\n for Point of Vec loop\n Put (\"(\" & Point.X'Image & \",\" & Point.Y'Image & \")\");\n end loop;\n Put (\" ]\");\n end Show;\n\n Vec : constant Vector :=\n (16, 3) & (12,17) & ( 0, 6) & (-4,-6) & (16, 6) &\n (16,-7) & (16,-3) & (17,-4) & ( 5,19) & (19,-8) &\n ( 3,16) & (12,13) & ( 3,-4) & (17, 5) & (-3,15) &\n (-3,-9) & ( 0,11) & (-9,-3) & (-4,-2) & (12,10);\nbegin\n Show (Find_Convex_Hull (Vec));\n Ada.Text_IO.New_Line;\nend Convex_Hull;\n", "language": "Ada" }, { "code": "define :point [x y][]\n\norientation: function [P Q R][\n val: sub (Q\\y - P\\y)*(R\\x - Q\\x) (Q\\x - P\\x)*(R\\y - Q\\y)\n if val=0 -> return 0\n if val>0 -> return 1\n return 2\n]\n\ncalculateConvexHull: function [points][\n result: new []\n\n if 3 > size points [\n loop points 'p -> 'result ++ p\n ]\n\n indexMinX: 0\n loop.with:'i points 'p [\n if p\\x < get points\\[indexMinX] 'x ->\n indexMinX: i\n ]\n\n p: indexMinX\n q: 0\n\n while [true][\n 'result ++ points\\[p]\n\n q: (p + 1) % size points\n\n loop 0..dec size points 'i [\n if 2 = orientation points\\[p] points\\[i] points\\[q] ->\n q: i\n ]\n\n p: q\n\n if p=indexMinX -> break\n ]\n\n return result\n]\n\npoints: @[\n to :point [16 3],\n to :point [12 17],\n to :point [0 6],\n to :point @[neg 4 neg 6],\n to :point [16 6],\n to :point @[16 neg 7],\n to :point @[17 neg 4],\n to :point [5 19],\n to :point @[19 neg 8],\n to :point [3 16],\n to :point [12 13],\n to :point @[3 neg 4],\n to :point [17 5],\n to :point @[neg 3 15],\n to :point @[neg 3 neg 9],\n to :point [0 11],\n to :point @[neg 9 neg 3],\n to :point @[neg 4 neg 2],\n to :point [12 10]\n]\n\nhull: calculateConvexHull points\nloop hull 'i ->\n print i\n", "language": "Arturo" }, { "code": "//\n// Convex hulls by Andrew's monotone chain algorithm.\n//\n// For a description of the algorithm, see\n// https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169\n//\n//\n// The implementation is designed for use with a garbage collector.\n// In other words, some of the memory is allowed to leak.\n//\n// Sometimes, where it is slightly easier if one does so, we do try to\n// free memory. Boehm GC sometimes cannot free allocated memory\n// itself, so perhaps it is just as well if an ATS program explicitly\n// frees some of its memory.\n//\n\n#include \"share/atspre_staload.hats\"\n\n#define NIL list_nil ()\n#define :: list_cons\n\n(* Make the floating point type big, so use of a boxed representation\n for points makes some sense. *)\ntypedef floatpt = ldouble\n\nextern castfn int2floatpt : int -<> floatpt\noverload i2fp with int2floatpt\n\n(*------------------------------------------------------------------*)\n//\n// Enough plane geometry for our purpose.\n//\n\n(* Let us make the point type boxed. Here is one way to do that. The\n name of the type will be \"plane_point_t\". The constructor will be\n named \"plane_point\". *)\ndatatype plane_point_t =\n| plane_point of (floatpt, floatpt)\n\nfn {}\nplane_point_x (p : plane_point_t) :<> floatpt =\n let\n val+ plane_point (x, _) = p\n in\n x\n end\n\nfn {}\nplane_point_y (p : plane_point_t) :<> floatpt =\n let\n val+ plane_point (_, y) = p\n in\n y\n end\n\nfn {}\nplane_point_eq (p : plane_point_t,\n q : plane_point_t) :<> bool =\n let\n val+ plane_point (xp, yp) = p\n val+ plane_point (xq, yq) = q\n in\n xp = xq && yp = yq\n end\n\n(* Impose a total order on points, making it one that will work for\n Andrew's monotone chain algorithm. *)\nfn {}\nplane_point_order (p : plane_point_t,\n q : plane_point_t) :<> bool =\n let\n val+ plane_point (xp, yp) = p\n val+ plane_point (xq, yq) = q\n in\n xp < xq || (xp = xq && yp < yq)\n end\n\n(* Subtraction is really a vector or multivector operation. *)\nfn {}\nplane_point_sub (p : plane_point_t,\n q : plane_point_t) :<> plane_point_t =\n let\n val+ plane_point (xp, yp) = p\n val+ plane_point (xq, yq) = q\n in\n plane_point (xp - xq, yp - yq)\n end\n\n(* Cross product is really a multivector operation. *)\nfn {}\nplane_point_cross (p : plane_point_t,\n q : plane_point_t) :<> floatpt =\n let\n val+ plane_point (xp, yp) = p\n val+ plane_point (xq, yq) = q\n in\n (xp * yq) - (yp * xq)\n end\n\noverload .x with plane_point_x\noverload .y with plane_point_y\noverload = with plane_point_eq\noverload order with plane_point_order\noverload < with plane_point_order\noverload - with plane_point_sub\n\n(* Make \"cross\" a left-associative infix operator with the same\n precedence as \"*\". *)\ninfixl ( * ) cross\noverload cross with plane_point_cross\n\n(*------------------------------------------------------------------*)\n//\n// Sorting an array of points.\n//\n\nfn\nplane_point_array_sort\n {n : int}\n (arr : &(@[plane_point_t][n]) >> _,\n n : size_t n) :<!wrt> void =\n let\n (* The comparison will be inlined by template expansion. *)\n implement\n array_quicksort$cmp<plane_point_t> (p, q) =\n if order (p, q) then (* An overload for plane_point_order. *)\n ~1\n else if q < p then (* Another overload for plane_point_order. *)\n 1\n else\n 0\n in\n (* The following sort routine is in the ATS2 prelude. *)\n array_quicksort<plane_point_t> (arr, n)\n end\n\n(*------------------------------------------------------------------*)\n//\n// Removing duplicates from a sorted array. Returns a new array.\n//\n\nextern fun {a : t@ype}\narray_delete_neighbor_dups$eq (p : a, q : a) :<> bool\n\nfn {a : t@ype}\narray_delete_neighbor_dups\n {n : int}\n (arr : &(@[a][n]),\n n : size_t n)\n :<!wrt> [m : nat | m <= n]\n [parr1 : addr]\n @(@[a][m] @ parr1,\n mfree_gc_v parr1 |\n ptr parr1,\n size_t m) =\n let\n macdef eq = array_delete_neighbor_dups$eq<a>\n\n fn\n nondups_list {n : int}\n (arr : &(@[a][n]),\n n : size_t n)\n :<> [m : nat | m <= n] list (a, m) =\n let\n fun\n loop {i : nat | i < n}\n {k : nat | k < n - i}\n .<i>. (* <-- proof of termination. *)\n (arr : &(@[a][n]),\n i : size_t i,\n lst : list (a, k))\n :<> [m : nat | m <= n] list (a, m) =\n (* Cons a list of non-duplicates, going backwards through\n the array so the list will be in forwards order. (The\n order does not really matter in ATS, though, because in\n the prelude there are both array_initize_list *and*\n array_initize_rlist. *)\n if i = i2sz 0 then\n arr[i] :: lst\n (* The \"\\\" in the following line makes eq temporarily\n infix. *)\n else if arr[i - 1] \\eq arr[i] then\n loop (arr, pred i, lst)\n else\n loop (arr, pred i, arr[i] :: lst)\n\n prval () = lemma_array_param arr\n in\n if n = i2sz 0 then\n NIL\n else\n loop (arr, pred n, NIL)\n end\n\n val lst = nondups_list (arr, n)\n prval () = lemma_list_param lst\n val m = i2sz (length lst)\n\n val @(pfarr1, pfgc1 | parr1) = array_ptr_alloc<a> (m)\n val () = array_initize_list<a> (!parr1, sz2i m, lst)\n in\n @(pfarr1, pfgc1 | parr1, m)\n end\n\n(*------------------------------------------------------------------*)\n//\n// Removing duplicates from a sorted plane_point_t array. Returns a\n// new array.\n//\n\nfn\nplane_point_array_delete_neighbor_dups\n {n : int}\n (arr : &(@[plane_point_t][n]),\n n : size_t n)\n :<!wrt> [m : nat | m <= n]\n [parr1 : addr]\n @(@[plane_point_t][m] @ parr1,\n mfree_gc_v parr1 |\n ptr parr1,\n size_t m) =\n let\n implement\n array_delete_neighbor_dups$eq<plane_point_t> (p, q) =\n p = q (* Here = is an overload for plane_point_eq. *)\n in\n array_delete_neighbor_dups<plane_point_t> (arr, n)\n end\n\n(*------------------------------------------------------------------*)\n//\n// The convex hull algorithm.\n//\n\nfn\ncross_test {m, k : int | 1 <= k; k < m}\n (pt_i : plane_point_t,\n hull : &(@[plane_point_t][m]),\n k : size_t k) :<> bool =\n let\n val hull_k = hull[k]\n and hull_k1 = hull[k - 1]\n in\n i2fp 0 < (hull_k - hull_k1) cross (pt_i - hull_k1)\n end\n\nfn\nconstruct_lower_hull {n : int | 2 <= n}\n (pt : &(@[plane_point_t][n]),\n n : size_t n)\n :<!wrt> [m : int | 2 <= m; m <= n]\n [phull : addr]\n @(@[plane_point_t][n] @ phull,\n mfree_gc_v phull |\n ptr phull,\n size_t m) =\n let\n val @(pfhull, pfgc | phull) = array_ptr_alloc<plane_point_t> n\n\n (* It is easier to work with an array if it is fully\n initialized. (Yes, there are also ways to cheat and so merely\n pretend the array has been initialized.) *)\n val arbitrary_point = plane_point (i2fp 0, i2fp 0)\n val () = array_initize_elt<plane_point_t> (!phull, n,\n arbitrary_point)\n\n (* The macro \"hull\" can be used with index notation \"[]\". *)\n macdef hull = !phull\n\n val () = hull[0] := pt[0]\n val () = hull[1] := pt[1]\n\n fun\n outer_loop {i : int | 0 <= i; i <= n}\n {j : int | 1 <= j; j < n}\n .<n - i>. (* <-- proof of termination. *)\n (pt : &(@[plane_point_t][n]),\n hull : &(@[plane_point_t][n]),\n i : size_t i,\n j : size_t j)\n :<!wrt> [m : int | 2 <= m; m <= n] size_t m =\n if i = n then\n succ j\n else\n let\n val pt_i = pt[i]\n\n fun\n inner_loop {k : int | 0 <= k; k < n - 1}\n .<k>. (* <-- proof of termination. *)\n (hull : &(@[plane_point_t][n]),\n k : size_t k)\n :<!wrt> [j : int | 1 <= j; j < n] size_t j =\n if k = i2sz 0 then\n begin\n hull[succ k] := pt_i;\n succ k\n end\n else if cross_test (pt_i, hull, k) then\n begin\n hull[succ k] := pt_i;\n succ k\n end\n else\n inner_loop (hull, pred k)\n\n (* I do not know how to write a proof of the following, so\n let us test it at runtime. *)\n val () = $effmask_exn assertloc (j < n - 1)\n in\n outer_loop (pt, hull, succ i, inner_loop (hull, j))\n end\n\n val hull_size = outer_loop (pt, hull, i2sz 2, i2sz 1)\n in\n @(pfhull, pfgc | phull, hull_size)\n end\n\nfn\nconstruct_upper_hull {n : int | 2 <= n}\n (pt : &(@[plane_point_t][n]),\n n : size_t n)\n :<!wrt> [m : int | 2 <= m; m <= n]\n [phull : addr]\n @(@[plane_point_t][n] @ phull,\n mfree_gc_v phull |\n ptr phull,\n size_t m) =\n let\n val @(pfhull, pfgc | phull) = array_ptr_alloc<plane_point_t> n\n\n (* It is easier to work with an array if it is fully\n initialized. (Yes, there are also ways to cheat and so merely\n pretend the array has been initialized.) *)\n val arbitrary_point = plane_point (i2fp 0, i2fp 0)\n val () = array_initize_elt<plane_point_t> (!phull, n,\n arbitrary_point)\n\n (* The macro \"hull\" can be used with index notation \"[]\". *)\n macdef hull = !phull\n\n val () = hull[0] := pt[n - 1]\n val () = hull[1] := pt[n - 2]\n\n fun\n outer_loop {i1 : int | 0 <= i1; i1 <= n - 2}\n {j : int | 1 <= j; j < n}\n .<i1>. (* <-- proof of termination. *)\n (pt : &(@[plane_point_t][n]),\n hull : &(@[plane_point_t][n]),\n i1 : size_t i1,\n j : size_t j)\n :<!wrt> [m : int | 2 <= m; m <= n] size_t m =\n if i1 = i2sz 0 then\n succ j\n else\n let\n val i = pred i1\n val pt_i = pt[i]\n\n fun\n inner_loop {k : int | 0 <= k; k < n - 1}\n .<k>. (* <-- proof of termination. *)\n (hull : &(@[plane_point_t][n]),\n k : size_t k)\n :<!wrt> [j : int | 1 <= j; j < n] size_t j =\n if k = i2sz 0 then\n begin\n hull[succ k] := pt_i;\n succ k\n end\n else if cross_test (pt_i, hull, k) then\n begin\n hull[succ k] := pt_i;\n succ k\n end\n else\n inner_loop (hull, pred k)\n\n (* I do not know how to write a proof of the following, so\n let us test it at runtime. *)\n val () = $effmask_exn assertloc (j < n - 1)\n in\n outer_loop (pt, hull, pred i1, inner_loop (hull, j))\n end\n\n val hull_size = outer_loop (pt, hull, n - i2sz 2, i2sz 1)\n in\n @(pfhull, pfgc | phull, hull_size)\n end\n\nfn\nconstruct_hull {n : int | 2 <= n}\n (pt : &(@[plane_point_t][n]),\n n : size_t n)\n :<!wrt> [hull_size : int | 2 <= hull_size]\n [phull : addr]\n @(@[plane_point_t][hull_size] @ phull,\n mfree_gc_v phull |\n ptr phull,\n size_t hull_size) =\n\n (* The following implementation demonstrates slightly complicated\n \"safe\" initialization. By \"safe\" I mean so one never *reads* from\n an uninitialized entry. Elsewhere in the program I did this more\n simply, with prelude routines.\n\n I also demonstrate freeing of a linear object. If you remove the\n calls to array_ptr_free, you cannot compile the program. *)\n\n let\n (* Side note: Construction of the lower and upper hulls can be\n done in parallel. *)\n val [lower_hull_size : int]\n [p_lower_hull : addr]\n @(pf_lower_hull, pfgc_lower | p_lower_hull, lower_hull_size) =\n construct_lower_hull (pt, n)\n and [upper_hull_size : int]\n [p_upper_hull : addr]\n @(pf_upper_hull, pfgc_upper | p_upper_hull, upper_hull_size) =\n construct_upper_hull (pt, n)\n\n stadef hull_size = lower_hull_size + upper_hull_size - 2\n val hull_size : size_t hull_size =\n lower_hull_size + upper_hull_size - i2sz 2\n\n val [phull : addr] @(pfhull, pfgc_hull | phull) =\n array_ptr_alloc<plane_point_t> hull_size\n\n (* Split off the part of each partial hull's view that we actually\n will use. *)\n prval @(pf_lower, pf_lower_rest) =\n array_v_split {plane_point_t} {p_lower_hull} {n}\n {lower_hull_size - 1}\n pf_lower_hull\n prval @(pf_upper, pf_upper_rest) =\n array_v_split {plane_point_t} {p_upper_hull} {n}\n {upper_hull_size - 1}\n pf_upper_hull\n\n (* Split the new array's view in two. The question mark means\n that the array elements are uninitialized. *)\n prval @(pfleft, pfright) =\n array_v_split {plane_point_t?} {phull} {hull_size}\n {lower_hull_size - 1}\n pfhull\n\n (* Copy the lower hull, thus initializing the left side of the new\n array. *)\n val () = array_copy<plane_point_t> (!phull, !p_lower_hull,\n pred lower_hull_size)\n\n (* Copy the upper hull, thus initializing the left side of the new\n array. *)\n val phull_right =\n ptr_add<plane_point_t> (phull, pred lower_hull_size)\n val () = array_copy<plane_point_t> (!phull_right, !p_upper_hull,\n pred upper_hull_size)\n\n (* Join the views of the initialized halves. *)\n prval pfhull = array_v_unsplit (pfleft, pfright)\n\n (* Restore the views of the partial hulls. *)\n prval () = pf_lower_hull :=\n array_v_unsplit (pf_lower, pf_lower_rest)\n prval () = pf_upper_hull :=\n array_v_unsplit (pf_upper, pf_upper_rest)\n\n (* We do not need the lower and upper hulls anymore, and so can\n free them. (Of course, if there is a garbage collector, you\n could make freeing be a no-operation.) *)\n val () = array_ptr_free (pf_lower_hull, pfgc_lower | p_lower_hull)\n val () = array_ptr_free (pf_upper_hull, pfgc_upper | p_upper_hull)\n in\n @(pfhull, pfgc_hull | phull, hull_size)\n end\n\nfn\nplane_convex_hull {num_points : int}\n (points_lst : list (plane_point_t, num_points))\n :<!wrt> [hull_size : int | 0 <= hull_size]\n [phull : addr]\n @(@[plane_point_t][hull_size] @ phull,\n mfree_gc_v phull |\n ptr phull,\n size_t hull_size) =\n (* Takes an arbitrary list of points, which may be in any order and\n may contain duplicates. Returns an ordered array of points that\n make up the convex hull. If the initial list of points is empty,\n the returned array is empty. *)\n let\n prval () = lemma_list_param points_lst\n val num_points = i2sz (length points_lst)\n\n (* Copy the list to an array. *)\n val @(pf_points, pfgc_points | p_points) =\n array_ptr_alloc<plane_point_t> num_points\n val () =\n array_initize_list<plane_point_t> (!p_points, sz2i num_points,\n points_lst)\n\n (* Sort the array. *)\n val () = plane_point_array_sort (!p_points, num_points)\n\n (* Create a new sorted array that has the duplicates removed. *)\n val @(pf_pt, pfgc_pt | p_pt, n) =\n plane_point_array_delete_neighbor_dups (!p_points, num_points)\n\n (* The original array no longer is needed. *)\n val () = array_ptr_free (pf_points, pfgc_points | p_points)\n in\n if n <= 2 then\n @(pf_pt, pfgc_pt | p_pt, n)\n else\n let\n val @(pfhull, pfgc_hull | phull, hull_size) =\n construct_hull (!p_pt, n)\n val () = array_ptr_free (pf_pt, pfgc_pt | p_pt)\n in\n @(pfhull, pfgc_hull | phull, hull_size)\n end\n end\n\n(*------------------------------------------------------------------*)\n\nimplement\nmain0 () =\n {\n val example_points =\n $list (plane_point (i2fp 16, i2fp 3),\n plane_point (i2fp 12, i2fp 17),\n plane_point (i2fp 0, i2fp 6),\n plane_point (i2fp ~4, i2fp ~6),\n plane_point (i2fp 16, i2fp 6),\n plane_point (i2fp 16, i2fp ~7),\n plane_point (i2fp 16, i2fp ~3),\n plane_point (i2fp 17, i2fp ~4),\n plane_point (i2fp 5, i2fp 19),\n plane_point (i2fp 19, i2fp ~8),\n plane_point (i2fp 3, i2fp 16),\n plane_point (i2fp 12, i2fp 13),\n plane_point (i2fp 3, i2fp ~4),\n plane_point (i2fp 17, i2fp 5),\n plane_point (i2fp ~3, i2fp 15),\n plane_point (i2fp ~3, i2fp ~9),\n plane_point (i2fp 0, i2fp 11),\n plane_point (i2fp ~9, i2fp ~3),\n plane_point (i2fp ~4, i2fp ~2),\n plane_point (i2fp 12, i2fp 10))\n\n val (pf_hull, pfgc_hull | p_hull, hull_size) =\n plane_convex_hull example_points\n\n macdef hull = !p_hull\n\n val () =\n let\n var i : [i : nat] size_t i\n in\n for (i := i2sz 0; i < hull_size; i := succ i)\n println! (\"(\", hull[i].x(), \" \", hull[i].y(), \")\")\n end\n\n val () = array_ptr_free (pf_hull, pfgc_hull | p_hull)\n }\n\n(*------------------------------------------------------------------*)\n", "language": "ATS" }, { "code": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct tPoint {\n int x, y;\n} Point;\n\nbool ccw(const Point *a, const Point *b, const Point *c) {\n return (b->x - a->x) * (c->y - a->y)\n > (b->y - a->y) * (c->x - a->x);\n}\n\nint comparePoints(const void *lhs, const void *rhs) {\n const Point* lp = lhs;\n const Point* rp = rhs;\n if (lp->x < rp->x)\n return -1;\n if (rp->x < lp->x)\n return 1;\n if (lp->y < rp->y)\n return -1;\n if (rp->y < lp->y)\n return 1;\n return 0;\n}\n\nvoid fatal(const char* message) {\n fprintf(stderr, \"%s\\n\", message);\n exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n void* ptr = malloc(n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n void* ptr = realloc(p, n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nvoid printPoints(const Point* points, int len) {\n printf(\"[\");\n if (len > 0) {\n const Point* ptr = points;\n const Point* end = points + len;\n printf(\"(%d, %d)\", ptr->x, ptr->y);\n ++ptr;\n for (; ptr < end; ++ptr)\n printf(\", (%d, %d)\", ptr->x, ptr->y);\n }\n printf(\"]\");\n}\n\nPoint* convexHull(Point p[], int len, int* hsize) {\n if (len == 0) {\n *hsize = 0;\n return NULL;\n }\n\n int i, size = 0, capacity = 4;\n Point* hull = xmalloc(capacity * sizeof(Point));\n\n qsort(p, len, sizeof(Point), comparePoints);\n\n /* lower hull */\n for (i = 0; i < len; ++i) {\n while (size >= 2 && !ccw(&hull[size - 2], &hull[size - 1], &p[i]))\n --size;\n if (size == capacity) {\n capacity *= 2;\n hull = xrealloc(hull, capacity * sizeof(Point));\n }\n assert(size >= 0 && size < capacity);\n hull[size++] = p[i];\n }\n\n /* upper hull */\n int t = size + 1;\n for (i = len - 1; i >= 0; i--) {\n while (size >= t && !ccw(&hull[size - 2], &hull[size - 1], &p[i]))\n --size;\n if (size == capacity) {\n capacity *= 2;\n hull = xrealloc(hull, capacity * sizeof(Point));\n }\n assert(size >= 0 && size < capacity);\n hull[size++] = p[i];\n }\n --size;\n assert(size >= 0);\n hull = xrealloc(hull, size * sizeof(Point));\n *hsize = size;\n return hull;\n}\n\nint main() {\n Point points[] = {\n {16, 3}, {12, 17}, { 0, 6}, {-4, -6}, {16, 6},\n {16, -7}, {16, -3}, {17, -4}, { 5, 19}, {19, -8},\n { 3, 16}, {12, 13}, { 3, -4}, {17, 5}, {-3, 15},\n {-3, -9}, { 0, 11}, {-9, -3}, {-4, -2}, {12, 10}\n };\n int hsize;\n Point* hull = convexHull(points, sizeof(points)/sizeof(Point), &hsize);\n printf(\"Convex Hull: \");\n printPoints(hull, hsize);\n printf(\"\\n\");\n free(hull);\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <algorithm>\n#include <iostream>\n#include <ostream>\n#include <vector>\n#include <tuple>\n\ntypedef std::tuple<int, int> point;\n\nstd::ostream& print(std::ostream& os, const point& p) {\n return os << \"(\" << std::get<0>(p) << \", \" << std::get<1>(p) << \")\";\n}\n\nstd::ostream& print(std::ostream& os, const std::vector<point>& v) {\n auto it = v.cbegin();\n auto end = v.cend();\n\n os << \"[\";\n\n if (it != end) {\n print(os, *it);\n it = std::next(it);\n }\n while (it != end) {\n os << \", \";\n print(os, *it);\n it = std::next(it);\n }\n\n return os << \"]\";\n}\n\n// returns true if the three points make a counter-clockwise turn\nbool ccw(const point& a, const point& b, const point& c) {\n return ((std::get<0>(b) - std::get<0>(a)) * (std::get<1>(c) - std::get<1>(a)))\n > ((std::get<1>(b) - std::get<1>(a)) * (std::get<0>(c) - std::get<0>(a)));\n}\n\nstd::vector<point> convexHull(std::vector<point> p) {\n if (p.size() == 0) return std::vector<point>();\n std::sort(p.begin(), p.end(), [](point& a, point& b){\n if (std::get<0>(a) < std::get<0>(b)) return true;\n return false;\n });\n\n std::vector<point> h;\n\n // lower hull\n for (const auto& pt : p) {\n while (h.size() >= 2 && !ccw(h.at(h.size() - 2), h.at(h.size() - 1), pt)) {\n h.pop_back();\n }\n h.push_back(pt);\n }\n\n // upper hull\n auto t = h.size() + 1;\n for (auto it = p.crbegin(); it != p.crend(); it = std::next(it)) {\n auto pt = *it;\n while (h.size() >= t && !ccw(h.at(h.size() - 2), h.at(h.size() - 1), pt)) {\n h.pop_back();\n }\n h.push_back(pt);\n }\n\n h.pop_back();\n return h;\n}\n\nint main() {\n using namespace std;\n\n vector<point> points = {\n make_pair(16, 3), make_pair(12, 17), make_pair(0, 6), make_pair(-4, -6), make_pair(16, 6),\n make_pair(16, -7), make_pair(16, -3), make_pair(17, -4), make_pair(5, 19), make_pair(19, -8),\n make_pair(3, 16), make_pair(12, 13), make_pair(3, -4), make_pair(17, 5), make_pair(-3, 15),\n make_pair(-3, -9), make_pair(0, 11), make_pair(-9, -3), make_pair(-4, -2), make_pair(12, 10)\n };\n\n auto hull = convexHull(points);\n auto it = hull.cbegin();\n auto end = hull.cend();\n\n cout << \"Convex Hull: \";\n print(cout, hull);\n cout << endl;\n\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\n\nnamespace ConvexHull {\n class Point : IComparable<Point> {\n private int x, y;\n\n public Point(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n public int X { get => x; set => x = value; }\n public int Y { get => y; set => y = value; }\n\n public int CompareTo(Point other) {\n return x.CompareTo(other.x);\n }\n\n public override string ToString() {\n return string.Format(\"({0}, {1})\", x, y);\n }\n }\n\n class Program {\n private static List<Point> ConvexHull(List<Point> p) {\n if (p.Count == 0) return new List<Point>();\n p.Sort();\n List<Point> h = new List<Point>();\n\n // lower hull\n foreach (var pt in p) {\n while (h.Count >= 2 && !Ccw(h[h.Count - 2], h[h.Count - 1], pt)) {\n h.RemoveAt(h.Count - 1);\n }\n h.Add(pt);\n }\n\n // upper hull\n int t = h.Count + 1;\n for (int i = p.Count - 1; i >= 0; i--) {\n Point pt = p[i];\n while (h.Count >= t && !Ccw(h[h.Count - 2], h[h.Count - 1], pt)) {\n h.RemoveAt(h.Count - 1);\n }\n h.Add(pt);\n }\n\n h.RemoveAt(h.Count - 1);\n return h;\n }\n\n private static bool Ccw(Point a, Point b, Point c) {\n return ((b.X - a.X) * (c.Y - a.Y)) > ((b.Y - a.Y) * (c.X - a.X));\n }\n\n static void Main(string[] args) {\n List<Point> points = new List<Point>() {\n new Point(16, 3),\n new Point(12, 17),\n new Point(0, 6),\n new Point(-4, -6),\n new Point(16, 6),\n\n new Point(16, -7),\n new Point(16, -3),\n new Point(17, -4),\n new Point(5, 19),\n new Point(19, -8),\n\n new Point(3, 16),\n new Point(12, 13),\n new Point(3, -4),\n new Point(17, 5),\n new Point(-3, 15),\n\n new Point(-3, -9),\n new Point(0, 11),\n new Point(-9, -3),\n new Point(-4, -2),\n new Point(12, 10)\n };\n\n List<Point> hull = ConvexHull(points);\n Console.Write(\"Convex Hull: [\");\n for (int i = 0; i < hull.Count; i++) {\n if (i > 0) {\n Console.Write(\", \");\n }\n Point pt = hull[i];\n Console.Write(pt);\n }\n Console.WriteLine(\"]\");\n }\n }\n}\n", "language": "C-sharp" }, { "code": "#!/bin/sh\n#|-*- mode:lisp -*-|#\n#|\nexec ros -Q -- $0 \"$@\"\n|#\n(progn ;;init forms\n (ros:ensure-asdf)\n #+quicklisp(ql:quickload '() :silent t)\n )\n\n(defpackage :ros.script.convex-hull-task.3861520611\n (:use :cl))\n(in-package :ros.script.convex-hull-task.3861520611)\n\n;;;\n;;; Convex hulls by Andrew's monotone chain algorithm.\n;;;\n;;; For a description of the algorithm, see\n;;; https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169\n;;;\n;;; This program is translated rather faithfully from the Scheme,\n;;; complete with tail recursions.\n;;;\n\n;; x and y coordinates of a \"point\". A \"point\" is represented by a\n;; list of length 2.\n(defun x@ (u) (car u))\n(defun y@ (u) (cadr u))\n\n(defun cross (u v)\n ;; Cross product (as a signed scalar).\n (- (* (x@ u) (y@ v)) (* (y@ u) (x@ v))))\n\n(defun point- (u v)\n (list (- (x@ u) (x@ v)) (- (y@ u) (y@ v))))\n\n(defun sort-points-vector (points-vector)\n ;; Ascending sort on x-coordinates, followed by ascending sort\n ;; on y-coordinates.\n (sort points-vector #'(lambda (u v)\n (or (< (x@ u) (x@ v))\n (and (= (x@ u) (x@ v))\n (< (y@ u) (y@ v)))))))\n\n(defun construct-lower-hull (sorted-points-vector)\n (let* ((pt sorted-points-vector)\n (n (length pt))\n (hull (make-array n))\n (j 1))\n (setf (aref hull 0) (aref pt 0))\n (setf (aref hull 1) (aref pt 1))\n (loop for i from 2 to (1- n)\n do (progn\n (defun inner-loop ()\n (if (or (zerop j)\n (plusp\n (cross (point- (aref hull j)\n (aref hull (1- j)))\n (point- (aref pt i)\n (aref hull (1- j))))))\n (progn\n (setf j (1+ j))\n (setf (aref hull j) (aref pt i)))\n (progn\n (setf j (1- j))\n (inner-loop))))\n (inner-loop)))\n (values (+ j 1) hull))) ; Hull size, hull points.\n\n(defun construct-upper-hull (sorted-points-vector)\n (let* ((pt sorted-points-vector)\n (n (length pt))\n (hull (make-array n))\n (j 1))\n (setf (aref hull 0) (aref pt (- n 1)))\n (setf (aref hull 1) (aref pt (- n 2)))\n (loop for i from (- n 3) downto 0\n do (progn\n (defun inner-loop ()\n (if (or (zerop j)\n (plusp\n (cross (point- (aref hull j)\n (aref hull (1- j)))\n (point- (aref pt i)\n (aref hull (1- j))))))\n (progn\n (setf j (1+ j))\n (setf (aref hull j) (aref pt i)))\n (progn\n (setf j (1- j))\n (inner-loop))))\n (inner-loop)))\n (values (+ j 1) hull))) ; Hull size, hull points.\n\n(defun construct-hull (sorted-points-vector)\n ;; Notice that the lower and upper hulls could be constructed in\n ;; parallel. (The Scheme \"let-values\" macro made this apparent,\n ;; despite not actually doing the computation in parallel. The\n ;; coding here makes it less obvious.)\n (multiple-value-bind (lower-hull-size lower-hull)\n (construct-lower-hull sorted-points-vector)\n (multiple-value-bind (upper-hull-size upper-hull)\n (construct-upper-hull sorted-points-vector)\n (let* ((hull-size (+ lower-hull-size upper-hull-size -2))\n (hull (make-array hull-size)))\n (loop for i from 0 to (- lower-hull-size 2)\n do (setf (aref hull i) (aref lower-hull i)))\n (loop for i from 0 to (- upper-hull-size 2)\n do (setf (aref hull (+ i (1- lower-hull-size)))\n (aref upper-hull i)))\n hull))))\n\n(defun vector-delete-neighbor-dups (elt= v)\n ;; A partial clone of the SRFI-132 procedure of the same name. This\n ;; implementation is similar to the reference implementation for\n ;; SRFI-132, and may use a bunch of stack space. That reference\n ;; implementation is by Olin Shivers and rests here:\n ;; https://github.com/scheme-requests-for-implementation/srfi-132/blob/master/sorting/delndups.scm\n ;; The license is:\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;; This code is\n;;; Copyright (c) 1998 by Olin Shivers.\n;;; The terms are: You may do as you please with this code, as long as\n;;; you do not delete this notice or hold me responsible for any outcome\n;;; related to its use.\n;;;\n;;; Blah blah blah. Don't you think source files should contain more lines\n;;; of code than copyright notice?\n;;;\n (let ((start 0)\n (end (length v)))\n (let ((x (aref v start)))\n (defun recur (x i j)\n (if (< i end)\n (let ((y (aref v i))\n (nexti (1+ i)))\n (if (funcall elt= x y)\n (recur x nexti j)\n (let ((ansvec (recur y nexti (1+ j))))\n (setf (aref ansvec j) y)\n ansvec)))\n (make-array j)))\n (let ((ans (recur x start 1)))\n (setf (aref ans 0) x)\n ans))))\n\n(defun vector-convex-hull (points)\n (let* ((points-vector (coerce points 'vector))\n (sorted-points-vector\n (vector-delete-neighbor-dups\n #'equalp\n (sort-points-vector points-vector))))\n (if (<= (length sorted-points-vector) 2)\n sorted-points-vector\n (construct-hull sorted-points-vector))))\n\n(defun list-convex-hull (points)\n (coerce (vector-convex-hull points) 'list))\n\n(defconstant example-points\n '((16 3) (12 17) (0 6) (-4 -6) (16 6)\n (16 -7) (16 -3) (17 -4) (5 19) (19 -8)\n (3 16) (12 13) (3 -4) (17 5) (-3 15)\n (-3 -9) (0 11) (-9 -3) (-4 -2) (12 10)))\n\n(defun main (&rest argv)\n (declare (ignorable argv))\n (write (list-convex-hull example-points))\n (terpri))\n\n;;; vim: set ft=lisp lisp:\n", "language": "Common-Lisp" }, { "code": "import std.algorithm.sorting;\nimport std.stdio;\n\nstruct Point {\n int x;\n int y;\n\n int opCmp(Point rhs) {\n if (x < rhs.x) return -1;\n if (rhs.x < x) return 1;\n return 0;\n }\n\n void toString(scope void delegate(const(char)[]) sink) const {\n import std.format;\n sink(\"(\");\n formattedWrite(sink, \"%d\", x);\n sink(\",\");\n formattedWrite(sink, \"%d\", y);\n sink(\")\");\n }\n}\n\nPoint[] convexHull(Point[] p) {\n if (p.length == 0) return [];\n p.sort;\n Point[] h;\n\n // lower hull\n foreach (pt; p) {\n while (h.length >= 2 && !ccw(h[$-2], h[$-1], pt)) {\n h.length--;\n }\n h ~= pt;\n }\n\n // upper hull\n auto t = h.length + 1;\n foreach_reverse (i; 0..(p.length - 1)) {\n auto pt = p[i];\n while (h.length >= t && !ccw(h[$-2], h[$-1], pt)) {\n h.length--;\n }\n h ~= pt;\n }\n\n h.length--;\n return h;\n}\n\n/* ccw returns true if the three points make a counter-clockwise turn */\nauto ccw(Point a, Point b, Point c) {\n return ((b.x - a.x) * (c.y - a.y)) > ((b.y - a.y) * (c.x - a.x));\n}\n\nvoid main() {\n auto points = [\n Point(16, 3), Point(12, 17), Point( 0, 6), Point(-4, -6), Point(16, 6),\n Point(16, -7), Point(16, -3), Point(17, -4), Point( 5, 19), Point(19, -8),\n Point( 3, 16), Point(12, 13), Point( 3, -4), Point(17, 5), Point(-3, 15),\n Point(-3, -9), Point( 0, 11), Point(-9, -3), Point(-4, -2), Point(12, 10)\n ];\n auto hull = convexHull(points);\n writeln(\"Convex Hull: \", hull);\n}\n", "language": "D" }, { "code": "program ConvexHulls;\n\n{$APPTYPE CONSOLE}\n\n{$R *.res}\n\nuses\n System.Types,\n System.SysUtils,\n System.Generics.Defaults,\n System.Generics.Collections;\n\n function Ccw(const a, b, c: TPoint): Boolean;\n begin\n Result := ((b.X - a.X) * (c.Y - a.Y)) > ((b.Y - a.Y) * (c.X - a.X));\n end;\n\n function ConvexHull(const p: TList<TPoint>): TList<TPoint>;\n var\n pt: TPoint;\n i, t: Integer;\n begin\n Result := TList<TPoint>.Create;\n\n if (p.Count = 0) then Exit;\n\n p.Sort(TComparer<TPoint>.Construct(\n function(const Left, Right: TPoint): Integer\n begin\n Result := Left.X - Right.X;\n end\n ));\n\n // lower hull\n for i := 0 to p.Count-1 do\n begin\n pt := p[i];\n while ((Result.Count >= 2) and (not Ccw(Result[Result.Count - 2], Result[Result.Count - 1], pt))) do\n begin\n Result.Delete(Result.Count - 1);\n end;\n Result.Add(pt);\n end;\n\n // upper hull\n t := Result.Count + 1;\n for i := p.Count-1 downto 0 do\n begin\n pt := p[i];\n while ((Result.Count >= t) and (not Ccw(Result[Result.Count - 2], Result[Result.Count - 1], pt))) do\n begin\n Result.Delete(Result.Count - 1);\n end;\n Result.Add(pt);\n end;\n\n Result.Delete(Result.Count - 1);\n end;\n\nvar\n points: TList<TPoint>;\n hull: TList<TPoint>;\n i: Integer;\nbegin\n\n hull := nil;\n points := TList<TPoint>.Create;\n try\n\n points.AddRange([\n Point(16, 3),\n Point(12, 17),\n Point(0, 6),\n Point(-4, -6),\n Point(16, 6),\n Point(16, -7),\n Point(16, -3),\n Point(17, -4),\n Point(5, 19),\n Point(19, -8),\n Point(3, 16),\n Point(12, 13),\n Point(3, -4),\n Point(17, 5),\n Point(-3, 15),\n Point(-3, -9),\n Point(0, 11),\n Point(-9, -3),\n Point(-4, -2),\n Point(12, 10)\n ]);\n\n hull := ConvexHull(points);\n\n // Output the result\n Write('Convex Hull: [');\n for i := 0 to hull.Count-1 do\n begin\n if (i > 0) then Write(', ');\n Write(Format('(%d, %d)', [hull[i].X, hull[i].Y]));\n end;\n WriteLn(']');\n\n finally\n hull.Free;\n points.Free;\n end;\n\nend.\n", "language": "Delphi" }, { "code": "func orientation p[] q[] r[] .\n return (q[2] - p[2]) * (r[1] - q[1]) - (q[1] - p[1]) * (r[2] - q[2])\n.\nproc calcConvexHull . pts[][] res[][] .\n res[][] = [ ]\n indMinX = 1\n for i to len pts[][]\n if pts[i][1] < pts[indMinX][1]\n indMinX = i\n .\n .\n p = indMinX\n repeat\n res[][] &= pts[p][]\n q = (p + 1) mod1 len pts[][]\n for i to len pts[][]\n if orientation pts[p][] pts[i][] pts[q][] < 0\n q = i\n .\n .\n p = q\n until p = indMinX\n .\n.\n#\npts[][] = [ [ 16 3 ] [ 12 17 ] [ 0 6 ] [ -4 -6 ] [ 16 6 ] [ 16 -7 ] [ 16 -3 ] [ 17 -4 ] [ 5 19 ] [ 19 -8 ] [ 3 16 ] [ 12 13 ] [ 3 -4 ] [ 17 5 ] [ -3 15 ] [ -3 -9 ] [ 0 11 ] [ -9 -3 ] [ -4 -2 ] [ 12 10 ] ]\ncalcConvexHull pts[][] res[][]\nprint res[][]\n", "language": "EasyLang" }, { "code": "open System\n\ntype Point =\n struct\n val X : int\n val Y : int\n new (x : int, y : int ) = {X = x; Y = y}\n end\n\nlet (poly : Point list) = [ Point(16, 3); Point(12, 17); Point( 0, 6); Point(-4, -6); Point(16, 6);\n Point(16, -7); Point(16, -3); Point(17, -4); Point( 5, 19); Point(19, -8);\n Point( 3, 16); Point(12, 13); Point( 3, -4); Point(17, 5); Point(-3, 15);\n Point(-3, -9); Point( 0, 11); Point(-9, -3); Point(-4, -2); Point(12, 10)]\n\n\nlet affiche (lst : Point list) =\n let mutable (str : string) = List.fold (fun acc (p : Point) -> acc + sprintf \"(%d, %d) \" p.X p.Y) \"Convex Hull: [\" lst\n printfn \"%s\" (str.[0.. str.Length - 2] + \"]\")\n\nlet ccw (p1 : Point) (p2 : Point) (p3 : Point) =\n (p2.X - p1.X) * (p3.Y - p1.Y) > (p2.Y - p1.Y) * (p3.X - p1.X)\n\nlet convexHull (poly : Point list) =\n let mutable (outHull : Point list) = List.Empty\n let mutable (k : int) = 0\n\n for p in poly do\n while k >= 2 && not (ccw outHull.[k-2] outHull.[k-1] p) do\n k <- k - 1\n if k >= outHull.Length\n then outHull <- outHull @ [p]\n else outHull <- outHull.[0..k - 1] @ [p]\n k <- k + 1\n\n let (t : int) = k + 1\n for p in List.rev poly do\n while k >= t && not (ccw outHull.[k-2] outHull.[k-1] p) do\n k <- k - 1\n if k >= outHull.Length\n then outHull <- outHull @ [p]\n else outHull <- outHull.[0..k - 1] @ [p]\n k <- k + 1\n\n outHull.[0 .. k - 2]\n\naffiche (convexHull (List.sortBy (fun (x : Point) -> x.X, x.Y) poly))\n", "language": "F-Sharp" }, { "code": "module convex_hulls\n !\n ! Convex hulls by Andrew's monotone chain algorithm.\n !\n ! For a description of the algorithm, see\n ! https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169\n !\n ! For brevity in the task, I shall use the built-in \"complex\" type\n ! to represent objects in the plane. One could have fun rewriting\n ! this implementation in terms of geometric algebra.\n !\n\n implicit none\n private\n\n public :: find_convex_hull\n\ncontains\n\n elemental function x (u)\n complex, intent(in) :: u\n real :: x\n\n x = real (u)\n end function x\n\n elemental function y (u)\n complex, intent(in) :: u\n real :: y\n\n y = aimag (u)\n end function y\n\n elemental function cross (u, v) result (p)\n complex, intent(in) :: u, v\n real :: p\n\n ! The cross product as a signed scalar.\n p = (x (u) * y (v)) - (y (u) * x (v))\n end function cross\n\n subroutine sort_points (num_points, points)\n integer, intent(in) :: num_points\n complex, intent(inout) :: points(0:*)\n\n ! Sort first in ascending order by x-coordinates, then in\n ! ascending order by y-coordinates. Any decent sort algorithm will\n ! suffice; for the sake of interest, here is the Shell sort of\n ! https://en.wikipedia.org/w/index.php?title=Shellsort&oldid=1084744510\n\n integer, parameter :: gaps(1:8) = (/ 701, 301, 132, 57, 23, 10, 4, 1 /)\n\n integer :: i, j, k, gap, offset\n complex :: temp\n logical :: done\n\n do k = 1, 8\n gap = gaps(k)\n do offset = 0, gap - 1\n do i = offset, num_points - 1, gap\n temp = points(i)\n j = i\n done = .false.\n do while (.not. done)\n if (j < gap) then\n done = .true.\n else if (x (points(j - gap)) < x (temp)) then\n done = .true.\n else if (x (points(j - gap)) == x (temp) .and. &\n & (y (points(j - gap)) <= y (temp))) then\n done = .true.\n else\n points(j) = points(j - gap)\n j = j - gap\n end if\n end do\n points(j) = temp\n end do\n end do\n end do\n end subroutine sort_points\n\n subroutine delete_neighbor_duplicates (n, pt)\n integer, intent(inout) :: n\n complex, intent(inout) :: pt(0:*)\n\n call delete_trailing_duplicates\n call delete_nontrailing_duplicates\n\n contains\n\n subroutine delete_trailing_duplicates\n integer :: i\n logical :: done\n\n i = n - 1\n done = .false.\n do while (.not. done)\n if (i == 0) then\n n = 1\n done = .true.\n else if (pt(i - 1) /= pt(i)) then\n n = i + 1\n done = .true.\n else\n i = i - 1\n end if\n end do\n end subroutine delete_trailing_duplicates\n\n subroutine delete_nontrailing_duplicates\n integer :: i, j, num_deleted\n logical :: done\n\n i = 0\n do while (i < n - 1)\n j = i + 1\n done = .false.\n do while (.not. done)\n if (j == n) then\n done = .true.\n else if (pt(j) /= pt(i)) then\n done = .true.\n else\n j = j + 1\n end if\n end do\n if (j /= i + 1) then\n num_deleted = j - i - 1\n do while (j /= n)\n pt(j - num_deleted) = pt(j)\n j = j + 1\n end do\n n = n - num_deleted\n end if\n i = i + 1\n end do\n end subroutine delete_nontrailing_duplicates\n\n end subroutine delete_neighbor_duplicates\n\n subroutine construct_lower_hull (n, pt, hull_size, hull)\n integer, intent(in) :: n ! Number of points.\n complex, intent(in) :: pt(0:*)\n integer, intent(inout) :: hull_size\n complex, intent(inout) :: hull(0:*)\n\n integer :: i, j\n logical :: done\n\n j = 1\n hull(0:1) = pt(0:1)\n do i = 2, n - 1\n done = .false.\n do while (.not. done)\n if (j == 0) then\n j = j + 1\n hull(j) = pt(i)\n done = .true.\n else if (0.0 < cross (hull(j) - hull(j - 1), &\n & pt(i) - hull(j - 1))) then\n j = j + 1\n hull(j) = pt(i)\n done = .true.\n else\n j = j - 1\n end if\n end do\n end do\n hull_size = j + 1\n end subroutine construct_lower_hull\n\n subroutine construct_upper_hull (n, pt, hull_size, hull)\n integer, intent(in) :: n ! Number of points.\n complex, intent(in) :: pt(0:*)\n integer, intent(inout) :: hull_size\n complex, intent(inout) :: hull(0:*)\n\n integer :: i, j\n logical :: done\n\n j = 1\n hull(0:1) = pt(n - 1 : n - 2 : -1)\n do i = n - 3, 0, -1\n done = .false.\n do while (.not. done)\n if (j == 0) then\n j = j + 1\n hull(j) = pt(i)\n done = .true.\n else if (0.0 < cross (hull(j) - hull(j - 1), &\n & pt(i) - hull(j - 1))) then\n j = j + 1\n hull(j) = pt(i)\n done = .true.\n else\n j = j - 1\n end if\n end do\n end do\n hull_size = j + 1\n end subroutine construct_upper_hull\n\n subroutine contruct_hull (n, pt, hull_size, hull)\n integer, intent(in) :: n ! Number of points.\n complex, intent(in) :: pt(0:*)\n integer, intent(inout) :: hull_size\n complex, intent(inout) :: hull(0:*)\n\n integer :: lower_hull_size, upper_hull_size\n complex :: lower_hull(0 : n - 1), upper_hull(0 : n - 1)\n integer :: ihull0\n\n ihull0 = lbound (hull, 1)\n\n ! A side note: the calls to construct_lower_hull and\n ! construct_upper_hull could be done in parallel.\n call construct_lower_hull (n, pt, lower_hull_size, lower_hull)\n call construct_upper_hull (n, pt, upper_hull_size, upper_hull)\n\n hull_size = lower_hull_size + upper_hull_size - 2\n\n hull(:ihull0 + lower_hull_size - 2) = &\n & lower_hull(:lower_hull_size - 2)\n hull(ihull0 + lower_hull_size - 1 : ihull0 + hull_size - 1) = &\n & upper_hull(0 : upper_hull_size - 2)\n end subroutine contruct_hull\n\n subroutine find_convex_hull (n, points, hull_size, hull)\n integer, intent(in) :: n ! Number of points.\n complex, intent(in) :: points(*) ! Input points.\n integer, intent(inout) :: hull_size ! The size of the hull.\n complex, intent(inout) :: hull(*) ! Points of the hull.\n\n !\n ! Yes, you can call this with something like\n !\n ! call find_convex_hull (n, points, n, points)\n !\n ! and in the program below I shall demonstrate that.\n !\n\n complex :: pt(0 : n - 1)\n integer :: ipoints0, ihull0, numpt\n\n ipoints0 = lbound (points, 1)\n ihull0 = lbound (hull, 1)\n\n pt = points(:ipoints0 + n - 1)\n numpt = n\n\n call sort_points (numpt, pt)\n call delete_neighbor_duplicates (numpt, pt)\n\n if (numpt == 0) then\n hull_size = 0\n else if (numpt <= 2) then\n hull_size = numpt\n hull(:ihull0 + numpt - 1) = pt(:numpt - 1)\n else\n call contruct_hull (numpt, pt, hull_size, hull)\n end if\n end subroutine find_convex_hull\n\nend module convex_hulls\n\nprogram convex_hull_task\n use, non_intrinsic :: convex_hulls\n implicit none\n\n complex, parameter :: example_points(20) = &\n & (/ (16, 3), (12, 17), (0, 6), (-4, -6), (16, 6), &\n & (16, -7), (16, -3), (17, -4), (5, 19), (19, -8), &\n & (3, 16), (12, 13), (3, -4), (17, 5), (-3, 15), &\n & (-3, -9), (0, 11), (-9, -3), (-4, -2), (12, 10) /)\n\n integer :: n, i\n complex :: points(0:100)\n character(len = 100) :: fmt\n\n n = 20\n points(1:n) = example_points\n call find_convex_hull (n, points(1:n), n, points(1:n))\n\n write (fmt, '(\"(\", I20, ''(\"(\", F3.0, 1X, F3.0, \") \")'', \")\")') n\n write (*, fmt) (points(i), i = 1, n)\n\nend program convex_hull_task\n", "language": "Fortran" }, { "code": "#include \"crt.bi\"\nScreen 20\nWindow (-20,-20)-(30,30)\n\nType Point\n As Single x,y\n As Long done\nEnd Type\n\n#macro rotate(pivot,p,a,scale)\nType<Point>(scale*(Cos(a*.0174533)*(p.x-pivot.x)-Sin(a*.0174533)*(p.y-pivot.y))+pivot.x, _\nscale*(Sin(a*.0174533)*(p.x-pivot.x)+Cos(a*.0174533)*(p.y-pivot.y))+pivot.y)\n#endmacro\n\n\nDim As Point p(1 To ...)={(16,3),(12,17),(0,6),(-4,-6),(16,6),(16,-7),(16,-3),(17,-4),(5,19), _\n(19,-8),(3,16),(12,13),(3,-4),(17,5),(-3,15),(-3,-9),(0,11),(-9,-3),(-4,-2),(12,10)}\n\n\nFunction south(p() As Point,Byref idx As Long) As Point\n Dim As Point s=Type(0,100)\n For n As Long=Lbound(p) To Ubound(p)\n Circle(p(n).x,p(n).y),.2,7,,,,f\n If s.y>p(n).y Then s=p(n):idx=n\n Next n\n Return s\nEnd Function\n\nFunction segment_distance(lx1 As Single, _\n ly1 As Single, _\n lx2 As Single, _\n ly2 As Single, _\n px As Single,_\n py As Single, _\n Byref ox As Single=0,_\n Byref oy As Single=0) As Single\n Dim As Single M1,M2,C1,C2,B\n B=(Lx2-Lx1):If B=0 Then B=1e-20\n M2=(Ly2-Ly1)/B:If M2=0 Then M2=1e-20\n M1=-1/M2\n C1=py-M1*px\n C2=(Ly1*Lx2-Lx1*Ly2)/B\n Var L1=((px-lx1)*(px-lx1)+(py-ly1)*(py-ly1)),L2=((px-lx2)*(px-lx2)+(py-ly2)*(py-ly2))\n Var a=((lx1-lx2)*(lx1-lx2) + (ly1-ly2)*(ly1-ly2))\n Var a1=a+L1\n Var a2=a+L2\n Var f1=a1>L2,f2=a2>L1\n If f1 Xor f2 Then\n Var d1=((px-Lx1)*(px-Lx1)+(py-Ly1)*(py-Ly1))\n Var d2=((px-Lx2)*(px-Lx2)+(py-Ly2)*(py-Ly2))\n If d1<d2 Then Ox=Lx1:Oy=Ly1 : Return Sqr(d1) Else Ox=Lx2:Oy=Ly2:Return Sqr(d2)\n End If\n Var M=M1-M2:If M=0 Then M=1e-20\n Ox=(C2-C1)/(M1-M2)\n Oy=(M1*C2-M2*C1)/M\n Return Sqr((px-Ox)*(px-Ox)+(py-Oy)*(py-Oy))\nEnd Function\n\n\nDim As Long idx\nVar s= south(p(),idx)\np(idx).done=1\nRedim As Point ans(1 To 1)\nans(1)=s\nDim As Point e=s\ne.x=1000\nDim As Long count=1\nDim As Single z\nCircle(s.x,s.y),.4,5\n\nDo\n z+=.05\n Var pt=rotate(s,e,z,1)\n For n As Long=Lbound(p) To Ubound(p)\n If segment_distance(s.x,s.y,pt.x,pt.y,p(n).x,p(n).y)<.05 Then\n s=p(n)\n If p(n).done=0 Then\n count+=1\n Redim Preserve ans(1 To count)\n ans(count)=p(n)\n p(n).done=1\n End If\n End If\n Circle(s.x,s.y),.4,5\n Next n\nLoop Until z>360\n\nFor n As Long=Lbound(ans) To Ubound(ans)\n printf (!\"(%2.0f , %2.0f )\\n\", ans(n).x, ans(n).y)\nNext\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"sort\"\n)\n\n\n// ConvexHull returns the set of points that define the\n// convex hull of p in CCW order starting from the left most.\nfunc (p points) ConvexHull() points {\n\t// From https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain\n\t// with only minor deviations.\n\tsort.Sort(p)\n\tvar h points\n\n\t// Lower hull\n\tfor _, pt := range p {\n\t\tfor len(h) >= 2 && !ccw(h[len(h)-2], h[len(h)-1], pt) {\n\t\t\th = h[:len(h)-1]\n\t\t}\n\t\th = append(h, pt)\n\t}\n\n\t// Upper hull\n\tfor i, t := len(p)-2, len(h)+1; i >= 0; i-- {\n\t\tpt := p[i]\n\t\tfor len(h) >= t && !ccw(h[len(h)-2], h[len(h)-1], pt) {\n\t\t\th = h[:len(h)-1]\n\t\t}\n\t\th = append(h, pt)\n\t}\n\n\treturn h[:len(h)-1]\n}\n\n// ccw returns true if the three points make a counter-clockwise turn\nfunc ccw(a, b, c image.Point) bool {\n\treturn ((b.X - a.X) * (c.Y - a.Y)) > ((b.Y - a.Y) * (c.X - a.X))\n}\n\ntype points []image.Point\n\nfunc (p points) Len() int { return len(p) }\nfunc (p points) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p points) Less(i, j int) bool {\n\tif p[i].X == p[j].X {\n\t\treturn p[i].Y < p[i].Y\n\t}\n\treturn p[i].X < p[j].X\n}\n\nfunc main() {\n\tpts := points{\n\t\t{16, 3}, {12, 17}, {0, 6}, {-4, -6}, {16, 6},\n\t\t{16, -7}, {16, -3}, {17, -4}, {5, 19}, {19, -8},\n\t\t{3, 16}, {12, 13}, {3, -4}, {17, 5}, {-3, 15},\n\t\t{-3, -9}, {0, 11}, {-9, -3}, {-4, -2}, {12, 10},\n\t}\n\thull := pts.ConvexHull()\n\tfmt.Println(\"Convex Hull:\", hull)\n}\n", "language": "Go" }, { "code": "class ConvexHull {\n private static class Point implements Comparable<Point> {\n private int x, y\n\n Point(int x, int y) {\n this.x = x\n this.y = y\n }\n\n @Override\n int compareTo(Point o) {\n return Integer.compare(x, o.x)\n }\n\n @Override\n String toString() {\n return String.format(\"(%d, %d)\", x, y)\n }\n }\n\n private static List<Point> convexHull(List<Point> p) {\n if (p.isEmpty()) return Collections.emptyList()\n p.sort(new Comparator<Point>() {\n @Override\n int compare(Point o1, Point o2) {\n return o1 <=> o2\n }\n })\n List<Point> h = new ArrayList<>()\n\n // lower hull\n for (Point pt : p) {\n while (h.size() >= 2 && !ccw(h.get(h.size() - 2), h.get(h.size() - 1), pt)) {\n h.remove(h.size() - 1)\n }\n h.add(pt)\n }\n\n // upper hull\n int t = h.size() + 1\n for (int i = p.size() - 1; i >= 0; i--) {\n Point pt = p.get(i)\n while (h.size() >= t && !ccw(h.get(h.size() - 2), h.get(h.size() - 1), pt)) {\n h.remove(h.size() - 1)\n }\n h.add(pt)\n }\n\n h.remove(h.size() - 1)\n return h\n }\n\n // ccw returns true if the three points make a counter-clockwise turn\n private static boolean ccw(Point a, Point b, Point c) {\n return ((b.x - a.x) * (c.y - a.y)) > ((b.y - a.y) * (c.x - a.x))\n }\n\n static void main(String[] args) {\n List<Point> points = Arrays.asList(new Point(16, 3),\n new Point(12, 17),\n new Point(0, 6),\n new Point(-4, -6),\n new Point(16, 6),\n\n new Point(16, -7),\n new Point(16, -3),\n new Point(17, -4),\n new Point(5, 19),\n new Point(19, -8),\n\n new Point(3, 16),\n new Point(12, 13),\n new Point(3, -4),\n new Point(17, 5),\n new Point(-3, 15),\n\n new Point(-3, -9),\n new Point(0, 11),\n new Point(-9, -3),\n new Point(-4, -2),\n new Point(12, 10))\n\n List<Point> hull = convexHull(points)\n println(\"Convex Hull: $hull\")\n }\n}\n", "language": "Groovy" }, { "code": "import Data.List (sortBy, groupBy, maximumBy)\nimport Data.Ord (comparing)\n\n(x, y) = ((!! 0), (!! 1))\n\ncompareFrom\n :: (Num a, Ord a)\n => [a] -> [a] -> [a] -> Ordering\ncompareFrom o l r =\n compare ((x l - x o) * (y r - y o)) ((y l - y o) * (x r - x o))\n\ndistanceFrom\n :: Floating a\n => [a] -> [a] -> a\ndistanceFrom from to = ((x to - x from) ** 2 + (y to - y from) ** 2) ** (1 / 2)\n\nconvexHull\n :: (Floating a, Ord a)\n => [[a]] -> [[a]]\nconvexHull points =\n let o = minimum points\n presorted = sortBy (compareFrom o) (filter (/= o) points)\n collinears = groupBy (((EQ ==) .) . compareFrom o) presorted\n outmost = maximumBy (comparing (distanceFrom o)) <$> collinears\n in dropConcavities [o] outmost\n\ndropConcavities\n :: (Num a, Ord a)\n => [[a]] -> [[a]] -> [[a]]\ndropConcavities (left:lefter) (right:righter:rightest) =\n case compareFrom left right righter of\n LT -> dropConcavities (right : left : lefter) (righter : rightest)\n EQ -> dropConcavities (left : lefter) (righter : rightest)\n GT -> dropConcavities lefter (left : righter : rightest)\ndropConcavities output lastInput = lastInput ++ output\n\nmain :: IO ()\nmain =\n mapM_ print $\n convexHull\n [ [16, 3]\n , [12, 17]\n , [0, 6]\n , [-4, -6]\n , [16, 6]\n , [16, -7]\n , [16, -3]\n , [17, -4]\n , [5, 19]\n , [19, -8]\n , [3, 16]\n , [12, 13]\n , [3, -4]\n , [17, 5]\n , [-3, 15]\n , [-3, -9]\n , [0, 11]\n , [-9, -3]\n , [-4, -2]\n , [12, 10]\n ]\n", "language": "Haskell" }, { "code": "typedef Point = {x:Float, y:Float};\n\nclass Main {\n\n // Calculate orientation for 3 points\n // 0 -> Straight line\n // 1 -> Clockwise\n // 2 -> Counterclockwise\n static function orientation(pt1:Point, pt2:Point, pt3:Point): Int\n {\n var val = ((pt2.x - pt1.x) * (pt3.y - pt1.y)) -\n ((pt2.y - pt1.y) * (pt3.x - pt1.x));\n if (val == 0)\n return 0;\n else if (val > 0)\n return 1;\n else return 2;\n }\n\n static function convexHull(pts:Array<Point>):Array<Point> {\n var result = new Array<Point>();\n\n // There must be at least 3 points\n if (pts.length < 3)\n for (i in pts) result.push(i);\n\n // Find the leftmost point\n var indexMinX = 0;\n for (i in 0...(pts.length - 1))\n if (pts[i].x < pts[indexMinX].x)\n indexMinX = i;\n\n var p = indexMinX;\n var q = 0;\n\n while (true) {\n // The leftmost point must be part of the hull.\n result.push(pts[p]);\n\n q = (p + 1) % pts.length;\n\n for (i in 0...(pts.length - 1))\n if (orientation(pts[p], pts[i], pts[q]) == 2) q = i;\n\n p = q;\n\n // Break from loop once we reach the first point again.\n if (p == indexMinX)\n break;\n }\n return result;\n }\n\n static function main() {\n var pts = new Array<Point>();\n pts.push({x: 16, y: 3});\n pts.push({x: 12, y: 17});\n pts.push({x: 0, y: 6});\n pts.push({x: -4, y: -6});\n pts.push({x: 16, y: 6});\n\n pts.push({x: 16, y: -7});\n pts.push({x: 16, y: -3});\n pts.push({x: 17, y: -4});\n pts.push({x: 5, y: 19});\n pts.push({x: 19, y: -8});\n\n pts.push({x: 3, y: 16});\n pts.push({x: 12, y: 13});\n pts.push({x: 3, y: -4});\n pts.push({x: 17, y: 5});\n pts.push({x: -3, y: 15});\n\n pts.push({x: -3, y: -9});\n pts.push({x: 0, y: 11});\n pts.push({x: -9, y: -3});\n pts.push({x: -4, y: -2});\n pts.push({x: 12, y: 10});\n\n var hull = convexHull(pts);\n Sys.print('Convex Hull: [');\n var length = hull.length;\n var i = 0;\n while (length > 0) {\n if (i > 0)\n Sys.print(', ');\n Sys.print('(${hull[i].x}, ${hull[i].y})');\n length--;\n i++;\n }\n Sys.println(']');\n }\n}\n", "language": "Haxe" }, { "code": "#\n# Convex hulls by Andrew's monotone chain algorithm.\n#\n# For a description of the algorithm, see\n# https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169\n#\n\nrecord PlanePoint (x, y)\n\n######################################################################\n#\n# Merge sort adapted from the Object Icon IPL (public domain code).\n#\n\n# A merge sort implementation. This returns a sorted copy, leaving the\n# original unchanged.\n#\n# :Parameters :\n# : `l` - the list to sort\n# : `cmp` - a comparator function\n#\nprocedure mergesort (l, cmp)\n return mergesort1 (l, cmp, 1, *l)\nend\n\nprocedure mergesort1 (l, cmp, first, last)\n local l1, l2, l3, m, v1\n if last <= first then\n return l[first:last + 1]\n m := (first + last) / 2\n l1 := mergesort1 (l, cmp, first, m)\n l2 := mergesort1 (l, cmp, m + 1, last)\n l3 := []\n every v1 := !l1 do {\n while cmp (v1, l2[1]) > 0 do\n put (l3, get(l2))\n put (l3, v1)\n }\n every put(l3, !l2)\n return l3\nend\n\n######################################################################\n\nprocedure point_equals (p, q)\n if p.x = q.x & p.y = q.y then return else fail\nend\n\n# Impose a total order on points, making it one that will work for\n# Andrew's monotone chain algorithm. *)\nprocedure point_comes_before (p, q)\n if (p.x < q.x) | (p.x = q.x & p.y < q.y) then return else fail\nend\n\n# Subtraction is really a vector or multivector operation.\nprocedure point_subtract (p, q)\n return PlanePoint (p.x - q.x, p.y - q.y)\nend\n\n# Cross product is really a multivector operation.\nprocedure point_cross (p, q)\n return (p.x * q.y) - (p.y * q.x)\nend\n\nprocedure point_to_string (p)\n return \"(\" || string (p.x) || \" \" || string (p.y) || \")\"\nend\n\n######################################################################\n\n# Comparison like C's strcmp(3).\nprocedure compare_points (p, q)\n local cmp\n\n if point_comes_before (p, q) then\n cmp := -1\n else if point_comes_before (q, p) then\n cmp := 1\n else\n cmp := 0\n return cmp\nend\n\nprocedure sort_points (points)\n # Non-destructive sort.\n return mergesort (points, compare_points)\nend\n\nprocedure delete_neighbor_dups (arr, equals)\n local arr1, i\n\n if *arr = 0 then {\n arr1 := []\n } else {\n arr1 := [arr[1]]\n i := 2\n while i <= *arr do {\n if not (equals (arr[i], arr1[-1])) then\n put (arr1, arr[i])\n i +:= 1\n }\n }\n return arr1\nend\n\nprocedure construct_lower_hull (pt)\n local hull, i, j\n\n hull := list (*pt)\n hull[1] := pt[1]\n hull[2] := pt[2]\n j := 2\n every i := 3 to *pt do {\n while (j ~= 1 &\n point_cross (point_subtract (hull[j], hull[j - 1]),\n point_subtract (pt[i], hull[j - 1])) <= 0) do j -:= 1\n j +:= 1\n hull[j] := pt[i]\n }\n return hull[1 : j + 1]\nend\n\nprocedure construct_upper_hull (pt)\n local hull, i, j\n\n hull := list (*pt)\n hull[1] := pt[-1]\n hull[2] := pt[-2]\n j := 2\n every i := 3 to *pt do {\n while (j ~= 1 &\n point_cross (point_subtract (hull[j], hull[j - 1]),\n point_subtract (pt[-i], hull[j - 1])) <= 0) do j -:= 1\n j +:= 1\n hull[j] := pt[-i]\n }\n return hull[1 : j + 1]\nend\n\nprocedure construct_hull (pt)\n local lower_hull, upper_hull\n\n lower_hull := construct_lower_hull (pt)\n upper_hull := construct_upper_hull (pt)\n return lower_hull[1 : -1] ||| upper_hull [1 : -1]\nend\n\nprocedure find_convex_hull (points)\n local pt, hull\n\n if *points = 0 then {\n hull := []\n } else {\n pt := delete_neighbor_dups (sort_points (points), point_equals)\n if *pt <= 2 then {\n hull := pt\n } else {\n hull := construct_hull (pt)\n }\n }\n return hull\nend\n\nprocedure main ()\n local example_points, hull\n\n example_points :=\n [PlanePoint (16.0, 3.0),\n PlanePoint (12.0, 17.0),\n PlanePoint (0.0, 6.0),\n PlanePoint (-4.0, -6.0),\n PlanePoint (16.0, 6.0),\n PlanePoint (16.0, -7.0),\n PlanePoint (16.0, -3.0),\n PlanePoint (17.0, -4.0),\n PlanePoint (5.0, 19.0),\n PlanePoint (19.0, -8.0),\n PlanePoint (3.0, 16.0),\n PlanePoint (12.0, 13.0),\n PlanePoint (3.0, -4.0),\n PlanePoint (17.0, 5.0),\n PlanePoint (-3.0, 15.0),\n PlanePoint (-3.0, -9.0),\n PlanePoint (0.0, 11.0),\n PlanePoint (-9.0, -3.0),\n PlanePoint (-4.0, -2.0),\n PlanePoint (12.0, 10.0)]\n\n hull := find_convex_hull (example_points)\n\n every write (point_to_string (!hull))\nend\n\n######################################################################\n", "language": "Icon" }, { "code": "counterclockwise =: ({. , }. /: 12 o. }. - {.) @ /:~\ncrossproduct =: 11 o. [: (* +)/ }. - {.\nremoveinner =: #~ (1 , (0 > 3 crossproduct\\ ]) , 1:)\nhull =: [: removeinner^:_ counterclockwise\n", "language": "J" }, { "code": " hull 16j3 12j17 0j6 _4j_6 16j6 16j_7 16j_3 17j_4 5j19 19j_8 3j16 12j13 3j_4 17j5 _3j15 _3j_9 0j11 _9j_3 _4j_2 12j10\n_9j_3 _3j_9 19j_8 17j5 12j17 5j19 _3j15\n\n ] A =: ~. 20 2 ?.@$ 9\n0 2\n1 3\n2 1\n4 1\n8 7\n3 5\n4 8\n7 5\n6 1\n2 6\n1 7\n0 1\n6 8\n4 0\n8 6\n7 6\n5 8\n0 4\n5 3\n hull&.:(+.inv\"1) A\n0 1\n4 0\n6 1\n8 6\n8 7\n6 8\n4 8\n1 7\n0 4\n", "language": "J" }, { "code": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\nimport static java.util.Collections.emptyList;\n\npublic class ConvexHull {\n private static class Point implements Comparable<Point> {\n private int x, y;\n\n public Point(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n @Override\n public int compareTo(Point o) {\n return Integer.compare(x, o.x);\n }\n\n @Override\n public String toString() {\n return String.format(\"(%d, %d)\", x, y);\n }\n }\n\n private static List<Point> convexHull(List<Point> p) {\n if (p.isEmpty()) return emptyList();\n p.sort(Point::compareTo);\n List<Point> h = new ArrayList<>();\n\n // lower hull\n for (Point pt : p) {\n while (h.size() >= 2 && !ccw(h.get(h.size() - 2), h.get(h.size() - 1), pt)) {\n h.remove(h.size() - 1);\n }\n h.add(pt);\n }\n\n // upper hull\n int t = h.size() + 1;\n for (int i = p.size() - 1; i >= 0; i--) {\n Point pt = p.get(i);\n while (h.size() >= t && !ccw(h.get(h.size() - 2), h.get(h.size() - 1), pt)) {\n h.remove(h.size() - 1);\n }\n h.add(pt);\n }\n\n h.remove(h.size() - 1);\n return h;\n }\n\n // ccw returns true if the three points make a counter-clockwise turn\n private static boolean ccw(Point a, Point b, Point c) {\n return ((b.x - a.x) * (c.y - a.y)) > ((b.y - a.y) * (c.x - a.x));\n }\n\n public static void main(String[] args) {\n List<Point> points = Arrays.asList(new Point(16, 3),\n new Point(12, 17),\n new Point(0, 6),\n new Point(-4, -6),\n new Point(16, 6),\n\n new Point(16, -7),\n new Point(16, -3),\n new Point(17, -4),\n new Point(5, 19),\n new Point(19, -8),\n\n new Point(3, 16),\n new Point(12, 13),\n new Point(3, -4),\n new Point(17, 5),\n new Point(-3, 15),\n\n new Point(-3, -9),\n new Point(0, 11),\n new Point(-9, -3),\n new Point(-4, -2),\n new Point(12, 10));\n\n List<Point> hull = convexHull(points);\n System.out.printf(\"Convex Hull: %s\\n\", hull);\n }\n}\n", "language": "Java" }, { "code": "function convexHull(points) {\n points.sort(comparison);\n var L = [];\n for (var i = 0; i < points.length; i++) {\n while (L.length >= 2 && cross(L[L.length - 2], L[L.length - 1], points[i]) <= 0) {\n L.pop();\n }\n L.push(points[i]);\n }\n var U = [];\n for (var i = points.length - 1; i >= 0; i--) {\n while (U.length >= 2 && cross(U[U.length - 2], U[U.length - 1], points[i]) <= 0) {\n U.pop();\n }\n U.push(points[i]);\n }\n L.pop();\n U.pop();\n return L.concat(U);\n}\n\nfunction comparison(a, b) {\n return a.x == b.x ? a.y - b.y : a.x - b.x;\n}\n\nfunction cross(a, b, o) {\n return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n}\n", "language": "JavaScript" }, { "code": "var points = [];\nvar hull = [];\n\nfunction setup() {\n createCanvas(1132, 700);\n frameRate(10);\n\n strokeWeight(4);\n stroke(220);\n}\n\nfunction draw() {\n background(40);\n // draw points\n for (i = 0; i < points.length; i++) {\n point(points[i].x, points[i].y);\n };\n console.log(hull);\n // draw hull\n noFill();\n beginShape();\n for (i = 0; i < hull.length; i++) {\n vertex(hull[i].x, hull[i].y);\n };\n endShape(CLOSE);\n}\n\nfunction mouseClicked() {\n points.push(createVector(mouseX, mouseY));\n hull = convexHull(points);\n noFill();\n //console.log(hull);\n beginShape();\n for (var i = 0; i < hull.length; i++) {\n vertex(hull[i].x, hull[i].y);\n }\n endShape(CLOSE);\n return false;\n}\n\n// https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain\nfunction convexHull(points) {\n points.sort(comparison);\n var L = [];\n for (var i = 0; i < points.length; i++) {\n while (L.length >= 2 && cross(L[L.length - 2], L[L.length - 1], points[i]) <= 0) {\n L.pop();\n }\n L.push(points[i]);\n }\n var U = [];\n for (var i = points.length - 1; i >= 0; i--) {\n while (U.length >= 2 && cross(U[U.length - 2], U[U.length - 1], points[i]) <= 0) {\n U.pop();\n }\n U.push(points[i]);\n }\n L.pop();\n U.pop();\n return L.concat(U);\n}\n\nfunction comparison(a, b) {\n return a.x == b.x ? a.y - b.y : a.x - b.x;\n}\n\nfunction cross(a, b, o) {\n return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n}\n", "language": "JavaScript" }, { "code": "<html>\n\n<head>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.js\"></script>\n <script src=\"convexhull.js\"></script>\n</head>\n\n<body>\n <table>\n <tr>\n <th><h1>Convex Hull</h4></th>\n <th><h4>Left mouse: Add points</h6></th>\n </tr>\n </table>\n\n</body>\n\n</html>\n", "language": "JavaScript" }, { "code": "# ccw returns true if the three points make a counter-clockwise turn\ndef ccw(a; b; c):\n a as [$ax, $ay]\n | b as [$bx, $by]\n | c as [$cx, $cy]\n | (($bx - $ax) * ($cy - $ay)) > (($by - $ay) * ($cx - $ax)) ;\n\ndef convexHull:\n if . == [] then []\n else sort as $pts\n # lower hull:\n | reduce $pts[] as $pt ([];\n until (length < 2 or ccw(.[-2]; .[-1]; $pt); .[:-1] )\n | . + [$pt] )\n # upper hull\n | (length + 1) as $t\n | reduce range($pts|length-2; -1; -1) as $i (.;\n $pts[$i] as $pt\n | until (length < $t or ccw(.[-2]; .[-1]; $pt); .[:-1] )\n | . + [$pt])\n | .[:-1]\n end ;\n", "language": "Jq" }, { "code": "def pts: [\n [16, 3], [12, 17], [ 0, 6], [-4, -6], [16, 6],\n [16, -7], [16, -3], [17, -4], [ 5, 19], [19, -8],\n [ 3, 16], [12, 13], [ 3, -4], [17, 5], [-3, 15],\n [-3, -9], [ 0, 11], [-9, -3], [-4, -2], [12, 10]\n];\n\n\"Convex Hull: \\(pts|convexHull)\"\n", "language": "Jq" }, { "code": "# v1.0.4\n# https://github.com/JuliaPolyhedra/Polyhedra.jl/blob/master/examples/operations.ipynb\nusing Polyhedra, CDDLib\n\nA = vrep([[16,3], [12,17], [0,6], [-4,-6], [16,6], [16,-7], [16,-3], [17,-4], [5,19], [19,-8], [3,16], [12,13], [3,-4], [17,5], [-3,15], [-3,-9], [0,11], [-9,-3], [-4,-2], [12,10]])\nP = polyhedron(A, CDDLib.Library())\nPch = convexhull(P, P)\nremovevredundancy!(Pch)\nprintln(\"$Pch\")\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nclass Point(val x: Int, val y: Int) : Comparable<Point> {\n\n override fun compareTo(other: Point) = this.x.compareTo(other.x)\n\n override fun toString() = \"($x, $y)\"\n}\n\nfun convexHull(p: Array<Point>): List<Point> {\n if (p.isEmpty()) return emptyList()\n p.sort()\n val h = mutableListOf<Point>()\n\n // lower hull\n for (pt in p) {\n while (h.size >= 2 && !ccw(h[h.size - 2], h.last(), pt)) {\n h.removeAt(h.lastIndex)\n }\n h.add(pt)\n }\n\n // upper hull\n val t = h.size + 1\n for (i in p.size - 2 downTo 0) {\n val pt = p[i]\n while (h.size >= t && !ccw(h[h.size - 2], h.last(), pt)) {\n h.removeAt(h.lastIndex)\n }\n h.add(pt)\n }\n\n h.removeAt(h.lastIndex)\n return h\n}\n\n/* ccw returns true if the three points make a counter-clockwise turn */\nfun ccw(a: Point, b: Point, c: Point) =\n ((b.x - a.x) * (c.y - a.y)) > ((b.y - a.y) * (c.x - a.x))\n\nfun main(args: Array<String>) {\n val points = arrayOf(\n Point(16, 3), Point(12, 17), Point( 0, 6), Point(-4, -6), Point(16, 6),\n Point(16, -7), Point(16, -3), Point(17, -4), Point( 5, 19), Point(19, -8),\n Point( 3, 16), Point(12, 13), Point( 3, -4), Point(17, 5), Point(-3, 15),\n Point(-3, -9), Point( 0, 11), Point(-9, -3), Point(-4, -2), Point(12, 10)\n )\n val hull = convexHull(points)\n println(\"Convex Hull: $hull\")\n}\n", "language": "Kotlin" }, { "code": "function print_point(p)\n io.write(\"(\"..p.x..\", \"..p.y..\")\")\n return nil\nend\n\nfunction print_points(pl)\n io.write(\"[\")\n for i,p in pairs(pl) do\n if i>1 then\n io.write(\", \")\n end\n print_point(p)\n end\n io.write(\"]\")\n return nil\nend\n\nfunction ccw(a,b,c)\n return (b.x - a.x) * (c.y - a.y) > (b.y - a.y) * (c.x - a.x)\nend\n\nfunction pop_back(ta)\n table.remove(ta,#ta)\n return ta\nend\n\nfunction convexHull(pl)\n if #pl == 0 then\n return {}\n end\n table.sort(pl, function(left,right)\n return left.x < right.x\n end)\n\n local h = {}\n\n -- lower hull\n for i,pt in pairs(pl) do\n while #h >= 2 and not ccw(h[#h-1], h[#h], pt) do\n table.remove(h,#h)\n end\n table.insert(h,pt)\n end\n\n -- upper hull\n local t = #h + 1\n for i=#pl, 1, -1 do\n local pt = pl[i]\n while #h >= t and not ccw(h[#h-1], h[#h], pt) do\n table.remove(h,#h)\n end\n table.insert(h,pt)\n end\n\n table.remove(h,#h)\n return h\nend\n\n-- main\nlocal points = {\n {x=16,y= 3},{x=12,y=17},{x= 0,y= 6},{x=-4,y=-6},{x=16,y= 6},\n {x=16,y=-7},{x=16,y=-3},{x=17,y=-4},{x= 5,y=19},{x=19,y=-8},\n {x= 3,y=16},{x=12,y=13},{x= 3,y=-4},{x=17,y= 5},{x=-3,y=15},\n {x=-3,y=-9},{x= 0,y=11},{x=-9,y=-3},{x=-4,y=-2},{x=12,y=10}\n}\nlocal hull = convexHull(points)\n\nio.write(\"Convex Hull: \")\nprint_points(hull)\nprint()\n", "language": "Lua" }, { "code": "pts:=[[16,3],[12,17],[0,6],[-4,-6],[16,6],[16,-7],[16,-3],[17,-4],[5,19],[19,-8],\n[3,16],[12,13],[3,-4],[17,5],[-3,15],[-3,-9],[0,11],[-9,-3],[-4,-2],[12,10]]:\n\nwith(geometry):\nmap(coordinates,convexhull([seq(point(P||i,pts[i]),i=1..nops(pts))]));\n# [[-9, -3], [-3, -9], [19, -8], [17, 5], [12, 17], [5, 19], [-3, 15]]\n\nwith(ComputationalGeometry):\npts[ConvexHull(pts)];\n# [[12, 17], [5, 19], [-3, 15], [-9, -3], [-3, -9], [19, -8], [17, 5]]\n\nsimplex:-convexhull(pts);\n# [[-9, -3], [-3, -9], [19, -8], [17, 5], [12, 17], [5, 19], [-3, 15]]\n", "language": "Maple" }, { "code": "hullPoints[data_] := MeshCoordinates[ConvexHullMesh[data]];\nhullPoints[{{16, 3}, {12, 17}, {0, 6}, {-4, -6}, {16, 6}, {16, -7}, {16, -3}, {17, -4}, {5, 19}, {19, -8}, {3, 16}, {12, 13}, {3, -4}, {17, 5}, {-3, 15}, {-3, -9}, {0, 11}, {-9, -3}, {-4, -2}, {12, 10}}]\n", "language": "Mathematica" }, { "code": ":- module convex_hull_task.\n\n:- interface.\n:- import_module io.\n:- pred main(io, io).\n:- mode main(di, uo) is det.\n\n:- implementation.\n:- import_module exception.\n:- import_module float.\n:- import_module int.\n:- import_module list.\n:- import_module pair.\n:- import_module string.\n:- import_module version_array.\n\n%%--------------------------------------------------------------------\n\n%% fetch_items/3 for version_array, similar to the library function\n%% for regular array.\n:- func fetch_items(version_array(T), int, int) = list(T).\nfetch_items(Arr, I, J) = fetch_items_(Arr, I, J, []).\n\n:- func fetch_items_(version_array(T), int, int, list(T)) = list(T).\nfetch_items_(Arr, I, J, Lst0) = Lst :-\n if (J < I) then (Lst = Lst0)\n else (J1 = J - 1,\n Lst = fetch_items_(Arr, I, J1, [Arr^elem(J) | Lst0])).\n\n%%--------------------------------------------------------------------\n\n:- type point == pair(float).\n:- type point_list == list(point).\n:- type point_array == version_array(point).\n\n:- pred point_comes_before(point, point).\n:- mode point_comes_before(in, in) is semidet.\npoint_comes_before(P, Q) :-\n (fst(P) < fst(Q); fst(P) - fst(Q) = (0.0),\n snd(P) < snd(Q)).\n\n:- pred point_compare(point, point, comparison_result).\n:- mode point_compare(in, in, out) is det.\npoint_compare(P, Q, Cmp) :-\n if (point_comes_before(P, Q)) then (Cmp = (<))\n else if (point_comes_before(Q, P)) then (Cmp = (>))\n else (Cmp = (=)).\n\n:- func point_subtract(point, point) = point.\npoint_subtract(P, Q) = pair(fst(P) - fst(Q),\n snd(P) - snd(Q)).\n\n:- func point_cross_product(point, point) = float.\npoint_cross_product(P, Q) = (fst(P) * snd(Q)) - (snd(P) * fst(Q)).\n\n:- func point_to_string(point) = string.\npoint_to_string(P) = (\"(\" ++ from_float(fst(P)) ++\n \" \" ++ from_float(snd(P)) ++ \")\").\n\n%%--------------------------------------------------------------------\n\n:- func convex_hull(point_list) = point_list.\nconvex_hull(Pt) = Hull :-\n Pt1 = unique_points_sorted(Pt),\n (if (Pt1 = []; Pt1 = [_]; Pt1 = [_, _]) then (Hull = Pt1)\n else (Hull = construct_hull(Pt1))).\n\n:- func unique_points_sorted(point_list) = point_list.\nunique_points_sorted(Pt0) = Pt :-\n sort_and_remove_dups(point_compare, Pt0, Pt).\n\n:- func construct_hull(point_list) = point_list.\nconstruct_hull(Pt) = (construct_lower_hull(Pt) ++\n construct_upper_hull(Pt)).\n\n:- func construct_lower_hull(point_list) = point_list.\nconstruct_lower_hull(Pt) = Hull :-\n if (Pt = [P0, P1 | Rest])\n then (N = length(Pt),\n Arr0 = (version_array.init(N, P0)),\n Arr1 = (Arr0^elem(1) := P1),\n hull_construction(Rest, Arr1, Arr2, 1, N_Hull),\n %% In the fetch_items/3 call, we leave out the last item. It\n %% is redundant with the first item of the upper hull.\n N_Hull2 = N_Hull - 2,\n Hull = fetch_items(Arr2, 0, N_Hull2))\n else throw(\"construct_lower_hull expects list of length >= 3\").\n\n:- func construct_upper_hull(point_list) = point_list.\n%% An upper hull is merely a lower hull for points going the other\n%% way.\nconstruct_upper_hull(Pt) = construct_lower_hull(reverse(Pt)).\n\n:- pred hull_construction(point_list, point_array, point_array,\n int, int).\n:- mode hull_construction(in, in, out, in, out) is det.\nhull_construction([], Arr0, Arr, J, N_Hull) :-\n Arr = Arr0,\n N_Hull = J + 1.\nhull_construction([P | Rest], Arr0, Arr, J, N_Hull) :-\n if cross_test(P, Arr0, J)\n then (J1 = J + 1,\n Arr1 = (Arr0^elem(J1) := P),\n hull_construction(Rest, Arr1, Arr, J1, N_Hull))\n else (J1 = J - 1,\n hull_construction([P | Rest], Arr0, Arr, J1, N_Hull)).\n\n:- pred cross_test(point, point_array, int).\n:- mode cross_test(in, in, in) is semidet.\ncross_test(P, Arr, J) :-\n if (J = 0) then true\n else (Elem_J = Arr^elem(J),\n J1 = J - 1,\n Elem_J1 = Arr^elem(J1),\n 0.0 < point_cross_product(point_subtract(Elem_J, Elem_J1),\n point_subtract(P, Elem_J1))).\n\n%%--------------------------------------------------------------------\n\nmain(!IO) :-\n Example_points = [pair(16.0, 3.0),\n pair(12.0, 17.0),\n pair(0.0, 6.0),\n pair(-4.0, -6.0),\n pair(16.0, 6.0),\n pair(16.0, -7.0),\n pair(16.0, -3.0),\n pair(17.0, -4.0),\n pair(5.0, 19.0),\n pair(19.0, -8.0),\n pair(3.0, 16.0),\n pair(12.0, 13.0),\n pair(3.0, -4.0),\n pair(17.0, 5.0),\n pair(-3.0, 15.0),\n pair(-3.0, -9.0),\n pair(0.0, 11.0),\n pair(-9.0, -3.0),\n pair(-4.0, -2.0),\n pair(12.0, 10.0)],\n Hull = convex_hull(Example_points),\n HullStr = join_list(\" \", map(point_to_string, Hull)),\n write_string(HullStr, !IO),\n nl(!IO).\n\n%%%-------------------------------------------------------------------\n%%% local variables:\n%%% mode: mercury\n%%% prolog-indent-width: 2\n%%% end:\n", "language": "Mercury" }, { "code": "MODULE ConvexHull;\nFROM FormatString IMPORT FormatString;\nFROM Storage IMPORT ALLOCATE, DEALLOCATE;\nFROM SYSTEM IMPORT TSIZE;\nFROM Terminal IMPORT WriteString,WriteLn,ReadChar;\n\nPROCEDURE WriteInt(n : INTEGER);\nVAR buf : ARRAY[0..15] OF CHAR;\nBEGIN\n FormatString(\"%i\", buf, n);\n WriteString(buf);\nEND WriteInt;\n\nTYPE\n Point = RECORD\n x, y : INTEGER;\n END;\n\nPROCEDURE WritePoint(pt : Point);\nBEGIN\n WriteString(\"(\");\n WriteInt(pt.x);\n WriteString(\", \");\n WriteInt(pt.y);\n WriteString(\")\");\nEND WritePoint;\n\nTYPE\n NextNode = POINTER TO PNode;\n PNode = RECORD\n value : Point;\n next : NextNode;\n END;\n\nPROCEDURE WriteNode(it : NextNode);\nBEGIN\n IF it = NIL THEN\n RETURN\n END;\n WriteString(\"[\");\n\n WritePoint(it^.value);\n it := it^.next;\n\n WHILE it # NIL DO\n WriteString(\", \");\n WritePoint(it^.value);\n it := it^.next\n END;\n WriteString(\"]\")\nEND WriteNode;\n\nPROCEDURE AppendNode(pn : NextNode; p : Point) : NextNode;\nVAR it,nx : NextNode;\nBEGIN\n IF pn = NIL THEN\n ALLOCATE(it,TSIZE(PNode));\n it^.value := p;\n it^.next := NIL;\n RETURN it\n END;\n\n it := pn;\n WHILE it^.next # NIL DO\n it := it^.next\n END;\n\n ALLOCATE(nx,TSIZE(PNode));\n nx^.value := p;\n nx^.next := NIL;\n\n it^.next := nx;\n RETURN pn\nEND AppendNode;\n\nPROCEDURE DeleteNode(VAR pn : NextNode);\nBEGIN\n IF pn = NIL THEN RETURN END;\n DeleteNode(pn^.next);\n\n DEALLOCATE(pn,TSIZE(PNode));\n pn := NIL\nEND DeleteNode;\n\nPROCEDURE SortNode(VAR pn : NextNode);\nVAR\n it : NextNode;\n tmp : Point;\n done : BOOLEAN;\nBEGIN\n REPEAT\n done := TRUE;\n it := pn;\n WHILE (it # NIL) AND (it^.next # NIL) DO\n IF it^.next^.value.x < it^.value.x THEN\n tmp := it^.value;\n it^.value := it^.next^.value;\n it^.next^.value := tmp;\n done := FALSE\n END;\n it := it^.next;\n END\n UNTIL done;\nEND SortNode;\n\nPROCEDURE NodeLength(it : NextNode) : INTEGER;\nVAR length : INTEGER;\nBEGIN\n length := 0;\n WHILE it # NIL DO\n INC(length);\n it := it^.next;\n END;\n RETURN length\nEND NodeLength;\n\nPROCEDURE ReverseNode(fp : NextNode) : NextNode;\nVAR rp,tmp : NextNode;\nBEGIN\n IF fp = NIL THEN RETURN NIL END;\n\n ALLOCATE(tmp,TSIZE(PNode));\n tmp^.value := fp^.value;\n tmp^.next := NIL;\n rp := tmp;\n fp := fp^.next;\n\n WHILE fp # NIL DO\n ALLOCATE(tmp,TSIZE(PNode));\n tmp^.value := fp^.value;\n tmp^.next := rp;\n rp := tmp;\n fp := fp^.next;\n END;\n\n RETURN rp\nEND ReverseNode;\n\n(* ccw returns true if the three points make a counter-clockwise turn *)\nPROCEDURE CCW(a,b,c : Point) : BOOLEAN;\nBEGIN\n RETURN ((b.x - a.x) * (c.y - a.y)) > ((b.y - a.y) * (c.x - a.x))\nEND CCW;\n\nPROCEDURE ConvexHull(p : NextNode) : NextNode;\nVAR\n hull,it,h1,h2 : NextNode;\n t : INTEGER;\nBEGIN\n IF p = NIL THEN RETURN NIL END;\n SortNode(p);\n hull := NIL;\n\n (* lower hull *)\n it := p;\n WHILE it # NIL DO\n IF hull # NIL THEN\n WHILE hull^.next # NIL DO\n (* At least two points in the list *)\n h2 := hull;\n h1 := hull^.next;\n WHILE h1^.next # NIL DO\n h2 := h1;\n h1 := h2^.next;\n END;\n\n IF CCW(h2^.value, h1^.value, it^.value) THEN\n BREAK\n ELSE\n h2^.next := NIL;\n DeleteNode(h1);\n h1 := NIL\n END\n END\n END;\n\n hull := AppendNode(hull, it^.value);\n it := it^.next;\n END;\n\n (* upper hull *)\n t := NodeLength(hull) + 1;\n p := ReverseNode(p);\n it := p;\n WHILE it # NIL DO\n WHILE NodeLength(hull) >= t DO\n h2 := hull;\n h1 := hull^.next;\n WHILE h1^.next # NIL DO\n h2 := h1;\n h1 := h2^.next;\n END;\n\n IF CCW(h2^.value, h1^.value, it^.value) THEN\n BREAK\n ELSE\n h2^.next := NIL;\n DeleteNode(h1);\n h1 := NIL\n END\n END;\n\n hull := AppendNode(hull, it^.value);\n it := it^.next;\n END;\n DeleteNode(p);\n\n h2 := hull;\n h1 := h2^.next;\n WHILE h1^.next # NIL DO\n h2 := h1;\n h1 := h1^.next;\n END;\n h2^.next := NIL;\n DeleteNode(h1);\n RETURN hull\nEND ConvexHull;\n\n(* Main *)\nVAR nodes,hull : NextNode;\nBEGIN\n nodes := AppendNode(NIL, Point{16, 3});\n AppendNode(nodes, Point{12,17});\n AppendNode(nodes, Point{ 0, 6});\n AppendNode(nodes, Point{-4,-6});\n AppendNode(nodes, Point{16, 6});\n AppendNode(nodes, Point{16,-7});\n AppendNode(nodes, Point{16,-3});\n AppendNode(nodes, Point{17,-4});\n AppendNode(nodes, Point{ 5,19});\n AppendNode(nodes, Point{19,-8});\n AppendNode(nodes, Point{ 3,16});\n AppendNode(nodes, Point{12,13});\n AppendNode(nodes, Point{ 3,-4});\n AppendNode(nodes, Point{17, 5});\n AppendNode(nodes, Point{-3,15});\n AppendNode(nodes, Point{-3,-9});\n AppendNode(nodes, Point{ 0,11});\n AppendNode(nodes, Point{-9,-3});\n AppendNode(nodes, Point{-4,-2});\n AppendNode(nodes, Point{12,10});\n\n hull := ConvexHull(nodes);\n WriteNode(hull);\n DeleteNode(hull);\n\n DeleteNode(nodes);\n ReadChar\nEND ConvexHull.\n", "language": "Modula-2" }, { "code": "type\n Point = object\n x: float\n y: float\n\n# Calculate orientation for 3 points\n# 0 -> Straight line\n# 1 -> Clockwise\n# 2 -> Counterclockwise\nproc orientation(p, q, r: Point): int =\n let val = (q.y - p.y) * (r.x - q.x) -\n (q.x - p.x) * (r.y - q.y)\n\n if val == 0: 0\n elif val > 0: 1\n else: 2\n\nproc calculateConvexHull(points: openArray[Point]): seq[Point] =\n result = newSeq[Point]()\n\n # There must be at least 3 points\n if len(points) < 3:\n for i in points: result.add(i)\n\n # Find the leftmost point\n var indexMinX = 0\n for i, _ in points:\n if points[i].x < points[indexMinX].x:\n indexMinX = i\n\n var p = indexMinX\n var q = 0\n\n while true:\n # The leftmost point must be part of the hull.\n result.add(points[p])\n\n q = (p + 1) mod len(points)\n\n for i in 0..<len(points):\n if orientation(points[p], points[i], points[q]) == 2:\n q = i\n\n p = q\n\n # Break from loop once we reach the first point again\n if p == indexMinX:\n break\n\nvar points = @[Point(x: 16, y: 3),\n Point(x: 12, y: 17),\n Point(x: 0, y: 6),\n Point(x: -4, y: -6),\n Point(x: 16, y: 6),\n Point(x: 16, y: -7),\n Point(x: 17, y: -4),\n Point(x: 5, y: 19),\n Point(x: 19, y: -8),\n Point(x: 3, y: 16),\n Point(x: 12, y: 13),\n Point(x: 3, y: -4),\n Point(x: 17, y: 5),\n Point(x: -3, y: 15),\n Point(x: -3, y: -9),\n Point(x: 0, y: 11),\n Point(x: -9, y: -3),\n Point(x: -4, y: -2),\n Point(x: 12, y: 10)]\n\nlet hull = calculateConvexHull(points)\nfor i in hull:\n echo i\n", "language": "Nim" }, { "code": "# -*- ObjectIcon -*-\n#\n# Convex hulls by Andrew's monotone chain algorithm.\n#\n# For a description of the algorithm, see\n# https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169\n#\n\nimport io\nimport ipl.sort\n\nclass PlanePoint () # Enough plane geometry for our purpose.\n\n private readable x, y\n\n public new (x, y)\n self.x := x\n self.y := y\n return\n end\n\n public equals (other)\n if self.x = other.x & self.y = other.y then\n return\n else\n fail\n end\n\n # Impose a total order on points, making it one that will work for\n # Andrew's monotone chain algorithm. *)\n public comes_before (other)\n if (self.x < other.x) | (self.x = other.x & self.y < other.y) then\n return\n else\n fail\n end\n\n # Subtraction is really a vector or multivector operation.\n public minus (other)\n return PlanePoint (self.x - other.x, self.y - other.y)\n end\n\n # Cross product is really a multivector operation.\n public cross (other)\n return (self.x * other.y) - (self.y * other.x)\n end\n\n public to_string ()\n return \"(\" || string (self.x) || \" \" || string (self.y) || \")\"\n end\n\nend\n\n# Comparison like C's strcmp(3).\nprocedure compare_points (p, q)\n local cmp\n\n if p.comes_before (q) then\n cmp := -1\n else if q.comes_before (p) then\n cmp := 1\n else\n cmp := 0\n return cmp\nend\n\nprocedure sort_points (points)\n # Non-destructive sort.\n return mergesort (points, compare_points)\nend\n\nprocedure delete_neighbor_dups (arr, equals)\n local arr1, i\n\n if *arr = 0 then {\n arr1 := []\n } else {\n arr1 := [arr[1]]\n i := 2\n while i <= *arr do {\n unless equals (arr[i], arr1[-1]) then\n put (arr1, arr[i])\n i +:= 1\n }\n }\n return arr1\nend\n\nprocedure construct_lower_hull (pt)\n local hull, i, j\n\n hull := list (*pt)\n hull[1] := pt[1]\n hull[2] := pt[2]\n j := 2\n every i := 3 to *pt do {\n while (j ~= 1 &\n (hull[j].minus (hull[j - 1])).cross (pt[i].minus (hull[j - 1])) <= 0) do\n j -:= 1\n j +:= 1\n hull[j] := pt[i]\n }\n return hull[1 : j + 1]\nend\n\nprocedure construct_upper_hull (pt)\n local hull, i, j\n\n hull := list (*pt)\n hull[1] := pt[-1]\n hull[2] := pt[-2]\n j := 2\n every i := 3 to *pt do {\n while (j ~= 1 &\n (hull[j].minus (hull[j - 1])).cross (pt[-i].minus (hull[j - 1])) <= 0) do\n j -:= 1\n j +:= 1\n hull[j] := pt[-i]\n }\n return hull[1 : j + 1]\nend\n\nprocedure construct_hull (pt)\n local lower_hull, upper_hull\n\n lower_hull := construct_lower_hull (pt)\n upper_hull := construct_upper_hull (pt)\n return lower_hull[1 : -1] ||| upper_hull [1 : -1]\nend\n\nprocedure points_equal (p, q)\n if p.equals (q) then\n return\n else\n fail\nend\n\nprocedure find_convex_hull (points)\n local pt, hull\n\n if *points = 0 then {\n hull := []\n } else {\n pt := delete_neighbor_dups (sort_points (points), points_equal)\n if *pt <= 2 then\n hull := pt\n else\n hull := construct_hull (pt)\n }\n return hull\nend\n\nprocedure main ()\n local example_points, hull\n\n example_points :=\n [PlanePoint (16.0, 3.0),\n PlanePoint (12.0, 17.0),\n PlanePoint (0.0, 6.0),\n PlanePoint (-4.0, -6.0),\n PlanePoint (16.0, 6.0),\n PlanePoint (16.0, -7.0),\n PlanePoint (16.0, -3.0),\n PlanePoint (17.0, -4.0),\n PlanePoint (5.0, 19.0),\n PlanePoint (19.0, -8.0),\n PlanePoint (3.0, 16.0),\n PlanePoint (12.0, 13.0),\n PlanePoint (3.0, -4.0),\n PlanePoint (17.0, 5.0),\n PlanePoint (-3.0, 15.0),\n PlanePoint (-3.0, -9.0),\n PlanePoint (0.0, 11.0),\n PlanePoint (-9.0, -3.0),\n PlanePoint (-4.0, -2.0),\n PlanePoint (12.0, 10.0)]\n\n hull := find_convex_hull (example_points)\n\n every write ((!hull).to_string ())\nend\n", "language": "ObjectIcon" }, { "code": "(*\n * Convex hulls by Andrew's monotone chain algorithm.\n *\n * For a description of the algorithm, see\n * https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169\n *)\n\n(*------------------------------------------------------------------*)\n(* Just enough plane geometry for our purpose. *)\n\nmodule Plane_point =\n struct\n type t = float * float\n\n let make (xy : t) = xy\n let to_tuple ((x, y) : t) = (x, y)\n\n let x ((x, _) : t) = x\n let y ((_, y) : t) = y\n\n let equal (u : t) (v : t) = (x u = x v && y u = y v)\n\n (* Impose a total order on points, making it one that will work\n for Andrew's monotone chain algorithm. *)\n let order (u : t) (v : t) =\n (x u < x v) || (x u = x v && y u < y v)\n\n (* The Array module's sort routines expect a \"cmp\" function. *)\n let cmp u v =\n if order u v then\n (-1)\n else if order v u then\n (1)\n else\n (0)\n\n (* Subtraction is really a vector or multivector operation. *)\n let sub (u : t) (v : t) = make (x u -. x v, y u -. y v)\n\n (* Cross product is really a multivector operation. *)\n let cross (u : t) (v : t) = (x u *. y v) -. (y u *. x v)\n\n let to_string ((x, y) : t) =\n \"(\" ^ string_of_float x ^ \" \" ^ string_of_float y ^ \")\"\n end\n;;\n\n(*------------------------------------------------------------------*)\n(* We want something akin to array_delete_neighbor_dups of Scheme's\n SRFI-132. *)\n\nlet array_delete_neighbor_dups equal arr =\n (* Returns a Seq.t rather than an array. *)\n let rec loop i lst =\n (* Cons a list of non-duplicates, going backwards through the\n array so the list will be in forwards order. *)\n if i = 0 then\n arr.(i) :: lst\n else if equal arr.(i - 1) arr.(i) then\n loop (i - 1) lst\n else\n loop (i - 1) (arr.(i) :: lst)\n in\n let n = Array.length arr in\n List.to_seq (if n = 0 then [] else loop (n - 1) [])\n;;\n\n(*------------------------------------------------------------------*)\n(* The convex hull algorithm. *)\n\nlet cross_test pt_i hull j =\n let hull_j = hull.(j)\n and hull_j1 = hull.(j - 1) in\n 0.0 < Plane_point.(cross (sub hull_j hull_j1)\n (sub pt_i hull_j1))\n\nlet construct_lower_hull n pt =\n let hull = Array.make n (Plane_point.make (0.0, 0.0)) in\n let () = hull.(0) <- pt.(0)\n and () = hull.(1) <- pt.(1) in\n let rec outer_loop i j =\n if i = n then\n j + 1\n else\n let pt_i = pt.(i) in\n let rec inner_loop j =\n if j = 0 || cross_test pt_i hull j then\n begin\n hull.(j + 1) <- pt_i;\n j + 1\n end\n else\n inner_loop (j - 1)\n in\n outer_loop (i + 1) (inner_loop j)\n in\n let hull_size = outer_loop 2 1 in\n (hull_size, hull)\n\nlet construct_upper_hull n pt =\n let hull = Array.make n (Plane_point.make (0.0, 0.0)) in\n let () = hull.(0) <- pt.(n - 1)\n and () = hull.(1) <- pt.(n - 2) in\n let rec outer_loop i j =\n if i = (-1) then\n j + 1\n else\n let pt_i = pt.(i) in\n let rec inner_loop j =\n if j = 0 || cross_test pt_i hull j then\n begin\n hull.(j + 1) <- pt_i;\n j + 1\n end\n else\n inner_loop (j - 1)\n in\n outer_loop (i - 1) (inner_loop j)\n in\n let hull_size = outer_loop (n - 3) 1 in\n (hull_size, hull)\n\nlet construct_hull n pt =\n\n (* Side note: Construction of the lower and upper hulls can be done\n in parallel. *)\n let (lower_hull_size, lower_hull) = construct_lower_hull n pt\n and (upper_hull_size, upper_hull) = construct_upper_hull n pt in\n\n let hull_size = lower_hull_size + upper_hull_size - 2 in\n let hull = Array.make hull_size (Plane_point.make (0.0, 0.0)) in\n\n begin\n Array.blit lower_hull 0 hull 0 (lower_hull_size - 1);\n Array.blit upper_hull 0 hull (lower_hull_size - 1)\n (upper_hull_size - 1);\n hull\n end\n\nlet plane_convex_hull points =\n (* Takes an arbitrary sequence of points, which may be in any order\n and may contain duplicates. Returns an ordered array of points\n that make up the convex hull. If the sequence of points is empty,\n the returned array is empty. *)\n let pt = Array.of_seq points in\n let () = Array.fast_sort Plane_point.cmp pt in\n let pt = Array.of_seq\n (array_delete_neighbor_dups Plane_point.equal pt) in\n let n = Array.length pt in\n if n <= 2 then\n pt\n else\n construct_hull n pt\n;;\n\n(*------------------------------------------------------------------*)\n\nlet example_points =\n [Plane_point.make (16.0, 3.0);\n Plane_point.make (12.0, 17.0);\n Plane_point.make (0.0, 6.0);\n Plane_point.make (-4.0, -6.0);\n Plane_point.make (16.0, 6.0);\n Plane_point.make (16.0, -7.0);\n Plane_point.make (16.0, -3.0);\n Plane_point.make (17.0, -4.0);\n Plane_point.make (5.0, 19.0);\n Plane_point.make (19.0, -8.0);\n Plane_point.make (3.0, 16.0);\n Plane_point.make (12.0, 13.0);\n Plane_point.make (3.0, -4.0);\n Plane_point.make (17.0, 5.0);\n Plane_point.make (-3.0, 15.0);\n Plane_point.make (-3.0, -9.0);\n Plane_point.make (0.0, 11.0);\n Plane_point.make (-9.0, -3.0);\n Plane_point.make (-4.0, -2.0);\n Plane_point.make (12.0, 10.0)]\n;;\n\nlet hull = plane_convex_hull (List.to_seq example_points)\n;;\n\nArray.iter\n (fun p -> (print_string (Plane_point.to_string p);\n print_string \" \"))\n hull;\nprint_newline ()\n;;\n\n(*------------------------------------------------------------------*)\n", "language": "OCaml" }, { "code": "{$mode ISO}\n\nprogram convex_hull_task (output);\n\n{ Convex hulls, by Andrew's monotone chain algorithm.\n\n For a description of the algorithm, see\n https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169 }\n\nconst max_points = 1000;\ntype points_range = 0 .. max_points - 1;\n\ntype point =\n record\n x, y : real\n end;\ntype point_array = array [points_range] of point;\n\nvar ciura_gaps : array [1 .. 8] of integer;\n\nvar example_points : point_array;\nvar hull : point_array;\nvar hull_size : integer;\nvar index : integer;\n\nfunction make_point (x, y : real) : point;\nbegin\n make_point.x := x;\n make_point.y := y;\nend;\n\n{ The cross product as a signed scalar. }\nfunction cross (u, v : point) : real;\nbegin\n cross := (u.x * v.y) - (u.y * v.x)\nend;\n\nfunction point_subtract (u, v : point) : point;\nbegin\n point_subtract := make_point (u.x - v.x, u.y - v.y)\nend;\n\nfunction point_equal (u, v : point) : boolean;\nbegin\n point_equal := (u.x = v.x) and (u.y = v.y)\nend;\n\nprocedure sort_points (num_points : integer;\n var points : point_array);\n{ Sort first in ascending order by x-coordinates, then in\n ascending order by y-coordinates. Any decent sort algorithm will\n suffice; for the sake of interest, here is the Shell sort of\n https://en.wikipedia.org/w/index.php?title=Shellsort&oldid=1084744510 }\nvar\n i, j, k, gap, offset : integer;\n temp : point;\n done : boolean;\nbegin\n for k := 1 to 8 do\n begin\n gap := ciura_gaps[k];\n for offset := 0 to gap - 1 do\n begin\n i := offset;\n while i <= num_points - 1 do\n begin\n temp := points[i];\n j := i;\n done := false;\n while not done do\n begin\n if j < gap then\n done := true\n else if points[j - gap].x < temp.x then\n done := true\n else if ((points[j - gap].x = temp.x)\n and (points[j - gap].y < temp.y)) then\n done := true\n else\n begin\n points[j] := points[j - gap];\n j := j - gap\n end\n end;\n points[j] := temp;\n i := i + gap\n end\n end\n end\nend; { sort_points }\n\nprocedure delete_neighbor_duplicates (var n : integer;\n var pt : point_array);\n\n procedure delete_trailing_duplicates;\n var\n i : integer;\n done : boolean;\n begin\n i := n - 1;\n done := false;\n while not done do\n begin\n if i = 0 then\n begin\n n := 1;\n done := true\n end\n else if not point_equal (pt[i - 1], pt[i]) then\n begin\n n := i + 1;\n done := true\n end\n else\n i := i + 1\n end\n end;\n\n procedure delete_nontrailing_duplicates;\n var\n i, j, num_deleted : integer;\n done : boolean;\n begin\n i := 0;\n while i < n - 1 do\n begin\n j := i + 1;\n done := false;\n while not done do\n begin\n if j = n then\n done := true\n else if not point_equal (pt[j], pt[i]) then\n done := true\n else\n j := j + 1\n end;\n if j <> i + 1 then\n begin\n num_deleted := j - i - 1;\n while j <> n do\n begin\n pt[j - num_deleted] := pt[j];\n j := j + 1\n end;\n n := n - num_deleted\n end;\n i := i + 1\n end\n end;\n\nbegin\n delete_trailing_duplicates;\n delete_nontrailing_duplicates\nend; { delete_neighbor_duplicates }\n\nprocedure construct_lower_hull (n : integer;\n pt : point_array;\n var hull_size : integer;\n var hull : point_array);\nvar\n i, j : integer;\n done : boolean;\nbegin\n j := 1;\n hull[0] := pt[0];\n hull[1] := pt[1];\n for i := 2 to n - 1 do\n begin\n done := false;\n while not done do\n begin\n if j = 0 then\n begin\n j := j + 1;\n hull[j] := pt[i];\n done := true\n end\n else if 0.0 < cross (point_subtract (hull[j],\n hull[j - 1]),\n point_subtract (pt[i],\n hull[j - 1])) then\n begin\n j := j + 1;\n hull[j] := pt[i];\n done := true\n end\n else\n j := j - 1\n end\n end;\n hull_size := j + 1\nend; { construct_lower_hull }\n\nprocedure construct_upper_hull (n : integer;\n pt : point_array;\n var hull_size : integer;\n var hull : point_array);\nvar\n i, j : integer;\n done : boolean;\nbegin\n j := 1;\n hull[0] := pt[n - 1];\n hull[1] := pt[n - 2];\n for i := n - 3 downto 0 do\n begin\n done := false;\n while not done do\n begin\n if j = 0 then\n begin\n j := j + 1;\n hull[j] := pt[i];\n done := true\n end\n else if 0.0 < cross (point_subtract (hull[j],\n hull[j - 1]),\n point_subtract (pt[i],\n hull[j - 1])) then\n begin\n j := j + 1;\n hull[j] := pt[i];\n done := true\n end\n else\n j := j - 1\n end\n end;\n hull_size := j + 1\nend; { construct_upper_hull }\n\nprocedure contruct_hull (n : integer;\n pt : point_array;\n var hull_size : integer;\n var hull : point_array);\nvar\n i : integer;\n lower_hull_size, upper_hull_size : integer;\n lower_hull, upper_hull : point_array;\nbegin\n { A side note: the calls to construct_lower_hull and\n construct_upper_hull could be done in parallel. }\n construct_lower_hull (n, pt, lower_hull_size, lower_hull);\n construct_upper_hull (n, pt, upper_hull_size, upper_hull);\n\n hull_size := lower_hull_size + upper_hull_size - 2;\n\n for i := 0 to lower_hull_size - 2 do\n hull[i] := lower_hull[i];\n for i := 0 to upper_hull_size - 2 do\n hull[lower_hull_size - 1 + i] := upper_hull[i]\nend; { contruct_hull }\n\nprocedure find_convex_hull (n : integer;\n points : point_array;\n var hull_size : integer;\n var hull : point_array);\nvar\n pt : point_array;\n numpt : integer;\n i : integer;\nbegin\n for i := 0 to n - 1 do\n pt[i] := points[i];\n numpt := n;\n\n sort_points (numpt, pt);\n delete_neighbor_duplicates (numpt, pt);\n\n if numpt = 0 then\n hull_size := 0\n else if numpt <= 2 then\n begin\n hull_size := numpt;\n for i := 0 to numpt - 1 do\n hull[i] := pt[i]\n end\n else\n contruct_hull (numpt, pt, hull_size, hull)\nend; { find_convex_hull }\n\nbegin\n ciura_gaps[1] := 701;\n ciura_gaps[2] := 301;\n ciura_gaps[3] := 132;\n ciura_gaps[4] := 57;\n ciura_gaps[5] := 23;\n ciura_gaps[6] := 10;\n ciura_gaps[7] := 4;\n ciura_gaps[8] := 1;\n\n example_points[0] := make_point (16, 3);\n example_points[1] := make_point (12, 17);\n example_points[2] := make_point (0, 6);\n example_points[3] := make_point (-4, -6);\n example_points[4] := make_point (16, 6);\n example_points[5] := make_point (16, -7);\n example_points[6] := make_point (16, -3);\n example_points[7] := make_point (17, -4);\n example_points[8] := make_point (5, 19);\n example_points[9] := make_point (19, -8);\n example_points[10] := make_point (3, 16);\n example_points[11] := make_point (12, 13);\n example_points[12] := make_point (3, -4);\n example_points[13] := make_point (17, 5);\n example_points[14] := make_point (-3, 15);\n example_points[15] := make_point (-3, -9);\n example_points[16] := make_point (0, 11);\n example_points[17] := make_point (-9, -3);\n example_points[18] := make_point (-4, -2);\n example_points[19] := make_point (12, 10);\n\n find_convex_hull (19, example_points, hull_size, hull);\n\n for index := 0 to hull_size - 1 do\n writeln (hull[index].x, ' ', hull[index].y)\nend.\n\n{--------------------------------------------------------------------}\n{ The Emacs Pascal mode is intolerable.\n Until I can find a substitute: }\n{ local variables: }\n{ mode: fundamental }\n{ end: }\n", "language": "Pascal" }, { "code": "use strict;\nuse warnings;\nuse feature 'say';\n\n{\npackage Point;\nuse Class::Struct;\nstruct( x => '$', y => '$',);\nsub print { '(' . $_->x . ', ' . $_->y . ')' }\n}\n\nsub ccw {\n my($a, $b, $c) = @_;\n ($b->x - $a->x)*($c->y - $a->y) - ($b->y - $a->y)*($c->x - $a->x);\n}\n\nsub tangent {\n my($a, $b) = @_;\n my $opp = $b->x - $a->x;\n my $adj = $b->y - $a->y;\n $adj != 0 ? $opp / $adj : 1E99;\n}\n\nsub graham_scan {\n our @coords; local *coords = shift;\n my @sp = sort { $a->y <=> $b->y or $a->x <=> $b->x } map { Point->new( x => $_->[0], y => $_->[1] ) } @coords;\n\n # need at least 3 points to make a hull\n return @sp if @sp < 3;\n\n # first point on hull is minimum y point\n my @h = shift @sp;\n\n # re-sort the points by angle, secondary on x (classic Schwartzian)\n @sp =\n map { $sp[$_->[0]] }\n sort { $b->[1] <=> $a->[1] or $a->[2] <=> $b->[2] }\n map { [$_, tangent($h[0], $sp[$_]), $sp[$_]->x] }\n 0..$#sp;\n\n # first point of re-sorted list is guaranteed to be on hull\n push @h, shift @sp;\n\n # check through the remaining list making sure that there is always a positive angle\n for my $point (@sp) {\n if (ccw( @h[-2,-1], $point ) >= 0) {\n push @h, $point;\n } else {\n pop @h;\n redo;\n }\n }\n @h\n}\n\nmy @hull_1 = graham_scan(\n [[16, 3], [12,17], [ 0, 6], [-4,-6], [16, 6], [16,-7], [16,-3],\n [17,-4], [ 5,19], [19,-8], [ 3,16], [12,13], [ 3,-4], [17, 5],\n [-3,15], [-3,-9], [ 0,11], [-9,-3], [-4,-2], [12,10]]\n );\n\nmy @hull_2 = graham_scan(\n [[16, 3], [12,17], [ 0, 6], [-4,-6], [16, 6], [16,-7], [16,-3],\n [17,-4], [ 5,19], [19,-8], [ 3,16], [12,13], [ 3,-4], [17, 5],\n [-3,15], [-3,-9], [ 0,11], [-9,-3], [-4,-2], [12,10], [14,-9], [1,-9]]\n );\n\nmy $list = join ' ', map { Point::print($_) } @hull_1;\nsay \"Convex Hull (@{[scalar @hull_1]} points): [$list]\";\n $list = join ' ', map { Point::print($_) } @hull_2;\nsay \"Convex Hull (@{[scalar @hull_2]} points): [$list]\";\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo/rosetta/Convex_hull.exw\n -- ============================\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{{</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">19</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">19</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">13</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">15</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">19</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">19</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">13</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">17</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">15</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">}}}</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #000080;font-style:italic;\">-- idx to tests, for the GTITLE.</span>\n\n <span style=\"color: #008080;\">enum</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">ccw</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #0000FF;\">></span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">convex_hull</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">points</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #000000;\">points</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sort</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">points</span><span style=\"color: #0000FF;\">))</span>\n\n <span style=\"color: #000080;font-style:italic;\">/* lower hull */</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">points</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">)>=</span><span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">ccw</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">[$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">[$],</span> <span style=\"color: #000000;\">points</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">points</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #000080;font-style:italic;\">/* upper hull */</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">points</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">)>=</span><span style=\"color: #000000;\">t</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">ccw</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">[$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">[$],</span><span style=\"color: #000000;\">points</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">points</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">h</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"For test set: \"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">pp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],{</span><span style=\"color: #004600;\">pp_Indent</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">13</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">pp_Maxlen</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">111</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Convex Hull is: \"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">pp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">convex_hull</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- plots the test points in red crosses and the convex hull in green circles</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #7060A8;\">IupGraph</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">graph</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">get_data</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*graph*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"GTITLE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"Marks Mode (%d/%d)\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">columnize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tt</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">columnize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">convex_hull</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tt</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000080;font-style:italic;\">-- and close the loop:</span>\n <span style=\"color: #000000;\">cx</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">cy</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">CD_RED</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">CD_GREEN</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"HOLLOW_CIRCLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"MARKLINE\"</span><span style=\"color: #0000FF;\">}}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">key_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">K_ESC</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_CLOSE</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span> <span style=\"color: #000080;font-style:italic;\">-- (standard practice for me)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">K_F5</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span> <span style=\"color: #000080;font-style:italic;\">-- (let browser reload work)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">K_LEFT</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">):</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">K_RIGHT</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)?</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">IupUpdate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_CONTINUE</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">graph</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGraph</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">get_data</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"RASTERSIZE=640x480,MODE=MARK\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`TITLE=\"Convex Hull\",MINSIZE=270x430`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttributes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"XTICK=2,XMIN=-12,XMAX=20,XMARGIN=25,YTICK=2,YMIN=-12,YMAX=20\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"GRIDCOLOR\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">CD_LIGHT_GREY</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"K_ANY\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"key_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`RASTERSIZE`</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n<!--\n", "language": "Phix" }, { "code": "from __future__ import print_function\nfrom shapely.geometry import MultiPoint\n\nif __name__==\"__main__\":\n\tpts = MultiPoint([(16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2), (12,10)])\n\tprint (pts.convex_hull)\n", "language": "Python" }, { "code": "#lang typed/racket\n(define-type Point (Pair Real Real))\n(define-type Points (Listof Point))\n\n(: ⊗ (Point Point Point -> Real))\n(define/match (⊗ o a b)\n [((cons o.x o.y) (cons a.x a.y) (cons b.x b.y))\n (- (* (- a.x o.x) (- b.y o.y)) (* (- a.y o.y) (- b.x o.x)))])\n\n(: Point<? (Point Point -> Boolean))\n(define (Point<? a b)\n (cond [(< (car a) (car b)) #t] [(> (car a) (car b)) #f] [else (< (cdr a) (cdr b))]))\n\n;; Input: a list P of points in the plane.\n(define (convex-hull [P:unsorted : Points])\n ;; Sort the points of P by x-coordinate (in case of a tie, sort by y-coordinate).\n (define P (sort P:unsorted Point<?))\n ;; for i = 1, 2, ..., n:\n ;; while L contains at least two points and the sequence of last two points\n ;; of L and the point P[i] does not make a counter-clockwise turn:\n ;; remove the last point from L\n ;; append P[i] to L\n ;; TB: U is identical with (reverse P)\n (define (upper/lower-hull [P : Points])\n (reverse\n (for/fold ((rev : Points null))\n ((P.i (in-list P)))\n (let u/l : Points ((rev rev))\n (match rev\n [(list p-2 p-1 ps ...) #:when (not (positive? (⊗ p-2 P.i p-1))) (u/l (list* p-1 ps))]\n [(list ps ...) (cons P.i ps)])))))\n\n ;; Initialize U and L as empty lists.\n ;; The lists will hold the vertices of upper and lower hulls respectively.\n (let ((U (upper/lower-hull (reverse P)))\n (L (upper/lower-hull P)))\n ;; Remove the last point of each list (it's the same as the first point of the other list).\n ;; Concatenate L and U to obtain the convex hull of P.\n (append (drop-right L 1) (drop-right U 1)))) ; Points in the result will be listed in CCW order.)\n\n(module+ test\n (require typed/rackunit)\n (check-equal?\n (convex-hull\n (list '(16 . 3) '(12 . 17) '(0 . 6) '(-4 . -6) '(16 . 6) '(16 . -7) '(16 . -3) '(17 . -4)\n '(5 . 19) '(19 . -8) '(3 . 16) '(12 . 13) '(3 . -4) '(17 . 5) '(-3 . 15) '(-3 . -9)\n '(0 . 11) '(-9 . -3) '(-4 . -2) '(12 . 10)))\n (list '(-9 . -3) '(-3 . -9) '(19 . -8) '(17 . 5) '(12 . 17) '(5 . 19) '(-3 . 15))))\n", "language": "Racket" }, { "code": "class Point {\n has Real $.x is rw;\n has Real $.y is rw;\n method gist { [~] '(', self.x,', ', self.y, ')' };\n}\n\nsub ccw (Point $a, Point $b, Point $c) {\n ($b.x - $a.x)*($c.y - $a.y) - ($b.y - $a.y)*($c.x - $a.x);\n}\n\nsub tangent (Point $a, Point $b) {\n my $opp = $b.x - $a.x;\n my $adj = $b.y - $a.y;\n $adj != 0 ?? $opp / $adj !! Inf\n}\n\nsub graham-scan (**@coords) {\n # sort points by y, secondary sort on x\n my @sp = @coords.map( { Point.new( :x($_[0]), :y($_[1]) ) } )\n .sort: {.y, .x};\n\n # need at least 3 points to make a hull\n return @sp if +@sp < 3;\n\n # first point on hull is minimum y point\n my @h = @sp.shift;\n\n # re-sort the points by angle, secondary on x\n @sp = @sp.map( { $++ => [tangent(@h[0], $_), $_.x] } )\n .sort( {-$_.value[0], $_.value[1] } )\n .map: { @sp[$_.key] };\n\n # first point of re-sorted list is guaranteed to be on hull\n @h.push: @sp.shift;\n\n # check through the remaining list making sure that\n # there is always a positive angle\n for @sp -> $point {\n if ccw( |@h.tail(2), $point ) > 0 {\n @h.push: $point;\n } else {\n @h.pop;\n @h.push: $point and next if +@h < 2;\n redo;\n }\n }\n @h\n}\n\nmy @hull = graham-scan(\n (16, 3), (12,17), ( 0, 6), (-4,-6), (16, 6), (16,-7), (16,-3),\n (17,-4), ( 5,19), (19,-8), ( 3,16), (12,13), ( 3,-4), (17, 5),\n (-3,15), (-3,-9), ( 0,11), (-9,-3), (-4,-2), (12,10)\n );\n\nsay \"Convex Hull ({+@hull} points): \", @hull;\n\n@hull = graham-scan(\n (16, 3), (12,17), ( 0, 6), (-4,-6), (16, 6), (16,-7), (16,-3),\n (17,-4), ( 5,19), (19,-8), ( 3,16), (12,13), ( 3,-4), (17, 5),\n (-3,15), (-3,-9), ( 0,11), (-9,-3), (-4,-2), (12,10), (20,-9), (1,-9)\n );\n\nsay \"Convex Hull ({+@hull} points): \", @hull;\n", "language": "Raku" }, { "code": "#\n# Convex hulls by Andrew's monotone chain algorithm.\n#\n# For a description of the algorithm, see\n# https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169\n#\n# As in the Fortran 2018 version upon which this code is based, I\n# shall use the built-in \"complex\" type to represent \"points\" in the\n# plane. This is merely for convenience, rather than to express a\n# mathematical equivalence.\n#\n\ndefine(point, complex)\n\nfunction x (u)\n\n # Return the x-coordinate of \"point\" u.\n\n implicit none\n\n point u\n real x\n\n x = real (u)\nend\n\nfunction y (u)\n\n # Return the y-coordinate of \"point\" u.\n\n implicit none\n\n point u\n real y\n\n y = aimag (u)\nend\n\nfunction cross (u, v)\n\n # Return, as a signed scalar, the cross product of \"points\" u and v\n # (regarded as \"vectors\" or multivectors).\n\n implicit none\n\n point u, v\n real cross, x, y\n\n cross = (x (u) * y (v)) - (y (u) * x (v))\nend\n\nsubroutine sortpt (numpt, pt)\n\n # Sort \"points\" in ascending order, first by the x-coordinates and\n # then by the y-coordinates. Any decent sort algorithm will suffice;\n # for the sake of interest, here is the Shell sort of\n # https://en.wikipedia.org/w/index.php?title=Shellsort&oldid=1084744510\n\n implicit none\n\n integer numpt\n point pt(0:*)\n\n real x, y\n integer i, j, k, gap, offset\n point temp\n logical done\n\n integer gaps(1:8)\n data gaps / 701, 301, 132, 57, 23, 10, 4, 1 /\n\n for (k = 1; k <= 8; k = k + 1)\n {\n gap = gaps(k)\n for (offset = 0; offset <= gap - 1; offset = offset + 1)\n for (i = offset; i <= numpt - 1; i = i + gap)\n {\n temp = pt(i)\n j = i\n done = .false.\n while (!done)\n {\n if (j < gap)\n done = .true.\n else if (x (pt(j - gap)) < x (temp))\n done = .true.\n else if (x (pt(j - gap)) == x (temp) _\n && (y (pt(j - gap)) <= y (temp)))\n done = .true.\n else\n {\n pt(j) = pt(j - gap)\n j = j - gap\n }\n }\n pt(j) = temp\n }\n }\nend\n\nsubroutine deltrd (n, pt)\n\n # Delete trailing neighbor duplicates.\n\n implicit none\n\n integer n\n point pt(0:*)\n\n integer i\n logical done\n\n i = n - 1\n done = .false.\n while (!done)\n {\n if (i == 0)\n {\n n = 1\n done = .true.\n }\n else if (pt(i - 1) != pt(i))\n {\n n = i + 1\n done = .true.\n }\n else\n i = i - 1\n }\nend\n\nsubroutine delntd (n, pt)\n\n # Delete non-trailing neighbor duplicates.\n\n implicit none\n\n integer n\n point pt(0:*)\n\n integer i, j, numdel\n logical done\n\n i = 0\n while (i < n - 1)\n {\n j = i + 1\n done = .false.\n while (!done)\n {\n if (j == n)\n done = .true.\n else if (pt(j) != pt(i))\n done = .true.\n else\n j = j + 1\n }\n if (j != i + 1)\n {\n numdel = j - i - 1\n while (j != n)\n {\n pt(j - numdel) = pt(j)\n j = j + 1\n }\n n = n - numdel\n }\n i = i + 1\n }\nend\n\nsubroutine deldup (n, pt)\n\n # Delete neighbor duplicates.\n\n implicit none\n\n integer n\n point pt(0:*)\n\n call deltrd (n, pt)\n call delntd (n, pt)\nend\n\nsubroutine cxlhul (n, pt, hullsz, hull)\n\n # Construct the lower hull.\n\n implicit none\n\n integer n # Number of points.\n point pt(0:*)\n integer hullsz # Output.\n point hull(0:*) # Output.\n\n real cross\n integer i, j\n logical done\n\n j = 1\n hull(0) = pt(0)\n hull(1) = pt(1)\n for (i = 2; i <= n - 1; i = i + 1)\n {\n done = .false.\n while (!done)\n {\n if (j == 0)\n {\n j = j + 1\n hull(j) = pt(i)\n done = .true.\n }\n else if (0.0 < cross (hull(j) - hull(j - 1), _\n pt(i) - hull(j - 1)))\n {\n j = j + 1\n hull(j) = pt(i)\n done = .true.\n }\n else\n j = j - 1\n }\n }\n hullsz = j + 1\nend\n\nsubroutine cxuhul (n, pt, hullsz, hull)\n\n # Construct the upper hull.\n\n implicit none\n\n integer n # Number of points.\n point pt(0:*)\n integer hullsz # Output.\n point hull(0:*) # Output.\n\n real cross\n integer i, j\n logical done\n\n j = 1\n hull(0) = pt(n - 1)\n hull(1) = pt(n - 2)\n for (i = n - 3; 0 <= i; i = i - 1)\n {\n done = .false.\n while (!done)\n {\n if (j == 0)\n {\n j = j + 1\n hull(j) = pt(i)\n done = .true.\n }\n else if (0.0 < cross (hull(j) - hull(j - 1), _\n pt(i) - hull(j - 1)))\n {\n j = j + 1\n hull(j) = pt(i)\n done = .true.\n }\n else\n j = j - 1\n }\n }\n hullsz = j + 1\nend\n\nsubroutine cxhull (n, pt, hullsz, lhull, uhull)\n\n # Construct the hull.\n\n implicit none\n\n integer n # Number of points.\n point pt(0:*) # Overwritten with hull.\n integer hullsz # Output.\n point lhull(0:*) # Workspace.\n point uhull(0:*) # Workspace\n\n integer lhulsz, uhulsz, i\n\n # A side note: the calls to construct_lower_hull and\n # construct_upper_hull could be done in parallel.\n call cxlhul (n, pt, lhulsz, lhull)\n call cxuhul (n, pt, uhulsz, uhull)\n\n hullsz = lhulsz + uhulsz - 2\n\n for (i = 0; i <= lhulsz - 2; i = i + 1)\n pt(i) = lhull(i)\n for (i = 0; i <= uhulsz - 2; i = i + 1)\n pt(lhulsz - 1 + i) = uhull(i)\nend\n\nsubroutine cvxhul (n, pt, hullsz, lhull, uhull)\n\n # Find a convex hull.\n\n implicit none\n\n integer n # Number of points.\n point pt(0:*) # The contents of pt is replaced with the hull.\n integer hullsz # Output.\n point lhull(0:*) # Workspace.\n point uhull(0:*) # Workspace\n\n integer numpt\n\n numpt = n\n\n call sortpt (numpt, pt)\n call deldup (numpt, pt)\n\n if (numpt == 0)\n hullsz = 0\n else if (numpt <= 2)\n hullsz = numpt\n else\n call cxhull (numpt, pt, hullsz, lhull, uhull)\nend\n\nprogram cvxtsk\n\n # The Rosetta Code convex hull task.\n\n implicit none\n\n integer n, i\n point points(0:100)\n point lhull(0:100)\n point uhull(0:100)\n character*100 fmt\n\n point exampl(0:19)\n data exampl / (16, 3), (12, 17), (0, 6), (-4, -6), (16, 6), _\n (16, -7), (16, -3), (17, -4), (5, 19), (19, -8), _\n (3, 16), (12, 13), (3, -4), (17, 5), (-3, 15), _\n (-3, -9), (0, 11), (-9, -3), (-4, -2), (12, 10) /\n\n n = 20\n for (i = 0; i <= n - 1; i = i + 1)\n points(i) = exampl(i)\n call cvxhul (n, points, n, lhull, uhull)\n\n write (fmt, '(\"(\", I20, ''(\"(\", F3.0, 1X, F3.0, \") \")'', \")\")') n\n write (*, fmt) (points(i), i = 0, n - 1)\nend\n", "language": "RATFOR" }, { "code": "/* REXX ---------------------------------------------------------------\n* Compute the Convex Hull for a set of points\n* Format of the input file:\n* (16,3) (12,17) (0,6) (-4,-6) (16,6) (16,-7) (16,-3) (17,-4) (5,19)\n* (19,-8) (3,16) (12,13) (3,-4) (17,5) (-3,15) (-3,-9) (0,11) (-9,-3)\n* (-4,-2)\n*--------------------------------------------------------------------*/\n Signal On Novalue\n Signal On Syntax\nParse Arg fid\nIf fid='' Then Do\n fid='chullmin.in' /* miscellaneous test data */\n fid='chullx.in'\n fid='chullt.in'\n fid='chulla.in'\n fid='chullxx.in'\n fid='sq.in'\n fid='tri.in'\n fid='line.in'\n fid='point.in'\n fid='chull.in' /* data from task description */\n End\ng.0debug=''\ng.0oid=fn(fid)'.txt'; 'erase' g.0oid\nx.=0\nyl.=''\nParse Value '1000 -1000' With g.0xmin g.0xmax\nParse Value '1000 -1000' With g.0ymin g.0ymax\n/*---------------------------------------------------------------------\n* First read the input and store the points' coordinates\n* x.0 contains the number of points, x.i contains the x.coordinate\n* yl.x contains the y.coordinate(s) of points (x/y)\n*--------------------------------------------------------------------*/\nDo while lines(fid)>0\n l=linein(fid)\n Do While l<>''\n Parse Var l '(' x ',' y ')' l\n Call store x,y\n End\n End\nCall lineout fid\nDo i=1 To x.0 /* loop over points */\n x=x.i\n yl.x=sortv(yl.x) /* sort y-coordinates */\n End\nCall sho\n\n/*---------------------------------------------------------------------\n* Now we look for special border points:\n* lefthigh and leftlow: leftmost points with higheste and lowest y\n* ritehigh and ritelow: rightmost points with higheste and lowest y\n* yl.x contains the y.coordinate(s) of points (x/y)\n*--------------------------------------------------------------------*/\nleftlow=0\nlefthigh=0\nDo i=1 To x.0\n x=x.i\n If maxv(yl.x)=g.0ymax Then Do\n If lefthigh=0 Then lefthigh=x'/'g.0ymax\n ritehigh=x'/'g.0ymax\n End\n If minv(yl.x)=g.0ymin Then Do\n ritelow=x'/'g.0ymin\n If leftlow=0 Then leftlow=x'/'g.0ymin\n End\n End\nCall o 'lefthigh='lefthigh\nCall o 'ritehigh='ritehigh\nCall o 'ritelow ='ritelow\nCall o 'leftlow ='leftlow\n/*---------------------------------------------------------------------\n* Now we look for special border points:\n* leftmost_n and leftmost_s: points with lowest x and highest/lowest y\n* ritemost_n and ritemost_s: points with largest x and highest/lowest y\n* n and s stand foNorth and South, respectively\n*--------------------------------------------------------------------*/\nx=g.0xmi; leftmost_n=x'/'maxv(yl.x)\nx=g.0xmi; leftmost_s=x'/'minv(yl.x)\nx=g.0xma; ritemost_n=x'/'maxv(yl.x)\nx=g.0xma; ritemost_s=x'/'minv(yl.x)\n\n/*---------------------------------------------------------------------\n* Now we compute the paths from ritehigh to ritelow (n_end)\n* and leftlow to lefthigh (s_end), respectively\n*--------------------------------------------------------------------*/\nx=g.0xma\nn_end=''\nDo i=words(yl.x) To 1 By -1\n n_end=n_end x'/'word(yl.x,i)\n End\nCall o 'n_end='n_end\nx=g.0xmi\ns_end=''\nDo i=1 To words(yl.x)\n s_end=s_end x'/'word(yl.x,i)\n End\nCall o 's_end='s_end\n\nn_high=''\ns_low=''\n/*---------------------------------------------------------------------\n* Now we compute the upper part of the convex hull (nhull)\n*--------------------------------------------------------------------*/\nCall o 'leftmost_n='leftmost_n\nCall o 'lefthigh ='lefthigh\nnhull=leftmost_n\nres=mk_nhull(leftmost_n,lefthigh);\nnhull=nhull res\nCall o 'A nhull='nhull\nDo While res<>lefthigh\n res=mk_nhull(res,lefthigh); nhull=nhull res\n Call o 'B nhull='nhull\n End\nres=mk_nhull(lefthigh,ritemost_n); nhull=nhull res\nCall o 'C nhull='nhull\nDo While res<>ritemost_n\n res=mk_nhull(res,ritemost_n); nhull=nhull res\n Call o 'D nhull='nhull\n End\n\nnhull=nhull n_end /* attach the right vertical border */\n\n/*---------------------------------------------------------------------\n* Now we compute the lower part of the convex hull (shull)\n*--------------------------------------------------------------------*/\nres=mk_shull(ritemost_s,ritelow);\nshull=ritemost_s res\nCall o 'A shull='shull\nDo While res<>ritelow\n res=mk_shull(res,ritelow)\n shull=shull res\n Call o 'B shull='shull\n End\nres=mk_shull(ritelow,leftmost_s)\nshull=shull res\nCall o 'C shull='shull\nDo While res<>leftmost_s\n res=mk_shull(res,leftmost_s);\n shull=shull res\n Call o 'D shull='shull\n End\n\nshull=shull s_end\n\nchull=nhull shull /* concatenate upper and lower part */\n /* eliminate duplicates */\n /* too lazy to take care before :-) */\nParse Var chull chullx chull\nhave.=0\nhave.chullx=1\nDo i=1 By 1 While chull>''\n Parse Var chull xy chull\n If have.xy=0 Then Do\n chullx=chullx xy\n have.xy=1\n End\n End\n /* show the result */\nSay 'Points of convex hull in clockwise order:'\nSay chullx\n/**********************************************************************\n* steps that were necessary in previous attempts\n/*---------------------------------------------------------------------\n* Final polish: Insert points that are not yet in chullx but should be\n* First on the upper hull going from left to right\n*--------------------------------------------------------------------*/\ni=1\nDo While i<words(chullx)\n xya=word(chullx,i) ; Parse Var xya xa '/' ya\n If xa=g.0xmax Then Leave\n xyb=word(chullx,i+1); Parse Var xyb xb '/' yb\n Do j=1 To x.0\n If x.j>xa Then Do\n If x.j<xb Then Do\n xx=x.j\n parse Value kdx(xya,xyb) With k d x\n If (k*xx+d)=maxv(yl.xx) Then Do\n chullx=subword(chullx,1,i) xx'/'maxv(yl.xx),\n subword(chullx,i+1)\n i=i+1\n End\n End\n End\n Else\n i=i+1\n End\n End\n\nSay chullx\n\n/*---------------------------------------------------------------------\n* Final polish: Insert points that are not yet in chullx but should be\n* Then on the lower hull going from right to left\n*--------------------------------------------------------------------*/\ni=wordpos(ritemost_s,chullx)\nDo While i<words(chullx)\n xya=word(chullx,i) ; Parse Var xya xa '/' ya\n If xa=g.0xmin Then Leave\n xyb=word(chullx,i+1); Parse Var xyb xb '/' yb\n Do j=x.0 To 1 By -1\n If x.j<xa Then Do\n If x.j>xb Then Do\n xx=x.j\n parse Value kdx(xya,xyb) With k d x\n If (k*xx+d)=minv(yl.xx) Then Do\n chullx=subword(chullx,1,i) xx'/'minv(yl.xx),\n subword(chullx,i+1)\n i=i+1\n End\n End\n End\n Else\n i=i+1\n End\n End\nSay chullx\n**********************************************************************/\nCall lineout g.0oid\n\nExit\n\nstore: Procedure Expose x. yl. g.\n/*---------------------------------------------------------------------\n* arrange the points in ascending order of x (in x.) and,\n* for each x in ascending order of y (in yl.x)\n* g.0xmin is the smallest x-value, etc.\n* g.0xmi is the x-coordinate\n* g.0ymin is the smallest y-value, etc.\n* g.0ymi is the x-coordinate of such a point\n*--------------------------------------------------------------------*/\n Parse Arg x,y\n Call o 'store' x y\n If x<g.0xmin Then Do; g.0xmin=x; g.0xmi=x; End\n If x>g.0xmax Then Do; g.0xmax=x; g.0xma=x; End\n If y<g.0ymin Then Do; g.0ymin=y; g.0ymi=x; End\n If y>g.0ymax Then Do; g.0ymax=y; g.0yma=x; End\n Do i=1 To x.0\n Select\n When x.i>x Then\n Leave\n When x.i=x Then Do\n yl.x=yl.x y\n Return\n End\n Otherwise\n Nop\n End\n End\n Do j=x.0 To i By -1\n ja=j+1\n x.ja=x.j\n End\n x.i=x\n yl.x=y\n x.0=x.0+1\n Return\n\nsho: Procedure Expose x. yl. g.\n Do i=1 To x.0\n x=x.i\n say format(i,2) 'x='format(x,3) 'yl='yl.x\n End\n Say ''\n Return\n\nmaxv: Procedure Expose g.\n Call trace 'O'\n Parse Arg l\n res=-1000\n Do While l<>''\n Parse Var l v l\n If v>res Then res=v\n End\n Return res\n\nminv: Procedure Expose g.\n Call trace 'O'\n Parse Arg l\n res=1000\n Do While l<>''\n Parse Var l v l\n If v<res Then res=v\n End\n Return res\n\nsortv: Procedure Expose g.\n Call trace 'O'\n Parse Arg l\n res=''\n Do Until l=''\n v=minv(l)\n res=res v\n l=remove(v,l)\n End\n Return space(res)\n\nlastword: return word(arg(1),words(arg(1)))\n\nkdx: Procedure Expose xy. g.\n/*---------------------------------------------------------------------\n* Compute slope and y-displacement of a straight line\n* that is defined by two points: y=k*x+d\n* Specialty; k='*' x=xa if xb=xa\n*--------------------------------------------------------------------*/\n Call trace 'O'\n Parse Arg xya,xyb\n Parse Var xya xa '/' ya\n Parse Var xyb xb '/' yb\n If xa=xb Then\n Parse Value '*' '-' xa With k d x\n Else Do\n k=(yb-ya)/(xb-xa)\n d=yb-k*xb\n x='*'\n End\n Return k d x\n\nremove:\n/*---------------------------------------------------------------------\n* Remove a specified element (e) from a given string (s)\n*--------------------------------------------------------------------*/\n Parse Arg e,s\n Parse Var s sa (e) sb\n Return space(sa sb)\n\no: Procedure Expose g.\n/*---------------------------------------------------------------------\n* Write a line to the debug file\n*--------------------------------------------------------------------*/\n If arg(2)=1 Then say arg(1)\n Return lineout(g.0oid,arg(1))\n\nis_ok: Procedure Expose x. yl. g. sigl\n/*---------------------------------------------------------------------\n* Test if a given point (b) is above/on/or below a straight line\n* defined by two points (a and c)\n*--------------------------------------------------------------------*/\n Parse Arg a,b,c,op\n Call o 'is_ok' a b c op\n Parse Value kdx(a,c) With k d x\n Parse Var b x'/'y\n If op='U' Then y=maxv(yl.x)\n Else y=minv(yl.x)\n Call o y x (k*x+d)\n If (abs(y-(k*x+d))<1.e-8) Then Return 0\n If op='U' Then res=(y<=(k*x+d))\n Else res=(y>=(k*x+d))\n Return res\n\nmk_nhull: Procedure Expose x. yl. g.\n/*---------------------------------------------------------------------\n* Compute the upper (north) hull between two points (xya and xyb)\n* Move x from xyb back to xya until all points within the current\n* range (x and xyb) are BELOW the straight line defined xya and x\n* Then make x the new starting point\n*--------------------------------------------------------------------*/\n Parse Arg xya,xyb\n Call o 'mk_nhull' xya xyb\n If xya=xyb Then Return xya\n Parse Var xya xa '/' ya\n Parse Var xyb xb '/' yb\n iu=0\n iv=0\n Do xi=1 To x.0\n if x.xi>=xa & iu=0 Then iu=xi\n if x.xi<=xb Then iv=xi\n If x.xi>xb Then Leave\n End\n Call o iu iv\n xu=x.iu\n xyu=xu'/'maxv(yl.xu)\n Do h=iv To iu+1 By -1 Until good\n Call o 'iv='iv,g.0debug\n Call o ' h='h,g.0debug\n xh=x.h\n xyh=xh'/'maxv(yl.xh)\n Call o 'Testing' xyu xyh,g.0debug\n good=1\n Do hh=h-1 To iu+1 By -1 While good\n xhh=x.hh\n xyhh=xhh'/'maxv(yl.xhh)\n Call o 'iu hh iv=' iu hh h,g.0debug\n If is_ok(xyu,xyhh,xyh,'U') Then Do\n Call o xyhh 'is under' xyu xyh,g.0debug\n Nop\n End\n Else Do\n good=0\n Call o xyhh 'is above' xyu xyh '-' xyh 'ist nicht gut'\n End\n End\n End\n Call o xyh 'is the one'\n\n Return xyh\n\np: Return\nSay arg(1)\nPull .\nReturn\n\nmk_shull: Procedure Expose x. yl. g.\n/*---------------------------------------------------------------------\n* Compute the lower (south) hull between two points (xya and xyb)\n* Move x from xyb back to xya until all points within the current\n* range (x and xyb) are ABOVE the straight line defined xya and x\n* Then make x the new starting point\n*-----\n---------------------------------------------------------------*/\n Parse Arg xya,xyb\n Call o 'mk_shull' xya xyb\n If xya=xyb Then Return xya\n Parse Var xya xa '/' ya\n Parse Var xyb xb '/' yb\n iu=0\n iv=0\n Do xi=x.0 To 1 By -1\n if x.xi<=xa & iu=0 Then iu=xi\n if x.xi>=xb Then iv=xi\n If x.xi<xb Then Leave\n End\n Call o iu iv '_' x.iu x.iv\n Call o 'mk_shull iv iu' iv iu\n xu=x.iu\n xyu=xu'/'minv(yl.xu)\n good=0\n Do h=iv To iu-1 Until good\n xh=x.h\n xyh=xh'/'minv(yl.xh)\n Call o 'Testing' xyu xyh h iu\n good=1\n Do hh=h+1 To iu-1 While good\n Call o 'iu hh h=' iu hh h\n xhh=x.hh\n xyhh=xhh'/'minv(yl.xhh)\n If is_ok(xyu,xyhh,xyh,'O') Then Do\n Call o xyhh 'is above' xyu xyh\n Nop\n End\n Else Do\n Call o xyhh 'is under' xyu xyh '-' xyh 'ist nicht gut'\n good=0\n End\n End\n End\n Call o xyh 'is the one'\n Return xyh\n\nNovalue:\n Say 'Novalue raised in line' sigl\n Say sourceline(sigl)\n Say 'Variable' condition('D')\n Signal lookaround\n\nSyntax:\n Say 'Syntax raised in line' sigl\n Say sourceline(sigl)\n Say 'rc='rc '('errortext(rc)')'\n\nhalt:\nlookaround:\n Say 'You can look around now.'\n Trace ?R\n Nop\n Exit 12\n", "language": "REXX" }, { "code": "/* REXX ---------------------------------------------------------------\n* Compute the Convex Hull for a set of points\n* Format of the input file:\n* (16,3) (12,17) (0,6) (-4,-6) (16,6) (16,-7) (16,-3) (17,-4) (5,19)\n* (19,-8) (3,16) (12,13) (3,-4) (17,5) (-3,15) (-3,-9) (0,11) (-9,-3)\n* (-4,-2)\n* Alternate (better) method using slopes\n* 1) Compute path from lowest/leftmost to leftmost/lowest\n* 2) Compute leftmost vertical border\n* 3) Compute path from rightmost/highest to highest/rightmost\n* 4) Compute path from highest/rightmost to rightmost/highest\n* 5) Compute rightmost vertical border\n* 6) Compute path from rightmost/lowest to lowest_leftmost point\n*--------------------------------------------------------------------*/\nParse Arg fid\nIf fid='' Then Do\n fid='line.in'\n fid='point.in'\n fid='chullmin.in' /* miscellaneous test data */\n fid='chullxx.in'\n fid='chullx.in'\n fid='chullt.in'\n fid='chulla.in'\n fid='sq.in'\n fid='tri.in'\n fid='z.in'\n fid='chull.in' /* data from task description */\n End\ng.0debug=''\ng.0oid=fn(fid)'.txt'; 'erase' g.0oid\nx.=0\nyl.=''\nParse Value '1000 -1000' With g.0xmin g.0xmax\nParse Value '1000 -1000' With g.0ymin g.0ymax\n/*---------------------------------------------------------------------\n* First read the input and store the points' coordinates\n* x.0 contains the number of points, x.i contains the x.coordinate\n* yl.x contains the y.coordinate(s) of points (x/y)\n*--------------------------------------------------------------------*/\nDo while lines(fid)>0\n l=linein(fid)\n Do While l<>''\n Parse Var l '(' x ',' y ')' l\n Call store x,y\n End\n End\nCall lineout fid\ng.0xlist=''\nDo i=1 To x.0 /* loop over points */\n x=x.i\n g.0xlist=g.0xlist x\n yl.x=sortv(yl.x) /* sort y-coordinates */\n End\nCall sho\nIf x.0<3 Then Do\n Say 'We need at least three points!'\n Exit\n End\nCall o 'g.0xmin='g.0xmin\nCall o 'g.0xmi ='g.0xmi\nCall o 'g.0ymin='g.0ymin\nCall o 'g.0ymi ='g.0ymi\n\nDo i=1 To x.0\n x=x.i\n If minv(yl.x)=g.0ymin Then Leave\n End\nlowest_leftmost=i\n\nhighest_rightmost=0\nDo i=1 To x.0\n x=x.i\n If maxv(yl.x)=g.0ymax Then\n highest_rightmost=i\n If maxv(yl.x)<g.0ymax Then\n If highest_rightmost>0 Then\n Leave\n End\nCall o 'lowest_leftmost='lowest_leftmost\nCall o 'highest_rightmost ='highest_rightmost\n\nx=x.lowest_leftmost\nCall o 'We start at' from x'/'minv(yl.x)\npath=x'/'minv(yl.x)\n/*---------------------------------------------------------------------\n* 1) Compute path from lowest/leftmost to leftmost/lowest\n*--------------------------------------------------------------------*/\nCall min_path lowest_leftmost,1\n/*---------------------------------------------------------------------\n* 2) Compute leftmost vertical border\n*--------------------------------------------------------------------*/\nDo i=2 To words(yl.x)\n path=path x'/'word(yl.x,i)\n End\ncxy=x'/'maxv(yl.x)\n/*---------------------------------------------------------------------\n* 3) Compute path from rightmost/highest to highest/rightmost\n*--------------------------------------------------------------------*/\nCall max_path ci,highest_rightmost\n/*---------------------------------------------------------------------\n* 4) Compute path from highest/rightmost to rightmost/highest\n*--------------------------------------------------------------------*/\nCall max_path ci,x.0\n/*---------------------------------------------------------------------\n* 5) Compute rightmost vertical border\n*--------------------------------------------------------------------*/\nDo i=words(yl.x)-1 To 1 By -1\n cxy=x'/'word(yl.x,i)\n path=path cxy\n End\n/*---------------------------------------------------------------------\n* 6) Compute path from rightmost/lowest to lowest_leftmost\n*--------------------------------------------------------------------*/\nCall min_path ci,lowest_leftmost\n\nParse Var path pathx path\nhave.=0\nDo i=1 By 1 While path>''\n Parse Var path xy path\n If have.xy=0 Then Do\n pathx=pathx xy\n have.xy=1\n End\n End\nSay 'Points of convex hull in clockwise order:'\nSay pathx\nCall lineout g.0oid\nExit\n\nmin_path:\n Parse Arg from,tgt\n ci=from\n cxy=x.ci\n Do Until ci=tgt\n kmax=-1000\n Do i=ci-1 To 1 By sign(tgt-from)\n x=x.i\n k=k(cxy'/'minv(yl.cxy),x'/'minv(yl.x))\n If k>kmax Then Do\n kmax=k\n ii=i\n End\n End\n ci=ii\n cxy=x.ii\n path=path cxy'/'minv(yl.cxy)\n End\n Return\n\nmax_path:\n Parse Arg from,tgt\n Do Until ci=tgt\n kmax=-1000\n Do i=ci+1 To tgt\n x=x.i\n k=k(cxy,x'/'maxv(yl.x))\n If k>kmax Then Do\n kmax=k\n ii=i\n End\n End\n x=x.ii\n cxy=x'/'maxv(yl.x)\n path=path cxy\n ci=ii\n End\n Return\n\nstore: Procedure Expose x. yl. g.\n/*---------------------------------------------------------------------\n* arrange the points in ascending order of x (in x.) and,\n* for each x in ascending order of y (in yl.x)\n* g.0xmin is the smallest x-value, etc.\n* g.0xmi is the x-coordinate\n* g.0ymin is the smallest y-value, etc.\n* g.0ymi is the x-coordinate of such a point\n*--------------------------------------------------------------------*/\n Parse Arg x,y\n Call o 'store' x y\n If x<g.0xmin Then Do; g.0xmin=x; g.0xmi=x; End\n If x>g.0xmax Then Do; g.0xmax=x; g.0xma=x; End\n If y<g.0ymin Then Do; g.0ymin=y; g.0ymi=x; End\n If y>g.0ymax Then Do; g.0ymax=y; g.0yma=x; End\n Do i=1 To x.0\n Select\n When x.i>x Then\n Leave\n When x.i=x Then Do\n yl.x=yl.x y\n Return\n End\n Otherwise\n Nop\n End\n End\n Do j=x.0 To i By -1\n ja=j+1\n x.ja=x.j\n End\n x.i=x\n yl.x=y\n x.0=x.0+1\n Return\n\nsho: Procedure Expose x. yl. g.\n Do i=1 To x.0\n x=x.i\n say format(i,2) 'x='format(x,3) 'yl='yl.x\n End\n Say ''\n Return\n\nmaxv: Procedure Expose g.\n Call trace 'O'\n Parse Arg l\n res=-1000\n Do While l<>''\n Parse Var l v l\n If v>res Then res=v\n End\n Return res\n\nminv: Procedure Expose g.\n Call trace 'O'\n Parse Arg l\n res=1000\n Do While l<>''\n Parse Var l v l\n If v<res Then res=v\n End\n Return res\n\nsortv: Procedure Expose g.\n Call trace 'O'\n Parse Arg l\n res=''\n Do Until l=''\n v=minv(l)\n res=res v\n l=remove(v,l)\n End\n Return space(res)\n\nlastword: return word(arg(1),words(arg(1)))\n\nk: Procedure\n/*---------------------------------------------------------------------\n* Compute slope of a straight line\n* that is defined by two points: y=k*x+d\n* Specialty; k='*' x=xa if xb=xa\n*--------------------------------------------------------------------*/\n Call trace 'O'\n Parse Arg xya,xyb\n Parse Var xya xa '/' ya\n Parse Var xyb xb '/' yb\n If xa=xb Then\n k='*'\n Else\n k=(yb-ya)/(xb-xa)\n Return k\n\nremove:\n/*---------------------------------------------------------------------\n* Remove a specified element (e) from a given string (s)\n*--------------------------------------------------------------------*/\n Parse Arg e,s\n Parse Var s sa (e) sb\n Return space(sa sb)\n\no: Procedure Expose g.\n/*---------------------------------------------------------------------\n* Write a line to the debug file\n*--------------------------------------------------------------------*/\n If arg(2)=1 Then say arg(1)\n Return lineout(g.0oid,arg(1))\n", "language": "REXX" }, { "code": "class Point\n include Comparable\n attr :x, :y\n\n def initialize(x, y)\n @x = x\n @y = y\n end\n\n def <=>(other)\n x <=> other.x\n end\n\n def to_s\n \"(%d, %d)\" % [@x, @y]\n end\n\n def to_str\n to_s()\n end\nend\n\ndef ccw(a, b, c)\n ((b.x - a.x) * (c.y - a.y)) > ((b.y - a.y) * (c.x - a.x))\nend\n\ndef convexHull(p)\n if p.length == 0 then\n return []\n end\n\n p = p.sort\n h = []\n\n # Lower hull\n p.each { |pt|\n while h.length >= 2 and not ccw(h[-2], h[-1], pt)\n h.pop()\n end\n h << pt\n }\n\n # upper hull\n t = h.length + 1\n p.reverse.each { |pt|\n while h.length >= t and not ccw(h[-2], h[-1], pt)\n h.pop()\n end\n h << pt\n }\n\n h.pop()\n h\nend\n\ndef main\n points = [\n Point.new(16, 3), Point.new(12, 17), Point.new( 0, 6), Point.new(-4, -6), Point.new(16, 6),\n Point.new(16, -7), Point.new(16, -3), Point.new(17, -4), Point.new( 5, 19), Point.new(19, -8),\n Point.new( 3, 16), Point.new(12, 13), Point.new( 3, -4), Point.new(17, 5), Point.new(-3, 15),\n Point.new(-3, -9), Point.new( 0, 11), Point.new(-9, -3), Point.new(-4, -2), Point.new(12, 10)\n ]\n hull = convexHull(points)\n print \"Convex Hull: [\", hull.join(\", \"), \"]\\n\"\nend\n\nmain()\n", "language": "Ruby" }, { "code": "#[derive(Debug, Clone)]\nstruct Point {\n x: f32,\n y: f32\n}\n\nfn calculate_convex_hull(points: &Vec<Point>) -> Vec<Point> {\n //There must be at least 3 points\n if points.len() < 3 { return points.clone(); }\n\n let mut hull = vec![];\n\n //Find the left most point in the polygon\n let (left_most_idx, _) = points.iter()\n .enumerate()\n .min_by(|lhs, rhs| lhs.1.x.partial_cmp(&rhs.1.x).unwrap())\n .expect(\"No left most point\");\n\n\n let mut p = left_most_idx;\n let mut q = 0_usize;\n\n loop {\n //The left most point must be part of the hull\n hull.push(points[p].clone());\n\n q = (p + 1) % points.len();\n\n for i in 0..points.len() {\n if orientation(&points[p], &points[i], &points[q]) == 2 {\n q = i;\n }\n }\n\n p = q;\n\n //Break from loop once we reach the first point again\n if p == left_most_idx { break; }\n }\n\n return hull;\n}\n\n//Calculate orientation for 3 points\n//0 -> Straight line\n//1 -> Clockwise\n//2 -> Counterclockwise\nfn orientation(p: &Point, q: &Point, r: &Point) -> usize {\n let val = (q.y - p.y) * (r.x - q.x) -\n (q.x - p.x) * (r.y - q.y);\n\n if val == 0. { return 0 };\n if val > 0. { return 1; } else { return 2; }\n}\n\nfn main(){\n let points = vec![pt(16,3), pt(12,17), pt(0,6), pt(-4,-6), pt(16,6), pt(16,-7), pt(16,-3), pt(17,-4), pt(5,19), pt(19,-8), pt(3,16), pt(12,13), pt(3,-4), pt(17,5), pt(-3,15), pt(-3,-9), pt(0,11), pt(-9,-3), pt(-4,-2), pt(12,10)];\n let hull = calculate_convex_hull(&points);\n\n hull.iter()\n .for_each(|pt| println!(\"{:?}\", pt));\n}\n\nfn pt(x: i32, y: i32) -> Point {\n return Point {x:x as f32, y:y as f32};\n}\n", "language": "Rust" }, { "code": "object convex_hull{\n def get_hull(points:List[(Double,Double)], hull:List[(Double,Double)]):List[(Double,Double)] = points match{\n case Nil => join_tail(hull,hull.size -1)\n case head :: tail => get_hull(tail,reduce(head::hull))\n }\n def reduce(hull:List[(Double,Double)]):List[(Double,Double)] = hull match{\n case p1::p2::p3::rest => {\n if(check_point(p1,p2,p3)) hull\n else reduce(p1::p3::rest)\n }\n case _ => hull\n }\n def check_point(pnt:(Double,Double), p2:(Double,Double),p1:(Double,Double)): Boolean = {\n val (x,y) = (pnt._1,pnt._2)\n val (x1,y1) = (p1._1,p1._2)\n val (x2,y2) = (p2._1,p2._2)\n ((x-x1)*(y2-y1) - (x2-x1)*(y-y1)) <= 0\n }\n def m(p1:(Double,Double), p2:(Double,Double)):Double = {\n if(p2._1 == p1._1 && p1._2>p2._2) 90\n else if(p2._1 == p1._1 && p1._2<p2._2) -90\n else if(p1._1<p2._1) 180 - Math.toDegrees(Math.atan(-(p1._2 - p2._2)/(p1._1 - p2._1)))\n else Math.toDegrees(Math.atan((p1._2 - p2._2)/(p1._1 - p2._1)))\n }\n def join_tail(hull:List[(Double,Double)],len:Int):List[(Double,Double)] = {\n if(m(hull(len),hull(0)) > m(hull(len-1),hull(0))) join_tail(hull.slice(0,len),len-1)\n else hull\n }\n def main(args:Array[String]){\n val points = List[(Double,Double)]((16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2), (12,10))\n val sorted_points = points.sortWith(m(_,(0.0,0.0)) < m(_,(0.0,0.0)))\n println(f\"Points:\\n\" + points + f\"\\n\\nConvex Hull :\\n\" +get_hull(sorted_points,List[(Double,Double)]()))\n }\n}\n", "language": "Scala" }, { "code": "(define-library (convex-hulls)\n\n (export vector-convex-hull)\n (export list-convex-hull)\n\n (import (scheme base))\n (import (srfi 132)) ; Sorting.\n\n (begin\n\n ;;\n ;; The implementation is based on Andrew's monotone chain\n ;; algorithm, and is adapted from a Fortran implementation I wrote\n ;; myself in 2011.\n ;;\n ;; For a description of the algorithm, see\n ;; https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=4016938\n ;;\n\n (define x@ car)\n (define y@ cadr)\n\n (define (cross u v)\n ;; Cross product (as a signed scalar).\n (- (* (x@ u) (y@ v)) (* (y@ u) (x@ v))))\n\n (define (point- u v)\n (list (- (x@ u) (x@ v)) (- (y@ u) (y@ v))))\n\n (define (sort-points-vector points-vector)\n ;; Ascending sort on x-coordinates, followed by ascending sort\n ;; on y-coordinates.\n (vector-sort (lambda (u v)\n (or (< (x@ u) (x@ v))\n (and (= (x@ u) (x@ v))\n (< (y@ u) (y@ v)))))\n points-vector))\n\n (define (construct-lower-hull sorted-points-vector)\n (let* ((pt sorted-points-vector)\n (n (vector-length pt))\n (hull (make-vector n))\n (j 1))\n (vector-set! hull 0 (vector-ref pt 0))\n (vector-set! hull 1 (vector-ref pt 1))\n (do ((i 2 (+ i 1)))\n ((= i n))\n (let inner-loop ()\n (if (or (zero? j)\n (positive?\n (cross (point- (vector-ref hull j)\n (vector-ref hull (- j 1)))\n (point- (vector-ref pt i)\n (vector-ref hull (- j 1))))))\n (begin\n (set! j (+ j 1))\n (vector-set! hull j (vector-ref pt i)))\n (begin\n (set! j (- j 1))\n (inner-loop)))))\n (values (+ j 1) hull))) ; Hull size, hull points.\n\n (define (construct-upper-hull sorted-points-vector)\n (let* ((pt sorted-points-vector)\n (n (vector-length pt))\n (hull (make-vector n))\n (j 1))\n (vector-set! hull 0 (vector-ref pt (- n 1)))\n (vector-set! hull 1 (vector-ref pt (- n 2)))\n (do ((i (- n 3) (- i 1)))\n ((= i -1))\n (let inner-loop ()\n (if (or (zero? j)\n (positive?\n (cross (point- (vector-ref hull j)\n (vector-ref hull (- j 1)))\n (point- (vector-ref pt i)\n (vector-ref hull (- j 1))))))\n (begin\n (set! j (+ j 1))\n (vector-set! hull j (vector-ref pt i)))\n (begin\n (set! j (- j 1))\n (inner-loop)))))\n (values (+ j 1) hull))) ; Hull size, hull points.\n\n (define (construct-hull sorted-points-vector)\n ;; Notice that the lower and upper hulls could be constructed in\n ;; parallel.\n (let-values (((lower-hull-size lower-hull)\n (construct-lower-hull sorted-points-vector))\n ((upper-hull-size upper-hull)\n (construct-upper-hull sorted-points-vector)))\n (let* ((hull-size (+ lower-hull-size upper-hull-size -2))\n (hull (make-vector hull-size)))\n (vector-copy! hull 0 lower-hull 0 (- lower-hull-size 1))\n (vector-copy! hull (- lower-hull-size 1) upper-hull\n 0 (- upper-hull-size 1))\n hull)))\n\n (define (vector-convex-hull points)\n (let* ((points-vector (if (vector? points)\n points\n (list->vector points)))\n (sorted-points-vector\n (vector-delete-neighbor-dups\n equal?\n (sort-points-vector points-vector))))\n (if (<= (vector-length sorted-points-vector) 2)\n sorted-points-vector\n (construct-hull sorted-points-vector))))\n\n (define (list-convex-hull points)\n (vector->list (vector-convex-hull points)))\n\n )) ;; end of library convex-hulls.\n\n;;\n;; A demonstration.\n;;\n\n(import (scheme base))\n(import (scheme write))\n(import (convex-hulls))\n\n(define example-points\n '((16 3) (12 17) (0 6) (-4 -6) (16 6)\n (16 -7) (16 -3) (17 -4) (5 19) (19 -8)\n (3 16) (12 13) (3 -4) (17 5) (-3 15)\n (-3 -9) (0 11) (-9 -3) (-4 -2) (12 10)))\n\n(write (list-convex-hull example-points))\n(newline)\n", "language": "Scheme" }, { "code": "(define-library (convex-hulls)\n\n (export convex-hull)\n\n (import (scheme base))\n (import (only (srfi 1) fold))\n (import (only (srfi 1) append!))\n (import (only (srfi 132) list-sort))\n (import (only (srfi 132) list-delete-neighbor-dups))\n\n (begin\n\n ;;\n ;; Andrew's monotone chain algorithm for the convex hull in a\n ;; plane.\n ;;\n ;; For a description of the algorithm, see\n ;; https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=4016938\n ;;\n\n (define x@ car)\n (define y@ cadr)\n\n (define (cross u v)\n ;; Cross product (as a signed scalar).\n (- (* (x@ u) (y@ v)) (* (y@ u) (x@ v))))\n\n (define (point- u v)\n (list (- (x@ u) (x@ v)) (- (y@ u) (y@ v))))\n\n (define (point=? u v)\n (and (= (x@ u) (x@ v)) (= (y@ u) (y@ v))))\n\n (define (point<? u v)\n (let ((xu (x@ u))\n (xv (x@ v)))\n (or (< xu xv) (and (= xu xv) (< (y@ u) (y@ v))))))\n\n (define (convex-hull points-list)\n (let* ((points (list-delete-neighbor-dups\n point=? (list-sort point<? points-list)))\n (n (length points)))\n (cond\n ((<= n 2) points)\n (else\n (let ((half-hull (make-vector n)))\n (define (cross-test pt j)\n (or (zero? j)\n (let ((elem-j (vector-ref half-hull j))\n (elem-j1 (vector-ref half-hull (- j 1))))\n (positive? (cross (point- elem-j elem-j1)\n (point- pt elem-j1))))))\n (define (construct-half-hull points)\n (vector-set! half-hull 0 (car points))\n (vector-set! half-hull 1 (cadr points))\n (fold (lambda (pt j)\n (let loop ((j j))\n (if (cross-test pt j)\n (let ((j1 (+ j 1)))\n (vector-set! half-hull j1 pt)\n j1)\n (loop (- j 1)))))\n 1 (cddr points)))\n (let* ((lower-hull\n ;; Leave out the last point, which is the same\n ;; as the first point of the upper hull.\n (let ((j (construct-half-hull points)))\n (vector->list half-hull 0 j)))\n (upper-hull\n ;; Leave out the last point, which is the same\n ;; as the first point of the lower hull.\n (let ((j (construct-half-hull (reverse points))))\n (vector->list half-hull 0 j))))\n (append! lower-hull upper-hull)))))))\n\n )) ;; end of library convex-hulls.\n\n;;\n;; A demonstration.\n;;\n\n(import (scheme base))\n(import (scheme write))\n(import (convex-hulls))\n\n(define example-points\n '((16 3) (12 17) (0 6) (-4 -6) (16 6)\n (16 -7) (16 -3) (17 -4) (5 19) (19 -8)\n (3 16) (12 13) (3 -4) (17 5) (-3 15)\n (-3 -9) (0 11) (-9 -3) (-4 -2) (12 10)))\n\n(write (convex-hull example-points))\n(newline)\n", "language": "Scheme" }, { "code": "class Point(Number x, Number y) {\n method to_s {\n \"(#{x}, #{y})\"\n }\n}\n\nfunc ccw (Point a, Point b, Point c) {\n (b.x - a.x)*(c.y - a.y) - (b.y - a.y)*(c.x - a.x)\n}\n\nfunc tangent (Point a, Point b) {\n (b.x - a.x) / (b.y - a.y)\n}\n\nfunc graham_scan (*coords) {\n\n ## sort points by y, secondary sort on x\n var sp = coords.map { |a|\n Point(a...)\n }.sort { |a,b|\n (a.y <=> b.y) ||\n (a.x <=> b.x)\n }\n\n # need at least 3 points to make a hull\n if (sp.len < 3) {\n return sp\n }\n\n # first point on hull is minimum y point\n var h = [sp.shift]\n\n # re-sort the points by angle, secondary on x\n sp = sp.map_kv { |k,v|\n Pair(k, [tangent(h[0], v), v.x])\n }.sort { |a,b|\n (b.value[0] <=> a.value[0]) ||\n (a.value[1] <=> b.value[1])\n }.map { |a|\n sp[a.key]\n }\n\n # first point of re-sorted list is guaranteed to be on hull\n h << sp.shift\n\n # check through the remaining list making sure that\n # there is always a positive angle\n sp.each { |point|\n loop {\n if (ccw(h.last(2)..., point) >= 0) {\n h << point\n break\n } else {\n h.pop\n }\n }\n }\n\n return h\n}\n\nvar hull = graham_scan(\n [16, 3], [12,17], [ 0, 6], [-4,-6], [16, 6], [16,-7], [16,-3],\n [17,-4], [ 5,19], [19,-8], [ 3,16], [12,13], [ 3,-4], [17, 5],\n [-3,15], [-3,-9], [ 0,11], [-9,-3], [-4,-2], [12,10])\n\nsay(\"Convex Hull (#{hull.len} points): \", hull.join(\" \"))\n\nhull = graham_scan(\n [16, 3], [12,17], [ 0, 6], [-4,-6], [16, 6], [16,-7], [16,-3],\n [17,-4], [ 5,19], [19,-8], [ 3,16], [12,13], [ 3,-4], [17, 5],\n [-3,15], [-3,-9], [ 0,11], [-9,-3], [-4,-2], [12,10], [14,-9], [1,-9])\n\nsay(\"Convex Hull (#{hull.len} points): \", hull.join(\" \"))\n", "language": "Sidef" }, { "code": "(*\n * Convex hulls by Andrew's monotone chain algorithm.\n *\n * For a description of the algorithm, see\n * https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169\n *)\n\n(*------------------------------------------------------------------*)\n(*\n * Just enough plane geometry for our purpose.\n *)\n\nsignature PLANE_POINT =\nsig\n type planePoint\n val planePoint : real * real -> planePoint\n val toTuple : planePoint -> real * real\n val x : planePoint -> real\n val y : planePoint -> real\n val == : planePoint * planePoint -> bool\n\n (* Impose a total order on points, making it one that will work for\n Andrew's monotone chain algorithm. *)\n val order : planePoint * planePoint -> bool\n\n (* Subtraction is really a vector or multivector operation. *)\n val subtract : planePoint * planePoint -> planePoint\n\n (* Cross product is really a multivector operation. *)\n val cross : planePoint * planePoint -> real\n\n val toString : planePoint -> string\nend\n\nstructure PlanePoint : PLANE_POINT =\nstruct\ntype planePoint = real * real\n\nfun planePoint xy = xy\nfun toTuple (x, y) = (x, y)\nfun x (x, _) = x\nfun y (_, y) = y\n\nfun == ((a : real, b : real), (c : real, d : real)) =\n Real.== (a, c) andalso Real.== (b, d)\n\nfun order ((a : real, b : real), (c : real, d : real)) =\n Real.< (a, c) orelse (Real.== (a, c) andalso Real.< (b, d))\n\nfun subtract ((a : real, b : real), (c : real, d : real)) =\n (a - c, b - d)\n\nfun cross ((a : real, b : real), (c : real, d : real)) =\n (a * d) - (b * c)\n\nfun toString (x, y) =\n \"(\" ^ Real.toString x ^ \" \" ^ Real.toString y ^ \")\"\nend\n\n(*------------------------------------------------------------------*)\n(*\n * Rather than rely on compiler extensions for sorting, let us write\n * our own.\n *\n * For no special reason, let us use the Shell sort of\n * https://en.wikipedia.org/w/index.php?title=Shellsort&oldid=1084744510\n *)\n\nval ciura_gaps = Array.fromList [701, 301, 132, 57, 23, 10, 4, 1]\n\nfun sort_in_place less arr =\n let\n open Array\n\n fun span_gap gap =\n let\n fun iloop i =\n if length arr <= i then\n ()\n else\n let\n val temp = sub (arr, i)\n fun jloop j =\n if j < gap orelse\n less (sub (arr, j - gap), temp) then\n update (arr, j, temp)\n else\n (update (arr, j, sub (arr, j - gap));\n jloop (j - gap))\n in\n jloop i;\n iloop (i + gap)\n end\n in\n iloop 0\n end\n in\n app span_gap ciura_gaps\n end\n\n(*------------------------------------------------------------------*)\n(*\n * To go with our sort routine, we want something akin to\n * array_delete_neighbor_dups of Scheme's SRFI-132.\n *)\n\nfun array_delete_neighbor_dups equal arr =\n let\n open Array\n\n fun loop i lst =\n (* Cons a list of non-duplicates, going backwards through\n the array so the list will be in forwards order. *)\n if i = 0 then\n sub (arr, i) :: lst\n else if equal (sub (arr, i - 1), sub (arr, i)) then\n loop (i - 1) lst\n else\n loop (i - 1) (sub (arr, i) :: lst)\n\n val n = length arr\n in\n fromList (if n = 0 then [] else loop (n - 1) [])\n end\n\n(*------------------------------------------------------------------*)\n(*\n * The convex hull algorithm.\n *)\n\nfun cross_test (pt_i, hull, j) =\n let\n open PlanePoint\n val hull_j = Array.sub (hull, j)\n val hull_j1 = Array.sub (hull, j - 1)\n in\n 0.0 < cross (subtract (hull_j, hull_j1),\n subtract (pt_i, hull_j1))\n end\n\nfun construct_lower_hull (n, pt) =\n let\n open PlanePoint\n\n val hull = Array.array (n, planePoint (0.0, 0.0))\n val () = Array.update (hull, 0, Array.sub (pt, 0))\n val () = Array.update (hull, 1, Array.sub (pt, 1))\n\n fun outer_loop i j =\n if i = n then\n j + 1\n else\n let\n val pt_i = Array.sub (pt, i)\n\n fun inner_loop j =\n if j = 0 orelse cross_test (pt_i, hull, j) then\n (Array.update (hull, j + 1, pt_i);\n j + 1)\n else\n inner_loop (j - 1)\n in\n outer_loop (i + 1) (inner_loop j)\n end\n\n val hull_size = outer_loop 2 1\n in\n (hull_size, hull)\n end\n\nfun construct_upper_hull (n, pt) =\n let\n open PlanePoint\n\n val hull = Array.array (n, planePoint (0.0, 0.0))\n val () = Array.update (hull, 0, Array.sub (pt, n - 1))\n val () = Array.update (hull, 1, Array.sub (pt, n - 2))\n\n fun outer_loop i j =\n if i = ~1 then\n j + 1\n else\n let\n val pt_i = Array.sub (pt, i)\n\n fun inner_loop j =\n if j = 0 orelse cross_test (pt_i, hull, j) then\n (Array.update (hull, j + 1, pt_i);\n j + 1)\n else\n inner_loop (j - 1)\n in\n outer_loop (i - 1) (inner_loop j)\n end\n\n val hull_size = outer_loop (n - 3) 1\n in\n (hull_size, hull)\n end\n\nfun construct_hull (n, pt) =\n let\n (* Side note: Construction of the lower and upper hulls can be\n done in parallel. *)\n val (lower_hull_size, lower_hull) = construct_lower_hull (n, pt)\n and (upper_hull_size, upper_hull) = construct_upper_hull (n, pt)\n\n val hull_size = lower_hull_size + upper_hull_size - 2\n val hull =\n Array.array (hull_size, PlanePoint.planePoint (0.0, 0.0))\n\n fun copy_lower i =\n if i = lower_hull_size - 1 then\n ()\n else\n (Array.update (hull, i, Array.sub (lower_hull, i));\n copy_lower (i + 1))\n\n fun copy_upper i =\n if i = upper_hull_size - 1 then\n ()\n else\n (Array.update (hull, i + lower_hull_size - 1,\n Array.sub (upper_hull, i));\n copy_upper (i + 1))\n in\n copy_lower 0;\n copy_upper 0;\n hull\n end\n\nfun plane_convex_hull points_lst =\n (* Takes an arbitrary list of points, which may be in any order\n and may contain duplicates. Returns an ordered array of points\n that make up the convex hull. If the list of points is empty,\n the returned array is empty. *)\n let\n val pt = Array.fromList points_lst\n val () = sort_in_place PlanePoint.order pt\n val pt = array_delete_neighbor_dups (PlanePoint.==) pt\n val n = Array.length pt\n in\n if n <= 2 then\n pt\n else\n construct_hull (n, pt)\n end\n\n(*------------------------------------------------------------------*)\n\nfun main () =\n let\n open PlanePoint\n\n val example_points =\n [planePoint (16.0, 3.0),\n planePoint (12.0, 17.0),\n planePoint (0.0, 6.0),\n planePoint (~4.0, ~6.0),\n planePoint (16.0, 6.0),\n planePoint (16.0, ~7.0),\n planePoint (16.0, ~3.0),\n planePoint (17.0, ~4.0),\n planePoint (5.0, 19.0),\n planePoint (19.0, ~8.0),\n planePoint (3.0, 16.0),\n planePoint (12.0, 13.0),\n planePoint (3.0, ~4.0),\n planePoint (17.0, 5.0),\n planePoint (~3.0, 15.0),\n planePoint (~3.0, ~9.0),\n planePoint (0.0, 11.0),\n planePoint (~9.0, ~3.0),\n planePoint (~4.0, ~2.0),\n planePoint (12.0, 10.0)]\n\n val hull = plane_convex_hull example_points\n in\n Array.app (fn p => (print (toString p);\n print \" \"))\n hull;\n print \"\\n\"\n end;\n\nmain ();\n\n(*------------------------------------------------------------------*)\n(* local variables: *)\n(* mode: sml *)\n(* sml-indent-level: 2 *)\n(* sml-indent-args: 2 *)\n(* end: *)\n", "language": "Standard-ML" }, { "code": "public struct Point: Equatable, Hashable {\n public var x: Double\n public var y: Double\n\n public init(fromTuple t: (Double, Double)) {\n self.x = t.0\n self.y = t.1\n }\n}\n\npublic func calculateConvexHull(fromPoints points: [Point]) -> [Point] {\n guard points.count >= 3 else {\n return points\n }\n\n var hull = [Point]()\n let (leftPointIdx, _) = points.enumerated().min(by: { $0.element.x < $1.element.x })!\n\n var p = leftPointIdx\n var q = 0\n\n repeat {\n hull.append(points[p])\n\n q = (p + 1) % points.count\n\n for i in 0..<points.count where calculateOrientation(points[p], points[i], points[q]) == .counterClockwise {\n q = i\n }\n\n p = q\n } while p != leftPointIdx\n\n return hull\n}\n\nprivate func calculateOrientation(_ p: Point, _ q: Point, _ r: Point) -> Orientation {\n let val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)\n\n if val == 0 {\n return .straight\n } else if val > 0 {\n return .clockwise\n } else {\n return .counterClockwise\n }\n}\n\nprivate enum Orientation {\n case straight, clockwise, counterClockwise\n}\n\nlet points = [\n (16,3),\n (12,17),\n (0,6),\n (-4,-6),\n (16,6),\n (16,-7),\n (16,-3),\n (17,-4),\n (5,19),\n (19,-8),\n (3,16),\n (12,13),\n (3,-4),\n (17,5),\n (-3,15),\n (-3,-9),\n (0,11),\n (-9,-3),\n (-4,-2),\n (12,10)\n].map(Point.init(fromTuple:))\n\nprint(\"Input: \\(points)\")\nprint(\"Output: \\(calculateConvexHull(fromPoints: points))\")\n", "language": "Swift" }, { "code": "catch {namespace delete test_convex_hull} ;# Start with a clean namespace\n\nnamespace eval test_convex_hull {\n package require Tcl 8.5 ;# maybe earlier?\n interp alias {} @ {} lindex;# An essential readability helper for list indexing\n\n proc cross {o a b} {\n ### 2D cross product of OA and OB vectors ###\n return [expr {([@ $a 0] - [@ $o 0]) * ([@ $b 1] - [@ $o 1]) - ([@ $a 1] - [@ $o 1]) * ([@ $b 0] - [@ $o 0]) }]\n }\n\n proc calc_hull_edge {points} {\n ### Build up hull edge ###\n set edge [list]\n foreach p $points {\n while {[llength $edge ] >= 2 && [cross [@ $edge end-1] [@ $edge end] $p] <= 0} {\n set edge [lreplace $edge end end] ;# pop\n }\n lappend edge $p\n }\n return $edge\n }\n\n proc convex_hull {points} {\n ### Convex hull of a set of 2D points ###\n\n # Unique points\n set points [lsort -unique $points]\n\n # Sorted points\n set points [lsort -real -index 0 [lsort -real -index 1 $points]]\n\n # No calculation necessary\n if {[llength $points] <= 1} {\n return $points\n }\n\n set lower [calc_hull_edge $points]\n set upper [calc_hull_edge [lreverse $points]]\n\n return [concat [lrange $lower 0 end-1] [lrange $upper 0 end-1]]\n }\n\n # Testing\n set tpoints {{16 3} {12 17} {0 6} {-4 -6} {16 6} {16 -7} {16 -3} {17 -4} {5 19} {19 -8}\n {3 16} {12 13} {3 -4} {17 5} {-3 15} {-3 -9} {0 11} {-9 -3} {-4 -2} {12 10}}\n\n puts \"Test points:\"\n puts [lrange $tpoints 0 end] ;# prettier\n puts \"Convex Hull:\"\n puts [convex_hull $tpoints]\n}\n", "language": "Tcl" }, { "code": "Imports ConvexHull\n\nModule Module1\n\n Class Point : Implements IComparable(Of Point)\n Public Property X As Integer\n Public Property Y As Integer\n\n Public Sub New(x As Integer, y As Integer)\n Me.X = x\n Me.Y = y\n End Sub\n\n Public Function CompareTo(other As Point) As Integer Implements IComparable(Of Point).CompareTo\n Return X.CompareTo(other.X)\n End Function\n\n Public Overrides Function ToString() As String\n Return String.Format(\"({0}, {1})\", X, Y)\n End Function\n End Class\n\n Function ConvexHull(p As List(Of Point)) As List(Of Point)\n If p.Count = 0 Then\n Return New List(Of Point)\n End If\n p.Sort()\n Dim h As New List(Of Point)\n\n ' Lower hull\n For Each pt In p\n While h.Count >= 2 AndAlso Not Ccw(h(h.Count - 2), h(h.Count - 1), pt)\n h.RemoveAt(h.Count - 1)\n End While\n h.Add(pt)\n Next\n\n ' Upper hull\n Dim t = h.Count + 1\n For i = p.Count - 1 To 0 Step -1\n Dim pt = p(i)\n While h.Count >= t AndAlso Not Ccw(h(h.Count - 2), h(h.Count - 1), pt)\n h.RemoveAt(h.Count - 1)\n End While\n h.Add(pt)\n Next\n\n h.RemoveAt(h.Count - 1)\n Return h\n End Function\n\n Function Ccw(a As Point, b As Point, c As Point) As Boolean\n Return ((b.X - a.X) * (c.Y - a.Y)) > ((b.Y - a.Y) * (c.X - a.X))\n End Function\n\n Sub Main()\n Dim points As New List(Of Point) From {\n New Point(16, 3),\n New Point(12, 17),\n New Point(0, 6),\n New Point(-4, -6),\n New Point(16, 6),\n New Point(16, -7),\n New Point(16, -3),\n New Point(17, -4),\n New Point(5, 19),\n New Point(19, -8),\n New Point(3, 16),\n New Point(12, 13),\n New Point(3, -4),\n New Point(17, 5),\n New Point(-3, 15),\n New Point(-3, -9),\n New Point(0, 11),\n New Point(-9, -3),\n New Point(-4, -2),\n New Point(12, 10)\n }\n\n Dim hull = ConvexHull(points)\n Dim it = hull.GetEnumerator()\n Console.Write(\"Convex Hull: [\")\n If it.MoveNext() Then\n Console.Write(it.Current)\n End If\n While it.MoveNext()\n Console.Write(\", {0}\", it.Current)\n End While\n Console.WriteLine(\"]\")\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./sort\" for Sort\nimport \"./trait\" for Comparable\nimport \"./iterate\" for Stepped\n\nclass Point is Comparable {\n construct new(x, y) {\n _x = x\n _y = y\n }\n\n x { _x }\n y { _y }\n\n compare(other) { (_x != other.x) ? (_x - other.x).sign : (_y - other.y).sign }\n\n toString { \"(%(_x), %(_y))\" }\n}\n\n/* ccw returns true if the three points make a counter-clockwise turn */\nvar ccw = Fn.new { |a, b, c| ((b.x - a.x) * (c.y - a.y)) > ((b.y - a.y) * (c.x - a.x)) }\n\nvar convexHull = Fn.new { |pts|\n if (pts.isEmpty) return []\n Sort.quick(pts)\n var h = []\n\n // lower hull\n for (pt in pts) {\n while (h.count >= 2 && !ccw.call(h[-2], h[-1], pt)) h.removeAt(-1)\n h.add(pt)\n }\n\n // upper hull\n var t = h.count + 1\n for (i in Stepped.descend(pts.count-2..0, 1)) {\n var pt = pts[i]\n while (h.count >= t && !ccw.call(h[-2], h[-1], pt)) h.removeAt(-1)\n h.add(pt)\n }\n\n h.removeAt(-1)\n return h\n}\n\nvar pts = [\n Point.new(16, 3), Point.new(12, 17), Point.new( 0, 6), Point.new(-4, -6), Point.new(16, 6),\n Point.new(16, -7), Point.new(16, -3), Point.new(17, -4), Point.new( 5, 19), Point.new(19, -8),\n Point.new( 3, 16), Point.new(12, 13), Point.new( 3, -4), Point.new(17, 5), Point.new(-3, 15),\n Point.new(-3, -9), Point.new( 0, 11), Point.new(-9, -3), Point.new(-4, -2), Point.new(12, 10)\n]\nSystem.print(\"Convex Hull: %(convexHull.call(pts))\")\n", "language": "Wren" }, { "code": "func real CosAng(A, B); \\Return cosine of angle between vectors A and B\nint A, B; \\Cos(Ang) = DotProd / (|A|*|B|)\nreal DotProd, Magnitude;\n[DotProd:= float( A(0)*B(0) + A(1)*B(1));\nMagnitude:= sqrt(float( sq(B(0)-A(0)) + sq(B(1)-A(1)) ));\nreturn DotProd / Magnitude;\n];\n\nproc ConvexHull(N, P);\nint N, P;\nint Min, I, HullI, EndI, A(2), B(2), J, SJ;\nreal Ang, MinAng;\n[Min:= -1>>1; \\find index of point with smallest X coordinate\nfor I:= 0 to N-1 do\n if P(I,0) < Min then\n [Min:= P(I,0); HullI:= I];\nEndI:= HullI;\n\nA(0):= 0; A(1):= -1;\nrepeat ChOut(0, ^();\n IntOut(0, P(HullI,0)); ChOut(0, ^,); IntOut(0, P(HullI,1));\n ChOut(0, ^));\n MinAng:= -1e12; \\find index of point with smallest diverting angle\n for J:= 0 to N-1 do\n [B(0):= P(J,0) - P(HullI,0); B(1):= P(J,1) - P(HullI,1);\n Ang:= CosAng(A, B);\n if Ang > MinAng and J # HullI then\n [MinAng:= Ang; SJ:= J];\n ];\n A(0):= P(SJ,0) - P(HullI,0); A(1):= P(SJ,1) - P(HullI,1);\n HullI:= SJ;\n if HullI # EndI then Text(0, \", \");\nuntil HullI = EndI;\n];\n\nConvexHull(20, [[16,3], [12,17], [0,6], [-4,-6], [16,6], [16,-7], [16,-3],\n [17,-4], [5,19], [19,-8], [3,16], [12,13], [3,-4], [17,5],\n [-3,15], [-3,-9], [0,11], [-9,-3], [-4,-2], [12,10]])\n", "language": "XPL0" }, { "code": "// Use Graham Scan to sort points into a convex hull\n// https://en.wikipedia.org/wiki/Graham_scan, O(n log n)\n// http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/\n// http://geomalgorithms.com/a10-_hull-1.html\nfcn grahamScan(points){\n N:=points.len();\n # find the point with the lowest y-coordinate, x is tie breaker\n p0:=points.reduce(fcn([(a,b)]ab,[(x,y)]xy){\n\tif(b<y)ab else if(b==y and a<x)ab else xy });\n #sort points by polar angle with p0, ie ccw from p0\n points.sort('wrap(p1,p2){ ccw(p0,p1,p2)>0 });\n\n # We want points[0] to be a sentinel point that will stop the loop.\n points.insert(0,points[-1]);\n M:=1; # M will denote the number of points on the convex hull.\n foreach i in ([2..N]){\n # Find next valid point on convex hull.\n while(ccw(points[M-1], points[M], points[i])<=0){\n\t if(M>1) M-=1;\n\t else if(i==N) break; # All points are collinear\n\t else i+=1;\n }\n points.swap(M+=1,i); # Update M and swap points[i] to the correct place.\n }\n points[0,M]\n}\n# Three points are a counter-clockwise turn if ccw > 0, clockwise if\n# ccw < 0, and collinear if ccw = 0 because ccw is a determinant that\n# gives twice the signed area of the triangle formed by p1, p2 and p3.\nfcn ccw(a,b,c){ // a,b,c are points: (x,y)\n ((b[0] - a[0])*(c[1] - a[1])) - ((b[1] - a[1])*(c[0] - a[0]))\n}\n", "language": "Zkl" }, { "code": "pts:=List( T(16,3), T(12,17), T(0,6), T(-4,-6), T(16,6),\n\t T(16, -7), T(16,-3),T(17,-4), T(5,19), T(19,-8),\n\t T(3,16), T(12,13), T(3,-4), T(17,5), T(-3,15),\n\t T(-3,-9), T(0,11), T(-9,-3), T(-4,-2), T(12,10), )\n\t .apply(fcn(xy){ xy.apply(\"toFloat\") }).copy();\nhull:=grahamScan(pts);\nprintln(\"Convex Hull (%d points): %s\".fmt(hull.len(),hull.toString(*)));\n", "language": "Zkl" } ]
Convex-hull
[ { "code": "---\ncategory:\n- String manipulation\n- Simple\n- Strings\nfrom: http://rosettacode.org/wiki/Copy_a_string\nnote: Basic language learning\n", "language": "00-META" }, { "code": "This task is about copying a string. \n\n\n;Task:\nWhere it is relevant, distinguish between copying the contents of a string \nversus making an additional reference to an existing string.\n\n\n{{Template:Strings}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "V src = ‘hello’\nV dst = copy(src)\n", "language": "11l" }, { "code": "* Duplicate a string\n MVC A,=CL64'Hello' a='Hello'\n MVC B,A b=a memory copy\n MVC A,=CL64'Goodbye' a='Goodbye'\n XPRNT A,L'A print a\n XPRNT B,L'B print b\n ...\n* Make reference to a string a string\n MVC A,=CL64'Hi!' a='Hi!'\n LA R1,A r1=@a set pointer\n ST R1,REFA refa=@a store pointer\n XPRNT A,L'A print a\n XPRNT 0(R1),L'A print %refa\n ...\nA DS CL64 a\nB DS CL64 b\nREFA DS A @a\n", "language": "360-Assembly" }, { "code": "source equ $10 ;$10 was chosen arbitrarily\nsource_hi equ source+1 ;the high byte MUST be after the low byte, otherwise this will not work.\ndest equ $12\ndest_hi equ dest+1\n\nLDA #<MyString ;get the low byte of &MyString\nSTA source\nLDA #>MyString ;get the high byte\nSTA source_hi ;we just created a \"shallow reference\" to an existing string.\n ;As it turns out, this is a necessary step to do a deep copy.\n\nLDA #<RamBuffer\nSTA dest\nLDA #>RamBuffer\nSTA dest_hi\n\n\nstrcpy:\n;assumes that RamBuffer is big enough to hold the source string, and that the memory ranges do not overlap.\n;if you've ever wondered why C's strcpy is considered \"unsafe\", this is why.\n\nLDY #0\n.again:\nLDA (source),y\nSTA (dest),y\nBEQ .done\nINY\nBNE .again ;exit after 256 bytes copied or the null terminator is reached, whichever occurs first.\nRTS\n\n\nMyString:\nbyte \"hello\",0\nRamBuffer:\nbyte 0,0,0,0,0,0\n", "language": "6502-Assembly" }, { "code": "myString: DC.B \"HELLO WORLD\",0\nEVEN\n\nLEA myString,A3\n", "language": "68000-Assembly" }, { "code": "StringRam equ $100000\n\nmyString: DC.B \"HELLO WORLD\",0\nEVEN\n\nLEA myString,A3\nLEA StringRam,A4\n\nCopyString:\nMOVE.B (A3)+,D0\nMOVE.B D0,(A4)+ ;we could have used \"MOVE.B (A3)+,(A4)+\" but this makes it easier to check for the terminator.\nBEQ Terminated\nBRA CopyString\n\nTerminated: ;the null terminator is already stored along with the string itself, so we are done.\n;program ends here.\n", "language": "68000-Assembly" }, { "code": ".model small\n.stack 1024\n\n.data\n\nmyString byte \"Hello World!\",0 ; a null-terminated string\n\nmyStruct word 0\n\n.code\n\nmov ax,@data\nmov ds,ax ;load data segment into DS\n\nmov bx,offset myString ;get the pointer to myString\n\nmov word ptr [ds:myStruct],bx\n\nmov ax,4C00h\nint 21h ;quit program and return to DOS\n", "language": "8086-Assembly" }, { "code": ".model small\n.stack 1024\n\n.data\n\nmyString byte \"Hello World!\",0 ; a null-terminated string\n\nStringRam byte 256 dup (0) ;256 null bytes\n\n.code\n\nmov ax,@data\nmov ds,ax ;load data segment into DS\nmov es,ax ;also load it into ES\n\nmov si,offset myString\nmov di,offset StringRam\nmov cx,12 ;length of myString\ncld ;make MOVSB auto-increment rather than auto-decrement (I'm pretty sure DOS begins with\n ;the direction flag cleared but just to be safe)\n\nrep movsb ;copies 12 bytes from [ds:si] to [es:di]\nmov al,0 ;create a null terminator\nstosb ;store at the end. (It's already there since we initialized StringRam to zeroes, but you may need to do this depending\n ;on what was previously stored in StringRam, if you've copied a string there already.\n\nmov ax,4C00h\nint 21h ;quit program and return to DOS\n", "language": "8086-Assembly" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program copystr64.s */\n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n/*******************************************/\n/* Initialized data */\n/*******************************************/\n.data\nszString: .asciz \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\\n\"\n/*******************************************/\n/* UnInitialized data */\n/*******************************************/\n.bss\n.align 4\nqPtString: .skip 8\nszString1: .skip 80\n/*******************************************/\n/* code section */\n/*******************************************/\n.text\n.global main\nmain: // entry of program\n\n // display start string\n ldr x0,qAdrszString\n bl affichageMess\n // copy pointer string\n ldr x0,qAdrszString\n ldr x1,qAdriPtString\n str x0,[x1]\n // control\n ldr x1,qAdriPtString\n ldr x0,[x1]\n bl affichageMess\n // copy string\n ldr x0,qAdrszString\n ldr x1,qAdrszString1\n1:\n ldrb w2,[x0],1 // read one byte and increment pointer one byte\n strb w2,[x1],1 // store one byte and increment pointer one byte\n cmp x2,#0 // end of string ?\n bne 1b // no -> loop\n // control\n ldr x0,qAdrszString1\n bl affichageMess\n\n100: // standard end of the program */\n mov x0,0 // return code\n mov x8,EXIT // request to exit program\n svc 0 // perform the system call\nqAdrszString: .quad szString\nqAdriPtString: .quad qPtString\nqAdrszString1: .quad szString1\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "data: lv_string1 type string value 'Test',\n lv_string2 type string.\nlv_string2 = lv_string1.\n", "language": "ABAP" }, { "code": "DATA(string1) = |Test|.\nDATA(string2) = string1.\n", "language": "ABAP" }, { "code": "PROC Main()\n CHAR ARRAY str1,str2,str3(10)\n\n str1=\"Atari\"\n str2=str1\n SCopy(str3,str1)\n\n PrintF(\" base=%S%E\",str1)\n PrintF(\"alias=%S%E\",str2)\n PrintF(\" copy=%S%E\",str3)\n PutE()\n\n SCopy(str1,\"Action!\")\n\n PrintF(\" base=%S%E\",str1)\n PrintF(\"alias=%S%E\",str2)\n PrintF(\" copy=%S%E\",str3)\nRETURN\n", "language": "Action-" }, { "code": "var str1:String = \"Hello\";\nvar str2:String = str1;\n", "language": "ActionScript" }, { "code": "Src : String := \"Hello\";\nDest : String := Src;\n", "language": "Ada" }, { "code": "Src : String := \"Rosetta Stone\";\nDest : String := Src(1..7); -- Assigns \"Rosetta\" to Dest\nDest2 : String := Src(9..13); -- Assigns \"Stone\" to Dest2\n", "language": "Ada" }, { "code": "-- Instantiate the generic package Ada.Strings.Bounded.Generic_Bounded_Length with a maximum length of 80 characters\npackage Flexible_String is new Ada.Strings.Bounded.Generic_Bounded_Length(80);\nuse Flexible_String;\n\nSrc : Bounded_String := To_Bounded_String(\"Hello\");\nDest : Bounded_String := Src;\n", "language": "Ada" }, { "code": "-- The package Ada.Strings.Unbounded contains the definition of the Unbounded_String type and all its methods\nSrc : Unbounded_String := To_Unbounded_String(\"Hello\");\nDest : Unbounded_String := Src;\n", "language": "Ada" }, { "code": "text s, t;\nt = \"Rosetta\";\ns = t;\n", "language": "Aime" }, { "code": "data s, t;\n# Copy -t- into -s-\nb_copy(s, t);\n# Set -s- as a reference of the object -t- is pointing\nb_set(s, t);\n# or:\ns = t;\n", "language": "Aime" }, { "code": "(\n STRING src:=\"Hello\", dest;\n dest:=src\n)\n", "language": "ALGOL-68" }, { "code": "begin\n % strings are (fixed length) values in algol W. Assignment makes a copy %\n string(10) a, copyOfA;\n a := \"some text\";\n copyOfA := a;\n % assignment to a will not change copyOfA %\n a := \"new value\";\n write( a, copyOfA )\nend.\n", "language": "ALGOL-W" }, { "code": "#include <hopper.h>\nmain:\n s = \"string to copy\"\n t = s\n {s,\"\\n\",t}println\nexit(0)\n", "language": "Amazing-Hopper" }, { "code": "#include <hopper.h>\nmain:\n s=\"\"\n {\"1:\",\"string to copy\"},cpy(s),println\n {\"2:\",s}println\nexit(0)\n", "language": "Amazing-Hopper" }, { "code": "#include <hopper.h>\nmain:\n s=\"\"\n {\"string to copy\"},mov(s)\n {s}println\nexit(0)\n", "language": "Amazing-Hopper" }, { "code": "String original = 'Test';\nString cloned = original;\n//\"original == cloned\" is true\n\ncloned += ' more';\n//\"original == cloned\" is false\n", "language": "Apex" }, { "code": "set src to \"Hello\"\nset dst to src\n", "language": "AppleScript" }, { "code": "100 DEF FN P(A) = PEEK (A) + PEEK(A + 1) * 256 : FOR I = FN P(105) TO FN P(107) - 1 STEP 7 : ON PEEK(I + 1) < 128 OR PEEK(I) > 127 GOTO 130 : ON LEFT$(P$, 1) <> CHR$(PEEK(I)) GOTO 130\n110 IF LEN(P$) > 1 THEN ON PEEK(I + 1) = 128 GOTO 130 : IF MID$(P$, 2, 1) <> CHR$(PEEK(I + 1) - 128) GOTO 130\n120 POKE I + 4, P / 256 : POKE I + 3, P - PEEK(I + 4) * 256 : RETURN\n130 NEXT I : STOP\n", "language": "Applesoft-BASIC" }, { "code": "S$ = \"HELLO\" : REM S$ IS THE ORIGINAL STRING\nC$ = S$ : REM C$ IS THE COPY\n", "language": "Applesoft-BASIC" }, { "code": "P$ = \"S\" : P = 53637 : GOSUB 100\"POINT STRING S AT SOMETHING ELSE\n?S$\n?C$\n", "language": "Applesoft-BASIC" }, { "code": "/* ARM assembly Raspberry PI */\n/* program copystr.s */\n\n/* Constantes */\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n/* Initialized data */\n.data\nszString: .asciz \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\\n\"\n\n/* UnInitialized data */\n.bss\n.align 4\niPtString: .skip 4\nszString1: .skip 80\n\n/* code section */\n.text\n.global main\nmain: /* entry of program */\n push {fp,lr} /* saves 2 registers */\n\n @ display start string\n ldr r0,iAdrszString\n bl affichageMess\n @ copy pointer string\n ldr r0,iAdrszString\n ldr r1,iAdriPtString\n str r0,[r1]\n @ control\n ldr r1,iAdriPtString\n ldr r0,[r1]\n bl affichageMess\n @ copy string\n ldr r0,iAdrszString\n ldr r1,iAdrszString1\n1:\n ldrb r2,[r0],#1 @ read one byte and increment pointer one byte\n strb r2,[r1],#1 @ store one byte and increment pointer one byte\n cmp r2,#0 @ end of string ?\n bne 1b @ no -> loop\n @ control\n ldr r0,iAdrszString1\n bl affichageMess\n\n100: /* standard end of the program */\n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\niAdrszString:\t\t.int szString\niAdriPtString:\t\t.int iPtString\niAdrszString1:\t\t.int szString1\n\n/******************************************************************/\n/* display text with size calculation */\n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {fp,lr} \t\t\t/* save registres */\n push {r0,r1,r2,r7} \t\t/* save others registers */\n mov r2,#0 \t\t\t\t/* counter length */\n1: \t/* loop length calculation */\n ldrb r1,[r0,r2] \t\t\t/* read octet start position + index */\n cmp r1,#0 \t\t\t/* if 0 its over */\n addne r2,r2,#1 \t\t\t/* else add 1 in the length */\n bne 1b \t\t\t/* and loop */\n /* so here r2 contains the length of the message */\n mov r1,r0 \t\t\t/* address message in r1 */\n mov r0,#STDOUT \t\t/* code to write to the standard output Linux */\n mov r7, #WRITE /* code call system \"write\" */\n swi #0 /* call systeme */\n pop {r0,r1,r2,r7} \t\t/* restaur others registers */\n pop {fp,lr} \t\t\t\t/* restaur des 2 registres */\n bx lr\t \t\t\t/* return */\n", "language": "ARM-Assembly" }, { "code": "a: new \"Hello\"\nb: a ; reference the same string\n\n; changing one string in-place\n; will change both strings\n\n'b ++ \"World\"\nprint b\nprint a\n\nc: \"Hello\"\nd: new c ; make a copy of the older string\n\n; changing one string in-place\n; will change only the string in question\n\n'd ++ \"World\"\nprint d\nprint c\n", "language": "Arturo" }, { "code": "string src, dst;\nsrc = \"Hello\";\ndst = src;\nsrc = \" world...\";\nwrite(dst, src);\n", "language": "Asymptote" }, { "code": "src := \"Hello\"\ndst := src\n", "language": "AutoHotkey" }, { "code": "$Src= \"Hello\"\n$dest = $Src\n", "language": "AutoIt" }, { "code": "BEGIN {\n a = \"a string\"\n b = a\n sub(/a/, \"X\", a) # modify a\n print b # b is a copy, not a reference to...\n}\n", "language": "AWK" }, { "code": "Lbl STRCPY\nr₁→S\nWhile {r₂}\n {r₂}→{r₁}\n r₁++\n r₂++\nEnd\n0→{r₁}\nS\nReturn\n", "language": "Axe" }, { "code": "babel> \"Hello, world\\n\" dup cp dup 0 \"Y\" 0 1 move8\nbabel> << <<\nYello, world\nHello, world\n", "language": "Babel" }, { "code": "a$ = \"I am here\"\nb$ = a$\na$ = \"Hello world...\"\nPRINT a$, b$\n", "language": "BaCon" }, { "code": "a$ = \"Hello world...\"\nLOCAL b TYPE STRING\nb = a$\na$ = \"Goodbye...\"\nPRINT a$, b\n", "language": "BaCon" }, { "code": "src$ = \"Hello\"\ndst$ = src$\nsrc$ = \" world...\"\nprint dst$; src$\n", "language": "BASIC256" }, { "code": "set src=Hello\nset dst=%src%\n", "language": "Batch-File" }, { "code": " source$ = \"Hello, world!\"\n\n REM Copy the contents of a string:\n copy$ = source$\n PRINT copy$\n\n REM Make an additional reference to a string:\n !^same$ = !^source$\n ?(^same$+4) = ?(^source$+4)\n ?(^same$+5) = ?(^source$+5)\n PRINT same$\n", "language": "BBC-BASIC" }, { "code": "a ← \"Hello\"\nb ← a\n•Show a‿b\na ↩ \"hi\"\n•Show a‿b\n", "language": "BQN" }, { "code": "⟨ \"Hello\" \"Hello\" ⟩\n⟨ \"hi\" \"Hello\" ⟩\n", "language": "BQN" }, { "code": "abcdef:?a;\n!a:?b;\n\nc=abcdef;\n!c:?d;\n\n!a:!b { variables a and b are the same and probably referencing the same string }\n!a:!d { variables a and d are also the same but not referencing the same string }\n", "language": "Bracmat" }, { "code": "#include <stdlib.h>\t/* exit(), free() */\n#include <stdio.h>\t/* fputs(), perror(), printf() */\n#include <string.h>\n\nint\nmain()\n{\n\tsize_t len;\n\tchar src[] = \"Hello\";\n\tchar dst1[80], dst2[80];\n\tchar *dst3, *ref;\n\n\t/*\n\t * Option 1. Use strcpy() from <string.h>.\n\t *\n\t * DANGER! strcpy() can overflow the destination buffer.\n\t * strcpy() is only safe if the source string is shorter than\n\t * the destination buffer. We know that \"Hello\" (6 characters\n\t * with the final '\\0') easily fits in dst1 (80 characters).\n\t */\n\tstrcpy(dst1, src);\n\n\t/*\n\t * Option 2. Use strlen() and memcpy() from <string.h>, to copy\n\t * strlen(src) + 1 bytes including the final '\\0'.\n\t */\n\tlen = strlen(src);\n\tif (len >= sizeof dst2) {\n\t\tfputs(\"The buffer is too small!\\n\", stderr);\n\t\texit(1);\n\t}\n\tmemcpy(dst2, src, len + 1);\n\n\t/*\n\t * Option 3. Use strdup() from <string.h>, to allocate a copy.\n\t */\n\tdst3 = strdup(src);\n\tif (dst3 == NULL) {\n\t\t/* Failed to allocate memory! */\n\t\tperror(\"strdup\");\n\t\texit(1);\n\t}\n\n\t/* Create another reference to the source string. */\n\tref = src;\n\n\t/* Modify the source string, not its copies. */\n\tmemset(src, '-', 5);\n\n\tprintf(\" src: %s\\n\", src); /* src: ----- */\n\tprintf(\"dst1: %s\\n\", dst1); /* dst1: Hello */\n\tprintf(\"dst2: %s\\n\", dst2); /* dst2: Hello */\n\tprintf(\"dst3: %s\\n\", dst3); /* dst3: Hello */\n\tprintf(\" ref: %s\\n\", ref); /* ref: ----- */\n\n\t/* Free memory from strdup(). */\n\tfree(dst3);\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <stdlib.h>\t/* exit() */\n#include <stdio.h>\t/* fputs(), printf() */\n#include <string.h>\n\nint\nmain()\n{\n\tchar src[] = \"Hello\";\n\tchar dst[80];\n\n\t/* Use strlcpy() from <string.h>. */\n\tif (strlcpy(dst, src, sizeof dst) >= sizeof dst) {\n\t\tfputs(\"The buffer is too small!\\n\", stderr);\n\t\texit(1);\n\t}\n\n\tmemset(src, '-', 5);\n\tprintf(\"src: %s\\n\", src); /* src: ----- */\n\tprintf(\"dst: %s\\n\", dst); /* dst: Hello */\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <gadget/gadget.h>\n\nLIB_GADGET_START\n\nMain\n String v, w = \"this message is a message\";\n\n Let( v, \"Hello world!\");\n Print \"v = %s\\nw = %s\\n\\n\", v,w;\n\n Get_fn_let( v, Upper(w) );\n\n Print \"v = %s\\nw = %s\\n\\n\", v,w;\n\n Stack{\n Store ( v, Str_tran_last( Upper(w), \"MESSAGE\", \"PROOF\" ) );\n }Stack_off;\n\n Print \"v = %s\\nw = %s\\n\\n\", v,w;\n\n Free secure v, w;\n\nEnd\n", "language": "C" }, { "code": "#include <iostream>\n#include <string>\n\nint main( ) {\n std::string original (\"This is the original\");\n std::string my_copy = original;\n std::cout << \"This is the copy: \" << my_copy << std::endl;\n original = \"Now we change the original! \";\n std::cout << \"my_copy still is \" << my_copy << std::endl;\n}\n", "language": "C++" }, { "code": "string src = \"Hello\";\nstring dst = src;\n", "language": "C-sharp" }, { "code": "(let [s \"hello\"\n s1 s]\n (println s s1))\n", "language": "Clojure" }, { "code": "MOVE \"Hello\" TO src\nMOVE src TO dst\n", "language": "COBOL" }, { "code": "<cfset stringOrig = \"I am a string.\" />\n<cfset stringCopy = stringOrig />\n", "language": "ColdFusion" }, { "code": "10 A$ = \"HELLO\"\n20 REM COPY CONTENTS OF A$ TO B$\n30 B$ = A$\n40 REM CHANGE CONTENTS OF A$\n50 A$ = \"HI\"\n60 REM DISPLAY CONTENTS\n70 PRINT A$, B$\n", "language": "Commodore-BASIC" }, { "code": "(let* ((s1 \"Hello\") ; s1 is a variable containing a string\n (s1-ref s1) ; another variable with the same value\n (s2 (copy-seq s1))) ; s2 has a distinct string object with the same contents\n (assert (eq s1 s1-ref)) ; same object\n (assert (not (eq s1 s2))) ; different object\n (assert (equal s1 s2)) ; same contents\n\n (fill s2 #\\!) ; overwrite s2\n (princ s1)\n (princ s2)) ; will print \"Hello!!!!!\"\n", "language": "Common-Lisp" }, { "code": "VAR\n\tstr1: ARRAY 128 OF CHAR;\n\tstr2: ARRAY 32 OF CHAR;\n\tstr3: ARRAY 25 OF CHAR;\n", "language": "Component-Pascal" }, { "code": "\tstr1 := \"abcdefghijklmnopqrstuvwxyz\";\n str3 := str1; (* don't compile, incompatible assignement *)\n str3 := str1$; (* runtime error, string too long *)\n str2 := str1$; (* OK *)\n", "language": "Component-Pascal" }, { "code": "ldsrc: LDA src\nstdest: STA dest\n BRZ done ; 0-terminated\n\n LDA ldsrc\n ADD one\n STA ldsrc\n\n LDA stdest\n ADD one\n STA stdest\n\n JMP ldsrc\n\ndone: STP\n\none: 1\n\nsrc: 82 ; ASCII\n 111\n 115\n 101\n 116\n 116\n 97\n 0\n\ndest:\n", "language": "Computer-zero-Assembly" }, { "code": "s1 = \"Hello\"\ns2 = s1\n", "language": "Crystal" }, { "code": "void main() {\n string src = \"This is a string\";\n\n // copy contents:\n auto dest1 = src.idup;\n\n // copy contents to mutable char array\n auto dest2 = src.dup;\n\n // copy just the fat reference of the string\n auto dest3 = src;\n}\n", "language": "D" }, { "code": "[a string] # push \"a string\" on the main stack\nd # duplicate the top value\nf # show the current contents of the main stack\n", "language": "Dc" }, { "code": "program CopyString;\n\n{$APPTYPE CONSOLE}\n\nvar\n s1: string;\n s2: string;\nbegin\n s1 := 'Goodbye';\n s2 := s1; // S2 points at the same string as S1\n s2 := s2 + ', World!'; // A new string is created for S2\n\n Writeln(s1);\n Writeln(s2);\nend.\n", "language": "Delphi" }, { "code": "var src = \"foobar\"\nvar dst = src\n", "language": "Dyalect" }, { "code": "a$ = \"hello\"\nb$ = a$\nprint b$\n", "language": "EasyLang" }, { "code": "(define-syntax-rule (string-copy s) (string-append s)) ;; copy = append nothing\n → #syntax:string-copy\n(define s \"abc\")\n(define t (string-copy s))\n t → \"abc\"\n(eq? s t) → #t ;; same reference, same object\n", "language": "EchoLisp" }, { "code": "[ Copy a string\n =============\n\n A program for the EDSAC\n\n Copies the source string into storage\n tank 6, which is assumed to be free,\n and then prints it from there\n\n Works with Initial Orders 2 ]\n\n T56K\n GK\n\n[ 0 ] A34@ [ copy the string ]\n[ 1 ] T192F\n[ 2 ] H34@\n C32@\n S32@\n E17@\n T31@\n A@\n A33@\n T@\n A1@\n A33@\n T1@\n A2@\n A33@\n T2@\n E@\n[ 17 ] O192F [ print the copy ]\n[ 18 ] H192F\n C32@\n S32@\n E30@\n T31@\n A17@\n A33@\n T17@\n A18@\n A33@\n T18@\n E17@\n[ 30 ] ZF\n[ 31 ] PF\n[ 32 ] PD\n[ 33 ] P1F\n[ 34 ] *F\n RF\n OF\n SF\n EF\n TF\n TF\n AF\n !F\n CF\n OF\n DF\n ED\n\n EZPF\n", "language": "EDSAC-order-code" }, { "code": "var src := \"Hello\";\nvar dst := src; // copying the reference\nvar copy := src.clone(); // copying the content\n", "language": "Elena" }, { "code": "src = \"Hello\"\ndst = src\n", "language": "Elixir" }, { "code": "(let* ((str1 \"hi\")\n (str1-ref str1)\n (str2 (copy-sequence str1)))\n (eq str1 str1-ref) ;=> t\n (eq str1 str2) ;=> nil\n (equal str1 str1-ref) ;=> t\n (equal str1 str2)) ;=> t\n", "language": "Emacs-Lisp" }, { "code": "text original = \"Yellow world\"\ntext ref = original # copying the reference\ntext copied = *original # copying the content\noriginal[0] = \"H\" # texts are indexable and mutable\noriginal[5] = \",\"\nref.append(\"!\") # texts are coercible and growable\ncopied += \"?\"\n^|\n | original == ref == \"Hello, world!\"\n | copied == \"Yellow world?\"\n |^\n", "language": "EMal" }, { "code": "Src = \"Hello\".\nDst = Src.\n", "language": "Erlang" }, { "code": "sequence first = \"ABC\"\nsequence newOne = first\n", "language": "Euphoria" }, { "code": "let str = \"hello\"\nlet additionalReference = str\nlet deepCopy = System.String.Copy( str )\n\nprintfn \"%b\" <| System.Object.ReferenceEquals( str, additionalReference ) // prints true\nprintfn \"%b\" <| System.Object.ReferenceEquals( str, deepCopy ) // prints false\n", "language": "F-Sharp" }, { "code": "\"This is a mutable string.\" dup ! reference\n\"Let's make a deal!\" dup clone ! copy\n\"New\" \" string\" append . ! new string\n \"New string\"\n", "language": "Factor" }, { "code": "SBUF\" Grow me!\" dup \" OK.\" append\n SBUF\" Grow me! OK.\"\n", "language": "Factor" }, { "code": "SBUF\" I'll be a string someday.\" >string .\n \"I'll be a string someday.\"\n", "language": "Factor" }, { "code": "\\ Allocate two string buffers\ncreate stringa 256 allot\ncreate stringb 256 allot\n\n\\ Copy a constant string into a string buffer\ns\" Hello\" stringa place\n\n\\ Copy the contents of one string buffer into another\nstringa count stringb place\n", "language": "Forth" }, { "code": "str2 = str1\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nDim s As String = \"This is a string\"\nDim t As String = s\n' a separate copy of the string contents has been made as can be seen from the addresses\nPrint s, StrPtr(s)\nPrint t, StrPtr(t)\n' to refer to the same string a pointer needs to be used\nDim u As String Ptr = @s\nPrint\nPrint *u, StrPtr(*u)\nSleep\n", "language": "FreeBASIC" }, { "code": "a = \"Monkey\"\nb = a\n", "language": "Frink" }, { "code": "include \"NSLog.incl\"\n\nCFStringRef original, copy\n\noriginal = @\"Hello!\"\ncopy = fn StringWithString( original )\n\nNSLog( @\"%@\", copy )\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub main()\nDim src As String\nDim dst As String\n\nsrc = \"Hello\"\ndst = src\n\nPrint src\nPrint dst\nEnd\n", "language": "Gambas" }, { "code": "#In GAP strings are lists of characters. An affectation simply copy references\na := \"more\";\nb := a;\nb{[1..4]} := \"less\";\na;\n# \"less\"\n\n# Here is a true copy\na := \"more\";\nb := ShallowCopy(a);\nb{[1..4]} := \"less\";\na;\n# \"more\"\n", "language": "GAP" }, { "code": "src = \"string\";\ndest = src;\n", "language": "GML" }, { "code": "src := \"Hello\"\ndst := src\n", "language": "Go" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\t// creature string\n\tvar creature string = \"shark\"\n\t// point to creature\n\tvar pointer *string = &creature\n\t// creature string\n\tfmt.Println(\"creature =\", creature) // creature = shark\n\t// creature location in memory\n\tfmt.Println(\"pointer =\", pointer) // pointer = 0xc000010210\n\t// creature through the pointer\n\tfmt.Println(\"*pointer =\", *pointer) // *pointer = shark\n\t// set creature through the pointer\n\t*pointer = \"jellyfish\"\n\t// creature through the pointer\n\tfmt.Println(\"*pointer =\", *pointer) // *pointer = jellyfish\n\t// creature string\n\tfmt.Println(\"creature =\", creature) // creature = jellyfish\n}\n", "language": "Go" }, { "code": "def string = 'Scooby-doo-bee-doo' // assigns string object to a variable reference\ndef stringRef = string // assigns another variable reference to the same object\ndef stringCopy = new String(string) // copies string value into a new object, and assigns to a third variable reference\n", "language": "Groovy" }, { "code": "assert string == stringRef // they have equal values (like Java equals(), not like Java ==)\nassert string.is(stringRef) // they are references to the same objext (like Java ==)\nassert string == stringCopy // they have equal values\nassert ! string.is(stringCopy) // they are references to different objects (like Java !=)\n", "language": "Groovy" }, { "code": "Start.Programs,Accessories,Notepad,\nType:Hello world[pling],Highlight:Hello world[pling],\nMenu,Edit,Copy,Menu,Edit,Paste\n", "language": "GUISS" }, { "code": "cSource := \"Hello World\"\ncDestination := cSource\n", "language": "Harbour" }, { "code": "src = \"Hello World\"\ndst = src\n", "language": "HicEst" }, { "code": "//Strings are immutable in 'i'.\nsoftware {\n\ta = \"Hello World\"\n\tb = a //This copies the string.\n\t\n\ta += \"s\"\n\t\n\tprint(a)\n\tprint(b)\n}\n", "language": "I" }, { "code": "procedure main()\n a := \"qwerty\"\n b := a\n b[2+:4] := \"uarterl\"\n write(a,\" -> \",b)\nend\n", "language": "Icon" }, { "code": "src =: 'hello'\ndest =: src\n", "language": "J" }, { "code": "String src = \"Hello\";\nString newAlias = src;\nString strCopy = new String(src);\n\n//\"newAlias == src\" is true\n//\"strCopy == src\" is false\n//\"strCopy.equals(src)\" is true\n", "language": "Java" }, { "code": "StringBuffer srcCopy = new StringBuffer(\"Hello\");\n", "language": "Java" }, { "code": "var container = {myString: \"Hello\"};\nvar containerCopy = container; // Now both identifiers refer to the same object\n\ncontainerCopy.myString = \"Goodbye\"; // container.myString will also return \"Goodbye\"\n", "language": "JavaScript" }, { "code": "var a = \"Hello\";\nvar b = a; // Same as saying window.b = window.a\n\nb = \"Goodbye\" // b contains a copy of a's value and a will still return \"Hello\"\n", "language": "JavaScript" }, { "code": "\"hello\" dup\n", "language": "Joy" }, { "code": "def demo:\n \"abc\" as $s # assignment of a string to a variable\n | $s as $t # $t points to the same string as $s\n | \"def\" as $s # This $s shadows the previous $s\n | $t # $t still points to \"abc\"\n;\n\ndemo\n", "language": "Jq" }, { "code": "s = \"Rosetta Code\"\nt = s\n\nprintln(\"s = \\\"\", s, \"\\\" and, after \\\"t = s\\\", t = \\\"\", t, \"\\\"\")\n\ns = \"Julia at \"*s\n\nprintln(\"s = \\\"\", s, \"\\\" and, after this change, t = \\\"\", t, \"\\\"\")\n", "language": "Julia" }, { "code": "Var:String str1 = \"Hello\";\nVar:String str2 = str1;\n", "language": "KonsolScript" }, { "code": "val s = \"Hello\"\nval alias = s // alias === s\nval copy = \"\" + s // copy !== s\n", "language": "Kotlin" }, { "code": "{def S1 hello world} // set S1 to \"hello world\"\n-> S1\n{S1} // get the value of S1\n-> hello world\n\n{def S2 S1} // define S2 as S1\n-> S2\n{S2} // the value of S2 is S1\n-> S1\n{{S2}} // get the value of the value of S2\n-> hello world\n\n{def S3 {S1}} // set S3 to the value of S1\n-> S3\n{S3} // get the value of S3\n-> hello world\n", "language": "Lambdatalk" }, { "code": "'hello dup\n", "language": "Lang5" }, { "code": "local(x = 'I saw a rhino!')\nlocal(y = #x)\n\n#x //I saw a rhino!\n'\\r'\n#y //I saw a rhino!\n\n'\\r\\r'\n#x = 'I saw one too'\n#x //I saw one too\n'\\r'\n#y //I saw a rhino!\n\n'\\r\\r'\n#y = 'it was grey.'\n#x //I saw one too\n'\\r'\n#y //it was grey.\n", "language": "Lasso" }, { "code": "a := \"Hello\".\nb := a.\nc := a clone.\nprintln: a == b. ; True\nprintln: a == c. ; True\nprintln: a === b. ; True\nprintln: a === c. ; False\n", "language": "Latitude" }, { "code": " .ORIG 0x3000\n\n LEA R1,SRC\n LEA R2,COPY\n\nLOOP LDR R3,R1,0\n STR R3,R2,0\n BRZ DONE\n ADD R1,R1,1\n ADD R2,R2,1\n BRNZP LOOP\n\nDONE LEA R0,COPY\n PUTS\n\n HALT\n\nSRC .STRINGZ \"What, has this thing appeared again tonight?\"\n\nCOPY .BLKW 128\n\n .END\n", "language": "LC3-Assembly" }, { "code": "(let* ((a '\"data assigned to a\")\n (b a))\n (: io format '\"Contents of 'b': ~s~n\" (list b)))\n", "language": "LFE" }, { "code": "> (set a '\"data\")\n\"data\"\n> a\n\"data\"\n> (set b a)\n\"data\"\n> b\n\"data\"\n", "language": "LFE" }, { "code": "src$ = \"Hello\"\ndest$ = src$\nprint src$\nprint dest$\n", "language": "Liberty-BASIC" }, { "code": "str = \"Hello world!\"\nstr2 = str\n", "language": "Lingo" }, { "code": "put \"X\" before str\nput \"X\" after str\nput \"X\" into char 6 of str\nput str\n-- \"XHellX world!X\"\n", "language": "Lingo" }, { "code": "+ scon : STRING_CONSTANT;\n+ svar : STRING;\n\nscon := \"sample\";\nsvar := STRING.create 20;\nsvar.copy scon;\nsvar.append \"!\\n\";\n\nsvar.print;\n", "language": "Lisaac" }, { "code": "string a = \"A string\";\nstring b = a;\na =~ s/$/\\./;\nputs(a);\nputs(b);\n", "language": "Little" }, { "code": "put \"foo\" into bar\nput bar into baz\nanswer bar && baz\n", "language": "LiveCode" }, { "code": "make \"a \"foo\nmake \"b \"foo\nprint .eq :a :b ; true, identical symbols are reused\n\nmake \"c :a\nprint .eq :a :c ; true, copy a reference\n\nmake \"c word :b \"|| ; force a copy of the contents of a word by appending the empty word\nprint equal? :b :c ; true\nprint .eq :b :c ; false\n", "language": "Logo" }, { "code": "a = \"string\"\nb = a\nprint(a == b) -->true\nprint(b) -->string\n", "language": "Lua" }, { "code": "> s := \"some string\";\n s := \"some string\"\n\n> t := \"some string\";\n t := \"some string\"\n\n> evalb( s = t ); # they are equal\n true\n\n> addressof( s ) = addressof( t ); # not just equal data, but the same address in memory\n 3078334210 = 3078334210\n\n> u := t: # copy reference\n", "language": "Maple" }, { "code": "a=\"Hello World\"\nb=a\n", "language": "Mathematica" }, { "code": "string1 = 'Hello';\nstring2 = string1;\n", "language": "MATLAB" }, { "code": "/* It's possible in Maxima to access individual characters by subscripts, but it's not the usual way.\nAlso, the result is \"Lisp character\", which cannot be used by other Maxima functions except cunlisp. The usual\nway to access characters is charat, returning a \"Maxima character\" (actually a one characte string). With the latter,\nit's impossible to modify a string in place, thus scopy is of little use. */\n\na: \"loners\"$\nb: scopy(a)$\nc: a$\n\nc[2]: c[5]$\n\na;\n\"losers\"\n\nb;\n\"loners\"\n\nc;\n\"losers\"\n", "language": "Maxima" }, { "code": "str1 = \"Hello\"\nstr2 = copy str1\n", "language": "MAXScript" }, { "code": "string s, a;\ns := \"hello\";\na := s;\ns := s & \" world\";\nmessage s; % writes \"hello world\"\nmessage a; % writes \"hello\"\nend\n", "language": "Metafont" }, { "code": "phrase = \"hi\"\ncopy = phrase\nprint phrase\nprint copy\n", "language": "MiniScript" }, { "code": ".data\n\t\n.text\n\nstrcpy:\n addi $sp, $sp, -4\n sw $s0, 0($sp)\n add $s0, $zero, $zero\n\nL1:\n add $t1, $s0, $a1\n lb $t2, 0($t1)\n add $t3, $s0, $a0\n sb $t2, 0($t3)\n beq $t2, $zero, L2\n addi $s0, $s0, 1\n j L1\n\nL2:\n lw $s0, 0($sp)\n addi $sp, $sp, 4\n jr $ra\n", "language": "MIPS-Assembly" }, { "code": "src = \"Hello\"\nnew_alias = src\n\nputs 'interned strings are equal' if src == new_alias\n\nstr_copy = String.new(src)\nputs 'non-interned strings are not equal' if str_copy != src\nputs 'compare strings with equals()' if str_copy.equals(src)\n", "language": "Mirah" }, { "code": "VAR src: TEXT := \"Foo\";\nVAR dst: TEXT := src;\n", "language": "Modula-3" }, { "code": "SET S1=\"Greetings, Planet\"\nSET S2=S1\n", "language": "MUMPS" }, { "code": "a = \"Hello\"\nb = a\n", "language": "Nanoquery" }, { "code": "var src = \"Hello\"\nvar dst = src\n", "language": "Neko" }, { "code": "using System;\nusing System.Console;\nusing Nemerle;\n\nmodule StrCopy\n{\n Main() : void\n {\n mutable str1 = \"I am not changed\"; // str1 is bound to literal\n def str2 = lazy(str1); // str2 will be bound when evaluated\n def str3 = str1; // str3 is bound to value of str1\n str1 = \"I am changed\"; // str1 is bound to new literal\n Write($\"$(str1)\\n$(str2)\\n$(str3)\\n\"); // str2 is bound to value of str1\n // Output: I am changed\n // I am changed\n // I am not changed\n }\n}\n", "language": "Nemerle" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\ns1 = 'This is a Rexx string'\ns2 = s1\n\ns2 = s2.changestr(' ', '_')\n\nsay s1\nsay s2\n", "language": "NetRexx" }, { "code": "(define (assert f msg) (if (not f) (println msg)))\n\n(setq s \"Greetings!\" c (copy s))\n(reverse c) ; Modifies c in place.\n\n(assert (= s c) \"Strings not equal.\")\n\n; another way\n; Nehal-Singhal 2018-05-25\n\n> (setq a \"abcd\")\n\"abcd\"\n> (setq b a)\n\"abcd\"\n> b\n\"abcd\"\n> (= a b)\ntrue\n", "language": "NewLISP" }, { "code": "var\n c = \"This is a string\"\n d = c # Copy c into a new string\n", "language": "Nim" }, { "code": "10 A$ = \"HELLO\"\n20 B$ = A$\n30 A$ = \"HI\"\n40 PRINT A$, B$\n", "language": "NS-HUBASIC" }, { "code": "MODULE CopyString;\nTYPE\n\tString = ARRAY 128 OF CHAR;\nVAR\n\ta,b: String;\n\nBEGIN\n\ta := \"plain string\";\n\tCOPY(a,b);\nEND CopyString.\n", "language": "Oberon" }, { "code": "a := \"GoodBye!\";\nb := a;\n", "language": "Objeck" }, { "code": "NSString *original = @\"Literal String\";\nNSString *new = [original copy];\nNSString *anotherNew = [NSString stringWithString:original];\nNSString *newMutable = [original mutableCopy];\n", "language": "Objective-C" }, { "code": "NSMutableString *original = [NSMutableString stringWithString:@\"Literal String\"];\nNSString *immutable = [original copy];\nNSString *anotherImmutable = [NSString stringWithString:original];\nNSMutableString *mutable = [original mutableCopy];\n", "language": "Objective-C" }, { "code": "const char *cstring = \"I'm a plain C string\";\nNSString *string = [NSString stringWithUTF8String:cstring];\n", "language": "Objective-C" }, { "code": "char bytes[] = \"some data\";\nNSString *string = [[NSString alloc] initWithBytes:bytes length:9 encoding:NSASCIIStringEncoding];\n", "language": "Objective-C" }, { "code": "let src = \"foobar\"\n", "language": "OCaml" }, { "code": "let dst = String.copy src\n", "language": "OCaml" }, { "code": "(* Transition-period synonymy between types, explicit type annotations are just for emphasis *)\nlet dst1 : string = Bytes.copy (src : bytes)\nlet dst2 : bytes = Bytes.copy (src : string)\n(* fails to compile with -safe-string *)\n", "language": "OCaml" }, { "code": "let dst = src\n", "language": "OCaml" }, { "code": "str2 = str1\n", "language": "Octave" }, { "code": "\"abcde\" dup\n", "language": "Oforth" }, { "code": "StringBuffer new \"abcde\" <<\n", "language": "Oforth" }, { "code": "(define a \"The String.\")\n\n; copy the string\n(define b (runes->string (string->runes a)))\n(print \"a: \" a)\n(print \"b: \" b)\n(print \"b is an a: \" (eq? a b))\n(print \"b same as a: \" (equal? a b))\n\n; another way: marshal the string\n(define c (fasl-decode (fasl-encode a) #f))\n(print \"a: \" a)\n(print \"c: \" c)\n(print \"c is an a: \" (eq? a c))\n(print \"c same as a: \" (equal? a c))\n", "language": "Ol" }, { "code": "/* Rexx ***************************************************************\n* 16.05.2013 Walter Pachl\n**********************************************************************/\n\ns1 = 'This is a Rexx string'\ns2 = s1 /* does not copy the string */\n\nSay 's1='s1\nSay 's2='s2\ni1=s1~identityhash; Say 's1~identityhash='i1\ni2=s2~identityhash; Say 's2~identityhash='i2\n\ns2 = s2~changestr('*', '*') /* creates a modified copy */\n\nSay 's1='s1\nSay 's2='s2\ni1=s1~identityhash; Say 's1~identityhash='i1\ni2=s2~identityhash; Say 's2~identityhash='i2\n", "language": "OoRexx" }, { "code": "string s, t=\"hello\"\ns=t\n", "language": "OxygenBasic" }, { "code": "s1=s\n", "language": "PARI-GP" }, { "code": "GEN string_copy = gcopy(string);\nGEN string_ref = string;\n", "language": "PARI-GP" }, { "code": "program copyAString;\n\tvar\n\t\t{ The Extended Pascal `string` schema data type\n\t\t is essentially a `packed array[1..capacity] of char`. }\n\t\tsource, destination: string(80);\n\tbegin\n\t\tsource := 'Hello world!';\n\t\t{ In Pascal _whole_ array data type values can be copied by assignment. }\n\t\tdestination := source;\n\t\t{ Provided `source` is a _non-empty_ string value\n\t\t you can copy in Extended Pascal sub-ranges _of_ _string_ types, too.\n\t\t Note, the sub-range notation is not permitted for a `bindable` data type. }\n\t\tdestination := source[1..length(source)];\n\t\t{ You can also employ Extended Pascal’s `writeStr` routine: }\n\t\twriteStr(destination, source);\n\tend.\n", "language": "Pascal" }, { "code": "my $original = 'Hello.';\nmy $new = $original;\n$new = 'Goodbye.';\nprint \"$original\\n\"; # prints \"Hello.\"\n", "language": "Perl" }, { "code": "my $original = 'Hello.';\nmy $ref = \\$original;\n$$ref = 'Goodbye.';\nprint \"$original\\n\"; # prints \"Goodbye.\"\n", "language": "Perl" }, { "code": "my $original = 'Hello.';\nour $alias;\nlocal *alias = \\$original;\n$alias = 'Good evening.';\nprint \"$original\\n\"; # prints \"Good evening.\"\n", "language": "Perl" }, { "code": "use Lexical::Alias;\nmy $original = 'Hello.';\nmy $alias;\nalias $alias, $original;\n$alias = 'Good evening.';\nprint \"$original\\n\"; # prints \"Good evening.\"\n", "language": "Perl" }, { "code": "-->\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">one</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"feed\"</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">two</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">one</span> <span style=\"color: #000080;font-style:italic;\">-- (two becomes \"feed\", one remains \"feed\")</span>\n <span style=\"color: #000000;\">two<span style=\"color: #0000FF;\">[<span style=\"color: #000000;\">2<span style=\"color: #0000FF;\">..<span style=\"color: #000000;\">3<span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"oo\"</span> <span style=\"color: #000080;font-style:italic;\">-- (two becomes \"food\", one remains \"feed\")</span>\n <span style=\"color: #000000;\">one<span style=\"color: #0000FF;\">[<span style=\"color: #000000;\">1<span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">'n'</span> <span style=\"color: #000080;font-style:italic;\">-- (two remains \"food\", one becomes \"need\")</span>\n <span style=\"color: #0000FF;\">?<span style=\"color: #0000FF;\">{<span style=\"color: #000000;\">one<span style=\"color: #0000FF;\">,<span style=\"color: #000000;\">two<span style=\"color: #0000FF;\">}\n<!--\n", "language": "Phix" }, { "code": "$src = \"Hello\";\n$dst = $src;\n", "language": "PHP" }, { "code": "go =>\n S1 = \"string\",\n println(s1=S1),\n S2 = S1,\n S2[1] := 'x', % also changes S1\n println(s1=S1),\n println(s2=S2),\n nl,\n\n S3 = \"string\",\n S4 = copy_term(S3),\n S4[1] := 'x', % no change of S3\n println(s3=S3),\n println(s4=S4),\n\n nl.\n", "language": "Picat" }, { "code": "(setq Str1 \"abcdef\")\n(setq Str2 Str1) # Create a reference to that symbol\n(setq Str3 (name Str1)) # Create new symbol with name \"abcdef\"\n", "language": "PicoLisp" }, { "code": "int main(){\n string hi = \"Hello World.\";\n string ih = hi;\n}\n", "language": "Pike" }, { "code": " declare (s1, s2) character (20) varying;\n s1 = 'now is the time';\n s2 = s1;\n", "language": "PL-I" }, { "code": "vars src, dst;\n'Hello' -> src;\ncopy(src) -> dst;\n", "language": "Pop11" }, { "code": "vars src='Hello';\nvars dst=copy(src);\n", "language": "Pop11" }, { "code": "(hello) dup length string copy\n", "language": "PostScript" }, { "code": "$str = \"foo\"\n$dup = $str\n", "language": "PowerShell" }, { "code": "$dup = $str.Clone()\n", "language": "PowerShell" }, { "code": "editvar /newvar /value=a /userinput=1 /title=Enter a string to be copied:\neditvar /newvar /value=b /userinput=1 /title=Enter current directory of the string:\neditvar /newvar /value=c /userinput=1 /title=Enter file to copy to:\ncopy -a- from -b- to -c-\n", "language": "ProDOS" }, { "code": "?- A = \"A test string\", A = B.\nA = B, B = \"A test string\".\n", "language": "Prolog" }, { "code": "src$ = \"Hello\"\ndst$ = src$\n", "language": "PureBasic" }, { "code": ">>> src = \"hello\"\n>>> a = src\n>>> b = src[:]\n>>> import copy\n>>> c = copy.copy(src)\n>>> d = copy.deepcopy(src)\n>>> src is a is b is c is d\nTrue\n", "language": "Python" }, { "code": ">>> a = 'hello'\n>>> b = ''.join(a)\n>>> a == b\nTrue\n>>> b is a ### Might be True ... depends on \"interning\" implementation details!\nFalse\n", "language": "Python" }, { "code": "src$ = \"Hello\" ' is the original string\ndst$ = src$ ' is the copy\nsrc$ = \" world...\"\nPRINT dst$; src$\n", "language": "QBasic" }, { "code": "$ \"hello\" dup\n", "language": "Quackery" }, { "code": "str1 <- \"abc\"\nstr2 <- str1\n", "language": "R" }, { "code": "#lang racket\n\n(let* ([s1 \"Hey\"]\n [s2 s1]\n [s3 (string-copy s1)]\n [s4 s3])\n (printf \"s1 and s2 refer to ~a strings\\n\"\n (if (eq? s1 s2) \"the same\" \"different\")) ; same\n (printf \"s1 and s3 refer to ~a strings\\n\"\n (if (eq? s1 s3) \"the same\" \"different\")) ; different\n (printf \"s3 and s4 refer to ~a strings\\n\"\n (if (eq? s3 s4) \"the same\" \"different\")) ; same\n (string-fill! s3 #\\!)\n (printf \"~a~a~a~a\\n\" s1 s2 s3 s4)) ; outputs \"HeyHey!!!!!!\"\n", "language": "Racket" }, { "code": "my $original = 'Hello.';\nmy $copy = $original;\nsay $copy; # prints \"Hello.\"\n$copy = 'Goodbye.';\nsay $copy; # prints \"Goodbye.\"\nsay $original; # prints \"Hello.\"\n", "language": "Raku" }, { "code": "my $original = 'Hello.';\nmy $bound := $original;\nsay $bound; # prints \"Hello.\"\n$bound = 'Goodbye.';\nsay $bound; # prints \"Goodbye.\"\nsay $original; # prints \"Goodbye.\"\n", "language": "Raku" }, { "code": "# y $original = 'Hello.';\n#my $bound-ro ::= $original;\n#say $bound-ro; # prints \"Hello.\"\n#try {\n# $bound-ro = 'Runtime error!';\n# CATCH {\n# say \"$!\"; # prints \"Cannot modify readonly value\"\n# };\n#};\nsay $bound-ro; # prints \"Hello.\"\n$original = 'Goodbye.';\nsay $bound-ro; # prints \"Goodbye.\"\n", "language": "Raku" }, { "code": "'abc' as a\na as b\n", "language": "Raven" }, { "code": "'abc' as a\na copy as b\n", "language": "Raven" }, { "code": "REBOL [\n Title: \"String Copy\"\n URL: http://rosettacode.org/wiki/Copy_a_string\n]\n\nx: y: \"Testing.\"\ny/2: #\"X\"\nprint [\"Both variables reference same string:\" mold x \",\" mold y]\n\nx: \"Slackeriffic!\"\nprint [\"Now reference different strings:\" mold x \",\" mold y]\n\ny: copy x ; String copy here!\ny/3: #\"X\" ; Modify string.\nprint [\"x copied to y, then modified:\" mold x \",\" mold y]\n\ny: copy/part x 7 ; Copy only the first part of y to x.\nprint [\"Partial copy:\" mold x \",\" mold y]\n\ny: copy/part skip x 2 3\nprint [\"Partial copy from offset:\" mold x \",\" mold y]\n", "language": "REBOL" }, { "code": "Red[]\noriginalString: \"hello wordl\"\ncopiedString: originalString\n; OR\ncopiedString2: copy originalString\n", "language": "Red" }, { "code": "'this_is_a_string dup s:temp\n", "language": "Retro" }, { "code": "src = \"this is a string\"\ndst = src\n", "language": "REXX" }, { "code": "cStr1 = \"Hello!\" # create original string\ncStr2 = cStr1 # make new string from original\n", "language": "Ring" }, { "code": ">> s1 = \"A string\"\nA string\n>> s2 = s1\nA string\n", "language": "RLaB" }, { "code": "set \"$string1\" to \"This is a string\"\nset \"$string2\" to \"$string1\"\n* \"&$string2&\"\n", "language": "Robotic" }, { "code": "original = \"hello\"\nreference = original # copies reference\ncopy1 = original.dup # instance of original.class\ncopy2 = String.new(original) # instance of String\n\noriginal << \" world!\" # append\np reference #=> \"hello world!\"\np copy1 #=> \"hello\"\np copy2 #=> \"hello\"\n", "language": "Ruby" }, { "code": "original = \"hello\".freeze # prevents further modifications\ncopy1 = original.dup # copies contents (without status)\ncopy2 = original.clone # copies contents (with status)\np copy1.frozen? #=> false\np copy1 << \" world!\" #=> \"hello world!\"\np copy2.frozen? #=> true\np copy2 << \" world!\" #=> can't modify frozen String (RuntimeError)\n", "language": "Ruby" }, { "code": "origString$ = \"Hello!\" ' create original string\nnewString$ = origString$ ' make new strig from original\n", "language": "Run-BASIC" }, { "code": "fn main() {\n let s1 = \"A String\";\n let mut s2 = s1;\n\n s2 = \"Another String\";\n\n println!(\"s1 = {}, s2 = {}\", s1, s2);\n}\n", "language": "Rust" }, { "code": "s1 = A String, s2 = Another String\n", "language": "Rust" }, { "code": "class MAIN is\n main is\n s ::= \"a string\";\n s1 ::= s;\n -- s1 is a copy\n end;\nend;\n", "language": "Sather" }, { "code": " val src = \"Hello\"\n // Its actually not a copy but a reference\n // That is not a problem because String is immutable\n // In fact its a feature\n val des = src\n assert(src eq des) // Proves the same reference is used.\n // To make a real copy makes no sense.\n // Actually its hard to make a copy, the compiler is too smart.\n // mkString, toString makes also not a real copy\n val cop = src.mkString.toString\n assert((src eq cop)) // Still no copyed image\n val copy = src.reverse.reverse // Finally double reverse makes a copy\n assert(src == copy && !(src eq copy))// Prove, but it really makes no sense.\n", "language": "Scala" }, { "code": "(define dst (string-copy src))\n", "language": "Scheme" }, { "code": "var string: dest is \"\";\n\ndest := \"Hello\";\n", "language": "Seed7" }, { "code": "(* In SenseTalk, assignments normally always make copies of values. *)\n\nput \"glorious\" into myWord\nput myWord into yourWord\n\n(* Assignments can also be made by reference if desired. *)\n\nput a reference to myWord into myRef\nset another to refer to myRef\n\nput \"ly\" after myWord\nput \"in\" before another\n\nput \"myWord: \" & myWord\nput \"yourWord: \" & yourWord\nput \"myRef: \" & myRef\nput \"another: \" & another\n", "language": "SenseTalk" }, { "code": "src: 'hello'\ncpy: src\n", "language": "Shiny" }, { "code": "var original = \"hello\"; # new String object\nvar reference = original; # points at the original object\nvar copy1 = String.new(original); # creates a new String object\nvar copy2 = original+''; # ==//==\n", "language": "Sidef" }, { "code": "BEGIN\n TEXT ORIGINAL, REFERENCE, COPY1;\n\n ORIGINAL :- \"THIS IS CONSTANT TEXT\";\n ORIGINAL.SETPOS(1);\n REFERENCE :- ORIGINAL;\n\n! RUN TIME ERROR:\n! ORIGINAL.PUTCHAR('X');\n! \"copy-a-string.sim\", line 9: ./copy-a-string: Putchar: Constant text object\n;\n\n OUTTEXT(ORIGINAL);\n OUTIMAGE;\n\n ! CONTENT EQUAL? => T ;\n OUTTEXT(IF ORIGINAL = REFERENCE THEN \"T\" ELSE \"F\");\n OUTIMAGE;\n\n ! SAME TEXT OBJECT? => T ;\n OUTTEXT(IF ORIGINAL == REFERENCE THEN \"T\" ELSE \"F\");\n OUTIMAGE;\n\n COPY1 :- COPY(ORIGINAL);\n COPY1.SETPOS(1);\n COPY1.PUTCHAR('X');\n OUTTEXT(COPY1);\n OUTIMAGE;\nEND;\n", "language": "Simula" }, { "code": "10 LET A$=\"BECAUSE I DO NOT HOPE TO TURN AGAIN\"\n20 LET B$=A$\n30 LET A$=A$( TO 21)\n40 PRINT B$\n50 PRINT A$\n60 LET B$=A$+B$(22 TO 29)\n70 PRINT B$\n", "language": "Sinclair-ZX81-BASIC" }, { "code": "[ | :s | s == s copy] applyTo: {'hello'}. \"returns False\"\n", "language": "Slate" }, { "code": "|s1 s2|\n\"bind the var s1 to the object string on the right\"\ns1 := 'i am a string'.\n\"bind the var s2 to the same object...\"\ns2 := s1.\n\"bind s2 to a copy of the object bound to s1\"\ns2 := (s1 copy).\n", "language": "Smalltalk" }, { "code": "* copy a to b\n b = a = \"test\"\n output = a\n output = b\n* change the copy\n b \"t\" = \"T\"\n output = b\nend\n", "language": "SNOBOL4" }, { "code": "val src = \"Hello\";\nval srcCopy = CharArray.array (size src, #\"x\"); (* 'x' is just dummy character *)\nCharArray.copyVec {src = src, dst = srcCopy, di = 0};\nsrc = CharArray.vector srcCopy; (* evaluates to true *)\n", "language": "Standard-ML" }, { "code": "val srcCopy2 = CharArray.array (CharArray.length srcCopy, #\"x\"); (* 'x' is just dummy character *)\nCharArray.copy {src = srcCopy, dst = srcCopy2, di = 0};\n", "language": "Standard-ML" }, { "code": "var src = \"Hello\"\nvar dst = src\n", "language": "Swift" }, { "code": "set src \"Rosetta Code\"\nset dst $src\n", "language": "Tcl" }, { "code": ":\"Rosetta Code\"→Str1\n:Str1→Str2\n", "language": "TI-83-BASIC" }, { "code": ":\"Rosetta Code\"→str1\n:str1→str2\n", "language": "TI-89-BASIC" }, { "code": "\" hello\" is-data a\na string.clone is-data b\n", "language": "Toka" }, { "code": "#lang transd\n\nMainModule : {\n _start: (λ\n (with s \"Hello!\" s1 \"\" s2 \"\"\n (= s1 s) // duplication of 's' content\n (rebind s2 s) // another reference to 's'\n (= s \"Good bye!\")\n (lout s)\n (lout s1)\n (lout s2)\n )\n )\n}\n", "language": "Transd" }, { "code": "\"Hello\" dup\n", "language": "Trith" }, { "code": "LET src$ = \"Hello\"\nLET dst$ = src$\nLET src$ = \" world...\"\nPRINT dst$; src$\nEND\n", "language": "True-BASIC" }, { "code": "$$ MODE TUSCRIPT\nstr=\"Hello\"\ndst=str\n", "language": "TUSCRIPT" }, { "code": "foo=\"Hello\"\nbar=$foo # This is a copy of the string\n", "language": "UNIX-Shell" }, { "code": "decl string a b\nset a \"hello\"\nset b a\n", "language": "Ursa" }, { "code": "\"hello\" dup\n", "language": "V" }, { "code": "text := \"Hello\"\ncopy_of := text\nprintln(copy_of)\n", "language": "V-(Vlang)" }, { "code": "Sub copystring()\n a = \"Hello World!\"\n b = a\n a = \"I'm gone\"\n Debug.Print b\n Debug.Print a\nEnd Sub\n", "language": "VBA" }, { "code": "let str1 = \"original string\"\nlet str2 = str1\nlet str1 = \"new string\"\n\necho \"String 1:\" str1\necho \"String 2:\" str2\n", "language": "Vim-Script" }, { "code": "'Immutable Strings\nDim a = \"Test string\"\nDim b = a 'reference to same string\nDim c = New String(a.ToCharArray) 'new string, normally not used\n\n'Mutable Strings\nDim x As New Text.StringBuilder(\"Test string\")\nDim y = x 'reference\nDim z = New Text.StringBuilder(x.ToString) 'new string\n", "language": "Visual-Basic-.NET" }, { "code": "Dim a As String = \"Test String\"\nDim b As String = String.Copy(a) ' New string\n", "language": "Visual-Basic-.NET" }, { "code": "var s = \"wren\"\nvar t = s\nSystem.print(\"Are 's' and 't' equal? %(s == t)\")\n", "language": "Wren" }, { "code": "option casemap:none\noption literals:on\n\nprintf proto :dword, :VARARG\nexit proto :dword\n\n.data\n s db \"Goodbye, World!\",0\n\n.data?\n d db 20 dup (?)\n dp dq ?\n tb dd ?\n\n.code\nmain proc\n lea rsi, s ;; Put the address of var S into the source index(RSI)\n xor rcx, rcx ;; Zero out RCX\n _getsize:\n inc rcx ;; Advanced the index by 1\n cmp byte ptr [rsi+rcx],0 ;; check the current byte for terminating 0\n jne _getsize ;; nope, jump back and check again\n\n mov tb, ecx ;; tb = Total bytes, Keep a copy of the size of the string\n lea rsi, s ;; Copy the address of s into the source index(rsi)\n lea rdi, d ;; Copy the address of d into the destination index(rdi)\n rep movsb ;; Copy bytes from ESI to EDI until RCX is 0\n\n lea rax, s ;; Get the address of S\n mov dp, rax ;; Copy it from RAX to dp\n\n mov rbx,rdi ;; Make a copy of RDI, cause over writes due to ABI call args T_T\n invoke printf, CSTR(\"-> s (0x%x) = %s\",10), rsi, addr s\n invoke printf, CSTR(\"-> d (0x%x) = %s\",10), rbx, addr d\n invoke printf, CSTR(\"-> dp (0x%x) = %s\",10), addr dp, dp\n invoke printf, CSTR(\"-> bytes copied: %i\",10), tb\n xor rsi, rsi\n call exit\n ret\nmain endp\n\nend\n", "language": "X86-64-Assembly" }, { "code": "%macro sysdef 2\n %define sys_%1 %2\n%endmacro\nsysdef write, 1\n\n%macro prolog 1\n push rbp\n mov rbp, rsp\n sub rsp, %1\n%endmacro\n\n%macro epilog 1\n add rsp, %1\n pop rbp\n%endmacro\n\n%macro xlea 2\n lea %1, [rel %2]\n%endmacro\n\n%macro inv 1-7 0,0,0,0,0,0\n mov r9,%7\n mov r8,%6\n mov r10,%5\n mov rdx,%4\n mov rsi,%3\n mov rdi,%2\n mov rax,sys_%1\n syscall\n%endmacro\n\nsection .rodata\nsz1 db \"Goodbye, World!\",0xa,0\n\nsection .bss\nsz2 resq 1\n\nsection .text\n strlcpy:\n prolog 0x38\n %define dest rbp-0x18\n %define src rbp-0x10\n %define n rbp-0x8\n\n mov qword [rbp-0x28], rdi\n mov qword [rbp-0x30], rsi\n mov qword [rbp-0x38], rdx\n mov rax, qword [rbp-0x28]\n mov qword [dest], rax\n mov rax, qword [rbp-0x30]\n mov qword [src], rax\n mov rax, qword [rbp-0x38]\n mov qword [n], rax\n cmp qword [n], 0\n je _stlc_done\n _stlc_doloop:\n dec qword [n]\n cmp qword [n], 0\n je _stlc_done\n mov rbx, qword [src]\n lea rax, [rbx+1]\n mov qword [src], rax\n mov rax, qword [dest]\n lea rcx, [rax+1]\n mov qword [dest], rcx\n movzx ebx, byte [rbx]\n mov byte [rax], bl\n movzx eax, byte [rax]\n test al, al\n je _stlc_done\n jmp _stlc_doloop\n _stlc_done:\n epilog 0x38\n ret\n\n strlen:\n prolog 0x10\n %define s rbp-0x8\n\n mov qword [rbp-0x10], rdi\n mov rax, qword [rbp-0x10]\n mov qword [s], rax\n mov rsi, qword [s]\n xor rcx, rcx\n _stl_count:\n cmp byte [rsi+rcx], 0\n je _stl_exit\n inc rcx\n jne _stl_count\n _stl_exit:\n mov rax, rcx\n epilog 0x10\n ret\n\n global main\n main:\n prolog 0x20\n %define tmp rbp-0x20\n xlea rbx, sz1\n mov qword [tmp], rbx\n mov rdi, qword [tmp]\n call strlen\n mov rcx, rax\n push rcx\n mov rdx, rcx\n xlea rsi, sz1\n xlea rdi, sz2\n call strlcpy\n xlea rbx, sz2\n pop rcx\n inv write, 1, rbx, rcx\n inv exit, 0\n epilog 0x20\n ret\n", "language": "X86-64-Assembly" }, { "code": "section .data\n string db \"Hello World\", 0\n\nsection .bss\n string2 resb 12\n\nsection .text\nglobal _main\n_main:\n mov ecx, 0\n looping:\n mov al, [string + ecx]\n mov [string2 + ecx], al\n inc ecx\n cmp al, 0 ;copy until we find the terminating 0\n je end\n jmp looping\n end:\n xor eax, eax\n ret\n", "language": "X86-Assembly" }, { "code": "section .data\n string db 11,\"Hello World\"\n\nsection .bss\n string2 resb 12\n\nsection .text\nglobal _main\n_main:\n xor ecx, ecx ;clear ecx\n mov cl, [string]\n mov [string2], cl ;copy byte signaling length\n mov edx, 1\n looping: ;copy each single byte\n mov al, [string + edx]\n mov [string2 + edx], al\n inc edx\n dec ecx\n cmp ecx, 0\n jg looping\n xor eax, eax\n ret\n", "language": "X86-Assembly" }, { "code": "proc StrCopy(A, B); \\Copy string: A --> B\nchar A, B; \\Strings: B must already have enough space \"Reserved\"\nint I; \\Beware if strings overlap\nfor I:= 0 to -1>>1-1 do\n [B(I):= A(I);\n if A(I) >= $80 then return\n ];\n\nchar S1, S2, S3(13);\n[S1:= \"Hello, world!\"; \\S1 now points to the string\nS2:= S1; \\S2 now also points to the string\nStrCopy(S1, S3); \\S3 points to a separate copy of the string\n]\n", "language": "XPL0" }, { "code": "src$ = \"Hello\"\ndst$ = src$\nsrc$ = \" world...\"\nprint dst$, src$\nend\n", "language": "Yabasic" }, { "code": "ld hl,MyString\nld (PointerVariable),hl\n\nMyString: ;assembler equates this label to a memory location at compile time\nbyte \"Hello\",0\n\nPointerVariable:\nword 0 ;placeholder for the address of the above string, gets written to by the code above.\n", "language": "Z80-Assembly" }, { "code": "ld a,<MyString ; < represents the low byte of the address. Some assemblers use LOW() with the label in the parentheses.\nld (PointerVariable),a\nld a,>MyString ; > represents the high byte of the address. Some assemblers use HIGH() with the label in the parentheses.\nld (PointerVariable+1),a\n", "language": "Z80-Assembly" }, { "code": "StrCpy:\n;input: HL = base address of string you wish to copy\n; DE = where you want to copy it to.\n; This program assumes that the string is null-terminated, and that there is enough RAM to hold the entire string.\n\n ld a,(hl)\n or a ;compare A to 0.\n ret z\n ld (de),a\n inc hl\n inc de\n jr StrCpy\n", "language": "Z80-Assembly" }, { "code": "ld hl,myString\nld c,(hl)\nld b,0\ninc c\nld de,buffer\nldir ;copies from (HL) to (DE), BC times.\nret\n\nmyString:\nbyte 5 ;len(\"Hello\")\nbyte \"Hello\"\n\nbuffer:\nbyte 0\nbyte 0,0,0,0,0\n", "language": "Z80-Assembly" }, { "code": "const std = @import(\"std\");\n\nconst debug = std.debug;\nconst mem = std.mem;\n\ntest \"copy a string\" {\n const source = \"A string.\";\n\n // Variable `dest1` will have the same type as `source`, which is\n // `*const [9:0]u8`.\n const dest1 = source;\n\n // Variable `dest2`'s type is [9]u8.\n //\n // The difference between the two is that `dest1` string is null-terminated,\n // while `dest2` is not.\n var dest2: [source.len]u8 = undefined;\n mem.copy(u8, dest2[0..], source[0..]);\n\n debug.assert(mem.eql(u8, dest1[0..], \"A string.\"));\n debug.assert(mem.eql(u8, dest2[0..], \"A string.\"));\n}\n", "language": "Zig" }, { "code": "\"abc\".copy() // noop\n", "language": "Zkl" }, { "code": "module Main;\nvar\n\ts,r: string;\n\tc: array 60 of char;\nbegin\n\ts := \"plain string\";r := s; writeln(s);\n\t(* copy string to array of char *)\n\tcopy(s,c);c[0] := 'P';\n\t(* copy array of char to string *)\n\tcopy(c,r);writeln(r);\nend Main.\n", "language": "Zonnon" }, { "code": "var a\nvar b\na = \"World\"\nb = a\na = \"Hello\"\nprint (a,\" \",b)\n", "language": "Zoomscript" }, { "code": "10 LET a$ = \"Hello\": REM a$ is the original string\n20 LET b$ = a$: REM b$ is the copy\n", "language": "ZX-Spectrum-Basic" } ]
Copy-a-string
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Copy_stdin_to_stdout\n", "language": "00-META" }, { "code": "Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.\n\n", "language": "00-TASK" }, { "code": "READ:\tequ\t3Fh\t\t; MS-DOS syscalls\nWRITE:\tequ\t40h\nBUFSZ:\tequ\t4000h\t\t; Buffer size\n\tcpu\t8086\n\tbits\t16\n\torg\t100h\nsection\t.text\nread:\tmov\tah,READ\t\t; Read into buffer\n\txor\tbx,bx\t\t; From STDIN (file 0)\n\tmov\tcx,BUFSZ\n\tmov\tdx,buffer\n\tint\t21h\n\ttest\tax,ax\t\t; Did we read anything?\n\tjz\tdone\t\t; If not, stop\n\txchg\tax,cx\t\t; Write as many bytes as read\n\tmov\tah,WRITE\n\tinc\tbx\t\t; To STDOUT (file 1)\n\tint\t21h\n\tjmp\tread\t\t; Go get more\ndone:\tret\t\nsection\t.bss\nbuffer:\tresb\tBUFSZ\n", "language": "8086-Assembly" }, { "code": "PROC Main()\n CHAR c\n\n DO\n c=GetD(7)\n Put(c)\n UNTIL c=27 ;repeat until Esc key is pressed\n OD\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO;\n\nprocedure Copy_Stdin_To_Stdout is\n use Ada.Text_IO;\n C : Character;\nbegin\n while not End_Of_File loop\n Get_Immediate (C);\n Put (C);\n end loop;\nend Copy_Stdin_To_Stdout;\n", "language": "Ada" }, { "code": "file f;\ndata b;\nf.stdin;\nwhile (f.b_line(b) ^ -1) {\n o_(b, \"\\n\");\n}\n", "language": "Aime" }, { "code": "BEGIN\n BOOL at eof := FALSE;\n # set the EOF handler for stand in to a procedure that sets \"at eof\" to true #\n # and returns true so processing can continue #\n on logical file end( stand in, ( REF FILE f )BOOL: at eof := TRUE );\n # copy stand in to stand out #\n WHILE STRING line; read( ( line, newline ) ); NOT at eof DO write( ( line, newline ) ) OD\nEND\n", "language": "ALGOL-68" }, { "code": "0 GET C$ : PRINT C$; : GOTO\n", "language": "Applesoft-BASIC" }, { "code": "awk \"//\"\n", "language": "AWK" }, { "code": "get \"libhdr\"\n\nlet start() be\n$( let c = rdch()\n if c = endstreamch then finish\n wrch(c)\n$) repeat\n", "language": "BCPL" }, { "code": ",[.,]\n", "language": "Brainf---" }, { "code": "#include <stdio.h>\n\nint main(){\n char c;\n while ( (c=getchar()) != EOF ){\n putchar(c);\n }\n return 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <iterator>\n\nint main() {\n using namespace std;\n noskipws(cin);\n copy(\n istream_iterator<char>(cin),\n istream_iterator<char>(),\n ostream_iterator<char>(cout)\n );\n return 0;\n}\n", "language": "C++" }, { "code": "#include <iostream>\n\nint main() {\n std::cout << std::cin.rdbuf();\n}\n", "language": "C++" }, { "code": "using System;\n\nclass Program\n{\n static void Main(string[] args)\n {\n Console.OpenStandardInput().CopyTo(Console.OpenStandardOutput());\n }\n}\n", "language": "C-sharp" }, { "code": "start_up = proc ()\n pi: stream := stream$primary_input()\n po: stream := stream$primary_output()\n\n while true do\n stream$putc(po, stream$getc(pi))\n end except when end_of_file:\n return\n end\nend start_up\n", "language": "CLU" }, { "code": "10 print chr$(147);chr$(14);\n11 print \"0:Keyboard 1:Tape 2:RS-232 3:Screen\"\n12 print \"4-7:printers/plotters\"\n13 print \"8-11:Disk Drives\":print\n14 input \"Input device\";d1\n15 if d1=1 or d1>=8 then input \"Filename for INPUT\";i$\n16 input \"Output device\";d2\n17 if d2=1 or d2>=8 then input \"Filename for OUTPUT\";o$\n18 print:if d1=0 then print \"Begin typing. Press CTRL-Z to end.\":print\n20 open 5,d1,5,\"0:\"+i$+\",s,r\"\n30 open 2,d2,2,\"@0:\"+o$+\",s,w\"\n40 get#5,a$\n50 if (d1=0 and a$=chr$(26)) or (d1>0 and st>0) then close 5:close 2:end\n60 print#2,a$;\n70 goto 40\n", "language": "Commodore-BASIC" }, { "code": "#|Loops while reading and collecting characters from STDIN until EOF (C-Z or C-D)\nThen concatenates the characters into a string|#\n(format t\n (concatenate 'string\n (loop for x = (read-char *query-io*) until (or (char= x #\\Sub) (char= x #\\Eot)) collecting x)))\n", "language": "Common-Lisp" }, { "code": "STDIN.each_line do |line|\n puts line\nend\n", "language": "Crystal" }, { "code": "import std.stdio;\n\nvoid main() {\n foreach (line; stdin.byLine) {\n writeln(line);\n }\n}\n", "language": "D" }, { "code": "import 'dart:io';\n\nvoid main() {\n var line = stdin.readLineSync();\n stdout.write(line);\n}\n", "language": "Dart" }, { "code": "\\util.g\n\nproc nonrec main() void:\n char c;\n while\n /* I/O is line-oriented, so first read characters\n * from the current line while that is possible */\n while read(c) do write(c) od;\n case ioerror()\n /* Then once it fails, if the line is empty,\n * try to go to the next line. */\n incase CH_MISSING:\n readln();\n writeln();\n true\n /* If it failed for another reason (which will be\n * EOF here), stop. */\n default:\n false\n esac\n do od\ncorp\n", "language": "Draco" }, { "code": "let copy()=let n,g=stdin,stdout\n let rec fN()=match n.ReadLine() with \"EOF\"->g.Write \"\" |i->g.WriteLine i; fN()\n fN()\ncopy()\n", "language": "F-Sharp" }, { "code": "USING: io kernel ;\n\n[ read1 dup ] [ write1 ] while drop\n", "language": "Factor" }, { "code": "stdin slurp-fid type bye\n", "language": "Forth" }, { "code": "#define FIN 255 'eof is already a reserved word\n#include \"crt/stdio.bi\" 'provides the C functions getchar and putchar\ndim as ubyte char\ndo\n char = getchar()\n if char = FIN then exit do else putchar(char)\nloop\n", "language": "FreeBASIC" }, { "code": "print[read[\"-\"]]\n", "language": "Frink" }, { "code": "package main\n\nimport (\n \"bufio\"\n \"io\"\n \"os\"\n)\n\nfunc main() {\n r := bufio.NewReader(os.Stdin)\n w := bufio.NewWriter(os.Stdout)\n for {\n b, err := r.ReadByte()\n if err == io.EOF {\n return\n }\n w.WriteByte(b)\n w.Flush()\n }\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\nfunc main() {\n\tio.Copy(os.Stdout, os.Stdin)\n}\n", "language": "Go" }, { "code": "class StdInToStdOut {\n static void main(args) {\n try (def reader = System.in.newReader()) {\n def line\n while ((line = reader.readLine()) != null) {\n println line\n }\n }\n }\n}\n", "language": "Groovy" }, { "code": "main = interact id\n", "language": "Haskell" }, { "code": "import java.util.Scanner;\n\npublic class CopyStdinToStdout {\n\n public static void main(String[] args) {\n try (Scanner scanner = new Scanner(System.in);) {\n String s;\n while ( (s = scanner.nextLine()).compareTo(\"\") != 0 ) {\n System.out.println(s);\n }\n }\n }\n\n}\n", "language": "Java" }, { "code": "process.stdin.resume();\nprocess.stdin.pipe(process.stdout);\n", "language": "JavaScript" }, { "code": "node index.js < index.js\n", "language": "JavaScript" }, { "code": "jq -Rr .\n", "language": "Jq" }, { "code": "while !eof(stdin)\n write(stdout, read(stdin, UInt8))\nend\n", "language": "Julia" }, { "code": "fun main() {\n var c: Int\n do {\n c = System.`in`.read()\n System.out.write(c)\n } while (c >= 0)\n}\n", "language": "Kotlin" }, { "code": "while { $stdin eof? not. } do {\n $stdout putln: $stdin readln.\n}.\n", "language": "Latitude" }, { "code": ":- module stdin_to_stdout.\n:- interface.\n\n:- import_module io.\n\n:- pred main(io::di, io::uo) is det.\n\n%-----------------------------------------------------------------------------%\n%-----------------------------------------------------------------------------%\n\n:- implementation.\n\n:- import_module char.\n:- import_module list.\n:- import_module string.\n\n%-----------------------------------------------------------------------------%\n\n\n\nmain(!IO) :-\n io.read_line_as_string(Result, !IO),\n (\n Result = ok(Line),\n io.write_string(Line, !IO),\n main(!IO)\n ;\n Result = eof\n ;\n Result = error(Error),\n io.error_message(Error, Message),\n io.input_stream_name(StreamName, !IO),\n io.progname(\"stdin_to_stdout\", ProgName, !IO),\n io.write_strings([\n ProgName, \": \",\n \"error reading from `\", StreamName, \"': \\n\\t\",\n Message, \"\\n\"\n ], !IO)\n ).\n\n%-----------------------------------------------------------------------------%\n", "language": "Mercury" }, { "code": "stdout.write readAll(stdin)\n", "language": "Nim" }, { "code": "try\n while true do\n output_char stdout (input_char stdin)\n done\nwith End_of_file -> ()\n", "language": "OCaml" }, { "code": "(bytestream->port (port->bytestream stdin) stdout)\n", "language": "Ol" }, { "code": "program writeInput(input, output);\nvar\n\tbuffer: char;\nbegin\n\twhile not EOF() do\n\tbegin\n\t\tread(buffer); // shorthand for read(input, buffer)\n\t\twrite(buffer); // shorthand for write(output, buffer)\n\tend;\nend.\n", "language": "Pascal" }, { "code": "perl -pe ''\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">wait_key</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">#1B</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n<!--\n", "language": "Phix" }, { "code": "(in NIL (echo))\n", "language": "PicoLisp" }, { "code": "%File: stdin_to_stdout.pl\n:- initialization(main).\n\nmain :- repeat,\n\tget_char(X),\n\tput_char(X),\n\tX == end_of_file,\n\tfail.\n", "language": "Prolog" }, { "code": "swipl stdin_to_stdout.pl\n", "language": "Prolog" }, { "code": "#lang racket\n\n(let loop ()\n (match (read-char)\n [(? eof-object?) (void)]\n [c (display c)\n (loop)]))\n", "language": "Racket" }, { "code": "raku -pe'.lines'\n", "language": "Raku" }, { "code": ".say for lines\n", "language": "Raku" }, { "code": "/*REXX pgm copies data from STDIN──►STDOUT (default input stream──►default output stream*/\n\n do while chars()\\==0 /*repeat loop until no more characters.*/\n call charin , x /*read a char from the input stream. */\n call charout , x /*write \" \" \" \" output \" */\n end /*while*/ /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "? \"give input: \" give str\n? \"output: \" + str\n", "language": "Ring" }, { "code": "$stdout << $stdin.gets\n", "language": "Ruby" }, { "code": "use std::io;\n\nfn main() {\n io::copy(&mut io::stdin().lock(), &mut io::stdout().lock());\n}\n", "language": "Rust" }, { "code": "object CopyStdinToStdout extends App {\n io.Source.fromInputStream(System.in).getLines().foreach(println)\n}\n", "language": "Scala" }, { "code": "scala -e \"io.Source.fromInputStream(System.in).getLines().foreach(println)\"\n", "language": "Scala" }, { "code": "(do ((c (read-char) (read-char)))\n ((eof-object? c) 'done)\n (display c))\n", "language": "Scheme" }, { "code": "sed -e ''\n", "language": "Sed" }, { "code": "$ include \"seed7_05.s7i\";\n include \"fileutil.s7i\";\n\nconst proc: main is func\n begin\n copyFile(IN, OUT);\n end func;\n", "language": "Seed7" }, { "code": "\"using Stream class's bulk copy method:\"\nStdin copyToEndInto:Stdout.\n\n\"line wise\"\n[Stdin atEnd] whileFalse:[ Stdout nextPutLine:(Stdin nextLine) ].\n\n\"character wise\"\n[Stdin atEnd] whileFalse:[ Stdout nextPut:(Stdin next) ].\n\n\"no EOF test, but handle EOF Exception\"\n[\n [ Stdout nextPut:(Stdin next) ] loop.\n] on: StreamError do:[]\n", "language": "Smalltalk" }, { "code": "fun copyLoop () =\n case TextIO.input TextIO.stdIn of\n \"\" => ()\n | tx => copyLoop (TextIO.output (TextIO.stdOut, tx))\n\nval () = copyLoop ()\n", "language": "Standard-ML" }, { "code": "Loop [] []\n go Loop\n", "language": "Symsyn" }, { "code": "package require Tcl 8.5\n\nchan copy stdin stdout\n# fcopy stdin stdout for older versions\n", "language": "Tcl" }, { "code": "do\n s=wscript.stdin.readline\n wscript.stdout.writeline s\nloop until asc(left(s,1))=26\n", "language": "VBScript" }, { "code": "import \"io\" for Stdin, Stdout\n\nStdin.isRaw = true // prevents echoing to the terminal\nwhile (true) {\n var byte = Stdin.readByte() // read a byte from stdin\n if (byte == 13) break // break when enter key pressed\n System.write(String.fromByte(byte)) // write the byte (in string form) to stdout\n Stdout.flush() // flush output\n}\nSystem.print()\nStdin.isRaw = false\n", "language": "Wren" }, { "code": "int C;\nloop [C:= ChIn(1);\n if C = $1A \\EOF\\ then quit;\n ChOut(0, C);\n ]\n", "language": "XPL0" }, { "code": "zkl --eval \"File.stdout.write(File.stdin.read())\"\n", "language": "Zkl" } ]
Copy-stdin-to-stdout
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Count_in_factors\nnote: Prime Numbers\n", "language": "00-META" }, { "code": ";Task:\nWrite a program which counts up from &nbsp; '''1''', &nbsp; displaying each number as the multiplication of its prime factors. \n\nFor the purpose of this task, &nbsp; '''1''' &nbsp; (unity) &nbsp; may be shown as itself.\n\n\n;Example:\n&nbsp; &nbsp; &nbsp; '''2''' &nbsp; is prime, &nbsp; so it would be shown as itself. \n<br>&nbsp; &nbsp; &nbsp; '''6''' &nbsp; is not prime; &nbsp; it would be shown as &nbsp; '''<math>2\\times3</math>.''' \n<br>'''2144''' &nbsp; is not prime; &nbsp; it would be shown as &nbsp; '''<math>2\\times2\\times2\\times2\\times2\\times67</math>.'''\n\n\n;Related tasks:\n* &nbsp; [[prime decomposition]]\n* &nbsp; [[factors of an integer]]\n* &nbsp; [[Sieve of Eratosthenes]]\n* &nbsp; [[primality by trial division]]\n* &nbsp; [[factors of a Mersenne number]]\n* &nbsp; [[trial factoring of a Mersenne number]]\n* &nbsp; [[partition an integer X into N primes]]\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F get_prime_factors(=li)\n I li == 1\n R ‘1’\n E\n V res = ‘’\n V f = 2\n L\n I li % f == 0\n res ‘’= f\n li /= f\n I li == 1\n L.break\n res ‘’= ‘ x ’\n E\n f++\n R res\n\nL(x) 1..17\n print(‘#4: #.’.format(x, get_prime_factors(x)))\nprint(‘2144: ’get_prime_factors(2144))\n", "language": "11l" }, { "code": "* Count in factors 24/03/2017\nCOUNTFAC CSECT assist plig\\COUNTFAC\n USING COUNTFAC,R13 base register\n B 72(R15) skip savearea\n DC 17F'0' savearea\n STM R14,R12,12(R13) save previous context\n ST R13,4(R15) link backward\n ST R15,8(R13) link forward\n LR R13,R15 set addressability\n L R6,=F'1' i=1\n DO WHILE=(C,R6,LE,=F'40') do i=1 to 40\n LR R7,R6 n=i\n MVI F,X'01' f=true\n MVC PG,=CL80' ' clear buffer\n LA R10,PG pgi=0\n XDECO R6,XDEC edit i\n MVC 0(12,R10),XDEC output i\n LA R10,12(R10) pgi=pgi+12\n MVC 0(1,R10),=C'=' output '='\n LA R10,1(R10) pgi=pgi+1\n IF C,R7,EQ,=F'1' THEN if n=1 then\n MVI 0(R10),C'1' output n\n ELSE , else\n LA R8,2 p=2\n DO WHILE=(CR,R8,LE,R7) do while p<=n\n LR R4,R7 n\n SRDA R4,32 ~\n DR R4,R8 /p\n IF LTR,R4,Z,R4 THEN if n//p=0 then\n IF CLI,F,EQ,X'00' THEN if not f then\n MVC 0(1,R10),=C'*' output '*'\n LA R10,1(R10) pgi=pgi+1\n ELSE , else\n MVI F,X'00' f=false\n ENDIF , endif\n CVD R8,PP convert bin p to packed pp\n MVC WORK12,MASX12 in fact L13\n EDMK WORK12,PP+2 edit and mark\n LA R9,WORK12+12 end of string(p)\n SR R9,R1 li=lengh(p) {r1 from edmk}\n MVC EDIT12,WORK12 L12<-L13\n LA R4,EDIT12+12 source+12\n SR R4,R9 -lengh(p)\n LR R5,R9 lengh(p)\n LR R2,R10 target ix\n LR R3,R9 lengh(p)\n MVCL R2,R4 f=f||p\n AR R10,R9 ix=ix+lengh(p)\n LR R4,R7 n\n SRDA R4,32 ~\n DR R4,R8 /p\n LR R7,R5 n=n/p\n ELSE , else\n LA R8,1(R8) p=p+1\n ENDIF , endif\n ENDDO , enddo while\n ENDIF , endif\n XPRNT PG,L'PG print buffer\n LA R6,1(R6) i++\n ENDDO , enddo i\n L R13,4(0,R13) restore previous savearea pointer\n LM R14,R12,12(R13) restore previous context\n XR R15,R15 rc=0\n BR R14 exit\nF DS X flag first factor\n DS 0D alignment for cvd\nPP DS PL8 packed CL8\nEDIT12 DS CL12 target CL12\nWORK12 DS CL13 char CL13\nMASX12 DC X'40',9X'20',X'212060' CL13\nXDEC DS CL12 temp\nPG DS CL80 buffer\n YREGS\n END COUNTFAC\n", "language": "360-Assembly" }, { "code": "PROC PrintFactors(CARD a)\n BYTE notFirst\n CARD p\n\n IF a=1 THEN\n PrintC(a) RETURN\n FI\n\n p=2 notFirst=0\n WHILE p<=a\n DO\n IF a MOD p=0 THEN\n IF notFirst THEN\n Put('x)\n FI\n notFirst=1\n PrintC(p)\n a==/p\n ELSE\n p==+1\n FI\n OD\nRETURN\n\nPROC Main()\n CARD i\n\n FOR i=1 TO 1000\n DO\n PrintC(i) Put('=)\n PrintFactors(i)\n PutE()\n OD\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Command_Line, Ada.Text_IO, Prime_Numbers;\n\nprocedure Count is\n package Prime_Nums is new Prime_Numbers\n (Number => Natural, Zero => 0, One => 1, Two => 2); use Prime_Nums;\n\n procedure Put (List : Number_List) is\n begin\n for Index in List'Range loop\n Ada.Text_IO.Put (Integer'Image (List (Index)));\n if Index /= List'Last then\n Ada.Text_IO.Put (\" x\");\n end if;\n end loop;\n end Put;\n\n N : Natural := 1;\n Max_N : Natural := 15; -- the default for Max_N\nbegin\n if Ada.Command_Line.Argument_Count = 1 then -- read Max_N from command line\n Max_N := Integer'Value (Ada.Command_Line.Argument (1));\n end if; -- else use the default\n loop\n Ada.Text_IO.Put (Integer'Image (N) & \": \");\n Put (Decompose (N));\n Ada.Text_IO.New_Line;\n N := N + 1;\n exit when N > Max_N;\n end loop;\nend Count;\n", "language": "Ada" }, { "code": "OP +:= = (REF FLEX []INT a, INT b) VOID:\n BEGIN\n [UPB a + 1] INT c;\n c[:UPB a] := a;\n c[UPB a+1:] := b;\n a := c\n END;\n\n\nPROC factorize = (INT nn) []INT:\n BEGIN\n IF nn = 1 THEN (1)\n ELSE\n\t INT k := 2, n := nn;\n\t FLEX[0]INT result;\n\t WHILE n > 1 DO\n\t WHILE n MOD k = 0 DO\n\t\t result +:= k;\n\t\t n := n % k\n\t OD;\n\t k +:= 1\n\t OD;\n\t result\n FI\n END;\n\nFLEX[0]INT factors;\nFOR i TO 22 DO\n factors := factorize (i);\n print ((whole (i, 0), \" = \"));\n FOR j TO UPB factors DO\n (j /= 1 | print (\" × \"));\n\tprint ((whole (factors[j], 0)))\n OD;\n print ((new line))\nOD\n", "language": "ALGOL-68" }, { "code": "begin % show numbers and their prime factors %\n % shows nand its prime factors %\n procedure showFactors ( integer value n ) ;\n if n <= 3 then write( i_w := 1, s_w := 0, n, \": \", n )\n else begin\n integer v, f; logical first;\n first := true;\n v := n;\n write( i_w := 1, s_w := 0, n, \": \" );\n while not odd( v ) and v > 1 do begin\n if not first then writeon( s_w := 0, \" x \" );\n writeon( i_w := 1, s_w := 0, 2 );\n v := v div 2;\n first := false\n end while_not_odd_v ;\n f := 1;\n while v > 1 do begin\n f := f + 2;\n while v rem f = 0 do begin\n if not first then writeon( s_w := 0, \" x \" );\n writeon( i_w := 1, s_w := 0, f );\n v := v div f;\n first := false\n end while_v_rem_f_eq_0\n end while_v_gt_0_and_f_le_v\n end showFactors ;\n\n % show the factors of various ranges - same as Wren %\n for i := 1 until 9 do showFactors( i );\n write( \"... \" );\n for i := 2144 until 2154 do showFactors( i );\n write( \"... \" );\n for i := 9987 until 9999 do showFactors( i )\nend.\n", "language": "ALGOL-W" }, { "code": " 100 FOR I = 1 TO 20\n 110 GOSUB 200\"FACTORIAL\n 120 PRINT I\" = \"FA$\n 130 NEXT I\n 140 END\n\n 200 FA$ = \"1\"\n 210 LET NUM = I\n 220 LET O = 5 - (I = 1) * 4\n 230 FOR F = 2 TO I\n 240 LET M = INT (NUM / F) * F\n 250 IF NUM - M GOTO 300\n 260 LET NUM = NUM / F\n 270 LET F$ = STR $(F)\n 280 FA$ = FA$ + \" X \" + F$\n 290 LET F = F - 1\n\n 300 NEXT F\n 310 FA$ = MID$ (FA$,O)\n 320 RETURN\n", "language": "Applesoft-BASIC" }, { "code": "/* ARM assembly Raspberry PI */\n/* program countFactors.s */\n\n /* REMARK 1 : this program use routines in a include file\n see task Include a file language arm assembly\n for the routine affichageMess conversion10\n see at end of this program the instruction include */\n/* for constantes see task include a file in arm assembly */\n/************************************/\n/* Constantes */\n/************************************/\n.include \"../constantes.inc\"\n.equ NBFACT, 33\n.equ MAXI, 1<<31\n\n//.equ NOMBRE, 65537\n//.equ NOMBRE, 99999999\n.equ NOMBRE, 2144\n//.equ NOMBRE, 529\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessNumber: .asciz \"Number @ : \"\nszMessResultFact: .asciz \"@ \"\nszCarriageReturn: .asciz \"\\n\"\nszErrorGen: .asciz \"Program error !!!\\n\"\nszMessPrime: .asciz \"This number is prime.\\n\"\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\nsZoneConv: .skip 24\ntbZoneDecom: .skip 8 * NBFACT // factor 4 bytes, number of each factor 4 bytes\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: @ entry of program\n ldr r7,iNombre @ number\n mov r0,r7\n ldr r1,iAdrsZoneConv\n bl conversion10 @ call décimal conversion\n ldr r0,iAdrszMessNumber\n ldr r1,iAdrsZoneConv @ insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess @ display message\n mov r0,r7\n ldr r1,iAdrtbZoneDecom\n bl decompFact\n cmp r0,#-1\n beq 98f @ error ?\n mov r1,r0\n ldr r0,iAdrtbZoneDecom\n bl displayDivisors\n\n b 100f\n98:\n ldr r0,iAdrszErrorGen\n bl affichageMess\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\niAdrszCarriageReturn: .int szCarriageReturn\niAdrszMessResultFact: .int szMessResultFact\niAdrszErrorGen: .int szErrorGen\niAdrsZoneConv: .int sZoneConv\niAdrtbZoneDecom: .int tbZoneDecom\niAdrszMessNumber: .int szMessNumber\niNombre: .int NOMBRE\n/******************************************************************/\n/* display divisors function */\n/******************************************************************/\n/* r0 contains address of divisors area */\n/* r1 contains the number of area items */\ndisplayDivisors:\n push {r2-r8,lr} @ save registers\n cmp r1,#0\n beq 100f\n mov r2,r1\n mov r3,#0 @ indice\n mov r4,r0\n1:\n add r5,r4,r3,lsl #3\n ldr r7,[r5] @ load factor\n ldr r6,[r5,#4] @ load number of factor\n mov r8,#0 @ display factor counter\n2:\n mov r0,r7\n ldr r1,iAdrsZoneConv\n bl conversion10 @ call décimal conversion\n ldr r0,iAdrszMessResultFact\n ldr r1,iAdrsZoneConv @ insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess @ display message\n add r8,#1 @ increment counter\n cmp r8,r6 @ same factors number ?\n blt 2b\n add r3,#1 @ other ithem\n cmp r3,r2 @ items maxi ?\n blt 1b\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n b 100f\n\n100:\n pop {r2-r8,lr} @ restaur registers\n bx lr @ return\n/******************************************************************/\n/* factor decomposition */\n/******************************************************************/\n/* r0 contains number */\n/* r1 contains address of divisors area */\n/* r0 return divisors items in table */\ndecompFact:\n push {r1-r8,lr} @ save registers\n mov r5,r1\n mov r8,r0 @ save number\n bl isPrime @ prime ?\n cmp r0,#1\n beq 98f @ yes is prime\n mov r4,#0 @ raz indice\n mov r1,#2 @ first divisor\n mov r6,#0 @ previous divisor\n mov r7,#0 @ number of same divisors\n2:\n mov r0,r8 @ dividende\n bl division @ r1 divisor r2 quotient r3 remainder\n cmp r3,#0\n bne 5f @ if remainder <> zero -> no divisor\n mov r8,r2 @ else quotient -> new dividende\n cmp r1,r6 @ same divisor ?\n beq 4f @ yes\n cmp r6,#0 @ no but is the first divisor ?\n beq 3f @ yes\n str r6,[r5,r4,lsl #2] @ else store in the table\n add r4,r4,#1 @ and increment counter\n str r7,[r5,r4,lsl #2] @ store counter\n add r4,r4,#1 @ next item\n mov r7,#0 @ and raz counter\n3:\n mov r6,r1 @ new divisor\n4:\n add r7,r7,#1 @ increment counter\n b 7f @ and loop\n\n /* not divisor -> increment next divisor */\n5:\n cmp r1,#2 @ if divisor = 2 -> add 1\n addeq r1,#1\n addne r1,#2 @ else add 2\n b 2b\n\n /* divisor -> test if new dividende is prime */\n7:\n mov r3,r1 @ save divisor\n cmp r8,#1 @ dividende = 1 ? -> end\n beq 10f\n mov r0,r8 @ new dividende is prime ?\n mov r1,#0\n bl isPrime @ the new dividende is prime ?\n cmp r0,#1\n bne 10f @ the new dividende is not prime\n\n cmp r8,r6 @ else dividende is same divisor ?\n beq 9f @ yes\n cmp r6,#0 @ no but is the first divisor ?\n beq 8f @ yes it is a first\n str r6,[r5,r4,lsl #2] @ else store in table\n add r4,r4,#1 @ and increment counter\n str r7,[r5,r4,lsl #2] @ and store counter\n add r4,r4,#1 @ next item\n8:\n mov r6,r8 @ new dividende -> divisor prec\n mov r7,#0 @ and raz counter\n9:\n add r7,r7,#1 @ increment counter\n b 11f\n\n10:\n mov r1,r3 @ current divisor = new divisor\n cmp r1,r8 @ current divisor > new dividende ?\n ble 2b @ no -> loop\n\n /* end decomposition */\n11:\n str r6,[r5,r4,lsl #2] @ store last divisor\n add r4,r4,#1\n str r7,[r5,r4,lsl #2] @ and store last number of same divisors\n add r4,r4,#1\n lsr r0,r4,#1 @ return number of table items\n mov r3,#0\n str r3,[r5,r4,lsl #2] @ store zéro in last table item\n add r4,r4,#1\n str r3,[r5,r4,lsl #2] @ and zero in counter same divisor\n b 100f\n\n\n98:\n ldr r0,iAdrszMessPrime\n bl affichageMess\n mov r0,#1 @ return code\n b 100f\n99:\n ldr r0,iAdrszErrorGen\n bl affichageMess\n mov r0,#-1 @ error code\n b 100f\n100:\n pop {r1-r8,lr} @ restaur registers\n bx lr\niAdrszMessPrime: .int szMessPrime\n\n/***************************************************/\n/* check if a number is prime */\n/***************************************************/\n/* r0 contains the number */\n/* r0 return 1 if prime 0 else */\n@2147483647\n@4294967297\n@131071\nisPrime:\n push {r1-r6,lr} @ save registers\n cmp r0,#0\n beq 90f\n cmp r0,#17\n bhi 1f\n cmp r0,#3\n bls 80f @ for 1,2,3 return prime\n cmp r0,#5\n beq 80f @ for 5 return prime\n cmp r0,#7\n beq 80f @ for 7 return prime\n cmp r0,#11\n beq 80f @ for 11 return prime\n cmp r0,#13\n beq 80f @ for 13 return prime\n cmp r0,#17\n beq 80f @ for 17 return prime\n1:\n tst r0,#1 @ even ?\n beq 90f @ yes -> not prime\n mov r2,r0 @ save number\n sub r1,r0,#1 @ exposant n - 1\n mov r0,#3 @ base\n bl moduloPuR32 @ compute base power n - 1 modulo n\n cmp r0,#1\n bne 90f @ if <> 1 -> not prime\n\n mov r0,#5\n bl moduloPuR32\n cmp r0,#1\n bne 90f\n\n mov r0,#7\n bl moduloPuR32\n cmp r0,#1\n bne 90f\n\n mov r0,#11\n bl moduloPuR32\n cmp r0,#1\n bne 90f\n\n mov r0,#13\n bl moduloPuR32\n cmp r0,#1\n bne 90f\n\n mov r0,#17\n bl moduloPuR32\n cmp r0,#1\n bne 90f\n80:\n mov r0,#1 @ is prime\n b 100f\n90:\n mov r0,#0 @ no prime\n100: @ fin standard de la fonction\n pop {r1-r6,lr} @ restaur des registres\n bx lr @ retour de la fonction en utilisant lr\n/********************************************************/\n/* Calcul modulo de b puissance e modulo m */\n/* Exemple 4 puissance 13 modulo 497 = 445 */\n/* */\n/********************************************************/\n/* r0 nombre */\n/* r1 exposant */\n/* r2 modulo */\n/* r0 return result */\nmoduloPuR32:\n push {r1-r7,lr} @ save registers\n cmp r0,#0 @ verif <> zero\n beq 100f\n cmp r2,#0 @ verif <> zero\n beq 100f @\n1:\n mov r4,r2 @ save modulo\n mov r5,r1 @ save exposant\n mov r6,r0 @ save base\n mov r3,#1 @ start result\n\n mov r1,#0 @ division de r0,r1 par r2\n bl division32R\n mov r6,r2 @ base <- remainder\n2:\n tst r5,#1 @ exposant even or odd\n beq 3f\n umull r0,r1,r6,r3\n mov r2,r4\n bl division32R\n mov r3,r2 @ result <- remainder\n3:\n umull r0,r1,r6,r6\n mov r2,r4\n bl division32R\n mov r6,r2 @ base <- remainder\n\n lsr r5,#1 @ left shift 1 bit\n cmp r5,#0 @ end ?\n bne 2b\n mov r0,r3\n100: @ fin standard de la fonction\n pop {r1-r7,lr} @ restaur des registres\n bx lr @ retour de la fonction en utilisant lr\n\n/***************************************************/\n/* division number 64 bits in 2 registers by number 32 bits */\n/***************************************************/\n/* r0 contains lower part dividende */\n/* r1 contains upper part dividende */\n/* r2 contains divisor */\n/* r0 return lower part quotient */\n/* r1 return upper part quotient */\n/* r2 return remainder */\ndivision32R:\n push {r3-r9,lr} @ save registers\n mov r6,#0 @ init upper upper part remainder !!\n mov r7,r1 @ init upper part remainder with upper part dividende\n mov r8,r0 @ init lower part remainder with lower part dividende\n mov r9,#0 @ upper part quotient\n mov r4,#0 @ lower part quotient\n mov r5,#32 @ bits number\n1: @ begin loop\n lsl r6,#1 @ shift upper upper part remainder\n lsls r7,#1 @ shift upper part remainder\n orrcs r6,#1\n lsls r8,#1 @ shift lower part remainder\n orrcs r7,#1\n lsls r4,#1 @ shift lower part quotient\n lsl r9,#1 @ shift upper part quotient\n orrcs r9,#1\n @ divisor sustract upper part remainder\n subs r7,r2\n sbcs r6,#0 @ and substract carry\n bmi 2f @ négative ?\n\n @ positive or equal\n orr r4,#1 @ 1 -> right bit quotient\n b 3f\n2: @ negative\n orr r4,#0 @ 0 -> right bit quotient\n adds r7,r2 @ and restaur remainder\n adc r6,#0\n3:\n subs r5,#1 @ decrement bit size\n bgt 1b @ end ?\n mov r0,r4 @ lower part quotient\n mov r1,r9 @ upper part quotient\n mov r2,r7 @ remainder\n100: @ function end\n pop {r3-r9,lr} @ restaur registers\n bx lr\n\n\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n.include \"../affichage.inc\"\n", "language": "ARM-Assembly" }, { "code": "loop 1..30 'x [\n fs: [1]\n if x<>1 -> fs: factors.prime x\n print [pad to :string x 3 \"=\" join.with:\" x \" to [:string] fs]\n]\n", "language": "Arturo" }, { "code": "factorize(n){\n\tif n = 1\n\t\treturn 1\n\tif n < 1\n\t\treturn false\n\tresult := 0, m := n, k := 2\n\tWhile n >= k{\n\t\twhile !Mod(m, k){\n\t\t\tresult .= \" * \" . k, m /= k\n\t\t}\n\t\tk++\n\t}\n\treturn SubStr(result, 5)\n}\nLoop 22\n out .= A_Index \": \" factorize(A_index) \"`n\"\nMsgBox % out\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f COUNT_IN_FACTORS.AWK\nBEGIN {\n fmt = \"%d=%s\\n\"\n for (i=1; i<=16; i++) {\n printf(fmt,i,factors(i))\n }\n i = 2144; printf(fmt,i,factors(i))\n i = 6358; printf(fmt,i,factors(i))\n exit(0)\n}\nfunction factors(n, f,p) {\n if (n == 1) {\n return(1)\n }\n p = 2\n while (p <= n) {\n if (n % p == 0) {\n f = sprintf(\"%s%s*\",f,p)\n n /= p\n }\n else {\n p++\n }\n }\n return(substr(f,1,length(f)-1))\n}\n", "language": "AWK" }, { "code": "for i = 1 to 20\n print i; \" = \"; factorial$(i)\nnext i\nend\n\nfunction factorial$ (num)\n factor$ = \"\" : x$ = \"\"\n if num = 1 then return \"1\"\n fct = 2\n while fct <= num\n if (num mod fct) = 0 then\n factor$ += x$ + string(fct)\n x$ = \" x \"\n num /= fct\n else\n fct += 1\n end if\n end while\n return factor$\nend function\n", "language": "BASIC256" }, { "code": " FOR i% = 1 TO 20\n PRINT i% \" = \" FNfactors(i%)\n NEXT\n END\n\n DEF FNfactors(N%)\n LOCAL P%, f$\n IF N% = 1 THEN = \"1\"\n P% = 2\n WHILE P% <= N%\n IF (N% MOD P%) = 0 THEN\n f$ += STR$(P%) + \" x \"\n N% DIV= P%\n ELSE\n P% += 1\n ENDIF\n ENDWHILE\n = LEFT$(f$, LEN(f$) - 3)\n", "language": "BBC-BASIC" }, { "code": "1>>>>:.48*\"=\",,::1-#v_.v\n$<<<^_@#-\"e\":+1,+55$2<<<\nv4_^#-1:/.:g00_00g1+>>0v\n>8*\"x\",,:00g%!^!%g00:p0<\n", "language": "Befunge" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned long long ULONG;\n\nULONG get_prime(int idx)\n{\n static long n_primes = 0, alloc = 0;\n static ULONG *primes = 0;\n ULONG last, p;\n int i;\n\n if (idx >= n_primes) {\n if (n_primes >= alloc) {\n alloc += 16; /* be conservative */\n primes = realloc(primes, sizeof(ULONG) * alloc);\n }\n if (!n_primes) {\n primes[0] = 2;\n primes[1] = 3;\n n_primes = 2;\n }\n\n last = primes[n_primes-1];\n while (idx >= n_primes) {\n last += 2;\n for (i = 0; i < n_primes; i++) {\n p = primes[i];\n if (p * p > last) {\n primes[n_primes++] = last;\n break;\n }\n if (last % p == 0) break;\n }\n }\n }\n return primes[idx];\n}\n\nint main()\n{\n ULONG n, x, p;\n int i, first;\n\n for (x = 1; ; x++) {\n printf(\"%lld = \", n = x);\n\n for (i = 0, first = 1; ; i++) {\n p = get_prime(i);\n while (n % p == 0) {\n n /= p;\n if (!first) printf(\" x \");\n first = 0;\n printf(\"%lld\", p);\n }\n if (n <= p * p) break;\n }\n\n if (first) printf(\"%lld\\n\", n);\n else if (n > 1) printf(\" x %lld\\n\", n);\n else printf(\"\\n\");\n }\n return 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <iomanip>\nusing namespace std;\n\nvoid getPrimeFactors( int li )\n{\n int f = 2; string res;\n if ( li == 1 ) res = \"1\";\n else\n {\n\twhile ( true )\n\t{\n\t if( !( li % f ) )\n\t {\n\t\tres += to_string(f);\n\t\tli /= f; if( li == 1 ) break;\n\t\tres += \" x \";\n\t }\n\t else f++;\n\t}\n }\n cout << res << \"\\n\";\n}\n\nint main( int argc, char* argv[] )\n{\n for ( int x = 1; x < 101; x++ )\n {\n\tcout << right << setw( 4 ) << x << \": \";\n\tgetPrimeFactors( x );\n }\n cout << 2144 << \": \"; getPrimeFactors( 2144 );\n cout << \"\\n\\n\";\n return system( \"pause\" );\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tfor( int i=1; i<=22; i++ )\n\t\t\t{\t\t\t\t\n\t\t\t\tList<int> f = Factorize(i);\n\t\t\t\tConsole.Write( i + \": \" + f[0] );\n\t\t\t\tfor( int j=1; j<f.Count; j++ )\n\t\t\t\t{\n\t\t\t\t\tConsole.Write( \" * \" + f[j] );\n\t\t\t\t}\n\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static List<int> Factorize( int n )\n\t\t{\n\t\t\tList<int> l = new List<int>();\n\t\t\n\t\t\tif ( n == 1 )\n\t\t\t{\n\t\t\t\tl.Add(1);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint k = 2;\n\t\t\t\twhile( n > 1 )\n\t\t\t\t{\n\t\t\t\t\twhile( n % k == 0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tl.Add( k );\n\t\t\t\t\t\tn /= k;\n\t\t\t\t\t}\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t\treturn l;\n\t\t}\t\n\t}\n}\n", "language": "C-sharp" }, { "code": "100 cls\n110 for i = 1 to 20\n120 rem for i = 1000 to 1016\n130 print i;\"= \";factorial$(i)\n140 next i\n150 end\n160 function factorial$(num)\n170 factor$ = \"\" : x$ = \"\"\n180 if num = 1 then print \"1\"\n190 fct = 2\n200 while fct <= num\n210 if (num mod fct) = 0 then\n220 factor$ = factor$+x$+str$(fct)\n230 x$ = \" x \"\n240 num = num/fct\n250 else\n260 fct = fct+1\n270 endif\n280 wend\n290 print factor$\n300 end function\n", "language": "Chipmunk-Basic" }, { "code": "(ns listfactors\n (:gen-class))\n\n(defn factors\n \"Return a list of factors of N.\"\n ([n]\n (factors n 2 ()))\n ([n k acc]\n (cond\n (= n 1) (if (empty? acc)\n [n]\n (sort acc))\n (>= k n) (if (empty? acc)\n [n]\n (sort (cons n acc)))\n (= 0 (rem n k)) (recur (quot n k) k (cons k acc))\n :else (recur n (inc k) acc))))\n\n(doseq [q (range 1 26)]\n (println q \" = \" (clojure.string/join \" x \"(factors q))))\n", "language": "Clojure" }, { "code": "count_primes = (max) ->\n # Count through the natural numbers and give their prime\n # factorization. This algorithm uses no division.\n # Instead, each prime number starts a rolling odometer\n # to help subsequent factorizations. The algorithm works similar\n # to the Sieve of Eratosthenes, as we note when each prime number's\n # odometer rolls a digit. (As it turns out, as long as your computer\n # is not horribly slow at division, you're better off just doing simple\n # prime factorizations on each new n vs. using this algorithm.)\n console.log \"1 = 1\"\n primes = []\n n = 2\n while n <= max\n factors = []\n for prime_odometer in primes\n # digits are an array w/least significant digit in\n # position 0; for example, [3, [0]] will roll as\n # follows:\n # [0] -> [1] -> [2] -> [0, 1]\n [base, digits] = prime_odometer\n i = 0\n while true\n digits[i] += 1\n break if digits[i] < base\n digits[i] = 0\n factors.push base\n i += 1\n if i >= digits.length\n digits.push 0\n\n if factors.length == 0\n primes.push [n, [0, 1]]\n factors.push n\n console.log \"#{n} = #{factors.join('*')}\"\n n += 1\n\n primes.length\n\nnum_primes = count_primes 10000\nconsole.log num_primes\n", "language": "CoffeeScript" }, { "code": "(defparameter *primes*\n (make-array 10 :adjustable t :fill-pointer 0 :element-type 'integer))\n\n(mapc #'(lambda (x) (vector-push x *primes*)) '(2 3 5 7))\n\n(defun extend-primes (n)\n (let ((p (+ 2 (elt *primes* (1- (length *primes*))))))\n (loop for i = p then (+ 2 i)\n\t while (<= (* i i) n) do\n\t (if (primep i t) (vector-push-extend i *primes*)))))\n\n(defun primep (n &optional skip)\n (if (not skip) (extend-primes n))\n (if (= n 1) nil\n (loop for p across *primes* while (<= (* p p) n)\n\t never (zerop (mod n p)))))\n\n(defun factors (n)\n (extend-primes n)\n (loop with res for x across *primes* while (> n (* x x)) do\n\t(loop while (zerop (rem n x)) do\n\t (setf n (/ n x))\n\t (push x res))\n\tfinally (return (if (> n 1) (cons n res) res))))\n\n(loop for n from 1 do\n (format t \"~a: ~{~a~^ × ~}~%\" n (reverse (factors n))))\n", "language": "Common-Lisp" }, { "code": "(defun factors (n)\n (loop with res for x from 2 to (isqrt n) do\n\t(loop while (zerop (rem n x)) do\n\t (setf n (/ n x))\n\t (push x res))\n\tfinally (return (if (> n 1) (cons n res) res))))\n\n(loop for n from 1 do\n (format t \"~a: ~{~a~^ × ~}~%\" n (reverse (factors n))))\n", "language": "Common-Lisp" }, { "code": "int[] factorize(in int n) pure nothrow\nin {\n assert(n > 0);\n} body {\n if (n == 1) return [1];\n int[] result;\n int m = n, k = 2;\n while (n >= k) {\n while (m % k == 0) {\n result ~= k;\n m /= k;\n }\n k++;\n }\n return result;\n}\n\nvoid main() {\n import std.stdio;\n foreach (i; 1 .. 22)\n writefln(\"%d: %(%d × %)\", i, i.factorize());\n}\n", "language": "D" }, { "code": "import std.stdio, std.math, std.conv, std.algorithm,\n std.array, std.string, import xt.uiprimes;\n\npragma(lib, \"uiprimes.lib\");\n\n// function _factorize_ included in uiprimes.lib\nulong[] factorize(ulong n) {\n if (n == 0) return [];\n if (n == 1) return [1];\n ulong[] res;\n uint limit = cast(uint)(1 + sqrt(n));\n foreach (p; Primes(limit)) {\n if (n == 1) break;\n if (0UL == (n % p))\n while((n > 1) && (0UL == (n % p ))) {\n res ~= p;\n n /= p;\n }\n }\n if (n > 1)\n res ~= [n];\n return res;\n}\n\nstring productStr(T)(in T[] nums) {\n return nums.map!text().join(\" x \");\n}\n\nvoid main() {\n foreach (i; 1 .. 21)\n writefln(\"%2d = %s\", i, productStr(factorize(i)));\n}\n", "language": "D" }, { "code": "$ close /nolog primes\n$ on control_y then $ goto clean\n$\n$ n = 1\n$ outer_loop:\n$ x = n\n$ open primes primes.txt\n$\n$ loop1:\n$ read /end_of_file = prime primes prime\n$ prime = f$integer( prime )\n$ loop2:\n$ t = x / prime\n$ if t * prime .eq. x\n$ then\n$ if f$type( factorization ) .eqs. \"\"\n$ then\n$ factorization = f$string( prime )\n$ else\n$ factorization = factorization + \"*\" + f$string( prime )\n$ endif\n$ if t .eq. 1 then $ goto done\n$ x = t\n$ goto loop2\n$ else\n$ goto loop1\n$ endif\n$ prime:\n$ if f$type( factorization ) .eqs. \"\"\n$ then\n$ factorization = f$string( x )\n$ else\n$ factorization = factorization + \"*\" + f$string( x )\n$ endif\n$ done:\n$ write sys$output f$fao( \"!4SL = \", n ), factorization\n$ delete /symbol factorization\n$ close primes\n$ n = n + 1\n$ if n .le. 2144 then $ goto outer_loop\n$ exit\n$\n$ clean:\n$ close /nolog primes\n", "language": "DCL" }, { "code": "function Factorize(n : Integer) : String;\nbegin\n if n <= 1 then\n Exit('1');\n var k := 2;\n while n >= k do begin\n while (n mod k) = 0 do begin\n Result += ' * '+IntToStr(k);\n n := n div k;\n end;\n Inc(k);\n end;\n Result:=SubStr(Result, 4);\nend;\n\nvar i : Integer;\nfor i := 1 to 22 do\n PrintLn(IntToStr(i) + ': ' + Factorize(i));\n", "language": "DWScript" }, { "code": "proc decompose num . primes[] .\n primes[] = [ ]\n t = 2\n while t * t <= num\n if num mod t = 0\n primes[] &= t\n num = num / t\n else\n t += 1\n .\n .\n primes[] &= num\n.\nfor i = 1 to 30\n write i & \": \"\n decompose i primes[]\n for j = 1 to len primes[]\n if j > 1\n write \" x \"\n .\n write primes[j]\n .\n print \"\"\n primes[] = [ ]\n.\n", "language": "EasyLang" }, { "code": "(define (task (nfrom 2) (range 20))\n (for ((i (in-range nfrom (+ nfrom range))))\n (writeln i \"=\" (string-join (prime-factors i) \" x \"))))\n", "language": "EchoLisp" }, { "code": "class\n\tCOUNT_IN_FACTORS\n\nfeature\n\n\tdisplay_factor (p: INTEGER)\n\t\t\t-- Factors of all integers up to 'p'.\n\t\trequire\n\t\t\tp_positive: p > 0\n\t\tlocal\n\t\t\tfactors: ARRAY [INTEGER]\n\t\tdo\n\t\t\tacross\n\t\t\t\t1 |..| p as c\n\t\t\tloop\n\t\t\t\tio.new_line\n\t\t\t\tio.put_string (c.item.out + \"%T\")\n\t\t\t\tfactors := factor (c.item)\n\t\t\t\tacross\n\t\t\t\t\tfactors as f\n\t\t\t\tloop\n\t\t\t\t\tio.put_integer (f.item)\n\t\t\t\t\tif f.is_last = False then\n\t\t\t\t\t\tio.put_string (\" x \")\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\n factor (p: INTEGER): ARRAY [INTEGER]\n\t\t\t-- Prime decomposition of 'p'.\n\t\trequire\n\t\t\tp_positive: p > 0\n\t\tlocal\n\t\t\tdiv, i, next, rest: INTEGER\n\t\tdo\n\t\t\tcreate Result.make_empty\n\t\t\tif p = 1 then\n\t\t\t\tResult.force (1, 1)\n\t\t\tend\n\t\t\tdiv := 2\n\t\t\tnext := 3\n\t\t\trest := p\n\t\t\tfrom\n\t\t\t\ti := 1\n\t\t\tuntil\n\t\t\t\trest = 1\n\t\t\tloop\n\t\t\t\tfrom\n\t\t\t\tuntil\n\t\t\t\t\trest \\\\ div /= 0\n\t\t\t\tloop\n\t\t\t\t\tResult.force (div, i)\n\t\t\t\t\trest := (rest / div).floor\n\t\t\t\t\ti := i + 1\n\t\t\t\tend\n\t\t\t\tdiv := next\n\t\t\t\tnext := next + 2\n\t\t\tend\n\t\tensure\n\t\t\tis_divisor: across Result as r all p \\\\ r.item = 0 end\n\t\tend\nend\n", "language": "Eiffel" }, { "code": "defmodule RC do\n def factor(n), do: factor(n, 2, [])\n\n def factor(n, i, fact) when n < i*i, do: Enum.reverse([n|fact])\n def factor(n, i, fact) do\n if rem(n,i)==0, do: factor(div(n,i), i, [i|fact]),\n else: factor(n, i+1, fact)\n end\nend\n\nEnum.each(1..20, fn n ->\n IO.puts \"#{n}: #{Enum.join(RC.factor(n),\" x \")}\" end)\n", "language": "Elixir" }, { "code": "function factorize(integer n)\n sequence result\n integer k\n if n = 1 then\n return {1}\n else\n k = 2\n result = {}\n while n > 1 do\n while remainder(n, k) = 0 do\n result &= k\n n /= k\n end while\n k += 1\n end while\n return result\n end if\nend function\n\nsequence factors\nfor i = 1 to 22 do\n printf(1, \"%d: \", i)\n factors = factorize(i)\n for j = 1 to length(factors)-1 do\n printf(1, \"%d * \", factors[j])\n end for\n printf(1, \"%d\\n\", factors[$])\nend for\n", "language": "Euphoria" }, { "code": "let factorsOf (num) =\n Seq.unfold (fun (f, n) ->\n let rec genFactor (f, n) =\n if f > n then None\n elif n % f = 0 then Some (f, (f, n/f))\n else genFactor (f+1, n)\n genFactor (f, n)) (2, num)\n\nlet showLines = Seq.concat (seq { yield seq{ yield(Seq.singleton 1)}; yield (Seq.skip 2 (Seq.initInfinite factorsOf))})\n\nshowLines |> Seq.iteri (fun i f -> printfn \"%d = %s\" (i+1) (String.Join(\" * \", Seq.toArray f)))\n", "language": "F-Sharp" }, { "code": "USING: io kernel math.primes.factors math.ranges prettyprint\nsequences ;\n\n: .factors ( n -- )\n dup pprint \": \" write factors\n [ \" × \" write ] [ pprint ] interleave nl ;\n\n\"1: 1\" print 2 20 [a,b] [ .factors ] each\n", "language": "Factor" }, { "code": ": .factors ( n -- )\n 2\n begin 2dup dup * >=\n while 2dup /mod swap\n if drop 1+ 1 or \\ next odd number\n else -rot nip dup . .\" x \"\n then\n repeat\n drop . ;\n\n: main ( n -- )\n .\" 1 : 1\" cr\n 1+ 2 ?do i . .\" : \" i .factors cr loop ;\n\n15 main bye\n", "language": "Forth" }, { "code": "!-*- mode: compilation; default-directory: \"/tmp/\" -*-\n!Compilation started at Thu Jun 6 23:29:06\n!\n!a=./f && make $a && echo -2 | OMP_NUM_THREADS=2 $a\n!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f\n! assert 1 = */ 1\n! assert 2 = */ 2\n! assert 3 = */ 3\n! assert 4 = */ 2 2\n! assert 5 = */ 5\n! assert 6 = */ 2 3\n! assert 7 = */ 7\n! assert 8 = */ 2 2 2\n! assert 9 = */ 3 3\n! assert 10 = */ 2 5\n! assert 11 = */ 11\n! assert 12 = */ 3 2 2\n! assert 13 = */ 13\n! assert 14 = */ 2 7\n! assert 15 = */ 3 5\n! assert 16 = */ 2 2 2 2\n! assert 17 = */ 17\n! assert 18 = */ 3 2 3\n! assert 19 = */ 19\n! assert 20 = */ 2 2 5\n! assert 21 = */ 3 7\n! assert 22 = */ 2 11\n! assert 23 = */ 23\n! assert 24 = */ 3 2 2 2\n! assert 25 = */ 5 5\n! assert 26 = */ 2 13\n! assert 27 = */ 3 3 3\n! assert 28 = */ 2 2 7\n! assert 29 = */ 29\n! assert 30 = */ 5 2 3\n! assert 31 = */ 31\n! assert 32 = */ 2 2 2 2 2\n! assert 33 = */ 3 11\n! assert 34 = */ 2 17\n! assert 35 = */ 5 7\n! assert 36 = */ 3 3 2 2\n! assert 37 = */ 37\n! assert 38 = */ 2 19\n! assert 39 = */ 3 13\n! assert 40 = */ 5 2 2 2\n\nmodule prime_mod\n\n ! sieve_table stores 0 in prime numbers, and a prime factor in composites.\n integer, dimension(:), allocatable :: sieve_table\n private :: PrimeQ\n\ncontains\n\n ! setup routine must be called first!\n subroutine sieve(n) ! populate sieve_table. If n is 0 it deallocates storage, invalidating sieve_table.\n integer, intent(in) :: n\n integer :: status, i, j\n if ((n .lt. 1) .or. allocated(sieve_table)) deallocate(sieve_table)\n if (n .lt. 1) return\n allocate(sieve_table(n), stat=status)\n if (status .ne. 0) stop 'cannot allocate space'\n sieve_table(1) = 1\n do i=2,int(sqrt(real(n)))+1\n if (sieve_table(i) .eq. 0) then\n do j = i*i, n, i\n sieve_table(j) = i\n end do\n end if\n end do\n end subroutine sieve\n\n subroutine check_sieve(n)\n integer, intent(in) :: n\n if (.not. (allocated(sieve_table) .and. ((1 .le. n) .and. (n .le. size(sieve_table))))) stop 'Call sieve first'\n end subroutine check_sieve\n\n logical function isPrime(p)\n integer, intent(in) :: p\n call check_sieve(p)\n isPrime = PrimeQ(p)\n end function isPrime\n\n logical function isComposite(p)\n integer, intent(in) :: p\n isComposite = .not. isPrime(p)\n end function isComposite\n\n logical function PrimeQ(p)\n integer, intent(in) :: p\n PrimeQ = sieve_table(p) .eq. 0\n end function PrimeQ\n\n subroutine prime_factors(p, rv, n)\n integer, intent(in) :: p ! number to factor\n integer, dimension(:), intent(out) :: rv ! the prime factors\n integer, intent(out) :: n ! number of factors returned\n integer :: i, m\n call check_sieve(p)\n m = p\n i = 1\n if (p .ne. 1) then\n do while ((.not. PrimeQ(m)) .and. (i .lt. size(rv)))\n rv(i) = sieve_table(m)\n m = m/rv(i)\n i = i+1\n end do\n end if\n if (i .le. size(rv)) rv(i) = m\n n = i\n end subroutine prime_factors\n\nend module prime_mod\n\nprogram count_in_factors\n use prime_mod\n integer :: i, n\n integer, dimension(8) :: factors\n call sieve(40) ! setup\n do i=1,40\n factors = 0\n call prime_factors(i, factors, n)\n write(6,*)'assert',i,'= */',factors(:n)\n end do\n call sieve(0) ! release memory\nend program count_in_factors\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nSub getPrimeFactors(factors() As UInteger, n As UInteger)\n If n < 2 Then Return\n Dim factor As UInteger = 2\n Do\n If n Mod factor = 0 Then\n Redim Preserve factors(0 To UBound(factors) + 1)\n factors(UBound(factors)) = factor\n n \\= factor\n If n = 1 Then Return\n Else\n factor += 1\n End If\n Loop\nEnd Sub\n\nDim factors() As UInteger\n\nFor i As UInteger = 1 To 20\n Print Using \"##\"; i;\n Print \" = \";\n If i > 1 Then\n Erase factors\n getPrimeFactors factors(), i\n For j As Integer = LBound(factors) To UBound(factors)\n Print factors(j);\n If j < UBound(factors) Then Print \" x \";\n Next j\n Print\n Else\n Print i\n End If\nNext i\n\nPrint\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "i = 1\nwhile true\n{\n println[join[\" x \", factorFlat[i]]]\n i = i + 1\n}\n", "language": "Frink" }, { "code": "local fn Factorial( num as long ) as CFStringRef\n CFStringRef x, f, result\n long fct\n f = @\"\" : x = @\"\"\n\n if num = 1 then result = @\" 1\" : exit fn\n fct = 2\n while ( fct <= num )\n if ( num mod fct == 0 )\n f = fn StringWithFormat( @\"%@%@%@\", f, x, str( fct ) )\n x = @\" x\"\n num = num / fct\n else\n fct++\n end if\n wend\n result = f\nend fn = result\n\nlong i\nfor i = 1 to 20\n printf @\"%2ld =%@\", i, fn Factorial(i)\nnext\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc main() {\n fmt.Println(\"1: 1\")\n for i := 2; ; i++ {\n fmt.Printf(\"%d: \", i)\n var x string\n for n, f := i, 2; n != 1; f++ {\n for m := n % f; m == 0; m = n % f {\n fmt.Print(x, f)\n x = \"×\"\n n /= f\n }\n }\n fmt.Println()\n }\n}\n", "language": "Go" }, { "code": "def factors(number) {\n if (number == 1) {\n return [1]\n }\n def factors = []\n BigInteger value = number\n BigInteger possibleFactor = 2\n while (possibleFactor <= value) {\n if (value % possibleFactor == 0) {\n factors << possibleFactor\n value /= possibleFactor\n } else {\n possibleFactor++\n }\n }\n factors\n}\nNumber.metaClass.factors = { factors(delegate) }\n\n((1..10) + (6351..6359)).each { number ->\n println \"$number = ${number.factors().join(' x ')}\"\n}\n", "language": "Groovy" }, { "code": "import Data.List (intercalate)\n\nshowFactors n = show n ++ \" = \" ++ (intercalate \" * \" . map show . factorize) n\n-- Pointfree form\nshowFactors = ((++) . show) <*> ((\" = \" ++) . intercalate \" * \" . map show . factorize)\n", "language": "Haskell" }, { "code": "Main> print 1 >> mapM_ (putStrLn . showFactors) [2..]\n1\n2 = 2\n3 = 3\n4 = 2 * 2\n5 = 5\n6 = 2 * 3\n7 = 7\n8 = 2 * 2 * 2\n9 = 3 * 3\n10 = 2 * 5\n11 = 11\n12 = 2 * 2 * 3\n. . .\n\nMain> mapM_ (putStrLn . showFactors) [2144..]\n2144 = 2 * 2 * 2 * 2 * 2 * 67\n2145 = 3 * 5 * 11 * 13\n2146 = 2 * 29 * 37\n2147 = 19 * 113\n2148 = 2 * 2 * 3 * 179\n2149 = 7 * 307\n2150 = 2 * 5 * 5 * 43\n2151 = 3 * 3 * 239\n2152 = 2 * 2 * 2 * 269\n2153 = 2153\n2154 = 2 * 3 * 359\n. . .\n\nMain> mapM_ (putStrLn . showFactors) [121231231232155..]\n121231231232155 = 5 * 11 * 419 * 5260630559\n121231231232156 = 2 * 2 * 97 * 1061 * 294487867\n121231231232157 = 3 * 3 * 3 * 131 * 34275157261\n121231231232158 = 2 * 19 * 67 * 1231 * 38681033\n121231231232159 = 121231231232159\n121231231232160 = 2 * 2 * 2 * 2 * 2 * 3 * 5 * 7 * 7 * 5154389083\n121231231232161 = 121231231232161\n121231231232162 = 2 * 60615615616081\n121231231232163 = 3 * 13 * 83 * 191089 * 195991\n121231231232164 = 2 * 2 * 253811 * 119410931\n121231231232165 = 5 * 137 * 176979899609\n. . .\n", "language": "Haskell" }, { "code": "procedure main()\nwrite(\"Press ^C to terminate\")\nevery f := [i:= 1] | factors(i := seq(2)) do {\n writes(i,\" : [\")\n every writes(\" \",!f|\"]\\n\")\n }\nend\n\nlink factors\n", "language": "Icon" }, { "code": "100 PROGRAM \"Factors.bas\"\n110 FOR I=1 TO 30\n120 PRINT I;\"= \";FACTORS$(I)\n130 NEXT\n140 DEF FACTORS$(N)\n150 LET F$=\"\"\n160 IF N=1 THEN\n170 LET FACTORS$=\"1\"\n180 ELSE\n190 LET P=2\n200 DO WHILE P<=N\n210 IF MOD(N,P)=0 THEN\n220 LET F$=F$&STR$(P)&\"*\"\n230 LET N=INT(N/P)\n240 ELSE\n250 LET P=P+1\n260 END IF\n270 LOOP\n280 LET FACTORS$=F$(1:LEN(F$)-1)\n290 END IF\n300 END DEF\n", "language": "IS-BASIC" }, { "code": "q:\n", "language": "J" }, { "code": " ('1 : 1',\":&> ,\"1 ': ',\"1 \":@q:) 2+i.10\n1 : 1\n2 : 2\n3 : 3\n4 : 2 2\n5 : 5\n6 : 2 3\n7 : 7\n8 : 2 2 2\n9 : 3 3\n10: 2 5\n11: 11\n", "language": "J" }, { "code": "public class CountingInFactors{\n public static void main(String[] args){\n for(int i = 1; i<= 10; i++){\n System.out.println(i + \" = \"+ countInFactors(i));\n }\n\n for(int i = 9991; i <= 10000; i++){\n \tSystem.out.println(i + \" = \"+ countInFactors(i));\n }\n }\n\n private static String countInFactors(int n){\n if(n == 1) return \"1\";\n\n StringBuilder sb = new StringBuilder();\n\n n = checkFactor(2, n, sb);\n if(n == 1) return sb.toString();\n\n n = checkFactor(3, n, sb);\n if(n == 1) return sb.toString();\n\n for(int i = 5; i <= n; i+= 2){\n if(i % 3 == 0)continue;\n\n n = checkFactor(i, n, sb);\n if(n == 1)break;\n }\n\n return sb.toString();\n }\n\n private static int checkFactor(int mult, int n, StringBuilder sb){\n while(n % mult == 0 ){\n if(sb.length() > 0) sb.append(\" x \");\n sb.append(mult);\n n /= mult;\n }\n return n;\n }\n}\n", "language": "Java" }, { "code": "for(i = 1; i <= 10; i++)\n console.log(i + \" : \" + factor(i).join(\" x \"));\n\nfunction factor(n) {\n var factors = [];\n if (n == 1) return [1];\n for(p = 2; p <= n; ) {\n\tif((n % p) == 0) {\n\t factors[factors.length] = p;\n\t n /= p;\n\t}\n\telse p++;\n }\n return factors;\n}\n", "language": "JavaScript" }, { "code": "# To take advantage of gojq's arbitrary-precision integer arithmetic:\ndef power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);\n\n# Input: a non-negative integer determining when to stop\ndef count_in_factors:\n \"1: 1\",\n (range(2;.) | \"\\(.): \\([factors] | join(\"x\"))\");\n\ndef count_in_factors($m;$n):\n if . == 1 then \"1: 1\" else empty end,\n (range($m;$n) | \"\\(.): \\([factors] | join(\"x\"))\");\n", "language": "Jq" }, { "code": "10 | count_in_factors,\n\"\",\ncount_in_factors(2144; 2145),\n\"\",\n(2|power(100) | count_in_factors(.; .+ 2))\n", "language": "Jq" }, { "code": "using Primes, Printf\nfunction strfactor(n::Integer)\n n > -2 || return \"-1 × \" * strfactor(-n)\n isprime(n) || n < 2 && return dec(n)\n f = factor(Vector{typeof(n)}, n)\n return join(f, \" × \")\nend\n\nlo, hi = -4, 40\nprintln(\"Factor print $lo to $hi:\")\nfor n in lo:hi\n @printf(\"%5d = %s\\n\", n, strfactor(n))\nend\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nfun isPrime(n: Int) : Boolean {\n if (n < 2) return false\n if (n % 2 == 0) return n == 2\n if (n % 3 == 0) return n == 3\n var d = 5\n while (d * d <= n) {\n if (n % d == 0) return false\n d += 2\n if (n % d == 0) return false\n d += 4\n }\n return true\n}\n\nfun getPrimeFactors(n: Int): List<Int> {\n val factors = mutableListOf<Int>()\n if (n < 1) return factors\n if (n == 1 || isPrime(n)) {\n factors.add(n)\n return factors\n }\n var factor = 2\n var nn = n\n while (true) {\n if (nn % factor == 0) {\n factors.add(factor)\n nn /= factor\n if (nn == 1) return factors\n if (isPrime(nn)) factor = nn\n }\n else if (factor >= 3) factor += 2\n else factor = 3\n }\n}\n\nfun main(args: Array<String>) {\n val list = (MutableList(22) { it + 1 } + 2144) + 6358\n for (i in list)\n println(\"${\"%4d\".format(i)} = ${getPrimeFactors(i).joinToString(\" * \")}\")\n}\n", "language": "Kotlin" }, { "code": "'see Run BASIC solution\nfor i = 1000 to 1016\n print i;\" = \"; factorial$(i)\nnext\nwait\nfunction factorial$(num)\n if num = 1 then factorial$ = \"1\"\n fct = 2\n while fct <= num\n if (num mod fct) = 0 then\n factorial$ = factorial$ ; x$ ; fct\n x$ = \" x \"\n num = num / fct\n else\n fct = fct + 1\n end if\n wend\nend function\n", "language": "Liberty-BASIC" }, { "code": "function factorize( n )\n if n == 1 then return {1} end\n\n local k = 2\n res = {}\n while n > 1 do\n\twhile n % k == 0 do\n\t res[#res+1] = k\n \t n = n / k\n\tend\n \tk = k + 1\n end\n return res\nend\n\nfor i = 1, 22 do\n io.write( i, \": \" )\n fac = factorize( i )\n io.write( fac[1] )\n for j = 2, #fac do\n\tio.write( \" * \", fac[j] )\n end\n print \"\"\nend\n", "language": "Lua" }, { "code": "Module Count_in_factors {\n\tInventory Known1=2@, 3@\n\tIsPrime=lambda Known1 (x as decimal) -> {\n\t\t=0=1\n\t\tif exist(Known1, x) then =1=1 : exit\n\t\tif x<=5 OR frac(x) then {if x == 2 OR x == 3 OR x == 5 then Append Known1, x : =1=1\n\t\tBreak}\n\t\tif frac(x/2) else exit\n\t\tif frac(x/3) else exit\n\t\tx1=sqrt(x):d = 5@\n\t\t{if frac(x/d ) else exit\n\t\t\td += 2: if d>x1 then Append Known1, x : =1=1 : exit\n\t\t\tif frac(x/d) else exit\n\t\t\td += 4: if d<= x1 else Append Known1, x : =1=1: exit\n\t\t\tloop\n\t\t}\n\t}\n\tdecompose=lambda IsPrime (n as decimal) -> {\n\t\tFactors=(,)\n\t\t{\n\t\t\tk=2@\n\t\t\tWhile frac(n/k)=0\n\t\t\t\tn/=k\n\t\t\t\tAppend Factors, (k,)\n\t\t\tEnd While\n\t\t\tif n=1 then exit\n\t\t\tk++\n\t\t\tWhile frac(n/k)=0\n\t\t\t\tn/=k\n\t\t\t\tAppend Factors, (k,)\n\t\t\tEnd While\n\t\t\tif n=1 then exit\n\t\t\t{\n\t\t\t\tk+=2\n\t\t\t\twhile not isprime(k) {k+=2}\n\t\t\t\tWhile frac(n/k)=0\n\t\t\t\t\tn/=k : Append Factors, (k,)\n\t\t\t\tEnd While\n\t\t\t\tif n=1 then exit\n\t\t\t\tloop\n\t\t\t}\n\t\t}\n\t\t=Factors\n\t}\n\tfold=lambda (a, f$)->{\n\t\tPush if$(len(f$)=0->f$, f$+\"x\")+str$(a,\"\")\n\t}\n\tPrint \"1=1\"\n\ti=1@\n\tdo\n\t\ti++\n\t\tPrint str$(i,\"\")+\"=\"+Decompose(i)#fold$(fold,\"\")\n\talways\n}\nCount_in_factors\n", "language": "M2000-Interpreter" }, { "code": "define(`for',\n `ifelse($#,0,``$0'',\n `ifelse(eval($2<=$3),1,\n `pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')dnl\ndefine(`by',\n `ifelse($1,$2,\n $1,\n `ifelse(eval($1%$2==0),1,\n `$2 x by(eval($1/$2),$2)',\n `by($1,eval($2+1))') ') ')dnl\ndefine(`wby',\n `$1 = ifelse($1,1,\n $1,\n `by($1,2)') ')dnl\n\nfor(`y',1,25,1, `wby(y)\n')\n", "language": "M4" }, { "code": "factorNum := proc(n)\n\tlocal i, j, firstNum;\n\tif n = 1 then\n\t\tprintf(\"%a\", 1);\n\tend if;\n\tfirstNum := true:\n\tfor i in ifactors(n)[2] do\n\t\tfor j to i[2] do\n\t\t\tif firstNum then\n\t\t\t\tprintf (\"%a\", i[1]);\n\t\t\t\tfirstNum := false:\n\t\t\telse\n\t\t\t\tprintf(\" x %a\", i[1]);\n\t\t\tend if;\n\t\tend do;\n\tend do;\n\tprintf(\"\\n\");\n\treturn NULL;\nend proc:\n\nfor i from 1 to 10 do\n\tprintf(\"%2a: \", i);\n\tfactorNum(i);\nend do;\n", "language": "Maple" }, { "code": "n = 2;\nWhile[n < 100,\n Print[Row[Riffle[Flatten[Map[Apply[ConstantArray, #] &, FactorInteger[n]]],\"*\"]]];\n n++]\n", "language": "Mathematica" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\nrunSample(arg)\nreturn\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod factor(val) public static\n rv = 1\n if val > 1 then do\n rv = ''\n loop n_ = val until n_ = 1\n parse checkFactor(2, n_, rv) n_ rv\n if n_ = 1 then leave n_\n parse checkFactor(3, n_, rv) n_ rv\n if n_ = 1 then leave n_\n loop m_ = 5 to n_ by 2 until n_ = 1\n if m_ // 3 = 0 then iterate m_\n parse checkFactor(m_, n_, rv) n_ rv\n end m_\n end n_\n end\n return rv\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod checkFactor(mult = long, n_ = long, fac) private static binary\n msym = 'x'\n loop while n_ // mult = 0\n fac = fac msym mult\n n_ = n_ % mult\n end\n fac = (fac.strip).strip('l', msym).space\n return n_ fac\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod runSample(arg) private static\n -- input is a list of pairs of numbers - no checking is done\n if arg = '' then arg = '1 11 89 101 1000 1020 10000 10010'\n loop while arg \\= ''\n parse arg lv rv arg\n say\n say '-'.copies(60)\n say lv.right(8) 'to' rv\n say '-'.copies(60)\n loop fv = lv to rv\n fac = factor(fv)\n pv = ''\n if fac.words = 1 & fac \\= 1 then pv = '<prime>'\n say fv.right(8) '=' fac pv\n end fv\n end\n return\n", "language": "NetRexx" }, { "code": "var primes = newSeq[int]()\n\nproc getPrime(idx: int): int =\n if idx >= primes.len:\n if primes.len == 0:\n primes.add 2\n primes.add 3\n\n var last = primes[primes.high]\n while idx >= primes.len:\n last += 2\n for i, p in primes:\n if p * p > last:\n primes.add last\n break\n if last mod p == 0:\n break\n\n return primes[idx]\n\nfor x in 1 ..< int32.high.int:\n stdout.write x, \" = \"\n var n = x\n var first = true\n\n for i in 0 ..< int32.high:\n let p = getPrime(i)\n while n mod p == 0:\n n = n div p\n if not first: stdout.write \" x \"\n first = false\n stdout.write p\n\n if n <= p * p:\n break\n\n if first > 0: echo n\n elif n > 1: echo \" x \", n\n else: echo \"\"\n", "language": "Nim" }, { "code": "class CountingInFactors {\n function : Main(args : String[]) ~ Nil {\n for(i := 1; i <= 10; i += 1;){\n count := CountInFactors(i);\n (\"{$i} = {$count}\")->PrintLine();\n };\n\n for(i := 9991; i <= 10000; i += 1;){\n count := CountInFactors(i);\n (\"{$i} = {$count}\")->PrintLine();\n };\n }\n\n function : CountInFactors(n : Int) ~ String {\n if(n = 1) {\n return \"1\";\n };\n\n sb := \"\";\n n := CheckFactor(2, n, sb);\n if(n = 1) {\n return sb;\n };\n\n n := CheckFactor(3, n, sb);\n if(n = 1) {\n return sb;\n };\n\n for(i := 5; i <= n; i += 2;) {\n if(i % 3 <> 0) {\n n := CheckFactor(i, n, sb);\n if(n = 1) {\n break;\n };\n };\n };\n\n return sb;\n }\n\n function : CheckFactor(mult : Int, n : Int, sb : String) ~ Int {\n while(n % mult = 0 ) {\n if(sb->Size() > 0) {\n sb->Append(\" x \");\n };\n sb->Append(mult);\n n /= mult;\n };\n\n return n;\n }\n}\n", "language": "Objeck" }, { "code": "open Big_int\n\nlet prime_decomposition x =\n let rec inner c p =\n if lt_big_int p (square_big_int c) then\n [p]\n else if eq_big_int (mod_big_int p c) zero_big_int then\n c :: inner c (div_big_int p c)\n else\n inner (succ_big_int c) p\n in\n inner (succ_big_int (succ_big_int zero_big_int)) x\n\nlet () =\n let rec aux v =\n let ps = prime_decomposition v in\n print_string (string_of_big_int v);\n print_string \" = \";\n print_endline (String.concat \" x \" (List.map string_of_big_int ps));\n aux (succ_big_int v)\n in\n aux unit_big_int\n", "language": "OCaml" }, { "code": "for (n = 1:20)\n printf (\"%i: \", n)\n printf (\"%i \", factor (n))\n printf (\"\\n\")\nendfor\n", "language": "Octave" }, { "code": "fnice(n)={\n\tmy(f,s=\"\",s1);\n\tif (n < 2, return(n));\n\tf = factor(n);\n\ts = Str(s, f[1,1]);\n\tif (f[1, 2] != 1, s=Str(s, \"^\", f[1,2]));\n\tfor(i=2,#f[,1], s1 = Str(\" * \", f[i, 1]); if (f[i, 2] != 1, s1 = Str(s1, \"^\", f[i, 2])); s = Str(s, s1));\n s\n};\n\nn=0;while(n++<21, printf(\"%2s: %s\\n\",n,fnice(n)))\n", "language": "PARI-GP" }, { "code": "program CountInFactors(output);\n\n{$IFDEF FPC}\n {$MODE DELPHI}\n{$ENDIF}\n\ntype\n TdynArray = array of integer;\n\nfunction factorize(number: integer): TdynArray;\nvar\n k: integer;\nbegin\n if number = 1 then\n begin\n setlength(Result, 1);\n Result[0] := 1\n end\n else\n begin\n k := 2;\n while number > 1 do\n begin\n while number mod k = 0 do\n begin\n setlength(Result, length(Result) + 1);\n Result[high(Result)] := k;\n number := number div k;\n end;\n inc(k);\n end;\n end\nend;\n\nvar\n i, j: integer;\n fac: TdynArray;\n\nbegin\n for i := 1 to 22 do\n begin\n write(i, ': ' );\n fac := factorize(i);\n write(fac[0]);\n for j := 1 to high(fac) do\n write(' * ', fac[j]);\n writeln;\n end;\nend.\n", "language": "Pascal" }, { "code": "use ntheory qw/factor/;\nprint \"$_ = \", join(\" x \", factor($_)), \"\\n\" for 1000000000000000000 .. 1000000000000000010;\n", "language": "Perl" }, { "code": "use Math::Pari qw/factorint/;\nsub factor {\n my ($pn,$pc) = @{Math::Pari::factorint(shift)};\n return map { ($pn->[$_]) x $pc->[$_] } 0 .. $#$pn;\n}\nprint \"$_ = \", join(\" x \", factor($_)), \"\\n\" for 1000000000000000000 .. 1000000000000000010;\n", "language": "Perl" }, { "code": "use Math::Factor::XS qw/prime_factors/;\nprint \"$_ = \", join(\" x \", prime_factors($_)), \"\\n\" for 1000000000000000000 .. 1000000000000000010;\n", "language": "Perl" }, { "code": "sub factors {\n my($n, $p, @out) = (shift, 3);\n return if $n < 1;\n while (!($n&1)) { $n >>= 1; push @out, 2; }\n while ($n > 1 && $p*$p <= $n) {\n while ( ($n % $p) == 0) {\n $n /= $p;\n push @out, $p;\n }\n $p += 2;\n }\n push @out, $n if $n > 1;\n @out;\n}\n\nprint \"$_ = \", join(\" x \", factors($_)), \"\\n\" for 100000000000 .. 100000000100;\n", "language": "Perl" }, { "code": "tie my @primes, 'Tie::SieveOfEratosthenes';\n\nsub factors {\n my($n, $i, $p, @out) = (shift, 0, 2);\n while ($n >= $p * $p) {\n while ($n % $p == 0) {\n push @out, $p;\n $n /= $p;\n }\n $p = $primes[++$i];\n }\n push @out, $n if $n > 1 || !@out;\n @out;\n}\n\nprint \"$_ = \", join(\" x \", factors($_)), \"\\n\" for 100000000000 .. 100000000010;\n", "language": "Perl" }, { "code": "#!perl -C\nuse utf8;\nuse strict;\nuse warnings;\n\nmy $limit = 1000;\n\nprint \"$_ = $_\\n\" for 1..3;\n\nmy @p_and_sq = ( [2, 4], [3, 9] );\n\nN: for my $n ( 4 .. 1000 ) {\n\tprint $n, \" = \";\n\tfor( my $i = 0; $i <= $#p_and_sq; ++$i ) {\n\t\tmy ($p, $sq) = @{ $p_and_sq[$i] };\n\t\tif( $sq > $n ) {\n\t\t\tprint $n, \"\\n\";\n\t\t\tpush @p_and_sq, [ $n, $n*$n ];\n\t\t\tnext N;\n\t\t}\n\t\twhile( 0 == ($n % $p) ) {\n\t\t\tprint $p;\n\t\t\t$n /= $p;\n\t\t\tif( $n == 1 ) {\n\t\t\t\tprint \"\\n\";\n\t\t\t\tnext N;\n\t\t\t}\n\t\t\tprint \" × \";\n\t\t}\n\t}\n\tdie \"Ran out of primes?!\";\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">factorise</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">prime_factors</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">apply</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">sprint</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\" x \"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%2d: %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #7060A8;\">papply</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)&{</span><span style=\"color: #000000;\">2144</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1000000000</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #000000;\">factorise</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "(de factor (N)\n (make\n (let (D 2 L (1 2 2 . (4 2 4 2 4 6 2 6 .)) M (sqrt N))\n (while (>= M D)\n (if (=0 (% N D))\n (setq M (sqrt (setq N (/ N (link D)))))\n (inc 'D (pop 'L)) ) )\n (link N) ) ) )\n\n(for N 20\n (prinl N \": \" (glue \" * \" (factor N))) )\n", "language": "PicoLisp" }, { "code": "cnt: procedure options (main);\n\tdeclare (i, k, n) fixed binary;\n\tdeclare first bit (1) aligned;\n\n do n = 1 to 40;\n put skip list (n || ' =');\n k = n; first = '1'b;\nrepeat:\n do i = 2 to k-1;\n\t\tif mod(k, i) = 0 then\n\t\t\tdo;\n\t\t\t\tk = k/i;\n if ^first then put edit (' x ')(A);\n first = '0'b;\n put edit (trim(i)) (A);\n\t\t\t\tgo to repeat;\n\t\t\tend;\n\n\tend;\n if ^first then put edit (' x ')(A);\n if n = 1 then i = 1;\n put edit (trim(i)) (A);\n end;\nend cnt;\n", "language": "PL-I" }, { "code": "function eratosthenes ($n) {\n if($n -ge 1){\n $prime = @(1..($n+1) | foreach{$true})\n $prime[1] = $false\n $m = [Math]::Floor([Math]::Sqrt($n))\n for($i = 2; $i -le $m; $i++) {\n if($prime[$i]) {\n for($j = $i*$i; $j -le $n; $j += $i) {\n $prime[$j] = $false\n }\n }\n }\n 1..$n | where{$prime[$_]}\n } else {\n \"$n must be equal or greater than 1\"\n }\n}\nfunction prime-decomposition ($n) {\n $array = eratosthenes $n\n $prime = @()\n foreach($p in $array) {\n while($n%$p -eq 0) {\n $n /= $p\n $prime += @($p)\n }\n }\n $prime\n}\n$OFS = \" x \"\n\"$(prime-decomposition 2144)\"\n\"$(prime-decomposition 100)\"\n\"$(prime-decomposition 12)\"\n", "language": "PowerShell" }, { "code": "Procedure Factorize(Number, List Factors())\n Protected I = 3, Max\n ClearList(Factors())\n While Number % 2 = 0\n AddElement(Factors())\n Factors() = 2\n Number / 2\n Wend\n Max = Number\n While I <= Max And Number > 1\n While Number % I = 0\n AddElement(Factors())\n Factors() = I\n Number / I\n Wend\n I + 2\n Wend\nEndProcedure\n\nIf OpenConsole()\n NewList n()\n For a=1 To 20\n text$=RSet(Str(a),2)+\"= \"\n Factorize(a,n())\n If ListSize(n())\n ResetList(n())\n While NextElement(n())\n text$ + Str(n())\n If ListSize(n())-ListIndex(n())>1\n text$ + \"*\"\n EndIf\n Wend\n Else\n text$+Str(a) ; To handle the '1', which is not really a prime...\n EndIf\n PrintN(text$)\n Next a\nEndIf\n", "language": "PureBasic" }, { "code": "from functools import lru_cache\n\nprimes = [2, 3, 5, 7, 11, 13, 17] # Will be extended\n\n@lru_cache(maxsize=2000)\ndef pfactor(n):\n if n == 1:\n return [1]\n n2 = n // 2 + 1\n for p in primes:\n if p <= n2:\n d, m = divmod(n, p)\n if m == 0:\n if d > 1:\n return [p] + pfactor(d)\n else:\n return [p]\n else:\n if n > primes[-1]:\n primes.append(n)\n return [n]\n\nif __name__ == '__main__':\n mx = 5000\n for n in range(1, mx + 1):\n factors = pfactor(n)\n if n <= 10 or n >= mx - 20:\n print( '%4i %5s %s' % (n,\n '' if factors != [n] or n == 1 else 'prime',\n 'x'.join(str(i) for i in factors)) )\n if n == 11:\n print('...')\n\n print('\\nNumber of primes gathered up to', n, 'is', len(primes))\n print(pfactor.cache_info())\n", "language": "Python" }, { "code": " [ [] swap\n dup times\n [ [ dup i^ 2 + /mod\n 0 = while\n nip dip\n [ i^ 2 + join ]\n again ]\n drop\n dup 1 = if conclude ]\n drop ] is primefactors ( n --> [ )\n\n [ 1 dup echo cr\n [ 1+ dup primefactors\n witheach\n [ echo\n i if [ say \" x \" ] ]\n cr again ] ] is countinfactors ( --> )\n\ncountinfactors\n", "language": "Quackery" }, { "code": "#initially I created a function which returns prime factors then I have created another function counts in the factors and #prints the values.\n\nfindfactors <- function(num) {\n x <- c()\n p1<- 2\n p2 <- 3\n everyprime <- num\n while( everyprime != 1 ) {\n while( everyprime%%p1 == 0 ) {\n x <- c(x, p1)\n everyprime <- floor(everyprime/ p1)\n }\n p1 <- p2\n p2 <- p2 + 2\n }\n x\n}\ncount_in_factors=function(x){\n primes=findfactors(x)\n x=c(1)\n for (i in 1:length(primes)) {\n x=paste(primes[i],\"x\",x)\n }\n return(x)\n}\ncount_in_factors(72)\n", "language": "R" }, { "code": "#lang typed/racket\n\n(require math/number-theory)\n\n(define (factorise-as-primes [n : Natural])\n (if\n (= n 1)\n '(1)\n (let ((F (factorize n)))\n (append*\n (for/list : (Listof (Listof Natural))\n ((f (in-list F)))\n (make-list (second f) (first f)))))))\n\n(define (factor-count [start-inc : Natural] [end-inc : Natural])\n (for ((i : Natural (in-range start-inc (add1 end-inc))))\n (define f (string-join (map number->string (factorise-as-primes i)) \" × \"))\n (printf \"~a:\\t~a~%\" i f)))\n\n(factor-count 1 22)\n(factor-count 2140 2150)\n; tb\n", "language": "Racket" }, { "code": "constant @primes = 2, |(3, 5, 7 ... *).grep: *.is-prime;\n\nmulti factors(1) { 1 }\nmulti factors(Int $remainder is copy) {\n gather for @primes -> $factor {\n\n # if remainder < factor², we're done\n if $factor * $factor > $remainder {\n take $remainder if $remainder > 1;\n last;\n }\n\n # How many times can we divide by this prime?\n while $remainder %% $factor {\n take $factor;\n last if ($remainder div= $factor) === 1;\n }\n }\n}\n\nsay \"$_: \", factors($_).join(\" × \") for 1..*;\n", "language": "Raku" }, { "code": "sub factor($n is copy) {\n $n == 1 ?? 1 !!\n gather {\n\t$n /= take 2 while $n %% 2;\n\t$n /= take 3 while $n %% 3;\n\tloop (my $p = 5; $p*$p <= $n; $p+=2) {\n\t $n /= take $p while $n %% $p;\n\t}\n\ttake $n unless $n == 1;\n }\n}\n\nsay \"$_ == \", join \" \\x00d7 \", factor $_ for 1 .. 20;\n", "language": "Raku" }, { "code": "use Prime::Factor;\n\nsay \"$_ = {(.&prime-factors || 1).join: ' x ' }\" for flat 1 .. 10, 10**20 .. 10**20 + 10;\n", "language": "Raku" }, { "code": "$ENTRY Go {\n = <Each Show <Iota 1 15> 2144>;\n};\n\nFactorize {\n 1 = 1;\n s.N = <Factorize 2 s.N>;\n s.D s.N, <Compare s.N s.D>: '-' = ;\n s.D s.N, <Divmod s.N s.D>: {\n (s.R) 0 = s.D <Factorize s.D s.R>;\n e.X = <Factorize <+ 1 s.D> s.N>;\n };\n};\n\nJoin {\n (e.J) = ;\n (e.J) s.N = <Symb s.N>;\n (e.J) s.N e.X = <Symb s.N> e.J <Join (e.J) e.X>;\n};\n\nIota {\n s.End s.End = s.End;\n s.Start s.End = s.Start <Iota <+ s.Start 1> s.End>;\n};\n\nEach {\n s.F = ;\n s.F t.I e.X = <Mu s.F t.I> <Each s.F e.X>;\n};\n\nShow {\n e.N = <Prout <Symb e.N> ' = ' <Join (' x ') <Factorize e.N>>>;\n};\n", "language": "Refal" }, { "code": "/*REXX program lists the prime factors of a specified integer (or a range of integers).*/\n@.=left('', 8); @.0=\"{unity} \"; @.1='[prime] ' /*some tags and handy-dandy literals.*/\nparse arg LO HI @ . /*get optional arguments from the C.L. */\nif LO=='' | LO==\",\" then do; LO=1; HI=40; end /*Not specified? Then use the default.*/\nif HI=='' | HI==\",\" then HI= LO /* \" \" \" \" \" \" */\nif @=='' then @= 'x' /* \" \" \" \" \" \" */\nif length(@)\\==1 then @= x2c(@) /*Not length 1? Then use hexadecimal. */\ntell= (HI>0) /*if HIGH is positive, then show #'s.*/\nHI= abs(HI) /*use the absolute value for HIGH. */\nw= length(HI) /*get maximum width for pretty output. */\nnumeric digits max(9, w + 1) /*maybe bump the precision of numbers. */\n#= 0 /*the number of primes found (so far). */\n do n=abs(LO) to HI; f= factr(n) /*process a single number or a range.*/\n p= words( translate(f, ,@) ) - (n==1) /*P: is the number of prime factors. */\n if p==1 then #= # + 1 /*bump the primes counter (exclude N=1)*/\n if tell then say right(n, w) '=' @.p f /*display if a prime, plus its factors.*/\n end /*n*/\nsay\nsay right(#, w) ' primes found.' /*display the number of primes found. */\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nfactr: procedure expose @; parse arg z 1 n,$; if z<2 then return z /*is Z too small?*/\n do while z//2==0; $= $||@||2; z= z%2; end /*maybe add factor of 2 */\n do while z//3==0; $= $||@||3; z= z%3; end /* \" \" \" \" 3 */\n do while z//5==0; $= $||@||5; z= z%5; end /* \" \" \" \" 5 */\n do while z//7==0; $= $||@||7; z= z%7; end /* \" \" \" \" 7 */\n\n do j=11 by 6 while j<=z /*insure that J isn't divisible by 3.*/\n parse var j '' -1 _ /*get the last decimal digit of J. */\n if _\\==5 then do while z//j==0; $=$||@||j; z= z%j; end /*maybe reduce Z.*/\n if _ ==3 then iterate /*Next # ÷ by 5? Skip. ___ */\n if j*j>n then leave /*are we higher than the √ N ? */\n y= j + 2 /*obtain the next odd divisor. */\n do while z//y==0; $=$||@||y; z= z%y; end /*maybe reduce Z.*/\n end /*j*/\n if z==1 then return substr($, 1+length(@) ) /*Is residual=1? Don't add 1*/\n return substr($||@||z, 1+length(@) ) /*elide superfluous header. */\n", "language": "REXX" }, { "code": "/*REXX program lists the prime factors of a specified integer (or a range of integers).*/\n@.=left('', 8); @.0=\"{unity} \"; @.1='[prime] ' /*some tags and handy-dandy literals.*/\nparse arg LO HI @ . /*get optional arguments from the C.L. */\nif LO=='' | LO==\",\" then do; LO=1; HI=40; end /*Not specified? Then use the default.*/\nif HI=='' | HI==\",\" then HI= LO /* \" \" \" \" \" \" */\nif @=='' then @= 'x' /* \" \" \" \" \" \" */\nif length(@)\\==1 then @= x2c(@) /*Not length 1? Then use hexadecimal. */\ntell= (HI>0) /*if HIGH is positive, then show #'s.*/\nHI= abs(HI) /*use the absolute value for HIGH. */\nw= length(HI) /*get maximum width for pretty output. */\nnumeric digits max(9, w + 1) /*maybe bump the precision of numbers. */\n#= 0 /*the number of primes found (so far). */\n do n=abs(LO) to HI; f= factr(n) /*process a single number or a range.*/\n p= words( translate(f, ,@) ) - (n==1) /*P: is the number of prime factors. */\n if p==1 then #= # + 1 /*bump the primes counter (exclude N=1)*/\n if tell then say right(n, w) '=' @.p f /*display if a prime, plus its factors.*/\n end /*n*/\nsay\nsay right(#, w) ' primes found.' /*display the number of primes found. */\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nfactr: procedure expose @; parse arg z 1 n,$; if z<2 then return z /*is Z too small?*/\n do while z// 2==0; $= $||@||2 ; z= z%2 ; end /*maybe add factor of 2 */\n do while z// 3==0; $= $||@||3 ; z= z%3 ; end /* \" \" \" \" 3 */\n do while z// 5==0; $= $||@||5 ; z= z%5 ; end /* \" \" \" \" 5 */\n do while z// 7==0; $= $||@||7 ; z= z%7 ; end /* \" \" \" \" 7 */\n do while z//11==0; $= $||@||11; z= z%11; end /* \" \" \" \" 11 */\n do while z//13==0; $= $||@||13; z= z%13; end /* \" \" \" \" 13 */\n do while z//17==0; $= $||@||17; z= z%17; end /* \" \" \" \" 17 */\n do while z//19==0; $= $||@||19; z= z%19; end /* \" \" \" \" 19 */\n do while z//23==0; $= $||@||23; z= z%23; end /* \" \" \" \" 23 */\n do while z//29==0; $= $||@||29; z= z%29; end /* \" \" \" \" 29 */\n do while z//31==0; $= $||@||31; z= z%31; end /* \" \" \" \" 31 */\n do while z//37==0; $= $||@||37; z= z%37; end /* \" \" \" \" 37 */\n if z>40 then do; t= z; q= 1; r= 0; do while q<=t; q= q * 4\n end /*while*/\n do while q>1; q=q%4; _=t-r-q; r=r%2; if _>=0 then do; t=_; r=r+q\n end\n end /*while*/ /* [↑] find integer SQRT(z). */\n /*R: is the integer SQRT of Z.*/\n do j=41 by 6 to r while j<=z /*insure J isn't divisible by 3*/\n parse var j '' -1 _ /*get last decimal digit of J.*/\n if _\\==5 then do while z//j==0; $=$||@||j; z= z%j; end\n if _ ==3 then iterate /*Next number ÷ by 5 ? Skip.*/\n y= j + 2 /*use the next (odd) divisor. */\n do while z//y==0; $=$||@||y; z= z%y; end\n end /*j*/ /* [↑] reduce Z by Y ? */\n end /*if z>40*/\n\n if z==1 then return substr($, 1+length(@) ) /*Is residual=1? Don't add 1*/\n return substr($||@||z, 1+length(@) ) /*elide superfluous header. */\n", "language": "REXX" }, { "code": "for i = 1 to 20\n see \"\" + i + \" = \" + factors(i) + nl\nnext\n\nfunc factors n\n f = \"\"\n if n = 1 return \"1\" ok\n p = 2\n while p <= n\n if (n % p) = 0\n f += string(p) + \" x \"\n n = n/p\n else p += 1 ok\n end\n return left(f, len(f) - 3)\n", "language": "Ring" }, { "code": "require 'optparse'\nrequire 'prime'\n\nmaximum = 10\nOptionParser.new do |o|\n o.banner = \"Usage: #{File.basename $0} [-m MAXIMUM]\"\n o.on(\"-m MAXIMUM\", Integer,\n \"Count up to MAXIMUM [#{maximum}]\") { |m| maximum = m }\n o.parse! rescue ($stderr.puts $!, o; exit 1)\n ($stderr.puts o; exit 1) unless ARGV.size == 0\nend\n\n# 1 has no prime factors\nputs \"1 is 1\" unless maximum < 1\n\n2.upto(maximum) do |i|\n # i is 504 => i.prime_division is [[2, 3], [3, 2], [7, 1]]\n f = i.prime_division.map! do |factor, exponent|\n # convert [2, 3] to \"2 x 2 x 2\"\n ([factor] * exponent).join \" x \"\n end.join \" x \"\n puts \"#{i} is #{f}\"\nend\n", "language": "Ruby" }, { "code": "for i = 1000 to 1016\n print i;\" = \"; factorial$(i)\nnext\nwait\nfunction factorial$(num)\n if num = 1 then factorial$ = \"1\"\n fct = 2\n while fct <= num\n if (num mod fct) = 0 then\n factorial$ = factorial$ ; x$ ; fct\n x$ = \" x \"\n num = num / fct\n else\n fct = fct + 1\n end if\n wend\nend function\n", "language": "Run-BASIC" }, { "code": "use std::env;\n\nfn main() {\n let args: Vec<_> = env::args().collect();\n let n = if args.len() > 1 {\n args[1].parse().expect(\"Not a valid number to count to\")\n }\n else {\n 20\n };\n count_in_factors_to(n);\n}\n\nfn count_in_factors_to(n: u64) {\n println!(\"1\");\n let mut primes = vec![];\n for i in 2..=n {\n let fs = factors(&primes, i);\n if fs.len() <= 1 {\n primes.push(i);\n println!(\"{}\", i);\n }\n else {\n println!(\"{} = {}\", i, fs.iter().map(|f| f.to_string()).collect::<Vec<String>>().join(\" x \"));\n }\n }\n}\n\nfn factors(primes: &[u64], mut n: u64) -> Vec<u64> {\n let mut result = Vec::new();\n for p in primes {\n while n % p == 0 {\n result.push(*p);\n n /= p;\n }\n if n == 1 {\n return result;\n }\n }\n vec![n]\n}\n", "language": "Rust" }, { "code": "def count_in_factors(n):\n if is_prime(n) or n == 1:\n print(n,end=\"\")\n return\n while n != 1:\n p = next_prime(1)\n while n % p != 0:\n p = next_prime(p)\n print(p,end=\"\")\n n = n / p\n if n != 1: print(\" x\",end=\" \")\n\nfor i in range(1, 101):\n print(i,\"=\",end=\" \")\n count_in_factors(i)\n print(\"\")\n", "language": "Sage" }, { "code": "object CountInFactors extends App {\n\n def primeFactors(n: Int): List[Int] = {\n\n def primeStream(s: LazyList[Int]): LazyList[Int] = {\n s.head #:: primeStream(s.tail filter {\n _ % s.head != 0\n })\n }\n\n val primes = primeStream(LazyList.from(2))\n\n def factors(n: Int): List[Int] = primes.takeWhile(_ <= n).find(n % _ == 0) match {\n case None => Nil\n case Some(p) => p :: factors(n / p)\n }\n\n if (n == 1) List(1) else factors(n)\n }\n\n // A little test...\n {\n val nums = (1 to 12).toList :+ 2144 :+ 6358\n nums.foreach(n => println(\"%6d : %s\".format(n, primeFactors(n).mkString(\" * \"))))\n }\n\n}\n", "language": "Scala" }, { "code": "(define (factors n)\n (let facs ((l '()) (d 2) (x n))\n (cond ((= x 1) (if (null? l) '(1) l))\n\t ((< x (* d d)) (cons x l))\n\t (else (if (= 0 (modulo x d))\n\t\t (facs (cons d l) d (/ x d))\n\t\t (facs l (+ 1 d) x))))))\n\n(define (show l)\n (display (car l))\n (if (not (null? (cdr l)))\n (begin\n (display \" × \")\n (show (cdr l)))\n (display \"\\n\")))\n\n(do ((i 1 (+ i 1))) (#f)\n (display i)\n (display \" = \")\n (show (reverse (factors i))))\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst proc: writePrimeFactors (in var integer: number) is func\n local\n var boolean: laterElement is FALSE;\n var integer: checker is 2;\n begin\n while checker * checker <= number do\n if number rem checker = 0 then\n if laterElement then\n write(\" * \");\n end if;\n laterElement := TRUE;\n write(checker);\n number := number div checker;\n else\n incr(checker);\n end if;\n end while;\n if number <> 1 then\n if laterElement then\n write(\" * \");\n end if;\n laterElement := TRUE;\n write(number);\n end if;\n end func;\n\nconst proc: main is func\n local\n var integer: number is 0;\n begin\n writeln(\"1: 1\");\n for number range 2 to 2147483647 do\n write(number <& \": \");\n writePrimeFactors(number);\n writeln;\n end for;\n end func;\n", "language": "Seed7" }, { "code": "class Counter {\n method factors(n, p=2) {\n var a = gather {\n while (n >= p*p) {\n while (p `divides` n) {\n take(p)\n n //= p\n }\n p = self.next_prime(p)\n }\n }\n (n > 1 || a.is_empty) ? (a << n) : a\n }\n \n method is_prime(n) {\n self.factors(n).len == 1\n }\n \n method next_prime(p) {\n do {\n p == 2 ? (p = 3) : (p+=2)\n } while (!self.is_prime(p))\n return p\n }\n}\n \nfor i in (1..100) {\n say \"#{i} = #{Counter().factors(i).join(' × ')}\"\n}\n", "language": "Sidef" }, { "code": "extension BinaryInteger {\n @inlinable\n public func primeDecomposition() -> [Self] {\n guard self > 1 else { return [] }\n\n func step(_ x: Self) -> Self {\n return 1 + (x << 2) - ((x >> 1) << 1)\n }\n\n let maxQ = Self(Double(self).squareRoot())\n var d: Self = 1\n var q: Self = self & 1 == 0 ? 2 : 3\n\n while q <= maxQ && self % q != 0 {\n q = step(d)\n d += 1\n }\n\n return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self]\n }\n}\n\nfor i in 1...20 {\n if i == 1 {\n print(\"1 = 1\")\n } else {\n print(\"\\(i) = \\(i.primeDecomposition().map(String.init).joined(separator: \" x \"))\")\n }\n}\n", "language": "Swift" }, { "code": "package require Tcl 8.5\n\nnamespace eval prime {\n variable primes [list 2 3 5 7 11]\n proc restart {} {\n\tvariable index -1\n\tvariable primes\n\tvariable current [lindex $primes end]\n }\n\n proc get_next_prime {} {\n\tvariable primes\n\tvariable index\n\tif {$index < [llength $primes]-1} {\n\t return [lindex $primes [incr index]]\n\t}\n\tvariable current\n\twhile 1 {\n\t incr current 2\n\t set p 1\n\t foreach prime $primes {\n\t\tif {$current % $prime} {} else {\n\t\t set p 0\n\t\t break\n\t\t}\n\t }\n\t if {$p} {\n\t\treturn [lindex [lappend primes $current] [incr index]]\n\t }\n\t}\n }\n\n proc factors {num} {\n\trestart\n\tset factors [dict create]\n\tfor {set i [get_next_prime]} {$i <= $num} {} {\n\t if {$num % $i == 0} {\n\t\tdict incr factors $i\n\t\tset num [expr {$num / $i}]\n\t\tcontinue\n\t } elseif {$i*$i > $num} {\n\t\tdict incr factors $num\n\t\tbreak\n\t } else {\n\t\tset i [get_next_prime]\n\t }\n\t}\n\treturn $factors\n }\n\n # Produce the factors in rendered form\n proc factors.rendered {num} {\n\tset factorDict [factors $num]\n\tif {[dict size $factorDict] == 0} {\n\t return 1\n\t}\n\tdict for {factor times} $factorDict {\n\t lappend v {*}[lrepeat $times $factor]\n\t}\n\treturn [join $v \"*\"]\n }\n}\n", "language": "Tcl" }, { "code": "set max 20\nfor {set i 1} {$i <= $max} {incr i} {\n puts [format \"%*d = %s\" [string length $max] $i [prime::factors.rendered $i]]\n}\n", "language": "Tcl" }, { "code": "FUNCTION factorial$ (num)\n LET f$ = \"\"\n LET x$ = \"\"\n IF num = 1 THEN LET f$ = \"1\"\n LET fct = 2\n DO WHILE fct <= num\n IF MOD(num, fct) = 0 THEN\n LET f$ = f$ & x$ & STR$(fct)\n LET x$ = \" x \"\n LET num = num / fct\n ELSE\n LET fct = fct + 1\n END IF\n LOOP\n LET factorial$ = f$\nEND FUNCTION\n\nFOR i = 1 TO 20\n PRINT i; \"= \"; factorial$(i)\nNEXT i\nEND\n", "language": "True-BASIC" }, { "code": "fn main() {\n println(\"1: 1\")\n for i := 2; ; i++ {\n print(\"$i: \")\n mut x := ''\n for n, f := i, 2; n != 1; f++ {\n for m := n % f; m == 0; m = n % f {\n print('$x$f')\n x = \"×\"\n n /= f\n }\n }\n println('')\n }\n}\n", "language": "V-(Vlang)" }, { "code": "Function CountFactors(n)\n\tIf n = 1 Then\n\t\tCountFactors = 1\n\tElse\n\t\tarrP = Split(ListPrimes(n),\" \")\n\t\tSet arrList = CreateObject(\"System.Collections.ArrayList\")\n\t\tdivnum = n\n\t\tDo Until divnum = 1\n\t\t\t'The -1 is to account for the null element of arrP\n\t\t\tFor i = 0 To UBound(arrP)-1\n\t\t\t\tIf divnum = 1 Then\n\t\t\t\t\tExit For\n\t\t\t\tElseIf divnum Mod arrP(i) = 0 Then\n\t\t\t\t\tdivnum = divnum/arrP(i)\n\t\t\t\t\tarrList.Add arrP(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\tLoop\n\t\tarrList.Sort\n\t\tFor i = 0 To arrList.Count - 1\n\t\t\tIf i = arrList.Count - 1 Then\n\t\t\t\tCountFactors = CountFactors & arrList(i)\n\t\t\tElse\n\t\t\t\tCountFactors = CountFactors & arrList(i) & \" * \"\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\nFunction IsPrime(n)\n\tIf n = 2 Then\n\t\tIsPrime = True\n\tElseIf n <= 1 Or n Mod 2 = 0 Then\n\t\tIsPrime = False\n\tElse\n\t\tIsPrime = True\n\t\tFor i = 3 To Int(Sqr(n)) Step 2\n\t\t\tIf n Mod i = 0 Then\n\t\t\t\tIsPrime = False\n\t\t\t\tExit For\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\nFunction ListPrimes(n)\n\tListPrimes = \"\"\n\tFor i = 1 To n\n\t\tIf IsPrime(i) Then\n\t\t\tListPrimes = ListPrimes & i & \" \"\n\t\tEnd If\n\tNext\nEnd Function\n\n'Testing the fucntions.\nWScript.StdOut.Write \"2 = \" & CountFactors(2)\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"2144 = \" & CountFactors(2144)\nWScript.StdOut.WriteLine\n", "language": "VBScript" }, { "code": "Module CountingInFactors\n\n Sub Main()\n For i As Integer = 1 To 10\n Console.WriteLine(\"{0} = {1}\", i, CountingInFactors(i))\n Next\n\n For i As Integer = 9991 To 10000\n Console.WriteLine(\"{0} = {1}\", i, CountingInFactors(i))\n Next\n End Sub\n\n Private Function CountingInFactors(ByVal n As Integer) As String\n If n = 1 Then Return \"1\"\n\n Dim sb As New Text.StringBuilder()\n\n CheckFactor(2, n, sb)\n If n = 1 Then Return sb.ToString()\n\n CheckFactor(3, n, sb)\n If n = 1 Then Return sb.ToString()\n\n For i As Integer = 5 To n Step 2\n If i Mod 3 = 0 Then Continue For\n\n CheckFactor(i, n, sb)\n If n = 1 Then Exit For\n Next\n\n Return sb.ToString()\n End Function\n\n Private Sub CheckFactor(ByVal mult As Integer, ByRef n As Integer, ByRef sb As Text.StringBuilder)\n Do While n Mod mult = 0\n If sb.Length > 0 Then sb.Append(\" x \")\n sb.Append(mult)\n n = n / mult\n Loop\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./math\" for Int\n\nfor (r in [1..9, 2144..2154, 9987..9999]) {\n for (i in r) {\n var factors = (i > 1) ? Int.primeFactors(i) : [1]\n System.print(\"%(i): %(factors.join(\" x \"))\")\n }\n System.print()\n}\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes;\nint N0, N, F;\n[N0:= 1;\nrepeat IntOut(0, N0); Text(0, \" = \");\n F:= 2; N:= N0;\n repeat if rem(N/F) = 0 then\n [if N # N0 then Text(0, \" * \");\n IntOut(0, F);\n N:= N/F;\n ]\n else F:= F+1;\n until F>N;\n if N0=1 then IntOut(0, 1); \\1 = 1\n CrLf(0);\n N0:= N0+1;\nuntil KeyHit;\n]\n", "language": "XPL0" }, { "code": "for i = 1 to 20\n print i, \" = \", factorial$(i)\nnext i\nend\n\nsub factorial$ (num)\n local f$, x$\n f$ = \"\" : x$ = \"\"\n if num = 1 return \"1\"\n fct = 2\n while fct <= num\n if mod(num, fct) = 0 then\n f$ = f$ + x$ + str$(fct)\n x$ = \" x \"\n num = num / fct\n else\n fct = fct + 1\n end if\n wend\n return f$\nend sub\n", "language": "Yabasic" }, { "code": "foreach n in ([1..*]){ println(n,\": \",primeFactors(n).concat(\"\\U2715;\")) }\n", "language": "Zkl" }, { "code": "fcn primeFactors(n){ // Return a list of factors of n\n acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum\n if(n==1 or k>maxD) acc.close();\n else{\n\t q,r:=n.divr(k); // divr-->(quotient,remainder)\n\t if(r==0) return(self.fcn(q,k,acc.write(k),q.toFloat().sqrt()));\n\t return(self.fcn(n,k+1+k.isOdd,acc,maxD))\n }\n }(n,2,Sink(List),n.toFloat().sqrt());\n m:=acc.reduce('*,1); // mulitply factors\n if(n!=m) acc.append(n/m); // opps, missed last factor\n else acc;\n}\n", "language": "Zkl" }, { "code": "10 FOR i=1 TO 20\n20 PRINT i;\" = \";\n30 IF i=1 THEN PRINT 1: GO TO 90\n40 LET p=2: LET n=i: LET f$=\"\"\n50 IF p>n THEN GO TO 80\n60 IF NOT FN m(n,p) THEN LET f$=f$+STR$ p+\" x \": LET n=INT (n/p): GO TO 50\n70 LET p=p+1: GO TO 50\n80 PRINT f$( TO LEN f$-3)\n90 NEXT i\n100 STOP\n110 DEF FN m(a,b)=a-INT (a/b)*b\n", "language": "ZX-Spectrum-Basic" } ]
Count-in-factors
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Count_occurrences_of_a_substring\nnote: String manipulation\n", "language": "00-META" }, { "code": ";Task:\nCreate a function, &nbsp; or show a built-in function, &nbsp; to count the number of non-overlapping occurrences of a substring inside a string.\n\nThe function should take two arguments: \n:::* &nbsp; the first argument being the string to search, &nbsp; and \n:::* &nbsp; the second a substring to be searched for. \n\n\nIt should return an integer count.\n<syntaxhighlight lang=\"pseudocode\">print countSubstring(\"the three truths\",\"th\")\n3\n\n// do not count substrings that overlap with previously-counted substrings:\nprint countSubstring(\"ababababab\",\"abab\")\n2</syntaxhighlight>\n\nThe matching should yield the highest number of non-overlapping matches. \n\nIn general, this essentially means matching from left-to-right or right-to-left &nbsp; (see proof on talk page).\n\n\n{{Template:Strings}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "print(‘the three truths’.count(‘th’))\nprint(‘ababababab’.count(‘abab’))\n", "language": "11l" }, { "code": "* Count occurrences of a substring 05/07/2016\nCOUNTSTR CSECT\n USING COUNTSTR,R13 base register\n B 72(R15) skip savearea\n DC 17F'0' savearea\n STM R14,R12,12(R13) prolog\n ST R13,4(R15) \"\n ST R15,8(R13) \"\n LR R13,R15 \"\n MVC HAYSTACK,=CL32'the three truths'\n MVC LENH,=F'17' lh=17\n MVC NEEDLE,=CL8'th' needle='th'\n MVC LENN,=F'2' ln=2\n BAL R14,SHOW call show\n MVC HAYSTACK,=CL32'ababababab'\n MVC LENH,=F'11' lh=11\n MVC NEEDLE,=CL8'abab' needle='abab'\n MVC LENN,=F'4' ln=4\n BAL R14,SHOW call show\n L R13,4(0,R13) epilog\n LM R14,R12,12(R13) \"\n XR R15,R15 \"\n BR R14 exit\nHAYSTACK DS CL32 haystack\nNEEDLE DS CL8 needle\nLENH DS F length(haystack)\nLENN DS F length(needle)\n*------- ---- show---------------------------------------------------\nSHOW ST R14,SAVESHOW save return address\n BAL R14,COUNT count(haystack,needle)\n LR R11,R0 ic=count(haystack,needle)\n MVC PG(20),HAYSTACK output haystack\n MVC PG+20(5),NEEDLE output needle\n XDECO R11,PG+25 output ic\n XPRNT PG,80 print buffer\n L R14,SAVESHOW restore return address\n BR R14 return to caller\nSAVESHOW DS A return address of caller\nPG DC CL80' ' buffer\n*------- ---- count--------------------------------------------------\nCOUNT ST R14,SAVECOUN save return address\n SR R7,R7 n=0\n LA R6,1 istart=1\n L R10,LENH lh\n S R10,LENN ln\n LA R10,1(R10) lh-ln+1\nLOOPI CR R6,R10 do istart=1 to lh-ln+1\n BH ELOOPI\n LA R8,NEEDLE @needle\n L R9,LENN ln\n LA R4,HAYSTACK-1 @haystack[0]\n AR R4,R6 +istart\n LR R5,R9 ln\n CLCL R4,R8 if substr(haystack,istart,ln)=needle\n BNE NOTEQ\n LA R7,1(R7) n=n+1\n A R6,LENN istart=istart+ln\nNOTEQ LA R6,1(R6) istart=istart+1\n B LOOPI\nELOOPI LR R0,R7 return(n)\n L R14,SAVECOUN restore return address\n BR R14 return to caller\nSAVECOUN DS A return address of caller\n* ---- -------------------------------------------------------\n YREGS\n END COUNTSTR\n", "language": "360-Assembly" }, { "code": "\torg\t100h\n\tjmp\tdemo\n\t;;;\tCount non-overlapping substrings (BC) in string (HL)\n\t;;;\tReturns amount of matches in DE\nsubcnt:\tlxi\td,0\t; Amount of matches\ns_scan:\tmov\ta,m\t; Get current character\n\tana\ta\t; End of string?\n\trz\t\t; Then stop\n\tpush\tb\t; Keep start of substring search\n\tpush\th \t; Keep current location in string\ns_cmp:\tldax\tb\t; Get character from substring\n\tcmp\tm\t; Compare to curent charracter of search string\n\tinx\tb\t; Advance pointers\n\tinx\th\n\tjz\ts_cmp\t; Keep going if they were equal\n\tana\ta\t; Did we reach the end of the substring?\n\tjz\ts_find\t; If so, we found a match\n\tpop\th\t; Otherwise, no match - restore search position\n\tpop\tb\t; Restore start of substring\n\tinx\th\t; Try next position\n\tjmp\ts_scan\ns_find:\tinx\td\t; We found a match\n\tpop\tb\t; Discard start of the search, keep going after match\n\tpop \tb\t; Restore start of substring\n\tdcx\th\t; The comparison routine overshoots by one\n\tjmp\ts_scan\n\t;;;\tTest on a few strings\ndemo:\tlxi\th,pairs\nloop:\tmov\te,m\t; Load string pointer\n\tinx\th\n\tmov\td,m\n\tinx\th\n\tmov\ta,d\t; If 0, stop\n\tora\te\n\trz\n\tmov\tc,m\t; Load substring pointer\n\tinx\th\n\tmov\tb,m\n\tinx\th\n\tpush\th\t; Save example pointer\n\txchg\t\t; Put string pointer in HL\n\tcall\tsubcnt\t; Count substrings\n\tmvi\ta,'0'\t; Assuming output is <10, print output\n\tadd\te\t; (This is true for all examples, and a proper numeric\n\tmov\te,a\t; output routine is big and not relevant.)\n\tmvi\tc,2\t; CP/M character output\n\tcall\t5\n\tpop\th\t; Restore example pointer\n\tjmp\tloop\npairs:\tdw\tstr1,sub1,str2,sub2,str3,sub3,0\nstr1:\tdb\t'the three truths',0\nsub1:\tdb\t'th',0\t\t; result should be 3\nstr2:\tdb\t'ababababab',0\nsub2:\tdb\t'abab',0\t; result should be 2\nstr3:\tdb\t'cat',0\nsub3:\tdb\t'dog',0\t\t; result should be 0\n", "language": "8080-Assembly" }, { "code": "\tcpu\t8086\n\torg\t100h\nsection\t.text\n\tjmp\tdemo\n\t;;;\tCount non-overlapping substrings [ES:DI] in [DS:SI]\n\t;;;\tReturn count in AX\nsubcnt:\txor\tax,ax\t\t; Set count to 0\n\txor\tdl,dl\t\t; Zero to compare to\n\tmov\tbp,di\t\t; Keep copy of substring pointer\n.scan:\tcmp\tdl,[si]\t\t; End of string?\n\tje\t.out\t\t; Then we're done\n\tmov\tbx,si\t\t; Keep copy of search position\n\tmov\tdi,bp\t\t; Start at beginning of substring\n.cmp:\txor\tcx,cx\t\n\tdec\tcx\n\trepe\tcmpsb\t\t; Scan until no match\n\tdec\tsi\t\t; Go to first non-match\n\tdec\tdi\n\tcmp\tdl,[es:di]\t; Reached end of substring?\n\tje\t.match\t\t; Then we found a match\n\tmov\tsi,bx \t\t; If not, continue searching one\n\tinc\tsi\t\t; position further\n\tjmp\t.scan\n.match:\tinc\tax\t\t; Found a match - increment count\n\tjmp\t.scan\n.out:\tret\n\t;;;\tTest the routine on a few examples\ndemo:\tmov\tsi,pairs\n.loop:\tlodsw\t\t\t; Load string pointer\n\ttest\tax,ax\t\t; If 0, stop\n\tjz\t.out\n\txchg\tdx,ax\n\tlodsw\t\t\t; Load substring pointer\n\txchg\tdi,ax\n\tpush\tsi\t\t; Keep example pointer\n\txchg\tsi,dx\n\tcall\tsubcnt\t\t; Count substrings\n\tcall\tprax\t\t; Print amount of substrings\n\tpop\tsi\t\t; Restore example pointer\n\tjmp\t.loop\n.out:\tret\n\t;;;\tPrint AX as number\nprax:\tmov\tbx,num\t\t; Pointer to end of number string\n\tmov\tcx,10 \t\t; Divisor\n.dgt:\txor\tdx,dx\t\t; Divide by 10\n\tdiv\tcx\n\tadd\tdl,'0'\t\t; Add ASCII 0 to remainder\n\tdec\tbx\t\t; Store digit\n\tmov\t[bx],dl\n\ttest\tax,ax\t\t; If number not zero yet\n\tjnz\t.dgt\t\t; Find rest of digits\n\tmov\tdx,bx\t\t; Print number string\n\tmov\tah,9\n\tint\t21h\n\tret\nsection\t.data\n\tdb\t'*****'\t\t; Output number placeholder\nnum:\tdb\t' $'\n\t;;;\tExamples\npairs:\tdw\t.str1,.sub1,.str2,.sub2,.str3,.sub3,0\n.str1:\tdb\t'the three truths',0\n.sub1:\tdb\t'th',0\t\t; result should be 3\n.str2:\tdb\t'ababababab',0\n.sub2:\tdb\t'abab',0\t; result should be 2\n.str3:\tdb\t'cat',0\n.sub3:\tdb\t'dog',0\t\t; result should be 0\n", "language": "8086-Assembly" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program strcptsub64.s */\n\n/************************************/\n/* Constantes */\n/************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n/************************************/\n/* Initialized data */\n/************************************/\n.data\nszMessResult: .asciz \"Result: \"\nszString: .asciz \"the three truths\"\nszSubString: .asciz \"th\"\nszString1: .asciz \"ababababab\"\nszSubString1: .asciz \"abab\"\nszCarriageReturn: .asciz \"\\n\"\nszMessStart: .asciz \"Program 64 bits start.\\n\"\n/************************************/\n/* UnInitialized data */\n/************************************/\n.bss\nsZoneConv: .skip 24\n/************************************/\n/* code section */\n/************************************/\n.text\n.global main\nmain: // entry of program\n ldr x0,qAdrszMessStart\n bl affichageMess\n ldr x0,qAdrszString\n ldr x1,qAdrszSubString\n bl countSubString\n ldr x0,qAdrszString1\n ldr x1,qAdrszSubString1\n bl countSubString\n\n100: // standard end of the program\n mov x0, #0 // return code\n mov x8, #EXIT // request to exit program\n svc 0 // perform the system call\nqAdrszString: .quad szString\nqAdrszSubString: .quad szSubString\nqAdrszString1: .quad szString1\nqAdrszSubString1: .quad szSubString1\nqAdrsZoneConv: .quad sZoneConv\nqAdrszMessResult: .quad szMessResult\nqAdrszCarriageReturn: .quad szCarriageReturn\nqAdrszMessStart: .quad szMessStart\n/***************************************************/\n/* count sub string of string */\n/***************************************************/\n/* r0 contains a string */\n/* r1 contains a substring */\n/* r0 return substring count */\ncountSubString:\n stp x1,lr,[sp,-16]!\n stp x2,x3,[sp,-16]!\n stp x4,x5,[sp,-16]!\n stp x6,x7,[sp,-16]!\n mov x4,#0 // counter\n mov x3,#0 // index string\n mov x5,#0 // index substring\n1:\n ldrb w6,[x0,x5] // load byte of string\n ldrb w7,[x1,x3] // load byte of substring\n cmp x6,x7 // compare byte\n bne 2f // not equal\n cmp x6,#0 // string end ?\n beq 3f // yes\n add x5,x5,#1 // else increment index\n add x3,x3,#1\n b 1b // and loop\n2: // characters not equal\n cmp x6,#0 // end string ?\n beq 4f\n cmp x7,#0 // end substring ?\n add x6,x4,1\n csel x4,x6,x4,eq // yes -> increment counter\n mov x3,#0 // raz index substring\n add x5,x5,#1 // increment string index\n b 1b // and loop\n3: // end string and end substring\n add x4,x4,#1 // increment counter\n4: // result display\n mov x0,x4\n ldr x1,qAdrsZoneConv\n bl conversion10\n ldr x0,qAdrszMessResult\n bl affichageMess\n ldr x0,qAdrsZoneConv\n bl affichageMess\n ldr x0,qAdrszCarriageReturn\n bl affichageMess\n\n mov x0,x4\n 100:\n ldp x6,x7,[sp],16\n ldp x4,x5,[sp],16\n ldp x2,x3,[sp],16\n ldp x1,lr,[sp],16\n ret\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "BYTE FUNC CountSubstring(CHAR ARRAY s,sub)\n BYTE i,j,res,found\n\n i=1 res=0\n WHILE i-1+sub(0)<=s(0)\n DO\n found=1\n FOR j=1 TO sub(0)\n DO\n IF s(j+i-1)#sub(j) THEN\n found=0\n EXIT\n FI\n OD\n\n IF found=1 THEN\n i==+sub(0)\n res==+1\n ELSE\n i==+1\n FI\n OD\nRETURN (res)\n\nPROC Test(CHAR ARRAY s,sub)\n BYTE c\n\n c=CountSubstring(s,sub)\n PrintF(\"%B \"\"%S\"\" in \"\"%S\"\"%E\",c,sub,s)\nRETURN\n\nPROC Main()\n Test(\"the three truths\",\"th\")\n Test(\"ababababab\",\"abab\")\n Test(\"11111111\",\"11\")\n Test(\"abcdefg\",\"123\")\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Strings.Fixed, Ada.Integer_Text_IO;\n\nprocedure Substrings is\nbegin\n Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source => \"the three truths\",\n Pattern => \"th\"));\n Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source => \"ababababab\",\n Pattern => \"abab\"));\nend Substrings;\n", "language": "Ada" }, { "code": "#!/usr/local/bin/a68g --script #\n\nPROC count string in string = (STRING needle, haystack)INT: (\n INT start:=LWB haystack, next, out:=0;\n FOR count WHILE string in string(needle, next, haystack[start:]) DO\n start+:=next+UPB needle-LWB needle;\n out:=count\n OD;\n out\n);\n\nprintf(($d\" \"$,\n count string in string(\"th\", \"the three truths\"), # expect 3 #\n count string in string(\"abab\", \"ababababab\"), # expect 2 #\n count string in string(\"a*b\", \"abaabba*bbaba*bbab\"), # expect 2 #\n $l$\n))\n", "language": "ALGOL-68" }, { "code": "String substr = 'ABC';\nString str = 'ABCZZZABCYABCABCXXABC';\nInteger substrLen = substr.length();\nInteger count = 0;\nInteger index = str.indexOf(substr);\nwhile (index >= 0) {\n count++;\n str = str.substring(index+substrLen);\n index = str.indexOf(substr);\n}\nSystem.debug('Count String : '+count);\n", "language": "Apex" }, { "code": "csubs←{0=x←⊃⍸⍺⍷⍵:0 ⋄ 1+⍺∇(¯1+x+⍴⍺)↓⍵}\n", "language": "APL" }, { "code": "use framework \"OSAKit\"\n\non run\n {countSubstring(\"the three truths\", \"th\"), ¬\n countSubstring(\"ababababab\", \"abab\")}\nend run\n\non countSubstring(str, subStr)\n return evalOSA(\"JavaScript\", \"var matches = '\" & str & \"'\" & ¬\n \".match(new RegExp('\" & subStr & \"', 'g'));\" & ¬\n \"matches ? matches.length : 0\") as integer\nend countSubstring\n\n-- evalOSA :: (\"JavaScript\" | \"AppleScript\") -> String -> String\non evalOSA(strLang, strCode)\n\n set ca to current application\n set oScript to ca's OSAScript's alloc's initWithSource:strCode ¬\n |language|:(ca's OSALanguage's languageForName:(strLang))\n\n set {blnCompiled, oError} to oScript's compileAndReturnError:(reference)\n\n if blnCompiled then\n set {oDesc, oError} to oScript's executeAndReturnError:(reference)\n if (oError is missing value) then return oDesc's stringValue as text\n end if\n\n return oError's NSLocalizedDescription as text\nend evalOSA\n", "language": "AppleScript" }, { "code": "on countSubstring(theString, theSubstring)\n set astid to AppleScript's text item delimiters\n set AppleScript's text item delimiters to theSubstring\n set substringCount to (count theString's text items) - 1\n set AppleScript's text item delimiters to astid\n\n return substringCount\nend countSubstring\n\n{countSubstring(\"the three truths\", \"th\"), countSubstring(\"ababababab\", \"abab\")}\n", "language": "AppleScript" }, { "code": "{3, 2}\n", "language": "AppleScript" }, { "code": "10 F$ = \"TH\"\n20 S$ = \"THE THREE TRUTHS\"\n30 GOSUB 100\"COUNT SUBSTRING\n40 PRINT R\n50 F$ = \"ABAB\"\n60 S$ = \"ABABABABAB\"\n70 GOSUB 100\"COUNT SUBSTRING\n80 PRINT R\n90 END\n\n100 R = 0\n110 F = LEN(F$)\n120 S = LEN(S$)\n130 IF F > S THEN RETURN\n140 IF F = 0 THEN RETURN\n150 IF F = S AND F$ = S$ THEN R = 1 : RETURN\n160 FOR I = 1 TO S - F\n170 IF F$ = MID$(S$, I, F) THEN R = R + 1 : I = I + F - 1\n180 NEXT I\n190 RETURN\n", "language": "Applesoft-BASIC" }, { "code": "/* ARM assembly Raspberry PI */\n/* program strcptsub.s */\n\n/************************************/\n/* Constantes */\n/************************************/\n/* for this file see task include a file in language ARM assembly*/\n.include \"../constantes.inc\"\n\n/************************************/\n/* Initialized data */\n/************************************/\n.data\nszMessResult: .asciz \"Result: \"\nszString: .asciz \"the three truths\"\nszSubString: .asciz \"th\"\nszString1: .asciz \"ababababab\"\nszSubString1: .asciz \"abab\"\nszCarriageReturn: .asciz \"\\n\"\nszMessStart: .asciz \"Program 32 bits start.\\n\"\n/************************************/\n/* UnInitialized data */\n/************************************/\n.bss\nsZoneConv: .skip 24\n/************************************/\n/* code section */\n/************************************/\n.text\n.global main\nmain: @ entry of program\n ldr r0,iAdrszMessStart\n bl affichageMess\n ldr r0,iAdrszString\n ldr r1,iAdrszSubString\n bl countSubString\n ldr r0,iAdrszString1\n ldr r1,iAdrszSubString1\n bl countSubString\n\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform the system call\niAdrszString: .int szString\niAdrszSubString: .int szSubString\niAdrszString1: .int szString1\niAdrszSubString1: .int szSubString1\niAdrsZoneConv: .int sZoneConv\niAdrszMessResult: .int szMessResult\niAdrszCarriageReturn: .int szCarriageReturn\niAdrszMessStart: .int szMessStart\n/***************************************************/\n/* count sub string of string */\n/***************************************************/\n/* r0 contains a string */\n/* r1 contains a substring */\n/* r0 return substring count */\ncountSubString:\n push {r1-r7,lr} @ save registers\n mov r4,#0 @ counter\n mov r3,#0 @ index string\n Mov r5,#0 @ index substring\n1:\n ldrb r6,[r0,r5] @ load byte of string\n ldrb r7,[r1,r3] @ load byte of substring\n cmp r6,r7 @ compare byte\n bne 2f @ not equal\n cmp r6,#0 @ string end ?\n beq 3f @ yes\n add r5,r5,#1 @ else increment index\n add r3,r3,#1\n b 1b @ and loop\n2: @ characters not equal\n cmp r6,#0 @ end string ?\n beq 4f\n cmp r7,#0 @ end substring ?\n addeq r4,r4,#1 @ yes -> increment counter\n mov r3,#0 @ raz index substring\n add r5,r5,#1 @ increment string index\n b 1b @ and loop\n3: @ end string and end substring\n add r4,r4,#1 @ increment counter\n4: @ result display\n mov r0,r4\n ldr r1,iAdrsZoneConv\n bl conversion10\n ldr r0,iAdrszMessResult\n bl affichageMess\n ldr r0,iAdrsZoneConv\n bl affichageMess\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n\n mov r0,r4\n 100:\n pop {r1-r7,pc}\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n/* for this file see task include a file in language ARM assembly*/\n.include \"../affichage.inc\"\n", "language": "ARM-Assembly" }, { "code": "countOccurrences: function [str, substr]-> size match str substr\n\nloop [[\"the three truths\" \"th\"] [\"ababababab\" \"abab\"]] 'pair ->\n print [\n ~\"occurrences of '|last pair|' in '|first pair|':\"\n countOccurrences first pair last pair\n ]\n", "language": "Arturo" }, { "code": "MsgBox % countSubstring(\"the three truths\",\"th\") ; 3\nMsgBox % countSubstring(\"ababababab\",\"abab\") ; 2\n\nCountSubstring(fullstring, substring){\n StringReplace, junk, fullstring, %substring%, , UseErrorLevel\n return errorlevel\n}\n", "language": "AutoHotkey" }, { "code": "#\n# countsubstring(string, pattern)\n# Returns number of occurrences of pattern in string\n# Pattern treated as a literal string (regex characters not expanded)\n#\nfunction countsubstring(str, pat, len, i, c) {\n c = 0\n if( ! (len = length(pat) ) )\n return 0\n while(i = index(str, pat)) {\n str = substr(str, i + len)\n c++\n }\n return c\n}\n#\n# countsubstring_regex(string, regex_pattern)\n# Returns number of occurrences of pattern in string\n# Pattern treated as regex\n#\nfunction countsubstring_regex(str, pat, c) {\n c = 0\n c += gsub(pat, \"\", str)\n return c\n}\nBEGIN {\n print countsubstring(\"[do&d~run?d!run&>run&]\", \"run&\")\n print countsubstring_regex(\"[do&d~run?d!run&>run&]\", \"run[&]\")\n print countsubstring(\"the three truths\",\"th\")\n}\n", "language": "AWK" }, { "code": "FUNCTION Uniq_Tally(text$, part$)\n LOCAL x\n WHILE TALLY(text$, part$)\n INCR x\n text$ = MID$(text$, INSTR(text$, part$)+LEN(part$))\n WEND\n RETURN x\nEND FUNCTION\n\nPRINT \"the three truths - th: \", Uniq_Tally(\"the three truths\", \"th\")\nPRINT \"ababababab - abab: \", Uniq_Tally(\"ababababab\", \"abab\")\n", "language": "BaCon" }, { "code": "DECLARE FUNCTION countSubstring& (where AS STRING, what AS STRING)\n\nPRINT \"the three truths, th:\", countSubstring&(\"the three truths\", \"th\")\nPRINT \"ababababab, abab:\", countSubstring&(\"ababababab\", \"abab\")\n\nFUNCTION countSubstring& (where AS STRING, what AS STRING)\n DIM c AS LONG, s AS LONG\n s = 1 - LEN(what)\n DO\n s = INSTR(s + LEN(what), where, what)\n IF 0 = s THEN EXIT DO\n c = c + 1\n LOOP\n countSubstring = c\nEND FUNCTION\n", "language": "BASIC" }, { "code": "print countSubstring(\"the three truths\",\"th\")\nprint countSubstring(\"ababababab\",\"abab\")\nend\n\nfunction countSubstring(s$,find$)\n\ti = 1\n\twhile instr(s$,find$,i) <> 0\n\t\tcountSubstring += 1\n\t\ti = instr(s$,find$,i) + length(find$)\n\tend while\nend function\n", "language": "BASIC256" }, { "code": "@echo off\nsetlocal enabledelayedexpansion\n\n\t::Main\ncall :countString \"the three truths\",\"th\"\ncall :countString \"ababababab\",\"abab\"\npause>nul\nexit /b\n\t::/Main\n\n\t::Procedure\n:countString\n\tset input=%~1\n\tset cnt=0\n\n\t:count_loop\n\tset trimmed=!input:*%~2=!\n\tif \"!trimmed!\"==\"!input!\" (echo.!cnt!&goto :EOF)\n\tset input=!trimmed!\n\tset /a cnt+=1\n\tgoto count_loop\n", "language": "Batch-File" }, { "code": " tst$ = \"the three truths\"\n sub$ = \"th\"\n PRINT ; FNcountSubstring(tst$, sub$) \" \"\"\" sub$ \"\"\" in \"\"\" tst$ \"\"\"\"\n tst$ = \"ababababab\"\n sub$ = \"abab\"\n PRINT ; FNcountSubstring(tst$, sub$) \" \"\"\" sub$ \"\"\" in \"\"\" tst$ \"\"\"\"\n END\n\n DEF FNcountSubstring(A$, B$)\n LOCAL I%, N%\n I% = 1 : N% = 0\n REPEAT\n I% = INSTR(A$, B$, I%)\n IF I% THEN N% += 1 : I% += LEN(B$)\n UNTIL I% = 0\n = N%\n", "language": "BBC-BASIC" }, { "code": "get \"libhdr\"\n\nlet countsubstr(str, match) = valof\n$( let i, count = 1, 0\n while i <= str%0 do\n test valof\n $( for j = 1 to match%0\n unless match%j = str%(i+j-1)\n resultis false\n resultis true\n $)\n then\n $( count := count + 1\n i := i + match%0\n $)\n else\n i := i + 1\n resultis count\n$)\n\nlet show(str, match) be\n writef(\"*\"%S*\" in *\"%S*\": %N*N\",\n match, str, countsubstr(str, match))\n\nlet start() be\n$( show(\"the three truths\", \"th\")\n show(\"ababababab\", \"abab\")\n show(\"cat\", \"dog\")\n$)\n", "language": "BCPL" }, { "code": "Find←{i←/𝕨⍷𝕩, i/˜i≥»0≤◶⟨⊣,(≠𝕨)+⊢⟩`i}\n\n•Show \"abab\" Find \"ababababab\"\n•Show \"th\" Find \"the three truths\"\n", "language": "BQN" }, { "code": "2\n3\n", "language": "BQN" }, { "code": " ( count-substring\n = n S s p\n . 0:?n:?p\n & !arg:(?S.?s)\n & @( !S\n : ?\n ( [!p ? !s [?p ?\n & !n+1:?n\n & ~\n )\n )\n | !n\n )\n& out$(count-substring$(\"the three truths\".th))\n& out$(count-substring$(ababababab.abab))\n& ;\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n#include <string.h>\n\nint match(const char *s, const char *p, int overlap)\n{\n int c = 0, l = strlen(p);\n\n while (*s != '\\0') {\n if (strncmp(s++, p, l)) continue;\n if (!overlap) s += l - 1;\n c++;\n }\n return c;\n}\n\nint main()\n{\n printf(\"%d\\n\", match(\"the three truths\", \"th\", 0));\n printf(\"overlap:%d\\n\", match(\"abababababa\", \"aba\", 1));\n printf(\"not: %d\\n\", match(\"abababababa\", \"aba\", 0));\n return 0;\n}\n", "language": "C" }, { "code": "#include <stdio.h>\n#include <string.h>\n\n// returns count of non-overlapping occurrences of 'sub' in 'str'\nint countSubstring(const char *str, const char *sub)\n{\n int length = strlen(sub);\n if (length == 0) return 0;\n int count = 0;\n for (str = strstr(str, sub); str; str = strstr(str + length, sub))\n ++count;\n return count;\n}\n\nint main()\n{\n printf(\"%d\\n\", countSubstring(\"the three truths\", \"th\"));\n printf(\"%d\\n\", countSubstring(\"ababababab\", \"abab\"));\n printf(\"%d\\n\", countSubstring(\"abaabba*bbaba*bbab\", \"a*b\"));\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <string>\n\n// returns count of non-overlapping occurrences of 'sub' in 'str'\nint countSubstring(const std::string& str, const std::string& sub)\n{\n if (sub.length() == 0) return 0;\n int count = 0;\n for (size_t offset = str.find(sub); offset != std::string::npos;\n\t offset = str.find(sub, offset + sub.length()))\n {\n ++count;\n }\n return count;\n}\n\nint main()\n{\n std::cout << countSubstring(\"the three truths\", \"th\") << '\\n';\n std::cout << countSubstring(\"ababababab\", \"abab\") << '\\n';\n std::cout << countSubstring(\"abaabba*bbaba*bbab\", \"a*b\") << '\\n';\n\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\n\nclass SubStringTestClass\n{\n public static int CountSubStrings(this string testString, string testSubstring)\n {\n int count = 0;\n\n if (testString.Contains(testSubstring))\n {\n for (int i = 0; i < testString.Length; i++)\n {\n if (testString.Substring(i).Length >= testSubstring.Length)\n {\n bool equals = testString.Substring(i, testSubstring.Length).Equals(testSubstring);\n if (equals)\n {\n count++;\n i += testSubstring.Length - 1; // Fix: Don't count overlapping matches\n }\n }\n }\n }\n return count;\n }\n}\n", "language": "C-sharp" }, { "code": "using System;\nclass SubStringTestClass\n{\n public static int CountSubStrings(this string testString, string testSubstring) =>\n testString?.Split(new [] { testSubstring }, StringSplitOptions.None)?.Length - 1 ?? 0;\n}\n", "language": "C-sharp" }, { "code": "10 CLS : REM 10 HOME for Applesoft BASIC\n20 F$ = \"TH\"\n30 S$ = \"THE THREE TRUTHS\"\n40 GOSUB 110: REM COUNT SUBSTRING\n50 PRINT R\n60 F$ = \"ABAB\"\n70 S$ = \"ABABABABAB\"\n80 GOSUB 110: REM COUNT SUBSTRING\n90 PRINT R\n100 END\n110 R = 0\n120 F = LEN(F$)\n130 S = LEN(S$)\n140 IF F > S THEN RETURN\n150 IF F = 0 THEN RETURN\n160 IF F = S AND F$ = S$ THEN R = 1: RETURN\n170 FOR I = 1 TO S - F\n180 IF F$ = MID$(S$, I, F) THEN R = R + 1: I = I + F - 1\n190 NEXT I\n200 RETURN\n", "language": "Chipmunk-Basic" }, { "code": "(defn re-quote\n \"Produces a string that can be used to create a Pattern\n that would match the string text as if it were a literal pattern.\n Metacharacters or escape sequences in text will be given no special\n meaning\"\n [text]\n (java.util.regex.Pattern/quote text))\n\n(defn count-substring [txt sub]\n (count (re-seq (re-pattern (re-quote sub)) txt)))\n", "language": "Clojure" }, { "code": "(defn count-substring1 [txt sub]\n (/ (- (count txt) (count (.replaceAll txt sub \"\")))\n (count sub)))\n", "language": "Clojure" }, { "code": "(defn count-substring2 [txt sub]\n (-> sub\n (re-quote)\n (re-pattern)\n (re-matcher txt)\n (.results)\n (.count)))\n", "language": "Clojure" }, { "code": " IDENTIFICATION DIVISION.\n PROGRAM-ID. testing.\n\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 occurrences PIC 99.\n\n PROCEDURE DIVISION.\n INSPECT \"the three truths\" TALLYING occurrences FOR ALL \"th\"\n DISPLAY occurrences\n\n MOVE 0 TO occurrences\n INSPECT \"ababababab\" TALLYING occurrences FOR ALL \"abab\"\n DISPLAY occurrences\n\n MOVE 0 TO occurrences\n INSPECT \"abaabba*bbaba*bbab\" TALLYING occurrences\n FOR ALL \"a*b\"\n DISPLAY occurrences\n\n GOBACK\n .\n", "language": "COBOL" }, { "code": "countSubstring = (str, substr) ->\n n = 0\n i = 0\n while (pos = str.indexOf(substr, i)) != -1\n n += 1\n i = pos + substr.length\n n\n\nconsole.log countSubstring \"the three truths\", \"th\"\nconsole.log countSubstring \"ababababab\", \"abab\"\n", "language": "CoffeeScript" }, { "code": "(defun count-sub (str pat)\n (loop with z = 0 with s = 0 while s do\n\t(when (setf s (search pat str :start2 s))\n\t (incf z) (incf s (length pat)))\n\tfinally (return z)))\n\n(count-sub \"ababa\" \"ab\") ; 2\n(count-sub \"ababa\" \"aba\") ; 1\n", "language": "Common-Lisp" }, { "code": "include \"cowgol.coh\";\n\nsub countSubstring(str: [uint8], match: [uint8]): (count: uint8) is\n count := 0;\n\n while [str] != 0 loop\n var find := match;\n var loc := str;\n while [loc] == [find] loop\n find := @next find;\n loc := @next loc;\n end loop;\n if [find] == 0 then\n str := loc;\n count := count + 1;\n else\n str := @next str;\n end if;\n end loop;\nend sub;\n\nprint_i8(countSubstring(\"the three truths\",\"th\")); # should print 3\nprint_nl();\nprint_i8(countSubstring(\"ababababab\",\"abab\")); # should print 2\nprint_nl();\nprint_i8(countSubstring(\"cat\",\"dog\")); # should print 0\nprint_nl();\n", "language": "Cowgol" }, { "code": "void main() {\n import std.stdio, std.algorithm;\n\n \"the three truths\".count(\"th\").writeln;\n \"ababababab\".count(\"abab\").writeln;\n}\n", "language": "D" }, { "code": "program OccurrencesOfASubstring;\n\n{$APPTYPE CONSOLE}\n\nuses StrUtils;\n\nfunction CountSubstring(const aString, aSubstring: string): Integer;\nvar\n lPosition: Integer;\nbegin\n Result := 0;\n lPosition := PosEx(aSubstring, aString);\n while lPosition <> 0 do\n begin\n Inc(Result);\n lPosition := PosEx(aSubstring, aString, lPosition + Length(aSubstring));\n end;\nend;\n\nbegin\n Writeln(CountSubstring('the three truths', 'th'));\n Writeln(CountSubstring('ababababab', 'abab'));\nend.\n", "language": "Delphi" }, { "code": "proc countSubstring(*char string, substring) word:\n word count;\n *char pos, loc;\n\n count := 0;\n while string* /= '\\e' do\n pos := substring;\n loc := string;\n while loc* = pos* do\n loc := loc + 1;\n pos := pos + 1\n od;\n if pos* = '\\e' then\n string := loc;\n count := count + 1\n else\n string := string + 1\n fi\n od;\n count\ncorp\n\nproc main() void:\n writeln(countSubstring(\"the three truths\", \"th\"));\n writeln(countSubstring(\"ababababab\", \"abab\"))\ncorp\n", "language": "Draco" }, { "code": "func countSubstring(str, val) {\n var idx = 0\n var count = 0\n while true {\n idx = str.IndexOf(val, idx)\n if idx == -1 {\n break\n }\n idx += val.Length()\n count += 1\n }\n return count\n}\n\nprint(countSubstring(\"the three truths\", \"th\"))\nprint(countSubstring(\"ababababab\", \"abab\"))\n", "language": "Dyalect" }, { "code": "func count str$ pat$ .\n ind = 1\n while ind + len pat$ - 1 <= len str$\n if substr str$ ind len pat$ = pat$\n cnt += 1\n ind += len pat$\n else\n ind += 1\n .\n .\n return cnt\n.\nprint count \"the three truths\" \"th\"\nprint count \"ababababab\" \"abab\"\nprint count \"11111111\" \"11\"\nprint count \"11111111\" \"12\"\nprint count \"12\" \"12\"\n", "language": "EasyLang" }, { "code": ";; from Racket\n(define count-substring\n (compose length regexp-match*))\n\n(count-substring \"aab\" \"graabaabdfaabgh\") ;; substring\n → 3\n(count-substring \"/ .e/\" \"Longtemps je me suis couché de bonne heure\") ;; regexp\n → 4\n", "language": "EchoLisp" }, { "code": "program CountStrings\n\t\n function main()\n SysLib.writeStdout(\"Remove and Count:\");\n SysLib.writeStdout(countSubstring(\"th\", \"the three truths\"));\n SysLib.writeStdout(countSubstring(\"abab\", \"ababababab\"));\n SysLib.writeStdout(countSubstring(\"a*b\", \"abaabba*bbaba*bbab\"));\n SysLib.writeStdout(countSubstring(\"a\", \"abaabba*bbaba*bbab\"));\n SysLib.writeStdout(countSubstring(\" \", \"abaabba*bbaba*bbab\"));\n SysLib.writeStdout(countSubstring(\"\", \"abaabba*bbaba*bbab\"));\n SysLib.writeStdout(countSubstring(\"a\", \"\"));\n SysLib.writeStdout(countSubstring(\"\", \"\"));\n\n SysLib.writeStdout(\"Manual Loop:\");\n SysLib.writeStdout(countSubstringWithLoop(\"th\", \"the three truths\"));\n SysLib.writeStdout(countSubstringWithLoop(\"abab\", \"ababababab\"));\n SysLib.writeStdout(countSubstringWithLoop(\"a*b\", \"abaabba*bbaba*bbab\"));\n SysLib.writeStdout(countSubstringWithLoop(\"a\", \"abaabba*bbaba*bbab\"));\n SysLib.writeStdout(countSubstringWithLoop(\" \", \"abaabba*bbaba*bbab\"));\n SysLib.writeStdout(countSubstringWithLoop(\"\", \"abaabba*bbaba*bbab\"));\n SysLib.writeStdout(countSubstringWithLoop(\"a\", \"\"));\n SysLib.writeStdout(countSubstringWithLoop(\"\", \"\"));\n end\n\n function countSubstring(substr string in, str string in) returns(int)\n if(str.length() > 0 and substr.length() > 0)\n\t return (str.length() - str.replaceStr(subStr, \"\").length()) / subStr.length();\n\telse\n\t return 0;\n\tend\n end\n\t\n function countSubstringWithLoop(substr string in, str string in) returns(int)\n count int = 0;\n loc, index int = 1;\n strlen int = str.length();\n substrlen int = substr.length();\n\t\t\n if(strlen > 0 and substrlen > 0)\n while(loc != 0 and index <= strlen)\n loc = str.indexOf(substr, index);\n if(loc > 0)\n count += 1;\n index = loc + substrlen;\n end\n end\n end\n return count;\n end\n\nend\n", "language": "EGL" }, { "code": "class\n\tAPPLICATION\ninherit\n\tARGUMENTS\ncreate\n\tmake\nfeature {NONE} -- Initialization\n\tmake\n\t\t\t-- Run application.\n\t\tdo\n\t\t\toccurance := 0\n\t\t\tfrom\n\t\t\t\tindex := 1\n\t\t\tuntil\n\t\t\t\tindex > text.count\n\t\t\tloop\n\t\t\t\ttemp := text.fuzzy_index(search_for, index, 0)\n\t\t\t\tif\n\t\t\t\t\ttemp /= 0\n\t\t\t\tthen\n\t\t\t\t\tindex := temp + search_for.count\n\t\t\t\t\toccurance := occurance + 1\n\t\t\t\telse\n\t\t\t\t\tindex := text.count + 1\n\t\t\t\tend\n\t\t\tend\n\t\t\tprint(occurance)\n\t\tend\n\n\tindex:INTEGER\n\ttemp:INTEGER\n\toccurance:INTEGER\n\ttext:STRING = \"ababababab\"\n\tsearch_for:STRING = \"abab\"\nend\n", "language": "Eiffel" }, { "code": "countSubstring = fn(_, \"\") -> 0\n (str, sub) -> length(String.split(str, sub)) - 1 end\n\ndata = [ {\"the three truths\", \"th\"},\n {\"ababababab\", \"abab\"},\n {\"abaabba*bbaba*bbab\", \"a*b\"},\n {\"abaabba*bbaba*bbab\", \"a\"},\n {\"abaabba*bbaba*bbab\", \" \"},\n {\"abaabba*bbaba*bbab\", \"\"},\n {\"\", \"a\"},\n {\"\", \"\"} ]\n\nEnum.each(data, fn{str, sub} ->\n IO.puts countSubstring.(str, sub)\nend)\n", "language": "Elixir" }, { "code": "(defun count-substrings (text substring)\n (with-temp-buffer\n (insert text)\n (goto-char (point-min))\n (how-many substring)))\n", "language": "Emacs-Lisp" }, { "code": "%% Count non-overlapping substrings in Erlang for the rosetta code wiki.\n%% Implemented by J.W. Luiten\n\n-module(substrings).\n-export([main/2]).\n\n%% String and Sub exhausted, count a match and present result\nmatch([], [], _OrigSub, Acc) ->\n Acc+1;\n\n%% String exhausted, present result\nmatch([], _Sub, _OrigSub, Acc) ->\n Acc;\n\t\n%% Sub exhausted, count a match\nmatch(String, [], Sub, Acc) ->\n match(String, Sub, Sub, Acc+1);\n\n%% First character matches, advance\nmatch([X|MainTail], [X|SubTail], Sub, Acc) ->\n match(MainTail, SubTail, Sub, Acc);\n\n%% First characters do not match. Keep scanning for sub in remainder of string\nmatch([_X|MainTail], [_Y|_SubTail], Sub, Acc)->\n match(MainTail, Sub, Sub, Acc).\n\t\nmain(String, Sub) ->\n match(String, Sub, Sub, 0).\n", "language": "Erlang" }, { "code": "substrings:main(\"ababababab\",\"abab\").\n", "language": "Erlang" }, { "code": "main( String, Sub ) -> erlang:length( binary:split(binary:list_to_bin(String), binary:list_to_bin(Sub), [global]) ) - 1.\n", "language": "Erlang" }, { "code": "function countSubstring(sequence s, sequence sub)\n integer from,count\n count = 0\n from = 1\n while 1 do\n from = match_from(sub,s,from)\n if not from then\n exit\n end if\n from += length(sub)\n count += 1\n end while\n return count\nend function\n\n? countSubstring(\"the three truths\",\"th\")\n? countSubstring(\"ababababab\",\"abab\")\n", "language": "Euphoria" }, { "code": "open System\n\nlet countSubstring (where :string) (what : string) =\n match what with\n | \"\" -> 0 // just a definition; infinity is not an int\n | _ -> (where.Length - where.Replace(what, @\"\").Length) / what.Length\n\n\n[<EntryPoint>]\nlet main argv =\n let show where what =\n printfn @\"countSubstring(\"\"%s\"\", \"\"%s\"\") = %d\" where what (countSubstring where what)\n show \"the three truths\" \"th\"\n show \"ababababab\" \"abab\"\n show \"abc\" \"\"\n 0\n", "language": "F-Sharp" }, { "code": "USING: math sequences splitting ;\n: occurences ( seq subseq -- n ) split-subseq length 1 - ;\n", "language": "Factor" }, { "code": ": str-count ( s1 len s2 len -- n )\n 2swap 0 >r\n begin 2over search\n while 2over nip /string\n r> 1+ >r\n repeat 2drop 2drop r> ;\n\ns\" the three truths\" s\" th\" str-count . \\ 3\ns\" ababababab\" s\" abab\" str-count . \\ 2\n", "language": "Forth" }, { "code": "program Example\n implicit none\n integer :: n\n\n n = countsubstring(\"the three truths\", \"th\")\n write(*,*) n\n n = countsubstring(\"ababababab\", \"abab\")\n write(*,*) n\n n = countsubstring(\"abaabba*bbaba*bbab\", \"a*b\")\n write(*,*) n\n\ncontains\n\nfunction countsubstring(s1, s2) result(c)\n character(*), intent(in) :: s1, s2\n integer :: c, p, posn\n\n c = 0\n if(len(s2) == 0) return\n p = 1\n do\n posn = index(s1(p:), s2)\n if(posn == 0) return\n c = c + 1\n p = p + posn + len(s2) - 1\n end do\nend function\nend program\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nFunction countSubstring(s As String, search As String) As Integer\n If s = \"\" OrElse search = \"\" Then Return 0\n Dim As Integer count = 0, length = Len(search)\n For i As Integer = 1 To Len(s)\n If Mid(s, i, length) = Search Then\n count += 1\n i += length - 1\n End If\n Next\n Return count\nEnd Function\n\nPrint countSubstring(\"the three truths\",\"th\")\nPrint countSubstring(\"ababababab\",\"abab\")\nPrint countSubString(\"zzzzzzzzzzzzzzz\", \"z\")\nPrint\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "import util.Regex\n\ndef countSubstring( str, substr ) = Regex( substr ).findAllMatchIn( str ).length()\n\nprintln( countSubstring(\"the three truths\", \"th\") )\nprintln( countSubstring(\"ababababab\", \"abab\") )\n", "language": "FunL" }, { "code": "window 1\n\nlocal fn CountSubstring( string as CFStringRef, substring as CFStringRef ) as long\nend fn = fn ArrayCount( fn StringComponentsSeparatedByString( string, substring ) ) - 1\n\nprint fn CountSubstring( @\"the three truths\", @\"th\" )\nprint fn CountSubstring( @\"ababababab\", @\"abab\" )\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\n\n Print countSubstring(\"the three truths\", \"th\")\n Print countSubstring(\"ababababab\", \"abab\")\n Print countSubString(\"zzzzzzzzzzzzzzz\", \"z\")\n\nEnd\n\nFunction countSubstring(s As String, search As String) As Integer\n\n If s = \"\" Or search = \"\" Then Return 0\n Dim count As Integer = 0, length As Integer = Len(search)\n For i As Integer = 1 To Len(s)\n If Mid(s, i, length) = Search Then\n count += 1\n i += length - 1\n End If\n Next\n Return count\n\nEnd Function\n", "language": "Gambas" }, { "code": "package main\nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc main() {\n fmt.Println(strings.Count(\"the three truths\", \"th\")) // says: 3\n fmt.Println(strings.Count(\"ababababab\", \"abab\")) // says: 2\n}\n", "language": "Go" }, { "code": "println (('the three truths' =~ /th/).count)\nprintln (('ababababab' =~ /abab/).count)\nprintln (('abaabba*bbaba*bbab' =~ /a*b/).count)\nprintln (('abaabba*bbaba*bbab' =~ /a\\*b/).count)\n", "language": "Groovy" }, { "code": "import Data.Text hiding (length)\n\n-- Return the number of non-overlapping occurrences of sub in str.\ncountSubStrs str sub = length $ breakOnAll (pack sub) (pack str)\n\nmain = do\n print $ countSubStrs \"the three truths\" \"th\"\n print $ countSubStrs \"ababababab\" \"abab\"\n", "language": "Haskell" }, { "code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.Text hiding (length)\n\n--------- COUNT OF SUBSTRING INSTANCES IN A STRING -------\n\ncountAll :: Text -> Text -> Int\ncountAll needle haystack =\n length\n (breakOnAll needle haystack)\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n print $\n countAll \"ab\"\n <$> [ \"ababababab\",\n \"abelian absurdity\",\n \"babel kebab\"\n ]\n", "language": "Haskell" }, { "code": "count :: Eq a => [a] -> [a] -> Int\ncount [] = error \"empty substring\"\ncount sub = go\n where\n go = scan sub . dropWhile (/= head sub)\n scan _ [] = 0\n scan [] xs = 1 + go xs\n scan (x:xs) (y:ys) | x == y = scan xs ys\n | otherwise = go ys\n", "language": "Haskell" }, { "code": "import Data.List (tails, stripPrefix)\nimport Data.Maybe (catMaybes)\n\ncount :: Eq a => [a] -> [a] -> Int\ncount sub = length . catMaybes . map (stripPrefix sub) . tails\n", "language": "Haskell" }, { "code": "procedure main()\nevery A := ![ [\"the three truths\",\"th\"], [\"ababababab\",\"abab\"] ] do\n write(\"The string \",image(A[2]),\" occurs as a non-overlapping substring \",\n countSubstring!A , \" times in \",image(A[1]))\nend\n\nprocedure countSubstring(s1,s2) #: return count of non-overlapping substrings\nc := 0\ns1 ? while tab(find(s2)) do {\n move(*s2)\n c +:= 1\n }\nreturn c\nend\n", "language": "Icon" }, { "code": "100 INPUT PROMPT \"String: \":TXT$\n110 INPUT PROMPT \"Substring: \":SUB$\n120 PRINT COUNT(LCASE$(TXT$),LCASE$(SUB$))\n130 DEF COUNT(TXT$,SUB$)\n140 LET N=0:LET PO=1\n150 DO\n160 LET PO=POS(TXT$,SUB$,PO)\n170 IF PO THEN LET N=N+1:LET PO=PO+LEN(SUB$)\n180 LOOP UNTIL PO=0\n190 LET COUNT=N\n200 END DEF\n", "language": "IS-BASIC" }, { "code": "require'strings'\ncountss=: #@] %~ #@[ - [ #@rplc '';~]\n", "language": "J" }, { "code": " 'the three truths' countss 'th'\n3\n 'ababababab' countss 'abab'\n2\n", "language": "J" }, { "code": "int countSubstring(String string, String substring) {\n substring = Pattern.quote(substring);\n Pattern pattern = Pattern.compile(substring);\n Matcher matcher = pattern.matcher(string);\n int count = 0;\n while (matcher.find())\n count++;\n return count;\n}\n", "language": "Java" }, { "code": "public class CountSubstring {\n\tpublic static int countSubstring(String subStr, String str){\n\t\treturn (str.length() - str.replace(subStr, \"\").length()) / subStr.length();\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(countSubstring(\"th\", \"the three truths\"));\n\t\tSystem.out.println(countSubstring(\"abab\", \"ababababab\"));\n\t\tSystem.out.println(countSubstring(\"a*b\", \"abaabba*bbaba*bbab\"));\n\t}\n}\n", "language": "Java" }, { "code": "import java.util.regex.Pattern;\n\npublic class CountSubstring {\n\tpublic static int countSubstring(String subStr, String str){\n\t\t// the result of split() will contain one more element than the delimiter\n\t\t// the \"-1\" second argument makes it not discard trailing empty strings\n\t\treturn str.split(Pattern.quote(subStr), -1).length - 1;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(countSubstring(\"th\", \"the three truths\"));\n\t\tSystem.out.println(countSubstring(\"abab\", \"ababababab\"));\n\t\tSystem.out.println(countSubstring(\"a*b\", \"abaabba*bbaba*bbab\"));\n\t}\n}\n", "language": "Java" }, { "code": "public class CountSubstring {\n\tpublic static int countSubstring(String subStr, String str){\n\t\tint count = 0;\n\t\tfor (int loc = str.indexOf(subStr); loc != -1;\n\t\t loc = str.indexOf(subStr, loc + subStr.length()))\n\t\t\tcount++;\n\t\treturn count;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(countSubstring(\"th\", \"the three truths\"));\n\t\tSystem.out.println(countSubstring(\"abab\", \"ababababab\"));\n\t\tSystem.out.println(countSubstring(\"a*b\", \"abaabba*bbaba*bbab\"));\n\t}\n}\n", "language": "Java" }, { "code": "function countSubstring(str, subStr) {\n var matches = str.match(new RegExp(subStr, \"g\"));\n return matches ? matches.length : 0;\n}\n", "language": "JavaScript" }, { "code": "const countSubString = (str, subStr) => str.split(subStr).length - 1;\n", "language": "JavaScript" }, { "code": "def countSubstring(sub):\n [match(sub; \"g\")] | length;\n", "language": "Jq" }, { "code": "\"the three truths\" | countSubstring(\"th\")\n", "language": "Jq" }, { "code": "ts = [\"the three truths\", \"ababababab\"]\ntsub = [\"th\", \"abab\"]\n\nprintln(\"Test of non-overlapping substring counts.\")\nfor i in 1:length(ts)\n print(ts[i], \" (\", tsub[i], \") => \")\n println(length(matchall(Regex(tsub[i]), ts[i])))\nend\nprintln()\nprintln(\"Test of overlapping substring counts.\")\nfor i in 1:length(ts)\n print(ts[i], \" (\", tsub[i], \") => \")\n println(length(matchall(Regex(tsub[i]), ts[i], true)))\nend\n", "language": "Julia" }, { "code": " \"the three truths\" _ss \"th\"\n0 4 13\n\n #\"the three truths\" _ss \"th\"\n3\n\n \"ababababab\" _ss \"abab\"\n0 4\n\n #\"ababababab\" _ss \"abab\"\n2\n", "language": "K" }, { "code": "include ..\\Utilitys.tlhy\n\n:count %s !s\n 0 >ps\n [ps> 1 + >ps\n $s len nip + snip nip] [$s find dup] while\n drop drop ps>\n;\n\n\"the three truths\" \"th\" count ?\n\"ababababab\" \"abab\" count ?\n\n\" \" input\n", "language": "Klingphix" }, { "code": "include ..\\Utilitys.tlhy\n\n:count \"- \" convert \"-\" 2 tolist split len nip ;\n\n\"the three truths\" \"th\" count ?\n\"ababababab\" \"abab\" count ?\n\n\" \" input\n", "language": "Klingphix" }, { "code": "// version 1.0.6\n\nfun countSubstring(s: String, sub: String): Int = s.split(sub).size - 1\n\nfun main(args: Array<String>) {\n println(countSubstring(\"the three truths\",\"th\"))\n println(countSubstring(\"ababababab\",\"abab\"))\n println(countSubstring(\"\",\"\"))\n}\n", "language": "Kotlin" }, { "code": "{def countSubstring\n {def countSubstring.r\n {lambda {:n :i :acc :s}\n {if {>= :i :n}\n then :acc\n else {countSubstring.r :n\n {+ :i 1}\n {if {W.equal? {W.get :i :s} ⫖}\n then {+ :acc 1}\n else :acc}\n :s} }}}\n {lambda {:w :s}\n {countSubstring.r {W.length :s} 0 0\n {S.replace \\s by ⫕ in\n {S.replace :w by ⫖ in :s}}}}}\n-> countSubstring\n\n{countSubstring th the three truths}\n-> 3\n{countSubstring ab ababa}\n-> 2\n{countSubstring aba ababa}\n-> 1\n", "language": "Lambdatalk" }, { "code": "writeln len indices \"th\", \"the three truths\"\nwriteln len indices \"abab\", \"ababababab\"\n", "language": "Langur" }, { "code": "define countSubstring(str::string, substr::string)::integer => {\n\tlocal(i = 1, foundpos = -1, found = 0)\n\twhile(#i < #str->size && #foundpos != 0) => {\n\t\tprotect => {\n\t\t\thandle_error => { #foundpos = 0 }\n\t\t\t#foundpos = #str->find(#substr, -offset=#i)\n\t\t}\n\t\tif(#foundpos > 0) => {\n\t\t\t#found += 1\n\t\t\t#i = #foundpos + #substr->size\n\t\telse\n\t\t\t#i++\n\t\t}\n\t}\n\treturn #found\n}\ndefine countSubstring_bothways(str::string, substr::string)::integer => {\n\tlocal(found = countSubstring(#str,#substr))\n\t#str->reverse\n\tlocal(found2 = countSubstring(#str,#substr))\n\t#found > #found2 ? return #found | return #found2\n}\ncountSubstring_bothways('the three truths','th')\n//3\ncountSubstring_bothways('ababababab','abab')\n//2\n", "language": "Lasso" }, { "code": "print countSubstring( \"the three truths\", \"th\")\nprint countSubstring( \"ababababab\", \"abab\")\nend\n\nfunction countSubstring( a$, s$)\n c =0\n la =len( a$)\n ls =len( s$)\n for i =1 to la -ls\n if mid$( a$, i, ls) =s$ then c =c +1: i =i +ls -1\n next i\n countSubstring =c\nend function\n", "language": "Liberty-BASIC" }, { "code": ":- object(counting).\n\n :- public(count/3).\n\n count(String, SubString, Count) :-\n count(String, SubString, 0, Count).\n\n count(String, SubString, Count0, Count) :-\n ( sub_atom(String, Before, Length, After, SubString) ->\n Count1 is Count0 + 1,\n Start is Before + Length,\n sub_atom(String, Start, After, 0, Rest),\n count(Rest, SubString, Count1, Count)\n ; Count is Count0\n ).\n\n:- end_object.\n", "language": "Logtalk" }, { "code": "| ?- counting::count('the three truths', th, N).\nN = 3\nyes\n\n| ?- counting::count(ababababab, abab, N).\nN = 2\nyes\n", "language": "Logtalk" }, { "code": "function countSubstring(s1, s2)\n return select(2, s1:gsub(s2, \"\"))\nend\n\nprint(countSubstring(\"the three truths\", \"th\"))\nprint(countSubstring(\"ababababab\", \"abab\"))\n", "language": "Lua" }, { "code": "function countSubstring(s1, s2)\n local count = 0\n for eachMatch in s1:gmatch(s2) do\n count = count + 1\n end\n return count\nend\n\nprint(countSubstring(\"the three truths\", \"th\"))\nprint(countSubstring(\"ababababab\", \"abab\"))\n", "language": "Lua" }, { "code": " .TITLE CSUBS\n .MCALL .TTYOUT,.EXIT\nCSUBS:: JMP DEMO\n\n ; COUNT SUBSTRINGS R1 IN R0\nCOUNT: CLR R2\n BR 4$\n1$: MOV R0,R3\n MOV R1,R4\n2$: CMPB (R3)+,(R4)+\n BEQ 2$\n TSTB -(R4)\n BNE 3$\n INC R2\n DEC R3\n MOV R3,R0\n BR 4$\n3$: INC R0\n4$: TSTB (R0)\n BNE 1$\n RTS PC\n\n ; TEST EXAMPLES\nDEMO: MOV #ST1,R0\n MOV #SU1,R1\n JSR PC,1$\n MOV #ST2,R0\n MOV #SU2,R1\n JSR PC,1$\n .EXIT\n1$: JSR PC,COUNT\n ADD #60,R2\n MOVB R2,3$\n MOV #3$,R2\n2$: MOVB (R2)+,R0\n .TTYOUT\n BNE 2$\n RTS PC\n3$: .BYTE 0,15,12,0\n\nST1: .ASCIZ /THE THREE TRUTHS/\nSU1: .ASCIZ /TH/\nST2: .ASCIZ /ABABABABAB/\nSU2: .ASCIZ /ABAB/\n .END CSUBS\n", "language": "MACRO-11" }, { "code": "f:=proc(s::string,c::string,count::nonnegint) local n;\n n:=StringTools:-Search(c,s);\n if n>0 then 1+procname(s[n+length(c)..],c,count);\n else 0; end if;\nend proc:\n\nf(\"the three truths\",\"th\",0);\n\nf(\"ababababab\",\"abab\",0);\n", "language": "Maple" }, { "code": "StringPosition[\"the three truths\",\"th\",Overlaps->False]//Length\n3\nStringPosition[\"ababababab\",\"abab\",Overlaps->False]//Length\n2\n", "language": "Mathematica" }, { "code": " % Count occurrences of a substring without overlap\n length(findstr(\"ababababab\",\"abab\",0))\n length(findstr(\"the three truths\",\"th\",0))\n\n % Count occurrences of a substring with overlap\n length(findstr(\"ababababab\",\"abab\",1))\n", "language": "MATLAB" }, { "code": "scount(e, s) := block(\n [n: 0, k: 1],\n while integerp(k: ssearch(e, s, k)) do (n: n + 1, k: k + 1),\n n\n)$\n\nscount(\"na\", \"banana\");\n2\n", "language": "Maxima" }, { "code": "string.count = function(s)\n return self.split(s).len - 1\nend function\n\nprint \"the three truths\".count(\"th\")\nprint \"ababababab\".count(\"abab\")\n", "language": "MiniScript" }, { "code": "import java.util.regex.Pattern\nimport java.util.regex.Matcher\n\n#The \"remove and count the difference\" method\ndef count_substring(pattern:string, source:string)\n (source.length() - source.replace(pattern, \"\").length()) / pattern.length()\nend\n\nputs count_substring(\"th\", \"the three truths\") # ==> 3\nputs count_substring(\"abab\", \"ababababab\") # ==> 2\nputs count_substring(\"a*b\", \"abaabba*bbaba*bbab\") # ==> 2\n\n\n# The \"split and count\" method\ndef count_substring2(pattern:string, source:string)\n # the result of split() will contain one more element than the delimiter\n\t# the \"-1\" second argument makes it not discard trailing empty strings\n source.split(Pattern.quote(pattern), -1).length - 1\nend\n\nputs count_substring2(\"th\", \"the three truths\") # ==> 3\nputs count_substring2(\"abab\", \"ababababab\") # ==> 2\nputs count_substring2(\"a*b\", \"abaabba*bbaba*bbab\") # ==> 2\n\n\n# This method does a match and counts how many times it matches\ndef count_substring3(pattern:string, source:string)\n result = 0\n Matcher m = Pattern.compile(Pattern.quote(pattern)).matcher(source);\n while (m.find())\n result = result + 1\n end\n result\nend\n\nputs count_substring3(\"th\", \"the three truths\") # ==> 3\nputs count_substring3(\"abab\", \"ababababab\") # ==> 2\nputs count_substring3(\"a*b\", \"abaabba*bbaba*bbab\") # ==> 2\n", "language": "Mirah" }, { "code": "main :: [sys_message]\nmain = [Stdout (show (countSubstring \"the three truths\" \"th\") ++ \"\\n\"),\n Stdout (show (countSubstring \"ababababab\" \"abab\") ++ \"\\n\")]\n\ncountSubstring :: [*]->[*]->num\ncountSubstring str ss\n = 0, if str = []\n = 1 + countSubstring (drop len str) ss, if match\n = countSubstring (tl str) ss, otherwise\n where len = #ss\n match = take len str = ss\n", "language": "Miranda" }, { "code": "def countSubstring(str, subStr)\n return int((len(str) - len(str.replace(subStr, \"\"))) / len(subStr))\nend\n", "language": "Nanoquery" }, { "code": "using System.Console;\n\nmodule CountSubStrings\n{\n CountSubStrings(this text : string, target : string) : int\n {\n match (target) {\n |\"\" => 0\n |_ => (text.Length - text.Replace(target, \"\").Length) / target.Length\n }\n }\n\n Main() : void\n {\n def text1 = \"the three truths\";\n def target1 = \"th\";\n def text2 = \"ababababab\";\n def target2 = \"abab\";\n\n WriteLine($\"$target1 occurs $(text1.CountSubStrings(target1)) times in $text1\");\n WriteLine($\"$target2 occurs $(text2.CountSubStrings(target2)) times in $text2\");\n }\n}\n", "language": "Nemerle" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod countSubstring(inStr, findStr) public static\n return inStr.countstr(findStr)\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod main(args = String[]) public static\n strings = ''\n find = 'FIND'\n ix = 0\n ix = ix + 1; strings[0] = ix; find[0] = ix; strings[ix] = 'the three truths'; strings[ix, find] = 'th'\n ix = ix + 1; strings[0] = ix; find[0] = ix; strings[ix] = 'ababababab'; strings[ix, find] = 'abab'\n\n loop ix = 1 to strings[0]\n str = strings[ix]\n fnd = strings[ix, find]\n say 'there are' countSubstring(str, fnd) 'occurences of \"'fnd'\" in \"'str'\"'\n end ix\n\n return\n", "language": "NetRexx" }, { "code": "; file: stringcount.lsp\n; url: http://rosettacode.org/wiki/Count_occurrences_of_a_substring\n; author: oofoe 2012-01-29\n\n; Obvious (and non-destructive...)\n\n; Note that NewLISP performs an /implicit/ slice on a string or list\n; with this form \"(start# end# stringorlist)\". If the end# is omitted,\n; the slice will go to the end of the string. This is handy here to\n; keep removing the front part of the string as it gets matched.\n\n(define (scount needle haystack)\n (let ((h (copy haystack)) ; Copy of haystack string.\n (i 0) ; Cursor.\n (c 0)) ; Count of occurences.\n\n (while (setq i (find needle h))\n (inc c)\n (setq h ((+ i (length needle)) h)))\n\n c)) ; Return count.\n\n; Tricky -- Uses functionality from replace function to find all\n; non-overlapping occurrences, replace them, and return the count of\n; items replaced in system variable $0.\n\n(define (rcount needle haystack)\n (replace needle haystack \"X\") $0)\n\n; Test\n\n(define (test f needle haystack)\n (println \"Found \" (f needle haystack)\n \" occurences of '\" needle \"' in '\" haystack \"'.\"))\n\n(dolist (f (list scount rcount))\n (test f \"glart\" \"hinkerpop\")\n (test f \"abab\" \"ababababab\")\n (test f \"th\" \"the three truths\")\n (println)\n )\n\n(exit)\n", "language": "NewLISP" }, { "code": "import strutils\n\nproc count(s, sub: string): int =\n var i = 0\n while true:\n i = s.find(sub, i)\n if i < 0:\n break\n i += sub.len # i += 1 for overlapping substrings\n inc result\n\necho count(\"the three truths\",\"th\")\n\necho count(\"ababababab\",\"abab\")\n", "language": "Nim" }, { "code": "@interface NSString (CountSubstrings)\n- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;\n@end\n\n@implementation NSString (CountSubstrings)\n- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr {\n return [[self componentsSeparatedByString:subStr] count] - 1;\n}\n@end\n\nint main(int argc, const char *argv[]) {\n @autoreleasepool {\n\n NSLog(@\"%lu\", [@\"the three truths\" occurrencesOfSubstring:@\"th\"]);\n NSLog(@\"%lu\", [@\"ababababab\" occurrencesOfSubstring:@\"abab\"]);\n NSLog(@\"%lu\", [@\"abaabba*bbaba*bbab\" occurrencesOfSubstring:@\"a*b\"]);\n\n }\n return 0;\n}\n", "language": "Objective-C" }, { "code": "@interface NSString (CountSubstrings)\n- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;\n@end\n\n@implementation NSString (CountSubstrings)\n- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr {\n return ([self length] - [[self stringByReplacingOccurrencesOfString:subStr withString:@\"\"] length]) / [subStr length];\n}\n@end\n\nint main(int argc, const char *argv[]) {\n @autoreleasepool {\n\n NSLog(@\"%lu\", [@\"the three truths\" occurrencesOfSubstring:@\"th\"]);\n NSLog(@\"%lu\", [@\"ababababab\" occurrencesOfSubstring:@\"abab\"]);\n NSLog(@\"%lu\", [@\"abaabba*bbaba*bbab\" occurrencesOfSubstring:@\"a*b\"]);\n\n }\n return 0;\n}\n", "language": "Objective-C" }, { "code": "@interface NSString (CountSubstrings)\n- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;\n@end\n\n@implementation NSString (CountSubstrings)\n- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr {\n NSUInteger count = 0;\n for (NSRange range = [self rangeOfString:subStr]; range.location != NSNotFound;\n range.location += range.length,\n range = [self rangeOfString:subStr options:0\n range:NSMakeRange(range.location, [self length] - range.location)])\n count++;\n return count;\n}\n@end\n\nint main(int argc, const char *argv[]) {\n @autoreleasepool {\n\n NSLog(@\"%lu\", [@\"the three truths\" occurrencesOfSubstring:@\"th\"]);\n NSLog(@\"%lu\", [@\"ababababab\" occurrencesOfSubstring:@\"abab\"]);\n NSLog(@\"%lu\", [@\"abaabba*bbaba*bbab\" occurrencesOfSubstring:@\"a*b\"]);\n\n }\n return 0;\n}\n", "language": "Objective-C" }, { "code": "let count_substring str sub =\n let sub_len = String.length sub in\n let len_diff = (String.length str) - sub_len\n and reg = Str.regexp_string sub in\n let rec aux i n =\n if i > len_diff then n else\n try\n let pos = Str.search_forward reg str i in\n aux (pos + sub_len) (succ n)\n with Not_found -> n\n in\n aux 0 0\n\nlet () =\n Printf.printf \"count 1: %d\\n\" (count_substring \"the three truth\" \"th\");\n Printf.printf \"count 2: %d\\n\" (count_substring \"ababababab\" \"abab\");\n;;\n", "language": "OCaml" }, { "code": ": countSubString(s, sub)\n 0 1 while(sub swap s indexOfAllFrom dup notNull) [ sub size + 1 under+ ]\n drop ;\n", "language": "Oforth" }, { "code": " bag=\"the three truths\"\n x=\"th\"\n say left(bag,30) left(x,15) 'found' bag~countstr(x)\n\n bag=\"ababababab\"\n x=\"abab\"\n say left(bag,30) left(x,15) 'found' bag~countstr(x)\n\n -- can be done caselessly too\n bag=\"abABAbaBab\"\n x=\"abab\"\n say left(bag,30) left(x,15) 'found' bag~caselesscountstr(x)\n", "language": "OoRexx" }, { "code": "subvec(v,u)={\n\tmy(i=1,s);\n\twhile(i+#u<=#v,\n\t\tfor(j=1,#u,\n\t\t\tif(v[i+j-1]!=u[j], i++; next(2))\n\t\t);\n\t\ts++;\n\t\ti+=#u\n\t);\n\ts\n};\nsubstr(s1,s2)=subvec(Vec(s1),Vec(s2));\nsubstr(\"the three truths\",\"th\")\nsubstr(\"ababababab\",\"abab\")\n", "language": "PARI-GP" }, { "code": "sub countSubstring {\n my $str = shift;\n my $sub = quotemeta(shift);\n my $count = () = $str =~ /$sub/g;\n return $count;\n# or return scalar( () = $str =~ /$sub/g );\n}\n\nprint countSubstring(\"the three truths\",\"th\"), \"\\n\"; # prints \"3\"\nprint countSubstring(\"ababababab\",\"abab\"), \"\\n\"; # prints \"2\"\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #008000;\">\"the three truths\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"th\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ababababab\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"abab\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ababababab\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"aba\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ababababab\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ab\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ababababab\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"a\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ababababab\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">}}</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">start</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">count</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">substring</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">start</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">substring</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">start</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">match</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">substring</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">start</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">start</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">start</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">substring</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"The string \\\"%s\\\" occurs as a non-overlapping substring %d times in \\\"%s\\\"\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">substring</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n", "language": "PHP" }, { "code": "count_substrings_rec(S, SB) = C =>\n count_rec(S,SB,0,C).\n\ncount_rec([],_SB,Count,Count).\ncount_rec(SBRest,SB,Count0,Count) :-\n SBRest = SB ++ Rest, % \"split\" into substring and the rest of the string\n count_rec(Rest,SB,Count0+1,Count).\ncount_rec([T|Rest],SB,Count0,Count) :-\n T != SB, % this character is not a substring\n count_rec(Rest,SB,Count0,Count).\n", "language": "Picat" }, { "code": "count_substrings_find(S, SB) = C =>\n SLen = S.len,\n Count = 0,\n From = 1,\n while (From <= SLen)\n (\n once(find(slice(S,From),SB,_From2,To)) ->\n Count := Count + 1,\n From := From + To\n ;\n From := From + 1\n )\n end,\n C = Count.\n", "language": "Picat" }, { "code": "(de countSubstring (Str Sub)\n (let (Cnt 0 H (chop Sub))\n (for (S (chop Str) S (cdr S))\n (when (head H S)\n (inc 'Cnt)\n (setq S (map prog2 H S)) ) )\n Cnt ) )\n", "language": "PicoLisp" }, { "code": "write(\"%d %d\\n\",\n String.count(\"the three truths\", \"th\"),\n String.count(\"ababababab\", \"abab\"));\n", "language": "Pike" }, { "code": "cnt: procedure options (main);\n declare (i, tally) fixed binary;\n declare (text, key) character (100) varying;\n\n get edit (text) (L); put skip data (text);\n get edit (key) (L); put skip data (key);\n\n tally = 0; i = 1;\n do until (i = 0);\n i = index(text, key, i);\n if i > 0 then do; tally = tally + 1; i = i + length(key); end;\n end;\n put skip list (tally);\nend cnt;\n", "language": "PL-I" }, { "code": "100H:\n/* CP/M CALLS */\nBDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;\nEXIT: PROCEDURE; CALL BDOS(0, 0); END EXIT;\nPRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;\n\n/* PRINT A NUMBER */\nPRINT$NUMBER: PROCEDURE (N);\n DECLARE S (8) BYTE INITIAL ('.....',13,10,'$');\n DECLARE (P, N) ADDRESS, C BASED P BYTE;\n P = .S(5);\nDIGIT:\n P = P - 1;\n C = N MOD 10 + '0';\n N = N / 10;\n IF N > 0 THEN GO TO DIGIT;\n CALL PRINT(P);\nEND PRINT$NUMBER;\n\n/* COUNT OCCURRENCES OF SUBSTRING IN STRING */\nCOUNT$SUBSTRING: PROCEDURE (STR, MATCH) ADDRESS;\n DECLARE (STR, MATCH) ADDRESS, C BASED STR BYTE;\n DECLARE (SP, MP) ADDRESS, (SC BASED SP, MC BASED MP) BYTE;\n DECLARE COUNT ADDRESS;\n COUNT = 0;\n DO WHILE C <> '$';\n SP = STR;\n MP = MATCH;\n DO WHILE SC = MC;\n SP = SP + 1;\n MP = MP + 1;\n END;\n IF MC = '$' THEN DO;\n STR = SP;\n COUNT = COUNT + 1;\n END;\n ELSE DO;\n STR = STR + 1;\n END;\n END;\n RETURN COUNT;\nEND COUNT$SUBSTRING;\n\nCALL PRINT$NUMBER(COUNT$SUBSTRING(.'THE THREE TRUTHS$', .'TH$')); /* PRINTS 3 */\nCALL PRINT$NUMBER(COUNT$SUBSTRING(.'ABABABABAB$', .'ABAB$')); /* PRINTS 2 */\nCALL PRINT$NUMBER(COUNT$SUBSTRING(.'CAT$', .'DOG$')); /* PRINTS 0 */\n\nCALL EXIT;\nEOF\n", "language": "PL-M" }, { "code": "FUNCTION PBMAIN () AS LONG\n PRINT \"the three truths, th:\", TALLY(\"the three truths\", \"th\")\n PRINT \"ababababab, abab:\", TALLY(\"ababababab\", \"abab\")\nEND FUNCTION\n", "language": "PowerBASIC" }, { "code": "[regex]::Matches(\"the three truths\", \"th\").count\n", "language": "PowerShell" }, { "code": "[regex]::Matches(\"ababababab\",\"abab\").count\n", "language": "PowerShell" }, { "code": "count_substring(String, Sub, Total) :-\n count_substring(String, Sub, 0, Total).\n\ncount_substring(String, Sub, Count, Total) :-\n ( substring_rest(String, Sub, Rest)\n ->\n succ(Count, NextCount),\n count_substring(Rest, Sub, NextCount, Total)\n ;\n Total = Count\n ).\n\nsubstring_rest(String, Sub, Rest) :-\n sub_string(String, Before, Length, Remain, Sub),\n DropN is Before + Length,\n sub_string(String, DropN, Remain, 0, Rest).\n", "language": "Prolog" }, { "code": "?- count_substring(\"the three truths\",\"th\",X).\nX = 3.\n\n?- count_substring(\"ababababab\",\"abab\",X).\nX = 2.\n", "language": "Prolog" }, { "code": ":- system:set_prolog_flag(double_quotes,chars) .\n\noccurrences(TARGETz0,SUBSTRINGz0,COUNT)\n:-\nprolog:phrase(occurrences(SUBSTRINGz0,0,COUNT),TARGETz0)\n.\n\noccurrences(\"\",_,_)\n-->\n! ,\n{ false }\n.\n\noccurrences(SUBSTRINGz0,COUNT0,COUNT)\n-->\nSUBSTRINGz0 ,\n! ,\n{ COUNT1 is COUNT0 + 1 } ,\noccurrences(SUBSTRINGz0,COUNT1,COUNT)\n.\n\noccurrences(SUBSTRINGz0,COUNT0,COUNT)\n-->\n[_] ,\n! ,\noccurrences(SUBSTRINGz0,COUNT0,COUNT)\n.\n\noccurrences(_SUBSTRINGz0_,COUNT,COUNT)\n-->\n!\n.\n", "language": "Prolog" }, { "code": "a = CountString(\"the three truths\",\"th\")\nb = CountString(\"ababababab\",\"abab\")\n; a = 3\n; b = 2\n", "language": "PureBasic" }, { "code": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n", "language": "Python" }, { "code": " [ [] 95 times\n [ i^ space +\n join ] ] constant is alphabet ( --> $ )\n\n [ [ 2dup != while\n -1 split drop\n swap 1 split\n unrot drop again ]\n drop size ] is overlap ( [ [ --> n )\n\n [ temp put [] swap\n alphabet witheach\n [ over -1 poke\n over overlap\n dup temp share\n = if negate\n swap dip join ]\n drop temp release ] is eachend ( [ n --> [ )\n\n [ [] swap\n dup temp put\n size times\n [ temp share\n i 1+ split drop\n temp share size eachend\n nested swap join ]\n temp release ] is buildfsm ( $ --> [ )\n\n [ dup [] = iff -1\n else\n [ behead\n dup carriage = if\n [ drop space ]\n space - ]\n swap ] is nextcharn ( $ --> n $ )\n\n [ swap dup size\n swap temp put\n swap 0\n [ over swap peek\n temp take\n nextcharn\n temp put\n dup 0 < iff\n [ 2drop 0 ] done\n peek\n dup 0 < until ]\n nip\n temp take size - + ] is usefsm ( $ [ --> n )\n\n [ over size 0 = iff\n [ 2drop 0 ]\n else\n [ swap buildfsm\n usefsm ] ] is find$ ( $ $ --> n )\n", "language": "Quackery" }, { "code": " [ over size 0 = iff\n [ 2drop [] ] done\n [] unrot\n swap buildfsm\n [ 2dup usefsm\n rot 2dup found while\n dip [ over size + ]\n dip\n [ rot over join\n unrot ]\n swap split\n nip swap again ]\n 2drop drop ] is findall$ ( $ $ --> [ )\n", "language": "Quackery" }, { "code": " [ swap findall$ size ] is occurences ( $ $ --> n )\n\n $ \"the three truths\" $ \"th\" occurences echo cr\n $ \"ababababab\" $ \"abab\" occurences echo cr\n", "language": "Quackery" }, { "code": "count = function(haystack, needle)\n {v = attr(gregexpr(needle, haystack, fixed = T)[[1]], \"match.length\")\n if (identical(v, -1L)) 0 else length(v)}\n\nprint(count(\"hello\", \"l\"))\n", "language": "R" }, { "code": "library(stringr)\nprint(str_count(\"hello\", fixed(\"l\")))\n", "language": "R" }, { "code": "(define count-substring\n (compose length regexp-match*))\n", "language": "Racket" }, { "code": "> (count-substring \"th\" \"the three truths\")\n3\n> (count-substring \"abab\" \"ababababab\")\n2\n", "language": "Racket" }, { "code": "sub count-substring($big, $little) { +$big.comb: / :r $little / }\n\nsay count-substring(\"the three truths\", \"th\"); # 3\nsay count-substring(\"ababababab\", \"abab\"); # 2\n\nsay count-substring(123123123, 12); # 3\n", "language": "Raku" }, { "code": "Red []\n\ncount-occurrences: function [string substring] [\n length? parse string [collect [some [keep substring to substring]]]\n]\n\ntest-case-1: \"the three truths\"\ntest-case-2: \"ababababab\"\n\nprint [test-case-1 \"-\" count-occurrences test-case-1 \"th\"]\nprint [test-case-2 \"-\" count-occurrences test-case-2 \"abab\"]\n", "language": "Red" }, { "code": "$ENTRY Go {\n = <Prout <Count ('th') 'the three truths'>>\n <Prout <Count ('abab') 'abababab'>>;\n};\n\nCount {\n (e.item) e.item e.rest = <+ 1 <Count (e.item) e.rest>>;\n (e.item) s.x e.rest = <Count (e.item) e.rest>;\n (e.item) = 0;\n};\n", "language": "Refal" }, { "code": "/*REXX program counts the occurrences of a (non─overlapping) substring in a string. */\nw=. /*max. width so far.*/\nbag= 'the three truths' ; x= \"th\" ; call showResult\nbag= 'ababababab' ; x= \"abab\" ; call showResult\nbag= 'aaaabacad' ; x= \"aa\" ; call showResult\nbag= 'abaabba*bbaba*bbab' ; x= \"a*b\" ; call showResult\nbag= 'abaabba*bbaba*bbab' ; x= \" \" ; call showResult\nbag= ; x= \"a\" ; call showResult\nbag= ; x= ; call showResult\nbag= 'catapultcatalog' ; x= \"cat\" ; call showResult\nbag= 'aaaaaaaaaaaaaa' ; x= \"aa\" ; call showResult\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncountstr: procedure; parse arg haystack,needle,start; if start=='' then start=1\n width=length(needle)\n do $=0 until p==0; p=pos(needle,haystack,start)\n start=width + p /*prevent overlaps.*/\n end /*$*/\n return $ /*return the count.*/\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nshowResult: if w==. then do; w=30 /*W: largest haystack width.*/\n say center('haystack',w) center('needle',w%2) center('count',5)\n say left('', w, \"═\") left('', w%2, \"═\") left('', 5, \"═\")\n end\n\n if bag=='' then bag= \" (null)\" /*handle displaying of nulls.*/\n if x=='' then x= \" (null)\" /* \" \" \" \" */\n say left(bag, w) left(x, w%2) center(countstr(bag, x), 5)\n return\n", "language": "REXX" }, { "code": "aString = \"Ring Welcome Ring to the Ring Ring Programming Ring Language Ring\"\nbString = \"Ring\"\nsee count(aString,bString)\n\nfunc count cString,dString\n sum = 0\n while substr(cString,dString) > 0\n sum++\n cString = substr(cString,substr(cString,dString)+len(string(sum)))\n end\n return sum\n", "language": "Ring" }, { "code": "def countSubstrings str, subStr\n str.scan(subStr).length\nend\n\np countSubstrings \"the three truths\", \"th\" #=> 3\np countSubstrings \"ababababab\", \"abab\" #=> 2\n", "language": "Ruby" }, { "code": "print countSubstring(\"the three truths\",\"th\")\nprint countSubstring(\"ababababab\",\"abab\")\n\nFUNCTION countSubstring(s$,find$)\nWHILE instr(s$,find$,i) <> 0\n countSubstring = countSubstring + 1\n i = instr(s$,find$,i) + len(find$)\nWEND\nEND FUNCTION\n", "language": "Run-BASIC" }, { "code": "fn main() {\n println!(\"{}\",\"the three truths\".matches(\"th\").count());\n println!(\"{}\",\"ababababab\".matches(\"abab\").count());\n}\n", "language": "Rust" }, { "code": "import scala.annotation.tailrec\ndef countSubstring(str1:String, str2:String):Int={\n @tailrec def count(pos:Int, c:Int):Int={\n val idx=str1 indexOf(str2, pos)\n if(idx == -1) c else count(idx+str2.size, c+1)\n }\n count(0,0)\n}\n", "language": "Scala" }, { "code": "def countSubstring(str: String, sub: String): Int =\n str.sliding(sub.length).count(_ == sub)\n", "language": "Scala" }, { "code": "def countSubstring( str:String, substr:String ) = substr.r.findAllMatchIn(str).length\n", "language": "Scala" }, { "code": "println(countSubstring(\"ababababab\", \"abab\"))\nprintln(countSubstring(\"the three truths\", \"th\"))\n", "language": "Scala" }, { "code": "gosh> (use gauche.lazy)\n#<undef>\ngosh> (length (lrxmatch \"th\" \"the three truths\"))\n3\ngosh> (length (lrxmatch \"abab\" \"ababababab\"))\n2\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst func integer: countSubstring (in string: stri, in string: searched) is func\n result\n var integer: count is 0;\n local\n var integer: offset is 0;\n begin\n offset := pos(stri, searched);\n while offset <> 0 do\n incr(count);\n offset := pos(stri, searched, offset + length(searched));\n end while;\n end func;\n\nconst proc: main is func\n begin\n writeln(countSubstring(\"the three truths\", \"th\"));\n writeln(countSubstring(\"ababababab\", \"abab\"));\n end func;\n", "language": "Seed7" }, { "code": "put the number of occurrences of \"th\" in \"the three truths\" --> 3\nput the number of occurrences of \"abab\" in \"ababababab\" -- > 2\n", "language": "SenseTalk" }, { "code": "put countSubstring(\"aaaaa\",\"a\") // 5\nput countSubstring(\"abababa\",\"aba\") // 2\n\nfunction countSubstring mainString, subString\n\treturn number of occurrences of subString in mainString\nend countSubstring\n", "language": "SenseTalk" }, { "code": "program count_overlapping_substrings;\n tests := [[\"the three truths\", \"th\"], [\"ababababab\", \"abab\"]];\n loop for [s, subs] in tests do\n print(\"'\" + subs + \"' in '\" + s + \"': \"\n + str countSubs(s, subs));\n end loop;\n\n proc countSubs(s, subs);\n count := 0;\n loop while s(subs) /= om do\n s(subs) := \"\";\n count +:= 1;\n end loop;\n return count;\n end proc;\nend program;\n", "language": "SETL" }, { "code": "say \"the three truths\".count(\"th\");\nsay \"ababababab\".count(\"abab\");\n", "language": "Sidef" }, { "code": "func countSubstring(s, ss) {\n var re = Regex.new(ss.escape, 'g'); # 'g' for global\n var counter = 0;\n while (s =~ re) { ++counter };\n return counter;\n}\n\nsay countSubstring(\"the three truths\",\"th\");\nsay countSubstring(\"ababababab\",\"abab\");\n", "language": "Sidef" }, { "code": "BEGIN\n\n INTEGER PROCEDURE COUNTSUBSTRING(T,TSUB); TEXT T,TSUB;\n BEGIN\n INTEGER N,I;\n I := 1;\n WHILE I+TSUB.LENGTH-1 <= T.LENGTH DO\n IF T.SUB(I,TSUB.LENGTH) = TSUB THEN\n BEGIN\n N := N+1;\n I := I+MAX(TSUB.LENGTH,1);\n END ELSE I := I+1;\n COUNTSUBSTRING:= N;\n END COUNTSUBSTRING;\n\n OUTINT(COUNTSUBSTRING(\"THE THREE TRUTHS\", \"TH\"),0);\n OUTIMAGE;\n OUTINT(COUNTSUBSTRING(\"ABABABABAB\", \"ABAB\"),0);\n OUTIMAGE;\nEND.\n", "language": "Simula" }, { "code": " 10 LET S$=\"THE THREE TRUTHS\"\n 20 LET U$=\"TH\"\n 30 GOSUB 100\n 40 PRINT N\n 50 LET S$=\"ABABABABAB\"\n 60 LET U$=\"ABAB\"\n 70 GOSUB 100\n 80 PRINT N\n 90 STOP\n100 LET N=0\n110 LET I=0\n120 LET I=I+1\n130 IF I+LEN U$>LEN S$ THEN RETURN\n140 IF S$(I TO I+LEN U$-1)<>U$ THEN GOTO 120\n150 LET N=N+1\n160 LET I=I+LEN U$\n170 GOTO 130\n", "language": "Sinclair-ZX81-BASIC" }, { "code": "Transcript showCR:('the three truths' occurrencesOfString:'th').\nTranscript showCR:('ababababab' occurrencesOfString:'abab')\n", "language": "Smalltalk" }, { "code": " DEFINE(\"countSubstring(t,s)\")\n\n OUTPUT = countSubstring(\"the three truths\",\"th\")\n OUTPUT = countSubstring(\"ababababab\",\"abab\")\n\n :(END)\ncountSubstring t ARB s = :F(RETURN)\n countSubstring = countSubstring + 1 :(countSubstring)\nEND\n3\n2\n", "language": "SNOBOL4" }, { "code": "fun count_substrings (str, sub) =\n let\n fun aux (str', count) =\n let\n val suff = #2 (Substring.position sub str')\n in\n if Substring.isEmpty suff then\n \t count\n else\n aux (Substring.triml (size sub) suff, count + 1)\n end\n in\n aux (Substring.full str, 0)\n end;\n\nprint (Int.toString (count_substrings (\"the three truths\", \"th\")) ^ \"\\n\");\nprint (Int.toString (count_substrings (\"ababababab\", \"abab\")) ^ \"\\n\");\nprint (Int.toString (count_substrings (\"abaabba*bbaba*bbab\", \"a*b\")) ^ \"\\n\");\n", "language": "Standard-ML" }, { "code": "function strcount(s, x) {\n\tn = 0\n\tk = 1-(i=strlen(x))\n\tdo {\n\t\tif (k = ustrpos(s, x, k+i)) n++\n\t} while(k)\n\treturn(n)\n}\n\nstrcount(\"peter piper picked a peck of pickled peppers\", \"pe\")\n 5\n\nstrcount(\"ababababab\",\"abab\")\n 2\n", "language": "Stata" }, { "code": "import Foundation\n\nfunc countSubstring(str: String, substring: String) -> Int {\n return str.components(separatedBy: substring).count - 1\n}\n\nprint(countSubstring(str: \"the three truths\", substring: \"th\"))\nprint(countSubstring(str: \"ababababab\", substring: \"abab\"))\n", "language": "Swift" }, { "code": "proc countSubstrings {haystack needle} {\n regexp -all ***=$needle $haystack\n}\nputs [countSubstrings \"the three truths\" \"th\"]\nputs [countSubstrings \"ababababab\" \"abab\"]\nputs [countSubstrings \"abaabba*bbaba*bbab\" \"a*b\"]\n", "language": "Tcl" }, { "code": "#lang transd\n\nMainModule: {\n countSubstring: (λ s String() sub String()\n (with n 0 pl 0\n (while (> (= pl (find s sub pl)) -1)\n (+= pl (size sub)) (+= n 1))\n (lout n))\n ),\n _start: (λ\n (countSubstring \"the three truths\" \"th\")\n (countSubstring \"ababababab\" \"abab\")\n )\n}\n", "language": "Transd" }, { "code": "FUNCTION countsubstring(where$, what$)\n LET c = 0\n LET s = 1-LEN(what$)\n DO\n LET s = POS(where$,what$,s+LEN(what$))\n IF 0 = s THEN EXIT DO\n LET c = c+1\n LOOP\n LET countsubstring = c\nEND FUNCTION\n\nPRINT \"the three truths, th:\", countSubstring(\"the three truths\", \"th\")\nPRINT \"ababababab, abab:\", countSubstring(\"ababababab\", \"abab\")\nEND\n", "language": "True-BASIC" }, { "code": "$$ MODE TUSCRIPT, {}\noccurences=COUNT (\"the three truths\", \":th:\")\noccurences=COUNT (\"ababababab\", \":abab:\")\noccurences=COUNT (\"abaabba*bbaba*bbab\",\":a\\*b:\")\n", "language": "TUSCRIPT" }, { "code": "@(next :args)\n@(do (defun count-occurrences (haystack needle)\n (for* ((occurrences 0)\n (old-pos 0)\n (new-pos (search-str haystack needle old-pos nil)))\n (new-pos occurrences)\n ((inc occurrences)\n (set old-pos (+ new-pos (length needle)))\n (set new-pos (search-str haystack needle old-pos nil))))))\n@ndl\n@hay\n@(output)\n@(count-occurrences hay ndl) occurrences(s) of @ndl inside @hay\n@(end)\n", "language": "TXR" }, { "code": "#!/bin/bash\n\nfunction countString(){\n\tinput=$1\n\tcnt=0\n\n\tuntil [ \"${input/$2/}\" == \"$input\" ]; do\n\t\tinput=${input/$2/}\n\t\tlet cnt+=1\n\tdone\n\techo $cnt\n}\n\ncountString \"the three truths\" \"th\"\ncountString \"ababababab\" \"abab\"\n", "language": "UNIX-Shell" }, { "code": "fn main(){\n println('the three truths'.count('th'))\n println('ababababab'.count('abab'))\n}\n", "language": "V-(Vlang)" }, { "code": "Function CountStringInString(stLookIn As String, stLookFor As String)\n CountStringInString = UBound(Split(stLookIn, stLookFor))\nEnd Function\n", "language": "VBA" }, { "code": "Function CountSubstring(str,substr)\n\tCountSubstring = 0\n\tFor i = 1 To Len(str)\n\t\tIf Len(str) >= Len(substr) Then\n\t\t\tIf InStr(i,str,substr) Then\n\t\t\t\tCountSubstring = CountSubstring + 1\n\t\t\t\ti = InStr(i,str,substr) + Len(substr) - 1\n\t\t\tEnd If\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write CountSubstring(\"the three truths\",\"th\") & vbCrLf\nWScript.StdOut.Write CountSubstring(\"ababababab\",\"abab\") & vbCrLf\n", "language": "VBScript" }, { "code": "function CountSubstring(str,substr)\n with new regexp\n .pattern=substr\n .global=true\n set m=.execute(str)\n end with\n CountSubstring =m.count\nend function\nWScript.StdOut.Writeline CountSubstring(\"the three truths\",\"th\")\nWScript.StdOut.Writeline CountSubstring(\"ababababab\",\"abab\")\n", "language": "VBScript" }, { "code": "Module Count_Occurrences_of_a_Substring\n Sub Main()\n Console.WriteLine(CountSubstring(\"the three truths\", \"th\"))\n Console.WriteLine(CountSubstring(\"ababababab\", \"abab\"))\n Console.WriteLine(CountSubstring(\"abaabba*bbaba*bbab\", \"a*b\"))\n Console.WriteLine(CountSubstring(\"abc\", \"\"))\n End Sub\n\n Function CountSubstring(str As String, substr As String) As Integer\n Dim count As Integer = 0\n If (Len(str) > 0) And (Len(substr) > 0) Then\n Dim p As Integer = InStr(str, substr)\n Do While p <> 0\n p = InStr(p + Len(substr), str, substr)\n count += 1\n Loop\n End If\n Return count\n End Function\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "@let {\n c &[s t] #!s.match &(t)g\n\n [[\n !!c \"the three truths\" \"th\"\n !!c \"ababababab\" \"abab\"\n ]]\n}\n", "language": "Wortel" }, { "code": "import \"./pattern\" for Pattern\nimport \"./fmt\" for Fmt\n\nvar countSubstring = Fn.new { |str, sub|\n var p = Pattern.new(sub)\n return p.findAll(str).count\n}\n\nvar tests = [\n [\"the three truths\", \"th\"],\n [\"ababababab\", \"abab\"],\n [\"abaabba*bbaba*bbab\", \"a*b\"],\n [\"aaaaaaaaaaaaaa\", \"aa\"],\n [\"aaaaaaaaaaaaaa\", \"b\"],\n]\n\nfor (test in tests) {\n var count = countSubstring.call(test[0], test[1])\n Fmt.print(\"$6s occurs $d times in $q.\", Fmt.q(test[1]), count, test[0])\n}\n", "language": "Wren" }, { "code": "import \"./str\" for Str\nimport \"./fmt\" for Fmt\n\nvar tests = [\n [\"the three truths\", \"th\"],\n [\"ababababab\", \"abab\"],\n [\"abaabba*bbaba*bbab\", \"a*b\"],\n [\"aaaaaaaaaaaaaa\", \"aa\"],\n [\"aaaaaaaaaaaaaa\", \"b\"],\n]\n\nfor (test in tests) {\n var count = Str.occurs(test[0], test[1])\n Fmt.print(\"$6s occurs $d times in $q.\", Fmt.q(test[1]), count, test[0])\n}\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes; \\intrinsic 'code' declarations\nstring 0; \\use zero-terminated strings, instead of MSb terminated\n\n\nfunc StrNCmp(A, B, N); \\Compare string A to string B up to N bytes long\n\\This returns:\n\\ >0 if A > B\n\\ =0 if A = B\n\\ <0 if A < B\nchar A, B; \\strings to be compared\nint N; \\number of bytes to compare\nint I;\n[for I:= 0 to N-1 do\n if A(I) # B(I) then\n return A(I) - B(I);\nreturn 0; \\they're equal\n]; \\StrNCmp\n\n\nfunc StrLen(Str); \\Return the number of characters in an ASCIIZ string\nchar Str;\nint I;\nfor I:= 0 to -1>>1-1 do\n if Str(I) = 0 then return I;\n\n\nfunc SubStr(A, B); \\Count number of times string B occurs in A\nchar A, B;\nint LA, LB, C, I;\n[LA:= StrLen(A); LB:= StrLen(B);\nC:= 0; I:= 0;\nwhile I < LA do\n if StrNCmp(B, A+I, LB) = 0 then [C:= C+1; I:= I+LB]\n else I:= I+1;\nreturn C;\n];\n\n\n[IntOut(0, SubStr(\"the three truths\", \"th\")); CrLf(0);\n IntOut(0, SubStr(\"ababababab\", \"abab\")); CrLf(0);\n]\n", "language": "XPL0" }, { "code": "print countSubstring(\"the three truths\",\"th\")\nprint countSubstring(\"ababababab\",\"abab\")\nend\n\nsub countSubstring(s$,find$)\n\tcountSubstring = 0\n\ti = 1\n\twhile instr(s$,find$,i) <> 0\n\t\tcountSubstring = countSubstring + 1\n\t\ti = instr(s$,find$,i) + len(find$)\n\tend while\n\treturn countSubstring\nend sub\n", "language": "Yabasic" }, { "code": "fcn countSubstring(s,p){ pn:=p.len(); cnt:=n:=0;\n while(Void!=(n:=s.find(p,n))){cnt+=1; n+=pn}\n cnt\n}\n", "language": "Zkl" }, { "code": "fcn countSubstring(s,p){ (pl:=p.len()) and (s.len()-(s-p).len())/pl }\n", "language": "Zkl" }, { "code": "10 LET t$=\"ABABABABAB\": LET p$=\"ABAB\": GO SUB 1000\n20 LET t$=\"THE THREE TRUTHS\": LET p$=\"TH\": GO SUB 1000\n30 STOP\n1000 PRINT t$: LET c=0\n1010 LET lp=LEN p$\n1020 FOR i=1 TO LEN t$-lp+1\n1030 IF (t$(i TO i+lp-1)=p$) THEN LET c=c+1: LET i=i+lp-1\n1040 NEXT i\n1050 PRINT p$;\"=\";c''\n1060 RETURN\n", "language": "ZX-Spectrum-Basic" } ]
Count-occurrences-of-a-substring
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Count_the_coins\n", "language": "00-META" }, { "code": "There are four types of common coins in &nbsp; [https://en.wikipedia.org/wiki/United_States US] &nbsp; currency: \n:::# &nbsp; quarters &nbsp; (25 cents)\n:::# &nbsp; dimes &nbsp; (10 cents)\n:::# &nbsp; nickels &nbsp; (5 cents), &nbsp; and \n:::# &nbsp; pennies &nbsp; (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# &nbsp; A dime and a nickel \n:::# &nbsp; A dime and 5 pennies\n:::# &nbsp; 3 nickels\n:::# &nbsp; 2 nickels and 5 pennies\n:::# &nbsp; A nickel and 10 pennies\n:::# &nbsp; 15 pennies\n<br>\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? &nbsp; &nbsp; (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); &nbsp; and very rare are half dollars (50 cents). &nbsp; With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: &nbsp; the answer is larger than &nbsp; 2<sup>32</sup>).\n\n\n;References:\n* [https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52 an algorithm] from the book ''[[wp:Structure and Interpretation of Computer Programs|Structure and Interpretation of Computer Programs]]''.\n* [https://algorithmist.com/wiki/Coin_change an article in the algorithmist].\n* [[wp:Change-making problem|Change-making problem]] on Wikipedia.\n<br><br>\n", "language": "00-TASK" }, { "code": "F changes(amount, coins)\n V ways = [Int64(0)] * (amount + 1)\n ways[0] = 1\n L(coin) coins\n L(j) coin .. amount\n ways[j] += ways[j - coin]\n R ways[amount]\n\nprint(changes(100, [1, 5, 10, 25]))\nprint(changes(100000, [1, 5, 10, 25, 50, 100]))\n", "language": "11l" }, { "code": "* count the coins 04/09/2015\nCOINS CSECT\n USING COINS,R12\n LR R12,R15\n L R8,AMOUNT npenny=amount\n L R4,AMOUNT\n SRDA R4,32\n D R4,=F'5'\n LR R9,R5 nnickle=amount/5\n L R4,AMOUNT\n SRDA R4,32\n D R4,=F'10'\n LR R10,R5 ndime=amount/10\n L R4,AMOUNT\n SRDA R4,32\n D R4,=F'25'\n LR R11,R5 nquarter=amount/25\n SR R1,R1 count=0\n SR R4,R4 p=0\nLOOPP CR R4,R8 do p=0 to npenny\n BH ELOOPP\n SR R5,R5 n=0\nLOOPN CR R5,R9 do n=0 to nnickle\n BH ELOOPN\n SR R6,R6\nLOOPD CR R6,R10 do d=0 to ndime\n BH ELOOPD\n SR R7,R7 q=0\nLOOPQ CR R7,R11 do q=0 to nquarter\n BH ELOOPQ\n LR R3,R5 n\n MH R3,=H'5'\n LR R2,R4 p\n AR R2,R3\n LR R3,R6 d\n MH R3,=H'10'\n AR R2,R3\n LR R3,R7 q\n MH R3,=H'25'\n AR R2,R3 s=p+n*5+d*10+q*25\n C R2,=F'100' if s=100\n BNE NOTOK\n LA R1,1(R1) count=count+1\nNOTOK LA R7,1(R7) q=q+1\n B LOOPQ\nELOOPQ LA R6,1(R6) d=d+1\n B LOOPD\nELOOPD LA R5,1(R5) n=n+1\n B LOOPN\nELOOPN LA R4,1(R4) p=p+1\n B LOOPP\nELOOPP XDECO R1,PG+0 edit count\n XPRNT PG,12 print count\n XR R15,R15\n BR R14\nAMOUNT DC F'100' start value in cents\nPG DS CL12\n YREGS\n END COINS\n", "language": "360-Assembly" }, { "code": "with Ada.Text_IO;\n\nprocedure Count_The_Coins is\n\n type Counter_Type is range 0 .. 2**63-1; -- works with gnat\n type Coin_List is array(Positive range <>) of Positive;\n\n function Count(Goal: Natural; Coins: Coin_List) return Counter_Type is\n Cnt: array(0 .. Goal) of Counter_Type := (0 => 1, others => 0);\n -- 0 => we already know one way to choose (no) coins that sum up to zero\n -- 1 .. Goal => we do not (yet) other ways to choose coins\n begin\n for C in Coins'Range loop\n for Amount in 1 .. Cnt'Last loop\n if Coins(C) <= Amount then\n Cnt(Amount) := Cnt(Amount) + Cnt(Amount-Coins(C));\n -- Amount-Coins(C) plus Coins(C) sums up to Amount;\n end if;\n end loop;\n end loop;\n return Cnt(Goal);\n end Count;\n\n procedure Print(C: Counter_Type) is\n begin\n Ada.Text_IO.Put_Line(Counter_Type'Image(C));\n end Print;\n\nbegin\n Print(Count( 1_00, (25, 10, 5, 1)));\n Print(Count(1000_00, (100, 50, 25, 10, 5, 1)));\nend Count_The_Coins;\n", "language": "Ada" }, { "code": "#\n Rosetta Code \"Count the coins\"\n This is a direct translation of the \"naive\" Haskell version, using an array\n rather than a list. LWB, UPB, and array slicing makes the mapping very simple:\n\n LWB > UPB <=> []\n LWB = UPB <=> [x]\n a[LWB a] <=> head xs\n a[LWB a + 1:] <=> tail xs\n#\n\nBEGIN\n PROC ways to make change = ([] INT denoms, INT amount) INT :\n BEGIN\n IF amount = 0 THEN\n 1\n ELIF LWB denoms > UPB denoms THEN\n 0\n ELIF LWB denoms = UPB denoms THEN\n (amount MOD denoms[LWB denoms] = 0 | 1 | 0)\n ELSE\n INT sum := 0;\n FOR i FROM 0 BY denoms[LWB denoms] TO amount DO\n sum +:= ways to make change(denoms[LWB denoms + 1:], amount - i)\n OD;\n sum\n FI\n END;\n [] INT denoms = (25, 10, 5, 1);\n print((ways to make change(denoms, 100), newline))\nEND\n", "language": "ALGOL-68" }, { "code": "#\n Rosetta Code \"Count the coins\"\n This uses what I believe are the ideas behind the \"much faster, probably\n harder to read\" Haskell version.\n#\n\nBEGIN\n PROC ways to make change = ([] INT denoms, INT amount) LONG INT:\n BEGIN\n [0:amount] LONG INT counts, new counts;\n\n FOR i FROM 0 TO amount DO counts[i] := (i = 0 | 1 | 0) OD;\n\n FOR i FROM LWB denoms TO UPB denoms DO\n INT denom = denoms[i];\n FOR j FROM 0 TO amount DO new counts[j] := 0 OD;\n FOR j FROM 0 TO amount DO\n IF LONG INT count = counts[j]; count > 0 THEN\n FOR k FROM j + denom BY denom TO amount DO\n new counts[k] +:= count\n OD\n FI;\n counts[j] +:= new counts[j]\n OD\n OD;\n counts[amount]\n END;\n\n print((ways to make change((1, 5, 10, 25), 100), newline));\n print((ways to make change((1, 5, 10, 25, 50, 100), 10000), newline));\n print((ways to make change((1, 5, 10, 25, 50, 100), 100000), newline))\nEND\n", "language": "ALGOL-68" }, { "code": "-- All input values must be integers and multiples of the same monetary unit.\non countCoins(amount, denominations)\n -- Potentially long list of counters, initialised with 1 (result for amount 0) and 'amount' zeros.\n script o\n property counters : {1}\n end script\n repeat amount times\n set end of o's counters to 0\n end repeat\n\n -- Less labour-intensive alternative to the following repeat's c = 1 iteration.\n set coinValue to beginning of denominations\n repeat with n from (coinValue + 1) to (amount + 1) by coinValue\n set item n of o's counters to 1\n end repeat\n\n repeat with c from 2 to (count denominations)\n set coinValue to item c of denominations\n repeat with n from (coinValue + 1) to (amount + 1)\n set item n of o's counters to (item n of o's counters) + (item (n - coinValue) of o's counters)\n end repeat\n end repeat\n\n return end of o's counters\nend countCoins\n\n-- Task calls:\nset c1 to countCoins(100, {25, 10, 5, 1})\nset c2 to countCoins(1000 * 100, {100, 50, 25, 10, 5, 1})\nreturn {c1, c2}\n", "language": "AppleScript" }, { "code": "{242, 13398445413854501}\n", "language": "AppleScript" }, { "code": "C=0:M=100:F=25:T=10:S=5:Q=INT(M/F):FORI=0TOQ:D=INT((M-I*F)/T):FORJ=0TOD:N=INT((M-J*T)/S):FORK=0TON:P=M-K*S:FORL=0TOPSTEPS:C=C+(L+K*S+J*T+I*F=M):NEXTL,K,J,I:?C;\n", "language": "Applesoft-BASIC" }, { "code": "changes: function [amount coins][\n\tways: map 0..amount+1 [x]-> 0\n\tways\\0: 1\n\n\tloop coins 'coin [\n\t\tloop coin..amount 'j ->\n\t\t\tset ways j (get ways j) + get ways j-coin\n\t]\n\n\tways\\[amount]\n]\n\nprint changes 100 [1 5 10 25]\nprint changes 100000 [1 5 10 25 50 100]\n", "language": "Arturo" }, { "code": "countChange(amount){\n\treturn cc(amount, 4)\n}\n\ncc(amount, kindsOfCoins){\n\tif ( amount == 0 )\n\t\treturn 1\n\tif ( amount < 0 ) || ( kindsOfCoins == 0 )\n\t\treturn 0\n\treturn cc(amount, kindsOfCoins-1)\n\t + cc(amount - firstDenomination(kindsOfCoins), kindsOfCoins)\n}\n\nfirstDenomination(kindsOfCoins){\n\treturn [1, 5, 10, 25][kindsOfCoins]\n}\nMsgBox % countChange(100)\n", "language": "AutoHotkey" }, { "code": "#!/usr/bin/awk -f\n\nBEGIN {\n print cc(100)\n exit\n}\n\nfunction cc(amount, coins, numPennies, numNickles, numQuarters, p, n, d, q, s, count) {\n numPennies = amount\n numNickles = int(amount / 5)\n numDimes = int(amount / 10)\n numQuarters = int(amount / 25)\n\n count = 0\n for (p = 0; p <= numPennies; p++) {\n for (n = 0; n <= numNickles; n++) {\n for (d = 0; d <= numDimes; d++) {\n for (q = 0; q <= numQuarters; q++) {\n s = p + n * 5 + d * 10 + q * 25;\n if (s == 100) count++;\n }\n }\n }\n }\n return count;\n}\n", "language": "AWK" }, { "code": "#!/usr/bin/awk -f\n\nBEGIN {\n COINSEP = \", \"\n coins = 1 COINSEP 5 COINSEP 10 COINSEP 25\n print cc(100, coins)\n exit\n}\n\nfunction cc(amt, coins) {\n if (length(coins) == 0) return 0\n if (amt < 0) return 0\n if (amt == 0) return 1\n return cc(amt, tail(coins)) + cc(amt - head(coins), coins)\n}\n\nfunction tail(coins, koins, s, c) {\n split(coins, koins, COINSEP)\n s = \"\"\n for (c = 2; c <= length(koins); c++) s = s (s == \"\" ? \"\" : COINSEP) koins[c]\n return s;\n}\n\nfunction head(coins, koins) {\n split(coins, koins, COINSEP)\n return koins[1]\n}\n", "language": "AWK" }, { "code": " DIM uscoins%(3)\n uscoins%() = 1, 5, 10, 25\n PRINT FNchange(100, uscoins%()) \" ways of making $1\"\n PRINT FNchange(1000, uscoins%()) \" ways of making $10\"\n\n DIM ukcoins%(7)\n ukcoins%() = 1, 2, 5, 10, 20, 50, 100, 200\n PRINT FNchange(100, ukcoins%()) \" ways of making £1\"\n PRINT FNchange(1000, ukcoins%()) \" ways of making £10\"\n END\n\n DEF FNchange(sum%, coins%())\n LOCAL C%, D%, I%, N%, P%, Q%, S%, table()\n C% = 0\n N% = DIM(coins%(),1) + 1\n FOR I% = 0 TO N% - 1\n D% = coins%(I%)\n IF D% <= sum% IF D% >= C% C% = D% + 1\n NEXT\n C% *= N%\n DIM table(C%-1)\n FOR I% = 0 TO N%-1 : table(I%) = 1 : NEXT\n\n P% = N%\n FOR S% = 1 TO sum%\n FOR I% = 0 TO N% - 1\n IF I% = 0 IF P% >= C% P% = 0\n IF coins%(I%) <= S% THEN\n Q% = P% - coins%(I%) * N%\n IF Q% >= 0 table(P%) = table(Q%) ELSE table(P%) = table(Q% + C%)\n ENDIF\n IF I% table(P%) += table(P% - 1)\n P% += 1\n NEXT\n NEXT\n = table(P%-1)\n", "language": "BBC-BASIC" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n// ad hoc 128 bit integer type; faster than using GMP because of low\n// overhead\ntypedef struct { uint64_t x[2]; } i128;\n\n// display in decimal\nvoid show(i128 v) {\n\tuint32_t x[4] = {v.x[0], v.x[0] >> 32, v.x[1], v.x[1] >> 32};\n\tint i, j = 0, len = 4;\n\tchar buf[100];\n\tdo {\n\t\tuint64_t c = 0;\n\t\tfor (i = len; i--; ) {\n\t\t\tc = (c << 32) + x[i];\n\t\t\tx[i] = c / 10, c %= 10;\n\t\t}\n\n\t\tbuf[j++] = c + '0';\n\t\tfor (len = 4; !x[len - 1]; len--);\n\t} while (len);\n\n\twhile (j--) putchar(buf[j]);\n\tputchar('\\n');\n}\n\ni128 count(int sum, int *coins)\n{\n\tint n, i, k;\n\tfor (n = 0; coins[n]; n++);\n\n\ti128 **v = malloc(sizeof(int*) * n);\n\tint *idx = malloc(sizeof(int) * n);\n\n\tfor (i = 0; i < n; i++) {\n\t\tidx[i] = coins[i];\n\t\t// each v[i] is a cyclic buffer\n\t\tv[i] = calloc(sizeof(i128), coins[i]);\n\t}\n\n\tv[0][coins[0] - 1] = (i128) {{1, 0}};\n\n\tfor (k = 0; k <= sum; k++) {\n\t\tfor (i = 0; i < n; i++)\n\t\t\tif (!idx[i]--) idx[i] = coins[i] - 1;\n\n\t\ti128 c = v[0][ idx[0] ];\n\n\t\tfor (i = 1; i < n; i++) {\n\t\t\ti128 *p = v[i] + idx[i];\n\n\t\t\t// 128 bit addition\n\t\t\tp->x[0] += c.x[0];\n\t\t\tp->x[1] += c.x[1];\n\t\t\tif (p->x[0] < c.x[0]) // carry\n\t\t\t\tp->x[1] ++;\n\t\t\tc = *p;\n\t\t}\n\t}\n\n\ti128 r = v[n - 1][idx[n-1]];\n\n\tfor (i = 0; i < n; i++) free(v[i]);\n\tfree(v);\n\tfree(idx);\n\n\treturn r;\n}\n\n// simple recursive method; slow\nint count2(int sum, int *coins)\n{\n\tif (!*coins || sum < 0) return 0;\n\tif (!sum) return 1;\n\treturn count2(sum - *coins, coins) + count2(sum, coins + 1);\n}\n\nint main(void)\n{\n\tint us_coins[] = { 100, 50, 25, 10, 5, 1, 0 };\n\tint eu_coins[] = { 200, 100, 50, 20, 10, 5, 2, 1, 0 };\n\n\tshow(count( 100, us_coins + 2));\n\tshow(count( 1000, us_coins));\n\n\tshow(count( 1000 * 100, us_coins));\n\tshow(count( 10000 * 100, us_coins));\n\tshow(count(100000 * 100, us_coins));\n\n\tputchar('\\n');\n\n\tshow(count( 1 * 100, eu_coins));\n\tshow(count( 1000 * 100, eu_coins));\n\tshow(count( 10000 * 100, eu_coins));\n\tshow(count(100000 * 100, eu_coins));\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "242\n13398445413854501\n1333983445341383545001\n133339833445334138335450001\n\n4563\n10056050940818192726001\n99341140660285639188927260001\n992198221207406412424859964272600001\n", "language": "C" }, { "code": "#include <iostream>\n#include <stack>\n#include <vector>\n\nstruct DataFrame {\n int sum;\n std::vector<int> coins;\n std::vector<int> avail_coins;\n};\n\nint main() {\n std::stack<DataFrame> s;\n s.push({ 100, {}, { 25, 10, 5, 1 } });\n int ways = 0;\n while (!s.empty()) {\n DataFrame top = s.top();\n s.pop();\n if (top.sum < 0) continue;\n if (top.sum == 0) {\n ++ways;\n continue;\n }\n if (top.avail_coins.empty()) continue;\n DataFrame d = top;\n d.sum -= top.avail_coins[0];\n d.coins.push_back(top.avail_coins[0]);\n s.push(d);\n d = top;\n d.avail_coins.erase(std::begin(d.avail_coins));\n s.push(d);\n }\n std::cout << ways << std::endl;\n return 0;\n}\n", "language": "C++" }, { "code": " // Adapted from http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/\n class Program\n {\n static long Count(int[] C, int m, int n)\n {\n var table = new long[n + 1];\n table[0] = 1;\n for (int i = 0; i < m; i++)\n for (int j = C[i]; j <= n; j++)\n table[j] += table[j - C[i]];\n return table[n];\n }\n static void Main(string[] args)\n {\n var C = new int[] { 1, 5, 10, 25 };\n int m = C.Length;\n int n = 100;\n Console.WriteLine(Count(C, m, n)); //242\n Console.ReadLine();\n }\n }\n", "language": "C-sharp" }, { "code": "(def denomination-kind [1 5 10 25])\n\n(defn- cc [amount denominations]\n (cond (= amount 0) 1\n (or (< amount 0) (empty? denominations)) 0\n :else (+ (cc amount (rest denominations))\n (cc (- amount (first denominations)) denominations))))\n\n(defn count-change\n \"Calculates the number of times you can give change with the given denominations.\"\n [amount denominations]\n (cc amount denominations))\n\n(count-change 15 denomination-kind) ; = 6\n", "language": "Clojure" }, { "code": " identification division.\n program-id. CountCoins.\n\n data division.\n working-storage section.\n 77 i pic 9(3).\n 77 j pic 9(3).\n 77 m pic 9(3) value 4.\n 77 n pic 9(3) value 100.\n 77 edited-value pic z(18).\n 01 coins-table value \"01051025\".\n 05 coin pic 9(2) occurs 4.\n 01 ways-table.\n 05 way pic 9(18) occurs 100.\n\n procedure division.\n main.\n perform calc-count\n move way(n) to edited-value\n display function trim(edited-value)\n stop run\n .\n calc-count.\n initialize ways-table\n move 1 to way(1)\n perform varying i from 1 by 1 until i > m\n perform varying j from coin(i) by 1 until j > n\n add way(j - coin(i)) to way(j)\n end-perform\n end-perform\n .\n", "language": "COBOL" }, { "code": "changes = (amount, coins) ->\n ways = [1].concat [0] * amount\n for coin of coins\n for j from coin to amount\n ways[j] += ways[j - coin]\n ways[amount]\n\nconsole.log changes 100, [1 5 10 25]\n", "language": "Coco" }, { "code": "5 m=100:rem money = $1.00 or 100 pennies.\n10 print chr$(147);chr$(14);\"This program will calculate the number\"\n11 print \"of combinations of 'change' that can be\"\n12 print \"given for a $1 bill.\"\n13 print:print \"The coin values are:\"\n14 print \"0.01 = Penny\":print \"0.05 = Nickle\"\n15 print \"0.10 = Dime\":print \"0.25 = Quarter\"\n16 print\n20 print \"Would you like to see each combination?\"\n25 get k$:yn=(k$=\"y\"):if k$=\"\" then 25\n100 p=m:ti$=\"000000\"\n130 q=int(m/25)\n140 count=0:ps=1\n147 if yn then print \"Count P N D Q\"\n150 for qc=0 to q:d=int((m-qc*25)/10)\n160 for dc=0 to d:n=int((m-dc*10)/5)\n170 for nc=0 to n:p=m-nc*5\n180 for pc=0 to p step 5\n190 s=pc+nc*5+dc*10+qc*25\n200 if s=m then count=count+1:if yn then gosub 1000\n210 next:next:next:next\n245 en$=ti$\n250 print:print count;\"different combinations found in\"\n260 print tab(len(str$(count))+1);\n265 print left$(en$,2);\":\";mid$(en$,3,2);\":\";right$(en$,2);\".\"\n270 end\n1000 print count;tab(6);pc;tab(11);nc;tab(16);dc;tab(21);qc:return\n", "language": "Commodore-BASIC" }, { "code": "145 if not yn then poke 53265,peek(53265) and 239\n245 en$=ti$:if not yn then poke 53265,peek(53265) or 16\n", "language": "Commodore-BASIC" }, { "code": "145 if not yn then fast\n245 en$=ti$:if not yn then slow\n", "language": "Commodore-BASIC" }, { "code": "(defun count-change (amount coins\n &optional\n (length (1- (length coins)))\n (cache (make-array (list (1+ amount) (length coins))\n :initial-element nil)))\n (cond ((< length 0) 0)\n ((< amount 0) 0)\n ((= amount 0) 1)\n (t (or (aref cache amount length)\n (setf (aref cache amount length)\n (+ (count-change (- amount (first coins)) coins length cache)\n (count-change amount (rest coins) (1- length) cache)))))))\n\n; (compile 'count-change) ; for CLISP\n\n(print (count-change 100 '(25 10 5 1)))\t\t ; = 242\n(print (count-change 100000 '(100 50 25 10 5 1))) ; = 13398445413854501\n(terpri)\n", "language": "Common-Lisp" }, { "code": "(defun count-change (amount coins &aux (ways (make-array (1+ amount) :initial-element 0)))\n (setf (aref ways 0) 1)\n (loop for coin in coins do\n (loop for j from coin upto amount\n do (incf (aref ways j) (aref ways (- j coin)))))\n (aref ways amount))\n", "language": "Common-Lisp" }, { "code": "import std.stdio, std.bigint;\n\nauto changes(int amount, int[] coins) {\n auto ways = new BigInt[amount + 1];\n ways[0] = 1;\n foreach (coin; coins)\n foreach (j; coin .. amount + 1)\n ways[j] += ways[j - coin];\n return ways[$ - 1];\n}\n\nvoid main() {\n changes( 1_00, [25, 10, 5, 1]).writeln;\n changes(1000_00, [100, 50, 25, 10, 5, 1]).writeln;\n}\n", "language": "D" }, { "code": "import std.stdio, core.checkedint;\n\nauto changes(int amount, int[] coins, ref bool overflow) {\n auto ways = new ulong[amount + 1];\n ways[0] = 1;\n foreach (coin; coins)\n foreach (j; coin .. amount + 1)\n ways[j] = ways[j].addu(ways[j - coin], overflow);\n return ways[amount];\n}\n\nvoid main() {\n bool overflow = false;\n changes( 1_00, [25, 10, 5, 1], overflow).writeln;\n if (overflow)\n \"Overflow\".puts;\n overflow = false;\n changes( 1000_00, [100, 50, 25, 10, 5, 1], overflow).writeln;\n if (overflow)\n \"Overflow\".puts;\n}\n", "language": "D" }, { "code": "import std.stdio, std.bigint;\n\nBigInt countChanges(in int amount, in int[] coins) pure /*nothrow*/ {\n immutable n = coins.length;\n int cycle;\n foreach (immutable c; coins)\n if (c <= amount && c >= cycle)\n cycle = c + 1;\n cycle *= n;\n auto table = new BigInt[cycle];\n table[0 .. n] = 1.BigInt;\n\n int pos = n;\n foreach (immutable s; 1 .. amount + 1) {\n foreach (immutable i; 0 .. n) {\n if (i == 0 && pos >= cycle)\n pos = 0;\n if (coins[i] <= s) {\n immutable int q = pos - (coins[i] * n);\n table[pos] = (q >= 0) ? table[q] : table[q + cycle];\n }\n if (i)\n table[pos] += table[pos - 1];\n pos++;\n }\n }\n\n return table[pos - 1];\n}\n\nvoid main() {\n immutable usCoins = [100, 50, 25, 10, 5, 1];\n immutable euCoins = [200, 100, 50, 20, 10, 5, 2, 1];\n\n foreach (immutable coins; [usCoins, euCoins]) {\n countChanges( 1_00, coins[2 .. $]).writeln;\n countChanges( 1000_00, coins).writeln;\n countChanges( 10000_00, coins).writeln;\n countChanges(100000_00, coins).writeln;\n writeln;\n }\n}\n", "language": "D" }, { "code": "import std.stdio, std.bigint, std.algorithm, std.conv, std.functional;\n\nstruct Ucent { /// Simplified 128-bit integer (like ucent).\n ulong hi, lo;\n static immutable one = Ucent(0, 1);\n\n void opOpAssign(string op=\"+\")(in ref Ucent y) pure nothrow @nogc @safe {\n this.hi += y.hi;\n if (this.lo >= ~y.lo)\n this.hi++;\n this.lo += y.lo;\n }\n\n string toString() const /*pure nothrow @safe*/ {\n return text((this.hi.BigInt << 64) + this.lo);\n }\n}\n\nUcent countChanges(in int amount, in int[] coins) pure nothrow {\n immutable n = coins.length;\n\n // Points to a cyclic buffer of length coins[i]\n auto p = new Ucent*[n];\n auto q = new Ucent*[n]; // iterates it.\n auto buf = new Ucent[coins.sum];\n\n p[0] = buf.ptr;\n foreach (immutable i; 0 .. n) {\n if (i)\n p[i] = coins[i - 1] + p[i - 1];\n *p[i] = Ucent.one;\n q[i] = p[i];\n }\n\n Ucent prev;\n foreach (immutable j; 1 .. amount + 1)\n foreach (immutable i; 0 .. n) {\n q[i]--;\n if (q[i] < p[i])\n q[i] = p[i] + coins[i] - 1;\n if (i)\n *q[i] += prev;\n prev = *q[i];\n }\n\n return prev;\n}\n\nvoid main() {\n immutable usCoins = [100, 50, 25, 10, 5, 1];\n immutable euCoins = [200, 100, 50, 20, 10, 5, 2, 1];\n\n foreach (immutable coins; [usCoins, euCoins]) {\n countChanges( 1_00, coins[2 .. $]).writeln;\n countChanges( 1000_00, coins).writeln;\n countChanges( 10000_00, coins).writeln;\n countChanges(100000_00, coins).writeln;\n writeln;\n }\n}\n", "language": "D" }, { "code": "import std.stdio, std.conv, std.string, std.algorithm, std.range;\n\nvoid printChange(in uint tot, in uint[] coins)\nin {\n assert(coins.isSorted);\n} body {\n auto freqs = new uint[coins.length];\n\n void inner(in uint curTot, in size_t start) {\n if (curTot == tot)\n return writefln(\"%-(%s %)\",\n zip(coins, freqs)\n .filter!(cf => cf[1] != 0)\n .map!(cf => format(\"%u:%u\", cf[])));\n\n foreach (immutable i; start .. coins.length) {\n immutable ci = coins[i];\n for (auto v = (freqs[i] + 1) * ci; v <= tot; v += ci)\n if (curTot + v <= tot) {\n freqs[i] += v / ci;\n inner(curTot + v, i + 1);\n freqs[i] -= v / ci;\n }\n }\n }\n\n inner(0, 0);\n}\n\nvoid main() {\n printChange(1_00, [1, 5, 10, 25]);\n}\n", "language": "D" }, { "code": "var cache = new Map();\n\nmain() {\n var stopwatch = new Stopwatch()..start();\n\n // use the brute-force recursion for the small problem\n int amount = 100;\n list coinTypes = [25,10,5,1];\n print (coins(amount,coinTypes).toString() + \" ways for $amount using $coinTypes coins.\");\n\n // use the cache version for the big problem\n amount = 100000;\n coinTypes = [100,50,25,10,5,1];\n print (cachedCoins(amount,coinTypes).toString() + \" ways for $amount using $coinTypes coins.\");\n\n stopwatch.stop();\n print (\"... completed in \" + (stopwatch.elapsedMilliseconds/1000).toString() + \" seconds\");\n}\n\n\ncoins(int amount, list coinTypes) {\n int count = 0;\n\n if(coinTypes.length == 1) return (1); // just pennies available, so only one way to make change\n\n for(int i=0; i<=(amount/coinTypes[0]).toInt(); i++){ // brute force recursion\n count += coins(amount-(i*coinTypes[0]),coinTypes.sublist(1)); // sublist(1) is like lisp's '(rest ...)'\n }\n\n // uncomment if you want to see intermediate steps\n //print(\"there are \" + count.toString() +\" ways to count change for ${amount.toString()} using ${coinTypes} coins.\");\n return(count);\n }\n\n\n cachedCoins(int amount, list coinTypes) {\n int count = 0;\n\n // this is more efficient, looks at last two coins. but not fast enough for the optional exercise.\n if(coinTypes.length == 2) return ((amount/coinTypes[0]).toInt() + 1);\n\n var key = \"$amount.$coinTypes\"; // lookes like \"100.[25,10,5,1]\"\n var cacheValue = cache[key]; // check whether we have seen this before\n\n if(cacheValue != null) return(cacheValue);\n\n count = 0;\n // same recursion as simple method, but caches all subqueries too\n for(int i=0; i<=(amount/coinTypes[0]).toInt(); i++){\n count += cachedCoins(amount-(i*coinTypes[0]),coinTypes.sublist(1)); // sublist(1) is like lisp's '(rest ...)'\n }\n\n cache[key] = count; // add this to the cache\n return(count);\n }\n", "language": "Dart" }, { "code": "/// Provides the same result and performance as the Dart 1 version\n/// but using the Dart 2 specifications.\nMap<String, int> cache = {};\n\nvoid main() {\n Stopwatch stopwatch = Stopwatch()..start();\n\n /// Use the brute-force recursion for the small problem\n int amount = 100;\n List<int> coinTypes = [25,10,5,1];\n print (\"${coins(amount,coinTypes)} ways for $amount using $coinTypes coins.\");\n\n /// Use the cache version for the big problem\n amount = 100000;\n coinTypes = [100,50,25,10,5,1];\n print (\"${cachedCoins(amount,coinTypes)} ways for $amount using $coinTypes coins.\");\n\n stopwatch.stop();\n print (\"... completed in ${stopwatch.elapsedMilliseconds/1000} seconds\");\n\n}\n\nint cachedCoins(int amount, List<int> coinTypes) {\n int count = 0;\n\n /// This is more efficient, looks at last two coins.\n /// But not fast enough for the optional exercise.\n if(coinTypes.length == 2) return (amount ~/ coinTypes[0] + 1);\n\n /// Looks like \"100.[25,10,5,1]\"\n String key = \"$amount.$coinTypes\";\n /// Check whether we have seen this before\n var cacheValue = cache[key];\n\n if(cacheValue != null) return(cacheValue);\n\n count = 0;\n /// Same recursion as simple method, but caches all subqueries too\n for(int i=0; i<=amount ~/ coinTypes[0]; i++){\n count += cachedCoins(amount-(i*coinTypes[0]),coinTypes.sublist(1)); // sublist(1) is like lisp's '(rest ...)'\n }\n\n /// add this to the cache\n cache[key] = count;\n return count;\n}\n\nint coins(int amount, List<int> coinTypes) {\n int count = 0;\n\n /// Just pennies available, so only one way to make change\n if(coinTypes.length == 1) return (1);\n\n /// Brute force recursion\n for(int i=0; i<=amount ~/ coinTypes[0]; i++){\n /// sublist(1) is like lisp's '(rest ...)'\n count += coins(amount - (i*coinTypes[0]),coinTypes.sublist(1));\n }\n\n /// Uncomment if you want to see intermediate steps\n /// print(\"there are \" + count.toString() +\" ways to count change for ${amount.toString()} using ${coinTypes} coins.\");\n return count;\n}\n", "language": "Dart" }, { "code": "program Count_the_coins;\n\n{$APPTYPE CONSOLE}\n\nfunction Count(c: array of Integer; m, n: Integer): Integer;\nvar\n table: array of Integer;\n i, j: Integer;\nbegin\n SetLength(table, n + 1);\n table[0] := 1;\n for i := 0 to m - 1 do\n for j := c[i] to n do\n table[j] := table[j] + table[j - c[i]];\n Exit(table[n]);\nend;\n\nvar\n c: array of Integer;\n m, n: Integer;\n\nbegin\n c := [1, 5, 10, 25];\n\n m := Length(c);\n n := 100;\n Writeln(Count(c, m, n)); //242\n Readln;\nend.\n", "language": "Delphi" }, { "code": "proc main() void:\n [4]byte coins = (1, 5, 10, 25);\n [101]byte tab;\n word m, n;\n\n for n from 1 upto 100 do tab[n] := 0 od;\n tab[0] := 1;\n\n for m from 0 upto 3 do\n for n from coins[m] upto 100 do\n tab[n] := tab[n] + tab[n - coins[m]]\n od\n od;\n\n writeln(tab[100])\ncorp\n", "language": "Draco" }, { "code": "func countCoins(coins, n) {\n var xs = Array.Empty(n + 1, 0)\n xs[0] = 1\n for c in coins {\n var cj = c\n while cj <= n {\n xs[cj] += xs[cj - c]\n cj += 1\n }\n }\n return xs[n]\n}\n\nvar coins = [1, 5, 10, 25]\nprint(countCoins(coins, 100))\n", "language": "Dyalect" }, { "code": "len cache[] 100000 * 7 + 6\nval[] = [ 1 5 10 25 50 100 ]\nfunc count sum kind .\n if sum = 0\n return 1\n .\n if sum < 0 or kind = 0\n return 0\n .\n chind = sum * 7 + kind\n if cache[chind] > 0\n return cache[chind]\n .\n r2 = count (sum - val[kind]) kind\n r1 = count sum (kind - 1)\n r = r1 + r2\n cache[chind] = r\n return r\n.\nprint count 100 4\nprint count 10000 6\nprint count 100000 6\n# this is not exact, since numbers\n# are doubles and r > 2^53\n", "language": "EasyLang" }, { "code": "(lib 'compile) ;; for (compile)\n(lib 'bigint) ;; integer results > 32 bits\n(lib 'hash) ;; hash table\n\n;; h-table\n(define Hcoins (make-hash))\n\n;; the function to memoize\n(define (sumways cents coins)\n\t(+ (ways cents (cdr coins)) (ways (- cents (car coins)) coins)))\n\t\n;; accelerator : ways (cents, coins) = ways ((cents - cents % 5) , coins)\n(define (ways cents coins)\n (cond ((null? coins) 0)\n ((negative? cents) 0)\n ((zero? cents) 1)\n ((eq? coins c-1) 1) ;; if coins = (1) --> 1\n (else (hash-ref! Hcoins (list (- cents (modulo cents 5)) coins) sumways))))\n\n(compile 'ways) ;; speed-up things\n", "language": "EchoLisp" }, { "code": "(define change '(25 10 5 1))\n(define c-1 (list-tail change -1)) ;; pointer to (1)\n(ways 100 change)\n → 242\n\n(define change '(100 50 25 10 5 1))\n(define c-1 (list-tail change -1))\n(for ((i (in-range 0 200001 20000)))\n (writeln i (time (ways i change)) (hash-count Hcoins)))\n\n\n;; iterate cents = 20000, 40000, ..\n;; cents ((time (msec) number-of-ways) number-of-entries-in-h-table\n\n20000 (350 4371565890901) 9398\n40000 (245 138204514221801) 18798\n60000 (230 1045248220992701) 28198\n80000 (255 4395748062203601) 37598\n100000 (234 13398445413854501) 46998\n120000 (230 33312577651945401) 56398\n140000 (292 71959878152476301) 65798\n160000 (736 140236576291447201) 75198\n180000 (237 252625397444858101) 84598\n200000 (240 427707562988709001) 93998\n\n;; One can see that the time is linear, and the h-table size reasonably small\n\nchange\n → (100 50 25 10 5 1)\n(ways 100000 change)\n → 13398445413854501\n", "language": "EchoLisp" }, { "code": "[\"Count the coins\" problem for Rosetta Code.]\n[EDSAC program, Initial Orders 2.]\n\n T51K P56F [G parameter: print subroutine]\n T54K P94F [C parameter: coins subroutine]\n T47K P200F [M parameter: main routine]\n\n[========================== M parameter ===============================]\n E25K TM GK\n[Parameter block for US coins. For convenience, all numbers\n are in the address field, e.g. 25 cents is P25F not P12D.]\n [0] UF SF [2-letter ID]\n P100F [amount to be made with coins]\n P4F [number of coin values]\n P1F P5F P10F P25F [list of coin values]\n [8] P@ [address of US parameter block]\n[Parameter block for UK coins]\n [9] UF KF\n P100F\n P7F\n P1F P2F P5F P10F P20F P50F P100F\n [20] P9@ [address of UK parameter block]\n[Enter with acc = 0]\n [21] A8@ [load address of parameter block for US coins]\n T4F [pass to subroutine in 4F]\n [23] A23@ [call subroutine to calculate and print result]\n G13C\n A20@ [same for UK coins]\n T4F\n [27] A27@\n G13C\n ZF [halt program]\n\n[========================== C parameter ===============================]\n[Subroutine to calculate and print the result for the given amount and\n set of coins. Address of parameter block (see above) is passed in 4F.]\n\n E25K TC GK\n [0] SF [S order for start of coin list]\n [1] A1023F [start table at top of memory and work downwarda]\n [2] PF [S order for exclusive end of coin list]\n [3] P2F [to increment address by 2]\n [4] OF [(1) add to address to make O order\n (2) add to A order to make T order with same address]\n [5] SF [add to address to make S order]\n [6] K4095F [add to S order to make A order, dec address]\n [7] K2048F [set teleprinter to letters]\n [8] #F [set teleprinter to figures]\n [9] !F [space character]\n [10] @F [carriage return]\n [11] &F [line feed]\n [12] K4096F [teleprinter null]\n[Subroutine entry. In this EDSAC program, the table used\n in the algorithm grows downward from the top of memory.]\n [13] A3F [plant jump back to caller, as usual]\n T89@\n A4F [load address of parameter block]\n A3@ [skip 2-letter ID]\n A5@ [make S order for amount]\n U27@ [plant in code]\n A3@ [make S order for first coin value]\n U@ [store it]\n A6@ [make A order for number of coins]\n T38@ [plant in code]\n A2F [load 1 (in address field)]\n [24] T1023F [store at start of table]\n[Set all other table entries to 0]\n A24@\n T32@\n [27] SF [acc := -amount]\n [28] TF [set negative count in 0F]\n A32@ [decrement address in manufactured order]\n S2F\n T32@\n [32] TF [manufactured: set table entry to 0]\n AF [update negative count]\n A2F\n G28@ [loop until count = 0]\n[Here acc = 0. Manufactured order (4 lines up) is T order\n for inclusive end of table; this is used again below.]\n A@ [load S order for first coin value]\n U43@ [plant in code]\n [38] AF [make S order for exclusive end of coin list]\n T2@ [store for comparison]\n[Start of outer loop, round coin values]\n [40] TF [clear acc]\n A1@ [load A order for start of table]\n U48@ [plant in code]\n [43] SF [manufactured order: subtract coin value]\n[Start of inner loop, round table entries]\n [44] U47@ [plant A order in code]\n A4@ [make T order for same address]\n T49@ [plant in code]\n[The next 3 orders are manufactured at run time]\n [47] AF [load table entry]\n [48] AF [add earlier table entry]\n [49] TF [update table entry]\n A32@ [load T order for inclusive end of table]\n S49@ [reached end of table?]\n E60@ [if yes, jump out of inner loop]\n TF [clear acc]\n A48@ [update the 3 manufactured instructions]\n S2F\n T48@\n A47@\n S2F\n G44@ [always loops back, since A < 0]\n[End of inner loop]\n [60] TF [clear acc]\n A43@ [update S order for coin value]\n A2F\n U43@\n S2@ [reached exclusive end?]\n G40@ [if no, loop back]\n[End of outer loop]\n[Here with acc = 0 and result at end of table]\n[Value is in address field, so shift 1 right for printing]\n A32@ [load T order for end of tab;e]\n S4@ [make A order for same address]\n T79@ [plant in code]\n A4F [load address of parameter block]\n A4@ [make O order for 1st char of ID]\n U75@ [plant in code]\n A2F [same for 2nd char]\n T76@\n O7@ [set teleprinter to letters]\n [75] OF [print ID, followed by space]\n [76] OF O9@\n O8@ [set teleprinter to figures]\n [79] AF [maunfactured order to load result]\n RD [shift 1 right for printing]\n TF [pass to print routine]\n A9@ [replace leading 0's with space]\n T1F\n [84] A84@ [call print routine]\n GG\n O10@ O11@ [print CR, LF]\n O12@ [print null to flush teleprinter buffer]\n [89] ZF [replaced by jump back to caller]\n\n[============================= G parameter ===============================]\n E25K TG GK\n[Subroutine to print non-negative 17-bit integer. Always prints 5 chars.\n Caller specifies character for leading 0 (typically 0, space or null).\n Parameters: 0F = integer to be printed (not preserved)\n 1F = character for leading zero (preserved)\n Workspace: 4F..7F, 38 locations]\n A3FT34@A1FT7FS35@T6FT4#FAFT4FH36@V4FRDA4#FR1024FH37@E23@O7FA2F\n T6FT5FV4#FYFL8FT4#FA5FL1024FUFA6FG16@OFTFT7FA6FG17@ZFP4FZ219DTF\n\n[========================== M parameter again ===============================]\n E25K TM GK\n E21Z [define entry point]\n PF [enter with acc = 0]\n", "language": "EDSAC-order-code" }, { "code": "defmodule Coins do\n def find(coins,lim) do\n vals = Map.new(0..lim,&{&1,0}) |> Map.put(0,1)\n count(coins,lim,vals)\n |> Map.values\n |> Enum.max\n |> IO.inspect\n end\n\n defp count([],_,vals), do: vals\n defp count([coin|coins],lim,vals) do\n count(coins,lim,ways(coin,coin,lim,vals))\n end\n\n defp ways(num,_coin,lim,vals) when num > lim, do: vals\n defp ways(num, coin,lim,vals) do\n ways(num+1,coin,lim,ad(coin,num,vals))\n end\n\n defp ad(a,b,c), do: Map.put(c,b,c[b]+c[b-a])\nend\n\nCoins.find([1,5,10,25],100)\nCoins.find([1,5,10,25,50,100],100_000)\n", "language": "Elixir" }, { "code": "-module(coins).\n-compile(export_all).\n\ncount(Amount, Coins) ->\n {N,_C} = count(Amount, Coins, dict:new()),\n N.\n\ncount(0,_,Cache) ->\n {1,Cache};\ncount(N,_,Cache) when N < 0 ->\n {0,Cache};\ncount(_N,[],Cache) ->\n {0,Cache};\ncount(N,[C|Cs]=Coins,Cache) ->\n case dict:is_key({N,length(Coins)},Cache) of\n true ->\n {dict:fetch({N,length(Coins)},Cache), Cache};\n false ->\n {N1,C1} = count(N-C,Coins,Cache),\n {N2,C2} = count(N,Cs,C1),\n {N1+N2,dict:store({N,length(Coins)},N1+N2,C2)}\n end.\n\nprint(Amount, Coins) ->\n io:format(\"~b ways to make change for ~b cents with ~p coins~n\",[count(Amount,Coins),Amount,Coins]).\n\ntest() ->\n A1 = 100, C1 = [25,10,5,1],\n print(A1,C1),\n A2 = 100000, C2 = [100, 50, 25, 10, 5, 1],\n print(A2,C2).\n", "language": "Erlang" }, { "code": "let changes amount coins =\n let ways = Array.zeroCreate (amount + 1)\n ways.[0] <- 1L\n List.iter (fun coin ->\n for j = coin to amount do ways.[j] <- ways.[j] + ways.[j - coin]\n ) coins\n ways.[amount]\n\n[<EntryPoint>]\nlet main argv =\n printfn \"%d\" (changes 100 [25; 10; 5; 1]);\n printfn \"%d\" (changes 100000 [100; 50; 25; 10; 5; 1]);\n 0\n", "language": "F-Sharp" }, { "code": "USING: combinators kernel locals math math.ranges sequences sets sorting ;\nIN: rosetta.coins\n\n<PRIVATE\n! recursive-count uses memoization and local variables.\n! coins must be a sequence.\nMEMO:: recursive-count ( cents coins -- ways )\n coins length :> types\n {\n ! End condition: 1 way to make 0 cents.\n { [ cents zero? ] [ 1 ] }\n ! End condition: 0 ways to make money without any coins.\n { [ types zero? ] [ 0 ] }\n ! Optimization: At most 1 way to use 1 type of coin.\n { [ types 1 number= ] [\n cents coins first mod zero? [ 1 ] [ 0 ] if\n ] }\n ! Find all ways to use the first type of coin.\n [\n ! f = first type, r = other types of coins.\n coins unclip-slice :> f :> r\n ! Loop for 0, f, 2*f, 3*f, ..., cents.\n 0 cents f <range> [\n ! Recursively count how many ways to make remaining cents\n ! with other types of coins.\n cents swap - r recursive-count\n ] [ + ] map-reduce ! Sum the counts.\n ]\n } cond ;\nPRIVATE>\n\n! How many ways can we make the given amount of cents\n! with the given set of coins?\n: make-change ( cents coins -- ways )\n members [ ] inv-sort-with ! Sort coins in descending order.\n recursive-count ;\n", "language": "Factor" }, { "code": "IN: scratchpad [ 100000 { 1 5 10 25 50 100 } make-change . ] time\n13398445413854501\nRunning time: 0.020869274 seconds\n", "language": "Factor" }, { "code": "USING: arrays locals math math.ranges sequences sets sorting ;\nIN: rosetta-code.count-the-coins\n\n<PRIVATE\n\n:: (make-change) ( cents coins -- ways )\n cents 1 + 0 <array> :> ways\n 1 ways set-first\n coins [| coin |\n coin cents [a,b] [| j |\n j coin - ways nth j ways [ + ] change-nth\n ] each\n ] each ways last ;\n\nPRIVATE>\n\n! How many ways can we make the given amount of cents\n! with the given set of coins?\n: make-change ( cents coins -- ways )\n members [ ] inv-sort-with (make-change) ;\n", "language": "Factor" }, { "code": "USE: math.ranges\n\n:: exchange-count ( seq val -- cnt )\n val 1 + 0 <array> :> tab\n 0 :> old!\n 1 0 tab set-nth\n seq length iota [\n seq nth old!\n old val [a,b] [| j |\n j old - tab nth\n j tab nth +\n j tab set-nth\n ] each\n ] each\n val tab nth\n;\n\n[ { 1 5 10 25 50 100 } 100000 exchange-count . ] time\n13398445413854501\nRunning time: 0.029163549 seconds\n", "language": "Factor" }, { "code": "01.10 S C(1)=1;S C(2)=5;S C(3)=10;S C(4)=25\n01.20 F N=1,100;S T(N)=0\n01.30 S T(0)=1\n01.40 F M=1,4;F N=C(M),100;S T(N)=T(N)+T(N-C(M))\n01.50 T %3,T(100),!\n01.60 Q\n", "language": "FOCAL" }, { "code": "\\ counting change (SICP section 1.2.2)\n\n: table create does> swap cells + @ ;\ntable coin-value 0 , 1 , 5 , 10 , 25 , 50 ,\n\n: count-change ( total coin -- n )\n over 0= if\n 2drop 1\n else over 0< over 0= or if\n 2drop 0\n else\n 2dup coin-value - over recurse\n >r 1- recurse r> +\n then then ;\n\n100 5 count-change .\n", "language": "Forth" }, { "code": "' version 09-10-2016\n' compile with: fbc -s console\n\n\nFunction count(S() As UInteger, n As UInteger) As ULongInt\n\n Dim As Integer i, j\n ' calculate m from array S()\n Dim As UInteger m = UBound(S) - LBound(S) +1\n Dim As ULongInt x, y\n\n '' We need n+1 rows as the table is consturcted in bottom up manner using\n '' the base case 0 value case (n = 0)\n Dim As ULongInt table(n +1, m)\n\n '' Fill the enteries for 0 value case (n = 0)\n For i = 0 To m -1\n table(0, i) = 1\n Next\n\n '' Fill rest of the table enteries in bottom up manner\n For i = 1 To n\n For j = 0 To m -1\n '' Count of solutions including S[j]\n x = IIf (i >= S(j), table(i - S(j), j), 0)\n '' Count of solutions excluding S[j]\n y = IIf (j >= 1, table(i, j -1), 0)\n ''total count\n table(i, j) = x + y\n Next\n Next\n\n Return table(n, m -1)\n\nEnd Function\n\n' ------=< MAIN >=------\n\nDim As UInteger n\nDim As UInteger value()\n\nReDim value(3)\nvalue(0) = 1 : value(1) = 5 : value(2) = 10 : value(3) = 25\n\nn = 100\nprint\nPrint \" There are \"; count(value(), n); \" ways to make change for $\";n/100;\" with 4 coins\"\nPrint\n\nn = 100000\nPrint \" There are \"; count(value(), n); \" ways to make change for $\";n/100;\" with 4 coins\"\nPrint\n\nReDim value(5)\nvalue(0) = 1 : value(1) = 5 : value(2) = 10\nvalue(3) = 25 : value(4) = 50 : value(5) = 100\n\nn = 100000\nPrint \" There are \"; count(value(), n); \" ways to make change for $\";n/100;\" with 6 coins\"\nPrint\n\n' empty keyboard buffer\nWhile Inkey <> \"\" : Wend\nPrint : Print \"hit any key to end program\"\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "include \"NSLog.incl\"\n\nvoid local fn Doit\n long penny, nickel, dime, quarter, count = 0\n\n NSLogSetTabInterval(30)\n\n for penny = 0 to 100\n for nickel = 0 to 20\n for dime = 0 to 10\n for quarter = 0 to 4\n if penny + nickel * 5 + dime * 10 + quarter * 25 == 100\n NSLog(@\"%ld pennies\\t%ld nickels\\t%ld dimes\\t%ld quarters\",penny,nickel,dime,quarter)\n count++\n end if\n next quarter\n next dime\n next nickel\n next penny\n\n NSLog(@\"\\n%ld ways to make a dollar\",count)\nend fn\n\nfn DoIt\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc main() {\n amount := 100\n fmt.Println(\"amount, ways to make change:\", amount, countChange(amount))\n}\n\nfunc countChange(amount int) int64 {\n return cc(amount, 4)\n}\n\nfunc cc(amount, kindsOfCoins int) int64 {\n switch {\n case amount == 0:\n return 1\n case amount < 0 || kindsOfCoins == 0:\n return 0\n }\n return cc(amount, kindsOfCoins-1) +\n cc(amount - firstDenomination(kindsOfCoins), kindsOfCoins)\n}\n\nfunc firstDenomination(kindsOfCoins int) int {\n switch kindsOfCoins {\n case 1:\n return 1\n case 2:\n return 5\n case 3:\n return 10\n case 4:\n return 25\n }\n panic(kindsOfCoins)\n}\n", "language": "Go" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc main() {\n amount := 1000 * 100\n fmt.Println(\"amount, ways to make change:\", amount, countChange(amount))\n}\n\nfunc countChange(amount int) int64 {\n ways := make([]int64, amount+1)\n ways[0] = 1\n for _, coin := range []int{100, 50, 25, 10, 5, 1} {\n for j := coin; j <= amount; j++ {\n ways[j] += ways[j-coin]\n }\n }\n return ways[amount]\n}\n", "language": "Go" }, { "code": "def ccR\nccR = { BigInteger tot, List<BigInteger> coins ->\n BigInteger n = coins.size()\n switch ([tot:tot, coins:coins]) {\n case { it.tot == 0 } :\n return 1g\n case { it.tot < 0 || coins == [] } :\n return 0g\n default:\n return ccR(tot, coins[1..<n]) +\n ccR(tot - coins[0], coins)\n }\n}\n", "language": "Groovy" }, { "code": "def ccI = { BigInteger tot, List<BigInteger> coins ->\n List<BigInteger> ways = [0g] * (tot+1)\n ways[0] = 1g\n coins.each { BigInteger coin ->\n (coin..tot).each { j ->\n ways[j] += ways[j-coin]\n }\n }\n ways[tot]\n}\n", "language": "Groovy" }, { "code": "println '\\nBase:'\n[iterative: ccI, recursive: ccR].each { label, cc ->\n print \"${label} \"\n def start = System.currentTimeMillis()\n def ways = cc(100g, [25g, 10g, 5g, 1g])\n def elapsed = System.currentTimeMillis() - start\n println (\"answer: ${ways} elapsed: ${elapsed}ms\")\n}\n\nprint '\\nExtra Credit:\\niterative '\ndef start = System.currentTimeMillis()\ndef ways = ccI(1000g * 100, [100g, 50g, 25g, 10g, 5g, 1g])\ndef elapsed = System.currentTimeMillis() - start\nprintln (\"answer: ${ways} elapsed: ${elapsed}ms\")\n", "language": "Groovy" }, { "code": "count :: (Integral t, Integral a) => t -> [t] -> a\ncount 0 _ = 1\ncount _ [] = 0\ncount x (c:coins) =\n sum\n [ count (x - (n * c)) coins\n | n <- [0 .. (quot x c)] ]\n\nmain :: IO ()\nmain = print (count 100 [1, 5, 10, 25])\n", "language": "Haskell" }, { "code": "count :: Integral a => [Int] -> [a]\ncount = foldr addCoin (1 : repeat 0)\n where\n addCoin c oldlist = newlist\n where\n newlist = take c oldlist ++ zipWith (+) newlist (drop c oldlist)\n\nmain :: IO ()\nmain = do\n print (count [25, 10, 5, 1] !! 100)\n print (count [100, 50, 25, 10, 5, 1] !! 10000)\n", "language": "Haskell" }, { "code": "import Data.Function (fix)\n\ncount\n :: Integral a\n => [Int] -> [a]\ncount =\n foldr\n (\\x a ->\n let (l, r) = splitAt x a\n in fix ((<>) l . flip (zipWith (+)) r))\n (1 : repeat 0)\n\n---------------------------- TEST --------------------------\nmain :: IO ()\nmain =\n mapM_\n (print . uncurry ((!!) . count))\n [ ([25, 10, 5, 1], 100)\n , ([100, 50, 25, 10, 5, 1], 10000)\n , ([100, 50, 25, 10, 5, 1], 1000000)\n ]\n", "language": "Haskell" }, { "code": "procedure main()\n\n US_coins := [1, 5, 10, 25]\n US_allcoins := [1,5,10,25,50,100]\n EU_coins := [1, 2, 5, 10, 20, 50, 100, 200]\n CDN_coins := [1,5,10,25,100,200]\n CDN_allcoins := [1,5,10,25,50,100,200]\n\n every trans := ![ [15,US_coins],\n [100,US_coins],\n [1000*100,US_allcoins]\n ] do\n printf(\"There are %i ways to count change for %i using %s coins.\\n\",CountCoins!trans,trans[1],ShowList(trans[2]))\nend\n\nprocedure ShowList(L) # helper list to string\nevery (s := \"[ \") ||:= !L || \" \"\nreturn s || \"]\"\nend\n", "language": "Icon" }, { "code": "procedure CountCoins(amt,coins) # very slow, recurse by coin value\nlocal count\nstatic S\n\nif type(coins) == \"list\" then {\n S := sort(set(coins))\n if *S < 1 then runerr(205,coins)\n return CountCoins(amt)\n }\nelse {\n /coins := 1\n if value := S[coins] then {\n every (count := 0) +:= CountCoins(amt - (0 to amt by value), coins + 1)\n return count\n }\n else\n return (amt ~= 0) | 1\n }\nend\n", "language": "Icon" }, { "code": "# coin.icn\n# usage: coin value\nprocedure count(coinlist, value)\n\tif value = 0 then return 1\n\tif value < 0 then return 0\n\tif (*coinlist <= 0) & (value >= 1) then return 0\n\treturn count(coinlist[1:*coinlist], value) + count(coinlist, value - coinlist[*coinlist])\nend\n\n\nprocedure main(params)\n\tmoney := params[1]\n\tcoins := [1,5,10,25]\n\t\n\twrites(\"Value of \", money, \" can be changed by using a set of \")\n\tevery writes(coins[1 to *coins], \" \")\n\twrite(\" coins in \", count(coins, money), \" different ways.\")\nend\n", "language": "Icon" }, { "code": "100 PROGRAM \"Coins.bas\"\n110 LET MONEY=100\n120 LET COUNT=0\n125 PRINT \"Count Pennies Nickles Dimes Quaters\"\n130 FOR QC=0 TO INT(MONEY/25)\n150 FOR DC=0 TO INT((MONEY-QC*25)/10)\n170 FOR NC=0 TO INT((MONEY-DC*10)/5)\n190 FOR PC=0 TO MONEY-NC*5 STEP 5\n200 LET S=PC+NC*5+DC*10+QC*25\n210 IF S=MONEY THEN\n220 LET COUNT=COUNT+1\n230 PRINT COUNT,PC,NC,DC,QC\n240 END IF\n250 NEXT\n260 NEXT\n270 NEXT\n280 NEXT\n290 PRINT COUNT;\"different combinations found.\"\n", "language": "IS-BASIC" }, { "code": "merge=: ({:\"1 (+/@:({.\"1),{:@{:)/. ])@;\ncount=: {.@] <@,. {:@] - [ * [ i.@>:@<.@%~ {:@]\ninit=: (1 ,. ,.)^:(0=#@$)\nnsplits=: 0 { [: +/ [: (merge@:(count\"1) init)/ }.@/:~@~.@,\n", "language": "J" }, { "code": " 100 nsplits 1 5 10 25\n242\n", "language": "J" }, { "code": " 100000 nsplits 1 5 10 25 50 100\n13398445413854501\n", "language": "J" }, { "code": " init =: 4 : '(1+x)$1'\nlength1 =: 4 : '1=#y'\n f =: 4 : ',/ +/\\ (-x) ]\\ y'\n\n 1000 { f ` init @. length1 / 1000 500 200 100 50 20 10 5 2 , 1000 0\n327631322\n\nNB. this is a foldLeft once initialised the intermediate right arguments are arrays\n 1000 f 500 f 200 f 100 f 50 f 20 f 10 f 5 f 2 f (1000 init 0)\n", "language": "J" }, { "code": "import java.util.Arrays;\nimport java.math.BigInteger;\n\nclass CountTheCoins {\n private static BigInteger countChanges(int amount, int[] coins){\n final int n = coins.length;\n int cycle = 0;\n for (int c : coins)\n if (c <= amount && c >= cycle)\n cycle = c + 1;\n cycle *= n;\n BigInteger[] table = new BigInteger[cycle];\n Arrays.fill(table, 0, n, BigInteger.ONE);\n Arrays.fill(table, n, cycle, BigInteger.ZERO);\n\n int pos = n;\n for (int s = 1; s <= amount; s++) {\n for (int i = 0; i < n; i++) {\n if (i == 0 && pos >= cycle)\n pos = 0;\n if (coins[i] <= s) {\n final int q = pos - (coins[i] * n);\n table[pos] = (q >= 0) ? table[q] : table[q + cycle];\n }\n if (i != 0)\n table[pos] = table[pos].add(table[pos - 1]);\n pos++;\n }\n }\n\n return table[pos - 1];\n }\n\n public static void main(String[] args) {\n final int[][] coinsUsEu = {{100, 50, 25, 10, 5, 1},\n {200, 100, 50, 20, 10, 5, 2, 1}};\n\n for (int[] coins : coinsUsEu) {\n System.out.println(countChanges( 100,\n Arrays.copyOfRange(coins, 2, coins.length)));\n System.out.println(countChanges( 100000, coins));\n System.out.println(countChanges( 1000000, coins));\n System.out.println(countChanges(10000000, coins) + \"\\n\");\n }\n }\n}\n", "language": "Java" }, { "code": "function countcoins(t, o) {\n 'use strict';\n var targetsLength = t + 1;\n var operandsLength = o.length;\n t = [1];\n\n for (var a = 0; a < operandsLength; a++) {\n for (var b = 1; b < targetsLength; b++) {\n\n // initialise undefined target\n t[b] = t[b] ? t[b] : 0;\n\n // accumulate target + operand ways\n t[b] += (b < o[a]) ? 0 : t[b - o[a]];\n }\n }\n\n return t[targetsLength - 1];\n}\n", "language": "JavaScript" }, { "code": "countcoins(100, [1,5,10,25]);\n242\n", "language": "JavaScript" }, { "code": "function countcoins(t, o) {\n 'use strict';\n var operandsLength = o.length;\n var solutions = 0;\n\n function permutate(a, x) {\n\n // base case\n if (a === t) {\n solutions++;\n }\n\n // recursive case\n else if (a < t) {\n for (var i = 0; i < operandsLength; i++) {\n if (i >= x) {\n permutate(o[i] + a, i);\n }\n }\n }\n }\n\n permutate(0, 0);\n return solutions;\n}\n", "language": "JavaScript" }, { "code": "countcoins(100, [1,5,10,25]);\n242\n", "language": "JavaScript" }, { "code": "var amount = 100,\n coin = [1, 5, 10, 25]\nvar t = [1];\nfor (t[amount] = 0, a = 1; a < amount; a++) t[a] = 0 // initialise t[0..amount]=[1,0,...,0]\nfor (var i = 0, e = coin.length; i < e; i++)\n for (var ci = coin[i], a = ci; a <= amount; a++)\n t[a] += t[a - ci]\ndocument.write(t[amount])\n", "language": "JavaScript" }, { "code": "# How many ways are there to make \"target\" cents, given a list of coin\n# denominations as input.\n# The strategy is to record at total[n] the number of ways to make n cents.\ndef countcoins(target):\n . as $coin\n | reduce range(0; length) as $a\n ( [1]; # there is 1 way to make 0 cents\n reduce range(1; target + 1) as $b\n (.; # total[]\n if $b < $coin[$a] then .\n else .[$b - $coin[$a]] as $count\n | if $count == 0 then .\n else .[$b] += $count\n end\n end ) )\n | .[target] ;\n", "language": "Jq" }, { "code": "function changes(amount::Int, coins::Array{Int})::Int128\n ways = zeros(Int128, amount + 1)\n ways[1] = 1\n for coin in coins, j in coin+1:amount+1\n ways[j] += ways[j - coin]\n end\n return ways[amount + 1]\nend\n\n@show changes(100, [1, 5, 10, 25])\n@show changes(100000, [1, 5, 10, 25, 50, 100])\n", "language": "Julia" }, { "code": "// version 1.0.6\n\nfun countCoins(c: IntArray, m: Int, n: Int): Long {\n val table = LongArray(n + 1)\n table[0] = 1\n for (i in 0 until m)\n for (j in c[i]..n) table[j] += table[j - c[i]]\n return table[n]\n}\n\nfun main(args: Array<String>) {\n val c = intArrayOf(1, 5, 10, 25, 50, 100)\n println(countCoins(c, 4, 100))\n println(countCoins(c, 6, 1000 * 100))\n}\n", "language": "Kotlin" }, { "code": "define cointcoins(\n\ttarget::integer,\n\toperands::array\n) => {\n\n\tlocal(\n\t\ttargetlength\t= #target + 1,\n\t\toperandlength\t= #operands -> size,\n\t\toutput\t\t\t= staticarray_join(#targetlength,0),\n\t\touterloopcount\n\t)\n\n\t#output -> get(1) = 1\n\n\tloop(#operandlength) => {\n\t\t#outerloopcount = loop_count\n\t\tloop(#targetlength) => {\n\n\t\t\tif(loop_count >= #operands -> get(#outerloopcount) and loop_count - #operands -> get(#outerloopcount) > 0) => {\n\t\t\t\t#output -> get(loop_count) += #output -> get(loop_count - #operands -> get(#outerloopcount))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn #output -> get(#targetlength)\n}\n\ncointcoins(100, array(1,5,10,25,))\n'<br />'\ncointcoins(100000, array(1, 5, 10, 25, 50, 100))\n", "language": "Lasso" }, { "code": "function countSums (amount, values)\n local t = {}\n for i = 1, amount do t[i] = 0 end\n t[0] = 1\n for k, val in pairs(values) do\n for i = val, amount do t[i] = t[i] + t[i - val] end\n end\n return t[amount]\nend\n\nprint(countSums(100, {1, 5, 10, 25}))\nprint(countSums(100000, {1, 5, 10, 25, 50, 100}))\n", "language": "Lua" }, { "code": "Module FindCoins {\n Function count(c(), n) {\n dim table(n+1)=0@ : table(0)=1@\n for c=0 to len(c())-1 {\n if c(c)>n then exit\n }\n if c else exit\n for i=0 to c-1 {for j=c(i) to n {table(j)+=table(j-c(i))}}\n =table(n)\n }\n Print \"For 1$ ways to change:\";count((1,5,10,25),100)\n Print \"For 100$ (optional task ways to change):\";count((1,5,10,25,50,100),100000)\n}\nFindCoins\n", "language": "M2000-Interpreter" }, { "code": "Module CheckThisToo {\n inventory c=\" 0 0\":=1@\n make_change=lambda c (amount, coins()) ->{\n m=lambda c,coins() (n,m)->{if n<0 or m<0 then =0@:exit\n if exist(c,str$(n)+str$(m)) then =eval(c):exit\n append c,str$(n)+str$(m):=lambda(n-coins(m), m)+lambda(n, m-1):=c(str$(n)+str$(m))}\n =m(amount,len(coins())-1)\n }\n Print make_change(100, (1,5,10,25,50,100))=293\n Print make_change(100, (1,5,10,25))=242\n Print make_change(15, (1,5,10,25))=6\n Print make_change(5, (1,5,10,25))=2\n}\nCheckThisToo\n", "language": "M2000-Interpreter" }, { "code": " NORMAL MODE IS INTEGER\n DIMENSION TAB(101)\n\n THROUGH ZERO, FOR N = 1, 1, N.G.100\nZERO TAB(N) = 0\n TAB(0) = 1\n\n THROUGH STEP, FOR VALUES OF COIN = 1, 5, 10, 25\n THROUGH STEP, FOR N = COIN, 1, N.G.100\nSTEP TAB(N) = TAB(N) + TAB(N - COIN)\n\n VECTOR VALUES FMT = $I3*$\n PRINT FORMAT FMT, TAB(100)\n END OF PROGRAM\n", "language": "MAD" }, { "code": "assume(p::posint,abs(x)<1):\ncoin:=unapply(sum(x^(p*n),n=0..infinity),p):\nways:=(amount,purse)->coeff(series(mul(coin(k),k in purse),x,amount+1),x,amount):\n\nways(100,[1,5,10,25]);\n# 242\n\nways(1000,[1,5,10,25,50,100]);\n# 2103596\n\nways(10000,[1,5,10,25,50,100]);\n# 139946140451\n\nways(100000,[1,5,10,25,50,100]);\n# 13398445413854501\n", "language": "Maple" }, { "code": "ways2:=proc(amount,purse)\n local a,n,k;\n a:=Array(1..amount);\n for k in purse do\n for n from k to amount do\n if n=k then\n a[n]++;\n else\n a[n]+=a[n-k]\n fi\n od\n od;\n a[-1]\nend:\n\nways2(100,[1,5,10,25]);\n# 242\n\nways2(100,[1,5,10,25,50,100]);\n# 293\n\nways2(1000,[1,5,10,25,50,100]);\n# 2103596\n\nways2(10000,[1,5,10,25,50,100]);\n# 139946140451\n\nways2(100000,[1,5,10,25,50,100]);\n# 13398445413854501\n\nways2(1000000,[1,5,10,25,50,100]);\n# 1333983445341383545001\n\nways2(10000000,[1,5,10,25,50,100]);\n# 133339833445334138335450001\n\nways2(100000000,[1,5,10,25,50,100]);\n# 13333398333445333413833354500001\n", "language": "Maple" }, { "code": "P:=n->4/(3*10^9)*n^5+65/10^8*n^4+112/10^6*n^3+805/10^5*n^2+635/3000*n+1:\n\nfor k from 2 to 8 do lprint(P(10^k)) od:\n293\n2103596\n139946140451\n13398445413854501\n1333983445341383545001\n133339833445334138335450001\n13333398333445333413833354500001\n", "language": "Maple" }, { "code": "Q:=n->40/3*n^5+65*n^4+112*n^3+161/2*n^2+127/6*n+1:\n", "language": "Maple" }, { "code": "CountCoins[amount_, coinlist_] := ( ways = ConstantArray[1, amount];\nDo[For[j = coin, j <= amount, j++,\n If[ j - coin == 0,\n ways[[j]] ++,\n ways[[j]] += ways[[j - coin]]\n]]\n, {coin, coinlist}];\nways[[amount]])\n", "language": "Mathematica" }, { "code": "%% Count_The_Coins\nclear;close all;clc;\ntic\n\nfor i = 1:2 % 1st loop is main challenge 2nd loop is optional challenge\n if (i == 1)\n amount = 100; % Matlab indexes from 1 not 0, so we need to add 1 to our target value\n amount = amount + 1;\n coins = [1 5 10 25]; % Value of coins we can use\n else\n amount = 100*1000; % Matlab indexes from 1 not 0, so we need to add 1 to our target value\n amount = amount + 1;\n coins = [1 5 10 25 50 100]; % Value of coins we can use\n end % End if\n ways = zeros(1,amount); % Preallocating for speed\n ways(1) = 1; % First solution is 1\n\n % Solves from smallest sub problem to largest (bottom up approach of dynamic programming).\n for j = 1:length(coins)\n for K = coins(j)+1:amount\n ways(K) = ways(K) + ways(K-coins(j));\n end % End for\n end % End for\n if (i == 1)\n fprintf(‘Main Challenge: %d \\n', ways(amount));\n else\n fprintf(‘Bonus Challenge: %d \\n', ways(amount));\n end % End if\nend % End for\ntoc\n", "language": "MATLAB" }, { "code": ":- module coins.\n:- interface.\n:- import_module int, io.\n:- type coin ---> quarter; dime; nickel; penny.\n:- type purse ---> purse(int, int, int, int).\n\n:- pred sum_to(int::in, purse::out) is nondet.\n\n:- pred main(io::di, io::uo) is det.\n:- implementation.\n:- import_module solutions, list, string.\n\n:- func value(coin) = int.\nvalue(quarter) = 25.\nvalue(dime) = 10.\nvalue(nickel) = 5.\nvalue(penny) = 1.\n\n:- pred supply(coin::in, int::in, int::out) is multi.\nsupply(C, Target, N) :- upto(Target div value(C), N).\n\n:- pred upto(int::in, int::out) is multi.\nupto(N, R) :- ( nondet_int_in_range(0, N, R0) -> R = R0 ; R = 0 ).\n\nsum_to(To, Purse) :-\n\tPurse = purse(Q, D, N, P),\n\tsum(Purse) = To,\n\tsupply(quarter, To, Q),\n\tsupply(dime, To, D),\n\tsupply(nickel, To, N),\n\tsupply(penny, To, P).\n\n:- func sum(purse) = int.\nsum(purse(Q, D, N, P)) =\n\tvalue(quarter) * Q + value(dime) * D +\n\tvalue(nickel) * N + value(penny) * P.\n\nmain(!IO) :-\n\tsolutions(sum_to(100), L),\n\tshow(L, !IO),\n\tio.format(\"There are %d ways to make change for a dollar.\\n\",\n [i(length(L))], !IO).\n\n:- pred show(list(purse)::in, io::di, io::uo) is det.\nshow([], !IO).\nshow([P|T], !IO) :-\n\tio.write(P, !IO), io.nl(!IO),\n\tshow(T, !IO).\n", "language": "Mercury" }, { "code": "proc changes(amount: int, coins: openArray[int]): int =\n var ways = @[1]\n ways.setLen(amount+1)\n for coin in coins:\n for j in coin..amount:\n ways[j] += ways[j-coin]\n ways[amount]\n\necho changes(100, [1, 5, 10, 25])\necho changes(100000, [1, 5, 10, 25, 50, 100])\n", "language": "Nim" }, { "code": "let changes amount coins =\n let ways = Array.make (amount + 1) 0L in\n ways.(0) <- 1L;\n List.iter (fun coin ->\n for j = coin to amount do\n ways.(j) <- Int64.add ways.(j) ways.(j - coin)\n done\n ) coins;\n ways.(amount)\n\nlet () =\n Printf.printf \"%Ld\\n\" (changes 1_00 [25; 10; 5; 1]);\n Printf.printf \"%Ld\\n\" (changes 1000_00 [100; 50; 25; 10; 5; 1]);\n;;\n", "language": "OCaml" }, { "code": "coins(v)=prod(i=1,#v,1/(1-'x^v[i]));\nways(v,n)=polcoeff(coins(v)+O('x^(n+1)),n);\nways([1,5,10,25],100)\nways([1,5,10,25,50,100],100000)\n", "language": "PARI-GP" }, { "code": "use 5.01;\nuse Memoize;\n\nsub cc {\n my $amount = shift;\n return 0 if !@_ || $amount < 0;\n return 1 if $amount == 0;\n my $first = shift;\n cc( $amount, @_ ) + cc( $amount - $first, $first, @_ );\n}\nmemoize 'cc';\n\n# Make recursive algorithm run faster by sorting coins descending by value:\nsub cc_optimized {\n my $amount = shift;\n cc( $amount, sort { $b <=> $a } @_ );\n}\n\nsay 'Ways to change $ 1 with common coins: ',\n cc_optimized( 100, 1, 5, 10, 25 );\nsay 'Ways to change $ 1000 with addition of less common coins: ',\n cc_optimized( 1000 * 100, 1, 5, 10, 25, 50, 100 );\n", "language": "Perl" }, { "code": "-->\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">coin_count</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">coins</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">amount</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">amount</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">coins</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">coins</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">amount</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">coins</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">]+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">amount</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">coin_count</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">coins</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">amount</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- start with 1 known way to achieve 0 (being no coins)\n -- (nb: s[1] holds the solution for 0, s[n+1] for n)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">amount</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000080;font-style:italic;\">-- then for every coin that we can use, increase number of\n -- solutions by that previously found for the remainder.</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">coins</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000080;font-style:italic;\">-- this inner loop is essentially behaving as if we had\n -- called this routine with 1..amount, but skipping any\n -- less than the coin's value, hence coins[c]..amount.</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">coins</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">amount</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">coins</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">]+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">amount</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- The key to understanding the above is to try a dry run of this:</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">coin_count</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">))</span> <span style=\"color: #000080;font-style:italic;\">-- (prints 1)\n -- You'll need 4 2p coins, 3 3p coins, and 5 spaces marked 1..5.\n -- Place 2p wherever it fits: 1:0 2:1 3:1 4:1 5:1\n -- Add previously found solns: +0 +1 +0 +1 +0 [1]\n -- Place 3p wherever it fits: 1:0 2:0 3:1 4:1 5:1\n -- Add previously found solns: +0 +0 +1 +0 +1 [2]\n -- [1] obviously at 2: we added the base soln for amount=0,\n -- and at 4: we added the previously found soln for 2.\n -- also note that we added nothing for 2p+3p, yet, that\n -- fact is central to understanding why this works. [3]\n -- [2] obviously at 3: we added the base soln for amount=0,\n -- at 4: we added the zero solutions yet found for 1p,\n -- and at 5: we added the previously found soln for 2.\n -- you can imagine at 6,9,12 etc all add in soln for 3,\n -- albeit by adding that as just added to the precessor.\n -- [3] since we add no 3p solns when processing 2p, we do\n -- not count 2p+3p and 3p+2p as two solutions.\n\n --For N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}.</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">coin_count</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000080;font-style:italic;\">--For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}.</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d\\n\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">coin_count</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">))</span>\n\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">coin_count</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">25</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #000000;\">1_00</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%,d\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">coin_count</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">50</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">25</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #000000;\">1000_00</span><span style=\"color: #0000FF;\">))</span>\n<!--\n", "language": "Phix" }, { "code": "go =>\n Problems = [[ 1*100, [25,10,5,1]], % 1 dollar\n [ 100*100, [100,50,25,10,5,1]], % 100 dollars\n [ 1_000*100, [100,50,25,10,5,1]], % 1000 dollars\n [ 10_000*100, [100,50,25,10,5,1]], % 10000 dollars\n [100_000*100, [100,50,25,10,5,1]] % 100000 dollars\n ],\n foreach([N,L] in Problems)\n initialize_table, % clear the tabling from previous run\n println([n=N,l=L]),\n time(println(num_sols=coins(L,N,1)))\n end.\n\ntable\ncoins(Coins, Money, M) = Sum =>\n Sum1 = 0,\n Len = Coins.length,\n if M == Len then\n Sum1 := 1,\n else\n foreach(I in M..Len)\n if Money - Coins[I] == 0 then\n Sum1 := Sum1 + 1\n end,\n if Money - Coins[I] > 0 then\n Sum1 := Sum1 + coins(Coins, Money-Coins[I], I)\n end,\n end\n end,\n Sum = Sum1.\n", "language": "Picat" }, { "code": "(de coins (Sum Coins)\n (let (Buf (mapcar '((N) (cons 1 (need (dec N) 0))) Coins) Prev)\n (do Sum\n (zero Prev)\n (for L Buf\n (inc (rot L) Prev)\n (setq Prev (car L)) ) )\n Prev ) )\n", "language": "PicoLisp" }, { "code": "(for Coins '((100 50 25 10 5 1) (200 100 50 20 10 5 2 1))\n (println (coins 100 (cddr Coins)))\n (println (coins (* 1000 100) Coins))\n (println (coins (* 10000 100) Coins))\n (println (coins (* 100000 100) Coins))\n (prinl) )\n", "language": "PicoLisp" }, { "code": ":- use_module(library(clpfd)).\n\n% Basic, Q = Quarter, D = Dime, N = Nickel, P = Penny\ncoins(Q, D, N, P, T) :-\n\t[Q,D,N,P] ins 0..T,\n\tT #= (Q * 25) + (D * 10) + (N * 5) + P.\n\ncoins_for(T) :-\n\tcoins(Q,D,N,P,T),\n\tmaplist(indomain, [Q,D,N,P]).\n", "language": "Prolog" }, { "code": "def changes(amount, coins):\n ways = [0] * (amount + 1)\n ways[0] = 1\n for coin in coins:\n for j in xrange(coin, amount + 1):\n ways[j] += ways[j - coin]\n return ways[amount]\n\nprint changes(100, [1, 5, 10, 25])\nprint changes(100000, [1, 5, 10, 25, 50, 100])\n", "language": "Python" }, { "code": "try:\n import psyco\n psyco.full()\nexcept ImportError:\n pass\n\ndef count_changes(amount_cents, coins):\n n = len(coins)\n # max([]) instead of max() for Psyco\n cycle = max([c+1 for c in coins if c <= amount_cents]) * n\n table = [0] * cycle\n for i in xrange(n):\n table[i] = 1\n\n pos = n\n for s in xrange(1, amount_cents + 1):\n for i in xrange(n):\n if i == 0 and pos >= cycle:\n pos = 0\n if coins[i] <= s:\n q = pos - coins[i] * n\n table[pos]= table[q] if (q >= 0) else table[q + cycle]\n if i:\n table[pos] += table[pos - 1]\n pos += 1\n return table[pos - 1]\n\ndef main():\n us_coins = [100, 50, 25, 10, 5, 1]\n eu_coins = [200, 100, 50, 20, 10, 5, 2, 1]\n\n for coins in (us_coins, eu_coins):\n print count_changes( 100, coins[2:])\n print count_changes( 100000, coins)\n print count_changes( 1000000, coins)\n print count_changes(10000000, coins), \"\\n\"\n\nmain()\n", "language": "Python" }, { "code": " [ stack ] is lim ( --> s )\n\n [ swap dup 1+ lim put\n 1 0 rot of join\n swap witheach\n [ 0 over of\n swap negate temp put\n lim share times\n [ over i^ peek\n over temp share peek\n + join ]\n temp take negate split\n nip nip ]\n -1 peek\n lim release ] is makechange ( n [ --> n )\n\n say \"With US coins.\" cr\n 100 ' [ 1 5 10 25 ] makechange echo cr\n 100000 ' [ 1 5 10 25 50 100 ] makechange echo cr\n cr\n say \"With EU coins.\" cr\n 100 ' [ 1 2 5 10 20 50 100 200 ] makechange echo cr\n 100000 ' [ 1 2 5 10 20 50 100 200 ] makechange echo cr\n", "language": "Quackery" }, { "code": "#lang racket\n(define (ways-to-make-change cents coins)\n (cond ((null? coins) 0)\n ((negative? cents) 0)\n ((zero? cents) 1)\n (else\n (+ (ways-to-make-change cents (cdr coins))\n (ways-to-make-change (- cents (car coins)) coins)))))\n\n(ways-to-make-change 100 '(25 10 5 1)) ; -> 242\n", "language": "Racket" }, { "code": "#lang racket\n\n(define memos (make-hash))\n(define (ways-to-make-change cents coins)\n (cond [(or (empty? coins) (negative? cents)) 0]\n [(zero? cents) 1]\n [else (define (answerer-for-new-arguments)\n (+ (ways-to-make-change cents (rest coins))\n (ways-to-make-change (- cents (first coins)) coins)))\n (hash-ref! memos (cons cents coins) answerer-for-new-arguments)]))\n\n(time (ways-to-make-change 100 '(25 10 5 1)))\n(time (ways-to-make-change 100000 '(100 50 25 10 5 1)))\n(time (ways-to-make-change 1000000 '(200 100 50 20 10 5 2 1)))\n\n#| Times in milliseconds, and results:\n\n cpu time: 1 real time: 1 gc time: 0\n 242\n\n cpu time: 524 real time: 553 gc time: 163\n 13398445413854501\n\n cpu time: 20223 real time: 20673 gc time: 10233\n 99341140660285639188927260001 |#\n", "language": "Racket" }, { "code": "# Recursive (cached)\nsub change-r($amount, @coins) {\n my @cache = [1 xx @coins], |([] xx $amount);\n\n multi ways($n where $n >= 0, @now [$coin,*@later]) {\n @cache[$n;+@later] //= ways($n - $coin, @now) + ways($n, @later);\n }\n multi ways($,@) { 0 }\n\n # more efficient to start with coins sorted in descending order\n ways($amount, @coins.sort(-*).list);\n}\n\n# Iterative\nsub change-i(\\n, @coins) {\n my @table = [1 xx @coins], [0 xx @coins] xx n;\n (1..n).map: -> \\i {\n for ^@coins -> \\j {\n my \\c = @coins[j];\n @table[i;j] = [+]\n @table[i - c;j] // 0,\n @table[i;j - 1] // 0;\n }\n }\n @table[*-1][*-1];\n}\n\nsay \"Iterative:\";\nsay change-i 1_00, [1,5,10,25];\nsay change-i 1000_00, [1,5,10,25,50,100];\n\nsay \"\\nRecursive:\";\nsay change-r 1_00, [1,5,10,25];\nsay change-r 1000_00, [1,5,10,25,50,100];\n", "language": "Raku" }, { "code": "/*REXX program counts the number of ways to make change with coins from an given amount.*/\nnumeric digits 20 /*be able to handle large amounts of $.*/\nparse arg N $ /*obtain optional arguments from the CL*/\nif N='' | N=\",\" then N= 100 /*Not specified? Then Use $1 (≡100¢).*/\nif $='' | $=\",\" then $= 1 5 10 25 /*Use penny/nickel/dime/quarter default*/\nif left(N, 1)=='$' then N= 100 * substr(N, 2) /*the count was specified in dollars. */\ncoins= words($) /*the number of coins specified. */\nNN= N; do j=1 for coins /*create a fast way of accessing specie*/\n _= word($, j) /*define an array element for the coin.*/\n if _=='1/2' then _=.5 /*an alternate spelling of a half-cent.*/\n if _=='1/4' then _=.25 /* \" \" \" \" \" quarter-¢.*/\n $.j= _ /*assign the value to a particular coin*/\n end /*j*/\n_= n//100; cnt=' cents' /* [↓] is the amount in whole dollars?*/\nif _=0 then do; NN= '$' || (NN%100); cnt= /*show the amount in dollars, not cents*/\n end /*show the amount in dollars, not cents*/\nsay 'with an amount of ' comma(NN)cnt\", there are \" comma( MKchg(N, coins) )\nsay 'ways to make change with coins of the following denominations: ' $\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncomma: procedure; parse arg _; n= _'.9'; #= 123456789; b= verify(n, #, \"M\")\n e= verify(n, #'0', , verify(n, #\"0.\", 'M')) - 4\n do j=e to b by -3; _= insert(',', _, j); end /*j*/; return _\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nMKchg: procedure expose $.; parse arg a,k /*this function is invoked recursively.*/\n if a==0 then return 1 /*unroll for a special case of zero. */\n if k==1 then return 1 /* \" \" \" \" \" \" unity. */\n if k==2 then f= 1 /*handle this special case of two. */\n else f= MKchg(a, k-1) /*count, and then recurse the amount. */\n if a==$.k then return f+1 /*handle this special case of A=a coin.*/\n if a <$.k then return f /* \" \" \" \" \" A<a coin.*/\n return f+MKchg(a-$.k,k) /*use diminished amount ($) for change.*/\n", "language": "REXX" }, { "code": "/*REXX program counts the number of ways to make change with coins from an given amount.*/\nnumeric digits 20 /*be able to handle large amounts of $.*/\nparse arg N $ /*obtain optional arguments from the CL*/\nif N='' | N=\",\" then N= 100 /*Not specified? Then Use $1 (≡100¢).*/\nif $='' | $=\",\" then $= 1 5 10 25 /*Use penny/nickel/dime/quarter default*/\nif left(N,1)=='$' then N= 100 * substr(N, 2) /*the amount was specified in dollars.*/\nNN= N; coins= words($) /*the number of coins specified. */\n!.= .; do j=1 for coins /*create a fast way of accessing specie*/\n _= word($, j); ?= _ ' coin' /*define an array element for the coin.*/\n if _=='½' | _==\"1/2\" then _= .5 /*an alternate spelling of a half─cent.*/\n if _=='¼' | _==\"1/4\" then _= .25 /* \" \" \" \" \" quarter─¢.*/\n $.j= _ /*assign the value to a particular coin*/\n end /*j*/\n_= n // 100; cnt=' cents' /* [↓] is the amount in whole dollars?*/\nif _=0 then do; NN= '$' || (NN%100); cnt= /*show the amount in dollars, not cents*/\n end\nsay 'with an amount of ' comma(NN)cnt\", there are \" comma( MKchg(N, coins) )\nsay 'ways to make change with coins of the following denominations: ' $\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncomma: procedure; parse arg _; n= _'.9'; #= 123456789; b= verify(n, #, \"M\")\n e= verify(n, #'0', , verify(n, #\"0.\", 'M')) - 4\n do j=e to b by -3; _= insert(',', _, j); end /*j*/; return _\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nMKchg: procedure expose $. !.; parse arg a,k /*function is recursive. */\n if !.a.k\\==. then return !.a.k /*found this A & K before? */\n if a==0 then return 1 /*unroll for a special case*/\n if k==1 then return 1 /* \" \" \" \" \" */\n if k==2 then f= 1 /*handle this special case.*/\n else f= MKchg(a, k-1) /*count, recurse the amount*/\n if a==$.k then do; !.a.k= f+1; return !.a.k; end /*handle this special case.*/\n if a <$.k then do; !.a.k= f ; return f ; end /* \" \" \" \" */\n !.a.k= f + MKchg(a-$.k, k); return !.a.k /*compute, define, return. */\n", "language": "REXX" }, { "code": "/*REXX program counts the number of ways to make change with coins from an given amount.*/\nnumeric digits 20 /*be able to handle large amounts of $.*/\nparse arg N $ /*obtain optional arguments from the CL*/\nif N='' | N=\",\" then N= 100 /*Not specified? Then Use $1 (≡100¢).*/\nif $='' | $=\",\" then $= 1 5 10 25 /*Use penny/nickel/dime/quarter default*/\nX= N /*save original for possible error msgs*/\nif left(N,1)=='$' then do /*the amount has a leading dollar sign.*/\n _= substr(N, 2) /*the amount was specified in dollars.*/\n if \\isNum(_) then call ser \"amount isn't numeric: \" N\n N= 100 * _ /*change amount (in $) ───► cents (¢).*/\n end\nmax$= 10 ** digits() /*the maximum amount this pgm can have.*/\nif \\isNum(N) then call ser X \" amount isn't numeric.\"\nif N=0 then call ser X \" amount can't be zero.\"\nif N<0 then call ser X \" amount can't be negative.\"\nif N>max$ then call ser X \" amount can't be greater than \" max$'.'\ncoins= words($); !.= .; NN= N; p= 0 /*#coins specified; coins; amount; prev*/\n@.= 0 /*verify a coin was only specified once*/\n do j=1 for coins; _= word($, j) /*create a fast way of accessing specie*/\n ?= _ ' coin' /*define an array element for the coin.*/\n if _=='½' | _==\"1/2\" then _= .5 /*an alternate spelling of a half─cent.*/\n if _=='¼' | _==\"1/4\" then _= .25 /* \" \" \" \" \" quarter─¢.*/\n if \\isNum(_) then call ser ? \"coin value isn't numeric.\"\n if _<0 then call ser ? \"coin value can't be negative.\"\n if _<=0 then call ser ? \"coin value can't be zero.\"\n if @._ then call ser ? \"coin was already specified.\"\n if _<p then call ser ? \"coin must be greater than previous:\" p\n if _>N then call ser ? \"coin must be less or equal to amount:\" X\n @._= 1; p= _ /*signify coin was specified; set prev.*/\n $.j= _ /*assign the value to a particular coin*/\n end /*j*/\n_= n // 100; cnt= ' cents' /* [↓] is the amount in whole dollars?*/\nif _=0 then do; NN= '$' || (NN%100); cnt= /*show the amount in dollars, not cents*/\n end\nsay 'with an amount of ' comma(NN)cnt\", there are \" comma( MKchg(N, coins) )\nsay 'ways to make change with coins of the following denominations: ' $\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nisNum: return datatype(arg(1), 'N') /*return 1 if arg is numeric, 0 if not.*/\nser: say; say '***error***'; say; say arg(1); say; exit 13 /*error msg.*/\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncomma: procedure; parse arg _; n= _'.9'; #= 123456789; b= verify(n, #, \"M\")\n e= verify(n, #'0', , verify(n, #\"0.\", 'M')) - 4\n do j=e to b by -3; _= insert(',', _, j); end /*j*/; return _\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nMKchg: procedure expose $. !.; parse arg a,k /*function is recursive. */\n if !.a.k\\==. then return !.a.k /*found this A & K before? */\n if a==0 then return 1 /*unroll for a special case*/\n if k==1 then return 1 /* \" \" \" \" \" */\n if k==2 then f= 1 /*handle this special case.*/\n else f= MKchg(a, k-1) /*count, recurse the amount*/\n if a==$.k then do; !.a.k= f+1; return !.a.k; end /*handle this special case.*/\n if a <$.k then do; !.a.k= f ; return f ; end /* \" \" \" \" */\n !.a.k= f + MKchg(a-$.k, k); return !.a.k /*compute, define, return. */\n", "language": "REXX" }, { "code": "penny = 1\nnickel = 1\ndime = 1\nquarter = 1\ncount = 0\n\nfor penny = 0 to 100\n for nickel = 0 to 20\n for dime = 0 to 10\n for quarter = 0 to 4\n if (penny + nickel * 5 + dime * 10 + quarter * 25) = 100\n see \"\" + penny + \" pennies \" + nickel + \" nickels \" + dime + \" dimes \" + quarter + \" quarters\" + nl\n count = count + 1\n ok\n next\n next\n next\nnext\nsee count + \" ways to make a dollar\" + nl\n", "language": "Ring" }, { "code": "def make_change(amount, coins)\n @cache = Array.new(amount+1){|i| Array.new(coins.size, i.zero? ? 1 : nil)}\n @coins = coins\n do_count(amount, @coins.length - 1)\nend\n\ndef do_count(n, m)\n if n < 0 || m < 0\n 0\n elsif @cache[n][m]\n @cache[n][m]\n else\n @cache[n][m] = do_count(n-@coins[m], m) + do_count(n, m-1)\n end\nend\n\np make_change( 1_00, [1,5,10,25])\np make_change(1000_00, [1,5,10,25,50,100])\n", "language": "Ruby" }, { "code": "def make_change2(amount, coins)\n n, m = amount, coins.size\n table = Array.new(n+1){|i| Array.new(m, i.zero? ? 1 : nil)}\n for i in 1..n\n for j in 0...m\n table[i][j] = (i<coins[j] ? 0 : table[i-coins[j]][j]) +\n (j<1 ? 0 : table[i][j-1])\n end\n end\n table[-1][-1]\nend\n\np make_change2( 1_00, [1,5,10,25])\np make_change2(1000_00, [1,5,10,25,50,100])\n", "language": "Ruby" }, { "code": "for penny = 0 to 100\n for nickel = 0 to 20\n for dime = 0 to 10\n for quarter = 0 to 4\n if penny + nickel * 5 + dime * 10 + quarter * 25 = 100 then\n print penny;\" pennies \";nickel;\" nickels \"; dime;\" dimes \";quarter;\" quarters\"\n count = count + 1\n end if\n next quarter\n next dime\n next nickel\nnext penny\nprint count;\" ways to make a buck\"\n", "language": "Run-BASIC" }, { "code": "fn make_change(coins: &[usize], cents: usize) -> usize {\n let size = cents + 1;\n let mut ways = vec![0; size];\n ways[0] = 1;\n for &coin in coins {\n for amount in coin..size {\n ways[amount] += ways[amount - coin];\n }\n }\n ways[cents]\n}\n\nfn main() {\n println!(\"{}\", make_change(&[1,5,10,25], 100));\n println!(\"{}\", make_change(&[1,5,10,25,50,100], 100_000));\n}\n", "language": "Rust" }, { "code": "/* call OPTMODEL procedure in SAS/OR */\nproc optmodel;\n /* declare set and names of coins */\n set COINS = {1,5,10,25};\n str name {COINS} = ['penny','nickel','dime','quarter'];\n\n /* declare variables and constraint */\n var NumCoins {COINS} >= 0 integer;\n con Dollar:\n sum {i in COINS} i * NumCoins[i] = 100;\n\n /* call CLP solver */\n solve with CLP / findallsolns;\n\n /* write solutions to SAS data set */\n create data sols(drop=s) from [s]=(1.._NSOL_) {i in COINS} <col(name[i])=NumCoins[i].sol[s]>;\nquit;\n\n/* print all solutions */\nproc print data=sols;\nrun;\n", "language": "SAS" }, { "code": "def countChange(amount: Int, coins:List[Int]) = {\n\t val ways = Array.fill(amount + 1)(0)\n\t ways(0) = 1\n\t coins.foreach (coin =>\n\t for (j<-coin to amount)\n\t\t ways(j) = ways(j) + ways(j - coin)\n\t\t )\n\tways(amount)\n }\n\ncountChange (15, List(1, 5, 10, 25))\n", "language": "Scala" }, { "code": "def count(target: Int, coins: List[Int]): Int = {\n if (target == 0) 1\n else if (coins.isEmpty || target < 0) 0\n else count(target, coins.tail) + count(target - coins.head, coins)\n}\n\n\ncount(100, List(25, 10, 5, 1))\n", "language": "Scala" }, { "code": "(define ways-to-make-change\n (lambda (x coins)\n (cond\n [(null? coins) 0]\n [(< x 0) 0]\n [(zero? x) 1]\n [else (+ (ways-to-make-change x (cdr coins)) (ways-to-make-change (- x (car coins)) coins))])))\n\n(ways-to-make-change 100)\n", "language": "Scheme" }, { "code": "amount=100;\ncoins=[25 10 5 1];\nn_coins=zeros(coins);\nways=0;\n\nfor a=0:4\n for b=0:10\n for c=0:20\n for d=0:100\n n_coins=[a b c d];\n change=sum(n_coins.*coins);\n if change==amount then\n ways=ways+1;\n elseif change>amount\n break\n end\n end\n end\n end\nend\n\ndisp(ways);\n", "language": "Scilab" }, { "code": "function varargout=changes(amount, coins)\n ways = zeros(1,amount + 2);\n ways(1) = 1;\n for coin=coins\n for j=coin:(amount+1)\n ways(j+1) = ways(j+1) + ways(j + 1 - coin);\n end\n end\n\n varargout=list(ways(length(ways)))\nendfunction\n\na=changes(100, [1, 5, 10, 25]);\nb=changes(100000, [1, 5, 10, 25, 50, 100]);\nmprintf(\"%.0f, %.0f\", a, b);\n", "language": "Scilab" }, { "code": "$ include \"seed7_05.s7i\";\n include \"bigint.s7i\";\n\nconst func bigInteger: changeCount (in integer: amountCents, in array integer: coins) is func\n result\n var bigInteger: waysToChange is 0_;\n local\n var array bigInteger: t is 0 times 0_;\n var integer: pos is 0;\n var integer: s is 0;\n var integer: i is 0;\n begin\n t := length(coins) times 1_ & (length(coins) * amountCents) times 0_;\n pos := length(coins) + 1;\n for s range 1 to amountCents do\n if coins[1] <= s then\n t[pos] := t[pos - (length(coins) * coins[1])];\n end if;\n incr(pos);\n for i range 2 to length(coins) do\n if coins[i] <= s then\n t[pos] := t[pos - (length(coins) * coins[i])];\n end if;\n t[pos] +:= t[pos - 1];\n incr(pos);\n end for;\n end for;\n waysToChange := t[pos - 1];\n end func;\n\nconst proc: main is func\n local\n const array integer: usCoins is [] (1, 5, 10, 25, 50, 100);\n const array integer: euCoins is [] (1, 2, 5, 10, 20, 50, 100, 200);\n begin\n writeln(changeCount( 100, usCoins[.. 4]));\n writeln(changeCount( 100000, usCoins));\n writeln(changeCount(1000000, usCoins));\n writeln(changeCount( 100000, euCoins));\n writeln(changeCount(1000000, euCoins));\n end func;\n", "language": "Seed7" }, { "code": "program count_the_coins;\n print(count([1, 5, 10, 25], 100));\n print(count([1, 5, 10, 25, 50, 100], 1000 * 100));\n\n proc count(coins, n);\n tab := {[0, 1]};\n loop for coin in coins do\n loop for i in [coin..n] do\n tab(i) +:= tab(i - coin) ? 0;\n end loop;\n end loop;\n return tab(n);\n end proc;\nend program;\n", "language": "SETL" }, { "code": "func cc(_) { 0 }\nfunc cc({ .is_neg }, *_) { 0 }\nfunc cc({ .is_zero }, *_) { 1 }\n\nfunc cc(amount, first, *rest) is cached {\n cc(amount, rest...) + cc(amount - first, first, rest...);\n}\n\nfunc cc_optimized(amount, *rest) {\n cc(amount, rest.sort_by{|v| -v }...);\n}\n\nvar x = cc_optimized(100, 1, 5, 10, 25);\nsay \"Ways to change $1 with common coins: #{x}\";\n\nvar y = cc_optimized(1000 * 100, 1, 5, 10, 25, 50, 100);\nsay \"Ways to change $1000 with addition of less common coins: #{y}\";\n", "language": "Sidef" }, { "code": "import BigInt\n\nfunc countCoins(amountCents cents: Int, coins: [Int]) -> BigInt {\n let cycle = coins.filter({ $0 <= cents }).map({ $0 + 1 }).max()! * coins.count\n var table = [BigInt](repeating: 0, count: cycle)\n\n for x in 0..<coins.count {\n table[x] = 1\n }\n\n var pos = coins.count\n\n for s in 1..<cents+1 {\n for i in 0..<coins.count {\n if i == 0 && pos >= cycle {\n pos = 0\n }\n\n if coins[i] <= s {\n let q = pos - coins[i] * coins.count\n table[pos] = q >= 0 ? table[q] : table[q + cycle]\n }\n\n if i != 0 {\n table[pos] += table[pos - 1]\n }\n\n pos += 1\n }\n }\n\n return table[pos - 1]\n}\n\nlet usCoins = [100, 50, 25, 10, 5, 1]\nlet euCoins = [200, 100, 50, 20, 10, 5, 2, 1]\n\nfor set in [usCoins, euCoins] {\n print(countCoins(amountCents: 100, coins: Array(set.dropFirst(2))))\n print(countCoins(amountCents: 100000, coins: set))\n print(countCoins(amountCents: 1000000, coins: set))\n print(countCoins(amountCents: 10000000, coins: set))\n print()\n}\n", "language": "Swift" }, { "code": "templates makeChange&{coins:}\n def paid: $;\n @: [1..$paid -> 0];\n $coins... -> \\(def coin: $;\n @makeChange($coin): $@makeChange($coin) + 1;\n $coin+1..$paid -> @makeChange($): $@makeChange($) + $@makeChange($-$coin);\n \\) -> !VOID\n $@($paid)!\nend makeChange\n\n100 -> makeChange&{coins: [1,5,10,25]} -> '$; ways to change a dollar\n' -> !OUT::write\n100000 -> makeChange&{coins: [1,5,10,25,50,100]} -> '$; ways to change 1000 dollars with all coins\n' -> !OUT::write\n", "language": "Tailspin" }, { "code": "package require Tcl 8.5\n\nproc makeChange {amount coins} {\n set table [lrepeat [expr {$amount+1}] [lrepeat [llength $coins] {}]]\n lset table 0 [lrepeat [llength $coins] 1]\n for {set i 1} {$i <= $amount} {incr i} {\n\tfor {set j 0} {$j < [llength $coins]} {incr j} {\n\t set k [expr {$i - [lindex $coins $j]}]\n\t lset table $i $j [expr {\n\t\t($k < 0 ? 0 : [lindex $table $k $j]) +\n\t\t($j < 1 ? 0 : [lindex $table $i [expr {$j-1}]])\n\t }]\n\t}\n }\n return [lindex $table end end]\n}\n\nputs [makeChange 100 {1 5 10 25}]\nputs [makeChange 100000 {1 5 10 25 50 100}]\n# Making change with the EU coin set:\nputs [makeChange 100 {1 2 5 10 20 50 100 200}]\nputs [makeChange 100000 {1 2 5 10 20 50 100 200}]\n", "language": "Tcl" }, { "code": "function count_change {\n local -i amount=$1 coin j\n local ways=(1)\n shift\n for coin; do\n for (( j=coin; j <= amount; j++ )); do\n let ways[j]=${ways[j]:-0}+${ways[j-coin]:-0}\n done\n done\n echo \"${ways[amount]}\"\n}\ncount_change 100 25 10 5 1\ncount_change 100000 100 50 25 10 5 1\n", "language": "UNIX-Shell" }, { "code": "function count_change {\n typeset -i amount=$1 coin j\n typeset ways\n set -A ways 1\n shift\n for coin; do\n for (( j=coin; j <= amount; j++ )); do\n let ways[j]=${ways[j]:-0}+${ways[j-coin]:-0}\n done\n done\n echo \"${ways[amount]}\"\n}\ncount_change 100 25 10 5 1\ncount_change 100000 100 50 25 10 5 1\n", "language": "UNIX-Shell" }, { "code": "function count_change {\n typeset -i amount=$1 coin j\n typeset ways\n set -A ways 1\n shift\n for coin; do\n let j=coin\n while (( j <= amount )); do\n let ways[j]=${ways[j]:-0}+${ways[j-coin]:-0}\n let j+=1\n done\n done\n echo \"${ways[amount]}\"\n}\ncount_change 100 25 10 5 1\n# (optional task exceeds a subscript limit in ksh88)\n", "language": "UNIX-Shell" }, { "code": "if [ $# -lt 2 ]; then\n set ${1-100} 25 10 5 1\nfi\namount=$1\nshift\nways_0=1\nfor coin in \"$@\"; do\n j=$coin\n while [ $j -le $amount ]; do\n d=`expr $j - $coin`\n eval \"ways_$j=\\`expr \\${ways_$j-0} + \\${ways_$d-0}\\`\"\n j=`expr $j + 1`\n done\ndone\neval \"echo \\$ways_$amount\"\n", "language": "UNIX-Shell" }, { "code": "fn main() {\n amount := 100\n println(\"amount: $amount; ways to make change: ${count_change(amount)}\")\n}\n\nfn count_change(amount int) i64 {\n\tif amount.str().count('0') > 4 {exit(-1)} // can be too slow\n return cc(amount, 4)\n}\n\nfn cc(amount int, kinds_of_coins int) i64 {\n if amount == 0 {return 1}\n else if amount < 0 || kinds_of_coins == 0 {return 0}\n return cc(amount, kinds_of_coins-1) +\n cc(amount - first_denomination(kinds_of_coins), kinds_of_coins)\n}\n\nfn first_denomination(kinds_of_coins int) int {\n match kinds_of_coins {\n\t\t1 {return 1}\n\t\t2 {return 5}\n\t\t3 {return 10}\n\t\t4 {return 25}\n\t\telse {exit(-2)}\n\t}\n\treturn kinds_of_coins\n}\n", "language": "V-(Vlang)" }, { "code": "fn main() {\n\tamount := 100\n\tcoins := [25, 10, 5, 1]\n\tprintln(\"amount: $amount; ways to make change: ${count(coins, amount)}\")\n}\n\nfn count(coins []int, amount int) int {\n\tmut ways := []int{len: amount + 1}\n\tways[0] = 1\n\tfor coin in coins {\n\t\tfor idx := coin; idx <= amount; idx++ {\n\t\t\tways[idx] += ways[idx - coin]\n\t\t}\n\t}\n\treturn ways[amount]\n}\n", "language": "V-(Vlang)" }, { "code": "Private Function coin_count(coins As Variant, amount As Long) As Variant 'return type will be Decimal\n 'sequence s = Repeat(0, amount + 1)\n Dim s As Variant\n ReDim s(amount + 1)\n Dim c As Integer\n s(1) = CDec(1)\n For c = 1 To UBound(coins)\n For n = coins(c) To amount\n s(n + 1) = CDec(s(n + 1) + s(n - coins(c) + 1))\n Next n\n Next c\n coin_count = s(amount + 1)\nEnd Function\nPublic Sub main2()\n Dim us_commons_coins As Variant\n 'The next line creates a base 1 array\n us_common_coins = [{25, 10, 5, 1}]\n Debug.Print coin_count(us_common_coins, 100)\n Dim us_coins As Variant\n us_coins = [{100,50,25, 10, 5, 1}]\n Debug.Print coin_count(us_coins, 100000)\nEnd Sub\n", "language": "VBA" }, { "code": "Function count(coins,m,n)\n\tReDim table(n+1)\n\ttable(0) = 1\n\ti = 0\n\tDo While i < m\n\t\tj = coins(i)\n\t\tDo While j <= n\n\t\t\ttable(j) = table(j) + table(j - coins(i))\n\t\t\tj = j + 1\n\t\tLoop\n\t\ti = i + 1\n\tLoop\n\tcount = table(n)\nEnd Function\n\n'testing\narr = Array(1,5,10,25)\nm = UBound(arr) + 1\nn = 100\nWScript.StdOut.WriteLine count(arr,m,n)\n", "language": "VBScript" }, { "code": "Option Explicit\n'----------------------------------------------------------------------\nPrivate Function coin_count(coins As Variant, amount As Long) As Variant\n'return type will be Decimal\nDim s() As Variant\nDim n As Long, c As Long\n\n ReDim s(amount + 1)\n s(1) = CDec(1)\n For c = LBound(coins) To UBound(coins)\n For n = coins(c) To amount\n s(n + 1) = CDec(s(n + 1) + s(n - coins(c) + 1))\n Next n\n Next c\n coin_count = s(amount + 1)\nEnd Function\n'----------------------------------------------------------------------\nSub Main()\nDim us_common_coins As Variant\nDim us_coins As Variant\n\n 'The next line creates 0-based array\n us_common_coins = Array(25, 10, 5, 1)\n Debug.Print coin_count(us_common_coins, 100)\n\n us_coins = Array(100, 50, 25, 10, 5, 1)\n Debug.Print coin_count(us_coins, 100000)\n\nEnd Sub\n", "language": "Visual-Basic" }, { "code": "import \"./big\" for BigInt\nimport \"./fmt\" for Fmt\n\nvar countCoins = Fn.new { |c, m, n|\n var table = List.filled(n + 1, null)\n table[0] = BigInt.one\n for (i in 1..n) table[i] = BigInt.zero\n for (i in 0...m) {\n for (j in c[i]..n) table[j] = table[j] + table[j-c[i]]\n }\n return table[n]\n}\n\nvar c = [1, 5, 10, 25, 50, 100]\nFmt.print(\"Ways to make change for $$1 using 4 coins = $,i\", countCoins.call(c, 4, 100))\nFmt.print(\"Ways to make change for $$1,000 using 6 coins = $,i\", countCoins.call(c, 6, 1000 * 100))\n", "language": "Wren" }, { "code": "fcn ways_to_make_change(x, coins=T(25,10,5,1)){\n if(not coins) return(0);\n if(x<0) return(0);\n if(x==0) return(1);\n ways_to_make_change(x, coins[1,*]) + ways_to_make_change(x - coins[0], coins)\n}\nways_to_make_change(100).println();\n", "language": "Zkl" }, { "code": "fcn make_change2(amount, coins){\n n, m := amount, coins.len();\n table := (0).pump(n+1,List, (0).pump(m,List().write,1).copy);\n foreach i,j in ([1..n],[0..m-1]){\n table[i][j] = (if(i<coins[j]) 0 else table[i-coins[j]][j]) +\n (if(j<1) 0 else table[i][j-1])\n }\n table[-1][-1]\n}\n\nprintln(make_change2( 100, T(1,5,10,25)));\nmake_change2(0d1000_00, T(1,5,10,25,50,100)) : \"%,d\".fmt(_).println();\n", "language": "Zkl" }, { "code": "10 LET amount=100\n20 GO SUB 1000\n30 STOP\n1000 LET nPennies=amount\n1010 LET nNickles=INT (amount/5)\n1020 LET nDimes=INT (amount/10)\n1030 LET nQuarters=INT (amount/25)\n1040 LET count=0\n1050 FOR p=0 TO nPennies\n1060 FOR n=0 TO nNickles\n1070 FOR d=0 TO nDimes\n1080 FOR q=0 TO nQuarters\n1090 LET s=p+n*5+d*10+q*25\n1100 IF s=100 THEN LET count=count+1\n1110 NEXT q\n1120 NEXT d\n1130 NEXT n\n1140 NEXT p\n1150 PRINT count\n1160 RETURN\n", "language": "ZX-Spectrum-Basic" } ]
Count-the-coins
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Cramer's_rule\nnote: Mathematics\n", "language": "00-META" }, { "code": "In [[wp:linear algebra|linear algebra]], [[wp:Cramer's rule|Cramer's rule]] is an explicit formula for the solution of a [[wp:system of linear equations|system of linear equations]] with as many equations as unknowns, valid whenever the system has a unique solution. It expresses the solution in terms of the determinants of the (square) coefficient matrix and of matrices obtained from it by replacing one column by the vector of right hand sides of the equations.\n\n\nGiven\n<big>\n: <math>\\left\\{\\begin{matrix}a_1x + b_1y + c_1z&= {\\color{red}d_1}\\\\a_2x + b_2y + c_2z&= {\\color{red}d_2}\\\\a_3x + b_3y + c_3z&= {\\color{red}d_3}\\end{matrix}\\right.</math>\n</big>\n\nwhich in matrix format is\n\n<big>\n: <math>\\begin{bmatrix} a_1 & b_1 & c_1 \\\\ a_2 & b_2 & c_2 \\\\ a_3 & b_3 & c_3 \\end{bmatrix}\\begin{bmatrix} x \\\\ y \\\\ z \\end{bmatrix}=\\begin{bmatrix} {\\color{red}d_1} \\\\ {\\color{red}d_2} \\\\ {\\color{red}d_3} \\end{bmatrix}.</math>\n</big>\n\nThen the values of <math>x, y</math> and <math>z</math> can be found as follows:\n\n<big>\n:<math>x = \\frac{\\begin{vmatrix} {\\color{red}d_1} & b_1 & c_1 \\\\ {\\color{red}d_2} & b_2 & c_2 \\\\ {\\color{red}d_3} & b_3 & c_3 \\end{vmatrix} } { \\begin{vmatrix} a_1 & b_1 & c_1 \\\\ a_2 & b_2 & c_2 \\\\ a_3 & b_3 & c_3 \\end{vmatrix}}, \\quad y = \\frac {\\begin{vmatrix} a_1 & {\\color{red}d_1} & c_1 \\\\ a_2 & {\\color{red}d_2} & c_2 \\\\ a_3 & {\\color{red}d_3} & c_3 \\end{vmatrix}} {\\begin{vmatrix} a_1 & b_1 & c_1 \\\\ a_2 & b_2 & c_2 \\\\ a_3 & b_3 & c_3 \\end{vmatrix}}, \\text{ and }z = \\frac { \\begin{vmatrix} a_1 & b_1 & {\\color{red}d_1} \\\\ a_2 & b_2 & {\\color{red}d_2} \\\\ a_3 & b_3 & {\\color{red}d_3} \\end{vmatrix}} {\\begin{vmatrix} a_1 & b_1 & c_1 \\\\ a_2 & b_2 & c_2 \\\\ a_3 & b_3 & c_3 \\end{vmatrix} }.</math>\n</big>\n\n\n;Task\nGiven the following system of equations:\n\n<big>\n:<math>\n\\begin{cases}\n2w-x+5y+z=-3 \\\\\n3w+2x+2y-6z=-32 \\\\\nw+3x+3y-z=-47 \\\\\n5w-2x-3y+3z=49 \\\\\n\\end{cases}\n</math>\n</big>\n\nsolve for <big><math>w</math>, <math>x</math>, <math>y</math></big> and <big><math>z</math></big>, using Cramer's rule.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F det(mm)\n V m = copy(mm)\n V result = 1.0\n\n L(j) 0 .< m.len\n V imax = j\n L(i) j + 1 .< m.len\n I m[i][j] > m[imax][j]\n imax = i\n\n I imax != j\n swap(&m[imax], &m[j])\n result = -result\n\n I abs(m[j][j]) < 1e-12\n R Float.infinity\n\n L(i) j + 1 .< m.len\n V mult = -m[i][j] / m[j][j]\n L(k) 0 .< m.len\n m[i][k] += mult * m[j][k]\n\n L(i) 0 .< m.len\n result *= m[i][i]\n R result\n\nF cramerSolve(aa, detA, b, col)\n V a = copy(aa)\n L(i) 0 .< a.len\n a[i][col] = b[i]\n R det(a) / detA\n\nV A = [[2.0, -1.0, 5.0, 1.0],\n [3.0, 2.0, 2.0, -6.0],\n [1.0, 3.0, 3.0, -1.0],\n [5.0, -2.0, -3.0, 3.0]]\n\nV B = [-3.0, -32.0, -47.0, 49.0]\n\nV detA = det(A)\n\nL(i) 0 .< A.len\n print(‘#3.3’.format(cramerSolve(A, detA, B, i)))\n", "language": "11l" }, { "code": "with Ada.Text_IO;\nwith Ada.Numerics.Generic_Real_Arrays;\n\nprocedure Cramers_Rules is\n\n type Real is new Float;\n -- This is the type we want to use in the matrix and vector\n\n package Real_Arrays is\n new Ada.Numerics.Generic_Real_Arrays (Real);\n\n use Real_Arrays;\n\n function Solve_Cramer (M : in Real_Matrix;\n V : in Real_Vector)\n return Real_Vector\n is\n Denominator : Real;\n Nom_Matrix : Real_Matrix (M'Range (1),\n M'Range (2));\n Numerator : Real;\n Result : Real_Vector (M'Range (1));\n begin\n if\n M'Length (2) /= V'Length or\n M'Length (1) /= M'Length (2)\n then\n raise Constraint_Error with \"Dimensions does not match\";\n end if;\n\n Denominator := Determinant (M);\n\n for Col in V'Range loop\n Nom_Matrix := M;\n\n -- Substitute column\n for Row in V'Range loop\n Nom_Matrix (Row, Col) := V (Row);\n end loop;\n\n Numerator := Determinant (Nom_Matrix);\n Result (Col) := Numerator / Denominator;\n end loop;\n\n return Result;\n end Solve_Cramer;\n\n procedure Put (V : Real_Vector) is\n use Ada.Text_IO;\n package Real_IO is\n new Ada.Text_IO.Float_IO (Real);\n begin\n Put (\"[\");\n for E of V loop\n Real_IO.Put (E, Exp => 0, Aft => 2);\n Put (\" \");\n end loop;\n Put (\"]\");\n New_Line;\n end Put;\n\n M : constant Real_Matrix := ((2.0, -1.0, 5.0, 1.0),\n (3.0, 2.0, 2.0, -6.0),\n (1.0, 3.0, 3.0, -1.0),\n (5.0, -2.0, -3.0, 3.0));\n V : constant Real_Vector := (-3.0, -32.0, -47.0, 49.0);\n R : constant Real_Vector := Solve_Cramer (M, V);\nbegin\n Put (R);\nend Cramers_Rules;\n", "language": "Ada" }, { "code": "# returns the solution of a.x = b via Cramer's rule #\n# this is for REAL arrays, could define additional operators #\n# for INT, COMPL, etc. #\nPRIO CRAMER = 1;\nOP CRAMER = ( [,]REAL a, []REAL b )[]REAL:\n IF 1 UPB a /= 2 UPB a\n OR 1 LWB a /= 2 LWB a\n OR 1 UPB a /= UPB b\n THEN\n # the array sizes and bounds do not match #\n print( ( \"Invaid parameters to CRAMER\", newline ) );\n stop\n ELIF REAL deta = DET a;\n det a = 0\n THEN\n # a is singular #\n print( ( \"Singular matrix for CRAMER\", newline ) );\n stop\n ELSE\n # the arrays have matching bounds #\n [ LWB b : UPB b ]REAL result;\n FOR col FROM LWB b TO UPB b DO\n # form a matrix from a with the col'th column replaced by b #\n [ 1 LWB a : 1 UPB a, 2 LWB a : 2 UPB a ]REAL m := a;\n m[ : , col ] := b[ : AT 1 ];\n # col'th result elemet as per Cramer's rule #\n result[ col ] := DET m / det a\n OD;\n result\n FI; # CRAMER #\n\n# test CRAMER using the matrix and column vector specified in the task #\n[,]REAL a = ( ( 2, -1, 5, 1 )\n , ( 3, 2, 2, -6 )\n , ( 1, 3, 3, -1 )\n , ( 5, -2, -3, 3 )\n );\n[]REAL b = ( -3\n , -32\n , -47\n , 49\n );\n[]REAL solution = a CRAMER b;\nFOR c FROM LWB solution TO UPB solution DO\n print( ( \" \", fixed( solution[ c ], -8, 4 ) ) )\nOD;\nprint( ( newline ) )\n", "language": "ALGOL-68" }, { "code": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n int n;\n double **elems;\n} SquareMatrix;\n\nSquareMatrix init_square_matrix(int n, double elems[n][n]) {\n SquareMatrix A = {\n .n = n,\n .elems = malloc(n * sizeof(double *))\n };\n for(int i = 0; i < n; ++i) {\n A.elems[i] = malloc(n * sizeof(double));\n for(int j = 0; j < n; ++j)\n A.elems[i][j] = elems[i][j];\n }\n\n return A;\n}\n\nSquareMatrix copy_square_matrix(SquareMatrix src) {\n SquareMatrix dest;\n dest.n = src.n;\n dest.elems = malloc(dest.n * sizeof(double *));\n for(int i = 0; i < dest.n; ++i) {\n dest.elems[i] = malloc(dest.n * sizeof(double));\n for(int j = 0; j < dest.n; ++j)\n dest.elems[i][j] = src.elems[i][j];\n }\n\n return dest;\n}\n\ndouble det(SquareMatrix A) {\n double det = 1;\n\n for(int j = 0; j < A.n; ++j) {\n int i_max = j;\n for(int i = j; i < A.n; ++i)\n if(A.elems[i][j] > A.elems[i_max][j])\n i_max = i;\n\n if(i_max != j) {\n for(int k = 0; k < A.n; ++k) {\n double tmp = A.elems[i_max][k];\n A.elems[i_max][k] = A.elems[j][k];\n A.elems[j][k] = tmp;\n }\n\n det *= -1;\n }\n\n if(abs(A.elems[j][j]) < 1e-12) {\n puts(\"Singular matrix!\");\n return NAN;\n }\n\n for(int i = j + 1; i < A.n; ++i) {\n double mult = -A.elems[i][j] / A.elems[j][j];\n for(int k = 0; k < A.n; ++k)\n A.elems[i][k] += mult * A.elems[j][k];\n }\n }\n\n for(int i = 0; i < A.n; ++i)\n det *= A.elems[i][i];\n\n return det;\n}\n\nvoid deinit_square_matrix(SquareMatrix A) {\n for(int i = 0; i < A.n; ++i)\n free(A.elems[i]);\n free(A.elems);\n}\n\ndouble cramer_solve(SquareMatrix A, double det_A, double *b, int var) {\n SquareMatrix tmp = copy_square_matrix(A);\n for(int i = 0; i < tmp.n; ++i)\n tmp.elems[i][var] = b[i];\n\n double det_tmp = det(tmp);\n deinit_square_matrix(tmp);\n\n return det_tmp / det_A;\n}\n\nint main(int argc, char **argv) {\n#define N 4\n double elems[N][N] = {\n { 2, -1, 5, 1},\n { 3, 2, 2, -6},\n { 1, 3, 3, -1},\n { 5, -2, -3, 3}\n };\n SquareMatrix A = init_square_matrix(N, elems);\n\n SquareMatrix tmp = copy_square_matrix(A);\n int det_A = det(tmp);\n deinit_square_matrix(tmp);\n\n double b[] = {-3, -32, -47, 49};\n\n for(int i = 0; i < N; ++i)\n printf(\"%7.3lf\\n\", cramer_solve(A, det_A, b, i));\n\n deinit_square_matrix(A);\n return EXIT_SUCCESS;\n}\n", "language": "C" }, { "code": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\nclass SubMatrix {\n const std::vector<std::vector<double>> *source;\n std::vector<double> replaceColumn;\n const SubMatrix *prev;\n size_t sz;\n int colIndex = -1;\n\npublic:\n SubMatrix(const std::vector<std::vector<double>> &src, const std::vector<double> &rc) : source(&src), replaceColumn(rc), prev(nullptr), colIndex(-1) {\n sz = replaceColumn.size();\n }\n\n SubMatrix(const SubMatrix &p) : source(nullptr), prev(&p), colIndex(-1) {\n sz = p.size() - 1;\n }\n\n SubMatrix(const SubMatrix &p, int deletedColumnIndex) : source(nullptr), prev(&p), colIndex(deletedColumnIndex) {\n sz = p.size() - 1;\n }\n\n int columnIndex() const {\n return colIndex;\n }\n void columnIndex(int index) {\n colIndex = index;\n }\n\n size_t size() const {\n return sz;\n }\n\n double index(int row, int col) const {\n if (source != nullptr) {\n if (col == colIndex) {\n return replaceColumn[row];\n } else {\n return (*source)[row][col];\n }\n } else {\n if (col < colIndex) {\n return prev->index(row + 1, col);\n } else {\n return prev->index(row + 1, col + 1);\n }\n }\n }\n\n double det() const {\n if (sz == 1) {\n return index(0, 0);\n }\n if (sz == 2) {\n return index(0, 0) * index(1, 1) - index(0, 1) * index(1, 0);\n }\n SubMatrix m(*this);\n double det = 0.0;\n int sign = 1;\n for (size_t c = 0; c < sz; ++c) {\n m.columnIndex(c);\n double d = m.det();\n det += index(0, c) * d * sign;\n sign = -sign;\n }\n return det;\n }\n};\n\nstd::vector<double> solve(SubMatrix &matrix) {\n double det = matrix.det();\n if (det == 0.0) {\n throw std::runtime_error(\"The determinant is zero.\");\n }\n\n std::vector<double> answer(matrix.size());\n for (int i = 0; i < matrix.size(); ++i) {\n matrix.columnIndex(i);\n answer[i] = matrix.det() / det;\n }\n return answer;\n}\n\nstd::vector<double> solveCramer(const std::vector<std::vector<double>> &equations) {\n int size = equations.size();\n if (std::any_of(\n equations.cbegin(), equations.cend(),\n [size](const std::vector<double> &a) { return a.size() != size + 1; }\n )) {\n throw std::runtime_error(\"Each equation must have the expected size.\");\n }\n\n std::vector<std::vector<double>> matrix(size);\n std::vector<double> column(size);\n for (int r = 0; r < size; ++r) {\n column[r] = equations[r][size];\n matrix[r].resize(size);\n for (int c = 0; c < size; ++c) {\n matrix[r][c] = equations[r][c];\n }\n }\n\n SubMatrix sm(matrix, column);\n return solve(sm);\n}\n\ntemplate<typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n auto it = v.cbegin();\n auto end = v.cend();\n\n os << '[';\n if (it != end) {\n os << *it++;\n }\n while (it != end) {\n os << \", \" << *it++;\n }\n\n return os << ']';\n}\n\nint main() {\n std::vector<std::vector<double>> equations = {\n { 2, -1, 5, 1, -3},\n { 3, 2, 2, -6, -32},\n { 1, 3, 3, -1, -47},\n { 5, -2, -3, 3, 49},\n };\n\n auto solution = solveCramer(equations);\n std::cout << solution << '\\n';\n\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class CramersRule\n{\n public static void Main() {\n var equations = new [] {\n new [] { 2, -1, 5, 1, -3 },\n new [] { 3, 2, 2, -6, -32 },\n new [] { 1, 3, 3, -1, -47 },\n new [] { 5, -2, -3, 3, 49 }\n };\n var solution = SolveCramer(equations);\n Console.WriteLine(solution.DelimitWith(\", \"));\n }\n\n public static int[] SolveCramer(int[][] equations) {\n int size = equations.Length;\n if (equations.Any(eq => eq.Length != size + 1)) throw new ArgumentException($\"Each equation must have {size+1} terms.\");\n int[,] matrix = new int[size, size];\n int[] column = new int[size];\n for (int r = 0; r < size; r++) {\n column[r] = equations[r][size];\n for (int c = 0; c < size; c++) {\n matrix[r, c] = equations[r][c];\n }\n }\n return Solve(new SubMatrix(matrix, column));\n }\n\n private static int[] Solve(SubMatrix matrix) {\n int det = matrix.Det();\n if (det == 0) throw new ArgumentException(\"The determinant is zero.\");\n\n int[] answer = new int[matrix.Size];\n for (int i = 0; i < matrix.Size; i++) {\n matrix.ColumnIndex = i;\n answer[i] = matrix.Det() / det;\n }\n return answer;\n }\n\n //Extension method from library.\n static string DelimitWith<T>(this IEnumerable<T> source, string separator = \" \") =>\n string.Join(separator ?? \" \", source ?? Empty<T>());\n\n private class SubMatrix\n {\n private int[,] source;\n private SubMatrix prev;\n private int[] replaceColumn;\n\n public SubMatrix(int[,] source, int[] replaceColumn) {\n this.source = source;\n this.replaceColumn = replaceColumn;\n this.prev = null;\n this.ColumnIndex = -1;\n Size = replaceColumn.Length;\n }\n\n private SubMatrix(SubMatrix prev, int deletedColumnIndex = -1) {\n this.source = null;\n this.prev = prev;\n this.ColumnIndex = deletedColumnIndex;\n Size = prev.Size - 1;\n }\n\n public int ColumnIndex { get; set; }\n public int Size { get; }\n\n public int this[int row, int column] {\n get {\n if (source != null) return column == ColumnIndex ? replaceColumn[row] : source[row, column];\n return prev[row + 1, column < ColumnIndex ? column : column + 1];\n }\n }\n\n public int Det() {\n if (Size == 1) return this[0, 0];\n if (Size == 2) return this[0, 0] * this[1, 1] - this[0, 1] * this[1, 0];\n SubMatrix m = new SubMatrix(this);\n int det = 0;\n int sign = 1;\n for (int c = 0; c < Size; c++) {\n m.ColumnIndex = c;\n int d = m.Det();\n det += this[0, c] * d * sign;\n sign = -sign;\n }\n return det;\n }\n\n public void Print() {\n for (int r = 0; r < Size; r++) {\n Console.WriteLine(Range(0, Size).Select(c => this[r, c]).DelimitWith(\", \"));\n }\n Console.WriteLine();\n }\n }\n\n}\n", "language": "C-sharp" }, { "code": "(defun minor (m col)\n (loop with dim = (1- (array-dimension m 0))\n with result = (make-array (list dim dim))\n for i from 1 to dim\n for r = (1- i)\n do (loop with c = 0\n for j to dim\n when (/= j col)\n do (setf (aref result r c) (aref m i j))\n (incf c))\n finally (return result)))\n\n(defun det (m)\n (assert (= (array-rank m) 2))\n (assert (= (array-dimension m 0) (array-dimension m 1)))\n (let ((dim (array-dimension m 0)))\n (if (= dim 1)\n (aref m 0 0)\n (loop for col below dim\n for sign = 1 then (- sign)\n sum (* sign (aref m 0 col) (det (minor m col)))))))\n\n(defun replace-column (m col values)\n (let* ((dim (array-dimension m 0))\n (result (make-array (list dim dim))))\n (dotimes (r dim result)\n (dotimes (c dim)\n (setf (aref result r c)\n (if (= c col) (aref values r) (aref m r c)))))))\n\n(defun solve (m v)\n (loop with dim = (array-dimension m 0)\n with det = (det m)\n for col below dim\n collect (/ (det (replace-column m col v)) det)))\n\n(solve #2A((2 -1 5 1)\n (3 2 2 -6)\n (1 3 3 -1)\n (5 -2 -3 3))\n #(-3 -32 -47 49))\n", "language": "Common-Lisp" }, { "code": "import std.array : array, uninitializedArray;\nimport std.range : iota;\nimport std.stdio : writeln;\nimport std.typecons : tuple;\n\nalias vector = double[4];\nalias matrix = vector[4];\n\nauto johnsonTrotter(int n) {\n auto p = iota(n).array;\n auto q = iota(n).array;\n auto d = uninitializedArray!(int[])(n);\n d[] = -1;\n auto sign = 1;\n int[][] perms;\n int[] signs;\n\n void permute(int k) {\n if (k >= n) {\n perms ~= p.dup;\n signs ~= sign;\n sign *= -1;\n return;\n }\n permute(k + 1);\n foreach (i; 0..k) {\n auto z = p[q[k] + d[k]];\n p[q[k]] = z;\n p[q[k] + d[k]] = k;\n q[z] = q[k];\n q[k] += d[k];\n permute(k + 1);\n }\n d[k] *= -1;\n }\n\n permute(0);\n return tuple!(\"sigmas\", \"signs\")(perms, signs);\n}\n\nauto determinant(matrix m) {\n auto jt = johnsonTrotter(m.length);\n auto sum = 0.0;\n foreach (i,sigma; jt.sigmas) {\n auto prod = 1.0;\n foreach (j,s; sigma) {\n prod *= m[j][s];\n }\n sum += jt.signs[i] * prod;\n }\n return sum;\n}\n\nauto cramer(matrix m, vector d) {\n auto divisor = determinant(m);\n auto numerators = uninitializedArray!(matrix[])(m.length);\n foreach (i; 0..m.length) {\n foreach (j; 0..m.length) {\n foreach (k; 0..m.length) {\n numerators[i][j][k] = m[j][k];\n }\n }\n }\n vector v;\n foreach (i; 0..m.length) {\n foreach (j; 0..m.length) {\n numerators[i][j][i] = d[j];\n }\n }\n foreach (i; 0..m.length) {\n v[i] = determinant(numerators[i]) / divisor;\n }\n return v;\n}\n\nvoid main() {\n matrix m = [\n [2.0, -1.0, 5.0, 1.0],\n [3.0, 2.0, 2.0, -6.0],\n [1.0, 3.0, 3.0, -1.0],\n [5.0, -2.0, -3.0, 3.0]\n ];\n vector d = [-3.0, -32.0, -47.0, 49.0];\n auto wxyz = cramer(m, d);\n writeln(\"w = \", wxyz[0], \", x = \", wxyz[1], \", y = \", wxyz[2], \", z = \", wxyz[3]);\n}\n", "language": "D" }, { "code": "proc det . a0[][] res .\n res = 1\n a[][] = a0[][]\n n = len a[][]\n for j to n\n imax = j\n for i = j + 1 to n\n if a[i][j] > a[imax][j]\n imax = i\n .\n .\n if imax <> j\n swap a[imax][] a[j][]\n res = -res\n .\n if abs a[j][j] < 1e-12\n print \"Singular matrix!\"\n res = 0 / 0\n return\n .\n for i = j + 1 to n\n mult = -a[i][j] / a[j][j]\n for k to n\n a[i][k] += mult * a[j][k]\n .\n .\n .\n for i to n\n res *= a[i][i]\n .\n.\nproc cramer_solve . a0[][] deta b[] col res .\n a[][] = a0[][]\n for i to len a[][]\n a[i][col] = b[i]\n .\n det a[][] d\n res = d / deta\n.\na[][] = [ [ 2 -1 5 1 ] [ 3 2 2 -6 ] [ 1 3 3 -1 ] [ 5 -2 -3 3 ] ]\nb[] = [ -3 -32 -47 49 ]\ndet a[][] deta\nfor i to len a[][]\n cramer_solve a[][] deta b[] i r\n print r\n.\n", "language": "EasyLang" }, { "code": "(lib 'matrix)\n(string-delimiter \"\")\n(define (cramer A B (X)) ;; --> vector X\n\t(define ∆ (determinant A))\n\t(for/vector [(i (matrix-col-num A))]\n\t\t(set! X (matrix-set-col! (array-copy A) i B))\n\t\t(// (determinant X) ∆)))\n\t\t\n(define (task)\n\t(define A (list->array\n \t'( 2 -1 5 1 3 2 2 -6 1 3 3 -1 5 -2 -3 3) 4 4))\n\t(define B #(-3 -32 -47 49))\n\t(writeln \"Solving A * X = B\")\n\t(array-print A)\n\t(writeln \"B = \" B)\n\t(writeln \"X = \" (cramer A B)))\n", "language": "EchoLisp" }, { "code": "USING: kernel math math.matrices.laplace prettyprint sequences ;\nIN: rosetta-code.cramers-rule\n\n: replace-col ( elt n seq -- seq' ) flip [ set-nth ] keep flip ;\n\n: solve ( m v -- seq )\n dup length <iota> [\n rot [ replace-col ] keep [ determinant ] bi@ /\n ] 2with map ;\n\n: cramers-rule-demo ( -- )\n {\n { 2 -1 5 1 }\n { 3 2 2 -6 }\n { 1 3 3 -1 }\n { 5 -2 -3 3 }\n }\n { -3 -32 -47 49 } solve . ;\n\nMAIN: cramers-rule-demo\n", "language": "Factor" }, { "code": " DATA A/2, -1, 5, 1\n 1 3, 2, 2, -6\n 2 1, 3, 3, -1\n 3 5, -2, -3, 3/\n", "language": "Fortran" }, { "code": " MODULE BAD IDEA\t!Employ Cramer's rule for solving A.x = b...\n INTEGER MSG\t!Might as well be here.\n CONTAINS\t\t!The details.\n SUBROUTINE SHOWMATRIX(A)\t!With nice vertical bars.\n DOUBLE PRECISION A(:,:)\t!The matrix.\n INTEGER R,N\t\t\t!Assistants.\n N = SIZE(A, DIM = 1)\t\t!Instead of passing an explicit parameter.\n DO R = 1,N\t\t\t!Work down the rows.\n WRITE (MSG,1) A(R,:)\t\t!Fling forth a row at a go.\n 1 FORMAT (\"|\",<N>F12.3,\"|\")\t\t!Bounded by bars.\n END DO\t\t\t!On to the next row.\n END SUBROUTINE SHOWMATRIX\t!Furrytran's default order is the transpose.\n\n RECURSIVE DOUBLE PRECISION FUNCTION DET(A)\t!Determine the determinant.\n DOUBLE PRECISION A(:,:)\t!The square matrix, order N.\n DOUBLE PRECISION MINOR(SIZE(A,DIM=1) - 1,SIZE(A,DIM=1) - 1)\t!Order N - 1.\n DOUBLE PRECISION D\t\t!A waystation.\n INTEGER C,N\t\t\t!Steppers.\n N = SIZE(A, DIM = 1)\t\t!Suplied via secret parameters.\n IF (N .LE. 0) THEN\t\t!This really ought not happen.\n STOP \"DET: null array!\"\t\t!But I'm endlessly suspicious.\n ELSE IF (N .NE. SIZE(A, DIM = 2)) THEN\t!And I'd rather have a decent message\n STOP \"DET: not a square array!\"\t!In place of a crashed run.\n ELSE IF (N .EQ. 1) THEN\t!Alright, now get on with it.\n DET = A(1,1)\t\t!This is really easy.\n ELSE\t\t\t\t!But otherwise,\n D = 0\t\t\t!Here we go.\n DO C = 1,N\t\t\t!Step along the columns of the first row.\n CALL FILLMINOR(C)\t\t\t!Produce the auxiliary array for each column.\n IF (MOD(C,2) .EQ. 0) THEN\t\t!Odd or even case?\n D = D - A(1,C)*DET(MINOR)\t!Even: subtract.\n ELSE\t\t\t\t!Otherwise,\n D = D + A(1,C)*DET(MINOR)\t!Odd: add.\n END IF\t\t\t\t!So much for that term.\n END DO\t\t\t!On to the next.\n DET = D\t\t!Declare the result.\n END IF\t!So much for that.\n CONTAINS\t!An assistant.\n SUBROUTINE FILLMINOR(CC)\t!Corresponding to A(1,CC).\n INTEGER CC\t!The column being omitted.\n INTEGER R\t!A stepper.\n DO R = 2,N\t\t!Ignoring the first row,\n MINOR(R - 1,1:CC - 1) = A(R,1:CC - 1)\t!Copy columns 1 to CC - 1. There may be none.\n MINOR(R - 1,CC:) = A(R,CC + 1:)\t\t!And from CC + 1 to N. There may be none.\n END DO\t\t!On to the next row.\n END SUBROUTINE FILLMINOR\t!Divide and conquer.\n END FUNCTION DET\t!Rather than mess with permutations.\n\n SUBROUTINE CRAMER(A,X,B)\t!Solve A.x = b, where A is a matrix...\nCareful! The array must be A(N,N), and not say A(100,100) of which only up to N = 6 are in use.\n DOUBLE PRECISION A(:,:)\t!A square matrix. I hope.\n DOUBLE PRECISION X(:),B(:)\t!Column matrices look rather like 1-D arrays.\n DOUBLE PRECISION AUX(SIZE(A,DIM=1),SIZE(A,DIM=1))\t!Can't say \"LIKE A\", as in pl/i, alas.\n DOUBLE PRECISION D\t!To be calculated once.\n INTEGER N\t\t!The order of the square matrix. I hope.\n INTEGER C\t\t!A stepper.\n N = SIZE(A, DIM = 1)\t!Alright, what's the order of battle?\n D = DET(A)\t\t!Once only.\n IF (D.EQ.0) STOP \"Cramer: zero determinant!\"\t!Surely, this won't happen...\n AUX = A\t\t!Prepare the assistant.\n DO C = 1,N\t\t!Step across the columns.\n IF (C.GT.1) AUX(1:N,C - 1) = A(1:N,C - 1)\t!Repair previous damage.\n AUX(1:N,C) = B(1:N)\t\t!Place the current damage.\n X(C) = DET(AUX)/D\t\t!The result!\n END DO\t\t!On to the next column.\n END SUBROUTINE CRAMER\t!This looks really easy!\n END MODULE BAD IDEA\t!But actually, it is a bad idea for N > 2.\n\n PROGRAM TEST\t!Try it and see.\n USE BAD IDEA\t!Just so.\n DOUBLE PRECISION, ALLOCATABLE ::A(:,:), B(:), X(:)\t!Custom work areas.\n INTEGER N,R\t!Assistants..\n INTEGER INF\t!An I/O unit.\n\n MSG = 6\t\t!Output.\n INF = 10\t\t!For reading test data.\n OPEN (INF,FILE=\"Test.dat\",STATUS=\"OLD\",ACTION=\"READ\")\t!As in this file..\n\nChew into the next problem.\n 10 IF (ALLOCATED(A)) DEALLOCATE(A)\t!First,\n IF (ALLOCATED(B)) DEALLOCATE(B)\t!Get rid of\n IF (ALLOCATED(X)) DEALLOCATE(X)\t!The hired help.\n READ (INF,*,END = 100) N\t\t!Since there is a new order.\n IF (N.LE.0) GO TO 100\t\t!Perhaps a final order.\n WRITE (MSG,11) N\t\t\t!Othewise, announce prior to acting.\n 11 FORMAT (\"Order \",I0,\" matrix A, as follows...\")\t!In case something goes wrong.\n ALLOCATE(A(N,N))\t\t\t!For instance,\n ALLOCATE(B(N))\t\t\t!Out of memory.\n ALLOCATE(X(N))\t\t\t!But otherwise, a tailored fit.\n DO R = 1,N\t\t\t!Now read in the values for the matrix.\n READ(INF,*,END=667,ERR=665) A(R,:),B(R)\t!One row of A at a go, followed by B's value.\n END DO\t\t\t\t!In free format.\n CALL SHOWMATRIX(A)\t\t!Show what we have managed to obtain.\n WRITE (MSG,12) \"In the scheme A.x = b, b = \",B\t!In case something goes wrong.\n 12 FORMAT (A,<N>F12.6)\t\t!How many would be too many?\n CALL CRAMER(A,X,B)\t\t!The deed!\n WRITE (MSG,12) \" Via Cramer's rule, x = \",X\t!The result!\n GO TO 10\t\t\t\t!And try for another test problem.\n\nComplaints.\n 665 WRITE (MSG,666) \"Format error\",R\t!I know where I came from.\n 666 FORMAT (A,\" while reading row \",I0,\"!\")\t!So I can refer to R.\n GO TO 100\t\t!So much for that.\n 667 WRITE (MSG,666) \"End-of-file\", R\t\t!Some hint as to where.\n\nClosedown.\n 100 WRITE (6,*) \"That was interesting.\"\t!Quite.\n END\t!Open files are closed, allocated memory is released.\n", "language": "Fortran" }, { "code": "Function determinant(matrix() As Double) As Double\n Dim As long n=Ubound(matrix,1),sign=1\n Dim As Double det=1,s=1\n Dim As Double b(1 To n,1 To n)\n For c As long=1 To n\n For d As long=1 To n\n b(c,d)=matrix(c,d)\n Next d\n Next c\n #macro pivot(num)\n For p1 As long = num To n - 1\n For p2 As long = p1 + 1 To n\n If Abs(b(p1,num))<Abs(b(p2,num)) Then\n sign=-sign\n For g As long=1 To n\n Swap b(p1,g),b(p2,g)\n Next g\n End If\n Next p2\n Next p1\n #endmacro\n For k As long=1 To n-1\n pivot(k)\n For row As long =k To n-1\n If b(row+1,k)=0 Then Exit For\n Var f=b(k,k)/b(row+1,k)\n s=s*f\n For g As long=1 To n\n b((row+1),g)=(b((row+1),g)*f-b(k,g))/f\n Next g\n Next row\n Next k\n For z As long=1 To n\n det=det*b(z,z)\n Next z\n Return sign*det\nEnd Function\n\n'CRAMER COLUMN SWAPS\nSub swapcolumn(m() As Double,c() As Double,_new() As Double,column As long)\n Redim _new(1 To Ubound(m,1),1 To Ubound(m,1))\n For x As long=1 To Ubound(m,1)\n For y As long=1 To Ubound(m,1)\n _new(x,y)=m(x,y)\n Next y\n Next x\n For z As long=1 To Ubound(m,1)\n _new(z,column)=c(z)\n Next z\nEnd Sub\n\nSub solve(mat() As Double,rhs() As Double,_out() As Double)\n redim _out(Lbound(mat,1) To Ubound(mat,1))\n Redim As Double result(Lbound(mat,1) To Ubound(mat,1),Lbound(mat,1) To Ubound(mat,1))\n Dim As Double maindeterminant=determinant(mat())\n If Abs(maindeterminant) < 1e-12 Then Print \"singular\":Exit Sub\n For column As Long=1 To Ubound(mat,1)\n swapcolumn(mat(),rhs(),result(),column)\n _out(column)= determinant(result())/maindeterminant\n Next\nEnd Sub\n\n\n\nDim As Double MainMat(1 To ...,1 To ...)={{2,-1,5,1}, _\n {3,2,2,-6}, _\n {1,3,3,-1}, _\n {5,-2,-3,3}}\n\nDim As Double rhs(1 To ...)={-3,-32,-47,49}\n\nRedim ans() As Double\nsolve(MainMat(),rhs(),ans())\n\nFor n As Long=1 To Ubound(ans)\n Print Csng(ans(n))\nNext\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n\n \"gonum.org/v1/gonum/mat\"\n)\n\nvar m = mat.NewDense(4, 4, []float64{\n 2, -1, 5, 1,\n 3, 2, 2, -6,\n 1, 3, 3, -1,\n 5, -2, -3, 3,\n})\n\nvar v = []float64{-3, -32, -47, 49}\n\nfunc main() {\n x := make([]float64, len(v))\n b := make([]float64, len(v))\n d := mat.Det(m)\n for c := range v {\n mat.Col(b, c, m)\n m.SetCol(c, v)\n x[c] = mat.Det(m) / d\n m.SetCol(c, b)\n }\n fmt.Println(x)\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"fmt\"\n\n \"github.com/skelterjohn/go.matrix\"\n)\n\nvar m = matrix.MakeDenseMatrixStacked([][]float64{\n {2, -1, 5, 1},\n {3, 2, 2, -6},\n {1, 3, 3, -1},\n {5, -2, -3, 3},\n})\n\nvar v = []float64{-3, -32, -47, 49}\n\nfunc main() {\n x := make([]float64, len(v))\n b := make([]float64, len(v))\n d := m.Det()\n for c := range v {\n m.BufferCol(c, b)\n m.FillCol(c, v)\n x[c] = m.Det() / d\n m.FillCol(c, b)\n }\n fmt.Println(x)\n}\n", "language": "Go" }, { "code": "class CramersRule {\n static void main(String[] args) {\n Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d),\n Arrays.asList(3d, 2d, 2d, -6d),\n Arrays.asList(1d, 3d, 3d, -1d),\n Arrays.asList(5d, -2d, -3d, 3d))\n List<Double> b = Arrays.asList(-3d, -32d, -47d, 49d)\n println(\"Solution = \" + cramersRule(mat, b))\n }\n\n private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n double denominator = matrix.determinant()\n List<Double> result = new ArrayList<>()\n for (int i = 0; i < b.size(); i++) {\n result.add(matrix.replaceColumn(b, i).determinant() / denominator)\n }\n return result\n }\n\n private static class Matrix {\n private List<List<Double>> matrix\n\n @Override\n String toString() {\n return matrix.toString()\n }\n\n @SafeVarargs\n Matrix(List<Double>... lists) {\n matrix = new ArrayList<>()\n for (List<Double> list : lists) {\n matrix.add(list)\n }\n }\n\n Matrix(List<List<Double>> mat) {\n matrix = mat\n }\n\n double determinant() {\n if (matrix.size() == 1) {\n return get(0, 0)\n }\n if (matrix.size() == 2) {\n return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0)\n }\n double sum = 0\n double sign = 1\n for (int i = 0; i < matrix.size(); i++) {\n sum += sign * get(0, i) * coFactor(0, i).determinant()\n sign *= -1\n }\n return sum\n }\n\n private Matrix coFactor(int row, int col) {\n List<List<Double>> mat = new ArrayList<>()\n for (int i = 0; i < matrix.size(); i++) {\n if (i == row) {\n continue\n }\n List<Double> list = new ArrayList<>()\n for (int j = 0; j < matrix.size(); j++) {\n if (j == col) {\n continue\n }\n list.add(get(i, j))\n }\n mat.add(list)\n }\n return new Matrix(mat)\n }\n\n private Matrix replaceColumn(List<Double> b, int column) {\n List<List<Double>> mat = new ArrayList<>()\n for (int row = 0; row < matrix.size(); row++) {\n List<Double> list = new ArrayList<>()\n for (int col = 0; col < matrix.size(); col++) {\n double value = get(row, col)\n if (col == column) {\n value = b.get(row)\n }\n list.add(value)\n }\n mat.add(list)\n }\n return new Matrix(mat)\n }\n\n private double get(int row, int col) {\n return matrix.get(row).get(col)\n }\n }\n}\n", "language": "Groovy" }, { "code": "import Data.Matrix\n\nsolveCramer :: (Ord a, Fractional a) => Matrix a -> Matrix a -> Maybe [a]\nsolveCramer a y\n | da == 0 = Nothing\n | otherwise = Just $ map (\\i -> d i / da) [1..n]\n where da = detLU a\n d i = detLU $ submatrix 1 n 1 n $ switchCols i (n+1) ay\n ay = a <|> y\n n = ncols a\n\ntask = solveCramer a y\n where a = fromLists [[2,-1, 5, 1]\n ,[3, 2, 2,-6]\n ,[1, 3, 3,-1]\n ,[5,-2,-3, 3]]\n y = fromLists [[-3], [-32], [-47], [49]]\n", "language": "Haskell" }, { "code": "s_permutations :: [a] -> [([a], Int)]\ns_permutations = flip zip (cycle [1, -1]) . (foldl aux [[]])\n where aux items x = do\n (f,item) <- zip (cycle [reverse,id]) items\n f (insertEv x item)\n insertEv x [] = [[x]]\n insertEv x l@(y:ys) = (x:l) : map (y:) (insertEv x ys)\n\nmult:: Num a => [[a]] -> [[a]] -> [[a]]\nmult uss vss = map ((\\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\\vs u -> map (u*) vs) vss) uss\n\nmatI::(Num a) => Int -> [[a]]\nmatI n = [ [fromIntegral.fromEnum $ i == j | i <- [1..n]] | j <- [1..n]]\n\nelemPos::[[a]] -> Int -> Int -> a\nelemPos ms i j = (ms !! i) !! j\n\nprod:: Num a => ([[a]] -> Int -> Int -> a) -> [[a]] -> [Int] -> a\nprod f ms = product.zipWith (f ms) [0..]\n\ns_determinant:: Num a => ([[a]] -> Int -> Int -> a) -> [[a]] -> [([Int],Int)] -> a\ns_determinant f ms = sum.map (\\(is,s) -> fromIntegral s * prod f ms is)\n\nelemCramerPos::Int -> Int -> [[a]] -> [[a]] -> Int -> Int -> a\nelemCramerPos l k ks ms i j = if j /= l then elemPos ms i j else elemPos ks i k\n\nsolveCramer:: [[Rational]] -> [[Rational]] -> [[Rational]]\nsolveCramer ms ks = xs\n where\n xs | d /= 0 = go (reverse [0..pred.length.head $ ks])\n | otherwise = []\n go (u:us) = foldl glue (col u) us\n glue us u = zipWith (\\ys (y:_) -> y:ys) us (col u)\n col k = map (\\l -> [(/d) $ s_determinant (elemCramerPos l k ks) ms ps]) $ ls\n ls = [0..pred.length $ ms]\n ps = s_permutations ls\n d = s_determinant elemPos ms ps\n\ntask::[[Rational]] -> [[Rational]] -> IO()\ntask a b = do\n let x = solveCramer a b\n let u = map (map fromRational) x\n let y = mult a x\n let identity = matI (length x)\n let a1 = solveCramer a identity\n let h = mult a a1\n let z = mult a1 b\n putStrLn \"a =\"\n mapM_ print a\n putStrLn \"b =\"\n mapM_ print b\n putStrLn \"solve: a * x = b => x = solveCramer a b =\"\n mapM_ print x\n putStrLn \"u = fromRationaltoDouble x =\"\n mapM_ print u\n putStrLn \"verification: y = a * x = mult a x =\"\n mapM_ print y\n putStrLn $ \"test: y == b = \"\n print $ y == b\n putStrLn \"identity matrix: identity =\"\n mapM_ print identity\n putStrLn \"find: a1 = inv(a) => solve: a * a1 = identity => a1 = solveCramer a identity =\"\n mapM_ print a1\n putStrLn \"verification: h = a * a1 = mult a a1 =\"\n mapM_ print h\n putStrLn $ \"test: h == identity = \"\n print $ h == identity\n putStrLn \"z = a1 * b = mult a1 b =\"\n mapM_ print z\n putStrLn \"test: z == x =\"\n print $ z == x\n\nmain = do\n let a = [[2,-1, 5, 1]\n ,[3, 2, 2,-6]\n ,[1, 3, 3,-1]\n ,[5,-2,-3, 3]]\n let b = [[-3], [-32], [-47], [49]]\n task a b\n", "language": "Haskell" }, { "code": "import Data.List\n\ndeterminant::(Fractional a, Ord a) => [[a]] -> a\ndeterminant ls = if null ls then 0 else pivot 1 (zip ls [(0::Int)..])\n where\n good rs ts = (abs.head.fst $ ts) <= (abs.head.fst $ rs)\n go us (vs,i) = if v == 0 then (ws,i) else (zipWith (\\x y -> y - x*v) us ws,i)\n where (v,ws) = (head $ vs,tail vs)\n change i (ys:zs) = map (\\xs -> if (==i).snd $ xs then ys else xs) zs\n pivot d [] = d\n pivot d zs@((_,j):ys) = if 0 == u then 0 else pivot e ws\n where\n e = if i == j then u*d else -u*d\n ((u:us),i) = foldl1 (\\rs ts -> if good rs ts then rs else ts) zs\n ws = map (go (map (/u) us)) $ if i == j then ys else change i zs\n\nsolveCramer::(Fractional a, Ord a) => [[a]] -> [[a]] -> [[a]]\nsolveCramer as bs = if 0 == d then [] else ans bs\n where\n d = determinant as\n ans = transpose.map go.transpose\n where\n ms = zip [0..] (transpose as)\n go us = [ (/d) $ determinant [if i /= j then vs else us | (j,vs) <- ms] | (i,_) <- ms]\n\nmatI::(Num a) => Int -> [[a]]\nmatI n = [ [fromIntegral.fromEnum $ i == j | i <- [1..n]] | j <- [1..n]]\n\nmult:: Num a => [[a]] -> [[a]] -> [[a]]\nmult uss vss = map ((\\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\\vs u -> map (u*) vs) vss) uss\n\ntask::[[Rational]] -> [[Rational]] -> IO()\ntask a b = do\n let x = solveCramer a b\n let u = map (map fromRational) x\n let y = mult a x\n let identity = matI (length x)\n let a1 = solveCramer a identity\n let h = mult a a1\n let z = mult a1 b\n putStrLn \"a =\"\n mapM_ print a\n putStrLn \"b =\"\n mapM_ print b\n putStrLn \"solve: a * x = b => x = solveCramer a b =\"\n mapM_ print x\n putStrLn \"u = fromRationaltoDouble x =\"\n mapM_ print u\n putStrLn \"verification: y = a * x = mult a x =\"\n mapM_ print y\n putStrLn $ \"test: y == b = \"\n print $ y == b\n putStrLn \"identity matrix: identity =\"\n mapM_ print identity\n putStrLn \"find: a1 = inv(a) => solve: a * a1 = identity => a1 = solveCramer a identity =\"\n mapM_ print a1\n putStrLn \"verification: h = a * a1 = mult a a1 =\"\n mapM_ print h\n putStrLn $ \"test: h == identity = \"\n print $ h == identity\n putStrLn \"z = a1 * b = mult a1 b =\"\n mapM_ print z\n putStrLn \"test: z == x =\"\n print $ z == x\n\nmain = do\n let a = [[2,-1, 5, 1]\n ,[3, 2, 2,-6]\n ,[1, 3, 3,-1]\n ,[5,-2,-3, 3]]\n let b = [[-3], [-32], [-47], [49]]\n task a b\n", "language": "Haskell" }, { "code": "cramer=:4 :0\n A=. x [ b=. y\n det=. -/ .*\n A %~&det (i.#A) b\"_`[`]}&.|:\"0 2 A\n)\n", "language": "J" }, { "code": "A=: _&\".;._2]t=: 0 :0\n 2 -1 5 1\n 3 2 2 -6\n 1 3 3 -1\n 5 -2 -3 3\n)\n\nb=: _3 _32 _47 49\n", "language": "J" }, { "code": " A cramer b\n2 _12 _4 1\n", "language": "J" }, { "code": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class CramersRule {\n\n public static void main(String[] args) {\n Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d),\n Arrays.asList(3d, 2d, 2d, -6d),\n Arrays.asList(1d, 3d, 3d, -1d),\n Arrays.asList(5d, -2d, -3d, 3d));\n List<Double> b = Arrays.asList(-3d, -32d, -47d, 49d);\n System.out.println(\"Solution = \" + cramersRule(mat, b));\n }\n\n private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n double denominator = matrix.determinant();\n List<Double> result = new ArrayList<>();\n for ( int i = 0 ; i < b.size() ; i++ ) {\n result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n }\n return result;\n }\n\n private static class Matrix {\n\n private List<List<Double>> matrix;\n\n @Override\n public String toString() {\n return matrix.toString();\n }\n\n @SafeVarargs\n public Matrix(List<Double> ... lists) {\n matrix = new ArrayList<>();\n for ( List<Double> list : lists) {\n matrix.add(list);\n }\n }\n\n public Matrix(List<List<Double>> mat) {\n matrix = mat;\n }\n\n public double determinant() {\n if ( matrix.size() == 1 ) {\n return get(0, 0);\n }\n if ( matrix.size() == 2 ) {\n return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n }\n double sum = 0;\n double sign = 1;\n for ( int i = 0 ; i < matrix.size() ; i++ ) {\n sum += sign * get(0, i) * coFactor(0, i).determinant();\n sign *= -1;\n }\n return sum;\n }\n\n private Matrix coFactor(int row, int col) {\n List<List<Double>> mat = new ArrayList<>();\n for ( int i = 0 ; i < matrix.size() ; i++ ) {\n if ( i == row ) {\n continue;\n }\n List<Double> list = new ArrayList<>();\n for ( int j = 0 ; j < matrix.size() ; j++ ) {\n if ( j == col ) {\n continue;\n }\n list.add(get(i, j));\n }\n mat.add(list);\n }\n return new Matrix(mat);\n }\n\n private Matrix replaceColumn(List<Double> b, int column) {\n List<List<Double>> mat = new ArrayList<>();\n for ( int row = 0 ; row < matrix.size() ; row++ ) {\n List<Double> list = new ArrayList<>();\n for ( int col = 0 ; col < matrix.size() ; col++ ) {\n double value = get(row, col);\n if ( col == column ) {\n value = b.get(row);\n }\n list.add(value);\n }\n mat.add(list);\n }\n return new Matrix(mat);\n }\n\n private double get(int row, int col) {\n return matrix.get(row).get(col);\n }\n\n }\n\n}\n", "language": "Java" }, { "code": "var matrix = [\n\t[2, -1, 5, 1],\n\t[3, 2, 2, -6],\n\t[1, 3, 3, -1],\n\t[5, -2, -3, 3]\n];\nvar freeTerms = [-3, -32, -47, 49];\n\nvar result = cramersRule(matrix,freeTerms);\nconsole.log(result);\n\n/**\n * Compute Cramer's Rule\n * @param {array} matrix x,y,z, etc. terms\n * @param {array} freeTerms\n * @return {array} solution for x,y,z, etc.\n */\nfunction cramersRule(matrix,freeTerms) {\n\tvar det = detr(matrix),\n\t\treturnArray = [],\n\t\ti,\n\t\ttmpMatrix;\n\n\tfor(i=0; i < matrix[0].length; i++) {\n\t\tvar tmpMatrix = insertInTerms(matrix, freeTerms,i)\n\t\treturnArray.push(detr(tmpMatrix)/det)\n\t}\n\treturn returnArray;\n}\n\n/**\n * Inserts single dimensional array into\n * @param {array} matrix multidimensional array to have ins inserted into\n * @param {array} ins single dimensional array to be inserted vertically into matrix\n * @param {array} at zero based offset for ins to be inserted into matrix\n * @return {array} New multidimensional array with ins replacing the at column in matrix\n */\nfunction insertInTerms(matrix, ins, at) {\n\tvar tmpMatrix = clone(matrix),\n\t\ti;\n\tfor(i=0; i < matrix.length; i++) {\n\t\ttmpMatrix[i][at] = ins[i];\n\t}\n\treturn tmpMatrix;\n}\n/**\n * Compute the determinate of a matrix. No protection, assumes square matrix\n * function borrowed, and adapted from MIT Licensed numericjs library (www.numericjs.com)\n * @param {array} m Input Matrix (multidimensional array)\n * @return {number} result rounded to 2 decimal\n */\nfunction detr(m) {\n\tvar ret = 1,\n\t\tk,\n\t\tA=clone(m),\n\t\tn=m[0].length,\n\t\talpha;\n\n\tfor(var j =0; j < n-1; j++) {\n\t\tk=j;\n\t\tfor(i=j+1;i<n;i++) { if(Math.abs(A[i][j]) > Math.abs(A[k][j])) { k = i; } }\n\t\tif(k !== j) {\n\t\t temp = A[k]; A[k] = A[j]; A[j] = temp;\n\t\t ret *= -1;\n\t\t}\n\t\tAj = A[j];\n\t\tfor(i=j+1;i<n;i++) {\n\t\t\tAi = A[i];\n alpha = Ai[j]/Aj[j];\n for(k=j+1;k<n-1;k+=2) {\n k1 = k+1;\n Ai[k] -= Aj[k]*alpha;\n Ai[k1] -= Aj[k1]*alpha;\n }\n if(k!==n) { Ai[k] -= Aj[k]*alpha; }\n }\n if(Aj[j] === 0) { return 0; }\n ret *= Aj[j];\n\t }\n return Math.round(ret*A[j][j]*100)/100;\n}\n\n/**\n * Clone two dimensional Array using ECMAScript 5 map function and EcmaScript 3 slice\n * @param {array} m Input matrix (multidimensional array) to clone\n * @return {array} New matrix copy\n */\nfunction clone(m) {\n\treturn m.map(function(a){return a.slice();});\n}\n", "language": "JavaScript" }, { "code": "# The minor of the input matrix after removing the specified row and column.\n# Assumptions: the input is square and the indices are hunky dory.\ndef minor(rowNum; colNum):\n . as $in\n | (length - 1) as $len\n | reduce range(0; $len) as $i (null;\n reduce range(0; $len) as $j (.;\n if $i < rowNum and $j < colNum\n then .[$i][$j] = $in[$i][$j]\n elif $i >= rowNum and $j < colNum\n then .[$i][$j] = $in[$i+1][$j]\n elif $i < rowNum and $j >= colNum\n then .[$i][$j] = $in[$i][$j+1]\n else .[$i][$j] = $in[$i+1][$j+1]\n end) );\n\n# The determinant using Laplace expansion.\n# Assumption: the matrix is square\ndef det:\n . as $a\n | length as $nr\n | if $nr == 1 then .[0][0]\n elif $nr == 2 then .[1][1] * .[0][0] - .[0][1] * .[1][0]\n else reduce range(0; $nr) as $i (\n { sign: 1, sum: 0 };\n ($a|minor(0; $i)) as $m\n | .sum += .sign * $a[0][$i] * ($m|det)\n | .sign *= -1 )\n | .sum\n end ;\n\n# Solve A X = D using Cramer's method\n# a is assumed to be a JSON array representing the 2-d square matrix A\n# d is assumed to be a JSON array representing the 1-d vector D\ndef cramer(a; d):\n (a | length) as $n\n | (a | det) as $ad\n | if $ad == 0 then \"matrix determinant is 0\" | error\n else reduce range(0; $n) as $c (null;\n (reduce range(0; $n) as $r (a; .[$r][$c] = d[$r])) as $aa\n | .[$c] = ($aa|det) / $ad )\n end ;\n\ndef a: [\n [2, -1, 5, 1],\n [3, 2, 2, -6],\n [1, 3, 3, -1],\n [5, -2, -3, 3]\n];\n\ndef d:\n [ -3, -32, -47, 49 ] ;\n\n\"Solution is \\(cramer(a; d))\"\n", "language": "Jq" }, { "code": "function cramersolve(A::Matrix, b::Vector)\n return collect(begin B = copy(A); B[:, i] = b; det(B) end for i in eachindex(b)) ./ det(A)\nend\n\nA = [2 -1 5 1\n 3 2 2 -6\n 1 3 3 -1\n 5 -2 -3 3]\n\nb = [-3, -32, -47, 49]\n\n@show cramersolve(A, b)\n", "language": "Julia" }, { "code": "@show A \\ b\n", "language": "Julia" }, { "code": "// version 1.1.3\n\ntypealias Vector = DoubleArray\ntypealias Matrix = Array<Vector>\n\nfun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> {\n val p = IntArray(n) { it } // permutation\n val q = IntArray(n) { it } // inverse permutation\n val d = IntArray(n) { -1 } // direction = 1 or -1\n var sign = 1\n val perms = mutableListOf<IntArray>()\n val signs = mutableListOf<Int>()\n\n fun permute(k: Int) {\n if (k >= n) {\n perms.add(p.copyOf())\n signs.add(sign)\n sign *= -1\n return\n }\n permute(k + 1)\n for (i in 0 until k) {\n val z = p[q[k] + d[k]]\n p[q[k]] = z\n p[q[k] + d[k]] = k\n q[z] = q[k]\n q[k] += d[k]\n permute(k + 1)\n }\n d[k] *= -1\n }\n\n permute(0)\n return perms to signs\n}\n\nfun determinant(m: Matrix): Double {\n val (sigmas, signs) = johnsonTrotter(m.size)\n var sum = 0.0\n for ((i, sigma) in sigmas.withIndex()) {\n var prod = 1.0\n for ((j, s) in sigma.withIndex()) prod *= m[j][s]\n sum += signs[i] * prod\n }\n return sum\n}\n\nfun cramer(m: Matrix, d: Vector): Vector {\n val divisor = determinant(m)\n val numerators = Array(m.size) { Matrix(m.size) { m[it].copyOf() } }\n val v = Vector(m.size)\n for (i in 0 until m.size) {\n for (j in 0 until m.size) numerators[i][j][i] = d[j]\n }\n for (i in 0 until m.size) v[i] = determinant(numerators[i]) / divisor\n return v\n}\n\nfun main(args: Array<String>) {\n val m = arrayOf(\n doubleArrayOf(2.0, -1.0, 5.0, 1.0),\n doubleArrayOf(3.0, 2.0, 2.0, -6.0),\n doubleArrayOf(1.0, 3.0, 3.0, -1.0),\n doubleArrayOf(5.0, -2.0, -3.0, 3.0)\n )\n val d = doubleArrayOf(-3.0, -32.0, -47.0, 49.0)\n val (w, x, y, z) = cramer(m, d)\n println(\"w = $w, x = $x, y = $y, z = $z\")\n}\n", "language": "Kotlin" }, { "code": "local matrix = require \"matrix\" -- https://github.com/davidm/lua-matrix\n\nlocal function cramer(mat, vec)\n -- Check if matrix is quadratic\n assert(#mat == #mat[1], \"Matrix is not square!\")\n -- Check if vector has the same size of the matrix\n assert(#mat == #vec, \"Vector has not the same size of the matrix!\")\n\t\n local size = #mat\n local main_det = matrix.det(mat)\n\n local aux_mats = {}\n local dets = {}\n local result = {}\n for i = 1, size do\n -- Construct the auxiliary matrixes\n aux_mats[i] = matrix.copy(mat)\n for j = 1, size do\n aux_mats[i][j][i] = vec[j]\n end\n\n -- Calculate the auxiliary determinants\n dets[i] = matrix.det(aux_mats[i])\n\n -- Calculate results\n result[i] = dets[i]/main_det\n end\n\n return result\nend\n\n-----------------------------------------------\n\nlocal A = {{ 2, -1, 5, 1},\n { 3, 2, 2, -6},\n { 1, 3, 3, -1},\n { 5, -2, -3, 3}}\nlocal b = {-3, -32, -47, 49}\n\nlocal result = cramer(A, b)\nprint(\"Result: \" .. table.concat(result, \", \"))\n", "language": "Lua" }, { "code": "with(LinearAlgebra):\ncramer:=proc(A,B)\n local n,d,X,V,i;\n n:=upperbound(A,2);\n d:=Determinant(A);\n X:=Vector(n,0);\n for i from 1 to n do\n V:=A(1..-1,i);\n A(1..-1,i):=B;\n X[i]:=Determinant(A)/d;\n A(1..-1,i):=V;\n od;\n X;\nend:\n\nA:=Matrix([[2,-1,5,1],[3,2,2,-6],[1,3,3,-1],[5,-2,-3,3]]):\nB:=Vector([-3,-32,-47,49]):\nprintf(\"%a\",cramer(A,B));\n", "language": "Maple" }, { "code": "crule[m_, b_] := Module[{d = Det[m], a},\n Table[a = m; a[[All, k]] = b; Det[a]/d, {k, Length[m]}]]\n\ncrule[{\n {2, -1, 5, 1},\n {3, 2, 2, -6},\n {1, 3, 3, -1},\n {5, -2, -3, 3}\n } , {-3, -32, -47, 49}]\n", "language": "Mathematica" }, { "code": "(%i1) eqns: [ 2*w-x+5*y+z=-3, 3*w+2*x+2*y-6*z=-32, w+3*x+3*y-z=-47, 5*w-2*x-3*y+3*z=49];\n(%o1) [z + 5 y - x + 2 w = - 3, (- 6 z) + 2 y + 2 x + 3 w = - 32,\n (- z) + 3 y + 3 x + w = - 47, 3 z - 3 y - 2 x + 5 w = 49]\n(%i2) A: augcoefmatrix (eqns, [w,x,y,z]);\n [ 2 - 1 5 1 3 ]\n [ ]\n [ 3 2 2 - 6 32 ]\n(%o2) [ ]\n [ 1 3 3 - 1 47 ]\n [ ]\n [ 5 - 2 - 3 3 - 49 ]\n(%i3) C: coefmatrix(eqns, [w,x,y,z]);\n [ 2 - 1 5 1 ]\n [ ]\n [ 3 2 2 - 6 ]\n(%o3) [ ]\n [ 1 3 3 - 1 ]\n [ ]\n [ 5 - 2 - 3 3 ]\n(%i4) c[n]:= (-1)^(n+1) * determinant (submatrix (A,n))/determinant (C);\n n + 1\n (- 1) determinant(submatrix(A, n))\n(%o4) c := ---------------------------------------\n n determinant(C)\n(%i5) makelist (c[n],n,1,4);\n(%o5) [2, - 12, - 4, 1]\n(%i6) linsolve(eqns, [w,x,y,z]);\n(%o6) [w = 2, x = - 12, y = - 4, z = 1]\n", "language": "Maxima" }, { "code": "type\n SquareMatrix[N: static Positive] = array[N, array[N, float]]\n Vector[N: static Positive] = array[N, float]\n\n\n####################################################################################################\n# Templates.\n\ntemplate `[]`(m: SquareMatrix; i, j: Natural): float =\n ## Allow to get value of an element using m[i, j] syntax.\n m[i][j]\n\ntemplate `[]=`(m: var SquareMatrix; i, j: Natural; val: float) =\n ## Allow to set value of an element using m[i, j] syntax.\n m[i][j] = val\n\n#---------------------------------------------------------------------------------------------------\n\nfunc det(m: SquareMatrix): float =\n ## Return the determinant of matrix \"m\".\n\n var m = m\n result = 1\n\n for j in 0..m.high:\n var imax = j\n for i in (j + 1)..m.high:\n if m[i, j] > m[imax, j]:\n imax = i\n\n if imax != j:\n swap m[iMax], m[j]\n result = -result\n\n if abs(m[j, j]) < 1e-12:\n return NaN\n\n for i in (j + 1)..m.high:\n let mult = -m[i, j] / m[j, j]\n for k in 0..m.high:\n m[i, k] += mult * m[j, k]\n\n for i in 0..m.high:\n result *= m[i, i]\n\n#---------------------------------------------------------------------------------------------------\n\nfunc cramerSolve(a: SquareMatrix; detA: float; b: Vector; col: Natural): float =\n ## Apply Cramer rule on matrix \"a\", using vector \"b\" to replace column \"col\".\n\n when a.N != b.N:\n {.error: \"incompatible matrix and vector sizes\".}\n\n else:\n var a = a\n for i in 0..a.high:\n a[i, col] = b[i]\n result = det(a) / detA\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nimport strformat\n\nconst\n\n A: SquareMatrix[4] = [[2.0, -1.0, 5.0, 1.0],\n [3.0, 2.0, 2.0, -6.0],\n [1.0, 3.0, 3.0, -1.0],\n [5.0, -2.0, -3.0, 3.0]]\n\n B: Vector[4] = [-3.0, -32.0, -47.0, 49.0]\n\nlet detA = det(A)\nif detA == NaN:\n echo \"Singular matrix!\"\n quit(QuitFailure)\n\nfor i in 0..A.high:\n echo &\"{cramerSolve(A, detA, B, i):7.3f}\"\n", "language": "Nim" }, { "code": "M = [2,-1,5,1;3,2,2,-6;1,3,3,-1;5,-2,-3,3];\nV = Col([-3,-32,-47,49]);\n\nmatadjoint(M) * V / matdet(M)\n", "language": "PARI-GP" }, { "code": "use Math::Matrix;\n\nsub cramers_rule {\n my ($A, $terms) = @_;\n my @solutions;\n my $det = $A->determinant;\n foreach my $i (0 .. $#{$A}) {\n my $Ai = $A->clone;\n foreach my $j (0 .. $#{$terms}) {\n $Ai->[$j][$i] = $terms->[$j];\n }\n push @solutions, $Ai->determinant / $det;\n }\n @solutions;\n}\n\nmy $matrix = Math::Matrix->new(\n [2, -1, 5, 1],\n [3, 2, 2, -6],\n [1, 3, 3, -1],\n [5, -2, -3, 3],\n);\n\nmy $free_terms = [-3, -32, -47, 49];\nmy ($w, $x, $y, $z) = cramers_rule($matrix, $free_terms);\n\nprint \"w = $w\\n\";\nprint \"x = $x\\n\";\nprint \"y = $y\\n\";\nprint \"z = $z\\n\";\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #7060A8;\">requires</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"0.8.4\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #000000;\">javascript_semantics</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">inf</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1e300</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">1e300</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">nan</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-(</span><span style=\"color: #000000;\">inf</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">inf</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">det</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n\n <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i_max</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">j</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i_max</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">i_max</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">i</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">i_max</span> <span style=\"color: #0000FF;\">!=</span> <span style=\"color: #000000;\">j</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">aim</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i_max</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i_max</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">aim</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #0000FF;\"><</span> <span style=\"color: #000000;\">1e-12</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Singular matrix!\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">nan</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">mult</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">mult</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">cramer_solve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">det_a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">det</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">det_a</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #000000;\">b</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">32</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">47</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">49</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">det_a</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">det</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"%7.3f\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cramer_solve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">det_a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "removeElement([_|Tail], 0, Tail).\nremoveElement([Head|Tail], J, [Head|X]) :-\n J_2 is J - 1,\n removeElement(Tail, J_2, X).\n\nremoveColumn([], _, []).\nremoveColumn([Matrix_head|Matrix_tail], J, [X|Y]) :-\n removeElement(Matrix_head, J, X),\n removeColumn(Matrix_tail, J, Y).\n\nremoveRow([_|Matrix_tail], 0, Matrix_tail).\nremoveRow([Matrix_head|Matrix_tail], I, [Matrix_head|X]) :-\n I_2 is I - 1,\n removeRow(Matrix_tail, I_2, X).\n\ncofactor(Matrix, I, J, X) :-\n removeRow(Matrix, I, Matrix_2),\n removeColumn(Matrix_2, J, Matrix_3),\n det(Matrix_3, Y),\n X is (-1) ** (I + J) * Y.\n\ndet_summand(_, _, [], 0).\ndet_summand(Matrix, J, B, X) :-\n B = [B_head|B_tail],\n cofactor(Matrix, 0, J, Z),\n J_2 is J + 1,\n det_summand(Matrix, J_2, B_tail, Y),\n X is B_head * Z + Y.\n\ndet([[X]], X).\ndet(Matrix, X) :-\n Matrix = [Matrix_head|_],\n det_summand(Matrix, 0, Matrix_head, X).\n\nreplaceElement([_|Tail], 0, New, [New|Tail]).\nreplaceElement([Head|Tail], J, New, [Head|Y]) :-\n J_2 is J - 1,\n replaceElement(Tail, J_2, New, Y).\n\nreplaceColumn([], _, _, []).\nreplaceColumn([Matrix_head|Matrix_tail], J, [Column_head|Column_tail], [X|Y]) :-\n replaceElement(Matrix_head, J, Column_head, X),\n replaceColumn(Matrix_tail, J, Column_tail, Y).\n\ncramerElements(_, B, L, []) :- length(B, L).\ncramerElements(A, B, J, [X_J|Others]) :-\n replaceColumn(A, J, B, A_J),\n det(A_J, Det_A_J),\n det(A, Det_A),\n X_J is Det_A_J / Det_A,\n J_2 is J + 1,\n cramerElements(A, B, J_2, Others).\n\ncramer(A, B, X) :- cramerElements(A, B, 0, X).\n\nresults(X) :-\n A = [\n [2, -1, 5, 1],\n [3, 2, 2, -6],\n [1, 3, 3, -1],\n [5, -2, -3, 3]\n ],\n B = [-3, -32, -47, 49],\n cramer(A, B, X).\n", "language": "Prolog" }, { "code": "def det(m,n):\n if n==1: return m[0][0]\n z=0\n for r in range(n):\n k=m[:]\n del k[r]\n z+=m[r][0]*(-1)**r*det([p[1:]for p in k],n-1)\n return z\nw=len(t)\nd=det(h,w)\nif d==0:r=[]\nelse:r=[det([r[0:i]+[s]+r[i+1:]for r,s in zip(h,t)],w)/d for i in range(w)]\nprint(r)\n", "language": "Python" }, { "code": "#lang racket\n(require math/matrix)\n\n(define sys\n (matrix [[2 -1 5 1]\n [3 2 2 -6]\n [1 3 3 -1]\n [5 -2 -3 3]]))\n\n(define soln\n (col-matrix [-3 -32 -47 49]))\n\n(define (matrix-set-column M new-col idx)\n (matrix-augment (list-set (matrix-cols M) idx new-col)))\n\n(define (cramers-rule M soln)\n (let ([denom (matrix-determinant M)]\n [nvars (matrix-num-cols M)])\n (letrec ([roots (λ (position)\n (if (>= position nvars)\n '()\n (cons (/ (matrix-determinant\n (matrix-set-column M soln position))\n denom)\n (roots (add1 position)))))])\n (map cons '(w x y z) (roots 0)))))\n\n(cramers-rule sys soln)\n", "language": "Racket" }, { "code": "sub det(@matrix) {\n my @a = @matrix.map: { [|$_] };\n my $sign = 1;\n my $pivot = 1;\n for ^@a -> \\k {\n my @r = (k+1 ..^ @a);\n my $previous-pivot = $pivot;\n if 0 == ($pivot = @a[k;k]) {\n (my \\s = @r.first: { @a[$_;k] != 0 }) // return 0;\n (@a[s], @a[k]) = (@a[k], @a[s]);\n my $pivot = @a[k;k];\n $sign = -$sign;\n }\n for @r X @r -> (\\i,\\j) {\n ((@a[i;j] ×= $pivot) -= @a[i;k]×@a[k;j]) /= $previous-pivot;\n }\n }\n $sign × $pivot\n}\n\nsub cramers_rule(@A, @terms) {\n gather for ^@A -> \\i {\n my @Ai = @A.map: { [|$_] };\n for ^@terms -> \\j {\n @Ai[j;i] = @terms[j];\n }\n take det(@Ai);\n } »/» det(@A);\n}\n\nmy @matrix = (\n [2, -1, 5, 1],\n [3, 2, 2, -6],\n [1, 3, 3, -1],\n [5, -2, -3, 3],\n);\n\nmy @free_terms = <-3 -32 -47 49>;\nmy ($w, $x, $y, $z) = cramers_rule(@matrix, @free_terms);\n(\"w = $w\", \"x = $x\", \"y = $y\", \"z = $z\").join(\"\\n\").say;\n", "language": "Raku" }, { "code": "/* REXX Use Cramer's rule to compute solutions of given linear equations */\nNumeric Digits 20\nnames='w x y z'\nM=' 2 -1 5 1',\n ' 3 2 2 -6',\n ' 1 3 3 -1',\n ' 5 -2 -3 3'\nv=' -3',\n '-32',\n '-47',\n ' 49'\nCall mk_mat(m) /* M -> a.i.j */\nDo j=1 To dim /* Show the input */\n ol=''\n Do i=1 To dim\n ol=ol format(a.i.j,6)\n End\n ol=ol format(word(v,j),6)\n Say ol\n End\nSay copies('-',35)\n\nd=det(m) /* denominator determinant */\n\nDo k=1 To dim /* construct nominator matrix */\n Do j=1 To dim\n Do i=1 To dim\n If i=k Then\n b.i.j=word(v,j)\n Else\n b.i.j=a.i.j\n End\n End\n Call show_b\n d.k=det(mk_str()) /* numerator determinant */\n Say word(names,k) '=' d.k/d /* compute value of variable k */\n End\nExit\n\nmk_mat: Procedure Expose a. dim /* Turn list into matrix a.i.j */\n Parse Arg list\n dim=sqrt(words(list))\n k=0\n Do j=1 To dim\n Do i=1 To dim\n k=k+1\n a.i.j=word(list,k)\n End\n End\n Return\n\nmk_str: Procedure Expose b. dim /* Turn matrix b.i.j into list */\n str=''\nDo j=1 To dim\n Do i=1 To dim\n str=str b.i.j\n End\n End\nReturn str\n\nshow_b: Procedure Expose b. dim /* show numerator matrix */\n do j=1 To dim\n ol=''\n Do i=1 To dim\n ol=ol format(b.i.j,6)\n end\n Call dbg ol\n end\n Return\n\ndet: Procedure /* compute determinant */\nParse Arg list\nn=words(list)\ncall dbg 'det:' list\ndo dim=1 To 10\n If dim**2=n Then Leave\n End\ncall dbg 'dim='dim\nIf dim=2 Then Do\n det=word(list,1)*word(list,4)-word(list,2)*word(list,3)\n call dbg 'det=>'det\n Return det\n End\nk=0\nDo j=1 To dim\n Do i=1 To dim\n k=k+1\n a.i.j=word(list,k)\n End\n End\nDo j=1 To dim\n ol=j\n Do i=1 To dim\n ol=ol format(a.i.j,6)\n End\n call dbg ol\n End\ndet=0\nDo i=1 To dim\n ol=''\n Do j=2 To dim\n Do ii=1 To dim\n If ii<>i Then\n ol=ol a.ii.j\n End\n End\n call dbg 'i='i 'ol='ol\n If i//2 Then\n det=det+a.i.1*det(ol)\n Else\n det=det-a.i.1*det(ol)\n End\nCall dbg 'det=>>>'det\nReturn det\nsqrt: Procedure\n/* REXX ***************************************************************\n* EXEC to calculate the square root of a = 2 with high precision\n**********************************************************************/\n Parse Arg x,prec\n If prec<9 Then prec=9\n prec1=2*prec\n eps=10**(-prec1)\n k = 1\n Numeric Digits 3\n r0= x\n r = 1\n Do i=1 By 1 Until r=r0 | (abs(r*r-x)<eps)\n r0 = r\n r = (r + x/r) / 2\n k = min(prec1,2*k)\n Numeric Digits (k + 5)\n End\n Numeric Digits prec\n r=r+0\n Return r\n\n\ndbg: Return\n", "language": "REXX" }, { "code": "/*REXX program uses Cramer's rule to find and display solution of given linear equations*/\nvalues= '-3 -32 -47 49' /*values of each matrix row of numbers.*/\nvariables= substr('abcdefghijklmnopqrstuvwxyz', 27 - words(values) ) /*variable names.*/\ncall makeM ' 2 -1 5 1 3 2 2 -6 1 3 3 -1 5 -2 -3 3'\n do y=1 for sz; $= /*display the matrix (linear equations)*/\n do x=1 for sz; $= $ right(psign(@.x.y), w)'*'substr(variables, x, 1)\n end /*y*/ /* [↑] right─justify matrix elements.*/\n pad= left('', length($) - 2); say $ ' = ' right( word(values, y), wv)\n end /*x*/ /* [↑] obtain value of the equation. */\nsay; say\n do k=1 for sz /*construct the nominator matrix. */\n do j=1 for sz\n do i=1 for sz; if i==k then !.i.j= word(values, j)\n else !.i.j= @.i.j\n end /*i*/\n end /*j*/\n say pad substr(variables,k,1) ' = ' right(det(makeL())/det(mat), digits()+2)\n end /*k*/\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nmakeL: $=; do x=1 for sz; do y=1 for sz; $= $ !.x.y; end; end; return $ /*matrix─►list*/\nmSize: arg _; do sz=0 for 1e3; if sz*sz==_ then return; end; say 'error,bad matrix';exit 9\npsign: parse arg num; if left(num, 1)\\=='-' & x>1 then return \"+\"num; return num\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ndet: procedure; parse arg a b c d 1 nums; call mSize words(nums); _= 0\n if sz==2 then return a*d - b*c\n do j=1 for sz\n do i=1 for sz; _= _ + 1; @.i.j= word(nums, _)\n end /*i*/\n end\n aa= 0\n do i=1 for sz; odd= i//2; $=\n do j=2 for sz-1\n do k=1 for sz; if k\\==i then $= $ @.k.j\n end /*k*/\n end /*j*/\n aa= aa - (-1 ** odd) * @.i.1 * det($)\n end; /*i*/; return aa\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nmakeM: procedure expose @. values mat sz w wv; parse arg mat; call mSize words(mat)\n #= 0; wv= 0; w= 0\n do j=1 for sz; wv= max(wv, length( word( values, j) ) )\n do k=1 for sz; #= #+1; @.k.j= word(mat, #); w= max(w, length(@.k.j))\n end /*k*/\n end; /*j*/; w= w + 1; return\n", "language": "REXX" }, { "code": "require 'matrix'\n\ndef cramers_rule(a, terms)\n raise ArgumentError, \" Matrix not square\" unless a.square?\n cols = a.to_a.transpose\n cols.each_index.map do |i|\n c = cols.dup\n c[i] = terms\n Matrix.columns(c).det / a.det\n end\nend\n\nmatrix = Matrix[\n [2, -1, 5, 1],\n [3, 2, 2, -6],\n [1, 3, 3, -1],\n [5, -2, -3, 3],\n]\n\nvector = [-3, -32, -47, 49]\nputs cramers_rule(matrix, vector)\n", "language": "Ruby" }, { "code": "use std::ops::{Index, IndexMut};\n\nfn main() {\n let m = matrix(\n vec![\n 2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3.,\n ],\n 4,\n );\n let mm = m.solve(&vec![-3., -32., -47., 49.]);\n println!(\"{:?}\", mm);\n}\n\n#[derive(Clone)]\nstruct Matrix {\n elts: Vec<f64>,\n dim: usize,\n}\n\nimpl Matrix {\n // Compute determinant using cofactor method\n // Using Gaussian elimination would have been more efficient, but it also solves the linear\n // system, so…\n fn det(&self) -> f64 {\n match self.dim {\n 0 => 0.,\n 1 => self[0][0],\n 2 => self[0][0] * self[1][1] - self[0][1] * self[1][0],\n d => {\n let mut acc = 0.;\n let mut signature = 1.;\n for k in 0..d {\n acc += signature * self[0][k] * self.comatrix(0, k).det();\n signature *= -1.\n }\n acc\n }\n }\n }\n\n // Solve linear systems using Cramer's method\n fn solve(&self, target: &Vec<f64>) -> Vec<f64> {\n let mut solution: Vec<f64> = vec![0.; self.dim];\n let denominator = self.det();\n for j in 0..self.dim {\n let mut mm = self.clone();\n for i in 0..self.dim {\n mm[i][j] = target[i]\n }\n solution[j] = mm.det() / denominator\n }\n solution\n }\n\n // Compute the cofactor matrix for determinant computations\n fn comatrix(&self, k: usize, l: usize) -> Matrix {\n let mut v: Vec<f64> = vec![];\n for i in 0..self.dim {\n for j in 0..self.dim {\n if i != k && j != l {\n v.push(self[i][j])\n }\n }\n }\n matrix(v, self.dim - 1)\n }\n}\n\nfn matrix(elts: Vec<f64>, dim: usize) -> Matrix {\n assert_eq!(elts.len(), dim * dim);\n Matrix { elts, dim }\n}\n\nimpl Index<usize> for Matrix {\n type Output = [f64];\n\n fn index(&self, i: usize) -> &Self::Output {\n let m = self.dim;\n &self.elts[m * i..m * (i + 1)]\n }\n}\n\nimpl IndexMut<usize> for Matrix {\n fn index_mut(&mut self, i: usize) -> &mut Self::Output {\n let m = self.dim;\n &mut self.elts[m * i..m * (i + 1)]\n }\n}\n", "language": "Rust" }, { "code": "func cramers_rule(A, terms) {\n gather {\n for i in ^A {\n var Ai = A.map{.map{_}}\n for j in ^terms {\n Ai[j][i] = terms[j]\n }\n take(Ai.det)\n }\n } »/» A.det\n}\n\nvar matrix = [\n [2, -1, 5, 1],\n [3, 2, 2, -6],\n [1, 3, 3, -1],\n [5, -2, -3, 3],\n]\n\nvar free_terms = [-3, -32, -47, 49]\nvar (w, x, y, z) = cramers_rule(matrix, free_terms)...\n\nsay \"w = #{w}\"\nsay \"x = #{x}\"\nsay \"y = #{y}\"\nsay \"z = #{z}\"\n", "language": "Sidef" }, { "code": "package require math::linearalgebra\nnamespace path ::math::linearalgebra\n\n# Setting matrix to variable A and size to n\nset A [list { 2 -1 5 1} { 3 2 2 -6} { 1 3 3 -1} { 5 -2 -3 3}]\nset n [llength $A]\n# Setting right side of equation\nset right {-3 -32 -47 49}\n\n# Calculating determinant of A\nset detA [det $A]\n\n# Apply Cramer's rule\nfor {set i 0} {$i < $n} {incr i} {\n set tmp $A ;# copy A to tmp\n setcol tmp $i $right ;# replace column i with right side vector\n set detTmp [det $tmp] ;# calculate determinant of tmp\n set v [expr $detTmp / $detA] ;# divide two determinants\n puts [format \"%0.4f\" $v] ;# format and display result\n}\n", "language": "Tcl" }, { "code": "Sub CramersRule()\n OrigM = [{2, -1, 5, 1; 3,2,2,-6;1,3,3,-1;5,-2,-3,3}]\n OrigD = [{-3;-32;-47;49}]\n\n MatrixSize = UBound(OrigM)\n DetOrigM = WorksheetFunction.MDeterm(OrigM)\n\n For i = 1 To MatrixSize\n ChangeM = OrigM\n\n For j = 1 To MatrixSize\n ChangeM(j, i) = OrigD(j, 1)\n Next j\n\n DetChangeM = WorksheetFunction.MDeterm(ChangeM)\n Debug.Print i & \": \" & DetChangeM / DetOrigM\n Next i\nEnd Sub\n", "language": "VBA" }, { "code": "Imports System.Runtime.CompilerServices\nImports System.Linq.Enumerable\n\nModule Module1\n <Extension()>\n Function DelimitWith(Of T)(source As IEnumerable(Of T), Optional seperator As String = \" \") As String\n Return String.Join(seperator, source)\n End Function\n\n Private Class SubMatrix\n Private ReadOnly source As Integer(,)\n Private ReadOnly prev As SubMatrix\n Private ReadOnly replaceColumn As Integer()\n\n Public Sub New(source As Integer(,), replaceColumn As Integer())\n Me.source = source\n Me.replaceColumn = replaceColumn\n prev = Nothing\n ColumnIndex = -1\n Size = replaceColumn.Length\n End Sub\n\n Public Sub New(prev As SubMatrix, Optional deletedColumnIndex As Integer = -1)\n source = Nothing\n replaceColumn = Nothing\n Me.prev = prev\n ColumnIndex = deletedColumnIndex\n Size = prev.Size - 1\n End Sub\n\n Public Property ColumnIndex As Integer\n Public ReadOnly Property Size As Integer\n\n Default Public ReadOnly Property Index(row As Integer, column As Integer) As Integer\n Get\n If Not IsNothing(source) Then\n Return If(column = ColumnIndex, replaceColumn(row), source(row, column))\n Else\n Return prev(row + 1, If(column < ColumnIndex, column, column + 1))\n End If\n End Get\n End Property\n\n Public Function Det() As Integer\n If Size = 1 Then Return Me(0, 0)\n If Size = 2 Then Return Me(0, 0) * Me(1, 1) - Me(0, 1) * Me(1, 0)\n Dim m As New SubMatrix(Me)\n Dim detVal = 0\n Dim sign = 1\n For c = 0 To Size - 1\n m.ColumnIndex = c\n Dim d = m.Det()\n detVal += Me(0, c) * d * sign\n sign = -sign\n Next\n Return detVal\n End Function\n\n Public Sub Print()\n For r = 0 To Size - 1\n Dim rl = r\n Console.WriteLine(Range(0, Size).Select(Function(c) Me(rl, c)).DelimitWith(\", \"))\n Next\n Console.WriteLine()\n End Sub\n End Class\n\n Private Function Solve(matrix As SubMatrix) As Integer()\n Dim det = matrix.Det()\n If det = 0 Then Throw New ArgumentException(\"The determinant is zero.\")\n\n Dim answer(matrix.Size - 1) As Integer\n For i = 0 To matrix.Size - 1\n matrix.ColumnIndex = i\n answer(i) = matrix.Det() / det\n Next\n Return answer\n End Function\n\n Public Function SolveCramer(equations As Integer()()) As Integer()\n Dim size = equations.Length\n If equations.Any(Function(eq) eq.Length <> size + 1) Then Throw New ArgumentException($\"Each equation must have {size + 1} terms.\")\n Dim matrix(size - 1, size - 1) As Integer\n Dim column(size - 1) As Integer\n For r = 0 To size - 1\n column(r) = equations(r)(size)\n For c = 0 To size - 1\n matrix(r, c) = equations(r)(c)\n Next\n Next\n Return Solve(New SubMatrix(matrix, column))\n End Function\n\n Sub Main()\n Dim equations = {\n ({2, -1, 5, 1, -3}),\n ({3, 2, 2, -6, -32}),\n ({1, 3, 3, -1, -47}),\n ({5, -2, -3, 3, 49})\n }\n Dim solution = SolveCramer(equations)\n Console.WriteLine(solution.DelimitWith(\", \"))\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./matrix\" for Matrix\n\nvar cramer = Fn.new { |a, d|\n var n = a.numRows\n var x = List.filled(n, 0)\n var ad = a.det\n for (c in 0...n) {\n var aa = a.copy()\n for (r in 0...n) aa[r, c] = d[r, 0]\n x[c] = aa.det/ad\n }\n return x\n}\n\nvar a = Matrix.new([\n [2, -1, 5, 1],\n [3, 2, 2, -6],\n [1, 3, 3, -1],\n [5, -2, -3, 3]\n])\n\nvar d = Matrix.new([\n [- 3],\n [-32],\n [-47],\n [ 49]\n])\n\nvar x = cramer.call(a, d)\nSystem.print(\"Solution is %(x)\")\n", "language": "Wren" }, { "code": "func Det(A, N); \\Return value of determinate A, order N\nint A, N;\nint B, Sum, I, K, L, Term;\n[if N = 1 then return A(0, 0);\nB:= Reserve((N-1)*4\\IntSize\\);\nSum:= 0;\nfor I:= 0 to N-1 do\n [L:= 0;\n for K:= 0 to N-1 do\n if K # I then\n [B(L):= @A(K, 1); L:= L+1];\n Term:= A(I, 0) * Det(B, N-1);\n if I & 1 then Term:= -Term;\n Sum:= Sum + Term;\n ];\nreturn Sum;\n];\n\nreal D;\n[D:= float(Det([[2,-1,5,1], [3,2,2,-6], [1,3,3,-1], [5,-2,-3,3]], 4));\nRlOut(0, float(Det([[-3,-1,5,1], [-32,2,2,-6], [-47,3,3,-1], [49,-2,-3,3]], 4)) / D);\nRlOut(0, float(Det([[2,-3,5,1], [3,-32,2,-6], [1,-47,3,-1], [5,49,-3,3]], 4)) / D);\nRlOut(0, float(Det([[2,-1,-3,1], [3,2,-32,-6], [1,3,-47,-1], [5,-2,49,3]], 4)) / D);\nRlOut(0, float(Det([[2,-1,5,-3], [3,2,2,-32], [1,3,3,-47], [5,-2,-3,49]], 4)) / D);\n]\n", "language": "XPL0" }, { "code": "var [const] GSL=Import(\"zklGSL\");\t// libGSL (GNU Scientific Library)\nA:=GSL.Matrix(4,4).set(2,-1, 5, 1,\n\t\t 3, 2, 2,-6,\n\t\t 1, 3, 3,-1,\n\t\t 5,-2,-3, 3);\nb:=GSL.Vector(4).set(-3,-32,-47,49);\n", "language": "Zkl" }, { "code": "A.AxEQb(b).format().println();\n", "language": "Zkl" }, { "code": "fcn cramersRule(A,b){\n b.len().pump(GSL.Vector(b.len()),'wrap(i){ // put calculations into new Vector\n A.copy().setColumn(i,b).det();\n }).close()/A.det();\n}\ncramersRule(A,b).format().println();\n", "language": "Zkl" } ]
Cramers-rule
[ { "code": "---\ncategory:\n- Simple\nfrom: http://rosettacode.org/wiki/Create_a_file\nnote: File System Operations\n", "language": "00-META" }, { "code": "In this task, the job is to create a new empty file called \"output.txt\" of size 0 bytes\nand an empty directory called \"docs\". This should be done twice: once \"here\", i.e. in the current working directory and once in the filesystem root.\n\n", "language": "00-TASK" }, { "code": "L(directory) [‘/’, ‘./’]\n File(directory‘output.txt’, ‘w’) // create /output.txt, then ./output.txt\n fs:create_dir(directory‘docs’) // create directory /docs, then ./docs\n", "language": "11l" }, { "code": "echos > output.txt\nmkdir docs\n\nechos > \\output.txt\nmkdir \\docs\n", "language": "4DOS-Batch" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program createDirFic64.s */\n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n.equ MKDIRAT, 0x22 // Linux Syscall create directory\n.equ CHGDIR, 0x31 // Linux Syscall change directory\n\n/*******************************************/\n/* Initialized data */\n/*******************************************/\n.data\nszMessCreateDirOk: .asciz \"Create directory Ok.\\n\"\nszMessErrCreateDir: .asciz \"Unable create directory. \\n\"\nszMessErrChangeDir: .asciz \"Unable change directory. \\n\"\nszMessCreateFileOk: .asciz \"Create file Ok.\\n\"\nszMessErrCreateFile: .asciz \"Unable create file. \\n\"\nszMessErrCloseFile: .asciz \"Unable close file. \\n\"\n\nszNameDir: .asciz \"Dix1\"\nszNameFile: .asciz \"file1.txt\"\n\n/*******************************************/\n/* UnInitialized data */\n/*******************************************/\n.bss\n/*******************************************/\n/* code section */\n/*******************************************/\n.text\n.global main\nmain: // entry of program\n // create directory\n mov x0,AT_FDCWD\n ldr x1,qAdrszNameDir // directory name\n mov x2,0775 // mode (in octal zero is important !!)\n mov x8,MKDIRAT // code call system create directory\n svc 0 // call systeme\n cbnz x0,99f // error ?\n\n // display message ok directory\n ldr x0,qAdrszMessCreateDirOk\n bl affichageMess\n // change directory\n ldr x0,qAdrszNameDir // directory name\n mov x8, #CHGDIR // code call system change directory\n svc #0 // call systeme\n cbnz x0,98f // error ?\n // create file\n mov x0,AT_FDCWD // current directory\n ldr x1,qAdrszNameFile // directory name\n mov x2,O_CREAT|O_WRONLY // flags\n mov x3,0644 // this zone is Octal number (0 before)\n mov x8,OPEN // code call system open file\n svc #0 // call systeme\n cmp x0,#0 // error ?\n ble 97f\n mov x19,x0 // save File Descriptor\n // display message ok file\n ldr x0,qAdrszMessCreateFileOk\n bl affichageMess\n\n // close file\n mov x0,x19 // Fd\n mov x8,CLOSE // close file\n svc 0\n cbnz x0,96f // error ?\n mov x0,0 // return code Ok\n b 100f // end Ok\n96: // display error message close file\n ldr x0,qAdrszMessErrCloseFile\n bl affichageMess\n mov x0,1 // return code error\n b 100f\n97: // display error message create file\n ldr x0,qAdrszMessErrCreateFile\n bl affichageMess\n mov x0,1 // return code error\n b 100f\n98: // display error message change directory\n ldr x0,qAdrszMessErrChangeDir\n bl affichageMess\n mov x0,1 // return code error\n b 100f\n99: // display error message create directory\n ldr x0,qAdrszMessErrCreateDir\n bl affichageMess\n mov x0,1 // return code error\n b 100f\n100: // standard end of the program\n mov x8,EXIT // request to exit program\n svc 0 // perform the system call\nqAdrszMessCreateDirOk: .quad szMessCreateDirOk\nqAdrszMessErrCreateDir: .quad szMessErrCreateDir\nqAdrszMessErrChangeDir: .quad szMessErrChangeDir\nqAdrszMessCreateFileOk: .quad szMessCreateFileOk\nqAdrszNameFile: .quad szNameFile\nqAdrszMessErrCreateFile: .quad szMessErrCreateFile\nqAdrszMessErrCloseFile: .quad szMessErrCloseFile\nqAdrszNameDir: .quad szNameDir\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "PROC Dir(CHAR ARRAY filter)\n CHAR ARRAY line(255)\n BYTE dev=[1]\n\n Close(dev)\n Open(dev,filter,6)\n DO\n InputSD(dev,line)\n PrintE(line)\n IF line(0)=0 THEN\n EXIT\n FI\n OD\n Close(dev)\nRETURN\n\nPROC CreateFile(CHAR ARRAY fname)\n BYTE dev=[1]\n\n Close(dev)\n Open(dev,fname,8)\n Close(dev)\nRETURN\n\nPROC Main()\n CHAR ARRAY filter=\"D:*.*\", fname=\"D:OUTPUT.TXT\"\n\n PrintF(\"Dir \"\"%S\"\"%E\",filter)\n Dir(filter)\n\n PrintF(\"Create file \"\"%S\"\"%E%E\",fname)\n CreateFile(fname)\n\n PrintF(\"Dir \"\"%S\"\"%E\",filter)\n Dir(filter)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Streams.Stream_IO, Ada.Directories;\nuse Ada.Streams.Stream_IO, Ada.Directories;\n\nprocedure File_Creation is\n\n File_Handle : File_Type;\n\nbegin\n\n Create (File_Handle, Out_File, \"output.txt\");\n Close (File_Handle);\n Create_Directory(\"docs\");\n Create (File_Handle, Out_File, \"/output.txt\");\n Close (File_Handle);\n Create_Directory(\"/docs\");\n\nend File_Creation;\n", "language": "Ada" }, { "code": "var sout = openout (\"output.txt\") // in current dir\nsout.close()\n\nvar sout1 = openout (\"/output.txt\") // in root dir\nsout1.close()\n\nmkdir (\"docs\")\nmkdir (\"/docs\")\n", "language": "Aikido" }, { "code": "# Make a directory using the -mkdir- program\nvoid\nmkdir(text p)\n{\n sshell ss;\n\n b_cast(ss_path(ss), \"mkdir\");\n\n l_append(ss_argv(ss), \"mkdir\");\n l_append(ss_argv(ss), p);\n\n ss_link(ss);\n}\n\nvoid\ncreate_file(text p)\n{\n file f;\n\n f_open(f, p, OPEN_CREATE | OPEN_TRUNCATE | OPEN_WRITEONLY, 00644);\n}\n\nvoid\ncreate_pair(text prefix)\n{\n create_file(cat(prefix, \"output.txt\"));\n mkdir(cat(prefix, \"docs\"));\n}\n\ninteger\nmain(void)\n{\n create_pair(\"\");\n create_pair(\"/\");\n\n return 0;\n}\n", "language": "Aime" }, { "code": "main:(\n\n INT errno;\n\n PROC touch = (STRING file name)INT:\n BEGIN\n FILE actual file;\n INT errno := open(actual file, file name, stand out channel);\n IF errno NE 0 THEN GO TO stop touch FI;\n close(actual file); # detach the book and keep it #\n errno\n EXIT\n stop touch:\n errno\n END;\n\n errno := touch(\"input.txt\");\n errno := touch(\"/input.txt\");\n\n # ALGOL 68 has no concept of directories,\n however a file can have multiple pages,\n the pages are identified by page number only #\n\n PROC mkpage = (STRING file name, INT page x)INT:\n BEGIN\n FILE actual file;\n INT errno := open(actual file, file name, stand out channel);\n IF errno NE 0 THEN GO TO stop mkpage FI;\n set(actual file,page x,1,1); # skip to page x, line 1, character 1 #\n close(actual file); # detach the new page and keep it #\n errno\n EXIT\n stop mkpage:\n errno\n END;\n\n errno := mkpage(\"input.txt\",2);\n)\n", "language": "ALGOL-68" }, { "code": " 'output.txt' ⎕ncreate ¯1+⌊/0,⎕nnums\n '\\output.txt' ⎕ncreate ¯1+⌊/0,⎕nnums\n ⎕mkdir 'Docs'\n ⎕mkdir '\\Docs'\n", "language": "APL" }, { "code": "close (open for access \"output.txt\")\n", "language": "AppleScript" }, { "code": "tell application \"Finder\" to make new folder at startup disk with properties {name:\"docs\"}\n", "language": "AppleScript" }, { "code": "tell application \"Finder\" to set wd to target of window 1 as string\nclose (open for access wd & \"output.txt\")\n", "language": "AppleScript" }, { "code": "tell application \"Finder\" to make new folder at window 1 with properties {name:\"docs\"}\n", "language": "AppleScript" }, { "code": " 0 D$ = CHR$ (4): PRINT D$\"OPEN OUTPUT.TXT\": PRINT D$\"CLOSE\"\n", "language": "Applesoft-BASIC" }, { "code": "/* ARM assembly Raspberry PI */\n/* program createDirFic.s */\n\n/* Constantes */\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall exit Program\n.equ WRITE, 4 @ Linux syscall write FILE\n.equ MKDIR, 0x27 @ Linux Syscal create directory\n.equ CHGDIR, 0xC @ Linux Syscal change directory\n.equ CREATE, 0x8 @ Linux Syscal create file\n.equ CLOSE, 0x6 @ Linux Syscal close file\n/* Initialized data */\n.data\nszMessCreateDirOk: .asciz \"Create directory Ok.\\n\"\nszMessErrCreateDir: .asciz \"Unable create directory. \\n\"\nszMessErrChangeDir: .asciz \"Unable change directory. \\n\"\nszMessCreateFileOk: .asciz \"Create file Ok.\\n\"\nszMessErrCreateFile: .asciz \"Unable create file. \\n\"\nszMessErrCloseFile: .asciz \"Unable close file. \\n\"\n\nszNameDir: .asciz \"Dir1\"\nszNameFile: .asciz \"file1.txt\"\n\n\n/* UnInitialized data */\n.bss\n\n/* code section */\n.text\n.global main\nmain: @ entry of program\n push {fp,lr} @ saves registers\n\t@ create directory\n ldr r0,iAdrszNameDir @ directory name\n mov r1,#0775 @ mode (in octal zero is important !!)\n mov r7, #MKDIR @ code call system create directory\n swi #0 @ call systeme\n cmp r0,#0 @ error ?\n bne 99f\n\n @ display message ok directory\n ldr r0,iAdrszMessCreateDirOk\n bl affichageMess\n @ change directory\n ldr r0,iAdrszNameDir @ directory name\n mov r7, #CHGDIR @ code call system change directory\n swi #0 @ call systeme\n cmp r0,#0 @ error ?\n bne 98f\n @ create file\n ldr r0,iAdrszNameFile @ directory name\n mov r1,#0755 @ mode (in octal zero is important !!)\n mov r2,#0\n mov r7,#CREATE @ code call system create file\n swi #0 @ call systeme\n cmp r0,#0 @ error ?\n ble 97f\n mov r8,r0 @ save File Descriptor\n @ display message ok file\n ldr r0,iAdrszMessCreateFileOk\n bl affichageMess\n\n @ close file\n mov r0,r8 @ Fd\n mov r7, #CLOSE @ close file\n swi 0\n cmp r0,#0\n bne 96f\n @ end Ok\n b 100f\n96:\n @ display error message close file\n ldr r0,iAdrszMessErrCloseFile\n bl affichageMess\n b 100f\n97:\n @ display error message create file\n ldr r0,iAdrszMessErrCreateFile\n bl affichageMess\n b 100f\n98:\n @ display error message change directory\n ldr r0,iAdrszMessErrChangeDir\n bl affichageMess\n b 100f\n99:\n @ display error message create directory\n ldr r0,iAdrszMessErrCreateDir\n bl affichageMess\n b 100f\n100: @ standard end of the program\n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\niAdrszMessCreateDirOk:\t\t.int szMessCreateDirOk\niAdrszMessErrCreateDir:\t.int szMessErrCreateDir\niAdrszMessErrChangeDir:\t.int szMessErrChangeDir\niAdrszMessCreateFileOk:\t.int szMessCreateFileOk\niAdrszNameFile:\t\t\t\t.int szNameFile\niAdrszMessErrCreateFile:\t.int szMessErrCreateFile\niAdrszMessErrCloseFile:\t.int szMessErrCloseFile\n\niAdrszNameDir:\t\t\t\t.int szNameDir\n/******************************************************************/\n/* display text with size calculation */\n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {fp,lr} \t\t\t/* save registres */\n push {r0,r1,r2,r7} \t\t/* save others registers */\n mov r2,#0 \t\t\t\t/* counter length */\n1: \t/* loop length calculation */\n ldrb r1,[r0,r2] \t\t\t/* read octet start position + index */\n cmp r1,#0 \t\t\t/* if 0 its over */\n addne r2,r2,#1 \t\t\t/* else add 1 in the length */\n bne 1b \t\t\t/* and loop */\n /* so here r2 contains the length of the message */\n mov r1,r0 \t\t\t/* address message in r1 */\n mov r0,#STDOUT \t\t/* code to write to the standard output Linux */\n mov r7, #WRITE /* code call system \"write\" */\n swi #0 /* call systeme */\n pop {r0,r1,r2,r7} \t\t/* restaur others registers */\n pop {fp,lr} \t\t\t\t/* restaur des 2 registres */\n bx lr\t \t\t\t/* return */\n\t\n", "language": "ARM-Assembly" }, { "code": "output: \"output.txt\"\ndocs: \"docs\"\n\nwrite output \"\"\nwrite.directory docs ø\n\nwrite join.path [\"/\" output] \"\"\nwrite.directory join.path [\"/\" docs] ø\n", "language": "Arturo" }, { "code": "FileAppend,,output.txt\nFileCreateDir, docs\nFileAppend,,c:\\output.txt\nFileCreateDir, c:\\docs\n", "language": "AutoHotkey" }, { "code": "BEGIN {\n printf \"\" > \"output.txt\"\n close(\"output.txt\")\n printf \"\" > \"/output.txt\"\n close(\"/output.txt\")\n system(\"mkdir docs\")\n system(\"mkdir /docs\")\n}\n", "language": "AWK" }, { "code": "GetCalc(\"appvOUTPUT\",0)\n", "language": "Axe" }, { "code": "' Create file and dir\nTRAP LOCAL\n\nOPEN \"output.txt\" FOR WRITING AS afile\nCLOSE FILE afile\n\nCATCH GOTO report\nOPEN \"/output.txt\" FOR WRITING AS afile\nCLOSE FILE afile\n\nLABEL trydir\nMAKEDIR \"docs\"\n\nCATCH GOTO report2\nMAKEDIR \"/docs\"\nEND\n\nLABEL report\n PRINT ERR$(ERROR)\n GOTO trydir\n\nLABEL report2\n PRINT ERR$(ERROR)\n", "language": "BaCon" }, { "code": "OPEN \"output.txt\" FOR OUTPUT AS 1\nCLOSE\nOPEN \"\\output.txt\" FOR OUTPUT AS 1\nCLOSE\n", "language": "BASIC" }, { "code": "copy nul output.txt\ncopy nul \\output.txt\n", "language": "Batch-File" }, { "code": "md docs\nmd \\docs\n", "language": "Batch-File" }, { "code": " CLOSE #OPENOUT(\"output.txt\")\n CLOSE #OPENOUT(\"\\output.txt\")\n *MKDIR docs\n *MKDIR \\docs\n", "language": "BBC-BASIC" }, { "code": "global _start\n\n: syscall ( num:eax -- result:eax ) syscall ;\n\n: exit ( status:edi -- noret ) 60 syscall ;\n: bye ( -- noret ) 0 exit ;\n: die ( err:eax -- noret ) neg exit ;\n\n: unwrap ( result:eax -- value:eax ) dup 0 cmp ' die xl ;\n: ordie ( result -- ) unwrap drop ;\n\n: open ( pathname:edi flags:esi mode:edx -- fd:eax ) 2 syscall unwrap ;\n: close ( fd:edi -- ) 3 syscall ordie ;\n\n: mkdir ( pathname:edi mode:esi -- ) 83 syscall ordie ;\n\n00001 const for-writing\n00100 const create\n01000 const truncate\n\n: create-file ( pathname -- )\n\tcreate for-writing or truncate or\n\t0640 open close ;\n\n: make-directory ( pathname -- ) 0750 mkdir ;\n\n: create-output-file ( -- ) s\" output.txt\" drop create-file ;\n: make-docs-directory ( -- ) s\" docs\" drop make-directory ;\n\n: _start ( -- noret )\n\tcreate-output-file\n\tmake-docs-directory\n\tbye\n;\n", "language": "Blue" }, { "code": "\"output.txt\" •file.Chars \"\"\n\"/output.txt\" •file.Chars \"\"\n•file.CreateDir \"docs\"\n•file.CreateDir \"/docs\"\n", "language": "BQN" }, { "code": "put$(,\"output.txt\",NEW)\n", "language": "Bracmat" }, { "code": "fil$(\"output.txt\",w)\n", "language": "Bracmat" }, { "code": "fil$(,SET,-1)\n", "language": "Bracmat" }, { "code": "sys$\"mkdir docs\"\n", "language": "Bracmat" }, { "code": "sys$\"mkdir \\\\docs\"\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n\nint main() {\n FILE *fh = fopen(\"output.txt\", \"w\");\n fclose(fh);\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <sys/stat.h>\n#include <unistd.h>\n#include <fcntl.h>\n\nint main() { /* permissions are before umask */\n int fd = open(\"output.txt\", O_WRONLY|O_CREAT|O_TRUNC, 0640); /* rights 0640 for rw-r----- */\n /* or equivalently:\n int fd = creat(\"output.txt\", 0640); */ /* rights 0640 for rw-r----- */\n close(fd);\n\n mkdir(\"docs\", 0750); /* rights 0750 for rwxr-x--- */\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <direct.h>\n#include <io.h>\n#include <sys/stat.h>\n\nint main(void) {\n int f;\n\n f = _creat(\"output.txt\", _S_IWRITE);\n if (f == -1) {\n perror(\"Unable to create file\");\n } else {\n _close(f);\n }\n\n if (_mkdir(\"docs\") == -1) {\n perror(\"Unable to create directory\");\n }\n\n f = _creat(\"\\\\output.txt\", _S_IWRITE);\n if (f == -1) {\n perror(\"Unable to create file\");\n } else {\n _close(f);\n }\n\n if (_mkdir(\"\\\\docs\") == -1) {\n perror(\"Unable to create directory\");\n }\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <windows.h>\n#include <stdio.h>\n\nint main(void) {\n HANDLE hFile;\n\n hFile = CreateFile(\"output.txt\", GENERIC_WRITE, 0, NULL,\n CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n if (hFile == INVALID_HANDLE_VALUE) {\n printf(\"Unable to create file\\n\");\n } else {\n CloseHandle(hFile);\n }\n\n if (CreateDirectory(\"docs\", NULL) == 0) {\n printf(\"Unable to create directory\\n\");\n }\n\n hFile = CreateFile(\"\\\\output.txt\", GENERIC_WRITE, 0, NULL,\n CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n if (hFile == INVALID_HANDLE_VALUE) {\n printf(\"Unable to create file\\n\");\n } else {\n CloseHandle(hFile);\n }\n\n if (CreateDirectory(\"\\\\docs\", NULL) == 0) {\n printf(\"Unable to create directory\\n\");\n }\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <os2.h>\n\nint main(void) {\n ULONG Result, ActionTaken, hFile;\n\n Result = DosOpen(\"output.txt\", &hFile, &ActionTaken, 0L,\n FILE_NORMAL,\n OPEN_ACTION_REPLACE_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,\n OPEN_ACCESS_WRITEONLY | OPEN_SHARE_DENYREADWRITE,\n NULL);\n if (Result != 0) {\n printf(\"Unable to create file\\n\");\n } else {\n DosClose(hFile);\n }\n\n Result = DosMkDir(\"docs\", NULL);\n if (Result != 0) {\n printf(\"Unable to create directory\\n\");\n }\n\n Result = DosOpen(\"\\\\output.txt\", &hFile, &ActionTaken, 0L,\n FILE_NORMAL,\n OPEN_ACTION_REPLACE_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,\n OPEN_ACCESS_WRITEONLY | OPEN_SHARE_DENYREADWRITE,\n NULL);\n if (Result != 0) {\n printf(\"Unable to create file\\n\");\n } else {\n DosClose(hFile);\n }\n\n Result = DosMkDir(\"\\\\docs\", NULL);\n if (Result != 0) {\n printf(\"Unable to create directory\\n\");\n }\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <direct.h>\n#include <fstream>\n\nint main() {\n std::fstream f(\"output.txt\", std::ios::out);\n f.close();\n f.open(\"/output.txt\", std::ios::out);\n f.close();\n\n _mkdir(\"docs\");\n _mkdir(\"/docs\");\n\n return 0;\n}\n", "language": "C++" }, { "code": "#include <filesystem>\n#include <fstream>\n\nnamespace fs = std::filesystem;\n\nint main() {\n std::fstream f(\"output.txt\", std::ios::out);\n f.close();\n f.open(\"/output.txt\", std::ios::out);\n f.close();\n\n fs::create_directory(\"docs\");\n fs::create_directory(\"/docs\");\n}\n", "language": "C++" }, { "code": "using System;\nusing System.IO;\n\nclass Program {\n static void Main(string[] args) {\n File.Create(\"output.txt\");\n File.Create(@\"\\output.txt\");\n\n Directory.CreateDirectory(\"docs\");\n Directory.CreateDirectory(@\"\\docs\");\n }\n}\n", "language": "C-sharp" }, { "code": "FileIO text;\ntext.open(\"output.txt\", FileIO.WRITE);\n", "language": "ChucK" }, { "code": "(import '(java.io File))\n(.createNewFile (new File \"output.txt\"))\n(.mkdir (new File \"docs\"))\n(.createNewFile (File. (str (File/separator) \"output.txt\")))\n(.mkdir (File. (str (File/separator) \"docs\")))\n", "language": "Clojure" }, { "code": " identification division.\n program-id. create-a-file.\n\n data division.\n working-storage section.\n 01 skip pic 9 value 2.\n 01 file-name.\n 05 value \"/output.txt\".\n 01 dir-name.\n 05 value \"/docs\".\n 01 file-handle usage binary-long.\n\n procedure division.\n files-main.\n\n *> create in current working directory\n perform create-file-and-dir\n\n *> create in root of file system, will fail without privilege\n move 1 to skip\n perform create-file-and-dir\n\n goback.\n\n create-file-and-dir.\n *> create file in current working dir, for read/write\n call \"CBL_CREATE_FILE\" using file-name(skip:) 3 0 0 file-handle\n if return-code not equal 0 then\n display \"error: CBL_CREATE_FILE \" file-name(skip:) \": \"\n file-handle \", \" return-code upon syserr\n end-if\n\n *> create dir below current working dir, owner/group read/write\n call \"CBL_CREATE_DIR\" using dir-name(skip:)\n if return-code not equal 0 then\n display \"error: CBL_CREATE_DIR \" dir-name(skip:) \": \"\n return-code upon syserr\n end-if\n .\n\n end program create-a-file.\n", "language": "COBOL" }, { "code": "10 rem create a file\n20 open 10,8,10,\"0:output.txt,seq,write\"\n30 print#10,chr$(0)\n40 close 10\n50 rem check device status for error\n60 open 15,8,15:input#15,a,b$,c,d:print a;b$;c;d:close 15\n", "language": "Commodore-BASIC" }, { "code": "(let ((stream (open \"output.txt\" :direction :output)))\n (close stream))\n", "language": "Common-Lisp" }, { "code": "(with-open-file (stream \"output.txt\" :direction :output)\n ;; use the stream here\n )\n", "language": "Common-Lisp" }, { "code": "(let ((paths (list (make-pathname :directory '(:relative \"docs\"))\n (make-pathname :directory '(:absolute \"docs\")))))\n (mapcar #'ensure-directories-exist paths))\n", "language": "Common-Lisp" }, { "code": "(with-open-file\n (stream\n (make-pathname :directory '(:absolute \"\") :name \"output.txt\")\n :direction :output))\n", "language": "Common-Lisp" }, { "code": "(mapcar #'ensure-directories-exist '(#p\"docs/\" #p\"/docs/\")))\n", "language": "Common-Lisp" }, { "code": "MODULE CreateFile;\nIMPORT Files, StdLog;\n\nPROCEDURE Do*;\nVAR\n\tf: Files.File;\n\tres: INTEGER;\nBEGIN\n\tf := Files.dir.New(Files.dir.This(\"docs\"),Files.dontAsk);\n\tf.Register(\"output\",\"txt\",TRUE,res);\n\tf.Close();\n\t\n\tf := Files.dir.New(Files.dir.This(\"C:\\AEAT\\docs\"),Files.dontAsk);\n\tf.Register(\"output\",\"txt\",TRUE,res);\n\tf.Close()\nEND Do;\n\nEND CreateFile.\n", "language": "Component-Pascal" }, { "code": "File.write \"output.txt\", \"\"\nDir.mkdir \"docs\"\n\nFile.write \"/output.txt\", \"\"\nDir.mkdir \"/docs\"\n", "language": "Crystal" }, { "code": "module fileio ;\nimport std.stdio ;\nimport std.path ;\nimport std.file ;\nimport std.stream ;\n\nstring[] genName(string name){\n string cwd = curdir ~ sep ; // on current directory\n string root = sep ; // on root\n name = std.path.getBaseName(name) ;\n return [cwd ~ name, root ~ name] ;\n}\nvoid Remove(string target){\n if(exists(target)){\n if (isfile(target))\n std.file.remove(target);\n else\n std.file.rmdir(target) ;\n }\n}\nvoid testCreate(string filename, string dirname){\n // files:\n foreach(fn ; genName(filename))\n try{\n writefln(\"file to be created : %s\", fn) ;\n std.file.write(fn, cast(void[])null) ;\n writefln(\"\\tsuccess by std.file.write\") ; Remove(fn) ;\n (new std.stream.File(fn, FileMode.OutNew)).close() ;\n writefln(\"\\tsuccess by std.stream\") ; Remove(fn) ;\n } catch(Exception e) {\n writefln(e.msg) ;\n }\n // dirs:\n foreach(dn ; genName(dirname))\n try{\n writefln(\"dir to be created : %s\", dn) ;\n std.file.mkdir(dn) ;\n writefln(\"\\tsuccess by std.file.mkdir\") ; Remove(dn) ;\n } catch(Exception e) {\n writefln(e.msg) ;\n }\n}\nvoid main(){\n writefln(\"== test: File & Dir Creation ==\") ;\n testCreate(\"output.txt\", \"docs\") ;\n}\n", "language": "D" }, { "code": "! for d in . / ;do > \"$d/output.txt\" ; mkdir \"$d/docs\" ;done\n", "language": "Dc" }, { "code": "open/write output_file output.txt\nopen/write output_file [000000]output.txt\ncreate/directory [.docs]\ncreate/directory [000000.docs]\n", "language": "DCL" }, { "code": "program createFile;\n\n{$APPTYPE CONSOLE}\n\nuses\n Classes,\n SysUtils;\n\nconst\n filename = 'output.txt';\n\nvar\n cwdPath,\n fsPath: string;\n\n\n// Create empty file in current working directory\nfunction CreateEmptyFile1: Boolean;\nvar\n f: textfile;\nbegin\n // Make path to the file to be created\n cwdPath := ExtractFilePath(ParamStr(0)) + '1_'+filename;\n\n // Create file\n AssignFile(f,cwdPath);\n {$I-}\n Rewrite(f);\n {$I+}\n Result := IOResult = 0;\n CloseFile(f);\nend;\n\n// Create empty file in filesystem root\nfunction CreateEmptyFile2: Boolean;\nvar\n f: textfile;\nbegin\n // Make path to the file to be created\n fsPath := ExtractFileDrive(ParamStr(0)) + '\\' + '2_'+filename;\n\n // Create file\n AssignFile(f,fsPath);\n {$I-}\n Rewrite(f);\n {$I+}\n Result := IOResult = 0;\n CloseFile(f);\nend;\n\nfunction CreateEmptyFile3: Boolean;\nvar\n fs: TFileStream;\nbegin\n // Make path to the file to be created\n cwdPath := ExtractFilePath(ParamStr(0)) + '3_'+filename;\n\n // Create file\n fs := TFileStream.Create(cwdPath,fmCreate);\n fs.Free;\n Result := FileExists(cwdPath);\nend;\n\nfunction CreateEmptyFile4: Boolean;\nvar\n fs: TFileStream;\nbegin\n // Make path to the file to be created\n fsPath := ExtractFileDrive(ParamStr(0)) + '\\' + '4_'+filename;\n\n // Create file\n fs := TFileStream.Create(fsPath,fmCreate);\n fs.Free;\n Result := FileExists(fsPath);\nend;\n\nbegin\n if CreateEmptyFile1 then\n Writeln('File created at '+cwdPath)\n else\n Writeln('Error creating file at '+cwdPath);\n\n if CreateEmptyFile2 then\n Writeln('File created at '+fsPath)\n else\n Writeln('Error creating file at '+fsPath);\n\n if CreateEmptyFile3 then\n Writeln('File created at '+cwdPath)\n else\n Writeln('Error creating file at '+cwdPath);\n\n if CreateEmptyFile4 then\n Writeln('File created at '+fsPath)\n else\n Writeln('Error creating file at '+fsPath);\n\n // Keep console window open\n Readln;\nend.\n", "language": "Delphi" }, { "code": "<file:output.txt>.setBytes([])\n<file:docs>.mkdir(null)\n<file:///output.txt>.setBytes([])\n<file:///docs>.mkdir(null)\n", "language": "E" }, { "code": ";; The file system is the browser local storage\n;; It is divided into named stores (directories)\n;; \"user\" is the default (home) store\n\n; before : list of stores\n(local-stores) → (\"system\" \"user\" \"words\" \"reader\" \"info\" \"root\")\n\n(local-put-value \"output.txt\" \"\") → \"output.txt\" ; into \"user\"\n(local-make-store \"user/docs\") → \"user/docs\"\n(local-put-value \"output.txt\" \"\" \"root\") → \"output.txt\" ; into \"root\"\n(local-make-store 'root/docs) → \"root/docs\"\n\n; after : list of stores\n(local-stores 'root) → (\"root\" \"root/docs\")\n(local-stores 'user) → (\"user\" \"user/docs\")\n", "language": "EchoLisp" }, { "code": "import system'io;\n\npublic program()\n{\n File.assign(\"output.txt\").textwriter().close();\n\n File.assign(\"\\output.txt\").textwriter().close();\n\n Directory.assign(\"docs\").create();\n\n Directory.assign(\"\\docs\").create();\n}\n", "language": "Elena" }, { "code": "File.open(\"output.txt\", [:write])\nFile.open(\"/output.txt\", [:write])\n\nFile.mkdir!(\"docs\")\nFile.mkdir!(\"/docs\")\n", "language": "Elixir" }, { "code": "(make-empty-file \"output.txt\")\n(make-directory \"docs\")\n(make-empty-file \"/output.txt\")\n(make-directory \"/docs\")\n", "language": "Emacs-Lisp" }, { "code": "-module(new_file).\n-export([main/0]).\n\nmain() ->\n\tok = file:write_file( \"output.txt\", <<>> ),\n\tok = file:make_dir( \"docs\" ),\n\tok = file:write_file( filename:join([\"/\", \"output.txt\"]), <<>> ),\n\tok = file:make_dir( filename:join([\"/\", \"docs\"]) ).\n", "language": "Erlang" }, { "code": "PROGRAM FILE_TEST\n\n!$INCLUDE=\"PC.LIB\"\n\nBEGIN\n\n OPEN(\"O\",#1,\"output.txt\")\n CLOSE(1)\n\n OS_MKDIR(\"C:\\RC\") ! with the appropriate access rights .......\n OPEN(\"O\",#1,\"C:\\RC\\output.txt\")\n CLOSE(1)\n\nEND PROGRAM\n", "language": "ERRE" }, { "code": "integer fn\n\n-- In the current working directory\nsystem(\"mkdir docs\",2)\nfn = open(\"output.txt\",\"w\")\nclose(fn)\n\n-- In the filesystem root\nsystem(\"mkdir \\\\docs\",2)\nfn = open(\"\\\\output.txt\",\"w\")\nclose(fn)\n", "language": "Euphoria" }, { "code": "open System.IO\n\n[<EntryPoint>]\nlet main argv =\n let fileName = \"output.txt\"\n let dirName = \"docs\"\n for path in [\".\"; \"/\"] do\n ignore (File.Create(Path.Combine(path, fileName)))\n ignore (Directory.CreateDirectory(Path.Combine(path, dirName)))\n 0\n", "language": "F-Sharp" }, { "code": "USE: io.directories\n\n\"output.txt\" \"/output.txt\" [ touch-file ] bi@\n\"docs\" \"/docs\" [ make-directory ] bi@\n", "language": "Factor" }, { "code": "[\"/\", \"./\"] each: |dir| {\n # create '/docs', then './docs'\n Directory create: (dir ++ \"docs\")\n # create files /output.txt, then ./output.txt\n File open: (dir ++ \"output.txt\") modes: ['write] with: |f| {\n f writeln: \"hello, world!\"\n }\n}\n", "language": "Fancy" }, { "code": " s\" output.txt\" w/o create-file throw ( fileid) drop\ns\" /output.txt\" w/o create-file throw ( fileid) drop\n", "language": "Forth" }, { "code": "PROGRAM CREATION\nOPEN (UNIT=5, FILE=\"output.txt\", STATUS=\"NEW\") ! Current directory\nCLOSE (UNIT=5)\nOPEN (UNIT=5, FILE=\"/output.txt\", STATUS=\"NEW\") ! Root directory\nCLOSE (UNIT=5)\n\n!Directories (Use System from GNU Fortran Compiler)\n! -- Added by Anant Dixit, November 2014\ncall system(\"mkdir docs/\")\ncall system(\"mkdir ~/docs/\")\n\nEND PROGRAM\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\n' create empty file and sub-directory in current directory\nOpen \"output.txt\" For Output As #1\nClose #1\nMkDir \"docs\"\n\n' create empty file and sub-directory in root directory c:\\\n' creating file in root requires administrative privileges in Windows 10\nOpen \"c:\\output.txt\" For Output As #1\nClose #1\nMkDir \"c:\\docs\"\n\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "touch {/,}output.txt # create both /output.txt and output.txt\nmkdir {/,}docs # create both /docs and docs\n", "language": "Friendly-interactive-shell" }, { "code": "import io.File\n\nFile( 'output.txt' ).createNewFile()\nFile( File.separator + 'output.txt' ).createNewFile()\nFile( 'docs' ).mkdir()\nFile( File.separator + 'docs' ).mkdir()\n", "language": "FunL" }, { "code": "include \"NSLog.incl\"\n\nCFURLRef url\n\nurl = fn URLFileURLWithPath( fn StringByExpandingTildeInPath(@\"~/Desktop/output.txt\") )\nif (fn FileManagerCreateFileAtURL( url, NULL, NULL ) )\n NSLog( @\"File \\\"output.txt\\\" created.\" )\nelse\n NSLog( @\"Unable to create file \\\"output.txt\\\".\" )\nend if\n\nurl = fn URLFileURLWithPath( fn StringByExpandingTildeInPath(@\"~/Desktop/docs\") )\nif (fn FileManagerCreateDirectoryAtURL( url, YES, NULL ) )\n NSLog( @\"Directory \\\"docs\\\" created.\" )\nelse\n NSLog( @\"Unabled to create directory \\\"docs\\\".\" )\nend if\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\nDim byCount As Byte\nDim sToSave As String\n\nFor byCount = 0 To 50\n sToSave &= Format(Str(byCount), \"00\") & \" - Charlie was here!\" & gb.NewLine\nNext\n\nFile.Save(User.Home &/ \"TestFile\", sToSave)\nPrint File.Load(User.Home &/ \"TestFile\")\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"os\"\n)\n\nfunc createFile(fn string) {\n f, err := os.Create(fn)\n if err != nil {\n fmt.Println(err)\n return\n }\n fmt.Println(\"file\", fn, \"created!\")\n f.Close()\n}\n\nfunc createDir(dn string) {\n err := os.Mkdir(dn, 0666)\n if err != nil {\n fmt.Println(err)\n return\n }\n fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n createFile(\"input.txt\")\n createFile(\"/input.txt\")\n createDir(\"docs\")\n createDir(\"/docs\")\n}\n", "language": "Go" }, { "code": "new File(\"output.txt\").createNewFile()\nnew File(File.separator + \"output.txt\").createNewFile()\nnew File(\"docs\").mkdir()\nnew File(File.separator + \"docs\").mkdir()\n", "language": "Groovy" }, { "code": "import System.Directory\n\ncreateFile name = writeFile name \"\"\n\nmain = do\n createFile \"output.txt\"\n createDirectory \"docs\"\n createFile \"/output.txt\"\n createDirectory \"/docs\"\n", "language": "Haskell" }, { "code": "SYSTEM(DIR=\"\\docs\") ! create argument if not existent, make it current\nOPEN(FILE=\"output.txt\", \"NEW\") ! in current directory\n\nSYSTEM(DIR=\"C:\\docs\") ! create C:\\docs if not existent, make it current\nOPEN(FILE=\"output.txt\", \"NEW\") ! in C:\\docs\n", "language": "HicEst" }, { "code": "software {\n\tcreate(\"output.txt\")\n\tcreate(\"docs/\")\n\tcreate(\"/output.txt\")\n\tcreate(\"/docs/\")\n}\n", "language": "I" }, { "code": "every dir := ![\"./\",\"/\"] do {\n close(open(f := dir || \"input.txt\",\"w\")) |stop(\"failure for open \",f)\n mkdir(f := dir || \"docs\") |stop(\"failure for mkdir \",f)\n }\n", "language": "Icon" }, { "code": "'' 1!:2 <'/output.txt' NB. write an empty file\n 1!:5 <'/docs' NB. create a directory\n", "language": "J" }, { "code": "require 'files'\nNB. create two empty files named /output.txt and output.txt\n'' fwrite '/output.txt' ; 'output.txt'\n\nrequire 'general/dirutils' NB. addon package\nNB. create two directories: /docs and docs:\ndircreate '/docs' ; 'docs'\n", "language": "J" }, { "code": "import java.io.File;\nimport java.io.IOException;\n", "language": "Java" }, { "code": "void create() throws IOException {\n File file = new File(\"output.txt\");\n /* create an empty file */\n file.createNewFile();\n File directory = new File(\"docs/\");\n /* create all parent directories */\n directory.mkdirs();\n File rootDirectory = new File(\"/docs/\");\n rootDirectory.mkdirs();\n}\n", "language": "Java" }, { "code": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n", "language": "Java" }, { "code": "const fs = require('fs');\n\nfunction fct(err) {\n if (err) console.log(err);\n}\n\nfs.writeFile(\"output.txt\", \"\", fct);\nfs.writeFile(\"/output.txt\", \"\", fct);\n\nfs.mkdir(\"docs\", fct);\nfs.mkdir(\"/docs\", fct);\n", "language": "JavaScript" }, { "code": "// EXEC PGM=IEFBR14\n//* CREATE EMPTY FILE NAMED \"OUTPUT.TXT\" (file names upper case only)\n//ANYNAME DD UNIT=SYSDA,SPACE=(0,0),DSN=OUTPUT.TXT,DISP=(,CATLG)\n//* CREATE DIRECTORY (PARTITIONED DATA SET) NAMED \"DOCS\"\n//ANYNAME DD UNIT=SYSDA,SPACE=(TRK,(1,1)),DSN=DOCS,DISP=(,CATLG)\n", "language": "JCL" }, { "code": "# many I/O functions have UNIX names\n\ntouch(\"output.txt\")\nmkdir(\"docs\")\n\n# probably don't have permission\ntry\n touch(\"/output.txt\")\n mkdir(\"/docs\")\ncatch e\n warn(e)\nend\n", "language": "Julia" }, { "code": " \"output.txt\" 1: \"\"\n \"/output.txt\" 1: \"\"\n \\ mkdir docs\n \\ mkdir /docs\n", "language": "K" }, { "code": "/* testing on Windows 10 which needs administrative privileges\n to create files in the root */\n\nimport java.io.File\n\nfun main(args: Array<String>) {\n val filePaths = arrayOf(\"output.txt\", \"c:\\\\output.txt\")\n val dirPaths = arrayOf(\"docs\", \"c:\\\\docs\")\n var f: File\n for (path in filePaths) {\n f = File(path)\n if (f.createNewFile())\n println(\"$path successfully created\")\n else\n println(\"$path already exists\")\n }\n for (path in dirPaths) {\n f = File(path)\n if (f.mkdir())\n println(\"$path successfully created\")\n else\n println(\"$path already exists\")\n }\n}\n", "language": "Kotlin" }, { "code": "# Load the IO module\n# Replace \"<pathToIO.lm>\" with the location where the io.lm Lang module was installed to without \"<\" and \">\"\nln.loadModule(<pathToIO.lm>)\n\n$file1 = [[io]]::fp.openFile(output.txt)\n[[io]]::fp.createFile($file1)\n[[io]]::fp.closeFile($file1)\n\n$file2 = [[io]]::fp.openFile(/output.txt)\n[[io]]::fp.createFile($file2)\n[[io]]::fp.closeFile($file2)\n\n$dir1 = [[io]]::fp.openFile(docs)\n[[io]]::fp.makeDirectory($dir1)\n[[io]]::fp.closeFile($dir1)\n\n$dir2 = [[io]]::fp.openFile(/docs)\n[[io]]::fp.makeDirectory($dir2)\n[[io]]::fp.closeFile($dir2)\n", "language": "Lang" }, { "code": "// create file\nlocal(f) = file\nhandle => { #f->close }\n#f->openWriteOnly('output.txt')\n\n// make directory, just like a file\nlocal(d = dir('docs'))\n#d->create\n\n// create file in root file system (requires permissions at user OS level)\nlocal(f) = file\nhandle => { #f->close }\n#f->openWriteOnly('//output.txt')\n\n// create directory in root file system (requires permissions at user OS level)\nlocal(d = dir('//docs'))\n#d->create\n", "language": "Lasso" }, { "code": "(: file write_file '\"output.txt\" '\"Some data\")\n(: file make_dir '\"docs\")\n(: file write_file '\"/output.txt\" '\"Some data\")\n(: file make_dir '\"/docs\")\n", "language": "LFE" }, { "code": "nomainwin\n\nopen \"output.txt\" for output as #f\nclose #f\n\nresult = mkdir( \"F:\\RC\")\nif result <>0 then notice \"Directory not created!\": end\n\nopen \"F:\\RC\\output.txt\" for output as #f\nclose #f\n\nend\n", "language": "Liberty-BASIC" }, { "code": "-- note: fileIO xtra is shipped with Director, i.e. an \"internal\"\nfp = xtra(\"fileIO\").new()\nfp.createFile(\"output.txt\")\n", "language": "Lingo" }, { "code": "-- note: fileIO xtra is shipped with Director, i.e. an \"internal\"\npd = the last char of _movie.path -- \"\\\" for win, \":\" for mac\n_player.itemDelimiter = pd\nvol = _movie.path.item[1]\nfp = xtra(\"fileIO\").new()\nfp.createFile(vol&pd&\"output.txt\")\n", "language": "Lingo" }, { "code": "shell_cmd(\"mkdir Docs\") -- in cwd, both win and mac\nshell_cmd(\"mkdir \\Docs\") -- win\nshell_cmd(\"mkdir /Docs\") -- mac\n", "language": "Lingo" }, { "code": "void create_file(string path) {\n FILE f;\n unless (exists(path)) {\n unless (f = fopen(path, \"w\")){\n die(path);\n } else {\n puts(\"file ${path} created\");\n fclose(f);\n }\n } else {\n puts(\"File ${path} already exists\");\n }\n}\n\nvoid create_dir(string path) {\n unless (exists(path)) {\n unless(mkdir(path)) { //mkdir returns 0 on success, -1 on error\n puts(\"directory ${path} created\");\n } else {\n puts(stderr, \"Error: directory ${path} not created\");\n }\n } else {\n puts(\"directory ${path} already exists\");\n }\n}\n\ncreate_file(\"output.txt\");\ncreate_file(\"/tmp/output.txt\");\ncreate_dir(\"docs\");\ncreate_dir(\"/tmp/docs\");\n", "language": "Little" }, { "code": "io.open(\"output.txt\", \"w\"):close()\nio.open(\"\\\\output.txt\", \"w\"):close()\n", "language": "Lua" }, { "code": "os.execute(\"mkdir docs\")\nos.execute(\"mkdir \\\\docs\")\n", "language": "Lua" }, { "code": "require \"lfs\"\nlfs.mkdir(\"docs\")\nlfs.mkdir(\"/docs\")\n", "language": "Lua" }, { "code": "Module MakeDirAndFile {\n Def WorkingDir$, RootDir$\n If Drive$(Dir$)=\"Drive Fixed\" Then WorkingDir$=Dir$\n If Drive$(\"C:\\\")=\"Drive Fixed\" Then RootDir$=\"C:\\\"\n\n if WorkingDir$<>\"\" Then task(WorkingDir$)\n If RootDir$<>\"\" then task(RootDir$)\n Dir User ' return to user directory\n\n Sub task(WorkingDir$)\n Dir WorkingDir$\n If Not Exist.Dir(\"docs\") then SubDir \"docs\" : Dir WorkingDir$\n If Exist.Dir(\"docs\") Then Print str$(File.Stamp(\"docs\"), \"YYYY|MM|DD|hh:nn:ss\")\n Open \"output.txt\" For Output as #F\n Close #f\n If Exist(\"output.txt\") Then Print str$(File.Stamp(\"output.txt\"), \"YYYY|MM|DD|hh:nn:ss\")\n End Sub\n}\nMakeDirAndFile\n", "language": "M2000-Interpreter" }, { "code": "FileTools:-Text:-WriteFile(\"output.txt\", \"\"); # make empty file in current dir\nFileTools:-MakeDirectory(\"docs\"); # make empty dir in current dir\nFileTools:-Text:-WriteFile(\"/output.txt\", \"\"); # make empty file in root dir\nFileTools:-MakeDirectory(\"/docs\"); # make empty dir in root dir\n", "language": "Maple" }, { "code": "SetDirectory@NotebookDirectory[];\nt = OpenWrite[\"output.txt\"]\nClose[t]\ns = OpenWrite[First@FileNameSplit[$InstallationDirectory] <> \"\\\\output.txt\"]\nClose[s]\n\n(*In root directory*)\nCreateDirectory[\"\\\\docs\"]\n(*In current operating directory*)\nCreateDirectory[Directory[]<>\"\\\\docs\"]\n(*\"left<>right\" is shorthand for \"StringJoin[left,right]\"*)\n", "language": "Mathematica" }, { "code": "\tfid = fopen('output.txt','w'); fclose(fid);\n\tfid = fopen('/output.txt','w'); fclose(fid);\n\tmkdir('docs');\n\tmkdir('/docs');\n", "language": "MATLAB" }, { "code": "f: openw(\"/output.txt\");\nclose(f);\n\nf: openw(\"output.txt\");\nclose(f);\n\n/* Maxima has no function to create directories, but one can use the underlying Lisp system */\n\n:lisp (mapcar #'ensure-directories-exist '(\"docs/\" \"/docs/\"))\n", "language": "Maxima" }, { "code": "-- Here\nf = createFile \"output.txt\"\nclose f\nmakeDir (sysInfo.currentDir + \"\\docs\")\n-- System root\nf = createFile \"\\output.txt\"\nclose f\nmakeDir (\"c:\\docs\")\n", "language": "MAXScript" }, { "code": ":- module create_file.\n:- interface.\n\n:- import_module io.\n:- pred main(io::di, io::uo) is det.\n\n:- implementation.\n\n:- import_module dir.\n\nmain(!IO) :-\n create_file(\"output.txt\", !IO),\n create_file(\"/output.txt\", !IO),\n create_dir(\"docs\", !IO),\n create_dir(\"/docs\", !IO).\n\n:- pred create_file(string::in, io::di, io::uo) is det.\n\ncreate_file(FileName, !IO) :-\n io.open_output(FileName, Result, !IO),\n (\n Result = ok(File),\n io.close_output(File, !IO)\n ;\n Result = error(Error),\n print_io_error(Error, !IO)\n ).\n\n:- pred create_dir(string::in, io::di, io::uo) is det.\n\ncreate_dir(DirName, !IO) :-\n dir.make_single_directory(DirName, Result, !IO),\n (\n Result = ok\n ;\n Result = error(Error),\n print_io_error(Error, !IO)\n ).\n\n:- pred print_io_error(io.error::in, io::di, io::uo) is det.\n\nprint_io_error(Error, !IO) :-\n io.stderr_stream(Stderr, !IO),\n io.write_string(Stderr, io.error_message(Error), !IO),\n io.nl(Stderr, !IO),\n io.set_exit_status(1, !IO).\n", "language": "Mercury" }, { "code": "import java.io.File\n\nFile.new('output.txt').createNewFile()\nFile.new('docs').mkdir()\nFile.new(\"docs#{File.separator}output.txt\").createNewFile()\n", "language": "Mirah" }, { "code": "MODULE FileCreation EXPORTS Main;\n\nIMPORT FS, File, OSError, IO, Stdio;\n\nVAR file: File.T;\n\nBEGIN\n TRY\n file := FS.OpenFile(\"output.txt\");\n file.close();\n FS.CreateDirectory(\"docs\");\n file := FS.OpenFile(\"/output.txt\");\n file.close();\n FS.CreateDirectory(\"/docs\");\n EXCEPT\n | OSError.E => IO.Put(\"Error creating file or directory.\\n\", Stdio.stderr);\n END;\nEND FileCreation.\n", "language": "Modula-3" }, { "code": "import Nanoquery.IO\n\nf = new(File)\nf.create(\"output.txt\")\nf.createDir(\"docs\")\n\n// in the root directory\nf.create(\"/output.txt\")\nf.createDir(\"/docs\")\n", "language": "Nanoquery" }, { "code": "using System;\nusing System.IO;\n\nmodule CreateFile\n{\n Main() : void\n {\n unless (File.Exists(\"output.txt\")) File.Create(\"output.txt\"); // here\n // returns a FileStream object which we're ignoring\n try {\n unless (File.Exists(@\"\\output.txt\")) File.Create(@\"\\output.txt\"); // root\n }\n catch {\n |e is UnauthorizedAccessException => Console.WriteLine(\n \"Cannot create file in root directory without Administrator priveleges.\")\n }\n\n unless (Directory.Exists(\"docs\")) Directory.CreateDirectory(\"docs\");\n // returns a DirectoryInfo object which we're ignoring\n unless (Directory.Exists(@\"\\docs\")) Directory.CreateDirectory(@\"\\docs\");\n // no Exception for directory creation\n }\n}\n", "language": "Nemerle" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\nfName = ''; fName[0] = 2; fName[1] = '.' || File.separator || 'output.txt'; fName[2] = File.separator || 'output.txt'\ndName = ''; dName[0] = 2; dName[1] = '.' || File.separator || 'docs'; dName[2] = File.separator || 'docs'\n\ndo\n loop i_ = 1 to fName[0]\n say fName[i_]\n fc = File(fName[i_]).createNewFile()\n if fc then say 'File' fName[i_] 'created successfully.'\n else say 'File' fName[i_] 'aleady exists.'\n end i_\n\n loop i_ = 1 to dName[0]\n say dName[i_]\n dc = File(dName[i_]).mkdir()\n if dc then say 'Directory' dName[i_] 'created successfully.'\n else say 'Directory' dName[i_] 'aleady exists.'\n end i_\ncatch iox = IOException\n iox.printStackTrace\nend\n\nreturn\n", "language": "NetRexx" }, { "code": "import os\n\nopen(\"output.txt\", fmWrite).close()\ncreateDir(\"docs\")\n\nopen(DirSep & \"output.txt\", fmWrite).close()\ncreateDir(DirSep & \"docs\")\n", "language": "Nim" }, { "code": "import os\nconst directories = [\"/\", \"./\"]\nfor directory in directories:\n open(directory & \"output.txt\", fmWrite).close()\n createDir(directory & \"docs\")\n", "language": "Nim" }, { "code": "use IO;\n\nbundle Default {\n class FileExample {\n function : Main(args : String[]) ~ Nil {\n file := FileWriter->New(\"output.txt\");\n file->Close();\n\n file := FileWriter->New(\"/output.txt\");\n file->Close();\n\n Directory->Create(\"docs\");\n Directory->Create(\"/docs\");\n }\n }\n}\n", "language": "Objeck" }, { "code": "NSFileManager *fm = [NSFileManager defaultManager];\n\n[fm createFileAtPath:@\"output.txt\" contents:[NSData data] attributes:nil];\n// Pre-OS X 10.5\n[fm createDirectoryAtPath:@\"docs\" attributes:nil];\n// OS X 10.5+\n[fm createDirectoryAtPath:@\"docs\" withIntermediateDirectories:NO attributes:nil error:NULL];\n", "language": "Objective-C" }, { "code": "# let oc = open_out \"output.txt\" in\n close_out oc;;\n- : unit = ()\n\n# Unix.mkdir \"docs\" 0o750 ;; (* rights 0o750 for rwxr-x--- *)\n- : unit = ()\n", "language": "OCaml" }, { "code": "for Dir in [\"/\" \"./\"] do\n File = {New Open.file init(name:Dir#\"output.txt\" flags:[create])}\nin\n {File close}\n {OS.mkDir Dir#\"docs\" ['S_IRUSR' 'S_IWUSR' 'S_IXUSR' 'S_IXGRP']}\nend\n", "language": "Oz" }, { "code": "write1(\"0.txt\",\"\")\nwrite1(\"/0.txt\",\"\")\n", "language": "PARI-GP" }, { "code": "system(\"mkdir newdir\")\n", "language": "PARI-GP" }, { "code": "program in out;\n\nvar\n\n f : textfile;\n\nbegin\n\n assignFile(f,'/output.txt');\n rewrite(f);\n close(f);\n makedir('/docs');\n assignFile(f,'/docs/output.txt');\n rewrite(f);\n close(f);\n\nend;\n", "language": "Pascal" }, { "code": "use File::Spec::Functions qw(catfile rootdir);\n{ # here\n open my $fh, '>', 'output.txt';\n mkdir 'docs';\n};\n{ # root dir\n open my $fh, '>', catfile rootdir, 'output.txt';\n mkdir catfile rootdir, 'docs';\n};\n", "language": "Perl" }, { "code": "perl -e 'qx(touch output.txt)'\nperl -e 'mkdir docs'\n", "language": "Perl" }, { "code": "perl -e 'qx(touch /output.txt)'\nperl -e 'mkdir \"/docs\"'\n", "language": "Perl" }, { "code": "for my $prefix (qw( ./ / )) {\n mkdir \"${prefix}docs\";\n open my $FH, '>', \"${prefix}docs/output.txt\";\n}\n", "language": "Perl" }, { "code": "unlink $_ for qw(/docs/output.txt ./docs/output.txt);\nrmdir $_ for qw(/docs ./docs);\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">fn</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- In the current working directory</span>\n <span style=\"color: #7060A8;\">system</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"mkdir docs\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">fn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">open</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"output.txt\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"w\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">close</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- In the filesystem root</span>\n <span style=\"color: #7060A8;\">system</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"mkdir \\\\docs\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">fn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">open</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\\\\output.txt\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"w\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">=-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"unable to create \\\\output.txt\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #7060A8;\">close</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n<!--\n", "language": "Phix" }, { "code": "\"foo.bar\" \"w\" fopen fclose\n", "language": "Phixmonti" }, { "code": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n", "language": "PHP" }, { "code": "(out \"output.txt\") # Empty output\n(call 'mkdir \"docs\") # Call external\n(out \"/output.txt\")\n(call 'mkdir \"/docs\")\n", "language": "PicoLisp" }, { "code": "import Stdio;\n\nint main(){\n write_file(\"input.txt\",\"\",0100);\n write_file(\"/input.txt\",\"\",0100);\n}\n", "language": "Pike" }, { "code": "open file (output) title ('/OUTPUT.TXT,type(text),recsize(100)' );\nclose file (output);\n", "language": "PL-I" }, { "code": "To run:\nStart up.\n\\ In the current working directory\nCreate \".\\output.txt\" in the file system.\nCreate \".\\docs\\\" in the file system.\n\\ In the filesystem root\nCreate \"C:\\output.txt\" in the file system.\nCreate \"C:\\docs\\\" in the file system.\nShut down.\n", "language": "Plain-English" }, { "code": "New-Item output.txt -ItemType File\nNew-Item \\output.txt -ItemType File\nNew-Item docs -ItemType Directory\nNew-Item \\docs -ItemType Directory\n", "language": "PowerShell" }, { "code": "makedirectory docs\nchangedirectory docs\nmakenewfile output.txt\n", "language": "ProDOS" }, { "code": "CreateFile(0,\"output.txt\"):CloseFile(0)\nCreateDirectory(\"docs\")\nCreateFile(0,\"/output.txt\"):CloseFile(0)\nCreateDirectory(\"/docs\")\n", "language": "PureBasic" }, { "code": "import os\nfor directory in ['/', './']:\n open(directory + 'output.txt', 'w').close() # create /output.txt, then ./output.txt\n os.mkdir(directory + 'docs') # create directory /docs, then ./docs\n", "language": "Python" }, { "code": "from __future__ import with_statement\nimport os\ndef create(directory):\n with open(os.path.join(directory, \"output.txt\"), \"w\"):\n pass\n os.mkdir(os.path.join(directory, \"docs\"))\n\ncreate(\".\") # current directory\ncreate(\"/\") # root directory\n", "language": "Python" }, { "code": "f <- file(\"output.txt\", \"w\")\nclose(f)\n\n# it may fails and the exact syntax to achieve the root\n# changes according to the operating system\nf <- file(\"/output.txt\", \"w\")\nclose(f)\n\nsuccess <- dir.create(\"docs\")\nsuccess <- dir.create(\"/docs\")\n", "language": "R" }, { "code": "#lang racket\n\n(display-to-file \"\" \"output.txt\")\n(make-directory \"docs\")\n(display-to-file \"\" \"/output.txt\")\n(make-directory \"/docs\")\n", "language": "Racket" }, { "code": "for '.', '' -> $prefix {\n mkdir \"$prefix/docs\";\n open \"$prefix/output.txt\", :w;\n}\n", "language": "Raku" }, { "code": "\"\" as str\nstr 'output.txt' write\nstr '/output.txt' write\n'docs' mkdir\n'/docs' mkdir\n", "language": "Raven" }, { "code": "; Creating in current directory:\n\nwrite %output.txt \"\"\nmake-dir %docs/\n\n; Creating in root directory:\n\nwrite %/output.txt \"\"\nmake-dir %/docs/\n", "language": "REBOL" }, { "code": "'output.txt file:W file:open file:close\n'/output.txt file:W file:open file:close\n", "language": "Retro" }, { "code": "/*REXX pgm creates a new empty file and directory; in curr dir and root.*/\n do 2 /*perform three statements twice.*/\n 'COPY NUL output.txt' /*copy a \"null\" (empty) file. */\n 'MKDIR DOCS' /*make a directory (aka: folder).*/\n 'CD \\' /*change currect dir to the root.*/\n end /*2*/ /*now, go and perform them again.*/\n /*stick a fork in it, we're done.*/\n", "language": "REXX" }, { "code": "system(\"mkdir C:\\Ring\\docs\")\nfopen(\"C:\\Ring\\docs\\output.txt\", \"w+\")\nsystem(\"mkdir docs\")\nfopen(\"output.txt\", \"w+\")\n", "language": "Ring" }, { "code": "['/', './'].each{|dir|\n Dir.mkdir(dir + 'docs') # create '/docs', then './docs'\n File.open(dir + 'output.txt', 'w') {} # create empty file /output.txt, then ./output.txt\n}\n", "language": "Ruby" }, { "code": "open \"output.txt\" for output as #f\nclose #f\n\ndirOk = mkdir( \"f:\\doc\")\nif not(dirOk) then print \"Directory not created!\": end\n\nopen \"f:\\doc\\output.txt\" for output as #f\nclose #f\n", "language": "Run-BASIC" }, { "code": "use std::io::{self, Write};\nuse std::fs::{DirBuilder, File};\nuse std::path::Path;\nuse std::{process,fmt};\n\nconst FILE_NAME: &'static str = \"output.txt\";\nconst DIR_NAME : &'static str = \"docs\";\n\nfn main() {\n create(\".\").and(create(\"/\"))\n .unwrap_or_else(|e| error_handler(e,1));\n}\n\n\nfn create<P>(root: P) -> io::Result<File>\n where P: AsRef<Path>\n{\n let f_path = root.as_ref().join(FILE_NAME);\n let d_path = root.as_ref().join(DIR_NAME);\n DirBuilder::new().create(d_path).and(File::create(f_path))\n}\n\nfn error_handler<E: fmt::Display>(error: E, code: i32) -> ! {\n let _ = writeln!(&mut io::stderr(), \"Error: {}\", error);\n process::exit(code)\n}\n", "language": "Rust" }, { "code": "rem -- Set the logged drive ('A' to 'P')\nprocedure setdrive (drive = char)\n var hl, de, bc, a_psw = integer\n rem -- ensure drive letter is upper case\n if drive >= 'a' then drive = drive - 32\n hl = 0\n de = drive - 65\n bc = 0EH rem BDOS set drive function\n a_psw = 0\n rem - call BDOS with drive number in DE\n call (5H,hl,de,bc,a_psw)\nend\n\nrem -- Set the CP/M user area (0 to 15)\nprocedure setuser (user = integer)\n var hl, bc, a_psw = integer\n hl = 0\n bc = 20H rem BDOS set user function\n a_psw = 0\n rem - call BDOS with user number in DE\n call (5H,hl,user,bc,a_psw)\nend\n\ncomment\n create empty file \"output.txt\" in current directory and in\n startup directory (drive A:, user 0)\nend\n\ncreate \"OUTPUT.TXT\"\nsetdrive 'A'\nsetuser 0\ncreate \"OUTPUT.TXT\"\n\nend\n", "language": "S-BASIC" }, { "code": "import java.io.File\n\nobject CreateFile extends App {\n try { new File(\"output.txt\").createNewFile() }\n catch { case e: Exception => println(s\"Exception caught: $e with creating output.txt\") }\n try { new File(s\"${File.separator}output.txt\").createNewFile() }\n catch { case e: Exception => println(s\"Exception caught: $e with creating ${File.separator}output.txt\") }\n try { new File(\"docs\").mkdir() }\n catch { case e: Exception => println(s\"Exception caught: $e with creating directory docs\") }\n try { new File(s\"${File.separator}docs\").mkdir() }\n catch { case e: Exception => println(s\"Exception caught: $e with creating directory ${File.separator}docs\") }\n}\n", "language": "Scala" }, { "code": "(open-output-file \"output.txt\")\n(open-output-file \"/output.txt\")\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n include \"osfiles.s7i\";\n\nconst proc: main is func\n local\n var file: aFile is STD_NULL;\n begin\n aFile := open(\"output.txt\", \"w\");\n close(aFile);\n mkdir(\"docs\");\n aFile := open(\"/output.txt\", \"w\");\n close(aFile);\n mkdir(\"/docs\");\n end func;\n", "language": "Seed7" }, { "code": "set the folder to \"~/Desktop\"\nput \"\" into file \"docs/output.txt\"\nset the folder to \"/\"\nput empty into file \"/docs/output.txt\"\n", "language": "SenseTalk" }, { "code": "put empty into file \"~/Desktop/docs/output.txt\"\nput \"\" into file \"/docs/output.txt\"\n", "language": "SenseTalk" }, { "code": "create file \"output.txt\"\ncreate folder \"docs\"\n", "language": "SenseTalk" }, { "code": "# Here\n%f'output.txt' -> create;\n%d'docs' -> create;\n\n# Root dir\nDir.root + %f'output.txt' -> create;\nDir.root + %d'docs' -> create;\n", "language": "Sidef" }, { "code": "(File newNamed: 'output.txt') touch.\n(Directory current / 'output.txt') touch.\n", "language": "Slate" }, { "code": "(File newNamed: '/output.txt') touch.\n(Directory root / 'output.txt') touch.\n", "language": "Slate" }, { "code": "(close (file-open-write \"output.txt\"))\n(mkdir \"docs\" 0755)\n", "language": "Slope" }, { "code": "(close (file-open-write \"/output.txt\"))\n(mkdir \"/docs\" 0755)\n", "language": "Slope" }, { "code": "(FileDirectory on: 'c:\\') newFileNamed: 'output.txt'; createDirectory: 'docs'.\n", "language": "Smalltalk" }, { "code": "ws := (File name: 'output.txt') writeStream.\nws close.\nDirectory create: 'docs'.\n\nws := (File name: '/output.txt') writeStream.\nws close.\nDirectory create: '/docs'.\n", "language": "Smalltalk" }, { "code": " output(.file,1,'output.txt'); endfile(1) ;* Macro Spitbol\n* output(.file,1,,'output.txt'); endfile(1) ;* CSnobol\n host(1,'mkdir docs')\n\n output(.file,1,'/output.txt'); endfile(1) ;* Macro Spitbol\n* output(.file,1,,'/output.txt'); endfile(1) ;* CSnobol\n host(1,'mkdir /docs')\nend\n", "language": "SNOBOL4" }, { "code": "BEGIN\n DECLARE UTL_FILE_HANDLER UTL_FILE.FILE_TYPE;\n DECLARE DIR_ALIAS_CURRENT VARCHAR(128);\n DECLARE DIR_ALIAS_ROOT VARCHAR(128);\n DECLARE DIRECTORY VARCHAR(1024);\n DECLARE FILENAME VARCHAR(255);\n\n SET DIR_ALIAS_CURRENT = 'outputFileCurrent';\n SET DIRECTORY = '/home/db2inst1/doc';\n SET FILENAME = 'output.txt';\n\n CALL UTL_DIR.CREATE_OR_REPLACE_DIRECTORY(DIR_ALIAS_CURRENT, DIRECTORY);\n SET UTL_FILE_HANDLER = UTL_FILE.FOPEN(DIR_ALIAS_CURRENT, FILENAME, 'a');\n CALL UTL_FILE.FFLUSH(UTL_FILE_HANDLER);\n CALL UTL_FILE.FCLOSE(UTL_FILE_HANDLER);\n\n SET DIR_ALIAS_ROOT = 'outputFileRoot';\n SET DIRECTORY = '/doc';\n\n CALL UTL_DIR.CREATE_OR_REPLACE_DIRECTORY(DIR_ALIAS_ROOT, DIRECTORY);\n SET UTL_FILE_HANDLER = UTL_FILE.FOPEN(DIR_ALIAS_ROOT, FILENAME, 'a');\n CALL UTL_FILE.FFLUSH(UTL_FILE_HANDLER);\n CALL UTL_FILE.FCLOSE(UTL_FILE_HANDLER);\nEND @\n", "language": "SQL-PL" }, { "code": "let val out = TextIO.openOut \"output.txt\" in\n TextIO.closeOut out\nend;\n\nOS.FileSys.mkDir \"docs\";\n", "language": "Standard-ML" }, { "code": "file open f using output.txt, write replace\nfile close f\nmkdir docs\n\nfile open f using \\output.txt, write replace\nfile close f\nmkdir \\docs\n", "language": "Stata" }, { "code": "close [open output.txt w]\nclose [open [file nativename /output.txt] w]\n\nfile mkdir docs\nfile mkdir [file nativename /docs]\n", "language": "Tcl" }, { "code": "needs shell\n\" output.txt\" \"W\" file.open file.close\n\" /output.txt\" \"W\" file.open file.close\n\n( Create the directories with permissions set to 777)\n\" docs\" &777 mkdir\n\" /docs\" &777 mkdir\n", "language": "Toka" }, { "code": "$$ MODE TUSCRIPT\n- create file\nERROR/STOP CREATE (\"output.txt\",FDF-o,-std-)\n- create directory\nERROR/STOP CREATE (\"docs\",project,-std-)\n", "language": "TUSCRIPT" }, { "code": "touch output.txt /output.txt # create both output.txt and /output.txt\nmkdir /docs\nmkdir docs # create both /docs and docs\n", "language": "UNIX-Shell" }, { "code": "touch {/,}output.txt # create both /output.txt and output.txt\nmkdir {/,}docs # create both /docs and docs\n", "language": "UNIX-Shell" }, { "code": "decl file f\nf.create \"output.txt\"\nf.createdir \"docs\"\n\n# in the root directory\nf.create \"/output.txt\"\nf.createdir \"/docs\"\n", "language": "Ursa" }, { "code": "Public Sub create_file()\n Dim FileNumber As Integer\n FileNumber = FreeFile\n MkDir \"docs\"\n Open \"docs\\output.txt\" For Output As #FreeFile\n Close #FreeFile\n MkDir \"C:\\docs\"\n Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n Close #FreeFile\nEnd Sub\n", "language": "VBA" }, { "code": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n'current directory\nobjFSO.CreateFolder(\".\\docs\")\nobjFSO.CreateTextFile(\".\\docs\\output.txt\")\n\n'root directory\nobjFSO.CreateFolder(\"\\docs\")\nobjFSO.CreateTextFile(\"\\docs\\output.txt\")\n", "language": "VBScript" }, { "code": "// In current directory\nFile_Open(\"input.txt\") Ins_Char(' ') Del_Char(-1) Buf_Close()\nFile_Mkdir(\"docs\")\n\n// In the root directory\nFile_Open(\"/input.txt\") Ins_Char(' ') Del_Char(-1) Buf_Close()\nFile_Mkdir(\"/docs\")\n", "language": "Vedit-macro-language" }, { "code": " 'Current Directory\nIO.Directory.CreateDirectory(\"docs\")\nIO.File.Create(\"output.txt\").Close()\n\n 'Root\nIO.Directory.CreateDirectory(\"\\docs\")\nIO.File.Create(\"\\output.txt\").Close()\n\n 'Root, platform independent\nIO.Directory.CreateDirectory(IO.Path.DirectorySeparatorChar & \"docs\")\nIO.File.Create(IO.Path.DirectorySeparatorChar & \"output.txt\").Close()\n", "language": "Visual-Basic-.NET" }, { "code": "DirMake(String2Psz(\"c:\\docs\"))\nFCreate(\"c:\\docs\\output.txt\", FC_NORMAL)\n", "language": "Visual-Objects" }, { "code": "import \"io\" for File\n\n// file is closed automatically after creation\nFile.create(\"output.txt\") {}\n\n// check size\nSystem.print(\"%(File.size(\"output.txt\")) bytes\")\n", "language": "Wren" }, { "code": "; syscall numbers for readability. :]\n\n%define sys_mkdir 39\n%define sys_creat 8\n\nsection .data\n\tfName db 'doc/output.txt',0\n\trfName db '/output.txt',0\n\tdName db 'doc',0\n\n\terr_msg db \"Something went wrong! :[\",0xa\n\terr_len equ $-err_msg\n\nsection .text\nglobal _start\n\n_start:\n\nnop\n\tmov ebx, dName ; Directory name\n\tmov eax, sys_mkdir ; Specify sys_mkdir call\n\tmov ecx, 0750o ; permission (rwxr-x---)\n\tint 0x80 ; Make kernel call\n\n\tmov ebx, fName ; File name\n\tmov eax, sys_creat ; Specify sys_creat call\n\tmov ecx, 0640o ; permission (rw-r-----)\n\tint 0x80 ; Make kernel call\n\ttest eax, eax ; eax AND eax\n\tjs _ragequit ; If EAX is less than zero\n ; THEN Display Message Error\n\n\tmov ebx, rfName ; File name Root\n\tmov eax, sys_creat ; Specify sys_creat call\n\tmov ecx, 0777o ; permission (rwxrwxrwx)\n\tint 0x80 ; Make kernel call\n\tcmp eax, 0\n\tjle _exit ; IF EAX is less or equal than zero\n ; THEN jump to EXIT\n ; ELSE Display Message Error\n\n\t_ragequit:\n\t\tmov edx, err_len ; Pass offset of the message error\n\t\tmov ecx, err_msg ; Pass the length of the message error\n\t\tmov eax, 4 ; Specify sys_write call\n\t\tmov ebx, 2 ; Specify File Descriptor 2: Error Output\n\t\tint 0x80 ; Make kernel call\n\n\t_exit:\n\t\tpush 0x1\n\t\tmov eax, 1 ; Code for Exit Syscall\n\t\tpush eax\n\t\tint 0x80 ; Make kernel call\n\t\tret\n", "language": "X86-Assembly" }, { "code": "int FD;\nFD:= FOpen(\"output.txt\", 1);\n", "language": "XPL0" }, { "code": "open \"output.txt\" for writing as #1\nclose #1\n\nsystem(\"mkdir \" + \"f:\\docs\")\nif open(2, \"f:\\docs\\output.txt\") then\n print \"Subdirectory or file already exists\"\nelse\n open \"f:\\docs\\output.txt\" for writing as #2\n close #2\nend if\n", "language": "Yabasic" }, { "code": "$ ls -l docs\nls: cannot access docs: No such file or directory\n$ zkl\nzkl: fcn createOutputTxt(dir){ dir=dir+\"/docs\"; File.mkdir(dir); File(dir+\"/output.txt\",\"w\") }\nVoid\nzkl: createOutputTxt(\".\")\nFile(./docs/output.txt)\nzkl: createOutputTxt(\"/\")\nStack trace for VM#1 ():\n Cmd.createOutputTxt@mkdir addr:16 args(1) reg(0)\n Cmd.__constructor@createOutputTxt addr:9 args(0) reg(0) R\n startup.__constructor addr:2271 args(0) reg(1) ER\n startup.__constructor addr:2207 args(0) reg(22)\nException thrown: IOError(File.mkdir(//docs): Permission denied)\nzkl: ^D\n$ ls -l docs\ntotal 0\n-rw-r--r-- 1 craigd craigd 0 Oct 27 22:08 output.txt\n", "language": "Zkl" }, { "code": "SAVE \"OUTPUT\" CODE 16384,0\n", "language": "ZX-Spectrum-Basic" } ]
Create-a-file
[ { "code": "---\ncategory:\n- Hardware\nfrom: http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape\nnote: File System Operations\n", "language": "00-META" }, { "code": "The task is to create a new file called \"TAPE.FILE\" of any size on Magnetic Tape.\n\n", "language": "00-TASK" }, { "code": "PROC Save(CHAR ARRAY text)\n BYTE dev=[1]\n\n Close(dev)\n Open(dev,\"C:\",8,128)\n PrintE(\"Saving started...\")\n PrintF(\"Saving text: \"\"%S\"\"%E\",text)\n PrintD(dev,text)\n Close(dev)\n PrintE(\"Saving finished.\")\nRETURN\n\nPROC Load()\n CHAR ARRAY result(255)\n BYTE dev=[1]\n\n Close(dev)\n Open(dev,\"C:\",4,128)\n PrintE(\"Loading started...\")\n WHILE Eof(dev)=0\n DO\n InputSD(dev,result)\n PrintF(\"Loading text: \"\"%S\"\"%E\",result)\n OD\n Close(dev)\n PrintE(\"Loading finished.\")\nRETURN\n\nPROC Main()\n BYTE CH=$02FC ;Internal hardware value for last key pressed\n\n PrintE(\"Press any key to save a file on tape.\")\n Save(\"Atari Action!\")\n\n PutE()\n PrintE(\"Rewind the tape and press any key to load previously saved file from tape.\")\n Load()\nRETURN\n", "language": "Action-" }, { "code": "SAVE\n", "language": "Applesoft-BASIC" }, { "code": "write \"TAPE.FILE\" {\n This code\n should be able to write\n a file\n to magnetic tape\n}\n", "language": "Arturo" }, { "code": "#include<stdio.h>\n\nint main()\n{\n\tFILE* fp = fopen(\"TAPE.FILE\",\"w\");\n\t\n\tfprintf(fp,\"This code should be able to write a file to magnetic tape.\\n\");\n\tfprintf(fp,\"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\\n\");\n\tfprintf(fp,\"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\\n\");\n\tfprintf(fp,\"And since C is already 44, maybe 45, years old in 2017, I am sure someone somewhere did use a C compiler on magnetic tapes.\\n\");\n\tfprintf(fp,\"If you happen to have one, please try to compile and execute me on that system.\\n\");\n\tfprintf(fp,\"My creator tested me on an i5 machine with SSD and RAM that couldn't have even been dreamt of by Denis Ritchie.\\n\");\n\tfprintf(fp,\"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\\n\");\n\tfprintf(fp,\"EOF\");\n\t\n\tfclose(fp);\n\t\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <fstream>\n\n#if defined(_WIN32) || defined(WIN32)\nconstexpr auto FILENAME = \"tape.file\";\n#else\nconstexpr auto FILENAME = \"/dev/tape\";\n#endif\n\nint main() {\n std::filebuf fb;\n fb.open(FILENAME,std::ios::out);\n std::ostream os(&fb);\n os << \"Hello World\\n\";\n fb.close();\n return 0;\n}\n", "language": "C++" }, { "code": "(spit \"/dev/tape\" \"Hello, World!\")\n", "language": "Clojure" }, { "code": " >>SOURCE FORMAT IS FREE\nIDENTIFICATION DIVISION.\nPROGRAM-ID. MAKE-TAPE-FILE.\n\nENVIRONMENT DIVISION.\nINPUT-OUTPUT SECTION.\nFILE-CONTROL.\n SELECT TAPE-FILE\n ASSIGN TO \"./TAPE.FILE\"\n ORGANIZATION IS SEQUENTIAL\n ACCESS MODE IS SEQUENTIAL.\n\nDATA DIVISION.\nFILE SECTION.\nFD TAPE-FILE RECORD CONTAINS 51 CHARACTERS.\n01 TAPE-FILE-RECORD PICTURE IS X(51).\n\nPROCEDURE DIVISION.\n OPEN OUTPUT SHARING WITH ALL OTHER TAPE-FILE\n WRITE TAPE-FILE-RECORD\n FROM \"COBOL treats tape files and text files identically.\"\n END-WRITE\n CLOSE TAPE-FILE\n STOP RUN.\n\nEND PROGRAM MAKE-TAPE-FILE.\n", "language": "COBOL" }, { "code": "filename = {% if flag?(:win32) %}\n \"TAPE.FILE\"\n {% else %}\n \"/dev/tape\"\n {% end %}\nFile.write filename, \"howdy, planet!\"\n", "language": "Crystal" }, { "code": "import std.stdio;\n\nvoid main() {\n version(Windows) {\n File f = File(\"TAPE.FILE\", \"w\");\n } else {\n File f = File(\"/dev/tape\", \"w\");\n }\n f.writeln(\"Hello World!\");\n}\n", "language": "D" }, { "code": "program Create_a_file_on_magnetic_tape;\n\n{$APPTYPE CONSOLE}\n\nconst\n{$IFDEF WIN32}\n FileName = 'tape.file';\n{$ELSE}\n FileName = '/dev/tape';\n{$ENDIF}\n\nvar\n f: TextFile;\n\nbegin\n Assign(f, FileName);\n Rewrite(f);\n Writeln(f, 'Hello World');\n close(f);\nend.\n", "language": "Delphi" }, { "code": "open System\nopen System.IO\n\nlet env = Environment.OSVersion.Platform\nlet msg = \"Hello Rosetta!\"\n\nmatch env with\n | PlatformID.Win32NT | PlatformID.Win32S | PlatformID.Win32Windows | PlatformID.WinCE -> File.WriteAllText(\"TAPE.FILE\", msg)\n | _ -> File.WriteAllText(\"/dev/tape\", msg)\n", "language": "F-Sharp" }, { "code": "USING: io.encodings.ascii io.files kernel system ;\n\n\"Hello from Rosetta Code!\"\nos windows? \"tape.file\" \"/dev/tape\" ?\nascii set-file-contents\n", "language": "Factor" }, { "code": "Dim As Integer numarch = Freefile\nOpen \"tape.file\" For Output As #numarch\nPrint #numarch, \"Soy un archivo de cinta ahora, o espero serlo pronto.\"\nClose #numarch\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"archive/tar\"\n \"compress/gzip\"\n \"flag\"\n \"io\"\n \"log\"\n \"os\"\n \"time\"\n)\n\nfunc main() {\n filename := flag.String(\"file\", \"TAPE.FILE\", \"filename within TAR\")\n data := flag.String(\"data\", \"\", \"data for file\")\n outfile := flag.String(\"out\", \"\", \"output file or device (e.g. /dev/tape)\")\n gzipFlag := flag.Bool(\"gzip\", false, \"use gzip compression\")\n flag.Parse()\n\n var w io.Writer = os.Stdout\n if *outfile != \"\" {\n f, err := os.Create(*outfile)\n if err != nil {\n log.Fatalf(\"opening/creating %q: %v\", *outfile, err)\n }\n defer f.Close()\n w = f\n }\n\n if *gzipFlag {\n zw := gzip.NewWriter(w)\n defer zw.Close()\n w = zw\n }\n\n tw := tar.NewWriter(w)\n defer tw.Close()\n w = tw\n tw.WriteHeader(&tar.Header{\n Name: *filename,\n Mode: 0660,\n Size: int64(len(*data)),\n ModTime: time.Now(),\n Typeflag: tar.TypeReg,\n Uname: \"guest\",\n Gname: \"guest\",\n })\n\n _, err := w.Write([]byte(*data))\n if err != nil {\n log.Fatal(\"writing data:\", err)\n }\n}\n", "language": "Go" }, { "code": "import java.nio.file.Files\nimport java.nio.file.Path\nimport java.nio.file.Paths\n\nclass CreateFile {\n static void main(String[] args) throws IOException {\n String os = System.getProperty(\"os.name\")\n if (os.contains(\"Windows\")) {\n Path path = Paths.get(\"tape.file\")\n Files.write(path, Collections.singletonList(\"Hello World!\"))\n } else {\n Path path = Paths.get(\"/dev/tape\")\n Files.write(path, Collections.singletonList(\"Hello World!\"))\n }\n }\n}\n", "language": "Groovy" }, { "code": "module Main (main) where\n\nmain :: IO ()\nmain = writeFile \"/dev/tape\" \"Hello from Rosetta Code!\"\n", "language": "Haskell" }, { "code": "procedure main()\n write(open(\"/dev/tape\",\"w\"),\"Hi\")\nend\n", "language": "Icon" }, { "code": "100 OPEN #1:\"Tape1:README.TXT\" ACCESS OUTPUT\n110 PRINT #1:\"I am a tape file now, or hope to be soon.\"\n120 CLOSE #1\n", "language": "IS-BASIC" }, { "code": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Collections;\n\npublic class CreateFile {\n public static void main(String[] args) throws IOException {\n String os = System.getProperty(\"os.name\");\n if (os.contains(\"Windows\")) {\n Path path = Paths.get(\"tape.file\");\n Files.write(path, Collections.singletonList(\"Hello World!\"));\n } else {\n Path path = Paths.get(\"/dev/tape\");\n Files.write(path, Collections.singletonList(\"Hello World!\"));\n }\n }\n}\n", "language": "Java" }, { "code": "// EXEC PGM=IEBGENER\n//* Create a file named \"TAPE.FILE\" on magnetic tape; \"UNIT=TAPE\"\n//* may vary depending on site-specific esoteric name assignment\n//SYSPRINT DD SYSOUT=*\n//SYSIN DD DUMMY\n//SYSUT2 DD UNIT=TAPE,DSN=TAPE.FILE,DISP=(,CATLG)\n//SYSUT1 DD *\nDATA TO BE WRITTEN TO TAPE\n/*\n", "language": "JCL" }, { "code": "open(\"/dev/tape\", \"w\") do f\n write(f, \"Hello tape!\")\nend\n", "language": "Julia" }, { "code": "// version 1.1.0 (Linux)\n\nimport java.io.FileWriter\n\nfun main(args: Array<String>) {\n val lp0 = FileWriter(\"/dev/tape\")\n lp0.write(\"Hello, world!\")\n lp0.close()\n}\n", "language": "Kotlin" }, { "code": "require \"lfs\"\n\nlocal out\nif lfs.attributes('/dev/tape') then\n out = '/dev/tape'\nelse\n out = 'tape.file'\nend\nfile = io.open(out, 'w')\nfile:write('Hello world')\nio.close(file)\n", "language": "Lua" }, { "code": "var t = open(\"/dev/tape\", fmWrite)\nt.writeln \"Hi Tape!\"\nt.close\n", "language": "Nim" }, { "code": "include builtins/write_file.e\nconstant filepath = iff(platform()=WINDOWS?\"tape.file\":\"/dev/tape\"),\nwrite_file(file_path,\"Hello world!\")\n", "language": "Phix" }, { "code": "(out \"/dev/tape\"\n (prin \"Hello World!\") )\n", "language": "PicoLisp" }, { "code": ">>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\\n')\n...\n>>>\n", "language": "Python" }, { "code": "#lang racket\n(with-output-to-file \"/dev/tape\" #:exists 'append\n (λ() (displayln \"I am a cheap imitation of the Perl code for a boring problem\")))\n", "language": "Racket" }, { "code": "my $tape = open \"/dev/tape\", :w or die \"Can't open tape: $!\";\n$tape.say: \"I am a tape file now, or hope to be soon.\";\n$tape.close;\n", "language": "Raku" }, { "code": "/*REXX pgm demonstrates writing records to an attached magnetic tape.*/\ndsName = 'TAPE.FILE' /*dsName of \"file\" being written.*/\n\n do j=1 for 100 /*write 100 records to mag tape. */\n call lineout dsName, 'this is record' j || \".\"\n end /*j*/\n /*stick a fork in it, we're done.*/\n", "language": "REXX" }, { "code": "# Project : Create a file on magnetic tape\n\nfn = \"Tape.file\"\nfp = fopen(fn,\"w\")\nstr = \"I am a tape file now, or hope to be soon.\"\nfwrite(fp, str)\nfclose(fp)\n", "language": "Ring" }, { "code": "File.open(\"tape.file\", \"w\") do |fh|\n fh.syswrite(\"This code should be able to write a file to magnetic tape.\\n\")\nend\n", "language": "Ruby" }, { "code": "use std::io::Write;\nuse std::fs::File;\n\nfn main() -> std::io::Result<()> {\n File::open(\"/dev/tape\")?.write_all(b\"Hello from Rosetta Code!\")\n}\n", "language": "Rust" }, { "code": "object LinePrinter extends App {\n import java.io.{ FileWriter, IOException }\n {\n val lp0 = new FileWriter(\"/dev/tape\")\n lp0.write(\"Hello, world!\")\n lp0.close()\n }\n}\n", "language": "Scala" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst proc: main is func\n local\n var file: tapeFile is STD_NULL;\n begin\n tapeFile := open(\"/dev/tape\", \"w\");\n if tapeFile = STD_NULL then\n tapeFile := open(\"tape.file\", \"w\");\n end if;\n if tapeFile <> STD_NULL then\n writeln(tapeFile, \"Hello, world!\");\n close(tapeFile);\n else\n writeln(\" ***** Cannot open tape file.\");\n end if;\n end func;\n", "language": "Seed7" }, { "code": "cd /tmp\n\n# Create the file\nset f [open hello.jnk w]\nputs $f \"Hello World!\"\nclose $f\n\n# Archive to tape\nset fin [open \"|tar cf - hello.jnk\" rb]\nset fout [open /dev/tape wb]\nfcopy $fin $fout\nclose $fin\nclose $fout\n", "language": "Tcl" }, { "code": "$$ MODE TUSCRIPT\nSTATUS = CREATE (\"tape.file\",tape-o,-std-)\nPRINT STATUS\n", "language": "TUSCRIPT" }, { "code": "#!/bin/sh\ncd # Make our home directory current\necho \"Hello World!\" > hello.jnk # Create a junk file\n# tape rewind # Uncomment this to rewind the tape\ntar c hello.jnk # Traditional archivers use magnetic tape by default\n# tar c hello.jnk > /dev/tape # With newer archivers redirection is needed\n", "language": "UNIX-Shell" }, { "code": "import \"os\" for Platform\nimport \"io\" for File\n\nvar fileName = (Platform.isWindows) ? \"TAPE.FILE\" : \"/dev/tape\"\nFile.create(fileName) { |file|\n file.writeBytes(\"Hello World!\\n\")\n}\n", "language": "Wren" }, { "code": "SAVE \"TAPEFILE\" CODE 16384,6912\n", "language": "ZX-Spectrum-Basic" } ]
Create-a-file-on-magnetic-tape
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime\nnote: Basic language learning\n", "language": "00-META" }, { "code": "{{data structure}}\nGet two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.\n\n", "language": "00-TASK" }, { "code": "V width = 3\nV height = 5\nV myarray = [[0] * width] * height\nprint(myarray[height-1][width-1])\n", "language": "11l" }, { "code": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; Array setup\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\nCreate_2D_Array:\nARRAY_2D equ $100000\nARRAY_POINTER_VARIABLE equ $200000\n; input: D0 = width, D1 = height\n; assume the input is byte length and unsigned, ranging from 1 to FF.\n\nAND.L #$000000FF,D0\nAND.L #$000000FF,D1 ;sanitize the input to byte length.\n\nLEA ARRAY_2D,A0 ;get base array address.\n\n;The array's size will be measured in bytes, as this is how memory offsetting is measured.\n;For this example the elements will all be 32-bit.\n;Therefore, the dimensions need to be multiplied by the byte count of each element.\n\nLSL.W #2,D0 ;four bytes per element = multiply by 4\nLSL.W #2,D1\n\n;Next, these values are multiplied to get the array's size.\nMOVE.L D0,D2\nMULU D1,D2\n;D2 is the array's size (measured in bytes) and will be placed at the beginning.\n;This does not count as an element of the array for the purposes of row/column indexing.\n;The array's base address will be offset by 4 bytes prior to any indexing.\n\nMOVE.L D2,(A0)+ ;store D2 in A0, add 4 to A0\nMOVEA.L A0,[ARRAY_POINTER_VARIABLE]\n\n;the brackets are optional, they show that this is a memory address label.\n;this is still a move to a memory address with or without the brackets.\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; Storing a value in the array\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\nLEA ARRAY_POINTER_VARIABLE,A1 ;load the address where the array's base address is stored.\nMOVE.L (A1),A1 ;dereference the pointer and get ARRAY_2D+4 into A1.\n\n; for this example the arbitrary row/column indices (2,5) will be used.\n\nMOVE.L #2,D4\nMULU D0,D4 ;there are D0 entries per row, multiply row index by elements per row.\nMOVE.L #5,D5\nMOVE.L #$00112233,D7 ;determine the value we want to store in the array.\n\n; The bytes per element was factored into D0 when the array was created. So D4 is already where it should be.\nLSL.L #2,D5 ;column index still needs to be scaled by the bytes per element.\n\nLEA (A1,D4),A1 ;select the desired row.\n\n;68000 doesn't allow you to use more than 1 data register at a time to offset. So we have to offset separately.\n;Despite the use of parentheses this is NOT a dereference like it would be with \"MOVE.L (A1),D7\". D4 is merely added to the address in A1.\n\nMOVE.L D7,(A1,D5) ;store #$00112233 in row 2, column 5 of the array.\n\n;Loading a value is the same as storing it, except the operands in the last instruction are reversed, and MOVE.L #$00112233,D7\n;is omitted.\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; Destroying the array\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n; The array is destroyed by storing something else in its location. If you really want to reset it to zero, you can\n; do so with the following:\n\nLEA ARRAY_POINTER_VARIABLE,A1\nMOVE.L (A1),A1\nMOVE.L -(A1),D7\n;get the array size into D7. Remember that the array's size was stored just before its data.\nThis value is potentially too large for a single DBRA, but it can be split up.\n\nSWAP D7\nMOVE.W D7,D6 ;get the top half of D7 into D6. D6 will be the outer loop's DBRA value.\nSWAP D7\nSUBQ.L #1,D7 ;D7 needs to be decremented by 1. D6 is fine the way it is.\n\nMOVE.L (A0)+,D0 ;dummy move to increment the pointer back to the array base.\nMOVEQ #0,D0 ;faster than MOVE.L #0,D0\n\nloop_destroyArray:\nMOVE.L D0,(A0)+\nDBRA D7,loop_destroyArray ;loop using bottom 2 bytes of the array size as a loop counter\nDBRA D6,loop_destroyArray ;decrement this, D7 is $FFFF each time execution gets here so this acts as a \"carry\" of sorts.\n ;if this value was 0 prior to the loop, the loop ends immediately.\n", "language": "68000-Assembly" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program createarray264.s */\n\n/************************************/\n/* Constantes */\n/************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n.equ BUFFERSIZE, 64\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessRead1: .asciz \"Input size level 1 : \"\nszMessRead2: .asciz \"Input size level 2 : \"\nszMessIndice1: .asciz \"Indice 1 =\"\nszMessIndice2: .asciz \" Indice 2 =\"\nszMessResult: .asciz \" Item = \"\nszMessStart: .asciz \"Program 64 bits start.\\n\"\nszCarriageReturn: .asciz \"\\n\"\n\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\nsZoneConv: .skip BUFFERSIZE // conversion buffer\nsZoneConv1: .skip BUFFERSIZE // conversion buffer\nsZoneConv2: .skip BUFFERSIZE // conversion buffer\nsBuffer: .skip BUFFERSIZE\n\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: // entry of program\n ldr x0,qAdrszMessStart\n bl affichageMess\n ldr x0,qAdrszMessRead1\n bl affichageMess\n mov x0,#STDIN // Linux input console\n ldr x1,qAdrsBuffer // buffer address\n mov x2,#BUFFERSIZE // buffer size\n mov x8,READ\n svc 0 // call system\n ldr x0,qAdrsBuffer // buffer address\n bl conversionAtoD\n mov x9,x0\n ldr x0,qAdrszMessRead2\n bl affichageMess\n mov x0,#STDIN // Linux input console\n ldr x1,qAdrsBuffer // buffer address\n mov x2,#BUFFERSIZE // buffer size\n mov x8,READ\n svc 0 // call system\n ldr x0,qAdrsBuffer // buffer address\n bl conversionAtoD\n mov x10,x0\n // create array\n lsl x12,x10,#3 // compute size level 2\n mul x8,x12,x9 // compute size array\n tst x8,0xF // multiple of 16 ?\n add x11,x8,8 // if no add 8 octets\n csel x8,x8,x11,eq // the stack must always be aligned on 16 bytes\n // in 64 assembly arm\n sub sp,sp,x8 // reserve place on stack\n mov fp,sp // save array address\n mov x0,#0 // init all items array\n 1: // begin loop1\n mov x1,#0\n 2: // begin loop2\n mul x2,x0,x12\n add x2,x2,x1, lsl #3\n str x2,[fp,x2] // store shift in array item\n add x1,x1,#1\n cmp x1,x10\n blt 2b\n add x0,x0,#1\n cmp x0,x9\n blt 1b\n mov x0,fp\n mov x1,#1 // second indice level 1\n mov x2,#0 // first indice level 2\n mov x3,x12 // level 2 size\n bl displayItem\n mov x0,fp\n sub x1,x9,#1 // last level 1\n sub x2,x10,#1 // last level 2\n mov x3,x12 // level 2 size\n bl displayItem\n\n add sp,sp,x8 // release space on stack\n\n100: // standard end of the program\n mov x0, #0 // return code\n mov x8,EXIT\n svc #0 // perform the system call\n\nqAdrszCarriageReturn: .quad szCarriageReturn\nqAdrsZoneConv: .quad sZoneConv\nqAdrsZoneConv1: .quad sZoneConv1\nqAdrsZoneConv2: .quad sZoneConv2\nqAdrszMessRead1: .quad szMessRead1\nqAdrszMessRead2: .quad szMessRead2\nqAdrsBuffer: .quad sBuffer\nqAdrszMessResult: .quad szMessResult\nqAdrszMessStart: .quad szMessStart\nqAdrszMessIndice1: .quad szMessIndice1\nqAdrszMessIndice2: .quad szMessIndice2\n/***************************************************/\n/* display array item */\n/***************************************************/\n/* x0 array address */\n/* x1 indice 1 */\n/* x2 indice 2 */\n/* x3 level 2 size */\ndisplayItem:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n stp x4,x5,[sp,-16]! // save registers\n stp x6,fp,[sp,-16]! // save registers\n mov x5,x0\n mov x6,x1\n mov x0,x6\n ldr x1,qAdrsZoneConv\n bl conversion10 // conversion indice 1\n mov x0,x2\n ldr x1,qAdrsZoneConv1\n bl conversion10 // conversion indice 2\n mul x4,x6,x3 // multiply indice level 1 by level 2 size\n add x4,x4,x2, lsl #3 // add indice level 2 * 8 (8 bytes)\n ldr x0,[x5,x4] // load array item\n ldr x1,qAdrsZoneConv2\n bl conversion10\n mov x0,#7 // string number to display\n ldr x1,qAdrszMessIndice1\n ldr x2,qAdrsZoneConv // insert conversion in message\n ldr x3,qAdrszMessIndice2\n ldr x4,qAdrsZoneConv1 // insert conversion in message\n ldr x5,qAdrszMessResult\n ldr x6,qAdrsZoneConv2 // insert conversion in message\n ldr x7,qAdrszCarriageReturn\n bl displayStrings // display message\n100:\n ldp x6,fp,[sp],16 // restaur registers\n ldp x4,x5,[sp],16 // restaur registers\n ldp x2,x3,[sp],16 // restaur registers\n ldp x1,lr,[sp],16 // restaur registers\n ret\n/***************************************************/\n/* display multi strings */\n/* new version 24/05/2023 */\n/***************************************************/\n/* x0 contains number strings address */\n/* x1 address string1 */\n/* x2 address string2 */\n/* x3 address string3 */\n/* x4 address string4 */\n/* x5 address string5 */\n/* x6 address string5 */\n/* x7 address string6 */\ndisplayStrings: // INFO: displayStrings\n stp x8,lr,[sp,-16]! // save registers\n stp x2,fp,[sp,-16]! // save registers\n add fp,sp,#32 // save paraméters address (4 registers saved * 8 bytes)\n mov x8,x0 // save strings number\n cmp x8,#0 // 0 string -> end\n ble 100f\n mov x0,x1 // string 1\n bl affichageMess\n cmp x8,#1 // number > 1\n ble 100f\n mov x0,x2\n bl affichageMess\n cmp x8,#2\n ble 100f\n mov x0,x3\n bl affichageMess\n cmp x8,#3\n ble 100f\n mov x0,x4\n bl affichageMess\n cmp x8,#4\n ble 100f\n mov x0,x5\n bl affichageMess\n cmp x8,#5\n ble 100f\n mov x0,x6\n bl affichageMess\n cmp x8,#6\n ble 100f\n mov x0,x7\n bl affichageMess\n\n100:\n ldp x2,fp,[sp],16 // restaur registers\n ldp x8,lr,[sp],16 // restaur registers\n ret\n\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "CARD EndProg ;required for ALLOCATE.ACT\n\nINCLUDE \"D2:ALLOCATE.ACT\" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!\n\nDEFINE PTR=\"CARD\"\nDEFINE INT_SIZE=\"2\"\nDEFINE CARD_SIZE=\"2\"\nTYPE IntArray2D=[BYTE rows,cols PTR p]\n\nBYTE FUNC GetNumber(CHAR ARRAY s)\n BYTE n,min=[1],max=[100]\n\n DO\n PrintF(\"Get number of %S (%B..%B): \",s,min,max)\n n=InputB()\n IF n>=min AND n<=max THEN\n EXIT\n FI\n OD\nRETURN (n)\n\nPROC Create(IntArray2D POINTER a)\n PTR ARRAY rowArray\n BYTE row\n\n IF a.p#0 THEN Break() FI\n rowArray=Alloc(a.rows*CARD_SIZE)\n a.p=rowArray\n FOR row=0 TO a.rows-1\n DO\n rowArray(row)=Alloc(a.cols*INT_SIZE)\n OD\nRETURN\n\nPROC Destroy(IntArray2D POINTER a)\n PTR ARRAY rowArray\n BYTE row\n\n IF a.p=0 THEN Break() FI\n rowArray=a.p\n FOR row=0 TO a.rows-1\n DO\n Free(rowArray(row),a.cols*INT_SIZE)\n OD\n Free(a.p,a.rows*CARD_SIZE)\n a.p=0\nRETURN\n\nPROC SetValue(IntArray2D POINTER a BYTE row,col INT v)\n PTR ARRAY rowArray\n INT ARRAY colArray\n\n IF a.p=0 OR row>=a.rows OR col>=a.cols THEN\n Break()\n FI\n rowArray=a.p\n colArray=rowArray(row)\n colArray(col)=v\nRETURN\n\nINT FUNC GetValue(IntArray2D POINTER a BYTE row,col)\n PTR ARRAY rowArray\n INT ARRAY colArray\n\n IF a.p=0 OR row>=a.rows OR col>=a.cols THEN\n Break()\n FI\n rowArray=a.p\n colArray=rowArray(row)\nRETURN (colArray(col))\n\nPROC TestCreate(IntArray2D POINTER a)\n PrintF(\"Create array of %B rows and %B cols%E\",a.rows,a.cols)\n Create(a)\nRETURN\n\nPROC TestDestroy(IntArray2D POINTER a)\n PrintF(\"Destroy array of %B rows and %B cols%E\",a.rows,a.cols)\n Destroy(a)\nRETURN\n\nPROC TestSetValue(IntArray2D POINTER a BYTE row,col INT v)\n PrintF(\"Write %I to row %B and col %B%E\",v,row,col)\n SetValue(a,row,col,v)\nRETURN\n\nPROC TestGetValue(IntArray2D POINTER a BYTE row,col)\n INT v\n\n v=GetValue(a,row,col)\n PrintF(\"Read at row %B and col %B: %I%E\",row,col,v)\nRETURN\n\nPROC Main()\n IntArray2D a\n\n Put(125) PutE() ;clear screen\n AllocInit(0)\n\n a.rows=GetNumber(\"rows\")\n a.cols=GetNumber(\"cols\")\n a.p=0\n\n TestCreate(a)\n TestSetValue(a,a.rows/2,a.cols/2,6502)\n TestGetValue(a,a.rows/2,a.cols/2)\n TestDestroy(a)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_Io;\nwith Ada.Float_Text_Io;\nwith Ada.Integer_Text_Io;\n\nprocedure Two_Dimensional_Arrays is\n type Matrix_Type is array(Positive range <>, Positive range <>) of Float;\n Dim_1 : Positive;\n Dim_2 : Positive;\nbegin\n Ada.Integer_Text_Io.Get(Item => Dim_1);\n Ada.Integer_Text_Io.Get(Item => Dim_2);\n -- Create an inner block with the correctly sized array\n declare\n Matrix : Matrix_Type(1..Dim_1, 1..Dim_2);\n begin\n Matrix(1, Dim_2) := 3.14159;\n Ada.Float_Text_Io.Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);\n Ada.Text_Io.New_Line;\n end;\n -- The variable Matrix is popped off the stack automatically\nend Two_Dimensional_Arrays;\n", "language": "Ada" }, { "code": " begin\n comment Create a two-dimensional array at runtime - Algol 60;\n integer n,m;\n ininteger(0,m);\n ininteger(0,n);\n begin\n integer array a[1:m,1:n];\n a[m,n] := 99;\n outinteger(1,a[m,n]);\n\t\toutstring(1,\"\\n\")\n end;\n comment array a : out of scope;\nend\n", "language": "ALGOL-60" }, { "code": "main:(\n print(\"Input two positive whole numbers separated by space and press newline:\");\n [read int,read int] INT array;\n array[1,1]:=42;\n print (array[1,1])\n)\n", "language": "ALGOL-68" }, { "code": "begin\n\ninteger first, second;\n\nwrite(\"Two Dimensional Array Exercise\");\nwrite(\"Length of first dimension:\");\nread(first);\nwrite(\"Length of second dimension:\");\nread(second);\n\nbegin % we need to start a new block %\n integer array test[1:first, 1:second];\n test[1,1] := 99;\n write(\"Stored value at 1,1 =\",test[1,1]);\nend; % array is now out of scope %\n\nend\n", "language": "ALGOL-M" }, { "code": "begin\n integer dimension1UpperBound, dimension2UpperBound;\n write( \"upper bound for dimension 1: \" );\n read( dimension1UpperBound );\n write( \"upper bound for dimension 2: \" );\n read( dimension2UpperBound );\n\n begin\n % we start a new block because declarations must precede statements %\n % and variables in array bounds must be from outside the block %\n integer array matrix ( 1 :: dimension1UpperBound\n , 1 :: dimension2UpperBound\n );\n % set the first element - the program will crash if the user input %\n % upper bounds less than 1 %\n matrix( 1, 1 ) := 3;\n % write it %\n write( matrix( 1, 1 ) );\n % the array is automatically deleted when the block ends %\n end\n\nend.\n", "language": "ALGOL-W" }, { "code": "#include <flow.h>\n#import lib/input.bas.lib\n#include include/flow-input.h\n\nDEF-MAIN\n CLR-SCR\n MSET(nRow, nCol)\n LOCATE( 2,5 ), PRN(\"Input size rows :\")\n LOC-COL( 23 ), LET( nRow := ABS(VAL(READ-NUMBER( nRow ) )))\n LOCATE( 3,5 ), PRN(\"Input size cols :\")\n LOC-COL( 23 ), LET( nCol := ABS(VAL(READ-NUMBER( nCol ) )))\n\n COND( IS-NOT-ZERO?( MUL(nRow,nCol) ) )\n DIM(nRow, nCol) AS-VOID( array )\n BLK-[1,1], {100} PUT(array)\n PRNL(\"\\tElement at position 1,1 : \", GET(array) )\n CLEAR(array) /* destroy array */\n CEND\nEND\nSUBRUTINES\n", "language": "Amazing-Hopper" }, { "code": "array←m n ⍴ 0 ⍝ array of zeros with shape of m by n.\n\narray[1;1]←73 ⍝ assign a value to location 1;1.\n\narray[1;1] ⍝ read the value back out\n\n⎕ex 'array' ⍝ erase the array\n", "language": "APL" }, { "code": "set R to text returned of (display dialog \"Enter number of rows:\" default answer 2) as integer\nset c to text returned of (display dialog \"Enter number of columns:\" default answer 2) as integer\nset array to {}\nrepeat with i from 1 to R\n\tset temp to {}\n\trepeat with j from 1 to c\n\t\tset temp's end to 0\n\tend repeat\n\tset array's end to temp\nend repeat\n\n-- Address the first column of the first row:\nset array's item 1's item 1 to -10\n\n-- Negative index values can be used to address from the end:\nset array's item -1's item -1 to 10\n\n-- Access an item (row 2 column 1):\nset x to array's item 2's item 1\n\nreturn array\n\n-- Destroy array (typically unnecessary since it'll automatically be destroyed once script ends).\nset array to {}\n", "language": "AppleScript" }, { "code": "10 INPUT \"ENTER TWO INTEGERS:\"; X%, Y%\n20 DIM A%(X% - 1, Y% - 1)\n30 X% = RND(1) * X%\n40 Y% = RND(1) * Y%\n50 A%(X%, Y%) = -32767\n60 PRINT A%(X%, Y%)\n70 CLEAR\n", "language": "Applesoft-BASIC" }, { "code": "/* ARM assembly Raspberry PI */\n/* program createarray2.s */\n\n /* REMARK 1 : this program use routines in a include file\n see task Include a file language arm assembly\n for the routine affichageMess conversion10\n see at end of this program the instruction include */\n\n/* for constantes see task include a file in arm assembly */\n/************************************/\n/* Constantes */\n/************************************/\n.include \"../constantes.inc\"\n.equ STDIN, 0 @ Linux input console\n.equ READ, 3 @ Linux syscall\n.equ BUFFERSIZE, 64\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessRead1: .asciz \"Input size level 1 : \"\nszMessRead2: .asciz \"Input size level 2 : \"\nszMessIndice1: .asciz \"Indice 1 =\"\nszMessIndice2: .asciz \"Indice 2 =\"\nszMessResult: .asciz \"Item = \"\nszMessStart: .asciz \"Program 32 bits start.\\n\"\nszCarriageReturn: .asciz \"\\n\"\n\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\nsZoneConv: .skip BUFFERSIZE // conversion buffer\nsZoneConv1: .skip BUFFERSIZE // conversion buffer\nsZoneConv2: .skip BUFFERSIZE // conversion buffer\nsBuffer: .skip BUFFERSIZE\n\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: @ entry of program\n ldr r0,iAdrszMessStart\n bl affichageMess\n ldr r0,iAdrszMessRead1\n bl affichageMess\n mov r0,#STDIN @ Linux input console\n ldr r1,iAdrsBuffer @ buffer address\n mov r2,#BUFFERSIZE @ buffer size\n mov r7,#READ @ request to read datas\n svc 0 @ call system\n ldr r0,iAdrsBuffer @ buffer address\n bl conversionAtoD\n mov r9,r0\n ldr r0,iAdrszMessRead2\n bl affichageMess\n mov r0,#STDIN @ Linux input console\n ldr r1,iAdrsBuffer @ buffer address\n mov r2,#BUFFERSIZE @ buffer size\n mov r7,#READ @ request to read datas\n svc 0 @ call system\n ldr r0,iAdrsBuffer @ buffer address\n bl conversionAtoD\n mov r10,r0\n @ create array\n lsl r12,r10,#2 @ compute size level 2\n mul r8,r12,r9 @ compute size array\n sub sp,sp,r8 @ reserve place on stack\n mov fp,sp\n mov r0,#0 @ init all items array\n 1: @ begin loop1\n mov r1,#0\n 2: @ begin loop2\n mul r2,r0,r12\n add r2,r2,r1, lsl #2\n str r2,[fp,r2] @ store shift in array item\n add r1,r1,#1\n cmp r1,r10\n blt 2b\n add r0,r0,#1\n cmp r0,r9\n blt 1b\n\n mov r0,fp\n mov r1,#1 @ second indice level 1\n mov r2,#0 @ first indice level 2\n mov r3,r12 @ level 2 size\n bl displayItem\n mov r0,fp\n sub r1,r9,#1 @ last level 1\n sub r2,r10,#1 @ last level 2\n mov r3,r12 @ level 2 size\n bl displayItem\n\n add sp,sp,r8 @ release space on stack\n\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsZoneConv: .int sZoneConv\niAdrsZoneConv1: .int sZoneConv1\niAdrsZoneConv2: .int sZoneConv2\niAdrszMessRead1: .int szMessRead1\niAdrszMessRead2: .int szMessRead2\niAdrsBuffer: .int sBuffer\niAdrszMessResult: .int szMessResult\niAdrszMessStart: .int szMessStart\niAdrszMessIndice1: .int szMessIndice1\niAdrszMessIndice2: .int szMessIndice2\n/***************************************************/\n/* display array item */\n/***************************************************/\n/* r0 array address */\n/* r1 indice 1 */\n/* r2 indice 2 */\n/* r3 level 2 size */\ndisplayItem:\n push {r1-r6,lr} @ save des registres\n mov r5,r0\n mov r6,r1\n mov r0,r6\n ldr r1,iAdrsZoneConv\n bl conversion10 @ conversion indice 1\n mov r0,r2\n ldr r1,iAdrsZoneConv1\n bl conversion10 @ conversion indice 2\n mul r4,r6,r3 @ multiply indice level 1 by level 2 size\n add r4,r4,r2, lsl #2 @ add indice level 2 * 4 (4 bytes)\n ldr r0,[r5,r4] @ load array item\n ldr r1,iAdrsZoneConv2\n bl conversion10\n mov r0,#7 @ string number to display\n ldr r1,iAdrszMessIndice1\n ldr r2,iAdrsZoneConv @ insert conversion in message\n ldr r3,iAdrszMessIndice2\n ldr r4,iAdrsZoneConv1 @ insert conversion in message\n push {r4}\n ldr r4,iAdrszMessResult\n push {r4}\n ldr r4,iAdrsZoneConv2 @ insert conversion in message\n push {r4}\n ldr r4,iAdrszCarriageReturn\n push {r4}\n bl displayStrings @ display message\n add sp,sp,#16\n100:\n pop {r1-r6,pc}\n/***************************************************/\n/* display multi strings */\n/***************************************************/\n/* r0 contains number strings address */\n/* r1 address string1 */\n/* r2 address string2 */\n/* r3 address string3 */\n/* other address on the stack */\n/* thinck to add number other address * 4 to add to the stack */\ndisplayStrings: @ INFO: displayStrings\n push {r1-r4,fp,lr} @ save des registres\n add fp,sp,#24 @ save paraméters address (6 registers saved * 4 bytes)\n mov r4,r0 @ save strings number\n cmp r4,#0 @ 0 string -> end\n ble 100f\n mov r0,r1 @ string 1\n bl affichageMess\n cmp r4,#1 @ number > 1\n ble 100f\n mov r0,r2\n bl affichageMess\n cmp r4,#2\n ble 100f\n mov r0,r3\n bl affichageMess\n cmp r4,#3\n ble 100f\n mov r3,#3\n sub r2,r4,#4\n1: @ loop extract address string on stack\n ldr r0,[fp,r2,lsl #2]\n bl affichageMess\n subs r2,#1\n bge 1b\n100:\n pop {r1-r4,fp,pc}\n\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n.include \"../affichage.inc\"\n", "language": "ARM-Assembly" }, { "code": "width: to :integer input \"give me the array's width: \"\nheight: to :integer input \"give me the array's height: \"\n\narr: array.of: @[width height] 0\n\nx: random 0 dec width\ny: random 0 dec height\n\narr\\[x]\\[y]: 123\n\nprint [\"item at [\" x \",\" y \"] =\" arr\\[x]\\[y]]\n", "language": "Arturo" }, { "code": "Array := []\nInputBox, data,, Enter two integers separated by a Space:`n(ex. 5 7)\nStringSplit, i, data, %A_Space%\nArray[i1,i2] := \"that element\"\nMsgBox, % \"Array[\" i1 \",\" i2 \"] = \" Array[i1,i2]\n", "language": "AutoHotkey" }, { "code": "; == get dimensions from user input\n$sInput = InputBox('2D Array Creation', 'Input comma separated count of rows and columns, i.e. \"5,3\"')\n$aDimension = StringSplit($sInput, ',', 2)\n\n; == create array\nDim $a2D[ $aDimension[0] ][ $aDimension[1] ]\n\n; == write value to last row/last column\n$a2D[ UBound($a2D) -1 ][ UBound($a2D, 2) -1 ] = 'test string'\n\n; == output this value to MsgBox\nMsgBox(0, 'Output', 'row[' & UBound($a2D) -1 & '], col[' & UBound($a2D, 2) -1 & ']' & @CRLF & '= ' & $a2D[ UBound($a2D) -1 ][ UBound($a2D, 2) -1 ] )\n", "language": "AutoIt" }, { "code": "/[0-9]+ [0-9]+/ {\n for(i=0; i < $1; i++) {\n for(j=0; j < $2; j++) {\n arr[i, j] = i*j\n }\n }\n\n # how to scan \"multidim\" array as explained in the GNU AWK manual\n for (comb in arr) {\n split(comb, idx, SUBSEP)\n print idx[1] \",\" idx[2] \"->\" arr[idx[1], idx[2]]\n }\n}\n", "language": "AWK" }, { "code": "arraybase 1\ninput integer \"Enter one positive integer: \", i\ninput integer \"Enter other positive integer: \", j\ndim a(i, j)\na[i, j] = i * j\nprint \"a(\"; string(i); \",\"; string(j); \") = \"; a[i, j]\nend\n", "language": "BASIC256" }, { "code": " INPUT \"Enter array dimensions separated by a comma: \" a%, b%\n\n DIM array(a%, b%)\n array(1, 1) = PI\n PRINT array(1, 1)\n", "language": "BBC-BASIC" }, { "code": "#!/usr/bin/env bqn\n\n# Cut 𝕩 at occurrences of 𝕨, removing separators and empty segments\n# (BQNcrate phrase).\nSplit ← (¬-˜⊢×·+`»⊸>)∘≠⊔⊢\n\n# Natural number from base-10 digits (BQNcrate phrase).\nBase10 ← 10⊸×⊸+˜´∘⌽\n\n# Parse any number of space-separated numbers from string 𝕩.\nParseNums ← {Base10¨ -⟜'0' ' ' Split 𝕩}\n\n# •GetLine is a nonstandard CBQN extension.\n•Show ⥊⟜(↕×´) ParseNums •GetLine@\n", "language": "BQN" }, { "code": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n\n int user1 = 0, user2 = 0;\n printf(\"Enter two integers. Space delimited, please: \");\n scanf(\"%d %d\",&user1, &user2);\n int array[user1][user2];\n array[user1/2][user2/2] = user1 + user2;\n printf(\"array[%d][%d] is %d\\n\",user1/2,user2/2,array[user1/2][user2/2]);\n\n return 0;\n}\n", "language": "C" }, { "code": "/*\n assume this file is c.c ,\n compile and run on linux: cc -Wall -g -DCOMPILE_EXAMPLE c.c -lm -o c && ./c\n*/\n\n#include<stdlib.h>\n#include<stdio.h>\n\nstatic void error(int status, char*message) {\n fprintf(stderr,\"\\n%s\\n\",message);\n exit(status);\n}\n\nstatic void*dwlcalloc(int n,size_t bytes) {\n void*rv = (void*)calloc(n,bytes);\n if (NULL == rv)\n error(1, \"memory allocation failure\");\n return rv;\n}\n\nvoid*allocarray(size_t rank,size_t*shape,size_t itemSize) {\n /*\n Allocates arbitrary dimensional arrays (and inits all pointers)\n with only 1 call to malloc. Lambert Electronics, USA, NY.\n This is wonderful because one only need call free once to deallocate\n the space. Special routines for each size array are not need for\n allocation of for deallocation. Also calls to malloc might be expensive\n because they might have to place operating system requests. One call\n seems optimal.\n */\n size_t size,i,j,dataSpace,pointerSpace,pointers,nextLevelIncrement;\n char*memory,*pc,*nextpc;\n if (rank < 2) {\n if (rank < 0)\n error(1,\"invalid negative rank argument passed to allocarray\");\n size = rank < 1 ? 1 : *shape;\n return dwlcalloc(size,itemSize);\n }\n pointerSpace = 0, dataSpace = 1;\n for (i = 0; i < rank-1; ++i)\n pointerSpace += (dataSpace *= shape[i]);\n pointerSpace *= sizeof(char*);\n dataSpace *= shape[i]*itemSize;\n memory = pc = dwlcalloc(1,pointerSpace+dataSpace);\n pointers = 1;\n for (i = 0; i < rank-2; ) {\n nextpc = pc + (pointers *= shape[i])*sizeof(char*);\n nextLevelIncrement = shape[++i]*sizeof(char*);\n for (j = 0; j < pointers; ++j)\n *((char**)pc) = nextpc, pc+=sizeof(char*), nextpc += nextLevelIncrement;\n }\n nextpc = pc + (pointers *= shape[i])*sizeof(char*);\n nextLevelIncrement = shape[++i]*itemSize;\n for (j = 0; j < pointers; ++j)\n *((char**)pc) = nextpc, pc+=sizeof(char*), nextpc += nextLevelIncrement;\n return memory;\n}\n\n#ifdef COMPILE_EXAMPLE\n\n#include<string.h>\n#include<math.h>\n\n#define Z 5\n#define Y 10\n#define X 39\n\n#define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L))\n\nvoid p_char(void*pv) {\n char s[3];\n int i = 0;\n s[i++] = ' ', s[i++] = *(char*)pv, s[i++] = 0;\n fputs(s, stdout);\n}\n\nvoid display(void*a,size_t rank,size_t*shape,void(*f)(void*)) {\n int i;\n if (0 == rank)\n (*f)(a);\n else if (1 == rank) {\n for (i = 0; i < *shape; ++i)\n (*f)(a+i);\n putchar('\\n');\n } else {\n for (i = 0; i < *shape; ++i)\n display(((void**)a)[i], rank-1, shape+1, f);\n putchar('\\n');\n }\n}\n\nint main() {\t\t\t/* character cell 3D graphics. Whoot */\n char***array;\n float x,y,z;\n size_t rank, shape[3], i, j, k;\n rank = 0;\n shape[rank++] = Z, shape[rank++] = Y, shape[rank++] = X;\n array = allocarray(rank, shape, sizeof(char));\n memset(**array, ' ', X*Y*Z*(sizeof(***array))); /* load the array with spaces */\n for (i = 0; i < X; ++i) {\n x = i/(float)X;\n for (j = 0; j < Y; ++j) {\n y = j/(float)X;\n z = x*y*(4*M_PI);\n z = 5.2*(0.5+(0.276765 - sin(z)*cos(z)*exp(1-z))/0.844087); /* a somewhat carefully designed silly function */\n /* printf(\"%g %g %g\\n\", x, y, z); */\n k = (int)z;\n array[BIND(k, 0, Z-1)][j][i] = '@'; /* BIND ensures a valid index */\n }\n }\n display(array, rank, shape, p_char);\n puts(\"\\nIt is what it is.\");\n free(array);\n return EXIT_SUCCESS;\n}\n#endif\n", "language": "C" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\nint main(int argc, char **argv)\n{\n int user1 = 0, user2 = 0;\n int *a1, **array, row;\n\n printf(\"Enter two integers. Space delimited, please: \");\n scanf(\"%d %d\",&user1, &user2);\n\n a1 = malloc(user1*user2*sizeof(int));\n array = malloc(user1*sizeof(int*));\n for (row=0; row<user1; row++) array[row]=a1+row*user2;\n\n array[user1/2][user2/2] = user1 + user2;\n printf(\"array[%d][%d] is %d\\n\",user1/2,user2/2,array[user1/2][user2/2]);\n free(array);\n free(a1);\n return 0;\n}\n", "language": "C" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\nint main(int argc, char **argv)\n{\n int user1 = 0;\n int space_needed;\n int *a1, **array;\n int row, col, offset;\n\n printf(\"Enter size of array: \");\n scanf(\"%d\",&user1);\n\n space_needed = (user1+1)*user1/2;\n a1 = malloc(space_needed * sizeof(*a1));\n array = malloc(user1 * sizeof(*array));\n for (row=0,offset=0; row<user1; offset+=(user1-row), row++) {\n array[row]=a1+offset-row;\n for (col=row; col<user1; col++)\n array[row][col] = 1+col-row;\n }\n for (row=0; row<user1; row++)\n printf(\"%d \", array[row][user1-1]);\n printf(\"\\n\");\n\n free(array);\n free(a1);\n return 0;\n}\n", "language": "C" }, { "code": "#include <stdio.h>\n#include <alloca.h>\nint main(int argc, char **argv)\n{\n int user1 = 0, user2 = 0;\n int *a1, **array, row;\n\n printf(\"Enter two integers. Space delimited, please: \");\n scanf(\"%d %d\",&user1, &user2);\n\n a1 = alloca(user1*user2*sizeof(int));\n array = alloca(user1*sizeof(int*));\n for (row=0; row<user1; row++) array[row]=a1+row*user2;\n\n array[user1/2][user2/2] = user1 + user2;\n printf(\"array[%d][%d] is %d\\n\",user1/2,user2/2,array[user1/2][user2/2]);\n return 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n\nint main()\n{\n // read values\n int dim1, dim2;\n std::cin >> dim1 >> dim2;\n\n // create array\n double* array_data = new double[dim1*dim2];\n double** array = new double*[dim1];\n for (int i = 0; i < dim1; ++i)\n array[i] = array_data + dim2*i;\n\n // write element\n array[0][0] = 3.5;\n\n // output element\n std::cout << array[0][0] << std::endl;\n\n // get rid of array\n delete[] array;\n delete[] array_data;\n\n return 0;\n}\n", "language": "C++" }, { "code": "#include <iostream>\n#include <vector>\n\nint main()\n{\n // read values\n int dim1, dim2;\n std::cin >> dim1 >> dim2;\n\n // create array\n std::vector<std::vector<double> > array(dim1, std::vector<double>(dim2));\n\n // write element\n array[0][0] = 3.5;\n\n // output element\n std::cout << array[0][0] << std::endl;\n\n // the array is automatically freed at the end of main()\n return 0;\n}\n", "language": "C++" }, { "code": "#include <iostream>\n#include <boost/multi_array.hpp>\n\ntypedef boost::multi_array<double, 2> two_d_array_type;\n\nint main()\n{\n // read values\n int dim1, dim2;\n std::cin >> dim1 >> dim2;\n\n // create array\n two_d_array_type A(boost::extents[dim1][dim2]);\n\n // write element\n A[0][0] = 3.1415;\n\n // read element\n std::cout << A[0][0] << std::endl;\n\n return 0;\n}\n", "language": "C++" }, { "code": "#include <cstdlib>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main (const int argc, const char** argv) {\n if (argc > 2) {\n using namespace boost::numeric::ublas;\n\n matrix<double> m(atoi(argv[1]), atoi(argv[2])); // build\n for (unsigned i = 0; i < m.size1(); i++)\n for (unsigned j = 0; j < m.size2(); j++)\n m(i, j) = 1.0 + i + j; // fill\n std::cout << m << std::endl; // print\n return EXIT_SUCCESS;\n }\n\n return EXIT_FAILURE;\n}\n", "language": "C++" }, { "code": "class Program\n {\n static void Main(string[] args)\n {\n Console.WriteLine(\"Enter two integers. Space delimited please: \");\n string s = Console.ReadLine();\n\n int[,] myArray=new int[(int)s[0],(int)s[2]];\n myArray[0, 0] = 2;\n Console.WriteLine(myArray[0, 0]);\n\n Console.ReadLine();\n }\n }\n", "language": "C-sharp" }, { "code": "10 input \"Enter two positive integers, separated by a comma? \";i,j\n20 dim array(i,j)\n30 array(i,j) = i*j\n40 print \"a(\";str$(i);\",\";str$(j);\") = \";array(i,j)\n50 erase array\n", "language": "Chipmunk-Basic" }, { "code": "import StdEnv\n\nStart :: *World -> { {Real} }\nStart world\n # (console, world) = stdio world\n (_, dim1, console) = freadi console\n (_, dim2, console) = freadi console\n = createArray dim1 (createArray dim2 1.0)\n", "language": "Clean" }, { "code": "(let [rows (Integer/parseInt (read-line))\n cols (Integer/parseInt (read-line))\n a (to-array-2d (repeat rows (repeat cols nil)))]\n (aset a 0 0 12)\n (println \"Element at 0,0:\" (aget a 0 0)))\n", "language": "Clojure" }, { "code": "prompt = proc (s: string) returns (int)\n stream$puts(stream$primary_output(), s)\n return(int$parse(stream$getl(stream$primary_input())))\nend prompt\n\nstart_up = proc ()\n po: stream := stream$primary_output()\n\n % Ask for width and height\n width: int := prompt(\"Width? \")\n height: int := prompt(\"Height? \")\n\n % Create an array of arrays.\n % In order to actually create separate arrays, rather than repeating\n % a reference to the same array over and over, fill_copy must be used.\n arr: array[array[int]] :=\n array[array[int]]$fill_copy(1, width, array[int]$fill(1, height, 0))\n\n % Set a value\n x: int := 1+width/2\n y: int := 1+height/2\n arr[x][y] := 123\n\n % Retrieve the value\n stream$putl(po, \"arr[\" || int$unparse(x) || \"][\" || int$unparse(y)\n || \"] = \" || int$unparse(arr[x][y]))\n\n % The array will be automatically garbage-collected once there\n % are no more references to it.\nend start_up\n", "language": "CLU" }, { "code": "10 print chr$(147);chr$(14);\n15 print \"Size of array:\"\n20 print \"Columns (1-20)\";:input x%\n25 if x%<1 or x%>20 then print \"Try again.\":goto 20\n30 print \"Rows (1-20)\";:input y%\n35 if y%<1 or y%>20 then print \"Try again.\":goto 30\n40 x%=x%-1:y%=y%-1:dim a$(x%,y%)\n50 nx=int(rnd(1)*x%):ny=int(rnd(1)*y%)\n60 a$(nx,ny)=\"X\"\n70 print \"Element\";nx;\",\";ny;\"= '\";a$(nx,ny);\"'\"\n80 clr:rem clear variables from ram\n", "language": "Commodore-BASIC" }, { "code": "(let ((d1 (read))\n (d2 (read)))\n (assert (and (typep d1 '(integer 1))\n (typep d2 '(integer 1)))\n (d1 d2))\n (let ((array (make-array (list d1 d2) :initial-element nil))\n (p1 0)\n (p2 (floor d2 2)))\n (setf (aref array p1 p2) t)\n (print (aref array p1 p2))))\n", "language": "Common-Lisp" }, { "code": "MODULE TestArray;\n(* Implemented in BlackBox Component Builder *)\n\n\tIMPORT Out;\n\n\t(* Open array *)\n\t\n\tPROCEDURE DoTwoDim*;\n\t\tVAR d: POINTER TO ARRAY OF ARRAY OF INTEGER;\n\tBEGIN\n\t\tNEW(d, 5, 4); (* allocating array in memory *)\n\t\td[1, 2] := 100; (* second row, third column element *)\n\t\td[4, 3] := -100; (* fifth row, fourth column element *)\n\t\tOut.Int(d[1, 2], 0); Out.Ln;\n\t\tOut.Int(d[4, 3], 0); Out.Ln;\n\tEND DoTwoDim;\n\nEND TestArray.\n", "language": "Component-Pascal" }, { "code": "require \"random\"\n\nfirst = gets.not_nil!.to_i32\nsecond = gets.not_nil!.to_i32\n\narr = Array(Array(Int32)).new(first, Array(Int32).new second, 0)\n\nrandom = Random.new\n\nfirst = random.rand 0..(first - 1)\nsecond = random.rand 0..(second - 1)\n\narr[first][second] = random.next_int\nputs arr[first][second]\n", "language": "Crystal" }, { "code": "void main() {\n import std.stdio, std.conv, std.string;\n int nRow, nCol;\n\n write(\"Give me the numer of rows: \");\n try {\n nRow = readln.strip.to!int;\n } catch (StdioException) {\n nRow = 3;\n writeln;\n }\n\n write(\"Give me the numer of columns: \");\n try {\n nCol = readln.strip.to!int;\n } catch (StdioException) {\n nCol = 5;\n writeln;\n }\n\n auto array = new float[][](nRow, nCol);\n array[0][0] = 3.5;\n writeln(\"The number at place [0, 0] is \", array[0][0]);\n}\n", "language": "D" }, { "code": "program Project1;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils;\nvar\n matrix:array of array of Byte;\n i,j:Integer;\nbegin\n Randomize;\n //Finalization is not required in this case, but you have to do\n //so when reusing the variable in scope\n Finalize(matrix);\n //Init first dimension with random size from 1..10\n //Remember dynamic arrays are indexed from 0\n SetLength(matrix,Random(10) + 1);\n //Init 2nd dimension with random sizes too\n for i := Low(matrix) to High(matrix) do\n SetLength(matrix[i],Random(10) + 1);\n\n //End of code, the following part is just output\n Writeln(Format('Total amount of columns = %.2d',[Length(matrix)]));\n for i := Low(matrix) to High(matrix) do\n Writeln(Format('Column %.2d = %.2d rows',[i,Length(matrix[i])]));\n\n Readln;\nend.\n", "language": "Delphi" }, { "code": "write \"Number of rows: \"\nnrows = number input\nprint nrows\nwrite \"Number of columns: \"\nncols = number input\nprint ncols\n#\nlen a[][] nrows\nfor i to nrows\n len a[i][] ncols\n.\na[1][1] = 11\nprint a[1][1]\nlen a[][] 0\n", "language": "EasyLang" }, { "code": "import extensions;\n\npublic program()\n{\n var n := new Integer();\n var m := new Integer();\n\n console.write(\"Enter two space delimited integers:\");\n console.loadLine(n,m);\n\n var myArray := class Matrix<int>.allocate(n,m);\n\n myArray.setAt(0,0,2);\n\n console.printLine(myArray.at(0, 0))\n}\n", "language": "Elena" }, { "code": "import system'routines;\nimport extensions;\n\npublic program()\n{\n auto n := new Integer();\n auto m := new Integer();\n\n console.write(\"Enter two space delimited integers:\");\n console.loadLine(n,m);\n\n auto myArray2 := new object[][](n.Value).populate::(int i => (new object[](m.Value)) );\n myArray2[0][0] := 2;\n myArray2[1][0] := \"Hello\";\n\n console.printLine(myArray2[0][0]);\n console.printLine(myArray2[1][0]);\n}\n", "language": "Elena" }, { "code": "defmodule TwoDimArray do\n\n def create(w, h) do\n List.duplicate(0, w)\n |> List.duplicate(h)\n end\n\n def set(arr, x, y, value) do\n List.replace_at(arr, x,\n List.replace_at(Enum.at(arr, x), y, value)\n )\n end\n\n def get(arr, x, y) do\n arr |> Enum.at(x) |> Enum.at(y)\n end\nend\n\n\nwidth = IO.gets \"Enter Array Width: \"\nw = width |> String.trim() |> String.to_integer()\n\nheight = IO.gets \"Enter Array Height: \"\nh = height |> String.trim() |> String.to_integer()\n\narr = TwoDimArray.create(w, h)\narr = TwoDimArray.set(arr,2,0,42)\n\nIO.puts(TwoDimArray.get(arr,2,0))\n", "language": "Elixir" }, { "code": "-module( two_dimensional_array ).\n\n-export( [create/2, get/3, set/4, task/0] ).\n\ncreate( X, Y ) -> array:new( [{size, X}, {default, array:new( [{size, Y}] )}] ).\n\nget( X, Y, Array ) -> array:get( Y, array:get(X, Array) ).\n\nset( X, Y, Value, Array ) ->\n\tY_array = array:get( X, Array ),\n\tNew_y_array = array:set( Y, Value, Y_array ),\n\tarray:set( X, New_y_array, Array ).\n\ntask() ->\n\t{ok, [X, Y]} = io:fread( \"Input two integers. Space delimited, please: \", \"~d ~d\" ),\n\tArray = create( X, Y ),\n\tNew_array = set( X - 1, Y - 1, X * Y, Array ),\n\tio:fwrite( \"In position ~p ~p we have ~p~n\", [X - 1, Y - 1, get( X - 1, Y - 1, New_array)] ).\n", "language": "Erlang" }, { "code": "PROGRAM DYNAMIC\n\n!$DYNAMIC\nDIM A%[0,0]\n\nBEGIN\n PRINT(CHR$(12);) !CLS\n INPUT(\"Subscripts\",R%,C%)\n !$DIM A%[R%,C%]\n A%[2,3]=6\n PRINT(\"Value in row\";2;\"and col\";3;\"is\";A%[2,3])\nEND PROGRAM\n", "language": "ERRE" }, { "code": "include get.e\n\nsequence array\ninteger height,width,i,j\n\nheight = floor(prompt_number(\"Enter height: \",{}))\nwidth = floor(prompt_number(\"Enter width: \",{}))\n\narray = repeat(repeat(0,width),height)\n\ni = floor(height/2+0.5)\nj = floor(width/2+0.5)\narray[i][j] = height + width\n\nprintf(1,\"array[%d][%d] is %d\\n\", {i,j,array[i][j]})\n", "language": "Euphoria" }, { "code": "open System\n\nlet width = int( Console.ReadLine() )\nlet height = int( Console.ReadLine() )\nlet arr = Array2D.create width height 0\narr.[0,0] <- 42\nprintfn \"%d\" arr.[0,0]\n", "language": "F-Sharp" }, { "code": "USING: io kernel math.matrices math.parser prettyprint\nsequences ;\nIN: rosettacode.runtime2darray\n\n: set-Mi,j ( elt {i,j} matrix -- )\n[ first2 swap ] dip nth set-nth ;\n: Mi,j ( {i,j} matrix -- elt )\n[ first2 swap ] dip nth nth ;\n\n: example ( -- )\nreadln readln [ string>number ] bi@ zero-matrix ! create the array\n[ [ 42 { 0 0 } ] dip set-Mi,j ] ! set the { 0 0 } element to 42\n[ [ { 0 0 } ] dip Mi,j . ] ! read the { 0 0 } element\nbi ;\n", "language": "Factor" }, { "code": "?m; {imput the dimensions of the array}\n?n;\nArray a[m,n]; {generate an array of m rows and n columns}\na[m\\2, n\\2] := m+n-1; {put some value in one of the cells}\n!!a[m\\2, n\\2]; {display that entry}\n@[a]; {delete the array}\n", "language": "Fermat" }, { "code": ": cell-matrix\n create ( width height \"name\" ) over , * cells allot\n does> ( x y -- addr ) dup cell+ >r @ * + cells r> + ;\n\n5 5 cell-matrix test\n\n36 0 0 test !\n0 0 test @ . \\ 36\n", "language": "Forth" }, { "code": "INTEGER DMATRIX my-matrix{{\n& my-matrix{{ 8 9 }}malloc\n\n8 my-matrix{{ 3 4 }} !\nmy-matrix{{ 3 4 }} @ .\n\n& my-matrix{{ }}free\n", "language": "Forth" }, { "code": "PROGRAM Example\n\n IMPLICIT NONE\n INTEGER :: rows, columns, errcheck\n INTEGER, ALLOCATABLE :: array(:,:)\n\n WRITE(*,*) \"Enter number of rows\"\n READ(*,*) rows\n WRITE(*,*) \"Enter number of columns\"\n READ(*,*) columns\n\n ALLOCATE (array(rows,columns), STAT=errcheck) ! STAT is optional and is used for error checking\n\n array(1,1) = 42\n\n WRITE(*,*) array(1,1)\n\n DEALLOCATE (array, STAT=errcheck)\n\nEND PROGRAM Example\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nDim As Integer i, j\nInput \"Enter two positive integers, separated by a comma\"; i, j\nDim a(1 To i, 1 To j) As Integer\na(i, j) = i * j\nPrint \"a(\"; Str(i); \",\"; Str(j); \") =\"; a(i, j)\nErase a\nPrint\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "[rows, cols] = dims = eval[input[\"Enter dimensions: \", [\"Rows\", \"Columns\"]]]\na = new array[dims, 0] // Create and initialize to 0\na@(rows-1)@(cols-1) = 10\nprintln[a@(rows-1)@(cols-1)]\n", "language": "Frink" }, { "code": "CFStringRef iStr, jStr\nlong i, j\n\niStr = input @\"Enter one positive integer: \"\njStr = input @\"Enter other positive integer: \"\ni = fn StringIntegerValue(iStr)\nj = fn StringIntegerValue(jStr)\nmda (0, 0) = {i, j}\nmda (i, j) = i * j\nprintf @\"mda(%ld, %ld) = %ld\", i, j, mda_integer (i, j)\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "# Creating an array of 0\na := NullMat(2, 2);\n# [ [ 0, 0 ], [ 0, 0 ] ]\n\n# Some assignments\na[1][1] := 4;\na[1][2] := 5;\na[2][1] := 3;\na[2][2] := 4;\n\na\n# [ [ 4, 5 ], [ 3, 4 ] ]\n\nDeterminant(a);\n# 1\n", "language": "GAP" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var row, col int\n fmt.Print(\"enter rows cols: \")\n fmt.Scan(&row, &col)\n\n // allocate composed 2d array\n a := make([][]int, row)\n for i := range a {\n a[i] = make([]int, col)\n }\n\n // array elements initialized to 0\n fmt.Println(\"a[0][0] =\", a[0][0])\n\n // assign\n a[row-1][col-1] = 7\n\n // retrieve\n fmt.Printf(\"a[%d][%d] = %d\\n\", row-1, col-1, a[row-1][col-1])\n\n // remove only reference\n a = nil\n // memory allocated earlier with make can now be garbage collected.\n}\n", "language": "Go" }, { "code": " // allocate composed 2d array\n a := make([][]int, row)\n e := make([]int, row * col)\n for i := range a {\n a[i] = e[i*col:(i+1)*col]\n }\n", "language": "Go" }, { "code": "func get(r, c int) int {\n return e[r*cols+c]\n}\n", "language": "Go" }, { "code": "def make2d = { nrows, ncols ->\n (0..<nrows).collect { [0]*ncols }\n}\n", "language": "Groovy" }, { "code": "def r = new Random()\n\nSystem.in.splitEachLine(/,\\s*/) { dim ->\n def nrows = dim[0] as int\n def ncols = dim[1] as int\n\n def a2d = make2d(nrows, ncols)\n\n def row = r.nextInt(nrows)\n def col = r.nextInt(ncols)\n def val = r.nextInt(nrows*ncols)\n\n a2d[row][col] = val\n\n println \"a2d[${row}][${col}] == ${a2d[row][col]}\"\n\n a2d.each { println it }\n println()\n}\n", "language": "Groovy" }, { "code": "10 INPUT \"Enter two positive integers, separated by a comma\"; I, J\n20 DIM ARRAY(I, J)\n30 ARRAY(I, J) = I * J\n40 PRINT \"a(\"; STR$(I); \",\"; STR$(J); \" ) =\"; ARRAY(I, J)\n50 ERASE ARRAY\n", "language": "GW-BASIC" }, { "code": "import Data.Array\n\ndoit n m = a!(0,0) where a = array ((0,0),(n,m)) [((0,0),42)]\n", "language": "Haskell" }, { "code": "REAL :: array(1)\n\nDLG(NameEdit=rows, NameEdit=cols, Button='OK', TItle='Enter array dimensions')\n\nALLOCATE(array, cols, rows)\narray(1,1) = 1.234\nWRITE(Messagebox, Name) array(1,1)\n", "language": "HicEst" }, { "code": "procedure main(args)\n nr := integer(args[1]) | 3 # Default to 3x3\n nc := integer(args[2]) | 3\n\n A := list(nr)\n every !A := list(nc)\n\n x := ?nr # Select a random element\n y := ?nc\n\n A[x][y] := &pi\n write(\"A[\",x,\"][\",y,\"] -> \",A[x][y])\nend\n", "language": "Icon" }, { "code": "read, x, prompt='Enter x size:'\nread, y, prompt='Enter y size:'\nd = fltarr(x,y)\n\nd[3,4] = 5.6\nprint,d[3,4]\n;==> outputs 5.6\n\ndelvar, d\n", "language": "IDL" }, { "code": "100 INPUT PROMPT \"Enter array dimensions separated by a coma: \":A,B\n110 NUMERIC ARRAY(1 TO A,1 TO B)\n120 LET ARRAY(1,1)=PI\n130 PRINT ARRAY(1,1)\n", "language": "IS-BASIC" }, { "code": " array1=:i. 3 4 NB. a 3 by 4 array with arbitrary values\n array2=: 5 6 $ 2 NB. a 5 by 6 array where every value is the number 2\n", "language": "J" }, { "code": " array1=: 99 (<0 0)} array1\n", "language": "J" }, { "code": " (<0 0) { array1\n", "language": "J" }, { "code": " array1=: 0\n", "language": "J" }, { "code": " erase'array1'\n", "language": "J" }, { "code": "task=: verb define\n assert. y -: 0 0 + , y NB. error except when 2 dimensions are specified\n INIT=. 0 NB. array will be populated with this value\n NEW=. 1 NB. we will later update one location with this value\n ARRAY=. y $ INIT NB. here, we create our 2-dimensional array\n INDEX=. < ? $ ARRAY NB. pick an arbitrary location within our array\n ARRAY=. NEW INDEX} ARRAY NB. use our new value at that location\n INDEX { ARRAY NB. and return the value from that location\n)\n", "language": "J" }, { "code": " task 99 99\n1\n", "language": "J" }, { "code": "'init new' =. ' ';'x' NB. literals\n'init new' =. 1r2;2r3 NB. fractions\n'init new' =. a: ; <<'Rosetta' NB. boxes\n", "language": "J" }, { "code": "import java.util.Scanner;\n\npublic class twoDimArray {\n public static void main(String[] args) {\n Scanner in = new Scanner(System.in);\n\n int nbr1 = in.nextInt();\n int nbr2 = in.nextInt();\n\n double[][] array = new double[nbr1][nbr2];\n array[0][0] = 42.0;\n System.out.println(\"The number at place [0 0] is \" + array[0][0]);\n }\n}\n", "language": "Java" }, { "code": "var width = Number(prompt(\"Enter width: \"));\nvar height = Number(prompt(\"Enter height: \"));\n\n//make 2D array\nvar arr = new Array(height);\n\nfor (var i = 0; i < h; i++) {\n arr[i] = new Array(width);\n}\n\n//set value of element\na[0][0] = 'foo';\n//print value of element\nconsole.log('arr[0][0] = ' + arr[0][0]);\n\n//cleanup array\narr = void(0);\n", "language": "JavaScript" }, { "code": "# A function to create an m x n matrix\n# filled with the input element\ndef matrix(m;n):\n . as $init\n | ( [ range(0; n + 1) ] | map($init)) as $row\n | ( [ range(0; m + 1) ] | map($row))\n ;\n\n# Task: create a matrix with dimensions specified by the user\n# and set the [1,2] element:\n(0 | matrix($m|tonumber; $n|tonumber)) | setpath([1,2]; 99)\n", "language": "Jq" }, { "code": "[[0,0,0,0],[0,0,99,0],[0,0,0,0]]\n", "language": "Jq" }, { "code": "function input(prompt::AbstractString)\n print(prompt)\n return readline()\nend\n\nn = input(\"Upper bound for dimension 1: \") |>\n x -> parse(Int, x)\nm = input(\"Upper bound for dimension 2: \") |>\n x -> parse(Int, x)\n\nx = rand(n, m)\ndisplay(x)\nx[3, 3] # overloads `getindex` generic function\nx[3, 3] = 5.0 # overloads `setindex!` generic function\nx::Matrix # `Matrix{T}` is an alias for `Array{T, 2}`\nx = 0; gc() # Julia has no `del` command, rebind `x` and call the garbage collector\n", "language": "Julia" }, { "code": "fun main(args: Array<String>) {\n // build\n val dim = arrayOf(10, 15)\n val array = Array(dim[0], { IntArray(dim[1]) } )\n\n // fill\n array.forEachIndexed { i, it ->\n it.indices.forEach { j ->\n it[j] = 1 + i + j\n }\n }\n\n // print\n array.forEach { println(it.asList()) }\n}\n", "language": "Kotlin" }, { "code": "input \"Enter first array dimension \"; a\ninput \"Enter second array dimension \"; b\n\ndim array( a, b)\n\narray( 1, 1) = 123.456\nprint array( 1, 1)\n\nend\n", "language": "Liberty-BASIC" }, { "code": "make \"a2 mdarray [5 5]\nmdsetitem [1 1] :a2 0 ; by default, arrays are indexed starting at 1\nprint mditem [1 1] :a2 ; 0\n", "language": "Logo" }, { "code": "function multiply(n, a, b) if a <= b then return n, multiply(n, a + 1, b) end end\n\na, b = io.read() + 0, io.read() + 0\nmatrix = {multiply({multiply(1, 1, b)}, 1, a)}\nmatrix[a][b] = 5\nprint(matrix[a][b])\nprint(matrix[1][1])\n", "language": "Lua" }, { "code": "Module CheckArray {\n Do {\n Input \"A, B=\", A% ,B%\n } Until A%>0 and B%>0\n\n \\\\ 1@ is 1 Decimal\n addone=lambda N=1@ ->{=N : N++}\n Dim Base 1, Arr(A%,B%)<<addone()\n \\\\ pi also is decimal\n Arr(1,1)=pi\n Print Arr(1,1)\n Print Arr()\n \\\\ all variables/arrays/inner functions/modules erased now\n}\nCheckArray\n", "language": "M2000-Interpreter" }, { "code": "> a := Array( 1 .. 3, 1 .. 4 ): # initialised to 0s\n> a[1,1] := 1: # assign an element\n> a[2,3] := 4: # assign an element\n> a; # display the array\n [1 0 0 0]\n [ ]\n [0 0 4 0]\n [ ]\n [0 0 0 0]\n\n> a := 'a': # unassign the name\n> gc(); # force a garbage collection; may or may not actually collect the array, but it will be eventually\n", "language": "Maple" }, { "code": "arrayFun[m_Integer,n_Integer]:=Module[{array=ConstantArray[0,{m,n}]},\n array[[1,1]]=RandomReal[];\n array[[1,1]]\n]\n", "language": "Mathematica" }, { "code": "width = input('Array Width: ');\nheight = input('Array Height: ');\n\narray = zeros(width,height);\n\narray(1,1) = 12;\n\ndisp(['Array element (1,1) = ' num2str(array(1,1))]);\n\nclear array; % de-allocate (remove) array from workspace\n", "language": "MATLAB" }, { "code": "Array Width: 18\nArray Height: 12\nArray element (1,1) = 12\n", "language": "MATLAB" }, { "code": "printf(true, \"in the following terminate every number with semicolon `;'\")$\nn: readonly(\"Input x-size: \")$\nm: readonly(\"Input y-size: \")$\na: make_array(fixnum, n, m)$\nfillarray(a, makelist(i, i, 1, m*n))$\n\n/* indexing starts from 0 */\nprint(a[0,0]);\nprint(a[n-1,m-1]);\n", "language": "Maxima" }, { "code": "a = getKBValue prompt:\"Enter first dimension:\"\nb = getKBValue prompt:\"Enter second dimension:\"\narr1 = #()\narr2 = #()\narr2[b] = undefined\nfor i in 1 to a do\n(\n append arr1 (deepCopy arr2)\n)\narr1[a][b] = 1\nprint arr1[a][b]\n", "language": "MAXScript" }, { "code": "10 PRINT \"ENTER ONE POSITIVE INTEGER: \"\n20 INPUT I\n30 PRINT \"ENTER OTHER POSITIVE INTEGER: \"\n40 INPUT J\n50 LET A(I,J) = I*J\n60 PRINT \"A(\";I;\",\";J;\") = \";A(I,J)\n70 END\n", "language": "Minimal-BASIC" }, { "code": "ARA2D\n NEW X,Y,A,I,J\nREARA\n WRITE !,\"Please enter two positive integers\"\n READ:10 !,\"First: \",X\n READ:10 !,\"Second: \",Y\n GOTO:(X\\1'=X)!(X<0)!(Y\\1'=Y)!(Y<0) REARA\n FOR I=1:1:X FOR J=1:1:Y SET A(I,J)=I+J\n WRITE !,\"The corner of X and Y is \",A(X,Y)\n KILL X,Y,A,I,J\n QUIT\n", "language": "MUMPS" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\nsay \"give me the X and Y dimensions as two positive integers:\"\nparse ask xDim yDim\nxPos = xDim % 2 -- integer divide to get close to the middle of the array\nyPos = yDim % 2\n\narry = Rexx[xDim, yDim]\narry[xPos, yPos] = xDim / yDim -- make up a value...\nsay \"arry[\"xPos\",\"yPos\"]:\" arry[xPos, yPos]\nreturn\n", "language": "NetRexx" }, { "code": "import strutils, rdstdin\n\nlet\n w = readLineFromStdin(\"Width: \").parseInt()\n h = readLineFromStdin(\"Height: \").parseInt()\n\n# Create the rows.\nvar s = newSeq[seq[int]](h)\n\n# Create the columns.\nfor i in 0 ..< h:\n s[i].newSeq(w)\n\n# Store a value in an element.\ns[0][0] = 5\n\n# Retrieve and print it.\necho s[0][0]\n\n# The allocated memory is freed by the garbage collector.\n", "language": "Nim" }, { "code": "class TwoDimArray {\n function : Main(args : String[]) ~ Nil {\n rows := Standard->ReadLine()->ToInt();\n cols := Standard->ReadLine()->ToInt();\n\n if(rows > 0 & cols > 0) {\n array := Float->New[rows, cols];\n array[0,0] := 42.0;\n Standard->Print(\"The number at place [0,] is: \")->PrintLine(array[0,0]);\n }\n }\n}\n", "language": "Objeck" }, { "code": "#import <Foundation/Foundation.h>\n\nint main()\n{\n @autoreleasepool {\n int num1, num2;\n scanf(\"%d %d\", &num1, &num2);\n\n NSLog(@\"%d %d\", num1, num2);\n\n NSMutableArray *arr = [NSMutableArray arrayWithCapacity: (num1*num2)];\n // initialize it with 0s\n for(int i=0; i < (num1*num2); i++) [arr addObject: @0];\n\n // replace 0s with something more interesting\n for(int i=0; i < num1; i++) {\n for(int j=0; j < num2; j++) {\n arr[i*num2+j] = @(i*j);\n }\n }\n\n // access a value: i*num2+j, where i,j are the indexes for the bidimensional array\n NSLog(@\"%@\", arr[1*num2+3]);\n }\n return 0;\n}\n", "language": "Objective-C" }, { "code": "let nbr1 = read_int ();;\nlet nbr2 = read_int ();;\nlet array = Array.make_matrix nbr1 nbr2 0.0;;\narray.(0).(0) <- 3.5;;\nprint_float array.(0).(0); print_newline ();;\n", "language": "OCaml" }, { "code": "let nbr1 = read_int ();;\nlet nbr2 = read_int ();;\nlet arr = Bigarray.Array2.create Bigarray.float32 Bigarray.c_layout nbr1 nbr2 ;;\narr.{0,0} <- 3.5;;\nprint_float arr.{0,0}; print_newline ();;\n", "language": "OCaml" }, { "code": "Say \"enter first dimension\"\npull d1\nsay \"enter the second dimension\"\npull d2\na = .array~new(d1, d2)\na[1, 1] = \"Abc\"\nsay a[1, 1]\nsay d1 d2 a[d1,d2]\nsay a[10,10]\nmax=1000000000\nb = .array~new(max,max)\n", "language": "OoRexx" }, { "code": "declare\n %% Read width and height from stdin\n class TextFile from Open.file Open.text end\n StdIn = {New TextFile init(name:stdin)}\n Width = {String.toInt {StdIn getS($)}}\n Height = {String.toInt {StdIn getS($)}}\n %% create array\n Arr = {Array.new 1 Width unit}\nin\n for X in 1..Width do\n Arr.X := {Array.new 1 Height 0}\n end\n %% set and read element\n Arr.1.1 := 42\n {Show Arr.1.1}\n", "language": "Oz" }, { "code": "tmp(m,n)={\n my(M=matrix(m,n,i,j,0));\n M[1,1]=1;\n M[1,1]\n};\n", "language": "PARI-GP" }, { "code": "program array2d(input, output);\n\ntype\n tArray2d(dim1, dim2: integer) = array[1 .. dim1, 1 .. dim2] of real;\n pArray2D = ^tArray2D;\n\nvar\n d1, d2: integer;\n data: pArray2D;\n\nbegin\n { read values }\n readln(d1, d2);\n\n { create array }\n new(data, d1, d2);\n\n { write element }\n data^[1,1] := 3.5;\n\n { output element }\n writeln(data^[1,1]);\n\n { get rid of array }\n dispose(data);\nend.\n", "language": "Pascal" }, { "code": "sub make_array($ $){\n # get array sizes from provided params, but force numeric value\n my $x = ($_[0] =~ /^\\d+$/) ? shift : 0;\n my $y = ($_[0] =~ /^\\d+$/) ? shift : 0;\n\n # define array, then add multi-dimensional elements\n my @array;\n $array[0][0] = 'X '; # first by first element\n $array[5][7] = 'X ' if (5 <= $y and 7 <= $x); # sixth by eighth element, if the max size is big enough\n $array[12][15] = 'X ' if (12 <= $y and 15 <= $x); # thirteenth by sixteenth element, if the max size is big enough\n\n # loop through the elements expected to exist base on input, and display the elements contents in a grid\n foreach my $dy (0 .. $y){\n foreach my $dx (0 .. $x){\n (defined $array[$dy][$dx]) ? (print $array[$dy][$dx]) : (print '. ');\n }\n print \"\\n\";\n }\n}\n", "language": "Perl" }, { "code": "sub array {\n my ($x, $y) = @_;\n map {[ (0) x $x ]} 1 .. $y\n}\n\nmy @square = array 3, 3;\n\n# everything above this line is mostly redundant in perl,\n# since perl would have created the array automatically when used.\n# however, the above function initializes the array elements to 0,\n# while perl would have used undef\n#\n# $cube[3][4][5] = 60 # this is valid even if @cube was previously undefined\n\n$square[1][1] = 1;\nprint \"@$_\\n\" for @square;\n> 0 0 0\n> 0 1 0\n> 0 0 0\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">-- demo\\rosetta\\Create2Darray.exw</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span> <span style=\"color: #000080;font-style:italic;\">-- (layout/spacing leaves a little to be desired...)</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">lab</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">tab</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">dlg</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">valuechanged_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">tab</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tab</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">scanf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d %d\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">j</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">array</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000000;\">array</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">height</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">width</span>\n\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"array[%d][%d] is %d\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">array</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]})</span>\n\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupRefresh</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">lab</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Enter two numbers (&gt;0) separated by a space\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">tab</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupText</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"VALUECHANGED_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"valuechanged_cb\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"EXPAND=HORIZONTAL\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">IupVbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #7060A8;\">IupHbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">lab</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tab</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #008000;\">\"GAP=10,NORMALIZESIZE=VERTICAL\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #7060A8;\">IupHbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">})},</span><span style=\"color: #008000;\">\"MARGIN=5x5\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">`TITLE=\"Create 2D array\"`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "include ..\\Utilitys.pmt\n\n\"Enter height: \" input tonum nl\n\"Enter width: \" input tonum nl\n0 swap repeat swap repeat /# create two dimensional array/list. All zeroes #/\n-1 get 99 -1 set -1 set /# set the last element o last dimension #/\npstack /# show the content of the stack #/\n-1 get -1 get \"Value of the last element of the last dimension: \" print print drop\ndrop /# remove array/list from the stack #/\n", "language": "Phixmonti" }, { "code": "include ..\\Utilitys.pmt\n\n\"Enter height: \" input tonum nl\n\"Enter width: \" input tonum nl\n0 swap repeat swap repeat /# create two dimensional array/list. All zeroes #/\n-1 get 99 ( -1 -1 ) mset /# set the last element o last dimension #/\npstack /# show the content of the stack #/\n( -1 -1 ) mget \"Value of the last element of the last dimension: \" print print drop\ndrop /# remove array/list from the stack #/\n", "language": "Phixmonti" }, { "code": "include ..\\Utilitys.pmt\n\n\"Enter height: \" input tonum nl\n\"Enter width: \" input tonum nl\n0 swap repeat swap repeat /# create two dimensional array/list. All zeroes #/\n99 ( -1 -1 ) sset /# set the last element o last dimension #/\npstack /# show the content of the stack #/\n( -1 -1 ) sget \"Value of the last element of the last dimension: \" print print\ndrop /# remove array/list from the stack #/\n", "language": "Phixmonti" }, { "code": "import util.\n\ngo =>\n print(\"Input the number of rows and columns: \"),\n [Rows,Cols]=split(read_line()).map(to_int),\n X=new_array(Rows,Cols),\n X[1,1] = Rows*Cols+1,\n println(X[1,1]).\n", "language": "Picat" }, { "code": "(de 2dimTest (DX DY)\n (let A (make (do DX (link (need DY))))\n (set (nth A 3 3) 999) # Set A[3][3] to 999\n (mapc println A) # Print all\n (get A 3 3) ) ) # Return A[3][3]\n\n(2dimTest 5 5)\n", "language": "PicoLisp" }, { "code": "/* First way using a controlled variable: */\n\ndeclare A(*,*) float controlled;\nget list (m, n);\nallocate A(m,n);\nget list (A);\nput skip list (A);\n\n/* The array remains allocated until the program terminates, */\n/* or until explicitly destroyed using a FREE statement. */\n\nfree A;\n", "language": "PL-I" }, { "code": " 6.00000E+0000 5.00000E+0000 4.00000E+0000 3.00000E+0000 2.00000E+0000\n 1.00000E+0000\n", "language": "PL-I" }, { "code": "/* Second way using a BEGIN block: */\n\nget list (m, n);\nbegin;\n declare A(m, n) float;\n get list (A);\n put skip list (A);\nend;\n\n/* The array is automatically destroyed when the block terminates. */\n", "language": "PL-I" }, { "code": " 1.00000E+0000 2.00000E+0000 3.00000E+0000 4.00000E+0000 5.00000E+0000\n 6.00000E+0000 7.00000E+0000 8.00000E+0000 9.00000E+0000 1.00000E+0001\n 1.10000E+0001 1.20000E+0002\n", "language": "PL-I" }, { "code": "/* Third way using a PROCEDURE block: */\n\nget list (m, n);\ncall S (m, n);\nS: procedure (m, n);\n declare A(m, n) float;\n get list (A);\n put skip list (A);\nend S;\n\n/* The array is automatically destroyed when the procedure terminates. */\n", "language": "PL-I" }, { "code": " 1.00000E+0000 2.00000E+0000 3.00000E+0000 4.00000E+0000 5.00000E+0000\n 6.00000E+0000 7.00000E+0000 8.00000E+0000 9.00000E+0000 1.00000E+0001\n 1.10000E+0001 1.20000E+0001 1.30000E+0001 1.40000E+0001 1.50000E+0001\n 1.60000E+0001 1.70000E+0001 1.80000E+0001 1.90000E+0001 2.00000E+0001\n", "language": "PL-I" }, { "code": "vars itemrep;\nincharitem(charin) -> itemrep;\n;;; Read sizes\nvars n1 = itemrep(), n2= itemrep();\n;;; Create 0 based array\nvars ar = newarray([0 ^(n1 - 1) 0 ^(n2 - 1)], 0);\n;;; Set element value\n15 -> ar(0, 0);\n;;; Print element value\nar(0,0) =>\n;;; Make sure array is unreferenced\n0 -> ar;\n", "language": "Pop11" }, { "code": "function Read-ArrayIndex ([string]$Prompt = \"Enter an integer greater than zero\")\n{\n [int]$inputAsInteger = 0\n\n while (-not [Int]::TryParse(([string]$inputString = Read-Host $Prompt), [ref]$inputAsInteger))\n {\n $inputString = Read-Host \"Enter an integer greater than zero\"\n }\n\n if ($inputAsInteger -gt 0) {return $inputAsInteger} else {return 1}\n}\n\n$x = $y = $null\n\ndo\n{\n if ($x -eq $null) {$x = Read-ArrayIndex -Prompt \"Enter two dimensional array index X\"}\n if ($y -eq $null) {$y = Read-ArrayIndex -Prompt \"Enter two dimensional array index Y\"}\n}\nuntil (($x -ne $null) -and ($y -ne $null))\n\n$array2d = New-Object -TypeName 'System.Object[,]' -ArgumentList $x, $y\n", "language": "PowerShell" }, { "code": "[int]$k = 1\n\nfor ($i = 0; $i -lt 6; $i++)\n{\n 0..5 | ForEach-Object -Begin {$k += 10} -Process {$array2d[$i,$_] = $k + $_}\n}\n", "language": "PowerShell" }, { "code": "for ($i = 0; $i -lt 6; $i++)\n{\n \"{0}`t{1}`t{2}`t{3}`t{4}`t{5}\" -f (0..5 | ForEach-Object {$array2d[$i,$_]})\n}\n", "language": "PowerShell" }, { "code": "$array2d[2,2]\n", "language": "PowerShell" }, { "code": ":- dynamic array/2.\n\nrun :-\n write('Enter two positive integers, separated by a comma: '),\n read((I,J)),\n assert(array(I,J)),\n Value is I * J,\n format('a(~w,~w) = ~w', [I, J, Value]),\n retractall(array(_,_)).\n", "language": "Prolog" }, { "code": "If OpenConsole()\n Define x, y\n\n Print(\"Input X-Size: \")\n x = Val(Input())\n\n Print(\"Input Y-Size: \")\n y = Val(Input())\n\n Dim a(x,y) ; Should really check if x & y are larger then 1, but that would be less fun....\n\n a(1,1)=Random(1000)\n PrintN(\"a(1,1)= \" + Str(a(1,1)) )\n\n PrintN(\"Press ENTER to exit\"):Input()\n End ; Close down and let PureBasic delete the Console and all variables.\nEndIf\n", "language": "PureBasic" }, { "code": "width = int(raw_input(\"Width of myarray: \"))\nheight = int(raw_input(\"Height of Array: \"))\nmyarray = [[0] * width for i in range(height)]\nmyarray[0][0] = 3.5\nprint (myarray[0][0])\n", "language": "Python" }, { "code": "myarray = {(w,h): 0 for w in range(width) for h in range(height)}\n# or, in pre 2.7 versions of Python: myarray = dict(((w,h), 0) for w in range(width) for h in range(height))\nmyarray[(0,0)] = 3.5\nprint (myarray[(0,0)])\n", "language": "Python" }, { "code": "INPUT \"Enter two positive integers, separated by a comma\"; i, j\nDIM array(1 TO i, 1 TO j)\narray(i, j) = i * j\nPRINT \"a(\"; STR$(i); \",\"; STR$(j); \" ) = \"; array(i, j)\nERASE array\n", "language": "QBasic" }, { "code": " [ witheach peek ] is {peek} ( { p --> x )\n\n [ dip dup\n witheach [ peek dup ]\n drop ] is depack ( { p --> * )\n\n [ reverse\n witheach\n [ dip swap poke ] ] is repack ( * p --> { )\n\n [ dup dip\n [ rot dip\n [ depack drop ] ]\n repack ] is {poke} ( x { p --> { )\n\n [ 0 swap of\n nested swap of ] is 2array ( n n --> [ )\n\n\n $ \"Array width (at least 2): \" input $->n drop\n $ \"Array length (at least 5): \" input $->n drop\n\n say \"Creating \" over echo say \" by \"\n dup echo say \" array.\" cr\n\n 2array\n\n say \"Writing 12345 to element {1,4} of array.\" cr\n\n 12345 swap ' [ 1 4 ] {poke}\n\n say \"Reading element {1,4} of array: \"\n\n ' [ 1 4 ] {peek} echo\n", "language": "Quackery" }, { "code": " CLS\n INPUT a, b 'inputs need to be separated by commas\n DIM array (1 TO a, 1 TO b)\n array(1,1) = 42\n PRINT array(1,1)\n ERASE array\n", "language": "QuickBASIC" }, { "code": "input <- readline(\"Enter two integers. Space delimited, please: \")\ndims <- as.numeric(strsplit(input, \" \")[[1]])\narr <- array(dim=dims)\nii <- ceiling(dims[1]/2)\njj <- ceiling(dims[2]/2)\narr[ii, jj] <- sum(dims)\ncat(\"array[\", ii, \",\", jj, \"] is \", arr[ii, jj], \"\\n\", sep=\"\")\n", "language": "R" }, { "code": "#lang racket\n\n(printf \"Enter XY dimensions: \")\n(define xy (cons (read) (read)))\n(define array (for/vector ([x (car xy)]) (for/vector ([y (cdr xy)]) 0)))\n\n(printf \"Enter a number for the top-left: \")\n(vector-set! (vector-ref array 0) 0 (read))\n(printf \"Enter a number for the bottom-right: \")\n(vector-set! (vector-ref array (sub1 (car xy))) (sub1 (cdr xy)) (read))\n\narray\n", "language": "Racket" }, { "code": "my ($major,$minor) = prompt(\"Dimensions? \").comb(/\\d+/);\nmy @array = [ '@' xx $minor ] xx $major;\n@array[ *.rand ][ *.rand ] = ' ';\n.say for @array;\n", "language": "Raku" }, { "code": "Dimensions? 5x35\n[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]\n[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]\n[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]\n[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]\n[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]\n", "language": "Raku" }, { "code": "my ($major,$minor) = +«prompt(\"Dimensions? \").comb(/\\d+/);\nmy Int @array[$major;$minor] = (7 xx $minor ) xx $major;\n@array[$major div 2;$minor div 2] = 42;\nsay @array;\n", "language": "Raku" }, { "code": "Dimensions? 3 x 10\n[[7 7 7 7 7 7 7 7 7 7] [7 7 7 7 7 42 7 7 7 7] [7 7 7 7 7 7 7 7 7 7]]\n", "language": "Raku" }, { "code": "Red [\"Create two-dimensional array at runtime\"]\n\nwidth: to-integer ask \"What is the width of the array? \"\nheight: to-integer ask \"What is the height of the array? \"\n\n ; 2D arrays are just nested blocks in Red.\nmatrix: copy [] ; Make an empty block to hold our rows.\nloop height [ ; A loop for each row...\n row: append/dup copy [] 0 width ; Create a block like [0 0 0 0] if width is 4.\n append/only matrix row ; Append the row to our matrix as its own block.\n]\n\na: 3\nb: 2\nmatrix/2/4: 27 ; use path syntax to access or assign\nmatrix/1/1: 99 ; series are 1-indexed in Red; there is no matrix/0/0\nmatrix/(a)/(a): 10 ; accessing elements with words requires special care\nmatrix/:b/:b: 33 ; alternative\nprint mold matrix\n", "language": "Red" }, { "code": "/*REXX program allocates/populates/displays a two-dimensional array. */\ncall bloat /*the BLOAT procedure does all allocations.*/\n /*no more array named @ at this point. */\nexit /*stick a fork in it, we're all done honey.*/\n/*─────────────────────────BLOAT subroutine─────────────────────────────*/\nbloat: procedure; say /*\"PROCEDURE\" makes this a ··· procedure. */\nsay 'Enter two positive integers (a 2-dimensional array will be created).'\npull n m . /*elements are allocated as they're defined*/\n /*N and M should be verified at this point.*/\n@.=' · ' /*Initial value for all @ array elements,*/\n /*this ensures every element has a value.*/\n do j =1 for n /*traipse through the first dimension [N]*/\n do k=1 for m /* \" \" \" second \" [M]*/\n if random()//7==0 then @.j.k=j'~'k /*populate every 7th random*/\n end /*k*/\n end /*j*/\n /* [↓] display array to console: row,col */\n do r=1 for n; _= /*construct one row (or line) at a time. */\n do c=1 for m /*construct row one column at a time. */\n _=_ right(@.r.c,4) /*append a nice-aligned column to the line.*/\n end /*kk*/ /* [↑] an nicely aligned line is built. */\n say _ /*display one row at a time to the terminal*/\n end /*jj*/\n/*╔════════════════════════════════════════════════════════════════════╗\n ║ When the RETURN is executed (from a PROCEDURE in this case), and ║\n ║ array @ is \"de─allocated\", that is, it's no longer defined, and ║\n ║ the array's storage is now free for other REXX variables. If the ║\n ║ BLOAT subroutine didn't have a \"PROCEDURE\" on that statement,║\n ║ the array @ would've been left intact. The same effect is ║\n ║ performed by a DROP statement (an example is shown below). ║\n ╚════════════════════════════════════════════════════════════════════╝*/\ndrop @. /*because of the PROCEDURE statement, the*/\nreturn /* [↑] DROP statement is superfluous. */\n", "language": "REXX" }, { "code": "See 'Enter width : ' give width\nSee 'Enter height : ' give height\nwidth=0+width height=0+height\naList = list(height) for x in aList x = list(width) next\naList[1][2] = 10 See aList[1][2] + nl\n", "language": "Ring" }, { "code": "puts 'Enter width and height: '\nw=gets.to_i\narr = Array.new(gets.to_i){Array.new(w)}\narr[1][3] = 5\np arr[1][3]\n", "language": "Ruby" }, { "code": "print \"Enter array 1 greater than 0\"; : input a1\nprint \"Enter array 2 greater than 0\"; : input a2\n\ndim chrArray$(max(a1,1),max(a2,1))\ndim numArray(max(a1,1),max(a2,1))\n\nchrArray$(1,1) = \"Hello\"\nnumArray(1,1) = 987.2\nprint chrArray$(1,1);\" \";numArray(1,1)\n", "language": "Run-BASIC" }, { "code": "use std::env;\n\nfn main() {\n let mut args = env::args().skip(1).flat_map(|num| num.parse());\n let rows = args.next().expect(\"Expected number of rows as first argument\");\n let cols = args.next().expect(\"Expected number of columns as second argument\");\n\n assert_ne!(rows, 0, \"rows were zero\");\n assert_ne!(cols, 0, \"cols were zero\");\n\n // Creates a vector of vectors with all elements initialized to 0.\n let mut v = vec![vec![0; cols]; rows];\n v[0][0] = 1;\n println!(\"{}\", v[0][0]);\n}\n", "language": "Rust" }, { "code": "var a, b = integer\n\nprint \"Two-Dimensional Array Example\"\ninput \"Size of first dimension\"; a\ninput \"Size of second dimension\"; b\n\ndim integer test_array(a, b)\n\ntest_array(1,1) = 99 rem S-BASIC arrays are indexed from 1\n\nprint \"Value stored at 1,1 =\"; test_array(1,1)\n\nend\n", "language": "S-BASIC" }, { "code": "object Array2D{\n def main(args: Array[String]): Unit = {\n val x = Console.readInt\n val y = Console.readInt\n\n val a=Array.fill(x, y)(0)\n a(0)(0)=42\n println(\"The number at (0, 0) is \"+a(0)(0))\n }\n}\n", "language": "Scala" }, { "code": "(import (scheme base)\n (scheme read)\n (scheme write))\n\n;; Read x/y from user\n(define x (begin (display \"X: \") (flush-output-port) (read)))\n(define y (begin (display \"Y: \") (flush-output-port) (read)))\n\n;; Create a vector, and fill it with a vector for each row\n(define arr (make-vector x))\n(do ((i 0 (+ 1 i)))\n ((= i x) )\n (vector-set! arr i (make-vector y 0)))\n\n;; set element (x/2, y/2) to 3\n(vector-set! (vector-ref arr (floor (/ x 2)))\n (floor (/ y 2))\n 3)\n\n(display arr) (newline)\n(display \"Retrieved: \")\n(display (vector-ref (vector-ref arr (floor (/ x 2)))\n (floor (/ y 2))))\n(newline)\n", "language": "Scheme" }, { "code": "(import (except (scheme base) equal?)\n (scheme read)\n (scheme write)\n (srfi 63) ; an array SRFI\n )\n\n;; Read x/y from user\n(define x (begin (display \"X: \") (flush-output-port) (read)))\n(define y (begin (display \"Y: \") (flush-output-port) (read)))\n\n;; Create an array\n(define array (make-array #(0) x y))\n\n;; Write to middle element of the array\n(array-set! array 3 (floor (/ x 2)) (floor (/ y 2)))\n\n;; Retrieve and display result\n(display (array-ref array (floor (/ x 2)) (floor (/ y 2)))) (newline)\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst proc: main is func\n local\n var integer: numRows is 0;\n var integer: numCols is 0;\n var array array integer: anArray is 0 times 0 times 0;\n begin\n write(\"Give me the numer of rows: \");\n readln(numRows);\n write(\"Give me the numer of columns: \");\n readln(numCols);\n anArray := numRows times numCols times 0;\n anArray[1][1] := 3;\n writeln(\"The number at place [1, 1] is \" <& anArray[1][1]);\n end func;\n", "language": "Seed7" }, { "code": "func make_matrix(x, y) {\n y.of { x.of(0) };\n}\n\nvar y = Sys.scanln(\"rows: \").to_i;\nvar x = Sys.scanln(\"cols: \").to_i;\n\nvar matrix = make_matrix(x, y); # create the matrix\nmatrix[y/2][x/2] = 1; # write something inside it\nsay matrix; # display the matrix\n", "language": "Sidef" }, { "code": "BEGIN\n INTEGER N,M;\n M := ININT;\n N := ININT;\n BEGIN\n INTEGER ARRAY A(1:M,1:N);\n A(M,N) := 99;\n OUTINT(A(M,N),0);\n OUTIMAGE;\n END;\n ! ARRAY A OUT OF SCOPE ;\nEND.\n", "language": "Simula" }, { "code": " 10 PRINT \"1ST DIMENSION: \";\n 20 INPUT D1\n 30 PRINT D1\n 40 PRINT \"2ND DIMENSION: \";\n 50 INPUT D2\n 60 PRINT D2\n 70 DIM A(D1,D1)\n 80 PRINT \"ARRAY CREATED\"\n 90 LET X=1+INT (D1*RND)\n100 LET Y=1+INT (D2*RND)\n110 LET A(X,Y)=37\n120 PRINT \"ITEM \";X;\", \";Y;\" = \";A(X,Y)\n130 CLEAR\n140 PRINT \"ARRAY DESTROYED\"\n", "language": "Sinclair-ZX81-BASIC" }, { "code": "(define width (string->number (read-line)))\n(define height (string->number (read-line)))\n(if (and width height)\n (list-seed height (list-seed width #t))\n (! \"A non-number value was submitted\"))\n", "language": "Slope" }, { "code": "m := (FillInTheBlankMorph request: 'Number of rows?') asNumber.\nn := (FillInTheBlankMorph request: 'Number of columns?') asNumber.\naMatrix := Matrix rows: m columns: n.\naMatrix\n\tat: (aMatrix rowCount // 2)\n\tat: (aMatrix columnCount // 2)\n\tput: 3.4.\ne := aMatrix\n\tat: (aMatrix rowCount // 2)\n\tat: (aMatrix columnCount // 2).\nTranscript show: 'Entry is', e printString.\n", "language": "Smalltalk" }, { "code": "|num1 num2 arr|\nnum1 := stdin nextLine asInteger.\nnum2 := stdin nextLine asInteger.\n\narr := MultidimensionalArray new: { num1. num2 }.\n\n1 to: num1 do: [ :i |\n 1 to: num2 do: [ :j |\n arr at: { i. j } put: (i*j)\n ]\n].\n\n1 to: num1 do: [ :i |\n 1 to: num2 do: [ :j |\n (arr at: {i. j}) displayNl\n ]\n].\n", "language": "Smalltalk" }, { "code": "Object subclass: BidimensionalArray [\n |biArr|\n <comment: 'bidim array'>\n].\nBidimensionalArray class extend [\n new: biDim [ |r|\n r := super new.\n r init: biDim.\n ^ r\n ]\n].\nBidimensionalArray extend [\n init: biDim [\n biArr := Array new: (biDim at: 1).\n 1 to: (biDim at: 1) do: [ :i |\n biArr at: i put: (Array new: (biDim at: 2))\n ].\n ^ self\n ]\n at: biDim [\n ^ (biArr at: (biDim at: 1)) at: (biDim at: 2)\n ]\n at: biDim put: val [\n ^ (biArr at: (biDim at: 1)) at: (biDim at: 2) put: val\n ]\n].\n", "language": "Smalltalk" }, { "code": "|num1 num2 pseudoArr|\nnum1 := stdin nextLine asInteger.\nnum2 := stdin nextLine asInteger.\n\n\"we can 'suggest' an initial value for the number\n of ''slot'' the table can hold; anyway, if we use\n more than these, the table automatically grows\"\npseudoArr := LookupTable new: (num1 * num2).\n\n1 to: num1 do: [ :i |\n 1 to: num2 do: [ :j |\n pseudoArr at: {i. j} put: (i * j).\n ]\n].\n\n1 to: num1 do: [ :i |\n 1 to: num2 do: [ :j |\n (pseudoArr at: {i. j}) displayNl.\n ]\n].\n", "language": "Smalltalk" }, { "code": "* # Get user X,Y dimensions\n output = 'Enter X,Y:'; xy = trim(input)\n xy break(',') . x ',' rem . y\n\n* # Define and create array, 1-based\n arr = array(x ',' y) ;* Or arr = array(xy)\n\n* # Display array prototype\n output = 'Prototype: ' prototype(arr)\n\n* # Assign elements, angle or square brackets\n* # Same array can hold ints, strings, etc.\n arr<x,y> = 99; arr[1,1] = 'dog'\n\n* # Display elements\n output = 'arr[' xy '] = ' arr[x,y]\n output = 'arr[1,1] = ' arr[1,1]\n\n* # Release array for garbage collection\n arr =\nend\n", "language": "SNOBOL4" }, { "code": "val nbr1 = valOf (TextIO.scanStream (Int.scan StringCvt.DEC) TextIO.stdIn);\nval nbr2 = valOf (TextIO.scanStream (Int.scan StringCvt.DEC) TextIO.stdIn);\nval array = Array2.array (nbr1, nbr2, 0.0);\nArray2.update (array, 0, 0, 3.5);\nprint (Real.toString (Array2.sub (array, 0, 0)) ^ \"\\n\");\n", "language": "Standard-ML" }, { "code": "display \"Number of rows?\" _request(nr)\ndisplay \"Number of columns?\" _request(nc)\nmatrix define a=J($nr,$nc,0)\nmatrix a[1,2]=1.5\nmatrix list a\nmatrix drop a\n", "language": "Stata" }, { "code": "mata\nmata stata display \"Number of rows?\" _request(nr)\nmata stata display \"Number of columns?\" _request(nc)\nnr = strtoreal(st_global(\"nr\"))\nnc = strtoreal(st_global(\"nc\"))\na = J(nr,nc,0)\na[1,2] = 1.5\na\nmata drop a\nend\n", "language": "Stata" }, { "code": "import Foundation\n\nprint(\"Enter the dimensions of the array seperated by a space (width height): \")\n\nlet fileHandle = NSFileHandle.fileHandleWithStandardInput()\nlet dims = NSString(data: fileHandle.availableData, encoding: NSUTF8StringEncoding)?.componentsSeparatedByString(\" \")\n\nif let dims = dims where dims.count == 2{\n\tlet w = dims[0].integerValue\n\tlet h = dims[1].integerValue\n\n\tif let w = w, h = h where w > 0 && h > 0 {\n\t\tvar array = Array<[Int!]>(count: h, repeatedValue: Array<Int!>(count: w, repeatedValue: nil))\n\n\t\tarray[0][0] = 2\n\t\tprintln(array[0][0])\n\t\tprintln(array)\n\t}\n}\n", "language": "Swift" }, { "code": "puts \"Enter width:\"\nset width [gets stdin]\nputs \"Enter height:\"\nset height [gets stdin]\n# Initialize array\nfor {set i 0} {$i < $width} {incr i} {\n\tfor {set j 0} {$j < $height} {incr j} {\n\t\tset arr($i,$j) \"\"\n\t}\n}\n# Store value\nset arr(0,0) \"abc\"\n# Print value\nputs \"Element (0/0): $arr(0,0)\"\n# Cleanup array\nunset arr\n", "language": "Tcl" }, { "code": "Input \"ROWS? \",R\nInput \"COLS? \",C\n{R,C}→dim([A])\n42→[A](1,1)\nDisp [A](1,1)\nDelVar [A]\n", "language": "TI-83-BASIC" }, { "code": "[ ( x y -- address )\n cells malloc >r\n dup cells >r\n [ r> r> r> 2dup >r >r swap malloc swap i swap array.put >r ] iterate\nr> r> nip\n] is 2D-array\n\n[ ( a b address -- value )\n array.get array.get\n] is 2D-get-element\n\n[ ( value a b address -- )\n array.get array.put\n] is 2D-put-element\n", "language": "Toka" }, { "code": "5 5 2D-array >r #! Create an array and save the pointer to it\n10 2 3 r@ 2D-put-element #! Set element 2,3 to 10\n2 3 r@ 2D-get-element #! Get the element at 2,3\nr> drop #! Discard the pointer to the array\n", "language": "Toka" }, { "code": "INPUT prompt \"Enter two positive integers, separated by a comma \": i, j\nDIM array(0,0)\nMAT REDIM array(1 TO i, 1 TO j)\nLET array(i, j) = i*j\nPRINT \"a(\"; STR$(i); \",\"; STR$(j); \") =\"; array(i, j)\nMAT REDIM array(0,0)\nEND\n", "language": "True-BASIC" }, { "code": "decl int width height\nout \"width: \" console\nset width (in int console)\nout \"height: \" console\nset height (in int console)\n\ndecl int<><> twodstream\nfor (decl int i) (< i height) (inc i)\n append (new int<>) twodstream\nend for\nfor (set i 0) (< i height) (inc i)\n decl int j\n for (set j 0) (< j width) (inc j)\n append 0 twodstream<i>\n end for\nend for\n\nset twodstream<0><0> 5\nout twodstream<0><0> endl console\n", "language": "Ursa" }, { "code": "import os\n\nfn main() {\n\t// input\n\tmut row := os.input(\"enter rows: \").str()\n\tfor elem in row {if elem.is_digit() == false {println('Input Error!') exit(1)}}\n\tmut col := os.input(\"enter cols: \").str()\t\n\tfor elem in col {if elem.is_digit() == false {println('Input Error!') exit(1)}}\n\t\n\t// create 2d array of specified size\n\tmut arr2d := [][]int{len: row.int(), init: []int{len: col.int()}}\n\n\t// assign values\n\tarr2d[0][0] = 7\n\n\t// view\n\tprintln(arr2d)\n\n\t// clear\n\tarr2d.clear()\n}\n", "language": "V-(Vlang)" }, { "code": "Option Explicit\n\nSub Main_Create_Array()\nDim NbColumns As Integer, NbRows As Integer\n\n 'Get two integers from the user,\n Do\n NbColumns = Application.InputBox(\"Enter number of columns : \", \"Numeric only\", 3, Type:=1)\n NbRows = Application.InputBox(\"Enter number of rows : \", \"Numeric only\", 5, Type:=1)\n Loop While NbColumns = 0 Or NbRows = 0\n 'Create a two-dimensional array at runtime\n ReDim myArray(1 To NbRows, 1 To NbColumns)\n 'Write some element of that array,\n myArray(LBound(myArray, 1), UBound(myArray, 2)) = \"Toto\"\n 'and then output that element.\n MsgBox myArray(LBound(myArray, 1), UBound(myArray, 2))\n 'destroy the array\n Erase myArray\nEnd Sub\n", "language": "VBA" }, { "code": "\" Create a two-dimensional array with r rows and c columns.\n\" The optional third argument specifies the initial value\n\" (default is 0).\nfunction MakeArray(r, c, ...)\n if a:0\n let init = a:1\n else\n let init = 0\n endif\n\n let temp = []\n for c in range(a:c)\n call add(temp, init)\n endfor\n\n let array = []\n for r in range(a:r)\n call add(array, temp[:])\n endfor\n return array\nendfunction\n\nlet rows = input(\"Enter number of rows: \")\nlet cols = input(\"Enter number of columns: \")\necho \"\\n\"\nlet array = MakeArray(rows, cols)\nlet array[rows - 1][cols - 1] = rows * cols\necho array[rows - 1][cols - 1]\nunlet array\n", "language": "Vim-Script" }, { "code": "Module Program\n Sub Main()\n Console.WriteLine(\"Enter two space-delimited integers:\")\n Dim input = Console.ReadLine().Split()\n Dim rows = Integer.Parse(input(0))\n Dim cols = Integer.Parse(input(1))\n\n ' VB uses max-index for array creation.\n Dim arr(rows - 1, cols - 1) As Integer\n\n arr(0, 0) = 2\n Console.WriteLine(arr(0, 0))\n End Sub\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"io\" for Stdin, Stdout\n\nvar x\nvar y\nSystem.print(\"Enter the dimensions of the array:\")\nwhile (true) {\n System.write(\" First dimension : \")\n Stdout.flush()\n x = Num.fromString(Stdin.readLine())\n if (x && (x is Num) && (x.isInteger) && (x > 0) ) {\n System.write(\" Second dimension : \")\n Stdout.flush()\n y = Num.fromString(Stdin.readLine())\n if (y && (y is Num) && (y.isInteger) && (y > 0) ) break\n System.print(\"Dimension must be a positive integer.\")\n } else {\n System.print(\"Dimension must be a positive integer.\")\n }\n}\n// create the 2d array\nvar a = List.filled(x, null)\nfor (i in 0...x) a[i] = List.filled(y, 0)\n// write an element\na[x - 1][y - 1] = 42\n// print it\nSystem.print(\"\\na[%(x-1)][%(y-1)] = %(a[x-1][y-1])\")\n// make the array eligible for garbage collection\na = null\n", "language": "Wren" }, { "code": "PROGRAM\t\"Create a two-dimensional array at runtime\"\nVERSION\t\"0.0001\"\n\nDECLARE FUNCTION Entry ()\n\nFUNCTION Entry ()\n\ti$ = INLINE$(\"Enter one positive integer: \")\n\tj$ = INLINE$(\"Enter other positive integer: \")\n\ti = SSHORT(i$)\n\tj = SSHORT(j$)\n\tDIM a[i, j]\n\ta[i, j] = i * j\n\tPRINT \"a(\"; STRING(i); \", \"; STRING(j); \") =\"; a[i, j]\nEND FUNCTION\n", "language": "XBasic" }, { "code": "inc c:\\cxpl\\codes; \\(command words can be abbreviated to first 3 letters)\ndef IntSize=4; \\number of bytes in an integer (2 or 4 depending on version)\nint X, Y, A, I;\n[X:= IntIn(0); Y:= IntIn(0); \\get 2 dimensions from user\nA:= Reserve(X*IntSize);\nfor I:= 0 to X-1 do A(I):= Reserve(Y*IntSize);\nA(X/2, Y/2):= X+Y;\nIntOut(0, A(X/2, Y/2)); CrLf(0);\n]\n", "language": "XPL0" }, { "code": "input \"Enter one positive integer: \" i\ninput \"Enter other positive integer: \" j\ndim a(i, j)\na(i, j) = i * j\nprint \"a(\", str$(i), \",\", str$(j), \") = \", a(i, j)\nexit\n", "language": "Yabasic" }, { "code": "rows:=ask(\"Rows: \").toInt();\ncols:=ask(\"columns: \").toInt();\narray:=rows.pump(List.createLong(rows),List.createLong(cols,0).copy);\narray[1][2]=123;\narray.println();\narray[1][2].println();\n", "language": "Zkl" }, { "code": "var [const] GSL=Import(\"zklGSL\");\t// libGSL (GNU Scientific Library)\nrows:=ask(\"Rows: \").toInt();\ncols:=ask(\"columns: \").toInt();\nm:=GSL.Matrix(rows,cols);\nm[1,2]=123;\nm.format().println();\nprintln(m[1,2]);\n", "language": "Zkl" }, { "code": "module Main;\ntype\n\tMatrix = array *,* of integer;\n\nvar\n\tm: Matrix;\n\ti,j: integer;\nbegin\n\twrite(\"first dim? \");readln(i);\n\twrite(\"second dim? \");readln(j);\n\tm := new Matrix(i,j);\n\tm[0,0] := 10;\n\twriteln(\"m[0,0]:> \",m[0,0]);\n\twriteln(\"m[0,1].> \",m[0,1])\nend Main.\n", "language": "Zonnon" } ]
Create-a-two-dimensional-array-at-runtime
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Create_an_object_at_a_given_address\nnote: Basic Data Operations\n", "language": "00-META" }, { "code": "{{basic data operation}}\n\nIn systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.\n\n\n;Task:\nShow how language objects can be allocated at a specific machine addresses.\n\nSince most [[OS]]es prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable [[Address Operations|address operations]] if necessary). \n\n\nFor example: \n::* &nbsp; create an integer object\n::* &nbsp; print the machine address of the object\n::* &nbsp; take the address of the object and create another integer object at this address\n::* &nbsp; print the value of this object to verify that it is same as one of the origin\n::* &nbsp; change the value of the origin and verify it again\n<br><br>\n\n", "language": "00-TASK" }, { "code": " sta $1900\n stx $1901\n sty $1902\n", "language": "6502-Assembly" }, { "code": " ldx #54\n.loop sta $1900,X\n dex\n bne loop\n", "language": "6502-Assembly" }, { "code": " lda #0\n sta $70\n lda #$20\n sta $71\n ldy #0\n sta ($70),Y\n", "language": "6502-Assembly" }, { "code": " lda #0\n sta $70\n lda #$20\n sta $71\n ldx #0\n sta ($70,X)\n", "language": "6502-Assembly" }, { "code": "MOVE.L #$12345678,$100000\n", "language": "68000-Assembly" }, { "code": "myVariable equ $100000\nMOVE.L #myVariable,D0\nJSR printLong ;some unimplemented printing routine.\n", "language": "68000-Assembly" }, { "code": "MOVE.L #$FFFFFFFF,myVariable\n", "language": "68000-Assembly" }, { "code": ".model small ;specify memory model to use\n.stack 1024 ;set up stack\n\n.data ;data segment\n\nUserRam BYTE 256 DUP (0) ;allocate 256 bytes of user RAM, initialized to zero.\n\ntempByte equ UserRam ;define a few labels for clarity\ntempWord equ UserRam+2\ntempLong_LoWord equ UserRam+4\ntempLong_HiWord equ UserRam+6\n\n.code ;code segment\n\nmov ax, @data\nmov ds, ax\n\nmov ax, @code\nmov es, ax ;load segment registers with the appropriate segments.\n\n; now there is no need to use \"mov ax, seg UserRam\" since we've already loaded the data segment into DS\n\n\n;store an integer value into memory\n\nmov ax, 1000h ;load the value 0x1000 into AX\nmov word ptr [ds:tempLong_LoWord],ax ;store 0x1000 into tempLong_LoWord\nmov ax, 0040h ;the 8086 is 16-bit so we have to load the pieces separately.\nmov word ptr [ds:tempLong_HiWord],ax ;store 0x0040 into tempLong_HiWord\n\n;get the address of a variable\nmov ax, tempLong_LoWord ;without \"word ptr\" and brackets, the assembler interprets a label as a constant.\n", "language": "8086-Assembly" }, { "code": "DEFINE FIRST=\"12345\"\nDEFINE SECOND=\"54321\"\nDEFINE PTR=\"CARD\"\n\nPROC Main()\n PTR base,copy=base\n\n PrintF(\"Address of base variable: %H%E\",@base)\n PrintF(\"Address of copy variable: %H%E\",@copy)\n PutE()\n\n PrintF(\"Assign %U value to base variable%E\",FIRST)\n base=FIRST\n PrintF(\"Value of base variable: %U%E\",base)\n PrintF(\"Value of copy variable: %U%E\",copy)\n PutE()\n\n PrintF(\"Assign %U value to base variable%E\",SECOND)\n base=SECOND\n PrintF(\"Value of base variable: %U%E\",base)\n PrintF(\"Value of copy variable: %U%E\",copy)\nRETURN\n", "language": "Action-" }, { "code": "type IO_Port is mod 2**8; -- One byte\nDevice_Port : type IO_Port;\nfor Device_Port'Address use 16#FFFF_F000#;\n", "language": "Ada" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\nwith System.Storage_Elements; use System.Storage_Elements;\n\nprocedure Test_Address is\n X : Integer := 123;\n Y : Integer;\n for Y'Address use X'Address;\nbegin\n Put_Line (\"At address:\" & Integer_Address'Image (To_Integer (Y'Address)));\n Put_Line (Integer'Image (Y));\n X := 456;\n Put_Line (Integer'Image (Y));\nend Test_Address;\n", "language": "Ada" }, { "code": "var portaddr = 0x80\nvar v = peek (portaddr, 1) // 1 byte\nv |= 0x40\npoke (portaddr, v, 1) // 1 byte back again\n\nvar addr = malloc (16)\npoke (addr, 1234, 4)\npoke (addr+4, 0, 2)\npoke (addr+6, 12, 2)\n", "language": "Aikido" }, { "code": " 0 DEF FN P(A) = PEEK (A) + PEEK (A + 1) * 256\n 100 :\n 110 REM CREATE AN INTEGER OBJECT\n 120 :\n 130 I$ = CHR$ (42)\n 140 POKE 236, PEEK (131)\n 150 POKE 237, PEEK (132)\n 160 PRINT \"HERE IS AN INTEGER : \" ASC (I$)\n 200 :\n 210 REM PRINT THE MACHINE ADDRESS OF THE OBJECT\n 220 :\n 230 PRINT \"ITS ADDRESS IS : \" FN P( FN P(236) + 1)\n 300 :\n 310 REM TAKE THE ADDRESS OF THE OBJECT AND CREATE ANOTHER INTEGER OBJECT AT THIS ADDRESS\n 320 :\n 330 O$ = CHR$ (0)\n 340 POKE 250, PEEK (131)\n 350 POKE 251, PEEK (132)\n 360 POKE FN P(250) + 1, PEEK ( FN P(236) + 1)\n 370 POKE FN P(250) + 2, PEEK ( FN P(236) + 2)\n 400 :\n 410 REM PRINT THE VALUE OF THIS OBJECT TO VERIFY THAT IT IS SAME AS ONE OF THE ORIGIN\n 420 :\n 430 PRINT \"COMPARE OTHER INTEGER : \" ASC (O$)\n 500 :\n 510 REM CHANGE THE VALUE OF THE ORIGIN AND VERIFY IT AGAIN\n 520 :\n 530 POKE FN P( FN P(236) + 1),69\n 540 PRINT \"NEW INTEGER VALUE : \" ASC (I$)\n 550 PRINT \"COMPARE OTHER INTEGER : \" ASC (O$)\n", "language": "Applesoft-BASIC" }, { "code": "mov r0,#0x00100000\nldr r1,testData\nstr r1,[r0] ;store 0x12345678 at address $100000\nbx lr ;return from subroutine\n\ntestData:\n .long 0x12345678 ;VASM uses .long for 32 bit and .word for 16 bit values, unlike most ARM assemblers.\n", "language": "ARM-Assembly" }, { "code": ".equ myVariable,0x00100000\nmov r0,#myVariable\nbl printLong ;unimplemented printing routine\n", "language": "ARM-Assembly" }, { "code": "mov r0,#0x00100000\nmov r1,#0\nmvn r1,r1 ;flip the bits of r1\nstr r1,[r0] ;store 0xFFFFFFFF at address $100000\nbx lr ;return from subroutine\n", "language": "ARM-Assembly" }, { "code": "; Create a variable with 4 bytes size and show it's machine address.\nVarSetCapacity(var, 4, 0)\npAddress := &var\nMsgBox Machine address: %pAddress%\n\n; pAddress contains the memory address.\n; Write a number and read it back.\nNumPut(123456, pAddress+0, 0, \"UInt\")\nMsgBox % \"Contents of *pAddress: \" . NumGet(pAddress+0, 0, \"UInt\")\n", "language": "AutoHotkey" }, { "code": " REM Create an integer object:\n anInteger% = 12345678\n PRINT \"Original value =\", anInteger%\n\n REM Print the machine address of the object:\n address% = ^anInteger%\n PRINT \"Hexadecimal address = \";~address%\n\n REM Take the address of the object and create\n REM another integer object at this address:\n !address% = 87654321\n\n REM Print the value of this object to verify\n REM that it is same as one of the origin:\n PRINT \"New value =\", anInteger%\n\n REM Change the value and verify it again:\n anInteger% = 55555555\n PRINT \"Final value =\", !address%\n", "language": "BBC-BASIC" }, { "code": "#include <stdio.h>\n\nint main()\n{\n int intspace;\n int *address;\n\n address = &intspace; // address = 0x100;\n *address = 65535;\n printf(\"%p: %08x (=%08x)\\n\", address, *address, intspace);\n // likely we must be worried about endianness, e.g.\n *((char*)address) = 0x00;\n *((char*)address+1) = 0x00;\n *((char*)address+2) = 0xff;\n *((char*)address+3) = 0xff; // if sizeof(int) == 4!\n // which maybe is not the best way of writing 32 bit values...\n printf(\"%p: %08x (=%08x)\\n\", address, *address, intspace);\n return 0;\n}\n", "language": "C" }, { "code": "#include <stdint.h>\n#include <stddef.h>\n\n// This is a port variable located at address 0x100\n#define PORT_A (*(volatile uint32_t*)0x100)\n\nint main()\n{\n uint32_t dat;\n size_t addr;\n\n PORT_A ^= 0x01; // Toggle bit 0 of PORT_A\n dat = PORT_A; // Read PORT_A\n addr = &PORT_A; // addr = 0x100\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <string>\n#include <iostream>\n\nint main()\n{\n // Allocate enough memory to hold an instance of std::string\n char* data = new char[sizeof(std::string)];\n\n // use placement new to construct a std::string in the memory we allocated previously\n std::string* stringPtr = new (data) std::string(\"ABCD\");\n\n std::cout << *stringPtr << \" 0x\" << stringPtr << std::endl;\n\n // use placement new to construct a new string object in the same memory location\n // remember to manually call destructor\n stringPtr->~basic_string();\n stringPtr = new (data) std::string(\"123456\");\n\n std::cout << *stringPtr << \" 0x\" << stringPtr << std::endl;\n\n // clean up\n stringPtr->~basic_string();\n delete[] data;\n}\n", "language": "C++" }, { "code": "IDENTIFICATION DIVISION.\nPROGRAM-ID. object-address-test.\nDATA DIVISION.\nLOCAL-STORAGE SECTION.\n77 int-space PICTURE IS 9(5) VALUE IS 12345.\n77 addr PICTURE IS 9(5) BASED VALUE IS ZERO.\n77 point USAGE IS POINTER.\nPROCEDURE DIVISION.\n DISPLAY \"Value of integer object : \" int-space\n SET point TO ADDRESS OF int-space\n DISPLAY \"Machine address of object : \" point\n SET ADDRESS OF addr TO point\n DISPLAY \"Value of referent object : \" addr\n MOVE 65535 TO int-space\n DISPLAY \"New value of original : \" addr\n DISPLAY \"New value of reference : \" int-space\n GOBACK.\nEND PROGRAM object-address-test.\n", "language": "COBOL" }, { "code": "10 POKE 50000,(3) REM EQUIVALENT OF LDA #$03 STA 50000\n20 PEEK(50000) REM READ THE VALUE AT MEMORY ADDRESS 50000\n", "language": "Commodore-BASIC" }, { "code": "import std.stdio ;\n\nvoid main() {\n int[] arr ;\n foreach(i; [0,1,2,3])\n arr ~= i*(1 << 24) + 0x417e7e7e ;\n\n struct X {\n char[16] msg ;\n }\n\n X* xPtr ;\n int* iPtr ;\n float* fPtr ;\n\n int adrSpace = cast(int) arr.ptr ;\n // get address of an existing object arr\n\n xPtr = cast(X*) adrSpace ;\n // xPtr now point to arr, as a struct X\n writefln(\"arr(as X)'s msg = '%s' (len %d) @ 0x%08x\",\n xPtr.msg, xPtr.msg.length, xPtr) ;\n\n iPtr = cast(int*) (adrSpace + 1 * 4 /*bytes*/) ;\n fPtr = cast(float*) iPtr ;\n // pointers now point to arr[1]\n writefln(\"arr[1] = 0x%8x (%9.4f) @ 0x%08X\", *iPtr, *fPtr, iPtr) ;\n iPtr = cast(int*) (adrSpace + 3 * 4 /*bytes*/) ;\n fPtr = cast(float*) iPtr ;\n // pointers now point to arr[3]\n writefln(\"arr[3] = 0x%8x (%9.4f) @ 0x%08X\", *iPtr, *fPtr, iPtr) ;\n *fPtr = 0.5f ; // change value\n writefln(\"arr[3] = 0x%8x (%9.4f) @ 0x%08X\", *iPtr, *fPtr, iPtr) ;\n}\n", "language": "D" }, { "code": "program Create_an_object_at_a_given_address;\n\n{$APPTYPE CONSOLE}\n\nvar\n origem: Integer;\n copy: Integer absolute origem; // This is old the trick\n\nbegin\n writeln('The \"origem\" adress is: ', cardinal(@origem));\n writeln('The \"copy\" adress is: ', cardinal(@copy));\n writeln;\n\n origem := 10;\n writeln('Assign 10 to \"origem\" ');\n writeln('The value of \"origem\" é ', origem);\n writeln('The value of \"copy\" é ', copy);\n writeln;\n\n copy := 2;\n writeln('Assign 2 to \"copy\" ');\n\n writeln('The value of \"origem\" é ', origem);\n writeln('The value of \"copy\" é ', copy);\n\n Readln;\n\nend.\n", "language": "Delphi" }, { "code": "$3f8 constant LPT1:\n\nLPT1: c@ .\n$3f LPT1: c!\n", "language": "Forth" }, { "code": "' FB 1.05.0\n\nType Person\n As String name\n As Integer age\n Declare Constructor(name As String, age As Integer)\nEnd Type\n\nConstructor Person(name As String, age As Integer)\n This.name = name\n This.age = age\nEnd Constructor\n\nDim ap As Any Ptr = CAllocate(SizeOf(Person)) ' allocate memory to store a Person object\n\n'create a Person object at the address of the memory we've just allocated\n\nDim p As Person Ptr = New(ap) Person(\"Teresa\", 60)\n\n'check addresses are same\nPrint ap, p\n\n'check data is not corrupt\nPrint p -> name, p -> age\n\n'call implicit destructor\np -> Destructor\n\n'free memory\nDeallocate(ap)\n\nPrint\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "include \"NSLog.incl\"\n\n\nlocal fn DoIt\n NSLog( @\"Dimension in integer \\\"x\\\", but do not assign it a value.\\n\" )\n long x\n // Note that the @ (at sign) prefixing x is a pointer to its machine address\n NSLog( @\"The machine address of x is: %p\", @x )\n NSLog( @\"While x is unassigned, the machine address will contain a garbage value: %ld\\n\", x )\n\n // Assign x a value of 1234\n x = 1234\n NSLog( @\"When x is assigned a value of %ld, that value will be stored in the machine address: %p\", x, @x )\n NSLog( @\"The machine address now contains the value: %ld\\n\", x )\n\n // Reassign x a value of 5678\n x = 5678\n NSLog( @\"Wnen x is reassigned the new value %ld, that value will be stored in the existing machine address: %p\", x, @x )\n NSLog( @\"The machine address now contains the value: %ld\\n\", x )\nend fn\n\nfn DoIt\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport(\n\t\"fmt\"\n\t\"unsafe\"\n\t\"reflect\"\n)\n\nfunc pointer() {\n\tfmt.Printf(\"Pointer:\\n\")\n\n\t// Create a *int and store the address of 'i' in it. To create a pointer to\n\t// an arbitrary memory location, use something like the following:\n\t// p := (*int)(unsafe.Pointer(uintptr(0x100)))\n\t// And replace '0x100' with the desired address.\n\tvar i int\n\tp := &i\n\n\tfmt.Printf(\"Before:\\n\\t%v: %v, %v\\n\", p, *p, i)\n\n\t*p = 3\n\n\tfmt.Printf(\"After:\\n\\t%v: %v, %v\\n\", p, *p, i)\n}\n\nfunc slice() {\n\tfmt.Printf(\"Slice:\\n\")\n\n\tvar a [10]byte\n\n\t// reflect.SliceHeader is a runtime representation of the internal workings\n\t// of a slice. To make it point to a specific address, use something like\n\t// the following:\n\t// h.Data = uintptr(0x100)\n\t// And replace '0x100' with the desired address.\n\tvar h reflect.SliceHeader\n\th.Data = uintptr(unsafe.Pointer(&a)) // The address of the first element of the underlying array.\n\th.Len = len(a)\n\th.Cap = len(a)\n\n\t// Create an actual slice from the SliceHeader.\n\ts := *(*[]byte)(unsafe.Pointer(&h))\n\n\tfmt.Printf(\"Before:\\n\\ts: %v\\n\\ta: %v\\n\", s, a)\n\n\t// Copy a string into the slice. This fills the underlying array, which in\n\t// this case has been manually set to 'a'.\n\tcopy(s, \"A string.\")\n\n\tfmt.Printf(\"After:\\n\\ts: %v\\n\\ta: %v\\n\", s, a)\n}\n\nfunc main() {\n\tpointer()\n\tfmt.Println()\n\n\tslice()\n}\n", "language": "Go" }, { "code": "function unsafepointers()\n intspace = [42]\n address = pointer_from_objref(intspace)\n println(\"The address of intspace is $address\")\n anotherint = unsafe_pointer_to_objref(address)\n println(\"intspace is $(intspace[1]), memory at $address, reference value $(anotherint[1])\")\n intspace[1] = 123456\n println(\"Now, intspace is $(intspace[1]), memory at $address, reference value $(anotherint[1])\")\n anotherint[1] = 7890\n println(\"Now, intspace is $(intspace[1]), memory at $(pointer_from_objref(anotherint)), reference value $(anotherint[1])\")\nend\n\nunsafepointers()\n", "language": "Julia" }, { "code": "// Kotlin/Native Technology Preview\n\nimport kotlinx.cinterop.*\n\nfun main(args: Array<String>) {\n val intVar = nativeHeap.alloc<IntVar>().apply { value = 42 }\n with(intVar) { println(\"Value is $value, address is $rawPtr\") }\n intVar.value = 52 // create new value at this address\n with(intVar) { println(\"Value is $value, address is $rawPtr\") }\n nativeHeap.free(intVar)\n}\n", "language": "Kotlin" }, { "code": "local a = {10}\nlocal b = a\n\nprint (\"address a:\"..tostring(a), \"value a:\"..a[1])\nprint (\"address b:\"..tostring(b), \"value b:\"..b[1])\n\nb[1] = 42\n\nprint (\"address a:\"..tostring(a), \"value a:\"..a[1])\nprint (\"address b:\"..tostring(b), \"value b:\"..b[1])\n", "language": "Lua" }, { "code": "Module CheckIt {\n structure alfa {\n val as long\n }\n Buffer Clear Beta as alfa*2\n Print Beta(0) ' return address\n Return Beta, 0!val:=500 ' unsigned integer 32 bit\n Print Eval(Beta, 0!val)=500\n Return Beta, 0!val:=0xFFFFFFFF\n Print Eval(Beta, 0!val)=4294967295\n Buffer Code ExecMem as byte*1024\n Offset=0\n EmbLong(0xb8, 5000) ' mov eax,5100\n EmbByteLong(0x3,0x5, Beta(0)) ' add eax, [Beta(0)]\n EmbLong(0xa3, Beta(1)) ' mov [Beta(1)], eax\n EmbByte(0x31, 0xC0) ' xor eax, eax\n Ret() ' Return\n Execute Code ExecMem, 0\n Print eval(Beta, 1!val)=4999\n Sub Ret()\n Return ExecMem, Offset:=0xC3\n Offset++\n End Sub\n Sub EmbByte()\n Return ExecMem, Offset:=Number, Offset+1:=Number\n Offset+=2\n End Sub\n Sub EmbLong()\n Return ExecMem, Offset:=Number, Offset+1:=Number as Long\n Offset+=5\n End Sub\n Sub EmbByteLong()\n Return ExecMem, Offset:=Number, Offset+1:=Number, Offset+2:=Number as Long\n Offset+=6\n End Sub\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "type\n MyObject = object\n x: int\n y: float\n\nvar\n mem = alloc(sizeof(MyObject))\n objPtr = cast[ptr MyObject](mem)\necho \"object at \", cast[int](mem), \": \", objPtr[]\n\nobjPtr[] = MyObject(x: 42, y: 3.1415)\necho \"object at \", cast[int](mem), \": \", objPtr[]\n", "language": "Nim" }, { "code": "var x: int = 3\nvar p: ptr int\n\np = cast[ptr int](addr(x))\n\necho \"Before \", x\np[] = 5\necho \"After: \", x\n", "language": "Nim" }, { "code": "program test;\ntype\n t8Byte = array[0..7] of byte;\nvar\n I : integer;\n A : integer absolute I;\n K : t8Byte;\n L : Int64 absolute K;\nbegin\n I := 0;\n A := 255; writeln(I);\n I := 4711;writeln(A);\n\n For i in t8Byte do\n Begin\n K[i]:=i;\n write(i:3,' ');\n end;\n writeln(#8#32);\n writeln(L);\nend.\n", "language": "Pascal" }, { "code": "# 20210218 Perl programming solution\n\nuse strict;\nuse warnings;\n\n# create an integer object\n\nprint \"Here is an integer : \", my $target = 42, \"\\n\";\n\n# print the machine address of the object\n\nprint \"And its reference is : \", my $targetref = \\$target, \"\\n\";\n\n# take the address of the object and create another integer object at this address\n\nprint \"Now assigns a new value to it : \", $$targetref = 69, \"\\n\";\n\n# print the value of this object to verify that it is same as one of the origin\n\nprint \"Then compare with the referent : \", $target, \"\\n\";\n", "language": "Perl" }, { "code": "-->\n <span style=\"color: #7060A8;\">poke</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0x80</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">or_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">peek</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0x80</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">0x40</span><span style=\"color: #0000FF;\">))</span>\n #ilASM{ mov al,[0x80]\n or al,0x40\n mov [0x80],al}\n<!--\n", "language": "Phix" }, { "code": ": (setq IntSpace 12345) # Integer\n-> 12345\n\n: (setq Address (adr 'IntSpace)) # Encoded machine address\n-> -2969166782547\n\n: (set (adr Address) 65535) # Set this address to a new value\n-> 65535\n\n: IntSpace # Show the new value\n-> 65535\n", "language": "PicoLisp" }, { "code": "; Allocate a 1Mb memory area work within to avoid conflicts,\n; this address could be any number but it may then fail on some systems.\n*a=AllocateMemory(1024*1024)\n\n; Write a int wit value \"31415\" at address +312,\n; using pointer '*a' with a displacement.\nPokeI(*a+312, 31415)\n\n; Write a float with value Pi at address +316,\n; by creating a new pointer '*b' for this address\n*b=*a+316\nPokeF(*b, #PI)\n\n;Now test it\nFor i=0 To 1024000 Step 4\n n=PeekI(*a+i)\n If n\n Debug \"Int at +\"+Str(i)+\" = \"+Str(n)\n Debug \"Float at +\"+Str(i)+\"= \"+StrF(PeekF(*a+i))\n EndIf\nNext\n", "language": "PureBasic" }, { "code": "#lang racket\n(require ffi/unsafe)\n\n(define x #\"Foo\")\n;; Get the address of the `x' object\n(printf \"The address of `x' is: ~s\\n\" (cast x _scheme _long))\n(define address (cast x _bytes _long))\n(printf \"The address of the bytestring it holds: ~s\\n\" address)\n(define y (cast address _long _bytes))\n(printf \"Converting this back to a bytestring: ~s\\n\" y)\n(bytes-set! y 0 71)\n(printf \"Changed the converted bytestring: ~s\\n\" y)\n(printf \"The original one is now: ~s\\n\" x)\n;; But (bytes-set! x 0 71) will throw an error since `x' is immutable,\n;; showing that we've really modifed the memory directly in a way that\n;; the runtime doesn't like.\n\n;; Also, the above can fail at any moment if a GC happens, since\n;; Racket's GC moves objects. So a proper way to do this is not to\n;; start from an existing object, but allocate one outside of the GC's\n;; reach, using raw malloc():\n(define buf (malloc 4 'raw))\n(make-sized-byte-string buf 4)\n;; or start with a given address of something like a memory-mapped IO\n;; object\n", "language": "Racket" }, { "code": "use NativeCall;\nuse NativeCall::Types;\n\n# bind to basic libc memory management\nsub malloc(size_t) returns Pointer[uint8] is native {*};\nsub memset(Pointer, uint32, size_t) is native {*};\nsub free(Pointer[uint8]) is native {*};\n\nmy Pointer[uint8] $base-p = malloc(100);\nmemset($base-p, 0, 100);\n\n# define object as a C struct that contains a short and an int\nclass SampleObject is repr('CStruct') {\n has uint16 $.foo is rw;\n has uint8 $.bar is rw;\n}\n\n# for arguments sake our object is at byte offset 64 in the\n# allocated memory\n\nmy $offset-p = $base-p.clone.add(64);\nmy $object-p := nativecast(Pointer[SampleObject], $offset-p);\nnote \"creating object at address {+$object-p}\";\n\nmy $struct := $object-p.deref;\n\n$struct.foo = 41;\n$struct.bar = 99;\n\n# check we can update\n$struct.foo++; # 42\n\n# Check that we're actually updating the memory\nuse Test;\n\n# look at the bytes directly to verify we've written to memory. Don't be too exact, as\n# the positions may vary on different platforms depending on endianess and field alignment.\n\nmy $rec-size = nativesizeof(SampleObject);\nmy uint8 @bytes-written = (0 ..^ $rec-size).map(-> $i {$base-p[64 + $i]}).grep: * > 0;\n\n# first field 'foo' (amount is small enough to fit in one byte)\nis @bytes-written[0], 42, 'object first field';\n\n# second field 'bar'\nis @bytes-written[1], 99, 'object second field';\n\n# verify that changing the origin changes the object values\nmemset($base-p, 1, 100); # set every byte to 1\n\nis $struct.foo, 256 + 1, 'short updated at origin';\nis $struct.bar, 1, 'byte updated at origin';\n\n# tidy up\nfree($base-p);\ndone-testing;\n", "language": "Raku" }, { "code": "use std::{mem,ptr};\n\nfn main() {\n let mut data: i32;\n\n // Rust does not allow us to use uninitialized memory but the STL provides an `unsafe`\n // function to override this protection.\n unsafe {data = mem::uninitialized()}\n\n // Construct a raw pointer (perfectly safe)\n let address = &mut data as *mut _;\n\n unsafe {ptr::write(address, 5)}\n println!(\"{0:p}: {0}\", &data);\n\n unsafe {ptr::write(address, 6)}\n println!(\"{0:p}: {0}\", &data);\n\n}\n", "language": "Rust" }, { "code": "var first, addr = integer\nbased second = integer\n\nfirst = 12345\nlocation var addr = first\nbase second at addr\n\nprint \"Value of first variable =\"; first\nprint \"Address of first variable = \"; hex$(addr)\nprint \"Value of second variable =\"; second\n\nend\n", "language": "S-BASIC" }, { "code": "package require critcl\n\n# A command to 'make an integer object' and couple it to a Tcl variable\ncritcl::cproc linkvar {Tcl_Interp* interp char* var1} int {\n int *intPtr = (int *) ckalloc(sizeof(int));\n\n *intPtr = 0;\n Tcl_LinkVar(interp, var1, (void *) intPtr, TCL_LINK_INT);\n return (int) intPtr;\n}\n\n# A command to couple another Tcl variable to an 'integer object'; UNSAFE!\ncritcl::cproc linkagain(Tcl_Interp* interp int addr char* var2} void {\n int *intPtr = (int *) addr;\n\n Tcl_LinkVar(interp, var2, (void *) intPtr, TCL_LINK_INT);\n}\n\n# Conventionally, programs that use critcl structure in packages\n# This is used to prevent recompilation, especially on systems like Windows\npackage provide machAddrDemo 1\n", "language": "Tcl" }, { "code": "package require machAddrDemo\nset addr [linkvar foo]\nputs \"var 'foo' at $addr with value $foo\"\nlinkagain $addr bar\nputs \"var 'bar' at $addr with value $bar\"\nincr foo\nputs \"incremented 'foo' so 'bar' is $bar\"\n", "language": "Tcl" }, { "code": "/* Create_an_object_at_a_given_address.wren */\n\nimport \"./fmt\" for Fmt\n\nforeign class Integer {\n construct new(i) {}\n\n foreign value\n\n foreign value=(i)\n\n foreign address\n}\n\nvar i = Integer.new(42)\nFmt.print(\"Integer object with value of: $d allocated at address $#x.\", i.value, i.address)\ni.value = 42\nFmt.print(\"Integer object value reset to: $d but still at address $#x.\", i.value, i.address)\ni.value = 43\nFmt.print(\"Integer object value changed to: $d but still at address $#x.\", i.value, i.address)\n", "language": "Wren" }, { "code": "/* gcc Create_an_object_at_a_given_address.c -o Create_an_object_at_a_given_address -lwren -lm */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"wren.h\"\n\n/* C <=> Wren interface functions */\n\nvoid C_integerAllocate(WrenVM* vm) {\n long *pi = (long *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(long));\n long i = (long)wrenGetSlotDouble(vm, 1);\n *pi = i;\n}\n\nvoid C_value(WrenVM* vm) {\n long i = *(long *)wrenGetSlotForeign(vm, 0);\n wrenSetSlotDouble(vm, 0, (double)i);\n}\n\nvoid C_setValue(WrenVM* vm) {\n long *pi = (long *)wrenGetSlotForeign(vm, 0);\n long i = (long)wrenGetSlotDouble(vm, 1);\n *pi = i;\n}\n\nvoid C_address(WrenVM* vm) {\n long *pi = (long *)wrenGetSlotForeign(vm, 0);\n wrenSetSlotDouble(vm, 0, (double)(unsigned long long)pi);\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n WrenForeignClassMethods methods;\n methods.allocate = NULL;\n methods.finalize = NULL;\n if (strcmp(module, \"main\") == 0) {\n if (strcmp(className, \"Integer\") == 0) {\n methods.allocate = C_integerAllocate;\n }\n }\n return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n WrenVM* vm,\n const char* module,\n const char* className,\n bool isStatic,\n const char* signature) {\n if (strcmp(module, \"main\") == 0) {\n if (strcmp(className, \"Integer\") == 0) {\n if (!isStatic && strcmp(signature, \"value\") == 0) return C_value;\n if (!isStatic && strcmp(signature, \"value=(_)\") == 0) return C_setValue;\n if (!isStatic && strcmp(signature, \"address\") == 0) return C_address;\n }\n }\n return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n switch (errorType) {\n case WREN_ERROR_COMPILE:\n printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_STACK_TRACE:\n printf(\"[%s line %d] in %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_RUNTIME:\n printf(\"[Runtime Error] %s\\n\", msg);\n break;\n }\n}\n\nchar *readFile(const char *fileName) {\n FILE *f = fopen(fileName, \"r\");\n fseek(f, 0, SEEK_END);\n long fsize = ftell(f);\n rewind(f);\n char *script = malloc(fsize + 1);\n fread(script, 1, fsize, f);\n fclose(f);\n script[fsize] = 0;\n return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n WrenLoadModuleResult result = {0};\n if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n result.onComplete = loadModuleComplete;\n char fullName[strlen(name) + 6];\n strcpy(fullName, name);\n strcat(fullName, \".wren\");\n result.source = readFile(fullName);\n }\n return result;\n}\n\nint main(int argc, char **argv) {\n WrenConfiguration config;\n wrenInitConfiguration(&config);\n config.writeFn = &writeFn;\n config.errorFn = &errorFn;\n config.bindForeignClassFn = &bindForeignClass;\n config.bindForeignMethodFn = &bindForeignMethod;\n config.loadModuleFn = &loadModule;\n WrenVM* vm = wrenNewVM(&config);\n const char* module = \"main\";\n const char* fileName = \"Create_an_object_at_a_given_address.wren\";\n char *script = readFile(fileName);\n WrenInterpretResult result = wrenInterpret(vm, module, script);\n switch (result) {\n case WREN_RESULT_COMPILE_ERROR:\n printf(\"Compile Error!\\n\");\n break;\n case WREN_RESULT_RUNTIME_ERROR:\n printf(\"Runtime Error!\\n\");\n break;\n case WREN_RESULT_SUCCESS:\n break;\n }\n wrenFreeVM(vm);\n free(script);\n return 0;\n}\n", "language": "Wren" }, { "code": "LD HL,&FFFF\nLD (&C000),HL\n", "language": "Z80-Assembly" }, { "code": "LD HL,(&C000) ;load &FFFF into HL\nINC HL ;HL now equals &0000\nLD BC,(&C000) ;load &FFFF into BC.\n", "language": "Z80-Assembly" }, { "code": "LD HL,&C000 ;get the address of our variable.\nINC (hl) ;increment the low byte.\nLD HL,(&C000) ;load &FF00 into HL.\n", "language": "Z80-Assembly" } ]
Create-an-object-at-a-given-address
[ { "code": "---\nfrom: http://rosettacode.org/wiki/CSV_data_manipulation\n", "language": "00-META" }, { "code": "[[wp:Comma-separated values|CSV spreadsheet files]] are suitable for storing tabular data in a relatively portable way. \n\nThe CSV format is flexible but somewhat ill-defined. \n\nFor present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.\n\n\n;Task:\nRead a CSV file, change some values and save the changes back to a file.\n\nFor this task we will use the following CSV file:\n\n C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n\n<i>Suggestions</i>\n<ul>\n<li/> Show how to add a column, headed 'SUM', of the sums of the rows.\n<li/> If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.\n</ul>\n<br><br>\n\n", "language": "00-TASK" }, { "code": "L(=line) File(‘data.csv’).read_lines()\n I L.index == 0\n line ‘’= ‘,SUM’\n E\n line ‘’= ‘,’sum(line.split(‘,’).map(Int))\n print(line)\n", "language": "11l" }, { "code": "package CSV is\n\n type Row(<>) is tagged private;\n\n function Line(S: String; Separator: Character := ',') return Row;\n function Next(R: in out Row) return Boolean;\n -- if there is still an item in R, Next advances to it and returns True\n function Item(R: Row) return String;\n -- after calling R.Next i times, this returns the i'th item (if any)\n\nprivate\n type Row(Length: Natural) is tagged record\n Str: String(1 .. Length);\n Fst: Positive;\n Lst: Natural;\n Nxt: Positive;\n Sep: Character;\n end record;\nend CSV;\n", "language": "Ada" }, { "code": "package body CSV is\n\n function Line(S: String; Separator: Character := ',')\n return Row is\n (Length => S'Length, Str => S,\n Fst => S'First, Lst => S'Last, Nxt => S'First, Sep => Separator);\n\n function Item(R: Row) return String is\n (R.Str(R.Fst .. R.Lst));\n\n function Next(R: in out Row) return Boolean is\n Last: Natural := R.Nxt;\n begin\n R.Fst := R.Nxt;\n while Last <= R.Str'Last and then R.Str(Last) /= R.Sep loop\n -- find Separator\n Last := Last + 1;\n end loop;\n R.Lst := Last - 1;\n R.Nxt := Last + 1;\n return (R.Fst <= R.Str'Last);\n end Next;\n\nend CSV;\n", "language": "Ada" }, { "code": "with CSV, Ada.Text_IO; use Ada.Text_IO;\n\nprocedure CSV_Data_Manipulation is\n Header: String := Get_Line;\nbegin\n Put_Line(Header & \", SUM\");\n while not End_Of_File loop\n declare\n R: CSV.Row := CSV.Line(Get_Line);\n Sum: Integer := 0;\n begin\n while R.Next loop\n Sum := Sum + Integer'Value(R.Item);\n Put(R.Item & \",\");\n end loop;\n Put_Line(Integer'Image(Sum));\n end;\n end loop;\nend CSV_Data_Manipulation;\n", "language": "Ada" }, { "code": "void\nread_csv(list t, text path)\n{\n file f;\n list l;\n\n f_affix(f, path);\n while (f_news(f, l, 0, 0, \",\") ^ -1) {\n l_append(t, l);\n }\n}\n\nlist\nsum_columns(list t)\n{\n list c, l;\n integer i;\n\n l_append(c, \"SUM\");\n for (i, l in t) {\n if (i) {\n integer j, sum;\n text s;\n\n sum = 0;\n for (j, s in l) {\n sum += atoi(s);\n }\n\n l_append(c, sum);\n }\n }\n\n return c;\n}\n\nvoid\nadd_column(list t, list c)\n{\n integer i;\n list l;\n\n for (i, l in t) {\n l_append(l, c[i]);\n }\n}\n\nvoid\nwrite_csv(list t, text path)\n{\n integer i;\n file f;\n list l;\n\n f_create(f, path, 00644);\n for (i, l in t) {\n f_(f, l[0]);\n l_ocall(l, f_, 2, 1, -1, f, \",\");\n f_newline(f);\n }\n}\n\ninteger\nmain(void)\n{\n list t;\n\n read_csv(t, \"tmp/CSV_data_manipulation.csv\");\n add_column(t, sum_columns(t));\n write_csv(t, \"tmp/CSV_data_manipulated.csv\");\n\n return 0;\n}\n", "language": "Aime" }, { "code": "# count occurrances of a char in string #\nPROC char count = (CHAR c, STRING str) INT:\n BEGIN\n INT count := 0;\n FOR i TO UPB str DO\n\t IF c = str[i] THEN count +:= 1\n\t FI\n OD;\n count\n END;\n\n# split string on separator #\nPROC char split = (STRING str, CHAR sep) FLEX[]STRING :\n BEGIN\n INT strlen := UPB str, cnt := 0;\n INT len, p;\n INT start := 1;\n [char count (sep, str) + 1] STRING list;\n WHILE start <= strlen ANDF char in string (sep, p, str[start:]) DO\n\t p +:= start - 1;\n\t list[cnt +:= 1] := str[start:p-1];\n\t start := p + 1\n OD;\n IF cnt = 0 THEN list[cnt +:= 1] := str\n ELIF start <= UPB str + 1 THEN list[cnt +:= 1] := str[start:]\n FI;\n list\n END;\n\nPROC join = ([]STRING words, STRING sep) STRING:\n IF UPB words > 0 THEN\n STRING str := words [1];\n FOR i FROM 2 TO UPB words DO\n\t str +:= sep + words[i]\n OD;\n str\n ELSE\n \"\"\n FI;\n\n# read a line from file #\nPROC readline = (REF FILE f) STRING:\n BEGIN\n STRING line;\n get (f, line); new line (f);\n line\n END;\n\n# Add one item to tuple #\nOP +:= = (REF FLEX[]STRING tuple, STRING item) VOID:\n BEGIN\n [UPB tuple+1]STRING new;\n new[:UPB tuple] := tuple;\n new[UPB new] := item;\n tuple := new\n END;\n\n# convert signed number TO INT #\nOP TOINT = (STRING str) INT:\n BEGIN\n INT n := 0, sign := 1;\n FOR i TO UPB str WHILE sign /= 0 DO\n\t IF is digit (str[i]) THEN n := n * 10 + ABS str[i] - ABS \"0\"\n\t ELIF i = 1 AND str[i] = \"-\" THEN sign := -1\n\t ELIF i /= 1 OR str[i] /= \"+\" THEN sign := 0\n\t FI\n OD;\n n * sign\n END;\n\nOP STR = (INT i) STRING: whole (i,0);\n\n# The main program #\nFILE foo;\nopen (foo, \"CSV_data_manipulation.data\", stand in channel);\nFLEX[0]STRING header := char split (readline (foo), \",\");\nheader +:= \"SUM\";\nprint ((join (header, \",\"), new line));\nWHILE NOT end of file (foo) DO\n FLEX[0]STRING fields := char split (readline (foo), \",\");\n INT sum := 0;\n FOR i TO UPB fields DO\n sum +:= TOINT fields[i]\n OD;\n fields +:= STR sum;\n print ((join (fields, \",\"), new line))\nOD;\nclose (foo)\n", "language": "ALGOL-68" }, { "code": "; data.csv\n;\n; C1,C2,C3,C4,C5\n; 1,5,9,13,17\n; 2,6,10,14,18\n; 3,7,11,15,19\n; 4,8,12,16,20\n\ntable: read.csv \"data.csv\"\ndata: []\nloop table 'row [\n addable: [\"SUM\"]\n if row <> first table ->\n addable: @[to :string sum map row 'x [to :integer x]]\n\n 'data ++ @[row ++ addable]\n]\n\nloop data 'row [\n loop row 'column ->\n prints pad column 6\n print \"\"\n]\n", "language": "Arturo" }, { "code": "Loop, Read, Data.csv\n{\n i := A_Index\n Loop, Parse, A_LoopReadLine, CSV\n Output .= (i=A_Index && i!=1 ? A_LoopField**2 : A_LoopField) (A_Index=5 ? \"`n\" : \",\")\n}\nFileAppend, %Output%, NewData.csv\n", "language": "AutoHotkey" }, { "code": "#!/usr/bin/awk -f\nBEGIN { FS = OFS = \",\" }\nNR==1 {\n print $0, \"SUM\"\n next\n}\n{\n sum = 0\n for (i=1; i<=NF; i++) {\t\n sum += $i\n }\n print $0, sum\n}\n", "language": "AWK" }, { "code": "OPTION COLLAPSE TRUE\nOPTION DELIM \",\"\n\ncsv$ = LOAD$(\"data.csv\")\n\nDOTIMES AMOUNT(csv$, NL$)\n line$ = TOKEN$(csv$, _, NL$)\n\n IF _ = 1 THEN\n total$ = APPEND$(line$, 0, \"SUM\")\n ELSE\n line$ = CHANGE$(line$, _, STR$(_*10) )\n total$ = APPEND$(total$, 0, line$, NL$)\n total$ = APPEND$(total$, 0, STR$(LOOP(i, AMOUNT(line$), VAL(TOKEN$(line$, i)))) )\n FI\nDONE\n\nSAVE total$ TO \"data.csv\"\nPRINT total$\n", "language": "BaCon" }, { "code": "OPEN \"manip.csv\" FOR INPUT AS #1\nOPEN \"manip2.csv\" FOR OUTPUT AS #2\n\nLINE INPUT #1, header$\nPRINT #2, header$ + \",SUM\"\n\nWHILE NOT EOF(1)\n INPUT #1, c1, c2, c3, c4, c5\n sum = c1 + c2 + c3 + c4 + c5\n WRITE #2, c1, c2, c3, c4, c5, sum\nWEND\n\nCLOSE #1, #2\nEND\n", "language": "BASIC" }, { "code": "csvstr ← ⟨\"C1,C2,C3,C4,C5\", \"1,5,9,13,17\", \"2,6,10,14,18\", \"3,7,11,15,19\", \"4,8,12,16,20\"⟩\n\nSplit ← (⊢-˜¬×+`)∘=⟜','⊸⊔\nstrdata ← >Split¨csvstr\nintdata ← •BQN¨⌾(1⊸↓) strdata\nsums ← ⟨\"SUMS\"⟩ ∾+´˘ 1↓ intdata\ndone ← sums ∾˜˘ intdata\n", "language": "BQN" }, { "code": "#define TITLE \"CSV data manipulation\"\n#define URL \"http://rosettacode.org/wiki/CSV_data_manipulation\"\n\n#define _GNU_SOURCE\n#define bool int\n#include <stdio.h>\n#include <stdlib.h> /* malloc...*/\n#include <string.h> /* strtok...*/\n#include <ctype.h>\n#include <errno.h>\n\n\n/**\n * How to read a CSV file ?\n */\n\n\ntypedef struct {\n\tchar * delim;\n\tunsigned int rows;\n\tunsigned int cols;\n\tchar ** table;\n} CSV;\n\n\n/**\n * Utility function to trim whitespaces from left & right of a string\n */\nint trim(char ** str) {\n\tint trimmed;\n\tint n;\n\tint len;\n\t\n\tlen = strlen(*str);\n\tn = len - 1;\n\t/* from right */\n\twhile((n>=0) && isspace((*str)[n])) {\n\t\t(*str)[n] = '\\0';\n\t\ttrimmed += 1;\n\t\tn--;\n\t}\n\n\t/* from left */\n\tn = 0;\n\twhile((n < len) && (isspace((*str)[0]))) {\n\t\t(*str)[0] = '\\0';\n\t\t*str = (*str)+1;\n\t\ttrimmed += 1;\n\t\tn++;\n\t}\n\treturn trimmed;\n}\n\n\n/**\n * De-allocate csv structure\n */\nint csv_destroy(CSV * csv) {\n\tif (csv == NULL) { return 0; }\n\tif (csv->table != NULL) { free(csv->table); }\n\tif (csv->delim != NULL) { free(csv->delim); }\n\tfree(csv);\n\treturn 0;\n}\n\n\n/**\n * Allocate memory for a CSV structure\n */\nCSV * csv_create(unsigned int cols, unsigned int rows) {\n\tCSV * csv;\n\t\n\tcsv = malloc(sizeof(CSV));\n\tcsv->rows = rows;\n\tcsv->cols = cols;\n\tcsv->delim = strdup(\",\");\n\n\tcsv->table = malloc(sizeof(char *) * cols * rows);\n\tif (csv->table == NULL) { goto error; }\n\n\tmemset(csv->table, 0, sizeof(char *) * cols * rows);\n\n\treturn csv;\n\nerror:\n\tcsv_destroy(csv);\n\treturn NULL;\n}\n\n\n/**\n * Get value in CSV table at COL, ROW\n */\nchar * csv_get(CSV * csv, unsigned int col, unsigned int row) {\n\tunsigned int idx;\n\tidx = col + (row * csv->cols);\n\treturn csv->table[idx];\n}\n\n\n/**\n * Set value in CSV table at COL, ROW\n */\nint csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {\n\tunsigned int idx;\n\tidx = col + (row * csv->cols);\n\tcsv->table[idx] = value;\n\treturn 0;\n}\n\nvoid csv_display(CSV * csv) {\n\tint row, col;\n\tchar * content;\n\tif ((csv->rows == 0) || (csv->cols==0)) {\n\t\tprintf(\"[Empty table]\\n\");\n\t\treturn ;\n\t}\n\n\tprintf(\"\\n[Table cols=%d rows=%d]\\n\", csv->cols, csv->rows);\n\tfor (row=0; row<csv->rows; row++) {\n\t\tprintf(\"[|\");\n\t\tfor (col=0; col<csv->cols; col++) {\n\t\t\tcontent = csv_get(csv, col, row);\n printf(\"%s\\t|\", content);\n\t\t}\n printf(\"]\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\n/**\n * Resize CSV table\n */\nint csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {\n\tunsigned int cur_col,\n\t\t\t\t cur_row,\n\t\t\t\t max_cols,\n\t\t\t\t max_rows;\n\tCSV * new_csv;\n\tchar * content;\n\tbool in_old, in_new;\n\n\t/* Build a new (fake) csv */\n\tnew_csv = csv_create(new_cols, new_rows);\n\tif (new_csv == NULL) { goto error; }\n\n\tnew_csv->rows = new_rows;\n\tnew_csv->cols = new_cols;\n\n\n\tmax_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;\n\tmax_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;\n\n\tfor (cur_col=0; cur_col<max_cols; cur_col++) {\n\t\tfor (cur_row=0; cur_row<max_rows; cur_row++) {\n\t\t\tin_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);\n\t\t\tin_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);\n\n\t\t\tif (in_old && in_new) {\n\t\t\t\t/* re-link data */\n\t\t\t\tcontent = csv_get(old_csv, cur_col, cur_row);\n\t\t\t\tcsv_set(new_csv, cur_col, cur_row, content);\n\t\t\t} else if (in_old) {\n\t\t\t\t/* destroy data */\n\t\t\t\tcontent = csv_get(old_csv, cur_col, cur_row);\n\t\t\t\tfree(content);\n\t\t\t} else { /* skip */ }\n\t\t}\n\t}\n\t/* on rows */\t\t\n\tfree(old_csv->table);\n\told_csv->rows = new_rows;\n\told_csv->cols = new_cols;\n\told_csv->table = new_csv->table;\n\tnew_csv->table = NULL;\n\tcsv_destroy(new_csv);\n\n\treturn 0;\n\nerror:\n\tprintf(\"Unable to resize CSV table: error %d - %s\\n\", errno, strerror(errno));\n\treturn -1;\n}\n\n\n/**\n * Open CSV file and load its content into provided CSV structure\n **/\nint csv_open(CSV * csv, char * filename) {\n\tFILE * fp;\n\tunsigned int m_rows;\n\tunsigned int m_cols, cols;\n\tchar line[2048];\n\tchar * lineptr;\n\tchar * token;\n\n\n\tfp = fopen(filename, \"r\");\n\tif (fp == NULL) { goto error; }\n\n\tm_rows = 0;\n\tm_cols = 0;\n\twhile(fgets(line, sizeof(line), fp) != NULL) {\n \t\tm_rows += 1;\n \t\tcols = 0;\n \t\tlineptr = line;\n \t\twhile ((token = strtok(lineptr, csv->delim)) != NULL) {\n \t\t\tlineptr = NULL;\n \t\t\ttrim(&token);\n cols += 1;\n \tif (cols > m_cols) { m_cols = cols; }\n csv_resize(csv, m_cols, m_rows);\n csv_set(csv, cols-1, m_rows-1, strdup(token));\n }\n\t}\n\n\tfclose(fp);\n\tcsv->rows = m_rows;\n\tcsv->cols = m_cols;\n\treturn 0;\n\nerror:\n\tfclose(fp);\n\tprintf(\"Unable to open %s for reading.\", filename);\n\treturn -1;\n}\n\n\n/**\n * Open CSV file and save CSV structure content into it\n **/\nint csv_save(CSV * csv, char * filename) {\n\tFILE * fp;\n\tint row, col;\n\tchar * content;\n\n\tfp = fopen(filename, \"w\");\n\tfor (row=0; row<csv->rows; row++) {\n\t\tfor (col=0; col<csv->cols; col++) {\n\t\t\tcontent = csv_get(csv, col, row);\n fprintf(fp, \"%s%s\", content,\n \t\t((col == csv->cols-1) ? \"\" : csv->delim) );\n\t\t}\n fprintf(fp, \"\\n\");\n\t}\n\n\tfclose(fp);\n\treturn 0;\n}\n\n\n/**\n * Test\n */\nint main(int argc, char ** argv) {\n\tCSV * csv;\n\n\tprintf(\"%s\\n%s\\n\\n\",TITLE, URL);\n\n\tcsv = csv_create(0, 0);\n\tcsv_open(csv, \"fixtures/csv-data-manipulation.csv\");\n\tcsv_display(csv);\n\n\tcsv_set(csv, 0, 0, \"Column0\");\n\tcsv_set(csv, 1, 1, \"100\");\n\tcsv_set(csv, 2, 2, \"200\");\n\tcsv_set(csv, 3, 3, \"300\");\n\tcsv_set(csv, 4, 4, \"400\");\n\tcsv_display(csv);\n\n\tcsv_save(csv, \"tmp/csv-data-manipulation.result.csv\");\n\tcsv_destroy(csv);\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <gadget/gadget.h>\n\nLIB_GADGET_START\n\nvoid Muestra_archivo_original();\n\nMain\n if(Exist_file(\"load_matrix.txt\"))\n {\n /* recupero informacion del archivo para su apertura segura */\n F_STAT dataFile = Stat_file(\"load_matrix.txt\");\n if(dataFile.is_matrix) // tiene forma de matriz???\n {\n New multitype test;\n\n /* establezco los rangos a leer */\n Range for test [0:1:dataFile.total_lines-1, 0:1:dataFile.max_tokens_per_line-1];\n\n /* cargamos el array con detección de enteros como LONG */\n test = Load_matrix_mt( pSDS(test), \"load_matrix.txt\", dataFile, DET_LONG);\n\n /* modifica algunas cosas del archivo */\n /* sChg() no es necesario aquí, porque no se está cambiando el tipo\n de la celda, sino que se reemplaza el string: */\n ///sChg( test, 0,1, \"Columna 1\");\n\n /* Con Let() basta... */\n Let( $s-test[0,1], \"Columna 1\");\n $l-test[2,1] = 1000;\n $l-test[2,2] = 2000;\n\n /* inserto filas */\n /* preparo la fila a insertar */\n New multitype nueva_fila;\n sAppend_mt(nueva_fila,\"fila 3.1\");\n Append_mt(nueva_fila,float,0.0);\n Append_mt(nueva_fila,int,0);\n Append_mt(nueva_fila,double,0.0);\n Append_mt(nueva_fila,long, 0L);\n /* insertamos la misma fila en el array, 3 veces */\n test = Insert_row_mt(pSDS(test),pSDS(nueva_fila), 4);\n test = Insert_row_mt(pSDS(test),pSDS(nueva_fila), 4);\n test = Insert_row_mt(pSDS(test),pSDS(nueva_fila), 4);\n Free multitype nueva_fila;\n\n Print \"\\nGuardando archivo en \\\"save_matrix.txt\\\"...\\n\";\n DEC_PREC = 20; /* establece precision decimal para despliegue */\n\n All range for test;\n Save_matrix_mt(SDS(test), \"save_matrix.txt\" );\n\n Free multitype test;\n\n Print \"\\nArchivo original:\\n\";\n Muestra_archivo_original();\n }\n }\n\nEnd\n\nvoid Muestra_archivo_original(){\n String csys;\n csys = `cat load_matrix.txt`;\n Print \"\\n%s\\n\", csys;\n Free secure csys;\n}\n", "language": "C" }, { "code": "#include <map>\n#include <vector>\n#include <iostream>\n#include <fstream>\n#include <utility>\n#include <functional>\n#include <string>\n#include <sstream>\n#include <algorithm>\n#include <cctype>\n\nclass CSV\n{\npublic:\n CSV(void) : m_nCols( 0 ), m_nRows( 0 )\n {}\n\n bool open( const char* filename, char delim = ',' )\n {\n std::ifstream file( filename );\n\n clear();\n if ( file.is_open() )\n {\n open( file, delim );\n return true;\n }\n\n return false;\n }\n\n void open( std::istream& istream, char delim = ',' )\n {\n std::string line;\n\n clear();\n while ( std::getline( istream, line ) )\n {\n unsigned int nCol = 0;\n std::istringstream lineStream(line);\n std::string cell;\n\n while( std::getline( lineStream, cell, delim ) )\n {\n m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );\n nCol++;\n }\n m_nCols = std::max( m_nCols, nCol );\n m_nRows++;\n }\n }\n\n bool save( const char* pFile, char delim = ',' )\n {\n std::ofstream ofile( pFile );\n if ( ofile.is_open() )\n {\n save( ofile );\n return true;\n }\n return false;\n }\n\n void save( std::ostream& ostream, char delim = ',' )\n {\n for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )\n {\n for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )\n {\n ostream << trim( m_oData[std::make_pair( nCol, nRow )] );\n if ( (nCol+1) < m_nCols )\n {\n ostream << delim;\n }\n else\n {\n ostream << std::endl;\n }\n }\n }\n }\n\n void clear()\n {\n m_oData.clear();\n m_nRows = m_nCols = 0;\n }\n\n std::string& operator()( unsigned int nCol, unsigned int nRow )\n {\n m_nCols = std::max( m_nCols, nCol+1 );\n m_nRows = std::max( m_nRows, nRow+1 );\n return m_oData[std::make_pair(nCol, nRow)];\n }\n\n inline unsigned int GetRows() { return m_nRows; }\n inline unsigned int GetCols() { return m_nCols; }\n\nprivate:\n // trim string for empty spaces in begining and at the end\n inline std::string &trim(std::string &s)\n {\n\n s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));\n s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());\n return s;\n }\n\nprivate:\n std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;\n\n unsigned int m_nCols;\n unsigned int m_nRows;\n};\n\n\nint main()\n{\n CSV oCSV;\n\n oCSV.open( \"test_in.csv\" );\n oCSV( 0, 0 ) = \"Column0\";\n oCSV( 1, 1 ) = \"100\";\n oCSV( 2, 2 ) = \"200\";\n oCSV( 3, 3 ) = \"300\";\n oCSV( 4, 4 ) = \"400\";\n oCSV.save( \"test_out.csv\" );\n return 0;\n}\n", "language": "C++" }, { "code": "using System.IO;\nusing System.Linq;\n\nnamespace CSV_data_manipulation\n{\n class Program\n {\n static void Main()\n {\n var input = File.ReadAllLines(\"test_in.csv\");\n var output = input.Select((line, i) =>\n {\n if (i == 0)\n return line + \",SUM\";\n var sum = line.Split(',').Select(int.Parse).Sum();\n return line + \",\" + sum;\n }).ToArray();\n File.WriteAllLines(\"test_out.csv\", output);\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(require '[clojure.data.csv :as csv]\n '[clojure.java.io :as io])\n\n(defn add-sum-column [coll]\n (let [titles (first coll)\n values (rest coll)]\n (cons (conj titles \"SUM\")\n (map #(conj % (reduce + (map read-string %))) values))))\n\n(with-open [in-file (io/reader \"test_in.csv\")]\n (doall\n (let [out-data (add-sum-column (csv/read-csv in-file))]\n (with-open [out-file (io/writer \"test_out.csv\")]\n (csv/write-csv out-file out-data)))))\n", "language": "Clojure" }, { "code": "(require '[tech.v3.dataset :as ds]\n '[tech.v3.datatype.functional :as dfn])\n\n(defn add-sum\n [dataframe]\n (assoc dataframe\n \"SUM\"\n (apply dfn/+ (map dataframe (ds/column-names dataframe)))))\n\n(ds/write! (add-sum (ds/->dataset \"resources/input.csv\")) \"resources/output.csv\")\n", "language": "Clojure" }, { "code": " IDENTIFICATION DIVISION.\n PROGRAM-ID. CSV.\n AUTHOR. Bill Gunshannon.\n INSTALLATION. Home.\n DATE-WRITTEN. 19 December 2021.\n ************************************************************\n ** Program Abstract:\n ** CSVs are something COBOL does pretty well.\n ** The commented out CONCATENATE statements are a\n ** second method other than the STRING method.\n ************************************************************\n\n ENVIRONMENT DIVISION.\n CONFIGURATION SECTION.\n REPOSITORY.\n FUNCTION ALL INTRINSIC.\n\n INPUT-OUTPUT SECTION.\n FILE-CONTROL.\n SELECT CSV-File ASSIGN TO \"csv.txt\"\n ORGANIZATION IS LINE SEQUENTIAL.\n SELECT Out-File ASSIGN TO \"new.csv.txt\"\n ORGANIZATION IS LINE SEQUENTIAL.\n\n\n DATA DIVISION.\n\n FILE SECTION.\n\n FD CSV-File\n DATA RECORD IS CSV-Record.\n 01 CSV-Record.\n 05 Field1 PIC X(64).\n\n FD Out-File\n DATA RECORD IS Out-Line.\n 01 Out-Line PIC X(80).\n\n WORKING-STORAGE SECTION.\n\n 01 Eof PIC X VALUE 'F'.\n\n 01 CSV-Data.\n 05 CSV-Col1 PIC 9(5).\n 05 CSV-Col2 PIC 9(5).\n 05 CSV-Col3 PIC 9(5).\n 05 CSV-Col4 PIC 9(5).\n 05 CSV-Col5 PIC 9(5).\n\n 01 CSV-Sum PIC ZZZ9.\n 01 CSV-Sum-Alpha\n REDEFINES CSV-Sum PIC X(4).\n\n PROCEDURE DIVISION.\n\n Main-Program.\n OPEN INPUT CSV-File\n OPEN OUTPUT Out-File\n PERFORM Read-a-Record\n PERFORM Build-Header\n PERFORM UNTIL Eof = 'T'\n PERFORM Read-a-Record\n IF Eof NOT EQUAL 'T' PERFORM Process-a-Record\n END-PERFORM\n CLOSE CSV-File\n CLOSE Out-File\n STOP RUN.\n\n Read-a-Record.\n READ CSV-File\n AT END MOVE 'T' TO Eof\n END-READ.\n\n Build-Header.\n ** MOVE CONCATENATE(TRIM(CSV-Record), \",SUM\"\n ** TO Out-Line.\n STRING TRIM(CSV-Record), \",SUM\" INTO Out-Line.\n WRITE Out-Line.\n MOVE SPACES TO Out-Line.\n\n Process-a-Record.\n UNSTRING CSV-Record DELIMITED BY ',' INTO\n CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5.\n COMPUTE CSV-Sum =\n CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5.\n ** MOVE CONCATENATE(TRIM(CSV-Record), \",\" TRIM(CSV-Sum-Alpha))\n ** TO Out-Line.\n STRING TRIM(CSV-Record), \",\" TRIM(CSV-Sum-Alpha)\n INTO Out-Line.\n WRITE Out-Line.\n MOVE SPACES TO Out-Line.\n\n END-PROGRAM.\n", "language": "COBOL" }, { "code": "(defun csvfile-to-nested-list (filename delim-char)\n \"Reads the csv to a nested list, where each sublist represents a line.\"\n (with-open-file (input filename)\n (loop :for line := (read-line input nil) :while line\n :collect (read-from-string\n (substitute #\\SPACE delim-char\n (format nil \"(~a)~%\" line))))))\n\n(defun sublist-sum-list (nested-list)\n \"Return a list with the sum of each list of numbers in a nested list.\"\n (mapcar (lambda (l) (if (every #'numberp l)\n (reduce #'+ l) nil))\n nested-list))\n\n(defun append-each-sublist (nested-list1 nested-list2)\n \"Horizontally append the sublists in two nested lists. Used to add columns.\"\n (mapcar #'append nested-list1 nested-list2))\n\n(defun nested-list-to-csv (nested-list delim-string)\n \"Converts the nested list back into a csv-formatted string.\"\n (format nil (concatenate 'string \"~{~{~2,'0d\" delim-string \"~}~%~}\")\n nested-list))\n\n(defun main ()\n (let* ((csvfile-path #p\"projekte/common-lisp/example_comma_csv.txt\")\n (result-path #p\"results.txt\")\n (data-list (csvfile-to-nested-list csvfile-path #\\,))\n (list-of-sums (sublist-sum-list data-list))\n (result-header \"C1,C2,C3,C4,C5,SUM\"))\n\n (setf data-list ; add list of sums as additional column\n (rest ; remove old header\n (append-each-sublist data-list\n (mapcar #'list list-of-sums))))\n ;; write to output-file\n (with-open-file (output result-path :direction :output :if-exists :supersede)\n (format output \"~a~%~a\"\n result-header (nested-list-to-csv data-list \",\")))))\n(main)\n", "language": "Common-Lisp" }, { "code": "void main() {\n import std.stdio, std.csv, std.file, std.typecons, std.array,\n std.algorithm, std.conv, std.range;\n\n auto rows = \"csv_data_in.csv\".File.byLine;\n auto fout = \"csv_data_out.csv\".File(\"w\");\n fout.writeln(rows.front);\n fout.writef(\"%(%(%d,%)\\n%)\", rows.dropOne\n .map!(r => r.csvReader!int.front.map!(x => x + 1)));\n}\n", "language": "D" }, { "code": "program CSV_data_manipulation;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils,\n System.IoUtils,\n System.Types;\n\ntype\n TStringDynArrayHelper = record helper for TStringDynArray\n function Sum: Integer;\n end;\n\n{ TStringDynArrayHelper }\n\nfunction TStringDynArrayHelper.Sum: Integer;\nvar\n value: string;\nbegin\n Result := 0;\n for value in self do\n Result := Result + StrToIntDef(value, 0);\nend;\n\nconst\n FILENAME = './Data.csv';\n\nvar\n i: integer;\n Input, Row: TStringDynArray;\n\nbegin\n Input := TFile.ReadAllLines(FILENAME);\n for i := 0 to High(Input) do\n begin\n if i = 0 then\n Input[i] := Input[i] + ',SUM'\n else\n begin\n Row := Input[i].Split([',']);\n Input[i] := Input[i] + ',' + row.Sum.ToString;\n end;\n end;\n TFile.WriteAllLines(FILENAME, Input);\nend.\n", "language": "Delphi" }, { "code": "s$ = input\nprint s$ & \",SUM\"\nrepeat\n s$ = input\n until s$ = \"\"\n sum = 0\n for v in number strsplit s$ \",\"\n sum += v\n .\n print s$ & \",\" & sum\n.\ninput_data\nC1,C2,C3,C4,C5\n1,5,9,13,17\n2,6,10,14,18\n3,7,11,15,19\n4,8,12,16,20\n", "language": "EasyLang" }, { "code": ";; CSV -> LISTS\n(define (csv->row line) (map (lambda(x) (or (string->number x) x)) (string-split line \",\")))\n(define (csv->table csv) (map csv->row (string-split csv \"\\n\")))\n\n;; LISTS -> CSV\n(define (row->csv row) (string-join row \",\"))\n(define (table->csv header rows)\n (string-join (cons (row->csv header) (for/list ((row rows)) (row->csv row))) \"\\n\"))\n\n\n(define (task file)\n (let*\n \t((table (csv->table file))\n \t(header (first table))\n \t(rows (rest table)))\n \t\n \t(table->csv\n \t\t(append header \"SUM\") ;; add last column\n \t\t(for/list ((row rows)) (append row (apply + row))))))\n\n\t\n", "language": "EchoLisp" }, { "code": "(define file.csv #<<\nC1,C2,C3,C4,C5\n1,5,9,13,17\n2,6,10,14,18\n3,7,11,15,19\n4,8,12,16,20\n>>#)\n\n(task file.csv)\n\n → \"C1,C2,C3,C4,C5,SUM\n1,5,9,13,17,45\n2,6,10,14,18,50\n3,7,11,15,19,55\n4,8,12,16,20,60\"\n", "language": "EchoLisp" }, { "code": "// Assumes a CSV file exists and has been sprayed to a Thor cluster\nMyFileLayout := RECORD\nSTRING Field1;\nSTRING Field2;\nSTRING Field3;\nSTRING Field4;\nSTRING Field5;\nEND;\t\t\t\t\t\t\t\n\nMyDataset := DATASET ('~Rosetta::myCSVFile', MyFileLayout,CSV(SEPARATOR(',')));\n\nMyFileLayout Appended(MyFileLayout pInput):= TRANSFORM\n SELF.Field1 := pInput.Field1 +'x';\n SELF.Field2 := pInput.Field2 +'y';\n SELF.Field3 := pInput.Field3 +'z';\n SELF.Field4 := pInput.Field4 +'a';\n SELF.Field5 := pInput.Field5 +'b';\nEND ;\n\nMyNewDataset := PROJECT(MyDataset,Appended(LEFT));\nOUTPUT(myNewDataset,,'~Rosetta::myNewCSVFile',CSV,OVERWRITE);\n", "language": "ECL" }, { "code": "defmodule Csv do\n defstruct header: \"\", data: \"\", separator: \",\"\n\n def from_file(path) do\n [header | data] = path\n |> File.stream!\n |> Enum.to_list\n |> Enum.map(&String.trim/1)\n\n %Csv{ header: header, data: data }\n end\n\n def sums_of_rows(csv) do\n Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)\n end\n\n def sum_of_row(row, separator) do\n row\n |> String.split(separator)\n |> Enum.map(&String.to_integer/1)\n |> Enum.sum\n |> to_string\n end\n\n def append_column(csv, column_header, column_data) do\n header = append_to_row(csv.header, column_header, csv.separator)\n\n data = [csv.data, column_data]\n |> List.zip\n |> Enum.map(fn ({ row, value }) ->\n append_to_row(row, value, csv.separator)\n end)\n\n %Csv{ header: header, data: data }\n end\n\n def append_to_row(row, value, separator) do\n row <> separator <> value\n end\n\n def to_file(csv, path) do\n body = Enum.join([csv.header | csv.data], \"\\n\")\n\n File.write(path, body)\n end\nend\n\ncsv = Csv.from_file(\"in.csv\")\ncsv\n|> Csv.append_column(\"SUM\", Csv.sums_of_rows(csv))\n|> Csv.to_file(\"out.csv\")\n", "language": "Elixir" }, { "code": "-module( csv_data ).\n\n-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).\n\nchange( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).\n\nfrom_binary( Binary ) ->\n Lines = binary:split( Binary, <<\"\\n\">>, [global] ),\n [binary:split(X, <<\",\">>, [global]) || X <- Lines].\n\nfrom_file( Name ) ->\n {ok, Binary} = file:read_file( Name ),\n from_binary( Binary ).\n\ninto_file( Name, CSV ) ->\n Binaries = join_binaries( [join_binaries(X, <<\",\">>) || X <- CSV], <<\"\\n\">> ),\n file:write_file( Name, Binaries ).\n\ntask() ->\n CSV = from_file( \"CSV_file.in\" ),\n New_CSV = change( CSV, [{2,3,<<\"23\">>}, {4,4,<<\"44\">>}] ),\n into_file( \"CSV_file.out\", New_CSV ).\n\n\n\nchange_foldl( {Row_number, Column_number, New}, Acc ) ->\n {Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),\n {Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),\n Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.\n\njoin_binaries( Binaries, Binary ) ->\n [_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),\n lists:reverse( Rest ).\n\nsplit( 1, List ) -> {[], List};\nsplit( N, List ) -> lists:split( N - 1, List ).\n", "language": "Erlang" }, { "code": "--- Read CSV file and add columns headed with 'SUM'\n--- with trace\n-- trace(0)\n\ninclude get.e\ninclude std/text.e\n\nfunction split(sequence s, integer c)\n sequence removables = \" \\t\\n\\r\\x05\\u0234\\\" \"\n sequence out\n integer first, delim\n out = {}\n first = 1\n while first <= length(s) do\n delim = find_from(c,s,first)\n if delim = 0 then\n delim = length(s)+1\n end if\n out = append(out,trim(s[first..delim-1],removables))\n first = delim + 1\n end while\n return out\nend function\n\nprocedure main()\n integer fn -- the file number\n integer fn2 -- the output file number\n integer e -- the number of lines read\n object line -- the next line from the file\n sequence data = {} -- parsed csv data row\n sequence headerNames = {} -- array saving column names\n atom sum = 0.0 -- sum for each row\n sequence var -- holds numerical data read\n\n -- First we try to open the file called \"data.csv\".\n fn = open(\"data.csv\", \"r\")\n if fn = -1 then\n puts(1, \"Can't open data.csv\\n\")\n\t-- abort();\n end if\n\n -- Then we create an output file for processed data.\n fn2 = open(\"newdata.csv\", \"w\")\n if fn2 = -1 then\n puts(1, \"Can't create newdata.csv\\n\")\n end if\n\n -- By successfully opening the file we have established that\n -- the file exists, and open() gives us a file number (or \"handle\")\n -- that we can use to perform operations on the file.\n\n e = 1\n while 1 do\n line = gets(fn)\n if atom(line) then\n exit\n end if\n data = split(line, ',')\n\n if (e=1) then\n -- Save the header labels and\n\t -- write them to output file.\n headerNames = data\n\t for i=1 to length(headerNames) do\n\t printf(fn2, \"%s,\", {headerNames[i]})\n\t end for\n\t printf(fn2, \"SUM\\n\")\n end if\n\n -- Run a sum for the numerical data.\n if (e >= 2) then\n\t for i=1 to length(data) do\n\t printf(fn2, \"%s,\", {data[i]})\n\t\tvar = value(data[i])\n\t\tif var[1] = 0 then\n\t\t -- data read is numerical\n\t\t -- add to sum\n\t\t sum = sum + var[2]\n\t\tend if\n\t end for\n printf(fn2, \"%g\\n\", {sum})\n\t sum = 0.0\n end if\n e = e + 1\n end while\n\n close(fn)\n close(fn2)\nend procedure\n\nmain()\n", "language": "Euphoria" }, { "code": "open System.IO\n\n[<EntryPoint>]\nlet main _ =\n let input = File.ReadAllLines \"test_in.csv\"\n let output =\n input\n |> Array.mapi (fun i line ->\n if i = 0 then line + \",SUM\"\n else\n let sum = Array.sumBy int (line.Split(','))\n sprintf \"%s,%i\" line sum)\n File.WriteAllLines (\"test_out.csv\", output)\n 0\n", "language": "F-Sharp" }, { "code": "USING: csv io.encodings.utf8 kernel math.parser sequences ;\nIN: rosetta-code.csv-manipulation\n\n: append-sum ( seq -- seq' )\n dup [ string>number ] map-sum number>string suffix ;\n\n: csv-sums ( seq -- seq' )\n [ 0 = [ \"SUM\" suffix ] [ append-sum ] if ] map-index ;\n\n\"example.csv\" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi\n", "language": "Factor" }, { "code": "\\ csvsum.fs Add a new column named SUM that contain sums from rows of CommaSeparatedValues\n\\ USAGE:\n\\ gforth-fast csvsum.fs -e \"stdout stdin csvsum bye\" <input.csv >output.csv\n\n CHAR , CONSTANT SEPARATOR\n 3 CONSTANT DECIMALS\n 1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE\n\n: colsum ( ca u -- F: -- sum ;return SUM from CSV-string )\n 0E0 OVER SWAP BOUNDS\n ?DO ( a )\n I C@ SEPARATOR =\n IF ( a )\n I TUCK OVER - >FLOAT IF F+ THEN\n 1+\n THEN\n LOOP DROP\n;\n: f>string ( -- ca u F: x -- )\n FSCALE F*\n F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>\n;\n: rowC!+ ( offs char -- u+1 ;store CHAR at here+OFFS,increment offset )\n OVER HERE + C! 1+\n;\n: row$!+ ( offs ca u -- offs+u ;store STRING at here+OFFS,update offset )\n ROT 2DUP + >R HERE + SWAP MOVE R>\n;\n\\ If run program with '-m 4G'option, we have practically 4G to store a row\n: csvsum ( fo fi -- ;write into FILEID-OUTPUT processed input from FILEID-INPUT )\n 2DUP\n HERE UNUSED ROT READ-LINE THROW\n IF ( fo fi fo u )\n HERE SWAP ( fo fi fo ca u )\n SEPARATOR rowC!+\n s\\\" SUM\" row$!+ ( fo fi fo ca u' )\n ROT WRITE-LINE THROW\n BEGIN ( fo fi )\n 2DUP HERE UNUSED ROT READ-LINE THROW\n WHILE ( fo fi fo u )\n HERE SWAP ( fo fi fo ca u )\n SEPARATOR rowC!+\n HERE OVER colsum f>string ( fo fi fo ca u ca' u' )\n row$!+ ( fo fi fo ca u'+u )\n ROT WRITE-LINE THROW\n REPEAT\n THEN\n 2DROP 2DROP\n;\n", "language": "Forth" }, { "code": "program rowsum\n implicit none\n character(:), allocatable :: line, name, a(:)\n character(20) :: fmt\n double precision, allocatable :: v(:)\n integer :: n, nrow, ncol, i\n\n call get_command_argument(1, length=n)\n allocate(character(n) :: name)\n call get_command_argument(1, name)\n open(unit=10, file=name, action=\"read\", form=\"formatted\", access=\"stream\")\n deallocate(name)\n\n call get_command_argument(2, length=n)\n allocate(character(n) :: name)\n call get_command_argument(2, name)\n open(unit=11, file=name, action=\"write\", form=\"formatted\", access=\"stream\")\n deallocate(name)\n\n nrow = 0\n ncol = 0\n do while (readline(10, line))\n nrow = nrow + 1\n\n call split(line, a)\n\n if (nrow == 1) then\n ncol = size(a)\n write(11, \"(A)\", advance=\"no\") line\n write(11, \"(A)\") \",Sum\"\n allocate(v(ncol + 1))\n write(fmt, \"('(',G0,'(G0,:,''',A,'''))')\") ncol + 1, \",\"\n else\n if (size(a) /= ncol) then\n print \"(A,' ',G0)\", \"Invalid number of values on row\", nrow\n stop\n end if\n\n do i = 1, ncol\n read(a(i), *) v(i)\n end do\n v(ncol + 1) = sum(v(1:ncol))\n write(11, fmt) v\n end if\n end do\n close(10)\n close(11)\ncontains\n function readline(unit, line)\n use iso_fortran_env\n logical :: readline\n integer :: unit, ios, n\n character(:), allocatable :: line\n character(10) :: buffer\n\n line = \"\"\n readline = .false.\n do\n read(unit, \"(A)\", advance=\"no\", size=n, iostat=ios) buffer\n if (ios == iostat_end) return\n readline = .true.\n line = line // buffer(1:n)\n if (ios == iostat_eor) return\n end do\n end function\n\n subroutine split(line, array, separator)\n character(*) line\n character(:), allocatable :: array(:)\n character, optional :: separator\n character :: sep\n integer :: n, m, p, i, k\n\n if (present(separator)) then\n sep = separator\n else\n sep = \",\"\n end if\n\n n = len(line)\n m = 0\n p = 1\n k = 1\n do i = 1, n\n if (line(i:i) == sep) then\n p = p + 1\n m = max(m, i - k)\n k = i + 1\n end if\n end do\n m = max(m, n - k + 1)\n\n if (allocated(array)) deallocate(array)\n allocate(character(m) :: array(p))\n\n p = 1\n k = 1\n do i = 1, n\n if (line(i:i) == sep) then\n array(p) = line(k:i-1)\n p = p + 1\n k = i + 1\n end if\n end do\n array(p) = line(k:n)\n end subroutine\nend program\n", "language": "Fortran" }, { "code": "Copies a file with 5 comma-separated values to a line, appending a column holding their sum.\n INTEGER N\t\t\t!Instead of littering the source with \"5\"\n PARAMETER (N = 5)\t\t!Provide some provenance.\n CHARACTER*6 HEAD(N)\t!A perfect size?\n INTEGER X(N)\t\t!Integers suffice.\n INTEGER LINPR,IN\t\t!I/O unit numbers.\n LINPR = 6\t\t!Standard output via this unit number.\n IN = 10\t\t!Some unit number for the input file.\n OPEN (IN,FILE=\"CSVtest.csv\",STATUS=\"OLD\",ACTION=\"READ\")\t!For formatted input.\n\n READ (IN,*) HEAD\t!The first line has texts as column headings.\n WRITE (LINPR,1) (TRIM(HEAD(I)), I = 1,N),\"Sum\"\t!Append a \"Sum\" column.\n 1 FORMAT (666(A:\",\"))\t!The : sez \"stop if no list element awaits\".\n 2 READ (IN,*,END = 10) X\t!Read a line's worth of numbers, separated by commas or spaces.\n WRITE (LINPR,3) X,SUM(X)\t!Write, with a total appended.\n 3 FORMAT (666(I0:\",\"))\t!I0 editing uses only as many columns as are needed.\n GO TO 2\t\t\t!Do it again.\n\n 10 CLOSE (IN)\t!All done.\n END\t!That's all.\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nOpen \"manip.csv\" For Input As #1 ' existing CSV file\nOpen \"manip2.csv\" For Output As #2 ' new CSV file for writing changed data\n\nDim header As String\nLine Input #1, header\nheader += \",SUM\"\nPrint #2, header\n\nDim As Integer c1, c2, c3, c4, c5, sum\n\nWhile Not Eof(1)\n Input #1, c1, c2, c3, c4, c5\n sum = c1 + c2 + c3 + c4 + c5\n Write #2, c1, c2, c3, c4, c5, sum\nWend\n\nClose #1\nClose #2\n", "language": "FreeBASIC" }, { "code": "import io.{lines, PrintWriter}\n\ndata Table( header, rows )\n\ndef read( file ) =\n l = lines( file )\n\n def next = vector( l.next().split(',') )\n\n if l.isEmpty() then\n return Table( vector(), [] )\n\n header = next()\n rows = seq()\n\n while l.hasNext()\n rows += next()\n\n Table( header, rows.toList() )\n\ndef write( table, out ) =\n w = if out is String then PrintWriter( out ) else out\n\n w.println( table.header.mkString(',') )\n\n for r <- table.rows\n w.println( r.mkString(',') )\n\n if out is String\n w.close()\n\ndef updateRow( header, row, updates ) =\n r = dict( (header(i), row(i)) | i <- 0:header.length() )\n updates( r )\n vector( r(f) | f <- header )\n\ndef update( table, updates ) =\t\t\n Table( table.header, (updateRow(table.header, r, updates) | r <- table.rows).toList() )\n\ndef addColumn( table, column, updates ) =\n Table( table.header + [column], (updateRow(table.header + [column], r + [null], updates) | r <- table.rows).toList() )\n\nt = addColumn( read('test.csv'), 'SUM', r -> r('SUM') = sum(int(v) | (_, v) <- r if v != null) )\nwrite( t, 'test_out.csv' )\nwrite( t, System.out )\n", "language": "FunL" }, { "code": "include \"NSLog.incl\"\n\ninclude resources \"rosetta_csv.csv\"\n\n/*\n\nThis ASCII text data is saved as a resource file\nnamed \"rosetta_csv.csv\" in the application bundle.\n\nC1,C2,C3,C4,C5\n1,5,9,13,17\n2,6,10,14,18\n3,7,11,15,19\n4,8,12,16,20\n\n*/\n\nvoid local fn ManipulateCSV\n CFURLRef url = fn BundleURLForResource( fn BundleMain, @\"rosetta_csv\", @\"csv\", NULL )\n CFStringRef csvString = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )\n CFArrayRef csvArray = fn StringComponentsSeparatedByCharactersInSet( csvString, fn CharacterSetNewlineSet )\n CFMutableStringRef mutStr = fn MutableStringWithCapacity(0)\n long i\n\n MutableStringAppendFormat( mutStr, @\",%@,SUM,AVG\\n\", csvArray[0] )\n for i = 1 to len(csvArray) - 1\n CFArrayRef nums = fn StringComponentsSeparatedByString( csvArray[i], @\",\" )\n CFNumberRef sum = fn ObjectValueForKeyPath( nums, @\"@sum.self\" )\n CFNumberRef avg = fn ObjectValueForKeyPath( nums, @\"@avg.self\" )\n MutableStringAppendFormat( mutStr, @\"R%ld,%@,%@,%@\\n\",i,csvArray[i],sum,avg )\n next\n\n NSLog( @\"%@\", mutStr )\n\n CFURLRef desktopURL = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask )\n url = fn URLByAppendingPathComponent( desktopURL, @\"final_csv.csv\" )\n fn StringWriteToURL( mutStr, url, YES, NSUTF8StringEncoding, NULL )\nend fn\n\nfn ManipulateCSV\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Form_Open()\nDim sData As String = File.Load(\"data.csv\")\nDim sLine, sTemp As String\nDim sOutput As New String[]\nDim siCount As Short\nDim bLine1 As Boolean\n\nFor Each sLine In Split(sData, gb.NewLine)\n If Not bLine1 Then\n sLine &= \",SUM\"\n sOutput.Add(sLine)\n bLine1 = True\n Continue\n End If\n For Each sTemp In Split(sLine)\n siCount += Val(sTemp)\n Next\n sOutput.Add(sLine & \",\" & Str(siCount))\n siCount = 0\nNext\n\nsData = \"\"\n\nFor Each sTemp In sOutput\n sData &= sTemp & gb.NewLine\n Print sTemp;\n Print\nNext\n\nFile.Save(User.home &/ \"CSVData.csv\", sData)\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport (\n\t\"encoding/csv\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n)\n\nfunc main() {\n\trows := readSample()\n\tappendSum(rows)\n\twriteChanges(rows)\n}\n\nfunc readSample() [][]string {\n\tf, err := os.Open(\"sample.csv\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\trows, err := csv.NewReader(f).ReadAll()\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn rows\n}\n\nfunc appendSum(rows [][]string) {\n\trows[0] = append(rows[0], \"SUM\")\n\tfor i := 1; i < len(rows); i++ {\n\t\trows[i] = append(rows[i], sum(rows[i]))\n\t}\n}\n\nfunc sum(row []string) string {\n\tsum := 0\n\tfor _, s := range row {\n\t\tx, err := strconv.Atoi(s)\n\t\tif err != nil {\n\t\t\treturn \"NA\"\n\t\t}\n\t\tsum += x\n\t}\n\treturn strconv.Itoa(sum)\n}\n\nfunc writeChanges(rows [][]string) {\n\tf, err := os.Create(\"output.csv\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = csv.NewWriter(f).WriteAll(rows)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n", "language": "Go" }, { "code": "def csv = []\ndef loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }\ndef saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }\n\nloadCsv new File('csv.txt')\ncsv[0][0] = 'Column0'\n(1..4).each { i -> csv[i][i] = i * 100 }\nsaveCsv new File('csv_out.txt')\n", "language": "Groovy" }, { "code": "import Data.Array (Array(..), (//), bounds, elems, listArray)\nimport Data.List (intercalate)\nimport Control.Monad (when)\nimport Data.Maybe (isJust)\n\ndelimiters :: String\ndelimiters = \",;:\"\n\nfields :: String -> [String]\nfields [] = []\nfields xs =\n let (item, rest) = break (`elem` delimiters) xs\n (_, next) = break (`notElem` delimiters) rest\n in item : fields next\n\nunfields :: Maybe (Array (Int, Int) String) -> [String]\nunfields Nothing = []\nunfields (Just a) = every fieldNumber $ elems a\n where\n ((_, _), (_, fieldNumber)) = bounds a\n every _ [] = []\n every n xs =\n let (y, z) = splitAt n xs\n in intercalate \",\" y : every n z\n\nfieldArray :: [[String]] -> Maybe (Array (Int, Int) String)\nfieldArray [] = Nothing\nfieldArray xs =\n Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs\n\nfieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))\nfieldsFromFile = fmap (fieldArray . map fields . lines) . readFile\n\nfieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()\nfieldsToFile f = writeFile f . unlines . unfields\n\nsomeChanges :: Maybe (Array (Int, Int) String)\n -> Maybe (Array (Int, Int) String)\nsomeChanges =\n fmap (// [((1, 1), \"changed\"), ((3, 4), \"altered\"), ((5, 2), \"modified\")])\n\nmain :: IO ()\nmain = do\n a <- fieldsFromFile \"example.txt\"\n when (isJust a) $ fieldsToFile \"output.txt\" $ someChanges a\n", "language": "Haskell" }, { "code": "{-# LANGUAGE FlexibleContexts,\n TypeFamilies,\n NoMonomorphismRestriction #-}\nimport Data.List (intercalate)\nimport Data.List.Split (splitOn)\nimport Lens.Micro\n\n(<$$>) :: (Functor f1, Functor f2) =>\n (a -> b) -> f1 (f2 a) -> f1 (f2 b)\n(<$$>) = fmap . fmap\n\n------------------------------------------------------------\n-- reading and writing\n\nnewtype CSV = CSV { values :: [[String]] }\n\nreadCSV :: String -> CSV\nreadCSV = CSV . (splitOn \",\" <$$> lines)\n\ninstance Show CSV where\n show = unlines . map (intercalate \",\") . values\n\n------------------------------------------------------------\n-- construction and combination\n\nmkColumn, mkRow :: [String] -> CSV\n(<||>), (<==>) :: CSV -> CSV -> CSV\n\nmkColumn lst = CSV $ sequence [lst]\nmkRow lst = CSV [lst]\n\nCSV t1 <||> CSV t2 = CSV $ zipWith (++) t1 t2\nCSV t1 <==> CSV t2 = CSV $ t1 ++ t2\n\n------------------------------------------------------------\n-- access and modification via lenses\n\ntable = lens values (\\csv t -> csv {values = t})\nrow i = table . ix i . traverse\ncol i = table . traverse . ix i\nitem i j = table . ix i . ix j\n\n------------------------------------------------------------\n\nsample = readCSV \"C1, C2, C3, C4, C5\\n\\\n \\1, 5, 9, 13, 17\\n\\\n \\2, 6, 10, 14, 18\\n\\\n \\3, 7, 11, 15, 19\\n\\\n \\4, 8, 12, 16, 20\"\n", "language": "Haskell" }, { "code": "sampleSum = sample <||> (mkRow [\"SUM\"] <==> mkColumn sums)\n where sums = map (show . sum) (read <$$> drop 1 (values sample))\n", "language": "Haskell" }, { "code": "import Utils # To get CSV procedures\n\nprocedure main(A)\n f := open(A[1]) | &input\n i := 1\n write(!f) # header line(?)\n every csv := parseCSV(!f) do {\n csv[i+:=1] *:= 100\n write(encodeCSV(csv))\n }\nend\n", "language": "Icon" }, { "code": " data=: (','&splitstring);.2 freads 'rc_csv.csv' NB. read and parse data\n data=: (<'\"spam\"') (<2 3)} data NB. amend cell in 3rd row, 4th column (0-indexing)\n 'rc_outcsv.csv' fwrites~ ;<@(','&joinstring\"1) data NB. format and write out amended data\n", "language": "J" }, { "code": " require 'tables/csv'\n data=: makenum readcsv 'rc_csv.csv' NB. read data and convert cells to numeric where possible\n data=: (<'spam') (2 3;3 0)} data NB. amend 2 cells\n data writecsv 'rc_outcsv.csv' NB. write out amended data. Strings are double-quoted\n", "language": "J" }, { "code": " require 'tables/csv'\n 'hdr data'=: split readcsv 'rc_csv.csv' NB. read data, split the header & data\n hdr=: hdr , <'SUM' NB. add title for extra column to header\n data=: <\"0 (,. +/\"1) makenum data NB. convert to numeric, sum rows & append column\n (hdr,data) writecsv 'rc_out.csv'\n", "language": "J" }, { "code": " sumCSVrows=: writecsv~ (((<'SUM') ,~ {.) , [: (<\"0)@(,. +/\"1) makenum@}.)@readcsv\n 'rc_out.csv' sumCSVrows 'rc.csv'\n", "language": "J" }, { "code": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n", "language": "Java" }, { "code": "public class CSV {\n public static void main(String[] args) throws IOException {\n CSV csv = new CSV(\"data.csv\");\n csv.sumAllRows();\n csv.write();\n }\n\n private final File file;\n private List<List<String>> data;\n\n public CSV(File file) throws IOException {\n this.file = file;\n open();\n }\n\n /* convenience constructor */\n public CSV(String path) throws IOException {\n this(new File(path));\n }\n\n public void sumAllRows() {\n appendColumn(\"SUM\");\n int sum;\n int length;\n for (int index = 1; index < data.size(); index++) {\n sum = sum(data.get(index));\n length = data.get(index).size();\n data.get(index).set(length - 1, String.valueOf(sum));\n }\n }\n\n private int sum(List<String> row) {\n int sum = 0;\n for (int index = 0; index < row.size() - 1; index++)\n sum += Integer.parseInt(row.get(index));\n return sum;\n }\n\n private void appendColumn(String title) {\n List<String> titles = data.get(0);\n titles.add(title);\n /* append an empty cell to each row */\n for (int index = 1; index < data.size(); index++)\n data.get(index).add(\"\");\n }\n\n private void open() throws IOException {\n try (BufferedReader reader = new BufferedReader(new FileReader(file))) {\n data = new ArrayList<>();\n String line;\n while ((line = reader.readLine()) != null) {\n /* using a limit of -1 will preserve trailing commas */\n data.add(new ArrayList<>(List.of(line.split(\",\", -1))));\n }\n }\n }\n\n public void write() throws IOException {\n try (FileWriter writer = new FileWriter(file)) {\n String newline = System.lineSeparator();\n for (List<String> row : data) {\n writer.write(String.join(\",\", row));\n writer.write(newline);\n }\n writer.flush();\n }\n }\n}\n", "language": "Java" }, { "code": "import java.io.*;\nimport java.awt.Point;\nimport java.util.HashMap;\nimport java.util.Scanner;\n\npublic class CSV {\n\n private HashMap<Point, String> _map = new HashMap<Point, String>();\n private int _cols;\n private int _rows;\n\n public void open(File file) throws FileNotFoundException, IOException {\n open(file, ',');\n }\n\n public void open(File file, char delimiter)\n throws FileNotFoundException, IOException {\n Scanner scanner = new Scanner(file);\n scanner.useDelimiter(Character.toString(delimiter));\n\n clear();\n\n while(scanner.hasNextLine()) {\n String[] values = scanner.nextLine().split(Character.toString(delimiter));\n\n int col = 0;\n for ( String value: values ) {\n _map.put(new Point(col, _rows), value);\n _cols = Math.max(_cols, ++col);\n }\n _rows++;\n }\n scanner.close();\n }\n\n public void save(File file) throws IOException {\n save(file, ',');\n }\n\n public void save(File file, char delimiter) throws IOException {\n FileWriter fw = new FileWriter(file);\n BufferedWriter bw = new BufferedWriter(fw);\n\n for (int row = 0; row < _rows; row++) {\n for (int col = 0; col < _cols; col++) {\n Point key = new Point(col, row);\n if (_map.containsKey(key)) {\n bw.write(_map.get(key));\n }\n\n if ((col + 1) < _cols) {\n bw.write(delimiter);\n }\n }\n bw.newLine();\n }\n bw.flush();\n bw.close();\n }\n\n public String get(int col, int row) {\n String val = \"\";\n Point key = new Point(col, row);\n if (_map.containsKey(key)) {\n val = _map.get(key);\n }\n return val;\n }\n\n public void put(int col, int row, String value) {\n _map.put(new Point(col, row), value);\n _cols = Math.max(_cols, col+1);\n _rows = Math.max(_rows, row+1);\n }\n\n public void clear() {\n _map.clear();\n _cols = 0;\n _rows = 0;\n }\n\n public int rows() {\n return _rows;\n }\n\n public int cols() {\n return _cols;\n }\n\n public static void main(String[] args) {\n try {\n CSV csv = new CSV();\n\n csv.open(new File(\"test_in.csv\"));\n csv.put(0, 0, \"Column0\");\n csv.put(1, 1, \"100\");\n csv.put(2, 2, \"200\");\n csv.put(3, 3, \"300\");\n csv.put(4, 4, \"400\");\n csv.save(new File(\"test_out.csv\"));\n } catch (Exception e) {\n }\n }\n}\n", "language": "Java" }, { "code": "import java.io.*;\nimport java.util.*;\n\nimport org.apache.commons.csv.*;\n\npublic class RCsv {\n private static final String NL = System.getProperty(\"line.separator\");\n private static final String FILENAME_IR = \"data/csvtest_in.csv\";\n private static final String FILENAME_OR = \"data/csvtest_sum.csv\";\n private static final String COL_NAME_SUM = \"SUM, \\\"integers\\\"\"; // demonstrate white space, comma & quote handling\n\n public static void main(String[] args) {\n Reader iCvs = null;\n Writer oCvs = null;\n System.out.println(textFileContentsToString(FILENAME_IR));\n try {\n iCvs = new BufferedReader(new FileReader(FILENAME_IR));\n oCvs = new BufferedWriter(new FileWriter(FILENAME_OR));\n processCsv(iCvs, oCvs);\n }\n catch (IOException ex) {\n ex.printStackTrace();\n }\n finally {\n try {\n if (iCvs != null) { iCvs.close(); }\n if (oCvs != null) { oCvs.close(); }\n }\n catch (IOException ex) {\n ex.printStackTrace();\n }\n }\n System.out.println(textFileContentsToString(FILENAME_OR));\n return;\n }\n\n public static void processCsv(Reader iCvs, Writer oCvs) throws IOException {\n CSVPrinter printer = null;\n try {\n printer = new CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL));\n List<String> oCvsHeaders;\n List<String> oCvsRecord;\n CSVParser records = CSVFormat.DEFAULT.withHeader().parse(iCvs);\n Map<String, Integer> irHeader = records.getHeaderMap();\n oCvsHeaders = new ArrayList<String>(Arrays.asList((irHeader.keySet()).toArray(new String[0])));\n oCvsHeaders.add(COL_NAME_SUM);\n printer.printRecord(oCvsHeaders);\n for (CSVRecord record : records) {\n oCvsRecord = record2list(record, oCvsHeaders);\n printer.printRecord(oCvsRecord);\n }\n }\n finally {\n if (printer != null) {\n printer.close();\n }\n }\n return;\n }\n\n private static List<String> record2list(CSVRecord record, List<String> oCvsHeaders) {\n List<String> cvsRecord;\n Map<String, String> rMap = record.toMap();\n long recNo = record.getRecordNumber();\n rMap = alterRecord(rMap, recNo);\n int sum = 0;\n sum = summation(rMap);\n rMap.put(COL_NAME_SUM, String.valueOf(sum));\n cvsRecord = new ArrayList<String>();\n for (String key : oCvsHeaders) {\n cvsRecord.add(rMap.get(key));\n }\n return cvsRecord;\n }\n\n private static Map<String, String> alterRecord(Map<String, String> rMap, long recNo) {\n int rv;\n Random rg = new Random(recNo);\n rv = rg.nextInt(50);\n String[] ks = rMap.keySet().toArray(new String[0]);\n int ix = rg.nextInt(ks.length);\n long yv = 0;\n String ky = ks[ix];\n String xv = rMap.get(ky);\n if (xv != null && xv.length() > 0) {\n yv = Long.valueOf(xv) + rv;\n rMap.put(ks[ix], String.valueOf(yv));\n }\n return rMap;\n }\n\n private static int summation(Map<String, String> rMap) {\n int sum = 0;\n for (String col : rMap.keySet()) {\n String nv = rMap.get(col);\n sum += nv != null && nv.length() > 0 ? Integer.valueOf(nv) : 0;\n }\n return sum;\n }\n\n private static String textFileContentsToString(String filename) {\n StringBuilder lineOut = new StringBuilder();\n Scanner fs = null;\n try {\n fs = new Scanner(new File(filename));\n lineOut.append(filename);\n lineOut.append(NL);\n while (fs.hasNextLine()) {\n String line = fs.nextLine();\n lineOut.append(line);\n lineOut.append(NL);\n }\n }\n catch (FileNotFoundException ex) {\n // TODO Auto-generated catch block\n ex.printStackTrace();\n }\n finally {\n if (fs != null) {\n fs.close();\n }\n }\n return lineOut.toString();\n }\n}\n", "language": "Java" }, { "code": "public static void main(String[] args) throws IOException {\n\n // 1st, config the CSV reader with line separator\n CsvParserSettings settings = new CsvParserSettings();\n settings.getFormat().setLineSeparator(\"\\n\");\n\n // 2nd, config the CSV reader with row processor attaching the bean definition\n BeanListProcessor<Employee> rowProcessor = new BeanListProcessor<Employee>(Employee.class);\n settings.setRowProcessor(rowProcessor);\n\n // 3rd, creates a CSV parser with the configs\n CsvParser parser = new CsvParser(settings);\n\n // 4th, parse all rows from the CSF file into the list of beans you defined\n parser.parse(new FileReader(\"/examples/employees.csv\"));\n List<Employee> resolvedBeans = rowProcessor.getBeans();\n\n // 5th, Store, Delete duplicates, Re-arrange the words in specific order\n // ......\n\n // 6th, Write the listed of processed employee beans out to a CSV file.\n CsvWriterSettings writerSettings = new CsvWriterSettings();\n\n // 6.1 Creates a BeanWriterProcessor that handles annotated fields in the Employee class.\n writerSettings.setRowWriterProcessor(new BeanWriterProcessor<Employee>(Employee.class));\n\n // 6.2 persistent the employee beans to a CSV file.\n CsvWriter writer = new CsvWriter(new FileWriter(\"/examples/processed_employees.csv\"), writerSettings);\n writer.processRecords(resolvedBeans);\n writer.writeRows(new ArrayList<List<Object>>());\n }\n", "language": "Java" }, { "code": "(function () {\n 'use strict';\n\n // splitRegex :: Regex -> String -> [String]\n function splitRegex(rgx, s) {\n return s.split(rgx);\n }\n\n // lines :: String -> [String]\n function lines(s) {\n return s.split(/[\\r\\n]/);\n }\n\n // unlines :: [String] -> String\n function unlines(xs) {\n return xs.join('\\n');\n }\n\n // macOS JavaScript for Automation version of readFile.\n // Other JS contexts will need a different definition of this function,\n // and some may have no access to the local file system at all.\n\n // readFile :: FilePath -> maybe String\n function readFile(strPath) {\n var error = $(),\n str = ObjC.unwrap(\n $.NSString.stringWithContentsOfFileEncodingError(\n $(strPath)\n .stringByStandardizingPath,\n $.NSUTF8StringEncoding,\n error\n )\n );\n return error.code ? error.localizedDescription : str;\n }\n\n // macOS JavaScript for Automation version of writeFile.\n // Other JS contexts will need a different definition of this function,\n // and some may have no access to the local file system at all.\n\n // writeFile :: FilePath -> String -> IO ()\n function writeFile(strPath, strText) {\n $.NSString.alloc.initWithUTF8String(strText)\n .writeToFileAtomicallyEncodingError(\n $(strPath)\n .stringByStandardizingPath, false,\n $.NSUTF8StringEncoding, null\n );\n }\n\n // EXAMPLE - appending a SUM column\n\n var delimCSV = /,\\s*/g;\n\n var strSummed = unlines(\n lines(readFile('~/csvSample.txt'))\n .map(function (x, i) {\n var xs = x ? splitRegex(delimCSV, x) : [];\n\n return (xs.length ? xs.concat(\n // 'SUM' appended to first line, others summed.\n i > 0 ? xs.reduce(\n function (a, b) {\n return a + parseInt(b, 10);\n }, 0\n ).toString() : 'SUM'\n ) : []).join(',');\n })\n );\n\n return (\n writeFile('~/csvSampleSummed.txt', strSummed),\n strSummed\n );\n\n})();\n", "language": "JavaScript" }, { "code": "const fs = require('fs');\n\n// formats for the data parameter in the function below: {col1: array | function, col2: array | function}\n\nfunction addCols(path, data) {\n let csv = fs.readFileSync(path, 'utf8');\n csv = csv.split('\\n').map(line => line.trim());\n let colNames = Object.keys(data);\n for (let i = 0; i < colNames.length; i++) {\n let c = colNames[i];\n if (typeof data[c] === 'function') {\n csv = csv.map((line, idx) => idx === 0\n ? line + ',' + c\n : line + ',' + data[c](line, idx)\n );\n } else if (Array.isArray(data[c])) {\n csv = csv.map((line, idx) => idx === 0\n ? line + ',' + c\n : line + ',' + data[c][idx - 1]\n );\n }\n }\n fs.createWriteStream(path, {\n flag: 'w',\n defaultEncoding: 'utf8'\n }).end(csv.join('\\n'));\n}\n\naddCols('test.csv', {\n sum: function (line, idx) {\n let s = 0;\n line = line.split(',').map(d => +(d.trim()));\n for (let i = 0; i < line.length; i++) {\n s += line[i];\n }\n return s;\n },\n id: function(line, idx) {\n return idx;\n }\n });\n", "language": "JavaScript" }, { "code": "# Input: a single row\n# Omit empty rows\ndef read_csv:\n if length>0 then split(\",\") else empty end ;\n\n# Input: an array\n# Output: the same array but with an additional summation column.\n# If .[0] is a number, then it is assumed the entire row consists of numbers or numeric strings;\n# otherwise, 0 is added\ndef add_sum:\n (if .[0] | type == \"number\" then (map(tonumber) | add) else 0 end) as $sum\n | . + [$sum] ;\n\n# `tocsv` is only needed if fields should only be quoted by necessity:\ndef tocsv:\n map( if type == \"string\" and test(\"[,\\\"\\r\\n]\") then \"\\\"\\(.)\\\"\" else . end )\n | join(\",\");\n\n( input | read_csv | . + [\"SUM\"] | @csv),\n(inputs | read_csv | add_sum | @csv)\n", "language": "Jq" }, { "code": "using DataFrames, CSV\n\nifn = \"csv_data_manipulation_in.dat\"\nofn = \"csv_data_manipulation_out.dat\"\n\ndf = CSV.read(ifn, DataFrame)\ndf.SUM = sum.(eachrow(df))\nCSV.write(ofn, df)\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nimport java.io.File\n\nfun main(args: Array<String>) {\n val lines = File(\"example.csv\").readLines().toMutableList()\n lines[0] += \",SUM\"\n for (i in 1 until lines.size) {\n lines[i] += \",\" + lines[i].split(',').sumBy { it.toInt() }\n }\n val text = lines.joinToString(\"\\n\")\n File(\"example2.csv\").writeText(text) // write to new file\n println(text) // print to console\n}\n", "language": "Kotlin" }, { "code": "----------------------------------------\n-- Simplified CSV parser (without escape character support etc.).\n-- First line is interrepted as header with column names.\n-- @param {string} csvStr\n-- @param {string} [sep=\",\"] - single char as string\n-- @param {string} [eol=RETURN]\n-- @return {propList}\n----------------------------------------\non parseSimpleCSVString (csvStr, sep, eol)\n if voidP(sep) then sep=\",\"\n if voidP(eol) then eol = RETURN\n lines = explode(eol, csvStr)\n if lines.getLast()=\"\" then lines.deleteAt(lines.count)\n res = [:]\n res[#header] = explode(sep, lines[1])\n res[#data] = []\n cnt = lines.count\n repeat with i = 2 to cnt\n res[#data].append(explodeBySingleChar(sep, lines[i]))\n end repeat\n return res\nend\n\n----------------------------------------\n-- Simplified CSV creater (without escape character support etc.).\n-- @param {propList} csvData\n-- @param {string} [sep=\",\"]\n-- @param {string} [eol=RETURN]\n-- @return {string}\n----------------------------------------\non createSimpleCSVString (csvData, sep, eol)\n if voidP(sep) then sep=\",\"\n if voidP(eol) then eol = RETURN\n res = \"\"\n put implode(sep, csvData[#header])&eol after res\n cnt = csvData[#data].count\n repeat with i = 1 to cnt\n put implode(sep, csvData[#data][i])&eol after res\n end repeat\n return res\nend\n\n----------------------------------------\n-- Explodes string into list\n-- @param {string} delim\n-- @param {string} str\n-- @return {list}\n----------------------------------------\non explode (delim, str)\n if delim.length=1 then return explodeBySingleChar(delim, str)\n l = []\n if voidP(str) then return l\n dl = delim.length\n repeat while true\n pos = offset(delim, str)\n if pos=0 then exit repeat\n l.add(str.char[1..pos-1])\n delete char 1 to pos+dl-1 of str\n end repeat\n if pos=0 then pos = 1-dl\n l.add(str.char[pos+dl..str.length])\n return l\nend\n\n----------------------------------------\n-- Explode string into list based on single char delimiter\n-- (uses Lingo's build-in 'item' support, therefor faster)\n-- @param {string} delim\n-- @param {string} str\n-- @return {list}\n----------------------------------------\non explodeBySingleChar (delim, str)\n l = []\n if voidP(str) then return l\n od = _player.itemDelimiter\n _player.itemDelimiter = delim\n cnt = str.item.count\n repeat with i = 1 to cnt\n l.add(str.item[i])\n end repeat\n _player.itemDelimiter = od\n return l\nend\n\n----------------------------------------\n-- Implodes list into string\n-- @param {string} delim\n-- @param {list} l\n-- @return {string}\n----------------------------------------\non implode (delim, l)\n str = \"\"\n cnt = l.count\n repeat with i = 1 to cnt\n put l[i]&delim after str\n end repeat\n delete char (str.length-delim.length+1) to str.length of str\n return str\nend\n", "language": "Lingo" }, { "code": "sep = \",\"\neol = numtochar(10)\n\n-- load CSV string from file\nfn = _movie.path & \"file.csv\"\nfp = xtra(\"fileIO\").new()\nfp.openFile(fn, 1)\ncsvStr = fp.readFile()\nfp.closeFile()\n\n-- parse CSV string into propList\ncsvData = parseSimpleCSVString(csvStr, sep, eol)\n\n-- add SUM column\ncsvData[#header].append(\"SUM\")\nrepeat with row in csvData[#data]\n sum = 0\n repeat with cell in row\n sum = sum+integer(cell)\n end repeat\n row.append(sum)\nend repeat\n\n-- create CSV string from updated propList\ncsvString = createSimpleCSVString(csvData, sep, eol)\n\n-- save CSV string to file\nfn = _movie.path & \"file.csv\"\nfp.openFile(fn, 2)\nif not fp.status() then fp.delete()\nfp.createFile(fn)\nfp.openFile(fn, 2)\nfp.writeString(csvString)\nfp.closeFile()\n\n-- show the CSV string\nput csvString\n\n-- \"C1,C2,C3,C4,C5,SUM\n1,5,9,13,17,45\n2,6,10,14,18,50\n3,7,11,15,19,55\n4,8,12,16,20,60\n\"\n", "language": "Lingo" }, { "code": "to csv.data.manipulation :in :out\n local [header line list sum]\n\topenread :in\n\tsetread :in\n\topenwrite :out\n\tsetwrite :out\n\tmake \"header readword\n print word :header \",SUM\n\twhile [not eofp] [\n\t\tmake \"line readword\n\t\tmake \"list parse map [ifelse equalp ? \", [\"\\ ] [?]] :line\n\t\tmake \"sum apply \"sum :list\n\t\tprint (word :line \"\\, :sum)\n\t]\n\tclose :in\n\tsetread []\n\tclose :out\n\tsetwrite []\nend\n", "language": "Logo" }, { "code": "csv.data.manipulation \"data.csv \"output.csv\n", "language": "Logo" }, { "code": "local csv={}\nfor line in io.lines('file.csv') do\n table.insert(csv, {})\n local i=1\n for j=1,#line do\n if line:sub(j,j) == ',' then\n table.insert(csv[#csv], line:sub(i,j-1))\n i=j+1\n end\n end\n table.insert(csv[#csv], line:sub(i,j))\nend\n\ntable.insert(csv[1], 'SUM')\nfor i=2,#csv do\n local sum=0\n for j=1,#csv[i] do\n sum=sum + tonumber(csv[i][j])\n end\n if sum>0 then\n table.insert(csv[i], sum)\n end\nend\n\nlocal newFileData = ''\nfor i=1,#csv do\n newFileData=newFileData .. table.concat(csv[i], ',') .. '\\n'\nend\n\nlocal file=io.open('file.csv', 'w')\nfile:write(newFileData)\n", "language": "Lua" }, { "code": "Module Checkit {\n Function Sum {\n Long c=0\n while not empty {\n c+=number\n }\n =c\n }\n Document CSV$ = {C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n }\n \\\\ export encoded to UTF-16LE\n Save.Doc CSV$, \"data1.csv\", 0\n \\\\ Open Wide read UTF-16LE\n \\\\ use standard colum sep. as \",\"\n \\\\ use standard decimal point char\n \\\\ use standard (non json style string)\n \\\\ True = use bare strings (without \"\")\n Input With \"\",,,true\n Write With\"\",,,true\n \\\\ for excel csv use Input With chr$(9),,true, true\n Open \"data1.csv\" for Wide Input as #M\n Open \"data2.csv\" for Wide Output as #M1\n Input #M, h1$, h2$, h3$, h4$, h5$\n Write #M1, h1$, h2$, h3$, h4$, h5$\n Print h1$, h2$, h3$, h4$, h5$\n\n While not Eof(#M) {\n Input #M, A1, A2, A3, A4, A5\n Write #M1, A1, A2, A3, A4, A5, Sum(A1, A2, A3, A4, A5)\n Print A1, A2, A3, A4, A5\n }\n close #M1\n Close #M\n Open \"data2.csv\" for Wide Input as #M\n Input #M, h1$, h2$, h3$, h4$, h5$\n Print h1$, h2$, h3$, h4$, h5$\n While not Eof(#M) {\n Input #M, A1, A2, A3, A4, A5, Sum\n Print A1, A2, A3, A4, A5, Sum\n }\n Close #M\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "M := ImportMatrix(\"data.csv\",source=csv);\nM(..,6) := < \"Total\", seq( add(M[i,j], j=1..5), i=2..5 ) >;\nExportMatrix(\"data_out.csv\",M,target=csv);\n", "language": "Maple" }, { "code": "> M := ImportMatrix(\"data.csv\",source=csv);\n [\"C1\" \"C2\" \"C3\" \"C4\" \"C5\"]\n [ ]\n [ 1 5 9 13 17 ]\n [ ]\n M := [ 2 6 10 14 18 ]\n [ ]\n [ 3 7 11 15 19 ]\n [ ]\n [ 4 8 12 16 20 ]\n\n> M(..,6) := < \"Total\", seq( add(M[i,j], j=1..5), i=2..5 ) >;\n [\"C1\" \"C2\" \"C3\" \"C4\" \"C5\" \"Total\"]\n [ ]\n [ 1 5 9 13 17 45 ]\n [ ]\n M := [ 2 6 10 14 18 50 ]\n [ ]\n [ 3 7 11 15 19 55 ]\n [ ]\n [ 4 8 12 16 20 60 ]\n\n> ExportMatrix(\"data_out.csv\",M,target=csv);\n 96\n", "language": "Maple" }, { "code": "iCSV=Import[\"test.csv\"]\n->{{\"C1\",\"C2\",\"C3\",\"C4\",\"C5\"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}}\niCSV = Transpose@\n Append[Transpose[iCSV], Join[{\"Sum\"}, Total /@ Drop[iCSV, 1]]];\niCSV // MatrixForm\nExport[\"test.csv\",iCSV];\n", "language": "Mathematica" }, { "code": "filename='data.csv';\nfid = fopen(filename);\nheader = fgetl(fid);\nfclose(fid);\nX = dlmread(filename,',',1,0);\n\nfid = fopen('data.out.csv','w+');\nfprintf(fid,'%s,sum\\n',header);\nfor k=1:size(X,1),\n\tfprintf(fid,\"%i,\",X(k,:));\n\tfprintf(fid,\"%i\\n\",sum(X(k,:)));\nend;\nfclose(fid);\n", "language": "MATLAB" }, { "code": "filename='data.csv';\ndata = readtable(filename);\ndata.SUM = sum([data{:,:}],2);\nwritetable(data,filename);\n", "language": "MATLAB" }, { "code": "def sum(record)\n sum = 0\n\n for i in range(1, len(record) - 1)\n sum = sum + int(record ~ i)\n end for\n\n return sum\nend def\n\nopen \"file.csv\"\nadd \"SUM\"\n\nfor i in range($dbsize, 1)\n (i ~ @\"SUM\") = sum(#i)\nend for\n\nwrite\n", "language": "Nanoquery" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols\n\nimport org.apache.commons.csv.\n\n-- =============================================================================\nclass RCsv public final\n\nproperties private constant\n NL = String System.getProperty(\"line.separator\")\n COL_NAME_SUM = String 'SUM, \"integers\"'\n CSV_IFILE = 'data/csvtest_in.csv'\n CSV_OFILE = 'data/csvtest_sumRexx.csv'\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod main(args = String[]) public static\n Arg = Rexx(args)\n iCvs = Reader null\n oCvs = Writer null\n parse arg ifile ofile .\n if ifile = '', ifile = '.' then ifile = CSV_IFILE\n if ofile = '', ofile = '.' then ofile = CSV_OFILE\n say textFileContentsToString(ifile)\n do\n iCvs = BufferedReader(FileReader(ifile))\n oCvs = BufferedWriter(FileWriter(ofile))\n processCsv(iCvs, oCvs);\n catch ex = IOException\n ex.printStackTrace();\n finally\n do\n if iCvs \\= null then iCvs.close()\n if oCvs \\= null then oCvs.close()\n catch ex = IOException\n ex.printStackTrace()\n end\n end\n say textFileContentsToString(ofile)\n return\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException\n printer = CSVPrinter null\n do\n printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL))\n oCvsHeaders = java.util.List\n oCvsRecord = java.util.List\n records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs)\n irHeader = records.getHeaderMap()\n oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0])))\n oCvsHeaders.add(COL_NAME_SUM)\n printer.printRecord(oCvsHeaders)\n recordIterator = records.iterator()\n record = CSVRecord\n loop while recordIterator.hasNext()\n record = CSVRecord recordIterator.next()\n oCvsRecord = record2list(record, oCvsHeaders)\n printer.printRecord(oCvsRecord)\n end\n finally\n if printer \\= null then printer.close()\n end\n return\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List\n cvsRecord = java.util.List\n rMap = record.toMap()\n recNo = record.getRecordNumber()\n rMap = alterRecord(rMap, recNo)\n sum = summation(record.iterator())\n rMap.put(COL_NAME_SUM, sum)\n cvsRecord = ArrayList()\n loop ci = 0 to oCvsHeaders.size() - 1\n key = oCvsHeaders.get(ci)\n cvsRecord.add(rMap.get(key))\n end ci\n return cvsRecord\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod alterRecord(rMap = Map, recNo = long) private static binary returns Map\n rv = int\n rg = Random(recNo)\n rv = rg.nextInt(50)\n ks = rMap.keySet().toArray(String[0])\n ix = rg.nextInt(ks.length)\n yv = long 0\n ky = ks[ix];\n xv = String rMap.get(ky)\n if xv \\= null & xv.length() > 0 then do\n yv = Long.valueOf(xv).longValue() + rv\n rMap.put(ks[ix], String.valueOf(yv))\n end\n return rMap\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod summation(iColumn = Iterator) private static\n sum = 0\n loop while iColumn.hasNext()\n nv = Rexx(String iColumn.next())\n if nv = null, nv.length() = 0, \\nv.datatype('n') then nv = 0\n sum = sum + nv\n end\n return sum\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod textFileContentsToString(filename) private static\n lineOut = ''\n fs = Scanner null\n do\n fs = Scanner(File(filename))\n lineOut = lineout || filename || NL\n loop while fs.hasNextLine()\n line = fs.nextLine()\n lineOut = lineout || line || NL\n end\n catch ex = FileNotFoundException\n ex.printStackTrace()\n finally\n if fs \\= null then fs.close()\n end\n return lineOut\n", "language": "NetRexx" }, { "code": "import strutils, streams\n\nlet\n csv = newFileStream(\"data.csv\", fmRead)\n outf = newFileStream(\"data-out.csv\", fmWrite)\n\nvar lineNumber = 1\n\nwhile true:\n if atEnd(csv):\n break\n var line = readLine(csv)\n\n if lineNumber == 1:\n line.add(\",SUM\")\n else:\n var sum = 0\n for n in split(line, \",\"):\n sum += parseInt(n)\n line.add(\",\")\n line.add($sum)\n\n outf.writeLine(line)\n\n inc lineNumber\n", "language": "Nim" }, { "code": "use System.IO.File;\nuse Data.CSV;\n\nclass CsvData {\n function : Main(args : String[]) ~ Nil {\n file_out : FileWriter;\n leaving {\n if(file_out <> Nil) {\n file_out->Close();\n };\n };\n\n if(args->Size() > 0) {\n file_name := args[0];\n csv := CsvTable->New(FileReader->ReadFile(file_name));\n if(csv->IsParsed()) {\n csv->AppendColumn(\"SUM\");\n for(i := 1; i < csv->Size(); i += 1;) {\n row := csv->Get(i);\n sum := row->Sum(row->Size() - 1);\n row->Set(\"SUM\", sum->ToString());\n };\n };\n\n output := csv->ToString();\n output->PrintLine();\n\n file_out := FileWriter->New(\"new-csv.csv\");\n file_out->WriteString(output);\n };\n }\n}\n", "language": "Objeck" }, { "code": "let list_add_last this lst =\n List.rev (this :: (List.rev lst))\n\nlet () =\n let csv = Csv.load \"data.csv\" in\n let fields, data =\n (List.hd csv,\n List.tl csv)\n in\n let fields =\n list_add_last \"SUM\" fields\n in\n let sums =\n List.map (fun row ->\n let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in\n list_add_last (string_of_int tot) row\n ) data\n in\n Csv.output_all (Csv.to_channel stdout) (fields :: sums)\n", "language": "OCaml" }, { "code": "\\\\ CSV data manipulation\n\\\\ 10/24/16 aev\n\\\\ processCsv(fn): Where fn is an input path and file name (but no actual extension).\nprocessCsv(fn)=\n{my(F, ifn=Str(fn,\".csv\"), ofn=Str(fn,\"r.csv\"), cn=\",SUM\",nf,nc,Vr,svr);\nif(fn==\"\", return(-1));\nF=readstr(ifn); nf=#F;\nF[1] = Str(F[1],cn);\nfor(i=2, nf,\n Vr=stok(F[i],\",\"); if(i==2,nc=#Vr);\n svr=sum(k=1,nc,eval(Vr[k]));\n F[i] = Str(F[i],\",\",svr);\n);\\\\fend i\nfor(j=1, nf, write(ofn,F[j]))\n}\n\n\\\\ Testing:\nprocessCsv(\"c:\\\\pariData\\\\test\");\n", "language": "PARI-GP" }, { "code": "program CSV_Data_Manipulation;\nuses Classes, SysUtils;\n\nvar s: string;\n ts: tStringList;\n inFile,\n outFile: Text;\n Sum: integer;\n Number: string;\n\nbegin\n\n Assign(inFile,'input.csv');\n Reset(inFile);\n\n Assign(outFile,'result.csv');\n Rewrite(outFile);\n\n ts:=tStringList.Create;\n ts.StrictDelimiter:=True;\n\n // Handle the header\n ReadLn(inFile,s); // Read a line from input file\n ts.CommaText:=s; // Split it to lines\n ts.Add('SUM'); // Add a line\n WriteLn(outFile,ts.CommaText); // Reassemble it with comma as delimiter\n\n // Handle the data\n while not eof(inFile) do\n begin\n ReadLn(inFile,s);\n ts.CommaText:=s;\n\n Sum:=0;\n for Number in ts do\n Sum+=StrToInt(Number);\n\n ts.Add('%D',[Sum]);\n\n writeln(outFile, ts.CommaText);\n end;\n Close(outFile);\n Close(inFile);\n ts.Free;\nend.\n", "language": "Pascal" }, { "code": "#!/usr/bin/perl\nuse warnings;\nuse strict;\n\nuse List::Util 'sum';\n\nmy @header = split /,/, <>;\n# Remove the newline.\nchomp $header[-1];\n\nmy %column_number;\nfor my $i (0 .. $#header) {\n $column_number{$header[$i]} = $i;\n}\nmy @rows = map [ split /,/ ], <>;\nchomp $_->[-1] for @rows;\n\n# Add 1 to the numbers in the 2nd column:\n$_->[1]++ for @rows;\n\n# Add C1 into C4:\n$_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows;\n\n# Add sums to both rows and columns.\npush @header, 'Sum';\n$column_number{Sum} = $#header;\n\npush @$_, sum(@$_) for @rows;\npush @rows, [\n map {\n my $col = $_;\n sum(map $_->[ $column_number{$col} ], @rows);\n } @header\n ];\n\n# Print the output.\nprint join(',' => @header), \"\\n\";\nprint join(',' => @$_), \"\\n\" for @rows;\n", "language": "Perl" }, { "code": "#!/usr/bin/perl\nuse warnings;\nuse strict;\n\nuse Text::CSV;\nuse List::Util 'sum';\n\nmy $csv = 'Text::CSV'->new({eol => \"\\n\"})\n or die 'Cannot use CSV: ' . 'Text::CSV'->error_diag;\n\nmy $file = shift;\nmy @rows;\nopen my $FH, '<', $file or die \"Cannot open $file: $!\";\nmy @header = @{ $csv->getline($FH) };\nwhile (my $row = $csv->getline($FH)) {\n push @rows, $row;\n}\n$csv->eof or $csv->error_diag;\n\n#\n# The processing is the same.\n#\n\n# Print the output.\n$csv->print(*STDOUT, $_) for \\@header, @rows;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tcsv</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"\"\n C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n \"\"\"</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">lines</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">JS</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tcsv</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">):</span><span style=\"color: #7060A8;\">get_text</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"test.csv\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">GT_LF_STRIPPED</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">trim</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]),</span><span style=\"color: #008000;\">','</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #008000;\">','</span><span style=\"color: #0000FF;\">)&</span><span style=\"color: #008000;\">\",SUM\"</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]),</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">scanf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">)[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000080;font-style:italic;\">-- s[rand(length(s))] = rand(100) -- (if you like)</span>\n <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d,%d,%d,%d,%d,%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">lines</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'\\n'</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">fn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">open</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"out.csv\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"w\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">close</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\n\n// fputcsv() requires at least PHP 5.1.0\n// file \"data_in.csv\" holds input data\n// the result is saved in \"data_out.csv\"\n// this version has no error-checking\n\n$handle = fopen('data_in.csv','r');\n$handle_output = fopen('data_out.csv','w');\n$row = 0;\n$arr = array();\n\nwhile ($line = fgetcsv($handle))\n{\n $arr[] = $line;\n}\n\n//change some data to zeroes\n$arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17\n$arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18\n\n//add sum and write file\nforeach ($arr as $line)\n{\n if ($row==0)\n {\n array_push($line,\"SUM\");\n }\n else\n {\n array_push($line,array_sum($line));\n }\n fputcsv($handle_output, $line);\n $row++;\n}\n?>\n", "language": "PHP" }, { "code": "(in \"data.csv\"\n (prinl (line) \",\" \"SUM\")\n (while (split (line) \",\")\n (prinl (glue \",\" @) \",\" (sum format @)) ) )\n", "language": "PicoLisp" }, { "code": "*process source xref attributes or(!);\n csv: Proc Options(Main);\n /*********************************************************************\n * 19.10.2013 Walter Pachl\n * 'erase d:\\csv.out'\n * 'set dd:in=d:\\csv.in,recsize(300)'\n * 'set dd:out=d:\\csv.out,recsize(300)'\n * Say 'Input:'\n * 'type csv.in'\n * 'csv'\n * Say ' '\n * Say 'Output:'\n * 'type csv.out'\n *********************************************************************/\n Dcl in Record Input;\n Dcl out Record Output;\n On Endfile(in) Goto part2;\n Dcl (INDEX,LEFT,SUBSTR,TRIM) Builtin;\n\n Dcl (i,j,p,m,n) Bin Fixed(31) Init(0);\n Dcl s Char(100) Var;\n Dcl iline(10) Char(100) Var;\n Dcl a(20,20) Char(10) Var;\n Dcl sum Dec Fixed(3);\n Dcl oline Char(100) Var;\n\n Do i=1 By 1;\n Read File(in) Into(s);\n iline(i)=s;\n m=i;\n Call sep((s));\n End;\n\n part2:\n Do i=1 To m;\n If i=1 Then\n oline=iline(1)!!','!!'SUM';\n Else Do;\n sum=0;\n Do j=1 To n;\n sum=sum+a(i,j);\n End;\n oline=iline(i)!!','!!trim(sum);\n End;\n Write File(out) From(oline);\n End;\n\n sep: Procedure(line);\n Dcl line Char(*) Var;\n loop:\n Do j=1 By 1;\n p=index(line,',');\n If p>0 Then Do;\n a(i,j)=left(line,p-1);\n line=substr(line,p+1);\n End;\n Else Do;\n a(i,j)=line;\n Leave loop;\n End;\n End;\n n=j;\n End;\n\n End;\n", "language": "PL-I" }, { "code": "## Create a CSV file\n@\"\nC1,C2,C3,C4,C5\n1,5,9,13,17\n2,6,10,14,18\n3,7,11,15,19\n4,8,12,16,20\n\"@ -split \"`r`n\" | Out-File -FilePath .\\Temp.csv -Force\n\n## Import each line of the CSV file into an array of PowerShell objects\n$records = Import-Csv -Path .\\Temp.csv\n\n## Sum the values of the properties of each object\n$sums = $records | ForEach-Object {\n [int]$sum = 0\n foreach ($field in $_.PSObject.Properties.Name)\n {\n $sum += $_.$field\n }\n $sum\n}\n\n## Add a column (Sum) and its value to each object in the array\n$records = for ($i = 0; $i -lt $sums.Count; $i++)\n{\n $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}}\n}\n\n## Export the array of modified objects to the CSV file\n$records | Export-Csv -Path .\\Temp.csv -Force\n\n## Display the object in tabular form\n$records | Format-Table -AutoSize\n", "language": "PowerShell" }, { "code": "test :- augment('test.csv', 'test.out.csv').\n\n% augment( +InFileName, +OutFileName)\naugment(InFile, OutFile) :-\n\topen(OutFile, write, OutStream),\n\t( ( csv_read_file_row(InFile, Row, [line(Line)]),\n\t % Row is of the form row( Item1, Item2, ....).\n\t addrow(Row, Out),\n\t csv_write_stream(OutStream, [Out], []),\n\t fail\n\t )\n\t; close(OutStream)\n\t).\n\n% If the first item in a row is an integer, then append the sum;\n% otherwise append 'SUM':\naddrow( Term, NewTerm ) :-\n\tTerm =.. [F | List],\n\tList = [X|_],\n\t(integer(X) -> sum_list(List, Sum) ; Sum = 'SUM'),\n\tappend(List, [Sum], NewList),\n\tNewTerm =.. [F | NewList].\n", "language": "Prolog" }, { "code": "EnableExplicit\n\n#Separator$ = \",\"\n\nDefine fInput$ = \"input.csv\"; insert path to input file\nDefine fOutput$ = \"output.csv\"; insert path to output file\nDefine header$, row$, field$\nDefine nbColumns, sum, i\n\nIf OpenConsole()\n If Not ReadFile(0, fInput$)\n PrintN(\"Error opening input file\")\n Goto Finish\n EndIf\n\n If Not CreateFile(1, fOutput$)\n PrintN(\"Error creating output file\")\n CloseFile(0)\n Goto Finish\n EndIf\n\n ; Read header row\n header$ = ReadString(0)\n ; Determine number of columns\n nbColumns = CountString(header$, \",\") + 1\n ; Change header row\n header$ + #Separator$ + \"SUM\"\n ; Write to output file\n WriteStringN(1, header$)\n\n ; Read remaining rows, process and write to output file\n While Not Eof(0)\n row$ = ReadString(0)\n sum = 0\n For i = 1 To nbColumns\n field$ = StringField(row$, i, #Separator$)\n sum + Val(field$)\n Next\n row$ + #Separator$ + sum\n WriteStringN(1, row$)\n Wend\n\n CloseFile(0)\n CloseFile(1)\n\n Finish:\n PrintN(\"\")\n PrintN(\"Press any key to close the console\")\n Repeat: Delay(10) : Until Inkey() <> \"\"\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": "import fileinput\n\nchangerow, changecolumn, changevalue = 2, 4, '\"Spam\"'\n\nwith fileinput.input('csv_data_manipulation.csv', inplace=True) as f:\n for line in f:\n if fileinput.filelineno() == changerow:\n fields = line.rstrip().split(',')\n fields[changecolumn-1] = changevalue\n line = ','.join(fields) + '\\n'\n print(line, end='')\n", "language": "Python" }, { "code": "import csv\nfrom pathlib import Path\nfrom tempfile import NamedTemporaryFile\n\nfilepath = Path('data.csv')\ntemp_file = NamedTemporaryFile('w',\n newline='',\n delete=False)\n\nwith filepath.open() as csv_file, temp_file:\n reader = csv.reader(csv_file)\n writer = csv.writer(temp_file)\n\n header = next(reader)\n writer.writerow(header + ['SUM'])\n\n for row in reader:\n row_sum = sum(map(int, row))\n writer.writerow(row + [row_sum])\n\ntemp_file_path = Path(temp_file.name)\ntemp_file_path.replace(filepath)\n", "language": "Python" }, { "code": "import pandas as pd\n\nfilepath = 'data.csv'\n\ndf = pd.read_csv(filepath)\nrows_sums = df.sum(axis=1)\ndf['SUM'] = rows_sums\ndf.to_csv(filepath, index=False)\n", "language": "Python" }, { "code": "t:(\"IIIII\";enlist \",\")0: `:input.csv / Read CSV file input.csv into table t\nt:update SUM:sum value flip t from t / Add SUM column to t\n`:output.csv 0: csv 0: t / Write updated table as CSV to output.csv\n", "language": "Q" }, { "code": "df <- read.csv(textConnection(\n\"C1,C2,C3,C4,C5\n1,5,9,13,17\n2,6,10,14,18\n3,7,11,15,19\n4,8,12,16,20\"))\n\ndf$sum <- rowSums(df)\nwrite.csv(df,row.names = FALSE)\n", "language": "R" }, { "code": " write.csv(df, file = \"foo.csv\",row.names = FALSE)\n", "language": "R" }, { "code": "#lang racket\n(require (planet neil/csv:1:=7) net/url)\n\n(define make-reader\n (make-csv-reader-maker\n '((separator-chars #\\,)\n (strip-leading-whitespace? . #t)\n (strip-trailing-whitespace? . #t))))\n\n(define (all-rows port)\n (define read-row (make-reader port))\n (define head (append (read-row) '(\"SUM\")))\n (define rows (for/list ([row (in-producer read-row '())])\n (define xs (map string->number row))\n (append row (list (~a (apply + xs))))))\n (define (->string row) (string-join row \",\" #:after-last \"\\n\"))\n (string-append* (map ->string (cons head rows))))\n", "language": "Racket" }, { "code": "(define csv-file\n \"C1, C2, C3, C4, C5\n 1, 5, 9, 13, 17\n 2, 6, 10, 14, 18\n 3, 7, 11, 15, 19\n 4, 8, 12, 16, 20\")\n\n(display (all-rows (open-input-string csv-file)))\n", "language": "Racket" }, { "code": "my $csvfile = './whatever.csv';\nmy $fh = open($csvfile, :r);\nmy @header = $fh.get.split(',');\nmy @csv = map {[.split(',')]>>.Num}, $fh.lines;\nclose $fh;\n\nmy $out = open($csvfile, :w);\n$out.say((@header,'SUM').join(','));\n$out.say((@$_, [+] @$_).join(',')) for @csv;\nclose $out;\n", "language": "Raku" }, { "code": "use Text::CSV;\nmy $csvfile = './whatever.csv';\nmy @csv = Text::CSV.parse-file($csvfile);\n# modify(@csv); # do whatever;\ncsv-write-file( @csv, :file($csvfile) );\n", "language": "Raku" }, { "code": ">>filein: read/lines %file.csv\n>>data: copy []\n>>foreach item filein [append/only data split item \",\"]\n; [[\"C1\" \"C2\" \"C3\" \"C4\" \"C5\"] [\"1\" \"5\" \"9\" \"13\" \"17\"] [\"2\" \"6\" \"10\" \"14\" \"18\"] [\"3\" \"7\" \"11\" \"15\" \"19\"][\"4\" \"8\" \"12\" \"16\" \"20\"]]\n", "language": "Red" }, { "code": ">>forall data [either (index? data) = 1[\n\tappend data/1 \"SUM\"\n][\n\tappend data/1 to string!\n\t(to integer! data/1/1) + (to integer! data/1/2) + (to integer! data/1/3) + (to integer! data/1/4) + (to integer! data/1/5)\n]]\n", "language": "Red" }, { "code": ">>foreach item data [append item/6 \"^/\" repeat c 5 [append item/:c \",\"]]\n>> print data\nC1, C2, C3, C4, C5, SUM\n1, 5, 9, 13, 17, 45\n2, 6, 10, 14, 18, 50\n3, 7, 11, 15, 19, 55\n4, 8, 12, 16, 20, 60\n>>write fileout.csv form data\n", "language": "Red" }, { "code": "/* REXX ***************************************************************\n* extend in.csv to add a column containing the sum of the lines' elems\n* 21.06.2013 Walter Pachl\n**********************************************************************/\ncsv='in.csv'\nDo i=1 By 1 While lines(csv)>0\n l=linein(csv)\n If i=1 Then\n l.i=l',SUM'\n Else Do\n ol=l\n sum=0\n Do While l<>''\n Parse Var l e ',' l\n sum=sum+e\n End\n l.i=ol','sum\n End\n End\nCall lineout csv\n'erase' csv\nDo i=1 To i-1\n Call lineout csv,l.i\n End\n", "language": "REXX" }, { "code": "/*REXX program reads a CSV file & appends a SUM column (which is the sum of all columns)*/\nparse arg iFID . /*obtain optional argument from the CL*/\nif iFID=='' | iFID==\",\" then iFID= 'CSV_SUM.DAT' /*Not specified? Then use the default*/\ncall linein iFID,1,0 /*position the input file to line one.*/\n /* [↑] only needed if pgm is nested. */\n do rec=1 while lines(iFID)\\==0 /*read the input file (all records). */\n x= linein(iFid); y= translate(x, , ',') /*read a rec; change commas to blanks.*/\n $= 0 /*initial the sum to zero. */\n do j=1 for words(y); _= word(y, j) /*get a CSV value. */\n if datatype(_, 'N') then $= $ + _ /*Numeric? Add to $.*/\n else $= 'SUM' /*Not? Append \"SUM\".*/\n end /*j*/\n @.rec = x','$ /*append the sum to the record. */\n end /*rec*/ /*Note: at EOF, REC ≡ # of records+1.*/\nsay rec-1 ' records read from: ' iFID /* [↓] this elides the need for ERASE*/\ncall lineout iFID,@.1,1 /*set file ptr to 1st rec., write hdr.*/\n do k=2 for rec-2 /*process all the records just read. */\n call lineout iFID,@.k /*write the new CSV record (has SUM). */\n end /*k*/ /*stick a fork in it, we're all done.*/\n", "language": "REXX" }, { "code": "# Project : CSV data manipulation\n\nload \"stdlib.ring\"\nfnin = \"input.csv\"\nfnout = \"output.csv\"\nfpin = fopen(fnin,\"r\")\nfpout = fopen(fnout,\"r\")\ncsv = read(fnin)\nnr = 0\ncsvstr = \"\"\n\nwhile not feof(fpin)\n sum = 0\n nr = nr + 1\n line = readline(fpin)\n if nr = 1\n line = substr(line,nl,\"\")\n line = line + \",SUM\"\n csvstr = csvstr + line + windowsnl()\n else\n csvarr = split(line,\",\")\n for n = 1 to len(csvarr)\n sum = sum + csvarr[n]\n next\n line = substr(line,nl,\"\")\n line = line + \",\" + string(sum)\n csvstr = csvstr + line + windowsnl()\n ok\nend\nwrite(fnout,csvstr)\ncsvend = read(fnout)\nfclose(fpin)\nfclose(fpout)\nsee csvend + nl\n", "language": "Ring" }, { "code": "require 'csv'\n# read:\nar = CSV.table(\"test.csv\").to_a #table method assumes headers and converts numbers if possible.\n\n# manipulate:\nar.first << \"SUM\"\nar[1..-1].each{|row| row << row.sum}\n\n# write:\nCSV.open(\"out.csv\", 'w') do |csv|\n ar.each{|line| csv << line}\nend\n", "language": "Ruby" }, { "code": "csv$ = \"C1,C2,C3,C4,C5\n1,5,9,13,17\n2,6,10,14,18\n3,7,11,15,19\n4,8,12,16,20\n\"\n\nprint csv$\ndim csvData$(5,5)\n\nfor r = 1 to 5\n a$ = word$(csv$,r,chr$(13))\n for c = 1 to 5\n csvData$(r,c) = word$(a$,c,\",\")\n next c\nnext r\n\n[loop]\ninput \"Row to change:\";r\ninput \"Col to change;\";c\nif r > 5 or c > 5 then\n print \"Row \";r;\" or Col \";c;\" is greater than 5\"\n goto [loop]\nend if\ninput \"Change Row \";r;\" Col \";c;\" from \";csvData$(r,c);\" to \";d$\ncsvData$(r,c) = d$\nfor r = 1 to 5\n for c = 1 to 5\n print cma$;csvData$(r,c);\n cma$ = \",\"\n next c\n cma$ = \"\"\n print\nnext r\n", "language": "Run-BASIC" }, { "code": "use std::error::Error;\nuse std::num::ParseIntError;\nuse csv::{Reader, Writer};\n\nfn main() -> Result<(), Box<dyn Error>> {\n let mut reader = Reader::from_path(\"data.csv\")?;\n let mut writer = Writer::from_path(\"output.csv\")?;\n\n // headers() returns an immutable reference, so clone() before appending\n let mut headers = reader.headers()?.clone();\n headers.push_field(\"SUM\");\n writer.write_record(headers.iter())?;\n\n for row in reader.records() {\n let mut row = row?;\n\n // `sum` needs the type annotation so that `parse::<i64>` knows what error type to return\n let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| {\n Ok(accum + s.parse::<i64>()?)\n });\n\n row.push_field(&sum?.to_string());\n writer.write_record(row.iter())?;\n }\n\n writer.flush()?;\n Ok(())\n}\n", "language": "Rust" }, { "code": "data _null_;\ninfile datalines dlm=\",\" firstobs=2;\nfile \"output.csv\" dlm=\",\";\ninput c1-c5;\nif _n_=1 then put \"C1,C2,C3,C4,C5,Sum\";\ns=sum(of c1-c5);\nput c1-c5 s;\ndatalines;\nC1,C2,C3,C4,C5\n1,5,9,13,17\n2,6,10,14,18\n3,7,11,15,19\n4,8,12,16,20\n;\nrun;\n", "language": "SAS" }, { "code": "import scala.io.Source\n\nobject parseCSV extends App {\n\n val rawData = \"\"\"|C1,C2,C3,C4,C5\n\t\t \t\t |1,5,9,13,17\n\t\t \t\t |2,6,10,14,18\n\t\t \t\t |3,7,11,15,19\n\t\t \t\t |20,21,22,23,24\"\"\".stripMargin\n\n val data = Seq((Source.fromString(rawData).getLines()).map(_.split(\",\")).toSeq: _*)\n\n val output = ((data.take(1).flatMap(x => x) :+ \"SUM\").mkString(\",\") +: // Header line\n data.drop(1).map(_.map(_.toInt)). // Convert per line each array of String to array of integer\n map(cells => (cells, cells.sum)). //Add sum column to assemble a tuple. Part 1 are original numbers, 2 is the sum\n map(part => s\"${part._1.mkString(\",\")},${part._2}\")).mkString(\"\\n\")\n\n println(output)\n /* Outputs:\n\nC1,C2,C3,C4,C5,SUM\n1,5,9,13,17,45\n2,6,10,14,18,50\n3,7,11,15,19,55\n20,21,22,23,24,110\n\n*/\n}\n", "language": "Scala" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst proc: main is func\n local\n var file: input is STD_NULL;\n var array array string: csvData is 0 times 0 times \"\";\n var integer: line is 0;\n begin\n input := open(dir(PROGRAM) & \"/csvDataManipulation.in\", \"r\");\n while hasNext(input) do\n csvData &:= split(getln(input), \",\");\n end while;\n csvData[3][3] := \"X\";\n for key line range csvData do\n writeln(join(csvData[line], \",\"));\n end for;\n end func;\n", "language": "Seed7" }, { "code": "// For test purposes, start by creating (or re-creating) the data file\nput {{\nC1,C2,C3,C4,C5\n1,5,9,13,17\n2,6,10,14,18\n3,7,11,15,19\n4,8,12,16,20\n}} into file \"myData.csv\"\n\n// Read the file as a list of lists (rather than as the default list of property lists)\nput CSVValue(file \"myData.csv\", asLists:Yes) into csvData\n\ninsert \"SUM\" into item 1 of csvData -- add a new column heading\n\n// Go through all of the data rows to add the sum\nrepeat with rowNum= 2 to the number of items in csvData\n\tinsert the sum of item rowNum of csvData into item rowNum of csvData\nend repeat\n\nput csvData -- see the modified data as a list of lists\n\nput CSVFormat of csvData into file \"myData.csv\"\n\nput file \"myData.csv\" -- display the updated file contents\n", "language": "SenseTalk" }, { "code": "# Read\nvar csvfile = %f'data.csv';\nvar fh = csvfile.open_r;\nvar header = fh.line.trim_end.split(',');\nvar csv = fh.lines.map { .trim_end.split(',').map{.to_num} };\nfh.close;\n\n# Write\nvar out = csvfile.open_w;\nout.say([header..., 'SUM'].join(','));\ncsv.each { |row| out.say([row..., row.sum].join(',')) };\nout.close;\n", "language": "Sidef" }, { "code": "var csv = require('Text::CSV').new(\n Hash(eol => \"\\n\")\n);\n\n# Open\nvar csvfile = %f'data.csv';\nvar fh = csvfile.open_r;\n\n# Read\nvar rows = [];\nvar header = csv.getline(fh);\nwhile (var row = csv.getline(fh)) {\n rows.append(row.map{.to_num});\n}\n\n# Process\nheader.append('SUM');\nrows.each { |row| row.append(row.sum) };\n\n# Write\nvar out = csvfile.open_w;\n[header, rows...].each { |row|\n csv.print(out, row);\n};\n", "language": "Sidef" }, { "code": "import delim input.csv, clear\nreplace c5=c3+c4\negen sum=rowtotal(c*)\ndrop if mod(c3,3)==0\nexport delim output.csv, replace\n", "language": "Stata" }, { "code": "package require struct::matrix\npackage require csv\n\nproc addSumColumn {filename {title \"SUM\"}} {\n set m [struct::matrix]\n\n # Load the CSV in\n set f [open $filename]\n csv::read2matrix $f $m \",\" auto\n close $f\n\n # Add the column with the sums\n set sumcol [$m columns]\n $m add column $title\n for {set i 1} {$i < [$m rows]} {incr i} {\n\t# Fill out a dummy value\n\t$m set cell $sumcol $i 0\n\t$m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]]\n }\n\n # Write the CSV out\n set f [open $filename w]\n csv::writematrix $m $f\n close $f\n\n $m destroy\n}\n\naddSumColumn \"example.csv\"\n", "language": "Tcl" }, { "code": "set f [open example.csv r]\nputs \"[gets $f],SUM\"\nwhile { [gets $f row] > 0 } {\n\tputs \"$row,[expr [string map {, +} $row]]\"\n}\nclose $f\n", "language": "Tcl" }, { "code": "$$ MODE DATA\n$$ csv=*\nC1,C2,C3,C4,C5\n1,5,9,13,17\n2,6,10,14,18\n3,7,11,15,19\n4,8,12,16,20\n$$ MODE TUSCRIPT\nLOOP/CLEAR n,line=csv\n IF (n==1) THEN\n line=CONCAT (line,\",SUM\")\n ELSE\n lineadd=EXCHANGE(line,\":,:':\")\n sum=SUM(lineadd)\n line=JOIN(line,\",\",sum)\n ENDIF\n csv=APPEND(csv,line)\nENDLOOP\n", "language": "TUSCRIPT" }, { "code": "@(coll)@{name /[^,]+/}@(end)\n@(collect :vars (value sum))\n@ (bind sum 0)\n@ (coll)@{value /[^,]+/}@(set sum @(+ sum (int-str value)))@(end)\n@(end)\n@(output)\n@ (rep)@name,@(last)SUM@(end)\n@ (repeat)\n@ (rep)@value,@(last)@sum@(end)\n@ (end)\n@(end)\n", "language": "TXR" }, { "code": "cat csv | while read S; do\n [ -z ${S##*C*} ] && echo $S,SUM || echo $S,`echo $S | tr ',' '+' | bc`\ndone\n", "language": "UNIX-Shell" }, { "code": "C1,C2,C3,C4,C5,SUM\n1,5,9,13,17,45\n2,6,10,14,18,50\n3,7,11,15,19,55\n4,8,12,16,20,60\n", "language": "UNIX-Shell" }, { "code": "bash>exec 0<\"$1\" # open the input file on stdin\nexec 1>\"$1.new\" # open an output file on stdout\n{\n read -r header\n echo \"$header,SUM\"\n IFS=,\n while read -r -a numbers; do\n sum=0\n for num in \"${numbers[@]}\"; do\n (( sum += num ))\n done\n\n # can write the above loop as\n # sum=$(( $(IFS=+; echo \"${numbers[*]}\") ))\n\n echo \"${numbers[*]},$sum\"\n done\n} &&\nmv \"$1\" \"$1.bak\" &&\nmv \"$1.new\" \"$1\"\n", "language": "UNIX-Shell" }, { "code": "#\n# csv data manipulation\n#\n\n# declare a string stream to hold lines\ndecl string<> lines\n\n# open the file specified on the command line, halting\n# execution if they didn't enter one. it will be created if\n# it doesn't exist yet\ndecl file f\nif (< (size args) 2)\n out \"error: please specify a csv file\" endl console\n stop\nend if\nf.create args<1>\nf.open args<1>\n\n# read in all lines from the file\nset lines (f.readlines)\n\n# append sum column to header\nset lines<0> (+ lines<0> \",SUM\")\n\n# determine sums and append them\ndecl int i sum\nfor (set i 1) (< i (size lines)) (inc i)\n set sum 0\n for (decl int j) (< j (size (split lines<i> \",\"))) (inc j)\n set sum (int (+ sum (int (split lines<i> \",\")<j>)))\n end for\n set lines<i> (+ lines<i> (+ \",\" sum))\nend for\n\n# delete the file, then create it again\nf.delete args<1>\nf.create args<1>\n\n# output all lines to the file\nfor (set i 0) (< i (size lines)) (inc i)\n out lines<i> endl f\nend for\n", "language": "Ursa" }, { "code": "Sub ReadCSV()\n Workbooks.Open Filename:=\"L:\\a\\input.csv\"\n Range(\"F1\").Value = \"Sum\"\n Range(\"F2:F5\").Formula = \"=SUM(A2:E2)\"\n ActiveWorkbook.SaveAs Filename:=\"L:\\a\\output.csv\", FileFormat:=xlCSV\n ActiveWindow.Close\nEnd Sub\n", "language": "VBA" }, { "code": "'Instatiate FSO.\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n'Open the CSV file for reading. The file is in the same folder as the script and named csv_sample.csv.\nSet objInCSV = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & \"\\csv_sample.csv\",1,False)\n'Set header status to account for the first line as the column headers.\nIsHeader = True\n'Initialize the var for the output string.\nOutTxt = \"\"\n'Read each line of the file.\nDo Until objInCSV.AtEndOfStream\n\tline = objInCSV.ReadLine\n\tIf IsHeader Then\n\t\tOutTxt = OutTxt & line & \",SUM\" & vbCrLf\n\t\tIsHeader = False\n\tElse\n\t\tOutTxt = OutTxt & line & \",\" & AddElements(line) & vbCrLf\n\tEnd If\nLoop\n'Close the file.\nobjInCSV.Close\n'Open the same file for writing.\nSet objOutCSV = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & \"\\csv_sample.csv\",2,True)\n'Write the var OutTxt to the file overwriting existing contents.\nobjOutCSV.Write OutTxt\n'Close the file.\nobjOutCSV.Close\nSet objFSO = Nothing\n\n'Routine to add each element in a row.\nFunction AddElements(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tAddElements = AddElements + CInt(arr(i))\n\tNext\nEnd Function\n", "language": "VBScript" }, { "code": "File_Open(\"input.csv\")\nfor (#1 = 0; #1 < 4; #1++) {\n Goto_Line(#1+2) // line (starting from line 2)\n if (#1) {\n Search(\",\", ADVANCE+COUNT, #1) // column\n }\n #2 = Num_Eval() // #2 = old value\n Del_Char(Chars_Matched) // delete old value\n Num_Ins(#2+100, LEFT+NOCR) // write new value\n}\nFile_Save_As(\"output.csv\", OK+NOMSG)\n", "language": "Vedit-macro-language" }, { "code": "CLOSE DATABASES ALL\nSET SAFETY OFF\nMODIFY FILE file1.csv NOEDIT\n*!* Create a cursor with integer columns\nCREATE CURSOR tmp1 (C1 I, C2 I, C3 I, C4 I, C5 I)\nAPPEND FROM file1.csv TYPE CSV\nSELECT C1, C2, C3, C4, C5, C1+C2+C3+C4+C5 As sum ;\nFROM tmp1 INTO CURSOR tmp2\nCOPY TO file2.csv TYPE CSV\nMODIFY FILE file2.csv NOEDIT IN SCREEN\nSET SAFETY ON\n", "language": "Visual-FoxPro" }, { "code": "import \"io\" for File\n\nvar lines = File.read(\"rc.csv\").split(\"\\n\").map { |w| w.trim() }.toList\n\nvar file = File.create(\"rc.csv\") // overwrite existing file\nfile.writeBytes(lines[0] + \",SUM\\n\")\nfor (line in lines.skip(1)) {\n if (line != \"\") {\n var nums = line.split(\",\").map { |s| Num.fromString(s) }\n var sum = nums.reduce { |acc, n| acc + n }\n file.writeBytes(line + \",%(sum)\\n\")\n }\n}\nfile.close()\n", "language": "Wren" }, { "code": "string 0; \\use zero-terminated strings\ndef LF=$0A, EOF=$1A;\nint Val, Char;\nchar Str(80);\n\nproc InField;\nint I;\n[I:= 0; Val:= 0;\nloop [Char:= ChIn(1);\n if Char=^, or Char=LF or Char=EOF then quit;\n Str(I):= Char;\n I:= I+1;\n if Char>=^0 and Char<=^9 then\n Val:= Val*10 + Char - ^0;\n ];\nStr(I):= 0;\n];\n\nint Sum;\n[loop [InField;\n Text(0, Str);\n if Char = LF then quit;\n ChOut(0, ^,);\n ];\nText(0, \",SUM\");\nCrLf(0);\nloop [Sum:= 0;\n loop [InField;\n if Char = EOF then return;\n if rem(Val/5)=0 then Val:= Val*20;\n IntOut(0, Val);\n Sum:= Sum + Val;\n if Char = LF then quit;\n ChOut(0, ^,);\n ];\n Text(0, \",\");\n IntOut(0, Sum);\n CrLf(0);\n ];\n]\n", "language": "XPL0" }, { "code": "open #1, \"manipy.csv\", \"r\" //existing CSV file separated by spaces, not commas\nopen #2, \"manip2.csv\", \"w\" //new CSV file for writing changed data\n\nline input #1 header$\nheader$ = header$ + \",SUM\"\nprint #2 header$\n\nwhile !eof(1)\n input #1 c1, c2, c3, c4, c5\n sum = c1 + c2 + c3 + c4 + c5\n print #2 c1, c2, c3, c4, c5, sum\nwend\n\nclose #1\nclose #2\nend\n", "language": "Yabasic" }, { "code": "csvFile:=File(\"test.csv\");\nheader:=csvFile.readln().strip(); // remove trailing \"\\n\" and leading white space\nlistOfLines:=csvFile.pump(List,fcn(line){ line.strip().split(\",\").apply(\"toInt\") });\n\nnewFile:=File(\"test2.csv\",\"w\");\nnewFile.writeln(header + \",sum\");\nlistOfLines.pump(newFile.writeln,fcn(ns){ String(ns.concat(\",\"),\",\",ns.sum()) });\nnewFile.close();\n", "language": "Zkl" } ]
CSV-data-manipulation
[ { "code": "---\nfrom: http://rosettacode.org/wiki/CSV_to_HTML_translation\n", "language": "00-META" }, { "code": "Consider a simplified CSV format where all rows are separated by a newline \nand all columns are separated by commas. \n\nNo commas are allowed as field data, but the data may contain \nother characters and character sequences that would \nnormally be &nbsp; ''escaped'' &nbsp; when converted to HTML\n\n\n;Task:\nCreate a function that takes a string representation of the CSV data\nand returns a text string of an HTML table representing the CSV data. \n\nUse the following data as the CSV text to convert, and show your output.\n: Character,Speech\n: The multitude,The messiah! Show us the messiah!\n: Brians mother,<nowiki><angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry></nowiki>\n: The multitude,Who are you?\n: Brians mother,I'm his mother; that's who!\n: The multitude,Behold his mother! Behold his mother!\n\n\n;Extra credit:\n''Optionally'' allow special formatting for the first row of the table as if it is the tables header row \n(via <nowiki><thead></nowiki> preferably; CSS if you must).\n<br><br>\n\n", "language": "00-TASK" }, { "code": "V input_csv = ‘Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!’\n\nprint(\"<table>\\n<tr><td>\", end' ‘’)\n\nL(c) input_csv\n print(S c {\n \"\\n\"{\"</td></tr>\\n<tr><td>\"}\n ‘,’ {‘</td><td>’}\n ‘<’ {‘&lt;’}\n ‘>’ {‘&gt;’}\n ‘&’ {‘&amp;’}\n E {c}\n }, end' ‘’)\n\nprint(\"</td></tr>\\n</table>\")\n", "language": "11l" }, { "code": "<table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "11l" }, { "code": "with Ada.Strings.Fixed;\nwith Ada.Text_IO;\nwith Templates_Parser;\n\nprocedure Csv2Html is\n use type Templates_Parser.Vector_Tag;\n\n Chars : Templates_Parser.Vector_Tag;\n Speeches : Templates_Parser.Vector_Tag;\n\n CSV_File : Ada.Text_IO.File_Type;\nbegin\n -- read the csv data\n Ada.Text_IO.Open (File => CSV_File,\n Mode => Ada.Text_IO.In_File,\n Name => \"data.csv\");\n\n -- fill the tags\n while not Ada.Text_IO.End_Of_File (CSV_File) loop\n declare\n Whole_Line : String := Ada.Text_IO.Get_Line (CSV_File);\n Comma_Pos : Natural := Ada.Strings.Fixed.Index (Whole_Line, \",\");\n begin\n Chars := Chars & Whole_Line (Whole_Line'First .. Comma_Pos - 1);\n Speeches := Speeches & Whole_Line (Comma_Pos + 1 .. Whole_Line'Last);\n end;\n end loop;\n\n Ada.Text_IO.Close (CSV_File);\n\n -- build translation table and output html\n declare\n Translations : constant Templates_Parser.Translate_Table :=\n (1 => Templates_Parser.Assoc (\"CHAR\", Chars),\n 2 => Templates_Parser.Assoc (\"SPEECH\", Speeches));\n begin\n Ada.Text_IO.Put_Line\n (Templates_Parser.Parse (\"table.tmplt\", Translations));\n end;\nend Csv2Html;\n", "language": "Ada" }, { "code": "<table>\n@@TABLE@@\n <tr>\n <td>@_WEB_ESCAPE:CHAR_@</td>\n <td>@_WEB_ESCAPE:SPEECH_@</td>\n </tr>\n@@END_TABLE@@\n</table>\n", "language": "Ada" }, { "code": "<table>\n <tr>\n <td>Character</td>\n <td>Speech</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Who are you?</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>I'm his mother; that's who!</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n</table>\n", "language": "Ada" }, { "code": "#!/usr/local/bin/a68g --script #\n\n[6]STRING rows := []STRING(\n \"Character,Speech\",\n \"The multitude,The messiah! Show us the messiah!\",\n \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\",\n \"The multitude,Who are you?\",\n \"Brians mother,I'm his mother; that's who!\",\n \"The multitude,Behold his mother! Behold his mother!\"\n);\n\n[max abs char]STRING encoded; FOR i TO UPB encoded DO encoded[i]:=REPR i OD;\n# encoded[ABS\"\"\"\"] := \"&quot;\"; optional #\n encoded[ABS \"&\"] := \"&amp;\";\n encoded[ABS \"<\"] := \"&lt;\";\n# encoded[ABS \">\"] := \"&gt;\"; optional #\n\nOP ENCODE = (STRING s)STRING: (\n STRING out := \"\";\n FOR i TO UPB s DO out+:= encoded[ABS s[i]] OD;\n out\n);\n\nPROC head = (STRING title)VOID: (\n printf((\n $\"<HEAD>\"l$,\n $\"<TITLE>\"g\"</TITLE>\"l$, title,\n $\"<STYLE type=\"\"text/css\"\">\"l$,\n $\"TD {background-color:#ddddff; }\"l$,\n $\"thead TD {background-color:#ddffdd; text-align:center; }\"l$,\n $\"</STYLE>\"l$,\n $\"</HEAD>\"l$\n ))\n);\n\n# define HTML tags using Algol68's \"reverent\" block structuring #\nPROC html = VOID: print((\"<HTML>\", new line)),\n body = VOID: print((\"<BODY>\", new line)),\n table = VOID: print((\"<TABLE>\", new line)),\n table row = VOID: print((\"<TR>\")),\n th = (STRING s)VOID: printf(($\"<TH>\"g\"</TH>\"$, s)),\n td = (STRING s)VOID: printf(($\"<TD>\"g\"</TD>\"$, s)),\n elbat row = VOID: print((\"</TR>\", new line)),\n elbat = VOID: print((\"</TABLE>\", new line)),\n ydob = VOID: print((\"</BODY>\", new line)),\n lmth = VOID: print((\"</HTML>\", new line));\n\nFILE row input; STRING row; CHAR ifs = \",\";\nassociate(row input, row); make term(row input, ifs);\n\nhtml;\n head(\"CSV to HTML translation - Extra Credit\");\n body;\n table;\n FOR nr TO UPB rows DO\n row := rows[nr];\n table row;\n on logical file end(row input, (REF FILE row input)BOOL: row end);\n FOR nf DO\n STRING field; get(row input,field);\n (nr=1|th|td)(ENCODE field);\n get(row input, space)\n OD;\n row end: reset(row input);\n elbat row\n OD;\n elbat;\n ydob;\nlmth\n", "language": "ALGOL-68" }, { "code": "<HTML>\n<HEAD>\n<TITLE>CSV to HTML translation - Extra Credit</TITLE>\n<STYLE type=\"text/css\">\nTD {background-color:#ddddff; }\nthead TD {background-color:#ddffdd; text-align:center; }\n</STYLE>\n</HEAD>\n<BODY>\n<TABLE>\n<TR><TH>Character</TH><TH>Speech</TH></TR>\n<TR><TD>The multitude</TD><TD>The messiah! Show us the messiah!</TD></TR>\n<TR><TD>Brians mother</TD><TD>&lt;angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry></TD></TR>\n<TR><TD>The multitude</TD><TD>Who are you?</TD></TR>\n<TR><TD>Brians mother</TD><TD>I'm his mother; that's who!</TD></TR>\n<TR><TD>The multitude</TD><TD>Behold his mother! Behold his mother!</TD></TR>\n</TABLE>\n</BODY>\n</HTML>\n", "language": "ALGOL-68" }, { "code": "// Create an HTML Table from comma seperated values\n// Nigel Galloway - June 2nd., 2013\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow : field ',' field '\\r'? '\\n';\nfield : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField : ~[,\\n\\r]+;\n", "language": "ANTLR" }, { "code": " 100 DATA \"Character,Speech\"\n 110 DATA \"The multitude,The messiah! Show us the messiah!\"\n 120 DATA \"Brian's mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\"\n 130 DATA \"The multitude,Who are you?\"\n 140 DATA \"Brian's mother,I'm his mother; that's who!\"\n 150 DATA \"The multitude,Behold his mother! Behold his mother!\"\n 160 DATA\n 170 LET M$ = CHR$ (13)\n 180 LET Q$ = CHR$ (34)\n 190 LET TRUE = NOT FALSE\n 200 LET HEADER = TRUE\n 210 DIM C(255),H$(4,1)\n 220 LET H$(1,0) = \"</TD><TD>\"\n 230 LET H$(2,0) = \"&LT;\"\n 240 LET H$(3,0) = \"&GT;\"\n 250 LET H$(4,0) = \"&AMP;\"\n 260 FOR I = 1 TO 4\n 270 LET C( ASC ( MID$ (\",<>&\",I,1))) = I\n 280 LET H$(I,HEADER) = H$(I,0)\n 290 NEXT I\n 300 LET H$(1,1) = \"</TH><TH>\"\n 310 PRINT \"<!DOCTYPE HTML>\"M$\"<HTML>\"M$\"<HEAD>\"M$\"</HEAD>\"M$\"<BODY>\"\n 320 PRINT \"<TABLE BORDER=\"Q$\"1\"Q$\" CELLPADDING=\"Q$\"10\"Q$\" CELLSPACING=\"Q$\"0\"Q$\">\"\n 330 READ CSV$\n 340 FOR Q = 0 TO 1 STEP 0\n 350 PRINT \"<TR><T\" MID$ (\"DH\",1 + HEADER,1)\">\";\n 360 FOR I = 1 TO LEN (CSV$)\n 370 LET C$ = MID$ (CSV$,I,1)\n 380 LET H = C( ASC (C$))\n 390 PRINT H$(H,HEADER) MID$ (C$,1,H = 0);\n 400 NEXT I\n 410 PRINT \"</T\" MID$ (\"DH\",1 + HEADER,1)\"></TR>\"\n 420 LET HEADER = FALSE\n 430 READ CSV$\n 440 LET Q = CSV$ = \"\"\n 450 NEXT Q\n 460 PRINT \"</TABLE>\"M$\"</BODY>\"M$\"</HTML>\"\n", "language": "Applesoft-BASIC" }, { "code": "in: {\n Character,Speech\n The multitude,The messiah! Show us the messiah!\n Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n The multitude,Who are you?\n Brians mother,I'm his mother; that's who!\n The multitude,Behold his mother! Behold his mother!\n}\n\ntable: function [content]\n -> join @[\"<table>\" join content \"</table>\"]\n\nrow: function [data]\n -> join @[\n \"<tr><td>\" escape.xml first data \"</td>\"\n \"<td>\" escape.xml last data \"</td></tr>\"\n ]\n\nprint table map read.csv in => row\n", "language": "Arturo" }, { "code": "CSVData =\n(\nCharacter,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\n)\nTableData := \"<table>\"\nLoop Parse, CSVData,`n\n{\n TableData .= \"`n <tr>\"\n Loop Parse, A_LoopField, CSV\n TableData .= \"<td>\" HTMLEncode(A_LoopField) \"</td>\"\n TableData .= \"</tr>\"\n}\nTableData .= \"`n</table>\"\nHTMLEncode(str){\n static rep := \"&amp;<lt;>gt;\"\"quot\"\n Loop Parse, rep,;\n StringReplace, str, str, % SubStr(A_LoopField, 1, 1), % \"&\" . SubStr(A_LoopField, 2) . \";\", All\n return str\n}\nMsgBox % clipboard := TableData\n", "language": "AutoHotkey" }, { "code": "\tLocal $ascarray[4] = [34,38,60,62]\n\t$String = \"Character,Speech\" & @CRLF\n\t$String &= \"The multitude,The messiah! Show us the messiah!\" & @CRLF\n\t$String &= \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\" & @CRLF\n\t$String &= \"The multitude,Who are you?\" & @CRLF\n\t$String &= \"Brians mother,I'm his mother; that's who!\" & @CRLF\n\t$String &= \"The multitude,Behold his mother! Behold his mother!\"\n\tFor $i = 0 To UBound($ascarray) -1\n\t\t$String = Stringreplace($String, chr($ascarray[$i]), \"&#\"&$ascarray[$i]&\";\")\n\tNext\n\t$newstring = \"<table>\" & @CRLF\n\t$crlfsplit = StringSplit($String, @CRLF, 1)\n\tFor $i = 1 To $crlfsplit[0]\n\t\tIf $i = 1 Then $newstring &= \"<thead>\" & @CRLF\n\t\t$newstring &= \"<tr>\" & @CRLF\n\t\t$komsplit = StringSplit($crlfsplit[$i], \",\")\n\t\tFor $k = 1 To $komsplit[0]\n\t\t\tIf $i = 1 Then\n\t\t\t\t$newstring &= \"<th>\" &$komsplit[$k] & \"</th>\" & @CRLF\n\t\t\tElse\n\t\t\t\t$newstring &= \"<td>\" &$komsplit[$k] & \"</td>\" & @CRLF\n\t\t\tEndIf\n\t\tNext\n\t\t$newstring &= \"</tr>\" & @CRLF\n\t\tIf $i = 1 Then $newstring &= \"</thead>\" & @CRLF\n\tNext\n\t$newstring &= \"</table>\"\n\tConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $newstring = ' & $newstring & @crlf & '>Error code: ' & @error & @crlf) ;### Debug Console\n", "language": "AutoIt" }, { "code": "#!/usr/bin/awk -f\nBEGIN {\n FS=\",\"\n print \"<table>\"\n}\n\n{\n gsub(/</, \"\\\\&lt;\")\n gsub(/>/, \"\\\\&gt;\")\n gsub(/&/, \"\\\\&gt;\")\n print \"\\t<tr>\"\n for(f = 1; f <= NF; f++) {\n if(NR == 1 && header) {\n printf \"\\t\\t<th>%s</th>\\n\", $f\n }\n else printf \"\\t\\t<td>%s</td>\\n\", $f\n }\n print \"\\t</tr>\"\n}\n\nEND {\n print \"</table>\"\n}\n", "language": "AWK" }, { "code": "<table>\n <tr>\n <td>Character</td>\n <td>Speech</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>&gt;lt;angry&gt;gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&gt;lt;/angry&gt;gt;</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Who are you?</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>I'm his mother; that's who!</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n</table>\n", "language": "AWK" }, { "code": "<table>\n <tr>\n <th>Character</th>\n <th>Speech</th>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>&gt;lt;angry&gt;gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&gt;lt;/angry&gt;gt;</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Who are you?</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>I'm his mother; that's who!</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n</table>\n", "language": "AWK" }, { "code": "::Batch Files are terrifying when it comes to string processing.\n::But well, a decent implementation!\n@echo off\n\nREM Below is the CSV data to be converted.\nREM Exactly three colons must be put before the actual line.\n\n:::Character,Speech\n:::The multitude,The messiah! Show us the messiah!\n:::Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n:::The multitude,Who are you?\n:::Brians mother,I'm his mother; that's who!\n:::The multitude,Behold his mother! Behold his mother!\n\nsetlocal disabledelayedexpansion\necho ^<table^>\nfor /f \"delims=\" %%A in ('findstr \"^:::\" \"%~f0\"') do (\n set \"var=%%A\"\n setlocal enabledelayedexpansion\n REM The next command removes the three colons...\n set \"var=!var:~3!\"\n\n REM The following commands to the substitions per line...\n set \"var=!var:&=&amp;!\"\n set \"var=!var:<=&lt;!\"\n set \"var=!var:>=&gt;!\"\n set \"var=!var:,=</td><td>!\"\n\n echo ^<tr^>^<td^>!var!^</td^>^</tr^>\n endlocal\n)\necho ^</table^>\n", "language": "Batch-File" }, { "code": "<table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "Batch-File" }, { "code": " DATA \"Character,Speech\"\n DATA \"The multitude,The messiah! Show us the messiah!\"\n DATA \"Brian's mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\"\n DATA \"The multitude,Who are you?\"\n DATA \"Brian's mother,I'm his mother; that's who!\"\n DATA \"The multitude,Behold his mother! Behold his mother!\"\n DATA \"***\"\n\n *SPOOL CSVtoHTML.htm\n PRINT \"<HTML>\"\n PRINT \"<HEAD>\"\n PRINT \"</HEAD>\"\n PRINT \"<BODY>\"\n PRINT \"<table border=1 cellpadding =10 cellspacing=0>\"\n\n header% = TRUE\n REPEAT\n READ csv$\n IF csv$ = \"***\" THEN EXIT REPEAT\n\n IF header% PRINT \"<tr><th>\"; ELSE PRINT \"<tr><td>\";\n FOR i% = 1 TO LEN(csv$)\n c$ = MID$(csv$, i%, 1)\n CASE c$ OF\n WHEN \",\": IF header% PRINT \"</th><th>\"; ELSE PRINT \"</td><td>\";\n WHEN \"<\": PRINT \"&lt;\";\n WHEN \">\": PRINT \"&gt;\";\n WHEN \"&\": PRINT \"&amp;\";\n OTHERWISE: PRINT c$;\n ENDCASE\n NEXT i%\n IF header% PRINT \"</th></tr>\" ELSE PRINT \"</td></tr>\"\n\n header% = FALSE\n UNTIL FALSE\n\n PRINT \"</table>\"\n PRINT \"</BODY>\"\n PRINT \"</HTML>\"\n *spool\n\n SYS \"ShellExecute\", @hwnd%, 0, \"CSVtoHTML.htm\", 0, 0, 1\n", "language": "BBC-BASIC" }, { "code": "<v_>#!,#:< \"<table>\" \\0 +55\n v >0>::65*1+`\\\"~\"`!*#v_4-5v >\nv>#^~^<v\"<tr><td>\" < \\v-1/<>\">elb\"\n<^ >:#,_$10 |!:<>\\#v_ vv\"ta\"\nv-\",\":\\-\"&\":\\-\"<\":\\<>5#05#<v+ >\"/\"v\n>#v_$$$0\">dt<>dt/<\"vv\"tr>\"+<5 v\"<\"<\n>^>\\#v_$$0\";pma&\" v>\"/<>d\"v5 v , <\n$ > \\#v_$0\";tl&\"v v\"</t\"<0 > : |\n^_>#!,#:<>#<0#<\\#<<< >:#,_$#^_v@ $<\n", "language": "Befunge" }, { "code": "<table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry></td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "Befunge" }, { "code": "( ( CSVtoHTML\n = p q Character Speech swor rows row\n . 0:?p\n & :?swor:?rows\n & ( @( !arg\n : ?\n ( [!p ?Character \",\" ?Speech \\n [?q ?\n & !q:?p\n & (tr.,(th.,!Character) (th.,!Speech))\n !swor\n : ?swor\n & ~\n )\n )\n | whl\n ' ( !swor:%?row %?swor\n & !row \\n !rows:?rows\n )\n & toML\n $ (table.,(thead.,!swor) \\n (tbody.,!rows))\n )\n )\n& CSVtoHTML\n $ \"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\n\"\n)\n", "language": "Bracmat" }, { "code": "<table><thead><tr><th>Character</th><th>Speech</th></tr></thead>\n<tbody><tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</tbody></table>\n", "language": "Bracmat" }, { "code": "( ( Csv2Html\n =\n . toML\n $ ( table\n .\n , vap\n $ ( (\n = .tr.,vap$((=.td.,!arg).!arg.\",\")\n )\n . !arg\n . \\n\n )\n )\n )\n& Csv2Html\n $ \"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\n\"\n)\n", "language": "Bracmat" }, { "code": "( ( Csv2Html\n =\n . toML\n $ ( table\n .\n , vap\n $ ( (=..vap$((=.,!arg).!arg.\",\"))\n . !arg\n . \\n\n )\n : (.%?header) ?body\n & ( thead\n .\n , (tr.,map$((=.th.!arg).!header))\n \\n\n )\n ( tbody\n .\n , map\n $ ( (\n =\n . !arg:(.?arg)\n & (tr.,map$((=.td.!arg).!arg))\n \\n\n )\n . !body\n )\n )\n )\n )\n& Csv2Html\n $ \"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\n\"\n)\n", "language": "Bracmat" }, { "code": "<table><thead><tr><th>Character</th><th>Speech</th></tr>\n</thead><tbody><tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n<tr><td /></tr>\n</tbody></table>\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n\nconst char *input =\n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',': printf(\"</td><td>\"); break;\n\t\tcase '<': printf(\"&lt;\"); break;\n\t\tcase '>': printf(\"&gt;\"); break;\n\t\tcase '&': printf(\"&amp;\"); break;\n\t\tdefault: putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "<table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "C" }, { "code": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n std::string text = \"Character,Speech\\n\"\n \"The multitude,The messiah! Show us the messiah!\\n\"\n\t\t\t \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\"\n\t \"The multitude,Who are you?\\n\"\n\t\t \"Brians mother,I'm his mother; that's who!\\n\"\n\t\t \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n std::cout << csvToHTML( text ) ;\n return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n //the order of the regexes and the replacements is decisive!\n std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \" <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\" } ;\n boost::regex e1( regexes[ 0 ] ) ;\n std::string tabletext = boost::regex_replace( csvtext , e1 ,\n replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n for ( int i = 1 ; i < 5 ; i++ ) {\n e1.assign( regexes[ i ] ) ;\n tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n }\n tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n tabletext.append( \"</TABLE>\\n\" ) ;\n return tabletext ;\n}\n", "language": "C++" }, { "code": "<TABLE>\n <TR><TD>Character</TD><TD>Speech</TD></TR>\n <TR><TD>The multitude</TD><TD>The messiah! Show us the messiah!</TD></TR>\n <TR><TD>Brians mother</TD><TD>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</TD></TR>\n <TR><TD>The multitude</TD><TD>Who are you?</TD></TR>\n <TR><TD>Brians mother</TD><TD>I'm his mother; that's who!</TD></TR>\n <TR><TD>The multitude</TD><TD>Behold his mother! Behold his mother!</TD></TR>\n</TABLE>\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net;\n\n class Program\n {\n private static string ConvertCsvToHtmlTable(string csvText)\n {\n //split the CSV, assume no commas or line breaks in text\n List<List<string>> splitString = new List<List<string>>();\n List<string> lineSplit = csvText.Split('\\n').ToList();\n foreach (string line in lineSplit)\n {\n splitString.Add(line.Split(',').ToList());\n }\n\n //encode text safely, and create table\n string tableResult = \"<table>\";\n foreach(List<string> splitLine in splitString)\n {\n tableResult += \"<tr>\";\n foreach(string splitText in splitLine)\n {\n tableResult += \"<td>\" + WebUtility.HtmlEncode(splitText) + \"</td>\";\n }\n tableResult += \"</tr>\";\n }\n tableResult += \"</table>\";\n return tableResult;\n }\n }\n", "language": "C-sharp" }, { "code": "<table><tr><td>Character</td><td>Speech</td></tr><tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr><tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He&#39;s not the messiah; he&#39;s a very naughty boy! Now go away!&lt;/angry&gt;</td></tr><tr><td>The multitude</td><td>Who are you?</td></tr><tr><td>Brians mother</td><td>I&#39;m his mother; that&#39;s who!</td></tr><tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr></table>\n", "language": "C-sharp" }, { "code": "using System;\nusing System.Linq;\nusing System.Net;\n\nnamespace CsvToHtml\n{\n class Program\n {\n static void Main(string[] args)\n {\n string csv =\n @\"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\";\n\n Console.Write(ConvertCsvToHtmlTable(csv, true));\n }\n\n private static string ConvertCsvToHtmlTable(string csvText, bool formatHeaders)\n {\n var rows =\n (from text in csvText.Split(new[] { '\\r', '\\n' }, StringSplitOptions.RemoveEmptyEntries) /* Split the string by newline,\n * removing any empty rows. */\n select text.Split(',')).ToArray(); // Split each row by comma.\n\n string output = \"<table>\"; // Initialize the output with the value of \"<table>\".\n\n for (int index = 0; index < rows.Length; index++) // Iterate through each row.\n {\n var row = rows[index];\n var tag = (index == 0 && formatHeaders) ? \"th\" : \"td\"; /* Check if this is the first row, and if to format headers.\n * If so, then set the tags as table headers.\n * Otherwise, set the tags as table data. */\n\n output += \"\\r\\n\\t<tr>\"; // Add table row tag to output string.\n\n // Add escaped cell data with proper tags to output string for each cell in row.\n output = row.Aggregate(output,\n (current, cell) =>\n current +\n string.Format(\"\\r\\n\\t\\t<{0}>{1}</{0}>\", tag, WebUtility.HtmlEncode(cell)));\n\n output += \"\\r\\n\\t</tr>\"; // Add closing table row tag to output string.\n }\n\n output += \"\\r\\n</table>\"; // Add closing table tag to output string.\n\n return output;\n }\n }\n}\n", "language": "C-sharp" }, { "code": "<table>\n\t<tr>\n\t\t<th>Character</th>\n\t\t<th>Speech</th>\n\t</tr>\n\t<tr>\n\t\t<td>The multitude</td>\n\t\t<td>The messiah! Show us the messiah!</td>\n\t</tr>\n\t<tr>\n\t\t<td>Brians mother</td>\n\t\t<td>&lt;angry&gt;Now you listen here! He&#39;s not the messiah; he&#39;s a very naughty boy! Now go away!&lt;/angry&gt;</td>\n\t</tr>\n\t<tr>\n\t\t<td>The multitude</td>\n\t\t<td>Who are you?</td>\n\t</tr>\n\t<tr>\n\t\t<td>Brians mother</td>\n\t\t<td>I&#39;m his mother; that&#39;s who!</td>\n\t</tr>\n\t<tr>\n\t\t<td>The multitude</td>\n\t\t<td>Behold his mother! Behold his mother!</td>\n\t</tr>\n</table>\n", "language": "C-sharp" }, { "code": "Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\n", "language": "Clojure" }, { "code": "(require 'clojure.string)\n\n(def escapes\n {\\< \"&lt;\", \\> \"&gt;\", \\& \"&amp;\"})\n\n(defn escape\n [content]\n (clojure.string/escape content escapes))\n\n(defn tr\n [cells]\n (format \"<tr>%s</tr>\"\n (apply str (map #(str \"<td>\" (escape %) \"</td>\") cells))))\n\n;; turn a seq of seq of cells into a string.\n(defn to-html\n [tbl]\n (format \"<table><tbody>%s</tbody></thead>\"\n (apply str (map tr tbl))))\n\n;; Read from a string to a seq of seq of cells.\n(defn from-csv\n [text]\n (map #(clojure.string/split % #\",\")\n (clojure.string/split-lines text)))\n\n(defn -main\n []\n (let [lines (line-seq (java.io.BufferedReader. *in*))\n tbl (map #(clojure.string/split % #\",\") lines)]\n (println (to-html tbl)))\n", "language": "Clojure" }, { "code": "<table><tbody><tr><td>Character</td><td>Speech</td></tr><tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr><tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr><tr><td>The multitude</td><td>Who are you?</td></tr><tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr><tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr></tbody></thead>\n", "language": "Clojure" }, { "code": "String::__defineGetter__ 'escaped', () ->\n\tthis.replace(/&/g, '&amp;')\n\t .replace(/</g, '&lt;')\n\t .replace(/>/g, '&gt;')\n\t .replace(/\"/g, '&quot;') // rosettacode doesn't like \"\n\ntext = '''\nCharacter,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\n'''\n\nlines = (line.split ',' for line in text.split /[\\n\\r]+/g)\n\nheader = lines.shift()\n\nconsole.log \"\"\"\n<table cellspacing=\"0\">\n\t<thead>\n\t\t<th scope=\"col\">#{header[0]}</th>\n\t\t<th scope=\"col\">#{header[1]}</th>\n\t</thead>\n\t<tbody>\n\"\"\"\n\nfor line in lines\n\t[character, speech] = line\n\tconsole.log \"\"\"\n\t\t<th scope=\"row\">#{character}</th>\n\t\t<td>#{speech.escaped}</td>\n\t\"\"\"\n\nconsole.log \"\"\"\n\t</tbody>\n</table>\n\t\"\"\"\n", "language": "CoffeeScript" }, { "code": "<table cellspacing=\"0\">\n <thead>\n <th scope=\"col\">Character</th>\n <th scope=\"col\">Speech</th>\n </thead>\n <tbody>\n <th scope=\"row\">The multitude</th>\n <td>The messiah! Show us the messiah!</td>\n <th scope=\"row\">Brians mother</th>\n <td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td>\n <th scope=\"row\">The multitude</th>\n <td>Who are you?</td>\n <th scope=\"row\">Brians mother</th>\n <td>I'm his mother; that's who!</td>\n <th scope=\"row\">The multitude</th>\n <td>Behold his mother! Behold his mother!</td>\n </tbody>\n</table>\n", "language": "CoffeeScript" }, { "code": "(defvar *csv* \"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\")\n\n(defun split-string (string delim-char)\n (let ((result '()))\n (do* ((start 0 (1+ end))\n\t (end (position delim-char string)\n\t (position delim-char string :start start)))\n\t ((not end) (reverse (cons (subseq string start) result)))\n (push (subseq string start end) result))))\n\n;;; HTML escape code modified from:\n;;; http://www.gigamonkeys.com/book/practical-an-html-generation-library-the-interpreter.html\n\n(defun escape-char (char)\n (case char\n (#\\& \"&amp;\")\n (#\\< \"&lt;\")\n (#\\> \"&gt;\")\n (t (format nil \"&#~d;\" (char-code char)))))\n\n(defun escape (in)\n (let ((to-escape \"<>&\"))\n (flet ((needs-escape-p (char) (find char to-escape)))\n (with-output-to-string (out)\n\t(loop for start = 0 then (1+ pos)\n\t for pos = (position-if #'needs-escape-p in :start start)\n\t do (write-sequence in out :start start :end pos)\n\t when pos do (write-sequence (escape-char (char in pos)) out)\n\t while pos)))))\n\n(defun html-row (values headerp)\n (let ((tag (if headerp \"th\" \"td\")))\n (with-output-to-string (out)\n (write-string \"<tr>\" out)\n (dolist (val values)\n\t(format out \"<~A>~A</~A>\" tag (escape val) tag))\n (write-string \"</tr>\" out))))\n\n(defun csv->html (csv)\n (let* ((lines (split-string csv #\\Newline))\n\t (cols (split-string (first lines) #\\,))\n\t (rows (mapcar (lambda (row) (split-string row #\\,)) (rest lines))))\n (with-output-to-string (html)\n (format html \"<table>~C\" #\\Newline)\n (format html \"~C~A~C\" #\\Tab (html-row cols t) #\\Newline)\n (dolist (row rows)\n\t(format html \"~C~A~C\" #\\Tab (html-row row nil) #\\Newline))\n (write-string \"</table>\" html))))\n", "language": "Common-Lisp" }, { "code": "<table>\n\t<tr><th>Character</th><th>Speech</th></tr>\n\t<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n\t<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n\t<tr><td>The multitude</td><td>Who are you?</td></tr>\n\t<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n\t<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "Common-Lisp" }, { "code": "void main() {\n import std.stdio;\n\n immutable input =\n \"Character,Speech\\n\" ~\n \"The multitude,The messiah! Show us the messiah!\\n\" ~\n \"Brians mother,<angry>Now you listen here! He's not the messiah; \" ~\n \"he's a very naughty boy! Now go away!</angry>\\n\" ~\n \"The multitude,Who are you?\\n\" ~\n \"Brians mother,I'm his mother; that's who!\\n\" ~\n \"The multitude,Behold his mother! Behold his mother!\";\n\n \"<html>\\n<head><meta charset=\\\"utf-8\\\"></head>\\n<body>\\n\\n\".write;\n \"<table border=\\\"1\\\" cellpadding=\\\"5\\\" cellspacing=\\\"0\\\">\\n<thead>\\n <tr><td>\".write;\n\n bool theadDone = false;\n\n foreach (immutable c; input) {\n switch(c) {\n case '\\n':\n if (theadDone) {\n \"</td></tr>\\n <tr><td>\".write;\n } else {\n \"</td></tr>\\n</thead>\\n<tbody>\\n <tr><td>\".write;\n theadDone = true;\n }\n break;\n case ',': \"</td><td>\".write; break;\n case '<': \"&lt;\".write; break;\n case '>': \"&gt;\".write; break;\n case '&': \"&amp;\".write; break;\n default: c.write; break;\n }\n }\n\n \"</td></tr>\\n</tbody>\\n</table>\\n\\n</body></html>\".write;\n}\n", "language": "D" }, { "code": "<html>\n<head><meta charset=\"utf-8\"></head>\n<body>\n\n<table border=\"1\" cellpadding=\"5\" cellspacing=\"0\">\n<thead>\n <tr><td>Character</td><td>Speech</td></tr>\n</thead>\n<tbody>\n <tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n <tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n <tr><td>The multitude</td><td>Who are you?</td></tr>\n <tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n <tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</tbody>\n</table>\n\n</body>\n</html>\n", "language": "D" }, { "code": "program csv2html;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils,\n Classes;\n\nconst\n // Carriage Return/Line Feed\n CRLF = #13#10;\n\n // The CSV data\n csvData =\n 'Character,Speech'+CRLF+\n 'The multitude,The messiah! Show us the messiah!'+CRLF+\n 'Brians mother,<angry>Now you listen here! He''s not the messiah; he''s a very naughty boy! Now go away!</angry>'+CRLF+\n 'The multitude,Who are you?'+CRLF+\n 'Brians mother,I''m his mother; that''s who!'+CRLF+\n 'The multitude,Behold his mother! Behold his mother!';\n\n // HTML header\n htmlHead =\n '<!DOCTYPE html'+CRLF+\n 'PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"'+CRLF+\n '\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">'+CRLF+\n '<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">'+CRLF+\n '<head>'+CRLF+\n '<meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-1\" />'+CRLF+\n '<title>CSV-to-HTML Conversion</title>'+CRLF+\n '<style type=\"text/css\">'+CRLF+\n 'body {font-family:verdana,helvetica,sans-serif;font-size:100%}'+CRLF+\n 'table {width:70%;border:0;font-size:80%;margin:auto}'+CRLF+\n 'th,td {padding:4px}'+CRLF+\n 'th {text-align:left;background-color:#eee}'+CRLF+\n 'th.c {width:15%}'+CRLF+\n 'td.c {width:15%}'+CRLF+\n '</style>'+CRLF+\n '</head>'+CRLF+\n '<body>'+CRLF;\n\n // HTML footer\n htmlFoot =\n '</body>'+CRLF+\n '</html>';\n\n{ Function to split a string into a list using a given delimiter }\nprocedure SplitString(S, Delim: string; Rslt: TStrings);\nvar\n i: integer;\n fld: string;\nbegin\n fld := '';\n\n for i := Length(S) downto 1 do\n begin\n if S[i] = Delim then\n begin\n Rslt.Insert(0,fld);\n fld := '';\n end\n else\n fld := S[i]+fld;\n end;\n\n if (fld <> '') then\n Rslt.Insert(0,fld);\nend;\n\n{ Simple CSV parser with option to specify that the first row is a header row }\nprocedure ParseCSV(const csvIn: string; htmlOut: TStrings; FirstRowIsHeader: Boolean = True);\nconst\n rowstart = '<tr><td class=\"c\">';\n rowend = '</td></tr>';\n cellendstart = '</td><td class=\"s\">';\n hcellendstart = '</th><th class=\"s\">';\n hrowstart = '<tr><th class=\"c\">';\n hrowend = '</th></tr>';\nvar\n tmp,pieces: TStrings;\n i: Integer;\nbegin\n // HTML header\n htmlOut.Text := htmlHead + CRLF + CRLF;\n\n // Start the HTML table\n htmlOut.Text := htmlOut.Text + '<table summary=\"csv2table conversion\">' + CRLF;\n\n // Create stringlist\n tmp := TStringList.Create;\n try\n // Assign CSV data to stringlist and fix occurences of '<' and '>'\n tmp.Text := StringReplace(csvIn,'<','&lt;',[rfReplaceAll]);\n tmp.Text := StringReplace(tmp.Text,'>','&gt;',[rfReplaceAll]);\n\n // Create stringlist to hold the parts of the split data\n pieces := TStringList.Create;\n try\n\n // Loop through the CSV rows\n for i := 0 to Pred(tmp.Count) do\n begin\n // Split the current row\n SplitString(tmp[i],',',pieces);\n\n // Check if first row and FirstRowIsHeader flag set\n if (i = 0) and FirstRowIsHeader then\n\n // Render HTML\n htmlOut.Text := htmlOut.Text + hrowstart + pieces[0] + hcellendstart + pieces[1] + hrowend + CRLF\n else\n htmlOut.Text := htmlOut.Text + rowstart + pieces[0] + cellendstart + pieces[1] + rowend + CRLF;\n\n end;\n\n // Finish the HTML table and end the HTML page\n htmlOut.Text := htmlOut.Text + '</table>' + CRLF + htmlFoot;\n\n finally\n pieces.Free;\n end;\n\n finally\n tmp.Free;\n end;\nend;\n\nvar\n HTML: TStrings;\n\nbegin\n // Create stringlist to hold HTML output\n HTML := TStringList.Create;\n try\n Writeln('Basic:');\n Writeln('');\n\n // Load and parse the CSV data\n ParseCSV(csvData,HTML,False);\n\n // Output the HTML to the console\n Writeln(HTML.Text);\n\n // Save the HTML to a file (in application's folder)\n HTML.SaveToFile('csv2html_basic.html');\n\n Writeln('');\n Writeln('=====================================');\n Writeln('');\n\n HTML.Clear;\n\n Writeln('Extra Credit:');\n Writeln('');\n\n // Load and parse the CSV data\n ParseCSV(csvData,HTML,True);\n\n // Output the HTML to the console\n Writeln(HTML.Text);\n\n // Save the HTML to a file (in application's folder)\n HTML.SaveToFile('csv2html_extra.html');\n Writeln('');\n Writeln('=====================================');\n\n finally\n HTML.Free;\n end;\n\n // Keep console window open\n Readln;\nend.\n", "language": "Delphi" }, { "code": "<!DOCTYPE html\nPUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n<head>\n<meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-1\" />\n<title>CSV-to-HTML Conversion</title>\n<style type=\"text/css\">\nbody {font-family:verdana,helvetica,sans-serif;font-size:100%}\ntable {width:70%;border:0;font-size:80%;margin:auto}\nth,td {padding:4px}\nth {text-align:left;background-color:#eee}\nth.c {width:15%}\ntd.c {width:15%}\n</style>\n</head>\n<body>\n\n\n<table summary=\"csv2table conversion\">\n<tr><td class=\"c\">Character</td><td class=\"s\">Speech</td></tr>\n<tr><td class=\"c\">The multitude</td><td class=\"s\">The messiah! Show us the messiah!</td></tr>\n<tr><td class=\"c\">Brians mother</td><td class=\"s\">&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td class=\"c\">The multitude</td><td class=\"s\">Who are you?</td></tr>\n<tr><td class=\"c\">Brians mother</td><td class=\"s\">I'm his mother; that's who!</td></tr>\n<tr><td class=\"c\">The multitude</td><td class=\"s\">Behold his mother! Behold his mother!</td></tr>\n</table>\n</body>\n</html>\n", "language": "Delphi" }, { "code": "<!DOCTYPE html\nPUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n<head>\n<meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-1\" />\n<title>CSV-to-HTML Conversion</title>\n<style type=\"text/css\">\nbody {font-family:verdana,helvetica,sans-serif;font-size:100%}\ntable {width:70%;border:0;font-size:80%;margin:auto}\nth,td {padding:4px}\nth {text-align:left;background-color:#eee}\nth.c {width:15%}\ntd.c {width:15%}\n</style>\n</head>\n<body>\n\n\n<table summary=\"csv2table conversion\">\n<tr><th class=\"c\">Character</th><th class=\"s\">Speech</th></tr>\n<tr><td class=\"c\">The multitude</td><td class=\"s\">The messiah! Show us the messiah!</td></tr>\n<tr><td class=\"c\">Brians mother</td><td class=\"s\">&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td class=\"c\">The multitude</td><td class=\"s\">Who are you?</td></tr>\n<tr><td class=\"c\">Brians mother</td><td class=\"s\">I'm his mother; that's who!</td></tr>\n<tr><td class=\"c\">The multitude</td><td class=\"s\">Behold his mother! Behold his mother!</td></tr>\n</table>\n</body>\n</html>\n", "language": "Delphi" }, { "code": "h$ = \"<table border=1>\\n<tr><th>\"\nrepeat\n s$ = input\n until s$ = \"\"\n write h$\n for c$ in strchars s$\n if c$ = \",\"\n if scnd = 0\n c$ = \"</th><th>\"\n else\n c$ = \"</td><td>\"\n .\n elif c$ = \"<\"\n c$ = \"&lt;\"\n elif c$ = \">\"\n c$ = \"&gt;\"\n elif c$ = \"&\"\n c$ = \"&amp;\"\n .\n write c$\n .\n if scnd = 0\n h$ = \"</th></tr>\\n<tr><td>\"\n scnd = 1\n else\n h$ = \"</td></tr>\\n<tr><td>\"\n .\n.\nprint \"</td></tr>\\n</table>\"\n#\ninput_data\nCharacter,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\n", "language": "EasyLang" }, { "code": ";; CSV -> LISTS\n(define (csv->row line) (string-split line \",\"))\n(define (csv->table csv) (map csv->row (string-split csv \"\\n\")))\n\n;; LISTS->HTML\n(define html 'html)\n(define (emit-tag tag html-proc content )\n\t\t (if (style tag)\n\t\t \t(push html (format \"<%s style='%a'>\" tag (style tag)))\n\t\t \t(push html (format \"<%s>\" tag )))\n\t\t (html-proc content)\n\t\t (push html (format \"</%s> \" tag )))\n\t\t\n;; html procs : 1 tag, 1 proc\n(define (h-raw content)\n\t\t(push html (format \"%s\" content)))\n(define (h-header headers)\n\t\t(for ((h headers)) (emit-tag 'th h-raw h)))\n(define (h-row row)\n\t\t(for ((item row)) (emit-tag 'td h-raw item)))\n(define (h-table table )\n\t(emit-tag 'tr h-header (first table))\n\t(for ((row (rest table))) (emit-tag 'tr h-row row)))\n\t\n(define (html-dump) (string-join (stack->list html) \" \"))\n\t\n;; STYLES\n(style 'td \"text-align:left\")\n(style 'table \"border-spacing: 10px;border:28px ridge orange\") ;; special biblical border\n(style 'th \"color:blue;\")\n", "language": "EchoLisp" }, { "code": ";; changed <angry> to <b> to show that html tags inside text are correctly transmitted.\n(define MontyPython #<<\n Character,Speech\n The multitude,The messiah! Show us the messiah!\n Brians mother,<b>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</b>\n The multitude,Who are you?\n Brians mother,I'm his mother; that's who!\n The multitude,Behold his mother! Behold his mother!\n>>#)\n\n(define (task speech)\n\t(define table (csv->table speech))\n\t(stack html)\n\t(emit-tag 'table h-table table)\n\t(html-dump))\n\t\n(task MontyPython)\n", "language": "EchoLisp" }, { "code": "-module( csv_to_html ).\n\n-export( [table_translation/1, task/0] ).\n\ntable_translation( CSV ) ->\n\t[Headers | Contents] = [string:tokens(X, \",\") || X <- string:tokens( CSV, \"\\n\")],\n\tTable = create_html_table:html_table( [{border, \"1\"}, {cellpadding, \"10\"}], Headers, Contents ),\n\tcreate_html_table:external_format( Table ).\n\ntask() -> table_translation( csv() ).\n\n\n\ncsv() ->\n\"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\".\n", "language": "Erlang" }, { "code": "constant input = \"Character,Speech\\n\" &\n \"The multitude,The messiah! Show us the messiah!\\n\" &\n \"Brians mother,<angry>Now you listen here! He's not the messiah; \" &\n \"he's a very naughty boy! Now go away!</angry>\\n\" &\n \"The multitude,Who are you?\\n\" &\n \"Brians mother,I'm his mother; that's who!\\n\" &\n \"The multitude,Behold his mother! Behold his mother!\"\n\nputs(1,\"<table>\\n<tr><td>\")\nfor i = 1 to length(input) do\n switch input[i] do\n case '\\n' then puts(1,\"</td></tr>\\n<tr><td>\")\n case ',' then puts(1,\"</td><td>\")\n case '<' then puts(1,\"&lt;\")\n case '>' then puts(1,\"&gt;\")\n case '&' then puts(1,\"&amp;\")\n case else puts(1,input[i])\n end switch\nend for\nputs(1,\"</td></tr>\\n</table>\")\n", "language": "Euphoria" }, { "code": "<table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "Euphoria" }, { "code": "open System\nopen System.Text\nopen System.Xml\n\nlet data = \"\"\"\nCharacter,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\n\"\"\"\n\nlet csv =\n Array.map\n (fun (line : string) -> line.Split(','))\n (data.Trim().Split([|'\\n';'\\r'|],StringSplitOptions.RemoveEmptyEntries))\n\n\n[<EntryPoint>]\nlet main argv =\n let style = argv.Length > 0 && argv.[0] = \"-h\"\n Console.OutputEncoding <- UTF8Encoding()\n let xs = XmlWriterSettings()\n xs.Indent <- true // be friendly to humans\n use x = XmlWriter.Create(Console.Out, xs)\n x.WriteStartDocument()\n x.WriteDocType(\"HTML\", null, null, null) // HTML5\n x.WriteStartElement(\"html\")\n x.WriteStartElement(\"head\")\n x.WriteElementString(\"title\", \"Rosettacode - CSV to HTML translation\")\n if style then\n x.WriteStartElement(\"style\"); x.WriteAttributeString(\"type\", \"text/css\")\n x.WriteString(\"\"\"\n table { border-collapse: collapse; }\n td, th { border: 1px solid black; padding: .25em}\n th { background-color: #EEE; }\n tbody th { font-weight: normal; font-size: 85%; }\n \"\"\")\n x.WriteEndElement() // style\n x.WriteEndElement() // head\n x.WriteStartElement(\"body\")\n x.WriteStartElement(\"table\")\n x.WriteStartElement(\"thead\"); x.WriteStartElement(\"tr\")\n for part in csv.[0] do x.WriteElementString(\"th\", part)\n x.WriteEndElement(); x.WriteEndElement() // tr thead\n x.WriteStartElement(\"tbody\")\n for line in csv.[1..] do\n x.WriteStartElement(\"tr\")\n x.WriteElementString(\"th\", line.[0])\n x.WriteElementString(\"td\", line.[1])\n x.WriteEndElement() // tr\n x.Close()\n 0\n", "language": "F-Sharp" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE HTML >\n<html>\n <head>\n <title>Rosettacode - CSV to HTML translation</title>\n <style type=\"text/css\">\n table { border-collapse: collapse; }\n td, th { border: 1px solid black; padding: .25em}\n th { background-color: #EEE; }\n tbody th { font-weight: normal; font-size: 85%; }\n </style>\n </head>\n <body>\n <table>\n <thead>\n <tr>\n <th>Character</th>\n <th>Speech</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>The multitude</th>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr>\n <th>Brians mother</th>\n <td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td>\n </tr>\n <tr>\n <th>The multitude</th>\n <td>Who are you?</td>\n </tr>\n <tr>\n <th>Brians mother</th>\n <td>I'm his mother; that's who!</td>\n </tr>\n <tr>\n <th>The multitude</th>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n </tbody>\n </table>\n </body>\n</html>\n", "language": "F-Sharp" }, { "code": "USING: csv html.streams prettyprint xml.writer ;\n\n\"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\"\n\nstring>csv [ simple-table. ] with-html-writer pprint-xml\n", "language": "Factor" }, { "code": "<table style=\"display: inline-table; border-collapse: collapse;\">\n <tr>\n <td valign=\"top\" style=\"border: 1px solid #cccccc; padding: 2px; \">\n Character\n </td>\n <td valign=\"top\" style=\"border: 1px solid #cccccc; padding: 2px; \">\n Speech\n </td>\n </tr>\n <tr>\n <td valign=\"top\" style=\"border: 1px solid #cccccc; padding: 2px; \">\n The multitude\n </td>\n <td valign=\"top\" style=\"border: 1px solid #cccccc; padding: 2px; \">\n The messiah! Show us the messiah!\n </td>\n </tr>\n <tr>\n <td valign=\"top\" style=\"border: 1px solid #cccccc; padding: 2px; \">\n Brians mother\n </td>\n <td valign=\"top\" style=\"border: 1px solid #cccccc; padding: 2px; \">\n &lt;angry&gt;Now you listen here! He's not the messiah; he's a very\n naughty boy! Now go away!&lt;/angry&gt;\n </td>\n </tr>\n <tr>\n <td valign=\"top\" style=\"border: 1px solid #cccccc; padding: 2px; \">\n The multitude\n </td>\n <td valign=\"top\" style=\"border: 1px solid #cccccc; padding: 2px; \">\n Who are you?\n </td>\n </tr>\n <tr>\n <td valign=\"top\" style=\"border: 1px solid #cccccc; padding: 2px; \">\n Brians mother\n </td>\n <td valign=\"top\" style=\"border: 1px solid #cccccc; padding: 2px; \">\n I'm his mother; that's who!\n </td>\n </tr>\n <tr>\n <td valign=\"top\" style=\"border: 1px solid #cccccc; padding: 2px; \">\n The multitude\n </td>\n <td valign=\"top\" style=\"border: 1px solid #cccccc; padding: 2px; \">\n Behold his mother! Behold his mother!\n </td>\n </tr>\n</table>\n<br/>\n", "language": "Factor" }, { "code": ": BEGIN-COLUMN .\" <td>\" ;\n: END-COLUMN .\" </td>\" ;\n\n: BEGIN-ROW .\" <tr>\" BEGIN-COLUMN ;\n: END-ROW END-COLUMN .\" </tr>\" CR ;\n\n: CSV2HTML\n\t.\" <table>\" CR BEGIN-ROW\n\tBEGIN KEY DUP #EOF <> WHILE\n\t\tCASE\n\t\t\t 10 OF END-ROW BEGIN-ROW ENDOF\n\t\t\t[CHAR] , OF END-COLUMN BEGIN-COLUMN ENDOF\n\t [CHAR] < OF .\" &lt;\" ENDOF\n\t\t\t[CHAR] > OF .\" &gt;\" ENDOF\n\t\t\t[CHAR] & OF .\" &amp;\" ENDOF\n\t\t\tDUP EMIT\n\t\tENDCASE\n\tREPEAT\n\tEND-ROW .\" </table>\" CR\n;\n\nCSV2HTML BYE\n", "language": "Forth" }, { "code": "<table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "Forth" }, { "code": " SUBROUTINE CSVTEXT2HTML(FNAME,HEADED)\t!Does not recognise quoted strings.\nConverts without checking field counts, or noting special characters.\n CHARACTER*(*) FNAME\t!Names the input file.\n LOGICAL HEADED\t\t!Perhaps its first line is to be a heading.\n INTEGER MANY\t\t!How long is a piece of string?\n PARAMETER (MANY=666)\t!This should suffice.\n CHARACTER*(MANY) ALINE\t!A scratchpad for the input.\n INTEGER MARK(0:MANY + 1)\t!Fingers the commas on a line.\n INTEGER I,L,N\t\t!Assistants.\n CHARACTER*2 WOT(2)\t!I don't see why a \"table datum\" could not be for either.\n PARAMETER (WOT = (/\"th\",\"td\"/))\t!A table heding or a table datum\n INTEGER IT\t\t!But, one must select appropriately.\n INTEGER KBD,MSG,IN\t\t!A selection.\n COMMON /IOUNITS/ KBD,MSG,IN\t!The caller thus avoids collisions.\n OPEN(IN,FILE=FNAME,STATUS=\"OLD\",ACTION=\"READ\",ERR=661)\t!Go for the file.\n WRITE (MSG,1)\t\t\t!Start the blather.\n 1 FORMAT (\"<Table border=1>\")\t!By stating that a table follows.\n MARK(0) = 0\t\t!Syncopation for the comma fingers.\n N = 0\t\t\t!No records read.\n\n 10 READ (IN,11,END = 20) L,ALINE(1:MIN(L,MANY))\t!Carefully acquire some text.\n 11 FORMAT (Q,A)\t\t!Q = number of characters yet to read, A = characters.\n N = N + 1\t\t!So, a record has been read.\n IF (L.GT.MANY) THEN\t!Perhaps it is rather long?\n WRITE (MSG,12) N,L,MANY\t!Alas!\n 12 FORMAT (\"Line \",I0,\" has length \",I0,\"! My limit is \",I0)\t!Squawk/\n L = MANY\t\t\t!The limit actually read.\n END IF\t\t\t!So much for paranoia.\n IF (N.EQ.1 .AND. HEADED) THEN\t!Is the first line to be treated specially?\n WRITE (MSG,*) \"<tHead>\"\t!Yep. Nominate a heading.\n IT = 1\t\t\t!And select \"th\" rather than \"td\".\n ELSE\t\t\t\t!But mostly,\n IT = 2\t\t\t!Just another row for the table.\n END IF\t\t\t!So much for the first line.\n NCOLS = 0\t\t!No commas have been seen.\n DO I = 1,L\t\t!So scan the text for them.\n IF (ICHAR(ALINE(I:I)).EQ.ICHAR(\",\")) THEN\t!Here?\n NCOLS = NCOLS + 1\t\t!Yes!\n MARK(NCOLS) = I\t\t!The texts are between commas.\n END IF\t\t\t!So much for that character.\n END DO\t\t\t!On to the next.\n NCOLS = NCOLS + 1\t!This is why the + 1 for the size of MARK.\n MARK(NCOLS) = L + 1\t!End-of-line is as if a comma was one further along.\n WRITE (MSG,13)\t\t!Now roll all the texts.\n 1 (WOT(IT),\t\t\t\t!This starting a cell,\n 2 ALINE(MARK(I - 1) + 1:MARK(I) - 1),\t!This being the text between the commas,\n 3 WOT(IT),\t\t\t\t!And this ending each cell.\n 4 I = 1,NCOLS),\t\t\t!For this number of columns.\n 5 \"/tr\"\t\t\t!And this ends the row.\n 13 FORMAT (\" <tr>\",666(\"<\",A,\">\",A,\"</\",A,\">\"))\t!How long is a piece of string?\n IF (N.EQ.1 .AND. HEADED) WRITE (MSG,*) \"</tHead>\"\t!Finish the possible header.\n GO TO 10\t\t!And try for another record.\n\n 20 CLOSE (IN)\t\t!Finished with input.\n WRITE (MSG,21)\t\t!And finished with output.\n 21 FORMAT (\"</Table>\")\t!This writes starting at column one.\n RETURN\t\t\t!Done!\nConfusions.\n 661 WRITE (MSG,*) \"Can't open file \",FNAME\t!Alas.\n END\t\t\t!So much for the conversion.\n\n INTEGER KBD,MSG,IN\n COMMON /IOUNITS/ KBD,MSG,IN\n KBD = 5\t!Standard input.\n MSG = 6\t!Standard output.\n IN = 10\t!Some unspecial number.\n\n CALL CSVTEXT2HTML(\"Text.csv\",.FALSE.)\t!The first line is not special.\n WRITE (MSG,*)\n CALL CSVTEXT2HTML(\"Text.csv\",.TRUE.)\t!The first line is a heading.\n END\n", "language": "Fortran" }, { "code": "Data \"Character,Speech\"\nData \"The multitude,The messiah! Show us the messiah!\"\nData \"Brian's mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\"\nData \"The multitude,Who are you?\"\nData \"Brian's mother,I'm his mother; that's who!\"\nData \"The multitude,Behold his mother! Behold his mother!\"\nData \"***\"\n\nPrint \"<!DOCTYPE html>\" & Chr(10) & \"<html>\"\nPrint \"<head>\"\nPrint \"</head>\" & Chr(10)\nPrint \"<body>\"\nPrint \"<h1 style=\"\"text-align:center\"\">CSV to html translation </h1>\"\nPrint: Print \"<table border = 1 cellpadding = 10 cellspacing = 0>\"\n\nDim As Boolean header = true\nDim As String cadenaCSV, txt\nDo\n Read cadenaCSV\n If cadenaCSV = \"***\" then Exit Do\n\n If header then\n Print \"<thead bgcolor=\"\"green\"\">\" & Chr(10) & \"<tr><th>\";\n Else\n Print \"<tr><td>\";\n End If\n For i As Integer = 1 To Len(cadenaCSV)\n txt = Mid(cadenaCSV, i, 1)\n Select Case txt\n Case \",\": If header then Print \"</th><th>\"; Else Print \"</td><td>\";\n Case \"<\": Print \"&lt;\";\n Case \">\": Print \"&gt;\";\n Case \"&\": Print \"&amp;\";\n Case Else: Print txt;\n End Select\n Next i\n If header then\n Print \"</th></tr>\" & Chr(10) & \"</thead>\" & Chr(10) & \"<tbody bgcolor=\"\"yellow\"\">\"\n Else\n Print \"</td></tr>\"\n End If\n\n header = false\nLoop Until false\n\nPrint \"</tbody>\" & Chr(10) & \"</table>\"\nPrint Chr(10) & \"</body>\"\nPrint \"</html>\"\nSleep\n", "language": "FreeBASIC" }, { "code": "output file \"CSV2HTML\"\n\ninclude \"Tlbx WebKit.incl\"\n\n_window = 1\nbegin enum output 1\n _webView\nend enum\n\nvoid local fn BuildWindow\n CGRect r = fn CGRectMake( 0, 0, 600, 220 )\n window _window, @\"Rosetta Code CSV to HTML\", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable\n\n r = fn CGRectMake( 20, 20, 560, 180 )\n wkwebview _webView, r,, _window\nend fn\n\nlocal fn CSV2HTML as CFStringRef\n NSUInteger i, count\n\n CFStringRef csvStr = @\"Character,Speech\\n¬\n The multitude,The messiah! Show us the messiah!\\n¬\n Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\\n¬\n The multitude,Who are you\\n¬\n Brians mother,I'm his mother; that's who!\\n¬\n The multitude,Behold his mother! Behold his mother!\"\n\n CFArrayRef linesArray = fn StringComponentsSeparatedByString( csvStr, @\"\\n\" )\n CFMutableStringRef htmlStr = fn MutableStringWithCapacity(0)\n MutableStringAppendString( htmlStr, @\"<table style=\\\"background:#eee;\\\">\\n\" )\n MutableStringAppendString( htmlStr, @\"<tr bgcolor=wheat><th>Character</th><th>Speech</th></tr>\" )\n MutableStringAppendString( htmlStr, @\"<caption>From Monty Python's \\\"The Life of Brian\\\"</caption>\\n\" )\n count = len( linesArray )\n for i = 1 to count - 1\n CFStringRef tempStr = linesArray[i]\n CFArrayRef tempArr = fn StringComponentsSeparatedByString( tempStr, @\",\" )\n MutableStringAppendString( htmlStr, @\"<tr>\\n\" )\n MutableStringAppendString( htmlStr, fn StringWithFormat( @\"<td style=\\\"width:120px;\\\"><b>%@</b></td>>\\n\", tempArr[0] ) )\n MutableStringAppendString( htmlStr, fn StringWithFormat( @\"<td><i>%@</i></td>\\n\", tempArr[1] ) )\n MutableStringAppendString( htmlStr, @\"</tr>\\n\" )\n next\n MutableStringAppendString( htmlStr, @\"</table><br></br>\" )\nend fn = fn StringWithString( htmlStr )\n\nlocal fn LoadHTML2WebView\n CFStringRef htmlStr = fn CSV2HTML\n fn WKWebViewLoadHTMLString( _webView, htmlStr, NULL )\nend fn\n\nvoid local fn DoDialog( ev as long, tag as long, wnd as long, obj as CFTypeRef )\n select (ev)\n case _windowWillClose : end\n end select\nend fn\n\non dialog fn DoDialog\n\nfn BuildWindow\nfn LoadHTML2WebView\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport (\n \"bytes\"\n \"encoding/csv\"\n \"fmt\"\n \"html/template\"\n \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n if h, err := csvToHtml(c); err != nil {\n fmt.Println(err)\n } else {\n fmt.Print(h)\n }\n}\n\nfunc csvToHtml(c string) (string, error) {\n data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n if err != nil {\n return \"\", err\n }\n var b strings.Builder\n err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n return b.String(), err\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"bytes\"\n \"encoding/csv\"\n \"flag\"\n \"fmt\"\n \"html/template\"\n \"strings\"\n)\n\nvar csvStr = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n headings := flag.Bool(\"h\", false, \"format first row as column headings\")\n flag.Parse()\n if html, err := csvToHtml(csvStr, *headings); err != nil {\n fmt.Println(err)\n } else {\n fmt.Print(html)\n }\n}\n\nfunc csvToHtml(csvStr string, headings bool) (string, error) {\n data, err := csv.NewReader(bytes.NewBufferString(csvStr)).ReadAll()\n if err != nil {\n return \"\", err\n }\n tStr := tPlain\n if headings {\n tStr = tHeadings\n }\n var b strings.Builder\n err = template.Must(template.New(\"\").Parse(tStr)).Execute(&b, data)\n return b.String(), err\n}\n\nconst (\n tPlain = `<table>\n{{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`\n tHeadings = `<table>{{if .}}\n{{range $x, $e := .}}{{if $x}}\n <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>{{else}} <thead>\n <tr>{{range .}}<th>{{.}}</th>{{end}}</tr>\n </thead>\n <tbody>{{end}}{{end}}\n </tbody>{{end}}\n</table>\n`\n)\n", "language": "Go" }, { "code": "<table>\n <thead>\n <tr><th>Character</th><th>Speech</th></tr>\n </thead>\n <tbody>\n <tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n <tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He&#39;s not the messiah; he&#39;s a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n <tr><td>The multitude</td><td>Who are you?</td></tr>\n <tr><td>Brians mother</td><td>I&#39;m his mother; that&#39;s who!</td></tr>\n <tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n </tbody>\n</table>\n", "language": "Go" }, { "code": "<table>\n <tr><td>Character</td><td>Speech</td></tr>\n <tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n <tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He&#39;s not the messiah; he&#39;s a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n <tr><td>The multitude</td><td>Who are you?</td></tr>\n <tr><td>Brians mother</td><td>I&#39;m his mother; that&#39;s who!</td></tr>\n <tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "Go" }, { "code": "def formatCell = { cell ->\n \"<td>${cell.replaceAll('&','&amp;').replaceAll('<','&lt;')}</td>\"\n}\n\ndef formatRow = { row ->\n \"\"\"<tr>${row.split(',').collect { cell -> formatCell(cell) }.join('')}</tr>\n\"\"\"\n}\n\ndef formatTable = { csv, header=false ->\n def rows = csv.split('\\n').collect { row -> formatRow(row) }\n header \\\n ? \"\"\"\n<table>\n<thead>\n${rows[0]}</thead>\n<tbody>\n${rows[1..-1].join('')}</tbody>\n</table>\n\"\"\" \\\n : \"\"\"\n<table>\n${rows.join('')}</table>\n\"\"\"\n}\n\ndef formatPage = { title, csv, header=false ->\n\"\"\"<html>\n<head>\n<title>${title}</title>\n<style type=\"text/css\">\ntd {background-color:#ddddff; }\nthead td {background-color:#ddffdd; text-align:center; }\n</style>\n</head>\n<body>${formatTable(csv, header)}</body>\n</html>\"\"\"\n}\n", "language": "Groovy" }, { "code": "def csv = '''Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!'''\n\nprintln 'Basic:'\nprintln '-----------------------------------------'\nprintln (formatPage('Basic', csv))\nprintln '-----------------------------------------'\nprintln()\nprintln()\nprintln 'Extra Credit:'\nprintln '-----------------------------------------'\nprintln (formatPage('Extra Credit', csv, true))\nprintln '-----------------------------------------'\n", "language": "Groovy" }, { "code": "<html>\n<head>\n<title>Basic</title>\n<style type=\"text/css\">\ntd {background-color:#ddddff; }\nthead td {background-color:#ddffdd; text-align:center; }\n</style>\n</head>\n<body>\n<table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry></td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n</body>\n</html>\n", "language": "Groovy" }, { "code": "<html>\n<head>\n<title>Extra Credit</title>\n<style type=\"text/css\">\ntd {background-color:#ddddff; }\nthead td {background-color:#ddffdd; text-align:center; }\n</style>\n</head>\n<body>\n<table>\n<thead>\n<tr><td>Character</td><td>Speech</td></tr>\n</thead>\n<tbody>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry></td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</tbody>\n</table>\n</body>\n</html>\n", "language": "Groovy" }, { "code": "import groovy.xml.MarkupBuilder\n\ndef formatRow = { doc, row ->\n doc.tr { row.each { cell -> td { mkp.yield(cell) } } }\n}\n\ndef formatPage = { titleString, csv, header=false ->\n def writer = new StringWriter()\n def doc = new MarkupBuilder(writer)\n def rows = csv.split('\\n').collect { row -> row.split(',') }\n doc.html {\n head {\n title (titleString)\n style (type:\"text/css\") {\n mkp.yield('''\n td {background-color:#ddddff; }\n thead td {background-color:#ddffdd; text-align:center; }\n ''')\n }\n }\n body {\n table {\n header && thead { formatRow(doc, rows[0]) }\n header && tbody { rows[1..-1].each { formatRow(doc, it) } }\n header || rows.each { formatRow(doc, it) }\n }\n }\n }\n writer.toString()\n}\n", "language": "Groovy" }, { "code": "<html>\n <head>\n <title>Basic</title>\n <style type='text/css'>\n td {background-color:#ddddff; }\n thead td {background-color:#ddffdd; text-align:center; }\n </style>\n </head>\n <body>\n <table>\n <tr>\n <td>Character</td>\n <td>Speech</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Who are you?</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>I'm his mother; that's who!</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n </table>\n </body>\n</html>\n", "language": "Groovy" }, { "code": "<html>\n <head>\n <title>Extra Credit</title>\n <style type='text/css'>\n td {background-color:#ddddff; }\n thead td {background-color:#ddffdd; text-align:center; }\n </style>\n </head>\n <body>\n <table>\n <thead>\n <tr>\n <td>Character</td>\n <td>Speech</td>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Who are you?</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>I'm his mother; that's who!</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n </tbody>\n </table>\n </body>\n</html>\n", "language": "Groovy" }, { "code": "--import Data.List.Split (splitOn) -- if the import is available\nsplitOn :: Char -> String -> [String] -- otherwise\nsplitOn delim = foldr (\\x rest ->\n if x == delim then \"\" : rest\n else (x:head rest):tail rest) [\"\"]\n\nhtmlEscape :: String -> String\nhtmlEscape = concatMap escapeChar\n where escapeChar '<' = \"&lt;\"\n escapeChar '>' = \"&gt;\"\n escapeChar '&' = \"&amp;\"\n escapeChar '\"' = \"&quot;\" --\"\n escapeChar c = [c]\n\ntoHtmlRow :: [String] -> String\ntoHtmlRow [] = \"<tr></tr>\"\ntoHtmlRow cols = let htmlColumns = concatMap toHtmlCol cols\n in \"<tr>\\n\" ++ htmlColumns ++ \"</tr>\"\n where toHtmlCol x = \" <td>\" ++ htmlEscape x ++ \"</td>\\n\"\n\ncsvToTable :: String -> String\ncsvToTable csv = let rows = map (splitOn ',') $ lines csv\n html = unlines $ map toHtmlRow rows\n in \"<table>\\n\" ++ html ++ \"</table>\"\n\nmain = interact csvToTable\n", "language": "Haskell" }, { "code": "import Data.List (unfoldr)\nsplit p = unfoldr (\\s -> case dropWhile p s of [] -> Nothing\n ss -> Just $ break p ss)\n\nmain = interact (\\csv -> \"<table>\\n\" ++\n (unlines $ map ((\\cols -> \"<tr>\\n\" ++\n (concatMap (\\x -> \" <td>\" ++ concatMap (\\c ->\n case c of {'<' -> \"&lt;\"; '>' -> \"&gt;\";\n\t\t\t'&' -> \"&amp;\"; '\"' -> \"&quot;\"; _ -> [c]}) x\n ++ \"</td>\\n\") cols)\n ++ \"</tr>\") . split (==',')) $ lines csv) ++ \"</table>\")\n", "language": "Haskell" }, { "code": "<table>\n<tr>\n <td>Character</td>\n <td>Speech</td>\n</tr>\n<tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n</tr>\n<tr>\n <td>Brians mother</td>\n <td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td>\n</tr>\n<tr>\n <td>The multitude</td>\n <td>Who are you?</td>\n</tr>\n<tr>\n <td>Brians mother</td>\n <td>I'm his mother; that's who!</td>\n</tr>\n<tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n</tr>\n</table>\n", "language": "Haskell" }, { "code": "procedure main(arglist)\n pchar := &letters ++ &digits ++ '!?;. ' # printable chars\n\n write(\"<TABLE>\")\n firstHead := (!arglist == \"-heading\")\n tHead := write\n while row := trim(read()) do {\n if \\firstHead then write(\" <THEAD>\") else tHead(\" <TBODY>\")\n writes(\" <TR><TD>\")\n while *row > 0 do\n row ?:= ( (=\",\",writes(\"</TD><TD>\")) |\n writes( tab(many(pchar)) |\n (\"&#\" || ord(move(1))) ), tab(0))\n write(\"</TD></TR>\")\n if (\\firstHead) := &null then write(\" </THEAD>\\n <TBODY>\")\n tHead := 1\n }\n write(\" </TBODY>\")\n write(\"</TABLE>\")\nend\n", "language": "Icon" }, { "code": "<TABLE>\n <THEAD>\n <TR><TD>Character</TD><TD>Speech</TD></TR>\n </THEAD>\n <TBODY>\n <TR><TD>The multitude</TD><TD>The messiah! Show us the messiah!</TD></TR>\n <TR><TD>Brians mother</TD><TD>&#60angry&#62Now you listen here! He&#39s not the messiah; he&#39s a very naughty boy! Now go away!&#60&#47angry&#62</TD></TR>\n <TR><TD>The multitude</TD><TD>Who are you?</TD></TR>\n <TR><TD>Brians mother</TD><TD>I&#39m his mother; that&#39s who!</TD></TR>\n <TR><TD>The multitude</TD><TD>Behold his mother! Behold his mother!</TD></TR>\n </TBODY>\n</TABLE>\n", "language": "Icon" }, { "code": "require 'strings tables/csv'\nencodeHTML=: ('&';'&amp;';'<';'&lt;';'>';'&gt;')&stringreplace\n\ntag=: adverb define\n 'starttag endtag'=.m\n (,&.>/)\"1 (starttag , ,&endtag) L:0 y\n)\n\nmarkupCells=: ('<td>';'</td>') tag\nmarkupHdrCells=: ('<th>';'</th>') tag\nmarkupRows=: ('<tr>';'</tr>',LF) tag\nmarkupTable=: (('<table>',LF);'</table>') tag\n\nmakeHTMLtablefromCSV=: verb define\n 0 makeHTMLtablefromCSV y NB. default left arg is 0 (no header row)\n:\n t=. fixcsv encodeHTML y\n if. x do. t=. (markupHdrCells@{. , markupCells@}.) t\n else. t=. markupCells t\n end.\n ;markupTable markupRows t\n)\n", "language": "J" }, { "code": "tag=: adverb def '[: (,&.>/)\"1 m&(0&{::@[ , 1&{::@[ ,~ ]) L:0@]'\nmakeHTMLtablefromCSV6=: 0&$: : ([: ; markupTable@markupRows@([ markupCells`(markupHdrCells@{. , markupCells@}.)@.[ fixcsv@encodeHTML))\n", "language": "J" }, { "code": " CSVstrng=: noun define\nCharacter,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\n)\n 1 makeHTMLtablefromCSV CSVstrng\n", "language": "J" }, { "code": "<table>\n<tr><th>Character</th><th>Speech</th></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "J" }, { "code": "String csv = \"...\";\n// Use Collectors.joining(...) for streaming, otherwise StringJoiner\nStringBuilder html = new StringBuilder(\"<table>\\n\");\nCollector collector = Collectors.joining(\"</td><td>\", \" <tr><td>\", \"</td></tr>\\n\");\nfor (String row : csv.split(\"\\n\") ) {\n html.append(Arrays.stream(row.split(\",\")).collect(collector));\n}\nhtml.append(\"</table>\\n\");\n", "language": "Java" }, { "code": "import java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.io.PrintStream;\n\nclass Csv2Html {\n\n\tpublic static String escapeChars(String lineIn) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tint lineLength = lineIn.length();\n\t\tfor (int i = 0; i < lineLength; i++) {\n\t\t\tchar c = lineIn.charAt(i);\n\t\t\tswitch (c) {\n\t\t\t\tcase '\"':\n\t\t\t\t\tsb.append(\"&quot;\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase '&':\n\t\t\t\t\tsb.append(\"&amp;\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase '\\'':\n\t\t\t\t\tsb.append(\"&apos;\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase '<':\n\t\t\t\t\tsb.append(\"&lt;\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase '>':\n\t\t\t\t\tsb.append(\"&gt;\");\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: sb.append(c);\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\tpublic static void tableHeader(PrintStream ps, String[] columns) {\n\t\tps.print(\"<tr>\");\n\t\tfor (int i = 0; i < columns.length; i++) {\n\t\t\tps.print(\"<th>\");\n\t\t\tps.print(columns[i]);\n\t\t\tps.print(\"</th>\");\n\t\t}\n\t\tps.println(\"</tr>\");\n\t}\n\t\n\tpublic static void tableRow(PrintStream ps, String[] columns) {\n\t\tps.print(\"<tr>\");\n\t\tfor (int i = 0; i < columns.length; i++) {\n\t\t\tps.print(\"<td>\");\n\t\t\tps.print(columns[i]);\n\t\t\tps.print(\"</td>\");\n\t\t}\n\t\tps.println(\"</tr>\");\n\t}\n\t\n\tpublic static void main(String[] args) throws Exception {\n\t\tboolean withTableHeader = (args.length != 0);\n\t\t\n\t\tInputStreamReader isr = new InputStreamReader(System.in);\n\t\tBufferedReader br = new BufferedReader(isr);\n\t\tPrintStream stdout = System.out;\n\t\t\n\t\tstdout.println(\"<!DOCTYPE html PUBLIC \\\"-//W3C//DTD XHTML 1.0 Strict//EN\\\" \\\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\\\">\");\n\t\tstdout.println(\"<html xmlns=\\\"http://www.w3.org/1999/xhtml\\\">\");\n\t\tstdout.println(\"<head><meta http-equiv=\\\"Content-type\\\" content=\\\"text/html;charset=UTF-8\\\"/>\");\n\t\tstdout.println(\"<title>Csv2Html</title>\");\n\t\tstdout.println(\"<style type=\\\"text/css\\\">\");\n\t\tstdout.println(\"body{background-color:#FFF;color:#000;font-family:OpenSans,sans-serif;font-size:10px;}\");\n\t\tstdout.println(\"table{border:0.2em solid #2F6FAB;border-collapse:collapse;}\");\n\t\tstdout.println(\"th{border:0.15em solid #2F6FAB;padding:0.5em;background-color:#E9E9E9;}\");\n\t\tstdout.println(\"td{border:0.1em solid #2F6FAB;padding:0.5em;background-color:#F9F9F9;}</style>\");\n\t\tstdout.println(\"</head><body><h1>Csv2Html</h1>\");\n\n\t\tstdout.println(\"<table>\");\n\t\tString stdinLine;\n\t\tboolean firstLine = true;\n\t\twhile ((stdinLine = br.readLine()) != null) {\n\t\t\tString[] columns = escapeChars(stdinLine).split(\",\");\n\t\t\tif (withTableHeader == true && firstLine == true) {\n\t\t\t\ttableHeader(stdout, columns);\n\t\t\t\tfirstLine = false;\n\t\t\t} else {\n\t\t\t\ttableRow(stdout, columns);\n\t\t\t}\n\t\t}\n\t\tstdout.println(\"</table></body></html>\");\n\t}\n}\n", "language": "Java" }, { "code": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head><meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\"/>\n<title>Csv2Html</title>\n<style type=\"text/css\">\nbody{background-color:#FFF;color:#000;font-family:OpenSans,sans-serif;font-size:10px;}\ntable{border:0.2em solid #2F6FAB;border-collapse:collapse;}\nth{border:0.15em solid #2F6FAB;padding:0.5em;background-color:#E9E9E9;}\ntd{border:0.1em solid #2F6FAB;padding:0.5em;background-color:#F9F9F9;}</style>\n</head><body><h1>Csv2Html</h1>\n<table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He&apos;s not the messiah; he&apos;s a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I&apos;m his mother; that&apos;s who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table></body></html>\n", "language": "Java" }, { "code": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head><meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\"/>\n<title>Csv2Html</title>\n<style type=\"text/css\">\nbody{background-color:#FFF;color:#000;font-family:OpenSans,sans-serif;font-size:10px;}\ntable{border:0.2em solid #2F6FAB;border-collapse:collapse;}\nth{border:0.15em solid #2F6FAB;padding:0.5em;background-color:#E9E9E9;}\ntd{border:0.1em solid #2F6FAB;padding:0.5em;background-color:#F9F9F9;}</style>\n</head><body><h1>Csv2Html</h1>\n<table>\n<tr><th>Character</th><th>Speech</th></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He&apos;s not the messiah; he&apos;s a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I&apos;m his mother; that&apos;s who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table></body></html>\n", "language": "Java" }, { "code": "var csv = \"Character,Speech\\n\" +\n\t \"The multitude,The messiah! Show us the messiah!\\n\" +\n\t \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" +\n\t \"The multitude,Who are you?\\n\" +\n\t \"Brians mother,I'm his mother; that's who!\\n\" +\n\t \"The multitude,Behold his mother! Behold his mother!\";\n\nvar lines = csv.replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .split(/[\\n\\r]/)\n .map(function(line) { return line.split(',')})\n .map(function(row) {return '\\t\\t<tr><td>' + row[0] + '</td><td>' + row[1] + '</td></tr>';});\n\nconsole.log('<table>\\n\\t<thead>\\n' + lines[0] +\n '\\n\\t</thead>\\n\\t<tbody>\\n' + lines.slice(1).join('\\n') +\n '\\t</tbody>\\n</table>');\n", "language": "JavaScript" }, { "code": "<table>\n <thead>\n <tr><td>Character</td><td>Speech</td></tr>\n </thead>\n <tbody>\n <tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n <tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n <tr><td>The multitude</td><td>Who are you?</td></tr>\n <tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n <tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n </tbody>\n</table>\n", "language": "JavaScript" }, { "code": "<table>\n\t<thead>\n\t\t<tr><td>Character</td><td>Speech</td></tr>\n\t</thead>\n\t<tbody>\n\t\t<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n\t\t<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n\t\t<tr><td>The multitude</td><td>Who are you?</td></tr>\n\t\t<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n\t\t<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\t</tbody>\n</table>\n", "language": "JavaScript" }, { "code": "jq -R . csv2html.csv | jq -r -s -f csv2html.jq\n", "language": "Jq" }, { "code": "def headerrow2html:\n [\" <thead> <tr>\"]\n + (split(\",\") | map(\" <th>\\(@html)</th>\"))\n + [ \" </tr> </thead>\" ]\n;\n\ndef row2html:\n [\" <tr>\"]\n + (split(\",\") | map(\" <td>\\(@html)</td>\"))\n + [ \" </tr>\" ]\n;\n\ndef csv2html:\n def rows: reduce .[] as $row\n ([]; . + ($row | row2html));\n [\"<table>\"]\n + (.[0] | headerrow2html)\n + (.[1:] | rows)\n + [ \"</table>\"]\n;\n\ncsv2html | .[]\n", "language": "Jq" }, { "code": "<table>\n <thead> <tr>\n <th>Character</th>\n <th>Speech </th>\n </tr> </thead>\n <tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah! </td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>&lt;angry&gt;Now you listen here! He&apos;s not the messiah; he&apos;s a very naughty boy! Now go away!&lt;/angry&gt; </td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Who are you? </td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>I&apos;m his mother; that&apos;s who! </td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother! </td>\n </tr>\n</table>\n", "language": "Jq" }, { "code": "/* CSV to HTML, in Jsish */\nvar csv = \"Character,Speech\\n\" +\n \"The multitude,The messiah! Show us the messiah!\\n\" +\n \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" +\n \"The multitude,Who are you?\\n\" +\n \"Brians mother,I'm his mother; that's who!\\n\" +\n \"The multitude,Behold his mother! Behold his mother!\";\n\nvar lines = csv.replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .split('\\n')\n .map(function(line) { return line.split(','); })\n .map(function(row) { return '\\t\\t<tr><td>' + row[0] + '</td><td>' + row[1] + '</td></tr>'; });\n\nif (Interp.conf('unitTest')) {\n puts('<table>\\n\\t<thead>\\n' + lines[0] + '\\n\\t</thead>\\n\\t<tbody>\\n'\n + lines.slice(1).join('\\n') + '\\t</tbody>\\n</table>');\n}\n\n/*\n=!EXPECTSTART!=\n<table>\n <thead>\n <tr><td>Character</td><td>Speech</td></tr>\n </thead>\n <tbody>\n <tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n <tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n <tr><td>The multitude</td><td>Who are you?</td></tr>\n <tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n <tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr> </tbody>\n</table>\n=!EXPECTEND!=\n*/\n", "language": "Jsish" }, { "code": "using DataFrames, CSV\n\nusing CSV, DataFrames\n\nfunction csv2html(fname; header::Bool=false)\n csv = CSV.read(fname)\n @assert(size(csv, 2) > 0)\n str = \"\"\"\n<html>\n\n<head>\n <style type=\"text/css\">\n body {\n margin: 2em;\n }\n h1 {\n text-align: center;\n }\n table {\n border-spacing: 0;\n box-shadow: 0 0 0.25em #888;\n margin: auto;\n }\n table,\n tr,\n th,\n td {\n border-collapse: collapse;\n }\n th {\n color: white;\n background-color: rgb(43, 53, 59);\n }\n th,\n td {\n padding: 0.5em;\n }\n table tr:nth-child(even) td {\n background-color: rgba(218, 224, 229, 0.850);\n }\n </style>\n</head>\n\n<body>\n <h1>csv2html Example</h1>\n <table>\n <tr>\n\"\"\"\n tags = header ? (\"<th>\", \"</th>\") : (\"<td>\", \"</td>\")\n\n for i=1:size(csv, 2)\n str *= \" \" * tags[1] * csv[1, i] * tags[2] * \"\\n\"\n end\n\n str *= \" \"^8 * \"</tr>\\n\"\n\n for i=2:size(csv, 1)\n str *= \" <tr>\\n\"\n\n for j=1:size(csv, 2)\n str *= \" \" * \"<td>\" * csv[i, j] * \"</td>\\n\"\n end\n\n str *= \" </tr>\\n\"\n end\n\n str * \" </table>\\n</body>\\n\\n</html>\\n\"\nend\n\nprint(csv2html(\"input.csv\", header=true))\n", "language": "Julia" }, { "code": "<html>\n\n<head>\n <style type=\"text/css\">\n body {\n margin: 2em;\n }\n h1 {\n text-align: center;\n }\n table {\n border-spacing: 0;\n box-shadow: 0 0 0.25em #888;\n margin: auto;\n }\n table,\n tr,\n th,\n td {\n border-collapse: collapse;\n }\n th {\n color: white;\n background-color: rgb(43, 53, 59);\n }\n th,\n td {\n padding: 0.5em;\n }\n table tr:nth-child(even) td {\n background-color: rgba(218, 224, 229, 0.850);\n }\n </style>\n</head>\n\n<body>\n <h1>csv2html Example</h1>\n <table>\n <tr>\n <th>Character</th>\n <th>Speech</th>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Who are you?</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>I'm his mother; that's who!</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n </table>\n</body>\n</html>\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nval csv =\n \"Character,Speech\\n\" +\n \"The multitude,The messiah! Show us the messiah!\\n\" +\n \"Brians mother,<angry>Now you listen here! He's not the messiah; \" +\n \"he's a very naughty boy! Now go away!</angry>\\n\" +\n \"The multitude,Who are you?\\n\" +\n \"Brians mother,I'm his mother; that's who!\\n\" +\n \"The multitude,Behold his mother! Behold his mother!\"\n\nfun main(args: Array<String>) {\n val i = \" \" // indent\n val sb = StringBuilder(\"<table>\\n$i<tr>\\n$i$i<td>\")\n for (c in csv) {\n sb.append( when (c) {\n '\\n' -> \"</td>\\n$i</tr>\\n$i<tr>\\n$i$i<td>\"\n ',' -> \"</td>\\n$i$i<td>\"\n '&' -> \"&amp;\"\n '\\'' -> \"&apos;\"\n '<' -> \"&lt;\"\n '>' -> \"&gt;\"\n else -> c.toString()\n })\n }\n sb.append(\"</td>\\n$i</tr>\\n</table>\")\n println(sb.toString())\n println()\n\n // now using first row as a table header\n sb.setLength(0)\n sb.append(\"<table>\\n$i<thead>\\n$i$i<tr>\\n$i$i$i<td>\")\n val hLength = csv.indexOf('\\n') + 1 // find length of first row including CR\n for (c in csv.take(hLength)) {\n sb.append( when (c) {\n '\\n' -> \"</td>\\n$i$i</tr>\\n$i</thead>\\n$i<tbody>\\n$i$i<tr>\\n$i$i$i<td>\"\n ',' -> \"</td>\\n$i$i$i<td>\"\n else -> c.toString()\n })\n }\n for (c in csv.drop(hLength)) {\n sb.append( when (c) {\n '\\n' -> \"</td>\\n$i$i</tr>\\n$i$i<tr>\\n$i$i$i<td>\"\n ',' -> \"</td>\\n$i$i$i<td>\"\n '&' -> \"&amp;\"\n '\\'' -> \"&apos;\"\n '<' -> \"&lt;\"\n '>' -> \"&gt;\"\n else -> c.toString()\n })\n }\n sb.append(\"</td>\\n$i$i</tr>\\n$i</tbody>\\n</table>\")\n println(sb.toString())\n}\n", "language": "Kotlin" }, { "code": "<table>\n <tr>\n <td>Character</td>\n <td>Speech</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>&lt;angry&gt;Now you listen here! He&apos;s not the messiah; he&apos;s a very naughty boy! Now go away!&lt;/angry&gt;</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Who are you?</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>I&apos;m his mother; that&apos;s who!</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n</table>\n\n<table>\n <thead>\n <tr>\n <td>Character</td>\n <td>Speech</td>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>&lt;angry&gt;Now you listen here! He&apos;s not the messiah; he&apos;s a very naughty boy! Now go away!&lt;/angry&gt;</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Who are you?</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>I&apos;m his mother; that&apos;s who!</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n </tbody>\n</table>\n", "language": "Kotlin" }, { "code": "{def CSV\nCharacter,Speech\\n\nThe multitude,The messiah! Show us the messiah!\\n\nBrians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\\n\nThe multitude,Who are you\\n\nBrians mother,I'm his mother; that's who!\\n\nThe multitude,Behold his mother! Behold his mother!\\n\n}\n-> CSV\n\n{def csv2html\n {lambda {:csv}\n {table {@ style=\"background:#eee;\"}\n {S.replace ([^,]*),([^_]*)_\n by {tr {td {@ style=\"width:120px;\"}{b €1}} {td {i €2}}}\n in {S.replace \\\\n by _ in :csv}}}}}\n-> csv2html\n\n{csv2html {CSV}} ->\n", "language": "Lambdatalk" }, { "code": " newline$ =\"|\"\n ' No escape behaviour, so can't refer to '/n'.\n ' Generally imported csv would have separator CR LF; easily converted first if needed\n\n csv$ =\"Character,Speech\" +newline$+_\n \"The multitude,The messiah! Show us the messiah!\" +newline$+_\n \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\" +newline$+_\n \"The multitude,Who are you?\" +newline$+_\n \"Brians mother,I'm his mother; that's who!\" +newline$+_\n \"The multitude,Behold his mother! Behold his mother!\"\n\n print \"<HTML>\"\n print \"<HEAD>\"\n print \"</HEAD>\"\n print \"<BODY>\"\n print \"<center><H1>CSV to HTML translation </H1></center>\"\n print \"<table border=1 cellpadding =10>\"\n print \"<tr><td>\"\n\n for i =1 to len( csv$)\n c$ =mid$( csv$, i, 1)\n select case c$\n case \"|\": print \"</td></tr>\": print \"<tr><td>\"\n case \",\": print \"</td><td>\";\n case \"<\": print \"&\"+\"lt;\";\n case \">\": print \"&\"+\"gt;\";\n case \"&\": print \"&\"+\"amp;\";\n case else: print c$;\n end select\n next i\n\n print \"</td></tr>\"\n print \"</table>\"\n print \"</BODY>\"\n print \"</HTML>\"\n end\n", "language": "Liberty-BASIC" }, { "code": "FS = \",\" -- field separator\n\ncsv = [[\nCharacter,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\n]]\n\ncsv = csv:gsub( \"<\", \"&lt;\" )\ncsv = csv:gsub( \">\", \"&gr;\" )\n\nhtml = { \"<table>\" }\nfor line in string.gmatch( csv, \"(.-\\n)\" ) do\n str = \"<tr>\"\n for field in string.gmatch( line, \"(.-)[\"..FS..\"?\\n?]\" ) do\n str = str .. \"<td>\" .. field .. \"</td>\"\n end\n str = str .. \"</tr>\"\n html[#html+1] = str;\nend\nhtml[#html+1] = \"</table>\"\n\nfor _, line in pairs(html) do\n print(line)\nend\n", "language": "Lua" }, { "code": "<table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gr;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gr;</td></tr>\n<tr><td>The multitude</td><td>Who are you</td><td></td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "Lua" }, { "code": "module csv2html {\n\tnl$={\n\t}\n\tRepl$=lambda$ (a$) ->{\n\t\ta$=replace$(\"&\", \"&amp;\",a$)\n\t\ta$=replace$(\">\", \"&gt;\",a$)\n\t\ta$=replace$(\"\"\"\", \"&quot;\",a$)\n\t\t// add any other replacement here\n\t\t=replace$(\"<\", \"&lt;\",a$)\n\t}\n\tTag$=lambda$ nl$, repl$ (a$, b$, n=4)->{\n\t\tif n>0 then\n\t\t\ta$=rtrim$(replace$(nl$, nl$+string$(\" \", n), nl$+a$))\n\t\t\tif right$(a$,2)<>nl$ then a$+=nl$\n\t\telse\n\t\t\tif right$(a$, 2)=nl$ then if left$(a$,2)<>nl$ then a$=nl$+a$\n\t end if\n\t\tprop=(,) : Read ? prop // forth parameter optional (we have to initalize first with an empty array)\n\t\tp=each(prop) : prop$=\"\" // p is an iteration object.\n\t\twhile p\n\t\t\tprop$+=\" \"+repl$(prop#val$(p^))+\"=\"+quote$(repl$(prop#val$(p^+1)))\n\t\t\tp=each(prop,p^+2) // start new from p^+2 (p^ is the internal counter)\n\t\tend while\n\t\t=\"<\"+b$+prop$+\">\"+a$+\"</\"+b$+\">\"+nl$\n\t}\n\t\n\t// Prepare FILE csv\n\ttofile$={Character,Speech\n\tThe multitude,The messiah! Show us the messiah!\n\tBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n\tThe multitude,Who are you?\n\tBrians mother,I'm his mother; that's who!\n\tThe multitude,Behold his mother! Behold his mother!\n\t}\n\topen \"forHtml.csv\" for wide output as #f\n\tPrint #f, tofile$;\n\tclose #f\n\t// prepare the input style for Input from file statement\n\t// \",\" - we use comma between fields\n\t// \".\" - for numbers we use dot for decimal separator\n\t// false - we didn't read json style strings to normal strings (so \\n convert to code 13, \\t to code 9)\n\t// true - we read strings unquote\n\tinput with \",\",\".\",false, true\n\t\n\t// Read csv file\n\ti=1\n\tdocument export$=\"\"\n\tOpen \"forHtml.csv\" for wide input as #f\n\twhile not eof(#f)\n\t\tinput #f, a$, b$\n\t\ta$=repl$(a$)\n\t\tb$=repl$(b$)\n\t\tif i=1 then\n\t\t\texport$+=tag$(tag$(a$, \"th\", 0)+tag$(b$,\"th\", 0), \"tr\", 4)\n\t\telse\n\t\t\texport$+=tag$(tag$(a$, \"td\", 0)+tag$(b$,\"td\", 0), \"tr\", 4)\n\t\tend if\n\t\ti++\n\tend while\n\tclose #f\n\tstyle$=tag$({TD {background-color:#ddddff; }\n\t\tthead TD {background-color:#ddffdd; text-align:center; }\n\t\t},\"style\",4,(\"type\", \"text/css\"))\n\ttitle$= tag$(\"CSV to HTML translation - Extra Credit\",\"title\",0)\n\tHead$= tag$(title$+ style$,\"head\")\n\thtml$={<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">}+nl$+tag$(head$+tag$(tag$(export$, \"table\"), \"body\"), \"html\")\n\tclipboard html$\n\tReport html$\n\tPrint \"Press Esc to exit browser\"\n\tbrowser \"about: \"+html$\n}\ncsv2html\n", "language": "M2000-Interpreter" }, { "code": " #A translation of the C code posted\nhtml_table := proc(str)\n\tlocal char;\n printf(\"<table>\\n<tr><td>\");\n for char in str do\n if char = \"\\n\" then\n \tprintf(\"</td></tr>\\n<tr><td>\")\n elif char = \",\" then\n printf(\"</td><td>\")\n elif char = \"<\" then\n printf(\"&lt;\")\n elif char = \">\" then\n printf(\"&gt;\")\n elif char = \"&\" then\n \tprintf(\"&amp;\")\n else\n printf(char)\n end if;\n end do;\n printf(\"</td></tr>\\n</table>\");\nend proc;\n\nhtml_table(\"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\");\n", "language": "Maple" }, { "code": "a=\"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah;he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother;that's who!\nThe multitude,Behold his mother! Behold his mother!\";\n(*Naive*)\nStringJoin[\"<table>\\n\",Map[StringJoin[\"<tr><td>\",#,\"</td></tr>\\n\"]&,\nStringSplit[StringReplace[a,{\",\"->\"</td><td>\",\"<\"->\"&lt;\",\">\"->\"&gt;\"}],\"\\n\"]]\n,\"</table>\"]\n(*Extra*)\nStringJoin[\"<table>\\n\",StringJoin[\"<tr><th>\",#,\"</th></tr>\\n\"]&[\nStringSplit[StringReplace[a,{\",\"->\"</td><td>\",\"<\"->\"&lt;\",\">\"->\"&gt;\"}],\"\\n\"]//First]\n,Map[StringJoin[\"<tr><td>\",#,\"</td></tr>\\n\"]&,\nStringSplit[StringReplace[a,{\",\"->\"</td><td>\",\"<\"->\"&lt;\",\">\"->\"&gt;\"}],\"\\n\"]//Rest]\n,\"</table>\"]\n", "language": "Mathematica" }, { "code": "inputString = fileread(csvFileName);\n % using multiple regular expressions to clear up special chars\nhtmlFriendly = regexprep(regexprep(regexprep(regexprep(inputString,...\n '&','&amp;'),...\n '\"','&quot;'),...\n '<','&lt;'),...\n '>','&gt;');\n % split string into cell array\ntableValues = regexp(regexp(htmlFriendly,'(\\r\\n|\\r|\\n)','split')',',','split');\n %%% print in html format %%%\n % <Extra Credit> first line gets treated as header\nfprintf(1,['<table>\\n\\t<tr>' sprintf('\\n\\t\\t<th>%s</th>',tableValues{1,:}{:})])\n % print remaining lines of csv as html table (rows 2:end in cell array of csv values)\ncellfun(@(x)fprintf(1,['\\n\\t<tr>' sprintf('\\n\\t\\t<td>%s</td>',x{:}) '\\n\\t</tr>']),tableValues(2:end))\nfprintf(1,'\\n</table>')\n", "language": "MATLAB" }, { "code": "fprintf(1,['<table>\\n\\t<tr>\\n\\t\\t<th>',regexprep(regexprep(regexprep(regexprep(regexprep(regexprep(regexprep(regexprep(fileread(cvsFileName),'&','&amp;'),'\"','&quot;'),'<','&lt;'),'>','&gt;'),'(?<=(^[^\\n\\r]*)),','</th>\\n\\t\\t<th>'),'(?<!>)(\\r\\n|\\r|\\n)','</td>\\n\\t<tr>\\n\\t</tr>\\n\\t\\t<td>'),'</td>\\n','</th>\\n','once'),',','</td>\\n\\t\\t<td>'),'</td>\\n\\t</tr>\\n</table>\\n'])\n", "language": "MATLAB" }, { "code": "<table>\n\t<tr>\n\t\t<th>Character</th>\n\t\t<th>Speech</th>\n\t<tr>\n\t\t<td>The multitude</td>\n\t\t<td>The messiah! Show us the messiah!</td>\n\t</tr>\n\t<tr>\n\t\t<td>Brians mother</td>\n\t\t<td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td>\n\t</tr>\n\t<tr>\n\t\t<td>The multitude</td>\n\t\t<td>Who are you?</td>\n\t</tr>\n\t<tr>\n\t\t<td>Brians mother</td>\n\t\t<td>I'm his mother; that's who!</td>\n\t</tr>\n\t<tr>\n\t\t<td>The multitude</td>\n\t\t<td>Behold his mother! Behold his mother!</td>\n\t</tr>\n</table>\n", "language": "MATLAB" }, { "code": "infile: \"input.csv\";\noutfile: \"table.html\";\ninstream: openr(infile);\noutstream: openw(outfile);\n\nprintf(outstream, \"<TABLE border=\\\"1\\\">~%\");\nnr: 0;\nwhile (line: readline(instream))#false do (\n nr: nr + 1,\n line: ssubst(\"&lt;\", \"<\", line),\n line: ssubst(\"&gt;\", \">\", line),\n value_list: map(lambda([f], strim(\" \", f)), split(line, \",\")),\n if nr=1 then printf(outstream, \" <THEAD bgcolor=\\\"yellow\\\">\") else printf(outstream, \" <TBODY bgcolor=\\\"orange\\\">\"),\n printf(outstream, \"<TR>\"),\n for value in value_list do printf(outstream, \"<TD>~a</TD>\", value),\n printf(outstream, \"</TR>\"),\n if nr=1 then printf(outstream, \"</THEAD>~%\") else printf(outstream, \"</TBODY>~%\"));\nprintf(outstream, \"</TABLE>~%\");\n\nclose(instream);\nclose(outstream);\n", "language": "Maxima" }, { "code": "<TABLE border=\"1\">\n <THEAD bgcolor=\"yellow\"><TR><TD>Character</TD><TD>Speech</TD></TR></THEAD>\n <TBODY bgcolor=\"orange\"><TR><TD>The multitude</TD><TD>The messiah! Show us the messiah!</TD></TR></TBODY>\n <TBODY bgcolor=\"orange\"><TR><TD>Brians mother</TD><TD>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</TD></TR></TBODY>\n <TBODY bgcolor=\"orange\"><TR><TD>The multitude</TD><TD>Who are you?</TD></TR></TBODY>\n <TBODY bgcolor=\"orange\"><TR><TD>Brians mother</TD><TD>I'm his mother; that's who!</TD></TR></TBODY>\n <TBODY bgcolor=\"orange\"><TR><TD>The multitude</TD><TD>Behold his mother! Behold his mother!</TD></TR></TBODY>\n</TABLE>\n", "language": "Maxima" }, { "code": "MCSKIP \"WITH\" NL\n\"\" CSV to HTML\n\"\" assumes macros on input stream 1, terminal on stream 2\nMCSKIP MT,[]\nMCSKIP SL WITH ~\nMCINS %.\n\"\" C1=th before header output, td afterwards\nMCCVAR 1,2\nMCSET C1=[th]\n\"\" HTML escapes\nMCDEF < AS [[&lt;]]\nMCDEF > AS [[&gt;]]\nMCDEF & AS [[&amp;]]\n\"\" Main line processing\nMCDEF SL N1 OPT , N1 OR NL ALL\nAS [[ <tr>]\nMCSET T2=1\n%L1.MCGO L2 IF T2 GR T1\n [<]%C1.[>]%AT2.[</]%C1.[>]\nMCSET T2=T2+1\nMCGO L1\n%L2.[ </tr>]\nMCSET C1=[td]\n]\n[<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n<html>\n<head>\n<title>HTML converted from CSV</title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<style type=\"text/css\"><!--\nth {\n font-weight:bold;\n text-align:left\n}\ntable,td,th {\n border:1px solid;\n border-collapse:collapse\n}\ntd,th {\n padding:10px\n}\n//-->\n</style>\n</head>\n\n<body>\n<table>]\nMCSET S1=1\n~MCSET S10=2\n~MCSET S1=0\n[</table>\n</body>\n</html>\n]\n", "language": "ML-I" }, { "code": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n<html>\n<head>\n<title>HTML converted from CSV</title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<style type=\"text/css\"><!--\nth {\n font-weight:bold;\n text-align:left\n}\ntable,td,th {\n border:1px solid;\n border-collapse:collapse\n}\ntd,th {\n padding:10px\n}\n//-->\n</style>\n</head>\n\n<body>\n<table>\n <tr>\n <th>Character</th>\n <th>Speech</th>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a\n very naughty boy! Now go away!&lt;/angry&gt;</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Who are you?</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>I'm his mother; that's who!</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n</table>\n</body>\n</html>\n", "language": "ML-I" }, { "code": "// a method that converts a csv row into a html table row as a string\ndef toHtmlRow(record, tag)\n\thtmlrow = \"\\t<tr>\\n\"\n\n\t// loop through the values in the current csv row\n\tfor i in range(1, len(record))\n\t\thtmlrow = htmlrow + \"\\t\\t<\" + tag + \">\" + (record ~ i) + \"</\" + tag + \">\\n\"\n\tend for\n\n\treturn htmlrow + \"\\t</tr>\\n\"\nend def\n\n// get the name of the csv file then open it\nprint \"filename: \"\ninput fname\nopen fname\n\n// allocate a string to hold the table\nhtmltable = \"<table>\\n\"\n\n// add the column names to the table (#0 returns column names as a record object)\nhtmltable = (htmltable + toHtmlRow(#0, \"th\"))\n\n// add all other rows to the table\nfor i in range(1, $dbsize)\n\thtmltable = (htmltable + toHtmlRow(#i, \"td\"))\nend for\n\n// close the html table\nhtmltable = htmltable+\"</table>\"\n\nprintln htmltable\n", "language": "Nanoquery" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\nparse arg inFileName .\nif inFileName = '' | inFileName = '.' then inFileName = './data/Brian.csv'\ncsv = RREadFileLineByLine01.scanFile(inFileName)\n\nheader = htmlHeader()\npre = htmlCsvText(csv, inFileName)\ntable = htmlCsvTable(csv, inFileName)\nfooter = htmlFooter()\n\nsay header\nsay pre\nsay table\nsay footer\n\nreturn\n\nmethod htmlHeader() public static returns Rexx\n html = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' -\n || '<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\\n' -\n || '<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en-US\" xml:lang=\"en-US\">\\n' -\n || '<head>\\n' -\n || '<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\"/>\\n' -\n || '<title>RCsv2Html</title>\\n' -\n || '<style type=\"text/css\">\\n' -\n || '<!--\\n' -\n || '/* <![DATA[ */\\n' -\n || 'body {\\n' -\n || ' font-family: \"Verdana\", \"Geneva\", \"Helvetica Neue\", \"Helvetica\", \"DejaVu Sans\", \"Arial\", sans-serif;\\n' -\n || '}\\n' -\n || 'table, th, td {\\n' -\n || ' border: 1px solid black;\\n' -\n || ' border-collapse: collapse;\\n' -\n || ' padding: 0.25em;\\n' -\n || ' font-size: 85%;\\n' -\n || '}\\n' -\n || 'th {\\n' -\n || ' color: white;\\n' -\n || ' background-color: green;\\n' -\n || '}\\n' -\n || 'p.classname {\\n' -\n || ' font-size: inherit;\\n' -\n || '}\\n' -\n || '/* ]] */\\n' -\n || '//-->\\n' -\n || '</style>\\n' -\n || '</head>\\n' -\n || '<body>\\n' -\n || '<h1>Rosetta Code &ndash; NetRexx Sample Output</h2>\\n' -\n || '<h2><a href=\"http://rosettacode.org/wiki/CSV_to_HTML_translation\">CSV to HTML translation</a></h2>\\n' -\n || ''\n\n return html\n\nmethod htmlFooter() public static returns Rexx\n html = '</body>\\n' -\n || '</html>\\n' -\n || ''\n return html\n\nmethod htmlCsvText(csv, fileName = '.') public static returns Rexx\n html = '<h3>Contents of CSV <code>'fileName'</code></h3>\\n' -\n || '<pre>\\n' -\n || ''\n loop row = 1 to csv[0]\n html = html || csv[row]'\\n'\n end row\n html = html -\n || '</pre>\\n' -\n || ''\n return html\n\nmethod htmlCsvTable(csv, fileName = '.') public static returns Rexx\n html = '<table>\\n' -\n || '<caption>Translation of CSV <code>'fileName'</code></caption>\\n' -\n || '<thead>\\n' -\n || ''\n html = html -\n || htmlCsvTableRow(csv[1], 'th')'\\n' -\n || '</thead>\\n' -\n || '<tbody>\\n' -\n || ''\n loop r_ = 2 to csv[0]\n html = html -\n || htmlCsvTableRow(csv[r_])'\\n' -\n || ''\n end r_\n html = html -\n || '</tbody>\\n' -\n || '</table>\\n' -\n || ''\n return html\n\nmethod htmlCsvTableRow(row, tag = 'td') public static returns Rexx\n row = row.strip('t')\n row = row.changestr('&', '&amp;') -- need to do this one first to avoid double translation\n row = row.changestr('\"', '&quot;')\n row = row.changestr(\"'\", '&apos;')\n row = row.changestr('<', '&lt;')\n row = row.changestr('>', '&gt;')\n elmts = ''\n elmts[0] = 0\n e_ = 0\n loop while row.length() > 0\n parse row elmt ',' row\n e_ = e_ + 1; elmts[0] = e_; elmts[e_] = elmt\n end\n html = '<tr>\\n' -\n || ''\n loop e_ = 1 to elmts[0]\n html = html -\n || '<'tag'>'elmts[e_]'</'tag'>\\n' -\n || ''\n end e_\n html = html -\n || '</tr>\\n' -\n || ''\n return html\n", "language": "NetRexx" }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en-US\" xml:lang=\"en-US\">\n<head>\n<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\"/>\n<title>RCsv2Html</title>\n<style type=\"text/css\">\n<!--\n/* <![DATA[ */\nbody {\n font-family: \"Verdana\", \"Geneva\", \"Helvetica Neue\", \"Helvetica\", \"DejaVu Sans\", \"Arial\", sans-serif;\n}\ntable, th, td {\n border: 1px solid black;\n border-collapse: collapse;\n padding: 0.25em;\n font-size: 85%;\n}\nth {\n color: white;\n background-color: green;\n}\np.classname {\n font-size: inherit;\n}\n/* ]] */\n//-->\n</style>\n</head>\n<body>\n<h1>Rosetta Code &ndash; NetRexx Sample Output</h2>\n<h2><a href=\"http://rosettacode.org/wiki/CSV_to_HTML_translation\">CSV to HTML translation</a></h2>\n\n<h3>Contents of CSV <code>./data/Brian.csv</code></h3>\n<pre>\nCharacter,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\n</pre>\n\n<table>\n<caption>Contents of CSV <code>./data/Brian.csv</code></caption>\n<thead>\n<tr>\n<th>Character</th>\n<th>Speech</th>\n</tr>\n\n</thead>\n<tbody>\n<tr>\n<td>The multitude</td>\n<td>The messiah! Show us the messiah!</td>\n</tr>\n\n<tr>\n<td>Brians mother</td>\n<td>&lt;angry&gt;Now you listen here! He&apos;s not the messiah; he&apos;s a very naughty boy! Now go away!&lt;/angry&gt;</td>\n</tr>\n\n<tr>\n<td>The multitude</td>\n<td>Who are you?</td>\n</tr>\n\n<tr>\n<td>Brians mother</td>\n<td>I&apos;m his mother; that&apos;s who!</td>\n</tr>\n\n<tr>\n<td>The multitude</td>\n<td>Behold his mother! Behold his mother!</td>\n</tr>\n\n</tbody>\n</table>\n\n</body>\n</html>\n", "language": "NetRexx" }, { "code": "import cgi, strutils\n\nconst csvtext = \"\"\"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\"\"\"\n\nproc row2tr(row: string): string =\n result = \"<tr>\"\n let cols = xmlEncode(row).split(\",\")\n for col in cols:\n result.add \"<td>\"&col&\"</td>\"\n result.add \"</tr>\"\n\nproc csv2html(txt: string): string =\n result = \"<table summary=\\\"csv2html program output\\\">\\n\"\n for row in txt.splitLines():\n result.add \" <tbody>\"&row2tr(row)&\"</tbody>\\n\"\n result.add \"</table>\"\n\necho csv2html(csvtext)\n", "language": "Nim" }, { "code": "MODULE CSV2HTML;\nIMPORT\n Object,\n IO,\n IO:FileChannel,\n IO:TextRider,\n SB := ADT:StringBuffer,\n NPCT:Tools,\n NPCT:CGI:Utils,\n Ex := Exception,\n Out;\nVAR\n fileChannel: FileChannel.Channel;\n rd: TextRider.Reader;\n line: ARRAY 1024 OF CHAR;\n table: SB.StringBuffer;\n parts: ARRAY 2 OF STRING;\n\n PROCEDURE DoTableHeader(sb: SB.StringBuffer;parts: ARRAY OF STRING);\n BEGIN\n sb.Append(\"<tr><th>\"+Utils.EscapeHTML(parts[0])+\"</th><th>\"+Utils.EscapeHTML(parts[1])+\"</th></tr>\");\n sb.AppendLn\n END DoTableHeader;\n\n PROCEDURE DoTableRow(sb: SB.StringBuffer;parts: ARRAY OF STRING);\n BEGIN\n sb.Append(\"<tr><td>\"+Utils.EscapeHTML(parts[0])+\"</td><td>\"+Utils.EscapeHTML(parts[1])+\"</td></tr>\");\n sb.AppendLn\n END DoTableRow;\n\n PROCEDURE DoTable(sb: SB.StringBuffer): STRING;\n VAR\n aux: SB.StringBuffer;\n BEGIN\n aux := SB.New(\"<table>\");aux.AppendLn;\n RETURN aux.ToString() + sb.ToString() + \"</table>\";\n END DoTable;\n\nBEGIN\n TRY\n fileChannel := FileChannel.OpenUnbuffered(\"script.csv\",{FileChannel.read});\n CATCH Ex.Exception(ex):\n Out.Object(ex.GetMessage());Out.Ln;\n HALT(1)\n END;\n rd := TextRider.ConnectReader(fileChannel);\n (* Extract headers *)\n TRY\n rd.ReadLine(line);\n table := NEW(SB.StringBuffer,2048);\n Tools.Split(Object.NewLatin1(line),\",\",parts);\n DoTableHeader(table,parts);\n CATCH IO.Error(ex):\n Out.Object(ex.Name() + \": \" + ex.GetMessage());Out.Ln;\n HALT(2)\n END;\n\n (* Extract data *)\n LOOP\n TRY\n rd.ReadLine(line);\n IF (line[0] # 0X)THEN (* skip empty lines *)\n Tools.Split(Object.NewLatin1(line),\",\",parts);\n DoTableRow(table,parts)\n END\n CATCH IO.Error(ex):\n EXIT\n END\n END;\n Out.Object(DoTable(table));Out.Ln;\n fileChannel.Close()\nEND CSV2HTML.\n", "language": "Oberon" }, { "code": "use System.IO.File;\nuse Data.CSV;\n\nclass CsvToHtml {\n function : Main(args : String[]) ~ Nil {\n if(args->Size() = 1) {\n table := CsvTable->New(FileReader->ReadFile(args[0]));\n if(table->IsParsed()) {\n buffer := \"<html><body><table>\";\n Header(table->GetHeaders(), buffer);\n for(i := 1; i < table->Size(); i += 1;) {\n Data(table->Get(i), buffer);\n };\n buffer += \"</table></body></html>\";\n buffer->PrintLine();\n };\n };\n }\n\n function : Header(row : CsvRow, buffer : String) ~ Nil {\n buffer += \"<tr>\";\n each(i : row) {\n buffer += \"<th>\";\n buffer += Encode(row->Get(i));\n buffer += \"</th>\";\n };\n buffer += \"</tr>\";\n }\n\n function : Data(row : CsvRow, buffer : String) ~ Nil {\n buffer += \"<tr>\";\n each(i : row) {\n buffer += \"<td>\";\n buffer += Encode(row->Get(i));\n buffer += \"</td>\";\n };\n buffer += \"</tr>\";\n }\n\n function : Encode(in : String) ~ String {\n out := \"\";\n\n each(i : in) {\n c := in->Get(i);\n select(c) {\n label '&': {\n out->Append(\"&amp;\");\n\n }\n\n label '\\'': {\n out->Append(\"&apos;\");\n }\n\n label '<': {\n out->Append(\"&lt;\");\n }\n\n label '>': {\n out->Append(\"&gt;\");\n }\n\n other: {\n out->Append(c);\n }\n };\n };\n\n return out;\n }\n}\n", "language": "Objeck" }, { "code": "open Printf\n\nlet csv_data = \"\\\nCharacter,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; \\\n he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\"\n\n(* General HTML escape *)\nlet escape =\n let html_escapes = Str.regexp \"\\\\([^A-Za-z0-9 ;!?'/]\\\\)\" in\n let esc s = sprintf \"&#%04d;\" (Char.code s.[Str.group_beginning 1]) in\n Str.global_substitute html_escapes esc\n\nlet nl = Str.regexp \"\\n\\r?\"\nlet coma = Str.regexp \",\"\n\nlet list_of_csv csv =\n List.map (fun l -> Str.split coma l) (Str.split nl csv)\n\nlet print_html_table segments =\n printf \"<table>\\n\";\n List.iter (fun line ->\n printf \"<tr>\";\n List.iter (fun c -> printf \"<td>%s</td>\" (escape c)) line;\n printf \"</tr>\\n\";\n ) segments;\n printf \"</table>\\n\";\n;;\n\nlet () =\n print_html_table (list_of_csv csv_data)\n", "language": "OCaml" }, { "code": "<table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&#0060;angry&#0062;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&#0060;/angry&#0062;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "OCaml" }, { "code": "open Printf\n\nlet csv_data = \"\\\nCharacter,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; \\\n he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\"\n\n(* General HTML escape *)\nlet escape =\n let html_escapes = Str.regexp \"\\\\([^A-Za-z0-9 ;!?'/]\\\\)\" in\n let esc s = sprintf \"&#%04d;\" (Char.code s.[Str.group_beginning 1]) in\n Str.global_substitute html_escapes esc\n\nlet nl = Str.regexp \"\\n\\r?\"\nlet coma = Str.regexp \",\"\n\nlet list_of_csv csv =\n List.map (fun l -> Str.split coma l) (Str.split nl csv)\n\nlet print_html_table segments =\n let print_row line =\n printf \"<tr>\";\n List.iter (fun c -> printf \"<td>%s</td>\" (escape c)) line;\n printf \"</tr>\\n\" in\n printf \"<html>\n <head>\n <style type=\\\"text/css\\\">\n td {background-color:#ddddff; }\n thead td {background-color:#ddffdd; text-align:center; }\n </style>\n </head>\";\n printf \"<table>\\n<thead>\";\n print_row (List.hd segments);\n printf \"</thead><tbody>\\n\";\n List.iter print_row (List.tl segments);\n printf \"</tbody>\\n</table>\\n</html>\";\n;;\n\nlet () =\n print_html_table (list_of_csv csv_data)\n", "language": "OCaml" }, { "code": "<html>\n <head>\n <style type=\"text/css\">\n td {background-color:#ddddff; }\n thead td {background-color:#ddffdd; text-align:center; }\n </style>\n </head><table>\n<thead><tr><td>Character</td><td>Speech</td></tr>\n</thead><tbody>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&#0060;angry&#0062;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&#0060;/angry&#0062;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</tbody>\n</table>\n</html>\n", "language": "OCaml" }, { "code": "FUNCTION csvToHtml RETURNS CHARACTER (\n i_lhas_header AS LOGICAL,\n i_cinput AS CHARACTER\n):\n\n DEFINE VARIABLE coutput AS CHARACTER NO-UNDO.\n\n DEFINE VARIABLE irow AS INTEGER NO-UNDO.\n DEFINE VARIABLE icolumn AS INTEGER NO-UNDO.\n DEFINE VARIABLE crow AS CHARACTER NO-UNDO.\n DEFINE VARIABLE ccell AS CHARACTER NO-UNDO.\n\n coutput = \"<html>~n~t<table>\".\n\n DO irow = 1 TO NUM-ENTRIES( i_cinput, \"~n\":U ):\n\n coutput = coutput + \"~n~t~t<tr>\".\n\n crow = ENTRY( irow, i_cinput, \"~n\":U ).\n\n DO icolumn = 1 TO NUM-ENTRIES( crow ):\n ccell = ENTRY( icolumn, crow ).\n\n coutput = coutput + \"~n~t~t~t\" + IF i_lhas_header AND irow = 1 THEN \"<th>\" ELSE \"<td>\".\n coutput = coutput + REPLACE( REPLACE( REPLACE( ccell, \"&\", \"&amp;\" ), \"<\", \"&lt;\" ), \">\", \"&gt;\" ).\n coutput = coutput + IF i_lhas_header AND irow = 1 THEN \"</th>\" ELSE \"</td>\".\n\n END.\n\n coutput = coutput + \"~n~t~t</tr>\".\n\n END.\n\n coutput = coutput + \"~n~t</table>~n</html>\".\n\n RETURN coutput.\n\nEND FUNCTION. /* csvToHtml */\n\nMESSAGE\n csvToHtml(\n TRUE,\n \"Character,Speech\" + \"~n\" +\n \"The multitude,The messiah! Show us the messiah!\" + \"~n\" +\n \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\" + \"~n\" +\n \"The multitude,Who are you?\" + \"~n\" +\n \"Brians mother,I'm his mother; that's who!\" + \"~n\" +\n \"The multitude,Behold his mother! Behold his mother!\"\n )\nVIEW-AS ALERT-BOX.\n", "language": "OpenEdge-Progress" }, { "code": "<html>\n\t<table>\n\t\t<tr>\n\t\t\t<th>Character</th>\n\t\t\t<th>Speech</th>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>The multitude</td>\n\t\t\t<td>The messiah! Show us the messiah!</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>Brians mother</td>\n\t\t\t<td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>The multitude</td>\n\t\t\t<td>Who are you?</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>Brians mother</td>\n\t\t\t<td>I'm his mother; that's who!</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>The multitude</td>\n\t\t\t<td>Behold his mother! Behold his mother!</td>\n\t\t</tr>\n\t</table>\n</html>\n", "language": "OpenEdge-Progress" }, { "code": "use HTML::Entities;\n\nsub row {\n my $elem = shift;\n my @cells = map {\"<$elem>$_</$elem>\"} split ',', shift;\n print '<tr>', @cells, \"</tr>\\n\";\n}\n\nmy ($first, @rest) = map\n {my $x = $_; chomp $x; encode_entities $x}\n <STDIN>;\nprint \"<table>\\n\";\nrow @ARGV ? 'th' : 'td', $first;\nrow 'td', $_ foreach @rest;\nprint \"</table>\\n\";\n", "language": "Perl" }, { "code": "<table>\n<tr><th>Character</th><th>Speech</th></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He&#39;s not the messiah; he&#39;s a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I&#39;m his mother; that&#39;s who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with javascript_semantics</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">input</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"\"\n Character,Speech\n The multitude,The messiah! Show us the messiah!\n Brians mother,&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;\n The multitude,Who are you?\n Brians mother,I'm his mother; that's who!\n The multitude,Behold his mother! Behold his mother!\"\"\"</span>\n\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"&lt;table&gt;\\n&lt;tr&gt;&lt;td&gt;\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008000;\">'\\n'</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"&lt;/td&gt;&lt;/tr&gt;\\n&lt;tr&gt;&lt;td&gt;\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008000;\">','</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"&lt;/td&gt;&lt;td&gt;\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008000;\">'&lt;'</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"&amp;lt;\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008000;\">'&gt;'</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"&amp;gt;\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008000;\">'&'</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"&amp;amp;\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008080;\">else</span> <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"&lt;/td&gt;&lt;/tr&gt;\\n&lt;/table&gt;\"</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "(load \"@lib/http.l\")\n\n(in \"text.csv\"\n (<table> 'myStyle NIL NIL\n (prinl)\n (while (split (line) \",\")\n (<row> NIL (ht:Prin (pack (car @))) (ht:Prin (pack (cadr @))))\n (prinl) ) ) )\n", "language": "PicoLisp" }, { "code": "<table class=\"myStyle\">\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "PicoLisp" }, { "code": "(load \"@lib/http.l\")\n\n(in \"text.csv\"\n (when (split (line) \",\")\n (<table> 'myStyle NIL (mapcar '((S) (list NIL (pack S))) @)\n (prinl)\n (while (split (line) \",\")\n (<row> NIL (ht:Prin (pack (car @))) (ht:Prin (pack (cadr @))))\n (prinl) ) ) ) )\n", "language": "PicoLisp" }, { "code": "<table class=\"myStyle\"><tr><th>Character</th><th>Speech</th></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "PicoLisp" }, { "code": "Import-Csv -Path .\\csv_html_test.csv | ConvertTo-Html -Fragment | Out-File .\\csv_html_test.html\n", "language": "PowerShell" }, { "code": "<table>\n<colgroup>\n<col/>\n<col/>\n</colgroup>\n<tr><th>Character</th><th>Speech </th></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah! </td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt; </td></tr>\n\n<tr><td>The multitude</td><td>Who are you? </td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who! </td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother! </td></tr>\n</table>\n", "language": "PowerShell" }, { "code": "$htmlformat = '<title>Csv to Html</title>'\n$htmlformat += '<style type=\"text/css\">'\n$htmlformat += 'BODY{background-color:#663300;color:#FFCC00;font-family:Arial Narrow,sans-serif;font-size:17px;}'\n$htmlformat += 'TABLE{border-width: 3px;border-style: solid;border-color: black;border-collapse: collapse;}'\n$htmlformat += 'TH{border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color:#663333}'\n$htmlformat += 'TD{border-width: 1px;padding: 8px;border-style: solid;border-color: black;background-color:#660033}'\n$htmlformat += '</style>'\nImport-Csv -Path .\\csv_html_test.csv | ConvertTo-Html -Head $htmlformat -Body '<h1>Csv to Html</h1>' | Out-File .\\csv_html_test.html\nInvoke-Expression .\\csv_html_test.html\n", "language": "PowerShell" }, { "code": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<title>Csv to Html</title><style type=\"text/css\">BODY{background-color:#663300;color:#FFCC00;font-family:Arial Narrow,sans-serif;font-size:17px;}TABLE{border-width: 3px;border-style: solid;border-color: black;border-collapse: collapse;}TH{border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color:#663333}TD{border-width: 1px;padding: 8px;border-style: solid;border-color: black;background-color:#660033}</style>\n</head><body>\n<h1>Csv to Html</h1>\n<table>\n<colgroup>\n<col/>\n<col/>\n</colgroup>\n<tr><th>Character</th><th>Speech </th></tr>\n\n<tr><td>The multitude</td><td>The messiah! Show us the messiah! </td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt; </td></tr>\n<tr><td>The multitude</td><td>Who are you? </td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who! </td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother! </td></tr>\n\n</table>\n</body></html>\n", "language": "PowerShell" }, { "code": "csv_html :-\n\tL = \"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\",\n\n\tcsv_html(L, Out, []),\n\tstring_to_list(Str, Out),\n\twriteln(Str).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% simple HTML\n%\ncsv_html(L) -->\n\t\"<TABLE>\\n\",\n\tcsv_tr(L),\n\t\"</TABLE>\".\n\ncsv_tr([]) --> [].\n\ncsv_tr(L) -->\n\t\"<TR>\\n\",\n\tcsv_td(L, S),\n\t\"\\n</TR>\\n\",\n\tcsv_tr(S).\n\ncsv_td(L, S) -->\n\t\"<TD>\",\n\tcsv_td_in(L, S),\n\t\"</TD>\".\n\ncsv_td_in([], []) --> [].\n\ncsv_td_in([10|L], L) --> [].\n\ncsv_td_in([44|L], S) -->\n\t\"</TD><TD>\",\n\tcsv_td_in(L,S).\n\ncsv_td_in([60|T], S) -->\n\t\"&lt;\",\n\tcsv_td_in(T, S).\n\ncsv_td_in([62|T], S) -->\n\t\"&gt;\",\n\tcsv_td_in(T, S).\n\ncsv_td_in([H|T], S) -->\n\t[H],\n\tcsv_td_in(T, S).\n", "language": "Prolog" }, { "code": "<TABLE>\n<TR>\n<TD>Character</TD><TD>Speech</TD>\n</TR>\n<TR>\n<TD>The multitude</TD><TD>The messiah! Show us the messiah!</TD>\n</TR>\n<TR>\n<TD>Brians mother</TD><TD>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!>&lt;/angry&gt;</TD>\n</TR>\n<TR>\n<TD>The multitude</TD><TD>Who are you?</TD>\n</TR>\n<TR>\n<TD>Brians mother</TD><TD>I'm his mother; that's who!</TD>\n</TR>\n<TR>\n<TD>The multitude</TD><TD>Behold his mother! Behold his mother!</TD>\n</TR>\n</TABLE>\n", "language": "Prolog" }, { "code": "csv_html_plus :-\n\tL =\n\"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\",\n\n\tcsv_html_plus(L, Out1, []),\n\tstring_to_list(Str1, Out1),\n\twriteln(Str1).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% HTML +\n%\ncsv_html_plus(L) -->\n\t\"<TABLE>\\n\",\n\tcsv_head(L, R),\n\tcsv_body(R),\n\t\"</TABLE>\".\n\n\ncsv_head(L, R) -->\n\t\"<THEAD>\\n\",\n\tcsv_head_tr(L, R),\n\t\"</THEAD>\\n\".\n\n\ncsv_head_tr(L, R) -->\n\t\"<TR>\\n\",\n\tcsv_head_th(L, R),\n\t\"\\n</TR>\\n\".\n\n\ncsv_head_th(L, S) -->\n\t\"<TH style='color:#000; background:#FF0;'>\",\n\tcsv_head_th_in(L, S),\n\t\"</TH>\".\n\ncsv_head_th_in([], []) --> [].\n\ncsv_head_th_in([10|L], L) --> [].\n\ncsv_head_th_in([44|L], S) -->\n\t\"</TH><TH style='color:#000; background:#FF0;'>\",\n\tcsv_head_th_in(L,S).\n\ncsv_head_th_in([H|T], S) -->\n\t[H],\n\tcsv_head_th_in(T, S).\n\n\ncsv_body(L) -->\n\t\"<TBODY>\\n\",\n\tcsv_body_tr(L),\n\t\"</TBODY>\\n\".\n\ncsv_body_tr([]) --> [].\n\ncsv_body_tr(L) -->\n\t\"<TR>\\n\",\n\tcsv_body_td(L, S),\n\t\"\\n</TR>\\n\",\n\tcsv_body_tr(S).\n\ncsv_body_td(L, S) -->\n\t\"<TD style='color:#000; background:#8FF; border:1px #000 solid; padding:0.6em;'>\",\n\tcsv_body_td_in(L, S),\n\t\"</TD>\".\n\ncsv_body_td_in([], []) --> [].\n\ncsv_body_td_in([10|L], L) --> [].\n\ncsv_body_td_in([44|L], S) -->\n\t\"</TD><TD style='color:#000; background:#8FF; border:1px #000 solid; padding:0.6em;'>\",\n\tcsv_body_td_in(L,S).\n\ncsv_body_td_in([60|T], S) -->\n\t\"&lt;\",\n\tcsv_body_td_in(T, S).\n\ncsv_body_td_in([62|T], S) -->\n\t\"&gt;\",\n\tcsv_body_td_in(T, S).\n\ncsv_body_td_in([H|T], S) -->\n\t[H],\n\tcsv_body_td_in(T, S).\n", "language": "Prolog" }, { "code": "<TABLE>\n<THEAD>\n<TR>\n<TH style='color:#000; background:#FF0;'>Character</TH><TH style='color:#000; background:#FF0;'>Speech</TH>\n</TR>\n</THEAD>\n<TBODY>\n<TR>\n<TD style='color:#000; background:#8FF; border:1px #000 solid; padding:0.6em;'>The multitude</TD><TD style='color:#000; background:#8FF; border:1px #000 solid; padding:0.6em;'>The messiah! Show us the messiah!</TD>\n</TR>\n<TR>\n<TD style='color:#000; background:#8FF; border:1px #000 solid; padding:0.6em;'>Brians mother</TD><TD style='color:#000; background:#8FF; border:1px #000 solid; padding:0.6em;'>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!>&lt;/angry&gt;</TD>\n</TR>\n<TR>\n<TD style='color:#000; background:#8FF; border:1px #000 solid; padding:0.6em;'>The multitude</TD><TD style='color:#000; background:#8FF; border:1px #000 solid; padding:0.6em;'>Who are you?</TD>\n</TR>\n<TR>\n<TD style='color:#000; background:#8FF; border:1px #000 solid; padding:0.6em;'>Brians mother</TD><TD style='color:#000; background:#8FF; border:1px #000 solid; padding:0.6em;'>I'm his mother; that's who!</TD>\n</TR>\n<TR>\n<TD style='color:#000; background:#8FF; border:1px #000 solid; padding:0.6em;'>The multitude</TD><TD style='color:#000; background:#8FF; border:1px #000 solid; padding:0.6em;'>Behold his mother! Behold his mother!</TD>\n</TR>\n</TBODY>\n</TABLE>\n", "language": "Prolog" }, { "code": "csvtxt = '''\\\nCharacter,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\\\n'''\n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n cols = escape(row).split(',')\n return ('<TR>'\n + ''.join('<TD>%s</TD>' % data for data in cols)\n + '</TR>')\n\ndef csv2html(txt):\n htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n for rownum, row in enumerate(txt.split('\\n')):\n htmlrow = _row2tr(row)\n htmlrow = ' <TBODY>%s</TBODY>\\n' % htmlrow\n htmltxt += htmlrow\n htmltxt += '</TABLE>\\n'\n return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n", "language": "Python" }, { "code": "<TABLE summary=\"csv2html program output\">\n <TBODY><TR><TD>Character</TD><TD>Speech</TD></TR></TBODY>\n <TBODY><TR><TD>The multitude</TD><TD>The messiah! Show us the messiah!</TD></TR></TBODY>\n <TBODY><TR><TD>Brians mother</TD><TD>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</TD></TR></TBODY>\n <TBODY><TR><TD>The multitude</TD><TD>Who are you?</TD></TR></TBODY>\n <TBODY><TR><TD>Brians mother</TD><TD>I'm his mother; that's who!</TD></TR></TBODY>\n <TBODY><TR><TD>The multitude</TD><TD>Behold his mother! Behold his mother!</TD></TR></TBODY>\n</TABLE>\n", "language": "Python" }, { "code": "def _row2trextra(row, attr=None):\n cols = escape(row).split(',')\n attr_tr = attr.get('TR', '')\n attr_td = attr.get('TD', '')\n return (('<TR%s>' % attr_tr)\n + ''.join('<TD%s>%s</TD>' % (attr_td, data) for data in cols)\n + '</TR>')\n\ndef csv2htmlextra(txt, header=True, attr=None):\n ' attr is a dictionary mapping tags to attributes to add to that tag'\n\n attr_table = attr.get('TABLE', '')\n attr_thead = attr.get('THEAD', '')\n attr_tbody = attr.get('TBODY', '')\n htmltxt = '<TABLE%s>\\n' % attr_table\n for rownum, row in enumerate(txt.split('\\n')):\n htmlrow = _row2trextra(row, attr)\n rowclass = ('THEAD%s' % attr_thead) if (header and rownum == 0) else ('TBODY%s' % attr_tbody)\n htmlrow = ' <%s>%s</%s>\\n' % (rowclass, htmlrow, rowclass[:5])\n htmltxt += htmlrow\n htmltxt += '</TABLE>\\n'\n return htmltxt\n\nhtmltxt = csv2htmlextra(csvtxt, True,\n dict(TABLE=' border=\"1\" summary=\"csv2html extra program output\"',\n THEAD=' bgcolor=\"yellow\"',\n TBODY=' bgcolor=\"orange\"'\n )\n )\nprint(htmltxt)\n", "language": "Python" }, { "code": "<TABLE border=\"1\" summary=\"csv2html extra program output\">\n <THEAD bgcolor=\"yellow\"><TR><TD>Character</TD><TD>Speech</TD></TR></THEAD>\n <TBODY bgcolor=\"orange\"><TR><TD>The multitude</TD><TD>The messiah! Show us the messiah!</TD></TR></TBODY>\n <TBODY bgcolor=\"orange\"><TR><TD>Brians mother</TD><TD>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</TD></TR></TBODY>\n <TBODY bgcolor=\"orange\"><TR><TD>The multitude</TD><TD>Who are you?</TD></TR></TBODY>\n <TBODY bgcolor=\"orange\"><TR><TD>Brians mother</TD><TD>I'm his mother; that's who!</TD></TR></TBODY>\n <TBODY bgcolor=\"orange\"><TR><TD>The multitude</TD><TD>Behold his mother! Behold his mother!</TD></TR></TBODY>\n</TABLE>\n", "language": "Python" }, { "code": "from csv import DictReader\nfrom xml.etree import ElementTree as ET\n\ndef csv2html_robust(txt, header=True, attr=None):\n # Use DictReader because, despite what the docs say, reader() doesn't\n # return an object with .fieldnames\n # (DictReader expects an iterable that returns lines, so split on \\n)\n reader = DictReader(txt.split('\\n'))\n\n table = ET.Element(\"TABLE\", **attr.get('TABLE', {}))\n thead_tr = ET.SubElement(\n ET.SubElement(table, \"THEAD\", **attr.get('THEAD', {})),\n \"TR\")\n tbody = ET.SubElement(table, \"TBODY\", **attr.get('TBODY', {}))\n\n if header:\n for name in reader.fieldnames:\n ET.SubElement(thead_tr, \"TD\").text = name\n\n for row in reader:\n tr_elem = ET.SubElement(tbody, \"TR\", **attr.get('TR', {}))\n\n # Use reader.fieldnames to query `row` in the correct order.\n # (`row` isn't an OrderedDict prior to Python 3.6)\n for field in reader.fieldnames:\n td_elem = ET.SubElement(tr_elem, \"TD\", **attr.get('TD', {}))\n td_elem.text = row[field]\n\n return ET.tostring(table, method='html')\n\nhtmltxt = csv2html_robust(csvtxt, True, {\n 'TABLE': {'border': \"1\", 'summary': \"csv2html extra program output\"},\n 'THEAD': {'bgcolor': \"yellow\"},\n 'TBODY': {'bgcolor': \"orange\"}\n})\n\nprint(htmltxt.decode('utf8'))\n", "language": "Python" }, { "code": "<TABLE border=\"1\" summary=\"csv2html extra program output\"><THEAD bgcolor=\"yellow\"><TR><TD>Character</TD><TD>Speech</TD></TR></THEAD><TBODY bgcolor=\"orange\"><TR><TD>The multitude</TD><TD>The messiah! Show us the messiah!</TD></TR><TR><TD>Brians mother</TD><TD>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</TD></TR><TR><TD>The multitude</TD><TD>Who are you?</TD></TR><TR><TD>Brians mother</TD><TD>I'm his mother; that's who!</TD></TR><TR><TD>The multitude</TD><TD>Behold his mother! Behold his mother!</TD></TR></TBODY></TABLE>\n", "language": "Python" }, { "code": "File <- \"~/test.csv\"\nOpened <- readLines(con = File)\nSize <- length(Opened)\n\nHTML <- \"~/test.html\"\n\nTable <- list()\n\nfor(i in 1:Size)\n{\n #i=1\n Split <- unlist(strsplit(Opened[i],split = \",\"))\n Table[i] <- paste0(\"<td>\",Split,\"</td>\",collapse = \"\")\n Table[i] <- paste0(\"<tr>\",Table[i],\"</tr>\")\n}\n\nTable[1] <- paste0(\"<table>\",Table[1])\nTable[length(Table)] <- paste0(Table[length(Table)],\"</table>\")\n\nwriteLines(as.character(Table), HTML)\n", "language": "R" }, { "code": "<table><tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td><angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry></td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr></table>\n", "language": "R" }, { "code": "#lang racket\n\n(define e.g.-CSV\n (string-join\n '(\"Character,Speech\"\n \"The multitude,The messiah! Show us the messiah!\"\n \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\"\n \"The multitude,Who are you?\"\n \"Brians mother,I'm his mother; that's who!\"\n \"The multitude,Behold his mother! Behold his mother!\")\n \"\\n\"))\n\n(define (CSV-lines->HTML-table csv)\n (define csv-rows\n (regexp-split \"\\n\" csv))\n (define csv-row-cells\n (map (lambda (row) (regexp-split \",\" row)) csv-rows))\n (define (cell-data->HTML-data data)\n `(td () ,data))\n (define (row-data->HTML-row CSV-row)\n `(tr () ,@(map cell-data->HTML-data CSV-row) \"\\n\"))\n `(table\n (thead\n ,(row-data->HTML-row (car csv-row-cells)))\n (tbody ,@(map row-data->HTML-row (cdr csv-row-cells)))))\n\n(require xml)\n(display (xexpr->string (CSV-lines->HTML-table e.g.-CSV)))\n", "language": "Racket" }, { "code": "<table><thead><tr><td>Character</td><td>Speech</td>\n</tr></thead><tbody><tr><td>The multitude</td><td>The messiah! Show us the messiah!</td>\n</tr><tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td>\n</tr><tr><td>The multitude</td><td>Who are you?</td>\n</tr><tr><td>Brians mother</td><td>I'm his mother; that's who!</td>\n</tr><tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td>\n</tr></tbody></table>\n", "language": "Racket" }, { "code": "my $str = \"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\";\n\n# comment the next line out, if you want to read from standard input instead of the hard-coded $str above\n# my $str = $*IN.slurp;\n\nmy &escape = *.trans(« & < > » => « &amp; &lt; &gt; »); # a function with one argument that escapes the entities\nmy &tag = {\"<$^tag>\"~$^what~\"</$^tag>\"};\n\nprintf\n'<!DOCTYPE html>\n<html>\n<head><title>Some Text</title></head>\n<body><table>\n%s\n</table></body></html>\n', [~] # concatenation reduction ('a', 'b', 'c') → 'abc'\n(escape($str).split(/\\n/) # escape the string and split at newline\n ==> map -> $line {tag 'tr', # feed that into a map, that map function will tag as 'tr, and has an argument called $line\n ([~] $line.split(/','/)\\ # split $line at ',',\n # that / at the end is just an unspace, you can omit it, but then you have to delete\n # all whitespace and comments between split(…) and .map\n .map({tag 'td', $^cell}))})\\ # map those cells as td\n\t\t .join(\"\\n\"); # append a newline for nicer output\n", "language": "Raku" }, { "code": "<!DOCTYPE html>\n<html>\n<head><title>Some Text</title></head>\n<body><table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table></body></html>\n", "language": "Raku" }, { "code": "Red []\n\ncsv: {Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!}\n\nadd2html: func [ bl ] [append html rejoin bl ] ;; helper function to add block data to html string\n\n;;----------------------------------------------------------------------\ncsv2html: func [\"function to generate string with html table from csv data file\"\n;;----------------------------------------------------------------------\n s [string!] \"input .csv data\"\n][\narr: split s newline ;; generate array (series) from string\nhtml: copy \"<table border=1>^/\" ;; init html string\n\nforall arr [ ;; i use forall here so that i can test for head? of series ...\n either head? arr [ append html \"<tr bgcolor=wheat>\"]\n [ append html \"<tr>\"]\n replace/all first arr \"<\" \"&lt;\" ;; escape \"<\" and \">\" characters\n replace/all first arr \">\" \"&gt;\"\n foreach col split first arr \",\" [\n either head? arr [\n add2html ['<th> col '</th>]\n ][\n add2html ['<td> col '</td>]\n ]\n ]\n add2html ['</tr> newline]\n]\nreturn add2html ['</table>]\n]\n;;----------------------------------------------------------------------\n\nprint csv2html csv ;; call function\nwrite %data.html csv2html csv ;; write to file\n", "language": "Red" }, { "code": "remapping off\n\"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\" remapping on\nkeepString constant CSV\n\n: display ( c- )\n [ ', = ] [ drop \"</td><td>\" puts ] when\n [ 10 = ] [ drop \"</td></tr>\\n<tr><td>\" puts ] when\n [ '< = ] [ drop \"&lt;\" puts ] when\n [ '> = ] [ drop \"&gt;\" puts ] when\n [ '& = ] [ drop \"&amp;\" puts ] when\n putc ;\n\n: displayHTML ( $- )\n \"<table>\\n<tr><td>\" puts\n [ @ display ] ^types'STRING each@\n \"</td></tr>\\n</table>\" puts ;\n\nCSV displayHTML\n", "language": "Retro" }, { "code": "<table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "Retro" }, { "code": "/*REXX program converts CSV ───► HTML table representing the CSV data. */\narg header_ . /*obtain an uppercase version of args. */\nwantsHdr= (header_=='HEADER') /*is the arg (low/upp/mix case)=HEADER?*/\n /* [↑] determine if user wants a hdr. */\n iFID= 'CSV_HTML.TXT' /*the input fileID to be used. */\nif wantsHdr then oFID= 'OUTPUTH.HTML' /*the output fileID with header.*/\n else oFID= 'OUTPUT.HTML' /* \" \" \" without \" */\n\n do rows=0 while lines(iFID)\\==0 /*read the rows from a (text/txt) file.*/\n row.rows= strip( linein(iFID) )\n end /*rows*/\n\nconvFrom= '& < > \"' /*special characters to be converted. */\nconvTo = '&amp; &lt; &gt; &quot;' /*display what they are converted into.*/\n\ncall write , '<html>'\ncall write , '<table border=4 cellpadding=9 cellspacing=1>'\n\n do j=0 for rows; call write 5, '<tr>'\n tx= 'td'\n if wantsHdr & j==0 then tx= 'th' /*if user wants a header, then oblige. */\n\n do while row.j\\==''; parse var row.j yyy \",\" row.j\n do k=1 for words(convFrom)\n yyy=changestr( word( convFrom, k), yyy, word( convTo, k))\n end /*k*/\n call write 10, '<'tx\">\"yyy'</'tx\">\"\n end /*forever*/\n end /*j*/\n\ncall write 5, '<tr>'\ncall write , '</table>'\ncall write , '</html>'\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nwrite: call lineout oFID, left('', 0 || arg(1) )arg(2); return\n", "language": "REXX" }, { "code": "require 'cgi'\n\nputs '<table summary=\"csv2html program output\">'\n\ndef row2html str, wrap = \"td\"\n \"<tr>\" +\n str.split(\",\").map { |cell| \"<#{wrap}>#{CGI.escapeHTML cell}</#{wrap}>\" }.join +\n \"</tr>\"\nend\n\nputs row2html gets.chomp, \"th\" if ARGV.delete \"header\"\n\nwhile str = gets\n puts row2html str.chomp\nend\n\nputs \"</table>\"\n", "language": "Ruby" }, { "code": "<table summary=\"csv2html program output\">\n<tr><th>Character</th><th>Speech</th></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "Ruby" }, { "code": "csv$ = \"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\"\n\nk\t= instr(csv$,\",\") ' 2 exra lines to get heading\ncsv$ = left$(csv$,k - 1) + \"</th><th> + mid$(csv$,k + 1)\n\ncsv$ = strRep$(csv$,\",\",\"</td><td>\")\nhtml \"<table border=1><TR bgcolor=wheat align=center><th>\";strRep$(csv$,chr$(13),\"</td></tr><tr><td>\");\"</td></tr></table\"\nwait\n' --------------------------------\n' string replace rep str with\n' --------------------------------\nFUNCTION strRep$(strRep$,rep$,with$)\nln\t= len(rep$)\nk\t= instr(strRep$,rep$)\nwhile k\n\tstrRep$\t= left$(strRep$,k - 1) + with$ + mid$(strRep$,k + ln)\n\tk\t= instr(strRep$,rep$)\nWEND\nEND FUNCTION\n", "language": "Run-BASIC" }, { "code": "static INPUT : &'static str =\n\"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\";\n\nfn main() {\n print!(\"<table>\\n<tr><td>\");\n for c in INPUT.chars() {\n match c {\n '\\n' => print!(\"</td></tr>\\n<tr><td>\"),\n ',' => print!(\"</td><td>\"),\n '<' => print!(\"&lt;\"),\n '>' => print!(\"&gt;\"),\n '&' => print!(\"&amp;\"),\n _ => print!(\"{}\", c)\n }\n }\n println!(\"</td></tr>\\n</table>\");\n}\n", "language": "Rust" }, { "code": "<table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "Rust" }, { "code": "object CsvToHTML extends App {\n val header = <head>\n <title>CsvToHTML</title>\n <style type=\"text/css\">\n td {{background-color:#ddddff; }} thead td {{background-color:#ddffdd; text-align:center; }}\n </style>\n </head>\n val csv =\n \"\"\"Character,Speech\n |The multitude,The messiah! Show us the messiah!\n |Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n |The multitude,Who are you?\n |Brians mother,I'm his mother; that's who!\n |The multitude,Behold his mother! Behold his mother!\"\"\".stripMargin\n\n def csv2html(csv: String, withHead: Boolean) = {\n\n def processRow(text: String) = <tr>\n {text.split(',').map(s => <td>\n {s}\n </td>)}\n </tr>\n\n val (first :: rest) = csv.lines.toList // Separate the header and the rest\n\n def tableHead = if (withHead)\n <thead>\n {processRow(first)}\n </thead>\n else processRow(first)\n\n <html>\n {header}<body>\n <table>\n {tableHead}{rest.map(processRow)}\n </table>\n </body>\n </html>\n }\n\n println(csv2html(csv, true))\n}\n", "language": "Scala" }, { "code": "<html>\n <head>\n <title>CsvToHTML</title>\n <style type=\"text/css\">\n td {background-color:#ddddff; } thead td {background-color:#ddffdd; text-align:center; }\n </style>\n </head><body>\n <table>\n <thead>\n <tr>\n <td>\n Character\n </td><td>\n Speech\n </td>\n </tr>\n </thead><tr>\n <td>\n The multitude\n </td><td>\n The messiah! Show us the messiah!\n </td>\n </tr><tr>\n <td>\n Brians mother\n </td><td>\n &lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;\n </td>\n </tr><tr>\n <td>\n The multitude\n </td><td>\n Who are you?\n </td>\n </tr><tr>\n <td>\n Brians mother\n </td><td>\n I'm his mother; that's who!\n </td>\n </tr><tr>\n <td>\n The multitude\n </td><td>\n Behold his mother! Behold his mother!\n </td>\n </tr>\n </table>\n </body>\n </html>\n", "language": "Scala" }, { "code": "#!/bin/sed -f\n\ns|<|\\&lt;|g\ns|>|\\&gt;|g\ns|^| <tr>\\n <td>|\ns|,|</td>\\n <td>|\ns|$|</td>\\n </tr>|\n1s|^|<table>\\n|\n$s|$|\\n</table>|\n", "language": "Sed" }, { "code": "<table>\n <tr>\n <td>Character</td>\n <td>Speech</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Who are you?</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>I'm his mother; that's who!</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n</table>\n", "language": "Sed" }, { "code": "$ include \"seed7_05.s7i\";\n include \"html_ent.s7i\";\n\nconst string: csvData is \"\\\n \\Character,Speech\\n\\\n \\The multitude,The messiah! Show us the messiah!\\n\\\n \\Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\\\n \\The multitude,Who are you?\\n\\\n \\Brians mother,I'm his mother; that's who!\\n\\\n \\The multitude,Behold his mother! Behold his mother!\\n\";\n\nconst proc: main is func\n local\n var string: line is \"\";\n var string: column is \"\";\n const array [boolean] string: columnStartTag is [boolean] (\"<td>\", \"<th>\");\n const array [boolean] string: columnEndTag is [boolean] (\"</td>\", \"</th>\");\n var boolean: firstLine is TRUE;\n begin\n writeln(\"<table>\");\n for line range split(csvData, '\\n') do\n write(\"<tr>\");\n for column range split(line, ',') do\n write(columnStartTag[firstLine] <& encodeHtmlContent(column) <& columnEndTag[firstLine]);\n end for;\n writeln(\"</tr>\");\n firstLine := FALSE;\n end for;\n writeln(\"</table>\");\n end func;\n", "language": "Seed7" }, { "code": "<table>\n<tr><th>Character</th><th>Speech</th></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry></td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n<tr><td></td></tr>\n</table>\n", "language": "Seed7" }, { "code": "func escape(str) { str.trans(« & < > », « &amp; &lt; &gt; ») }\nfunc tag(t, d) { \"<#{t}>#{d}</#{t}>\" }\n\nfunc csv2html(str) {\n\n var template = <<-'EOT'\n <!DOCTYPE html>\n <html>\n <head><title>Some Text</title></head>\n <body><table>\n %s\n </table></body></html>\n EOT\n\n template.sprintf(escape(str).lines.map{ |line|\n tag('tr', line.split(',').map{|cell| tag('td', cell) }.join)\n }.join(\"\\n\")\n )\n}\n\nvar str = <<'EOT';\nCharacter,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\nEOT\n\nprint csv2html(str)\n", "language": "Sidef" }, { "code": "<!DOCTYPE html>\n<html>\n<head><title>Some Text</title></head>\n<body><table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table></body></html>\n", "language": "Sidef" }, { "code": "package require Tcl 8.5\npackage require csv\npackage require html\npackage require struct::queue\n\nset csvData \"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\"\n\nstruct::queue rows\nforeach line [split $csvData \"\\n\"] {\n csv::split2queue rows $line\n}\nhtml::init\nputs [subst {\n [html::openTag table {summary=\"csv2html program output\"}]\n [html::while {[rows size]} {\n\t[html::row {*}[html::quoteFormValue [rows get]]]\n }]\n [html::closeTag]\n}]\n", "language": "Tcl" }, { "code": "package require Tcl 8.5\npackage require csv\npackage require html\npackage require struct::queue\n\nset csvData \"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\"\n\nhtml::init {\n table.border 1\n table.summary \"csv2html program output\"\n tr.bgcolor orange\n}\n\n# Helpers; the html package is a little primitive otherwise\nproc table {contents {opts \"\"}} {\n set out [html::openTag table $opts]\n append out [uplevel 1 [list subst $contents]]\n append out [html::closeTag]\n}\nproc tr {list {ropt \"\"}} {\n set out [html::openTag tr $ropt]\n foreach x $list {append out [html::cell \"\" $x td]}\n append out [html::closeTag]\n}\n\n# Parse the CSV data\nstruct::queue rows\nforeach line [split $csvData \"\\n\"] {\n csv::split2queue rows $line\n}\n\n# Generate the output\nputs [subst {\n [table {\n\t[tr [html::quoteFormValue [rows get]] {bgcolor=\"yellow\"}]\n\t[html::while {[rows size]} {\n\t [tr [html::quoteFormValue [rows get]]]\n\t}]\n }]\n}]\n", "language": "Tcl" }, { "code": "<table border=\"1\" summary=\"csv2html program output\">\n <tr bgcolor=\"yellow\"><td>Character</td><td>Speech</td></tr>\n <tr bgcolor=\"orange\"><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n <tr bgcolor=\"orange\"><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He&#39;s not the messiah; he&#39;s a very naughty boy! Now go away! &lt;/angry&gt;</td></tr>\n <tr bgcolor=\"orange\"><td>The multitude</td><td>Who are you?</td></tr>\n <tr bgcolor=\"orange\"><td>Brians mother</td><td>I&#39;m his mother; that&#39;s who!</td></tr>\n <tr bgcolor=\"orange\"><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "Tcl" }, { "code": "$$ MODE TUSCRIPT\nMODE DATA\n$$ csv=*\nCharacter,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\n$$ htmlhead=*\n<!DOCTYPE html system>\n<html>\n<head>\n<title>Life of Brian</title>\n<style type=\"text/css\">\nth {background-color:orange}\ntd {background-color:yellow}\n</style></head><body><table>\n$$ BUILD X_TABLE txt2html=*\n << &lt;\n >> &gt;\n$$ MODE TUSCRIPT\nfile=\"brian.html\"\nERROR/STOP CREATE (file,FDF-o,-std-)\ncsv=EXCHANGE (csv,txt2html)\nx=SPLIT (csv,\":,:\",row1,row2)\nACCESS html: WRITE/ERASE/RECORDS/UTF8 $file s,html\nWRITE html htmlhead\nLOOP n,td1=row1,td2=row2\nIF (n==1) THEN\nrow=CONCAT (\"<tr><th>\",td1,\"</th><th>\",td2,\"</th></tr>\")\nELSE\nrow=CONCAT (\"<tr><td>\",td1,\"</td><td>\",td2,\"</td></tr>\")\nENDIF\nWRITE html row\nENDLOOP\nWRITE html \"</table></body></html>\"\nENDACCESS/PRINT html\n", "language": "TUSCRIPT" }, { "code": "<!DOCTYPE html system>\n<html>\n<head>\n<title>Life of Brian</title>\n<style type=\"text/css\">\nth {background-color:orange}\ntd {background-color:yellow}\n</style></head><body><table>\n<tr><th>Character</th><th>Speech</th></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table></body></html>\n", "language": "TUSCRIPT" }, { "code": "@(collect)\n@char,@speech\n@(end)\n@(output :filter :to_html)\n<table>\n@ (repeat)\n <tr>\n <td>@char</td>\n <td>@speech</td>\n </tr>\n@ (end)\n</table>\n@(end)\n", "language": "TXR" }, { "code": "<table>\n <tr>\n <td>Character</td>\n <td>Speech</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Who are you?</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>I'm his mother; that's who!</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n</table>\n", "language": "TXR" }, { "code": "@(collect)\n@char,@speech\n@(end)\n@(output :filter :to_html)\n<style type=\"text/css\">\ntr.odd td {\n background-color: #CC9999; color: black;\n}\ntr.even td {\n background-color: #9999CC; color: black;\n}\nth {\n background-color: #99CC99; color: black;\n}\n</style>\n<table>\n@ (repeat :counter row)\n <tr class=\"@(if (evenp row) 'even 'odd)\">\n <td>@char</td>\n <td>@speech</td>\n </tr>\n@ (first)\n <tr>\n <th>@char</th>\n <th>@speech</th>\n </tr>\n@ (end)\n</table>\n@(end)\n", "language": "TXR" }, { "code": "<style type=\"text/css\">\ntr.odd td {\n background-color: #CC9999; color: black;\n}\ntr.even td {\n background-color: #9999CC; color: black;\n}\nth {\n background-color: #99CC99; color: black;\n}\n</style>\n<table>\n <tr>\n <th>Character</th>\n <th>Speech</th>\n </tr>\n <tr class=\"odd\">\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr class=\"even\">\n <td>Brians mother</td>\n <td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td>\n </tr>\n <tr class=\"odd\">\n <td>The multitude</td>\n <td>Who are you?</td>\n </tr>\n <tr class=\"even\">\n <td>Brians mother</td>\n <td>I'm his mother; that's who!</td>\n </tr>\n <tr class=\"odd\">\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n</table>\n", "language": "TXR" }, { "code": "csv2html() {\n IFS=,\n echo \"<table>\"\n\n echo \"<thead>\"\n read -a fields\n htmlrow th \"${fields[@]}\"\n echo \"</thead>\"\n\n echo \"<tbody>\"\n while read -a fields\n do htmlrow td \"${fields[@]}\"\n done\n echo \"</tbody>\"\n echo \"</table>\"\n}\n\nhtmlrow() {\n cell=$1\n shift\n echo \"<tr>\"\n for field\n do echo \"<$cell>$(escape_html \"$field\")</$cell>\"\n done\n echo \"</tr>\"\n}\n\nescape_html() {\n str=${1//\\&/&amp;}\n str=${str//</&lt;}\n str=${str//>/&gt;}\n echo \"$str\"\n}\n\ncsv2html <<-END\nCharacter,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\nEND\n", "language": "UNIX-Shell" }, { "code": "<table>\n<thead>\n<tr>\n<th>Character</th>\n<th>Speech</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>The multitude</td>\n<td>The messiah! Show us the messiah!</td>\n</tr>\n<tr>\n<td>Brians mother</td>\n<td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td>\n</tr>\n<tr>\n<td>The multitude</td>\n<td>Who are you?</td>\n</tr>\n<tr>\n<td>Brians mother</td>\n<td>I'm his mother; that's who!</td>\n</tr>\n<tr>\n<td>The multitude</td>\n<td>Behold his mother! Behold his mother!</td>\n</tr>\n</tbody>\n</table>\n", "language": "UNIX-Shell" }, { "code": "Public Sub CSV_TO_HTML()\n input_ = \"Character,Speech\\n\" & _\n \"The multitude,The messiah! Show us the messiah!\\n\" & _\n \"Brians mother,<angry>Now you listen here! He's not the messiah; \" & _\n \"he's a very naughty boy! Now go away!</angry>\\n\" & _\n \"The multitude,Who are you?\\n\" & _\n \"Brians mother,I'm his mother; that's who!\\n\" & _\n \"The multitude,Behold his mother! Behold his mother!\"\n\n Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n For i = 1 To Len(input_)\n Select Case Mid(input_, i, 1)\n Case \"\\\"\n If Mid(input_, i + 1, 1) = \"n\" Then\n Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n i = i + 1\n Else\n Debug.Print Mid(input_, i, 1);\n End If\n Case \",\": Debug.Print \"</td><td>\";\n Case \"<\": Debug.Print \"&lt;\";\n Case \">\": Debug.Print \"&gt;\";\n Case \"&\": Debug.Print \"&amp;\";\n Case Else: Debug.Print Mid(input_, i, 1);\n End Select\n Next i\n Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n", "language": "VBA" }, { "code": "<table>\n<tr><td>\nCharacter</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "VBA" }, { "code": "Set objfso = CreateObject(\"Scripting.FileSystemObject\")\n\nparent_folder = objfso.GetParentFolderName(WScript.ScriptFullName) & \"\\\"\n\nSet objcsv = objfso.OpenTextFile(parent_folder & \"in.csv\",1,False)\nSet objhtml = objfso.OpenTextFile(paren_folder & \"out.html\",2,True)\n\nobjhtml.Write(csv_to_html(objcsv.ReadAll))\n\nobjcsv.Close\nobjhtml.Close\nSet objfso = Nothing\n\nFunction csv_to_html(s)\n\trow = Split(s,vbCrLf)\n\t'write the header\n\ttmp = \"<html><head><head/><body><table border=1 cellpadding=10 cellspacing=0>\"\n\tFor i = 0 To UBound(row)\n\t\tfield = Split(row(i),\",\")\n\t\tIf i = 0 Then\n\t\t\ttmp = tmp & \"<tr><th>\" & replace_chars(field(0)) & \"</th><th>\" & replace_chars(field(1)) & \"</th><tr>\"\t\t\n\t\tElse\n\t\t\ttmp = tmp & \"<tr><td>\" & replace_chars(field(0)) & \"</td><td>\" & replace_chars(field(1)) & \"</td><tr>\"\n\t\tEnd If\n\tNext\n\t'write the footer\n\ttmp = tmp & \"</table></body></html>\"\n\tcsv_to_html = tmp\nEnd Function\n\nFunction replace_chars(s)\n\treplace_chars = Replace(Replace(s,\"<\",\"&lt;\"),\">\",\"&gt;\")\nEnd Function\n", "language": "VBScript" }, { "code": "if (BB < 0) { // block not set\n BB(0) // convert entire file\n BE(File_Size)\n}\n\n// Convert special characters into entities\nReplace_Block(\"&\",\"&amp;\", BB, BE, BEGIN+ALL+NOERR)\nReplace_Block(\"<\",\"&lt;\", BB, BE, BEGIN+ALL+NOERR)\nReplace_Block(\">\",\"&gt;\", BB, BE, BEGIN+ALL+NOERR)\n\n// Convert CSV into HTML table\nGoto_Pos(BB)\nIT('<table>') IN\n#80 = Cur_Pos\nGoto_Pos(BE)\nIT(\"</table>\")\n#81 = Cur_Line\nIN\nGoto_Pos(#80)\nwhile (Cur_Line < #81) {\n IT(\" <tr><td>\")\n Replace_Block(\",\",\"</td><td>\",Cur_Pos,EOL_Pos,ALL+NOERR)\n EOL\n IT(\"</td></tr>\")\n Line(1)\n}\nBB(Clear)\n", "language": "Vedit-macro-language" }, { "code": "<table>\n <tr><td>Character</td><td>Speech </td></tr>\n <tr><td>The multitude</td><td>The messiah! Show us the messiah! </td></tr>\n <tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt; </td></tr>\n <tr><td>The multitude</td><td>Who are you? </td></tr>\n <tr><td>Brians mother</td><td>I'm his mother; that's who! </td></tr>\n <tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table>\n", "language": "Vedit-macro-language" }, { "code": "Imports Microsoft.VisualBasic.FileIO\n\nModule Program\n Sub Main(args As String())\n Dim parser As TextFieldParser\n Try\n If args.Length > 1 Then\n parser = My.Computer.FileSystem.OpenTextFieldParser(args(1), \",\")\n Else\n parser = New TextFieldParser(Console.In) With {.Delimiters = {\",\"}}\n End If\n\n Dim getLines =\n Iterator Function() As IEnumerable(Of String())\n Do Until parser.EndOfData\n Yield parser.ReadFields()\n Loop\n End Function\n\n Dim result = CSVTOHTML(getLines(), If(args.Length > 0, Boolean.Parse(args(0)), False))\n\n Console.WriteLine(result)\n Finally\n If parser IsNot Nothing Then parser.Dispose()\n End Try\n End Sub\n\n Function CSVTOHTML(lines As IEnumerable(Of IEnumerable(Of String)), useTHead As Boolean) As XElement\n Dim getRow = Function(row As IEnumerable(Of String)) From field In row Select <td><%= field %></td>\n\n CSVTOHTML =\n<table>\n <%= From l In lines.Select(\n Function(line, i)\n If useTHead AndAlso i = 0 Then\n Return <thead><%= getRow(line) %></thead>\n Else\n Return <tr><%= getRow(line) %></tr>\n End If\n End Function) %>\n</table>\n End Function\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\n^Z\n^Z\n<table>\n <thead>\n <td>Character</td>\n <td>Speech</td>\n </thead>\n <tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Who are you?</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>I'm his mother; that's who!</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n</table>\n", "language": "Visual-Basic-.NET" }, { "code": "var csv =\n \"Character,Speech\\n\" +\n \"The multitude,The messiah! Show us the messiah!\\n\" +\n \"Brians mother,<angry>Now you listen here! He's not the messiah; \" +\n \"he's a very naughty boy! Now go away!</angry>\\n\" +\n \"The multitude,Who are you?\\n\" +\n \"Brians mother,I'm his mother; that's who!\\n\" +\n \"The multitude,Behold his mother! Behold his mother!\"\n\nvar i = \" \" // indent\nvar ii = i + i // double indent\nvar iii = ii + i // triple indent\nvar sb = \"<table>\\n%(i)<tr>\\n%(ii)<td>\"\nfor (c in csv) {\n sb = sb + ((c == \"\\n\") ? \"</td>\\n%(i)</tr>\\n%(i)<tr>\\n%(ii)<td>\" :\n (c == \",\") ? \"</td>\\n%(ii)<td>\" :\n (c == \"&\") ? \"&amp;\" :\n (c == \"'\") ? \"&apos;\" :\n (c == \"<\") ? \"&lt;\" :\n (c == \">\") ? \"&gt;\" : c)\n}\nsb = sb + \"</td>\\n%(i)</tr>\\n</table>\"\nSystem.print(sb)\nSystem.print()\n\n// now using first row as a table header\nsb = \"<table>\\n%(i)<thead>\\n%(ii)<tr>\\n%(iii)<td>\"\nvar hLength = csv.indexOf(\"\\n\") + 1 // find length of first row including CR\nfor (c in csv.take(hLength)) {\n sb = sb + ((c == \"\\n\") ? \"</td>\\n%(ii)</tr>\\n%(i)</thead>\\n%(i)<tbody>\\n%(ii)<tr>\\n%(iii)<td>\" :\n (c == \",\") ? \"</td>\\n%(iii)<td>\" : c)\n}\nfor (c in csv.skip(hLength)) {\n sb = sb + ((c == \"\\n\") ? \"</td>\\n%(ii)</tr>\\n%(ii)<tr>\\n%(iii)<td>\" :\n (c == \",\") ? \"</td>\\n%(iii)<td>\" :\n (c == \"&\") ? \"&amp;\" :\n (c == \"'\") ? \"&apos;\" :\n (c == \"<\") ? \"&lt;\" :\n (c == \">\") ? \"&gt;\" : c)\n}\nsb = sb + \"</td>\\n%(ii)</tr>\\n%(i)</tbody>\\n</table>\"\nSystem.print(sb)\n", "language": "Wren" }, { "code": "string 0;\nchar Input, S;\n[Input:=\n\"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\";\n\nText(0, \"<table>^m^j<tr><td>\");\nS:= Input;\nwhile S(0) do\n [case S(0) of\n $0A: Text(0, \"</td></tr>^m^j<tr><td>\");\n ^,: Text(0, \"</td><td>\");\n ^<: Text(0, \"&lt;\");\n ^>: Text(0, \"&gt;\");\n ^&: Text(0, \"&amp;\")\n other ChOut(0, S(0));\n S:= S+1;\n ];\nText(0, \"</td></tr>^m^j</table>\");\n]\n", "language": "XPL0" }, { "code": "<xsl:stylesheet\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:xcsvt=\"http://www.seanbdurkin.id.au/xslt/csv-to-xml.xslt\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:xcsv=\"http://www.seanbdurkin.id.au/xslt/xcsv.xsd\"\n version=\"2.0\"\n exclude-result-prefixes=\"xsl xs xcsvt xcsv\">\n <xsl:import href=\"csv-to-xml.xslt\" />\n <xsl:output indent=\"yes\" encoding=\"UTF-8\" method=\"html\" doctype-system=\"about:legacy-compat\" />\n <xsl:import-schema schema-location=\"http://www.seanbdurkin.id.au/xslt/xcsv.xsd\"\n use-when=\"system-property('xsl:is-schema-aware')='yes'\" />\n <xsl:param name=\"url-of-csv\" as=\"xs:string\" select=\"'roseta.csv'\" />\n\n\n <xsl:variable name=\"phase-1-result\">\n <xsl:call-template name=\"xcsvt:main\" />\n </xsl:variable>\n\n <xsl:template match=\"/\">\n <html lang=\"en\">\n <head><title>CSV to HTML translation - Extra Credit</title></head>\n <body>\n <xsl:apply-templates select=\"$phase-1-result\" mode=\"phase-2\" />\n </body>\n </html>\n </xsl:template>\n\n <xsl:template match=\"xcsv:comma-separated-single-line-values\" mode=\"phase-2\">\n <table>\n <xsl:apply-templates mode=\"phase-2\" />\n </table>\n </xsl:template>\n\n <xsl:template match=\"xcsv:row[1]\" mode=\"phase-2\">\n <th>\n <xsl:apply-templates mode=\"phase-2\" />\n </th>\n </xsl:template>\n\n <xsl:template match=\"xcsv:row\" mode=\"phase-2\">\n <tr>\n <xsl:apply-templates mode=\"phase-2\" />\n </tr>\n </xsl:template>\n\n <xsl:template match=\"xcsv:value\" mode=\"phase-2\">\n <td>\n <xsl:apply-templates mode=\"phase-2\" />\n </td>\n </xsl:template>\n\n <xsl:template match=\"xcsv:notice\" mode=\"phase-2\" />\n\n </xsl:stylesheet>\n", "language": "XSLT-2.0" }, { "code": "<!DOCTYPE html\n SYSTEM \"about:legacy-compat\">\n<html lang=\"en\">\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n <title>CSV to HTML translation - Extra Credit</title>\n </head>\n <body>\n <table>\n <th>\n <td>Character</td>\n <td>Speech</td>\n </th>\n <tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go\n away!&lt;/angry&gt;\n </td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Who are you?</td>\n </tr>\n <tr>\n <td>Brians mother</td>\n <td>I'm his mother; that's who!</td>\n </tr>\n <tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n </tr>\n </table>\n </body>\n</html>\n", "language": "XSLT-2.0" }, { "code": "csvData:=Data(0,Int,\"Character,Speech\\n\"\n\"The multitude,The messiah! Show us the messiah!\\n\"\n\"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\"\n\"The multitude,Who are you\\n\"\n\"Brians mother,I'm his mother; that's who!\\n\"\n\"The multitude,Behold his mother! Behold his mother!\");\n\nhtml:=csvData.pump(\"<table>\\n\",fcn(line){\n line.replace(\"&\",\"&amp;\").replace(\"<\",\"&lt;\") // <angry/> --> &lt;angry/>\n .split(\",\")\n .pump(\"<tr>\\n\",\"strip\",String.fpM(\"101\",\" <td>\",\"</td>\\n\"))+\"</tr>\\n\"\n}) + \"</table>\";\nhtml.println();\n", "language": "Zkl" }, { "code": "<table>\n<tr>\n <td>Character</td>\n <td>Speech</td>\n</tr>\n<tr>\n <td>The multitude</td>\n <td>The messiah! Show us the messiah!</td>\n</tr>\n<tr>\n <td>Brians mother</td>\n <td>&lt;angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry></td>\n</tr>\n<tr>\n <td>The multitude</td>\n <td>Who are you</td>\n</tr>\n<tr>\n <td>Brians mother</td>\n <td>I'm his mother; that's who!</td>\n</tr>\n<tr>\n <td>The multitude</td>\n <td>Behold his mother! Behold his mother!</td>\n</tr>\n</table>\n", "language": "Zkl" } ]
CSV-to-HTML-translation
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Cullen_and_Woodall_numbers\n", "language": "00-META" }, { "code": "A [[wp:Cullen_number|Cullen number]] is a number of the form <span style=\"font-size:125%;\">'''n × 2<sup>n</sup> + 1'''</span> where <span style=\"font-size:125%;\">'''n'''</span> is a natural number.\n\nA [[wp:Woodall_number|Woodall number]] is very similar. It is a number of the form <span style=\"font-size:125%;\">'''n × 2<sup>n</sup> - 1'''</span> where <span style=\"font-size:125%;\">'''n'''</span> is a natural number.\n\nSo for each <span style=\"font-size:125%;\">'''n'''</span> the associated Cullen number and Woodall number differ by 2.\n\n''Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.''\n\n\n'''Cullen primes''' are Cullen numbers that are prime. Similarly, '''Woodall primes''' are Woodall numbers that are prime.\n\nIt is common to list the Cullen and Woodall primes by the value of '''n''' rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, '''n''' == 4713, has 1423 digits when evaluated.\n\n\n;Task\n\n* Write procedures to find Cullen numbers and Woodall numbers. \n\n* Use those procedures to find and show here, on this page the first 20 of each.\n\n\n;Stretch\n\n* Find and show the first '''5''' '''Cullen primes''' in terms of '''n'''.\n\n* Find and show the first '''12''' '''Woodall primes''' in terms of '''n'''.\n\n\n;See also\n\n* [[oeis:A002064|OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1]]\n\n* [[oeis:A003261|OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1]]\n\n* [[oeis:A005849|OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime]]\n\n* [[oeis:A002234|OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime]]\n\n\n", "language": "00-TASK" }, { "code": "F cullen(n)\n R (n << n) + 1\n\nF woodall(n)\n R (n << n) - 1\n\nprint(‘First 20 Cullen numbers:’)\nL(i) 1..20\n print(cullen(i), end' ‘ ’)\nprint()\nprint()\nprint(‘First 20 Woodall numbers:’)\nL(i) 1..20\n print(woodall(i), end' ‘ ’)\nprint()\n", "language": "11l" }, { "code": "BEGIN # find Cullen and Woodall numbers and determine which are prime #\n # a Cullen number n is n2^2 + 1, Woodall number is n2^n - 1 #\n PR read \"primes.incl.a68\" PR # include prime utilities #\n PR precision 800 PR # set number of digits for Algol 68G LONG LONG INT #\n # returns the nth Cullen number #\n OP CULLEN = ( INT n )LONG LONG INT: n * LONG LONG INT(2)^n + 1;\n # returns the nth Woodall number #\n OP WOODALL = ( INT n )LONG LONG INT: CULLEN n - 2;\n\n # show the first 20 Cullen numbers #\n print( ( \"1st 20 Cullen numbers:\" ) );\n FOR n TO 20 DO\n print( ( \" \", whole( CULLEN n, 0 ) ) )\n OD;\n print( ( newline ) );\n # show the first 20 Woodall numbers #\n print( ( \"1st 20 Woodall numbers:\" ) );\n FOR n TO 20 DO\n print( ( \" \", whole( WOODALL n, 0 ) ) )\n OD;\n print( ( newline ) );\n BEGIN # first 2 Cullen primes #\n print( ( \"Index of the 1st 2 Cullen primes:\" ) );\n LONG LONG INT power of 2 := 1;\n INT prime count := 0;\n FOR n WHILE prime count < 2 DO\n power of 2 *:= 2;\n LONG LONG INT c n = ( n * power of 2 ) + 1;\n IF is probably prime( c n ) THEN\n prime count +:= 1;\n print( ( \" \", whole( n, 0 ) ) )\n FI\n OD;\n print( ( newline ) )\n END;\n BEGIN # first 12 Woodall primes #\n print( ( \"Index of the 1st 12 Woodall primes:\" ) );\n LONG LONG INT power of 2 := 1;\n INT prime count := 0;\n FOR n WHILE prime count < 12 DO\n power of 2 *:= 2;\n LONG LONG INT w n = ( n * power of 2 ) - 1;\n IF is probably prime( w n ) THEN\n prime count +:= 1;\n print( ( \" \", whole( n, 0 ) ) )\n FI\n OD;\n print( ( newline ) )\n END\nEND\n", "language": "ALGOL-68" }, { "code": "10 REM Cullen and Woodall numbers\n20 HOME : REM 20 CLS for Chipmunk Basic\n30 PRINT \"First 20 Cullen numbers:\"\n40 FOR n = 1 TO 20\n50 num = n*(2^n)+1\n60 PRINT INT(num);\" \";\n70 NEXT\n80 PRINT : PRINT\n90 PRINT \"First 20 Woodall numbers:\"\n100 FOR n = 1 TO 20\n110 num = n*(2^n)-1\n120 PRINT INT(num);\" \";\n130 NEXT n\n140 END\n", "language": "Applesoft-BASIC" }, { "code": "cullen: function [n]->\n inc n * 2^n\n\nwoodall: function [n]->\n dec n * 2^n\n\nprint [\"First 20 cullen numbers:\" join.with:\" \" to [:string] map 1..20 => cullen]\nprint [\"First 20 woodall numbers:\" join.with:\" \" to [:string] map 1..20 => woodall]\n", "language": "Arturo" }, { "code": "int num = 0;\n\nwrite(\"First 20 Cullen numbers:\");\n\nfor(int n = 1; n < 20; ++n) {\n num = n * (2^n) + 1;\n write(\" \", num, suffix=none);\n}\n\nwrite(\"\");\nwrite(\"First 20 Woodall numbers:\");\n\nfor(int n = 1; n < 20; ++n) {\n num = n * (2^n) - 1;\n write(\" \", num, suffix=none);\n}\n", "language": "Asymptote" }, { "code": "# syntax: GAWK -f CULLEN_AND_WOODALL_NUMBERS.AWK\nBEGIN {\n start = 1\n stop = 20\n printf(\"Cullen %d-%d:\",start,stop)\n for (n=start; n<=stop; n++) {\n printf(\" %d\",n*(2^n)+1)\n }\n printf(\"\\n\")\n printf(\"Woodall %d-%d:\",start,stop)\n for (n=start; n<=stop; n++) {\n printf(\" %d\",n*(2^n)-1)\n }\n printf(\"\\n\")\n exit(0)\n}\n", "language": "AWK" }, { "code": "print \"First 20 Cullen numbers:\"\n\nfor n = 1 to 20\n\tnum = n * (2^n)+1\n\tprint int(num); \" \";\nnext\n\nprint : print\nprint \"First 20 Woodall numbers:\"\n\nfor n = 1 to 20\n\tnum = n * (2^n)-1\n\tprint int(num); \" \";\nnext n\nend\n", "language": "BASIC256" }, { "code": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nuint32_t number, power;\n\nvoid number_initialise() {\n\tnumber = 0;\n\tpower = 1;\n}\n\nenum NumberType { Cullen, Woodhall };\n\nuint32_t next_number(const NumberType& number_type) {\n\tnumber += 1;\n\tpower <<= 1;\n\tswitch ( number_type ) {\n\t\tcase Cullen: return number * power + 1;\n\t\tcase Woodhall: return number * power - 1;\n\t};\n\treturn 0;\n}\n\nvoid number_sequence(const uint32_t& count, const NumberType& number_type) {\n\tstd::string type = ( number_type == Cullen ) ? \"Cullen\" : \"Woodhall\";\n\tstd::cout << \"The first \" << count << \" \" << type << \" numbers are:\" << std::endl;\n\tnumber_initialise();\n\tfor ( uint32_t index = 1; index <= count; ++index ) {\n\t\tstd::cout << next_number(number_type) << \" \";\n\t}\n\tstd::cout << std::endl << std::endl;\n}\n\nint main() {\n\tnumber_sequence(20, Cullen);\n\tnumber_sequence(20, Woodhall);\n}\n", "language": "C++" }, { "code": "10 REM Cullen and Woodall numbers\n20 CLS : REM 20 HOME for Applesoft BASIC\n30 PRINT \"First 20 Cullen numbers:\"\n40 FOR n = 1 TO 20\n50 num = n*(2^n)+1\n60 PRINT INT(num);\" \";\n70 NEXT\n80 PRINT : PRINT\n90 PRINT \"First 20 Woodall numbers:\"\n100 FOR n = 1 TO 20\n110 num = n*(2^n)-1\n120 PRINT INT(num);\" \";\n130 NEXT n\n140 END\n", "language": "Chipmunk-Basic" }, { "code": "uses SysUtils,StdCtrls;\n\nprocedure CullenWoodallTest(Memo: TMemo);\n\nimplementation\n\nprocedure FindCullenNumbers(Memo: TMemo);\nvar N,R: integer;\nvar S: string;\nbegin\nS:='';\nMemo.Lines.Add('First 20 Cullen Numbers:');\nfor N:=1 to 20 do\n\tbegin\n\tR:=N * (1 shl N) + 1;\n\tS:=S+IntToStr(R)+' ';\n\tend;\nMemo.Lines.Add(S);\nend;\n\n\nprocedure FindWoodallNumbers(Memo: TMemo);\nvar N,R: integer;\nvar S: string;\nbegin\nS:='';\nMemo.Lines.Add('First 20 Woodall Numbers:');\nfor N:=1 to 20 do\n\tbegin\n\tR:=N * (1 shl N) - 1;\n\tS:=S+IntToStr(R)+' ';\n\tend;\nMemo.Lines.Add(S);\nend;\n\n\nprocedure CullenWoodallTest(Memo: TMemo);\nbegin\nFindCullenNumbers(Memo);\nFindWoodallNumbers(Memo);\nend;\n", "language": "Delphi" }, { "code": "for n = 1 to 20\n write n * pow 2 n + 1 & \" \"\n.\nprint \"\"\nfor n = 1 to 20\n write n * pow 2 n - 1 & \" \"\n.\nprint \"\"\n", "language": "EasyLang" }, { "code": "// Cullen and Woodall numbers. Nigel Galloway: January 14th., 2022\nlet Cullen,Woodall=let fG n (g:int)=(bigint g)*2I**g+n in fG 1I, fG -1I\nSeq.initInfinite((+)1>>Cullen)|>Seq.take 20|>Seq.iter(printf \"%A \"); printfn \"\"\nSeq.initInfinite((+)1>>Woodall)|>Seq.take 20|>Seq.iter(printf \"%A \"); printfn \"\"\nSeq.initInfinite((+)1)|>Seq.filter(fun n->let mutable n=Woodall n in Open.Numeric.Primes.MillerRabin.IsProbablePrime &n)|>Seq.take 12|>Seq.iter(printf \"%A \"); printfn \"\"\nSeq.initInfinite((+)1)|>Seq.filter(fun n->let mutable n=Cullen n in Open.Numeric.Primes.MillerRabin.IsProbablePrime &n)|>Seq.take 5|>Seq.iter(printf \"%A \"); printfn \"\"\n", "language": "F-Sharp" }, { "code": "USING: arrays kernel math math.vectors prettyprint ranges\nsequences ;\n\n20 [1..b] [ dup 2^ * 1 + ] map dup 2 v-n 2array simple-table.\n", "language": "Factor" }, { "code": "Dim As Uinteger n, num\nPrint \"First 20 Cullen numbers:\"\n\nFor n = 1 To 20\n num = n * (2^n)+1\n Print num; \" \";\nNext\n\nPrint !\"\\n\\nFirst 20 Woodall numbers:\"\n\nFor n = 1 To 20\n num = n * (2^n)-1\n Print num; \" \";\nNext n\nSleep\n", "language": "FreeBASIC" }, { "code": "local fn CullenAndWoodall( limit as long )\n NSUInteger i, cullen, woodall\n\n printf @\"%13s %9s\", fn StringUTF8String( @\"Cullen\" ), fn StringUTF8String( @\"Woodall\" )\n for i = 1 to limit\n cullen = i * ( 2^i ) + 1\n woodall = i * ( 2^i ) - 1\n printf @\"%3lu %9lu %9lu\", i, cullen, woodall\n next\nend fn\n\nfn CullenAndWoodall( 20 )\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\n\n Dim n, num As Integer\n\n Print \"First 20 Cullen numbers:\"\n\n For n = 1 To 20\n num = n * (2 ^ n) + 1\n Print num; \" \";\n Next\n\n Print \"\\n\\nFirst 20 Woodall numbers:\"\n\n For n = 1 To 20\n num = n * (2 ^ n) - 1\n Print num; \" \";\n Next\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport (\n \"fmt\"\n big \"github.com/ncw/gmp\"\n)\n\nfunc cullen(n uint) *big.Int {\n one := big.NewInt(1)\n bn := big.NewInt(int64(n))\n res := new(big.Int).Lsh(one, n)\n res.Mul(res, bn)\n return res.Add(res, one)\n}\n\nfunc woodall(n uint) *big.Int {\n res := cullen(n)\n return res.Sub(res, big.NewInt(2))\n}\n\nfunc main() {\n fmt.Println(\"First 20 Cullen numbers (n * 2^n + 1):\")\n for n := uint(1); n <= 20; n++ {\n fmt.Printf(\"%d \", cullen(n))\n }\n\n fmt.Println(\"\\n\\nFirst 20 Woodall numbers (n * 2^n - 1):\")\n for n := uint(1); n <= 20; n++ {\n fmt.Printf(\"%d \", woodall(n))\n }\n\n fmt.Println(\"\\n\\nFirst 5 Cullen primes (in terms of n):\")\n count := 0\n for n := uint(1); count < 5; n++ {\n cn := cullen(n)\n if cn.ProbablyPrime(15) {\n fmt.Printf(\"%d \", n)\n count++\n }\n }\n\n fmt.Println(\"\\n\\nFirst 12 Woodall primes (in terms of n):\")\n count = 0\n for n := uint(1); count < 12; n++ {\n cn := woodall(n)\n if cn.ProbablyPrime(15) {\n fmt.Printf(\"%d \", n)\n count++\n }\n }\n fmt.Println()\n}\n", "language": "Go" }, { "code": "findCullen :: Int -> Integer\nfindCullen n = toInteger ( n * 2 ^ n + 1 )\n\ncullens :: [Integer]\ncullens = map findCullen [1 .. 20]\n\nwoodalls :: [Integer]\nwoodalls = map (\\i -> i - 2 ) cullens\n\nmain :: IO ( )\nmain = do\n putStrLn \"First 20 Cullen numbers:\"\n print cullens\n putStrLn \"First 20 Woodall numbers:\"\n print woodalls\n", "language": "Haskell" }, { "code": "cullen=: {{ y* 1+2x^y }}\nwoodall=: {{ y*_1+2x^y }}\n", "language": "J" }, { "code": " cullen 1+i.20\n3 10 27 68 165 390 903 2056 4617 10250 22539 49164 106509 229390 491535 1048592 2228241 4718610 9961491 20971540\n woodall 1+i.20\n1 6 21 60 155 378 889 2040 4599 10230 22517 49140 106483 229362 491505 1048560 2228207 4718574 9961453 20971500\n", "language": "J" }, { "code": "import java.math.BigInteger;\n\npublic final class CullenAndWoodhall {\n\n\tpublic static void main(String[] aArgs) {\n\t\tnumberSequence(20, NumberType.Cullen);\n\t\t\n\t\tnumberSequence(20, NumberType.Woodhall);\n\t\t\n\t\tprimeSequence(5, NumberType.Cullen);\n\t\t\n\t\tprimeSequence(12, NumberType.Woodhall);\n\t}\n\n\tprivate enum NumberType { Cullen, Woodhall }\n\t\n\tprivate static void numberSequence(int aCount, NumberType aNumberType) {\n\t\tSystem.out.println();\n\t\tSystem.out.println(\"The first \" + aCount + \" \" + aNumberType + \" numbers are:\");\n\t\tnumberInitialise();\n\t\tfor ( int index = 1; index <= aCount; index++ ) {\n\t\t\tSystem.out.print(nextNumber(aNumberType) + \" \");\n\t\t}\t\n\t\tSystem.out.println();\t\n\t}\n\t\n\tprivate static void primeSequence(int aCount, NumberType aNumberType) {\n\t\tSystem.out.println();\n\t\tSystem.out.println(\"The indexes of the first \" + aCount + \" \" + aNumberType + \" primes are:\");\n\t\tprimeInitialise();\n\t\t\n\t\twhile ( count < aCount ) {\t\t\t\n\t\t\tif ( nextNumber(aNumberType).isProbablePrime(CERTAINTY) ) {\n\t\t\t\tSystem.out.print(primeIndex + \" \");\n\t\t\t\tcount += 1;\n\t\t\t}\n\t\t\t\n\t\t\tprimeIndex += 1;\n\t\t}\n\t\tSystem.out.println();\n\t}\n\t\n\tprivate static BigInteger nextNumber(NumberType aNumberType) {\n\t\tnumber = number.add(BigInteger.ONE);\n\t\tpower = power.shiftLeft(1);\n\t\treturn switch ( aNumberType ) {\n\t\t\tcase Cullen -> number.multiply(power).add(BigInteger.ONE);\n\t\t\tcase Woodhall -> number.multiply(power).subtract(BigInteger.ONE);\n\t\t};\n\t}\n\t\n\tprivate static void numberInitialise() {\n\t\tnumber = BigInteger.ZERO;\n\t\tpower = BigInteger.ONE;\t\t\n\t}\n\t\n\tprivate static void primeInitialise() {\t\n\t\tcount = 0;\n\t\tprimeIndex = 1;\n\t\tnumberInitialise();\n\t}\n\t\n\tprivate static BigInteger number;\n\tprivate static BigInteger power;\n\tprivate static int count;\n\tprivate static int primeIndex;\n\t\n\tprivate static final int CERTAINTY = 20;\n\t\n}\n", "language": "Java" }, { "code": "def is_prime:\n . as $n\n | if ($n < 2) then false\n elif ($n % 2 == 0) then $n == 2\n elif ($n % 3 == 0) then $n == 3\n elif ($n % 5 == 0) then $n == 5\n elif ($n % 7 == 0) then $n == 7\n elif ($n % 11 == 0) then $n == 11\n elif ($n % 13 == 0) then $n == 13\n elif ($n % 17 == 0) then $n == 17\n elif ($n % 19 == 0) then $n == 19\n else\n ($n | sqrt) as $rt\n | 23\n | until( . > $rt or ($n % . == 0); .+2)\n | . > $rt\n end;\n\ndef ipow($m; $n): reduce range(0;$n) as $i (1; $m * .);\n\ndef cullen: ipow(2;.) * . + 1;\n\ndef woodall: cullen - 2;\n\ndef task:\n \"First 20 Cullen numbers (n * 2^n + 1):\",\n (range(1; 21) | cullen),\n \"\\n\\nFirst 20 Woodall numbers (n * 2^n - 1):\",\n (range(1; 21) | woodall),\n\n \"\\n\\nFirst Cullen primes (in terms of n):\",\n limit(1;\n range(1; infinite)\n | select(cullen|is_prime) ),\n\n \"\\n\\nFirst 4 Woodall primes (in terms of n):\",\n limit(4;\n range(0; infinite)\n | select(woodall|is_prime) ) ;\n\ntask\n", "language": "Jq" }, { "code": "using Lazy\nusing Primes\n\ncullen(n, two = BigInt(2)) = n * two^n + 1\nwoodall(n, two = BigInt(2)) = n * two^n - 1\nprimecullens = @>> Lazy.range() filter(n -> isprime(cullen(n)))\nprimewoodalls = @>> Lazy.range() filter(n -> isprime(woodall(n)))\n\nprintln(\"First 20 Cullen numbers: ( n × 2**n + 1)\\n\", [cullen(n, 2) for n in 1:20]) # A002064\nprintln(\"First 20 Woodall numbers: ( n × 2**n - 1)\\n\", [woodall(n, 2) for n in 1:20]) # A003261\nprintln(\"\\nFirst 5 Cullen primes: (in terms of n)\\n\", take(5, primecullens)) # A005849\nprintln(\"\\nFirst 12 Woodall primes: (in terms of n)\\n\", Int.(collect(take(12, primewoodalls)))) # A002234\n", "language": "Julia" }, { "code": "function T(t) return setmetatable(t, {__index=table}) end\ntable.range = function(t,n) local s=T{} for i=1,n do s[i]=i end return s end\ntable.map = function(t,f) local s=T{} for i=1,#t do s[i]=f(t[i]) end return s end\n\nfunction cullen(n) return (n<<n)+1 end\nprint(\"First 20 Cullen numbers:\")\nprint(T{}:range(20):map(cullen):concat(\" \"))\n\nfunction woodall(n) return (n<<n)-1 end\nprint(\"First 20 Woodall numbers:\")\nprint(T{}:range(20):map(woodall):concat(\" \"))\n", "language": "Lua" }, { "code": "ClearAll[CullenNumber, WoodallNumber]\nSetAttributes[{CullenNumber, WoodallNumber}, Listable]\nCullenNumber[n_Integer] := n 2^n + 1\nWoodallNumber[n_Integer] := n 2^n - 1\n\nCullenNumber[Range[20]]\nWoodallNumber[Range[20]]\n\ncps = {};\nDo[\n If[PrimeQ[CullenNumber[i]],\n AppendTo[cps, i];\n If[Length[cps] >= 5, Break[]]\n ]\n ,\n {i, 1, \\[Infinity]}\n ]\ncps\n\nwps = {};\nDo[\n If[PrimeQ[WoodallNumber[i]],\n AppendTo[wps, i];\n If[Length[wps] >= 12, Break[]]\n ]\n ,\n {i, 1, \\[Infinity]}\n ];\nwps\n", "language": "Mathematica" }, { "code": "/* Functions */\ncullen(n):=(n*2^n)+1$\nwoodall(n):=(n*2^n)-1$\n\n/* Test cases */\nmakelist(cullen(i),i,20);\nmakelist(woodall(i),i,20);\n", "language": "Maxima" }, { "code": "import std/strformat\nimport integers\n\niterator cullenNumbers(): (int, Integer) =\n var n = 1\n var p = newInteger(2)\n while true:\n yield (n , n * p + 1)\n inc n\n p = p shl 1\n\niterator woodallNumbers(): (int, Integer) =\n var n = 1\n var p = newInteger(2)\n while true:\n yield (n , n * p - 1)\n inc n\n p = p shl 1\n\necho \"First 20 Cullen numbers:\"\nfor (n, cn) in cullenNumbers():\n stdout.write &\"{cn:>9}\"\n if n mod 5 == 0: echo()\n if n == 20: break\n\necho \"\\nFirst 20 Woodall numbers:\"\nfor (n, wn) in woodallNumbers():\n stdout.write &\"{wn:>9}\"\n if n mod 5 == 0: echo()\n if n == 20: break\n\necho \"\\nFirst 5 Cullen primes (in terms of n):\"\nvar count = 0\nfor (n, cn) in cullenNumbers():\n if cn.isPrime:\n stdout.write ' ', n\n inc count\n if count == 5: break\necho()\n\necho \"\\nFirst 12 Woodall primes (in terms of n):\"\ncount = 0\nfor (n, wn) in woodallNumbers():\n if wn.isPrime:\n stdout.write ' ', n\n inc count\n if count == 12: break\necho()\n", "language": "Nim" }, { "code": "/* Define the Cullen and Woodall number functions */\ncullen(n) = n * 2^n + 1;\nwoodall(n) = n * 2^n - 1;\n\n{\n/* Generate the first 20 Cullen and Woodall numbers */\nprint(vector(20, n, cullen(n)));\nprint(vector(20, n, woodall(n)));\n\n/* Find the first 5 Cullen prime numbers */\ncps = [];\nfor(i = 1, +oo,\n if(isprime(cullen(i)),\n cps = concat(cps, i);\n if(#cps >= 5, break);\n );\n);\nprint(cps);\n\n/* Find the first 12 Woodall prime numbers */\nwps = [];\nfor(i = 1, +oo,\n if(isprime(woodall(i)),\n wps = concat(wps, i);\n if(#wps >= 12, break);\n );\n);\nprint(wps);\n}\n", "language": "PARI-GP" }, { "code": "use strict;\nuse warnings;\nuse bigint;\nuse ntheory 'is_prime';\nuse constant Inf => 1e10;\n\nsub cullen {\n my($n,$c) = @_;\n ($n * 2**$n) + $c;\n}\n\nmy($m,$n);\n\n($m,$n) = (20,0);\nprint \"First $m Cullen numbers:\\n\";\nprint do { $n < $m ? (++$n and cullen($_,1) . ' ') : last } for 1 .. Inf;\n\n($m,$n) = (20,0);\nprint \"\\n\\nFirst $m Woodall numbers:\\n\";\nprint do { $n < $m ? (++$n and cullen($_,-1) . ' ') : last } for 1 .. Inf;\n\n($m,$n) = (5,0);\nprint \"\\n\\nFirst $m Cullen primes: (in terms of n)\\n\";\nprint do { $n < $m ? (!!is_prime(cullen $_,1) and ++$n and \"$_ \") : last } for 1 .. Inf;\n\n($m,$n) = (12,0);\nprint \"\\n\\nFirst $m Woodall primes: (in terms of n)\\n\";\nprint do { $n < $m ? (!!is_prime(cullen $_,-1) and ++$n and \"$_ \") : last } for 1 .. Inf;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">mpfr</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">cullen</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpz_ui_pow_ui</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpz_mul_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpz_add_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">woodall</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cullen</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpz_sub_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span> <span style=\"color: #000000;\">w</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">z</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_init</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">20</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">cullen</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">mpz_get_str</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">mpz_sub_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">w</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">mpz_get_str</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" Cullen[1..20]:%s\\nWoodall[1..20]:%s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">)})</span>\n\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)<</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">JS</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">cullen</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">mpz_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">sprint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">))</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()></span><span style=\"color: #000000;\">t1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">progress</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"c(%d) [needs to get to 6611], %d found\\r\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()+</span><span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">progress</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"First 5 Cullen primes (in terms of n):%s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #000000;\">w</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">)<</span><span style=\"color: #000000;\">12</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">woodall</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">mpz_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">w</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">sprint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">))</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"First 12 Woodall primes (in terms of n):%s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "OpenConsole()\nPrintN(\"First 20 Cullen numbers:\")\n\nFor n.i = 1 To 20\n num = n * Pow(2, n)+1\n Print(Str(num) + \" \")\nNext\n\nPrintN(#CRLF$ + \"First 20 Woodall numbers:\")\n\nFor n.i = 1 To 20\n num = n * Pow(2, n)-1\n Print(Str(num) + \" \")\nNext n\n\nPrintN(#CRLF$ + \"--- terminado, pulsa RETURN---\"): Input()\nCloseConsole()\n", "language": "PureBasic" }, { "code": "print(\"working...\")\nprint(\"First 20 Cullen numbers:\")\n\nfor n in range(1,21):\n num = n*pow(2,n)+1\n print(str(num),end= \" \")\n\nprint()\nprint(\"First 20 Woodall numbers:\")\n\nfor n in range(1,21):\n num = n*pow(2,n)-1\n print(str(num),end=\" \")\n\nprint()\nprint(\"done...\")\n", "language": "Python" }, { "code": "def cullen(n): return((n<<n)+1)\n\t\ndef woodall(n): return((n<<n)-1)\n\nprint(\"First 20 Cullen numbers:\")\nfor i in range(1,21):\n\tprint(cullen(i),end=\" \")\nprint()\nprint()\nprint(\"First 20 Woodall numbers:\")\nfor i in range(1,21):\n\tprint(woodall(i),end=\" \")\nprint()\n", "language": "Python" }, { "code": "DIM num AS LONG ''comment this line for True BASIC\nPRINT \"First 20 Cullen numbers:\"\n\nFOR n = 1 TO 20\n LET num = n * (2 ^ n) + 1\n PRINT num;\nNEXT n\n\nPRINT\nPRINT\nPRINT \"First 20 Woodall numbers:\"\n\nFOR n = 1 TO 20\n LET num = n * (2 ^ n) - 1\n PRINT num;\nNEXT n\nEND\n", "language": "QBasic" }, { "code": " [ dup << 1+ ] is cullen ( n --> n )\n\n [ dup << 1 - ] is woodall ( n --> n )\n\n say \"First 20 Cullen numbers:\" cr\n 20 times [ i^ 1+ cullen echo sp ] cr\n cr\n say \"First 20 Woodall numbers:\" cr\n 20 times [ i^ 1+ woodall echo sp ] cr\n", "language": "Quackery" }, { "code": "my @cullen = ^∞ .map: { $_ × 1 +< $_ + 1 };\nmy @woodall = ^∞ .map: { $_ × 1 +< $_ - 1 };\n\nput \"First 20 Cullen numbers: ( n × 2**n + 1)\\n\", @cullen[1..20]; # A002064\nput \"\\nFirst 20 Woodall numbers: ( n × 2**n - 1)\\n\", @woodall[1..20]; # A003261\nput \"\\nFirst 5 Cullen primes: (in terms of n)\\n\", @cullen.grep( &is-prime, :k )[^5]; # A005849\nput \"\\nFirst 12 Woodall primes: (in terms of n)\\n\", @woodall.grep( &is-prime, :k )[^12]; # A002234\n", "language": "Raku" }, { "code": "load \"stdlib.ring\"\n\nsee \"working...\" + nl\nsee \"First 20 Cullen numbers:\" + nl\n\nfor n = 1 to 20\n num = n*pow(2,n)+1\n see \"\" + num + \" \"\nnext\n\nsee nl + nl + \"First 20 Woodall numbers:\" + nl\n\nfor n = 1 to 20\n num = n*pow(2,n)-1\n see \"\" + num + \" \"\nnext\n\nsee nl + \"done...\" + nl\n", "language": "Ring" }, { "code": "require 'openssl'\n\ncullen = Enumerator.new{|y| (1..).each{|n| y << (n*(1<<n) + 1)} }\nwoodall = Enumerator.new{|y| (1..).each{|n| y << (n*(1<<n) - 1)} }\ncullen_primes = Enumerator.new{|y| (1..).each {|i|y << i if OpenSSL::BN.new(cullen.next).prime?}}\nwoodall_primes = Enumerator.new{|y| (1..).each{|i|y << i if OpenSSL::BN.new(woodall.next).prime?}}\n\nnum = 20\nputs \"First #{num} Cullen numbers:\\n#{cullen.first(num).join(\" \")}\"\nputs \"First #{num} Woodal numbers:\\n#{woodall.first(num).join(\" \")}\"\nputs \"First 5 Cullen primes:\\n#{cullen_primes.first(5).join(\", \")}\"\nputs \"First 12 Woodall primes:\\n#{woodall_primes.first(12).join(\", \")}\"\n", "language": "Ruby" }, { "code": "print \"First 20 Cullen numbers:\"\n\nfor n = 1 to 20\n\tnum = n * (2^n)+1\n\tprint int(num); \" \";\nnext\n\nprint : print\nprint \"First 20 Woodall numbers:\"\n\nfor n = 1 to 20\n\tnum = n * (2^n)-1\n\tprint int(num); \" \";\nnext n\nend\n", "language": "Run-BASIC" }, { "code": "REM Rosetta Code problem: https://rosettacode.org/wiki/Cullen_and_Woodall_numbers\nREM by Jjuanhdez, 03/2023\n\n REM TinyBasic does not support values greater than 32767\n\n PRINT \"First 11 Cullen numbers:\"\n LET N = 0\n LET I = 1\n 10 IF I = 12 THEN GOTO 20\n GOSUB 50\n LET N = (I*R) +1\n PRINT N, \" \"\n LET I = I+1\n GOTO 10\n 20 PRINT \"\"\n PRINT \"First 11 Woodall numbers:\"\n LET I = 1\n 30 IF I = 12 THEN GOTO 40\n GOSUB 50\n LET N = (I*R) -1\n PRINT N, \" \"\n LET I = I+1\n GOTO 30\n 40 END\n\n 50 REM Exponent calculation\n LET A = 2\n\tLET B = I\n LET X = 1\n LET R = 2\n 60 IF X >= B THEN RETURN\n LET T = R\n IF R < A THEN LET R = A*A\n IF T < A THEN GOTO 70\n IF R >= A THEN LET R = R*A\n 70 LET X = X+1\n GOTO 60\n", "language": "Run-BASIC" }, { "code": "// [dependencies]\n// rug = \"1.15.0\"\n\nuse rug::integer::IsPrime;\nuse rug::Integer;\n\nfn cullen_number(n: u32) -> Integer {\n let num = Integer::from(n);\n (num << n) + 1\n}\n\nfn woodall_number(n: u32) -> Integer {\n let num = Integer::from(n);\n (num << n) - 1\n}\n\nfn main() {\n println!(\"First 20 Cullen numbers:\");\n let cullen: Vec<String> = (1..21).map(|x| cullen_number(x).to_string()).collect();\n println!(\"{}\", cullen.join(\" \"));\n\n println!(\"\\nFirst 20 Woodall numbers:\");\n let woodall: Vec<String> = (1..21).map(|x| woodall_number(x).to_string()).collect();\n println!(\"{}\", woodall.join(\" \"));\n\n println!(\"\\nFirst 5 Cullen primes in terms of n:\");\n let cullen_primes: Vec<String> = (1..)\n .filter_map(|x| match cullen_number(x).is_probably_prime(25) {\n IsPrime::No => None,\n _ => Some(x.to_string()),\n })\n .take(5)\n .collect();\n println!(\"{}\", cullen_primes.join(\" \"));\n\n println!(\"\\nFirst 12 Woodall primes in terms of n:\");\n let woodall_primes: Vec<String> = (1..)\n .filter_map(|x| match woodall_number(x).is_probably_prime(25) {\n IsPrime::No => None,\n _ => Some(x.to_string()),\n })\n .take(12)\n .collect();\n println!(\"{}\", woodall_primes.join(\" \"));\n}\n", "language": "Rust" }, { "code": "import java.math.BigInteger\nimport scala.annotation.tailrec\n\nobject CullenAndWoodhall extends App {\n\n val Certainty = 20\n var number: BigInteger = _\n var power: BigInteger = _\n var count: Int = _\n var primeIndex: Int = _\n\n sealed trait NumberType\n case object Cullen extends NumberType\n case object Woodhall extends NumberType\n\n numberSequence(20, Cullen)\n numberSequence(20, Woodhall)\n primeSequence(5, Cullen)\n primeSequence(12, Woodhall)\n\n def numberSequence(aCount: Int, aNumberType: NumberType): Unit = {\n println(s\"\\nThe first $aCount $aNumberType numbers are:\")\n numberInitialise()\n (1 to aCount).foreach { _ =>\n print(nextNumber(aNumberType).toString + \" \")\n }\n println()\n}\n\n\n def primeSequence(aCount: Int, aNumberType: NumberType): Unit = {\n println(s\"\\nThe indexes of the first $aCount $aNumberType primes are:\")\n primeInitialise()\n\n @tailrec\n def findPrimes(): Unit = {\n if (count < aCount) {\n if (nextNumber(aNumberType).isProbablePrime(Certainty)) {\n print(primeIndex + \" \")\n count += 1\n }\n primeIndex += 1\n findPrimes()\n }\n }\n\n findPrimes()\n println()\n }\n\n def nextNumber(aNumberType: NumberType): BigInteger = {\n number = number.add(BigInteger.ONE)\n power = power.shiftLeft(1)\n aNumberType match {\n case Cullen => number.multiply(power).add(BigInteger.ONE)\n case Woodhall => number.multiply(power).subtract(BigInteger.ONE)\n }\n }\n\n def numberInitialise(): Unit = {\n number = BigInteger.ZERO\n power = BigInteger.ONE\n }\n\n def primeInitialise(): Unit = {\n count = 0\n primeIndex = 1\n numberInitialise()\n }\n}\n", "language": "Scala" }, { "code": "func cullen(n) { n * (1 << n) + 1 }\nfunc woodall(n) { n * (1 << n) - 1 }\n\nsay \"First 20 Cullen numbers:\"\nsay cullen.map(1..20).join(' ')\n\nsay \"\\nFirst 20 Woodall numbers:\"\nsay woodall.map(1..20).join(' ')\n\nsay \"\\nFirst 5 Cullen primes: (in terms of n)\"\nsay 5.by { cullen(_).is_prime }.join(' ')\n\nsay \"\\nFirst 12 Woodall primes: (in terms of n)\"\nsay 12.by { woodall(_).is_prime }.join(' ')\n", "language": "Sidef" }, { "code": "REM DIM num AS LONG !uncomment this line for QBasic\nPRINT \"First 20 Cullen numbers:\"\n\nFOR n = 1 TO 20\n LET num = n * (2 ^ n) + 1\n PRINT num;\nNEXT n\n\nPRINT\nPRINT\nPRINT \"First 20 Woodall numbers:\"\n\nFOR n = 1 TO 20\n LET num = n * (2 ^ n) - 1\n PRINT num;\nNEXT n\nEND\n", "language": "True-BASIC" }, { "code": "module main;\n integer n, num;\n\n initial begin\n $display(\"First 20 Cullen numbers:\");\n for(n = 1; n <= 20; n=n+1)\n begin\n num = n * (2 ** n) + 1;\n $write(num, \" \");\n end\n $display(\"\");\n $display(\"First 20 Woodall numbers:\");\n for(n = 1; n <= 20; n=n+1)\n begin\n num = n * (2 ** n) - 1;\n $write(num, \" \");\n end\n $finish ;\n end\nendmodule\n", "language": "Verilog" }, { "code": "import \"./big\" for BigInt\n\nvar cullen = Fn.new { |n| (BigInt.one << n) * n + 1 }\n\nvar woodall = Fn.new { |n| cullen.call(n) - 2 }\n\nSystem.print(\"First 20 Cullen numbers (n * 2^n + 1):\")\nfor (n in 1..20) System.write(\"%(cullen.call(n)) \")\n\nSystem.print(\"\\n\\nFirst 20 Woodall numbers (n * 2^n - 1):\")\nfor (n in 1..20) System.write(\"%(woodall.call(n)) \")\n\nSystem.print(\"\\n\\nFirst 2 Cullen primes (in terms of n):\")\nvar count = 0\nvar n = 1\nwhile (count < 2) {\n var cn = cullen.call(n)\n if (cn.isProbablePrime(5)){\n System.write(\"%(n) \")\n count = count + 1\n }\n n = n + 1\n}\n\nSystem.print(\"\\n\\nFirst 12 Woodall primes (in terms of n):\")\ncount = 0\nn = 1\nwhile (count < 12) {\n var wn = woodall.call(n)\n if (wn.isProbablePrime(5)){\n System.write(\"%(n) \")\n count = count + 1\n }\n n = n + 1\n}\nSystem.print()\n", "language": "Wren" }, { "code": "/* Cullen_and_woodall_numbers_2.wren */\n\nimport \"./gmp\" for Mpz\n\nvar cullen = Fn.new { |n| (Mpz.one << n) * n + 1 }\n\nvar woodall = Fn.new { |n| cullen.call(n) - 2 }\n\nSystem.print(\"First 20 Cullen numbers (n * 2^n + 1):\")\nfor (n in 1..20) System.write(\"%(cullen.call(n)) \")\n\nSystem.print(\"\\n\\nFirst 20 Woodall numbers (n * 2^n - 1):\")\nfor (n in 1..20) System.write(\"%(woodall.call(n)) \")\n\nSystem.print(\"\\n\\nFirst 5 Cullen primes (in terms of n):\")\nvar count = 0\nvar n = 1\nwhile (count < 5) {\n var cn = cullen.call(n)\n if (cn.probPrime(15) > 0){\n System.write(\"%(n) \")\n count = count + 1\n }\n n = n + 1\n}\n\nSystem.print(\"\\n\\nFirst 12 Woodall primes (in terms of n):\")\ncount = 0\nn = 1\nwhile (count < 12) {\n var wn = woodall.call(n)\n if (wn.probPrime(15) > 0){\n System.write(\"%(n) \")\n count = count + 1\n }\n n = n + 1\n}\nSystem.print()\n", "language": "Wren" }, { "code": "PROGRAM\t\"progname\"\nVERSION\t\"0.0000\"\n\nIMPORT \"xma\"\n\nDECLARE FUNCTION Entry ()\n\nFUNCTION Entry ()\n\nPRINT \"First 20 Cullen numbers:\"\n\nFOR n = 1 TO 20\n num! = n * POWER (2, n) + 1\n PRINT num!;\nNEXT n\n\nPRINT\nPRINT\nPRINT \"First 20 Woodall numbers:\"\n\nFOR n = 1 TO 20\n num! = n * POWER (2, n) - 1\n PRINT num!;\nNEXT n\n\nEND FUNCTION\nEND PROGRAM\n", "language": "XBasic" }, { "code": "func Cullen(N);\nint N;\nreturn N<<N + 1;\n\nfunc Woodall(N);\nint N;\nreturn N<<N - 1;\n\nint I;\n[Text(0, \"First 20 Cullen numbers:^m^j\");\nfor I:= 1 to 20 do\n [IntOut(0, Cullen(I)); ChOut(0, ^ )];\nCrLf(0);\nCrLf(0);\nText(0, \"First 20 Woodall numbers:^m^j\");\nfor I:= 1 to 20 do\n [IntOut(0, Woodall(I)); ChOut(0, ^ )];\nCrLf(0);\n]\n", "language": "XPL0" }, { "code": "print \"First 20 Cullen numbers:\"\n\nfor n = 1 to 20\n num = n * (2^n)+1\n print num, \" \";\nnext\n\nprint \"\\n\\nFirst 20 Woodall numbers:\"\n\nfor n = 1 to 20\n num = n * (2^n)-1\n print num, \" \";\nnext n\nprint\nend\n", "language": "Yabasic" } ]
Cullen-and-Woodall-numbers
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Cumulative_standard_deviation\nnote: Probability and statistics\n", "language": "00-META" }, { "code": "{{task heading}}\n\nWrite a stateful function, class, generator or co-routine that takes a series of floating point numbers, ''one at a time'', and returns the running [[wp:Standard Deviation|standard deviation]] of the series. \n\nThe task implementation should use the most natural programming style of those listed for the function in the implementation language; the task ''must'' state which is being used. \n\nDo not apply [[wp:Bessel's correction|Bessel's correction]]; the returned standard deviation should always be computed as if the sample seen so far is the entire population.\n\n\n;Test case:\nUse this to compute the standard deviation of this demonstration set, <math>\\{2, 4, 4, 4, 5, 5, 7, 9\\}</math>, which is <math>2</math>.\n\n\n;Related tasks:\n* [[Random numbers]]\n\n\n{{Related tasks/Statistical measures}}\n\n<hr>\n\n", "language": "00-TASK" }, { "code": "T SD\n sum = 0.0\n sum2 = 0.0\n n = 0.0\n\n F ()(x)\n .sum += x\n .sum2 += x ^ 2\n .n += 1.0\n R sqrt(.sum2 / .n - (.sum / .n) ^ 2)\n\nV sd_inst = SD()\nL(value) [2, 4, 4, 4, 5, 5, 7, 9]\n print(value‘ ’sd_inst(value))\n", "language": "11l" }, { "code": "******** Standard deviation of a population\nSTDDEV CSECT\n USING STDDEV,R13\nSAVEAREA B STM-SAVEAREA(R15)\n DC 17F'0'\n DC CL8'STDDEV'\nSTM STM R14,R12,12(R13)\n ST R13,4(R15)\n ST R15,8(R13)\n LR R13,R15\n SR R8,R8 s=0\n SR R9,R9 ss=0\n SR R4,R4 i=0\n LA R6,1\n LH R7,N\nLOOPI BXH R4,R6,ENDLOOPI\n LR R1,R4 i\n BCTR R1,0\n SLA R1,1\n LH R5,T(R1)\n ST R5,WW ww=t(i)\n MH R5,=H'1000' w=ww*1000\n AR R8,R5 s=s+w\n LR R15,R5\n MR R14,R5 w*w\n AR R9,R15 ss=ss+w*w\n LR R14,R8 s\n SRDA R14,32\n DR R14,R4 /i\n ST R15,AVG avg=s/i\n LR R14,R9 ss\n SRDA R14,32\n DR R14,R4 ss/i\n LR R2,R15 ss/i\n LR R15,R8 s\n MR R14,R8 s*s\n LR R3,R15\n LR R15,R4 i\n MR R14,R4 i*i\n LR R1,R15\n LA R14,0\n LR R15,R3\n DR R14,R1 (s*s)/(i*i)\n SR R2,R15\n LR R10,R2 std=ss/i-(s*s)/(i*i)\n LR R11,R10 std\n SRA R11,1 x=std/2\n LR R12,R10 px=std\nLOOPWHIL EQU *\n CR R12,R11 while px<>=x\n BE ENDWHILE\n LR R12,R11 px=x\n LR R15,R10 std\n LA R14,0\n DR R14,R12 /px\n LR R1,R12 px\n AR R1,R15 px+std/px\n SRA R1,1 /2\n LR R11,R1 x=(px+std/px)/2\n B LOOPWHIL\nENDWHILE EQU *\n LR R10,R11\n CVD R4,P8 i\n MVC C17,MASK17\n ED C17,P8\n MVC BUF+2(1),C17+15\n L R1,WW\n CVD R1,P8\n MVC C17,MASK17\n ED C17,P8\n MVC BUF+10(1),C17+15\n L R1,AVG\n CVD R1,P8\n MVC C18,MASK18\n ED C18,P8\n MVC BUF+17(5),C18+12\n CVD R10,P8 std\n MVC C18,MASK18\n ED C18,P8\n MVC BUF+31(5),C18+12\n WTO MF=(E,WTOMSG)\t\t\n B LOOPI\nENDLOOPI EQU *\n L R13,4(0,R13)\n LM R14,R12,12(R13)\n XR R15,R15\n BR R14\n DS 0D\nN DC H'8'\nT DC H'2',H'4',H'4',H'4',H'5',H'5',H'7',H'9'\nWW DS F\nAVG DS F\nP8 DS PL8\nMASK17 DC C' ',13X'20',X'2120',C'-'\nMASK18 DC C' ',10X'20',X'2120',C'.',3X'20',C'-'\nC17 DS CL17\nC18 DS CL18\nWTOMSG DS 0F\n DC H'80',XL2'0000'\nBUF DC CL80'N=1 ITEM=1 AVG=1.234 STDDEV=1.234 '\n YREGS\n END STDDEV\n", "language": "360-Assembly" }, { "code": "INCLUDE \"H6:REALMATH.ACT\"\n\nREAL sum,sum2\nINT count\n\nPROC Calc(REAL POINTER x,sd)\n REAL tmp1,tmp2,tmp3\n\n RealAdd(sum,x,tmp1) ;tmp1=sum+x\n RealAssign(tmp1,sum) ;sum=sum+x\n RealMult(x,x,tmp1) ;tmp1=x*x\n RealAdd(sum2,tmp1,tmp2) ;tmp2=sum2+x*x\n RealAssign(tmp2,sum2) ;sum2=sum2+x*x\n count==+1\n IF count=0 THEN\n IntToReal(0,sd) ;sd=0\n ELSE\n IntToReal(count,tmp1)\n RealMult(sum,sum,tmp2) ;tmp2=sum*sum\n RealDiv(tmp2,tmp1,tmp3) ;tmp3=sum*sum/count\n RealDiv(tmp3,tmp1,tmp2) ;tmp2=sum*sum/count/count\n RealDiv(sum2,tmp1,tmp3) ;tmp3=sum2/count\n RealSub(tmp3,tmp2,tmp1) ;tmp1=sum2/count-sum*sum/count/count\n Sqrt(tmp1,sd) ;sd=sqrt(sum2/count-sum*sum/count/count)\n FI\nRETURN\n\nPROC Main()\n INT ARRAY values=[2 4 4 4 5 5 7 9]\n INT i\n REAL x,sd\n\n Put(125) PutE() ;clear screen\n MathInit()\n IntToReal(0,sum)\n IntToReal(0,sum2)\n count=0\n FOR i=0 TO 7\n DO\n IntToReal(values(i),x)\n Calc(x,sd)\n Print(\"x=\") PrintR(x)\n Print(\" sum=\") PrintR(sum)\n Print(\" sd=\") PrintRE(sd)\n OD\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;\nwith Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Float_Text_IO; use Ada.Float_Text_IO;\nwith Ada.Integer_Text_IO; use Ada.Integer_Text_IO;\n\nprocedure Test_Deviation is\n type Sample is record\n N : Natural := 0;\n Sum : Float := 0.0;\n SumOfSquares : Float := 0.0;\n end record;\n procedure Add (Data : in out Sample; Point : Float) is\n begin\n Data.N := Data.N + 1;\n Data.Sum := Data.Sum + Point;\n Data.SumOfSquares := Data.SumOfSquares + Point ** 2;\n end Add;\n function Deviation (Data : Sample) return Float is\n begin\n return Sqrt (Data.SumOfSquares / Float (Data.N) - (Data.Sum / Float (Data.N)) ** 2);\n end Deviation;\n\n Data : Sample;\n Test : array (1..8) of Integer := (2, 4, 4, 4, 5, 5, 7, 9);\nbegin\n for Index in Test'Range loop\n Add (Data, Float(Test(Index)));\n Put(\"N=\"); Put(Item => Index, Width => 1);\n Put(\" ITEM=\"); Put(Item => Test(Index), Width => 1);\n Put(\" AVG=\"); Put(Item => Float(Data.Sum)/Float(Index), Fore => 1, Aft => 3, Exp => 0);\n Put(\" STDDEV=\"); Put(Item => Deviation (Data), Fore => 1, Aft => 3, Exp => 0);\n New_line;\n end loop;\nend Test_Deviation;\n", "language": "Ada" }, { "code": "MODE VALUE = STRUCT(CHAR value),\n STDDEV = STRUCT(CHAR stddev),\n MEAN = STRUCT(CHAR mean),\n VAR = STRUCT(CHAR var),\n COUNT = STRUCT(CHAR count),\n RESET = STRUCT(CHAR reset);\n\nMODE ACTION = UNION ( VALUE, STDDEV, MEAN, VAR, COUNT, RESET );\n\nLONG REAL sum := 0;\nLONG REAL sum2 := 0;\nINT num := 0;\n\nPROC stat object = (LONG REAL v, ACTION action)LONG REAL:\n(\n\n LONG REAL m;\n\n CASE action IN\n (VALUE):(\n num +:= 1;\n sum +:= v;\n sum2 +:= v*v;\n stat object(0, LOC STDDEV)\n ),\n (STDDEV):\n long sqrt(stat object(0, LOC VAR)),\n (MEAN):\n IF num>0 THEN sum/LONG REAL(num) ELSE 0 FI,\n (VAR):(\n m := stat object(0, LOC MEAN);\n IF num>0 THEN sum2/LONG REAL(num)-m*m ELSE 0 FI\n ),\n (COUNT):\n num,\n (RESET):\n sum := sum2 := num := 0\n ESAC\n);\n\n[]LONG REAL v = ( 2,4,4,4,5,5,7,9 );\n\nmain:\n(\n LONG REAL sd;\n\n FOR i FROM LWB v TO UPB v DO\n sd := stat object(v[i], LOC VALUE);\n printf(($\"value: \"g(0,6),\" standard dev := \"g(0,6)l$, v[i], sd))\n OD\n\n)\n", "language": "ALGOL-68" }, { "code": "MODE STAT = STRUCT(\n LONG REAL sum,\n LONG REAL sum2,\n INT num\n);\n\nOP INIT = (REF STAT new)REF STAT:\n (init OF class stat)(new);\n\nMODE CLASSSTAT = STRUCT(\n PROC (REF STAT, LONG REAL #value#)VOID plusab,\n PROC (REF STAT)LONG REAL stddev, mean, variance, count,\n PROC (REF STAT)REF STAT init\n);\n\nCLASSSTAT class stat;\n\nplusab OF class stat := (REF STAT self, LONG REAL value)VOID:(\n num OF self +:= 1;\n sum OF self +:= value;\n sum2 OF self +:= value*value\n );\n\nOP +:= = (REF STAT lhs, LONG REAL rhs)VOID: # some syntatic sugar #\n (plusab OF class stat)(lhs, rhs);\n\nstddev OF class stat := (REF STAT self)LONG REAL:\n long sqrt((variance OF class stat)(self));\n\nOP STDDEV = ([]LONG REAL value)LONG REAL: ( # more syntatic sugar #\n REF STAT stat = INIT LOC STAT;\n FOR i FROM LWB value TO UPB value DO\n stat +:= value[i]\n OD;\n (stddev OF class stat)(stat)\n);\n\nmean OF class stat := (REF STAT self)LONG REAL:\n sum OF self/LONG REAL(num OF self);\n\nvariance OF class stat := (REF STAT self)LONG REAL:(\n LONG REAL m = (mean OF class stat)(self);\n sum2 OF self/LONG REAL(num OF self)-m*m\n );\n\ncount OF class stat := (REF STAT self)LONG REAL:\n num OF self;\n\ninit OF class stat := (REF STAT self)REF STAT:(\n sum OF self := sum2 OF self := num OF self := 0;\n self\n );\n\n[]LONG REAL value = ( 2,4,4,4,5,5,7,9 );\n\nmain:\n(\n# printf(($\"standard deviation operator = \"g(0,6)l$, STDDEV value));\n#\n\n REF STAT stat = INIT LOC STAT;\n\n FOR i FROM LWB value TO UPB value DO\n stat +:= value[i];\n printf(($\"value: \"g(0,6),\" standard dev := \"g(0,6)l$, value[i], (stddev OF class stat)(stat)))\n OD\n#\n;\n printf(($\"standard deviation = \"g(0,6)l$, (stddev OF class stat)(stat)));\n printf(($\"mean = \"g(0,6)l$, (mean OF class stat)(stat)));\n printf(($\"variance = \"g(0,6)l$, (variance OF class stat)(stat)));\n printf(($\"count = \"g(0,6)l$, (count OF class stat)(stat)))\n#\n\n)\n", "language": "ALGOL-68" }, { "code": "LONG REAL sum, sum2;\nINT n;\n\nPROC sd = (LONG REAL x)LONG REAL:(\n sum +:= x;\n sum2 +:= x*x;\n n +:= 1;\n IF n = 0 THEN 0 ELSE long sqrt(sum2/n - sum*sum/n/n) FI\n);\n\nsum := sum2 := n := 0;\n[]LONG REAL values = (2,4,4,4,5,5,7,9);\nFOR i TO UPB values DO\n LONG REAL value = values[i];\n printf(($2(xg(0,6))l$, value, sd(value)))\nOD\n", "language": "ALGOL-68" }, { "code": "begin\n\n long real sum, sum2;\n integer n;\n\n long real procedure sd (long real value x) ;\n begin\n sum := sum + x;\n sum2 := sum2 + (x*x);\n n := n + 1;\n if n = 0 then 0 else longsqrt(sum2/n - sum*sum/n/n)\n end sd;\n\n sum := sum2 := n := 0;\n\n r_format := \"A\"; r_w := 14; r_d := 6; % set output to fixed point format %\n\n for i := 2,4,4,4,5,5,7,9\n do begin\n long real val;\n val := i;\n write(val, sd(val))\n end for_i\n\nend.\n", "language": "ALGOL-W" }, { "code": "-------------- CUMULATIVE STANDARD DEVIATION -------------\n\n-- stdDevInc :: Accumulator -> Num -> Index -> Accumulator\n-- stdDevInc :: {sum:, squaresSum:, stages:} -> Real -> Integer\n-- -> {sum:, squaresSum:, stages:}\non stdDevInc(a, n, i)\n set sum to (sum of a) + n\n set squaresSum to (squaresSum of a) + (n ^ 2)\n set stages to (stages of a) & ¬\n ((squaresSum / i) - ((sum / i) ^ 2)) ^ 0.5\n\n {sum:(sum of a) + n, squaresSum:squaresSum, stages:stages}\nend stdDevInc\n\n\n--------------------------- TEST -------------------------\non run\n set xs to [2, 4, 4, 4, 5, 5, 7, 9]\n\n stages of foldl(stdDevInc, ¬\n {sum:0, squaresSum:0, stages:[]}, xs)\n\n --> {0.0, 1.0, 0.942809041582, 0.866025403784, 0.979795897113, 1.0, 1.399708424448, 2.0}\nend run\n\n\n\n-------------------- GENERIC FUNCTIONS -------------------\n\n-- foldl :: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n\n-- mReturn :: First-class m => (a -> b) -> m (a -> b)\non mReturn(f)\n -- 2nd class handler function lifted into 1st class script wrapper.\n if script is class of f then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n", "language": "AppleScript" }, { "code": "{0.0, 1.0, 0.942809041582, 0.866025403784,\n0.979795897113, 1.0, 1.399708424448, 2.0}\n", "language": "AppleScript" }, { "code": "-------------- CUMULATIVE STANDARD DEVIATION -------------\n\n-- cumulativeStdDevns :: [Float] -> [Float]\non cumulativeStdDevns(xs)\n script go\n on |λ|(sq, x, i)\n set {s, q} to sq\n set _s to x + s\n set _q to q + (x ^ 2)\n\n {{_s, _q}, ((_q / i) - ((_s / i) ^ 2)) ^ 0.5}\n end |λ|\n end script\n\n item 2 of mapAccumL(go, {0, 0}, xs)\nend cumulativeStdDevns\n\n\n--------------------------- TEST -------------------------\non run\n\n cumulativeStdDevns({2, 4, 4, 4, 5, 5, 7, 9})\n\nend run\n\n\n------------------------- GENERIC ------------------------\n\n-- foldl :: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n\n-- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\non mapAccumL(f, acc, xs)\n -- 'The mapAccumL function behaves like a combination of map and foldl;\n -- it applies a function to each element of a list, passing an\n -- accumulating parameter from |Left| to |Right|, and returning a final\n -- value of this accumulator together with the new list.' (see Hoogle)\n script\n on |λ|(a, x, i)\n tell mReturn(f) to set pair to |λ|(item 1 of a, x, i)\n {item 1 of pair, (item 2 of a) & {item 2 of pair}}\n end |λ|\n end script\n\n foldl(result, {acc, []}, xs)\nend mapAccumL\n\n\n-- mReturn :: First-class m => (a -> b) -> m (a -> b)\non mReturn(f)\n -- 2nd class handler function lifted into 1st class script wrapper.\n if script is class of f then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n", "language": "AppleScript" }, { "code": "arr: new []\nloop [2 4 4 4 5 5 7 9] 'value [\n 'arr ++ value\n print [value \"->\" deviation arr]\n]\n", "language": "Arturo" }, { "code": "Data := [2,4,4,4,5,5,7,9]\n\nfor k, v in Data {\n FileAppend, % \"#\" a_index \" value = \" v \" stddev = \" stddev(v) \"`n\", * ; send to stdout\n}\nreturn\n\nstddev(x) {\n\tstatic n, sum, sum2\n\tn++\n\tsum += x\n\tsum2 += x*x\n\n\treturn sqrt((sum2/n) - (((sum*sum)/n)/n))\n}\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f STANDARD_DEVIATION.AWK\nBEGIN {\n n = split(\"2,4,4,4,5,5,7,9\",arr,\",\")\n for (i=1; i<=n; i++) {\n temp[i] = arr[i]\n printf(\"%g %g\\n\",arr[i],stdev(temp))\n }\n exit(0)\n}\nfunction stdev(arr, i,n,s1,s2,variance,x) {\n for (i in arr) {\n n++\n x = arr[i]\n s1 += x ^ 2\n s2 += x\n }\n variance = ((n * s1) - (s2 ^ 2)) / (n ^ 2)\n return(sqrt(variance))\n}\n", "language": "AWK" }, { "code": ")abbrev package TESTD TestDomain\nTestDomain(T : Join(Field,RadicalCategory)): Exports == Implementation where\n R ==> Record(n : Integer, sum : T, ssq : T)\n Exports == AbelianMonoid with\n _+ : (%,T) -> %\n _+ : (T,%) -> %\n sd : % -> T\n Implementation == R add\n Rep := R -- similar representation and implementation\n obj : %\n 0 == [0,0,0]\n obj + (obj2:%) == [obj.n + obj2.n, obj.sum + obj2.sum, obj.ssq + obj2.ssq]\n obj + (x:T) == obj + [1, x, x*x]\n (x:T) + obj == obj + x\n sd obj ==\n mean : T := obj.sum / (obj.n::T)\n sqrt(obj.ssq / (obj.n::T) - mean*mean)\n", "language": "Axiom" }, { "code": "T ==> Expression Integer\nD ==> TestDomain(T)\nitems := [2,4,4,4,5,5,7,9+x] :: List T;\nmap(sd, scan(+, items, 0$D))\n +---------------+\n +-+ +-+ +-+ +-+ | 2\n 2\\|2 \\|3 2\\|6 4\\|6 \\|7x + 64x + 256\n (1) [0,1,-----,----,-----,1,-----,------------------]\n 3 2 5 7 8\n Type: List(Expression(Integer))\neval subst(last %,x=0)\n\n (2) 2\n Type: Expression(Integer)\n", "language": "Axiom" }, { "code": " MAXITEMS = 100\n FOR i% = 1 TO 8\n READ n\n PRINT \"Value = \"; n \", running SD = \" FNrunningsd(n)\n NEXT\n END\n\n DATA 2,4,4,4,5,5,7,9\n\n DEF FNrunningsd(n)\n PRIVATE list(), i%\n DIM list(MAXITEMS)\n i% += 1\n list(i%) = n\n = SQR(MOD(list())^2/i% - (SUM(list())/i%)^2)\n", "language": "BBC-BASIC" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef enum Action { STDDEV, MEAN, VAR, COUNT } Action;\n\ntypedef struct stat_obj_struct {\n double sum, sum2;\n size_t num;\n Action action;\n} sStatObject, *StatObject;\n\nStatObject NewStatObject( Action action )\n{\n StatObject so;\n\n so = malloc(sizeof(sStatObject));\n so->sum = 0.0;\n so->sum2 = 0.0;\n so->num = 0;\n so->action = action;\n return so;\n}\n#define FREE_STAT_OBJECT(so) \\\n free(so); so = NULL\ndouble stat_obj_value(StatObject so, Action action)\n{\n double num, mean, var, stddev;\n\n if (so->num == 0.0) return 0.0;\n num = so->num;\n if (action==COUNT) return num;\n mean = so->sum/num;\n if (action==MEAN) return mean;\n var = so->sum2/num - mean*mean;\n if (action==VAR) return var;\n stddev = sqrt(var);\n if (action==STDDEV) return stddev;\n return 0;\n}\n\ndouble stat_object_add(StatObject so, double v)\n{\n so->num++;\n so->sum += v;\n so->sum2 += v*v;\n return stat_obj_value(so, so->action);\n}\n", "language": "C" }, { "code": "double v[] = { 2,4,4,4,5,5,7,9 };\n\nint main()\n{\n int i;\n StatObject so = NewStatObject( STDDEV );\n\n for(i=0; i < sizeof(v)/sizeof(double) ; i++)\n printf(\"val: %lf std dev: %lf\\n\", v[i], stat_object_add(so, v[i]));\n\n FREE_STAT_OBJECT(so);\n return 0;\n}\n", "language": "C" }, { "code": "#include <cassert>\n#include <cmath>\n#include <vector>\n#include <iostream>\n\ntemplate<int N> struct MomentsAccumulator_\n{\n\tstd::vector<double> m_;\n\tMomentsAccumulator_() : m_(N + 1, 0.0) {}\n\tvoid operator()(double v)\n\t{\n\t\tdouble inc = 1.0;\n\t\tfor (auto& mi : m_)\n\t\t{\n\t\t\tmi += inc;\n\t\t\tinc *= v;\n\t\t}\n\t}\n};\n\ndouble Stdev(const std::vector<double>& moments)\n{\n\tassert(moments.size() > 2);\n\tassert(moments[0] > 0.0);\n\tconst double mean = moments[1] / moments[0];\n\tconst double meanSquare = moments[2] / moments[0];\n\treturn sqrt(meanSquare - mean * mean);\n}\n\nint main(void)\n{\n\tstd::vector<int> data({ 2, 4, 4, 4, 5, 5, 7, 9 });\n\tMomentsAccumulator_<2> accum;\n\tfor (auto d : data)\n\t{\n\t\taccum(d);\n\t\tstd::cout << \"Running stdev: \" << Stdev(accum.m_) << \"\\n\";\n\t}\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace standardDeviation\n{\n class Program\n {\n static void Main(string[] args)\n {\n List<double> nums = new List<double> { 2, 4, 4, 4, 5, 5, 7, 9 };\n for (int i = 1; i <= nums.Count; i++)\n Console.WriteLine(sdev(nums.GetRange(0, i)));\n }\n\n static double sdev(List<double> nums)\n {\n List<double> store = new List<double>();\n foreach (double n in nums)\n store.Add((n - nums.Average()) * (n - nums.Average()));\n\n return Math.Sqrt(store.Sum() / store.Count);\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(defn stateful-std-deviation[x]\n (letfn [(std-dev[x]\n (let [v (deref (find-var (symbol (str *ns* \"/v\"))))]\n (swap! v conj x)\n (let [m (/ (reduce + @v) (count @v))]\n (Math/sqrt (/ (reduce + (map #(* (- m %) (- m %)) @v)) (count @v))))))]\n (when (nil? (resolve 'v))\n (intern *ns* 'v (atom [])))\n (std-dev x)))\n", "language": "Clojure" }, { "code": "IDENTIFICATION DIVISION.\nPROGRAM-ID. run-stddev.\nenvironment division.\ninput-output section.\nfile-control.\n select input-file assign to \"input.txt\"\n organization is line sequential.\ndata division.\nfile section.\nfd input-file.\n 01 inp-record.\n 03 inp-fld pic 9(03).\nworking-storage section.\n01 filler pic 9(01) value 0.\n 88 no-more-input value 1.\n01 ws-tb-data.\n 03 ws-tb-size pic 9(03).\n 03 ws-tb-table.\n 05 ws-tb-fld pic s9(05)v9999 comp-3 occurs 0 to 100 times\n depending on ws-tb-size.\n01 ws-stddev pic s9(05)v9999 comp-3.\nPROCEDURE DIVISION.\n move 0 to ws-tb-size\n open input input-file\n read input-file\n at end\n set no-more-input to true\n end-read\n perform\n test after\n until no-more-input\n add 1 to ws-tb-size\n move inp-fld to ws-tb-fld (ws-tb-size)\n call 'stddev' using by reference ws-tb-data\n ws-stddev\n display 'inp=' inp-fld ' stddev=' ws-stddev\n read input-file at end set no-more-input to true end-read\n end-perform\n close input-file\n stop run.\nend program run-stddev.\nIDENTIFICATION DIVISION.\nPROGRAM-ID. stddev.\ndata division.\nworking-storage section.\n01 ws-tbx pic s9(03) comp.\n01 ws-tb-work.\n 03 ws-sum pic s9(05)v9999 comp-3 value +0.\n 03 ws-sumsq pic s9(05)v9999 comp-3 value +0.\n 03 ws-avg pic s9(05)v9999 comp-3 value +0.\nlinkage section.\n01 ws-tb-data.\n 03 ws-tb-size pic 9(03).\n 03 ws-tb-table.\n 05 ws-tb-fld pic s9(05)v9999 comp-3 occurs 0 to 100 times\n depending on ws-tb-size.\n01 ws-stddev pic s9(05)v9999 comp-3.\nPROCEDURE DIVISION using ws-tb-data ws-stddev.\n compute ws-sum = 0\n perform test before varying ws-tbx from 1 by +1 until ws-tbx > ws-tb-size\n compute ws-sum = ws-sum + ws-tb-fld (ws-tbx)\n end-perform\n compute ws-avg rounded = ws-sum / ws-tb-size\n compute ws-sumsq = 0\n perform test before varying ws-tbx from 1 by +1 until ws-tbx > ws-tb-size\n compute ws-sumsq = ws-sumsq\n + (ws-tb-fld (ws-tbx) - ws-avg) ** 2.0\n end-perform\n compute ws-stddev = ( ws-sumsq / ws-tb-size) ** 0.5\n goback.\nend program stddev.\n", "language": "COBOL" }, { "code": "sample output:\ninp=002 stddev=+00000.0000\ninp=004 stddev=+00001.0000\ninp=004 stddev=+00000.9427\ninp=004 stddev=+00000.8660\ninp=005 stddev=+00000.9797\ninp=005 stddev=+00001.0000\ninp=007 stddev=+00001.3996\ninp=009 stddev=+00002.0000\n", "language": "COBOL" }, { "code": "class StandardDeviation\n constructor: ->\n @sum = 0\n @sumOfSquares = 0\n @values = 0\n @deviation = 0\n\n include: ( n ) ->\n @values += 1\n @sum += n\n @sumOfSquares += n * n\n mean = @sum / @values\n mean *= mean\n @deviation = Math.sqrt @sumOfSquares / @values - mean\n\ndev = new StandardDeviation\nvalues = [ 2, 4, 4, 4, 5, 5, 7, 9 ]\ntmp = []\n\nfor value in values\n tmp.push value\n dev.include value\n console.log \"\"\"\n Values: #{ tmp }\n Standard deviation: #{ dev.deviation }\n\n \"\"\"\n", "language": "CoffeeScript" }, { "code": "(defun running-stddev ()\n (let ((sum 0) (sq 0) (n 0))\n (lambda (x)\n (incf sum x) (incf sq (* x x)) (incf n)\n (/ (sqrt (- (* n sq) (* sum sum))) n))))\n\nCL-USER> (loop with f = (running-stddev) for i in '(2 4 4 4 5 5 7 9) do\n\t(format t \"~a ~a~%\" i (funcall f i)))\nNIL\n2 0.0\n4 1.0\n4 0.94280905\n4 0.8660254\n5 0.97979593\n5 1.0\n7 1.3997085\n9 2.0\n", "language": "Common-Lisp" }, { "code": "CL-USER> (setf fn (running-stddev))\n#<Interpreted Closure (:INTERNAL RUNNING-STDDEV) @ #x21b9a492>\nCL-USER> (funcall fn 2)\n0.0\nCL-USER> (funcall fn 4)\n1.0\nCL-USER> (funcall fn 4)\n0.94280905\nCL-USER> (funcall fn 4)\n0.8660254\nCL-USER> (funcall fn 5)\n0.97979593\nCL-USER> (funcall fn 5)\n1.0\nCL-USER> (funcall fn 7)\n1.3997085\nCL-USER> (funcall fn 9)\n2.0\n", "language": "Common-Lisp" }, { "code": "MODULE StandardDeviation;\nIMPORT StdLog, Args,Strings,Math;\n\nPROCEDURE Mean(x: ARRAY OF REAL; n: INTEGER; OUT mean: REAL);\nVAR\n\ti: INTEGER;\n\ttotal: REAL;\nBEGIN\n\ttotal := 0.0;\n\tFOR i := 0 TO n - 1 DO total := total + x[i] END;\n\tmean := total /n\nEND Mean;\n\nPROCEDURE SDeviation(x : ARRAY OF REAL;n: INTEGER): REAL;\nVAR\n\ti: INTEGER;\n\tmean,sum: REAL;\nBEGIN\n\tMean(x,n,mean);\n\tsum := 0.0;\n\tFOR i := 0 TO n - 1 DO\n\t\tsum:= sum + ((x[i] - mean) * (x[i] - mean));\n\tEND;\n\tRETURN Math.Sqrt(sum/n);\nEND SDeviation;\n\nPROCEDURE Do*;\nVAR\n\tp: Args.Params;\n\tx: POINTER TO ARRAY OF REAL;\n\ti,done: INTEGER;\nBEGIN\n\tArgs.Get(p);\n\tIF p.argc > 0 THEN\n\t\tNEW(x,p.argc);\n\t\tFOR i := 0 TO p.argc - 1 DO x[i] := 0.0 END;\n\t\tFOR i := 0 TO p.argc - 1 DO\n\t\t\tStrings.StringToReal(p.args[i],x[i],done);\n\t\t\tStdLog.Int(i + 1);StdLog.String(\" :> \");StdLog.Real(SDeviation(x,i + 1));StdLog.Ln\n\t\tEND\n\tEND\nEND Do;\nEND StandardDeviation.\n", "language": "Component-Pascal" }, { "code": "class StdDevAccumulator\n def initialize\n @n, @sum, @sum2 = 0, 0.0, 0.0\n end\n\n def <<(num)\n @n += 1\n @sum += num\n @sum2 += num**2\n Math.sqrt (@sum2 * @n - @sum**2) / @n**2\n end\nend\n\nsd = StdDevAccumulator.new\ni = 0\n[2,4,4,4,5,5,7,9].each { |n| puts \"adding #{n}: stddev of #{i+=1} samples is #{sd << n}\" }\n", "language": "Crystal" }, { "code": "def sdaccum\n n, sum, sum2 = 0, 0.0, 0.0\n ->(num : Int32) do\n n += 1\n sum += num\n sum2 += num**2\n Math.sqrt( (sum2 * n - sum**2) / n**2 )\n end\nend\n\nsd = sdaccum\n[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), \", \"}\n", "language": "Crystal" }, { "code": "import std.stdio, std.math;\n\nstruct StdDev {\n real sum = 0.0, sqSum = 0.0;\n long nvalues;\n\n void addNumber(in real input) pure nothrow {\n nvalues++;\n sum += input;\n sqSum += input ^^ 2;\n }\n\n real getStdDev() const pure nothrow {\n if (nvalues == 0)\n return 0.0;\n immutable real mean = sum / nvalues;\n return sqrt(sqSum / nvalues - mean ^^ 2);\n }\n}\n\nvoid main() {\n StdDev stdev;\n\n foreach (el; [2.0, 4, 4, 4, 5, 5, 7, 9]) {\n stdev.addNumber(el);\n writefln(\"%e\", stdev.getStdDev());\n }\n}\n", "language": "D" }, { "code": "program prj_CalcStdDerv;\n\n{$APPTYPE CONSOLE}\n\nuses\n Math;\n\nvar Series:Array of Extended;\n UserString:String;\n\n\nfunction AppendAndCalc(NewVal:Extended):Extended;\n\nbegin\n setlength(Series,high(Series)+2);\n Series[high(Series)] := NewVal;\n result := PopnStdDev(Series);\nend;\n\nconst data:array[0..7] of Extended =\n (2,4,4,4,5,5,7,9);\n\nvar rr: Extended;\nbegin\n setlength(Series,0);\n for rr in data do\n begin\n writeln(rr,' -> ',AppendAndCalc(rr));\n end;\n Readln;\nend.\n", "language": "Delphi" }, { "code": "def makeRunningStdDev() {\n var sum := 0.0\n var sumSquares := 0.0\n var count := 0.0\n\n def insert(v) {\n sum += v\n sumSquares += v ** 2\n count += 1\n }\n\n /** Returns the standard deviation of the inputs so far, or null if there\n have been no inputs. */\n def stddev() {\n if (count > 0) {\n def meanSquares := sumSquares/count\n def mean := sum/count\n def variance := meanSquares - mean**2\n return variance.sqrt()\n }\n }\n\n return [insert, stddev]\n}\n", "language": "E" }, { "code": "? def [insert, stddev] := makeRunningStdDev()\n# value: <insert>, <stddev>\n\n? [stddev()]\n# value: [null]\n\n? for value in [2,4,4,4,5,5,7,9] {\n> insert(value)\n> println(stddev())\n> }\n0.0\n1.0\n0.9428090415820626\n0.8660254037844386\n0.9797958971132716\n1.0\n1.3997084244475297\n2.0\n", "language": "E" }, { "code": "global sum sum2 n .\nproc sd x . r .\n sum += x\n sum2 += x * x\n n += 1\n r = sqrt (sum2 / n - sum * sum / n / n)\n.\nv[] = [ 2 4 4 4 5 5 7 9 ]\nfor v in v[]\n sd v r\n print v & \" \" & r\n.\n", "language": "EasyLang" }, { "code": "defmodule Standard_deviation do\n def add_sample( pid, n ), do: send( pid, {:add, n} )\n\n def create, do: spawn_link( fn -> loop( [] ) end )\n\n def destroy( pid ), do: send( pid, :stop )\n\n def get( pid ) do\n send( pid, {:get, self()} )\n receive do\n { :get, value, _pid } -> value\n end\n end\n\n def task do\n pid = create()\n for x <- [2,4,4,4,5,5,7,9], do: add_print( pid, x, add_sample(pid, x) )\n destroy( pid )\n end\n\n defp add_print( pid, n, _add ) do\n IO.puts \"Standard deviation #{ get(pid) } when adding #{ n }\"\n end\n\n defp loop( ns ) do\n receive do\n {:add, n} -> loop( [n | ns] )\n {:get, pid} ->\n send( pid, {:get, loop_calculate( ns ), self()} )\n loop( ns )\n :stop -> :ok\n end\n end\n\n defp loop_calculate( ns ) do\n average = loop_calculate_average( ns )\n :math.sqrt( loop_calculate_average( for x <- ns, do: :math.pow(x - average, 2) ) )\n end\n\n defp loop_calculate_average( ns ), do: Enum.sum( ns ) / length( ns )\nend\n\nStandard_deviation.task\n", "language": "Elixir" }, { "code": "(defun running-std (items)\n (let ((running-sum 0)\n (running-len 0)\n (running-squared-sum 0)\n (result 0))\n (dolist (item items)\n (setq running-sum (+ running-sum item))\n (setq running-len (1+ running-len))\n (setq running-squared-sum (+ running-squared-sum (* item item)))\n (setq result (sqrt (- (/ running-squared-sum (float running-len))\n (/ (* running-sum running-sum)\n (float (* running-len running-len))))))\n (message \"%f\" result))\n result))\n\n(running-std '(2 4 4 4 5 5 7 9))\n", "language": "Emacs-Lisp" }, { "code": "(let ((x '(2 4 4 4 5 5 7 9)))\n (string-to-number (calc-eval \"sqrt(vpvar($1))\" nil (append '(vec) x))))\n", "language": "Emacs-Lisp" }, { "code": ";; lexical-binding: t\n(require 'generator)\n\n(iter-defun std-dev-gen (lst)\n (let ((sum 0)\n (avg 0)\n (tmp '())\n (std 0))\n (dolist (i lst)\n (setq i (float i))\n (push i tmp)\n (setq sum (+ sum i))\n (setq avg (/ sum (length tmp)))\n (setq std 0)\n (dolist (j tmp)\n (setq std (+ std (expt (- j avg) 2))))\n (setq std (/ std (length tmp)))\n (setq std (sqrt std))\n (iter-yield std))))\n\n(let* ((test-data '(2 4 4 4 5 5 7 9))\n (generator (std-dev-gen test-data)))\n (dolist (i test-data)\n (message \"with %d: %f\" i (iter-next generator))))\n", "language": "Emacs-Lisp" }, { "code": "-module( standard_deviation ).\n\n-export( [add_sample/2, create/0, destroy/1, get/1, task/0] ).\n\n-compile({no_auto_import,[get/1]}).\n\nadd_sample( Pid, N ) -> Pid ! {add, N}.\n\ncreate() -> erlang:spawn_link( fun() -> loop( [] ) end ).\n\ndestroy( Pid ) -> Pid ! stop.\n\nget( Pid ) ->\n\tPid ! {get, erlang:self()},\n\treceive\n\t{get, Value, Pid} -> Value\n\tend.\n\ntask() ->\n\tPid = create(),\n\t[add_print(Pid, X, add_sample(Pid, X)) || X <- [2,4,4,4,5,5,7,9]],\n\tdestroy( Pid ).\n\nadd_print( Pid, N, _Add ) -> io:fwrite( \"Standard deviation ~p when adding ~p~n\", [get(Pid), N] ).\n\nloop( Ns ) ->\n\treceive\n\t{add, N} -> loop( [N | Ns] );\n\t{get, Pid} ->\n\t\tPid ! {get, loop_calculate( Ns ), erlang:self()},\n\t\tloop( Ns );\n\tstop -> ok\n\tend.\n\nloop_calculate( Ns ) ->\n\tAverage = loop_calculate_average( Ns ),\n\tmath:sqrt( loop_calculate_average([math:pow(X - Average, 2) || X <- Ns]) ).\n\nloop_calculate_average( Ns ) -> lists:sum( Ns ) / erlang:length( Ns ).\n", "language": "Erlang" }, { "code": "USING: accessors io kernel math math.functions math.parser\nsequences ;\nIN: standard-deviator\n\nTUPLE: standard-deviator sum sum^2 n ;\n\n: <standard-deviator> ( -- standard-deviator )\n 0.0 0.0 0 standard-deviator boa ;\n\n: current-std ( standard-deviator -- std )\n [ [ sum^2>> ] [ n>> ] bi / ]\n [ [ sum>> ] [ n>> ] bi / sq ] bi - sqrt ;\n\n: add-value ( value standard-deviator -- )\n [ nip [ 1 + ] change-n drop ]\n [ [ + ] change-sum drop ]\n [ [ [ sq ] dip + ] change-sum^2 drop ] 2tri ;\n\n: main ( -- )\n { 2 4 4 4 5 5 7 9 }\n <standard-deviator> [ [ add-value ] curry each ] keep\n current-std number>string print ;\n", "language": "Factor" }, { "code": "01.01 C-- TEST SET\n01.10 S T(1)=2;S T(2)=4;S T(3)=4;S T(4)=4\n01.20 S T(5)=5;S T(6)=5;S T(7)=7;S T(8)=9\n01.30 D 2.1\n01.35 T %6.40\n01.40 F I=1,8;S A=T(I);D 2.2;T \"VAL\",A;D 2.3;T \" SD\",A,!\n01.50 Q\n\n02.01 C-- RUNNING STDDEV\n02.02 C-- 2.1: INITIALIZE\n02.03 C-- 2.2: INSERT VALUE A\n02.04 C-- 2.3: A = CURRENT STDDEV\n02.10 S XN=0;S XS=0;S XQ=0\n02.20 S XN=XN+1;S XS=XS+A;S XQ=XQ+A*A\n02.30 S A=FSQT(XQ/XN - (XS/XN)^2)\n", "language": "FOCAL" }, { "code": ": f+! ( x addr -- ) dup f@ f+ f! ;\n\n: st-count ( stats -- n ) f@ ;\n: st-sum ( stats -- sum ) float+ f@ ;\n: st-sumsq ( stats -- sum*sum ) 2 floats + f@ ;\n\n: st-mean ( stats -- mean )\n dup st-sum st-count f/ ;\n\n: st-variance ( stats -- var )\n dup st-sumsq\n dup st-mean fdup f* dup st-count f* f-\n st-count f/ ;\n\n: st-stddev ( stats -- stddev )\n st-variance fsqrt ;\n\n: st-add ( fnum stats -- )\n dup\n 1e dup f+! float+\n fdup dup f+! float+\n fdup f* f+!\n std-stddev ;\n", "language": "Forth" }, { "code": ": st-count ( stats -- n ) f@ ;\n: st-mean ( stats -- mean ) float+ f@ ;\n: st-nvar ( stats -- n*var ) 2 floats + f@ ;\n\n: st-variance ( stats -- var ) dup st-nvar st-count f/ ;\n: st-stddev ( stats -- stddev ) st-variance fsqrt ;\n\n: st-add ( x stats -- )\n dup\n 1e dup f+!\t\t\t\\ update count\n fdup dup st-mean f- fswap\n ( delta x )\n fover dup st-count f/\n ( delta x delta/n )\n float+ dup f+!\t\t\\ update mean\n ( delta x )\n dup f@ f- f* float+ f+!\t\\ update nvar\n st-stddev ;\n", "language": "Forth" }, { "code": "create stats 0e f, 0e f, 0e f,\n\n2e stats st-add f. \\ 0.\n4e stats st-add f. \\ 1.\n4e stats st-add f. \\ 0.942809041582063\n4e stats st-add f. \\ 0.866025403784439\n5e stats st-add f. \\ 0.979795897113271\n5e stats st-add f. \\ 1.\n7e stats st-add f. \\ 1.39970842444753\n9e stats st-add f. \\ 2.\n", "language": "Forth" }, { "code": "program standard_deviation\n implicit none\n integer(kind=4), parameter :: dp = kind(0.0d0)\n\n real(kind=dp), dimension(:), allocatable :: vals\n integer(kind=4) :: i\n\n real(kind=dp), dimension(8) :: sample_data = (/ 2, 4, 4, 4, 5, 5, 7, 9 /)\n\n do i = lbound(sample_data, 1), ubound(sample_data, 1)\n call sample_add(vals, sample_data(i))\n write(*, fmt='(''#'',I1,1X,''value = '',F3.1,1X,''stddev ='',1X,F10.8)') &\n i, sample_data(i), stddev(vals)\n end do\n\n if (allocated(vals)) deallocate(vals)\ncontains\n ! Adds value :val: to array :population: dynamically resizing array\n subroutine sample_add(population, val)\n real(kind=dp), dimension(:), allocatable, intent (inout) :: population\n real(kind=dp), intent (in) :: val\n\n real(kind=dp), dimension(:), allocatable :: tmp\n integer(kind=4) :: n\n\n if (.not. allocated(population)) then\n allocate(population(1))\n population(1) = val\n else\n n = size(population)\n call move_alloc(population, tmp)\n\n allocate(population(n + 1))\n population(1:n) = tmp\n population(n + 1) = val\n endif\n end subroutine sample_add\n\n ! Calculates standard deviation for given set of values\n real(kind=dp) function stddev(vals)\n real(kind=dp), dimension(:), intent(in) :: vals\n real(kind=dp) :: mean\n integer(kind=4) :: n\n\n n = size(vals)\n mean = sum(vals)/n\n stddev = sqrt(sum((vals - mean)**2)/n)\n end function stddev\nend program standard_deviation\n", "language": "Fortran" }, { "code": " REAL FUNCTION STDDEV(X)\t!Standard deviation for successive values.\n REAL X\t\t!The latest value.\n REAL V\t\t!Scratchpad.\n INTEGER N\t!Ongoing: count of the values.\n REAL EX,EX2\t!Ongoing: sum of X and X**2.\n SAVE N,EX,EX2\t\t!Retain values from one invocation to the next.\n DATA N,EX,EX2/0,0.0,0.0/\t!Initial values.\n N = N + 1\t\t!Another value arrives.\n EX = X + EX\t\t!Augment the total.\n EX2 = X**2 + EX2\t!Augment the sum of squares.\n V = EX2/N - (EX/N)**2\t!The variance, but, it might come out negative!\n STDDEV = SIGN(SQRT(ABS(V)),V)\t!Protect the SQRT, but produce a negative result if so.\n END FUNCTION STDDEV\t!For the sequence of received X values.\n\n REAL FUNCTION STDDEVP(X)\t!Standard deviation for successive values.\n REAL X\t\t!The latest value.\n INTEGER N\t!Ongoing: count of the values.\n REAL A,V\t\t!Ongoing: average, and sum of squared deviations.\n SAVE N,A,V\t\t!Retain values from one invocation to the next.\n DATA N,A,V/0,0.0,0.0/\t!Initial values.\n N = N + 1\t\t!Another value arrives.\n V = (N - 1)*(X - A)**2 /N + V\t!First, as it requires the existing average.\n A = (X - A)/N + A\t\t!= [x + (n - 1).A)]/n: recover the total from the average.\n STDDEVP = SQRT(V/N)\t!V can never be negative, even with limited precision.\n END FUNCTION STDDEVP\t!For the sequence of received X values.\n\n REAL FUNCTION STDDEVW(X)\t!Standard deviation for successive values.\n REAL X\t\t!The latest value.\n REAL V,D\t\t!Scratchpads.\n INTEGER N\t!Ongoing: count of the values.\n REAL EX,EX2\t!Ongoing: sum of X and X**2.\n REAL W\t\t!Ongoing: working mean.\n SAVE N,EX,EX2,W\t\t!Retain values from one invocation to the next.\n DATA N,EX,EX2/0,0.0,0.0/\t!Initial values.\n IF (N.LE.0) W = X\t!Take the first value as the working mean.\n N = N + 1\t\t!Another value arrives.\n D = X - W\t\t!Its deviation from the working mean.\n EX = D + EX\t\t!Augment the total.\n EX2 = D**2 + EX2\t!Augment the sum of squares.\n V = EX2/N - (EX/N)**2\t!The variance, but, it might come out negative!\n STDDEVW = SIGN(SQRT(ABS(V)),V)\t!Protect the SQRT, but produce a negative result if so.\n END FUNCTION STDDEVW\t!For the sequence of received X values.\n\n REAL FUNCTION STDDEVPW(X)\t!Standard deviation for successive values.\n REAL X\t\t!The latest value.\n INTEGER N\t!Ongoing: count of the values.\n REAL A,V\t\t!Ongoing: average, and sum of squared deviations.\n REAL W\t\t!Ongoing: working mean.\n SAVE N,A,V,W\t\t!Retain values from one invocation to the next.\n DATA N,A,V/0,0.0,0.0/\t!Initial values.\n IF (N.LE.0) W = X\t!Oh for self-modifying code!\n N = N + 1\t\t!Another value arrives.\n D = X - W\t\t!Its deviation from the working mean.\n V = (N - 1)*(D - A)**2 /N + V\t!First, as it requires the existing average.\n A = (D - A)/N + A\t\t!= [x + (n - 1).A)]/n: recover the total from the average.\n STDDEVPW = SQRT(V/N)\t!V can never be negative, even with limited precision.\n END FUNCTION STDDEVPW\t!For the sequence of received X values.\n\n PROGRAM TEST\n INTEGER I\t\t!A stepper.\n REAL A(8)\t\t!The example data.\n DATA A/2.0,3*4.0,2*5.0,7.0,9.0/\t!Alas, another opportunity to use @ passed over.\n REAL B\t\t!An offsetting base.\n WRITE (6,1)\n 1 FORMAT (\"Progressive calculation of the standard deviation.\"/\n 1 \" I\",7X,\"A(I) EX EX2 Av V*N Ed Ed2 wAv V*N\")\n B = 1000000\t\t!Provoke truncation error.\n DO I = 1,8\t\t\t!Step along the data series,\n WRITE (6,2) I,INT(A(I) + B),\t\t!No fractional part, so I don't want F11.0.\n 1 STDDEV(A(I) + B),STDDEVP(A(I) + B),\t!Showing progressive values.\n 2 STDDEVW(A(I) + B),STDDEVPW(A(I) + B)\t!These with a working mean.\n 2 FORMAT (I2,I11,1X,4F12.6)\t\t!Should do for the example.\n END DO\t\t\t\t!On to the next value.\n END\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nFunction calcStandardDeviation(number As Double) As Double\n Static a() As Double\n Redim Preserve a(0 To UBound(a) + 1)\n Dim ub As UInteger = UBound(a)\n a(ub) = number\n Dim sum As Double = 0.0\n For i As UInteger = 0 To ub\n sum += a(i)\n Next\n Dim mean As Double = sum / (ub + 1)\n Dim diff As Double\n sum = 0.0\n For i As UInteger = 0 To ub\n diff = a(i) - mean\n sum += diff * diff\n Next\n Return Sqr(sum/ (ub + 1))\nEnd Function\n\nDim a(0 To 7) As Double = {2, 4, 4, 4, 5, 5, 7, 9}\n\nFor i As UInteger = 0 To 7\n Print \"Added\"; a(i); \" SD now : \"; calcStandardDeviation(a(i))\nNext\n\nPrint\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc newRsdv() func(float64) float64 {\n var n, a, q float64\n return func(x float64) float64 {\n n++\n a1 := a+(x-a)/n\n q, a = q+(x-a)*(x-a1), a1\n return math.Sqrt(q/n)\n }\n}\n\nfunc main() {\n r := newRsdv()\n for _, x := range []float64{2,4,4,4,5,5,7,9} {\n fmt.Println(r(x))\n }\n}\n", "language": "Go" }, { "code": "List samples = []\n\ndef stdDev = { def sample ->\n samples << sample\n def sum = samples.sum()\n def sumSq = samples.sum { it * it }\n def count = samples.size()\n (sumSq/count - (sum/count)**2)**0.5\n}\n\n[2,4,4,4,5,5,7,9].each {\n println \"${stdDev(it)}\"\n}\n", "language": "Groovy" }, { "code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List (foldl') -- '\nimport Data.STRef\nimport Control.Monad.ST\n\ndata Pair a b = Pair !a !b\n\nsumLen :: [Double] -> Pair Double Double\nsumLen = fiof2 . foldl' (\\(Pair s l) x -> Pair (s+x) (l+1)) (Pair 0.0 0) --'\n where fiof2 (Pair s l) = Pair s (fromIntegral l)\n\ndivl :: Pair Double Double -> Double\ndivl (Pair _ 0.0) = 0.0\ndivl (Pair s l) = s / l\n\nsd :: [Double] -> Double\nsd xs = sqrt $ foldl' (\\a x -> a+(x-m)^2) 0 xs / l --'\n where p@(Pair s l) = sumLen xs\n m = divl p\n\nmkSD :: ST s (Double -> ST s Double)\nmkSD = go <$> newSTRef []\n where go acc x =\n modifySTRef acc (x:) >> (sd <$> readSTRef acc)\n\nmain = mapM_ print $ runST $\n mkSD >>= forM [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]\n", "language": "Haskell" }, { "code": "import Data.List (mapAccumL)\n\n\n-------------- CUMULATIVE STANDARD DEVIATION -------------\n\ncumulativeStdDevns :: [Float] -> [Float]\ncumulativeStdDevns = snd . mapAccumL go (0, 0) . zip [1.0..]\n where\n go (s, q) (i, x) =\n let _s = s + x\n _q = q + (x ^ 2)\n in ((_s, _q), sqrt ((_q / i) - ((_s / i) ^ 2)))\n\n\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain = mapM_ print $ cumulativeStdDevns [2, 4, 4, 4, 5, 5, 7, 9]\n", "language": "Haskell" }, { "code": "using Lambda;\n\nclass Main {\n\tstatic function main():Void {\n\t\tvar nums = [2, 4, 4, 4, 5, 5, 7, 9];\n\t\tfor (i in 1...nums.length+1)\t\t\t\n\t\t\tSys.println(sdev(nums.slice(0, i)));\n\t}\n\t\n\tstatic function average<T:Float>(nums:Array<T>):Float {\n\t\treturn nums.fold(function(n, t) return n + t, 0) / nums.length;\n\t}\n\n\tstatic function sdev<T:Float>(nums:Array<T>):Float {\n\t\tvar store = [];\n\t\tvar avg = average(nums);\n\t\tfor (n in nums) {\n\t\t\tstore.push((n - avg) * (n - avg));\n\t\t}\n\t\t\n\t\treturn Math.sqrt(average(store));\n\t}\n}\n", "language": "Haxe" }, { "code": "REAL :: n=8, set(n), sum=0, sum2=0\n\nset = (2,4,4,4,5,5,7,9)\n\nDO k = 1, n\n WRITE() 'Adding ' // set(k) // 'stdev = ' // stdev(set(k))\nENDDO\n\nEND ! end of \"main\"\n\nFUNCTION stdev(x)\n USE : sum, sum2, k\n sum = sum + x\n sum2 = sum2 + x*x\n stdev = ( sum2/k - (sum/k)^2) ^ 0.5\n END\n", "language": "HicEst" }, { "code": "procedure main()\n\nstddev() # reset state / empty\nevery s := stddev(![2,4,4,4,5,5,7,9]) do\n write(\"stddev (so far) := \",s)\n\nend\n\nprocedure stddev(x) # running standard deviation\nstatic X,sumX,sum2X\n\n if /x then { # reset state\n X := []\n sumX := sum2X := 0.\n }\n else { # accumulate\n put(X,x)\n sumX +:= x\n sum2X +:= x^2\n return sqrt( (sum2X / *X) - (sumX / *X)^2 )\n }\nend\n", "language": "Icon" }, { "code": "100 PROGRAM \"StDev.bas\"\n110 LET N=8\n120 NUMERIC ARR(1 TO N)\n130 FOR I=1 TO N\n140 READ ARR(I)\n150 NEXT\n160 DEF STDEV(N)\n170 LET S1,S2=0\n180 FOR I=1 TO N\n190 LET S1=S1+ARR(I)^2:LET S2=S2+ARR(I)\n200 NEXT\n210 LET STDEV=SQR((N*S1-S2^2)/N^2)\n220 END DEF\n230 FOR J=1 TO N\n240 PRINT J;\"item =\";ARR(J),\"standard dev =\";STDEV(J)\n250 NEXT\n260 DATA 2,4,4,4,5,5,7,9\n", "language": "IS-BASIC" }, { "code": " mean=: +/ % #\n dev=: - mean\n stddevP=: [: %:@mean *:@dev NB. A) 3 equivalent defs for stddevP\n stddevP=: [: mean&.:*: dev NB. B) uses Under (&.:) to apply inverse of *: after mean\n stddevP=: %:@(mean@:*: - *:@mean) NB. C) sqrt of ((mean of squares) - (square of mean))\n\n\n stddevP\\ 2 4 4 4 5 5 7 9\n0 1 0.942809 0.866025 0.979796 1 1.39971 2\n", "language": "J" }, { "code": " of =: @:\n sqrt =: %:\n sum =: +/\n squares=: *:\n data =: ]\n mean =: sum % #\n\n stddevP=: sqrt of mean of squares of (data-mean)\n\n stddevP\\ 2 4 4 4 5 5 7 9\n0 1 0.942809 0.866025 0.979796 1 1.39971 2\n", "language": "J" }, { "code": " require'stats'\n (%:@:(%~<:)@:# * stddev)\\ 2 4 4 4 5 5 7 9\n0 1 0.942809 0.866025 0.979796 1 1.39971 2\n", "language": "J" }, { "code": "public class StdDev {\n int n = 0;\n double sum = 0;\n double sum2 = 0;\n\n public double sd(double x) {\n\tn++;\n\tsum += x;\n\tsum2 += x*x;\n\n\treturn Math.sqrt(sum2/n - sum*sum/n/n);\n }\n\n public static void main(String[] args) {\n double[] testData = {2,4,4,4,5,5,7,9};\n StdDev sd = new StdDev();\n\n for (double x : testData) {\n System.out.println(sd.sd(x));\n }\n }\n}\n", "language": "Java" }, { "code": "function running_stddev() {\n var n = 0;\n var sum = 0.0;\n var sum_sq = 0.0;\n return function(num) {\n n++;\n sum += num;\n sum_sq += num*num;\n return Math.sqrt( (sum_sq / n) - Math.pow(sum / n, 2) );\n }\n}\n\nvar sd = running_stddev();\nvar nums = [2,4,4,4,5,5,7,9];\nvar stddev = [];\nfor (var i in nums)\n stddev.push( sd(nums[i]) );\n\n// using WSH\nWScript.Echo(stddev.join(', ');\n", "language": "JavaScript" }, { "code": "(function (xs) {\n\n return xs.reduce(function (a, x, i) {\n var n = i + 1,\n sum_ = a.sum + x,\n squaresSum_ = a.squaresSum + (x * x);\n\n return {\n sum: sum_,\n squaresSum: squaresSum_,\n stages: a.stages.concat(\n Math.sqrt((squaresSum_ / n) - Math.pow((sum_ / n), 2))\n )\n };\n\n }, {\n sum: 0,\n squaresSum: 0,\n stages: []\n }).stages\n\n})([2, 4, 4, 4, 5, 5, 7, 9]);\n", "language": "JavaScript" }, { "code": "[0, 1, 0.9428090415820626, 0.8660254037844386,\n0.9797958971132716, 1, 1.3997084244475297, 2]\n", "language": "JavaScript" }, { "code": "(() => {\n 'use strict';\n\n // ---------- CUMULATIVE STANDARD DEVIATION ----------\n\n // cumulativeStdDevns :: [Float] -> [Float]\n const cumulativeStdDevns = ns => {\n const go = ([s, q]) =>\n ([i, x]) => {\n const\n _s = s + x,\n _q = q + (x * x),\n j = 1 + i;\n return [\n [_s, _q],\n Math.sqrt(\n (_q / j) - Math.pow(_s / j, 2)\n )\n ];\n };\n return mapAccumL(go)([0, 0])(ns)[1];\n };\n\n // ---------------------- TEST -----------------------\n const main = () =>\n showLog(\n cumulativeStdDevns([\n 2, 4, 4, 4, 5, 5, 7, 9\n ])\n );\n\n // --------------------- GENERIC ---------------------\n\n // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\n const mapAccumL = f =>\n // A tuple of an accumulation and a list\n // obtained by a combined map and fold,\n // with accumulation from left to right.\n acc => xs => [...xs].reduce((a, x, i) => {\n const pair = f(a[0])([i, x]);\n return [pair[0], a[1].concat(pair[1])];\n }, [acc, []]);\n\n\n // showLog :: a -> IO ()\n const showLog = (...args) =>\n console.log(\n args\n .map(x => JSON.stringify(x, null, 2))\n .join(' -> ')\n );\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "# Compute the standard deviation of the observations\n# seen so far, given the current state as input:\ndef standard_deviation: .ssd / .n | sqrt;\n\ndef update_state(observation):\n def sq: .*.;\n ((.mean * .n + observation) / (.n + 1)) as $newmean\n | (.ssd + .n * ((.mean - $newmean) | sq)) as $ssd\n | { \"n\": (.n + 1),\n \"ssd\": ($ssd + ((observation - $newmean) | sq)),\n \"mean\": $newmean }\n;\n\ndef initial_state: { \"n\": 0, \"ssd\": 0, \"mean\": 0 };\n\n# Given an array of observations presented as input:\ndef simulate:\n def _simulate(i; observations):\n if (observations|length) <= i then empty\n else update_state(observations[i])\n | standard_deviation, _simulate(i+1; observations)\n end ;\n . as $in | initial_state | _simulate(0; $in);\n\n# Begin:\nsimulate\n", "language": "Jq" }, { "code": "$ jq -s -f Dynamic_standard_deviation.jq observations.txt\n0\n1\n0.9428090415820634\n0.8660254037844386\n0.9797958971132711\n0.9999999999999999\n1.3997084244475302\n1.9999999999999998\n", "language": "Jq" }, { "code": "# requires jq version > 1.4\ndef simulate(stream):\n foreach stream as $observation\n (initial_state;\n update_state($observation);\n standard_deviation);\n", "language": "Jq" }, { "code": "#!/bin/bash\n\n# jq is assumed to be on PATH\n\nPROGRAM='\ndef standard_deviation: .ssd / .n | sqrt;\n\ndef update_state(observation):\n def sq: .*.;\n ((.mean * .n + observation) / (.n + 1)) as $newmean\n | (.ssd + .n * ((.mean - $newmean) | sq)) as $ssd\n | { \"n\": (.n + 1),\n \"ssd\": ($ssd + ((observation - $newmean) | sq)),\n \"mean\": $newmean }\n;\n\ndef initial_state: { \"n\": 0, \"ssd\": 0, \"mean\": 0 };\n\n# Input should be [observation, null] or [observation, state]\ndef standard_deviations:\n . as $in\n | if type == \"array\" then\n (if .[1] == null then initial_state else .[1] end) as $state\n | $state | update_state($in[0])\n | standard_deviation, .\n else empty\n end\n;\n\nstandard_deviations\n'\nstate=null\nwhile read -p \"Next observation: \" observation\ndo\n result=$(echo \"[ $observation, $state ]\" | jq -c \"$PROGRAM\")\n sed -n 1p <<< \"$result\"\n state=$(sed -n 2p <<< \"$result\")\ndone\n", "language": "Jq" }, { "code": "$ ./standard_deviation_server.sh\nNext observation: 10\n0\nNext observation: 20\n5\nNext observation: 0\n8.16496580927726\n", "language": "Jq" }, { "code": "function makerunningstd(::Type{T} = Float64) where T\n ∑x = ∑x² = zero(T)\n n = 0\n function runningstd(x)\n ∑x += x\n ∑x² += x ^ 2\n n += 1\n s = ∑x² / n - (∑x / n) ^ 2\n return s\n end\n return runningstd\nend\n\ntest = Float64[2, 4, 4, 4, 5, 5, 7, 9]\nrstd = makerunningstd()\n\nprintln(\"Perform a running standard deviation of \", test)\nfor i in test\n println(\" - add $i → \", rstd(i))\nend\n", "language": "Julia" }, { "code": "// version 1.0.5-2\n\nclass CumStdDev {\n private var n = 0\n private var sum = 0.0\n private var sum2 = 0.0\n\n fun sd(x: Double): Double {\n n++\n sum += x\n sum2 += x * x\n return Math.sqrt(sum2 / n - sum * sum / n / n)\n }\n}\n\nfun main(args: Array<String>) {\n val testData = doubleArrayOf(2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0)\n val csd = CumStdDev()\n for (d in testData) println(\"Add $d => ${csd.sd(d)}\")\n}\n", "language": "Kotlin" }, { "code": " dim SD.storage$( 100) ' can call up to 100 versions, using ID to identify.. arrays are global.\n ' holds (space-separated) number of data items so far, current sum.of.values and current sum.of.squares\n\n for i =1 to 8\n read x\n print \"New data \"; x; \" so S.D. now = \"; using( \"###.######\", standard.deviation( 1, x))\n next i\n\n end\n\nfunction standard.deviation( ID, in)\n if SD.storage$( ID) =\"\" then SD.storage$( ID) =\"0 0 0\"\n num.so.far =val( word$( SD.storage$( ID), 1))\n sum.vals =val( word$( SD.storage$( ID), 2))\n sum.sqs =val( word$( SD.storage$( ID), 3))\n num.so.far =num.so.far +1\n sum.vals =sum.vals +in\n sum.sqs =sum.sqs +in^2\n\n ' standard deviation = square root of (the average of the squares less the square of the average)\n standard.deviation =( ( sum.sqs /num.so.far) - ( sum.vals /num.so.far)^2)^0.5\n\n SD.storage$( ID) =str$( num.so.far) +\" \" +str$( sum.vals) +\" \" +str$( sum.sqs)\nend function\n\n Data 2, 4, 4, 4, 5, 5, 7, 9\n", "language": "Liberty-BASIC" }, { "code": "// Stats computes a running mean and variance\n// See Knuth TAOCP vol 2, 3rd edition, page 232\n\nclass Stats:\n M = 0.0\n S = 0.0\n n = 0\n def incl(x):\n n += 1\n if n == 1:\n M = x\n else:\n let mm = (x - M)\n M += mm / n\n S += mm * (x - M)\n def mean(): return M\n //def variance(): return (if n > 1.0: S / (n - 1.0) else: 0.0) // Bessel's correction\n def variance(): return (if n > 0.0: S / n else: 0.0)\n def stddev(): return sqrt(variance())\n def count(): return n\n\ndef test_stdv() -> float:\n let v = [2,4,4,4,5,5,7,9]\n let s = Stats {}\n for(v) x: s.incl(x+0.0)\n print concat_string([\"Mean: \", string(s.mean()), \", Std.Deviation: \", string(s.stddev())], \"\")\n\ntest_stdv()\n", "language": "Lobster" }, { "code": "function stdev()\n local sum, sumsq, k = 0,0,0\n return function(n)\n sum, sumsq, k = sum + n, sumsq + n^2, k+1\n return math.sqrt((sumsq / k) - (sum/k)^2)\n end\nend\n\nldev = stdev()\nfor i, v in ipairs{2,4,4,4,5,5,7,9} do\n print(ldev(v))\nend\n", "language": "Lua" }, { "code": "runningSTDDev[n_] := (If[Not[ValueQ[$Data]], $Data = {}];StandardDeviation[AppendTo[$Data, n]])\n", "language": "Mathematica" }, { "code": " x = [2,4,4,4,5,5,7,9];\n n = length (x);\n\n m = mean (x);\n x2 = mean (x .* x);\n dev= sqrt (x2 - m * m)\n dev = 2\n", "language": "MATLAB" }, { "code": " m = cumsum(x) ./ [1:n];\t% running mean\n x2= cumsum(x.^2) ./ [1:n]; % running squares\n\n dev = sqrt(x2 - m .* m)\n dev =\n 0.00000 1.00000 0.94281 0.86603 0.97980 1.00000 1.39971 2.00000\n", "language": "MATLAB" }, { "code": "function stdDevEval(n)\ndisp(sqrt(sum((n-sum(n)/length(n)).^2)/length(n)));\nend\n", "language": "MATLAB" }, { "code": "StdDeviator = {}\nStdDeviator.count = 0\nStdDeviator.sum = 0\nStdDeviator.sumOfSquares = 0\n\nStdDeviator.add = function(x)\n self.count = self.count + 1\n self.sum = self.sum + x\n self.sumOfSquares = self.sumOfSquares + x*x\nend function\n\nStdDeviator.stddev = function()\n m = self.sum / self.count\n return sqrt(self.sumOfSquares / self.count - m*m)\nend function\n\nsd = new StdDeviator\nfor x in [2, 4, 4, 4, 5, 5, 7, 9]\n sd.add x\nend for\nprint sd.stddev\n", "language": "MiniScript" }, { "code": "class StdDev\n\tdeclare n\n\tdeclare sum\n\tdeclare sum2\n\n\tdef StdDev()\n\t\tn = 0\n\t\tsum = 0\n\t\tsum2 = 0\n\tend\n\n\tdef sd(x)\n\t\tthis.n += 1\n\t\tthis.sum += x\n\t\tthis.sum2 += x*x\n\n\t\treturn sqrt(sum2/n - sum*sum/n/n)\n\tend\nend\n\ntestData = {2,4,4,4,5,5,7,9}\nsd = new(StdDev)\n\nfor x in testData\n\tprintln sd.sd(x)\nend\n", "language": "Nanoquery" }, { "code": "import math, strutils\n\nvar sdSum, sdSum2, sdN = 0.0\n\nproc sd(x: float): float =\n sdN += 1\n sdSum += x\n sdSum2 += x * x\n sqrt(sdSum2 / sdN - sdSum * sdSum / (sdN * sdN))\n\nfor value in [float 2,4,4,4,5,5,7,9]:\n echo value, \" \", formatFloat(sd(value), precision = -1)\n", "language": "Nim" }, { "code": "import math, strutils\n\ntype SDAccum = object\n sdN, sdSum, sdSum2: float\n\nvar accum: SDAccum\n\nproc add(accum: var SDAccum; value: float): float =\n # Add a value to the accumulator. Return the standard deviation.\n accum.sdN += 1\n accum.sdSum += value\n accum.sdSum2 += value * value\n result = sqrt(accum.sdSum2 / accum.sdN - accum.sdSum * accum.sdSum / (accum.sdN * accum.sdN))\n\nfor value in [float 2, 4, 4, 4, 5, 5, 7, 9]:\n echo value, \" \", formatFloat(accum.add(value), precision = -1)\n", "language": "Nim" }, { "code": "import math, strutils\n\nfunc accumBuilder(): auto =\n var sdSum, sdSum2, sdN = 0.0\n\n result = func(value: float): float =\n sdN += 1\n sdSum += value\n sdSum2 += value * value\n result = sqrt(sdSum2 / sdN - sdSum * sdSum / (sdN * sdN))\n\nlet std = accumBuilder()\n\nfor value in [float 2, 4, 4, 4, 5, 5, 7, 9]:\n echo value, \" \", formatFloat(std(value), precision = -1)\n", "language": "Nim" }, { "code": "use Structure;\n\nbundle Default {\n class StdDev {\n nums : FloatVector;\n\n New() {\n nums := FloatVector->New();\n }\n\n function : Main(args : String[]) ~ Nil {\n sd := StdDev->New();\n test_data := [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];\n each(i : test_data) {\n sd->AddNum(test_data[i]);\n sd->GetSD()->PrintLine();\n };\n }\n\n method : public : AddNum(num : Float) ~ Nil {\n nums->AddBack(num);\n }\n\n method : public : native : GetSD() ~ Float {\n sq_diffs := 0.0;\n avg := nums->Average();\n each(i : nums) {\n num := nums->Get(i);\n sq_diffs += (num - avg) * (num - avg);\n };\n\n return (sq_diffs / nums->Size())->SquareRoot();\n }\n }\n}\n", "language": "Objeck" }, { "code": "#import <Foundation/Foundation.h>\n\n@interface SDAccum : NSObject\n{\n double sum, sum2;\n unsigned int num;\n}\n-(double)value: (double)v;\n-(unsigned int)count;\n-(double)mean;\n-(double)variance;\n-(double)stddev;\n@end\n\n@implementation SDAccum\n-(double)value: (double)v\n{\n sum += v;\n sum2 += v*v;\n num++;\n return [self stddev];\n}\n-(unsigned int)count\n{\n return num;\n}\n-(double)mean\n{\n return (num>0) ? sum/(double)num : 0.0;\n}\n-(double)variance\n{\n double m = [self mean];\n return (num>0) ? (sum2/(double)num - m*m) : 0.0;\n}\n-(double)stddev\n{\n return sqrt([self variance]);\n}\n@end\n\nint main()\n{\n @autoreleasepool {\n\n double v[] = { 2,4,4,4,5,5,7,9 };\n\n SDAccum *sdacc = [[SDAccum alloc] init];\n\n for(int i=0; i < sizeof(v)/sizeof(*v) ; i++)\n printf(\"adding %f\\tstddev = %f\\n\", v[i], [sdacc value: v[i]]);\n\n }\n return 0;\n}\n", "language": "Objective-C" }, { "code": "#import <Foundation/Foundation.h>\n\ntypedef double (^Func)(double); // a block that takes a double and returns a double\n\nFunc sdCreator() {\n __block int n = 0;\n __block double sum = 0;\n __block double sum2 = 0;\n return ^(double x) {\n sum += x;\n sum2 += x*x;\n n++;\n return sqrt(sum2/n - sum*sum/n/n);\n };\n}\n\nint main()\n{\n @autoreleasepool {\n\n double v[] = { 2,4,4,4,5,5,7,9 };\n\n Func sdacc = sdCreator();\n\n for(int i=0; i < sizeof(v)/sizeof(*v) ; i++)\n printf(\"adding %f\\tstddev = %f\\n\", v[i], sdacc(v[i]));\n\n }\n return 0;\n}\n", "language": "Objective-C" }, { "code": "let sqr x = x *. x\n\nlet stddev l =\n let n, sx, sx2 =\n List.fold_left\n (fun (n, sx, sx2) x -> succ n, sx +. x, sx2 +. sqr x)\n (0, 0., 0.) l\n in\n sqrt ((sx2 -. sqr sx /. float n) /. float n)\n\nlet _ =\n let l = [ 2.;4.;4.;4.;5.;5.;7.;9. ] in\n Printf.printf \"List: \";\n List.iter (Printf.printf \"%g \") l;\n Printf.printf \"\\nStandard deviation: %g\\n\" (stddev l)\n", "language": "OCaml" }, { "code": "Channel new [ ] over send drop const: StdValues\n\n: stddev(x)\n| l |\n StdValues receive x + dup ->l StdValues send drop\n #qs l map sum l size asFloat / l avg sq - sqrt ;\n", "language": "Oforth" }, { "code": "sdacc = .SDAccum~new\nx = .array~of(2,4,4,4,5,5,7,9)\nsd = 0\ndo i = 1 to x~size\n sd = sdacc~value(x[i])\n Say '#'i 'value =' x[i] 'stdev =' sd\nend\n\n::class SDAccum\n::method sum attribute\n::method sum2 attribute\n::method count attribute\n::method init\n self~sum = 0.0\n self~sum2 = 0.0\n self~count = 0\n::method value\n expose sum sum2 count\n parse arg x\n sum = sum + x\n sum2 = sum2 + x*x\n count = count + 1\n return self~stddev\n::method mean\n expose sum count\n return sum/count\n::method variance\n expose sum2 count\n m = self~mean\n return sum2/count - m*m\n::method stddev\n return self~sqrt(self~variance)\n::method sqrt\n arg n\n if n = 0 then return 0\n ans = n / 2\n prev = n\n do until prev = ans\n prev = ans\n ans = ( prev + ( n / prev ) ) / 2\n end\n return ans\n", "language": "OoRexx" }, { "code": "newpoint(x)={\n myT=x;\n myS=0;\n myN=1;\n [myT,myS]/myN\n};\naddpoint(x)={\n myT+=x;\n myN++;\n myS+=(myN*x-myT)^2/myN/(myN-1);\n [myT,myS]/myN\n};\naddpoints(v)={\n print(newpoint(v[1]));\n for(i=2,#v,print(addpoint(v[i])));\n print(\"Mean: \",myT/myN);\n print(\"Standard deviation: \",sqrt(myS/myN))\n};\naddpoints([2,4,4,4,5,5,7,9])\n", "language": "PARI-GP" }, { "code": "program stddev;\nuses math;\nconst\n n=8;\nvar\n arr: array[1..n] of real =(2,4,4,4,5,5,7,9);\nfunction stddev(n: integer): real;\nvar\n i: integer;\n s1,s2,variance,x: real;\nbegin\n for i:=1 to n do\n begin\n x:=arr[i];\n s1:=s1+power(x,2);\n s2:=s2+x\n end;\n variance:=((n*s1)-(power(s2,2)))/(power(n,2));\n stddev:=sqrt(variance)\nend;\nvar\n i: integer;\nbegin\n for i:=1 to n do\n begin\n writeln(i,' item=',arr[i]:2:0,' stddev=',stddev(i):18:15)\n end\nend.\n", "language": "Pascal" }, { "code": "{\n package SDAccum;\n sub new {\n\tmy $class = shift;\n\tmy $self = {};\n\t$self->{sum} = 0.0;\n\t$self->{sum2} = 0.0;\n\t$self->{num} = 0;\n\tbless $self, $class;\n\treturn $self;\n }\n sub count {\n\tmy $self = shift;\n\treturn $self->{num};\n }\n sub mean {\n\tmy $self = shift;\n\treturn ($self->{num}>0) ? $self->{sum}/$self->{num} : 0.0;\n }\n sub variance {\n\tmy $self = shift;\n\tmy $m = $self->mean;\n\treturn ($self->{num}>0) ? $self->{sum2}/$self->{num} - $m * $m : 0.0;\n }\n sub stddev {\n\tmy $self = shift;\n\treturn sqrt($self->variance);\n }\n sub value {\n\tmy $self = shift;\n\tmy $v = shift;\n\t$self->{sum} += $v;\n\t$self->{sum2} += $v * $v;\n\t$self->{num}++;\n\treturn $self->stddev;\n }\n}\n", "language": "Perl" }, { "code": "my $sdacc = SDAccum->new;\nmy $sd;\n\nforeach my $v ( 2,4,4,4,5,5,7,9 ) {\n $sd = $sdacc->value($v);\n}\nprint \"std dev = $sd\\n\";\n", "language": "Perl" }, { "code": "# <(x - <x>)²> = <x²> - <x>²\n{\n my $num, $sum, $sum2;\n sub stddev {\n\tmy $x = shift;\n\t$num++;\n\treturn sqrt(\n\t ($sum2 += $x**2) / $num -\n\t (($sum += $x) / $num)**2\n\t);\n }\n}\n\nprint stddev($_), \"\\n\" for qw(2 4 4 4 5 5 7 9);\n", "language": "Perl" }, { "code": "perl -MMath::StdDev -e '$d=new Math::StdDev;foreach my $v ( 2,4,4,4,5,5,7,9 ) {$d->Update($v); print $d->variance(),\"\\n\"}'\n", "language": "Perl" }, { "code": "use Math::StdDev;\n$d=new Math::StdDev;\nforeach my $v ( 2,4,4,4,5,5,7,9 ) {\n $d->Update($v);\n print $d->variance(),\"\\n\"\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">sdn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">sdsum</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">sdsumsq</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">sdadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">sdn</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">sdsum</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">n</span>\n <span style=\"color: #000000;\">sdsumsq</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">n</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">sdavg</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">sdsum</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">sdn</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">sddev</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">sqrt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">sdsumsq</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">sdn</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">sdsum</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">sdn</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #000080;font-style:italic;\">--test code:</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">testset</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ti</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">testset</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">ti</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">testset</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">sdadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"N=%d Item=%d Avg=%5.3f StdDev=%5.3f\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">sdavg</span><span style=\"color: #0000FF;\">(),</span><span style=\"color: #000000;\">sddev</span><span style=\"color: #0000FF;\">()})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\nclass sdcalc {\n private $cnt, $sumup, $square;\n\n function __construct() {\n $this->reset();\n }\n # callable on an instance\n function reset() {\n $this->cnt=0; $this->sumup=0; $this->square=0;\n }\n function add($f) {\n $this->cnt++;\n $this->sumup += $f;\n $this->square += pow($f, 2);\n return $this->calc();\n }\n function calc() {\n if ($this->cnt==0 || $this->sumup==0) {\n return 0;\n } else {\n return sqrt($this->square / $this->cnt - pow(($this->sumup / $this->cnt),2));\n }\n }\n }\n\n# start test, adding test data one by one\n$c = new sdcalc();\nforeach ([2,4,4,4,5,5,7,9] as $v) {\n printf('Adding %g: result %g%s', $v, $c->add($v), PHP_EOL);\n}\n", "language": "PHP" }, { "code": "(scl 2)\n\n(de stdDev ()\n (curry ((Data)) (N)\n (push 'Data N)\n (let (Len (length Data) M (*/ (apply + Data) Len))\n (sqrt\n (*/\n (sum\n '((N) (*/ (- N M) (- N M) 1.0))\n Data )\n 1.0\n Len )\n T ) ) ) )\n\n(let Fun (stdDev)\n (for N (2.0 4.0 4.0 4.0 5.0 5.0 7.0 9.0)\n (prinl (format N *Scl) \" -> \" (format (Fun N) *Scl)) ) )\n", "language": "PicoLisp" }, { "code": "*process source attributes xref;\n stddev: proc options(main);\n declare a(10) float init(1,2,3,4,5,6,7,8,9,10);\n declare stdev float;\n declare i fixed binary;\n\n stdev=std_dev(a);\n put skip list('Standard deviation', stdev);\n\n std_dev: procedure(a) returns(float);\n declare a(*) float, n fixed binary;\n n=hbound(a,1);\n begin;\n declare b(n) float, average float;\n declare i fixed binary;\n do i=1 to n;\n b(i)=a(i);\n end;\n average=sum(a)/n;\n put skip data(average);\n return( sqrt(sum(b**2)/n - average**2) );\n end;\n end std_dev;\n\n end;\n", "language": "PL-I" }, { "code": "function Get-StandardDeviation {\n begin {\n $avg = 0\n $nums = @()\n }\n process {\n $nums += $_\n $avg = ($nums | Measure-Object -Average).Average\n $sum = 0;\n $nums | ForEach-Object { $sum += ($avg - $_) * ($avg - $_) }\n [Math]::Sqrt($sum / $nums.Length)\n }\n}\n", "language": "PowerShell" }, { "code": ";Define our Standard deviation function\nDeclare.d Standard_deviation(x)\n\n; Main program\nIf OpenConsole()\n Define i, x\n Restore MyList\n For i=1 To 8\n Read.i x\n PrintN(StrD(Standard_deviation(x)))\n Next i\n Print(#CRLF$+\"Press ENTER to exit\"): Input()\nEndIf\n\n;Calculation procedure, with memory\nProcedure.d Standard_deviation(In)\n Static in_summa, antal\n Static in_kvadrater.q\n in_summa+in\n in_kvadrater+in*in\n antal+1\n ProcedureReturn Pow((in_kvadrater/antal)-Pow(in_summa/antal,2),0.50)\nEndProcedure\n\n;data section\nDataSection\nMyList:\n Data.i 2,4,4,4,5,5,7,9\nEndDataSection\n", "language": "PureBasic" }, { "code": ">>> from math import sqrt\n>>> def sd(x):\n sd.sum += x\n sd.sum2 += x*x\n sd.n += 1.0\n sum, sum2, n = sd.sum, sd.sum2, sd.n\n return sqrt(sum2/n - sum*sum/n/n)\n\n>>> sd.sum = sd.sum2 = sd.n = 0\n>>> for value in (2,4,4,4,5,5,7,9):\n print (value, sd(value))\n\n\n(2, 0.0)\n(4, 1.0)\n(4, 0.94280904158206258)\n(4, 0.8660254037844386)\n(5, 0.97979589711327075)\n(5, 1.0)\n(7, 1.3997084244475311)\n(9, 2.0)\n>>>\n", "language": "Python" }, { "code": ">>> class SD(object): # Plain () for python 3.x\n\tdef __init__(self):\n\t\tself.sum, self.sum2, self.n = (0,0,0)\n\tdef sd(self, x):\n\t\tself.sum += x\n\t\tself.sum2 += x*x\n\t\tself.n += 1.0\n\t\tsum, sum2, n = self.sum, self.sum2, self.n\n\t\treturn sqrt(sum2/n - sum*sum/n/n)\n\n>>> sd_inst = SD()\n>>> for value in (2,4,4,4,5,5,7,9):\n\tprint (value, sd_inst.sd(value))\n", "language": "Python" }, { "code": ">>> from math import sqrt\n>>> def sdcreator():\n\tsum = sum2 = n = 0\n\tdef sd(x):\n\t\tnonlocal sum, sum2, n\n\n\t\tsum += x\n\t\tsum2 += x*x\n\t\tn += 1.0\n\t\treturn sqrt(sum2/n - sum*sum/n/n)\n\treturn sd\n\n>>> sd = sdcreator()\n>>> for value in (2,4,4,4,5,5,7,9):\n\tprint (value, sd(value))\n\n\t\n2 0.0\n4 1.0\n4 0.942809041582\n4 0.866025403784\n5 0.979795897113\n5 1.0\n7 1.39970842445\n9 2.0\n", "language": "Python" }, { "code": ">>> from math import sqrt\n>>> def sdcreator():\n\tsum = sum2 = n = 0\n\twhile True:\n\t\tx = yield sqrt(sum2/n - sum*sum/n/n) if n else None\n\n\t\tsum += x\n\t\tsum2 += x*x\n\t\tn += 1.0\n\n>>> sd = sdcreator()\n>>> sd.send(None)\n>>> for value in (2,4,4,4,5,5,7,9):\n\tprint (value, sd.send(value))\n\n\t\n2 0.0\n4 1.0\n4 0.942809041582\n4 0.866025403784\n5 0.979795897113\n5 1.0\n7 1.39970842445\n9 2.0\n", "language": "Python" }, { "code": ">>> myMean = lambda MyList : reduce(lambda x, y: x + y, MyList) / float(len(MyList))\n>>> myStd = lambda MyList : (reduce(lambda x,y : x + y , map(lambda x: (x-myMean(MyList))**2 , MyList)) / float(len(MyList)))**.5\n\n>>> print myStd([2,4,4,4,5,5,7,9])\n2.0\n", "language": "Python" }, { "code": "cumsd <- function(x) {\n n <- seq_along(x)\n sqrt(cumsum(x^2) / n - (cumsum(x) / n)^2)\n}\n\nset.seed(12345L)\nx <- rnorm(10)\n\ncumsd(x)\n# [1] 0.0000000 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814\n\n# Compare to the naive implementation, i.e. compute sd on each sublist:\nVectorize(function(k) sd(x[1:k]) * sqrt((k - 1) / k))(seq_along(x))\n# [1] NA 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814\n# Note that the first is NA because sd is unbiased formula, hence there is a division by n-1, which is 0 for n=1.\n", "language": "R" }, { "code": "accumsd <- function() {\n n <- 0\n m <- 0\n s <- 0\n\n function(x) {\n n <<- n + 1\n m <<- m + x\n s <<- s + x * x\n sqrt(s / n - (m / n)^2)\n }\n}\n\nf <- accumsd()\nsapply(x, f)\n# [1] 0.0000000 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814\n", "language": "R" }, { "code": "#lang racket\n(require math)\n(define running-stddev\n (let ([ns '()])\n (λ(n) (set! ns (cons n ns)) (stddev ns))))\n;; run it on each number, return the last result\n(last (map running-stddev '(2 4 4 4 5 5 7 9)))\n", "language": "Racket" }, { "code": "sub sd (@a) {\n my $mean = @a R/ [+] @a;\n sqrt @a R/ [+] map (* - $mean)², @a;\n}\n\nsub sdaccum {\n my @a;\n return { push @a, $^x; sd @a; };\n}\n\nmy &f = sdaccum;\nsay f $_ for 2, 4, 4, 4, 5, 5, 7, 9;\n", "language": "Raku" }, { "code": "sub stddev($x) {\n sqrt\n ( .[2] += $x²) / ++.[0]\n - ((.[1] += $x ) / .[0])²\n given state @;\n}\n\nsay .&stddev for <2 4 4 4 5 5 7 9>;\n", "language": "Raku" }, { "code": "/*REXX program calculates and displays the standard deviation of a given set of numbers.*/\nparse arg # /*obtain optional arguments from the CL*/\nif #='' then #= 2 4 4 4 5 5 7 9 /*None specified? Then use the default*/\nn= words(#); $= 0; $$= 0; L= length(n) /*N: # items; $,$$: sums to be zeroed*/\n /* [↓] process each number in the list*/\n do j=1 for n\n _= word(#, j); $= $ + _\n $$= $$ + _**2\n say ' item' right(j, L)\":\" right(_, 4) ' average=' left($/j, 12),\n ' standard deviation=' sqrt($$/j - ($/j)**2)\n end /*j*/ /* [↑] prettify output with whitespace*/\nsay 'standard deviation: ' sqrt($$/n - ($/n)**2) /*calculate & display the std deviation*/\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h=d+6; m.=9; numeric form\n numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g * .5'e'_ % 2\n do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/\n do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/\n numeric digits d; return g/1\n", "language": "REXX" }, { "code": "/*REXX program calculates and displays the standard deviation of a given set of numbers.*/\nparse arg # /*obtain optional arguments from the CL*/\nif #='' then #= 2 4 4 4 5 5 7 9 /*None specified? Then use the default*/\nn= words(#); $= 0; $$= 0 /*N: # items; $,$$: sums to be zeroed*/\n /* [↓] process each number in the list*/\n do j=1 for n /*perform summation on two sets of #'s.*/\n _= word(#, j); $= $ + _\n $$= $$ + _**2\n end /*j*/\nsay 'standard deviation: ' sqrt($$/n - ($/n)**2) /*calculate&display the std, deviation.*/\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h=d+6; m.=9; numeric form\n numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g * .5'e'_ % 2\n do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/\n do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/\n numeric digits d; return g/1\n", "language": "REXX" }, { "code": "# Project : Cumulative standard deviation\n\ndecimals(6)\nsdsave = list(100)\nsd = \"2,4,4,4,5,5,7,9\"\nsumval = 0\nsumsqs = 0\n\nfor num = 1 to 8\n sd = substr(sd, \",\", \"\")\n stddata = number(sd[num])\n sumval = sumval + stddata\n sumsqs = sumsqs + pow(stddata,2)\n standdev = pow(((sumsqs / num) - pow((sumval /num),2)),0.5)\n sdsave[num] = string(num) + \" \" + string(sumval) +\" \" + string(sumsqs)\n see \"\" + num + \" value in = \" + stddata + \" Stand Dev = \" + standdev + nl\nnext\n", "language": "Ring" }, { "code": "class StdDevAccumulator\n def initialize\n @n, @sum, @sumofsquares = 0, 0.0, 0.0\n end\n\n def <<(num)\n # return self to make this possible: sd << 1 << 2 << 3 # => 0.816496580927726\n @n += 1\n @sum += num\n @sumofsquares += num**2\n self\n end\n\n def stddev\n Math.sqrt( (@sumofsquares / @n) - (@sum / @n)**2 )\n end\n\n def to_s\n stddev.to_s\n end\nend\n\nsd = StdDevAccumulator.new\ni = 0\n[2,4,4,4,5,5,7,9].each {|n| puts \"adding #{n}: stddev of #{i+=1} samples is #{sd << n}\" }\n", "language": "Ruby" }, { "code": "def sdaccum\n n, sum, sum2 = 0, 0.0, 0.0\n lambda do |num|\n n += 1\n sum += num\n sum2 += num**2\n Math.sqrt( (sum2 / n) - (sum / n)**2 )\n end\nend\n\nsd = sdaccum\n[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), \", \"}\n", "language": "Ruby" }, { "code": "dim sdSave$(100) 'can call up to 100 versions\n 'holds (space-separated) number of data , sum of values and sum of squares\nsd$ = \"2,4,4,4,5,5,7,9\"\n\nfor num = 1 to 8\n stdData = val(word$(sd$,num,\",\"))\n sumVal = sumVal + stdData\n sumSqs = sumSqs + stdData^2\n\n ' standard deviation = square root of (the average of the squares less the square of the average)\n standDev =((sumSqs / num) - (sumVal /num) ^ 2) ^ 0.5\n\n sdSave$(num) = str$(num);\" \";str$(sumVal);\" \";str$(sumSqs)\n print num;\" value in = \";stdData; \" Stand Dev = \"; using(\"###.######\", standDev)\n\nnext num\n", "language": "Run-BASIC" }, { "code": "pub struct CumulativeStandardDeviation {\n n: f64,\n sum: f64,\n sum_sq: f64\n}\n\nimpl CumulativeStandardDeviation {\n pub fn new() -> Self {\n CumulativeStandardDeviation {\n n: 0.,\n sum: 0.,\n sum_sq: 0.\n }\n }\n\n fn push(&mut self, x: f64) -> f64 {\n self.n += 1.;\n self.sum += x;\n self.sum_sq += x * x;\n\n (self.sum_sq / self.n - self.sum * self.sum / self.n / self.n).sqrt()\n }\n}\n\nfn main() {\n let nums = [2, 4, 4, 4, 5, 5, 7, 9];\n\n let mut cum_stdev = CumulativeStandardDeviation::new();\n for num in nums.iter() {\n println!(\"{}\", cum_stdev.push(*num as f64));\n }\n}\n", "language": "Rust" }, { "code": "fn sd_creator() -> impl FnMut(f64) -> f64 {\n let mut n = 0.0;\n let mut sum = 0.0;\n let mut sum_sq = 0.0;\n move |x| {\n sum += x;\n sum_sq += x*x;\n n += 1.0;\n (sum_sq / n - sum * sum / n / n).sqrt()\n }\n}\n\nfn main() {\n let nums = [2, 4, 4, 4, 5, 5, 7, 9];\n\n let mut sd_acc = sd_creator();\n for num in nums.iter() {\n println!(\"{}\", sd_acc(*num as f64));\n }\n}\n", "language": "Rust" }, { "code": "*--Load the test data;\ndata test1;\n input x @@;\n obs=_n_;\ndatalines;\n2 4 4 4 5 5 7 9\n;\nrun;\n\n*--Create a dataset with the cummulative data for each set of data for which the SD should be calculated;\ndata test2 (drop=i obs);\n set test1;\n y=x;\n do i=1 to n;\n set test1 (rename=(obs=setid)) nobs=n point=i;\n if obs<=setid then output;\n end;\nproc sort;\n by setid;\nrun;\n\n*--Calulate the standards deviation (and mean) using PROC MEANS;\nproc means data=test2 vardef=n noprint; *--use vardef=n option to calculate the population SD;\n by setid;\n var y;\n output out=stat1 n=n mean=mean std=sd;\nrun;\n\n*--Output the calculated standard deviations;\nproc print data=stat1 noobs;\n var n sd /*mean*/;\nrun;\n", "language": "SAS" }, { "code": "import scala.math.sqrt\n\nobject StddevCalc extends App {\n\n def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = {\n def avg(ts: Iterable[T])(implicit num: Fractional[T]): T =\n num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T\n\n val mean: T = avg(ts) // Leave val type of T\n // Root of mean diffs\n val stdDev = sqrt(ts.map { x =>\n val diff = num.toDouble(num.minus(x, mean))\n diff * diff\n }.sum / ts.size)\n\n (mean, stdDev)\n }\n\n println(calcAvgAndStddev(List(2.0E0, 4.0, 4, 4, 5, 5, 7, 9)))\n println(calcAvgAndStddev(Set(1.0, 2, 3, 4)))\n println(calcAvgAndStddev(0.1 to 1.1 by 0.05))\n println(calcAvgAndStddev(List(BigDecimal(120), BigDecimal(1200))))\n\n println(s\"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart}ms]\")\n\n}\n", "language": "Scala" }, { "code": "(define (standart-deviation-generator)\n (let ((nums '()))\n (lambda (x)\n (set! nums (cons x nums))\n (let* ((mean (/ (apply + nums) (length nums)))\n (mean-sqr (lambda (y) (expt (- y mean) 2)))\n (variance (/ (apply + (map mean-sqr nums)) (length nums))))\n (sqrt variance)))))\n\n(let loop ((f (standart-deviation-generator))\n (input '(2 4 4 4 5 5 7 9)))\n (unless (null? input)\n (display (f (car input)))\n (newline)\n (loop f (cdr input))))\n", "language": "Scheme" }, { "code": "T=[2,4,4,4,5,5,7,9];\nstdev(T)*sqrt((length(T)-1)/length(T))\n", "language": "Scilab" }, { "code": "class StdDevAccumulator(n=0, sum=0, sumofsquares=0) {\n method <<(num) {\n n += 1\n sum += num\n sumofsquares += num**2\n self\n }\n \n method stddev {\n sqrt(sumofsquares/n - pow(sum/n, 2))\n }\n \n method to_s {\n self.stddev.to_s\n }\n}\n \nvar i = 0\nvar sd = StdDevAccumulator()\n[2,4,4,4,5,5,7,9].each {|n|\n say \"adding #{n}: stddev of #{i+=1} samples is #{sd << n}\"\n}\n", "language": "Sidef" }, { "code": "func stddev(x) {\n static(num=0, sum=0, sum2=0)\n num++\n sqrt(\n (sum2 += x**2) / num -\n (((sum += x) / num)**2)\n )\n}\n \n%n(2 4 4 4 5 5 7 9).each { say stddev(_) }\n", "language": "Sidef" }, { "code": "Object subclass: SDAccum [\n |sum sum2 num|\n SDAccum class >> new [ |o|\n o := super basicNew.\n ^ o init.\n ]\n init [ sum := 0. sum2 := 0. num := 0 ]\n value: aValue [\n sum := sum + aValue.\n sum2 := sum2 + ( aValue * aValue ).\n num := num + 1.\n ^ self stddev\n ]\n count [ ^ num ]\n mean [ num>0 ifTrue: [^ sum / num] ifFalse: [ ^ 0.0 ] ]\n variance [ |m| m := self mean.\n num>0 ifTrue: [^ (sum2/num) - (m*m) ] ifFalse: [ ^ 0.0 ]\n ]\n stddev [ ^ (self variance) sqrt ]\n].\n", "language": "Smalltalk" }, { "code": "|sdacc sd|\nsdacc := SDAccum new.\n\n#( 2 4 4 4 5 5 7 9 ) do: [ :v | sd := sdacc value: v ].\n('std dev = %1' % { sd }) displayNl.\n", "language": "Smalltalk" }, { "code": "-- the minimal table\ncreate table if not exists teststd (n double precision not null);\n\n-- code modularity with view, we could have used a common table expression instead\ncreate view vteststd as\n select count(n) as cnt,\n sum(n) as tsum,\n sum(power(n,2)) as tsqr\nfrom teststd;\n\n-- you can of course put this code into every query\ncreate or replace function std_dev() returns double precision as $$\n select sqrt(tsqr/cnt - (tsum/cnt)^2) from vteststd;\n$$ language sql;\n\n-- test data is: 2,4,4,4,5,5,7,9\ninsert into teststd values (2);\nselect std_dev() as std_deviation;\ninsert into teststd values (4);\nselect std_dev() as std_deviation;\ninsert into teststd values (4);\nselect std_dev() as std_deviation;\ninsert into teststd values (4);\nselect std_dev() as std_deviation;\ninsert into teststd values (5);\nselect std_dev() as std_deviation;\ninsert into teststd values (5);\nselect std_dev() as std_deviation;\ninsert into teststd values (7);\nselect std_dev() as std_deviation;\ninsert into teststd values (9);\nselect std_dev() as std_deviation;\n-- cleanup test data\ndelete from teststd;\n", "language": "SQL" }, { "code": "import Darwin\nclass stdDev{\n\n var n:Double = 0.0\n var sum:Double = 0.0\n var sum2:Double = 0.0\n\n init(){\n\n let testData:[Double] = [2,4,4,4,5,5,7,9];\n for x in testData{\n\n var a:Double = calcSd(x)\n println(\"value \\(Int(x)) SD = \\(a)\");\n }\n\n }\n\n func calcSd(x:Double)->Double{\n\n n += 1\n sum += x\n sum2 += x*x\n return sqrt( sum2 / n - sum*sum / n / n)\n }\n\n}\nvar aa = stdDev()\n", "language": "Swift" }, { "code": "func standardDeviation(arr : [Double]) -> Double\n{\n let length = Double(arr.count)\n let avg = arr.reduce(0, { $0 + $1 }) / length\n let sumOfSquaredAvgDiff = arr.map { pow($0 - avg, 2.0)}.reduce(0, {$0 + $1})\n return sqrt(sumOfSquaredAvgDiff / length)\n}\n\nlet responseTimes = [ 18.0, 21.0, 41.0, 42.0, 48.0, 50.0, 55.0, 90.0 ]\n\nstandardDeviation(responseTimes) // 20.8742514835862\nstandardDeviation([2,4,4,4,5,5,7,9]) // 2.0\n", "language": "Swift" }, { "code": "oo::class create SDAccum {\n variable sum sum2 num\n constructor {} {\n set sum 0.0\n set sum2 0.0\n set num 0\n }\n method value {x} {\n set sum2 [expr {$sum2 + $x**2}]\n set sum [expr {$sum + $x}]\n incr num\n return [my stddev]\n }\n method count {} {\n return $num\n }\n method mean {} {\n expr {$sum / $num}\n }\n method variance {} {\n expr {$sum2/$num - [my mean]**2}\n }\n method stddev {} {\n expr {sqrt([my variance])}\n }\n}\n\n# Demonstration\nset sdacc [SDAccum new]\nforeach val {2 4 4 4 5 5 7 9} {\n set sd [$sdacc value $val]\n}\nputs \"the standard deviation is: $sd\"\n", "language": "Tcl" }, { "code": "# Make a coroutine out of a lambda application\ncoroutine sd apply {{} {\n set sum 0.0\n set sum2 0.0\n set sd {}\n # Keep processing argument values until told not to...\n while {[set val [yield $sd]] ne \"stop\"} {\n incr n\n set sum [expr {$sum + $val}]\n set sum2 [expr {$sum2 + $val**2}]\n set sd [expr {sqrt($sum2/$n - ($sum/$n)**2)}]\n }\n}}\n\n# Demonstration\nforeach val {2 4 4 4 5 5 7 9} {\n set sd [sd $val]\n}\nsd stop\nputs \"the standard deviation is: $sd\"\n", "language": "Tcl" }, { "code": "data = Array(2,4,4,4,5,5,7,9)\n\nFor i = 0 To UBound(data)\n\tWScript.StdOut.Write \"value = \" & data(i) &_\n\t\t\" running sd = \" & sd(data,i)\n\tWScript.StdOut.WriteLine\nNext\n\nFunction sd(arr,n)\n\tmean = 0\n\tvariance = 0\n\tFor j = 0 To n\n\t\tmean = mean + arr(j)\n\tNext\n\tmean = mean/(n+1)\n\tFor k = 0 To n\n\t\tvariance = variance + ((arr(k)-mean)^2)\n\tNext\n\tvariance = variance/(n+1)\n\tsd = FormatNumber(Sqr(variance),6)\nEnd Function\n", "language": "VBScript" }, { "code": "Function avg(what() As Variant) As Variant\n 'treats non-numeric strings as zero\n Dim L0 As Variant, total As Variant\n For L0 = LBound(what) To UBound(what)\n If IsNumeric(what(L0)) Then total = total + what(L0)\n Next\n avg = total / (1 + UBound(what) - LBound(what))\nEnd Function\n\nFunction standardDeviation(fp As Variant) As Variant\n Static list() As Variant\n Dim av As Variant, tmp As Variant, L0 As Variant\n\n 'add to sequence if numeric\n If IsNumeric(fp) Then\n On Error GoTo makeArr 'catch undimensioned list\n ReDim Preserve list(UBound(list) + 1)\n On Error GoTo 0\n list(UBound(list)) = fp\n End If\n\n 'get average\n av = avg(list())\n\n 'the actual work\n For L0 = 0 To UBound(list)\n tmp = tmp + ((list(L0) - av) ^ 2)\n Next\n tmp = Sqr(tmp / (UBound(list) + 1))\n\n standardDeviation = tmp\n\n Exit Function\nmakeArr:\n If 9 = Err.Number Then\n ReDim list(0)\n Else\n 'something's wrong\n Err.Raise Err.Number\n End If\n Resume Next\nEnd Function\n\nSub tester()\n Dim x As Variant\n x = Array(2, 4, 4, 4, 5, 5, 7, 9)\n For L0 = 0 To UBound(x)\n Debug.Print standardDeviation(x(L0))\n Next\nEnd Sub\n", "language": "Visual-Basic" }, { "code": "import \"./fmt\" for Fmt\nimport \"./math\" for Nums\n\nvar cumStdDev = Fiber.new { |a|\n for (i in 0...a.count) {\n var b = a[0..i]\n System.print(\"Values : %(b)\")\n Fiber.yield(Nums.popStdDev(b))\n }\n}\n\nvar a = [2, 4, 4, 4, 5, 5, 7, 9]\nwhile (true) {\n var sd = cumStdDev.call(a)\n if (cumStdDev.isDone) return\n Fmt.print(\"Std Dev : $10.8f\\n\", sd)\n}\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes; \\intrinsic 'code' declarations\nint A, I;\nreal N, S, S2;\n[A:= [2,4,4,4,5,5,7,9];\nN:= 0.0; S:= 0.0; S2:= 0.0;\nfor I:= 0 to 8-1 do\n [N:= N + 1.0;\n S:= S + float(A(I));\n S2:= S2 + float(sq(A(I)));\n RlOut(0, sqrt((S2/N) - sq(S/N)));\n ];\nCrLf(0);\n]\n", "language": "XPL0" }, { "code": "fcn sdf{ fcn(x,xs){\n m:=xs.append(x.toFloat()).sum(0.0)/xs.len();\n (xs.reduce('wrap(p,x){(x-m)*(x-m) +p},0.0)/xs.len()).sqrt()\n }.fp1(L())\n}\n", "language": "Zkl" } ]
Cumulative-standard-deviation
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Currency\n", "language": "00-META" }, { "code": ";Task:\nShow how to represent currency in a simple example, using a data type that represent exact values of dollars and cents. \n\n\n;Note:\nThe '''IEEE 754''' binary floating point representations of numbers like &nbsp; '''2.86''' &nbsp; and &nbsp; '''.0765''' &nbsp; are not exact.\n\nFor this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate. \n \nUse the values:\n::* 4000000000000000 hamburgers at $5.50 each &nbsp; &nbsp; &nbsp; (four quadrillion burgers)\n::* 2 milkshakes at $2.86 each, and \n::* a tax rate of 7.65%. \n\n<br>\n(That number of hamburgers is a 4 with 15 zeros after it. &nbsp; The number is contrived to exclude naïve task solutions using 64 bit floating point types.) \n\nCompute and output (show results on this page):\n::* the total price before tax\n::* the tax\n::* the total with tax \n\n<br>\nThe tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax. \n\nThe output must show dollars and cents with a decimal point. \n \nThe three results displayed should be:\n::* 22000000000000005.72\n::* 1683000000000000.44 \n::* 23683000000000006.16 \n\n<br>\nDollar signs and thousands separators are optional.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F currency(units, subunits)\n R BigInt(units) * 100 + subunits\n\nF currency_from_str(s)\n V (units, subunits) = s.split(‘.’)\n R BigInt(units) * 100 + Int(subunits)\n\nF percentage(a, num, denom)\n R (a * num * 10 I/ denom + 5) I/ 10\n\nF to_str(c)\n R String(c I/ 100)‘’‘.#02’.format(c % 100)\n\nV hamburgers = currency(5, 50) * 4'000'000'000'000'000\nV milkshakes = currency_from_str(‘2.86’) * 2\nV beforeTax = hamburgers + milkshakes\nV tax = percentage(beforeTax, 765, 10'000)\nV total = beforeTax + tax\n\nV maxlen = max(to_str(beforeTax).len, to_str(tax).len, to_str(total).len)\n\nprint(‘Total price before tax: ’to_str(beforeTax).rjust(maxlen))\nprint(‘Tax: ’to_str(tax).rjust(maxlen))\nprint(‘Total with tax: ’to_str(total).rjust(maxlen))\n", "language": "11l" }, { "code": "with Ada.Text_IO;\n\nprocedure Currency is\n type Dollar is delta 0.01 range 0.0 .. 24_000_000_000_000_000.0;\n package Dollar_IO is new Ada.Text_IO.Fixed_IO(Dollar);\n\n hamburger_cost : constant := 5.50;\n milkshake_cost : constant := 2.86;\n tax_rate : constant := 0.0765;\n\n total_cost : constant := hamburger_cost * 4_000_000_000_000_000.0 + milkshake_cost * 2;\n total_tax : constant := total_cost * tax_rate;\n total_with_tax : constant := total_cost + total_tax;\nbegin\n Ada.Text_IO.Put(\"Price before tax:\");\n Dollar_IO.Put(total_cost);\n Ada.Text_IO.New_Line;\n\n Ada.Text_IO.Put(\"Tax: \");\n Dollar_IO.Put(total_tax);\n Ada.Text_IO.New_Line;\n\n Ada.Text_IO.Put(\"Total: \");\n Dollar_IO.Put(total_with_tax);\n Ada.Text_IO.New_Line;\nend Currency;\n", "language": "Ada" }, { "code": "BEGIN\n # currency calculations #\n # simple fixed point type, LONG INT is 64-bit in Algol 68G #\n MODE FIXED = STRUCT( LONG INT value\n , INT decimals\n , INT fraction modulus\n );\n # make CURRENCY a synonym for FIXED #\n MODE CURRENCY = FIXED;\n # dyadic operator so we can write e.g. 5 DOLLARS 50 to construct #\n # a CURRENCY value with 2 decimal places #\n PRIO DOLLARS = 9;\n OP DOLLARS = ( LONG INT v, INT dp )CURRENCY: ( ( v * 100 ) + dp, 2, 100 );\n OP DOLLARS = ( INT v, INT dp )CURRENCY: LENG v DOLLARS dp;\n # issues an error message and stops the program if a has a different #\n # number of decimal places to b #\n PROC check compatible = ( CURRENCY a, b )VOID:\n IF decimals OF a /= decimals OF b THEN print( ( \"Incompatible CURRENCY values\", newline ) ); stop FI;\n # operators to multiply CURRENCY values by integers #\n OP * = ( CURRENCY v, LONG INT m )CURRENCY: ( value OF v * m, decimals OF v, fraction modulus OF v );\n OP * = ( CURRENCY v, INT m )CURRENCY: v * LENG m;\n # returns the CURRENCY value a + b #\n OP + = ( CURRENCY a, CURRENCY b )CURRENCY:\n BEGIN\n check compatible( a, b );\n ( value OF a + value OF b, decimals OF a, fraction modulus OF a )\n END # + # ;\n # multiplies the CURRENCY value a by the FIXED value b, #\n # rounding the result to the decimal places of a #\n OP * = ( CURRENCY a, FIXED b )CURRENCY:\n BEGIN\n LONG INT result := ( value OF a * value OF b );\n IF decimals OF b > 0 THEN\n INT d = fraction modulus OF b;\n LONG INT abs result := ABS result;\n INT extra places = SHORTEN ( abs result MOD d );\n abs result OVERAB d;\n IF extra places >= d OVER 2 THEN abs result +:= 1 FI;\n IF result < 0 THEN result := - abs result ELSE result := abs result FI\n FI;\n ( result, decimals OF a, fraction modulus OF a )\n END # * # ;\n # converts a FIXED value to a STRING with the appropriate number of #\n # decimal places #\n OP TOSTRING = ( FIXED v )STRING:\n IF decimals OF v < 1 THEN\n whole( value OF v, 0 )\n ELSE\n INT d = fraction modulus OF v;\n STRING result := whole( value OF v OVER d, 0 );\n STRING dp := whole( ( ABS value OF v ) MOD d, - decimals OF v );\n FOR i FROM LWB dp TO UPB dp DO IF dp[ i ] = \" \" THEN dp[ i ] := \"0\" FI OD;\n result + \".\" + dp\n FI # TOSTRING # ;\n # Task calculations #\n CURRENCY hb = 5 DOLLARS 50 * LONG 4000000000000000;\n CURRENCY ms = 2 DOLLARS 86 * 2;\n FIXED rate = ( 765, 4, 10 000 ); # 0.0765 #\n CURRENCY net = hb + ms;\n CURRENCY tax = net * rate;\n CURRENCY total = net + tax;\n print( ( \"before tax: \", TOSTRING net, newline ) );\n print( ( \"tax: \", TOSTRING tax, newline ) );\n print( ( \"total: \", TOSTRING total, newline ) )\nEND\n", "language": "ALGOL-68" }, { "code": "use AppleScript version \"2.4\" -- OS X 10.10 (Yosemite) or later\nuse framework \"Foundation\"\n\n-- Derive an NSDecimalNumber from an AppleScript number or numeric text.\n-- NSDecimalNumbers also allow arithmetic and have a far greater range than AS numbers.\non decimalNumberFrom(n)\n return current application's class \"NSDecimalNumber\"'s decimalNumberWithString:(n as text)\nend decimalNumberFrom\n\n-- Multiply two NSDecimalNumbers.\non multiply(dn1, dn2)\n return dn1's decimalNumberByMultiplyingBy:(dn2)\nend multiply\n\n-- Add two NSDecimalNumbers.\non add(dn1, dn2)\n return dn1's decimalNumberByAdding:(dn2)\nend add\n\non billTotal(quantitiesAndPrices, taxRate, currencySymbol)\n -- Set up an NSNumberFormatter for converting between currency strings and NSDecimalNumbers.\n set currencyFormatter to current application's class \"NSNumberFormatter\"'s new()\n tell currencyFormatter to setNumberStyle:(current application's NSNumberFormatterCurrencyStyle)\n tell currencyFormatter to setCurrencySymbol:(currencySymbol)\n tell currencyFormatter to setGeneratesDecimalNumbers:(true)\n\n -- Tot up the bill from the list of quantities (numbers or numeric strings) and unit prices (currency strings with symbols).\n set subtotal to decimalNumberFrom(0) -- or: current application's class \"NSDecimalNumber\"'s zero()\n repeat with thisEntry in quantitiesAndPrices\n set {quantity:quantity, unitPrice:unitPrice} to thisEntry\n set entryTotal to multiply(decimalNumberFrom(quantity), currencyFormatter's numberFromString:(unitPrice))\n set subtotal to add(subtotal, entryTotal)\n end repeat\n -- Work out the tax and add it to the subtotal.\n set tax to multiply(subtotal, decimalNumberFrom(taxRate / 100))\n set total to add(subtotal, tax)\n\n -- Format and return the results.\n return (current application's class \"NSString\"'s stringWithFormat_(\"Subtotal: %@\nTax: %@\nTotal: %@\", ¬\n currencyFormatter's stringFromNumber:(subtotal), ¬\n currencyFormatter's stringFromNumber:(tax), ¬\n currencyFormatter's stringFromNumber:(total))) ¬\n as text\nend billTotal\n\n-- Demo code:\nset currencySymbol to \"$\"\nset quantitiesAndPrices to {{quantity:\"4000000000000000\", unitPrice:currencySymbol & \"5.50\"}, ¬\n {quantity:2, unitPrice:currencySymbol & 2.86}}\nset taxRate to 7.65\nreturn billTotal(quantitiesAndPrices, taxRate, currencySymbol)\n", "language": "AppleScript" }, { "code": "\"Subtotal: $22,000,000,000,000,005.72\nTax: $1,683,000,000,000,000.44\nTotal: $23,683,000,000,000,006.16\"\n", "language": "AppleScript" }, { "code": "# syntax: GAWK -M -f CURRENCY.AWK\n# using GNU Awk 4.1.1, API: 1.1 (GNU MPFR 3.1.2, GNU MP 5.1.2)\nBEGIN {\n PREC = 100\n hamburger_p = 5.50\n hamburger_q = 4000000000000000\n hamburger_v = hamburger_p * hamburger_q\n milkshake_p = 2.86\n milkshake_q = 2\n milkshake_v = milkshake_p * milkshake_q\n subtotal = hamburger_v + milkshake_v\n tax = subtotal * .0765\n printf(\"%-9s %8s %18s %22s\\n\",\"item\",\"price\",\"quantity\",\"value\")\n printf(\"hamburger %8.2f %18d %22.2f\\n\",hamburger_p,hamburger_q,hamburger_v)\n printf(\"milkshake %8.2f %18d %22.2f\\n\\n\",milkshake_p,milkshake_q,milkshake_v)\n printf(\"%37s %22.2f\\n\",\"subtotal\",subtotal)\n printf(\"%37s %22.2f\\n\",\"tax\",tax)\n printf(\"%37s %22.2f\\n\",\"total\",subtotal+tax)\n exit(0)\n}\n", "language": "AWK" }, { "code": "# syntax: GAWK -M -f CURRENCY2.AWK\n# using GNU Awk 4.1.1, API: 1.1 (GNU MPFR 3.1.2, GNU MP 5.1.2)\n# INT is used to define values and do math; results then converted to FLOAT\nBEGIN {\n PREC = 100\n hamburger_p = 550\n hamburger_q = 4000000000000000\n hamburger_v = hamburger_p * hamburger_q\n milkshake_p = 286\n milkshake_q = 2\n milkshake_v = milkshake_p * milkshake_q\n subtotal = hamburger_v + milkshake_v\n tax = subtotal * 765\n subtotal /= 100\n tax /= 1000000\n printf(\"%-9s %8s %18s %22s\\n\",\"item\",\"price\",\"quantity\",\"value\")\n printf(\"hamburger %8.2f %18d %22.2f\\n\",hamburger_p/100,hamburger_q,hamburger_v/100)\n printf(\"milkshake %8.2f %18d %22.2f\\n\\n\",milkshake_p/100,milkshake_q,milkshake_v/100)\n printf(\"%37s %22.2f\\n\",\"subtotal\",subtotal)\n printf(\"%37s %22.2f\\n\",\"tax\",tax)\n printf(\"%37s %22.2f\\n\",\"total\",subtotal+tax)\n exit(0)\n}\n", "language": "AWK" }, { "code": " REM No need for BigNum library.\n REM This language uses 80bit (10 bytes!) for real values internally.\n Price = 4E15 * 5.50 + 2.0 * 2.86\n Tax = Price * .0765\n Total = Price + Tax\n\n REM Number printing will use 2 decimal places and 21 positions zone\n @%=&020215\n PRINT \"Price = $\" Price\n PRINT \"Tax = $\" Tax\n PRINT \"Total = $\" Total\n", "language": "BBC-BASIC" }, { "code": " div$((4000000000000000*550+2*286)+1/2,1):?before-tax\n& div$(!before-tax*765/10000+1/2,1):?tax\n& !before-tax+!tax:?after-tax\n& ( fix\n = cents dollars\n . mod$(!arg.100):?cents\n & ( !cents:<10&0 !cents:?cents\n |\n )\n & div$(!arg.100):?dollars\n & str$(!dollars \".\" !cents)\n )\n& str\n $ ( \"before-tax \"\n fix$!before-tax\n \"\\ntax \"\n fix$!tax\n \\n\n \"after-tax \"\n fix$!after-tax\n \\n\n )\n", "language": "Bracmat" }, { "code": "\tmpf_set_d(burgerUnitPrice,5.50);\n\tmpf_set_d(milkshakePrice,2 * 2.86);\n\tmpf_set_d(burgerNum,4000000000000000);\n\tmpf_set_d(milkshakeNum,2);\n", "language": "C" }, { "code": "\tmpf_set_str(tax,\"0.0765\",10);\n", "language": "C" }, { "code": "#include<stdio.h>\n#include<gmp.h>\n\nint main()\n{\n\tmpf_t burgerUnitPrice, milkshakePrice, burgerTotalPrice, totalPrice, tax, burgerNum, milkshakeNum;\n\t\n\tmpf_inits(burgerUnitPrice, milkshakePrice, burgerTotalPrice, totalPrice, tax,burgerNum, milkshakeNum,NULL);\n\t\n\tmpf_set_d(burgerUnitPrice,5.50);\n\tmpf_set_d(milkshakePrice,2 * 2.86);\n\tmpf_set_d(burgerNum,4000000000000000);\n\tmpf_set_d(milkshakeNum,2);\n\t\n\tmpf_mul(burgerTotalPrice,burgerNum,burgerUnitPrice);\n\tmpf_add(totalPrice,burgerTotalPrice,milkshakePrice);\n\t\n\tmpf_set_str(tax,\"0.0765\",10);\n\tmpf_mul(tax,totalPrice,tax);\n\t\n\tgmp_printf(\"\\nTotal price before tax : $ %.*Ff\", 2, totalPrice);\n\tgmp_printf(\"\\nTotal tax : $ %.*Ff\", 2, tax);\n\t\n\tmpf_add(totalPrice,totalPrice,tax);\n\t\n\tgmp_printf(\"\\nTotal price after tax : $ %.*Ff\", 2, totalPrice);\n\t\n\treturn 0;\n}\n", "language": "C" }, { "code": "using System;\nusing System.Collections.Generic;\n\nnamespace Currency\n{\n class Program\n {\n static void Main(string[] args)\n {\n MenuItem hamburger = new MenuItem() { Name = \"Hamburger\", Price = 5.5M };\n MenuItem milkshake = new MenuItem() { Name = \"Milkshake\", Price = 2.86M };\n\n IList<CartItem> cart = new List<CartItem>();\n cart.Add(new CartItem() { item = hamburger, quantity = 4000000000000000 });\n cart.Add(new CartItem() { item = milkshake, quantity = 2 });\n\n decimal total = CalculateTotal(cart);\n\n Console.WriteLine(string.Format(\"Total before tax: {0:C}\", total));\n\n // Add Tax\n decimal tax = total * 0.0765M;\n\n Console.WriteLine(string.Format(\"Tax: {0:C}\", tax));\n\n total += tax;\n\n Console.WriteLine(string.Format(\"Total with tax: {0:C}\", total));\n }\n\n private static decimal CalculateTotal(IList<CartItem> cart)\n {\n decimal total = 0M;\n\n foreach (CartItem item in cart)\n {\n total += item.quantity * item.item.Price;\n }\n\n return total;\n }\n\n private struct MenuItem\n {\n public string Name { get; set; }\n public decimal Price { get; set; }\n }\n\n private struct CartItem\n {\n public MenuItem item { get; set; }\n public decimal quantity { get; set; }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(require '[clojurewerkz.money.amounts :as ma])\n(require '[clojurewerkz.money.currencies :as mc])\n(require '[clojurewerkz.money.format :as mf])\n\n(let [burgers (ma/multiply (ma/amount-of mc/USD 5.50) 4000000000000000)\n milkshakes (ma/multiply (ma/amount-of mc/USD 2.86) 2)\n pre-tax (ma/plus burgers milkshakes)\n tax (ma/multiply pre-tax 0.0765 :up)]\n (println \"Total before tax: \" (mf/format pre-tax))\n (println \" Tax: \" (mf/format tax))\n (println \" Total with tax: \" (mf/format (ma/plus pre-tax tax))))\n", "language": "Clojure" }, { "code": "(require '[io.randomseed.bankster.money :as m])\n\n(let [burgers (m/mul #money[USD 5.50] 4000000000000000)\n milkshakes (m/mul #money[USD 2.86] 2)\n pre-tax (m/add burgers milkshakes)\n tax (m/with-rounding UP (m/mul pre-tax 0.0765))]\n (println \"Total before tax: \" (m/format pre-tax))\n (println \" Tax: \" (m/format tax))\n (println \" Total with tax: \" (m/format (m/add pre-tax tax))))\n", "language": "Clojure" }, { "code": " >>SOURCE FREE\nIDENTIFICATION DIVISION.\nPROGRAM-ID. currency-example.\n\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01 Burger-Price CONSTANT 5.50.\n01 Milkshake-Price CONSTANT 2.86.\n01 num-burgers PIC 9(18) VALUE 4000000000000000.\n01 num-milkshakes PIC 9(18) VALUE 2.\n01 tax PIC 9(18)V99.\n01 tax-edited PIC $(17)9.99.\n01 Tax-Rate CONSTANT 7.65.\n01 total PIC 9(18)V99.\n01 total-edited PIC $(17)9.99.\n\nPROCEDURE DIVISION.\n COMPUTE total rounded, total-edited rounded =\n num-burgers * Burger-Price + num-milkshakes * Milkshake-Price\n DISPLAY \"Total before tax: \" total-edited\n\n COMPUTE tax rounded, tax-edited rounded = total * (Tax-Rate / 100)\n DISPLAY \" Tax: \" tax-edited\n\n ADD tax TO total GIVING total-edited rounded\n DISPLAY \" Total with tax: \" total-edited\n .\nEND PROGRAM currency-example.\n", "language": "COBOL" }, { "code": "(defun print-$ (rat &key (prefix \"\") (stream t))\n (multiple-value-bind (dollars cents) (truncate rat)\n (format stream \"~A~D.~D~%\" prefix dollars (round (* 100 cents)))))\n\n(defun compute-check (order-alist tax-rate)\n (let* ((total-before-tax\n (loop :for (amount . price) in order-alist\n :sum (* (rationalize price) amount)))\n (tax (* (rationalize tax-rate) total-before-tax)))\n (print-$ total-before-tax :prefix \"Total before tax: \")\n (print-$ tax :prefix \"Tax: \")\n (print-$ (+ total-before-tax tax) :prefix \"Total with tax: \")))\n\n(compute-check '((4000000000000000 . 5.5) (2 . 2.86)) 0.0765)\n", "language": "Common-Lisp" }, { "code": "(defun read-$ (stream char)\n (declare (ignore char))\n (let* ((str (with-output-to-string (out)\n ;; TODO: read integer, if dot, read dot and another integer\n (loop :for next = (peek-char nil stream t nil t)\n :while (or (digit-char-p next) (char= next #\\.))\n :do (write-char (read-char stream t nil t) out))))\n (dot-pos (position #\\. str))\n (dollars (parse-integer str :end dot-pos))\n (cents (if dot-pos\n (/ (parse-integer str :start (+ dot-pos 1))\n (expt 10 (- (length str) (+ dot-pos 1))))\n 0)))\n (+ dollars cents)))\n(set-macro-character #\\$ #'read-$ t)\n\n(defun print-$ (rat &key (prefix \"\") (stream t))\n (multiple-value-bind (dollars cents) (truncate rat)\n (format stream \"~A~D.~D~%\" prefix dollars (round (* 100 cents)))))\n\n(defun compute-check (order-alist tax-rate)\n (let* ((total-before-tax\n (loop :for (amount . price) in order-alist\n :sum (* price amount)))\n (tax (* (rationalize tax-rate) total-before-tax)))\n (print-$ total-before-tax :prefix \"Total before tax: \")\n (print-$ tax :prefix \"Tax: \")\n (print-$ (+ total-before-tax tax) :prefix \"Total with tax: \")))\n\n(compute-check '((4000000000000000 . $5.5) (2 . $2.86)) 0.0765)\n", "language": "Common-Lisp" }, { "code": "program Currency;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils,\n Velthuis.BigRationals,\n Velthuis.BigDecimals,\n Velthuis.BigIntegers;\n\nvar\n one: BigInteger;\n hundred: BigInteger;\n half: BigRational;\n\ntype\n TDc = record\n value: BigInteger;\n function ToString: string;\n function Extend(n: BigInteger): TDc;\n class operator Add(a, b: TDc): TDc;\n end;\n\n TTR = record\n value: BigRational;\n function SetString(const s: string; var TR: TTR): boolean;\n function Tax(dc: TDc): TDc;\n end;\n\n{ TDc }\n\n// Extend returns extended price of a unit price.\nclass operator TDc.Add(a, b: TDc): TDc;\nbegin\n Result.value := a.value + b.value;\nend;\n\nfunction TDc.Extend(n: BigInteger): TDc;\nbegin\n Result.value := n * value;\nend;\n\nfunction TDc.ToString: string;\nvar\n d: BigInteger;\nbegin\n d := value.Divide(value, 100);\n if value < 0 then\n value := -value;\n Result := Format('%s.%2s', [d.ToString, (value mod 100).ToString]);\nend;\n\n// ParseDC parses dollars and cents as a string into a DC.\nfunction ParseDC(s: string; var Dc: TDc): Boolean;\nvar\n r: BigRational;\n d: BigDecimal;\nbegin\n Result := d.TryParse(s, d);\n if not Result then\n begin\n Dc.value := 0;\n exit(false);\n end;\n\n r := r.Create(d);\n r := r.Multiply(r, 100);\n if BigInteger.Compare(r.Denominator, 1) <> 0 then\n begin\n Dc.value := 0;\n exit(false);\n end;\n Result := true;\n Dc.value := r.Numerator;\nend;\n\n{ TTR }\n\nfunction TTR.SetString(const s: string; var TR: TTR): boolean;\nvar\n d: BigDecimal;\nbegin\n\n Result := d.TryParse(s, d);\n if Result then\n TR.value := BigRational.Create(d);\nend;\n\nfunction TTR.Tax(dc: TDc): TDc;\nvar\n r: BigRational;\n i: BigInteger;\nbegin\n r := BigRational.Create(dc.value, 1);\n r := r.Multiply(r, self.value);\n r := r.add(r, half);\n i := i.Divide(r.Numerator, r.Denominator);\n Result.value := i;\nend;\n\nvar\n hamburgerPrice, milkshakePrice, totalBeforeTax, tax, total: TDc;\n taxRate: TTR;\n\nbegin\n one := 1;\n hundred := 100;\n half := BigRational.Create(1, 2);\n\n if not ParseDC('5.50', hamburgerPrice) then\n begin\n Writeln('Invalid hamburger price');\n halt(1);\n end;\n\n if not ParseDC('2.86', milkshakePrice) then\n begin\n Writeln('Invalid milkshake price');\n halt(2);\n end;\n\n if not taxRate.SetString('0.0765', taxRate) then\n begin\n Writeln('Invalid tax rat');\n halt(3);\n end;\n\n totalBeforeTax := hamburgerPrice.Extend(4000000000000000) + milkshakePrice.Extend(2);\n tax := taxRate.Tax(totalBeforeTax);\n total := totalBeforeTax + tax;\n Writeln('Total before tax: ', totalBeforeTax.ToString: 22);\n Writeln(' Tax: ', tax.ToString: 22);\n Writeln(' Total: ', total.ToString: 22);\n readln;\nend.\n", "language": "Delphi" }, { "code": "open System\n\nlet hamburgers = 4000000000000000M\nlet hamburgerPrice = 5.50M\nlet milkshakes = 2M\nlet milkshakePrice = 2.86M\nlet taxRate = 0.0765M\n\nlet total = hamburgers * hamburgerPrice + milkshakes * milkshakePrice\nlet tax = total * taxRate\nlet totalWithTax = total + tax\n\nprintfn \"Total before tax:\\t$%M\" <| Math.Round (total, 2)\nprintfn \" Tax:\\t$%M\" <| Math.Round (tax, 2)\nprintfn \" Total:\\t$%M\" <| Math.Round (totalWithTax, 2)\n", "language": "F-Sharp" }, { "code": "USING: combinators.smart io kernel math math.functions money ;\n\n10 15 ^ 4 * 5+50/100 * ! hamburger subtotal\n2 2+86/100 * ! milkshake subtotal\n+ ! subtotal\ndup DECIMAL: 0.0765 * ! tax\n[ + ] preserving ! total\n\n\"Total before tax: \" write [ money. ] 2dip\n\"Tax: \" write [ money. ] dip\n\"Total with tax: \" write money.\n", "language": "Factor" }, { "code": "Dim As Longint hamburger_p = 550\nDim As Longint hamburger_q = 4000000000000000\nDim As Longint hamburger_v = hamburger_p * hamburger_q\nDim As Longint milkshake_p = 286\nDim As Longint milkshake_q = 2\nDim As Longint milkshake_v = milkshake_p * milkshake_q\nDim As Longint subtotal = hamburger_v + milkshake_v\nDim As Longint tax = subtotal * .765\nPrint Using \"\\ \\ \\ \\ \\ \\ \\ \\\";\"item\";\"price\";\"quantity\";\"value\"\nPrint Using \"hamburger ##.## ################ #####################.##\";hamburger_p/100;hamburger_q;hamburger_v/100\nPrint Using \"milkshake ##.## ################ #####################.##\";milkshake_p/100;milkshake_q;milkshake_v/100\n?\nPrint Using \" subtotal #####################.##\";subtotal/10\nPrint Using \" tax #####################.##\";tax/100\nPrint Using \" total #####################.##\";subtotal/10+tax/100\nSleep\n", "language": "FreeBASIC" }, { "code": "st = 4000000000000000 * 5.50 dollars + 2 * 2.86 dollars\ntax = round[st * 7.65 percent, cent]\ntotal = st + tax\nprintln[\"Subtotal: \" + format[st, \"dollars\", 2]]\nprintln[\"Tax: \" + format[tax, \"dollars\", 2]]\nprintln[\"Total: \" + format[total, \"dollars\", 2]]\n", "language": "Frink" }, { "code": "local fn Lunch_Invoice( burger_price as CFStringRef, burger_amount as CFStringRef, shake_price as CFStringRef, shake_amount as CFStringRef, tax as CFStringRef )\n'~'1\nDecimalNumberRef burgerPriceDecimal = fn DecimalNumberWithString( burger_price )\nDecimalNumberRef burgerAmountDecimal = fn DecimalNumberWithString( burger_amount )\nDecimalNumberRef burgersDecimal = fn DecimalNumberByMultiplyingBy( burgerPriceDecimal, burgerAmountDecimal )\nDecimalNumberRef shakePriceDecimal = fn DecimalNumberWithString( shake_price )\nDecimalNumberRef shakeAmountDecimal = fn DecimalNumberWithString( shake_amount )\nDecimalNumberRef shakesDecimal = fn DecimalNumberByMultiplyingBy( shakePriceDecimal, shakeAmountDecimal )\nDecimalNumberRef taxDecimal = fn DecimalNumberWithString( tax )\nDecimalNumberRef subtotalDecimal = fn DecimalNumberByAdding( burgersDecimal, shakesDecimal )\nDecimalNumberRef taxTotalDecimal = fn DecimalNumberByMultiplyingBy( subtotalDecimal, taxDecimal )\nDecimalNumberRef adjTaxTotalDecimal = fn DecimalNumberByAdding( taxTotalDecimal, fn DecimalNumberWithString( @\"0.01\" ) )\nDecimalNumberRef billTotalDecimal = fn DecimalNumberByAdding( subtotalDecimal, adjTaxTotalDecimal )\n\nCFStringRef burgersString = fn DecimalNumberString( burgersDecimal )\nCFStringRef shakesString = fn DecimalNumberString( shakesDecimal )\nCFStringRef taxTotalString = fn DecimalNumberString( adjTaxTotalDecimal )\nCFStringRef billTotalString = fn DecimalNumberString( billTotalDecimal )\n\nprintf @\"%@\", fn StringByPaddingToLength( @\"\", 55, @\"-\", 0 )\nprintf @\"Item Price Quantity Cost\"\nprintf @\"Hamburgers %6s %18s %18s\", fn StringUTF8String( burger_price ), fn StringUTF8String( burger_amount ), fn StringUTF8String( burgersString )\nprintf @\"Milkshakes %6s %18s %18s\", fn StringUTF8String( shake_price ), fn StringUTF8String( shake_amount ), fn StringUTF8String( shakesString )\nprintf @\"%@\", fn StringByPaddingToLength( @\"\", 55, @\"-\", 0 )\nprintf @\"%34s %@\", fn StringUTF8String( @\"Subtotal:\" ), fn DecimalNumberString( subtotalDecimal )\nprintf @\"%35s %@\", fn StringUTF8String( @\" Tax: \" ), fn StringSubstringToIndex( taxTotalString, len(taxTotalString) - 3 )\nprintf @\"%34s %@\", fn StringUTF8String( @\" Total:\" ), fn StringSubstringToIndex( billTotalString, len(billTotalString) - 3 )\nend fn\n\nNSLog( @\"%@\", fn WindowPrintViewString( 1 ) )\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math/big\"\n)\n\n// DC for dollars and cents. Value is an integer number of cents.\ntype DC int64\n\nfunc (dc DC) String() string {\n d := dc / 100\n if dc < 0 {\n dc = -dc\n }\n return fmt.Sprintf(\"%d.%02d\", d, dc%100)\n}\n\n// Extend returns extended price of a unit price.\nfunc (dc DC) Extend(n int) DC {\n return dc * DC(n)\n}\n\nvar one = big.NewInt(1)\nvar hundred = big.NewRat(100, 1)\n\n// ParseDC parses dollars and cents as a string into a DC.\nfunc ParseDC(s string) (DC, bool) {\n r, ok := new(big.Rat).SetString(s)\n if !ok {\n return 0, false\n }\n r.Mul(r, hundred)\n if r.Denom().Cmp(one) != 0 {\n return 0, false\n }\n return DC(r.Num().Int64()), true\n}\n\n// TR for tax rate. Value is an an exact rational.\ntype TR struct {\n *big.Rat\n}\nfunc NewTR() TR {\n return TR{new(big.Rat)}\n}\n\n// SetString overrides Rat.SetString to return the TR type.\nfunc (tr TR) SetString(s string) (TR, bool) {\n if _, ok := tr.Rat.SetString(s); !ok {\n return TR{}, false\n }\n return tr, true\n}\n\nvar half = big.NewRat(1, 2)\n\n// Tax computes a tax amount, rounding to the nearest cent.\nfunc (tr TR) Tax(dc DC) DC {\n r := big.NewRat(int64(dc), 1)\n r.Add(r.Mul(r, tr.Rat), half)\n return DC(new(big.Int).Div(r.Num(), r.Denom()).Int64())\n}\n\nfunc main() {\n hamburgerPrice, ok := ParseDC(\"5.50\")\n if !ok {\n log.Fatal(\"Invalid hamburger price\")\n }\n milkshakePrice, ok := ParseDC(\"2.86\")\n if !ok {\n log.Fatal(\"Invalid milkshake price\")\n }\n taxRate, ok := NewTR().SetString(\"0.0765\")\n if !ok {\n log.Fatal(\"Invalid tax rate\")\n }\n\n totalBeforeTax := hamburgerPrice.Extend(4000000000000000) +\n milkshakePrice.Extend(2)\n tax := taxRate.Tax(totalBeforeTax)\n total := totalBeforeTax + tax\n\n fmt.Printf(\"Total before tax: %22s\\n\", totalBeforeTax)\n fmt.Printf(\" Tax: %22s\\n\", tax)\n fmt.Printf(\" Total: %22s\\n\", total)\n}\n", "language": "Go" }, { "code": "import Data.Fixed\nimport Text.Printf\n\ntype Percent = Centi\ntype Dollars = Centi\n\ntax :: Percent -> Dollars -> Dollars\ntax rate = MkFixed . round . (rate *)\n\nprintAmount :: String -> Dollars -> IO ()\nprintAmount name = printf \"%-10s %20s\\n\" name . showFixed False\n\nmain :: IO ()\nmain = do\n let subtotal = 4000000000000000 * 5.50 + 2 * 2.86\n tx = tax 7.65 subtotal\n total = subtotal + tx\n printAmount \"Subtotal\" subtotal\n printAmount \"Tax\" tx\n printAmount \"Total\" total\n", "language": "Haskell" }, { "code": "require 'format/printf'\n\nItems=: ;: 'Hamburger Milkshake'\nQuantities=: 4000000000000000 2\nPrices=: x: 5.50 2.86\nTax_rate=: x: 0.0765\n\nmakeBill=: verb define\n 'items prices quantities'=. y\n values=. prices * quantities\n subtotal=. +/ values\n tax=. Tax_rate * subtotal\n total=. subtotal + tax\n\n '%9s %8s %20s %22s' printf ;:'Item Price Quantity Value'\n '%9s %8.2f %20d %22.2f' printf\"1 items ,. <\"0 prices ,. quantities ,. values\n '%62s' printf <'-------------------------------'\n '%40s %21.2f' printf\"1 (;:'Subtotal: Tax: Total:') ,. subtotal;tax;total\n)\n\nmakeBill Items;Prices;Quantities\n", "language": "J" }, { "code": "import java.math.*;\nimport java.util.*;\n\npublic class Currency {\n final static String taxrate = \"7.65\";\n\n enum MenuItem {\n\n Hamburger(\"5.50\"), Milkshake(\"2.86\");\n\n private MenuItem(String p) {\n price = new BigDecimal(p);\n }\n\n public final BigDecimal price;\n }\n\n public static void main(String[] args) {\n Locale.setDefault(Locale.ENGLISH);\n\n MathContext mc = MathContext.DECIMAL128;\n\n Map<MenuItem, BigDecimal> order = new HashMap<>();\n order.put(MenuItem.Hamburger, new BigDecimal(\"4000000000000000\"));\n order.put(MenuItem.Milkshake, new BigDecimal(\"2\"));\n\n BigDecimal subtotal = BigDecimal.ZERO;\n for (MenuItem it : order.keySet())\n subtotal = subtotal.add(it.price.multiply(order.get(it), mc));\n\n BigDecimal tax = new BigDecimal(taxrate, mc);\n tax = tax.divide(new BigDecimal(\"100\"), mc);\n tax = subtotal.multiply(tax, mc);\n\n System.out.printf(\"Subtotal: %20.2f%n\", subtotal);\n System.out.printf(\" Tax: %20.2f%n\", tax);\n System.out.printf(\" Total: %20.2f%n\", subtotal.add(tax));\n }\n}\n", "language": "Java" }, { "code": "const money = require('money-math')\n\nlet hamburgers = 4000000000000000\nlet hamburgerPrice = 5.50\n\nlet shakes = 2\nlet shakePrice = 2.86\n\nlet tax = 7.65\n\nlet hamburgerTotal = money.mul(hamburgers.toFixed(0), money.floatToAmount(hamburgerPrice))\nlet shakeTotal = money.mul(shakes.toFixed(0), money.floatToAmount(shakePrice))\n\nlet subTotal = money.add(hamburgerTotal, shakeTotal)\n\nlet taxTotal = money.percent(subTotal, tax)\n\nlet total = money.add(subTotal, taxTotal)\n\nconsole.log('Hamburger Total:', hamburgerTotal)\nconsole.log('Shake Total:', shakeTotal)\nconsole.log('Sub Total:', subTotal)\nconsole.log('Tax:', taxTotal)\nconsole.log('Total:', total)\n", "language": "JavaScript" }, { "code": "def lpad($len): tostring | ($len - length) as $l | (\" \" * $l)[:$l] + .;\n\n# print as dollars and cents\ndef dollars:\n (. % 100) as $c\n | \"$\\((. - $c) /100).\\($c)\";\n\ndef dollars($width):\n dollars | lpad($width);\n\ndef innerproduct($y):\n . as $x\n | reduce range(0;$x|length) as $i (0; . + ($x[$i]*$y[$i]));\n\ndef plus($y):\n . as $x\n | reduce range(0;$x|length) as $i ([]; .[$i] = ($x[$i]+$y[$i]));\n\n# Round up or down\ndef integer_division($y):\n (. % $y) as $remainder\n | (. - $remainder) / $y\n | if $remainder * 2 > $y then . + 1 else . end;\n\n# For computing taxes\ndef precision: 10000;\ndef cents: integer_division(precision);\n\n\n### The task:\n\ndef p: [550, 286];\ndef q: [4000000000000000, 2];\n\ndef taxrate: 765; # relative to `precision`\n\n(p | innerproduct(q)) as $before_tax # cents\n| ($before_tax * taxrate) as $taxes # relative to precision\n| ((($before_tax * precision) + $taxes) | cents) as $after_tax # cents\n| ($after_tax|tostring|length + 2) as $width\n|\n \" Total before tax: \\($before_tax | dollars($width))\",\n \" - tax: \\($taxes | cents | dollars($width))\",\n \" Total after tax: \\($after_tax | dollars($width))\"\n", "language": "Jq" }, { "code": "using Printf\n\np = [big\"5.50\", big\"2.86\"]\nq = [4000000000000000, 2]\ntr = big\"0.0765\"\n\nbeftax = p' * q\ntax = beftax * tr\nafttax = beftax + tax\n\n@printf \" - tot. before tax: %20.2f \\$\\n\" beftax\n@printf \" - tax: %20.2f \\$\\n\" tax\n@printf \" - tot. after tax: %20.2f \\$\\n\" afttax\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nimport java.math.BigDecimal\nimport java.math.MathContext\n\nfun main(args: Array<String>) {\n val mc = MathContext.DECIMAL128\n val nHamburger = BigDecimal(\"4000000000000000\", mc)\n val pHamburger = BigDecimal(\"5.50\")\n val nMilkshakes = BigDecimal(\"2\", mc)\n val pMilkshakes = BigDecimal(\"2.86\")\n val taxRate = BigDecimal(\"0.0765\")\n val price = nHamburger * pHamburger + nMilkshakes * pMilkshakes\n val tax = price * taxRate\n val fmt = \"%20.2f\"\n println(\"Total price before tax : ${fmt.format(price)}\")\n println(\"Tax thereon @ 7.65% : ${fmt.format(tax)}\")\n println(\"Total price after tax : ${fmt.format(price + tax)}\")\n}\n", "language": "Kotlin" }, { "code": "C = setmetatable(require(\"bc\"), {__call=function(t,...) return t.new(...) end})\nC.digits(6) -- enough for .nn * .nnnn ==> .nnnnnn, follow with trunc(2) to trim trailing zeroes\n\nsubtot = (C\"4000000000000000\" * C\"5.50\" + C\"2\" * C\"2.86\"):trunc(2) -- cosmetic trunc\ntax = (subtot * C\"0.0765\" + C\"0.005\"):trunc(2) -- rounding trunc\ntotal = (subtot + tax):trunc(2) -- cosmetic trunc\n\nprint((\"Before tax: %20s\"):format(subtot:tostring()))\nprint((\"Tax : %20s\"):format(tax:tostring()))\nprint((\"With tax : %20s\"):format(total:tostring()))\n", "language": "Lua" }, { "code": "Module Currency_Task {\n Locale 1033\n Font \"Courier New\"\n Form 80,32\n \\\\Decimal type\n hamburgers=4000000000000000@\n \\\\ Currency type\n hamburger_price=5.5#\n milkshakes=2#\n milkshake_price=2.86#\n tax_rate=0.0765#\n \\\\ Using Columns with variable width in console\n PrHeadLine(\"Item\",\"price\",\"quantity\", \"value\")\n PrLine(\"hamburger\",hamburger_price,hamburgers,hamburgers*hamburger_price)\n PrLine(\"milkshake\", milkshake_price,milkshakes,milkshakes*milkshake_price)\n PrResults( \"subtotal\", hamburgers*hamburger_price+milkshakes*milkshake_price)\n PrResults(\"tax\", (hamburgers*hamburger_price+milkshakes*milkshake_price)*tax_rate)\n \\\\ 1 is double by default we can use 1# or 1@\n PrResults(\"total\", (hamburgers*hamburger_price+milkshakes*milkshake_price)*(tax_rate+1))\n\n \\\\ Using variables for partial calculations. They get type from expression result\n h_p_q=hamburgers*hamburger_price\n m_p_q=milkshakes*milkshake_price\n\n \\\\ Using format$ to prepare final strings\n Print format$(\"{0:15}{1:-8}{2:-25}{3:-25}\",\"Item\", \"price\", \"quantity\", \"value\")\n Print format$(\"{0:15}{1:2:-8}{2:0:-25}{3:2:-25}\",\"hamburger\",hamburger_price,hamburgers, h_p_q)\n Print format$(\"{0:15}{1:2:-8}{2:0:-25}{3:2:-25}\",\"milkshake\", milkshake_price,milkshakes,m_p_q)\n Print format$(\"{0:-48}{1:2:-25}\",\"subtotal\", h_p_q+m_p_q)\n Print format$(\"{0:-48}{1:2:-25}\",\"tax\", (h_p_q+m_p_q)*tax_rate)\n Print format$(\"{0:-48}{1:2:-25}\",\"total\", (h_p_q+m_p_q)*(tax_rate+1))\n \\\\ Another time to feed Document to export to clipboard\n Document Doc$=format$(\"{0:15}{1:-8}{2:-25}{3:-25}\",\"Item\", \"price\", \"quantity\", \"value\")+{\n }+format$(\"{0:15}{1:2:-8}{2:0:-25}{3:2:-25}\",\"hamburger\",hamburger_price,hamburgers, h_p_q)+{\n }+format$(\"{0:15}{1:2:-8}{2:0:-25}{3:2:-25}\",\"milkshake\", milkshake_price,milkshakes,m_p_q)+{\n }+format$(\"{0:-48}{1:2:-25}\",\"subtotal\", h_p_q+m_p_q)+{\n }+format$(\"{0:-48}{1:2:-25}\",\"tax\", (h_p_q+m_p_q)*tax_rate)+{\n }+format$(\"{0:-48}{1:2:-25}\",\"total\", (h_p_q+m_p_q)*(tax_rate+1))+{\n }\n clipboard Doc$\n \\\\ one line user function definition\n \\\\ x get type from passed value\n Def ExpressionType$(x)=Type$(X)\n \\\\ Check Expression final type\n Print ExpressionType$(hamburgers)=\"Decimal\"\n Print ExpressionType$(milkshakes)=\"Currency\"\n Print ExpressionType$(h_p_q)=\"Decimal\"\n Print ExpressionType$(m_p_q)=\"Currency\"\n Print ExpressionType$((h_p_q+m_p_q)*tax_rate)=\"Decimal\"\n Print ExpressionType$((h_p_q+m_p_q)*(tax_rate+1))=\"Decimal\"\n\n Sub PrHeadLine(a$,b$,c$,d$)\n Print Part $(1,15),a$,$(3,8),b$, $(3,25),c$, $(3,25),d$\n Print\n End Sub\n Sub PrLine(a$,b,c,d)\n Print Part $(1,15),a$,$(\"0.00\"),$(3,8),b, $(\"0\"),$(3,25),c,$(\"0.00\"), $(3,25),d\n Print\n End Sub\n Sub PrResults(a$,b)\n Print Part $(3,48),a$,$(\"0.00\"),$(3,25),b\n Print\n End Sub\n}\nCurrency_Task\n", "language": "M2000-Interpreter" }, { "code": "Module Currency_Task {\n Locale 1033\n Font \"Courier New\"\n Form 80,32\n hamburgers=4000000000000000@\n hamburger_price=5.5#\n milkshakes=2#\n milkshake_price=2.86#\n tax_rate=0.0765#\n PrHeadLine(\"Item\",\"price\",\"quantity\", \"value\")\n PrLine(\"hamburger\",hamburger_price,hamburgers,hamburgers*hamburger_price)\n PrLine(\"milkshake\", milkshake_price,milkshakes,milkshakes*milkshake_price)\n PrResults( \"subtotal\", hamburgers*hamburger_price+milkshakes*milkshake_price)\n PrResults(\"tax\", (hamburgers*hamburger_price+milkshakes*milkshake_price)*tax_rate)\n PrResults(\"total\", (hamburgers*hamburger_price+milkshakes*milkshake_price)*(tax_rate+1))\n\n h_p_q=hamburgers*hamburger_price\n m_p_q=milkshakes*milkshake_price\n Document Doc$=format$(\"{0:15}{1:-8}{2:-25}{3:-30}\",\"Item\", \"price\", \"quantity\", \"value\")+{\n }+format$(\"{0:15}{1:-8}{2:-25}{3:-30}\",\"hamburger\",str$(hamburger_price,\"$#,##0.00\"),str$(hamburgers, \"#,##0\"), Str$(h_p_q,\"$#,##0.00\"))+{\n }+format$(\"{0:15}{1:-8}{2:-25}{3:-30}\",\"milkshake\", str$(milkshake_price,\"$#,##0.00\"),Str$(milkshakes, \"#,##0\"), Str$(m_p_q,\"$#,##0.00\"))+{\n }+format$(\"{0:-48}{1:-30}\",\"subtotal\", Str$(h_p_q+m_p_q,\"$#,##0.00\"))+{\n }+format$(\"{0:-48}{1:-30}\",\"tax\", Str$((h_p_q+m_p_q)*tax_rate,\"$#,##0.00\"))+{\n }+format$(\"{0:-48}{1:-30}\",\"total\", Str$((h_p_q+m_p_q)*(tax_rate+1),\"$#,##0.00\"))+{\n }\n clipboard Doc$\n\n\n Sub PrHeadLine(a$,b$,c$,d$)\n Print Part $(1,15),a$,$(3,8),b$, $(3,25),c$, $(3,30),d$\n Print\n End Sub\n Sub PrLine(a$,b,c,d)\n Print Part $(1,15),a$,$(\"$#,###.00\"),$(3,8),b, $(\"#,##0\"),$(3,25),c,$(\"$#,###.00\"), $(3,30),d\n Print\n End Sub\n Sub PrResults(a$,b)\n Print Part $(3,48),a$,$(\"$#,###.00\"),$(3,30),b\n Print\n End Sub\n}\nCurrency_Task\n", "language": "M2000-Interpreter" }, { "code": "Digits := 50;\ntax := .0765;\n\nburgersquantity := 4000000000000000;\nburgersprice := 5.50;\nburgerscost := burgersquantity * burgersprice;\n\nmilkshakesquantity := 2;\nmilkshakesprice := 2.86;\nmilkshakescost := milkshakesquantity * milkshakesprice;\n\ntotal := burgerscost + milkshakescost;\nprintf(\"%.2f\\n\",total);\n\ntotaltax := total * tax;\nprintf(\"%.2f\\n\",totaltax);\n\ntotalprice := totaltax + total;\nprintf(\"%.2f\\n\",totalprice);\n", "language": "Maple" }, { "code": "total = 4000000000000000 Rationalize[5.50] + 2 Rationalize[2.86];\nAccountingForm[N[total, 20], {\\[Infinity], 2}]\ntax = total Rationalize[0.0765];\nAccountingForm[N[tax, 20], {\\[Infinity], 2}]\nAccountingForm[N[total + tax, 20], {\\[Infinity], 2}]\n", "language": "Mathematica" }, { "code": "import strutils\nimport bignum\n\ntype Currency = Int\n\n#---------------------------------------------------------------------------------------------------\n\nfunc currency(units, subunits: int): Currency =\n ## Build a currency from units and subunits.\n ## Units may be negative. Subunits must be in range 0..99.\n if subunits notin 0..99:\n raise newException(ValueError, \"wrong value for subunits\")\n result = if units >= 0: newInt(units * 100 + subunits)\n else: newInt(subunits * 100 - subunits)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc currency(value: string): Currency =\n ## Build a currency from a string.\n ## Negative values are allowed. At most two digits are allowed for subunits.\n\n const StartingChars = Digits + {'-'}\n if value.len == 0 or value[0] notin StartingChars:\n raise newException(ValueError, \"wrong currency string\")\n\n # process sign and units.\n var units = newInt(0)\n var subunits = 0\n let sign = if value[0] == '-': -1 else: 1\n var idx = if sign == 1: 0 else: 1\n while idx < value.len:\n if value[idx] notin Digits: break\n units = 10 * units + ord(value[idx]) - ord('0')\n inc idx\n\n # Process separator.\n if idx <= value.high:\n if value[idx] != '.':\n raise newException(ValueError, \"expected a separator\")\n inc idx\n\n # Process subunits.\n for _ in 0..1:\n let c = if idx >= value.len: '0' else: value[idx]\n if c notin Digits:\n raise newException(ValueError, \"wrong value for subunits\")\n subunits = 10 * subunits + ord(c) - ord('0')\n inc idx\n\n if idx <= value.high:\n raise newException(ValueError, \"extra characters after subunits digits\")\n\n result = sign * (units * 100 + subunits)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `//`(a, b: int): Rat =\n ## Create a rational value.\n newRat(a, b)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc percentage(a: Currency; p: Rat): Currency =\n ## Compute a percentage on currency value \"a\".\n ## Returned value is rounded to nearest integer.\n\n (a * p.num * 10 div p.denom + 5) div 10\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `$`(a: Currency): string =\n ## Build a string representation of a currency value.\n\n result = bignum.`$`(a div 100) & '.' & ($(a mod 100).toInt).align(2, '0')\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nlet hamburgers = currency(5, 50) * int 4_000_000_000_000_000\nlet milkshakes = currency(\"2.86\") * 2\nlet rate = 765 // 10_000\nlet beforeTax = hamburgers + milkshakes\nlet tax = beforeTax.percentage(rate)\nlet total = beforeTax + tax\n\n# Find the maximum length of numerical value representations.\nlet beforeTaxStr = $beforeTax\nlet taxStr = $tax\nlet totalStr = $total\nlet length = max([beforeTaxStr.len, taxStr.len, totalStr.len])\n\n# Display the results.\necho \"Total price before tax: \", beforeTaxStr.align(length)\necho \"Tax: \", taxStr.align(length)\necho \"Total with tax: \", totalStr.align(length)\n", "language": "Nim" }, { "code": "let () =\n let open Decimal in (* bring all functions and operators into scope locally *)\n let s = of_string in\n let i = of_int in\n\n let hamburgers = s \"4e15\" * s \"5.50\" in\n let milkshakes = i 2 * s \"2.86\" in\n let tax_rate = s \"7.65e-2\" in\n let subtotal = hamburgers + milkshakes in\n let tax = subtotal * tax_rate in\n let total = subtotal + tax in\n\n Printf.printf\n \"Subtotal: %20s\n Tax: %20s\n Total: %20s\\n\"\n (to_string (round ~n:2 subtotal))\n (to_string (round ~n:2 tax))\n (to_string (round ~n:2 total))\n", "language": "OCaml" }, { "code": "use Math::Decimal qw(dec_canonise dec_add dec_mul dec_rndiv_and_rem);\n\n@check = (\n [<Hamburger 5.50 4000000000000000>],\n [<Milkshake 2.86 2>]\n);\n\nmy $fmt = \"%-10s %8s %18s %22s\\n\";\nprintf $fmt, <Item Price Quantity Extension>;\n\nmy $subtotal = dec_canonise(0);\nfor $line (@check) {\n ($item,$price,$quant) = @$line;\n $dp = dec_canonise($price); $dq = dec_canonise($quant);\n my $extension = dec_mul($dp,$dq);\n $subtotal = dec_add($subtotal, $extension);\n printf $fmt, $item, $price, $quant, rnd($extension);\n}\n\nmy $rate = dec_canonise(0.0765);\nmy $tax = dec_mul($subtotal,$rate);\nmy $total = dec_add($subtotal,$tax);\n\nprintf $fmt, '', '', '', '-----------------';\nprintf $fmt, '', '', 'Subtotal ', rnd($subtotal);\nprintf $fmt, '', '', 'Tax ', rnd($tax);\nprintf $fmt, '', '', 'Total ', rnd($total);\n\nsub rnd {\n ($q, $r) = dec_rndiv_and_rem(\"FLR\", @_[0], 1);\n $q . substr((sprintf \"%.2f\", $r), 1, 3);\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #7060A8;\">requires</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"1.0.4\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (mpfr_get_fixed() busted in 1.0.2|3)</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">mpfr</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #7060A8;\">mpfr_set_default_precision</span><span style=\"color: #0000FF;\">(-</span><span style=\"color: #000000;\">20</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- ensure accuracy to at least 20 d.p.</span>\n\n <span style=\"color: #004080;\">mpfr</span> <span style=\"color: #000000;\">total_price</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpfr_init</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"4000000000000000\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">tmp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpfr_init</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"5.5\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">tax</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpfr_init</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"0.0765\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">total</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpfr_init</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">mpfr_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">total_price</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">total_price</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tmp</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpfr_set_str</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tmp</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"2.86\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpfr_mul_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tmp</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tmp</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpfr_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">total_price</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">total_price</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tmp</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpfr_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tax</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">total_price</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tax</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpfr_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">total</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">total_price</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tax</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Total before tax:%26s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">mpfr_get_fixed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">total_price</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">comma_fill</span><span style=\"color: #0000FF;\">:=</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" Tax:%26s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">mpfr_get_fixed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tax</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">comma_fill</span><span style=\"color: #0000FF;\">:=</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" Total:%26s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">mpfr_get_fixed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">total</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">comma_fill</span><span style=\"color: #0000FF;\">:=</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)})</span>\n<!--\n", "language": "Phix" }, { "code": "-->\n <span style=\"color: #7060A8;\">requires</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">64</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">total_price</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">4000000000000000</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">5.5</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2.86</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">tax</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">total_price</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">0.0765</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">total</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">total_price</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">tax</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Total before tax:%,26.2f\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">total_price</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" Tax:%,26.2f\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">tax</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" Total:%,26.2f\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">total</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "(scl 2)\n(let\n (Before\n (+\n (* 4000000000000000 5.50)\n (* 2 2.86) )\n Tax (*/ Before 7.65 100.00)\n Total (+ Before Tax)\n Fmt (17 27) )\n (tab Fmt \"Total before tax:\" (format Before *Scl \".\" \",\"))\n (tab Fmt \"Tax:\" (format Tax *Scl \".\" \",\"))\n (tab Fmt \"Total:\" (format Total *Scl \".\" \",\")) )\n", "language": "PicoLisp" }, { "code": "from decimal import Decimal as D\nfrom collections import namedtuple\n\nItem = namedtuple('Item', 'price, quant')\n\nitems = dict( hamburger=Item(D('5.50'), D('4000000000000000')),\n milkshake=Item(D('2.86'), D('2')) )\ntax_rate = D('0.0765')\n\nfmt = \"%-10s %8s %18s %22s\"\nprint(fmt % tuple('Item Price Quantity Extension'.upper().split()))\n\ntotal_before_tax = 0\nfor item, (price, quant) in sorted(items.items()):\n ext = price * quant\n print(fmt % (item, price, quant, ext))\n total_before_tax += ext\nprint(fmt % ('', '', '', '--------------------'))\nprint(fmt % ('', '', 'subtotal', total_before_tax))\n\ntax = (tax_rate * total_before_tax).quantize(D('0.00'))\nprint(fmt % ('', '', 'Tax', tax))\n\ntotal = total_before_tax + tax\nprint(fmt % ('', '', '', '--------------------'))\nprint(fmt % ('', '', 'Total', total))\n", "language": "Python" }, { "code": " [ $ \"bigrat.qky\" loadfile ] now!\n\n [ 100 * n->v ] is dollars ( n --> n/d )\n\n [ n->v v+ ] is cents ( n/d n --> n/d )\n\n [ rot n->v v* ] is cost ( n n/d --> n/d )\n\n [ $->v drop v* 100 n->v v/ ] is tax ( n/d $ --> n/d )\n\n [ 100 n->v v/\n 2 point$\n $ \" $\" swap join\n ' [ 2 split nip ] ]do[\n dup -3 peek\n char . = if done\n dup -2 peek\n char . = iff\n [ char 0 join ]\n done\n $ \".00\" join ] is currency$ ( n/d --> $ )\n\n [ currency$ echo$ ] is echocurrency ( n/d --> )\n\n\n 4000000000000000 5 dollars 50 cents cost\n 2 2 dollars 86 cents cost v+\n\n say \"Total price before tax: \" 2dup echocurrency cr\n\n 2dup $ \"7.65\" tax\n\n say \"Tax: \" 2dup echocurrency cr\n\n v+\n say \"Total price with tax: \" echocurrency cr\n", "language": "Quackery" }, { "code": "#lang racket\n(define (cents-* x y)\n (/ (round (* 100 x y)) 100))\n\n(struct item (name count price))\n\n(define (string-pad-right len . strs)\n (define all (apply string-append strs))\n (string-append all (make-string (- len (string-length all)) #\\space)))\n\n(define (string-pad-left len . strs)\n (define all (apply string-append strs))\n (string-append (make-string (- len (string-length all)) #\\space) all))\n\n(define (show-formated name count price total)\n (printf \"~a ~a ~a -> ~a\\n\"\n (string-pad-right 10 name)\n (string-pad-left 18 count)\n (string-pad-left 8 price)\n (string-pad-left 23 total)\n ))\n\n(define (show-item it)\n (show-formated (item-name it)\n (~r (item-count it))\n (string-append \"$\" (~r (item-price it) #:precision '(= 2)))\n (string-append \"$\" (~r (cents-* (item-count it) (item-price it)) #:precision '(= 2)))\n ))\n\n(define (show-total all tax-rate)\n (define net (for/sum ([it (in-list all)])\n (cents-* (item-count it) (item-price it))))\n (define tax (cents-* net tax-rate))\n (show-formated \"\" \"\" \"net\" (string-append \"$\" (~r net #:precision '(= 2))))\n (show-formated \"\" \"\" \"tax\" (string-append \"$\" (~r tax #:precision '(= 2))))\n (show-formated \"\" \"\" \"total\" (string-append \"$\" (~r (+ net tax) #:precision '(= 2))))\n )\n\n(define hamburger (item \"hamburger\" 4000000000000000 #e5.50))\n(define milkshake (item \"milkshake\" 2 #e2.86))\n(define all (list hamburger milkshake))\n\n(for-each show-item all)\n(newline)\n(show-total all (/ #e7.65 100))\n", "language": "Racket" }, { "code": "my @check = q:to/END/.lines.map: { [.split(/\\s+/)] };\n Hamburger 5.50 4000000000000000\n Milkshake 2.86 2\n END\n\nmy $tax-rate = 0.0765;\n\nmy $fmt = \"%-10s %8s %18s %22s\\n\";\n\nprintf $fmt, <Item Price Quantity Extension>;\n\nmy $subtotal = [+] @check.map: -> [$item,$price,$quant] {\n my $extension = $price * $quant;\n printf $fmt, $item, $price, $quant, fix2($extension);\n $extension;\n}\n\nprintf $fmt, '', '', '', '-----------------';\nprintf $fmt, '', '', 'Subtotal ', $subtotal;\n\nmy $tax = ($subtotal * $tax-rate).round(0.01);\nprintf $fmt, '', '', 'Tax ', $tax;\n\nmy $total = $subtotal + $tax;\nprintf $fmt, '', '', 'Total ', $total;\n\n# make up for lack of a Rat fixed-point printf format\nsub fix2($x) { ($x + 0.001).subst(/ <?after \\.\\d\\d> .* $ /, '') }\n", "language": "Raku" }, { "code": "/*REXX program shows a method of computing the total price and tax for purchased items.*/\nnumeric digits 200 /*support for gihugic numbers.*/\ntaxRate= 7.65 /*number is: nn or nn% */\nif right(taxRate, 1)\\=='%' then taxRate= taxRate / 100 /*handle plain tax rate number*/\ntaxRate= strip(taxRate, , '%') /*strip the % (if present).*/\nitem. =; items= 0 /*zero out the register. */\nitem.1 = '4000000000000000 $5.50 hamburger' /*the first item purchased. */\nitem.2 = ' 2 $2.86 milkshake' /* \" second \" \" */\nsay center('quantity', 22) center(\"item\", 22) center('price', 22)\nhdr= center('', 27, \"─\") center('', 20, \"─\") center('', 27, \"─\")\nsay hdr; total= 0\n do j=1 while item.j\\=='' /*calculate the total and tax.*/\n parse var item.j quantity price thing /*ring up an item on register.*/\n items = items + quantity /*tally the number of items. */\n price = translate(price, , '$') /*maybe scrub out the $ symbol*/\n subtotal = quantity * price /*calculate the sub-total.*/\n total = total + subtotal /* \" \" running total.*/\n say right(quantity, 27) left(thing, 20) show$(subtotal)\n end /*j*/\nsay /*display a blank line for separator. */\nsay translate(hdr, '═', \"─\") /*display the separator part of the hdr*/\ntax= format(total * taxRate, , 2) /*round the total tax for all the items*/\nsay right(items \"(items)\", 35) right('total=', 12) show$(total)\nsay right('tax at' (taxRate * 100 / 1)\"%=\", 48) show$(tax)\nsay\nsay right('grand total=', 48) show$(total+tax)\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nshow$: return right( '$'arg(1), 27) /*right─justify and format a number. */\n", "language": "REXX" }, { "code": "/*REXX program shows a method of computing the total price and tax for purchased items.*/\nnumeric digits 200 /*support for gihugic numbers.*/\ntaxRate= 7.65 /*number is: nn or nn% */\nif right(taxRate, 1)\\=='%' then taxRate= taxRate / 100 /*handle plain tax rate number*/\ntaxRate=strip(taxRate, , '%') /*strip the % (if present).*/\nitem. =; items= 0 /*zero out the register. */\nitem.1 = '4000000000000000 $5.50 hamburger' /*the first item purchased. */\nitem.2 = ' 2 $2.86 milkshake' /* \" second \" \" */\nsay center('quantity', 22) center(\"item\", 22) center('price', 22)\nhdr= center('', 27 ,\"─\") center('', 20, \"─\") center('', 27, \"─\")\nsay hdr; total=0\n do j=1 while item.j\\=='' /*calculate the total and tax.*/\n parse var item.j quantity price thing /*ring up an item on register.*/\n items = items + quantity /*tally the number of items. */\n price = translate(price, , '$') /*maybe scrub out the $ symbol*/\n subtotal = quantity * price /*calculate the sub-total.*/\n total = total + subtotal /* \" \" running total.*/\n say right(quantity, 27) left(thing, 20) show$(subtotal)\n end /*j*/\nsay /*display a blank line for separator. */\nsay translate(hdr, '═', \"─\") /*display the separator part of the hdr*/\ntax= format(total * taxRate, , 2) /*round the total tax for all the items*/\nsay right( commas(items \"(items)\"), 35) right('total=', 12) show$(total)\nsay right('tax at' (taxRate * 100 / 1)\"%=\", 48) show$(tax)\nsay\nsay right('grand total=', 48) show$(total + tax)\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncommas: procedure; parse arg _; n= _'.9'; #= 123456789; b= verify(n, #, \"M\")\n e= verify(n, #'0', , verify(n, #\"0.\", 'M') ) - 4 /* [↓] commatize number*/\n do j=e to b by -3; _= insert(',', _, j); end /*j*/; return _\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nshow$: return right( commas( '$'arg(1) ), 27) /*right─justify and format a number. */\n", "language": "REXX" }, { "code": "# Project : Currency\n\nnhamburger = \"4000000000\"\nphamburger = \"5.50\"\nnmilkshakes = \"2\"\npmilkshakes = \"2.86\"\ntaxrate = \"0.0765\"\nprice = nhamburger * phamburger + nmilkshakes * pmilkshakes\ntax = price * taxrate\nsee \"total price before tax : \" + price + nl\nsee \"tax thereon @ 7.65 : \" + tax + nl\nsee \"total price after tax : \" + (price + tax) + nl\n", "language": "Ring" }, { "code": "require 'bigdecimal/util'\n\nbefore_tax = 4000000000000000 * 5.50.to_d + 2 * 2.86.to_d\ntax = (before_tax * 0.0765.to_d).round(2)\ntotal = before_tax + tax\n\nputs \"Before tax: $#{before_tax.to_s('F')}\nTax: $#{tax.to_s('F')}\nTotal: $#{total.to_s('F')}\"\n", "language": "Ruby" }, { "code": "extern crate num_bigint; // 0.3.0\nextern crate num_rational; // 0.3.0\n\nuse num_bigint::BigInt;\nuse num_rational::BigRational;\n\n\nuse std::ops::{Add, Mul};\nuse std::fmt;\n\nfn main() {\n let hamburger = Currency::new(5.50);\n let milkshake = Currency::new(2.86);\n let pre_tax = hamburger * 4_000_000_000_000_000 + milkshake * 2;\n println!(\"Price before tax: {}\", pre_tax);\n let tax = pre_tax.calculate_tax();\n println!(\"Tax: {}\", tax);\n let post_tax = pre_tax + tax;\n println!(\"Price after tax: {}\", post_tax);\n}\n\n#[derive(Debug)]\nstruct Currency {\n amount: BigRational,\n}\n\nimpl Add for Currency {\n\n type Output = Self;\n\n fn add(self, other: Self) -> Self {\n Self {\n amount: self.amount + other.amount,\n }\n }\n}\n\nimpl Mul<u64> for Currency {\n\n type Output = Self;\n\n fn mul(self, other: u64) -> Self {\n Self {\n amount: self.amount * BigInt::from(other),\n }\n }\n}\n\nimpl fmt::Display for Currency {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n let cents = (&self.amount * BigInt::from(100)).to_integer();\n write!(f, \"${}.{:0>2}\", &cents / 100, &cents % 100)\n }\n}\n\nimpl Currency {\n\n fn new(num: f64) -> Self {\n Self {\n amount: BigRational::new(((num * 100.0).round() as i64).into(), 100.into())\n }\n }\n\n fn calculate_tax(&self) -> Self {\n let tax_val = BigRational::new(765.into(), 100.into());// 7,65 -> 0.0765 after the next line\n let amount = (&self.amount * tax_val).ceil() / BigInt::from(100);\n Self {\n amount\n }\n }\n}\n", "language": "Rust" }, { "code": "import java.text.NumberFormat\nimport java.util.Locale\n\nobject SizeMeUp extends App {\n\n val menu: Map[String, (String, Double)] = Map(\"burg\" ->(\"Hamburger XL\", 5.50), \"milk\" ->(\"Milkshake\", 2.86))\n val order = List((4000000000000000L, \"burg\"), (2L, \"milk\"))\n\n Locale.setDefault(new Locale(\"ru\", \"RU\"))\n\n val (currSymbol, tax) = (NumberFormat.getInstance().getCurrency.getSymbol, 0.0765)\n\n def placeOrder(order: List[(Long, String)]) = {\n val totals = for ((qty, article) <- order) yield {\n val (desc, itemPrize) = menu(article)\n val (items, post) = (qty, qty * BigDecimal(itemPrize))\n println(f\"$qty%16d\\t$desc%-16s\\t$currSymbol%4s$itemPrize%6.2f\\t$post%,25.2f\")\n (items, post)\n }\n totals.foldLeft((0L, BigDecimal(0))) { (acc, n) => (acc._1 + n._1, acc._2 + n._2)}\n }\n\n val (items, beforeTax) = placeOrder(order)\n\n println(f\"$items%16d\\t${\"ordered items\"}%-16s${'\\t' + \" Subtotal\" + '\\t'}$beforeTax%,25.2f\")\n\n val taxation = beforeTax * tax\n println(f\"${\" \" * 16 + '\\t' + \" \" * 16 + '\\t' + f\"${tax * 100}%5.2f%% tax\" + '\\t'}$taxation%,25.2f\")\n println(f\"${\" \" * 16 + '\\t' + \" \" * 16 + '\\t' + \"Amount due\" + '\\t'}${beforeTax + taxation}%,25.2f\")\n}\n", "language": "Scala" }, { "code": "struct Item {\n name, price, quant\n}\n\nvar check = %q{\n Hamburger 5.50 4000000000000000\n Milkshake 2.86 2\n}.lines.grep(/\\S/).map { Item(.words...) }\n\nvar tax_rate = 0.0765\nvar fmt = \"%-10s %8s %18s %22s\\n\"\n\nprintf(fmt, %w(Item Price Quantity Extension)...)\n\nvar subtotal = check.map { |item|\n var extension = Num(item.price)*Num(item.quant)\n printf(fmt, item.name, item.price, item.quant, extension.round(-2))\n extension\n}.sum(0)\n\nprintf(fmt, '', '', '', '-----------------')\nprintf(fmt, '', '', 'Subtotal ', subtotal)\n\nvar tax = (subtotal * tax_rate -> round(-2))\nprintf(fmt, '', '', 'Tax ', tax)\n\nvar total = subtotal+tax\nprintf(fmt, '', '', 'Total ', total)\n", "language": "Sidef" }, { "code": "check := #(\n \" amount name price \"\n (4000000000000000 'hamburger' 5.50s2 )\n (2 'milkshakes' 2.86s2 )\n).\ntax := 7.65s2.\nfmt := '%-10s %10P %22P %26P\\n'.\n\ntotalSum := 0.\ntotalTax := 0.\n\nTranscript clear.\nTranscript printf:fmt withAll:#('Item' 'Price' 'Qty' 'Extension').\nTranscript printCR:('-' ,* 72).\n\ncheck do:[:entry|\n |amount name price itemTotal itemTax|\n\n amount := entry[1].\n name := entry[2].\n price := entry[3].\n itemTotal := (price*amount).\n itemTax := ((price*amount)*tax/100) roundedToScale.\n\n totalSum := totalSum + itemTotal.\n totalTax := totalTax + itemTax.\n Transcript printf:fmt\n withAll:{name . price . amount . itemTotal}.\n].\nTranscript printCR:('-' ,* 72).\nTranscript printf:fmt withAll:{'' . '' . 'Subtotal' . totalSum}.\nTranscript printf:fmt withAll:{'' . '' . 'Tax' . totalTax}.\nTranscript printf:fmt withAll:{'' . '' . 'Total' . (totalSum+totalTax)}.\n\nTranscript cr; printCR:('Enjoy your Meal & Thank You for Dining at Milliways')\n", "language": "Smalltalk" }, { "code": "import Foundation\n\nextension Decimal {\n func rounded(_ scale: Int, _ roundingMode: NSDecimalNumber.RoundingMode) -> Decimal {\n var result = Decimal()\n var localCopy = self\n NSDecimalRound(&result, &localCopy, scale, roundingMode)\n return result\n }\n}\n\nlet costHamburgers = Decimal(4000000000000000) * Decimal(5.50)\nlet costMilkshakes = Decimal(2) * Decimal(2.86)\nlet totalBeforeTax = costMilkshakes + costHamburgers\nlet taxesToBeCollected = (Decimal(string: \"0.0765\")! * totalBeforeTax).rounded(2, .bankers)\n\nprint(\"Price before tax: $\\(totalBeforeTax)\")\nprint(\"Total tax to be collected: $\\(taxesToBeCollected)\")\nprint(\"Total with taxes: $\\(totalBeforeTax + taxesToBeCollected)\")\n", "language": "Swift" }, { "code": "package require math::decimal\nnamespace import math::decimal::*\n\nset hamburgerPrice [fromstr 5.50]\nset milkshakePrice [fromstr 2.86]\nset taxRate [/ [fromstr 7.65] [fromstr 100]]\n\nset burgers 4000000000000000\nset shakes 2\nset net [+ [* [fromstr $burgers] $hamburgerPrice] [* [fromstr $shakes] $milkshakePrice]]\nset tax [round_up [* $net $taxRate] 2]\nset total [+ $net $tax]\n\nputs \"net=[tostr $net], tax=[tostr $tax], total=[tostr $total]\"\n", "language": "Tcl" }, { "code": "import math\n\nprocedure main()\n n_burgers := 4000000000000000\n n_shakes := 2\n\n price := FxPt(5.50) * n_burgers + FxPt(2.86) * n_shakes\n tax := (price * FxPt(7.65/100)).round(2)\n total := price + tax\n\n write(left(\"Price\", 10), \"$\", right(price.toString(),21))\n write(left(\"Tax\", 10), \"$\", right(tax.toString(),21))\n write(left(\"Total\", 10), \"$\", right(total.toString(),21))\nend\n", "language": "Unicon" }, { "code": "Public Sub currency_task()\n '4000000000000000 hamburgers at $5.50 each\n Dim number_of_hamburgers As Variant\n number_of_hamburgers = CDec(4E+15)\n Dim price_of_hamburgers As Currency\n price_of_hamburgers = 5.5\n '2 milkshakes at $2.86 each, and\n Dim number_of_milkshakes As Integer\n number_of_milkshakes = 2\n Dim price_of_milkshakes As Currency\n price_of_milkshakes = 2.86\n 'a tax rate of 7.65%.\n Dim tax_rate As Single\n tax_rate = 0.0765\n 'the total price before tax\n Dim total_price_before_tax As Variant\n total_price_before_tax = number_of_hamburgers * price_of_hamburgers\n total_price_before_tax = total_price_before_tax + number_of_milkshakes * price_of_milkshakes\n Debug.Print \"Total price before tax \"; Format(total_price_before_tax, \"Currency\")\n 'the tax\n Dim tax As Variant\n tax = total_price_before_tax * tax_rate\n Debug.Print \"Tax \"; Format(tax, \"Currency\")\n 'the total with tax\n Debug.Print \"Total with tax \"; Format(total_price_before_tax + tax, \"Currency\")\nEnd Sub\n", "language": "VBA" }, { "code": "import \"./big\" for BigRat\n\nvar hamburgers = BigRat.new(\"4000000000000000\")\nvar milkshakes = BigRat.two\nvar price1 = BigRat.fromFloat(5.5)\nvar price2 = BigRat.fromFloat(2.86)\nvar taxPc = BigRat.fromFloat(0.0765)\nvar totalPc = BigRat.fromFloat(1.0765)\nvar totalPreTax = hamburgers*price1 + milkshakes*price2\nvar totalTax = taxPc * totalPreTax\nvar totalAfterTax = totalPreTax + totalTax\nSystem.print(\"Total price before tax : %((totalPreTax).toDecimal(2))\")\nSystem.print(\"Tax : %((totalTax).toDecimal(2))\")\nSystem.print(\"Total price after tax : %((totalAfterTax).toDecimal(2))\")\n", "language": "Wren" }, { "code": "var priceList=Dictionary(\"hamburger\",550, \"milkshake\",286);\nvar taxRate=765; // percent*M\nconst M=0d10_000;\n\nfcn toBucks(n){ \"$%,d.%02d\".fmt(n.divr(100).xplode()) }\nfcn taxIt(n) { d,c:=n.divr(M).apply('*(taxRate)); d + (c+5000)/M; }\nfcn calcTab(items){ // (hamburger,15), (milkshake,100) ...\n items=vm.arglist;\n fmt:=\"%-10s %8s %18s %26s\";\n fmt.fmt(\"Item Price Quantity Extension\".split().xplode()).println();\n\n totalBeforeTax:=0;\n foreach item,n in (items.sort(fcn(a,b){ a[0]<b[0] })){\n price:=priceList[item]; t:=price*n;\n fmt.fmt(item,toBucks(price),n,toBucks(t)).println();\n totalBeforeTax+=t;\n }\n fmt.fmt(\"\",\"\",\"\",\"--------------------\").println();\n fmt.fmt(\"\",\"\",\"subtotal\",toBucks(totalBeforeTax)).println();\n\n tax:=taxIt(totalBeforeTax);\n fmt.fmt(\"\",\"\",\"Tax\",toBucks(tax)).println();\n\n fmt.fmt(\"\",\"\",\"\",\"--------------------\").println();\n fmt.fmt(\"\",\"\",\"Total\",toBucks(totalBeforeTax + tax)).println();\n}\n", "language": "Zkl" }, { "code": "calcTab(T(\"milkshake\",2),T(\"hamburger\",4000000000000000));\n", "language": "Zkl" } ]
Currency
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Curzon_numbers\n", "language": "00-META" }, { "code": "A '''Curzon number''' is defined to be a positive integer '''n''' for which '''2<sup>n</sup> + 1''' is evenly divisible by '''2 × n + 1'''.\n\n'''Generalized Curzon numbers''' are those where the positive integer '''n''', using a base integer '''k''', satisfy the condition that '''k<sup>n</sup> + 1''' is evenly divisible by '''k × n + 1'''.\n\n''Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.'' \n\nGeneralized Curzon numbers only exist for even base integers. \n\n\n;Task \n\n* Find and show the first '''50 Generalized Curzon numbers''' for even base integers from '''2''' through '''10'''.\n\n\n;Stretch\n\n* Find and show the '''one thousandth'''.\n\n\n;See also\n\n;* [https://www.numbersaplenty.com/set/Curzon_number Numbers Aplenty - Curzon numbers]\n;* [[oeis:A224486|OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1]] (Curzon numbers)\n\n''and even though it is not specifically mentioned that they are Curzon numbers:''\n\n;* [[oeis:A230076|OEIS:A230076 - (A007521(n)-1)/4]] (Generalized Curzon numbers with a base 4)\n<br>\n\n\n", "language": "00-TASK" }, { "code": "F is_curzon(n, k)\n V m = k * n + 1\n R pow(Int64(k), n, m) + 1 == m\n\nL(k) [2, 4, 6, 8, 10]\n V n = 1\n [Int] curzons\n L curzons.len < 1000\n I is_curzon(n, k)\n curzons.append(n)\n n++\n print(‘Curzon numbers with k = ’k‘:’)\n L(c) curzons[0.<50]\n V i = L.index\n print(f:‘{commatize(c):6}’, end' I (i + 1) % 25 == 0 {\"\\n\"} E ‘’)\n print(‘ Thousandth Curzon with k = ’k‘: ’curzons[999]\".\\n\")\n", "language": "11l" }, { "code": "BEGIN # find some generalised Curzon numbers - translation of the C++ sample #\n PROC modpow = ( LONG INT rqd base, rqd exp, mod )LONG INT:\n IF mod = 1\n THEN 0\n ELSE\n LONG INT result := 1;\n LONG INT base := rqd base MOD mod;\n LONG INT exp := rqd exp;\n WHILE exp > 0 DO\n IF ODD exp THEN\n result TIMESAB base MODAB mod\n FI;\n base TIMESAB base MODAB mod;\n exp OVERAB 2\n OD;\n result\n FI # modpow # ;\n\n PROC is curzon = ( LONG INT n, k )BOOL:\n BEGIN\n LONG INT m = k * n + 1;\n modpow( k, n, m ) + 1 = m\n END # is curon # ;\n\n FOR k FROM 2 BY 2 TO 10 DO\n print( ( \"Curzon numbers with base \", whole( k, 0 ), \":\", newline ) );\n INT count := 0, n := 0;\n WHILE n +:= 1;\n count < 50\n DO\n IF is curzon( n, k ) THEN\n print( ( whole( n, -4 )\n , IF ( count +:= 1 ) MOD 10 = 0 THEN newline ELSE \" \" FI\n )\n )\n FI\n OD;\n WHILE IF is curzon( n, k ) THEN count +:= 1 FI;\n count < 1000\n DO\n n +:= 1\n OD;\n print( ( \"1000th Curzon number with base \", whole( k, 0 ), \": \", whole( n, 0 ) ) );\n print( ( newline, newline ) )\n OD\nEND\n", "language": "ALGOL-68" }, { "code": "curzon?: function [n,base]->\n zero? (inc base^n) % inc base*n\n\nfirst50: function [b][\n result: new []\n i: 1\n while [50 > size result][\n if curzon? i b -> 'result ++ i\n i: i + 1\n ]\n return result\n]\n\noneThousandth: function [b][\n cnt: 0\n i: 1\n while [cnt < 1000][\n if curzon? i b -> cnt: cnt+1\n i: i + 1\n ]\n return dec i\n]\n\nloop select 2..10 => even? 'withBase [\n print [\"First 50 Curzon numbers with base\" withBase]\n loop split.every: 10 first50 withBase 'row [\n print map to [:string] row 'item -> pad item 4\n ]\n print [\"\\n1000th Curzon with base\" withBase \"=\" oneThousandth withBase]\n print \"\"\n]\n", "language": "Arturo" }, { "code": "#include <stdio.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <locale.h>\n\nuint64_t modPow(uint64_t base, uint64_t exp, uint64_t mod) {\n if (mod == 1) return 0;\n uint64_t result = 1;\n base %= mod;\n for (; exp > 0; exp >>= 1) {\n if ((exp & 1) == 1) result = (result * base) % mod;\n base = (base * base) % mod;\n }\n return result;\n}\n\nbool isCurzon(uint64_t n, uint64_t k) {\n const uint64_t r = k * n;\n return modPow(k, n, r+1) == r;\n}\n\nint main() {\n uint64_t k, n, count;\n setlocale(LC_NUMERIC, \"\");\n for (k = 2; k <= 10; k += 2) {\n printf(\"Curzon numbers with base %ld:\\n\", k);\n for (n = 1, count = 0; count < 50; ++n) {\n if (isCurzon(n, k)) {\n printf(\"%4ld \", n);\n if (++count % 10 == 0) printf(\"\\n\");\n }\n }\n for (;;) {\n if (isCurzon(n, k)) ++count;\n if (count == 1000) break;\n ++n;\n }\n printf(\"1,000th Curzon number with base %ld: %'ld\\n\\n\", k, n);\n }\n return 0;\n}\n", "language": "C" }, { "code": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nuint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {\n if (mod == 1)\n return 0;\n uint64_t result = 1;\n base %= mod;\n for (; exp > 0; exp >>= 1) {\n if ((exp & 1) == 1)\n result = (result * base) % mod;\n base = (base * base) % mod;\n }\n return result;\n}\n\nbool is_curzon(uint64_t n, uint64_t k) {\n const uint64_t r = k * n;\n return modpow(k, n, r + 1) == r;\n}\n\nint main() {\n for (uint64_t k = 2; k <= 10; k += 2) {\n std::cout << \"Curzon numbers with base \" << k << \":\\n\";\n uint64_t count = 0, n = 1;\n for (; count < 50; ++n) {\n if (is_curzon(n, k)) {\n std::cout << std::setw(4) << n\n << (++count % 10 == 0 ? '\\n' : ' ');\n }\n }\n for (;;) {\n if (is_curzon(n, k))\n ++count;\n if (count == 1000)\n break;\n ++n;\n }\n std::cout << \"1000th Curzon number with base \" << k << \": \" << n\n << \"\\n\\n\";\n }\n return 0;\n}\n", "language": "C++" }, { "code": "func pow_mod b power modulus .\n x = 1\n while power > 0\n if power mod 2 = 1\n x = x * b mod modulus\n .\n b = b * b mod modulus\n power = power div 2\n .\n return x\n.\nfor k = 2 step 2 to 10\n numfmt 0 0\n print \"First 50 Curzon numbers using a base of \" & k & \":\"\n numfmt 0 4\n n = 1\n count = 0\n repeat\n m = k * n + 1\n p = pow_mod k n m + 1\n if p = m\n count += 1\n if count <= 50\n write \" \" & n\n if count mod 9 = 0\n print \"\"\n .\n .\n .\n until count = 1000\n n += 1\n .\n print \"\" ; print \"One thousandth: \" & n\n print \"\"\n.\n", "language": "EasyLang" }, { "code": "USING: grouping interpolate io kernel make math math.functions\nprettyprint ranges sequences ;\n\n: curzon? ( k n -- ? ) [ ^ 1 + ] 2keep * 1 + divisor? ;\n\n: next ( k n -- k n' ) [ 2dup curzon? ] [ 1 + ] do until ;\n\n: curzon ( k -- seq )\n 1 [ 50 [ dup , next ] times ] { } make 2nip ;\n\n: curzon. ( k -- )\n dup [I Curzon numbers with base ${}:I] nl\n curzon 10 group simple-table. ;\n\n2 10 2 <range> [ curzon. nl ] each\n", "language": "Factor" }, { "code": "' limit: k * n +1 must be smaller then 2^32-1\n\nFunction pow_mod(b As ULongInt, power As ULongInt, modulus As ULongInt) As ULongInt\n ' returns b ^ power mod modulus\n Dim As ULongInt x = 1\n\n While power > 0\n If (power And 1) = 1 Then\n x = (x * b) Mod modulus\n End If\n b = (b * b) Mod modulus\n power = power Shr 1\n Wend\n\n Return x\n\nEnd Function\n\n\nFor k As ULongInt= 2 To 10 Step 2\n Print \"The first 50 Curzon numbers using a base of \"; k; \":\"\n Dim As ULongInt count, n = 1, p, m\n\n Do\n m = k * n +1\n p = pow_mod(k, n ,m) +1\n If p = m Then\n count += 1\n If count <= 50 Then\n Print Using \"#####\"; n;\n If (count Mod 10) = 0 Then Print\n ElseIf count = 1000 Then\n Print : Print \"One thousandth: \"; n\n Print : Print\n Exit Do\n End If\n End If\n n += 1\n Loop\n\nNext\nSleep\n", "language": "FreeBASIC" }, { "code": "#include once \"gmp.bi\"\n\nDim As Longint t = Len(__mpz_struct)\nDim As mpz_ptr pow = Allocate(t)\nDim As mpz_ptr z = Allocate(t)\nmpz_init(pow): mpz_init(z)\n\nFor k As Uinteger = 2 To 10 Step 2\n Print \"The first 50 Curzon numbers using a base of\"; k; \":\"\n Dim As Integer count = 0, n = 1\n mpz_set_si(pow,k)\n Do\n mpz_add_ui(z,pow,1)\n Dim As Integer d = k*n + 1\n If mpz_divisible_ui_p(z,d) Then\n count += 1\n If count <= 50 Then\n Print Using \"#####\"; n\n If (count Mod 25) = 0 Then Print\n Elseif count=1000 Then\n Print \"One thousandth: \"; n\n Print : Print\n Exit Do\n End If\n End If\n n += 1\n mpz_mul_si(pow,pow,k)\n Loop\nNext k\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n zero := big.NewInt(0)\n one := big.NewInt(1)\n for k := int64(2); k <= 10; k += 2 {\n bk := big.NewInt(k)\n fmt.Println(\"The first 50 Curzon numbers using a base of\", k, \":\")\n count := 0\n n := int64(1)\n pow := big.NewInt(k)\n z := new(big.Int)\n var curzon50 []int64\n for {\n z.Add(pow, one)\n d := k*n + 1\n bd := big.NewInt(d)\n if z.Rem(z, bd).Cmp(zero) == 0 {\n if count < 50 {\n curzon50 = append(curzon50, n)\n }\n count++\n if count == 50 {\n for i := 0; i < len(curzon50); i++ {\n fmt.Printf(\"%4d \", curzon50[i])\n if (i+1)%10 == 0 {\n fmt.Println()\n }\n }\n fmt.Print(\"\\nOne thousandth: \")\n }\n if count == 1000 {\n fmt.Println(n)\n break\n }\n }\n n++\n pow.Mul(pow, bk)\n }\n fmt.Println()\n }\n}\n", "language": "Go" }, { "code": "import Data.List.Split ( chunksOf )\n\nisGeneralizedCurzon :: Integer -> Integer -> Bool\nisGeneralizedCurzon base n = mod ( base ^ n + 1 ) ( base * n + 1 ) == 0\n\nsolution :: Integer -> [Integer]\nsolution base = take 50 $ filter (\\i -> isGeneralizedCurzon base i ) [1..]\n\nprintChunk :: [Integer] -> String\nprintChunk chunk = foldl1 (++) $ map (\\i -> (take ( 4 - (length $ show i) )\n $ repeat ' ' ) ++ show i ++ \" \") chunk\n\nprettyPrint :: [Integer] -> [String]\nprettyPrint list = map printChunk $ chunksOf 10 list\n\noneThousandth :: Integer -> Integer\noneThousandth base = last $ take 950 $ filter (\\i -> isGeneralizedCurzon base i )\n [(last $ solution base) + 1 ..]\n\nprintBlock :: Integer -> [String]\nprintBlock base = [\"first 50 Curzon numbers using a base of \" ++ show base ++ \" :\"]\n ++ (prettyPrint $ solution base) ++ [\"one thousandth at base \" ++ show base ++\n \": \" ++ (show $ oneThousandth base)] ++ [take 50 $ repeat '-']\n\nmain :: IO ( )\nmain = do\n blocks <- return $ concat $ map (\\i -> printBlock i ) [2 , 4 , 6 , 8 , 10]\n mapM_ putStrLn blocks\n", "language": "Haskell" }, { "code": "isCurzon =: 2&$: : (0 = * |&:>: ^)\n", "language": "J" }, { "code": "modpow =: {{ m&|@^ }}\nisCurzon =: {{\n z =: >: x * y\n z = >: x z modpow y\n}}\n", "language": "J" }, { "code": "generateCurzons =: {{\n found =. i. 0x\n current =. 0x\n while. 1000 > # found do.\n if. y isCurzon current do. found =. found , current end.\n current =. >: current\n end.\n y ; (5 10 $ found) ; {: found\n}}\n\n('Base';'First 50';'1000th') , generateCurzons\"0 +:>:i.5\n", "language": "J" }, { "code": "public final class CurzonNumbers {\n\n\tpublic static void main(String[] aArgs) {\n\t\tfor ( int k = 2; k <= 10; k += 2 ) {\n\t System.out.println(\"Generalised Curzon numbers with base \" + k + \":\");\n\t int n = 1;\n\t int count = 0;\n\t while ( count < 50 ) {\n\t if ( isGeneralisedCurzonNumber(k, n) ) {\n\t System.out.print(String.format(\"%4d%s\", n, ( ++count % 10 == 0 ? \"\\n\" : \" \" )));\n\t }\n\t n += 1;\n\t }\n\t\n\t while ( count < 1_000 ) {\n\t \tif ( isGeneralisedCurzonNumber(k, n) ) {\n\t \t\tcount += 1;\n\t \t}\n\t \tn += 1;\n\t }\t\n\t System.out.println(\"1,000th Generalised Curzon number with base \" + k + \": \" + ( n - 1 ));\n\t System.out.println();\n\t }\n\t}\n\t\n\tprivate static boolean isGeneralisedCurzonNumber(int aK, int aN) {\n\t final long r = aK * aN;\n\t return modulusPower(aK, aN, r + 1) == r;\n\t}\n\t\n\tprivate static long modulusPower(long aBase, long aExponent, long aModulus) {\n\t if ( aModulus == 1 ) {\n\t return 0;\n\t }\t\n\t\n\t aBase %= aModulus;\n\t long result = 1;\n\t while ( aExponent > 0 ) {\n\t if ( ( aExponent & 1 ) == 1 ) {\n\t result = ( result * aBase ) % aModulus;\n\t }\n\t aBase = ( aBase * aBase ) % aModulus;\n\t aExponent >>= 1;\n\t }\n\t return result;\n\t}\n\n}\n", "language": "Java" }, { "code": "# To take advantage of gojq's arbitrary-precision integer arithmetic:\ndef power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);\n\ndef lpad($len): tostring | ($len - length) as $l | (\" \" * $l)[:$l] + .;\n\n# gojq does not currently define _nwise\ndef _nwise($n):\n def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;\n n;\n\ndef printRows($m): _nwise($m) | map(lpad(5)) | join(\"\");\n", "language": "Jq" }, { "code": "def isCurzon($n; $k):\n ($k | power($n) + 1) % ($k * $n + 1) == 0;\n\n# Emit a stream of Curzon numbers base $k\ndef curzons($k):\n range(0; infinite) | select(isCurzon(.; $k));\n\n# Print the first 50 and the $n-th Curzon numbers\n# for k in range(klow; khigh+1; 2)\ndef printcurzons(klow; khigh; $n):\n range(klow; khigh+1; 2) as $k\n | [limit($n; curzons($k))] as $curzons\n | \"Curzon numbers with k = \\($k):\",\n ($curzons[:50] | printRows(25) ),\n \" \\($n)-th Curzon with k = \\($k): \\($curzons[$n - 1])\",\n \"\";\n\nprintcurzons(2; 10; 1000)\n", "language": "Jq" }, { "code": "isCurzon(n, k) = (BigInt(k)^n + 1) % (k * n + 1) == 0\n\nfunction printcurzons(klow, khigh)\n for k in filter(iseven, klow:khigh)\n n, curzons = 0, Int[]\n while length(curzons) < 1000\n isCurzon(n, k) && push!(curzons, n)\n n += 1\n end\n println(\"Curzon numbers with k = $k:\")\n foreach(p -> print(lpad(p[2], 5), p[1] % 25 == 0 ? \"\\n\" : \"\"), enumerate(curzons[1:50]))\n println(\" Thousandth Curzon with k = $k: \", curzons[1000])\n end\nend\n\nprintcurzons(2, 10)\n", "language": "Julia" }, { "code": "{def is_curzon\n {lambda {:n :k}\n {= {BI.% {BI.+ {BI.** :k :n} 1}\n {BI.+ {BI.* :k :n} 1} } 0}}}\n-> is_curzon\n\n{def curzon\n {lambda {:length :base}\n {S.replace \\s by space in\n {S.brmap {{lambda {:length :base :count :i}\n {if {< {A.get 0 :count} :length}\n then {if {is_curzon :i :base}\n then {{lambda {:a :i} :i}\n {A.set! 0 {+ {A.get 0 :count} 1} :count} :i}\n else}\n else _break_}\n } :length :base {A.new 0}}\n 1 100000 1 }}}}\n-> curzon\n\n{S.map {lambda {:i}\n {div {b First 50 Curzon numbers using a base of :i:}\n {div {curzon 50 :i}}}}\n {S.serie 2 10 2}}\n->\nFirst 50 Curzon numbers using a base of 2:\n1 2 5 6 9 14 18 21 26 29 30 33 41 50 53 54 65 69 74 78 81 86 89 90 98 105 113 114 125 134 138 141 146 153 158 165 173 174 186 189 194 198 209 210 221 230 233 245 249 254\n\nFirst 50 Curzon numbers using a base of 4:\n1 3 7 9 13 15 25 27 37 39 43 45 49 57 67 69 73 79 87 93 97 99 105 115 127 135 139 153 163 165 169 175 177 183 189 193 199 205 207 213 219 235 249 253 255 265 267 273 277 279\n\nFirst 50 Curzon numbers using a base of 6:\n1 6 30 58 70 73 90 101 105 121 125 146 153 166 170 181 182 185 210 233 241 242 266 282 290 322 373 381 385 390 397 441 445 446 450 453 530 557 562 585 593 601 602 605 606 621 646 653 670 685\n\nFirst 50 Curzon numbers using a base of 8:\n1 14 35 44 72 74 77 129 131 137 144 149 150 185 200 219 236 266 284 285 299 309 336 357 381 386 390 392 402 414 420 441 455 459 470 479 500 519 527 536 557 582 600 602 617 639 654 674 696 735\n\nFirst 50 Curzon numbers using a base of 10:\n1 9 10 25 106 145 190 193 238 253 306 318 349 385 402 462 486 526 610 649 658 678 733 762 810 990 994 1033 1077 1125 1126 1141 1149 1230 1405 1422 1441 1485 1509 1510 1513 1606 1614 1630 1665 1681 1690 1702 1785 1837\n\n{S.last {curzon 1000 6}} -> 20717 in 272193ms = 4.53655 minutes\n", "language": "Lambdatalk" }, { "code": "ClearAll[CurzonNumberQ]\nCurzonNumberQ[b_Integer][n_Integer]:=PowerMod[b,n,b n+1]==b n\nval=Select[Range[100000],CurzonNumberQ[2]];\nTake[val,50]\nval[[1000]]\n\nval=Select[Range[100000],CurzonNumberQ[4]];\nTake[val,50]\nval[[1000]]\n\nval=Select[Range[100000],CurzonNumberQ[6]];\nTake[val,50]\nval[[1000]]\n\nval=Select[Range[100000],CurzonNumberQ[8]];\nTake[val,50]\nval[[1000]]\n\nval=Select[Range[100000],CurzonNumberQ[10]];\nTake[val,50]\nval[[1000]]\n", "language": "Mathematica" }, { "code": "/* Predicate function that checks wether a positive integer is generalized k-Curzon number or not */\ng_curzonp(n,k):=if mod((k^n)+1,k*n+1)=0 then true$\n\n/* Function that returns a list of the first len generalized k-Curzon numbers */\ng_curzon_count(len,k):=block(\n [i:1,count:0,result:[]],\n while count<len do (if g_curzonp(i,k) then (result:endcons(i,result),count:count+1),i:i+1),\n result)$\n\n/* Test cases */\ng_curzon_count(50,2);\ng_curzon_count(50,4);\ng_curzon_count(50,6);\ng_curzon_count(50,8);\ng_curzon_count(50,10);\n", "language": "Maxima" }, { "code": "import std/strformat\n\nfunc pow(a, n: Natural; m: Positive): Natural =\n var a = a mod m\n var n = n\n if a > 0:\n result = 1\n while n > 0:\n if (n and 1) != 0:\n result = (result * a) mod m\n n = n shr 1\n a = (a * a) mod m\n\niterator curzonNumbers(k: Positive): Natural =\n assert (k and 1) == 0, \"base must be even.\"\n var n = 1\n while true:\n let m = k * n + 1\n if pow(k, n, m) + 1 == m:\n yield n\n inc n\n\n### Task ###\nfor k in countup(2, 10, 2):\n echo &\"Curzon numbers for k = {k}:\"\n var count = 0\n for n in curzonNumbers(k):\n inc count\n stdout.write &\"{n:>4}\"\n stdout.write if count mod 10 == 0: '\\n' else: ' '\n if count == 50: break\n echo()\n\n### Stretch task ###\nfor k in countup(2, 10, 2):\n var count = 0\n for n in curzonNumbers(k):\n inc count\n if count == 1000:\n echo &\"1000th Curzon number for k = {k:>2}: {n:>5}\"\n break\n", "language": "Nim" }, { "code": "let modpow m =\n let rec loop p b e =\n if e land 1 = 0\n then if e = 0 then p else loop p (b * b mod m) (e lsr 1)\n else loop (p * b mod m) (b * b mod m) (e lsr 1)\n in loop 1\n\nlet is_curzon k n =\n let r = k * n in r = modpow (succ r) k n\n\nlet () =\n List.iter (fun x ->\n Seq.(ints 0 |> filter (is_curzon x) |> take 50 |> map string_of_int)\n |> List.of_seq |> String.concat \" \" |> Printf.printf \"base %u:\\n%s\\n\" x)\n [2; 4; 6; 8; 10]\n\nlet () =\n List.iter (fun x ->\n Seq.(ints 0 |> filter (is_curzon x) |> drop 999 |> take 1\n |> iter (Printf.printf \"base %u (1000th): %u\\n\" x)))\n [2; 4; 6; 8; 10]\n", "language": "OCaml" }, { "code": "package curzon_numbers\n/* imports */\nimport \"core:c/libc\"\nimport \"core:fmt\"\n/* main block */\nmain :: proc() {\n\tfor k: int = 2; k <= 10; k += 2 {\n\t\tfmt.println(\"\\nCurzon numbers with base \", k)\n\t\tcount := 0\n\t\tn: int = 1\n\t\tfor ; count < 50; n += 1 {\n\t\t\tif is_curzon(n, k) {\n\t\t\t\tcount += 1\n\t\t\t\tlibc.printf(\"%*d \", 4, n)\n\t\t\t\tif (count) % 10 == 0 {\n\t\t\t\t\tfmt.printf(\"\\n\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor {\n\t\t\tif is_curzon(n, k) {\n\t\t\t\tcount += 1}\n\t\t\tif count == 1000 {\n\t\t\t\tbreak}\n\t\t\tn += 1\n\t\t}\n\t\tlibc.printf(\"1000th Curzon number with base %d: %d \\n\", k, n)\n\t}\n}\n/* definitions */\nmodpow :: proc(base, exp, mod: int) -> int {\n\tif mod == 1 {\n\t\treturn 0}\n\tresult: int = 1\n\tbase := base\n\texp := exp\n\tbase %= mod\n\tfor ; exp > 0; exp >>= 1 {\n\t\tif ((exp & 1) == 1) {\n\t\t\tresult = (result * base) % mod}\n\t\tbase = (base * base) % mod\n\t}\n\treturn result\n}\n\nis_curzon :: proc(n: int, k: int) -> bool {\n\tr := k * n //const?\n\treturn modpow(k, n, r + 1) == r\n}\n", "language": "Odin" }, { "code": "/* Define the CurzonNumberQ function for base b */\npowermod(a,k,n)=lift(Mod(a,n)^k)\nCurzonNumberQ(b, n) = (powermod(b,n,b*n+1)== b*n);\n\n/* Define a function to find Curzon numbers within a range for base b */\nFindCurzonNumbers(b, maxrange) = {\n local(val, res, i);\n val = vector(maxrange);\n res = [];\n for(i = 1, maxrange,\n if(CurzonNumberQ(b, i), res = concat(res, i));\n );\n return(Vec(res));\n}\n\n/* Select and display the first 50 Curzon numbers and the 1000th for base 2 */\nval = FindCurzonNumbers(2, 100000);\nprint(vector(50, i, val[i])); /* First 50 */\nprint(val[1000]); /* 1000th Curzon number */\n\n/* Select and display for base 4 */\nval = FindCurzonNumbers(4, 100000);\nprint(vector(50, i, val[i])); /* First 50 */\nprint(val[1000]); /* 1000th Curzon number */\n\n/* Select and display for base 6 */\nval = FindCurzonNumbers(6, 100000);\nprint(vector(50, i, val[i])); /* First 50 */\nprint(val[1000]); /* 1000th Curzon number */\n\n/* Select and display for base 8 */\nval = FindCurzonNumbers(8, 100000);\nprint(vector(50, i, val[i])); /* First 50 */\nprint(val[1000]); /* 1000th Curzon number */\n\n/* Select and display for base 10 */\nval = FindCurzonNumbers(10, 100000);\nprint(vector(50, i, val[i])); /* First 50 */\nprint(val[1000]); /* 1000th Curzon number */\n", "language": "PARI-GP" }, { "code": "program CurzonNumbers;\nuses SysUtils;\nconst\n MAX_CURZON_MEG = 100;\n RC_LINE_LENGTH = 66;\n\nprocedure ListCurzonNumbers( base : integer);\nvar\n k, n, m, x, testBit, maxCurzon : uint64;\n nrHits : integer;\n lineOut : string;\nbegin\n maxCurzon := 1000000*MAX_CURZON_MEG;\n k := uint64( base);\n nrHits := 0;\n n := 0;\n WriteLn;\n if Odd( base) then WriteLn( SysUtils.Format(\n 'Curzon numbers with base %d up to %d million', [base, MAX_CURZON_MEG]))\n else WriteLn( SysUtils.Format(\n 'First 50 Curzon numbers with base %d', [base]));\n lineOut := '';\n repeat\n inc(n); // possible (generalized) Curzon number\n m := k*n + 1; // modulus\n testBit := 1;\n repeat testBit := testBit shl 1 until testBit > n;\n testBit := testBit shr 2;\n // Calculate k^n modulo m\n x := k;\n while testBit > 0 do begin\n x := (x*x) mod m;\n if (testBit and n) <> 0 then x := (x*k) mod m;\n testBit := testBit shr 1;\n end;\n // n is a Curzon number to base k iff k^n + 1 is divisible by m\n if (x + 1) mod m = 0 then begin\n inc( nrHits);\n if Odd( base) then\n lineOut := lineOut + ' ' + SysUtils.IntToStr( n)\n else if (nrHits <= 50) then\n lineOut := lineOut + SysUtils.Format( '%5d', [n]);\n if Length( lineOut) >= RC_LINE_LENGTH then begin\n WriteLn( lineOut); lineOut := '';\n end\n else if (nrHits = 1000) then begin\n if lineOut <> '' then begin\n WriteLn( lineOut); lineOut := '';\n end;\n WriteLn( SysUtils.Format( '1000th = %d', [n]));\n end;\n end;\n until (n = maxCurzon) or (nrHits = 1000);\n if lineOut <> '' then WriteLn( lineOut);\nend;\n\nbegin\n ListCurzonNumbers( 2);\n ListCurzonNumbers( 4);\n ListCurzonNumbers( 6);\n ListCurzonNumbers( 8);\n ListCurzonNumbers(10);\n ListCurzonNumbers( 3);\n ListCurzonNumbers( 5);\n ListCurzonNumbers( 7);\n ListCurzonNumbers( 9);\n ListCurzonNumbers(11);\nend.\n", "language": "Pascal" }, { "code": "use strict;\nuse warnings;\nuse ntheory 'powmod';\n\nsub curzon {\n my($base,$cnt) = @_;\n my($n,@C) = 0;\n while (++$n) {\n my $r = $base * $n;\n push @C, $n if powmod($base, $n, $r + 1) == $r;\n return @C if $cnt == @C;\n }\n}\n\nmy $upto = 50;\nfor my $k (<2 4 6 8 10>) {\n my @C = curzon $k, 1000;\n print \"First $upto Curzon numbers using a base of $k:\\n\" .\n (sprintf \"@{['%5d' x $upto]}\", @C[0..$upto-1]) =~ s/.{100}/$&\\n/gr;\n printf \"%50s\\n\\n\", \"Thousandth: $C[-1]\"\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">mpfr</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #004080;\">mpz</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">pow</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_inits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"The first 50 Curzon numbers using a base of %d:\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #7060A8;\">mpz_set_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pow</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">mpz_add_ui</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">pow</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">mpz_divisible_ui_p</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">50</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%5d%s\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">25</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1000</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"One thousandth: %d\\n\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #7060A8;\">mpz_mul_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pow</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">pow</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "def is_Curzon(n, k):\n r = k * n\n return pow(k, n, r + 1) == r\n\nfor k in [2, 4, 6, 8, 10]:\n n, curzons = 1, []\n while len(curzons) < 1000:\n if is_Curzon(n, k):\n curzons.append(n)\n n += 1\n print(f'Curzon numbers with k = {k}:')\n for i, c in enumerate(curzons[:50]):\n print(f'{c: 5,}', end='\\n' if (i + 1) % 25 == 0 else '')\n print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\\n')\n", "language": "Python" }, { "code": " [ number$\n space 4 of swap join\n -5 split nip echo$ ] is rjust ( n --> )\n\n [ 5 times\n [ 10 times\n [ behead rjust ]\n cr ]\n drop ] is display ( [ --> )\n\n [ temp take\n over join\n temp put ] is dax ( [ --> )\n\n [ 2dup ** 1+\n unrot * 1+ mod 0 = ] is curzon ( n n --> b )\n\n 5 times\n [ i^ 1+ 2 *\n say \"Curzon numbers base \"\n dup echo cr\n 1\n [] temp put\n [ 2dup curzon if dax\n temp share\n size 1000 < while\n 1+ again ]\n 2drop\n temp take\n 50 split swap display\n say \" ... \"\n -1 peek echo cr cr ]\n", "language": "Quackery" }, { "code": "sub curzon ($base) { lazy (1..∞).hyper.map: { $_ if (exp($_, $base) + 1) %% ($base × $_ + 1) } };\n\nfor <2 4 6 8 10> {\n my $curzon = .&curzon;\n say \"\\nFirst 50 Curzon numbers using a base of $_:\\n\" ~\n $curzon[^50].batch(10)».fmt(\"%4s\").join(\"\\n\") ~\n \"\\nOne thousandth: \" ~ $curzon[999]\n}\n", "language": "Raku" }, { "code": "def curzons(k)\n Enumerator.new do |y|\n (1..).each do |n|\n r = k * n\n y << n if k.pow(n, r + 1) == r\n end\n end\nend\n\n[2,4,6,8,10].each do |base|\n puts \"Curzon numbers with k = #{base}:\"\n puts curzons(base).take(50).join(\", \")\n puts \"Thousandth Curzon with k = #{base}: #{curzons(base).find.each.with_index(1){|_,i| i == 1000} }\",\"\"\nend\n", "language": "Ruby" }, { "code": "fn modpow(mut base: usize, mut exp: usize, n: usize) -> usize {\n if n == 1 {\n return 0;\n }\n let mut result = 1;\n base %= n;\n while exp > 0 {\n if (exp & 1) == 1 {\n result = (result * base) % n;\n }\n base = (base * base) % n;\n exp >>= 1;\n }\n result\n}\n\nfn is_curzon(n: usize, k: usize) -> bool {\n let m = k * n + 1;\n modpow(k, n, m) + 1 == m\n\n}\n\nfn main() {\n for k in (2..=10).step_by(2) {\n println!(\"Curzon numbers with base {k}:\");\n let mut count = 0;\n let mut n = 1;\n while count < 50 {\n if is_curzon(n, k) {\n count += 1;\n print!(\"{:4}{}\", n, if count % 10 == 0 { \"\\n\" } else { \" \" });\n }\n n += 1;\n }\n loop {\n if is_curzon(n, k) {\n count += 1;\n if count == 1000 {\n break;\n }\n }\n n += 1;\n }\n println!(\"1000th Curzon number with base {k}: {n}\\n\");\n }\n}\n", "language": "Rust" }, { "code": "func is_curzon(n, k) {\n powmod(k, n, k*n + 1).is_congruent(-1, k*n + 1) && (n > 0)\n}\n\nfor k in (2 .. 10 `by` 2) {\n say \"\\nFirst 50 Curzon numbers using a base of #{k}:\"\n say 50.by {|n| is_curzon(n, k) }.join(' ')\n say (\"1000th term: \", 1000.th {|n| is_curzon(n,k) })\n}\n", "language": "Sidef" }, { "code": "import math.big\n\nfn main() {\n zero := big.zero_int\n one := big.one_int\n for k := i64(2); k <= 10; k += 2 {\n bk := big.integer_from_i64(k)\n println(\"The first 50 Curzon numbers using a base of $k:\")\n mut count := 0\n mut n := i64(1)\n mut pow := big.integer_from_i64(k)\n mut curzon50 := []i64{}\n for {\n z := pow + one\n d := k*n + 1\n bd := big.integer_from_i64(d)\n if z%bd == zero {\n if count < 50 {\n curzon50 << n\n }\n count++\n if count == 50 {\n for i in 0..curzon50.len {\n print(\"${curzon50[i]:4} \")\n if (i+1)%10 == 0 {\n println('')\n }\n }\n print(\"\\nOne thousandth: \")\n }\n if count == 1000 {\n println(n)\n break\n }\n }\n n++\n pow *= bk\n }\n println('')\n }\n}\n", "language": "V-(Vlang)" }, { "code": "/* Curzon_numbers.wren */\n\nimport \"./gmp\" for Mpz\nimport \"./fmt\" for Fmt\n\nfor (k in [2, 4, 6, 8, 10]) {\n System.print(\"The first 50 Curzon numbers using a base of %(k):\")\n var count = 0\n var n = 1\n var pow = Mpz.from(k)\n var curzon50 = []\n while (true) {\n var z = pow + Mpz.one\n var d = k*n + 1\n if (z.isDivisibleUi(d)) {\n if (count < 50) curzon50.add(n)\n count = count + 1\n if (count == 50) {\n Fmt.tprint(\"$4d\", curzon50, 10)\n System.write(\"\\nOne thousandth: \")\n }\n if (count == 1000) {\n Fmt.print(\"$,d\", n)\n break\n }\n }\n n = n + 1\n pow.mul(k)\n }\n System.print()\n}\n", "language": "Wren" }, { "code": "import \"./math\" for Int\nimport \"./fmt\" for Fmt\n\nvar isCurzon = Fn.new { |n, k|\n var r = k * n\n return Int.modPow(k, n, r+1) == r\n}\n\nvar k = 2\nwhile (k <= 10) {\n System.print(\"Curzon numbers with base %(k):\")\n var n = 1\n var count = 0\n while (count < 50) {\n if (isCurzon.call(n, k)) {\n Fmt.write(\"$4d \", n)\n count = count + 1\n if (count % 10 == 0) System.print()\n }\n n = n + 1\n }\n while (true) {\n if (isCurzon.call(n, k)) count = count + 1\n if (count == 1000) break\n n = n + 1\n }\n Fmt.print(\"1,000th Curzon number with base $d: $,d\\n\", k, n)\n k = k + 2\n}\n", "language": "Wren" }, { "code": "func ModPow(Base, Exp, Mod);\nint Base, Exp, Mod, Result;\n[if Mod = 1 then return 0;\nResult:= 1;\nBase:= rem(Base/Mod);\nwhile Exp > 0 do\n [if (Exp&1) = 1 then Result:= rem((Result*Base)/Mod);\n Base:= rem((Base*Base) / Mod);\n Exp:= Exp >> 1;\n ];\nreturn Result;\n];\n\nfunc IsCurzon(N, K);\nint N, K, R;\n[R:= K * N;\nreturn ModPow(K, N, R+1) = R;\n];\n\nint K, N, Count;\n[K:= 2;\nFormat(5, 0);\nwhile K <= 10 do\n [Text(0, \"Curzon numbers with base \"); IntOut(0, K); CrLf(0);\n N:= 1; Count:= 0;\n while Count < 50 do\n [if IsCurzon(N, K) then\n [RlOut(0, float(N));\n Count:= Count+1;\n if rem(Count/10) = 0 then CrLf(0);\n ];\n N:= N+1;\n ];\n K:= K+2;\n ];\n]\n", "language": "XPL0" } ]
Curzon-numbers
[ { "code": "---\nfrom: http://rosettacode.org/wiki/CUSIP\nnote: Checksums\n", "language": "00-META" }, { "code": "<br/>\n\nA &nbsp; '''CUSIP''' &nbsp; is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.\n\n\n;Task:\nEnsure the last digit &nbsp; (i.e., the &nbsp; ''check digit'') &nbsp; of the '''CUSIP''' code (the 1<sup>st</sup> column) is correct, against the following:\n* &nbsp; 037833100 &nbsp; &nbsp; &nbsp; Apple Incorporated \n* &nbsp; 17275R102 &nbsp; &nbsp; &nbsp; Cisco Systems \n* &nbsp; 38259P508 &nbsp; &nbsp; &nbsp; Google Incorporated \n* &nbsp; 594918104 &nbsp; &nbsp; &nbsp; Microsoft Corporation \n* &nbsp; 68389X106 &nbsp; &nbsp; &nbsp; Oracle Corporation &nbsp; (''incorrect'')\n* &nbsp; 68389X105 &nbsp; &nbsp; &nbsp; Oracle Corporation \n\n\n;Example pseudo-code below.\n<syntaxhighlight lang=text>algorithm Cusip-Check-Digit(cusip) is\n Input: an 8-character CUSIP\n\n sum := 0\n for 1 ≤ i ≤ 8 do\n c := the ith character of cusip\n if c is a digit then\n v := numeric value of the digit c\n else if c is a letter then\n p := ordinal position of c in the alphabet (A=1, B=2...)\n v := p + 9\n else if c = \"*\" then\n v := 36\n else if c = \"@\" then\n v := 37\n else if' c = \"#\" then\n v := 38\n end if\n if i is even then\n v := v × 2\n end if\n\n sum := sum + int ( v div 10 ) + v mod 10\n repeat\n \n return (10 - (sum mod 10)) mod 10\nend function</syntaxhighlight>\n\n;See related tasks: \n* [[SEDOLs|SEDOL]]\n* [[Validate_International_Securities_Identification_Number|ISIN]]\n<br>\n\n", "language": "00-TASK" }, { "code": "F cusip_check(=cusip)\n I cusip.len != 9\n X.throw ValueError(‘CUSIP must be 9 characters’)\n\n cusip = cusip.uppercase()\n V total = 0\n L(i) 8\n V v = 0\n V c = cusip[i]\n I c.is_digit()\n v = Int(c)\n E I c.is_alpha()\n V p = c.code - ‘A’.code + 1\n v = p + 9\n E I c == ‘*’\n v = 36\n E I c == ‘@’\n v = 37\n E I c == ‘#’\n v = 38\n\n I i % 2 != 0\n v *= 2\n\n total += v I/ 10 + v % 10\n V check = (10 - (total % 10)) % 10\n R String(check) == cusip.last\n\nV codes = [‘037833100’,\n ‘17275R102’,\n ‘38259P508’,\n ‘594918104’,\n ‘68389X106’,\n ‘68389X105’]\nL(code) codes\n print(code‘: ’(I cusip_check(code) {‘valid’} E ‘invalid’))\n", "language": "11l" }, { "code": "* CUSIP 07/06/2018\nCUSIP CSECT\n USING CUSIP,R13 base register\n B 72(R15) skip savearea\n DC 17F'0' savearea\n SAVE (14,12) save previous context\n ST R13,4(R15) link backward\n ST R15,8(R13) link forward\n LR R13,R15 set addressability\n LA R6,1 i=1\n DO WHILE=(C,R6,LE,=F'6') do i=1 to 6\n LR R1,R6 i\n MH R1,=H'9' *9\n LA R4,T-9(R1) @t(i)\n MVC X,0(R4) x=t(i)\n SR R10,R10 w=0\n LA R7,1 j=1\n DO WHILE=(C,R7,LE,=F'8') do j=1 to 8\n LA R14,X-1 x\n AR R14,R7 j\n MVC Y(1),0(R14) y=substr(x,j,1)\n LA R9,L'XX z=length(xx)\n LA R8,1 k=1\n DO WHILE=(C,R8,LE,=A(L'XX)) do k=1 to length(xx)\n LA R4,XX-1 xx\n AR R4,R8 k\n MVC C(1),0(R4) c=substr(xx,k,1)\n IF CLC,Y(1),EQ,C THEN if y=c then\n LR R9,R8 k\n BCTR R9,0 z=k-1\n ENDIF , endif\n LA R8,1(R8) k++\n ENDDO , enddo k\n LR R4,R7 j\n LA R1,2 2\n SRDA R4,32 ~\n DR R4,R1 j/2=0\n IF LTR,R4,Z,R4 THEN if j//2=0 then\n AR R9,R9 z=z+z\n ENDIF , endif\n LR R4,R9 z\n LA R1,10 10\n SRDA R4,32 ~\n DR R4,R1 r4=z//10 ; r5=z/10\n AR R10,R5 w+z/10\n AR R10,R4 w=w+z/10+z//10\n LA R7,1(R7) j++\n ENDDO , enddo j\n LR R4,R10 w\n LA R1,10 10\n SRDA R4,32 ~\n DR R4,R1 w/10\n LA R2,10 10\n SR R2,R4 10-w//10\n SRDA R2,32 ~\n DR R2,R1 /10\n STC R2,U u=(10-w//10)//10\n OI U,X'F0' bin to char\n IF CLC,U,EQ,X+8 THEN if u=substr(x,9,1) then\n MVC OK,=CL3' ' ok=' '\n ELSE , else\n MVC OK,=C'n''t' ok='n''t'\n ENDIF , endif\n MVC PG+6(9),X output x\n MVC PG+18(3),OK output ok\n XPRNT PG,L'PG print\n LA R6,1(R6) i++\n ENDDO , enddo i\n L R13,4(0,R13) restore previous savearea pointer\n RETURN (14,12),RC=0 restore registers from calling sav\nXX DC CL39'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#'\nU DS CL1\nY DS CL1\nC DS CL1\nT DC CL9'037833100',CL9'17275R102',CL9'38259P508'\n DC CL9'594918104',CL9'68389X106',CL9'68389X105'\nX DS CL9\nOK DS CL3\nPG DC CL80'CUSIP ......... is... valid'\n YREGS\n END CUSIP\n", "language": "360-Assembly" }, { "code": "INCLUDE \"D2:CHARTEST.ACT\" ;from the Action! Tool Kit\n\nBYTE FUNC Verify(CHAR ARRAY code)\n BYTE i,c,v\n CARD sum\n\n IF code(0)#9 THEN\n RETURN (0)\n ELSEIF IsDigit(code(1))=0 THEN\n RETURN (0)\n FI\n\n sum=0\n FOR i=2 TO code(0)\n DO\n c=code(i)\n IF IsDigit(c) THEN\n v=c-'0\n ELSEIF IsAlpha(c) THEN\n v=ToUpper(c)-'A+10\n ELSEIF c='* THEN\n v=36\n ELSEIF c='@ THEN\n v=37\n ELSEIF c='# THEN\n v=38\n ELSE\n RETURN (0)\n FI\n\n IF (i&1)=0 THEN\n v==*2\n FI\n\n sum==+v/10+v MOD 10\n OD\n\n v=(10-(sum MOD 10)) MOD 10\n IF v#code(1)-'0 THEN\n RETURN (0)\n FI\nRETURN (1)\n\nPROC Test(CHAR ARRAY code)\n Print(code)\n IF Verify(code) THEN\n PrintE(\" is valid\")\n ELSE\n PrintE(\" is invalid\")\n FI\nRETURN\n\nPROC Main()\n Put(125) PutE() ;clear the screen\n Test(\"037833100\")\n Test(\"17275R102\")\n Test(\"38259P508\")\n Test(\"594918104\")\n Test(\"68389X106\")\n Test(\"68389X105\")\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO;\n\nprocedure Cusip_Test is\n use Ada.Text_IO;\n\n subtype Cusip is String (1 .. 9);\n\n function Check_Cusip (Code : Cusip) return Boolean is\n Sum : Integer := 0;\n V : Integer;\n\n begin\n for I in Code'First .. Code'Last - 1 loop\n case Code (I) is\n when '0' .. '9' =>\n V := Character'Pos (Code (I)) - Character'Pos ('0');\n when 'A' .. 'Z' =>\n V := Character'Pos (Code (I)) - Character'Pos ('A') + 10;\n when '*' => V := 36;\n when '@' => V := 37;\n when '#' => V := 38;\n when others => return False;\n end case;\n\n if I mod 2 = 0 then\n V := V * 2;\n end if;\n\n Sum := Sum + V / 10 + (V mod 10);\n end loop;\n\n return (10 - (Sum mod 10)) mod 10 =\n Character'Pos (Code (Code'Last)) - Character'Pos ('0');\n end Check_Cusip;\n\n type Cusip_Array is array (Natural range <>) of Cusip;\n\n Test_Array : Cusip_Array :=\n (\"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\");\nbegin\n for I in Test_Array'Range loop\n Put (Test_Array (I) & \": \");\n if Check_Cusip (Test_Array (I)) then\n Put_Line (\"valid\");\n else\n Put_Line (\"not valid\");\n end if;\n end loop;\nend Cusip_Test;\n", "language": "Ada" }, { "code": "BEGIN\n # returns TRUE if cusip is a valid CUSIP code #\n OP ISCUSIP = ( STRING cusip )BOOL:\n IF ( UPB cusip - LWB cusip ) /= 8\n THEN\n # code is wrong length #\n FALSE\n ELSE\n # string is 9 characters long - check it is valid #\n STRING cusip digits = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#\"[ AT 0 ];\n INT check digit := 0;\n IF NOT char in string( cusip[ UPB cusip ], check digit, cusip digits )\n THEN\n # invalid check digit #\n FALSE\n ELSE\n # OK so far compare the calculated check sum to the supplied one #\n INT sum := 0;\n INT c pos := LWB cusip - 1;\n FOR i TO 8 DO\n INT digit := 0;\n IF NOT char in string( cusip[ i + c pos ], digit, cusip digits )\n THEN\n # invalid digit #\n digit := -999\n FI;\n IF NOT ODD i\n THEN\n # even digit #\n digit *:= 2\n FI;\n sum +:= ( digit OVER 10 ) + ( digit MOD 10 )\n OD;\n ( 10 - ( sum MOD 10 ) ) MOD 10 = check digit\n FI\n FI ; # ISCUSIP #\n\n # task test cases #\n\n PROC test cusip = ( STRING cusip )VOID:\n print( ( cusip, IF ISCUSIP cusip THEN \" valid\" ELSE \" invalid\" FI, newline ) );\n\n test cusip( \"037833100\" );\n test cusip( \"17275R102\" );\n test cusip( \"38259P508\" );\n test cusip( \"594918104\" );\n test cusip( \"68389X106\" );\n test cusip( \"68389X105\" )\nEND\n", "language": "ALGOL-68" }, { "code": "begin % returns true if cusip is a valid CUSIP code %\n logical procedure isCusip ( string(9) value cusip ) ;\n begin\n % returns the base 39 digit corresponding to a character of a CUSIP code %\n integer procedure cusipDigit( string(1) value cChar ) ;\n if cChar >= \"0\" and cChar <= \"9\" then ( decode( cChar ) - decode( \"0\" ) )\n else if cChar >= \"A\" and cChar <= \"Z\" then ( decode( cChar ) - decode( \"A\" ) ) + 10\n else if cChar = \"*\" then 36\n else if cChar = \"@\" then 37\n else if cChar = \"#\" then 38\n else % invalid digit % -999 ;\n\n integer checkDigit, sum;\n checkDigit := cusipDigit( cusip( 8 // 1 ) );\n for cPos := 1 until 8 do begin\n integer digit;\n digit := cusipDigit( cusip( ( cPos - 1 ) // 1 ) );\n if not odd( cPos ) then digit := digit * 2;\n sum := sum + ( digit div 10 ) + ( digit rem 10 )\n end for_cPos ;\n ( ( 10 - ( sum rem 10 ) ) rem 10 ) = checkDigit\n end isCusip ;\n\n begin % task test cases %\n procedure testCusip ( string(9) value cusip ) ;\n write( s_w := 0, cusip, if isCusip( cusip ) then \" valid\" else \" invalid\" );\n\n testCusip( \"037833100\" );\n testCusip( \"17275R102\" );\n testCusip( \"38259P508\" );\n testCusip( \"594918104\" );\n testCusip( \"68389X106\" );\n testCusip( \"68389X105\" )\n end testCases\nend.\n", "language": "ALGOL-W" }, { "code": "use AppleScript version \"2.4\"\nuse framework \"Foundation\"\nuse scripting additions\n\n\n-- isCusip :: String -> Bool\non isCusip(s)\n set cs to \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*&#\"\n set ns to mapMaybe(elemIndex(cs), s)\n\n script go\n on |λ|(f, x)\n set fx to apply(f, x)\n (fx div 10) + (fx mod 10)\n end |λ|\n end script\n\n 9 = length of ns and item -1 of ns = (10 - (sum(zipWith(go, ¬\n cycle({my identity, my double}), ¬\n take(8, ns))) mod 10)) mod 10\nend isCusip\n\n\n-------------------------- TEST ---------------------------\non run\n script test\n on |λ|(s)\n s & \" -> \" & isCusip(s)\n end |λ|\n end script\n\n unlines(map(test, ¬\n {\"037833100\", \"17275R102\", \"38259P508\", ¬\n \"594918104\", \"68389X106\", \"68389X105\"}))\nend run\n\n-- 037833100 -> true\n-- 17275R102 -> true\n-- 38259P508 -> true\n-- 594918104 -> true\n-- 68389X106 -> false\n-- 68389X105 -> true\n\n\n-------------------- GENERIC FUNCTIONS --------------------\n\n-- Just :: a -> Maybe a\non Just(x)\n -- Constructor for an inhabited Maybe (option type) value.\n -- Wrapper containing the result of a computation.\n {type:\"Maybe\", Nothing:false, Just:x}\nend Just\n\n\n-- Nothing :: Maybe a\non Nothing()\n -- Constructor for an empty Maybe (option type) value.\n -- Empty wrapper returned where a computation is not possible.\n {type:\"Maybe\", Nothing:true}\nend Nothing\n\n\n-- Tuple (,) :: a -> b -> (a, b)\non Tuple(a, b)\n -- Constructor for a pair of values, possibly of two different types.\n {type:\"Tuple\", |1|:a, |2|:b, length:2}\nend Tuple\n\n\n-- apply ($) :: (a -> b) -> a -> b\non apply(f, x)\n -- The value of f(x)\n mReturn(f)'s |λ|(x)\nend apply\n\n\n-- cycle :: [a] -> Generator [a]\non cycle(xs)\n script\n property lng : 1 + (length of xs)\n property i : missing value\n on |λ|()\n if missing value is i then\n set i to 1\n else\n set nxt to (1 + i) mod lng\n if 0 = ((1 + i) mod lng) then\n set i to 1\n else\n set i to nxt\n end if\n end if\n return item i of xs\n end |λ|\n end script\nend cycle\n\n\n-- double :: Num -> Num\non double(x)\n 2 * x\nend double\n\n\n-- elemIndex :: Eq a => [a] -> a -> Maybe Int\non elemIndex(xs)\n script\n on |λ|(x)\n set lng to length of xs\n repeat with i from 1 to lng\n if x = (item i of xs) then return Just(i - 1)\n end repeat\n return Nothing()\n end |λ|\n end script\nend elemIndex\n\n\n-- identity :: a -> a\non identity(x)\n -- The argument unchanged.\n x\nend identity\n\n\n-- foldl :: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n\n-- length :: [a] -> Int\non |length|(xs)\n set c to class of xs\n if list is c or string is c then\n length of xs\n else\n (2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)\n end if\nend |length|\n\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n -- The list obtained by applying f\n -- to each element of xs.\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n\n-- The mapMaybe function is a version of map which can throw out\n-- elements. In particular, the functional argument returns\n-- something of type Maybe b. If this is Nothing, no element is\n-- added on to the result list. If it just Just b, then b is\n-- included in the result list.\n-- mapMaybe :: (a -> Maybe b) -> [a] -> [b]\non mapMaybe(mf, xs)\n script\n property g : mReturn(mf)\n on |λ|(a, x)\n set mb to g's |λ|(x)\n if Nothing of mb then\n a\n else\n a & (Just of mb)\n end if\n end |λ|\n end script\n foldl(result, {}, xs)\nend mapMaybe\n\n\n-- min :: Ord a => a -> a -> a\non min(x, y)\n if y < x then\n y\n else\n x\n end if\nend min\n\n\n-- mReturn :: First-class m => (a -> b) -> m (a -> b)\non mReturn(f)\n -- 2nd class handler function lifted into 1st class script wrapper.\n if script is class of f then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n\n-- sum :: [Num] -> Num\non sum(xs)\n script add\n on |λ|(a, b)\n a + b\n end |λ|\n end script\n\n foldl(add, 0, xs)\nend sum\n\n\n-- take :: Int -> [a] -> [a]\n-- take :: Int -> String -> String\non take(n, xs)\n set c to class of xs\n if list is c then\n if 0 < n then\n items 1 thru min(n, length of xs) of xs\n else\n {}\n end if\n else if string is c then\n if 0 < n then\n text 1 thru min(n, length of xs) of xs\n else\n \"\"\n end if\n else if script is c then\n set ys to {}\n repeat with i from 1 to n\n set v to |λ|() of xs\n if missing value is v then\n return ys\n else\n set end of ys to v\n end if\n end repeat\n return ys\n else\n missing value\n end if\nend take\n\n\n-- unlines :: [String] -> String\non unlines(xs)\n -- A single string formed by the intercalation\n -- of a list of strings with the newline character.\n set {dlm, my text item delimiters} to ¬\n {my text item delimiters, linefeed}\n set str to xs as text\n set my text item delimiters to dlm\n str\nend unlines\n\n\n-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\non zipWith(f, xs, ys)\n set lng to min(|length|(xs), |length|(ys))\n if 1 > lng then return {}\n set xs_ to take(lng, xs) -- Allow for non-finite\n set ys_ to take(lng, ys) -- generators like cycle etc\n set lst to {}\n tell mReturn(f)\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs_, item i of ys_)\n end repeat\n return lst\n end tell\nend zipWith\n", "language": "AppleScript" }, { "code": "validCUSIP?: function [cusip][\n s: 0\n alpha: `A`..`Z`\n\n loop.with:'i chop cusip 'c [\n v: 0\n\n case ø\n when? [numeric? c] -> v: to :integer to :string c\n when? [in? c alpha] -> v: (index alpha c) + 1 + 9\n when? [c = `*`] -> v: 36\n when? [c = `@`] -> v: 37\n when? [c = `#`] -> v: 38\n else []\n\n if odd? i -> v: 2 * v\n\n s: s + (v / 10) + (v % 10)\n ]\n check: (10 - (s % 10)) % 10\n\n return check = to :integer to :string last cusip\n]\n\nloop [\"037833100\" \"17275R102\" \"38259P508\" \"594918104\" \"68389X106\" \"68389X105\"] 'cusip [\n print [cusip \"=>\" (validCUSIP? cusip)? -> \"VALID\" -> \"INVALID\"]\n]\n", "language": "Arturo" }, { "code": "Cusip_Check_Digit(cusip){\n sum := 0, i := 1, x := StrSplit(cusip)\n while (i <= 8) {\n c := x[i]\n if c is digit\n v := c\n else if c is alpha\n v := Asc(c) - 64 + 9\n else if (c = \"*\")\n v := 36\n else if (c = \"@\")\n v := 37\n else if (c = \"#\")\n v := 38\n if (i/2 = Floor(i/2))\n v *= 2\n sum += Floor(v/10) + Mod(v, 10)\n i++\n }\n return (Mod(10 - Mod(sum, 10), 10) = x[9])\n}\n", "language": "AutoHotkey" }, { "code": "data =\n(\n037833100\n17275R102\n38259P508\n594918104\n68389X106\n68389X105\n)\n\noutput := \"Cusip`t`tValid`n\"\nloop, Parse, data, `n, `r\n output .= A_LoopField \"`t\" Cusip_Check_Digit(A_LoopField) \"`n\"\nMsgBox % output\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f CUSIP.AWK\nBEGIN {\n n = split(\"037833100,17275R102,38259P508,594918104,68389X106,68389X105\",arr,\",\")\n for (i=1; i<=n; i++) {\n printf(\"%9s %s\\n\",arr[i],cusip(arr[i]))\n }\n exit(0)\n}\nfunction cusip(n, c,i,sum,v,x) {\n# returns: 1=OK, 0=NG, -1=bad data\n if (length(n) != 9) {\n return(-1)\n }\n for (i=1; i<=8; i++) {\n c = substr(n,i,1)\n if (c ~ /[0-9]/) {\n v = c\n }\n else if (c ~ /[A-Z]/) {\n v = index(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\",c) + 9\n }\n else if (c == \"*\") {\n v = 36\n }\n else if (c == \"@\") {\n v = 37\n }\n else if (c == \"#\") {\n v = 38\n }\n else {\n return(-1)\n }\n if (i ~ /[02468]/) {\n v *= 2\n }\n sum += int(v / 10) + (v % 10)\n }\n x = (10 - (sum % 10)) % 10\n return(substr(n,9,1) == x ? 1 : 0)\n}\n", "language": "AWK" }, { "code": "get \"libhdr\"\n\nlet validcusip(c) = valof\n$( let sum = 0\n unless c%0 = 9 resultis false\n for i = 1 to 8 do\n $( let v = ( 2 - (i & 1) ) * valof\n $( test '0' <= c%i <= '9'\n then resultis c%i - '0'\n or test 'A' <= c%i <= 'Z'\n then resultis 10 + c%i - 'A'\n or test c%i = '**'\n then resultis 36\n or test c%i = '@'\n then resultis 37\n or test c%i = '#'\n then resultis 38\n else resultis -1\n $)\n sum := sum + v/10 + v rem 10\n $)\n resultis (10 - (sum rem 10)) rem 10 = c%9 - '0'\n$)\n\nlet show(c) be\n writef(\"%S: %Svalid*N\", c, validcusip(c) -> \"\", \"in\")\n\nlet start() be\n$( show(\"037833100\")\n show(\"17275R102\")\n show(\"38259P508\")\n show(\"594918104\")\n show(\"68389X106\")\n show(\"68389X105\")\n$)\n", "language": "BCPL" }, { "code": "#include<stdlib.h>\n#include<stdio.h>\n\nint cusipCheck(char str[10]){\n\tint sum=0,i,v;\n\t\n\tfor(i=0;i<8;i++){\n\t\tif(str[i]>='0'&&str[i]<='9')\n\t\t\tv = str[i]-'0';\n\t\telse if(str[i]>='A'&&str[i]<='Z')\n\t\t\tv = (str[i] - 'A' + 10);\n\t\telse if(str[i]=='*')\n\t\t\tv = 36;\n\t\telse if(str[i]=='@')\n\t\t\tv = 37;\n\t\telse if(str[i]=='#')\n\t\t\tv = 38;\n\t\tif(i%2!=0)\n\t\t\tv*=2;\n\t\t\n\t\tsum += ((int)(v/10) + v%10);\n\t}\n\treturn ((10 - (sum%10))%10);\n}\n\nint main(int argC,char* argV[])\n{\n\tchar cusipStr[10];\n\t\n\tint i,numLines;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <full path of CUSIP Data file>\",argV[0]);\n\t\n\telse{\n\t\tFILE* fp = fopen(argV[1],\"r\");\n\t\n\t\tfscanf(fp,\"%d\",&numLines);\n\t\t\n\t\tprintf(\"CUSIP Verdict\\n\");\n\t\tprintf(\"-------------------\");\n\t\t\n\t\tfor(i=0;i<numLines;i++){\n\t\t\n\t\t\tfscanf(fp,\"%s\",cusipStr);\n\t\t\n\t\t\tprintf(\"\\n%s : %s\",cusipStr,(cusipCheck(cusipStr)==(cusipStr[8]-'0'))?\"Valid\":\"Invalid\");\n\t\t}\n\t\n\t\tfclose(fp);\n\t}\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <vector>\n\nbool isCusip(const std::string& s) {\n if (s.size() != 9) return false;\n\n int sum = 0;\n for (int i = 0; i <= 7; ++i) {\n char c = s[i];\n\n int v;\n if ('0' <= c && c <= '9') {\n v = c - '0';\n } else if ('A' <= c && c <= 'Z') {\n v = c - 'A' + 10;\n } else if (c = '*') {\n v = 36;\n } else if (c = '@') {\n v = 37;\n } else if (c = '#') {\n v = 38;\n } else {\n return false;\n }\n if (i % 2 == 1) {\n v *= 2;\n }\n sum += v / 10 + v % 10;\n }\n return s[8] - '0' == (10 - (sum % 10)) % 10;\n}\n\nint main() {\n using namespace std;\n\n vector<string> candidates{\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n };\n\n for (auto str : candidates) {\n auto res = isCusip(str) ? \"correct\" : \"incorrect\";\n cout << str.c_str() << \" -> \" << res << \"\\n\";\n }\n\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\n\nnamespace CUSIP {\n class Program {\n static bool IsCusip(string s) {\n if (s.Length != 9) return false;\n int sum = 0;\n for (int i = 0; i <= 7; i++) {\n char c = s[i];\n\n int v;\n if (c >= '0' && c <= '9') {\n v = c - 48;\n }\n else if (c >= 'A' && c <= 'Z') {\n v = c - 55; // lower case letters apparently invalid\n }\n else if (c == '*') {\n v = 36;\n }\n else if (c == '#') {\n v = 38;\n }\n else {\n return false;\n }\n if (i % 2 == 1) v *= 2; // check if odd as using 0-based indexing\n sum += v / 10 + v % 10;\n }\n return s[8] - 48 == (10 - (sum % 10)) % 10;\n }\n\n static void Main(string[] args) {\n List<string> candidates = new List<string>() {\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n };\n foreach (var candidate in candidates) {\n Console.WriteLine(\"{0} -> {1}\", candidate, IsCusip(candidate) ? \"correct\" : \"incorrect\");\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(defn- char->value\n \"convert the given char c to a value used to calculate the cusip check sum\"\n [c]\n (let [int-char (int c)]\n (cond\n (and (>= int-char (int \\0)) (<= int-char (int \\9))) (- int-char 48)\n (and (>= int-char (int \\A)) (<= int-char (int \\Z))) (- int-char 55)\n (= c \\*) 36\n (= c \\@) 37\n (= c \\#) 38\n :else nil)))\n\n(defn- calc-sum\n \"Calculate cusip sum. nil is returned for an invalid cusip.\"\n [cusip]\n (reduce\n (fn [sum [i c]]\n (if-let [v (char->value c)]\n (let [v (if (= (mod i 2) 1) (* v 2) v)]\n (+ sum (int (+ (/ v 10) (mod v 10)))))\n (reduced nil)))\n 0\n (map-indexed vector (subs cusip 0 8))))\n\n(defn calc-cusip-checksum\n \"Given a valid 8 or 9 digit cusip, return the 9th checksum digit\"\n [cusip]\n (when (>= (count cusip) 8)\n (let [sum (calc-sum cusip)]\n (when sum\n (mod (- 10 (mod sum 10)) 10)))))\n\n(defn is-valid-cusip9?\n \"predicate validating a 9 digit cusip.\"\n [cusip9]\n (when-let [checksum (and (= (count cusip9) 9)\n (calc-cusip-checksum cusip9))]\n (= (- (int (nth cusip9 8)) 48)\n checksum)))\n\n(defn rosetta-output\n \"show some nice output for the Rosetta Wiki\"\n []\n (doseq [cusip [\"037833100\" \"17275R102\" \"38259P508\" \"594918104\" \"68389X106\" \"68389X105\" \"EXTRACRD8\"\n \"EXTRACRD9\" \"BADCUSIP!\" \"683&9X106\" \"68389x105\" \"683$9X106\" \"68389}105\" \"87264ABE4\"]]\n (println cusip (if (is-valid-cusip9? cusip) \"valid\" \"invalid\"))))\n", "language": "Clojure" }, { "code": "valid_cusip = proc (s: string) returns (bool)\n own chars: string := \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#\"\n if string$size(s) ~= 9 then return(false) end\n sum: int := 0\n for i: int in int$from_to(1,8) do\n v: int := string$indexc(s[i], chars)-1\n if v<0 then return(false) end\n if i//2=0 then v := v*2 end\n sum := sum + v/10 + v//10\n end\n check: int := (10 - sum // 10) // 10\n return(check = string$indexc(s[9], chars)-1)\nend valid_cusip\n\nstart_up = proc ()\n po: stream := stream$primary_output()\n cusips: array[string] := array[string]$[\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n ]\n\n for cusip: string in array[string]$elements(cusips) do\n stream$puts(po, cusip || \": \")\n if valid_cusip(cusip)\n then stream$putl(po, \"valid\")\n else stream$putl(po, \"invalid\")\n end\n end\nend start_up\n", "language": "CLU" }, { "code": "(defun char->value (c)\n (cond ((digit-char-p c 36))\n ((char= c #\\*) 36)\n ((char= c #\\@) 37)\n ((char= c #\\#) 38)\n (t (error \"Invalid character: ~A\" c))))\n\n(defun cusip-p (cusip)\n (and (= 9 (length cusip))\n (loop for i from 1 to 8\n for c across cusip\n for v = (char->value c)\n when (evenp i)\n do (setf v (* 2 v))\n sum (multiple-value-bind (quot rem) (floor v 10)\n (+ quot rem))\n into sum\n finally (return (eql (digit-char-p (char cusip 8))\n (mod (- 10 (mod sum 10)) 10))))))\n\n(defun main ()\n (dolist (cusip '(\"037833100\" \"17275R102\" \"38259P508\" \"594918104\" \"68389X106\" \"68389X105\"))\n (format t \"~A: ~A~%\" cusip (cusip-p cusip))))\n", "language": "Common-Lisp" }, { "code": "import std.stdio;\n\nvoid main(string[] args) {\n writeln(\"CUSIP Verdict\");\n foreach(arg; args[1..$]) {\n writefln(\"%9s : %s\", arg, isValidCusip(arg) ? \"Valid\" : \"Invalid\");\n }\n}\n\nclass IllegalCharacterException : Exception {\n this(string msg) {\n super(msg);\n }\n}\n\nbool isValidCusip(string cusip) in {\n assert(cusip.length == 9, \"Incorrect cusip length\");\n} body {\n try {\n auto check = cusipCheckDigit(cusip);\n return cusip[8] == ('0' + check);\n } catch (IllegalCharacterException e) {\n return false;\n }\n}\n\nunittest {\n // Oracle Corporation\n assertEquals(isValidCusip(\"68389X105\"), true);\n\n // Oracle Corporation (invalid)\n assertEquals(isValidCusip(\"68389X106\"), false);\n}\n\nint cusipCheckDigit(string cusip) in {\n assert(cusip.length == 9, \"Incorrect cusip length\");\n} body {\n int sum;\n for (int i=0; i<8; ++i) {\n char c = cusip[i];\n int v;\n\n switch(c) {\n case '0': .. case '9':\n v = c - '0';\n break;\n case 'A': .. case 'Z':\n v = c - 'A' + 10;\n break;\n case '*':\n v = 36;\n break;\n case '@':\n v = 37;\n break;\n case '#':\n v = 38;\n break;\n default:\n throw new IllegalCharacterException(\"Saw character: \" ~ c);\n }\n if (i%2 == 1) {\n v = 2 * v;\n }\n\n sum = sum + (v / 10) + (v % 10);\n }\n\n return (10 - (sum % 10)) % 10;\n}\n\nunittest {\n // Apple Incorporated\n assertEquals(cusipCheckDigit(\"037833100\"), 0);\n\n // Cisco Systems\n assertEquals(cusipCheckDigit(\"17275R102\"), 2);\n\n // Google Incorporated\n assertEquals(cusipCheckDigit(\"38259P508\"), 8);\n\n // Microsoft Corporation\n assertEquals(cusipCheckDigit(\"594918104\"), 4);\n\n // Oracle Corporation\n assertEquals(cusipCheckDigit(\"68389X105\"), 5);\n}\n\nversion(unittest) {\n void assertEquals(T)(T actual, T expected) {\n import core.exception;\n import std.conv;\n if (actual != expected) {\n throw new AssertError(\"Actual [\" ~ to!string(actual) ~ \"]; Expected [\" ~ to!string(expected) ~ \"]\");\n }\n }\n}\n\n/// Invoke with `cusip 037833100 17275R102 38259P508 594918104 68389X106 68389X105`\n", "language": "D" }, { "code": "type TCUSIPInfo = record\n ID,Company: string;\n end;\n\nvar CUSIPArray: array [0..5] of TCUSIPInfo = (\n (ID:'037833100'; Company: 'Apple Incorporated'),\n (ID:'17275R102'; Company: 'Cisco Systems'),\n (ID:'38259P508'; Company: 'Google Incorporated'),\n (ID:'594918104'; Company: 'Microsoft Corporation'),\n (ID:'68389X106'; Company: 'Oracle Corporation'),\n (ID:'68389X105'; Company: 'Oracle Corporation'));\n\nfunction IsValidCUSIP(Info: TCUSIPInfo): boolean;\n{Calculate checksum on first 7 chars of CUSIP }\n{And compare with the last char - the checksum char}\nvar I,V,Sum: integer;\nvar C: char;\nbegin\nSum:=0;\nfor I:=1 to Length(Info.ID)-1 do\n\tbegin\n\tC:=Info.ID[I];\n\tif C in ['0'..'9'] then V:=byte(C)-$30\n\telse if C in ['A'..'Z'] then V:=(byte(C)-$40) + 9\n\telse case C of\n\t '*': V:=36;\n\t '@': V:=37;\n\t '#': V:=38;\n\t end;\n\tif (I and 1)=0 then V:=V*2;\n\tSum:=Sum + (V div 10) + (V mod 10);\n\tend;\nSum:=(10 - (Sum mod 10)) mod 10;\nResult:=StrToInt(Info.ID[Length(Info.ID)])=Sum;\nend;\n\n\nprocedure TestCUSIPList(Memo: TMemo);\n{Test every item in the CSUIP array}\nvar I: integer;\nvar S: string;\nbegin\nfor I:=0 to High(CUSIPArray) do\n\tbegin\n\tif IsValidCUSIP(CUSIPArray[I]) then S:='Valid' else S:='Invalid';\n\tMemo.Lines.Add(CUSIPArray[I].ID+'\t'+CUSIPArray[I].Company+':\t'+S);\n\tend;\nend;\n", "language": "Delphi" }, { "code": "func isCusip(s) {\n if s.Length() != 9 { return false }\n var sum = 0\n for i in 0..7 {\n var c = s[i]\n var v =\n match c {\n '0'..'9' => c.Order() - 48,\n 'A'..'Z' => c.Order() - 55,\n '*' => 36,\n '@' => 37,\n '#' => 38,\n _ => false\n }\n if i % 2 == 1 { v *= 2 }\n sum += v / 10 + v % 10\n }\n s[8].Order() - 48 == (10 - (sum % 10)) % 10\n}\n\nvar candidates = [\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n]\n\nfor candidate in candidates {\n var b =\n if isCusip(candidate) {\n \"correct\"\n } else {\n \"incorrect\"\n }\n print(\"\\(candidate) -> \\(b)\")\n}\n", "language": "Dyalect" }, { "code": "func check inp$ .\n for i = 1 to 8\n c = strcode substr inp$ i 1\n if c >= 48 and c <= 57\n v = c - 48\n elif c >= 65 and c <= 91\n v = c - 64 + 9\n elif c = 42\n v = 36\n elif c = 64\n v = 37\n elif c = 35\n v = 38\n .\n if i mod 2 = 0\n v *= 2\n .\n sum += v div 10 + v mod 10\n .\n return if (10 - (sum mod 10)) mod 10 = number substr inp$ 9 1\n.\nfor s$ in [ \"037833100\" \"17275R102\" \"38259P508\" \"594918104\" \"68389X106\" \"68389X105\" ]\n write s$ & \" is \"\n if check s$ = 1\n print \"valid\"\n else\n print \"invalid\"\n .\n.\n", "language": "EasyLang" }, { "code": "=LAMBDA(s,\n LET(\n ns, VLOOKUP(\n CHARS(s), CUSIPMAP, 2, FALSE\n ),\n\n AND(\n 9 = COLUMNS(ns),\n LET(\n firstEight, INITCOLS(ns),\n\n ixs, SEQUENCE(1, 8),\n\n evensDoubled, IF(ISEVEN(ixs),\n 2 * INDEX(firstEight, 1, ixs),\n INDEX(firstEight, 1, ixs)\n ),\n\n LASTCOL(ns) = MOD(\n 10 - MOD(\n SUM(\n QUOTIENT(evensDoubled, 10),\n MOD(evensDoubled, 10)\n ),\n 10\n ),\n 10\n )\n )\n )\n )\n)\n\n\nCUSIPMAP\n={\"0\",0;\"1\",1;\"2\",2;\"3\",3;\"4\",4;\"5\",5;\"6\",6;\"7\",7;\"8\",8;\"9\",9;\"A\",\n10;\"B\",11;\"C\",12;\"D\",13;\"E\",14;\"F\",15;\"G\",16;\"H\",17;\"I\",18;\"J\",19;\"K\",\n20;\"L\",21;\"M\",22;\"N\",23;\"O\",24;\"P\",25;\"Q\",26;\"R\",27;\"S\",28;\"T\",29;\"U\",\n30;\"V\",31;\"W\",32;\"X\",33;\"Y\",34;\"Z\",35;\"*\",36;\"@\",37;\"#\",38}\n", "language": "Excel" }, { "code": "CHARS\n=LAMBDA(s,\n MID(\n s,\n SEQUENCE(1, LEN(s), 1, 1),\n 1\n )\n)\n\n\nINITCOLS\n=LAMBDA(xs,\n INDEX(\n xs,\n SEQUENCE(\n 1,\n COLUMNS(xs) - 1,\n 1,\n )\n )\n)\n\n\nLASTCOL\n=LAMBDA(xs,\n INDEX(\n xs,\n SEQUENCE(ROWS(xs), 1, 1, 1),\n COLUMNS(xs)\n )\n)\n", "language": "Excel" }, { "code": "// Validate CUSIP: Nigel Galloway. June 2nd., 2021\nlet fN=function n when n>47 && n<58->n-48 |n when n>64 && n<91->n-55 |42->36 |64->37 |_->38\nlet cD(n:string)=(10-(fst((n.[0..7])|>Seq.fold(fun(z,n)g->let g=(fN(int g))*(n+1) in (z+g/10+g%10,(n+1)%2))(0,0)))%10)%10=int(n.[8])-48\n[\"037833100\";\"17275R102\";\"38259P508\";\"594918104\";\"68389X103\";\"68389X105\"]|>List.iter(fun n->printfn \"CUSIP %s is %s\" n (if cD n then \"valid\" else \"invalid\"))\n", "language": "F-Sharp" }, { "code": "USING: combinators.short-circuit formatting kernel math\nmath.parser qw regexp sequences unicode ;\nIN: rosetta-code.cusip\n\n: cusip-check-digit ( seq -- n )\n but-last-slice [\n [ dup alpha? [ digit> ] [ \"*@#\" index 36 + ] if ] dip\n odd? [ 2 * ] when 10 /mod +\n ] map-index sum 10 mod 10 swap - 10 mod ;\n\n: cusip? ( seq -- ? )\n {\n [ R/ [0-9A-Z*@#]+/ matches? ]\n [ [ last digit> ] [ cusip-check-digit ] bi = ]\n } 1&& ;\n\nqw{ 037833100 17275R102 38259P508 594918104 68389X106 68389X105 }\n[ dup cusip? \"correct\" \"incorrect\" ? \"%s -> %s\\n\" printf ] each\n", "language": "Factor" }, { "code": " CHARACTER*1 FUNCTION CUSIPCHECK(TEXT)\t!Determines the check sum character.\nCommittee on Uniform Security Identification Purposes, of the American (i.e. USA) Bankers' Association.\n CHARACTER*8 TEXT\t\t!Specifically, an eight-symbol code.\n CHARACTER*(*) VALID\t!These only are valid.\n PARAMETER (VALID = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#\")\n INTEGER I,V,S\t\t!Assistants.\n S = 0\t\t!Start the checksum.\n DO I = 1,LEN(TEXT)\t!Step through the text.\n V = INDEX(VALID,TEXT(I:I)) - 1\t!Since counting starts with one.\n IF (MOD(I,2).EQ.0) V = V*2\t\t!V = V*(2 - MOD(I,2))?\n S = S + V/10 + MOD(V,10)\t\t!Specified calculation.\n END DO\t\t\t!On to the next character.\n I = MOD(10 - MOD(S,10),10) + 1\t!Again, counting starts with one.\n CUSIPCHECK = VALID(I:I)\t!Thanks to the MOD 10, surely a digit.\n END FUNCTION CUSIPCHECK\t!No checking for invalid input...\n\n PROGRAM POKE\t!Just to try it out.\n INTEGER I,N\t!Assistants.\n PARAMETER (N = 6)\t\t!A whole lot of blather\n CHARACTER*9 CUSIP(N)\t!Just to have an array of test codes.\n DATA CUSIP/\t\t!Here they are, as specified.\n 1 \"037833100\",\n 2 \"17275R102\",\n 3 \"38259P508\",\n 4 \"594918104\",\n 5 \"68389X106\",\n 6 \"68389X105\"/\n CHARACTER*1 CUSIPCHECK\t!Needed as no use of the MODULE protocol.\n\n DO I = 1,N\t!\"More than two? Use a DO...\"\n WRITE (6,*) CUSIP(I),CUSIPCHECK(CUSIP(I)(1:8)).EQ.CUSIP(I)(9:9)\n END DO\n\n END\n", "language": "Fortran" }, { "code": "' version 04-04-2017\n' compile with: fbc -s console\n\nsub cusip(input_str As String)\n\n Print input_str;\n If Len(input_str) <> 9 Then\n Print \" length is incorrect, invalid cusip\"\n Return\n End If\n\n Dim As Long i, v , sum\n Dim As UByte x\n\n For i = 1 To 8\n x = input_str[i-1]\n Select Case x\n Case Asc(\"0\") To Asc(\"9\")\n v = x - Asc(\"0\")\n Case Asc(\"A\") To Asc(\"Z\")\n v = x - Asc(\"A\") + 1 + 9\n Case Asc(\"*\")\n v= 36\n Case Asc(\"@\")\n v = 37\n Case Asc(\"#\")\n v = 38\n Case Else\n Print \" found a invalid character, invalid cusip\"\n return\n End Select\n\n If (i And 1) = 0 Then v = v * 2\n sum = sum + v \\ 10 + v Mod 10\n Next\n\n sum = (10 - (sum Mod 10)) Mod 10\n If sum = (input_str[8] - Asc(\"0\")) Then\n Print \" is valid\"\n Else\n Print \" is invalid\"\n End If\n\nEnd Sub\n\n' ------=< MAIN >=------\n\nData \"037833100\", \"17275R102\", \"38259P508\"\nData \"594918104\", \"68389X106\", \"68389X105\"\n\nDim As String input_str\n\nPrint\nFor i As Integer = 1 To 6\n Read input_str\n cusip(input_str)\nNext\n\n' empty keyboard buffer\nWhile InKey <> \"\" : Wend\nPrint : Print \"hit any key to end program\"\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "include \"NSLog.incl\"\n\nlocal fn VerifyCUSIP( cusipStr as CFStringRef ) as CFStringRef\n NSUInteger i, v, sum = 0, count = len(cusipStr)\n CFStringRef resultStr\n\n if count != 9 then exit fn = @\"Invalid length\"\n\n for i = 0 to 7\n unichar x = fn StringCharacterAtIndex( cusipStr, i )\n select x\n case _\"*\" : v = 36\n case _\"@\" : v = 37\n case _\"#\" : v = 38\n case else\n if ( x >= _\"0\" and x <= _\"9\" )\n v = x - _\"0\"\n else\n if ( x >= _\"A\" and x <= _\"Z\" )\n v = x - _\"A\" + 10\n else\n exit fn = fn StringWithFormat( @\"Invalid character: %c\", x )\n end if\n end if\n end select\n\n if ( i and 1 ) then v = v * 2\n\n sum += (v / 10) + (v mod 10)\n next\n sum = ((10-(sum mod 10)) mod 10)\n\n if (sum == ( fn StringCharacterAtIndex( cusipStr, 8 ) - _\"0\" ))\n resultStr = @\"Valid\"\n else\n resultStr = @\"Invalid\"\n end If\nend fn = resultStr\n\nNSLog( @\"0378331009: %@\", fn VerifyCUSIP( @\"0378331009\" ) ) // Invalid length expected\nNSLog( @\"037833100: %@\", fn VerifyCUSIP( @\"037833100\" ) ) // Valid expected\nNSLog( @\"17275R102: %@\", fn VerifyCUSIP( @\"17275R102\" ) ) // Valid expected\nNSLog( @\"38259P508: %@\", fn VerifyCUSIP( @\"38259P508\" ) ) // Valid expected\nNSLog( @\"594918104: %@\", fn VerifyCUSIP( @\"594918104\" ) ) // Valid expected\nNSLog( @\"68389X106: %@\", fn VerifyCUSIP( @\"68389X106\" ) ) // Invalid expected\nNSLog( @\"68389X105: %@\", fn VerifyCUSIP( @\"68389X105\" ) ) // Valid expected\nNSLog( @\"683&9X105: %@\", fn VerifyCUSIP( @\"683&9X105\" ) ) // Invalid character expected: &\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc isCusip(s string) bool {\n if len(s) != 9 { return false }\n sum := 0\n for i := 0; i < 8; i++ {\n c := s[i]\n var v int\n switch {\n case c >= '0' && c <= '9':\n v = int(c) - 48\n case c >= 'A' && c <= 'Z':\n v = int(c) - 55\n case c == '*':\n v = 36\n case c == '@':\n v = 37\n case c == '#':\n v = 38\n default:\n return false\n }\n if i % 2 == 1 { v *= 2 } // check if odd as using 0-based indexing\n sum += v/10 + v%10\n }\n return int(s[8]) - 48 == (10 - (sum%10)) % 10\n}\n\nfunc main() {\n candidates := []string {\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\",\n }\n\n for _, candidate := range candidates {\n var b string\n if isCusip(candidate) {\n b = \"correct\"\n } else {\n b = \"incorrect\"\n }\n fmt.Printf(\"%s -> %s\\n\", candidate, b)\n }\n}\n", "language": "Go" }, { "code": "class Cusip {\n private static Boolean isCusip(String s) {\n if (s.length() != 9) return false\n int sum = 0\n for (int i = 0; i <= 7; i++) {\n char c = s.charAt(i)\n\n int v\n if (c >= ('0' as char) && c <= ('9' as char)) {\n v = c - 48\n } else if (c >= ('A' as char) && c <= ('Z' as char)) {\n v = c - 55 // lower case letters apparently invalid\n } else if (c == '*' as char) {\n v = 36\n } else if (c == '@' as char) {\n v = 37\n } else if (c == '#' as char) {\n v = 38\n } else {\n return false\n }\n if (i % 2 == 1) v *= 2 // check if odd as using 0-based indexing\n sum += v / 10 + v % 10\n }\n return s.charAt(8) - 48 == (10 - (sum % 10)) % 10\n }\n\n static void main(String[] args) {\n List<String> candidates=new ArrayList<>()\n candidates.add(\"037833100\")\n candidates.add(\"17275R102\")\n candidates.add(\"38259P508\")\n candidates.add(\"594918104\")\n candidates.add(\"68389X106\")\n candidates.add(\"68389X105\")\n for (String candidate : candidates) {\n System.out.printf(\"%s -> %s%n\", candidate, isCusip(candidate) ? \"correct\" : \"incorrect\")\n }\n }\n}\n", "language": "Groovy" }, { "code": "import Data.List(elemIndex)\n\ndata Result = Valid | BadCheck | TooLong | TooShort | InvalidContent deriving Show\n\n-- convert a list of Maybe to a Maybe list.\n-- result is Nothing if any of values from the original list are Nothing\nallMaybe :: [Maybe a] -> Maybe [a]\nallMaybe = sequence\n\ntoValue :: Char -> Maybe Int\ntoValue c = elemIndex c $ ['0'..'9'] ++ ['A'..'Z'] ++ \"*@#\"\n\n-- check a list of ints to see if they represent a valid CUSIP\nvalid :: [Int] -> Bool\nvalid ns0 =\n let -- multiply values with even index by 2\n ns1 = zipWith (\\i n -> (if odd i then n else 2*n)) [1..] $ take 8 ns0\n\n -- apply div/mod formula from site and sum up results\n sm = sum $ fmap (\\s -> ( s `div` 10 ) + s `mod` 10) ns1\n\n in -- apply mod/mod formula from site and compare to last value in list\n ns0!!8 == (10 - (sm `mod` 10)) `mod` 10\n\n-- check a String to see if it represents a valid CUSIP\ncheckCUSIP :: String -> Result\ncheckCUSIP cs\n | l < 9 = TooShort\n | l > 9 = TooLong\n | otherwise = case allMaybe (fmap toValue cs) of\n Nothing -> InvalidContent\n Just ns -> if valid ns then Valid else BadCheck\n where l = length cs\n\ntestData =\n [ \"037833100\"\n , \"17275R102\"\n , \"38259P508\"\n , \"594918104\"\n , \"68389X106\"\n , \"68389X105\"\n ]\n\nmain = mapM_ putStrLn (fmap (\\s -> s ++ \": \" ++ show (checkCUSIP s)) testData)\n", "language": "Haskell" }, { "code": "import qualified Data.Map as M (Map, fromList, lookup)\nimport Data.Maybe (fromMaybe)\n\n-------------------------- CUSIP -------------------------\n\ncusipMap :: M.Map Char Int\ncusipMap =\n M.fromList $\n zip (['0' .. '9'] <> ['A' .. 'Z'] <> \"*@#\") [0 ..]\n\ncusipValid :: String -> Bool\ncusipValid s =\n let ns = (fromMaybe [] . traverse (`M.lookup` cusipMap)) s\n in (9 == length ns)\n && let qrSum =\n sum $\n ( [quot, rem]\n <*> zipWith\n id\n (cycle [id, (* 2)])\n (take 8 ns)\n )\n <*> [10]\n in last ns == rem (10 - rem qrSum 10) 10\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n mapM_\n (print . ((,) <*> cusipValid))\n [ \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n ]\n", "language": "Haskell" }, { "code": "# cusip.icn -- Committee on Uniform Security Identification Procedures\n\nprocedure main()\n local code, codes\n codes := [\"037833100\", \"17275R102\", \"38259P508\",\n \"594918104\", \"68389X106\", \"68389X105\"]\n while code := pop(codes) do {\n writes(code, \" : \")\n if check_code(code) then\n write(\"valid.\")\n else write(\"not valid.\")\n }\nend\n\nprocedure check_code(c)\n local p, sum, value\n static codetable\n initial codetable := buildtable()\n\n sum := 0\n value := 0\n every p := 1 to 8 do {\n if p % 2 = 1 then # odd position\n value := codetable[c[p]]\n else # even position\n value := 2 * codetable[c[p]]\n sum +:= (value / 10) + (value % 10)\n }\n sum := (10 - (sum % 10)) % 10\n if sum = c[9] then return else fail\nend\n\nprocedure buildtable()\n local chars, n, t\n t := table()\n chars := &digits || &ucase || \"*@#\"\n every n := 1 to *chars do\n t[chars[n]] := (n - 1)\n return t\nend\n", "language": "Icon" }, { "code": " ccd =. 10 | 10 - 10 | [: +/ [: , 10 (#.^:_1) (8 $ 1 2) * '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#' i. ]\n ccd '68389X10'\n5\n", "language": "J" }, { "code": " CUSIPcheckdigit =. 3 : 0\nassert. 8 = $ y NB. Only accept an 8-element long list\nassert. */ y e. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#' NB. Only accept characters from the list of 38\nvalues =. (8 $ 1 2) * '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#' i. ] NB. Verb to translate characters and then double every second value.\nsumdigits =. +/@,@(10 10&#:) NB. Verb to sum the base-10 digits in a numerical array\ninvertedmod =. 10 | 10 - 10 | ] NB. Verb to find the mod-10 of 10 minus mod-10\n\": invertedmod sumdigits values y NB. Return the check digit as a character\n)\n addCUSIPcheckdigit =: , CUSIPcheckdigit\n verifyCUSIPcheckdigit =: {: = CUSIPcheckdigit@}:\n", "language": "J" }, { "code": " addCUSIPcheckdigit '68389X10'\n68389X105\n verifyCUSIPcheckdigit '68389X106'\n0\n verifyCUSIPcheckdigit '68389X105'\n1\n samples =: '037833100', '17275R102', '38259P508', '594918104', '68389X106',: '68389X105'\n samples ; verifyCUSIPcheckdigit\"1 samples\n┌─────────┬─┐\n│037833100│1│\n│17275R102│1│\n│38259P508│1│\n│594918104│1│\n│68389X106│0│\n│68389X105│1│\n└─────────┴─┘\n", "language": "J" }, { "code": "import java.util.List;\n\npublic class Cusip {\n private static Boolean isCusip(String s) {\n if (s.length() != 9) return false;\n int sum = 0;\n for (int i = 0; i <= 7; i++) {\n char c = s.charAt(i);\n\n int v;\n if (c >= '0' && c <= '9') {\n v = c - 48;\n } else if (c >= 'A' && c <= 'Z') {\n v = c - 55; // lower case letters apparently invalid\n } else if (c == '*') {\n v = 36;\n } else if (c == '@') {\n v = 37;\n } else if (c == '#') {\n v = 38;\n } else {\n return false;\n }\n if (i % 2 == 1) v *= 2; // check if odd as using 0-based indexing\n sum += v / 10 + v % 10;\n }\n return s.charAt(8) - 48 == (10 - (sum % 10)) % 10;\n }\n\n public static void main(String[] args) {\n List<String> candidates = List.of(\n \"037833100\", \"17275R102\", \"38259P508\", \"594918104\", \"68389X106\", \"68389X105\", \"EXTRACRD8\",\n \"EXTRACRD9\", \"BADCUSIP!\", \"683&9X106\", \"68389x105\", \"683$9X106\", \"68389}105\", \"87264ABE4\"\n );\n for (String candidate : candidates) {\n System.out.printf(\"%s -> %s%n\", candidate, isCusip(candidate) ? \"correct\" : \"incorrect\");\n }\n }\n}\n", "language": "Java" }, { "code": "(() => {\n 'use strict';\n\n // cusipValid = Dict Char Int -> String -> Bool\n const cusipValid = charMap => s => {\n const\n ns = fromMaybe([])(\n traverse(flip(lookupDict)(charMap))(\n chars(s)\n )\n );\n return 9 === ns.length && (\n last(ns) === rem(\n 10 - rem(\n sum(apList(\n apList([quot, rem])(\n zipWith(identity)(\n cycle([identity, x => 2 * x])\n )(take(8)(ns))\n )\n )([10]))\n )(10)\n )(10)\n );\n };\n\n //----------------------- TEST ------------------------\n // main :: IO ()\n const main = () => {\n\n // cusipMap :: Dict Char Int\n const cusipMap = dictFromList(\n zip(chars(\n \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#\"\n ))(enumFrom(0)));\n\n console.log(unlines(map(\n apFn(\n s => validity => s + ' -> ' + str(validity)\n )(cusipValid(cusipMap))\n )([\n '037833100',\n '17275R102',\n '38259P508',\n '594918104',\n '68389X106',\n '68389X105'\n ])));\n };\n\n\n //----------------- GENERIC FUNCTIONS -----------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a =>\n b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n\n // apFn :: (a -> b -> c) -> (a -> b) -> a -> c\n const apFn = f =>\n // Applicative instance for functions.\n // f(x) applied to g(x).\n g => x => f(x)(\n g(x)\n );\n\n\n // apList (<*>) :: [(a -> b)] -> [a] -> [b]\n const apList = fs =>\n // The sequential application of each of a list\n // of functions to each of a list of values.\n xs => fs.flatMap(\n f => xs.map(f)\n );\n\n\n // append (++) :: [a] -> [a] -> [a]\n // append (++) :: String -> String -> String\n const append = xs =>\n // A list or string composed by\n // the concatenation of two others.\n ys => xs.concat(ys);\n\n\n // chars :: String -> [Char]\n const chars = s =>\n s.split('');\n\n\n // cons :: a -> [a] -> [a]\n const cons = x =>\n xs => Array.isArray(xs) ? (\n [x].concat(xs)\n ) : 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n x + xs\n ) : ( // cons(x)(Generator)\n function*() {\n yield x;\n let nxt = xs.next()\n while (!nxt.done) {\n yield nxt.value;\n nxt = xs.next();\n }\n }\n )();\n\n\n // cycle :: [a] -> Generator [a]\n function* cycle(xs) {\n const lng = xs.length;\n let i = 0;\n while (true) {\n yield(xs[i])\n i = (1 + i) % lng;\n }\n }\n\n\n // dictFromList :: [(k, v)] -> Dict\n const dictFromList = kvs =>\n Object.fromEntries(kvs);\n\n\n // enumFrom :: Enum a => a -> [a]\n function* enumFrom(x) {\n // A non-finite succession of enumerable\n // values, starting with the value x.\n let v = x;\n while (true) {\n yield v;\n v = succ(v);\n }\n }\n\n\n // flip :: (a -> b -> c) -> b -> a -> c\n const flip = f =>\n 1 < f.length ? (\n (a, b) => f(b, a)\n ) : (x => y => f(y)(x));\n\n\n // fromEnum :: Enum a => a -> Int\n const fromEnum = x =>\n typeof x !== 'string' ? (\n x.constructor === Object ? (\n x.value\n ) : parseInt(Number(x))\n ) : x.codePointAt(0);\n\n\n // fromMaybe :: a -> Maybe a -> a\n const fromMaybe = def =>\n // A default value if mb is Nothing\n // or the contents of mb.\n mb => mb.Nothing ? def : mb.Just;\n\n\n // fst :: (a, b) -> a\n const fst = tpl =>\n // First member of a pair.\n tpl[0];\n\n\n // identity :: a -> a\n const identity = x =>\n // The identity function. (`id`, in Haskell)\n x;\n\n\n // last :: [a] -> a\n const last = xs =>\n // The last item of a list.\n 0 < xs.length ? xs.slice(-1)[0] : undefined;\n\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n\n // liftA2 :: (a -> b -> c) -> Maybe a -> Maybe b -> Maybe c\n const liftA2 = f => a => b =>\n a.Nothing ? a : b.Nothing ? b : Just(f(a.Just)(b.Just));\n\n\n // lookupDict :: a -> Dict -> Maybe b\n const lookupDict = k => dct => {\n const v = dct[k];\n return undefined !== v ? (\n Just(v)\n ) : Nothing();\n };\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f =>\n // The list obtained by applying f\n // to each element of xs.\n // (The image of xs under f).\n xs => (\n Array.isArray(xs) ? (\n xs\n ) : xs.split('')\n ).map(f);\n\n\n // pureMay :: a -> Maybe a\n const pureMay = x => Just(x);\n\n // Given a type name string, returns a\n // specialised 'pure', where\n // 'pure' lifts a value into a particular functor.\n\n // pureT :: String -> f a -> (a -> f a)\n const pureT = t => x =>\n 'List' !== t ? (\n 'Either' === t ? (\n pureLR(x)\n ) : 'Maybe' === t ? (\n pureMay(x)\n ) : 'Node' === t ? (\n pureTree(x)\n ) : 'Tuple' === t ? (\n pureTuple(x)\n ) : pureList(x)\n ) : pureList(x);\n\n\n // pureTuple :: a -> (a, a)\n const pureTuple = x =>\n Tuple('')(x);\n\n // quot :: Int -> Int -> Int\n const quot = n =>\n m => Math.floor(n / m);\n\n // rem :: Int -> Int -> Int\n const rem = n => m => n % m;\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // str :: a -> String\n const str = x =>\n x.toString();\n\n // succ :: Enum a => a -> a\n const succ = x => {\n const t = typeof x;\n return 'number' !== t ? (() => {\n const [i, mx] = [x, maxBound(x)].map(fromEnum);\n return i < mx ? (\n toEnum(x)(1 + i)\n ) : Error('succ :: enum out of range.')\n })() : x < Number.MAX_SAFE_INTEGER ? (\n 1 + x\n ) : Error('succ :: Num out of range.')\n };\n\n // sum :: [Num] -> Num\n const sum = xs =>\n // The numeric sum of all values in xs.\n xs.reduce((a, x) => a + x, 0);\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // The first argument is a sample of the type\n // allowing the function to make the right mapping\n\n // toEnum :: a -> Int -> a\n const toEnum = e => x =>\n ({\n 'number': Number,\n 'string': String.fromCodePoint,\n 'boolean': Boolean,\n 'object': v => e.min + v\n } [typeof e])(x);\n\n\n // traverse :: (Applicative f) => (a -> f b) -> [a] -> f [b]\n const traverse = f =>\n // Collected results of mapping each element\n // of a structure to an action, and evaluating\n // these actions from left to right.\n xs => 0 < xs.length ? (() => {\n const\n vLast = f(xs.slice(-1)[0]),\n t = vLast.type || 'List';\n return xs.slice(0, -1).reduceRight(\n (ys, x) => liftA2(cons)(f(x))(ys),\n liftA2(cons)(vLast)(pureT(t)([]))\n );\n })() : [\n []\n ];\n\n\n // uncons :: [a] -> Maybe (a, [a])\n const uncons = xs => {\n // Just a tuple of the head of xs and its tail,\n // Or Nothing if xs is an empty list.\n const lng = length(xs);\n return (0 < lng) ? (\n Infinity > lng ? (\n Just(Tuple(xs[0])(xs.slice(1))) // Finite list\n ) : (() => {\n const nxt = take(1)(xs);\n return 0 < nxt.length ? (\n Just(Tuple(nxt[0])(xs))\n ) : Nothing();\n })() // Lazy generator\n ) : Nothing();\n };\n\n\n // uncurry :: (a -> b -> c) -> ((a, b) -> c)\n const uncurry = f =>\n // A function over a pair, derived\n // from a curried function.\n x => ((...args) => {\n const\n xy = 1 < args.length ? (\n args\n ) : args[0];\n return f(xy[0])(xy[1]);\n })(x);\n\n\n // unlines :: [String] -> String\n const unlines = xs =>\n // A single string formed by the intercalation\n // of a list of strings with the newline character.\n xs.join('\\n');\n\n\n // zip :: [a] -> [b] -> [(a, b)]\n const zip = xs =>\n // Use of `take` and `length` here allows for zipping with non-finite\n // lists - i.e. generators like cycle, repeat, iterate.\n ys => {\n const\n lng = Math.min(length(xs), length(ys)),\n vs = take(lng)(ys);\n return take(lng)(xs).map(\n (x, i) => Tuple(x)(vs[i])\n );\n };\n\n // Use of `take` and `length` here allows zipping with non-finite lists\n // i.e. generators like cycle, repeat, iterate.\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f => xs => ys => {\n const lng = Math.min(length(xs), length(ys));\n return Infinity > lng ? (() => {\n const\n as = take(lng)(xs),\n bs = take(lng)(ys);\n return Array.from({\n length: lng\n }, (_, i) => f(as[i])(\n bs[i]\n ));\n })() : zipWithGen(f)(xs)(ys);\n };\n\n\n // zipWithGen :: (a -> b -> c) ->\n // Gen [a] -> Gen [b] -> Gen [c]\n const zipWithGen = f => ga => gb => {\n function* go(ma, mb) {\n let\n a = ma,\n b = mb;\n while (!a.Nothing && !b.Nothing) {\n let\n ta = a.Just,\n tb = b.Just\n yield(f(fst(ta))(fst(tb)));\n a = uncons(snd(ta));\n b = uncons(snd(tb));\n }\n }\n return go(uncons(ga), uncons(gb));\n };\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "def isCusip:\n length == 9 and\n explode as $s\n | {sum: 0, i: 0}\n | until(. == false or .i == 8;\n $s[.i] as $c\n | (if ($c >= 48 and $c <= 57) # '0' to '9'\n then $c - 48\n elif ($c >= 65 and $c <= 90) # 'A' to 'Z'\n then $c - 55\n elif $c == 42 # '*'\n then 36\n elif $c == 64 # '@'\n then 37\n elif $c == 35 # '#'\n then 38\n else false # return false\n end ) as $v\n | if $v == false then false\n else # check if odd as using 0-based indexing\n (if (.i%2 == 1) then 2 * $v else $v end) as $v\n | .sum += (($v/10)|floor) + $v%10\n | .i += 1\n end )\n | if . == false then false\n else $s[8] - 48 == (10 - (.sum%10)) % 10\n end;\n\ndef candidates: [\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n];\n\ncandidates[]\n| \"\\(.) -> \\(if isCusip then \"correct\" else \"incorrect\" end)\"\n", "language": "Jq" }, { "code": "module CUSIP\n\nfunction _lastdigitcusip(input::AbstractString)\n input = uppercase(input)\n s = 0\n\n for (i, c) in enumerate(input)\n if isdigit(c)\n v = Int(c) - 48\n elseif isalpha(c)\n v = Int(c) - 64 + 9\n elseif c == '*'\n v = 36\n elseif c == '@'\n v = 37\n elseif c == '#'\n v = 38\n end\n\n if iseven(i); v *= 2 end\n s += div(v, 10) + rem(v, 10)\n end\n\n return Char(rem(10 - rem(s, 10), 10) + 48)\nend\n\ncheckdigit(input::AbstractString) = input[9] == _lastdigitcusip(input[1:8])\n\nend # module CUSIP\n\nfor code in (\"037833100\", \"17275R102\", \"38259P508\", \"594918104\", \"68389X106\", \"68389X105\")\n println(\"$code is \", CUSIP.checkdigit(code) ? \"correct.\" : \"not correct.\")\nend\n", "language": "Julia" }, { "code": "// version 1.1.0\n\nfun isCusip(s: String): Boolean {\n if (s.length != 9) return false\n var sum = 0\n for (i in 0..7) {\n val c = s[i]\n var v = when (c) {\n in '0'..'9' -> c.toInt() - 48\n in 'A'..'Z' -> c.toInt() - 55 // lower case letters apparently invalid\n '*' -> 36\n '@' -> 37\n '#' -> 38\n else -> return false\n }\n if (i % 2 == 1) v *= 2 // check if odd as using 0-based indexing\n sum += v / 10 + v % 10\n }\n return s[8].toInt() - 48 == (10 - (sum % 10)) % 10\n}\n\nfun main(args: Array<String>) {\n val candidates = listOf(\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n )\n for (candidate in candidates)\n println(\"$candidate -> ${if(isCusip(candidate)) \"correct\" else \"incorrect\"}\")\n}\n", "language": "Kotlin" }, { "code": "val .isCusip = fn(.s) {\n if .s is not string or len(.s) != 9 {\n return false\n }\n\n val .basechars = '0'..'9' ~ 'A'..'Z' ~ \"*@#\"\n\n val .sum = for[=0] .i of 8 {\n var .v = index(s2s(.s, .i), .basechars)\n if not .v: return false\n .v = .v[1]-1\n if .i div 2: .v *= 2\n _for += .v \\ 10 + .v rem 10\n }\n\n .s[9]-'0' == (10-(.sum rem 10)) rem 10\n}\n\nval .candidates = fw/037833100 17275R102 38259P508 594918104 68389X106 68389X105/\n\nfor .c in .candidates {\n writeln .c, \": \", if(.isCusip(.c): \"good\" ; \"bad\")\n}\n", "language": "Langur" }, { "code": "val .isCusip = fn(.s) {\n if .s is not string or len(.s) != 9 {\n return false\n }\n\n val .sum = for[=0] .i of 8 {\n val .c = .s[.i]\n var .v = 0\n\n switch[and] .c {\n case >= '0', <= '9':\n .v = .c-'0'\n\n case >= 'A', <= 'Z':\n .v = .c-55 # .c-'A'+10\n\n case '*': .v = 36\n case '@': .v = 37\n case '#': .v = 38\n\n default: return false\n }\n\n if .i div 2: .v *= 2\n _for += .v \\ 10 + .v rem 10\n }\n\n .s[9]-'0' == (10-(.sum rem 10)) rem 10\n}\n\nval .candidates = w/037833100 17275R102 38259P508 594918104 68389X106 68389X105/\n\nfor .c in .candidates {\n writeln .c, \": \", if(.isCusip(.c): \"good\" ; \"bad\")\n}\n", "language": "Langur" }, { "code": "function checkDigit (cusip)\n if #cusip ~= 8 then return false end\n\n local sum, c, v, p = 0\n for i = 1, 8 do\n c = cusip:sub(i, i)\n if c:match(\"%d\") then\n v = tonumber(c)\n elseif c:match(\"%a\") then\n p = string.byte(c) - 55\n v = p + 9\n elseif c == \"*\" then\n v = 36\n elseif c == \"@\" then\n v = 37\n elseif c == \"#\" then\n v = 38\n end\n if i % 2 == 0 then\n v = v * 2\n end\n\n sum = sum + math.floor(v / 10) + v % 10\n end\n\n return tostring((10 - (sum % 10)) % 10)\nend\n\nlocal testCases = {\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n}\nfor _, CUSIP in pairs(testCases) do\n io.write(CUSIP .. \": \")\n if checkDigit(CUSIP:sub(1, 8)) == CUSIP:sub(9, 9) then\n print(\"VALID\")\n else\n print(\"INVALID\")\n end\nend\n", "language": "Lua" }, { "code": "ClearAll[Cusip]\nrules = Thread[(ToString /@ Range[0, 9]) -> Range[0, 9]]~Join~\n Thread[CharacterRange[\"A\", \"Z\"] -> Range[26] + 9]~Join~\n Thread[Characters[\"*@#\"] -> {36, 37, 38}];\nCusip[cusip_String] := Module[{s = cusip, sum = 0, c, value, check},\n If[StringLength[s] != 9,\n Print[\"Cusip must be 9 characters!\"];\n False\n ,\n s = Characters[ToUpperCase[s]];\n Do[\n c = s[[i]];\n value = c /. rules;\n If[EvenQ[i], value *= 2];\n sum += Floor[value/10] + Mod[value, 10];\n ,\n {i, 8}\n ];\n check = Mod[(10 - Mod[sum, 10]), 10];\n s[[-1]] === ToString[check]\n ]\n ]\nCusip /@ {\"037833100\", \"17275R102\", \"38259P508\", \"594918104\", \"68389X106\", \"68389X105\"}\n", "language": "Mathematica" }, { "code": "isCusip = function(s)\n if s.len != 9 then return false\n sum = 0\n for i in range(0, 7)\n c = s[i]\n v = 0\n if c >= \"0\" and c <= \"9\" then\n v = code(c) - 48\n else if c >= \"A\" and c <= \"Z\" then\n v = code(c) - 55\n else if c == \"*\" then\n v = 36\n else if c == \"@\" then\n v = 37\n else if c == \"#\" then\n v = 38\n else\n return false\n end if\n if i%2 == 1 then v *= 2 // check if odd as using 0-based indexing\n sum += floor(v/10) + v%10\n end for\n return code(s[8]) - 48 == (10 - (sum%10)) % 10\nend function\n\ncandidates = [\n \"037833100\", \"17275R102\", \"38259P508\",\n \"594918104\", \"68389X106\", \"68389X105\",\n]\nfor candidate in candidates\n s = \"valid\"\n if not isCusip(candidate) then s = \"invalid\"\n print candidate + \" -> \" + s\nend for\n", "language": "MiniScript" }, { "code": "MODULE CUSIP;\nFROM FormatString IMPORT FormatString;\nFROM Terminal IMPORT WriteString,WriteLn,ReadChar;\n\nPROCEDURE WriteInt(n : INTEGER);\nVAR buf : ARRAY[0..10] OF CHAR;\nBEGIN\n FormatString(\"%i\", buf, n);\n WriteString(buf)\nEND WriteInt;\n\nPROCEDURE cusipCheckDigit(cusip : ARRAY OF CHAR) : INTEGER;\nVAR\n i,v,sum : INTEGER;\nBEGIN\n i := 0;\n sum := 0;\n WHILE cusip[i] # 0C DO\n IF ('0' <= cusip[i]) AND (cusip[i] <= '9') THEN\n v := ORD(cusip[i]) - 48 (* 0 *)\n ELSIF ('A' <= cusip[i]) AND (cusip[i] <= 'Z') THEN\n v := ORD(cusip[i]) - 65 (* A *) + 10\n ELSIF cusip[i] = '*' THEN\n v := 36\n ELSIF cusip[i] = '@' THEN\n v := 37\n ELSIF cusip[i] = '#' THEN\n v := 38\n ELSE\n RETURN -1\n END;\n IF i MOD 2 = 1 THEN v := 2 * v END;\n IF i < 8 THEN\n sum := sum + (v DIV 10) + (v MOD 10);\n END;\n INC(i)\n END;\n\n IF i # 9 THEN RETURN -1 END;\n RETURN (10 - (sum MOD 10)) MOD 10\nEND cusipCheckDigit;\n\nPROCEDURE isValidCusip(cusip : ARRAY OF CHAR) : BOOLEAN;\nVAR\n check : INTEGER;\nBEGIN\n check := cusipCheckDigit(cusip);\n IF check < 0 THEN RETURN FALSE END;\n RETURN cusip[8] = CHR(48 (* 0 *) + check)\nEND isValidCusip;\n\nPROCEDURE Print(cusip : ARRAY OF CHAR);\nBEGIN\n WriteString(cusip);\n IF isValidCusip(cusip) THEN\n WriteString(\" : Valid\")\n ELSE\n WriteString(\" : Invalid\")\n END;\n WriteLn\nEND Print;\n\n(* main *)\nBEGIN\n WriteString(\"CUSIP Verdict\");\n WriteLn;\n\n Print(\"037833100\");\n Print(\"17275R102\");\n Print(\"38259P508\");\n Print(\"594918104\");\n Print(\"68389X106\");\n Print(\"68389X105\");\n\n ReadChar\nEND CUSIP.\n", "language": "Modula-2" }, { "code": "def cusip_checksum(cusip)\n alpha = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n num = \"0123456789\"\n sum = 0\n\n for i in range(1, 8)\n c = cusip[i - 1]\n v = 0\n if c in num\n v = int(c)\n else if c in alpha\n p = alpha[c] + 1\n v = p + 9\n else if c in \"*@#\"\n v = \"*@#\"[c] + 36\n end\n if (i % 2) = 0\n v *= 2\n end\n\n sum += int(v / 10) + (v % 10)\n end\n\n return (10 - (sum % 10)) % 10\nend\n\nif main\n codes = {\"037833100\", \"17275R102\", \"38259P508\",\\\n \"594918104\", \"68389X106\", \"68389X105\"}\n\n for code in codes\n if int(code[len(code) - 1]) = cusip_checksum(code)\n println code + \" is valid\"\n else\n println code + \" is invalid\"\n end\n end\nend\n", "language": "Nanoquery" }, { "code": "import strutils\n\nproc cusipCheck(cusip: string): bool =\n if cusip.len != 9:\n return false\n\n var\n sum, v = 0\n for i, c in cusip[0 .. ^2]:\n if c.isDigit:\n v = parseInt($c)\n elif c.isUpperAscii:\n v = ord(c) - ord('A') + 10\n elif c == '*':\n v = 36\n elif c == '@':\n v = 37\n elif c == '#':\n v = 38\n\n if i mod 2 == 1:\n v *= 2\n\n sum += v div 10 + v mod 10\n let check = (10 - (sum mod 10)) mod 10\n return $check == $cusip[^1]\n\nproc main =\n let codes = [\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n ]\n\n for code in codes:\n echo code, \": \", if cusipCheck(code): \"Valid\" else: \"Invalid\"\n\nmain()\n", "language": "Nim" }, { "code": "class Cusip {\n function : native : IsCusip(s : String) ~ Bool {\n if(s->Size() <> 9) {\n return false;\n };\n\n sum := 0;\n for(i := 0; i < 7; i+=1;) {\n c := s->Get(i);\n\n v : Int;\n if (c >= '0' & c <= '9') {\n v := c - 48;\n } else if (c >= 'A' & c <= 'Z') {\n v := c - 55; # lower case letters apparently invalid\n } else if (c = '*') {\n v := 36;\n } else if (c = '@') {\n v := 37;\n } else if (c = '#') {\n v := 38;\n } else {\n return false;\n };\n\n # check if odd as using 0-based indexing\n if(i % 2 = 1) {\n v *= 2;\n };\n\n sum += v / 10 + v % 10;\n };\n\n return s->Get(8) - 48 = (10 - (sum % 10)) % 10;\n }\n\n function : Main(args : String[]) ~ Nil {\n candidates := [\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n ];\n\n each(i : candidates) {\n candidate := candidates[i];\n \"{$candidate} => \"->Print();\n if(IsCusip(candidate)) {\n \"correct\"->PrintLine();\n }\n else {\n \"incorrect\"->PrintLine();\n };\n };\n }\n}\n", "language": "Objeck" }, { "code": "$cv{$_} = $i++ for '0'..'9', 'A'..'Z', '*', '@', '#';\n\nsub cusip_check_digit {\n my @cusip = split m{}xms, shift;\n my $sum = 0;\n\n for $i (0..7) {\n return 'Invalid character found' unless $cusip[$i] =~ m{\\A [[:digit:][:upper:]*@#] \\z}xms;\n $v = $cv{ $cusip[$i] };\n $v *= 2 if $i%2;\n $sum += int($v/10) + $v%10;\n }\n\n $check_digit = (10 - ($sum%10)) % 10;\n $check_digit == $cusip[8] ? '' : ' (incorrect)';\n}\n\nmy %test_data = (\n '037833100' => 'Apple Incorporated',\n '17275R102' => 'Cisco Systems',\n '38259P508' => 'Google Incorporated',\n '594918104' => 'Microsoft Corporation',\n '68389X106' => 'Oracle Corporation',\n '68389X105' => 'Oracle Corporation',\n);\n\nprint \"$_ $test_data{$_}\" . cusip_check_digit($_) . \"\\n\" for sort keys %test_data;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">CusipCheckDigit</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">cusip</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">v</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cch</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">cch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">256</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'0'</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #008000;\">'9'</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">cch</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #008000;\">'0'</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'A'</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #008000;\">'Z'</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">cch</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">55</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">cch</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #008000;\">'*'</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">36</span>\n <span style=\"color: #000000;\">cch</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #008000;\">'@'</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">37</span>\n <span style=\"color: #000000;\">cch</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #008000;\">'#'</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">38</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cusip</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">9</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">'\\0'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cusip</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">8</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">cusip</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">v</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">cch</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">=-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">v</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">cusip</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #008000;\">'0'</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"037833100\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- Apple Incorporated</span>\n <span style=\"color: #008000;\">\"17275R102\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- Cisco Systems</span>\n <span style=\"color: #008000;\">\"38259P508\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- Google Incorporated</span>\n <span style=\"color: #008000;\">\"594918104\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- Microsoft Corporation</span>\n <span style=\"color: #008000;\">\"68389X106\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- Oracle Corporation (incorrect)</span>\n <span style=\"color: #008000;\">\"68389X105\"</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- Oracle Corporation</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">ti</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s : %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #008000;\">\"invalid\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"valid\"</span><span style=\"color: #0000FF;\">}[</span><span style=\"color: #000000;\">CusipCheckDigit</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "function IsCusip(string $s) {\n if (strlen($s) != 9) return false;\n $sum = 0;\n for ($i = 0; $i <= 7; $i++) {\n $c = $s[$i];\n if (ctype_digit($c)) {\n // if character is numeric, get character's numeric value\n $v = intval($c);\n } elseif (ctype_alpha($c)) {\n // if character is alphabetic, get character's ordinal position in alphabet\n $position = ord(strtoupper($c)) - ord('A') + 1;\n $v = $position + 9;\n } elseif ($c == \"*\") {\n $v = 36;\n } elseif ($c == \"@\") {\n $v = 37;\n } elseif ($c == \"#\") {\n $v = 38;\n } else {\n return false;\n }\n // is this character position even?\n if ($i % 2 == 1) {\n $v *= 2;\n }\n // calculate the checksum digit\n $sum += floor($v / 10 ) + ( $v % 10 );\n }\n return ord($s[8]) - 48 == (10 - ($sum % 10)) % 10;\n}\n\n$cusips = array(\"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\");\n\nforeach ($cusips as $cusip) echo $cusip . \" -> \" . (IsCusip($cusip) ? \"valid\" : \"invalid\") . \"\\n\";\n", "language": "PHP" }, { "code": "(de cusip (Str)\n (let (Str (mapcar char (chop Str)) S 0)\n (for (I . C) (head 8 Str)\n (let V\n (cond\n ((<= 48 C 57) (- C 48))\n ((<= 65 C 90) (+ 10 (- C 65)))\n ((= C 42) 36)\n ((= C 64) 37)\n ((= C 35) 38) )\n (or\n (bit? 1 I)\n (setq V (>> -1 V)) )\n (inc\n 'S\n (+ (/ V 10) (% V 10)) ) ) )\n (=\n (- (last Str) 48)\n (% (- 10 (% S 10)) 10) ) ) )\n\n(println\n (mapcar\n cusip\n (quote\n \"037833100\"\n \"17275R102\"\n \"38259P508\"\n \"68389X106\"\n \"68389X105\" ) ) )\n", "language": "PicoLisp" }, { "code": "function Get-CheckDigitCUSIP {\n [CmdletBinding()]\n [OutputType([int])]\n Param ( # Validate input\n [Parameter(Mandatory=$true, Position=0)]\n [ValidatePattern( '^[A-Z0-9@#*]{8}\\d$' )] # @#*\n [ValidateScript({$_.Length -eq 9})]\n [string]\n $cusip\n )\n $sum = 0\n 0..7 | ForEach { $c = $cusip[$_] ; $v = $null\n if ([Char]::IsDigit($c)) { $v = [char]::GetNumericValue($c) }\n if ([Char]::IsLetter($c)) { $v = [int][char]$c - [int][char]'A' +10 }\n if ($c -eq '*') { $v = 36 }\n if ($c -eq '@') { $v = 37 }\n if ($c -eq '#') { $v = 38 }\n if($_ % 2){ $v += $v }\n $sum += [int][Math]::Floor($v / 10 ) + ($v % 10)\n }\n [int]$checkDigit_calculated = ( 10 - ($sum % 10) ) % 10\n return( $checkDigit_calculated )\n}\n\nfunction Test-IsCUSIP {\n [CmdletBinding()]\n [OutputType([bool])]\n Param (\n [Parameter(Mandatory=$true, Position=0)]\n [ValidatePattern( '^[A-Z0-9@#*]{8}\\d$' )]\n [ValidateScript({$_.Length -eq 9})]\n [string]\n $cusip\n )\n [int]$checkDigit_told = $cusip[-1].ToString()\n $checkDigit_calculated = Get-CheckDigitCUSIP $cusip\n ($checkDigit_calculated -eq $checkDigit_told)\n}\n\n$data = @\"\n037833100`tApple Incorporated\n17275R102`tCisco Systems\n38259P508`tGoogle Incorporated\n594918104`tMicrosoft Corporation\n68389X106`tOracle Corporation (incorrect)\n68389X105`tOracle Corporation\n\"@ -split \"`n\"\n$data |%{ Test-IsCUSIP $_.Split(\"`t\")[0] }\n", "language": "PowerShell" }, { "code": "#!/usr/bin/env python3\n\nimport math\n\ndef cusip_check(cusip):\n if len(cusip) != 9:\n raise ValueError('CUSIP must be 9 characters')\n\n cusip = cusip.upper()\n total = 0\n for i in range(8):\n c = cusip[i]\n if c.isdigit():\n v = int(c)\n elif c.isalpha():\n p = ord(c) - ord('A') + 1\n v = p + 9\n elif c == '*':\n v = 36\n elif c == '@':\n v = 37\n elif c == '#':\n v = 38\n\n if i % 2 != 0:\n v *= 2\n\n total += int(v / 10) + v % 10\n check = (10 - (total % 10)) % 10\n return str(check) == cusip[-1]\n\nif __name__ == '__main__':\n codes = [\n '037833100',\n '17275R102',\n '38259P508',\n '594918104',\n '68389X106',\n '68389X105'\n ]\n for code in codes:\n print(f'{code} -> {cusip_check(code)}')\n", "language": "Python" }, { "code": "'''CUSIP'''\n\nfrom itertools import (cycle, islice, starmap)\nfrom functools import (reduce)\nfrom operator import (add)\nfrom enum import (Enum)\n\n\n# isCusip :: Dict -> String -> Bool\ndef isCusip(dct):\n '''Test for the validity of a CUSIP string in the\n context of a supplied dictionary of char values'''\n def go(s):\n ns = [dct[c] for c in list(s) if c in dct]\n return 9 == len(ns) and (\n ns[-1] == (\n 10 - (\n sum(zipWith(\n lambda f, x: add(*divmod(f(x), 10))\n )(cycle([identity, double]))(\n take(8)(ns)\n )) % 10\n )\n ) % 10\n )\n return go\n\n\n# cusipCharDict :: () -> Dict Char Int\ndef cusipCharDict():\n '''Dictionary of integer values for CUSIP characters'''\n def kv(a, ic):\n i, c = ic\n a[c] = i\n return a\n return reduce(\n kv,\n enumerate(\n enumFromTo('0')('9') + (\n enumFromTo('A')('Z') + list('*&#')\n )\n ),\n {}\n )\n\n\n# TEST -------------------------------------------------\n# main :: IO ()\ndef main():\n '''Tests'''\n\n # cusipTest :: String -> Bool\n cusipTest = isCusip(cusipCharDict())\n\n print(\n tabulated('Valid as CUSIP string:')(\n cusipTest\n )([\n '037833100',\n '17275R102',\n '38259P508',\n '594918104',\n '68389X106',\n '68389X105'\n ])\n )\n\n# GENERIC -------------------------------------------------\n\n\n# double :: Num -> Num\ndef double(x):\n '''Wrapped here as a function for the zipWith expression'''\n return 2 * x\n\n\n# enumFromTo :: Enum a => a -> a -> [a]\ndef enumFromTo(m):\n '''Enumeration of values [m..n]'''\n def go(x, y):\n t = type(m)\n i = fromEnum(x)\n d = 0 if t != float else (x - i)\n return list(map(\n lambda x: toEnum(t)(d + x),\n range(i, 1 + fromEnum(y))\n ) if int != t else range(x, 1 + y))\n return lambda n: go(m, n)\n\n\n# fromEnum :: Enum a => a -> Int\ndef fromEnum(x):\n '''Index integer for enumerable value.'''\n return ord(x) if str == type(x) else (\n x.value if isinstance(x, Enum) else int(x)\n )\n\n\n# mul :: Num -> Num -> Num\ndef mul(x):\n '''Function version of (*) operator;\n a curried equivalent of operator.mul'''\n return lambda y: x * y\n\n\n# identity :: a -> a\ndef identity(x):\n '''The identity function.\n The usual 'id' is reserved in Python.'''\n return x\n\n\n# tabulated :: String -> (a -> b) -> [a] -> String\ndef tabulated(s):\n '''heading -> function -> input List -> tabulated output string'''\n def go(f, xs):\n def width(x):\n return len(str(x))\n w = width(max(xs, key=width))\n return s + '\\n' + '\\n'.join([\n str(x).rjust(w, ' ') + ' -> ' + str(f(x)) for x in xs\n ])\n return lambda f: lambda xs: go(f, xs)\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.'''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, list)\n else list(islice(xs, n))\n )\n\n\n# toEnum :: Type -> Int -> a\ndef toEnum(t):\n '''Enumerable value from index integer'''\n dct = {\n int: int,\n float: float,\n str: chr,\n bool: bool\n }\n return lambda x: dct[t](x) if t in dct else t(x)\n\n\n# zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\ndef zipWith(f):\n '''Zipping with a custom (rather than tuple) function'''\n return lambda xs: lambda ys: (\n list(starmap(f, zip(xs, ys)))\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": " [ -1 split 0 peek char 0 -\n swap 0 swap\n witheach\n [ [ dup char 0 char 9 1+ within iff\n [ char 0 - ] done\n dup char A char Z 1+ within iff\n [ char A - 10 + ] done\n dup char * = iff\n [ drop 36 ] done\n dup char @ = iff\n [ drop 37 ] done\n dup char # = iff\n [ drop 38 ] done\n $ \"Unexpected character '\" swap\n join $ \"' in CUSIP.\" join fail ]\n i^ 1 & if [ 2 * ]\n 10 /mod + + ]\n 10 mod 10 swap - 10 mod = ] is cusip ( $ --> b )\n\n [ dup echo$ cusip iff\n [ say \" is correct.\" ]\n else [ say \" is incorrect.\" ]\n cr ] is task ( $ --> )\n\n $ \"037833100 17275R102 38259P508 594918104 68389X106 68389X105\"\n nest$ witheach task\n", "language": "Quackery" }, { "code": "#lang racket\n(require srfi/14)\n\n(define 0-char (char->integer #\\0))\n(define A-char (char->integer #\\A))\n\n(define (cusip-value c)\n (cond\n [(char-set-contains? char-set:digit c)\n (- (char->integer c) 0-char)]\n [(char-set-contains? char-set:upper-case c)\n (+ 10 (- (char->integer c) A-char))]\n [(char=? c #\\*) 36]\n [(char=? c #\\@) 37]\n [(char=? c #\\#) 38]))\n\n(define (cusip-check-digit cusip)\n (modulo\n (- 10\n (modulo\n (for/sum\n ((i (sequence-map add1 (in-range 8))) (c (in-string cusip)))\n (let* ((v (cusip-value c)) (v′ (if (even? i) (* v 2) v)))\n (+ (quotient v′ 10) (modulo v′ 10)))) 10)) 10))\n\n(define (CUSIP? s)\n (char=? (string-ref s (sub1 (string-length s)))\n (integer->char (+ 0-char (cusip-check-digit s)))))\n\n(module+ test\n (require rackunit)\n (check-true (CUSIP? \"037833100\"))\n (check-true (CUSIP? \"17275R102\"))\n (check-true (CUSIP? \"38259P508\"))\n (check-true (CUSIP? \"594918104\"))\n (check-false (CUSIP? \"68389X106\"))\n (check-true (CUSIP? \"68389X105\")))\n", "language": "Racket" }, { "code": "sub divmod ($v, $r) { $v div $r, $v mod $r }\nmy %chr = (flat 0..9, 'A'..'Z', <* @ #>) Z=> 0..*;\n\nsub cuisp-check ($cuisp where *.chars == 9) {\n my ($code, $chk) = $cuisp.comb(8);\n my $sum = [+] $code.comb.kv.map: { [+] (($^k % 2 + 1) * %chr{$^v}).&divmod(10) };\n so (10 - $sum mod 10) mod 10 eq $chk;\n}\n\n# TESTING\nsay \"$_: \", $_.&cuisp-check for <\n037833100\n17275R102\n38259P508\n594918104\n68389X106\n68389X105\n>\n", "language": "Raku" }, { "code": "/*REXX program validates that the last digit (the check digit) of a CUSIP is valid. */\n@.=\nparse arg @.1 .\nif @.1=='' | @.1==\",\" then do; @.1= 037833100 /* Apple Incorporated */\n @.2= 17275R102 /* Cisco Systems */\n @.3= 38259P508 /* Google Incorporated */\n @.4= 594918104 /* Microsoft Corporation */\n @.5= 68389X106 /* Oracle Corporation (incorrect)*/\n @.6= 68389X105 /* Oracle Corporation */\n end\n\n do j=1 while @.j\\=''; chkDig=CUSIPchk(@.j) /*calculate check digit from func*/\n OK=word(\"isn't is\", 1 + (chkDig==right(@.j,1) ) ) /*validate check digit with func*/\n say 'CUSIP ' @.j right(OK, 6) \"valid.\" /*display the CUSIP and validity.*/\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nCUSIPchk: procedure; arg x 9; $=0; abc= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n do k=1 for 8\n y=substr(x, k, 1)\n select\n when datatype(y,'W') then #=y\n when datatype(y,'U') then #=pos(y, abc) + 9\n when y=='*' then #=36\n when y=='@' then #=37\n when y=='#' then #=38\n otherwise return 0 /*invalid character.*/\n end /*select*/\n if k//2==0 then #=#+# /*K even? Double it*/\n $=$ + #%10 + #//10\n end /*k*/\n return (10- $//10) // 10\n", "language": "REXX" }, { "code": "/*REXX program validates that the last digit (the check digit) of a CUSIP is valid. */\n@.=\nparse arg @.1 .\nif @.1=='' | @.1==\",\" then do; @.1= 037833100 /* Apple Incorporated */\n @.2= 17275R102 /* Cisco Systems */\n @.3= 38259P508 /* Google Incorporated */\n @.4= 594918104 /* Microsoft Corporation */\n @.5= 68389X106 /* Oracle Corporation (incorrect)*/\n @.6= 68389X105 /* Oracle Corporation */\n end\n\n do j=1 while @.j\\=''; chkDig=CUSIPchk(@.j) /*calculate check digit from func*/\n OK=word(\"isn't is\", 1 + (chkDig==right(@.j,1) ) ) /*validate check digit with func*/\n say 'CUSIP ' @.j right(OK, 6) \"valid.\" /*display the CUSIP and validity.*/\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nCUSIPchk: procedure; arg x 9; $=0; abc= '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#'\n /* [↓] if Y isn' found, then POS returns zero.*/\n do k=1 for 8; y=substr(x,k,1) /*get a character. */\n #=pos(y, abc) - 1 /*get its position.*/\n if # == -1 then return 0 /*invalid character*/\n if k//2== 0 then #=#+# /*K even? double it*/\n $=$ + #%10 + #//10\n end /*k*/\n return (10-$//10) // 10\n", "language": "REXX" }, { "code": "# Project : CUSIP\n\ninputstr = list(6)\ninputstr[1] = \"037833100\"\ninputstr[2] = \"17275R102\"\ninputstr[3] = \"38259P508\"\ninputstr[4] = \"594918104\"\ninputstr[5] = \"68389X106\"\ninputstr[6] = \"68389X105\"\nfor n = 1 to len(inputstr)\n cusip(inputstr[n])\nnext\n\nfunc cusip(inputstr)\n if len(inputstr) != 9\n see \" length is incorrect, invalid cusip\"\n return\n ok\n v = 0\n sum = 0\n for i = 1 to 8\n flag = 0\n x = ascii(inputstr[i])\n if x >= ascii(\"0\") and x <= ascii(\"9\")\n v = x - ascii(\"0\")\n flag = 1\n ok\n if x >= ascii(\"A\") and x <= ascii(\"Z\")\n v = x - 55\n flag = 1\n ok\n if x = ascii(\"*\")\n v= 36\n flag = 1\n ok\n if x = ascii(\"@\")\n v = 37\n flag = 1\n ok\n if x = ascii(\"#\")\n v = 38\n flag = 1\n ok\n if flag = 0\n see \" found a invalid character, invalid cusip\" + nl\n ok\n if (i % 2) = 0\n v = v * 2\n ok\n sum = sum + floor(v / 10) + v % 10\n next\n sum = (10 - (sum % 10)) % 10\n if sum = (ascii(inputstr[9]) - ascii(\"0\"))\n see inputstr + \" is valid\" + nl\n else\n see inputstr + \" is invalid\" + nl\n ok\n", "language": "Ring" }, { "code": "#!/usr/bin/env ruby\n\ndef check_cusip(cusip)\n abort('CUSIP must be 9 characters') if cusip.size != 9\n\n sum = 0\n cusip.split('').each_with_index do |char, i|\n next if i == cusip.size - 1\n case\n when char.scan(/\\D/).empty?\n v = char.to_i\n when char.scan(/\\D/).any?\n pos = char.upcase.ord - 'A'.ord + 1\n v = pos + 9\n when char == '*'\n v = 36\n when char == '@'\n v = 37\n when char == '#'\n v = 38\n end\n\n v *= 2 unless (i % 2).zero?\n sum += (v/10).to_i + (v % 10)\n end\n\n check = (10 - (sum % 10)) % 10\n return 'VALID' if check.to_s == cusip.split('').last\n 'INVALID'\nend\n\nCUSIPs = %w[\n 037833100 17275R102 38259P508 594918104 68389X106 68389X105\n]\n\nCUSIPs.each do |cusip|\n puts \"#{cusip}: #{check_cusip(cusip)}\"\nend\n", "language": "Ruby" }, { "code": "TABLE = (\"0\"..\"9\").chain(\"A\"..\"Z\", %w(* @ #)).zip(0..).to_h\n\ndef valid_CUSIP?(str)\n sum = str[0..-2].chars.each_slice(2).sum do |c1,c2|\n TABLE[c1].divmod(10).sum + (TABLE[c2]*2).divmod(10).sum\n end\n str[-1].to_i == (10 - (sum % 10)) % 10\nend\n\nCUSIPs = %w(037833100 17275R102 38259P508 594918104 68389X106 68389X105)\nCUSIPs.each{|cusip| puts \"#{cusip}: #{valid_CUSIP? cusip}\"}\n", "language": "Ruby" }, { "code": "fn cusip_check(cusip: &str) -> bool {\n if cusip.len() != 9 {\n return false;\n }\n\n let mut v = 0;\n let capital_cusip = cusip.to_uppercase();\n let char_indices = capital_cusip.as_str().char_indices().take(7);\n\n let total = char_indices.fold(0, |total, (i, c)| {\n v = match c {\n '*' => 36,\n '@' => 37,\n '#' => 38,\n _ if c.is_digit(10) => c.to_digit(10).unwrap() as u8,\n _ if c.is_alphabetic() => (c as u8) - b'A' + 1 + 9,\n _ => v,\n };\n\n if i % 2 != 0 {\n v *= 2\n }\n total + (v / 10) + v % 10\n });\n\n let check = (10 - (total % 10)) % 10;\n (check.to_string().chars().nth(0).unwrap()) == cusip.chars().nth(cusip.len() - 1).unwrap()\n}\n\nfn main() {\n let codes = [\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\",\n ];\n for code in &codes {\n println!(\"{} -> {}\", code, cusip_check(code))\n }\n}\n", "language": "Rust" }, { "code": "object Cusip extends App {\n\n val candidates = Seq(\"037833100\", \"17275R102\", \"38259P508\", \"594918104\", \"68389X106\", \"68389X105\")\n\n for (candidate <- candidates)\n printf(f\"$candidate%s -> ${if (isCusip(candidate)) \"correct\" else \"incorrect\"}%s%n\")\n\n private def isCusip(s: String): Boolean = {\n if (s.length != 9) false\n else {\n var sum = 0\n for (i <- 0 until 7) {\n val c = s(i)\n var v = 0\n if (c >= '0' && c <= '9') v = c - 48\n else if (c >= 'A' && c <= 'Z') v = c - 55 // lower case letters apparently invalid\n else if (c == '*') v = 36\n else if (c == '@') v = 37\n else if (c == '#') v = 38\n else return false\n if (i % 2 == 1) v *= 2 // check if odd as using 0-based indexing\n sum += v / 10 + v % 10\n }\n s(8) - 48 == (10 - (sum % 10)) % 10\n }\n }\n\n}\n", "language": "Scala" }, { "code": "#!/usr/local/bin/snobol4 -r\n* cusip.sno\n* -- Committee on Uniform Security Identification Procedures\n* -r : read data placed after the end label.\n* Verify check digit and size of cusip code.\n\n define(\"cusipt()i\") :(cusipt_end)\ncusipt\n chars = &digits &ucase \"*@#\"\n cusipt = table()\n i = 0\ncusipt_1\n chars pos(i) len(1) . c :f(return)\n cusipt[c] = i\n i = i + 1 :(cusipt_1)\ncusipt_end\n\n define(\"check_cusip(line)c,i\") :(check_cusip_end)\ncheck_cusip\n eq(size(line), 9) :f(freturn)\n check_cusip = 0\n i = 0\ncheck_cusip_1\n line pos(i) len(1) . c\n value = t[c]\n value = eq(remdr(i, 2), 1) t[c] * 2\n check_cusip = check_cusip + (value / 10) + remdr(value, 10)\n i = lt(i, 7) i + 1 :s(check_cusip_1)\n check_cusip = remdr(10 - remdr(check_cusip, 10), 10)\n eq(substr(line, 9, 1), check_cusip) :s(return)f(freturn)\ncheck_cusip_end\n\n*** main ***\n t = cusipt()\n\nread line = input :f(end)\n check_cusip(line) :f(bad_cusip)\n output = line \" valid.\" :(read)\nbad_cusip\n output = line \" not valid.\" :(read)\nend\n037833100\n17275R102\n38259P508\n594918104\n68389X106\n68389X105\n68389X10\n68389X1059\n68389x105\n", "language": "SNOBOL4" }, { "code": "struct CUSIP {\n var value: String\n\n private static let alphabet = Array(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n\n init?(value: String) {\n if value.count == 9 && String(value.last!) == CUSIP.checkDigit(cusipString: String(value.dropLast())) {\n self.value = value\n } else if value.count == 8, let checkDigit = CUSIP.checkDigit(cusipString: value) {\n self.value = value + checkDigit\n } else {\n return nil\n }\n }\n\n static func checkDigit(cusipString: String) -> String? {\n guard cusipString.count == 8, cusipString.allSatisfy({ $0.isASCII }) else {\n return nil\n }\n\n let sum = cusipString.uppercased().enumerated().reduce(0, {sum, pair in\n let (i, char) = pair\n var v: Int\n\n switch char {\n case \"*\":\n v = 36\n case \"@\":\n v = 37\n case \"#\":\n v = 38\n case _ where char.isNumber:\n v = char.wholeNumberValue!\n case _:\n v = Int(char.asciiValue! - 65) + 10\n }\n\n if i & 1 == 1 {\n v *= 2\n }\n\n return sum + (v / 10) + (v % 10)\n })\n\n return String((10 - (sum % 10)) % 10)\n }\n}\n\nlet testCases = [\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n]\n\nfor potentialCUSIP in testCases {\n print(\"\\(potentialCUSIP) -> \", terminator: \"\")\n\n switch CUSIP(value: potentialCUSIP) {\n case nil:\n print(\"Invalid\")\n case _:\n print(\"Valid\")\n }\n}\n", "language": "Swift" }, { "code": "proc ordinal-of-alpha {c} { ;# returns ordinal position of c in the alphabet (A=1, B=2...)\n lsearch {_ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z} [string toupper $c]\n}\n\nproc Cusip-Check-Digit {cusip} { ;# algorithm Cusip-Check-Digit(cusip) is\n if {[string length $cusip] != 8} { ;# Input: an 8-character CUSIP\n return false\n }\n\n set sum 0 ;# sum := 0\n for {set i 1} {$i <= 8} {incr i} { ;# for 1 ≤ i ≤ 8 do\n set c [string index $cusip $i-1] ;# c := the ith character of cusip\n if {[string is digit $c]} { ;# if c is a digit then\n set v $c ;# v := numeric value of the digit c\n } elseif {[string is alpha $c]} { ;# else if c is a letter then\n set p [ordinal-of-alpha $c] ;# p := ordinal position of c in the alphabet (A=1, B=2...)\n set v [expr {$p + 9}] ;# v := p + 9\n } elseif {$c eq \"*\"} { ;# else if c = \"*\" then\n set v 36 ;# v := 36\n } elseif {$c eq \"@\"} { ;# else if c = \"@\" then\n set v 37 ;# v := 37\n } elseif {$c eq \"#\"} { ;# else if c = \"#\" then\n set v 38 ;# v := 38\n } ;# end if\n if {$i % 2 == 0} { ;# if i is even then\n set v [expr {$v * 2}] ;# v := v × 2\n } ;# end if\n\n incr sum [expr {$v / 10 + $v % 10}] ;# sum := sum + int ( v div 10 ) + v mod 10\n } ;# repeat\n\n expr {(10 - ($sum % 10)) % 10} ;# return (10 - (sum mod 10)) mod 10\n}\nproc check-cusip {cusip} {\n set last [string index $cusip end]\n set cusip [string range $cusip 0 end-1]\n expr {$last eq [Cusip-Check-Digit $cusip]}\n}\n", "language": "Tcl" }, { "code": "proc check-cusip {code} {\n if {[string length $code] != 9} {\n return false\n }\n set alphabet 0123456789abcdefghijklmnopqrstuvwxyz@#\n set code [split [string tolower $code] \"\"]\n foreach char $code idx {1 2 3 4 5 6 7 8 9} {\n set v [string first $char $alphabet]\n if {$v == -1} {return false}\n if {$idx % 2 == 0} {\n incr v $v\n }\n set v [::tcl::mathop::+ {*}[split $v \"\"]]\n incr sum $v\n }\n expr {$sum % 10 == 0}\n}\n", "language": "Tcl" }, { "code": "proc test {} {\n foreach {cusip name} {\n 037833100 \"Apple Incorporated\"\n 17275R102 \"Cisco Systems\"\n 38259P508 \"Google Incorporated\"\n 594918104 \"Microsoft Corporation\"\n 68389X106 \"Oracle Corporation (incorrect)\"\n 68389X105 \"Oracle Corporation\"\n } {\n puts [format %-40s%s $name [expr {[check-cusip $cusip] ? \"valid\" : \"invalid\"}]]\n puts [format %-40s%s $name [expr {[cusip-check $cusip] ? \"valid\" : \"invalid\"}]]\n }\n}\ntest\n", "language": "Tcl" }, { "code": "fn is_cusip(s string) bool {\n if s.len != 9 { return false }\n mut sum := 0\n for i in 0..8 {\n c := s[i]\n mut v :=0\n match true {\n c >= '0'[0] && c <= '9'[0] {\n v = c - 48\n\t\t\t}\n c >= 'A'[0] && c <= 'Z'[0] {\n v = c - 55\n\t\t\t}\n c == '*'[0] {\n v = 36\n\t\t\t}\n c == '@'[0] {\n v = 37\n\t\t\t}\n c == '#'[0] {\n v = 38\n\t\t\t}\n else {\n return false\n\t\t\t}\n }\n if i % 2 == 1 { v *= 2 } // check if odd as using 0-based indexing\n sum += v/10 + v%10\n }\n return int(s[8]) - 48 == (10 - (sum%10)) % 10\n}\n\nfn main() {\n candidates := [\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\",\n\t]\n\n for candidate in candidates {\n mut b :=' '\n if is_cusip(candidate) {\n b = \"correct\"\n } else {\n b = \"incorrect\"\n }\n println(\"$candidate -> $b\")\n }\n}\n", "language": "V-(Vlang)" }, { "code": "Private Function Cusip_Check_Digit(s As Variant) As Integer\n Dim Sum As Integer, c As String, v As Integer\n For i = 1 To 8\n c = Mid(s, i, 1)\n If IsNumeric(c) Then\n v = Val(c)\n Else\n Select Case c\n Case \"a\" To \"z\"\n v = Asc(c) - Asc(\"a\") + 10\n Case \"A\" To \"Z\"\n v = Asc(c) - Asc(\"A\") + 10\n Case \"*\"\n v = 36\n Case \"@\"\n v = 37\n Case \"#\"\n v = 38\n Case Else\n Debug.Print \"not expected\"\n End Select\n End If\n If i Mod 2 = 0 Then v = v * 2\n Sum = Sum + Int(v \\ 10) + v Mod 10\n Next i\n Cusip_Check_Digit = (10 - (Sum Mod 10)) Mod 10\nEnd Function\n", "language": "VBA" }, { "code": "Module Module1\n\n Function IsCUSIP(s As String) As Boolean\n If s.Length <> 9 Then\n Return False\n End If\n\n Dim sum = 0\n For i = 0 To 7\n Dim c = s(i)\n\n Dim v As Integer\n If \"0\" <= c AndAlso c <= \"9\" Then\n v = Asc(c) - 48\n ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n v = Asc(c) - 55 ' Lower case letters are apparently invalid\n ElseIf c = \"*\" Then\n v = 36\n ElseIf c = \"#\" Then\n v = 38\n Else\n Return False\n End If\n\n If i Mod 2 = 1 Then\n v *= 2 ' check if odd as using 0-based indexing\n End If\n sum += v \\ 10 + v Mod 10\n Next\n Return Asc(s(8)) - 48 = (10 - (sum Mod 10)) Mod 10\n End Function\n\n Sub Main()\n Dim candidates As New List(Of String) From {\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n }\n\n For Each candidate In candidates\n Console.WriteLine(\"{0} -> {1}\", candidate, If(IsCUSIP(candidate), \"correct\", \"incorrect\"))\n Next\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "var isCusip = Fn.new { |s|\n if (s.count != 9) return false\n var sum = 0\n for (i in 0..7) {\n var c = s[i].bytes[0]\n var v\n if (c >= 48 && c <= 57) { // '0' to '9'\n v = c - 48\n } else if (c >= 65 && c <= 90) { // 'A' to 'Z'\n v = c - 55\n } else if (s[i] == \"*\") {\n v = 36\n } else if (s[i] == \"@\") {\n v = 37\n } else if (s[i] == \"#\") {\n v = 38\n } else {\n return false\n }\n if (i%2 == 1) v = v * 2 // check if odd as using 0-based indexing\n sum = sum + (v/10).floor + v%10\n }\n return s[8].bytes[0] - 48 == (10 - (sum%10)) % 10\n}\n\nvar candidates = [\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n]\nfor (candidate in candidates) {\n var b = (isCusip.call(candidate)) ? \"correct\" : \"incorrect\"\n System.print(\"%(candidate) -> %(b)\")\n}\n", "language": "Wren" }, { "code": "string 0; \\use zero-terminated strings\n\nfunc Valid(Cusip); \\Return 'true' if valid CUSIP code\nchar Cusip;\nint Sum, I, C, V;\n[Sum:= 0;\nfor I:= 0 to 8-1 do\n [C:= Cusip(I);\n ChOut(0, C);\n case of\n C>=^0 & C<=^9: V:= C-^0;\n C>=^A & C<=^Z: V:= C-^A+10;\n C=^*: V:=36;\n C=^@: V:=37;\n C=^#: V:=38\n other V:= -1;\n if I&1 then V:= V*2;\n Sum:= Sum + V/10 + rem(0);\n ];\nC:= Cusip(I);\nChOut(0, C);\nV:= rem( (10-rem(Sum/10)) / 10 );\nreturn V = C-^0;\n];\n\nint Cusip, N;\n[Cusip:= [\"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"];\nfor N:= 0 to 6-1 do\n [Text(0, if Valid(Cusip(N))\n then \" is valid\"\n else \" is invalid\");\n CrLf(0);\n ];\n]\n", "language": "XPL0" }, { "code": "sub cusip(inputStr$)\n local i, v, sum, x$\n\n Print inputStr$;\n If Len(inputStr$) <> 9 Print \" length is incorrect, invalid cusip\" : return\n\n For i = 1 To 8\n x$ = mid$(inputStr$, i, 1)\n switch x$\n Case \"*\": v = 36 : break\n Case \"@\": v = 37 : break\n Case \"#\": v = 38 : break\n default:\n if x$ >= \"A\" and x$ <= \"Z\" then\n v = asc(x$) - Asc(\"A\") + 10\n elsif x$ >= \"0\" and x$ <= \"9\" then\n v = asc(x$) - asc(\"0\")\n else\n Print \" found a invalid character, invalid cusip\"\n return\n end if\n End switch\n\n If and(i, 1) = 0 v = v * 2\n sum = sum + int(v / 10) + mod(v, 10)\n Next\n\n sum = mod(10 - mod(sum, 10), 10)\n If sum = asc(mid$(inputStr$, 9, 1)) - Asc(\"0\") Then\n Print \" is valid\"\n Else\n Print \" is invalid\"\n End If\n\nEnd Sub\n\n// ------=< MAIN >=------\n\nData \"037833100\", \"17275R102\", \"38259P508\"\nData \"594918104\", \"68389X106\", \"68389X105\", \"\"\n\nPrint\ndo\n Read inputStr$\n if inputStr$ = \"\" break\n cusip(inputStr$)\nloop\n", "language": "Yabasic" }, { "code": "const std = @import(\"std\");\nconst print = std.debug.print;\n\npub fn CusipCheckDigit(cusip: *const [9:0]u8) bool {\n var i: usize = 0;\n var sum: i32 = 0;\n while (i < 8) {\n const c = cusip[i];\n var v: i32 = undefined;\n if (c <= '9' and c >= '0') {\n v = c - 48;\n }\n else if (c <= 'Z' and c >= 'A') {\n v = c - 55;\n }\n else if (c == '*') {\n v = 36;\n }\n else if (c == '@') {\n v = 37;\n }\n else if (c == '#') {\n v = 38;\n }\n else {\n return false;\n }\n if (i % 2 == 1) {\n v *= 2;\n }\n sum = sum + @divFloor(v, 10) + @mod(v, 10);\n i += 1;\n }\n return (cusip[8] - 48 == @mod((10 - @mod(sum, 10)), 10));\n}\n\npub fn main() void {\n const cusips = [_]*const [9:0]u8 {\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n };\n for (cusips) |cusip| {\n print(\"{s} -> {}\\n\", .{cusip, CusipCheckDigit(cusip)});\n }\n}\n", "language": "Zig" }, { "code": "fcn cusipCheckDigit(cusip){\n var [const] vs=[0..9].chain([\"A\"..\"Z\"],T(\"*\",\"@\",\"#\")).pump(String);\n try{\n sum:=Walker.cycle(1,2).zipWith(fcn(n,c){ v:=vs.index(c)*n; v/10 + v%10 },\n cusip[0,8]).reduce('+);\n ((10 - sum%10)%10 == cusip[8].toInt()) and cusip.len()==9\n }catch{ False }\n}\n", "language": "Zkl" }, { "code": "foreach cusip in (T(\"037833100\", \"17275R102\",\n\t\t \"38259P508\", \"594918104\", \"68389X106\", \"68389X105\")){\n println(cusip,\": \",cusipCheckDigit(cusip));\n}\n", "language": "Zkl" } ]
CUSIP
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Cut_a_rectangle\n", "language": "00-META" }, { "code": "A given rectangle is made from ''m'' × ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles are shown below.\n\n[[file:rect-cut.svg]]\n\nWrite a program that calculates the number of different ways to cut an ''m'' × ''n'' rectangle. Optionally, show each of the cuts.\n\nPossibly related task: [[Maze generation]] for depth-first search.\n\n", "language": "00-TASK" }, { "code": "F cut_it(=h, =w)\n V dirs = [(1, 0), (-1, 0), (0, -1), (0, 1)]\n I h % 2 != 0\n swap(&h, &w)\n I h % 2 != 0\n R 0\n I w == 1\n R 1\n V count = 0\n\n V next = [w + 1, -w - 1, -1, 1]\n V blen = (h + 1) * (w + 1) - 1\n V grid = [0B] * (blen + 1)\n\n F walk(Int y, x, =count) -> Int\n I y == 0 | y == @h | x == 0 | x == @w\n R count + 1\n\n V t = y * (@w + 1) + x\n @grid[t] = @grid[@blen - t] = 1B\n\n L(i) 4\n I !@grid[t + @next[i]]\n count = @walk(y + @dirs[i][0], x + @dirs[i][1], count)\n\n @grid[t] = @grid[@blen - t] = 0B\n R count\n\n V t = h I/ 2 * (w + 1) + w I/ 2\n I w % 2 != 0\n grid[t] = grid[t + 1] = 1B\n count = walk(h I/ 2, w I/ 2 - 1, count)\n V res = count\n count = 0\n count = walk(h I/ 2 - 1, w I/ 2, count)\n R res + count * 2\n E\n grid[t] = 1B\n count = walk(h I/ 2, w I/ 2 - 1, count)\n I h == w\n R count * 2\n count = walk(h I/ 2 - 1, w I/ 2, count)\n R count\n\nL(w) 1..9\n L(h) 1..w\n I (w * h) % 2 == 0\n print(‘#. x #.: #.’.format(w, h, cut_it(w, h)))\n", "language": "11l" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "2 x 1: 1\n2 x 2: 2\n3 x 2: 3\n4 x 1: 1\n4 x 2: 4\n4 x 3: 9\n4 x 4: 22\n5 x 2: 5\n5 x 4: 39\n6 x 1: 1\n6 x 2: 6\n6 x 3: 23\n6 x 4: 90\n6 x 5: 263\n6 x 6: 1018\n7 x 2: 7\n7 x 4: 151\n7 x 6: 2947\n8 x 1: 1\n8 x 2: 8\n8 x 3: 53\n8 x 4: 340\n8 x 5: 1675\n8 x 6: 11174\n8 x 7: 55939\n8 x 8: 369050\n9 x 2: 9\n9 x 4: 553\n9 x 6: 31721\n9 x 8: 1812667\n10 x 1: 1\n10 x 2: 10\n10 x 3: 115\n10 x 4: 1228\n10 x 5: 10295\n10 x 6: 118276\n10 x 7: 1026005\n10 x 8: 11736888\n10 x 9: 99953769\n10 x 10: 1124140214\n", "language": "C" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned char byte;\nint w = 0, h = 0, verbose = 0;\nunsigned long count = 0;\n\nbyte **hor, **ver, **vis;\nbyte **c = 0;\n\nenum { U = 1, D = 2, L = 4, R = 8 };\n\nbyte ** alloc2(int w, int h)\n{\n\tint i;\n\tbyte **x = calloc(1, sizeof(byte*) * h + h * w);\n\tx[0] = (byte *)&x[h];\n\tfor (i = 1; i < h; i++)\n\t\tx[i] = x[i - 1] + w;\n\treturn x;\n}\n\nvoid show()\n{\n\tint i, j, v, last_v;\n\tprintf(\"%ld\\n\", count);\n#if 0\n\tfor (i = 0; i <= h; i++) {\n\t\tfor (j = 0; j <= w; j++)\n\t\t\tprintf(\"%d \", hor[i][j]);\n\t\tputs(\"\");\n\t}\n\tputs(\"\");\n\n\tfor (i = 0; i <= h; i++) {\n\t\tfor (j = 0; j <= w; j++)\n\t\t\tprintf(\"%d \", ver[i][j]);\n\t\tputs(\"\");\n\t}\n\tputs(\"\");\n#endif\n\tfor (i = 0; i < h; i++) {\n\t\tif (!i) v = last_v = 0;\n\t\telse last_v = v = hor[i][0] ? !last_v : last_v;\n\n\t\tfor (j = 0; j < w; v = ver[i][++j] ? !v : v)\n\t\t\tprintf(v ? \"\\033[31m[]\" : \"\\033[33m{}\");\n\t\tputs(\"\\033[m\");\n\t}\n\tputchar('\\n');\n}\n\nvoid walk(int y, int x)\n{\n\tif (x < 0 || y < 0 || x > w || y > h) return;\n\n\tif (!x || !y || x == w || y == h) {\n\t\t++count;\n\t\tif (verbose) show();\n\t\treturn;\n\t}\n\n\tif (vis[y][x]) return;\n\tvis[y][x]++; vis[h - y][w - x]++;\n\n\tif (x && !hor[y][x - 1]) {\n\t\thor[y][x - 1] = hor[h - y][w - x] = 1;\n\t\twalk(y, x - 1);\n\t\thor[y][x - 1] = hor[h - y][w - x] = 0;\n\t}\n\tif (x < w && !hor[y][x]) {\n\t\thor[y][x] = hor[h - y][w - x - 1] = 1;\n\t\twalk(y, x + 1);\n\t\thor[y][x] = hor[h - y][w - x - 1] = 0;\n\t}\n\n\tif (y && !ver[y - 1][x]) {\n\t\tver[y - 1][x] = ver[h - y][w - x] = 1;\n\t\twalk(y - 1, x);\n\t\tver[y - 1][x] = ver[h - y][w - x] = 0;\n\t}\n\n\tif (y < h && !ver[y][x]) {\n\t\tver[y][x] = ver[h - y - 1][w - x] = 1;\n\t\twalk(y + 1, x);\n\t\tver[y][x] = ver[h - y - 1][w - x] = 0;\n\t}\n\n\tvis[y][x]--; vis[h - y][w - x]--;\n}\n\nvoid cut(void)\n{\n\tif (1 & (h * w)) return;\n\n\thor = alloc2(w + 1, h + 1);\n\tver = alloc2(w + 1, h + 1);\n\tvis = alloc2(w + 1, h + 1);\n\n\tif (h & 1) {\n\t\tver[h/2][w/2] = 1;\n\t\twalk(h / 2, w / 2);\n\t} else if (w & 1) {\n\t\thor[h/2][w/2] = 1;\n\t\twalk(h / 2, w / 2);\n\t} else {\n\t\tvis[h/2][w/2] = 1;\n\n\t\thor[h/2][w/2-1] = hor[h/2][w/2] = 1;\n\t\twalk(h / 2, w / 2 - 1);\n\t\thor[h/2][w/2-1] = hor[h/2][w/2] = 0;\n\n\t\tver[h/2 - 1][w/2] = ver[h/2][w/2] = 1;\n\t\twalk(h / 2 - 1, w/2);\n\t}\n}\n\nvoid cwalk(int y, int x, int d)\n{\n\tif (!y || y == h || !x || x == w) {\n\t\t++count;\n\t\treturn;\n\t}\n\tvis[y][x] = vis[h-y][w-x] = 1;\n\n\tif (x && !vis[y][x-1])\n\t\tcwalk(y, x - 1, d|1);\n\tif ((d&1) && x < w && !vis[y][x+1])\n\t\tcwalk(y, x + 1, d|1);\n\tif (y && !vis[y-1][x])\n\t\tcwalk(y - 1, x, d|2);\n\tif ((d&2) && y < h && !vis[y + 1][x])\n\t\tcwalk(y + 1, x, d|2);\n\n\tvis[y][x] = vis[h-y][w-x] = 0;\n}\n\nvoid count_only(void)\n{\n\tint t;\n\tlong res;\n\tif (h * w & 1) return;\n\tif (h & 1) t = h, h = w, w = t;\n\n\tvis = alloc2(w + 1, h + 1);\n\tvis[h/2][w/2] = 1;\n\n\tif (w & 1) vis[h/2][w/2 + 1] = 1;\n\tif (w > 1) {\n\t\tcwalk(h/2, w/2 - 1, 1);\n\t\tres = 2 * count - 1;\n\t\tcount = 0;\n\t\tif (w != h)\n\t\t\tcwalk(h/2+1, w/2, (w & 1) ? 3 : 2);\n\n\t\tres += 2 * count - !(w & 1);\n\t} else {\n\t\tres = 1;\n\t}\n\tif (w == h) res = 2 * res + 2;\n\tcount = res;\n}\n\nint main(int c, char **v)\n{\n\tint i;\n\n\tfor (i = 1; i < c; i++) {\n\t\tif (v[i][0] == '-' && v[i][1] == 'v' && !v[i][2]) {\n\t\t\tverbose = 1;\n\t\t} else if (!w) {\n\t\t\tw = atoi(v[i]);\n\t\t\tif (w <= 0) goto bail;\n\t\t} else if (!h) {\n\t\t\th = atoi(v[i]);\n\t\t\tif (h <= 0) goto bail;\n\t\t} else\n\t\t\tgoto bail;\n\t}\n\tif (!w) goto bail;\n\tif (!h) h = w;\n\n\tif (verbose) cut();\n\telse count_only();\n\n\tprintf(\"Total: %ld\\n\", count);\n\treturn 0;\n\nbail:\tfprintf(stderr, \"bad args\\n\");\n\treturn 1;\n}\n", "language": "C" }, { "code": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n std::make_pair(0, -1),\n std::make_pair(-1, 0),\n std::make_pair(0, 1),\n std::make_pair(1, 0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n for (auto &row : v) {\n auto it = row.cbegin();\n auto end = row.cend();\n\n std::cout << '[';\n if (it != end) {\n std::cout << *it;\n it = std::next(it);\n }\n while (it != end) {\n std::cout << \", \" << *it;\n it = std::next(it);\n }\n std::cout << \"]\\n\";\n }\n}\n\nvoid cutRectangle(int w, int h) {\n if (w % 2 == 1 && h % 2 == 1) {\n return;\n }\n\n std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n std::stack<int> stack;\n\n int half = (w * h) / 2;\n long bits = (long)pow(2, half) - 1;\n\n for (; bits > 0; bits -= 2) {\n for (int i = 0; i < half; i++) {\n int r = i / w;\n int c = i % w;\n grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n }\n\n stack.push(0);\n grid[0][0] = 2;\n int count = 1;\n while (!stack.empty()) {\n int pos = stack.top();\n stack.pop();\n\n int r = pos / w;\n int c = pos % w;\n for (auto dir : DIRS) {\n int nextR = r + dir.first;\n int nextC = c + dir.second;\n\n if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n if (grid[nextR][nextC] == 1) {\n stack.push(nextR * w + nextC);\n grid[nextR][nextC] = 2;\n count++;\n }\n }\n }\n }\n if (count == half) {\n printResult(grid);\n std::cout << '\\n';\n }\n }\n}\n\nint main() {\n cutRectangle(2, 2);\n cutRectangle(4, 3);\n\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\n\npublic class CutRectangle\n{\n private static int[][] dirs = new int[][] { new int[] { 0, -1 }, new int[] { -1, 0 }, new int[] { 0, 1 }, new int[] { 1, 0 } };\n\n public static void Main(string[] args)\n {\n CutRectangleMethod(2, 2);\n CutRectangleMethod(4, 3);\n }\n\n static void CutRectangleMethod(int w, int h)\n {\n if (w % 2 == 1 && h % 2 == 1)\n return;\n\n int[,] grid = new int[h, w];\n Stack<int> stack = new Stack<int>();\n\n int half = (w * h) / 2;\n long bits = (long)Math.Pow(2, half) - 1;\n\n for (; bits > 0; bits -= 2)\n {\n for (int i = 0; i < half; i++)\n {\n int r = i / w;\n int c = i % w;\n grid[r, c] = (bits & (1L << i)) != 0 ? 1 : 0;\n grid[h - r - 1, w - c - 1] = 1 - grid[r, c];\n }\n\n stack.Push(0);\n grid[0, 0] = 2;\n int count = 1;\n while (stack.Count > 0)\n {\n int pos = stack.Pop();\n int r = pos / w;\n int c = pos % w;\n\n foreach (var dir in dirs)\n {\n int nextR = r + dir[0];\n int nextC = c + dir[1];\n\n if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w)\n {\n if (grid[nextR, nextC] == 1)\n {\n stack.Push(nextR * w + nextC);\n grid[nextR, nextC] = 2;\n count++;\n }\n }\n }\n }\n if (count == half)\n {\n PrintResult(grid, h, w);\n }\n }\n }\n\n static void PrintResult(int[,] arr, int height, int width)\n {\n for (int i = 0; i < height; i++)\n {\n for (int j = 0; j < width; j++)\n {\n Console.Write(arr[i, j] + (j == width - 1 ? \"\" : \", \"));\n }\n Console.WriteLine();\n }\n Console.WriteLine();\n }\n}\n", "language": "C-sharp" }, { "code": "(defun cut-it (w h &optional (recur t))\n (if (oddp (* w h)) (return-from cut-it 0))\n (if (oddp h) (rotatef w h))\n (if (= w 1) (return-from cut-it 1))\n\n (let ((cnt 0)\n\t(m (make-array (list (1+ h) (1+ w))\n\t\t :element-type 'bit\n\t\t :initial-element 0))\n\t(cy (truncate h 2))\n\t(cx (truncate w 2)))\n\n (setf (aref m cy cx) 1)\n (if (oddp w) (setf (aref m cy (1+ cx)) 1))\n\n (labels\n ((walk (y x turned)\n\t (when (or (= y 0) (= y h) (= x 0) (= x w))\n\t (incf cnt (if turned 2 1))\n\t (return-from walk))\n\n\t (setf (aref m y x) 1)\n\t (setf (aref m (- h y) (- w x)) 1)\n\t (loop for i from 0\n\t\t for (dy dx) in '((0 -1) (-1 0) (0 1) (1 0))\n\t\t while (or turned (< i 2)) do\n\t\t (let ((y2 (+ y dy))\n\t\t\t (x2 (+ x dx)))\n\t\t (when (zerop (aref m y2 x2))\n\t\t (walk y2 x2 (or turned (> i 0))))))\n\t (setf (aref m (- h y) (- w x)) 0)\n\t (setf (aref m y x) 0)))\n\n (walk cy (1- cx) nil)\n (cond ((= h w) (incf cnt cnt))\n\t ((oddp w) (walk (1- cy) cx t))\n\t (recur (incf cnt (cut-it h w nil))))\n cnt)))\n\n(loop for w from 1 to 9 do\n (loop for h from 1 to w do\n\t (if (evenp (* w h))\n\t (format t \"~d x ~d: ~d~%\" w h (cut-it w h)))))\n", "language": "Common-Lisp" }, { "code": "2 x 1: 2\n2 x 2: 2\n3 x 2: 3\n4 x 1: 4\n4 x 2: 4\n4 x 3: 9\n4 x 4: 22\n5 x 2: 5\n5 x 4: 39\n6 x 1: 6\n6 x 2: 6\n6 x 3: 23\n6 x 4: 90\n6 x 5: 263\n6 x 6: 1018\n7 x 2: 7\n7 x 4: 151\n7 x 6: 2947\n8 x 1: 8\n8 x 2: 8\n8 x 3: 53\n8 x 4: 340\n8 x 5: 1675\n8 x 6: 11174\n8 x 7: 55939\n8 x 8: 369050\n9 x 2: 9\n9 x 4: 553\n9 x 6: 31721\n9 x 8: 1812667\n", "language": "Common-Lisp" }, { "code": "import core.stdc.stdio, core.stdc.stdlib, core.stdc.string, std.typecons;\n\nenum int[2][4] dir = [[0, -1], [-1, 0], [0, 1], [1, 0]];\n\n__gshared ubyte[] grid;\n__gshared uint w, h, len;\n__gshared ulong cnt;\n__gshared uint[4] next;\n\nvoid walk(in uint y, in uint x) nothrow @nogc {\n if (!y || y == h || !x || x == w) {\n cnt += 2;\n return;\n }\n\n immutable t = y * (w + 1) + x;\n grid[t]++;\n grid[len - t]++;\n\n foreach (immutable i; staticIota!(0, 4))\n if (!grid[t + next[i]])\n walk(y + dir[i][0], x + dir[i][1]);\n\n grid[t]--;\n grid[len - t]--;\n}\n\nulong solve(in uint hh, in uint ww, in bool recur) nothrow @nogc {\n h = (hh & 1) ? ww : hh;\n w = (hh & 1) ? hh : ww;\n\n if (h & 1) return 0;\n if (w == 1) return 1;\n if (w == 2) return h;\n if (h == 2) return w;\n\n immutable cy = h / 2;\n immutable cx = w / 2;\n\n len = (h + 1) * (w + 1);\n {\n // grid.length = len; // Slower.\n alias T = typeof(grid[0]);\n auto ptr = cast(T*)alloca(len * T.sizeof);\n if (ptr == null)\n exit(1);\n grid = ptr[0 .. len];\n }\n grid[] = 0;\n len--;\n\n next = [-1, -w - 1, 1, w + 1];\n\n if (recur)\n cnt = 0;\n foreach (immutable x; cx + 1 .. w) {\n immutable t = cy * (w + 1) + x;\n grid[t] = 1;\n grid[len - t] = 1;\n walk(cy - 1, x);\n }\n cnt++;\n\n if (h == w)\n cnt *= 2;\n else if (!(w & 1) && recur)\n solve(w, h, 0);\n\n return cnt;\n}\n\nvoid main() {\n foreach (immutable uint y; 1 .. 11)\n foreach (immutable uint x; 1 .. y + 1)\n if (!(x & 1) || !(y & 1))\n printf(\"%d x %d: %llu\\n\", y, x, solve(y, x, true));\n}\n", "language": "D" }, { "code": "program Cut_a_rectangle;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils;\n\nvar\n grid: array of byte;\n w, h, len: Integer;\n cnt: UInt64;\n next: array of Integer;\n dir: array of array of Integer = [[0, -1], [-1, 0], [0, 1], [1, 0]];\n\nprocedure walk(y, x: Integer);\nvar\n i, t: Integer;\nbegin\n if (y = 0) or (y = h) or (x = 0) or (x = w) then\n begin\n inc(cnt);\n Exit;\n end;\n t := y * (w + 1) + x;\n inc(grid[t]);\n inc(grid[len - t]);\n\n for i := 0 to 3 do\n if grid[t + next[i]] = 0 then\n walk(y + dir[i][0], x + dir[i][1]);\n dec(grid[t]);\n dec(grid[len - t]);\nend;\n\nfunction solve(hh, ww: Integer; recur: Boolean): UInt64;\nvar\n t, cx, cy, x, i: Integer;\nbegin\n h := hh;\n w := ww;\n\n if Odd(h) then\n begin\n t := w;\n w := h;\n h := t;\n end;\n\n if Odd(h) then\n Exit(0);\n\n if w = 1 then\n Exit(1);\n\n if w = 2 then\n Exit(h);\n\n if h = 2 then\n Exit(w);\n\n cy := h div 2;\n cx := w div 2;\n len := (h + 1) * (w + 1);\n\n setlength(grid, len);\n\n for i := 0 to High(grid) do\n grid[i] := 0;\n\n dec(len);\n\n next := [-1, -w - 1, 1, w + 1];\n\n if recur then\n cnt := 0;\n\n for x := cx + 1 to w - 1 do\n begin\n t := cy * (w + 1) + x;\n grid[t] := 1;\n grid[len - t] := 1;\n walk(cy - 1, x);\n end;\n Inc(cnt);\n\n if h = w then\n inc(cnt, 2)\n else if not odd(w) and recur then\n solve(w, h, False);\n Result := cnt;\nend;\n\nvar\n y, x: Integer;\n\nbegin\n for y := 1 to 10 do\n for x := 1 to y do\n if not Odd(x) or not Odd(y) then\n writeln(format('%d x %d: %d', [y, x, solve(y, x, True)]));\n Readln;\nend.\n", "language": "Delphi" }, { "code": "global grid[] blen w h cnt .\ndir[][] = [ [ 0 -1 ] [ -1 0 ] [ 0 1 ] [ 1 0 ] ]\n#\nproc walk y x . .\n if y = 0 or y = h or x = 0 or x = w\n cnt += 2\n return\n .\n t = y * (w + 1) + x\n grid[t] += 1\n grid[blen - t] += 1\n for i to 4\n dx = dir[i][1]\n dy = dir[i][2]\n d = dx + dy * (w + 1)\n if grid[t + d] = 0\n walk y + dy x + dx\n .\n .\n grid[t] -= 1\n grid[blen - t] -= 1\n.\nproc solve hh ww recur . .\n w = ww\n h = hh\n if h mod 2 = 1\n swap h w\n .\n if h mod 2 = 1\n cnt = 0\n return\n .\n if w = 1\n cnt = 1\n return\n .\n if w = 2\n cnt = h\n return\n .\n if h = 2\n cnt = w\n return\n .\n cy = h div 2 ; cx = w div 2\n blen = (h + 1) * (w + 1)\n grid[] = [ ]\n len grid[] blen\n blen -= 1\n if recur = 1\n cnt = 0\n .\n for x = cx + 1 to w - 1\n t = cy * (w + 1) + x\n grid[t] = 1\n grid[blen - t] = 1\n walk cy - 1 x\n .\n cnt += 1\n if h = w\n cnt *= 2\n elif w mod 2 = 0 and recur = 1\n solve w h 0\n .\n.\nproc main . .\n for y = 1 to 8\n for x = 1 to y\n if x mod 2 = 0 or y mod 2 = 0\n solve y x 1\n print y & \" x \" & x & \": \" & cnt\n .\n .\n .\n.\nmain\n", "language": "EasyLang" }, { "code": "class\n\tAPPLICATION\n\ncreate\n\tmake\n\nfeature {NONE} -- Initialization\n\n\tmake\n\t\t\t-- Finds solution for cut a rectangle up to 10 x 10.\n\t\tlocal\n\t\t\ti, j, n: Integer\n\t\t\tr: GRID\n\t\tdo\n\t\t\tn := 10\n\t\t\tfrom\n\t\t\t\ti := 1\n\t\t\tuntil\n\t\t\t\ti > n\n\t\t\tloop\n\t\t\t\tfrom\n\t\t\t\t\tj := 1\n\t\t\t\tuntil\n\t\t\t\t\tj > i\n\t\t\t\tloop\n\t\t\t\t\tif i.bit_and (1) /= 1 or j.bit_and (1) /= 1 then\n\t\t\t\t\t\tcreate r.make (i, j)\n\t\t\t\t\t\tr.print_solution\n\t\t\t\t\tend\n\t\t\t\t\tj := j + 1\n\t\t\t\tend\n\t\t\t\ti := i + 1\n\t\t\tend\n\t\tend\n\nend\n", "language": "Eiffel" }, { "code": "class\n\tGRID\n\ncreate\n\tmake\n\nfeature {NONE}\n\n\tn: INTEGER\n\n\tm: INTEGER\n\nfeature\n\n\tprint_solution\n\t -- Prints solution to cut a rectangle.\n\t\tdo\n\t\t\tcalculate_possibilities\n\t\t\tio.put_string (\"Rectangle \" + n.out + \" x \" + m.out + \": \" + count.out + \" possibilities%N\")\n\t\tend\n\n\tcount: INTEGER\n\t\t\t-- Number of solutions\n\n\tmake (a_n: INTEGER; a_m: INTEGER)\n\t -- Initialize Problem with 'a_n' and 'a_m'.\n\t\trequire\n\t\t\ta_n > 0\n\t\t\ta_m > 0\n\t\tdo\n\t\t\tn := a_n\n\t\t\tm := a_m\n\t\t\tcount := 0\n\t\tend\n\n\tcalculate_possibilities\n\t -- Select all possible starting points.\n\t\tlocal\n\t\t\ti: INTEGER\n\t\tdo\n\t\t\tif (n = 1 or m = 1) then\n\t\t\t\tcount := 1\n\t\t\tend\n\n\t\t\tfrom\n\t\t\t\ti := 0\n\t\t\tuntil\n\t\t\t\ti > n or (n = 1 or m = 1)\n\t\t\tloop\n\t\t\t\tsolve (create {POINT}.make_with_values (i, 0), create {POINT}.make_with_values (n - i, m), create {LINKED_LIST [POINT]}.make, create {LINKED_LIST [POINT]}.make)\n\t\t\t\ti := i + 1\n\t\t\tvariant\n\t\t\t\tn - i + 1\n\t\t\tend\n\t\t\tfrom\n\t\t\t\ti := 0\n\t\t\tuntil\n\t\t\t\ti > m or (n = 1 or m = 1)\n\t\t\tloop\n\t\t\t\tsolve (create {POINT}.make_with_values (n, i), create {POINT}.make_with_values (0, m - i), create {LINKED_LIST [POINT]}.make, create {LINKED_LIST [POINT]}.make)\n\t\t\t\ti := i + 1\n\t\t\tvariant\n\t\t\t\tm - i + 1\n\t\t\tend\n\t\tend\n\nfeature {NONE}\n\n\tsolve (p, q: POINT; visited_p, visited_q: LINKED_LIST [POINT])\n\t -- Recursive solution of cut a rectangle.\n\t\tlocal\n\t\t\tpossible_next: LINKED_LIST [POINT]\n\t\t\tnext: LINKED_LIST [POINT]\n\t\t\topposite: POINT\n\t\tdo\n\t\t\tif p.negative or q.negative then\n\n\t\t\telseif p.same (q) then\n\t\t\t\tadd_solution\n\t\t\telse\n\t\t\t\tpossible_next := get_possible_next (p)\n\t\t\t\tcreate next.make\n\t\t\t\tacross\n\t\t\t\t\tpossible_next as x\n\t\t\t\tloop\n\t\t\t\t\tif x.item.x >= n or x.item.y >= m then\n\t\t\t\t\t\t\t-- Next point cannot be on the border. Do nothing.\n\n\t\t\t\t\telseif x.item.same (q) then\n\t\t\t\t\t\tadd_solution\n\t\t\t\t\telseif not contains (x.item, visited_p) and not contains (x.item, visited_q) then\n\t\t\t\t\t\tnext.extend (x.item)\n\t\t\t\t\tend\n\t\t\t\tend\n\n\t\t\t\tacross\n\t\t\t\t\tnext as x\n\t\t\t\tloop\n\t\t\t\t\t\t-- Move in one direction\n\t\t\t\t\t\t-- Calculate the opposite end of the cut by moving into the opposite direction (compared to p -> x)\n\t\t\t\t\tcreate opposite.make_with_values (q.x - (x.item.x - p.x), q.y - (x.item.y - p.y))\n\n\t\t\t\t\tvisited_p.extend (p)\n\t\t\t\t\tvisited_q.extend (q)\n\n\t\t\t\t\tsolve (x.item, opposite, visited_p, visited_q)\n\n\t\t\t\t\t\t-- Remove last point again\n\t\t\t\t\tvisited_p.finish\n\t\t\t\t\tvisited_p.remove\n\n\t\t\t\t\tvisited_q.finish\n\t\t\t\t\tvisited_q.remove\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\tget_possible_next (p: POINT): LINKED_LIST [POINT]\n\t\t\t-- Four possible next points.\n\t\tlocal\n\t\t\tq: POINT\n\t\tdo\n\t\t\tcreate Result.make\n\n\t\t\t\t--up\n\t\t\tcreate q.make_with_values (p.x + 1, p.y)\n\t\t\tif q.valid and q.x <= n and q.y <= m then\n\t\t\t\tResult.extend (q);\n\t\t\tend\n\n\t\t\t\t--down\n\t\t\tcreate q.make_with_values (p.x - 1, p.y)\n\t\t\tif q.valid and q.x <= n and q.y <= m then\n\t\t\t\tResult.extend (q)\n\t\t\tend\n\n\t\t\t\t--left\n\t\t\tcreate q.make_with_values (p.x, p.y - 1)\n\t\t\tif q.valid and q.x <= n and q.y <= m then\n\t\t\t\tResult.extend (q)\n\t\t\tend\n\n\t\t\t\t--right\n\t\t\tcreate q.make_with_values (p.x, p.y + 1)\n\t\t\tif q.valid and q.x <= n and q.y <= m then\n\t\t\t\tResult.extend (q)\n\t\t\tend\n\t\tend\n\n\tadd_solution\n\t\t\t-- Increment count.\n\t\tdo\n\t\t\tcount := count + 1\n\t\tend\n\n\tcontains (p: POINT; set: LINKED_LIST [POINT]): BOOLEAN\n\t\t\t-- Does set contain 'p'?\n\t\tdo\n\t\t\tset.compare_objects\n\t\t\tResult := set.has (p)\n\t\tend\n\nend\n", "language": "Eiffel" }, { "code": "class\n\tPOINT\n\ncreate\n\tmake, make_with_values\n\n\n\nfeature\n\n\tmake_with_values (a_x: INTEGER; a_y: INTEGER)\n\t-- Initialize x and y with 'a_x' and 'a_y'.\n\t\tdo\n\t\t\tx := a_x\n\t\t\ty := a_y\n\t\tend\n\n\tmake\n\t-- Initialize x and y with 0.\n\t\tdo\n\t\t\tx := 0\n\t\t\ty := 0\n\t\tend\n\n\tx: INTEGER\n\n\ty: INTEGER\n\n\tnegative: BOOLEAN\n\t\t\t-- Are x or y negative?\n\t\tdo\n\t\t\tResult := x < 0 or y < 0\n\t\tend\n\n\tsame (other: POINT): BOOLEAN\n\t\t\t-- Does x and y equal 'other's x and y?\n\t\tdo\n\t\t\tResult := (x = other.x) and (y = other.y)\n\t\tend\n\n\tvalid: BOOLEAN\n\t\t\t-- Are x and y valid points?\n\t\tdo\n\t\t\tResult := (x > 0) and (y > 0)\n\t\tend\n\nend\n", "language": "Eiffel" }, { "code": "import Integer\n\ndefmodule Rectangle do\n def cut_it(h, w) when is_odd(h) and is_odd(w), do: 0\n def cut_it(h, w) when is_odd(h), do: cut_it(w, h)\n def cut_it(_, 1), do: 1\n def cut_it(h, 2), do: h\n def cut_it(2, w), do: w\n def cut_it(h, w) do\n grid = List.duplicate(false, (h + 1) * (w + 1))\n t = div(h, 2) * (w + 1) + div(w, 2)\n if is_odd(w) do\n grid = grid |> List.replace_at(t, true) |> List.replace_at(t+1, true)\n walk(h, w, div(h, 2), div(w, 2) - 1, grid) + walk(h, w, div(h, 2) - 1, div(w, 2), grid) * 2\n else\n grid = grid |> List.replace_at(t, true)\n count = walk(h, w, div(h, 2), div(w, 2) - 1, grid)\n if h == w, do: count * 2,\n else: count + walk(h, w, div(h, 2) - 1, div(w, 2), grid)\n end\n end\n\n defp walk(h, w, y, x, grid, count\\\\0)\n defp walk(h, w, y, x,_grid, count) when y in [0,h] or x in [0,w], do: count+1\n defp walk(h, w, y, x, grid, count) do\n blen = (h + 1) * (w + 1) - 1\n t = y * (w + 1) + x\n grid = grid |> List.replace_at(t, true) |> List.replace_at(blen-t, true)\n Enum.reduce(next(w), count, fn {nt, dy, dx}, cnt ->\n if Enum.at(grid, t+nt), do: cnt, else: cnt + walk(h, w, y+dy, x+dx, grid)\n end)\n end\n\n defp next(w), do: [{w+1, 1, 0}, {-w-1, -1, 0}, {-1, 0, -1}, {1, 0, 1}] # {next,dy,dx}\nend\n\nEnum.each(1..9, fn w ->\n Enum.each(1..w, fn h ->\n if is_even(w * h), do: IO.puts \"#{w} x #{h}: #{Rectangle.cut_it(w, h)}\"\n end)\nend)\n", "language": "Elixir" }, { "code": "defmodule Rectangle do\n def cut(h, w, disp\\\\true) when rem(h,2)==0 or rem(w,2)==0 do\n limit = div(h * w, 2)\n start_link\n grid = make_grid(h, w)\n walk(h, w, grid, 0, 0, limit, %{}, [])\n if disp, do: display(h, w)\n result = Agent.get(__MODULE__, &(&1))\n Agent.stop(__MODULE__)\n MapSet.to_list(result)\n end\n\n defp start_link do\n Agent.start_link(fn -> MapSet.new end, name: __MODULE__)\n end\n\n defp make_grid(h, w) do\n for i <- 0..h-1, j <- 0..w-1, into: %{}, do: {{i,j}, true}\n end\n\n defp walk(h, w, grid, x, y, limit, cut, select) do\n grid2 = grid |> Map.put({x,y}, false) |> Map.put({h-x-1,w-y-1}, false)\n select2 = [{x,y} | select] |> Enum.sort\n unless cut[select2] do\n if length(select2) == limit do\n Agent.update(__MODULE__, fn set -> MapSet.put(set, select2) end)\n else\n cut2 = Map.put(cut, select2, true)\n search_next(grid2, select2)\n |> Enum.each(fn {i,j} -> walk(h, w, grid2, i, j, limit, cut2, select2) end)\n end\n end\n end\n\n defp dirs(x, y), do: [{x+1, y}, {x-1, y}, {x, y-1}, {x, y+1}]\n\n defp search_next(grid, select) do\n (for {x,y} <- select, {i,j} <- dirs(x,y), grid[{i,j}], do: {i,j})\n |> Enum.uniq\n end\n\n defp display(h, w) do\n Agent.get(__MODULE__, &(&1))\n |> Enum.each(fn select ->\n grid = Enum.reduce(select, make_grid(h,w), fn {x,y},grid ->\n %{grid | {x,y} => false}\n end)\n IO.puts to_string(h, w, grid)\n end)\n end\n\n defp to_string(h, w, grid) do\n text = for x <- 0..h*2, into: %{}, do: {x, String.duplicate(\" \", w*4+1)}\n text = Enum.reduce(0..h, text, fn i,acc ->\n Enum.reduce(0..w, acc, fn j,txt ->\n to_s(txt, i, j, grid)\n end)\n end)\n Enum.map_join(0..h*2, \"\\n\", fn i -> text[i] end)\n end\n\n defp to_s(text, i, j, grid) do\n text = if grid[{i,j}] != grid[{i-1,j}], do: replace(text, i*2, j*4+1, \"---\"), else: text\n text = if grid[{i,j}] != grid[{i,j-1}], do: replace(text, i*2+1, j*4, \"|\"), else: text\n replace(text, i*2, j*4, \"+\")\n end\n\n defp replace(text, x, y, replacement) do\n len = String.length(replacement)\n Map.update!(text, x, fn str ->\n String.slice(str, 0, y) <> replacement <> String.slice(str, y+len..-1)\n end)\n end\nend\n\nRectangle.cut(2, 2) |> length |> IO.puts\nRectangle.cut(3, 4) |> length |> IO.puts\n", "language": "Elixir" }, { "code": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n if y == 0 || y == h || x == 0 || x == w {\n cnt += 2\n return\n }\n t := y*(w+1) + x\n grid[t]++\n grid[last-t]++\n for i, d := range dir {\n if grid[t+next[i]] == 0 {\n walk(y+d[0], x+d[1])\n }\n }\n grid[t]--\n grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n h = hh\n w = ww\n\n if h&1 != 0 {\n h, w = w, h\n }\n switch {\n case h&1 == 1:\n return 0\n case w == 1:\n return 1\n case w == 2:\n return h\n case h == 2:\n return w\n }\n cy := h / 2\n cx := w / 2\n\n grid = make([]byte, (h+1)*(w+1))\n last = len(grid) - 1\n next[0] = -1\n next[1] = -w - 1\n next[2] = 1\n next[3] = w + 1\n\n if recur != 0 {\n cnt = 0\n }\n for x := cx + 1; x < w; x++ {\n t := cy*(w+1) + x\n grid[t] = 1\n grid[last-t] = 1\n walk(cy-1, x)\n }\n cnt++\n\n if h == w {\n cnt *= 2\n } else if w&1 == 0 && recur != 0 {\n solve(w, h, 0)\n }\n return cnt\n}\n\nfunc main() {\n for y := 1; y <= 10; y++ {\n for x := 1; x <= y; x++ {\n if x&1 == 0 || y&1 == 0 {\n fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n }\n }\n }\n}\n", "language": "Go" }, { "code": "class CutRectangle {\n private static int[][] dirs = [[0, -1], [-1, 0], [0, 1], [1, 0]]\n\n static void main(String[] args) {\n cutRectangle(2, 2)\n cutRectangle(4, 3)\n }\n\n static void cutRectangle(int w, int h) {\n if (w % 2 == 1 && h % 2 == 1) {\n return\n }\n\n int[][] grid = new int[h][w]\n Stack<Integer> stack = new Stack<>()\n\n int half = (int) ((w * h) / 2)\n long bits = (long) Math.pow(2, half) - 1\n\n for (; bits > 0; bits -= 2) {\n for (int i = 0; i < half; i++) {\n int r = (int) (i / w)\n int c = i % w\n grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0\n grid[h - r - 1][w - c - 1] = 1 - grid[r][c]\n }\n\n stack.push(0)\n grid[0][0] = 2\n int count = 1\n while (!stack.empty()) {\n int pos = stack.pop()\n int r = (int) (pos / w)\n int c = pos % w\n\n for (int[] dir : dirs) {\n int nextR = r + dir[0]\n int nextC = c + dir[1]\n\n if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n if (grid[nextR][nextC] == 1) {\n stack.push(nextR * w + nextC)\n grid[nextR][nextC] = 2\n count++\n }\n }\n }\n }\n if (count == half) {\n printResult(grid)\n }\n }\n }\n\n static void printResult(int[][] arr) {\n for (int[] a : arr) {\n println(Arrays.toString(a))\n }\n println()\n }\n}\n", "language": "Groovy" }, { "code": "import qualified Data.Vector.Unboxed.Mutable as V\nimport Data.STRef\nimport Control.Monad (forM_, when)\nimport Control.Monad.ST\n\ndir :: [(Int, Int)]\ndir = [(1, 0), (-1, 0), (0, -1), (0, 1)]\n\ndata Env = Env { w, h, len, count, ret :: !Int, next :: ![Int] }\n\ncutIt :: STRef s Env -> ST s ()\ncutIt env = do\n e <- readSTRef env\n when (odd $ h e) $ modifySTRef env $ \\en -> en { h = w e,\n w = h e }\n e <- readSTRef env\n if odd (h e)\n then modifySTRef env $ \\en -> en { ret = 0 }\n else\n if w e == 1\n then modifySTRef env $ \\en -> en { ret = 1 }\n else do\n let blen = (h e + 1) * (w e + 1) - 1\n t = (h e `div` 2) * (w e + 1) + (w e `div` 2)\n modifySTRef env $ \\en -> en { len = blen,\n count = 0,\n next = [ w e + 1, (negate $ w e) - 1, -1, 1] }\n grid <- V.replicate (blen + 1) False\n case odd (w e) of\n True -> do\n V.write grid t True\n V.write grid (t + 1) True\n walk grid (h e `div` 2) (w e `div` 2 - 1)\n e1 <- readSTRef env\n let res1 = count e1\n modifySTRef env $ \\en -> en { count = 0 }\n walk grid (h e `div` 2 - 1) (w e `div` 2)\n modifySTRef env $ \\en -> en { ret = res1 +\n (count en * 2) }\n False -> do\n V.write grid t True\n walk grid (h e `div` 2) (w e `div` 2 - 1)\n e2 <- readSTRef env\n let count2 = count e2\n if h e == w e\n then modifySTRef env $ \\en -> en { ret =\n count2 * 2 }\n else do\n walk grid (h e `div` 2 - 1)\n (w e `div` 2)\n modifySTRef env $ \\en -> en { ret =\n count en }\n where\n walk grid y x = do\n e <- readSTRef env\n if y <= 0 || y >= h e || x <= 0 || x >= w e\n then modifySTRef env $ \\en -> en { count = count en + 1 }\n else do\n let t = y * (w e + 1) + x\n V.write grid t True\n V.write grid (len e - t) True\n forM_ (zip (next e) [0..3]) $ \\(n, d) -> do\n g <- V.read grid (t + n)\n when (not g) $\n walk grid (y + fst (dir !! d)) (x + snd (dir !! d))\n V.write grid t False\n V.write grid (len e - t) False\n\ncut :: (Int, Int) -> Int\ncut (x, y) = runST $ do\n env <- newSTRef $ Env { w = y, h = x, len = 0, count = 0, ret = 0, next = [] }\n cutIt env\n result <- readSTRef env\n return $ ret result\n\nmain :: IO ()\nmain = do\n mapM_ (\\(x, y) -> when (even (x * y)) (putStrLn $\n show x ++ \" x \" ++ show y ++ \": \" ++ show (cut (x, y))))\n [ (x, y) | x <- [1..10], y <- [1..x] ]\n", "language": "Haskell" }, { "code": "init=: - {. 1: NB. initial state: 1 square choosen\nprop=: < {:,~2 ~:/\\ ] NB. propagate: neighboring squares (vertically)\nposs=: I.@,@(prop +. prop\"1 +. prop&.|. +. prop&.|.\"1)\nkeep=: poss -. <:@#@, - I.@, NB. symmetrically valid possibilities\nN=: <:@-:@#@, NB. how many neighbors to add\nstep=: [: ~.@; <@(((= i.@$) +. ])\"0 _~ keep)\"2\nall=: step^:N@init\n", "language": "J" }, { "code": " '.#' <\"2@:{~ all 3 4\n┌────┬────┬────┬────┬────┬────┬────┬────┬────┐\n│.###│.###│..##│...#│...#│....│....│....│....│\n│.#.#│..##│..##│..##│.#.#│..##│.#.#│#.#.│##..│\n│...#│...#│..##│.###│.###│####│####│####│####│\n└────┴────┴────┴────┴────┴────┴────┴────┴────┘\n $ all 4 5\n39 4 5\n 3 13$ '.#' <\"2@:{~ all 4 5\n┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐\n│.####│.####│.####│.####│.####│.####│..###│..###│..###│..###│..###│...##│...##│\n│.####│.##.#│.#..#│..###│...##│....#│.####│.##.#│..###│...##│....#│.####│..###│\n│....#│.#..#│.##.#│...##│..###│.####│....#│.#..#│...##│..###│.####│....#│...##│\n│....#│....#│....#│....#│....#│....#│...##│...##│...##│...##│...##│..###│..###│\n├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤\n│...##│...##│...##│....#│....#│....#│....#│....#│....#│.....│.....│.....│.....│\n│...##│....#│.#..#│.####│..###│...##│....#│.#..#│.##.#│.####│..###│...##│....#│\n│..###│.####│.##.#│....#│...##│..###│.####│.##.#│.#..#│....#│...##│..###│.####│\n│..###│..###│..###│.####│.####│.####│.####│.####│.####│#####│#####│#####│#####│\n├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤\n│.....│.....│.....│.....│.....│.....│.....│.....│.....│.....│.....│.....│.....│\n│.#..#│.##.#│..##.│...#.│.....│.#...│.##..│#.##.│#..#.│#....│##...│###..│####.│\n│.##.#│.#..#│#..##│#.###│#####│###.#│##..#│#..#.│#.##.│####.│###..│##...│#....│\n│#####│#####│#####│#####│#####│#####│#####│#####│#####│#####│#####│#####│#####│\n└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘\n", "language": "J" }, { "code": "import java.util.*;\n\npublic class CutRectangle {\n\n private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n public static void main(String[] args) {\n cutRectangle(2, 2);\n cutRectangle(4, 3);\n }\n\n static void cutRectangle(int w, int h) {\n if (w % 2 == 1 && h % 2 == 1)\n return;\n\n int[][] grid = new int[h][w];\n Stack<Integer> stack = new Stack<>();\n\n int half = (w * h) / 2;\n long bits = (long) Math.pow(2, half) - 1;\n\n for (; bits > 0; bits -= 2) {\n\n for (int i = 0; i < half; i++) {\n int r = i / w;\n int c = i % w;\n grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n }\n\n stack.push(0);\n grid[0][0] = 2;\n int count = 1;\n while (!stack.empty()) {\n\n int pos = stack.pop();\n int r = pos / w;\n int c = pos % w;\n\n for (int[] dir : dirs) {\n\n int nextR = r + dir[0];\n int nextC = c + dir[1];\n\n if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n if (grid[nextR][nextC] == 1) {\n stack.push(nextR * w + nextC);\n grid[nextR][nextC] = 2;\n count++;\n }\n }\n }\n }\n if (count == half) {\n printResult(grid);\n }\n }\n }\n\n static void printResult(int[][] arr) {\n for (int[] a : arr)\n System.out.println(Arrays.toString(a));\n System.out.println();\n }\n}\n", "language": "Java" }, { "code": "def dir: [[0, -1], [-1, 0], [0, 1], [1, 0]] ;\n\n# input and output: {grid, w, h, len, count, next}\ndef mywalk($y; $x):\n if ($y == 0 or $y == .h or $x == 0 or $x == .w)\n then .count += 2\n else ($y * (.w + 1) + $x) as $t\n | .grid[$t] += 1\n | .grid[.len-$t] += 1\n | reduce range(0; 4) as $i (.;\n if .grid[$t + .next[$i]] == 0\n then mywalk($y + dir[$i][0]; $x + dir[$i][1])\n else .\n end )\n | .grid[$t] += -1\n | .grid[.len-$t] += -1\n end;\n\n# solve/3 returns an integer.\n# If $count is null, the value is the count of permissible cuts for an $h x $w rectangle.\n# Otherwise, the computed value augments $count.\ndef solve($h; $w; $count):\n if $count then {$count} else {} end\n | if $h % 2 == 0\n then . + {$h, $w}\n else . + {w: $h, h: $w} # swap\n end\n | if (.h % 2 == 1) then 0\n elif (.w == 1) then 1\n elif (.w == 2) then .h\n elif (.h == 2) then .w\n else ((.h/2)|floor) as $cy\n | ((.w/2)|floor) as $cx\n | .len = (.h + 1) * (.w + 1)\n | .grid = [range(0; .len) | 0]\n | .len += -1\n | .next = [-1, - .w - 1, 1, .w + 1]\n | .x = $cx + 1\n | until (.x >= .w;\n ($cy * (.w + 1) + .x) as $t\n | .grid[$t] = 1\n | .grid[.len-$t] = 1\n | mywalk($cy - 1; .x)\n | .x += 1 )\n | .count += 1\n | if .h == .w\n then .count * 2\n elif (.w % 2 == 0) and $count == null\n then solve(.w; .h; .count)\n else .count\n end\n end ;\n\ndef task($n):\n range (1; $n+1) as $y\n | range(1; $y + 1) as $x\n | select(($x % 2 == 0) or ($y % 2 == 0))\n | \"\\($y) x \\($x) : \\(solve($y; $x; null))\" ;\n\ntask(10)\n", "language": "Jq" }, { "code": "const count = [0]\nconst dir = [[0, -1], [-1, 0], [0, 1], [1, 0]]\n\nfunction walk(y, x, h, w, grid, len, next)\n if y == 0 || y == h || x == 0 || x == w\n count[1] += 2\n return\n end\n t = y * (w + 1) + x\n grid[t + 1] += UInt8(1)\n grid[len - t + 1] += UInt8(1)\n for i in 1:4\n if grid[t + next[i] + 1] == 0\n walk(y + dir[i][1], x + dir[i][2], h, w, grid, len, next)\n end\n end\n grid[t + 1] -= 1\n grid[len - t + 1] -= 1\nend\n\nfunction cutrectangle(hh, ww, recur)\n if isodd(hh)\n h, w = ww, hh\n else\n h, w = hh, ww\n end\n if isodd(h)\n return 0\n elseif w == 1\n return 1\n elseif w == 2\n return h\n elseif h == 2\n return w\n end\n cy = div(h, 2)\n cx = div(w, 2)\n len = (h + 1) * (w + 1)\n grid = zeros(UInt8, len)\n len -= 1\n next = [-1, -w - 1, 1, w + 1]\n if recur\n count[1] = 0\n end\n for x in cx + 1:w - 1\n t = cy * (w + 1) + x\n grid[t + 1] = 1\n grid[len - t + 1] = 1\n walk(cy - 1, x, h, w, grid, len, next)\n end\n count[1] += 1\n if h == w\n count[1] *= 2\n elseif iseven(w) && recur\n cutrectangle(w, h, false)\n end\n return count[1]\nend\n\nfunction runtest()\n for y in 1:10, x in 1:y\n if iseven(x) || iseven(y)\n println(\"$y x $x: $(cutrectangle(y, x, true))\")\n end\n end\nend\n\nruntest()\n", "language": "Julia" }, { "code": "// version 1.0.6\n\nobject RectangleCutter {\n private var w: Int = 0\n private var h: Int = 0\n private var len: Int = 0\n private var cnt: Long = 0\n\n private lateinit var grid: ByteArray\n private val next = IntArray(4)\n private val dir = arrayOf(\n intArrayOf(0, -1),\n intArrayOf(-1, 0),\n intArrayOf(0, 1),\n intArrayOf(1, 0)\n )\n\n private fun walk(y: Int, x: Int) {\n if (y == 0 || y == h || x == 0 || x == w) {\n cnt += 2\n return\n }\n val t = y * (w + 1) + x\n grid[t]++\n grid[len - t]++\n (0..3).filter { grid[t + next[it]] == 0.toByte() }\n .forEach { walk(y + dir[it][0], x + dir[it][1]) }\n grid[t]--\n grid[len - t]--\n }\n\n fun solve(hh: Int, ww: Int, recur: Boolean): Long {\n var t: Int\n h = hh\n w = ww\n if ((h and 1) != 0) {\n t = w\n w = h\n h = t\n }\n if ((h and 1) != 0) return 0L\n if (w == 1) return 1L\n if (w == 2) return h.toLong()\n if (h == 2) return w.toLong()\n val cy = h / 2\n val cx = w / 2\n len = (h + 1) * (w + 1)\n grid = ByteArray(len)\n len--\n next[0] = -1\n next[1] = -w - 1\n next[2] = 1\n next[3] = w + 1\n if (recur) cnt = 0L\n for (x in cx + 1 until w) {\n t = cy * (w + 1) + x\n grid[t] = 1\n grid[len - t] = 1\n walk(cy - 1, x)\n }\n cnt++\n if (h == w) cnt *= 2\n else if ((w and 1) == 0 && recur) solve(w, h, false)\n return cnt\n }\n}\n\nfun main(args: Array<String>) {\n for (y in 1..10) {\n for (x in 1..y) {\n if ((x and 1) == 0 || (y and 1) == 0) {\n println(\"${\"%2d\".format(y)} x ${\"%2d\".format(x)}: ${RectangleCutter.solve(y, x, true)}\")\n }\n }\n }\n}\n", "language": "Kotlin" }, { "code": "function array1D(w, d)\n local t = {}\n for i=1,w do\n table.insert(t, d)\n end\n return t\nend\n\nfunction array2D(h, w, d)\n local t = {}\n for i=1,h do\n table.insert(t, array1D(w, d))\n end\n return t\nend\n\nfunction push(s, v)\n s[#s + 1] = v\nend\n\nfunction pop(s)\n return table.remove(s, #s)\nend\n\nfunction empty(s)\n return #s == 0\nend\n\nDIRS = {\n {0, -1},\n {-1, 0},\n {0, 1},\n {1, 0}\n}\n\nfunction printResult(aa)\n for i,u in pairs(aa) do\n io.write(\"[\")\n for j,v in pairs(u) do\n if j > 1 then\n io.write(\", \")\n end\n io.write(v)\n end\n print(\"]\")\n end\nend\n\nfunction cutRectangle(w, h)\n if w % 2 == 1 and h % 2 == 1 then\n return nil\n end\n\n local grid = array2D(h, w, 0)\n local stack = {}\n\n local half = math.floor((w * h) / 2)\n local bits = 2 ^ half - 1\n\n while bits > 0 do\n for i=1,half do\n local r = math.floor((i - 1) / w)\n local c = (i - 1) % w\n if (bits & (1 << (i - 1))) ~= 0 then\n grid[r + 1][c + 1] = 1\n else\n grid[r + 1][c + 1] = 0\n end\n grid[h - r][w - c] = 1 - grid[r + 1][c + 1]\n end\n\n push(stack, 0)\n grid[1][1] = 2\n local count = 1\n while not empty(stack) do\n local pos = pop(stack)\n\n local r = math.floor(pos / w)\n local c = pos % w\n\n for i,dir in pairs(DIRS) do\n local nextR = r + dir[1]\n local nextC = c + dir[2]\n\n if nextR >= 0 and nextR < h and nextC >= 0 and nextC < w then\n if grid[nextR + 1][nextC + 1] == 1 then\n push(stack, nextR * w + nextC)\n grid[nextR + 1][nextC + 1] = 2\n count = count + 1\n end\n end\n end\n end\n if count == half then\n printResult(grid)\n print()\n end\n\n -- loop end\n bits = bits - 2\n end\nend\n\ncutRectangle(2, 2)\ncutRectangle(4, 3)\n", "language": "Lua" }, { "code": "ClearAll[CutRectangle]\ndirs = AngleVector /@ Most[Range[0, 2 Pi, Pi/2]];\nCutRectangle[nm : {n_, m_}] := Module[{start, stop, count, sols},\n If[OddQ[n] \\[And] OddQ[m], Return[<|\"Count\" -> 0, \"Solutions\" -> {}|>]];\n\n start = {0, 0};\n stop = nm;\n ClearAll[ValidPosition, ValidRoute, ProceedStep];\n ValidPosition[{x_, y_}] := 0 <= x <= n \\[And] 0 <= y <= m;\n ValidRoute[route_List] := Module[{},\n If[MatchQ[route[[All, 1]], {0 .., Except[0] .., 0, ___}], Return[False]]; (* once it leaves the left border, don't return (disjoint pieces) *)\n If[MatchQ[route[[All, 2]], {0 .., Except[0] .., 0, ___}], Return[False]];(* once it leaves the bottom border, don't return (disjoint pieces) *)\n\n True\n ];\n ProceedStep[nnmm : {nn_, mm_}, steps1_List, steps2_List] := Module[{nextposs, newsteps1, newsteps2, route},\n If[Last[steps1] == Last[steps2],\n route = Join[Most[steps1], Reverse[steps2]];\n If[ValidRoute[route],\n count++;\n AppendTo[sols, route];\n ]\n ,\n If[Length[steps1] >= 2,\n If[Take[steps1, -2] == Reverse[Take[steps2, -2]],\n route = Join[Most[steps1], Reverse[Most[steps2]]];\n If[ValidRoute[route],\n count++;\n AppendTo[sols, route];\n ]\n ]\n ]\n ];\n nextposs = {Last[steps1] + #, Last[steps2] - #} & /@ dirs;\n nextposs //= Select[First/*ValidPosition];\n nextposs //= Select[Last/*ValidPosition];\n nextposs //= Select[! MemberQ[steps1, First[#]] &];\n nextposs //= Select[! MemberQ[steps2, Last[#]] &];\n nextposs //= Select[! MemberQ[Most[steps2], First[#]] &];\n nextposs //= Select[! MemberQ[Most[steps1], Last[#]] &];\n\n Do[\n newsteps1 = Append[steps1, First[np]];\n newsteps2 = Append[steps2, Last[np]];\n ProceedStep[nnmm, newsteps1, newsteps2]\n ,\n {np, nextposs}\n ]\n ];\n count = 0;\n sols = {};\n ProceedStep[nm, {start}, {stop}];\n <|\"Count\" -> count, \"Solutions\" -> sols|>\n ]\n\nmaxsize = 6;\nsols = Reap[Do[\n If[EvenQ[i] \\[Or] EvenQ[j],\n If[i >= j,\n Sow@{i, j, CutRectangle[{i, j}][\"Count\"]}\n ]\n ],\n {i, maxsize},\n {j, maxsize}\n ]][[2, 1]];\nColumn[Row[{#1, \" \\[Times] \", #2, \": \", #3}] & @@@ sols]\n", "language": "Mathematica" }, { "code": "size = {4, 3};\ncr = CutRectangle[size];\nGraphics[{Style[Rectangle[{0, 0}, size], FaceForm[], EdgeForm[Red]], Style[Arrow[#], Black], Style[Point[#], Black]}, ] & /@ cr[\"Solutions\"]\n", "language": "Mathematica" }, { "code": "import strformat\n\nvar\n w, h: int\n grid: seq[byte]\n next: array[4, int]\n count: int\n\nconst Dirs = [[0, -1], [-1, 0], [0, 1], [1, 0]]\n\ntemplate odd(n: int): bool = (n and 1) != 0\n\n#------------------------------------------------------------------------------\n\nproc walk(y, x: int) =\n\n if y == 0 or y == h or x == 0 or x == w:\n inc count, 2\n return\n\n let t = y * (w + 1) + x\n inc grid[t]\n inc grid[grid.high - t]\n\n for i, dir in Dirs:\n if grid[t + next[i]] == 0:\n walk(y + dir[0], x + dir[1])\n\n dec grid[t]\n dec grid[grid.high - t]\n\n#------------------------------------------------------------------------------\n\nproc solve(y, x: int; recursive: bool): int =\n\n h = y\n w = x\n if odd(h): swap w, h\n\n if odd(h): return 0\n if w == 1: return 1\n if w == 2: return h\n if h == 2: return w\n\n let cy = h div 2\n let cx = w div 2\n\n grid = newSeq[byte]((w + 1) * (h + 1))\n\n next[0] = -1\n next[1] = -w - 1\n next[2] = 1\n next[3] = w + 1\n\n if recursive: count = 0\n\n for x in (cx + 1)..<w:\n let t = cy * (w + 1) + x\n grid[t] = 1\n grid[grid.high - t] = 1\n walk(cy - 1, x)\n inc count\n\n if h == w:\n count *= 2\n elif not odd(w) and recursive:\n discard solve(w, h, false)\n\n result = count\n\n#——————————————————————————————————————————————————————————————————————————————\n\nfor y in 1..10:\n for x in 1..y:\n if not odd(x) or not odd(y):\n echo &\"{y:2d} x {x:2d}: {solve(y, x, true)}\"\n", "language": "Nim" }, { "code": "use strict;\nuse warnings;\nmy @grid = 0;\n\nmy ($w, $h, $len);\nmy $cnt = 0;\n\nmy @next;\nmy @dir = ([0, -1], [-1, 0], [0, 1], [1, 0]);\n\nsub walk {\n my ($y, $x) = @_;\n\n if (!$y || $y == $h || !$x || $x == $w) {\n\t$cnt += 2;\n\treturn;\n }\n\n my $t = $y * ($w + 1) + $x;\n $grid[$_]++ for $t, $len - $t;\n\n for my $i (0 .. 3) {\n\tif (!$grid[$t + $next[$i]]) {\n\t walk($y + $dir[$i]->[0], $x + $dir[$i]->[1]);\n\t}\n }\n\n $grid[$_]-- for $t, $len - $t;\n}\n\nsub solve {\n my ($hh, $ww, $recur) = @_;\n my ($t, $cx, $cy, $x);\n ($h, $w) = ($hh, $ww);\n\n if ($h & 1) { ($t, $w, $h) = ($w, $h, $w); }\n if ($h & 1) { return 0; }\n if ($w == 1) { return 1; }\n if ($w == 2) { return $h; }\n if ($h == 2) { return $w; }\n\n {\n\tuse integer;\n\t($cy, $cx) = ($h / 2, $w / 2);\n }\n\n $len = ($h + 1) * ($w + 1);\n @grid = ();\n $grid[$len--] = 0;\n\n @next = (-1, -$w - 1, 1, $w + 1);\n\n if ($recur) { $cnt = 0; }\n for ($x = $cx + 1; $x < $w; $x++) {\n\t$t = $cy * ($w + 1) + $x;\n\t@grid[$t, $len - $t] = (1, 1);\n\twalk($cy - 1, $x);\n }\n $cnt++;\n\n if ($h == $w) {\n\t$cnt *= 2;\n } elsif (!($w & 1) && $recur) {\n\tsolve($w, $h);\n }\n\n return $cnt;\n}\n\nsub MAIN {\n print \"ok\\n\";\n my ($y, $x);\n for my $y (1 .. 10) {\n\tfor my $x (1 .. $y) {\n\t if (!($x & 1) || !($y & 1)) {\n\t\tprintf(\"%d x %d: %d\\n\", $y, $x, solve($y, $x, 1));\n\t }\n\t}\n }\n}\n\nMAIN();\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">show</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- max number to show\n -- (nb mirrors are not shown)</span>\n <span style=\"color: #000000;\">chance</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1000</span> <span style=\"color: #000080;font-style:italic;\">-- 1=always, 2=50%, 3=33%, etc</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">grid</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">gh</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- = length(grid),</span>\n <span style=\"color: #000000;\">gw</span> <span style=\"color: #000080;font-style:italic;\">-- = length(grid[1])</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ty1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">ty2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">tx1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">tx2</span> <span style=\"color: #000080;font-style:italic;\">-- target {y,x}s</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">mirror</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- plant/reset ch and the symmetric copy</span>\n <span style=\"color: #000000;\">grid</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">ch</span>\n <span style=\"color: #000000;\">grid</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">gh</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">gw</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">ch</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">enum</span> <span style=\"color: #000000;\">RIGHT</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">UP</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">DOWN</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">LEFT</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">dyx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #000000;\">chx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"-||-\"</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">search</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">level</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">level</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">grid</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #008000;\">'x'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">mirror</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'x'</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">dy</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">dyx</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">ny</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nx</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">dy</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">yy</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">xx</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">dy</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">grid</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ny</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nx</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #008000;\">' '</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">chx</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">mirror</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ny</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'-'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">mirror</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ny</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nx</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">meet</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">yy</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">ty1</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">yy</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">ty2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xx</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">tx1</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">xx</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">tx2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">meet</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">show</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">rand</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">chance</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">chance</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">show</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">g</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">grid</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (make copy/avoid reset)\n -- fill in(/overwrite) the last cut, if any</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ty1</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">ty2</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ty1</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tx1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">'|'</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">tx1</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">tx2</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ty1</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">tx1</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">tx1</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"--\"</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'\\n'</span><span style=\"color: #0000FF;\">)&</span><span style=\"color: #008000;\">\"\\n\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">grid</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">yy</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">xx</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #008000;\">'+'</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000080;font-style:italic;\">-- (minor gain)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">RIGHT</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">LEFT</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #000080;font-style:italic;\">-- (kinda true!)</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">search</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">yy</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">xx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">level</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">mirror</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ny</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'-'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">mirror</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ny</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nx</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">level</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000080;font-style:italic;\">-- ((level=0)==leave outer edges 'x' for next iteration)</span>\n <span style=\"color: #000000;\">mirror</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">count</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">make_grid</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- The outer edges are 'x'; the inner '+' become 'x' when visited.\n -- Likewise edges are cuts but the inner ones get filled in later.</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tb</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"x\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"--\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">hz</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">'x'</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"+\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)&</span><span style=\"color: #008000;\">'x'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">)&</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">vt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"|\"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)&</span><span style=\"color: #008000;\">\"|\\n\"</span>\n <span style=\"color: #000000;\">grid</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tb</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">vt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">hz</span><span style=\"color: #0000FF;\">)&</span><span style=\"color: #000000;\">tb</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'\\n'</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- set size (for mirroring) and target info:</span>\n <span style=\"color: #000000;\">gh</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">grid</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000000;\">gw</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">grid</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">ty1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">even</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000000;\">ty2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">ty1</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">odd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">2</span>\n <span style=\"color: #000000;\">tx1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #000000;\">tx2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tx1</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">odd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">3</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">side</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">make_grid</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- search top to mid-point</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">last</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">last</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">search</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">RIGHT</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- left to right</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">last</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">even</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">last</span> <span style=\"color: #000080;font-style:italic;\">-- (un-double the centre line)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">count</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #000080;font-style:italic;\">--atom t0 = time()\n -- nb sub-optimal: obviously \"grid\" was designed for easy display, rather than speed.</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">JS</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #000080;font-style:italic;\">-- 24s\n --for y=1 to 10 do -- (gave up on &gt;10x8)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">y</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000080;font-style:italic;\">-- for x=1 to min(y,8) do -- 4 mins 16s (with y to 10)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">even</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">side</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">y</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">side</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d x %d: %d\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000080;font-style:italic;\">--?elapsed(time()-t0)</span>\n<!--\n", "language": "Phix" }, { "code": "def cut_it(h, w):\n dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n if h % 2: h, w = w, h\n if h % 2: return 0\n if w == 1: return 1\n count = 0\n\n next = [w + 1, -w - 1, -1, 1]\n blen = (h + 1) * (w + 1) - 1\n grid = [False] * (blen + 1)\n\n def walk(y, x, count):\n if not y or y == h or not x or x == w:\n return count + 1\n\n t = y * (w + 1) + x\n grid[t] = grid[blen - t] = True\n\n if not grid[t + next[0]]:\n count = walk(y + dirs[0][0], x + dirs[0][1], count)\n if not grid[t + next[1]]:\n count = walk(y + dirs[1][0], x + dirs[1][1], count)\n if not grid[t + next[2]]:\n count = walk(y + dirs[2][0], x + dirs[2][1], count)\n if not grid[t + next[3]]:\n count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n grid[t] = grid[blen - t] = False\n return count\n\n t = h // 2 * (w + 1) + w // 2\n if w % 2:\n grid[t] = grid[t + 1] = True\n count = walk(h // 2, w // 2 - 1, count)\n res = count\n count = 0\n count = walk(h // 2 - 1, w // 2, count)\n return res + count * 2\n else:\n grid[t] = True\n count = walk(h // 2, w // 2 - 1, count)\n if h == w:\n return count * 2\n count = walk(h // 2 - 1, w // 2, count)\n return count\n\ndef main():\n for w in xrange(1, 10):\n for h in xrange(1, w + 1):\n if not((w * h) % 2):\n print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n", "language": "Python" }, { "code": "try:\n import psyco\nexcept ImportError:\n pass\nelse:\n psyco.full()\n\nw, h = 0, 0\ncount = 0\nvis = []\n\ndef cwalk(y, x, d):\n global vis, count, w, h\n if not y or y == h or not x or x == w:\n count += 1\n return\n\n vis[y][x] = vis[h - y][w - x] = 1\n\n if x and not vis[y][x - 1]:\n cwalk(y, x - 1, d | 1)\n if (d & 1) and x < w and not vis[y][x+1]:\n cwalk(y, x + 1, d|1)\n if y and not vis[y - 1][x]:\n cwalk(y - 1, x, d | 2)\n if (d & 2) and y < h and not vis[y + 1][x]:\n cwalk(y + 1, x, d | 2)\n\n vis[y][x] = vis[h - y][w - x] = 0\n\ndef count_only(x, y):\n global vis, count, w, h\n count = 0\n w = x\n h = y\n\n if (h * w) & 1:\n return count\n if h & 1:\n w, h = h, w\n\n vis = [[0] * (w + 1) for _ in xrange(h + 1)]\n vis[h // 2][w // 2] = 1\n\n if w & 1:\n vis[h // 2][w // 2 + 1] = 1\n\n res = 0\n if w > 1:\n cwalk(h // 2, w // 2 - 1, 1)\n res = 2 * count - 1\n count = 0\n if w != h:\n cwalk(h // 2 + 1, w // 2, 3 if (w & 1) else 2)\n\n res += 2 * count - (not (w & 1))\n else:\n res = 1\n\n if w == h:\n res = 2 * res + 2\n return res\n\ndef main():\n for y in xrange(1, 10):\n for x in xrange(1, y + 1):\n if not (x & 1) or not (y & 1):\n print \"%d x %d: %d\" % (y, x, count_only(x, y))\n\nmain()\n", "language": "Python" }, { "code": "#lang racket\n\n(define (cuts W H [count 0]) ; count = #f => visualize instead\n (define W1 (add1 W)) (define H1 (add1 H))\n (define B (make-vector (* W1 H1) #f))\n (define (fD d) (cadr (assq d '([U D] [D U] [L R] [R L] [#f #f] [#t #t]))))\n (define (fP p) (- (* W1 H1) p 1))\n (define (Bset! p d) (vector-set! B p d) (vector-set! B (fP p) (fD d)))\n (define center (/ (fP 0) 2))\n (when (integer? center) (Bset! center #t))\n (define (run c* d)\n (define p (- center c*))\n (Bset! p d)\n (let loop ([p p])\n (define-values [q r] (quotient/remainder p W1))\n (if (and (< 0 r W) (< 0 q H))\n (for ([d '(U D L R)])\n (define n (+ p (case d [(U) (- W1)] [(D) W1] [(L) -1] [(R) 1])))\n (unless (vector-ref B n) (Bset! n (fD d)) (loop n) (Bset! n #f)))\n (if count (set! count (add1 count)) (visualize B W H))))\n (Bset! p #f))\n (when (even? W) (run (if (odd? H) (/ W1 2) W1) 'D))\n (when (even? H) (run (if (odd? W) 1/2 1) 'R))\n (or count (void)))\n\n(define (visualize B W H)\n (define W2 (+ 2 (* W 2))) (define H2 (+ 1 (* H 2)))\n (define str (make-string (* H2 W2) #\\space))\n (define (Sset! i c) (string-set! str i c))\n (for ([i (in-range (- W2 1) (* W2 H2) W2)]) (Sset! i #\\newline))\n (for ([i (in-range 0 (- W2 1))]) (Sset! i #\\#) (Sset! (+ i (* W2 H 2)) #\\#))\n (for ([i (in-range 0 (* W2 H2) W2)]) (Sset! i #\\#) (Sset! (+ i W2 -2) #\\#))\n (for* ([i (add1 W)] [j (add1 H)])\n (define p (* 2 (+ i (* j W2))))\n (define b (vector-ref B (+ i (* j (+ W 1)))))\n (cond [b (Sset! p #\\#)\n (define d (case b [(U) (- W2)] [(D) W2] [(R) 1] [(L) -1]))\n (when (integer? d) (Sset! (+ p d) #\\#))]\n [(equal? #\\space (string-ref str p)) (Sset! p #\\.)]))\n (display str) (newline))\n\n(printf \"Counts:\\n\")\n(for* ([W (in-range 1 10)] [H (in-range 1 (add1 W))]\n #:unless (and (odd? W) (odd? H)))\n (printf \"~s x ~s: ~s\\n\" W H (cuts W H)))\n\n(newline)\n(cuts 4 3 #f)\n", "language": "Racket" }, { "code": "sub solve($hh, $ww, $recurse) {\n my ($h, $w, $t, @grid) = $hh, $ww, 0;\n state $cnt;\n $cnt = 0 if $recurse;\n\n ($t, $w, $h) = ($w, $h, $w) if $h +& 1;\n return 0 if $h == 1;\n return 1 if $w == 1;\n return $h if $w == 2;\n return $w if $h == 2;\n\n my ($cy, $cx) = ($h, $w) «div» 2;\n my $len = ($h + 1) × ($w + 1);\n @grid[$len--] = 0;\n my @next = -1, -$w-1, 1, $w+1;\n\n for $cx+1 ..^ $w -> $x {\n $t = $cy × ($w + 1) + $x;\n @grid[$_] = 1 for $t, $len-$t;\n walk($cy - 1, $x);\n }\n\n sub walk($y, $x) {\n constant @dir = <0 -1 0 1> Z <-1 0 1 0>;\n $cnt += 2 and return if not $y or $y == $h or not $x or $x == $w;\n my $t = $y × ($w+1) + $x;\n @grid[$_]++ for $t, $len-$t;\n walk($y + @dir[$_;0], $x + @dir[$_;1]) if not @grid[$t + @next[$_]] for 0..3;\n @grid[$_]-- for $t, $len-$t;\n }\n\n $cnt++;\n if $h == $w { $cnt ×= 2 }\n elsif $recurse and not $w +& 1 { solve($w, $h, False) }\n $cnt\n}\n\n((1..9 X 1..9).grep:{ .[0] ≥ .[1] }).flat.map: -> $y, $x {\n say \"$y × $x: \" ~ solve $y, $x, True unless $x +& 1 and $y +& 1;\n}\n", "language": "Raku" }, { "code": "/*REXX program cuts rectangles into two symmetric pieces, the rectangles are cut along */\n/*────────────────────────────────────────────────── unit dimensions and may be rotated.*/\nnumeric digits 20 /*be able to handle some big integers. */\nparse arg N .; if N=='' | N==\",\" then N= 10 /*N not specified? Then use default.*/\ndir.= 0; dir.0.1= -1; dir.1.0= -1; dir.2.1= 1; dir.3.0= 1 /*the four directions*/\n\n do y=2 to N; say /*calculate rectangles up to size NxN.*/\n do x=1 for y; if x//2 & y//2 then iterate /*Both X&Y odd? Skip.*/\n z= solve(y,x,1); _= comma(z); _= right(_, max(14, length(_))) /*align output.*/\n say right(y, 9) \"x\" right(x, 2) 'rectangle can be cut' _ \"way\"s(z).\n end /*x*/\n end /*y*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncomma: procedure; arg _; do k=length(_)-3 to 1 by -3; _=insert(',',_,k); end; return _\ns: if arg(1)=1 then return arg(3); return word( arg(2) 's', 1) /*pluralizer.*/\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsolve: procedure expose # @. dir. h len next. w; @.= 0 /*zero rectangle coördinates.*/\n parse arg h,w,recur /*get values for some args. */\n if h//2 then do; t= w; w= h; h= t; if h//2 then return 0\n end\n if w==1 then return 1\n if w==2 then return h\n if h==2 then return w /* [↓] % is REXX's integer ÷*/\n cy= h % 2; cx= w % 2; wp= w + 1 /*cut the rectangle in half. */\n len= (h+1) * wp - 1 /*extend area of rectangle. */\n next.0= '-1'; next.1= -wp; next.2= 1; next.3= wp /*direction & distance*/\n if recur then #= 0\n cywp= cy * wp /*shortcut calculation*/\n do x=cx+1 to w-1; t= cywp + x; @.t= 1\n _= len - t; @._= 1; call walk cy - 1, x\n end /*x*/\n #= # + 1\n if h==w then #= # + # /*double rectangle cut count.*/\n else if w//2==0 & recur then call solve w, h, 0\n return #\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nwalk: procedure expose # @. dir. h len next. w wp; parse arg y,x\n if y==h | x==0 | x==w | y==0 then do; #= # + 2; return; end\n t= y*wp + x; @.t= @.t + 1; _= len - t\n @._= @._ + 1\n do j=0 for 4; _= t + next.j /*try each of 4 directions.*/\n if @._==0 then call walk y + dir.j.0, x + dir.j.1\n end /*j*/\n @.t= @.t - 1\n _= len - t; @._= @._ - 1; return\n", "language": "REXX" }, { "code": "/*REXX program cuts rectangles into two symmetric pieces, the rectangles are cut along */\n/*────────────────────────────────────────────────── unit dimensions and may be rotated.*/\nnumeric digits 40 /*be able to handle some big integers. */\nparse arg m . /*obtain optional argument from the CL.*/\nif m=='' | m==\",\" then m= 9 /*Not specified? Then use the default.*/\nif m<0 then start= max(2, abs(m) ) /*<0? Then just use this size rectangle*/\n else start= 2 /*start from two for regular invocation*/\ndir.= 0; dir.0.1= -1; dir.1.0= -1; dir.2.1= 1; dir.3.0= 1 /*the 4 directions.*/\n $= '# @. dir. h len next. w wp'\n /*define the default for memoizations. */\n do y=start to abs(m); yOdd= y//2; say /*calculate rectangles up to size MxM.*/\n do x=1 for y; if x//2 then if yOdd then iterate /*X and Y odd? Skip.*/\n z= solve(y, x, 1); zc= comma(z) /*add commas to the result for SOLVE. */\n zca= right(zc, max(14,length(zc) ) ) /*align the output for better perusing.*/\n say right(y, 9) \"x\" right(x, 2) 'rectangle can be cut' zca \"way\"s(z).\n end /*x*/\n end /*y*/\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncomma: procedure; arg ?; do k=length(?)-3 to 1 by -3; ?=insert(',',?,k); end; return ?\ns: if arg(1)=1 then return arg(3); return word(arg(2) 's', 1) /*pluralizer.*/\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsolve: procedure expose ($); @.= 0 /*zero rectangle coördinates.*/\n parse arg h,w,recurse /*get values for some args. */\n if w==3 then do; z= h % 2 + 2; return 2**z - (z + z) + 1\n end\n if h//2 then do; t= w; w= h; h= t; if h//2 then return 0\n end\n if w==1 then return 1\n if w==2 then return h\n if h==2 then return w /* [↓] % is REXX's integer division.*/\n cy= h % 2; cx= w % 2; wp= w + 1 /*cut the [XY] rectangle in half. */\n len= (h+1) * wp - 1 /*extend the area of the rectangle. */\n next.0= '-1'; next.1= -wp; next.2= 1; next.3= wp /*direction & distance*/\n if recurse then #= 0 /*doing recursion ? */\n cywp= cy * wp /*shortcut calculation*/\n do x=cx+1 to w-1; t= cywp + x; @.t= 1\n __= len - t; @.__= 1; call walk cy - 1, x\n end /*x*/\n #= # + 1\n if h==w then #= # + # /*double the count of rectangle cuts. */\n else if w//2==0 then if recurse then call solve w, h, 0\n return #\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nwalk: procedure expose ($); parse arg y,x\n if y==h then do; #= # + 2; return; end /* ◄──┐ REXX short circuit. */\n if x==0 then do; #= # + 2; return; end /* ◄──┤ \" \" \" */\n if x==w then do; #= # + 2; return; end /* ◄──┤ \" \" \" */\n if y==0 then do; #= # + 2; return; end /* ◄──┤ \" \" \" */\n q= y*wp + x; @.q= @.q + 1; _= len - q /* │ordered by most likely ►──┐*/\n @._= @._ + 1 /* └──────────────────────────┘*/\n do j=0 for 4; _= q + next.j /*try each of the four directions.*/\n if @._==0 then do; yn= y + dir.j.0\n if yn==h then do; #= # + 2; iterate; end\n xn= x + dir.j.1\n if xn==0 then do; #= # + 2; iterate; end\n if xn==w then do; #= # + 2; iterate; end\n if yn==0 then do; #= # + 2; iterate; end\n call walk yn, xn\n end\n end /*j*/\n @.q= @.q - 1; _= len - q; @._= @._ - 1; return\n", "language": "REXX" }, { "code": "def cut_it(h, w)\n if h.odd?\n return 0 if w.odd?\n h, w = w, h\n end\n return 1 if w == 1\n\n nxt = [[w+1, 1, 0], [-w-1, -1, 0], [-1, 0, -1], [1, 0, 1]] # [next,dy,dx]\n blen = (h + 1) * (w + 1) - 1\n grid = [false] * (blen + 1)\n\n walk = lambda do |y, x, count=0|\n return count+1 if y==0 or y==h or x==0 or x==w\n t = y * (w + 1) + x\n grid[t] = grid[blen - t] = true\n nxt.each do |nt, dy, dx|\n count += walk[y + dy, x + dx] unless grid[t + nt]\n end\n grid[t] = grid[blen - t] = false\n count\n end\n\n t = h / 2 * (w + 1) + w / 2\n if w.odd?\n grid[t] = grid[t + 1] = true\n count = walk[h / 2, w / 2 - 1]\n count + walk[h / 2 - 1, w / 2] * 2\n else\n grid[t] = true\n count = walk[h / 2, w / 2 - 1]\n return count * 2 if h == w\n count + walk[h / 2 - 1, w / 2]\n end\nend\n\nfor w in 1..9\n for h in 1..w\n puts \"%d x %d: %d\" % [w, h, cut_it(w, h)] if (w * h).even?\n end\nend\n", "language": "Ruby" }, { "code": "class Rectangle\n DIRS = [[1, 0], [-1, 0], [0, -1], [0, 1]]\n def initialize(h, w)\n raise ArgumentError if (h.odd? and w.odd?) or h<=0 or w<=0\n @h, @w = h, w\n @limit = h * w / 2\n end\n\n def cut(disp=true)\n @cut = {}\n @select = []\n @result = []\n @grid = make_grid\n walk(0,0)\n display if disp\n @result\n end\n\n def make_grid\n Array.new(@h+1) {|i| Array.new(@w+1) {|j| true if i<@h and j<@w }}\n end\n\n def walk(y, x)\n @grid[y][x] = @grid[@h-y-1][@w-x-1] = false\n @select.push([y,x])\n select = @select.sort\n unless @cut[select]\n @cut[select] = true\n if @select.size == @limit\n @result << select\n else\n search_next.each {|yy,xx| walk(yy,xx)}\n end\n end\n @select.pop\n @grid[y][x] = @grid[@h-y-1][@w-x-1] = true\n end\n\n def search_next\n nxt = {}\n @select.each do |y,x|\n DIRS.each do |dy, dx|\n nxt[[y+dy, x+dx]] = true if @grid[y+dy][x+dx]\n end\n end\n nxt.keys\n end\n\n def display\n @result.each do |select|\n @grid = make_grid\n select.each {|y,x| @grid[y][x] = false}\n puts to_s\n end\n end\n\n def to_s\n text = Array.new(@h*2+1) {\" \" * (@w*4+1)}\n for i in 0..@h\n for j in 0..@w\n text[i*2][j*4+1,3] = \"---\" if @grid[i][j] != @grid[i-1][j]\n text[i*2+1][j*4] = \"|\" if @grid[i][j] != @grid[i][j-1]\n text[i*2][j*4] = \"+\"\n end\n end\n text.join(\"\\n\")\n end\nend\n\nrec = Rectangle.new(2,2)\nputs rec.cut.size\n\nrec = Rectangle.new(3,4)\nputs rec.cut.size\n", "language": "Ruby" }, { "code": "fn cwalk(mut vis: &mut Vec<Vec<bool>>, count: &mut isize, w: usize, h: usize, y: usize, x: usize, d: usize) {\n if x == 0 || y == 0 || x == w || y == h {\n *count += 1;\n return;\n }\n\n vis[y][x] = true;\n vis[h - y][w - x] = true;\n\n if x != 0 && ! vis[y][x - 1] {\n cwalk(&mut vis, count, w, h, y, x - 1, d | 1);\n }\n if d & 1 != 0 && x < w && ! vis[y][x+1] {\n cwalk(&mut vis, count, w, h, y, x + 1, d | 1);\n }\n if y != 0 && ! vis[y - 1][x] {\n cwalk(&mut vis, count, w, h, y - 1, x, d | 2);\n }\n if d & 2 != 0 && y < h && ! vis[y + 1][x] {\n cwalk(&mut vis, count, w, h, y + 1, x, d | 2);\n }\n\n vis[y][x] = false;\n vis[h - y][w - x] = false;\n}\n\nfn count_only(x: usize, y: usize) -> isize {\n let mut count = 0;\n let mut w = x;\n let mut h = y;\n\n if (h * w) & 1 != 0 {\n return count;\n }\n if h & 1 != 0 {\n std::mem::swap(&mut w, &mut h);\n }\n\n let mut vis = vec![vec![false; w + 1]; h + 1];\n vis[h / 2][w / 2] = true;\n\n if w & 1 != 0 {\n vis[h / 2][w / 2 + 1] = true;\n }\n let mut res;\n if w > 1 {\n cwalk(&mut vis, &mut count, w, h, h / 2, w / 2 - 1, 1);\n res = 2 * count - 1;\n count = 0;\n if w != h {\n cwalk(&mut vis, &mut count, w, h, h / 2 + 1, w / 2, if w & 1 != 0 { 3 } else { 2 });\n }\n res += 2 * count - if w & 1 == 0 { 1 } else { 0 };\n }\n else {\n res = 1;\n }\n\n if w == h {\n res = 2 * res + 2;\n }\n res\n}\n\nfn main() {\n for y in 1..10 {\n for x in 1..y + 1 {\n if x & 1 == 0 || y & 1 == 0 {\n println!(\"{} x {}: {}\", y, x, count_only(x, y));\n }\n }\n }\n}\n", "language": "Rust" }, { "code": "package require Tcl 8.5\n\nproc walk {y x} {\n global w ww h cnt grid len\n if {!$y || $y==$h || !$x || $x==$w} {\n\tincr cnt 2\n\treturn\n }\n set t [expr {$y*$ww + $x}]\n set m [expr {$len - $t}]\n lset grid $t [expr {[lindex $grid $t] + 1}]\n lset grid $m [expr {[lindex $grid $m] + 1}]\n if {![lindex $grid [expr {$y*$ww + $x-1}]]} {\n\twalk $y [expr {$x-1}]\n }\n if {![lindex $grid [expr {($y-1)*$ww + $x}]]} {\n\twalk [expr {$y-1}] $x\n }\n if {![lindex $grid [expr {$y*$ww + $x+1}]]} {\n\twalk $y [expr {$x+1}]\n }\n if {![lindex $grid [expr {($y+1)*$ww + $x}]]} {\n\twalk [expr {$y+1}] $x\n }\n lset grid $t [expr {[lindex $grid $t] - 1}]\n lset grid $m [expr {[lindex $grid $m] - 1}]\n}\n\n# Factored out core of [solve]\nproc SolveCore {} {\n global w ww h cnt grid len\n set ww [expr {$w+1}]\n set cy [expr {$h / 2}]\n set cx [expr {$w / 2}]\n\n set len [expr {($h+1) * $ww}]\n set grid [lrepeat $len 0]\n incr len -1\n\n for {set x $cx;incr x} {$x < $w} {incr x} {\n\tset t [expr {$cy*$ww+$x}]\n\tlset grid $t 1\n\tlset grid [expr {$len - $t}] 1\n\twalk [expr {$cy - 1}] $x\n }\n incr cnt\n}\nproc solve {H W} {\n global w h cnt\n set h $H\n set w $W\n if {$h & 1} {\n\tset h $W\n\tset w $H\n }\n if {$h & 1} {\n\treturn 0\n }\n if {$w==1} {return 1}\n if {$w==2} {return $h}\n if {$h==2} {return $w}\n\n set cnt 0\n SolveCore\n if {$h==$w} {\n\tincr cnt $cnt\n } elseif {!($w & 1)} {\n\tlassign [list $w $h] h w\n\tSolveCore\n }\n return $cnt\n}\n\napply {{limit} {\n for {set yy 1} {$yy <= $limit} {incr yy} {\n\tfor {set xx 1} {$xx <= $yy} {incr xx} {\n\t if {!($xx&1 && $yy&1)} {\n\t\tputs [format \"%d x %d: %ld\" $yy $xx [solve $yy $xx]]\n\t }\n\t}\n }\n}} 10\n", "language": "Tcl" }, { "code": "import \"./fmt\" for Fmt\n\nvar grid = []\nvar w = 0\nvar h = 0\nvar len = 0\nvar cnt = 0\nvar next = [0] * 4\nvar dir = [[0, -1], [-1, 0], [0, 1], [1, 0]]\n\nvar walk // recursive\nwalk = Fn.new { |y, x|\n if (y == 0 || y == h || x == 0 || x == w) {\n cnt = cnt + 2\n return\n }\n var t = y * (w + 1) + x\n grid[t] = grid[t] + 1\n grid[len-t] = grid[len-t] + 1\n for (i in 0..3) {\n if (grid[t + next[i]] == 0) {\n walk.call(y + dir[i][0], x + dir[i][1])\n }\n }\n grid[t] = grid[t] - 1\n grid[len-t] = grid[len-t] - 1\n}\n\nvar solve // recursive\nsolve = Fn.new { |hh, ww, recur|\n h = hh\n w = ww\n if (h&1 != 0) {\n var t = w\n w = h\n h = t\n }\n if (h&1 != 0) return 0\n if (w == 1) return 1\n if (w == 2) return h\n if (h == 2) return w\n var cy = (h/2).floor\n var cx = (w/2).floor\n len = (h + 1) * (w + 1)\n grid = List.filled(len, 0)\n len = len - 1\n next[0] = -1\n next[1] = -w - 1\n next[2] = 1\n next[3] = w + 1\n if (recur) cnt = 0\n var x = cx + 1\n while (x < w) {\n var t = cy * (w + 1) + x\n grid[t] = 1\n grid[len-t] = 1\n walk.call(cy - 1, x)\n x = x + 1\n }\n cnt = cnt + 1\n if (h == w) {\n cnt = cnt * 2\n } else if ((w&1 == 0) && recur) {\n solve.call(w, h, false)\n }\n return cnt\n}\n\nfor (y in 1..10) {\n for (x in 1..y) {\n if ((x&1 == 0) || (y&1 ==0)) {\n Fmt.print(\"$2d x $2d : $d\", y, x, solve.call(y, x, true))\n }\n }\n}\n", "language": "Wren" }, { "code": "include xpllib; \\for Print\n\nchar Grid;\nint W, H, Len, Cnt;\nint Next(4), Dir;\n\nproc Walk(Y, X);\nint Y, X;\nint I, T;\n[if Y=0 or Y=H or X=0 or X=W then\n [Cnt:= Cnt+2; return];\nT:= Y * (W + 1) + X;\nGrid(T):= Grid(T)+1;\nGrid(Len-T):= Grid(Len-T)+1;\nfor I:= 0 to 4-1 do\n if Grid(T + Next(I)) = 0 then\n Walk(Y+Dir(I,0), X+Dir(I,1));\nGrid(T):= Grid(T)-1;\nGrid(Len-T):= Grid(Len-T)-1;\n];\n\nfunc Solve(HH, WW, Recur);\nint HH, WW, Recur;\nint T, CX, CY, X;\n[H:= HH; W:= WW;\nif H & 1 then [T:= W; W:= H; H:= T];\nif H & 1 then return 0;\nif W = 1 then return 1;\nif W = 2 then return H;\nif H = 2 then return W;\nCY:= H/2; CX:= W/2;\nLen:= (H + 1) * (W + 1);\nGrid:= ReallocMem(Grid, Len);\nFillMem(Grid, 0, Len); Len:= Len-1;\nNext(0):= -1;\nNext(1):= -W - 1;\nNext(2):= 1;\nNext(3):= W + 1;\nif Recur then Cnt:= 0;\nfor X:= CX+1 to W-1 do\n [T:= CY * (W + 1) + X;\n Grid(T):= 1;\n Grid(Len - T):= 1;\n Walk(CY - 1, X);\n ];\nCnt:= Cnt+1;\nif H = W then Cnt:= Cnt * 2\nelse if (W&1) = 0 and Recur then Solve(W, H, 0);\nreturn Cnt;\n];\n\nint Y, X;\n[Grid:= 0;\nDir:= [[0, -1], [-1, 0], [0, 1], [1, 0]];\nfor Y:= 1 to 10 do\n for X:= 1 to Y do\n if (X&1) = 0 or (Y&1) = 0 then\n Print(\"%d x %d: %d\\n\", Y, X, Solve(Y, X, 1));\n]\n", "language": "XPL0" }, { "code": "fcn cut_it(h,w){\n if(h.isOdd){\n if(w.isOdd) return(0);\n t,h,w=h,w,t; // swap w,h: a,b=c,d --> a=c; b=d; so need a tmp\n }\n if(w==1) return(1);\n\n nxt :=T(T(w+1, 1,0), T(-w-1, -1,0), T(-1, 0,-1), T(1, 0,1)); #[next, dy,dx]\n blen:=(h + 1)*(w + 1) - 1;\n grid:=(blen + 1).pump(List(),False); //-->L(False,False...)\n\n walk:='wrap(y,x){ // lambda closure\n if(y==0 or y==h or x==0 or x==w) return(1);\n count,t:=0,y*(w + 1) + x;\n grid[t]=grid[blen - t]=True;\n foreach nt,dy,dx in (nxt){\n if(not grid[t + nt]) count+=self.fcn(y + dy, x + dx,vm.pasteArgs(2));\n }\n grid[t]=grid[blen - t]=False;\n count\n };\n\n t:=h/2*(w + 1) + w/2;\n if(w.isOdd){\n grid[t]=grid[t + 1]=True;\n count:=walk(h/2, w/2 - 1);\n count + walk(h/2 - 1, w/2)*2;\n }else{\n grid[t]=True;\n count:=walk(h/2, w/2 - 1);\n if(h==w) return(count*2);\n count + walk(h/2 - 1, w/2);\n }\n}\n", "language": "Zkl" }, { "code": "foreach w,h in ([1..9],[1..w]){\n if((w*h).isEven) println(\"%d x %d: %d\".fmt(w, h, cut_it(w,h)));\n}\n", "language": "Zkl" } ]
Cut-a-rectangle
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Cyclotomic_polynomial\n", "language": "00-META" }, { "code": "The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n.\n\n\n;Task:\n* Find and print the first 30 cyclotomic polynomials.\n* Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.\n\n\n;See also\n* Wikipedia article, [[wp:Cyclotomic_polynomial|Cyclotomic polynomial]], showing ways to calculate them.\n* The sequence [[oeis:A013594|A013594]] with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.\n\n", "language": "00-TASK" }, { "code": "#include <algorithm>\n#include <iostream>\n#include <initializer_list>\n#include <map>\n#include <vector>\n\nconst int MAX_ALL_FACTORS = 100000;\nconst int algorithm = 2;\nint divisions = 0;\n\n//Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage.\nclass Term {\nprivate:\n long m_coefficient;\n long m_exponent;\n\npublic:\n Term(long c, long e) : m_coefficient(c), m_exponent(e) {\n // empty\n }\n\n Term(const Term &t) : m_coefficient(t.m_coefficient), m_exponent(t.m_exponent) {\n // empty\n }\n\n long coefficient() const {\n return m_coefficient;\n }\n\n long degree() const {\n return m_exponent;\n }\n\n Term operator -() const {\n return { -m_coefficient, m_exponent };\n }\n\n Term operator *(const Term &rhs) const {\n return { m_coefficient * rhs.m_coefficient, m_exponent + rhs.m_exponent };\n }\n\n Term operator +(const Term &rhs) const {\n if (m_exponent != rhs.m_exponent) {\n throw std::runtime_error(\"Exponents not equal\");\n }\n return { m_coefficient + rhs.m_coefficient, m_exponent };\n }\n\n friend std::ostream &operator<<(std::ostream &, const Term &);\n};\n\nstd::ostream &operator<<(std::ostream &os, const Term &t) {\n if (t.m_coefficient == 0) {\n return os << '0';\n }\n if (t.m_exponent == 0) {\n return os << t.m_coefficient;\n }\n if (t.m_coefficient == 1) {\n if (t.m_exponent == 1) {\n return os << 'x';\n }\n return os << \"x^\" << t.m_exponent;\n }\n if (t.m_coefficient == -1) {\n if (t.m_exponent == 1) {\n return os << \"-x\";\n }\n return os << \"-x^\" << t.m_exponent;\n }\n if (t.m_exponent == 1) {\n return os << t.m_coefficient << 'x';\n }\n return os << t.m_coefficient << \"x^\" << t.m_exponent;\n}\n\nclass Polynomial {\npublic:\n std::vector<Term> polynomialTerms;\n\n Polynomial() {\n polynomialTerms.push_back({ 0, 0 });\n }\n\n Polynomial(std::initializer_list<int> values) {\n if (values.size() % 2 != 0) {\n throw std::runtime_error(\"Length must be even.\");\n }\n\n bool ready = false;\n long t;\n for (auto v : values) {\n if (ready) {\n polynomialTerms.push_back({ t, v });\n } else {\n t = v;\n }\n ready = !ready;\n }\n std::sort(\n polynomialTerms.begin(), polynomialTerms.end(),\n [](const Term &t, const Term &u) {\n return u.degree() < t.degree();\n }\n );\n }\n\n Polynomial(const std::vector<Term> &termList) {\n if (termList.size() == 0) {\n polynomialTerms.push_back({ 0, 0 });\n } else {\n for (auto t : termList) {\n if (t.coefficient() != 0) {\n polynomialTerms.push_back(t);\n }\n }\n if (polynomialTerms.size() == 0) {\n polynomialTerms.push_back({ 0, 0 });\n }\n std::sort(\n polynomialTerms.begin(), polynomialTerms.end(),\n [](const Term &t, const Term &u) {\n return u.degree() < t.degree();\n }\n );\n }\n }\n\n Polynomial(const Polynomial &p) : Polynomial(p.polynomialTerms) {\n // empty\n }\n\n long leadingCoefficient() const {\n return polynomialTerms[0].coefficient();\n }\n\n long degree() const {\n return polynomialTerms[0].degree();\n }\n\n bool hasCoefficientAbs(int coeff) {\n for (auto term : polynomialTerms) {\n if (abs(term.coefficient()) == coeff) {\n return true;\n }\n }\n return false;\n }\n\n Polynomial operator+(const Term &term) const {\n std::vector<Term> termList;\n bool added = false;\n for (size_t index = 0; index < polynomialTerms.size(); index++) {\n auto currentTerm = polynomialTerms[index];\n if (currentTerm.degree() == term.degree()) {\n added = true;\n if (currentTerm.coefficient() + term.coefficient() != 0) {\n termList.push_back(currentTerm + term);\n }\n } else {\n termList.push_back(currentTerm);\n }\n }\n if (!added) {\n termList.push_back(term);\n }\n return Polynomial(termList);\n }\n\n Polynomial operator*(const Term &term) const {\n std::vector<Term> termList;\n for (size_t index = 0; index < polynomialTerms.size(); index++) {\n auto currentTerm = polynomialTerms[index];\n termList.push_back(currentTerm * term);\n }\n return Polynomial(termList);\n }\n\n Polynomial operator+(const Polynomial &p) const {\n std::vector<Term> termList;\n int thisCount = polynomialTerms.size();\n int polyCount = p.polynomialTerms.size();\n while (thisCount > 0 || polyCount > 0) {\n if (thisCount == 0) {\n auto polyTerm = p.polynomialTerms[polyCount - 1];\n termList.push_back(polyTerm);\n polyCount--;\n } else if (polyCount == 0) {\n auto thisTerm = polynomialTerms[thisCount - 1];\n termList.push_back(thisTerm);\n thisCount--;\n } else {\n auto polyTerm = p.polynomialTerms[polyCount - 1];\n auto thisTerm = polynomialTerms[thisCount - 1];\n if (thisTerm.degree() == polyTerm.degree()) {\n auto t = thisTerm + polyTerm;\n if (t.coefficient() != 0) {\n termList.push_back(t);\n }\n thisCount--;\n polyCount--;\n } else if (thisTerm.degree() < polyTerm.degree()) {\n termList.push_back(thisTerm);\n thisCount--;\n } else {\n termList.push_back(polyTerm);\n polyCount--;\n }\n }\n }\n return Polynomial(termList);\n }\n\n Polynomial operator/(const Polynomial &v) {\n divisions++;\n\n Polynomial q;\n Polynomial r(*this);\n long lcv = v.leadingCoefficient();\n long dv = v.degree();\n while (r.degree() >= v.degree()) {\n long lcr = r.leadingCoefficient();\n long s = lcr / lcv;\n Term term(s, r.degree() - dv);\n q = q + term;\n r = r + v * -term;\n }\n\n return q;\n }\n\n friend std::ostream &operator<<(std::ostream &, const Polynomial &);\n};\n\nstd::ostream &operator<<(std::ostream &os, const Polynomial &p) {\n auto it = p.polynomialTerms.cbegin();\n auto end = p.polynomialTerms.cend();\n if (it != end) {\n os << *it;\n it = std::next(it);\n }\n while (it != end) {\n if (it->coefficient() > 0) {\n os << \" + \" << *it;\n } else {\n os << \" - \" << -*it;\n }\n it = std::next(it);\n }\n return os;\n}\n\nstd::vector<int> getDivisors(int number) {\n std::vector<int> divisiors;\n long root = (long)sqrt(number);\n for (int i = 1; i <= root; i++) {\n if (number % i == 0) {\n divisiors.push_back(i);\n int div = number / i;\n if (div != i && div != number) {\n divisiors.push_back(div);\n }\n }\n }\n return divisiors;\n}\n\nstd::map<int, std::map<int, int>> allFactors;\n\nstd::map<int, int> getFactors(int number) {\n if (allFactors.find(number) != allFactors.end()) {\n return allFactors[number];\n }\n\n std::map<int, int> factors;\n if (number % 2 == 0) {\n auto factorsDivTwo = getFactors(number / 2);\n factors.insert(factorsDivTwo.begin(), factorsDivTwo.end());\n if (factors.find(2) != factors.end()) {\n factors[2]++;\n } else {\n factors.insert(std::make_pair(2, 1));\n }\n if (number < MAX_ALL_FACTORS) {\n allFactors.insert(std::make_pair(number, factors));\n }\n return factors;\n }\n long root = (long)sqrt(number);\n long i = 3;\n while (i <= root) {\n if (number % i == 0) {\n auto factorsDivI = getFactors(number / i);\n factors.insert(factorsDivI.begin(), factorsDivI.end());\n if (factors.find(i) != factors.end()) {\n factors[i]++;\n } else {\n factors.insert(std::make_pair(i, 1));\n }\n if (number < MAX_ALL_FACTORS) {\n allFactors.insert(std::make_pair(number, factors));\n }\n return factors;\n }\n i += 2;\n }\n factors.insert(std::make_pair(number, 1));\n if (number < MAX_ALL_FACTORS) {\n allFactors.insert(std::make_pair(number, factors));\n }\n return factors;\n}\n\nstd::map<int, Polynomial> COMPUTED;\nPolynomial cyclotomicPolynomial(int n) {\n if (COMPUTED.find(n) != COMPUTED.end()) {\n return COMPUTED[n];\n }\n\n if (n == 1) {\n // Polynomial: x - 1\n Polynomial p({ 1, 1, -1, 0 });\n COMPUTED.insert(std::make_pair(1, p));\n return p;\n }\n\n auto factors = getFactors(n);\n if (factors.find(n) != factors.end()) {\n // n prime\n std::vector<Term> termList;\n for (int index = 0; index < n; index++) {\n termList.push_back({ 1, index });\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.size() == 2 && factors.find(2) != factors.end() && factors[2] == 1 && factors.find(n / 2) != factors.end() && factors[n / 2] == 1) {\n // n = 2p\n int prime = n / 2;\n std::vector<Term> termList;\n int coeff = -1;\n\n for (int index = 0; index < prime; index++) {\n coeff *= -1;\n termList.push_back({ coeff, index });\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.size() == 1 && factors.find(2) != factors.end()) {\n // n = 2^h\n int h = factors[2];\n std::vector<Term> termList;\n termList.push_back({ 1, (int)pow(2, h - 1) });\n termList.push_back({ 1, 0 });\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.size() == 1 && factors.find(n) != factors.end()) {\n // n = p^k\n int p = 0;\n int k = 0;\n for (auto iter = factors.begin(); iter != factors.end(); ++iter) {\n p = iter->first;\n k = iter->second;\n }\n std::vector<Term> termList;\n for (int index = 0; index < p; index++) {\n termList.push_back({ 1, index * (int)pow(p, k - 1) });\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.size() == 2 && factors.find(2) != factors.end()) {\n // n = 2^h * p^k\n int p = 0;\n for (auto iter = factors.begin(); iter != factors.end(); ++iter) {\n if (iter->first != 2) {\n p = iter->first;\n }\n }\n\n std::vector<Term> termList;\n int coeff = -1;\n int twoExp = (int)pow(2, factors[2] - 1);\n int k = factors[p];\n for (int index = 0; index < p; index++) {\n coeff *= -1;\n termList.push_back({ coeff, index * twoExp * (int)pow(p, k - 1) });\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.find(2) != factors.end() && ((n / 2) % 2 == 1) && (n / 2) > 1) {\n // CP(2m)[x] = CP(-m)[x], n odd integer > 1\n auto cycloDiv2 = cyclotomicPolynomial(n / 2);\n std::vector<Term> termList;\n for (auto term : cycloDiv2.polynomialTerms) {\n if (term.degree() % 2 == 0) {\n termList.push_back(term);\n } else {\n termList.push_back(-term);\n }\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n }\n\n // General Case\n\n if (algorithm == 0) {\n // slow - uses basic definition\n auto divisors = getDivisors(n);\n // Polynomial: (x^n - 1)\n Polynomial cyclo({ 1, n, -1, 0 });\n for (auto i : divisors) {\n auto p = cyclotomicPolynomial(i);\n cyclo = cyclo / p;\n }\n\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (algorithm == 1) {\n // Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor\n auto divisors = getDivisors(n);\n int maxDivisor = INT_MIN;\n for (auto div : divisors) {\n maxDivisor = std::max(maxDivisor, div);\n }\n std::vector<int> divisorExceptMax;\n for (auto div : divisors) {\n if (maxDivisor % div != 0) {\n divisorExceptMax.push_back(div);\n }\n }\n\n // Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor\n auto cyclo = Polynomial({ 1, n, -1, 0 }) / Polynomial({ 1, maxDivisor, -1, 0 });\n for (int i : divisorExceptMax) {\n auto p = cyclotomicPolynomial(i);\n cyclo = cyclo / p;\n }\n\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (algorithm == 2) {\n // Fastest\n // Let p ; q be primes such that p does not divide n, and q q divides n.\n // Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]\n int m = 1;\n auto cyclo = cyclotomicPolynomial(m);\n std::vector<int> primes;\n for (auto iter = factors.begin(); iter != factors.end(); ++iter) {\n primes.push_back(iter->first);\n }\n std::sort(primes.begin(), primes.end());\n for (auto prime : primes) {\n // CP(m)[x]\n auto cycloM = cyclo;\n // Compute CP(m)[x^p].\n std::vector<Term> termList;\n for (auto t : cycloM.polynomialTerms) {\n termList.push_back({ t.coefficient(), t.degree() * prime });\n }\n cyclo = Polynomial(termList) / cycloM;\n m = m * prime;\n }\n // Now, m is the largest square free divisor of n\n int s = n / m;\n // Compute CP(n)[x] = CP(m)[x^s]\n std::vector<Term> termList;\n for (auto t : cyclo.polynomialTerms) {\n termList.push_back({ t.coefficient(), t.degree() * s });\n }\n\n cyclo = Polynomial(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else {\n throw std::runtime_error(\"Invalid algorithm\");\n }\n}\n\nint main() {\n // initialization\n std::map<int, int> factors;\n factors.insert(std::make_pair(2, 1));\n allFactors.insert(std::make_pair(2, factors));\n\n // rest of main\n std::cout << \"Task 1: cyclotomic polynomials for n <= 30:\\n\";\n for (int i = 1; i <= 30; i++) {\n auto p = cyclotomicPolynomial(i);\n std::cout << \"CP[\" << i << \"] = \" << p << '\\n';\n }\n\n std::cout << \"Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\\n\";\n int n = 0;\n for (int i = 1; i <= 10; i++) {\n while (true) {\n n++;\n auto cyclo = cyclotomicPolynomial(n);\n if (cyclo.hasCoefficientAbs(i)) {\n std::cout << \"CP[\" << n << \"] has coefficient with magnitude = \" << i << '\\n';\n n--;\n break;\n }\n }\n }\n\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing IntMap = System.Collections.Generic.Dictionary<int, int>;\n\npublic static class CyclotomicPolynomial\n{\n public static void Main2() {\n Console.WriteLine(\"Task 1: Cyclotomic polynomials for n <= 30:\");\n for (int i = 1; i <= 30; i++) {\n var p = GetCyclotomicPolynomial(i);\n Console.WriteLine($\"CP[{i}] = {p.ToString()}\");\n }\n Console.WriteLine();\n\n Console.WriteLine(\"Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\");\n for (int i = 1, n = 0; i <= 10; i++) {\n while (true) {\n n++;\n var p = GetCyclotomicPolynomial(n);\n if (p.Any(t => Math.Abs(t.Coefficient) == i)) {\n Console.WriteLine($\"CP[{n}] has coefficient with magnitude = {i}\");\n n--;\n break;\n }\n }\n }\n }\n\n private const int MaxFactors = 100_000;\n private const int Algorithm = 2;\n private static readonly Term x = new Term(1, 1);\n private static readonly Dictionary<int, Polynomial> polyCache =\n new Dictionary<int, Polynomial> { [1] = x - 1 };\n private static readonly Dictionary<int, IntMap> factorCache =\n new Dictionary<int, IntMap> { [2] = new IntMap { [2] = 1 } };\n\n private static Polynomial GetCyclotomicPolynomial(in int n) {\n if (polyCache.TryGetValue(n, out var result)) return result;\n\n var factors = GetFactors(n);\n if (factors.ContainsKey(n)) { //n is prime\n result = new Polynomial(from exp in ..n select x[exp]);\n } else if (factors.Count == 2 && factors.Contains(2, 1) && factors.Contains(n/2, 1)) { //n = 2p\n result = new Polynomial(from i in ..(n/2) select (IsOdd(i) ? -x : x)[i]);\n } else if (factors.Count == 1 && factors.TryGetValue(2, out int h)) { //n = 2^h\n result = x[1<<(h-1)] + 1;\n } else if (factors.Count == 1 && !factors.ContainsKey(n)) { // n = p^k\n (int p, int k) = factors.First();\n result = new Polynomial(from i in ..p select x[i * (int)Math.Pow(p, k-1)]);\n } else if (factors.Count == 2 && factors.ContainsKey(2)) { //n = 2^h * p^k\n (int p, int k) = factors.First(entry => entry.Key != 2);\n int twoExp = 1 << (factors[2] - 1);\n result = new Polynomial(from i in ..p select (IsOdd(i) ? -x : x)[i * twoExp * (int)Math.Pow(p, k-1)]);\n } else if (factors.ContainsKey(2) && IsOdd(n/2) && n/2 > 1) { // CP(2m)[x] = CP[-m][x], n is odd > 1\n Polynomial cycloDiv2 = GetCyclotomicPolynomial(n/2);\n result = new Polynomial(from term in cycloDiv2 select IsOdd(term.Exponent) ? -term : term);\n #pragma warning disable CS0162\n } else if (Algorithm == 0) {\n var divisors = GetDivisors(n);\n result = x[n] - 1;\n foreach (int d in divisors) result /= GetCyclotomicPolynomial(d);\n } else if (Algorithm == 1) {\n var divisors = GetDivisors(n).ToList();\n int maxDivisor = divisors.Max();\n result = (x[n] - 1) / (x[maxDivisor] - 1);\n foreach (int d in divisors.Where(div => maxDivisor % div == 0)) {\n result /= GetCyclotomicPolynomial(d);\n }\n } else if (Algorithm == 2) {\n int m = 1;\n result = GetCyclotomicPolynomial(m);\n var primes = factors.Keys.ToList();\n primes.Sort();\n foreach (int prime in primes) {\n var cycloM = result;\n result = new Polynomial(from term in cycloM select term.Coefficient * x[term.Exponent * prime]);\n result /= cycloM;\n m *= prime;\n }\n int s = n / m;\n result = new Polynomial(from term in result select term.Coefficient * x[term.Exponent * s]);\n #pragma warning restore CS0162\n } else {\n throw new InvalidOperationException(\"Invalid algorithm\");\n }\n polyCache[n] = result;\n return result;\n }\n\n private static bool IsOdd(int i) => (i & 1) != 0;\n private static bool Contains(this IntMap map, int key, int value) => map.TryGetValue(key, out int v) && v == value;\n private static int GetOrZero(this IntMap map, int key) => map.TryGetValue(key, out int v) ? v : 0;\n private static IEnumerable<T> Select<T>(this Range r, Func<int, T> f) => Enumerable.Range(r.Start.Value, r.End.Value - r.Start.Value).Select(f);\n\n private static IntMap GetFactors(in int n) {\n if (factorCache.TryGetValue(n, out var factors)) return factors;\n\n factors = new IntMap();\n if (!IsOdd(n)) {\n foreach (var entry in GetFactors(n/2)) factors.Add(entry.Key, entry.Value);\n factors[2] = factors.GetOrZero(2) + 1;\n return Cache(n, factors);\n }\n for (int i = 3; i * i <= n; i+=2) {\n if (n % i == 0) {\n foreach (var entry in GetFactors(n/i)) factors.Add(entry.Key, entry.Value);\n factors[i] = factors.GetOrZero(i) + 1;\n return Cache(n, factors);\n }\n }\n factors[n] = 1;\n return Cache(n, factors);\n }\n\n private static IntMap Cache(int n, IntMap factors) {\n if (n < MaxFactors) factorCache[n] = factors;\n return factors;\n }\n\n private static IEnumerable<int> GetDivisors(int n) {\n for (int i = 1; i * i <= n; i++) {\n if (n % i == 0) {\n yield return i;\n int div = n / i;\n if (div != i && div != n) yield return div;\n }\n }\n }\n\n public sealed class Polynomial : IEnumerable<Term>\n {\n public Polynomial() { }\n public Polynomial(params Term[] terms) : this(terms.AsEnumerable()) { }\n\n public Polynomial(IEnumerable<Term> terms) {\n Terms.AddRange(terms);\n Simplify();\n }\n\n private List<Term>? terms;\n private List<Term> Terms => terms ??= new List<Term>();\n\n public int Count => terms?.Count ?? 0;\n public int Degree => Count == 0 ? -1 : Terms[0].Exponent;\n public int LeadingCoefficient => Count == 0 ? 0 : Terms[0].Coefficient;\n\n public IEnumerator<Term> GetEnumerator() => Terms.GetEnumerator();\n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n\n public override string ToString() => Count == 0 ? \"0\" : string.Join(\" + \", Terms).Replace(\"+ -\", \"- \");\n\n public static Polynomial operator *(Polynomial p, Term t) => new Polynomial(from s in p select s * t);\n public static Polynomial operator +(Polynomial p, Polynomial q) => new Polynomial(p.Terms.Concat(q.Terms));\n public static Polynomial operator -(Polynomial p, Polynomial q) => new Polynomial(p.Terms.Concat(q.Terms.Select(t => -t)));\n public static Polynomial operator *(Polynomial p, Polynomial q) => new Polynomial(from s in p from t in q select s * t);\n public static Polynomial operator /(Polynomial p, Polynomial q) => p.Divide(q).quotient;\n\n public (Polynomial quotient, Polynomial remainder) Divide(Polynomial divisor) {\n if (Degree < 0) return (new Polynomial(), this);\n Polynomial quotient = new Polynomial();\n Polynomial remainder = this;\n int lcv = divisor.LeadingCoefficient;\n int dv = divisor.Degree;\n while (remainder.Degree >= divisor.Degree) {\n int lcr = remainder.LeadingCoefficient;\n Term div = new Term(lcr / lcv, remainder.Degree - dv);\n quotient.Terms.Add(div);\n remainder += divisor * -div;\n }\n quotient.Simplify();\n remainder.Simplify();\n return (quotient, remainder);\n }\n\n private void Simplify() {\n if (Count < 2) return;\n Terms.Sort((a, b) => -a.CompareTo(b));\n for (int i = Terms.Count - 1; i > 0; i--) {\n Term s = Terms[i-1];\n Term t = Terms[i];\n if (t.Exponent == s.Exponent) {\n Terms[i-1] = new Term(s.Coefficient + t.Coefficient, s.Exponent);\n Terms.RemoveAt(i);\n }\n }\n Terms.RemoveAll(t => t.IsZero);\n }\n\n }\n\n public readonly struct Term : IEquatable<Term>, IComparable<Term>\n {\n public Term(int coefficient, int exponent = 0) => (Coefficient, Exponent) = (coefficient, exponent);\n\n public Term this[int exponent] => new Term(Coefficient, exponent); //Using x[exp] because x^exp has low precedence\n public int Coefficient { get; }\n public int Exponent { get; }\n public bool IsZero => Coefficient == 0;\n\n public static Polynomial operator +(Term left, Term right) => new Polynomial(left, right);\n public static Polynomial operator -(Term left, Term right) => new Polynomial(left, -right);\n public static implicit operator Term(int coefficient) => new Term(coefficient);\n public static Term operator -(Term t) => new Term(-t.Coefficient, t.Exponent);\n public static Term operator *(Term left, Term right) => new Term(left.Coefficient * right.Coefficient, left.Exponent + right.Exponent);\n\n public static bool operator ==(Term left, Term right) => left.Equals(right);\n public static bool operator !=(Term left, Term right) => !left.Equals(right);\n public static bool operator <(Term left, Term right) => left.CompareTo(right) < 0;\n public static bool operator >(Term left, Term right) => left.CompareTo(right) > 0;\n public static bool operator <=(Term left, Term right) => left.CompareTo(right) <= 0;\n public static bool operator >=(Term left, Term right) => left.CompareTo(right) >= 0;\n\n public bool Equals(Term other) => Exponent == other.Exponent && Coefficient == other.Coefficient;\n public override bool Equals(object? obj) => obj is Term t && Equals(t);\n public override int GetHashCode() => Coefficient.GetHashCode() * 31 + Exponent.GetHashCode();\n\n public int CompareTo(Term other) {\n int c = Exponent.CompareTo(other.Exponent);\n if (c != 0) return c;\n return Coefficient.CompareTo(other.Coefficient);\n }\n\n public override string ToString() => (Coefficient, Exponent) switch {\n (0, _) => \"0\",\n (_, 0) => $\"{Coefficient}\",\n (1, 1) => \"x\",\n (-1, 1) => \"-x\",\n (_, 1) => $\"{Coefficient}x\",\n (1, _) => $\"x^{Exponent}\",\n (-1, _) => $\"-x^{Exponent}\",\n _ => $\"{Coefficient}x^{Exponent}\"\n };\n }\n}\n", "language": "C-sharp" }, { "code": "import std.algorithm;\nimport std.exception;\nimport std.format;\nimport std.functional;\nimport std.math;\nimport std.range;\nimport std.stdio;\n\nimmutable MAX_ALL_FACTORS = 100_000;\nimmutable ALGORITHM = 2;\n\n//Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage.\n\nstruct Term {\n private long m_coefficient;\n private long m_exponent;\n\n public this(long c, long e) {\n m_coefficient = c;\n m_exponent = e;\n }\n\n public long coefficient() const {\n return m_coefficient;\n }\n\n public long exponent() const {\n return m_exponent;\n }\n\n public Term opUnary(string op)() const {\n static if (op == \"-\") {\n return Term(-m_coefficient, m_exponent);\n } else {\n assert(false, \"Not implemented\");\n }\n }\n\n public Term opBinary(string op)(Term term) const {\n static if (op == \"+\") {\n if (exponent() != term.exponent()) {\n assert(false, \"Error 102: Exponents not equals.\");\n }\n return Term(coefficient() + term.coefficient(), exponent());\n } else if (op == \"*\") {\n return Term(coefficient() * term.coefficient(), exponent() + term.exponent());\n } else {\n assert(false, \"Not implemented: \" ~ op);\n }\n }\n\n public void toString(scope void delegate(const(char)[]) sink) const {\n auto spec = singleSpec(\"%s\");\n if (m_coefficient == 0) {\n sink(\"0\");\n } else if (m_exponent == 0) {\n formatValue(sink, m_coefficient, spec);\n } else if (m_coefficient == 1) {\n if (m_exponent == 1) {\n sink(\"x\");\n } else {\n sink(\"x^\");\n formatValue(sink, m_exponent, spec);\n }\n } else if (m_coefficient == -1) {\n if (m_exponent == 1) {\n sink(\"-x\");\n } else {\n sink(\"-x^\");\n formatValue(sink, m_exponent, spec);\n }\n } else if (m_exponent == 1) {\n formatValue(sink, m_coefficient, spec);\n sink(\"x\");\n } else {\n formatValue(sink, m_coefficient, spec);\n sink(\"x^\");\n formatValue(sink, m_exponent, spec);\n }\n }\n}\n\nstruct Polynomial {\n private Term[] terms;\n\n public this(const Term[] ts...) {\n terms = ts.dup;\n terms.sort!\"b.exponent < a.exponent\";\n }\n\n bool hasCoefficientAbs(int coeff) const {\n foreach (term; terms) {\n if (abs(term.coefficient) == coeff) {\n return true;\n }\n }\n return false;\n }\n\n public long leadingCoefficient() const {\n return terms[0].coefficient();\n }\n\n public long degree() const {\n if (terms.empty) {\n return -1;\n }\n return terms[0].exponent();\n }\n\n public Polynomial opBinary(string op)(Term term) const {\n static if (op == \"+\") {\n Term[] newTerms;\n auto added = false;\n foreach (currentTerm; terms) {\n if (currentTerm.exponent() == term.exponent()) {\n added = true;\n if (currentTerm.coefficient() + term.coefficient() != 0) {\n newTerms ~= currentTerm + term;\n }\n } else {\n newTerms ~= currentTerm;\n }\n }\n if (!added) {\n newTerms ~= term;\n }\n return Polynomial(newTerms);\n } else if (op == \"*\") {\n Term[] newTerms;\n foreach (currentTerm; terms) {\n newTerms ~= currentTerm * term;\n }\n return Polynomial(newTerms);\n } else {\n assert(false, \"Not implemented: \" ~ op);\n }\n }\n\n public Polynomial opBinary(string op)(Polynomial rhs) const {\n static if (op == \"+\") {\n Term[] newTerms;\n auto thisCount = terms.length;\n auto polyCount = rhs.terms.length;\n while (thisCount > 0 || polyCount > 0) {\n if (thisCount == 0) {\n newTerms ~= rhs.terms[polyCount - 1];\n polyCount--;\n } else if (polyCount == 0) {\n newTerms ~= terms[thisCount - 1];\n thisCount--;\n } else {\n auto thisTerm = terms[thisCount - 1];\n auto polyTerm = rhs.terms[polyCount - 1];\n if (thisTerm.exponent() == polyTerm.exponent()) {\n auto t = thisTerm + polyTerm;\n if (t.coefficient() != 0) {\n newTerms ~= t;\n }\n thisCount--;\n polyCount--;\n } else if (thisTerm.exponent() < polyTerm.exponent()) {\n newTerms ~= thisTerm;\n thisCount--;\n } else {\n newTerms ~= polyTerm;\n polyCount--;\n }\n }\n }\n return Polynomial(newTerms);\n } else if (op == \"/\") {\n Polynomial q;\n auto r = Polynomial(terms);\n auto lcv = rhs.leadingCoefficient();\n auto dv = rhs.degree();\n while (r.degree() >= rhs.degree()) {\n auto lcr = r.leadingCoefficient();\n auto s = lcr / lcv;\n auto term = Term(s, r.degree() - dv);\n q = q + term;\n r = r + rhs * -term;\n }\n return q;\n } else {\n assert(false, \"Not implemented: \" ~ op);\n }\n }\n\n public int opApply(int delegate(Term) dg) const {\n foreach (term; terms) {\n auto rv = dg(term);\n if (rv != 0) {\n return rv;\n }\n }\n return 0;\n }\n\n public void toString(scope void delegate(const(char)[]) sink) const {\n auto spec = singleSpec(\"%s\");\n if (!terms.empty) {\n formatValue(sink, terms[0], spec);\n foreach (t; terms[1..$]) {\n if (t.coefficient > 0) {\n sink(\" + \");\n formatValue(sink, t, spec);\n } else {\n sink(\" - \");\n formatValue(sink, -t, spec);\n }\n }\n }\n }\n}\n\nvoid putAll(K, V)(ref V[K] a, V[K] b) {\n foreach (k, v; b) {\n a[k] = v;\n }\n}\n\nvoid merge(K, V, F)(ref V[K] a, K k, V v, F f) {\n if (k in a) {\n a[k] = f(a[k], v);\n } else {\n a[k] = v;\n }\n}\n\nint sum(int a, int b) {\n return a + b;\n}\n\nint[int] getFactorsImpl(int number) {\n int[int] factors;\n if (number % 2 == 0) {\n if (number > 2) {\n auto factorsDivTwo = memoize!getFactorsImpl(number / 2);\n factors.putAll(factorsDivTwo);\n }\n factors.merge(2, 1, &sum);\n return factors;\n }\n auto root = sqrt(cast(real) number);\n auto i = 3;\n while (i <= root) {\n if (number % i == 0) {\n factors.putAll(memoize!getFactorsImpl(number / i));\n factors.merge(i, 1, &sum);\n return factors;\n }\n i += 2;\n }\n factors[number] = 1;\n return factors;\n}\nalias getFactors = memoize!getFactorsImpl;\n\nint[] getDivisors(int number) {\n int[] divisors;\n auto root = cast(int)sqrt(cast(real) number);\n foreach (i; 1..root) {\n if (number % i == 0) {\n divisors ~= i;\n }\n auto div = number / i;\n if (div != i && div != number) {\n divisors ~= div;\n }\n }\n return divisors;\n}\n\nPolynomial cyclotomicPolynomialImpl(int n) {\n if (n == 1) {\n // Polynomial: x - 1\n return Polynomial(Term(1, 1), Term(-1, 0));\n }\n auto factors = getFactors(n);\n if (n in factors) {\n // n prime\n Term[] terms;\n foreach (i; 0..n) {\n terms ~= Term(1, i);\n }\n return Polynomial(terms);\n } else if (factors.length == 2 && 2 in factors && factors[2] == 1 && (n / 2) in factors && factors[n / 2] == 1) {\n // n = 2p\n auto prime = n / 2;\n Term[] terms;\n auto coeff = -1;\n foreach (i; 0..prime) {\n coeff *= -1;\n terms ~= Term(coeff, i);\n }\n return Polynomial(terms);\n } else if (factors.length == 1 && 2 in factors) {\n // n = 2^h\n auto h = factors[2];\n Term[] terms;\n terms ~= Term(1, 2 ^^ (h - 1));\n terms ~= Term(1, 0);\n return Polynomial(terms);\n } else if (factors.length == 1 && n !in factors) {\n // n = p^k\n auto p = 0;\n auto k = 0;\n foreach (prime, v; factors) {\n if (prime > p) {\n p = prime;\n k = v;\n }\n }\n Term[] terms;\n foreach (i; 0..p) {\n terms ~= Term(1, (i * p) ^^ (k - 1));\n }\n return Polynomial(terms);\n } else if (factors.length == 2 && 2 in factors) {\n // n = 2^h * p^k\n auto p = 0;\n auto k = 0;\n foreach (prime, v; factors) {\n if (prime != 2 && prime > p) {\n p = prime;\n k = v;\n }\n }\n Term[] terms;\n auto coeff = -1;\n auto twoExp = 2 ^^ (factors[2] - 1);\n foreach (i; 0..p) {\n coeff *= -1;\n auto exponent = i * twoExp * p ^^ (k - 1);\n terms ~= Term(coeff, exponent);\n }\n return Polynomial(terms);\n } else if (2 in factors && n / 2 % 2 == 1 && n / 2 > 1) {\n // CP(2m)[x] = CP(-m)[x], n odd integer > 1\n auto cycloDiv2 = memoize!cyclotomicPolynomialImpl(n / 2);\n Term[] terms;\n foreach (term; cycloDiv2) {\n if (term.exponent() % 2 == 0) {\n terms ~= term;\n } else {\n terms ~= -term;\n }\n }\n return Polynomial(terms);\n }\n\n if (ALGORITHM == 0) {\n // Slow - uses basic definition.\n auto divisors = getDivisors(n);\n // Polynomial: ( x^n - 1 )\n auto cyclo = Polynomial(Term(1, n), Term(-1, 0));\n foreach (i; divisors) {\n auto p = memoize!cyclotomicPolynomialImpl(i);\n cyclo = cyclo / p;\n }\n return cyclo;\n }\n if (ALGORITHM == 1) {\n // Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor\n auto divisors = getDivisors(n);\n auto maxDivisor = int.min;\n foreach (div; divisors) {\n maxDivisor = max(maxDivisor, div);\n }\n int[] divisorsExceptMax;\n foreach (div; divisors) {\n if (maxDivisor % div != 0) {\n divisorsExceptMax ~= div;\n }\n }\n\n // Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor\n auto cyclo = Polynomial(Term(1, n), Term(-1, 0)) / Polynomial(Term(1, maxDivisor), Term(-1, 0));\n foreach (i; divisorsExceptMax) {\n auto p = memoize!cyclotomicPolynomialImpl(i);\n cyclo = cyclo / p;\n }\n return cyclo;\n }\n if (ALGORITHM == 2) {\n // Fastest\n // Let p ; q be primes such that p does not divide n, and q q divides n.\n // Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]\n auto m = 1;\n auto cyclo = memoize!cyclotomicPolynomialImpl(m);\n auto primes = factors.keys;\n primes.sort;\n foreach (prime; primes) {\n // CP(m)[x]\n auto cycloM = cyclo;\n // Compute CP(m)[x^p].\n Term[] terms;\n foreach (term; cycloM) {\n terms ~= Term(term.coefficient(), term.exponent() * prime);\n }\n cyclo = Polynomial(terms) / cycloM;\n m *= prime;\n }\n // Now, m is the largest square free divisor of n\n auto s = n / m;\n // Compute CP(n)[x] = CP(m)[x^s]\n Term[] terms;\n foreach (term; cyclo) {\n terms ~= Term(term.coefficient(), term.exponent() * s);\n }\n return Polynomial(terms);\n }\n assert(false, \"Error 103: Invalid algorithm\");\n}\nalias cyclotomicPolynomial = memoize!cyclotomicPolynomialImpl;\n\nvoid main() {\n writeln(\"Task 1: cyclotomic polynomials for n <= 30:\");\n foreach (i; 1 .. 31) {\n auto p = cyclotomicPolynomial(i);\n writefln(\"CP[%d] = %s\", i, p);\n }\n writeln;\n\n writeln(\"Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\");\n auto n = 0;\n foreach (i; 1 .. 11) {\n while (true) {\n n++;\n auto cyclo = cyclotomicPolynomial(n);\n if (cyclo.hasCoefficientAbs(i)) {\n writefln(\"CP[%d] has coefficient with magnitude = %d\", n, i);\n n--;\n break;\n }\n }\n }\n}\n", "language": "D" }, { "code": "&(J=x); {adjoin x as the variable in the polynomials}\n\nFunc Cyclotomic(n) =\n if n=1 then x-1 fi; {first cyclotomic polynomial is x^n-1}\n r:=x^n-1; {caclulate cyclotomic by division}\n for d = 1 to n-1 do\n if Divides(d,n) then\n r:=r\\Cyclotomic(d)\n fi;\n od;\n r.; {return the polynomial}\n\nFunc Hascoef(n, k) =\n p:=Cyclotomic(n);\n for d = 0 to Deg(p) do\n if |(Coef(p,d))|=k then Return(1) fi\n od;\n 0.;\n\nfor d = 1 to 30 do\n !!(d,' : ',Cyclotomic(d))\nod;\n\nfor m = 1 to 10 do\n i:=1;\n while not Hascoef(i, m) do\n i:+\n od;\n !!(m,' : ',i);\nod;\n", "language": "Fermat" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math\"\n \"sort\"\n \"strings\"\n)\n\nconst (\n algo = 2\n maxAllFactors = 100000\n)\n\nfunc iabs(i int) int {\n if i < 0 {\n return -i\n }\n return i\n}\n\ntype term struct{ coef, exp int }\n\nfunc (t term) mul(t2 term) term {\n return term{t.coef * t2.coef, t.exp + t2.exp}\n}\n\nfunc (t term) add(t2 term) term {\n if t.exp != t2.exp {\n log.Fatal(\"exponents unequal in term.add method\")\n }\n return term{t.coef + t2.coef, t.exp}\n}\n\nfunc (t term) negate() term { return term{-t.coef, t.exp} }\n\nfunc (t term) String() string {\n switch {\n case t.coef == 0:\n return \"0\"\n case t.exp == 0:\n return fmt.Sprintf(\"%d\", t.coef)\n case t.coef == 1:\n if t.exp == 1 {\n return \"x\"\n } else {\n return fmt.Sprintf(\"x^%d\", t.exp)\n }\n case t.exp == 1:\n return fmt.Sprintf(\"%dx\", t.coef)\n }\n return fmt.Sprintf(\"%dx^%d\", t.coef, t.exp)\n}\n\ntype poly struct{ terms []term }\n\n// pass coef, exp in pairs as parameters\nfunc newPoly(values ...int) poly {\n le := len(values)\n if le == 0 {\n return poly{[]term{term{0, 0}}}\n }\n if le%2 != 0 {\n log.Fatalf(\"odd number of parameters (%d) passed to newPoly function\", le)\n }\n var terms []term\n for i := 0; i < le; i += 2 {\n terms = append(terms, term{values[i], values[i+1]})\n }\n p := poly{terms}.tidy()\n return p\n}\n\nfunc (p poly) hasCoefAbs(coef int) bool {\n for _, t := range p.terms {\n if iabs(t.coef) == coef {\n return true\n }\n }\n return false\n}\n\nfunc (p poly) add(p2 poly) poly {\n p3 := newPoly()\n le, le2 := len(p.terms), len(p2.terms)\n for le > 0 || le2 > 0 {\n if le == 0 {\n p3.terms = append(p3.terms, p2.terms[le2-1])\n le2--\n } else if le2 == 0 {\n p3.terms = append(p3.terms, p.terms[le-1])\n le--\n } else {\n t := p.terms[le-1]\n t2 := p2.terms[le2-1]\n if t.exp == t2.exp {\n t3 := t.add(t2)\n if t3.coef != 0 {\n p3.terms = append(p3.terms, t3)\n }\n le--\n le2--\n } else if t.exp < t2.exp {\n p3.terms = append(p3.terms, t)\n le--\n } else {\n p3.terms = append(p3.terms, t2)\n le2--\n }\n }\n }\n return p3.tidy()\n}\n\nfunc (p poly) addTerm(t term) poly {\n q := newPoly()\n added := false\n for i := 0; i < len(p.terms); i++ {\n ct := p.terms[i]\n if ct.exp == t.exp {\n added = true\n if ct.coef+t.coef != 0 {\n q.terms = append(q.terms, ct.add(t))\n }\n } else {\n q.terms = append(q.terms, ct)\n }\n }\n if !added {\n q.terms = append(q.terms, t)\n }\n return q.tidy()\n}\n\nfunc (p poly) mulTerm(t term) poly {\n q := newPoly()\n for i := 0; i < len(p.terms); i++ {\n ct := p.terms[i]\n q.terms = append(q.terms, ct.mul(t))\n }\n return q.tidy()\n}\n\nfunc (p poly) div(v poly) poly {\n q := newPoly()\n lcv := v.leadingCoef()\n dv := v.degree()\n for p.degree() >= v.degree() {\n lcp := p.leadingCoef()\n s := lcp / lcv\n t := term{s, p.degree() - dv}\n q = q.addTerm(t)\n p = p.add(v.mulTerm(t.negate()))\n }\n return q.tidy()\n}\n\nfunc (p poly) leadingCoef() int {\n return p.terms[0].coef\n}\n\nfunc (p poly) degree() int {\n return p.terms[0].exp\n}\n\nfunc (p poly) String() string {\n var sb strings.Builder\n first := true\n for _, t := range p.terms {\n if first {\n sb.WriteString(t.String())\n first = false\n } else {\n sb.WriteString(\" \")\n if t.coef > 0 {\n sb.WriteString(\"+ \")\n sb.WriteString(t.String())\n } else {\n sb.WriteString(\"- \")\n sb.WriteString(t.negate().String())\n }\n }\n }\n return sb.String()\n}\n\n// in place descending sort by term.exp\nfunc (p poly) sortTerms() {\n sort.Slice(p.terms, func(i, j int) bool {\n return p.terms[i].exp > p.terms[j].exp\n })\n}\n\n// sort terms and remove any unnecesary zero terms\nfunc (p poly) tidy() poly {\n p.sortTerms()\n if p.degree() == 0 {\n return p\n }\n for i := len(p.terms) - 1; i >= 0; i-- {\n if p.terms[i].coef == 0 {\n copy(p.terms[i:], p.terms[i+1:])\n p.terms[len(p.terms)-1] = term{0, 0}\n p.terms = p.terms[:len(p.terms)-1]\n }\n }\n if len(p.terms) == 0 {\n p.terms = append(p.terms, term{0, 0})\n }\n return p\n}\n\nfunc getDivisors(n int) []int {\n var divs []int\n sqrt := int(math.Sqrt(float64(n)))\n for i := 1; i <= sqrt; i++ {\n if n%i == 0 {\n divs = append(divs, i)\n d := n / i\n if d != i && d != n {\n divs = append(divs, d)\n }\n }\n }\n return divs\n}\n\nvar (\n computed = make(map[int]poly)\n allFactors = make(map[int]map[int]int)\n)\n\nfunc init() {\n f := map[int]int{2: 1}\n allFactors[2] = f\n}\n\nfunc getFactors(n int) map[int]int {\n if f, ok := allFactors[n]; ok {\n return f\n }\n factors := make(map[int]int)\n if n%2 == 0 {\n factorsDivTwo := getFactors(n / 2)\n for k, v := range factorsDivTwo {\n factors[k] = v\n }\n factors[2]++\n if n < maxAllFactors {\n allFactors[n] = factors\n }\n return factors\n }\n prime := true\n sqrt := int(math.Sqrt(float64(n)))\n for i := 3; i <= sqrt; i += 2 {\n if n%i == 0 {\n prime = false\n for k, v := range getFactors(n / i) {\n factors[k] = v\n }\n factors[i]++\n if n < maxAllFactors {\n allFactors[n] = factors\n }\n return factors\n }\n }\n if prime {\n factors[n] = 1\n if n < maxAllFactors {\n allFactors[n] = factors\n }\n }\n return factors\n}\n\nfunc cycloPoly(n int) poly {\n if p, ok := computed[n]; ok {\n return p\n }\n if n == 1 {\n // polynomial: x - 1\n p := newPoly(1, 1, -1, 0)\n computed[1] = p\n return p\n }\n factors := getFactors(n)\n cyclo := newPoly()\n if _, ok := factors[n]; ok {\n // n is prime\n for i := 0; i < n; i++ {\n cyclo.terms = append(cyclo.terms, term{1, i})\n }\n } else if len(factors) == 2 && factors[2] == 1 && factors[n/2] == 1 {\n // n == 2p\n prime := n / 2\n coef := -1\n for i := 0; i < prime; i++ {\n coef *= -1\n cyclo.terms = append(cyclo.terms, term{coef, i})\n }\n } else if len(factors) == 1 {\n if h, ok := factors[2]; ok {\n // n == 2^h\n cyclo.terms = append(cyclo.terms, term{1, 1 << (h - 1)}, term{1, 0})\n } else if _, ok := factors[n]; !ok {\n // n == p ^ k\n p := 0\n for prime := range factors {\n p = prime\n }\n k := factors[p]\n for i := 0; i < p; i++ {\n pk := int(math.Pow(float64(p), float64(k-1)))\n cyclo.terms = append(cyclo.terms, term{1, i * pk})\n }\n }\n } else if len(factors) == 2 && factors[2] != 0 {\n // n = 2^h * p^k\n p := 0\n for prime := range factors {\n if prime != 2 {\n p = prime\n }\n }\n coef := -1\n twoExp := 1 << (factors[2] - 1)\n k := factors[p]\n for i := 0; i < p; i++ {\n coef *= -1\n pk := int(math.Pow(float64(p), float64(k-1)))\n cyclo.terms = append(cyclo.terms, term{coef, i * twoExp * pk})\n }\n } else if factors[2] != 0 && ((n/2)%2 == 1) && (n/2) > 1 {\n // CP(2m)[x] == CP(-m)[x], n odd integer > 1\n cycloDiv2 := cycloPoly(n / 2)\n for _, t := range cycloDiv2.terms {\n t2 := t\n if t.exp%2 != 0 {\n t2 = t.negate()\n }\n cyclo.terms = append(cyclo.terms, t2)\n }\n } else if algo == 0 {\n // slow - uses basic definition\n divs := getDivisors(n)\n // polynomial: x^n - 1\n cyclo = newPoly(1, n, -1, 0)\n for _, i := range divs {\n p := cycloPoly(i)\n cyclo = cyclo.div(p)\n }\n } else if algo == 1 {\n // faster - remove max divisor (and all divisors of max divisor)\n // only one divide for all divisors of max divisor\n divs := getDivisors(n)\n maxDiv := math.MinInt32\n for _, d := range divs {\n if d > maxDiv {\n maxDiv = d\n }\n }\n var divsExceptMax []int\n for _, d := range divs {\n if maxDiv%d != 0 {\n divsExceptMax = append(divsExceptMax, d)\n }\n }\n // polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor\n cyclo = newPoly(1, n, -1, 0)\n cyclo = cyclo.div(newPoly(1, maxDiv, -1, 0))\n for _, i := range divsExceptMax {\n p := cycloPoly(i)\n cyclo = cyclo.div(p)\n }\n } else if algo == 2 {\n // fastest\n // let p, q be primes such that p does not divide n, and q divides n\n // then CP(np)[x] = CP(n)[x^p] / CP(n)[x]\n m := 1\n cyclo = cycloPoly(m)\n var primes []int\n for prime := range factors {\n primes = append(primes, prime)\n }\n sort.Ints(primes)\n for _, prime := range primes {\n // CP(m)[x]\n cycloM := cyclo\n // compute CP(m)[x^p]\n var terms []term\n for _, t := range cycloM.terms {\n terms = append(terms, term{t.coef, t.exp * prime})\n }\n cyclo = newPoly()\n cyclo.terms = append(cyclo.terms, terms...)\n cyclo = cyclo.tidy()\n cyclo = cyclo.div(cycloM)\n m *= prime\n }\n // now, m is the largest square free divisor of n\n s := n / m\n // Compute CP(n)[x] = CP(m)[x^s]\n var terms []term\n for _, t := range cyclo.terms {\n terms = append(terms, term{t.coef, t.exp * s})\n }\n cyclo = newPoly()\n cyclo.terms = append(cyclo.terms, terms...)\n } else {\n log.Fatal(\"invalid algorithm\")\n }\n cyclo = cyclo.tidy()\n computed[n] = cyclo\n return cyclo\n}\n\nfunc main() {\n fmt.Println(\"Task 1: cyclotomic polynomials for n <= 30:\")\n for i := 1; i <= 30; i++ {\n p := cycloPoly(i)\n fmt.Printf(\"CP[%2d] = %s\\n\", i, p)\n }\n\n fmt.Println(\"\\nTask 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\")\n n := 0\n for i := 1; i <= 10; i++ {\n for {\n n++\n cyclo := cycloPoly(n)\n if cyclo.hasCoefAbs(i) {\n fmt.Printf(\"CP[%d] has coefficient with magnitude = %d\\n\", n, i)\n n--\n break\n }\n }\n }\n}\n", "language": "Go" }, { "code": "import Data.List\nimport Data.Numbers.Primes (primeFactors)\n\nnegateVar p = zipWith (*) p $ reverse $ take (length p) $ cycle [1,-1]\n\nlift p 1 = p\nlift p n = intercalate (replicate (n-1) 0) (pure <$> p)\n\nshortDiv :: [Integer] -> [Integer] -> [Integer]\nshortDiv p1 (_:p2) = unfoldr go (length p1 - length p2, p1)\n where\n go (0, _) = Nothing\n go (i, h:t) = Just (h, (i-1, zipWith (+) (map (h *) ker) t))\n ker = negate <$> p2 ++ repeat 0\n\nprimePowerFactors = sortOn fst . map (\\x-> (head x, length x)) . group . primeFactors\n\n-- simple memoization\ncyclotomics :: [[Integer]]\ncyclotomics = cyclotomic <$> [0..]\n\ncyclotomic :: Int -> [Integer]\ncyclotomic 0 = [0]\ncyclotomic 1 = [1, -1]\ncyclotomic 2 = [1, 1]\ncyclotomic n = case primePowerFactors n of\n -- for n = 2^k\n [(2,h)] -> 1 : replicate (2 ^ (h-1) - 1) 0 ++ [1]\n -- for prime n\n [(p,1)] -> replicate n 1\n -- for power of prime n\n [(p,m)] -> lift (cyclotomics !! p) (p^(m-1))\n -- for n = 2*p and prime p\n [(2,1),(p,1)] -> take (n `div` 2) $ cycle [1,-1]\n -- for n = 2*m and odd m\n (2,1):_ -> negateVar $ cyclotomics !! (n `div` 2)\n -- general case\n (p, m):ps -> let cm = cyclotomics !! (n `div` (p ^ m))\n in lift (lift cm p `shortDiv` cm) (p^(m-1))\n", "language": "Haskell" }, { "code": "showPoly [] = \"0\"\nshowPoly p = foldl1 (\\r -> (r ++) . term) $\n dropWhile null $\n foldMap (\\(c, n) -> [show c ++ expt n]) $\n zip (reverse p) [0..]\n where\n expt = \\case 0 -> \"\"\n 1 -> \"*x\"\n n -> \"*x^\" ++ show n\n\n term = \\case [] -> \"\"\n '0':'*':t -> \"\"\n '-':'1':'*':t -> \" - \" ++ t\n '1':'*':t -> \" + \" ++ t\n '-':t -> \" - \" ++ t\n t -> \" + \" ++ t\n\nmain = do\n mapM_ (print . showPoly . cyclotomic) [1..30]\n putStrLn $ replicate 40 '-'\n\n mapM_ showLine $ take 4 task2\n where\n showLine (j, i, l) = putStrLn $ concat [ show j\n , \" appears in CM(\", show i\n , \") of length \", show l ]\n\n -- in order to make computations faster we leave only each 5-th polynomial\n task2 = (1,1,2) : tail (search 1 $ zip [0,5..] $ skipBy 5 cyclotomics)\n where\n search i ((k, p):ps) = if i `notElem` (abs <$> p)\n then search i ps\n else (i, k, length p) : search (i+1) ((k, p):ps)\n\nskipBy n [] = []\nskipBy n lst = let (x:_, b) = splitAt n lst in x:skipBy n b\n", "language": "Haskell" }, { "code": "cyclo=: {{<.-:1+(++) p. 1;^0j2p1* y%~1+I.1=y+.1+i.y}}\n", "language": "J" }, { "code": "{{ if.0>nc<'cache' do.cache=:y end.}} (,1);_1 1\n\ncyclotomic=: {{\n if.y<#cache do.\n if.#c=. y{::cache do.\n c return.\n end.\n end.\n c=. unpad cyclotomic000 y\n if. y>:#cache do. cache=:(100+y){.cache end.\n cache=: (<c) y} cache\n c\n}}\n\ncyclotomic000=: {{ assert.0<y\n 'q p'=. __ q: y\n if. 1=#q do.\n ,(y%*/q) {.\"0 q#1\n elseif.2={.q do.\n ,(y%*/q) {.\"0 (* 1 _1 $~ #) cyclotomic */}.q\n elseif. 1 e. 1 < p do.\n ,(y%*/q) {.\"0 cyclotomic */q\n else.\n (_1,(-y){.1) pDiv ;+//.@(*/)each/ cyclotomic each}:*/@>,{1,each q\n end.\n}}\n\n\nNB. discard high order zero coefficients in representation of polynomial\nunpad=: {.~ 1+0 i:~0=]\n\nNB. polynomial division, optimized for somewhat sparse polynomials\npDiv=: {{\n q=. $j=. 2 + x -&# y\n 'x y'=. x,:y\n while. j=. j-1 do.\n if. 0={.x do. j=. j-<:i=. 0 i.~ 0=x\n q=. q,i#0\n x=. i |.!.0 x\n else.\n q=. q, r=. x %&{. y\n x=. 1 |.!.0 x - y*r\n end.\n end.q\n}}\n", "language": "J" }, { "code": "taskfmt=: {{\n c=. \":each j=.cyclotomic y\n raw=. rplc&'_-' ;:inv}.,'+';\"0|.(*|j)#c('(',[,],')'\"_)each '*x^',&\":L:0 <\"0 i.#c\n txt=. raw rplc'(1*x^0)';'1';'(-1*x^0)';'(-1)';'*x^1)';'*x)'\n LF,~'CP[',y,&\":']= ',rplc&('(x)';'x';'+ (-1)';'- 1')txt rplc'(1*';'(';'(-1*';'(-'\n}}\n\ntaskorder=: {{\n r=.$k=.0\n while.y>#r do.k=.k+1\n if.(1+#r) e.|cyclotomic k do.\n r=. r,k\n k=. k-1\n end.\n end.r\n}}\n\n ;taskfmt each 1+i.30\nCP[1]= x - 1\nCP[2]= x + 1\nCP[3]= (x^2) + x + 1\nCP[4]= (x^2) + 1\nCP[5]= (x^4) + (x^3) + (x^2) + x + 1\nCP[6]= (x^2) + (-x) + 1\nCP[7]= (x^6) + (x^5) + (x^4) + (x^3) + (x^2) + x + 1\nCP[8]= (x^4) + 1\nCP[9]= (x^6) + (x^3) + 1\nCP[10]= (x^4) + (-x^3) + (x^2) + (-x) + 1\nCP[11]= (x^10) + (x^9) + (x^8) + (x^7) + (x^6) + (x^5) + (x^4) + (x^3) + (x^2) + x + 1\nCP[12]= (x^4) + (-x^2) + 1\nCP[13]= (x^12) + (x^11) + (x^10) + (x^9) + (x^8) + (x^7) + (x^6) + (x^5) + (x^4) + (x^3) + (x^2) + x + 1\nCP[14]= (x^6) + (-x^5) + (x^4) + (-x^3) + (x^2) + (-x) + 1\nCP[15]= (x^8) + (-x^7) + (x^5) + (-x^4) + (x^3) + (-x) + 1\nCP[16]= (x^8) + 1\nCP[17]= (x^16) + (x^15) + (x^14) + (x^13) + (x^12) + (x^11) + (x^10) + (x^9) + (x^8) + (x^7) + (x^6) + (x^5) + (x^4) + (x^3) + (x^2) + x + 1\nCP[18]= (x^6) + (-x^3) + 1\nCP[19]= (x^18) + (x^17) + (x^16) + (x^15) + (x^14) + (x^13) + (x^12) + (x^11) + (x^10) + (x^9) + (x^8) + (x^7) + (x^6) + (x^5) + (x^4) + (x^3) + (x^2) + x + 1\nCP[20]= (x^8) + (-x^6) + (x^4) + (-x^2) + 1\nCP[21]= (x^12) + (-x^11) + (x^9) + (-x^8) + (x^6) + (-x^4) + (x^3) + (-x) + 1\nCP[22]= (x^10) + (-x^9) + (x^8) + (-x^7) + (x^6) + (-x^5) + (x^4) + (-x^3) + (x^2) + (-x) + 1\nCP[23]= (x^22) + (x^21) + (x^20) + (x^19) + (x^18) + (x^17) + (x^16) + (x^15) + (x^14) + (x^13) + (x^12) + (x^11) + (x^10) + (x^9) + (x^8) + (x^7) + (x^6) + (x^5) + (x^4) + (x^3) + (x^2) + x + 1\nCP[24]= (x^8) + (-x^4) + 1\nCP[25]= (x^20) + (x^15) + (x^10) + (x^5) + 1\nCP[26]= (x^12) + (-x^11) + (x^10) + (-x^9) + (x^8) + (-x^7) + (x^6) + (-x^5) + (x^4) + (-x^3) + (x^2) + (-x) + 1\nCP[27]= (x^18) + (x^9) + 1\nCP[28]= (x^12) + (-x^10) + (x^8) + (-x^6) + (x^4) + (-x^2) + 1\nCP[29]= (x^28) + (x^27) + (x^26) + (x^25) + (x^24) + (x^23) + (x^22) + (x^21) + (x^20) + (x^19) + (x^18) + (x^17) + (x^16) + (x^15) + (x^14) + (x^13) + (x^12) + (x^11) + (x^10) + (x^9) + (x^8) + (x^7) + (x^6) + (x^5) + (x^4) + (x^3) + (x^2) + x + 1\nCP[30]= (x^8) + (x^7) + (-x^5) + (-x^4) + (-x^3) + x + 1\n\n (,.~#\\) taskorder 10\n 1 1\n 2 105\n 3 385\n 4 1365\n 5 1785\n 6 2805\n 7 3135\n 8 6545\n 9 6545\n10 10465\n", "language": "J" }, { "code": "NB. install'math/fftw'\nrequire'math/fftw'\n\ncyclotomic000=: {{ assert.0<y\n if. y = 1 do. _1 1 return. end.\n 'q p'=. __ q: y\n if. 1=#q do.\n ,(y%*/q) {.\"0 q#1\n elseif.2={.q do.\n ,(y%*/q) {.\"0 (* 1 _1 $~ #) cyclotomic */}.q\n elseif. 1 e. 1 < p do.\n ,(y%*/q) {.\"0 cyclotomic */q\n else.\n lgl=. {:$ ctlist=. cyclotomic \"0 }:*/@>,{1,each q NB. ctlist is 2-d table of polynomial divisors\n lgd=. # dividend=. _1,(-y){.1 NB. (x^n) - 1, and its size\n lg=. >.&.(2&^.) lgl >. lgd NB. required lengths of all polynomials for fft transforms\n NB. really, \"divisor\" is the fft of the divisor!\n divisor=. */ fftw\"1 lg{.\"1 ctlist NB. FFT article doesn't deal with lists of multiplicands\n unpad roundreal ifftw\"1 divisor %~ fftw lg{.dividend NB. similar to article's multiplication\n end.\n}}\n\nroundreal =: [: <. 0.5 + 9&o.\n", "language": "J" }, { "code": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TreeMap;\n\npublic class CyclotomicPolynomial {\n\n @SuppressWarnings(\"unused\")\n private static int divisions = 0;\n private static int algorithm = 2;\n\n public static void main(String[] args) throws Exception {\n System.out.println(\"Task 1: cyclotomic polynomials for n <= 30:\");\n for ( int i = 1 ; i <= 30 ; i++ ) {\n Polynomial p = cyclotomicPolynomial(i);\n System.out.printf(\"CP[%d] = %s%n\", i, p);\n }\n System.out.println(\"Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\");\n int n = 0;\n for ( int i = 1 ; i <= 10 ; i++ ) {\n while ( true ) {\n n++;\n Polynomial cyclo = cyclotomicPolynomial(n);\n if ( cyclo.hasCoefficientAbs(i) ) {\n System.out.printf(\"CP[%d] has coefficient with magnitude = %d%n\", n, i);\n n--;\n break;\n }\n }\n }\n }\n\n private static final Map<Integer, Polynomial> COMPUTED = new HashMap<>();\n\n private static Polynomial cyclotomicPolynomial(int n) {\n if ( COMPUTED.containsKey(n) ) {\n return COMPUTED.get(n);\n }\n\n //System.out.println(\"COMPUTE: n = \" + n);\n\n if ( n == 1 ) {\n // Polynomial: x - 1\n Polynomial p = new Polynomial(1, 1, -1, 0);\n COMPUTED.put(1, p);\n return p;\n }\n\n Map<Integer,Integer> factors = getFactors(n);\n\n if ( factors.containsKey(n) ) {\n // n prime\n List<Term> termList = new ArrayList<>();\n for ( int index = 0 ; index < n ; index++ ) {\n termList.add(new Term(1, index));\n }\n\n Polynomial cyclo = new Polynomial(termList);\n COMPUTED.put(n, cyclo);\n return cyclo;\n }\n else if ( factors.size() == 2 && factors.containsKey(2) && factors.get(2) == 1 && factors.containsKey(n/2) && factors.get(n/2) == 1 ) {\n // n = 2p\n int prime = n/2;\n List<Term> termList = new ArrayList<>();\n int coeff = -1;\n for ( int index = 0 ; index < prime ; index++ ) {\n coeff *= -1;\n termList.add(new Term(coeff, index));\n }\n\n Polynomial cyclo = new Polynomial(termList);\n COMPUTED.put(n, cyclo);\n return cyclo;\n }\n else if ( factors.size() == 1 && factors.containsKey(2) ) {\n // n = 2^h\n int h = factors.get(2);\n List<Term> termList = new ArrayList<>();\n termList.add(new Term(1, (int) Math.pow(2, h-1)));\n termList.add(new Term(1, 0));\n Polynomial cyclo = new Polynomial(termList);\n COMPUTED.put(n, cyclo);\n return cyclo;\n }\n else if ( factors.size() == 1 && ! factors.containsKey(n) ) {\n // n = p^k\n int p = 0;\n for ( int prime : factors.keySet() ) {\n p = prime;\n }\n int k = factors.get(p);\n List<Term> termList = new ArrayList<>();\n for ( int index = 0 ; index < p ; index++ ) {\n termList.add(new Term(1, index * (int) Math.pow(p, k-1)));\n }\n\n Polynomial cyclo = new Polynomial(termList);\n COMPUTED.put(n, cyclo);\n return cyclo;\n }\n else if ( factors.size() == 2 && factors.containsKey(2) ) {\n // n = 2^h * p^k\n int p = 0;\n for ( int prime : factors.keySet() ) {\n if ( prime != 2 ) {\n p = prime;\n }\n }\n List<Term> termList = new ArrayList<>();\n int coeff = -1;\n int twoExp = (int) Math.pow(2, factors.get(2)-1);\n int k = factors.get(p);\n for ( int index = 0 ; index < p ; index++ ) {\n coeff *= -1;\n termList.add(new Term(coeff, index * twoExp * (int) Math.pow(p, k-1)));\n }\n\n Polynomial cyclo = new Polynomial(termList);\n COMPUTED.put(n, cyclo);\n return cyclo;\n }\n else if ( factors.containsKey(2) && ((n/2) % 2 == 1) && (n/2) > 1 ) {\n // CP(2m)[x] = CP(-m)[x], n odd integer > 1\n Polynomial cycloDiv2 = cyclotomicPolynomial(n/2);\n List<Term> termList = new ArrayList<>();\n for ( Term term : cycloDiv2.polynomialTerms ) {\n termList.add(term.exponent % 2 == 0 ? term : term.negate());\n }\n Polynomial cyclo = new Polynomial(termList);\n COMPUTED.put(n, cyclo);\n return cyclo;\n }\n\n // General Case\n\n if ( algorithm == 0 ) {\n // Slow - uses basic definition.\n List<Integer> divisors = getDivisors(n);\n // Polynomial: ( x^n - 1 )\n Polynomial cyclo = new Polynomial(1, n, -1, 0);\n for ( int i : divisors ) {\n Polynomial p = cyclotomicPolynomial(i);\n cyclo = cyclo.divide(p);\n }\n\n COMPUTED.put(n, cyclo);\n return cyclo;\n }\n else if ( algorithm == 1 ) {\n // Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor\n List<Integer> divisors = getDivisors(n);\n int maxDivisor = Integer.MIN_VALUE;\n for ( int div : divisors ) {\n maxDivisor = Math.max(maxDivisor, div);\n }\n List<Integer> divisorsExceptMax = new ArrayList<Integer>();\n for ( int div : divisors ) {\n if ( maxDivisor % div != 0 ) {\n divisorsExceptMax.add(div);\n }\n }\n\n // Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor\n Polynomial cyclo = new Polynomial(1, n, -1, 0).divide(new Polynomial(1, maxDivisor, -1, 0));\n for ( int i : divisorsExceptMax ) {\n Polynomial p = cyclotomicPolynomial(i);\n cyclo = cyclo.divide(p);\n }\n\n COMPUTED.put(n, cyclo);\n\n return cyclo;\n }\n else if ( algorithm == 2 ) {\n // Fastest\n // Let p ; q be primes such that p does not divide n, and q q divides n.\n // Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]\n int m = 1;\n Polynomial cyclo = cyclotomicPolynomial(m);\n List<Integer> primes = new ArrayList<>(factors.keySet());\n Collections.sort(primes);\n for ( int prime : primes ) {\n // CP(m)[x]\n Polynomial cycloM = cyclo;\n // Compute CP(m)[x^p].\n List<Term> termList = new ArrayList<>();\n for ( Term t : cycloM.polynomialTerms ) {\n termList.add(new Term(t.coefficient, t.exponent * prime));\n }\n cyclo = new Polynomial(termList).divide(cycloM);\n m = m * prime;\n }\n // Now, m is the largest square free divisor of n\n int s = n / m;\n // Compute CP(n)[x] = CP(m)[x^s]\n List<Term> termList = new ArrayList<>();\n for ( Term t : cyclo.polynomialTerms ) {\n termList.add(new Term(t.coefficient, t.exponent * s));\n }\n cyclo = new Polynomial(termList);\n COMPUTED.put(n, cyclo);\n\n return cyclo;\n }\n else {\n throw new RuntimeException(\"ERROR 103: Invalid algorithm.\");\n }\n }\n\n private static final List<Integer> getDivisors(int number) {\n List<Integer> divisors = new ArrayList<Integer>();\n long sqrt = (long) Math.sqrt(number);\n for ( int i = 1 ; i <= sqrt ; i++ ) {\n if ( number % i == 0 ) {\n divisors.add(i);\n int div = number / i;\n if ( div != i && div != number ) {\n divisors.add(div);\n }\n }\n }\n return divisors;\n }\n\n private static final Map<Integer,Map<Integer,Integer>> allFactors = new TreeMap<Integer,Map<Integer,Integer>>();\n static {\n Map<Integer,Integer> factors = new TreeMap<Integer,Integer>();\n factors.put(2, 1);\n allFactors.put(2, factors);\n }\n\n public static Integer MAX_ALL_FACTORS = 100000;\n\n public static final Map<Integer,Integer> getFactors(Integer number) {\n if ( allFactors.containsKey(number) ) {\n return allFactors.get(number);\n }\n Map<Integer,Integer> factors = new TreeMap<Integer,Integer>();\n if ( number % 2 == 0 ) {\n Map<Integer,Integer> factorsdDivTwo = getFactors(number/2);\n factors.putAll(factorsdDivTwo);\n factors.merge(2, 1, (v1, v2) -> v1 + v2);\n if ( number < MAX_ALL_FACTORS )\n allFactors.put(number, factors);\n return factors;\n }\n boolean prime = true;\n long sqrt = (long) Math.sqrt(number);\n for ( int i = 3 ; i <= sqrt ; i += 2 ) {\n if ( number % i == 0 ) {\n prime = false;\n factors.putAll(getFactors(number/i));\n factors.merge(i, 1, (v1, v2) -> v1 + v2);\n if ( number < MAX_ALL_FACTORS )\n allFactors.put(number, factors);\n return factors;\n }\n }\n if ( prime ) {\n factors.put(number, 1);\n if ( number < MAX_ALL_FACTORS )\n allFactors.put(number, factors);\n }\n return factors;\n }\n\n private static final class Polynomial {\n\n private List<Term> polynomialTerms;\n\n // Format - coeff, exp, coeff, exp, (repeating in pairs) . . .\n public Polynomial(int ... values) {\n if ( values.length % 2 != 0 ) {\n throw new IllegalArgumentException(\"ERROR 102: Polynomial constructor. Length must be even. Length = \" + values.length);\n }\n polynomialTerms = new ArrayList<>();\n for ( int i = 0 ; i < values.length ; i += 2 ) {\n Term t = new Term(values[i], values[i+1]);\n polynomialTerms.add(t);\n }\n Collections.sort(polynomialTerms, new TermSorter());\n }\n\n public Polynomial() {\n // zero\n polynomialTerms = new ArrayList<>();\n polynomialTerms.add(new Term(0,0));\n }\n\n private boolean hasCoefficientAbs(int coeff) {\n for ( Term term : polynomialTerms ) {\n if ( Math.abs(term.coefficient) == coeff ) {\n return true;\n }\n }\n return false;\n }\n\n private Polynomial(List<Term> termList) {\n if ( termList.size() == 0 ) {\n // zero\n termList.add(new Term(0,0));\n }\n else {\n // Remove zero terms if needed\n for ( int i = 0 ; i < termList.size() ; i++ ) {\n if ( termList.get(i).coefficient == 0 ) {\n termList.remove(i);\n }\n }\n }\n if ( termList.size() == 0 ) {\n // zero\n termList.add(new Term(0,0));\n }\n polynomialTerms = termList;\n Collections.sort(polynomialTerms, new TermSorter());\n }\n\n public Polynomial divide(Polynomial v) {\n //long start = System.currentTimeMillis();\n divisions++;\n Polynomial q = new Polynomial();\n Polynomial r = this;\n long lcv = v.leadingCoefficient();\n long dv = v.degree();\n while ( r.degree() >= v.degree() ) {\n long lcr = r.leadingCoefficient();\n long s = lcr / lcv; // Integer division\n Term term = new Term(s, r.degree() - dv);\n q = q.add(term);\n r = r.add(v.multiply(term.negate()));\n }\n //long end = System.currentTimeMillis();\n //System.out.printf(\"Divide: Elapsed = %d, Degree 1 = %d, Degree 2 = %d%n\", (end-start), this.degree(), v.degree());\n return q;\n }\n\n public Polynomial add(Polynomial polynomial) {\n List<Term> termList = new ArrayList<>();\n int thisCount = polynomialTerms.size();\n int polyCount = polynomial.polynomialTerms.size();\n while ( thisCount > 0 || polyCount > 0 ) {\n Term thisTerm = thisCount == 0 ? null : polynomialTerms.get(thisCount-1);\n Term polyTerm = polyCount == 0 ? null : polynomial.polynomialTerms.get(polyCount-1);\n if ( thisTerm == null ) {\n termList.add(polyTerm.clone());\n polyCount--;\n }\n else if (polyTerm == null ) {\n termList.add(thisTerm.clone());\n thisCount--;\n }\n else if ( thisTerm.degree() == polyTerm.degree() ) {\n Term t = thisTerm.add(polyTerm);\n if ( t.coefficient != 0 ) {\n termList.add(t);\n }\n thisCount--;\n polyCount--;\n }\n else if ( thisTerm.degree() < polyTerm.degree() ) {\n termList.add(thisTerm.clone());\n thisCount--;\n }\n else {\n termList.add(polyTerm.clone());\n polyCount--;\n }\n }\n return new Polynomial(termList);\n }\n\n public Polynomial add(Term term) {\n List<Term> termList = new ArrayList<>();\n boolean added = false;\n for ( int index = 0 ; index < polynomialTerms.size() ; index++ ) {\n Term currentTerm = polynomialTerms.get(index);\n if ( currentTerm.exponent == term.exponent ) {\n added = true;\n if ( currentTerm.coefficient + term.coefficient != 0 ) {\n termList.add(currentTerm.add(term));\n }\n }\n else {\n termList.add(currentTerm.clone());\n }\n }\n if ( ! added ) {\n termList.add(term.clone());\n }\n return new Polynomial(termList);\n }\n\n public Polynomial multiply(Term term) {\n List<Term> termList = new ArrayList<>();\n for ( int index = 0 ; index < polynomialTerms.size() ; index++ ) {\n Term currentTerm = polynomialTerms.get(index);\n termList.add(currentTerm.clone().multiply(term));\n }\n return new Polynomial(termList);\n }\n\n public Polynomial clone() {\n List<Term> clone = new ArrayList<>();\n for ( Term t : polynomialTerms ) {\n clone.add(new Term(t.coefficient, t.exponent));\n }\n return new Polynomial(clone);\n }\n\n public long leadingCoefficient() {\n// long coefficient = 0;\n// long degree = Integer.MIN_VALUE;\n// for ( Term t : polynomialTerms ) {\n// if ( t.degree() > degree ) {\n// coefficient = t.coefficient;\n// degree = t.degree();\n// }\n// }\n return polynomialTerms.get(0).coefficient;\n }\n\n public long degree() {\n// long degree = Integer.MIN_VALUE;\n// for ( Term t : polynomialTerms ) {\n// if ( t.degree() > degree ) {\n// degree = t.degree();\n// }\n// }\n return polynomialTerms.get(0).exponent;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n boolean first = true;\n for ( Term term : polynomialTerms ) {\n if ( first ) {\n sb.append(term);\n first = false;\n }\n else {\n sb.append(\" \");\n if ( term.coefficient > 0 ) {\n sb.append(\"+ \");\n sb.append(term);\n }\n else {\n sb.append(\"- \");\n sb.append(term.negate());\n }\n }\n }\n return sb.toString();\n }\n }\n\n private static final class TermSorter implements Comparator<Term> {\n @Override\n public int compare(Term o1, Term o2) {\n return (int) (o2.exponent - o1.exponent);\n }\n }\n\n // Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage.\n private static final class Term {\n long coefficient;\n long exponent;\n\n public Term(long c, long e) {\n coefficient = c;\n exponent = e;\n }\n\n public Term clone() {\n return new Term(coefficient, exponent);\n }\n\n public Term multiply(Term term) {\n return new Term(coefficient * term.coefficient, exponent + term.exponent);\n }\n\n public Term add(Term term) {\n if ( exponent != term.exponent ) {\n throw new RuntimeException(\"ERROR 102: Exponents not equal.\");\n }\n return new Term(coefficient + term.coefficient, exponent);\n }\n\n public Term negate() {\n return new Term(-coefficient, exponent);\n }\n\n public long degree() {\n return exponent;\n }\n\n @Override\n public String toString() {\n if ( coefficient == 0 ) {\n return \"0\";\n }\n if ( exponent == 0 ) {\n return \"\" + coefficient;\n }\n if ( coefficient == 1 ) {\n if ( exponent == 1 ) {\n return \"x\";\n }\n else {\n return \"x^\" + exponent;\n }\n }\n if ( exponent == 1 ) {\n return coefficient + \"x\";\n }\n return coefficient + \"x^\" + exponent;\n }\n }\n\n}\n", "language": "Java" }, { "code": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class CyclotomicPolynomials {\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Task 1: Cyclotomic polynomials for n <= 30:\");\n for ( int cpIndex = 1; cpIndex <= 30; cpIndex++ ) {\n \tSystem.out.println(\"CP[\" + cpIndex + \"] = \" + toString(cyclotomicPolynomial(cpIndex)));\n }\n\n System.out.println();\n System.out.println(\"Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\");\n System.out.println(\"CP[1] has a coefficient with magnitude 1\");\n int cpIndex = 2;\n for ( int coefficient = 2; coefficient <= 10; coefficient++ ) {\n while ( BigInteger.valueOf(cpIndex).isProbablePrime(PRIME_CERTAINTY)\n \t\t|| ! hasHeight(cyclotomicPolynomial(cpIndex), coefficient) ) {\n \tcpIndex += 1; \t\n }\n System.out.println(\"CP[\" + cpIndex + \"] has a coefficient with magnitude \" + coefficient);\n }\n\t}\n\t\n\t// Return the Cyclotomic Polynomial of order 'cpIndex' as an array of coefficients,\n\t// where, for example, the polynomial 3x^2 - 1 is represented by the array [3, 0, -1].\n\tprivate static int[] cyclotomicPolynomial(int cpIndex) {\n\t\tint[] polynomial = new int[] { 1, -1 };\n\t\tif ( cpIndex == 1 ) {\n\t\t\treturn polynomial;\n\t\t}\n\t\t\n\t\tif ( BigInteger.valueOf(cpIndex).isProbablePrime(PRIME_CERTAINTY) ) {\n\t\t\tint[] result = new int[cpIndex];\n\t\t\tArrays.fill(result, 1);\n\t\t\treturn result;\n\t\t}\n\t\t\n\t\tList<Integer> primes = distinctPrimeFactors(cpIndex);\n\t\tint product = 1;\n\t\tfor ( int prime : primes ) {\n\t\t\tint[] numerator = substituteExponent(polynomial, prime);\n\t\t\tpolynomial = exactDivision(numerator, polynomial);\n\t\t\tproduct *= prime;\n\t\t}\n\t\t\n\t\tpolynomial = substituteExponent(polynomial, cpIndex / product);\t\t\n\t\treturn polynomial;\n\t}\n\t\n\t// Return the Cyclotomic Polynomial obtained from 'polynomial' by replacing x with x^'exponent'.\t\n\tprivate static int[] substituteExponent(int[] polynomial, int exponent) {\n\t\tint[] result = new int[exponent * ( polynomial.length - 1 ) + 1];\n\t\tfor ( int i = polynomial.length - 1; i >= 0; i-- ) {\n\t\t\tresult[i * exponent] = polynomial[i];\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\t// Return the Cyclotomic Polynomial equal to 'dividend' / 'divisor'. The division is always exact.\n\tprivate static int[] exactDivision(int[] dividend, int[] divisor) {\n\t\tint[] result = Arrays.copyOf(dividend, dividend.length);\n\t for ( int i = 0; i < dividend.length - divisor.length + 1; i++ ) {\n\t if ( result[i] != 0 ) {\n\t for ( int j = 1; j < divisor.length; j ++ ) {\n\t result[i + j] += -divisor[j] * result[i];\n\t }\n\t }\n\t }\n\t\n\t result = Arrays.copyOf(result, result.length - divisor.length + 1);\n\t return result;\n\t}\n\n\t// Return whether 'polynomial' has a coefficient of equal magnitude to 'coefficient'.\n\tprivate static boolean hasHeight(int[] polynomial, int coefficient) {\n for ( int i = 0; i <= ( polynomial.length + 1 ) / 2; i++ ) {\n if ( Math.abs(polynomial[i]) == coefficient ) {\n return true;\n }\n }\n\n return false;\n }\n\t\n\t// Return a string representation of 'polynomial'.\n\tprivate static String toString(int[] polynomial) {\n StringBuilder text = new StringBuilder();\n for ( int i = 0; i < polynomial.length; i++ ) {\n \tif ( polynomial[i] == 0 ) {\n \t\tcontinue;\n \t}\n \t\n \ttext.append(( polynomial[i] < 0 ) ?\t( ( i == 0 ) ? \"-\" : \" - \" ) : ( ( i == 0 ) ? \"\" : \" + \" ));\n \t\n \tfinal int exponent = polynomial.length - 1 - i;\n \tif ( exponent > 0 && Math.abs(polynomial[i]) > 1 ) {\n \t\ttext.append(Math.abs(polynomial[i]));\n \t} \t\n \t\n \ttext.append(( exponent > 1 ) ?\n \t\t( \"x^\" + String.valueOf(exponent) ) : ( ( exponent == 1 ) ? \"x\" : Math.abs(polynomial[i]) ));\n }\n\n return text.toString();\n }\n\t\n\t// Return a list of the distinct prime factors of 'number'.\n\tprivate static List<Integer> distinctPrimeFactors(int number) {\t\t\n \tList<Integer> primeFactors = new ArrayList<Integer>();\n \tfor ( int divisor = 2; divisor * divisor <= number; divisor++ ) {\n \t\tif ( number % divisor == 0 ) {\n \t\t\tprimeFactors.add(divisor);\n \t\t}\n \t\twhile ( number % divisor == 0 ) {\n \t\t\tnumber = number / divisor;\n \t\t}\n \t}\n \t\n \tif ( number > 1 ) {\n \t\tprimeFactors.add(number);\n \t}\n \t\n \treturn primeFactors;\n }\n\t\n\tprivate static final int PRIME_CERTAINTY = 15;\n\n}\n", "language": "Java" }, { "code": "### Generic utilities\n\ndef lpad($len): tostring | ($len - length) as $l | (\" \" * $l) + .;\n\n# Return the maximum item in the stream assuming it is not empty:\ndef max(s): reduce s as $s (null; if . == null then $s elif $s > . then $s else . end);\n\n# Truncated integer division (consistent with % operator).\n# `round` is used for the sake of jaq.\ndef quo($x; $y): ($x - ($x%$y)) / $y | round;\n\n### Primes\ndef is_prime:\n . as $n\n | if ($n < 2) then false\n elif ($n % 2 == 0) then $n == 2\n elif ($n % 3 == 0) then $n == 3\n elif ($n % 5 == 0) then $n == 5\n elif ($n % 7 == 0) then $n == 7\n elif ($n % 11 == 0) then $n == 11\n elif ($n % 13 == 0) then $n == 13\n elif ($n % 17 == 0) then $n == 17\n elif ($n % 19 == 0) then $n == 19\n else sqrt as $s\n | 23\n | until( . > $s or ($n % . == 0); . + 2)\n | . > $s\n end;\n\n# Emit an array of the distinct prime factors of 'n' in order using a wheel\n# with basis [2, 3, 5], e.g. 44 | distinctPrimeFactors #=> [2,11]\ndef distinctPrimeFactors:\n def augment($x): if .[-1] == $x then . else . + [$x] end;\n def out($i):\n if (.n % $i) == 0\n then .factors += [$i]\n | until (.n % $i != 0; .n = ((.n/$i)|floor) )\n else .\n end;\n\n if . < 2 then []\n else [4, 2, 4, 2, 4, 6, 2, 6] as $inc\n | { n: .,\n factors: [] }\n | out(2)\n | out(3)\n | out(5)\n | .k = 7\n | .i = 0\n | until(.k * .k > .n;\n if .n % .k == 0\n then .k as $k | .factors |= augment($k)\n | .n = ((.n/.k)|floor)\n else .k += $inc[.i]\n | .i = ((.i + 1) % 8)\n end)\n | if .n > 1 then .n as $n | .factors |= augment($n) else . end\n | .factors\n end;\n\n### Polynomials\ndef canonical:\n if length == 0 then .\n elif .[-1] == 0 then .[:-1]|canonical\n else .\n end;\n\n# For pretty-printing the input array as the polynomial it represents\n# e.g. [1,-1] => x-1\ndef pp:\n def digits: tostring | explode[] | [.] | implode | tonumber;\n def superscript:\n if . <= 1 then \"\"\n else [\"\\u2070\", \"\\u00b9\", \"\\u00b2\", \"\\u00b3\", \"\\u2074\", \"\\u2075\", \"\\u2076\", \"\\u2077\", \"\\u2078\", \"\\u2079\"] as $ss\n | reduce digits as $d (\"\"; . + $ss[$d] )\n end;\n\n if length == 1 then .[0] | tostring\n else reverse as $p\n | reduce range(length-1; -1; -1) as $i ([];\n if $p[$i] != 0\n\tthen (if $i > 0 then \"x\" else \"\" end) as $x\n | ( if $i > 0 and ($p[$i]|length) == 1\n\t then (if $p[$i] == 1 then \"\" else \"-\" end)\n\t else ($p[$i]|tostring)\n\t end ) as $c\n\t| . + [\"\\($c)\\($x)\\($i|superscript)\"]\n else . end )\n | join(\"+\")\n | gsub(\"\\\\+-\"; \"-\")\n end ;\n\ndef polynomialDivide($divisor):\n . as $in\n | ($divisor|canonical) as $divisor\n | { curr: canonical}\n | .base = ((.curr|length) - ($divisor|length))\n | until( .base < 0;\n (.curr[-1] / $divisor[-1]) as $res\n | .result += [$res]\n | .curr |= .[:-1]\n | reduce range (0;$divisor|length-1) as $i (.;\n .curr[.base + $i] += (- $res * $divisor[$i]) )\n | .base += -1 )\n | (.result | reverse) as $quot\n | (.curr | canonical) as $rem\n | [$quot, $rem];\n\n# Call `round` for the sake of jaq\ndef exactDivision($numerator; $denominator):\n ($numerator | polynomialDivide($denominator))\n | .[0]\n | map(round);\n\ndef init($n; $value): [range(0;$n)|$value];\n\n### Cyclotomic Polynomials\n\n# The Cyclotomic Polynomial obtained from $polynomial\n# by replacing x with x^$exponent\ndef substituteExponent($polynomial; $exponent):\n init( ($polynomial|length - 1) * $exponent + 1; 0)\n | reduce range(0; $polynomial|length) as $i (.; .[$i*$exponent] = $polynomial[$i]);\n\n# Return the Cyclotomic Polynomial of order 'cpIndex' as a JSON array of coefficients,\n# where, for example, the polynomial 3x^2 - 1 is represented by [3, 0, -1].\ndef cycloPoly($cpIndex):\n { polynomial: [1, -1] }\n | if $cpIndex == 1 then .polynomial\n elif ($cpIndex|is_prime) then [range(0; $cpIndex) | 1 ]\n else .product = 1\n | reduce ($cpIndex | distinctPrimeFactors[]) as $prime (.;\n substituteExponent(.polynomial; $prime) as $numerator\n | .polynomial = exactDivision($numerator; .polynomial)\n | .product *= $prime )\n | substituteExponent(.polynomial; quo($cpIndex; .product) )\n end;\n\n# The Cyclotomic Polynomial equal to $dividend / $divisor\ndef exactDivision($dividend; $divisor):\n reduce range(0; 1 + ($dividend|length) - ($divisor|length)) as $i ($dividend;\n if .[$i] != 0\n then reduce range(1; $divisor|length) as $j (.;\n .[$i+$j] = .[$i+$j] - $divisor[$j] * .[$i] )\n else .\n end)\n | .[0: 1 + length - ($divisor|length)];\n\n### The tasks\ndef task1($n):\n \"Task 1: Cyclotomic polynomials for n <= \\($n):\",\n ( range(1;$n+1) | \"CP[\\(lpad(2))]: \\(cycloPoly(.)|pp)\" );\n\n# For range(1;$n+1) as $c, report the first cpIndex which has a coefficient\n# equal in magnitude to $c, possibly reporting others as well.\ndef task2($n):\n def height: max(.[]|length); # i.e. abs\n # update .summary and .todo\n def register($cpIndex):\n cycloPoly($cpIndex) as $poly\n | if ($poly|height) < .todo[0] then .\n else # it is a palindrome so we can halve the checks\n reduce ($poly | .[0: quo(length + 1; 2)][]|length|select(.>1)) as $c (.;\n if .summary[$c|tostring] then .\n else .summary[$c|tostring] = $cpIndex\n | .todo -= [$c]\n | debug\n end)\n end;\n\n {cpIndex:1, summary: {\"1\": 1}, todo: [range(2; $n + 1)]}\n | until(.todo|length == 0;\n if .cpIndex|is_prime then . else register(.cpIndex) end\n | .cpIndex += 1)\n | .summary\n | (keys | sort_by(tonumber)[]) as $key\n | \"CP[\\(.[$key]|lpad(5))] has a coefficient with magnitude \\($key)\"\n ;\n\ntask1(30),\n\"\",\ntask2(10)\n", "language": "Jq" }, { "code": "using Primes, Polynomials\n\n# memoize cache for recursive calls\nconst cyclotomics = Dict([1 => Poly([big\"-1\", big\"1\"]), 2 => Poly([big\"1\", big\"1\"])])\n\n# get all integer divisors of an integer, except itself\nfunction divisors(n::Integer)\n f = [one(n)]\n for (p, e) in factor(n)\n f = reduce(vcat, [f * p^j for j in 1:e], init=f)\n end\n return resize!(f, length(f) - 1)\nend\n\n\"\"\"\n cyclotomic(n::Integer)\n\nCalculate the n -th cyclotomic polynomial.\nSee wikipedia article at bottom of section /wiki/Cyclotomic_polynomial#Fundamental_tools\nThe algorithm is reliable but slow for large n > 1000.\n\"\"\"\nfunction cyclotomic(n::Integer)\n if haskey(cyclotomics, n)\n c = cyclotomics[n]\n elseif isprime(n)\n c = Poly(ones(BigInt, n))\n cyclotomics[n] = c\n else # recursive formula seen in wikipedia article\n c = Poly([big\"-1\"; zeros(BigInt, n - 1); big\"1\"])\n for d in divisors(n)\n c ÷= cyclotomic(d)\n end\n cyclotomics[n] = c\n end\n return c\nend\n\nprintln(\"First 30 cyclotomic polynomials:\")\nfor i in 1:30\n println(rpad(\"$i: \", 5), cyclotomic(BigInt(i)))\nend\n\nconst dig = zeros(BigInt, 10)\nfor i in 1:1000000\n if all(x -> x != 0, dig)\n break\n end\n for coef in coeffs(cyclotomic(i))\n x = abs(coef)\n if 0 < x < 11 && dig[Int(x)] == 0\n dig[Int(x)] = coef < 0 ? -i : i\n end\n end\nend\nfor (i, n) in enumerate(dig)\n println(\"The cyclotomic polynomial Φ(\", abs(n), \") has a coefficient that is \", n < 0 ? -i : i)\nend\n", "language": "Julia" }, { "code": "import java.util.TreeMap\nimport kotlin.math.abs\nimport kotlin.math.pow\nimport kotlin.math.sqrt\n\nprivate const val algorithm = 2\n\nfun main() {\n println(\"Task 1: cyclotomic polynomials for n <= 30:\")\n for (i in 1..30) {\n val p = cyclotomicPolynomial(i)\n println(\"CP[$i] = $p\")\n }\n println()\n\n println(\"Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\")\n var n = 0\n for (i in 1..10) {\n while (true) {\n n++\n val cyclo = cyclotomicPolynomial(n)\n if (cyclo!!.hasCoefficientAbs(i)) {\n println(\"CP[$n] has coefficient with magnitude = $i\")\n n--\n break\n }\n }\n }\n}\n\nprivate val COMPUTED: MutableMap<Int, Polynomial> = HashMap()\nprivate fun cyclotomicPolynomial(n: Int): Polynomial? {\n if (COMPUTED.containsKey(n)) {\n return COMPUTED[n]\n }\n if (n == 1) {\n // Polynomial: x - 1\n val p = Polynomial(1, 1, -1, 0)\n COMPUTED[1] = p\n return p\n }\n val factors = getFactors(n)\n if (factors.containsKey(n)) {\n // n prime\n val termList: MutableList<Term> = ArrayList()\n for (index in 0 until n) {\n termList.add(Term(1, index.toLong()))\n }\n val cyclo = Polynomial(termList)\n COMPUTED[n] = cyclo\n return cyclo\n } else if (factors.size == 2 && factors.containsKey(2) && factors[2] == 1 && factors.containsKey(n / 2) && factors[n / 2] == 1) {\n // n = 2p\n val prime = n / 2\n val termList: MutableList<Term> = ArrayList()\n var coeff = -1\n for (index in 0 until prime) {\n coeff *= -1\n termList.add(Term(coeff.toLong(), index.toLong()))\n }\n val cyclo = Polynomial(termList)\n COMPUTED[n] = cyclo\n return cyclo\n } else if (factors.size == 1 && factors.containsKey(2)) {\n // n = 2^h\n val h = factors[2]!!\n val termList: MutableList<Term> = ArrayList()\n termList.add(Term(1, 2.0.pow((h - 1).toDouble()).toLong()))\n termList.add(Term(1, 0))\n val cyclo = Polynomial(termList)\n COMPUTED[n] = cyclo\n return cyclo\n } else if (factors.size == 1 && !factors.containsKey(n)) {\n // n = p^k\n var p = 0\n for (prime in factors.keys) {\n p = prime\n }\n val k = factors[p]!!\n val termList: MutableList<Term> = ArrayList()\n for (index in 0 until p) {\n termList.add(Term(1, (index * p.toDouble().pow(k - 1.toDouble()).toInt()).toLong()))\n }\n val cyclo = Polynomial(termList)\n COMPUTED[n] = cyclo\n return cyclo\n } else if (factors.size == 2 && factors.containsKey(2)) {\n // n = 2^h * p^k\n var p = 0\n for (prime in factors.keys) {\n if (prime != 2) {\n p = prime\n }\n }\n val termList: MutableList<Term> = ArrayList()\n var coeff = -1\n val twoExp = 2.0.pow((factors[2]!!) - 1.toDouble()).toInt()\n val k = factors[p]!!\n for (index in 0 until p) {\n coeff *= -1\n termList.add(Term(coeff.toLong(), (index * twoExp * p.toDouble().pow(k - 1.toDouble()).toInt()).toLong()))\n }\n val cyclo = Polynomial(termList)\n COMPUTED[n] = cyclo\n return cyclo\n } else if (factors.containsKey(2) && n / 2 % 2 == 1 && n / 2 > 1) {\n // CP(2m)[x] = CP(-m)[x], n odd integer > 1\n val cycloDiv2 = cyclotomicPolynomial(n / 2)\n val termList: MutableList<Term> = ArrayList()\n for (term in cycloDiv2!!.polynomialTerms) {\n termList.add(if (term.exponent % 2 == 0L) term else term.negate())\n }\n val cyclo = Polynomial(termList)\n COMPUTED[n] = cyclo\n return cyclo\n }\n\n // General Case\n return when (algorithm) {\n 0 -> {\n // Slow - uses basic definition.\n val divisors = getDivisors(n)\n // Polynomial: ( x^n - 1 )\n var cyclo = Polynomial(1, n, -1, 0)\n for (i in divisors) {\n val p = cyclotomicPolynomial(i)\n cyclo = cyclo.divide(p)\n }\n COMPUTED[n] = cyclo\n cyclo\n }\n 1 -> {\n // Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor\n val divisors = getDivisors(n)\n var maxDivisor = Int.MIN_VALUE\n for (div in divisors) {\n maxDivisor = maxDivisor.coerceAtLeast(div)\n }\n val divisorsExceptMax: MutableList<Int> = ArrayList()\n for (div in divisors) {\n if (maxDivisor % div != 0) {\n divisorsExceptMax.add(div)\n }\n }\n\n // Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor\n var cyclo = Polynomial(1, n, -1, 0).divide(Polynomial(1, maxDivisor, -1, 0))\n for (i in divisorsExceptMax) {\n val p = cyclotomicPolynomial(i)\n cyclo = cyclo.divide(p)\n }\n COMPUTED[n] = cyclo\n cyclo\n }\n 2 -> {\n // Fastest\n // Let p ; q be primes such that p does not divide n, and q q divides n.\n // Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]\n var m = 1\n var cyclo = cyclotomicPolynomial(m)\n val primes = factors.keys.toMutableList()\n primes.sort()\n for (prime in primes) {\n // CP(m)[x]\n val cycloM = cyclo\n // Compute CP(m)[x^p].\n val termList: MutableList<Term> = ArrayList()\n for (t in cycloM!!.polynomialTerms) {\n termList.add(Term(t.coefficient, t.exponent * prime))\n }\n cyclo = Polynomial(termList).divide(cycloM)\n m *= prime\n }\n // Now, m is the largest square free divisor of n\n val s = n / m\n // Compute CP(n)[x] = CP(m)[x^s]\n val termList: MutableList<Term> = ArrayList()\n for (t in cyclo!!.polynomialTerms) {\n termList.add(Term(t.coefficient, t.exponent * s))\n }\n cyclo = Polynomial(termList)\n COMPUTED[n] = cyclo\n cyclo\n }\n else -> {\n throw RuntimeException(\"ERROR 103: Invalid algorithm.\")\n }\n }\n}\n\nprivate fun getDivisors(number: Int): List<Int> {\n val divisors: MutableList<Int> = ArrayList()\n val sqrt = sqrt(number.toDouble()).toLong()\n for (i in 1..sqrt) {\n if (number % i == 0L) {\n divisors.add(i.toInt())\n val div = (number / i).toInt()\n if (div.toLong() != i && div != number) {\n divisors.add(div)\n }\n }\n }\n return divisors\n}\n\nprivate fun crutch(): MutableMap<Int, Map<Int, Int>> {\n val allFactors: MutableMap<Int, Map<Int, Int>> = TreeMap()\n\n val factors: MutableMap<Int, Int> = TreeMap()\n factors[2] = 1\n\n allFactors[2] = factors\n return allFactors\n}\n\nprivate val allFactors = crutch()\n\nvar MAX_ALL_FACTORS = 100000\n\nfun getFactors(number: Int): Map<Int, Int> {\n if (allFactors.containsKey(number)) {\n return allFactors[number]!!\n }\n val factors: MutableMap<Int, Int> = TreeMap()\n if (number % 2 == 0) {\n val factorsDivTwo = getFactors(number / 2)\n factors.putAll(factorsDivTwo)\n factors.merge(2, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }\n if (number < MAX_ALL_FACTORS) allFactors[number] = factors\n return factors\n }\n val sqrt = sqrt(number.toDouble()).toLong()\n var i = 3\n while (i <= sqrt) {\n if (number % i == 0) {\n factors.putAll(getFactors(number / i))\n factors.merge(i, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }\n if (number < MAX_ALL_FACTORS) {\n allFactors[number] = factors\n }\n return factors\n }\n i += 2\n }\n factors[number] = 1\n if (number < MAX_ALL_FACTORS) {\n allFactors[number] = factors\n }\n return factors\n}\n\nprivate class Polynomial {\n val polynomialTerms: MutableList<Term>\n\n // Format - coeff, exp, coeff, exp, (repeating in pairs) . . .\n constructor(vararg values: Int) {\n require(values.size % 2 == 0) { \"ERROR 102: Polynomial constructor. Length must be even. Length = \" + values.size }\n polynomialTerms = mutableListOf()\n var i = 0\n while (i < values.size) {\n val t = Term(values[i].toLong(), values[i + 1].toLong())\n polynomialTerms.add(t)\n i += 2\n }\n polynomialTerms.sortWith(TermSorter())\n }\n\n constructor() {\n // zero\n polynomialTerms = ArrayList()\n polynomialTerms.add(Term(0, 0))\n }\n\n fun hasCoefficientAbs(coeff: Int): Boolean {\n for (term in polynomialTerms) {\n if (abs(term.coefficient) == coeff.toLong()) {\n return true\n }\n }\n return false\n }\n\n constructor(termList: MutableList<Term>) {\n if (termList.isEmpty()) {\n // zero\n termList.add(Term(0, 0))\n } else {\n // Remove zero terms if needed\n termList.removeIf { t -> t.coefficient == 0L }\n }\n if (termList.size == 0) {\n // zero\n termList.add(Term(0, 0))\n }\n polynomialTerms = termList\n polynomialTerms.sortWith(TermSorter())\n }\n\n fun divide(v: Polynomial?): Polynomial {\n var q = Polynomial()\n var r = this\n val lcv = v!!.leadingCoefficient()\n val dv = v.degree()\n while (r.degree() >= v.degree()) {\n val lcr = r.leadingCoefficient()\n val s = lcr / lcv // Integer division\n val term = Term(s, r.degree() - dv)\n q = q.add(term)\n r = r.add(v.multiply(term.negate()))\n }\n return q\n }\n\n fun add(polynomial: Polynomial): Polynomial {\n val termList: MutableList<Term> = ArrayList()\n var thisCount = polynomialTerms.size\n var polyCount = polynomial.polynomialTerms.size\n while (thisCount > 0 || polyCount > 0) {\n val thisTerm = if (thisCount == 0) null else polynomialTerms[thisCount - 1]\n val polyTerm = if (polyCount == 0) null else polynomial.polynomialTerms[polyCount - 1]\n when {\n thisTerm == null -> {\n termList.add(polyTerm!!.clone())\n polyCount--\n }\n polyTerm == null -> {\n termList.add(thisTerm.clone())\n thisCount--\n }\n thisTerm.degree() == polyTerm.degree() -> {\n val t = thisTerm.add(polyTerm)\n if (t.coefficient != 0L) {\n termList.add(t)\n }\n thisCount--\n polyCount--\n }\n thisTerm.degree() < polyTerm.degree() -> {\n termList.add(thisTerm.clone())\n thisCount--\n }\n else -> {\n termList.add(polyTerm.clone())\n polyCount--\n }\n }\n }\n return Polynomial(termList)\n }\n\n fun add(term: Term): Polynomial {\n val termList: MutableList<Term> = ArrayList()\n var added = false\n for (currentTerm in polynomialTerms) {\n if (currentTerm.exponent == term.exponent) {\n added = true\n if (currentTerm.coefficient + term.coefficient != 0L) {\n termList.add(currentTerm.add(term))\n }\n } else {\n termList.add(currentTerm.clone())\n }\n }\n if (!added) {\n termList.add(term.clone())\n }\n return Polynomial(termList)\n }\n\n fun multiply(term: Term): Polynomial {\n val termList: MutableList<Term> = ArrayList()\n for (currentTerm in polynomialTerms) {\n termList.add(currentTerm.clone().multiply(term))\n }\n return Polynomial(termList)\n }\n\n fun leadingCoefficient(): Long {\n return polynomialTerms[0].coefficient\n }\n\n fun degree(): Long {\n return polynomialTerms[0].exponent\n }\n\n override fun toString(): String {\n val sb = StringBuilder()\n var first = true\n for (term in polynomialTerms) {\n if (first) {\n sb.append(term)\n first = false\n } else {\n sb.append(\" \")\n if (term.coefficient > 0) {\n sb.append(\"+ \")\n sb.append(term)\n } else {\n sb.append(\"- \")\n sb.append(term.negate())\n }\n }\n }\n return sb.toString()\n }\n}\n\nprivate class TermSorter : Comparator<Term> {\n override fun compare(o1: Term, o2: Term): Int {\n return (o2.exponent - o1.exponent).toInt()\n }\n}\n\n// Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage.\nprivate class Term(var coefficient: Long, var exponent: Long) {\n fun clone(): Term {\n return Term(coefficient, exponent)\n }\n\n fun multiply(term: Term): Term {\n return Term(coefficient * term.coefficient, exponent + term.exponent)\n }\n\n fun add(term: Term): Term {\n if (exponent != term.exponent) {\n throw RuntimeException(\"ERROR 102: Exponents not equal.\")\n }\n return Term(coefficient + term.coefficient, exponent)\n }\n\n fun negate(): Term {\n return Term(-coefficient, exponent)\n }\n\n fun degree(): Long {\n return exponent\n }\n\n override fun toString(): String {\n if (coefficient == 0L) {\n return \"0\"\n }\n if (exponent == 0L) {\n return \"\" + coefficient\n }\n if (coefficient == 1L) {\n return if (exponent == 1L) {\n \"x\"\n } else {\n \"x^$exponent\"\n }\n }\n return if (exponent == 1L) {\n coefficient.toString() + \"x\"\n } else coefficient.toString() + \"x^\" + exponent\n }\n}\n", "language": "Kotlin" }, { "code": "with(NumberTheory):\nfor n to 30 do lprint(Phi(n,x)) od:\n\nx-1\nx+1\nx^2+x+1\nx^2+1\nx^4+x^3+x^2+x+1\nx^2-x+1\nx^6+x^5+x^4+x^3+x^2+x+1\nx^4+1\nx^6+x^3+1\nx^4-x^3+x^2-x+1\nx^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1\nx^4-x^2+1\nx^12+x^11+x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1\nx^6-x^5+x^4-x^3+x^2-x+1\nx^8-x^7+x^5-x^4+x^3-x+1\nx^8+1\nx^16+x^15+x^14+x^13+x^12+x^11+x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1\nx^6-x^3+1\nx^18+x^17+x^16+x^15+x^14+x^13+x^12+x^11+x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1\nx^8-x^6+x^4-x^2+1\nx^12-x^11+x^9-x^8+x^6-x^4+x^3-x+1\nx^10-x^9+x^8-x^7+x^6-x^5+x^4-x^3+x^2-x+1\nx^22+x^21+x^20+x^19+x^18+x^17+x^16+x^15+x^14+x^13+x^12+x^11+x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1\nx^8-x^4+1\nx^20+x^15+x^10+x^5+1\nx^12-x^11+x^10-x^9+x^8-x^7+x^6-x^5+x^4-x^3+x^2-x+1\nx^18+x^9+1\nx^12-x^10+x^8-x^6+x^4-x^2+1\nx^28+x^27+x^26+x^25+x^24+x^23+x^22+x^21+x^20+x^19+x^18+x^17+x^16+x^15+x^14+x^13+x^12+x^11+x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1\nx^8+x^7-x^5-x^4-x^3+x+1\n\nPhiSet:=[seq(map(abs,{coeffs(Phi(k,x),x)}),k=1..15000)]:\n[seq(ListTools:-SelectFirst(s->member(n,s),PhiSet,output=indices),n=1..20)];\n#[1, 105, 385, 1365, 1785, 2805, 3135, 6545, 6545, 10465, 10465,\n# 10465, 10465, 10465, 11305, 11305, 11305, 11305, 11305, 11305]\n", "language": "Maple" }, { "code": "Cyclotomic[#, x] & /@ Range[30] // Column\ni = 1;\nn = 10;\nPrintTemporary[Dynamic[{magnitudes, i}]];\nmagnitudes = ConstantArray[True, n];\nWhile[Or @@ magnitudes,\n coeff = Abs[CoefficientList[Cyclotomic[i, x], x]];\n coeff = Select[coeff, Between[{1, n}]];\n coeff = DeleteDuplicates[coeff];\n If[Or @@ magnitudes[[coeff]],\n Do[\n If[magnitudes[[c]] == True,\n Print[\"CyclotomicPolynomial(\", i,\n \") has coefficient with magnitude \", c]\n ]\n ,\n {c, coeff}\n ];\n magnitudes[[coeff]] = False;\n ];\n i++;\n ]\n", "language": "Mathematica" }, { "code": "import algorithm, math, sequtils, strformat, tables\n\ntype\n\n Term = tuple[coeff: int; exp: Natural]\n Polynomial = seq[Term]\n\n # Table used to represent the list of factors of a number.\n # If, for a number \"n\", \"k\" is present in the table \"f\" of its factors,\n # \"f[k]\" contains the exponent of \"k\" in the prime factor decomposition.\n Factors = Table[int, int]\n\n\n####################################################################################################\n# Miscellaneous.\n\n## Parity tests.\ntemplate isOdd(n: int): bool = (n and 1) != 0\ntemplate isEven(n: int): bool = (n and 1) == 0\n\n#---------------------------------------------------------------------------------------------------\n\nproc sort(poly: var Polynomial) {.inline.} =\n ## Sort procedure for the terms of a polynomial (high degree first).\n algorithm.sort(poly, proc(x, y: Term): int = cmp(x.exp, y.exp), Descending)\n\n\n####################################################################################################\n# Superscripts.\n\nconst Superscripts: array['0'..'9', string] = [\"⁰\", \"¹\", \"²\", \"³\", \"⁴\", \"⁵\", \"⁶\", \"⁷\", \"⁸\", \"⁹\"]\n\nfunc superscript(n: Natural): string =\n ## Return the Unicode string to use to represent an exponent.\n if n == 1:\n return \"\"\n for d in $n:\n result.add(Superscripts[d])\n\n\n####################################################################################################\n# Term operations.\n\nfunc term(coeff, exp: int): Term =\n ## Create a term.\n if exp < 0:\n raise newException(ValueError, \"term exponent cannot be negative\")\n (coeff, Natural exp)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `*`(a, b: Term): Term =\n ## Multiply two terms.\n (a.coeff * b.coeff, Natural a.exp + b.exp)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `+`(a, b: Term): Term =\n ## Add two terms.\n\n if a.exp != b.exp:\n raise newException(ValueError, \"addition of terms with unequal exponents\")\n (a.coeff + b.coeff, a.exp)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `-`(a: Term): Term =\n ## Return the opposite of a term.\n (-a.coeff, a.exp)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `$`(a: Term): string =\n ## Return the string representation of a term.\n if a.coeff == 0: \"0\"\n elif a.exp == 0: $a.coeff\n elif a.coeff == 1: 'x' & superscript(a.exp)\n elif a.coeff == -1: \"-x\" & superscript(a.exp)\n else: $a.coeff & 'x' & superscript(a.exp)\n\n\n####################################################################################################\n# Polynomial.\n\nfunc polynomial(terms: varargs[Term]): Polynomial =\n ## Create a polynomial described by its terms.\n for t in terms:\n if t.coeff != 0:\n result.add(t)\n if result.len == 0:\n return @[term(0, 0)]\n sort(result)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc hasCoeffAbs(poly: Polynomial; coeff: int): bool =\n ## Return true if the polynomial contains a given coefficient.\n for t in poly:\n if abs(t.coeff) == coeff:\n return true\n\n#---------------------------------------------------------------------------------------------------\n\nfunc leadingCoeff(poly: Polynomial): int {.inline.} =\n ## Return the coefficient of the term with the highest degree.\n poly[0].coeff\n\n#---------------------------------------------------------------------------------------------------\n\nfunc degree(poly: Polynomial): int {.inline.} =\n ## Return the degree of the polynomial.\n if poly.len == 0: -1\n else: poly[0].exp\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `+`(poly: Polynomial; someTerm: Term): Polynomial =\n ## Add a term to a polynomial.\n\n var added = false\n for currTerm in poly:\n if currterm.exp == someTerm.exp:\n added = true\n if currTerm.coeff + someTerm.coeff != 0:\n result.add(currTerm + someTerm)\n else:\n result.add(currTerm)\n\n if not added:\n result.add(someTerm)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `+`(a, b: Polynomial): Polynomial =\n ## Add two polynomials.\n\n var aIndex = a.high\n var bIndex = b.high\n\n while aIndex >= 0 or bIndex >= 0:\n if aIndex < 0:\n result &= b[bIndex]\n dec bIndex\n elif bIndex < 0:\n result &= a[aIndex]\n dec aIndex\n else:\n let t1 = a[aIndex]\n let t2 = b[bIndex]\n if t1.exp == t2.exp:\n let t3 = t1 + t2\n if t3.coeff != 0:\n result.add(t3)\n dec aIndex\n dec bIndex\n elif t1.exp < t2.exp:\n result.add(t1)\n dec aIndex\n else:\n result.add(t2)\n dec bIndex\n\n sort(result)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `*`(poly: Polynomial; someTerm: Term): Polynomial =\n ## Multiply a polynomial by a term.\n for currTerm in poly:\n result.add(currTerm * someTerm)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `/`(a, b: Polynomial): Polynomial =\n ## Divide a polynomial by another polynomial.\n\n var a = a\n let lcb = b.leadingCoeff\n let db = b.degree\n while a.degree >= b.degree:\n let lca = a.leadingCoeff\n let s = lca div lcb\n let t = term(s, a.degree - db)\n result = result + t\n a = a + b * -t\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `$`(poly: Polynomial): string =\n ## Return the string representation of a polynomial.\n\n for t in poly:\n if result.len == 0:\n result.add($t)\n else:\n if t.coeff > 0:\n result.add('+')\n result.add($t)\n else:\n result.add('-')\n result.add($(-t))\n\n\n####################################################################################################\n# Cyclotomic polynomial.\n\nvar\n\n # Cache of list of factors.\n factorCache: Table[int, Factors] = {2: {2: 1}.toTable}.toTable\n\n # Cache of cyclotomic polynomials. Initialized with 1 -> x - 1.\n polyCache: Table[int, Polynomial] = {1: polynomial(term(1, 1), term(-1, 0))}.toTable\n\n#---------------------------------------------------------------------------------------------------\n\nproc getFactors(n: int): Factors =\n ## Return the list of factors of a number.\n\n if n in factorCache:\n return factorCache[n]\n\n if n.isEven:\n result = getFactors(n div 2)\n result[2] = result.getOrDefault(2) + 1\n factorCache[n] = result\n return\n\n var i = 3\n while i * i <= n:\n if n mod i == 0:\n result = getFactors( n div i)\n result[i] = result.getOrDefault(i) + 1\n factorCache[n] = result\n return\n inc i, 2\n\n result[n] = 1\n factorCache[n] = result\n\n#---------------------------------------------------------------------------------------------------\n\nproc cycloPoly(n: int): Polynomial =\n ## Find the nth cyclotomic polynomial.\n\n if n in polyCache:\n return polyCache[n]\n\n let factors = getFactors(n)\n\n if n in factors:\n # n is prime.\n for i in countdown(n - 1, 0): # Add the terms by decreasing degrees.\n result.add(term(1, i))\n\n elif factors.len == 2 and factors.getOrDefault(2) == 1 and factors.getOrDefault(n div 2) == 1:\n # n = 2 x prime.\n let prime = n div 2\n var coeff = -1\n for i in countdown(prime - 1, 0): # Add the terms by decreasing degrees.\n coeff *= -1\n result.add(term(coeff, i))\n\n elif factors.len == 1 and 2 in factors:\n # n = 2 ^ h.\n let h = factors[2]\n result.add([term(1, 1 shl (h - 1)), term(1, 0)])\n\n elif factors.len == 1 and n notin factors:\n # n = prime ^ k.\n var p, k = 0\n for prime, v in factors.pairs:\n if prime > p:\n p = prime\n k = v\n for i in countdown(p - 1, 0): # Add the terms by decreasing degrees.\n result.add(term(1, i * p^(k-1)))\n\n elif factors.len == 2 and 2 in factors:\n # n = 2 ^ h x prime ^ k.\n var p, k = 0\n for prime, v in factors.pairs:\n if prime != 2 and prime > p:\n p = prime\n k = v\n var coeff = -1\n let twoExp = 1 shl (factors[2] - 1)\n for i in countdown(p - 1, 0): # Add the terms by decreasing degrees.\n coeff *= -1\n result.add(term(coeff, i * twoExp * p^(k-1)))\n\n elif 2 in factors and isOdd(n div 2) and n div 2 > 1:\n # CP(2m)[x] = CP(-m)[x], n odd integer > 1.\n let cycloDiv2 = cycloPoly(n div 2)\n for t in cycloDiv2:\n result.add(if t.exp.isEven: t else: -t)\n\n else:\n # Let p, q be primes such that p does not divide n, and q divides n.\n # Then CP(np)[x] = CP(n)[x^p] / CP(n)[x].\n var m = 1\n var cyclo = cycloPoly(m)\n let primes = sorted(toSeq(factors.keys))\n for prime in primes:\n # Compute CP(m)[x^p].\n var terms: Polynomial\n for t in cyclo:\n terms.add(term(t.coeff, t.exp * prime))\n cyclo = terms / cyclo\n m *= prime\n # Now, m is the largest square free divisor of n.\n let s = n div m\n # Compute CP(n)[x] = CP(m)[x^s].\n for t in cyclo:\n result.add(term(t.coeff, t.exp * s))\n\n polyCache[n] = result\n\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\necho \"Cyclotomic polynomials for n ⩽ 30:\"\nfor i in 1..30:\n echo &\"Φ{'(' & $i & ')':4} = {cycloPoly(i)}\"\n\necho \"\"\necho \"Smallest cyclotomic polynomial with n or -n as a coefficient:\"\nvar n = 0\nfor i in 1..10:\n while true:\n inc n\n if cycloPoly(n).hasCoeffAbs(i):\n echo &\"Φ{'(' & $n & ')':7} has coefficient with magnitude = {i}\"\n dec n\n break\n", "language": "Nim" }, { "code": "for(n=1,30,print(n,\" : \",polcyclo(n)))\n\ncontains_coeff(n, d) = p=polcyclo(n);for(k=0,poldegree(p),if(abs(polcoef(p,k))==d,return(1)));return(0)\n\nfor(d=1,10,i=1; while(contains_coeff(i,d)==0,i=i+1);print(d,\" : \",i))\n", "language": "PARI-GP" }, { "code": "use feature 'say';\nuse List::Util qw(first);\nuse Math::Polynomial::Cyclotomic qw(cyclo_poly_iterate);\n\nsay 'First 30 cyclotomic polynomials:';\nmy $it = cyclo_poly_iterate(1);\nsay \"$_: \" . $it->() for 1 .. 30;\n\nsay \"\\nSmallest cyclotomic polynomial with n or -n as a coefficient:\";\n$it = cyclo_poly_iterate(1);\n\nfor (my ($n, $k) = (1, 1) ; $n <= 10 ; ++$k) {\n my $poly = $it->();\n while (my $c = first { abs($_) == $n } $poly->coeff) {\n say \"CP $k has coefficient with magnitude = $n\";\n $n++;\n }\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">-- demo\\rosetta\\Cyclotomic_Polynomial.exw</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">degree</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">i</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">poly_div</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">)<</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">&=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">dn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">degree</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">dd</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">degree</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">dd</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">throw</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"divide by zero\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">quot</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">dn</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">dn</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">dd</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">dn</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">dd</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">qk</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">dn</span><span style=\"color: #0000FF;\">]/</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">dd</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">quot</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">qk</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">d2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">mi</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">i</span>\n <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">mi</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">d2</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">mi</span><span style=\"color: #0000FF;\">]*</span><span style=\"color: #000000;\">qk</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">dn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">degree</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #000080;font-style:italic;\">-- return {quot,n} -- (n is now the remainder)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">))</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">quot</span><span style=\"color: #0000FF;\">[$]=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #000000;\">quot</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">quot</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">quot</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">poly</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- display helper</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">sit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">sit</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">sit</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">?</span> <span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\" + \"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">sit</span><span style=\"color: #0000FF;\">=-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"-\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\" - \"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #008000;\">\"\"</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">sit</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\" - \"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\" + \"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">sit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">sit</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">sit</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"x\"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"^%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">):</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">):</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">\"\"</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">\"0\"</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">r</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #000080;font-style:italic;\">--&lt;/Polynomial_long_division.exw&gt;\n\n --# memoize cache for recursive calls</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">cyclotomics</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">new_dict</span><span style=\"color: #0000FF;\">({{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}},{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}}})</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">cyclotomic</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">--\n -- Calculate the nth cyclotomic polynomial.\n -- See wikipedia article at bottom of section /wiki/Cyclotomic_polynomial#Fundamental_tools\n -- The algorithm is reliable but slow for large n &gt; 1000.\n --</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">c</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">getd_index</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cyclotomics</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #004600;\">NULL</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">getd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cyclotomics</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">is_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span> <span style=\"color: #000080;font-style:italic;\">-- recursive formula seen in wikipedia article</span>\n <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)&</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">f</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">factors</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">poly_div</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cyclotomic</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">setd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cyclotomics</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">c</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">30</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">z</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">cyclotomic</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">poly</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"cp(%2d) = %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #7060A8;\">reverse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span> <span style=\"color: #000080;font-style:italic;\">-- sanity check</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">found</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cheat</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">fn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">nxt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">105</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">385</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1365</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1785</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2805</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3135</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6545</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6545</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10465</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10465</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">found</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">JS</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">z</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">cyclotomic</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">azi</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">azi</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">azi</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">azi</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"cp(%d) has a coefficient with magnitude %d\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">azi</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">cheat</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">azi</span> <span style=\"color: #000080;font-style:italic;\">-- (comment this out to prevent cheating!)</span>\n <span style=\"color: #000000;\">found</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">azi</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">cheat</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cheat</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">nxt</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">cheat</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">else</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()></span><span style=\"color: #000000;\">t1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"working (%d) ...\\r\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n<!--\n", "language": "Phix" }, { "code": "from itertools import count, chain\nfrom collections import deque\n\ndef primes(_cache=[2, 3]):\n yield from _cache\n for n in count(_cache[-1]+2, 2):\n if isprime(n):\n _cache.append(n)\n yield n\n\ndef isprime(n):\n for p in primes():\n if n%p == 0:\n return False\n if p*p > n:\n return True\n\ndef factors(n):\n for p in primes():\n # prime factoring is such a non-issue for small numbers that, for\n # this example, we might even just say\n # for p in count(2):\n if p*p > n:\n if n > 1:\n yield(n, 1, 1)\n break\n\n if n%p == 0:\n cnt = 0\n while True:\n n, cnt = n//p, cnt+1\n if n%p != 0: break\n yield p, cnt, n\n# ^^ not the most sophisticated prime number routines, because no need\n\n# Returns (list1, list2) representing the division between\n# two polinomials. A list p of integers means the product\n# (x^p[0] - 1) * (x^p[1] - 1) * ...\ndef cyclotomic(n):\n def poly_div(num, den):\n return (num[0] + den[1], num[1] + den[0])\n\n def elevate(poly, n): # replace poly p(x) with p(x**n)\n powerup = lambda p, n: [a*n for a in p]\n return poly if n == 1 else (powerup(poly[0], n), powerup(poly[1], n))\n\n\n if n == 0:\n return ([], [])\n if n == 1:\n return ([1], [])\n\n p, m, r = next(factors(n))\n poly = cyclotomic(r)\n return elevate(poly_div(elevate(poly, p), poly), p**(m-1))\n\ndef to_text(poly):\n def getx(c, e):\n if e == 0:\n return '1'\n elif e == 1:\n return 'x'\n return 'x' + (''.join('⁰¹²³⁴⁵⁶⁷⁸⁹'[i] for i in map(int, str(e))))\n\n parts = []\n for (c,e) in (poly):\n if c < 0:\n coef = ' - ' if c == -1 else f' - {-c} '\n else:\n coef = (parts and ' + ' or '') if c == 1 else f' + {c}'\n parts.append(coef + getx(c,e))\n return ''.join(parts)\n\ndef terms(poly):\n # convert above representation of division to (coef, power) pairs\n\n def merge(a, b):\n # a, b should be deques. They may change during the course.\n while a or b:\n l = a[0] if a else (0, -1) # sentinel value\n r = b[0] if b else (0, -1)\n if l[1] > r[1]:\n a.popleft()\n elif l[1] < r[1]:\n b.popleft()\n l = r\n else:\n a.popleft()\n b.popleft()\n l = (l[0] + r[0], l[1])\n yield l\n\n def mul(poly, p): # p means polynomial x^p - 1\n poly = list(poly)\n return merge(deque((c, e+p) for c,e in poly),\n deque((-c, e) for c,e in poly))\n\n def div(poly, p): # p means polynomial x^p - 1\n q = deque()\n for c,e in merge(deque(poly), q):\n if c:\n q.append((c, e - p))\n yield (c, e - p)\n if e == p: break\n\n p = [(1, 0)] # 1*x^0, i.e. 1\n\n for x in poly[0]: # numerator\n p = mul(p, x)\n for x in sorted(poly[1], reverse=True): # denominator\n p = div(p, x)\n return p\n\nfor n in chain(range(11), [2]):\n print(f'{n}: {to_text(terms(cyclotomic(n)))}')\n\nwant = 1\nfor n in count():\n c = [c for c,_ in terms(cyclotomic(n))]\n while want in c or -want in c:\n print(f'C[{want}]: {n}')\n want += 1\n", "language": "Python" }, { "code": "use Math::Polynomial::Cyclotomic:from<Perl5> <cyclo_poly_iterate cyclo_poly>;\n\nsay 'First 30 cyclotomic polynomials:';\nmy $iterator = cyclo_poly_iterate(1);\nsay \"Φ($_) = \" ~ super $iterator().Str for 1..30;\n\nsay \"\\nSmallest cyclotomic polynomial with |n| as a coefficient:\";\nsay \"Φ(1) has a coefficient magnitude: 1\";\n\nmy $index = 0;\nfor 2..9 -> $coefficient {\n loop {\n $index += 5;\n my \\Φ = cyclo_poly($index);\n next unless Φ ~~ / $coefficient\\* /;\n say \"Φ($index) has a coefficient magnitude: $coefficient\";\n $index -= 5;\n last;\n }\n}\n\nsub super ($str) {\n $str.subst( / '^' (\\d+) /, { $0.trans([<0123456789>.comb] => [<⁰¹²³⁴⁵⁶⁷⁸⁹>.comb]) }, :g)\n}\n", "language": "Raku" }, { "code": "say \"First 30 cyclotomic polynomials:\"\nfor k in (1..30) {\n say (\"Φ(#{k}) = \", cyclotomic(k))\n}\n\nsay \"\\nSmallest cyclotomic polynomial with n or -n as a coefficient:\"\nfor n in (1..10) { # slow\n var k = (1..Inf -> first {|k|\n cyclotomic(k).coeffs.any { .tail.abs == n }\n })\n say \"Φ(#{k}) has coefficient with magnitude #{n}\"\n}\n", "language": "Sidef" }, { "code": "Imports System.Text\n\nModule Module1\n Private ReadOnly MAX_ALL_FACTORS As Integer = 100_000\n#Const ALGORITHM = 2\n\n Class Term\n Implements IComparable(Of Term)\n\n Public ReadOnly Property Coefficient As Long\n Public ReadOnly Property Exponent As Long\n\n Public Sub New(c As Long, Optional e As Long = 0)\n Coefficient = c\n Exponent = e\n End Sub\n\n Public Shared Operator -(t As Term) As Term\n Return New Term(-t.Coefficient, t.Exponent)\n End Operator\n\n Public Shared Operator +(lhs As Term, rhs As Term) As Term\n If lhs.Exponent <> rhs.Exponent Then\n Throw New ArgumentException(\"Exponents not equal\")\n End If\n Return New Term(lhs.Coefficient + rhs.Coefficient, lhs.Exponent)\n End Operator\n\n Public Shared Operator *(lhs As Term, rhs As Term) As Term\n Return New Term(lhs.Coefficient * rhs.Coefficient, lhs.Exponent + rhs.Exponent)\n End Operator\n\n Public Function CompareTo(other As Term) As Integer Implements IComparable(Of Term).CompareTo\n Return -Exponent.CompareTo(other.Exponent)\n End Function\n\n Public Overrides Function ToString() As String\n If Coefficient = 0 Then\n Return \"0\"\n End If\n If Exponent = 0 Then\n Return Coefficient.ToString\n End If\n If Coefficient = 1 Then\n If Exponent = 1 Then\n Return \"x\"\n End If\n Return String.Format(\"x^{0}\", Exponent)\n End If\n If Coefficient = -1 Then\n If Exponent = 1 Then\n Return \"-x\"\n End If\n Return String.Format(\"-x^{0}\", Exponent)\n End If\n If Exponent = 1 Then\n Return String.Format(\"{0}x\", Coefficient)\n End If\n Return String.Format(\"{0}x^{1}\", Coefficient, Exponent)\n End Function\n End Class\n\n Class Polynomial\n Implements IEnumerable(Of Term)\n\n Private ReadOnly polyTerms As New List(Of Term)\n\n Public Sub New()\n polyTerms.Add(New Term(0))\n End Sub\n\n Public Sub New(ParamArray values() As Term)\n If values.Length = 0 Then\n polyTerms.Add(New Term(0))\n Else\n polyTerms.AddRange(values)\n End If\n Normalize()\n End Sub\n\n Public Sub New(values As IEnumerable(Of Term))\n polyTerms.AddRange(values)\n If polyTerms.Count = 0 Then\n polyTerms.Add(New Term(0))\n End If\n Normalize()\n End Sub\n\n Public Function LeadingCoeficient() As Long\n Return polyTerms(0).Coefficient\n End Function\n\n Public Function Degree() As Long\n Return polyTerms(0).Exponent\n End Function\n\n Public Function HasCoefficentAbs(coeff As Long) As Boolean\n For Each t In polyTerms\n If Math.Abs(t.Coefficient) = coeff Then\n Return True\n End If\n Next\n Return False\n End Function\n\n Public Function GetEnumerator() As IEnumerator(Of Term) Implements IEnumerable(Of Term).GetEnumerator\n Return polyTerms.GetEnumerator\n End Function\n\n Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator\n Return polyTerms.GetEnumerator\n End Function\n\n Private Sub Normalize()\n polyTerms.Sort(Function(a As Term, b As Term) a.CompareTo(b))\n End Sub\n\n Public Shared Operator +(lhs As Polynomial, rhs As Term) As Polynomial\n Dim terms As New List(Of Term)\n Dim added = False\n For Each ct In lhs\n If ct.Exponent = rhs.Exponent Then\n added = True\n If ct.Coefficient + rhs.Coefficient <> 0 Then\n terms.Add(ct + rhs)\n End If\n Else\n terms.Add(ct)\n End If\n Next\n If Not added Then\n terms.Add(rhs)\n End If\n Return New Polynomial(terms)\n End Operator\n\n Public Shared Operator *(lhs As Polynomial, rhs As Term) As Polynomial\n Dim terms As New List(Of Term)\n For Each ct In lhs\n terms.Add(ct * rhs)\n Next\n Return New Polynomial(terms)\n End Operator\n\n Public Shared Operator +(lhs As Polynomial, rhs As Polynomial) As Polynomial\n Dim terms As New List(Of Term)\n Dim thisCount = lhs.polyTerms.Count\n Dim polyCount = rhs.polyTerms.Count\n While thisCount > 0 OrElse polyCount > 0\n If thisCount = 0 Then\n Dim polyTerm = rhs.polyTerms(polyCount - 1)\n terms.Add(polyTerm)\n polyCount -= 1\n ElseIf polyCount = 0 Then\n Dim thisTerm = lhs.polyTerms(thisCount - 1)\n terms.Add(thisTerm)\n thisCount -= 1\n Else\n Dim polyTerm = rhs.polyTerms(polyCount - 1)\n Dim thisTerm = lhs.polyTerms(thisCount - 1)\n If thisTerm.Exponent = polyTerm.Exponent Then\n Dim t = thisTerm + polyTerm\n If t.Coefficient <> 0 Then\n terms.Add(t)\n End If\n thisCount -= 1\n polyCount -= 1\n ElseIf thisTerm.Exponent < polyTerm.Exponent Then\n terms.Add(thisTerm)\n thisCount -= 1\n Else\n terms.Add(polyTerm)\n polyCount -= 1\n End If\n End If\n End While\n Return New Polynomial(terms)\n End Operator\n\n Public Shared Operator *(lhs As Polynomial, rhs As Polynomial) As Polynomial\n Throw New Exception(\"Not implemented\")\n End Operator\n\n Public Shared Operator /(lhs As Polynomial, rhs As Polynomial) As Polynomial\n Dim q As New Polynomial\n Dim r = lhs\n Dim lcv = rhs.LeadingCoeficient\n Dim dv = rhs.Degree\n While r.Degree >= rhs.Degree\n Dim lcr = r.LeadingCoeficient\n Dim s = lcr \\ lcv\n Dim t As New Term(s, r.Degree() - dv)\n q += t\n r += rhs * -t\n End While\n Return q\n End Operator\n\n Public Overrides Function ToString() As String\n Dim builder As New StringBuilder\n Dim it = polyTerms.GetEnumerator()\n If it.MoveNext Then\n builder.Append(it.Current)\n End If\n While it.MoveNext\n If it.Current.Coefficient < 0 Then\n builder.Append(\" - \")\n builder.Append(-it.Current)\n Else\n builder.Append(\" + \")\n builder.Append(it.Current)\n End If\n End While\n Return builder.ToString\n End Function\n End Class\n\n Function GetDivisors(number As Integer) As List(Of Integer)\n Dim divisors As New List(Of Integer)\n Dim root = CType(Math.Sqrt(number), Long)\n For i = 1 To root\n If number Mod i = 0 Then\n divisors.Add(i)\n Dim div = number \\ i\n If div <> i AndAlso div <> number Then\n divisors.Add(div)\n End If\n End If\n Next\n Return divisors\n End Function\n\n Private ReadOnly allFactors As New Dictionary(Of Integer, Dictionary(Of Integer, Integer)) From {{2, New Dictionary(Of Integer, Integer) From {{2, 1}}}}\n Function GetFactors(number As Integer) As Dictionary(Of Integer, Integer)\n If allFactors.ContainsKey(number) Then\n Return allFactors(number)\n End If\n\n Dim factors As New Dictionary(Of Integer, Integer)\n If number Mod 2 = 0 Then\n Dim factorsDivTwo = GetFactors(number \\ 2)\n For Each pair In factorsDivTwo\n If Not factors.ContainsKey(pair.Key) Then\n factors.Add(pair.Key, pair.Value)\n End If\n Next\n If factors.ContainsKey(2) Then\n factors(2) += 1\n Else\n factors.Add(2, 1)\n End If\n If number < MAX_ALL_FACTORS Then\n allFactors.Add(number, factors)\n End If\n Return factors\n End If\n Dim root = CType(Math.Sqrt(number), Long)\n Dim i = 3L\n While i <= root\n If number Mod i = 0 Then\n Dim factorsDivI = GetFactors(number \\ i)\n For Each pair In factorsDivI\n If Not factors.ContainsKey(pair.Key) Then\n factors.Add(pair.Key, pair.Value)\n End If\n Next\n If factors.ContainsKey(i) Then\n factors(i) += 1\n Else\n factors.Add(i, 1)\n End If\n If number < MAX_ALL_FACTORS Then\n allFactors.Add(number, factors)\n End If\n Return factors\n End If\n i += 2\n End While\n factors.Add(number, 1)\n If number < MAX_ALL_FACTORS Then\n allFactors.Add(number, factors)\n End If\n Return factors\n End Function\n\n Private ReadOnly computedPolynomials As New Dictionary(Of Integer, Polynomial)\n Function CyclotomicPolynomial(n As Integer) As Polynomial\n If computedPolynomials.ContainsKey(n) Then\n Return computedPolynomials(n)\n End If\n\n If n = 1 Then\n REM polynomial: x - 1\n Dim p As New Polynomial(New Term(1, 1), New Term(-1))\n computedPolynomials.Add(n, p)\n Return p\n End If\n\n Dim factors = GetFactors(n)\n Dim terms As New List(Of Term)\n Dim cyclo As Polynomial\n\n If factors.ContainsKey(n) Then\n REM n prime\n For index = 1 To n\n terms.Add(New Term(1, index - 1))\n Next\n\n cyclo = New Polynomial(terms)\n computedPolynomials.Add(n, cyclo)\n Return cyclo\n ElseIf factors.Count = 2 AndAlso factors.ContainsKey(2) AndAlso factors(2) = 1 AndAlso factors.ContainsKey(n / 2) AndAlso factors(n / 2) = 1 Then\n REM n = 2p\n Dim prime = n \\ 2\n Dim coeff = -1\n\n For index = 1 To prime\n coeff *= -1\n terms.Add(New Term(coeff, index - 1))\n Next\n\n cyclo = New Polynomial(terms)\n computedPolynomials.Add(n, cyclo)\n Return cyclo\n ElseIf factors.Count = 1 AndAlso factors.ContainsKey(2) Then\n REM n = 2^h\n Dim h = factors(2)\n terms = New List(Of Term) From {\n New Term(1, Math.Pow(2, h - 1)),\n New Term(1)\n }\n\n cyclo = New Polynomial(terms)\n computedPolynomials.Add(n, cyclo)\n Return cyclo\n ElseIf factors.Count = 1 AndAlso factors.ContainsKey(n) Then\n REM n = p^k\n Dim p = 0\n Dim k = 0\n For Each it In factors\n p = it.Key\n k = it.Value\n Next\n For index = 1 To p\n terms.Add(New Term(1, (index - 1) * Math.Pow(p, k - 1)))\n Next\n\n cyclo = New Polynomial(terms)\n computedPolynomials.Add(n, cyclo)\n Return cyclo\n ElseIf factors.Count = 2 AndAlso factors.ContainsKey(2) Then\n REM n = 2^h * p^k\n Dim p = 0\n For Each it In factors\n If it.Key <> 2 Then\n p = it.Key\n End If\n Next\n\n Dim coeff = -1\n Dim twoExp = CType(Math.Pow(2, factors(2) - 1), Long)\n Dim k = factors(p)\n For index = 1 To p\n coeff *= -1\n terms.Add(New Term(coeff, (index - 1) * twoExp * Math.Pow(p, k - 1)))\n Next\n\n cyclo = New Polynomial(terms)\n computedPolynomials.Add(n, cyclo)\n Return cyclo\n ElseIf factors.ContainsKey(2) AndAlso (n / 2) Mod 2 = 1 AndAlso n / 2 > 1 Then\n REM CP(2m)[x] = CP(-m)[x], n odd integer > 1\n Dim cycloDiv2 = CyclotomicPolynomial(n \\ 2)\n For Each t In cycloDiv2\n If t.Exponent Mod 2 = 0 Then\n terms.Add(t)\n Else\n terms.Add(-t)\n End If\n Next\n\n cyclo = New Polynomial(terms)\n computedPolynomials.Add(n, cyclo)\n Return cyclo\n End If\n\n#If ALGORITHM = 0 Then\n REM slow - uses basic definition\n Dim divisors = GetDivisors(n)\n REM Polynomial: (x^n - 1)\n cyclo = New Polynomial(New Term(1, n), New Term(-1))\n For Each i In divisors\n Dim p = CyclotomicPolynomial(i)\n cyclo /= p\n Next\n\n computedPolynomials.Add(n, cyclo)\n Return cyclo\n#ElseIf ALGORITHM = 1 Then\n REM Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor\n Dim divisors = GetDivisors(n)\n Dim maxDivisor = Integer.MinValue\n For Each div In divisors\n maxDivisor = Math.Max(maxDivisor, div)\n Next\n Dim divisorExceptMax As New List(Of Integer)\n For Each div In divisors\n If maxDivisor Mod div <> 0 Then\n divisorExceptMax.Add(div)\n End If\n Next\n\n REM Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor\n cyclo = New Polynomial(New Term(1, n), New Term(-1)) / New Polynomial(New Term(1, maxDivisor), New Term(-1))\n For Each i In divisorExceptMax\n Dim p = CyclotomicPolynomial(i)\n cyclo /= p\n Next\n\n computedPolynomials.Add(n, cyclo)\n Return cyclo\n#ElseIf ALGORITHM = 2 Then\n REM Fastest\n REM Let p ; q be primes such that p does not divide n, and q divides n\n REM Then Cp(np)[x] = CP(n)[x^p] / CP(n)[x]\n Dim m = 1\n cyclo = CyclotomicPolynomial(m)\n Dim primes As New List(Of Integer)\n For Each it In factors\n primes.Add(it.Key)\n Next\n primes.Sort()\n For Each prime In primes\n REM CP(m)[x]\n Dim cycloM = cyclo\n REM Compute CP(m)[x^p]\n terms = New List(Of Term)\n For Each t In cyclo\n terms.Add(New Term(t.Coefficient, t.Exponent * prime))\n Next\n cyclo = New Polynomial(terms) / cycloM\n m *= prime\n Next\n REM Now, m is the largest square free divisor of n\n Dim s = n \\ m\n REM Compute CP(n)[x] = CP(m)[x^s]\n terms = New List(Of Term)\n For Each t In cyclo\n terms.Add(New Term(t.Coefficient, t.Exponent * s))\n Next\n\n cyclo = New Polynomial(terms)\n computedPolynomials.Add(n, cyclo)\n Return cyclo\n#Else\n Throw New Exception(\"Invalid algorithm\")\n#End If\n End Function\n\n Sub Main()\n Console.WriteLine(\"Task 1: cyclotomic polynomials for n <= 30:\")\n For i = 1 To 30\n Dim p = CyclotomicPolynomial(i)\n Console.WriteLine(\"CP[{0}] = {1}\", i, p)\n Next\n Console.WriteLine()\n\n Console.WriteLine(\"Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\")\n Dim n = 0\n For i = 1 To 10\n While True\n n += 1\n Dim cyclo = CyclotomicPolynomial(n)\n If cyclo.HasCoefficentAbs(i) Then\n Console.WriteLine(\"CP[{0}] has coefficient with magnitude = {1}\", n, i)\n n -= 1\n Exit While\n End If\n End While\n Next\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./iterate\" for Stepped\nimport \"./sort\" for Sort\nimport \"./math\" for Int, Nums\nimport \"./fmt\" for Fmt\n\nvar algo = 2\nvar maxAllFactors = 1e5\n\nclass Term {\n construct new(coef, exp) {\n _coef = coef\n _exp = exp\n }\n\n coef { _coef }\n exp { _exp }\n\n *(t) { Term.new(_coef * t.coef, _exp + t.exp) }\n\n +(t) {\n if (_exp != t.exp) Fiber.abort(\"Exponents unequal in term '+' method.\")\n return Term.new(_coef + t.coef, _exp)\n }\n\n - { Term.new(-_coef, _exp) }\n\n toString {\n if (_coef == 0) return \"0\"\n if (_exp == 0) return _coef.toString\n if (_coef == 1) return (_exp == 1) ? \"x\" : \"x^%(_exp)\"\n if (_exp == 1) return \"%(_coef)x\"\n return \"%(_coef)x^%(_exp)\"\n }\n}\n\nclass Poly {\n // pass coef, exp in pairs as parameters\n construct new(values) {\n var le = values.count\n if (le == 0) {\n _terms = [Term.new(0, 0)]\n } else {\n if (le%2 != 0) Fiber.abort(\"Odd number of parameters(%(le)) passed to Poly constructor.\")\n _terms = []\n for (i in Stepped.new(0...le, 2)) _terms.add(Term.new(values[i], values[i+1]))\n tidy()\n }\n }\n\n terms { _terms }\n\n hasCoefAbs(coef) { _terms.any { |t| t.coef.abs == coef } }\n\n +(p2) {\n var p3 = Poly.new([])\n var le = _terms.count\n var le2 = p2.terms.count\n while (le > 0 || le2 > 0) {\n if (le == 0) {\n p3.terms.add(p2.terms[le2-1])\n le2 = le2 - 1\n } else if (le2 == 0) {\n p3.terms.add(_terms[le-1])\n le = le - 1\n } else {\n var t = _terms[le-1]\n var t2 = p2.terms[le2-1]\n if (t.exp == t2.exp) {\n var t3 = t + t2\n if (t3.coef != 0) p3.terms.add(t3)\n le = le - 1\n le2 = le2 - 1\n } else if (t.exp < t2.exp) {\n p3.terms.add(t)\n le = le - 1\n } else {\n p3.terms.add(t2)\n le2 = le2 - 1\n }\n }\n }\n p3.tidy()\n return p3\n }\n\n addTerm(t) {\n var q = Poly.new([])\n var added = false\n for (i in 0..._terms.count) {\n var ct = _terms[i]\n if (ct.exp == t.exp) {\n added = true\n if (ct.coef + t.coef != 0) q.terms.add(ct + t)\n } else {\n q.terms.add(ct)\n }\n }\n if (!added) q.terms.add(t)\n q.tidy()\n return q\n }\n\n mulTerm(t) {\n var q = Poly.new([])\n for (i in 0..._terms.count) {\n var ct = _terms[i]\n q.terms.add(ct * t)\n }\n q.tidy()\n return q\n }\n\n /(v) {\n var p = this\n var q = Poly.new([])\n var lcv = v.leadingCoef\n var dv = v.degree\n while (p.degree >= v.degree) {\n var lcp = p.leadingCoef\n var s = (lcp/lcv).truncate\n var t = Term.new(s, p.degree - dv)\n q = q.addTerm(t)\n p = p + v.mulTerm(-t)\n }\n q.tidy()\n return q\n }\n\n leadingCoef { _terms[0].coef }\n\n degree { _terms[0].exp }\n\n toString {\n var sb = \"\"\n var first = true\n for (t in _terms) {\n if (first) {\n sb = sb + t.toString\n first = false\n } else {\n sb = sb + \" \"\n if (t.coef > 0) {\n sb = sb + \"+ \"\n sb = sb + t.toString\n } else {\n sb = sb + \"- \"\n sb = sb + (-t).toString\n }\n }\n }\n return sb\n }\n\n // in place descending sort by term.exp\n sortTerms() {\n var cmp = Fn.new { |t1, t2| (t2.exp - t1.exp).sign }\n Sort.quick(_terms, 0, _terms.count-1, cmp)\n }\n\n // sort terms and remove any unnecesary zero terms\n tidy() {\n sortTerms()\n if (degree > 0) {\n for (i in _terms.count-1..0) {\n if (_terms[i].coef == 0) _terms.removeAt(i)\n }\n if (_terms.count == 0) _terms.add(Term.new(0, 0))\n }\n }\n}\n\nvar computed = {}\nvar allFactors = {2: {2: 1}}\n\nvar getFactors // recursive function\ngetFactors = Fn.new { |n|\n var f = allFactors[n]\n if (f) return f\n var factors = {}\n if (n%2 == 0) {\n var factorsDivTwo = getFactors.call(n/2)\n for (me in factorsDivTwo) factors[me.key] = me.value\n factors[2] = factors[2] ? factors[2] + 1 : 1\n if (n < maxAllFactors) allFactors[n] = factors\n return factors\n }\n var prime = true\n var sqrt = n.sqrt.floor\n var i = 3\n while (i <= sqrt){\n if (n%i == 0) {\n prime = false\n for (me in getFactors.call(n/i)) factors[me.key] = me.value\n factors[i] = factors[i] ? factors[i] + 1 : 1\n if (n < maxAllFactors) allFactors[n] = factors\n return factors\n }\n i = i + 2\n }\n if (prime) {\n factors[n] = 1\n if (n < maxAllFactors) allFactors[n] = factors\n }\n return factors\n}\n\nvar cycloPoly // recursive function\ncycloPoly = Fn.new { |n|\n var p = computed[n]\n if (p) return p\n if (n == 1) {\n // polynomialL x - 1\n p = Poly.new([1, 1, -1, 0])\n computed[1] = p\n return p\n }\n var factors = getFactors.call(n)\n var cyclo = Poly.new([])\n if (factors[n]) {\n // n is prime\n for (i in 0...n) cyclo.terms.add(Term.new(1, i))\n } else if (factors.count == 2 && factors[2] == 1 && factors[n/2] == 1) {\n // n == 2p\n var prime = n / 2\n var coef = -1\n for (i in 0...prime) {\n coef = coef * (-1)\n cyclo.terms.add(Term.new(coef, i))\n }\n } else if (factors.count == 1) {\n var h = factors[2]\n if (h) { // n == 2^h\n cyclo.terms.addAll([Term.new(1, 1 << (h-1)), Term.new(1, 0)])\n } else if (!factors[n]) {\n // n == p ^ k\n var p = 0\n for (prime in factors.keys) p = prime\n var k = factors[p]\n for (i in 0...p) {\n var pk = p.pow(k-1).floor\n cyclo.terms.add(Term.new(1, i * pk))\n }\n }\n } else if (factors.count == 2 && factors[2]) {\n // n = 2^h * p^k\n var p = 0\n for (prime in factors.keys) if (prime != 2) p = prime\n var coef = -1\n var twoExp = 1 << (factors[2] - 1)\n var k = factors[p]\n for (i in 0...p) {\n coef = coef * (-1)\n var pk = p.pow(k-1).floor\n cyclo.terms.add(Term.new(coef, i * twoExp * pk))\n }\n } else if (factors[2] && (n/2) % 2 == 1 && (n/2) > 1) {\n // CP(2m)[x] == CP(-m)[x], n odd integer > 1\n var cycloDiv2 = cycloPoly.call(n/2)\n for (t in cycloDiv2.terms) {\n var t2 = t\n if (t.exp % 2 != 0) t2 = -t\n cyclo.terms.add(t2)\n }\n } else if (algo == 0) {\n // slow - uses basic definition\n var divs = Int.properDivisors(n)\n // polynomial: x^n - 1\n var cyclo = Poly.new([1, n, -1, 0])\n for (i in divs) {\n var p = cycloPoly.call(i)\n cyclo = cyclo / p\n }\n } else if (algo == 1) {\n // faster - remove max divisor (and all divisors of max divisor)\n // only one divide for all divisors of max divisor\n var divs = Int.properDivisors(n)\n var maxDiv = Nums.max(divs)\n var divsExceptMax = divs.where { |d| maxDiv % d != 0 }.toList\n // polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor\n cyclo = Poly.new([1, n, -1, 0])\n cyclo = cyclo / Poly.new([1, maxDiv, -1, 0])\n for (i in divsExceptMax) {\n var p = cycloPoly.call(i)\n cyclo = cyclo / p\n }\n } else if (algo == 2) {\n // fastest\n // let p, q be primes such that p does not divide n, and q divides n\n // then CP(np)[x] = CP(n)[x^p] / CP(n)[x]\n var m = 1\n cyclo = cycloPoly.call(m)\n var primes = []\n for (prime in factors.keys) primes.add(prime)\n Sort.quick(primes)\n for (prime in primes) {\n // CP(m)[x]\n var cycloM = cyclo\n // compute CP(m)[x^p]\n var terms = []\n for (t in cycloM.terms) terms.add(Term.new(t.coef, t.exp * prime))\n cyclo = Poly.new([])\n cyclo.terms.addAll(terms)\n cyclo.tidy()\n cyclo = cyclo / cycloM\n m = m * prime\n }\n // now, m is the largest square free divisor of n\n var s = n / m\n // Compute CP(n)[x] = CP(m)[x^s]\n var terms = []\n for (t in cyclo.terms) terms.add(Term.new(t.coef, t.exp * s))\n cyclo = Poly.new([])\n cyclo.terms.addAll(terms)\n } else {\n Fiber.abort(\"Invalid algorithm.\")\n }\n cyclo.tidy()\n computed[n] = cyclo\n return cyclo\n}\n\nSystem.print(\"Task 1: cyclotomic polynomials for n <= 30:\")\nfor (i in 1..30) {\n var p = cycloPoly.call(i)\n Fmt.print(\"CP[$2d] = $s\", i, p)\n}\n\nSystem.print(\"\\nTask 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\")\nvar n = 0\nfor (i in 1..7) {\n while(true) {\n n = n + 1\n var cyclo = cycloPoly.call(n)\n if (cyclo.hasCoefAbs(i)) {\n Fmt.print(\"CP[$d] has coefficient with magnitude = $d\", n, i)\n n = n - 1\n break\n }\n }\n}\n", "language": "Wren" }, { "code": "import \"./math\" for Int\nimport \"./fmt\" for Fmt\n\nclass CP {\n // Return the Cyclotomic Polynomial of order 'cpIndex' as a list of coefficients,\n // where, for example, the polynomial 3x^2 - 1 is represented by the list [3, 0, -1].\n static cycloPoly(cpIndex) {\n var polynomial = [1, -1]\n if (cpIndex == 1) return polynomial\n if (Int.isPrime(cpIndex)) return List.filled(cpIndex, 1)\n var primes = Int.distinctPrimeFactors(cpIndex)\n var product = 1\n for (prime in primes) {\n var numerator = substituteExponent(polynomial, prime)\n polynomial = exactDivision(numerator, polynomial)\n product = product * prime\n }\n return substituteExponent(polynomial, Int.quo(cpIndex, product))\n }\n\n // Return the Cyclotomic Polynomial obtained from 'polynomial'\n // by replacing x with x^'exponent'.\n static substituteExponent(polynomial, exponent) {\n var result = List.filled(exponent * (polynomial.count - 1) + 1, 0)\n for (i in polynomial.count-1..0) result[i*exponent] = polynomial[i]\n return result\n }\n\n // Return the Cyclotomic Polynomial equal to 'dividend' / 'divisor'.\n // The division is always exact.\n static exactDivision(dividend, divisor) {\n var result = dividend.toList\n for (i in 0..dividend.count - divisor.count) {\n if (result[i] != 0) {\n for (j in 1...divisor.count) {\n result[i+j] = result[i+j] - divisor[j] * result[i]\n }\n }\n }\n return result[0..result.count - divisor.count]\n }\n\n // Return whether 'polynomial' has a coefficient of equal magnitude\n // to 'coefficient'.\n static hasHeight(polynomial, coefficient) {\n for (i in 0..Int.quo(polynomial.count + 1, 2)) {\n if (polynomial[i].abs == coefficient) return true\n }\n return false\n }\n}\n\nSystem.print(\"Task 1: Cyclotomic polynomials for n <= 30:\")\nfor (cpIndex in 1..30) {\n Fmt.write(\"CP[$2d] = \", cpIndex)\n Fmt.pprint(\"$d\", CP.cycloPoly(cpIndex), \"\", \"x\")\n}\n\nSystem.print(\"\\nTask 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\")\nSystem.print(\"CP[ 1] has a coefficient with magnitude 1\")\nvar cpIndex = 2\nfor (coeff in 2..10) {\n while (Int.isPrime(cpIndex) || !CP.hasHeight(CP.cycloPoly(cpIndex), coeff)) {\n cpIndex = cpIndex + 1\n }\n Fmt.print(\"CP[$5d] has a coefficient with magnitude $d\", cpIndex, coeff)\n}\n", "language": "Wren" } ]
Cyclotomic-polynomial
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Damm_algorithm\n", "language": "00-META" }, { "code": "The [[wp:Damm_algorithm|'''Damm''' algorithm]] is a checksum algorithm which detects all single digit errors and adjacent transposition errors. \n\n\nThe algorithm is named after H. Michael Damm.\n\n\n;Task:\nVerify the checksum, stored as last digit of an input.\n\n<!-- It's draft because I didn't specify it's requirements, see Wikipedia. -->\n<br><br>\n\n", "language": "00-TASK" }, { "code": "V matrix = [\n [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0]\n]\n\nF damm(Int num) -> Bool\n V row = 0\n L(digit) String(num)\n row = :matrix[row][Int(digit)]\n R row == 0\n\nL(test) [5724, 5727, 112946]\n print(test\"\\t Validates as: \"damm(test))\n", "language": "11l" }, { "code": "\torg\t100h\n\tjmp\tdemo\n\t;;;\tGiven an 0-terminated ASCII string containing digits in [DE],\n\t;;;\tsee if it matches its check digit. Returns with zero flag set\n\t;;;\tif the string matches.\ndamm:\tmvi\tc,0\t; Interim digit in C, starts off at 0.\n\tldax\td\t; Get current byte from string\n\tinx\td \t; Advance the pointer\n\tana\ta\t; Is the byte zero?\n\tjnz\t$+5\t; If not, go look up interim digit\n\tcmp\tc\t; But if so, see if the interim digit is also zero\n\tret\t\t; And return whether this was the case\n\tsui\t'0'\t; Subtract ASCII 0\n\tmov\tb,a\t; Keep digit to be processed in B\n\tmov\ta,c\t; Calculate C*10 (interim digit row index)\n\tadd\ta\t; * 2\n\tadd\ta\t; * 4\n\tadd\tc\t; * 5\n\tadd\ta\t; * 10\n\tadd\tb\t; Add column index\n\tlxi\th,dammit\n\tadd\tl\t; Table lookup (assuming H doesn't change, i.e. it\n\tmov\tl,a\t; doesn't cross a page boundary).\n\tmov\tc,m\t; Get new interim digit from table\n\tjmp\tdamm+2\t; And check next character\n\t;;;\tTable of interim digits\n\t;;;\tNOTE: must not cross page boundary\ndammit:\tdb\t0,3,1,7,5,9,8,6,4,2\n\tdb\t7,0,9,2,1,5,4,8,6,3\n\tdb\t4,2,0,6,8,7,1,3,5,9\n\tdb\t1,7,5,0,9,8,3,4,2,6\n\tdb\t6,1,2,3,0,4,5,9,7,8\n\tdb\t3,6,7,4,2,0,9,5,8,1\n\tdb\t5,8,6,9,7,2,0,1,3,4\n\tdb\t8,9,4,5,3,6,2,0,1,7\n\tdb\t9,4,3,8,6,1,7,2,0,5\n\tdb\t2,5,8,1,4,3,6,7,9,0\n\t;;;\tDemo code: see if the argument on the CP/M command line\n\t;;;\tmatches its input.\ndemo:\tlxi\th,80h\t; Zero-terminate input\n\tmov\te,m\n\tmvi\td,0\n\tinx\td\n\tdad\td\n\tmov\tm,d\n\tlxi\td,82h\t; Command line argument, skipping first space\n\tcall\tdamm\t; See if it validates\n\tmvi\tc,9\n\tlxi\td,ok\t; Print OK...\n\tjz\t5\t; ...if the checksum matches,\n\tlxi\td,no\t; Print NOT OK otherwise.\n\tjmp\t5\nno:\tdb\t'NOT '\nok:\tdb\t'OK$'\n", "language": "8080-Assembly" }, { "code": "\tcpu\t8086\n\tbits\t16\nsection\t.text\n\torg\t100h\n\tjmp\tdemo\n\t;;;\tGiven a 0-terminated ASCII string containing digits in\n\t;;;\t[DS:SI], see if the check digit matches. Returns with zero flag\n\t;;;\tset if it matches.\ndamm:\txor\tcl,cl\t; Interim digit starts out at 0\n\tmov\tbx,.tab\t; Index for table lookup\n.dgt:\tlodsb\t\t; Get next string byte\n\ttest\tal,al\t; If it is zero, we're done\n\tjz\t.out\n\tsub\tal,'0'\t; Make ASCII digit\n\tmov\tah,cl\t; Table lookup, AH = interim digit\n\taad\t\t; AL += AH * 10 (such handy instructions the 8086 has)\n\tcs \txlatb\t; AL = CS:table[AL]\n\tmov\tcl,al\t; CL = new interim digit\n\tjmp\t.dgt\t; Get next string\n.out:\ttest\tcl,cl\t; Interim digit should be zero at the end\n\tret\n.tab:\tdb\t0,3,1,7,5,9,8,6,4,2\t; Table can be stored as part of the\n\tdb\t7,0,9,2,1,5,4,8,6,3\t; code\n\tdb\t4,2,0,6,8,7,1,3,5,9\n\tdb\t1,7,5,0,9,8,3,4,2,6\n\tdb\t6,1,2,3,0,4,5,9,7,8\n\tdb\t3,6,7,4,2,0,9,5,8,1\n\tdb\t5,8,6,9,7,2,0,1,3,4\n\tdb\t8,9,4,5,3,6,2,0,1,7\n\tdb\t9,4,3,8,6,1,7,2,0,5\n\tdb\t2,5,8,1,4,3,6,7,9,0\n\t;;;\tDemo: see if the argument on the MS-DOS command line is valid\ndemo:\txor\tbh,bh\t; Zero-terminate the input\n\tmov\tbl,[80h]\n\tmov\t[bx+81h],bh\n\tmov\tsi,82h\t; Start of input skipping first space\n\tcall\tdamm\t; Is it valid?\n\tmov\tdx,ok\t; If so, print OK\n\tjz\t.print\n\tmov\tdx,no \t; Otherwise, print NOT OK\n.print:\tmov\tah,9\n\tint\t21h\n\tret\nsection\t.data\nno:\tdb\t'NOT '\nok: \tdb\t'OK$'\n", "language": "8086-Assembly" }, { "code": "BYTE FUNC Damm(CHAR ARRAY a)\n BYTE ARRAY table=[\n 0 3 1 7 5 9 8 6 4 2\n 7 0 9 2 1 5 4 8 6 3\n 4 2 0 6 8 7 1 3 5 9\n 1 7 5 0 9 8 3 4 2 6\n 6 1 2 3 0 4 5 9 7 8\n 3 6 7 4 2 0 9 5 8 1\n 5 8 6 9 7 2 0 1 3 4\n 8 9 4 5 3 6 2 0 1 7\n 9 4 3 8 6 1 7 2 0 5\n 2 5 8 1 4 3 6 7 9 0]\n BYTE i,x,c\n\n x=0\n FOR i=1 TO a(0)\n DO\n c=a(i)\n IF c<'0 OR c>'9 THEN\n RETURN (0)\n FI\n c==-'0\n x=table(x*10+c)\n OD\n IF x=0 THEN\n RETURN (1)\n FI\nRETURN (0)\n\nPROC Test(CHAR ARRAY a)\n BYTE i\n\n Print(a) Print(\" -> \")\n IF Damm(a)=1 THEN\n PrintE(\"valid\")\n ELSE\n PrintE(\"invalid\")\n FI\nRETURN\n\nPROC Main()\n Test(\"5724\")\n Test(\"5727\")\n Test(\"112946\")\n Test(\"112949\")\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO;\n\nprocedure Damm_Algorithm is\n\n function Damm (Input : in String) return Boolean\n is\n subtype Digit is Character range '0' .. '9';\n\n Table : constant array (Digit, Digit) of Digit :=\n (('0', '3', '1', '7', '5', '9', '8', '6', '4', '2'),\n ('7', '0', '9', '2', '1', '5', '4', '8', '6', '3'),\n ('4', '2', '0', '6', '8', '7', '1', '3', '5', '9'),\n ('1', '7', '5', '0', '9', '8', '3', '4', '2', '6'),\n ('6', '1', '2', '3', '0', '4', '5', '9', '7', '8'),\n ('3', '6', '7', '4', '2', '0', '9', '5', '8', '1'),\n ('5', '8', '6', '9', '7', '2', '0', '1', '3', '4'),\n ('8', '9', '4', '5', '3', '6', '2', '0', '1', '7'),\n ('9', '4', '3', '8', '6', '1', '7', '2', '0', '5'),\n ('2', '5', '8', '1', '4', '3', '6', '7', '9', '0'));\n Intern : Digit := '0';\n begin\n for D of Input loop\n Intern := Table (Intern, D);\n end loop;\n return Intern = '0';\n end Damm;\n\n procedure Put_Damm (Input : in String) is\n use Ada.Text_IO;\n begin\n Put_Line (\"Damm of \" & Input & \" validates as \" & Damm (Input)'Image);\n end Put_Damm;\n\nbegin\n Put_Damm (\"5724\");\n Put_Damm (\"5727\");\n Put_Damm (\"112946\");\n Put_Damm (\"112949\");\nend Damm_Algorithm;\n", "language": "Ada" }, { "code": "BEGIN\n # returns TRUE if the check digit of s is correct according to the Damm algorithm, #\n # FALSE otherwise #\n PROC has valid damm check digit = ( STRING s )BOOL:\n BEGIN\n # operation table - as per wikipedia example #\n [,]INT operation table =\n ( [,]INT( ( 0, 3, 1, 7, 5, 9, 8, 6, 4, 2 )\n , ( 7, 0, 9, 2, 1, 5, 4, 8, 6, 3 )\n , ( 4, 2, 0, 6, 8, 7, 1, 3, 5, 9 )\n , ( 1, 7, 5, 0, 9, 8, 3, 4, 2, 6 )\n , ( 6, 1, 2, 3, 0, 4, 5, 9, 7, 8 )\n , ( 3, 6, 7, 4, 2, 0, 9, 5, 8, 1 )\n , ( 5, 8, 6, 9, 7, 2, 0, 1, 3, 4 )\n , ( 8, 9, 4, 5, 3, 6, 2, 0, 1, 7 )\n , ( 9, 4, 3, 8, 6, 1, 7, 2, 0, 5 )\n , ( 2, 5, 8, 1, 4, 3, 6, 7, 9, 0 )\n )\n ) [ AT 0, AT 0 ]\n ;\n INT interim digit := 0;\n FOR s pos FROM LWB s TO UPB s DO\n INT next digit = ABS s[ s pos ] - ABS \"0\";\n IF next digit < 0 OR next digit > 9 THEN\n # invalid digit #\n print( ( \"Invalid damm digit: \", s[ s pos ], newline ) );\n stop\n ELSE\n # have a valid digit #\n interim digit := operation table[ interim digit, next digit ]\n FI\n OD;\n interim digit = 0\n END # has valid damm check digit # ;\n\n # test the damm algorithm #\n PROC test damm algorithm = ( STRING s, BOOL expected )VOID:\n BEGIN\n BOOL valid = has valid damm check digit( s );\n print( ( \"check digit of \", s, \" is \"\n , IF valid THEN \"valid\" ELSE \"invalid\" FI\n , IF valid = expected THEN \"\" ELSE \" *** NOT AS EXPECTED\" FI\n , newline\n )\n )\n END # test damm algorithm # ;\n # test cases - as per other language samples #\n test damm algorithm( \"5724\", TRUE );\n test damm algorithm( \"5727\", FALSE );\n test damm algorithm( \"112946\", TRUE )\nEND\n", "language": "ALGOL-68" }, { "code": " damm←{⎕IO←0\n tbl←⍉⍪0 3 1 7 5 9 8 6 4 2\n tbl⍪← 7 0 9 2 1 5 4 8 6 3\n tbl⍪← 4 2 0 6 8 7 1 3 5 9\n tbl⍪← 1 7 5 0 9 8 3 7 2 6\n tbl⍪← 6 1 2 3 0 4 5 9 7 8\n tbl⍪← 3 6 7 4 2 0 9 5 8 1\n tbl⍪← 5 8 6 9 7 2 0 1 3 4\n tbl⍪← 8 9 4 5 3 6 2 0 1 7\n tbl⍪← 9 4 3 8 6 1 7 2 0 5\n tbl⍪← 2 5 8 1 4 3 6 7 9 0\n 0={tbl[⍵;⍺]}/⌽0,⍵\n }\n", "language": "APL" }, { "code": "-- Return a check digit value for the given integer value or numeric string.\n-- The result is 0 if the input's last digit is already a valid check digit for it.\non damm(n)\n set digits to {n mod 10}\n set n to n div 10\n repeat until (n is 0)\n set beginning of digits to n mod 10\n set n to n div 10\n end repeat\n\n script o\n property table : {0, 3, 1, 7, 5, 9, 8, 6, 4, 2, ¬\n 7, 0, 9, 2, 1, 5, 4, 8, 6, 3, ¬\n 4, 2, 0, 6, 8, 7, 1, 3, 5, 9, ¬\n 1, 7, 5, 0, 9, 8, 3, 4, 2, 6, ¬\n 6, 1, 2, 3, 0, 4, 5, 9, 7, 8, ¬\n 3, 6, 7, 4, 2, 0, 9, 5, 8, 1, ¬\n 5, 8, 6, 9, 7, 2, 0, 1, 3, 4, ¬\n 8, 9, 4, 5, 3, 6, 2, 0, 1, 7, ¬\n 9, 4, 3, 8, 6, 1, 7, 2, 0, 5, ¬\n 2, 5, 8, 1, 4, 3, 6, 7, 9, 0}\n end script\n set interim to 0\n repeat with d in digits\n set interim to item (interim * 10 + d + 1) of o's table -- AppleScript indices are 1-based.\n end repeat\n\n return interim\nend damm\n\n-- Task code:\nlocal testNumbers, possibilities, output, n\nset testNumbers to {5724, 57240, 572400, 87591, 100}\n-- Include a number with a check digit actually generated by the handler.\ntell (random number 1000000) to set end of testNumbers to it * 10 + (my damm(it))\nset possibilities to {\" is invalid\", \" is valid\"}\nset output to {}\nrepeat with n in testNumbers\n set end of output to (n as text) & item (((damm(n) is 0) as integer) + 1) of possibilities\nend repeat\nreturn output\n", "language": "AppleScript" }, { "code": "{\"5724 is valid\", \"57240 is valid\", \"572400 is valid\", \"87591 is invalid\", \"100 is invalid\", \"3922446 is valid\"}\n", "language": "AppleScript" }, { "code": ".text\n.global\t_start\n\t@@@\tCheck if the zero-terminated ASCII string in [r0],\n\t@@@\twhich should contain a decimal number, has a\n\t@@@\tmatching check digit. Zero flag set if true,\n\t@@@\tcheck digit returned in r0.\ndamm:\tmov\tr1,#0\t\t@ R1 = interim digit\n\tldr\tr2,=3f\t\t@ R2 = table base address\n1:\tldrb\tr3,[r0],#1\t@ Load byte\n\ttst\tr3,r3\t\t@ Zero yet?\n\tbeq\t2f\t\t@ If so, stop\n\tsub\tr3,r3,#'0\t@ Subtract ASCII 0\n\tlsl\tr1,r1,#1\t@ Table lookup\n\tadd\tr1,r1,r1,lsl#2\t@ R3 = R1*10 + R3\n\tadd\tr3,r1,r3\n\tldrb\tr1,[r2,r3]\t@ R1 = new interim digit\n\tb\t1b\t\t@ Next value\n2:\tmovs\tr0,r1\t\t@ Set flag according to r0.\n\tbx\tlr\n3:\t.byte\t0,3,1,7,5,9,8,6,4,2\t@ Since the table is constant,\n\t.byte\t7,0,9,2,1,5,4,8,6,3\t@ it can be stored as part of\n\t.byte\t4,2,0,6,8,7,1,3,5,9\t@ the subroutine.\n\t.byte\t1,7,5,0,9,8,3,4,2,6\t@ This way the OS will even mark\n\t.byte\t6,1,2,3,0,4,5,9,7,8\t@ it as read-only, so we can\n\t.byte\t3,6,7,4,2,0,9,5,8,1\t@ be sure nothing changes it.\n\t.byte\t5,8,6,9,7,2,0,1,3,4\n\t.byte\t8,9,4,5,3,6,2,0,1,7\n\t.byte\t9,4,3,8,6,1,7,2,0,5\n\t.byte\t2,5,8,1,4,3,6,7,9,0\n.align\t4\t\t\t@ Instructions must be word-aligned\n\t@@@\tGrab the argument from the command line, and see\n\t@@@\tif it matches.\n_start:\tpop\t{r0}\t\t@ Is there even an argument?\n\tcmp \tr0,#2\n\tmovne\tr7,#1\t\t@ If not, exit immediately\n\tswine\t#0\n\tadd\tsp,sp,#4\t@ Discard program name\n\tpop\t{r0}\t\t@ Grab argument\n\tbl\tdamm\t\t@ Check if it matches\n\tldreq\tr1,=pass\t@ If yes, say 'pass'\n\tldrne\tr1,=fail\t@ If not, say 'fail'\n\tmov\tr0,#1\t\t@ Print string to stdout\n\tmov\tr2,#5\t\t@ Both are 5 characters\n\tmov\tr7,#4\t\t@ Write syscall = 4\n\tswi\t#0\n\tmov\tr0,#0\t\t@ Exit\n\tmov\tr7,#1\n\tswi\t#0\npass:\t.ascii\t\"Pass\\n\"\nfail:\t.ascii\t\"Fail\\n\"\n", "language": "ARM-Assembly" }, { "code": "; by @Krenium\n\ntable: [\n [0 3 1 7 5 9 8 6 4 2]\n [7 0 9 2 1 5 4 8 6 3]\n [4 2 0 6 8 7 1 3 5 9]\n [1 7 5 0 9 8 3 4 2 6]\n [6 1 2 3 0 4 5 9 7 8]\n [3 6 7 4 2 0 9 5 8 1]\n [5 8 6 9 7 2 0 1 3 4]\n [8 9 4 5 3 6 2 0 1 7]\n [9 4 3 8 6 1 7 2 0 5]\n [2 5 8 1 4 3 6 7 9 0]\n]\n\ndamm?: function [z][zero? fold digits to :integer z .seed: 0 [x y]-> table\\[x]\\[y] ]\n\n; Or, being more explicit:\ndigits2: function [str][\n chars: split str\n result: map chars 'ch -> to :integer ch\n return result\n]\n\ndamm2?: function [str][\n d: digits2 str\n r: fold d .seed: 0 [x y] -> get get table x y\n return r = 0\n]\n\ntest: function [str][\n result: switch damm? str -> \"valid\"\n -> \"invalid\"\n print [str \"is\" result]\n]\n\nloop [\"5724\" \"5727\" \"112946\" \"112949\"] => test\n", "language": "Arturo" }, { "code": "Damm(num){\n\trow := 1, Damm := [[0,3,1,7,5,9,8,6,4,2]\n\t\t\t ,[7,0,9,2,1,5,4,8,6,3]\n\t\t\t ,[4,2,0,6,8,7,1,3,5,9]\n\t\t\t ,[1,7,5,0,9,8,3,4,2,6]\n\t\t\t ,[6,1,2,3,0,4,5,9,7,8]\n\t\t\t ,[3,6,7,4,2,0,9,5,8,1]\n\t\t\t ,[5,8,6,9,7,2,0,1,3,4]\n\t\t\t ,[8,9,4,5,3,6,2,0,1,7]\n\t\t\t ,[9,4,3,8,6,1,7,2,0,5]\n\t\t\t ,[2,5,8,1,4,3,6,7,9,0]]\n\tfor i, v in StrSplit(SubStr(num, 1, -1)){\n\t\t++row := Damm[row, v+1]\n\t}\n\treturn (SubStr(num, 0)=row-1 && !Damm[row, row])\n}\n", "language": "AutoHotkey" }, { "code": "result := \"\"\nfor i, num in [5724, 5727, 112946, 112949]\n\tresult .= num \"`tis \" (Damm(num) ? \"valid\" : \"not valid\") \"`n\"\nMsgBox % result\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f DAMM_ALGORITHM.AWK\nBEGIN {\n damm_init()\n leng = split(\"5724,5727,112946\",arr,\",\") # test cases\n for (i=1; i<=leng; i++) {\n n = arr[i]\n printf(\"%s %s\\n\",damm_check(n),n)\n }\n exit(0)\n}\nfunction damm_check(n, a,i) {\n a = 0\n for (i=1; i<=length(n); i++) {\n a = substr(damm[a],substr(n,i,1)+1,1)\n }\n return(a == 0 ? \"T\" : \"F\")\n}\nfunction damm_init() {\n# 0123456789\n damm[0] = \"0317598642\"\n damm[1] = \"7092154863\"\n damm[2] = \"4206871359\"\n damm[3] = \"1750983426\"\n damm[4] = \"6123045978\"\n damm[5] = \"3674209581\"\n damm[6] = \"5869720134\"\n damm[7] = \"8945362017\"\n damm[8] = \"9438617205\"\n damm[9] = \"2581436790\"\n}\n", "language": "AWK" }, { "code": "10 DEFINT D,I,X,Y: DIM DT(9,9)\n20 FOR Y=0 TO 9: FOR X=0 TO 9: READ DT(X,Y): NEXT X,Y\n30 INPUT N$: IF N$=\"\" THEN END\n40 D=0\n50 FOR I=1 TO LEN(N$): D=DT(VAL(MID$(N$,I,1)),D): NEXT I\n60 IF D THEN PRINT \"FAIL\" ELSE PRINT \"PASS\"\n70 GOTO 30\n100 DATA 0,3,1,7,5,9,8,6,4,2\n110 DATA 7,0,9,2,1,5,4,8,6,3\n120 DATA 4,2,0,6,8,7,1,3,5,9\n130 DATA 1,7,5,0,9,8,3,4,2,6\n140 DATA 6,1,2,3,0,4,5,9,7,8\n150 DATA 3,6,7,4,2,0,9,5,8,1\n160 DATA 5,8,6,9,7,2,0,1,3,4\n170 DATA 8,9,4,5,3,6,2,0,1,7\n180 DATA 9,4,3,8,6,1,7,2,0,5\n190 DATA 2,5,8,1,4,3,6,7,9,0\n", "language": "BASIC" }, { "code": "arraybase 1\nglobal matrix\nmatrix = {{0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, {8, 9, 4, 5, 3, 6, 2, 0, 1, 7}, {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}}\ntest = {5724, 5727, 112946}\n\nfor i = 1 to 3\n\tprint \"Checksum test: \"; rjust(string(test[i]),8); encode(test[i])\nnext i\nend\n\nfunction encode(n)\n\tcad = string(n)\n\tcheck = 0\n\tfor d = 1 to length(cad)\n\t\tcheck = matrix[int(mid(cad, d, 1)), d]\n\tnext d\n\tif check = 0 then\n\t\treturn \" is valid\"\n\telse\n\t\treturn \" is invalid\"\n\tend if\nend function\n", "language": "BASIC256" }, { "code": "get \"libhdr\"\n\nlet Damm(ns) = valof\n$( let dt = table\n 0,3,1,7,5,9,8,6,4,2,\n 7,0,9,2,1,5,4,8,6,3,\n 4,2,0,6,8,7,1,3,5,9,\n 1,7,5,0,9,8,3,4,2,6,\n 6,1,2,3,0,4,5,9,7,8,\n 3,6,7,4,2,0,9,5,8,1,\n 5,8,6,9,7,2,0,1,3,4,\n 8,9,4,5,3,6,2,0,1,7,\n 9,4,3,8,6,1,7,2,0,5,\n 2,5,8,1,4,3,6,7,9,0\n let idgt = 0\n for i=1 to ns%0\n test '0' <= ns%i <= '9'\n do idgt := dt!(ns%i-'0' + 10*idgt)\n or resultis false\n resultis idgt = 0\n$)\n\nlet check(ns) be\n writef(\"%S: %S*N\", ns, damm(ns) -> \"pass\", \"fail\")\n\nlet start() be\n$( check(\"5724\")\n check(\"5727\")\n check(\"112946\")\n check(\"112949\")\n$)\n", "language": "BCPL" }, { "code": "table ← >⟨ 0‿3‿1‿7‿5‿9‿8‿6‿4‿2\n 7‿0‿9‿2‿1‿5‿4‿8‿6‿3\n 4‿2‿0‿6‿8‿7‿1‿3‿5‿9\n 1‿7‿5‿0‿9‿8‿3‿4‿2‿6\n 6‿1‿2‿3‿0‿4‿5‿9‿7‿8\n 3‿6‿7‿4‿2‿0‿9‿5‿8‿1\n 5‿8‿6‿9‿7‿2‿0‿1‿3‿4\n 8‿9‿4‿5‿3‿6‿2‿0‿1‿7\n 9‿4‿3‿8‿6‿1‿7‿2‿0‿5\n 2‿5‿8‿1‿4‿3‿6‿7‿9‿0 ⟩\n\n\nDigits ← 10{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}\n\nDamm ← {0=0(table⊑˜⋈)˜´⌽Digits 𝕩}\n\nDamm¨5724‿5727‿112946\n", "language": "BQN" }, { "code": "⟨ 1 0 1 ⟩\n", "language": "BQN" }, { "code": "#include <stdbool.h>\n#include <stddef.h>\n#include <stdio.h>\n\nbool damm(unsigned char *input, size_t length) {\n static const unsigned char table[10][10] = {\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0},\n };\n\n unsigned char interim = 0;\n for (size_t i = 0; i < length; i++) {\n interim = table[interim][input[i]];\n }\n return interim == 0;\n}\n\nint main() {\n unsigned char input[4] = {5, 7, 2, 4};\n puts(damm(input, 4) ? \"Checksum correct\" : \"Checksum incorrect\");\n return 0;\n}\n", "language": "C" }, { "code": "#include <string>\n\n#include <cstdio>\n\ninline constexper int TABLE[][10] = {\n\t{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n\t{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n\t{4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n\t{1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n\t{6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n\t{3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n\t{5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n\t{8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n\t{9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n\t{2, 5, 8, 1, 4, 3, 6, 7, 9, 0},\n};\n\n[[nodiscard]] bool damm(std::string s) noexcept {\n\tint interim = 0;\n\tfor (const auto c : s) {\n\t\tinterim = TABLE[interim][c - '0'];\n\t}\n\treturn interim == 0;\n}\n\nint main() {\n\tfor (const auto num : { 5724, 5727, 112946, 112949 }) {\n\t\tif (damm(std::to_string(num))) {\n\t \t \tstd::printf(\"%6d is valid\\n\", num);\n\t\t}\t\n\t\telse std::printf(\"%6d is invalid\\n\", num);\n\t}\n}\n", "language": "C++" }, { "code": "// Compile with:\n// g++ -std=c++20 -Wall -Wextra -pedantic damm.cpp -o damm\n\n#include <iostream>\n#include <array> // for std::array\n#include <string> // for std::string, std::to_string and std::string::find\n\nconst std::array<std::array<int, 10>, 10> table = {{ // Operation table\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}\n}};\n\nbool damm(int input) {\n int interim = 0; // initialise to 0\n const std::string digit = \"0123456789\";\n for (const auto c : std::to_string(input))\n interim = table[interim][digit.find(c)];\n // Process the number digit by digit:\n // 1. The column index = number's digit\n // 2. The row index = interim digit\n // 3. Replace interim digit with table entry (table[<interim digit>][<number's digit>])\n return interim == 0; // Is interim digit equals zero? If so, the input is valid, invalid otherwise.\n}\n\nint main() {\n for (const auto num : {5724, 5727, 112946, 112949})\n std::cout << num << \"\\t\" << \"Checksum is \" << (damm(num) ? \"valid\" : \"invalid\") << std::endl;\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\n\nnamespace DammAlgorithm {\n class Program {\n static int[,] table = {\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0},\n };\n\n static bool Damm(string s) {\n int interim = 0;\n foreach (char c in s) {\n interim = table[interim, c - '0'];\n }\n return interim == 0;\n }\n\n static void Main(string[] args) {\n int[] numbers = { 5724, 5727, 112946, 112949 };\n foreach (int number in numbers) {\n bool isValid = Damm(number.ToString());\n if (isValid) {\n Console.WriteLine(\"{0,6} is valid\", number);\n }\n else {\n Console.WriteLine(\"{0,6} is invalid\", number);\n }\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(def tbl [[0 3 1 7 5 9 8 6 4 2]\n [7 0 9 2 1 5 4 8 6 3]\n [4 2 0 6 8 7 1 3 5 9]\n [1 7 5 0 9 8 3 4 2 6]\n [6 1 2 3 0 4 5 9 7 8]\n [3 6 7 4 2 0 9 5 8 1]\n [5 8 6 9 7 2 0 1 3 4]\n [8 9 4 5 3 6 2 0 1 7]\n [9 4 3 8 6 1 7 2 0 5]\n [2 5 8 1 4 3 6 7 9 0]])\n\n(defn damm? [digits]\n (= 0 (reduce #(nth (nth tbl %1) %2) 0\n (map #(Character/getNumericValue %) (seq digits)))))\n", "language": "Clojure" }, { "code": "% Verify that the Damm check digit of a string of digits is correct.\n% Signals 'bad_format' if the string contains non-digits.\ndamm = proc (s: string) returns (bool) signals (bad_format)\n ai = array[int]\n aai = array[ai]\n own damm_table: aai := aai$[0:\n ai$[0: 0,3,1,7,5,9,8,6,4,2],\n ai$[0: 7,0,9,2,1,5,4,8,6,3],\n ai$[0: 4,2,0,6,8,7,1,3,5,9],\n ai$[0: 1,7,5,0,9,8,3,4,2,6],\n ai$[0: 6,1,2,3,0,4,5,9,7,8],\n ai$[0: 3,6,7,4,2,0,9,5,8,1],\n ai$[0: 5,8,6,9,7,2,0,1,3,4],\n ai$[0: 8,9,4,5,3,6,2,0,1,7],\n ai$[0: 9,4,3,8,6,1,7,2,0,5],\n ai$[0: 2,5,8,1,4,3,6,7,9,0]\n ]\n\n interim: int := 0\n for c: char in string$chars(s) do\n d: int := int$parse(string$c2s(c)) resignal bad_format\n interim := damm_table[interim][d]\n end\n\n return(interim = 0)\nend damm\n\n% Checks\nstart_up = proc ()\n po: stream := stream$primary_output()\n tests: sequence[string] := sequence[string]$[\n \"5724\", \"5727\", \"112946\", \"112949\"\n ]\n\n for test: string in sequence[string]$elements(tests) do\n stream$puts(po, test || \": \")\n if damm(test) then\n stream$putl(po, \"pass\")\n else\n stream$putl(po, \"fail\")\n end\n end\nend start_up\n", "language": "CLU" }, { "code": "include \"cowgol.coh\";\n\n# Damm test on number given as ASCII string\n# Returns check digit\nsub damm(num: [uint8]): (chk: uint8) is\n var table: uint8[] := {\n 0,3,1,7,5,9,8,6,4,2,\n 7,0,9,2,1,5,4,8,6,3,\n 4,2,0,6,8,7,1,3,5,9,\n 1,7,5,0,9,8,3,4,2,6,\n 6,1,2,3,0,4,5,9,7,8,\n 3,6,7,4,2,0,9,5,8,1,\n 5,8,6,9,7,2,0,1,3,4,\n 8,9,4,5,3,6,2,0,1,7,\n 9,4,3,8,6,1,7,2,0,5,\n 2,5,8,1,4,3,6,7,9,0\n };\n\n chk := 0;\n while [num] != 0 loop\n chk := table[(chk<<1) + (chk<<3) + ([num] - '0')];\n num := @next num;\n end loop;\nend sub;\n\n# Test and print\nsub test(num: [uint8]) is\n print(num);\n print(\":\");\n if damm(num) == 0 then\n print(\"Pass\\n\");\n else\n print(\"Fail\\n\");\n end if;\nend sub;\n\ntest(\"5724\");\ntest(\"5727\");\ntest(\"112946\");\ntest(\"112949\");\n", "language": "Cowgol" }, { "code": "import std.stdio;\n\nauto table = [\n [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0],\n];\n\nbool damm(string s) {\n int interim = 0;\n foreach (c; s) {\n interim = table[interim][c - '0'];\n }\n return interim == 0;\n}\n\nvoid main() {\n import std.conv : to;\n auto numbers = [5724, 5727, 112946, 112949];\n foreach (number; numbers) {\n bool isValid = damm(number.to!string());\n writef(\"%6d is \", number);\n if (isValid) {\n writeln(\"valid\");\n } else {\n writeln(\"invalid\");\n }\n }\n}\n", "language": "D" }, { "code": "proc damm(*char str) bool:\n [10][10]byte dammtbl = (\n (0,3,1,7,5,9,8,6,4,2),\n (7,0,9,2,1,5,4,8,6,3),\n (4,2,0,6,8,7,1,3,5,9),\n (1,7,5,0,9,8,3,4,2,6),\n (6,1,2,3,0,4,5,9,7,8),\n (3,6,7,4,2,0,9,5,8,1),\n (5,8,6,9,7,2,0,1,3,4),\n (8,9,4,5,3,6,2,0,1,7),\n (9,4,3,8,6,1,7,2,0,5),\n (2,5,8,1,4,3,6,7,9,0)\n );\n byte interim;\n char c;\n channel input text ch;\n\n interim := 0;\n open(ch, str);\n while read(ch; c) do\n interim := dammtbl[interim][c-'0']\n od;\n close(ch);\n interim = 0\ncorp\n\nproc check(*char str) void:\n writeln(str, \": \", if damm(str) then \"pass\" else \"fail\" fi)\ncorp\n\nproc main() void:\n check(\"5724\");\n check(\"5727\");\n check(\"112946\");\n check(\"112949\");\ncorp\n", "language": "Draco" }, { "code": "let table = [\n [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0]\n]\n\nfunc damm(s) {\n var interim = 0\n for c in s {\n interim = table[interim][Integer(c)]\n }\n return interim == 0;\n}\n\nlet numbers = [5724, 5727, 112946, 112949]\nfor number in numbers {\n let isValid = damm(number.ToString())\n if isValid {\n print(\"\\(number) is valid\")\n } else {\n print(\"\\(number) is invalid\")\n }\n}\n", "language": "Dyalect" }, { "code": "func damm inp$ .\n table[][] = [ [ 0 3 1 7 5 9 8 6 4 2 ] [ 7 0 9 2 1 5 4 8 6 3 ] [ 4 2 0 6 8 7 1 3 5 9 ] [ 1 7 5 0 9 8 3 4 2 6 ] [ 6 1 2 3 0 4 5 9 7 8 ] [ 3 6 7 4 2 0 9 5 8 1 ] [ 5 8 6 9 7 2 0 1 3 4 ] [ 8 9 4 5 3 6 2 0 1 7 ] [ 9 4 3 8 6 1 7 2 0 5 ] [ 2 5 8 1 4 3 6 7 9 0 ] ]\n inp[] = number strchars inp$\n for v in inp[]\n inter = table[inter + 1][v + 1]\n .\n return if inter = 0\n.\nnums[] = [ 5724 5727 112946 112949 ]\nfor v in nums[]\n write v & \" is \"\n if damm v = 1\n print \"valid\"\n else\n print \"invalid\"\n .\n.\n", "language": "EasyLang" }, { "code": "=REDUCE(0,MID(A1,SEQUENCE(1,LEN(A1)),1),LAMBDA(i,j,INDEX({0,3,1,7,5,9,8,6,4,2;7,0,9,2,1,5,4,8,6,3;4,2,0,6,8,7,1,3,5,9;1,7,5,0,9,8,3,4,2,6;6,1,2,3,0,4,5,9,7,8;3,6,7,4,2,0,9,5,8,1;5,8,6,9,7,2,0,1,3,4;8,9,4,5,3,6,2,0,1,7;9,4,3,8,6,1,7,2,0,5;2,5,8,1,4,3,6,7,9,0},i+1,j+1)))\n", "language": "Excel" }, { "code": "=REDUCE(0,arrayformula(MID(A1,SEQUENCE(1,LEN(A1)),1)),lambda(i,j,INDEX({0,3,1,7,5,9,8,6,4,2;7,0,9,2,1,5,4,8,6,3;4,2,0,6,8,7,1,3,5,9;1,7,5,0,9,8,3,4,2,6;6,1,2,3,0,4,5,9,7,8;3,6,7,4,2,0,9,5,8,1;5,8,6,9,7,2,0,1,3,4;8,9,4,5,3,6,2,0,1,7;9,4,3,8,6,1,7,2,0,5;2,5,8,1,4,3,6,7,9,0},i+1,j+1)))\n", "language": "Excel" }, { "code": "=REDUCE(0;MID(A2;SEQUENCE(1;LEN(A2));1);lambda(i;j;INDEX({0\\3\\1\\7\\5\\9\\8\\6\\4\\2;7\\0\\9\\2\\1\\5\\4\\8\\6\\3;4\\2\\0\\6\\8\\7\\1\\3\\5\\9;1\\7\\5\\0\\9\\8\\3\\4\\2\\6;6\\1\\2\\3\\0\\4\\5\\9\\7\\8;3\\6\\7\\4\\2\\0\\9\\5\\8\\1;5\\8\\6\\9\\7\\2\\0\\1\\3\\4;8\\9\\4\\5\\3\\6\\2\\0\\1\\7;9\\4\\3\\8\\6\\1\\7\\2\\0\\5;2\\5\\8\\1\\4\\3\\6\\7\\9\\0};i+1;j+1)))\n", "language": "Excel" }, { "code": "open System\n\nlet TABLE = [|\n [|0; 3; 1; 7; 5; 9; 8; 6; 4; 2|];\n [|7; 0; 9; 2; 1; 5; 4; 8; 6; 3|];\n [|4; 2; 0; 6; 8; 7; 1; 3; 5; 9|];\n [|1; 7; 5; 0; 9; 8; 3; 4; 2; 6|];\n [|6; 1; 2; 3; 0; 4; 5; 9; 7; 8|];\n [|3; 6; 7; 4; 2; 0; 9; 5; 8; 1|];\n [|5; 8; 6; 9; 7; 2; 0; 1; 3; 4|];\n [|8; 9; 4; 5; 3; 6; 2; 0; 1; 7|];\n [|9; 4; 3; 8; 6; 1; 7; 2; 0; 5|];\n [|2; 5; 8; 1; 4; 3; 6; 7; 9; 0|];\n|]\n\nlet damm str =\n let rec helper (v:string) interim =\n if v.Length = 0 then 0 = interim\n else helper (v.Substring(1)) (TABLE.[interim].[(int (v.[0])) - (int '0')])\n helper str 0\n\n[<EntryPoint>]\nlet main _ =\n let numbers = [|5724; 5727; 112946; 112949|]\n for number in numbers do\n let isValid = damm (number.ToString())\n if isValid then\n printfn \"%6d is valid\" number\n else\n printfn \"%6d is invalid\" number\n\n 0 // return an integer exit code\n", "language": "F-Sharp" }, { "code": "USING: interpolate kernel math math.parser qw sequences ;\n\nCONSTANT: table\n{\n { 0 3 1 7 5 9 8 6 4 2 }\n { 7 0 9 2 1 5 4 8 6 3 }\n { 4 2 0 6 8 7 1 3 5 9 }\n { 1 7 5 0 9 8 3 4 2 6 }\n { 6 1 2 3 0 4 5 9 7 8 }\n { 3 6 7 4 2 0 9 5 8 1 }\n { 5 8 6 9 7 2 0 1 3 4 }\n { 8 9 4 5 3 6 2 0 1 7 }\n { 9 4 3 8 6 1 7 2 0 5 }\n { 2 5 8 1 4 3 6 7 9 0 }\n}\n\n: damm? ( str -- ? )\n 0 [ digit> swap table nth nth ] reduce zero? ;\n\nqw{ 5724 5727 112946 112949 }\n[ dup damm? \"\" \"in\" ? [I ${} is ${}validI] nl ] each\n", "language": "Factor" }, { "code": ": newdigit ( col row -- u ) 10 * + C\" 0317598642709215486342068713591750983426612304597836742095815869720134894536201794386172052581436790\" 1+ + c@ 48 - ;\n: nextdigit ( addr -- addr+1 u ) dup c@ 48 - swap 1+ swap ;\n\n: damm ( c u -- u )\n0 rot rot\n0 do\n nextdigit\n rot newdigit swap\nloop drop\n;\n\n: isdamm? damm 0= if .\" yes\" else .\" no\" then ;\n\n: .damm\n2dup damm\nrot rot type 48 + emit\n;\n", "language": "Forth" }, { "code": " LOGICAL FUNCTION DAMM(DIGIT)\t!Check that a sequence of digits checks out..\nCalculates according to the method of H. Michael Damm, described in 2004.\n CHARACTER*(*) DIGIT\t\t!A sequence of digits only.\n INTEGER*1 OPTABLE(0:9,0:9)\t!The special \"Operation table\" of the method.\n PARAMETER (OPTABLE = (/\t\t!A set of constants...\n o 0, 3, 1, 7, 5, 9, 8, 6, 4, 2,\t! CAREFUL!\n 1 7, 0, 9, 2, 1, 5, 4, 8, 6, 3,\t!Fortran stores arrays in column-major order.\n 2 4, 2, 0, 6, 8, 7, 1, 3, 5, 9,\t!Despite the manifest row and column layout apparent here\n 3 1, 7, 5, 0, 9, 8, 3, 4, 2, 6,\t!This sequence of consecutive items will go into storage order.\n 4 6, 1, 2, 3, 0, 4, 5, 9, 7, 8,\t!The table resulting from this sequence of constants\n 5 3, 6, 7, 4, 2, 0, 9, 5, 8, 1,\t!Will appear to be transposed if referenced as (row,column)\n 6 5, 8, 6, 9, 7, 2, 0, 1, 3, 4,\t!What appears to be row=6 column=1 (counting from zero)\n 7 8, 9, 4, 5, 3, 6, 2, 0, 1, 7,\t!is to be accessed as OPTABLE(1,6) = 8, not OPTABLE(6,1)\n 8 9, 4, 3, 8, 6, 1, 7, 2, 0, 5,\t!Storage order is (0,0), (1,0), (2,0), ... (9,0)\n 9 2, 5, 8, 1, 4, 3, 6, 7, 9, 0/))\t!Followed by (0,1), (1,1), (2,1), ... (9,1)\n INTEGER I,D,ID\t!Assistants.\n ID = 0\t\t!Here we go.\n DO I = 1,LEN(DIGIT)\t!Step through the text.\n D = ICHAR(DIGIT(I:I)) - ICHAR(\"0\")\t!Convert to an integer. (ASCII or EBCDIC)\n IF (D.LT.0 .OR. D.GT.9) STOP \"DAMM! Not a digit!\"\t!This shouldn't happen!\n ID = OPTABLE(D,ID)\t\t!Transposed: D is the column index and ID the row.\n END DO\t\t\t!On to the next.\n DAMM = ID .EQ. 0\t!Somewhere, a check digit should ensure this.\n END FUNCTION DAMM\t!Simple, fast, and alas, rarely used.\n\n LOGICAL DAMM\t!Not a default type.\n\n WRITE (6,*) DAMM(\"5724\"),\"5724\"\n WRITE (6,*) DAMM(\"5727\"),\"5727\"\n WRITE (6,*) DAMM(\"112946\"),\"112946\"\n\n END\n", "language": "Fortran" }, { "code": "' version 04-07-2018\n' compile with: fbc -s console\n\nFunction Damm(digit_str As String) As UInteger\n\n Dim As UInteger table(10,10) => { { 0, 3, 1, 7, 5, 9, 8, 6, 4, 2 } , _\n { 7, 0, 9, 2, 1, 5, 4, 8, 6, 3 } , { 4, 2, 0, 6, 8, 7, 1, 3, 5, 9 } , _\n { 1, 7, 5, 0, 9, 8, 3, 4, 2, 6 } , { 6, 1, 2, 3, 0, 4, 5, 9, 7, 8 } , _\n { 3, 6, 7, 4, 2, 0, 9, 5, 8, 1 } , { 5, 8, 6, 9, 7, 2, 0, 1, 3, 4 } , _\n { 8, 9, 4, 5, 3, 6, 2, 0, 1, 7 } , { 9, 4, 3, 8, 6, 1, 7, 2, 0, 5 } , _\n { 2, 5, 8, 1, 4, 3, 6, 7, 9, 0 } }\n\n Dim As UInteger i, col_i, old_row_i, new_row_i\n\n For i = 0 To Len(digit_str) -1\n col_i = digit_str[i] - Asc(\"0\")\n new_row_i = table(old_row_i, col_i)\n old_row_i = new_row_i\n Next\n\n Return new_row_i\n\nEnd Function\n\n' ------=< MAIN >=------\n\nData \"5724\", \"5727\", \"112946\", \"\"\n\nDim As UInteger checksum, t\nDim As String test_string\n\nDo\n\n Read test_string\n If test_string = \"\" Then Exit Do\n Print \"Checksum test: \";test_string;\n\n checksum = Damm(test_string)\n If checksum = 0 Then\n Print \" is valid\"\n Else\n Print \" is invalid\"\n End If\n\nLoop\n\n' empty keyboard buffer\nWhile Inkey <> \"\" : Wend\nPrint : Print \"hit any key to end program\"\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport \"fmt\"\n\nvar table = [10][10]byte{\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0},\n}\n\nfunc damm(input string) bool {\n var interim byte\n for _, c := range []byte(input) {\n interim = table[interim][c-'0']\n }\n return interim == 0\n}\n\nfunc main() {\n for _, s := range []string{\"5724\", \"5727\", \"112946\", \"112949\"} {\n fmt.Printf(\"%6s %t\\n\", s, damm(s))\n }\n}\n", "language": "Go" }, { "code": "class DammAlgorithm {\n private static final int[][] TABLE = [\n [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0],\n ]\n\n private static boolean damm(String s) {\n int interim = 0\n for (char c : s.toCharArray()) interim = TABLE[interim][c - ('0' as Character)]\n return interim == 0\n }\n\n static void main(String[] args) {\n int[] numbers = [5724, 5727, 112946, 112949]\n for (Integer number : numbers) {\n boolean isValid = damm(number.toString())\n if (isValid) {\n System.out.printf(\"%6d is valid\\n\", number)\n } else {\n System.out.printf(\"%6d is invalid\\n\", number)\n }\n }\n }\n}\n", "language": "Groovy" }, { "code": "import Data.Char (digitToInt)\nimport Text.Printf (printf)\n\ndamm :: String -> Bool\ndamm = (==0) . foldl (\\r -> (table !! r !!) . digitToInt) 0\n where\n table =\n [ [0, 3, 1, 7, 5, 9, 8, 6, 4, 2]\n , [7, 0, 9, 2, 1, 5, 4, 8, 6, 3]\n , [4, 2, 0, 6, 8, 7, 1, 3, 5, 9]\n , [1, 7, 5, 0, 9, 8, 3, 4, 2, 6]\n , [6, 1, 2, 3, 0, 4, 5, 9, 7, 8]\n , [3, 6, 7, 4, 2, 0, 9, 5, 8, 1]\n , [5, 8, 6, 9, 7, 2, 0, 1, 3, 4]\n , [8, 9, 4, 5, 3, 6, 2, 0, 1, 7]\n , [9, 4, 3, 8, 6, 1, 7, 2, 0, 5]\n , [2, 5, 8, 1, 4, 3, 6, 7, 9, 0] ]\n\nmain :: IO ()\nmain = mapM_ (uncurry(printf \"%6s is valid: %s\\n\") . ((,) <*> show . damm) . show)\n [5724, 5727, 112946, 112949]\n", "language": "Haskell" }, { "code": "OpTbl=: _99 \". ];._2 noun define\n0 3 1 7 5 9 8 6 4 2\n7 0 9 2 1 5 4 8 6 3\n4 2 0 6 8 7 1 3 5 9\n1 7 5 0 9 8 3 4 2 6\n6 1 2 3 0 4 5 9 7 8\n3 6 7 4 2 0 9 5 8 1\n5 8 6 9 7 2 0 1 3 4\n8 9 4 5 3 6 2 0 1 7\n9 4 3 8 6 1 7 2 0 5\n2 5 8 1 4 3 6 7 9 0\n)\n\ngetdigits=: 10&#.inv\n\ngetDamm=: verb define\n row=. 0\n for_digit. getdigits y do.\n row=. OpTbl {~ <row,digit\n end.\n)\n\ncheckDamm=: 0 = getDamm\n", "language": "J" }, { "code": " checkDamm&> 5724 5727 112946\n1 0 1\n", "language": "J" }, { "code": "checkdamm=: {{0=((\".;._2{{)n\n0 7 4 1 6 3 5 8 9 2\n3 0 2 7 1 6 8 9 4 5\n1 9 0 5 2 7 6 4 3 8\n7 2 6 0 3 4 9 5 8 1\n5 1 8 9 0 2 7 3 6 4\n9 5 7 8 4 0 2 6 1 3\n8 4 1 3 5 9 0 2 7 6\n6 8 3 4 9 5 1 0 2 7\n4 6 5 2 7 8 3 1 0 9\n2 3 9 6 8 1 4 7 5 0\n}}){~<@,)/|.0,10#.inv y}}\"0\n", "language": "J" }, { "code": " checkdamm 5724 5727 112946\n1 0 1\n", "language": "J" }, { "code": "public class DammAlgorithm {\n private static final int[][] table = {\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0},\n };\n\n private static boolean damm(String s) {\n int interim = 0;\n for (char c : s.toCharArray()) interim = table[interim][c - '0'];\n return interim == 0;\n }\n\n public static void main(String[] args) {\n int[] numbers = {5724, 5727, 112946, 112949};\n for (Integer number : numbers) {\n boolean isValid = damm(number.toString());\n if (isValid) {\n System.out.printf(\"%6d is valid\\n\", number);\n } else {\n System.out.printf(\"%6d is invalid\\n\", number);\n }\n }\n }\n}\n", "language": "Java" }, { "code": "const table = [\n [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0],\n ];\n\nconst lookup = (p, c) => table[p][parseInt(c, 10)]\nconst damm = input => [...input].reduce(lookup, 0) === 0;\n\n// ----------------------------------------------------------[ Tests ]----\nconst test = () => [\"5724\", \"5727\", \"112946\", \"112949\"].forEach(e =>\n console.log(`${e} => ${damm(e) ? 'Pass' : 'Fail'}`)\n);\ntest();\n", "language": "JavaScript" }, { "code": "def checkdigit:\n [[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0]]\n as $m\n | tostring | explode\n # \"0\" is 48\n | 0 == reduce (.[] - 48) as $d (0; $m[.][$d] );\n\t\n# The task:\n5724, 5727, 112946, 112949\n| checkdigit as $d\n| [., $d]\n", "language": "Jq" }, { "code": "[5724,true]\n[5727,false]\n[112946,true]\n[112949,false]\n", "language": "Jq" }, { "code": "function checkdigit(n)\n matrix = (\n (0, 3, 1, 7, 5, 9, 8, 6, 4, 2),\n (7, 0, 9, 2, 1, 5, 4, 8, 6, 3),\n (4, 2, 0, 6, 8, 7, 1, 3, 5, 9),\n (1, 7, 5, 0, 9, 8, 3, 4, 2, 6),\n (6, 1, 2, 3, 0, 4, 5, 9, 7, 8),\n (3, 6, 7, 4, 2, 0, 9, 5, 8, 1),\n (5, 8, 6, 9, 7, 2, 0, 1, 3, 4),\n (8, 9, 4, 5, 3, 6, 2, 0, 1, 7),\n (9, 4, 3, 8, 6, 1, 7, 2, 0, 5),\n (2, 5, 8, 1, 4, 3, 6, 7, 9, 0))\n row = 0\n for d in string(n)\n row = matrix[row + 1][d - '0' + 1]\n end\n return row\nend\n\nforeach(i -> println(\"$i validates as: \", checkdigit(string(i)) == 0), [5724, 5727, 112946])\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nval table = arrayOf(\n intArrayOf(0, 3, 1,\t7, 5, 9, 8, 6, 4, 2),\n intArrayOf(7, 0, 9, 2, 1, 5, 4, 8, 6, 3),\n intArrayOf(4, 2, 0, 6, 8, 7, 1, 3, 5, 9),\n intArrayOf(1, 7, 5, 0, 9, 8, 3, 4, 2, 6),\n intArrayOf(6, 1, 2, 3, 0, 4, 5, 9, 7, 8),\n intArrayOf(3, 6, 7, 4, 2, 0, 9, 5, 8, 1),\n intArrayOf(5, 8, 6, 9, 7, 2, 0, 1, 3, 4),\n intArrayOf(8, 9, 4, 5, 3, 6, 2, 0, 1, 7),\n intArrayOf(9, 4, 3, 8, 6, 1, 7, 2, 0, 5),\n intArrayOf(2, 5, 8, 1, 4, 3, 6, 7, 9, 0)\n)\n\nfun damm(s: String): Boolean {\n var interim = 0\n for (c in s) interim = table[interim][c - '0']\n return interim == 0\n}\n\nfun main(args: Array<String>) {\n val numbers = intArrayOf(5724, 5727, 112946, 112949)\n for (number in numbers) {\n val isValid = damm(number.toString())\n println(\"${\"%6d\".format(number)} is ${if (isValid) \"valid\" else \"invalid\"}\")\n }\n}\n", "language": "Kotlin" }, { "code": "Dim DT(9, 9)\n\nFor y = 0 To 9\n For x = 0 To 9\n Read val\n DT(x, y) = val\n Next x\nNext y\n\nInput check$\nWhile (check$ <> \"\")\n D = 0\n For i = 1 To Len(check$)\n D = DT(Val(Mid$(check$, i, 1)), D)\n Next i\n If D Then\n Print \"Invalid\"\n Else\n Print \"Valid\"\n End If\n Input check$\nWend\nEnd\n\nDATA 0,3,1,7,5,9,8,6,4,2\nDATA 7,0,9,2,1,5,4,8,6,3\nDATA 4,2,0,6,8,7,1,3,5,9\nDATA 1,7,5,0,9,8,3,4,2,6\nDATA 6,1,2,3,0,4,5,9,7,8\nDATA 3,6,7,4,2,0,9,5,8,1\nDATA 5,8,6,9,7,2,0,1,3,4\nDATA 8,9,4,5,3,6,2,0,1,7\nDATA 9,4,3,8,6,1,7,2,0,5\nDATA 2,5,8,1,4,3,6,7,9,0\n", "language": "Liberty-BASIC" }, { "code": "local tab = {\n {0,3,1,7,5,9,8,6,4,2}, {7,0,9,2,1,5,4,8,6,3},\n {4,2,0,6,8,7,1,3,5,9}, {1,7,5,0,9,8,3,4,2,6},\n {6,1,2,3,0,4,5,9,7,8}, {3,6,7,4,2,0,9,5,8,1},\n {5,8,6,9,7,2,0,1,3,4}, {8,9,4,5,3,6,2,0,1,7},\n {9,4,3,8,6,1,7,2,0,5}, {2,5,8,1,4,3,6,7,9,0}\n}\nfunction check( n )\n local idx, a = 0, tonumber( n:sub( 1, 1 ) )\n for i = 1, #n do\n a = tonumber( n:sub( i, i ) )\n if a == nil then return false end\n idx = tab[idx + 1][a + 1]\n end\n return idx == 0\nend\nlocal n, r\nwhile( true ) do\n io.write( \"Enter the number to check: \" )\n n = io.read(); if n == \"0\" then break end\n r = check( n ); io.write( n, \" is \" )\n if not r then io.write( \"in\" ) end\n io.write( \"valid!\\n\" )\nend\n", "language": "Lua" }, { "code": "Module Damm_Algorithm{\n\tFunction Prepare {\n\t\tfunction OperationTable {\n\t\t\tdata (0, 3, 1, 7, 5, 9, 8, 6, 4, 2)\n\t\t\tdata (7, 0, 9, 2, 1, 5, 4, 8, 6, 3)\n\t\t\tdata (4, 2, 0, 6, 8, 7, 1, 3, 5, 9)\n\t\t\tdata (1, 7, 5, 0, 9, 8, 3, 4, 2, 6)\n\t\t\tdata (6, 1, 2, 3, 0, 4, 5, 9, 7, 8)\n\t\t\tdata (3, 6, 7, 4, 2, 0, 9, 5, 8, 1)\n\t\t\tdata (5, 8, 6, 9, 7, 2, 0, 1, 3, 4)\n\t\t\tdata (8, 9, 4, 5, 3, 6, 2, 0, 1, 7)\n\t\t\tdata (9, 4, 3, 8, 6, 1, 7, 2, 0, 5)\n\t\t\tdata (2, 5, 8, 1, 4, 3, 6, 7, 9, 0)\n\t\t\t=array([])\n\t\t}\n\t\tDigits= Lambda (d) ->{\n\t\t\td$=str$(d,\"\")\n\t\t\tfor i=1 to len(d$)\n\t\t\t\tdata val(mid$(d$,i,1))\n\t\t\tnext\n\t\t\t=Array([])\n\t\t}\n\t\t=Lambda a()=OperationTable(), Digits (N) -> {\n\t\t\tdim b()\n\t\t\tb()=Digits(N)\n\t\t\tm=0\n\t\t\tfor i=0 to len(b())-1\n\t\t\t\tm=a(m)(b(i))\n\t\t\tnext i\n\t\t\t=m\n\t\t}\n\t}\n\tDamm=Prepare()\n\tData 5724, 5727, 112946, 112940\n\twhile not empty\n\t\tover ' double the top of stack\n\t\tover\n\t\tPrint number, Damm(number), Damm(number)=0\n\tEnd While\n}\nDamm_Algorithm\n", "language": "M2000-Interpreter" }, { "code": " .TITLE DAMMAL\n .MCALL .GTLIN,.PRINT,.EXIT\nDAMMAL::JMP DEMO\n\n ; VALIDATE DAMM STRING IN R0; ZERO FLAG SET IF VALID\nDAMM: CLR R2 ; INTERIM DIGIT\n BR 2$\n1$: SUB #60,R1 ; DIGIT?\n BCS 3$ ; IF NOT, NOT VALID\n CMP R1,#^D9\n BGT 3$\n MOV R2,R3 ; CALCULATE DAMM TABLE INDEX\n ASL R3\n ASL R3\n ADD R2,R3\n ASL R3\n ADD R1,R3\n MOVB 4$(R3),R2 ; GET NEW INTERIM DIGIT FROM TABLE\n2$: MOVB (R0)+,R1 ; NEXT CHAR\n BNE 1$ ; END OF STRING?\n TST R2 ; IF SO, CHECK IF INTERIM DIGIT IS 0\n3$: RTS PC\n4$: .BYTE ^D0,^D3,^D1,^D7,^D5,^D9,^D8,^D6,^D4,^D2\n .BYTE ^D7,^D0,^D9,^D2,^D1,^D5,^D4,^D8,^D6,^D3\n .BYTE ^D4,^D2,^D0,^D6,^D8,^D7,^D1,^D3,^D5,^D9\n .BYTE ^D1,^D7,^D5,^D0,^D9,^D8,^D3,^D4,^D2,^D6\n .BYTE ^D6,^D1,^D2,^D3,^D0,^D4,^D5,^D9,^D7,^D8\n .BYTE ^D3,^D6,^D7,^D4,^D2,^D0,^D9,^D5,^D8,^D1\n .BYTE ^D5,^D8,^D6,^D9,^D7,^D2,^D0,^D1,^D3,^D4\n .BYTE ^D8,^D9,^D4,^D5,^D3,^D6,^D2,^D0,^D1,^D7\n .BYTE ^D9,^D4,^D4,^D8,^D6,^D1,^D7,^D2,^D0,^D5\n .BYTE ^D2,^D5,^D8,^D1,^D4,^D3,^D6,^D7,^D9,^D0\n\nDEMO: .GTLIN #5$ ; READ LINE\n MOV #5$,R0\n TSTB (R0) ; EMPTY LINE?\n BNE 1$\n .EXIT ; IF SO, STOP\n1$: JSR PC,DAMM ; TEST LINE\n BNE 2$ ; FAIL?\n .PRINT #3$\n BR DEMO\n2$: .PRINT #4$ ; PASS?\n BR DEMO\n3$: .ASCIZ /PASS/\n4$: .ASCIZ /FAIL/\n5$: .BLKB 200\n .END DAMMAL\n", "language": "MACRO-11" }, { "code": " NORMAL MODE IS INTEGER\n\n R VERIFY DAMM CHECKSUM OF NUMBER\n INTERNAL FUNCTION(CKNUM)\n VECTOR VALUES DAMMIT =\n 0 0,3,1,7,5,9,8,6,4,2\n 1 , 7,0,9,2,1,5,4,8,6,3\n 2 , 4,2,0,6,8,7,1,3,5,9\n 3 , 1,7,5,0,9,8,3,4,2,6\n 4 , 6,1,2,3,0,4,5,9,7,8\n 5 , 3,6,7,4,2,0,9,5,8,1\n 6 , 5,8,6,9,7,2,0,1,3,4\n 7 , 8,9,4,5,3,6,2,0,1,7\n 8 , 9,4,3,8,6,1,7,2,0,5\n 9 , 2,5,8,1,4,3,6,7,9,0\n DIMENSION DAMDGT(10)\n ENTRY TO DAMM.\n TMP=CKNUM\n THROUGH GETDGT, FOR NDGT=0, 1, TMP.E.0\n DAMDGT(NDGT) = TMP-TMP/10*10\nGETDGT TMP = TMP/10\n INTRM = 0\n THROUGH CKDGT, FOR NDGT=NDGT, -1, NDGT.L.0\nCKDGT INTRM = DAMMIT(INTRM*10 + DAMDGT(NDGT))\n FUNCTION RETURN INTRM.E.0\n END OF FUNCTION\n\n R TEST SOME NUMBERS\n THROUGH TEST, FOR VALUES OF N = 5724,5727,112946,112949\n WHENEVER DAMM.(N)\n PRINT FORMAT VALID,N\n OTHERWISE\n PRINT FORMAT INVAL,N\nTEST END OF CONDITIONAL\n\n VECTOR VALUES VALID = $I9,S1,5HVALID*$\n VECTOR VALUES INVAL = $I9,S1,7HINVALID*$\n END OF PROGRAM\n", "language": "MAD" }, { "code": "matrix = {{0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, {7, 0, 9, 2, 1, 5, 4, 8, 6,\n 3}, {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, {1, 7, 5, 0, 9, 8, 3, 4, 2,\n 6}, {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, {3, 6, 7, 4, 2, 0, 9, 5, 8,\n 1}, {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, {8, 9, 4, 5, 3, 6, 2, 0, 1,\n 7}, {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, {2, 5, 8, 1, 4, 3, 6, 7, 9,\n 0}};\nDamm[num_Integer] := Module[{row},\n row = 0;\n Do[\n row = matrix[[row + 1, d + 1]]\n ,\n {d, IntegerDigits[num]}\n ];\n row == 0\n ]\nDamm /@ {5724, 5727, 112946}\n", "language": "Mathematica" }, { "code": "clear all;close all;clc;\n\n% Test the function with the provided numbers\nnumbers = [5724, 5727, 112946];\nfor i = 1:length(numbers)\n if checkdigit(numbers(i))\n fprintf('%d validates as: true\\n', numbers(i));\n else\n fprintf('%d validates as: false\\n', numbers(i));\n end\nend\n\nfunction isValid = checkdigit(n)\n matrix = [\n 0, 3, 1, 7, 5, 9, 8, 6, 4, 2;\n 7, 0, 9, 2, 1, 5, 4, 8, 6, 3;\n 4, 2, 0, 6, 8, 7, 1, 3, 5, 9;\n 1, 7, 5, 0, 9, 8, 3, 4, 2, 6;\n 6, 1, 2, 3, 0, 4, 5, 9, 7, 8;\n 3, 6, 7, 4, 2, 0, 9, 5, 8, 1;\n 5, 8, 6, 9, 7, 2, 0, 1, 3, 4;\n 8, 9, 4, 5, 3, 6, 2, 0, 1, 7;\n 9, 4, 3, 8, 6, 1, 7, 2, 0, 5;\n 2, 5, 8, 1, 4, 3, 6, 7, 9, 0\n ];\n\n row = 0;\n nString = num2str(n);\n for i = 1:length(nString)\n d = str2double(nString(i));\n row = matrix(row+1, d + 1);\n end\n isValid = (row == 0);\nend\n", "language": "MATLAB" }, { "code": "MODULE DammAlgorithm;\nFROM FormatString IMPORT FormatString;\nFROM Terminal IMPORT WriteString,WriteLn,ReadChar;\n\nTYPE TA = ARRAY[0..9],[0..9] OF INTEGER;\nCONST table = TA{\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}\n };\n\nPROCEDURE Damm(s : ARRAY OF CHAR) : BOOLEAN;\nVAR interim,i : INTEGER;\nBEGIN\n interim := 0;\n\n i := 0;\n WHILE s[i] # 0C DO\n interim := table[interim,INT(s[i])-INT('0')];\n INC(i);\n END;\n RETURN interim=0;\nEND Damm;\n\nPROCEDURE Print(number : INTEGER);\nVAR\n isValid : BOOLEAN;\n buf : ARRAY[0..16] OF CHAR;\nBEGIN\n FormatString(\"%i\", buf, number);\n isValid := Damm(buf);\n WriteString(buf);\n IF isValid THEN\n WriteString(\" is valid\");\n ELSE\n WriteString(\" is invalid\");\n END;\n WriteLn;\nEND Print;\n\nBEGIN\n Print(5724);\n Print(5727);\n Print(112946);\n Print(112949);\n\n ReadChar;\nEND DammAlgorithm.\n", "language": "Modula-2" }, { "code": "MODULE DammAlgorithm EXPORTS Main;\n\nIMPORT IO, Text;\n\nVAR\n Numbers:ARRAY[0..3] OF TEXT := ARRAY OF TEXT{\"5724\", \"5727\", \"112946\", \"112949\"};\n\nPROCEDURE Damm(READONLY Str:TEXT):BOOLEAN =\n TYPE\n TTable = ARRAY[0..9],[0..9] OF INTEGER;\n VAR\n Table := TTable\n {ARRAY OF INTEGER{0,3,1,7,5,9,8,6,4,2},\n ARRAY OF INTEGER{7,0,9,2,1,5,4,8,6,3},\n ARRAY OF INTEGER{4,2,0,6,8,7,1,3,5,9},\n ARRAY OF INTEGER{1,7,5,0,9,8,3,4,2,6},\n ARRAY OF INTEGER{6,1,2,3,0,4,5,9,7,8},\n ARRAY OF INTEGER{3,6,7,4,2,0,9,5,8,1},\n ARRAY OF INTEGER{5,8,6,9,7,2,0,1,3,4},\n ARRAY OF INTEGER{8,9,4,5,3,6,2,0,1,7},\n ARRAY OF INTEGER{9,4,3,8,6,1,7,2,0,5},\n ARRAY OF INTEGER{2,5,8,1,4,3,6,7,9,0}};\n Interim,I:INTEGER := 0;\n BEGIN\n WHILE I <= Text.Length(Str)-1 DO\n Interim := Table[Interim, ORD(Text.GetChar(Str, I)) - ORD('0')];\n INC(I);\n END;\n RETURN Interim = 0;\n END Damm;\n\nBEGIN\n FOR I := FIRST(Numbers) TO LAST(Numbers) DO\n IF Damm(Numbers[I]) THEN\n IO.Put(Numbers[I] & \" is valid\\n\");\n ELSE\n IO.Put(Numbers[I] & \" is invalid\\n\");\n END;\n END;\nEND DammAlgorithm.\n", "language": "Modula-3" }, { "code": "from algorithm import reverse\n\nconst Table = [[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0]]\n\ntype Digit = range[0..9]\n\nfunc isValid(digits: openArray[Digit]): bool =\n ## Apply Damm algorithm to check validity of a digit sequence.\n var interim = 0\n for d in digits:\n interim = Table[interim][d]\n result = interim == 0\n\nproc toDigits(n: int): seq[Digit] =\n ## Return the digits of a number.\n var n = n\n while true:\n result.add(n mod 10)\n n = n div 10\n if n == 0:\n break\n result.reverse()\n\nproc checkData(digits: openArray[Digit]) =\n ## Check if a digit sequence if valid.\n if isValid(digits):\n echo \"Sequence \", digits, \" is valid.\"\n else:\n echo \"Sequence \", digits, \" is invalid.\"\n\ncheckData(5724.toDigits)\ncheckData(5727.toDigits)\ncheckData([Digit 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 6, 7, 8, 9, 0, 1])\ncheckData([Digit 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 6, 7, 8, 9, 0, 8])\n", "language": "Nim" }, { "code": "class DammAlgorithm {\n @table : static : Int[,];\n\n function : Main(args : String[]) ~ Nil {\n @table := [\n [0, 3, 1, 7, 5, 9, 8, 6, 4, 2]\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3]\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9]\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6]\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8]\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1]\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4]\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7]\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5]\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0]];\n\n numbers := [ 5724, 5727, 112946, 112949 ];\n each (i : numbers) {\n number := numbers[i];\n isValid := Damm(number->ToString());\n if (isValid) {\n \"{$number} is valid\"->PrintLine();\n }\n else {\n \"{$number} is invalid\"->PrintLine();\n };\n };\n }\n\n function : Damm(s : String) ~ Bool {\n interim := 0;\n each (i : s) {\n interim := @table[interim, s->Get(i) - '0'];\n };\n return interim = 0;\n }\n}\n", "language": "Objeck" }, { "code": "program DammAlgorithm;\nuses\n sysutils;\n\nTYPE TA = ARRAY[0..9,0..9] OF UInt8;\nCONST table : TA =\n ((0,3,1,7,5,9,8,6,4,2),\n (7,0,9,2,1,5,4,8,6,3),\n (4,2,0,6,8,7,1,3,5,9),\n (1,7,5,0,9,8,3,4,2,6),\n (6,1,2,3,0,4,5,9,7,8),\n (3,6,7,4,2,0,9,5,8,1),\n (5,8,6,9,7,2,0,1,3,4),\n (8,9,4,5,3,6,2,0,1,7),\n (9,4,3,8,6,1,7,2,0,5),\n (2,5,8,1,4,3,6,7,9,0));\n\nfunction Damm(s : string) : BOOLEAN;\nVAR\n interim,i : UInt8;\nBEGIN\n interim := 0;\n i := 1;\n WHILE i <= length(s) DO\n Begin\n interim := table[interim,ORD(s[i])-ORD('0')];\n INC(i);\n END;\n Damm := interim=0;\nEND;\n\nPROCEDURE Print(number : Uint32);\nVAR\n isValid : BOOLEAN;\n buf :string;\nBEGIN\n buf := IntToStr(number);\n isValid := Damm(buf);\n Write(buf);\n IF isValid THEN\n Write(' is valid')\n ELSE\n Write(' is invalid');\n WriteLn;\nEND;\n\nBEGIN\n Print(5724);\n Print(5727);\n Print(112946);\n Print(112949);\n Readln;\nEND.\n", "language": "Pascal" }, { "code": "sub damm {\n my(@digits) = split '', @_[0];\n my @tbl =([< 0 3 1 7 5 9 8 6 4 2 >],\n [< 7 0 9 2 1 5 4 8 6 3 >],\n [< 4 2 0 6 8 7 1 3 5 9 >],\n [< 1 7 5 0 9 8 3 4 2 6 >],\n [< 6 1 2 3 0 4 5 9 7 8 >],\n [< 3 6 7 4 2 0 9 5 8 1 >],\n [< 5 8 6 9 7 2 0 1 3 4 >],\n [< 8 9 4 5 3 6 2 0 1 7 >],\n [< 9 4 3 8 6 1 7 2 0 5 >],\n [< 2 5 8 1 4 3 6 7 9 0 >]\n );\n my $row = 0;\n for my $col (@digits) { $row = $tbl[$row][$col] }\n not $row\n}\n\nfor (5724, 5727, 112946) {\n print \"$_:\\tChecksum digit @{[damm($_) ? '' : 'in']}correct.\\n\"\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tbl</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}})</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">damm</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">interim</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">nxt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]-</span><span style=\"color: #008000;\">'0'</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">nxt</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">nxt</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">interim</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tbl</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">interim</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">nxt</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">interim</span> <span style=\"color: #0000FF;\">==</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"5724\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"5727\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"112946\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"112949\"</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">ti</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%7s is %svalid\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">damm</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">)?</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"in\"</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\nfunction lookup($r,$c) {\n $table = array(\n array(0, 3, 1, 7, 5, 9, 8, 6, 4, 2),\n array(7, 0, 9, 2, 1, 5, 4, 8, 6, 3),\n array(4, 2, 0, 6, 8, 7, 1, 3, 5, 9),\n array(1, 7, 5, 0, 9, 8, 3, 4, 2, 6),\n array(6, 1, 2, 3, 0, 4, 5, 9, 7, 8),\n array(3, 6, 7, 4, 2, 0, 9, 5, 8, 1),\n array(5, 8, 6, 9, 7, 2, 0, 1, 3, 4),\n array(8, 9, 4, 5, 3, 6, 2, 0, 1, 7),\n array(9, 4, 3, 8, 6, 1, 7, 2, 0, 5),\n array(2, 5, 8, 1, 4, 3, 6, 7, 9, 0),\n );\n return $table[$r][$c];\n}\n\nfunction isDammValid($input) {\n return array_reduce(str_split($input), \"lookup\", 0) == 0;\n}\n\nforeach(array(\"5724\", \"5727\", \"112946\", \"112949\") as $i) {\n echo \"{$i} is \".(isDammValid($i) ? \"valid\" : \"invalid\").\"<br>\";\n}\n?>\n", "language": "PHP" }, { "code": "(setq *D\n (quote\n (0 3 1 7 5 9 8 6 4 2)\n (7 0 9 2 1 5 4 8 6 3)\n (4 2 0 6 8 7 1 3 5 9)\n (1 7 5 0 9 8 3 4 2 6)\n (6 1 2 3 0 4 5 9 7 8)\n (3 6 7 4 2 0 9 5 8 1)\n (5 8 6 9 7 2 0 1 3 4)\n (8 9 4 5 3 6 2 0 1 7)\n (9 4 3 8 6 1 7 2 0 5)\n (2 5 8 1 4 3 6 7 9 0) ) )\n(de damm? (N)\n (let R 1\n (for N (mapcar format (chop N))\n (setq R (inc (get *D R (inc N)))) )\n (= 1 R) ) )\n(println (damm? 5724))\n(println (damm? 5727))\n(println (damm? 112946))\n(println (damm? 112940))\n", "language": "PicoLisp" }, { "code": "100H:\n\n/* DAMM CHECKSUM FOR DECIMAL NUMBER IN GIVEN STRING */\nCHECK$DAMM: PROCEDURE (PTR) BYTE;\n DECLARE PTR ADDRESS, CH BASED PTR BYTE;\n DECLARE DAMM DATA\n ( 0,3,1,7,5,9,8,6,4,2,\n 7,0,9,2,1,5,4,8,6,3,\n 4,2,0,6,8,7,1,3,5,9,\n 1,7,5,0,9,8,3,4,2,6,\n 6,1,2,3,0,4,5,9,7,8,\n 3,6,7,4,2,0,9,5,8,1,\n 5,8,6,9,7,2,0,1,3,4,\n 8,9,4,5,3,6,2,0,1,7,\n 9,4,3,8,6,1,7,2,0,5,\n 2,5,8,1,4,3,6,7,9,0 );\n DECLARE I BYTE;\n I = 0;\n DO WHILE CH <> '$';\n I = DAMM((I*10) + (CH-'0'));\n PTR = PTR + 1;\n END;\n RETURN I = 0;\nEND CHECK$DAMM;\n\n/* CP/M BDOS CALLS */\nBDOS: PROCEDURE (FN, ARG);\n DECLARE FN BYTE, ARG ADDRESS;\n GO TO 5;\nEND BDOS;\n\nPRINT: PROCEDURE (STR);\n DECLARE STR ADDRESS;\n CALL BDOS(9, STR);\nEND PRINT;\n\n/* TESTS */\nDECLARE TEST (4) ADDRESS;\nTEST(0) = .'5724$';\nTEST(1) = .'5727$';\nTEST(2) = .'112946$';\nTEST(3) = .'112949$';\n\nDECLARE N BYTE;\nDO N = 0 TO LAST(TEST);\n CALL PRINT(TEST(N));\n CALL PRINT(.': $');\n IF CHECK$DAMM(TEST(N)) THEN\n CALL PRINT(.'PASS$');\n ELSE\n CALL PRINT(.'FAIL$');\n CALL PRINT(.(13,10,'$'));\nEND;\n\nCALL BDOS(0,0);\nEOF\n", "language": "PL-M" }, { "code": "$table = (\n (0, 3, 1, 7, 5, 9, 8, 6, 4, 2),\n (7, 0, 9, 2, 1, 5, 4, 8, 6, 3),\n (4, 2, 0, 6, 8, 7, 1, 3, 5, 9),\n (1, 7, 5, 0, 9, 8, 3, 4, 2, 6),\n (6, 1, 2, 3, 0, 4, 5, 9, 7, 8),\n (3, 6, 7, 4, 2, 0, 9, 5, 8, 1),\n (5, 8, 6, 9, 7, 2, 0, 1, 3, 4),\n (8, 9, 4, 5, 3, 6, 2, 0, 1, 7),\n (9, 4, 3, 8, 6, 1, 7, 2, 0, 5),\n (2, 5, 8, 1, 4, 3, 6, 7, 9, 0)\n)\n\nfunction Test-Damm([string]$s) {\n $interim = 0\n foreach ($c in $s.ToCharArray()) {\n $interim = $table[$interim][[int]$c - [int][char]'0']\n }\n return $interim -eq 0\n}\n\nforeach ($number in 5724, 5727, 112946, 112949) {\n $validity = if (Test-Damm $number) {'valid'} else {'invalid'}\n '{0,6} is {1}' -f $number, $validity\n}\n", "language": "PowerShell" }, { "code": "DataSection\n DT_Start:\n Data.b\t0,3,1,7,5,9,8,6,4,2\t\n\tData.b\t7,0,9,2,1,5,4,8,6,3\t\n\tData.b\t4,2,0,6,8,7,1,3,5,9\n\tData.b\t1,7,5,0,9,8,3,4,2,6\n\tData.b\t6,1,2,3,0,4,5,9,7,8\n\tData.b\t3,6,7,4,2,0,9,5,8,1\n\tData.b\t5,8,6,9,7,2,0,1,3,4\n\tData.b\t8,9,4,5,3,6,2,0,1,7\n\tData.b\t9,4,3,8,6,1,7,2,0,5\n\tData.b\t2,5,8,1,4,3,6,7,9,0 \t\nEndDataSection\n\nProcedure.i Adr(Row,Col) : ProcedureReturn ?DT_Start+Row+10*Col : EndProcedure\n\nProcedure.b CheckDamm(Value.s)\n *ipc.Character=@Value : it=0\n While *ipc\\c\n it=PeekB(Adr(*ipc\\c-'0',it)) : *ipc+SizeOf(Character)\n Wend\n ProcedureReturn Bool(it)\nEndProcedure\n\nIf OpenConsole()\n Repeat\n Print(\"Check Damm: \") : i$=Input()\n If CheckDamm(i$) : PrintN(Space(12)+\"FALSE\") : Else : PrintN(Space(12)+\"TRUE\") : EndIf\n Until i$=\"\"\nEndIf\nEnd\n", "language": "PureBasic" }, { "code": "def damm(num: int) -> bool:\n row = 0\n for digit in str(num):\n row = _matrix[row][int(digit)]\n return row == 0\n\n_matrix = (\n (0, 3, 1, 7, 5, 9, 8, 6, 4, 2),\n (7, 0, 9, 2, 1, 5, 4, 8, 6, 3),\n (4, 2, 0, 6, 8, 7, 1, 3, 5, 9),\n (1, 7, 5, 0, 9, 8, 3, 4, 2, 6),\n (6, 1, 2, 3, 0, 4, 5, 9, 7, 8),\n (3, 6, 7, 4, 2, 0, 9, 5, 8, 1),\n (5, 8, 6, 9, 7, 2, 0, 1, 3, 4),\n (8, 9, 4, 5, 3, 6, 2, 0, 1, 7),\n (9, 4, 3, 8, 6, 1, 7, 2, 0, 5),\n (2, 5, 8, 1, 4, 3, 6, 7, 9, 0)\n)\n\nif __name__ == '__main__':\n for test in [5724, 5727, 112946]:\n print(f'{test}\\t Validates as: {damm(test)}')\n", "language": "Python" }, { "code": " [ 0 swap witheach\n [ char 0 - dip\n [ table\n [ 0 3 1 7 5 9 8 6 4 2 ]\n [ 7 0 9 2 1 5 4 8 6 3 ]\n [ 4 2 0 6 8 7 1 3 5 9 ]\n [ 1 7 5 0 9 8 3 4 2 6 ]\n [ 6 1 2 3 0 4 5 9 7 8 ]\n [ 3 6 7 4 2 0 9 5 8 1 ]\n [ 5 8 6 9 7 2 0 1 3 4 ]\n [ 8 9 4 5 3 6 2 0 1 7 ]\n [ 9 4 3 8 6 1 7 2 0 5 ]\n [ 2 5 8 1 4 3 6 7 9 0 ] ]\n peek ] ] is damm ( $ --> n )\n\n [ damm 0 = ] is dammvalid ( $ --> b )\n\n [ dup echo$ say \" is \"\n dammvalid not if [ say \"not \" ]\n say \"valid.\" cr ] is validate ( & --> )\n\n $ \"5724 5725 112946 112949\"\n nest$ witheach validate\n", "language": "Quackery" }, { "code": "Damm_algo <- function(number){\n row_i = 0\n\n iterable = strsplit(toString(number), \"\")[[1]]\n\n validation_matrix =\n matrix(\n c(\n 0, 3, 1, 7, 5, 9, 8, 6, 4, 2,\n 7, 0, 9, 2, 1, 5, 4, 8, 6, 3,\n 4, 2, 0, 6, 8, 7, 1, 3, 5, 9,\n 1, 7, 5, 0, 9, 8, 3, 4, 2, 6,\n 6, 1, 2, 3, 0, 4, 5, 9, 7, 8,\n 3, 6, 7, 4, 2, 0, 9, 5, 8, 1,\n 5, 8, 6, 9, 7, 2, 0, 1, 3, 4,\n 8, 9, 4, 5, 3, 6, 2, 0, 1, 7,\n 9, 4, 3, 8, 6, 1, 7, 2, 0, 5,\n 2, 5, 8, 1, 4, 3, 6, 7, 9, 0),\n nrow = 10, ncol = 10, byrow = T\n )\n\n for(digit in as.integer(iterable)){\n row_i = validation_matrix[row_i + 1, digit + 1] #in R indexes start from 1 and not from zero\n }\n\n test <- ifelse(row_i == 0, \"VALID\", \"NOT VALID\")\n message(paste(\"Number\", number, \"is\", test))\n}\n\nfor(number in c(5724, 5727, 112946, 112949)){\nDamm_algo(number)\n }\n", "language": "R" }, { "code": "#lang racket/base\n(require racket/match)\n\n(define operation-table\n #(#(0 3 1 7 5 9 8 6 4 2)\n #(7 0 9 2 1 5 4 8 6 3)\n #(4 2 0 6 8 7 1 3 5 9)\n #(1 7 5 0 9 8 3 4 2 6)\n #(6 1 2 3 0 4 5 9 7 8)\n #(3 6 7 4 2 0 9 5 8 1)\n #(5 8 6 9 7 2 0 1 3 4)\n #(8 9 4 5 3 6 2 0 1 7)\n #(9 4 3 8 6 1 7 2 0 5)\n #(2 5 8 1 4 3 6 7 9 0)))\n\n(define (integer->digit-list n)\n (let loop ((n n) (a null))\n (if (zero? n) a (let-values (([q r] (quotient/remainder n 10))) (loop q (cons r a))))))\n\n(define/match (check-digit n)\n [((list ds ...))\n (foldl\n (λ (d interim)\n (vector-ref (vector-ref operation-table interim) d))\n 0 ds)]\n [((? integer? i))\n (check-digit (integer->digit-list i))])\n\n(define/match (valid-number? n)\n [((? integer? i))\n (valid-number? (integer->digit-list i))]\n [((list ds ...))\n (zero? (check-digit ds))])\n\n(module+ test\n (require rackunit)\n (check-equal? (integer->digit-list 572) '(5 7 2))\n (check-equal? (check-digit 572) 4)\n (check-equal? (check-digit '(5 7 2)) 4)\n (check-true (valid-number? 5724))\n (check-false (valid-number? 5274))\n (check-true (valid-number? 112946)))\n", "language": "Racket" }, { "code": "sub damm ( *@digits ) {\n my @tbl = [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0];\n my $row = 0;\n for @digits -> $col { $row = @tbl[$row][$col] }\n not $row\n}\n\n# Testing\nfor 5724, 5727, 112946 {\n say \"$_:\\tChecksum digit { damm( $_.comb ) ?? '' !! 'in' }correct.\"\n}\n", "language": "Raku" }, { "code": "/* REXX */\nCall init\nCall test 5724\nCall test 5727\nCall test 112946\nCall test 112940\nExit\n\ntest:\nParse Arg number\nint_digit=0\nDo p=1 To length(number)\n d=substr(number,p,1)\n int_digit=grid.int_digit.d\n If p<length(number) Then cd=int_digit\n End\nIf int_digit=0 Then\n Say number 'is ok'\nElse\n Say number 'is not ok, check-digit should be' cd '(instead of' d')'\nReturn\n\ninit:\ni=-2\nCall setup '* 0 1 2 3 4 5 6 7 8 9'\nCall setup '0 0 3 1 7 5 9 8 6 4 2'\nCall setup '1 7 0 9 2 1 5 4 8 6 3'\nCall setup '2 4 2 0 6 8 7 1 3 5 9'\nCall setup '3 1 7 5 0 9 8 3 4 2 6'\nCall setup '4 6 1 2 3 0 4 5 9 7 8'\nCall setup '5 3 6 7 4 2 0 9 5 8 1'\nCall setup '6 5 8 6 9 7 2 0 1 3 4'\nCall setup '7 8 9 4 5 3 6 2 0 1 7'\nCall setup '8 9 4 3 8 6 1 7 2 0 5'\nCall setup '9 2 5 8 1 4 3 6 7 9 0'\nReturn\nsetup:\n Parse Arg list\n i=i+1\n Do col=-1 To 9\n grid.i.col=word(list,col+2)\n End\n Return\n", "language": "REXX" }, { "code": "/*REXX pgm uses H. Michael Damm's algorithm to validate numbers with suffixed check sum. digit*/\n a.0= 0317598642; a.1= 7092154863; a.2= 4206871359; a.3= 1750983426; a.4= 6123045978\n a.5= 3674209581; a.6= 5869720134; a.7= 8945362017; a.8= 9438617205; a.9= 2581436790\nCall Damm 5724, 5727, 112946, 112940 /*invoke Damm's algorithm To some #'s.*/\nExit /*stick a Tok in it, we're all Done. */\n/*---------------------------------------------------------------------------------*/\nDamm:\n Do j=1 To arg() /* loop over numbers */\n x=arg(j)\n d=0\n Do p=1 To length(x)-1 /* compute the checksum digit */\n d=substr(a.d,substr(x,p,1)+1,1)\n end /*p*/\n z=right(x,1) /* the given digit */\n If z=d Then Say ' valid checksum digit ' z \" for \" x\n Else Say ' invalid checksum digit ' z \" for \" x ' (should be' d\")\"\n End /*j*/\n Return /syntaxhighlight>\n{{out|output|text=&nbsp; when using the (internal) default inputs:}}\n<pre>\n valid checksum digit 4 for 5724\n invalid checksum digit 7 for 5727 (should be 4)\n valid checksum digit 6 for 112946\n invalid checksum digit 0 for 112940 (should be 6)\n</pre>\n", "language": "REXX" }, { "code": "# Project : Damm algorithm\n\nmatrix = [[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0]]\n\nsee \"5724\" + encode(5724 ) + nl\nsee \"5727\" + encode(5727 ) + nl\nsee \"112946\" + encode(112946) + nl\n\nfunc encode(n)\n check = 0\n for d in string(n)\n check = matrix[check+1][d-'0'+1]\n next\n if check = 0\n return \" is valid\"\n else\n return \" is invalid\"\n ok\n", "language": "Ring" }, { "code": "TABLE = [\n [0,3,1,7,5,9,8,6,4,2], [7,0,9,2,1,5,4,8,6,3],\n [4,2,0,6,8,7,1,3,5,9], [1,7,5,0,9,8,3,4,2,6],\n [6,1,2,3,0,4,5,9,7,8], [3,6,7,4,2,0,9,5,8,1],\n [5,8,6,9,7,2,0,1,3,4], [8,9,4,5,3,6,2,0,1,7],\n [9,4,3,8,6,1,7,2,0,5], [2,5,8,1,4,3,6,7,9,0]\n]\n\ndef damm_valid?(n) = n.digits.reverse.inject(0){|idx, a| TABLE[idx][a] } == 0\n\n[5724, 5727, 112946].each{|n| puts \"#{n}: #{damm_valid?(n) ? \"\" : \"in\"}valid\"}\n", "language": "Ruby" }, { "code": "fn damm(number: &str) -> u8 {\n static TABLE: [[u8; 10]; 10] = [\n [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0],\n ];\n\n number.chars().fold(0, |row, digit| {\n let digit = digit.to_digit(10).unwrap();\n TABLE[row as usize][digit as usize]\n })\n}\n\nfn damm_validate(number: &str) -> bool {\n damm(number) == 0\n}\n\nfn main() {\n let numbers = &[\"5724\", \"5727\", \"112946\"];\n for number in numbers {\n let is_valid = damm_validate(number);\n if is_valid {\n println!(\"{:>6} is valid\", number);\n } else {\n println!(\"{:>6} is invalid\", number);\n }\n }\n}\n", "language": "Rust" }, { "code": "import scala.annotation.tailrec\n\nobject DammAlgorithm extends App {\n\n private val numbers = Seq(5724, 5727, 112946, 112949)\n\n @tailrec\n private def damm(s: String, interim: Int): String = {\n def table =\n Vector(\n Vector(0, 3, 1, 7, 5, 9, 8, 6, 4, 2),\n Vector(7, 0, 9, 2, 1, 5, 4, 8, 6, 3),\n Vector(4, 2, 0, 6, 8, 7, 1, 3, 5, 9),\n Vector(1, 7, 5, 0, 9, 8, 3, 4, 2, 6),\n Vector(6, 1, 2, 3, 0, 4, 5, 9, 7, 8),\n Vector(3, 6, 7, 4, 2, 0, 9, 5, 8, 1),\n Vector(5, 8, 6, 9, 7, 2, 0, 1, 3, 4),\n Vector(8, 9, 4, 5, 3, 6, 2, 0, 1, 7),\n Vector(9, 4, 3, 8, 6, 1, 7, 2, 0, 5),\n Vector(2, 5, 8, 1, 4, 3, 6, 7, 9, 0)\n )\n\n if (s.isEmpty) if (interim == 0) \"✔\" else \"✘\"\n else damm(s.tail, table(interim)(s.head - '0'))\n }\n\n for (number <- numbers) println(f\"$number%6d is ${damm(number.toString, 0)}.\")\n\n}\n", "language": "Scala" }, { "code": "func damm(digits) {\n static tbl = [\n [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0],\n ]\n\n !digits.flip.reduce({|row,col| tbl[row][col] }, 0)\n}\n\nfor n in [5724, 5727, 112946] {\n say \"#{n}:\\tChecksum digit #{ damm(n.digits) ? '' : 'in'}correct.\"\n}\n", "language": "Sidef" }, { "code": "proc damm {number} {\n set digits [split $number \"\"]\n set tbl {\n {0 3 1 7 5 9 8 6 4 2}\n {7 0 9 2 1 5 4 8 6 3}\n {4 2 0 6 8 7 1 3 5 9}\n {1 7 5 0 9 8 3 4 2 6}\n {6 1 2 3 0 4 5 9 7 8}\n {3 6 7 4 2 0 9 5 8 1}\n {5 8 6 9 7 2 0 1 3 4}\n {8 9 4 5 3 6 2 0 1 7}\n {9 4 3 8 6 1 7 2 0 5}\n {2 5 8 1 4 3 6 7 9 0}\n }\n\n set row 0\n foreach col $digits {\n set row [lindex $tbl $row $col]\n }\n return [expr {$row == 0 ? 1 : 0}]\n}\n\nforeach number {5724 5727 112946} {\n set correct [damm $number]\n puts \"$number:\\tChecksum digit [expr {$correct ? \"\" : \"in\"}]correct.\"\n}\n", "language": "Tcl" }, { "code": "const table = [\n [u8(0), 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [u8(7), 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [u8(4), 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [u8(1), 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [u8(6), 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [u8(3), 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [u8(5), 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [u8(8), 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [u8(9), 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [u8(2), 5, 8, 1, 4, 3, 6, 7, 9, 0],\n]\n\nfn damm(input string) bool {\n mut interim := u8(0)\n for c in input.bytes() {\n interim = table[interim][c-'0'[0]]\n }\n return interim == 0\n}\n\nfn main() {\n for s in [\"5724\", \"5727\", \"112946\", \"112949\"] {\n println(\"${s:6} ${damm(s)}\")\n }\n}\n", "language": "V-(Vlang)" }, { "code": "Module Module1\n\n ReadOnly table = {\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}\n }\n\n Function Damm(s As String) As Boolean\n Dim interim = 0\n For Each c In s\n interim = table(interim, AscW(c) - AscW(\"0\"))\n Next\n Return interim = 0\n End Function\n\n Sub Main()\n Dim numbers = {5724, 5727, 112946, 112949}\n For Each number In numbers\n Dim isvalid = Damm(number.ToString())\n If isvalid Then\n Console.WriteLine(\"{0,6} is valid\", number)\n Else\n Console.WriteLine(\"{0,6} is invalid\", number)\n End If\n Next\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./fmt\" for Fmt\n\nvar table = [\n [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0]\n]\n\nvar damm = Fn.new { |input|\n var interim = 0\n for (c in input.bytes) interim = table[interim][c-48]\n return interim == 0\n}\n\nfor (s in [\"5724\", \"5727\", \"112946\", \"112949\"]) {\n Fmt.print(\"$6s $s\", s, damm.call(s))\n}\n", "language": "Wren" }, { "code": "string 0; \\use zero-terminated strings\n\nfunc Damm(Input); \\Return 'true' if checksum is correct\nchar Input;\nint Interim, Table;\n[Table:= [\n [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0] ];\nInterim:= 0;\nwhile Input(0) do\n [Interim:= Table(Interim, Input(0)-^0);\n Input:= Input+1;\n ];\nreturn Interim = 0;\n];\n\nint String, I;\n[String:= [\"5724\", \"5727\", \"112946\", \"112949\"];\nfor I:= 0 to 4-1 do\n [Text(0, String(I)); ChOut(0, 9\\tab\\);\n Text(0, if Damm(String(I)) then \"true\" else \"false\");\n CrLf(0);\n ];\n]\n", "language": "XPL0" }, { "code": "fcn damm(digits){ // digits is something that supports an iterator of integers\n var [const] tbl=Data(0,Int,\t\t// 10x10 byte bucket\n 0, 3, 1, 7, 5, 9, 8, 6, 4, 2,\n 7, 0, 9, 2, 1, 5, 4, 8, 6, 3,\n 4, 2, 0, 6, 8, 7, 1, 3, 5, 9,\n 1, 7, 5, 0, 9, 8, 3, 4, 2, 6,\n 6, 1, 2, 3, 0, 4, 5, 9, 7, 8,\n 3, 6, 7, 4, 2, 0, 9, 5, 8, 1,\n 5, 8, 6, 9, 7, 2, 0, 1, 3, 4,\n 8, 9, 4, 5, 3, 6, 2, 0, 1, 7,\n 9, 4, 3, 8, 6, 1, 7, 2, 0, 5,\n 2, 5, 8, 1, 4, 3, 6, 7, 9, 0);\n 0 == digits.reduce(fcn(interim,digit){ tbl[interim*10 + digit] },0)\n}\n", "language": "Zkl" }, { "code": "damm(List(5,7,2,4)).println();\t\t// True\ndamm(Data(0,Int,5,7,2,7).howza(0)).println();\t// stream bytes, False\ndamm((112946).split()).println();\t// True\n", "language": "Zkl" } ]
Damm-algorithm
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Date_format\nnote: Text processing\n", "language": "00-META" }, { "code": ";Task:\nDisplay the &nbsp; current date &nbsp; in the formats of:\n:::* &nbsp; '''2007-11-23''' &nbsp; &nbsp; and \n:::* &nbsp; '''Friday, November 23, 2007'''\n<br><br>\n\n", "language": "00-TASK" }, { "code": "print(Time().format(‘YYYY-MM-DD’))\nprint(Time().strftime(‘%A, %B %e, %Y’))\n", "language": "11l" }, { "code": " JSR SYS_READ_CALENDAR ;outputs calendar date to BIOS RAM\n\n\tMOVE.B #'2',D0 ;a character in single or double quotes refers to its ascii equivalent.\n\tJSR PrintChar\n\tMOVE.B #'0',D0\n\tJSR PrintChar\n\t\n\tLEA BIOS_YEAR,A1\t\n\tMOVE.B (A1)+,D0\t\t\t;stores last 2 digits of year into D0, in binary coded decimal\n\tJSR UnpackNibbles8\t\t;separate the digits into high and low nibbles: D0 = 00020001\n\tADD.L #$00300030,D0\t\t;convert both numerals to their ascii equivalents.\n\tSWAP D0\t\t\t\t;print the \"2\" first\n\tJSR PrintChar\n\tSWAP D0\t\t\t\t;then the \"1\"\n\tJSR PrintChar\n\t\n\tMOVE.B #'-',D0\n\tJSR PrintChar\n\t\n\tMOVE.B (A1)+,D0\t\t\t;get the month\n\tJSR UnpackNibbles8\t\t\n\tADD.L #$00300030,D0\n\tSWAP D0\n\tJSR PrintChar\n\tSWAP D0\n\tJSR PrintChar\n\t\n\tMOVE.B #'-',D0\n\tJSR PrintChar\n\t\n\tMOVE.B (A1)+,D0\t\t\t;get the day\n\tJSR UnpackNibbles8\n\tADD.L #$00300030,D0\n\tSWAP D0\n\tJSR PrintChar\n\tSWAP D0\n\tJSR PrintChar\n\t\n\t;now the date is printed.\n\t\n\t;Now do it again only written out:\n\tjsr NewLine\n\t\n\tCLR.L D0\t\t\t\t;reset D0\n\tMOVE.B (A1),D0\t\t\t;A1 happens to point to the weekday\n\tLSL.W #2,D0\t\t\t\t;we are indexing into a table of longs\n\tLEA Days_Lookup,A2\n\tLEA (A2,D0),A2\n\tMOVEA.L (A2),A3\t\t\t;dereference the pointer into A3, which the PrintString routine takes as an argument.\n\t\n\tJSR PrintString\n\t\n\tCLR.L D0\n\tLEA BIOS_MONTH,A1\t\t;GET THE MONTH\n\tMOVE.B (A1)+,D0\n\tLSL.W #2,D0\n\tLEA Months_Lookup,A2\n\tLEA (A2,D0),A2\n\tMOVEA.L (A2),A3\n\t\n\tJSR PrintString\n\t\n\tMOVE.B (A1),D0\t\t\t;GET THE DAY\n\tJSR UnpackNibbles8\t\t\n\tADD.L #$00300030,D0\n\tSWAP D0\n\tJSR PrintChar\n\tSWAP D0\n\tJSR PrintChar\n\t\n\tMOVE.B #',',D0\n\tJSR PrintChar\n\tMOVE.B #' ',D0\n\tJSR PrintChar\n\t\n\tMOVE.B #'2',D0\n\tJSR PrintChar\n\tMOVE.B #'0',D0\n\tJSR PrintChar\n\t\n\tLEA BIOS_YEAR,A1\t\n\tMOVE.B (A1)+,D0\t\t\t;stores last 2 digits of year into D0, in binary coded decimal\n\tJSR UnpackNibbles8\t\t;separate the digits into high and low nibbles: D0 = 00020001\n\tADD.L #$00300030,D0\t\t;convert both numerals to their ascii equivalents.\n\tSWAP D0\t\t\t\t\t;print the \"2\" first\n\tJSR PrintChar\n\tSWAP D0\t\t\t\t\t;then the \"1\"\n\tJSR PrintChar\n\nforever:\n\tbra forever ;trap the program counter\n\nUnpackNibbles8:\n; INPUT: D0 = THE VALUE YOU WISH TO UNPACK.\n; HIGH NIBBLE IN HIGH WORD OF D0, LOW NIBBLE IN LOW WORD. SWAP D0 TO GET THE OTHER HALF.\n\tpushWord D1\n\t\tCLR.W D1\t\t\n\t\tMOVE.B D0,D1\n\t\tCLR.L D0\n\t\tMOVE.B D1,D0\t ;now D0 = D1 = $000000II, where I = input\n\t\t\n\t\tAND.B #$F0,D0\t ;chop off bottom nibble\n\t\tLSR.B #4,D0\t\t ;downshift top nibble into bottom nibble of the word\n\t\tSWAP D0\t\t\t ;store in high word\n\t\tAND.B #$0F,D1\t ;chop off bottom nibble\n\t\tMOVE.B D1,D0\t ;store in low word\n\tpopWord D1\n\trts\n", "language": "68000-Assembly" }, { "code": "d:new\n\"%Y-%M-%D\" over d:format . cr\n\"%W, %N %D, %Y\" over d:format . cr\nbye\n", "language": "8th" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program dateFormat64.s */\n\n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n.equ GETTIME, 169 // call system linux gettimeofday\n\n/*******************************************/\n/* Structures */\n/********************************************/\n/* example structure time */\n .struct 0\ntimeval_sec: //\n .struct timeval_sec + 8\ntimeval_usec: //\n .struct timeval_usec + 8\ntimeval_end:\n .struct 0\ntimezone_min: //\n .struct timezone_min + 8\ntimezone_dsttime: //\n .struct timezone_dsttime + 8\ntimezone_end:\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessError: .asciz \"Error detected !!!!. \\n\"\nszMessResult: .asciz \"Date : @/@/@ \\n\" // message result\nszMessResult1: .asciz \"Date day : @ @ @ @ \\n\" // message result\nszJan: .asciz \"Janvier\"\nszFev: .asciz \"Fèvrier\"\nszMars: .asciz \"Mars\"\nszAvril: .asciz \"Avril\"\nszMai: .asciz \"Mai\"\nszJuin: .asciz \"Juin\"\nszJuil: .asciz \"Juillet\"\nszAout: .asciz \"Aout\"\nszSept: .asciz \"Septembre\"\nszOct: .asciz \"Octobre\"\nszNov: .asciz \"Novembre\"\nszDec: .asciz \"Décembre\"\nszLundi: .asciz \"Lundi\"\nszMardi: .asciz \"Mardi\"\nszMercredi: .asciz \"Mercredi\"\nszJeudi: .asciz \"Jeudi\"\nszVendredi: .asciz \"Vendredi\"\nszSamedi: .asciz \"Samedi\"\nszDimanche: .asciz \"Dimanche\"\nszCarriageReturn: .asciz \"\\n\"\n.align 4\ntbDayMonthYear: .quad 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335\n .quad 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700\n .quad 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065\n .quad 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430\ntbMonthName: .quad szJan\n .quad szFev\n .quad szMars\n .quad szAvril\n .quad szMai\n .quad szJuin\n .quad szJuil\n .quad szAout\n .quad szSept\n .quad szOct\n .quad szNov\n .quad szDec\ntbDayName: .quad szLundi\n .quad szMardi\n .quad szMercredi\n .quad szJeudi\n .quad szVendredi\n .quad szSamedi\n .quad szDimanche\n\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\n.align 4\nstTVal: .skip timeval_end\nstTZone: .skip timezone_end\nsZoneConv: .skip 24\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: // entry of program\n ldr x0,qAdrstTVal\n ldr x1,qAdrstTZone\n mov x8,#GETTIME\n svc 0\n cmp x0,#-1 // error ?\n beq 99f\n ldr x1,qAdrstTVal\n ldr x0,[x1,#timeval_sec] // timestamp in second\n bl dateFormatNum\n ldr x0,[x1,#timeval_sec] // timestamp in second\n bl dateFormatAlpha\n ldr x0,qTStest1\n bl dateFormatNum\n ldr x0,qTStest1\n bl dateFormatAlpha\n ldr x0,qTStest2\n bl dateFormatNum\n ldr x0,qTStest2\n bl dateFormatAlpha\n ldr x0,qTStest3\n bl dateFormatNum\n ldr x0,qTStest3\n bl dateFormatAlpha\n b 100f\n99:\n ldr x0,qAdrszMessError\n bl affichageMess\n100: // standard end of the program\n mov x0,#0 // return code\n mov x8,#EXIT // request to exit program\n svc 0 // perform the system call\n\nqAdrszMessError: .quad szMessError\nqAdrstTVal: .quad stTVal\nqAdrstTZone: .quad stTZone\nqAdrszCarriageReturn: .quad szCarriageReturn\nqAdrsZoneConv: .quad sZoneConv\nqTStest1: .quad 1609508339 // 01/01/2021\nqTStest2: .quad 1657805939 // 14/07/2022\nqTStest3: .quad 1767221999 // 31/12/2025\n/******************************************************************/\n/* date format numeric */\n/******************************************************************/\n/* x0 contains the timestamp in seconds */\ndateFormatNum:\n stp x1,lr,[sp,-16]! // save registers\n ldr x2,qSecJan2020\n sub x0,x0,x2 // total secondes to 01/01/2020\n mov x1,60\n udiv x0,x0,x1 // divide secondes\n udiv x0,x0,x1 // divide minutes\n mov x1,#24\n udiv x0,x0,x1 // divide hours\n mov x11,x0\n mov x1,#(365 * 4 + 1)\n udiv x9,x0,x1\n lsl x9,x9,#2 // multiply by 4 = year1\n mov x1,#(365 * 4 + 1)\n udiv x2,x11,x1\n msub x10,x2,x1,x11\n\n ldr x1,qAdrtbDayMonthYear\n mov x2,#3\n mov x3,#12\n1:\n mul x11,x3,x2\n ldr x4,[x1,x11,lsl 3] // load days by year\n cmp x10,x4\n bge 2f\n sub x2,x2,1\n cbnz x2,1b\n2: // x2 = year2\n mov x5,11\n mul x11,x3,x2\n lsl x11,x11,3\n add x11,x11,x1 // table address\n3:\n ldr x4,[x11,x5,lsl 3] // load days by month\n cmp x10,x4\n bge 4f\n subs x5,x5,1\n bne 3b\n4: // x5 = month - 1\n mul x11,x3,x2\n add x11,x11,x5\n ldr x1,qAdrtbDayMonthYear\n ldr x3,[x1,x11,lsl 3]\n sub x0,x10,x3\n add x0,x0,1 // final compute day\n ldr x1,qAdrsZoneConv\n bl conversion10 // this function do not zero final\n ldr x0,qAdrszMessResult\n ldr x1,qAdrsZoneConv\n bl strInsertAtCharInc // insert result at first // character\n mov x3,x0\n add x0,x5,1 // final compute month\n cmp x0,12\n sub x1,x0,12\n csel x0,x1,x0,gt\n ldr x1,qAdrsZoneConv\n bl conversion10\n mov x0,x3\n ldr x1,qAdrsZoneConv\n bl strInsertAtCharInc // insert result at next // character\n mov x3,x0\n ldr x11,qYearStart\n add x0,x9,x11\n add x0,x0,x2 // final compute year = 2020 + yeax1 + yeax2\n ldr x1,qAdrsZoneConv\n bl conversion10\n mov x0,x3\n ldr x1,qAdrsZoneConv\n bl strInsertAtCharInc // insert result at next // character\n bl affichageMess\n100:\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\nqAdrszMessResult: .quad szMessResult\n/******************************************************************/\n/* date format alphanumeric */\n/******************************************************************/\n/* x0 contains the timestamp in seconds */\ndateFormatAlpha:\n stp x1,lr,[sp,-16]! // save registers\n ldr x2,qSecJan2020\n sub x0,x0,x2 // total secondes to 01/01/2020\n mov x6,x0\n mov x1,60\n udiv x0,x0,x1\n udiv x0,x0,x1\n mov x1,24\n udiv x0,x0,x1\n mov x7,x0\n mov x1,(365 * 4 + 1)\n udiv x9,x0,x1\n lsl x9,x9,#2 // multiply by 4 = year1\n mov x1,(365 * 4 + 1)\n udiv x0,x7,x1\n msub x10,x0,x1,x7\n ldr x1,qAdrtbDayMonthYear\n mov x8,3\n mov x3,12\n1:\n mul x7,x3,x8\n ldr x4,[x1,x7,lsl 3] // load days by year\n cmp x10,x4\n bge 2f\n sub x8,x8,1\n cmp x8,0\n bne 1b\n2: // x8 = yeax2\n mov x5,#11\n mul x7,x3,x8\n lsl x7,x7,3\n add x7,x7,x1\n3:\n ldr x4,[x7,x5,lsl 3] // load days by month\n cmp x10,x4\n bge 4f\n subs x5,x5,1\n bne 3b\n4: // x5 = month - 1\n\n mov x0,x6 // number secondes depuis 01/01/2020\n ldr x1,qNbSecByDay\n udiv x0,x6,x1\n mov x1,7\n udiv x2,x0,x1\n msub x3,x2,x1,x0\n add x2,x3,2\n cmp x2,7\n sub x3,x2,7\n csel x2,x3,x2,ge\n ldr x1,qAdrtbDayName\n ldr x1,[x1,x2,lsl 3]\n ldr x0,qAdrszMessResult1\n\n bl strInsertAtCharInc // insert result at next // character\n mov x3,x0\n mov x7,12\n mul x11,x7,x8\n add x11,x11,x5\n ldr x1,qAdrtbDayMonthYear\n ldr x7,[x1,x11,lsl 3]\n sub x0,x10,x7\n add x0,x0,1 // final compute day\n ldr x1,qAdrsZoneConv\n bl conversion10 // this function do not zero final\n mov x0,x3\n ldr x1,qAdrsZoneConv\n bl strInsertAtCharInc // insert result at first // character\n mov x3,x0\n ldr x1,qAdrtbMonthName\n cmp x5,12\n sub x2,x5,12\n csel x5,x2,x5,ge\n ldr x1,[x1,x5,lsl 3] // month name\n mov x0,x3\n bl strInsertAtCharInc // insert result at first // character\n mov x3,x0\n ldr x0,qYearStart\n add x0,x0,x8\n add x0,x0,x9 // final compute year = 2020 + yeax1 + yeax2\n\n ldr x1,qAdrsZoneConv\n bl conversion10 // this function do not zero final\n mov x0,x3\n ldr x1,qAdrsZoneConv\n bl strInsertAtCharInc // insert result at first // character\n bl affichageMess\n100:\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\nqAdrszMessResult1: .quad szMessResult1\nqSecJan2020: .quad 1577836800\nqAdrtbDayMonthYear: .quad tbDayMonthYear\nqYearStart: .quad 2020\nqAdrtbMonthName: .quad tbMonthName\nqAdrtbDayName: .quad tbDayName\nqNbSecByDay: .quad 3600 * 24\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "report zdate.\ndata: lv_month type string,\n lv_weekday type string,\n lv_date type string,\n lv_day type c.\n\ncall function 'DATE_COMPUTE_DAY'\n exporting date = sy-datum\n importing day = lv_day.\nselect single ltx from t247 into lv_month\n where spras = sy-langu and\n mnr = sy-datum+4(2).\n\nselect single langt from t246 into lv_weekday\n where sprsl = sy-langu and\n wotnr = lv_day.\n\nconcatenate lv_weekday ', ' lv_month ' ' sy-datum+6(2) ', ' sy-datum(4) into lv_date respecting blanks.\nwrite lv_date.\nconcatenate sy-datum(4) '-' sy-datum+4(2) '-' sy-datum+6(2) into lv_date.\nwrite / lv_date.\n", "language": "ABAP" }, { "code": "DEFINE PTR=\"CARD\"\n\nTYPE Date=[\n INT year\n BYTE month\n BYTE day]\n\nPTR ARRAY DayOfWeeks(7)\nPTR ARRAY Months(12)\n\nPROC Init()\n DayOfWeeks(0)=\"Sunday\" DayOfWeeks(1)=\"Monday\"\n DayOfWeeks(2)=\"Tuesday\" DayOfWeeks(3)=\"Wednesday\"\n DayOfWeeks(4)=\"Thursday\" DayOfWeeks(5)=\"Friday\"\n DayOfWeeks(6)=\"Saturday\"\n Months(0)=\"January\" Months(1)=\"February\"\n Months(2)=\"March\" Months(3)=\"April\"\n Months(4)=\"May\" Months(5)=\"June\"\n Months(6)=\"July\" Months(7)=\"August\"\n Months(8)=\"September\" Months(9)=\"October\"\n Months(10)=\"November\" Months(11)=\"December\"\nRETURN\n\n;https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods\nBYTE FUNC DayOfWeek(Date POINTER d)\t;1<=m<=12, y>1752\n BYTE ARRAY t=[0 3 2 5 0 3 5 1 4 6 2 4]\n BYTE res\n INT y\n\n y=d.year\n IF d.month<3 THEN\n y==-1\n FI\n res=(y+y/4-y/100+y/400+t(d.month-1)+d.day) MOD 7\nRETURN (res)\n\nPROC PrintB2(BYTE x)\n IF x<10 THEN\n Put('0)\n FI\n PrintB(x)\nRETURN\n\nPROC PrintDateShort(Date POINTER d)\n PrintI(d.year) Put('-)\n PrintB2(d.month) Put('-)\n PrintB2(d.day)\nRETURN\n\nPROC PrintDateLong(Date POINTER d)\n BYTE wd\n\n wd=DayOfWeek(d)\n Print(DayOfWeeks(wd)) Print(\", \")\n Print(Months(d.month-1)) Put(' )\n PrintB(d.day) Print(\", \")\n PrintI(d.year)\nRETURN\n\nPROC Main()\n Date d\n\n Init()\n\n ;There is no function to get the current date\n ;on Atari 8-bit computer\n d.year=2021 d.month=9 d.day=1\n\n PrintDateShort(d) PutE()\n PrintDateLong(d) PutE()\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Calendar; use Ada.Calendar;\nwith Ada.Calendar.Formatting; use Ada.Calendar.Formatting;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Date_Format is\n function Image (Month : Month_Number) return String is\n begin\n case Month is\n when 1 => return \"January\";\n when 2 => return \"February\";\n when 3 => return \"March\";\n when 4 => return \"April\";\n when 5 => return \"May\";\n when 6 => return \"June\";\n when 7 => return \"July\";\n when 8 => return \"August\";\n when 9 => return \"September\";\n when 10 => return \"October\";\n when 11 => return \"November\";\n when 12 => return \"December\";\n end case;\n end Image;\n function Image (Day : Day_Name) return String is\n begin\n case Day is\n when Monday => return \"Monday\";\n when Tuesday => return \"Tuesday\";\n when Wednesday => return \"Wednesday\";\n when Thursday => return \"Thursday\";\n when Friday => return \"Friday\";\n when Saturday => return \"Saturday\";\n when Sunday => return \"Sunday\";\n end case;\n end Image;\n Today : Time := Clock;\nbegin\n Put_Line (Image (Today) (1..10));\n Put_Line\n ( Image (Day_Of_Week (Today)) & \", \"\n & Image (Ada.Calendar.Month (Today))\n & Day_Number'Image (Ada.Calendar.Day (Today)) & \",\"\n & Year_Number'Image (Ada.Calendar.Year (Today))\n );\nend Date_Format;\n", "language": "Ada" }, { "code": "# define the layout of the date/time as provided by the call to local time #\nSTRUCT ( INT sec, min, hour, mday, mon, year, wday, yday, isdst) tm = (6,5,4,3,2,1,7,~,8);\n\nFORMAT # some useful format declarations #\n ymd repr = $4d,\"-\"2d,\"-\"2d$,\n month repr = $c(\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\",\n \"August\",\"September\",\"October\",\"November\",\"December\")$,\n week day repr = $c(\"Sunday\",\"Monday\",\"Tuesday\",\"Wednesday\",\n \"Thursday\",\"Friday\",\"Saturday\")$,\n dmdy repr = $f(week day repr)\", \"f(month repr)\" \"g(-0)\", \"g(-4)$,\n\n mon = $c(\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\")$,\n wday = $c(\"Sun\",\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\")$,\n tz = $c(\"MSK\",\"MSD\")$,\n unix time repr = $f(wday)\" \"f(mon)z-d,\" \"dd,\":\"dd,\":\"dd,\" \"f(tz)\" \"dddd$;\n\n[]INT now = local time;\n\nprintf((ymd repr, now[year OF tm:mday OF tm], $l$));\nprintf((dmdy repr, now[wday OF tm], now[mon OF tm], now[mday OF tm], now[year OF tm], $l$));\n\nprintf((unix time repr, now[wday OF tm], now[mon OF tm], now[mday OF tm],\n now[hour OF tm:sec OF tm], now[isdst OF tm]+1, now[year OF tm], $l$))\n", "language": "ALGOL-68" }, { "code": "Datetime dtNow = datetime.now();\nString strDt1 = dtNow.format('yyyy-MM-dd');\nString strDt2 = dtNow.format('EEEE, MMMM dd, yyyy');\nsystem.debug(strDt1); // \"2007-11-10\"\nsystem.debug(strDt2); //\"Sunday, November 10, 2007\"\n", "language": "Apex" }, { "code": "set {year:y, month:m, day:d, weekday:w} to (current date)\n\ntell (y * 10000 + m * 100 + d) as text to set shortFormat to text 1 thru 4 & \"-\" & text 5 thru 6 & \"-\" & text 7 thru 8\nset longFormat to (w as text) & (\", \" & m) & (space & d) & (\", \" & y)\n\nreturn (shortFormat & linefeed & longFormat)\n", "language": "AppleScript" }, { "code": "\"2020-10-28\nWednesday, October 28, 2020\"\n", "language": "AppleScript" }, { "code": "tell (the current date)\n\tset shortdate to text 1 thru 10 of (it as «class isot» as string)\n\tset longdate to the contents of [its weekday, \", \", ¬\n\t\t(its month), \" \", day, \", \", year] as text\nend tell\n\nlog the shortdate\nlog the longdate\n", "language": "AppleScript" }, { "code": "-- iso8601Short :: Date -> String\non iso8601Short(dte)\n text 1 thru 10 of iso8601Local(dte)\nend iso8601Short\n\n\n-- longDate :: Date -> String\non longDate(dte)\n tell dte\n \"\" & its weekday & \", \" & its month & \" \" & its day & \", \" & year\n end tell\nend longDate\n\n\n---------------------------- TEST --------------------------\non run\n\n unlines(apList({iso8601Short, longDate}, ¬\n {current date}))\n\nend run\n\n\n-------------------------- GENERIC -------------------------\n\n\n-- Each member of a list of functions applied to\n-- each of a list of arguments, deriving a list of new values\n-- apList (<*>) :: [(a -> b)] -> [a] -> [b]\non apList(fs, xs)\n set lst to {}\n repeat with f in fs\n tell mReturn(contents of f)\n repeat with x in xs\n set end of lst to |λ|(contents of x)\n end repeat\n end tell\n end repeat\n return lst\nend apList\n\n\n-- iso8601Local :: Date -> String\non iso8601Local(dte)\n (dte as «class isot» as string)\nend iso8601Local\n\n\n-- mReturn :: First-class m => (a -> b) -> m (a -> b)\non mReturn(f)\n -- 2nd class handler function lifted into 1st class script wrapper.\n if script is class of f then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n\n-- unlines :: [String] -> String\non unlines(xs)\n -- A single string formed by the intercalation\n -- of a list of strings with the newline character.\n set {dlm, my text item delimiters} to ¬\n {my text item delimiters, linefeed}\n set s to xs as text\n set my text item delimiters to dlm\n s\nend unlines\n", "language": "AppleScript" }, { "code": "/* ARM assembly Raspberry PI */\n/* program dateFormat.s */\n\n/* REMARK 1 : this program use routines in a include file\n see task Include a file language arm assembly\n for the routine affichageMess conversion10\n see at end of this program the instruction include */\n\n/*******************************************/\n/* Constantes */\n/*******************************************/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ BRK, 0x2d @ Linux syscall\n.equ CHARPOS, '@'\n\n.equ GETTIME, 0x4e @ call system linux gettimeofday\n\n/*******************************************/\n/* Structures */\n/********************************************/\n/* example structure time */\n .struct 0\ntimeval_sec: @\n .struct timeval_sec + 4\ntimeval_usec: @\n .struct timeval_usec + 4\ntimeval_end:\n .struct 0\ntimezone_min: @\n .struct timezone_min + 4\ntimezone_dsttime: @\n .struct timezone_dsttime + 4\ntimezone_end:\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessError: .asciz \"Error detected !!!!. \\n\"\nszMessResult: .asciz \"Date : @/@/@ \\n\" @ message result\nszMessResult1: .asciz \"Date day : @ @ @ @ \\n\" @ message result\nszJan: .asciz \"Janvier\"\nszFev: .asciz \"Février\"\nszMars: .asciz \"Mars\"\nszAvril: .asciz \"Avril\"\nszMai: .asciz \"Mai\"\nszJuin: .asciz \"Juin\"\nszJuil: .asciz \"Juillet\"\nszAout: .asciz \"Aout\"\nszSept: .asciz \"Septembre\"\nszOct: .asciz \"Octobre\"\nszNov: .asciz \"Novembre\"\nszDec: .asciz \"Décembre\"\nszLundi: .asciz \"Lundi\"\nszMardi: .asciz \"Mardi\"\nszMercredi: .asciz \"Mercredi\"\nszJeudi: .asciz \"Jeudi\"\nszVendredi: .asciz \"Vendredi\"\nszSamedi: .asciz \"Samedi\"\nszDimanche: .asciz \"Dimanche\"\nszCarriageReturn: .asciz \"\\n\"\n.align 4\ntbDayMonthYear: .int 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335\n .int 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700\n .int 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065\n .int 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430\ntbMonthName: .int szJan\n .int szFev\n .int szMars\n .int szAvril\n .int szMai\n .int szJuin\n .int szJuil\n .int szAout\n .int szSept\n .int szOct\n .int szNov\n .int szDec\ntbDayName: .int szLundi\n .int szMardi\n .int szMercredi\n .int szJeudi\n .int szVendredi\n .int szSamedi\n .int szDimanche\n\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\n.align 4\nstTVal: .skip timeval_end\nstTZone: .skip timezone_end\nsZoneConv: .skip 100\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: @ entry of program\n ldr r0,iAdrstTVal\n ldr r1,iAdrstTZone\n mov r7,#GETTIME\n svc 0\n cmp r0,#-1 @ error ?\n beq 99f\n ldr r1,iAdrstTVal\n ldr r0,[r1,#timeval_sec] @ timestemp in second\n bl dateFormatNum\n ldr r0,[r1,#timeval_sec] @ timestemp in second\n bl dateFormatAlpha\n ldr r0,iTStest1\n bl dateFormatNum\n ldr r0,iTStest1\n bl dateFormatAlpha\n ldr r0,iTStest2\n bl dateFormatNum\n ldr r0,iTStest2\n bl dateFormatAlpha\n ldr r0,iTStest3\n bl dateFormatNum\n ldr r0,iTStest3\n bl dateFormatAlpha\n b 100f\n99:\n ldr r0,iAdrszMessError\n bl affichageMess\n100: @ standard end of the program\n mov r0,#0 @ return code\n mov r7,#EXIT @ request to exit program\n svc 0 @ perform the system call\n\niAdrszMessError: .int szMessError\niAdrstTVal: .int stTVal\niAdrstTZone: .int stTZone\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsZoneConv: .int sZoneConv\niTStest1: .int 1609508339 @ 01/01/2021\niTStest2: .int 1657805939 @ 14/07/2022\niTStest3: .int 1767221999 @ 31/12/2025\n/******************************************************************/\n/* date format numeric */\n/******************************************************************/\n/* r0 contains the timestamp in seconds */\ndateFormatNum:\n push {r1-r11,lr} @ save registers\n ldr r2,iSecJan2020\n sub r0,r0,r2 @ total secondes to 01/01/2020\n mov r1,#60\n bl division\n mov r0,r2\n mov r6,r3 @ compute secondes\n mov r1,#60\n bl division\n mov r7,r3 @ compute minutes\n mov r0,r2\n mov r1,#24\n bl division\n mov r8,r3 @ compute hours\n mov r0,r2\n mov r11,r0\n mov r1,#(365 * 4 + 1)\n bl division\n lsl r9,r2,#2 @ multiply by 4 = year1\n mov r1,#(365 * 4 + 1)\n mov r0,r11\n bl division\n mov r10,r3\n\n ldr r1,iAdrtbDayMonthYear\n mov r2,#3\n mov r3,#12\n1:\n mul r11,r3,r2\n ldr r4,[r1,r11,lsl #2] @ load days by year\n cmp r10,r4\n bge 2f\n sub r2,r2,#1\n cmp r2,#0\n bne 1b\n2: @ r2 = year2\n mov r5,#11\n mul r11,r3,r2\n lsl r11,#2\n add r11,r1 @ table address\n3:\n ldr r4,[r11,r5,lsl #2] @ load days by month\n cmp r10,r4\n bge 4f\n subs r5,r5,#1\n bne 3b\n4: @ r5 = month - 1\n mul r11,r3,r2\n add r11,r5\n ldr r1,iAdrtbDayMonthYear\n ldr r3,[r1,r11,lsl #2]\n sub r0,r10,r3\n add r0,r0,#1 @ final compute day\n ldr r1,iAdrsZoneConv\n bl conversion10 @ this function do not zero final\n mov r11,#0 @ store zero final\n strb r11,[r1,r0]\n ldr r0,iAdrszMessResult\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at first @ character\n mov r3,r0\n add r0,r5,#1 @ final compute month\n cmp r0,#12\n subgt r0,#12\n ldr r1,iAdrsZoneConv\n bl conversion10\n mov r11,#0 @ store zero final\n strb r11,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at next @ character\n mov r3,r0\n ldr r11,iYearStart\n add r0,r9,r11\n add r0,r0,r2 @ final compute year = 2020 + year1 + year2\n ldr r1,iAdrsZoneConv\n bl conversion10\n mov r11,#0 @ store zero final\n strb r11,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at next @ character\n bl affichageMess\n100:\n pop {r1-r11,lr} @ restaur registers\n bx lr @ return\niAdrszMessResult: .int szMessResult\n/******************************************************************/\n/* date format alphanumeric */\n/******************************************************************/\n/* r0 contains the timestamp in seconds */\ndateFormatAlpha:\n push {r1-r10,lr} @ save registers\n ldr r2,iSecJan2020\n sub r0,r0,r2 @ total secondes to 01/01/2020\n mov r6,r0\n mov r1,#60\n bl division\n mov r0,r2\n mov r1,#60\n bl division\n mov r0,r2\n mov r1,#24\n bl division\n mov r0,r2\n mov r8,r0\n mov r1,#(365 * 4 + 1)\n bl division\n lsl r9,r2,#2 @ multiply by 4 = year1\n mov r1,#(365 * 4 + 1)\n mov r0,r8\n bl division\n mov r10,r3 @ reste\n\n ldr r1,iAdrtbDayMonthYear\n mov r7,#3\n mov r3,#12\n1:\n mul r8,r3,r7\n ldr r4,[r1,r8,lsl #2] @ load days by year\n cmp r10,r4\n bge 2f\n sub r7,r7,#1\n cmp r7,#0\n bne 1b\n2: @ r7 = year2\n mov r5,#11\n mul r8,r3,r7\n lsl r8,#2\n add r8,r1\n3:\n ldr r4,[r8,r5,lsl #2] @ load days by month\n cmp r10,r4\n bge 4f\n subs r5,r5,#1\n bne 3b\n4: @ r5 = month - 1\n\n mov r0,r6 @ number secondes depuis 01/01/2020\n ldr r1,iNbSecByDay\n bl division\n mov r0,r2\n mov r1,#7\n bl division\n add r2,r3,#2\n cmp r2,#7\n subge r2,#7\n ldr r1,iAdrtbDayName\n ldr r1,[r1,r2,lsl #2]\n ldr r0,iAdrszMessResult1\n bl strInsertAtCharInc @ insert result at next @ character\n mov r3,r0\n mov r8,#12\n mul r11,r8,r7\n add r11,r5\n ldr r1,iAdrtbDayMonthYear\n ldr r8,[r1,r11,lsl #2]\n sub r0,r10,r8\n add r0,r0,#1 @ final compute day\n ldr r1,iAdrsZoneConv\n bl conversion10 @ this function do not zero final\n mov r8,#0 @ store zero final\n strb r8,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at first @ character\n mov r3,r0\n ldr r1,iAdrtbMonthName\n cmp r5,#12\n subge r5,#12\n ldr r1,[r1,r5,lsl #2] @ month name\n mov r0,r3\n bl strInsertAtCharInc @ insert result at first @ character\n mov r3,r0\n ldr r0,iYearStart\n add r0,r7\n add r0,r9 @ final compute year = 2020 + year1 + year2\n\n ldr r1,iAdrsZoneConv\n bl conversion10 @ this function do not zero final\n mov r8,#0 @ store zero final\n strb r8,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at first @ character\n bl affichageMess\n100:\n pop {r1-r10,lr} @ restaur registers\n bx lr @ return\niAdrszMessResult1: .int szMessResult1\niSecJan2020: .int 1577836800\niAdrtbDayMonthYear: .int tbDayMonthYear\niYearStart: .int 2020\niAdrtbMonthName: .int tbMonthName\niAdrtbDayName: .int tbDayName\niNbSecByDay: .int 3600 * 24\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n.include \"../affichage.inc\"\n", "language": "ARM-Assembly" }, { "code": "currentTime: now\n\nprint to :string.format: \"YYYY-MM-dd\" currentTime\nprint to :string.format: \"dddd, MMMM dd, YYYY\" currentTime\n", "language": "Arturo" }, { "code": "FormatTime, Date1, , yyyy-MM-dd ; \"2007-11-10\"\nFormatTime, Date2, , LongDate ; \"Sunday, November 10, 2007\"\nMsgBox %Date1% `n %Date2%\n", "language": "AutoHotkey" }, { "code": "#include <Date.au3>\n\n$iYear = 2007\n$iMonth = 11\n$iDay = 10\n\nConsoleWrite(StringFormat('%4d-%02d-%02d', $iYear, $iMonth, $iDay) & @LF)\n\n$iWeekDay = _DateToDayOfWeekISO($iYear, $iMonth, $iDay)\nConsoleWrite(StringFormat('%s, %s %02d, %4d', _GetLongDayLocale($iWeekDay), _GetLongMonthLocale($iMonth), $iDay, $iYear) & @LF)\n\n\nFunc _GetLongDayLocale($_iWeekDay) ; 1..7 Monday=1\n\tLocal $aDayName[8] = [0, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30]\n\tReturn GetLocaleInfo($aDayName[$_iWeekDay])\nEndFunc\n\nFunc _GetLongMonthLocale($_iMonth) ; 1..12 January=1\n\tLocal $aMonthName[13] = [0, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43]\n\tReturn GetLocaleInfo($aMonthName[$_iMonth])\nEndFunc\n\nFunc GetLocaleInfo($_LCType)\n\tLocal $ret, $LCID, $sBuffer, $iLen\n\t$ret = DllCall('kernel32', 'long', 'GetSystemDefaultLCID')\n\t$LCID = $ret[0]\n\t$ret = DllCall('kernel32', 'long', 'GetLocaleInfo', 'long', $LCID, 'long', $_LCType, 'str', $sBuffer, 'long', 0)\n\t$iLen = $ret[0]\n\t$ret = DllCall('kernel32', 'long', 'GetLocaleInfo', 'long', $LCID, 'long', $_LCType, 'str', $sBuffer, 'long', $iLen)\n\tReturn $ret[3]\nEndFunc\n", "language": "AutoIt" }, { "code": "$ awk 'BEGIN{t=systime();print strftime(\"%Y-%m-%d\",t)\"\\n\"strftime(\"%A, %B %d, %Y\",t)}'\n2009-05-15\nFriday, May 15, 2009\n", "language": "AWK" }, { "code": "' Date format\nn = NOW\nPRINT YEAR(n), MONTH(n), DAY(n) FORMAT \"%ld-%02ld-%02ld\\n\"\nPRINT WEEKDAY$(n), MONTH$(n), DAY(n), YEAR(n) FORMAT \"%s, %s %02ld, %ld\\n\"\n", "language": "BaCon" }, { "code": "#include \"vbcompat.bi\"\n\nDIM today As Double = Now()\n\nPRINT Format(today, \"yyyy-mm-dd\")\nPRINT Format(today, \"dddd, mmmm d, yyyy\")\n", "language": "BASIC" }, { "code": "@echo off\nsetlocal enabledelayedexpansion\n\n:: Define arrays of days/months we'll need\nset daynames=Monday Tuesday Wednesday Thursday Friday Saturday Sunday\nset monthnames=January February March April May June July August September October November December\n\n:: Separate the output of the 'date /t' command (outputs in the format of \"Sun 16/04/2017\") into 4 variables\nfor /f \"tokens=1,2,3,4 delims=/ \" %%i in ('date /t') do (\n set dayname=%%i\n set day=%%j\n set month=%%k\n set year=%%l\n)\n\n:: Crosscheck the first 3 letters of every word in %daynames% to the 3 letter day name found previously\nfor %%i in (%daynames%) do (\n set tempdayname=%%i\n set comparedayname=!tempdayname:~0,3!\n if \"%dayname%\"==\"!comparedayname!\" set fulldayname=%%i\n)\n\n:: Variables starting with \"0\" during the 'set /a' command are treated as octal numbers. To avoid this, if the first character of %month% is \"0\", it is removed\nif \"%month:~0,1%\"==\"0\" set monthtemp=%month:~1,1%\nset monthcount=0\n\n:: Iterates through %monthnames% and when it reaches the amount of iterations dictated by %month%, sets %monthname% as the current month being iterated through\nfor %%i in (%monthnames%) do (\n set /a monthcount+=1\n if %monthtemp%==!monthcount! set monthname=%%i\n)\n\necho %year%-%month%-%day%\necho %fulldayname%, %monthname% %day%, %year%\npause>nul\n", "language": "Batch-File" }, { "code": " daysow$ = \"Sunday Monday Tuesday Wednesday Thursday Friday Saturday\"\n months$ = \"January February March April May June \" + \\\n \\ \"July August September October November December\"\n\n date$ = TIME$\n dayow% = (INSTR(daysow$, MID$(date$,1,3)) + 9) DIV 10\n month% = (INSTR(months$, MID$(date$,8,3)) + 9) DIV 10\n\n PRINT MID$(date$,12,4) \"-\" RIGHT$(\"0\"+STR$month%,2) + \"-\" + MID$(date$,5,2)\n\n PRINT FNrtrim(MID$(daysow$, dayow%*10-9, 10)) \", \" ;\n PRINT FNrtrim(MID$(months$, month%*10-9, 10)) \" \" ;\n PRINT MID$(date$,5,2) \", \" MID$(date$,12,4)\n END\n\n DEF FNrtrim(A$)\n WHILE RIGHT$(A$) = \" \" A$ = LEFT$(A$) : ENDWHILE\n = A$\n", "language": "BBC-BASIC" }, { "code": "beads 1 program 'Date format'\n\ncalc main_init\n\tlog time_to_str('[iso date]')\n\tlog time_to_str('[sunday], [january] [day2], [year]')\n", "language": "Beads" }, { "code": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#define MAX_BUF 50\n\nint main(void)\n{\n char buf[MAX_BUF];\n time_t seconds = time(NULL);\n struct tm *now = localtime(&seconds);\n const char *months[] = {\"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"};\n\n const char *days[] = {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\"};\n\n (void) printf(\"%d-%d-%d\\n\", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday);\n (void) printf(\"%s, %s %d, %d\\n\",days[now->tm_wday], months[now->tm_mon],\n now->tm_mday, now->tm_year + 1900);\n /* using the strftime (the result depends on the locale) */\n (void) strftime(buf, MAX_BUF, \"%A, %B %e, %Y\", now);\n (void) printf(\"%s\\n\", buf);\n return EXIT_SUCCESS;\n}\n", "language": "C" }, { "code": "// Display the current date in the formats of \"2007-11-10\"\n// and \"Sunday, November 10, 2007\".\n\n#include <vector>\n#include <string>\n#include <iostream>\n#include <ctime>\n\n/** Return the current date in a string, formatted as either ISO-8601\n * or \"Weekday-name, Month-name Day, Year\".\n *\n * The date is initialized when the object is created and will return\n * the same date for the lifetime of the object. The date returned\n * is the date in the local timezone.\n */\nclass Date\n{\n struct tm ltime;\n\npublic:\n /// Default constructor.\n Date()\n {\n time_t t = time(0);\n localtime_r(&t, &ltime);\n }\n\n /** Return the date based on a format string. The format string is\n * fed directly into strftime(). See the strftime() documentation\n * for information on the proper construction of format strings.\n *\n * @param[in] fmt is a valid strftime() format string.\n *\n * @return a string containing the formatted date, or a blank string\n * if the format string was invalid or resulted in a string that\n * exceeded the internal buffer length.\n */\n std::string getDate(const char* fmt)\n {\n char out[200];\n size_t result = strftime(out, sizeof out, fmt, &ltime);\n return std::string(out, out + result);\n }\n\n /** Return the date in ISO-8601 date format.\n *\n * @return a string containing the date in ISO-8601 date format.\n */\n std::string getISODate() {return getDate(\"%F\");}\n\n /** Return the date formatted as \"Weekday-name, Month-name Day, Year\".\n *\n * @return a string containing the date in the specified format.\n */\n std::string getTextDate() {return getDate(\"%A, %B %d, %Y\");}\n};\n\nint main()\n{\n Date d;\n std::cout << d.getISODate() << std::endl;\n std::cout << d.getTextDate() << std::endl;\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\n\nnamespace RosettaCode.DateFormat\n{\n class Program\n {\n static void Main(string[] args)\n {\n DateTime today = DateTime.Now.Date;\n Console.WriteLine(today.ToString(\"yyyy-MM-dd\"));\n Console.WriteLine(today.ToString(\"dddd, MMMMM d, yyyy\"));\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(let [now (.getTime (java.util.Calendar/getInstance))\n f1 (java.text.SimpleDateFormat. \"yyyy-MM-dd\")\n f2 (java.text.SimpleDateFormat. \"EEEE, MMMM dd, yyyy\")]\n (println (.format f1 now))\n (println (.format f2 now)))\n", "language": "Clojure" }, { "code": " IDENTIFICATION DIVISION.\n PROGRAM-ID. Date-Format.\n\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n\n 01 Days-Area.\n 03 Days-Data.\n 05 FILLER PIC X(9) VALUE \"Monday\".\n 05 FILLER PIC X(9) VALUE \"Tuesday\".\n 05 FILLER PIC X(9) VALUE \"Wednesday\".\n 05 FILLER PIC X(9) VALUE \"Thursday\".\n 05 FILLER PIC X(9) VALUE \"Friday\".\n 05 FILLER PIC X(9) VALUE \"Saturday\".\n 05 FILLER PIC X(9) VALUE \"Sunday\".\n\n 03 Days-Values REDEFINES Days-Data.\n 05 Days-Table PIC X(9) OCCURS 7 TIMES.\n\n 01 Months-Area.\n 03 Months-Data.\n 05 FILLER PIC X(9) VALUE \"January\".\n 05 FILLER PIC X(9) VALUE \"February\".\n 05 FILLER PIC X(9) VALUE \"March\".\n 05 FILLER PIC X(9) VALUE \"April\".\n 05 FILLER PIC X(9) VALUE \"May\".\n 05 FILLER PIC X(9) VALUE \"June\".\n 05 FILLER PIC X(9) VALUE \"July\".\n 05 FILLER PIC X(9) VALUE \"August\".\n 05 FILLER PIC X(9) VALUE \"September\".\n 05 FILLER PIC X(9) VALUE \"October\".\n 05 FILLER PIC X(9) VALUE \"November\".\n 05 FILLER PIC X(9) VALUE \"December\".\n\n 03 Months-Values REDEFINES Months-Data.\n 05 Months-Table PIC X(9) OCCURS 12 TIMES.\n\n 01 Current-Date-Str.\n 03 Current-Year PIC X(4).\n 03 Current-Month PIC X(2).\n 03 Current-Day PIC X(2).\n\n 01 Current-Day-Of-Week PIC 9.\n\n PROCEDURE DIVISION.\n MOVE FUNCTION CURRENT-DATE (1:8) TO Current-Date-Str\n\n DISPLAY Current-Year \"-\" Current-Month \"-\" Current-Day\n\n ACCEPT Current-Day-Of-Week FROM DAY-OF-WEEK\n DISPLAY\n FUNCTION TRIM(\n Days-Table (FUNCTION NUMVAL(Current-Day-Of-Week)))\n \", \"\n FUNCTION TRIM(\n Months-Table (FUNCTION NUMVAL(Current-Month)))\n \" \"\n Current-Day\n \", \"\n Current-Year\n END-DISPLAY\n\n GOBACK\n .\n", "language": "COBOL" }, { "code": "date = new Date\n\nconsole.log date.toLocaleDateString 'en-GB',\n month: '2-digit'\n day: '2-digit'\n year: 'numeric'\n.split('/').reverse().join '-'\n\nconsole.log date.toLocaleDateString 'en-US',\n weekday: 'long'\n month: 'long'\n day: 'numeric'\n year: 'numeric'\n", "language": "CoffeeScript" }, { "code": "# JS does not have extensive formatting support out of the box. This code shows\n# how you could create a date formatter object.\nDateFormatter = ->\n weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']\n pad = (n) ->\n if n < 10\n \"0\" + n\n else\n n\n\n brief: (date) ->\n month = 1 + date.getMonth()\n \"#{date.getFullYear()}-#{pad month}-#{pad date.getDate()}\"\n\n verbose: (date) ->\n weekday = weekdays[date.getDay()]\n month = months[date.getMonth()]\n day = date.getDate()\n year = date.getFullYear();\n \"#{weekday}, #{month} #{day}, #{year}\"\n\nformatter = DateFormatter()\ndate = new Date()\nconsole.log formatter.brief(date)\nconsole.log formatter.verbose(date)\n", "language": "CoffeeScript" }, { "code": "<cfoutput>\n #dateFormat(Now(), \"YYYY-MM-DD\")#<br />\n #dateFormat(Now(), \"DDDD, MMMM DD, YYYY\")#\n</cfoutput>\n", "language": "ColdFusion" }, { "code": "(defconstant *day-names*\n #(\"Monday\" \"Tuesday\" \"Wednesday\" \"Thursday\" \"Friday\" \"Saturday\" \"Sunday\"))\n(defconstant *month-names*\n #(nil \"January\" \"February\" \"March\" \"April\" \"May\" \"June\" \"July\"\n \"August\" \"September\" \"October\" \"November\" \"December\"))\n\n(multiple-value-bind (sec min hour date month year day daylight-p zone) (get-decoded-time)\n (format t \"~4d-~2,'0d-~2,'0d~%\" year month date)\n (format t \"~a, ~a ~d, ~4d~%\"\n (aref *day-names* day) (aref *month-names* month) date year))\n", "language": "Common-Lisp" }, { "code": "(local-time:format-timestring nil (local-time:now) :format '(:year \"-\" (:month 2) \"-\" (:day 2)))\n;; => \"2019-11-13\"\n(local-time:format-timestring nil (local-time:now) :format '(:long-weekday \", \" :long-month #\\space (:day 2) \", \" :year))\n;; => \"Wednesday, November 13, 2019\"\n", "language": "Common-Lisp" }, { "code": "MODULE DateFormat;\nIMPORT StdLog, Dates;\n\nPROCEDURE Do*;\nVAR\n\td: Dates.Date;\n\tresp: ARRAY 64 OF CHAR;\nBEGIN\n\tDates.GetDate(d);\n\tDates.DateToString(d,Dates.short,resp);\n\tStdLog.String(\":> \" + resp);StdLog.Ln;\n\tDates.DateToString(d,Dates.abbreviated,resp);\n\tStdLog.String(\":> \" + resp);StdLog.Ln;\n\tDates.DateToString(d,Dates.long,resp);\n\tStdLog.String(\":> \" + resp);StdLog.Ln;\n\tDates.DateToString(d,Dates.plainAbbreviated,resp);\n\tStdLog.String(\":> \" + resp);StdLog.Ln;\n\tDates.DateToString(d,Dates.plainLong,resp);\n\tStdLog.String(\":> \" + resp);StdLog.Ln;\nEND Do;\nEND DateFormat.\n", "language": "Component-Pascal" }, { "code": "require \"time\"\n\ntime = Time.local\nputs time.to_s(\"%Y-%m-%d\")\nputs time.to_s(\"%A, %B %d, %Y\")\n", "language": "Crystal" }, { "code": "module datetimedemo ;\n\nimport tango.time.Time ;\nimport tango.text.locale.Locale ;\nimport tango.time.chrono.Gregorian ;\n\nimport tango.io.Stdout ;\n\nvoid main() {\n Gregorian g = new Gregorian ;\n Stdout.layout = new Locale; // enable Stdout to handle date/time format\n Time d = g.toTime(2007, 11, 10, 0, 0, 0, 0, g.AD_ERA) ;\n Stdout.format(\"{:yyy-MM-dd}\", d).newline ;\n Stdout.format(\"{:dddd, MMMM d, yyy}\", d).newline ;\n d = g.toTime(2008, 2, 1, 0, 0, 0, 0, g.AD_ERA) ;\n Stdout.format(\"{:dddd, MMMM d, yyy}\", d).newline ;\n}\n", "language": "D" }, { "code": "ShowMessage(FormatDateTime('yyyy-mm-dd', Now) +#13#10+ FormatDateTime('dddd, mmmm dd, yyyy', Now));\n", "language": "Delphi" }, { "code": "me_lang(en)_cal(gregorian);\nme_msg()_now()_format(yyyy-mm-dd);\nme_msg()_now()_format(eeee, mmmm dd, yyyy);\n", "language": "Diego" }, { "code": "// 2012-09-26\nSysLib.writeStdout(StrLib.formatDate(DateTimeLib.currentDate(), \"yyyy-MM-dd\"));\n// Wednesday, September 26, 2012\nSysLib.setLocale(\"en\", \"US\");\nSysLib.writeStdout(StrLib.formatDate(DateTimeLib.currentDate(), \"EEEE, MMMM dd, yyyy\"));\n", "language": "EGL" }, { "code": "defmodule Date_format do\n def iso_date, do: Date.utc_today |> Date.to_iso8601\n\n def iso_date(year, month, day), do: Date.from_erl!({year, month, day}) |> Date.to_iso8601\n\n def long_date, do: Date.utc_today |> long_date\n\n def long_date(year, month, day), do: Date.from_erl!({year, month, day}) |> long_date\n\n @months Enum.zip(1..12, ~w[January February March April May June July August September October November December])\n |> Map.new\n @weekdays Enum.zip(1..7, ~w[Monday Tuesday Wednesday Thursday Friday Saturday Sunday])\n |> Map.new\n def long_date(date) do\n weekday = Date.day_of_week(date)\n \"#{@weekdays[weekday]}, #{@months[date.month]} #{date.day}, #{date.year}\"\n end\nend\n\nIO.puts Date_format.iso_date\nIO.puts Date_format.long_date\nIO.puts Date_format.iso_date(2007,11,10)\nIO.puts Date_format.long_date(2007,11,10)\n", "language": "Elixir" }, { "code": "(format-time-string \"%Y-%m-%d\")\n(format-time-string \"%F\") ;; new in Emacs 24\n;; => \"2015-11-08\"\n\n(format-time-string \"%A, %B %e, %Y\")\n;; => \"Sunday, November 8, 2015\"\n", "language": "Emacs-Lisp" }, { "code": "-module(format_date).\n-export([iso_date/0, iso_date/1, iso_date/3, long_date/0, long_date/1, long_date/3]).\n-import(calendar,[day_of_the_week/1]).\n-import(io,[format/2]).\n-import(lists,[append/1]).\n\niso_date() -> iso_date(date()).\niso_date(Year, Month, Day) -> iso_date({Year, Month, Day}).\niso_date(Date) ->\n format(\"~4B-~2..0B-~2..0B~n\", tuple_to_list(Date)).\n\nlong_date() -> long_date(date()).\nlong_date(Year, Month, Day) -> long_date({Year, Month, Day}).\nlong_date(Date = {Year, Month, Day}) ->\n Months = { \"January\", \"February\", \"March\", \"April\",\n \"May\", \"June\", \"July\", \"August\",\n \"September\", \"October\", \"November\", \"December\" },\n Weekdays = { \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n \"Friday\", \"Saturday\", \"Sunday\" },\n Weekday = day_of_the_week(Date),\n WeekdayName = element(Weekday, Weekdays),\n MonthName = element(Month, Months),\n append([WeekdayName, \", \", MonthName, \" \", integer_to_list(Day), \", \",\n integer_to_list(Year)]).\n", "language": "Erlang" }, { "code": "constant days = {\"Sunday\",\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\"}\nconstant months = {\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\n \"July\",\"August\",\"September\",\"October\",\"November\",\"December\"}\n\nsequence now\n\nnow = date()\nnow[1] += 1900\n\nprintf(1,\"%d-%02d-%02d\\n\",now[1..3])\nprintf(1,\"%s, %s %d, %d\\n\",{days[now[7]],months[now[2]],now[3],now[1]})\n", "language": "Euphoria" }, { "code": "> open System;;\n> Console.WriteLine( DateTime.Now.ToString(\"yyyy-MM-dd\") );;\n2010-08-13\n> Console.WriteLine( \"{0:D}\", DateTime.Now );;\nFriday, August 13, 2010\n", "language": "F-Sharp" }, { "code": "USING: formatting calendar io ;\n\nnow \"%Y-%m-%d\" strftime print\nnow \"%A, %B %d, %Y\" strftime print\n", "language": "Factor" }, { "code": "fansh> Date.today.toLocale(\"YYYY-MM-DD\")\n2011-02-24\nfansh> Date.today.toLocale(\"WWWW, MMMM DD, YYYY\")\nThursday, February 24, 2011\n", "language": "Fantom" }, { "code": ": .-0 ( n -- n )\n [char] - emit\n dup 10 < if [char] 0 emit then ;\n\n: .short-date\n time&date ( s m h D M Y )\n 1 u.r .-0 1 u.r .-0 1 u.r\n drop drop drop ;\n\n: str-table\n create ( n -- ) 0 do , loop\n does> ( n -- str len ) swap cells + @ count ;\n\n here ,\" December\"\n here ,\" November\"\n here ,\" October\"\n here ,\" September\"\n here ,\" August\"\n here ,\" July\"\n here ,\" June\"\n here ,\" May\"\n here ,\" April\"\n here ,\" March\"\n here ,\" February\"\n here ,\" January\"\n12 str-table months\n\n here ,\" Sunday\"\n here ,\" Saturday\"\n here ,\" Friday\"\n here ,\" Thursday\"\n here ,\" Wednesday\"\n here ,\" Tuesday\"\n here ,\" Monday\"\n7 str-table weekdays\n\n\\ Zeller's Congruence\n: zeller ( m -- days since March 1 )\n 9 + 12 mod 1- 26 10 */ 3 + ;\n\n: weekday ( d m y -- 0..6 ) \\ Monday..Sunday\n over 3 < if 1- then\n dup 4 /\n over 100 / -\n over 400 / + +\n swap zeller + +\n 1+ 7 mod ;\n\n: 3dup dup 2over rot ;\n\n: .long-date\n time&date ( s m h D M Y )\n 3dup weekday weekdays type .\" , \"\n >R 1- months type space 1 u.r .\" , \" R> .\n drop drop drop ;\n", "language": "Forth" }, { "code": "\\ Build up a \"language\" for date formatting\n\n\\ utility words\n: UNDER+ ( a b c -- a+c b ) ROT + SWAP ;\n: 3DUP ( a b c -- a b c a b c ) 2 PICK 2 PICK 2 PICK ;\n: WRITE$ ( caddr -- ) COUNT TYPE ; \\ print a counted string\n: ',' ( -- ) .\" , \" ;\n: '-' ( -- ) .\" -\" ;\n\n\\ day of week calculation\n\\ \"This is an algorithm I've carried with me for 35 years,\n\\ originally in Assembler and Fortran II.\"\n\\ It counts the number of days from March 1, 1900.\"\n\\ Wil Baden R.I.P.\n\\ *****************************************************\n\\ **WARNING** only good until 2078 on 16 bit machine **\n\\ *****************************************************\nDECIMAL\n: CDAY ( dd mm yyyy -- century_day )\n -3 UNDER+ OVER 0<\n IF 12 UNDER+ 1- THEN\n 1900 - 1461 4 */ SWAP 306 * 5 + 10 / + + ;\n\n: DOW ( cday -- day_of_week ) 2 + 7 MOD 1+ ; ( 7 is Sunday)\n\n\\ formatted number printers\n: ##. ( n -- ) 0 <# # # #> TYPE ;\n: ####. ( n -- ) 0 <# # # # # #> TYPE ;\n\n\\ make some string list words\n: LIST[ ( -- ) !CSP 0 C, ; \\ list starts with 0 bytes, record stack pos.\n: ]LIST ( -- ) 0 C, ALIGN ?CSP ; \\ '0' ends list, check stack\n\n: NEXT$ ( $[1] -- $[2] ) COUNT + ; \\ get next string\n: NTH$ ( n list -- $addr ) SWAP 0 DO NEXT$ LOOP ; \\ get nth string\n\n: \" ( -- ) [CHAR] \" WORD C@ CHAR+ ALLOT ; \\ compile text upto \"\n\n\\ make the lists\nCREATE MONTHS\n LIST[ \" January\" \" February\" \" March\" \" April\" \" May\" \" June\" \" July\"\n \" August\" \" September\" \" October\" \" November\" \" December\" ]LIST\n\nCREATE DAYS\n LIST[ \" Monday\" \" Tuesday\" \" Wednesday\" \" Thursday\"\n \" Friday\" \" Saturday\" \" Sunday\" ]LIST\n\n\\ expose lists as indexable arrays that print the string\n: ]MONTH$. ( n -- ) MONTHS NTH$ WRITE$ ;\n: ]DAY$. ( n -- ) DAYS NTH$ WRITE$ ;\n\n\n\\ ===========================================\n\\ Rosetta Task Code Begins\n\n\\ Rosetta Date Format 1\n: Y-M-D. ( d m y -- ) ####. '-' ##. '-' ##. ;\n\n\\ Rosetta Date Format 2\n: LONG.DATE ( d m y -- )\n 3DUP CDAY DOW ]DAY$. ',' -ROT ]MONTH$. SPACE ##. ',' ####. ;\n", "language": "Forth" }, { "code": " 5 7 2018 Y-M-D. 2018-07-05 ok\n ok\n5 7 2018 LONG.DATE Thursday, July 05, 2018 ok\n", "language": "Forth" }, { "code": "PROGRAM DATE\n\n IMPLICIT NONE\n\n INTEGER :: dateinfo(8), day\n CHARACTER(9) :: month, dayname\n\n CALL DATE_AND_TIME(VALUES=dateinfo)\n SELECT CASE(dateinfo(2))\n CASE(1)\n month = \"January\"\n CASE(2)\n month = \"February\"\n CASE(3)\n month = \"March\"\n CASE(4)\n month = \"April\"\n CASE(5)\n month = \"May\"\n CASE(6)\n month = \"June\"\n CASE(7)\n month = \"July\"\n CASE(8)\n month = \"August\"\n CASE(9)\n month = \"September\"\n CASE(10)\n month = \"October\"\n CASE(11)\n month = \"November\"\n CASE(12)\n month = \"December\"\n END SELECT\n\n day = Day_of_week(dateinfo(3), dateinfo(2), dateinfo(1))\n\n SELECT CASE(day)\n CASE(0)\n dayname = \"Saturday\"\n CASE(1)\n dayname = \"Sunday\"\n CASE(2)\n dayname = \"Monday\"\n CASE(3)\n dayname = \"Tuesday\"\n CASE(4)\n dayname = \"Wednesday\"\n CASE(5)\n dayname = \"Thursday\"\n CASE(6)\n dayname = \"Friday\"\n END SELECT\n\n WRITE(*,\"(I0,A,I0,A,I0)\") dateinfo(1),\"-\", dateinfo(2),\"-\", dateinfo(3)\n WRITE(*,\"(4(A),I0,A,I0)\") trim(dayname), \", \", trim(month), \" \", dateinfo(3), \", \", dateinfo(1)\n\nCONTAINS\n\n FUNCTION Day_of_week(d, m, y)\n INTEGER :: Day_of_week, j, k\n INTEGER, INTENT(IN) :: d, m, y\n\n j = y / 100\n k = MOD(y, 100)\n Day_of_week = MOD(d + (m+1)*26/10 + k + k/4 + j/4 + 5*j, 7)\n END FUNCTION Day_of_week\n\nEND PROGRAM DATE\n", "language": "Fortran" }, { "code": "program Format_Date_Time;\nuses\n SysUtils;\nbegin\n WriteLn(FormatDateTime('yyyy-mm-dd', Now) +#13#10+ FormatDateTime('dddd, mmmm dd, yyyy', Now));\nend.\n", "language": "Free-Pascal-Lazarus" }, { "code": "' FB 1.05.0 Win64\n\n#Include \"vbcompat.bi\"\n\nDim d As Long = Now\nPrint \"This example was created on : \"; Format(d, \"yyyy-mm-dd\")\nPrint \"In other words on : \"; Format(d, \"dddd, mmmm d, yyyy\")\nPrint\nPrint \"Press any key to quit the program\"\nSleep\n", "language": "FreeBASIC" }, { "code": "println[now[] -> ### yyyy-MM-dd ###]\nprintln[now[] -> ### EEEE, MMMM d, yyyy ###]\n", "language": "Frink" }, { "code": "println( format('%tF', $date) )\nprintln( format('%1$tA, %1$tB %1$td, %1$tY', $date) )\n", "language": "FunL" }, { "code": "window 1\n\nprint date(@\"yyyy-MM-dd\")\nprint date(@\"EEEE, MMMM dd, yyyy\")\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\n\nPrint Format(Now, \"yyyy - mm - dd\")\nPrint Format(Now, \"dddd, mmmm dd, yyyy\")\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport \"time\"\nimport \"fmt\"\n\nfunc main() {\n fmt.Println(time.Now().Format(\"2006-01-02\"))\n fmt.Println(time.Now().Format(\"Monday, January 2, 2006\"))\n}\n", "language": "Go" }, { "code": "def isoFormat = { date -> date.format(\"yyyy-MM-dd\") }\ndef longFormat = { date -> date.format(\"EEEE, MMMM dd, yyyy\") }\n", "language": "Groovy" }, { "code": "def now = new Date()\nprintln isoFormat(now)\nprintln longFormat(now)\n", "language": "Groovy" }, { "code": "import Data.Time\n (FormatTime, formatTime, defaultTimeLocale, utcToLocalTime,\n getCurrentTimeZone, getCurrentTime)\n\nformats :: FormatTime t => [t -> String]\nformats = (formatTime defaultTimeLocale) <$> [\"%F\", \"%A, %B %d, %Y\"]\n\nmain :: IO ()\nmain = do\n t <- pure utcToLocalTime <*> getCurrentTimeZone <*> getCurrentTime\n putStrLn $ unlines (formats <*> pure t)\n", "language": "Haskell" }, { "code": " CHARACTER string*40\n\n WRITE(Text=string, Format='UCCYY-MM-DD') 0 ! string: 2010-03-13\n\n ! the U-format to write date and time uses ',' to separate additional output formats\n ! we therefore use ';' in this example and change it to ',' below:\n WRITE(Text=string,Format='UWWWWWWWWW; MM DD; CCYY') 0 ! string = \"Saturday ; 03 13; 2010\"\n READ(Text=string) month ! first numeric value = 3 (no literal month name available)\n EDIT(Text='January,February,March,April,May,June,July,August,September,October,November,December', ITeM=month, Parse=cMonth) ! cMonth = \"March\"\n ! change now string = \"Saturday ; 03 13; 2010\" to \"Saturday, March 13, 2010\":\n EDIT(Text=string, Right=' ', Mark1, Right=';', Right=3, Mark2, Delete, Insert=', '//cMonth, Right=';', RePLaceby=',')\n\n END\n", "language": "HicEst" }, { "code": "procedure main()\nwrite(map(&date,\"/\",\"-\"))\nwrite(&dateline ? tab(find(&date[1:5])+4))\nend\n", "language": "Icon" }, { "code": " 6!:0 'YYYY-MM-DD'\n2010-08-19\n", "language": "J" }, { "code": "require 'dates system/packages/misc/datefmt.ijs'\ndays=:;:'Sunday Monday Tuesday Wednesday Thursday Friday Saturday'\nfmtDate=: [:((days ;@{~ weekday),', ',ms0) 3 {.]\n\n fmtDate 6!:0 ''\nThursday, August 19, 2010\n", "language": "J" }, { "code": "public static void main(String[] args) {\n long millis = System.currentTimeMillis();\n System.out.printf(\"%tF%n\", millis);\n System.out.printf(\"%tA, %1$tB %1$td, %1$tY%n\", millis);\n}\n", "language": "Java" }, { "code": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\nimport java.text.DateFormatSymbols;\nimport java.text.DateFormat;\npublic class Dates{\n public static void main(String[] args){\n Calendar now = new GregorianCalendar(); //months are 0 indexed, dates are 1 indexed\n DateFormatSymbols symbols = new DateFormatSymbols(); //names for our months and weekdays\n\n //plain numbers way\n System.out.println(now.get(Calendar.YEAR) + \"-\" + (now.get(Calendar.MONTH) + 1) + \"-\" + now.get(Calendar.DATE));\n\n //words way\n System.out.print(symbols.getWeekdays()[now.get(Calendar.DAY_OF_WEEK)] + \", \");\n System.out.print(symbols.getMonths()[now.get(Calendar.MONTH)] + \" \");\n System.out.println(now.get(Calendar.DATE) + \", \" + now.get(Calendar.YEAR));\n }\n}\n", "language": "Java" }, { "code": "import java.time.LocalDate;\nimport java.time.format.DateTimeFormatter;\npublic class Dates\n{\n public static void main(final String[] args)\n {\n //using DateTimeFormatter\n LocalDate date = LocalDate.now();\n DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern(\"yyyy MM dd\");\n\n System.out.println(dtFormatter.format(date));\n }\n}\n", "language": "Java" }, { "code": "import java.text.SimpleDateFormat;\nimport java.util.Date;\n\npublic class DateFormat {\n public static void main(String[]args){\n SimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\");\n SimpleDateFormat formatLong = new SimpleDateFormat(\"EEEE, MMMM dd, yyyy\");\n System.out.println(format.format(new Date()));\n System.out.println(formatLong.format(new Date()));\n }\n}\n", "language": "Java" }, { "code": "var now = new Date(),\n weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],\n months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],\n fmt1 = now.getFullYear() + '-' + (1 + now.getMonth()) + '-' + now.getDate(),\n fmt2 = weekdays[now.getDay()] + ', ' + months[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear();\nconsole.log(fmt1);\nconsole.log(fmt2);\n", "language": "JavaScript" }, { "code": "DEFINE weekdays == [\"Monday\" \"Tuesday\" \"Wednesday\" \"Thursday\" \"Friday\" \"Saturday\" \"Sunday\"];\n months == [\"January\" \"February\" \"March\" \"April\" \"May\" \"June\" \"July\" \"August\"\n \"September\" \"October\" \"November\" \"December\" ].\n\ntime localtime [[0 at 'd 4 4 format] [\"-\"] [1 at 'd 2 2 format] [\"-\"] [2 at 'd 2 2 format]]\n[i] map [putchars] step '\\n putch pop.\n\ntime localtime [[8 at pred weekdays of] [\", \"] [1 at pred months of] [\" \"] [2 at 'd 1 1 format]\n[\", \"] [0 at 'd 4 4 format]] [i] map [putchars] step '\\n putch pop.\n", "language": "Joy" }, { "code": "$ jq -n 'now | (strftime(\"%Y-%m-%d\"), strftime(\"%A, %B %d, %Y\"))'\n\"2015-07-02\"\n\"Thursday, July 02, 2015\"\n", "language": "Jq" }, { "code": "ts = Dates.today()\n\nprintln(\"Today's date is:\")\nprintln(\"\\t$ts\")\nprintln(\"\\t\", Dates.format(ts, \"E, U dd, yyyy\"))\n", "language": "Julia" }, { "code": "// version 1.0.6\n\nimport java.util.GregorianCalendar\n\nfun main(args: Array<String>) {\n val now = GregorianCalendar()\n println(\"%tF\".format(now))\n println(\"%tA, %1\\$tB %1\\$te, %1\\$tY\".format(now))\n}\n", "language": "Kotlin" }, { "code": "var .now = dt//\nvar .format1 = \"2006-01-02\"\nvar .format2 = \"Monday, January 2, 2006\"\nwriteln $\"\\.now:dt.format1;\"\nwriteln $\"\\.now:dt.format2;\"\n", "language": "Langur" }, { "code": "var .now = dt//\nwriteln $\"\\.now:dt(2006-01-02);\"\nwriteln $\"\\.now:dt(Monday, January 2, 2006);\"\n", "language": "Langur" }, { "code": "writeln string dt//, \"2006-01-02\"\nwriteln string dt//, \"Monday, January 2, 2006\"\n", "language": "Langur" }, { "code": "date('11/10/2007')->format('%Q') // 2007-11-10\ndate('11/10/2007')->format('EEEE, MMMM d, YYYY') //Saturday, November 10, 2007\n", "language": "Lasso" }, { "code": "'Display the current date in the formats of \"2007-11-10\"\nd$=date$(\"yyyy/mm/dd\")\nprint word$(d$,1,\"/\")+\"-\"+word$(d$,2,\"/\")+\"-\"+word$(d$,3,\"/\")\n\n'and \"Sunday, November 10, 2007\".\nday$(0)=\"Tuesday\"\nday$(1)=\"Wednesday\"\nday$(2)=\"Thursday\"\nday$(3)=\"Friday\"\nday$(4)=\"Saturday\"\nday$(5)=\"Sunday\"\nday$(6)=\"Monday\"\ntheDay = date$(\"days\") mod 7\nprint day$(theDay);\", \";date$()\n\n' month in full\nyear=val(word$(d$,1,\"/\"))\nmonth=val(word$(d$,2,\"/\"))\nday=val(word$(d$,3,\"/\"))\nweekDay$=\"Tuesday Wednesday Thursday Friday Saturday Sunday Monday\"\nmonthLong$=\"January February March April May June July August September October November December\"\n\nprint word$(weekDay$,theDay+1);\", \";word$(monthLong$,month);\" \";day;\", \";year\n", "language": "Liberty-BASIC" }, { "code": "on mouseUp pButtonNumber\n put the date into tDate\n convert tDate to dateItems\n put item 1 of tDate & \"-\" & item 2 of tDate & \"-\" & item 3 of tDate & return into tMyFormattedDate\n put tMyFormattedDate & the long date\nend mouseUp\n", "language": "LiveCode" }, { "code": "print first shell [date +%F]\nprint first shell [date +\"%A, %B %d, %Y\"]\n", "language": "Logo" }, { "code": "print( os.date( \"%Y-%m-%d\" ) )\nprint( os.date( \"%A, %B %d, %Y\" ) )\n", "language": "Lua" }, { "code": "Print str$(today, \"yyyy-mm-dd\")\nPrint str$(today, \"dddd, mmm, dd, yyyy\")\n", "language": "M2000-Interpreter" }, { "code": "with(StringTools);\nFormatTime(\"%Y-%m-%d\")\nFormatTime(\"%A,%B %d, %y\")\n", "language": "Maple" }, { "code": "DateString[{\"Year\", \"-\", \"Month\", \"-\", \"Day\"}]\nDateString[{\"DayName\", \", \", \"MonthName\", \" \", \"Day\", \", \", \"Year\"}]\n", "language": "Mathematica" }, { "code": ">> datestr(now,'yyyy-mm-dd')\n\nans =\n\n2010-06-18\n\n>> datestr(now,'dddd, mmmm dd, yyyy')\n\nans =\n\nFriday, June 18, 2010\n", "language": "MATLAB" }, { "code": "(\"YYYY-MM-dd\" \"dddd, MMMM dd, YYYY\") ('timestamp dip tformat puts!) foreach\n", "language": "Min" }, { "code": "import \"dateTime\"\n\nprint dateTime.now(\"yyyy-MM-dd\")\nprint dateTime.now(\"dddd, MMMM d, yyyy\")\n", "language": "MiniScript" }, { "code": "echo -ag $time(yyyy-mm-dd)\necho -ag $time(dddd $+ $chr(44) mmmm dd $+ $chr(44) yyyy)\n", "language": "MIRC-Scripting-Language" }, { "code": "DTZ\n WRITE !,\"Date format 3: \",$ZDATE($H,3)\n WRITE !,\"Or \",$ZDATE($H,12),\", \",$ZDATE($H,9)\n QUIT\n", "language": "MUMPS" }, { "code": "DTM(H)\n ;You can pass an integer, but the default is to use today's value\n SET:$DATA(H)=0 H=$HOROLOG\n NEW Y,YR,RD,MC,MO,DA,MN,DN,DOW\n SET MN=\"January,February,March,April,May,June,July,August,September,October,November,December\"\n SET DN=\"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday\"\n SET MC=\"31,28,31,30,31,30,31,31,30,31,30,31\"\n SET Y=+H\\365.25 ;This shouldn't be an approximation in production code\n SET YR=Y+1841 ;Y is the offset from the epoch in years\n SET RD=((+H-(Y*365.25))+1)\\1 ;How far are we into the year?\n SET $P(MC,\",\",2)=$S(((YR#4=0)&(YR#100'=0))!((YR#100=0)&(YR#400=0))=0:28,1:29) ;leap year correction\n SET MO=1,RE=RD FOR QUIT:RE<=$P(MC,\",\",MO) SET RE=RE-$P(MC,\",\",MO),MO=MO+1\n SET DA=RE+1\n SET DOW=(H#7)+5 ;Fencepost issue - the first piece is 1\n ;add padding as needed\n SET:$L(MO)<2 MO=\"0\"_MO\n SET:$L(DA)<2 DA=\"0\"_DA\n WRITE !,YR,\"-\",MO,\"-\",DA\n WRITE !,$P(DN,\",\",DOW),\", \",$P(MN,\",\",MO),\" \",DA,\", \",YR\n KILL Y,YR,RD,MC,MO,DA,MN,DN,DOW\n QUIT\n", "language": "MUMPS" }, { "code": "import Nanoquery.Util\n\nd = new(Date)\nprintln d.getYear() + \"-\" + d.getMonth() + \"-\" + d.getDay()\nprintln d.getDayOfWeek() + \", \" + d.getMonthName() + \" \" + d.getDay() + \", \" + d.getYear()\n", "language": "Nanoquery" }, { "code": "/**\n <doc>\n <h2>Date format</h2>\n <p>Neko uses Int32 to store system date/time values.\n And lib C strftime style formatting for converting to string form</p>\n </doc>\n*/\n\nvar date_now = $loader.loadprim(\"std@date_now\", 0)\nvar date_format = $loader.loadprim(\"std@date_format\", 2)\n\nvar now = date_now()\n$print(date_format(now, \"%F\"), \"\\n\")\n$print(date_format(now, \"%A, %B %d, %Y\"), \"\\n\")\n", "language": "Neko" }, { "code": "import java.text.SimpleDateFormat\nsay SimpleDateFormat(\"yyyy-MM-dd\").format(Date())\nsay SimpleDateFormat(\"EEEE, MMMM dd, yyyy\").format(Date())\n", "language": "NetRexx" }, { "code": "; file: date-format.lsp\n; url: http://rosettacode.org/wiki/Date_format\n; author: oofoe 2012-02-01\n\n; The \"now\" function returns the current time as a list. A time zone\n; offset in minutes can be supplied. The example below is for Eastern\n; Standard Time. NewLISP's implicit list indexing is used to extract\n; the first three elements of the returned list (year, month and day).\n\n(setq n (now (* -5 60)))\n(println \"short: \" (format \"%04d-%02d-%02d\" (n 0) (n 1) (n 2)))\n\n; The \"date-value\" function returns the time in seconds from the epoch\n; when used without arguments. The \"date\" function converts the\n; seconds into a time representation specified by the format string at\n; the end. The offset argument (\"0\" in this example) specifies a\n; time-zone offset in minutes.\n\n(println \"short: \" (date (date-value) 0 \"%Y-%m-%d\"))\n\n; The time formatting is supplied by the underlying C library, so\n; there may be differences on certain platforms. Particularly, leading\n; zeroes in day numbers can be suppressed with \"%-d\" on Linux and\n; FreeBSD, \"%e\" on OpenBSD, SunOS/Solaris and Mac OS X. Use \"%#d\" for\n; Windows.\n\n(println \"long: \" (date (date-value) 0 \"%A, %B %#d, %Y\"))\n\n; By setting the locale, the date will be displayed appropriately:\n\n(set-locale \"japanese\")\n(println \"long: \" (date (date-value) 0 \"%A, %B %#d, %Y\"))\n\n(exit)\n", "language": "NewLISP" }, { "code": "import times\n\nvar t = now()\necho(t.format(\"yyyy-MM-dd\"))\necho(t.format(\"dddd',' MMMM d',' yyyy\"))\n", "language": "Nim" }, { "code": "use IO;\nuse Time;\n\nbundle Default {\n class CurrentDate {\n function : Main(args : String[]) ~ Nil {\n t := Date->New();\n Console->Print(t->GetYear())->Print(\"-\")->Print(t->GetMonth())->Print(\"-\")\n ->PrintLine(t->GetDay());\n Console->Print(t->GetDayName())->Print(\", \")->Print(t->GetMonthName())\n ->Print(\" \")->Print(t->GetDay())->Print(\", \")\n ->PrintLine(t->GetYear());\n }\n }\n}\n", "language": "Objeck" }, { "code": "NSLog(@\"%@\", [NSDate date]);\nNSLog(@\"%@\", [[NSDate date] descriptionWithCalendarFormat:@\"%Y-%m-%d\" timeZone:nil locale:nil]);\nNSLog(@\"%@\", [[NSDate date] descriptionWithCalendarFormat:@\"%A, %B %d, %Y\" timeZone:nil locale:nil]);\n", "language": "Objective-C" }, { "code": "NSLog(@\"%@\", [NSDate date]);\nNSDateFormatter *dateFormatter = [[NSDateFormat alloc] init];\n[dateFormatter setDateFormat:@\"yyyy-MM-dd\"];\nNSLog(@\"%@\", [dateFormatter stringFromDate:[NSDate date]]);\n[dateFormatter setDateFormat:@\"EEEE, MMMM d, yyyy\"];\nNSLog(@\"%@\", [dateFormatter stringFromDate:[NSDate date]]);\n", "language": "Objective-C" }, { "code": "# #load \"unix.cma\";;\n# open Unix;;\n\n# let t = time() ;;\nval t : float = 1219997516.\n\n# let gmt = gmtime t ;;\nval gmt : Unix.tm =\n {tm_sec = 56; tm_min = 11; tm_hour = 8; tm_mday = 29; tm_mon = 7;\n tm_year = 108; tm_wday = 5; tm_yday = 241; tm_isdst = false}\n\n# Printf.sprintf \"%d-%02d-%02d\" (1900 + gmt.tm_year) (1 + gmt.tm_mon) gmt.tm_mday ;;\n- : string = \"2008-08-29\"\n", "language": "OCaml" }, { "code": "let months = [| \"January\"; \"February\"; \"March\"; \"April\"; \"May\"; \"June\";\n \"July\"; \"August\"; \"September\"; \"October\"; \"November\"; \"December\" |]\n\nlet days = [| \"Sunday\"; \"Monday\"; \"Tuesday\"; (* Sunday is 0 *)\n \"Wednesday\"; \"Thursday\"; \"Friday\"; \"Saturday\" |]\n\n# Printf.sprintf \"%s, %s %d, %d\"\n days.(gmt.tm_wday)\n months.(gmt.tm_mon)\n gmt.tm_mday\n (1900 + gmt.tm_year) ;;\n- : string = \"Friday, August 29, 2008\"\n", "language": "OCaml" }, { "code": "/* REXX */\ndats='20071123'\nSay date('I',dats,'S')\nSay date('W',dats,'S')',' date('M',dats,'S') substr(dats,7,2)',' left(dats,4)\nSay date('W',dats,'S')',' date('M',dats,'S') translate('gh, abcd',dats,'abcdefgh')\ndati=date('I')\nSay dati\nSay date('W',dati,'I')',' date('M',dati,'I') translate('ij, abcd',dati,'abcdefghij')\n", "language": "OoRexx" }, { "code": "extern lib \"kernel32.dll\"\n\n'http://msdn.microsoft.com/en-us/library/windows/desktop/ms724950(v=vs.85).aspx\n\ntypedef struct _SYSTEMTIME {\n WORD wYear;\n WORD wMonth;\n WORD wDayOfWeek;\n WORD wDay;\n WORD wHour;\n WORD wMinute;\n WORD wSecond;\n WORD wMilliseconds;\n} SYSTEMTIME, *PSYSTEMTIME;\n\nvoid GetSystemTime(SYSTEMTIME*t);\nvoid GetLocalTime(SYSTEMTIME*t);\n\nend extern\n\nSYSTEMTIME t\n'GetSystemTime t 'GMT (Greenwich Mean Time)\nGetLocalTime t\n\nString WeekDay[7]={\"Sunday\",\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\"}\nString MonthName[12]={\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\",\"August\",\"September\",\"October\",\"November\",\"December\"}\nString month=str t.wMonth : if len(month)<2 then month=\"0\"+month\nString day=str t.wDay : if len(day)<2 then day=\"0\"+day\n'\nprint \"\" t.wYear \"-\" month \"-\" day\nprint WeekDay[t.wDayOfWeek+1 and 7 ] \" \" MonthName[t.wMonth and 31] \" \" t.wDay \" \" t.wYear\n", "language": "OxygenBasic" }, { "code": "declare\n WeekDays = unit(0:\"Sunday\" \"Monday\" \"Tuesday\" \"Wednesday\"\n \"Thursday\" \"Friday\" \"Saturday\")\n Months = unit(0:\"January\" \"February\" \"March\" \"April\"\n \"May\" \"June\" \"July\" \"August\" \"September\"\n \"October\" \"November\" \"December\")\n\n fun {DateISO Time}\n Year = 1900 + Time.year\n Month = Time.mon + 1\n in\n Year#\"-\"#{Align Month}#\"-\"#{Align Time.mDay}\n end\n\n fun {DateLong Time}\n Year = 1900 + Time.year\n in\n WeekDays.(Time.wDay)#\", \"#Months.(Time.mon)#\" \"#Time.mDay#\", \"#Year\n end\n\n fun {Align Num}\n if Num < 10 then \"0\"#Num else Num end\n end\nin\n {System.showInfo {DateISO {OS.localTime}}}\n {System.showInfo {DateLong {OS.localTime}}}\n", "language": "Oz" }, { "code": "program dateform;\nuses DOS;\n\n{ Format digit with leading zero }\nfunction lz(w: word): string;\nvar\n s: string;\nbegin\n str(w,s);\n if length(s) = 1 then\n s := '0' + s;\n lz := s\nend;\n\nfunction m2s(mon: integer): string;\nbegin\n case mon of\n 1: m2s := 'January';\n 2: m2s := 'February';\n 3: m2s := 'March';\n 4: m2s := 'April';\n 5: m2s := 'May';\n 6: m2s := 'June';\n 7: m2s := 'July';\n 8: m2s := 'August';\n 9: m2s := 'September';\n 10: m2s := 'October';\n 11: m2s := 'November';\n 12: m2s := 'December'\n end\nend;\n\nfunction d2s(dow: integer): string;\nbegin\n case dow of\n 0: d2s := 'Sunday';\n 1: d2s := 'Monday';\n 2: d2s := 'Tueday';\n 3: d2s := 'Wednesday';\n 4: d2s := 'Thursday';\n 5: d2s := 'Friday';\n 6: d2s := 'Saturday'\n end\nend;\n\nvar\n yr,mo,dy,dow: word;\n mname,dname: string;\n\nbegin\n GetDate(yr,mo,dy,dow);\n writeln(yr,'-',lz(mo),'-',lz(dy));\n mname := m2s(mo); dname := d2s(dow);\n writeln(dname,', ',mname,' ',dy,', ',yr)\nend.\n", "language": "Pascal" }, { "code": "use POSIX;\n\nprint strftime('%Y-%m-%d', 0, 0, 0, 10, 10, 107), \"\\n\";\nprint strftime('%A, %B %d, %Y', 0, 0, 0, 10, 10, 107), \"\\n\";\n", "language": "Perl" }, { "code": "use POSIX;\n\nprint strftime('%Y-%m-%d', localtime), \"\\n\";\nprint strftime('%A, %B %d, %Y', localtime), \"\\n\";\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">builtins</span><span style=\"color: #0000FF;\">\\</span><span style=\"color: #004080;\">timedate</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">format_timedate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">date</span><span style=\"color: #0000FF;\">(),</span><span style=\"color: #008000;\">\"YYYY-MM-DD\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">format_timedate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">date</span><span style=\"color: #0000FF;\">(),</span><span style=\"color: #008000;\">\"Dddd, Mmmm d, YYYY\"</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\necho date('Y-m-d', time()).\"\\n\";\necho date('l, F j, Y', time()).\"\\n\";\n?>\n", "language": "PHP" }, { "code": "(let (Date (date) Lst (date Date))\n (prinl (dat$ Date \"-\")) # 2010-02-19\n (prinl # Friday, February 19, 2010\n (day Date)\n \", \"\n (get *MonFmt (cadr Lst))\n \" \"\n (caddr Lst)\n \", \"\n (car Lst) ) )\n", "language": "PicoLisp" }, { "code": "object cal = Calendar.ISO.Day();\nwrite( cal->format_ymd() +\"\\n\" );\nstring special = sprintf(\"%s, %s %d, %d\",\n cal->week_day_name(),\n cal->month_name(),\n cal->month_day(),\n cal->year_no());\nwrite( special +\"\\n\" );\n", "language": "Pike" }, { "code": "df: proc Options(main);\n declare day_of_week(7) character (9) varying initial(\n 'Sunday','Monday','Tuesday','Wednesday',\n 'Thursday','Friday','Saturday');\n declare today character (9);\n\n today = datetime('YYYYMMDD');\n put edit(substr(today,1,4),'-',substr(today,5,2),'-',substr(today,7))\n (A);\n\n today = datetime('MmmDDYYYY');\n put skip edit(day_of_week(weekday(days())),', ') (A);\n put edit(substr(today,1,3),' ',substr(today,4,2),', ',\n substr(today,6,4))(A);\n end;\n", "language": "PL-I" }, { "code": " df: proc Options(Main);\n declare day_of_week(7) character(9) varying initial(\n 'Sunday','Monday','Tuesday','Wednesday',\n 'Thursday','Friday','Saturday');\n declare today character(8);\n declare month(12) character(10) varying initial(\n 'January','February','March','April','May','June','July',\n 'August','September','October','November','December');\n\n Put edit(translate('abcd-ef-gh',datetime('YYYYMMDD'),'abcdefgh'))(a);\n today = datetime('MMDDYYYY');\n\n put skip edit(day_of_week(weekday()),', ') (A);\n put edit(month(substr(today,1,2)),' ',substr(today,3,2),', ',\n substr(today,5,4))(A);\n End;\n", "language": "PL-I" }, { "code": "\"{0:yyyy-MM-dd}\" -f (Get-Date)\n\"{0:dddd, MMMM d, yyyy}\" -f (Get-Date)\n# or\n(Get-Date).ToString(\"yyyy-MM-dd\")\n(Get-Date).ToString(\"dddd, MMMM d, yyyy\")\n", "language": "PowerShell" }, { "code": "display_date :-\n get_time(Time),\n format_time(atom(Short), '%Y-%M-%d', Time),\n format_time(atom(Long), '%A, %B %d, %Y', Time),\n format('~w~n~w~n', [Short, Long]).\n", "language": "Prolog" }, { "code": ";Declare Procedures\nDeclare.s MonthInText()\nDeclare.s DayInText()\n\n;Output the requested strings\nDebug FormatDate(\"%yyyy-%mm-%dd\", Date())\nDebug DayInText() + \", \" + MonthInText() + FormatDate(\" %dd, %yyyy\", Date())\n\n;Used procedures\nProcedure.s DayInText()\n Protected d$\n Select DayOfWeek(Date())\n Case 1: d$=\"Monday\"\n Case 2: d$=\"Tuesday\"\n Case 3: d$=\"Wednesday\"\n Case 4: d$=\"Thursday\"\n Case 5: d$=\"Friday\"\n Case 6: d$=\"Saturday\"\n Default: d$=\"Sunday\"\n EndSelect\n ProcedureReturn d$\nEndProcedure\n\nProcedure.s MonthInText()\n Protected m$\n Select Month(Date())\n Case 1: m$=\"January\"\n Case 2: m$=\"February\"\n Case 3: m$=\"March\"\n Case 4: m$=\"April\"\n Case 5: m$=\"May\"\n Case 6: m$=\"June\"\n Case 7: m$=\"July\"\n Case 8: m$=\"August\"\n Case 9: m$=\"September\"\n Case 10:m$=\"October\"\n Case 11:m$=\"November\"\n Default:m$=\"December\"\n EndSelect\n ProcedureReturn m$\nEndProcedure\n", "language": "PureBasic" }, { "code": "import datetime\ntoday = datetime.date.today()\n# The first requested format is a method of datetime objects:\ntoday.isoformat()\n# For full flexibility, use the strftime formatting codes from the link above:\ntoday.strftime(\"%A, %B %d, %Y\")\n# This mechanism is integrated into the general string formatting system.\n# You can do this with positional arguments referenced by number\n\"The date is {0:%A, %B %d, %Y}\".format(d)\n# Or keyword arguments referenced by name\n\"The date is {date:%A, %B %d, %Y}\".format(date=d)\n# Since Python 3.6, f-strings allow the value to be inserted inline\nf\"The date is {d:%A, %B %d, %Y}\"\n", "language": "Python" }, { "code": "now <- Sys.time()\nstrftime(now, \"%Y-%m-%d\")\nstrftime(now, \"%A, %B %d, %Y\")\n", "language": "R" }, { "code": "#lang racket\n(require srfi/19)\n\n;;; The first required format is an ISO-8601 year-month-day format, predefined\n;;; as ~1 in date->string\n(displayln (date->string (current-date) \"~1\"))\n\n;;; You should be able to see how each of the components of the following format string\n;;; work...\n;;; ~d is zero padded day of month:\n(displayln (date->string (current-date) \"~A, ~B ~d, ~Y\"))\n;;; ~e is space padded day of month:\n(displayln (date->string (current-date) \"~A, ~B ~e, ~Y\"))\n", "language": "Racket" }, { "code": "use DateTime::Format;\n\nmy $dt = DateTime.now;\n\nsay strftime('%Y-%m-%d', $dt);\nsay strftime('%A, %B %d, %Y', $dt);\n", "language": "Raku" }, { "code": "my $d = Date.today;\n\nsay $d.yyyy-mm-dd;\n", "language": "Raku" }, { "code": "my @months = <January February March April May June July\n August September October November December>;\nmy @days = <Monday Tuesday Wednesday Thursday Friday Saturday Sunday>;\nmy $us-long = sub ($self) { \"{@days[$self.day-of-week - 1]}, {@months[$self.month - 1]} {$self.day}, {$self.year}\" };\nmy $d = Date.today :formatter($us-long);\n\nsay $d.yyyy-mm-dd; # still works\nsay $d; # uses our formatter sub\n", "language": "Raku" }, { "code": "time int as today\n", "language": "Raven" }, { "code": "today '%Y-%m-%d' date\n", "language": "Raven" }, { "code": "today '%A, %B %d, %Y' date\n", "language": "Raven" }, { "code": "REBOL [\n\tTitle: \"Date Formatting\"\n\tURL: http://rosettacode.org/wiki/Date_format\n]\n\n; REBOL has no built-in pictured output.\n\nzeropad: func [pad n][\n n: to-string n\n insert/dup n \"0\" (pad - length? n)\n n\n]\nd02: func [n][zeropad 2 n]\n\nprint now ; Native formatting.\n\nprint rejoin [now/year \"-\" d02 now/month \"-\" d02 now/day]\n\nprint rejoin [\n\tpick system/locale/days now/weekday \", \"\n\tpick system/locale/months now/month \" \"\n\tnow/day \", \" now/year\n]\n", "language": "REBOL" }, { "code": "Red []\n;; zeropad\nf2n: func [d] [ if d > 9 [return d ] append copy \"0\" d ]\n\nd: now/date\n\nprint rejoin [d/year \"-\" f2n d/month \"-\" f2n d/day]\nprint rejoin [system/locale/days/(d/weekday) \", \" system/locale/months/(d/month) \" \" f2n d/day \", \" d/year]\n", "language": "Red" }, { "code": "/*REXX pgm shows current date: yyyy-mm-dd & Dayofweek, Month dd, yyyy*/\n x = date('S') /*get current date as yyyymmdd */\nyyyy = left(x,4) /*pick off year (4 digs).*/\n dd = right(x,2) /*pick off day-of-month (2 digs).*/\n mm = substr(x,5,2) /*pick off month number (2 digs).*/\nsay yyyy'-'mm\"-\"dd /*yyyy-mm-dd with leading zeroes.*/\n\nweekday = date('W') /*dayofweek (Monday or somesuch).*/\nmonth = date('M') /*Month (August or somesuch).*/\nzdd = dd+0 /*remove leading zero from DD */\nsay weekday',' month zdd\",\" yyyy /*format date as: Month dd, yyyy*/\n /*stick a fork in it, we're done.*/\n", "language": "REXX" }, { "code": "/*REXX pgm shows current date: yyyy-mm-dd & Dayofweek, Month dd, yyyy*/\n/* ╔══════════════════════════════════════════════════════════════════╗\n ║ function returns a specific example ║\n ║ ─────────── ─────────────────────────── ──────────────────── ║\n ║ date() dd mon yyyy 3 Jun 2009 ║\n ║ date('N') (same as above) ║\n ║ date('B') days since Jan 1, year 1 735382 ║\n ║ date('C') days since Jan 1 this century 5264 ║\n ║ date('D') days since Jan 1, this yr 154 ║\n ║ date('E') dd/mm/yy 03/06/09 ║\n ║ date('I') yyyy-mm-dd 2009-03-06 ║\n ║ date('J') yyddd 2009154 ║\n ║ date('M') month name June ║\n ║ date('O') yy/mm/dd 09/03/06 ║\n ║ date('S') yyyyddmm 20090603 ║\n ║ date('T') seconds since Jan 1st, 1970 1401483686 ║\n ║ date('U') mm/dd/yy 03/06/09 ║\n ║ date('W') day─of─the─week Wednesday ║\n ║ ─────────── ─────────────────────────── ──────────────────── ║\n ║ ║\n ║ Note: not all of the above are supported by all REXX versions. ║\n ╚══════════════════════════════════════════════════════════════════╝ */\nparse value date('S') with yyyy 5 mm 7 dd /*get various pieces of date*/\nsay yyyy'-'mm\"-\"dd /*yyyy-mm-dd with leading zeroes.*/\n\nsay date('W')\",\" date('M') word(date(), 1)\",\" yyyy\n /* [↑] dayofweek Month dd, yyyy*/\n /*stick a fork in it, we're done.*/\n", "language": "REXX" }, { "code": "/*REXX pgm shows current date: yyyy-mm-dd & Dayofweek, Month dd, yyyy*/\nsay date('I') /*yyyy-mm-dd with leading zeroes.*/\n\nsay date('W')\",\" date('M') word(date(), 1)\",\" left(date('S'),4)\n /* [↑] dayofweek Month dd, yyyy*/\n /*stick a fork in it, we're done.*/\n", "language": "REXX" }, { "code": "dateStr = date()\ndate1 = timelist()[19] + \"-\" + timelist()[10] + \"-\" + timelist()[6]\ndate2 = timelist()[2] + \", \" + timelist()[4] + \" \" + timelist()[6] + \", \" + timelist()[19] + nl\n? dateStr\n? date1\n? date2\n\n/*\ntimelist() ---> List contains the time and date information.\nIndex Value\n----------------------------\n1 - abbreviated weekday name\n2 - full weekday name\n3 - abbreviated month name\n4 - full month name\n5 - Date & Time\n6 - Day of the month\n7 - Hour (24)\n8 - Hour (12)\n9 - Day of the year\n10 - Month of the year\n11 - Minutes after hour\n12 - AM or PM\n13 - Seconds after the hour\n14 - Week of the year (sun-sat)\n15 - day of the week\n16 - date\n17 - time\n18 - year of the century\n19 - year\n20 - time zone\n21 - percent sign\n*/\n", "language": "Ring" }, { "code": "puts Time.now\nputs Time.now.strftime('%Y-%m-%d')\nputs Time.now.strftime('%F') # same as %Y-%m-%d (ISO 8601 date formats)\nputs Time.now.strftime('%A, %B %d, %Y')\n", "language": "Ruby" }, { "code": "'Display the current date in the formats of \"2007-11-10\" and \"Sunday, November 10, 2007\".\nprint date$(\"yyyy-mm-dd\")\nprint date$(\"dddd\");\", \"; 'return full day of the week (eg. Wednesday\nprint date$(\"mmmm\");\" \"; 'return full month name (eg. March)\nprint date$(\"dd, yyyy\") 'return day, year\n", "language": "Run-BASIC" }, { "code": "fn main() {\n let now = chrono::Utc::now();\n println!(\"{}\", now.format(\"%Y-%m-%d\"));\n println!(\"{}\", now.format(\"%A, %B %d, %Y\"));\n}\n", "language": "Rust" }, { "code": "import java.util.Date\n\nval now=new Date()\nprintln(\"%tF\".format(now))\nprintln(\"%1$tA, %1$tB %1$td, %1$tY\".format(now))\n", "language": "Scala" }, { "code": "(define short-date\n (lambda (lt)\n (strftime \"%Y-%m-%d\" (localtime lt))))\n\n(define long-date\n (lambda (lt)\n (strftime \"%A, %B %d, %Y\" (localtime lt))))\n\n(define main\n (lambda (args)\n ;; Current date\n (let ((dt (car (gettimeofday))))\n ;; Short style\n (display (short-date dt))(newline)\n ;; Long style\n (display (long-date dt))(newline))))\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n include \"time.s7i\";\n\nconst proc: main is func\n local\n const array string: months is [] (\"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\");\n const array string: days is [] (\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\");\n var time: now is time.value;\n begin\n now := time(NOW);\n writeln(strDate(now));\n writeln(days[dayOfWeek(now)] <& \", \" <& months[now.month] <& \" \" <& now.day <& \", \" <& now.year);\n end func;\n", "language": "Seed7" }, { "code": "put formattedTime( \"[year]-[month]-[day]\", the date)\n\nput formattedTime( \"[weekday], [month name] [day], [year]\", the date)\n", "language": "SenseTalk" }, { "code": "say time.format 'Y-m-d' time.now\nsay time.format 'l, F j, Y' time.now\n", "language": "Shiny" }, { "code": "var time = Time.local;\nsay time.ctime;\nsay time.strftime(\"%Y-%m-%d\");\nsay time.strftime(\"%A, %B %d, %Y\");\n", "language": "Sidef" }, { "code": "| d |\nd := Date today.\nd printFormat: #(3 2 1 $- 1 1 2).\n(d weekday asString), ', ', (d monthName), ' ', (d dayOfMonth asString), ', ', (d year asString)\n", "language": "Smalltalk" }, { "code": "d := Date today.\nd printOn:Stdout format:'%y-%m-%d'. Stdout cr.\nd printOn:Stdout format:'%(DayName), %(MonthName) %d, %y' language:#en. Stdout cr.\nd printOn:Stdout format:'%(DayName), %(MonthName) %d, %y' language:#de. Stdout cr.\nd printOn:Stdout format:'%(DayName), %(MonthName) %d, %y' language:#fr. Stdout cr.\n", "language": "Smalltalk" }, { "code": "#!/usr/local/bin/spar\npragma annotate( summary, \"dateformat\")\n @( description, \"Display the current date in the formats of '2007-11-10' \" )\n @( description, \"and 'Sunday, November 10, 2007'.\" )\n @( see_also, \"http://rosettacode.org/wiki/Date_format\" )\n @( \"Ken O. Burtch\" );\npragma license( unrestricted );\n\npragma restriction( no_external_commands );\n\nprocedure dateformat is\n function Month_Image (Month : calendar.month_number) return string is\n begin\n case Month is\n when 1 => return \"January\";\n when 2 => return \"February\";\n when 3 => return \"March\";\n when 4 => return \"April\";\n when 5 => return \"May\";\n when 6 => return \"June\";\n when 7 => return \"July\";\n when 8 => return \"August\";\n when 9 => return \"September\";\n when 10 => return \"October\";\n when 11 => return \"November\";\n when others => return \"December\";\n end case;\n end Month_Image;\n function Day_Image (Day : integer) return string is\n begin\n case Day is\n when 0 => return \"Monday\";\n when 1 => return \"Tuesday\";\n when 2 => return \"Wednesday\";\n when 3 => return \"Thursday\";\n when 4 => return \"Friday\";\n when 5 => return \"Saturday\";\n when others => return \"Sunday\";\n end case;\n end Day_Image;\n Today : constant calendar.time := calendar.clock;\nbegin\n --put_line(\n --Put_Line (Image (Today) (1..10));\n\n put( calendar.year( Today ), \"9999\" ) @( \"-\" )\n @( calendar.month( Today ), \"99\" ) @( \"-\" )\n @( calendar.day( Today ), \"99\" );\n new_line;\n\n put_line(\n Day_Image( calendar.day_of_week( Today ) ) & \", \" &\n Month_Image( calendar.month( Today ) ) &\n strings.image( calendar.day( Today ) ) & \",\" &\n strings.image( calendar.year( Today ) ) );\nend dateformat;\n", "language": "SparForte" }, { "code": "select to_char(sysdate,'YYYY-MM-DD') date_fmt_1 from dual;\n\nselect to_char(sysdate,'fmDay, Month DD, YYYY') date_fmt_2 from dual;\n", "language": "SQL" }, { "code": "print (Date.fmt \"%Y-%m-%d\" (Date.fromTimeLocal (Time.now ())) ^ \"\\n\");\nprint (Date.fmt \"%A, %B %d, %Y\" (Date.fromTimeLocal (Time.now ())) ^ \"\\n\");\n", "language": "Standard-ML" }, { "code": "display %tdCCYY-NN-DD td($S_DATE)\ndisplay %tdDayname,_Month_dd,_CCYY td($S_DATE)\n", "language": "Stata" }, { "code": "Date().Format('yyyy-MM-dd') --> \"2010-03-16\"\nDate().LongDate() --> \"Tuesday, March 16, 2010\"\n", "language": "Suneido" }, { "code": "import Foundation\nextension String {\n func toStandardDateWithDateFormat(format: String) -> String {\n let dateFormatter = NSDateFormatter()\n dateFormatter.dateFormat = format\n dateFormatter.dateStyle = .LongStyle\n return dateFormatter.stringFromDate(dateFormatter.dateFromString(self)!)\n }\n}\n\nlet date = \"2015-08-28\".toStandardDateWithDateFormat(\"yyyy-MM-dd\")\n", "language": "Swift" }, { "code": "set now [clock seconds]\nputs [clock format $now -format \"%Y-%m-%d\"]\nputs [clock format $now -format \"%A, %B %d, %Y\"]\n", "language": "Tcl" }, { "code": "locals {\n today = timestamp()\n}\n\noutput \"iso\" {\n value = formatdate(\"YYYY-MM-DD\", local.today)\n}\n\noutput \"us-long\" {\n value = formatdate(\"EEEE, MMMM D, YYYY\", local.today)\n}\n", "language": "Terraform" }, { "code": "$$ MODE TUSCRIPT\nSET dayofweek = DATE (today,day,month,year,number)\n\nSET months=*\nDATA January\nDATA Februari\nDATA March\nDATA April\nDATA Mai\nDATA June\nDATA July\nDATA August\nDATA September\nDATA October\nDATA November\nDATA December\n\nSET days=\"Monday'Tuesday'Wendsday'Thursday'Fryday'Saturday'Sonday\"\n\nSET nameofday =SELECT (days,#dayofweek)\nSET nameofmonth=SELECT (months,#month)\n\nSET format1=JOIN (year,\"-\",month,day)\nSET format2=CONCAT (nameofday,\", \",nameofmonth,\" \",day, \", \",year)\n\nPRINT format1\nPRINT format2\n", "language": "TUSCRIPT" }, { "code": "date +\"%Y-%m-%d\"\ndate +\"%A, %B %d, %Y\"\n", "language": "UNIX-Shell" }, { "code": "date +\"%F\"\n", "language": "UNIX-Shell" }, { "code": "cygnus/x ursa v0.78 (default, release 0)\n[Oracle Corporation JVM 1.8.0_51 on Mac OS X 10.10.5 x86_64]\n> import \"java.util.Date\"\n> import \"java.text.SimpleDateFormat\"\n> decl java.text.SimpleDateFormat sdf\n> sdf.applyPattern \"yyyy-MM-dd\"\n> decl java.util.Date d\n> out (sdf.format d) endl console\n2016-07-23\n> sdf.applyPattern \"EEEE, MMMM dd, yyyy\"\n> out (sdf.format d) endl console\nSaturday, July 23, 2016\n> _\n", "language": "Ursa" }, { "code": "#import std\n#import cli\n\nmonths = ~&p/block3'JanFebMarAprMayJunJulAugSepOctNovDec' block2'010203040506070809101112'\n\ncompletion =\n\n-:~& ~&pllrTXS/block3'SunMonTueWedThuFriSat'--(~&lS months) -- (\n --','* sep`, 'day,day,sday,nesday,rsday,day,urday',\n sep`, 'uary,ruary,ch,il,,e,y,ust,tember,ober,ember,ember')\n\ntext_form = sep` ; mat` + completion*+ <.~&hy,~&tth,--','@th,~&ttth>\nnumeric_form = sep` ; mat`-+ <.~&ttth,@tth -: months,~&th>\n\n#show+\n\nmain = <.text_form,numeric_form> now0\n", "language": "Ursala" }, { "code": "import time\n\nfn main() {\n println(time.now().custom_format(\"YYYY-MM-DD\"))\n println(time.now().custom_format(\"dddd, MMMM D, YYYY\"))\n}\n", "language": "V-(Vlang)" }, { "code": "Function DateFormats()\n Debug.Print Format(Date, \"yyyy-mm-dd\")\n Debug.Print Format(Date, \"dddd, mmmm dd yyyy\")\nEnd Function\n", "language": "VBA" }, { "code": "'YYYY-MM-DD format\nWScript.StdOut.WriteLine Year(Date) & \"-\" & Right(\"0\" & Month(Date),2) & \"-\" & Right(\"0\" & Day(Date),2)\n\n'Weekday_Name, Month_Name DD, YYYY format\nWScript.StdOut.WriteLine FormatDateTime(Now,1)\n", "language": "VBScript" }, { "code": "Date(REVERSE+NOMSG+VALUE, '-')\n", "language": "Vedit-macro-language" }, { "code": "// Get todays date into #1, #2, #3 and #7\n#1 = Date_Day\n#2 = Date_Month\n#3 = Date_Year\n#7 = JDate() % 7 // #7 = weekday\n\n// Convert weekday number (in #7) into word in T-reg 1\nif (#7==0) { RS(1,\"Sunday\") }\nif (#7==1) { RS(1,\"Monday\") }\nif (#7==2) { RS(1,\"Tuesday\") }\nif (#7==3) { RS(1,\"Wednesday\") }\nif (#7==4) { RS(1,\"Thursday\") }\nif (#7==5) { RS(1,\"Friday\") }\nif (#7==6) { RS(1,\"Saturday\") }\n\n// Convert month number (in #2) into word in T-reg 2\nif (#2==1) { RS(2,\"January\") }\nif (#2==2) { RS(2,\"February\") }\nif (#2==3) { RS(2,\"March\") }\nif (#2==4) { RS(2,\"April\") }\nif (#2==5) { RS(2,\"May\") }\nif (#2==6) { RS(2,\"June\") }\nif (#2==7) { RS(2,\"July\") }\nif (#2==8) { RS(2,\"August\") }\nif (#2==9) { RS(2,\"September\") }\nif (#2==10) { RS(2,\"October\") }\nif (#2==11) { RS(2,\"November\") }\nif (#2==12) { RS(2,\"December\") }\n\n// Display the date string\nRT(1) M(\", \") RT(2) M(\" \") NT(#1, LEFT+NOCR) M(\",\") NT(#3)\n", "language": "Vedit-macro-language" }, { "code": "RI(1) IT(\", \") RI(2) IT(\" \") NI(#1, LEFT+NOCR) IT(\",\") NI(#3)\n", "language": "Vedit-macro-language" }, { "code": "echo strftime(\"%Y-%m-%d\")\necho strftime(\"%A, %B %d, %Y\")\n", "language": "Vim-Script" }, { "code": "import \"os\" for Process\nimport \"./date\" for Date\n\nvar args = Process.arguments\nif (args.count != 1) {\n Fiber.abort(\"Please pass just the current date in yyyy-mm-dd format.\")\n}\nvar current = Date.parse(args[0])\nSystem.print(current.format(Date.isoDate))\nSystem.print(current.format(\"dddd|, |mmmm| |d|, |yyyy\"))\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes;\nint CpuReg, Year, Month, Day, DName, MName, WDay;\n[CpuReg:= GetReg; \\access CPU registers\nCpuReg(0):= $2A00; \\DOS system call\nSoftInt($21);\nYear:= CpuReg(2);\nMonth:= CpuReg(3) >> 8;\nDay:= CpuReg(3) & $FF;\nWDay:= CpuReg(0) & $FF;\nIntOut(0, Year); ChOut(0, ^-);\nif Month<10 then ChOut(0, ^0); IntOut(0, Month); ChOut(0, ^-);\nif Day<10 then ChOut(0, ^0); IntOut(0, Day); CrLf(0);\nDName:= [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n \"Thursday\", \"Friday\", \"Saturday\"];\nMName:= [0, \"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\",\n \"August\", \"September\", \"October\", \"November\", \"December\"];\nText(0, DName(WDay)); Text(0, \", \"); Text(0, MName(Month)); Text(0, \" \");\nIntOut(0, Day); Text(0, \", \"); IntOut(0, Year); CrLf(0);\n]\n", "language": "XPL0" }, { "code": "dim n$(1)\n\nn = token(date$, n$(), \"-\")\n\nprint n$(4), \"-\", n$(2), \"-\", n$(3)\nprint nDay$(n$(5)), \", \", nMonth$(n$(6)), \" \", n$(3), \", \", n$(4)\n\nsub nDay$(n$)\n\tswitch n$\n\tcase \"Mon\": case \"Fri\": case \"Sun\": break\n\tcase \"Tue\": n$ = n$ + \"s\" : break\n\tcase \"Wed\": n$ = n$ + \"nes\" : break\n\tcase \"Thu\": n$ = n$ + \"rs\" : break\n\tcase \"Sat\": n$ = n$ + \"ur\" : break\n\tdefault: n$ = \"none\" : break\n\tend switch\n\t\n\treturn n$ + \"day\"\nend sub\n\nsub nMonth$(n$)\n\tlocal month$(1), n\n\t\n\tn = token(\"January, February, March, April, May, June, July, August, September, October, November, December\", month$(), \", \")\n\tn = instr(\"JanFebMarAprMayJunJulAugSepOctNovDec\", n$)\n\t\n\treturn month$(int(n/3) + 1)\nend sub\n", "language": "Yabasic" }, { "code": "\"%d-%02d-%02d\".fmt(Time.Clock.localTime.xplode()).println()\n//--> \"2014-02-28\" (ISO format)\n", "language": "Zkl" }, { "code": "Time.Date.prettyDay(Time.Clock.localTime.xplode())\n//--> \"Friday, the 28th of February 2014\"\n", "language": "Zkl" }, { "code": "y,m,d:=Time.Clock.localTime; D:=Time.Date;\n\"%s, %s %d, %d\".fmt(D.dayName(D.weekDay(y,m,d)),\n D.monthName(m), d,y)\n//-->\"Friday, February 28, 2014\"\n", "language": "Zkl" }, { "code": "module Main;\nimport System;\n\nvar\n\tnow: System.DateTime;\nbegin\n\tnow := System.DateTime.Now;\n\tSystem.Console.WriteLine(now.ToString(\"yyyy-MM-dd\");\n\tSystem.Console.WriteLine(\"{0}, {1}\",now.DayOfWeek,now.ToString(\"MMMM dd, yyyy\"));\nend Main.\n", "language": "Zonnon" } ]
Date-format
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Day_of_the_week\nnote: Date and time\n", "language": "00-META" }, { "code": "A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).\n \n\n;Task:\n'''In what years between 2008 and 2121 will the 25th of December be a Sunday?'''\n\nUsing any standard date handling libraries of your programming language; \ncompare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to &nbsp; [[wp:Y2k#See_also|y2k]] &nbsp; type problems.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "print((2008..2121).filter(y -> Time(y, 12, 25).strftime(‘%w’) == ‘0’))\n", "language": "11l" }, { "code": "* Day of the week 06/07/2016\nDOW CSECT\n USING DOW,R15 base register\n LA R6,2008 year=2008\nLOOP C R6,=F'2121' do year=2008 to 2121\n BH ELOOP .\n LR R7,R6 y=year\n LA R8,12 m=12\n LA R9,25 d=25\n C R8,=F'3' if m<3\n BNL MGE3 then\n LA R8,12(R8) m=m+12\n BCTR R7,0 y=y-1\nMGE3 LR R10,R7 y\n SRDA R10,32 .\n D R10,=F'100' r=y//100 ; l=y/100\n LR R3,R8 m\n LA R3,1(R3) m+1\n M R2,=F'26' *26\n D R2,=F'10' /10\n AR R3,R9 +d\n AR R3,R10 +r\n LR R2,R10 r\n SRA R2,2 /4\n AR R2,R3 (d+(m+1)*26/10+r+r/4\n LR R3,R11 l\n SRA R3,2 /4\n AR R2,R3 (d+(m+1)*26/10+r+r/4+l/4\n LA R5,5 5\n MR R4,R11 *l\n AR R2,R5 (d+(m+1)*26/10+r+r/4+l/4+5*l)\n SRDA R2,32 .\n D R2,=F'7' w=(d+(m+1)*26/10+r+r/4+l/4+5*l)//7\n C R2,=F'1' if w=1 (sunday)\n BNE WNE1 then\n XDECO R6,PG edit year\n XPRNT PG,12 print year\nWNE1 LA R6,1(R6) year=year+1\n B LOOP next year\nELOOP BR R14 exit\nPG DS CL12 buffer\n YREGS\n END DOW\n", "language": "360-Assembly" }, { "code": "report zday_of_week\ndata: lv_start type i value 2007,\n lv_n type i value 114,\n lv_date type sy-datum,\n lv_weekday type string,\n lv_day type c,\n lv_year type n length 4.\n\nwrite 'December 25 is a Sunday in: '.\ndo lv_n times.\n lv_year = lv_start + sy-index.\n concatenate lv_year '12' '25' into lv_date.\n call function 'DATE_COMPUTE_DAY'\n exporting date = lv_date\n importing day = lv_day.\n\n select single langt from t246 into lv_weekday\n where sprsl = sy-langu and\n wotnr = lv_day.\n\n if lv_weekday eq 'Sunday'.\n write / lv_year.\n endif.\nenddo.\n", "language": "ABAP" }, { "code": "Byte FUNC DayOfWeek(BYTE day, month CARD year BYTE century)\nCARD weekday\nBYTE ARRAY index=[0 3 2 5 0 3 5 1 4 6 2 4]\n\nIF year < 100 THEN\n year = year + century * 100\nFI\n\nIF year < 1753 THEN RETURN(7) FI\n\nIF month < 3 THEN\n year==-1\nFI\n\nmonth = index(month-1)\nweekday=year + year/4 - year/100 + year/400 + month + day\nweekday = weekday MOD 7\nRETURN (weekday)\n\nPROC main()\nCARD y\nPrintE(\"December 25 is a Sunday in:\")\nFOR y = 2008 to 2121\nDO\nIF DayOfWeek(25, 12, y)=0 THEN\nPrintCE(y)\nFI\nOD\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Calendar.Formatting; use Ada.Calendar.Formatting;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Yuletide is\nbegin\n for Year in 2008..2121 loop\n if Day_Of_Week (Time_Of (Year, 12, 25)) = Sunday then\n Put_Line (Image (Time_Of (Year, 12, 25)));\n end if;\n end loop;\nend Yuletide;\n", "language": "Ada" }, { "code": "# example from: http://www.xs4all.nl/~jmvdveer/algol.html - GPL #\nINT sun=0 # , mon=1, tue=2, wed=3, thu=4, fri=5, sat=6 #;\n\nPROC day of week = (INT year, month, day) INT: (\n # Day of the week by Zeller’s Congruence algorithm from 1887 #\n INT y := year, m := month, d := day, c;\n IF m <= 2 THEN\n m +:= 12; y -:= 1\n FI;\n c := y OVER 100;\n y %*:= 100;\n (d - 1 + ((m + 1) * 26) OVER 10 + y + y OVER 4 + c OVER 4 - 2 * c) MOD 7\n);\n\ntest:(\n print(\"December 25th is a Sunday in:\");\n FOR year FROM 2008 TO 2121 DO\n INT wd = day of week(year, 12, 25);\n IF wd = sun THEN print(whole(year,-5)) FI\n OD;\n new line(stand out)\n)\n", "language": "ALGOL-68" }, { "code": "BEGIN\n\n% CALCULATE P MOD Q %\nINTEGER FUNCTION MOD(P, Q);\nINTEGER P, Q;\nBEGIN\n MOD := P - Q * (P / Q);\nEND;\n\nCOMMENT\n RETURN DAY OF WEEK (SUN=0, MON=1, ETC.) FOR A GIVEN\n GREGORIAN CALENDAR DATE USING ZELLER'S CONGRUENCE;\nINTEGER FUNCTION DAYOFWEEK(MO, DA, YR);\nINTEGER MO, DA, YR;\nBEGIN\n INTEGER Y, C, Z;\n IF MO < 3 THEN\n BEGIN\n MO := MO + 10;\n YR := YR - 1;\n END\n ELSE MO := MO - 2;\n Y := MOD(YR, 100);\n C := YR / 100;\n Z := (26 * MO - 2) / 10;\n Z := Z + DA + Y + (Y / 4) + (C /4) - 2 * C + 777;\n DAYOFWEEK := MOD(Z, 7);\nEND;\n\n% MAIN PROGRAM STARTS HERE %\nINTEGER YEAR, SUNDAY;\nSUNDAY := 0;\nWRITE(\"CHRISTMAS WILL FALL ON A SUNDAY IN THESE YEARS:\");\nFOR YEAR := 2008 STEP 1 UNTIL 2121 DO\n BEGIN\n IF DAYOFWEEK(12, 25, YEAR) = SUNDAY THEN\n WRITE(YEAR);\n END;\n\nEND\n", "language": "ALGOL-M" }, { "code": "begin % find years where Christmas day falls on a Sunday %\n integer procedure Day_of_week ( integer value d, m, y );\n begin\n integer j, k, mm, yy;\n mm := m;\n yy := y;\n if mm <= 2 then begin\n mm := mm + 12;\n yy := yy - 1;\n end if_m_le_2;\n j := yy div 100;\n k := yy rem 100;\n (d + ( ( mm + 1 ) * 26 ) div 10 + k + k div 4 + j div 4 + 5 * j ) rem 7\n end Day_of_week;\n write( \"25th of December is a Sunday in\" );\n for year := 2008 until 2121 do begin\n integer day;\n day := Day_of_week( 25, 12, year );\n if day = 1 then writeon( I_W := 5, S_W := 0, year );\n end for_year\nend.\n", "language": "ALGOL-W" }, { "code": "⍝ Based on the simplified calculation of Zeller's congruence, since Christmas is after March 1st, no adjustment is required.\n⎕IO ← 0 ⍝ Indices are 0-based\ny ← 2008 + ⍳114 ⍝ Years from 2008 to 2121\n⍝ Simplified Zeller function operating on table of dates formatted as 114 rows and 3 columns of (day, month, year)\n⍝ 0 = Saturday, 1 = Sunday, 2 = Monday, 3 = Tuesday, 4 = Wednesday, 5 = Thursday, 6 = Friday\nzeller ← { 7 | +/ (((1↑⍴⍵),6)⍴1 1 1 1 ¯1 1) × ⌊(((⍴⍵)⍴1 13 1)×⍵+(⍴⍵)⍴0 1 0)[;0 1 2 2 2 2]÷((1↑⍴⍵),6)⍴1 5 1 4 100 400 }\nresult ← (1 = zeller 25,[1]12,[0.5]y) / y\n", "language": "APL" }, { "code": "set ChristmasSundays to {}\nset Christmas to (current date)\nset month of Christmas to December\nset day of Christmas to 25\nrepeat with |year| from 2008 to 2121\n\tset year of Christmas to |year|\n\tif weekday of Christmas is Sunday then set end of ChristmasSundays to |year|\nend repeat\nChristmasSundays\n", "language": "AppleScript" }, { "code": "-- xmasIsSunday :: Int -> Bool\non xmasIsSunday(y)\n tell (current date)\n set {its year, its month, its day, its time} to {y, 12, 25, 0}\n its weekday is Sunday\n end tell\nend xmasIsSunday\n\n\n-------------------------- TEST ---------------------------\non run\n\n filter(xmasIsSunday, enumFromTo(2008, 2121))\n\nend run\n\n\n-------------------- GENERIC FUNCTIONS --------------------\n\n-- enumFromTo :: Int -> Int -> [Int]\non enumFromTo(m, n)\n if m ≤ n then\n set lst to {}\n repeat with i from m to n\n set end of lst to i\n end repeat\n lst\n else\n {}\n end if\nend enumFromTo\n\n\n-- filter :: (a -> Bool) -> [a] -> [a]\non filter(f, xs)\n tell mReturn(f)\n set lst to {}\n set lng to length of xs\n repeat with i from 1 to lng\n set v to item i of xs\n if |λ|(v, i, xs) then set end of lst to v\n end repeat\n return lst\n end tell\nend filter\n\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n", "language": "AppleScript" }, { "code": "{2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067,\n2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118}\n", "language": "AppleScript" }, { "code": " 1 DEF FN D7(N) = N - 7 * INT (N / 7)\n 2 DEF FN RD(Y) = 365 * Y + INT (Y / 4) - INT (Y / 100) + INT (Y / 400)\n 3 PRINT \"YEARS WITH CHRISTMAS ON A SUNDAY\" CHR$ (13)\n 4 FOR Y = 2008 TO 2121\n 5 IF NOT FN D7( FN RD(Y) - 6) THEN PRINT Y,\n 6 NEXT Y\n", "language": "Applesoft-BASIC" }, { "code": "(= day-names '(Sunday Monday Tuesday Wednesday Thursday Friday Saturday))\n(= get-weekday-num (fn (year month day)\n (= helper '(0 3 2 5 0 3 5 1 4 6 2 4))\n (if (< month 3) (= year (- year 1)))\n (mod (+ year (helper (- month 1)) day\n (apply + (map [trunc (/ year _)] '(4 -100 400))))\n 7)))\n(= get-weekday-name (fn (weekday-num) (day-names weekday-num)))\n", "language": "Arc" }, { "code": "(up i 2008 2121\n (when (is 0 (get-weekday-num i 12 25))\n (prn i)))\n\n2011\n2016\n2022\n2033\n2039\n2044\n2050\n2061\n2067\n2072\n2078\n2089\n2095\n2101\n2107\n2112\n2118\n", "language": "Arc" }, { "code": "print select 2008..2121 'year [\n \"Sunday\" = get to :date.format:\"dd-MM-YYYY\" ~\"25-12-|year|\" 'Day\n]\n", "language": "Arturo" }, { "code": "REM Day of the week\nMonth = 12\nDay = 25\nFOR Year = 2007 TO 2122\n GOSUB CalcDayOfWeek:\n IF DayOfWeek = 0 THEN\n PRINT Year;\n ENDIF\nNEXT Year\nPRINT\nEND\n\nCalcDayOfWeek:\nREM Sunday = 0, Saturday = 6\nIF Month < 3 THEN\n Year = Year - 1\n Month = Month + 12\nENDIF\nDayOfWeek = Year\nYearDiv = Year / 4\nDayOfWeek = DayOfWeek + YearDiv\nYearDiv = Year / 100\nDayOfWeek = DayOfWeek - YearDiv\nYearDiv = Year / 400\nDayOfWeek = DayOfWeek + YearDiv\nDayPlus = 153 * Month\nDayPlus = DayPlus + 8\nDayPlus = DayPlus / 5\nDayOfWeek = DayOfWeek + Day\nDayOfWeek = DayOfWeek + DayPlus\nDayOfWeek = DayOfWeek MOD 7\nRETURN\n", "language": "ASIC" }, { "code": "100 REM FIND YEARS WITH SUNDAY CHRISTMAS\n110 PRINT CHR$(125);\"SUNDAY CHRISTMASES 2008-2121:\":PRINT\n120 FOR Y=2008 TO 2121\n130 EOY=Y*365+INT(Y/4)-INT(Y/100)+INT(Y/400)\n140 XMAS=EOY-6\n150 DOW=XMAS-7*INT(XMAS/7)\n160 IF DOW THEN 220\n170 PRINT Y;\n180 FOUND=FOUND+1\n190 IF FOUND<3 THEN PRINT ,:GOTO 220\n200 FOUND=0\n210 PRINT\n220 NEXT Y\n230 IF FOUND THEN PRINT\n", "language": "Atari-BASIC" }, { "code": "year = 2008\nstop = 2121\n\nWhile year <= stop {\n FormatTime, day,% year 1225, dddd\n If day = Sunday\n out .= year \"`n\"\n year++\n}\nMsgBox,% out\n", "language": "AutoHotkey" }, { "code": "#include <date.au3>\nConst $iSunday = 1\nFor $iYear = 2008 To 2121 Step 1\n If $iSunday = _DateToDayOfWeek($iYear, 12, 25) Then\n ConsoleWrite(StringFormat($iYear & \"\\n\"))\n EndIf\nNext\n", "language": "AutoIt" }, { "code": "# syntax: GAWK -f DAY_OF_THE_WEEK.AWK\n# runtime does not support years > 2037 on my 32-bit Windows XP O/S\nBEGIN {\n for (i=2008; i<=2121; i++) {\n x = strftime(\"%Y/%m/%d %a\",mktime(sprintf(\"%d 12 25 0 0 0\",i)))\n if (x ~ /Sun/) { print(x) }\n }\n}\n", "language": "AWK" }, { "code": "' Sunday Christmas\nPRINT \"Years with Christmas on a Sunday\"\nFOR y = 2008 TO 2121\n tv = TIMEVALUE(y, 12, 25, 0, 0, 0)\n IF WEEKDAY$(tv) = \"Sunday\" THEN PRINT y\nNEXT\n", "language": "BaCon" }, { "code": "for yr = 2008 to 2121\n\tif wd(12, 25, yr) = 0 then print \"Dec 25 \"; yr\nnext\nend\n\nfunction wd(m, d, y)\n\tif m < 3 then\t# if m = 1 or m = 2 then\n\t\tm += 12\n\t\ty -= 1\n\tend if\n\treturn (y + (y \\ 4) - (y \\ 100) + (y \\ 400) + d + ((153 * m + 8) \\ 5)) % 7\nend function\n", "language": "BASIC256" }, { "code": ":: Day of the Week task from Rosetta Code\n:: Batch File Implementation\n:: Question: In what years between 2008 and 2121 will the 25th of December be a Sunday?\n:: Method: Zeller's Rule\n\n@echo off\nrem set month code for December\nset mon=33\nrem set day number\nset day=25\n\nfor /L %%y in (2008,1,2121) do (\n setlocal enabledelayedexpansion\n set /a \"a=%%y/100\"\n set /a \"b=%%y-(a*100)\"\n set /a \"weekday=(day+mon+b+(b/4)+(a/4)+(5*a))%%7\"\n if \"!weekday!\"==\"1\" echo(Dec 25, %%y is a Sunday.\n endlocal\n)\npause\nexit /b 0\n", "language": "Batch-File" }, { "code": " INSTALL @lib$+\"DATELIB\"\n\n FOR year% = 2008 TO 2121\n IF FN_dow(FN_mjd(25, 12, year%)) = 0 THEN\n PRINT \"Christmas Day is a Sunday in \"; year%\n ENDIF\n NEXT\n", "language": "BBC-BASIC" }, { "code": "scale = 0\n\n/*\n * Returns day of week (0 to 6) for year, month m, day d in proleptic\n * Gregorian calendar. Sunday is 0. Assumes y >= 1, scale = 0.\n */\ndefine w(y, m, d) {\n\tauto a\n\n\t/* Calculate Zeller's congruence. */\n\ta = (14 - m) / 12\n\tm += 12 * a\n\ty -= a\n\treturn ((d + (13 * m + 8) / 5 +\t\t\t\\\n\t\t y + y / 4 - y / 100 + y / 400) % 7)\n}\n\nfor (y = 2008; y <= 2121; y++) {\n\t/* If December 25 is a Sunday, print year. */\n\tif (w(y, 12, 25) == 0) y\n}\nquit\n", "language": "Bc" }, { "code": "get \"libhdr\"\n\nlet weekday(y, m, d) =\n m<3 -> wd((y-1)/100, (y-1) rem 100, m + 10, d),\n wd(y/100, y rem 100, m - 2, d)\nand wd(c, y, m, d) =\n ((26*m-2)/10 + d + y + y/4 + c/4 - 2 * c + 777) rem 7\n\nlet start() be\n for year = 2008 to 2121\n if weekday(year, 12, 25) = 0\n do writef(\"%N*N\", year)\n", "language": "BCPL" }, { "code": "8 >:\"2(\"*+::::4/+\\\"d\"/-\\45v\n@_^#`\"y\": +1$<_v#%7+1+/*:*<\n>:#,_>$:.55+,^ >0\" ,52 ceD\"\n", "language": "Befunge" }, { "code": "{ Calculate day of week in proleptic Gregorian calendar. Sunday == 0. }\n ( wday\n = year month day adjustment mm yy\n . !arg:(?year,?month,?day)\n & div$(14+-1*!month,12):?adjustment\n & !month+12*!adjustment+-2:?mm\n & !year+-1*!adjustment:?yy\n & mod\n $ ( !day\n + div$(13*!mm+-1,5)\n + !yy\n + div$(!yy,4)\n + -1*div$(!yy,100)\n + div$(!yy,400)\n , 7\n )\n )\n& 2008:?y\n& whl\n ' ( !y:~>2121\n & ( wday$(!y,12,25):0\n & put$(str$(!y \"-12-25\\n\"))\n |\n )\n & 1+!y:?y\n )\n& done;\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n\n/* Calculate day of week in proleptic Gregorian calendar. Sunday == 0. */\nint wday(int year, int month, int day)\n{\n\tint adjustment, mm, yy;\n\n\tadjustment = (14 - month) / 12;\n\tmm = month + 12 * adjustment - 2;\n\tyy = year - adjustment;\n\treturn (day + (13 * mm - 1) / 5 +\n\t\tyy + yy / 4 - yy / 100 + yy / 400) % 7;\n}\n\nint main()\n{\n\tint y;\n\n\tfor (y = 2008; y <= 2121; y++) {\n\t\tif (wday(y, 12, 25) == 0) printf(\"%04d-12-25\\n\", y);\n\t}\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <chrono>\n#include <ranges>\n#include <iostream>\n\nint main() {\n std::cout << \"Yuletide holidays must be allowed in the following years:\\n\";\n for (int year : std::views::iota(2008, 2121)\n | std::views::filter([](auto year) {\n if (std::chrono::weekday{\n std::chrono::year{year}/std::chrono::December/25}\n == std::chrono::Sunday) {\n return true;\n }\n return false;\n })) {\n std::cout << year << '\\n';\n }\n}\n", "language": "C++" }, { "code": "using System;\n\nclass Program\n{\n static void Main(string[] args)\n {\n for (int i = 2008; i <= 2121; i++)\n {\n DateTime date = new DateTime(i, 12, 25);\n if (date.DayOfWeek == DayOfWeek.Sunday)\n {\n Console.WriteLine(date.ToString(\"dd MMM yyyy\"));\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "using System;\nusing System.Linq;\n\nclass Program\n{\n static void Main(string[] args)\n {\n string[] days = Enumerable.Range(2008, 2121 - 2007)\n .Select(year => new DateTime(year, 12, 25))\n .Where(day => day.DayOfWeek == DayOfWeek.Sunday)\n .Select(day => day.ToString(\"dd MMM yyyy\")).ToArray();\n\n foreach (string day in days) Console.WriteLine(day);\n }\n}\n", "language": "C-sharp" }, { "code": "using System;\nusing System.Linq;\n\nclass Program\n{\n static void Main(string[] args)\n {\n Enumerable.Range(2008, 113).ToList()\n .ConvertAll(ent => new DateTime(ent, 12, 25))\n .Where(ent => ent.DayOfWeek.Equals(DayOfWeek.Sunday)).ToList()\n .ForEach(ent => Console.WriteLine(ent.ToString(\"dd MMM yyyy\")));\n }\n}\n", "language": "C-sharp" }, { "code": "10 CLS : REM 10 HOME for Applesoft BASIC\n20 DEF fnd7(n) = n - 7 * INT (n / 7)\n30 DEF fnrd(y) = 365 * y + INT (y / 4) - INT (y / 100) + INT (y / 400)\n40 PRINT \"YEARS WITH CHRISTMAS ON A SUNDAY\" CHR$(13)\n50 FOR y = 2008 TO 2121\n60 IF NOT fn d7(fn rd(y)-6) THEN PRINT y,\n70 NEXT y\n", "language": "Chipmunk-Basic" }, { "code": "(import '[java.util GregorianCalendar])\n(defn yuletide [start end]\n (->> (range start (inc end))\n (filter #(= GregorianCalendar/SUNDAY\n (.get (GregorianCalendar. % GregorianCalendar/DECEMBER 25)\n GregorianCalendar/DAY_OF_WEEK)))))\n\n(println (yuletide 2008 2121))\n", "language": "Clojure" }, { "code": "weekday = proc (d: date) returns (int)\n y: int := d.year\n m: int := d.month\n if m<3\n then y, m := y-1, m+10\n else m := m-2\n end\n c: int := y/100\n y := y//100\n z: int := (26*m-2)/10 + d.day + y + y/4 + c/4 - 2*c + 777\n return(z//7)\nend weekday\n\nstart_up = proc ()\n po: stream := stream$primary_output()\n for year: int in int$from_to(2008, 2121) do\n if weekday(date$create(25, 12, year, 0, 0, 0))=0 then\n stream$putl(po, int$unparse(year))\n end\n end\nend start_up\n", "language": "CLU" }, { "code": " program-id. dec25.\n data division.\n working-storage section.\n 1 work-date.\n 2 yr pic 9(4) value 2008.\n 2 mo-da pic 9(4) value 1225. *> Dec 25\n 1 wk-date redefines work-date pic 9(8).\n 1 binary.\n 2 int-date pic 9(8).\n 2 dow pic 9(4).\n procedure division.\n perform varying yr from 2008 by 1\n until yr > 2121\n compute int-date = function integer-of-date (wk-date)\n compute dow = function mod ((int-date - 1) 7) + 1\n if dow = 7 *> Sunday = 7 per ISO 8601 and ISO 1989\n display yr\n end-if\n end-perform\n stop run\n .\n end program dec25.\n", "language": "COBOL" }, { "code": " identification division.\n program-id. dowtest.\n data division.\n working-storage section.\n 01 ws-inp-date pic x(08).\n 01 filler redefines ws-inp-date.\n 03 ws-inp-year pic 9(04).\n 01 ws-dow pic 9(05).\n procedure division.\n move '00001225' to ws-inp-date\n perform test before\n varying ws-inp-year from 2008 by +1\n until ws-inp-year > 2121\n call \"todow\" using\n by reference ws-inp-date\n by reference ws-dow\n if ws-dow = 1 then\n display 'year=' ws-inp-year\n end-if\n end-perform\n stop run.\n\n end program dowtest.\n\n identification division.\n program-id. todow.\n environment division.\n input-output section.\n file-control.\n data division.\n file section.\n working-storage section.\n 01 tally pic 9(05).\n 01 wms-work-area.\n 03 wms-year pic 9(04).\n 03 wms-month pic 9(02).\n 03 wms-csys pic 9(01) value 1.\n 03 wms-sum pic 9(05).\n linkage section.\n 01 lkip-date.\n 03 lkip-date-year pic 9(04).\n 03 lkip-date-month pic 9(02).\n 03 lkip-date-day pic 9(02).\n 01 lkop-dow pic 9(05).\n 88 lkop-sunday value 1.\n procedure division using\n by reference lkip-date\n by reference lkop-dow\n .\n\n if lkip-date-month < 3\n compute wms-month = lkip-date-month + 12\n compute wms-year = lkip-date-year - 1\n else\n compute wms-month = lkip-date-month\n compute wms-year = lkip-date-year\n end-if\n\n compute wms-sum =\n ( lkip-date-day + 2 * wms-month + wms-year\n + function integer (6 * (wms-month + 1) / 10)\n + function integer ( wms-year / 4 )\n - function integer ( wms-year / 100 )\n + function integer ( wms-year / 400 )\n + wms-csys )\n compute lkop-dow = function mod (wms-sum, 7) + 1\n .\n end program todow.\n", "language": "COBOL" }, { "code": "december = 11 # gotta love Date APIs :)\nsunday = 0\nfor year in [2008..2121]\n xmas = new Date year, december, 25\n console.log year if xmas.getDay() is sunday\n", "language": "CoffeeScript" }, { "code": "console.log year for year in [2008...2121] when new Date(year, 11, 25).getDay() is 0\n", "language": "CoffeeScript" }, { "code": "<cfloop from = \"2008\" to = \"2121\" index = \"i\">\n <cfset myDate = createDate(i, 12, 25) />\n <cfif dayOfWeek(myDate) eq 1>\n December 25th falls on a Sunday in <cfoutput>#i#</cfoutput><br />\n </cfif>\n</cfloop>\n", "language": "ColdFusion" }, { "code": "100 REM FIND OUT WHAT YEARS HAVE CHRISTMAS ON A SUNDAY\n110 REM MODULO FUNCTION (USES CALLER'S N AS DIVIDEND)\n120 DEF FNNM(D) = N - D * INT(N/D)\n130 REM RATA DIE OF 31 DEC Y (CAN BE TAKEN MODULO 7 TO GET DAY OF WEEK)\n140 DEF FNRD(Y) = 365 * Y + INT(Y/4) - INT(Y/100) + INT(Y/400)\n150 REM TRUE IF THE GIVEN RD IS A SUNDAY\n160 DEF FND7(N) = 0 = FNNM(7)\n170 REM TRUE IF CHRISTMAS FALLS ON A SUNDAY IN THE GIVEN YEAR\n180 DEF FNXS(Y) = FND7(FNRD(Y) - 6):REM 6 DAYS BEFORE THE END OF THE YEAR\n190 REM TRY OUR TARGET YEARS AND OUTPUT THE ONES THAT MATCH\n200 Y1 = 2008: Y2 = 2121\n210 PRINT CHR$(147);\"CHRISTMASES ON SUNDAY\";Y1;\"-\";Y2;CHR$(13)\n220 FOR Y=Y1 TO Y2\n230 : IF FNXS(Y) THEN PRINT Y,:REM PRINT YEARS IN COLUMNS\n240 NEXT Y\n250 PRINT\n", "language": "Commodore-BASIC" }, { "code": "(loop for year from 2008 upto 2121\n when (= 6 (multiple-value-bind\n (second minute hour date month year day-of-week dst-p tz)\n (decode-universal-time (encode-universal-time 0 0 0 25 12 year))\n (declare (ignore second minute hour date month year dst-p tz))\n day-of-week))\n collect year)\n", "language": "Common-Lisp" }, { "code": "(loop for year from 2008 upto 2121\n for xmas = (encode-universal-time 0 0 0 25 12 year)\n for day = (nth-value 6 (decode-universal-time xmas))\n when (= day 6) collect year)\n", "language": "Common-Lisp" }, { "code": "MODULE DayOfWeek;\nIMPORT DevCommanders, TextMappers, Dates, StdLog;\n\nPROCEDURE XmastOnSun(s,e: INTEGER);\nVAR\n\ti: INTEGER;\n\td: Dates.Date;\nBEGIN\n\ti := s;d.day := 25;d.month := 12;\n\tWHILE i < e DO\n\t\td.year := i;\n\t\tIF Dates.DayOfWeek(d) = Dates.sunday THEN\n\t\t\tStdLog.Int(i);StdLog.Ln\n\t\tEND;\n\t\tINC(i)\n\tEND\nEND XmastOnSun;\n\nPROCEDURE Do*;\nVAR\n\ts: TextMappers.Scanner;\n\tr: ARRAY 2 OF INTEGER;\n\ti: INTEGER;\nBEGIN\n\ts.ConnectTo(DevCommanders.par.text);\n\ts.SetPos(DevCommanders.par.beg);\n\ts.Scan;i := 0;\n\tWHILE ~s.rider.eot DO\n\t\tIF s.type = TextMappers.int THEN\n\t\t\tr[i] := s.int; INC(i)\n\t\tEND;\n\t\ts.Scan\n\tEND;\n\tXmastOnSun(r[0],r[1]);\nEND Do;\n\nEND DayOfWeek.\n", "language": "Component-Pascal" }, { "code": "include \"cowgol.coh\";\n\nsub weekday(year: uint16, month: uint8, day: uint8): (wd: uint8) is\n if month < 3 then\n month := month + 10;\n year := year - 1;\n else\n month := month - 2;\n end if;\n var c := year / 100;\n var y := year % 100;\n var z := (26 * month as uint16 - 2) / 10;\n z := z + day as uint16 + y + (y / 4) + (c / 4) - 2 * c + 777;\n wd := (z % 7) as uint8;\nend sub;\n\nvar year: uint16 := 2008;\nwhile year <= 2121 loop\n if weekday(year, 12, 25) == 0 then\n print_i16(year);\n print_nl();\n end if;\n year := year + 1;\nend loop;\n", "language": "Cowgol" }, { "code": "void main() {\n import std.stdio, std.range, std.algorithm, std.datetime;\n\n writeln(\"Christmas comes on a Sunday in the years:\\n\",\n iota(2008, 2122)\n .filter!(y => Date(y, 12, 25).dayOfWeek == DayOfWeek.sun));\n}\n", "language": "D" }, { "code": "procedure IsXmasSunday(fromyear, toyear: integer);\nvar\ni: integer;\nTestDate: TDateTime;\noutputyears: string;\nbegin\noutputyears := '';\n for i:= fromyear to toyear do\n begin\n TestDate := EncodeDate(i,12,25);\n if dayofweek(TestDate) = 1 then\n begin\n outputyears := outputyears + inttostr(i) + ' ';\n end;\n end;\n //CONSOLE\n //writeln(outputyears);\n //GUI\n form1.label1.caption := outputyears;\nend;\n", "language": "Delphi" }, { "code": "proc nonrec weekday(word y, m, d) byte:\n word c;\n if m<3 then\n m := m+10;\n y := y+1\n else\n m := m-2\n fi;\n c := y/100;\n y := y%100;\n ((26 * m - 2)/10 + d + y + y/4 + c/4 - 2*c + 777) % 7\ncorp\n\nproc nonrec main() void:\n word year;\n for year from 2008 upto 2121 do\n if weekday(year, 12, 25)=0 then\n writeln(year)\n fi\n od\ncorp\n", "language": "Draco" }, { "code": "func dayOfTheWeek year month day .\n # Based on Conway's doomsday algorithm\n # 1. Calculate the doomsday for the century\n century = floor (year / 100)\n if century mod 4 = 0\n centuryDoomsday = 2\n elif century mod 4 = 1\n centuryDoomsday = 0\n elif century mod 4 = 2\n centuryDoomsday = 5\n elif century mod 4 = 3\n centuryDoomsday = 3\n .\n # 2. Find the doomsday of the year\n mainYear = year mod 100\n yearDoomsday = (floor (mainYear / 12) + mainYear mod 12 + floor (mainYear mod 12 / 4) + centuryDoomsday) mod 7\n # 3. Check if the year is leap\n if mainYear = 0\n if century mod 4 = 0\n leap = 1\n else\n leap = 0\n .\n else\n if mainYear mod 4 = 0\n leap = 1\n else\n leap = 0\n .\n .\n # 4. Calculate the DOTW of January 1\n if leap = 1\n januaryOne = (yearDoomsday + 4) mod 7\n else\n januaryOne = (yearDoomsday + 5) mod 7\n .\n # 5. Determine the nth day of the year\n if month = 1\n NthDay = 0\n elif month = 2\n NthDay = 31\n elif month = 3\n NthDay = 59 + leap\n elif month = 4\n NthDay = 90 + leap\n elif month = 5\n NthDay = 120 + leap\n elif month = 6\n NthDay = 151 + leap\n elif month = 7\n NthDay = 181 + leap\n elif month = 8\n NthDay = 212 + leap\n elif month = 9\n NthDay = 243 + leap\n elif month = 10\n NthDay = 273 + leap\n elif month = 11\n NthDay = 304 + leap\n elif month = 12\n NthDay = 334 + leap\n .\n NthDay += day\n # 6. Finally, calculate the day of the week\n return (januaryOne + NthDay - 1) mod 7\n.\nfor i = 2008 to 2121\n if dayOfTheWeek i 12 25 = 0\n print \"Christmas in \" & i & \" is on Sunday\"\n .\n.\n", "language": "EasyLang" }, { "code": "//In what years between 2008 and 2121 will the 25th of December be a Sunday?\n\nIMPORT STD;\n\nBaseYear := 2008;\nEndYear := 2121;\n\nChristmasDay := RECORD\n UNSIGNED1 DayofWeek;\n UNSIGNED2 Year;\nEND;\n\nChristmasDay FindDate(INTEGER Ctr) := TRANSFORM\n SELF.DayofWeek := (STD.Date.FromGregorianYMD((BaseYear-1) + Ctr,12,25)) % 7; //0=Sunday\n SELF.Year := (BaseYear-1) + Ctr;\nEND;\n\nYearDS := DATASET(EndYear-BaseYear,FindDate(COUNTER));\nOUTPUT(YearDS(DayofWeek=0),{Year});\n\n/* Outputs:\n 2011\n 2016\n 2022\n 2033\n 2039\n 2044\n 2050\n 2061\n 2067\n 2072\n 2078\n 2089\n 2095\n 2101\n 2107\n 2112\n 2118\n*/\n", "language": "ECL" }, { "code": "[Day of week for Rosetta Code.]\n[EDSAC program, Initial Orders 2.]\n\n[Library subroutine M3 - prints header and is then overwritten.]\n[Here, the last character sets the teleprinter to figures.]\n PF GK IF AF RD LF UF OF E@ A6F G@ E8F EZ PF\n *CHRISTMAS!DAY!ON!SUNDAY@&#\n ..PZ [blank tape, then resync]\n\n[Subroutine to find day of week in Gregorian calendar, by Zeller's method.]\n[This EDSAC implementation is valid up to and including 28 Feb 43699.]\n[Input: 4F = year, 5F = month, 6F = day of month (all preserved).]\n[Output: 7F = day of week: 0 = Saturday, 1 = Sunday, ..., 6 = Friday.]\n[Workspace: 0F]\n T128K GK\n A3F T41@ [plant return link as usual]\n[January and February are taken as months 13 and 14 of the previous year]\n A5F [load month]\n S43@ [subtract 3 to test for Jan or Feb]\n E9@ [jump if not Jan or Feb]\n A45@ [add 16 to make month + 1]\n T7F [to 7F]\n S42@ [acc := -1]\n G11@ [join common code]\n [9] A44@ [not Jan, Feb; make month + 1]\n T7F [to 7F; acc := 0]\n [11] A4F [here with acc = 0 or -1; add year]\n TF [adjusted year to 0F]\n H46@ [mult reg := 13/20 (near enough)]\n V7F [times (month + 1)]\n L1F [shift 2 left]\n T7F [7F := 13*(month + 1) div 5]\n AF [year]\n R1F [shift 2 right]\n AF [year + (year div 4)]\n A7F [add into 7F]\n T7F\n H47@ [mult reg := 64/100 (approx, OK for dates as above)]\n VF [times year]\n R16F [shift 6 right]\n UF [0F := year div 100]\n R1F [shift 2 more right]\n SF [(year div 400) - (year div 100)]\n A6F [add day of month]\n A7F [add into 7F]\n T7F\n[Finally take 7F modulo 7. Suppose 7F = 7*q + r (0 <= r < 7)]\n H48@ [mult reg := 4/7 (near enough)]\n V7F [acc := 4*q + (4/7)*r]\n R1F [shift 2 right: acc := q + r/7]\n TF [0F := acc high word = q]\n H49@ [mult reg := 7/8 (exact)]\n A7F [acc := 7*q + r]\n R2F [shift 3 right, acc := (7*q + r)/8]\n NF [subtract (7/8)*q, acc := r/8]\n L2F [shift 3 left, acc := r as required]\n T7F [return result r in 7F]\n [41] ZF [(planted) jump back to caller]\n[Constants]\n [42] PD [1]\n [43] P1D [3]\n [44] P2F [4]\n [45] P8F [16]\n [46] J819D [0.A667 hex, approx 13/20]\n [47] J492F [0.A3D8 hex, approx 64/100]\n [48] O293F [0.924A hex, approx 4/7]\n [49] KF [0.1110 hex = 7/8]\n\n[Subroutine to print non-negative 17-bit integer.]\n[Parameters: 0F = integer to be printed (not preserved)\n 1F = character for leading zero (preserved)]\n[Workspace: 4F..7F, 38 locations]\n T64K\n GK A3F T34@ A1F T7F S35@ T6F T4#F AF T4F H36@ V4F RD A4#F R1024F H37@ E23@ O7F A2F\n T6F T5F V4#F YF L8F T4#F A5F L1024F UF A6F G16@ OF TF T7F A6F G17@ ZF P4F Z219D TF\n\n[Main routine]\n T400K GK\n[Constants]\n [0] P1004F [2008]\n [1] P1060D [2121]\n [2] P6F [12 (December)]\n [3] P12D [25]\n [4] PD [1]\n [5] @F [carriage return]\n [6] &F [line feed]\n [7] K4096F [null char]\n[Variable]\n [8] PF [year]\n[Enter with acc = 0]\n [9] A7@ T1F [1F := null for print subroutine]\n A@ [load first year]\n [12] U8@ T4F [save year, and pass to Zeller subroutine]\n A2@ T5F [pass month 12 to Zeller subroutine]\n A3@ T6F [pass day 25 to Zeller subroutine]\n A18@ G128F [call Zeller subroutine]\n A7F S4@ [load day of week, subtract 1]\n G32@ [jump if day = 0]\n S4@ E32@ [subtract 1, jump if day >= 2]\n TF [here if day = 1 (Sunday); clear acc]\n A4F TF [pass year to print subroutine]\n A28@ G64F [call print subroutine (overwrites 4F)]\n O5@ O6@ [print CR, LF]\n [32] TF [common code; clear acc]\n A8@ S1@ [test for end]\n E39@ [jump to exit if so]\n A1@ [restore acc after test]\n A4@ E12@ [inc year and loop back]\n [39] O7@ [done; print null]\n ZF [halt the machine]\n\n E9Z [define entry point]\n PF [acc = 0 on entry]\n[end]\n", "language": "EDSAC-order-code" }, { "code": "Enum.each(2008..2121, fn year ->\n wday = Date.from_erl!({year, 12, 25}) |> Date.day_of_week\n if wday==7, do: IO.puts \"25 December #{year} is sunday\"\nend)\n", "language": "Elixir" }, { "code": "(require 'calendar)\n\n(defun sunday-p (y)\n \"Is Dec 25th a Sunday in this year?\"\n (= (calendar-day-of-week (list 12 25 y)) 0))\n\n(defun xmas-sunday (a b)\n \"In which years in the range a, b is Dec 25th a Sunday?\"\n (seq-filter #'sunday-p (number-sequence a b)))\n\n(print (xmas-sunday 2008 2121))\n", "language": "Emacs-Lisp" }, { "code": "% Implemented by bengt kleberg\n-module(yuletide).\n-export([main/0, sunday_years/2]).\n\nmain() ->\n\t[io:fwrite(\"25 December ~p is Sunday~n\", [X]) || X <- sunday_years(2008, 2121)].\n\nsunday_years( Start, Stop ) ->\n\t[X || X <- lists:seq(Start, Stop), is_sunday(calendar:day_of_the_week({X, 12, 25}))].\n\nis_sunday( 7 ) -> true;\nis_sunday( _ ) -> false.\n", "language": "Erlang" }, { "code": "PROGRAM DAY_OF_THE_WEEK\n\nPROCEDURE MODULO(X,Y->RES)\n IF Y=0 THEN\n RES=X\n ELSE\n RES=X-Y*INT(X/Y)\n END IF\nEND PROCEDURE\n\nPROCEDURE WD(M,D,Y->RES%)\n IF M=1 OR M=2 THEN\n M+=12\n Y-=1\n END IF\n MODULO(365*Y+INT(Y/4)-INT(Y/100)+INT(Y/400)+D+INT((153*M+8)/5),7->RES)\n RES%=RES+1.0\nEND PROCEDURE\n\nBEGIN\nPRINT(CHR$(12);) ! CLS\nFOR YR=2008 TO 2121 DO\n WD(12,25,YR->RES%)\n IF RES%=1 THEN ! day 1 is Sunday......\n PRINT(\"Dec\";25;\",\";YR)\n END IF\nEND FOR\nGET(K$)\nEND PROGRAM\n", "language": "ERRE" }, { "code": "--Day of the week task from Rosetta Code wiki\n--User:Lnettnay\n\n--In what years between 2008 and 2121 will the 25th of December be a Sunday\n\ninclude std/datetime.e\n\ndatetime dt\n\nfor year = 2008 to 2121 do\n dt = new(year, 12, 25)\n if weeks_day(dt) = 1 then -- Sunday = 1\n ? year\n end if\nend for\n", "language": "Euphoria" }, { "code": "open System\n\n[ 2008 .. 2121 ]\n|> List.choose (fun y -> if DateTime(y,12,25).DayOfWeek = DayOfWeek.Sunday then Some(y) else None)\n|> printfn \"%A\"\n", "language": "F-Sharp" }, { "code": "USING: calendar math.ranges prettyprint sequences ;\n2008 2121 [a,b] [ 12 25 <date> sunday? ] filter .\n", "language": "Factor" }, { "code": "#APPTYPE CONSOLE\n\n'In what years between 2008 and 2121 will the 25th of December be a Sunday?\ndim date as integer, dayname as string\nfor dim year = 2008 to 2121\n\tdate = year * 10000 + 1225\n\tdayname = dateconv(date,\"dddd\")\n\tif dayname = \"Sunday\" then\n\t\tprint \"Christmas Day is on a Sunday in \", year\n\tend if\nnext\nPAUSE\n", "language": "FBSL" }, { "code": "\\ Zeller's Congruence\n: weekday ( d m y -- wd) \\ 1 mon..7 sun\n over 3 < if 1- swap 12 + swap then\n 100 /mod\n dup 4 / swap 2* -\n swap dup 4 / + +\n swap 1+ 13 5 */ + +\n ( in zeller 0=sat, so -2 to 0= mon, then mod, then 1+ for 1=mon)\n 2- 7 mod 1+ ;\n\n: yuletide\n .\" December 25 is Sunday in \"\n 2122 2008 do\n 25 12 i weekday\n 7 = if i . then\n loop cr ;\n", "language": "Forth" }, { "code": "cr yuletide\nDecember 25 is Sunday in 2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2101 2107 2112 2118\n ok\n", "language": "Forth" }, { "code": ": yuletide\n .\" December 25 is Sunday in \"\n 2122 2008 do\n 25 12 i d/m/y\n 7 mod 0= if i . then\n loop cr ;\n\ncr yuletide\nDecember 25 is Sunday in 2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2100 2106 2117\n", "language": "Forth" }, { "code": "include lib/time.4th\n\n: yuletide\n .\" December 25 is Sunday in \"\n 2122 2008 do\n 25 12 i weekday\n 6 = if i . then\n loop cr ;\n\ncr yuletide\n", "language": "Forth" }, { "code": "PROGRAM YULETIDE\n\nIMPLICIT NONE\n\nINTEGER :: day, year\n\nWRITE(*, \"(A)\", ADVANCE=\"NO\") \"25th of December is a Sunday in\"\nDO year = 2008, 2121\n day = Day_of_week(25, 12, year)\n IF (day == 1) WRITE(*, \"(I5)\", ADVANCE=\"NO\") year\nEND DO\n\nCONTAINS\n\nFUNCTION Day_of_week(d, m, y)\n INTEGER :: Day_of_week, j, k, mm, yy\n INTEGER, INTENT(IN) :: d, m, y\n\n mm=m\n yy=y\n IF(mm.le.2) THEN\n mm=mm+12\n yy=yy-1\n END IF\n j = yy / 100\n k = MOD(yy, 100)\n Day_of_week = MOD(d + ((mm+1)*26)/10 + k + k/4 + j/4 + 5*j, 7)\nEND FUNCTION Day_of_week\n\nEND PROGRAM YULETIDE\n", "language": "Fortran" }, { "code": "' version 17-06-2015\n' compile with: fbc -s console\n\nFunction wd(m As Integer, d As Integer, y As Integer) As Integer\n If m < 3 Then ' If m = 1 Or m = 2 Then\n m += 12\n y -= 1\n End If\n Return (y + (y \\ 4) - (y \\ 100) + (y \\ 400) + d + ((153 * m + 8) \\ 5)) Mod 7\nEnd Function\n\n' ------=< MAIN >=------\n\nFor yr As Integer = 2008 To 2121\n If wd(12, 25, yr) = 0 Then\n Print \"Dec 25 \"; yr\n EndIf\nNext\n\n' empty keyboard buffer\nWhile InKey <> \"\" : Wend\nPrint : Print \"hit any key to end program\"\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "Declare Function modulo(x As Double, y As Double) As Double\nDeclare Function wd(m As Double, d As Double, y As Double) As Integer\n\nCls\nDim yr As Double\nFor yr = 2008 To 2121\n\tIf wd(12,25,yr) = 1 Then\n\t\tPrint \"Dec \" & 25 & \", \" & yr\n\tEndIf\nNext\nSleep\n\nFunction modulo(x As Double, y As Double) As Double\n\tIf y = 0 Then\n\t\tReturn x\n\tElse\n\t\tReturn x - y * Int(x / y)\n\tEnd If\nEnd Function\n\nFunction wd(m As Double, d As Double, y As Double) As Integer\n\tIf m = 1 Or m = 2 Then\n\t\tm += 12\n\t\ty-= 1\n\tEnd If\n\tReturn modulo(365 * y + Fix(y / 4) - Fix(y / 100) + Fix(y / 400) + d + Fix((153 * m + 8) / 5), 7) + 1\nEnd Function\n", "language": "FreeBASIC" }, { "code": "' version 17-06-2015\n' Weekday And DateSerial only works with #Include \"vbcompat.bi\"\n' compile with: fbc -s console\n\n#Include Once \"vbcompat.bi\"\nDim As Double a\n\nFor yr As Integer = 2008 To 2121\n a = DateSerial (yr, 12, 25)\n If Weekday(a) = 1 Then Print Format(a, \"dd-mm-yyyy\") ' 1 = sunday, 2 = monday ...\nNext\n\n' empty keyboard buffer\nWhile InKey <> \"\" : Wend\nPrint : Print \"hit any key to end program\"\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "for y = 2008 to 2121\n if (parseDate[\"$y-12-25\"] -> ### u ###) == \"7\"\n println[y]\n", "language": "Frink" }, { "code": "window 1\n\nlong y\nCFDateRef dt\nNSInteger day\nCFCalendarRef cal\nDateComponentsRef comps\n\ncal = fn CalendarCurrent\n\ncomps = fn DateComponentsInit\nDateComponentsSetMonth( comps, 12 )\nDateComponentsSetDay( comps, 25 )\n\nfor y = 2008 to 2121\n DateComponentsSetYear( comps, y )\n dt = fn CalendarDateFromComponents( cal, comps )\n day = fn CalendarComponentFromDate( cal, NSCalendarUnitWeekday, dt )\n if ( day == 1 )\n print y\n end if\nnext\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\nDim siCount As Short\n\nFor siCount = 2008 To 2121\n If WeekDay(Date(siCount, 12, 25)) = 0 Then Print Format(Date(siCount, 12, 25), \"dddd dd mmmm yyyy\") & \" falls on a Sunday\"\nNext\n\nEnd\n", "language": "Gambas" }, { "code": "Filtered([2008 .. 2121], y -> WeekDay([25, 12, y]) = \"Sun\");\n# [ 2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118 ]\n\n# A possible implementation of WeekDayAlt\n\ndays := [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"];;\n\nWeekDayAlt := function(args)\n local d, m, y, k;\n d := args[1];\n m := args[2];\n y := args[3];\n if m < 3 then\n m := m + 12;\n y := y - 1;\n fi;\n k := 1 + RemInt(d + QuoInt((m + 1)*26, 10) + y + QuoInt(y, 4)\n + 6*QuoInt(y, 100) + QuoInt(y, 400) + 5, 7);\n return days[k];\nend;\n\nFiltered([2008 .. 2121], y -> WeekDayAlt([25, 12, y]) = \"Sun\");\n# [ 2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118 ]\n", "language": "GAP" }, { "code": "package main\n\nimport \"fmt\"\nimport \"time\"\n\nfunc main() {\n for year := 2008; year <= 2121; year++ {\n if time.Date(year, 12, 25, 0, 0, 0, 0, time.UTC).Weekday() ==\n time.Sunday {\n fmt.Printf(\"25 December %d is Sunday\\n\", year)\n }\n }\n}\n", "language": "Go" }, { "code": "def yuletide = { start, stop -> (start..stop).findAll { Date.parse(\"yyyy-MM-dd\", \"${it}-12-25\").format(\"EEE\") == \"Sun\" } }\n", "language": "Groovy" }, { "code": "println yuletide(2008, 2121)\n", "language": "Groovy" }, { "code": "10 REM Day of the week\n20 DEFINT D, M, Y-Z\n30 M = 12: D = 25\n40 FOR Y = 2007 TO 2122\n50 GOSUB 200\n60 IF Z = 0 THEN PRINT Y;\n70 NEXT Y\n80 PRINT\n90 END\n170 REM Calculate day of week Z given\n180 REM year Y, month M, and day D\n190 REM Sunday = 0, Saturday = 6\n200 IF M < 3 THEN Y = Y - 1: M = M + 12\n210 Z = Y + Y \\ 4 - Y \\ 100 + Y \\ 400\n220 Z = Z + D + (153 * M + 8) \\ 5\n230 Z = Z MOD 7\n240 RETURN\n", "language": "GW-BASIC" }, { "code": "import Data.Time (fromGregorian)\nimport Data.Time.Calendar.WeekDate (toWeekDate)\n\n--------------------- DAY OF THE WEEK --------------------\n\nisXmasSunday :: Integer -> Bool\nisXmasSunday year = 7 == weekDay\n where\n (_, _, weekDay) = toWeekDate $ fromGregorian year 12 25\n\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n mapM_\n putStrLn\n [ \"Sunday 25 December \" <> show year\n | year <- [2008 .. 2121],\n isXmasSunday year\n ]\n", "language": "Haskell" }, { "code": "import System.Time\n\nisXmasSunday :: Int -> Bool\nisXmasSunday year = ctWDay cal == Sunday\n where\n cal = toUTCTime $ toClockTime cal'\n cal' =\n CalendarTime\n { ctYear = year\n , ctMonth = December\n , ctDay = 25\n , ctHour = 0\n , ctMin = 0\n , ctSec = 0\n , ctPicosec = 0\n , ctWDay = Friday\n , ctYDay = 0\n , ctTZName = \"\"\n , ctTZ = 0\n , ctIsDST = False\n }\n\nmain :: IO ()\nmain =\n mapM_\n putStrLn\n [ \"25 December \" ++ show year ++ \" is Sunday\"\n | year <- [2008 .. 2121]\n , isXmasSunday year ]\n", "language": "Haskell" }, { "code": "DO year = 1, 1000000\n TIME(Year=year, MOnth=12, Day=25, TO, WeekDay=weekday)\n IF( weekday == 7) WRITE(StatusBar) year\nENDDO\n\nEND\n", "language": "HicEst" }, { "code": "link datetime\n\nprocedure main()\nwrites(\"December 25th is a Sunday in: \")\nevery writes((dayoweek(25,12,y := 2008 to 2122)==\"Sunday\",y),\" \")\nend\n", "language": "Icon" }, { "code": "procedure dayoweek(day, month, year)\t#: day of the week\n static d_code, c_code, m_code, ml_code, y, C, M, Y\n\n initial {\n d_code := [\"Saturday\", \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\"]\n\n c_code := table()\n c_code[16] := c_code[20] := 0\n c_code[17] := c_code[21] := 6\n c_code[18] := c_code[22] := 4\n c_code[19] := c_code[23] := 2\n\n m_code := table()\n m_code[1] := m_code[\"January\"] := 1\n m_code[2] := m_code[\"February\"] := 4\n m_code[3] := m_code[\"March\"] := 4\n m_code[4] := m_code[\"April\"] := 0\n m_code[5] := m_code[\"May\"] := 2\n m_code[6] := m_code[\"June\"] := 5\n m_code[7] := m_code[\"July\"] := 0\n m_code[8] := m_code[\"August\"] := 3\n m_code[9] := m_code[\"September\"] := 6\n m_code[10] := m_code[\"October\"] := 1\n m_code[11] := m_code[\"November\"] := 4\n m_code[12] := m_code[\"December\"] := 6\n\n ml_code := copy(m_code)\n ml_code[1] := ml_code[\"January\"] := 0\n ml_code[2] := ml_code[\"February\"] := 3\n }\n\n if year < 1600 then stop(\"*** can't compute day of week that far back\")\n if year > 2299 then stop(\"*** can't compute day of week that far ahead\")\n\n C := c_code[(year / 100) + 1]\n y := year % 100\n Y := (y / 12) + (y % 12) + ((y % 12) / 4)\n month := integer(month)\n M := if (year % 4) = 0 then ml_code[month] else m_code[month]\n\n return d_code[(C + Y + M + day) % 7 + 1]\n\nend\n", "language": "Icon" }, { "code": "100 PROGRAM \"Dayweek.bas\"\n110 PRINT \"The years between 2008 and 2121 will the 25th of December be a Sunday:\"\n120 FOR Y=2008 TO 2121\n130 IF DAYWEEK(Y,12,25)=0 THEN PRINT \"Dec 25,\";Y\n140 NEXT\n150 DEF DAYWEEK(Y,M,D)\n160 LET A=INT((14-M)/12):LET Y=Y-A\n170 LET W=D+INT((13*(M+12*A-2)-1)/5)+Y+INT(Y/4)-INT(Y/100)+INT(Y/400)\n180 LET DAYWEEK=W-7*INT(W/7)\n190 END DEF\n", "language": "IS-BASIC" }, { "code": " load 'dates' NB. provides verb 'weekday'\n xmasSunday=: #~ 0 = [: weekday 12 25 ,~\"1 0 ] NB. returns years where 25 Dec is a Sunday\n xmasSunday 2008 + i.114 NB. check years from 2008 to 2121\n2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2101 2107 2112 2118\n", "language": "J" }, { "code": "import static java.util.Calendar.*;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.GregorianCalendar;\n\npublic class Yuletide{\n\tpublic static void main(String[] args) {\n\t\tCalendar calendar;\n int count = 1;\n for (int year = 2008; year <= 2121; year++) {\n calendar = new GregorianCalendar(year, DECEMBER, 25);\n if (calendar.get(DAY_OF_WEEK) == SUNDAY) {\n if (count != 1)\n System.out.print(\", \");\n System.out.printf(\"%d\", calendar.get(YEAR));\n count++;\n }\n }\n\t}\n}\n", "language": "Java" }, { "code": "for (var year = 2008; year <= 2121; year++){\n var xmas = new Date(year, 11, 25)\n if ( xmas.getDay() === 0 )\n console.log(year)\n}\n", "language": "JavaScript" }, { "code": "(function () {\n 'use strict';\n\n // isXmasSunday :: Integer -> Bool\n function isXmasSunday(year) {\n return (new Date(year, 11, 25))\n .getDay() === 0;\n }\n\n // range :: Int -> Int -> [Int]\n function range(m, n) {\n return Array.apply(null, Array(n - m + 1))\n .map(function (_, i) {\n return m + i;\n });\n }\n\n return range(2008, 2121)\n .filter(isXmasSunday);\n\n})();\n", "language": "JavaScript" }, { "code": "(() => {\n \"use strict\";\n\n // main :: IO ()\n const main = () => {\n const\n xs = enumFromTo(2008)(2121)\n .filter(xmasIsSunday);\n\n return (\n console.log(xs),\n xs\n );\n };\n\n\n // xmasIsSunday :: Int -> Bool\n const xmasIsSunday = year =>\n (new Date(year, 11, 25))\n .getDay() === 0;\n\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "[2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118]\n", "language": "JavaScript" }, { "code": "# Use Zeller's Congruence to determine the day of the week, given\n# year, month and day as integers in the conventional way.\n# If iso == \"iso\" or \"ISO\", then emit an integer in 1 -- 7 where\n# 1 represents Monday, 2 Tuesday, etc;\n# otherwise emit 0 for Saturday, 1 for Sunday, etc.\n#\ndef day_of_week(year; month; day; iso):\n if month == 1 or month == 2 then\n [month + 12, year - 1]\n else\n [month, year]\n end\n | day + (13*(.[0] + 1)/5|floor)\n + (.[1]%100) + ((.[1]%100)/4|floor)\n + (.[1]/400|floor) - 2*(.[1]/100|floor)\n | if iso == \"iso\" or iso == \"ISO\" then 1 + ((. + 5) % 7)\n else . % 7\n end;\n", "language": "Jq" }, { "code": "# Give the results as an array so they can\n# readily be presented on a single line:\n[range(2008; 2122) | select( day_of_week(.;12;25;0) == 1 )]\n", "language": "Jq" }, { "code": "/* Day of the week, December 25th on a Sunday */\nfor (var year = 2008; year <= 2121; year++) {\n var xmas = strptime(year + '/12/25', '%Y/%m/%d');\n var weekDay = strftime(xmas, '%w');\n if (weekDay == 0) puts(year);\n}\n\n/*\n=!EXPECTSTART!=\n2011\n2016\n2022\n2033\n2039\n2044\n2050\n2061\n2067\n2072\n2078\n2089\n2095\n2101\n2107\n2112\n2118\n=!EXPECTEND!=\n*/\n", "language": "Jsish" }, { "code": "using Dates\n\nlo, hi = 2008, 2121\nxmas = collect(Date(lo, 12, 25):Year(1):Date(hi, 12, 25))\nfilter!(xmas) do dt\n dayofweek(dt) == Dates.Sunday\nend\n\nprintln(\"Years from $lo to $hi having Christmas on Sunday: \")\nforeach(println, year.(xmas))\n", "language": "Julia" }, { "code": " wd:{(__jd x)!7} / Julian day count, Sun=6\n y@&6={wd 1225+x*10000}'y:2008+!114\n2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2101 2107 2112 2118\n", "language": "K" }, { "code": "import std/time/date\nimport std/time/calendar\nimport std/time/instant\nimport std/time/utc\n\nfun main()\n for(2008, 2121) fn(year)\n val i = instant(year, 12, 25, cal=cal-gregorian)\n val dow = (i.days+6)%7 // plus 6 since 2000-01-01 epoch was a Saturday\n match dow.weekday\n Sun -> println(year.show)\n _ -> ()\n", "language": "Koka" }, { "code": "// version 1.0.6\n\nimport java.util.*\n\nfun main(args: Array<String>) {\n println(\"Christmas day in the following years falls on a Sunday:\\n\")\n val calendar = GregorianCalendar(2008, Calendar.DECEMBER, 25)\n for (year in 2008..2121) {\n if (Calendar.SUNDAY == calendar[Calendar.DAY_OF_WEEK]) println(year)\n calendar.add(Calendar.YEAR, 1)\n }\n}\n", "language": "Kotlin" }, { "code": "{xmasOnSunday 2008 2121}\n->\n2011\n2016\n2022\n2033\n2039\n2044\n2050\n2061\n2067\n2072\n2078\n2089\n2095\n2101\n2107\n2112\n2118\n\n{script\nLAMBDATALK.DICT[\"xmasOnSunday\"] = function() {\n var args = arguments[0].trim().split(\" \"),\n days = [];\n\n for (var year = args[0]; year <= args[1]; year++) {\n var xmas = new Date(year, 11, 25)\n if ( xmas.getDay() === 0 )\n days.push(year)\n }\n\n return days.join(\"\\n\")\n};\n}\n", "language": "Lambdatalk" }, { "code": "loop(-From=2008, -to=2121) => {^\n local(tDate = date('12/25/' + loop_count))\n #tDate->dayOfWeek == 1 ? '\\r' + #tDate->format('%D') + ' is a Sunday'\n^}\n", "language": "Lasso" }, { "code": "count = 0\nfor year = 2008 to 2121\n dateString$=\"12/25/\";year\n dayNumber=date$(dateString$)\n if dayNumber mod 7 = 5 then\n count = count + 1\n print dateString$\n end if\nnext year\nprint count; \" years when Christmas Day falls on a Sunday\"\nend\n", "language": "Liberty-BASIC" }, { "code": "put \"December 25 is a Sunday in:\"\nrefDateObj = date(1905,1,2)\nrepeat with year = 2008 to 2121\n dateObj = date(year, 12, 25)\n dayOfWeek = ((dateObj - refDateObj) mod 7)+1 -- 1=Monday..7=Sunday\n if dayOfWeek=7 then put year\nend repeat\n", "language": "Lingo" }, { "code": "function xmasSunday startDate endDate\n convert the long date to dateitems\n put it into xmasDay\n put 12 into item 2 of xmasDay\n put 25 into item 3 of xmasDay\n repeat with i = startDate to endDate\n put i into item 1 of xmasDay\n convert xmasDay to dateItems\n if item 7 of xmasDay is 1 then put i & comma after xmasYear\n end repeat\n if the last char of xmasYear is comma then delete the last char of xmasYear\n return xmasYear\nend xmasSunday\n", "language": "LiveCode" }, { "code": "put xmasSunday(2008,2121)\n", "language": "LiveCode" }, { "code": "; Determine if a Gregorian calendar year is leap\nto leap? :year\n output (and\n equal? 0 modulo :year 4\n not member? modulo :year 400 [100 200 300]\n )\nend\n\n; Convert Gregorian calendar date to a simple day count from\n; day 1 = January 1, 1 CE\nto day_number :year :month :day\n local \"elapsed make \"elapsed difference :year 1\n output (sum product 365 :elapsed\n int quotient :elapsed 4\n minus int quotient :elapsed 100\n int quotient :elapsed 400\n int quotient difference product 367 :month 362 12\n ifelse lessequal? :month 2 0 ifelse leap? :year -1 -2\n :day)\nend\n\n; Find the day of the week from a day number; 0 = Sunday through 6 = Saturday\nto day_of_week :day_number\n output modulo :day_number 7\nend\n\n; True if the given day is a Sunday\nto sunday? :year :month :day\n output equal? 0 day_of_week day_number :year :month :day\nend\n\n; Put it all together to answer the question posed in the problem\nprint filter [sunday? ? 12 25] iseq 2008 2121\nbye\n", "language": "Logo" }, { "code": "require(\"date\")\n\nfor year=2008,2121 do\n if date(year, 12, 25):getweekday() == 1 then\n print(year)\n end\nend\n", "language": "Lua" }, { "code": "local dTab = {day = 25, month = 12}\nfor year = 2008, 2121 do\n dTab.year = year\n if os.date(\"%A\", os.time(dTab)) == \"Sunday\" then\n print(year)\n end\nend\n", "language": "Lua" }, { "code": "Print \"December 25 is a Sunday in:\"\nFor Year=2008 to 2121 {\n if Str$(Date(\"25/12/\"+str$(Year,\"\")),\"w\")=\"1\" Then {\n Print Year\n }\n}\n\\\\ is the same with this:\nPrint \"December 25 is a Sunday in:\"\nFor Year=2008 to 2121 {\n if Str$(Date(str$(Year,\"\")+\"-12-25\"),\"w\")=\"1\" Then {\n Print Year\n }\n}\n", "language": "M2000-Interpreter" }, { "code": "divert(-1)\n\ndefine(`for',\n `ifelse($#,0,``$0'',\n `ifelse(eval($2<=$3),1,\n `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')\n\ndnl julian day number corresponding to December 25th of given year\ndefine(`julianxmas',\n `define(`yrssince0',eval($1+4712))`'define(`noOfLpYrs',\n eval((yrssince0+3)/4))`'define(`jd',\n eval(365*yrssince0+noOfLpYrs-10-($1-1501)/100+($1-1201)/400+334+25-1))`'\n ifelse(eval($1%4==0 && ($1%100!=0 || $1%400==0)),1,\n `define(`jd',incr(jd))')`'jd')\n\ndivert\n\nfor(`yr',2008,2121,\n `ifelse(eval(julianxmas(yr)%7==6),1,`yr ')')\n", "language": "M4" }, { "code": "xmas:= proc()\n\tlocal i, dt;\n\tfor i from 2008 to 2121 by 1 do\n\t\tdt := Date(i, 12, 25);\n\t\tif (Calendar:-DayOfWeek(dt) = 1) then\n\t\t\tprint(i);\n\t\tend if;\n\tend do;\nend proc;\n\nxmas();\n", "language": "Maple" }, { "code": "select(y->Calendar:-DayOfWeek(Date(y,12,25))=1,[$2008..2121]);\n", "language": "Maple" }, { "code": "Reap[If[DateString[{#,12,25},\"DayName\"]==\"Sunday\",Sow[#]]&/@Range[2008,2121]][[2,1]]\n", "language": "Mathematica" }, { "code": "{2011,2016,2022,2033,2039,2044,2050,2061,2067,2072,2078,2089,2095,2101,2107,2112,2118}\n", "language": "Mathematica" }, { "code": " t = datenum([[2008:2121]',repmat([12,25,0,0,0], 2121-2007, 1)]);\n t = t(strmatch('Sunday', datestr(t,'dddd')), :);\n datestr(t,'yyyy')\t\t\n", "language": "MATLAB" }, { "code": "weekday(year, month, day) := block([m: month, y: year, k],\n if m < 3 then (m: m + 12, y: y - 1),\n k: 1 + remainder(day + quotient((m + 1)*26, 10) + y + quotient(y, 4)\n + 6*quotient(y, 100) + quotient(y, 400) + 5, 7),\n ['monday, 'tuesday, 'wednesday, 'thurdsday, 'friday, 'saturday, 'sunday][k]\n)$\n\nsublist(makelist(i, i, 2008, 2121),\n lambda([y], weekday(y, 12, 25) = 'sunday));\n/* [2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118] */\n", "language": "Maxima" }, { "code": "10 REM Find years with Sunday Christmas\n20 LET F = 2008\n30 LET T = 2121\n40 PRINT \"Sunday Christmases\"; F; \"-\"; T\n50 PRINT\n60 FOR Y = F TO T\n70 LET E = Y*365+INT(Y/4)-INT(Y/100)+INT(Y/400)\n80 LET X = E-6\n90 LET D = X-7*INT(X/7)\n100 IF D <> 0 THEN 120\n110 PRINT Y,\n120 NEXT Y\n130 PRINT\n140 END\n", "language": "Minimal-BASIC" }, { "code": "import \"dateTime\"\n\nprint \"Years between 2008 and 2121 when 25th December falls on Sunday:\"\nyears = []\nfor year in range(2008, 2121)\n date = year + \"-12-25\"\n if dateTime.weekday(date) == 0 then years.push year\nend for\nprint years.join(\", \")\n", "language": "MiniScript" }, { "code": "MODULE Yule EXPORTS Main;\n\nIMPORT IO, Fmt, Date, Time;\n\nVAR date: Date.T;\n time: Time.T;\n\nBEGIN\n FOR year := 2008 TO 2121 DO\n date.day := 25;\n date.month := Date.Month.Dec;\n date.year := year;\n\n TRY\n time := Date.ToTime(date);\n EXCEPT\n | Date.Error =>\n IO.Put(Fmt.Int(year) & \" is the last year we can specify\\n\");\n EXIT;\n END;\n\n date := Date.FromTime(time);\n\n IF date.weekDay = Date.WeekDay.Sun THEN\n IO.Put(\"25th of December \" & Fmt.Int(year) & \" is Sunday\\n\");\n END;\n END;\nEND Yule.\n", "language": "Modula-3" }, { "code": "10 REM Find years with Sunday Christmas\n11 CLS\n20 LET F = 2008\n30 LET T = 2121\n40 PRINT \"Sunday Christmases\"; F; \"-\"; T\n50 PRINT\n60 FOR Y = F TO T\n70 LET E = Y * 365 + INT(Y/4) - INT(Y/100) + INT(Y/400)\n80 LET X = E - 6\n90 LET D = X - 7 * INT(X/7)\n100 IF D <> 0 THEN 120\n110 PRINT Y; \" \";\n120 NEXT Y\n130 PRINT\n140 END\n", "language": "MSX-Basic" }, { "code": "DOWHOLIDAY\n ;In what years between 2008 and 2121 will December 25 be a Sunday?\n ;Uses the VA's public domain routine %DTC (Part of the Kernel) named here DIDTC\n NEW BDT,EDT,CHECK,CHKFOR,LIST,I,X,Y\n ;BDT - the beginning year to check\n ;EDT - the end year to check\n ;BDT and EDT are year offsets from the epoch date 1/1/1700\n ;CHECK - the month and day to look at\n ;CHKFOR - what day of the week to look for\n ;LIST - list of years in which the condition is true\n ;I - the year currently being checked\n ;X - the date in an \"internal\" format, for input to DOW^DIDTC\n ;Y - the output from DOW^DIDTC\n SET BDT=308,EDT=421,CHECK=\"1225\",CHKFOR=0,LIST=\"\"\n FOR I=BDT:1:EDT SET X=I_CHECK D DOW^DIDTC SET:(Y=0) LIST=$SELECT($LENGTH(LIST):LIST_\", \",1:\"\")_(I+1700)\n IF $LENGTH(LIST)=0 WRITE !,\"There are no years that have Christmas on a Sunday in the given range.\"\n IF $LENGTH(LIST) WRITE !,\"The following years have Christmas on a Sunday: \",LIST\n KILL BDT,EDT,CHECK,CHKFOR,LIST,I,X,Y\n QUIT\n", "language": "MUMPS" }, { "code": "import Nanoquery.Util\n\n// loop through the years 2008 through 2121\nfor year in range(2008, 2121)\n\tif (new(Date,\"12/25/\" + str(year)).getDayOfWeek() = \"Sunday\")\n\t\tprintln \"In \" + year + \", December 25th is a Sunday.\"\n\tend if\nend for\n", "language": "Nanoquery" }, { "code": "/* NetRexx */\noptions replace format comments java crossref savelog symbols nobinary\n\nyearRanges = [int 2008, 2121]\nsearchday = ''\ncal = Calendar\n\nloop year = yearRanges[0] to yearRanges[1]\n cal = GregorianCalendar(year, Calendar.DECEMBER, 25)\n dayIndex = cal.get(Calendar.DAY_OF_WEEK)\n if dayIndex = Calendar.SUNDAY then searchday = searchday year\n end year\n\nsay 'Between' yearRanges[0] 'and' yearRanges[1]', Christmas day falls on a Sunday on the following years:'\nsearchday = searchday.strip.changestr(' ', ',')\nsay ' 'searchday\n\nreturn\n", "language": "NetRexx" }, { "code": "/* NetRexx */\noptions replace format comments java crossref savelog symbols nobinary\n\ndays = 'Monday Tuesday Wednesday Thursday Friday Saturday Sunday'\nyearRanges = [int 2008, 2121]\n\nsearchday = ''\nsearchday['index'] = days.wordpos('Sunday')\nsearchday[0] = 0\n\nalgorithmName = ['Java Calendar', 'Zeller[1]', 'Zeller[2]', 'Sakamoto', 'Gauss', 'Keith', 'Babwani']\n\nloop alg = 0 to algorithmName.length - 1\n sd = searchday[0] + 1\n searchday[0] = sd\n searchday['agorithm', sd] = algorithmName[alg]\n loop year = yearRanges[0] to yearRanges[1]\n select case alg\n when 0 then dayIndex = getDaynumJavaLibrary(year, 12, 25)\n when 1 then dayIndex = getDaynumZellersCongruenceMethod1(year, 12, 25)\n when 2 then dayIndex = getDaynumZellersCongruenceMethod2(year, 12, 25)\n when 3 then dayIndex = getDaynumSakamoto(year, 12, 25)\n when 4 then dayIndex = getDaynumGauss(year, 12, 25)\n when 5 then dayIndex = getDaynumKeith(year, 12, 25)\n when 6 then dayIndex = getDaynumBabwani(year, 12, 25)\n otherwise nop\n end\n if dayIndex = searchday['index'] then\n searchday[sd] = searchday[sd] year\n end year\n end alg\n\n-- display results\nsay 'Between' yearRanges[0] 'and' yearRanges[1]', Christmas day falls on a Sunday in the following years:'\nloop r_ = 1 to searchday[0]\n searchday[r_] = searchday[r_].strip.changestr(' ', ',')\n say searchday['agorithm', r_].right(20)':' searchday[r_]\n end r_\n\nreturn\n\n-- -----------------------------------------------------------------------------\nmethod getDaynumJavaLibrary(Year = int, Month = int, Day = int, iso = Rexx 'Y') public static binary returns int\n -- The day-of-week is an integer value where 1 is Sunday, 2 is Monday, ..., and 7 is Saturday\n -- For an ISO week date Day-of-Week d (1 = Monday to 7 = Sunday), use d = ((h - 1 + 6) mod 7) + 1\n\n cal = Calendar\n jmNumber = [ -\n Calendar.JANUARY, Calendar.FEBRUARY, Calendar.MARCH, Calendar.APRIL -\n , Calendar.MAY, Calendar.JUNE, Calendar.JULY, Calendar.AUGUST -\n , Calendar.SEPTEMBER, Calendar.OCTOBER, Calendar.NOVEMBER, Calendar.DECEMBER -\n ]\n\n mon = jmNumber[Month - 1]\n cal = GregorianCalendar(Year, mon, Day)\n h = cal.get(Calendar.DAY_OF_WEEK)\n\n if 'YES'.abbrev(iso.upper, 1) then w = ((h - 1 + 6) // 7) + 1\n else w = h\n\n return w\n\n-- -----------------------------------------------------------------------------\nmethod getDaynumZellersCongruenceMethod1(Year = int, Month = int, Day = int, iso = Rexx 'Y') public static returns int\n -- DayNum results in an integer in the range 0-6 where 0 represents Monday etc.\n -- For an ISO week date add 1\n\n if Month = 1 | Month = 2 then do\n Month = Month + 12\n Year = Year - 1\n end\n\n MonthFactor = 2 * Month + 3 * (Month + 1) % 5\n YearFactor = Year + Year % 4 - Year % 100 + Year % 400\n DayNum = (Day + MonthFactor + YearFactor) // 7\n\n if 'YES'.abbrev(iso.upper, 1) then d = DayNum + 1\n else d = DayNum\n\n return d\n\n-- -----------------------------------------------------------------------------\nmethod getDaynumZellersCongruenceMethod2(Year = int, Month = int, Day = int, iso = Rexx 'Y') public static binary returns int\n -- h is the day of the week (0 = Saturday, 1 = Sunday, 2 = Monday, ...)\n -- For an ISO week date Day-of-Week d (1 = Monday to 7 = Sunday), use d = ((h + 5) mod 7) + 1\n\n if Month < 3 then do\n Month = Month + 12\n Year = Year - 1\n end\n q = Day\n m = Month\n Y = Year\n\n h = (q + ((m + 1) * 26 % 10) + Y + (Y % 4) + 6 * (Y % 100) + (Y % 400)) // 7\n\n if 'YES'.abbrev(iso.upper, 1) then d = ((h + 5) // 7) + 1\n else d = h\n\n return d\n\n-- -----------------------------------------------------------------------------\nmethod getDaynumSakamoto(y = int, m = int, d = int, iso = Rexx 'Y') public static binary returns int\n -- h is the day of the week (0 = Sunday, 1 = Monday, 2 = Tuesday...)\n -- For an ISO week date Day-of-Week d (1 = Monday to 7 = Sunday), use d = ((h + 6) mod 7) + 1\n\n t = [int 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]\n y = y - (m < 3)\n h = (y + y % 4 - y % 100 + y % 400 + t[m - 1] + d) // 7\n\n if 'YES'.abbrev(iso.upper, 1) then d = ((h + 6) // 7) + 1\n else d = h\n\n return d\n\n-- -----------------------------------------------------------------------------\nmethod getDaynumGauss(Year = int, Month = int, Day = int, iso = Rexx 'Y') public static binary returns int\n -- W is week day (0 = Sunday, ..., 6 = Saturday)\n -- For an ISO week date Day-of-Week d (1 = Monday to 7 = Sunday), use d = ((h + 6) mod 7) + 1\n\n Year = Year - (Month < 3)\n k = double Day\n C = double Year % 100\n Y = double Year // 100\n m = double ((Month + 9) // 12) + 1\n\n W = modulo(int (k + Math.floor(2.6 * m - 0.2) + y + Math.floor(y / 4) + Math.floor(c / 4) - 2 * c), 7)\n\n if 'YES'.abbrev(iso.upper, 1) then h = ((W + 6) // 7) + 1\n else h = W\n\n return h\n\n-- -----------------------------------------------------------------------------\nmethod getDaynumKeith(y = int, m = int, d = int, iso = Rexx 'Y') public constant binary returns int\n -- W is week day (0 = Sunday, ..., 6 = Saturday)\n -- For an ISO week date Day-of-Week d (1 = Monday to 7 = Sunday), use d = ((h + 6) mod 7) + 1\n\n if m < 3 then do\n d = d + y\n y = y - 1\n end\n else do\n d = d + y - 2\n end\n\n h = (23 * m % 9 + d + 4 + y % 4 - y % 100 + y % 400) // 7\n\n if 'YES'.abbrev(iso.upper, 1) then W = ((h + 6) // 7) + 1\n else W = h\n\n return W\n\n-- -----------------------------------------------------------------------------\nmethod getDaynumBabwani(Year = int, Month = int, Day = int, iso = Rexx 'Y') public constant binary returns int\n -- return dow = Day of week: 0 = Saturday, 1 = Sunday, ... 6 = Friday\n -- For an ISO week date Day-of-Week W (1 = Monday to 7 = Sunday), use W = ((dow + 5) mod 7) + 1\n\n y = Year\n m = Month\n d = Day\n\n dow = int -- dow stands for day of week\n dowfg = double\n fmonth = int\n leap = int\n\n if ((y // 100 == 0) & (y // 400 \\= 0)) then -- leap function 1 for leap & 0 for non-leap\n leap = 0\n else if (y // 4 == 0) then\n leap = 1\n else\n leap = 0\n\n fmonth = 3 + (2 - leap) * ((m + 2) % (2 * m)) + (5 * m + m % 9) % 2 -- f(m) formula\n fmonth = fmonth // 7 -- f(m) is brought in range of 0 to 6\n\n century = y % 100\n lastdigits = y // 100\n\n dowfg = 1.25 * lastdigits + fmonth + d - 2 * (century // 4) -- function of weekday for Gregorian\n dow = int dowfg // 7 -- remainder on division by 7\n\n if 'YES'.abbrev(iso.upper, 1) then W = ((dow + 5) // 7) + 1\n else W = dow\n\n return W\n\n-- -----------------------------------------------------------------------------\nmethod modulo(N = int, D = int) inheritable static binary returns int\n return (D + (N // D)) // D\n", "language": "NetRexx" }, { "code": "import times\n\nfor year in 2008..2121:\n if getDayOfWeek(25, mDec, year) == dSun:\n stdout.write year, ' '\necho \"\"\n", "language": "Nim" }, { "code": "MODULE DayOfWeek;\nIMPORT NPCT:Dates, Out;\nVAR\n year: INTEGER;\n date: Dates.Date;\nBEGIN\n FOR year := 2008 TO 2121 DO\n date := Dates.NewDate(25,12,year);\n IF date.DayOfWeek() = Dates.sunday THEN\n Out.Int(date.year,4);Out.Ln\n END\n END\nEND DayOfWeek.\n", "language": "Oberon" }, { "code": "MODULE DaysOfWeek; (** AUTHOR \"\"; PURPOSE \"\"; *)\n\nIMPORT\n\tOut := KernelLog, Dates;\n\t\nPROCEDURE Do*;\nVAR\n\tdate: Dates.DateTime;\n\ti,y,w,wd: LONGINT;\nBEGIN\n\tFOR i := 2008 TO 2121 DO\n\t\tdate.year := i;date.month :=12; date.day := 25;\n\t\tdate.hour := 0;date.minute := 0; date.second := 0;\n\t\tDates.WeekDate(date,y,w,wd);\n\t\tIF wd = 7 THEN Out.Int(i,0);Out.Ln END\n\tEND\nEND Do;\n\nEND DaysOfWeek.\n", "language": "Oberon" }, { "code": "#import <Foundation/Foundation.h>\n\nint main()\n{\n @autoreleasepool {\n for(NSUInteger i=2008; i<2121; i++)\n {\n NSCalendarDate *d = [[NSCalendarDate alloc]\n initWithYear: i\n month: 12\n day: 25\n hour: 0 minute: 0 second:0\n timeZone: [NSTimeZone timeZoneWithAbbreviation:@\"CET\"] ];\n if ( [d dayOfWeek] == 0 )\n {\n printf(\"25 Dec %u is Sunday\\n\", i);\n }\n }\n\n }\n return 0;\n}\n", "language": "Objective-C" }, { "code": "#load \"unix.cma\"\nopen Unix\n\ntry\n for i = 2008 to 2121 do\n (* I'm lazy so we'll just borrow the current time\n instead of having to set all the fields explicitly *)\n let mytime = { (localtime (time ())) with\n tm_year = i - 1900;\n tm_mon = 11;\n tm_mday = 25 } in\n try\n let _, mytime = mktime mytime in\n if mytime.tm_wday = 0 then\n Printf.printf \"25 December %d is Sunday\\n\" i\n with e ->\n Printf.printf \"%d is the last year we can specify\\n\" (i-1);\n raise e\n done\nwith _ -> ()\n", "language": "OCaml" }, { "code": "open CalendarLib\n\nlet list_make_seq first last =\n let rec aux i acc =\n if i < first then acc\n else aux (pred i) (i::acc)\n in\n aux last []\n\nlet print_date (year, month, day) =\n Printf.printf \"%d-%02d-%02d\\n\" year month day\n\nlet () =\n let years = list_make_seq 2008 2121 in\n let years = List.filter (fun year ->\n Date.day_of_week (Date.make year 12 25) = Date.Sun) years in\n print_endline \"December 25 is a Sunday in:\";\n List.iter (Printf.printf \"%d\\n\") years\n", "language": "OCaml" }, { "code": "import: date\nseqFrom(2008, 2121) filter(#[ 12 25 Date newDate dayOfWeek Date.SUNDAY == ]) .\n", "language": "Oforth" }, { "code": "date = .datetime~new(2008, 12, 25)\nlastdate = .datetime~new(2121, 12, 25)\n\nresultList = .array~new -- our collector of years\n\n-- date objects are directly comparable\nloop while date <= lastdate\n if date~weekday == 7 then resultList~append(date~year)\n -- step to the next year\n date = date~addYears(1)\nend\n\nsay \"Christmas falls on Sunday in the years\" resultList~toString(\"Line\", \", \")\n", "language": "OoRexx" }, { "code": "/* REXX */\nParse Arg yyyymmdd\nIf arg(1)='' |,\n arg(1)='?' Then Do\n Say 'rexx wd yyyymmdd will show which weekday that is'\n Exit\n End\nParse Var yyyymmdd y +4 m +2 d\nwd=.Array~of('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday')\ndt=.DateTime~new(y,m,d)\nsay yyyymmdd 'is a' wd[dt~weekday]\n", "language": "OoRexx" }, { "code": "10 REM DAY OF THE WEEK\n20 LET M=12,D=25\n30 FOR Y=2007 TO 2122\n40 GOSUB 200\n50 IF Z=0 PRINT Y,\" \",\n60 NEXT Y\n70 PRINT\n80 STOP\n170 REM CALCULATE DAY OF WEEK Z GIVEN\n180 REM YEAR Y, MONTH M, AND DAY D\n190 REM SUNDAY = 0, SATURDAY = 6\n200 IF M<3 LET Y=Y-1,M=M+12\n210 LET Z=Y+Y/4-Y/100+Y/400\n220 LET Z=Z+D+(153*M+8)/5\n230 LET Z=Z-(Z/7)*7\n240 RETURN\n", "language": "Palo-Alto-Tiny-BASIC" }, { "code": "njd(D) =\n{\n my (m, y);\n\n if (D[2] > 2, y = D[1]; m = D[2]+1, y = D[1]-1; m = D[2]+13);\n\n (1461*y)\\4 + (306001*m)\\10000 + D[3] - 694024 + if (100*(100*D[1]+D[2])+D[3] > 15821004, 2 - y\\100 + y\\400)\n}\n\nfor (y = 2008, 2121, if (njd([y,12,25]) % 7 == 1, print(y)));\n", "language": "PARI-GP" }, { "code": "<@ SAI>\n\t<@ ITEFORLI3>2121|2008|\n\t\t<@ LETVARCAP>Christmas Day|25-Dec-<@ SAYVALFOR>...</@></@>\n\t\t<@ TSTDOWVARLIT>Christmas Day|1</@>\n\t\t<@ IFF>\n\t\t\t<@ SAYCAP>Christmas Day <@ SAYVALFOR>...</@> is a Sunday</@><@ SAYKEY>__Newline</@>\n\t\t</@>\n\t</@>\n</@>\n", "language": "Peloton" }, { "code": "<# suppressimplicitoutput>\n\t<# iterate foriteration literalstring3>2121|2008|\n\t\t<# let variable capture>Christmas Day|25-Dec-<# say value foriteration>...</#></#>\n\t\t<# test dayofweek variable literal>Christmas Day|1</#>\n\t\t<# if>\n\t\t\t<# say capture>Christmas Day <# say value foriteration>...</#> is a Sunday</#><# say keyword>__Newline</#>\n\t\t</#>\n\t</#>\n\t\n</#>\n", "language": "Peloton" }, { "code": "#! /usr/bin/perl -w\n\nuse Time::Local;\nuse strict;\n\nforeach my $i (2008 .. 2121)\n{\n my $time = timelocal(0,0,0,25,11,$i);\n my ($s,$m,$h,$md,$mon,$y,$wd,$yd,$is) = localtime($time);\n if ( $wd == 0 )\n {\n print \"25 Dec $i is Sunday\\n\";\n }\n}\n\nexit 0;\n", "language": "Perl" }, { "code": "#! /usr/bin/perl -w\n\nuse DateTime;\nuse strict;\n\nforeach my $i (2008 .. 2121)\n{\n my $dt = DateTime->new( year => $i,\n month => 12,\n day => 25\n );\n if ( $dt->day_of_week == 7 )\n {\n print \"25 Dec $i is Sunday\\n\";\n }\n}\n\nexit 0;\n", "language": "Perl" }, { "code": "#! /usr/bin/perl -w\n\nuse DateTime;\nuse strict;\n\nfor (2008 .. 2121) {\n print \"25 Dec $_ is Sunday\\n\"\n if DateTime->new(year => $_, month => 12, day => 25)->day_of_week == 7;\n}\n\nexit 0;\n", "language": "Perl" }, { "code": "#! /usr/bin/perl -w\n\nuse DateTime;\nuse strict;\n\nprint join \" \", grep { DateTime->new(year => $_, month => 12, day => 25)->day_of_week == 7 } (2008 .. 2121);\n\n0;\n", "language": "Perl" }, { "code": "-->\n <span style=\"color: #000080;font-style:italic;\">-- demo\\rosetta\\Day_of_the_week.exw</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{<span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">y<span style=\"color: #0000FF;\">=<span style=\"color: #000000;\">2008</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">2121</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">day_of_week<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">y<span style=\"color: #0000FF;\">,<span style=\"color: #000000;\">12<span style=\"color: #0000FF;\">,<span style=\"color: #000000;\">25<span style=\"color: #0000FF;\">,<span style=\"color: #004600;\">true<span style=\"color: #0000FF;\">)<span style=\"color: #0000FF;\">=<span style=\"color: #008000;\">\"Sunday\"</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">res<span style=\"color: #0000FF;\">,<span style=\"color: #000000;\">y<span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #0000FF;\">?<span style=\"color: #000000;\">res\n<!--\n", "language": "Phix" }, { "code": "<?php\nfor($i=2008; $i<2121; $i++)\n{\n $datetime = new DateTime(\"$i-12-25 00:00:00\");\n if ( $datetime->format(\"w\") == 0 )\n {\n echo \"25 Dec $i is Sunday\\n\";\n }\n}\n?>\n", "language": "PHP" }, { "code": "go =>\n L = [Year : Year in 2008..2121, dow(Year, 12, 25) == 0],\n println(L),\n println(len=L.length),\n nl.\n\n% Day of week, Sakamoto's method\ndow(Y, M, D) = R =>\n T = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4],\n if M < 3 then\n Y := Y - 1\n end,\n R = (Y + Y // 4 - Y // 100 + Y // 400 + T[M] + D) mod 7.\n", "language": "Picat" }, { "code": "(for (Y 2008 (>= 2121 Y) (inc Y))\n (when (= \"Sunday\" (day (date Y 12 25)))\n (printsp Y) ) )\n", "language": "PicoLisp" }, { "code": "filter(Calendar.Year(2008)->range(Calendar.Year(2121))->years()->month(12)->day(25), lambda(object day){ return day->week_day()==7; })->year()->format_nice();\n", "language": "Pike" }, { "code": "var year, month, day, dayofweek;\n\nprocedure calcdayofweek;\nbegin\n if month < 3 then\n begin\n year := year - 1;\n month := month + 12\n end;\n dayofweek := year + year / 4 - year / 100 + year / 400;\n dayofweek := dayofweek + day + (153 * month + 8) / 5;\n dayofweek := dayofweek - (dayofweek / 7) * 7\nend;\n\nbegin\n month := 12; day := 25;\n year := 2007;\n while year <= 2122 do\n begin\n call calcdayofweek;\n if dayofweek = 0 then ! year;\n year := year + 1\n end\nend.\n", "language": "PL-0" }, { "code": "declare i picture '9999';\ndo i = 2008 to 2121;\n if weekday(days('25Dec' || i, 'DDMmmYYYY')) = 1 then\n put skip list ('Christmas day ' || i || ' is a Sunday');\nend;\n", "language": "PL-I" }, { "code": "/* Test of PL/I-80 routine to determine day of the week */\n\nsunday_christmas:\n proc options (main);\n %replace\n sunday by 0;\n dcl\n (year, w) fixed bin(15);\n put skip list ('Christmas will fall on Sunday in these years:');\n do year = 2008 to 2121;\n w = weekday((year),12,25);\n if w = sunday then\n put skip edit (year) (f(4));\n end;\n\n stop;\n\n/*\n* Return day of week (Sun=0, Mon=1, etc.) for a given\n* yr, mo, da using Zeller's congruence\n*/\nweekday:\n proc (yr, mo, da) returns (fixed bin(15));\n dcl (yr, mo, da) fixed bin(15);\n dcl (c, y, m, d, z) fixed bin(15);\n y = yr; /* make local copies */\n m = mo;\n d = da;\n if m < 3 then\n do;\n m = m + 10;\n y = y - 1;\n end;\n else m = m - 2;\n c = y / 100;\n y = mod(y, 100);\n z = (26 * m - 2) / 10;\n z = z + d + y + (y/4) + (c/4) - 2 * c + 777;\n return (mod(z, 7));\nend weekday;\n\nend sunday_christmas;\n", "language": "PL-I-80" }, { "code": "100H: /* FIND YEARS WHERE CHRISTMAS DAY FALLS ON A SUNDAY */\n\n /* CP/M BDOS SYSTEM CALL AND I/O ROUTINES */\n BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;\n PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;\n PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;\n PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;\n PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */\n DECLARE N ADDRESS;\n DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;\n V = N;\n W = LAST( N$STR );\n N$STR( W ) = '$';\n N$STR( W := W - 1 ) = '0' + ( V MOD 10 );\n DO WHILE( ( V := V / 10 ) > 0 );\n N$STR( W := W - 1 ) = '0' + ( V MOD 10 );\n END;\n CALL PR$STRING( .N$STR( W ) );\n END PR$NUMBER;\n\n /* TASK */\n\n /* RETURNS THE DAY OF THE WEEK CORRESPONDING To D/M/Y */\n DAY$OF$WEEK: PROCEDURE( D, M, Y )BYTE;\n DECLARE ( D, M, Y ) ADDRESS;\n DECLARE ( J, K, MM, YY ) ADDRESS;\n MM = M;\n YY = Y;\n IF MM <= 2 THEN DO;\n MM = MM + 12;\n YY = YY - 1;\n END;\n J = YY / 100;\n K = YY MOD 100;\n RETURN ( D + ( ( MM + 1 ) * 26 ) / 10 + K + K / 4 + J / 4 + 5 * J )\n MOD 7;\n END DAY$OF$WEEK ;\n\n DECLARE ( YEAR, MONTH, DAY, COUNT ) ADDRESS;\n CALL PR$STRING( .'25TH OF DECEMBER IS A SUNDAY IN$' );CALL PR$NL;\n COUNT = 0;\n DO YEAR = 2008 TO 2121;\n DAY = DAY$OF$WEEK( 25, 12, YEAR );\n IF DAY = 1 THEN DO;\n CALL PR$CHAR( ' ' );CALL PR$NUMBER( YEAR );\n IF ( COUNT := COUNT + 1 ) MOD 10= 0 THEN CALL PR$NL;\n END;\n END;\n\nEOF\n", "language": "PL-M" }, { "code": "2008..2121 | Where-Object { (Get-Date $_-12-25).DayOfWeek -eq \"Sunday\" }\n", "language": "PowerShell" }, { "code": "function Get-ChristmasHoliday\n{\n [CmdletBinding()]\n [OutputType([PSCustomObject])]\n Param\n (\n [Parameter(Mandatory=$false,\n ValueFromPipeline=$true,\n ValueFromPipelineByPropertyName=$true,\n Position=0)]\n [ValidateRange(1,9999)]\n [int[]]\n $Year = (Get-Date).Year\n )\n\n Process\n {\n [datetime]$christmas = Get-Date $Year/12/25\n\n switch ($christmas.DayOfWeek)\n {\n \"Sunday\" {[datetime[]]$dates = 1..5 | ForEach-Object {$christmas.AddDays($_)}}\n \"Monday\" {[datetime[]]$dates = $christmas, $christmas.AddDays(1)}\n \"Saturday\" {[datetime[]]$dates = $christmas.AddDays(-2), $christmas.AddDays(-1)}\n Default {[datetime[]]$dates = $christmas.AddDays(-1), $christmas}\n }\n\n $dates | Group-Object -Property Year |\n Select-Object -Property @{Name=\"Year\" ; Expression={$_.Name}},\n @{Name=\"DayOfWeek\"; Expression={$christmas.DayOfWeek}},\n @{Name=\"Christmas\"; Expression={$christmas.ToString(\"MM/dd/yyyy\")}},\n @{Name=\"DaysOff\" ; Expression={$_.Group | ForEach-Object {$_.ToString(\"MM/dd/yyyy\")}}}\n }\n}\n", "language": "PowerShell" }, { "code": "2008..2121 | Get-ChristmasHoliday | where DayOfWeek -match Su\n", "language": "PowerShell" }, { "code": "Get-ChristmasHoliday -Year (2008..2121 | Get-Random)\n", "language": "PowerShell" }, { "code": "(Get-Date | Get-ChristmasHoliday).DaysOff\n", "language": "PowerShell" }, { "code": "(Get-Date | Get-ChristmasHoliday).DaysOff | Get-Date\n", "language": "PowerShell" }, { "code": "main() :-\n christmas_days_falling_on_sunday(2011, 2121, SundayList),\n writeln(SundayList).\n\nchristmas_days_falling_on_sunday(StartYear, EndYear, SundayList) :-\n numlist(StartYear, EndYear, YearRangeList),\n include(is_christmas_day_a_sunday, YearRangeList, SundayList).\n\nis_christmas_day_a_sunday(Year) :-\n Date = date(Year, 12, 25),\n day_of_the_week(Date, DayOfTheWeek),\n DayOfTheWeek == 7.\n", "language": "Prolog" }, { "code": "For i=2008 To 2037\n If DayOfWeek(Date(i,12,25,0,0,0))=0\n PrintN(Str(i))\n EndIf\nNext\n", "language": "PureBasic" }, { "code": "from calendar import weekday, SUNDAY\n\n[year for year in range(2008, 2122) if weekday(year, 12, 25) == SUNDAY]\n", "language": "Python" }, { "code": "'''Days of the week'''\n\nfrom datetime import date\nfrom itertools import islice\n\n\n# xmasIsSunday :: Int -> Bool\ndef xmasIsSunday(y):\n '''True if Dec 25 in the given year is a Sunday.'''\n return 6 == date(y, 12, 25).weekday()\n\n\n# main :: IO ()\ndef main():\n '''Years between 2008 and 2121 with 25 Dec on a Sunday'''\n\n xs = list(filter(\n xmasIsSunday,\n enumFromTo(2008)(2121)\n ))\n total = len(xs)\n print(\n fTable(main.__doc__ + ':\\n\\n' + '(Total ' + str(total) + ')\\n')(\n lambda i: str(1 + i)\n )(str)(index(xs))(\n enumFromTo(0)(total - 1)\n )\n )\n\n\n# GENERIC -------------------------------------------------\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: list(range(m, 1 + n))\n\n\n# index (!!) :: [a] -> Int -> a\ndef index(xs):\n '''Item at given (zero-based) index.'''\n return lambda n: None if 0 > n else (\n xs[n] if (\n hasattr(xs, \"__getitem__\")\n ) else next(islice(xs, n, None))\n )\n\n\n\n# FORMATTING ---------------------------------------------\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# MAIN --\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "FOR yr = 2008 TO 2121\n IF wd(12, 25, yr) = 0 THEN PRINT \"Dec 25 \"; yr\nNEXT yr\nEND\n\nFUNCTION wd (m, d, y)\n IF m < 3 THEN\n LET m = m + 12\n LET y = y - 1\n END IF\n wd = ((y + INT(y / 4) - INT(y / 100) + INT(y / 400) + d + INT((153 * m + 8) / 5)) MOD 7)\nEND FUNCTION\n", "language": "QBasic" }, { "code": " AUTO 100,10\n\n DEF PROC Iso(S,O)\n REM passing starting & ending years via integers S & O\n LOCal y$,m%,d%,i$,n%,w%\n\n LET m%=12 : d%=25\n REM m% & d% are constants, so avoid recalculating n% (=48) each iteration\n LET i$=m%*256+ 19300 : n%=i$(2 TO 3)+ d%\n FOR count=S TO O\n LET y$=count : w%=(y$(1 TO 2)&\"32\"DIV 16+ count DIV 4+ count+ n%)MOD 7\n REM otherwise w%=(y$(1 TO 2)&\"16\"DIV 16+ count DIV 4+ count)MOD 7\n REM = further optimisation beyond skipping irrelevant years:\n IF w%=0 THEN PRINT count : count = count+ 4\n END FOR count\n END DEF Iso\n\nctrl+space\n", "language": "QL-SuperBASIC" }, { "code": " [ over 3 < if [ 1 - ]\n dup 4 / over +\n over 100 / -\n swap 400 / +\n swap 1 -\n [ table\n 0 3 2 5 0 3\n 5 1 4 6 2 4 ]\n + + 7 mod ] is dayofweek ( day month year --> weekday )\n\nsay \"The 25th of December is a Sunday in: \" cr\n2121 1+ 2008 - times\n [ 25 12 i^ 2008 + dayofweek\n 0 = if [ i^ 2008 + echo sp ] ]\n", "language": "Quackery" }, { "code": "years <- 2008:2121\nxmas <- as.POSIXlt(paste0(years, '/12/25'))\nyears[xmas$wday==0]\n# 2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2101 2107 2112 2118\n\n# Also:\nxmas=seq(as.Date(\"2008/12/25\"), as.Date(\"2121/12/25\"), by=\"year\")\nas.numeric(format(xmas[weekdays(xmas)== 'Sunday'], \"%Y\"))\n\n# Still another solution, using ISOdate and weekdays\nwith(list(years=2008:2121), years[weekdays(ISOdate(years, 12, 25)) == \"Sunday\"])\n\n# Or with \"subset\"\nsubset(data.frame(years=2008:2121), weekdays(ISOdate(years, 12, 25)) == \"Sunday\")$years\n\n# Simply replace \"Sunday\" with whatever it's named in your country,\n# or set locale first, with\nSys.setlocale(cat=\"LC_ALL\", \"en\")\n\n# Under MS Windows, write instead\nSys.setlocale(\"LC_ALL\", \"English\")\n", "language": "R" }, { "code": "#lang racket\n\n(require racket/date)\n\n(define (xmas-on-sunday? year)\n (zero? (date-week-day (seconds->date (find-seconds 0 0 12 25 12 year)))))\n\n(for ([y (in-range 2008 2121)] #:when (xmas-on-sunday? y))\n (displayln y))\n", "language": "Racket" }, { "code": "say join ' ', grep { Date.new($_, 12, 25).day-of-week == 7 }, 2008 .. 2121;\n", "language": "Raku" }, { "code": "REBOL [\n\tTitle: \"Yuletide Holiday\"\n\tURL: http://rosettacode.org/wiki/Yuletide_Holiday\n]\n\nfor y 2008 2121 1 [\n\td: to-date reduce [y 12 25]\n\tif 7 = d/weekday [prin [y \"\"]]\n]\n", "language": "REBOL" }, { "code": "Red []\nrepeat yy 114 [\n d: to-date reduce [25 12 (2007 + yy )]\n if 7 = d/weekday [ print d ] ;; 7 = sunday\n]\n;; or\nprint \"version 2\"\n\nd: to-date [25 12 2008]\nwhile [d <= 25/12/2121 ] [\n if 7 = d/weekday [\n print rejoin [d/day '. d/month '. d/year ]\n ]\n d/year: d/year + 1\n]\n", "language": "Red" }, { "code": " do year=2008 to 2121\n if date('w', year\"1225\", 's') == 'Sunday' then say year\n end /*year*/\n", "language": "REXX" }, { "code": " do year=2008 to 2121\n if date('b', year\"1225\", 's') // 7 == 6 then say year\n end /*year*/\n", "language": "REXX" }, { "code": "/*REXX program displays in which years 12/25 (December 25th) falls on a Sunday. */\nparse arg start finish . /*get the START and FINISH years. */\nif start=='' | start==\",\" then start=2008 /*Not specified? Then use the default.*/\nif finish=='' | finish==\",\" then finish=2121 /* \" \" \" \" \" \" */\n\n do y=start to finish /*process all the years specified. */\n\n if date('Weekday', y\"-12-25\", 'ISO')\\=='Sunday' then iterate\n\n /* if date('w' , y\"-12-25\", 'i' ) ··· (same as above). */\n /* ↑↑↑↑↑↑ ↑↑↑↑↑↑↑↑↑↑ ↑↑↑ */\n /* option yyyy-mm-dd fmt */\n\n say 'December 25th,' y \"falls on a Sunday.\"\n end /*y*/\n /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "/*REXX program (old school) displays in which years 12/25 (Dec. 25th) falls on a Sunday.*/\nparse arg start finish . /*get the START and FINISH years. */\nif start=='' | start==\",\" then start=2008 /*Not specified? Then use the default.*/\nif finish=='' | finish==\",\" then finish=2121 /* \" \" \" \" \" \" */\n\n do y=start to finish /*process all the years specified. */\n if dow(12,25,y)==1 then say 'December 25th,' y \"falls on a Sunday.\"\n end /*y*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ndow: procedure; parse arg m,d,y; if m<3 then do; m= m+12; y= y-1; end\n yL= left(y, 2); yr= right(y, 2); w= (d + (m+1)*26%10 +yr +yr%4 +yL%4 +5*yL) //7\n if w==0 then w= 7; return w /*Sunday=1, Monday=2, ··· Saturday=7*/\n", "language": "REXX" }, { "code": "for n = 2008 to 2121\n if n < 2100 leap = n - 1900 else leap = n - 1904 ok\n m = (((n-1900)%7) + floor(leap/4) + 27) % 7\n if m = 4 see \"25 Dec \" + n + nl ok\nnext\n", "language": "Ring" }, { "code": "require 'date'\n\n(2008..2121).each {|year| puts \"25 Dec #{year}\" if Date.new(year, 12, 25).sunday? }\n", "language": "Ruby" }, { "code": "(2008..2121).each {|year| puts \"25 Dec #{year}\" if Time.local(year, 12, 25).sunday?}\n", "language": "Ruby" }, { "code": "for year = 2008 to 2121\n if val(date$(\"12-25-\";year)) mod 7 = 5 then print \"For \";year;\"xmas is Sunday\"\nnext year\n", "language": "Run-BASIC" }, { "code": "extern crate chrono;\n\nuse chrono::prelude::*;\n\nfn main() {\n let years = (2008..2121).filter(|&y| Local.ymd(y, 12, 25).weekday() == Weekday::Sun).collect::<Vec<i32>>();\n println!(\"Years = {:?}\", years);\n}\n", "language": "Rust" }, { "code": "$constant SUNDAY = 0\n\nrem - compute p mod q\nfunction mod(p, q = integer) = integer\nend = p - q * (p/q)\n\ncomment\n return day of week (Sun = 0, Mon = 1, etc.) for a\n given Gregorian calendar date using Zeller's congruence\nend\nfunction dayofweek (mo, da, yr = integer) = integer\n var y, c, z = integer\n if mo < 3 then\n begin\n mo = mo + 10\n yr = yr - 1\n end\n else mo = mo - 2\n y = mod(yr,100)\n c = int(yr / 100)\n z = int((26 * mo - 2) / 10)\n z = z + da + y + int(y/4) + int(c/4) - 2 * c + 777\n z = mod(z,7)\nend = z\n\nrem - main program\nvar year = integer\nprint \"Christmas will fall on a Sunday in\"\nfor year=2008 to 2121\n if dayofweek(12,25,year) = SUNDAY then\n print year\nnext year\nend\n", "language": "S-BASIC" }, { "code": "data _null_;\ndo y=2008 to 2121;\n a=mdy(12,25,y);\n if weekday(a)=1 then put y;\nend;\nrun;\n\n/* 2011 2016 2022 2033 2039 2044 2050 2061 2067\n 2072 2078 2089 2095 2101 2107 2112 2118 */\n", "language": "SAS" }, { "code": "import java.util.{ Calendar, GregorianCalendar }\nimport Calendar.{ DAY_OF_WEEK, DECEMBER, SUNDAY }\n\nobject DayOfTheWeek extends App {\n val years = 2008 to 2121\n\n val yuletide =\n years.filter(year => (new GregorianCalendar(year, DECEMBER, 25)).get(DAY_OF_WEEK) == SUNDAY)\n\n // If you want a test: (optional)\n assert(yuletide ==\n Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061,\n 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118))\n\n println(yuletide.mkString(\n s\"${yuletide.length} Years between ${years.head} and ${years.last}\" +\n \" including where Christmas is observed on Sunday:\\n\", \", \", \".\"))\n}\n", "language": "Scala" }, { "code": "import java.time.{ DayOfWeek, LocalDate }\n\nobject DayOfTheWeek1 extends App {\n val years = 2008 to 2121\n val yuletide = for {\n year <- years\n if LocalDate.of(year, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY\n } yield year\n\n println(yuletide.mkString(\n s\"${yuletide.count(p => true)} Years between ${years.head} and ${years.last}\" +\n \" including where Christmas is observed on Sunday:\\n\", \", \", \".\"))\n}\n", "language": "Scala" }, { "code": "import java.time.{ DayOfWeek, LocalDate }\n\nobject DayOfTheWeek1 extends App {\n val years = 2008 to 2121\n val yuletide =\n years.filter(year => (LocalDate.of(year, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY))\n\n // If you want a test: (optional)\n assert(yuletide ==\n Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061,\n 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118))\n\n println(yuletide.mkString(\n s\"${yuletide.length} Years between ${years.head} and ${years.last}\" +\n \" including where Christmas is observed on Sunday:\\n\", \", \", \".\"))\n}\n", "language": "Scala" }, { "code": "import java.time.{ DayOfWeek, LocalDate }\nimport scala.annotation.tailrec\n\nobject DayOfTheWeek3 extends App {\n val years = 2008 to 2121\n val yuletide = {\n @tailrec\n def inner(anni: List[Int], accu: List[Int]): List[Int] = {\n if (anni == Nil) accu\n else inner(anni.tail, accu ++\n (if (LocalDate.of(anni.head, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY) List(anni.head)\n else Nil))\n }\n inner(years.toList, Nil)\n }\n\n // If you want a test: (optional)\n assert(yuletide ==\n Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061,\n 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118))\n\n println(yuletide.mkString(\n s\"${yuletide.length} Years between ${years.head} and ${years.last}\" +\n \" including where Christmas is observed on Sunday:\\n\", \", \", \".\"))\n}\n", "language": "Scala" }, { "code": "(define (day-of-week year month day)\n(if (< month 3)\n (begin (set! month (+ month 12)) (set! year (- year 1))))\n(+ 1\n (remainder (+ 5 day (quotient (* (+ 1 month) 13) 5)\n year (quotient year 4) (* (quotient year 100) 6) (quotient year 400))\n 7)))\n\n(define (task)\n(let loop ((y 2121) (v '()))\n(if (< y 2008)\n v\n (loop (- y 1)\n (if (= 7 (day-of-week y 12 25))\n (cons y v)\n v)))))\n\n(task)\n; (2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2101 2107 2112 2118)\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n include \"time.s7i\";\n\nconst proc: main is func\n local\n var integer: year is 0;\n begin\n for year range 2008 to 2122 do\n if dayOfWeek(date(year, 12, 25)) = 7 then\n writeln(\"Christmas comes on a sunday in \" <& year);\n end if;\n end for;\n end func;\n", "language": "Seed7" }, { "code": "// In what years between 2008 and 2121 will the 25th of December be a Sunday?\n\nrepeat with year = 2008 to 2121\n\tset Christmas to \"12/25/\" & year\n\tif the WeekDayName of Christmas is Sunday then\n\t\tput \"Christmas in \" & year & \" falls on a Sunday\"\n\tend if\nend repeat\n", "language": "SenseTalk" }, { "code": "require('Time::Local')\n \nfor year in (2008 .. 2121) {\n var time = %S<Time::Local>.timelocal(0,0,0,25,11,year)\n var wd = Time(time).local.wday\n if (wd == 0) {\n say \"25 Dec #{year} is Sunday\"\n }\n}\n", "language": "Sidef" }, { "code": "BEGIN\n INTEGER M,D,Y;\n M := 12;\n D := 25;\n FOR Y := 2008 STEP 1 UNTIL 2121 DO BEGIN\n INTEGER W,A,MM,YY;\n A := (14 - M)//12;\n MM := M + 12*A - 2;\n YY := Y - A;\n W := D + ((13*MM - 1)//5) + YY + (YY//4) - (YY//100) + (YY//400);\n W := MOD(W,7);\n IF W = 0 THEN\n BEGIN OUTINT(Y,0);\n OUTIMAGE;\n END;\n END;\nEND.\n", "language": "Simula" }, { "code": " 10 LET M=12\n 20 LET D=25\n 30 FOR Y=2008 TO 2121\n 40 GOSUB 80\n 50 IF W=0 THEN PRINT Y\n 60 NEXT Y\n 70 STOP\n 80 LET A=INT ((14-M)/12)\n 90 LET MM=M+12*A-2\n100 LET YY=Y-A\n110 LET W=D+INT ((13*MM-1)/5)+YY+INT (YY/4)-INT (YY/100)+INT (YY/400)\n120 LET W=W-7*INT (W/7)\n130 RETURN\n", "language": "Sinclair-ZX81-BASIC" }, { "code": "2008 to: 2121 do: [ :year | |date|\n date := Date newDay: 25 monthIndex: 12 year: year.\n date dayName = #Sunday\n ifTrue: [ date displayNl ]\n]\n", "language": "Smalltalk" }, { "code": "#!/usr/local/bin/spar\npragma annotate( summary, \"yuletide\" );\npragma annotate( description, \"A company decides that whenever Xmas falls on a Sunday they will give their\" );\npragma annotate( description, \"workers all extra paid holidays so that, together with any public holidays,\" );\npragma annotate( description, \"workers will not have to work the following week (between the 25th of\" );\npragma annotate( description, \"December and the first of January).\" );\npragma annotate( description, \"\");\npragma annotate( description, \"In what years between 2008 and 2121 will the 25th of December be a Sunday?\" );\npragma annotate( description, \"\");\npragma annotate( description, \"Using any standard date handling libraries of your programming language;\" );\npragma annotate( description, \"compare the dates calculated with the output of other languages to discover\" );\npragma annotate( description, \"any anomalies in the handling of dates which may be due to, for example,\" );\npragma annotate( description, \"overflow in types used to represent dates/times similar to y2k type\" );\npragma annotate( description, \"problems. \");\npragma annotate( see_also, \"http://rosettacode.org/wiki/Day_of_the_week\" );\npragma annotate( author, \"Ken O. Burtch \");\npragma license( unrestricted );\n\npragma restriction( no_external_commands );\n\nprocedure yuletide is\nbegin\n for Year in 2008..2121 loop\n if calendar.day_of_week ( calendar.time_of (Year, 12, 25, 0)) = 1 then\n put_line( \"Christmas \" & strings.image( Year ) & \" is on a Sunday\" );\n end if;\n end loop;\nend yuletide;\n", "language": "SparForte" }, { "code": "select extract(year from dt) as year_with_xmas_on_sunday\nfrom (\n select add_months(date '2008-12-25', 12 * (level - 1)) as dt\n from dual\n connect by level <= 2121 - 2008 + 1\n )\nwhere to_char(dt, 'Dy', 'nls_date_language=English') = 'Sun'\norder by 1\n;\n", "language": "SQL" }, { "code": "where dt - trunc(dt, 'iw') = 6\n", "language": "SQL" }, { "code": "WITH RECURSIVE cte AS (\n SELECT DATE('2008-12-25', '+'||(12*0)||' months') as dt, 1 AS level\n UNION ALL\n SELECT DATE('2008-12-25', '+'||(12*level)||' months') as dt, c.level + 1\n FROM cte c\n WHERE c.level <= 2121 - 2008 + 1\n )\n SELECT strftime('%Y', dt)\n FROM cte\n where strftime('%w', dt) = '0';\n", "language": "SQL" }, { "code": " WITH RECURSIVE cte AS (\n SELECT date '2008-12-25' + interval '12 month' * 0 as dt, 1 AS level\n UNION ALL\n SELECT date '2008-12-25' + interval '12 month' * level as dt, c.level + 1\n FROM cte c\n WHERE c.level <= 2121 - 2008 + 1\n )\n SELECT dt\n FROM cte\n where to_char(dt, 'Dy') = 'Sun';\n", "language": "SQL" }, { "code": "(* Call: yearsOfSundayXmas(2008, 2121) *)\nfun yearsOfSundayXmas(fromYear, toYear) =\n if fromYear>toYear then\n ()\n else\n let\n val d = Date.date {year=fromYear, month=Date.Dec, day=25,\n hour=0, minute=0, second=0,\n offset=SOME Time.zeroTime}\n val wd = Date.weekDay d\n in\n if wd=Date.Sun then\n (\n print(Int.toString fromYear ^ \"\\n\");\n yearsOfSundayXmas(fromYear+1, toYear)\n )\n else\n yearsOfSundayXmas(fromYear+1, toYear)\n end;\n", "language": "Standard-ML" }, { "code": "clear\nsca n=2121-2008+1\nset obs `=n'\ngen year=2007+_n\nlist if dow(mdy(12,25,year))==0, noobs sep(0)\n\n +------+\n | year |\n |------|\n | 2011 |\n | 2016 |\n | 2022 |\n | 2033 |\n | 2039 |\n | 2044 |\n | 2050 |\n | 2061 |\n | 2067 |\n | 2072 |\n | 2078 |\n | 2089 |\n | 2095 |\n | 2101 |\n | 2107 |\n | 2112 |\n | 2118 |\n +------+\n", "language": "Stata" }, { "code": "year=2008::2121\nselect(year,dow(mdy(12,25,year)):==0)\n", "language": "Stata" }, { "code": "year = 2008\nwhile (year <= 2121)\n {\n if Date('#' $ year $ '1225').WeekDay() is 0\n Print(year)\n ++year\n }\n", "language": "Suneido" }, { "code": "import Cocoa\n\nvar year=2008\nlet formatter=DateFormatter()\nformatter.dateFormat = \"yyyy-MM-dd\"\n\nlet gregorian:NSCalendar! = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)\nwhile (year<2122){\n var date:NSDate!=formatter.date(from: String(year)+\"-12-25\") as NSDate?\n var components=gregorian.components(NSCalendar.Unit.weekday, from: date as Date)\n var dayOfWeek:NSInteger=components.weekday!\n if(dayOfWeek==1){\n print(year)\n }\n year+=1\n}\n", "language": "Swift" }, { "code": "package require Tcl 8.5\n\nfor {set y 2008} {$y <= 2121} {incr y} {\n if {[clock format [clock scan \"$y-12-25\" -format {%Y-%m-%d}] -format %w] == 0} {\n puts \"xmas $y is a sunday\"\n }\n}\n", "language": "Tcl" }, { "code": ":For(A,2008,2121\n:If dayofWk(A,12,25)=1\n:Disp A\n:End\n", "language": "TI-83-BASIC" }, { "code": "10 REM Day of the week\n20 LET Y = 2007\n30 LET M = 12\n40 LET D = 25\n50 IF Y = 2122 THEN END\n60 LET Y = Y + 1\n70 GOSUB 200\n80 IF Z = 0 THEN PRINT Y\n90 GOTO 50\n170 REM Calculate day of week Z given\n180 REM year Y, month M, and day D\n190 REM Sunday = 0, Saturday = 6\n200 IF M < 3 THEN LET Y = Y - 1\n210 IF M < 3 THEN LET M = M + 12\n220 LET Z = Y + Y / 4 - Y / 100 + Y / 400\n230 LET Z = Z + D + (153 * M + 8) / 5\n240 LET Z = Z - 7 * (Z / 7)\n250 RETURN\n", "language": "Tiny-BASIC" }, { "code": "FUNCTION wd (m, d, y)\n IF m < 3 THEN\n LET m = m + 12\n LET y = y - 1\n END IF\n LET wd = REMAINDER ((y + INT(y / 4) - INT(y / 100) + INT(y / 400) + d + INT((153 * m + 8) / 5)), 7)\nEND FUNCTION\n\nFOR yr = 2008 TO 2121\n IF wd(12, 25, yr) = 0 THEN PRINT \"Dec 25 \"; yr\nNEXT yr\nEND\n", "language": "True-BASIC" }, { "code": "$$ MODE TUSCRIPT\nPRINT \"25th of December will be a Sunday in the following years: \"\nLOOP year=2008,2121\nSET dayofweek = DATE (number,25,12,year,nummer)\nIF (dayofweek==7) PRINT year\nENDLOOP\n", "language": "TUSCRIPT" }, { "code": "// Find years with Sunday Christmas\nvar f = 2008;\nvar t = 2121;\nconsole.log(`Sunday Christmases ${f} - ${t}`);\nfor (y = f; y <= t; y++) {\n var x = (y * 365) + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) - 6;\n if (x % 7 == 0)\n process.stdout.write(`${y}\\t`);\n}\nprocess.stdout.write(\"\\n\");\n", "language": "TypeScript" }, { "code": "#! /bin/bash\n\nfor (( i=2008; i<=2121; ++i ))\ndo\n date -d \"$i-12-25\"\ndone |grep Sun\n\nexit 0\n", "language": "UNIX-Shell" }, { "code": "Sun Dec 25 00:00:00 CET 2011\nSun Dec 25 00:00:00 CET 2016\nSun Dec 25 00:00:00 CET 2022\nSun Dec 25 00:00:00 CET 2033\ndate: invalid date `2038-12-25'\n", "language": "UNIX-Shell" }, { "code": "bash-3.00$ date --version\ndate (coreutils) 5.2.1\nWritten by David MacKenzie.\n\nCopyright (C) 2004 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\nbash-3.00$ uname -a\nLinux brslln01 2.6.9-67.ELsmp #1 SMP Wed Nov 7 13:56:44 EST 2007 x86_64 x86_64 x86_64 GNU/Linux\nbash-3.00$ for((i=2009; i <= 2121; i++)); do date -d \"$i-12-25\" |egrep Sun; done\nSun Dec 25 00:00:00 GMT 2011\nSun Dec 25 00:00:00 GMT 2016\nSun Dec 25 00:00:00 GMT 2022\nSun Dec 25 00:00:00 GMT 2033\nSun Dec 25 00:00:00 GMT 2039\nSun Dec 25 00:00:00 GMT 2044\nSun Dec 25 00:00:00 GMT 2050\nSun Dec 25 00:00:00 GMT 2061\nSun Dec 25 00:00:00 GMT 2067\nSun Dec 25 00:00:00 GMT 2072\nSun Dec 25 00:00:00 GMT 2078\nSun Dec 25 00:00:00 GMT 2089\nSun Dec 25 00:00:00 GMT 2095\nSun Dec 25 00:00:00 GMT 2101\nSun Dec 25 00:00:00 GMT 2107\nSun Dec 25 00:00:00 GMT 2112\nSun Dec 25 00:00:00 GMT 2118\nbash-3.00$\n", "language": "UNIX-Shell" }, { "code": "seq 2008 2121 | xargs -IYEAR -n 1 date +%c -d 'Dec 25 YEAR' | grep Sun\n", "language": "UNIX-Shell" }, { "code": "y=2008\nwhile test $y -lt 2122; do\n\tcal 12 $y | tail +3 | cut -c1-2 | grep -Fq 25 && echo 25 Dec $y\n\ty=`expr $y + 1`\ndone\n", "language": "UNIX-Shell" }, { "code": "zmodload zsh/datetime\nfor (( year = 2010; year <= 2121; year++ ));\n if [[ $(strftime '%A' $(strftime -r '%F' $year-12-25)) == Sunday ]] print $year\n", "language": "UNIX-Shell" }, { "code": "#import std\n#import nat\n#import stt\n\nchristmases = time_to_string* string_to_time*TS 'Dec 25 0:0:0 '-*@hS %nP* nrange/2008 2121\n\n#show+\n\nsunday_years = ~&zS sep` * =]'Sun'*~ christmases\n", "language": "Ursala" }, { "code": "import time\n\nfn main() {\n for year := 2008; year <= 2121; year++ {\n date := time.parse('${year}-12-25 00:00:00') or { continue }\n if date.long_weekday_str() == 'Sunday' {\n println('December 25 ${year} is a ${date.long_weekday_str()}')\n }\n }\n}\n", "language": "V-(Vlang)" }, { "code": "Option Explicit\n\nSub MainDayOfTheWeek()\n Debug.Print \"Xmas will be a Sunday in : \" & XmasSunday(2008, 2121)\nEnd Sub\n\nPrivate Function XmasSunday(firstYear As Integer, lastYear As Integer) As String\nDim i As Integer, temp$\n For i = firstYear To lastYear\n If Weekday(CDate(\"25/12/\" & i)) = vbSunday Then temp = temp & \", \" & i\n Next\n XmasSunday = Mid(temp, 2)\nEnd Function\n", "language": "VBA" }, { "code": "For year = 2008 To 2121\n If Weekday(DateSerial(year, 12, 25)) = 1 Then\n WScript.Echo year\n End If\nNext\n", "language": "VBScript" }, { "code": "Buf_Switch(Buf_Free)\nfor (#3 = 2008; #3 < 2122; #3++) {\n Reg_Set(10, \"12/25/\")\n Num_Str(#3, 10, LEFT+APPEND)\n if (JDate(@10) % 7 == 0) {\n\tNum_Ins(#3, NOCR)\n }\n}\n", "language": "Vedit-macro-language" }, { "code": "local i as dword\n \t\nfor i := 2008 upto 2121\n\tif DOW(ConDate(i, 12, 25)) = 1\n\t\t? AsString(i)\n\tendif\nnext i\n", "language": "Visual-Objects" }, { "code": "1000 #=2000\n1010 R=!\n1020 N=M\n1030 X=Y\n1040 #=N>3*1070\n1050 N=N+12\n1060 X=X-1\n1070 J=X/100\n1080 K=%\n1090 W=N+1*26/10+D+K+(K/4)+(J/4)+(5*J)/7*0+%\n1100 #=R\n2000 ?=\"25th of December is a Sunday in\";\n2010 Y=2008\n2020 M=12\n2030 D=25\n2040 #=1010\n2050 #=W=1=0*2080\n2060 $=32\n2070 ?=Y\n2080 Y=Y+1\n2090 #=Y<2121*2040\n2100 ?=\"\"\n", "language": "VTL-2" }, { "code": "!-&y = 0 `.getDay. @new Date[y 11 25] @range[2008 2121]\n", "language": "Wortel" }, { "code": "import \"./date\" for Date\n\nSystem.print(\"Years between 2008 and 2121 when 25th December falls on Sunday:\")\nfor (year in 2008..2121) {\n if (Date.new(year, 12, 25).dayOfWeek == 7) System.print(year)\n}\n", "language": "Wren" }, { "code": "PROGRAM\t\"progname\"\nVERSION\t\"0.0000\"\n\nDECLARE FUNCTION Entry ()\nDECLARE FUNCTION wd (m, d, y)\n\nFUNCTION Entry ()\nFOR yr = 2008 TO 2121\n IF wd(12, 25, yr) = 0 THEN PRINT \"Dec 25 \"; yr\nNEXT yr\n\nEND FUNCTION\n\nFUNCTION wd (m, d, y)\n IF m < 3 THEN\n m = m + 12\n DEC y\n END IF\n RETURN ((y + INT(y / 4) - INT(y / 100) + INT(y / 400) + d + INT((153 * m + 8) / 5)) MOD 7)\nEND FUNCTION\nEND PROGRAM\n", "language": "XBasic" }, { "code": "include c:\\cxpl\\codes; \\intrinsic 'code' declarations\n\nfunc WeekDay(Year, Month, Day); \\Return day of week (0=Sat 1=Sun..6=Fri)\nint Year, Month, Day;\n[if Month<=2 then [Month:= Month+12; Year:= Year-1];\nreturn rem((Day + (Month+1)*26/10 + Year + Year/4 + Year/100*6 + Year/400) / 7);\n]; \\WeekDay\n\n\nint Year;\n[for Year:= 2008 to 2121 do\n if WeekDay(Year, 12, 25) = 1 then \\25th of December is a Sunday\n [IntOut(0, Year); CrLf(0)];\n]\n", "language": "XPL0" }, { "code": "sub wd(m, d, y)\n If m < 3 Then // If m = 1 Or m = 2 Then\n m = m + 12\n y = y - 1\n End If\n Return mod((y + int(y / 4) - int(y / 100) + int(y / 400) + d + int((153 * m + 8) / 5)), 7)\nEnd sub\n\n// ------=< MAIN >=------\n\nFor yr = 2008 To 2121\n If wd(12, 25, yr) = 0 Then\n Print \"Dec 25 \", yr\n EndIf\nNext\n", "language": "Yabasic" }, { "code": "var [const] D=Time.Date;\nforeach y in ([2008..2121]){\n if (D.Sunday==D.weekDay(y,12,25)) println(y)\n}\n", "language": "Zkl" }, { "code": "var [const] D=Time.Date;\n[2008..2121].filter(fcn(y){ D.Sunday==D.weekDay(y,12,25) }).println()\n", "language": "Zkl" }, { "code": "module Main;\n(*Access to Mono System package *)\nimport System;\n\nvar\n\tnow: System.DateTime;\nbegin\n\tnow := System.DateTime.Now;\n\tSystem.Console.Write(now.ToString(\"yyyy-MM-dd :\"));\n\tSystem.Console.WriteLine(now.DayOfWeek);\nend Main.\n", "language": "Zonnon" }, { "code": "10 CLS\n20 FOR y=2008 TO 2121\n30 LET year=y: LET m=12: LET d=25: GO SUB 1000\n40 IF wd=0 THEN PRINT d;\" \";m;\" \";y\n50 NEXT y\n60 STOP\n1000 REM week day\n1010 IF m=1 OR m=2 THEN LET m=m+12: LET year=year-1\n1020 LET wd=FN m(year+INT (year/4)-INT (year/100)+INT (year/400)+d+INT ((153*m+8)/5),7)\n1030 RETURN\n1100 DEF FN m(a,b)=a-INT (a/b)*b\n", "language": "ZX-Spectrum-Basic" } ]
Day-of-the-week
[ { "code": "---\nfrom: http://rosettacode.org/wiki/De_Bruijn_sequences\n", "language": "00-META" }, { "code": "{{DISPLAYTITLE:de Bruijn sequences}}\nThe sequences are named after the Dutch mathematician &nbsp; Nicolaas Govert de Bruijn.\n\n\nA note on Dutch capitalization: &nbsp; Nicolaas' last name is &nbsp; '''de Bruijn''', &nbsp; the &nbsp; '''de''' &nbsp; isn't normally capitalized\nunless it's the first word in a sentence. &nbsp; Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be\ncapitalized.\n\n\nIn combinatorial mathematics, &nbsp; a &nbsp; '''de Bruijn sequence''' &nbsp; of order &nbsp; <big> ''n'' </big> &nbsp; on\na &nbsp; <big> size-''k'' </big> &nbsp; alphabet (computer science) &nbsp; <big> ''A'' </big> &nbsp; is a cyclic sequence in which every\npossible &nbsp; <big> length-''n'' </big> &nbsp; string (computer science, formal theory) &nbsp; on &nbsp; <big> ''A'' </big> &nbsp; occurs\nexactly once as a contiguous substring.\n<!--\n──────────────────────────────────────────────────────────────────────────────────────────────────────────\nYeah, I know, it's a pretty big mouthful, but it's what Wikipedia uses, so I went with that definition.\n──────────────────────────────────────────────────────────────────────────────────────────────────────────\n!-->\n\nSuch a sequence is denoted by &nbsp; <big> ''B''(''k'', ''n'') </big> &nbsp; and has\nlength &nbsp; <big>''k''<sup>''n''</sup></big>, &nbsp; which is also the number of distinct substrings of\nlength &nbsp; <big>''n''</big> &nbsp; on &nbsp; <big>''A''</big>; &nbsp; &nbsp;\n<br>de Bruijn sequences are therefore optimally short.\n\n<!--\n──────────────────────────────────────────────────────────────────────────────────────────────────────────\nExpressing the (below) equation with a <math> HTML tag causes it to \"blow up\" on Rosetta Code's version.\n──────────────────────────────────────────────────────────────────────────────────────────────────────────\n!-->\nThere are:\n <big><big><big>(k!)<sup>k<sup>(n-1)</sup></sup> &nbsp; <big><b>&divide;</b></big> &nbsp; k<sup>n</sup></big></big></big>\ndistinct de Bruijn sequences &nbsp; <big> ''B''(''k'', ''n''). </big>\n\n\n;Task:\nFor this Rosetta Code task, &nbsp; a &nbsp; '''de Bruijn''' &nbsp; sequence is to be generated that can be used to shorten a brute-force attack on\na &nbsp; [[wp:Personal_Identification_Number|PIN]]-like &nbsp; code lock that does not have an \"enter\"\nkey and accepts the last &nbsp; <big> ''n'' </big> &nbsp; digits entered.\n\n\nNote: &nbsp; [[wp:Automated_teller_machine|automated teller machines (ATMs)]] &nbsp; used to work like\nthis, &nbsp; but their software has been updated to not allow a brute-force attack.\n\n\n;Example:\nA &nbsp; [[wp:digital_door_lock|digital door lock]] &nbsp; with a 4-digit code would\nhave ''B''&thinsp;(10,&nbsp;4) solutions, &nbsp; with a length of &nbsp; '''10,000''' &nbsp; (digits).\n\nTherefore, only at most &nbsp; &nbsp; '''10,000 + 3''' &nbsp; &nbsp; (as the solutions are cyclic or ''wrap-around'') &nbsp; presses are needed to\nopen the lock.\n\nTrying all 4-digit codes separately would require &nbsp; '''4 &times; 10,000''' &nbsp; or &nbsp; '''40,000''' &nbsp; presses.\n\n\n;Task requirements:\n:* &nbsp; Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.\n:::* &nbsp; Show the length of the generated de Bruijn sequence.\n:::* &nbsp; (There are many possible de Bruijn sequences that solve this task, &nbsp; one solution is shown on the ''discussion'' page).\n:::* &nbsp; Show the first and last &nbsp; '''130''' &nbsp; digits of the de Bruijn sequence.\n:* &nbsp; Verify that all four-digit (decimal) &nbsp; '''1,000''' &nbsp; PIN codes are contained within the de Bruijn sequence.\n:::* &nbsp; 0000, 0001, 0002, 0003, &nbsp; ... &nbsp; 9996, 9997, 9998, 9999 &nbsp; (note the leading zeros).\n:* &nbsp; Reverse the de Bruijn sequence.\n:* &nbsp; Again, perform the (above) verification test.\n:* &nbsp; Replace the 4,444<sup>th</sup> digit with a period (.) in the original de Bruijn sequence.\n:::* &nbsp; Perform the verification test (again). &nbsp; There should be four PIN codes missing.\n\n\n(The last requirement is to ensure that the verification tests performs correctly. &nbsp; The verification processes should list\nany and all missing PIN codes.)\n\nShow all output here, on this page.\n\n{{Template:Strings}}\n\n\n;References:\n:* &nbsp; Wikipedia entry: &nbsp; [[wp:De_Bruijn_sequence|de Bruijn sequence]].\n:* &nbsp; MathWorld entry: &nbsp; [http://mathworld.wolfram.com/deBruijnSequence.html de Bruijn sequence].\n:* &nbsp; An &nbsp;OEIS&nbsp; entry: &nbsp; [[oeis:A166315|A166315 lexicographically earliest binary de Bruijn sequences, B(2,n)]] &nbsp; &nbsp; --- Not B(10,4), &nbsp; but possibly relevant.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "V digits = ‘0123456789’\n\nF deBruijn(k, n)\n V alphabet = :digits[0 .< k]\n V a = [Byte(0)] * (k * n)\n [Byte] seq\n\n F db(Int t, Int p) -> N\n I t > @n\n I @n % p == 0\n @seq.extend(@a[1 .< p + 1])\n E\n @a[t] = @a[t - p]\n @db(t + 1, p)\n V j = @a[t - p] + 1\n L j < @k\n @a[t] = j [&] F'F\n @db(t + 1, t)\n j++\n\n db(1, 1)\n V buf = ‘’\n L(i) seq\n buf ‘’= alphabet[i]\n\n R buf‘’buf[0 .< n - 1]\n\nF validate(db)\n V found = [0] * 10'000\n [String] errs\n\n L(i) 0 .< db.len - 3\n V s = db[i .< i + 4]\n I s.is_digit()\n found[Int(s)]++\n\n L(i) 10'000\n I found[i] == 0\n errs [+]= ‘ PIN number #04 missing’.format(i)\n E I found[i] > 1\n errs [+]= ‘ PIN number #04 occurs #. times’.format(i, found[i])\n\n I errs.empty\n print(‘ No errors found’)\n E\n V pl = I errs.len == 1 {‘’} E ‘s’\n print(‘ ’String(errs.len)‘ error’pl‘ found:’)\n L(err) errs\n print(err)\n\nV db = deBruijn(10, 4)\n\nprint(‘The length of the de Bruijn sequence is ’db.len)\nprint(\"\\nThe first 130 digits of the de Bruijn sequence are: \"db[0.<130])\nprint(\"\\nThe last 130 digits of the de Bruijn sequence are: \"db[(len)-130..])\n\nprint(\"\\nValidating the deBruijn sequence:\")\nvalidate(db)\n\nprint(\"\\nValidating the reversed deBruijn sequence:\")\nvalidate(reversed(db))\n\ndb[4443] = ‘.’\nprint(\"\\nValidating the overlaid deBruijn sequence:\")\nvalidate(db)\n", "language": "11l" }, { "code": "bdos:\tequ\t5\t; BDOS entry point\t\nputch:\tequ\t2\t; Write character to console\nputs:\tequ\t9\t; Write string to console\n\torg\t100h\n\tlhld\tbdos+1\t; Put stack at highest usable address\n\tsphl\n\t;;;\tGenerate de_bruijn(10,4) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\tmvi\tc,40\t; Zero out a[]\n\txra\ta\n\tlxi\td,arr\nzloop:\tstax\td\n\tinx\td\n\tdcr\tc\n\tjnz\tzloop\n\tlxi\th,seq\t; H = start of sequence\n\tlxi\tb,0101h\t; db(1,1)\n\tcall\tdb_\n\tlxi\td,seq\t; Allow wrap-around by appending first 3 digits\n\tmvi\tc,3\nwrap:\tldax\td\t; get one of first digits\n\tmov\tm,a\t; store after last digit\n\tinx\td\t; advance pointers\n\tinx\th\n\tdcr\tc\t; do this 3 times\n\tjnz\twrap\n\tpush\th\t; store end of data\n\t;;;\tPrint length ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\tlxi\td,slen\t; print \"Length: \"\n\tcall\tpstr\n\tlxi \td,-seq\t; calculate length (-seq+seqEnd)\n\tdad\td\n\tcall\tputhl\t; print length\n\tcall\tpnl\t; print newline\n\t;;;\tPrint first and last 130 digits ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\tlxi\td,sfrst\t; print \"First 130: \"\n\tcall\tpstr\n\tlxi \th,seq\t; print first 130 digits\n\tcall\tp130\n\tcall\tpnl\t; print newline\n\tlxi\td,slast\t; print \"Last 130: \"\n\tcall\tpstr\n\tpop\th\t; Get end of sequence\n\tpush\th\n\tlxi\td,-130\t; 130th last digit\n\tdad\td\n\tcall\tp130\t; print last 130 digits\n\tcall\tpnl\n\tcall\tverify\t; verify that all numbers are there\n\t;;;\tReverse and verify ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\tlxi\td,srev\t; Print \"reversing...\"\n\tcall\tpstr\n\tpop\th\t; HL = address of last digit\n\tdcx\th\n\tpush\th\t; stack = address of last digit\n\tlxi\td,seq\t; DE = address of first digit\n\tcall\trvrs\t; Reverse\n\tcall\tverify\t; Verify that all numbers are there\n\tlxi\td,seq\t; Then reverse again (restoring it)\n\tpop\th\n\tcall\trvrs\n\t;;;\tReplace 4444th digit with '.' and verify ;;;;;;;;;;;;;;;;;;;;;;\n\tlxi\td,s4444\n\tcall\tpstr\n\tmvi\ta,'.'\n\tsta\tseq+4444\n\tcall\tverify\n\trst\t0\n\t;;;\tdb(t,p); t,p in B,C; end of sequence in HL ;;;;;;;;;;;;;;;;;;;;\ndb_:\tmov\ta,b\t; if t>n (n=4)\n\tcpi\t5\t; t >= n+1\n\tjc\tdbelse\n\tmov\ta,c\t; 4%p==0, for p in {1,2,3,4}, is false iff p=3\n\tcpi\t3\n\trz\t\t; stop if p=3, i.e. 4%p<>0\n\tlxi\td,arr+1\t; copy P elements to seq forom arr[1..]\ndbextn:\tldax\td\t; take from a[]\n\tmov\tm,a\t; store in sequence\n\tinx\th\t; advance pointers\n\tinx\td\n\tdcr\tc\t; and do this P times\n\tjnz\tdbextn\n\tret\ndbelse:\tmov\ta,b\t; t - p\n\tsub\tc\n\tmvi\td,arr/256\n\tmov\te,a\t; a[] is page-aligned for easier indexing\n\tldax\td\t; get a[t-p]\n\tmov\te,b\t; store in a[t]\n\tstax\td\n\tpush\tb\t; keep T and P\n\tinr\tb\t; db(t+1, p)\n\tcall\tdb_\n\tpop\tb\t; restore T and P\n\tmov\ta,b\t; get a[t-p]\n\tsub\tc\n\tmvi\td,arr/256\n\tmov\te,a\n\tldax\td\t; j = a[t-p]\ndbloop:\tinr\ta\t; j++\n\tcpi\t10\t; reached K = 10?\n\trnc\t\t; then stop\n\tmvi\td,arr/256\n\tmov\te,b\n\tstax\td\t; a[t] = j\n\tpush\tpsw\t; keep j\n\tpush\tb\t; keep t and p\n\tmov\tc,b\n\tinr\tb\n\tcall\tdb_\t; db(t+1, t)\n\tpop\tb\t; restore t and p\n\tpop\tpsw\t; restore j\n\tjmp\tdbloop\n\t;;;\tVerify that all numbers are there ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\nverify:\tlxi\td,sver\t; print \"Verifying... \"\n\tcall\tpstr\n\tmvi\td,0\t; Zero out the flag array\n\tlxi\tb,10000\t\n\tlxi\th,val\nvzero:\tmov\tm,d\n\tinx\th\n\tdcx\tb\n\tmov\ta,b\n\tora\tc\n\tjnz\tvzero\n\tlxi\th,seq\t; Sequence pointer\ndonum:\tpush\th\t; Store sequence pointer\n\tpush\th\t; Push two copies\n\tlxi\th,0\t; Current 4-digit number\n\tmvi\tc,4\t; Number has 4 digits\ndgtadd:\tmov\td,h\t; HL *= 10\n\tmov\te,l\n\tdad\th\n\tdad\th\n\tdad\td\n\tdad\th\n\txthl\t\t; Get sequence pointer\n\tmov\ta,m\t; Get digit\n\tinx\th\t; Advance pointer\n\tcpi\t10\t; Valid digit?\n\tjnc\tdinval\t; If not, go do next 4-digit number\n\txthl\t\t; Back to number\n\tmov\te,a\n\tmvi\td,0\n\tdad\td\t; Add digit to number\n\tdcr\tc\t; More digits?\n\tjnz\tdgtadd\t; Then get digit\n\tlxi\td,val\t; HL is now the current 4-digit number\n\tdad\td\n\tinr\tm \t; val[HL]++ (we've seen it)\ndinval:\tpop\th\t; Pointer to after last valid digit\n\tpop\th\t; Pointer to start of current number\n\tinx\th\t; Get 4-digit number that starts at next digit\t\n\tmov\td,h\t; Next pointer in DE\n\tmov\te,l\n\tlxi\tb,-(seq+10000)\t; Are we there yet?\n\tdad\tb\n\tmov\ta,h\n\tora\tl\n\txchg\t\t; Next pointer back in HL\n\tjnz\tdonum\t; If not done, do next number.\n\tlxi\th,val\t; Done - get start of validation array\n\tmvi\tb,0\t; B will be set if one is missing\nvnum:\tmov\ta,m\t; Have we seen HL-val?\n\tana\ta \t\n\tjnz\tvnext\t; If so, do the next number\n\tpush\th\t; Otherwise, keep current address,\n\tlxi\td,-val\t; Subtract val (to get the number)\n\tdad\td\n\tcall\tputhl\t; Print this number as being missing\n\tmvi\tb,1\t; Set B,\n\tpop \th\t; and then restore the address\nvnext:\tinx\th\t; Increment the number\n\tpush\th\n\tlxi\td,-(val+10000)\t; Are we there yet?\n\tdad\td\n\tmov\ta,h\n\tora\tl\n\tpop\th\n\tjnz\tvnum\t; If not, check next number.\n\tdcr\tb\t; At the end, if B was not set,\n\tlxi\td,snone\t; print \"none missing\",\n\tjnz\tpstr\n\tlxi\td,smiss\t; otherwise, print \"missing\"\n\tjmp\tpstr\n\t;;;\tSubroutines ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\t;;;\treverse memory starting at DE and ending at HL\nrvrs:\tmov\tb,m\t; Load [HL]\n\tldax\td\t; Load [DE]\n\tmov\tm,a\t; [HL] = old [DE]\n\tmov\ta,b\n\tstax\td\t; [DE] = old [HL]\n\tinx\td\t; Move bottom pointer upwards,\n\tdcx\th\t; Move top pointer downwards,\n\tmov\ta,d\t; D<H = not there yet\n\tcmp\th\n\tjc\trvrs\n\tmov\ta,e\t; E<L = not there yet\n\tcmp\tl\n\tjc\trvrs\n\tret\n\t;;;\tprint number in HL, saving registers\nputhl:\tpush\th\t; save registers\n\tpush\td\n\tpush\tb\n\tlxi\tb,nbuf\t; number buffer pointer\n\tpush\tb\t; keep it on the stack\ndgt:\tlxi\tb,-10\n\tlxi\td,-1\ndgtdiv:\tinx\td\t; calculate digit\n\tdad\tb\n\tjc\tdgtdiv\n\tmvi\ta,'0'+10\n\tadd\tl\n\tpop\th\t; get pointer from stack\n\tdcx\th\t; go to previous digit\n\tmov\tm,a\t; store digit\n\tpush\th \t; put pointer back\n\txchg\t\t; are there any more digits?\n\tmov\ta,h\n\tora\tl\n\tjnz\tdgt\t; if so, calculate next digit\n\tpop\td \t; otherwise, get pointer to first digit\n\tjmp\tpstr_\t; and print the resulting string\t\n\t;;;\tprint 130 digits from the sequence, starting at HL\np130:\tpush\th\n\tpush\td\n\tpush\tb\n\tmvi\tb,130\t; 130 digits\np130l:\tmov\ta,m\t; get current digit\n\tadi \t'0'\t; make ASCII\n\tinx\th\t; advance pointer\n\tpush\tb\t; save pointer and counter\n\tpush\th\n\tmvi\tc,putch\t; print character\n\tmov\te,a\n\tcall\tbdos\n\tpop\th\t; restore pointer and counter\n\tpop\tb\n\tdcr\tb\t; one fewer character left\n\tjnz\tp130l\t; if characters left, print next\n\tjmp\trsreg\t; otherwise, restore registers and return\n\t;;;\tprint newline\npnl:\tlxi\td,snl\n\t;;;\tprint string in DE, saving registers\npstr:\tpush\th\t; store registers\n\tpush\td\n\tpush \tb\npstr_:\tmvi\tc,puts\t; print string using CP/M\n\tcall\tbdos\nrsreg:\tpop\tb\t; restore registers\n\tpop\td\n\tpop \th\n\tret\nsnl:\tdb\t13,10,'$'\nslen:\tdb\t'Length: $'\nsfrst:\tdb\t'First 130: $'\nslast:\tdb\t'Last 130: $'\nsrev:\tdb\t'Reversing...',13,10,'$'\ns4444:\tdb\t'Set seq[4444] to `.`...',13,10,'$'\nsver:\tdb\t'Verifying... $'\nsnone:\tdb\t'none '\nsmiss:\tdb\t'missing',13,10,'$'\n\tdb\t'00000'\t; number output buffer\nnbuf:\tdb\t' $'\narr:\tequ\t($/256+1)*256\t; Place to store a[] (page-aligned)\nval:\tequ\tarr+40\t\t; Place to store validation flags\nseq:\tequ\tval+10000\t; Place to store De Bruijn sequence\n", "language": "8080-Assembly" }, { "code": "putch:\tequ\t2\t; Print character\nputs:\tequ\t9\t; Print string\n\tcpu\t8086\n\tbits\t16\nsection\t.text\n\torg\t100h\n\t;;;\tCalculate de_bruijn(10, 4) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\txor\tax,ax\t\t; zero a[]\n\tmov\tdi,arr\n\tmov\tcx,20\t\t; 20 words = 40 bytes\n\trep\tstosw\n\tmov\tdi,seq\t\t; start of sequence\n\tmov\tdx,0101h\t; db(1,1)\n\tcall\tdb_\n\tmov\tsi,seq\t\t; Add first 3 to end for wrapping\n\tmov\tcx,3\n\trep\tmovsb\n\tlea\tbp,[di-1]\t; Store pointer to last digit in BP\n\t;;;\tPrint length ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\tmov\tah,puts\t\t; Print \"Length:\"\n\tmov\tdx,slen\n\tint\t21h\n\tmov\tax,di\t\t; Length = end - start\n\tsub\tax,seq\n\tcall\tputax\t\t; Print length\n\t;;;\tPrint first and last 130 characters and verify ;;;;;;;;;;;;;;;;\n\tmov\tah,puts\t\t; Print \"First 130...\"\n\tmov\tdx,sfrst\n\tint\t21h\n\tmov\tsi,seq\t\t; print first 130 digits\n\tcall\tp130\n\tmov\tah,puts\t\t; Print \"Last 130...\"\n\tmov\tdx,slast\n\tint \t21h\n\tmov\tsi,di\t\t; print last 130 digit\n\tsub\tsi,130\n\tcall\tp130\n\tcall\tverify\n\t;;;;\tReverse the sequence and verify ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\tmov\tah,puts\t\t; Print \"Reversing...\"\n\tmov\tdx,srev\n\tint\t21h\n\tmov\tsi,seq\t\t; SI = first digit in sequence\n\tmov\tdi,bp\t\t; DI = last digit in sequence\n\tcall\trvrs\t\t; Reverse\n\tcall\tverify\t\t; Verify\n\tmov\tsi,seq\t\t; Reverse again, putting it back\n\tmov\tdi,bp\n\tcall\trvrs\n\t;;;\tSet seq[4444] to '.' and verify ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\tmov\tah,puts\t\t; Print \"set seq[4444] to '.'\"\n\tmov\tdx,s4444\n\tint\t21h\n\tmov\t[seq+4444],byte '.'\n\tcall\tverify\t\t; Verify\n\tret\n\t;;;\tdb(t, p); t=dh p=dl, di=seq ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\ndb_:\tcmp\tdh,4\t\t; t>n? (n=4)\n\tjbe\t.els\n\tcmp\tdl,3\t\t; for p in {1,2,3,4}, 4%p==0 iff p=3\n\tje\t.out\n\tmov\tsi,arr+1\t; add DL=P bytes from a[1..] to sequence\n\tmov\tcl,dl\n\txor \tch,ch\n\trep\tmovsb\n\tjmp\t.out\n.els:\txor\tbh,bh\n\tmov\tbl,dh\n\tsub\tbl,dl\t\t; t - p\n\tmov\tal,[arr+bx]\t; al = a[t-p]\n\tmov\tbl,dh\t\t; t\n\tmov\t[arr+bx],al\t; a[t] = al\n\tpush\tdx\t\t; keep arguments\n\tinc\tdh\t\t; db(++t,p)\n\tcall\tdb_\t\t\t\n\tpop\tdx\t\t; restore arguments\n\tmov\tbl,dh\t\t; al = a[t-p]\n\tsub\tbl,dl\n\tmov\tal,[arr+bx]\n.loop:\tinc\tal\t\t; al++\n\tcmp\tal,10\t\t; when al>=k,\n\tjae\t.out\t\t; then stop.\n\tmov\tbl,dh\n\tmov\t[arr+bx],al\t; a[t] = j\n\tpush\tax\t\t; keep state\n\tpush\tdx\n\tmov\tdl,dh\t\t; db(t+1, t)\n\tinc\tdh\n\tcall\tdb_\n\tpop\tdx\n\tpop\tax\n\tjmp\t.loop\n.out:\tret\n\t;;;\tVerify that all numbers are there ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\nverify:\tmov\tah,puts\t\t; Print \"verifying...\"\n\tmov\tdx,sver\n\tint\t21h\n\tmov\tdi,val\t\t; Zero validation array\n\tmov\tcx,5000\t\t; 10000 bytes = 5000 words\n\txor\tax,ax\n\trep\tstosw\n\tmov\tdi,val\n\tmov\tsi,seq\t\t; Pointer to start of sequence\n\tmov\tcx,6409h\t; CH=100 (multiplier), CL=9 (highest digit)\n.num:\tmov\tax,[si]\t\t; Read first two digits\n\tcmp\tah,cl\t\t; Check that they are valid\n\tja\t.inval\n\tcmp\tal,cl\n\tja\t.inval\n\txchg\tal,ah\t\t; High digit * 10 + low digit\n\taad\n\tmul\tch\t\t; Multiply by 100 (to add in next two)\n\tmov\tbx,ax\n\tmov\tax,[si+2]\t; Read last two digits\n\tcmp\tah,cl\t\t; Check that they are valid\n\tja\t.inval\n\tcmp\tal,cl\n\tja\t.inval\n\txchg\tal,ah\t\t; High digit * 10 + low digit\n\taad\n\tadd\tbx,ax\t\t; BX = final 4-digit number\n\tinc\tbyte [di+bx]\t; Mark this 4-digit number as seen\n.inval:\tinc\tsi\t\t; Next digit\n\tcmp\tsi,seq+10000\t; Are we at the end yet?\n\tjne\t.num\t\t; If not, do next number\n\tmov\tsi,val\t\t; For each number < 10000, check if it's there\n\txor\tcl,cl\t\t; Will be set if a number is missing\n.test:\tlodsb\t\t\t; Do we have this number?\n\ttest\tal,al\n\tjnz\t.tnext\t\t; If so, try next number\n\tmov\tax,si\t\t; Otherwise, print the missing number\n\tsub\tax,val\n\tcall\tputax\n\tmov\tcl,1\t\t; And set CL\n.tnext:\tcmp\tsi,val+10000\t; Are we at the end yet?\n\tjne\t.test\n\ttest\tcl,cl\n\tmov\tdx,smiss\t; Print \"... missing\"\n\tjnz\t.print\t\t; if CL is set\n\tmov\tdx,snone\t; or \"none missing\" otherwise.\n.print:\tmov\tah,puts\n\tint\t21h\n\tret\n\t;;;\tSubroutines ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\t;;;\tPrint number in AX\nputax:\tpush\tax\t\t; Keep registers we're changing\n\tpush\tdx\t\t\n\tpush\tbx\n\tpush\tdi\n\tmov\tdi,numbuf\t; Pointer to number buffer\n\tmov\tbx,10\t\t; Divisor\n.digit:\txor\tdx,dx\t\t; Divide AX by 10\n\tdiv\tbx\n\tadd\tdl,'0'\t\t; Add '0' to remainder (digit)\n\tdec\tdi\t\t; Store digit in buffer\n\tmov\t[di],dl\n\ttest\tax,ax\t\t; Any more digits?\n\tjnz\t.digit\t\t; If so, do next digits\n\tmov\tdx,di\t\t; At the end, print the string\n\tmov\tah,puts\n\tint\t21h\n\tpop\tdi\t\t; Restore registers\n\tpop\tbx\n\tpop\tdx\n\tpop\tax\n\tret\n\t;;;\tPrint 130 digits starting at SI\np130:\tmov\tcx,130\t\t; 130 characters\n\tmov\tah,putch\t; Print characters\n.loop:\tlodsb\t\t\t; Get digit\n\tadd\tal,'0'\t\t; Make ASCII\n\tmov\tdl,al\t\t; Print digit\n\tint\t21h\n\tloop \t.loop\n\tret\n\t;;;\tReverse memory starting at SI and ending at DI\nrvrs:\tmov\tal,[si]\t\t; Load [SI],\n\tmov\tah,[di]\t\t; Load [DI],\n\tmov\t[di],al\t\t; Set [DI] = old [SI]\n\tmov\t[si],ah\t\t; Set [SI] = old [DI]\n\tinc\tsi\t\t; Increment bottom pointer\n\tdec\tdi\t\t; Decrement top pointer\n\tcmp\tsi,di\t\t; If SI >= DI, we're done\n\tjb\trvrs\n\tret\nsection\t.data\nslen:\tdb\t'Length: $'\nsfrst:\tdb\t13,10,'First 130: $'\nslast:\tdb\t13,10,'Last 130: $'\nsrev:\tdb\t13,10,'Reversing... $'\ns4444:\tdb\t13,10,'Set seq[4444] to `.`...$'\nsver:\tdb\t13,10,'Verifying... $'\nsnone:\tdb\t'none '\nsmiss:\tdb\t'missing.$'\n\tdb\t'00000'\nnumbuf:\tdb\t' $'\nsection\t.bss\narr:\tresb\t40\t\t; a[]\nval:\tresb\t10000\t\t; validation array\nseq:\tequ\t$\n", "language": "8086-Assembly" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Strings.Fixed; use Ada.Strings;\nwith Ada.Strings.Unbounded;\n\nprocedure De_Bruijn_Sequences is\n\n function De_Bruijn (K, N : Positive) return String\n is\n use Ada.Strings.Unbounded;\n\n Alphabet : constant String := \"0123456789\";\n\n subtype Decimal is Integer range 0 .. 9;\n type Decimal_Array is array (Natural range <>) of Decimal;\n\n A : Decimal_Array (0 .. K * N - 1) := (others => 0);\n Seq : Unbounded_String;\n\n procedure Db (T, P : Positive) is\n begin\n if T > N then\n if N mod P = 0 then\n for E of A (1 .. P) loop\n Append (Seq, Alphabet (Alphabet'First + E));\n end loop;\n end if;\n else\n A (T) := A (T - P);\n Db (T + 1, P);\n for J in A (T - P) + 1 .. K - 1 loop\n A (T) := J;\n Db (T + 1, T);\n end loop;\n end if;\n end Db;\n\n begin\n Db (1, 1);\n return To_String (Seq) & Slice (Seq, 1, N - 1);\n end De_Bruijn;\n\n function Image (Value : Integer) return String\n is (Fixed.Trim (Value'Image, Left));\n\n function PIN_Image (Value : Integer) return String\n is (Fixed.Tail (Image (Value), Count => 4, Pad => '0'));\n\n procedure Validate (Db : String)\n is\n Found : array (0 .. 9_999) of Natural := (others => 0);\n Errors : Natural := 0;\n begin\n\n -- Check all strings of 4 consecutive digits within 'db'\n -- to see if all 10,000 combinations occur without duplication.\n for A in Db'First .. Db'Last - 3 loop\n declare\n PIN : String renames Db (A .. A + 4 - 1);\n begin\n if (for all Char of PIN => Char in '0' .. '9') then\n declare\n N : constant Integer := Integer'Value (PIN);\n F : Natural renames Found (N);\n begin\n F := F + 1;\n end;\n end if;\n end;\n end loop;\n\n for I in 0_000 .. 9_999 loop\n if Found (I) = 0 then\n Put_Line (\" PIN number \" & PIN_Image (I) & \" missing\");\n Errors := Errors + 1;\n elsif Found (I) > 1 then\n Put_Line (\" PIN number \" & PIN_Image (I) & \" occurs \"\n & Image (Found (I)) & \" times\");\n Errors := Errors + 1;\n end if;\n end loop;\n\n case Errors is\n when 0 => Put_Line (\" No errors found\");\n when 1 => Put_Line (\" 1 error found\");\n when others =>\n Put_Line (\" \" & Image (Errors) & \" errors found\");\n end case;\n end Validate;\n\n function Backwards (S : String) return String is\n R : String (S'Range);\n begin\n for A in 0 .. S'Length - 1 loop\n R (R'Last - A) := S (S'First + A);\n end loop;\n return R;\n end Backwards;\n\n DB : constant String := De_Bruijn (K => 10, N => 4);\n Rev : constant String := Backwards (DB);\n Ovl : String := DB;\nbegin\n Put_Line (\"The length of the de Bruijn sequence is \" & DB'Length'Image);\n New_Line;\n\n Put_Line (\"The first 130 digits of the de Bruijn sequence are: \");\n Put_Line (\" \" & Fixed.Head (DB, 130));\n New_Line;\n\n Put_Line (\"The last 130 digits of the de Bruijn sequence are: \");\n Put_Line (\" \" & Fixed.Tail (DB, 130));\n New_Line;\n\n Put_Line (\"Validating the deBruijn sequence:\");\n Validate (DB);\n New_Line;\n\n Put_Line (\"Validating the reversed deBruijn sequence:\");\n Validate (Rev);\n New_Line;\n\n Ovl (4444) := '.';\n Put_Line (\"Validating the overlaid deBruijn sequence:\");\n Validate (Ovl);\n New_Line;\nend De_Bruijn_Sequences;\n", "language": "Ada" }, { "code": "10 DEFINT A-Z\n20 K = 10: N = 4\n30 DIM A(K*N), S(K^N+N), T(5), P(5), V(K^N\\8)\n40 GOSUB 200\n50 PRINT \"Length: \",S\n60 PRINT \"First 130:\"\n70 FOR I=0 TO 129: PRINT USING \"#\";S(I);: NEXT\n80 PRINT: PRINT \"Last 130:\"\n90 FOR I=S-130 TO S-1: PRINT USING \"#\";S(I);: NEXT\n100 PRINT\n110 GOSUB 600\n120 PRINT \"Reversing...\": GOSUB 500: GOSUB 600: GOSUB 500\n130 PRINT USING \"Replacing 4444'th element (#):\";S(4443)\n140 S(4443) = -1 : REM 0-indexed, and using integers\n150 GOSUB 600\n160 END\n200 REM Generate De Bruijn sequence given K and N\n210 T(R) = 1: P(R) = 1\n220 IF T(R) > N GOTO 380\n230 A(T(R)) = A(T(R)-P(R))\n240 R = R+1\n250 T(R) = T(R-1)+1\n260 P(R) = P(R-1)\n270 GOSUB 220\n280 R = R-1\n290 FOR J = A(T(R)-P(R))+1 TO K-1\n300 A(T(R)) = J\n310 R = R+1\n320 T(R) = T(R-1)+1\n330 P(R) = T(R-1)\n340 GOSUB 220\n350 R = R-1\n355 J = A(T(R))\n360 NEXT\n370 RETURN\n380 IF N MOD P(R) THEN RETURN\n390 FOR I = 1 TO P(R)\n400 S(S) = A(I)\n410 S = S+1\n420 NEXT\n430 RETURN\n500 REM Reverse the sequence\n510 FOR I=0 TO S\\2\n520 J = S(I)\n530 S(I) = S(S-I)\n540 S(S-I) = J\n550 NEXT\n560 RETURN\n600 REM Validate the sequence (uses bit packing to save memory)\n610 PRINT \"Validating...\";\n620 FOR I=0 TO N-1: S(S+I)=S(I): NEXT\n630 FOR I=0 TO K^N\\8-1: V(I)=0: NEXT\n640 FOR I=0 TO S\n650 P=0\n660 FOR J=0 TO N-1\n662 D=S(I+J)\n663 IF D<0 GOTO 690\n665 P=K*P+D\n669 NEXT J\n670 X=P\\8\n680 V(X) = V(X) OR 2^(P AND 7)\n690 NEXT I\n700 M=1\n710 FOR I=0 TO K^N\\8-1\n720 IF V(I)=255 GOTO 760\n730 FOR J=0 TO 7\n740 IF (V(I) AND 2^J)=0 THEN M=0: PRINT USING \" ####\";I*8+J;\n750 NEXT\n760 NEXT\n770 IF M THEN PRINT \" none\";\n780 PRINT \" missing.\"\n790 RETURN\n", "language": "BASIC" }, { "code": "#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <iterator>\n#include <string>\n#include <sstream>\n#include <vector>\n\ntypedef unsigned char byte;\n\nstd::string deBruijn(int k, int n) {\n std::vector<byte> a(k * n, 0);\n std::vector<byte> seq;\n\n std::function<void(int, int)> db;\n db = [&](int t, int p) {\n if (t > n) {\n if (n % p == 0) {\n for (int i = 1; i < p + 1; i++) {\n seq.push_back(a[i]);\n }\n }\n } else {\n a[t] = a[t - p];\n db(t + 1, p);\n auto j = a[t - p] + 1;\n while (j < k) {\n a[t] = j & 0xFF;\n db(t + 1, t);\n j++;\n }\n }\n };\n\n db(1, 1);\n std::string buf;\n for (auto i : seq) {\n buf.push_back('0' + i);\n }\n return buf + buf.substr(0, n - 1);\n}\n\nbool allDigits(std::string s) {\n for (auto c : s) {\n if (c < '0' || '9' < c) {\n return false;\n }\n }\n return true;\n}\n\nvoid validate(std::string db) {\n auto le = db.size();\n std::vector<int> found(10000, 0);\n std::vector<std::string> errs;\n\n // Check all strings of 4 consecutive digits within 'db'\n // to see if all 10,000 combinations occur without duplication.\n for (size_t i = 0; i < le - 3; i++) {\n auto s = db.substr(i, 4);\n if (allDigits(s)) {\n auto n = stoi(s);\n found[n]++;\n }\n }\n\n for (int i = 0; i < 10000; i++) {\n if (found[i] == 0) {\n std::stringstream ss;\n ss << \" PIN number \" << i << \" missing\";\n errs.push_back(ss.str());\n } else if (found[i] > 1) {\n std::stringstream ss;\n ss << \" PIN number \" << i << \" occurs \" << found[i] << \" times\";\n errs.push_back(ss.str());\n }\n }\n\n if (errs.empty()) {\n std::cout << \" No errors found\\n\";\n } else {\n auto pl = (errs.size() == 1) ? \"\" : \"s\";\n std::cout << \" \" << errs.size() << \" error\" << pl << \" found:\\n\";\n for (auto e : errs) {\n std::cout << e << '\\n';\n }\n }\n}\n\nint main() {\n std::ostream_iterator<byte> oi(std::cout, \"\");\n auto db = deBruijn(10, 4);\n\n std::cout << \"The length of the de Bruijn sequence is \" << db.size() << \"\\n\\n\";\n std::cout << \"The first 130 digits of the de Bruijn sequence are: \";\n std::copy_n(db.cbegin(), 130, oi);\n std::cout << \"\\n\\nThe last 130 digits of the de Bruijn sequence are: \";\n std::copy(db.cbegin() + (db.size() - 130), db.cend(), oi);\n std::cout << \"\\n\";\n\n std::cout << \"\\nValidating the de Bruijn sequence:\\n\";\n validate(db);\n\n std::cout << \"\\nValidating the reversed de Bruijn sequence:\\n\";\n auto rdb = db;\n std::reverse(rdb.begin(), rdb.end());\n validate(rdb);\n\n auto by = db;\n by[4443] = '.';\n std::cout << \"\\nValidating the overlaid de Bruijn sequence:\\n\";\n validate(by);\n\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace DeBruijn {\n class Program {\n const string digits = \"0123456789\";\n\n static string DeBruijn(int k, int n) {\n var alphabet = digits.Substring(0, k);\n var a = new byte[k * n];\n var seq = new List<byte>();\n void db(int t, int p) {\n if (t > n) {\n if (n % p == 0) {\n seq.AddRange(new ArraySegment<byte>(a, 1, p));\n }\n } else {\n a[t] = a[t - p];\n db(t + 1, p);\n var j = a[t - p] + 1;\n while (j < k) {\n a[t] = (byte)j;\n db(t + 1, t);\n j++;\n }\n }\n }\n db(1, 1);\n var buf = new StringBuilder();\n foreach (var i in seq) {\n buf.Append(alphabet[i]);\n }\n var b = buf.ToString();\n return b + b.Substring(0, n - 1);\n }\n\n static bool AllDigits(string s) {\n foreach (var c in s) {\n if (c < '0' || '9' < c) {\n return false;\n }\n }\n return true;\n }\n\n static void Validate(string db) {\n var le = db.Length;\n var found = new int[10_000];\n var errs = new List<string>();\n // Check all strings of 4 consecutive digits within 'db'\n // to see if all 10,000 combinations occur without duplication.\n for (int i = 0; i < le - 3; i++) {\n var s = db.Substring(i, 4);\n if (AllDigits(s)) {\n int.TryParse(s, out int n);\n found[n]++;\n }\n }\n for (int i = 0; i < 10_000; i++) {\n if (found[i] == 0) {\n errs.Add(string.Format(\" PIN number {0,4} missing\", i));\n } else if (found[i] > 1) {\n errs.Add(string.Format(\" PIN number {0,4} occurs {1} times\", i, found[i]));\n }\n }\n var lerr = errs.Count;\n if (lerr == 0) {\n Console.WriteLine(\" No errors found\");\n } else {\n var pl = lerr == 1 ? \"\" : \"s\";\n Console.WriteLine(\" {0} error{1} found:\", lerr, pl);\n errs.ForEach(Console.WriteLine);\n }\n }\n\n static string Reverse(string s) {\n char[] arr = s.ToCharArray();\n Array.Reverse(arr);\n return new string(arr);\n }\n\n static void Main() {\n var db = DeBruijn(10, 4);\n var le = db.Length;\n\n Console.WriteLine(\"The length of the de Bruijn sequence is {0}\", le);\n Console.WriteLine(\"\\nThe first 130 digits of the de Bruijn sequence are: {0}\", db.Substring(0, 130));\n Console.WriteLine(\"\\nThe last 130 digits of the de Bruijn sequence are: {0}\", db.Substring(le - 130, 130));\n\n Console.WriteLine(\"\\nValidating the deBruijn sequence:\");\n Validate(db);\n\n Console.WriteLine(\"\\nValidating the reversed deBruijn sequence:\");\n Validate(Reverse(db));\n\n var bytes = db.ToCharArray();\n bytes[4443] = '.';\n db = new string(bytes);\n Console.WriteLine(\"\\nValidating the overlaid deBruijn sequence:\");\n Validate(db);\n }\n }\n}\n", "language": "C-sharp" }, { "code": "% Generate the De Bruijn sequence consisiting of N-digit numbers\nde_bruijn = cluster is generate\n rep = null\n own k: int := 0\n own n: int := 0\n own a: array[int] := array[int]$[]\n own seq: array[int] := array[int]$[]\n\n generate = proc (k_, n_: int) returns (string)\n k := k_\n n := n_\n a := array[int]$fill(0, k*n, 0)\n seq := array[int]$[]\n db(1, 1)\n s: stream := stream$create_output()\n for i: int in array[int]$elements(seq) do\n stream$puts(s, int$unparse(i))\n end\n return(stream$get_contents(s))\n end generate\n\n db = proc (t, p: int)\n if t>n then\n if n//p = 0 then\n for i: int in int$from_to(1, p) do\n array[int]$addh(seq, a[i])\n end\n end\n else\n a[t] := a[t - p]\n db(t+1, p)\n for j: int in int$from_to(a[t - p] + 1, k-1) do\n a[t] := j\n db(t + 1, t)\n end\n end\n end db\nend de_bruijn\n\n% Reverse a string\nreverse = proc (s: string) returns (string)\n r: array[char] := array[char]$predict(1, string$size(s))\n for c: char in string$chars(s) do\n array[char]$addl(r, c)\n end\n return(string$ac2s(r))\nend reverse\n\n% Find all missing N-digit values\nfind_missing = proc (db: string, n: int) returns (sequence[string])\n db := db || string$substr(db, 1, n) % wrap\n missing: array[string] := array[string]$[]\n s: stream := stream$create_output()\n for i: int in int$from_to(0, 10**n-1) do\n %s: stream := stream$create_output()\n stream$reset(s)\n stream$putzero(s, int$unparse(i), n)\n val: string := stream$get_contents(s)\n if string$indexs(val, db) = 0 then\n array[string]$addh(missing, val)\n end\n end\n return(sequence[string]$a2s(missing))\nend find_missing\n\n% Report all missing values, or 'none'.\nvalidate = proc (s: stream, db: string, n: int)\n stream$puts(s, \"Validating...\")\n missing: sequence[string] := find_missing(db, n)\n for v: string in sequence[string]$elements(missing) do\n stream$puts(s, \" \" || v)\n end\n if sequence[string]$size(missing) = 0 then\n stream$puts(s, \" none\")\n end\n stream$putl(s, \" missing.\")\nend validate\n\nstart_up = proc ()\n po: stream := stream$primary_output()\n\n % Generate the De Bruijn sequence for 4-digit numbers\n db: string := de_bruijn$generate(10, 4)\n\n % Report length and first and last digits\n stream$putl(po, \"Length: \" || int$unparse(string$size(db)))\n stream$putl(po, \"First 130 characters:\")\n stream$putl(po, string$substr(db, 1, 130))\n stream$putl(po, \"Last 130 characters:\")\n stream$putl(po, string$substr(db, string$size(db)-130, 130))\n\n % See if there are any missing values in the sequence\n validate(po, db, 4)\n\n % Reverse and validate again\n stream$putl(po, \"Reversing...\")\n validate(po, reverse(db), 4)\n\n % Replace the 4444'th element with '.' and validate again\n stream$putl(po, \"Setting the 4444'th character to '.'...\")\n db := string$substr(db, 1, 4443) || \".\" || string$rest(db, 4445)\n validate(po, db, 4)\nend start_up\n", "language": "CLU" }, { "code": "import std.array;\nimport std.conv;\nimport std.format;\nimport std.range;\nimport std.stdio;\n\nimmutable DIGITS = \"0123456789\";\n\nstring deBruijn(int k, int n) {\n auto alphabet = DIGITS[0..k];\n byte[] a;\n a.length = k * n;\n byte[] seq;\n\n void db(int t, int p) {\n if (t > n) {\n if (n % p == 0) {\n auto temp = a[1..p + 1];\n seq ~= temp;\n }\n } else {\n a[t] = a[t - p];\n db(t + 1, p);\n auto j = a[t - p] + 1;\n while (j < k) {\n a[t] = cast(byte)(j & 0xFF);\n db(t + 1, t);\n j++;\n }\n }\n }\n db(1, 1);\n string buf;\n foreach (i; seq) {\n buf ~= alphabet[i];\n }\n\n return buf ~ buf[0 .. n - 1];\n}\n\nbool allDigits(string s) {\n foreach (c; s) {\n if (c < '0' || '9' < c) {\n return false;\n }\n }\n return true;\n}\n\nvoid validate(string db) {\n auto le = db.length;\n int[10_000] found;\n string[] errs;\n // Check all strings of 4 consecutive digits within 'db'\n // to see if all 10,000 combinations occur without duplication.\n foreach (i; 0 .. le - 3) {\n auto s = db[i .. i + 4];\n if (allDigits(s)) {\n auto n = s.to!int;\n found[n]++;\n }\n }\n foreach (i; 0 .. 10_000) {\n if (found[i] == 0) {\n errs ~= format(\" PIN number %04d missing\", i);\n } else if (found[i] > 1) {\n errs ~= format(\" PIN number %04d occurs %d times\", i, found[i]);\n }\n }\n if (errs.empty) {\n writeln(\" No errors found\");\n } else {\n auto pl = (errs.length == 1) ? \"\" : \"s\";\n writeln(\" \", errs.length, \" error\", pl, \" found:\");\n writefln(\"%-(%s\\n%)\", errs);\n }\n}\n\nvoid main() {\n auto db = deBruijn(10, 4);\n\n writeln(\"The length of the de Bruijn sequence is \", db.length);\n writeln(\"\\nThe first 130 digits of the de Bruijn sequence are: \", db[0 .. 130]);\n writeln(\"\\nThe last 130 digits of the de Bruijn sequence are: \", db[$ - 130 .. $]);\n\n writeln(\"\\nValidating the deBruijn sequence:\");\n validate(db);\n\n writeln(\"\\nValidating the reversed deBruijn sequence:\");\n validate(db.retro.to!string);\n\n auto by = db.dup;\n by[4443] = '.';\n db = by.idup;\n writeln(\"\\nValidating the overlaid deBruijn sequence:\");\n validate(db);\n}\n", "language": "D" }, { "code": "global a[] seq[] k n .\nproc db t p . .\n if t > n\n if n mod p = 0\n for i = 1 to p\n seq[] &= a[i + 1]\n .\n .\n else\n a[t + 1] = a[t - p + 1]\n db t + 1 p\n j = a[t - p + 1] + 1\n while j < k\n a[t + 1] = j mod 256\n db t + 1 t\n j += 1\n .\n .\n.\nfunc$ debruijn k0 n0 .\n k = k0\n n = n0\n a[] = [ ]\n len a[] k * n\n seq[] = [ ]\n db 1 1\n for v in seq[]\n buf$ &= v\n .\n buf$ &= substr buf$ 1 (n - 1)\n return buf$\n.\nfunc alldigits s$ .\n for c$ in strchars s$\n if strcode c$ < 48 or strcode c$ > 57\n return 0\n .\n .\n return 1\n.\nproc validate db$ . .\n len found[] 10000\n for i = 1 to len db$ - 3\n s$ = substr db$ i 4\n if alldigits s$ = 1\n n = number s$\n found[n + 1] += 1\n .\n .\n for i = 1 to 10000\n if found[i] = 0\n errs$[] &= \" PIN number \" & i - 1 & \" missing\"\n elif found[i] > 1\n errs$[] &= \" PIN number \" & i - 1 & \" occurs \" & found[i] & \" times\"\n .\n .\n if len errs$[] = 0\n print \" No errors found\"\n else\n for s$ in errs$[]\n print s$\n .\n .\n.\nproc main . .\n db$ = debruijn 10 4\n print \"The length of the de Bruijn sequence is \" & len db$\n print \"\"\n write \"The first 130 digits of the de Bruijn sequence are: \"\n print substr db$ 1 130\n print \"\"\n write \"The last 130 digits of the de Bruijn sequence are: \"\n print substr db$ -130 130\n print \"\"\n print \"Validating the de Bruijn sequence:\"\n validate db$\n print \"\"\n print \"Validating the reversed de Bruijn sequence:\"\n for i = len db$ downto 1\n dbr$ &= substr db$ i 1\n .\n validate dbr$\n print \"\"\n db$ = substr db$ 1 4443 & \".\" & substr db$ 4445 (1 / 0)\n print \"Validating the overlaid de Bruijn sequence:\"\n validate db$\n print \"\"\n.\nmain\n", "language": "EasyLang" }, { "code": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"strconv\"\n \"strings\"\n)\n\nconst digits = \"0123456789\"\n\nfunc deBruijn(k, n int) string {\n alphabet := digits[0:k]\n a := make([]byte, k*n)\n var seq []byte\n var db func(int, int) // recursive closure\n db = func(t, p int) {\n if t > n {\n if n%p == 0 {\n seq = append(seq, a[1:p+1]...)\n }\n } else {\n a[t] = a[t-p]\n db(t+1, p)\n for j := int(a[t-p] + 1); j < k; j++ {\n a[t] = byte(j)\n db(t+1, t)\n }\n }\n }\n db(1, 1)\n var buf bytes.Buffer\n for _, i := range seq {\n buf.WriteByte(alphabet[i])\n }\n b := buf.String()\n return b + b[0:n-1] // as cyclic append first (n-1) digits\n}\n\nfunc allDigits(s string) bool {\n for _, b := range s {\n if b < '0' || b > '9' {\n return false\n }\n }\n return true\n}\n\nfunc validate(db string) {\n le := len(db)\n found := make([]int, 10000)\n var errs []string\n // Check all strings of 4 consecutive digits within 'db'\n // to see if all 10,000 combinations occur without duplication.\n for i := 0; i < le-3; i++ {\n s := db[i : i+4]\n if allDigits(s) {\n n, _ := strconv.Atoi(s)\n found[n]++\n }\n }\n for i := 0; i < 10000; i++ {\n if found[i] == 0 {\n errs = append(errs, fmt.Sprintf(\" PIN number %04d missing\", i))\n } else if found[i] > 1 {\n errs = append(errs, fmt.Sprintf(\" PIN number %04d occurs %d times\", i, found[i]))\n }\n }\n lerr := len(errs)\n if lerr == 0 {\n fmt.Println(\" No errors found\")\n } else {\n pl := \"s\"\n if lerr == 1 {\n pl = \"\"\n }\n fmt.Printf(\" %d error%s found:\\n\", lerr, pl)\n fmt.Println(strings.Join(errs, \"\\n\"))\n }\n}\n\nfunc reverse(s string) string {\n bytes := []byte(s)\n for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n bytes[i], bytes[j] = bytes[j], bytes[i]\n }\n return string(bytes)\n}\n\nfunc main() {\n db := deBruijn(10, 4)\n le := len(db)\n fmt.Println(\"The length of the de Bruijn sequence is\", le)\n fmt.Println(\"\\nThe first 130 digits of the de Bruijn sequence are:\")\n fmt.Println(db[0:130])\n fmt.Println(\"\\nThe last 130 digits of the de Bruijn sequence are:\")\n fmt.Println(db[le-130:])\n fmt.Println(\"\\nValidating the de Bruijn sequence:\")\n validate(db)\n\n fmt.Println(\"\\nValidating the reversed de Bruijn sequence:\")\n dbr := reverse(db)\n validate(dbr)\n\n bytes := []byte(db)\n bytes[4443] = '.'\n db = string(bytes)\n fmt.Println(\"\\nValidating the overlaid de Bruijn sequence:\")\n validate(db)\n}\n", "language": "Go" }, { "code": "import java.util.function.BiConsumer\n\nclass DeBruijn {\n interface Recursable<T, U> {\n void apply(T t, U u, Recursable<T, U> r);\n }\n\n static <T, U> BiConsumer<T, U> recurse(Recursable<T, U> f) {\n return { t, u -> f.apply(t, u, f) }\n }\n\n private static String deBruijn(int k, int n) {\n byte[] a = new byte[k * n]\n Arrays.fill(a, (byte) 0)\n\n List<Byte> seq = new ArrayList<>()\n\n BiConsumer<Integer, Integer> db = recurse({ int t, int p, f ->\n if (t > n) {\n if (n % p == 0) {\n for (int i = 1; i < p + 1; ++i) {\n seq.add(a[i])\n }\n }\n } else {\n a[t] = a[t - p]\n f.apply(t + 1, p, f)\n int j = a[t - p] + 1\n while (j < k) {\n a[t] = (byte) (j & 0xFF)\n f.apply(t + 1, t, f)\n j++\n }\n }\n })\n db.accept(1, 1)\n\n StringBuilder sb = new StringBuilder()\n for (Byte i : seq) {\n sb.append(\"0123456789\".charAt(i))\n }\n\n sb.append(sb.subSequence(0, n - 1))\n return sb.toString()\n }\n\n private static boolean allDigits(String s) {\n for (int i = 0; i < s.length(); ++i) {\n char c = s.charAt(i)\n if (!Character.isDigit(c)) {\n return false\n }\n }\n return true\n }\n\n private static void validate(String db) {\n int le = db.length()\n int[] found = new int[10_000]\n Arrays.fill(found, 0)\n List<String> errs = new ArrayList<>()\n\n // Check all strings of 4 consecutive digits within 'db'\n // to see if all 10,000 combinations occur without duplication.\n for (int i = 0; i < le - 3; ++i) {\n String s = db.substring(i, i + 4)\n if (allDigits(s)) {\n int n = Integer.parseInt(s)\n found[n]++\n }\n }\n\n for (int i = 0; i < 10_000; ++i) {\n if (found[i] == 0) {\n errs.add(String.format(\" PIN number %d is missing\", i))\n } else if (found[i] > 1) {\n errs.add(String.format(\" PIN number %d occurs %d times\", i, found[i]))\n }\n }\n\n if (errs.isEmpty()) {\n System.out.println(\" No errors found\")\n } else {\n String pl = (errs.size() == 1) ? \"\" : \"s\"\n System.out.printf(\" %d error%s found:\\n\", errs.size(), pl)\n errs.forEach(System.out.&println)\n }\n }\n\n static void main(String[] args) {\n String db = deBruijn(10, 4)\n\n System.out.printf(\"The length of the de Bruijn sequence is %d\\n\\n\", db.length())\n System.out.printf(\"The first 130 digits of the de Bruijn sequence are: %s\\n\\n\", db.substring(0, 130))\n System.out.printf(\"The last 130 digits of the de Bruijn sequence are: %s\\n\\n\", db.substring(db.length() - 130))\n\n System.out.println(\"Validating the de Bruijn sequence:\")\n validate(db)\n\n StringBuilder sb = new StringBuilder(db)\n String rdb = sb.reverse().toString()\n System.out.println()\n System.out.println(\"Validating the de Bruijn sequence:\")\n validate(rdb)\n\n sb = new StringBuilder(db)\n sb.setCharAt(4443, '.' as char)\n System.out.println()\n System.out.println(\"Validating the overlaid de Bruijn sequence:\")\n validate(sb.toString())\n }\n}\n", "language": "Groovy" }, { "code": "import Data.List\nimport Data.Map ((!))\nimport qualified Data.Map as M\n\n-- represents a permutation in a cycle notation\ncycleForm :: [Int] -> [[Int]]\ncycleForm p = unfoldr getCycle $ M.fromList $ zip [0..] p\n where\n getCycle p\n | M.null p = Nothing\n | otherwise =\n let Just ((x,y), m) = M.minViewWithKey p\n c = if x == y then [] else takeWhile (/= x) (iterate (m !) y)\n in Just (c ++ [x], foldr M.delete m c)\n\n-- the set of Lyndon words generated by inverse Burrows—Wheeler transform\nlyndonWords :: Ord a => [a] -> Int -> [[a]]\nlyndonWords s n = map (ref !!) <$> cycleForm perm\n where\n ref = concat $ replicate (length s ^ (n - 1)) s\n perm = s >>= (`elemIndices` ref)\n\n-- returns the de Bruijn sequence of order n for an alphabeth s\ndeBruijn :: Ord a => [a] -> Int -> [a]\ndeBruijn s n = let lw = concat $ lyndonWords n s\n in lw ++ take (n-1) lw\n", "language": "Haskell" }, { "code": "import Control.Monad (replicateM)\n\nmain = do\n let symbols = ['0'..'9']\n let db = deBruijn symbols 4\n putStrLn $ \"The length of de Bruijn sequence: \" ++ show (length db)\n putStrLn $ \"The first 130 symbols are:\\n\" ++ show (take 130 db)\n putStrLn $ \"The last 130 symbols are:\\n\" ++ show (drop (length db - 130) db)\n\n let words = replicateM 4 symbols\n let validate db = filter (not . (`isInfixOf` db)) words\n putStrLn $ \"Words not in the sequence: \" ++ unwords (validate db)\n\n let db' = a ++ ('.': tail b) where (a,b) = splitAt 4444 db\n putStrLn $ \"Words not in the corrupted sequence: \" ++ unwords (validate db')\n", "language": "Haskell" }, { "code": "import Control.Monad.State\nimport Data.Array (Array, listArray, (!), (//))\nimport qualified Data.Array as A\n\ndeBruijn :: [a] -> Int -> [a]\ndeBruijn s n =\n let\n k = length s\n\n db :: Int -> Int -> State (Array Int Int) [Int]\n db t p =\n if t > n\n then\n if n `mod` p == 0\n then get >>= \\a -> return [ a ! k | k <- [1 .. p]]\n else return []\n else do\n a <- get\n x <- setArray t (a ! (t-p)) >> db (t+1) p\n a <- get\n y <- sequence [ setArray t j >> db (t+1) t\n | j <- [a ! (t-p) + 1 .. k - 1] ]\n return $ x ++ concat y\n\n setArray i x = modify (// [(i, x)])\n\n seqn = db 1 1 `evalState` listArray (0, k*n-1) (repeat 0)\n\n in [ s !! i | i <- seqn ++ take (n-1) seqn ]\n", "language": "Haskell" }, { "code": "NB. implement inverse Burrows—Wheeler transform sequence method\n\nrepeat_alphabet=: [: , [: i.&> (^ <:) # [\nassert 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 -: 2 repeat_alphabet 4\n\nde_bruijn=: ({~ ([: ; [: C. /:^:2))@:repeat_alphabet NB. K de_bruijn N\n\npins=: #&10 #: [: i. 10&^ NB. pins y generates all y digit PINs\ngroups=: [ ]\\ ] , ({.~ <:)~ NB. length x infixes of sequence y cyclically extended by x-1\nverify_PINs=: (/:~@:groups -: pins@:[) NB. LENGTH verify_PINs SEQUENCE\n", "language": "J" }, { "code": " NB. A is the sequence\n A=: 10 de_bruijn 4\n\n NB. tally A\n #A\n10000\n\n NB. literally the first and final 130 digits\n Num_j_ {~ 130 ({. ,: ({.~ -)~) A\n0000101001101111000210020102110202001210120112111202121200221022012211220222122220003100320030103110321030203120322030300131013201\n9469956996699769986990799179927993799479957996799779987990899189928993899489958996899789988990999199929993999499959996999799989999\n\n NB. verifications. seriously?\n 4 verify_PINs A\n1\n 4 (verify_PINs |.) A\n1\n 4 verify_PINs (a.i.'.') (<: 4444)} A\n0\n", "language": "J" }, { "code": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.function.BiConsumer;\n\npublic class DeBruijn {\n public interface Recursable<T, U> {\n void apply(T t, U u, Recursable<T, U> r);\n }\n\n public static <T, U> BiConsumer<T, U> recurse(Recursable<T, U> f) {\n return (t, u) -> f.apply(t, u, f);\n }\n\n private static String deBruijn(int k, int n) {\n byte[] a = new byte[k * n];\n Arrays.fill(a, (byte) 0);\n\n List<Byte> seq = new ArrayList<>();\n\n BiConsumer<Integer, Integer> db = recurse((t, p, f) -> {\n if (t > n) {\n if (n % p == 0) {\n for (int i = 1; i < p + 1; ++i) {\n seq.add(a[i]);\n }\n }\n } else {\n a[t] = a[t - p];\n f.apply(t + 1, p, f);\n int j = a[t - p] + 1;\n while (j < k) {\n a[t] = (byte) (j & 0xFF);\n f.apply(t + 1, t, f);\n j++;\n }\n }\n });\n db.accept(1, 1);\n\n StringBuilder sb = new StringBuilder();\n for (Byte i : seq) {\n sb.append(\"0123456789\".charAt(i));\n }\n\n sb.append(sb.subSequence(0, n - 1));\n return sb.toString();\n }\n\n private static boolean allDigits(String s) {\n for (int i = 0; i < s.length(); ++i) {\n char c = s.charAt(i);\n if (!Character.isDigit(c)) {\n return false;\n }\n }\n return true;\n }\n\n private static void validate(String db) {\n int le = db.length();\n int[] found = new int[10_000];\n Arrays.fill(found, 0);\n List<String> errs = new ArrayList<>();\n\n // Check all strings of 4 consecutive digits within 'db'\n // to see if all 10,000 combinations occur without duplication.\n for (int i = 0; i < le - 3; ++i) {\n String s = db.substring(i, i + 4);\n if (allDigits(s)) {\n int n = Integer.parseInt(s);\n found[n]++;\n }\n }\n\n for (int i = 0; i < 10_000; ++i) {\n if (found[i] == 0) {\n errs.add(String.format(\" PIN number %d is missing\", i));\n } else if (found[i] > 1) {\n errs.add(String.format(\" PIN number %d occurs %d times\", i, found[i]));\n }\n }\n\n if (errs.isEmpty()) {\n System.out.println(\" No errors found\");\n } else {\n String pl = (errs.size() == 1) ? \"\" : \"s\";\n System.out.printf(\" %d error%s found:\\n\", errs.size(), pl);\n errs.forEach(System.out::println);\n }\n }\n\n public static void main(String[] args) {\n String db = deBruijn(10, 4);\n\n System.out.printf(\"The length of the de Bruijn sequence is %d\\n\\n\", db.length());\n System.out.printf(\"The first 130 digits of the de Bruijn sequence are: %s\\n\\n\", db.substring(0, 130));\n System.out.printf(\"The last 130 digits of the de Bruijn sequence are: %s\\n\\n\", db.substring(db.length() - 130));\n\n System.out.println(\"Validating the de Bruijn sequence:\");\n validate(db);\n\n StringBuilder sb = new StringBuilder(db);\n String rdb = sb.reverse().toString();\n System.out.println();\n System.out.println(\"Validating the de Bruijn sequence:\");\n validate(rdb);\n\n sb = new StringBuilder(db);\n sb.setCharAt(4443, '.');\n System.out.println();\n System.out.println(\"Validating the overlaid de Bruijn sequence:\");\n validate(sb.toString());\n }\n}\n", "language": "Java" }, { "code": "def allDigits:\n all(explode[]; 48 <= . and . <= 57);\n\ndef lpad($len): tostring | ($len - length) as $l | (\"0\" * $l) + .;\n\ndef deBruijn:\n {deBruijn: \"\"}\n | reduce range(0; 100) as $n (.;\n ($n|lpad(2)) as $a\n | ($a | explode) as [$a1, $a2]\n | if $a2 >= $a1\n then .deBruijn += (if ($a1 == $a2) then ([$a1]|implode) else $a end)\n | .m = $n + 1\n | until(.m > 99;\n (.m|lpad(2)) as $ms\n | if ($ms[1:2]|explode[0]) > $a1\n then .deBruijn += $a + $ms\n end\n | .m += 1 )\n end )\n | .deBruijn + \"000\" ;\n\ndef describe:\n . as $d\n | \"de Bruijn sequence length: \\($d|length)\",\n \"First 130 characters:\",\n $d[0:130],\n \"Last 130 characters:\",\n $d[-130:];\n\ndef check:\n . as $text\n | { res: [],\n found: [range(0;10000) | 0],\n k: 0 }\n | reduce range( 0; $text|length-3) as $i (.;\n $text[$i : $i+4] as $s\n | if ($s|allDigits)\n then .k = ($s|tonumber)\n | .found[.k] += 1\n end )\n | reduce range(0; 10000) as $i (.;\n .k = .found[$i]\n | if .k != 1\n then (\" Pin number \\($i) \"\n + (if .k == 0 then \"missing\" else \"occurs \\(.k) times\" end ) ) as $e\n | .res += [$e]\n end )\n | .k = (.res|length)\n | if .k == 0\n then .res = \"No errors found\"\n else\n (if .k == 1 then \"\" else \"s\" end) as $s\n | .res = \"\\(.k) error\\($s) found:\\n\" + (.res | join(\"\\n\"))\n end\n | .res ;\n\n# The tasks\ndeBruijn\n| describe,\n \"Missing 4 digit PINs in this sequence: \\(check)\",\n \"Missing 4 digit PINs in the reversed sequence: \\(explode|reverse|implode|check)\",\n\n \"4,444th digit in the sequence: '\\(.[4443])' (setting it to '.')\",\n ( .[0:4443] + \".\" + .[4444:]\n | \"Re-running checks: \\(check)\" )\n", "language": "Jq" }, { "code": "function debruijn(k::Integer, n::Integer)\n alphabet = b\"0123456789abcdefghijklmnopqrstuvwxyz\"[1:k]\n a = zeros(UInt8, k * n)\n seq = UInt8[]\n\n function db(t, p)\n if t > n\n if n % p == 0\n append!(seq, a[2:p+1])\n end\n else\n a[t + 1] = a[t - p + 1]\n db(t + 1, p)\n for j in a[t-p+1]+1:k-1\n a[t + 1] = j\n db(t + 1, t)\n end\n end\n end\n\n db(1, 1)\n return String([alphabet[i + 1] for i in vcat(seq, seq[1:n-1])])\nend\n\nfunction verifyallPIN(str, k, n, deltaposition=0)\n if deltaposition != 0\n str = str[1:deltaposition-1] * \".\" * str[deltaposition+1:end]\n end\n result = true\n for i in 1:k^n-1\n pin = string(i, pad=n)\n if !occursin(pin, str)\n println(\"PIN $pin does not occur in the sequence.\")\n result = false\n end\n end\n println(\"The sequence does \", result ? \"\" : \"not \", \"contain all PINs.\")\nend\n\nconst s = debruijn(10, 4)\nprintln(\"The length of the sequence is $(length(s)). The first 130 digits are:\\n\",\n s[1:130], \"\\nand the last 130 digits are:\\n\", s[end-130:end])\nprint(\"Testing sequence: \"), verifyallPIN(s, 10, 4)\nprint(\"Testing the reversed sequence: \"), verifyallPIN(reverse(s), 10, 4)\nprintln(\"\\nAfter replacing 4444th digit with \\'.\\':\"), verifyallPIN(s, 10, 4, 4444)\n", "language": "Julia" }, { "code": "const val digits = \"0123456789\"\n\nfun deBruijn(k: Int, n: Int): String {\n val alphabet = digits.substring(0, k)\n val a = ByteArray(k * n)\n val seq = mutableListOf<Byte>()\n fun db(t: Int, p: Int) {\n if (t > n) {\n if (n % p == 0) {\n seq.addAll(a.sliceArray(1..p).asList())\n }\n } else {\n a[t] = a[t - p]\n db(t + 1, p)\n var j = a[t - p] + 1\n while (j < k) {\n a[t] = j.toByte()\n db(t + 1, t)\n j++\n }\n }\n }\n db(1, 1)\n val buf = StringBuilder()\n for (i in seq) {\n buf.append(alphabet[i.toInt()])\n }\n val b = buf.toString()\n return b + b.subSequence(0, n - 1)\n}\n\nfun allDigits(s: String): Boolean {\n for (c in s) {\n if (c < '0' || '9' < c) {\n return false\n }\n }\n return true\n}\n\nfun validate(db: String) {\n val le = db.length\n val found = MutableList(10_000) { 0 }\n val errs = mutableListOf<String>()\n // Check all strings of 4 consecutive digits within 'db'\n // to see if all 10,000 combinations occur without duplication.\n for (i in 0 until le - 3) {\n val s = db.substring(i, i + 4)\n if (allDigits(s)) {\n val n = s.toInt()\n found[n]++\n }\n }\n for (i in 0 until 10_000) {\n if (found[i] == 0) {\n errs.add(\" PIN number %04d missing\".format(i))\n } else if (found[i] > 1) {\n errs.add(\" PIN number %04d occurs %d times\".format(i, found[i]))\n }\n }\n val lerr = errs.size\n if (lerr == 0) {\n println(\" No errors found\")\n } else {\n val pl = if (lerr == 1) {\n \"\"\n } else {\n \"s\"\n }\n println(\" $lerr error$pl found:\")\n println(errs.joinToString(\"\\n\"))\n }\n}\n\nfun main() {\n var db = deBruijn(10, 4)\n val le = db.length\n\n println(\"The length of the de Bruijn sequence is $le\")\n println(\"\\nThe first 130 digits of the de Bruijn sequence are: ${db.subSequence(0, 130)}\")\n println(\"\\nThe last 130 digits of the de Bruijn sequence are: ${db.subSequence(le - 130, le)}\")\n\n println(\"\\nValidating the deBruijn sequence:\")\n validate(db)\n\n println(\"\\nValidating the reversed deBruijn sequence:\")\n validate(db.reversed())\n\n val bytes = db.toCharArray()\n bytes[4443] = '.'\n db = String(bytes)\n println(\"\\nValidating the overlaid deBruijn sequence:\")\n validate(db)\n}\n", "language": "Kotlin" }, { "code": "function tprint(tbl)\n for i,v in pairs(tbl) do\n print(v)\n end\nend\n\nfunction deBruijn(k, n)\n local a = {}\n for i=1, k*n do\n table.insert(a, 0)\n end\n\n local seq = {}\n function db(t, p)\n if t > n then\n if n % p == 0 then\n for i=1, p do\n table.insert(seq, a[i + 1])\n end\n end\n else\n a[t + 1] = a[t - p + 1]\n db(t + 1, p)\n\n local j = a[t - p + 1] + 1\n while j < k do\n a[t + 1] = j % 256\n db(t + 1, t)\n j = j + 1\n end\n end\n end\n\n db(1, 1)\n\n local buf = \"\"\n for i,v in pairs(seq) do\n buf = buf .. tostring(v)\n end\n return buf .. buf:sub(1, n - 1)\nend\n\nfunction allDigits(s)\n return s:match('[0-9]+') == s\nend\n\nfunction validate(db)\n local le = string.len(db)\n local found = {}\n local errs = {}\n\n for i=1, 10000 do\n table.insert(found, 0)\n end\n\n -- Check all strings of 4 consecutive digits within 'db'\n -- to see if all 10,000 combinations occur without duplication.\n for i=1, le - 3 do\n local s = db:sub(i, i + 3)\n if allDigits(s) then\n local n = tonumber(s)\n found[n + 1] = found[n + 1] + 1\n end\n end\n\n local count = 0\n for i=1, 10000 do\n if found[i] == 0 then\n table.insert(errs, \" PIN number \" .. (i - 1) .. \" missing\")\n count = count + 1\n elseif found[i] > 1 then\n table.insert(errs, \" PIN number \" .. (i - 1) .. \" occurs \" .. found[i] .. \" times\")\n count = count + 1\n end\n end\n\n if count == 0 then\n print(\" No errors found\")\n else\n tprint(errs)\n end\nend\n\nfunction main()\n local db = deBruijn(10,4)\n\n print(\"The length of the de Bruijn sequence is \" .. string.len(db))\n print()\n\n io.write(\"The first 130 digits of the de Bruijn sequence are: \")\n print(db:sub(0, 130))\n print()\n\n io.write(\"The last 130 digits of the de Bruijn sequence are: \")\n print(db:sub(-130))\n print()\n\n print(\"Validating the de Bruijn sequence:\")\n validate(db)\n print()\n\n print(\"Validating the reversed de Bruijn sequence:\")\n validate(db:reverse())\n print()\n\n db = db:sub(1,4443) .. \".\" .. db:sub(4445)\n print(\"Validating the overlaid de Bruijn sequence:\")\n validate(db)\n print()\nend\n\nmain()\n", "language": "Lua" }, { "code": "seq = DeBruijnSequence[Range[0, 9], 4];\nseq = seq~Join~Take[seq, 3];\nLength[seq]\n{seq[[;; 130]], seq[[-130 ;;]]}\nComplement[\n StringDrop[ToString[NumberForm[#, 4, NumberPadding -> {\"0\", \"0\"}]],\n 1] & /@ Range[0, 9999],\n Union[StringJoin /@ Partition[ToString /@ seq, 4, 1]]]\nseq = Reverse[seq];\nComplement[\n StringDrop[ToString[NumberForm[#, 4, NumberPadding -> {\"0\", \"0\"}]],\n 1] & /@ Range[0, 9999],\n Union[StringJoin /@ Partition[ToString /@ seq, 4, 1]]]\nseq[[4444]] = \".\";\nComplement[\n StringDrop[ToString[NumberForm[#, 4, NumberPadding -> {\"0\", \"0\"}]],\n 1] & /@ Range[0, 9999],\n Union[StringJoin /@ Partition[ToString /@ seq, 4, 1]]]\n", "language": "Mathematica" }, { "code": "import algorithm, parseutils, strformat, strutils\n\nconst Digits = \"0123456789\"\n\n#---------------------------------------------------------------------------------------------------\n\nfunc deBruijn(k, n: int): string =\n let alphabet = Digits[0..<k]\n var a = newSeq[byte](k * n)\n var sequence: seq[byte]\n\n #.................................................................................................\n\n func db(t, p: int) =\n if t > n:\n if n mod p == 0:\n sequence &= a[1..p]\n else:\n a[t] = a[t - p]\n db(t + 1, p)\n var j = a[t - p] + 1\n while j < k.uint:\n a[t] = j\n db(t + 1, t)\n inc j\n\n #...............................................................................................\n\n db(1, 1)\n for i in sequence:\n result &= alphabet[i]\n result &= result[0..(n-2)]\n\n#---------------------------------------------------------------------------------------------------\n\nproc validate(db: string) =\n\n var found: array[10_000, int]\n var errs: seq[string]\n\n ## Check all strings of 4 consecutive digits within 'db'\n ## to see if all 10,000 combinations occur without duplication.\n for i in 0..(db.len - 4):\n let s = db[i..(i+3)]\n var n: int\n if s.parseInt(n) == 4:\n inc found[n]\n\n for n, count in found:\n if count == 0:\n errs &= fmt\" PIN number {n:04d} missing\"\n elif count > 1:\n errs &= fmt\" PIN number {n:04d} occurs {count} times\"\n\n if errs.len == 0:\n echo \" No errors found\"\n else:\n let plural = if errs.len == 1: \"\" else: \"s\"\n echo fmt\" {errs.len} error{plural} found\"\n for err in errs: echo err\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nvar db = deBruijn(10, 4)\n\necho fmt\"The length of the de Bruijn sequence is {db.len}\"\necho \"\"\necho fmt\"The first 130 digits of the de Bruijn sequence are: {db[0..129]}\"\necho \"\"\necho fmt\"The last 130 digits of the de Bruijn sequence are: {db[^130..^1]}\"\necho \"\"\n\necho \"Validating the deBruijn sequence:\"\ndb.validate()\necho \"\"\necho \"Validating the reversed deBruijn sequence:\"\nreversed(db).join().validate()\necho \"\"\n\ndb[4443] = '.'\necho \"Validating the overlaid deBruijn sequence:\"\ndb.validate()\n", "language": "Nim" }, { "code": "program deBruijnSequence;\nuses SysUtils;\n\n// Create a de Bruijn sequence for the given word length and alphabet.\nfunction deBruijn( const n : integer; // word length\n const alphabet : string) : string;\nvar\n d, k, m, s, t, seqLen : integer;\n w : array of integer;\nbegin\n k := Length( alphabet);\n // de Bruijn sequence will have length k^n\n seqLen := 1;\n for t := 1 to n do seqLen := seqLen*k;\n SetLength( result, seqLen);\n d := 0; // index into de Bruijn sequence (will be pre-inc'd)\n // Work through Lyndon words of length <= n, in lexicographic order.\n SetLength( w, n); // w holds array of indices into the alphabet\n w[0] := 1; // first Lyndon word\n m := 1; // m = length of Lyndon word\n repeat\n // If m divides n, append the current Lyndon word to the output\n if (m = n) or (m = 1) or (n mod m = 0) then begin\n for t := 0 to m - 1 do begin\n inc(d);\n result[d] := alphabet[w[t]];\n end;\n end;\n // Get next Lyndon word using Duval's algorithm:\n // (1) Fill w with repetitions of current word\n s := 0; t := m;\n while (t < n) do begin\n w[t] := w[s];\n inc(t); inc(s);\n if s = m then s := 0;\n end;\n // (2) Repeatedly delete highest index k from end of w, if present\n m := n;\n while (m > 0) and (w[m - 1] = k) do dec(m);\n // (3) If word is now null, stop; else increment end value\n if m > 0 then inc( w[m - 1]);\n until m = 0;\n Assert( d = seqLen); // check that the sequence is exactly filled in\nend;\n\n// Check a de Bruijn sequence, assuming that its alphabet consists\n// of the digits '0'..'9' (in any order);\nprocedure CheckDecimal( const n : integer; // word length\n const deB : string);\nvar\n count : array of integer;\n j, L, pin, nrErrors : integer;\n wrap : string;\nbegin\n L := Length( deB);\n // The de Bruijn sequence is cyclic; make an array to handle wrapround.\n SetLength( wrap, 2*n - 2);\n for j := 1 to n - 1 do wrap[j] := deB[L + j - n + 1];\n for j := n to 2*n - 2 do wrap[j] := deB[j - n + 1];\n // Count occurrences of each PIN.\n // PIN = -1 if character is not a decimal digit.\n SetLength( count, L);\n for j := 0 to L - 1 do count[L] := 0;\n for j := 1 to L - n + 1 do begin\n pin := SysUtils.StrToIntDef( Copy( deB, j, n), -1);\n if pin >= 0 then inc( count[pin]);\n end;\n for j := 1 to n - 1 do begin\n pin := SysUtils.StrToIntDef( Copy( wrap, j, n), -1);\n if pin >= 0 then inc( count[pin]);\n end;\n // Check that all counts are 1\n nrErrors := 0;\n for j := 0 to L - 1 do begin\n if count[j] <> 1 then begin\n inc( nrErrors);\n WriteLn( SysUtils.Format( ' PIN %d has count %d', [j, count[j]]));\n end;\n end;\n WriteLn( SysUtils.Format( ' Number of errors = %d', [nrErrors]));\n end;\n\n// Main routine\nvar\n deB, rev : string;\n L, j : integer;\nbegin\n deB := deBruijn( 4, '0123456789');\n// deB := deBruijn( 4, '7368290514'); // any permutation would do\n L := Length( deB);\n WriteLn( SysUtils.Format( 'Length of de Bruijn sequence = %d', [L]));\n if L >= 260 then begin\n WriteLn;\n WriteLn( 'First and last 130 characters are:');\n WriteLn( Copy( deB, 1, 65));\n WriteLn( Copy( deb, 66, 65));\n WriteLn( '...');\n WriteLn( Copy( deB, L - 129, 65));\n WriteLn( Copy( deB, L - 64, 65));\n end;\n WriteLn;\n WriteLn( 'Checking de Bruijn sequence:');\n CheckDecimal( 4, deB);\n // Check reversed sequence\n SetLength( rev, L);\n for j := 1 to L do rev[j] := deB[L + 1 - j];\n WriteLn( 'Checking reversed sequence:');\n CheckDecimal( 4, rev);\n // Check sequence with '.' instad of decimal digit\n if L >= 4444 then begin\n deB[4444] := '.';\n WriteLn( 'Checking vandalized sequence:');\n CheckDecimal( 4, deB);\n end;\nend.\n", "language": "Pascal" }, { "code": "use strict;\nuse warnings;\nuse feature 'say';\n\nmy $seq;\nfor my $x (0..99) {\n my $a = sprintf '%02d', $x;\n next if substr($a,1,1) < substr($a,0,1);\n $seq .= (substr($a,0,1) == substr($a,1,1)) ? substr($a,0,1) : $a;\n for ($a+1 .. 99) {\n next if substr(sprintf('%02d', $_), 1,1) <= substr($a,0,1);\n $seq .= sprintf \"%s%02d\", $a, $_;\n }\n}\n$seq .= '000';\n\nsub check {\n my($seq) = @_;\n my %chk;\n for (0.. -1 + length $seq) { $chk{substr($seq, $_, 4)}++ }\n say 'Missing: ' . join ' ', grep { ! $chk{ sprintf('%04d',$_) } } 0..9999;\n say 'Extra: ' . join ' ', sort grep { $chk{$_} > 1 } keys %chk;\n}\n\nmy $n = 130;\nsay \"de Bruijn sequence length: \" . length $seq;\nsay \"\\nFirst $n characters:\\n\" . substr($seq, 0, $n );\nsay \"\\nLast $n characters:\\n\" . substr($seq, -$n, $n);\nsay \"\\nIncorrect 4 digit PINs in this sequence:\";\ncheck $seq;\n\nsay \"\\nIncorrect 4 digit PINs in the reversed sequence:\";\ncheck(reverse $seq);\n\nsay \"\\nReplacing the 4444th digit, '@{[substr($seq,4443,1)]}', with '5'\";\nsubstr $seq, 4443, 1, 5;\nsay \"Incorrect 4 digit PINs in the revised sequence:\";\ncheck $seq;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">deBruijn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">99</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%02d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">a1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">a2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">a2</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">a1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">deBruijn</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a1</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">a2</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">a1</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">99</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">ms</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%02d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ms</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]></span><span style=\"color: #000000;\">a1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">deBruijn</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">ms</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">deBruijn</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #008000;\">\"000\"</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"de Bruijn sequence length: %d\\n\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">deBruijn</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"First 130 characters:\\n%s\\n\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">deBruijn</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">130</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Last 130 characters:\\n%s\\n\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">deBruijn</span><span style=\"color: #0000FF;\">[-</span><span style=\"color: #000000;\">130</span><span style=\"color: #0000FF;\">..-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">check</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">text</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">found</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10000</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">k</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">text</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">to_integer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">text</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">],-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">found</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">10000</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">found</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">e</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Pin number %04d \"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">e</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"missing\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"occurs %d times\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"No errors found\"</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"s\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d error%s found:\\n \"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">})&</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n \"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Missing 4 digit PINs in this sequence: %s\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">check</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">deBruijn</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Missing 4 digit PINs in the reversed sequence: %s\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">check</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">reverse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">deBruijn</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"4444th digit in the sequence: %c (setting it to .)\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">deBruijn</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">4444</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">deBruijn</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">4444</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">'.'</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Re-running checks: %s\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">check</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">deBruijn</span><span style=\"color: #0000FF;\">))</span>\n<!--\n", "language": "Phix" }, { "code": "# from https://en.wikipedia.org/wiki/De_Bruijn_sequence\n\ndef de_bruijn(k, n):\n \"\"\"\n de Bruijn sequence for alphabet k\n and subsequences of length n.\n \"\"\"\n try:\n # let's see if k can be cast to an integer;\n # if so, make our alphabet a list\n _ = int(k)\n alphabet = list(map(str, range(k)))\n\n except (ValueError, TypeError):\n alphabet = k\n k = len(k)\n\n a = [0] * k * n\n sequence = []\n\n def db(t, p):\n if t > n:\n if n % p == 0:\n sequence.extend(a[1:p + 1])\n else:\n a[t] = a[t - p]\n db(t + 1, p)\n for j in range(a[t - p] + 1, k):\n a[t] = j\n db(t + 1, t)\n db(1, 1)\n return \"\".join(alphabet[i] for i in sequence)\n\ndef validate(db):\n \"\"\"\n\n Check that all 10,000 combinations of 0-9 are present in\n De Bruijn string db.\n\n Validating the reversed deBruijn sequence:\n No errors found\n\n Validating the overlaid deBruijn sequence:\n 4 errors found:\n PIN number 1459 missing\n PIN number 4591 missing\n PIN number 5814 missing\n PIN number 8145 missing\n\n \"\"\"\n\n dbwithwrap = db+db[0:3]\n\n digits = '0123456789'\n\n errorstrings = []\n\n for d1 in digits:\n for d2 in digits:\n for d3 in digits:\n for d4 in digits:\n teststring = d1+d2+d3+d4\n if teststring not in dbwithwrap:\n errorstrings.append(teststring)\n\n if len(errorstrings) > 0:\n print(\" \"+str(len(errorstrings))+\" errors found:\")\n for e in errorstrings:\n print(\" PIN number \"+e+\" missing\")\n else:\n print(\" No errors found\")\n\ndb = de_bruijn(10, 4)\n\nprint(\" \")\nprint(\"The length of the de Bruijn sequence is \", str(len(db)))\nprint(\" \")\nprint(\"The first 130 digits of the de Bruijn sequence are: \"+db[0:130])\nprint(\" \")\nprint(\"The last 130 digits of the de Bruijn sequence are: \"+db[-130:])\nprint(\" \")\nprint(\"Validating the deBruijn sequence:\")\nvalidate(db)\ndbreversed = db[::-1]\nprint(\" \")\nprint(\"Validating the reversed deBruijn sequence:\")\nvalidate(dbreversed)\ndboverlaid = db[0:4443]+'.'+db[4444:]\nprint(\" \")\nprint(\"Validating the overlaid deBruijn sequence:\")\nvalidate(dboverlaid)\n", "language": "Python" }, { "code": "#lang racket\n\n(define (de-bruijn k n)\n (define a (make-vector (* k n) 0))\n (define seq '())\n (define (db t p)\n (cond\n [(> t n) (when (= (modulo n p) 0)\n (set! seq (cons (call-with-values\n (thunk (vector->values a 1 (add1 p)))\n list)\n seq)))]\n [else (vector-set! a t (vector-ref a (- t p)))\n (db (add1 t) p)\n (for ([j (in-range (add1 (vector-ref a (- t p))) k)])\n (vector-set! a t j)\n (db (add1 t) t))]))\n (db 1 1)\n (define seq* (append* (reverse seq)))\n (append seq* (take seq* (sub1 n))))\n\n(define seq (de-bruijn 10 4))\n(printf \"The length of the de Bruijn sequence is ~a\\n\\n\" (length seq))\n(printf \"The first 130 digits of the de Bruijn sequence are:\\n~a\\n\\n\"\n (take seq 130))\n(printf \"The last 130 digits of the de Bruijn sequence are:\\n~a\\n\\n\"\n (take-right seq 130))\n\n(define (validate name seq)\n (printf \"Validating the ~ade Bruijn sequence:\\n\" name)\n (define expected (for/set ([i (in-range 0 10000)]) i))\n (define actual (for/set ([a (in-list seq)]\n [b (in-list (rest seq))]\n [c (in-list (rest (rest seq)))]\n [d (in-list (rest (rest (rest seq))))])\n (+ (* 1000 a) (* 100 b) (* 10 c) d)))\n (define diff (set-subtract expected actual))\n (cond\n [(set-empty? diff) (printf \" No errors found\\n\")]\n [else (for ([n (in-set diff)])\n (printf \" ~a is missing\\n\" (~a n #:width 4 #:pad-string \"0\")))])\n (newline))\n\n(validate \"\" seq)\n(validate \"reversed \" (reverse seq))\n(validate \"overlaid \" (list-update seq 4443 add1))\n", "language": "Racket" }, { "code": "# Generate the sequence\nmy $seq;\n\nfor ^100 {\n my $a = .fmt: '%02d';\n next if $a.substr(1,1) < $a.substr(0,1);\n $seq ~= ($a.substr(0,1) == $a.substr(1,1)) ?? $a.substr(0,1) !! $a;\n for +$a ^..^ 100 {\n next if .fmt('%02d').substr(1,1) <= $a.substr(0,1);\n $seq ~= sprintf \"%s%02d\", $a, $_ ;\n }\n}\n\n$seq = $seq.comb.list.rotate((^10000).pick).join;\n\n$seq ~= $seq.substr(0,3);\n\nsub check ($seq) {\n my %chk;\n for ^($seq.chars) { %chk{$seq.substr( $_, 4 )}++ }\n put 'Missing: ', (^9999).grep( { not %chk{ .fmt: '%04d' } } ).fmt: '%04d';\n put 'Extra: ', %chk.grep( *.value > 1 )».key.sort.fmt: '%04d';\n}\n\n## The Task\nput \"de Bruijn sequence length: \" ~ $seq.chars;\n\nput \"\\nFirst 130 characters:\\n\" ~ $seq.substr( 0, 130 );\n\nput \"\\nLast 130 characters:\\n\" ~ $seq.substr( * - 130 );\n\nput \"\\nIncorrect 4 digit PINs in this sequence:\";\ncheck $seq;\n\nput \"\\nIncorrect 4 digit PINs in the reversed sequence:\";\ncheck $seq.flip;\n\nmy $digit = $seq.substr(4443,1);\nput \"\\nReplacing the 4444th digit, ($digit) with { ($digit += 1) %= 10 }\";\nput \"Incorrect 4 digit PINs in the revised sequence:\";\n$seq.substr-rw(4443,1) = $digit;\ncheck $seq;\n", "language": "Raku" }, { "code": "/*REXX pgm calculates the de Bruijn sequence for all pin numbers (4 digit decimals). */\n$= /*initialize the de Bruijn sequence. */\n#=10; lastNode= (#-2)(#-2)(#-1)(#-2) /*this number is formed when this # ···*/\n /* ··· is skipped near the cycle end. */\n do j=0 for 10; $= $ || j; jj= j || j /*compose the left half of the numbers.*/\n /* [↓] \" right \" \" \" \" */\n do k=jj+1 to 99; z= jj || right(k, 2, 0)\n if z==lastNode then iterate /*the last node skipped.*/\n if pos(z, $)\\==0 then iterate /*# in sequence? Skip it*/\n $= $ || z /* ◄─────────────────────────────────┐ */\n end /*k*/ /*append a number to the sequence──◄─┘ */\n\n do r= jj to (j || 9); b= right(r, 2, 0) /*compose the left half of the numbers.*/\n if b==jj then iterate\n $= $ || right(b, 2, 0) /* [↓] \" right \" \" \" \" */\n do k= b+1 to 99; z= right(b, 2, 0) || right(k, 2, 0)\n if pos(z, $)\\==0 then iterate /*# in sequence? Skip it*/\n $= $ || z /* ◄─────────────────────────────────┐ */\n end /*k*/ /*append a number to the sequence──◄─┘ */\n end /*r*/\n end /*j*/\n @deB= 'de Bruijn sequence' /*literal used in some SAY instructions*/\n$= $ || left($, 3) /*append 000*/ /*simulate \"wrap-around\" de Bruijn seq.*/\n say 'length of the' @deB \" is \" length($) /*display the length of de Bruijn seq.*/\nsay; say 'first 130 digits of the' @deB\":\" /*display the title for the next line. */\n say left($, 130) /*display 130 left-most digits of seq. */\nsay; say ' last 130 digits of the' @deB\":\" /*display the title for the next line. */\n say right($, 130) /*display 130 right-most digits of seq.*/\nsay /*display a blank line. */\ncall val $ /*call the VAL sub for verification. */\n @deB= 'reversed' @deB /*next, we'll check on a reversed seq.*/\n$$= reverse($) /*do what a mirror does, reversify it.*/\ncall val $$ /*call the VAL sub for verification. */\n$= overlay(., $, 4444) /*replace 4,444th digit with a period. */\n @deB= 'overlaid' subword(@deB, 2) /* [↑] this'll cause a validation barf.*/\ncall val $ /*call the VAL sub for verification. */\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nval: parse arg $$$; e= 0; _= copies('─',8) /*count of errors (missing PINs) so far*/\n say; say _ 'validating the' @deB\".\" /*display what's happening in the pgm. */\n do pin=0 for 1e4; pin4= right(pin,4,0) /* [↓] maybe add leading zeros to pin.*/\n if pos(pin4, $$$)\\==0 then iterate /*Was number found? Just as expected. */\n say 'PIN number ' pin \" wasn't found in\" @deb'.'\n e= e + 1 /*bump the counter for number of errors*/\n end /*pin*/ /* [↑] validate all 10,000 pin numbers*/\n if e==0 then e= 'No' /*Gooder English (sic) the error count.*/\n say _ e 'errors found.' /*display the number of errors found. */\n return\n", "language": "REXX" }, { "code": "/*REXX pgm calculates the de Bruijn sequence for all pin numbers (4 digit decimals). */\n$= /*initialize the de Bruijn sequence. */\n do j=0 for 10; $= $ j; jj= j || j /*compose the left half of the numbers.*/\n $$= space($, 0) /* [↓] \" right \" \" \" \" */\n do k=jj+1 to 99; z= jj || right(k, 2, 0)\n if pos(z, $$)\\==0 then iterate /*# in sequence? Skip it*/\n $= $ z /* ◄─────────────────────────────────┐ */\n end /*k*/ /*append a number to the sequence──◄─┘ */\n $$= space($, 0)\n do r= jj to (j || 9); b= right(r, 2, 0) /*compose the left half of the numbers.*/\n if b==jj then iterate\n $= $ right(b, 2, 0) /* [↓] \" right \" \" \" \" */\n $$= space($, 0); do k= b+1 to 99; z= right(b, 2, 0) || right(k, 2, 0)\n if pos(z, $$)\\==0 then iterate /*# in sequence? Skip it*/\n $= $ z /* ◄─────────────────────────────────┐ */\n end /*k*/ /*append a number to the sequence──◄─┘ */\n $$= space($, 0)\n end /*r*/\n end /*j*/\n\n$= delword($, words($)-4, 1) /*delete 5th from the last word in $. */\n$= space($, 0)\n @deB= 'de Bruijn sequence' /*literal used in some SAY instructions*/\n$= $ || left($, 3) /*append 000*/ /*simulate \"wrap-around\" de Bruijn seq.*/\n say 'length of the' @deB \" is \" length($) /*display the length of de Bruijn seq.*/\nsay; say 'first 130 digits of the' @deB\":\" /*display the title for the next line. */\n say left($, 130) /*display 130 left-most digits of seq. */\nsay; say ' last 130 digits of the' @deB\":\" /*display the title for the next line. */\n say right($, 130) /*display 130 right-most digits of seq.*/\ncall val $ /*call the VAL sub for verification. */\n @deB= 'reversed' @deB /*next, we'll check on a reversed seq.*/\n$r= reverse($) /*do what a mirror does, reversify it.*/\ncall val $r /*call the VAL sub for verification. */\n$= overlay(., $, 4444) /*replace 4,444th digit with a period. */\n @deB= 'overlaid' subword(@deB, 2) /* [↑] this'll cause a validation barf.*/\ncall val $ /*call the VAL sub for verification. */\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nval: parse arg $$$; e= 0; _= copies('─',8) /*count of errors (missing PINs) so far*/\n say; say _ 'validating the' @deB\".\" /*display what's happening in the pgm. */\n do pin=0 for 1e4; pin4= right(pin,4,0) /* [↓] maybe add leading zeros to pin.*/\n if pos(pin4, $$$)\\==0 then iterate /*Was number found? Just as expected. */\n say 'PIN number ' pin \" wasn't found in\" @deb'.'\n e= e + 1 /*bump the counter for number of errors*/\n end /*pin*/ /* [↑] validate all 10,000 pin numbers*/\n if e==0 then e= 'No' /*Gooder English (sic) the error count.*/\n say _ e 'errors found.' /*display the number of errors found. */\n return\n", "language": "REXX" }, { "code": "def deBruijn(k, n)\n alphabet = \"0123456789\"\n @a = Array.new(k * n, 0)\n @seq = []\n\n def db(k, n, t, p)\n if t > n then\n if n % p == 0 then\n temp = @a[1 .. p]\n @seq.concat temp\n end\n else\n @a[t] = @a[t - p]\n db(k, n, t + 1, p)\n j = @a[t - p] + 1\n while j < k do\n @a[t] = j # & 0xFF\n db(k, n, t + 1, t)\n j = j + 1\n end\n end\n end\n db(k, n, 1, 1)\n\n buf = \"\"\n for i in @seq\n buf <<= alphabet[i]\n end\n return buf + buf[0 .. n-2]\nend\n\ndef validate(db)\n le = db.length\n found = Array.new(10000, 0)\n errs = []\n # Check all strings of 4 consecutive digits within 'db'\n # to see if all 10,000 combinations occur without duplication.\n for i in 0 .. le-4\n s = db[i .. i+3]\n if s.scan(/\\D/).empty? then\n found[s.to_i] += 1\n end\n end\n for i in 0 .. found.length - 1\n if found[i] == 0 then\n errs <<= (\" PIN number %04d missing\" % [i])\n elsif found[i] > 1 then\n errs <<= (\" PIN number %04d occurs %d times\" % [i, found[i]])\n end\n end\n if errs.length == 0 then\n print \" No errors found\\n\"\n else\n pl = (errs.length == 1) ? \"\" : \"s\"\n print \" \", errs.length, \" error\", pl, \" found:\\n\"\n for err in errs\n print err, \"\\n\"\n end\n end\nend\n\ndb = deBruijn(10, 4)\nprint \"The length of the de Bruijn sequence is \", db.length, \"\\n\\n\"\nprint \"The first 130 digits of the de Bruijn sequence are: \", db[0 .. 129], \"\\n\\n\"\nprint \"The last 130 digits of the de Bruijn sequence are: \", db[-130 .. db.length], \"\\n\\n\"\n\nprint \"Validating the de Bruijn sequence:\\n\"\nvalidate(db)\nprint \"\\n\"\n\ndb[4443] = '.'\nprint \"Validating the overlaid de Bruijn sequence:\\n\"\nvalidate(db)\n", "language": "Ruby" }, { "code": "import scala.collection.mutable.ListBuffer\n\nobject DeBruijn {\n\n def deBruijn(k: Int, n: Int): String = {\n val a = Array.fill[Byte](k * n)(0)\n val seq = new ListBuffer[Byte]()\n\n def db(t: Int, p: Int): Unit = {\n if (t > n) {\n if (n % p == 0) {\n seq ++= a.slice(1, p + 1)\n }\n } else {\n a(t) = a(t - p)\n db(t + 1, p)\n for (j <- (a(t - p) + 1).until(k)) {\n a(t) = j.toByte\n db(t + 1, t)\n }\n }\n }\n\n db(1, 1)\n\n val sb = new StringBuilder\n seq.foreach(i => sb.append(\"0123456789\".charAt(i)))\n sb.append(sb.subSequence(0, n - 1)).toString\n }\n\n private def allDigits(s: String): Boolean = s.forall(_.isDigit)\n\n private def validate(db: String): Unit = {\n val found = Array.fill(10000)(0)\n val errs = ListBuffer[String]()\n\n for (i <- 0 until db.length - 3) {\n val s = db.substring(i, i + 4)\n if (allDigits(s)) {\n val n = s.toInt\n found(n) += 1\n }\n }\n\n for (i <- found.indices) {\n if (found(i) == 0) errs += s\" PIN number $i is missing\"\n else if (found(i) > 1) errs += s\" PIN number $i occurs ${found(i)} times\"\n }\n\n if (errs.isEmpty) println(\" No errors found\")\n else {\n val pl = if (errs.size == 1) \"\" else \"s\"\n println(s\" ${errs.size} error$pl found:\")\n errs.foreach(println)\n }\n }\n\n def main(args: Array[String]): Unit = {\n val db = deBruijn(10, 4)\n\n println(s\"The length of the de Bruijn sequence is ${db.length}\\n\")\n println(s\"The first 130 digits of the de Bruijn sequence are: ${db.take(130)}\\n\")\n println(s\"The last 130 digits of the de Bruijn sequence are: ${db.takeRight(130)}\\n\")\n\n println(\"Validating the de Bruijn sequence:\")\n validate(db)\n\n println()\n println(\"Validating the reversed de Bruijn sequence:\")\n validate(db.reverse)\n\n val overlaidDb = db.updated(4443, '.')\n println()\n println(\"Validating the overlaid de Bruijn sequence:\")\n validate(overlaidDb)\n }\n}\n", "language": "Scala" }, { "code": "Imports System.Text\n\nModule Module1\n\n ReadOnly DIGITS As String = \"0123456789\"\n\n Function DeBruijn(k As Integer, n As Integer) As String\n Dim alphabet = DIGITS.Substring(0, k)\n Dim a(k * n) As Byte\n Dim seq As New List(Of Byte)\n Dim db As Action(Of Integer, Integer) = Sub(t As Integer, p As Integer)\n If t > n Then\n If n Mod p = 0 Then\n Dim seg = New ArraySegment(Of Byte)(a, 1, p)\n seq.AddRange(seg)\n End If\n Else\n a(t) = a(t - p)\n db(t + 1, p)\n Dim j = a(t - p) + 1\n While j < k\n a(t) = j\n db(t + 1, t)\n j += 1\n End While\n End If\n End Sub\n db(1, 1)\n Dim buf As New StringBuilder\n For Each i In seq\n buf.Append(alphabet(i))\n Next\n Dim b = buf.ToString\n Return b + b.Substring(0, n - 1)\n End Function\n\n Function AllDigits(s As String) As Boolean\n For Each c In s\n If c < \"0\" OrElse \"9\" < c Then\n Return False\n End If\n Next\n Return True\n End Function\n\n Sub Validate(db As String)\n Dim le = db.Length\n Dim found(10000) As Integer\n Dim errs As New List(Of String)\n ' Check all strings of 4 consecutive digits within 'db'\n ' to see if all 10,000 combinations occur without duplication.\n For i = 1 To le - 3\n Dim s = db.Substring(i - 1, 4)\n If (AllDigits(s)) Then\n Dim n As Integer = Nothing\n Integer.TryParse(s, n)\n found(n) += 1\n End If\n Next\n For i = 1 To 10000\n If found(i - 1) = 0 Then\n errs.Add(String.Format(\" PIN number {0,4} missing\", i - 1))\n ElseIf found(i - 1) > 1 Then\n errs.Add(String.Format(\" PIN number {0,4} occurs {1} times\", i - 1, found(i - 1)))\n End If\n Next\n Dim lerr = errs.Count\n If lerr = 0 Then\n Console.WriteLine(\" No errors found\")\n Else\n Dim pl = If(lerr = 1, \"\", \"s\")\n Console.WriteLine(\" {0} error{1} found:\", lerr, pl)\n errs.ForEach(Sub(x) Console.WriteLine(x))\n End If\n End Sub\n\n Function Reverse(s As String) As String\n Dim arr = s.ToCharArray\n Array.Reverse(arr)\n Return New String(arr)\n End Function\n\n Sub Main()\n Dim db = DeBruijn(10, 4)\n Dim le = db.Length\n\n Console.WriteLine(\"The length of the de Bruijn sequence is {0}\", le)\n Console.WriteLine(vbNewLine + \"The first 130 digits of the de Bruijn sequence are: {0}\", db.Substring(0, 130))\n Console.WriteLine(vbNewLine + \"The last 130 digits of the de Bruijn sequence are: {0}\", db.Substring(le - 130, 130))\n\n Console.WriteLine(vbNewLine + \"Validating the deBruijn sequence:\")\n Validate(db)\n\n Console.WriteLine(vbNewLine + \"Validating the reversed deBruijn sequence:\")\n Validate(Reverse(db))\n\n Dim bytes = db.ToCharArray\n bytes(4443) = \".\"\n db = New String(bytes)\n Console.WriteLine(vbNewLine + \"Validating the overlaid deBruijn sequence:\")\n Validate(db)\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./fmt\" for Fmt\nimport \"./str\" for Str\n\nvar deBruijn = \"\"\nfor (n in 0..99) {\n var a = Fmt.rjust(2, n, \"0\")\n var a1 = a[0].bytes[0]\n var a2 = a[1].bytes[0]\n if (a2 >= a1) {\n deBruijn = deBruijn + ((a1 == a2) ? String.fromByte(a1): a)\n var m = n + 1\n while (m <= 99) {\n var ms = Fmt.rjust(2, m, \"0\")\n if (ms[1].bytes[0] > a1) deBruijn = deBruijn + a + ms\n m = m + 1\n }\n }\n}\n\ndeBruijn = deBruijn + \"000\"\nSystem.print(\"de Bruijn sequence length: %(deBruijn.count)\\n\")\nSystem.print(\"First 130 characters:\\n%(deBruijn[0...130])\\n\")\nSystem.print(\"Last 130 characters:\\n%(deBruijn[-130..-1])\\n\")\n\nvar check = Fn.new { |text|\n var res = []\n var found = List.filled(10000, 0)\n var k = 0\n for (i in 0...(text.count-3)) {\n var s = text[i..i+3]\n if (Str.allDigits(s)) {\n k = Num.fromString(s)\n found[k] = found[k] + 1\n }\n }\n for (i in 0...10000) {\n k = found[i]\n if (k != 1) {\n var e = \" Pin number %(Fmt.dz(4, i)) \"\n e = e + ((k == 0) ? \"missing\" : \"occurs %(k) times\")\n res.add(e)\n }\n }\n k = res.count\n if (k == 0) {\n res = \"No errors found\"\n } else {\n var s = (k == 1) ? \"\" : \"s\"\n res = \"%(k) error%(s) found:\\n\" + res.join(\"\\n\")\n }\n return res\n}\n\nSystem.print(\"Missing 4 digit PINs in this sequence: %(check.call(deBruijn))\")\nSystem.print(\"Missing 4 digit PINs in the reversed sequence: %(check.call(deBruijn[-1..0]))\")\n\nSystem.print(\"\\n4,444th digit in the sequence: '%(deBruijn[4443])' (setting it to '.')\")\ndeBruijn = deBruijn[0..4442] + \".\" + deBruijn[4444..-1]\nSystem.print(\"Re-running checks: %(check.call(deBruijn))\")\n", "language": "Wren" }, { "code": "dbSeq:=Data();\t// a byte/character buffer\nforeach n in (100){\n a,a01,a11 := \"%02d\".fmt(n), a[0,1], a[1,1];\n if(a11<a01) continue;\n dbSeq.append( if(a01==a11) a01 else a );\n foreach m in ([n+1 .. 99]){\n if(\"%02d\".fmt(m)[1,1] <= a01) continue;\n dbSeq.append(\"%s%02d\".fmt(a,m));\n }\n}\ndbSeq.append(\"000\");\n", "language": "Zkl" }, { "code": "seqText:=dbSeq.text;\nprintln(\"de Bruijn sequence length: \",dbSeq.len());\n\nprintln(\"\\nFirst 130 characters:\\n\",seqText[0,130]);\nprintln(\"\\nLast 130 characters:\\n\", seqText[-130,*]);\n\nfcn chk(seqText){\n chk:=Dictionary();\n foreach n in ([0..seqText.len()-1]){ chk[seqText[n,4]]=True }\n (9999).pump(List,\"%04d\".fmt,'wrap(k){ if(chk.holds(k)) Void.Skip else k })\n}\nprintln(\"\\nMissing 4 digit PINs in this sequence: \", chk(seqText).concat(\" \"));\nprint(\"Missing 4 digit PINs in the reversed sequence: \",chk(seqText.reverse()).concat(\" \"));\n\nprintln(\"\\n4444th digit in the sequence: \", seqText[4443]);\ndbSeq[4443]=\".\";\nprintln(\"Setting the 4444th digit and reruning checks: \",chk(dbSeq.text).concat(\" \"));\n", "language": "Zkl" } ]
De-Bruijn-sequences
[ { "code": "---\ncategory:\n- Cards\nfrom: http://rosettacode.org/wiki/Deal_cards_for_FreeCell\nnote: Games\n", "language": "00-META" }, { "code": "''Free Cell'' is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to ''FreeCell'' and reimplemented the game for [[DOS]], then [[Windows]]. <br>\nThis version introduced 32000 numbered deals. (The [http://www.solitairelaboratory.com/fcfaq.html FreeCell FAQ] tells this history.)\n\nAs the game became popular, Jim Horne disclosed [http://www.solitairelaboratory.com/mshuffle.txt the algorithm], and other implementations of FreeCell began to reproduce the Microsoft deals. <br>\nThese deals are numbered from 1 to 32000. \nNewer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.\n\nThe algorithm uses this [[linear congruential generator]] from Microsoft C:\n\n* <math>state_{n + 1} \\equiv 214013 \\times state_n + 2531011 \\pmod{2^{31}}</math>\n* <math>rand_n = state_n \\div 2^{16}</math>\n* <math>rand_n</math> is in range 0 to 32767.\n* Rosetta Code has another task, [[linear congruential generator]], with code for this RNG in several languages.\n\n<br>\nThe algorithm follows:\n\n# Seed the RNG with the number of the deal.\n# Create an [[array]] of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.\n# Until the array is empty:\n#* Choose a random card at ''index'' &equiv; ''next random number'' (mod ''array length'').\n#* Swap this random card with the last card of the array.\n#* Remove this random card from the array. (Array length goes down by 1.)\n#* Deal this random card.\n# Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.\n\n::::{| class=\"wikitable\"\n!| Order to deal cards\n!| Game #1\n!| Game #617\n|-\n|| <pre> 1 2 3 4 5 6 7 8\n 9 10 11 12 13 14 15 16\n17 18 19 20 21 22 23 24\n25 26 27 28 29 30 31 32\n33 34 35 36 37 38 39 40\n41 42 43 44 45 46 47 48\n49 50 51 52</pre>\n|| <pre>JD 2D 9H JC 5D 7H 7C 5H\nKD KC 9S 5S AD QC KH 3H\n2S KS 9D QD JS AS AH 3C\n4C 5C TS QH 4H AC 4D 7S\n3S TD 4S TH 8H 2C JH 7D\n6D 8S 8D QS 6C 3D 8C TC\n6S 9C 2H 6H</pre>\n|| <pre>7D AD 5C 3S 5S 8C 2D AH\nTD 7S QD AC 6D 8H AS KH\nTH QC 3H 9D 6S 8D 3D TC\nKD 5H 9S 3C 8S 7H 4D JS\n4C QS 9C 9H 7C 6H 2C 2S\n4S TS 2H 5D JC 6C JH QH\nJD KS KC 4H</pre>\n|}\n\nDeals can also be checked against [http://freecellgamesolutions.com/ FreeCell solutions to 1000000 games]. \n(Summon a video solution, and it displays the initial deal.)\n\nWrite a program to take a deal number and deal cards in the same order as this algorithm. \nThe program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.\n\nRelated tasks:\n* [[Playing cards]]\n* [[Card shuffles]]\n* [[War Card_Game]]\n* [[Poker hand_analyser]]\n* [[Go Fish]]\n\n\n", "language": "00-TASK" }, { "code": "F randomGenerator(=seed, n)\n [Int] r\n -V max_int32 = 7FFF'FFFF\n seed = seed [&] max_int32\n\n L r.len < n\n seed = (seed * 214013 + 2531011) [&] max_int32\n r [+]= seed >> 16\n\n R r\n\nF deal(seed)\n V nc = 52\n V cards = Array((nc - 1 .< -1).step(-1))\n V rnd = randomGenerator(seed, nc)\n L(r) rnd\n V j = (nc - 1) - r % (nc - L.index)\n swap(&cards[L.index], &cards[j])\n R cards\n\nF show(cards)\n V l = cards.map(c -> ‘A23456789TJQK’[Int(c / 4)]‘’‘CDHS’[c % 4])\n L(i) (0 .< cards.len).step(8)\n print((l[i .< i + 8]).join(‘ ’))\n\n:start:\nV seed = I :argv.len == 2 {Int(:argv[1])} E 11982\nprint(‘Hand #.’.format(seed))\nV deck = deal(seed)\nshow(deck)\n", "language": "11l" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\nprocedure FreeCell is\n type State is mod 2**31;\n type Deck is array (0..51) of String(1..2);\n\n package Random is\n procedure Init(Seed: State);\n function Rand return State;\n end Random;\n package body Random is\n S : State := State'First;\n procedure Init(Seed: State) is begin S := Seed; end Init;\n function Rand return State is begin\n S := S * 214013 + 2531011; return S / 2**16;\n end Rand;\n end Random;\n\n procedure Deal (num : State) is\n thedeck : Deck; pick : State;\n Chars : constant String := \"A23456789TJQKCDHS\";\n begin\n for i in thedeck'Range loop\n thedeck(i):= Chars(i/4+1) & Chars(i mod 4 + 14);\n end loop;\n Random.Init(num);\n for i in 0..51 loop\n pick := Random.Rand mod State(52-i);\n Put(thedeck(Natural(pick))&' ');\n if (i+1) mod 8 = 0 then New_Line; end if;\n thedeck(Natural(pick)) := thedeck(51-i);\n end loop; New_Line;\n end Deal;\n\nbegin\n Deal(1);\n New_Line;\n Deal(617);\nend FreeCell;\n", "language": "Ada" }, { "code": "FreeCell(num){\n\tcards := \"A23456789TJQK\", suits := \"♣♦♥♠\", card := [], Counter := 0\n\tloop, parse, cards\n\t{\n\t\tThisCard := A_LoopField\n\t\tloop, parse, suits\n\t\t\tCard[Counter++] := ThisCard . A_LoopField\n\t}\n\tloop, 52\n\t{\n\t\ta := MS(num)\n\t\tnum:=a[1]\n\t\tMyCardNo := mod(a[2],53-A_Index)\n\t\tMyCard := Card[MyCardNo]\n\t\tCard[MyCardNo] := Card[52-A_Index]\n\t\tCard.Remove(52-A_Index)\n\t\tRes .= MyCard (Mod(A_Index,8)?\" \":\"`n\")\t\n\t}\n\treturn Res\n}\nMS(Seed) {\n\tSeed := Mod(214013 * Seed + 2531011, 2147483648)\n\treturn, [Seed, Seed // 65536]\n}\n", "language": "AutoHotkey" }, { "code": "Gui, font, s12, Courier\nGui, add, edit, w320 r17 -VScroll, % \"Game# 1`n\" FreeCell(1) \"`n`nGame#617`n\" FreeCell(617)\nGui, show\nreturn\n\nGuiClose:\nGuiEscape:\nExitApp\nreturn\n", "language": "AutoHotkey" }, { "code": " *FLOAT 64\n\n hand% = 617\n\n REM Initialise card library:\n SYS \"LoadLibrary\", \"CARDS.DLL\" TO cards%\n IF cards% = 0 ERROR 100, \"No CARDS library\"\n SYS \"GetProcAddress\", cards%, \"cdtInit\" TO cdtInit%\n SYS \"GetProcAddress\", cards%, \"cdtDraw\" TO cdtDraw%\n SYS cdtInit%, ^dx%, ^dy%\n VDU 23,22,8*dx%;5*dy%;8,16,16,128\n\n REM Initialise deck:\n DIM card&(51)\n FOR I% = 0 TO 51 : card&(I%) = I% : NEXT\n\n REM Shuffle deck:\n dummy% = FNrng(hand%)\n FOR I% = 51 TO 0 STEP -1\n C% = FNrng(-1) MOD (I% + 1)\n SWAP card&(C%), card&(I%)\n NEXT\n\n REM Display deck:\n FOR I% = 0 TO 51\n C% = card&(51 - I%)\n X% = (I% MOD 8) * dx%\n Y% = (I% DIV 8) * dy% * 2 / 3\n SYS cdtDraw%, @memhdc%, X%, Y%, C%, 0, 0\n NEXT\n SYS \"InvalidateRect\", @hwnd%, 0, 0\n *GSAVE freecell\n END\n\n DEF FNrng(seed)\n PRIVATE state, M%\n IF seed >= 0 THEN\n state = seed\n ELSE\n state = (state * 214013 + 2531011)\n FOR M% = 52 TO 31 STEP -1\n IF state >= 2^M% state -= 2^M%\n NEXT\n ENDIF\n = state >> 16\n", "language": "BBC-BASIC" }, { "code": "vutsrqponmlkjihgfedcba`_^]\\[ZYXWVUTSRQPONMLKJIHGFEDC\n>4$0\" :rebmun emaG\">:#,_$&>55+,>\"O?+\"**2+*\"C4'' \"**v\n>8%!492*+*48*\\-,1-:11p0g\\0p11g#^_@A23456789TJQKCDHS*\n^+3:g11,g2+\"/\"%4,g2+g14/4:-\\\"v\"g0:%g11+*-/2-10-1*<>+\n>8#8*#4*#::#%*#*/#*:#*0#:\\#*`#:8#::#*:#8*#8:#2*#+^#<\n", "language": "Befunge" }, { "code": "( ( createArray\n = array rank ranks suit suits\n . A 2 3 4 5 6 7 8 9 T J Q K:?ranks\n & :?array\n & whl\n ' ( !ranks:%?rank ?ranks\n & ♣ ♦ ♥ ♠:?suits\n & whl\n ' ( !suits:%?suit ?suits\n & !array str$(!rank !suit):?array\n )\n )\n & !array\n )\n& ( deal\n = A B D L Z pick card dealt deck\n , i last rand row state\n . !arg:(?deck:? [?L.?state)\n & 8:?row\n & :?dealt\n & ( pick\n = sep\n . ( -1+!row:>0:?row\n & \" \":?sep\n | \\n:?sep&8:?row\n )\n & !dealt !arg !sep:?dealt\n )\n & 2^31:?B\n & 2^16:?D\n & \"\n 'Hard code' the numbers B and D into the rand function using\n macro expansion. (Gives a marginally faster execution speed.)\n \"\n &\n ' (\n . mod$(!state*214013+2531011.$B):?state\n & div$(!state.$D)\n )\n : (=?rand)\n & !L+1:?L\n & whl\n ' ( mod$(rand$.!L+-1:?L):?i\n & !deck:?A [!i %?card ?Z\n & ( !Z:?Z %@?last&!A !last !Z\n | !A\n )\n : ?deck\n & pick$!card\n )\n & pick$\\n\n & str$!dealt\n )\n& createArray$:?deck\n& put$(\"Game #1\\n\",\"dealt.txt\",NEW)\n& put$(deal$(!deck.1),\"dealt.txt\",APP)\n& put$(\"\n\nGame #617\n\",\"dealt.txt\",APP)\n& put$(deal$(!deck.617),\"dealt.txt\",APP)\n&\n)\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nwchar_t s_suits[] = L\"♣♦♥♠\", s_nums[] = L\"A23456789TJQK\";\n\n#define RMAX32 ((1U << 31) - 1)\nstatic int seed = 1;\nint rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; }\nvoid srnd(int x) { seed = x; }\n\nvoid show(const int *c)\n{\n\tint i;\n\tfor (i = 0; i < 52; c++) {\n\t\tprintf(\" \\033[%dm%lc\\033[m%lc\", 32 - (1 + *c) % 4 / 2,\n\t\t\ts_suits[*c % 4], s_nums[*c / 4]);\n\t\tif (!(++i % 8) || i == 52) putchar('\\n');\n\t}\n}\n\nvoid deal(int s, int *t)\n{\n\tint i, j;\n\tsrnd(s);\n\n\tfor (i = 0; i < 52; i++) t[i] = 51 - i;\n\tfor (i = 0; i < 51; i++) {\n\t\tj = 51 - rnd() % (52 - i);\n\t\ts = t[i], t[i] = t[j], t[j] = s;\n\t}\n}\n\nint main(int c, char **v)\n{\n\tint s, card[52];\n\tif (c < 2 || (s = atoi(v[1])) <= 0) s = 11982;\n\n\tsetlocale(LC_ALL, \"\");\n\n\tdeal(s, card);\n\tprintf(\"Hand %d\\n\", s);\n\tshow(card);\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <windows.h>\n#include <iostream>\n\n//--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n//--------------------------------------------------------------------------------------------------\nclass fc_dealer\n{\npublic:\n void deal( int game )\n {\n\t_gn = game;\n\tfillDeck();\n\tshuffle();\n\tdisplay();\n }\n\nprivate:\n void fillDeck()\n {\n\tint p = 0;\n\tfor( int c = 0; c < 13; c++ )\n\t for( int s = 0; s < 4; s++ )\n\t\t_cards[p++] = c | s << 4;\n }\n\n void shuffle()\n {\n\tsrand( _gn );\n\tint cc = 52, nc, lc;\n\twhile( cc )\n\t{\n\t nc = rand() % cc;\n\t lc = _cards[--cc];\n\t _cards[cc] = _cards[nc];\n\t _cards[nc] = lc;\n\t}\n }\n\n void display()\n {\n\tchar* suit = \"CDHS\";\n\tchar* symb = \"A23456789TJQK\";\n\tint z = 0;\n\tcout << \"GAME #\" << _gn << endl << \"=======================\" << endl;\n\tfor( int c = 51; c >= 0; c-- )\n\t{\n\t cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << \" \";\n\t if( ++z >= 8 )\n\t {\n\t\tcout << endl;\n\t\tz = 0;\n\t }\n\t}\n }\n\n int _cards[52], _gn;\n};\n//--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n fc_dealer dealer;\n int gn;\n while( true )\n {\n\tcout << endl << \"Game number please ( 0 to QUIT ): \"; cin >> gn;\n\tif( !gn ) break;\n\n\tsystem( \"cls\" );\n\tdealer.deal( gn );\n\tcout << endl << endl;\n }\n return 0;\n}\n//--------------------------------------------------------------------------------------------------\n", "language": "C++" }, { "code": "#include <string> // std::string\n#include <iostream> // std::cout\n#include <sstream> // std::stringstream\n#include <vector> // std::vector\n\nusing namespace std;\n\n//------------------------------------------------------------------------------\n\nclass Random {\npublic:\n void init(uint32_t seed) { _seed = seed; }\n int roll() { return (_seed = (_seed * MULT + INCR) & MASK) >> 16; }\nprivate:\n int _seed;\n enum { MULT = 214013, INCR = 2531011, MASK = (1U << 31) - 1 };\n};\n\n//------------------------------------------------------------------------------\n\nclass Card {\npublic:\n Card(int value) : _value(value) { }\n int suit() const { return _value % 4; }\n int rank() const { return _value / 4; }\n string str() const {\n stringstream s; s << _ranks[rank()] << _suits[suit()]; return s.str();\n }\nprivate:\n int _value;\n const char* _suits = \"CDHS\";\n const char* _ranks = \"A23456789TJQK\";\n};\n\n//------------------------------------------------------------------------------\n\nclass Deck {\npublic:\n Deck(int seed) {\n _random.init(seed);\n for (int i = 0; i < 52; i++)\n _cards.push_back(Card(51 - i));\n for (int i = 0; i < 51; i++) {\n int j = 51 - _random.roll() % (52 - i);\n swap(_cards[i], _cards[j]);\n }\n }\n string str() const {\n stringstream s;\n for (int i = 0; i < _cards.size(); i++)\n s << _cards[i].str() << (i % 8 == 7 || i == 51 ? \"\\n\" : \" \");\n return s.str();\n }\nprivate:\n vector<Card> _cards;\n Random _random;\n};\n\n//------------------------------------------------------------------------------\n\nint main(int argc, const char * argv[])\n{\n {\n Deck deck(1);\n cout << \"Deck 1\" << endl << deck.str() << endl;\n }\n {\n Deck deck(617);\n cout << \"Deck 617\" << endl << deck.str() << endl;\n }\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace FreeCellDeals\n{\n public class RNG\n {\n private int _state;\n\n public RNG()\n {\n _state = (int)DateTime.Now.Ticks;\n }\n\n public RNG(int n)\n {\n _state = n;\n }\n public int Next()\n {\n return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16;\n }\n }\n\n public enum Rank\n {\n Ace,\n One,\n Two,\n Three,\n Four,\n Five,\n Six,\n Seven,\n Eight,\n Nine,\n Ten,\n Jack,\n Queen,\n King\n }\n\n public enum Suit\n {\n Clubs,\n Diamonds,\n Hearts,\n Spades\n }\n\n public class Card\n {\n private const string Ranks = \"A23456789TJQK\";\n private const string Suits = \"CDHS\";\n\n private Rank _rank;\n public Rank Rank\n {\n get\n {\n return _rank;\n }\n set\n {\n if ((int)value < 0 || (int)value > 12)\n {\n throw new InvalidOperationException(\"Setting card rank out of range\");\n }\n _rank = value;\n }\n }\n\n private Suit _suit;\n public Suit Suit\n {\n get\n {\n return _suit;\n }\n set\n {\n if ((int)value < 0 || (int)value > 3)\n {\n throw new InvalidOperationException(\"Setting card rank out of range\");\n }\n _suit = value;\n }\n }\n\n public Card(Rank rank, Suit suit)\n {\n Rank = rank;\n Suit = suit;\n }\n\n public int NRank()\n {\n return (int) Rank;\n }\n\n public int NSuit()\n {\n return (int) Suit;\n }\n\n public override string ToString()\n {\n return new string(new[] {Ranks[NRank()], Suits[NSuit()]});\n }\n }\n\n public class FreeCellDeal\n {\n public List<Card> Deck { get; private set; }\n\n public FreeCellDeal(int iDeal)\n {\n RNG rng = new RNG(iDeal);\n\n List<Card> rDeck = new List<Card>();\n Deck = new List<Card>();\n\n for (int rank = 0; rank < 13; rank++)\n {\n for (int suit = 0; suit < 4; suit++)\n {\n rDeck.Add(new Card((Rank)rank, (Suit)suit));\n }\n }\n\n // Normally we deal from the front of a deck. The algorithm \"deals\" from the back so we reverse the\n // deck here to more conventionally deal from the front/start of the array.\n for (int iCard = 51; iCard >= 0; iCard--)\n {\n int iSwap = rng.Next() % (iCard + 1);\n Deck.Add(rDeck[iSwap]);\n rDeck[iSwap] = rDeck[iCard];\n }\n }\n\n public override string ToString()\n {\n StringBuilder sb = new StringBuilder();\n for (int iRow = 0; iRow < 6; iRow++ )\n {\n for (int iCol = 0; iCol < 8; iCol++)\n {\n sb.AppendFormat(\"{0} \", Deck[iRow * 8 + iCol]);\n }\n sb.Append(\"\\n\");\n }\n for (int iCard = 48; iCard < 52; iCard++)\n {\n sb.AppendFormat(\"{0} \", Deck[iCard]);\n }\n return sb.ToString();\n }\n }\n\n class Program\n {\n static void Main()\n {\n Console.WriteLine(new FreeCellDeal(1));\n Console.WriteLine();\n Console.WriteLine(new FreeCellDeal(617));\n }\n }\n}\n", "language": "C-sharp" }, { "code": "using System;\nusing System.Text;\n\nnamespace FreeCellConsole\n{\n\tpublic class Rand {\n\t\tlong _seed;\n\t\tpublic Rand(int seed=1) {\n\t\t\t_seed = seed;\n\t\t}\n\t\tpublic int Next() {\n\t\t\treturn (int) ((_seed = (_seed * 214013 + 2531011) & int.MaxValue) >> 16);\n\t\t}\n\t}\n\t\n\tpublic class Card {\n\t\tprivate static readonly string kSuits = \"♣♦♥♠\";\n\t\tprivate static readonly string kValues = \"A23456789TJQK\";\n\t\tpublic int Value { get; set; }\n\t\tpublic int Suit { get; set; }\n\t\tpublic Card(int rawvalue=0) : this(rawvalue / 4, rawvalue % 4) {\n\t\t}\n\t\tpublic Card(int value, int suit) {\n\t\t\tValue = value; Suit = suit;\n\t\t}\n\t\tpublic override string ToString() {\n\t\t\treturn string.Format(\"{0}{1}\", kValues[Value], kSuits[Suit]);\n\t\t}\n\t}\n\t\n\tpublic class Deck {\n\t\tpublic Card[] Cards;\n\t\tpublic Deck(int seed) {\n\t\t\tvar r = new Rand(seed);\n\t\t\tCards = new Card[52];\n\t\t\tfor (int i=0; i < 52; i++)\n\t\t\t\tCards[i] = new Card(51 - i);\n\t\t\tfor (int i=0; i < 51; i++) {\n\t\t\t\tint j = 51 - r.Next() % (52 - i);\n\t\t\t\tCard tmp = Cards[i]; Cards[i] = Cards[j]; Cards[j] = tmp;\n\t\t\t}\n\t\t}\n\t\tpublic override string ToString() {\n\t\t\tvar sb = new StringBuilder();\n\t\t\tfor (int i=0; i < Cards.Length; i++) {\n\t\t\t\tsb.Append(Cards[i].ToString());\n\t\t\t\tsb.Append(i % 8 == 7 ? \"\\n\" : \" \");\n\t\t\t}\n\t\t\treturn sb.ToString();\n\t\t}\n\t}\n\t\n\tclass Program {\n\t\tpublic static void Main(string[] args) {\n\t\t\tConsole.WriteLine(\"Deck 1\\n{0}\\n\", new Deck(1));\n\t\t\tConsole.WriteLine(\"Deck 617\\n{0}\\n\", new Deck(617));\n\t\t}\n\t}\n}\n", "language": "C-sharp" }, { "code": "shared void freeCellDeal() {\n\n\t//a function that returns a random number generating function\n\tfunction createRNG(variable Integer state) =>\n\t\t\t() => (state = (214_013 * state + 2_531_011) % 2^31) / 2^16;\n\t\n\tvoid deal(Integer num) {\n\t\t// create an array with a list comprehension\n\t\tvariable value deck = Array {\n\t\t\tfor(rank in \"A23456789TJQK\")\n\t\t\tfor(suit in \"CDHS\")\n\t\t\t\"``rank````suit``\"\n\t\t};\n\t\tvalue rng = createRNG(num);\n\t\tfor(i in 1..52) {\n\t\t\tvalue index = rng() % deck.size;\n\t\t\tassert(exists lastIndex = deck.lastIndex);\n\t\t\t//swap the random card with the last one\n\t\t\tdeck.swap(index, lastIndex);\n\t\t\t//print the last one\n\t\t\tprocess.write(\"``deck.last else \"missing card\"`` \" );\n\t\t\tif(i % 8 == 0) {\n\t\t\t\tprint(\"\");\n\t\t\t}\n\t\t\t//and shrink the array to remove the last card\n\t\t\tdeck = deck[...lastIndex - 1];\n\t\t}\n\t}\n\t\n\tdeal(1);\n\tprint(\"\\n\");\n\tdeal(617);\n}\n", "language": "Ceylon" }, { "code": "(def deck (into [] (for [rank \"A23456789TJQK\" suit \"CDHS\"] (str rank suit))))\n\n(defn lcg [seed]\n (map #(bit-shift-right % 16)\n (rest (iterate #(mod (+ (* % 214013) 2531011) (bit-shift-left 1 31)) seed))))\n\n(defn gen [seed]\n (map (fn [rnd rng] (into [] [(mod rnd rng) (dec rng)]))\n (lcg seed) (range 52 0 -1)))\n\n(defn xchg [v [src dst]] (assoc v dst (v src) src (v dst)))\n\n(defn show [seed] (map #(println %) (partition 8 8 \"\"\n (reverse (reduce xchg deck (gen seed))))))\n\n(show 1)\n", "language": "Clojure" }, { "code": "(defun make-rng (seed)\n #'(lambda ()\n\t(ash (setf seed (mod (+ (* 214013 seed) 2531011) (expt 2 31))) -16)))\n\n(defun split (s) (map 'list #'string s))\n\n(defun make-deck (seed)\n (let ((hand (make-array 52 :fill-pointer 0))\n\t(rng (make-rng seed)))\n (dolist (d (split \"A23456789TJQK\"))\n (dolist (s (split \"♣♦♥♠\"))\n\t(vector-push (concatenate 'string d s) hand)))\n (dotimes (i 52)\n\t(rotatef (aref hand (- 51 i))\n\t\t (aref hand (mod (funcall rng) (- 52 i)))))\n (nreverse hand)))\n\n(defun show-deck (seed)\n (let ((hand (make-deck seed)))\n (format t \"~%Hand ~d~%\" seed)\n (dotimes (i 52)\n (format t \"~A \" (aref hand i))\n (if (= (mod i 8) 7) (write-line \"\")))))\n\n(show-deck 1)\n(show-deck 617)\n", "language": "Common-Lisp" }, { "code": "import std.stdio, std.conv, std.algorithm, std.range;\n\nstruct RandomGenerator {\n uint seed = 1;\n\n @property uint next() pure nothrow @safe @nogc {\n seed = (seed * 214_013 + 2_531_011) & int.max;\n return seed >> 16;\n }\n}\n\nstruct Deck {\n int[52] cards;\n\n void deal(in uint seed) pure nothrow @safe @nogc {\n enum int nc = cards.length; // Must be signed for iota.\n nc.iota.retro.copy(cards[]);\n\n auto rnd = RandomGenerator(seed);\n foreach (immutable i, ref c; cards)\n c.swap(cards[(nc - 1) - rnd.next % (nc - i)]);\n }\n\n void show() const @safe {\n writefln(\"%(%-( %s%)\\n%)\",\n cards[]\n .chunks(8)\n .map!(row => row.map!(c => only(\"A23456789TJQK\"[c / 4],\n \"CDHS\"[c % 4]))));\n }\n}\n\nvoid main(in string[] args) @safe {\n immutable seed = (args.length == 2) ? args[1].to!uint : 11_982;\n writeln(\"Hand \", seed);\n Deck cards;\n cards.deal(seed);\n cards.show;\n}\n", "language": "D" }, { "code": "program Deal_cards_for_FreeCell;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils;\n\ntype\n TRandom = record\n Seed: Int64;\n function Next: Integer;\n end;\n\n TCard = record\n const\n kSuits = '♣♦♥♠';\n kValues = 'A23456789TJQK';\n var\n Value: Integer;\n Suit: Integer;\n procedure Create(rawvalue: Integer); overload;\n procedure Create(value, suit: Integer); overload;\n procedure Assign(other: TCard);\n function ToString: string;\n end;\n\n TDeck = record\n Cards: TArray<TCard>;\n procedure Create(Seed: Integer);\n function ToString: string;\n end;\n\n{ TRandom }\n\nfunction TRandom.Next: Integer;\nbegin\n Seed := ((Seed * 214013 + 2531011) and Integer.MaxValue);\n Result := Seed shr 16;\nend;\n\n{ TCard }\n\nprocedure TCard.Create(rawvalue: Integer);\nbegin\n Create(rawvalue div 4, rawvalue mod 4);\nend;\n\nprocedure TCard.Assign(other: TCard);\nbegin\n Create(other.Value, other.Suit);\nend;\n\nprocedure TCard.Create(value, suit: Integer);\nbegin\n self.Value := value;\n self.Suit := suit;\nend;\n\nfunction TCard.ToString: string;\nbegin\n result := format('%s%s', [kValues[value + 1], kSuits[suit + 1]]);\nend;\n\n{ TDeck }\n\nprocedure TDeck.Create(Seed: Integer);\nvar\n r: TRandom;\n i, j: integer;\n tmp: Tcard;\nbegin\n r.Seed := Seed;\n SetLength(Cards, 52);\n for i := 0 to 51 do\n Cards[i].Create(51 - i);\n for i := 0 to 50 do\n begin\n j := 51 - (r.Next mod (52 - i));\n tmp.Assign(Cards[i]);\n Cards[i].Assign(Cards[j]);\n Cards[j].Assign(tmp);\n end;\nend;\n\nfunction TDeck.ToString: string;\nvar\n i: Integer;\nbegin\n Result := '';\n for i := 0 to length(Cards) - 1 do\n begin\n Result := Result + Cards[i].ToString;\n if i mod 8 = 7 then\n Result := Result + #10\n else\n Result := Result + ' ';\n end;\nend;\n\nvar\n Deck: TDeck;\n\nbegin\n Deck.Create(1);\n Writeln('Deck 1'#10, Deck.ToString, #10);\n Deck.Create(617);\n Writeln('Deck 617'#10, Deck.ToString);\n readln;\nend.\n", "language": "Delphi" }, { "code": "global seed .\nfunc xrnd .\n seed = (seed * 214013 + 2531011) mod 0x80000000\n return seed div 0x10000\n.\nlen cards[] 52\nproc deal game_num . .\n print \"hand \" & game_num\n seed = game_num\n for i = 1 to 52\n cards[i] = 52 - i\n .\n for i = 1 to 51\n j = 52 - xrnd mod (53 - i)\n swap cards[i] cards[j]\n .\n.\nsuits$[] = strchars \"CDHS\"\nranks$[] = strchars \"A23456789TJQK\"\n#\nproc show . .\n for idx = 1 to 52\n rank = cards[idx] div 4 + 1\n suit = cards[idx] mod 4 + 1\n write ranks$[rank] & suits$[suit] & \" \"\n if idx mod1 13 = 13\n print \"\"\n .\n .\n print \"\"\n.\ndeal 1 ; show\ndeal 617 ; show\n", "language": "EasyLang" }, { "code": "defmodule FreeCell do\n import Bitwise\n\n @suits ~w( C D H S )\n @pips ~w( A 2 3 4 5 6 7 8 9 T J Q K )\n @orig_deck for pip <- @pips, suit <- @suits, do: pip <> suit\n\n def deal(games) do\n games = if length(games) == 0, do: [Enum.random(1..32000)], else: games\n Enum.each(games, fn seed ->\n IO.puts \"Game ##{seed}\"\n Enum.reduce(52..2, {seed,@orig_deck}, fn len,{state,deck} ->\n state = ((214013 * state) + 2531011) &&& 0x7fff_ffff\n index = rem(state >>> 16, len)\n last = len - 1\n {a, b} = {Enum.at(deck, index), Enum.at(deck, last)}\n {state, deck |> List.replace_at(index, b) |> List.replace_at(last, a)}\n end)\n |> elem(1)\n |> Enum.reverse\n |> Enum.chunk(8,8,[])\n |> Enum.each(fn row -> Enum.join(row, \" \") |> IO.puts end)\n IO.puts \"\"\n end)\n end\nend\n\nSystem.argv |> Enum.map(&String.to_integer/1)\n|> FreeCell.deal\n", "language": "Elixir" }, { "code": "PROGRAM FREECELL\n\n!$DOUBLE\n\nDIM CARDS%[52]\n\nPROCEDURE XRANDOM(SEED->XRND)\n POW31=2^31\n POW16=2^16\n SEED=SEED*214013+2531011\n SEED=SEED-POW31*INT(SEED/POW31)\n XRND=INT(SEED/POW16)\nEND PROCEDURE\n\nPROCEDURE DEAL(CARDS%[],GAME_NUM)\n LOCAL I%,J%,S%\n SEED=GAME_NUM\n FOR I%=1 TO 52 DO\n CARDS%[I%]=52-I%\n END FOR\n FOR I%=1 TO 51 DO\n XRANDOM(SEED->XRND)\n J%=52-XRND MOD (53-I%)\n S%=CARDS%[I%]\n CARDS%[I%]=CARDS%[J%]\n CARDS%[J%]=S%\n END FOR\nEND PROCEDURE\n\nPROCEDURE SHOW(CARDS%[])\n LOCAL INDEX%\n FOR INDEX%=1 TO 52 DO\n PRINT(MID$(SUITS$,CARDS%[INDEX%] MOD 4+1,1);MID$(NUMS$,CARDS%[INDEX%] DIV 4+1,1);\" \";)\n IF INDEX% MOD 8=0 OR INDEX%=52 THEN\n PRINT\n END IF\n END FOR\nEND PROCEDURE\n\nBEGIN\n PRINT(CHR$(12);)\n SUITS$=\"♣♦♥♠\"\n NUMS$=\"A23456789TJQK\"\n GAME_NUM=1982 ! if missing command line\n IF CMDLINE$<>\"\" THEN GAME_NUM=VAL(CMDLINE$) END IF\n SEED=1\n DEAL(CARDS%[],GAME_NUM)\n PRINT(\"Hand \";GAME_NUM)\n SHOW(CARDS%[])\nEND PROGRAM\n", "language": "ERRE" }, { "code": "let msKindaRand seed =\n let state = ref seed\n (fun (_:unit) ->\n state := (214013 * !state + 2531011) &&& System.Int32.MaxValue\n !state / (1<<<16))\n\nlet unshuffledDeck = [0..51] |> List.map(fun n->sprintf \"%c%c\" \"A23456789TJQK\".[n / 4] \"CDHS\".[n % 4])\n\nlet deal boot idx =\n let (last,rest) = boot |> List.rev |> fun xs->(List.head xs),(xs |> List.tail |> List.rev)\n if idx=((List.length boot) - 1) then last, rest\n else\n rest\n |> List.mapi (fun i x -> i,x)\n |> List.partition (fst >> ((>) idx))\n |> fun (xs,ys) -> (List.map snd xs),(List.map snd ys)\n |> fun (xs,ys) -> (List.head ys),(xs @ last::(List.tail ys))\n\nlet game gameNo =\n let rnd = msKindaRand gameNo\n [52..-1..1]\n |> List.map (fun i->rnd() % i)\n |> List.fold (fun (dealt, boot) idx->deal boot idx |> fun (x,xs) -> (x::dealt, xs)) ([],unshuffledDeck)\n |> fst |> List.rev\n |> List.chunkBySize 8\n |> List.map (String.concat \" \")\n |> String.concat \"\\n\"\n |> printfn \"Game #%d\\n%s\\n\" gameNo\n\n\n[1; 617] |> List.iter game\n", "language": "F-Sharp" }, { "code": "USING: formatting grouping io kernel literals make math\nmath.functions namespaces qw sequences sequences.extras ;\nIN: rosetta-code.freecell\n\nCONSTANT: max-rand-ms $[ 1 15 shift 1 - ]\nCONSTANT: suits qw{ C D H S }\nCONSTANT: ranks qw{ A 2 3 4 5 6 7 8 9 T J Q K }\nSYMBOL: seed\n\n: (random) ( n1 n2 -- n3 ) seed get * + dup seed set ;\n\n: rand-ms ( -- n )\n max-rand-ms 2531011 214013 (random) -16 shift bitand ;\n\n: init-deck ( -- seq )\n ranks suits [ append ] cartesian-map concat V{ } like ;\n\n: swap-cards ( seq -- seq' )\n rand-ms over length [ mod ] [ 1 - ] bi pick exchange ;\n\n: (deal) ( seq -- seq' )\n [ [ swap-cards dup pop , ] until-empty ] { } make ;\n\n: deal ( game# -- seq ) seed set init-deck (deal) ;\n\n: .cards ( seq -- ) 8 group [ [ write bl ] each nl ] each nl ;\n\n: .game ( game# -- ) dup \"Game #%d\\n\" printf deal .cards ;\n\n: freecell ( -- ) 1 617 [ .game ] bi@ ;\n\nMAIN: freecell\n", "language": "Factor" }, { "code": "module Freecell\n use lcgs\n implicit none\n\n character(4) :: suit = \"CDHS\"\n character(13) :: rank = \"A23456789TJQK\"\n character(2) :: deck(0:51)\n\ncontains\n\nsubroutine Createdeck()\n integer :: i, j, n\n\n n = 0\n do i = 1, 13\n do j = 1, 4\n deck(n) = rank(i:i) // suit(j:j)\n n = n + 1\n end do\n end do\n\nend subroutine\n\nsubroutine Freecelldeal(game)\n integer, intent(in) :: game\n integer(i64) :: rnum\n integer :: i, n\n character(2) :: tmp\n\n call Createdeck()\n rnum = msrand(game)\n\n do i = 51, 1, -1\n n = mod(rnum, i+1)\n tmp = deck(n)\n deck(n) = deck(i)\n deck(i) = tmp\n rnum = msrand()\n end do\n\n write(*, \"(a, i0)\") \"Game #\", game\n write(*, \"(8(a, tr1))\") deck(51:0:-1)\n write(*,*)\n\nend subroutine\nend module Freecell\n\nprogram Freecell_test\n use Freecell\n implicit none\n\n call Freecelldeal(1)\n call Freecelldeal(617)\n\nend program\n", "language": "Fortran" }, { "code": "' version 04-11-2016\n' compile with: fbc -s console\n\n' to seed ms_lcg(seed > -1)\n' to get random number ms_lcg(-1) or ms_lcg() or just ms_lcg\nFunction ms_lcg(seed As Integer = -1) As UInteger\n\n Static As UInteger ms_state\n\n If seed <> -1 Then\n ms_state = seed Mod 2 ^ 31\n Else\n ms_state = (214013 * ms_state + 2531011) Mod 2 ^ 31\n End If\n\n Return ms_state Shr 16\n\nEnd Function\n\n' ------=< MAIN >=------\n\nDim As UByte card(51)\nDim As String suit = \"CDHS\", value = \"A23456789TJQK\"\nDim As Long i, c, s, v, game = 1\nDim As ULong game_nr(1 To 2) = { 1, 617}\n\nDo\n\n ms_lcg(game_nr(game)) ' seed generator\n Print \"game #\"; game_nr(game)\n game = game + 1\n\n For i = 0 To 51 ' set up the cards\n card(i) = i\n Next\n\n For i = 51 To 0 Step -1 ' shuffle\n c = ms_lcg Mod (i +1)\n Swap card(i), card(c)\n Next\n\n c = 0\n Do\n For i = 0 To 7\n s = card(51 - c) Mod 4\n v = card(51 - c) \\ 4\n Print Chr(value[v]); Chr(suit[s]); \" \";\n c = c +1\n If c > 51 Then Exit Do\n Next\n Print\n Loop\n Print : Print\n\nLoop Until game > UBound(game_nr)\n\n\n' empty keyboard buffer\nWhile Inkey <> \"\" : Wend\nPrint : Print \"hit any key to end program\"\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/rand\"\n \"os\"\n \"strconv\"\n \"time\"\n)\n\nconst sSuits = \"CDHS\"\nconst sNums = \"A23456789TJQK\"\nconst rMax32 = math.MaxInt32\n\nvar seed = 1\n\nfunc rnd() int {\n seed = (seed*214013 + 2531011) & rMax32\n return seed >> 16\n}\n\nfunc deal(s int) []int {\n seed = s\n t := make([]int, 52)\n for i := 0; i < 52; i++ {\n t[i] = 51 - i\n }\n for i := 0; i < 51; i++ {\n j := 51 - rnd()%(52-i)\n t[i], t[j] = t[j], t[i]\n }\n return t\n}\n\nfunc show(cs []int) {\n for i, c := range cs {\n fmt.Printf(\" %c%c\", sNums[c/4], sSuits[c%4])\n if (i+1)%8 == 0 || i+1 == len(cs) {\n fmt.Println()\n }\n }\n}\n\nfunc main() {\n var game int\n switch len(os.Args) {\n case 1:\n rand.Seed(time.Now().UnixNano())\n game = 1 + rand.Intn(32000)\n case 2:\n var err error\n game, err = strconv.Atoi(os.Args[1])\n if err == nil && game >= 1 && game <= 32000 {\n break\n }\n fallthrough\n default:\n fmt.Println(\"usage: deal [game]\")\n fmt.Println(\" where game is a number in the range 1 to 32000\")\n return\n }\n fmt.Printf(\"\\nGame #%d\\n\", game)\n show(deal(game))\n}\n", "language": "Go" }, { "code": "class FreeCell{\n int seed\n\n List<String> createDeck(){\n List<String> suits = ['♣','♦','♥','♠']\n List<String> values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']\n return [suits,values].combinations{suit,value -> \"$suit$value\"}\n }\n\n int random() {\n seed = (214013 * seed + 2531011) & Integer.MAX_VALUE\n return seed >> 16\n }\n\n List<String> shuffledDeck(List<String> cards) {\n List<String> deck = cards.clone()\n\n (deck.size() - 1..1).each{index ->\n int r = random() % (index + 1)\n deck.swap(r, index)\n }\n\n return deck\n }\n\n List<String> dealGame(int seed = 1){\n this.seed= seed\n List<String> cards = shuffledDeck(createDeck())\n\n (1..cards.size()).each{ number->\n print \"${cards.pop()}\\t\"\n if(number % 8 == 0) println('')\n }\n\n println('\\n')\n }\n}\n\ndef freecell = new FreeCell()\nfreecell.dealGame()\nfreecell.dealGame(617)\n", "language": "Groovy" }, { "code": "import Data.Int\nimport Data.Bits\nimport Data.List\nimport Data.Array.ST\nimport Control.Monad\nimport Control.Monad.ST\nimport System.Environment\n\nsrnd :: Int32 -> [Int]\nsrnd = map (fromIntegral . flip shiftR 16) .\n tail . iterate (\\x -> (x * 214013 + 2531011) .&. maxBound)\n\ndeal :: Int32 -> [String]\ndeal s = runST (do\n ar <- newListArray (0,51) $ sequence [\"A23456789TJQK\", \"CDHS\"]\n :: ST s (STArray s Int String)\n forM (zip [52,51..1] rnd) $ \\(n, r) -> do\n let j = r `mod` n\n vj <- readArray ar j\n vn <- readArray ar (n - 1)\n writeArray ar j vn\n return vj)\n where rnd = srnd s\n\nshowCards :: [String] -> IO ()\nshowCards = mapM_ (putStrLn . unwords) .\n takeWhile (not . null) .\n unfoldr (Just . splitAt 8)\n\nmain :: IO ()\nmain = do\n args <- getArgs\n let s = read (head args) :: Int32\n putStrLn $ \"Deal \" ++ show s ++ \":\"\n let cards = deal s\n showCards cards\n", "language": "Haskell" }, { "code": "procedure main(A) # freecelldealer\n freecelldealer(\\A[1] | &null) # seed from command line\nend\n\nprocedure newDeck() #: return a new unshuffled deck\n every D := list(52) & i := 0 & r := !\"A23456789TJQK\" & s := !\"CDHS\" do\n D[i +:= 1] := r || s # initial deck AC AD ... KS\n return D\nend\n\nprocedure freecelldealer(gamenum) #: deal a freecell hand\n /gamenum := 11982\n return showHand(freecellshuffle(newDeck(),gamenum))\nend\n\nprocedure showHand(D) #: show a freecell hand\n write(\"Hand:\\n\")\n every writes(\" \",(1 to 8) | \"\\n\")\n every writes(\" \",D[i := 1 to *D]) do\n if i%8 = 0 then write()\n write(\"\\n\")\n return D\nend\n\nprocedure freecellshuffle(D,gamenum) #: freecell shuffle\n\n srand_freecell(gamenum) # seed random number generator\n D2 := []\n until *D = 0 do { # repeat until all dealt\n D[r := rand_freecell() % *D + 1] :=: D[*D] # swap random & last cards\n put(D2,pull(D)) # remove dealt card from list\n }\n return D2\nend\n\nprocedure srand_freecell(x) #: seed random\nstatic seed\n return seed := \\x | \\seed | 0 # parm or seed or zero if none\nend\n\nprocedure rand_freecell() #: lcrng\n return ishift(srand_freecell((214013 * srand_freecell() + 2531011) % 2147483648),-16)\nend\n", "language": "Icon" }, { "code": "deck=: ,/ 'A23456789TJQK' ,\"0/ 7 u: '♣♦♥♠'\n\nsrnd=: 3 :'SEED=:{.y,11982'\nsrnd ''\nseed=: do bind 'SEED'\nrnd=: (2^16) <.@%~ (2^31) srnd@| 2531011 + 214013 * seed\n\npairs=: <@<@~.@(<: , (| rnd))@>:@i.@-@# NB. indices to swap, for shuffle\nswaps=: [: > C.&.>/@|.@; NB. implement the specified shuffle\ndeal=: |.@(swaps pairs) bind deck\n\nshow=: (,\"2)@:(_8 ]\\ ' '&,.)\n", "language": "J" }, { "code": " show deal srnd 1\n J♦ 2♦ 9♥ J♣ 5♦ 7♥ 7♣ 5♥\n K♦ K♣ 9♠ 5♠ A♦ Q♣ K♥ 3♥\n 2♠ K♠ 9♦ Q♦ J♠ A♠ A♥ 3♣\n 4♣ 5♣ T♠ Q♥ 4♥ A♣ 4♦ 7♠\n 3♠ T♦ 4♠ T♥ 8♥ 2♣ J♥ 7♦\n 6♦ 8♠ 8♦ Q♠ 6♣ 3♦ 8♣ T♣\n 6♠ 9♣ 2♥ 6♥\n show deal srnd 617\n 7♦ A♦ 5♣ 3♠ 5♠ 8♣ 2♦ A♥\n T♦ 7♠ Q♦ A♣ 6♦ 8♥ A♠ K♥\n T♥ Q♣ 3♥ 9♦ 6♠ 8♦ 3♦ T♣\n K♦ 5♥ 9♠ 3♣ 8♠ 7♥ 4♦ J♠\n 4♣ Q♠ 9♣ 9♥ 7♣ 6♥ 2♣ 2♠\n 4♠ T♠ 2♥ 5♦ J♣ 6♣ J♥ Q♥\n J♦ K♠ K♣ 4♥\n", "language": "J" }, { "code": "import java.util.Arrays;\n\npublic class Shuffler {\n\t\n\tprivate int seed;\n\t\n\tprivate String[] deck = {\n\t\t\t\"AC\", \"AD\", \"AH\", \"AS\",\n\t\t\t\"2C\", \"2D\", \"2H\", \"2S\",\n\t\t\t\"3C\", \"3D\", \"3H\", \"3S\",\n\t\t\t\"4C\", \"4D\", \"4H\", \"4S\",\n\t\t\t\"5C\", \"5D\", \"5H\", \"5S\",\n\t\t\t\"6C\", \"6D\", \"6H\", \"6S\",\n\t\t\t\"7C\", \"7D\", \"7H\", \"7S\",\n\t\t\t\"8C\", \"8D\", \"8H\", \"8S\",\n\t\t\t\"9C\", \"9D\", \"9H\", \"9S\",\n\t\t\t\"TC\", \"TD\", \"TH\", \"TS\",\n\t\t\t\"JC\", \"JD\", \"JH\", \"JS\",\n\t\t\t\"QC\", \"QD\", \"QH\", \"QS\",\n\t\t\t\"KC\", \"KD\", \"KH\", \"KS\",\n\t};\n\t\n\tprivate int random() {\n\t\tseed = (214013 * seed + 2531011) & Integer.MAX_VALUE;\n\t\treturn seed >> 16;\n\t}\n\t\n\t//shuffled cards go to the end\n\tprivate String[] getShuffledDeck() {\n\t\tString[] deck = Arrays.copyOf(this.deck, this.deck.length);\n\t\tfor(int i = deck.length - 1; i > 0; i--) {\n\t\t\tint r = random() % (i + 1);\n\t\t\tString card = deck[r];\n\t\t\tdeck[r] = deck[i];\n\t\t\tdeck[i] = card;\n\t\t}\n\t\treturn deck;\n\t}\n\t\n\t//deal from end first\n\tpublic void dealGame(int seed) {\n\t\tthis.seed = seed;\n\t\tString[] shuffledDeck = getShuffledDeck();\n\t\tfor(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) {\n\t\t\tSystem.out.print(shuffledDeck[i]);\n\t\t\tif(count % 8 == 0) {\n\t\t\t\tSystem.out.println();\n\t\t\t} else {\n\t\t\t\tSystem.out.print(\" \");\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tShuffler s = new Shuffler();\n\t\ts.dealGame(1);\n\t\tSystem.out.println();\n\t\ts.dealGame(617);\n\t}\n\t\n}\n", "language": "Java" }, { "code": "\"use strict\";\n/*\n * Microsoft C Run-time-Library-compatible Random Number Generator\n * Copyright by Shlomi Fish, 2011.\n * Released under the MIT/X11 License\n * ( http://en.wikipedia.org/wiki/MIT_License ).\n * */\n/* This uses Joose 2.x-or-above, an object system for JavaScript - http://code.google.com/p/joose-js/ . */\n\nClass('MSRand', {\n has: {\n seed: { is: rw, },\n },\n methods: {\n rand: function() {\n this.setSeed((this.getSeed() * 214013 + 2531011) & 0x7FFFFFFF);\n return ((this.getSeed() >> 16) & 0x7fff);\n },\n max_rand: function(mymax) {\n return this.rand() % mymax;\n },\n shuffle: function(deck) {\n if (deck.length) {\n var i = deck.length;\n while (--i) {\n var j = this.max_rand(i+1);\n var tmp = deck[i];\n deck[i] = deck[j];\n deck[j] = tmp;\n }\n }\n return deck;\n },\n },\n});\n\n/*\n * Microsoft Windows Freecell / Freecell Pro boards generation.\n *\n * See:\n *\n * - http://rosettacode.org/wiki/Deal_cards_for_FreeCell\n *\n * - http://www.solitairelaboratory.com/mshuffle.txt\n *\n * Under MIT/X11 Licence.\n *\n * */\n\nfunction deal_ms_fc_board(seed) {\n var randomizer = new MSRand({ seed: seed });\n var num_cols = 8;\n\n var _perl_range = function(start, end) {\n var ret = [];\n\n for (var i = start; i <= end; i++) {\n ret.push(i);\n }\n\n return ret;\n };\n\n var columns = _perl_range(0, num_cols-1).map(function () { return []; });\n var deck = _perl_range(0, 4*13-1);\n\n randomizer.shuffle(deck);\n\n deck = deck.reverse()\n\n for (var i = 0; i < 52; i++) {\n columns[i % num_cols].push(deck[i]);\n }\n\n var render_card = function (card) {\n var suit = (card % 4);\n var rank = Math.floor(card / 4);\n\n return \"A23456789TJQK\".charAt(rank) + \"CDHS\".charAt(suit);\n }\n\n var render_column = function(col) {\n return \": \" + col.map(render_card).join(\" \") + \"\\n\";\n }\n\n return columns.map(render_column).join(\"\");\n}\n", "language": "JavaScript" }, { "code": "const rank = split(\"A23456789TJQK\", \"\")\nconst suit = split(\"♣♦♥♠\", \"\")\nconst deck = Vector{String}()\n\nconst mslcg = [0]\nrng() = (mslcg[1] = ((mslcg[1] * 214013 + 2531011) & 0x7fffffff)) >> 16\n\ninitdeck() = for r in rank, s in suit push!(deck, \"$r$s\") end\n\nfunction deal(num = rand(UInt,1)[1] % 32000 + 1)\n initdeck()\n mslcg[1] = num\n println(\"\\nGame # \", num)\n while length(deck) > 0\n choice = rng() % length(deck) + 1\n deck[choice], deck[end] = deck[end], deck[choice]\n print(\" \", pop!(deck), length(deck) % 8 == 4 ? \"\\n\" : \"\")\n end\nend\n\ndeal(1)\ndeal(617)\ndeal()\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nclass Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) {\n private var state = s\n\n fun nextInt(): Long {\n state = (a * state + c) % m\n return state / d\n }\n}\n\nconst val CARDS = \"A23456789TJQK\"\nconst val SUITS = \"♣♦♥♠\"\n\nfun deal(): Array<String?> {\n val cards = arrayOfNulls<String>(52)\n for (i in 0 until 52) {\n val card = CARDS[i / 4]\n val suit = SUITS[i % 4]\n cards[i] = \"$card$suit\"\n }\n return cards\n}\n\nfun game(n: Int) {\n require(n > 0)\n println(\"Game #$n:\")\n val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, n.toLong())\n val cards = deal()\n for (m in 52 downTo 1) {\n val index = (msc.nextInt() % m).toInt()\n val temp = cards[index]\n cards[index] = cards[m - 1]\n print(\"$temp \")\n if ((53 - m) % 8 == 0) println()\n }\n println(\"\\n\")\n}\n\nfun main(args: Array<String>) {\n game(1)\n game(617)\n}\n", "language": "Kotlin" }, { "code": "; Linear congruential random number generator\nmake \"_lcg_state 0\n\nto seed_lcg :seed\n make \"_lcg_state :seed\nend\n\nto sample_lcg\n make \"_lcg_state modulo sum product 214013 :_lcg_state 2531011 2147483648\n output int quotient :_lcg_state 65536\nend\n\n; FreeCell\nto card_from_number :number\n output word item sum 1 int quotient :number 4 \"A23456789TJQK item sum 1 modulo :number 4 \"CDHS\nend\n\nto generate_deal :number\n (local \"deck \"size \"index \"deal)\n seed_lcg :number\n make \"deck []\n repeat 52 [\n make \"deck lput difference # 1 :deck\n ]\n make \"deck listtoarray :deck\n make \"deal []\n repeat 52 [\n make \"size difference 53 #\n make \"index sum 1 modulo sample_lcg :size\n make \"deal lput item :index :deck :deal\n setitem :index :deck item :size :deck\n ]\n output :deal\nend\n\nto print_deal :number\n (local \"deal \"i \"j \"index)\n make \"deal generate_deal :number\n repeat 7 [\n make \"i difference # 1\n repeat (ifelse [equal? :i 6] 4 8) [\n make \"j difference # 1\n make \"index (sum 1 product :i 8 :j)\n type (word (card_from_number item :index :deal) \"| |)\n ]\n print \"||\n ]\nend\n\nprint [Game #1]\nprint_deal 1\nprint \"||\nprint [Game #617]\nprint_deal 617\nprint \"||\nbye\n", "language": "Logo" }, { "code": "deck = {}\nrank = {\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"T\", \"J\", \"Q\", \"K\"}\nsuit = {\"C\", \"D\", \"H\", \"S\"}\ntwo31, state = bit32.lshift(1, 31), 0\n\nfunction rng()\n state = (214013 * state + 2531011) % two31\n return bit32.rshift(state, 16)\nend\n\nfunction initdeck()\n for i, r in ipairs(rank) do\n for j, s in ipairs(suit) do\n table.insert(deck, r .. s)\n end\n end\nend\n\nfunction deal(num)\n initdeck()\n state = num\n print(\"Game #\" .. num)\n repeat\n choice = rng(num) % #deck + 1\n deck[choice], deck[#deck] = deck[#deck], deck[choice]\n io.write(\" \" .. deck[#deck])\n if (#deck % 8 == 5) then\n print()\n end\n deck[#deck] = nil\n until #deck == 0\n print()\nend\n\ndeal(1)\ndeal(617)\n", "language": "Lua" }, { "code": "next[last_] := Mod[214013 last + 2531011, 2^31];\ndeal[n_] :=\n Module[{last = n, idx,\n deck = StringJoin /@\n Tuples[{{\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"T\", \"J\",\n \"Q\", \"K\"}, {\"C\", \"D\", \"H\", \"S\"}}], res = {}},\n While[deck != {}, last = next[last];\n idx = Mod[BitShiftRight[last, 16], Length[deck]] + 1;\n deck = ReplacePart[deck, {idx -> deck[[-1]], -1 -> deck[[idx]]}];\n AppendTo[res, deck[[-1]]]; deck = deck[[;; -2]]]; res];\nformat[deal_] := Grid[Partition[deal, 8, 8, {1, 4}, Null]];\nPrint[format[deal[1]]];\nPrint[format[deal[617]]];\n", "language": "Mathematica" }, { "code": "import sequtils, strutils, os\n\nproc randomGenerator(seed: int): iterator: int =\n var state = seed\n return iterator: int =\n while true:\n state = (state * 214013 + 2531011) and int32.high\n yield state shr 16\n\nproc deal(seed: int): seq[int] =\n const nc = 52\n result = toSeq countdown(nc - 1, 0)\n var rnd = randomGenerator seed\n for i in 0 ..< nc:\n let r = rnd()\n let j = (nc - 1) - r mod (nc - i)\n swap result[i], result[j]\n\nproc show(cards: seq[int]) =\n var l = newSeq[string]()\n for c in cards:\n l.add \"A23456789TJQK\"[c div 4] & \"CDHS\"[c mod 4]\n for i in countup(0, cards.high, 8):\n echo \" \", l[i..min(i+7, l.high)].join(\" \")\n\nlet seed = if paramCount() == 1: paramStr(1).parseInt else: 11982\necho \"Hand \", seed\nlet deck = deal seed\nshow deck\n", "language": "Nim" }, { "code": "class FreeCell {\n function : Main(args : String[]) ~ Nil {\n Deal(1)->PrintLine();\n Deal(617)->PrintLine();\n }\n\n function : Deal(seed : Int) ~ String {\n deck := Deck->New(seed)->ToString();\n return \"Game #{$seed}:\\n{$deck}\\n\";\n }\n}\n\nclass Deck {\n @cards : Card[];\n\n New(seed : Int) {\n r := Random->New(seed);\n\n @cards := Card->New[52];\n for(i := 0; i < 52; i+= 1;) {\n @cards[i] := Card->New(51 - i);\n };\n\n for(i := 0; i < 51; i += 1;) {\n j := 51 - r->Next() % (52 - i);\n tmp := @cards[i]; @cards[i] := @cards[j]; @cards[j] := tmp;\n };\n }\n\n method : public : ToString() ~ String {\n buffer := \"\";\n\n each(i : @cards) {\n buffer += @cards[i]->ToString();\n buffer += (i % 8 = 7 ? \"\\n\" : \" \");\n };\n\n return buffer;\n }\n\n\n}\n\nclass Random {\n @seed : Int;\n\n New(seed : Int) {\n @seed := seed;\n }\n\n method : public : Next() ~ Int {\n @seed := (@seed * 214013 + 2531011) and Int->MaxSize();\n return @seed >> 16;\n }\n}\n\nclass Card {\n @value : Int;\n @suit : Int;\n\n New(value : Int) {\n @value := value / 4; @suit := value % 4;\n }\n\n method : public : ToString() ~ String {\n suits := \"♣♦♥♠\"; values := \"A23456789TJQK\";\n value := values->Get(@value); suit := suits->Get(@suit);\n return \"{$value}{$suit}\";\n }\n}\n", "language": "Objeck" }, { "code": "#define RMAX32 ((1U << 31) - 1)\n\n//--------------------------------------------------------------------\n\n@interface Rand : NSObject\n-(instancetype) initWithSeed: (int)seed;\n-(int) next;\n@property (nonatomic) long seed;\n@end\n\n@implementation Rand\n-(instancetype) initWithSeed: (int)seed {\n if ((self = [super init])) {\n self.seed = seed;\n }\n return self;\n}\n-(int) next {\n return (int) ((_seed = (_seed * 214013 + 2531011) & RMAX32) >> 16);\n}\n@end\n\n//--------------------------------------------------------------------\n\n@interface Card : NSObject\n-(instancetype) initWithSequence: (int)n;\n-(instancetype) initWithValue: (int)v suit: (int)s;\n@property (nonatomic) int value;\n@property (nonatomic) int suit;\n@end\n\n@implementation Card\n-(instancetype) initWithSequence: (int)n {\n return [self initWithValue:n/4 suit:n%4];\n}\n-(instancetype) initWithValue: (int)v suit: (int)s {\n if ((self = [super init])) {\n _value = v; _suit = s;\n }\n return self;\n}\n-(NSString *) description {\n static NSString * const kSuits = @\"♣♦♥♠\";\n static NSString * const kValues = @\"A23456789TJQK\";\n return [NSString stringWithFormat:@\"%C%C\",\n [kValues characterAtIndex:_value],\n [kSuits characterAtIndex:_suit]];\n}\n@end\n\n//--------------------------------------------------------------------\n\n@interface Deck : NSObject\n-(instancetype) initWithSeed: (int)seed;\n@property (nonatomic, strong) NSMutableArray *cards;\n@end\n\n@implementation Deck\n-(instancetype) initWithSeed: (int)seed {\n if ((self = [super init])) {\n Rand *r = [[Rand alloc] initWithSeed:seed];\n _cards = [NSMutableArray array];\n for (int i = 0; i < 52; i++)\n [_cards addObject:[[Card alloc] initWithSequence:51 - i]];\n for (int i = 0; i < 51; i++)\n [_cards exchangeObjectAtIndex:i withObjectAtIndex:51 - [r next] % (52 - i)];\n }\n return self;\n}\n-(NSString *) description {\n NSMutableString *s = [NSMutableString string];\n for (int i = 0; i < [_cards count]; i++) {\n [s appendString:[_cards[i] description]];\n [s appendString:i%8==7 ? @\"\\n\" : @\" \"];\n }\n return s;\n}\n@end\n\n//--------------------------------------------------------------------\n\nint main(int argc, const char * argv[])\n{\n @autoreleasepool {\n NSLog(@\"Deck 1\\n%@\\n\", [[Deck alloc] initWithSeed:1]);\n NSLog(@\"Deck 617\\n%@\\n\", [[Deck alloc] initWithSeed:617]);\n }\n return 0;\n}\n", "language": "Objective-C" }, { "code": "let srnd x =\n (* since OCaml's built-in int type is at least 31 (note: not 32) bits wide,\n and this problem takes mod 2^31, it is just enough if we treat it as\n an unsigned integer, which means taking the logical right shift *)\n let seed = ref x in\n fun () ->\n seed := (!seed * 214013 + 2531011) land 0x7fffffff;\n !seed lsr 16\n\nlet deal s =\n let rnd = srnd s in\n let t = Array.init 52 (fun i -> i) in\n let cards =\n Array.init 52 (fun j ->\n let n = 52 - j in\n let i = rnd() mod n in\n let this = t.(i) in\n t.(i) <- t.(pred n);\n this)\n in\n (cards)\n\nlet show cards =\n let suits = \"CDHS\"\n and nums = \"A23456789TJQK\" in\n Array.iteri (fun i card ->\n Printf.printf \"%c%c%c\"\n nums.[card / 4]\n suits.[card mod 4]\n (if (i mod 8) = 7 then '\\n' else ' ')\n ) cards;\n print_newline()\n\nlet () =\n let s =\n try int_of_string Sys.argv.(1)\n with _ -> 11982\n in\n Printf.printf \"Deal %d:\\n\" s;\n let cards = deal s in\n show cards\n", "language": "OCaml" }, { "code": "card(n)=concat([\"A\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"T\",\"J\",\"Q\",\"K\"][n\\4+1],[\"C\",\"D\",\"H\",\"S\"][n%4+1]);\nnextrand()={\n (state=(214013*state+2531011)%2^31)>>16\n};\ndeal(seed)={\n my(deck=vector(52,n,n-1),t);\n local(state=seed);\n forstep(last=52,1,-1,\n t=nextrand()%last+1;\n print1(card(deck[t]),if(last%8==5,\"\\n\",\" \"));\n deck[t]=deck[last]\n )\n};\n", "language": "PARI-GP" }, { "code": "#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse utf8;\n\nsub deal {\n my $s = shift;\n\n my $rnd = sub {\n return (($s = ($s * 214013 + 2531011) & 0x7fffffff) >> 16 );\n };\n\n my @d;\n for my $b (split \"\", \"A23456789TJQK\") {\n push @d, map(\"$_$b\", qw/♣ ♦ ♥ ♠/);\n }\n\n for my $idx (reverse 0 .. $#d) {\n my $r = $rnd->() % ($idx + 1);\n @d[$r, $idx] = @d[$idx, $r];\n }\n\n return [reverse @d];\n}\n\nmy $hand_idx = shift(@ARGV) // 11_982;\n\nmy $cards = deal($hand_idx);\n\nmy $num_cards_in_height = 8;\nmy $string = '';\n\nwhile (@$cards)\n{\n $string .= join(' ', splice(@$cards, 0, 8)) . \"\\n\";\n}\n\nbinmode STDOUT, ':encoding(utf-8)';\nprint \"Hand $hand_idx\\n\";\nprint $string;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">seed</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">xrnd</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">seed</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">and_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">seed</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">214013</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2531011</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">#7FFFFFFF</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">seed</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">cards</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">52</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">deal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">game_num</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">seed</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">game_num</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">52</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">cards</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">52</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">i</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">51</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">j</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">52</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xrnd</span><span style=\"color: #0000FF;\">(),</span><span style=\"color: #000000;\">53</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">cards</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">cards</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">cards</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">cards</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">suits</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"CDHS\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">ranks</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"A23456789TJQK\"</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">show</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">idx</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">52</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">rank</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cards</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">idx</span><span style=\"color: #0000FF;\">]/</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">suit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cards</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">idx</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">eol</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">idx</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">13</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">12</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%c%c%s\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">ranks</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">rank</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">suits</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">suit</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">eol</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">game_num</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000080;font-style:italic;\">--integer game_num=617</span>\n <span style=\"color: #000000;\">deal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">game_num</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"hand %d\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">game_num</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">show</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "class FreeCell_Deal {\n\n protected $deck = array(\n 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S',\n '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S',\n '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S',\n 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS',\n 'KC', 'KD', 'KH', 'KS'\n );\n\n protected $game; // Freecell Game Number\n protected $state; // Current state of the LCG\n\n public $deal = array(); // Generated card sequence to deal\n\n function __construct( $game ) {\n\n $this->game = max( min( $game, 32000 ), 1 );\n\n // seed RNG with game number\n $this->state = $this->game;\n\n while ( ! empty( $this->deck ) ) {\n\n // choose random card\n $i = $this->lcg_rnd() % count( $this->deck );\n\n // move random card to game deal pile\n $this->deal[] = $this->deck[ $i ];\n\n // move last card to random card spot\n $this->deck[ $i ] = end( $this->deck );\n\n // remove last card from deck\n array_pop( $this->deck );\n\n }\n\n }\n\n protected function lcg_rnd() {\n return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16;\n }\n\n function print( $cols = 8 ) {\n echo str_pad( \" Game \" . $this->game . \" \", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL;\n foreach ( array_chunk( $this->deal, $cols ) as $row ) {\n echo implode( \" \", $row ), PHP_EOL;\n }\n echo PHP_EOL;\n }\n\n}\n\n$tests = array( 1, 617, 11982 );\n\nforeach ( $tests as $game_num ) {\n $deal = new FreeCell_Deal( $game_num );\n $deal->print();\n}\n", "language": "PHP" }, { "code": "(setq *MsSeed 11982)\n\n(de msRand ()\n (>> 16\n (setq *MsSeed\n (& (+ 2531011 (* 214013 *MsSeed)) `(dec (** 2 31))) ) ) )\n\n(let L\n (make\n (for Num (range 13 1)\n (for Suit '((32 . \"♠\") (31 . \"♥\") (31 . \"♦\") (32 . \"♣\"))\n (link (cons (get '`(chop \"A23456789TJQK\") Num) Suit)) ) ) )\n (for I 51\n (xchg\n (nth L I)\n (nth L (- 52 (% (msRand) (- 53 I)))) ) )\n (for C L\n (prin \" ^[[\" (cadr C) \"m\" (cddr C) \"^[[m\" (car C))\n (at (0 . 8) (prinl)) )\n (prinl) )\n", "language": "PicoLisp" }, { "code": "#MaxCardNum = 51 ;zero-based count of cards in a deck\nGlobal deckSize\nGlobal Dim cards(#MaxCardNum) ;card with highest index is at the top of deck\n\nProcedure RNG(seed.q = -1)\n Static state.q\n If seed >= 0\n state = seed\n Else\n state = (state * 214013 + 2531011) % (1 << 31)\n ProcedureReturn state >> 16\n EndIf\nEndProcedure\n\nProcedure makeDeck(hand)\n Protected i, c\n For i = 0 To #MaxCardNum: cards(i) = i: Next\n\n RNG(hand) ;set seed value\n deckSize = #MaxCardNum\n While deckSize\n c = RNG() % (deckSize + 1)\n Swap cards(c), cards(deckSize)\n deckSize - 1\n Wend\n deckSize = #MaxCardNum\nEndProcedure\n\nProcedure showDeck(hand)\n Protected i, c\n PrintN(\"Hand #\" + Str(hand))\n makeDeck(hand)\n For i = 0 To #MaxCardNum\n c = cards(#MaxCardNum - i)\n Print(\" \" + Mid(\"A23456789TJQK\", (c / 4) + 1, 1) + Mid(\"CDHS\",(c % 4) + 1, 1))\n If (i + 1) % 8 = 0 Or i = #MaxCardNum: PrintN(\"\"): EndIf\n Next\nEndProcedure\n\nIf OpenConsole()\n showDeck(1)\n showDeck(617)\n showDeck(11982)\n\n Print(#CRLF$ + #CRLF$ + \"Press ENTER to exit\"): Input()\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": "def randomGenerator(seed=1):\n max_int32 = (1 << 31) - 1\n seed = seed & max_int32\n\n while True:\n seed = (seed * 214013 + 2531011) & max_int32\n yield seed >> 16\n\ndef deal(seed):\n nc = 52\n cards = list(range(nc - 1, -1, -1))\n rnd = randomGenerator(seed)\n for i, r in zip(range(nc), rnd):\n j = (nc - 1) - r % (nc - i)\n cards[i], cards[j] = cards[j], cards[i]\n return cards\n\ndef show(cards):\n l = [\"A23456789TJQK\"[int(c/4)] + \"CDHS\"[c%4] for c in cards]\n for i in range(0, len(cards), 8):\n print(\" \".join(l[i : i+8]))\n\nif __name__ == '__main__':\n from sys import argv\n seed = int(argv[1]) if len(argv) == 2 else 11982\n print(\"Hand {}\".format(seed))\n deck = deal(seed)\n show(deck)\n", "language": "Python" }, { "code": " [ [ [] 52 times\n [ i^ join ] ]\n constant ] is newpack ( --> n )\n\n [ 2dup peek\n dip [ over -1 peek ]\n swap 2swap poke\n -1 poke ] is to-end ( [ n --> [ )\n\n [ [] swap\n 52 times\n [ MCR-rand\n over size mod\n to-end\n -1 split\n swap dip join ]\n drop ] is mixem ( [ --> [ )\n\n [ 4 /mod\n $ \"A23456789TJQK\"\n rot peek emit\n $ \"CDHS\"\n swap peek emit ] is echocard ( n --> )\n\n [ witheach\n [ echocard\n i^ 8 mod 7 =\n iff cr else sp ] ] is echopack ( [ --> )\n\n [ MCR-seed replace\n newpack\n mixem\n echopack ] is deal ( n --> )\n\n ' [ 1 617 11982 ]\n witheach\n [ say \"Deal #\"\n dup echo cr\n deal cr cr ]\n", "language": "Quackery" }, { "code": "## Linear congruential generator code not original -\n## copied from\n## http://www.rosettacode.org/wiki/Linear_congruential_generator#R\n## altered to allow seed as an argument\n\nlibrary(gmp) # for big integers\n\nrand_MS <- function(n = 1, seed = 1) {\n a <- as.bigz(214013)\n c <- as.bigz(2531011)\n m <- as.bigz(2^31)\n x <- rep(as.bigz(0), n)\n x[1] <- (a * as.bigz(seed) + c) %% m\n i <- 1\n while (i < n) {\n x[i+1] <- (a * x[i] + c) %% m\n i <- i + 1\n }\n as.integer(x / 2^16)\n}\n\n## =============================\n## New code follows:\n## =============================\n\ndealFreeCell <- function(seedNum) {\n deck <- paste(rep(c(\"A\",2,3,4,5,6,7,8,9,10,\"J\",\"Q\",\"K\"), each = 4), c(\"C\",\"D\",\"H\",\"S\"), sep = \"\")\n cards = rand_MS(52,seedNum)\n\n for (i in 52:1) {\n cardToPick <- (cards[53-i]%% i)+1 # R indexes from 1, not 0\n deck[c(cardToPick,i)] <- deck[c(i, cardToPick)]\n }\n\n deck <- rev(deck) # flip the deck to deal\n deal = matrix(c(deck,NA,NA,NA,NA),ncol = 8, byrow = TRUE)\n # using a matrix for simple printing, but requires filling with NA\n # if implementing as a game, a list for each pile would make more sense\n print(paste(\"Hand numer:\",seedNum), quote = FALSE)\n print(deal, quote = FALSE, na.print = \"\")\n}\n", "language": "R" }, { "code": "#lang racket\n\n(module Linear_congruential_generator racket\n ;; taken from http://rosettacode.org/wiki/Linear_congruential_generator#Racket\n ;; w/o BSD generator\n (require racket/generator)\n (provide ms-rand)\n (define (ms-update state_n)\n (modulo (+ (* 214013 state_n) 2531011)\n (expt 2 31)))\n (define ((rand update ->rand) seed)\n (generator () (let loop ([state_n seed])\n (define state_n+1 (update state_n))\n (yield (->rand state_n+1))\n (loop state_n+1))))\n (define ms-rand (rand ms-update (lambda (x) (quotient x (expt 2 16))))))\n\n(require (submod \".\" Linear_congruential_generator))\n\n;; Personally I prefer CDHS to the unicode characters (on an aesthetic basis,\n;; rather than anything else. Plus it helps match with the examples given at the\n;; head of the task.\n(define suits \"CDHS\")\n(define (initial-deck)\n (for*/vector #:length 52\n ((face \"A23456789TJQK\")\n (suit suits))\n (cons face suit)))\n\n;; srfi/43 has one of these, but is quick enough to reimplement!\n(define (vector-swap! v i j)\n (let ((t (vector-ref v i)))\n (vector-set! v i (vector-ref v j))\n (vector-set! v j t)))\n\n(define (deal hand)\n (define pack (initial-deck))\n (define rnd (ms-rand hand))\n (define (deal-nth-card pack-sz card-no deal)\n (vector-swap! pack card-no (sub1 pack-sz))\n (cons (vector-ref pack (sub1 pack-sz)) deal))\n\n (let inner-deal ((pack-sz (vector-length pack)) (deal null))\n (if (zero? pack-sz) (reverse deal) ;; we accumulated this backwards!\n (inner-deal (sub1 pack-sz)\n (deal-nth-card pack-sz (modulo (rnd) pack-sz) deal)))))\n\n(define (present-deal hand)\n (printf \"Game #~a~%\" hand)\n (let inner-present-deal ((pile 0) (deck (deal hand)))\n (unless (null? deck)\n (printf \"~a~a~a\" (caar deck) (cdar deck)\n (if (or (null? (cdr deck)) (= 7 (modulo pile 8))) \"\\n\" \" \"))\n (inner-present-deal (add1 pile) (cdr deck)))))\n\n;; Run it so we get some output:\n(present-deal 1)\n(newline)\n(present-deal 617)\n", "language": "Racket" }, { "code": "sub dealgame ($game-number = 1) {\n sub ms-lcg-method($seed = $game-number) { ( 214013 * $seed + 2531011 ) % 2**31 }\n\n # lazy list of the random sequence\n my @ms-lcg = |(&ms-lcg-method ... *).map: * +> 16;\n\n constant CardBlock = '🂠'.ord;\n my @deck = gather for flat(1..11,13,14) X+ (48,32...0) -> $off {\n take chr CardBlock + $off;\n }\n\n my @game = gather while @deck {\n @deck[@ms-lcg.shift % @deck, @deck-1] .= reverse;\n take @deck.pop;\n }\n\n say \"Game #$game-number\";\n say @game.splice(0, 8 min +@game) while @game;\n}\n\ndealgame;\ndealgame 617;\n", "language": "Raku" }, { "code": "/*REXX program deals cards for a specific FreeCell solitaire card game (0 ──► 32767).*/\nnumeric digits 15 /*ensure enough digits for the random #*/\nparse arg game cols . /*obtain optional arguments from the CL*/\nif game=='' | game==\",\" then game=1 /*No game specified? Then use default.*/\nif cols=='' | cols==\",\" then cols=8 /* \" cols \" \" \" \" */\nstate=game /*seed random # generator with game num*/\nif 8=='f8'x then suit= \"cdhs\" /*EBCDIC? Then use letters for suits.*/\n else suit= \"♣♦♥♠\" /* ASCII? \" \" symbols \" \" */\nrank= 'A23456789tJQK' /*t in the rank represents a ten (10).*/\npad=left('', 13) /*used for indentation for the tableau.*/\nsay center('tableau for FreeCell game' game, 50, \"─\") /*show title for FreeCell game #*/\nsay /* [↓] @ is an array of all 52 cards.*/\n#=-1; do r=1 for length(rank) /*build the deck first by the rank. */\n do s=1 for length(suit); #=#+1 /* \" \" \" secondly \" \" suit. */\n @.#=substr(rank, r,1)substr(suit, s,1) /*build the $ array one card at at time*/\n end /*s*/ /* [↑] first card is number 0 (zero).*/\n end /*r*/ /* [↑] build deck per FreeCell rules. */\n$=pad /*@: cards to be dealt, eight at a time*/\n do cards=51 by -1 for 52 /* [↓] deal the cards for the tableau.*/\n ?=rand() // (cards+1) /*get next rand#; card # is remainder.*/\n $=$ @.?; @[email protected] /*swap two cards: use random and last.*/\n if words($)==cols then do; say $; $=pad /*deal FreeCell cards for the tableau. */\n end\n end /*cards*/ /*normally, 8 cards are dealt to a row.*/\n /* [↓] residual cards may exist. */\nif $\\='' then say $ /*Any residual cards in the tableau ? */\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nrand: state=(214013*state + 2531011) // 2**31; return state % 2**16 /*FreeCell rand#*/\n", "language": "REXX" }, { "code": "# games = ARGV converted to Integer\n# No arguments? Pick any of first 32000 games.\nbegin\n games = ARGV.map {|s| Integer(s)}\nrescue => err\n $stderr.puts err.inspect\n $stderr.puts \"Usage: #{__FILE__} number...\"\n abort\nend\ngames.empty? and games = [rand(32000)]\n\n# Create original deck of 52 cards, not yet shuffled.\norig_deck = %w{A 2 3 4 5 6 7 8 9 T J Q K}.product(%w{C D H S}).map(&:join)\n\ngames.each do |seed|\n deck = orig_deck.dup\n\n # Shuffle deck with random index from linear congruential\n # generator like Microsoft.\n state = seed\n 52.downto(2) do |len|\n state = ((214013 * state) + 2531011) & 0x7fff_ffff\n index = (state >> 16) % len\n last = len - 1\n deck[index], deck[last] = deck[last], deck[index]\n end\n\n deck.reverse! # Shuffle did reverse deck. Do reverse again.\n\n # Deal cards.\n puts \"Game ##{seed}\"\n deck.each_slice(8) {|row| puts \" \" + row.join(\" \")}\n puts\nend\n", "language": "Ruby" }, { "code": "projectDir$\t= \"a_project\" ' project directory\nimageDir$ \t= DefaultDir$ + \"\\projects\\\" + projectDir$ + \"\\image\\\" ' directory of deck images\nimagePath$\t= \"../\";projectDir$;\"/image/\" ' path of deck images\n\nsuite$ = \"C,D,H,S\" ' Club,Diamond,Heart,Spades\ncard$ = \"A,2,3,4,5,6,7,8,9,T,J,Q,K\" ' Cards Ace to King\n\ndim n(55) ' make ordered deck\nfor i = 1 to 52 ' of 52 cards\n n(i) \t= i\nnext i\n\nfor i = 1 to 52 * 3 ' shuffle deck 3 times\n i1 = int(rnd(1)*52) + 1\n i2 = int(rnd(1)*52) + 1\n h2 = n(i1)\n n(i1) = n(i2)\n n(i2) = h2\nnext i\n\nfor yy = 1 to 8 ' display 7 across and 8 down\n for xx = 1 to 7\n card = card + 1\n s = (n(card) mod 4) + 1 ' determine suite\n c = (n(card) mod 13) + 1 ' determine card\n cardId$ = word$(card$,c,\",\");word$(suite$,s,\",\");\".gif\"\n html \"<div style='position: relative; left:\";(xx -1) * 80;\"px; top:\";(yy -1) * 20;\"px; height:0px; width:0px;>\"\n html \"<div style='width:100px; height:100px; border:solid 0px #000;'>\"\n html \"<img src=\";imagePath$;cardId$;\" width=70px >\"\n html \"</div></div>\"\n if card = 52 then end ' out of cards\n next xx\nnext yy\n", "language": "Run-BASIC" }, { "code": "// Code available at https://rosettacode.org/wiki/Linear_congruential_generator#Rust\nextern crate linear_congruential_generator;\n\nuse linear_congruential_generator::{MsLcg, Rng, SeedableRng};\n\n// We can't use `rand::Rng::shuffle` because it uses the more uniform `rand::Rng::gen_range`\n// (`% range` is subject to modulo bias). If an exact match of the old dealer is not needed,\n// `rand::Rng::shuffle` should be used.\nfn shuffle<T>(rng: &mut MsLcg, deck: &mut [T]) {\n let len = deck.len() as u32;\n for i in (1..len).rev() {\n let j = rng.next_u32() % (i + 1);\n deck.swap(i as usize, j as usize);\n }\n}\n\nfn gen_deck() -> Vec<String> {\n const RANKS: [char; 13] = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'];\n const SUITS: [char; 4] = ['C', 'D', 'H', 'S'];\n\n let render_card = |card: usize| {\n let (suit, rank) = (card % 4, card / 4);\n format!(\"{}{}\", RANKS[rank], SUITS[suit])\n };\n\n (0..52).map(render_card).collect()\n}\n\nfn deal_ms_fc_board(seed: u32) -> Vec<String> {\n let mut rng = MsLcg::from_seed(seed);\n let mut deck = gen_deck();\n\n shuffle(&mut rng, &mut deck);\n deck.reverse();\n\n deck.chunks(8).map(|row| row.join(\" \")).collect::<Vec<_>>()\n}\n\nfn main() {\n let seed = std::env::args()\n .nth(1)\n .and_then(|n| n.parse().ok())\n .expect(\"A 32-bit seed is required\");\n\n for row in deal_ms_fc_board(seed) {\n println!(\": {}\", row);\n }\n}\n", "language": "Rust" }, { "code": "object Shuffler extends App {\n\n private val suits = Array(\"C\", \"D\", \"H\", \"S\")\n private val values = Array(\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"T\", \"J\", \"Q\", \"K\")\n private val deck = values.flatMap(v => suits.map(s => s\"$v$s\"))\n\n private var seed: Int = _\n\n private def random() = {\n seed = (214013 * seed + 2531011) & Integer.MAX_VALUE\n seed >> 16\n }\n\n private def getShuffledDeck = {\n val d = deck.map(c => c)\n for(i <- deck.length - 1 until 0 by -1) {\n val r = random() % (i + 1)\n val card = d(r)\n d(r) = d(i)\n d(i) = card\n }\n d.reverse\n }\n\n def deal(seed: Int): Unit = {\n this.seed = seed\n getShuffledDeck.grouped(8).foreach(e => println(e.mkString(\" \")))\n }\n\n deal(1)\n println\n deal(617)\n}\n", "language": "Scala" }, { "code": "$ include \"seed7_05.s7i\";\n include \"console.s7i\";\n\nconst string: suits is \"♣♦♥♠\";\nconst string: nums is \"A23456789TJQK\";\n\nvar integer: randomSeed is 1;\n\nconst func integer: random is func\n result\n var integer: rand is 1;\n begin\n randomSeed := (randomSeed * 214013 + 2531011) mod 2 ** 31;\n rand := randomSeed >> 16;\n end func;\n\nconst proc: show (in array integer: cards) is func\n local\n var integer: index is 0;\n begin\n for index range 1 to 52 do\n write(\" \" <& suits[succ(cards[index] rem 4)] <& nums[succ(cards[index] div 4)]);\n if index rem 8 = 0 or index = 52 then\n writeln;\n end if;\n end for;\n end func;\n\nconst func array integer: deal (in integer: gameNum) is func\n result\n var array integer: cards is 52 times 0;\n local\n var integer: i is 0;\n var integer: j is 0;\n var integer: s is 0;\n begin\n randomSeed := gameNum;\n for i range 1 to 52 do\n cards[i] := 52 - i;\n end for;\n for i range 1 to 51 do\n j := 52 - random mod (53 - i);\n s := cards[i];\n cards[i] := cards[j];\n cards[j] := s;\n end for;\n end func;\n\nconst proc: main is func\n local\n var integer: gameNum is 11982;\n var array integer: cards is 0 times 0;\n begin\n OUT := STD_CONSOLE;\n if length(argv(PROGRAM)) >= 1 then\n block\n gameNum := integer parse (argv(PROGRAM)[1]);\n exception\n catch RANGE_ERROR: noop;\n end block;\n end if;\n cards := deal(gameNum);\n writeln(\"Hand \" <& gameNum);\n show(cards);\n end func;\n", "language": "Seed7" }, { "code": "enum Suit : String, CustomStringConvertible, CaseIterable {\n case clubs = \"C\", diamonds = \"D\", hearts = \"H\", spades = \"S\"\n var description: String {\n return self.rawValue\n }\n}\nenum Rank : Int, CustomStringConvertible, CaseIterable {\n case ace=1, two, three, four, five, six, seven\n case eight, nine, ten, jack, queen, king\n var description: String {\n let d : [Rank:String] = [.ace:\"A\", .king:\"K\", .queen:\"Q\", .jack:\"J\", .ten:\"T\"]\n return d[self] ?? String(self.rawValue)\n }\n}\nstruct Card : CustomStringConvertible {\n let rank : Rank, suit : Suit\n var description : String {\n return String(describing:self.rank) + String(describing:self.suit)\n }\n init(rank:Rank, suit:Suit) {\n self.rank = rank; self.suit = suit\n }\n init(sequence n:Int) {\n self.init(rank:Rank.allCases[n/4], suit:Suit.allCases[n%4])\n }\n}\nstruct Deck : CustomStringConvertible {\n var cards = [Card]()\n init(seed:Int) {\n for i in (0..<52).reversed() {\n self.cards.append(Card(sequence:i))\n }\n struct MicrosoftLinearCongruentialGenerator {\n var seed : Int\n mutating func next() -> Int {\n self.seed = (self.seed * 214013 + 2531011) % (Int(Int32.max)+1)\n return self.seed >> 16\n }\n }\n var r = MicrosoftLinearCongruentialGenerator(seed: seed)\n for i in 0..<51 {\n self.cards.swapAt(i, 51-r.next()%(52-i))\n }\n }\n var description : String {\n var s = \"\"\n for (ix,c) in self.cards.enumerated() {\n s.write(String(describing:c))\n s.write(ix % 8 == 7 ? \"\\n\" : \" \")\n }\n return s\n }\n}\nlet d1 = Deck(seed: 1)\nprint(d1)\nlet d617 = Deck(seed: 617)\nprint(d617)\n", "language": "Swift" }, { "code": "proc rnd {{*r seed}} {\n upvar 1 ${*r} r\n expr {[set r [expr {($r * 214013 + 2531011) & 0x7fffffff}]] >> 16}\n}\nproc show cards {\n set suits {\\u2663 \\u2666 \\u2665 \\u2660}\n set values {A 2 3 4 5 6 7 8 9 T J Q K}\n for {set i 0} {$i < 52} {incr i} {\n\tset c [lindex $cards $i]\n\tputs -nonewline [format \" \\033\\[%dm%s\\033\\[m%s\" [expr {32-(1+$c)%4/2}] \\\n\t [lindex $suits [expr {$c % 4}]] [lindex $values [expr {$c / 4}]]]\n\tif {($i&7)==7 || $i==51} {puts \"\"}\n }\n}\nproc deal {seed} {\n for {set i 0} {$i < 52} {incr i} {lappend cards [expr {51 - $i}]}\n for {set i 0} {$i < 51} {incr i} {\n\tset j [expr {51 - [rnd]%(52-$i)}]\n\tset tmp [lindex $cards $i]\n\tlset cards $i [lindex $cards $j]\n\tlset cards $j $tmp\n }\n return $cards\n}\n\nif {![scan =[lindex $argv 0]= =%d= s] || $s <= 0} {\n set s 11982\n}\nset cards [deal $s]\nputs \"Hand $s\"\nshow $cards\n", "language": "Tcl" }, { "code": "test $# -gt 0 || set -- $((RANDOM % 32000))\nfor seed; do\n\tprint Game $seed:\n\n\t# Shuffle deck.\n\tdeck=({A,{2..9},T,J,Q,K}{C,D,H,S})\n\tfor i in {52..1}; do\n\t\t((seed = (214013 * seed + 2531011) & 0x7fffffff))\n\t\t((j = (seed >> 16) % i + 1))\n\t\tt=$deck[$i]\n\t\tdeck[$i]=$deck[$j]\n\t\tdeck[$j]=$t\n\tdone\n\n\t# Deal cards.\n\tprint -n ' '\n\tfor i in {52..1}; do\n\t\tprint -n ' '$deck[$i]\n\t\t((i % 8 == 5)) && print -n $'\\n '\n\tdone\n\tprint\ndone\n", "language": "UNIX-Shell" }, { "code": "class Lcg {\n construct new(a, c, m, d, s) {\n _a = a\n _c = c\n _m = m\n _d = d\n _s = s\n }\n\n nextInt() {\n _s = (_a * _s + _c) % _m\n return _s / _d\n }\n}\n\nvar CARDS = \"A23456789TJQK\"\nvar SUITS = \"♣♦♥♠\".toList\n\nvar deal = Fn.new {\n var cards = List.filled(52, null)\n for (i in 0...52) {\n var card = CARDS[(i/4).floor]\n var suit = SUITS[i%4]\n cards[i] = card + suit\n }\n return cards\n}\n\nvar game = Fn.new { |n|\n if (n.type != Num || !n.isInteger || n <= 0) {\n Fiber.abort(\"Game number must be a positive integer.\")\n }\n System.print(\"Game #%(n):\")\n var msc = Lcg.new(214013, 2531011, 1<<31, 1<<16, n)\n var cards = deal.call()\n for (m in 52..1) {\n var index = (msc.nextInt() % m).floor\n var temp = cards[index]\n cards[index] = cards[m - 1]\n System.write(\"%(temp) \")\n if ((53 - m) % 8 == 0) System.print()\n }\n System.print(\"\\n\")\n}\n\ngame.call(1)\ngame.call(617)\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes; \\intrinsic 'code' declarations\nstring 0; \\use zero-terminated string convention\nint RandState;\n\nfunc Rand; \\Random number in range 0 to 32767\n[RandState:= (214013*RandState + 2531011) & $7FFF_FFFF;\nreturn RandState >> 16;\n];\n\nint Card, Deck(52), Size;\nchar Suit, Rank;\n[RandState:= IntIn(8); \\seed RNG with number from command line\nfor Card:= 0 to 52-1 do Deck(Card):= Card; \\create array of 52 cards\nRank:= \"A23456789TJQK\";\nSuit:= \"CDHS\";\nSize:= 52;\nrepeat Card:= rem(Rand/Size); \\choose a random card\n ChOut(0, Rank(Deck(Card)/4)); \\deal it by showing it\n ChOut(0, Suit(rem(0)));\n if rem(Size/8)=5 then CrLf(0) else ChOut(0, ^ );\n Size:= Size-1; \\one less card in deck\n Deck(Card):= Deck(Size); \\replace dealt card with last card\nuntil Size = 0; \\all cards have been dealt\n]\n", "language": "XPL0" }, { "code": "var suits=T(0x1F0D1,0x1F0C1,0x1F0B1,0x1F0A1); //unicode 🃑,🃁,🂱,🂡\n\nvar seed=1; const RMAX32=(1).shiftLeft(31) - 1;\nfcn rnd{ (seed=((seed*214013 + 2531011).bitAnd(RMAX32))).shiftRight(16) }\n\nfcn game(n){\n seed=n;\n deck:=(0).pump(52,List,'wrap(n){ if(n>=44) n+=4; // I want JQK, not JCQ\n (suits[n%4] + n/4).toString(8) }).copy(); // int-->UTF-8\n [52..1,-1].pump(Void,'wrap(len){ deck.swap(len-1,rnd()%len); });\n deck.reverse();\n println(\"Game #\",n);\n foreach n in ([0..51,8]){ deck[n,8].concat(\" \").println(); }\n}\n\ngame(1);\ngame(617);\n", "language": "Zkl" } ]
Deal-cards-for-FreeCell
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Deceptive_numbers\n", "language": "00-META" }, { "code": "Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation '''R<sub>n</sub>''' symbolizes the repunit made up of '''n''' ones.\n\nEvery prime '''p''' larger than 5, evenly divides the repunit '''R<sub>p-1</sub>'''.\n\n\n;E.G.\n\nThe repunit '''R<sub>6</sub>''' is evenly divisible by '''7'''.\n\n<span style=font-size:125%;font-weight:bold;padding-left:3em;>111111 / 7 = 15873</span>\n\nThe repunit '''R<sub>42</sub>''' is evenly divisible by '''43'''.\n\n<span style=font-size:125%;font-weight:bold;padding-left:3em;>111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677</span>\n\nAnd so on.\n\n\nThere are composite numbers that also have this same property. They are often referred to as ''deceptive non-primes'' or ''deceptive numbers''.\n\n\nThe repunit '''R<sub>90</sub>''' is evenly divisible by the composite number '''91''' (=7*13).\n\n<div style=font-size:125%;font-weight:bold;padding-left:3em;>111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221</div>\n\n\n;Task \n\n* Find and show at least the first '''10 deceptive numbers'''; composite numbers '''n''' that evenly divide the repunit '''R<sub>n-1</sub>'''\n\n\n;See also\n\n;* [https://www.numbersaplenty.com/set/deceptive_number Numbers Aplenty - Deceptive numbers]\n;* [[oeis:A000864|OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}]]\n<br>\n\n\n", "language": "00-TASK" }, { "code": "BEGIN # find repunits (all digits are 1 ) such that R(n-1) is divisible by n and n is not prime #\n # R(n) is the nth repunit, so has n 1s #\n PR precision 8000 PR # set precision of LONG LONG INT, enough for up to R(8000) #\n PR read \"primes.incl.a68\" PR # include prime utilities #\n []BOOL prime = PRIMESIEVE 8000;\n LONG LONG INT repunit := 111 111; # n must be odd as all repunits are odd, the lowest odd #\n INT r count := 0; # non-prime is 9, so we start with repunit set to R(6) #\n FOR n FROM 9 BY 2 WHILE r count < 15 DO\n repunit *:= 100 +:= 11; # gets R(n-1) from R(n-3) #\n IF NOT prime[ n ] THEN\n IF repunit MOD n = 0 THEN\n # found non-prime n which divides R(n-1) #\n print( ( \" \", whole( n, 0 ) ) );\n r count +:= 1\n FI\n FI\n OD\nEND\n", "language": "ALGOL-68" }, { "code": "begin % find deceptive numbers - repunits R(n) evenly divisible by composite %\n % numbers and n+1; see the task talk page based on the second Wren sample %\n\n % returns true if n is an odd prime, false otherwise, uses trial division %\n logical procedure isOddPrime ( integer value n ) ;\n begin\n logical prime;\n integer f, f2, toNext;\n prime := true;\n f := 3;\n f2 := 9;\n toNext := 16; % note: ( 2n + 1 )^2 - ( 2n - 1 )^2 = 8n %\n while f2 <= n and prime do begin\n prime := n rem f not = 0;\n f := f + 2;\n f2 := toNext;\n toNext := toNext + 8\n end while_f2_le_n_and_prime ;\n prime\n end isOddPrime ;\n\n begin % -- task %\n integer n, count;\n count := 0;\n n := 47;\n while begin n := n + 2;\n count < 25\n end\n do begin\n if n rem 3 not = 0 and n rem 5 not = 0 and not isOddPrime( n ) then begin\n integer mp;\n mp := 10;\n for p := 2 until n - 1 do mp := ( mp * 10 ) rem n;\n if mp = 1 then begin\n count := count + 1;\n writeon( i_w := 5, s_w := 0, \" \", n );\n if count rem 10 = 0 then write()\n end if_mp_eq_1\n end if_have_a_candidate\n end while_count_lt_50\n end task\n\nend.\n", "language": "ALGOL-W" }, { "code": "#include <jambo.h>\n\n#prototype isdeceptive(_X_)\n#prototype modulepow(_X_,_Y_,_Z_)\n#synon _isdeceptive Isdeceptive\n#synon _modulepow ModulePow\n#define Breaking Goto(exit)\nMain\n i = 49, c=0\n Iterator ( ++i, #(c <> 10), \\\n Print only if ( Is deceptive 'i', Set 'i,\"\\n\"'; ++c ) )\nEnd\n\nSubrutines\n\nis deceptive ( n )\n x=7\n And( Bitand(n,1), And( Mod(n,3), Mod(n,5) )), do {\n Iterator( x+=6, #( (x*x) <= n ),\\\n #(!( (n%x) && (n%(x+4)) )), do{ \\\n Module Pow (10, Minus one(n), n), Is equal to '1', Breaking } )\n }\n Set '0'\n exit:\nReturn\n\nmodule pow(b, e, m)\n Loop for (p = 1, e, e >>= 1)\n Bitand(e, 1), do{ #( p = (p * b) % m ) }\n #( b = (b * b) % m )\n Next\nReturn (p)\n", "language": "Amazing-Hopper" }, { "code": "deceptive?: function [n][\n and? -> not? prime? n\n -> zero? (to :integer repeat \"1\" n-1) % n\n]\n\ncnt: 0\ni: 3\n\nwhile [cnt < 10][\n if deceptive? i [\n print i\n cnt: cnt + 1\n ]\n i: i + 2\n]\n", "language": "Arturo" }, { "code": "function modpow(b, e, m, r) {\n for (r = 1; e > 0; e = int(e / 2)) {\n if (e % 2 == 1)\n r = r * b % m\n b = b * b % m\n }\n return r\n}\n\nfunction is_pseudo(n, i, p, r) {\n if (modpow(10, n - 1, n) == 1) {\n r = int(sqrt(n))\n while ((p = primes[++i]) <= r)\n if (n % p == 0)\n return 1\n primes[++l] = n\n }\n return 0\n}\n\nBEGIN {\n primes[l = 1] = n = 7\n split(\"4 2 4 2 4 6 2 6\", wheel)\n\n do if (is_pseudo(n += wheel[i = i % 8 + 1])) {\n printf \" %u\", n\n ++c\n } while (c != 50)\n print\n}\n", "language": "AWK" }, { "code": "/* modular exponentiation */\ndefine p(b, e, m) {\n auto r\n for (r = 1; e > 0; e /= 2) {\n if (e % 2 == 1) r = r * b % m\n b = b * b % m\n }\n return(r)\n}\n\n/* cache for the primes found */\np[0] = 7\n\ndefine d(n) {\n auto i, p, r;\n if (p(10, n - 1, n) == 1) {\n for (r = sqrt(n); (p = p[i]) <= r; ++i) if (n % p == 0) return(1)\n p[++l] = n\n }\n return(0)\n}\n\n/* wheel to skip multiples of 2, 3, and 5 */\nw[0] = 4\nw[1] = 2\nw[2] = 4\nw[3] = 2\nw[4] = 4\nw[5] = 6\nw[6] = 2\nw[7] = 6\n\nfor (n = p[0]; c != 10; i = (i + 1) % 8) {\n if (d(n += w[i]) == 1) {\n n\n c += 1\n }\n}\n", "language": "Bc" }, { "code": "#include <inttypes.h>\n#include <stdio.h>\n\nuint32_t modpow(uint32_t b, uint32_t e, uint32_t m)\n{\n uint32_t p;\n for (p = 1; e; e >>= 1) {\n if (e & 1)\n p = (uint64_t)p * b % m;\n b = (uint64_t)b * b % m;\n }\n return p;\n}\n\nint is_deceptive(uint32_t n)\n{\n uint32_t x;\n if (n & 1 && n % 3 && n % 5 && modpow(10, n - 1, n) == 1) {\n for (x = 7; x * x <= n; x += 6) {\n if (!(n % x && n % (x + 4)))\n return 1;\n }\n }\n return 0;\n}\n\nint main(void)\n{\n uint32_t n = 49;\n unsigned int c;\n for (c = 0; c != 500; ++n) {\n if (is_deceptive(n)) {\n printf(\" %\" PRIu32, n);\n ++c;\n }\n }\n return 0;\n}\n", "language": "C" }, { "code": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nbool is_prime(int n) {\n if (n < 2)\n return false;\n if (n % 2 == 0)\n return n == 2;\n if (n % 3 == 0)\n return n == 3;\n for (int p = 5; p * p <= n; p += 4) {\n if (n % p == 0)\n return false;\n p += 2;\n if (n % p == 0)\n return false;\n }\n return true;\n}\n\nint main() {\n std::cout << \"First 100 deceptive numbers:\\n\";\n mpz_class repunit = 11;\n for (int n = 3, count = 0; count != 100; n += 2) {\n if (n % 3 != 0 && n % 5 != 0 && !is_prime(n) &&\n mpz_divisible_ui_p(repunit.get_mpz_t(), n))\n std::cout << std::setw(6) << n << (++count % 10 == 0 ? '\\n' : ' ');\n repunit *= 100;\n repunit += 11;\n }\n}\n", "language": "C++" }, { "code": "#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n\nuint64_t power_modulus(uint64_t base, uint64_t exponent, const uint64_t& modulus) {\n\tif ( modulus == 1 ) {\n\t\treturn 0;\n\t}\n\n\tbase %= modulus;\n\tuint64_t result = 1;\n\twhile ( exponent > 0 ) {\n\t\tif ( ( exponent & 1 ) == 1 ) {\n\t\t\tresult = ( result * base ) % modulus;\n\t\t}\n\t\tbase = ( base * base ) % modulus;\n\t\texponent >>= 1;\n\t}\n\treturn result;\n}\n\nbool is_deceptive(const uint32_t& n) {\n\tif ( n % 2 != 0 && n % 3 != 0 && n % 5 != 0 && power_modulus(10, n - 1, n) == 1 ) {\n\t\tfor ( uint32_t divisor = 7; divisor < sqrt(n); divisor += 6 ) {\n\t\t\tif ( n % divisor == 0 || n % ( divisor + 4 ) == 0 ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nint main() {\n\tuint32_t n = 7;\n\tuint32_t count = 0;\n\twhile ( count < 100 ) {\n\t\tif ( is_deceptive(n) ) {\n\t\t\tstd::cout << std::setw(6) << n << ( ++count % 10 == 0 ? \"\\n\" : \" \" );\n\t\t}\n\t\tn += 1;\n\t}\n}\n", "language": "C++" }, { "code": "func modpow b e m .\n r = 1\n while e > 0\n if e mod 2 = 1\n r = r * b mod m\n .\n b = b * b mod m\n e = e div 2\n .\n return r\n.\nfunc is_deceptive n .\n if n mod 2 = 1 and n mod 3 <> 0 and n mod 5 <> 0\n if modpow 10 (n - 1) n = 1\n x = 7\n while x * x <= n\n if n mod x = 0 or n mod (x + 4) = 0\n return 1\n .\n x += 6\n .\n .\n .\n.\nwhile cnt < 10\n n += 1\n if is_deceptive n = 1\n write n & \" \"\n cnt += 1\n .\n.\n", "language": "EasyLang" }, { "code": "// Deceptive numbers. Nigel Galloway: February 13th., 2022\nSeq.unfold(fun n->Some(n|>Seq.filter(isPrime>>not)|>Seq.filter(fun n->(10I**(n-1)-1I)%(bigint n)=0I),n|>Seq.map((+)30)))(seq{1;7;11;13;17;19;23;29})|>Seq.concat|>Seq.skip 1\n|>Seq.chunkBySize 10|>Seq.take 7|>Seq.iter(fun n->n|>Array.iter(printf \"%7d \"); printfn \"\")\n", "language": "F-Sharp" }, { "code": "USING: io kernel lists lists.lazy math math.functions\nmath.primes prettyprint ;\n\n: repunit ( m -- n ) 10^ 1 - 9 / ;\n\n: composite ( -- list ) 4 lfrom [ prime? not ] lfilter ;\n\n: deceptive ( -- list )\n composite [ [ 1 - repunit ] keep divisor? ] lfilter ;\n\n10 deceptive ltake [ pprint bl ] leach nl\n", "language": "Factor" }, { "code": "Func Rep(n)=Sigma<m=0,n-1>[10^m].;\nc:=0;\nn:=3;\nwhile c<10 do\n n:=n+1;\n if Isprime(n)>1 and Divides(n,Rep(n-1)) then !!n; c:+; fi\nod;\n", "language": "Fermat" }, { "code": "program DeceptiveNumbers;\n{$IfDef FPC} {$Optimization ON,ALL} {$ENDIF}\n{$IfDef Windows} {$APPTYPE CONSOLE} {$ENDIF}\nuses\n sysutils;\nconst\n LIMIT = 100000;//1E6 at home takes over (5 min) now 1m10s\n RepInitLen = 13; //Uint64 19 decimal digits -> max 6 digits divisor\n DecimalDigits = 10*1000*1000*1000*1000;//1E13\n RepLimit = (DecimalDigits-1)DIV 9;//RepInitLen '1'\n\ntype\n tmyUint64 = array[0..Limit DIV RepInitLen+1] of Uint64;\nvar\n {$Align 32}\n K: tmyUint64;\n {$Align 32}\n MaxKIdx : Int32;\n\nprocedure OutK(const K:tmyUint64);\nvar\n i : Uint32;\nbegin\n For i := MaxKidx downto 0 do\n begin\n write(k[i]:13);\n end;\n writeln;\nend;\n\nfunction isPrime(n: UInt64):boolean;\nvar\n p: Uint64;\nbegin\n if n in [2,3,5,7,11,13,17,19,23,29] then\n EXIT(true);\n\n if Not ODD(n) OR ( n MOD 3 = 0) then\n EXIT(false);\n p := 5;\n repeat\n if (n mod p=0)or(n mod(p+2)=0) then\n EXIT(false);\n p +=6;\n until p*p>n;\n Exit(true);\nend;\n\nprocedure ExtendRep(var K:tmyUint64;n:NativeUint);\nvar\n q : Uint64;\n i : Int32;\nbegin\n n -= MaxKidx*RepInitLen;\n i := MaxKidx;\n while RepInitLen<=n do\n begin\n K[i] := RepLimit;\n inc(i);\n dec(n,RepInitLen);\n end;\n if n = 0 then\n Exit;\n MaxKidx := i;\n q := 1;\n while n<RepInitLen do\n begin\n q *= 10;\n inc(n);\n end;\n K[i] := RepLimit DIV q;\nend;\n\nfunction GetModK(const K:tmyUint64;n:Uint64):NativeUint;\nvar\n r,q : Uint64;\n i : Uint32;\nBegin\n r := 0;\n For i := MaxKidx downto 0 do\n begin\n q := K[i]+r*DecimalDigits;\n r := q MOD n;\n end;\n Exit(r)\nend;\n\nconst\n NextNotMulOF35 : array[0..7] of byte = (6,4,2,4,2,4,6,2);\nvar\n i,cnt,idx35 : UInt64;\nBEGIN\n fillchar(K,SizeOF(K),#0);\n MaxKIdx:= 0;\n cnt := 0;\n i := 1;\n idx35 := 0;\n repeat\n inc(i,NextNotMulOF35[idx35]);\n IF i > LIMIT then\n BREAK;\n idx35 := (idx35+1) AND 7;\n if isprime(i) then\n continue;\n ExtendRep(k,i-1);\n IF GetModK(K,i)=0 then\n Begin\n inc(cnt);\n write(i:6,',');\n if cnt Mod 10 = 0 then\n writeln;\n end;\n until false;\n {$IfDef Windows}\n readln;\n {$ENDIF}\nEND.\n", "language": "Free-Pascal-Lazarus" }, { "code": "Function ModPow(b As Uinteger, e As Uinteger, m As Uinteger) As Uinteger\n Dim As Uinteger p = 1\n While e <> 0\n If (e And 1) Then p = (p*b) Mod m\n b = (b*b) Mod m\n e Shr= 1\n Wend\n Return p\nEnd Function\n\nFunction isDeceptive(n As Uinteger) As Uinteger\n Dim As Uinteger x\n If (n And 1) <> 0 Andalso (n Mod 3) <> 0 Andalso (n Mod 5) <> 0 Then\n x = 7\n While x*x <= n\n If (n Mod x) = 0 Orelse (n Mod (x+4)) = 0 Then Return (ModPow(10, n-1, n) = 1)\n x += 6\n Wend\n End If\n Return 0\nEnd Function\n\nDim As Uinteger c = 0, i = 49\nWhile c <> 41 ' limit for signed 32-bit integers\n If isDeceptive(i) Then\n Print Using \"#######\"; Csng(i);\n c += 1\n If (c Mod 10) = 0 Then Print\n End If\n i += 1\nWend\n\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n \"rcu\"\n)\n\nfunc main() {\n count := 0\n limit := 25\n n := int64(17)\n repunit := big.NewInt(1111111111111111)\n t := new(big.Int)\n zero := new(big.Int)\n eleven := big.NewInt(11)\n hundred := big.NewInt(100)\n var deceptive []int64\n for count < limit {\n if !rcu.IsPrime(int(n)) && n%3 != 0 && n%5 != 0 {\n bn := big.NewInt(n)\n if t.Rem(repunit, bn).Cmp(zero) == 0 {\n deceptive = append(deceptive, n)\n count++\n }\n }\n n += 2\n repunit.Mul(repunit, hundred)\n repunit.Add(repunit, eleven)\n }\n fmt.Println(\"The first\", limit, \"deceptive numbers are:\")\n fmt.Println(deceptive)\n}\n", "language": "Go" }, { "code": "wheel=. 4 6 2 6 4 2 4 2\nfermat=. {{1 = 10 (y&|@^) <: y}}\"0\n\n_10 ]\\ (#~ fermat) (#~ 0&p:) +/\\ 49 , 15e4 $ wheel\n", "language": "J" }, { "code": "public final class DeceptiveNumbers {\n\n\tpublic static void main(String[] aArgs) {\n\t\tint n = 7;\n\t\tint count = 0;\n\t\twhile ( count < 100 ) {\n\t\t\tif ( isDeceptive(n) ) {\n\t\t\t\tSystem.out.print(String.format(\"%6d%s\", n, ( ++count % 10 == 0 ? \"\\n\" : \" \" )));\n\t\t\t}\n\t\t\tn += 1;\n\t\t}\n\t}\n\t\n\tprivate static boolean isDeceptive(int aN) {\n\t\tif ( aN % 2 != 0 && aN % 3 != 0 && aN % 5 != 0 && modulusPower(10, aN - 1, aN) == 1 ) {\n\t\t\tfor ( int divisor = 7; divisor < Math.sqrt(aN); divisor += 6 ) {\n\t\t\t\tif ( aN % divisor == 0 || aN % ( divisor + 4 ) == 0 ) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate static long modulusPower(long aBase, long aExponent, long aModulus) {\n\t if ( aModulus == 1 ) {\n\t return 0;\n\t }\t\n\t\n\t aBase %= aModulus;\n\t long result = 1;\n\t while ( aExponent > 0 ) {\n\t if ( ( aExponent & 1 ) == 1 ) {\n\t result = ( result * aBase ) % aModulus;\n\t }\n\t aBase = ( aBase * aBase ) % aModulus;\n\t aExponent >>= 1;\n\t }\n\t return result;\n\t}\n\t\n}\n", "language": "Java" }, { "code": "def is_prime:\n . as $n\n | if ($n < 2) then false\n elif ($n % 2 == 0) then $n == 2\n elif ($n % 3 == 0) then $n == 3\n elif ($n % 5 == 0) then $n == 5\n elif ($n % 7 == 0) then $n == 7\n elif ($n % 11 == 0) then $n == 11\n elif ($n % 13 == 0) then $n == 13\n elif ($n % 17 == 0) then $n == 17\n elif ($n % 19 == 0) then $n == 19\n else 23\n | until( (. * .) > $n or ($n % . == 0); .+2)\n\t| . * . > $n\n end;\n\n# Output: a stream\ndef deceptives:\n {nextrepunit: 1111111111111111}\n | foreach range(17; infinite; 2) as $n (.;\n .repunit = .nextrepunit\n | .nextrepunit |= . * 100 + 11;\n select( ($n | is_prime | not)\n and ($n % 3 != 0) and ($n % 5 != 0)\n and (.repunit % $n == 0 ))\n | $n );\n\n\"The first 25 deceptive numbers are:\", [limit(25;deceptives)]\n", "language": "Jq" }, { "code": "using Primes\n\nfunction deceptives(numwanted)\n n, r, ret = 2, big\"1\", Int[]\n while length(ret) < numwanted\n !isprime(n) && r % n == 0 && push!(ret, n)\n n += 1\n r = 10r + 1\n end\n return ret\nend\n\n@time println(deceptives(30))\n", "language": "Julia" }, { "code": "val .isPrime = fn(.i) .i == 2 or .i > 2 and\n not any fn(.x) .i div .x, pseries 2 .. .i ^/ 2\n\nvar .nums = []\nvar .repunit = 111_111\n\nfor .n = 9; len(.nums) < 10; .n += 2 {\n .repunit = .repunit * 100 + 11\n if not .isPrime(.n) and .repunit div .n {\n .nums = more .nums, .n\n }\n}\n\nwriteln .nums\n", "language": "Langur" }, { "code": "(defmodule deceptives\n (export (prime? 1) (deceptives 1)))\n\n(defun prime? (n)\n (if (< n 2)\n 'false\n (prime? n 2 0 #B(1 2 2 4 2 4 2 4 6 2 6))))\n\n(defun prime? (n d j wheel)\n (cond\n ((=:= j (byte_size wheel))\n (prime? n d 3 wheel))\n ((> (* d d) n)\n 'true)\n ((=:= 0 (rem n d))\n 'false)\n (else\n (prime? n (+ d (binary:at wheel j)) (+ j 1) wheel))))\n\n(defun deceptives (n)\n (deceptives 2 1 n '()))\n\n(defun deceptives\n ((_ _ 0 l)\n (lists:reverse l))\n ((k r n l)\n (if (andalso (not (prime? k)) (=:= 0 (rem r k)))\n (deceptives (+ k 1) (+ (* r 10) 1) (- n 1) (cons k l))\n (deceptives (+ k 1) (+ (* r 10) 1) n l))))\n", "language": "LFE" }, { "code": "do -- find deceptive numbers - repunits R(n) evenly divisible by composite numbers and n+1\n -- see tha task talk page based on the second Wren sample\n\n -- returns true if n is prime, false otherwise, uses trial division %\n local function isPrime ( n )\n if n < 3 then return n == 2\n elseif n % 3 == 0 then return n == 3\n elseif n % 2 == 0 then return false\n else\n local prime = true\n local f, f2, toNext = 5, 25, 24\n while f2 <= n and prime do\n prime = n % f ~= 0\n f = f + 2\n f2 = toNext\n toNext = toNext + 8\n end\n return prime\n end\n end\n\n do -- task\n local n, count = 47, 0\n while count < 25 do\n n = n + 2\n if n % 3 ~= 0 and n % 5 ~= 0 and not isPrime( n ) then\n local mp = 10\n for p = 2, n - 1 do mp = ( mp * 10 ) % n end\n if mp == 1 then\n count = count + 1\n io.write( string.format( \" %5d\", n ) )\n if count % 10 == 0 then io.write( \"\\n\" ) end\n end\n end\n end\n end\n\nend\n", "language": "Lua" }, { "code": "ClearAll[DeceptiveNumberQ]\nDeceptiveNumberQ[n_Integer] := If[! PrimeQ[n], PowerMod[10, n - 1, 9 n] == 1]\nc = 0;\nout = Reap[Do[\n If[DeceptiveNumberQ[i],\n Sow[i];\n c++;\n If[c >= 1000, Break[]]\n ]\n ,\n {i, 2, \\[Infinity]}\n ]][[2, 1]];\nPrint[\"The first 100:\"]\nMulticolumn[Take[out, 100], Appearance -> \"Horizontal\"]\nPrint[\"The 1000th is: \", out[[1000]]]\n", "language": "Mathematica" }, { "code": "/* Function for repunit numbers */\nrepunit(n):=(10^n-1)/9;\n\n/* Function that checks if property is satisfied */\nrepunit_property(n):=is(mod(repunit(n-1),n)=0);\n\n/* Function to list the first n deceptive numbers */\ndeceptive_list(n):=block([deceptives:[],count:0,i:5],\nwhile count<n do (if repunit_property(i) and not primep(i) then (push(i,deceptives),count:count+1),i:i+1),\nreverse(deceptives));\n", "language": "Maxima" }, { "code": "import std/[math, strutils]\n\nfunc pow(a, n: Natural; m: Positive): Natural =\n var a = a mod m\n var n = n\n if a > 0:\n result = 1\n while n > 0:\n if (n and 1) != 0:\n result = (result * a) mod m\n n = n shr 1\n a = (a * a) mod m\n\nfunc sqrt(n: Natural): Natural = Natural(sqrt(float(n)))\n\nfunc isDeceptive(n: Natural): bool =\n if (n and 1) != 0 and n mod 3 != 0 and n mod 5 != 0 and pow(10, n - 1, n) == 1:\n for d in countup(7, sqrt(n), 6):\n if n mod d == 0 or n mod (d + 4) == 0:\n return true\n result = false\n\nvar count = 0\nvar n = 7\nwhile true:\n if n.isDeceptive:\n inc count\n stdout.write align($n, 6)\n stdout.write if count mod 10 == 0: '\\n' else: ' '\n if count == 100: break\n inc n\n", "language": "Nim" }, { "code": "let modpow m =\n let rec loop p b e =\n if e land 1 = 0\n then if e = 0 then p else loop p (b * b mod m) (e lsr 1)\n else loop (p * b mod m) (b * b mod m) (e lsr 1)\n in loop 1\n\nlet is_deceptive n =\n let rec loop x =\n x * x <= n && (n mod x = 0 || n mod (x + 4) = 0 || loop (x + 6))\n in\n n land 1 <> 0 && n mod 3 <> 0 && n mod 5 <> 0 &&\n modpow n 10 (pred n) = 1 && loop 7\n\nlet () =\n Seq.(ints 49 |> filter is_deceptive |> take 100\n |> iter (Printf.printf \" %u%!\")) |> print_newline\n", "language": "OCaml" }, { "code": "Rep(n)=sum(X=0,n-1,10^X)\nc=0\nn=4\nwhile(c<10,if(!isprime(n)&&Rep(n-1)%n==0,c=c+1;print(n));n=n+1)\n", "language": "PARI-GP" }, { "code": "use strict;\nuse warnings;\nuse Math::AnyNum qw(imod is_prime);\n\nmy($x,@D) = 2;\nwhile ($x++) {\n push @D, $x if 1 == $x%2 and !is_prime $x and 0 == imod(1x($x-1),$x);\n last if 25 == @D\n}\nprint \"@D\\n\";\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">limit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">70</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">mpfr</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">repunit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_init</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"The first %d deceptive numbers are:\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">limit</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">limit</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000080;font-style:italic;\">-- No repunit is ever divisible by 2 or 5 since it ends in 1.\n -- If n is 3*k, sum(digits(repunit))=3*k-1, not divisible by 3.\n -- Hence only check odd and hop any multiples of 3 or 5.</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #7060A8;\">mpz_mul_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">repunit</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">repunit</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpz_add_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">repunit</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">repunit</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">gcd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">is_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">mpz_divisible_ui_p</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">repunit</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" %7d%n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">))</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">limit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">JS</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">1000</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">showlim</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">70</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">(),</span> <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"The first %d deceptive numbers are:\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">showlim</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">limit</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">gcd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">is_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">powmod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">showlim</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" %7d%n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">limit</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()></span><span style=\"color: #000000;\">t1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"The %d%s is %d\\r\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">ord</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n%s\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">))</span>\n<!--\n", "language": "Phix" }, { "code": "checkpair(1, 2).\ncheckpair(R, K) :-\n checkpair(R0, K0),\n R is 10*R0 + 1,\n K is K0 + 1.\n\ndeceptive(K) :-\n checkpair(R, K),\n \\+ prime(K),\n divmod(R, K, _, 0).\n\ntask(K, Ns) :-\n lazy_findall(N, deceptive(N), Ds),\n length(Ns, K),\n prefix(Ns, Ds).\n\n% check if a number is prime\n%\nwheel235(L) :-\n W = [4, 2, 4, 2, 4, 6, 2, 6 | W],\n L = [1, 2, 2 | W].\n\nprime(N) :-\n N >= 2,\n wheel235(W),\n prime(N, 2, W).\n\nprime(N, D, _) :- D*D > N, !.\nprime(N, D, [A|As]) :-\n N mod D =\\= 0,\n D2 is D + A, prime(N, D2, As).\n", "language": "Prolog" }, { "code": "from itertools import count, islice\nfrom math import isqrt\n\ndef is_deceptive(n):\n if n & 1 and n % 3 and n % 5 and pow(10, n - 1, n) == 1:\n for d in range(7, isqrt(n) + 1, 6):\n if not (n % d and n % (d + 4)): return True\n return False\n\nprint(*islice(filter(is_deceptive, count(49)), 100))\n", "language": "Python" }, { "code": "from itertools import accumulate, cycle, islice\nfrom math import isqrt\n\nprimes = []\nwheel = 4, 2, 4, 2, 4, 6, 2, 6\n\ndef is_pseudo(n):\n if pow(10, n - 1, n) == 1:\n s = isqrt(n)\n for p in primes:\n if p > s: break\n if n % p == 0: return True\n primes.append(n)\n return False\n\nprint(*islice(filter(is_pseudo, accumulate(cycle(wheel), initial=7)), 100))\n", "language": "Python" }, { "code": " [ 10 swap ** 1 - 9 / ] is rep ( n --> n )\n\n [] 0\n [ 2 + dup 1+ isprime if again\n dup rep over 1+ mod if again\n tuck 1+ join\n tuck size 20 = until ]\n drop echo\n", "language": "Quackery" }, { "code": "my \\R = [\\+] 1, 10, 100 … *;\nput (2..∞).grep( {$_ % 2 && $_ % 3 && $_ % 5 && !.is-prime} ).grep( { R[$_-2] %% $_ } )[^25];\n", "language": "Raku" }, { "code": "require 'prime'\n\ndeceptives = Enumerator.new do |y|\n 10.step(by: 10) do |n|\n [1,3,7,9].each do |digit|\n cand = n + digit\n next if cand % 3 == 0 || cand.prime?\n repunit = (\"1\"*(cand-1)).to_i\n y << cand if (repunit % cand) == 0\n end\n end\nend\n\np deceptives.take(25).to_a\n", "language": "Ruby" }, { "code": "// [dependencies]\n// primal = \"0.3\"\n// rug = \"1.15.0\"\n\nfn main() {\n println!(\"First 100 deceptive numbers:\");\n use rug::Integer;\n let mut repunit = Integer::from(11);\n let mut n: u32 = 3;\n let mut count = 0;\n while count != 100 {\n if n % 3 != 0 && n % 5 != 0 && !primal::is_prime(n as u64) && repunit.is_divisible_u(n) {\n print!(\"{:6}\", n);\n count += 1;\n if count % 10 == 0 {\n println!();\n } else {\n print!(\" \");\n }\n }\n n += 2;\n repunit *= 100;\n repunit += 11;\n }\n}\n", "language": "Rust" }, { "code": "(define prime?\n (let ((wheel '(1 2 2 . #1=(4 2 4 2 4 6 2 6 . #1#))))\n (lambda (n)\n (if (< n 2)\n #f\n (let loop ((f 2) (w wheel))\n (cond\n ((> (* f f) n) #t)\n ((zero? (remainder n f)) #f)\n (#t (loop (+ f (car w)) (cdr w)))))))))\n\n(define (deceptives n)\n (let loop ((k 2) (r 1) (n n) (l '()))\n (if (zero? n)\n (reverse! l)\n (if (and (not (prime? k)) (zero? (remainder r k)))\n (loop (+ k 1) (+ (* 10 r) 1) (- n 1) (cons k l))\n (loop (+ k 1) (+ (* 10 r) 1) n l)))))\n", "language": "Scheme" }, { "code": "say 100.by {|n|\n n.is_composite && (divmod(powmod(10, n-1, n)-1, 9, n) == 0)\n}.join(' ')\n", "language": "Sidef" }, { "code": "is () {\n return \"$((!($1)))\"\n}\n\nfermat_test () {\n set -- 1 \"$1\" \"$(($2 - 1))\" \"$2\"\n while is \"$3 > 0\"\n do\n set -- \"$(($1 * (-($3 & 1) & ($2 ^ 1) ^ 1) % $4))\" \"$(($2 * $2 % $4))\" \"$(($3 >> 1))\" \"$4\"\n done\n return \"$(($1 != 1))\"\n}\n\nset -- 7\nc=0 n=$1\nwhile :\ndo\n for w in 4 2 4 2 4 6 2 6\n do\n fermat_test 10 \"$((n += w))\" && for p\n do\n is 'p * p > n' && {\n set -- \"$@\" \"$n\"\n break\n }\n is 'n % p == 0' && {\n echo \"$n\"\n is '(c += 1) == 10' && exit\n break\n }\n done\n done\ndone\n", "language": "UNIX-Shell" }, { "code": "import math.big\n\nfn is_prime(n int) bool {\n if n < 2 {return false}\n\telse if n % 2 == 0 {return n == 2}\n\telse if n % 3 == 0 {return n == 3}\n\telse {\n mut d := 5\n for d * d <= n {\n if n % d == 0 {return false}\n d += 2\n if n % d == 0 {return false}\n d += 4\n }\n return true\n }\n}\n\nfn main() {\n mut count := 0\n limit := 25\n mut n := i64(17)\n mut repunit := big.integer_from_i64(1111111111111111)\n mut t := big.integer_from_int(0)\n zero := big.integer_from_int(0)\n eleven := big.integer_from_int(11)\n hundred := big.integer_from_int(100)\n mut deceptive := []i64{}\n for count < limit {\n if !is_prime(int(n)) && n % 3 != 0 && n % 5 != 0 {\n bn := big.integer_from_i64(n)\n t = repunit % bn\n if t == zero {\n deceptive << n\n count++\n }\n }\n n += 2\n repunit = repunit * hundred\n repunit = repunit + eleven\n }\n println(\"The first $limit deceptive numbers are:\")\n println(deceptive)\n}\n", "language": "V-(Vlang)" }, { "code": "/* Deceptive_numbers.wren */\n\nimport \"./gmp\" for Mpz\nimport \"./math\" for Int\n\nvar count = 0\nvar limit = 25\nvar n = 17\nvar repunit = Mpz.from(1111111111111111)\nvar deceptive = []\nwhile (count < limit) {\n if (!Int.isPrime(n) && n % 3 != 0 && n % 5 != 0) {\n if (repunit.isDivisibleUi(n)) {\n deceptive.add(n)\n count = count + 1\n }\n }\n n = n + 2\n repunit.mul(100).add(11)\n}\nSystem.print(\"The first %(limit) deceptive numbers are:\")\nSystem.print(deceptive)\n", "language": "Wren" }, { "code": "import \"./math\" for Int\n\nvar count = 0\nvar limit = 25 // or 62\nvar n = 49\nvar deceptive = []\nwhile (count < limit) {\n if (!Int.isPrime(n) && n % 3 != 0 && n % 5 != 0 && Int.modPow(10, n-1, n) == 1) {\n deceptive.add(n)\n count = count + 1\n }\n n = n + 2\n}\nSystem.print(\"The first %(limit) deceptive numbers are:\")\nSystem.print(deceptive)\n", "language": "Wren" }, { "code": "func ModPow(B, E, M);\nint B, E, M, P;\n[P:= 1;\nwhile E # 0 do\n [if E & 1 then\n P:= rem(P*B/M);\n B:= rem(B*B/M);\n E:= E >> 1;\n ];\nreturn P;\n];\n\nfunc IsDeceptive(N);\nint N, X;\n[if (N&1) # 0 and rem(N/3) # 0 and rem(N/5) # 0 then\n [X:= 7;\n while X*X <= N do\n [if rem(N/X) = 0 or rem(N/(X+4)) = 0 then\n return ModPow(10, N-1, N) = 1;\n X:= X + 6;\n ];\n ];\nreturn false;\n];\n\nint C, I;\n[Format(7, 0);\nI:= 49; C:= 0;\nwhile C # 41 do \\limit for signed 32-bit integers\n [if IsDeceptive(I) then\n [RlOut(0, float(I));\n C:= C+1;\n if rem(C/10) = 0 then CrLf(0);\n ];\n I:= I+1;\n ];\n]\n", "language": "XPL0" } ]
Deceptive-numbers
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Deconvolution/1D\nnote: Mathematical operations\n", "language": "00-META" }, { "code": "The convolution of two functions <math>\\mathit{F}</math> and <math>\\mathit{H}</math> of\nan integer variable is defined as the function <math>\\mathit{G}</math>\nsatisfying\n\n:<math> G(n) = \\sum_{m=-\\infty}^{\\infty} F(m) H(n-m) </math>\n\nfor all integers <math>\\mathit{n}</math>. Assume <math>F(n)</math> can be non-zero only for <math>0</math> &le; <math>\\mathit{n}</math> &le; <math>|\\mathit{F}|</math>, where <math>|\\mathit{F}|</math> is the \"length\" of <math>\\mathit{F}</math>, and similarly for <math>\\mathit{G}</math> and <math>\\mathit{H}</math>, so that the functions can be modeled as finite sequences by identifying <math>f_0, f_1, f_2, \\dots</math> with <math>F(0), F(1), F(2), \\dots</math>, etc. \nThen for example, values of <math>|\\mathit{F}| = 6</math> and <math>|\\mathit{H}| = 5</math> would determine the following value of <math>\\mathit{g}</math> by definition.\n\n:<math>\n\\begin{array}{lllllllllll}\ng_0 &= &f_0h_0\\\\\ng_1 &= &f_1h_0 &+ &f_0h_1\\\\\ng_2 &= &f_2h_0 &+ &f_1h_1 &+ &f_0h_2\\\\\ng_3 &= &f_3h_0 &+ &f_2h_1 &+ &f_1h_2 &+ &f_0h_3\\\\\ng_4 &= &f_4h_0 &+ &f_3h_1 &+ &f_2h_2 &+ &f_1h_3 &+ &f_0h_4\\\\\ng_5 &= &f_5h_0 &+ &f_4h_1 &+ &f_3h_2 &+ &f_2h_3 &+ &f_1h_4\\\\\ng_6 &= & & &f_5h_1 &+ &f_4h_2 &+ &f_3h_3 &+ &f_2h_4\\\\\ng_7 &= & & & & &f_5h_2 &+ &f_4h_3 &+ &f_3h_4\\\\\ng_8 &= & & & & & & &f_5h_3 &+ &f_4h_4\\\\\ng_9 &= & & & & & & & & &f_5h_4\n\\end{array}\n</math>\n\nWe can write this in matrix form as:\n\n:<math>\n\\left( \n\\begin{array}{l}\ng_0 \\\\\ng_1 \\\\\ng_2 \\\\\ng_3 \\\\\ng_4 \\\\\ng_5 \\\\\ng_6 \\\\\ng_7 \\\\\ng_8 \\\\\ng_9 \\\\\n\\end{array}\n\\right) = \\left(\n\\begin{array}{lllll}\nf_0\\\\\nf_1 & f_0\\\\\nf_2 & f_1 & f_0\\\\\nf_3 & f_2 & f_1 & f_0\\\\\nf_4 & f_3 & f_2 & f_1 & f_0\\\\\nf_5 & f_4 & f_3 & f_2 & f_1\\\\\n & f_5 & f_4 & f_3 & f_2\\\\\n & & f_5 & f_4 & f_3\\\\\n & & & f_5 & f_4\\\\\n & & & & f_5\n\\end{array}\n\\right) \\; \\left(\n\\begin{array}{l}\nh_0 \\\\\nh_1 \\\\\nh_2 \\\\\nh_3 \\\\\nh_4 \\\\\n\\end{array} \\right)\n</math>\n\nor\n\n:<math>\ng = A \\; h\n</math>\n\nFor this task, implement a function (or method, procedure, subroutine, etc.) <code>deconv</code> to perform ''deconvolution'' (i.e., the ''inverse'' of convolution) by constructing and solving such a system of equations represented by the above matrix <math>A</math> for <math>\\mathit{h}</math> given <math>\\mathit{f}</math> and <math>\\mathit{g}</math>.\n\n* The function should work for <math>\\mathit{G}</math> of arbitrary length (i.e., not hard coded or constant) and <math>\\mathit{F}</math> of any length up to that of <math>\\mathit{G}</math>. Note that <math>|\\mathit{H}|</math> will be given by <math>|\\mathit{G}| - |\\mathit{F}| + 1</math>.\n* There may be more equations than unknowns. If convenient, use a function from a [http://www.netlib.org/lapack/lug/node27.html library] that finds the best fitting solution to an overdetermined system of linear equations (as in the [[Multiple regression]] task). Otherwise, prune the set of equations as needed and solve as in the [[Reduced row echelon form]] task.\n* Test your solution on the following data. Be sure to verify both that <code>deconv</code><math>(g,f) = h</math> and <code>deconv</code><math>(g,h) = f</math> and display the results in a human readable form.\n<code>\nh = [-8,-9,-3,-1,-6,7]<br>\nf = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]<br>\ng = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]\n</code>\n\n", "language": "00-TASK" }, { "code": "F deconv(g, f)\n V result = [0]*(g.len - f.len + 1)\n L(&e) result\n V n = L.index\n e = g[n]\n V lower_bound = I n >= f.len {n - f.len + 1} E 0\n L(i) lower_bound .< n\n e -= result[i] * f[n - i]\n e /= f[0]\n R result\n\nV h = [-8,-9,-3,-1,-6,7]\nV f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]\nV g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]\nprint(deconv(g, f))\nprint(deconv(g, h))\n", "language": "11l" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Main is\n package real_io is new Float_IO (Long_Float);\n use real_io;\n\n type Vector is array (Natural range <>) of Long_Float;\n\n function deconv (g, f : Vector) return Vector is\n len : Positive :=\n Integer'Max ((g'Length - f'length), (f'length - g'length));\n h : Vector (0 .. len);\n Lower : Natural := 0;\n begin\n for n in h'range loop\n h (n) := g (n);\n if n >= f'length then\n Lower := n - f'length + 1;\n end if;\n for i in Lower .. n - 1 loop\n h (n) := h (n) - (h (i) * f (n - i));\n end loop;\n h (n) := h (n) / f (0);\n end loop;\n return h;\n end deconv;\n\n procedure print (v : Vector) is\n begin\n Put (\"(\");\n for I in v'range loop\n Put (Item => v (I), Fore => 1, Aft => 1, Exp => 0);\n if I < v'Last then\n Put (\" \");\n else\n Put_Line (\")\");\n end if;\n end loop;\n end print;\n\n h : Vector := (-8.0, -9.0, -3.0, -1.0, -6.0, 7.0);\n f : Vector :=\n (-3.0, -6.0, -1.0, 8.0, -6.0, 3.0, -1.0, -9.0, -9.0, 3.0, -2.0, 5.0, 2.0,\n -2.0, -7.0, -1.0);\n g : Vector :=\n (24.0, 75.0, 71.0, -34.0, 3.0, 22.0, -45.0, 23.0, 245.0, 25.0, 52.0, 25.0,\n -67.0, -96.0, 96.0, 31.0, 55.0, 36.0, 29.0, -43.0, -7.0);\nbegin\n print (h);\n print (deconv (g, f));\n print (f);\n print (deconv (g, h));\nend Main;\n", "language": "Ada" }, { "code": " *FLOAT 64\n DIM h(5), f(15), g(20)\n h() = -8,-9,-3,-1,-6,7\n f() = -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1\n g() = 24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7\n\n PROCdeconv(g(), f(), x())\n PRINT \"deconv(g,f) = \" FNprintarray(x())\n x() -= h() : IF SUM(x()) <> 0 PRINT \"Error!\"\n\n PROCdeconv(g(), h(), y())\n PRINT \"deconv(g,h) = \" FNprintarray(y())\n y() -= f() : IF SUM(y()) <> 0 PRINT \"Error!\"\n END\n\n DEF PROCdeconv(g(), f(), RETURN h())\n LOCAL f%, g%, i%, l%, n%\n f% = DIM(f(),1) + 1\n g% = DIM(g(),1) + 1\n DIM h(g% - f%)\n FOR n% = 0 TO g% - f%\n h(n%) = g(n%)\n IF n% < f% THEN l% = 0 ELSE l% = n% - f% + 1\n IF n% THEN\n FOR i% = l% TO n% - 1\n h(n%) -= h(i%) * f(n% - i%)\n NEXT\n ENDIF\n h(n%) /= f(0)\n NEXT n%\n ENDPROC\n\n DEF FNprintarray(a())\n LOCAL i%, a$\n FOR i% = 0 TO DIM(a(),1)\n a$ += STR$(a(i%)) + \", \"\n NEXT\n = LEFT$(LEFT$(a$))\n", "language": "BBC-BASIC" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n\ndouble PI;\ntypedef double complex cplx;\n\nvoid _fft(cplx buf[], cplx out[], int n, int step)\n{\n\tif (step < n) {\n\t\t_fft(out, buf, n, step * 2);\n\t\t_fft(out + step, buf + step, n, step * 2);\n\n\t\tfor (int i = 0; i < n; i += 2 * step) {\n\t\t\tcplx t = cexp(-I * PI * i / n) * out[i + step];\n\t\t\tbuf[i / 2] = out[i] + t;\n\t\t\tbuf[(i + n)/2] = out[i] - t;\n\t\t}\n\t}\n}\n\nvoid fft(cplx buf[], int n)\n{\n\tcplx out[n];\n\tfor (int i = 0; i < n; i++) out[i] = buf[i];\n\t_fft(buf, out, n, 1);\n}\n\n/* pad array length to power of two */\ncplx *pad_two(double g[], int len, int *ns)\n{\n\tint n = 1;\n\tif (*ns) n = *ns;\n\telse while (n < len) n *= 2;\n\n\tcplx *buf = calloc(sizeof(cplx), n);\n\tfor (int i = 0; i < len; i++) buf[i] = g[i];\n\t*ns = n;\n\treturn buf;\n}\n\nvoid deconv(double g[], int lg, double f[], int lf, double out[]) {\n\tint ns = 0;\n\tcplx *g2 = pad_two(g, lg, &ns);\n\tcplx *f2 = pad_two(f, lf, &ns);\n\n\tfft(g2, ns);\n\tfft(f2, ns);\n\n\tcplx h[ns];\n\tfor (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];\n\tfft(h, ns);\n\n\tfor (int i = 0; i >= lf - lg; i--)\n\t\tout[-i] = h[(i + ns) % ns]/32;\n\tfree(g2);\n\tfree(f2);\n}\n\nint main()\n{\n\tPI = atan2(1,1) * 4;\n\tdouble g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7};\n\tdouble f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 };\n\tdouble h[] = { -8,-9,-3,-1,-6,7 };\n\n\tint lg = sizeof(g)/sizeof(double);\n\tint lf = sizeof(f)/sizeof(double);\n\tint lh = sizeof(h)/sizeof(double);\n\n\tdouble h2[lh];\n\tdouble f2[lf];\n\n\tprintf(\"f[] data is : \");\n\tfor (int i = 0; i < lf; i++) printf(\" %g\", f[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"deconv(g, h): \");\n\tdeconv(g, lg, h, lh, f2);\n\tfor (int i = 0; i < lf; i++) printf(\" %g\", f2[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"h[] data is : \");\n\tfor (int i = 0; i < lh; i++) printf(\" %g\", h[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"deconv(g, f): \");\n\tdeconv(g, lg, f, lf, h2);\n\tfor (int i = 0; i < lh; i++) printf(\" %g\", h2[i]);\n\tprintf(\"\\n\");\n}\n", "language": "C" }, { "code": "#include <algorithm>\n#include <cstdint>\n#include <iostream>\n#include <vector>\n\nvoid print_vector(const std::vector<int32_t>& list) {\n\tstd::cout << \"[\";\n\tfor ( uint64_t i = 0; i < list.size() - 1; ++i ) {\n\t\tstd::cout << list[i] << \", \";\n\t}\n\tstd::cout << list.back() << \"]\" << std::endl;\n}\n\nstd::vector<int32_t> deconvolution(const std::vector<int32_t>& a, const std::vector<int32_t>& b) {\n\tstd::vector<int32_t> result(a.size() - b.size() + 1, 0);\n\tfor ( uint64_t n = 0; n < result.size(); n++ ) {\n\t\tresult[n] = a[n];\n\t\tuint64_t start = std::max((int) (n - b.size() + 1), 0);\n\t\tfor ( uint64_t i = start; i < n; i++ ) {\n\t\t\tresult[n] -= result[i] * b[n - i];\n\t\t}\n\t\tresult[n] /= b[0];\n\t}\n\treturn result;\n}\n\nint main() {\n\tconst std::vector<int32_t> h = { -8, -9, -3, -1, -6, 7 };\n\tconst std::vector<int32_t> f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 };\n\tconst std::vector<int32_t> g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52,\n 25, -67, -96, 96, 31, 55, 36, 29, -43, -7 };\n\n std::cout << \"h = \"; print_vector(h);\n\tstd::cout << \"deconvolution(g, f) = \"; print_vector(deconvolution(g, f));\n\tstd::cout << \"f = \"; print_vector(f);\n\tstd::cout << \"deconvolution(g, h) = \"; print_vector(deconvolution(g, h));\n}\n", "language": "C++" }, { "code": ";; Assemble the mxn matrix A from the 2D row vector x.\n(defun make-conv-matrix (x m n)\n (let ((lx (cadr (array-dimensions x)))\n (A (make-array `(,m ,n) :initial-element 0)))\n\n (loop for j from 0 to (- n 1) do\n (loop for i from 0 to (- m 1) do\n (setf (aref A i j)\n (cond ((or (< i j) (>= i (+ j lx)))\n 0)\n ((and (>= i j) (< i (+ j lx)))\n (aref x 0 (- i j)))))))\n A))\n\n;; Solve the overdetermined system A(f)*h=g by linear least squares.\n(defun deconv (g f)\n (let* ((lg (cadr (array-dimensions g)))\n (lf (cadr (array-dimensions f)))\n (lh (+ (- lg lf) 1))\n (A (make-conv-matrix f lg lh)))\n\n (lsqr A (mtp g))))\n", "language": "Common-Lisp" }, { "code": "(setf f #2A((-3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1)))\n(setf h #2A((-8 -9 -3 -1 -6 7)))\n(setf g #2A((24 75 71 -34 3 22 -45 23 245 25 52 25 -67 -96 96 31 55 36 29 -43 -7)))\n\n(deconv g f)\n#2A((-8.0)\n (-9.000000000000002)\n (-2.999999999999999)\n (-0.9999999999999997)\n (-6.0)\n (7.000000000000002))\n\n(deconv g h)\n#2A((-2.999999999999999)\n (-6.000000000000001)\n (-1.0000000000000002)\n (8.0)\n (-5.999999999999999)\n (3.0000000000000004)\n (-1.0000000000000004)\n (-9.000000000000002)\n (-9.0)\n (2.9999999999999996)\n (-1.9999999999999991)\n (5.0)\n (1.9999999999999996)\n (-2.0000000000000004)\n (-7.000000000000001)\n (-0.9999999999999994))\n", "language": "Common-Lisp" }, { "code": "T[] deconv(T)(in T[] g, in T[] f) pure nothrow {\n int flen = f.length;\n int glen = g.length;\n auto result = new T[glen - flen + 1];\n foreach (int n, ref e; result) {\n e = g[n];\n immutable lowerBound = (n >= flen) ? n - flen + 1 : 0;\n foreach (i; lowerBound .. n)\n e -= result[i] * f[n - i];\n e /= f[0];\n }\n return result;\n}\n\nvoid main() {\n import std.stdio;\n immutable h = [-8,-9,-3,-1,-6,7];\n immutable f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1];\n immutable g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,\n -96,96,31,55,36,29,-43,-7];\n writeln(deconv(g, f) == h, \" \", deconv(g, f));\n writeln(deconv(g, h) == f, \" \", deconv(g, h));\n}\n", "language": "D" }, { "code": "! Build\n! Windows: ifort /I \"%IFORT_COMPILER11%\\mkl\\include\\ia32\" deconv1d.f90 \"%IFORT_COMPILER11%\\mkl\\ia32\\lib\\*.lib\"\n! Linux:\n\nprogram deconv\n ! Use gelsd from LAPACK95.\n use mkl95_lapack, only : gelsd\n\n implicit none\n real(8), allocatable :: g(:), href(:), A(:,:), f(:)\n real(8), pointer :: h(:), r(:)\n integer :: N\n character(len=16) :: cbuff\n integer :: i\n intrinsic :: nint\n\n ! Allocate data arrays\n allocate(g(21),f(16))\n g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]\n f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]\n\n ! Calculate deconvolution\n h => deco(f, g)\n\n ! Check result against reference\n N = size(h)\n allocate(href(N))\n href = [-8,-9,-3,-1,-6,7]\n cbuff = ' '\n write(cbuff,'(a,i0,a)') '(a,',N,'(i0,a),i0)'\n if (any(abs(h-href) > 1.0d-4)) then\n write(*,'(a)') 'deconv(f, g) - FAILED'\n else\n write(*,cbuff) 'deconv(f, g) = ',(nint(h(i)),', ',i=1,N-1),nint(h(N))\n end if\n\n ! Calculate deconvolution\n r => deco(h, g)\n\n cbuff = ' '\n N = size(r)\n write(cbuff,'(a,i0,a)') '(a,',N,'(i0,a),i0)'\n if (any(abs(r-f) > 1.0d-4)) then\n write(*,'(a)') 'deconv(h, g) - FAILED'\n else\n write(*,cbuff) 'deconv(h, g) = ',(nint(r(i)),', ',i=1,N-1),nint(r(N))\n end if\n\ncontains\n function deco(p, q)\n real(8), pointer :: deco(:)\n real(8), intent(in) :: p(:), q(:)\n\n real(8), allocatable, target :: r(:)\n real(8), allocatable :: A(:,:)\n integer :: N\n\n ! Construct derived arrays\n N = size(q) - size(p) + 1\n allocate(A(size(q),N),r(size(q)))\n A = 0.0d0\n do i=1,N\n A(i:i+size(p)-1,i) = p\n end do\n\n ! Invoke the LAPACK routine to do the work\n r = q\n call gelsd(A, r)\n\n deco => r(1:N)\n end function deco\n\nend program deconv\n", "language": "Fortran" }, { "code": "deconv(f, g) = -8, -9, -3, -1, -6, 7\ndeconv(h, g) = -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1\n", "language": "Fortran" }, { "code": "Sub Deconv(g() As Double, f() As Double, h() As Double)\n Dim As Integer n, i, lower\n Dim As Integer hCount = Ubound(g) - Ubound(f) + 2\n Redim h(hCount - 1)\n\n For n = 0 To hCount - 1\n h(n) = g(n)\n lower = Iif(n >= Ubound(f) + 1, n - Ubound(f), 0)\n i = lower\n While i < n\n h(n) -= h(i) * f(n - i)\n i += 1\n Wend\n h(n) /= f(0)\n Next n\nEnd Sub\n\nDim As Integer i\nDim As Double h(5) = {-8, -9, -3, -1, -6, 7}\nDim As Double f(15) = {-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}\nDim As Double g(20) = {24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7}\nDim As Double result()\n\nPrint !\"h:\\n[\";\nFor i = Lbound(h) To Ubound(h)\n Print h(i); \",\";\nNext i\nPrint Chr(8) & !\"]\\n\";\n\nDeconv(g(), f(), result())\nPrint !\"\\deconv(g, f):\\n[\";\nFor i = Lbound(result) To Ubound(result)-1\n Print result(i); \",\";\nNext i\nPrint Chr(8) & !\"]\\n\";\n\nPrint\nPrint !\"f:\\n[\";\nFor i = Lbound(f) To Ubound(f)\n Print f(i); \",\";\nNext i\nPrint Chr(8) & !\"]\\n\";\n\nDeconv(g(), h(), result())\nPrint !\"\\deconv(g, h):\\n[\";\nFor i = Lbound(result) To Ubound(result)-1\n Print Using \"##_,\"; result(i);\nNext i\nPrint Chr(8) & !\"]\\n\";\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc main() {\n h := []float64{-8, -9, -3, -1, -6, 7}\n f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}\n g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n 96, 31, 55, 36, 29, -43, -7}\n fmt.Println(h)\n fmt.Println(deconv(g, f))\n fmt.Println(f)\n fmt.Println(deconv(g, h))\n}\n\nfunc deconv(g, f []float64) []float64 {\n h := make([]float64, len(g)-len(f)+1)\n for n := range h {\n h[n] = g[n]\n var lower int\n if n >= len(f) {\n lower = n - len(f) + 1\n }\n for i := lower; i < n; i++ {\n h[n] -= h[i] * f[n-i]\n }\n h[n] /= f[0]\n }\n return h\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/cmplx\"\n)\n\nfunc main() {\n h := []float64{-8, -9, -3, -1, -6, 7}\n f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}\n g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n 96, 31, 55, 36, 29, -43, -7}\n fmt.Printf(\"%.1f\\n\", h)\n fmt.Printf(\"%.1f\\n\", deconv(g, f))\n fmt.Printf(\"%.1f\\n\", f)\n fmt.Printf(\"%.1f\\n\", deconv(g, h))\n}\n\nfunc deconv(g, f []float64) []float64 {\n n := 1\n for n < len(g) {\n n *= 2\n }\n g2 := make([]complex128, n)\n for i, x := range g {\n g2[i] = complex(x, 0)\n }\n f2 := make([]complex128, n)\n for i, x := range f {\n f2[i] = complex(x, 0)\n }\n gt := fft(g2)\n ft := fft(f2)\n for i := range gt {\n gt[i] /= ft[i]\n }\n ht := fft(gt)\n it := 1 / float64(n)\n out := make([]float64, len(g)-len(f)+1)\n out[0] = real(ht[0]) * it\n for i := 1; i < len(out); i++ {\n out[i] = real(ht[n-i]) * it\n }\n return out\n}\n\nfunc fft(in []complex128) []complex128 {\n out := make([]complex128, len(in))\n ditfft2(in, out, len(in), 1)\n return out\n}\n\nfunc ditfft2(x, y []complex128, n, s int) {\n if n == 1 {\n y[0] = x[0]\n return\n }\n ditfft2(x, y, n/2, 2*s)\n ditfft2(x[s:], y[n/2:], n/2, 2*s)\n for k := 0; k < n/2; k++ {\n tf := cmplx.Rect(1, -2*math.Pi*float64(k)/float64(n)) * y[k+n/2]\n y[k], y[k+n/2] = y[k]+tf, y[k]-tf\n }\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"fmt\"\n\n \"gonum.org/v1/gonum/mat\"\n)\n\nvar (\n h = []float64{-8, -9, -3, -1, -6, 7}\n f = []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}\n g = []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n 96, 31, 55, 36, 29, -43, -7}\n)\n\nfunc band(g, f []float64) *mat.Dense {\n nh := len(g) - len(f) + 1\n b := mat.NewDense(len(g), nh, nil)\n for j := 0; j < nh; j++ {\n for i, fi := range f {\n b.Set(i+j, j, fi)\n }\n }\n return b\n}\n\nfunc deconv(g, f []float64) mat.Matrix {\n z := mat.NewDense(len(g)-len(f)+1, 1, nil)\n z.Solve(band(g, f), mat.NewVecDense(len(g), g))\n return z\n}\n\nfunc main() {\n fmt.Printf(\"deconv(g, f) =\\n%.1f\\n\\n\", mat.Formatted(deconv(g, f)))\n fmt.Printf(\"deconv(g, h) =\\n%.1f\\n\", mat.Formatted(deconv(g, h)))\n}\n", "language": "Go" }, { "code": "deconv1d :: [Double] -> [Double] -> [Double]\ndeconv1d xs ys = takeWhile (/= 0) $ deconv xs ys\n where\n [] `deconv` _ = []\n (0:xs) `deconv` (0:ys) = xs `deconv` ys\n (x:xs) `deconv` (y:ys) =\n let q = x / y\n in q : zipWith (-) xs (scale q ys ++ repeat 0) `deconv` (y : ys)\n\nscale :: Double -> [Double] -> [Double]\nscale = map . (*)\n\nh, f, g :: [Double]\nh = [-8, -9, -3, -1, -6, 7]\n\nf = [-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1]\n\ng =\n [ 24\n , 75\n , 71\n , -34\n , 3\n , 22\n , -45\n , 23\n , 245\n , 25\n , 52\n , 25\n , -67\n , -96\n , 96\n , 31\n , 55\n , 36\n , 29\n , -43\n , -7\n ]\n\nmain :: IO ()\nmain = print $ (h == deconv1d g f) && (f == deconv1d g h)\n", "language": "Haskell" }, { "code": "Ai=: (i.@] =/ i.@[ -/ i.@>:@-)&#\ndivide=: [ +/ .*~ [:%.&.x: ] +/ .* Ai\n", "language": "J" }, { "code": "h=: _8 _9 _3 _1 _6 7\nf=: _3 _6 _1 8 _6 3 _1 _9 _9 3 _2 5 2 _2 _7 _1\ng=: 24 75 71 _34 3 22 _45 23 245 25 52 25 _67 _96 96 31 55 36 29\n", "language": "J" }, { "code": " g divide f\n_8 _9 _3 _1 _6 7\n g divide h\n_3 _6 _1 8 _6 3 _1 _9 _9 3 _2 5 2 _2 _7 _1\n", "language": "J" }, { "code": "divide=: [ +/ .*~ [:%. ] +/ .* Ai\n", "language": "J" }, { "code": "import java.util.Arrays;\n\npublic class Deconvolution1D {\n public static int[] deconv(int[] g, int[] f) {\n int[] h = new int[g.length - f.length + 1];\n for (int n = 0; n < h.length; n++) {\n h[n] = g[n];\n int lower = Math.max(n - f.length + 1, 0);\n for (int i = lower; i < n; i++)\n h[n] -= h[i] * f[n - i];\n h[n] /= f[0];\n }\n return h;\n }\n\n public static void main(String[] args) {\n int[] h = { -8, -9, -3, -1, -6, 7 };\n int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 };\n int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n 96, 31, 55, 36, 29, -43, -7 };\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"h = \" + Arrays.toString(h) + \"\\n\");\n sb.append(\"deconv(g, f) = \" + Arrays.toString(deconv(g, f)) + \"\\n\");\n sb.append(\"f = \" + Arrays.toString(f) + \"\\n\");\n sb.append(\"deconv(g, h) = \" + Arrays.toString(deconv(g, h)) + \"\\n\");\n System.out.println(sb.toString());\n }\n}\n", "language": "Java" }, { "code": "h = [-8, -9, -3, -1, -6, 7]\ng = [24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7]\nf = [-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1]\n\nhanswer = deconv(float.(g), float.(f))\nprintln(\"The deconvolution deconv(g, f) is $hanswer, which is the same as h = $h\\n\")\n\nfanswer = deconv(float.(g), float.(h))\nprintln(\"The deconvolution deconv(g, h) is $fanswer, which is the same as f = $f\\n\")\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nfun deconv(g: DoubleArray, f: DoubleArray): DoubleArray {\n val fs = f.size\n val h = DoubleArray(g.size - fs + 1)\n for (n in h.indices) {\n h[n] = g[n]\n val lower = if (n >= fs) n - fs + 1 else 0\n for (i in lower until n) h[n] -= h[i] * f[n -i]\n h[n] /= f[0]\n }\n return h\n}\n\nfun main(args: Array<String>) {\n val h = doubleArrayOf(-8.0, -9.0, -3.0, -1.0, -6.0, 7.0)\n val f = doubleArrayOf(-3.0, -6.0, -1.0, 8.0, -6.0, 3.0, -1.0, -9.0,\n -9.0, 3.0, -2.0, 5.0, 2.0, -2.0, -7.0, -1.0)\n val g = doubleArrayOf(24.0, 75.0, 71.0, -34.0, 3.0, 22.0, -45.0,\n 23.0, 245.0, 25.0, 52.0, 25.0, -67.0, -96.0,\n 96.0, 31.0, 55.0, 36.0, 29.0, -43.0, -7.0)\n println(\"${h.map { it.toInt() }}\")\n println(\"${deconv(g, f).map { it.toInt() }}\")\n println()\n println(\"${f.map { it.toInt() }}\")\n println(\"${deconv(g, h).map { it.toInt() }}\")\n}\n", "language": "Kotlin" }, { "code": "function deconvolve(f, g)\n local h = setmetatable({}, {__index = function(self, n)\n if n == 1 then self[1] = g[1] / f[1]\n else\n self[n] = g[n]\n for i = 1, n - 1 do\n self[n] = self[n] - self[i] * (f[n - i + 1] or 0)\n end\n self[n] = self[n] / f[1]\n end\n return self[n]\n end})\n local _ = h[#g - #f + 1]\n return setmetatable(h, nil)\nend\n", "language": "Lua" }, { "code": "local f = {-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1}\nlocal g = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7}\nlocal h = {-8,-9,-3,-1,-6,7}\nprint(unpack(deconvolve(f, g))) --> -8 -9 -3 -1 -6 7\nprint(unpack(deconvolve(h, g))) --> -3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1\n", "language": "Lua" }, { "code": "deconv[f_List, g_List] :=\n Module[{A =\n SparseArray[\n Table[Band[{n, 1}] -> f[[n]], {n, 1, Length[f]}], {Length[g], Length[f] - 1}]},\n Take[LinearSolve[A, g], Length[g] - Length[f] + 1]]\n", "language": "Mathematica" }, { "code": ">> h = [-8,-9,-3,-1,-6,7];\n>> g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7];\n>> f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1];\n>> deconv(g,f)\n\nans =\n\n -8.0000 -9.0000 -3.0000 -1.0000 -6.0000 7.0000\n\n>> deconv(g,h)\n\nans =\n\n -3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1\n", "language": "MATLAB" }, { "code": "proc deconv(g, f: openArray[float]): seq[float] =\n var h: seq[float] = newSeq[float](len(g) - len(f) + 1)\n for n in 0..<len(h):\n h[n] = g[n]\n var lower: int\n if n >= len(f):\n lower = n - len(f) + 1\n for i in lower..<n:\n h[n] -= h[i] * f[n - i]\n h[n] /= f[0]\n h\n\nlet h = [-8'f64, -9, -3, -1, -6, 7]\nlet f = [-3'f64, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1]\nlet g = [24'f64, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n 96, 31, 55, 36, 29, -43, -7]\necho h\necho deconv(g, f)\necho f\necho deconv(g, h)\n", "language": "Nim" }, { "code": "use v5.36;\nuse Math::Cartesian::Product;\n\nsub deconvolve($g,$f) {\n my @g = @{$g};\n my @f = @{$f};\n my(@m,@d);\n\n my $h = 1 + @g - @f;\n push @m, [(0) x $h, $g[$_]] for 0..$#g;\n for my $j (0..$h-1) {\n for my $k (0..$#f) {\n $m[$j + $k][$j] = $f[$k]\n }\n }\n rref(\\@m);\n push @d, @{ $m[$_] }[$h] for 0..$h-1;\n @d;\n}\n\nsub convolve($f,$h) {\n my @f = @{$f};\n my @h = @{$h};\n my @i;\n for my $x (cartesian {@_} [0..$#f], [0..$#h]) {\n push @i, @$x[0]+@$x[1];\n }\n my $cnt = 0;\n my @g = (0) x (@f + @h - 1);\n for my $x (cartesian {@_} [@f], [@h]) {\n $g[$i[$cnt++]] += @$x[0]*@$x[1];\n }\n @g;\n}\n\nsub rref($m) {\n my @m = @{$m};\n @m or return;\n my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]}));\n\n for my $r (0 .. $rows - 1) {\n $lead < $cols or return;\n my $i = $r;\n\n until ($m[$i][$lead]) {\n ++$i == $rows or next;\n $i = $r;\n ++$lead == $cols and return;\n }\n\n @m[$i, $r] = @m[$r, $i];\n my $lv = $m[$r][$lead];\n $_ /= $lv foreach @{ $m[$r] };\n\n my @mr = @{ $m[$r] };\n for my $i (0 .. $rows - 1) {\n $i == $r and next;\n ($lv, my $n) = ($m[$i][$lead], -1);\n $_ -= $lv * $mr[++$n] foreach @{ $m[$i] };\n }\n ++$lead;\n }\n}\n\nmy @h = qw<-8 -9 -3 -1 -6 7>;\nmy @f = qw<-3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1>;\nprint ' conv(f,h) = g = ' . join(' ', my @g = convolve(\\@f, \\@h)) . \"\\n\";\nprint 'deconv(g,f) = h = ' . join(' ', deconvolve(\\@g, \\@f)) . \"\\n\";\nprint 'deconv(g,h) = f = ' . join(' ', deconvolve(\\@g, \\@h)) . \"\\n\";\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">deconv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">lf</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">lg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">lh</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">lg</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">lf</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">lh</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">lh</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">e</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">lf</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">e</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">h</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">conv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">lf</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">lh</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">lg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">lf</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">lh</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">g</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">lg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">lh</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">lf</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">g</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #000000;\">f</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #000000;\">g</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">24</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">75</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">71</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">34</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">22</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">45</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">23</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">245</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">25</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">52</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">25</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">67</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">96</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">96</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">31</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">55</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">36</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">29</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">43</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">}</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">desc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">eq</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s (%ssame as %s): %V\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">desc</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">==</span><span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"**NOT** \"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">eq</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\" conv(h,f)\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"g\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">conv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"deconv(g,f)\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"h\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">deconv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"deconv(g,h)\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"f\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">deconv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "(load \"@lib/math.l\")\n\n(de deconv (G F)\n (let A (pop 'F)\n (make\n (for (N . H) (head (- (length F)) G)\n (for (I . M) (made)\n (dec 'H\n (*/ M (get F (- N I)) 1.0) ) )\n (link (*/ H 1.0 A)) ) ) ) )\n", "language": "PicoLisp" }, { "code": "(setq\n F (-3. -6. -1. 8. -6. 3. -1. -9. -9. 3. -2. 5. 2. -2. -7. -1.)\n G (24. 75. 71. -34. 3. 22. -45. 23. 245. 25. 52. 25. -67. -96. 96. 31. 55. 36. 29. -43. -7.)\n H (-8. -9. -3. -1. -6. 7.) )\n\n(test H (deconv G F))\n(test F (deconv G H))\n", "language": "PicoLisp" }, { "code": "def ToReducedRowEchelonForm( M ):\n if not M: return\n lead = 0\n rowCount = len(M)\n columnCount = len(M[0])\n for r in range(rowCount):\n if lead >= columnCount:\n return\n i = r\n while M[i][lead] == 0:\n i += 1\n if i == rowCount:\n i = r\n lead += 1\n if columnCount == lead:\n return\n M[i],M[r] = M[r],M[i]\n lv = M[r][lead]\n M[r] = [ mrx / lv for mrx in M[r]]\n for i in range(rowCount):\n if i != r:\n lv = M[i][lead]\n M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]\n lead += 1\n return M\n\ndef pmtx(mtx):\n print ('\\n'.join(''.join(' %4s' % col for col in row) for row in mtx))\n\ndef convolve(f, h):\n g = [0] * (len(f) + len(h) - 1)\n for hindex, hval in enumerate(h):\n for findex, fval in enumerate(f):\n g[hindex + findex] += fval * hval\n return g\n\ndef deconvolve(g, f):\n lenh = len(g) - len(f) + 1\n mtx = [[0 for x in range(lenh+1)] for y in g]\n for hindex in range(lenh):\n for findex, fval in enumerate(f):\n gindex = hindex + findex\n mtx[gindex][hindex] = fval\n for gindex, gval in enumerate(g):\n mtx[gindex][lenh] = gval\n ToReducedRowEchelonForm( mtx )\n return [mtx[i][lenh] for i in range(lenh)] # h\n\nif __name__ == '__main__':\n h = [-8,-9,-3,-1,-6,7]\n f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]\n g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]\n assert convolve(f,h) == g\n assert deconvolve(g, f) == h\n", "language": "Python" }, { "code": "import numpy\n\nh = [-8,-9,-3,-1,-6,7]\nf = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]\ng = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]\n\n# https://stackoverflow.com/questions/14267555/find-the-smallest-power-of-2-greater-than-n-in-python\n\ndef shift_bit_length(x):\n return 1<<(x-1).bit_length()\n\ndef conv(a, b):\n p = len(a)\n q = len(b)\n n = p + q - 1\n r = shift_bit_length(n)\n y = numpy.fft.ifft(numpy.fft.fft(a,r) * numpy.fft.fft(b,r),r)\n return numpy.trim_zeros(numpy.around(numpy.real(y),decimals=6))\n\ndef deconv(a, b):\n p = len(a)\n q = len(b)\n n = p - q + 1\n r = shift_bit_length(max(p, q))\n y = numpy.fft.ifft(numpy.fft.fft(a,r) / numpy.fft.fft(b,r), r)\n return numpy.trim_zeros(numpy.around(numpy.real(y),decimals=6))\n\n# should return g\n\nprint(conv(h,f))\n\n# should return h\n\nprint(deconv(g,f))\n\n# should return f\n\nprint(deconv(g,h))\n", "language": "Python" }, { "code": "conv <- function(a, b) {\n\tp <- length(a)\n\tq <- length(b)\n\tn <- p + q - 1\n\tr <- nextn(n, f=2)\n\ty <- fft(fft(c(a, rep(0, r-p))) * fft(c(b, rep(0, r-q))), inverse=TRUE)/r\n\ty[1:n]\n}\n\ndeconv <- function(a, b) {\n\tp <- length(a)\n\tq <- length(b)\n\tn <- p - q + 1\n\tr <- nextn(max(p, q), f=2)\n\ty <- fft(fft(c(a, rep(0, r-p))) / fft(c(b, rep(0, r-q))), inverse=TRUE)/r\n\treturn(y[1:n])\n}\n", "language": "R" }, { "code": "h <- c(-8,-9,-3,-1,-6,7)\nf <- c(-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1)\ng <- c(24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7)\n\nmax(abs(conv(f,h) - g))\nmax(abs(deconv(g,f) - h))\nmax(abs(deconv(g,h) - f))\n", "language": "R" }, { "code": "conv(a, b) == convolve(a, rev(b), type=\"open\")\n", "language": "R" }, { "code": "#lang racket\n(require math/matrix)\n(define T matrix-transpose)\n\n(define (convolution-matrix f m n)\n (define l (matrix-num-rows f))\n (for*/matrix m n ([i (in-range 0 m)] [j (in-range 0 n)])\n (cond [(or (< i j) (>= i (+ j l))) 0]\n [(matrix-ref f (- i j) 0)])))\n\n(define (least-square X y)\n (matrix-solve (matrix* (T X) X) (matrix* (T X) y)))\n\n(define (deconvolve g f)\n (define lg (matrix-num-rows g))\n (define lf (matrix-num-rows f))\n (define lh (+ (- lg lf) 1))\n (least-square (convolution-matrix f lg lh) g))\n", "language": "Racket" }, { "code": "(define f (col-matrix [-3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1]))\n(define h (col-matrix [-8 -9 -3 -1 -6 7]))\n(define g (col-matrix [24 75 71 -34 3 22 -45 23 245 25 52 25 -67 -96 96 31 55 36 29 -43 -7]))\n\n(deconvolve g f)\n(deconvolve g h)\n", "language": "Racket" }, { "code": "#<array '#(6 1) #[-8 -9 -3 -1 -6 7]>\n#<array '#(16 1) #[-3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1]>\n", "language": "Racket" }, { "code": "sub deconvolve (@g, @f) {\n my \\h = 1 + @g - @f;\n my @m;\n @m[^@g;^h] »+=» 0;\n @m[^@g; h] »=« @g;\n for ^h -> \\j { for @f.kv -> \\k, \\v { @m[j+k;j] = v } }\n (rref @m)[^h;h]\n}\n\nsub convolve (@f, @h) {\n my @g = 0 xx + @f + @h - 1;\n @g[^@f X+ ^@h] »+=« (@f X× @h);\n @g\n}\n\n# Reduced Row Echelon Form simultaneous equation solver\n# Can handle over-specified systems of equations (N unknowns in N + M equations)\nsub rref (@m) {\n @m = trim-system @m;\n my ($lead, $rows, $cols) = 0, @m, @m[0];\n for ^$rows -> $r {\n return @m unless $lead < $cols;\n my $i = $r;\n until @m[$i;$lead] {\n next unless ++$i == $rows;\n $i = $r;\n return @m if ++$lead == $cols;\n }\n @m[$i, $r] = @m[$r, $i] if $r != $i;\n @m[$r] »/=» $ = @m[$r;$lead];\n for ^$rows -> $n {\n next if $n == $r;\n @m[$n] »-=» @m[$r] »×» (@m[$n;$lead] // 0);\n }\n ++$lead;\n }\n @m\n }\n\n# Reduce to N equations in N unknowns; a no-op unless rows > cols\nsub trim-system (@m) {\n return @m unless @m ≥ @m[0];\n my (\\vars, @t) = @m[0] - 1;\n for ^vars -> \\lead {\n for ^@m -> \\row {\n @t.append: @m.splice(row, 1) and last if @m[row;lead];\n }\n }\n while @t < vars and @m { @t.push: shift @m }\n @t\n}\n\nmy @h = (-8,-9,-3,-1,-6,7);\nmy @f = (-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1);\nmy @g = (24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7);\n\n.say for ~@g, ~convolve(@f, @h),'';\n.say for ~@h, ~deconvolve(@g, @f),'';\n.say for ~@f, ~deconvolve(@g, @h),'';\n", "language": "Raku" }, { "code": "/*REXX pgm performs deconvolution of two arrays: deconv(g,f)=h and deconv(g,h)=f */\ncall make 'H', \"-8 -9 -3 -1 -6 7\"\ncall make 'F', \"-3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1\"\ncall make 'G', \"24 75 71 -34 3 22 -45 23 245 25 52 25 -67 -96 96 31 55 36 29 -43 -7\"\ncall show 'H' /*display the elements of array H. */\ncall show 'F' /* \" \" \" \" \" F. */\ncall show 'G' /* \" \" \" \" \" G. */\ncall deco 'G', \"F\", 'X' /*deconvolution of G and F ───► X */\ncall test 'X', \"H\" /*test: is array H equal to array X?*/\ncall deco 'G', \"H\", 'Y' /*deconvolution of G and H ───► Y */\ncall test 'F', \"Y\" /*test: is array F equal to array Y?*/\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ndeco: parse arg $1,$2,$r; b= @.$2.# + 1; a= @.$1.# + 1 /*get sizes of array 1&2*/\n @.$r.#= a - b /*size of return array. */\n do n=0 to a-b /*define return array. */\n @.$r.n= @.$1.n /*define RETURN element.*/\n if n<b then L= 0 /*define the variable L.*/\n else L= n - b + 1 /* \" \" \" \" */\n if n>0 then do j=L to n-1; _= n-j /*define elements > 0. */\n @.$r.n= @.$r.n - @.$r.j * @.$2._ /*compute \" \" \" */\n end /*j*/ /* [↑] subtract product.*/\n @.$r.n= @.$r.n / @.$2.0 /*divide array element. */\n end /*n*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nmake: parse arg $,z; @.$.#= words(z) - 1 /*obtain args; set size.*/\n do k=0 to @.$.#; @.$.k= word(z, k + 1) /*define array element. */\n end /*k*/; return /*array starts at unity.*/\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nshow: parse arg $,z,_; do s=0 to @.$.#; _= strip(_ @.$.s) /*obtain the arguments. */\n end /*s*/ /* [↑] build the list. */\n say 'array' $\": \" _; return /*show the list; return*/\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ntest: parse arg $1,$2; do t=0 to max(@.$1.#, @.$2.#) /*obtain the arguments. */\n if @.$1.t= @.$2.t then iterate /*create array list. */\n say \"***error*** arrays\" $1 ' and ' $2 \"aren't equal.\"\n end /*t*/; return /* [↑] build the list. */\n", "language": "REXX" }, { "code": "object Deconvolution1D extends App {\n val (h, f) = (Array(-8, -9, -3, -1, -6, 7), Array(-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1))\n val g = Array(24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7)\n val sb = new StringBuilder\n\n private def deconv(g: Array[Int], f: Array[Int]) = {\n val h = Array.ofDim[Int](g.length - f.length + 1)\n\n for (n <- h.indices) {\n h(n) = g(n)\n for (i <- math.max(n - f.length + 1, 0) until n) h(n) -= h(i) * f(n - i)\n h(n) /= f(0)\n }\n h\n }\n\n sb.append(s\"h = ${h.mkString(\"[\", \", \", \"]\")}\\n\")\n .append(s\"deconv(g, f) = ${deconv(g, f).mkString(\"[\", \", \", \"]\")}\\n\")\n .append(s\"f = ${f.mkString(\"[\", \", \", \"]\")}\\n\")\n .append(s\"deconv(g, h) = ${deconv(g, h).mkString(\"[\", \", \", \"]\")}\")\n println(sb.result())\n\n}\n", "language": "Scala" }, { "code": "func deconv(g: [Double], f: [Double]) -> [Double] {\n let fs = f.count\n var ret = [Double](repeating: 0, count: g.count - fs + 1)\n\n for n in 0..<ret.count {\n ret[n] = g[n]\n let lower = n >= fs ? n - fs + 1 : 0\n\n for i in lower..<n {\n ret[n] -= ret[i] * f[n - i]\n }\n\n ret[n] /= f[0]\n }\n\n return ret\n}\n\nlet h = [-8.0, -9.0, -3.0, -1.0, -6.0, 7.0]\nlet f = [-3.0, -6.0, -1.0, 8.0, -6.0, 3.0, -1.0, -9.0,\n -9.0, 3.0, -2.0, 5.0, 2.0, -2.0, -7.0, -1.0]\nlet g = [24.0, 75.0, 71.0, -34.0, 3.0, 22.0, -45.0,\n 23.0, 245.0, 25.0, 52.0, 25.0, -67.0, -96.0,\n 96.0, 31.0, 55.0, 36.0, 29.0, -43.0, -7.0]\n\nprint(\"\\(h.map({ Int($0) }))\")\nprint(\"\\(deconv(g: g, f: f).map({ Int($0) }))\\n\")\n\n\nprint(\"\\(f.map({ Int($0) }))\")\nprint(\"\\(deconv(g: g, f: h).map({ Int($0) }))\")\n", "language": "Swift" }, { "code": "package require Tcl 8.5\nnamespace eval 1D {\n namespace ensemble create; # Will be same name as namespace\n namespace export convolve deconvolve\n # Access core language math utility commands\n namespace path {::tcl::mathfunc ::tcl::mathop}\n\n # Utility for converting a matrix to Reduced Row Echelon Form\n # From http://rosettacode.org/wiki/Reduced_row_echelon_form#Tcl\n proc toRREF {m} {\n\tset lead 0\n\tset rows [llength $m]\n\tset cols [llength [lindex $m 0]]\n\tfor {set r 0} {$r < $rows} {incr r} {\n\t if {$cols <= $lead} {\n\t\tbreak\n\t }\n\t set i $r\n\t while {[lindex $m $i $lead] == 0} {\n\t\tincr i\n\t\tif {$rows == $i} {\n\t\t set i $r\n\t\t incr lead\n\t\t if {$cols == $lead} {\n\t\t\t# Tcl can't break out of nested loops\n\t\t\treturn $m\n\t\t }\n\t\t}\n\t }\n\t # swap rows i and r\n\t foreach j [list $i $r] row [list [lindex $m $r] [lindex $m $i]] {\n\t\tlset m $j $row\n\t }\n\t # divide row r by m(r,lead)\n\t set val [lindex $m $r $lead]\n\t for {set j 0} {$j < $cols} {incr j} {\n\t\tlset m $r $j [/ [double [lindex $m $r $j]] $val]\n\t }\n\n\t for {set i 0} {$i < $rows} {incr i} {\n\t\tif {$i != $r} {\n\t\t # subtract m(i,lead) multiplied by row r from row i\n\t\t set val [lindex $m $i $lead]\n\t\t for {set j 0} {$j < $cols} {incr j} {\n\t\t\tlset m $i $j \\\n\t\t\t [- [lindex $m $i $j] [* $val [lindex $m $r $j]]]\n\t\t }\n\t\t}\n\t }\n\t incr lead\n\t}\n\treturn $m\n }\n\n # How to apply a 1D convolution of two \"functions\"\n proc convolve {f h} {\n\tset g [lrepeat [+ [llength $f] [llength $h] -1] 0]\n\tset fi -1\n\tforeach fv $f {\n\t incr fi\n\t set hi -1\n\t foreach hv $h {\n\t\tset gi [+ $fi [incr hi]]\n\t\tlset g $gi [+ [lindex $g $gi] [* $fv $hv]]\n\t }\n\t}\n\treturn $g\n }\n\n # How to apply a 1D deconvolution of two \"functions\"\n proc deconvolve {g f} {\n\t# Compute the length of the result vector\n\tset hlen [- [llength $g] [llength $f] -1]\n\n\t# Build a matrix of equations to solve\n\tset matrix {}\n\tset i -1\n\tforeach gv $g {\n\t lappend matrix [list {*}[lrepeat $hlen 0] $gv]\n\t set j [incr i]\n\t foreach fv $f {\n\t\tif {$j < 0} {\n\t\t break\n\t\t} elseif {$j < $hlen} {\n\t\t lset matrix $i $j $fv\n\t\t}\n\t\tincr j -1\n\t }\n\t}\n\n\t# Convert to RREF, solving the system of simultaneous equations\n\tset reduced [toRREF $matrix]\n\n\t# Extract the deconvolution from the last column of the reduced matrix\n\tfor {set i 0} {$i<$hlen} {incr i} {\n\t lappend result [lindex $reduced $i end]\n\t}\n\treturn $result\n }\n}\n", "language": "Tcl" }, { "code": "# Simple pretty-printer\nproc pp {name nlist} {\n set sep \"\"\n puts -nonewline \"$name = \\[\"\n foreach n $nlist {\n\tputs -nonewline [format %s%g $sep $n]\n\tset sep ,\n }\n puts \"\\]\"\n}\n\nset h {-8 -9 -3 -1 -6 7}\nset f {-3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1}\nset g {24 75 71 -34 3 22 -45 23 245 25 52 25 -67 -96 96 31 55 36 29 -43 -7}\n\npp \"deconv(g,f) = h\" [1D deconvolve $g $f]\npp \"deconv(g,h) = f\" [1D deconvolve $g $h]\npp \" conv(f,h) = g\" [1D convolve $f $h]\n", "language": "Tcl" }, { "code": "#import std\n#import nat\n\nband = pad0+ ~&rSS+ zipt^*D(~&r,^lrrSPT/~&ltK33tx zipt^/~&r ~&lSNyCK33+ zipp0)^/~&rx ~&B->NlNSPC ~&bt\n\ndeconv = lapack..dgelsd^\\~&l ~&||0.!**+ band\n", "language": "Ursala" }, { "code": "h = <-8.,-9.,-3.,-1.,-6.,7.>\nf = <-3.,-6.,-1.,8.,-6.,3.,-1.,-9.,-9.,3.,-2.,5.,2.,-2.,-7.,-1.>\ng = <24.,75.,71.,-34.,3.,22.,-45.,23.,245.,25.,52.,25.,-67.,-96.,96.,31.,55.,36.,29.,-43.,-7.>\n\n#cast %eLm\n\ntest =\n\n<\n 'h': deconv(g,f),\n 'f': deconv(g,h)>\n", "language": "Ursala" }, { "code": "fn main() {\n h := [f64(-8), -9, -3, -1, -6, 7]\n f := [f64(-3), -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1]\n g := [f64(24), 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n 96, 31, 55, 36, 29, -43, -7]\n println(h)\n println(deconv(g, f))\n println(f)\n println(deconv(g, h))\n}\n\nfn deconv(g []f64, f []f64) []f64 {\n mut h := []f64{len: g.len-f.len+1}\n for n in 0..h.len {\n h[n] = g[n]\n mut lower := 0\n if n >= f.len {\n lower = n - f.len + 1\n }\n for i in lower..n {\n h[n] -= h[i] * f[n-i]\n }\n h[n] /= f[0]\n }\n return h\n}\n", "language": "V-(Vlang)" }, { "code": "var deconv = Fn.new { |g, f|\n var h = List.filled(g.count - f.count + 1, 0)\n for (n in 0...h.count) {\n h[n] = g[n]\n var lower = (n >= f.count) ? n - f.count + 1 : 0\n var i = lower\n while (i < n) {\n h[n] = h[n] - h[i]*f[n-i]\n i = i + 1\n }\n h[n] = h[n] / f[0]\n }\n return h\n}\n\nvar h = [-8, -9, -3, -1, -6, 7]\nvar f = [-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1]\nvar g = [24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7]\nSystem.print(h)\nSystem.print(deconv.call(g, f))\nSystem.print(f)\nSystem.print(deconv.call(g, h))\n", "language": "Wren" }, { "code": "var [const] GSL=Import(\"zklGSL\");\t// libGSL (GNU Scientific Library)\nfcn dconv1D(f,g){\n fsz,hsz:=f.len(), g.len() - fsz +1;\n A:=GSL.Matrix(g.len(),hsz);\n foreach n,fn in ([0..].zip(f)){ foreach rc in (hsz){ A[rc+n,rc]=fn } }\n h:=A.AxEQb(g);\n h\n}\n", "language": "Zkl" }, { "code": "f:=GSL.VectorFromData(-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1);\ng:=GSL.VectorFromData(24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7);\nh:=dconv1D(f,g);\nh.format().println();\n\nf:=dconv1D(h,g);\nf.format().println();\n", "language": "Zkl" }, { "code": "fcn deconv(g,f){\n flen, glen, delta:=f.len(), g.len(), glen - flen + 1;\n result:=List.createLong(delta); // allocate list with space for items\n foreach n in (delta){\n e:=g[n];\n lowerBound:=(if (n>=flen) n - flen + 1 else 0);\n foreach i in ([lowerBound .. n-1]){ e-=result[i]*f[n - i]; }\n result.append(e/f[0]);\n }\n result;\n}\n", "language": "Zkl" }, { "code": "h:=T(-8,-9,-3,-1,-6,7);\nf:=T(-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1);\ng:=T(24,75,71,-34,3,22,-45,23,245,25,52,25,-67,\n -96,96,31,55,36,29,-43,-7);\nprintln(deconv(g, f) == h, \" \", deconv(g, f));\nprintln(deconv(g, h) == f, \" \", deconv(g, h));\n", "language": "Zkl" } ]
Deconvolution-1D
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Deconvolution/2D+\nnote: Mathematical operations\n", "language": "00-META" }, { "code": "This task is a straightforward generalization of [[Deconvolution/1D]] to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in <math>\\mathit d</math> dimensions of two functions\n\n:<math>H,F:\\mathbb{Z}^d\\rightarrow\\mathbb{R}</math> \n\ntaking <math>\\mathit d</math>-tuples of integers to real numbers as the function\n\n:<math>G:\\mathbb{Z}^d\\rightarrow\\mathbb{R}</math>\n\nalso taking <math>\\mathit d</math>-tuples of integers to reals and satisfying\n\n:<math>G(n_0, \\dots, n_{d-1})=\\sum_{m_0=-\\infty}^{\\infty}\\dots\\sum_{m_{d-1}=-\\infty}^{\\infty}F(m_0, \\dots, m_{d-1})H(n_0-m_0, \\dots, n_{d-1}-m_{d-1})</math>\n\nfor all <math>\\mathit d</math>-tuples of integers <math>(n_0, \\dots, n_{d-1})\\in\\mathbb{Z}^d</math>. Assume\n<math>\\mathit F</math> and <math>\\mathit H</math> (and therefore <math>\\mathit G</math>) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists <math>\\mathit f</math>, <math>\\mathit h</math>, and <math>\\mathit g</math>.\n\nFor this task, implement a function (or method, procedure, subroutine, etc.) <code>deconv</code> to perform ''deconvolution'' (i.e., the ''inverse'' of convolution) by solving for <math>\\mathit{h}</math> given <math>\\mathit{f}</math> and <math>\\mathit{g}</math>. (See [[Deconvolution/1D]] for details.)\n* The function should work for <math>\\mathit{g}</math> of arbitrary length in each dimension (i.e., not hard coded or constant) and <math>\\mathit{f}</math> of any length up to that of <math>\\mathit{g}</math> in the corresponding dimension.\n* The <code>deconv</code> function will need to be parameterized by the dimension <math>\\mathit d</math> unless the dimension can be inferred from the data structures representing <math>\\mathit g</math> and <math>\\mathit f</math>.\n* There may be more equations than unknowns. If convenient, use a function from a [http://www.netlib.org/lapack/lug/node27.html library] that finds the best fitting solution to an overdetermined system of linear equations (as in the [[Multiple regression]] task). Otherwise, prune the set of equations as needed and solve as in the [[Reduced row echelon form]] task.\n* Debug your solution using [http://rosettacode.org/mw/index.php?title=Deconvolution/2D%2B/Test_data&action=raw this test data], of which a portion is shown below. Be sure to verify both that the deconvolution of <math>\\mathit g</math> with <math>\\mathit f</math> is <math>\\mathit h</math> and that the deconvolution of <math>\\mathit g</math> with <math>\\mathit h</math> is <math>\\mathit f</math>. Display the results in a human readable form for the three dimensional case ''only''.\n\ndimension 1:\n<pre>\nh: [-8, 2, -9, -2, 9, -8, -2]\nf: [ 6, -9, -7, -5]\ng: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10]\n</pre>\ndimension 2:\n<pre>\nh: [\n [-8, 1, -7, -2, -9, 4], \n [4, 5, -5, 2, 7, -1], \n [-6, -3, -3, -6, 9, 5]]\nf: [\n [-5, 2, -2, -6, -7], \n [9, 7, -6, 5, -7], \n [1, -1, 9, 2, -7], \n [5, 9, -9, 2, -5], \n [-8, 5, -2, 8, 5]]\ng: [\n [40, -21, 53, 42, 105, 1, 87, 60, 39, -28], \n [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21], \n [58, 85, -93, 37, 101, -14, 5, 37, -76, -56], \n [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48], \n [78, 16, 7, -199, 156, -162, 29, 28, -103, -10], \n [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30], \n [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]]\n</pre>\ndimension 3:\n<pre>\nh: [\n [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], \n [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]\nf: [\n [[-9, 5, -8], [3, 5, 1]], \n [[-1, -7, 2], [-5, -6, 6]], \n [[8, 5, 8],[-2, -6, -4]]]\ng: [\n [\n [54, 42, 53, -42, 85, -72], \n [45, -170, 94, -36, 48, 73], \n [-39, 65, -112, -16, -78, -72], \n [6, -11, -6, 62, 49, 8]], \n [\n [-57, 49, -23, 52, -135, 66], \n [-23, 127, -58, -5, -118, 64], \n [87, -16, 121, 23, -41, -12], \n [-19, 29, 35, -148, -11, 45]], \n [\n [-55, -147, -146, -31, 55, 60], \n [-88, -45, -28, 46, -26, -144], \n [-12, -107, -34, 150, 249, 66], \n [11, -15, -34, 27, -78, -50]], \n [\n [56, 67, 108, 4, 2, -48], \n [58, 67, 89, 32, 32, -8], \n [-42, -31, -103, -30, -23, -8],\n [6, 4, -26, -10, 26, 12]]]\n</pre>\n\n", "language": "00-TASK" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n\ndouble PI;\ntypedef double complex cplx;\n\nvoid _fft(cplx buf[], cplx out[], int n, int step)\n{\n\tif (step < n) {\n\t\t_fft(out, buf, n, step * 2);\n\t\t_fft(out + step, buf + step, n, step * 2);\n\n\t\tfor (int i = 0; i < n; i += 2 * step) {\n\t\t\tcplx t = cexp(-I * PI * i / n) * out[i + step];\n\t\t\tbuf[i / 2] = out[i] + t;\n\t\t\tbuf[(i + n)/2] = out[i] - t;\n\t\t}\n\t}\n}\n\nvoid fft(cplx buf[], int n)\n{\n\tcplx out[n];\n\tfor (int i = 0; i < n; i++) out[i] = buf[i];\n\t_fft(buf, out, n, 1);\n}\n\n/* pad array length to power of two */\ncplx *pad_two(double g[], int len, int *ns)\n{\n\tint n = 1;\n\tif (*ns) n = *ns;\n\telse while (n < len) n *= 2;\n\n\tcplx *buf = calloc(sizeof(cplx), n);\n\tfor (int i = 0; i < len; i++) buf[i] = g[i];\n\t*ns = n;\n\treturn buf;\n}\n\nvoid deconv(double g[], int lg, double f[], int lf, double out[], int row_len) {\n\tint ns = 0;\n\tcplx *g2 = pad_two(g, lg, &ns);\n\tcplx *f2 = pad_two(f, lf, &ns);\n\n\tfft(g2, ns);\n\tfft(f2, ns);\n\n\tcplx h[ns];\n\tfor (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];\n\tfft(h, ns);\n\n\tfor (int i = 0; i < ns; i++) {\n\t\tif (cabs(creal(h[i])) < 1e-10)\n\t\t\th[i] = 0;\n\t}\n\n\tfor (int i = 0; i > lf - lg - row_len; i--)\n\t\tout[-i] = h[(i + ns) % ns]/32;\n\tfree(g2);\n\tfree(f2);\n}\n\ndouble* unpack2(void *m, int rows, int len, int to_len)\n{\n\tdouble *buf = calloc(sizeof(double), rows * to_len);\n\tfor (int i = 0; i < rows; i++)\n\t\tfor (int j = 0; j < len; j++)\n\t\t\tbuf[i * to_len + j] = ((double(*)[len])m)[i][j];\n\treturn buf;\n}\n\nvoid pack2(double * buf, int rows, int from_len, int to_len, void *out)\n{\n\tfor (int i = 0; i < rows; i++)\n\t\tfor (int j = 0; j < to_len; j++)\n\t\t\t((double(*)[to_len])out)[i][j] = buf[i * from_len + j] / 4;\n}\n\nvoid deconv2(void *g, int row_g, int col_g, void *f, int row_f, int col_f, void *out) {\n\tdouble *g2 = unpack2(g, row_g, col_g, col_g);\n\tdouble *f2 = unpack2(f, row_f, col_f, col_g);\n\n\tdouble ff[(row_g - row_f + 1) * col_g];\n\tdeconv(g2, row_g * col_g, f2, row_f * col_g, ff, col_g);\n\tpack2(ff, row_g - row_f + 1, col_g, col_g - col_f + 1, out);\n\n\tfree(g2);\n\tfree(f2);\n}\n\ndouble* unpack3(void *m, int x, int y, int z, int to_y, int to_z)\n{\n\tdouble *buf = calloc(sizeof(double), x * to_y * to_z);\n\tfor (int i = 0; i < x; i++)\n\t\tfor (int j = 0; j < y; j++) {\n\t\t\tfor (int k = 0; k < z; k++)\n\t\t\t\tbuf[(i * to_y + j) * to_z + k] =\n\t\t\t\t\t((double(*)[y][z])m)[i][j][k];\n\t\t}\n\treturn buf;\n}\n\nvoid pack3(double * buf, int x, int y, int z, int to_y, int to_z, void *out)\n{\n\tfor (int i = 0; i < x; i++)\n\t\tfor (int j = 0; j < to_y; j++)\n\t\t\tfor (int k = 0; k < to_z; k++)\n\t\t\t\t((double(*)[to_y][to_z])out)[i][j][k] =\n\t\t\t\t\tbuf[(i * y + j) * z + k] / 4;\n}\n\nvoid deconv3(void *g, int gx, int gy, int gz, void *f, int fx, int fy, int fz, void *out) {\n\tdouble *g2 = unpack3(g, gx, gy, gz, gy, gz);\n\tdouble *f2 = unpack3(f, fx, fy, fz, gy, gz);\n\n\tdouble ff[(gx - fx + 1) * gy * gz];\n\tdeconv(g2, gx * gy * gz, f2, fx * gy * gz, ff, gy * gz);\n\tpack3(ff, gx - fx + 1, gy, gz, gy - fy + 1, gz - fz + 1, out);\n\n\tfree(g2);\n\tfree(f2);\n}\n\nint main()\n{\n\tPI = atan2(1,1) * 4;\n\tdouble h[2][3][4] = {\n\t\t{{-6, -8, -5, 9}, {-7, 9, -6, -8}, { 2, -7, 9, 8}},\n\t\t{{ 7, 4, 4, -6}, { 9, 9, 4, -4}, {-3, 7, -2, -3}}\n\t};\n\tint hx = 2, hy = 3, hz = 4;\n\tdouble f[3][2][3] = {\t{{-9, 5, -8}, { 3, 5, 1}},\n\t\t\t\t{{-1, -7, 2}, {-5, -6, 6}},\n\t\t\t\t{{ 8, 5, 8}, {-2, -6, -4}} };\n\tint fx = 3, fy = 2, fz = 3;\n\tdouble g[4][4][6] = {\n\t\t{\t{ 54, 42, 53, -42, 85, -72}, { 45,-170, 94, -36, 48, 73},\n\t\t\t{-39, 65,-112, -16, -78, -72}, { 6, -11, -6, 62, 49, 8} },\n\t\t{ \t{-57, 49, -23, 52, -135, 66},{-23, 127, -58, -5, -118, 64},\n\t\t\t{ 87, -16, 121, 23, -41, -12},{-19, 29, 35,-148, -11, 45} },\n\t\t{\t{-55, -147, -146, -31, 55, 60},{-88, -45, -28, 46, -26,-144},\n\t\t\t{-12, -107, -34, 150, 249, 66},{ 11, -15, -34, 27, -78, -50} },\n\t\t{\t{ 56, 67, 108, 4, 2,-48},{ 58, 67, 89, 32, 32, -8},\n\t\t\t{-42, -31,-103, -30,-23, -8},{ 6, 4, -26, -10, 26, 12}\n\t\t}\n\t};\n\tint gx = 4, gy = 4, gz = 6;\n\n\tdouble h2[gx - fx + 1][gy - fy + 1][gz - fz + 1];\n\tdeconv3(g, gx, gy, gz, f, fx, fy, fz, h2);\n\tprintf(\"deconv3(g, f):\\n\");\n\tfor (int i = 0; i < gx - fx + 1; i++) {\n\t\tfor (int j = 0; j < gy - fy + 1; j++) {\n\t\t\tfor (int k = 0; k < gz - fz + 1; k++)\n\t\t\t\tprintf(\"%g \", h2[i][j][k]);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tif (i < gx - fx) printf(\"\\n\");\n\t}\n\n\tdouble f2[gx - hx + 1][gy - hy + 1][gz - hz + 1];\n\tdeconv3(g, gx, gy, gz, h, hx, hy, hz, f2);\n\tprintf(\"\\ndeconv3(g, h):\\n\");\n\tfor (int i = 0; i < gx - hx + 1; i++) {\n\t\tfor (int j = 0; j < gy - hy + 1; j++) {\n\t\t\tfor (int k = 0; k < gz - hz + 1; k++)\n\t\t\t\tprintf(\"%g \", f2[i][j][k]);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tif (i < gx - hx) printf(\"\\n\");\n\t}\n}\n\n/* two-D case; since task doesn't require showing it, it's commented out */\n/*\nint main()\n{\n\tPI = atan2(1,1) * 4;\n\tdouble h[][6] = { \t{-8, 1, -7, -2, -9, 4},\n\t\t\t\t{4, 5, -5, 2, 7, -1},\n\t\t\t\t{-6, -3, -3, -6, 9, 5} };\n\tint hr = 3, hc = 6;\n\n\tdouble f[][5] = {\t{-5, 2, -2, -6, -7},\n\t\t\t\t{9, 7, -6, 5, -7},\n\t\t\t\t{1, -1, 9, 2, -7},\n\t\t\t\t{5, 9, -9, 2, -5},\n\t\t\t\t{-8, 5, -2, 8, 5} };\n\tint fr = 5, fc = 5;\n\tdouble g[][10] = {\n\t\t\t{40, -21, 53, 42, 105, 1, 87, 60, 39, -28},\n\t\t\t{-92, -64, 19, -167, -71, -47, 128, -109, 40, -21},\n\t\t\t{58, 85, -93, 37, 101, -14, 5, 37, -76, -56},\n\t\t\t{-90, -135, 60, -125, 68, 53, 223, 4, -36, -48},\n\t\t\t{78, 16, 7, -199, 156, -162, 29, 28, -103, -10},\n\t\t\t{-62, -89, 69, -61, 66, 193, -61, 71, -8, -30},\n\t\t\t{48, -6, 21, -9, -150, -22, -56, 32, 85, 25}\t};\n\tint gr = 7, gc = 10;\n\n\tdouble h2[gr - fr + 1][gc - fc + 1];\n\tdeconv2(g, gr, gc, f, fr, fc, h2);\n\tfor (int i = 0; i < gr - fr + 1; i++) {\n\t\tfor (int j = 0; j < gc - fc + 1; j++)\n\t\t\tprintf(\" %g\", h2[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\n\tdouble f2[gr - hr + 1][gc - hc + 1];\n\tdeconv2(g, gr, gc, h, hr, hc, f2);\n\tfor (int i = 0; i < gr - hr + 1; i++) {\n\t\tfor (int j = 0; j < gc - hc + 1; j++)\n\t\t\tprintf(\" %g\", f2[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n}*/\n", "language": "C" }, { "code": "deconv3(g, f):\n-6 -8 -5 9\n-7 9 -6 -8\n2 -7 9 8\n\n7 4 4 -6\n9 9 4 -4\n-3 7 -2 -3\n\ndeconv3(g, h):\n-9 5 -8\n3 5 1\n\n-1 -7 2\n-5 -6 6\n\n8 5 8\n-2 -6 -4\n", "language": "C" }, { "code": "import std.stdio, std.conv, std.algorithm, std.numeric, std.range;\n\nclass M(T) {\n private size_t[] dim;\n private size_t[] subsize;\n private T[] d;\n\n this(size_t[] dimension...) pure nothrow {\n setDimension(dimension);\n d[] = 0; // init each entry to zero;\n }\n\n M!T dup() {\n auto m = new M!T(dim);\n return m.set1DArray(d);\n }\n\n M!T setDimension(size_t[] dimension ...) pure nothrow {\n foreach (const e; dimension)\n assert(e > 0, \"no zero dimension\");\n dim = dimension.dup;\n subsize = dim.dup;\n foreach (immutable i; 0 .. dim.length)\n subsize[i] = reduce!q{a * b}(1, dim[i + 1 .. $]);\n immutable dlength = dim[0] * subsize[0];\n if (d.length != dlength)\n d = new T[dlength];\n return this;\n }\n\n M!T set1DArray(in T[] t ...) pure nothrow @nogc {\n auto minLen = min(t.length, d.length);\n d[] = 0;\n d[0 .. minLen] = t[0 .. minLen];\n return this;\n }\n\n size_t[] seq2idx(in size_t seq) const pure nothrow {\n size_t acc = seq, tmp;\n size_t[] idx;\n foreach (immutable e; subsize) {\n idx ~= tmp = acc / e;\n acc = acc - tmp * e; // same as % (mod) e.\n }\n return idx;\n }\n\n size_t size() const pure nothrow @nogc @property {\n return d.length;\n }\n\n size_t rank() const pure nothrow @nogc @property {\n return dim.length;\n }\n\n size_t[] shape() const pure nothrow @property { return dim.dup; }\n\n T[] raw() const pure nothrow @property { return d.dup; }\n\n bool checkBound(size_t[] idx ...) const pure nothrow @nogc {\n if (idx.length > dim.length)\n return false;\n foreach (immutable i, immutable dm; idx)\n if (dm >= dim[i])\n return false;\n return true;\n }\n\n T opIndex(size_t[] idx ...) const pure nothrow @nogc {\n assert(checkBound(idx), \"OOPS\");\n return d[dotProduct(idx, subsize)];\n }\n\n T opIndexAssign(T v, size_t[] idx ...) pure nothrow @nogc {\n assert(checkBound(idx), \"OOPS\");\n d[dotProduct(idx, subsize)] = v;\n return v;\n }\n\n override bool opEquals(Object o) const pure {\n const rhs = to!(M!T)(o);\n return dim == rhs.dim && d == rhs.d;\n }\n\n int opApply(int delegate(ref size_t[]) dg) const {\n size_t[] yieldIdx;\n foreach (immutable i; 0 .. d.length) {\n yieldIdx = seq2idx(i);\n if (dg(yieldIdx))\n break;\n }\n return 0;\n }\n\n int opApply(int delegate(ref size_t[], ref T) dg) {\n size_t idx1d = 0;\n foreach (idx; this) {\n if (dg(idx, d[idx1d++]))\n break;\n }\n return 0;\n }\n\n // _this_ is h, rhs is f, output g.\n M!T convolute(M!T rhs) const pure nothrow {\n auto dm = dim.dup;\n dm[] += rhs.dim[] - 1;\n M!T m = new M!T(dm); // dm will be reused as m's idx.\n auto bound = m.size;\n foreach (immutable i; 0 .. d.length) {\n auto thisIdx = seq2idx(i);\n foreach (immutable j; 0 .. rhs.d.length) {\n dm[] = thisIdx[] + rhs.seq2idx(j)[];\n immutable midx1d = dotProduct(dm, m.subsize);\n if (midx1d < bound)\n m.d[midx1d] += d[i] * rhs.d[j];\n else\n break; // Bound reach, OK to break.\n }\n }\n return m;\n }\n\n // _this_ is g, rhs is f, output is h.\n M!T deconvolute(M!T rhs) const pure nothrow {\n auto dm = dim.dup;\n foreach (i, e; dm)\n assert(e + 1 > rhs.dim[i],\n \"deconv : dimensions is zero or negative\");\n dm[] -= (rhs.dim[] - 1);\n auto m = new M!T(dm); // dm will be reused as rhs' idx.\n\n foreach (immutable i; 0 .. m.size) {\n auto idx = m.seq2idx(i);\n m.d[i] = this[idx];\n foreach (immutable j; 0 .. i) {\n immutable jdx = m.seq2idx(j);\n dm[] = idx[] - jdx[];\n if (rhs.checkBound(dm))\n m.d[i] -= m.d[j] * rhs[dm];\n }\n m.d[i] /= rhs.d[0];\n }\n return m;\n }\n\n override string toString() const pure { return d.text; }\n}\n\nauto fold(T)(T[] arr, ref size_t[] d) pure {\n if (d.length == 0)\n d ~= arr.length;\n\n static if (is(T U : U[])) { // Is arr an array of arrays?\n assert(arr.length > 0, \"no empty dimension\");\n d ~= arr[0].length;\n foreach (e; arr)\n assert(e.length == arr[0].length, \"Not rectangular\");\n return fold(arr.reduce!q{a ~ b}, d);\n } else {\n assert(arr.length == d.reduce!q{a * b}, \"Not same size\");\n return arr;\n }\n}\n\nauto arr2M(T)(T a) pure {\n size_t[] dm;\n auto d = fold(a, dm);\n alias E = ElementType!(typeof(d));\n auto m = new M!E(dm);\n m.set1DArray(d);\n return m;\n}\n\nvoid main() {\n alias Mi = M!int;\n auto hh = [[[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]],\n [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]];\n auto ff = [[[-9, 5, -8], [3, 5, 1]],[[-1, -7, 2], [-5, -6, 6]],\n [[8, 5, 8],[-2, -6, -4]]];\n auto h = arr2M(hh);\n auto f = arr2M(ff);\n\n const g = h.convolute(f);\n\n writeln(\"g == f convolute h ? \", g == f.convolute(h));\n writeln(\"h == g deconv f ? \", h == g.deconvolute(f));\n writeln(\"f == g deconv h ? \", f == g.deconvolute(h));\n writeln(\" f = \", f);\n writeln(\"g deconv h = \", g.deconvolute(h));\n}\n", "language": "D" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/cmplx\"\n)\n\nfunc fft(buf []complex128, n int) {\n out := make([]complex128, n)\n copy(out, buf)\n fft2(buf, out, n, 1)\n}\n\nfunc fft2(buf, out []complex128, n, step int) {\n if step < n {\n fft2(out, buf, n, step*2)\n fft2(out[step:], buf[step:], n, step*2)\n for j := 0; j < n; j += 2 * step {\n fj, fn := float64(j), float64(n)\n t := cmplx.Exp(-1i*complex(math.Pi, 0)*complex(fj, 0)/complex(fn, 0)) * out[j+step]\n buf[j/2] = out[j] + t\n buf[(j+n)/2] = out[j] - t\n }\n }\n}\n\n/* pad slice length to power of two */\nfunc padTwo(g []float64, le int, ns *int) []complex128 {\n n := 1\n if *ns != 0 {\n n = *ns\n } else {\n for n < le {\n n *= 2\n }\n }\n buf := make([]complex128, n)\n for i := 0; i < le; i++ {\n buf[i] = complex(g[i], 0)\n }\n *ns = n\n return buf\n}\n\nfunc deconv(g []float64, lg int, f []float64, lf int, out []float64, rowLe int) {\n ns := 0\n g2 := padTwo(g, lg, &ns)\n f2 := padTwo(f, lf, &ns)\n fft(g2, ns)\n fft(f2, ns)\n h := make([]complex128, ns)\n for i := 0; i < ns; i++ {\n h[i] = g2[i] / f2[i]\n }\n fft(h, ns)\n for i := 0; i < ns; i++ {\n if math.Abs(real(h[i])) < 1e-10 {\n h[i] = 0\n }\n }\n for i := 0; i > lf-lg-rowLe; i-- {\n out[-i] = real(h[(i+ns)%ns] / 32)\n }\n}\n\nfunc unpack2(m [][]float64, rows, le, toLe int) []float64 {\n buf := make([]float64, rows*toLe)\n for i := 0; i < rows; i++ {\n for j := 0; j < le; j++ {\n buf[i*toLe+j] = m[i][j]\n }\n }\n return buf\n}\n\nfunc pack2(buf []float64, rows, fromLe, toLe int, out [][]float64) {\n for i := 0; i < rows; i++ {\n for j := 0; j < toLe; j++ {\n out[i][j] = buf[i*fromLe+j] / 4\n }\n }\n}\n\nfunc deconv2(g [][]float64, rowG, colG int, f [][]float64, rowF, colF int, out [][]float64) {\n g2 := unpack2(g, rowG, colG, colG)\n f2 := unpack2(f, rowF, colF, colG)\n ff := make([]float64, (rowG-rowF+1)*colG)\n deconv(g2, rowG*colG, f2, rowF*colG, ff, colG)\n pack2(ff, rowG-rowF+1, colG, colG-colF+1, out)\n}\n\nfunc unpack3(m [][][]float64, x, y, z, toY, toZ int) []float64 {\n buf := make([]float64, x*toY*toZ)\n for i := 0; i < x; i++ {\n for j := 0; j < y; j++ {\n for k := 0; k < z; k++ {\n buf[(i*toY+j)*toZ+k] = m[i][j][k]\n }\n }\n }\n return buf\n}\n\nfunc pack3(buf []float64, x, y, z, toY, toZ int, out [][][]float64) {\n for i := 0; i < x; i++ {\n for j := 0; j < toY; j++ {\n for k := 0; k < toZ; k++ {\n out[i][j][k] = buf[(i*y+j)*z+k] / 4\n }\n }\n }\n}\n\nfunc deconv3(g [][][]float64, gx, gy, gz int, f [][][]float64, fx, fy, fz int, out [][][]float64) {\n g2 := unpack3(g, gx, gy, gz, gy, gz)\n f2 := unpack3(f, fx, fy, fz, gy, gz)\n ff := make([]float64, (gx-fx+1)*gy*gz)\n deconv(g2, gx*gy*gz, f2, fx*gy*gz, ff, gy*gz)\n pack3(ff, gx-fx+1, gy, gz, gy-fy+1, gz-fz+1, out)\n}\n\nfunc main() {\n f := [][][]float64{\n {{-9, 5, -8}, {3, 5, 1}},\n {{-1, -7, 2}, {-5, -6, 6}},\n {{8, 5, 8}, {-2, -6, -4}},\n }\n fx, fy, fz := len(f), len(f[0]), len(f[0][0])\n\n g := [][][]float64{\n {{54, 42, 53, -42, 85, -72}, {45, -170, 94, -36, 48, 73},\n {-39, 65, -112, -16, -78, -72}, {6, -11, -6, 62, 49, 8}},\n {{-57, 49, -23, 52, -135, 66}, {-23, 127, -58, -5, -118, 64},\n {87, -16, 121, 23, -41, -12}, {-19, 29, 35, -148, -11, 45}},\n {{-55, -147, -146, -31, 55, 60}, {-88, -45, -28, 46, -26, -144},\n {-12, -107, -34, 150, 249, 66}, {11, -15, -34, 27, -78, -50}},\n {{56, 67, 108, 4, 2, -48}, {58, 67, 89, 32, 32, -8},\n {-42, -31, -103, -30, -23, -8}, {6, 4, -26, -10, 26, 12},\n },\n }\n gx, gy, gz := len(g), len(g[0]), len(g[0][0])\n\n h := [][][]float64{\n {{-6, -8, -5, 9}, {-7, 9, -6, -8}, {2, -7, 9, 8}},\n {{7, 4, 4, -6}, {9, 9, 4, -4}, {-3, 7, -2, -3}},\n }\n hx, hy, hz := gx-fx+1, gy-fy+1, gz-fz+1\n\n h2 := make([][][]float64, hx)\n for i := 0; i < hx; i++ {\n h2[i] = make([][]float64, hy)\n for j := 0; j < hy; j++ {\n h2[i][j] = make([]float64, hz)\n }\n }\n deconv3(g, gx, gy, gz, f, fx, fy, fz, h2)\n fmt.Println(\"deconv3(g, f):\\n\")\n for i := 0; i < hx; i++ {\n for j := 0; j < hy; j++ {\n for k := 0; k < hz; k++ {\n fmt.Printf(\"% .10g \", h2[i][j][k])\n }\n fmt.Println()\n }\n if i < hx-1 {\n fmt.Println()\n }\n }\n\n kx, ky, kz := gx-hx+1, gy-hy+1, gz-hz+1\n f2 := make([][][]float64, kx)\n for i := 0; i < kx; i++ {\n f2[i] = make([][]float64, ky)\n for j := 0; j < ky; j++ {\n f2[i][j] = make([]float64, kz)\n }\n }\n deconv3(g, gx, gy, gz, h, hx, hy, hz, f2)\n fmt.Println(\"\\ndeconv(g, h):\\n\")\n for i := 0; i < kx; i++ {\n for j := 0; j < ky; j++ {\n for k := 0; k < kz; k++ {\n fmt.Printf(\"% .10g \", f2[i][j][k])\n }\n fmt.Println()\n }\n if i < kx-1 {\n fmt.Println()\n }\n }\n}\n", "language": "Go" }, { "code": "deconv3 =: 4 : 0\n sz =. x >:@-&$ y NB. shape of z\n poi =. ,<\"1 ($y) ,\"0/&(,@i.) sz NB. pair of indexes\n t=. /: sc=: , <@(+\"1)/&(#: ,@i.)/ ($y),:sz NB. order of ,y\n T0=. (<\"0,x) ,:~ (]/:\"1 {.)&.> (<, y) ({:@] ,: ({\"1~ {.))&.> sc <@|:@:>/.&(t&{) poi NB. set of boxed equations\n T1=. (,x),.~(<0 #~ */sz) (({:@])`({.@])`[})&> {.T0 NB. set of linear equations\n sz $ 1e_8 round ({:\"1 %. }:\"1) T1\n)\nround=: [ * <.@%~\n", "language": "J" }, { "code": "h1=: _8 2 _9 _2 9 _8 _2\nf1=: 6 _9 _7 _5\ng1=: _48 84 _16 95 125 _70 7 29 54 10\n\nh2=: \".;._2]0 :0\n _8 1 _7 _2 _9 4\n 4 5 _5 2 7 _1\n _6 _3 _3 _6 9 5\n)\n\nf2=: \".;._2]0 :0\n _5 2 _2 _6 _7\n 9 7 _6 5 _7\n 1 _1 9 2 _7\n 5 9 _9 2 _5\n _8 5 _2 8 5\n)\n\ng2=: \".;._2]0 :0\n 40 _21 53 42 105 1 87 60 39 _28\n _92 _64 19 _167 _71 _47 128 _109 40 _21\n 58 85 _93 37 101 _14 5 37 _76 _56\n _90 _135 60 _125 68 53 223 4 _36 _48\n 78 16 7 _199 156 _162 29 28 _103 _10\n _62 _89 69 _61 66 193 _61 71 _8 _30\n 48 _6 21 _9 _150 _22 _56 32 85 25\n)\n\nh3=: \".;._1;._2]0 :0\n/ _6 _8 _5 9/ _7 9 _6 _8/ 2 _7 9 8\n/ 7 4 4 _6/ 9 9 4 _4/ _3 7 _2 _3\n)\n\nf3=: \".;._1;._2]0 :0\n/ _9 5 _8/ 3 5 1\n/ _1 _7 2/ _5 _6 6\n/ 8 5 8/_2 _6 _4\n)\n\ng3=: \".;._2;._1]0 :0\n/ 54 42 53 _42 85 _72\n 45 _170 94 _36 48 73\n _39 65 _112 _16 _78 _72\n 6 _11 _6 62 49 8\n/ _57 49 _23 52 _135 66\n _23 127 _58 _5 _118 64\n 87 _16 121 23 _41 _12\n _19 29 35 _148 _11 45\n/ _55 _147 _146 _31 55 60\n _88 _45 _28 46 _26 _144\n _12 _107 _34 150 249 66\n 11 _15 _34 27 _78 _50\n/ 56 67 108 4 2 _48\n 58 67 89 32 32 _8\n _42 _31 _103 _30 _23 _8\n 6 4 _26 _10 26 12\n)\n", "language": "J" }, { "code": " h1 -: g1 deconv3 f1\n1\n h2 -: g2 deconv3 f2\n1\n h3 -: g3 deconv3 f3 NB. -: checks for matching structure and data\n1\n", "language": "J" }, { "code": "using FFTW, DSP\n\nconst h1 = [-8, 2, -9, -2, 9, -8, -2]\nconst f1 = [ 6, -9, -7, -5]\nconst g1 = [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10]\n\nconst h2nested = [\n [-8, 1, -7, -2, -9, 4],\n [4, 5, -5, 2, 7, -1],\n [-6, -3, -3, -6, 9, 5]]\nconst f2nested = [\n [-5, 2, -2, -6, -7],\n [9, 7, -6, 5, -7],\n [1, -1, 9, 2, -7],\n [5, 9, -9, 2, -5],\n [-8, 5, -2, 8, 5]]\nconst g2nested = [\n [40, -21, 53, 42, 105, 1, 87, 60, 39, -28],\n [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21],\n [58, 85, -93, 37, 101, -14, 5, 37, -76, -56],\n [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48],\n [78, 16, 7, -199, 156, -162, 29, 28, -103, -10],\n [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30],\n [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]]\n\nconst h3nested = [\n [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]],\n [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]\nconst f3nested = [\n [[-9, 5, -8], [3, 5, 1]],\n [[-1, -7, 2], [-5, -6, 6]],\n [[8, 5, 8],[-2, -6, -4]]]\nconst g3nested = [\n [ [54, 42, 53, -42, 85, -72],\n [45, -170, 94, -36, 48, 73],\n [-39, 65, -112, -16, -78, -72],\n [6, -11, -6, 62, 49, 8]],\n [ [-57, 49, -23, 52, -135, 66],\n [-23, 127, -58, -5, -118, 64],\n [87, -16, 121, 23, -41, -12],\n [-19, 29, 35, -148, -11, 45]],\n [ [-55, -147, -146, -31, 55, 60],\n [-88, -45, -28, 46, -26, -144],\n [-12, -107, -34, 150, 249, 66],\n [11, -15, -34, 27, -78, -50]],\n [ [56, 67, 108, 4, 2, -48],\n [58, 67, 89, 32, 32, -8],\n [-42, -31, -103, -30, -23, -8],\n [6, 4, -26, -10, 26, 12]]]\n\nfunction flatnested2d(a, siz)\n ret = zeros(Int, prod(siz))\n for i in 1:length(a), j in 1:length(a[1])\n ret[siz[2] * (i - 1) + j] = a[i][j]\n end\n Float64.(ret)\nend\n\nfunction flatnested3d(a, siz)\n ret = zeros(Int, prod(siz))\n for i in 1:length(a), j in 1:length(a[1]), k in 1:length(a[1][1])\n ret[siz[2] * siz[3] * (i - 1) + siz[3] * (j - 1) + k] = a[i][j][k]\n end\n Float64.(ret)\nend\n\ntopow2(siz) = map(x -> nextpow(2, x), siz)\ndeconv1d(f1, g1) = Int.(round.(deconv(Float64.(g1), Float64.(f1))))\n\nfunction deconv2d(f2, g2, xd2)\n siz = topow2([length(g2), length(g2[1])])\n h2 = Int.(round.(real.(ifft(fft(flatnested2d(g2, siz)) ./ fft(flatnested2d(f2, siz))))))\n [[h2[siz[2] * (i - 1) + j] for j in 1:xd2[2]] for i in 1:xd2[1]]\nend\n\nfunction deconv3d(f3, g3, xd3)\n siz = topow2([length(g3), length(g3[1]), length(g3[1][1])])\n h3 = Int.(round.(real.(ifft(fft(flatnested3d(g3, siz)) ./ fft(flatnested3d(f3, siz))))))\n [[[h3[siz[2] * siz[3] *(i - 1) + siz[3] * (j - 1) + k] for k in 1:xd3[3]]\n for j in 1:xd3[2]] for i in 1:xd3[1]]\nend\n\ndeconvn(f, g, tup=()) = length(tup) < 2 ? deconv1d(f, g) :\n length(tup) == 2 ? deconv2d(f, g, tup) :\n length(tup) == 3 ? deconv3d(f, g, tup) :\n println(\"Array nesting > 3D not supported\")\n\ndeconvn(f1, g1) # 1D\ndeconvn(f2nested, g2nested, (length(h2nested), length(h2nested[1]))) # 2D\nprintln(deconvn(f3nested, g3nested,\n (length(h3nested), length(h3nested[1]), length(h3nested[1][1])))) # 3D\n", "language": "Julia" }, { "code": "Round[ListDeconvolve[{6, -9, -7, -5}, {-48, 84, -16, 95, 125, -70, 7, 29, 54, 10}, Method -> \"Wiener\"]]\n\nRound[ListDeconvolve[{{-5, 2, -2, -6, -7}, {9, 7, -6, 5, -7}, {1, -1, 9, 2, -7}, {5, 9, -9, 2, -5}, {-8, 5, -2, 8, 5}},\n{{40, -21, 53, 42, 105, 1, 87, 60, 39, -28}, {-92, -64, 19, -167, -71, -47, 128, -109, 40, -21},\n{58, 85, -93, 37, 101, -14, 5, 37, -76, -56}, {-90, -135, 60, -125, 68, 53, 223, 4, -36, -48},\n{78, 16, 7, -199, 156, -162, 29, 28, -103, -10}, {-62, -89, 69, -61, 66, 193, -61, 71, -8, -30},\n{48, -6, 21, -9, -150, -22, -56, 32, 85, 25}}, Method -> \"Wiener\"]]\n\nRound[ListDeconvolve [{{{-9, 5, -8}, {3, 5, 1}}, {{-1, -7, 2}, {-5, -6, 6}}, {{8, 5, 8}, {-2, -6, -4}}},\n{{{54, 42, 53, -42, 85, -72}, {45, -170, 94, -36, 48, 73}, {-39, 65, -112, -16, -78, -72},\n{6, -11, -6, 62, 49, 8}}, {{-57, 49, -23, 52, -135, 66}, {-23, 127, -58, -5, -118, 64}, {87, -16, 121, 23, -41, -12},\n{-19, 29, 35, -148, -11, 45}}, {{-55, -147, -146, -31, 55, 60}, {-88, -45, -28, 46, -26, -144},\n{-12, -107, -34, 150, 249, 66}, {11, -15, -34, 27, -78, -50}}, {{56, 67, 108, 4, 2, -48}, {58, 67, 89, 32, 32, -8},\n{-42, -31, -103, -30, -23, -8}, {6, 4, -26, -10, 26, 12}}}, Method -> \"Wiener\"]]\n", "language": "Mathematica" }, { "code": "import sequtils, typetraits\n\ntype Size = uint64\n\ntype M[T: SomeNumber] = object\n dims: seq[Size]\n subsizes: seq[Size]\n data: seq[T]\n\n####################################################################################################\n# Miscellaneous.\n\nfunc dotProduct[T: SomeNumber](a, b: openArray[T]): T =\n assert a.len == b.len\n for i in 0..a.high:\n result += a[i] * b[i]\n\n\n####################################################################################################\n# Operations on M objects.\n\nfunc setDimensions(m: var M; dimensions: varargs[Size]) =\n\n for dim in dimensions:\n if dim == 0:\n raise newException(IndexDefect, \"wrong dimension: 0\")\n\n m.dims = @dimensions\n m.subsizes = m.dims\n for i in 0..dimensions.high:\n m.subsizes[i] = m.dims[(i+1)..^1].foldl(a * b, Size(1))\n\n let dlength = m.dims[0] * m.subsizes[0]\n if Size(m.data.len) != dlength:\n m.data.setLen(dlength)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc initM(m: var M; dimensions: varargs[Size]) =\n m.setDimensions(dimensions)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc set1DArray(m: var M; t: varargs[m.T]) =\n\n let minLen = min(m.data.len, t.len)\n m.data.setLen(minLen)\n m.data[0..<minLen] = t[0..<minLen]\n\n#---------------------------------------------------------------------------------------------------\n\nfunc seqToIdx(m: M; s: Size): seq[Size] =\n\n var acc = s\n for subsize in m.subsizes:\n result.add(acc div subsize)\n acc = acc mod subsize\n\n#---------------------------------------------------------------------------------------------------\n\ntemplate size(m: M): Size = Size(m.data.len)\n\n#---------------------------------------------------------------------------------------------------\n\nfunc checkBounds(m: M; indexes: varargs[Size]): bool =\n\n if indexes.len > m.dims.len:\n return false\n\n for i, dim in indexes:\n if dim >= m.dims[i]:\n return false\n\n result = true\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `[]`(m: M; indexes: varargs[Size]): m.T =\n\n if not m.checkBounds(indexes):\n raise newException(IndexDefect, \"index out of range: \" & $indexes)\n\n m.data[dotProduct(indexes, m.subsizes)]\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `[]=`(m: M; indexes: varargs[int]; val: m.T) =\n\n if not m.checkBounds(indexes):\n raise newException(IndexDefect, \"index out of range: \" & $indexes)\n\n m.data[dotProduct(indexes, m.subsizes)] = val\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `==`(a, b: M): bool = a.dims == b.dims and a.data == b.data\n\n#---------------------------------------------------------------------------------------------------\n\nfunc `$`(m: M): string = $m.data\n\n\n####################################################################################################\n# Convolution/deconvolution.\n\nfunc convolute(h, f: M): M =\n ## Result is \"g\".\n\n var dims = h.dims\n for i in 0..dims.high:\n dims[i] += f.dims[i] - 1\n result.initM(dims)\n\n let bound = result.size\n for i in 0..<h.size:\n let hIndexes = h.seqToIdx(i)\n\n for j in 0..<f.size:\n let fIndexes = f.seqToIdx(j)\n for k in 0..dims.high:\n dims[k] = hIndexes[k] + fIndexes[k]\n let idx1d = dotProduct(dims, result.subsizes)\n if idx1d < bound:\n result.data[idx1d] += h.data[i] * f.data[j]\n else:\n break # Bound reached.\n\n#---------------------------------------------------------------------------------------------------\n\nfunc deconvolute(g, f: M): M =\n ## Result is \"h\".\n\n var dims = g.dims\n for i, d in dims:\n if d + 1 <= f.dims[i]:\n raise newException(IndexDefect, \"a dimension is zero or negative\")\n\n for i in 0..dims.high:\n dims[i] -= f.dims[i] - 1\n result.initM(dims)\n\n for i in 0..<result.size:\n let iIndexes = result.seqToIdx(i)\n result.data[i] = g[iIndexes]\n\n for j in 0..<i:\n let jIndexes = result.seqToIdx(j)\n for k in 0..dims.high:\n dims[k] = iIndexes[k] - jIndexes[k]\n if f.checkBounds(dims):\n result.data[i] -= result.data[j] * f[dims]\n\n when result.T is SomeInteger:\n result.data[i] = result.data[i] div f.data[0]\n else:\n result.data[i] /= f.data[0]\n\n\n####################################################################################################\n# Transformation of a sequence into an M object.\n\nfunc fold[T](a: seq[T]; d: var seq[Size]): auto =\n\n if d.len == 0:\n d.add(Size(a.len))\n\n when a.elementType is seq:\n if a.len == 0:\n raise newException(ValueError, \"empty dimension\")\n d.add(Size(a[0].len))\n for elem in a:\n if elem.len != a[0].len:\n raise newException(ValueError, \"not rectangular\")\n result = fold(a.foldl(a & b), d)\n\n else:\n if Size(a.len) != d.foldl(a * b):\n raise newException(ValueError, \"not same size\")\n result = a\n\n#---------------------------------------------------------------------------------------------------\n\nfunc arrtoM[T](a: T): auto =\n\n var dims: seq[Size]\n let d = fold(a, dims)\n var res: M[d.elementType]\n res.initM(dims)\n res.set1DArray(d)\n return res\n\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nconst H = @[ @[ @[-6, -8, -5, 9], @[-7, 9, -6, -8], @[ 2, -7, 9, 8] ],\n @[ @[ 7, 4, 4, -6], @[ 9, 9, 4, -4], @[-3, 7, -2, -3] ] ]\n\nconst F = @[ @[ @[-9, 5, -8], @[ 3, 5, 1] ],\n @[ @[-1, -7, 2], @[-5, -6, 6] ],\n @[ @[ 8, 5, 8], @[-2, -6, -4] ] ]\n\nlet h = arrToM(H)\nlet f = arrToM(F)\n\nlet g = h.convolute(f)\n\necho \"g == f convolute h ? \", g == f.convolute(h)\necho \"h == g deconv f ? \", h == g.deconvolute(f)\necho \"f == g deconv h ? \", f == g.deconvolute(h)\necho \" f = \", f\necho \"g deconv f = \", g.deconvolute(h)\n", "language": "Nim" }, { "code": "use feature 'say';\nuse ntheory qw/forsetproduct/;\n\n# Deconvolution of N dimensional matrices\nsub deconvolve_N {\n our @g; local *g = shift;\n our @f; local *f = shift;\n my @df = shape(@f);\n my @dg = shape(@g);\n my @hsize;\n push @hsize, $dg[$_] - $df[$_] + 1 for 0..$#df;\n my @toSolve = map { [row(\\@g, \\@f, \\@hsize, $_)] } coords(shape(@g));\n rref( \\@toSolve );\n\n my @h;\n my $n = 0;\n for (coords(@hsize)) {\n my($k,$j,$i) = split ' ', $_;\n $h[$i][$j][$k] = $toSolve[$n++][-1];\n }\n @h;\n}\n\nsub row {\n our @g; local *g = shift;\n our @f; local *f = shift;\n our @hsize; local *hsize = shift;\n my @gc = reverse split ' ', shift;\n\n my @row;\n my @fdim = shape(@f);\n for (coords(@hsize)) {\n my @hc = reverse split ' ', $_;\n my @fc;\n for my $i (0..$#hc) {\n my $window = $gc[$i] - $hc[$i];\n push(@fc, $window), next if 0 <= $window && $window < $fdim[$i];\n }\n push @row, $#fc == $#hc ? $f [$fc[0]] [$fc[1]] [$fc[2]] : 0;\n }\n push @row, $g [$gc[0]] [$gc[1]] [$gc[2]];\n return @row;\n}\n\nsub rref {\n our @m; local *m = shift;\n @m or return;\n my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]}));\n\n foreach my $r (0 .. $rows - 1) {\n $lead < $cols or return;\n my $i = $r;\n\n until ($m[$i][$lead])\n {++$i == $rows or next;\n $i = $r;\n ++$lead == $cols and return;}\n\n @m[$i, $r] = @m[$r, $i];\n my $lv = $m[$r][$lead];\n $_ /= $lv foreach @{ $m[$r] };\n\n my @mr = @{ $m[$r] };\n foreach my $i (0 .. $rows - 1)\n {$i == $r and next;\n ($lv, my $n) = ($m[$i][$lead], -1);\n $_ -= $lv * $mr[++$n] foreach @{ $m[$i] };}\n\n ++$lead;}\n}\n\n# Constructs an AoA of coordinates to all elements of N dimensional array\nsub coords {\n my(@dimensions) = reverse @_;\n my(@ranges,@coords);\n push @ranges, [0..$_-1] for @dimensions;\n forsetproduct { push @coords, \"@_\" } @ranges;\n @coords;\n}\n\nsub shape {\n my(@dim);\n push @dim, scalar @_;\n push @dim, shape(@{$_[0]}) if 'ARRAY' eq ref $_[0];\n @dim;\n}\n\n# Pretty printer for N dimensional arrays\n# Assumes if first element in level is an array, then all are\nsub pretty_print {\n my($i, @a) = @_;\n if ('ARRAY' eq ref $a[0]) {\n say ' 'x$i, '[';\n pretty_print($i+2, @$_) for @a;\n say ' 'x$i, ']', $i ? ',' : '';\n } else {\n say ' 'x$i, '[', sprintf(\"@{['%5s'x@a]}\",@a), ']', $i ? ',' : '';\n }\n}\n\nmy @f = (\n [\n [ -9, 5, -8 ],\n [ 3, 5, 1 ],\n ],\n [\n [ -1, -7, 2 ],\n [ -5, -6, 6 ],\n ],\n [\n [ 8, 5, 8 ],\n [ -2, -6, -4 ],\n ]\n);\n\nmy @g = (\n [\n [ 54, 42, 53, -42, 85, -72 ],\n [ 45,-170, 94, -36, 48, 73 ],\n [ -39, 65,-112, -16, -78, -72 ],\n [ 6, -11, -6, 62, 49, 8 ],\n ],\n [\n [ -57, 49, -23, 52,-135, 66 ],\n [ -23, 127, -58, -5,-118, 64 ],\n [ 87, -16, 121, 23, -41, -12 ],\n [ -19, 29, 35,-148, -11, 45 ],\n ],\n [\n [ -55,-147,-146, -31, 55, 60 ],\n [ -88, -45, -28, 46, -26,-144 ],\n [ -12,-107, -34, 150, 249, 66 ],\n [ 11, -15, -34, 27, -78, -50 ],\n ],\n [\n [ 56, 67, 108, 4, 2, -48 ],\n [ 58, 67, 89, 32, 32, -8 ],\n [ -42, -31,-103, -30, -23, -8 ],\n [ 6, 4, -26, -10, 26, 12 ],\n ]\n);\n\nmy @h = deconvolve_N( \\@g, \\@f );\nmy @ff = deconvolve_N( \\@g, \\@h );\n\nmy $d = scalar shape(@g);\nprint \"${d}D arrays:\\n\";\nprint \"h =\\n\";\npretty_print(0,@h);\nprint \"\\nff =\\n\";\npretty_print(0,@ff);\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">-- demo\\rosetta\\Deconvolution.exw</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #000000;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">m_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">--\n -- returns the size of a matrix as a list of lengths\n --</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">me</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">m</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004080;\">sequence</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">me</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">me</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">me</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">me</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">make_coordset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">size</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">--\n -- returns all points in the matrix, in zero-based indexes,\n -- eg {{0,0,0}..{3,3,5}} for a 4x4x6 matrix [96 in total]\n --</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">product</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">size</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">coords</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">j</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">i</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">size</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">dimension</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">size</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">coords</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">dimension</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">j</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">dimension</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">coords</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">reverse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">coords</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">coords</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">row</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">gs</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">gc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">fs</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">hs</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">--\n --# Assembles a row, which is one of the simultaneous equations that needs\n --# to be solved by reducing the whole set to reduced row echelon form. Note\n --# that each row describes the equation for a single cell of the 'g' function.\n --#\n --# Arguments:\n --# g The \"result\" matrix of the convolution being undone.\n --# h The known \"input\" matrix of the convolution being undone.\n --# gs The size descriptor of 'g', passed as argument for efficiency.\n --# gc The coordinate in 'g' that we are generating the equation for.\n --# fs The size descriptor of 'f', passed as argument for efficiency.\n --# hs The size descriptor of 'h' (the unknown \"input\" matrix), passed\n --# as argument for efficiency.\n --</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">row</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span>\n <span style=\"color: #000000;\">coords</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">make_coordset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hs</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">coords</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">hc</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">coords</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">fn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">f</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">gc</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">gc</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]-</span><span style=\"color: #000000;\">hc</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">fs</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">fn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">fn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">row</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">row</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">gn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">g</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">gc</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">gn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">gn</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">gc</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">row</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">row</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">gn</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">row</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">toRREF</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">--\n -- [renamed] copy of Reduced_row_echelon_form.htm#Phix\n -- plus one small tweak, as noted below, exit-&gt;return,\n -- not that said seems to make any actual difference.\n --</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">lead</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">rows</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">cols</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">rows</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">lead</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">cols</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">r</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">lead</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">rows</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">r</span>\n <span style=\"color: #000000;\">lead</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000080;font-style:italic;\">-- if lead=cols then exit end if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">lead</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">cols</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">m</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">mi</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">]),</span>\n <span style=\"color: #000000;\">mr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_div</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">lead</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">mi</span>\n <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">mr</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">rows</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">r</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_sub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #7060A8;\">sq_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">lead</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">]))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">lead</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">m</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">lset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">idx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- helper routine: store v somewhere deep inside h</span>\n <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">idx</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">idx</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">v</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">lset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i1</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">idx</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">..$],</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">h</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">deconvolve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">--\n --# Deconvolve a pair of matrixes. Solves for 'h' such that 'g = f convolve h'.\n --#\n --# Arguments:\n --# g The matrix of data to be deconvolved.\n --# f The matrix describing the convolution to be removed.\n --\n -- Compute the sizes of the various matrixes involved.</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">gsize</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">m_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">fsize</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">m_size</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">hsize</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_sub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">gsize</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">fsize</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- Prepare the set of simultaneous equations to solve</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">toSolve</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span>\n <span style=\"color: #000000;\">coords</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">make_coordset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">gsize</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">coords</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">toSolve</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">toSolve</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">row</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">gsize</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">coords</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">fsize</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">hsize</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- Solve the equations</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">solved</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">toRREF</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">toSolve</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- Create a result matrix of the right size</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hsize</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">hsize</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- Fill the results from the equations into the result matrix</span>\n <span style=\"color: #000000;\">coords</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">make_coordset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hsize</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">coords</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">lset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">coords</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">solved</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][$])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">h</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">f1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #000000;\">g1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">48</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">84</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">95</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">125</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">70</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">29</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">54</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #000000;\">h1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">}</span>\n\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">deconvolve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">f1</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">h1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">deconvolve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">h1</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">f1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">f2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{-</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #000000;\">g2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span> <span style=\"color: #000000;\">40</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">21</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">53</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">42</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">105</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">87</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">60</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">39</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">28</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">92</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">64</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">19</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">167</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">71</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">47</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">128</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">109</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">40</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">21</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">58</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">85</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">93</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">37</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">101</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">14</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">37</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">76</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">56</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">90</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">135</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">60</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">125</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">68</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">53</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">223</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">36</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">48</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">78</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">199</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">156</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">162</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">29</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">28</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">103</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">62</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">89</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">69</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">61</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">66</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">193</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">61</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">71</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">30</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">48</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">21</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">150</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">22</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">56</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">32</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">85</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">25</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #000000;\">h2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">}}</span>\n\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">deconvolve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">f2</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">h2</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">deconvolve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">h2</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">f2</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">f3</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{{-</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">}}},</span>\n <span style=\"color: #000000;\">g3</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{{</span> <span style=\"color: #000000;\">54</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">42</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">53</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">42</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">85</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">72</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">45</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">170</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">94</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">36</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">48</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">73</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">39</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">65</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">112</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">78</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">72</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">62</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">49</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{-</span><span style=\"color: #000000;\">57</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">49</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">23</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">52</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">135</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">66</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">23</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">127</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">58</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">118</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">64</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">87</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">16</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">121</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">23</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">41</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">19</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">29</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">35</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">148</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">45</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{-</span><span style=\"color: #000000;\">55</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">147</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">146</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">31</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">55</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">60</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">88</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">45</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">28</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">46</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">26</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">144</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">107</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">34</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">150</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">249</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">66</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">15</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">34</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">27</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">78</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">50</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span> <span style=\"color: #000000;\">56</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">67</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">108</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">48</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">58</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">67</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">89</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">32</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">32</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">42</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">31</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">103</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">30</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">23</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">26</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">26</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">}}},</span>\n <span style=\"color: #000000;\">h3</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{{</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #0000FF;\">{{</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">}}}</span>\n\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">deconvolve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">f3</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">h3</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">deconvolve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">h3</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">f3</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #7060A8;\">ppOpt</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #004600;\">pp_Nest</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">pp_IntFmt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%3d\"</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">pp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">deconvolve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">f3</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">pp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">deconvolve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">h3</span><span style=\"color: #0000FF;\">))</span>\n<!--\n", "language": "Phix" }, { "code": "\"\"\"\n\nhttps://rosettacode.org/wiki/Deconvolution/2D%2B\n\nWorking on 3 dimensional example using test data from the\nRC task.\n\nPython fft:\n\nhttps://docs.scipy.org/doc/numpy/reference/routines.fft.html\n\n\"\"\"\n\nimport numpy\nimport pprint\n\nh = [\n [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]],\n [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]\nf = [\n [[-9, 5, -8], [3, 5, 1]],\n [[-1, -7, 2], [-5, -6, 6]],\n [[8, 5, 8],[-2, -6, -4]]]\ng = [\n [\n [54, 42, 53, -42, 85, -72],\n [45, -170, 94, -36, 48, 73],\n [-39, 65, -112, -16, -78, -72],\n [6, -11, -6, 62, 49, 8]],\n [\n [-57, 49, -23, 52, -135, 66],\n [-23, 127, -58, -5, -118, 64],\n [87, -16, 121, 23, -41, -12],\n [-19, 29, 35, -148, -11, 45]],\n [\n [-55, -147, -146, -31, 55, 60],\n [-88, -45, -28, 46, -26, -144],\n [-12, -107, -34, 150, 249, 66],\n [11, -15, -34, 27, -78, -50]],\n [\n [56, 67, 108, 4, 2, -48],\n [58, 67, 89, 32, 32, -8],\n [-42, -31, -103, -30, -23, -8],\n [6, 4, -26, -10, 26, 12]]]\n\ndef trim_zero_empty(x):\n \"\"\"\n\n Takes a structure that represents an n dimensional example.\n For a 2 dimensional example it will be a list of lists.\n For a 3 dimensional one it will be a list of list of lists.\n etc.\n\n Actually these are multidimensional numpy arrays but I was thinking\n in terms of lists.\n\n Returns the same structure without trailing zeros in the inner\n lists and leaves out inner lists with all zeros.\n\n \"\"\"\n\n if len(x) > 0:\n if type(x[0]) != numpy.ndarray:\n # x is 1d array\n return list(numpy.trim_zeros(x))\n else:\n # x is a multidimentional array\n new_x = []\n for l in x:\n tl = trim_zero_empty(l)\n if len(tl) > 0:\n new_x.append(tl)\n return new_x\n else:\n # x is empty list\n return x\n\ndef deconv(a, b):\n \"\"\"\n\n Returns function c such that b * c = a.\n\n https://en.wikipedia.org/wiki/Deconvolution\n\n \"\"\"\n\n # Convert larger polynomial using fft\n\n ffta = numpy.fft.fftn(a)\n\n # Get it's shape so fftn will expand\n # smaller polynomial to fit.\n\n ashape = numpy.shape(a)\n\n # Convert smaller polynomial with fft\n # using the shape of the larger one\n\n fftb = numpy.fft.fftn(b,ashape)\n\n # Divide the two in frequency domain\n\n fftquotient = ffta / fftb\n\n # Convert back to polynomial coefficients using ifft\n # Should give c but with some small extra components\n\n c = numpy.fft.ifftn(fftquotient)\n\n # Get rid of imaginary part and round up to 6 decimals\n # to get rid of small real components\n\n trimmedc = numpy.around(numpy.real(c),decimals=6)\n\n # Trim zeros and eliminate\n # empty rows of coefficients\n\n cleanc = trim_zero_empty(trimmedc)\n\n return cleanc\n\nprint(\"deconv(g,h)=\")\n\npprint.pprint(deconv(g,h))\n\nprint(\" \")\n\nprint(\"deconv(g,f)=\")\n\npprint.pprint(deconv(g,f))\n", "language": "Python" }, { "code": "# Deconvolution of N dimensional matrices.\nsub deconvolve-N ( @g, @f ) {\n my @hsize = @g.shape »-« @f.shape »+» 1;\n\n my @toSolve = coords(@g.shape).map:\n { [row(@g, @f, $^coords, @hsize)] };\n\n my @solved = rref( @toSolve );\n\n my @h;\n for flat coords(@hsize) Z @solved[*;*-1] -> $_, $v {\n @h.AT-POS(|$_) = $v;\n }\n @h\n}\n\n# Construct a row for each value in @g to be sent to the simultaneous equation solver\nsub row ( @g, @f, @gcoord, $hsize ) {\n my @row;\n @gcoord = @gcoord[(^@f.shape)]; # clip extraneous values\n for coords( $hsize ) -> @hc {\n my @fcoord;\n for ^@hc -> $i {\n my $window = @gcoord[$i] - @hc[$i];\n @fcoord.push($window) and next if 0 ≤ $window < @f.shape[$i];\n last;\n }\n @row.push: @fcoord == @hc ?? @f.AT-POS(|@fcoord) !! 0;\n }\n @row.push: @g.AT-POS(|@gcoord);\n @row\n}\n\n# Constructs an AoA of coordinates to all elements of N dimensional array\nsub coords ( @dim ) {\n @[reverse $_ for [X] ([^$_] for reverse @dim)]\n}\n\n# Reduced Row Echelon Form simultaneous equation solver\n# Can handle over-specified systems (N unknowns in N + M equations)\nsub rref (@m) {\n @m = trim-system @m;\n my ($lead, $rows, $cols) = 0, @m, @m[0];\n for ^$rows -> $r {\n return @m unless $lead < $cols;\n my $i = $r;\n until @m[$i;$lead] {\n next unless ++$i == $rows;\n $i = $r;\n return @m if ++$lead == $cols;\n }\n @m[$i, $r] = @m[$r, $i] if $r != $i;\n @m[$r] »/=» $ = @m[$r;$lead];\n for ^$rows -> $n {\n next if $n == $r;\n @m[$n] »-=» @m[$r] »×» (@m[$n;$lead] // 0);\n }\n ++$lead;\n }\n @m\n }\n\n# Reduce to N equations in N unknowns; a no-op unless rows > cols\nsub trim-system (@m) {\n return @m unless @m ≥ @m[0];\n my (\\vars, @t) = @m[0] - 1;\n for ^vars -> \\lead {\n for ^@m -> \\row {\n @t.append: @m.splice(row, 1) and last if @m[row;lead];\n }\n }\n while @t < vars and @m { @t.push: shift @m }\n @t\n}\n\n# Pretty printer for N dimensional arrays\n# Assumes if first element in level is an array, then all are\nsub pretty-print ( @array, $indent = 0 ) {\n if @array[0] ~~ Array {\n say ' ' x $indent,\"[\";\n pretty-print( $_, $indent + 2 ) for @array;\n say ' ' x $indent, \"]{$indent??','!!''}\";\n } else {\n say ' ' x $indent, \"[{say_it(@array)} ]{$indent??','!!''}\";\n }\n\n sub say_it ( @array ) { return join \",\", @array».fmt(\"%4s\"); }\n}\n\nmy @f[3;2;3] = (\n [\n [ -9, 5, -8 ],\n [ 3, 5, 1 ],\n ],\n [\n [ -1, -7, 2 ],\n [ -5, -6, 6 ],\n ],\n [\n [ 8, 5, 8 ],\n [ -2, -6, -4 ],\n ]\n);\n\nmy @g[4;4;6] = (\n [\n [ 54, 42, 53, -42, 85, -72 ],\n [ 45,-170, 94, -36, 48, 73 ],\n [ -39, 65,-112, -16, -78, -72 ],\n [ 6, -11, -6, 62, 49, 8 ],\n ],\n [\n [ -57, 49, -23, 52,-135, 66 ],\n [ -23, 127, -58, -5,-118, 64 ],\n [ 87, -16, 121, 23, -41, -12 ],\n [ -19, 29, 35,-148, -11, 45 ],\n ],\n [\n [ -55,-147,-146, -31, 55, 60 ],\n [ -88, -45, -28, 46, -26,-144 ],\n [ -12,-107, -34, 150, 249, 66 ],\n [ 11, -15, -34, 27, -78, -50 ],\n ],\n [\n [ 56, 67, 108, 4, 2, -48 ],\n [ 58, 67, 89, 32, 32, -8 ],\n [ -42, -31,-103, -30, -23, -8 ],\n [ 6, 4, -26, -10, 26, 12 ],\n ]\n);\n\nsay \"# {[email protected]}D array:\";\nmy @h = deconvolve-N( @g, @f );\nsay \"h =\";\npretty-print( @h );\nmy @h-shaped[2;3;4] = @(deconvolve-N( @g, @f ));\nmy @ff = deconvolve-N( @g, @h-shaped );\nsay \"\\nff =\";\npretty-print( @ff );\n", "language": "Raku" }, { "code": "package require Tcl 8.5\nnamespace path {::tcl::mathfunc ::tcl::mathop}\n\n# Utility to extract the number of dimensions of a matrix\nproc rank m {\n for {set rank 0} {[llength $m] > 1} {incr rank} {\n\tset m [lindex $m 0]\n }\n return $rank\n}\n\n# Utility to get the size of a matrix, as a list of lengths\nproc size m {\n set r [rank $m]\n set index {}\n set size {}\n for {set i 0} {$i<$r} {incr i} {\n\tlappend size [llength [lindex $m $index]]\n\tlappend index 0\n }\n return $size\n}\n\n# Utility that iterates over the space of coordinates within a matrix.\n#\n# Arguments:\n# var The name of the variable (in the caller's context) to set to each\n# coordinate.\n# size The size of matrix whose coordinates are to be iterated over.\n# body The script to evaluate (in the caller's context) for each coordinate,\n# with the variable named by 'var' set to the coordinate for the particular\n# iteration.\nproc loopcoords {var size body} {\n upvar 1 $var v\n set count [* {*}$size]\n for {set i 0} {$i < $count} {incr i} {\n\tset coords {}\n\tset j $i\n\tfor {set s $size} {[llength $s]} {set s [lrange $s 0 end-1]} {\n\t set dimension [lindex $s end]\n\t lappend coords [expr {$j % $dimension}]\n\t set j [expr {$j / $dimension}]\n\t}\n\tset v [lreverse $coords]\n\tuplevel 1 $body\n }\n}\n\n# Assembles a row, which is one of the simultaneous equations that needs\n# to be solved by reducing the whole set to reduced row echelon form. Note\n# that each row describes the equation for a single cell of the 'g' function.\n#\n# Arguments:\n# g\tThe \"result\" matrix of the convolution being undone.\n# h\tThe known \"input\" matrix of the convolution being undone.\n# gs\tThe size descriptor of 'g', passed as argument for efficiency.\n# gc\tThe coordinate in 'g' that we are generating the equation for.\n# fs\tThe size descriptor of 'f', passed as argument for efficiency.\n# hs\tThe size descriptor of 'h' (the unknown \"input\" matrix), passed\n#\tas argument for efficiency.\nproc row {g f gs gc fs hs} {\n loopcoords hc $hs {\n\tset fc {}\n\tset ok 1\n\tforeach a $gc b $fs c $hc {\n\t set d [expr {$a - $c}]\n\t if {$d < 0 || $d >= $b} {\n\t\tset ok 0\n\t\tbreak\n\t }\n\t lappend fc $d\n\t}\n\tif {$ok} {\n\t lappend row [lindex $f $fc]\n\t} else {\n\t lappend row 0\n\t}\n }\n return [lappend row [lindex $g $gc]]\n}\n\n# Utility for converting a matrix to Reduced Row Echelon Form\n# From http://rosettacode.org/wiki/Reduced_row_echelon_form#Tcl\nproc toRREF {m} {\n set lead 0\n set rows [llength $m]\n set cols [llength [lindex $m 0]]\n for {set r 0} {$r < $rows} {incr r} {\n\tif {$cols <= $lead} {\n\t break\n\t}\n\tset i $r\n\twhile {[lindex $m $i $lead] == 0} {\n\t incr i\n\t if {$rows == $i} {\n\t\tset i $r\n\t\tincr lead\n\t\tif {$cols == $lead} {\n\t\t # Tcl can't break out of nested loops\n\t\t return $m\n\t\t}\n\t }\n\t}\n\t# swap rows i and r\n\tforeach j [list $i $r] row [list [lindex $m $r] [lindex $m $i]] {\n\t lset m $j $row\n\t}\n\t# divide row r by m(r,lead)\n\tset val [lindex $m $r $lead]\n\tfor {set j 0} {$j < $cols} {incr j} {\n\t lset m $r $j [/ [double [lindex $m $r $j]] $val]\n\t}\n\n\tfor {set i 0} {$i < $rows} {incr i} {\n\t if {$i != $r} {\n\t\t# subtract m(i,lead) multiplied by row r from row i\n\t\tset val [lindex $m $i $lead]\n\t\tfor {set j 0} {$j < $cols} {incr j} {\n\t\t lset m $i $j \\\n\t\t\t[- [lindex $m $i $j] [* $val [lindex $m $r $j]]]\n\t\t}\n\t }\n\t}\n\tincr lead\n }\n return $m\n}\n\n# Deconvolve a pair of matrixes. Solves for 'h' such that 'g = f convolve h'.\n#\n# Arguments:\n# g The matrix of data to be deconvolved.\n# f The matrix describing the convolution to be removed.\n# type Optional description of the type of data expected. Defaults to 32-bit\n# integer data; use 'double' for floating-point data.\nproc deconvolve {g f {type int}} {\n # Compute the sizes of the various matrixes involved.\n set gsize [size $g]\n set fsize [size $f]\n foreach gs $gsize fs $fsize {\n\tlappend hsize [expr {$gs - $fs + 1}]\n }\n\n # Prepare the set of simultaneous equations to solve\n set toSolve {}\n loopcoords coords $gsize {\n\tlappend toSolve [row $g $f $gsize $coords $fsize $hsize]\n }\n\n # Solve the equations\n set solved [toRREF $toSolve]\n\n # Make a dummy result matrix of the right size\n set h 0\n foreach hs [lreverse $hsize] {set h [lrepeat $hs $h]}\n\n # Fill the results from the equations into the result matrix\n set idx 0\n loopcoords coords $hsize {\n\tlset h $coords [$type [lindex $solved $idx end]]\n\tincr idx\n }\n\n return $h\n}\n", "language": "Tcl" }, { "code": "# A pretty-printer\nproc pretty matrix {\n set size [rank $matrix]\n if {$size == 1} {\n\treturn \\[[join $matrix \", \"]\\]\n } elseif {$size == 2} {\n\tset out \"\"\n\tforeach row $matrix {\n\t append out \" \" [pretty $row] \",\\n\"\n\t}\n\treturn \\[[string trimleft [string trimright $out ,\\n]]\\]\n }\n set rowout {}\n foreach row $matrix {append rowout [pretty $row] ,\\n}\n set rowout2 {}\n foreach row [split [string trimright $rowout ,\\n] \\n] {\n\tappend rowout2 \" \" $row \\n\n }\n return \\[\\n[string trimright $rowout2 \\n]\\n\\]\n}\n\n# The 3D test data\nset f {\n {{-9 5 -8} {3 5 1}}\n {{-1 -7 2} {-5 -6 6}}\n {{8 5 8} {-2 -6 -4}}\n}\nset g {\n {\n\t{54 42 53 -42 85 -72}\n\t{45 -170 94 -36 48 73}\n\t{-39 65 -112 -16 -78 -72}\n\t{6 -11 -6 62 49 8}}\n {\n\t{-57 49 -23 52 -135 66}\n\t{-23 127 -58 -5 -118 64}\n\t{87 -16 121 23 -41 -12}\n\t{-19 29 35 -148 -11 45}}\n {\n\t{-55 -147 -146 -31 55 60}\n\t{-88 -45 -28 46 -26 -144}\n\t{-12 -107 -34 150 249 66}\n\t{11 -15 -34 27 -78 -50}}\n {\n\t{56 67 108 4 2 -48}\n\t{58 67 89 32 32 -8}\n\t{-42 -31 -103 -30 -23 -8}\n\t{6 4 -26 -10 26 12}}\n}\n\n# Now do the deconvolution and print it out\nputs h:\\ [pretty [deconvolve $g $f]]\n", "language": "Tcl" }, { "code": "#import std\n#import nat\n\nbreak = ~&r**+ zipt*+ ~&lh*~+ ~&lzyCPrX|\\+ -*^|\\~&tK33 :^/~& 0!*t\n\nband = pad0+ ~&rSS+ zipt^*D(~&r,^lrrSPT/~&ltK33tx zipt^/~&r ~&lSNyCK33+ zipp0)^/~&rx ~&B->NlNSPC ~&bt\n\ndeconv = # takes a natural number n to the n-dimensional deconvolution function\n\n~&?\\math..div! iota; ~&!*; @h|\\; (~&al^?\\~&ar break@alh2faltPrXPRX)^^(\n ~&B->NlC~&bt*++ gang@t+ ~~*,\n lapack..dgelsd^^(\n (~&||0.!**+ ~&B^?a\\~&Y@a ^lriFhNSS2iDrlYSK7LS2SL2rQ/~&alt band@alh2faltPrDPMX)^|\\~&+ gang,\n @t =>~&l ~&L+@r))\n", "language": "Ursala" }, { "code": "deconv = # takes a number n to the n-dimensional deconvolution function\n\n~&?\\math..div! iota; ~&!*; @h|\\; -+\n //+ ~&al^?\\~&ar @alh2faltPrXPRX @liX ~&arr2arl2arrh3falrbt2XPRXlrhPCrtPCPNfallrrPXXPRCQNNCq,\n ^^/-+~&B->NlC~&bt*+,gang@t,~~*+- (umf..di_a_trp^/~&DSLlrnPXrmPXS+num@lmS ^niK10mS/num@r ~&lnS)^^(\n gang; ^|\\~&; //+ -+\n ^niK10/~& @NnmlSPASX ~&r->lL @lrmK2K8SmtPK20PPPX ^/~&rrnS2lC ~&rnPrmPljASmF@rrmhPSPlD,\n num+ ~&B^?a\\~&Y@a -+\n ~&l?\\~&r *=r ~&K7LS+ * (*D ^\\~&rr sum@lrlPX)^*D\\~&r product^|/~& successor@zhl,\n ^/~&alt @alh2faltPrDPMX -+\n ~&rFS+ num*rSS+ zipt^*D/~&r ^lrrSPT/~&ltK33tx zipt^/~&r ~&lSNyCK33+ zipp0,\n ^/~&rx ~&B->NlNSPC ~&bt+-+-+-,\n @t =>~&l ~&L+@r)+-\n", "language": "Ursala" }, { "code": "h = <<<-6.,-8.,-5.,9.>,<-7.,9.,-6.,-8.>,<2.,-7.,9.,8.>>,<<7.,4.,4.,-6.>,<9.,9.,4.,-4.>,<-3.,7.,-2.,-3.>>>\nf = <<<-9.,5.,-8.>,<3.,5.,1.>>,<<-1.,-7.,2.>,<-5.,-6.,6.>>,<<8.,5.,8.>,<-2.,-6.,-4.>>>\n\ng =\n\n<\n <\n <54.,42.,53.,-42.,85.,-72.>,\n <45.,-170.,94.,-36.,48.,73.>,\n <-39.,65.,-112.,-16.,-78.,-72.>,\n <6.,-11.,-6.,62.,49.,8.>>,\n <\n <-57.,49.,-23.,52.,-135.,66.>,\n <-23.,127.,-58.,-5.,-118.,64.>,\n <87.,-16.,121.,23.,-41.,-12.>,\n <-19.,29.,35.,-148.,-11.,45.>>,\n <\n <-55.,-147.,-146.,-31.,55.,60.>,\n <-88.,-45.,-28.,46.,-26.,-144.>,\n <-12.,-107.,-34.,150.,249.,66.>,\n <11.,-15.,-34.,27.,-78.,-50.>>,\n <\n <56.,67.,108.,4.,2.,-48.>,\n <58.,67.,89.,32.,32.,-8.>,\n <-42.,-31.,-103.,-30.,-23.,-8.>,\n <6.,4.,-26.,-10.,26.,12.>>>\n\n#cast %eLLLm\n\ntest =\n\n<\n 'h': deconv3(g,f),\n 'f': deconv3(g,h)>\n", "language": "Ursala" }, { "code": "import \"./complex\" for Complex\nimport \"./fmt\" for Fmt\n\nvar fft2 // recursive\nfft2 = Fn.new { |buf, out, n, step, start|\n if (step < n) {\n fft2.call(out, buf, n, step*2, start)\n fft2.call(out, buf, n, step*2, start + step)\n var j = 0\n while (j < n) {\n var t = (Complex.imagMinusOne * Num.pi * j / n).exp * out[j+step+start]\n buf[(j/2).floor + start] = out[j+start] + t\n buf[((j+n)/2).floor + start] = out[j+start] - t\n j = j + 2 * step\n }\n }\n}\n\nvar fft = Fn.new { |buf, n|\n var out = List.filled(n, null)\n for (i in 0...n) out[i] = buf[i]\n fft2.call(buf, out, n, 1, 0)\n}\n\n/* pad list length to power of two */\nvar padTwo = Fn.new { |g, le, nsl|\n var n = 1\n var ns = nsl[0]\n if (ns != 0) {\n n = ns\n } else {\n while (n < le) n = n * 2\n }\n var buf = List.filled(n, Complex.zero)\n for (i in 0...le) buf[i] = Complex.new(g[i], 0)\n nsl[0] = n\n return buf\n}\n\nvar deconv = Fn.new { |g, lg, f, lf, out, rowLe|\n var ns = 0\n var nsl = [ns]\n var g2 = padTwo.call(g, lg, nsl)\n var f2 = padTwo.call(f, lf, nsl)\n ns = nsl[0]\n fft.call(g2, ns)\n fft.call(f2, ns)\n var h = List.filled(ns, null)\n for (i in 0...ns) h[i] = g2[i] / f2[i]\n fft.call(h, ns)\n for (i in 0...ns) {\n if (h[i].real.abs < 1e-10) h[i] = Complex.zero\n }\n var i = 0\n while (i > lf-lg-rowLe) {\n out[-i] = (h[(i+ns)%ns]/32).real\n i = i - 1\n }\n}\n\nvar unpack2 = Fn.new { |m, rows, le, toLe|\n var buf = List.filled(rows*toLe, 0)\n for (i in 0...rows) {\n for (j in 0...le) buf[i*toLe+j] = m[i][j]\n }\n return buf\n}\n\nvar pack2 = Fn.new { |buf, rows, fromLe, toLe, out|\n for (i in 0...rows) {\n for (j in 0...toLe) out[i][j] = buf[i*fromLe+j] / 4\n }\n}\n\nvar deconv2 = Fn.new { |g, rowG, colG, f, rowF, colF, out|\n var g2 = unpack2.call(g, rowG, colG, colG)\n var f2 = unpack2.call(f, rowF, colF, colG)\n var ff = List.filled((rowG-rowF+1)*colG, 0)\n deconv.call(g2, rowG*colG, f2, rowF*colG, ff, colG)\n pack2.call(ff, rowG-rowF+1, colG, colG-colF+1, out)\n}\n\nvar unpack3 = Fn.new { |m, x, y, z, toY, toZ|\n var buf = List.filled(x*toY*toZ, 0)\n for (i in 0...x) {\n for (j in 0...y) {\n for (k in 0...z) {\n buf[(i*toY+j)*toZ+k] = m[i][j][k]\n }\n }\n }\n return buf\n}\n\nvar pack3 = Fn.new { |buf, x, y, z, toY, toZ, out|\n for (i in 0...x) {\n for (j in 0...toY) {\n for (k in 0...toZ) {\n out[i][j][k] = buf[(i*y+j)*z+k] / 4\n }\n }\n }\n}\n\nvar deconv3 = Fn.new { |g, gx, gy, gz, f, fx, fy, fz, out|\n var g2 = unpack3.call(g, gx, gy, gz, gy, gz)\n var f2 = unpack3.call(f, fx, fy, fz, gy, gz)\n var ff = List.filled((gx-fx+1)*gy*gz, 0)\n deconv.call(g2, gx*gy*gz, f2, fx*gy*gz, ff, gy*gz)\n pack3.call(ff, gx-fx+1, gy, gz, gy-fy+1, gz-fz+1, out)\n}\n\nvar f = [\n [[-9, 5, -8], [ 3, 5, 1]],\n [[-1, -7, 2], [-5, -6, 6]],\n [[ 8, 5, 8], [-2, -6, -4]]\n]\nvar fx = f.count\nvar fy = f[0].count\nvar fz = f[0][0].count\n\nvar g = [\n [[ 54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73],\n [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]],\n [[-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64],\n [ 87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]],\n [[-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144],\n [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]],\n [[ 56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8],\n [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]\n]\n\nvar gx = g.count\nvar gy = g[0].count\nvar gz = g[0][0].count\n\nvar h = [\n [[-6, -8, -5, 9], [-7, 9, -6, -8], [ 2, -7, 9, 8]],\n [[ 7, 4, 4, -6], [ 9, 9, 4, -4], [-3, 7, -2, -3]]\n]\n\nvar hx = gx - fx + 1\nvar hy = gy - fy + 1\nvar hz = gz - fz + 1\n\nvar h2 = List.filled(hx, null)\nfor (i in 0...hx) {\n h2[i] = List.filled(hy, 0)\n for (j in 0...hy) h2[i][j] = List.filled(hz, 0)\n}\ndeconv3.call(g, gx, gy, gz, f, fx, fy, fz, h2)\nSystem.print(\"deconv3(g, f):\\n\")\nfor (i in 0...hx) {\n for (j in 0...hy) {\n for (k in 0...hz) Fmt.write(\"$9.6h \", h2[i][j][k])\n System.print()\n }\n if (i < hx-1) System.print()\n}\n\nvar kx = gx - hx + 1\nvar ky = gy - hy + 1\nvar kz = gz - hz + 1\nvar f2 = List.filled(kx, null)\nfor (i in 0...kx) {\n f2[i] = List.filled(ky, 0)\n for (j in 0...ky) f2[i][j] = List.filled(kz, 0)\n}\ndeconv3.call(g, gx, gy, gz, h, hx, hy, hz, f2)\nSystem.print(\"\\ndeconv3(g, h):\\n\")\nfor (i in 0...kx) {\n for (j in 0...ky) {\n for (k in 0...kz) Fmt.write(\"$9.6h \", f2[i][j][k])\n System.print()\n }\n if (i < kx-1) System.print()\n}\n", "language": "Wren" } ]
Deconvolution-2D+
[ { "code": "---\ncategory:\n- Type System\nfrom: http://rosettacode.org/wiki/Define_a_primitive_data_type\nnote: Basic language learning\n", "language": "00-META" }, { "code": "Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.\n\n", "language": "00-TASK" }, { "code": "type My_Type is range 1..10;\n", "language": "Ada" }, { "code": "A : My_Type := 3;\nB : My_Type := A;\n", "language": "Ada" }, { "code": " # assume max int <= ABS - max negative int #\n INT max bounded = ( LENG max int * max int > long max int | ENTIER sqrt(max int) | max int );\n\n MODE RANGE = STRUCT(INT lwb, upb);\n MODE BOUNDED = STRUCT(INT value, RANGE range);\n FORMAT bounded repr = $g\"[\"g(-0)\":\"g(-0)\"]\"$;\n\n # Define some useful operators for looping over ranges #\n OP LWB = (RANGE range)INT: lwb OF range,\n UPB = (RANGE range)INT: upb OF range,\n LWB = (BOUNDED bounded)INT: lwb OF range OF bounded,\n UPB = (BOUNDED bounded)INT: upb OF range OF bounded;\n\n PROC raise exception = ([]STRING args)VOID: (\n put(stand error, (\"exception: \",args, newline));\n stop\n );\n\n PROC raise not implemented error := ([]STRING args)VOID: raise exception(args);\n PROC raise bounds error := ([]STRING args)VOID: raise exception(args);\n\n PRIO MIN=9, MAX=9;\n OP MIN = ([]INT list)INT: (\n INT out:= list[LWB list];\n FOR index FROM LWB list+1 TO UPB list DO IF list[index]<out THEN out :=list[index] FI OD;\n out\n );\n OP MAX = ([]INT list)INT: (\n INT out:= list[LWB list];\n FOR index FROM LWB list+1 TO UPB list DO IF list[index]>out THEN out :=list[index] FI OD;\n out\n );\n\n PRIO ASSERTIN = 6;\n OP ASSERTIN = (INT result, []RANGE range)BOUNDED: (\n BOUNDED out = (result, (MAX lwb OF range, MIN upb OF range));\n IF value OF out < lwb OF range OF out THEN\n raise bounds error((\"out of bounds\", whole(result, int width),\" < [\",whole(MAX lwb OF range, int width),\":]\"))\n ELIF value OF out > upb OF range OF out THEN\n raise bounds error((\"out of bounds\", whole(result, int width),\" > [:\",whole(MIN upb OF range, int width),\"]\"))\n FI;\n out\n ),\n ASSERTIN = (LONG INT result, []RANGE range)BOUNDED: (\n STRUCT (LONG INT value, RANGE range) out = (result, (MAX lwb OF range, MIN upb OF range));\n IF value OF out < lwb OF range OF out THEN\n raise bounds error((\"out of bounds\", whole(result, long int width),\" < [\",whole(MAX lwb OF range, int width),\":]\"))\n ELIF value OF out > upb OF range OF out THEN\n raise bounds error((\"out of bounds\", whole(result, long int width),\" > [:\",whole(MIN upb OF range, int width),\"]\"))\n FI;\n (SHORTEN value OF out, range OF out)\n ),\n ASSERTIN = (INT result, []BOUNDED bounds)BOUNDED: result ASSERTIN range OF bounds,\n ASSERTIN = (LONG INT result, []BOUNDED bounds)BOUNDED: result ASSERTIN range OF bounds;\n\n INT half max int = max int OVER 2;\n INT sqrt max int = ENTIER sqrt (max int);\n\n OP + = (BOUNDED a, b)BOUNDED:\n IF ABS value OF a < half max int AND ABS value OF b < half max int THEN\n value OF a + value OF b ASSERTIN []BOUNDED(a,b)\n ELSE\n LENG value OF a + value OF b ASSERTIN []BOUNDED(a,b)\n FI,\n - = (BOUNDED a, b)BOUNDED: value OF a + -value OF b ASSERTIN []BOUNDED(a,b),\n * = (BOUNDED a, b)BOUNDED:\n IF ABS value OF a < sqrt max int AND ABS value OF b < sqrt max int THEN\n value OF a * value OF b ASSERTIN []BOUNDED(a,b)\n ELSE\n LENG value OF a * value OF b ASSERTIN []BOUNDED(a,b)\n FI,\n / = (BOUNDED a, b)REAL: value OF a / value OF b,\n % = (BOUNDED a, b)BOUNDED: value OF a % value OF b ASSERTIN []BOUNDED(a,b),\n %* = (BOUNDED a, b)BOUNDED: value OF a %* value OF b ASSERTIN []BOUNDED(a,b),\n ** = (BOUNDED a, INT exponent)BOUNDED: value OF a ** exponent ASSERTIN []BOUNDED(a);\n\n OP OVER = (INT value, RANGE range)BOUNDED:\n IF ABS lwb OF range > max bounded THEN\n raise bounds error((\"out of bounds, ABS\", whole(lwb OF range, int width),\" > [:\",whole(max bounded, int width),\"]\"));\n SKIP\n ELIF ABS upb OF range > max bounded THEN\n raise bounds error((\"out of bounds, ABS\", whole(upb OF range, int width),\" > [:\",whole(max bounded, int width),\"]\"));\n SKIP\n ELSE\n value ASSERTIN []RANGE(range)\n FI;\n\n OP INTINIT = (BOUNDED range)REAL: value OF range;\n\n OP < = (BOUNDED a, b)BOOL: value OF a < value OF b,\n > = (BOUNDED a, b)BOOL: value OF a > value OF b,\n <= = (BOUNDED a, b)BOOL: NOT ( value OF a > value OF b ),\n >= = (BOUNDED a, b)BOOL: NOT ( value OF a < value OF b ),\n = = (BOUNDED a, b)BOOL: value OF a = value OF b,\n /= = (BOUNDED a, b)BOOL: NOT (a = b);\n\n # Monadic operators #\n OP - = (BOUNDED range)BOUNDED: -value OF range ASSERTIN []BOUNDED(range),\n ABS = (BOUNDED range)BOUNDED: ABS value OF range ASSERTIN []BOUNDED(range);\n\n COMMENT Operators for extended characters set, and increment/decrement:\n OP +:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a + b ),\n +=: = (BOUNDED a, REF BOUNDED b)REF BOUNDED: ( b := a + b ),\n -:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a - b ),\n *:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a * b ),\n %:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a % b ),\n %*:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a %* b );\n\n # OP aliases for extended character sets (eg: Unicode, APL, ALCOR and GOST 10859) #\n OP × = (BOUNDED a, b)BOUNDED: a * b,\n ÷ = (BOUNDED a, b)INT: a OVER b,\n ÷× = (BOUNDED a, b)BOUNDED: a MOD b,\n ÷* = (BOUNDED a, b)BOUNDED: a MOD b,\n %× = (BOUNDED a, b)BOUNDED: a MOD b,\n ≤ = (BOUNDED a, b)BOUNDED: a <= b,\n ≥ = (BOUNDED a, b)BOUNDED: a >= b,\n ≠ = (BOUNDED a, b)BOOL: a /= b,\n ↑ = (BOUNDED range, INT exponent)BOUNDED: value OF range ** exponent,\n\n ÷×:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a MOD b ),\n %×:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a MOD b ),\n ÷*:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a MOD b );\n\n # BOLD aliases for CPU that only support uppercase for 6-bit bytes - wrist watches #\n OP OVER = (BOUNDED a, b)INT: a % b,\n MOD = (BOUNDED a, b)BOUNDED: a %*b,\n LT = (BOUNDED a, b)BOOL: a < b,\n GT = (BOUNDED a, b)BOOL: a > b,\n LE = (BOUNDED a, b)BOOL: a <= b,\n GE = (BOUNDED a, b)BOOL: a >= b,\n EQ = (BOUNDED a, b)BOOL: a = b,\n NE = (BOUNDED a, b)BOOL: a /= b,\n UP = (BOUNDED range, INT exponent)BOUNDED: range**exponent;\n\n # the required standard assignment operators #\n OP PLUSAB = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a +:= b ), # PLUS #\n PLUSTO = (BOUNDED a, REF BOUNDED b)REF BOUNDED: ( a +=: b ), # PRUS #\n MINUSAB = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a *:= b ),\n DIVAB = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a /:= b ),\n OVERAB = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a %:= b ),\n MODAB = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a %*:= b );\n\nEND COMMENT\nTest:\n RANGE range = RANGE(0, 10000);\n\n # override the default exception #\n raise bounds error := ([]STRING args)VOID: (\n putf(stand error, ($g$, args, $\"- exiting to except bounds error\"l$));\n except bounds error\n );\n\n BOUNDED a, b := 0 OVER range;\n FOR step FROM 4 BY 4 TO UPB range DO # something for pythagoras #\n b := b + step OVER range;\n a := ENTIER sqrt( 1.5 + 2 * value OF b ) OVER range OF b;\n printf(($\"Sum of \"$, bounded repr, a * a, b * b,\n $\" is \"$, bounded repr, a * a + b * b, $l$))\n OD;\n except bounds error:\n SKIP\n", "language": "ALGOL-68" }, { "code": "(*\n\nHere is the type:\n\n*)\n\ntypedef rosetta_code_primitive_type =\n [i : int | 1 <= i; i <= 10] int i\n\n(*\n\nYou do not have to insert bounds checking, and the compiler inserts no\nbounds checking. You simply *cannot* assign an out-of-range value.\n\n(Proviso: unless you do some serious cheating.)\n\n*)\n\nimplement\nmain0 (argc, argv) =\n let\n var n : rosetta_code_primitive_type\n in\n n := 1;\n n := 10;\n n := 11\n end\n\n(*\n\nAn attempt to compile this program *will fail* when it typechecks ‘n := 11’:\n\n$ patscc primitive_type-postiats.dats\n/path/to/primitive_type-postiats.dats: 282(line=21, offs=3) -- 373(line=27, offs=6): error(3): unsolved constraint: C3NSTRprop(C3TKmain(); S2Eapp(S2Ecst(<=); S2EVar(0->S2Eintinf(11)), S2Eintinf(10)))\n/path/to/primitive_type-postiats.dats: 282(line=21, offs=3) -- 373(line=27, offs=6): error(3): unsolved constraint for lvar preservation\ntypechecking has failed: there are some unsolved constraints: please inspect the above reported error message(s) for information.\nexit(ATS): uncaught exception: _2tmp_2ATS_2dPostiats_2src_2pats_error_2esats__FatalErrorExn(1025)\n\n*)\n", "language": "ATS" }, { "code": "#include <stdexcept>\n\nclass tiny_int\n{\npublic:\n tiny_int(int i):\n value(i)\n {\n if (value < 1)\n throw std::out_of_range(\"tiny_int: value smaller than 1\");\n if (value > 10)\n throw std::out_of_range(\"tiny_int: value larger than 10\");\n }\n operator int() const\n {\n return value;\n }\n tiny_int& operator+=(int i)\n {\n // by assigning to *this instead of directly modifying value, the\n // constructor is called and thus the check is enforced\n *this = value + i;\n return *this;\n }\n tiny_int& operator-=(int i)\n {\n *this = value - i;\n return *this;\n }\n tiny_int& operator*=(int i)\n {\n *this = value * i;\n return *this;\n }\n tiny_int& operator/=(int i)\n {\n *this = value / i;\n return *this;\n }\n tiny_int& operator<<=(int i)\n {\n *this = value << i;\n return *this;\n }\n tiny_int& operator>>=(int i)\n {\n *this = value >> i;\n return *this;\n }\n tiny_int& operator&=(int i)\n {\n *this = value & i;\n return *this;\n }\n tiny_int& operator|=(int i)\n {\n *this = value | i;\n return *this;\n }\nprivate:\n unsigned char value; // we don't need more space\n};\n", "language": "C++" }, { "code": "using System;\nusing System.Globalization;\n\nstruct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable\n{\n const int MIN_VALUE = 1;\n const int MAX_VALUE = 10;\n\n public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);\n public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);\n\n static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;\n\n readonly int _value;\n public int Value => this._value == 0 ? MIN_VALUE : this._value; // Treat the default, 0, as being the minimum value.\n\n public LimitedInt(int value)\n {\n if (!IsValidValue(value))\n throw new ArgumentOutOfRangeException(nameof(value), value, $\"Value must be between {MIN_VALUE} and {MAX_VALUE}.\");\n this._value = value;\n }\n\n #region IComparable\n public int CompareTo(object obj)\n {\n if (obj is LimitedInt l) return this.Value.CompareTo(l);\n throw new ArgumentException(\"Object must be of type \" + nameof(LimitedInt), nameof(obj));\n }\n #endregion\n\n #region IComparable<LimitedInt>\n public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);\n #endregion\n\n #region IConvertible\n public TypeCode GetTypeCode() => this.Value.GetTypeCode();\n bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);\n byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);\n char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);\n DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);\n decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);\n double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);\n short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);\n int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);\n long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);\n sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);\n float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);\n string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);\n object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);\n ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);\n uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);\n ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);\n #endregion\n\n #region IEquatable<LimitedInt>\n public bool Equals(LimitedInt other) => this == other;\n #endregion\n\n #region IFormattable\n public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);\n #endregion\n\n #region operators\n public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;\n public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;\n public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;\n public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;\n public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;\n public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;\n\n public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);\n public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);\n\n public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);\n public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);\n public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);\n public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);\n public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);\n\n public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);\n public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);\n public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);\n public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;\n\n public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);\n public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);\n\n public static implicit operator int(LimitedInt value) => value.Value;\n public static explicit operator LimitedInt(int value)\n {\n if (!IsValidValue(value)) throw new OverflowException();\n return new LimitedInt(value);\n }\n #endregion\n\n public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)\n => this.Value.TryFormat(destination, out charsWritten, format, provider);\n\n public override int GetHashCode() => this.Value.GetHashCode();\n public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);\n public override string ToString() => this.Value.ToString();\n\n #region static methods\n public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);\n public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);\n public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);\n public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);\n public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);\n public static int Parse(string s) => int.Parse(s);\n public static int Parse(string s, NumberStyles style) => int.Parse(s, style);\n public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);\n public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);\n #endregion\n}\n", "language": "C-sharp" }, { "code": "(defn tinyint [^long value]\n (if (<= 1 value 10)\n (proxy [Number] []\n (doubleValue [] value)\n (longValue [] value))\n (throw (ArithmeticException. \"integer overflow\"))))\n", "language": "Clojure" }, { "code": "(deftype one-to-ten ()\n '(integer 1 10))\n", "language": "Common-Lisp" }, { "code": "(defun word (i)\n (check-type i one-to-ten)\n (case i\n (1 \"one\")\n (2 \"two\")\n (3 \"three\")\n (4 \"four\")\n (5 \"five\")\n (6 \"six\")\n (7 \"seven\")\n (8 \"eight\")\n (9 \"nine\")\n (10 \"ten\")))\n", "language": "Common-Lisp" }, { "code": "(dolist (i numbers)\n (declare (type one-to-ten i))\n ...)\n", "language": "Common-Lisp" }, { "code": "import std.exception, std.string, std.traits;\n\n/++\nA bounded integral type template.\nTemplate params:\n- min: the minimal value\n- max: the maximal value\n- I: the type used to store the value internally\n+/\nstruct BoundedInt(alias min, alias max, I = int)\n{\n // Static checks\n static assert(isIntegral!(typeof(min)));\n static assert(isIntegral!(typeof(max)));\n static assert(isIntegral!I);\n static assert(min < max);\n static assert(cast(I) max == max, \"Type \" ~ I.stringof\n ~ \" cannot hold values up to \" ~ max.stringof);\n\n /// The actual value stored in this struct\n private I _value;\n\n /// Getter for the internal value\n @property I internalValue()\n {\n return _value;\n }\n\n /// 'alias this' to make this struct look like a built-in integer\n alias internalValue this;\n\n /// Constructor\n this(T)(T value)\n {\n opAssign(value);\n }\n\n /// Assignment operator\n void opAssign(T)(T value)\n if (isIntegral!T)\n {\n _value = checked(value);\n }\n\n /// Unary operators\n auto opUnary(string op)() const\n {\n return checked(mixin(op ~ \"_value\"));\n }\n\n /// Binary operators\n auto opBinary(string op, T)(T other) const\n {\n return checked(mixin(\"_value\" ~ op ~ \"other\"));\n }\n\n /// ditto\n auto opBinaryRight(string op, T)(T other) const\n if (isIntegral!T)\n {\n return checked(mixin(\"_value\" ~ op ~ \"other\"));\n }\n\n // Bounds enforcement\n private I checked(T)(T value) const\n {\n enforce(value >= min && value <= max,\n format(\"Value %s is out of bounds (%s to %s).\", value, min, max));\n return cast(I) value;\n }\n}\n\nunittest\n{\n alias MyInt = BoundedInt!(1, 10);\n // alias BoundInt!(1, 10) MyInt; // D < 2.061\n\n MyInt i = 4;\n MyInt j = i + i;\n assert(j / 2 == 4);\n assert(2 + j == 10);\n assert(i < 5);\n assert(j > i);\n}\n", "language": "D" }, { "code": "type TinyInt(Integer value) {\n throw @Overflow(value) when value is <1 or >10\n} with Lookup, Show\n\nfunc TinyInt as Integer => this.value\n\nfunc TinyInt + (other) => TinyInt(this.value + other as Integer)\n\nfunc TinyInt * (other) => TinyInt(this.value * other as Integer)\n\nfunc TinyInt - (other) => TinyInt(this.value - other as Integer)\n\nfunc TinyInt / (other) => TinyInt(this.value / other as Integer)\n", "language": "Dyalect" }, { "code": "def MyNumber := 1..10\n\nfor i :MyNumber in [0, 5, 10, 15, 20, 25] {\n println(i)\n}\n", "language": "E" }, { "code": "(require 'types)\n(require 'math)\n\n;; type defined by a predicate\n(define (one-ten? x) (in-interval? x 1 10))\n(type One-ten [Integer & one-ten?])\n\n;; OR by an enumeration\n(type One-ten [ 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 ])\n\n;; EXPLICIT type checking\n;; type-of? returns a Boolean\n\n(type-of? 5 One-ten) → #t\n(type-of? 'Albert One-ten) → #f\n\n;; type-check raises an error\n(type-check 6 One-ten) → #t\n(type-check 88 One-ten)\n⛔ error: One-ten : type-check failure : 88 → 'one-ten?'\n\n\n;; IMPLICIT type checking\n;; declare a function signature\n(define (f10 x y) (+ x y))\n(signature f10 One-ten -> One-ten -> Integer)\n\n(f10 6 7) → 13\n(f10 42 666)\n❗ error: One-ten : type-check failure : 42 → 'f10:x'\n", "language": "EchoLisp" }, { "code": "import extensions;\n\nsealed struct TinyInt : BaseNumber\n{\n int value;\n\n int cast() = value;\n\n constructor(int n)\n {\n if (n <= 1 || n >= 10)\n {\n InvalidArgumentException.raise()\n };\n\n value := n\n }\n\n cast t(string s)\n {\n value := s.toInt();\n\n if (value <= 1 || value >= 10)\n {\n InvalidArgumentException.raise()\n }\n }\n\n TinyInt add(TinyInt t)\n = value + (cast int(t));\n\n TinyInt subtract(TinyInt t)\n = value - (cast int(t));\n\n TinyInt multiply(TinyInt t)\n = value * (cast int(t));\n\n TinyInt divide(TinyInt t)\n = value / (cast int(t));\n\n bool equal(TinyInt t)\n = value == (cast int(t));\n\n bool less(TinyInt t)\n = value == (cast int(t));\n\n string toPrintable()\n => value;\n}\n\npublic program()\n{\n TinyInt i := 4t;\n TinyInt j := i + i;\n\n console.printLine(\"4t = \", i);\n console.printLine(\"8t = \", j);\n console.write(\"4t + 8t = \");\n\n try\n {\n i + j\n }\n catch(InvalidArgumentException e)\n {\n console.printLine(\"A value is out of range\")\n }\n}\n", "language": "Elena" }, { "code": "type My_Type(integer i)\n return i >= 1 and i <= 10\nend type\n", "language": "Euphoria" }, { "code": "PREDICATE: my-int < integer [ 0 > ] [ 11 < ] bi and ;\n", "language": "Factor" }, { "code": "11 my-int? ! f\n10 my-int? ! t\n\"hello\" my-int? ! f\n", "language": "Factor" }, { "code": "GENERIC: ++ ( m -- n )\nM: integer ++ 1 + ;\nM: my-int ++ 2/ ;\n\n10 ++ ! 5\n11 ++ ! 12\n", "language": "Factor" }, { "code": "DECIMAL\n: CLIP ( n lo hi -- n') ROT MIN MAX ;\n: BETWEEN ( n lo hi -- flag) 1+ WITHIN ;\n\n\\ programmer chooses CLIPPED or SAFE integer assignment\n: CLIP! ( n addr -- ) SWAP 1 10 CLIP SWAP ! ;\n: SAFE! ( n addr -- )\n OVER 1 10 BETWEEN 0= ABORT\" out of range!\"\n ! ;\n", "language": "Forth" }, { "code": "VARIABLE X\n7 X SAFE! X ? 7 ok\n12 X CLIP! X ? 10 ok\n\n99 X SAFE!\n:64: out of range!\n99 X >>>SAFE!<<<\nBacktrace:\n$7FAA2B0C throw\n$7FAD4698 c(abort\")\n", "language": "Forth" }, { "code": "DECIMAL\n: FAST! ( n addr -- ) ! ; ( alias the standard version)\n\nDEFER !\n\n\\ commands to change the action of '!'\n: LIMITS-ON ( -- ) ['] SAFE! IS ! ;\n: LIMITS-OFF ( -- ) ['] FAST! IS ! ;\n: CLIPPING-ON ( -- ) ['] CLIP! IS ! ;\n", "language": "Forth" }, { "code": "VARIABLE Y\n\nLIMITS-OFF ok\n 1 Y ! Y ? 1 ok\n 10 Y ! Y ? 10 ok\n 11 Y ! Y ? 11 ok\n 0 Y ! Y ? 0 ok\n LIMITS-ON ok\n 1 Y ! Y ? 1 ok\n 10 Y ! Y ? 10 ok\n 11 Y ! Y ?\n:25: out of range!\n 11 Y >>>!<<< Y ?\nBacktrace:\n$7FAA2B0C throw\n$7FAD4460 c(abort\")\n 0 Y ! Y ?\n:26: out of range!\n 0 Y >>>!<<< Y ?\nBacktrace:\n$7FAA2B0C throw\n$7FAD4460 c(abort\")\n", "language": "Forth" }, { "code": ": (->) ( n <text> -- )\n OVER 1 10 BETWEEN 0= ABORT\" out of range!\"\n >BODY ! ;\n\n: -> ( n -- )\n STATE @\n IF POSTPONE ['] POSTPONE (->) \\ compiling action\n ELSE ' (->) \\ interpret action\n THEN ; IMMEDIATE\n", "language": "Forth" }, { "code": "0 VALUE Z ok\n99 TO Z ok ( normal assignment)\nZ . 99 ok\n99 -> Z ( safe assignment)\n:43: out of range!\n99 -> >>>Z<<<\nBacktrace:\n$7FAA2B0C throw\n$7FAD4570 c(abort\")\n$7FAD45DC (->)\n", "language": "Forth" }, { "code": "module Bounded\n implicit none\n\n type BoundedInteger\n integer, private :: v ! we cannot allow direct access to this, or we\n integer, private :: from, to ! can't check the bounds!\n logical, private :: critical\n end type BoundedInteger\n\n interface assignment(=)\n module procedure bounded_assign_bb, bounded_assign_bi !, &\n ! bounded_assign_ib\n end interface\n\n interface operator(+)\n module procedure bounded_add_bbb !, bounded_add_bbi, &\n ! bounded_add_bib, bounded_add_ibb, &\n ! bounded_add_iib, bounded_add_ibi, &\n ! bounded_add_bii\n end interface\n\n private :: bounded_assign_bb, bounded_assign_bi, &\n bounded_add_bbb\n\ncontains\n\n subroutine set_bound(bi, lower, upper, critical, value)\n type(BoundedInteger), intent(out) :: bi\n integer, intent(in) :: lower, upper\n integer, intent(in), optional :: value\n logical, intent(in), optional :: critical\n\n bi%from = min(lower, upper)\n bi%to = max(lower, upper)\n if ( present(critical) ) then\n bi%critical = critical\n else\n bi%critical = .false.\n end if\n if ( present(value) ) then\n bi = value\n end if\n end subroutine set_bound\n\n subroutine bounded_assign_bb(a, b)\n type(BoundedInteger), intent(out) :: a\n type(BoundedInteger), intent(in) :: b\n\n call bounded_assign_bi(a, b%v)\n\n end subroutine bounded_assign_bb\n\n\n subroutine bounded_assign_bi(a, b)\n type(BoundedInteger), intent(out) :: a\n integer, intent(in) :: b\n\n if ( (a%from <= b) .and. (a%to >= b) ) then\n a%v = b\n else\n write(0,*) \"BoundedInteger: out of bound assignment\"\n if ( a%critical ) then\n stop\n else\n if ( b < a%from ) then\n a%v = a%from\n else\n a%v = a%to\n end if\n write(0,\"(A,' (',I0, ')')\") \"BoundedInteger: set to nearest bound\", a%v\n end if\n end if\n end subroutine bounded_assign_bi\n\n\n function bounded_add_bbb(a, b) result(c)\n type(BoundedInteger) :: c\n type(BoundedInteger), intent(in) :: a, b\n\n integer :: t\n\n c%from = max(a%from, b%from)\n c%to = min(a%to, b%to)\n t = a%v + b%v\n if ( c%from <= t .and. c%to >= t ) then\n c%v = t\n else\n write(0,*) \"BoundedInteger: out of bound sum\"\n if ( a%critical .or. b%critical ) then\n stop\n else\n if ( t < c%from ) then\n c%v = c%from\n else\n c%v = c%to\n end if\n write(0,\"(A,' (',I0,')')\") \"BoundedInteger: set to nearest bound\", c%v\n end if\n end if\n end function bounded_add_bbb\n\nend module Bounded\n", "language": "Fortran" }, { "code": "program BoundedTest\n use Bounded\n implicit none\n\n type(BoundedInteger) :: a, b, c\n\n call set_bound(a, 1, 10)\n ! if we want to stop the program if a is out of bounds...\n ! call set_bound(a, 1, 10, critical=.true.)\n call set_bound(b, 1, 10)\n call set_bound(c, 1, 10)\n ! if we want to init c to a specific value...:\n ! call set_bound(c, 1, 10, value=6)\n\n a = 1 ! ok\n a = 4 ! ok\n a = -1 ! warning (a=1)\n a = 11 ! warning (a=10)\n a = 3 ! ok\n b = a ! ok\n c = a + b ! ok (3+3)\n c = c + a ! ok (6+3=9)\n c = c + b ! warning (c=10)\n\nend program BoundedTest\n", "language": "Fortran" }, { "code": "type\n\trange = 1..10;\nvar\n\tn: range;\nbegin\n\tn := 10;\n\t{$rangeChecks on}\n\tn := n + 10; // will yield a run-time error\nend;\n", "language": "Free-Pascal-Lazarus" }, { "code": "' FB 1.05.0 Win64\n\nType MyInteger\n Private:\n Dim i_ As Integer\n Public:\n Declare Constructor(i_ As Integer)\n Declare Property I() As Integer\n Declare Operator Cast() As Integer\n Declare Operator Cast() As String\nEnd Type\n\nConstructor MyInteger(i_ As Integer)\n If i_ < 1 Then\n i_ = 1\n ElseIf i_ > 10 Then\n i_ = 10\n End If\n This.i_ = i_\nEnd Constructor\n\nProperty MyInteger.I() As Integer\n Return i_\nEnd Property\n\nOperator MyInteger.Cast() As Integer\n Return i_\nEnd Operator\n\nOperator MyInteger.Cast() As String\n Return Str(i_)\nEnd Operator\n\nDim i As MyInteger = 11 ' implicit constructor call; i_ automatically limited to 10\nDim j As MyInteger = 3 ' implicit constructor call; no adjustment needed\nDim k As Integer = 4\nPrint \"i = \"; i; \" j = \" ; j; \" k = \"; k; \" j + 6 =\"; j.I + 6; \" j + k =\"; j + k\nPrint\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "oneToTen[x] := isInteger[x] AND x >= 1 AND x <= 10\n\nvar y is oneToTen = 1\n\nwhile (true)\n{\n println[y]\n y = y + 1\n}\n", "language": "Frink" }, { "code": "package main\n\nimport \"fmt\"\n\ntype TinyInt int\n\nfunc NewTinyInt(i int) TinyInt {\n if i < 1 {\n i = 1\n } else if i > 10 {\n i = 10\n }\n return TinyInt(i)\n}\n\nfunc (t1 TinyInt) Add(t2 TinyInt) TinyInt {\n return NewTinyInt(int(t1) + int(t2))\n}\n\nfunc (t1 TinyInt) Sub(t2 TinyInt) TinyInt {\n return NewTinyInt(int(t1) - int(t2))\n}\n\nfunc (t1 TinyInt) Mul(t2 TinyInt) TinyInt {\n return NewTinyInt(int(t1) * int(t2))\n}\n\nfunc (t1 TinyInt) Div(t2 TinyInt) TinyInt {\n return NewTinyInt(int(t1) / int(t2))\n}\n\nfunc (t1 TinyInt) Rem(t2 TinyInt) TinyInt {\n return NewTinyInt(int(t1) % int(t2))\n}\n\nfunc (t TinyInt) Inc() TinyInt {\n return t.Add(TinyInt(1))\n}\n\nfunc (t TinyInt) Dec() TinyInt {\n return t.Sub(TinyInt(1))\n}\n\nfunc main() {\n t1 := NewTinyInt(6)\n t2 := NewTinyInt(3)\n fmt.Println(\"t1 =\", t1)\n fmt.Println(\"t2 =\", t2)\n fmt.Println(\"t1 + t2 =\", t1.Add(t2))\n fmt.Println(\"t1 - t2 =\", t1.Sub(t2))\n fmt.Println(\"t1 * t2 =\", t1.Mul(t2))\n fmt.Println(\"t1 / t2 =\", t1.Div(t2))\n fmt.Println(\"t1 % t2 =\", t1.Rem(t2))\n fmt.Println(\"t1 + 1 =\", t1.Inc())\n fmt.Println(\"t1 - 1 =\", t1.Dec())\n}\n", "language": "Go" }, { "code": "{-# OPTIONS -fglasgow-exts #-}\n\ndata Check a b = Check { unCheck :: b } deriving (Eq, Ord)\n\nclass Checked a b where\n check :: b -> Check a b\n\nlift f x = f (unCheck x)\nliftc f x = check $ f (unCheck x)\n\nlift2 f x y = f (unCheck x) (unCheck y)\nlift2c f x y = check $ f (unCheck x) (unCheck y)\nlift2p f x y = (check u, check v) where (u,v) = f (unCheck x) (unCheck y)\n\ninstance Show b => Show (Check a b) where\n show (Check x) = show x\n showsPrec p (Check x) = showsPrec p x\n\ninstance (Enum b, Checked a b) => Enum (Check a b) where\n succ = liftc succ\n pred = liftc pred\n toEnum = check . toEnum\n fromEnum = lift fromEnum\n\ninstance (Num b, Checked a b) => Num (Check a b) where\n (+) = lift2c (+)\n (-) = lift2c (-)\n (*) = lift2c (*)\n negate = liftc negate\n abs = liftc abs\n signum = liftc signum\n fromInteger = check . fromInteger\n\ninstance (Real b, Checked a b) => Real (Check a b) where\n toRational = lift toRational\n\ninstance (Integral b, Checked a b) => Integral (Check a b) where\n quot = lift2c quot\n rem = lift2c rem\n div = lift2c div\n mod = lift2c mod\n quotRem = lift2p quotRem\n divMod = lift2p divMod\n toInteger = lift toInteger\n", "language": "Haskell" }, { "code": "newtype TinyInt = TinyInt Int\n\ninstance Checked TinyInt Int where\n check x | x >= 0 && x <= 10 = Check x\n | otherwise = error \"Out of range\"\n", "language": "Haskell" }, { "code": "newtype EvenInt = EvenInt Int\n\n instance Checked EvenInt Int where\n check x | even x = Check x\n | otherwise = error \"Not even\"\n", "language": "Haskell" }, { "code": "NB. z locale by default on path.\ntype_z_=: 3!:0\nnameClass_z_=: 4!:0\nsignalError_z_=: 13!:8\n\nNB. create a restricted object from an appropriate integer\ncreate_restrict_ =: monad define\n 'Domain error: expected integer' assert 1 4 e.~ type y NB. or Boolean\n 'Domain error: not on [1,10]' assert (0 -.@:e. [: , (0&<*.<&11)) y\n value=: y\n)\n\nadd_restrict_=: monad define\n if. 0 = nameClass<'value__y' do.\n (value + value__y) conew 0{::coname''\n else.\n 'value unavailable'signalError 21\n end.\n)\n", "language": "J" }, { "code": "class BoundedIntOutOfBoundsException extends Exception\n{\n public BoundedIntOutOfBoundsException(int v, int l, int u) {\n super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n }\n}\n\nclass BoundedInt {\n private int value;\n private int lower;\n private int upper;\n\n public BoundedInt(int l, int u) {\n lower = Math.min(l, u);\n upper = Math.max(l, u);\n }\n\n private boolean checkBounds(int v) {\n return (v >= this.lower) && (v <= this.upper);\n }\n\n public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n assign(i.value()); //could still throw Exception if the other BoundedInt has different bounds\n }\n\n public void assign(int v) throws BoundedIntOutOfBoundsException {\n if ( checkBounds(v) ) {\n this.value = v;\n } else {\n throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n }\n }\n\n public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n return add(i.value());\n }\n\n public int add(int i) throws BoundedIntOutOfBoundsException {\n if ( checkBounds(this.value + i) ) {\n this.value += i;\n } else {\n throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n }\n return this.value;\n }\n\n public int value() {\n return this.value;\n }\n}\n\n\npublic class Bounded {\n public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n BoundedInt a = new BoundedInt(1, 10);\n BoundedInt b = new BoundedInt(1, 10);\n\n a.assign(6);\n try {\n b.assign(12);\n } catch (Exception e) {\n System.out.println(e.getMessage());\n }\n b.assign(9);\n try {\n a.add(b.value());\n } catch (Exception e) {\n System.out.println(e.getMessage());\n }\n }\n}\n", "language": "Java" }, { "code": "function Num(n){\n n = Math.floor(n);\n if(isNaN(n))\n throw new TypeError(\"Not a Number\");\n if(n < 1 || n > 10)\n throw new TypeError(\"Out of range\");\n this._value = n;\n}\nNum.prototype.valueOf = function() { return this._value; }\nNum.prototype.toString = function () { return this._value.toString();}\n\nvar w = new Num(3), x = new Num(4);\n\nWScript.Echo(w + x); //7\nWScript.Echo(x - w); //1\nWScript.Echo(w * x); //12\nWScript.Echo(w / x); //0.75\nWScript.Echo(w < x); //true\nWScript.Echo(x < w); //false\n\nvar y = new Num(0); //TypeError\nvar z = new Num(11); //TypeError\n", "language": "JavaScript" }, { "code": "def typeof:\n if type == \"object\" and has(\"type\") then .type else type end;\n", "language": "Jq" }, { "code": "def pp:\n if type == \"object\" and has(\"type\") then \"\\(.type)::\\(.value)\"\n else .\n end;\n", "language": "Jq" }, { "code": "def smallint(i): i as $i\n | if (i|type) == \"number\" and i == (i|floor) and i > 0 and i < 11 then {\"type\": \"smallint\", \"value\": i}\n else empty\n end ;\n\n# A convenience function to save typing:\ndef s(i): smallint(i);\n\n# To convert from the pretty-print representation back to smallint:\ndef tosmallint:\n if type == \"string\" and startswith(\"smallint::\") then\n split(\"::\") | smallint( .[1] | tonumber )\n else empty\n end ;\n", "language": "Jq" }, { "code": "def add(a;b): smallint(a.value + b.value);\ndef minus(a;b): smallint(a.value - b.value);\ndef times(a;b): smallint(a.value * b.value);\ndef mod(a;b): smallint(a.value % b.value);\ndef divide(a;b): smallint( (a.value / b.value) | floor );\n", "language": "Jq" }, { "code": "s(1) < s(3) # => true\nadd( s(1); s(2)) | pp # \"smallint::3\"\nadd( s(6); s(6)) # (nothing)\n", "language": "Jq" }, { "code": "struct LittleInt <: Integer\n val::Int8\n function LittleInt(n::Real)\n 1 ≤ n ≤ 10 || throw(ArgumentError(\"LittleInt number must be in [1, 10]\"))\n return new(Int8(n))\n end\nend\nBase.show(io::IO, x::LittleInt) = print(io, x.val)\nBase.convert(::Type{T}, x::LittleInt) where T<:Number = convert(T, x.val)\nBase.promote_rule(::Type{LittleInt}, ::Type{T}) where T<:Number = T\n\nfor op in (:+, :*, :÷, :-, :&, :|, :$, :<, :>, :(==))\n @eval (Base.$op)(a::LittleInt, b::LittleInt) = LittleInt(($op)(a.val, b.val))\nend\n\n# Test\na = LittleInt(3)\nb = LittleInt(4.0)\n@show a b\n@show a + b\n@show b - a\n@show a * LittleInt(2)\n@show b ÷ LittleInt(2)\n@show a * b\n", "language": "Julia" }, { "code": "// version 1.1\n\nclass TinyInt(i: Int) {\n private val value = makeTiny(i)\n\n operator fun plus (other: TinyInt): TinyInt = TinyInt(this.value + other.value)\n operator fun minus(other: TinyInt): TinyInt = TinyInt(this.value - other.value)\n operator fun times(other: TinyInt): TinyInt = TinyInt(this.value * other.value)\n operator fun div (other: TinyInt): TinyInt = TinyInt(this.value / other.value)\n operator fun rem (other: TinyInt): TinyInt = TinyInt(this.value % other.value)\n\n operator fun inc() = TinyInt(this.value + 1)\n operator fun dec() = TinyInt(this.value - 1)\n\n private fun makeTiny(i: Int): Int =\n when {\n i < 1 -> 1\n i > 10 -> 10\n else -> i\n }\n\n override fun toString(): String = value.toString()\n}\n\nfun main(args: Array<String>) {\n var t1 = TinyInt(6)\n var t2 = TinyInt(3)\n println(\"t1 = $t1\")\n println(\"t2 = $t2\")\n println(\"t1 + t2 = ${t1 + t2}\")\n println(\"t1 - t2 = ${t1 - t2}\")\n println(\"t1 * t2 = ${t1 * t2}\")\n println(\"t1 / t2 = ${t1 / t2}\")\n println(\"t1 % t2 = ${t1 % t2}\")\n println(\"t1 + 1 = ${++t1}\")\n println(\"t2 - 1 = ${--t2}\")\n}\n", "language": "Kotlin" }, { "code": "define dint => type {\n data private value\n\n public oncreate(value::integer) => {\n\tfail_if(#value < 1,#value+' less than 1 ')\n\tfail_if(#value > 10,#value+' greater than 10')\n\t.value = #value\n }\n\n public +(rhs::integer) => dint(.value + #rhs)\n public -(rhs::integer) => dint(.value - #rhs)\n public *(rhs::integer) => dint(.value * #rhs)\n public /(rhs::integer) => dint(.value / #rhs)\n public %(rhs::integer) => dint(.value % #rhs)\n\n public asstring() => string(.value)\n\n}\n\ndint(1) // 1\ndint(10) // 10\n\ndint(0) // Error: 0 less than 1\ndint(2) - 5 // Error: -3 less than 1\n\ndint(11) // Error: 11 greater than 10\ndint(10) + 1 // Error: 11 greater than 10\ndint(10) * 2 // Error: 20 greater than 10\n", "language": "Lasso" }, { "code": "BI = { -- Bounded Integer\n new = function(self, v) return setmetatable({v = self:_limit(v)}, BI_mt) end,\n _limit = function(self,v) return math.max(1, math.min(math.floor(v), 10)) end,\n}\nBI_mt = {\n __index = BI,\n __call = function(self,v) return self:new(v) end,\n __unm = function(self) return BI(-self.v) end,\n __add = function(self,other) return BI(self.v+other.v) end,\n __sub = function(self,other) return BI(self.v-other.v) end,\n __mul = function(self,other) return BI(self.v*other.v) end,\n __div = function(self,other) return BI(self.v/other.v) end,\n __mod = function(self,other) return BI(self.v%other.v) end,\n __pow = function(self,other) return BI(self.v^other.v) end,\n __eq = function(self,other) return self.v==other.v end,\n __lt = function(self,other) return self.v<other.v end,\n __le = function(self,other) return self.v<=other.v end,\n __tostring = function(self) return tostring(self.v) end\n}\nsetmetatable(BI, BI_mt)\n", "language": "Lua" }, { "code": "zero, one, two, three, four, five = BI(0), BI(1), BI(2), BI(3), BI(4), BI(5)\nsix, seven, eight, nine, ten, eleven = BI(6), BI(7), BI(8), BI(9), BI(10), BI(11)\nprint(\"zero through eleven:\\t\", zero, one, two, three, four, five, six, seven, eight, nine, ten, eleven)\nprint(\"zero less than one?\\t\", zero < one)\nprint(\"eleven greater than ten?\", eleven > ten)\nprint(\"negative one equals one:\", -one)\nprint(\"zero plus one equals two:\", zero + one)\nprint(\"one minus one equals one:\", one - one)\nprint(\"two minus three equals one:\", two - three)\nprint(\"three minus two equals one:\", three - two)\nprint(\"two times three equals six:\", two * three)\nprint(\"two times three equals six?\", two * three == six)\nprint(\"three times four equals ten?\", three * four == ten)\nprint(\"one divided by two equals one:\",one / two)\nprint(\"five divided by two equals two:\", five / two)\nprint(\"order of operations (seven):\", one + two * three)\nprint(\"order of operations (nine):\", (one + two) * three)\nprint(\"eight mod three equals two:\", eight % three)\nprint(\"eight mod two equals one:\", eight % two)\nprint(\"two to the third equals eight:\", two ^ three)\nprint(\"two to the fourth equals ten:\", two ^ four)\n", "language": "Lua" }, { "code": "Module CheckDataType {\n Module CheckThis {\n Class typeA {\n Private:\n mval as currency\n Public:\n Property min {value}=-1\n Property max {value}=0\n Operator \"++\" {\n if .mval=.[max] then Error \"Number bigger than Max Value\"\n .mval++\n }\n Operator \"--\" {\n if .mval=.[min] then Error \"Number lower than Min Value\"\n .mval--\n }\n Operator \"+=\" (x){\n if .mval>.[max]+x then Error \"Number bigger than Max Value\"\n .mval+=x\n }\n Operator \"-=\" (x) {\n if .mval<.[min]-x then Error \"Number lower than Min Value\"\n .mval-=x\n }\n Value {\n =.mval\n }\n Set (x) {\n if x>.[max] then Error \"Number bigger than Max Value\"\n if x<.[min] then Error \"Number lower than Min Value\"\n .mval<=int(x)\n }\n Class:\n Module typeA (.[min], .[max]) {\n .mval<=.[min]\n }\n }\n K=typeA(1, 10)\n K=5\n Def TypeExp$(x)=Type$(x)\n Print Type$(K)=\"Group\", TypeExp$(K)=\"Currency\"\n K--\n Print K\n K=K+1\n Print K, K.Max, K.Min\n K+=4\n Print K, K.Max, K.Min\n Print -K*4=-36\n Try Ok {\n K=400\n }\n If Error or Not Ok then Print Error$\n \\\\ make a new K as K with name Z\n Z=Group(K)\n Print Z.Max, Z.Min, Z\n K++\n Z=Group(K)\n Print Z=K\n K-=5\n \\\\ We make M as pointer to K\n M->K\n Print Eval(M), K\n For M {This++}\n Print Eval(M), K\n For M {This=8}\n Print Eval(M), K\n Push Group(M), Group(M)\n }\n CheckThis\n \\\\ Read Group from stack of values and place a copy in each item in A()\n Dim A(4)=Group\n \\\\ We have one more group in stack, so we read it to new variable What\n \\\\ What isn't a pointer to object, is the object (internal is a pointer to objet but isn't usable for M2000)\n Read What\n What++\n Print What.Max=10, What.Min=1, What=9 ' True True True\n Print A(2).Max=10, A(2).Min=1, A(2)=8 ' True True True\n}\nCheckDataType\n", "language": "M2000-Interpreter" }, { "code": "classdef RingInt\n\n properties\n value\n end\n\n methods\n\n %RingInt constructor\n function theInt = RingInt(varargin)\n if numel(varargin) == 0\n theInt.value = 1;\n elseif numel(varargin) > 1\n error 'The RingInt constructor can''''t take more than 1 argument.';\n else\n\n %Makes sure any doubles are coerced to ints\n if not(isinteger(varargin{1}))\n varargin{1} = int32(varargin{1});\n end\n\n %Maps out of bound values to the proper range\n if varargin{1} > 10\n theInt.value = varargin{1} - (10 * (idivide(varargin{1},10,'ceil') - 1));\n elseif varargin{1} < 1\n theInt.value = varargin{1} + (10 * (idivide(abs(varargin{1}),10,'floor') + 1));\n else\n theInt.value = varargin{1};\n end\n end\n end %constructor\n\n %Overload the \"+\" operator\n function sum = plus(firstNumber,secondNumber)\n\n if isa(firstNumber,'RingInt') && isa(secondNumber,'RingInt')\n sum = firstNumber.value + secondNumber.value;\n elseif isa(firstNumber,'RingInt') && not(isa(secondNumber,'RingInt'))\n sum = firstNumber.value + secondNumber;\n else\n sum = secondNumber.value + firstNumber;\n end\n\n sum = RingInt(sum);\n\n end %+\n\n %Overload the \"-\" operator\n function difference = minus(firstNumber,secondNumber)\n\n if isa(firstNumber,'RingInt') && isa(secondNumber,'RingInt')\n difference = firstNumber.value - secondNumber.value;\n elseif isa(firstNumber,'RingInt') && not(isa(secondNumber,'RingInt'))\n difference = firstNumber.value - secondNumber;\n else\n difference = firstNumber - secondNumber.value;\n end\n\n difference = RingInt(difference);\n\n end %-\n\n %Overload the \"==\" operator\n function trueFalse = eq(firstNumber,secondNumber)\n\n if isa(firstNumber,'RingInt') && isa(secondNumber,'RingInt')\n trueFalse = firstNumber.value == secondNumber.value;\n else\n error 'You can only compare a RingInt to another RingInt';\n end\n\n end %==\n\n\n %Overload the display() function\n function display(ringInt)\n disp(ringInt);\n end\n\n %Overload the disp() function\n function disp(ringInt)\n disp(sprintf('\\nans =\\n\\n\\t %d\\n',ringInt.value));\n end\n\n end %methods\nend %classdef\n", "language": "MATLAB" }, { "code": ">> RingInt(10) + 1\n\nans =\n\n\t 1\n\n>> RingInt(5) - 20\n\nans =\n\n\t 5\n\n>> a = RingInt(3)\n\nans =\n\n\t 3\n\n>> a == RingInt(3)\n\nans =\n\n 1\n", "language": "MATLAB" }, { "code": "TYPE MyInt = [1..10];\n", "language": "Modula-3" }, { "code": "type\n MyInt = range[1..10]\n\nvar x: MyInt = 5\n\nx = x + 6 # Runtime error: unhandled exception: value out of range: 11 notin 1 .. 10 [RangeDefect]\n\nx = 12 # Compile-time error: conversion from int literal(12) to MyInt is invalid\n", "language": "Nim" }, { "code": "exception Out_of_bounds\n\ntype 'a bounds = { min: 'a; max: 'a }\n\ntype 'a bounded = { value: 'a; bounds: 'a bounds }\n\nlet mk_bounds ~min ~max = { min=min; max=max } ;;\n(** val mk_bounds : min:'a -> max:'a -> 'a bounds *)\n\nlet check_bounds ~value ~bounds =\n if value < bounds.min || value > bounds.max then\n raise Out_of_bounds ;;\n(** val check_bounds : value:'a -> bounds:'a bounds -> unit *)\n\nlet mk_bounded ~value ~bounds =\n check_bounds ~value ~bounds;\n { value=value; bounds=bounds } ;;\n(** val mk_bounded : value:'a -> bounds:'a bounds -> 'a bounded *)\n\nlet op f a b =\n if a.bounds <> b.bounds then\n invalid_arg \"different bounds\";\n let res = f a.value b.value in\n check_bounds res a.bounds;\n (mk_bounded res a.bounds)\n ;;\n(** val op : ('a -> 'a -> 'a) -> 'a bounded -> 'a bounded -> 'a bounded *)\n", "language": "OCaml" }, { "code": "# let range = mk_bounds 1 10 ;;\nval range : int bounds = {min = 1; max = 10}\n\n# let a = mk_bounded 2 range ;;\nval a : int bounded = {value = 2; bounds = {min = 1; max = 10}}\n\n# let b = mk_bounded 5 range ;;\nval b : int bounded = {value = 5; bounds = {min = 1; max = 10}}\n\n# let c = mk_bounded 14 range ;;\nException: Out_of_bounds.\n\n# op ( + ) a b ;;\n- : int bounded = {value = 7; bounds = {min = 1; max = 10}}\n", "language": "OCaml" }, { "code": "# let rf = mk_bounds 1.0 10.0 ;;\nval rf : float bounds = {min = 1.; max = 10.}\n\n# let a = mk_bounded 2.2 rf\n and b = mk_bounded 5.6 rf in\n op ( +. ) a b ;;\n- : float bounded = {value = 7.8; bounds = {min = 1.; max = 10.}}\n", "language": "OCaml" }, { "code": "/* REXX ----------------------------------------------------------------\n* 21.06.2014 Walter Pachl\n* implements a data type tinyint that can have an integer value 1..10\n* 22.06.2014 WP corrected by Rony Flatscher to handle arithmetic\n*---------------------------------------------------------------------*/\na=.tinyint~new(1) ; Say 'a='||a~value\nSay '2*a='||(2*a)\nSay 'a*2='||((0+a)*2)\nsay \"---> rony was here: :)\"\nsay \"The above statement was in effect: '(0+a)*2', NOT 'a*2*, hence it worked!\"\nsay \"These statements work now:\"\nsay \"(a)*2:\" (a)*2\nsay \"a*2: \" a*2\nsay \"<--- rony was here, The end. :)\"\nb=.tinyint~new(11); Say 'b='||b~value\nb=.tinyint~new('B'); Say 'b='||b~value\nsay 'b='||(b) -- show string value\nSay '2*b='||(2*b)\n::class tinyint\n::method init\n Expose v\n Use Arg i\n Select\n When datatype(i,'W') Then Do\n If i>=1 & i<=10 Then\n v=i\n Else Do\n Say 'Argument 1 must be between 1 and 10'\n Raise Syntax 88.907 array(1,1,10,i)\n End\n End\n Otherwise Do\n Say 'Argument 1 must be a whole number between 1 and 10'\n Raise Syntax 88.905 array(1,i)\n End\n End\n::method string\n Expose v\n Return v\n::method value\n Expose v\n Return v\n\n-- rgf, 20140622, intercept unknown messages, forward arithmetic messages to string value\n::method unknown\n expose v\n use arg methName, methArgs\n if wordpos(methName, \"+ - * / % //\")>0 then -- an arithmetic message in hand?\n forward message (methName) to (v) array (methArgs[1])\n", "language": "OoRexx" }, { "code": "declare\n I\nin\n I::1#10\n I = {Pow 2 4}\n", "language": "Oz" }, { "code": "type\n\tnaturalTen = 1..10;\n", "language": "Pascal" }, { "code": "package One_To_Ten;\nuse Carp qw(croak);\nuse Tie::Scalar qw();\nuse base qw(Tie::StdScalar);\n\nsub STORE {\n my $self = shift;\n my $val = int shift;\n croak 'out of bounds' if $val < 1 or $val > 10;\n $$self = $val;\n};\n\npackage main;\ntie my $t, 'One_To_Ten';\n$t = 3; # ok\n$t = 5.2; # ok, silently coerced to int\n$t = -2; # dies, too small\n$t = 11; # dies, too big\n$t = 'xyzzy';\n# dies, too small. string is 0 interpreted numerically\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">type</span> <span style=\"color: #000000;\">iten</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">10</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">type</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i</span>\n <span style=\"color: #000000;\">iten</span> <span style=\"color: #000000;\">i10</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">11</span> <span style=\"color: #000080;font-style:italic;\">-- fine</span>\n <span style=\"color: #000000;\">i10</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">11</span> <span style=\"color: #000080;font-style:italic;\">-- runtime error (desktop/Phix only, not pwa/p2js)</span>\n<!--\n", "language": "Phix" }, { "code": "(class +BoundedInt)\n# value lower upper\n\n(dm T (Low Up)\n (=: lower (min Low Up))\n (=: upper (max Low Up)) )\n\n(de \"checkBounds\" (Val)\n (if (>= (: upper) Val (: lower))\n Val\n (throw 'boundedIntOutOfBounds\n (pack\n \"value \" Val\n \" is out of bounds [\" (: lower) \",\" (: upper) \"]\" ) ) ) )\n\n(dm set> (Val)\n (=: value (\"checkBounds\" Val)) )\n\n(dm +> (Val)\n (=: value (\"checkBounds\" (+ Val (: value)))) )\n\n(dm val> ()\n (: value) )\n\n(de main ()\n (let (A (new '(+BoundedInt) 1 10) B (new '(+BoundedInt) 1 10))\n (set> A 6)\n (when (catch 'boundedIntOutOfBounds (set> B 12) NIL)\n (prinl @) )\n (set> B 9)\n (when (catch 'boundedIntOutOfBounds (+> A (val> B)) NIL)\n (prinl @) ) ) )\n", "language": "PicoLisp" }, { "code": "[Int][ValidateRange(1,10)]$n = 3 # $n can only accept integers between 1 and 10\n", "language": "PowerShell" }, { "code": "If OpenConsole()\n Structure Persona\n nombre.s{15}\n apellido.s{30}\n edad.w\n List amigos$()\n EndStructure\n\n Dim MyFriends.Persona(100)\n\n ; Aquí la posición '1' del array MyFriends()\n ; contendrá una persona y su propia información\n MyFriends(1)\\nombre = \"Carlos\"\n MyFriends(1)\\apellido = \"Gzlez.\"\n MyFriends(1)\\edad = 47\n\n individuo.Persona\n individuo\\nombre = \"Juan\"\n individuo\\apellido = \"Hdez.\"\n individuo\\edad = 49\n\n ; Ahora, agrega algunos amigos\n AddElement(individuo\\amigos$())\n individuo\\amigos$() = \"Lucia\"\n\n AddElement(individuo\\amigos$())\n individuo\\amigos$() = \"Isabel\"\n\n ForEach individuo\\amigos$()\n Debug individuo\\amigos$()\n Next\n\n ;Estructura extendida\n Structure Domicilio Extends Persona\n calle.s\n numero.b\n EndStructure\n\n MyFriends.Domicilio\\calle = \"Grillo\"\n MyFriends.Domicilio\\numero = 20\n\n\n PrintN(individuo\\nombre + \" \" + individuo\\apellido + \" \" + Str(individuo\\edad) + \" \" + Str(MyFriends.Domicilio\\numero))\n PrintN(MyFriends(1)\\nombre + \" \" + MyFriends(1)\\apellido + \" \" + Str(MyFriends(1)\\edad))\n\n\n If TypeOf(Persona\\edad) = #PB_Word\n Debug \"Edad ess un 'Word'\"\n EndIf\n\n superficie.f\n If TypeOf(superficie) = #PB_Float\n Debug \"superficie es un 'Float'\"\n EndIf\n\n Print(#CRLF$ + #CRLF$ + \"--- terminado, pulsa RETURN---\"): Input()\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": ">>> class num(int):\n def __init__(self, b):\n if 1 <= b <= 10:\n return int.__init__(self+0)\n else:\n raise ValueError,\"Value %s should be >=0 and <= 10\" % b\n\n\n>>> x = num(3)\n>>> x = num(11)\n\nTraceback (most recent call last):\n File \"<pyshell#394>\", line 1, in <module>\n x = num(11)\n File \"<pyshell#392>\", line 6, in __init__\n raise ValueError,\"Value %s should be >=0 and <= 10\" % b\nValueError: Value 11 should be >=0 and <= 10\n>>> x\n3\n>>> type(x)\n<class '__main__.num'>\n>>>\n", "language": "Python" }, { "code": "TYPE TipoUsuario\n nombre AS STRING * 15\n apellido AS STRING * 30\n edad AS INTEGER\nEND TYPE\n\nDIM usuario(1 TO 20) AS TipoUsuario\n\nusuario(1).nombre = \"Juan\"\nusuario(1).apellido = \"Hdez.\"\nusuario(1).edad = 49\n\nPRINT usuario(1).nombre, usuario(1).apellido, usuario(1).edad\n", "language": "QBasic" }, { "code": "#lang racket\n\n(provide (contract-out [x 1-to-10/c]))\n\n(define 1-to-10/c (between/c 1 10))\n\n(define x 5)\n", "language": "Racket" }, { "code": "#lang typed/racket\n\n(define-type 1UpTo10 (U 1 2 3 4 5 6 7 8 9 10))\n\n;; type-checks\n(: x 1UpTo10)\n(define x 3)\n\n;; does not type-check\n(: y 1UpTo10)\n(define y 18)\n", "language": "Racket" }, { "code": "subset OneToTen of Int where 1..10;\n\nmy OneToTen $n = 5;\n$n += 6;\n", "language": "Raku" }, { "code": "subset Prime of Int where -> $n { $n > 1 and so $n %% none 2 .. $n.sqrt }\n", "language": "Raku" }, { "code": "{{\n variable update\n---reveal---\n : .limited @update &! &@ if update off ;\n : to dup 1 10 within [ update on ] [ drop \"Out of bounds\\n\" puts ] if ;\n : limited: create 1 , &.limited reclass ;\n}}\n", "language": "Retro" }, { "code": "limited: foo\n1 to foo\nfoo .s\n51 to foo\nfoo .s\nbye\n", "language": "Retro" }, { "code": "require 'test/unit'\ninclude Test::Unit::Assertions\n\nclass MyInt\n @@min = 1\n @@max = 10\n\n attr_reader :value\n private :value\n\n def initialize(val)\n begin\n v = Integer(val)\n rescue ArgumentError\n raise ArgumentError, \"invalid value '#{val}', must be an integer\"\n end\n\n unless v.between?(@@min, @@max)\n raise ArgumentError, \"invalid value '#{v}', must be between #{@@min} and #{@@max}\"\n end\n\n @value = v\n end\n\n def method_missing(m, *args)\n super unless @value.respond_to?(m)\n myint_args = args.collect do |arg|\n arg.kind_of?(self.class) ? arg.to_int : arg\n end\n result = @value.send(m, *myint_args)\n return result if m == :coerce\n case result\n when Integer\n MyInt.new(result)\n when Array\n result.collect do |element|\n element.kind_of?(Integer) ? MyInt.new(element) : element\n end\n else\n result\n end\n end\n\n def respond_to?(method)\n super or @value.respond_to? method\n end\n\n def to_int\n @value\n end\n def to_f\n Float(@value)\n end\n def to_s\n @value.to_s\n end\n def inspect\n to_s\n end\nend\n\n\nassert_raise(ArgumentError) { MyInt.new(\"foo\") } # => invalid value 'foo', must be an integer\nassert_raise(ArgumentError) { MyInt.new(11) } # => invalid value '11', must be an integer\n\na = MyInt.new(7)\nb = MyInt.new(5)\n\nc = 5 + a\nassert_kind_of(Fixnum, c)\nassert_equal(12, c)\n\nc = a + 2\nassert_kind_of(MyInt, c)\nassert_equal(9, c.to_int)\n\nc = a + 2.8\nassert_kind_of(Float, c)\nassert_equal(9.8, c)\n\nc = a - b\nassert_kind_of(MyInt, c)\nassert_equal(2, c.to_int)\n\nassert_raise(ArgumentError) { c = a + b } # => invalid value '12', must be an integer\nassert_raise(ArgumentError) { c = b - a } # => invalid value '-2', must be an integer\n", "language": "Ruby" }, { "code": "use std::convert::TryFrom;\n\nmod test_mod {\n use std::convert::TryFrom;\n use std::fmt;\n\n // Because the `i8` is not `pub` this cannot be directly constructed\n // by code outside this module\n #[derive(Copy, Clone, Debug)]\n pub struct TwoDigit(i8);\n\n impl TryFrom<i8> for TwoDigit {\n type Error = &'static str;\n\n fn try_from(value: i8) -> Result<Self, Self::Error> {\n if value < -99 || value > 99 {\n Err(\"Number cannot fit into two decimal digits\")\n } else {\n Ok(TwoDigit(value))\n }\n }\n }\n\n impl Into<i8> for TwoDigit {\n fn into(self) -> i8 { self.0 }\n }\n\n // This powers `println!`'s `{}` token.\n impl fmt::Display for TwoDigit {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{}\", self.0)\n }\n }\n}\n\npub fn main() {\n let foo = test_mod::TwoDigit::try_from(50).unwrap();\n let bar: i8 = foo.into();\n println!(\"{} == {}\", foo, bar);\n}\n", "language": "Rust" }, { "code": " class TinyInt(val int: Byte) {\n import TinyInt._\n require(int >= lower && int <= upper, \"TinyInt out of bounds.\")\n\n override def toString = int.toString\n }\n\n object TinyInt {\n val (lower, upper) = (1, 10)\n\n def apply(i: Byte) = new TinyInt(i)\n }\n\n val test = (TinyInt.lower to TinyInt.upper).map(n => TinyInt(n.toByte))\n", "language": "Scala" }, { "code": "subset Integer < Number { .is_int }\nsubset MyIntLimit < Integer { . ~~ (1 .. 10) }\n\nclass MyInt(value < MyIntLimit) {\n\n method to_s { value.to_s }\n method get_value { value.get_value }\n\n method ==(Number x) { value == x }\n method ==(MyInt x) { value == x.value }\n\n method AUTOLOAD(_, name, *args) {\n var results = [value.(name)(args.map {|n| Number(n) }...)]\n results.map{|r| r.kind_of(Number) ? MyInt(r.int) : r}...\n }\n}\n\n#\n## Example:\n#\nvar a = MyInt(2) # creates a new object of type `MyInt`\na += 7 # adds 7 to a\nsay a # => 9\nsay a/2 # => 4\n\nvar b = (a - 3) # b is of type `MyInt`\nsay b # => 6\n\nsay a.as_hex.dump # => \"9\" -- an hexadecimal string\n\na -= 6 # a=3\nvar c = (a + b) # MyInt(3) + MyInt(6)\nsay c # => 9\nsay c.class # => MyInt\n\na *= 2 # a=6\nsay a+b # error: class `MyInt` does not match MyInt(12)\n", "language": "Sidef" }, { "code": "struct SmallInt {\n var value: Int\n\n init(value: Int) {\n guard value >= 1 && value <= 10 else {\n fatalError(\"SmallInts must be in the range [1, 10]\")\n }\n\n self.value = value\n }\n\n static func +(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value + rhs.value) }\n static func -(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value - rhs.value) }\n static func *(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value * rhs.value) }\n static func /(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value / rhs.value) }\n}\n\nextension SmallInt: ExpressibleByIntegerLiteral {\n public init(integerLiteral value: Int) { self.init(value: value) }\n}\n\nextension SmallInt: CustomStringConvertible {\n public var description: String { \"\\(value)\" }\n}\n\nlet a: SmallInt = 1\nlet b: SmallInt = 9\nlet c: SmallInt = 10\nlet d: SmallInt = 2\n\nprint(a + b)\nprint(c - b)\nprint(a * c)\nprint(c / d)\nprint(a + c)\n", "language": "Swift" }, { "code": "namespace eval ::myIntType {\n variable value_cache\n array set value_cache {}\n variable type integer\n variable min 1\n variable max 10\n variable errMsg \"cannot set %s to %s: must be a $type between $min and $max\"\n}\nproc ::myIntType::declare varname {\n set ns [namespace current]\n uplevel [list trace add variable $varname write ${ns}::write]\n uplevel [list trace add variable $varname unset ${ns}::unset_var]\n}\nproc ::myIntType::unset_var {varname args} {\n variable value_cache\n unset value_cache($varname)\n}\nproc ::myIntType::validate {value} {\n variable type\n variable min\n variable max\n expr {[string is $type -strict $value] && $min <= $value && $value <= $max}\n}\nproc ::myIntType::write {varname args} {\n variable value_cache\n upvar $varname var\n set value $var\n if {[validate $value]} {\n set value_cache($varname) $value\n } else {\n if {[info exists value_cache($varname)]} {\n set var $value_cache($varname)\n }\n variable errMsg\n error [format $errMsg $varname $value]\n }\n}\n", "language": "Tcl" }, { "code": "needs quotes\n{\n variable update\n [ update @ [ ! ] [ @ ] ifTrueFalse update off ] is action\n [ dup >r 0 11 r> within [ update on ] [ drop .\" Out of bounds\\n \" ] ifTrueFalse ]\n [ ` [ invoke cell-size malloc # ` action compile ` ] invoke is ]\n} is value:1-10:\n is to\n\nvalue:1-10: foo\n1 to foo\nfoo .\n", "language": "Toka" }, { "code": "typeset -i boundedint\nfunction boundedint.set {\n nameref var=${.sh.name}\n if (( 1 <= .sh.value && .sh.value <= 10 )); then\n # stash the valid value as a backup, in case we need to restore it\n typeset -i var.previous_value=${.sh.value}\n else\n print -u2 \"value out of bounds\"\n # restore previous value\n .sh.value=${var.previous_value}\n fi\n}\n\nboundedint=-5; echo $boundedint\nboundedint=5; echo $boundedint\nboundedint=15; echo $boundedint\n", "language": "UNIX-Shell" }, { "code": "#import nat\n\nmy_number ::\n\nthe_number %n -|~bounds.&BZ,~&B+ nleq~~lrlXPrX@G+ ~/the_number bounds|-?(~the_number,<'out of bounds'>!%)\nbounds %nW ~bounds.&B?(~bounds,(1,10)!)\n\nadd = my_number$[the_number: sum+ ~the_number~~]\nmul = my_number$[the_number: product+ ~the_number~~]\n", "language": "Ursala" }, { "code": "#cast _my_number\n\ntotal = add(my_number[the_number: 3],my_number[the_number: 4])\n", "language": "Ursala" }, { "code": "#cast _my_number\n\ntotal = mul(my_number[the_number: 3],my_number[the_number: 4])\n", "language": "Ursala" }, { "code": "#import nat\n\n#library+\n\n#import\n ^|A(~&,//+ nrange(1,10)?</~& <'out of bounds'>!%)*\n ~&n-=<'sum','difference','product','quotient','remainder'>*~ %QI nat\n", "language": "Ursala" }, { "code": "Private mvarValue As Integer\n\nPublic Property Let Value(ByVal vData As Integer)\n If (vData > 10) Or (vData < 1) Then\n Error 380 'Invalid property value; could also use 6, Overflow\n Else\n mvarValue = vData\n End If\nEnd Property\n\nPublic Property Get Value() As Integer\n Value = mvarValue\nEnd Property\n\nPrivate Sub Class_Initialize()\n 'vb defaults to 0 for numbers; let's change that...\n mvarValue = 1\nEnd Sub\n", "language": "Visual-Basic" }, { "code": "Public x As TinyInt\n\nPrivate Sub Form_Click()\n '0-11, to give chance of errors; also not integers, because VB massages data to fit, if possible.\n x = Rnd * 12\n Me.Print x\nEnd Sub\n\nPrivate Sub Form_Load()\n Randomize Timer\n Set x = New TinyInt '\"Set = New\" REQUIRED\nEnd Sub\n", "language": "Visual-Basic" }, { "code": "Structure LimitedInt\n Implements IComparable, IComparable(Of LimitedInt), IConvertible, IEquatable(Of LimitedInt), IFormattable\n\n Private Const MIN_VALUE = 1\n Private Const MAX_VALUE = 10\n\n Shared ReadOnly MinValue As New LimitedInt(MIN_VALUE)\n Shared ReadOnly MaxValue As New LimitedInt(MAX_VALUE)\n\n Private Shared Function IsValidValue(value As Integer) As Boolean\n Return value >= MIN_VALUE AndAlso value <= MAX_VALUE\n End Function\n\n Private ReadOnly _value As Integer\n ReadOnly Property Value As Integer\n Get\n ' Treat the default, 0, as being the minimum value.\n Return If(Me._value = 0, MIN_VALUE, Me._value)\n End Get\n End Property\n\n Sub New(value As Integer)\n If Not IsValidValue(value) Then Throw New ArgumentOutOfRangeException(NameOf(value), value, $\"Value must be between {MIN_VALUE} and {MAX_VALUE}.\")\n Me._value = value\n End Sub\n\n#Region \"IComparable\"\n Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo\n If TypeOf obj IsNot LimitedInt Then Throw New ArgumentException(\"Object must be of type \" + NameOf(LimitedInt), NameOf(obj))\n Return Me.CompareTo(DirectCast(obj, LimitedInt))\n End Function\n#End Region\n\n#Region \"IComparable(Of LimitedInt)\"\n Function CompareTo(other As LimitedInt) As Integer Implements IComparable(Of LimitedInt).CompareTo\n Return Me.Value.CompareTo(other.Value)\n End Function\n#End Region\n\n#Region \"IConvertible\"\n Function GetTypeCode() As TypeCode Implements IConvertible.GetTypeCode\n Return Me.Value.GetTypeCode()\n End Function\n\n Private Function ToBoolean(provider As IFormatProvider) As Boolean Implements IConvertible.ToBoolean\n Return DirectCast(Me.Value, IConvertible).ToBoolean(provider)\n End Function\n\n Private Function ToByte(provider As IFormatProvider) As Byte Implements IConvertible.ToByte\n Return DirectCast(Me.Value, IConvertible).ToByte(provider)\n End Function\n\n Private Function ToChar(provider As IFormatProvider) As Char Implements IConvertible.ToChar\n Return DirectCast(Me.Value, IConvertible).ToChar(provider)\n End Function\n\n Private Function ToDateTime(provider As IFormatProvider) As Date Implements IConvertible.ToDateTime\n Return DirectCast(Me.Value, IConvertible).ToDateTime(provider)\n End Function\n\n Private Function ToDecimal(provider As IFormatProvider) As Decimal Implements IConvertible.ToDecimal\n Return DirectCast(Me.Value, IConvertible).ToDecimal(provider)\n End Function\n\n Private Function ToDouble(provider As IFormatProvider) As Double Implements IConvertible.ToDouble\n Return DirectCast(Me.Value, IConvertible).ToDouble(provider)\n End Function\n\n Private Function ToInt16(provider As IFormatProvider) As Short Implements IConvertible.ToInt16\n Return DirectCast(Me.Value, IConvertible).ToInt16(provider)\n End Function\n\n Private Function ToInt32(provider As IFormatProvider) As Integer Implements IConvertible.ToInt32\n Return DirectCast(Me.Value, IConvertible).ToInt32(provider)\n End Function\n\n Private Function ToInt64(provider As IFormatProvider) As Long Implements IConvertible.ToInt64\n Return DirectCast(Me.Value, IConvertible).ToInt64(provider)\n End Function\n\n Private Function ToSByte(provider As IFormatProvider) As SByte Implements IConvertible.ToSByte\n Return DirectCast(Me.Value, IConvertible).ToSByte(provider)\n End Function\n\n Private Function ToSingle(provider As IFormatProvider) As Single Implements IConvertible.ToSingle\n Return DirectCast(Me.Value, IConvertible).ToSingle(provider)\n End Function\n\n Private Overloads Function ToString(provider As IFormatProvider) As String Implements IConvertible.ToString\n Return Me.Value.ToString(provider)\n End Function\n\n Private Function ToType(conversionType As Type, provider As IFormatProvider) As Object Implements IConvertible.ToType\n Return DirectCast(Me.Value, IConvertible).ToType(conversionType, provider)\n End Function\n\n Private Function ToUInt16(provider As IFormatProvider) As UShort Implements IConvertible.ToUInt16\n Return DirectCast(Me.Value, IConvertible).ToUInt16(provider)\n End Function\n\n Private Function ToUInt32(provider As IFormatProvider) As UInteger Implements IConvertible.ToUInt32\n Return DirectCast(Me.Value, IConvertible).ToUInt32(provider)\n End Function\n\n Private Function ToUInt64(provider As IFormatProvider) As ULong Implements IConvertible.ToUInt64\n Return DirectCast(Me.Value, IConvertible).ToUInt64(provider)\n End Function\n#End Region\n\n#Region \"IEquatable(Of LimitedInt)\"\n Overloads Function Equals(other As LimitedInt) As Boolean Implements IEquatable(Of LimitedInt).Equals\n Return Me = other\n End Function\n#End Region\n\n#Region \"IFormattable\"\n Private Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString\n Return Me.Value.ToString(format, formatProvider)\n End Function\n#End Region\n\n#Region \"Operators\"\n Shared Operator =(left As LimitedInt, right As LimitedInt) As Boolean\n Return left.Value = right.Value\n End Operator\n\n Shared Operator <>(left As LimitedInt, right As LimitedInt) As Boolean\n Return left.Value <> right.Value\n End Operator\n\n Shared Operator <(left As LimitedInt, right As LimitedInt) As Boolean\n Return left.Value < right.Value\n End Operator\n\n Shared Operator >(left As LimitedInt, right As LimitedInt) As Boolean\n Return left.Value > right.Value\n End Operator\n\n Shared Operator <=(left As LimitedInt, right As LimitedInt) As Boolean\n Return left.Value <= right.Value\n End Operator\n\n Shared Operator >=(left As LimitedInt, right As LimitedInt) As Boolean\n Return left.Value >= right.Value\n End Operator\n\n Shared Operator +(left As LimitedInt) As LimitedInt\n Return CType(+left.Value, LimitedInt)\n End Operator\n\n Shared Operator -(left As LimitedInt) As LimitedInt\n Return CType(-left.Value, LimitedInt)\n End Operator\n\n Shared Operator +(left As LimitedInt, right As LimitedInt) As LimitedInt\n Return CType(left.Value + right.Value, LimitedInt)\n End Operator\n\n Shared Operator -(left As LimitedInt, right As LimitedInt) As LimitedInt\n Return CType(left.Value - right.Value, LimitedInt)\n End Operator\n\n Shared Operator *(left As LimitedInt, right As LimitedInt) As LimitedInt\n Return CType(left.Value * right.Value, LimitedInt)\n End Operator\n\n Shared Operator /(left As LimitedInt, right As LimitedInt) As Double\n Return left.Value / right.Value\n End Operator\n\n Shared Operator \\(left As LimitedInt, right As LimitedInt) As LimitedInt\n Return CType(left.Value \\ right.Value, LimitedInt)\n End Operator\n\n Shared Operator ^(left As LimitedInt, right As LimitedInt) As Double\n Return left.Value ^ right.Value\n End Operator\n\n Shared Operator Mod(left As LimitedInt, right As LimitedInt) As LimitedInt\n Return CType(left.Value Mod right.Value, LimitedInt)\n End Operator\n\n Shared Operator And(left As LimitedInt, right As LimitedInt) As LimitedInt\n Return CType(left.Value And right.Value, LimitedInt)\n End Operator\n\n Shared Operator Or(left As LimitedInt, right As LimitedInt) As LimitedInt\n Return CType(left.Value Or right.Value, LimitedInt)\n End Operator\n\n Shared Operator Xor(left As LimitedInt, right As LimitedInt) As LimitedInt\n Return CType(left.Value Xor right.Value, LimitedInt)\n End Operator\n\n Shared Operator Not(left As LimitedInt) As LimitedInt\n Return CType(Not left.Value, LimitedInt)\n End Operator\n\n Shared Operator >>(left As LimitedInt, right As Integer) As LimitedInt\n Return CType(left.Value >> right, LimitedInt)\n End Operator\n\n Shared Operator <<(left As LimitedInt, right As Integer) As LimitedInt\n Return CType(left.Value << right, LimitedInt)\n End Operator\n\n Shared Widening Operator CType(value As LimitedInt) As Integer\n Return value.Value\n End Operator\n\n Shared Narrowing Operator CType(value As Integer) As LimitedInt\n If Not IsValidValue(value) Then Throw New OverflowException()\n Return New LimitedInt(value)\n End Operator\n#End Region\n\n 'Function TryFormat(destination As Span(Of Char), ByRef charsWritten As Integer, Optional format As ReadOnlySpan(Of Char) = Nothing, Optional provider As IFormatProvider = Nothing) As Boolean\n ' Return Me.Value.TryFormat(destination, charsWritten, format, provider)\n 'End Function\n\n Overrides Function GetHashCode() As Integer\n Return Me.Value.GetHashCode\n End Function\n\n Overrides Function Equals(obj As Object) As Boolean\n Return TypeOf obj Is LimitedInt AndAlso Me.Equals(DirectCast(obj, LimitedInt))\n End Function\n\n Overrides Function ToString() As String\n Return Me.Value.ToString()\n End Function\n\n#Region \"Shared Methods\"\n 'Shared Function TryParse(s As ReadOnlySpan(Of Char), ByRef result As Integer) As Boolean\n ' Return Integer.TryParse(s, result)\n 'End Function\n\n 'Shared Function TryParse(s As ReadOnlySpan(Of Char), style As Globalization.NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean\n ' Return Integer.TryParse(s, style, provider, result)\n 'End Function\n\n Shared Function Parse(s As String, provider As IFormatProvider) As Integer\n Return Integer.Parse(s, provider)\n End Function\n\n Shared Function Parse(s As String, style As Globalization.NumberStyles, provider As IFormatProvider) As Integer\n Return Integer.Parse(s, style, provider)\n End Function\n\n Shared Function TryParse(s As String, style As Globalization.NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean\n Return Integer.TryParse(s, style, provider, result)\n End Function\n\n Shared Function Parse(s As String) As Integer\n Return Integer.Parse(s)\n End Function\n Shared Function Parse(s As String, style As Globalization.NumberStyles) As Integer\n Return Integer.Parse(s, style)\n End Function\n\n 'Shared Function Parse(s As ReadOnlySpan(Of Char), Optional style As Globalization.NumberStyles = Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As Integer\n ' Return Integer.Parse(s, style, provider)\n 'End Function\n\n Shared Function TryParse(s As String, ByRef result As Integer) As Boolean\n Return Integer.TryParse(s, result)\n End Function\n#End Region\nEnd Structure\n", "language": "Visual-Basic-.NET" }, { "code": "LOCAL o As BoundedInt\no = NEWOBJECT(\"BoundedInt\")\nDO WHILE NOT o.lHasError\n o.nValue = o.nValue + 2 && will get as far as 9.\n ? o.nValue\nENDDO\n\nDEFINE CLASS BoundedInt As Custom\nnValue = 1\t&& default value\nlHasError = .F.\n\nPROCEDURE nValue_Assign(tnValue)\n*!* This method will check the parameter and if\n*!* it is out of bounds, the value will remain unchanged\n*!* and an error generated.\ntnValue = CAST(tnValue As I)\nIF BETWEEN(tnValue, 1, 10)\n THIS.nValue = tnValue\nELSE\n ERROR \"Value must be between 1 and 10.\"\nENDIF\nENDPROC\n\nPROCEDURE Error(nError, cMethod, nLine)\nIF nError = 1098\n MESSAGEBOX(MESSAGE(), 0, \"Error\")\nELSE\n DODEFAULT()\nENDIF \t\t\nTHIS.lHasError = .T.\nENDDEFINE\n", "language": "Visual-FoxPro" }, { "code": "class TinyInt {\n construct new(n) {\n if (!(n is Num && n.isInteger && n >= 1 && n <= 10)) {\n Fiber.abort(\"Argument must be an integer between 1 and 10.\")\n }\n _n = n\n }\n\n n { _n }\n\n +(other) { TinyInt.new(_n + other.n) }\n -(other) { TinyInt.new(_n - other.n) }\n *(other) { TinyInt.new(_n * other.n) }\n /(other) { TinyInt.new((_n / other.n).truncate) }\n\n ==(other) { _n == other.n }\n !=(other) { _n != other.n }\n\n toString { _n.toString }\n}\n\nvar a = TinyInt.new(1)\nvar b = TinyInt.new(2)\nvar c = a + b\nSystem.print(\"%(a) + %(b) = %(c)\")\nvar d = c - a\nSystem.print(\"%(c) - %(a) = %(d)\")\nvar e = d / d\nSystem.print(\"%(d) / %(d) = %(e)\")\nvar f = c * c\nSystem.print(\"%(c) * %(c) = %(f)\")\nSystem.print(\"%(a) != %(b) -> %(a != b)\")\nSystem.print(\"%(a) + %(a) == %(b) -> %((a + a) == b)\")\nvar g = f + b // out of range error here\n", "language": "Wren" } ]
Define-a-primitive-data-type
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Delegates\nnote: Object oriented\n", "language": "00-META" }, { "code": "A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in [http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaDesignPatterns/chapter_5_section_3.html#//apple_ref/doc/uid/TP40002974-CH6-DontLinkElementID_93 Cocoa framework on Mac OS X]. See also [[wp:Delegation pattern]].\n\nObjects responsibilities:\n\nDelegator:\n* Keep an optional delegate instance.\n* Implement \"operation\" method, returning the delegate \"thing\" if the delegate respond to \"thing\", or the string \"default implementation\".\n\nDelegate:\n* Implement \"thing\" and return the string \"delegate implementation\"\n\nShow how objects are created and used. First, without a delegate, then with a delegate that does not implement \"thing\", and last with a delegate that implements \"thing\".\n\n", "language": "00-TASK" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Delegation is\n package Things is\n -- We need a common root for our stuff\n type Object is tagged null record;\n type Object_Ptr is access all Object'Class;\n\n -- Objects that have operation thing\n type Substantial is new Object with null record;\n function Thing (X : Substantial) return String;\n\n -- Delegator objects\n type Delegator is new Object with record\n Delegate : Object_Ptr;\n end record;\n function Operation (X : Delegator) return String;\n\n No_Thing : aliased Object; -- Does not have thing\n Has_Thing : aliased Substantial; -- Has one\n end Things;\n\n package body Things is\n function Thing (X : Substantial) return String is\n begin\n return \"delegate implementation\";\n end Thing;\n\n function Operation (X : Delegator) return String is\n begin\n if X.Delegate /= null and then X.Delegate.all in Substantial'Class then\n return Thing (Substantial'Class (X.Delegate.all));\n else\n return \"default implementation\";\n end if;\n end Operation;\n end Things;\n\n use Things;\n\n A : Delegator; -- Without a delegate\nbegin\n Put_Line (A.Operation);\n A.Delegate := No_Thing'Access; -- Set no thing\n Put_Line (A.Operation);\n A.Delegate := Has_Thing'Access; -- Set a thing\n Put_Line (A.Operation);\nend Delegation;\n", "language": "Ada" }, { "code": "class Delegator {\n public generic delegate = none\n\n public function operation {\n if (typeof(delegate) == \"none\") {\n return \"default implementation\"\n }\n return delegate()\n }\n}\n\nfunction thing {\n return \"delegate implementation\"\n}\n\n// default, no delegate\nvar d = new Delegator()\nprintln (d.operation())\n\n// delegate\nvar d1 = new Delegator()\nd1.delegate = thing\nprintln (d1.operation())\n", "language": "Aikido" }, { "code": "text\nthing(void)\n{\n return \"delegate implementation\";\n}\n\ntext\noperation(record delegator)\n{\n text s;\n\n if (r_key(delegator, \"delegate\")) {\n if (r_key(delegator[\"delegate\"], \"thing\")) {\n s = call(r_query(delegator[\"delegate\"], \"thing\"));\n } else {\n s = \"default implementation\";\n }\n } else {\n s = \"default implementation\";\n }\n\n return s;\n}\n\ninteger\nmain(void)\n{\n record delegate, delegator;\n\n o_text(operation(delegator));\n o_byte('\\n');\n\n r_link(delegator, \"delegate\", delegate);\n o_text(operation(delegator));\n o_byte('\\n');\n\n r_put(delegate, \"thing\", thing);\n o_text(operation(delegator));\n o_byte('\\n');\n\n return 0;\n}\n", "language": "Aime" }, { "code": "# An Algol 68 approximation of delegates #\n\n# The delegate mode - the delegate is a STRUCT with a single field #\n# that is a REF PROC STRING. If this is NIL, it doesn't implement #\n# thing #\nMODE DELEGATE = STRUCT( REF PROC STRING thing );\n\n\n# A delegator mode that will invoke the delegate's thing method #\n# - if there is a delegate and the delegate has a thing method #\nMODE DELEGATOR = STRUCT( REF DELEGATE delegate\n , PROC( REF DELEGATE )STRING thing\n );\n\n# constructs a new DELEGATE with the specified PROC as its thing #\n# Algol 68 HEAP is like \"new\" in e.g. Java, but it can't take #\n# parameters, so this PROC does the equivalent #\nPROC new delegate = ( REF PROC STRING thing )REF DELEGATE:\n BEGIN\n REF DELEGATE result = HEAP DELEGATE;\n thing OF result := thing;\n\n result\n END # new delegate #\n;\n\n# constructs a new DELEGATOR with the specified DELEGATE #\nPROC new delegator = ( REF DELEGATE delegate )REF DELEGATOR:\n HEAP DELEGATOR := ( delegate\n , # anonymous PROC to invoke the delegate's thing #\n ( REF DELEGATE delegate )STRING:\n IF delegate IS REF DELEGATE(NIL)\n THEN\n # we have no delegate #\n \"default implementation\"\n\n ELIF thing OF delegate IS REF PROC STRING(NIL)\n THEN\n # the delegate doesn't have an implementation #\n \"default implementation\"\n\n ELSE\n # the delegate can thing #\n thing OF delegate\n\n FI\n )\n;\n\n\n# invokes the delegate's thing via the delagator #\n# Because the PROCs of a STRUCT don't have an equivalent of e.g. Java's #\n# \"this\", we have to explicitly pass the delegate as a parameter #\nPROC invoke thing = ( REF DELEGATOR delegator )STRING:\n # the following is Algol 68 for what would be written in Java as #\n # \"delegator.thing( delegator.delegate )\" #\n ( thing OF delegator )( delegate OF delegator )\n;\n\nmain:\n(\n\n print( ( \"No delegate : \"\n , invoke thing( new delegator( NIL ) )\n , newline\n , \"Delegate with no thing: \"\n , invoke thing( new delegator( new delegate( NIL ) ) )\n , newline\n , \"Delegate with a thing : \"\n , invoke thing( new delegator( new delegate( HEAP PROC STRING := STRING: ( \"delegate implementation\" ) ) ) )\n , newline\n )\n )\n\n)\n", "language": "ALGOL-68" }, { "code": "10 REM DELEGATION CODE AND EXAMPLE . ATARI BASIC 2020 A. KRESS [email protected]\n14 REM\n15 GOTO 100:REM MAINLOOP\n16 REM\n20 REM DELEGATOR OBJECT\n21 REM\n30 IF DELEGATE THEN GOSUB DELEGATE:GOTO 56\n35 REM\n50 REM DELEGATOR HAS TO DO THE JOB\n55 PRINT \"DEFAULT IMPLEMENTATION - DONE BY DELEGATOR\"\n56 RETURN\n60 REM CALL DELEGATE\n65 GOSUB DELEGATOR\n66 RETURN\n79 REM\n80 REM DELEGATE OBJECT\n81 REM\n90 PRINT \"DELEGATE IMPLEMENTATION - DONE BY DELEGATE\"\n91 RETURN\n99 REM\n100 REM MAINLOOP - DELEGATION EXAMPLE\n101 REM\n110 DELEGATE=0:REM NO DELEGATE\n120 GOSUB 20:REM INIT DELEGATOR\n130 DELEGATE=80:REM DELEGATE IS\n140 GOSUB 20:REM INIT DELEGATOR\n", "language": "Atari-BASIC" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n Responder operation;\n} *Delegate;\n\n/* Delegate class constructor */\nDelegate NewDelegate( Responder rspndr )\n{\n Delegate dl = malloc(sizeof(struct sDelegate));\n dl->operation = rspndr;\n return dl;\n}\n\n/* Thing method of Delegate */\nconst char *DelegateThing(Delegate dl, int p1)\n{\n return (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\ntypedef struct sDelegator {\n int param;\n char *phrase;\n Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n/* Delegator class constructor */\nDelegator NewDelegator( int p, char *phrase)\n{\n Delegator d = malloc(sizeof(struct sDelegator));\n d->param = p;\n d->phrase = phrase;\n d->delegate = &defaultDel;\t/* default delegate */\n return d;\n}\n\n/* Operation method of Delegator */\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n const char *rtn;\n if (delroy) {\n rtn = DelegateThing(delroy, p1);\n if (!rtn) {\t\t\t/* delegate didn't handle 'thing' */\n rtn = DelegateThing(theDelegator->delegate, p1);\n }\n }\n else \t\t/* no delegate */\n rtn = DelegateThing(theDelegator->delegate, p1);\n\n printf(\"%s\\n\", theDelegator->phrase );\n return rtn;\n}\n\n/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\nconst char *thing1( int p1)\n{\n printf(\"We're in thing1 with value %d\\n\" , p1);\n return \"delegate implementation\";\n}\n\nint main()\n{\n Delegate del1 = NewDelegate(&thing1);\n Delegate del2 = NewDelegate(NULL);\n Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n printf(\"Delegator returns %s\\n\\n\",\n Delegator_Operation( theDelegator, 3, NULL));\n printf(\"Delegator returns %s\\n\\n\",\n Delegator_Operation( theDelegator, 3, del1));\n printf(\"Delegator returns %s\\n\\n\",\n Delegator_Operation( theDelegator, 3, del2));\n return 0;\n}\n", "language": "C" }, { "code": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n// interface for all delegates\nclass IDelegate\n{\npublic:\n virtual ~IDelegate() {}\n};\n\n//interface for delegates supporting thing\nclass IThing\n{\npublic:\n virtual ~IThing() {}\n virtual std::string Thing() = 0;\n};\n\n// Does not handle Thing\nclass DelegateA : virtual public IDelegate\n{\n};\n\n// Handles Thing\nclass DelegateB : public IThing, public IDelegate\n{\n std::string Thing()\n {\n return \"delegate implementation\";\n }\n};\n\nclass Delegator\n{\npublic:\n std::string Operation()\n {\n if(Delegate) //have delegate\n if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n //delegate provides IThing interface\n return pThing->Thing();\n\n return \"default implementation\";\n }\n\n shared_ptr<IDelegate> Delegate;\n};\n\nint main()\n{\n shared_ptr<DelegateA> delegateA(new DelegateA());\n shared_ptr<DelegateB> delegateB(new DelegateB());\n Delegator delegator;\n\n // No delegate\n std::cout << delegator.Operation() << std::endl;\n\n // Delegate doesn't handle \"Thing\"\n delegator.Delegate = delegateA;\n std::cout << delegator.Operation() << std::endl;\n\n // Delegate handles \"Thing\"\n delegator.Delegate = delegateB;\n std::cout << delegator.Operation() << std::endl;\n\n/*\nPrints:\n\n default implementation\n default implementation\n delegate implementation\n */\n}\n", "language": "C++" }, { "code": "using System;\n\ninterface IOperable\n{\n string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n public string Operate()\n {\n return \"Delegate implementation.\";\n }\n}\n\nclass Delegator : IOperable\n{\n object Delegate;\n\n public string Operate()\n {\n var operable = Delegate as IOperable;\n return operable != null ? operable.Operate() : \"Default implementation.\";\n }\n\n static void Main()\n {\n var delegator = new Delegator();\n foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n {\n delegator.Delegate = @delegate;\n Console.WriteLine(delegator.Operate());\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(defprotocol Thing\n (thing [_]))\n\n(defprotocol Operation\n (operation [_]))\n\n(defrecord Delegator [delegate]\n Operation\n (operation [_] (try (thing delegate) (catch IllegalArgumentException e \"default implementation\"))))\n\n(defrecord Delegate []\n Thing\n (thing [_] \"delegate implementation\"))\n", "language": "Clojure" }, { "code": "class Delegator\n operation: ->\n if @delegate and typeof (@delegate.thing) is \"function\"\n return @delegate.thing()\n \"default implementation\"\n\nclass Delegate\n thing: ->\n \"Delegate Implementation\"\n\ntestDelegator = ->\n # Delegator with no delegate.\n a = new Delegator()\n console.log a.operation()\n\n # Delegator with delegate not implementing \"thing\"\n a.delegate = \"A delegate may be any object\"\n console.log a.operation()\n\n # Delegator with delegate that does implement \"thing\"\n a.delegate = new Delegate()\n console.log a.operation()\n\ntestDelegator()\n", "language": "CoffeeScript" }, { "code": " > coffee foo.coffee\ndefault implementation\ndefault implementation\nDelegate Implementation\n", "language": "CoffeeScript" }, { "code": "(defgeneric thing (object)\n (:documentation \"Thing the object.\"))\n\n(defmethod thing (object)\n \"default implementation\")\n\n(defclass delegator ()\n ((delegate\n :initarg :delegate\n :reader delegator-delegate)))\n\n(defmethod thing ((delegator delegator))\n \"If delegator has a delegate, invoke thing on the delegate,\notherwise return \\\"no delegate\\\".\"\n (if (slot-boundp delegator 'delegate)\n (thing (delegator-delegate delegator))\n \"no delegate\"))\n\n(defclass delegate () ())\n\n(defmethod thing ((delegate delegate))\n \"delegate implementation\")\n\n(let ((d1 (make-instance 'delegator))\n (d2 (make-instance 'delegator :delegate nil))\n (d3 (make-instance 'delegator :delegate (make-instance 'delegate))))\n (assert (string= \"no delegate\" (thing d1)))\n (assert (string= \"default implementation\" (thing d2)))\n (assert (string= \"delegate implementation\" (thing d3))))\n", "language": "Common-Lisp" }, { "code": "class Delegator {\n string delegate() hasDelegate;\n\n string operation() {\n if (hasDelegate is null)\n return \"Default implementation\";\n return hasDelegate();\n }\n\n typeof(this) setDg(string delegate() dg) {\n hasDelegate = dg;\n return this;\n }\n}\n\nvoid main() {\n import std.stdio;\n auto dr = new Delegator;\n string delegate() thing = () => \"Delegate implementation\";\n\n writeln(dr.operation());\n writeln(dr.operation());\n writeln(dr.setDg(thing).operation());\n}\n", "language": "D" }, { "code": "import tango.io.Stdout;\n\nclass Delegator\n{\n private char[] delegate() hasDelegate;\npublic:\n char[] operation() {\n if (hasDelegate is null)\n return \"default implementation\";\n return hasDelegate();\n }\n\n typeof(this) setDg(char[] delegate() dg)\n {\n hasDelegate = dg;\n return this;\n }\n}\n\nint main(char[][] args)\n{\n auto dr = new Delegator();\n auto thing = delegate char[]() { return \"delegate implementation\"; };\n\n Stdout ( dr.operation ).newline;\n Stdout ( dr.operation ).newline;\n Stdout ( dr.setDg(thing).operation ).newline;\n return 0;\n}\n", "language": "D" }, { "code": "class Delegator {\n var delegate;\n\n String operation() {\n if (delegate == null)\n return \"default implementation\";\n else\n return delegate.thing();\n }\n}\n\nclass Delegate {\n String thing() => \"delegate implementation\";\n}\n\nmain() {\n // Without a delegate:\n Delegator a = new Delegator();\n Expect.equals(\"default implementation\",a.operation());\n\n // any object doesn't work unless we can check for existing methods\n // a.delegate=new Object();\n // Expect.equals(\"default implementation\",a.operation());\n\n // With a delegate:\n Delegate d = new Delegate();\n a.delegate = d;\n Expect.equals(\"delegate implementation\",a.operation());\n}\n", "language": "Dart" }, { "code": "unit Printer;\n\ninterface\n\ntype\n // the \"delegate\"\n TRealPrinter = class\n public\n procedure Print;\n end;\n\n // the \"delegator\"\n TPrinter = class\n private\n FPrinter: TRealPrinter;\n public\n constructor Create;\n destructor Destroy; override;\n procedure Print;\n end;\n\nimplementation\n\n{ TRealPrinter }\n\nprocedure TRealPrinter.Print;\nbegin\n Writeln('Something...');\nend;\n\n{ TPrinter }\n\nconstructor TPrinter.Create;\nbegin\n inherited Create;\n FPrinter:= TRealPrinter.Create;\nend;\n\ndestructor TPrinter.Destroy;\nbegin\n FPrinter.Free;\n inherited;\nend;\n\nprocedure TPrinter.Print;\nbegin\n FPrinter.Print;\nend;\n\nend.\n", "language": "Delphi" }, { "code": "program Delegate;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils,\n Printer in 'Printer.pas';\n\nvar\n PrinterObj: TPrinter;\nbegin\n PrinterObj:= TPrinter.Create;\n try\n PrinterObj.Print;\n Readln;\n finally\n PrinterObj.Free;\n end;\nend.\n", "language": "Delphi" }, { "code": "def makeDelegator {\n /** construct without an explicit delegate */\n to run() {\n return makeDelegator(null)\n }\n\n /** construct with a delegate */\n to run(delegateO) { # suffix because \"delegate\" is a reserved keyword\n def delegator {\n to operation() {\n return if (delegateO.__respondsTo(\"thing\", 0)) {\n delegateO.thing()\n } else {\n \"default implementation\"\n }\n }\n }\n return delegator\n }\n}\n\n? def delegator := makeDelegator()\n> delegator.operation()\n# value: \"default implementation\"\n\n? def delegator := makeDelegator(def doesNotImplement {})\n> delegator.operation()\n# value: \"default implementation\"\n\n? def delegator := makeDelegator(def doesImplement {\n> to thing() { return \"delegate implementation\" }\n> })\n> delegator.operation()\n# value: \"default implementation\"\n", "language": "E" }, { "code": "import extensions;\nimport system'routines;\n\ninterface IOperable\n{\n abstract operate();\n}\n\nclass Operable : IOperable\n{\n constructor() {}\n\n operate()\n = \"delegate implementation\";\n}\n\nclass Delegator\n{\n object theDelegate;\n\n set Delegate(object)\n {\n theDelegate := object\n }\n\n internal operate(operable)\n = \"default implementation\";\n\n internal operate(IOperable operable)\n = operable.operate();\n\n operate()\n <= operate(theDelegate);\n}\n\npublic program()\n{\n var delegator := new Delegator();\n\n new object[]{nil, new Object(), new Operable()}.forEach::(o)\n {\n delegator.Delegate := o;\n\n console.printLine(delegator.operate())\n }\n}\n", "language": "Elena" }, { "code": "import extensions;\nimport system'routines;\n\nclass Operable\n{\n Operable = self;\n\n operate()\n = \"delegate implementation\";\n}\n\nclass Delegator\n{\n object Delegate : prop;\n\n constructor()\n {\n Delegate := nil\n }\n\n operate()\n {\n // if the object does not support \"Operable\" message - returns nil\n var operable := Delegate.Operable \\ back(nil);\n\n if (nil == operable)\n {\n ^ \"default implementation\"\n }\n else\n {\n ^ operable.operate()\n }\n }\n}\n\npublic program()\n{\n var delegator := new Delegator();\n\n new object[]{nil, new Object(), new Operable()}.forEach::(o)\n {\n delegator.Delegate := o;\n\n console.printLine(delegator.operate())\n }\n}\n", "language": "Elena" }, { "code": "type Delegator() =\n let defaultOperation() = \"default implementation\"\n let mutable del = null\n\n // write-only property \"Delegate\"\n member x.Delegate with set(d:obj) = del <- d\n\n member x.operation() =\n if del = null then\n defaultOperation()\n else\n match del.GetType().GetMethod(\"thing\", [||]) with\n | null -> defaultOperation()\n | thing -> thing.Invoke(del, [||]) :?> string\n\ntype Delegate() =\n member x.thing() = \"delegate implementation\"\n\nlet d = new Delegator()\nassert (d.operation() = \"default implementation\")\n\nd.Delegate <- \"A delegate may be any object\"\nassert (d.operation() = \"default implementation\")\n\nd.Delegate <- new Delegate()\nassert (d.operation() = \"delegate implementation\")\n", "language": "F-Sharp" }, { "code": "include FMS-SI.f\n\n:class delegate\n :m thing .\" delegate implementation\" ;m\n;class\n\ndelegate slave\n\n:class delegator\n ivar del \\ object container\n :m !: ( n -- ) del ! ;m\n :m init: 0 del ! ;m\n :m default .\" default implementation\" ;m\n :m operation\n del @ 0= if self default exit then\n del @ has-meth thing\n if del @ thing\n else self default\n then ;m\n;class\n\ndelegator master\n\n\\ First, without a delegate\nmaster operation \\ => default implementation\n\n\\ then with a delegate that does not implement \"thing\"\nobject o\no master !:\nmaster operation \\ => default implementation\n\n\\ and last with a delegate that implements \"thing\"\nslave master !:\nmaster operation \\ => delegate implementation\n", "language": "Forth" }, { "code": "Type Objeto\n operation As Function() As String\n other As String\nEnd Type\n\nFunction xthing() As String\n Return \"default implementation\"\nEnd Function\n\nFunction newX() As Objeto\n Dim As Objeto o\n o.operation = @xthing\n Return o\nEnd Function\n\nFunction newY() As Objeto\n Dim As Objeto o = newX()\n o.other = \"something else\"\n o.operation = 0 ' remove delegate\n Return o\nEnd Function\n\nFunction zthing() As String\n Return \"delegate implementation\"\nEnd Function\n\nFunction newZ() As Objeto\n Dim As Objeto o = newX()\n o.operation = @zthing ' replace delegate\n Return o\nEnd Function\n\nFunction operation(o As Objeto) As String\n Return Iif(o.operation <> 0, o.operation(), \"no implementation\")\nEnd Function\n\nDim As Objeto x = newX()\nDim As Objeto y = newY()\nDim As Objeto z = newZ()\n\nPrint operation(x)\nPrint operation(y)\nPrint operation(z)\n\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n delegate interface{} // the delegate may be any type\n}\n\n// interface that represents anything that supports thing()\ntype Thingable interface {\n thing() string\n}\n\nfunc (self Delegator) operation() string {\n if v, ok := self.delegate.(Thingable); ok {\n return v.thing()\n }\n return \"default implementation\"\n}\n\ntype Delegate int // any dummy type\n\nfunc (Delegate) thing() string {\n return \"delegate implementation\"\n}\n\nfunc main() {\n // Without a delegate:\n a := Delegator{}\n fmt.Println(a.operation()) // prints \"default implementation\"\n\n // With a delegate that does not implement \"thing\"\n a.delegate = \"A delegate may be any object\"\n fmt.Println(a.operation()) // prints \"default implementation\"\n\n // With a delegate:\n var d Delegate\n a.delegate = d\n fmt.Println(a.operation()) // prints \"delegate implementation\"\n}\n", "language": "Go" }, { "code": "Delegator := Object clone do(\n delegate ::= nil\n operation := method(\n if((delegate != nil) and (delegate hasSlot(\"thing\")),\n delegate thing,\n \"default implementation\"\n )\n )\n)\n\nDelegate := Object clone do(\n thing := method(\"delegate implementation\")\n)\n\na := clone Delegator\na operation println\n\na setDelegate(\"A delegate may be any object\")\na operation println\n\na setDelegate(Delegate clone)\na operation println\n", "language": "Io" }, { "code": "coclass 'delegator'\n operation=:3 :'thing__delegate ::thing y'\n thing=: 'default implementation'\"_\n setDelegate=:3 :'delegate=:y' NB. result is the reference to our new delegate\n delegate=:<'delegator'\n\ncoclass 'delegatee1'\n\ncoclass 'delegatee2'\n thing=: 'delegate implementation'\"_\n\nNB. set context in case this script was used interactively, instead of being loaded\ncocurrent 'base'\n", "language": "J" }, { "code": " obj=:conew'delegator'\n operation__obj''\ndefault implementation\n setDelegate__obj conew'delegatee1'\n┌─┐\n│4│\n└─┘\n operation__obj''\ndefault implementation\n setDelegate__obj conew'delegatee2'\n┌─┐\n│5│\n└─┘\n operation__obj''\ndelegate implementation\n", "language": "J" }, { "code": "interface Thingable {\n String thing();\n}\n\nclass Delegator {\n public Thingable delegate;\n\n public String operation() {\n if (delegate == null)\n return \"default implementation\";\n else\n return delegate.thing();\n }\n}\n\nclass Delegate implements Thingable {\n public String thing() {\n return \"delegate implementation\";\n }\n}\n\n// Example usage\n// Memory management ignored for simplification\npublic class DelegateExample {\n public static void main(String[] args) {\n // Without a delegate:\n Delegator a = new Delegator();\n assert a.operation().equals(\"default implementation\");\n\n // With a delegate:\n Delegate d = new Delegate();\n a.delegate = d;\n assert a.operation().equals(\"delegate implementation\");\n\n // Same as the above, but with an anonymous class:\n a.delegate = new Thingable() {\n public String thing() {\n return \"anonymous delegate implementation\";\n }\n };\n assert a.operation().equals(\"anonymous delegate implementation\");\n }\n}\n", "language": "Java" }, { "code": "package delegate;\n\n@FunctionalInterface\npublic interface Thingable {\n public String thing();\n}\n", "language": "Java" }, { "code": "package delegate;\n\nimport java.util.Optional;\n\npublic interface Delegator {\n public Thingable delegate();\n public Delegator delegate(Thingable thingable);\n\n public static Delegator new_() {\n return $Delegator.new_();\n }\n\n public default String operation() {\n return Optional.ofNullable(delegate())\n .map(Thingable::thing)\n .orElse(\"default implementation\")\n ;\n }\n}\n", "language": "Java" }, { "code": "package delegate;\n\n@FunctionalInterface\n/* package */ interface $Delegator extends Delegator {\n @Override\n public default Delegator delegate(Thingable thingable) {\n return new_(thingable);\n }\n\n public static $Delegator new_() {\n return new_(() -> null);\n }\n\n public static $Delegator new_(Thingable thingable) {\n return () -> thingable;\n }\n}\n", "language": "Java" }, { "code": "package delegate;\n\npublic final class Delegate implements Thingable {\n @Override\n public String thing() {\n return \"delegate implementation\";\n }\n}\n", "language": "Java" }, { "code": "package delegate;\n\n// Example usage\n// Memory management ignored for simplification\npublic interface DelegateTest {\n public static String thingable() {\n return \"method reference implementation\";\n }\n\n public static void main(String... arguments) {\n // Without a delegate:\n Delegator d1 = Delegator.new_();\n assert d1.operation().equals(\"default implementation\");\n\n // With a delegate:\n Delegator d2 = d1.delegate(new Delegate());\n assert d2.operation().equals(\"delegate implementation\");\n\n // Same as the above, but with an anonymous class:\n Delegator d3 = d2.delegate(new Thingable() {\n @Override\n public String thing() {\n return \"anonymous delegate implementation\";\n }\n });\n assert d3.operation().equals(\"anonymous delegate implementation\");\n\n // Same as the above, but with a method reference:\n Delegator d4 = d3.delegate(DelegateTest::thingable);\n assert d4.operation().equals(\"method reference implementation\");\n\n // Same as the above, but with a lambda expression:\n Delegator d5 = d4.delegate(() -> \"lambda expression implementation\");\n assert d5.operation().equals(\"lambda expression implementation\");\n }\n}\n", "language": "Java" }, { "code": "function Delegator() {\n this.delegate = null ;\n this.operation = function(){\n if(this.delegate && typeof(this.delegate.thing) == 'function')\n return this.delegate.thing() ;\n return 'default implementation' ;\n }\n}\n\nfunction Delegate() {\n this.thing = function(){\n return 'Delegate Implementation' ;\n }\n}\n\nfunction testDelegator(){\n var a = new Delegator() ;\n document.write(a.operation() + \"\\n\") ;\n\n a.delegate = 'A delegate may be any object' ;\n document.write(a.operation() + \"\\n\") ;\n\n a.delegate = new Delegate() ;\n document.write(a.operation() + \"\\n\") ;\n}\n", "language": "JavaScript" }, { "code": "module Delegates\n\nexport Delegator, Delegate\n\nstruct Delegator{T}\n delegate::T\nend\n\nstruct Delegate end\n\noperation(x::Delegator) = thing(x.delegate)\nthing(::Any) = \"default implementation\"\nthing(::Delegate) = \"delegate implementation\"\n\nend # module Delegates\n", "language": "Julia" }, { "code": "using .Delegates\n\na = Delegator(nothing)\nb = Delegator(\"string\")\n\nd = Delegate()\nc = Delegator(d)\n\n@show Delegates.operation(a)\n@show Delegates.operation(b)\n@show Delegates.operation(c)\n", "language": "Julia" }, { "code": "// version 1.1.51\n\ninterface Thingable {\n fun thing(): String?\n}\n\nclass Delegate(val responds: Boolean) : Thingable {\n override fun thing() = if (responds) \"delegate implementation\" else null\n}\n\nclass Delegator(d: Delegate) : Thingable by d {\n fun operation() = thing() ?: \"default implementation\"\n}\n\nfun main(args: Array<String>) {\n // delegate doesn't respond to 'thing'\n val d = Delegate(false)\n val dd = Delegator(d)\n println(dd.operation())\n\n // delegate responds to 'thing'\n val d2 = Delegate(true)\n val dd2 = Delegator(d2)\n println(dd2.operation())\n}\n", "language": "Kotlin" }, { "code": "Delegator ::= Object clone tap {\n self delegate := Nil.\n self clone := {\n Parents above (parent self, 'clone) call tap {\n self delegate := #'(self delegate).\n }.\n }.\n self operation := {\n localize.\n if { this delegate slot? 'thing. } then {\n this delegate thing.\n } else {\n \"default implementation\".\n }.\n }.\n}.\n\nDelegate ::= Object clone tap {\n self thing := \"delegate implementation\".\n}.\n\n;; No delegate\nfoo := Delegator clone.\nprintln: foo operation. ;; \"default implementation\"\n\n;; Delegate which lacks `thing`\nfoo delegate := Object.\nprintln: foo operation. ;; \"default implementation\"\n\n;; Delegate which implements `thing`\nfoo delegate := Delegate.\nprintln: foo operation. ;; \"delegate implementation\"\n", "language": "Latitude" }, { "code": "% define a category for holding the interface\n% and implementation for delegator objects\n\n:- category(delegator).\n\n :- public(delegate/1).\n :- public(set_delegate/1).\n\n :- private(delegate_/1).\n :- dynamic(delegate_/1).\n\n delegate(Delegate) :-\n ::delegate_(Delegate).\n\n set_delegate(Delegate) :-\n ::retractall(delegate_(Delegate)),\n ::assertz(delegate_(Delegate)).\n\n:- end_category.\n\n% define a simpler delegator object, with a\n% method, operation/1, for testing delegation\n\n:- object(a_delegator,\n imports(delegator)).\n\n :- public(operation/1).\n\n operation(String) :-\n ( ::delegate(Delegate), Delegate::current_predicate(thing/1) ->\n % a delegate is defined that understands the method thing/1\n Delegate::thing(String)\n ; % otherwise just use the default implementation\n String = 'default implementation'\n ).\n\n:- end_object.\n\n% define an interface for delegate objects\n\n:- protocol(delegate).\n\n :- public(thing/1).\n\n:- end_protocol.\n\n% define a simple delegate\n\n:- object(a_delegate,\n implements(delegate)).\n\n thing('delegate implementation').\n\n:- end_object.\n\n% define a simple object that doesn't implement the \"delegate\" interface\n\n:- object(an_object).\n\n:- end_object.\n\n% test the delegation solution when this file is compiled and loaded\n\n:- initialization((\n % without a delegate:\n a_delegator::operation(String1),\n String1 == 'default implementation',\n % with a delegate that does not implement thing/1:\n a_delegator::set_delegate(an_object),\n a_delegator::operation(String2),\n String2 == 'default implementation',\n % with a delegate that implements thing/1:\n a_delegator::set_delegate(a_delegate),\n a_delegator::operation(String3),\n String3 == 'delegate implementation'\n)).\n", "language": "Logtalk" }, { "code": "local function Delegator()\n return {\n operation = function(self)\n if (type(self.delegate)==\"table\") and (type(self.delegate.thing)==\"function\") then\n return self.delegate:thing()\n else\n return \"default implementation\"\n end\n end\n }\nend\n\nlocal function Delegate()\n return {\n thing = function(self)\n return \"delegate implementation\"\n end\n }\nend\n\nlocal function NonDelegate(which)\n if (which == 1) then return true -- boolean\n elseif (which == 2) then return 12345 -- number\n elseif (which == 3) then return \"Hello\" -- string\n elseif (which == 4) then return function() end -- function\n elseif (which == 5) then return { nothing = function() end } -- table (without \"thing\")\n elseif (which == 6) then return coroutine.create(function() end) -- thread\n elseif (which == 7) then return io.open(\"delegates.lua\",\"r\") -- userdata (if exists, or nil)\n end\nend\n\n-- WITH NO (NIL) DELEGATE\nlocal d = Delegator()\nassert(d:operation() == \"default implementation\")\n\n-- WITH A NON-DELEGATE\nfor i = 1, 7 do\n d.delegate = NonDelegate(i)\n assert(d:operation() == \"default implementation\")\nend\n\n-- WITH A PROPER DELEGATE\nd.delegate = Delegate()\nassert(d:operation() == \"delegate implementation\")\n\nprint(\"pass\")\n", "language": "Lua" }, { "code": "Module Checkit {\n\t\\\\ there are some kinds of objects in M2000, one of them is the Group, the user object\n\t\\\\ the delegate is a pointer to group\n\t\\\\ 1. We pass parameters to function operations$(), $ means that this function return string value\n\t\\\\ 2. We see how this can be done with pointers to group\n\tglobal doc$ \\\\ first define a global (for this module) to log output\n\tdocument doc$=\"Output:\"+{\n\t}\n\tclass Delegator {\n\tprivate:\n\t\tgroup delegate\n\t\tgroup null\n\tpublic:\n\t\tfunction operation$ {\n\t\t\tif not .delegate is .null then\n\t\t\t\ttry ok {\n\t\t\t\t\tret$=\"Delegate implementation:\"+.delegate=>operation$(![])\n\t\t\t\t\t\\\\ [] is the stack of values (leave empty stack), ! used to place this to callee stack\n\t\t\t\t}\n\t\t\t\tif not ok or error then ret$=\"No implementation\"\n\t\t\telse\n\t\t\t\tret$= \"Default implementation\"\n\t\t\tend if\n\t\t\t\\\\ a global variable and all group members except arrays use <= not =. Simple = used for declaring local variables\n\t\t\tdoc$<=ret$+{\n\t\t\t}\n\t\t\t=ret$\n\t\t}\t\n\tclass:\n\t\tModule Delegator {\n\t\t\t\tclass none {}\n\t\t\t\t.null->none()\n\t\t\t\tIf match(\"G\") then .delegate->(group) else .delegate<=.null\n\t\t}\n\t}\n\t\n\tClass Thing {\n\t\tfunction operation$(a,b) {\n\t\t\t=str$(a*b)\n\t\t}\t\n\t}\n\tModule CallbyReference (&z as group) {\n\t\tPrint Z.operation$(5,30)\n\t}\n\tModule CallbyValue (z as group) {\n\t\tPrint Z.operation$(2,30)\n\t}\n\tModule CallbyReference2 (&z as pointer) {\n\t\tPrint Z=>operation$(5,30)\n\t}\n\tModule CallbyValue2 (z as pointer) {\n\t\tPrint Z=>operation$(2,30)\n\t}\n\t\\\\ Normal Group ' no logging to doc$\n\tN=Thing()\n\tPrint N.operation$(10,20)\n\tCallbyReference &N\n\tCallbyValue N\n\tN1->N ' N1 is a pointer to a named group\n\tPrint N1=>operation$(10,20)\n\tCallbyReference2 &N1\n\tCallbyValue2 N1\n\tN1->(N) ' N1 now is a pointer to a float group (a copy of N)\n \tPrint N1=>operation$(10,20)\n\tCallbyReference2 &N1\n\tCallbyValue2 N1\n\t\\\\ using named groups (A is a group, erased when this module exit)\n\tA=Delegator()\n\tB=Delegator(Thing())\n\tPrint A.operation$(10,20)\n\tPrint B.operation$(10,20)\n\tA=B\n\tCallbyReference &A\n\tCallbyValue A\n\t\\\\ M2000 has two kinds of pointers to groups\n\t\\\\ one is a pointer to a no named group (a float group)\n\t\\\\ a float group leave until no pointer refer to it\n\t\\\\ using pointers to groups (A1 is a pointer to Group)\n\tA1->Delegator()\n\tB1->Delegator(Thing())\n\tPrint A1=>operation$(10,20)\n\tPrint B1=>operation$(10,20)\n\tA1=B1\n\tCallbyReference2 &A1\n\tCallbyValue2 A1\n\t\\\\ Second type is a pointer to a named group\n\t\\\\ the pointer hold a weak reference to named group\n\t\\\\ so a returned pointer of thid kind can be invalid if actual reference not exist\n\tA=Delegator() ' copy a float group to A\n\tA1->A\n\tB1->B\n\tPrint A1=>operation$(10,20)\n\tPrint B1=>operation$(10,20)\n\tA1=B1\n\tCallbyReference2 &A1\n\tCallbyValue2 A1\n\tGroup Something {\t\t\n\t}\n\tB=Delegator(Something)\n\tPrint B.operation$(10,20)\n\tCallbyReference &B\n\tCallbyValue B\n\tReport Doc$\n\tClipboard Doc$\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "delegator[del_]@operate :=\n If[StringQ[del@operate], del@operate, \"default implementation\"];\ndel1 = Null;\ndel2@banana = \"phone\";\ndel3@operate = \"delegate implementation\";\nPrint[delegator[#]@operate] & /@ {del1, del2, del3};\n", "language": "Mathematica" }, { "code": "{\n\ttype Delegator\n\n\tF init(d:Delegator) d.delegate = null\n\n\tF default_impl(d:Delegator) 'default implementation'\n\n\tF operation(d:Delegator) default_impl(d)\n\n\tF operation(d:Delegator) {\n\t\tguard defined thing\n\t\tguard thing is Fun\n\t\ttry {\n\t\t\td.delegate.thing()\n\t\t}\n\t\tcatch(e:ImplNotFound) {\n\t\t\t# Might be unrelated exception, so check and optionally rethrow\n\t\t\te.callable !== thing throws e\n\t\t\tdefault_impl(d)\n\t\t}\n\t}\n\n\tF operation(d:Delegator) {\n\t\tguard d.delegate is Null\n\t\tdefault_impl(d)\n\t}\n\n\n\ta = Delegator()\n\techo(a.operation())\n\n\t# There is no method thing(s:Str)\n\ta.delegate = \"abc\"\n\techo(a.operation())\n\n\t# ... now there is method thing(s:Str)\n\tF thing(s:Str) 'delegate implementation'\n\techo(a.operation())\n\t\n}\n", "language": "NGS" }, { "code": "####################################################################################################\n# Base delegate.\n\ntype Delegate = ref object of RootObj\n nil\n\nmethod thing(d: Delegate): string {.base.} =\n ## Default implementation of \"thing\".\n ## Using a method rather than a proc allows dynamic dispatch.\n \"default implementation\"\n\n\n####################################################################################################\n# Delegator.\n\ntype Delegator = object\n delegate: Delegate\n\nproc initDelegator(d: Delegate = nil): Delegator =\n ## Create a delegator with given delegate or nil.\n if d.isNil:\n Delegator(delegate: Delegate()) # Will use a default delegate instance.\n else:\n Delegator(delegate: d) # Use the provided delegate instance.\n\nproc operation(d: Delegator): string =\n ## Calls the delegate.\n d.delegate.thing()\n\n\n####################################################################################################\n# Usage.\n\nlet d = initDelegator()\necho \"Without any delegate: \", d.operation()\n\ntype Delegate1 = ref object of Delegate\n\nlet d1 = initDelegator(Delegate1())\necho \"With a delegate which desn’t provide the “thing” method: \", d1.operation()\n\ntype Delegate2 = ref object of Delegate\n\nmethod thing(d: Delegate2): string =\n \"delegate implementation\"\n\nlet d2 = initDelegator(Delegate2())\necho \"With a delegate which provided the “thing” method: \", d2.operation()\n", "language": "Nim" }, { "code": "interface Thingable {\n method : virtual : public : Thing() ~ String;\n}\n\nclass Delegator {\n @delegate : Thingable;\n\n New() {\n }\n\n method : public : SetDelegate(delegate : Thingable) ~ Nil {\n @delegate := delegate;\n }\n\n method : public : Operation() ~ String {\n if(@delegate = Nil) {\n return \"default implementation\";\n }\n else {\n return @delegate->Thing();\n };\n }\n}\n\nclass Delegate implements Thingable {\n New() {\n }\n\n method : public : Thing() ~ String {\n return \"delegate implementation\";\n }\n}\n\nclass Example {\n function : Main(args : String[]) ~ Nil {\n # Without a delegate:\n a := Delegator->New();\n Runtime->Assert(a->Operation()->Equals(\"default implementation\"));\n\n # With a delegate:\n d := Delegate->New();\n a->SetDelegate(d);\n Runtime->Assert(a->Operation()->Equals(\"delegate implementation\"));\n\n # Same as the above, but with an anonymous class:\n a->SetDelegate(Base->New() implements Thingable {\n method : public : Thing() ~ String {\n return \"anonymous delegate implementation\";\n }\n });\n\n Runtime->Assert(a->Operation()->Equals(\"anonymous delegate implementation\"));\n }\n}\n", "language": "Objeck" }, { "code": "#import <Foundation/Foundation.h>\n\n@interface Delegator : NSObject {\n\n id delegate;\n}\n\n- (id)delegate;\n- (void)setDelegate:(id)obj;\n- (NSString *)operation;\n\n@end\n\n@implementation Delegator\n\n- (id)delegate {\n\n return delegate;\n}\n\n- (void)setDelegate:(id)obj {\n\n delegate = obj; // Weak reference\n}\n\n- (NSString *)operation {\n\n if ([delegate respondsToSelector:@selector(thing)])\n return [delegate thing];\n\n return @\"default implementation\";\n}\n\n@end\n\n// Any object may implement these\n@interface NSObject (DelegatorDelegating)\n\n- (NSString *)thing;\n\n@end\n\n@interface Delegate : NSObject\n\n// Don't need to declare -thing because any NSObject has this method\n\n@end\n\n@implementation Delegate\n\n- (NSString *)thing {\n\n return @\"delegate implementation\";\n}\n\n@end\n\n// Example usage\n// Memory management ignored for simplification\nint main() {\n\n // Without a delegate:\n Delegator *a = [[Delegator alloc] init];\n NSLog(@\"%d\\n\", [[a operation] isEqualToString:@\"default implementation\"]);\n\n // With a delegate that does not implement thing:\n [a setDelegate:@\"A delegate may be any object\"];\n NSLog(@\"%d\\n\", [[a operation] isEqualToString:@\"delegate implementation\"]);\n\n // With a delegate that implements \"thing\":\n Delegate *d = [[Delegate alloc] init];\n [a setDelegate:d];\n NSLog(@\"%d\\n\", [[a operation] isEqualToString:@\"delegate implementation\"]);\n\n return 0;\n}\n", "language": "Objective-C" }, { "code": "#import <Foundation/Foundation.h>\n\n// Formal protocol for the delegate\n@protocol DelegatorDelegatingProtocol\n - (NSString *)thing;\n@end\n\n@interface Delegator : NSObject\n @property (weak) id delegate;\n - (NSString *)operation;\n@end\n@implementation Delegator\n - (NSString *)operation {\n if ([self.delegate respondsToSelector: @selector(thing)])\n return [self.delegate thing];\n\n return @\"default implementation\";\n }\n@end\n\n@interface Delegate : NSObject\n <DelegatorDelegatingProtocol>\n@end\n@implementation Delegate\n - (NSString *)thing { return @\"delegate implementation\"; }\n@end\n\n// Example usage with Automatic Reference Counting\nint main() {\n @autoreleasepool {\n // Without a delegate:\n Delegator *a = [Delegator new];\n NSLog(@\"%@\", [a operation]); // prints \"default implementation\"\n\n // With a delegate that does not implement thing:\n a.delegate = @\"A delegate may be any object\";\n NSLog(@\"%@\", [a operation]); // prints \"default implementation\"\n\n // With a delegate that implements \"thing\":\n Delegate *d = [Delegate new];\n a.delegate = d;\n NSLog(@\"%@\", [a operation]); // prints \"delegate implementation\"\n }\n return 0;\n}\n", "language": "Objective-C" }, { "code": "Object Class new: Delegate1\n\nObject Class new: Delegate2\nDelegate2 method: thing \"Delegate implementation\" println ;\n\nObject Class new: Delegator(delegate)\nDelegator method: initialize := delegate ;\n\nDelegator method: operation\n @delegate respondTo(#thing) ifTrue: [ @delegate thing return ]\n \"Default implementation\" println ;\n", "language": "Oforth" }, { "code": "Delegator new(null) operation\nDefault implementation\n\nDelegator new(Delegate1 new) operation\nDefault implementation\n\nDelegator new(Delegate2 new) operation\nDelegate implementation\n", "language": "Oforth" }, { "code": "delegator = .delegator~new -- no delegate\nsay delegator~operation\n-- an invalid delegate type\ndelegator~delegate = \"Some string\"\nsay delegator~operation\n-- a good delegate\ndelegator~delegate = .thing~new\nsay delegator~operation\n-- a directory object with a thing entry defined\nd = .directory~new\nd~thing = \"delegate implementation\"\ndelegator~delegate = d\nsay delegator~operation\n\n-- a class we can use as a delegate\n::class thing\n::method thing\n return \"delegate implementation\"\n\n::class delegator\n::method init\n expose delegate\n use strict arg delegate = .nil\n\n::attribute delegate\n\n::method operation\n expose delegate\n if delegate == .nil then return \"default implementation\"\n\n -- Note: We could use delegate~hasMethod(\"THING\") to check\n -- for a THING method, but this will fail of the object relies\n -- on an UNKNOWN method to handle the method. By trapping\n -- NOMETHOD conditions, we can allow those calls to go\n -- through\n signal on nomethod\n return delegate~thing\n\nnomethod:\n return \"default implementation\"\n", "language": "OoRexx" }, { "code": "class DelegateA 'not implmenting thing()\n'==============\n'\nstring message\n\nend class\n\nclass DelegateB 'implementing thing()\n'==============\n'\nstring message\n\nmethod thing() as string\nreturn message\nend method\n'\nend class\n\n\nClass Delegator\n'==============\n'\nhas DelegateA dgA\nhas DelegateB dgB\n'\nmethod operation() as DelegateB\ndgB.message=\"Delegate Implementation\"\nreturn @dgB\nend method\n\nmethod thing() as string\nreturn \"not using Delegate\"\nend method\n'\nend class\n\n'====\n'TEST\n'====\n\nDelegator dgr\nlet dg=dgr.operation\nprint dgr.thing 'result \"not using Delegate\"\nprint dg.thing 'result \"Delegate Implementation\"\n", "language": "OxygenBasic" }, { "code": "declare\n class Delegator from BaseObject\n attr\n\tdelegate:unit\n\n meth set(DG)\n\t{Object.is DG} = true %% assert: DG must be an object\n\tdelegate := DG\n end\n\n meth operation($)\n\tif @delegate == unit then\n\t {self default($)}\n\telse\n\t try\n\t {@delegate thing($)}\n\t catch error(object(lookup ...) ...) then\n\t %% the delegate did not understand the message\n\t {self default($)}\n\t end\n\tend\n end\n\n meth default($)\n\t\"default implementation\"\n end\n end\n\n class Delegate from BaseObject\n meth thing($)\n\t\"delegate Implementation\"\n end\n end\n\n A = {New Delegator noop}\nin\n {System.showInfo {A operation($)}}\n\n {A set({New BaseObject noop})}\n {System.showInfo {A operation($)}}\n\n {A set({New Delegate noop})}\n {System.showInfo {A operation($)}}\n", "language": "Oz" }, { "code": "use strict;\n\npackage Delegator;\nsub new {\n bless {}\n}\nsub operation {\n my ($self) = @_;\n if (defined $self->{delegate} && $self->{delegate}->can('thing')) {\n $self->{delegate}->thing;\n } else {\n 'default implementation';\n }\n}\n1;\n\npackage Delegate;\nsub new {\n bless {};\n}\nsub thing {\n 'delegate implementation'\n}\n1;\n\n\npackage main;\n# No delegate\nmy $a = Delegator->new;\n$a->operation eq 'default implementation' or die;\n\n# With a delegate that does not implement \"thing\"\n$a->{delegate} = 'A delegate may be any object';\n$a->operation eq 'default implementation' or die;\n\n# With delegate that implements \"thing\"\n$a->{delegate} = Delegate->new;\n$a->operation eq 'delegate implementation' or die;\n", "language": "Perl" }, { "code": "use 5.010_000;\n\npackage Delegate::Protocol\nuse Moose::Role;\n# All methods in the Protocol is optional\n#optional 'thing';\n# If we wanted to have a required method, we would state:\n# requires 'required_method';\n#\n\npackage Delegate::NoThing;\nuse Moose;\nwith 'Delegate::Protocol';\n\npackage Delegate;\nuse Moose;\n\n# The we confirm to Delegate::Protocol\nwith 'Delegate::Protocol';\nsub thing { 'delegate implementation' };\n\npackage Delegator;\nuse Moose;\n\nhas delegate => (\n is => 'rw',\n does => 'Delegate::Protocol', # Moose insures that the delegate confirms to the protocol.\n predicate => 'hasDelegate'\n);\n\nsub operation {\n\n my ($self) = @_;\n if( $self->hasDelegate && $self->delegate->can('thing') ){\n return $self->delegate->thing() . $postfix; # we are know that delegate has thing.\n } else {\n return 'default implementation';\n }\n};\n\npackage main;\nuse strict;\n\n# No delegate\nmy $delegator = Delegator->new();\n$delegator->operation eq 'default implementation' or die;\n\n# With a delegate that does not implement \"thing\"\n$delegator->delegate( Delegate::NoThing->new );\n$delegator->operation eq 'default implementation' or die;\n\n# With delegate that implements \"thing\"\n$delegator->delegate( Delegate->new );\n$delegator->operation eq 'delegate implementation' or die;\n", "language": "Perl" }, { "code": "enum OTHER, OPERATION\n\nfunction operation(object o)\n integer rid = o[OPERATION]\n if rid!=NULL then\n return call_func(rid,{})\n end if\n return \"no implementation\"\nend function\n\nfunction xthing()\n return \"default implementation\"\nend function\n\nfunction newX()\n return {1,routine_id(\"xthing\"),2}\nend function\n\nfunction newY()\n object res = newX()\n res[OTHER] = \"something else\"\n -- remove delegate:\n res[OPERATION] = NULL\n return res\nend function\n\nfunction zthing()\n return \"delegate implementation\"\nend function\n\nfunction newZ()\n object res = newX()\n -- replace delegate:\n res[OPERATION] = routine_id(\"zthing\")\n return res\nend function\n\nobject x = newX(),\n y = newY(),\n z = newZ()\n\n?operation(x)\n?operation(y)\n?operation(z)\n", "language": "Phix" }, { "code": "?operation(x)\ntry -- (since rid=NULL check commented out)\n ?operation(y)\ncatch e\n ?\"oops, no implementation\"\nend try\n?operation(z)\n", "language": "Phix" }, { "code": "class Delegator {\n function __construct() {\n $this->delegate = NULL ;\n }\n function operation() {\n if(method_exists($this->delegate, \"thing\"))\n return $this->delegate->thing() ;\n return 'default implementation' ;\n }\n}\n\nclass Delegate {\n function thing() {\n return 'Delegate Implementation' ;\n }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n", "language": "PHP" }, { "code": "(class +Delegator)\n# delegate\n\n(dm operation> ()\n (if (: delegate)\n (thing> @)\n \"default implementation\" ) )\n\n\n(class +Delegate)\n# thing\n\n(dm T (Msg)\n (=: thing Msg) )\n\n(dm thing> ()\n (: thing) )\n\n\n(let A (new '(+Delegator))\n # Without a delegate\n (println (operation> A))\n\n # With delegate that does not implement 'thing>'\n (put A 'delegate (new '(+Delegate)))\n (println (operation> A))\n\n # With delegate that implements 'thing>'\n (put A 'delegate (new '(+Delegate) \"delegate implementation\"))\n (println (operation> A)) )\n", "language": "PicoLisp" }, { "code": "uses objectclass;\ndefine :class Delegator;\n slot delegate = false;\nenddefine;\n\ndefine :class Delegate;\nenddefine;\n\ndefine :method thing(x : Delegate);\n 'delegate implementation'\nenddefine;\n\ndefine :method operation(x : Delegator);\nif delegate(x) and fail_safe(delegate(x), thing) then\n ;;; Return value is on the stack\nelse\n 'default implementation'\nendif;\nenddefine;\n\n;;; Default, without a delegate\nlvars a = newDelegator();\noperation(a) =>\n\n;;; a delegating to itself (works because Delegator does not\n;;; implement thing)\na -> delegate(a);\noperation(a) =>\n\n;;; delegating to a freshly created Delegate\nnewDelegate() -> delegate(a);\noperation(a) =>\n", "language": "Pop11" }, { "code": "class Delegator:\n def __init__(self):\n self.delegate = None\n def operation(self):\n if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n return self.delegate.thing()\n return 'default implementation'\n\nclass Delegate:\n def thing(self):\n return 'delegate implementation'\n\nif __name__ == '__main__':\n\n # No delegate\n a = Delegator()\n assert a.operation() == 'default implementation'\n\n # With a delegate that does not implement \"thing\"\n a.delegate = 'A delegate may be any object'\n assert a.operation() == 'default implementation'\n\n # With delegate that implements \"thing\"\n a.delegate = Delegate()\n assert a.operation() == 'delegate implementation'\n", "language": "Python" }, { "code": "#lang racket\n;; Delegates. Tim Brown 2014-10-16\n\n(define delegator%\n (class object%\n (init-field [delegate #f])\n (define/public (operation)\n (cond [(and (object? delegate) (object-method-arity-includes? delegate 'thing 0))\n (send delegate thing)]\n [else \"default implementation\"]))\n (super-new)))\n\n(define non-thinging-delegate% (class object% (super-new)))\n\n(define thinging-delegate%\n (class object%\n (define/public (thing) \"delegate implementation\")\n (super-new)))\n\n(module+ test\n (require tests/eli-tester)\n (define delegator-1 (new delegator%))\n (define delegator-2 (new delegator%))\n (define non-thinging-delegate (new non-thinging-delegate%))\n (define thinging-delegate (new thinging-delegate%))\n\n (test\n (send delegator-1 operation) => \"default implementation\"\n (send delegator-2 operation) => \"default implementation\"\n (set-field! delegate delegator-1 non-thinging-delegate) => (void)\n (set-field! delegate delegator-2 thinging-delegate) => (void)\n (send delegator-1 operation) => \"default implementation\"\n (send delegator-2 operation) => \"delegate implementation\"\n (send (new delegator% [delegate thinging-delegate]) operation) => \"delegate implementation\"))\n", "language": "Racket" }, { "code": "class Non-Delegate { }\n\nclass Delegate {\n\tmethod thing {\n\t\treturn \"delegate implementation\"\n\t}\n}\n\nclass Delegator {\n\thas $.delegate is rw;\n\n\tmethod operation {\n\t\t$.delegate.^can( 'thing' ) ?? $.delegate.thing\n\t\t!! \"default implementation\"\n\t}\n}\n\nmy Delegator $d .= new;\n\nsay \"empty: \"~$d.operation;\n\n$d.delegate = Non-Delegate.new;\n\nsay \"Non-Delegate: \"~$d.operation;\n\n$d.delegate = Delegate.new;\n\nsay \"Delegate: \"~$d.operation;\n", "language": "Raku" }, { "code": "class Delegator\n attr_accessor :delegate\n def operation\n if @delegate.respond_to?(:thing)\n @delegate.thing\n else\n 'default implementation'\n end\n end\nend\n\nclass Delegate\n def thing\n 'delegate implementation'\n end\nend\n\nif __FILE__ == $PROGRAM_NAME\n\n # No delegate\n a = Delegator.new\n puts a.operation # prints \"default implementation\"\n\n # With a delegate that does not implement \"thing\"\n a.delegate = 'A delegate may be any object'\n puts a.operation # prints \"default implementation\"\n\n # With delegate that implements \"thing\"\n a.delegate = Delegate.new\n puts a.operation # prints \"delegate implementation\"\nend\n", "language": "Ruby" }, { "code": "require 'forwardable'\n\nclass Delegator; extend Forwardable\n attr_accessor :delegate\n def_delegator :@delegate, :thing, :delegated\n\n def initialize\n @delegate = Delegate.new()\n end\nend\n\nclass Delegate\n def thing\n 'Delegate'\n end\nend\n\na = Delegator.new\nputs a.delegated # prints \"Delegate\"\n", "language": "Ruby" }, { "code": "trait Thingable {\n fn thing(&self) -> &str;\n}\n\nstruct Delegator<T>(Option<T>);\n\nstruct Delegate {}\n\nimpl Thingable for Delegate {\n fn thing(&self) -> &'static str {\n \"Delegate implementation\"\n }\n}\n\nimpl<T: Thingable> Thingable for Delegator<T> {\n fn thing(&self) -> &str {\n self.0.as_ref().map(|d| d.thing()).unwrap_or(\"Default implmementation\")\n }\n}\n\nfn main() {\n let d: Delegator<Delegate> = Delegator(None);\n println!(\"{}\", d.thing());\n\n let d: Delegator<Delegate> = Delegator(Some(Delegate {}));\n println!(\"{}\", d.thing());\n}\n", "language": "Rust" }, { "code": "#![feature(specialization)]\n\ntrait Thingable {\n fn thing(&self) -> &str;\n}\n\nstruct Delegator<T>(Option<T>);\n\nstruct Delegate {}\n\nimpl Thingable for Delegate {\n fn thing(&self) -> &'static str {\n \"Delegate implementation\"\n }\n}\n\nimpl<T> Thingable for Delegator<T> {\n default fn thing(&self) -> &str {\n \"Default implementation\"\n }\n}\n\nimpl<T: Thingable> Thingable for Delegator<T> {\n fn thing(&self) -> &str {\n self.0.as_ref().map(|d| d.thing()).unwrap_or(\"Default implmementation\")\n }\n}\n\nfn main() {\n let d: Delegator<i32> = Delegator(None);\n println!(\"{}\", d.thing());\n\n let d: Delegator<i32> = Delegator(Some(42));\n println!(\"{}\", d.thing());\n\n let d: Delegator<Delegate> = Delegator(None);\n println!(\"{}\", d.thing());\n\n let d: Delegator<Delegate> = Delegator(Some(Delegate {}));\n println!(\"{}\", d.thing());\n}\n", "language": "Rust" }, { "code": "trait Thingable {\n def thing: String\n}\n\nclass Delegator {\n var delegate: Thingable = _\n\n def operation: String = if (delegate == null) \"default implementation\"\n else delegate.thing\n}\n\nclass Delegate extends Thingable {\n override def thing = \"delegate implementation\"\n}\n\n// Example usage\n// Memory management ignored for simplification\nobject DelegateExample extends App {\n\n val a = new Delegator\n assert(a.operation == \"default implementation\")\n // With a delegate:\n val d = new Delegate\n a.delegate = d\n assert(a.operation == \"delegate implementation\")\n // Same as the above, but with an anonymous class:\n a.delegate = new Thingable() {\n override def thing = \"anonymous delegate implementation\"\n }\n assert(a.operation == \"anonymous delegate implementation\")\n\n}\n", "language": "Scala" }, { "code": "class NonDelegate { }\n\nclass Delegate {\n method thing {\n return \"delegate implementation\"\n }\n}\n\nclass Delegator (delegate = null) {\n method operation {\n\n if (delegate.respond_to(:thing)) {\n return delegate.thing\n }\n\n return \"default implementation\"\n }\n}\n\nvar d = Delegator()\nsay \"empty: #{d.operation}\"\nd.delegate = NonDelegate()\nsay \"NonDelegate: #{d.operation}\"\nd.delegate = Delegate()\nsay \"Delegate: #{d.operation}\"\n", "language": "Sidef" }, { "code": "Object\n subclass:#Thingy\n instanceVariableNames:''\n\nthing\n ^ 'thingy implementation'\n", "language": "Smalltalk" }, { "code": "Object\n subclass:#Delegator\n instanceVariableNames:'delegate'\n\ndelegate:something\n delegate := something\n\noperation\n ^ delegate\n perform:#thing ifNotUnderstood:'default implementation'.\n", "language": "Smalltalk" }, { "code": "|d|\nd := Delegator new.\nd operation.\n-> 'default implementation'\n\nd delegate:(Thingy new).\nd operation.\n-> 'thingy implementation'\n", "language": "Smalltalk" }, { "code": "import Foundation\n\nprotocol Thingable { // prior to Swift 1.2, needs to be declared @objc\n func thing() -> String\n}\n\nclass Delegator {\n weak var delegate: AnyObject?\n func operation() -> String {\n if let f = self.delegate?.thing {\n return f()\n } else {\n return \"default implementation\"\n }\n }\n}\n\nclass Delegate {\n dynamic func thing() -> String { return \"delegate implementation\" }\n}\n\n// Without a delegate:\nlet a = Delegator()\nprintln(a.operation()) // prints \"default implementation\"\n\n// With a delegate that does not implement thing:\na.delegate = \"A delegate may be any object\"\nprintln(a.operation()) // prints \"default implementation\"\n\n// With a delegate that implements \"thing\":\nlet d = Delegate()\na.delegate = d\nprintln(a.operation()) // prints \"delegate implementation\"\n", "language": "Swift" }, { "code": "protocol Thingable : class {\n func thing() -> String\n}\n\nclass Delegator {\n weak var delegate: Thingable?\n func operation() -> String {\n if let d = self.delegate {\n return d.thing()\n } else {\n return \"default implementation\"\n }\n }\n}\n\nclass Delegate : Thingable {\n func thing() -> String { return \"delegate implementation\" }\n}\n\n// Without a delegate:\nlet a = Delegator()\nprintln(a.operation()) // prints \"default implementation\"\n\n// With a delegate:\nlet d = Delegate()\na.delegate = d\nprintln(a.operation()) // prints \"delegate implementation\"\n", "language": "Swift" }, { "code": "package require TclOO\n\noo::class create Delegate {\n method thing {} {\n return \"delegate impl.\"\n }\n export thing\n}\n\noo::class create Delegator {\n variable delegate\n constructor args {\n my delegate {*}$args\n }\n\n method delegate args {\n if {[llength $args] == 0} {\n if {[info exists delegate]} {\n return $delegate\n }\n } elseif {[llength $args] == 1} {\n set delegate [lindex $args 0]\n } else {\n return -code error \"wrong # args: should be \\\"[self] delegate ?target?\\\"\"\n }\n }\n\n method operation {} {\n try {\n set result [$delegate thing]\n } on error e {\n set result \"default implementation\"\n }\n return $result\n }\n}\n\n# to instantiate a named object, use: class create objname; objname aMethod\n# to have the class name the object: set obj [class new]; $obj aMethod\n\nDelegator create a\nset b [Delegator new \"not a delegate object\"]\nset c [Delegator new [Delegate new]]\n\nassert {[a operation] eq \"default implementation\"} ;# a \"named\" object, hence \"a ...\"\nassert {[$b operation] eq \"default implementation\"} ;# an \"anonymous\" object, hence \"$b ...\"\nassert {[$c operation] ne \"default implementation\"}\n\n# now, set a delegate for object a\na delegate [$c delegate]\nassert {[a operation] ne \"default implementation\"}\n\nputs \"all assertions passed\"\n", "language": "Tcl" }, { "code": "method operation {} {\n if { [info exists delegate] &&\n [info object isa object $delegate] &&\n \"thing\" in [info object methods $delegate -all]\n } then {\n set result [$delegate thing]\n } else {\n set result \"default implementation\"\n }\n}\n", "language": "Tcl" }, { "code": ";; TXR Lisp's :delegate implementation is hard delegation: the indicated\n;; delegate object must exist and take the method call. To do soft\n;; delegation, we develop a macro (delegate-or-fallback x y z)\n;; which chooses x if x is an object which supports a z method,\n;; or else chooses y.\n\n(defun delegate-or-fallback-impl (del-inst fb-inst required-meth)\n (let (del-type)\n (if (and (structp del-inst)\n (set del-type (struct-type del-inst))\n (static-slot-p del-type required-meth)\n (functionp (static-slot del-type required-meth)))\n del-inst\n fb-inst)))\n\n(defmacro delegate-or-fallback (delegate-expr fallback-obj : required-meth)\n ^(delegate-or-fallback-impl ,delegate-expr ,fallback-obj ',required-meth))\n\n;; With the above, we can use the defstruct delegate clause syntax:\n;;\n;; (:delegate source-method (obj) target-obj target-method)\n;;\n;; which writes a delegate method called source-method, that delegates\n;; to target-method on target-obj. We calculate target-obj using\n;; our macro and ensure that the delegator itself imlpements target-method.\n\n(defstruct delegator ()\n delegate\n (:delegate operation (me) (delegate-or-fallback me.delegate me thing) thing)\n\n (:method thing (me)\n \"default implementation\"))\n\n(defstruct delegate ()\n (:method thing (me)\n \"delegate implementation\"))\n\n;; Tests:\n\n;; no delegate\n(prinl (new delegator).(operation))\n\n;; struct delegate, but not with thing method\n(prinl (new delegator delegate (new time)).(operation))\n\n;; delegate with thing method\n(prinl (new delegator delegate (new delegate)).(operation))\n", "language": "TXR" }, { "code": "a = new()\na.f = method(){\n .x.print()\n}\n\nc = new()\nc.g = method(){\n (.x + 1).print()\n}\n\n# array of delegates\nb = new()\nb.delegate = new()\nb.delegate[0] = a\nb.delegate[1] = c\nb.x = 3\nb.f()\nb.g()\n\n# single delegate\nd = new()\nd.delegate = a\nd.x = 7\nd.f()\n", "language": "Vorpal" }, { "code": "class Thingable {\n thing { }\n}\n\n// Delegate that doesn't implement Thingable\nclass Delegate {\n construct new() { }\n}\n\n// Delegate that implements Thingable\nclass Delegate2 is Thingable {\n construct new() { }\n\n thing { \"delegate implementation\" }\n}\n\nclass Delegator {\n construct new() {\n _delegate = null\n }\n\n delegate { _delegate }\n delegate=(d) { _delegate = d }\n\n operation {\n if (!_delegate || !(_delegate is Thingable)) return \"default implementation\"\n return _delegate.thing\n }\n}\n\n// without a delegate\nvar d = Delegator.new()\nSystem.print(d.operation)\n\n// with a delegate that doesn't implement Thingable\nd.delegate = Delegate.new()\nSystem.print(d.operation)\n\n// with a delegate that does implement Thingable\nd.delegate = Delegate2.new()\nSystem.print(d.operation)\n", "language": "Wren" }, { "code": "class Thingable{ var thing; }\n\nclass Delegator{\n var delegate;\n fcn operation{\n if (delegate) delegate.thing;\n else \"default implementation\"\n }\n}\n\nclass Delegate(Thingable){ thing = \"delegate implementation\" }\n", "language": "Zkl" }, { "code": " // Without a delegate:\na:= Delegator();\na.operation().println(); //--> \"default implementation\"\n\n // With a delegate:\na.delegate = Delegate();\na.operation().println(); //-->\"delegate implementation\"\n", "language": "Zkl" }, { "code": "class [static] Logger{ // Only one logging resource\n var [mixin=File] dst; // File like semantics, eg Data, Pipe\n dst = File.DevNull;\n // initially, the logger does nothing\n fcn log(msg){dst.writeln(vm.pasteArgs())}\n}\n", "language": "Zkl" }, { "code": "Logger.log(\"this is a test\"); //-->nada\nLogger.dst=Console;\nLogger.log(\"this is a test 2\"); //-->writes to Console\n\nclass B(Logger){ log(\"Hello from \",self,\"'s constructor\"); }\nB(); //-->Hello from Class(B)'s constructor\n", "language": "Zkl" } ]
Delegates
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Delete_a_file\nnote: File System Operations\n", "language": "00-META" }, { "code": ";Task:\nDelete a file called \"input.txt\" and delete a directory called \"docs\". \n\nThis should be done twice: once \"here\", i.e. in the current working directory and once in the filesystem root.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "fs:remove_file(‘output.txt’)\nfs:remove_dir(‘docs’)\nfs:remove_file(‘/output.txt’)\nfs:remove_dir(‘/docs’)\n", "language": "11l" }, { "code": "\"input.txt\" f:rm drop\n\"/input.txt\" f:rm drop\n\"docs\" f:rmdir drop\n\"/docs\" f:rmdir drop\n", "language": "8th" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program deleteFic64.s */\n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n.equ UNLINK, 35\n\n.equ AT_REMOVEDIR, 0x200 // flag for delete directory\n\n/******************************************/\n/* Initialized data */\n/******************************************/\n.data\nszMessDeleteDirOk: .asciz \"Delete directory Ok.\\n\"\nszMessErrDeleteDir: .asciz \"Unable delete dir. \\n\"\nszMessDeleteFileOk: .asciz \"Delete file Ok.\\n\"\nszMessErrDeleteFile: .asciz \"Unable delete file. \\n\"\n\nszNameDir: .asciz \"Docs\"\nszNameFile: .asciz \"input.txt\"\n\n/******************************************/\n/* UnInitialized data */\n/******************************************/\n.bss\n/******************************************/\n/* code section */\n/******************************************/\n.text\n.global main\nmain: // entry of program\n // delete file\n mov x0,AT_FDCWD // current directory\n ldr x1,qAdrszNameFile // file name\n mov x8,UNLINK // code call system delete file\n svc 0 // call systeme\n cmp x0,0 // error ?\n blt 99f\n ldr x0,qAdrszMessDeleteFileOk // delete file OK\n bl affichageMess\n // delete directory\n mov x0,AT_FDCWD // current directory\n ldr x1,qAdrszNameDir // directory name\n mov x2,AT_REMOVEDIR\n mov x8,UNLINK // code call system delete directory\n svc 0 // call systeme\n cmp x0,0 // error ?\n blt 98f\n ldr x0,qAdrszMessDeleteDirOk // display message ok directory\n bl affichageMess\n // end Ok\n b 100f\n\n98: // display error message delete directory\n ldr x0,qAdrszMessErrDeleteDir\n bl affichageMess\n b 100f\n99: // display error message delete file\n ldr x0,qAdrszMessErrDeleteFile\n bl affichageMess\n b 100f\n100: // standard end of the program\n mov x0,0 // return code\n mov x8,EXIT // request to exit program\n svc 0 // perform the system call\nqAdrszMessDeleteDirOk: .quad szMessDeleteDirOk\nqAdrszMessErrDeleteDir: .quad szMessErrDeleteDir\nqAdrszMessDeleteFileOk: .quad szMessDeleteFileOk\nqAdrszNameFile: .quad szNameFile\nqAdrszMessErrDeleteFile: .quad szMessErrDeleteFile\nqAdrszNameDir: .quad szNameDir\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "PROC Dir(CHAR ARRAY filter)\n CHAR ARRAY line(255)\n BYTE dev=[1]\n\n Close(dev)\n Open(dev,filter,6)\n DO\n InputSD(dev,line)\n PrintE(line)\n IF line(0)=0 THEN\n EXIT\n FI\n OD\n Close(dev)\nRETURN\n\nPROC DeleteFile(CHAR ARRAY fname)\n BYTE dev=[1]\n\n Close(dev)\n Xio(dev,0,33,0,0,fname)\nRETURN\n\nPROC Main()\n CHAR ARRAY filter=\"D:*.*\", fname=\"D:INPUT.TXT\"\n\n PrintF(\"Dir \"\"%S\"\"%E\",filter)\n Dir(filter)\n\n PrintF(\"Delete file \"\"%S\"\"%E%E\",fname)\n DeleteFile(fname)\n\n PrintF(\"Dir \"\"%S\"\"%E\",filter)\n Dir(filter)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Directories; use Ada.Directories;\n", "language": "Ada" }, { "code": "Delete_File (\"input.txt\");\nDelete_File (\"/input.txt\");\nDelete_Tree (\"docs\");\nDelete_Tree (\"/docs\");\n", "language": "Ada" }, { "code": "remove (\"input.txt\")\nremove (\"/input.txt\")\nremove (\"docs\")\nremove (\"/docs\")\n", "language": "Aikido" }, { "code": "remove(\"input.txt\");\nremove(\"/input.txt\");\nremove(\"docs\");\nremove(\"/docs\");\n", "language": "Aime" }, { "code": "main:(\n PROC remove = (STRING file name)INT:\n BEGIN\n FILE actual file;\n INT errno = open(actual file, file name, stand back channel);\n IF errno NE 0 THEN stop remove FI;\n scratch(actual file); # detach the book and burn it #\n errno\n EXIT\n stop remove:\n errno\n END;\n remove(\"input.txt\");\n remove(\"/input.txt\");\n remove(\"docs\");\n remove(\"/docs\")\n)\n", "language": "ALGOL-68" }, { "code": " 0 PRINT CHR$ (4)\"DELETE INPUT.TXT\"\n", "language": "Applesoft-BASIC" }, { "code": "/* ARM assembly Raspberry PI */\n/* program deleteFic.s */\n\n/* REMARK 1 : this program use routines in a include file\n see task Include a file language arm assembly\n for the routine affichageMess conversion10\n see at end of this program the instruction include */\n/***************************************************************/\n/* File Constantes see task Include a file for arm assembly */\n/***************************************************************/\n.include \"../constantes.inc\"\n\n.equ RMDIR, 0x28\n.equ UNLINK, 0xA\n/******************************************/\n/* Initialized data */\n/******************************************/\n.data\nszMessDeleteDirOk: .asciz \"Delete directory Ok.\\n\"\nszMessErrDeleteDir: .asciz \"Unable delete dir. \\n\"\nszMessDeleteFileOk: .asciz \"Delete file Ok.\\n\"\nszMessErrDeleteFile: .asciz \"Unable delete file. \\n\"\n\nszNameDir: .asciz \"Docs\"\nszNameFile: .asciz \"input.txt\"\n\n/******************************************/\n/* UnInitialized data */\n/******************************************/\n.bss\n/******************************************/\n/* code section */\n/******************************************/\n.text\n.global main\nmain: @ entry of program\n @ delete file\n ldr r0,iAdrszNameFile @ file name\n\n mov r7,#UNLINK @ code call system delete file\n svc #0 @ call systeme\n cmp r0,#0 @ error ?\n blt 99f\n ldr r0,iAdrszMessDeleteFileOk @ delete file OK\n bl affichageMess\n @ delete directory\n ldr r0,iAdrszNameDir @ directory name\n mov r7, #RMDIR @ code call system delete directory\n swi #0 @ call systeme\n cmp r0,#0 @ error ?\n blt 98f\n ldr r0,iAdrszMessDeleteDirOk @ display message ok directory\n bl affichageMess\n @ end Ok\n b 100f\n\n98: @ display error message delete directory\n ldr r0,iAdrszMessErrDeleteDir\n bl affichageMess\n b 100f\n99: @ display error message delete file\n ldr r0,iAdrszMessErrDeleteFile\n bl affichageMess\n b 100f\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\niAdrszMessDeleteDirOk: .int szMessDeleteDirOk\niAdrszMessErrDeleteDir: .int szMessErrDeleteDir\niAdrszMessDeleteFileOk: .int szMessDeleteFileOk\niAdrszNameFile: .int szNameFile\niAdrszMessErrDeleteFile: .int szMessErrDeleteFile\niAdrszNameDir: .int szNameDir\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n.include \"../affichage.inc\"\n", "language": "ARM-Assembly" }, { "code": "file: \"input.txt\"\ndocs: \"docs\"\n\ndelete file\ndelete.directory file\n\ndelete join.path [\"/\" file]\ndelete.directory join.path [\"/\" docs]\n", "language": "Arturo" }, { "code": "FileDelete, input.txt\nFileDelete, \\input.txt\nFileRemoveDir, docs, 1\nFileRemoveDir, \\docs, 1\n", "language": "AutoHotkey" }, { "code": "DeleteFile(lpFileName)\n{\n DllCall(\"Kernel32.dll\\DeleteFile\", \"Str\", lpFileName)\n}\n\nDeleteFile(\"C:\\Temp\\TestFile.txt\")\n", "language": "AutoHotkey" }, { "code": "system(\"rm input.txt\")\nsystem(\"rm /input.txt\")\nsystem(\"rm -rf docs\")\nsystem(\"rm -rf /docs\")\n", "language": "AWK" }, { "code": "DelVar \"appvINPUT\"\n", "language": "Axe" }, { "code": "DELETE FILE \"input.txt\"\nDELETE FILE \"/input.txt\"\n", "language": "BaCon" }, { "code": "KILL \"INPUT.TXT\"\nKILL \"C:\\INPUT.TXT\"\nSHELL \"RMDIR /S /Q DIR\"\nSHELL \"RMDIR /S /Q C:\\DIR\"\n", "language": "BASIC" }, { "code": "del input.txt\nrd /s /q docs\n\ndel \\input.txt\nrd /s /q \\docs\n", "language": "Batch-File" }, { "code": " *DELETE input.txt\n *DELETE \\input.txt\n *RMDIR docs\n *RMDIR \\docs\n", "language": "BBC-BASIC" }, { "code": " OSCLI \"DELETE \" + file$\n OSCLI \"RMDIR \" + dir$\n", "language": "BBC-BASIC" }, { "code": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n class Program {\n static void Main() {\n File.Delete(\"input.txt\");\n Directory.Delete(\"docs\");\n File.Delete(\"/input.txt\");\n Directory.Delete(\"/docs\");\n }\n }\n}\n", "language": "Beef" }, { "code": "•file.Remove \"input.txt\"\n•file.Remove \"/input.txt\"\n•file.RemoveDir \"docs\"\n•file.RemoveDir \"/docs\"\n", "language": "BQN" }, { "code": "#include <stdio.h>\n\nint main() {\n remove(\"input.txt\");\n remove(\"/input.txt\");\n remove(\"docs\");\n remove(\"/docs\");\n return 0;\n}\n", "language": "C" }, { "code": "#include <unistd.h>\n\nint main() {\n unlink(\"input.txt\");\n unlink(\"/input.txt\");\n rmdir(\"docs\");\n rmdir(\"/docs\");\n return 0;\n}\n", "language": "C" }, { "code": "#include <cstdio>\n#include <direct.h>\n\nint main() {\n\tremove( \"input.txt\" );\n\tremove( \"/input.txt\" );\n\t_rmdir( \"docs\" );\n\t_rmdir( \"/docs\" );\n\n\treturn 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.IO;\n\nnamespace RosettaCode {\n class Program {\n static void Main() {\n try {\n File.Delete(\"input.txt\");\n Directory.Delete(\"docs\");\n File.Delete(@\"\\input.txt\");\n Directory.Delete(@\"\\docs\");\n } catch (Exception exception) {\n Console.WriteLine(exception.Message);\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(import '(java.io File))\n(.delete (File. \"output.txt\"))\n(.delete (File. \"docs\"))\n\n(.delete (new File (str (File/separator) \"output.txt\")))\n(.delete (new File (str (File/separator) \"docs\")))\n", "language": "Clojure" }, { "code": " IDENTIFICATION DIVISION.\n PROGRAM-ID. Delete-Files.\n\n ENVIRONMENT DIVISION.\n INPUT-OUTPUT SECTION.\n FILE-CONTROL.\n SELECT Local-File ASSIGN TO \"input.txt\".\n SELECT Root-File ASSIGN TO \"/input.txt\".\n\n DATA DIVISION.\n FILE SECTION.\n FD Local-File.\n 01 Local-Record PIC X.\n FD Root-File.\n 01 Root-Record PIC X.\n\n PROCEDURE DIVISION.\n DELETE FILE Local-File\n DELETE FILE Root-File\n GOBACK.\n\n END PROGRAM Delete-Files.\n", "language": "COBOL" }, { "code": " IDENTIFICATION DIVISION.\n PROGRAM-ID. Delete-Files.\n\n PROCEDURE DIVISION.\n CALL \"CBL_DELETE_FILE\" USING \"input.txt\"\n CALL \"CBL_DELETE_DIR\" USING \"docs\"\n CALL \"CBL_DELETE_FILE\" USING \"/input.txt\"\n CALL \"CBL_DELETE_DIR\" USING \"/docs\"\n\n GOBACK.\n\n END PROGRAM Delete-Files.\n", "language": "COBOL" }, { "code": "(delete-file (make-pathname :name \"input.txt\"))\n(delete-file (make-pathname :directory '(:absolute \"\") :name \"input.txt\"))\n", "language": "Common-Lisp" }, { "code": "(let ((path (make-pathname :directory '(:relative \"docs\"))))\n (ext:delete-dir path))\n\n(let ((path (make-pathname :directory '(:absolute \"docs\"))))\n (ext:delete-dir path))\n", "language": "Common-Lisp" }, { "code": "(let ((path (make-pathname :directory '(:relative \"docs\"))))\n (cl-fad:delete-directory-and-files path))\n", "language": "Common-Lisp" }, { "code": "VAR\n l: Files.Locator;\nBEGIN\n (* Locator is the directory *)\n l := Files.dir.This(\"proof\");\n (* delete 'xx.txt' file, in directory 'proof' *)\n Files.dir.Delete(l,\"xx.txt\");\nEND ...\n", "language": "Component-Pascal" }, { "code": "import std.file: remove;\n\nvoid main() {\n remove(\"data.txt\");\n}\n", "language": "D" }, { "code": "import tango.io.Path;\n\nvoid main() {\n remove(\"input.txt\");\n remove(\"/input.txt\");\n remove(\"docs\");\n remove(\"/docs\");\n}\n", "language": "D" }, { "code": "import tango.stdc.posix.unistd;\n\nvoid main() {\n unlink(\"input.txt\");\n unlink(\"/input.txt\");\n rmdir(\"docs\");\n rmdir(\"/docs\");\n}\n", "language": "D" }, { "code": "procedure TMain.btnDeleteClick(Sender: TObject);\nvar\n CurrentDirectory : String;\nbegin\n CurrentDirectory := GetCurrentDir;\n\n DeleteFile(CurrentDirectory + '\\input.txt');\n RmDir(PChar(CurrentDirectory + '\\docs'));\n\n DeleteFile('c:\\input.txt');\n RmDir(PChar('c:\\docs'));\nend;\n", "language": "Delphi" }, { "code": "<file:input.txt>.delete(null)\n<file:docs>.delete(null)\n<file:///input.txt>.delete(null)\n<file:///docs>.delete(null)\n", "language": "E" }, { "code": "import system'io;\n\npublic program()\n{\n File.assign(\"output.txt\").delete();\n\n File.assign(\"\\output.txt\").delete();\n\n Directory.assign(\"docs\").delete();\n\n Directory.assign(\"\\docs\").delete();\n}\n", "language": "Elena" }, { "code": "File.rm!(\"input.txt\")\nFile.rmdir!(\"docs\")\nFile.rm!(\"/input.txt\")\nFile.rmdir!(\"/docs\")\n", "language": "Elixir" }, { "code": "(delete-file \"input.txt\")\n(delete-directory \"docs\")\n(delete-file \"/input.txt\")\n(delete-directory \"/docs\")\n", "language": "Emacs-Lisp" }, { "code": "-module(delete).\n-export([main/0]).\n\nmain() ->\n\t% current directory\n ok = file:del_dir( \"docs\" ),\n\tok = file:delete( \"input.txt\" ),\n\t% root directory\n\tok = file:del_dir( \"/docs\" ),\n\tok = file:delete( \"/input.txt\" ).\n", "language": "Erlang" }, { "code": "open System.IO\n\n[<EntryPoint>]\nlet main argv =\n let fileName = \"input.txt\"\n let dirName = \"docs\"\n for path in [\".\"; \"/\"] do\n ignore (File.Delete(Path.Combine(path, fileName)))\n ignore (Directory.Delete(Path.Combine(path, dirName)))\n 0\n", "language": "F-Sharp" }, { "code": "\"docs\" \"/docs\" [ delete-tree ] bi@\n\"input.txt\" \"/input.txt\" [ delete-file ] bi@\n", "language": "Factor" }, { "code": " s\" input.txt\" delete-file throw\ns\" /input.txt\" delete-file throw\n", "language": "Forth" }, { "code": " OPEN (UNIT=5, FILE=\"input.txt\", STATUS=\"OLD\") ! Current directory\n CLOSE (UNIT=5, STATUS=\"DELETE\")\n OPEN (UNIT=5, FILE=\"/input.txt\", STATUS=\"OLD\") ! Root directory\n CLOSE (UNIT=5, STATUS=\"DELETE\")\n", "language": "Fortran" }, { "code": "program DeleteFileExample\n use kernel32\n implicit none\n print *, DeleteFile(\"input.txt\")\n print *, DeleteFile(\"\\input.txt\")\n print *, RemoveDirectory(\"docs\")\n print *, RemoveDirectory(\"\\docs\")\nend program\n", "language": "Fortran" }, { "code": "program deletion(input, output, stdErr);\nconst\n\trootDirectory = '/'; // might have to be altered for other platforms\n\tinputTextFilename = 'input.txt';\n\tdocsFilename = 'docs';\nvar\n\tfd: file;\nbegin\n\tassign(fd, inputTextFilename);\n\terase(fd);\n\t\n\trmDir(docsFilename);\n\t\n\tassign(fd, rootDirectory + inputTextFilename);\n\terase(fd);\n\t\n\trmDir(rootDirectory + docsFilename);\nend.\n", "language": "Free-Pascal-Lazarus" }, { "code": "' FB 1.05.0 Win64\n\n' delete file and empty sub-directory in current directory\n\nKill \"input.txt\"\nRmDir \"docs\"\n\n' delete file and empty sub-directory in root directory c:\\\n' deleting file in root requires administrative privileges in Windows 10\n\n'Kill \"c:\\input.txt\"\n'RmDir \"c:\\docs\"\n\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "###sysinclude dir.uh\n// ===================\nargc 3 < { #s .\"Usage: \" 0 argv print SPACE 1 argv print .\" filename\\n\" end }\n2 argv 'e !istrue { #s .\"The given file ( \" 2 argv print .\" ) doesn't exist!\\n\" end }\n2 argv removefile\nend\n", "language": "Furor" }, { "code": "###sysinclude dir.uh\n#g argc 3 < { .\"Usage: \" #s 0 argv print SPACE 1 argv print SPACE .\"unnecessary_directory\\n\" end }\n2 argv 'd !istrue { .\"The given directory doesn't exist! Exited.\\n\" }{\n2 argv rmdir\n}\nend\n", "language": "Furor" }, { "code": "include \"NSLog.incl\"\n\nCFURLRef url\n\nurl = fn URLFileURLWithPath( fn StringByExpandingTildeInPath( @\"~/Desktop/input.txt\" ) )\nif (fn FileManagerRemoveItemAtURL( url ) )\n NSLog( @\"File \\\"intput.txt\\\" deleted.\" )\nelse\n NSLog( @\"Unable to delete file \\\"input.txt\\\".\" )\nend if\n\nurl = fn URLFileURLWithPath( fn StringByExpandingTildeInPath( @\"~/Desktop/docs\" ) )\nif (fn FileManagerRemoveItemAtURL( url ) )\n NSLog( @\"Directory \\\"docs\\\" deleted.\" )\nelse\n NSLog( @\"Unabled to delete directory \\\"docs\\\".\" )\nend if\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\n\nKill User.home &/ \"input.txt\"\nRmdir User.home &/ \"docs\"\n\n'Administrative privileges (sudo) would be required to mess about in Root - I'm not going there!\n\nEnd\n", "language": "Gambas" }, { "code": "# Apparently GAP can only remove a file, not a directory\nRemoveFile(\"input.txt\");\n# true\nRemoveFile(\"docs\");\n# fail\n", "language": "GAP" }, { "code": "package main\nimport \"os\"\n\nfunc main() {\n os.Remove(\"input.txt\")\n os.Remove(\"/input.txt\")\n os.Remove(\"docs\")\n os.Remove(\"/docs\")\n // recursively removes contents:\n os.RemoveAll(\"docs\")\n os.RemoveAll(\"/docs\")\n}\n", "language": "Go" }, { "code": "// Gets the first filesystem root. On most systems this will be / or c:\\\ndef fsRoot = File.listRoots().first()\n\n// Create our list of files (including directories)\ndef files = [\n new File(\"input.txt\"),\n new File(fsRoot, \"input.txt\"),\n new File(\"docs\"),\n new File(fsRoot, \"docs\")\n]\n\n/*\nWe use it.directory to determine whether each file is a regular file or directory. If it is a directory, we delete\nit with deleteDir(), otherwise we just use delete().\n */\nfiles.each{\n it.directory ? it.deleteDir() : it.delete()\n}\n", "language": "Groovy" }, { "code": "import System.IO\nimport System.Directory\n\nmain = do\n removeFile \"output.txt\"\n removeDirectory \"docs\"\n removeFile \"/output.txt\"\n removeDirectory \"/docs\"\n", "language": "Haskell" }, { "code": "SYSTEM(DIR=\"docs\") ! create docs in current directory (if not existent), make it current\nOPEN (FILE=\"input.txt\", \"NEW\") ! in current directory = docs\nWRITE(FIle=\"input.txt\", DELETE=1) ! no command to DELETE a DIRECTORY in HicEst\n\nSYSTEM(DIR=\"C:\\docs\") ! create C:\\docs (if not existent), make it current\nOPEN (FILE=\"input.txt\", \"NEW\") ! in current directory = C:\\docs\nWRITE(FIle=\"input.txt\", DELETE=1)\n", "language": "HicEst" }, { "code": "every dir := ![\"./\",\"/\"] do {\n remove(f := dir || \"input.txt\") |stop(\"failure for file remove \",f)\n rmdir(f := dir || \"docs\") |stop(\"failure for directory remove \",f)\n }\n", "language": "Icon" }, { "code": "Directory fileNamed(\"input.txt\") remove\nDirectory directoryNamed(\"docs\") remove\nRootDir := Directory clone setPath(\"/\")\nRootDir fileNamed(\"input.txt\") remove\nRootDir directoryNamed(\"docs\") remove\n", "language": "Io" }, { "code": "File with(\"input.txt\") remove\nDirectory with(\"docs\") remove\nFile with(\"/input.txt\") remove\nDirectory with(\"/docs\") remove\n", "language": "Io" }, { "code": "100 WHEN EXCEPTION USE IOERROR\n110 EXT \"del input.txt\"\n120 EXT \"del \\input.txt\"\n130 EXT \"rmdir docs\"\n140 EXT \"rmdir \\docs\"\n150 END WHEN\n160 HANDLER IOERROR\n170 PRINT \"Error in line\";EXLINE\n180 PRINT \"*** \";EXSTRING$(EXTYPE)\n190 CONTINUE\n200 END HANDLER\n", "language": "IS-BASIC" }, { "code": " load 'files'\n ferase 'input.txt'\n ferase '\\input.txt'\n ferase 'docs'\n ferase '\\docs'\n\nNB. Or all at once...\n ferase 'input.txt';'/input.txt';'docs';'/docs'\n", "language": "J" }, { "code": "NB. =========================================================\nNB.*ferase v erases a file\nNB. Returns 1 if successful, otherwise _1\nferase=: (1!:55 :: _1:) @ (fboxname &>) @ boxopen\n", "language": "J" }, { "code": "1!:55 <'input.txt'\n1!:55 <'\\input.txt'\n1!:55 <'docs'\n1!:55 <'\\docs'\n", "language": "J" }, { "code": "import java.io.File;\n\npublic class FileDeleteTest {\n public static boolean deleteFile(String filename) {\n boolean exists = new File(filename).delete();\n return exists;\n }\n\n public static void test(String type, String filename) {\n System.out.println(\"The following \" + type + \" called \" + filename +\n (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n );\n }\n\n public static void main(String args[]) {\n test(\"file\", \"input.txt\");\n test(\"file\", File.seperator + \"input.txt\");\n test(\"directory\", \"docs\");\n test(\"directory\", File.seperator + \"docs\" + File.seperator);\n }\n}\n", "language": "Java" }, { "code": "var fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\nfso.DeleteFile('input.txt');\nfso.DeleteFile('c:/input.txt');\n\nfso.DeleteFolder('docs');\nfso.DeleteFolder('c:/docs');\n", "language": "JavaScript" }, { "code": "var fso = new ActiveXObject(\"Scripting.FileSystemObject\");\nvar f;\nf = fso.GetFile('input.txt');\nf.Delete();\nf = fso.GetFile('c:/input.txt');\nf.Delete();\nf = fso.GetFolder('docs');\nf.Delete();\nf = fso.GetFolder('c:/docs');\nf.Delete();\n", "language": "JavaScript" }, { "code": "const fs = require('fs');\nfs.unlinkSync('myfile.txt');\n", "language": "JavaScript" }, { "code": "const fs = require('fs');\nfs.unlink('myfile.txt', ()=>{\n console.log(\"Done!\");\n})\n", "language": "JavaScript" }, { "code": "\"input.txt\" fremove\n\"docs\" fremove\n\"/input.txt\" fremove\n\"/docs\" fremove.\n", "language": "Joy" }, { "code": "# Delete a file\nrm(\"input.txt\")\n\n# Delete a directory\nrm(\"docs\", recursive = true)\n", "language": "Julia" }, { "code": "// version 1.0.6\n\n/* testing on Windows 10 which needs administrative privileges\n to delete files from the root */\n\nimport java.io.File\n\nfun main(args: Array<String>) {\n val paths = arrayOf(\"input.txt\", \"docs\", \"c:\\\\input.txt\", \"c:\\\\docs\")\n var f: File\n for (path in paths) {\n f = File(path)\n if (f.delete())\n println(\"$path successfully deleted\")\n else\n println(\"$path could not be deleted\")\n }\n}\n", "language": "Kotlin" }, { "code": "# Load the IO module\n# Replace \"<pathToIO.lm>\" with the location where the io.lm Lang module was installed to without \"<\" and \">\"\nln.loadModule(<pathToIO.lm>)\n\n$file1 = [[io]]::fp.openFile(input.txt)\n[[io]]::fp.delete($file1)\n[[io]]::fp.closeFile($file1)\n\n$file2 = [[io]]::fp.openFile(/input.txt)\n[[io]]::fp.delete($file2)\n[[io]]::fp.closeFile($file2)\n\n$dir1 = [[io]]::fp.openFile(docs)\n[[io]]::fp.delete($dir1)\n[[io]]::fp.closeFile($dir1)\n\n$dir2 = [[io]]::fp.openFile(/docs)\n[[io]]::fp.delete($dir2)\n[[io]]::fp.closeFile($dir2)\n", "language": "Lang" }, { "code": "// delete file\nlocal(f = file('input.txt'))\n#f->delete\n\n// delete directory\n// directory must be empty before it can be successfully deleted. A failure is generated if the operation fails.\nlocal(d = dir('docs'))\n#d->delete\n\n// delete file in root file system (requires permissions at user OS level)\nlocal(f = file('//input.txt'))\n#f->delete\n\n// delete directory in root file system (requires permissions at user OS level)\n// directory must be empty before it can be successfully deleted. A failure is generated if the operation fails.\nlocal(d = file('//docs'))\n#d->delete\n", "language": "Lasso" }, { "code": "' show where we are\nprint DefaultDir$\n\n' in here\nkill \"input.txt\"\nresult=rmdir(\"Docs\")\n\n' from root\nkill \"\\input.txt\"\nresult=rmdir(\"\\Docs\")\n", "language": "Liberty-BASIC" }, { "code": "-- note: fileIO xtra is shipped with Director, i.e. an \"internal\"\nfp = xtra(\"fileIO\").new()\nfp.openFile(\"input.txt\", 0)\nfp.delete()\n", "language": "Lingo" }, { "code": "-- note: fileIO xtra is shipped with Director, i.e. an \"internal\"\npd = the last char of _movie.path -- \"\\\" for win, \":\" for mac\n_player.itemDelimiter = pd\nvol = _movie.path.item[1]\nfp = xtra(\"fileIO\").new()\nfp.openFile(vol&pd&\"input.txt\", 0)\nfp.delete()\n", "language": "Lingo" }, { "code": "-- delete (empty) directory \"docs\" in cwd\nbx_folder_delete(\"docs\")\n\n-- delete (empty) directory \"docs\" in root of current volume\npd = the last char of _movie.path -- \"\\\" for win, \":\" for mac\n_player.itemDelimiter = pd\nvol = _movie.path.item[1]\nbx_folder_delete(vol&pd&\"docs\")\n", "language": "Lingo" }, { "code": "|era,\"input.txt\"\n", "language": "Locomotive-Basic" }, { "code": "erasefile \"input.txt\nerasefile \"/input.txt\n", "language": "Logo" }, { "code": "os.remove(\"input.txt\")\nos.remove(\"/input.txt\")\nos.remove(\"docs\")\nos.remove(\"/docs\")\n", "language": "Lua" }, { "code": "FileTools:-Remove(\"input.txt\");\nFileTools:-RemoveDirectory(\"docs\");\nFileTools:-Remove(\"/input.txt\");\nFileTools:-RemoveDirectory(\"/docs\");\n", "language": "Maple" }, { "code": "wd = NotebookDirectory[];\nDeleteFile[wd <> \"input.txt\"]\nDeleteFile[\"/\" <> \"input.txt\"]\nDeleteDirectory[wd <> \"docs\"]\nDeleteDirectory[\"/\" <> \"docs\"]\n", "language": "Mathematica" }, { "code": " delete('input.txt'); % delete local file input.txt\n delete('/input.txt'); % delete file /input.txt\n rmdir('docs'); % remove local directory docs\n rmdir('/docs'); % remove directory /docs\n", "language": "MATLAB" }, { "code": "if system('rm input.txt') == 0\n disp('input.txt removed')\nend\nif system('rm /input.txt') == 0\n disp('/input.txt removed')\nend\nif system('rmdir docs') == 0\n disp('docs removed')\nend\nif system('rmdir /docs') == 0\n disp('/docs removed')\nend\n", "language": "MATLAB" }, { "code": "-- Here\ndeleteFile \"input.txt\"\n-- Root\ndeleteFile \"\\input.txt\"\n", "language": "MAXScript" }, { "code": ":- module delete_file.\n:- interface.\n\n:- import_module io.\n\n:- pred main(io::di, io::uo) is det.\n\n:- implementation.\n\nmain(!IO) :-\n io.remove_file(\"input.txt\", _, !IO),\n io.remove_file(\"/input.txt\", _, !IO),\n io.remove_file(\"docs\", _, !IO),\n io.remove_file(\"/docs\", _, !IO).\n", "language": "Mercury" }, { "code": "f = new(Nanoquery.IO.File)\nf.delete(\"input.txt\")\nf.delete(\"docs\")\nf.delete(\"/input.txt\")\nf.delete(\"/docs\")\n", "language": "Nanoquery" }, { "code": "using System;\nusing System.IO;\nusing System.Console;\n\nmodule DeleteFile\n{\n Main() : void\n {\n when (File.Exists(\"input.txt\")) File.Delete(\"input.txt\");\n try {\n when (File.Exists(@\"\\input.txt\")) File.Delete(@\"\\input.txt\");\n }\n catch {\n |e is UnauthorizedAccessException => WriteLine(e.Message)\n }\n\n when (Directory.Exists(\"docs\")) Directory.Delete(\"docs\");\n when (Directory.Exists(@\"\\docs\")) Directory.Delete(@\"\\docs\");\n }\n}\n", "language": "Nemerle" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols binary\n\nrunSample(arg)\nreturn\n\n-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\nmethod isFileDeleted(fn) public static returns boolean\n ff = File(fn)\n fDeleted = ff.delete()\n return fDeleted\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod runSample(arg) private static\n parse arg files\n if files = '' then files = 'input.txt F docs D /input.txt F /docs D'\n loop while files.length > 0\n parse files fn ft files\n select case(ft.upper())\n when 'F' then do\n ft = 'File'\n end\n when 'D' then do\n ft = 'Directory'\n end\n otherwise do\n ft = 'File'\n end\n end\n if isFileDeleted(fn) then dl = 'deleted'\n else dl = 'not deleted'\n say ft ''''fn'''' dl\n end\n\n return\n", "language": "NetRexx" }, { "code": "(delete-file \"input.txt\")\n(delete-file \"/input.txt\")\n(remove-dir \"docs\")\n(remove-dir \"/docs\")\n", "language": "NewLISP" }, { "code": "import os\nremoveFile(\"input.txt\")\nremoveFile(\"/input.txt\")\nremoveDir(\"docs\")\nremoveDir(\"/docs\")\n", "language": "Nim" }, { "code": "use IO;\n\nbundle Default {\n class FileExample {\n function : Main(args : String[]) ~ Nil {\n File->Delete(\"output.txt\");\n File->Delete(\"/output.txt\");\n\n Directory->Delete(\"docs\");\n Directory->Delete(\"/docs\");\n }\n }\n}\n", "language": "Objeck" }, { "code": "NSFileManager *fm = [NSFileManager defaultManager];\n\n// Pre-OS X 10.5\n[fm removeFileAtPath:@\"input.txt\" handler:nil];\n[fm removeFileAtPath:@\"/input.txt\" handler:nil];\n[fm removeFileAtPath:@\"docs\" handler:nil];\n[fm removeFileAtPath:@\"/docs\" handler:nil];\n\n// OS X 10.5+\n[fm removeItemAtPath:@\"input.txt\" error:NULL];\n[fm removeItemAtPath:@\"/input.txt\" error:NULL];\n[fm removeItemAtPath:@\"docs\" error:NULL];\n[fm removeItemAtPath:@\"/docs\" error:NULL];\n", "language": "Objective-C" }, { "code": "Sys.remove \"input.txt\";;\nSys.remove \"/input.txt\";;\nSys.rmdir \"docs\";;\nSys.rmdir \"/docs\";;\n", "language": "OCaml" }, { "code": "#load \"unix.cma\";;\nUnix.unlink \"input.txt\";;\nUnix.unlink \"/input.txt\";;\nUnix.rmdir \"docs\";;\nUnix.rmdir \"/docs\";;\n", "language": "OCaml" }, { "code": "/*REXX pgm deletes a file */\nfile= 'afile.txt' /*name of a file to be deleted.*/\nres=sysFileDelete(file); Say file 'res='res\nFile= 'bfile.txt' /*name of a file to be deleted.*/\nres=sysFileDelete(file); Say file 'res='res\n", "language": "OoRexx" }, { "code": "for Dir in [\"/\" \"./\"] do\n try {OS.unlink Dir#\"output.txt\"}\n catch _ then {System.showInfo \"File does not exist.\"} end\n try {OS.rmDir Dir#\"docs\"}\n catch _ then {System.showInfo \"Directory does not exist.\"} end\nend\n", "language": "Oz" }, { "code": "system(\"rm -rf docs\");\nsystem(\"rm input.txt\");\nsystem(\"rm -rf /docs\");\nsystem(\"rm /input.txt\");\n", "language": "PARI-GP" }, { "code": "###sysinclude standard.uh\n###sysinclude args.uh\n###sysinclude str.uh\n###sysinclude io.uh\n// ===================\n#g argc 3 < { #s .\"Usage: \" 0 argv print SPACE 1 argv print .\" filename\\n\" end }\n2 argv 'e inv istrue { #s .\"The given file ( \" 2 argv print .\" ) doesn't exist!\\n\" end }\n2 argv removefile\nend\n", "language": "Peri" }, { "code": "###sysinclude standard.uh\n###sysinclude args.uh\n###sysinclude str.uh\n###sysinclude io.uh\n#g argc 3 < { .\"Usage: \" #s 0 argv print SPACE 1 argv print SPACE .\"unnecessary_directory\\n\" end }\n2 argv 'd inv istrue { .\"The given directory doesn't exist! Exited.\\n\" }{\n2 argv rmdir\n}\nend\n", "language": "Peri" }, { "code": "use File::Spec::Functions qw(catfile rootdir);\n# here\nunlink 'input.txt';\nrmdir 'docs';\n# root dir\nunlink catfile rootdir, 'input.txt';\nrmdir catfile rootdir, 'docs';\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span> <span style=\"color: #000080;font-style:italic;\">-- (file i/o)</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">root</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">LINUX</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"/\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"C:\\\\\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">delete_file</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"input.txt\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">delete_file</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #008000;\">\"input.txt\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">remove_directory</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"docs\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">remove_directory</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #008000;\">\"docs\"</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n", "language": "PHP" }, { "code": "import os.\n\ndel(Arg), directory(Arg) =>\n rmdir(Arg).\n\ndel(Arg), file(Arg) =>\n rm(Arg).\n\nmain(Args) =>\n foreach (Arg in Args)\n del(Arg)\n end.\n", "language": "Picat" }, { "code": "(call 'rm \"input.txt\")\n(call 'rmdir \"docs\")\n(call 'rm \"/input.txt\")\n(call 'rmdir \"/docs\")\n", "language": "PicoLisp" }, { "code": "int main(){\n rm(\"input.txt\");\n rm(\"/input.txt\");\n rm(\"docs\");\n rm(\"/docs\");\n}\n", "language": "Pike" }, { "code": "To run:\nStart up.\n\\ In the current working directory\nDestroy \".\\input.txt\" in the file system.\nDestroy \".\\docs\\\" in the file system.\n\\ In the filesystem root\nDestroy \"C:\\input.txt\" in the file system.\nDestroy \"C:\\docs\\\" in the file system.\nShut down.\n", "language": "Plain-English" }, { "code": "# possible aliases for Remove-Item: rm, del, ri\nRemove-Item input.txt\nRemove-Item \\input.txt # file system root\n\nRemove-Item -Recurse docs # recurse for deleting folders including content\nRemove-Item -Recurse \\docs\n", "language": "PowerShell" }, { "code": "deletedirectory docs\n", "language": "ProDOS" }, { "code": "DeleteFile(\"input.txt\")\nDeleteDirectory(\"docs\",\"\") ; needs to delete all included files\nDeleteFile(\"/input.txt\")\nDeleteDirectory(\"/docs\",\"*.*\") ; deletes all files according to a pattern\n\nDeleteDirectory(\"/docs\",\"\",#PB_FileSystem_Recursive) ; deletes all files and directories recursive\n", "language": "PureBasic" }, { "code": "import os\n# current directory\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n# root directory\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n", "language": "Python" }, { "code": "import shutil\nshutil.rmtree(\"docs\")\n", "language": "Python" }, { "code": "file.remove(\"input.txt\")\nfile.remove(\"/input.txt\")\n\n# or\nfile.remove(\"input.txt\", \"/input.txt\")\n\n# or\nunlink(\"input.txt\"); unlink(\"/input.txt\")\n\n# directories needs the recursive flag\nunlink(\"docs\", recursive = TRUE)\nunlink(\"/docs\", recursive = TRUE)\n", "language": "R" }, { "code": "#lang racket\n\n;; here\n(delete-file \"input.txt\")\n(delete-directory \"docs\")\n(delete-directory/files \"docs\") ; recursive deletion\n\n;; in the root\n(delete-file \"/input.txt\")\n(delete-directory \"/docs\")\n(delete-directory/files \"/docs\")\n\n;; or in the root with relative paths\n(parameterize ([current-directory \"/\"])\n (delete-file \"input.txt\")\n (delete-directory \"docs\")\n (delete-directory/files \"docs\"))\n", "language": "Racket" }, { "code": "unlink 'input.txt';\nunlink '/input.txt';\nrmdir 'docs';\nrmdir '/docs';\n", "language": "Raku" }, { "code": "'input.txt' delete\n'/input.txt' delete\n'docs' rmdir\n'/docs' rmdir\n", "language": "Raven" }, { "code": "; Local.\ndelete %input.txt\ndelete-dir %docs/\n\n; Root.\ndelete %/input.txt\ndelete-dir %/docs/\n", "language": "REBOL" }, { "code": "'input.txt file:delete\n'/input.txt file:delete\n", "language": "Retro" }, { "code": "/*REXX program deletes a file and a folder in the current directory and the root. */\ntrace off /*suppress REXX error messages from DOS*/\naFile= 'input.txt' /*name of a file to be deleted. */\naDir = 'docs' /*name of a folder to be removed. */\n do j=1 for 2 /*perform this DO loop exactly twice.*/\n 'ERASE' aFile /*erase this file in the current dir. */\n 'RMDIR' \"/s /q\" aDir /*remove the folder \" \" \" \" */\n if j==1 then 'CD \\' /*make the current dir the root dir.*/\n end /* [↑] just do CD \\ command once.*/\n /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "remove(\"output.txt\")\nsystem(\"rmdir docs\")\n", "language": "Ring" }, { "code": "File.delete(\"output.txt\", \"/output.txt\")\nDir.delete(\"docs\")\nDir.delete(\"/docs\")\n", "language": "Ruby" }, { "code": "'------ delete input.txt ----------------\nkill \"input.txt\" ' this is where we are\nkill \"/input.txt\" ' this is the root\n\n' ---- delete directory docs ----------\nresult = rmdir(\"Docs\") ' directory where we are\nresult = rmdir(\"/Docs\") ' root directory\n", "language": "Run-BASIC" }, { "code": "use std::io::{self, Write};\nuse std::fs::{remove_file,remove_dir};\nuse std::path::Path;\nuse std::{process,display};\n\nconst FILE_NAME: &'static str = \"output.txt\";\nconst DIR_NAME : &'static str = \"docs\";\n\nfn main() {\n delete(\".\").and(delete(\"/\"))\n .unwrap_or_else(|e| error_handler(e,1));\n}\n\n\nfn delete<P>(root: P) -> io::Result<()>\n where P: AsRef<Path>\n{\n remove_file(root.as_ref().join(FILE_NAME))\n .and(remove_dir(root.as_ref().join(DIR_NAME)))\n}\n\nfn error_handler<E: fmt::Display>(error: E, code: i32) -> ! {\n let _ = writeln!(&mut io::stderr(), \"{:?}\", error);\n process::exit(code)\n}\n", "language": "Rust" }, { "code": "import java.util._\nimport java.io.File\n\nobject FileDeleteTest extends App {\n def deleteFile(filename: String) = { new File(filename).delete() }\n\n def test(typ: String, filename: String) = {\n System.out.println(\"The following \" + typ + \" called \" + filename +\n (if (deleteFile(filename)) \" was deleted.\" else \" could not be deleted.\"))\n }\n test(\"file\", \"input.txt\")\n test(\"file\", File.separatorChar + \"input.txt\")\n test(\"directory\", \"docs\")\n test(\"directory\", File.separatorChar + \"docs\" + File.separatorChar)\n}\n", "language": "Scala" }, { "code": "(delete-file filename)\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n include \"osfiles.s7i\";\n\nconst proc: main is func\n begin\n removeFile(\"input.txt\");\n removeFile(\"/input.txt\");\n removeTree(\"docs\");\n removeTree(\"/docs\");\n end func;\n", "language": "Seed7" }, { "code": "// Delete locally (relative to \"the folder\")\ndelete file \"input.txt\"\ndelete folder \"docs\"\n\n// Delete at the file system root\ndelete file \"/input.txt\"\ndelete folder \"/docs\"\n", "language": "SenseTalk" }, { "code": "# here\n%f'input.txt' -> delete;\n%d'docs' -> delete;\n\n# root dir\nDir.root + %f'input.txt' -> delete;\nDir.root + %d'docs' -> delete;\n", "language": "Sidef" }, { "code": "(File newNamed: 'input.txt') delete.\n(File newNamed: '/input.txt') delete.\n(Directory newNamed: 'docs') delete.\n(Directory newNamed: '/docs') delete.\n", "language": "Slate" }, { "code": "(Directory current / 'input.txt') delete.\n(Directory root / 'input.txt') delete.\n", "language": "Slate" }, { "code": "File remove: 'input.txt'.\nFile remove: 'docs'.\nFile remove: '/input.txt'.\nFile remove: '/docs'\n", "language": "Smalltalk" }, { "code": "OS.FileSys.remove \"input.txt\";\nOS.FileSys.remove \"/input.txt\";\nOS.FileSys.rmDir \"docs\";\nOS.FileSys.rmDir \"/docs\";\n", "language": "Standard-ML" }, { "code": "erase input.txt\nrmdir docs\n", "language": "Stata" }, { "code": "file delete input.txt /input.txt\n\n# preserve directory if non-empty\nfile delete docs /docs\n\n# delete even if non-empty\nfile delete -force docs /docs\n", "language": "Tcl" }, { "code": "needs shell\n\" docs\" remove\n\" input.txt\" remove\n", "language": "Toka" }, { "code": "$$ MODE TUSCRIPT\n- delete file\nSET status = DELETE (\"input.txt\")\n- delete directory\nSET status = DELETE (\"docs\",-std-)\n", "language": "TUSCRIPT" }, { "code": "rm -rf docs\nrm input.txt\nrm -rf /docs\nrm /input.txt\n", "language": "UNIX-Shell" }, { "code": "decl file f\nf.delete \"input.txt\"\nf.delete \"docs\"\nf.delete \"/input.txt\"\nf.delete \"/docs\"\n", "language": "Ursa" }, { "code": "import os\n\nfn main() {\n\tos.rm(\"./input.txt\") or {println(err) exit(-1)}\n\tos.rmdir(\"./docs\") or {println(err) exit(-2)} // os.rmdir_all, recursively removes specified directory\n\t// check if file exists\n\tif os.is_file(\"./input.txt\") == true {println(\"Found file!\")}\n\telse {println(\"File was not found!\")}\n\t// check if directory exists\n\tif os.is_dir(\"./docs\") == true {println(\"Found directory!\")}\n\telse {println(\"Directory was not found!\")}\n}\n", "language": "V-(Vlang)" }, { "code": "74 75 70 6E 69 20 65 74 65 6C 65 64 0000 1 dcl:\t.ascii\t\"delete input.txt;,docs.dir;\"\n64 2E 73 63 6F 64 2C 3B 74 78 74 2E 000C\n 3B 72 69 0018\n69 76 65 64 73 79 73 24 73 79 73 2C 001B 2 \t.ascii\t\",sys$sysdevice:[000000]input.txt;\"\n69 5D 30 30 30 30 30 30 5B 3A 65 63 0027\n 3B 74 78 74 2E 74 75 70 6E 0033\n69 76 65 64 73 79 73 24 73 79 73 2C 003C 3 \t.ascii\t\",sys$sysdevice:[000000]docs.dir;\"\n64 5D 30 30 30 30 30 30 5B 3A 65 63 0048\n 3B 72 69 64 2E 73 63 6F 0054\n 005C 4\n 0000005C 005C 5 desc:\t.long\t.-dcl\t\t\t\t\t;character count\n 00000000' 0060 6 \t.address dcl\n 0064 7\n 0000 0064 8 .entry\tmain,0\n F3 AF 7F 0066 9 \tpushaq\tdesc\n 00000000'GF 01 FB 0069 10 \tcalls\t#1, g^lib$do_command\t\t\t;execute shell command\n 04 0070 11 \tret\n 0071 12 .end\tmain\n", "language": "VAX-Assembly" }, { "code": "Option Explicit\n\nSub DeleteFileOrDirectory()\nDim myPath As String\n myPath = \"C:\\Users\\surname.name\\Desktop\\Docs\"\n'delete file\n Kill myPath & \"\\input.txt\"\n'delete Directory\n RmDir myPath\nEnd Sub\n", "language": "VBA" }, { "code": "Set oFSO = CreateObject( \"Scripting.FileSystemObject\" )\n\noFSO.DeleteFile \"input.txt\"\noFSO.DeleteFolder \"docs\"\n\noFSO.DeleteFile \"\\input.txt\"\noFSO.DeleteFolder \"\\docs\"\n\n'Using Delete on file and folder objects\n\ndim fil, fld\n\nset fil = oFSO.GetFile( \"input.txt\" )\nfil.Delete\nset fld = oFSO.GetFolder( \"docs\" )\nfld.Delete\n\nset fil = oFSO.GetFile( \"\\input.txt\" )\nfil.Delete\nset fld = oFSO.GetFolder( \"\\docs\" )\nfld.Delete\n", "language": "VBScript" }, { "code": "// In current directory\nFile_Delete(\"input.txt\", OK)\nFile_Rmdir(\"docs\")\n\n// In the root directory\nFile_Delete(\"/input.txt\", OK)\nFile_Rmdir(\"/docs\")\n", "language": "Vedit-macro-language" }, { "code": "'Current Directory\nIO.Directory.Delete(\"docs\")\nIO.Directory.Delete(\"docs\", True) 'also delete files and sub-directories\nIO.File.Delete(\"output.txt\")\n\n'Root\nIO.Directory.Delete(\"\\docs\")\nIO.File.Delete(\"\\output.txt\")\n\n'Root, platform independent\nIO.Directory.Delete(IO.Path.DirectorySeparatorChar & \"docs\")\nIO.File.Delete(IO.Path.DirectorySeparatorChar & \"output.txt\")\n", "language": "Visual-Basic-.NET" }, { "code": "import \"io\" for File\n\nFile.delete(\"input.txt\")\n\n// check it worked\nSystem.print(File.exists(\"input.txt\"))\n", "language": "Wren" }, { "code": ";syscall numbers for readability. :]\n%define sys_rmdir 40\n%define sys_unlink 10\n\nsection .text\n\tglobal _start\n\t\n\t_start:\n\t\tmov ebx, fn\n\t\tmov eax, sys_unlink\n\t\tint 0x80\n\t\ttest eax, eax\n\t\tjs _ragequit\n\t\t\n\t\tmov ebx, dn\n\t\tmov eax, sys_rmdir\t\t\t\n\t\tint 0x80\n\t\t\n\t\tmov ebx, rfn\n\t\tmov eax, sys_unlink\n\t\tint 0x80\n\t\tcmp eax, 0\n\t\tje _exit\n\t\t\n\t\t_ragequit:\n\t\t\tmov edx, err_len\n\t\t\tmov ecx, err_msg\n\t\t\tmov ebx, 4\n\t\t\tmov eax ,1\n\t\t\tint 0x80\n\t\t\t\n\t\t_exit:\n\t\t\tpush 0x1\n\t\t\tmov eax, 1\n\t\t\tpush eax\n\t\t\tint 0x80\n\t\t\tret\n\t\nsection .data\nfn\t\tdb 'input.txt',0\nrfn\t\tdb '/input.txt',0\ndn\t\tdb 'doc',0\n\nerr_msg\t\tdb \"Something went wrong! :[\",0xa\nerr_len\t\tequ $-err_msg\n", "language": "X86-Assembly" }, { "code": "remove, \"input.txt\";\nremove, \"/input.txt\";\nrmdir, \"docs\";\nrmdir, \"/docs\";\n", "language": "Yorick" }, { "code": "const std = @import(\"std\");\nconst fs = std.fs;\n\npub fn main() !void {\n const here = fs.cwd();\n try here.deleteFile(\"input.txt\");\n try here.deleteDir(\"docs\");\n\n const root = try fs.openDirAbsolute(\"/\", .{});\n try root.deleteFile(\"input.txt\");\n try root.deleteDir(\"docs\");\n}\n", "language": "Zig" }, { "code": "zkl: System.cmd((System.isWindows and \"del\" or \"unlink\") + \" input.txt\")\n0\nzkl: System.cmd((System.isWindows and \"del\" or \"unlink\") + \" /input.txt\")\nunlink: cannot unlink ‘/input.txt’: No such file or directory\n256\nzkl: System.cmd(\"rmdir docs\")\nrmdir: failed to remove ‘docs’: Directory not empty\n256\nzkl: System.cmd(\"rm -r docs\")\n0\nzkl: System.cmd(\"rm -r /docs\")\nrm: cannot remove ‘/docs’: No such file or directory\n256\n", "language": "Zkl" }, { "code": "ERASE \"m\"; 1; \"INPUTTXT\"\n", "language": "ZX-Spectrum-Basic" }, { "code": "ERASE \"a:INPUTTXT\"\n", "language": "ZX-Spectrum-Basic" } ]
Delete-a-file
[ { "code": "---\ncategory:\n- Puzzles\nfrom: http://rosettacode.org/wiki/Department_numbers\n", "language": "00-META" }, { "code": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* &nbsp; police department\n::* &nbsp; sanitation department\n::* &nbsp; fire department \n\n\nEach department can have a number between &nbsp; '''1''' &nbsp; and &nbsp; '''7''' &nbsp; (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to &nbsp; '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs <u>all</u> valid combinations.\n\n\nPossible output &nbsp; (for the 1<sup>st</sup> and 14<sup>th</sup> solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n<br><br>\n\n", "language": "00-TASK" }, { "code": "print(‘Police Sanitation Fire’)\nprint(‘----------------------------------’)\n\nL(police) (2..6).step(2)\n L(sanitation) 1..7\n L(fire) 1..7\n I police!=sanitation & sanitation!=fire & fire!=police & police+fire+sanitation==12\n print(police\"\\t\\t\"sanitation\"\\t\\t\"fire)\n", "language": "11l" }, { "code": "\torg\t100h\n\tlxi\th,obuf\t; HL = output buffer\n\tmvi\tb,2\t; B = police\npol:\tmvi\tc,1\t; C = sanitation\nsan:\tmvi\td,1\t; D = fire\nfire:\tmov\ta,b\t; Fire equal to police?\n\tcmp\td\n\tjz\tnext\t; If so, invalid combination\n\tmov\ta,c\t; Fire equal to sanitation?\n\tcmp\td\n\tjz\tnext\t; If so, invalid combination\n\tmov\ta,b\t; Total equal to 12?\n\tadd\tc\n\tadd\td\n\tcpi\t12\n\tjnz\tnext\t; If not, invalid combination\t\n\tmov\ta,b\t; Combination is valid, add to output\n\tcall\tnum\n\tmov\ta,c\n\tcall \tnum\n\tmov\ta,d\n\tcall\tnum\n\tmvi\tm,13\t; Add a newline to the output\n\tinx\th\n\tmvi\tm,10\n\tinx\th\nnext:\tmvi\ta,7\t; Load 7 to compare to\n\tinr\td\t; Next fire number\n\tcmp\td\t; Reached the end?\n\tjnc\tfire\t; If not, next fire number\n\tinr\tc\t; Otherwise, next sanitation number\n\tcmp\tc\t; Reached the end?\n\tjnc\tsan\t; If not, next sanitation number\n\tinr\tb\t; Increment police number twice\n\tinr\tb\t; (twice, because it must be even)\n\tcmp\tb\t; Reached the end?\n\tjnc\tpol \t; If not, next police number\n\tmvi\tm,'$'\t; If so, we're done - add CP/M string terminator\n\tmvi\tc,9\t; Print the output string\n\tlxi\td,ohdr\n\tjmp\t5\nnum:\tadi\t'0'\t; Add number A and space to the output\n\tmov\tm,a\n\tinx\th\n\tmvi\tm,' '\n\tinx\th\n\tret\nohdr:\tdb\t'P S F',13,10\nobuf:\tequ\t$\t; Output buffer goes after program\n", "language": "8080-Assembly" }, { "code": "\tcpu\t8086\n\tbits\t16\n\torg\t100h\nsection\t.text\n\tmov\tdi,obuf\t\t; Output buffer\n\tmov\tbl,2\t\t; BL = police\npol:\tmov\tcl,1\t\t; CL = sanitation\nsan:\tmov\tdl,1\t\t; DL = fire\nfire:\tcmp\tbl,cl\t\t; Police equal to sanitation?\n\tje\tnext\t\t; Invalid combination\n\tcmp\tbl,dl\t\t; Police equal to fire?\n\tje\tnext\t\t; Invalid combination\n\tcmp\tcl,dl\t\t; Sanitation equal to fire?\n\tje\tnext\t\t; Invalid combination\n\tmov\tal,bl\t\t; Total equal to 12?\n\tadd\tal,cl\n\tadd\tal,dl\n\tcmp\tal,12\n\tjne\tnext\t\t; If not, invalid combination\n\tmov\tal,bl\t\t; Combination is valid, write the three numbers\n\tcall\tnum\n\tmov\tal,cl\n\tcall \tnum\n\tmov\tal,dl\n\tcall \tnum\n\tmov\tax,0A0Dh\t; And a newline\n\tstosw\nnext:\tmov\tal,7\t\t; Load 7 to compare to\n\tinc\tdx\t\t; Increment fire number\n\tcmp\tal,dl\t\t; If 7 or less,\n\tjae\tfire\t\t; next fire number.\n\tinc\tcx\t\t; Otherwise, ncrement sanitation number\n\tcmp\tal,cl\t\t; If 7 or less,\n\tjae\tsan\t\t; next sanitation number\n\tinc\tbx\t\t; Increment police number twice\n\tinc\tbx\t\t; (it must be even)\n\tcmp\tal,bl\t\t; If 7 or less,\n\tjae\tpol\t\t; next police number.\n\tmov\tbyte [di],'$'\t; At the end, terminate the string\n\tmov\tdx,ohdr\t\t; Tell MS-DOS to print it\n\tmov\tah,9\n\tint\t21h\n\tret\nnum:\tmov\tah,' '\t\t; Space\n\tadd\tal,'0'\t\t; Add number to output\n\tstosw\t\t\t; Store number and space\n\tret\nsection\t.data\nohdr:\tdb\t'P S F',13,10\t; Header\nobuf:\tequ\t$\t\t; Place to write output\n", "language": "8086-Assembly" }, { "code": "PUT 7 IN max.department.number\nPUT 12 IN department.sum\nWRITE \"police sanitation fire\" /\nPUT 2 IN police\nWHILE police <= max.department.number:\n FOR sanitation IN { 1 .. max.department.number }:\n IF sanitation <> police:\n PUT ( department.sum - police ) - sanitation IN fire\n IF fire > 0 AND fire <= max.department.number AND fire <> sanitation AND fire <> police:\n WRITE police>>6, sanitation>>11, fire>>5 /\n PUT police + 2 IN police\n", "language": "ABC" }, { "code": "PROC Main()\n BYTE p,s,f\n\n PrintE(\"P S F\")\n FOR p=2 TO 6 STEP 2\n DO\n FOR s=1 TO 7\n DO\n FOR f=1 TO 7\n DO\n IF p#s AND p#f AND s#f AND p+s+f=12 THEN\n PrintF(\"%B %B %B%E\",p,s,f)\n FI\n OD\n OD\n OD\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO;\n\nprocedure Department_Numbers is\n use Ada.Text_IO;\nbegin\n Put_Line (\" P S F\");\n for Police in 2 .. 6 loop\n for Sanitation in 1 .. 7 loop\n for Fire in 1 .. 7 loop\n if\n Police mod 2 = 0 and\n Police + Sanitation + Fire = 12 and\n Sanitation /= Police and\n Sanitation /= Fire and\n Police /= Fire\n then\n Put_Line (Police'Image & Sanitation'Image & Fire'Image);\n end if;\n end loop;\n end loop;\n end loop;\nend Department_Numbers;\n", "language": "Ada" }, { "code": "integer p, s, f;\n\np = 0;\nwhile ((p += 2) <= 7) {\n s = 0;\n while ((s += 1) <= 7) {\n f = 0;\n while ((f += 1) <= 7) {\n if (p + s + f == 12 && p != s && p != f && s != f) {\n o_form(\" ~ ~ ~\\n\", p, s, f);\n }\n }\n }\n}\n", "language": "Aime" }, { "code": "BEGIN\n # show possible department number allocations for police, sanitation and fire departments #\n # the police department number must be even, all department numbers in the range 1 .. 7 #\n # the sum of the department numbers must be 12 #\n INT max department number = 7;\n INT department sum = 12;\n print( ( \"police sanitation fire\", newline ) );\n FOR police FROM 2 BY 2 TO max department number DO\n FOR sanitation TO max department number DO\n IF sanitation /= police THEN\n INT fire = ( department sum - police ) - sanitation;\n IF fire > 0 AND fire <= max department number\n AND fire /= sanitation\n AND fire /= police\n THEN\n print( ( whole( police, -6 )\n , whole( sanitation, -11 )\n , whole( fire, -5 )\n , newline\n )\n )\n FI\n FI\n OD\n OD\nEND\n", "language": "ALGOL-68" }, { "code": "begin\n % show possible department number allocations for police, sanitation and fire departments %\n % the police department number must be even, all department numbers in the range 1 .. 7 %\n % the sum of the department numbers must be 12 %\n integer MAX_DEPARTMENT_NUMBER, DEPARTMENT_SUM;\n MAX_DEPARTMENT_NUMBER := 7;\n DEPARTMENT_SUM := 12;\n write( \"police sanitation fire\" );\n for police := 2 step 2 until MAX_DEPARTMENT_NUMBER do begin\n for sanitation := 1 until MAX_DEPARTMENT_NUMBER do begin\n IF sanitation not = police then begin\n integer fire;\n fire := ( DEPARTMENT_SUM - police ) - sanitation;\n if fire > 0 and fire <= MAX_DEPARTMENT_NUMBER and fire not = sanitation and fire not = police then begin\n write( s_w := 0, i_w := 6, police, i_w := 11, sanitation, i_w := 5, fire )\n end if_valid_combination\n end if_sanitation_ne_police\n end for_sanitation\n end for_police\nend.\n", "language": "ALGOL-W" }, { "code": "'PSF'⍪(⊢(⌿⍨)((∪≡⊢)¨↓∧(0=2|1⌷[2]⊢)∧12=+/))↑,⍳3/7\n", "language": "APL" }, { "code": "on run\n script\n on |λ|(x)\n script\n on |λ|(y)\n script\n on |λ|(z)\n if y ≠ z and 1 ≤ z and z ≤ 7 then\n {{x, y, z} as string}\n else\n {}\n end if\n end |λ|\n end script\n\n concatMap(result, {12 - (x + y)}) --Z\n end |λ|\n end script\n\n concatMap(result, {1, 2, 3, 4, 5, 6, 7}) --Y\n end |λ|\n end script\n\n unlines(concatMap(result, {2, 4, 6})) --X\nend run\n\n\n-- GENERIC FUNCTIONS ----------------------------------------------------------\n\n-- concatMap :: (a -> [b]) -> [a] -> [b]\non concatMap(f, xs)\n set lst to {}\n set lng to length of xs\n tell mReturn(f)\n repeat with i from 1 to lng\n set lst to (lst & |λ|(contents of item i of xs, i, xs))\n end repeat\n end tell\n return lst\nend concatMap\n\n-- intercalate :: Text -> [Text] -> Text\non intercalate(strText, lstText)\n set {dlm, my text item delimiters} to {my text item delimiters, strText}\n set strJoined to lstText as text\n set my text item delimiters to dlm\n return strJoined\nend intercalate\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n-- unlines :: [String] -> String\non unlines(xs)\n intercalate(linefeed, xs)\nend unlines\n", "language": "AppleScript" }, { "code": "-- NUMBERING CONSTRAINTS ------------------------------------------------------\n\n-- options :: Int -> Int -> Int -> [(Int, Int, Int)]\non options(lo, hi, total)\n set ds to enumFromTo(lo, hi)\n\n script Xeven\n on |λ|(x)\n script Ydistinct\n on |λ|(y)\n script ZinRange\n on |λ|(z)\n if y ≠ z and lo ≤ z and z ≤ hi then\n {{x, y, z}}\n else\n {}\n end if\n end |λ|\n end script\n\n concatMap(ZinRange, {total - (x + y)}) -- Z IS IN RANGE\n end |λ|\n end script\n\n script notX\n on |λ|(d)\n d ≠ x\n end |λ|\n end script\n\n concatMap(Ydistinct, filter(notX, ds)) -- Y IS NOT X\n end |λ|\n end script\n\n concatMap(Xeven, filter(my even, ds)) -- X IS EVEN\nend options\n\n\n-- TEST -----------------------------------------------------------------------\non run\n set xs to options(1, 7, 12)\n\n intercalate(\"\\n\\n\", ¬\n {\"(Police, Sanitation, Fire)\", ¬\n unlines(map(show, xs)), ¬\n \"Number of options: \" & |length|(xs)})\nend run\n\n\n-- GENERIC FUNCTIONS ----------------------------------------------------------\n\n-- concatMap :: (a -> [b]) -> [a] -> [b]\non concatMap(f, xs)\n set lst to {}\n set lng to length of xs\n tell mReturn(f)\n repeat with i from 1 to lng\n set lst to (lst & |λ|(contents of item i of xs, i, xs))\n end repeat\n end tell\n return lst\nend concatMap\n\n-- enumFromTo :: Int -> Int -> [Int]\non enumFromTo(m, n)\n if n < m then\n set d to -1\n else\n set d to 1\n end if\n set lst to {}\n repeat with i from m to n by d\n set end of lst to i\n end repeat\n return lst\nend enumFromTo\n\n-- even :: Int -> Bool\non even(x)\n x mod 2 = 0\nend even\n\n-- filter :: (a -> Bool) -> [a] -> [a]\non filter(f, xs)\n tell mReturn(f)\n set lst to {}\n set lng to length of xs\n repeat with i from 1 to lng\n set v to item i of xs\n if |λ|(v, i, xs) then set end of lst to v\n end repeat\n return lst\n end tell\nend filter\n\n-- intercalate :: Text -> [Text] -> Text\non intercalate(strText, lstText)\n set {dlm, my text item delimiters} to {my text item delimiters, strText}\n set strJoined to lstText as text\n set my text item delimiters to dlm\n return strJoined\nend intercalate\n\n-- length :: [a] -> Int\non |length|(xs)\n length of xs\nend |length|\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n-- show :: a -> String\non show(e)\n set c to class of e\n if c = list then\n script serialized\n on |λ|(v)\n show(v)\n end |λ|\n end script\n\n \"[\" & intercalate(\", \", map(serialized, e)) & \"]\"\n else if c = record then\n script showField\n on |λ|(kv)\n set {k, ev} to kv\n \"\\\"\" & k & \"\\\":\" & show(ev)\n end |λ|\n end script\n\n \"{\" & intercalate(\", \", ¬\n map(showField, zip(allKeys(e), allValues(e)))) & \"}\"\n else if c = date then\n \"\\\"\" & iso8601Z(e) & \"\\\"\"\n else if c = text then\n \"\\\"\" & e & \"\\\"\"\n else if (c = integer or c = real) then\n e as text\n else if c = class then\n \"null\"\n else\n try\n e as text\n on error\n (\"«\" & c as text) & \"»\"\n end try\n end if\nend show\n\n-- unlines :: [String] -> String\non unlines(xs)\n intercalate(linefeed, xs)\nend unlines\n", "language": "AppleScript" }, { "code": "loop 1..7 'x [\n loop 1..7 'y [\n loop 1..7 'z [\n if all? @[\n even? x\n 12 = sum @[x y z]\n 3 = size unique @[x y z]\n ] -> print [x y z]\n ]\n ]\n]\n", "language": "Arturo" }, { "code": "write(\"--police-- --sanitation-- --fire--\");\n\nfor(int police = 2; police < 6; police += 2) {\n for(int sanitation = 1; sanitation < 7; ++sanitation) {\n for(int fire = 1; fire < 7; ++fire) {\n if(police != sanitation && sanitation != fire && fire != police && police+fire+sanitation == 12){\n write(\" \", police, suffix=none);\n write(\" \", sanitation, suffix=none);\n write(\" \", fire);\n }\n }\n }\n}\n", "language": "Asymptote" }, { "code": "perm(elements, n, opt:=\"\", Delim:=\"\", str:=\"\", res:=\"\", j:=0, dup:=\"\") {\t\n\tres := IsObject(res) ? res : [], dup := IsObject(dup) ? dup : []\n\tif (n > j)\n\t\tLoop, parse, elements, % Delim\n\t\t\tres := !(InStr(str, A_LoopField) && !(InStr(opt, \"rep\"))) ? perm(elements, n, opt, Delim, trim(str Delim A_LoopField, Delim), res, j+1, dup) : res\n\telse if !(dup[x := perm_sort(str, Delim)] && (InStr(opt, \"comb\")))\n\t\tdup[x] := 1, res.Insert(str)\n\treturn res, j++\n}\n\nperm_sort(str, Delim){\n\tLoop, Parse, str, % Delim\n\t\tres .= A_LoopField \"`n\"\n\tSort, res, D`n\n\treturn StrReplace(res, \"`n\", Delim)\n}\n", "language": "AutoHotkey" }, { "code": "elements := \"1234567\", n := 3\nfor k, v in perm(elements, n)\n\tif (SubStr(v, 1, 1) + SubStr(v, 2, 1) + SubStr(v, 3, 1) = 12) && (SubStr(v, 1, 1) / 2 = Floor(SubStr(v, 1, 1)/2))\n\t\tres4 .= v \"`n\"\n\nMsgBox, 262144, , % res4\nreturn\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f DEPARTMENT_NUMBERS.AWK\nBEGIN {\n print(\" # FD PD SD\")\n for (fire=1; fire<=7; fire++) {\n for (police=1; police<=7; police++) {\n for (sanitation=1; sanitation<=7; sanitation++) {\n if (rules() ~ /^1+$/) {\n printf(\"%2d %2d %2d %2d\\n\",++count,fire,police,sanitation)\n }\n }\n }\n }\n exit(0)\n}\nfunction rules( stmt1,stmt2,stmt3) {\n stmt1 = fire != police && fire != sanitation && police != sanitation\n stmt2 = fire + police + sanitation == 12\n stmt3 = police % 2 == 0\n return(stmt1 stmt2 stmt3)\n}\n", "language": "AWK" }, { "code": "print \"--police-- --sanitation-- --fire--\"\n\nfor police = 2 to 7 step 2\n for fire = 1 to 7\n if fire = police then continue for\n sanitation = 12 - police - fire\n if sanitation = fire or sanitation = police then continue for\n if sanitation >= 1 and sanitation <= 7 then\n print rjust(police, 6); rjust(fire, 13); rjust(sanitation, 12)\n end if\n next fire\nnext police\n", "language": "BASIC256" }, { "code": "REM >deptnums\nmax_dept_num% = 7\ndept_sum% = 12\nPRINT \"police sanitation fire\"\nFOR police% = 2 TO max_dept_num% STEP 2\n FOR sanitation% = 1 TO max_dept_num%\n IF sanitation% <> police% THEN\n fire% = (dept_sum% - police%) - sanitation%\n IF fire% > 0 AND fire% <= max_dept_num% AND fire% <> sanitation% AND fire% <> police% THEN PRINT \" \"; police%; \" \"; sanitation%; \" \"; fire%\n ENDIF\n NEXT\nNEXT\nEND\n", "language": "BBC-BASIC" }, { "code": "get \"libhdr\"\n\nlet start() be\n for p=2 to 6 by 2\n for s=1 to 7\n for f=1 to 7\n if p~=s & s~=f & p~=f & p+s+f=12 then\n writef(\"%N %N %N*N\", p, s, f)\n", "language": "BCPL" }, { "code": "#include<stdio.h>\n\nint main()\n{\n\tint police,sanitation,fire;\n\t\n\tprintf(\"Police Sanitation Fire\\n\");\n\tprintf(\"----------------------------------\");\n\t\n\tfor(police=2;police<=6;police+=2){\n\t\tfor(sanitation=1;sanitation<=7;sanitation++){\n\t\t\tfor(fire=1;fire<=7;fire++){\n\t\t\t\tif(police!=sanitation && sanitation!=fire && fire!=police && police+fire+sanitation==12){\n\t\t\t\t\tprintf(\"\\n%d\\t\\t%d\\t\\t%d\",police,sanitation,fire);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <iomanip>\n\nint main( int argc, char* argv[] ) {\n int sol = 1;\n std::cout << \"\\t\\tFIRE\\t\\tPOLICE\\t\\tSANITATION\\n\";\n for( int f = 1; f < 8; f++ ) {\n for( int p = 1; p < 8; p++ ) {\n for( int s = 1; s < 8; s++ ) {\n if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) {\n std::cout << \"SOLUTION #\" << std::setw( 2 ) << sol++ << std::setw( 2 )\n << \":\\t\" << std::setw( 2 ) << f << \"\\t\\t \" << std::setw( 3 ) << p\n << \"\\t\\t\" << std::setw( 6 ) << s << \"\\n\";\n }\n }\n }\n }\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\npublic class Program\n{\n public static void Main() {\n for (int p = 2; p <= 7; p+=2) {\n for (int s = 1; s <= 7; s++) {\n int f = 12 - p - s;\n if (s >= f) break;\n if (f > 7) continue;\n if (s == p || f == p) continue; //not even necessary\n Console.WriteLine($\"Police:{p}, Sanitation:{s}, Fire:{f}\");\n Console.WriteLine($\"Police:{p}, Sanitation:{f}, Fire:{s}\");\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "10 CLS\n20 PRINT \"--police-- --sanitation-- --fire--\"\n30 FOR police = 2 TO 7 STEP 2\n40 FOR fire = 1 TO 7\n50 sanitation = 12-police-fire\n60 IF sanitation >= 1 AND sanitation <= 7 THEN\n70 PRINT TAB (5)police TAB (18)fire TAB (30)sanitation\n80 endif\n90 NEXT fire\n100 NEXT police\n", "language": "Chipmunk-Basic" }, { "code": "(let [n (range 1 8)]\n (for [police n\n sanitation n\n fire n\n :when (distinct? police sanitation fire)\n :when (even? police)\n :when (= 12 (+ police sanitation fire))]\n (println police sanitation fire)))\n", "language": "Clojure" }, { "code": "start_up = proc ()\n po: stream := stream$primary_output()\n\n stream$putl(po, \"P S F\\n- - -\")\n for police: int in int$from_to_by(2,7,2) do\n for sanitation: int in int$from_to(1,7) do\n for fire: int in int$from_to(1,7) do\n if police~=sanitation\n & sanitation~=fire\n & police~=fire\n & police+sanitation+fire = 12\n then\n stream$putl(po, int$unparse(police) || \" \" ||\n int$unparse(sanitation) || \" \" ||\n int$unparse(fire))\n end\n end\n end\n end\nend start_up\n", "language": "CLU" }, { "code": " IDENTIFICATION DIVISION.\n PROGRAM-ID. DEPARTMENT-NUMBERS.\n\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 BANNER PIC X(24) VALUE \"POLICE SANITATION FIRE\".\n 01 COMBINATION.\n 03 FILLER PIC X(5) VALUE SPACES.\n 03 POLICE PIC 9.\n 03 FILLER PIC X(11) VALUE SPACES.\n 03 SANITATION PIC 9.\n 03 FILLER PIC X(5) VALUE SPACES.\n 03 FIRE PIC 9.\n 01 TOTAL PIC 99.\n\n PROCEDURE DIVISION.\n BEGIN.\n DISPLAY BANNER.\n PERFORM POLICE-LOOP VARYING POLICE FROM 2 BY 2\n UNTIL POLICE IS GREATER THAN 6.\n STOP RUN.\n\n POLICE-LOOP.\n PERFORM SANITATION-LOOP VARYING SANITATION FROM 1 BY 1\n UNTIL SANITATION IS GREATER THAN 7.\n\n SANITATION-LOOP.\n PERFORM FIRE-LOOP VARYING FIRE FROM 1 BY 1\n UNTIL FIRE IS GREATER THAN 7.\n\n FIRE-LOOP.\n ADD POLICE, SANITATION, FIRE GIVING TOTAL.\n IF POLICE IS NOT EQUAL TO SANITATION\n AND POLICE IS NOT EQUAL TO FIRE\n AND SANITATION IS NOT EQUAL TO FIRE\n AND TOTAL IS EQUAL TO 12,\n DISPLAY COMBINATION.\n", "language": "COBOL" }, { "code": "include \"cowgol.coh\";\n\ntypedef Dpt is int(1, 7);\n\n# print combination if valid\nsub print_comb(p: Dpt, s: Dpt, f: Dpt) is\n var out: uint8[] := {'*',' ','*',' ','*','\\n',0};\n out[0] := p + '0';\n out[2] := s + '0';\n out[4] := f + '0';\n if p != s and p != f and f != s and p+s+f == 12 then\n print(&out[0]);\n end if;\nend sub;\n\nprint(\"P S F\\n\"); # header\n\nvar pol: Dpt := 2;\nwhile pol <= 7 loop\n var san: Dpt := 1;\n while san <= 7 loop\n var fire: Dpt := 1;\n while fire <= 7 loop\n print_comb(pol, san, fire);\n fire := fire + 1;\n end loop;\n san := san + 1;\n end loop;\n pol := pol + 2;\nend loop;\n", "language": "Cowgol" }, { "code": "print \"P S F\"\n\nfor p = 2 to 7 step 2\n\n\tfor s = 1 to 7\n\n\t\tif s <> p then\n\n\t\t\tlet f = (12 - p) - s\n\n\t\t\tif f > 0 and f <= 7 and f <> s and f <> p then\n\n\t\t\t\tprint p, \" \", s, \" \", f\n\n\t\t\tendif\n\n\t\tendif\n\n\tnext s\n\nnext p\n\nend\n", "language": "Craft-Basic" }, { "code": "import std.stdio, std.range;\n\nvoid main() {\n int sol = 1;\n writeln(\"\\t\\tFIRE\\t\\tPOLICE\\t\\tSANITATION\");\n foreach( f; iota(1,8) ) {\n foreach( p; iota(1,8) ) {\n foreach( s; iota(1,8) ) {\n if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) {\n writefln(\"SOLUTION #%2d:\\t%2d\\t\\t%3d\\t\\t%6d\", sol++, f, p, s);\n }\n }\n }\n }\n}\n", "language": "D" }, { "code": "program Department_numbers;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils;\n\nvar\n i, j, k, count: Integer;\n\nbegin\n writeln('Police Sanitation Fire');\n writeln('------ ---------- ----');\n count := 0;\n i := 2;\n while i < 7 do\n begin\n for j := 1 to 7 do\n begin\n if j = i then\n Continue;\n for k := 1 to 7 do\n begin\n if (k = i) or (k = j) then\n Continue;\n if i + j + k <> 12 then\n Continue;\n writeln(format(' %d %d %d', [i, j, k]));\n inc(count);\n end;\n end;\n inc(i, 2);\n end;\n writeln(#10, count, ' valid combinations');\n readln;\nend.\n", "language": "Delphi" }, { "code": "proc main() void:\n byte police, sanitation, fire;\n\n writeln(\"Police Sanitation Fire\");\n for police from 2 by 2 upto 7 do\n for sanitation from 1 upto 7 do\n for fire from 1 upto 7 do\n if police /= sanitation\n and police /= fire\n and sanitation /= fire\n and police + sanitation + fire = 12 then\n writeln(police:6, \" \", sanitation:10, \" \", fire:4)\n fi\n od\n od\n od\ncorp\n", "language": "Draco" }, { "code": "numfmt 0 3\nfor pol = 2 step 2 to 6\n for san = 1 to 7\n for fire = 1 to 7\n if pol <> san and san <> fire and fire <> pol\n if pol + fire + san = 12\n print pol & san & fire\n .\n .\n .\n .\n.\n", "language": "EasyLang" }, { "code": "IO.puts(\"P - F - S\")\nfor p <- [2,4,6],\n f <- 1..7,\n s <- 1..7,\n p != f and p != s and f != s and p + f + s == 12 do\n \"#{p} - #{f} - #{s}\"\n end\n |> Enum.each(&IO.puts/1)\n", "language": "Elixir" }, { "code": "P - F - S\n2 - 3 - 7\n2 - 4 - 6\n2 - 6 - 4\n2 - 7 - 3\n4 - 1 - 7\n4 - 2 - 6\n4 - 3 - 5\n4 - 5 - 3\n4 - 6 - 2\n4 - 7 - 1\n6 - 1 - 5\n6 - 2 - 4\n6 - 4 - 2\n6 - 5 - 1\n", "language": "Elixir" }, { "code": "departmentNumbers\n=validRows(\n LAMBDA(ab,\n LET(\n x, INDEX(ab, 0, 1),\n y, INDEX(ab, 0, 2),\n z, 12 - (x + y),\n\n IF(y <> z,\n IF(1 <= z,\n IF(7 >= z,\n CHOOSE({1, 2, 3}, x, y, z),\n NA()\n ),\n NA()\n ),\n NA()\n )\n )\n )(\n cartesianProduct({2;4;6})(\n SEQUENCE(7, 1, 1, 1)\n )\n )\n)\n", "language": "Excel" }, { "code": "cartesianProduct\n=LAMBDA(xs,\n LAMBDA(ys,\n LET(\n ny, ROWS(ys),\n ixs, SEQUENCE(ROWS(xs) * ny, 2, 1, 1),\n\n IF(0 <> MOD(ixs, 2),\n INDEX(xs,\n 1 + QUOTIENT(ixs, ny * 2)\n ),\n LET(\n r, MOD(QUOTIENT(ixs, 2), ny),\n\n INDEX(ys, IF(0 = r, ny, r))\n )\n )\n )\n )\n)\n\n\nvalidRows\n=LAMBDA(xs,\n LET(\n ixs, SEQUENCE(ROWS(xs), 1, 1, 1),\n valids, FILTER(\n ixs,\n LAMBDA(i,\n NOT(ISNA(INDEX(xs, i)))\n )(ixs)\n ),\n\n INDEX(\n xs,\n valids,\n SEQUENCE(\n 1,\n COLUMNS(xs)\n )\n )\n )\n)\n", "language": "Excel" }, { "code": "// A function to generate department numbers. Nigel Galloway: May 2nd., 2018\ntype dNum = {Police:int; Fire:int; Sanitation:int}\nlet fN n=n.Police%2=0&&n.Police+n.Fire+n.Sanitation=12&&n.Police<>n.Fire&&n.Police<>n.Sanitation&&n.Fire<>n.Sanitation\nList.init (7*7*7) (fun n->{Police=n%7+1;Fire=(n/7)%7+1;Sanitation=(n/49)+1})|>List.filter fN|>List.iter(printfn \"%A\")\n", "language": "F-Sharp" }, { "code": "USING: formatting io kernel math math.combinatorics math.ranges\nsequences sets ;\nIN: rosetta-code.department-numbers\n\n7 [1,b] 3 <k-permutations>\n[ [ first even? ] [ sum 12 = ] bi and ] filter\n\n\"{ Police, Sanitation, Fire }\" print nl\n[ \"%[%d, %]\\n\" printf ] each\n", "language": "Factor" }, { "code": "!!'Police Sanitation Fire';\n!!'------|----------|----';\nfor p = 2 to 6 by 2 do\n for s = 1 to 7 do\n for f = 1 to 7 do\n if p+f+s=12 and f<>p and f<>s and s<>p then !!(' ',p,' ',s,' ',f);\n fi od od od;\n", "language": "Fermat" }, { "code": "01.10 F P=2,2,6;F S=1,7;F G=1,7;D 2\n01.20 Q\n\n02.10 I (P-S)2.2,2.6,2.2\n02.20 I (P-G)2.3,2.6,2.3\n02.30 I (S-G)2.4,2.6,2.4\n02.40 I (P+S+G-12)2.6,2.5,2.6\n02.50 T %1,P,S,G,!\n02.60 R\n", "language": "FOCAL" }, { "code": "\\ if department numbers are valid, print them on a single line\n: fire ( pol san fir -- )\n 2dup = if 2drop drop exit then\n 2 pick over = if 2drop drop exit then\n rot . swap . . cr ;\n\n\\ tries to assign numbers with given policeno and sanitationno\n\\ and fire = 12 - policeno - sanitationno\n: sanitation ( pol san -- )\n 2dup = if 2drop exit then \\ no repeated numbers\n 12 over - 2 pick - \\ calculate fireno\n dup 1 < if 2drop drop exit then \\ cannot be less than 1\n dup 7 > if 2drop drop exit then \\ cannot be more than 7\n fire ;\n\n\\ tries to assign numbers with given policeno\n\\ and sanitation = 1, 2, 3, ..., or 7\n: police ( pol -- )\n 8 1 do dup i sanitation loop drop ;\n\n\\ tries to assign numbers with police = 2, 4, or 6\n: departments cr \\ leave input line\n 8 2 do i police 2 +loop ;\n", "language": "Forth" }, { "code": " INTEGER P,S,F\t!Department codes for Police, Sanitation, and Fire. Values 1 to 7 only.\n 1 PP:DO P = 2,7,2\t!The police demand an even number. They're special and use violence.\n 2 SS:DO S = 1,7\t\t!The sanitation department accepts any value.\n 3 IF (P.EQ.S) CYCLE SS\t!But it must differ from the others.\n 4 F = 12 - (P + S)\t\t!The fire department accepts any number, but the sum must be twelve.\n 5 IF (F.LE.0 .OR. F.GT.7) CYCLE SS\t!Ensure that the only option is within range.\n 6 IF ((F - S)*(F - P)) 7,8,7\t\t!And F is to differ from S and from P\n 7 WRITE (6,\"(3I2)\") P,S,F\t\t!If we get here, we have a possible set.\n 8 END DO SS\t\t!Next S\n 9 END DO PP\t!Next P.\n END\t!Well, that was straightforward.\n", "language": "Fortran" }, { "code": "' version 15-08-2017\n' compile with: fbc -s console\n\nDim As Integer fire, police, sanitation\n\nPrint \"police fire sanitation\"\nPrint \"----------------------\"\n\nFor police = 2 To 7 Step 2\n For fire = 1 To 7\n If fire = police Then Continue For\n sanitation = 12 - police - fire\n If sanitation = fire Or sanitation = police Then Continue For\n If sanitation >= 1 And sanitation <= 7 Then\n Print Using \" # # # \"; police; fire; sanitation\n End If\n Next\nNext\n\n' empty keyboard buffer\nWhile Inkey <> \"\" : Wend\nPrint : Print \"hit any key to end program\"\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "include \"NSLog.incl\"\n\nvoid local fn DepartmentNumbers\n long police, sanitation, fire\n\n printf @\"Police Sanitation Fire\"\n printf @\"-------------------------------\"\n\n for police = 2 to 7 step 2\n for fire = 1 to 7\n if ( fire = police ) then continue\n sanitation = 12 - police - fire\n if ( sanitation == fire ) or ( sanitation == police ) then continue\n if ( sanitation >= 1 ) and ( sanitation <= 7 )\n printf @\"%4d%12d%13d\", police, fire, sanitation\n end if\n next\n next\nend fn\n\nwindow 1\n\nfn DepartmentNumbers\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\nDim siC0, siC1, siC2 As Short\nDim sOut As New String[]\nDim sTemp As String\n\nFor siC0 = 2 To 6 Step 2\n For siC1 = 1 To 7\n For siC2 = 1 To 7\n If sic0 + siC1 + siC2 = 12 Then\n If siC0 <> siC1 And siC1 <> siC2 And siC0 <> siC2 Then sOut.Add(Str(siC0) & Str(siC1) & Str(siC2))\n End If\n Next\n Next\nNext\n\nPrint \"\\tPolice\\tFire\\tSanitation\"\nsiC0 = 0\n\nFor Each sTemp In sOut\n Inc sic0\n Print \"[\" & Format(Str(siC0), \"00\") & \"]\\t\" & Left(sTemp, 1) & \"\\t\" & Mid(sTemp, 2, 1) & \"\\t\" & Right(sTemp, 1)\nNext\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc main() {\n fmt.Println(\"Police Sanitation Fire\")\n fmt.Println(\"------ ---------- ----\")\n count := 0\n for i := 2; i < 7; i += 2 {\n for j := 1; j < 8; j++ {\n if j == i { continue }\n for k := 1; k < 8; k++ {\n if k == i || k == j { continue }\n if i + j + k != 12 { continue }\n fmt.Printf(\" %d %d %d\\n\", i, j, k)\n count++\n }\n }\n }\n fmt.Printf(\"\\n%d valid combinations\\n\", count)\n}\n", "language": "Go" }, { "code": "class DepartmentNumbers {\n static void main(String[] args) {\n println(\"Police Sanitation Fire\")\n println(\"------ ---------- ----\")\n int count = 0\n for (int i = 2; i <= 6; i += 2) {\n for (int j = 1; j <= 7; ++j) {\n if (j == i) continue\n for (int k = 1; k <= 7; ++k) {\n if (k == i || k == j) continue\n if (i + j + k != 12) continue\n println(\" $i $j $k\")\n count++\n }\n }\n }\n println()\n println(\"$count valid combinations\")\n }\n}\n", "language": "Groovy" }, { "code": "10 PRINT \"Police Sanitation Fire\"\n20 PRINT \"------|----------|----\"\n30 FOR P = 2 TO 7 STEP 2\n40 FOR S = 1 TO 7\n50 IF S = P THEN GOTO 100\n60 FOR F = 1 TO 7\n70 IF S = F OR F = P THEN GOTO 90\n80 IF P+S+F = 12 THEN PRINT USING \" # # #\";P;F;S\n90 NEXT F\n100 NEXT S\n110 NEXT P\n", "language": "GW-BASIC" }, { "code": "main :: IO ()\nmain =\n mapM_ print $\n [2, 4, 6] >>=\n \\x ->\n [1 .. 7] >>=\n \\y ->\n [12 - (x + y)] >>=\n \\z ->\n case y /= z && 1 <= z && z <= 7 of\n True -> [(x, y, z)]\n _ -> []\n", "language": "Haskell" }, { "code": "main :: IO ()\nmain =\n mapM_\n print\n [ (x, y, z)\n | x <- [2, 4, 6]\n , y <- [1 .. 7]\n , z <- [12 - (x + y)]\n , y /= z && 1 <= z && z <= 7 ]\n", "language": "Haskell" }, { "code": "main :: IO ()\nmain =\n mapM_ print $\n do x <- [2, 4, 6]\n y <- [1 .. 7]\n z <- [12 - (x + y)]\n if y /= z && 1 <= z && z <= 7\n then [(x, y, z)]\n else []\n", "language": "Haskell" }, { "code": "import Data.List (nub)\n\nmain :: IO ()\nmain =\n let xs = [1 .. 7]\n in mapM_ print $\n xs >>=\n \\x ->\n xs >>=\n \\y ->\n xs >>=\n \\z ->\n [ (x, y, z)\n | even x && 3 == length (nub [x, y, z]) && 12 == sum [x, y, z] ]\n", "language": "Haskell" }, { "code": "-------------------- DEPARTMENT NUMBERS ------------------\n\noptions :: Int -> Int -> Int -> [(Int, Int, Int)]\noptions lo hi total =\n ( \\ds ->\n filter even ds\n >>= \\x ->\n filter (/= x) ds\n >>= \\y ->\n [total - (x + y)]\n >>= \\z ->\n [ (x, y, z)\n | y /= z && lo <= z && z <= hi\n ]\n )\n [lo .. hi]\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n let xs = options 1 7 12\n in putStrLn \"(Police, Sanitation, Fire)\\n\"\n >> mapM_ print xs\n >> mapM_\n putStrLn\n [ \"\\nNumber of options: \",\n show (length xs)\n ]\n", "language": "Haskell" }, { "code": "options :: Int -> Int -> Int -> [(Int, Int, Int)]\noptions lo hi total =\n let ds = [lo .. hi]\n in [ (x, y, z)\n | x <- filter even ds\n , y <- filter (/= x) ds\n , let z = total - (x + y)\n , y /= z && lo <= z && z <= hi ]\n", "language": "Haskell" }, { "code": "import Control.Monad (guard)\n\noptions :: Int -> Int -> Int -> [(Int, Int, Int)]\noptions lo hi total =\n let ds = [lo .. hi]\n in do x <- filter even ds\n y <- filter (/= x) ds\n let z = total - (x + y)\n guard $ y /= z && lo <= z && z <= hi\n return (x, y, z)\n", "language": "Haskell" }, { "code": "100 PRINT \"Police\",\"San.\",\"Fire\"\n110 FOR P=2 TO 7 STEP 2\n120 FOR S=1 TO 7\n130 IF S<>P THEN\n131 LET F=(12-P)-S\n140 IF F>0 AND F<=7 AND F<>S AND F<>P THEN PRINT P,S,F\n141 END IF\n150 NEXT\n160 NEXT\n", "language": "IS-BASIC" }, { "code": "require 'stats'\npermfrom=: ,/@(perm@[ {\"_ 1 comb) NB. get permutations of length x from y possible items\n\nalluniq=: # = #@~. NB. check items are unique\naddto12=: 12 = +/ NB. check items add to 12\niseven=: -.@(2&|) NB. check items are even\npoliceeven=: {.@iseven NB. check first item is even\nconditions=: policeeven *. addto12 *. alluniq\n\nValidnums=: >: i.7 NB. valid Department numbers\n\ngetDeptNums=: [: (#~ conditions\"1) Validnums {~ permfrom\n", "language": "J" }, { "code": " 3 getDeptNums 7\n4 1 7\n4 7 1\n6 1 5\n6 5 1\n2 3 7\n2 7 3\n2 4 6\n2 6 4\n4 2 6\n4 6 2\n6 2 4\n6 4 2\n4 3 5\n4 5 3\n", "language": "J" }, { "code": " (/:\"#. 2|]) (#~ 12=+/\"1) 1+3 comb 7 [ load'stats'\n4 1 7\n6 1 5\n2 3 7\n2 4 6\n4 3 5\n", "language": "J" }, { "code": " NB. 3 departments, 1..7 in each\n #rule1=. >,{3#<1+i.7\n343\n NB. total must be 12, numbers must be unique\n #rule2=. (#~ ((3=#@~.) * 12=+/)\"1) rule1\n30\n NB. no odd numbers in police department (first department)\n #rule3=. (#~ 0=2|{.\"1) rule2\n14\n rule3\n2 3 7\n2 4 6\n2 6 4\n2 7 3\n4 1 7\n4 2 6\n4 3 5\n4 5 3\n4 6 2\n4 7 1\n6 1 5\n6 2 4\n6 4 2\n6 5 1\n", "language": "J" }, { "code": "public class DepartmentNumbers {\n public static void main(String[] args) {\n System.out.println(\"Police Sanitation Fire\");\n System.out.println(\"------ ---------- ----\");\n int count = 0;\n for (int i = 2; i <= 6; i += 2) {\n for (int j = 1; j <= 7; ++j) {\n if (j == i) continue;\n for (int k = 1; k <= 7; ++k) {\n if (k == i || k == j) continue;\n if (i + j + k != 12) continue;\n System.out.printf(\" %d %d %d\\n\", i, j, k);\n count++;\n }\n }\n }\n System.out.printf(\"\\n%d valid combinations\", count);\n }\n}\n", "language": "Java" }, { "code": "(function () {\n 'use strict';\n\n // concatMap :: (a -> [b]) -> [a] -> [b]\n function concatMap(f, xs) {\n return [].concat.apply([], xs.map(f));\n };\n\n return '(Police, Sanitation, Fire)\\n' +\n concatMap(function (x) {\n return concatMap(function (y) {\n return concatMap(function (z) {\n return z !== y && 1 <= z && z <= 7 ? [\n [x, y, z]\n ] : [];\n }, [12 - (x + y)]);\n }, [1, 2, 3, 4, 5, 6, 7]);\n }, [2, 4, 6])\n .map(JSON.stringify)\n .join('\\n');\n})();\n", "language": "JavaScript" }, { "code": "(function () {\n 'use strict';\n\n // NUMBERING CONSTRAINTS --------------------------------------------------\n\n // options :: Int -> Int -> Int -> [(Int, Int, Int)]\n function options(lo, hi, total) {\n var bind = flip(concatMap),\n ds = enumFromTo(lo, hi);\n\n return bind(filter(even, ds),\n function (x) { // X is even,\n return bind(filter(function (d) { return d !== x; }, ds),\n function (y) { // Y is distinct from X,\n return bind([total - (x + y)],\n function (z) { // Z sums with x and y to total, and is in ds.\n return z !== y && lo <= z && z <= hi ? [\n [x, y, z]\n ] : [];\n })})})};\n\n // GENERIC FUNCTIONS ------------------------------------------------------\n\n // concatMap :: (a -> [b]) -> [a] -> [b]\n function concatMap(f, xs) {\n return [].concat.apply([], xs.map(f));\n };\n\n // enumFromTo :: Int -> Int -> [Int]\n function enumFromTo(m, n) {\n return Array.from({\n length: Math.floor(n - m) + 1\n }, function (_, i) {\n return m + i;\n });\n };\n\n // even :: Integral a => a -> Bool\n function even(n) {\n return n % 2 === 0;\n };\n\n // filter :: (a -> Bool) -> [a] -> [a]\n function filter(f, xs) {\n return xs.filter(f);\n };\n\n // flip :: (a -> b -> c) -> b -> a -> c\n function flip(f) {\n return function (a, b) {\n return f.apply(null, [b, a]);\n };\n };\n\n // length :: [a] -> Int\n function length(xs) {\n return xs.length;\n };\n\n // map :: (a -> b) -> [a] -> [b]\n function map(f, xs) {\n return xs.map(f);\n };\n\n // show :: a -> String\n function show(x) {\n return JSON.stringify(x);\n }; //, null, 2);\n\n // unlines :: [String] -> String\n function unlines(xs) {\n return xs.join('\\n');\n };\n\n // TEST -------------------------------------------------------------------\n var xs = options(1, 7, 12);\n return '(Police, Sanitation, Fire)\\n\\n' +\n unlines(map(show, xs)) + '\\n\\nNumber of options: ' + length(xs);\n})();\n", "language": "JavaScript" }, { "code": "(() => {\n \"use strict\";\n\n const\n label = \"(Police, Sanitation, Fire)\",\n solutions = [2, 4, 6]\n .flatMap(\n x => [1, 2, 3, 4, 5, 6, 7]\n .flatMap(\n y => [12 - (x + y)]\n .flatMap(\n z => z !== y && 1 <= z && z <= 7 ? [\n [x, y, z]\n ] : []\n )\n )\n )\n .map(JSON.stringify)\n .join(\"\\n\");\n\n return `${label}\\n${solutions}`;\n})();\n", "language": "JavaScript" }, { "code": "(() => {\n \"use strict\";\n\n // -------------- NUMBERING CONSTRAINTS --------------\n\n // options :: Int -> Int -> Int -> [(Int, Int, Int)]\n const options = lo => hi => total => {\n const\n bind = xs => f => xs.flatMap(f),\n ds = enumFromTo(lo)(hi);\n\n return bind(ds.filter(even))(\n x => bind(ds.filter(d => d !== x))(\n y => bind([total - (x + y)])(\n z => (z !== y && lo <= z && z <= hi) ? [\n [x, y, z]\n ] : []\n )\n )\n );\n };\n\n // ---------------------- TEST -----------------------\n const main = () => {\n const\n label = \"(Police, Sanitation, Fire)\",\n solutions = options(1)(7)(12),\n n = solutions.length,\n list = solutions\n .map(JSON.stringify)\n .join(\"\\n\");\n\n return (\n `${label}\\n\\n${list}\\n\\nNumber of options: ${n}`\n );\n };\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // even :: Integral a => a -> Bool\n const even = n => n % 2 === 0;\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "def check(fire; police; sanitation):\n (fire != police) and (fire != sanitation) and (police != sanitation)\n and (fire + police + sanitation == 12)\n and (police % 2 == 0);\n\nrange(1;8) as $fire\n| range(1;8) as $police\n| range(1;8) as $sanitation\n| select( check($fire; $police; $sanitation) )\n| {$fire, $police, $sanitation}\n", "language": "Jq" }, { "code": "{fire: range(1;8), police: range(1;8), sanitation: range(1;8)}\n| select( .fire != .police and .fire != .sanitation and .police != .sanitation\n and .fire + .police + .sanitation == 12\n and .police % 2 == 0 )\n", "language": "Jq" }, { "code": " [range(1;8)]\n | combinations(3)\n | select( add == 12 and .[1] % 2 == 0)\n | {fire: .[0], police: .[1], sanitation: .[2]}\n", "language": "Jq" }, { "code": "using Printf\n\nfunction findsolution(rng=1:7)\n rst = Matrix{Int}(0, 3)\n for p in rng, f in rng, s in rng\n if p != s != f != p && p + s + f == 12 && iseven(p)\n rst = [rst; p s f]\n end\n end\n return rst\nend\n\nfunction printsolutions(sol::Matrix{Int})\n println(\" Pol. Fire San.\")\n println(\" ---- ---- ----\")\n for row in 1:size(sol, 1)\n @printf(\"%2i | %4i%7i%7i\\n\", row, sol[row, :]...)\n end\nend\n\nprintsolutions(findsolution())\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nfun main(args: Array<String>) {\n println(\"Police Sanitation Fire\")\n println(\"------ ---------- ----\")\n var count = 0\n for (i in 2..6 step 2) {\n for (j in 1..7) {\n if (j == i) continue\n for (k in 1..7) {\n if (k == i || k == j) continue\n if (i + j + k != 12) continue\n println(\" $i $j $k\")\n count++\n }\n }\n }\n println(\"\\n$count valid combinations\")\n}\n", "language": "Kotlin" }, { "code": "print( \"Fire\", \"Police\", \"Sanitation\" )\nsol = 0\nfor f = 1, 7 do\n for p = 1, 7 do\n for s = 1, 7 do\n if s + p + f == 12 and p % 2 == 0 and f ~= p and f ~= s and p ~= s then\n print( f, p, s ); sol = sol + 1\n end\n end\n end\nend\nprint( string.format( \"\\n%d solutions found\", sol ) )\n", "language": "Lua" }, { "code": " NORMAL MODE IS INTEGER\n PRINT COMMENT $ POLICE SANITATION FIRE$\n THROUGH LOOP, FOR P=2, 2, P.G.7\n THROUGH LOOP, FOR S=1, 1, S.G.7\n THROUGH LOOP, FOR F=1, 1, F.G.7\n WHENEVER P.E.S .OR. P.E.F .OR. S.E.F, TRANSFER TO LOOP\n WHENEVER P+S+F .E. 12, PRINT FORMAT OCC, P, S, F\nLOOP CONTINUE\n VECTOR VALUES OCC = $I6,S2,I10,S2,I4*$\n END OF PROGRAM\n", "language": "MAD" }, { "code": "#determines if i, j, k are exclusive numbers\nexclusive_numbers := proc(i, j, k)\n\tif (i = j) or (i = k) or (j = k) then\n\t\treturn false;\n\tend if;\n\treturn true;\nend proc;\n\n#outputs all possible combinations of numbers that statisfy given conditions\ndepartment_numbers := proc()\n\tlocal i, j, k;\n\tprintf(\"Police\t\tSanitation\tFire\\n\");\n\tfor i to 7 do\n\t\tfor j to 7 do\n\t\t\tk := 12 - i - j;\n\t\t\tif (k <= 7) and (k >= 1) and (i mod 2 = 0) and exclusive_numbers(i,j,k) then\n\t\t\t\tprintf(\"%d\t\t%d\t\t%d\\n\", i, j, k);\n\t\t\tend if;\n\t\tend do;\n\tend do;\nend proc;\n\ndepartment_numbers();\n", "language": "Maple" }, { "code": "Select[Permutations[Range[7], {3}], Total[#] == 12 && EvenQ[First[#]] &]\n", "language": "Mathematica" }, { "code": "% Execute the functions\nclear all;close all;clc;\nsol = findsolution();\ndisp(table(sol(:, 1), sol(:, 2), sol(:, 3), 'VariableNames',{'Pol.','Fire','San.'}))\n\nfunction sol = findsolution()\n rng = 1:7;\n sol = [];\n for p = rng\n for f = rng\n for s = rng\n if p ~= s && s ~= f && f ~= p && p + s + f == 12 && mod(p, 2) == 0\n sol = [sol; p s f];\n end\n end\n end\n end\nend\n", "language": "MATLAB" }, { "code": ":- module department_numbers.\n:- interface.\n\n:- import_module io.\n:- pred main(io::di, io::uo) is cc_multi.\n\n:- implementation.\n\n:- import_module int, list, solutions, string.\n\nmain(!IO) :-\n io.print_line(\"P S F\", !IO),\n unsorted_aggregate(department_number, print_solution, !IO).\n\n:- pred print_solution({int, int, int}::in, io::di, io::uo) is det.\n\nprint_solution({P, S, F}, !IO) :-\n io.format(\"%d %d %d\\n\", [i(P), i(S), i(F)], !IO).\n\n:- pred department_number({int, int, int}::out) is nondet.\n\ndepartment_number({Police, Sanitation, Fire}) :-\n list.member(Police, [2, 4, 6]),\n list.member(Sanitation, 1 .. 7),\n list.member(Fire, 1 .. 7),\n Police \\= Sanitation,\n Police \\= Fire,\n Sanitation \\= Fire,\n Police + Sanitation + Fire = 12.\n", "language": "Mercury" }, { "code": "10 REM Department numbers\n20 PRINT \"POLICE SANITATION FIRE\"\n30 FOR P = 2 TO 7 STEP 2\n40 FOR S = 1 TO 7\n50 IF S = P THEN 120\n60 LET F = (12-P)-S\n70 IF F <= 0 THEN 120\n80 IF F > 7 THEN 120\n90 IF F = S THEN 120\n100 IF F = P THEN 120\n110 PRINT TAB(3); P; TAB(11); S; TAB(19); F\n120 NEXT S\n130 NEXT P\n140 END\n", "language": "Minimal-BASIC" }, { "code": "print \"Police Sanitation Fire\"\nprint \"------ ---------- ----\"\ncount = 0\nfor h in range(1, 3)\n i = h * 2\n for j in range(1, 7)\n if j != i then\n for k in range(1, 7)\n if k != i and k != j and i + j + k == 12 then\n print \" \" + i + \" \" + j + \" \" + k\n count += 1\n end if\n end for\n end if\n end for\nend for\nprint char(10) + count + \" valid combinations\"\n", "language": "MiniScript" }, { "code": "MODULE DepartmentNumbers;\nFROM Conversions IMPORT IntToStr;\nFROM Terminal IMPORT WriteString,WriteLn,ReadChar;\n\nPROCEDURE WriteInt(num : INTEGER);\nVAR str : ARRAY[0..16] OF CHAR;\nBEGIN\n IntToStr(num,str);\n WriteString(str);\nEND WriteInt;\n\nVAR i,j,k,count : INTEGER;\nBEGIN\n count:=0;\n\n WriteString(\"Police Sanitation Fire\");\n WriteLn;\n WriteString(\"------ ---------- ----\");\n WriteLn;\n\n FOR i:=2 TO 6 BY 2 DO\n FOR j:=1 TO 7 DO\n IF j=i THEN CONTINUE; END;\n FOR k:=1 TO 7 DO\n IF (k=i) OR (k=j) THEN CONTINUE; END;\n IF i+j+k # 12 THEN CONTINUE; END;\n WriteString(\" \");\n WriteInt(i);\n WriteString(\" \");\n WriteInt(j);\n WriteString(\" \");\n WriteInt(k);\n WriteLn;\n INC(count);\n END;\n END;\n END;\n\n WriteLn;\n WriteInt(count);\n WriteString(\" valid combinations\");\n WriteLn;\n\n ReadChar;\nEND DepartmentNumbers.\n", "language": "Modula-2" }, { "code": "type Solution = tuple[p, s, f: int]\n\niterator solutions(max, total: Positive): Solution =\n for p in countup(2, max, 2):\n for s in 1..max:\n if s == p: continue\n let f = total - p - s\n if f notin [p, s] and f in 1..max:\n yield (p, s, f)\n\necho \"P S F\"\nfor sol in solutions(7, 12):\n echo sol.p, \" \", sol.s, \" \", sol.f\n", "language": "Nim" }, { "code": "class Program {\n function : Main(args : String[]) ~ Nil {\n sol := 1;\n \"\\t\\tFIRE\\tPOLICE\\tSANITATION\"->PrintLine();\n for( f := 1; f < 8; f+=1; ) {\n for( p := 1; p < 8; p+=1; ) {\n for( s:= 1; s < 8; s+=1; ) {\n if( f <> p & f <> s & p <> s & ( p and 1 ) = 0 & ( f + s + p = 12 ) ) {\n \"SOLUTION #{$sol}: \\t{$f}\\t{$p}\\t{$s}\"->PrintLine();\n sol += 1;\n };\n };\n };\n };\n }\n}\n", "language": "Objeck" }, { "code": "(*\n * Caution: This is my first Ocaml program and anyone with Ocaml experience probably thinks it's horrible\n * So please don't use this as an example for \"good ocaml code\" see it more as\n * \"this is what my first lines of ocaml might look like\"\n *\n * The only reason im publishing this is that nobody has yet submitted an example in ocaml\n *)\n\n\n(* sfp is just a convenience to put a combination if sanitation (s) fire (f) and police (p) department in one record*)\ntype sfp = {s : int; f : int; p : int}\n\n(* Convenience Function to print a single sfp Record *)\nlet print_sfp e =\n Printf.printf \"%d %d %d\\n\" e.s e.f e.p\n\n(* Convenience Function to print a list of sfp Records*)\nlet print_sfp_list l =\n l |> List.iter print_sfp\n\n(* Computes sum of list l *)\nlet sum l = List.fold_left (+) 0 l\n\n(* checks if element e is in list l *)\nlet element_in_list e l =\n l |> List.find_map (fun x -> if x == e then Some(e) else None) <> None\n\n(* returns a list with only the unique elements of list l *)\nlet uniq l =\n let rec uniq_helper acc l =\n match l with\n | [] -> acc\n | h::t -> if element_in_list h t then uniq_helper acc t else uniq_helper (h::acc) t in\n uniq_helper [] l |> List.rev\n\n(* checks wheter or not list l only contains unique elements *)\nlet is_uniq l = uniq l = l\n\n\n(* computes all combinations for a given list of sanitation, fire & police departments\n im not very proud of this function...maybe someone with some experience can clean it up? ;)\n*)\nlet department_numbers sl fl pl =\n sl |> List.fold_left (fun aa s ->\n fl |> List.fold_left (fun fa f ->\n pl |> List.fold_left (fun pa p ->\n if\n sum [s;f;p] == 12 &&\n is_uniq [s;f;p] then\n {s = s; f = f; p = p} :: pa\n else\n pa) []\n |> List.append fa) []\n |> List.append aa) []\n\n\n(* \"main\" function *)\nlet _ =\n let s = [1;2;3;4;5;6;7] in\n let f = [1;2;3;4;5;6;7] in\n let p = [2;4;6] in\n let result = department_numbers s f p in\n print_endline \"S F P\";\n print_sfp_list result;\n", "language": "OCaml" }, { "code": "forstep(p=2,6,2, for(f=1,7, s=12-p-f; if(p!=f && p!=s && f!=s && s>0 && s<8, print(p\" \"f\" \"s))))\n", "language": "PARI-GP" }, { "code": "#!/usr/bin/perl\n\nmy @even_numbers;\n\nfor (1..7)\n{\n if ( $_ % 2 == 0)\n {\n push @even_numbers, $_;\n }\n}\n\t\nprint \"Police\\tFire\\tSanitation\\n\";\n\nforeach my $police_number (@even_numbers)\n{\n for my $fire_number (1..7)\n {\n for my $sanitation_number (1..7)\n {\n if ( $police_number + $fire_number + $sanitation_number == 12 &&\n $police_number != $fire_number &&\n $fire_number != $sanitation_number &&\n $sanitation_number != $police_number)\n {\n print \"$police_number\\t$fire_number\\t$sanitation_number\\n\";\n }\n }\n }\t\n}\n", "language": "Perl" }, { "code": "#!/usr/bin/perl\n\nuse strict; # Not necessary but considered good perl style\nuse warnings; # this one too\n\nprint \"Police\\t-\\tFire\\t-\\tSanitation\\n\";\nfor my $p ( 1..7 ) # Police Department\n{\n for my $f ( 1..7) # Fire Department\n {\n for my $s ( 1..7 ) # Sanitation Department\n {\n if ( $p % 2 == 0 && $p + $f + $s == 12 && $p != $f && $f != $s && $s != $p && $f != $s) # Check if the combination of numbers is valid\n {\n print \"$p\\t-\\t$f\\t-\\t$s\\n\";\n }\n }\n }\n}\n", "language": "Perl" }, { "code": "Police - Fire - Sanitation\n2 - 3 - 7\n2 - 4 - 6\n2 - 6 - 4\n2 - 7 - 3\n4 - 1 - 7\n4 - 2 - 6\n4 - 3 - 5\n4 - 5 - 3\n4 - 6 - 2\n4 - 7 - 1\n6 - 1 - 5\n6 - 2 - 4\n6 - 4 - 2\n6 - 5 - 1\n", "language": "Perl" }, { "code": "#!/usr/bin/perl\n\nuse strict; # https://rosettacode.org/wiki/Department_numbers\nuse warnings;\n\nprint \"P S F\\n\\n\";\n\n'246 1234567 1234567' =~\n /(.).* \\s .*?(?!\\1)(.).* \\s .*(?!\\1)(?!\\2)(.)\n (??{$1+$2+$3!=12})\n (?{ print \"@{^CAPTURE}\\n\" })(*FAIL)/x;\n", "language": "Perl" }, { "code": "#!/usr/bin/perl\n\nuse strict; # https://rosettacode.org/wiki/Department_numbers\nuse warnings;\n\nprint \"P S F\\n\\n\";\n\nprint tr/+/ /r, \"\\n\" for\n grep !/(\\d).*\\1/ && 12 == eval,\n glob '{2,4,6}' . '+{1,2,3,4,5,6,7}' x 2;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Police Sanitation Fire\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"------ ---------- ----\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">solutions</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">police</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">7</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">sanitation</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">7</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">sanitation</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">police</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">fire</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">-(</span><span style=\"color: #000000;\">police</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">sanitation</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">fire</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">fire</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">7</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">fire</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">police</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">fire</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">sanitation</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" %d %d %d\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">police</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">sanitation</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">fire</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">solutions</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n%d solutions found\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">solutions</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\n\n$valid = 0;\nfor ($police = 2 ; $police <= 6 ; $police += 2) {\n for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {\n $fire = 12 - $police - $sanitation;\n if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {\n echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;\n $valid++;\n }\n }\n}\necho $valid, ' valid combinations found.', PHP_EOL;\n", "language": "PHP" }, { "code": "import cp.\n\ngo ?=>\n N = 7,\n Sols = findall([P,S,F], department_numbers(N, P,S,F)),\n println(\" P S F\"),\n foreach([P,S,F] in Sols)\n printf(\"%2d %2d %2d\\n\",P,S,F)\n end,\n nl,\n printf(\"Number of solutions: %d\\n\", Sols.len),\n nl.\ngo => true.\n\ndepartment_numbers(N, Police,Sanitation,Fire) =>\n Police :: 1..N,\n Sanitation :: 1..N,\n Fire :: 1..N,\n all_different([Police,Sanitation,Fire]),\n Police + Sanitation + Fire #= 12,\n Police mod 2 #= 0,\n solve([Police,Sanitation,Fire]).\n", "language": "Picat" }, { "code": "go2 => department_numbers2(N) =>\n println(\" P S F\"),\n foreach(P in 1..N, P mod 2 == 0)\n foreach(S in 1..N, P != S)\n foreach(F in 1..N, F != P, F != S, P + S + F == 12)\n printf(\"%2d %2d %2d\\n\",P,S,F)\n end\n end\n end.\n", "language": "Picat" }, { "code": "import util.\n\ndepartment_numbers3(N) =>\n println(\"P S F\"),\n L = [[P.to_string,S.to_string,F.to_string] : P in 1..N, P mod 2 == 0,\n S in 1..N, P != S,\n F in 1..N,\n F != P, F != S, P + S + F == 12],\n println(map(L,join).join(\"\\n\")).\n", "language": "Picat" }, { "code": "go :-\n println(\"P F S\"),\n assign(Police, Fire, Sanitation),\n printf(\"%w %w %w\\n\", Police, Fire, Sanitation),\n fail,\n nl.\n\ndept(X) :- between(1, 7, X).\n\npolice(X) :- member(X, [2, 4, 6]).\nfire(X) :- dept(X).\nsan(X) :- dept(X).\n\nassign(A, B, C) :-\n police(A), fire(B), san(C),\n A != B, A != C, B != C,\n 12 is A + B + C.\n", "language": "Picat" }, { "code": "(de numbers NIL\n (co 'numbers\n (let N 7\n (for P N\n (for S N\n (for F N\n (yield (list P S F)) ) ) ) ) ) )\n(de departments NIL\n (use (L)\n (while (setq L (numbers))\n (or\n (bit? 1 (car L))\n (= (car L) (cadr L))\n (= (car L) (caddr L))\n (= (cadr L) (caddr L))\n (<> 12 (apply + L))\n (println L) ) ) ) )\n(departments)\n", "language": "PicoLisp" }, { "code": "(be departments (@Pol @Fire @San)\n (member @Pol (2 4 6))\n (for @Fire 1 7)\n (for @San 1 7)\n (different @Pol @Fire)\n (different @Pol @San)\n (different @Fire @San)\n (^ @\n (= 12\n (+ (-> @Pol) (-> @Fire) (-> @San)) ) ) )\n", "language": "PicoLisp" }, { "code": "100H: /* SHOW POSSIBLE DEPARTMENT NUMBERS FOR POLICE, SANITATION AND FIRE */\n /* THE POLICE DEPARTMENT NUMBER MUST BE EVEN, ALL DEPARTMENT NUMBERS */\n /* MUST BE IN THE RANGE 1 .. 7 AND THE NUMBERS MUST SUM TO 12 */\n\n /* CP/M SYSTEM CALL AND I/O ROUTINES */\n BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;\n PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;\n PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;\n PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;\n PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */\n DECLARE N ADDRESS;\n DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;\n V = N;\n W = LAST( N$STR );\n N$STR( W ) = '$';\n N$STR( W := W - 1 ) = '0' + ( V MOD 10 );\n DO WHILE( ( V := V / 10 ) > 0 );\n N$STR( W := W - 1 ) = '0' + ( V MOD 10 );\n END;\n CALL PR$STRING( .N$STR( W ) );\n END PR$NUMBER;\n\n /* TASK */\n DECLARE MAX$DEPARTMENT$NUMBER LITERALLY '7';\n DECLARE DEPARTMENT$SUM LITERALLY '12';\n DECLARE ( POLICE, SANITATION, FIRE ) BYTE;\n\n CALL PR$STRING( .'POLICE SANITATION FIRE$' );\n CALL PR$NL;\n\n DO POLICE = 2 TO MAX$DEPARTMENT$NUMBER BY 2;\n DO SANITATION = 1 TO MAX$DEPARTMENT$NUMBER;\n IF SANITATION <> POLICE THEN DO;\n FIRE = ( DEPARTMENT$SUM - POLICE ) - SANITATION;\n IF FIRE <= MAX$DEPARTMENT$NUMBER\n AND FIRE <> SANITATION\n AND FIRE <> POLICE\n THEN DO;\n CALL PR$STRING( .' $' ); CALL PR$NUMBER( POLICE );\n CALL PR$STRING( .' $' ); CALL PR$NUMBER( SANITATION );\n CALL PR$STRING( .' $' ); CALL PR$NUMBER( FIRE );\n CALL PR$NL;\n END;\n END;\n END;\n END;\n\nEOF\n", "language": "PL-M" }, { "code": "dept(X) :- between(1, 7, X).\n\npolice(X) :- member(X, [2, 4, 6]).\nfire(X) :- dept(X).\nsan(X) :- dept(X).\n\nassign(A, B, C) :-\n police(A), fire(B), san(C),\n A =\\= B, A =\\= C, B =\\= C,\n 12 is A + B + C.\n\nmain :-\n write(\"P F S\"), nl,\n forall(assign(Police, Fire, Sanitation), format(\"~w ~w ~w~n\", [Police, Fire, Sanitation])),\n halt.\n\n?- main.\n", "language": "Prolog" }, { "code": "OpenConsole()\nPrintN(\"--police-- --sanitation-- --fire--\")\n\nFor police = 2 To 7 Step 2\n For fire = 1 To 7\n If fire = police:\n Continue\n EndIf\n sanitation = 12 - police - fire\n If sanitation = fire Or sanitation = police: Continue : EndIf\n If sanitation >= 1 And sanitation <= 7:\n PrintN(\" \" + Str(police) + #TAB$ + #TAB$ + Str(fire) + #TAB$ + #TAB$ + Str(sanitation))\n EndIf\n Next fire\nNext police\n\nInput()\nCloseConsole()\n", "language": "PureBasic" }, { "code": "from itertools import permutations\n\ndef solve():\n c, p, f, s = \"\\\\,Police,Fire,Sanitation\".split(',')\n print(f\"{c:>3} {p:^6} {f:^4} {s:^10}\")\n c = 1\n for p, f, s in permutations(range(1, 8), r=3):\n if p + s + f == 12 and p % 2 == 0:\n print(f\"{c:>3}: {p:^6} {f:^4} {s:^10}\")\n c += 1\n\nif __name__ == '__main__':\n solve()\n", "language": "Python" }, { "code": "'''Department numbers'''\n\nfrom itertools import (chain)\nfrom operator import (ne)\n\n\n# options :: Int -> Int -> Int -> [(Int, Int, Int)]\ndef options(lo, hi, total):\n '''Eligible integer triples.'''\n ds = enumFromTo(lo)(hi)\n return bind(filter(even, ds))(\n lambda x: bind(filter(curry(ne)(x), ds))(\n lambda y: bind([total - (x + y)])(\n lambda z: [(x, y, z)] if (\n z != y and lo <= z <= hi\n ) else []\n )\n )\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test'''\n\n xs = options(1, 7, 12)\n print(('Police', 'Sanitation', 'Fire'))\n for tpl in xs:\n print(tpl)\n print('\\nNo. of options: ' + str(len(xs)))\n\n\n# GENERIC ABSTRACTIONS ------------------------------------\n\n# bind (>>=) :: [a] -> (a -> [b]) -> [b]\ndef bind(xs):\n '''List monad injection operator.\n Two computations sequentially composed,\n with any value produced by the first\n passed as an argument to the second.'''\n return lambda f: list(\n chain.from_iterable(\n map(f, xs)\n )\n )\n\n\n# curry :: ((a, b) -> c) -> a -> b -> c\ndef curry(f):\n '''A curried function derived\n from an uncurried function.'''\n return lambda a: lambda b: f(a, b)\n\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: list(range(m, 1 + n))\n\n\n# even :: Int -> Bool\ndef even(x):\n '''True if x is an integer\n multiple of two.'''\n return 0 == x % 2\n\n\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "'''Department numbers'''\n\nfrom operator import ne\n\n\n# options :: Int -> Int -> Int -> [(Int, Int, Int)]\ndef options(lo, hi, total):\n '''Eligible triples.'''\n ds = enumFromTo(lo)(hi)\n return [\n (x, y, z)\n for x in filter(even, ds)\n for y in filter(curry(ne)(x), ds)\n for z in [total - (x + y)]\n if y != z and lo <= z <= hi\n ]\n\n\n# Or with less tightly-constrained generation,\n# and more winnowing work downstream:\n\n# options2 :: Int -> Int -> Int -> [(Int, Int, Int)]\ndef options2(lo, hi, total):\n '''Eligible triples.'''\n ds = enumFromTo(lo)(hi)\n return [\n (x, y, z)\n for x in ds\n for y in ds\n for z in [total - (x + y)]\n if even(x) and y not in [x, z] and lo <= z <= hi\n ]\n\n\n# GENERIC -------------------------------------------------\n\n\n# curry :: ((a, b) -> c) -> a -> b -> c\ndef curry(f):\n '''A curried function derived\n from an uncurried function.'''\n return lambda a: lambda b: f(a, b)\n\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: list(range(m, 1 + n))\n\n\n# even :: Int -> Bool\ndef even(x):\n '''True if x is an integer\n multiple of two.'''\n return 0 == x % 2\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single string derived by the intercalation\n of a list of strings with the newline character.'''\n return '\\n'.join(xs)\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test'''\n\n xs = options(1, 7, 12)\n print(('Police', 'Sanitation', 'Fire'))\n print(unlines(map(str, xs)))\n print('\\nNo. of options: ' + str(len(xs)))\n\n\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "# We start with the Police Department.\n# Range is the start, stop, and step. This returns only even numbers.\nfor p in range(2, 7, 2):\n #Next, the Sanitation Department. A simple range.\n for s in range(1, 7):\n # And now the Fire Department. After determining the Police and Fire\n # numbers we just have to subtract those from 12 to get the FD number.\n f = 12 - p -s\n if s >= f:\n break\n elif f > 7:\n continue\n print(\"Police: \", p, \" Sanitation:\", s, \" Fire: \", f)\n print(\"Police: \", p, \" Sanitation:\", f, \" Fire: \", s)\n", "language": "Python" }, { "code": "import constraint\n\ndepts = ( 'police', 'sanitation', 'fire' )\n\np = constraint.Problem()\n\nfor var in depts:\n p.addVariable(var, range(1,8))\n\np.addConstraint(constraint.AllDifferentConstraint())\np.addConstraint(lambda *vars: sum(vars)==12, depts)\np.addConstraint(lambda p: p%2==0, ('police',))\n\nfor s in p.getSolutions():\n print(s)\n", "language": "Python" }, { "code": "PRINT \"--police-- --sanitation-- --fire--\"\n\nFOR police = 2 TO 7 STEP 2\n FOR fire = 1 TO 7\n IF fire = police THEN GOTO cont\n sanitation = 12 - police - fire\n IF sanitation = fire OR sanitation = police THEN GOTO cont\n IF sanitation >= 1 AND sanitation <= 7 THEN\n PRINT USING \" # # #\"; police; fire; sanitation\n END IF\ncont:\n NEXT fire\nNEXT police\n", "language": "QBasic" }, { "code": " [ 2dup = iff\n [ 2drop drop ] done\n dip over swap over = iff\n [ 2drop drop ] done\n rot echo sp\n swap echo sp\n echo cr ] is fire ( pol san fir --> )\n\n [ 2dup = iff 2drop done\n 12 over -\n dip over swap -\n dup 1 < iff\n [ 2drop drop ] done\n dup 7 > iff\n [ 2drop drop ] done\n fire ] is sanitation ( pol san --> )\n\n [ 7 times\n [ dup\n i^ 1+ sanitation ]\n drop ] is police ( pol --> )\n\n [ cr ' [ 2 4 6 ]\n witheach police ] is departments ( --> )\n\n departments\n", "language": "Quackery" }, { "code": "10 REM Department numbers\n20 PRINT \"POLICE SANITATION FIRE\"\n30 FOR P = 2 TO 7 STEP 2\n40 FOR S = 1 TO 7\n50 IF S = P THEN 80\n60 LET F = (12-P)-S\n70 IF F > 0 AND F <= 7 AND F <> S AND F <> P THEN PRINT \" \";P;\" \";S;\" \";F\n80 NEXT S\n90 NEXT P\n100 END\n", "language": "Quite-BASIC" }, { "code": "allPermutations <- setNames(expand.grid(seq(2, 7, by = 2), 1:7, 1:7), c(\"Police\", \"Sanitation\", \"Fire\"))\nsolution <- allPermutations[which(rowSums(allPermutations)==12 & apply(allPermutations, 1, function(x) !any(duplicated(x)))),]\nsolution <- solution[order(solution$Police, solution$Sanitation),]\nrow.names(solution) <- paste0(\"Solution #\", seq_len(nrow(solution)), \":\")\nprint(solution)\n", "language": "R" }, { "code": "#lang racket\n(cons '(police fire sanitation)\n (filter (λ (pfs) (and (not (check-duplicates pfs))\n (= 12 (apply + pfs))\n pfs))\n (cartesian-product (range 2 8 2) (range 1 8) (range 1 8))))\n", "language": "Racket" }, { "code": "for (1..7).combinations(3).grep(*.sum == 12) {\n for .permutations\\ .grep(*.[0] %% 2) {\n say <police fire sanitation> Z=> .list;\n }\n}\n", "language": "Raku" }, { "code": "/*REXX program finds/displays all possible variants of (3) department numbering puzzle.*/\nsay 'police sanitation fire' /*display simple title for the output*/\nsay '══════ ══════════ ════' /* \" head separator \" \" \" */\n#=0 /*number of solutions found (so far). */\n do p=1 for 7; if p//2 then iterate /*try numbers for the police department*/\n do s=1 for 7; if s==p then iterate /* \" \" \" \" fire \" */\n do f=1 for 7; if f==s then iterate /* \" \" \" \" sanitation \" */\n if p + s + f \\== 12 then iterate /*check if sum of department nums ¬= 12*/\n #= # + 1 /*bump count of the number of solutions*/\n say center(p,6) center(s,10) center(f,4) /*display one possible solution. */\n end /*s*/\n end /*f*/\n end /*p*/\n\nsay '══════ ══════════ ════' /* \" head separator \" \" \" */\nsay /*stick a fork in it, we're all done. */\nsay # ' solutions found.' /*also, show the # of solutions found. */\n", "language": "REXX" }, { "code": "sanitation= 0\nsee \"police fire sanitation\" + nl\n\nfor police = 2 to 7 step 2\n for fire = 1 to 7\n if fire = police\n loop\n ok\n sanitation = 12 - police - fire\n if sanitation = fire or sanitation = police\n loop\n ok\n if sanitation >= 1 and sanitation <= 7\n see \" \" + police + \" \" + fire + \" \" + sanitation + nl\n ok\n next\nnext\n", "language": "Ring" }, { "code": "(1..7).to_a.permutation(3){|p| puts p.join if p.first.even? && p.sum == 12 }\n", "language": "Ruby" }, { "code": "print \"police fire sanitation\"\n\nfor police = 2 to 7 step 2\n for fire = 1 to 7\n if fire = police then [cont]\n sanitation = (12-police)-fire\n if sanitation <= 0 or sanitation > 7 or sanitation = fire or sanitation = police then [cont]\n print \" \"; police; chr$(9); fire; chr$(9); sanitation\n[cont]\n next fire\nnext police\n", "language": "Run-BASIC" }, { "code": "extern crate num_iter;\nfn main() {\n println!(\"Police Sanitation Fire\");\n println!(\"----------------------\");\n\n for police in num_iter::range_step(2, 7, 2) {\n for sanitation in 1..8 {\n for fire in 1..8 {\n if police != sanitation\n && sanitation != fire\n && fire != police\n && police + fire + sanitation == 12\n {\n println!(\"{:6}{:11}{:4}\", police, sanitation, fire);\n }\n }\n }\n }\n}\n", "language": "Rust" }, { "code": "val depts = {\n (1 to 7).permutations.map{ n => (n(0),n(1),n(2)) }.toList.distinct // All permutations of possible department numbers\n .filter{ n => n._1 % 2 == 0 } // Keep only even numbers favored by Police Chief\n .filter{ n => n._1 + n._2 + n._3 == 12 } // Keep only numbers that add to 12\n}\n\n{\nprintln( \"(Police, Sanitation, Fire)\")\nprintln( depts.mkString(\"\\n\") )\n}\n", "language": "Scala" }, { "code": "@(1..7)->combinations(3, {|*a|\n a.sum == 12 || next\n a.permutations {|*b|\n b[0].is_even || next\n say (%w(police fire sanitation) ~Z b -> join(\" \"))\n }\n})\n", "language": "Sidef" }, { "code": "10 PRINT \"POLICE SANITATION FIRE\"\n20 FOR P=2 TO 7 STEP 2\n30 FOR S=1 TO 7\n40 IF S=P THEN NEXT S\n50 LET F=(12-P)-S\n60 IF F>0 AND F<=7 AND F<>S AND F<>P THEN PRINT \" \";P;\" \";S;\" \";F\n70 NEXT S\n80 NEXT P\n", "language": "Sinclair-ZX81-BASIC" }, { "code": "let res = [2, 4, 6].map({x in\n return (1...7)\n .filter({ $0 != x })\n .map({y -> (Int, Int, Int)? in\n let z = 12 - (x + y)\n\n guard y != z && 1 <= z && z <= 7 else {\n return nil\n }\n\n return (x, y, z)\n }).compactMap({ $0 })\n}).flatMap({ $0 })\n\nfor result in res {\n print(result)\n}\n", "language": "Swift" }, { "code": "var res = [(Int, Int, Int)]()\n\nfor x in [2, 4, 6] {\n for y in 1...7 where x != y {\n let z = 12 - (x + y)\n\n guard y != z && 1 <= z && z <= 7 else {\n continue\n }\n\n res.append((x, y, z))\n }\n}\n\nfor result in res {\n print(result)\n}\n", "language": "Swift" }, { "code": "# Procedure named \"..\" returns list of integers from 1 to max.\nproc .. max {\n for {set i 1} {$i <= $max} {incr i} {\n lappend l $i\n }\n return $l\n}\n\n# Procedure named \"anyEqual\" returns true if any elements are equal,\n# false otherwise.\nproc anyEqual l {\n if {[llength [lsort -unique $l]] != [llength $l]} {\n return 1\n }\n return 0\n}\n\n# Procedure named \"odd\" tells whether a value is odd or not.\nproc odd n {\n expr $n %2 != 0\n}\n\n\n# Procedure named \"sum\" sums its parameters.\nproc sum args {\n expr [join $args +]\n}\n\n\n# Create lists of candidate numbers using proc \"..\"\nset sanitation [.. 7]\nset fire $sanitation\n# Filter even numbers for police stations (remove odd ones).\nset police [lmap e $sanitation {\n if [odd $e] continue\n set e\n}]\n\n\n# Try all combinations and display acceptable ones.\nset valid 0\nforeach p $police {\n foreach s $sanitation {\n foreach f $fire {\n # Check for equal elements in list.\n if [anyEqual [list $p $s $f]] continue\n # Check for sum of list elements.\n if {[sum $p $s $f] != 12} continue\n puts \"$p $s $f\"\n incr valid\n }\n }\n}\nputs \"$valid valid combinations found.\"\n", "language": "Tcl" }, { "code": "set valid 0\nfor {set police 2} {$police <= 6} {incr police 2} {\n for {set sanitation 1} {$sanitation <= 7} {incr sanitation} {\n if {$police == $sanitation} continue\n for {set fire 1} {$fire <= 7} {incr fire} {\n if {$police == $fire || $sanitation == $fire} continue\n if {[expr $police + $sanitation + $fire] != 12} continue\n puts \"$police $sanitation $fire\"\n incr valid\n }\n }\n}\nputs \"$valid valid combinations found.\"\n", "language": "Tcl" }, { "code": "set min 1\nset max 7\nset valid 0\nfor {set police $min} {$police <= $max} {incr police} {\n if {[expr $police % 2] == 1} continue ;# filter even numbers for police\n for {set sanitation $min} {$sanitation <= $max} {incr sanitation} {\n if {$police == $sanitation} continue\n for {set fire $min} {$fire <= $max} {incr fire} {\n if {$police == $fire || $sanitation == $fire} continue\n if {[expr $police + $sanitation + $fire] != 12} continue\n puts \"$police $sanitation $fire\"\n incr valid\n }\n }\n}\n\nputs \"$valid valid combinations found.\"\n", "language": "Tcl" }, { "code": "# Procedure named \"..\" returns list of integers from 1 to max.\nproc .. max {\n for {set i 1} {$i <= $max} {incr i} {\n lappend l $i\n }\n return $l\n}\n\n\n# Procedure named \"...\" returns list of n lists of integers from 1 to max.\nproc ... {max n} {\n foreach i [.. $n] {\n lappend result [.. $max]\n }\n return $result\n}\n\n# Procedure named \"crossProduct\" returns cross product of lists\nproc crossProduct {listOfLists} {\n set result [list [list]]\n foreach factor $listOfLists {\n set newResult {}\n foreach combination $result {\n foreach elt $factor {\n lappend newResult [linsert $combination end $elt]\n }\n }\n set result $newResult\n }\n return $result\n}\n\n# Procedure named \"filter\" filters list elements by using a\n# condition λ (lambda) expression\nproc filter {l condition} {\n return [lmap el $l {\n if {![apply $condition $el]} continue\n set el\n }]\n}\n\n# Here the fun using lambda expressions begins. The following is the main program.\n\n# Set λ expressions\nset λPoliceEven {_ {expr [lindex $_ 0] % 2 == 0}}\nset λNoEquals {_ {expr [llength [lsort -unique $_]] == [llength $_]}}\nset λSumIs12 {_ {expr [join $_ +] == 12}}\n\n# Create all combinations and filter acceptable ones\nset numbersOk [filter [filter [filter [crossProduct [... 7 3]] ${λPoliceEven}] ${λSumIs12}] ${λNoEquals}]\nputs [join $numbersOk \\n]\nputs \"[llength $numbersOk] valid combinations found.\"\n", "language": "Tcl" }, { "code": " PRINT \"Police Sanitation Fire\"\n PRINT \"------|----------|----\"\n10 LET P = P + 2\n LET S = 0\n20 LET S = S + 1\n LET F = 0\n IF S = P THEN GOTO 20\n30 LET F = F + 1\n IF S = F THEN GOTO 30\n IF F = P THEN GOTO 30\n IF P + S + F = 12 THEN PRINT \" \",P,\" \", S,\" \", F\n IF F < 7 THEN GOTO 30\n IF S < 7 THEN GOTO 20\n IF P < 6 THEN GOTO 10\n", "language": "Tiny-BASIC" }, { "code": "#lang transd\n\nMainModule : {\n _start: (lambda\n (lout \"Police | Sanit. | Fire\")\n (for i in Range(1 8) where (not (mod i 2)) do\n (for j in Range(1 8) where (neq i j) do\n (for k in Range(1 8) where (and (neq i k) (neq j k)) do\n (if (eq (+ i j k) 12) (lout i \" \" j \" \" k)))))\n )\n}\n", "language": "Transd" }, { "code": "// Department numbers\nconsole.log(`POLICE SANITATION FIRE`);\nlet f: number;\nfor (var p = 2; p <= 7; p += 2) {\n for (var s = 1; s <= 7; s++) {\n if (s != p) {\n f = (12 - p) - s;\n if ((f > 0) && (f <= 7) && (f != s) && (f != p))\n console.log(` ${p} ${s} ${f}`);\n }\n }\n}\n", "language": "TypeScript" }, { "code": "function main {\n set -- Police Sanitation Fire\n typeset -i pw=${#1} sw=${#2} fw=${#3}\n printf '%s' \"$1\"\n shift\n printf '\\t%s' \"$@\"\n printf '\\n'\n for (( p=2; p<8; p+=2 )); do\n for (( s=1; s<8; ++s )); do\n if (( s == p )); then\n continue\n fi\n (( f = 12 - p - s ))\n if (( f == s || f == p || f < 1 || f > 7 )); then\n continue\n fi\n printf \"%${pw}d\\t%${sw}d\\t%${fw}d\\n\" \"$p\" \"$s\" \"$f\"\n done\n done\n}\n\nmain \"$@\"\n", "language": "UNIX-Shell" }, { "code": "fn main() {\n println(\"Police Sanitation Fire\")\n println(\"------ ---------- ----\")\n mut count := 0\n for i := 2; i < 7; i += 2 {\n for j in 1..8 {\n if j == i { continue }\n for k in 1..8 {\n if k == i || k == j { continue }\n if i + j + k != 12 { continue }\n println(\" $i $j $k\")\n count++\n }\n }\n }\n println(\"\\n$count valid combinations\")\n}\n", "language": "V-(Vlang)" }, { "code": "Module Module1\n\n Sub Main()\n For p = 2 To 7 Step 2\n For s = 1 To 7\n Dim f = 12 - p - s\n If s >= f Then\n Exit For\n End If\n If f > 7 Then\n Continue For\n End If\n If s = p OrElse f = p Then\n Continue For 'not even necessary\n End If\n Console.WriteLine($\"Police:{p}, Sanitation:{s}, Fire:{f}\")\n Console.WriteLine($\"Police:{p}, Sanitation:{f}, Fire:{s}\")\n Next\n Next\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "10 P=2\n20 S=1\n30 F=1\n40 #=0<((P=S)+(P=F)+(S=F)+(P+S+F=12=0))*110\n50 ?=P\n60 $=32\n70 ?=S\n80 $=32\n90 ?=F\n100 ?=\"\"\n110 F=F+1\n120 #=F<8*40\n130 S=S+1\n140 #=S<8*30\n150 P=P+2\n160 #=P<8*20\n", "language": "VTL-2" }, { "code": "System.print(\"Police Sanitation Fire\")\nSystem.print(\"------ ---------- ----\")\nvar count = 0\nfor (h in 1..3) {\n var i = h * 2\n for (j in 1..7) {\n if (j != i) {\n for (k in 1..7) {\n if ((k != i && k != j) && (i + j + k == 12) ) {\n System.print(\" %(i) %(j) %(k)\")\n count = count + 1\n }\n }\n }\n }\n}\nSystem.print(\"\\n%(count) valid combinations\")\n", "language": "Wren" }, { "code": "PROGRAM\t\"Depar/num\"\n\nDECLARE FUNCTION Entry ()\n\nFUNCTION Entry ()\n PRINT \"police sanitation fire\"\n\n FOR police = 2 TO 7 STEP 2\n FOR fire = 1 TO 7\n IF fire = police THEN GOTO cont\n sanitation = 12 - police - fire\n IF sanitation = fire OR sanitation = police THEN GOTO cont\n IF sanitation >= 1 AND sanitation <= 7 THEN\n PRINT TAB(3); police; TAB(13); fire; TAB(22); sanitation\n END IF\ncont:\n NEXT fire\n NEXT police\nEND FUNCTION\nEND PROGRAM\n", "language": "XBasic" }, { "code": "\\Department numbers\ncode CrLf=9, IntIn=10, IntOut=11, Text=12;\ninteger P, S, F;\n\nbegin\nText(0, \"POLICE SANITATION FIRE\");\nCrLf(0);\nP:= 2;\nwhile P <= 7 do\n begin\n for S:= 1, 7 do\n if S # P then\n begin\n F:= (12 - P) - S;\n if (F > 0) & (F <= 7) & (F # S) & (F # P) then\n begin\n Text(0, \" \"); IntOut(0, P);\n Text(0, \" \"); IntOut(0, S);\n Text(0, \" \"); IntOut(0, F);\n CrLf(0)\n end\n end;\n P:= P + 2\n end;\nend\n", "language": "XPL0" }, { "code": "print \"--police-- --sanitation-- --fire--\"\n\nfor police = 2 to 7 step 2\n for fire = 1 to 7\n if fire = police continue\n sanitation = 12 - police - fire\n if sanitation = fire or sanitation = police continue\n if sanitation >= 1 and sanitation <= 7 print police using \"######\", fire using \"############\", sanitation using \"###########\"\n next fire\nnext police\n", "language": "Yabasic" }, { "code": "const std = @import(\"std\");\n", "language": "Zig" }, { "code": "pub fn main() !void {\n const stdout = std.io.getStdOut().writer();\n\n try stdout.writeAll(\"Police Sanitation Fire\\n\");\n try stdout.writeAll(\"------ ---------- ----\\n\");\n\n var p: usize = 2;\n while (p <= 7) : (p += 2)\n for (1..7 + 1) |s|\n for (1..7 + 1) |f|\n if (p != s and s != f and f != p and p + f + s == 12) {\n try stdout.print(\" {d} {d} {d}\\n\", .{ p, s, f });\n };\n}\n", "language": "Zig" }, { "code": "const std = @import(\"std\");\n\npub fn main() !void {\n const stdout = std.io.getStdOut().writer();\n\n try stdout.writeAll(\"Police Sanitation Fire\\n\");\n try stdout.writeAll(\"------ ---------- ----\\n\");\n\n var it = SolutionIterator.init();\n while (it.next()) |solution| {\n try stdout.print(\n \" {d} {d} {d}\\n\",\n .{ solution.police, solution.sanitation, solution.fire },\n );\n }\n}\n\n/// 3 bit unsigned (u3) limits 0 <= department <= 7\nconst Departments = packed struct {\n police: u3,\n sanitation: u3,\n fire: u3,\n};\n\nconst DepartmentsUnion = packed union {\n departments: Departments,\n together: u9,\n};\n\nconst SolutionIterator = struct {\n // police is initialized to one as adding one is the first operation in next()\n // with the result .police == 2 (an even number) on the first pass.\n u: DepartmentsUnion = .{ .departments = .{ .police = 1, .sanitation = 1, .fire = 1 } },\n\n /// init() returns an initialised structure.\n /// Using init() is a common Zig pattern.\n fn init() SolutionIterator {\n return SolutionIterator{};\n }\n\n fn next(self: *SolutionIterator) ?Departments {\n if (self.u.together == 0) return null; // already completed\n\n while (true) {\n const ov = @addWithOverflow(self.u.together, 1);\n if (ov[1] == 1) {\n self.u.together = 0;\n return null; // overflowed, completed\n } else {\n self.u.together = ov[0];\n // None can be zero\n if (self.u.departments.police == 0) self.u.departments.police = 2; // even\n if (self.u.departments.sanitation == 0) self.u.departments.sanitation = 1;\n if (self.u.departments.fire == 0) self.u.departments.fire = 1;\n // Police must be even\n if (self.u.departments.police & 1 == 1)\n continue;\n // No two can be the same\n if (self.u.departments.police == self.u.departments.sanitation) continue;\n if (self.u.departments.sanitation == self.u.departments.fire) continue;\n if (self.u.departments.fire == self.u.departments.police) continue;\n // Must total twelve (maximum sum 7 + 7 + 7 = 21 requires 5 bits)\n const p = @as(u5, self.u.departments.police);\n const s = @as(u5, self.u.departments.sanitation);\n const f = @as(u5, self.u.departments.fire);\n if (p + s + f != 12)\n continue;\n\n return self.u.departments;\n }\n }\n }\n};\n", "language": "Zig" }, { "code": "Utils.Helpers.pickNFrom(3,[1..7].walk()) // 35 combos\n.filter(fcn(numbers){ numbers.sum(0)==12 }) // which all sum to 12 (==5)\n.println();\n", "language": "Zkl" }, { "code": "println(\"Police Fire Sanitation\");\nforeach p,f,s in ([2..7,2], [1..7], [1..7])\n { if((p!=s!=f) and p+f+s==12) println(p,\"\\t\",f,\"\\t\",s) }\n", "language": "Zkl" } ]
Department-numbers
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Descending_primes\n", "language": "00-META" }, { "code": "Generate and show all primes with strictly descending decimal digits.\n\n;See also\n;* [[oeis:A052014|OEIS:A052014 - Primes with distinct digits in descending order]]\n\n;Related:\n*[[Ascending primes]]\n\n\n", "language": "00-TASK" }, { "code": "F is_prime(p)\n I p < 2 | p % 2 == 0\n R p == 2\n L(i) (3 .. Int(sqrt(p))).step(2)\n I p % i == 0\n R 0B\n R 1B\n\nV c = 0\nV ps = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nV nxt = [0] * 128\n\nL\n V nc = 0\n L(a) ps\n I is_prime(a)\n c++\n print(‘#8’.format(a), end' I c % 5 == 0 {\"\\n\"} E ‘ ’)\n V b = a * 10\n V l = a % 10 + b\n b++\n L b < l\n nxt[nc] = b\n nc++\n b++\n\n I nc > 1\n ps = nxt[0 .< nc]\n E\n L.break\n\nprint(\"\\n\"c‘ descending primes found’)\n", "language": "11l" }, { "code": "F is_prime(p)\n I p < 2 | p % 2 == 0\n R p == 2\n L(i) (3 .. Int(sqrt(p))).step(2)\n I p % i == 0\n R 0B\n R 1B\n\n[Int] descending_primes\n\nL(n) 1 .< 2 ^ 9\n V s = ‘’\n L(i) (8 .. 0).step(-1)\n I n [&] (1 << i) != 0\n s ‘’= String(i + 1)\n I is_prime(Int(s))\n descending_primes.append(Int(s))\n\nL(n) sorted(descending_primes)\n print(‘#8’.format(n), end' I (L.index + 1) % 5 == 0 {\"\\n\"} E ‘ ’)\n\nprint(\"\\n\"descending_primes.len‘ descending primes found’)\n", "language": "11l" }, { "code": "BEGIN # find all primes with strictly decreasing digits #\n PR read \"primes.incl.a68\" PR # include prime utilities #\n PR read \"rows.incl.a68\" PR # include array utilities #\n [ 1 : 512 ]INT primes; # there will be at most 512 (2^9) primes #\n INT p count := 0; # number of primes found so far #\n FOR d1 FROM 0 TO 1 DO\n INT n1 = IF d1 = 1 THEN 9 ELSE 0 FI;\n FOR d2 FROM 0 TO 1 DO\n INT n2 = IF d2 = 1 THEN ( n1 * 10 ) + 8 ELSE n1 FI;\n FOR d3 FROM 0 TO 1 DO\n INT n3 = IF d3 = 1 THEN ( n2 * 10 ) + 7 ELSE n2 FI;\n FOR d4 FROM 0 TO 1 DO\n INT n4 = IF d4 = 1 THEN ( n3 * 10 ) + 6 ELSE n3 FI;\n FOR d5 FROM 0 TO 1 DO\n INT n5 = IF d5 = 1 THEN ( n4 * 10 ) + 5 ELSE n4 FI;\n FOR d6 FROM 0 TO 1 DO\n INT n6 = IF d6 = 1 THEN ( n5 * 10 ) + 4 ELSE n5 FI;\n FOR d7 FROM 0 TO 1 DO\n INT n7 = IF d7 = 1 THEN ( n6 * 10 ) + 3 ELSE n6 FI;\n FOR d8 FROM 0 TO 1 DO\n INT n8 = IF d8 = 1 THEN ( n7 * 10 ) + 2 ELSE n7 FI;\n FOR d9 FROM 0 TO 1 DO\n INT n9 = IF d9 = 1 THEN ( n8 * 10 ) + 1 ELSE n8 FI;\n IF n9 > 0 THEN\n IF is probably prime( n9 ) THEN\n # have a prime with strictly descending digits #\n primes[ p count +:= 1 ] := n9\n FI\n FI\n OD\n OD\n OD\n OD\n OD\n OD\n OD\n OD\n OD;\n QUICKSORT primes FROMELEMENT 1 TOELEMENT p count; # sort the primes #\n # display the primes #\n FOR i TO p count DO\n print( ( \" \", whole( primes[ i ], -8 ) ) );\n IF i MOD 10 = 0 THEN print( ( newline ) ) FI\n OD\nEND\n", "language": "ALGOL-68" }, { "code": "begin % find all primes with strictly descending digits - translation of Lua %\n\n % quicksorts v, the bounds of v must be specified in lb and ub %\n procedure quicksort ( integer array v( * )\n ; integer value lb, ub\n ) ;\n if ub > lb then begin\n % more than one element, so must sort %\n integer left, right, pivot;\n left := lb;\n right := ub;\n % choosing the middle element of the array as the pivot %\n pivot := v( left + ( ( right + 1 ) - left ) div 2 );\n while begin\n while left <= ub and v( left ) < pivot do left := left + 1;\n while right >= lb and v( right ) > pivot do right := right - 1;\n left <= right\n end do begin\n integer swap;\n swap := v( left );\n v( left ) := v( right );\n v( right ) := swap;\n left := left + 1;\n right := right - 1\n end while_left_le_right ;\n quicksort( v, lb, right );\n quicksort( v, left, ub )\n end quicksort ;\n\n % returns true if n is prime, false otherwise %\n logical procedure is_prime( integer value n ) ;\n if n < 2 then false\n else if n rem 2 = 0 then n = 2\n else if n rem 3 = 0 then n = 3\n else begin\n logical prime; prime := true;\n for f := 5 step 6 until entier( sqrt( n ) ) do begin\n if n rem f = 0 or n rem ( f + 2 ) = 0 then begin\n prime := false;\n goto done\n end if_n_rem_f_eq_0_or_n_rem_f_plus_2_eq_0\n end for_f;\ndone: prime\n end is_prime ;\n\n % increments n and also returns its new value %\n integer procedure inc ( integer value result n ) ; begin n := n + 1; n end;\n\n % sets primes to the list of descending primes and lenPrimes to the %\n % number of descending primes - primes must be big enough, e.g. have 511 %\n % elements %\n procedure descending_primes ( integer array primes ( * )\n ; integer result lenPrimes\n ) ;\n begin\n integer array digits ( 1 :: 9 );\n integer array candidates ( 1 :: 6000 );\n integer lenCandidates;\n candidates( 1 ) := 0;\n lenCandidates := 1;\n lenPrimes := 0;\n for i := 1 until 9 do digits( i ) := 10 - i;\n for i := 1 until 9 do begin\n for j := 1 until lenCandidates do begin\n integer cValue; cValue := candidates( j ) * 10 + digits( i );\n if is_prime( cValue ) then primes( inc( lenPrimes ) ) := cValue;\n candidates( inc( lenCandidates ) ) := cValue\n end for_j\n end for_i ;\n quickSort( primes, 1, lenPrimes );\n end descending_primes ;\n\n begin % find the descending primes and print them %\n integer array primes ( 1 :: 512 );\n integer lenPrimes;\n descending_primes( primes, lenPrimes );\n for i := 1 until lenPrimes do begin\n writeon( i_w := 8, s_w := 0, \" \", primes( i ) );\n if i rem 10 = 0 then write()\n end for_i\n end\nend.\n", "language": "ALGOL-W" }, { "code": "descending: @[\n loop 1..9 'a [\n loop 1..dec a 'b [\n loop 1..dec b 'c [\n loop 1..dec c 'd [\n loop 1..dec d 'e [\n loop 1..dec e 'f [\n loop 1..dec f 'g [\n loop 1..dec g 'h [\n loop 1..dec h 'i -> @[a b c d e f g h i]\n @[a b c d e f g h]]\n @[a b c d e f g]]\n @[a b c d e f]]\n @[a b c d e]]\n @[a b c d]]\n @[a b c]]\n @[a b]]\n @[a]]\n]\n\ndescending: filter descending 'd -> some? d 'n [not? positive? n]\ndescending: filter descending 'd -> d <> unique d\ndescending: sort map descending 'd -> to :integer join to [:string] d\n\nloop split.every:10 select descending => prime? 'row [\n print map to [:string] row 'item -> pad item 8\n]\n", "language": "Arturo" }, { "code": "# syntax: GAWK -f DESCENDING_PRIMES.AWK\nBEGIN {\n start = 1\n stop = 99999999\n for (i=start; i<=stop; i++) {\n leng = length(i)\n flag = 1\n for (j=1; j<leng; j++) {\n if (substr(i,j,1) <= substr(i,j+1,1)) {\n flag = 0\n break\n }\n }\n if (flag) {\n if (is_prime(i)) {\n printf(\"%9d%1s\",i,++count%10?\"\":\"\\n\")\n }\n }\n }\n printf(\"\\n%d-%d: %d descending primes\\n\",start,stop,count)\n exit(0)\n}\nfunction is_prime(n, d) {\n d = 5\n if (n < 2) { return(0) }\n if (n % 2 == 0) { return(n == 2) }\n if (n % 3 == 0) { return(n == 3) }\n while (d*d <= n) {\n if (n % d == 0) { return(0) }\n d += 2\n if (n % d == 0) { return(0) }\n d += 4\n }\n return(1)\n}\n", "language": "AWK" }, { "code": "#include <stdio.h>\n\nint ispr(unsigned int n) {\n if ((n & 1) == 0 || n < 2) return n == 2;\n for (unsigned int j = 3; j * j <= n; j += 2)\n if (n % j == 0) return 0; return 1; }\n\nint main() {\n unsigned int c = 0, nc, pc = 9, i, a, b, l,\n ps[128], nxt[128];\n for (a = 0, b = 1; a < pc; a = b++) ps[a] = b;\n while (1) {\n nc = 0;\n for (i = 0; i < pc; i++) {\n if (ispr(a = ps[i]))\n printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n for (b = a * 10, l = a % 10 + b++; b < l; b++)\n nxt[nc++] = b;\n }\n if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n else break;\n }\n printf(\"\\n%d descending primes found\", c);\n}\n", "language": "C" }, { "code": "#include <iostream>\n\nbool ispr(unsigned int n) {\n if ((n & 1) == 0 || n < 2) return n == 2;\n for (unsigned int j = 3; j * j <= n; j += 2)\n if (n % j == 0) return false; return true; }\n\nint main() {\n unsigned int c = 0, nc, pc = 9, i, a, b, l,\n ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n while (true) {\n nc = 0;\n for (i = 0; i < pc; i++) {\n if (ispr(a = ps[i]))\n printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n for (b = a * 10, l = a % 10 + b++; b < l; b++)\n nxt[nc++] = b;\n }\n if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n else break;\n }\n printf(\"\\n%d descending primes found\", c);\n}\n", "language": "C++" }, { "code": "using System;\n\nclass Program {\n\n static bool ispr(uint n) {\n if ((n & 1) == 0 || n < 2) return n == 2;\n for (uint j = 3; j * j <= n; j += 2)\n if (n % j == 0) return false; return true; }\n\n static void Main(string[] args) {\n uint c = 0; int nc;\n var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n var nxt = new uint[128];\n while (true) {\n nc = 0;\n foreach (var a in ps) {\n if (ispr(a))\n Console.Write(\"{0,8}{1}\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n for (uint b = a * 10, l = a % 10 + b++; b < l; b++)\n nxt[nc++] = b;\n }\n if (nc > 1) {\n Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }\n else break;\n }\n Console.WriteLine(\"\\n{0} descending primes found\", c);\n }\n}\n", "language": "C-sharp" }, { "code": "type TProgress = procedure(Percent: integer);\n\n\nfunction IsPrime(N: integer): boolean;\n{Optimised prime test - about 40% faster than the naive approach}\nvar I,Stop: integer;\nbegin\nif (N = 2) or (N=3) then Result:=true\nelse if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result:= false\nelse\n\tbegin\n\tI:=5;\n\tStop:=Trunc(sqrt(N));\n\tResult:=False;\n\twhile I<=Stop do\n\t\tbegin\n\t\tif ((N mod I) = 0) or ((N mod (i + 2)) = 0) then exit;\n\t\tInc(I,6);\n\t\tend;\n\tResult:=True;\n\tend;\nend;\n\nfunction IsDescending(N: integer): boolean;\n{Determine if each digit is less than previous, left to right}\nvar S: string;\nvar I: integer;\nbegin\nResult:=False;\nS:=IntToStr(N);\nfor I:=1 to Length(S)-1 do\n if S[I]<=S[I+1] then exit;\nResult:=True;\nend;\n\n\nprocedure ShowDescendingPrimes(Memo: TMemo; Prog: TProgress);\n{Write Descending primes up to 123,456,789 }\n{The Optional progress }\nvar I,Cnt: integer;\nvar S: string;\nconst Max = 123456789;\nbegin\nif Assigned(Prog) then Prog(0);\nS:='';\nCnt:=0;\nfor I:=2 to Max do\n\tbegin\n\tif ((I mod 1000000)=0) and Assigned(Prog) then Prog(Trunc(100*(I/Max)));\n\tif IsDescending(I) and IsPrime(I) then\n\t\tbegin\n\t\tS:=S+Format('%12.0n', [I*1.0]);\n\t\tInc(Cnt);\n\t\tif (Cnt mod 8)=0 then\n\t\t\tbegin\n\t\t\tMemo.Lines.Add(S);\n\t\t\tS:='';\n\t\t\tend;\n\t\tend;\n\tend;\nif S<>'' then Memo.Lines.Add(S);\nMemo.Lines.Add('Descending Primes Found: '+IntToStr(Cnt));\nend;\n", "language": "Delphi" }, { "code": "func isprim num .\n if num < 2\n return 0\n .\n i = 2\n while i <= sqrt num\n if num mod i = 0\n return 0\n .\n i += 1\n .\n return 1\n.\nproc nextdesc n . .\n if isprim n = 1\n write n & \" \"\n .\n if n > 987654321\n return\n .\n for d = n mod 10 - 1 downto 1\n nextdesc n * 10 + d\n .\n.\nfor i = 9 downto 1\n nextdesc i\n.\n", "language": "EasyLang" }, { "code": "// Descending primes. Nigel Galloway: April 19th., 2022\n[2;3;5;7]::List.unfold(fun(n,i)->match n with []->None |_->let n=n|>List.map(fun(n,g)->[for n in n..9->(n+1,i*n+g)])|>List.concat in Some(n|>List.choose(fun(_,n)->if isPrime n then Some n else None),(n|>List.filter(fst>>(>)10),i*10)))([(4,3);(2,1);(8,7)],10)\n |>List.concat|>List.sort|>List.iter(printf \"%d \"); printfn \"\"\n", "language": "F-Sharp" }, { "code": "USING: grouping grouping.extras math math.combinatorics\nmath.functions math.primes math.ranges prettyprint sequences\nsequences.extras ;\n\n9 1 [a,b] all-subsets [ reverse 0 [ 10^ * + ] reduce-index ]\n[ prime? ] map-filter 10 \"\" pad-groups 10 group simple-table.\n", "language": "Factor" }, { "code": ": is-prime? \\ n -- f ; \\ Fast enough for this application\n DUP 1 AND IF \\ n is odd\n DUP 3 DO\n DUP I DUP * < IF DROP -1 LEAVE THEN \\ Leave loop if I**2 > n\n DUP I MOD 0= IF DROP 0 LEAVE THEN \\ Leave loop if n%I is zero\n 2 +LOOP \\ iterate over odd I only\n ELSE \\ n is even\n 2 = \\ Returns true if n == 2.\n THEN ;\n\n: 1digit \\ -- ; \\ Select and print one digit numbers which are prime\n 10 2 ?DO\n I is-prime? IF I 9 .r THEN\n LOOP ;\n\n: 2digit \\ n-bfwd digit -- ;\n \\ Generate and print primes where least significant digit < digit\n \\ n-bfwd is the base number bought foward from calls to `digits` below.\n SWAP 10 * SWAP 1 ?DO\n DUP I + is-prime? IF DUP I + 9 .r THEN\n 2 I 3 = 2* - +LOOP DROP ; \\ This generates the I sequence 1 3 7 9\n\n: digits \\ #digits n-bfwd max-digit -- ;\n \\ Print descendimg primes with #digits digits.\n 2 PICK 9 > IF .\" #digits must be less than 10.\" 2DROP DROP EXIT THEN\n 2 PICK 1 = IF 2DROP DROP 1digit EXIT THEN \\ One digit is special simple case\n 2 PICK 2 = IF \\ Two digit special and\n SWAP 10 * SWAP 2 DO \\ I is 2 .. max-digit-1\n DUP I + I 2digit\n LOOP 2DROP\n ELSE\n SWAP 10 * SWAP 2 PICK ?DO \\ I is #digits .. max-digit-1\n DUP I + 2 PICK 1- SWAP I RECURSE \\ Recurse with #digits reduced by 1.\n LOOP 2DROP\n THEN ;\n\n: descending-primes\n \\ Print the descending primes. Call digits with increasing #digits\n CR 9 1 DO I 0 10 digits LOOP ;\n", "language": "Forth" }, { "code": "#include \"isprime.bas\"\n#include \"sort.bas\"\n\nDim As Double t0 = Timer\nDim As Integer i, n, tmp, num, cant\nDim Shared As Integer matriz(512)\nFor i = 0 To 511\n n = 0\n tmp = i\n num = 9\n While tmp\n If tmp And 1 Then n = n * 10 + num\n tmp = tmp Shr 1\n num -= 1\n Wend\n matriz(i) = n\nNext i\n\nSort(matriz())\n\ncant = 0\nFor i = 1 To Ubound(matriz)-1\n n = matriz(i)\n If IsPrime(n) Then\n Print Using \"#########\"; n;\n cant += 1\n If cant Mod 10 = 0 Then Print\n End If\nNext i\nPrint Using !\"\\n\\nThere are & descending primes.\"; cant\nSleep\n", "language": "FreeBASIC" }, { "code": "local fn IsPrime( n as NSUInteger ) as BOOL\n BOOL isPrime = YES\n NSUInteger i\n\n if n < 2 then exit fn = NO\n if n = 2 then exit fn = YES\n if n mod 2 == 0 then exit fn = NO\n for i = 3 to int(n^.5) step 2\n if n mod i == 0 then exit fn = NO\n next\nend fn = isPrime\n\nvoid local fn DesecendingPrimes( limit as long )\n long i, n, mask, num, count = 0\n\n for i = 0 to limit -1\n n = 0 : mask = i : num = 9\n while ( mask )\n if mask & 1 then n = n * 10 + num\n mask = mask >> 1\n num--\n wend\n mda(i) = n\n next\n\n mda_sort @\"compare:\"\n\n for i = 1 to mda_count (0) - 1\n n = mda_integer(i)\n if ( fn IsPrime( n ) )\n printf @\"%10ld\\b\", n\n count++\n if count mod 10 == 0 then print\n end if\n next\n printf @\"\\n\\n\\tThere are %ld descending primes.\", count\nend fn\n\nwindow 1, @\"Desecending Primes\", ( 0, 0, 780, 230 )\nprint\n\nCFTimeInterval t\nt = fn CACurrentMediaTime\nfn DesecendingPrimes( 512 )\nprintf @\"\\n\\tCompute time: %.3f ms\\n\",(fn CACurrentMediaTime-t)*1000\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"rcu\"\n \"sort\"\n \"strconv\"\n)\n\nfunc combinations(a []int, k int) [][]int {\n n := len(a)\n c := make([]int, k)\n var combs [][]int\n var combine func(start, end, index int)\n combine = func(start, end, index int) {\n if index == k {\n t := make([]int, len(c))\n copy(t, c)\n combs = append(combs, t)\n return\n }\n for i := start; i <= end && end-i+1 >= k-index; i++ {\n c[index] = a[i]\n combine(i+1, end, index+1)\n }\n }\n combine(0, n-1, 0)\n return combs\n}\n\nfunc powerset(a []int) (res [][]int) {\n if len(a) == 0 {\n return\n }\n for i := 1; i <= len(a); i++ {\n res = append(res, combinations(a, i)...)\n }\n return\n}\n\nfunc main() {\n ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})\n var descPrimes []int\n for i := 1; i < len(ps); i++ {\n s := \"\"\n for _, e := range ps[i] {\n s += string(e + '0')\n }\n p, _ := strconv.Atoi(s)\n if rcu.IsPrime(p) {\n descPrimes = append(descPrimes, p)\n }\n }\n sort.Ints(descPrimes)\n fmt.Println(\"There are\", len(descPrimes), \"descending primes, namely:\")\n for i := 0; i < len(descPrimes); i++ {\n fmt.Printf(\"%8d \", descPrimes[i])\n if (i+1)%10 == 0 {\n fmt.Println()\n }\n }\n fmt.Println()\n}\n", "language": "Go" }, { "code": " NB. increase maximum output line length\n 9!:37 (512) 1} 9!:36 ''\n\n (#~ 1&p:) (#: }. i. 512) 10&#.@# >: i. _9\n2 3 31 41 421 43 431 5 521 53 541 5431 61 631 641 6421 643 6521 653 7 71 73 7321 743 751 7541 75431 761 7621 76421 7643 764321 76541 76543 821 83 8431 8521 853 8543 863 8641 86531 865321 8731 8741 87421 8753 87541 8761 87631 87641 87643 876431 8764321 8765321 941 9421 9431 94321 9521 953 9631 9643 96431 97 971 9721 9743 975421 9754321 97651 97654321 983 98321 9851 98543 98621 98641 986543 9871 98731 9875321 987541 987631 98764321 98765431\n", "language": "J" }, { "code": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic final class DescendingPrimes {\n\n\tpublic static void main(String[] aArgs) {\n\t\tList<Integer> allNumbersStrictlyDescendingDigits = new ArrayList<Integer>(512);\n\t\tfor ( int i = 0; i < 512; i++ ) {\n\t\t int number = 0;\n\t\t int temp = i;\n\t\t int digit = 9;\n\t\t while ( temp > 0 ) {\n\t\t if ( temp % 2 == 1 ) {\n\t\t \tnumber = number * 10 + digit;\n\t\t }\n\t\t temp >>= 1;\n\t\t digit -= 1;\n\t\t }\n\t\t allNumbersStrictlyDescendingDigits.add(number);\n\t\t}\n\n\t\tCollections.sort(allNumbersStrictlyDescendingDigits);\n\t\t\n\t\tint count = 0;\n\t\tfor ( int number : allNumbersStrictlyDescendingDigits ) {\n\t\t if ( isPrime(number) ) {\n\t\t System.out.print(String.format(\"%9d%s\", number, ( ++count % 10 == 0 ? \"\\n\" : \" \" )));\n\t\t }\n\t\t}\n\t\tSystem.out.println(System.lineSeparator());\n\t\tSystem.out.println(\"There are \" + count + \" descending primes.\");\t\n\t}\n\t\n\tprivate static boolean isPrime(int aNumber) {\n\t if ( aNumber < 2 || ( aNumber % 2 ) == 0 ) {\n\t \treturn aNumber == 2;\n\t }\n\t\n\t for ( int divisor = 3; divisor * divisor <= aNumber; divisor += 2 ) {\n\t \tif ( aNumber % divisor == 0 ) {\n\t \t\treturn false;\n\t \t}\n\t }\n\t return true;\n\t}\n\n}\n", "language": "Java" }, { "code": "# Output: a stream of the powersets of the input array\ndef powersets:\n if length == 0 then .\n else .[-1] as $x\n | .[:-1] | powersets\n | ., . + [$x]\n end;\n\ndef is_prime:\n . as $n\n | if ($n < 2) then false\n elif ($n % 2 == 0) then $n == 2\n elif ($n % 3 == 0) then $n == 3\n elif ($n % 5 == 0) then $n == 5\n elif ($n % 7 == 0) then $n == 7\n elif ($n % 11 == 0) then $n == 11\n elif ($n % 13 == 0) then $n == 13\n elif ($n % 17 == 0) then $n == 17\n elif ($n % 19 == 0) then $n == 19\n else 23\n | until( (. * .) > $n or ($n % . == 0); .+2)\n\t | . * . > $n\n end;\n\ndef lpad($len): tostring | ($len - length) as $l | (\" \" * $l)[:$l] + .;\n", "language": "Jq" }, { "code": "[range(9;0;-1)]\n| [powersets\n | map(tostring)\n | join(\"\")\n | select(length > 0)\n | tonumber\n | select(is_prime)]\n| sort\n| _nwise(10)\n| map(lpad(9))\n| join(\" \")\n", "language": "Jq" }, { "code": "using Combinatorics\nusing Primes\n\nfunction descendingprimes()\n return sort!(filter(isprime, [evalpoly(10, x)\n for x in powerset([1, 2, 3, 4, 5, 6, 7, 8, 9]) if !isempty(x)]))\nend\n\nforeach(p -> print(rpad(p[2], 10), p[1] % 10 == 0 ? \"\\n\" : \"\"), enumerate(descendingprimes()))\n", "language": "Julia" }, { "code": "local function is_prime(n)\n if n < 2 then return false end\n if n % 2 == 0 then return n==2 end\n if n % 3 == 0 then return n==3 end\n for f = 5, n^0.5, 6 do\n if n%f==0 or n%(f+2)==0 then return false end\n end\n return true\nend\n\nlocal function descending_primes()\n local digits, candidates, primes = {9,8,7,6,5,4,3,2,1}, {0}, {}\n for i = 1, #digits do\n for j = 1, #candidates do\n local value = candidates[j] * 10 + digits[i]\n if is_prime(value) then primes[#primes+1] = value end\n candidates[#candidates+1] = value\n end\n end\n table.sort(primes)\n return primes\nend\n\nprint(table.concat(descending_primes(), \", \"))\n", "language": "Lua" }, { "code": "Sort[Select[FromDigits/@Subsets[Range[9,1,-1],{1,\\[Infinity]}],PrimeQ]]\n", "language": "Mathematica" }, { "code": "import std/[strutils, sugar]\n\nproc isPrime(n: int): bool =\n assert n > 7\n if n mod 2 == 0 or n mod 3 == 0: return false\n var d = 5\n var step = 2\n while d * d <= n:\n if n mod d == 0:\n return false\n inc d, step\n step = 6 - step\n result = true\n\niterator descendingPrimes(): int =\n\n # Yield one digit primes.\n for n in [2, 3, 5, 7]:\n yield n\n\n # Yield other primes by increasing length and in ascending order.\n type Item = tuple[val, lastDigit: int]\n var items: seq[Item] = collect(for n in 1..9: (n, n))\n for ndigits in 2..9:\n var nextItems: seq[Item]\n for item in items:\n for newDigit in 0..(item.lastDigit - 1):\n let newVal = 10 * item.val + newDigit\n nextItems.add (val: newVal, lastDigit: newDigit)\n if newVal.isPrime():\n yield newVal\n items = move(nextItems)\n\n\nvar rank = 0\nfor prime in descendingPrimes():\n inc rank\n stdout.write ($prime).align(8)\n stdout.write if rank mod 8 == 0: '\\n' else: ' '\necho()\n", "language": "Nim" }, { "code": "use strict;\nuse warnings;\nuse ntheory 'is_prime';\n\nprint join( '',\n sort\n map { sprintf '%9d', $_ }\n grep /./ && is_prime $_,\n glob join '', map \"{$_,}\", reverse 1..9\n ) =~ s/.{45}\\K/\\n/gr;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">descending_primes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">max_digit</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">max_digit</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">np</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">d</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">odd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">is_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">np</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">np</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">descending_primes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">np</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sort</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">descending_primes</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">})),</span>\n <span style=\"color: #000080;font-style:italic;\">--sequence r = descending_primes({2}),</span>\n <span style=\"color: #000000;\">j</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join_by</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%8d\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"There are %,d descending primes:\\n%s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">descending_primes</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">powerset</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">powerset</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">powerset</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">is_prime</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">next</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">powerset</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">powerset</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">next</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">powerset</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]*</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">d</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">powerset</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">next</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">descending_primes</span><span style=\"color: #0000FF;\">(),</span>\n <span style=\"color: #000000;\">j</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join_by</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%8d\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"There are %,d descending primes:\\n%s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "import util.\n\nmain =>\n DP = [N : S in power_set(\"987654321\"), S != [], N = S.to_int, prime(N)].sort,\n foreach({P,I} in zip(DP,1..DP.len))\n printf(\"%9d%s\",P,cond(I mod 10 == 0,\"\\n\",\"\"))\n end,\n nl,\n println(len=DP.len).\n", "language": "Picat" }, { "code": "isPrime(2).\nisPrime(N):-\n\tbetween(3, inf, N),\n\tN /\\ 1 > 0, % odd\n\tM is floor(sqrt(N)) - 1, % reverse 2*I+1\n\tMax is M div 2,\n\tforall(between(1, Max, I), N mod (2*I+1) > 0).\n\ncombi(0, _, []).\ncombi(N, [_|T], Comb):-\n N > 0,\n combi(N, T, Comb).\ncombi(N, [X|T], [X|Comb]):-\n N > 0,\n N1 is N - 1,\n combi(N1, T, Comb).\n\ndescPrimes(Num):-\n\tbetween(1, 9, N),\n\tcombi(N, [9, 8, 7, 6, 5, 4, 3, 2, 1], CList),\n\tatomic_list_concat(CList, Tmp), % swi specific\n\tatom_number(Tmp, Num),\t % int_list_to_number\n\tisPrime(Num).\n\nshowList(List):-\n\tfindnsols(10, DPrim, (member(DPrim, List), writef('%9r', [DPrim])), _),\n\tnl,\n\tfail.\nshowList(_).\n \t\ndo:-findall(DPrim, descPrimes(DPrim), DList),\n\tshowList(DList).\n", "language": "Prolog" }, { "code": "from sympy import isprime\n\ndef descending(xs=range(10)):\n for x in xs:\n yield x\n yield from descending(x*10 + d for d in range(x%10))\n\nfor i, p in enumerate(sorted(filter(isprime, descending()))):\n print(f'{p:9d}', end=' ' if (1 + i)%8 else '\\n')\n\nprint()\n", "language": "Python" }, { "code": " [ 0 swap witheach\n [ swap 10 * + ] ] is digits->n ( [ --> n )\n\n []\n ' [ 9 8 7 6 5 4 3 2 1 ] powerset\n witheach\n [ digits->n dup isprime\n iff join else drop ]\n sort echo\n", "language": "Quackery" }, { "code": "put (flat 2, 3, 5, 7, sort +*, gather (3..9).map: &recurse ).batch(10)».fmt(\"%8d\").join: \"\\n\";\n\nsub recurse ($str) {\n .take for ($str X~ (1, 3, 7)).grep: { .is-prime && [>] .comb };\n recurse $str × 10 + $_ for 2 ..^ $str % 10;\n}\n", "language": "Raku" }, { "code": "show(\"decending primes\", sort(cending_primes(seq(9, 1))))\n\nfunc show(title, itm)\n l = len(itm); ? \"\" + l + \" \" + title + \":\"\n for i = 1 to l\n see fmt(itm[i], 9)\n if i % 5 = 0 and i < l? \"\" ok\n next : ? \"\"\n\nfunc seq(b, e)\n res = []; d = e - b\n s = d / fabs(d)\n for i = b to e step s add(res, i) next\n return res\n\nfunc ispr(n)\n if n < 2 return 0 ok\n if n & 1 = 0 return n = 2 ok\n if n % 3 = 0 return n = 3 ok\n l = sqrt(n)\n for f = 5 to l\n if n % f = 0 or n % (f + 2) = 0 return false ok\n next : return 1\n\nfunc cending_primes(digs)\n cand = [0]\n pr = []\n for i in digs\n lcand = cand\n for j in lcand\n v = j * 10 + i\n if ispr(v) add(pr, v) ok\n add(cand, v)\n next\n next\n return pr\n\nfunc fmt(x, l)\n res = \" \" + x\n return right(res, l)\n", "language": "Ring" }, { "code": "require 'prime'\n\ndigits = [9,8,7,6,5,4,3,2,1].to_a\nres = 1.upto(digits.size).flat_map do |n|\n digits.combination(n).filter_map do |set|\n candidate = set.join.to_i\n candidate if candidate.prime?\n end.reverse\n end\n\n puts res.join(\",\")\n", "language": "Ruby" }, { "code": "func primes_with_descending_digits(base = 10) {\n\n var list = []\n var digits = @(1..^base)\n\n var end_digits = digits.grep { .is_coprime(base) }\n list << digits.grep { .is_prime && !.is_coprime(base) }...\n\n for k in (0 .. digits.end) {\n digits.combinations(k, {|*a|\n var v = a.digits2num(base)\n end_digits.each {|d|\n var n = (v*base + d)\n next if ((n >= base) && (a[0] <= d))\n list << n if n.is_prime\n }\n })\n }\n\n list.sort\n}\n\nvar base = 10\nvar arr = primes_with_descending_digits(base)\n\nsay \"There are #{arr.len} descending primes in base #{base}.\\n\"\n\narr.each_slice(8, {|*a|\n say a.map { '%9s' % _ }.join(' ')\n})\n", "language": "Sidef" }, { "code": "import \"./perm\" for Powerset\nimport \"./math\" for Int\nimport \"./seq\" for Lst\nimport \"./fmt\" for Fmt\n\nvar ps = Powerset.list((9..1).toList)\nvar descPrimes = ps.skip(1).map { |s| Num.fromString(s.join()) }\n .where { |p| Int.isPrime(p) }\n .toList\n .sort()\nSystem.print(\"There are %(descPrimes.count) descending primes, namely:\")\nFmt.tprint(\"$8s\", descPrimes, 10)\n", "language": "Wren" }, { "code": "include xpllib; \\provides IsPrime and Sort\n\nint I, N, Mask, Digit, A(512), Cnt;\n[for I:= 0 to 511 do\n [N:= 0; Mask:= I; Digit:= 9;\n while Mask do\n [if Mask&1 then\n N:= N*10 + Digit;\n Mask:= Mask>>1;\n Digit:= Digit-1;\n ];\n A(I):= N;\n ];\nSort(A, 512);\nCnt:= 0;\nFormat(9, 0);\nfor I:= 1 to 511 do \\skip empty set\n [N:= A(I);\n if IsPrime(N) then\n [RlOut(0, float(N));\n Cnt:= Cnt+1;\n if rem(Cnt/10) = 0 then CrLf(0);\n ];\n ];\n]\n", "language": "XPL0" } ]
Descending-primes
[ { "code": "---\ncategory:\n- Simple\nfrom: http://rosettacode.org/wiki/Detect_division_by_zero\n", "language": "00-META" }, { "code": ";Task:\nWrite a function to detect a &nbsp; ''divide by zero error'' &nbsp; without checking if the denominator is zero.\n<br><br>\n", "language": "00-TASK" }, { "code": "1 0 n:/ Inf? . cr\n", "language": "8th" }, { "code": "report zdiv_zero\ndata x type i.\ntry.\n x = 1 / 0.\ncatch CX_SY_ZERODIVIDE.\n write 'Divide by zero.'.\nendtry.\n", "language": "ABAP" }, { "code": "-- Divide By Zero Detection\n\nwith Ada.Text_Io; use Ada.Text_Io;\nwith Ada.Float_Text_Io; use Ada.Float_Text_Io;\nwith Ada.Integer_Text_Io; use Ada.Integer_Text_Io;\n\nprocedure Divide_By_Zero is\n Fnum : Float := 1.0;\n Fdenom : Float := 0.0;\n Fresult : Float;\n Inum : Integer := 1;\n Idenom : Integer := 0;\n Iresult : Integer;\nbegin\n begin\n Put(\"Integer divide by zero: \");\n Iresult := Inum / Idenom;\n Put(Item => Iresult);\n exception\n when Constraint_Error =>\n Put(\"Division by zero detected.\");\n end;\n New_Line;\n Put(\"Floating point divide by zero: \");\n Fresult := Fnum / Fdenom;\n if Fresult > Float'Last or Fresult < Float'First then\n Put(\"Division by zero detected (infinite value).\");\n else\n Put(Item => Fresult, Aft => 9, Exp => 0);\n end if;\n New_Line;\nend Divide_By_Zero;\n", "language": "Ada" }, { "code": "integer\ndivide(integer n, integer d)\n{\n return n / d;\n}\n\ninteger\ncan_divide(integer n, integer d)\n{\n return !trap(divide, n, d);\n}\n\ninteger\nmain(void)\n{\n if (!can_divide(9, 0)) {\n o_text(\"Division by zero.\\n\");\n }\n\n return 0;\n}\n", "language": "Aime" }, { "code": "PROC raise exception= ([]STRING args)VOID: (\n put(stand error, (\"Exception: \",args, newline));\n stop\n);\n\nPROC raise zero division error := VOID:\n raise exception(\"integer division or modulo by zero\");\n\nPROC int div = (INT a,b)REAL: a/b;\nPROC int over = (INT a,b)INT: a%b;\nPROC int mod = (INT a,b)INT: a%*b;\n\nBEGIN\n OP / = (INT a,b)REAL: ( b = 0 | raise zero division error; SKIP | int div (a,b) );\n OP % = (INT a,b)INT: ( b = 0 | raise zero division error; SKIP | int over(a,b) );\n OP %* = (INT a,b)INT: ( b = 0 | raise zero division error; SKIP | int mod (a,b) );\n\n PROC a different handler = VOID: (\n put(stand error,(\"caught division by zero\",new line));\n stop\n );\n\n INT x:=1, y:=0;\n raise zero division error := a different handler;\n print(x/y)\nEND\n", "language": "ALGOL-68" }, { "code": "begin\n % integer division procedure %\n % sets c to a divided by b, returns true if the division was OK, %\n % false if there was division by zero %\n logical procedure divideI ( integer value a, b; integer result c ) ;\n begin\n % set exception handling to allow integer division by zero to occur once %\n INTDIVZERO := EXCEPTION( false, 1, 0, false, \"INTDIVZERO\" );\n c := a div b;\n not XCPNOTED(INTDIVZERO)\n end divideI ;\n % real division procedure %\n % sets c to a divided by b, returns true if the division was OK, %\n % false if there was division by zero %\n logical procedure divideR ( long real value a, b; long real result c ) ;\n begin\n % set exception handling to allow realdivision by zero to occur once %\n DIVZERO := EXCEPTION( false, 1, 0, false, \"DIVZERO\" );\n c := a / b;\n not XCPNOTED(DIVZERO)\n end divideR ;\n integer c;\n real d;\n write( divideI( 4, 2, c ) ); % prints false as no exception %\n write( divideI( 5, 0, c ) ); % prints true as division by zero was detected %\n write( divideR( 4, 2, d ) ); % prints false as no exception %\n write( divideR( 5, 0, d ) ) % prints true as division by zero was detected %\nend.\n", "language": "ALGOL-W" }, { "code": " 100 REM TRY\n 110 ONERR GOTO 200\n 120 D = - 44 / 0\n 190 END\n 200 REM CATCH\n 210 E = PEEK (222) < > 133\n 220 POKE 216,0: REM ONERR OFF\n 230 IF E THEN RESUME\n 240 CALL - 3288: REM RECOVER\n 250 PRINT \"DIVISION BY ZERO\"\n", "language": "Applesoft-BASIC" }, { "code": "try? -> 3/0\nelse -> print \"division by zero\"\n", "language": "Arturo" }, { "code": "ZeroDiv(num1, num2) {\n If ((num1/num2) != \"\")\n MsgBox % num1/num2\n Else\n MsgBox, 48, Warning, The result is not valid (Divide By Zero).\n}\nZeroDiv(0, 3) ; is ok\nZeroDiv(3, 0) ; divize by zero alert\n", "language": "AutoHotkey" }, { "code": "onerror TratoError\n\nprint 2 / 3\nprint 3 / 5\nprint 4 / 0\nend\n\nTratoError:\nprint \"Error in the line \" + lasterrorline + \" – Error number: \" + lasterror + \" – \" + lasterrormessage + \" (\" + lasterrorextra + \")\"\nreturn\n", "language": "BASIC256" }, { "code": "@echo off\nset /a dummy=5/0 2>nul\n\nif %errorlevel%==1073750993 echo I caught a division by zero operation...\nexit /b 0\n", "language": "Batch-File" }, { "code": " PROCdivide(-44, 0)\n PROCdivide(-44, 5)\n PROCdivide(0, 5)\n PROCdivide(5, 0)\n END\n\n DEF PROCdivide(numerator, denominator)\n ON ERROR LOCAL IF FALSE THEN\n REM 'Try' clause:\n PRINT numerator / denominator\n ELSE\n REM 'Catch' clause:\n CASE ERR OF\n WHEN 18: PRINT \"Division by zero\"\n WHEN 20: PRINT \"Number too big\"\n OTHERWISE RESTORE LOCAL : ERROR ERR, REPORT$\n ENDCASE\n ENDIF\n ENDPROC\n", "language": "BBC-BASIC" }, { "code": "Div ← {∨´\"∞\"‿\"NaN\"≡¨<•Fmt𝕩}◶⊢‿\"Division by 0\"÷\n\n•Show 5 Div 0\n•Show 5 Div 5\n•Show 0 Div 0\n", "language": "BQN" }, { "code": "\"Division by 0\"\n1\n\"Division by 0\"\n", "language": "BQN" }, { "code": "#include <limits.h>\t/* INT_MIN */\n#include <setjmp.h>\t/* siglongjmp(), sigsetjmp() */\n#include <stdio.h>\t/* perror(), printf() */\n#include <stdlib.h>\t/* exit() */\n#include <signal.h>\t/* sigaction(), sigemptyset() */\n\nstatic sigjmp_buf fpe_env;\n\n/*\n * This SIGFPE handler jumps to fpe_env.\n *\n * A SIGFPE handler must not return, because the program might retry\n * the division, which might cause an infinite loop. The only safe\n * options are to _exit() the program or to siglongjmp() out.\n */\nstatic void\nfpe_handler(int signal, siginfo_t *w, void *a)\n{\n\tsiglongjmp(fpe_env, w->si_code);\n\t/* NOTREACHED */\n}\n\n/*\n * Try to do x / y, but catch attempts to divide by zero.\n */\nvoid\ntry_division(int x, int y)\n{\n\tstruct sigaction act, old;\n\tint code;\n\t/*\n\t * The result must be volatile, else C compiler might delay\n\t * division until after sigaction() restores old handler.\n\t */\n\tvolatile int result;\n\n\t/*\n\t * Save fpe_env so that fpe_handler() can jump back here.\n\t * sigsetjmp() returns zero.\n\t */\n\tcode = sigsetjmp(fpe_env, 1);\n\tif (code == 0) {\n\t\t/* Install fpe_handler() to trap SIGFPE. */\n\t\tact.sa_sigaction = fpe_handler;\n\t\tsigemptyset(&act.sa_mask);\n\t\tact.sa_flags = SA_SIGINFO;\n\t\tif (sigaction(SIGFPE, &act, &old) < 0) {\n\t\t\tperror(\"sigaction\");\n\t\t\texit(1);\n\t\t}\n\n\t\t/* Do division. */\n\t\tresult = x / y;\n\n\t\t/*\n\t\t * Restore old hander, so that SIGFPE cannot jump out\n\t\t * of a call to printf(), which might cause trouble.\n\t\t */\n\t\tif (sigaction(SIGFPE, &old, NULL) < 0) {\n\t\t\tperror(\"sigaction\");\n\t\t\texit(1);\n\t\t}\n\n\t\tprintf(\"%d / %d is %d\\n\", x, y, result);\n\t} else {\n\t\t/*\n\t\t * We caught SIGFPE. Our fpe_handler() jumped to our\n\t\t * sigsetjmp() and passes a nonzero code.\n\t\t *\n\t\t * But first, restore old handler.\n\t\t */\n\t\tif (sigaction(SIGFPE, &old, NULL) < 0) {\n\t\t\tperror(\"sigaction\");\n\t\t\texit(1);\n\t\t}\n\n\t\t/* FPE_FLTDIV should never happen with integers. */\n\t\tswitch (code) {\n\t\tcase FPE_INTDIV: /* integer division by zero */\n\t\tcase FPE_FLTDIV: /* float division by zero */\n\t\t\tprintf(\"%d / %d: caught division by zero!\\n\", x, y);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tprintf(\"%d / %d: caught mysterious error!\\n\", x, y);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/* Try some division. */\nint\nmain()\n{\n\ttry_division(-44, 0);\n\ttry_division(-44, 5);\n\ttry_division(0, 5);\n\ttry_division(0, 0);\n\ttry_division(INT_MIN, -1);\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include<iostream>\n#include<csignal> /* for signal */\n#include<cstdlib>\n\nusing namespace std;\n\nvoid fpe_handler(int signal)\n{\n cerr << \"Floating Point Exception: division by zero\" << endl;\n exit(signal);\n}\n\nint main()\n{\n // Register floating-point exception handler.\n signal(SIGFPE, fpe_handler);\n\n int a = 1;\n int b = 0;\n cout << a/b << endl;\n\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\n\nnamespace RosettaCode {\n class Program {\n static void Main(string[] args) {\n int x = 1;\n int y = 0;\n try {\n int z = x / y;\n } catch (DivideByZeroException e) {\n Console.WriteLine(e);\n }\n\n }\n }\n}\n", "language": "C-sharp" }, { "code": "shared void run() {\n\t\n\t//integers divided by zero throw an exception\n\ttry {\n\t\tvalue a = 1 / 0;\n\t} catch (Exception e) {\n\t\te.printStackTrace();\n\t}\n\n\t//floats divided by zero produce infinity\n\tprint(1.0 / 0 == infinity then \"division by zero!\" else \"not division by zero!\");\n}\n", "language": "Ceylon" }, { "code": "(defn safe-/ [x y]\n (try (/ x y)\n (catch ArithmeticException _\n (println \"Division by zero caught!\")\n (cond (> x 0) Double/POSITIVE_INFINITY\n (zero? x) Double/NaN\n :else Double/NEGATIVE_INFINITY) )))\n", "language": "Clojure" }, { "code": "% This will catch a divide-by-zero exception and\n% return a oneof instead, with either the result or div_by_zero.\n% Overflow and underflow are resignaled.\ncheck_div = proc [T: type] (a, b: T) returns (otype)\n signals (overflow, underflow)\n where T has div: proctype (T,T) returns (T)\n signals (zero_divide, overflow, underflow)\n otype = oneof[div_by_zero: null, result: T]\n\n return(otype$make_result(a/b))\n except when zero_divide:\n return(otype$make_div_by_zero(nil))\n end resignal overflow, underflow\nend check_div\n\n% Try it\nstart_up = proc ()\n pair = struct[n, d: int]\n pairs: sequence[pair] := sequence[pair]$[\n pair${n: 10, d: 2}, % OK\n pair${n: 10, d: 0}, % divide by zero\n pair${n: 20, d: 2} % another OK one to show the program doesn't stop\n ]\n\n po: stream := stream$primary_output()\n for p: pair in sequence[pair]$elements(pairs) do\n stream$puts(po, int$unparse(p.n) || \"/\" || int$unparse(p.d) || \" = \")\n tagcase check_div[int](p.n, p.d)\n tag div_by_zero: stream$putl(po, \"divide by zero\")\n tag result (r: int): stream$putl(po, int$unparse(r))\n end\n end\nend start_up\n", "language": "CLU" }, { "code": "DIVIDE foo BY bar GIVING foobar\n ON SIZE ERROR\n DISPLAY \"Division by zero detected!\"\nEND-DIVIDE\n", "language": "COBOL" }, { "code": "(handler-case (/ x y)\n (division-by-zero () (format t \"division by zero caught!~%\")))\n", "language": "Common-Lisp" }, { "code": "import std.stdio, std.string, std.math, std.traits;\n\nstring divCheck(T)(in T numer, in T denom)\nif (isIntegral!T || isFloatingPoint!T) {\n Unqual!(typeof(numer / denom)) result;\n string msg;\n\n static if (isIntegral!T) {\n try {\n result = numer / denom;\n } catch(Error e) {\n msg = \"| \" ~ e.msg ~ \" (by Error)\";\n result = T.max;\n }\n } else { // Floating Point Type.\n result = numer / denom;\n if (numer.isNormal && result.isInfinity) {\n msg = \"| Division by Zero\";\n } else if (result != 0 && !result.isNormal) {\n if (numer.isNaN)\n msg = \"| NaN numerator\";\n else if (denom.isNaN)\n msg = \"| NaN denominator\";\n else if (numer.isInfinity)\n msg = \"| Inf numerator\";\n else\n msg = \"| NaN (Zero Division by Zero)\";\n }\n }\n\n return format(\"%5s %s\", format(\"%1.1g\", real(result)), msg);\n}\n\nvoid main() {\n writeln(\"Division with check:\");\n writefln(\"int 1/ 0: %s\", divCheck(1, 0));\n writefln(\"ubyte 1/ 0: %s\", divCheck(ubyte(1), ubyte(0)));\n writefln(\"real 1/ 0: %s\", divCheck(1.0L, 0.0L));\n writefln(\"real -1/ 0: %s\", divCheck(-1.0L, 0.0L));\n writefln(\"real 0/ 0: %s\", divCheck(0.0L, 0.0L));\n writeln;\n writefln(\"real -4/-2: %s\", divCheck(-4.0L,-2.0L));\n writefln(\"real 2/-inf: %s\", divCheck(2.0L, -real.infinity));\n writeln;\n writefln(\"real -inf/-2: %s\", divCheck(-real.infinity, -2.0L));\n writefln(\"real +inf/-2: %s\", divCheck(real.infinity, -2.0L));\n writefln(\"real nan/-2: %s\", divCheck(real.nan, -2.0L));\n writefln(\"real -2/ nan: %s\", divCheck(-2.0L, real.nan));\n writefln(\"real nan/ 0: %s\", divCheck(real.nan, 0.0L));\n writefln(\"real inf/ inf: %s\",\n divCheck(real.infinity, real.infinity));\n writefln(\"real nan/ nan: %s\", divCheck(real.nan, real.nan));\n}\n", "language": "D" }, { "code": "program DivideByZero;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils;\n\nvar\n a, b: Integer;\nbegin\n a := 1;\n b := 0;\n try\n WriteLn(a / b);\n except\n on e: EZeroDivide do\n Writeln(e.Message);\n end;\nend.\n", "language": "Delphi" }, { "code": "def divide(numerator, denominator) {\n def floatQuotient := numerator / denominator\n if (floatQuotient.isNaN() || floatQuotient.isInfinite()) {\n return [\"zero denominator\"]\n } else {\n return [\"ok\", floatQuotient]\n }\n}\n", "language": "E" }, { "code": "func checkDivZero a b .\n r = a / b\n if r = number \"nan\" or r = number \"inf\" or r = number \"-inf\"\n return 1\n .\n.\nprint checkDivZero 5 7\nprint checkDivZero -1 0\n", "language": "EasyLang" }, { "code": "DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor;\n\n#option ('divideByZero', 'zero');\nDBZ(10,0); //returns 0.0\n", "language": "ECL" }, { "code": "DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor;\n#option ('divideByZero', 'fail');\nDBZ(10,0); //returns error message \"Error: System error: -1: Division by zero (0, 0), -1,\"\n", "language": "ECL" }, { "code": "DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor;\n#option ('divideByZero', 'nan');\nDBZ(10,0); //returns 'nan'\n\n/* NOTE: This is only currently supported for real numbers. Division by zero creates a quiet NaN,\n which will propogate through any real expressions it is used in.\n You can use NOT ISVALID(x) to test if the value is a NaN.\n Integer and decimal division by zero continue to return 0.\n*/\n", "language": "ECL" }, { "code": "class MAIN\n creation main\n feature main is\n local\n x, y: INTEGER;\n retried: BOOLEAN;\n do\n x := 42;\n y := 0;\n\n if not retried then\n io.put_real(x / y);\n else\n print(\"NaN%N\");\n end\n rescue\n print(\"Caught division by zero!%N\");\n retried := True;\n retry\n end\nend\n", "language": "Eiffel" }, { "code": "open core number\n\nx /. y = try Some (x `div` y) with\n _ = None\n\n(12 /. 2, 12 /. 0)\n", "language": "Ela" }, { "code": "x /. 0 = None\nx /. y = Some (x / y)\n", "language": "Ela" }, { "code": "defmodule Division do\n def by_zero?(x,y) do\n try do\n _ = x / y\n false\n rescue\n ArithmeticError -> true\n end\n end\nend\n\n[{2, 3}, {3, 0}, {0, 5}, {0, 0}, {2.0, 3.0}, {3.0, 0.0}, {0.0, 5.0}, {0.0, 0.0}]\n|> Enum.each(fn {x,y} ->\n IO.puts \"#{x} / #{y}\\tdivision by zero #{Division.by_zero?(x,y)}\"\nend)\n", "language": "Elixir" }, { "code": "(condition-case nil\n (/ 1 0)\n (arith-error\n (message \"Divide by zero (either integer or float)\")))\n", "language": "Emacs-Lisp" }, { "code": "div_check(X,Y) ->\n case catch X/Y of\n {'EXIT',_} -> true;\n _ -> false\n end.\n", "language": "Erlang" }, { "code": "PROGRAM DIV_BY_ZERO\n\nEXCEPTION\n IF ERR=11 THEN PRINT(\"Division by Zero\") END IF\nEND EXCEPTION\n\nBEGIN\n PRINT(0/3)\n PRINT(3/0)\nEND PROGRAM\n", "language": "ERRE" }, { "code": "let detectDivideZero (x : int) (y : int):int option =\n try\n Some(x / y)\n with\n | :? System.ArithmeticException -> None\n\n\nprintfn \"12 divided by 3 is %A\" (detectDivideZero 12 3)\nprintfn \"1 divided by 0 is %A\" (detectDivideZero 1 0)\n", "language": "F-Sharp" }, { "code": "USE: math.floats.env\n\n: try-div ( a b -- )\n '[ { +fp-zero-divide+ } [ _ _ /f . ] with-fp-traps ] try ;\n", "language": "Factor" }, { "code": "def divide: x by: y {\n try {\n x / y\n } catch DivisionByZeroError => e {\n e message println # prints error message\n }\n}\n", "language": "Fancy" }, { "code": ": safe-/ ( x y -- x/y )\n ['] / catch -55 = if cr .\" divide by zero!\" 2drop 0 then ;\n", "language": "Forth" }, { "code": "program rosetta_divbyzero\n implicit none\n integer, parameter :: rdp = kind(1.d0)\n real(rdp) :: normal,zero\n\n normal = 1.d0\n zero = 0.d0\n\n call div_by_zero_check(normal,zero)\n\n contains\n\n subroutine div_by_zero_check(x,y)\n use, intrinsic :: ieee_exceptions\n use, intrinsic :: ieee_arithmetic\n implicit none\n real(rdp), intent(in) :: x,y\n\n real(rdp) :: check\n type(ieee_status_type) :: status_value\n logical :: flag\n flag = .false.\n ! Get the flags\n call ieee_get_status(status_value)\n ! Set the flags quiet\n call ieee_set_flag(ieee_divide_by_zero,.false.)\n write(*,*)\"Inf supported? \",ieee_support_inf(check)\n\n ! Calculation involving exception handling\n check = x/y\n write(*,*)\"Is check finite?\",ieee_is_finite(check), check\n\n call ieee_get_flag(ieee_divide_by_zero, flag)\n if (flag) write(*,*)\"Warning! Division by zero detected\"\n\n ! Restore the flags\n call ieee_set_status(status_value)\n\n end subroutine div_by_zero_check\n\nend program rosetta_divbyzero\n", "language": "Fortran" }, { "code": "program rosetta_integer_divbyzero\n implicit none\n integer :: normal,zero,answer\n normal = 1\n zero = 0\n answer = normal/ zero\n write(*,*) answer\nend program rosetta_integer_divbyzero\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nConst divByZeroResult As Integer = -9223372036854775808\n\nSub CheckForDivByZero(result As Integer)\n If result = divByZeroResult Then\n Print \"Division by Zero\"\n Else\n Print \"Division by Non-Zero\"\n End If\nEnd Sub\n\nDim As Integer x, y\n\nx = 0 : y = 0\nCheckForDivByZero(x/y) ' automatic conversion to type of parameter which is Integer\nx = 1\nCheckForDivByZero(x/y)\nx = -1\nCheckForDivByZero(x/y)\ny = 1\nCheckForDivByZero(x/y)\nPrint\nPrint \"Press any key to exit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "on error stop\nlong a\nprint a / 0\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\n\nTry Print 1 / 0\nIf Error Then Print Error.Text\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc divCheck(x, y int) (q int, ok bool) {\n defer func() {\n recover()\n }()\n q = x / y\n return q, true\n}\n\nfunc main() {\n fmt.Println(divCheck(3, 2))\n fmt.Println(divCheck(3, 0))\n}\n", "language": "Go" }, { "code": "def dividesByZero = { double n, double d ->\n assert ! n.infinite : 'Algorithm fails if the numerator is already infinite.'\n (n/d).infinite || (n/d).naN\n}\n", "language": "Groovy" }, { "code": "((3d)..(0d)).each { i ->\n ((2d)..(0d)).each { j ->\n println \"${i}/${j} divides by zero? \" + dividesByZero(i,j)\n }\n}\n", "language": "Groovy" }, { "code": "import qualified Control.Exception as C\ncheck x y = C.catch (x `div` y `seq` return False)\n (\\_ -> return True)\n", "language": "Haskell" }, { "code": "let a 1\nlet b 0\nif tostr (a / (b + 0.)) = \"inf\"\n println \"Divide by Zero\"\nelse\n println a / b\nendif\n", "language": "Hexiscript" }, { "code": "FUNCTION zero_divide(num, denom)\n XEQ( num// \"/\" // denom, *99) ! on error jump to label 99\n zero_divide = 0 ! division OK\n RETURN\n\n 99 zero_divide = 1\nEND\n", "language": "HicEst" }, { "code": "zero_divide(0, 1) returns 0 (false)\nzero_divide( 1, 3-2-1 ) returns 1 (true)\n", "language": "HicEst" }, { "code": "try {\n Print(\"%d\\n\", 10 / 0);\n} catch {\n Print(\"Divide by zero\");\n}\n", "language": "HolyC" }, { "code": "//Division by zero is defined in 'i' so the result can be checked to determine division by zero.\nconcept IsDivisionByZero(a, b) {\n\tc = a/b\n\tif c = 0 and a - 0 or a = 0 and c > 0\n\t\tprint( a, \"/\", b, \" is a division by zero.\")\n\t\treturn\n\tend\n\tprint( a, \"/\", b, \" is not division by zero.\")\n}\n\nsoftware {\n\tIsDivisionByZero(5, 0)\n\tIsDivisionByZero(5, 2)\n\tIsDivisionByZero(0, 0)\n}\n", "language": "I" }, { "code": "procedure main()\n&error := 1\nudef := 1 / 0 | stop(\"Run-time error \", &errornumber, \" : \", &errortext,\" in line #\",&line,\" - converted to failure\")\nend\n", "language": "Icon" }, { "code": "if not finite( <i>expression</i> ) then ...\n", "language": "IDL" }, { "code": "100 WHEN EXCEPTION USE ERROR\n110 FOR I=5 TO-2 STEP-1\n120 PRINT 10/I\n130 NEXT\n140 END WHEN\n150 HANDLER ERROR\n160 IF EXTYPE=3001 THEN PRINT EXSTRING$(EXTYPE);\" in line\";EXLINE\n170 CONTINUE\n180 END HANDLER\n", "language": "IS-BASIC" }, { "code": "funnydiv=: 0 { [: (,:'division by zero detected')\"_^:(_ e. |@,) (,>:)@:(,:^:(0<#@$))@[ %\"_1 _ ]\n", "language": "J" }, { "code": " 3 funnydiv 2\n1.5\n 3 funnydiv 0\ndivision by zero detected\n 0 funnydiv 0\ndivision by zero detected\n 0 funnydiv 3\n0\n 2 3 4 funnydiv 5\n0.4 0.6 0.8\n", "language": "J" }, { "code": "public static boolean infinity(double numer, double denom){\n\treturn Double.isInfinite(numer/denom);\n}\n", "language": "Java" }, { "code": "public static boolean except(double numer, double denom){\n\ttry{\n\t\tint dummy = (int)numer / (int)denom;//ArithmeticException is only thrown from integer math\n\t\treturn false;\n\t}catch(ArithmeticException e){return true;}\n}\n", "language": "Java" }, { "code": "function divByZero(dividend,divisor)\n{\n\tvar quotient=dividend/divisor;\n if(isNaN(quotient)) return 0; //Can be changed to whatever is desired by the programmer to be 0, false, or Infinity\n return quotient; //Will return Infinity or -Infinity in cases of, for example, 5/0 or -7/0 respectively\n}\nalert(divByZero(0,0));\n", "language": "JavaScript" }, { "code": "def div(x;y): if y==0 then error(\"NaN\") else x/y end;\n", "language": "Jq" }, { "code": "try div(3;0) catch if \"NaN\" then \"div by 0 error detected\" else . end\n", "language": "Jq" }, { "code": "if (!isFinite(numerator/denominator)) puts(\"result is infinity or not a number\");\n", "language": "Jsish" }, { "code": "isdefinite(n::Number) = !isnan(n) && !isinf(n)\n\nfor n in (1, 1//1, 1.0, 1im, 0)\n d = n / 0\n println(\"Dividing $n by 0 \", isdefinite(d) ? \"results in $d.\" : \"yields an indefinite value ($d).\")\nend\n", "language": "Julia" }, { "code": "// version 1.1\n\nfun divideByZero(x: Int, y:Int): Boolean =\n try {\n x / y\n false\n } catch(e: ArithmeticException) {\n true\n }\n\nfun main(args: Array<String>) {\n val x = 1\n val y = 0\n if (divideByZero(x, y)) {\n println(\"Attempted to divide by zero\")\n } else {\n @Suppress(\"DIVISION_BY_ZERO\")\n println(\"$x / $y = ${x / y}\")\n }\n}\n", "language": "Kotlin" }, { "code": "{def DivByZero?\n {lambda {:w}\n {W.equal? :w Infinity}}}\n\n{DivByZero? {/ 3 2}}\n-> false\n{DivByZero? {/ 3 0}}\n-> true\n", "language": "Lambdatalk" }, { "code": "val .div = fn(.x, .y) {\n [.x / .y, true]\n catch {\n if _err'msg -> re/division by 0/ {\n [0, false]\n } else {\n # rethrow the error if not division by 0\n throw\n }\n }\n}\n\nwriteln .div(3, 2)\nwriteln .div(3, 0)\n", "language": "Langur" }, { "code": "define dividehandler(a,b) => {\n\t(\n\t\t#a->isNotA(::integer) && #a->isNotA(::decimal) ||\n\t\t#b->isNotA(::integer) && #b->isNotA(::decimal)\n\t) ? return 'Error: Please supply all params as integers or decimals'\n\tprotect => {\n\t\thandle_error => { return 'Error: Divide by zero' }\n\t\tlocal(x = #a / #b)\n\t\treturn #x\n\t}\n}\n\ndividehandler(1,0)\n", "language": "Lasso" }, { "code": "result = DetectDividebyZero(1, 0)\n\nFunction DetectDividebyZero(a, b)\n On Error GoTo [Error]\n DetectDividebyZero= (a/ b)\n Exit Function\n [Error]\n If Err = 11 Then '11 is the error number raised when divide by zero occurs\n Notice \"Divide by Zero Detected!\"\n End If\nEnd Function\n", "language": "Liberty-BASIC" }, { "code": "on div (a, b)\n -- for simplicity type check of vars omitted\n res = value(\"float(a)/b\")\n if voidP(res) then\n _player.alert(\"Division by zero!\")\n else\n return res\n end if\nend\n", "language": "Lingo" }, { "code": "10 ON ERROR GOTO 60\n20 PRINT 2/3\n30 PRINT 3/5\n40 PRINT 4/0\n50 END\n60 IF ERR=11 THEN PRINT \"Division by zero in line\"ERL:RESUME 50\n", "language": "Locomotive-Basic" }, { "code": "local function div(a,b)\n if b == 0 then error() end\n return a/b\nend\n", "language": "Lua" }, { "code": "Print function(\"{Read x : =x**2}\", 2)=4\n", "language": "M2000-Interpreter" }, { "code": "Print Valid(100/0)=False\n", "language": "M2000-Interpreter" }, { "code": "Module Checkit {\n Function DetectDivisionByZero(&a()) {\n Try {\n a=a()\n }\n =Error$=\" division by zero\"\n }\n\n Print DetectDivisionByZero(lazy$(10/0))=True\n Z=10\n A=4\n B=0\n Print DetectDivisionByZero(lazy$(Z/B))=True\n Print DetectDivisionByZero(lazy$(Z/A))=False\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "ifelse(eval(2/0),`',`detected divide by zero or some other error of some kind')\n", "language": "M4" }, { "code": "1/0; # Here is the default behavior.\n", "language": "Maple" }, { "code": "NumericEventHandler( ':-division_by_zero'\n = proc() infinity; end proc ):\n\n1/0;\n\nNumericStatus(':-division_by_zero'); # We may check the status flag\n", "language": "Maple" }, { "code": "NumericEventHandler( ':-division_by_zero'\n = proc()\n WARNING(\"division by zero\");\n NumericStatus(':-division_by_zero'=false):\n infinity;\n end proc ):\n\n1/0;\n\nNumericStatus(':-division_by_zero');\n", "language": "Maple" }, { "code": "Check[2/0, Print[\"division by 0\"], Power::infy]\n", "language": "Mathematica" }, { "code": "function [isDividedByZero] = dividebyzero(numerator, denomenator)\n isDividedByZero = isinf( numerator/denomenator );\n % If isDividedByZero equals 1, divide by zero occured.\n", "language": "MATLAB" }, { "code": "f(a, b) := block([q: errcatch(a / b)], if emptyp(q) then 'error else q[1]);\n\nf(5, 6);\n5 / 6\n\nf(5, 0;)\n'error\n", "language": "Maxima" }, { "code": "if not bit.isFinite (<i>expression</i>) then...\n", "language": "MAXScript" }, { "code": "(/ inf ==) :div-zero?\n", "language": "Min" }, { "code": "number.isInfinite = function\n return abs(self) == 1/0\nend function\n\nnumber.isNaN = function\n return self != self\nend function\n\nnumber.toBoolStr = function\n if self == 0 then return \"false\"\n return \"true\"\nend function\n\ncheckDivByZero = function(a, b)\n c = a / b\n if c.isInfinite or c.isNaN then return true\n return false\nend function\n\nprint \"Division by zero?\"\nprint \" 0 / 0 -> \" + checkDivByZero( 0, 0).toBoolStr\nprint \" 1 / 0 -> \" + checkDivByZero( 1, 0).toBoolStr\nprint \" 1 / 1 -> \" + checkDivByZero( 1, 1).toBoolStr\nprint \" -5 / 0 -> \" + checkDivByZero(-5, 0).toBoolStr\nprint \" -5 / 2 -> \" + checkDivByZero(-5, 2).toBoolStr\n", "language": "MiniScript" }, { "code": "var %n = $rand(0,1)\nif ($calc(1/ %n) == $calc((1/ %n)+1)) {\n echo -ag Divides By Zero\n}\nelse {\n echo -ag Does Not Divide By Zero\n}\n", "language": "MIRC-Scripting-Language" }, { "code": "DIV(A,B) ;Divide A by B, and watch for division by zero\n ;The ANSI error code for division by zero is \"M9\".\n ;$ECODE errors are surrounded by commas when set.\n NEW $ETRAP\n SET $ETRAP=\"GOTO DIVFIX^ROSETTA\"\n SET D=(A/B)\n SET $ETRAP=\"\"\n QUIT D\nDIVFIX\n IF $FIND($ECODE,\",M9,\")>1 WRITE !,\"Error: Division by zero\" SET $ECODE=\"\" QUIT \"\"\n QUIT \"\" ; Fall through for other errors\n", "language": "MUMPS" }, { "code": "def div_check(x, y)\n\ttry\n\t\t(x / y)\n\t\treturn false\n\tcatch\n\t\treturn true\n\tend\nend\n", "language": "Nanoquery" }, { "code": "/**\n Detect division by zero\n*/\n\nvar ans = 1.0 / 0.0\nif $isinfinite(ans) $print(\"division by zero: \", ans, \"\\n\")\n\nans = 1 / 0\nif $isinfinite(ans) $print(\"division by zero: \", ans, \"\\n\")\n\ntry $print($idiv(1, 0)) catch problem $print(\"idiv by zero: \", problem, \"\\n\")\n", "language": "Neko" }, { "code": ";; Division by zero detection using CAREFULLY\n;; The CAREFULLY clause exists in NetLogo since version 2.0\n;; In prior versions of NetLogo, you must examine the divisor prior to performing the division.\n;; The variables result, a, and b must all be previously created global, local, or agent -own'd variables.\n;; NetLogo variables are dynamically typed, so we are assuming that a and b contain numbers.\n;; (All numbers in NetLogo are double-precision floating-point numbers.)\n;; However, even if not numbers, the result is still the same: the carefully clause will\n;; supress the run-time error and run the \"commands if error\" block, setting result to false.\n;; this false value can be detected, to alter the rest of the course of the code\n;; This behavior is consistent with other NetLogo primitives, such as POSTIION, that report\n;; FALSE, rather than a number, if the operation fails.\ncarefully\n[ ;; commands to try to run\n set result a / b\n]\n[ ;; commands to run if an error occurs in the previous block.\n set result false\n]\nifelse is-number? result\n[ output-print (word a \" / \" b \" = \" result)\n]\n[ output-print (word a \" / \" b \" is not calculable\"\n]\n", "language": "NetLogo" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\nmethod divide(dividend, divisor) public constant returns Rexx\n do\n quotient = dividend / divisor\n catch exu = DivideException\n exu.printStackTrace()\n quotient = 'undefined'\n catch exr = RuntimeException\n exr.printStackTrace()\n quotient = 'error'\n end\n return quotient\n\nmethod main(args = String[]) public static\n -- process input arguments and set sensible defaults\n arg = Rexx(args)\n parse arg dividend .',' divisor .\n if dividend.length() = 0 then dividend = 1\n if divisor.length() = 0 then divisor = 0\n say dividend '/' divisor '=' divide(dividend, divisor)\n return\n", "language": "NetRexx" }, { "code": "#! /usr/local/bin/newlisp\n\n(define (check-division x y)\n (catch (/ x y) 'check-zero)\n (if (not (integer? check-zero))\n (setq check-zero \"Division by zero.\"))\n check-zero\n)\n\n(println (check-division 10 4))\n(println (check-division 4 0))\n(println (check-division 20 5))\n(println (check-division 11 0))\n\n(exit)\n", "language": "NewLISP" }, { "code": "{.push overflowChecks: on.}\nproc divCheck(x, y): bool =\n try:\n discard x div y\n except DivByZeroDefect:\n return true\n return false\n{.pop.} # Restore default check settings\n\necho divCheck(2, 0)\n", "language": "Nim" }, { "code": "10 ON ERROR GOTO 40\n20 PRINT 1/0\n30 END\n40 IF ERR = 10 THEN PRINT \"DIVISION BY ZERO IN LINE\"ERL\n50 RESUME 30\n", "language": "NS-HUBASIC" }, { "code": "let div_check x y =\n try\n ignore (x / y);\n false\n with Division_by_zero ->\n true\n", "language": "OCaml" }, { "code": "let div_check x y =\n classify_float (x /. y) = FP_infinite\n", "language": "OCaml" }, { "code": "d = 5/0;\nif ( isinf(d) )\n if ( index(lastwarn(), \"division by zero\") > 0 )\n error(\"division by zero\")\n endif\nendif\n", "language": "Octave" }, { "code": ": divideCheck(n)\n| e |\n try: e [ 128 n / ] when: [ \"Zero detected...\" . ]\n \"Leaving\" println ;\n", "language": "Oforth" }, { "code": "(define (safediv a b)\n (if (eq? (type b) type-complex)\n (/ a b) ; complex can't be 0\n (let ((z (/ 1 (inexact b))))\n (unless (or (equal? z +inf.0) (equal? z -inf.0))\n (/ a b)))))\n\n; testing:\n(for-each (lambda (x)\n (if x (print x) (print \"division by zero detected\")))\n (list\n (safediv 1 5) ; => 1/5\n (safediv 2 0) ; => division by zero detected\n (safediv 3 1+2i) ; => 3/5-6/5i\n (safediv 4 0+i) ; => 0-4i\n (safediv 5 7/5) ; => 25/7\n))\n", "language": "Ol" }, { "code": "/* REXX **************************************************************\n* program demonstrates detects and handles division by zero.\n* translated from REXX:\n* removed fancy error reporting (ooRexx does not support linesize)\n* removed label Novalue (as novalue is not enabled there)\n* 28.04.2013 Walter Pachl\n*********************************************************************/\nSignal on Syntax /*handle all REXX syntax errors. */\nx = sourceline() /*being cute, x=size of this pgm.*/\ny = x-x /*setting to zero the obtuse way.*/\nz = x/y /* attempt to divide by 0 */\nexit /* will not be reached */\n\nSyntax:\n Say 'Syntax raised in line' sigl\n Say sourceline(sigl)\n Say 'rc='rc '('errortext(rc)')'\n Exit 12\n", "language": "OoRexx" }, { "code": "try\n {Show 42 div 0}\ncatch error(kernel(div0 ...) ...) then\n {System.showInfo \"Division by zero detected.\"}\nend\n", "language": "Oz" }, { "code": "iferr(1/0,\n err,\n print(\"division by 0\"); print(\"or other non-invertible divisor\"),\n errname(err) == \"e_INV\");\n", "language": "PARI-GP" }, { "code": "trap(,\"division by 0\",m/n)\n", "language": "PARI-GP" }, { "code": "sub div_check\n {local $@;\n eval {$_[0] / $_[1]};\n $@ and $@ =~ /division by zero/;}\n", "language": "Perl" }, { "code": "-->\n <span style=\"color: #008080;\">try</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1<span style=\"color: #0000FF;\">/<span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">catch</span> <span style=\"color: #000000;\">e</span>\n <span style=\"color: #0000FF;\">?<span style=\"color: #000000;\">e<span style=\"color: #0000FF;\">[<span style=\"color: #000000;\">E_USER<span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">try</span>\n <span style=\"color: #7060A8;\">puts<span style=\"color: #0000FF;\">(<span style=\"color: #000000;\">1<span style=\"color: #0000FF;\">,<span style=\"color: #008000;\">\"still running...\\n\"<span style=\"color: #0000FF;\">)\n<!--\n", "language": "Phix" }, { "code": "function div_check($x, $y) {\n @trigger_error(''); // a dummy to detect when error didn't occur\n @($x / $y);\n $e = error_get_last();\n return $e['message'] != '';\n}\n", "language": "PHP" }, { "code": "function div_check($x, $y) {\n return @($x / $y) === FALSE; // works at least in PHP/5.2.6-3ubuntu4.5\n}\n", "language": "PHP" }, { "code": "(catch '(\"Div/0\") (/ A B))\n", "language": "PicoLisp" }, { "code": "Proc DivideDZ(a,b) Returns(Float Bin(33));\n Dcl (a,b,c) Float Bin(33);\t\n On ZeroDivide GoTo MyError;\n c=a/b;\n Return(c);\nMyError:\n Put Skip List('Divide by Zero Detected!');\nEnd DivideDZ;\n\nxx=DivideDZ(1,0);\n", "language": "PL-I" }, { "code": "FUNCTION divide(n1 IN NUMBER, n2 IN NUMBER)\nRETURN BOOLEAN\nIS\n result NUMBER;\nBEGIN\n result := n1/n2;\n RETURN(FALSE);\nEXCEPTION\n WHEN ZERO_DIVIDE THEN\n RETURN(true);\nend divide;\n", "language": "PL-SQL" }, { "code": "divide(0,1) --false\ndivide(1,0) --true, division by zero\n", "language": "PL-SQL" }, { "code": "To run:\nStart up.\nIf 1 and 0 does cause division error, write \"Division by zero found\" to the output.\nWait for the escape key.\nShut down.\n\nTo decide if a number and another number does cause division error:\nPut the number divided by the other number into a third number.\nIf the third number is the largest number, say yes.\nSay no.\n", "language": "Plain-English" }, { "code": "function div ($a, $b) {\n try{$a/$b}\n catch{\"Bad parameters: `$a = $a and `$b = $b\"}\n}\ndiv 10 2\ndiv 1 0\n", "language": "PowerShell" }, { "code": "div(A, B, C, Ex) :-\n catch((C is A/B), Ex, (C = infinity)).\n", "language": "Prolog" }, { "code": "> 1/0, -1/0, 0/0;\ninf,-inf,nan\n", "language": "Pure" }, { "code": "> inf_or_nan x = infp x || nanp x;\n> map inf_or_nan [1/0, -1/0, 0/0];\n[1,1,1]\n", "language": "Pure" }, { "code": "> divide n m = catch (\\_ -> \"divide by 0\") (n div m);\n> divide 0 1;\n0\n> divide 1 0;\n\"divide by 0\"\n", "language": "Pure" }, { "code": ";Set up a Procedure to handle any Error\nProcedure MyErrorHandler()\n Define txt$=\"The following error happened.\"+#CRLF$+ ErrorMessage()+\"at line \"+Str(ErrorLine())\n MessageRequester(\"OnError test\", txt$)\nEndProcedure\n\n; Tell where to go if an Error happens\nOnErrorCall(@MyErrorHandler())\n\n;Now, do something very stupid so that we may see an Error...\nRepeat\n A=Random(100)/Random(100)\nForEver\n", "language": "PureBasic" }, { "code": "Define.d a, b\nDebug a/b\n", "language": "PureBasic" }, { "code": "def div_check(x, y):\n try:\n x / y\n except ZeroDivisionError:\n return True\n else:\n return False\n", "language": "Python" }, { "code": "r:x%0\n?[1=sum r=(0n;0w;-0w);\"division by zero detected\";()]\n", "language": "Q" }, { "code": "ON ERROR GOTO TratoError\nPRINT 2 / 3\nPRINT 3 / 5\nPRINT 4 / 0\nEND\n\nTratoError:\nPRINT \"Error\"; ERR; \"in the line\"; ERL\nIF ERR = 11 THEN PRINT \"Division by zero in line\"; ERL: RESUME NEXT\n", "language": "QBasic" }, { "code": "d <- 5/0\nif ( !is.finite(d) ) {\n # it is Inf, -Inf, or NaN\n}\n", "language": "R" }, { "code": "#lang racket\n\n(with-handlers ([exn:fail:contract:divide-by-zero?\n (λ (e) (displayln \"Divided by zero\"))])\n (/ 1 0))\n", "language": "Racket" }, { "code": "sub div($a, $b) {\n my $r;\n try {\n $r = $a / $b;\n CATCH {\n default { note \"Unexpected exception, $_\" }\n }\n }\n return $r // Nil;\n}\nsay div(10,2);\nsay div(1, sin(0));\n", "language": "Raku" }, { "code": "multi div($a, $b) { return $a / $b }\nmulti div($a, $b where { $b == 0 }) { note 'Attempt to divide by zero.'; return Nil }\n\nsay div(10, 2);\nsay div(1, sin(0));\n", "language": "Raku" }, { "code": "REBOL [\n Title: \"Detect Divide by Zero\"\n URL: http://rosettacode.org/wiki/Divide_by_Zero_Detection\n]\n\n; The 'try' word returns an error object if the operation fails for\n; whatever reason. The 'error?' word detects an error object and\n; 'disarm' keeps it from triggering so I can analyze it to print the\n; appropriate message. Otherwise, any reference to the error object\n; will stop the program.\n\ndiv-check: func [\n\t\"Attempt to divide two numbers, report result or errors as needed.\"\n\tx y\n\t/local result\n] [\n\teither error? result: try [x / y][\n\t\tresult: disarm result\n\t\tprint [\"Caught\" result/type \"error:\" result/id]\n\t] [\n\t\tprint [x \"/\" y \"=\" result]\n\t]\n]\n\ndiv-check 12 2 ; An ordinary calculation.\ndiv-check 6 0 ; This will detect divide by zero.\ndiv-check \"7\" 0.0001 ; Other errors can be caught as well.\n", "language": "REBOL" }, { "code": "/*REXX program demonstrates detection and handling division by zero. */\nsignal on syntax /*handle all REXX syntax errors. */\nx = sourceline() /*being cute, x=is the size of this pgm*/\ny = x - x /*setting to zero the obtuse way. */\nz = x / y /*this'll trigger it, furrrr shurrre. */\nexit /*We're kaput. Ja vohl ! */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nerr: if rc==42 then do; say /*first, check for a specific error. */\n say center(' ***error*** ', 79, \"═\")\n say 'Division by zero detected at line ' @ ,\n \" and the REXX statement is:\"\n say sourceLine(@)\n say\n exit 42\n end\n say\n say center(' error! ', 79, \"*\")\n do #=1 for arg(); say; say arg(#); say\n end /*#*/\n exit 13\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsyntax: @=sigl; call err 'REXX program' condition(\"C\") 'error', condition('D'), ,\n 'REXX source statement (line' sigl\"):\", sourceLine(sigl)\n", "language": "REXX" }, { "code": "Try\n see 9/0\nCatch\n see \"Catch!\" + nl + cCatchError\nDone\n", "language": "Ring" }, { "code": " dcl-c DIVIDE_BY_ZERO 00102;\n\n dcl-s result zoned(5:2);\n dcl-s value1 zoned(5:2);\n dcl-s value2 zoned(5:2);\n\n value1 = 10;\n value2 = 0;\n\n monitor;\n eval(h) result = value1 / value2; // Using half rounding here for the eval result\n on-error DIVIDE_BY_ZERO;\n // Initialise the result to 0. Consider other messaging perhaps.\n result = 0;\n endmon;\n\n *inlr = *on;\n", "language": "RPGIV" }, { "code": "def div_check(x, y)\n begin\n x / y\n rescue ZeroDivisionError\n true\n else\n false\n end\nend\n", "language": "Ruby" }, { "code": "irb(main):010:0> div_check(5, 0)\n=> true\nirb(main):011:0> div_check(5.0, 0)\n=> false\n", "language": "Ruby" }, { "code": "def div_check(x, y)\n begin\n x.div y\n rescue ZeroDivisionError\n true\n else\n false\n end\nend\n", "language": "Ruby" }, { "code": "irb(main):010:0> div_check(5, 0)\n=> true\nirb(main):011:0> div_check(5.0, 0)\n=> true\n", "language": "Ruby" }, { "code": "on error goto [error]\na = 1 / 0\nwait\n\n[error] ' error 11 is division by zero err number\nIf err = 11 Then print \"Division by Zero\"\nwait\n", "language": "Run-BASIC" }, { "code": "fn test_division(numerator: u32, denominator: u32) {\n match numerator.checked_div(denominator) {\n Some(result) => println!(\"{} / {} = {}\", numerator, denominator, result),\n None => println!(\"{} / {} results in a division by zero\", numerator, denominator)\n }\n}\n\nfn main() {\n test_division(5, 4);\n test_division(4, 0);\n}\n", "language": "Rust" }, { "code": "object DivideByZero extends Application {\n\n def check(x: Int, y: Int): Boolean = {\n try {\n val result = x / y\n println(result)\n return false\n } catch {\n case x: ArithmeticException => {\n return true\n }\n }\n }\n\n println(\"divided by zero = \" + check(1, 0))\n\n def check1(x: Int, y: Int): Boolean = {\n import scala.util.Try\n Try(y/x).isFailure\n }\n println(\"divided by zero = \" + check1(1, 0))\n\n}\n", "language": "Scala" }, { "code": "$ include \"seed7_05.s7i\";\n include \"float.s7i\";\n\nconst proc: doDivide (in integer: numer, in integer: denom) is func\n begin\n block\n writeln(numer <& \" div \" <& denom <& \" = \" <& numer div denom);\n exception\n catch NUMERIC_ERROR:\n writeln(\"Division by zero detected.\");\n end block;\n end func;\n\nconst proc: doDivide (in float: numer, in float: denom) is func\n local\n var float: quotient is 0.0;\n begin\n quotient := numer / denom;\n if quotient <> Infinity and quotient <> -Infinity then\n writeln(numer <& \" / \" <& denom <& \" = \" <& quotient);\n else\n writeln(\"Division by zero detected.\");\n end if;\n end func;\n\nconst proc: main is func\n begin\n doDivide(10, 8);\n doDivide(1, 0);\n doDivide(10.0, 8.0);\n doDivide(1.0, 0.0);\n end func;\n", "language": "Seed7" }, { "code": "func div_check(a, b){\n var result = a/b\n result.abs == Inf ? nil : result\n}\n \nsay div_check(10, 2) # 5\nsay div_check(1, 0) # nil (detected)\n", "language": "Sidef" }, { "code": "func div_check(a, b){\n Perl.eval(\"#{a} / #{b}\")\n}\n \nsay div_check(10, 2) # 5\nsay div_check(1, 0) # nil (detected)\n", "language": "Sidef" }, { "code": "[ 1 / 0 ] on: Error do: [|:err| err return: PositiveInfinity].\n", "language": "Slate" }, { "code": "|didDivideByZero a b|\n\ndidDivideByZero := false.\na := 10.\nb := 0.\n[\n a/b\n] on: ZeroDivide do:[:ex |\n 'you tried to divide %P by zero\\n' printf:{ex suspendedContext receiver} on:Transcript.\n didDivideByZero := true.\n].\ndidDivideByZero ifTrue:[\n Transcript show:'bad bad bad, but I already told you in the handler'.\n].\n", "language": "Smalltalk" }, { "code": "testZeroDivide :=\n [:aBlock |\n\t[\n aBlock value.\n false\n ] on: ZeroDivide do: [true].\n ].\n\n\"Testing\"\ntestZeroDivide value: [2/1] \"------> false\"\ntestZeroDivide value: [2/0] \"------> true\"\n", "language": "Smalltalk" }, { "code": "[...] on:Error do: [...]\n", "language": "Smalltalk" }, { "code": "|a b result|\na := 10. b := 0.\nresult := [a / b] on:ZeroDivide do:[:ex | ex proceedWith:Float infinity].\nTranscript showCR:result.\n", "language": "Smalltalk" }, { "code": " define('zdiv(x,y)') :(zdiv_end)\nzdiv &errlimit = 1; setexit(.ztrap)\n zdiv = x / y :(return)\nztrap zdiv = ?(&errtype ? (14 | 262)) 'Division by zero' :s(continue)f(abort)\nzdiv_end\n\n* # Test and display\n output = '1/1 = ' zdiv(1,1) ;* Integers non-zero\n output = '1.0/1.0 = ' zdiv(1.0,1.0) ;* Reals non-zero\n output = '1/0 = ' zdiv(1,0) ;* Integers zero\n output = '1.0/0.0 = ' zdiv(1.0,0.0) ;* Reals zero\n output = 'Zero checks complete'\nend\n", "language": "SNOBOL4" }, { "code": "--#SET TERMINATOR @\n\nSET SERVEROUTPUT ON@\n\nCREATE OR REPLACE FUNCTION DIVISION(\n IN NUMERATOR DECIMAL(5, 3),\n IN DENOMINATOR DECIMAL(5, 3)\n ) RETURNS SMALLINT\n BEGIN\n DECLARE RET SMALLINT DEFAULT 1;\n DECLARE TMP DECIMAL(5, 3);\n DECLARE CONTINUE HANDLER FOR SQLSTATE '22012'\n SET RET = 1;\n\n SET RET = 0;\n SET TMP = NUMERATOR / DENOMINATOR;\n RETURN RET;\n END @\n\nVALUES DIVISION(10, 2)@\nVALUES DIVISION(10, 3)@\nVALUES DIVISION(10, 0)@\n", "language": "SQL-PL" }, { "code": "fun div_check (x, y) = (\n ignore (x div y);\n false\n) handle Div => true\n", "language": "Standard-ML" }, { "code": "fun div_check (x, y) =\n not (Real.isFinite (x / y))\n", "language": "Standard-ML" }, { "code": "proc div_check {x y} {\n if {[catch {expr {$x/$y}} result] == 0} {\n puts \"valid division: $x/$y=$result\"\n } else {\n if {$result eq \"divide by zero\"} {\n puts \"caught division by zero: $x/$y -> $result\"\n } else {\n puts \"caught another error: $x/$y -> $result\"\n }\n }\n}\n\nforeach denom {1 0 foo} {\n div_check 42 $denom\n}\n", "language": "Tcl" }, { "code": "proc div_check {x y} {\n try {\n puts \"valid division: $x/$y=[expr {$x/$y}]\"\n } trap {ARITH DIVZERO} msg {\n puts \"caught division by zero: $x/$y -> $msg\"\n } trap {ARITH DOMAIN} msg {\n puts \"caught bad division: $x/$y -> $msg\"\n } on error msg {\n puts \"caught another error: $x/$y -> $msg\"\n }\n}\n\nforeach {num denom} {42 1 42 0 42.0 0.0 0 0 0.0 0.0 0 foo} {\n div_check $num $denom\n}\n", "language": "Tcl" }, { "code": "WHEN error in\n PRINT 2 / 3\n PRINT 3 / 5\n PRINT 4 / 0\nUSE\n PRINT \"Error \"; EXTYPE; \"in the line\"; EXLINE\n PRINT EXTEXT$\nEND WHEN\nEND\n", "language": "True-BASIC" }, { "code": "@(do (defun div-check (x y)\n (catch (/ x y)\n (numeric_error (msg)\n 'div-check-failed))))\n@(bind good @(div-check 32 8))\n@(bind bad @(div-check 42 0))\n", "language": "TXR" }, { "code": "def div_check (int x, int y)\n\ttry\n\t\t/ x y\n\t\treturn false\n\tcatch divzeroerror\n\t\treturn true\n\tend try\nend\n", "language": "Ursa" }, { "code": "fn main() {\n\tdivide(0, 0)\t\n\tdivide(15, 0)\n\tdivide(15, 3)\n}\n\nfn divide(x f64, y f64) {\n\tresult := x/y\n\tif result.str().contains_any_substr([\"inf\",\"nan\"]) == true {\n\t\tprintln(\"Can\\'t divide by zero!\")\n\t\treturn\n\t}\n\tprintln(result)\n}\n", "language": "V-(Vlang)" }, { "code": "fn main() {\n\tdivide(0, 0)\t\n\tdivide(15, 0)\n\tdivide(15, 3)\n}\n\npub fn divide(x f64, y f64) {\n\tsucceed := divide_error_handler(x, y) or {\n\t\tprintln(err)\n\t\treturn\n\t}\n\tprintln(succeed)\n}\n\nfn divide_error_handler(x f64, y f64) !f64 {\n\tresult := x/y\n\tif result.str().contains_any_substr([\"inf\",\"nan\"]) == true {\n\t\treturn error(\"Can\\'t divide by zero!\")\n\t}\n\treturn result\n}\n", "language": "V-(Vlang)" }, { "code": "65 64 69 76 69 64 00000008'010E0000' 0000 1 desc:\t.ascid\t\"divide by zero\"\n 6F 72 65 7A 20 79 62 20 000E\n 0000 0016 2 .entry\thandler,0\n E5 AF 7F 0018 3 \tpushaq\tdesc\n 00000000'GF 01 FB 001B 4 \tcalls\t#1, g^lib$put_output\n 04 0022 5 \tret\n 0023 6\n 0000 0023 7 .entry\tmain,0\n 6D EE AF 9E 0025 8 \tmovab\thandler, (fp)\t;register exception handler\n 50 01 00 C7 0029 9 \tdivl3\t#0, #1, r0\n 04 002D 10 \tret\n 002E 11\n 002E 12 .end\tmain\n$ run dv\ndivide by zero\n", "language": "VAX-Assembly" }, { "code": "Option Explicit\n\nSub Main()\nDim Div\n If CatchDivideByZero(152, 0, Div) Then Debug.Print Div Else Debug.Print \"Error\"\n If CatchDivideByZero(152, 10, Div) Then Debug.Print Div Else Debug.Print \"Error\"\nEnd Sub\n\nFunction CatchDivideByZero(Num, Den, Div) As Boolean\n On Error Resume Next\n Div = Num / Den\n If Err = 0 Then CatchDivideByZero = True\n On Error GoTo 0\nEnd Function\n", "language": "VBA" }, { "code": "Function div(num,den)\n\tOn Error Resume Next\n\tn = num/den\n\tIf Err.Number <> 0 Then\n\t\tdiv = Err.Description & \" is not allowed.\"\n\tElse\n\t\tdiv = n\n\tEnd If\nEnd Function\n\nWScript.StdOut.WriteLine div(6,3)\nWScript.StdOut.WriteLine div(6,0)\nWScript.StdOut.WriteLine div(7,-4)\n", "language": "VBScript" }, { "code": "Module DivByZeroDetection\n\n Sub Main()\n Console.WriteLine(safeDivision(10, 0))\n End Sub\n\n Private Function safeDivision(v1 As Integer, v2 As Integer) As Boolean\n Try\n Dim answer = v1 / v2\n Return False\n Catch ex As Exception\n Return True\n End Try\n End Function\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "var checkDivByZero = Fn.new { |a, b|\n var c = a / b\n if (c.isInfinity || c.isNan) return true\n return false\n}\n\nSystem.print(\"Division by zero?\")\nSystem.print(\" 0 / 0 -> %(checkDivByZero.call(0, 0))\")\nSystem.print(\" 1 / 0 -> %(checkDivByZero.call(1, 0))\")\nSystem.print(\" 1 / 1 -> %(checkDivByZero.call(1, 1))\")\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes;\nint A, B;\n[Trap(false); \\turn off error trapping\nB:= 1234/(A-A); \\(error not detected at compile time)\nif GetErr then Text(0, \"Divide by zero\");\n]\n", "language": "XPL0" }, { "code": "func div_check(x, y) {\n if(catch(0x01))\n return 1;\n temp = x/y;\n return 0;\n}\n", "language": "Yorick" }, { "code": "fcn f(x,y){try{x/y}catch(MathError){println(__exception)}}\n", "language": "Zkl" } ]
Detect-division-by-zero
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters\n", "language": "00-META" }, { "code": ";Task:\n\nGiven a character string &nbsp; (which may be empty, or have a length of zero characters):\n::* &nbsp; create a function/procedure/routine to:\n::::* &nbsp; determine if all the characters in the string are the same\n::::* &nbsp; indicate if or which character is different from the previous character\n::* &nbsp; display each string and its length &nbsp; (as the strings are being examined)\n::* &nbsp; a zero─length (empty) string shall be considered as all the same character(s)\n::* &nbsp; process the strings from left─to─right\n::* &nbsp; if &nbsp; &nbsp; &nbsp; all the same character, &nbsp; display a message saying such\n::* &nbsp; if not all the same character, &nbsp; then:\n::::* &nbsp; display a message saying such\n::::* &nbsp; display what character is different\n::::* &nbsp; only the 1<sup>st</sup> different character need be displayed\n::::* &nbsp; display where the different character is in the string\n::::* &nbsp; the above messages can be part of a single message\n::::* &nbsp; display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values &nbsp; (strings):\n:::* &nbsp; a string of length &nbsp; 0 &nbsp; (an empty string)\n:::* &nbsp; a string of length &nbsp; 3 &nbsp; which contains three blanks\n:::* &nbsp; a string of length &nbsp; 1 &nbsp; which contains: &nbsp; '''2'''\n:::* &nbsp; a string of length &nbsp; 3 &nbsp; which contains: &nbsp; '''333'''\n:::* &nbsp; a string of length &nbsp; 3 &nbsp; which contains: &nbsp; '''.55'''\n:::* &nbsp; a string of length &nbsp; 6 &nbsp; which contains: &nbsp; '''tttTTT'''\n:::* &nbsp; a string of length &nbsp; 9 &nbsp; with a blank in the middle: &nbsp; '''4444 &nbsp; 444k'''\n\n\n\nShow all output here on this page.\n\n{{Template:Strings}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F analyze(s)\n print(‘Examining [’s‘] which has a length of ’s.len‘:’)\n I s.len > 1\n V b = s[0]\n L(c) s\n V i = L.index\n I c != b\n print(‘ Not all characters in the string are the same.’)\n print(‘ '’c‘' (0x’hex(c.code)‘) is different at position ’i)\n R\n\n print(‘ All characters in the string are the same.’)\n\nV strs = [‘’, ‘ ’, ‘2’, ‘333’, ‘.55’, ‘tttTTT’, ‘4444 444k’]\nL(s) strs\n analyze(s)\n", "language": "11l" }, { "code": "PROC PrintBH(BYTE a)\n BYTE ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F]\n\n Put(hex(a RSH 4))\n Put(hex(a&$0F))\nRETURN\n\nPROC Test(CHAR ARRAY s)\n BYTE i,pos\n\n pos=0\n FOR i=2 TO s(0)\n DO\n IF s(i)#s(1) THEN\n pos=i\n EXIT\n FI\n OD\n\n PrintF(\"\"\"%S\"\" (len=%B) -> \",s,s(0))\n IF pos=0 THEN\n PrintE(\"all characters are the same.\")\n ELSE\n PrintF(\"\"\"%C\"\" (hex=$\",s(pos))\n PrintBH(s(pos))\n PrintF(\") is the first difference at pos. %B.%E\",pos)\n FI\n PutE()\nRETURN\n\nPROC Main()\n Test(\"\")\n Test(\" \")\n Test(\"2\")\n Test(\"333\")\n Test(\".55\")\n Test(\"tttTTT\")\n Test(\"4444 444k\")\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;\nwith Ada.Text_IO; use Ada.Text_IO;\nprocedure Test_All_Chars_Are_Same is\n procedure All_Chars_Are_Same (S : in String) is\n First_Diff : Natural := 0;\n begin\n Put_Line (\"Input = \"\"\" & S & \"\"\", length =\" & S'Length'Image);\n for I in S'First + 1 .. S'Last loop\n if S(I) /= S(S'First) then\n First_Diff := I;\n exit;\n end if;\n end loop;\n if First_Diff = 0 then\n Put_Line (\" All characters are the same.\");\n else\n Put (\" First difference at position\" & First_Diff'Image &\n \", character = '\" & S(First_Diff) &\n \"', hex = \");\n Put (Character'Pos (S(First_Diff)), Width => 0, Base => 16);\n New_Line;\n end if;\n end All_Chars_Are_Same;\nbegin\n All_Chars_Are_Same (\"\");\n All_Chars_Are_Same (\" \");\n All_Chars_Are_Same (\"2\");\n All_Chars_Are_Same (\"333\");\n All_Chars_Are_Same (\".55\");\n All_Chars_Are_Same (\"tttTTT\");\n All_Chars_Are_Same (\"4444 444k\");\nend Test_All_Chars_Are_Same;\n", "language": "Ada" }, { "code": "BEGIN\n # return the position of the first different character in s #\n # or UPB s + 1 if all the characters are the same #\n OP FIRSTDIFF = ( STRING s )INT:\n IF UPB s <= LWB s\n THEN\n # 0 or 1 character #\n UPB s + 1\n ELSE\n # two or more characters #\n INT result := LWB s + 1;\n CHAR c1 = s[ LWB s ];\n FOR s pos FROM LWB s + 1 TO UPB s WHILE s[ s pos ] = c1 DO result +:= 1 OD;\n result\n FI # FIRSTDIFF # ;\n # convert a character to a hex string #\n PROC hex = ( CHAR c )STRING:\n BEGIN\n STRING result := \"\";\n INT n := ABS c;\n IF n = 0\n THEN\n result := \"0\"\n ELSE\n WHILE n > 0 DO\n INT d = n MOD 16;\n n OVERAB 16;\n IF d < 10\n THEN REPR ( d + ABS \"0\" )\n ELSE REPR ( ( d - 10 ) + ABS \"a\" )\n FI +=: result\n OD\n FI;\n result\n END # hex # ;\n # show whether s contains all the same character of the first diff #\n PROC show first diff = ( STRING s )VOID:\n IF print( ( \"\"\"\", s, \"\"\" (length \", whole( ( UPB s + 1 ) - LWB s, 0 ), \"): \" ) );\n INT diff pos = FIRSTDIFF s;\n diff pos > UPB s\n THEN\n # all characters the same #\n print( ( \"all characters are the same\", newline ) )\n ELSE\n # not all characters are the same #\n print( ( \"first different character \"\"\"\n , s[ diff pos ]\n , \"\"\"(0x\", hex( s[ diff pos ] )\n , \") at position: \"\n , whole( diff pos, 0 )\n , newline\n )\n )\n FI # show first diff # ;\n # task test cases #\n show first diff( \"\" );\n show first diff( \" \" );\n show first diff( \"2\" );\n show first diff( \"333\" );\n show first diff( \".55\" );\n show first diff( \"tttTTT\" );\n show first diff( \"4444 444k\" );\n show first diff( \"4444|444k\" )\nEND\n", "language": "ALGOL-68" }, { "code": " 10 DATA \"\",\" \",\"2\",\"333\",\".55\",\"tttTTT\",\"4444 444k\"\n 20 LET Q$ = CHR$ (34)\n 30 HOME\n 40 FOR E = 1 TO 7\n 50 READ S$\n 60 GOSUB 100\n 70 PRINT O$\" IN\"M$Q$S$Q$\" OF LENGTH \"L\".\";\n 80 NEXT E\n 90 END\n 100 GOSUB 200\n 110 PRINT M$M$;\n 120 LET M$ = CHR$ (13)\n 130 LET O$ = \"ALL OF THE CHARACTERS ARE THE SAME\"\n 140 IF SAME THEN RETURN\n 150 PRINT \"THE FIRST DIFFERENT CHARACTER IS\"\n 160 PRINT TAB( I)Q$C$Q$;\n 170 PRINT \" ASCII \" ASC (C$)\" AT POSITION \";\n 180 LET O$ = STR$ (I)\n 190 RETURN\n 200 LET C$ = LEFT$ (S$,1)\n 210 LET L = LEN (S$)\n 220 FOR I = 1 TO L\n 230 IF C$ = MID$ (S$,I,1) THEN NEXT I\n 240 LET C$ = MID$ (S$,I,1)\n 250 LET SAME = C$ = \"\"\n 260 RETURN\n", "language": "Applesoft-BASIC" }, { "code": "strings: [\n \"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\",\n \"4444 444k\", \"pépé\", \"🐶🐶🐺🐶\", \"🎄🎄🎄🎄\"\n]\n\nallSameChars?: function [str][\n if empty? str -> return ø\n current: first str\n loop.with:'i str 'ch [\n if ch <> current -> return i\n ]\n return ø\n]\n\nloop strings 's [\n prints [\"\\\"\" ++ s ++ \"\\\"\" ~\"(size |size s|):\"]\n firstNotSame: allSameChars? s\n if? null? firstNotSame -> print \"all the same.\"\n else -> print ~\"first different char `|get s firstNotSame|` at position |firstNotSame|.\"\n]\n", "language": "Arturo" }, { "code": "testCases := [\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 4444k\"]\nfor key, str in testCases {\n\tMsgBox % \"Examining `'\" str \"`' which has a length of \" StrLen(str) \":`n\"\n\tif (StrLen(str) == 0) or (StrLen(str) == 1) {\n\t\tMsgBox % \" All characters in the string are the same.`n\"\n\t\tcontinue\n\t}\n\tfirstChar := SubStr(str, 1, 1)\n\tLoop, Parse, str\n\t{\n\t\tif (firstChar != A_LoopField) {\n\t\t\thex := Format(\"0x{:x}\", Ord(A_LoopField))\n\t\t\tMsgBox % \" Not all characters in the string are the same.`n Character `'\" A_LoopField \"`' (\" hex \") is different at position \" A_Index \".`n\", *\n\t\t\tbreak\n\t\t}\n\t\tif (A_Index = StrLen(str))\n\t\t\tMsgBox % \" All characters in the string are the same.`n\", *\n\t}\n}\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f DETERMINE_IF_A_STRING_HAS_ALL_THE_SAME_CHARACTERS.AWK\nBEGIN {\n for (i=0; i<=255; i++) { ord_arr[sprintf(\"%c\",i)] = i } # build array[character]=ordinal_value\n n = split(\", ,2,333,.55,tttTTT,4444 444k\",arr,\",\")\n for (i in arr) {\n width = max(width,length(arr[i]))\n }\n width += 2\n fmt = \"| %-*s | %-6s | %-8s | %-8s | %-3s | %-8s |\\n\"\n head1 = head2 = sprintf(fmt,width,\"string\",\"length\",\"all same\",\"1st diff\",\"hex\",\"position\")\n gsub(/[^|\\n]/,\"-\",head1)\n printf(head1 head2 head1) # column headings\n for (i=1; i<=n; i++) {\n main(arr[i])\n }\n printf(head1) # column footing\n exit(0)\n}\nfunction main(str, c,first_diff,hex,i,leng,msg,position) {\n msg = \"yes\"\n leng = length(str)\n for (i=1; i<leng; i++) {\n c = substr(str,i+1,1)\n if (substr(str,i,1) != c) {\n msg = \"no\"\n first_diff = \"'\" c \"'\"\n hex = sprintf(\"%2X\",ord_arr[c])\n position = i + 1\n break\n }\n }\n printf(fmt,width,\"'\" str \"'\",leng,msg,first_diff,hex,position)\n}\nfunction max(x,y) { return((x > y) ? x : y) }\n", "language": "AWK" }, { "code": "get \"libhdr\"\n\nlet diffchar(s) = valof\n$( for i=2 to s%0\n unless s%i = s%1 resultis i\n resultis 0\n$)\n\nlet show(s) be\n$( let i = diffchar(s)\n writef(\"*\"%S*\" (length %N): \", s, s%0)\n test i=0\n do writes(\"all the same.*N\")\n or writef(\"'%C' at index %N.*N\", s%i, i)\n$)\n\nlet start() be\n$( show(\"\")\n show(\" \")\n show(\"2\")\n show(\"333\")\n show(\".55\")\n show(\"tttTTT\")\n show(\"4444 444k\")\n$)\n", "language": "BCPL" }, { "code": "Check←=´˘2⊸↕\nHex←⊏⟜(∾\"0A\"+⟜↕¨10‿26)16{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}\n\n{\n 𝕊 str:\n r←Check 2⊸↑⍟(0=≠)str\n •Out {\n ∧´r ? \"All characters are the same\" ;\n i←⊑r⊐0\n ch←(i+1)⊑str\n \"'\"∾ch∾\"' (hex: \"∾(Hex ch-@)∾\", index: \"∾(•Fmt i)∾\") mismatched in string '\"∾str∾\"'\"\n }\n}¨⟨\n \"\"\n \" \"\n \"2\"\n \"333\"\n \".55\"\n \"tttTTT\"\n \"4444 444k\"\n⟩\n", "language": "BQN" }, { "code": "All characters are the same\nAll characters are the same\nAll characters are the same\nAll characters are the same\n'5' (hex: 35, index: 0) mismatched in string '.55'\n'T' (hex: 54, index: 2) mismatched in string 'tttTTT'\n' ' (hex: 20, index: 3) mismatched in string '4444 444k'\n", "language": "BQN" }, { "code": "#include<string.h>\n#include<stdio.h>\n\nint main(int argc,char** argv)\n{\n int i,len;\n char reference;\n\n if(argc>2){\n printf(\"Usage : %s <Test String>\\n\",argv[0]);\n return 0;\n }\n\n if(argc==1||strlen(argv[1])==1){\n printf(\"Input string : \\\"%s\\\"\\nLength : %d\\nAll characters are identical.\\n\",argc==1?\"\":argv[1],argc==1?0:(int)strlen(argv[1]));\n return 0;\n }\n\n reference = argv[1][0];\n len = strlen(argv[1]);\n\n for(i=1;i<len;i++){\n if(argv[1][i]!=reference){\n printf(\"Input string : \\\"%s\\\"\\nLength : %d\\nFirst different character : \\\"%c\\\"(0x%x) at position : %d\\n\",argv[1],len,argv[1][i],argv[1][i],i+1);\n return 0;\n }\n }\n\n printf(\"Input string : \\\"%s\\\"\\nLength : %d\\nAll characters are identical.\\n\",argv[1],len);\n\n return 0;\n\n}\n", "language": "C" }, { "code": "/**\n * An example for RossetaCode - an example of string operation with wchar_t and\n * with old 8-bit characters. Anyway, it seem that C is not very UTF-8 friendly,\n * thus C# or C++ may be a better choice.\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n/*\n * The wide character version of the program is compiled if WIDE_CHAR is defined\n */\n#define WIDE_CHAR\n\n#ifdef WIDE_CHAR\n#define CHAR wchar_t\n#else\n#define CHAR char\n#endif\n\n/**\n * Find a character different from the preceding characters in the given string.\n *\n * @param s the given string, NULL terminated.\n *\n * @return the pointer to the occurence of the different character\n * or a pointer to NULL if all characters in the string\n * are exactly the same.\n *\n * @notice This function return a pointer to NULL also for empty strings.\n * Returning NULL-or-CHAR would not enable to compute the position\n * of the non-matching character.\n *\n * @warning This function compare characters (single-bytes, unicode etc.).\n * Therefore this is not designed to compare bytes. The NULL character\n * is always treated as the end-of-string marker, thus this function\n * cannot be used to scan strings with NULL character inside string,\n * for an example \"aaa\\0aaa\\0\\0\".\n */\nconst CHAR* find_different_char(const CHAR* s)\n{\n /* The code just below is almost the same regardles\n char or wchar_t is used. */\n\n const CHAR c = *s;\n while (*s && c == *s)\n {\n s++;\n }\n return s;\n}\n\n/**\n * Apply find_different_char function to a given string and output the raport.\n *\n * @param s the given NULL terminated string.\n */\nvoid report_different_char(const CHAR* s)\n{\n#ifdef WIDE_CHAR\n wprintf(L\"\\n\");\n wprintf(L\"string: \\\"%s\\\"\\n\", s);\n wprintf(L\"length: %d\\n\", wcslen(s));\n const CHAR* d = find_different_char(s);\n if (d)\n {\n /*\n * We have got the famous pointers arithmetics and we can compute\n * difference of pointers pointing to the same array.\n */\n wprintf(L\"character '%wc' (%#x) at %d\\n\", *d, *d, (int)(d - s));\n }\n else\n {\n wprintf(L\"all characters are the same\\n\");\n }\n wprintf(L\"\\n\");\n#else\n putchar('\\n');\n printf(\"string: \\\"%s\\\"\\n\", s);\n printf(\"length: %d\\n\", strlen(s));\n const CHAR* d = find_different_char(s);\n if (d)\n {\n /*\n * We have got the famous pointers arithmetics and we can compute\n * difference of pointers pointing to the same array.\n */\n printf(\"character '%c' (%#x) at %d\\n\", *d, *d, (int)(d - s));\n }\n else\n {\n printf(\"all characters are the same\\n\");\n }\n putchar('\\n');\n#endif\n}\n\n/* There is a wmain function as an entry point when argv[] points to wchar_t */\n\n#ifdef WIDE_CHAR\nint wmain(int argc, wchar_t* argv[])\n#else\nint main(int argc, char* argv[])\n#endif\n{\n if (argc < 2)\n {\n report_different_char(L\"\");\n report_different_char(L\" \");\n report_different_char(L\"2\");\n report_different_char(L\"333\");\n report_different_char(L\".55\");\n report_different_char(L\"tttTTT\");\n report_different_char(L\"4444 444k\");\n }\n else\n {\n report_different_char(argv[1]);\n }\n\n return EXIT_SUCCESS;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <string_view>\n\nvoid all_characters_are_the_same(std::string_view str) {\n size_t len = str.length();\n std::cout << \"input: \\\"\" << str << \"\\\", length: \" << len << '\\n';\n if (len > 0) {\n char ch = str[0];\n for (size_t i = 1; i < len; ++i) {\n if (str[i] != ch) {\n std::cout << \"Not all characters are the same.\\n\";\n std::cout << \"Character '\" << str[i] << \"' (hex \" << std::hex\n << static_cast<unsigned int>(str[i])\n << \") at position \" << std::dec << i + 1\n << \" is not the same as '\" << ch << \"'.\\n\\n\";\n return;\n }\n }\n }\n std::cout << \"All characters are the same.\\n\\n\";\n}\n\nint main() {\n all_characters_are_the_same(\"\");\n all_characters_are_the_same(\" \");\n all_characters_are_the_same(\"2\");\n all_characters_are_the_same(\"333\");\n all_characters_are_the_same(\".55\");\n all_characters_are_the_same(\"tttTTT\");\n all_characters_are_the_same(\"4444 444k\");\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\n\nnamespace AllSame {\n class Program {\n static void Analyze(string s) {\n Console.WriteLine(\"Examining [{0}] which has a length of {1}:\", s, s.Length);\n if (s.Length > 1) {\n var b = s[0];\n for (int i = 1; i < s.Length; i++) {\n var c = s[i];\n if (c != b) {\n Console.WriteLine(\" Not all characters in the string are the same.\");\n Console.WriteLine(\" '{0}' (0x{1:X02}) is different at position {2}\", c, (int)c, i);\n return;\n }\n }\n\n }\n Console.WriteLine(\" All characters in the string are the same.\");\n }\n\n static void Main() {\n var strs = new string[] { \"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\" };\n foreach (var str in strs) {\n Analyze(str);\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(defn check-all-chars-same [s]\n (println (format \"String (%s) of len: %d\" s (count s)))\n (let [num-same (-> (take-while #(= (first s) %) s)\n count)]\n (if (= num-same (count s))\n (println \"...all characters the same\")\n (println (format \"...character %d differs - it is 0x%x\"\n num-same\n (byte (nth s num-same)))))))\n\n (map check-all-chars-same\n [\"\"\n \" \"\n \"2\"\n \"333\"\n \".55\"\n \"tttTTT\"\n \"4444 444k\"])\n", "language": "Clojure" }, { "code": "(defun strequ (&rest str)\n (if (not str) (setf str (list \"\" \" \" \"2\" \"333\" \".55\" \"tttTTT\" \"4444 444k\")))\n (dolist (s str)\n (do ((i 0 (1+ i)))\n ((cond\n ((= i (length s))\n (format t \"\\\"~a\\\" [~d] : All characters are identical.~%\" s (length s)) t)\n ((char/= (char s i) (char s 0))\n (format t \"\\\"~a\\\" [~d] : '~c' (0x~0x) at index ~d is different.~%\" s (length s) (char s i) (char-int (char s i)) i) t))))))\n", "language": "Common-Lisp" }, { "code": "import std.stdio;\n\nvoid analyze(string s) {\n writefln(\"Examining [%s] which has a length of %d:\", s, s.length);\n if (s.length > 1) {\n auto b = s[0];\n foreach (i, c; s[1..$]) {\n if (c != b) {\n writeln(\" Not all characters in the string are the same.\");\n writefln(\" '%c' (0x%x) is different at position %d\", c, c, i);\n return;\n }\n }\n }\n writeln(\" All characters in the string are the same.\");\n}\n\nvoid main() {\n auto strs = [\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\"];\n foreach (str; strs) {\n analyze(str);\n }\n}\n", "language": "D" }, { "code": "program Determine_if_a_string_has_all_the_same_characters;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils;\n\nprocedure Analyze(s: string);\nvar\n b, c: char;\n i: Integer;\nbegin\n writeln(format('Examining [%s] which has a length of %d:', [s, s.Length]));\n if s.Length > 1 then\n begin\n b := s[1];\n for i := 2 to s.Length - 1 do\n begin\n c := s[i];\n if c <> b then\n begin\n writeln(' Not all characters in the string are the same.');\n writeln(format(' \"%s\" 0x%x is different at position %d', [c, Ord(c), i]));\n Exit;\n end;\n end;\n end;\n writeln(' All characters in the string are the same.');\nend;\n\nvar\n TestCases: array of string = ['', ' ', '2', '333', '.55', 'tttTTT', '4444 444k'];\n w: string;\n\nbegin\n for w in TestCases do\n Analyze(w);\n Readln;\nend.\n", "language": "Delphi" }, { "code": "func$ hex h .\n for d in [ h div 16 h mod 16 ]\n if d > 9\n d += 7\n .\n h$ &= strchar (d + 48)\n .\n return h$\n.\nproc samechar s$ . .\n s$[] = strchars s$\n for i = 2 to len s$[]\n if s$[i] <> s$[i - 1]\n h = strcode s$[i]\n write \" --> different: '\" & s$[i] & \"' (\" & hex h & \"h)\"\n print \"' position: \" & i\n return\n .\n .\n print \" --> ok\"\n.\nrepeat\n s$ = input\n until s$ = \"EOF\"\n print \"'\" & s$ & \"'\" & \" length \" & len s$\n samechar s$\n print \"\"\n.\ninput_data\n\n\n2\n333\n.55\ntttTTT\n4444 444k\nEOF\n", "language": "EasyLang" }, { "code": "-module(string_examples).\n-export([examine_all_same/1, all_same_examples/0]).\n\nall_same_characters([], _Offset) ->\n all_same;\nall_same_characters([_], _Offset) ->\n all_same;\nall_same_characters([X, X | Rest], Offset) ->\n all_same_characters([X | Rest], Offset + 1);\nall_same_characters([X, Y | _Rest], Offset) when X =/= Y ->\n {not_all_same, Y, Offset + 1}.\n\nexamine_all_same(String) ->\n io:format(\"String \\\"~ts\\\" of length ~p:~n\", [String, length(String)]),\n case all_same_characters(String, 0) of\n all_same ->\n io:format(\" All characters are the same.~n~n\");\n {not_all_same, OffendingChar, Offset} ->\n io:format(\" Not all characters are the same.~n\"),\n io:format(\" Char '~tc' (0x~.16b) at offset ~p differs.~n~n\",\n [OffendingChar, OffendingChar, Offset])\n end.\n\nall_same_examples() ->\n Strings = [\"\",\n \" \",\n \"2\",\n \"333\",\n \".55\",\n \"tttTTT\",\n \"4444 444k\",\n \"pépé\",\n \"🐶🐶🐺🐶\",\n \"🎄🎄🎄🎄\"],\n lists:foreach(fun examine_all_same/1, Strings).\n", "language": "Erlang" }, { "code": "// Determine if a string has all the same characters. Nigel Galloway: June 9th., 2020\nlet fN n=if String.length n=0 then None else n.ToCharArray()|>Array.tryFindIndex(fun g->g<>n.[0])\n\nlet allSame n=match fN n with\n Some g->printfn \"First different character in <<<%s>>> (length %d) is hex %x at position %d\" n n.Length (int n.[g]) g\n |_->printfn \"All Characters are the same in <<<%s>>> (length %d)\" n n.Length\n\n\nallSame \"\"\nallSame \" \"\nallSame \"2\"\nallSame \"333\"\nallSame \".55\"\nallSame \"tttTTT\"\nallSame \"4444 444k\"\n", "language": "F-Sharp" }, { "code": "USING: formatting io kernel math.parser sequences ;\n\n: find-diff ( str -- i elt ) dup ?first [ = not ] curry find ;\n: len. ( str -- ) dup length \"%u — length %d — \" printf ;\n: same. ( -- ) \"contains all the same character.\" print ;\n: diff. ( -- ) \"contains a different character at \" write ;\n\n: not-same. ( i elt -- )\n dup >hex diff. \"index %d: '%c' (0x%s)\\n\" printf ;\n\n: sameness-report. ( str -- )\n dup len. find-diff dup [ not-same. ] [ 2drop same. ] if ;\n\n{\n \"\"\n \" \"\n \"2\"\n \"333\"\n \".55\"\n \"tttTTT\"\n \"4444 444k\"\n} [ sameness-report. ] each\n", "language": "Factor" }, { "code": ": samechars? ( str-addr str-len -- )\n [char] \" emit 2dup type [char] \" emit .\" length: \" dup . .\" -> \"\n dup 1 > if\n over c@ swap 1 do\n over i + c@ over <> if\n .\" different character '\" drop i + c@ dup emit\n .\" ' ($\" hex 1 .r .\" ) at \" decimal i . cr unloop exit\n then\n loop\n then 2drop .\" all characters are the same\" cr ;\n\ns\" \" samechars?\ns\" \" samechars?\ns\" 2\" samechars?\ns\" 333\" samechars?\ns\" .55\" samechars?\ns\" tttTTT\" samechars?\ns\" 4444 444k\" samechars?\n", "language": "Forth" }, { "code": "program demo_verify\nimplicit none\n call homogeneous('')\n call homogeneous('2')\n call homogeneous('333')\n call homogeneous('.55')\n call homogeneous('tttTTT')\n call homogeneous('4444 444k')\ncontains\n\nsubroutine homogeneous(str)\ncharacter(len=*),intent(in) :: str\ncharacter(len=:),allocatable :: ch\ncharacter(len=*),parameter :: g='(*(g0))'\ninteger :: where\n if(len(str)>0)then;ch=str(1:1);else;ch='';endif\n where=verify(str,ch)\n if(where.eq.0)then\n write(*,g)'STR: \"',str,'\" LEN: ',len(str),'. All chars are a ','\"'//ch//'\"'\n else\n write(*,g)'STR: \"',str,'\" LEN: ',len(str), &\n & '. Multiple chars found. First difference at position ',where, &\n & ' where a ','\"'//str(where:where)//'\"(hex:',hex(str(where:where)),') was found.'\n write(*,g)repeat(' ',where+5),'^'\n endif\nend subroutine homogeneous\n\nfunction hex(ch) result(hexstr)\ncharacter(len=1),intent(in) :: ch\ncharacter(len=:),allocatable :: hexstr\n hexstr=repeat(' ',100)\n write(hexstr,'(Z0)')ch\n hexstr=trim(hexstr)\nend function hex\n\nend program demo_verify\n", "language": "Fortran" }, { "code": "dim as string s, nxt\n\ninput \"Enter string: \", s\n\nif len(s)<2 then 'A string with one or zero characters passes by default\n print \"All characters are the same.\"\n end\nend if\n\ndim as ubyte i\n\nfor i = 1 to len(s)-1\n nxt = mid(s, i+1, 1)\n if mid(s, i, 1)<>nxt then 'if any character differs from the previous one\n print \"First non-matching char is \"+nxt\n print \"It occurs at position \"+str(i+1)\n print \"Its hex value is \"+hex(asc(nxt))\n end\n end if\nnext i\n\n'otherwise, success!\nprint \"All characters are the same.\"\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc analyze(s string) {\n chars := []rune(s)\n le := len(chars)\n fmt.Printf(\"Analyzing %q which has a length of %d:\\n\", s, le)\n if le > 1 {\n for i := 1; i < le; i++ {\n if chars[i] != chars[i-1] {\n fmt.Println(\" Not all characters in the string are the same.\")\n fmt.Printf(\" %q (%#[1]x) is different at position %d.\\n\\n\", chars[i], i+1)\n return\n }\n }\n }\n fmt.Println(\" All characters in the string are the same.\\n\")\n}\n\nfunc main() {\n strings := []string{\n \"\",\n \" \",\n \"2\",\n \"333\",\n \".55\",\n \"tttTTT\",\n \"4444 444k\",\n \"pépé\",\n \"🐶🐶🐺🐶\",\n \"🎄🎄🎄🎄\",\n }\n for _, s := range strings {\n analyze(s)\n }\n}\n", "language": "Go" }, { "code": "class Main {\n static void main(String[] args) {\n String[] tests = [\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\"]\n for (String s : tests) {\n analyze(s)\n }\n }\n\n static void analyze(String s) {\n println(\"Examining [$s] which has a length of ${s.length()}\")\n if (s.length() > 1) {\n char firstChar = s.charAt(0)\n int lastIndex = s.lastIndexOf(firstChar as String)\n if (lastIndex != 0) {\n println(\"\\tNot all characters in the string are the same.\")\n println(\"\\t'$firstChar' (0x${Integer.toHexString(firstChar as Integer)}) is different at position $lastIndex\")\n return\n }\n }\n println(\"\\tAll characters in the string are the same.\")\n }\n}\n", "language": "Groovy" }, { "code": "10 'SAVE\"SAMECHAR\", A\n20 DEFINT A-Z\n30 DATA \"\",\" \",\"2\",\"333\",\".55\",\"tttTTT\",\"4444 444k\", \"FIN\"\n40 ' Main program cycle\n50 CLS\n60 PRINT \"Program SameChar\"\n70 PRINT \"Determines if a string has the same character or not.\"\n80 PRINT\n90 WHILE S$<>\"FIN\"\n100 READ S$\n110 IF S$=\"FIN\" THEN 150\n120 GOSUB 190 ' Revision subroutine\n130 PRINT \"'\";S$;\"' of length\";LEN(S$);\n140 IF I<2 THEN PRINT \"contains all the same character.\" ELSE PRINT \"is different at possition\";STR$(I);\": '\";DC$; \"' (0x\"; HEX$(ASC(DC$)); \")\"\n150 WEND\n160 PRINT\n170 PRINT \"End of program run.\"\n180 END\n190 ' DifChar subroutine\n200 C$ = LEFT$(S$,1)\n210 I = 1\n220 DC$=\"\"\n230 WHILE I<LEN(S$) AND DC$=\"\"\n240 IF MID$(S$,I,1)<>C$ THEN DC$=MID$(S$,I,1) ELSE I=I+1\n250 WEND\n260 IF DC$=\"\" THEN I=1\n270 RETURN\n", "language": "GW-BASIC" }, { "code": "import Numeric (showHex)\nimport Data.List (span)\nimport Data.Char (ord)\n\ninconsistentChar :: Eq a => [a] -> Maybe (Int, a)\ninconsistentChar [] = Nothing\ninconsistentChar xs@(x:_) =\n let (pre, post) = span (x ==) xs\n in if null post\n then Nothing\n else Just (length pre, head post)\n\n\n---------------------------TEST----------------------------\nsamples :: [String]\nsamples = [\" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444\"]\n\nmain :: IO ()\nmain = do\n let w = succ . maximum $ length <$> samples\n justifyRight n c = (drop . length) <*> (replicate n c ++)\n f = (++ \"' -> \") . justifyRight w ' ' . ('\\'' :)\n (putStrLn . unlines) $\n (\\s ->\n maybe\n (f s ++ \"consistent\")\n (\\(n, c) ->\n f s ++\n \"inconsistent '\" ++\n c : \"' (0x\" ++ showHex (ord c) \")\" ++ \" at char \" ++ show (succ n))\n (inconsistentChar s)) <$>\n samples\n", "language": "Haskell" }, { "code": "import Data.List (findIndex)\n\ninconsistentChar :: Eq a => [a] -> Maybe (Int, a)\ninconsistentChar [] = Nothing\ninconsistentChar xs@(x:_) = findIndex (x /=) xs >>= Just . ((,) <*> (xs !!))\n", "language": "Haskell" }, { "code": "(function check-all-chars-same string\n (print \"String (\" string \") of len: \" (len string))\n (let num-same (count-while (= (0 string)) string))\n (return-when (= num-same (len string))\n (print \"...all characters the same\"))\n (print (pad-left \" \" (+ 9 num-same) \"^\"))\n (print \"...character \" num-same \" differs - it is 0x\"\n (to-base 16 (char-code (num-same string)))))\n\n(map check-all-chars-same [\"\" \" \" \"2\" \"333\" \".55\" \"tttTTT\" \"4444 444k\"])\n", "language": "Haskell" }, { "code": "require'convert'\ntask=: {{\n if. 1>:#t=. ~.y do.\n echo 'all ',(\":#y),' character(s) same in \"',y,'\"'\n else.\n j=. \":1+y i. ch=.1{t\n echo '\"',ch,'\" (hex: ',(hfd 3 u:ch),', character ',j,' of ',(\":#y),') differs from previous characters in \"',y,'\"'\n end.\n}}\n", "language": "J" }, { "code": " task@>'';' ';'2';'333';'.55';'tttTTT';'4444 444k'\nall 0 character(s) same in \"\"\nall 3 character(s) same in \" \"\nall 1 character(s) same in \"2\"\nall 3 character(s) same in \"333\"\n\"5\" (hex: 35, character 2 of 3) differs from previous characters in \".55\"\n\"T\" (hex: 54, character 4 of 6) differs from previous characters in \"tttTTT\"\n\" \" (hex: 20, character 5 of 9) differs from previous characters in \"4444 444k\"\n", "language": "J" }, { "code": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n", "language": "Java" }, { "code": "public static void main(String[] args) {\n String[] strings = {\n \"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"5\", \"4444 444k\"\n };\n for (String string : strings)\n System.out.println(printCompare(string));\n}\n\nstatic String printCompare(String string) {\n String stringA = \"'%s' %d\".formatted(string, string.length());\n Pattern pattern = Pattern.compile(\"(.)\\\\1*\");\n Matcher matcher = pattern.matcher(string);\n StringBuilder stringB = new StringBuilder();\n /* 'Matcher' works dynamically, so we'll have to denote a change */\n boolean difference = false;\n char character;\n String newline = System.lineSeparator();\n while (matcher.find()) {\n if (matcher.start() != 0) {\n character = matcher.group(1).charAt(0);\n stringB.append(newline);\n stringB.append(\" Char '%s' (0x%x)\".formatted(character, (int) character));\n stringB.append(\" @ index %d\".formatted(matcher.start()));\n difference = true;\n }\n }\n if (!difference)\n stringB.append(newline).append(\" All characters are the same\");\n return stringA + stringB;\n}\n", "language": "Java" }, { "code": "public class Main{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\"};\n\t\tfor(String s:tests)\n\t\t\tanalyze(s);\n\t}\n\n\tpublic static void analyze(String s){\n\t\tSystem.out.printf(\"Examining [%s] which has a length of %d:\\n\", s, s.length());\n\t\tif(s.length() > 1){\n\t\t\tchar firstChar = s.charAt(0);\n\t\t\tint lastIndex = s.lastIndexOf(firstChar);\n\t\t\tif(lastIndex != 0){\n\t\t\t\tSystem.out.println(\"\\tNot all characters in the string are the same.\");\n\t\t\t\tSystem.out.printf(\"\\t'%c' (0x%x) is different at position %d\\n\", firstChar, (int) firstChar, lastIndex);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"\\tAll characters in the string are the same.\");\n\t}\n}\n", "language": "Java" }, { "code": "import java.util.OptionalInt;\n\npublic final class AllSameCharacters {\n\n\tpublic static void main(String[] aArgs) {\n\t\tString[] words = { \"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\" };\n\t\tfor ( String word : words ) {\n\t\t\tanalyse(word);\n\t\t}\t\t\n\t}\n\t\n\tprivate static void analyse(String aText) {\n\t\tSystem.out.println(\"Examining \\\"\" + aText + \"\\\", which has length \" + aText.length() + \":\");\n\n\t\tOptionalInt mismatch = aText.chars().filter( ch -> ch != aText.charAt(0) ).findFirst();\t\t\n\t\t\n\t\tif ( mismatch.isPresent() ) {\n\t\t\tchar fault = (char) mismatch.getAsInt();\n\t\t\tSystem.out.println(\" Not all characters in the string are the same.\");\n\t\t\tSystem.out.println(\" Character \\\"\" + fault + \"\\\" (\" + Integer.toHexString((char) fault)\n\t\t\t + \") is different at index \" + aText.indexOf(fault));\n\t\t} else {\n\t\t\tSystem.out.println(\" All characters in the string are the same.\");\t\t\t\n\t\t}\t\t\n\t}\n\n}\n", "language": "Java" }, { "code": "const check = s => {\n const arr = [...s];\n const at = arr.findIndex(\n (v, i) => i === 0 ? false : v !== arr[i - 1]\n )\n const l = arr.length;\n const ok = at === -1;\n const p = ok ? \"\" : at + 1;\n const v = ok ? \"\" : arr[at];\n const vs = v === \"\" ? v : `\"${v}\"`\n const h = ok ? \"\" : `0x${v.codePointAt(0).toString(16)}`;\n console.log(`\"${s}\" => Length:${l}\\tSame:${ok}\\tPos:${p}\\tChar:${vs}\\tHex:${h}`)\n}\n\n['', ' ', '2', '333', '.55', 'tttTTT', '4444 444k', '🐶🐶🐺🐶', '🎄🎄🎄🎄'].forEach(check)\n", "language": "JavaScript" }, { "code": "(() => {\n 'use strict';\n\n // ---------- FIRST INCONSISTENT CHARACTER -----------\n\n // inconsistentChar :: String -> Maybe (Char, Int)\n const inconsistentChar = s =>\n // Just the first inconsistent character in a\n // string, paired with the index of its position,\n // or Nothing if all of the characters in a string\n // are the same.\n 2 > s.length ? (\n Nothing()\n ) : (() => {\n const [h, ...t] = s;\n const i = t.findIndex(c => h !== c);\n return -1 !== i ? (\n Just([t[i], 1 + i])\n ) : Nothing();\n })();\n\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () =>\n fTable(\n 'First inconsistent character:\\n'\n )(\n s => `${quoted(\"'\")(s)} (${[...s].length} chars)`\n )(\n maybe('None')(pair => {\n const c = pair[0];\n return `${quoted(\"'\")(c)} at index ` + (\n `${pair[1]} (${showHex(ord(c))})`\n );\n })\n )(\n inconsistentChar\n )([\n '', ' ', '2', '333', '.55',\n 'tttTTT', '4444 444k',\n '🐶🐶🐺🐶', '🎄🎄🎄🎄'\n ]);\n\n\n // ----------- REUSABLE GENERIC FUNCTIONS ------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n\n // fTable :: String -> (a -> String) ->\n // (b -> String) -> (a -> b) -> [a] -> String\n const fTable = s =>\n // Heading -> x display function ->\n // fx display function ->\n // f -> values -> tabular string\n xShow => fxShow => f => xs => {\n const\n ys = xs.map(xShow),\n w = Math.max(...ys.map(length));\n return s + '\\n' + zipWith(\n a => b => a.padStart(w, ' ') + ' -> ' + b\n )(ys)(\n xs.map(x => fxShow(f(x)))\n ).join('\\n');\n };\n\n\n // maybe :: b -> (a -> b) -> Maybe a -> b\n const maybe = v =>\n // Default value (v) if m is Nothing, or f(m.Just)\n f => m => m.Nothing ? (\n v\n ) : f(m.Just);\n\n\n // showHex :: Int -> String\n const showHex = n =>\n // Hexadecimal string for a given integer.\n '0x' + n.toString(16);\n\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n 'GeneratorFunction' !== xs.constructor\n .constructor.name ? (\n xs.length\n ) : Infinity;\n\n\n // list :: StringOrArrayLike b => b -> [a]\n const list = xs =>\n // xs itself, if it is an Array,\n // or an Array derived from xs.\n Array.isArray(xs) ? (\n xs\n ) : Array.from(xs || []);\n\n\n // ord :: Char -> Int\n const ord = c =>\n // Unicode ordinal value of the character.\n c.codePointAt(0);\n\n\n // quoted :: Char -> String -> String\n const quoted = c =>\n // A string flanked on both sides\n // by a specified quote character.\n s => c + s + c;\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n // A map of f over each stepwise pair in\n // xs and ys, up to the length of the shorter\n // of those lists.\n xs => ys => {\n const\n n = Math.min(length(xs), length(ys)),\n vs = take(n)(list(ys));\n return take(n)(list(xs))\n .map((x, i) => f(x)(vs[i]));\n };\n\n // MAIN ---\n return main()\n})();\n", "language": "JavaScript" }, { "code": "jq -rn '\n\n def firstdifferent:\n label $out\n | foreach explode[] as $i ({index:-1};\n .prev = .i | .i = $i | .index +=1;\n if .prev and $i != .prev then .index, break $out else empty end)\n // null ;\n\n def lpad($n): \" \"*($n-length) + \"\\\"\\(.)\\\"\" ;\n\n [\" \"*10, \"length\", \"same\", \"index\", \"char\"],\n (inputs\n | firstdifferent as $d\n | [lpad(10), length, ($d == null)] + (if $d then [$d, .[$d:$d+1]] else null end) )\n | @tsv\n'\n", "language": "Jq" }, { "code": " \tlength\tsame\tindex\tchar\n \"\"\t0\ttrue\n \" \"\t3\ttrue\n \"2\"\t1\ttrue\n \"333\"\t3\ttrue\n \".55\"\t3\tfalse\t1\t5\n \"tttTTT\"\t6\tfalse\t3\tT\n \"4444 444k\"\t9\tfalse\t4\t\n \"🐶🐶🐺🐶\"\t4\tfalse\t2\t🐺\n \"🎄🎄🎄🎄\"\t4\ttrue\n", "language": "Jq" }, { "code": "firstdifferent(s) = isempty(s) ? nothing : findfirst(x -> x != s[1], s)\n\nfunction testfunction(strings)\n println(\"String | Length | All Same | First Different(Hex) | Position\\n\" *\n \"-----------------------------------------------------------------------------\")\n for s in strings\n n = firstdifferent(s)\n println(rpad(s, 27), rpad(length(s), 9), n == nothing ? \"yes\" :\n rpad(\"no $(s[n]) ($(string(Int(s[n]), base=16)))\", 36) * string(n))\n end\nend\n\ntestfunction([\n\t\"\",\n\t\" \",\n\t\"2\",\n\t\"333\",\n \".55\",\n \"tttTTT\",\n \"4444 444k\",\n \"pépé\",\n \"🐶🐶🐺🐶\",\n \"🎄🎄🎄🎄\",\n])\n", "language": "Julia" }, { "code": "fun analyze(s: String) {\n println(\"Examining [$s] which has a length of ${s.length}:\")\n if (s.length > 1) {\n val b = s[0]\n for ((i, c) in s.withIndex()) {\n if (c != b) {\n println(\" Not all characters in the string are the same.\")\n println(\" '$c' (0x${Integer.toHexString(c.toInt())}) is different at position $i\")\n return\n }\n }\n }\n println(\" All characters in the string are the same.\")\n}\n\nfun main() {\n val strs = listOf(\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\")\n for (str in strs) {\n analyze(str)\n }\n}\n", "language": "Kotlin" }, { "code": "{def firstDifferingChar\n {def firstDifferingChar.r\n {lambda {:w :i :n}\n {if {or {> :i :n} {= {+ :i 1} {W.length :w}}}\n then all characters are the same\n else {if {not {W.equal? {W.get :i :w} {W.get {+ :i 1} :w}}}\n then at position {+ :i 1} {W.get :i :w} becomes {W.get {+ :i 1} :w}\n else {firstDifferingChar.r :w {+ :i 1} :n}}}}}\n {lambda {:w}\n {if {= {W.length :w} 1}\n then :w is a single character\n else {firstDifferingChar.r :w 0 {W.length :w}}}}}\n-> firstDifferingChar\n\n{firstDifferingChar 2}\n-> 2 is a single character\n{firstDifferingChar 333}\n-> all characters are the same\n{firstDifferingChar .55}\n-> at position 1 . becomes 5\n{firstDifferingChar tttTTT}\n-> at position 3 t becomes T\n", "language": "Lambdatalk" }, { "code": "function analyze(s)\n print(string.format(\"Examining [%s] which has a length of %d:\", s, string.len(s)))\n if string.len(s) > 1 then\n local last = string.byte(string.sub(s,1,1))\n for i=1,string.len(s) do\n local c = string.byte(string.sub(s,i,i))\n if last ~= c then\n print(\" Not all characters in the string are the same.\")\n print(string.format(\" '%s' (0x%x) is different at position %d\", string.sub(s,i,i), c, i - 1))\n return\n end\n end\n end\n print(\" All characters in the string are the same.\")\nend\n\nfunction main()\n analyze(\"\")\n analyze(\" \")\n analyze(\"2\")\n analyze(\"333\")\n analyze(\".55\")\n analyze(\"tttTTT\")\n analyze(\"4444 444k\")\nend\n\nmain()\n", "language": "Lua" }, { "code": "CheckSame:=proc(s)\n\tlocal i, index;\n\tprintf(\"input: \\\"%s\\\", length: %a\\n\", s, StringTools:-Length(s));\n\tfor i from 2 to StringTools:-Length(s) do\n\t\tif (s[i - 1] <> s[i]) then\n\t\t\tprintf(\"The given string has different characters.\\n\");\n\t\t\tprintf(\"The first different character is %a (0x%x) which appears at index %a.\\n\\n\",\n\t\t\t \t s[i], convert(s[i], 'bytes')[1], i);\n\t\t\treturn;\n\t\tend if;\n\tend do;\n\t# if no difference found\n\tprintf(\"The given string has all same characters.\\n\\n\");\nend proc:\n\n# Test\nCheckSame(\"\");\nCheckSame(\" \");\nCheckSame(\"2\");\nCheckSame(\"333\");\nCheckSame(\".55\");\nCheckSame(\"tttTTT\");\nCheckSame(\"4444 444k\");\n", "language": "Maple" }, { "code": "ClearAll[AllSameCharacters]\nAllSameCharacters[s_String] := Module[{c = Characters[s], i = 0, tf},\n If[Length[c] > 1,\n tf = AllTrue[Rest[c], (i++; # == First[c]) &];\n If[tf,\n Print[\"input = \\\"\", s, \"\\\", Length = \", StringLength[s],\n \", All the same!\"]\n ,\n Print[\"input = \\\"\", s, \"\\\", Length = \", StringLength[s],\n \", Character \" <> ToString[i + 1] <>\n \" is different from character \" <> ToString[i], \", hex = \",\n IntegerString[First@ToCharacterCode[c[[i + 1]]], 16]]\n ]\n ,\n Print[\"input = \\\"\", s, \"\\\", Length = \", StringLength[s],\n \", All the same!\"]\n ];\n ]\nAllSameCharacters[\"\"]\nAllSameCharacters[\" \"]\nAllSameCharacters[\"2\"]\nAllSameCharacters[\"333\"]\nAllSameCharacters[\".55\"]\nAllSameCharacters[\"tttTTT\"]\nAllSameCharacters[\"4444 444k\"]\n", "language": "Mathematica" }, { "code": "def analyze(s)\n s = str(s)\n println \"Examining [\" + s + \"] which has a length of \" + str(len(s)) + \":\"\n\n if len(s) < 2\n println \"\\tAll characters in the string are the same.\"\n return\n end\n\n for i in range(0, len(s) - 2)\n if s[i] != s[i + 1]\n println \"\\tNot all characters in the string are the same.\"\n println \"\\t'\" + s[i + 1] + \"' \" + format(\"(0x%x)\", ord(s[i + 1])) +\\\n \" is different at position \" + str(i + 2)\n return\n end\n end\n\n println \"\\tAll characters in the string are the same.\"\nend\n\ntests = {\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"444 444k\"}\nfor s in tests\n analyze(s)\nend\n", "language": "Nanoquery" }, { "code": "import strformat\n\nproc analyze(str: string) =\n if str.len() > 1:\n var first = str[0]\n for i, c in str:\n if c != first:\n echo \"'\", str, \"': [len: \", str.len(), \"] not all characters are the same. starts to differ at index \",\n i, \": '\", first, \"' != '\", c, \"' [\", fmt\"{ord(c):#x}\", \"]\"\n return\n echo \"'\", str, \"': [len: \", str.len(), \"] all characters are the same\"\n\nvar strings = @[\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\"]\nfor str in strings:\n analyze(str)\n", "language": "Nim" }, { "code": "(* Task: Determine if a string has all the same characters *)\n\n(* Create a function that determines whether all characters in a string are identical,\n or returns the index of first different character.\n\n Using the option type here to combine the functionality.\n*)\nlet str_first_diff_char (s : string) : int option =\n let len = String.length s in\n if len = 0\n then None\n else\n let first = s.[0] in\n let rec helper idx =\n if idx >= len\n then None\n else if s.[idx] = first\n then helper (idx + 1)\n else Some idx\n in\n helper 1\n;;\n\n(* Task display: using format of Ada\n Example:\n\nInput = \"333\", length = 3\n All characters are the same.\nInput = \".55\", length = 3\n First difference at position 2, character = '5', hex = 16#35#\n*)\n\nlet format_answer s =\n let first_line = \"Input = \\\"\" ^ s ^ \"\\\", length = \" ^ (s |> String.length |> string_of_int) in\n let second_line = match str_first_diff_char s with\n | None -> \" All characters are the same.\"\n | Some idx -> Printf.sprintf \" First difference at position %d, character = %C, hex = %#x\" (idx+1) s.[idx] (Char.code s.[idx])\n in\n print_endline first_line; print_endline second_line\n;;\n\nlet _ =\n [\"\"; \" \"; \"2\"; \"333\"; \".55\"; \"tttTTT\"; \"4444 444k\"]\n |> List.iter format_answer\n;;\n", "language": "OCaml" }, { "code": "program SameNessOfChar;\n{$IFDEF FPC}\n {$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$CODEALIGN proc=16}{$ALIGN 16}\n{$ELSE}\n {$APPTYPE CONSOLE}\n{$ENDIF}\nuses\n sysutils;//Format\nconst\n TestData : array[0..6] of String =\n ('',' ','2','333','.55','tttTTT','4444 444k');\nfunction PosOfDifferentChar(const s: String):NativeInt;\nvar\n i: Nativeint;\n ch:char;\nBegin\n result := length(s);\n IF result < 2 then\n EXIT;\n ch := s[1];\n i := 2;\n while (i< result) AND (S[i] =ch) do\n inc(i);\n result := i;\nend;\n\nprocedure OutIsAllSame(const s: String);\nvar\n l,len: NativeInt;\nBegin\n l := PosOfDifferentChar(s);\n len := Length(s);\n write('\"',s,'\" of length ',len);\n IF l = len then\n writeln(' contains all the same character')\n else\n writeln(Format(' is different at position %d \"%s\" (0x%X)',[l,s[l],Ord(s[l])]));\nend;\n\nvar\n i : NativeInt;\nbegin\n For i := Low(TestData) to HIgh(TestData) do\n OutIsAllSame(TestData[i]);\nend.\n", "language": "Pascal" }, { "code": "use strict;\nuse warnings;\nuse feature 'say';\nuse utf8;\nbinmode(STDOUT, ':utf8');\nuse List::AllUtils qw(uniq);\nuse Unicode::UCD 'charinfo';\nuse Unicode::Normalize qw(NFC);\n\nfor my $str (\n '',\n ' ',\n '2',\n '333',\n '.55',\n 'tttTTT',\n '4444 444k',\n 'Δ👍👨',\n '🇬🇧🇬🇧🇬🇧🇬🇧',\n \"\\N{LATIN CAPITAL LETTER A}\\N{COMBINING DIAERESIS}\\N{COMBINING MACRON}\" .\n \"\\N{LATIN CAPITAL LETTER A WITH DIAERESIS}\\N{COMBINING MACRON}\" .\n \"\\N{LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON}\"\n) {\n my @S;\n push @S, NFC $1 while $str =~ /(\\X)/g;\n printf qq{\\n\"$str\" (length: %d) has }, scalar @S;\n my @U = uniq @S;\n if (1 != @U and @U > 0) {\n say 'different characters:';\n for my $l (@U) {\n printf \"'%s' %s (0x%x) in positions: %s\\n\",\n $l, charinfo(ord $l)->{'name'}, ord($l), join ', ', map { 1+$_ } grep { $l eq $S[$_] } 0..$#S;\n }\n } else {\n say 'the same character in all positions.'\n }\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">samechar</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"all characters are the same\"</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">si</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">ch</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">su</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">utf32_to_utf8</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">`first different character \"%s\"(#%02x) at position %d`</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">su</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\\"%s\\\" (length %d): %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">utf32_to_utf8</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"2\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"333\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\".55\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"tttTTT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"4444 444k\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #7060A8;\">utf8_to_utf32</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"🐶🐶🐺🐶\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #7060A8;\">utf8_to_utf32</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"🎄🎄🎄🎄\"</span><span style=\"color: #0000FF;\">)}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #000000;\">samechar</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "(de equal? (Str)\n (let (Lst (chop Str) C (car Lst) P 2 F)\n (prin Str \": \")\n (for A (cdr Lst)\n (NIL (= A C) (on F) (prin \"First different character \" A))\n (inc 'P) )\n (if F (prinl \" at position: \" P) (prinl \"all characters are the same\")) ) )\n(equal?)\n(equal? \" \")\n(equal? \"333\")\n(equal? \".55\")\n(equal? \"tttTTT\")\n", "language": "PicoLisp" }, { "code": "To run:\nStart up.\nShow the uniformity of \"\".\nShow the uniformity of \" \".\nShow the uniformity of \"2\".\nShow the uniformity of \"333\".\nShow the uniformity of \".55\".\nShow the uniformity of \"tttTTT\".\nShow the uniformity of \"4444 444k\".\nWait for the escape key.\nShut down.\n\nTo find the first different character in a string giving a byte and a count:\nIf the string is blank, put -1 into the count; exit.\nPut the string's first's target into a first letter.\nSlap a substring on the string.\nLoop.\nIf a counter is past the string's length, put -1 into the count; exit.\nPut the substring's first's target into a letter.\nIf the letter is not the first letter, put the letter into the byte; put the counter minus 1 into the count; exit.\nAdd 1 to the substring's first.\nRepeat.\n\nTo show the uniformity of a string:\nWrite \"\"\"\" then the string then \"\"\" (length \" then the string's length then \") \" on the console without advancing.\nFind the first different character in the string giving a byte and a count.\nIf the count is -1, write \"contains all the same character.\" on the console; exit.\nConvert the byte to a nibble string.\nWrite \"contains a different character at index \" then the count then \": '\" then the byte then \"' (0x\" then the nibble string then \").\" on the console.\n", "language": "Plain-English" }, { "code": ":- system:set_prolog_flag(double_quotes,chars) .\n\nmain\n:-\nsame_or_different(\"\") ,\nsame_or_different(\" \") ,\nsame_or_different(\"2\") ,\nsame_or_different(\"333\") ,\nsame_or_different(\".55\") ,\nsame_or_different(\"tttTTT\") ,\nsame_or_different(\"4444 444k\")\n.\n\n%! same_or_different(INPUTz0)\n\nsame_or_different(INPUTz0)\n:-\nsystem:format('input string is \"~s\" .~n',[INPUTz0]) ,\nexamine(INPUTz0)\n.\n\n%! examine(INPUTz0)\n\nexamine([])\n:-\n! ,\nsystem:format('all the same characters .~n',[])\n.\n\nexamine([COMPARE0|INPUTz0])\n:-\nexamine(INPUTz0,COMPARE0,2,_INDEX_)\n.\n\n%! examine(INPUTz0,COMPARE0,INDEX0,INDEX)\n\nexamine([],_COMPARE0_,INDEX0,INDEX0)\n:-\n! ,\nsystem:format('all the same characters .~n',[])\n.\n\nexamine([COMPARE0|INPUTz0],COMPARE0,INDEX0,INDEX)\n:-\n! ,\nINDEX1 is INDEX0 + 1 ,\nexamine(INPUTz0,COMPARE0,INDEX1,INDEX)\n.\n\nexamine([DIFFERENT0|_INPUTz0_],COMPARE0,INDEX0,INDEX0)\n:-\nprolog:char_code(DIFFERENT0,DIFFERENT_CODE) ,\nsystem:format('character \"~s\" (hex ~16r) different than \"~s\" at 1-based index ~10r .~n',[[DIFFERENT0],DIFFERENT_CODE,[COMPARE0],INDEX0])\n.\n", "language": "Prolog" }, { "code": "'''Determine if a string has all the same characters'''\n\nfrom itertools import groupby\n\n\n# firstDifferingCharLR :: String -> Either String Dict\ndef firstDifferingCharLR(s):\n '''Either a message reporting that no character changes were\n seen, or a dictionary with details of the first character\n (if any) that differs from that at the head of the string.\n '''\n def details(xs):\n c = xs[1][0]\n return {\n 'char': repr(c),\n 'hex': hex(ord(c)),\n 'index': s.index(c),\n 'total': len(s)\n }\n xs = list(groupby(s))\n return Right(details(xs)) if 1 < len(xs) else (\n Left('Total length ' + str(len(s)) + ' - No character changes.')\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test of 7 strings'''\n\n print(fTable('First, if any, points of difference:\\n')(repr)(\n either(identity)(\n lambda dct: dct['char'] + ' (' + dct['hex'] +\n ') at character ' + str(1 + dct['index']) +\n ' of ' + str(dct['total']) + '.'\n )\n )(firstDifferingCharLR)([\n '',\n ' ',\n '2',\n '333',\n '.55',\n 'tttTTT',\n '4444 444'\n ]))\n\n\n# GENERIC -------------------------------------------------\n\n# either :: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n '''The application of fl to e if e is a Left value,\n or the application of fr to e if e is a Right value.\n '''\n return lambda fr: lambda e: fl(e['Left']) if (\n None is e['Right']\n ) else fr(e['Right'])\n\n\n# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# Left :: a -> Either a b\ndef Left(x):\n '''Constructor for an empty Either (option type) value\n with an associated string.\n '''\n return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right :: b -> Either a b\ndef Right(x):\n '''Constructor for a populated Either (option type) value'''\n return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "'''Determine if a string has all the same characters'''\n\nfrom itertools import takewhile\n\n\n# inconsistentChar :: String -> Maybe (Int, Char)\ndef inconsistentChar(s):\n '''Just the first inconsistent character and its position,\n or Nothing if all the characters of s are the same,\n '''\n if s:\n h = s[0]\n pre, post = span(lambda c: h == c)(s)\n return Just((len(pre), post[0])) if post else Nothing()\n else:\n return Nothing()\n\n\n# --------------------------TEST---------------------------\n# main :: IO ()\ndef main():\n '''Consistency tests of seven strings'''\n\n samples = ['', ' ', '2', '333', '.55', 'tttTTT', '4444 444']\n w = 1 + max(map(len, samples))\n\n def pfx(s):\n return (\"'\" + s).rjust(w) + \"' -> \"\n\n def charPosn(ic):\n i, c = ic\n return \"inconsistent '\" + c + \"' (\" + hex(ord(c)) + \")\" + (\n \" at char \" + str(1 + i)\n )\n\n print(main.__doc__ + ':\\n')\n print(\n '\\n'.join([\n pfx(s) + maybe('consistent')(charPosn)(\n inconsistentChar(s)\n )\n for s in samples\n ])\n )\n\n\n# -------------------------GENERIC-------------------------\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.\n Wrapper containing the result of a computation.\n '''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.\n Empty wrapper returned where a computation is not possible.\n '''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# maybe :: b -> (a -> b) -> Maybe a -> b\ndef maybe(v):\n '''Either the default value v, if m is Nothing,\n or the application of f to x,\n where m is Just(x).\n '''\n return lambda f: lambda m: v if None is m or m.get('Nothing') else (\n f(m.get('Just'))\n )\n\n\n# span :: (a -> Bool) -> [a] -> ([a], [a])\ndef span(p):\n '''The longest (possibly empty) prefix of xs\n that contains only elements satisfying p,\n tupled with the remainder of xs.\n span p xs is equivalent to (takeWhile p xs, dropWhile p xs).\n '''\n def go(xs):\n prefix = list(takewhile(p, xs))\n return (prefix, xs[len(prefix):])\n return lambda xs: go(xs)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "# inconsistentChar :: String -> Maybe (Int, Char)\ndef inconsistentChar(s):\n '''Just the first inconsistent character and its index,\n or Nothing if all the characters of s are the same.\n '''\n return next(\n (Just(ix) for ix in enumerate(s) if s[0] != ix[1]),\n Nothing()\n )\n", "language": "Python" }, { "code": " [ 0 swap\n dup size 0 = iff\n drop done\n behead swap witheach\n [ over != if\n [ drop i^ 1+\n swap conclude ] ]\n drop ] is allsame ( [ --> n )\n\n ( 0 indicates all items are the same,\n otherwise n is first different item )\n\n [ say ' String: \"' dup echo$\n say '\" length ' dup size echo\n dup allsame dup 0 = iff\n [ say ', all characters are the same.'\n 2drop ]\n else\n [ say ', first difference is item '\n dup echo\n say ', char \"'\n peek dup emit\n say '\", hex: '\n 16 base put echo base release\n say '.' ]\n cr ] is task ( $ --> )\n\n $ \"\" task\n $ \" \" task\n $ \"2\" task\n $ \".55\" task\n $ \"tttTTT\" task\n $ \"4444 444k\" task\n", "language": "Quackery" }, { "code": "DECLARE SUB DifChar (sString AS STRING, wc AS INTEGER, dc AS STRING)\n\nDIM i AS INTEGER\nDIM s AS STRING\nDIM dc AS STRING\n\nDATA \"\", \" \", \"2\", \"333\",\".55\",\"tttTTT\", \"4444 444k\", \"FIN\"\n\n' Main program cycle\nCLS\nPRINT \"Program SameChar\"\nPRINT \"Determines if a string has the same character or not.\"\nPRINT\nDO\n READ s\n IF s = \"FIN\" THEN EXIT DO\n DifChar s, i, dc\n PRINT \"'\"; s; \"' of length\"; LEN(s);\n IF i < 2 THEN\n PRINT \"contains all the same character.\"\n ELSE\n PRINT \"is different at possition\"; STR$(i); \": '\"; dc; \"' (0x\"; HEX$(ASC(dc)); \")\"\n END IF\nLOOP\nPRINT\nPRINT \"End of program run.\"\nEND\n\nSUB DifChar (sString AS STRING, wc AS INTEGER, dc AS STRING)\n ' Var\n DIM c AS STRING\n\n ' Look for the distinct char\n c = LEFT$(sString, 1)\n wc = 1\n dc = \"\"\n DO WHILE wc < LEN(sString)\n IF MID$(sString, wc, 1) <> c THEN dc = MID$(sString, wc, 1): EXIT DO\n wc = wc + 1\n LOOP\n\n IF dc = \"\" THEN wc = 1\nEND SUB\n", "language": "QuickBASIC" }, { "code": "isAllSame <- function(string)\n{\n strLength <- nchar(string)\n if(length(strLength) > 1)\n {\n #R has a distinction between the length of a string and that of a character vector. It is a common source\n #of problems when coming from another language. We will try to avoid the topic here.\n #For our purposes, let us only say that there is a good reason why we have made\n #isAllSame(c(\"foo\", \"bar\") immediately throw an error.\n stop(\"This task is intended for character vectors with lengths of at most 1.\")\n }\n else if(length(strLength) == 0)\n {\n cat(\"Examining a character vector of length 0.\\n\")\n TRUE\n }\n else if(strLength == 0)\n {\n cat(\"Examining a character vector of length 1, containing an empty string.\\n\")\n TRUE\n }\n else\n {\n cat(\"Examining the string\", paste0(sQuote(string), \",\"),\n \"which is of length\", paste0(strLength, \":\"), \"\\n\")\n #strsplit outputs a list. Its first element is the vector of characters that we desire.\n characters <- strsplit(string, \"\")[[1]]\n #Our use of match is using R's vector recycling rules. Every element is being checked\n #against the first.\n differentElementIndex <- match(FALSE, characters[1] == characters, nomatch = 0)\n if(differentElementIndex == 0)\n {\n cat(\"It has no duplicates.\\n\")\n TRUE\n }\n else\n {\n cat(\"It has duplicates. \")\n firstDifferentCharacter <- characters[differentElementIndex]\n cat(sQuote(firstDifferentCharacter), \"is the first different character. It has hex value\",\n sprintf(\"0x%X\", as.integer(charToRaw(firstDifferentCharacter))),\n \"and is at index\", paste0(differentElementIndex, \".\"), \"\\n\")\n FALSE\n }\n }\n}\n\n#Tests:\ncat(\"Test: A string of length 0 (an empty string):\\n\")\ncat(\"Test 1 of 2: An empty character vector:\\n\")\nprint(isAllSame(character(0)))\ncat(\"Test 2 of 2: A character vector containing the empty string:\\n\")\nprint(isAllSame(\"\"))\ncat(\"Test: A string of length 3 which contains three blanks:\\n\")\nprint(isAllSame(\" \"))\ncat(\"Test: A string of length 1 which contains 2:\\n\")\nprint(isAllSame(\"2\"))\ncat(\"Test: A string of length 3 which contains 333:\\n\")\nprint(isAllSame(\"333\"))\ncat(\"Test: A string of length 3 which contains .55:\\n\")\nprint(isAllSame(\".55\"))\ncat(\"Test: A string of length 6 which contains tttTTT:\\n\")\nprint(isAllSame(\"tttTTT\"))\ncat(\"Test: A string of length 9 which contains 4444 444k:\\n\")\nprint(isAllSame(\"4444 444k\"))\n", "language": "R" }, { "code": "#lang racket\n\n(define (first-non-matching-index l =)\n (and (not (null? l)) (index-where l (curry (negate =) (car l)))))\n\n(define (report-string-sameness s)\n (printf \"~s (length: ~a): ~a~%\"\n s\n (string-length s)\n (cond [(first-non-matching-index (string->list s) char=?)\n => (λ (i)\n (let ((c (string-ref s i)))\n (format \"first different character ~s(~a) at position: ~a\" c (char->integer c) (add1 i))))]\n [else \"all characters are the same\"])))\n\n(module+ test\n (for-each report-string-sameness '(\"\" \" \" \"2\" \"333\" \".55\" \"tttTTT\" \"4444 444k\")))\n", "language": "Racket" }, { "code": " -> $str {\n my $i = 0;\n print \"\\n{$str.raku} (length: {$str.chars}), has \";\n my %m;\n %m{$_}.push: ++$i for $str.comb;\n\n if %m > 1 {\n say \"different characters:\";\n say \"'{.key}' ({.key.uninames}; hex ordinal: {(.key.ords).fmt: \"0x%X\"})\" ~\n \" in positions: {.value.join: ', '}\" for %m.sort( *.value[0] );\n } else {\n say \"the same character in all positions.\"\n }\n} for\n '',\n ' ',\n '2',\n '333',\n '.55',\n 'tttTTT',\n '4444 444k',\n '🇬🇧🇬🇧🇬🇧🇬🇧',\n \"\\c[LATIN CAPITAL LETTER A]\\c[COMBINING DIAERESIS]\\c[COMBINING MACRON]\" ~\n \"\\c[LATIN CAPITAL LETTER A WITH DIAERESIS]\\c[COMBINING MACRON]\" ~\n \"\\c[LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON]\",\n 'AАΑꓮ𐌀𐊠Ꭺ'\n", "language": "Raku" }, { "code": "/*REXX program verifies that all characters in a string are all the same (character). */\n@chr= ' [character' /* define a literal used for SAY.*/\n@all= 'all the same character for string (length' /* \" \" \" \" \" \" */\n@.= /*define a default for the @. array. */\nparse arg x /*obtain optional argument from the CL.*/\nif x\\='' then @.1= x /*if user specified an arg, use that. */\n else do; @.1= /*use this null string if no arg given.*/\n @.2= ' ' /* \" \" \" \" \" \" \" */\n @.3= 2 /* \" \" \" \" \" \" \" */\n @.4= 333 /* \" \" \" \" \" \" \" */\n @.5= .55 /* \" \" \" \" \" \" \" */\n @.6= 'tttTTT' /* \" \" \" \" \" \" \" */\n @.7= 4444 444k /* \" \" \" \" \" \" \" */\n end /* [↑] seventh value contains a blank.*/\n\n do j=1; L= length(@.j) /*obtain the length of an array element*/\n if j>1 & L==0 then leave /*if arg is null and J>1, then leave. */\n r= allSame(@.j) /*R: ≡0, or the location of bad char.*/\n if r\\==0 then ?= substr(@.j,r,1) /*if not monolithic, obtain the char.*/\n if r==0 then say ' ' @all L\"):\" @.j\n else say 'not' @all L\"):\" @.j @chr ? \"('\"c2x(?)\"'x) at position\" r\"].\"\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nallSame: procedure; parse arg y /*get a value from the argument list. */\n if y=='' then return 0 /*if Y is null, then return 0 (zero)*/\n return verify(y, left(y,1) ) /*All chars the same? Return 0 (zero)*/\n /* else return location*/\n", "language": "REXX" }, { "code": "nputStr = [\"\",\" \",\"2\",\"333\",\".55\",\"tttTTT\",\"4444 444k\"]\n\nfor word in inputStr\n for x = 1 to len(word)\n for y = x + 1 to len(word)\n if word[x] != word[y]\n char = word[y]\n ? \"Input = \" + \"'\" + word + \"'\" + \", length = \" + len(word)\n ? \" First difference at position \" + y + \", character = \" + \"'\" + char + \"'\"\n loop 3\n ok\n next\n next\n\n ? \"Input = \" + \"'\" + word + \"'\" + \", length = \" + len(word)\n ? \" All characters are the same.\"\nnext\n", "language": "Ring" }, { "code": "≪ DUP SIZE → s n\n ≪ \"Examining [\" s + \"], length=\" + n →STR + +\n 1 CF\n IF n THEN\n s 1 1 SUB 1\n DO\n s OVER DUP SUB\n IF 3 PICK OVER ≠ THEN\n 1 SF\n ROT DROP SWAP\n ELSE DROP\n END\n 1 +\n UNTIL DUP n ≥ 1 FS? OR END\n DROP\n ELSE DUP\n END\n IF 1 FC? THEN\n DROP\n \"All chars are the same.\"\n ELSE\n \"'\" OVER +\n \"' (hex=\" + OVER NUM HEX R→B →STR +\n \") is different at pos \" + s 4 ROLL POS →STR +\n END\n ≫\n≫\n'ALLSAME?' STO\n≪ { \"\" \" \" \"2\" \"333\" \".55\" \"tttTTT\" \"4444 444k\" }\n → tl ≪\n 1 tl SIZE FOR j\n tl j GET ALLSAME?\n NEXT\n ≫\n≫\nEVAL\n", "language": "RPL" }, { "code": "strings = [\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\", \"pépé\", \"🐶🐶🐺🐶\", \"🎄🎄🎄🎄\"]\n\nstrings.each do |str|\n pos = str.empty? ? nil : str =~ /[^#{str[0]}]/\n print \"#{str.inspect} (size #{str.size}): \"\n puts pos ? \"first different char #{str[pos].inspect} (#{'%#x' % str[pos].ord}) at position #{pos}.\" : \"all the same.\"\nend\n", "language": "Ruby" }, { "code": "fn test_string(input: &str) {\n println!(\"Checking string {:?} of length {}:\", input, input.chars().count());\n\n let mut chars = input.chars();\n\n match chars.next() {\n Some(first) => {\n if let Some((character, pos)) = chars.zip(2..).filter(|(c, _)| *c != first).next() {\n println!(\"\\tNot all characters are the same.\");\n println!(\"\\t{:?} (0x{:X}) at position {} differs.\", character, character as u32, pos);\n\n return;\n }\n },\n None => {}\n }\n\n println!(\"\\tAll characters in the string are the same\");\n}\n\nfn main() {\n let tests = [\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\", \"pépé\", \"🐶🐶🐺🐶\", \"🎄🎄🎄🎄\"];\n\n for string in &tests {\n test_string(string);\n }\n}\n", "language": "Rust" }, { "code": "comment\n Return 0 if all the characters in s are the same\n (including the special case of an empty string),\n otherwise the first position where a character\n differs from the preceeding one(s)\nend\nfunction samechars(s = string) = integer\n var i, slen, result = integer\n slen = len(s)\n i = 1\n while i < slen and mid(s,i,1) = mid(s,i+1,1) do\n i = i+1\n if i = slen or slen = 0 then\n result = 0\n else\n result = i+1\nend = result\n\nprocedure report(str = string)\n var p = integer\n print \"Test string \"; chr(34); str; chr(34); \\\n \" has length =\"; len(str)\n p = samechars(str)\n if p = 0 then\n print \"The characters are all the same\"\n else\n print \"Characters differ starting at position\";p;\" ('\"; \\\n mid(str,p,1);\"'=\";right$(hex$(asc(mid(str,p,1))),2);\"h)\"\n print\nend\n\nrem - apply to the test cases\n\nreport \"\"\nreport \" \"\nreport \"2\"\nreport \"333\"\nreport \".55\"\nreport \"tttTTT\"\nreport \"4444 444k\"\n\nend\n", "language": "S-BASIC" }, { "code": "import scala.collection.immutable.ListMap\n\nobject StringAllSameCharacters {\n\n /**Transform an input String into an HashMap of its characters and its first occurrence index*/\n def countChar( s : String) : Map[Char, Int] = {\n val mapChar = s.toSeq.groupBy(identity).map{ case (a,b) => a->s.indexOf(a) }\n val orderedMapChar = ListMap(mapChar.toSeq.sortWith(_._2 < _._2):_*)\n orderedMapChar\n }\n\n /**Check if all the characters of a String are the same given an input Hashmap of it */\n def areAllCharEquals ( mapChar : Map[Char, Int] ) : Boolean = {\n return mapChar.size <= 1\n }\n\n /**Retrieve the first \"breaking\" different character of a String*/\n def findFirstDifferentChar ( mapChar : Map[Char, Int] ) : Char = {\n if(areAllCharEquals(mapChar) == false) mapChar.keys.toList(1)\n else 0.toChar\n }\n\n /**Convert char to hexadecimal values as \"0xHEXVALUE\" */\n def charToHexString ( c : Char) : String = \"0x\" + c.toHexString\n\n /**Display results as asked in the ask*/\n def reportResults( s : String) : String = {\n val mapChar = countChar(s)\n if (areAllCharEquals(mapChar)) s + \" -- length \" + s.size + \" -- contains all the same character.\"\n else {\n val diffChar = findFirstDifferentChar(mapChar)\n s + \" -- length \" + s.size +\n \" -- contains a different character at index \" +\n (s.indexOf(diffChar).toInt+1).toString + \" : \" + charToHexString(diffChar)\n }\n }\n\n def main(args: Array[String]): Unit = {\n println(reportResults(\"\"))\n println(reportResults(\" \"))\n println(reportResults(\"2\"))\n println(reportResults(\"333\"))\n println(reportResults(\".55\"))\n println(reportResults(\"tttTTT\"))\n println(reportResults(\"4444 444k\"))\n }\n\n\n}\n", "language": "Scala" }, { "code": "func analyze_string(str) {\n var chars = str.chars\n chars.range.to_a.each_cons(2, {|a,b|\n chars[a] == chars[b] || return b\n })\n return str.len\n}\n\nvar strings = [\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\", \"pépé\", \"🐶🐶🐺🐶\", \"🎄🎄🎄🎄\"]\n\nstrings.each {|str|\n print \"'#{str}' (size #{str.len}): \"\n var idx = analyze_string(str)\n\n if (idx == str.len) {\n say \"all the same.\"\n }\n else {\n say \"first different char '#{str[idx]}' (#{'%#x' % str[idx].ord}) at position #{idx}.\"\n }\n}\n", "language": "Sidef" }, { "code": "/*\nThis code is an implementation of \"Determination if a string has all the same characters\" in SQL ORACLE 19c\np_in_str -- input string\n*/\nwith\n function same_characters_in_string(p_in_str in varchar2) return varchar2 is\n v_que varchar2(32767) := p_in_str;\n v_res varchar2(32767);\n v_first varchar2(1);\n v_next varchar2(1);\nbegin\n v_first := substr(v_que,1,1);\n if v_first is null then\n v_res := '\"\" length:0 all characters are the same';\n else\n for i in 2..length(v_que)\n loop\n v_next := substr(v_que,i,1);\n if v_first != v_next then\n v_res := '\"'||v_que||'\" length:'||length(v_que)||', first different character \"'||v_next||'\"(0x'||rawtohex(utl_raw.cast_to_raw(v_next))||') at position:'|| i;\n exit;\n end if;\n end loop;\n v_res := nvl(v_res,'\"'||v_que||'\" length:'||length(v_que)||' all characters are the same');\n end if;\n return v_res;\nend;\n\n--Test\nselect same_characters_in_string('') as res from dual\nunion all\nselect same_characters_in_string(' ') as res from dual\nunion all\nselect same_characters_in_string('2') as res from dual\nunion all\nselect same_characters_in_string('333') as res from dual\nunion all\nselect same_characters_in_string('.55') as res from dual\nunion all\nselect same_characters_in_string('tttTTT') as res from dual\nunion all\nselect same_characters_in_string('4444 444k') as res from dual\n;\n", "language": "SQL" }, { "code": "datatype result=allSame | difference of string*char*int ;\nval chkstring = fn input =>\nlet\nval rec chk = fn ([],n) => allSame\n | ([x],n) => allSame\n\t | (x::y::t,n)=> if x=y then chk (y::t,n+1)\n\t else difference (Int.fmt StringCvt.HEX(Char.ord(y)),y,n)\nin\n( input, String.size input , chk ( String.explode input,2 ) )\nend;\n", "language": "Standard-ML" }, { "code": "- map chkstring [ \"\",\" \",\"1\",\"333\",\".55\",\"tttTTT\",\"4444 444k\" ];\nval it =\n [(\"\", 0, allSame), (\" \", 3, allSame), (\"1\", 1, allSame),\n (\"333\", 3, allSame), (\".55\", 3, difference (\"35\", #\"5\", 2)),\n (\"tttTTT\", 6, difference (\"54\", #\"T\", 4)),\n (\"4444 444k\", 9, difference (\"20\", #\" \", 5))]:\n", "language": "Standard-ML" }, { "code": "package require Tcl 8.6 ; # For binary encode\n\narray set yesno {1 Yes 0 No}\n\nset test {\n {}\n { }\n {2}\n {333}\n {.55}\n {tttTTT}\n {4444 444k}\n {jjjjjjj}\n}\n\n# Loop through test strings\nforeach str $test {\n set chars [dict create] ; # init dictionary\n set same 1\n set prev {}\n # Loop through characters in string\n for {set i 0} {$i < [string length $str]} {incr i} {\n set c [string index $str $i] ; # get char at index\n if {$prev == {}} {\n set prev $c ; # initialize prev if it doesn't exist\n }\n if {$c != $prev} {\n set same 0\n break ; # Found a different char, break out of the loop\n }\n }\n\n # Handle Output\n puts [format \"Tested: %12s (len: %2d). All Same? %3s. \" \\\n \"'$str'\" [string length $str] $yesno($same)]\n if {! $same} {\n puts [format \" --> Different character '%s' (hex: 0x%s) appears at index: %s.\" \\\n $c [binary encode hex $c] $i]\n }\n}\n", "language": "Tcl" }, { "code": "fn analyze(s string) {\n chars := s.runes()\n le := chars.len\n println(\"Analyzing $s which has a length of $le:\")\n if le > 1 {\n for i in 1..le{\n if chars[i] != chars[i-1] {\n println(\" Not all characters in the string are the same.\")\n println(\" '${chars[i]}' (0x${chars[i]:x}) is different at position ${i+1}.\\n\")\n return\n }\n }\n }\n println(\" All characters in the string are the same.\\n\")\n}\n\nfn main() {\n strings := [\n \"\",\n \" \",\n \"2\",\n \"333\",\n \".55\",\n \"tttTTT\",\n \"4444 444k\",\n \"pépé\",\n \"🐶🐶🐺🐶\",\n \"🎄🎄🎄🎄\"\n\t]\n for s in strings {\n analyze(s)\n }\n}\n", "language": "V-(Vlang)" }, { "code": "Sub Main_SameCharacters()\nDim arr, i As Integer, respons As Integer\n arr = Array(\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\", \"111111112\", \" 123\")\n For i = LBound(arr) To UBound(arr)\n If SameCharacters(arr(i), respons) Then\n Debug.Print \"Analyze : [\" & arr(i) & \"], lenght \" & Len(arr(i)) & \" : \" & \" All characters are the same.\"\n Else\n Debug.Print \"Analyze : [\" & arr(i) & \"], lenght \" & Len(arr(i)) & \" : \" & \" is different at position \" & respons & \", character = '\" & Mid(arr(i), respons, 1) & \"', hexa : (0x\" & Hex(Asc(Mid(arr(i), respons, 1))) & \")\"\n End If\n Next\nEnd Sub\nFunction SameCharacters(sTxt, resp As Integer, Optional LowerUpper As Boolean = False) As Boolean\nDim A As String, B As String, i As Integer, temp As Integer\n If Len(sTxt) > 1 Then\n If LowerUpper Then\n SameCharacters = UCase(sTxt) = String$(Len(sTxt), UCase(Left$(sTxt, 1)))\n Else\n SameCharacters = sTxt = String$(Len(sTxt), Left$(sTxt, 1))\n End If\n If Not SameCharacters Then resp = InStr(sTxt, Left$(Replace(sTxt, Left$(sTxt, 1), vbNullString), 1))\n Else\n SameCharacters = True\n End If\nEnd Function\n", "language": "VBA" }, { "code": "Module Module1\n\n Sub Analyze(s As String)\n Console.WriteLine(\"Examining [{0}] which has a length of {1}:\", s, s.Length)\n If s.Length > 1 Then\n Dim b = s(0)\n For i = 1 To s.Length\n Dim c = s(i - 1)\n If c <> b Then\n Console.WriteLine(\" Not all characters in the string are the same.\")\n Console.WriteLine(\" '{0}' (0x{1:X02}) is different at position {2}\", c, AscW(c), i - 1)\n Return\n End If\n Next\n End If\n Console.WriteLine(\" All characters in the string are the same.\")\n End Sub\n\n Sub Main()\n Dim strs() = {\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\"}\n For Each s In strs\n Analyze(s)\n Next\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./fmt\" for Conv, Fmt\n\nvar analyze = Fn.new { |s|\n var chars = s.codePoints.toList\n var le = chars.count\n System.print(\"Analyzing %(Fmt.q(s)) which has a length of %(le):\")\n if (le > 1) {\n for (i in 1...le) {\n if (chars[i] != chars[i-1]) {\n System.print(\" Not all characters in the string are the same.\")\n var c = String.fromCodePoint(chars[i])\n var hex = Conv.hex(chars[i])\n System.print(\" '%(c)' (0x%(hex)) is different at position %(i+1).\\n\")\n return\n }\n }\n }\n System.print(\" All characters in the string are the same.\\n\")\n}\n\nvar strings = [\n \"\",\n \" \",\n \"2\",\n \"333\",\n \".55\",\n \"tttTTT\",\n \"4444 444k\",\n \"pépé\",\n \"🐶🐶🐺🐶\",\n \"🎄🎄🎄🎄\"\n]\nfor (s in strings) analyze.call(s)\n", "language": "Wren" }, { "code": "include xpllib; \\contains StrLen function\n\nproc StrSame(S); \\Show if string has same characters\nchar S;\nint L, I, J, K;\n[L:= StrLen(S);\nIntOut(0, L); Text(0, \": ^\"\"); Text(0, S); ChOut(0, ^\"); CrLf(0);\nfor I:= 0 to L-1 do\n for J:= I+1 to L-1 do\n [if S(I) # S(J) then\n [ChOut(0, \\tab\\ 9);\n for K:= 0 to J do ChOut(0, ^ );\n Text(0, \"^^ Not same character: \");\n ChOut(0, S(J));\n Text(0, \", hex \");\n SetHexDigits(2);\n HexOut(0, S(J));\n CrLf(0);\n return;\n ];\n ];\nText(0, \" All same character\"); CrLf(0);\n];\n\n[Text(0, \"Length\"); CrLf(0);\nStrSame(\"\");\nStrSame(\" \");\nStrSame(\"2\");\nStrSame(\"333\");\nStrSame(\".55\");\nStrSame(\"tttTTT\");\nStrSame(\"4444 444k\");\n]\n", "language": "XPL0" }, { "code": "fcn stringSameness(str){ // Does not handle Unicode\n sz,unique,uz := str.len(), str.unique(), unique.len();\n println(\"Length %d: \\\"%s\\\"\".fmt(sz,str));\n if(sz==uz or uz==1) println(\"\\tSame character in all positions\");\n else\n println(\"\\tDifferent: \",\n unique[1,*].pump(List,\n\t 'wrap(c){ \"'%s' (0x%x)[%d]\".fmt(c,c.toAsc(), str.find(c)+1) })\n .concat(\", \"));\n}\n", "language": "Zkl" }, { "code": "testStrings:=T(\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\");\nforeach s in (testStrings){ stringSameness(s) }\n", "language": "Zkl" } ]
Determine-if-a-string-has-all-the-same-characters
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters\n", "language": "00-META" }, { "code": ";Task:\n\nGiven a character string &nbsp; (which may be empty, or have a length of zero characters):\n::* &nbsp; create a function/procedure/routine to:\n::::* &nbsp; determine if all the characters in the string are unique\n::::* &nbsp; indicate if or which character is duplicated and where\n::* &nbsp; display each string and its length &nbsp; (as the strings are being examined)\n::* &nbsp; a zero─length (empty) string shall be considered as unique\n::* &nbsp; process the strings from left─to─right\n::* &nbsp; if &nbsp; &nbsp; &nbsp; unique, &nbsp; display a message saying such\n::* &nbsp; if not unique, &nbsp; then:\n::::* &nbsp; display a message saying such\n::::* &nbsp; display what character is duplicated\n::::* &nbsp; only the 1<sup>st</sup> non─unique character need be displayed\n::::* &nbsp; display where \"both\" duplicated characters are in the string\n::::* &nbsp; the above messages can be part of a single message\n::::* &nbsp; display the hexadecimal value of the duplicated character\n\n\n\nUse (at least) these five test values &nbsp; (strings):\n:::* &nbsp; a string of length &nbsp; &nbsp; 0 &nbsp; (an empty string)\n:::* &nbsp; a string of length &nbsp; &nbsp; 1 &nbsp; which is a single period &nbsp; (<big>'''.'''</big>)\n:::* &nbsp; a string of length &nbsp; &nbsp; 6 &nbsp; which contains: &nbsp; '''abcABC'''\n:::* &nbsp; a string of length &nbsp; &nbsp; 7 &nbsp; which contains a blank in the middle: &nbsp; '''XYZ&nbsp; ZYX'''\n:::* &nbsp; a string of length &nbsp; 36 &nbsp; which &nbsp; ''doesn't'' &nbsp; contain the letter \"oh\":\n:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''\n\n\n\nShow all output here on this page.\n\n{{Template:Strings}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F processString(input)\n [Char = Int] charMap\n V dup = Char(\"\\0\")\n V index = 0\n V pos1 = -1\n V pos2 = -1\n L(key) input\n index++\n I key C charMap\n dup = key\n pos1 = charMap[key]\n pos2 = index\n L.break\n charMap[key] = index\n V unique = I dup == Char(\"\\0\") {‘yes’} E ‘no’\n V diff = I dup == Char(\"\\0\") {‘’} E ‘'’dup‘'’\n V hexs = I dup == Char(\"\\0\") {‘’} E hex(dup.code)\n V position = I dup == Char(\"\\0\") {‘’} E pos1‘ ’pos2\n print(‘#<40 #<6 #<10 #<8 #<3 #<5’.format(input, input.len, unique, diff, hexs, position))\n\nprint(‘#<40 #2 #10 #8 #. #.’.format(‘String’, ‘Length’, ‘All Unique’, ‘1st Diff’, ‘Hex’, ‘Positions’))\nprint(‘#<40 #2 #10 #8 #. #.’.format(‘------------------------’, ‘------’, ‘----------’, ‘--------’, ‘---’, ‘---------’))\nL(s) [‘’, ‘.’, ‘abcABC’, ‘XYZ ZYX’, ‘1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ’]\n processString(s)\n", "language": "11l" }, { "code": "PROC PrintBH(BYTE a)\n BYTE ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F]\n\n Put(hex(a RSH 4))\n Put(hex(a&$0F))\nRETURN\n\nPROC Test(CHAR ARRAY s)\n BYTE i,j,n,pos1,pos2\n\n pos1=0 pos2=0\n n=s(0)-1\n IF n=255 THEN n=0 FI\n FOR i=1 TO n\n DO\n FOR j=i+1 TO s(0)\n DO\n IF s(j)=s(i) THEN\n pos1=i\n pos2=j\n EXIT\n FI\n OD\n IF pos1#0 THEN\n EXIT\n FI\n OD\n\n PrintF(\"\"\"%S\"\" (len=%B) -> \",s,s(0))\n IF pos1=0 THEN\n PrintE(\"all characters are unique.\")\n ELSE\n PrintF(\"\"\"%C\"\" (hex=$\",s(pos1))\n PrintBH(s(pos1))\n PrintF(\") is duplicated at pos. %B and %B.%E\",pos1,pos2)\n FI\n PutE()\nRETURN\n\nPROC Main()\n Test(\"\")\n Test(\".\")\n Test(\"abcABC\")\n Test(\"XYZ ZYX\")\n Test(\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\")\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;\nwith Ada.Text_IO; use Ada.Text_IO;\nprocedure Test_All_Chars_Unique is\n procedure All_Chars_Unique (S : in String) is\n begin\n Put_Line (\"Input = \"\"\" & S & \"\"\", length =\" & S'Length'Image);\n for I in S'First .. S'Last - 1 loop\n for J in I + 1 .. S'Last loop\n if S(I) = S(J) then\n Put (\" First duplicate at positions\" & I'Image &\n \" and\" & J'Image & \", character = '\" & S(I) &\n \"', hex = \");\n Put (Character'Pos (S(I)), Width => 0, Base => 16);\n New_Line;\n return;\n end if;\n end loop;\n end loop;\n Put_Line (\" All characters are unique.\");\n end All_Chars_Unique;\nbegin\n All_Chars_Unique (\"\");\n All_Chars_Unique (\".\");\n All_Chars_Unique (\"abcABC\");\n All_Chars_Unique (\"XYZ ZYX\");\n All_Chars_Unique (\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\");\nend Test_All_Chars_Unique;\n", "language": "Ada" }, { "code": "BEGIN\n # mode to hold the positions of duplicate characters in a string #\n MODE DUPLICATE = STRUCT( INT original, first duplicate );\n # finds the first non-unique character in s and returns its position #\n # and the position of the original character in a DUPLICATE #\n # if all characters in s are uniue, returns LWB s - 1, UPB s + 1 #\n PROC first duplicate position = ( STRING s )DUPLICATE:\n BEGIN\n BOOL all unique := TRUE;\n INT o pos := LWB s - 1;\n INT d pos := UPB s + 1;\n FOR i FROM LWB s TO UPB s WHILE all unique DO\n FOR j FROM i + 1 TO UPB s WHILE all unique DO\n IF NOT ( all unique := s[ i ] /= s[ j ] ) THEN\n o pos := i;\n d pos := j\n FI\n OD\n OD;\n DUPLICATE( o pos, d pos )\n END # first duplicate position # ;\n # task test cases #\n []STRING tests = ( \"\", \".\", \"abcABC\", \"XYZ ZYX\", \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\" );\n FOR t pos FROM LWB tests TO UPB tests DO\n IF STRING s = tests[ t pos ];\n DUPLICATE d = first duplicate position( s );\n print( ( \"<<<\", s, \">>> (length \", whole( ( UPB s + 1 ) - LWB s, 0 ), \"): \" ) );\n original OF d < LWB s\n THEN\n print( ( \" all characters are unique\", newline ) )\n ELSE\n # have at least one duplicate #\n print( ( \" first duplicate character: \"\"\", s[ original OF d ], \"\"\"\"\n , \" at: \", whole( original OF d, 0 ), \" and \", whole( first duplicate OF d, 0 )\n , newline\n )\n )\n FI\n OD\nEND\n", "language": "ALGOL-68" }, { "code": "use AppleScript version \"2.4\"\nuse framework \"Foundation\"\nuse scripting additions\n\non run\n script showSource\n on |λ|(s)\n quoted(\"'\", s) & \" (\" & length of s & \")\"\n end |λ|\n end script\n\n script showDuplicate\n on |λ|(mb)\n script go\n on |λ|(tpl)\n set {c, ixs} to tpl\n quoted(\"'\", c) & \" at \" & intercalate(\", \", ixs)\n end |λ|\n end script\n maybe(\"None\", go, mb)\n end |λ|\n end script\n\n fTable(\"Indices (1-based) of any duplicated characters:\\n\", ¬\n showSource, showDuplicate, ¬\n duplicatedCharIndices, ¬\n {\"\", \".\", \"abcABC\", \"XYZ ZYX\", \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"})\nend run\n\n\n------------------CHARACTER DUPLICATIONS-------------------\n\n-- duplicatedCharIndices :: String -> Maybe (Char, [Int])\non duplicatedCharIndices(s)\n script positionRecord\n on |λ|(dct, c, i)\n set k to (id of c) as string\n script additional\n on |λ|(xs)\n insertDict(k, xs & i, dct)\n end |λ|\n end script\n maybe(insertDict(k, {i}, dct), additional, lookupDict(k, dct))\n end |λ|\n end script\n\n script firstDuplication\n on |λ|(sofar, idxs)\n set {iCode, xs} to idxs\n if 1 < length of xs then\n script earliest\n on |λ|(kxs)\n if item 1 of xs < (item 1 of (item 2 of kxs)) then\n Just({chr(iCode), xs})\n else\n sofar\n end if\n end |λ|\n end script\n maybe(Just({chr(iCode), xs}), earliest, sofar)\n else\n sofar\n end if\n end |λ|\n end script\n\n foldl(firstDuplication, Nothing(), ¬\n assocs(foldl(positionRecord, {name:\"\"}, chars(s))))\nend duplicatedCharIndices\n\n\n--------------------------GENERIC--------------------------\n\n-- Just :: a -> Maybe a\non Just(x)\n -- Constructor for an inhabited Maybe (option type) value.\n -- Wrapper containing the result of a computation.\n {type:\"Maybe\", Nothing:false, Just:x}\nend Just\n\n-- Nothing :: Maybe a\non Nothing()\n -- Constructor for an empty Maybe (option type) value.\n -- Empty wrapper returned where a computation is not possible.\n {type:\"Maybe\", Nothing:true}\nend Nothing\n\n-- Tuple (,) :: a -> b -> (a, b)\non Tuple(a, b)\n -- Constructor for a pair of values, possibly of two different types.\n {type:\"Tuple\", |1|:a, |2|:b, length:2}\nend Tuple\n\n-- assocs :: Map k a -> [(k, a)]\non assocs(m)\n script go\n on |λ|(k)\n set mb to lookupDict(k, m)\n if true = |Nothing| of mb then\n {}\n else\n {{k, |Just| of mb}}\n end if\n end |λ|\n end script\n concatMap(go, keys(m))\nend assocs\n\n-- keys :: Dict -> [String]\non keys(rec)\n (current application's ¬\n NSDictionary's dictionaryWithDictionary:rec)'s allKeys() as list\nend keys\n\n-- chr :: Int -> Char\non chr(n)\n character id n\nend chr\n\n-- chars :: String -> [Char]\non chars(s)\n characters of s\nend chars\n\n-- compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\non compose(f, g)\n script\n property mf : mReturn(f)\n property mg : mReturn(g)\n on |λ|(x)\n mf's |λ|(mg's |λ|(x))\n end |λ|\n end script\nend compose\n\n-- concatMap :: (a -> [b]) -> [a] -> [b]\non concatMap(f, xs)\n set lng to length of xs\n set acc to {}\n tell mReturn(f)\n repeat with i from 1 to lng\n set acc to acc & (|λ|(item i of xs, i, xs))\n end repeat\n end tell\n return acc\nend concatMap\n\n-- enumFromTo :: Int -> Int -> [Int]\non enumFromTo(m, n)\n if m ≤ n then\n set lst to {}\n repeat with i from m to n\n set end of lst to i\n end repeat\n lst\n else\n {}\n end if\nend enumFromTo\n\n-- foldl :: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n-- fst :: (a, b) -> a\non fst(tpl)\n if class of tpl is record then\n |1| of tpl\n else\n item 1 of tpl\n end if\nend fst\n\n-- fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String\non fTable(s, xShow, fxShow, f, xs)\n set ys to map(xShow, xs)\n set w to maximum(map(my |length|, ys))\n script arrowed\n on |λ|(a, b)\n justifyRight(w, space, a) & \" -> \" & b\n end |λ|\n end script\n s & linefeed & unlines(zipWith(arrowed, ¬\n ys, map(compose(fxShow, f), xs)))\nend fTable\n\n-- insertDict :: String -> a -> Dict -> Dict\non insertDict(k, v, rec)\n tell current application\n tell dictionaryWithDictionary_(rec) of its NSMutableDictionary\n its setValue:v forKey:(k as string)\n it as record\n end tell\n end tell\nend insertDict\n\n-- intercalate :: String -> [String] -> String\non intercalate(delim, xs)\n set {dlm, my text item delimiters} to ¬\n {my text item delimiters, delim}\n set str to xs as text\n set my text item delimiters to dlm\n str\nend intercalate\n\n-- justifyRight :: Int -> Char -> String -> String\non justifyRight(n, cFiller, strText)\n if n > length of strText then\n text -n thru -1 of ((replicate(n, cFiller) as text) & strText)\n else\n strText\n end if\nend justifyRight\n\n-- length :: [a] -> Int\non |length|(xs)\n set c to class of xs\n if list is c or string is c then\n length of xs\n else\n (2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)\n end if\nend |length|\n\n-- lookupDict :: a -> Dict -> Maybe b\non lookupDict(k, dct)\n -- Just the value of k in the dictionary,\n -- or Nothing if k is not found.\n set ca to current application\n set v to (ca's NSDictionary's dictionaryWithDictionary:dct)'s objectForKey:k\n if missing value ≠ v then\n Just(item 1 of ((ca's NSArray's arrayWithObject:v) as list))\n else\n Nothing()\n end if\nend lookupDict\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n -- The list obtained by applying f\n -- to each element of xs.\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- maximum :: Ord a => [a] -> a\non maximum(xs)\n script\n on |λ|(a, b)\n if a is missing value or b > a then\n b\n else\n a\n end if\n end |λ|\n end script\n\n foldl(result, missing value, xs)\nend maximum\n\n-- maybe :: b -> (a -> b) -> Maybe a -> b\non maybe(v, f, mb)\n -- The 'maybe' function takes a default value, a function, and a 'Maybe'\n -- value. If the 'Maybe' value is 'Nothing', the function returns the\n -- default value. Otherwise, it applies the function to the value inside\n -- the 'Just' and returns the result.\n if Nothing of mb then\n v\n else\n tell mReturn(f) to |λ|(Just of mb)\n end if\nend maybe\n\n-- min :: Ord a => a -> a -> a\non min(x, y)\n if y < x then\n y\n else\n x\n end if\nend min\n\n-- mReturn :: First-class m => (a -> b) -> m (a -> b)\non mReturn(f)\n -- 2nd class handler function lifted into 1st class script wrapper.\n if script is class of f then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n-- quoted :: Char -> String -> String\non quoted(c, s)\n -- string flanked on both sides\n -- by a specified quote character.\n c & s & c\nend quoted\n\n-- Egyptian multiplication - progressively doubling a list, appending\n-- stages of doubling to an accumulator where needed for binary\n-- assembly of a target length\n-- replicate :: Int -> a -> [a]\non replicate(n, a)\n set out to {}\n if 1 > n then return out\n set dbl to {a}\n\n repeat while (1 < n)\n if 0 < (n mod 2) then set out to out & dbl\n set n to (n div 2)\n set dbl to (dbl & dbl)\n end repeat\n return out & dbl\nend replicate\n\n-- take :: Int -> [a] -> [a]\n-- take :: Int -> String -> String\non take(n, xs)\n set c to class of xs\n if list is c then\n if 0 < n then\n items 1 thru min(n, length of xs) of xs\n else\n {}\n end if\n else if string is c then\n if 0 < n then\n text 1 thru min(n, length of xs) of xs\n else\n \"\"\n end if\n else if script is c then\n set ys to {}\n repeat with i from 1 to n\n set v to |λ|() of xs\n if missing value is v then\n return ys\n else\n set end of ys to v\n end if\n end repeat\n return ys\n else\n missing value\n end if\nend take\n\n-- unlines :: [String] -> String\non unlines(xs)\n -- A single string formed by the intercalation\n -- of a list of strings with the newline character.\n set {dlm, my text item delimiters} to ¬\n {my text item delimiters, linefeed}\n set str to xs as text\n set my text item delimiters to dlm\n str\nend unlines\n\n-- zip :: [a] -> [b] -> [(a, b)]\non zip(xs, ys)\n zipWith(Tuple, xs, ys)\nend zip\n\n-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\non zipWith(f, xs, ys)\n set lng to min(|length|(xs), |length|(ys))\n if 1 > lng then return {}\n set xs_ to take(lng, xs) -- Allow for non-finite\n set ys_ to take(lng, ys) -- generators like cycle etc\n set lst to {}\n tell mReturn(f)\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs_, item i of ys_)\n end repeat\n return lst\n end tell\nend zipWith\n", "language": "AppleScript" }, { "code": "strings: [\n \"\", \".\", \"abcABC\", \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\",\n \"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X\",\n \"hétérogénéité\",\n \"🎆🎃🎇🎈\", \"😍😀🙌💃😍🙌\", \"🐠🐟🐡🦈🐬🐳🐋🐡\"\n]\n\nloop strings 'str [\n chars: split str\n prints [\"\\\"\" ++ str ++ \"\\\"\" ~\"(size |size str|):\"]\n\n if? chars = unique chars ->\n print \"has no duplicates.\"\n else [\n seen: #[]\n done: false\n\n i: 0\n while [and? i<size chars\n not? done][\n ch: chars\\[i]\n if? not? key? seen ch [\n seen\\[ch]: i\n ]\n else [\n print ~\"has duplicate char `|ch|` on |get seen ch| and |i|\"\n done: true\n ]\n i: i+1\n ]\n ]\n]\n", "language": "Arturo" }, { "code": "unique_characters(str){\n\tarr := [], res := \"\"\n\tfor i, v in StrSplit(str)\n\t\tarr[v] := arr[v] ? arr[v] \",\" i : i\n\tfor i, v in Arr\n\t\tif InStr(v, \",\")\n\t\t\tres .= v \"|\" i \" @ \" v \"`tHex = \" format(\"{1:X}\", Asc(i)) \"`n\"\n\tSort, res, N\n\tres := RegExReplace(res, \"`am)^[\\d,]+\\|\")\n\tres := StrSplit(res, \"`n\").1\n\treturn \"\"\"\" str \"\"\"`tlength = \" StrLen(str) \"`n\" (res ? \"Duplicates Found:`n\" res : \"Unique Characters\")\n}\n", "language": "AutoHotkey" }, { "code": "test := [\"\",\".\",\"abcABC\",\"XYZ ZYX\",\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"]\nfor i, v in test\n\tMsgBox % unique_characters(v)\nreturn\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f DETERMINE_IF_A_STRING_HAS_ALL_UNIQUE_CHARACTERS.AWK\nBEGIN {\n for (i=0; i<=255; i++) { ord_arr[sprintf(\"%c\",i)] = i } # build array[character]=ordinal_value\n n = split(\",.,abcABC,XYZ ZYX,1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\",arr,\",\")\n for (i in arr) {\n width = max(width,length(arr[i]))\n }\n width += 2\n fmt = \"| %-*s | %-6s | %-10s | %-8s | %-3s | %-9s |\\n\"\n head1 = head2 = sprintf(fmt,width,\"string\",\"length\",\"all unique\",\"1st diff\",\"hex\",\"positions\")\n gsub(/[^|\\n]/,\"-\",head1)\n printf(head1 head2 head1) # column headings\n for (i=1; i<=n; i++) {\n main(arr[i])\n }\n printf(head1) # column footing\n exit(0)\n}\nfunction main(str, c,hex,i,leng,msg,position1,position2,tmp_arr) {\n msg = \"yes\"\n leng = length(str)\n for (i=1; i<=leng; i++) {\n c = substr(str,i,1)\n if (c in tmp_arr) {\n msg = \"no\"\n first_diff = \"'\" c \"'\"\n hex = sprintf(\"%2X\",ord_arr[c])\n position1 = index(str,c)\n position2 = i\n break\n }\n tmp_arr[c] = \"\"\n }\n printf(fmt,width,\"'\" str \"'\",leng,msg,first_diff,hex,position1 \" \" position2)\n}\nfunction max(x,y) { return((x > y) ? x : y) }\n", "language": "AWK" }, { "code": "subroutine CaracteresUnicos (cad$)\n\tlngt = length(cad$)\n\tprint 'Cadena = \"'; cad$; '\", longitud = '; lngt\n\tfor i = 1 to lngt\n\t\tfor j = i + 1 to lngt\n\t\t\tif mid(cad$,i,1) = mid(cad$,j,1) then\n\t\t\t\tprint \" Primer duplicado en las posiciones \" & i & \" y \" & j & \", caracter = '\" & mid(cad$,i,1) & \"', valor hex = \" & tohex(asc(mid(cad$,i,1)))\n\t\t\t\treturn\n\t\t\tend if\n\t\tnext j\n\tnext i\n\tprint \" Todos los caracteres son unicos.\" & chr(10)\nend subroutine\n\ncall CaracteresUnicos(\"\")\ncall CaracteresUnicos(\".\")\ncall CaracteresUnicos(\"abcABC\")\ncall CaracteresUnicos(\"XYZ ZYX\")\ncall CaracteresUnicos(\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\")\n", "language": "BASIC256" }, { "code": "Check←=⌜˜\nHex←⊏⟜(∾\"0A\"+⟜↕¨10‿26)16{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}\n\n{\n 𝕊 str:\n r←Check str\n •Out {\n ∧´1=+´˘r ? \"All characters are unique\" ;\n i←/⊏(1<+´˘r)/r\n ch←(⊑i)⊑str\n \"'\"∾ch∾\"' (hex: \"∾(Hex ch-@)∾\", indices: \"∾(•Fmt i)∾\") duplicated in string '\"∾str∾\"'\"\n }\n}¨⟨\n \"\"\n \".\"\n \"abcABC\"\n \"XYZ ZYX\"\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"\n⟩\n", "language": "BQN" }, { "code": "All characters are unique\nAll characters are unique\nAll characters are unique\n'X' (hex: 58, indices: ⟨ 0 7 ⟩) duplicated in string 'XYZ ZYX'\n'0' (hex: 30, indices: ⟨ 9 24 ⟩) duplicated in string '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'\n", "language": "BQN" }, { "code": "#include<stdbool.h>\n#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct positionList{\n int position;\n struct positionList *next;\n}positionList;\n\ntypedef struct letterList{\n char letter;\n int repititions;\n positionList* positions;\n struct letterList *next;\n}letterList;\n\nletterList* letterSet;\nbool duplicatesFound = false;\n\nvoid checkAndUpdateLetterList(char c,int pos){\n bool letterOccurs = false;\n letterList *letterIterator,*newLetter;\n positionList *positionIterator,*newPosition;\n\n if(letterSet==NULL){\n letterSet = (letterList*)malloc(sizeof(letterList));\n letterSet->letter = c;\n letterSet->repititions = 0;\n\n letterSet->positions = (positionList*)malloc(sizeof(positionList));\n letterSet->positions->position = pos;\n letterSet->positions->next = NULL;\n\n letterSet->next = NULL;\n }\n\n else{\n letterIterator = letterSet;\n\n while(letterIterator!=NULL){\n if(letterIterator->letter==c){\n letterOccurs = true;\n duplicatesFound = true;\n\n letterIterator->repititions++;\n positionIterator = letterIterator->positions;\n\n while(positionIterator->next!=NULL)\n positionIterator = positionIterator->next;\n\n newPosition = (positionList*)malloc(sizeof(positionList));\n newPosition->position = pos;\n newPosition->next = NULL;\n\n positionIterator->next = newPosition;\n }\n if(letterOccurs==false && letterIterator->next==NULL)\n break;\n else\n letterIterator = letterIterator->next;\n }\n\n if(letterOccurs==false){\n newLetter = (letterList*)malloc(sizeof(letterList));\n newLetter->letter = c;\n\n newLetter->repititions = 0;\n\n newLetter->positions = (positionList*)malloc(sizeof(positionList));\n newLetter->positions->position = pos;\n newLetter->positions->next = NULL;\n\n newLetter->next = NULL;\n\n letterIterator->next = newLetter;\n }\n }\n}\n\nvoid printLetterList(){\n positionList* positionIterator;\n letterList* letterIterator = letterSet;\n\n while(letterIterator!=NULL){\n if(letterIterator->repititions>0){\n printf(\"\\n'%c' (0x%x) at positions :\",letterIterator->letter,letterIterator->letter);\n\n positionIterator = letterIterator->positions;\n\n while(positionIterator!=NULL){\n printf(\"%3d\",positionIterator->position + 1);\n positionIterator = positionIterator->next;\n }\n }\n\n letterIterator = letterIterator->next;\n }\n printf(\"\\n\");\n}\n\nint main(int argc,char** argv)\n{\n int i,len;\n\n if(argc>2){\n printf(\"Usage : %s <Test string>\\n\",argv[0]);\n return 0;\n }\n\n if(argc==1||strlen(argv[1])==1){\n printf(\"\\\"%s\\\" - Length %d - Contains only unique characters.\\n\",argc==1?\"\":argv[1],argc==1?0:1);\n return 0;\n }\n\n len = strlen(argv[1]);\n\n for(i=0;i<len;i++){\n checkAndUpdateLetterList(argv[1][i],i);\n }\n\n printf(\"\\\"%s\\\" - Length %d - %s\",argv[1],len,duplicatesFound==false?\"Contains only unique characters.\\n\":\"Contains the following duplicate characters :\");\n\n if(duplicatesFound==true)\n printLetterList();\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <string>\n\nvoid string_has_repeated_character(const std::string& str) {\n size_t len = str.length();\n std::cout << \"input: \\\"\" << str << \"\\\", length: \" << len << '\\n';\n for (size_t i = 0; i < len; ++i) {\n for (size_t j = i + 1; j < len; ++j) {\n if (str[i] == str[j]) {\n std::cout << \"String contains a repeated character.\\n\";\n std::cout << \"Character '\" << str[i]\n << \"' (hex \" << std::hex << static_cast<unsigned int>(str[i])\n << \") occurs at positions \" << std::dec << i + 1\n << \" and \" << j + 1 << \".\\n\\n\";\n return;\n }\n }\n }\n std::cout << \"String contains no repeated characters.\\n\\n\";\n}\n\nint main() {\n string_has_repeated_character(\"\");\n string_has_repeated_character(\".\");\n string_has_repeated_character(\"abcABC\");\n string_has_repeated_character(\"XYZ ZYX\");\n string_has_repeated_character(\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\");\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Linq;\n\npublic class Program\n{\n static void Main\n {\n string[] input = {\"\", \".\", \"abcABC\", \"XYZ ZYX\", \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"};\n foreach (string s in input) {\n Console.WriteLine($\"\\\"{s}\\\" (Length {s.Length}) \" +\n string.Join(\", \",\n s.Select((c, i) => (c, i))\n .GroupBy(t => t.c).Where(g => g.Count() > 1)\n .Select(g => $\"'{g.Key}' (0X{(int)g.Key:X})[{string.Join(\", \", g.Select(t => t.i))}]\")\n .DefaultIfEmpty(\"All characters are unique.\")\n )\n );\n }\n }\n}\n", "language": "C-sharp" }, { "code": "100 cls\n110 sub caracteresunicos(cad$)\n120 lngt = len(cad$)\n130 print 'Cadena = \"';cad$;'\" longitud = ';lngt\n140 for i = 1 to lngt\n150 for j = i+1 to lngt\n160 if mid$(cad$,i,1) = mid$(cad$,j,1) then\n170 print \" Primer duplicado en las posiciones \";i;\" y \";j;\", caracter = '\";mid$(cad$,i,1);\"', valor hex = \";hex$(asc(mid$(cad$,i,1)))\n180 print\n190 exit sub\n200 endif\n210 next j\n220 next i\n230 print \" Todos los caracteres son unicos.\";chr$(10)\n240 end sub\n250 caracteresunicos(\"\")\n260 caracteresunicos(\".\")\n270 caracteresunicos(\"abcABC\")\n280 caracteresunicos(\"XYZ ZYX\")\n290 caracteresunicos(\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\")\n300 end\n", "language": "Chipmunk-Basic" }, { "code": "(defn uniq-char-string [s]\n (let [len (count s)]\n (if (= len (count (set s)))\n (println (format \"All %d chars unique in: '%s'\" len s))\n (loop [prev-chars #{}\n idx 0\n chars (vec s)]\n (let [c (first chars)]\n (if (contains? prev-chars c)\n (println (format \"'%s' (len: %d) has '%c' duplicated at idx: %d\"\n s len c idx))\n (recur (conj prev-chars c)\n (inc idx)\n (rest chars))))))))\n", "language": "Clojure" }, { "code": ";; * Loading the iterate library\n(eval-when (:compile-toplevel :load-toplevel)\n (ql:quickload '(\"iterate\")))\n\n;; * The package definition\n(defpackage :unique-string\n (:use :common-lisp :iterate))\n(in-package :unique-string)\n\n;; * The test strings\n(defparameter test-strings\n '(\"\" \".\" \"abcABC\" \"XYZ ZYX\" \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"))\n\n;; * The function\n(defun unique-string (string)\n \"Returns T if STRING has all unique characters.\"\n (iter\n (with hash = (make-hash-table :test #'equal))\n (with len = (length string))\n (with result = T)\n (for char in-string string)\n (for pos from 0)\n (initially (format t \"String ~a of length ~D~%\" string len))\n (if #1=(gethash char hash)\n ;; The character was seen before\n (progn\n (format t\n \" --> Non-unique character ~c #X~X found at position ~D,\n before ~D ~%\" char (char-code char) pos #1#)\n (setf result nil))\n ;; The character was not seen before, saving its position\n (setf #1# pos))\n (finally (when result\n (format t \" --> All characters are unique~%\"))\n (return result))))\n\n(mapcar #'unique-string test-strings)\n", "language": "Common-Lisp" }, { "code": "import std.stdio;\n\nvoid uniqueCharacters(string str) {\n writefln(\"input: `%s`, length: %d\", str, str.length);\n foreach (i; 0 .. str.length) {\n foreach (j; i + 1 .. str.length) {\n if (str[i] == str[j]) {\n writeln(\"String contains a repeated character.\");\n writefln(\"Character '%c' (hex %x) occurs at positions %d and %d.\", str[i], str[i], i + 1, j + 1);\n writeln;\n return;\n }\n }\n }\n writeln(\"String contains no repeated characters.\");\n writeln;\n}\n\nvoid main() {\n uniqueCharacters(\"\");\n uniqueCharacters(\".\");\n uniqueCharacters(\"abcABC\");\n uniqueCharacters(\"XYZ ZYX\");\n uniqueCharacters(\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\");\n}\n", "language": "D" }, { "code": "program Determine_if_a_string_has_all_unique_characters;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils;\n\nprocedure string_has_repeated_character(str: string);\nvar\n len, i, j: Integer;\nbegin\n len := length(str);\n Writeln('input: \\', str, '\\, length: ', len);\n for i := 1 to len - 1 do\n begin\n for j := i + 1 to len do\n begin\n if str[i] = str[j] then\n begin\n Writeln('String contains a repeated character.');\n Writeln('Character \"', str[i], '\" (hex ', ord(str[i]).ToHexString,\n ') occurs at positions ', i + 1, ' and ', j + 1, '.'#10);\n Exit;\n end;\n end;\n end;\n Writeln('String contains no repeated characters.' + sLineBreak);\nend;\n\nbegin\n string_has_repeated_character('');\n string_has_repeated_character('.');\n string_has_repeated_character('abcABC');\n string_has_repeated_character('XYZ ZYX');\n string_has_repeated_character('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ');\n readln;\nend.\n", "language": "Delphi" }, { "code": "func$ hex h .\n for d in [ h div 16 h mod 16 ]\n if d > 9\n d += 7\n .\n h$ &= strchar (d + 48)\n .\n return h$\n.\nproc unichar s$ . .\n len d[] 65536\n s$[] = strchars s$\n for i to len s$[]\n h = strcode s$[i]\n if d[h] <> 0\n write \" --> duplicates: '\" & s$[i] & \"' (\" & hex h & \"h)\"\n print \"' positions: \" & d[h] & \", \" & i\n return\n .\n d[h] = i\n .\n print \"ok\"\n.\nrepeat\n s$ = input\n until s$ = \"EOF\"\n print \"'\" & s$ & \"'\" & \" length \" & len s$\n unichar s$\n print \"\"\n.\ninput_data\n\n.\nabcABC\nXYZ ZYX\n1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\nEOF\n", "language": "EasyLang" }, { "code": "-module(string_examples).\n-export([all_unique/1, all_unique_examples/0]).\n\nall_unique(String) ->\n CharPosPairs = lists:zip(String, lists:seq(1, length(String))),\n Duplicates = [{Char1, Pos1, Pos2} || {Char1, Pos1} <- CharPosPairs,\n {Char2, Pos2} <- CharPosPairs,\n Char1 =:= Char2,\n Pos2 > Pos1],\n case Duplicates of\n [] ->\n all_unique;\n [{Char, P1, P2}|_] ->\n {not_all_unique, Char, P1, P2}\n end.\n\nall_unique_examples() ->\n lists:foreach(fun (Str) ->\n io:format(\"String \\\"~ts\\\" (length ~p): \",\n [Str, length(Str)]),\n case all_unique(Str) of\n all_unique ->\n io:format(\"All characters unique.~n\");\n {not_all_unique, Char, P1, P2} ->\n io:format(\"First duplicate is '~tc' (0x~.16b)\"\n \" at positions ~p and ~p.~n\",\n [Char, Char, P1, P2])\n end\n end,\n [\"\", \".\", \"abcABC\", \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"]).\n", "language": "Erlang" }, { "code": "// Determine if a string has all unique characters. Nigel Galloway: June 9th., 2020\nlet fN (n:string)=n.ToCharArray()|>Array.mapi(fun n g->(n,g))|>Array.groupBy(fun (_,n)->n)|>Array.filter(fun(_,n)->n.Length>1)\n\nlet allUnique n=match fN n with\n g when g.Length=0->printfn \"All charcters in <<<%s>>> (length %d) are unique\" n n.Length\n |g->Array.iter(fun(n,g)->printf \"%A is repeated at positions\" n; Array.iter(fun(n,_)->printf \" %d\" n)g;printf \" \")g\n printfn \"in <<<%s>>> (length %d)\" n n.Length\n\nallUnique \"\"\nallUnique \".\"\nallUnique \"abcABC\"\nallUnique \"XYZ ZYX\"\nallUnique \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"\n", "language": "F-Sharp" }, { "code": "USING: formatting fry generalizations io kernel math.parser\nsequences sets ;\n\n: repeated ( elt seq -- )\n [ dup >hex over ] dip indices first2\n \" '%c' (0x%s) at indices %d and %d.\\n\" printf ;\n\n: uniqueness-report ( str -- )\n dup dup length \"%u — length %d — contains \" printf\n [ duplicates ] keep over empty?\n [ 2drop \"all unique characters.\" print ]\n [ \"repeated characters:\" print '[ _ repeated ] each ] if ;\n\n\"\"\n\".\"\n\"abcABC\"\n\"XYZ ZYX\"\n\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"\n[ uniqueness-report nl ] 5 napply\n", "language": "Factor" }, { "code": "program demo_verify\nimplicit none\n call nodup('')\n call nodup('.')\n call nodup('abcABC')\n call nodup('XYZ ZYX')\n call nodup('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ')\ncontains\n\nsubroutine nodup(str)\ncharacter(len=*),intent(in) :: str\ncharacter(len=*),parameter :: g='(*(g0))'\ncharacter(len=:),allocatable :: ch\ninteger :: where\ninteger :: i\n where=0\n ch=''\n\n do i=1,len(str)-1\n ch=str(i:i)\n where=index(str(i+1:),ch)\n if(where.ne.0)then\n where=where+i\n exit\n endif\n enddo\n\n if(where.eq.0)then\n write(*,g)'STR: \"',str,'\"',new_line('a'),'LEN: ',len(str),'. No duplicate characters found'\n else\n write(*,g)'STR: \"',str,'\"'\n write(*,'(a,a,t1,a,a)')repeat(' ',where+5),'^',repeat(' ',i+5),'^'\n write(*,g)'LEN: ',len(str), &\n & '. Duplicate chars. First duplicate at positions ',i,' and ',where, &\n & ' where a ','\"'//str(where:where)//'\"(hex:',hex(str(where:where)),') was found.'\n endif\n write(*,*)\n\nend subroutine nodup\n\nfunction hex(ch) result(hexstr)\ncharacter(len=1),intent(in) :: ch\ncharacter(len=:),allocatable :: hexstr\n hexstr=repeat(' ',100)\n write(hexstr,'(Z0)')ch\n hexstr=trim(hexstr)\nend function hex\n\nend program demo_verify\n", "language": "Fortran" }, { "code": "Sub CaracteresUnicos (cad As String)\n Dim As Integer lngt = Len(cad)\n Print \"Cadena = \"\"\"; cad; \"\"\", longitud = \"; lngt\n For i As Integer = 1 To lngt\n For j As Integer = i + 1 To lngt\n If Mid(cad,i,1) = Mid(cad,j,1) Then\n Print \" Primer duplicado en las posiciones \" & i & _\n \" y \" & j & \", caracter = '\" & Mid(cad,i,1) & _\n \"', valor hex = \" & Hex(Asc(Mid(cad,i,1)))\n Print\n Exit Sub\n End If\n Next j\n Next i\n Print \" Todos los caracteres son unicos.\" & Chr(10)\nEnd Sub\n\nCaracteresUnicos (\"\")\nCaracteresUnicos (\".\")\nCaracteresUnicos (\"abcABC\")\nCaracteresUnicos (\"XYZ ZYX\")\nCaracteresUnicos (\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\")\nSleep\n", "language": "FreeBASIC" }, { "code": "void local fn StringHasUniqueCharacters( string as CFStringRef )\n long i, j, length = len( string )\n\n if length == 0 then printf @\"The string \\\"\\\" is empty and thus has no characters to compare.\\n\" : exit fn\n\n printf @\"The string: \\\"%@\\\" has %ld characters.\", string, length\n\n for i = 0 to length - 1\n for j = i + 1 to length - 1\n if ( fn StringIsEqual( mid( string, i, 1 ), mid( string, j, 1 ) ) )\n CFStringRef duplicate = mid( string, i, 1 )\n printf @\"The first duplicate character, \\\"%@\\\", is found at positions %ld and %ld.\", duplicate, i, j\n printf @\"The hex value of \\\"%@\\\" is: 0X%x\\n\", duplicate, fn StringCharacterAtIndex( duplicate, 0 )\n exit fn\n end if\n next\n next\n printf @\"All characters in string are unique.\\n\"\nend fn\n\nfn StringHasUniqueCharacters( @\"\" )\nfn StringHasUniqueCharacters( @\".\" )\nfn StringHasUniqueCharacters( @\"abcABC\" )\nfn StringHasUniqueCharacters( @\"XYZ ZYX\" )\nfn StringHasUniqueCharacters( @\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\" )\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc analyze(s string) {\n chars := []rune(s)\n le := len(chars)\n fmt.Printf(\"Analyzing %q which has a length of %d:\\n\", s, le)\n if le > 1 {\n for i := 0; i < le-1; i++ {\n for j := i + 1; j < le; j++ {\n if chars[j] == chars[i] {\n fmt.Println(\" Not all characters in the string are unique.\")\n fmt.Printf(\" %q (%#[1]x) is duplicated at positions %d and %d.\\n\\n\", chars[i], i+1, j+1)\n return\n }\n }\n }\n }\n fmt.Println(\" All characters in the string are unique.\\n\")\n}\n\nfunc main() {\n strings := []string{\n \"\",\n \".\",\n \"abcABC\",\n \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\",\n \"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X\",\n \"hétérogénéité\",\n \"🎆🎃🎇🎈\",\n \"😍😀🙌💃😍🙌\",\n \"🐠🐟🐡🦈🐬🐳🐋🐡\",\n }\n for _, s := range strings {\n analyze(s)\n }\n}\n", "language": "Go" }, { "code": "class StringUniqueCharacters {\n static void main(String[] args) {\n printf(\"%-40s %2s %10s %8s %s %s%n\", \"String\", \"Length\", \"All Unique\", \"1st Diff\", \"Hex\", \"Positions\")\n printf(\"%-40s %2s %10s %8s %s %s%n\", \"------------------------\", \"------\", \"----------\", \"--------\", \"---\", \"---------\")\n for (String s : [\"\", \".\", \"abcABC\", \"XYZ ZYX\", \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"]) {\n processString(s)\n }\n }\n\n private static void processString(String input) {\n Map<Character, Integer> charMap = new HashMap<>()\n char dup = 0\n int index = 0\n int pos1 = -1\n int pos2 = -1\n for (char key : input.toCharArray()) {\n index++\n if (charMap.containsKey(key)) {\n dup = key\n pos1 = charMap.get(key)\n pos2 = index\n break\n }\n charMap.put(key, index)\n }\n String unique = (int) dup == 0 ? \"yes\" : \"no\"\n String diff = (int) dup == 0 ? \"\" : \"'\" + dup + \"'\"\n String hex = (int) dup == 0 ? \"\" : Integer.toHexString((int) dup).toUpperCase()\n String position = (int) dup == 0 ? \"\" : pos1 + \" \" + pos2\n printf(\"%-40s %-6d %-10s %-8s %-3s %-5s%n\", input, input.length(), unique, diff, hex, position)\n }\n}\n", "language": "Groovy" }, { "code": "import Data.List (groupBy, intersperse, sort, transpose)\nimport Data.Char (ord, toUpper)\nimport Data.Function(on)\nimport Numeric (showHex)\n\n\nhexFromChar :: Char -> String\nhexFromChar c = map toUpper $ showHex (ord c) \"\"\n\nstring :: String -> String\nstring xs = ('\\\"' : xs) <> \"\\\"\"\n\nchar :: Char -> String\nchar c = ['\\'', c, '\\'']\n\nsize :: String -> String\nsize = show . length\n\npositions :: (Int, Int) -> String\npositions (a, b) = show a <> \" \" <> show b\n\nforTable :: String -> [String]\nforTable xs = string xs : go (allUnique xs)\n where\n go Nothing = [size xs, \"yes\", \"\", \"\", \"\"]\n go (Just (u, ij)) = [size xs, \"no\", char u, hexFromChar u, positions ij]\n\nshowTable :: Bool -> Char -> Char -> Char -> [[String]] -> String\nshowTable _ _ _ _ [] = []\nshowTable header ver hor sep contents =\n unlines $\n hr :\n (if header\n then z : hr : zs\n else intersperse hr zss) <>\n [hr]\n where\n vss = map (map length) contents\n ms = map maximum (transpose vss) :: [Int]\n hr = concatMap (\\n -> sep : replicate n hor) ms <> [sep]\n top = replicate (length hr) hor\n bss = map (map (`replicate` ' ') . zipWith (-) ms) vss\n zss@(z:zs) =\n zipWith\n (\\us bs -> concat (zipWith (\\x y -> (ver : x) <> y) us bs) <> [ver])\n contents\n bss\n\ntable xs =\n showTable\n True\n '|'\n '-'\n '+'\n ([\"string\", \"length\", \"all unique\", \"1st diff\", \"hex\", \"positions\"] :\n map forTable xs)\n\nallUnique\n :: (Ord b, Ord a, Num b, Enum b)\n => [a] -> Maybe (a, (b, b))\nallUnique xs = go . groupBy (on (==) fst) . sort . zip xs $ [0 ..]\n where\n go [] = Nothing\n go ([_]:us) = go us\n go (((u, i):(_, j):_):_) = Just (u, (i, j))\n\nmain :: IO ()\nmain =\n putStrLn $\n table [\"\", \".\", \"abcABC\", \"XYZ ZYX\", \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"]\n", "language": "Haskell" }, { "code": "import Data.List (groupBy, intercalate, sortOn)\nimport Data.Function (on)\nimport Numeric (showHex)\nimport Data.Char (ord)\n\n\n------------- INDICES OF DUPLICATED CHARACTERS -----------\n\nduplicatedCharIndices :: String -> Maybe (Char, [Int])\nduplicatedCharIndices s\n | null duplicates = Nothing\n | otherwise =\n Just $\n ((,) . (snd . head) <*> fmap fst) (head (sortOn (fst . head) duplicates))\n where\n duplicates =\n filter ((1 <) . length) $\n groupBy (on (==) snd) $ sortOn snd $ zip [0 ..] s\n\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n putStrLn $\n fTable\n \"First duplicated character, if any:\"\n (fmap (<>) show <*> ((\" (\" <>) . (<> \")\") . show . length))\n (maybe\n \"None\"\n (\\(c, ixs) ->\n unwords\n [ show c\n , \"(0x\" <> showHex (ord c) \") at\"\n , intercalate \", \" (show <$> ixs)\n ]))\n duplicatedCharIndices\n [\"\", \".\", \"abcABC\", \"XYZ ZYX\", \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"]\n\n\n------------------------- DISPLAY ------------------------\n\nfTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String\nfTable s xShow fxShow f xs =\n unlines $\n s : fmap (((<>) . rjust w ' ' . xShow) <*> ((\" -> \" <>) . fxShow . f)) xs\n where\n rjust n c = drop . length <*> (replicate n c <>)\n w = maximum (length . xShow <$> xs)\n", "language": "Haskell" }, { "code": "import qualified Safe as S\nimport qualified Data.Map.Strict as M\nimport Data.List (intercalate, foldl') --'\nimport Data.Ord (comparing)\nimport Numeric (showHex)\nimport Data.Char (ord)\n\n\n----------- INDICES OF ANY DUPLICATED CHARACTERS ---------\n\nduplicatedCharIndices :: String -> Maybe (Char, [Int])\nduplicatedCharIndices xs =\n S.minimumByMay\n (comparing (head . snd))\n (M.toList\n (M.filter\n ((1 <) . length)\n (foldl' --'\n (\\a (i, c) -> M.insert c (maybe [i] (<> [i]) (M.lookup c a)) a)\n M.empty\n (zip [0 ..] xs))))\n\n-- OR, fusing filter, toList, and minimumByMay down to a single fold:\nduplicatedCharIndices_ :: String -> Maybe (Char, [Int])\nduplicatedCharIndices_ xs =\n M.foldrWithKey\n go\n Nothing\n (foldl' --'\n (\\a (i, c) -> M.insert c (maybe [i] (<> [i]) (M.lookup c a)) a)\n M.empty\n (zip [0 ..] xs))\n where\n go k [_] mb = mb -- Unique\n go k xs Nothing = Just (k, xs) -- Duplicated\n go k xs@(x:_) (Just (c, ys@(y:_)))\n | x < y = Just (k, xs) -- Earlier duplication\n | otherwise = Just (c, ys)\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n putStrLn $\n fTable\n \"First duplicated character, if any:\"\n ((<>) <$> show <*> ((\" (\" <>) . (<> \")\") . show . length))\n (maybe\n \"None\"\n (\\(c, ixs) ->\n unwords\n [ show c\n , \"(0x\" <> showHex (ord c) \") at\"\n , intercalate \", \" (show <$> ixs)\n ]))\n duplicatedCharIndices_\n [\"\", \".\", \"abcABC\", \"XYZ ZYX\", \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"]\n\n------------------------- DISPLAY ------------------------\nfTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String\nfTable s xShow fxShow f xs =\n unlines $\n s : fmap (((<>) . rjust w ' ' . xShow) <*> ((\" -> \" <>) . fxShow . f)) xs\n where\n rjust n c = drop . length <*> (replicate n c <>)\n w = maximum (length . xShow <$> xs)\n", "language": "Haskell" }, { "code": "rc_unique=: monad define\n string=. '\"' , y , '\"'\n self_classification=. = y NB. deprecated- consumes space proportional to the squared tally of y (*: # y)\n is_unique=. self_classification =&# y\n if. is_unique do.\n (# y) ; string ; 'unique'\n else.\n duplicate_masks=. (#~ (1 < +/\"1)) self_classification\n duplicate_characters=. ~. y #~ +./ duplicate_masks\n ASCII_values_of_duplicates=. a. i. duplicate_characters\n markers=. duplicate_masks { ' ^'\n A=. (# y) ; string , ' ' ,. markers\n B=. 'duplicate' , ASCII_values_of_duplicates ('<' , (#~ 31&<)~ , '> ASCII ' , \":@:[)\"0 duplicate_characters\n A , < B\n end.\n)\n", "language": "J" }, { "code": "NB. unique_index answers \"Do the left and right indexes match?\"\nunique_index=: (i. -: i:)~\nassert 0 1 -: 2 unique_index\\0 0 1\n\nNB. unique_set answers \"Are lengths of the nub and original equal?\"\nunique_set=: -:&# ~.\nassert 0 1 -: _2 unique_set\\'aab'\n\nNB. unique_nubsieve answers \"Are the items unique?\"\nunique_nubsieve=: 0 -.@:e. ~:\nassert 0 1 -: _2 unique_nubsieve\\'aab'\n\nNote'compared to nubsieve'\n the index method takes 131% longer and 15 times additional memory\n the set formation method 15% longer and uses 7 times additional memory.\n)\n", "language": "J" }, { "code": "import java.util.HashMap;\nimport java.util.Map;\n\n// Title: Determine if a string has all unique characters\n\npublic class StringUniqueCharacters {\n\n public static void main(String[] args) {\n System.out.printf(\"%-40s %2s %10s %8s %s %s%n\", \"String\", \"Length\", \"All Unique\", \"1st Diff\", \"Hex\", \"Positions\");\n System.out.printf(\"%-40s %2s %10s %8s %s %s%n\", \"------------------------\", \"------\", \"----------\", \"--------\", \"---\", \"---------\");\n for ( String s : new String[] {\"\", \".\", \"abcABC\", \"XYZ ZYX\", \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"} ) {\n processString(s);\n }\n }\n\n\n\n private static void processString(String input) {\n Map<Character,Integer> charMap = new HashMap<>();\n char dup = 0;\n int index = 0;\n int pos1 = -1;\n int pos2 = -1;\n for ( char key : input.toCharArray() ) {\n index++;\n if ( charMap.containsKey(key) ) {\n dup = key;\n pos1 = charMap.get(key);\n pos2 = index;\n break;\n }\n charMap.put(key, index);\n }\n String unique = dup == 0 ? \"yes\" : \"no\";\n String diff = dup == 0 ? \"\" : \"'\" + dup + \"'\";\n String hex = dup == 0 ? \"\" : Integer.toHexString(dup).toUpperCase();\n String position = dup == 0 ? \"\" : pos1 + \" \" + pos2;\n System.out.printf(\"%-40s %-6d %-10s %-8s %-3s %-5s%n\", input, input.length(), unique, diff, hex, position);\n }\n\n}\n", "language": "Java" }, { "code": "import java.util.HashSet;\nimport java.util.List;\nimport java.util.OptionalInt;\nimport java.util.Set;\n\npublic final class DetermineUniqueCharacters {\n\n\tpublic static void main(String[] aArgs) {\n\t\tList<String> words = List.of( \"\", \".\", \"abcABC\", \"XYZ ZYX\", \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\" );\n\t\t\n\t\tfor ( String word : words ) {\t\t\n\t\t\tSet<Integer> seen = new HashSet<Integer>();\n\t OptionalInt first = word.chars().filter( ch -> ! seen.add(ch) ).findFirst();\n\t if ( first.isPresent() ) {\t\n\t final char ch = (char) first.getAsInt();\n\t final String hex = Integer.toHexString(ch).toUpperCase();\n\t System.out.println(\"Word: \\\"\" + word + \"\\\" contains a repeated character.\");\n\t System.out.println(\"Character '\" + ch + \"' (hex \" + hex + \") occurs at positions \"\n\t \t+ word.indexOf(ch) + \" and \" + word.indexOf(ch, word.indexOf(ch) + 1));\n\t } else {\n\t \tSystem.out.println(\"Word: \\\"\" + word + \"\\\" has all unique characters.\");\n\t }\n\t System.out.println();\t\t\t\n\t\t}\n\t}\n\n}\n", "language": "Java" }, { "code": "(() => {\n 'use strict';\n\n // duplicatedCharIndices :: String -> Maybe (Char, [Int])\n const duplicatedCharIndices = s => {\n const\n duplicates = filter(g => 1 < g.length)(\n groupBy(on(eq)(snd))(\n sortOn(snd)(\n zip(enumFrom(0))(chars(s))\n )\n )\n );\n return 0 < duplicates.length ? Just(\n fanArrow(compose(snd, fst))(map(fst))(\n sortOn(compose(fst, fst))(\n duplicates\n )[0]\n )\n ) : Nothing();\n };\n\n // ------------------------TEST------------------------\n const main = () =>\n console.log(\n fTable('First duplicated character, if any:')(\n s => `'${s}' (${s.length})`\n )(maybe('None')(tpl => {\n const [c, ixs] = Array.from(tpl);\n return `'${c}' (0x${showHex(ord(c))}) at ${ixs.join(', ')}`\n }))(duplicatedCharIndices)([\n \"\", \".\", \"abcABC\", \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"\n ])\n );\n\n\n // -----------------GENERIC FUNCTIONS------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a => b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // chars :: String -> [Char]\n const chars = s => s.split('');\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n x => fs.reduceRight((a, f) => f(a), x);\n\n // enumFrom :: Enum a => a -> [a]\n function* enumFrom(x) {\n let v = x;\n while (true) {\n yield v;\n v = 1 + v;\n }\n }\n\n // eq (==) :: Eq a => a -> a -> Bool\n const eq = a => b => a === b;\n\n // fanArrow (&&&) :: (a -> b) -> (a -> c) -> (a -> (b, c))\n const fanArrow = f =>\n // Compose a function from a simple value to a tuple of\n // the separate outputs of two different functions.\n g => x => Tuple(f(x))(g(x));\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = f => xs => xs.filter(f);\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // fTable :: String -> (a -> String) -> (b -> String)\n // -> (a -> b) -> [a] -> String\n const fTable = s => xShow => fxShow => f => xs => {\n // Heading -> x display function ->\n // fx display function ->\n // f -> values -> tabular string\n const\n ys = xs.map(xShow),\n w = Math.max(...ys.map(length));\n return s + '\\n' + zipWith(\n a => b => a.padStart(w, ' ') + ' -> ' + b\n )(ys)(\n xs.map(x => fxShow(f(x)))\n ).join('\\n');\n };\n\n // groupBy :: (a -> a -> Bool) -> [a] -> [[a]]\n const groupBy = fEq =>\n // Typical usage: groupBy(on(eq)(f), xs)\n xs => 0 < xs.length ? (() => {\n const\n tpl = xs.slice(1).reduce(\n (gw, x) => {\n const\n gps = gw[0],\n wkg = gw[1];\n return fEq(wkg[0])(x) ? (\n Tuple(gps)(wkg.concat([x]))\n ) : Tuple(gps.concat([wkg]))([x]);\n },\n Tuple([])([xs[0]])\n );\n return tpl[0].concat([tpl[1]])\n })() : [];\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f => xs =>\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // maybe :: b -> (a -> b) -> Maybe a -> b\n const maybe = v =>\n // Default value (v) if m is Nothing, or f(m.Just)\n f => m => m.Nothing ? v : f(m.Just);\n\n // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c\n const on = f =>\n g => a => b => f(g(a))(g(b));\n\n // ord :: Char -> Int\n const ord = c => c.codePointAt(0);\n\n // showHex :: Int -> String\n const showHex = n =>\n n.toString(16);\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // sortOn :: Ord b => (a -> b) -> [a] -> [a]\n const sortOn = f =>\n // Equivalent to sortBy(comparing(f)), but with f(x)\n // evaluated only once for each x in xs.\n // ('Schwartzian' decorate-sort-undecorate).\n xs => xs.map(\n x => [f(x), x]\n ).sort(\n (a, b) => a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0)\n ).map(x => x[1]);\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n => xs =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // uncurry :: (a -> b -> c) -> ((a, b) -> c)\n const uncurry = f =>\n (x, y) => f(x)(y)\n\n // zip :: [a] -> [b] -> [(a, b)]\n const zip = xs => ys => {\n const\n lng = Math.min(length(xs), length(ys)),\n vs = take(lng)(ys);\n return take(lng)(xs)\n .map((x, i) => Tuple(x)(vs[i]));\n };\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n xs => ys => {\n const\n lng = Math.min(length(xs), length(ys)),\n vs = take(lng)(ys);\n return take(lng)(xs)\n .map((x, i) => f(x)(vs[i]));\n };\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "(() => {\n 'use strict';\n\n // duplicatedCharIndices :: String -> Maybe (Char, [Int])\n const duplicatedCharIndices = s =>\n minimumByMay(\n comparing(compose(fst, snd))\n )(filter(x => 1 < x[1].length)(\n Object.entries(\n s.split('').reduce(\n (a, c, i) => Object.assign(a, {\n [c]: (a[c] || []).concat(i)\n }), {}\n )\n )\n ));\n\n // ------------------------TEST------------------------\n const main = () =>\n console.log(\n fTable('First duplicated character, if any:')(\n s => `'${s}' (${s.length })`\n )(maybe('None')(tpl => {\n const [c, ixs] = Array.from(tpl);\n return `'${c}' (0x${showHex(ord(c))}) at ${ixs.join(', ')}`\n }))(duplicatedCharIndices)([\n \"\", \".\", \"abcABC\", \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"\n ])\n );\n\n\n // -----------------GENERIC FUNCTIONS------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a => b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // chars :: String -> [Char]\n const chars = s => s.split('');\n\n // comparing :: (a -> b) -> (a -> a -> Ordering)\n const comparing = f =>\n x => y => {\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : (a > b ? 1 : 0);\n };\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n x => fs.reduceRight((a, f) => f(a), x);\n\n // enumFrom :: Enum a => a -> [a]\n function* enumFrom(x) {\n let v = x;\n while (true) {\n yield v;\n v = 1 + v;\n }\n }\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = f => xs => xs.filter(f);\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // fTable :: String -> (a -> String) -> (b -> String)\n // -> (a -> b) -> [a] -> String\n const fTable = s => xShow => fxShow => f => xs => {\n // Heading -> x display function ->\n // fx display function ->\n // f -> values -> tabular string\n const\n ys = xs.map(xShow),\n w = Math.max(...ys.map(length));\n return s + '\\n' + zipWith(\n a => b => a.padStart(w, ' ') + ' -> ' + b\n )(ys)(\n xs.map(x => fxShow(f(x)))\n ).join('\\n');\n };\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // maybe :: b -> (a -> b) -> Maybe a -> b\n const maybe = v =>\n // Default value (v) if m is Nothing, or f(m.Just)\n f => m => m.Nothing ? v : f(m.Just);\n\n // minimumByMay :: (a -> a -> Ordering) -> [a] -> Maybe a\n const minimumByMay = f =>\n xs => xs.reduce((a, x) =>\n a.Nothing ? Just(x) : (\n f(x)(a.Just) < 0 ? Just(x) : a\n ), Nothing());\n\n // ord :: Char -> Int\n const ord = c => c.codePointAt(0);\n\n // showHex :: Int -> String\n const showHex = n =>\n n.toString(16);\n\n // snd :: (a, b) -> b\n const snd = tpl =>\n tpl[1];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n xs => 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n xs => ys => {\n const\n lng = Math.min(length(xs), length(ys)),\n vs = take(lng)(ys);\n return take(lng)(xs)\n .map((x, i) => f(x)(vs[i]));\n };\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "# Emit null if there is no duplicate, else [c, [ix1, ix2]]\ndef firstDuplicate:\n label $out\n | foreach explode[] as $i ({ix: -1};\n .ix += 1\n | .ix as $ix\n | .iu = ([$i] | implode)\n | .[.iu] += [ $ix] ;\n if .[.iu]|length == 2 then [.iu, .[.iu]], break $out else empty end )\n // null ;\n", "language": "Jq" }, { "code": "# hex of a number or a single (unicode) character\ndef hex:\n def stream:\n recurse(if . >= 16 then ./16|floor else empty end) | . % 16 ;\n if type==\"string\" then explode[0] else . end\n | [stream] | reverse\n | map(if . < 10 then 48 + . else . + 87 end) | implode ;\n\ndef lpad($len): tostring | \" \" * ($len - width) + .;\n\ndef q: \"«\\(.)»\";\n\ndef header:\n \"\\(\"string\"|q|lpad(38)) : |s| : C : hex IO=0\";\n\ndef data:\n \"\",\n \".\",\n \"abcABC\",\n \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\",\n \"😍😀🙌💃😍🙌\" ;\n", "language": "Jq" }, { "code": "header,\n (data\n | firstDuplicate as [$k, $v]\n | \"\\(q|lpad(38)) : \\(length|lpad(4)) : \\($k // \" \") : \\($k |if . then hex else \" \" end) \\($v // [])\" )\n", "language": "Jq" }, { "code": " «string» : |s| : C : hex IO=0\n «» : 0 : : []\n «.» : 1 : : []\n «abcABC» : 6 : : []\n «XYZ ZYX» : 7 : Z : 5A [2,4]\n«1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ» : 36 : 0 : 30 [9,24]\n «😍😀🙌💃😍🙌» : 6 : 😍:1f60d [0,4]\n", "language": "Jq" }, { "code": "arr(s) = [c for c in s]\nalldup(a) = filter(x -> length(x) > 1, [findall(x -> x == a[i], a) for i in 1:length(a)])\nfirstduplicate(s) = (a = arr(s); d = alldup(a); isempty(d) ? nothing : first(d))\n\nfunction testfunction(strings)\n println(\"String | Length | All Unique | First Duplicate | Positions\\n\" *\n \"-------------------------------------------------------------------------------------\")\n for s in strings\n n = firstduplicate(s)\n a = arr(s)\n println(rpad(s, 38), rpad(length(s), 11), n == nothing ? \"yes\" :\n rpad(\"no $(a[n[1]])\", 26) * rpad(n[1], 4) * \"$(n[2])\")\n end\nend\n\ntestfunction([\n\"\",\n\".\",\n\"abcABC\",\n\"XYZ ZYX\",\n\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\",\n \"hétérogénéité\",\n\"🎆🎃🎇🎈\",\n\"😍😀🙌💃😍🙌\",\n\"🐠🐟🐡🦈🐬🐳🐋🐡\",\n])\n", "language": "Julia" }, { "code": "import java.util.HashMap\n\nfun main() {\n System.out.printf(\"%-40s %2s %10s %8s %s %s%n\", \"String\", \"Length\", \"All Unique\", \"1st Diff\", \"Hex\", \"Positions\")\n System.out.printf(\"%-40s %2s %10s %8s %s %s%n\", \"------------------------\", \"------\", \"----------\", \"--------\", \"---\", \"---------\")\n for (s in arrayOf(\"\", \".\", \"abcABC\", \"XYZ ZYX\", \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\")) {\n processString(s)\n }\n}\n\nprivate fun processString(input: String) {\n val charMap: MutableMap<Char, Int?> = HashMap()\n var dup = 0.toChar()\n var index = 0\n var pos1 = -1\n var pos2 = -1\n for (key in input.toCharArray()) {\n index++\n if (charMap.containsKey(key)) {\n dup = key\n pos1 = charMap[key]!!\n pos2 = index\n break\n }\n charMap[key] = index\n }\n val unique = if (dup.toInt() == 0) \"yes\" else \"no\"\n val diff = if (dup.toInt() == 0) \"\" else \"'$dup'\"\n val hex = if (dup.toInt() == 0) \"\" else Integer.toHexString(dup.toInt()).toUpperCase()\n val position = if (dup.toInt() == 0) \"\" else \"$pos1 $pos2\"\n System.out.printf(\"%-40s %-6d %-10s %-8s %-3s %-5s%n\", input, input.length, unique, diff, hex, position)\n}\n", "language": "Kotlin" }, { "code": "local find, format = string.find, string.format\nlocal function printf(fmt, ...) print(format(fmt,...)) end\n\nlocal pattern = '(.).-%1' -- '(.)' .. '.-' .. '%1'\n\nfunction report_dup_char(subject)\n local pos1, pos2, char = find(subject, pattern)\n\n local prefix = format('\"%s\" (%d)', subject, #subject)\n if pos1 then\n local byte = char:byte()\n printf(\"%s: '%s' (0x%02x) duplicates at %d, %d\", prefix, char, byte, pos1, pos2)\n else\n printf(\"%s: no duplicates\", prefix)\n end\nend\n\nlocal show = report_dup_char\nshow('coccyx')\nshow('')\nshow('.')\nshow('abcABC')\nshow('XYZ ZYX')\nshow('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ')\n", "language": "Lua" }, { "code": "CheckUnique:=proc(s)\n\tlocal i, index;\n\tprintf(\"input: \\\"%s\\\", length: %a\\n\", s, StringTools:-Length(s));\n\tfor i from 1 to StringTools:-Length(s) do\n\t\tindex := StringTools:-SearchAll(s[i], s);\t\n\t\tif (numelems([index]) > 1) then\n\t\t\tprintf(\"The given string has duplicated characters.\\n\");\n\t\t\tprintf(\"The first duplicated character is %a (0x%x) which appears at index %a.\\n\\n\",\n\t\t\t\t s[i], convert(s[i], 'bytes')[1], {index});\n\t\t\treturn;\n\t\tend if;\n\tend do;\n\t# if no repeated found\n\tprintf(\"The given string has all unique characters.\\n\\n\");\nend proc:\n\n# Test\nCheckUnique(\"\");\nCheckUnique(\".\");\nCheckUnique(\"abcABC\");\nCheckUnique(\"XYZ ZYX\");\nCheckUnique(\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\");\n", "language": "Maple" }, { "code": "ClearAll[UniqueCharacters]\nUniqueCharacters[s_String] := Module[{c, len, good = True},\n c = Characters[s];\n len = Length[c];\n Print[s, \" with length \", len];\n Do[\n If[c[[i]] == c[[j]],\n Print[\"Character \", c[[i]], \" is repeated at positions \", i,\n \" and \", j];\n good = False\n ]\n ,\n {i, len - 1},\n {j, i + 1, len}\n ];\n If[good,\n Print[\"No repeats\"];\n True\n ,\n False\n ]\n ]\nUniqueCharacters[\"\"]\nUniqueCharacters[\".\"]\nUniqueCharacters[\"abcABC\"]\nUniqueCharacters[\"XYZ ZYX\"]\nUniqueCharacters[\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"]\n", "language": "Mathematica" }, { "code": "def analyze(s)\n s = str(s)\n println \"Examining [\" + s + \"] which has a length of \" + str(len(s)) + \":\"\n\n if len(s) < 2\n println \"\\tAll characters in the string are unique.\"\n return\n end\n\n seen = list()\n for i in range(0, len(s) - 2)\n if s[i] in seen\n println \"\\tNot all characters in the string are unique.\"\n println \"\\t'\" + s[i] + \"' \" + format(\"(0x%x)\", ord(s[i])) +\\\n \" is duplicated at positions \" + str(i + 1) + \" and \" +\\\n str(s.indexOf(s[i]) + 1)\n return\n end\n seen.append(s[i])\n end\n\n println \"\\tAll characters in the string are unique.\"\nend\n\ntests = {\"\", \".\", \"abcABC\", \"XYZ ZYX\", \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"}\nfor s in tests\n analyze(s)\nend\n", "language": "Nanoquery" }, { "code": "import unicode, strformat\n\nproc checkUniqueChars(s: string) =\n\n echo fmt\"Checking string \"\"{s}\"\":\"\n let runes = s.toRunes\n for i in 0..<runes.high:\n let rune = runes[i]\n for j in (i+1)..runes.high:\n if runes[j] == rune:\n echo \"The string contains duplicate characters.\"\n echo fmt\"Character {rune} ({int(rune):x}) is present at positions {i+1} and {j+1}.\"\n echo \"\"\n return\n echo \"All characters in the string are unique.\"\n echo \"\"\n\nconst Strings = [\"\",\n \".\",\n \"abcABC\",\n \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\",\n \"hétérogénéité\",\n \"🎆🎃🎇🎈\",\n \"😍😀🙌💃😍🙌\",\n \"🐠🐟🐡🦈🐬🐳🐋🐡\"]\n\nfor s in Strings:\n s.checkUniqueChars()\n", "language": "Nim" }, { "code": "module CMap = Map.Make(struct\n type t = char\n let compare = compare\nend)\n\n(** Add index as argument to string.fold_left *)\nlet string_fold_left_i f acc str =\n snd (String.fold_left\n (fun (index, acc) char -> (index+1, f acc index char))\n (0, acc) str)\n\nexception Found of int * int * char\n\nlet has_duplicates str =\n try let _ = string_fold_left_i\n (fun map index char ->\n match CMap.find_opt char map with\n | None -> CMap.add char index map\n | Some i -> raise (Found (i,index,char)))\n CMap.empty str\n in Ok ()\n with Found (i,j,c) -> Error (i,j,c)\n\nlet printer str =\n Format.printf \"%S (len %d) : \" str (String.length str);\n match has_duplicates str with\n | Ok () -> Format.printf \"No duplicates.\\n\"\n | Error (i,j,c) -> Format.printf \"Duplicate '%c' (%#x) at %d and %d\\n\" c (int_of_char c) i j\n\nlet () =\n printer \"\";\n printer \".\";\n printer \"abcABC\";\n printer \"XYZ ZYX\";\n printer \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"\n", "language": "OCaml" }, { "code": "use strict;\nuse warnings;\nuse feature 'say';\nuse utf8;\nbinmode(STDOUT, ':utf8');\nuse List::AllUtils qw(uniq);\nuse Unicode::UCD 'charinfo';\n\nfor my $str (\n '',\n '.',\n 'abcABC',\n 'XYZ ZYX',\n '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ',\n '01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X',\n 'Δ👍👨👍Δ',\n 'ΔδΔ̂ΔΛ',\n) {\n my @S;\n push @S, $1 while $str =~ /(\\X)/g;\n printf qq{\\n\"$str\" (length: %d) has }, scalar @S;\n if (@S != uniq @S ) {\n say \"duplicated characters:\";\n my %P;\n push @{ $P{$S[$_]} }, 1+$_ for 0..$#S;\n for my $k (sort keys %P) {\n next unless @{$P{$k}} > 1;\n printf \"'%s' %s (0x%x) in positions: %s\\n\", $k, charinfo(ord $k)->{'name'}, ord($k), join ', ', @{$P{$k}};\n }\n } else {\n say \"no duplicated characters.\"\n }\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">all_uniq</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">chars</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">posns</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span>\n <span style=\"color: #000000;\">multi</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">lm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">si</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">chars</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">chars</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">si</span>\n <span style=\"color: #000000;\">posns</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">}}</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">posns</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">i</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">posns</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">])=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">multi</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">k</span>\n <span style=\"color: #000000;\">lm</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\\\"%s\\\" (length %d): \"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)}),</span>\n <span style=\"color: #000000;\">nod</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">ordinal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lm</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">ess</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"s\"</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">lm</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lm</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"all characters are unique\"</span>\n <span style=\"color: #0000FF;\">:</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"contains %s duplicate%s:\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">nod</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ess</span><span style=\"color: #0000FF;\">}))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">multi</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">mi</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">multi</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">ci</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">chars</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">mi</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s '%c'(#%02x) at %V\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">posns</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">mi</span><span style=\"color: #0000FF;\">]})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\".\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"abcABC\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"XYZ ZYX\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"2\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"333\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"55\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"tttTTT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"tTTTtt\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"4444 444k\"</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #7060A8;\">papply</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">all_uniq</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "(de burn (Lst)\n (let P 0\n (by\n '((A)\n (set A (inc 'P))\n (put A 'P (char A)) )\n group\n Lst ) ) )\n(de first (Lst)\n (mini\n '((L)\n (nand\n (cdr L)\n (apply min (mapcar val L)) ) )\n Lst ) )\n(de uniq? (Str)\n (let M (first (burn (chop Str)))\n (ifn M\n (prinl Str \" (length \" (length Str) \"): all characters are unique\")\n (prin\n Str \" (length \" (length Str) \"): first duplicate character \"\n (car M)\n \" at positions \" )\n (println (mapcar val M)) ) ) )\n(uniq?)\n(uniq? \".\")\n(uniq? \"abcABC\")\n(uniq? \"XYZ ZYX\")\n(uniq? \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\")\n", "language": "PicoLisp" }, { "code": "report_duplicates(S) :-\n\tduplicates(S, Dups),\t\t\n\tformat('For value \"~w\":~n', S),\n\treport(Dups),\n\tnl.\n\t\nreport(Dups) :-\n\tmaplist(only_one_position, Dups),\n\tformat(' All characters are unique~n').\n\t\nreport(Dups) :-\n\texclude(only_one_position, Dups, [c(Char,Positions)|_]),\n\treverse(Positions, PosInOrder),\n\tatomic_list_concat(PosInOrder, ', ', PosAsList),\n\tformat(' The character ~w is non unique at ~p~n', [Char, PosAsList]).\t\n\t\nonly_one_position(c(_,[_])).\t\n\t\nduplicates(S, Count) :-\n\tatom_chars(S, Chars),\n\tchar_count(Chars, 0, [], Count).\n\t\t\nchar_count([], _, C, C).\nchar_count([C|T], Index, Counted, Result) :-\n\tselect(c(C,Positions), Counted, MoreCounted),\n\tsucc(Index, Index1),\n\tchar_count(T, Index1, [c(C,[Index|Positions])|MoreCounted], Result).\nchar_count([C|T], Index, Counted, Result) :-\n\t\\+ member(c(C,_), Counted),\n\tsucc(Index, Index1),\n\tchar_count(T, Index1, [c(C,[Index])|Counted], Result).\n\t\ntest :-\treport_duplicates('').\ntest :-\treport_duplicates('.').\ntest :-\treport_duplicates('abcABC').\ntest :-\treport_duplicates('XYZ ZYX').\ntest :-\treport_duplicates('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ').\n", "language": "Prolog" }, { "code": "Procedure CaracteresUnicos(cad.s)\n lngt.i = Len(cad)\n PrintN(\"Cadena = '\" + cad + \"' longitud = \" + Str(lngt))\n For i.i = 1 To lngt\n For j.i = i + 1 To lngt\n If Mid(cad, i, 1) = Mid(cad, j, 1)\n PrintN(\" Primer duplicado en las posiciones \" + Str(i) + \" y \" + Str(j) + \", caracter = '\" + Mid(cad, i, 1) + \"', valor hex = \" + Hex(Asc(Mid(cad, i, 1))))\n ProcedureReturn\n EndIf\n Next\n Next\n PrintN(\" Todos los caracteres son unicos.\")\nEndProcedure\n\nOpenConsole()\nCaracteresUnicos(\"\")\nCaracteresUnicos(\".\")\nCaracteresUnicos(\"abcABC\")\nCaracteresUnicos(\"XYZ ZYX\")\nCaracteresUnicos(\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\")\nPrintN(#CRLF$ + \"--- Press ENTER to exit ---\"): Input()\nCloseConsole()\n", "language": "PureBasic" }, { "code": "'''Determine if a string has all unique characters'''\n\nfrom itertools import groupby\n\n\n# duplicatedCharIndices :: String -> Maybe (Char, [Int])\ndef duplicatedCharIndices(s):\n '''Just the first duplicated character, and\n the indices of its occurrence, or\n Nothing if there are no duplications.\n '''\n def go(xs):\n if 1 < len(xs):\n duplicates = list(filter(lambda kv: 1 < len(kv[1]), [\n (k, list(v)) for k, v in groupby(\n sorted(xs, key=swap),\n key=snd\n )\n ]))\n return Just(second(fmap(fst))(\n sorted(\n duplicates,\n key=lambda kv: kv[1][0]\n )[0]\n )) if duplicates else Nothing()\n else:\n return Nothing()\n return go(list(enumerate(s)))\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test over various strings.'''\n\n def showSample(s):\n return repr(s) + ' (' + str(len(s)) + ')'\n\n def showDuplicate(cix):\n c, ix = cix\n return repr(c) + (\n ' (' + hex(ord(c)) + ') at ' + repr(ix)\n )\n\n print(\n fTable('First duplicated character, if any:')(\n showSample\n )(maybe('None')(showDuplicate))(duplicatedCharIndices)([\n '', '.', 'abcABC', 'XYZ ZYX',\n '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'\n ])\n )\n\n\n# FORMATTING ----------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# GENERIC -------------------------------------------------\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.\n Wrapper containing the result of a computation.\n '''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.\n Empty wrapper returned where a computation is not possible.\n '''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# fmap :: (a -> b) -> [a] -> [b]\ndef fmap(f):\n '''fmap over a list.\n f lifted to a function over a list.\n '''\n return lambda xs: [f(x) for x in xs]\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First member of a pair.'''\n return tpl[0]\n\n\n# head :: [a] -> a\ndef head(xs):\n '''The first element of a non-empty list.'''\n return xs[0] if isinstance(xs, list) else next(xs)\n\n\n# maybe :: b -> (a -> b) -> Maybe a -> b\ndef maybe(v):\n '''Either the default value v, if m is Nothing,\n or the application of f to x,\n where m is Just(x).\n '''\n return lambda f: lambda m: v if (\n None is m or m.get('Nothing')\n ) else f(m.get('Just'))\n\n\n# second :: (a -> b) -> ((c, a) -> (c, b))\ndef second(f):\n '''A simple function lifted to a function over a tuple,\n with f applied only to the second of two values.\n '''\n return lambda xy: (xy[0], f(xy[1]))\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second member of a pair.'''\n return tpl[1]\n\n\n# swap :: (a, b) -> (b, a)\ndef swap(tpl):\n '''The swapped components of a pair.'''\n return (tpl[1], tpl[0])\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "'''Determine if a string has all unique characters'''\n\nfrom functools import reduce\n\n\n# duplicatedCharIndices :: String -> Maybe (Char, [Int])\ndef duplicatedCharIndices(s):\n '''Just the first duplicated character, and\n the indices of its occurrence, or\n Nothing if there are no duplications.\n '''\n def go(dct, ic):\n i, c = ic\n return dict(\n dct,\n **{c: dct[c] + [i] if c in dct else [i]}\n )\n duplicates = [\n (k, v) for (k, v)\n in reduce(go, enumerate(s), {}).items()\n if 1 < len(v)\n ]\n return Just(\n min(duplicates, key=compose(head, snd))\n ) if duplicates else Nothing()\n\n\n# And another alternative here would be to fuse the 1 < len(v)\n# filtering, and the min() search for the earliest duplicate,\n# down to a single `earliestDuplication` fold:\n\n# duplicatedCharIndices_ :: String -> Maybe (Char, [Int])\ndef duplicatedCharIndices_(s):\n '''Just the first duplicated character, and\n the indices of its occurrence, or\n Nothing if there are no duplications.\n '''\n def positionRecord(dct, ic):\n i, c = ic\n return dict(\n dct,\n **{c: dct[c] + [i] if c in dct else [i]}\n )\n\n def earliestDuplication(sofar, charPosns):\n c, indices = charPosns\n return (\n maybe(Just((c, indices)))(\n lambda kxs: Just((c, indices)) if (\n # Earlier duplication ?\n indices[0] < kxs[1][0]\n ) else sofar\n )(sofar)\n ) if 1 < len(indices) else sofar\n\n return reduce(\n earliestDuplication,\n reduce(\n positionRecord,\n enumerate(s),\n {}\n ).items(),\n Nothing()\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test over various strings.'''\n\n def showSample(s):\n return repr(s) + ' (' + str(len(s)) + ')'\n\n def showDuplicate(cix):\n c, ix = cix\n return repr(c) + (\n ' (' + hex(ord(c)) + ') at ' + repr(ix)\n )\n\n print(\n fTable('First duplicated character, if any:')(\n showSample\n )(maybe('None')(showDuplicate))(duplicatedCharIndices_)([\n '', '.', 'abcABC', 'XYZ ZYX',\n '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'\n ])\n )\n\n\n# FORMATTING ----------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# GENERIC -------------------------------------------------\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.\n Wrapper containing the result of a computation.\n '''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.\n Empty wrapper returned where a computation is not possible.\n '''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# compose :: ((a -> a), ...) -> (a -> a)\ndef compose(*fs):\n '''Composition, from right to left,\n of a series of functions.\n '''\n return lambda x: reduce(\n lambda a, f: f(a),\n fs[::-1], x\n )\n\n\n# head :: [a] -> a\ndef head(xs):\n '''The first element of a non-empty list.'''\n return xs[0] if isinstance(xs, list) else next(xs)\n\n\n# maybe :: b -> (a -> b) -> Maybe a -> b\ndef maybe(v):\n '''Either the default value v, if m is Nothing,\n or the application of f to x,\n where m is Just(x).\n '''\n return lambda f: lambda m: v if (\n None is m or m.get('Nothing')\n ) else f(m.get('Just'))\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second member of a pair.'''\n return tpl[1]\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "import re\n\npattern = '(.)' + '.*?' + r'\\1'\n\ndef find_dup_char(subject):\n match = re.search(pattern, subject)\n if match:\n return match.groups(0)[0], match.start(0), match.end(0)\n\ndef report_dup_char(subject):\n dup = find_dup_char(subject)\n prefix = f'\"{subject}\" ({len(subject)})'\n if dup:\n ch, pos1, pos2 = dup\n print(f\"{prefix}: '{ch}' (0x{ord(ch):02x}) duplicates at {pos1}, {pos2-1}\")\n else:\n print(f\"{prefix}: no duplicate characters\")\n\nshow = report_dup_char\nshow('coccyx')\nshow('')\nshow('.')\nshow('abcABC')\nshow('XYZ ZYX')\nshow('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ')\n", "language": "Python" }, { "code": " [ over find swap found ] is has ( $ c --> b )\n\n [ dip [ 0 0 true ]\n dup size 2 < iff\n drop done\n dup size 1 - times\n [ behead 2dup has iff\n [ swap find\n dip not\n 2swap 2drop\n i^ tuck + 1+ rot\n 0 conclude ] done\n drop ]\n drop ] is uniquechars ( $ --> n n b )\n\n [ dup say 'String \"'\n echo$\n say '\" has length '\n dup size echo\n say \". \"\n dup uniquechars iff\n [ say \"There are no duplicated characters.\"\n drop 2drop ]\n else\n [ rot over peek\n dup say 'The character \"'\n emit\n say '\" (hex:'\n 16 base put\n echo\n base release\n say \") is at positions \"\n swap echo\n say \" and \"\n echo\n say \".\" ]\n cr ] is task ( $ --> )\n\n $ \"\" task\n $ \".\" task\n $ \"abcABC\" task\n $ \"XYZ ZYX\" task\n $ \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\" task\n", "language": "Quackery" }, { "code": "isAllUnique <- function(string)\n{\n strLength <- nchar(string)\n if(length(strLength) > 1)\n {\n #R has a distinction between the length of a string and that of a character vector. It is a common source\n #of problems when coming from another language. We will try to avoid the topic here.\n #For our purposes, let us only say that there is a good reason why we have made\n #isAllUnique(c(\"foo\", \"bar\") immediately throw an error.\n stop(\"This task is intended for character vectors with lengths of at most 1.\")\n }\n else if(length(strLength) == 0)\n {\n cat(\"Examining a character vector of length 0.\",\n \"It is therefore made entirely of unique characters.\\n\")\n TRUE\n }\n else if(strLength == 0)\n {\n cat(\"Examining a character vector of length 1, containing an empty string.\",\n \"It is therefore made entirely of unique characters.\\n\")\n TRUE\n }\n else if(strLength == 1)\n {\n cat(\"Examining the string\", paste0(sQuote(string), \",\"),\n \"which is of length\", paste0(strLength, \".\"),\n \"It is therefore made entirely of unique characters.\\n\")\n TRUE\n }\n else\n {\n cat(\"Examining the string\", paste0(sQuote(string), \",\"),\n \"which is of length\", paste0(strLength, \":\"), \"\\n\")\n #strsplit outputs a list. Its first element is the vector of characters that we desire.\n characters <- strsplit(string, \"\")[[1]]\n #Our use of match is using R's vector recycling rules. Element i is being checked\n #against every other.\n indexesOfDuplicates <- sapply(seq_len(strLength), function(i) match(TRUE, characters[i] == characters[-i], nomatch = -1)) + 1\n firstDuplicateElementIndex <- indexesOfDuplicates[indexesOfDuplicates != 0][1]\n if(is.na(firstDuplicateElementIndex))\n {\n cat(\"It has no duplicates. It is therefore made entirely of unique characters.\\n\")\n TRUE\n }\n else\n {\n cat(\"It has duplicates. \")\n firstDuplicatedCharacter <- characters[firstDuplicateElementIndex]\n cat(sQuote(firstDuplicatedCharacter), \"is the first duplicated character. It has hex value\",\n sprintf(\"0x%X\", as.integer(charToRaw(firstDuplicatedCharacter))),\n \"and is at index\", paste0(firstDuplicateElementIndex, \".\"),\n \"\\nThis is a duplicate of the character at index\",\n paste0(match(firstDuplicateElementIndex, indexesOfDuplicates), \".\"), \"\\n\")\n FALSE\n }\n }\n}\n\n#Tests:\ncat(\"Test: A string of length 0 (an empty string):\\n\")\ncat(\"Test 1 of 2: An empty character vector:\\n\")\nprint(isAllUnique(character(0)))\ncat(\"Test 2 of 2: A character vector containing the empty string:\\n\")\nprint(isAllUnique(\"\"))\ncat(\"Test: A string of length 1 which contains .:\\n\")\nprint(isAllUnique(\".\"))\ncat(\"Test: A string of length 6 which contains abcABC:\\n\")\nprint(isAllUnique(\"abcABC\"))\ncat(\"Test: A string of length 7 which contains XYZ ZYX:\\n\")\nprint(isAllUnique(\"XYZ ZYX\"))\ncat(\"Test: A string of length 36 doesn't contain the letter 'oh':\\n\")\nprint(isAllUnique(\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"))\n", "language": "R" }, { "code": "#lang racket\n\n(define (first-non-unique-element.index seq)\n (let/ec ret\n (for/fold ((es (hash))) ((e seq) (i (in-naturals)))\n (if (hash-has-key? es e) (ret (list e (hash-ref es e) i)) (hash-set es e i)))\n #f))\n\n(define (report-if-a-string-has-all-unique-characters str)\n (printf \"~s (length ~a): ~a~%\" str (string-length str)\n (match (first-non-unique-element.index str)\n [#f \"contains all unique characters\"]\n [(list e i i′) (format \"has character '~a' (0x~a) at index ~a (first seen at ~a)\"\n e (number->string (char->integer e) 16) i′ i)])))\n\n(module+ main\n (for-each report-if-a-string-has-all-unique-characters\n (list \"\" \".\" \"abcABC\" \"XYZ ZYX\"\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\")))\n", "language": "Racket" }, { "code": " -> $str {\n my $i = 0;\n print \"\\n{$str.raku} (length: {$str.chars}), has \";\n my %m = $str.comb.Bag;\n if any(%m.values) > 1 {\n say \"duplicated characters:\";\n say \"'{.key}' ({.key.uninames}; hex ordinal: {(.key.ords).fmt: \"0x%X\"})\" ~\n \" in positions: {.value.join: ', '}\" for %m.grep( *.value > 1 ).sort( *.value[0] );\n } else {\n say \"no duplicated characters.\"\n }\n} for\n '',\n '.',\n 'abcABC',\n 'XYZ ZYX',\n '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ',\n '01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X',\n '🦋🙂👨‍👩‍👧‍👦🙄ΔΔ̂ 🦋Δ👍👨‍👩‍👧‍👦'\n", "language": "Raku" }, { "code": "/*REXX pgm determines if a string is comprised of all unique characters (no duplicates).*/\n@.= /*assign a default for the @. array. */\nparse arg @.1 /*obtain optional argument from the CL.*/\nif @.1='' then do; @.1= /*Not specified? Then assume defaults.*/\n @.2= .\n @.3= 'abcABC'\n @.4= 'XYZ ZYX'\n @.5= '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'\n end\n\n do j=1; if j\\==1 & @.j=='' then leave /*String is null & not j=1? We're done*/\n say copies('─', 79) /*display a separator line (a fence). */\n say 'Testing for the string (length' length(@.j)\"): \" @.j\n say\n dup= isUnique(@.j)\n say 'The characters in the string' word(\"are aren't\", 1 + (dup>0) ) 'all unique.'\n if dup==0 then iterate\n ?= substr(@.j, dup, 1)\n say 'The character ' ? \" ('\"c2x(?)\"'x) at position \" dup ,\n ' is repeated at position ' pos(?, @.j, dup+1)\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nisUnique: procedure; parse arg x /*obtain the character string.*/\n do k=1 to length(x) - 1 /*examine all but the last. */\n p= pos( substr(x, k, 1), x, k + 1) /*see if the Kth char is a dup*/\n if p\\==0 then return k /*Find a dup? Return location.*/\n end /*k*/\n return 0 /*indicate all chars unique. */\n", "language": "REXX" }, { "code": "inputStr = [\"\",\".\",\"abcABC\",\"XYZ ZYX\",\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"]\n\nfor Str in inputStr\n for x = 1 to len(Str)\n for y = x + 1 to len(Str)\n if Str[x] = Str[y]\n char = Str[x]\n ? \"Input = \" + \"'\" + Str + \"'\" + \", length = \" + len(Str)\n ? \" First duplicate at positions \" + x + \" and \" + y + \", character = \" + \"'\" + char + \"'\"\n loop 3\n ok\n next\n next\n ? \"Input = \" + \"'\" + Str + \"'\" + \", length = \" + len(Str)\n ? \" All characters are unique.\"\nnext\n", "language": "Ring" }, { "code": "strings = [\"\",\n \".\",\n \"abcABC\",\n \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\",\n \"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X\",\n \"hétérogénéité\",\n \"🎆🎃🎇🎈\",\n \"😍😀🙌💃😍🙌\",\n \"🐠🐟🐡🦈🐬🐳🐋🐡\",]\n\nstrings.each do |str|\n seen = {}\n print \"#{str.inspect} (size #{str.size}) \"\n res = \"has no duplicates.\" #may change\n str.chars.each_with_index do |c,i|\n if seen[c].nil?\n seen[c] = i\n else\n res = \"has duplicate char #{c} (#{'%#x' % c.ord}) on #{seen[c]} and #{i}.\"\n break\n end\n end\n puts res\nend\n", "language": "Ruby" }, { "code": "fn unique(s: &str) -> Option<(usize, usize, char)> {\n s.chars().enumerate().find_map(|(i, c)| {\n s.chars()\n .enumerate()\n .skip(i + 1)\n .find(|(_, other)| c == *other)\n .map(|(j, _)| (i, j, c))\n })\n}\n\nfn main() {\n let strings = [\n \"\",\n \".\",\n \"abcABC\",\n \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\",\n \"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X\",\n \"hétérogénéité\",\n \"🎆🎃🎇🎈\",\n \"😍😀🙌💃😍🙌\",\n \"🐠🐟🐡🦈🐬🐳🐋🐡\",\n ];\n\n for string in &strings {\n print!(\"\\\"{}\\\" (length {})\", string, string.chars().count());\n match unique(string) {\n None => println!(\" is unique\"),\n Some((i, j, c)) => println!(\n \" is not unique\\n\\tfirst duplicate: \\\"{}\\\" (U+{:0>4X}) at indices {} and {}\",\n c, c as usize, i, j\n ),\n }\n }\n}\n", "language": "Rust" }, { "code": "func index_duplicates(str) {\n gather {\n for k,v in (str.chars.kv) {\n var i = str.index(v, k+1)\n take([k, i]) if (i != -1)\n }\n }\n}\n\nvar strings = [\n \"\", \".\", \"abcABC\", \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\",\n \"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X\",\n \"hétérogénéité\", \"🎆🎃🎇🎈\", \"😍😀🙌💃😍🙌\",\n \"🐠🐟🐡🦈🐬🐳🐋🐡\"\n]\n\nstrings.each {|str|\n print \"\\n'#{str}' (size: #{str.len}) \"\n var dups = index_duplicates(str)\n say \"has duplicated characters:\" if dups\n for i,j in (dups) {\n say \"#{str[i]} (#{'%#x' % str[i].ord}) in positions: #{i}, #{j}\"\n }\n say \"has no duplicates.\" if !dups\n}\n", "language": "Sidef" }, { "code": "package require Tcl 8.6 ; # For binary encode\n\narray set yesno {1 Yes 2 No}\n\nset test {\n {}\n {.}\n {abcABC}\n {XYZ ZYX}\n {1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ}\n {hétérogénéité}\n}\n\n# Loop through test strings\nforeach str $test {\n set chars [dict create] ; # init dictionary\n set num_chars 1 ; # In case of empty string\n\n # Loop through characters in string\n for {set i 0} {$i < [string length $str]} {incr i} {\n set c [string index $str $i] ; # get char at index\n dict lappend chars $c $i ; # add index to a running list for key=char\n set indexes [dict get $chars $c] ; # get the whole running list\n set num_chars [llength $indexes] ; # count the # of indexes\n if {$num_chars > 1} {\n break ; # Found a duplicate, break out of the loop\n }\n }\n\n # Handle Output\n puts [format \"Tested: %38s (len: %2d). All unique? %3s. \" \\\n \"'$str'\" [string length $str] $yesno($num_chars)]\n if {$num_chars > 1} {\n puts [format \" --> Character '%s' (hex: 0x%s) reappears at indexes: %s.\" \\\n $c [binary encode hex $c] $indexes]\n }\n}\n", "language": "Tcl" }, { "code": "fn analyze(s string) {\n chars := s.runes()\n le := chars.len\n println(\"Analyzing $s which has a length of $le:\")\n if le > 1 {\n for i := 0; i < le-1; i++ {\n for j := i + 1; j < le; j++ {\n if chars[j] == chars[i] {\n println(\" Not all characters in the string are unique.\")\n println(\" '${chars[i]}'' (0x${chars[i]:x}) is duplicated at positions ${i+1} and ${j+1}.\\n\")\n return\n }\n }\n }\n }\n println(\" All characters in the string are unique.\\n\")\n}\n\nfn main() {\n strings := [\n \"\",\n \".\",\n \"abcABC\",\n \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\",\n \"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X\",\n \"hétérogénéité\",\n \"🎆🎃🎇🎈\",\n \"😍😀🙌💃😍🙌\",\n \"🐠🐟🐡🦈🐬🐳🐋🐡\",\n ]\n for s in strings {\n analyze(s)\n }\n}\n", "language": "V-(Vlang)" }, { "code": "Module Module1\n\n Sub Main()\n Dim input() = {\"\", \".\", \"abcABC\", \"XYZ ZYX\", \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"}\n For Each s In input\n Console.WriteLine($\"'{s}' (Length {s.Length}) \" + String.Join(\", \", s.Select(Function(c, i) (c, i)).GroupBy(Function(t) t.c).Where(Function(g) g.Count() > 1).Select(Function(g) $\"'{g.Key}' (0X{AscW(g.Key):X})[{String.Join(\", \", g.Select(Function(t) t.i))}]\").DefaultIfEmpty(\"All characters are unique.\")))\n Next\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./fmt\" for Conv, Fmt\n\nvar analyze = Fn.new { |s|\n var chars = s.codePoints.toList\n var le = chars.count\n System.print(\"Analyzing %(Fmt.q(s)) which has a length of %(le):\")\n if (le > 1) {\n for (i in 0...le-1) {\n for (j in i+1...le) {\n if (chars[j] == chars[i]) {\n System.print(\" Not all characters in the string are unique.\")\n var c = String.fromCodePoint(chars[i])\n var hex = \"0x\" + Conv.hex(chars[i])\n System.print(\" '%(c)' (%(hex)) is duplicated at positions %(i+1) and %(j+1).\\n\")\n return\n }\n }\n }\n }\n System.print(\" All characters in the string are unique.\\n\")\n}\n\nvar strings = [\n \"\",\n \".\",\n \"abcABC\",\n \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\",\n \"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X\",\n \"hétérogénéité\",\n \"🎆🎃🎇🎈\",\n \"😍😀🙌💃😍🙌\",\n \"🐠🐟🐡🦈🐬🐳🐋🐡\"\n]\nfor (s in strings) analyze.call(s)\n", "language": "Wren" }, { "code": "include xpllib; \\contains StrLen function\n\nproc StrUnique(S); \\Show if string has unique chars\nchar S;\nint L, I, J, K;\n[L:= StrLen(S);\nIntOut(0, L); Text(0, \": ^\"\"); Text(0, S); ChOut(0, ^\"); CrLf(0);\nfor I:= 0 to L-1 do\n for J:= I+1 to L-1 do\n [if S(I) = S(J) then\n [ChOut(0, \\tab\\ 9);\n for K:= 0 to I do ChOut(0, ^ );\n ChOut(0, ^^);\n for K:= 0 to J-I-2 do ChOut(0, ^ );\n ChOut(0, ^^);\n Text(0, \" Duplicate character: \");\n ChOut(0, S(I));\n Text(0, \", hex \");\n SetHexDigits(2);\n HexOut(0, S(I));\n CrLf(0);\n return;\n ];\n ];\nText(0, \" Unique, no duplicates\"); CrLf(0);\n];\n\n[Text(0, \"Length\"); CrLf(0);\nStrUnique(\"\");\nStrUnique(\".\");\nStrUnique(\"abcABC\");\nStrUnique(\"XYZ ZYX\");\nStrUnique(\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\");\nStrUnique(\"thequickbrownfoxjumps\");\n]\n", "language": "XPL0" }, { "code": "sub caracteresunicos (cad$)\n local lngt, i, j\n\n\tlngt = len(cad$)\n print \"cadena = \\\"\", cad$, \"\\\", longitud = \", lngt\n for i = 1 to lngt\n for j = i + 1 to lngt\n if mid$(cad$,i,1) = mid$(cad$,j,1) then\n print \" Primer duplicado en las posiciones \", i, \" y \", j, \", caracter = \\'\", mid$(cad$,i,1), \"\\', valor hex = \", hex$(asc(mid$(cad$,i,1)))\n print\n return\n end if\n next j\n next i\n print \" Todos los caracteres son unicos.\\n\"\nend sub\n\ncaracteresunicos (\"\")\ncaracteresunicos (\".\")\ncaracteresunicos (\"abcABC\")\ncaracteresunicos (\"XYZ ZYX\")\ncaracteresunicos (\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\")\n", "language": "Yabasic" }, { "code": "fcn stringUniqueness(str){ // Does not handle Unicode\n sz,unique,uz,counts := str.len(), str.unique(), unique.len(), str.counts();\n println(\"Length %d: \\\"%s\\\"\".fmt(sz,str));\n if(sz==uz or uz==1) println(\"\\tAll characters are unique\");\n else // counts is (char,count, char,count, ...)\n println(\"\\tDuplicate: \",\n counts.pump(List,Void.Read,fcn(str,c,n){\n if(n>1){\n\t is,z:=List(),-1; do(n){ is.append(z=str.find(c,z+1)) }\n\t \"'%s' (0x%x)[%s]\".fmt(c,c.toAsc(),is.concat(\",\"))\n\t }\n\t else Void.Skip\n\t }.fp(str)).concat(\", \"));\n}\n", "language": "Zkl" }, { "code": "testStrings:=T(\"\", \".\", \"abcABC\", \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\",\n \"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X\");\nforeach s in (testStrings){ stringUniqueness(s) }\n", "language": "Zkl" } ]
Determine-if-a-string-has-all-unique-characters
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible\n", "language": "00-META" }, { "code": "Determine if a character string is &nbsp; ''collapsible''.\n\nAnd if so, &nbsp; collapse the string &nbsp; (by removing &nbsp; ''immediately repeated'' &nbsp; characters).\n\n\n\nIf a character string has &nbsp; ''immediately repeated'' &nbsp; character(s), &nbsp; the repeated characters are to be\ndeleted (removed), &nbsp; but not the primary (1<sup>st</sup>) character(s).\n\n\nAn &nbsp; ''immediately repeated'' &nbsp; character is any character that is &nbsp; <u>immediately</u> &nbsp; followed by an\nidentical character (or characters). &nbsp; Another word choice could've been &nbsp; ''duplicated character'', &nbsp; but that\nmight have ruled out &nbsp; (to some readers) &nbsp; triplicated characters &nbsp; ··· &nbsp; or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced &nbsp; (as of around November 2019) &nbsp; '''PL/I''' &nbsp; BIF: &nbsp; '''collapse'''.}\n\n\n;Examples:\nIn the following character string:\n\n\n <big><big> The bet<u>t</u>er the 4-whe<u>e</u>l drive, the further you'l<u>l</u> be from help when ya get stuck! </big></big>\n\n\nOnly the 2<sup>nd</sup> &nbsp; '''t''', &nbsp; '''e''', and &nbsp; '''l''' &nbsp; are repeated characters, &nbsp; indicated\nby underscores (above), &nbsp; even though they (those characters) appear elsewhere in the character string.\n\n\n\nSo, after ''collapsing'' the string, the result would be:\n\n <big><big> The beter the 4-whel drive, the further you'l be from help when ya get stuck! </big></big>\n\n\n\n\nAnother example:\nIn the following character string:\n\n <big><big> headmistres<u>ss</u>hip </big></big>\n\n\nThe \"collapsed\" string would be:\n\n <big><big> headmistreship </big></big>\n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine··· &nbsp; to\nlocate &nbsp; ''repeated'' &nbsp; characters and &nbsp; ''collapse'' &nbsp; (delete) &nbsp; them from the character\nstring. &nbsp; The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* &nbsp; the &nbsp; original string and its length\n:* &nbsp; the resultant string and its length\n:* &nbsp; the above strings should be \"bracketed\" with &nbsp; '''<<<''' &nbsp; and &nbsp; '''>>>''' &nbsp; (to delineate blanks)\n;* &nbsp; «««Guillemets may be used instead for \"bracketing\" for the more artistic programmers, &nbsp; shown used here»»»\n<!-- Guillemots shouldn't be used as they stink. !-->\n\n\n\nUse (at least) the following five strings, &nbsp; all strings are length seventy-two (characters, including blanks), &nbsp; except\nthe 1<sup>st</sup> string:\n\n string\n number\n ╔╗\n 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)\n 2 ║\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ║\n 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║\n 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║\n 5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks\n ╚════════════════════════════════════════════════════════════════════════╝\n\n{{Template:Strings}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F collapse(s)\n V cs = ‘’\n V last = Char(\"\\0\")\n L(c) s\n I c != last\n cs ‘’= c\n last = c\n R cs\n\nV strings = [\n ‘’,\n ‘\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ’,\n ‘..1111111111111111111111111111111111111111111111111111111111111117777888’,\n ‘I never give 'em hell, I just tell the truth, and they think it's hell. ’,\n ‘ --- Harry S Truman ’,\n ‘The better the 4-wheel drive, the further you'll be from help when ya get stuck!’,\n ‘headmistressship’,\n ‘aardvark’\n]\n\nL(s) strings\n V c = collapse(s)\n print(‘original : length = ’s.len‘, string = <<<’s‘>>>’)\n print(‘collapsed : length = ’c.len‘, string = <<<’c‘>>>’)\n print()\n", "language": "11l" }, { "code": "bdos:\tequ\t5\nputs:\tequ\t9\n\torg\t100h\n\tjmp\tmain\n\t;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\t;;;\tCollapse the $-terminated string at [HL]\ncolaps:\tmov\tb,m\t; B = last character seen\n\tinx\th\t; First character never collapses\n\tmov\td,h\t; DE = output pointer\n\tmov\te,l\n\tmov\ta,b\t; Empty string?\n\tcpi\t'$'\n\trz\t\t; Then do nothing\ncloop:\tmov\ta,m\t; Get character\n\tinx\th\t; Advance pointer\n\tcmp\tb\t; Same as last one?\n\tjz\tcloop\t; Then keep scanning\n\tmov\tb,a\t; Otherwise, it is a new one\n\tstax\td\t; Store it,\n\tinx\td\t; and increment output pointer.\n\tcpi\t'$'\t; Reached the end?\n\tjnz\tcloop\t; If not, next character\n\tret\n\t;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\t;;;\tCode to print the output in the required format\nmain:\tlxi\th,strs\t; List of string pointers\nloop:\tmov\te,m\t; DE = string pointer\n\tinx\th\n\tmov\td,m\n\tinx\th\n\tmov\ta,e\t; If zero, end\n\tora\td\n\trz\n\tpush\th\t; Keep the list pointer\n\tpush\td\t; Keep the string pointer\n\tcall\tbrstr\t; Print original string in brackets\n\tpop\th\t; Retrieve string pointer\n\tpush\th\n\tcall\tcolaps\t; Collapse the string\n\tpop\td\t; Retrieve string pointer\n\tcall\tbrstr\t; Print the collapsed string in brackets\n\tpop\th\t; Retrieve the list pointer\n\tjmp\tloop\t; Next string\n\t;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\t;;;\tPrint string at DE in brackets with length\nbrstr:\tpush\td\t; Store string pointer\n\tmvi\tc,puts\t; Print opening brackets\n\tlxi\td,open\n\tcall\tbdos\n\tpop\td\t; Print original string\n\tpush\td\n\tmvi\tc,puts\n\tcall\tbdos\n\tmvi\tc,puts\t; Print closing brackets\n\tlxi\td,close\n\tcall\tbdos\n\tpop\th\n\tcall\tstrlen\t; Find string length\n\tmov\ta,b\n\tjmp\tprnum\t; Print string length\n\t;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\t;;;\tFigure out the length of a string (max 255)\nstrlen:\tmvi\tb,0\t; Counter\n\tmvi\ta,'$'\t; Terminator\nsloop:\tcmp\tm\t; Reached the end yet?\n\trz\t\t; If so, stop\n\tinr\tb\t; If not, increment counter,\n\tinx\th\t; and pointer,\n\tjmp\tsloop\t; and check next byte.\n\t;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\t;;;\tPrint number in A as decimal\nprnum:\tlxi\td,num\t; End of number string\nprdgt:\tmvi\tb,-1\t; Quotient\nploop:\tinr\tb\t; Increment quotient\n\tsui\t10\t; Subtract 10\n\tjnc\tploop\t; Subtract until negative\n\tadi\t'0'+10\t; Make ASCII digit\n\tdcx\td\t; Store in number string\n\tstax\td\n\tmov\ta,b\t; If more digits,\n\tana\ta\n\tjnz\tprdgt\t; find next digit\n\tmvi\tc,puts\t; When done, print string\n\tjmp\tbdos\n\t;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\t;;;\tFormatting strings\nopen:\tdb\t'<<<$'\nclose:\tdb\t'>>> $'\n\tdb\t'***'\nnum:\tdb\t13,10,'$'\n\t;;;\tInput strings\nstrs:\tdw\tstr1,str2,str3,str4,str5,0\nstr1:\tdb\t'$'\t; Empty string\nstr2:\tdb\t'\"If I were two-faced, would I be wearing '\n\tdb\t'this one?\" --- Abraham Lincoln $'\nstr3:\tdb\t'..111111111111111111111111111111111111111'\n\tdb\t'1111111111111111111111117777888$'\nstr4:\tdb\t'I never give ',39,'em hell, I just tell the truth, '\n\tdb\t'and they think it',39,'s hell. $'\nstr5:\tdb\t' '\n\tdb\t' --- Harry S Truman $'\n", "language": "8080-Assembly" }, { "code": "PROC Collapse(CHAR ARRAY in,out)\n BYTE i,j\n CHAR c\n\n j=1 c=0\n FOR i=1 TO in(0)\n DO\n IF in(i)#c THEN\n c=in(i)\n out(j)=c\n j==+1\n FI\n OD\n out(0)=j-1\nRETURN\n\nPROC Test(CHAR ARRAY s)\n CHAR ARRAY c(100)\n BYTE CH=$02FC ;Internal hardware value for last key pressed\n\n Collapse(s,c)\n PrintF(\"<<<%S>>> (len=%B)%E\",s,s(0))\n PrintF(\"<<<%S>>> (len=%B)%E\",c,c(0))\n PutE()\n PrintE(\"Press any key to continue\")\n PutE()\n\n DO UNTIL CH#$FF OD\n CH=$FF\nRETURN\n\nPROC Main()\n Test(\"\")\n Test(\"\"\"If I were two-faced, would I be wearing this one?\"\" --- Abraham Lincoln \")\n Test(\"..1111111111111111111111111111111111111111111111111111111111111117777888\")\n Test(\"I never give 'em hell, I just tell the truth, and they think it's hell. \")\n Test(\" --- Harry S Truman \")\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\nprocedure Test_Collapsible is\n procedure Collapse (S : in String) is\n Res : String (1 .. S'Length);\n Len : Natural := 0;\n begin\n Put_Line (\"Input = <<<\" & S & \">>>, length =\" & S'Length'Image);\n for I in S'Range loop\n if Len = 0 or else S(I) /= Res(Len) then\n Len := Len + 1;\n Res(Len) := S(I);\n end if;\n end loop;\n Put_Line (\"Output = <<<\" & Res (1 .. Len) & \">>>, length =\" & Len'Image);\n end Collapse;\nbegin\n Collapse (\"\");\n Collapse (\"\"\"If I were two-faced, would I be wearing this one?\"\" --- Abraham Lincoln \");\n Collapse (\"..1111111111111111111111111111111111111111111111111111111111111117777888\");\n Collapse (\"I never give 'em hell, I just tell the truth, and they think it's hell. \");\n Collapse (\" --- Harry S Truman \");\nend Test_Collapsible;\n", "language": "Ada" }, { "code": "BEGIN\n # returns a collapsed version of s #\n # i.e. s with adjacent duplicate characters removed #\n PROC collapse = ( STRING s )STRING:\n IF s = \"\"\n THEN \"\" # empty string #\n ELSE # non-empty string #\n [ LWB s : UPB s ]CHAR result;\n INT r pos := LWB result;\n result[ r pos ] := s[ LWB s ];\n FOR s pos FROM LWB s + 1 TO UPB s DO\n IF result[ r pos ] /= s[ s pos ] THEN\n r pos +:= 1;\n result[ r pos ] := s[ s pos ]\n FI\n OD;\n result[ LWB result : r pos ]\n FI # callapse # ;\n # task test cases #\n []STRING tests = ( \"\"\n , \"\"\"If I were two-faced, would I be wearing this one?\"\" --- Abraham Lincoln \"\n , \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n , \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n , \" --- Harry S Truman \"\n );\n FOR t pos FROM LWB tests TO UPB tests DO\n STRING s = tests[ t pos ];\n STRING c = collapse( s );\n print( ( \" <<<\", s, \">>> (length \", whole( ( UPB s + 1 ) - LWB s, 0 ), \")\", newline ) );\n print( ( \"result <<<\", c, \">>> (length \", whole( ( UPB c + 1 ) - LWB c, 0 ), \")\", newline ) )\n OD\nEND\n", "language": "ALGOL-68" }, { "code": "task←{\n ⍝ Collapse a string\n collapse←{(1,¯1↓⍵≠1⌽⍵)/⍵}\n\n ⍝ Given a function ⍺⍺, display a string in brackets,\n ⍝ along with its length, and do the same for the result\n ⍝ of applying ⍺⍺ to the string.\n display←{\n bracket←{(⍕⍴⍵),' «««',⍵,'»»»'}\n ↑(⊂bracket ⍵),(⊂bracket ⍺⍺ ⍵)\n }\n\n ⍝ Strings from the task\n s1←''\n s2←'\"If I were two-faced, would I be wearing this one?\"'\n s2,←' --- Abraham Lincoln '\n s3←'..1111111111111111111111111111111111111111111111111'\n s3,←'111111111111117777888'\n s4←'I never give ''em hell, I just tell the truth, '\n s4,←'and they think it''s hell. '\n s5←' '\n s5,←' --- Harry S Truman '\n strs←s1 s2 s3 s4 s5\n\n ⍝ Collapse each string and display it as specified\n ↑collapse display¨ strs\n}\n", "language": "APL" }, { "code": "lines: [\n {::}\n {:\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln :}\n {:..1111111111111111111111111111111111111111111111111111111111111117777888:}\n {:I never give 'em hell, I just tell the truth, and they think it's hell. :}\n {: --- Harry S Truman :}\n]\n\nloop lines 'line ->\n print squeeze line\n", "language": "Arturo" }, { "code": "collapsible_string(str){\n\tfor i, ch in StrSplit(str){\n\t\tif (ch <> prev)\n\t\t\tres .= ch\n\t\tprev := ch\n\t}\n\treturn \"original string:`t\" StrLen(str) \" characters`t«««\" str \"»»»`nresultant string:`t\" StrLen(res) \" characters`t«««\" res \"»»»\"\n}\n", "language": "AutoHotkey" }, { "code": "data := [\"\"\n\t, \"\"\"If I were two-faced, would I be wearing this one?\"\" --- Abraham Lincoln \"\n\t, \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n\t, \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n\t, \" --- Harry S Truman \"]\nfor i, v in data\n\tMsgBox % := collapsible_string(v)\nreturn\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f DETERMINE_IF_A_STRING_IS_COLLAPSIBLE.AWK\nBEGIN {\n for (i=1; i<=9; i++) {\n for (j=1; j<=i; j++) {\n arr[0] = arr[0] i\n }\n }\n arr[++n] = \"\"\n arr[++n] = \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"\n arr[++n] = \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n arr[++n] = \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n arr[++n] = \" --- Harry S Truman \"\n arr[++n] = \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\"\n arr[++n] = \"headmistressship\"\n for (i=0; i<=n; i++) {\n main(arr[i])\n }\n exit(0)\n}\nfunction main(str, c,i,new_str,prev_c) {\n for (i=1; i<=length(str); i++) {\n c = substr(str,i,1)\n if (prev_c != c) {\n prev_c = c\n new_str = new_str c\n }\n }\n printf(\"old: %2d <<<%s>>>\\n\",length(str),str)\n printf(\"new: %2d <<<%s>>>\\n\\n\",length(new_str),new_str)\n}\n", "language": "AWK" }, { "code": "DATA \"\"\nDATA \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"\nDATA \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\nDATA \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\nDATA \" --- Harry S Truman \"\nDATA \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\"\nDATA \"headmistressship\"\n\nDOTIMES 7\n READ x$\n found = 0\n PRINT \"<<<\", x$, \">>> - length: \", LEN(x$)\n PRINT \"<<<\";\n FOR y = 1 TO LEN(x$)\n IF MID$(x$, y, 1) <> MID$(x$, y+1, 1) THEN\n PRINT MID$(x$, y, 1);\n INCR found\n ENDIF\n NEXT\n PRINT \">>> - length: \", found\nDONE\n", "language": "BaCon" }, { "code": "10 READ N%\n20 FOR A% = 1 TO N%\n30 READ I$: GOSUB 100\n40 PRINT LEN(I$); \"<<<\"; I$; \">>>\"\n50 PRINT LEN(O$); \"<<<\"; O$; \">>>\"\n55 PRINT\n60 NEXT\n70 END\n100 REM Collapse I$ into O$\n105 IF I$=\"\" THEN O$=I$: RETURN\n110 O$=SPACE$(LEN(I$))\n120 P$=LEFT$(I$,1)\n130 MID$(O$,1,1)=P$\n140 O%=2\n150 FOR I%=2 TO LEN(I$)\n160 C$=MID$(I$,I%,1)\n170 IF P$<>C$ THEN MID$(O$,O%,1)=C$: O%=O%+1: P$=C$\n180 NEXT\n190 O$=LEFT$(O$,O%-1)\n200 RETURN\n400 DATA 5: REM There are 5 strings\n410 DATA \"\"\n420 DATA \"'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln \"\n430 DATA \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n440 DATA \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n450 DATA \" --- Harry S Truman \"\n", "language": "BASIC" }, { "code": "get \"libhdr\"\n\n// Collapse a string\nlet collapse(in, out) = valof\n$( let o = 0\n for i = 1 to in%0\n unless i>1 & in%i = in%(i-1)\n $( o := o + 1\n out%o := in%i\n $)\n out%0 := o\n resultis out\n$)\n\n// Print string with brackets and length\nlet brackets(s) be\n writef(\"%N: <<<%S>>>*N\", s%0, s)\n\n// Print original and collapsed version\nlet show(s) be\n$( let v = vec 1+255/BYTESPERWORD\n brackets(s)\n brackets(collapse(s, v))\n wrch('*N')\n$)\n\nlet start() be\n$( show(\"\")\n show(\"*\"If I were two-faced, would I be wearing this one?*\" --- Abraham Lincoln \")\n show(\"..1111111111111111111111111111111111111111111111111111111111111111111788\")\n show(\"I never give 'em hell, I just tell the truth, and they think it's hell. \")\n show(\" --- Harry S Truman \")\n$)\n", "language": "BCPL" }, { "code": "Collapse←(≠↑1∾1↓≠⟜»)⊸/\n\n>{\n c←Collapse 𝕩\n ⟨⟨≠𝕩 ⋄ \"<<<\"∾𝕩∾\">>>\"⟩≍⟨≠c ⋄ \"<<<\"∾c∾\">>>\"⟩⟩\n}¨⟨\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\"\n \"headmistressship\"\n \"\"\n \"\"\"If I were two-faced, would I be wearing this one?\"\" --- Abraham Lincoln \"\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n \" --- Harry S Truman \"\n⟩\n", "language": "BQN" }, { "code": "┌─\n╵ ┌─\n ╵ 80 \"<<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>>\"\n 77 \"<<<The beter the 4-whel drive, the further you'l be from help when ya get stuck!>>>\"\n ┘\n ┌─\n ╵ 16 \"<<<headmistressship>>>\"\n 14 \"<<<headmistreship>>>\"\n ┘\n ┌─\n ╵ 0 \"<<<>>>\"\n 0 \"<<<>>>\"\n ┘\n ┌─\n ╵ 72 \"<<<\"\"If I were two-faced, would I be wearing this one?\"\" --- Abraham Lincoln >>>\"\n 70 \"<<<\"\"If I were two-faced, would I be wearing this one?\"\" - Abraham Lincoln >>>\"\n ┘\n ┌─\n ╵ 72 \"<<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>\"\n 4 \"<<<.178>>>\"\n ┘\n ┌─\n ╵ 72 \"<<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>\"\n 69 \"<<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>\"\n ┘\n ┌─\n ╵ 72 \"<<< --- Harry S Truman >>>\"\n 17 \"<<< - Hary S Truman >>>\"\n ┘\n ┘\n", "language": "BQN" }, { "code": " ( colapse\n = previous\n . str\n $ ( vap\n $ ( (\n =\n . !arg:!previous&\n | !arg:?previous\n )\n . !arg\n )\n )\n )\n& ( testcolapse\n = len\n . (len=.@(!arg:? [?arg)&!arg)\n & out$(str$(««« !arg \"»»» \" len$!arg))\n & colapse$!arg:?arg\n & out$(str$(««« !arg \"»»» \" len$!arg))\n )\n& testcolapse$\n& testcolapse\n $ \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"\n& testcolapse\n $ \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n& testcolapse\n $ \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n& testcolapse\n $ \" --- Harry S Truman \"\n", "language": "Bracmat" }, { "code": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\n#define COLLAPSE 0\n#define SQUEEZE 1\n\ntypedef struct charList{\n char c;\n struct charList *next;\n} charList;\n\n/*\nImplementing strcmpi, the case insensitive string comparator, as it is not part of the C Standard Library.\n\nComment this out if testing on a compiler where it is already defined.\n*/\n\nint strcmpi(char* str1,char* str2){\n int len1 = strlen(str1), len2 = strlen(str2), i;\n\n if(len1!=len2){\n return 1;\n }\n\n else{\n for(i=0;i<len1;i++){\n if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))\n return 1;\n else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))\n return 1;\n else if(str1[i]!=str2[i])\n return 1;\n }\n }\n\n return 0;\n}\n\ncharList *strToCharList(char* str){\n int len = strlen(str),i;\n\n charList *list, *iterator, *nextChar;\n\n list = (charList*)malloc(sizeof(charList));\n list->c = str[0];\n list->next = NULL;\n\n iterator = list;\n\n for(i=1;i<len;i++){\n nextChar = (charList*)malloc(sizeof(charList));\n nextChar->c = str[i];\n nextChar->next = NULL;\n\n iterator->next = nextChar;\n iterator = nextChar;\n }\n\n return list;\n}\n\nchar* charListToString(charList* list){\n charList* iterator = list;\n int count = 0,i;\n char* str;\n\n while(iterator!=NULL){\n count++;\n iterator = iterator->next;\n }\n\n str = (char*)malloc((count+1)*sizeof(char));\n iterator = list;\n\n for(i=0;i<count;i++){\n str[i] = iterator->c;\n iterator = iterator->next;\n }\n\n free(list);\n str[i] = '\\0';\n\n return str;\n}\n\nchar* processString(char str[100],int operation, char squeezeChar){\n charList *strList = strToCharList(str),*iterator = strList, *scout;\n\n if(operation==SQUEEZE){\n while(iterator!=NULL){\n if(iterator->c==squeezeChar){\n scout = iterator->next;\n\n while(scout!=NULL && scout->c==squeezeChar){\n iterator->next = scout->next;\n scout->next = NULL;\n free(scout);\n scout = iterator->next;\n }\n }\n iterator = iterator->next;\n }\n }\n\n else{\n while(iterator!=NULL && iterator->next!=NULL){\n if(iterator->c == (iterator->next)->c){\n scout = iterator->next;\n squeezeChar = iterator->c;\n\n while(scout!=NULL && scout->c==squeezeChar){\n iterator->next = scout->next;\n scout->next = NULL;\n free(scout);\n scout = iterator->next;\n }\n }\n iterator = iterator->next;\n }\n }\n\n return charListToString(strList);\n}\n\nvoid printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){\n if(operation==SQUEEZE){\n printf(\"Specified Operation : SQUEEZE\\nTarget Character : %c\",squeezeChar);\n }\n\n else\n printf(\"Specified Operation : COLLAPSE\");\n\n printf(\"\\nOriginal %c%c%c%s%c%c%c\\nLength : %d\",174,174,174,originalString,175,175,175,(int)strlen(originalString));\n printf(\"\\nFinal %c%c%c%s%c%c%c\\nLength : %d\\n\",174,174,174,finalString,175,175,175,(int)strlen(finalString));\n}\n\nint main(int argc, char** argv){\n int operation;\n char squeezeChar;\n\n if(argc<3||argc>4){\n printf(\"Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\\n\",argv[0]);\n return 0;\n }\n\n if(strcmpi(argv[1],\"SQUEEZE\")==0 && argc!=4){\n scanf(\"Please enter characted to be squeezed : %c\",&squeezeChar);\n operation = SQUEEZE;\n }\n\n else if(argc==4){\n operation = SQUEEZE;\n squeezeChar = argv[3][0];\n }\n\n else if(strcmpi(argv[1],\"COLLAPSE\")==0){\n operation = COLLAPSE;\n }\n\n if(strlen(argv[2])<2){\n printResults(argv[2],argv[2],operation,squeezeChar);\n }\n\n else{\n printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);\n }\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <string>\n#include <iostream>\n#include <algorithm>\n\ntemplate<typename char_type>\nstd::basic_string<char_type> collapse(std::basic_string<char_type> str) {\n auto i = std::unique(str.begin(), str.end());\n str.erase(i, str.end());\n return str;\n}\n\nvoid test(const std::string& str) {\n std::cout << \"original string: <<<\" << str << \">>>, length = \" << str.length() << '\\n';\n std::string collapsed(collapse(str));\n std::cout << \"result string: <<<\" << collapsed << \">>>, length = \" << collapsed.length() << '\\n';\n std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n test(\"\");\n test(\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \");\n test(\"..1111111111111111111111111111111111111111111111111111111111111117777888\");\n test(\"I never give 'em hell, I just tell the truth, and they think it's hell. \");\n test(\" --- Harry S Truman \");\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n static void Main()\n {\n string[] input = {\n \"\",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \"\n };\n foreach (string s in input) {\n Console.WriteLine($\"old: {s.Length} «««{s}»»»\");\n string c = Collapse(s);\n Console.WriteLine($\"new: {c.Length} «««{c}»»»\");\n }\n }\n\n static string Collapse(string s) => string.IsNullOrEmpty(s) ? \"\" :\n s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != s[i - 1]).Select(i => s[i]).ToArray());\n}\n", "language": "C-sharp" }, { "code": "(defn collapse [s]\n (let [runs (partition-by identity s)]\n (apply str (map first runs))))\n\n(defn run-test [s]\n (let [out (collapse s)]\n (str (format \"Input: <<<%s>>> (len %d)\\n\" s (count s))\n (format \"becomes: <<<%s>>> (len %d)\\n\" out (count out)))))\n", "language": "Clojure" }, { "code": "% Collapse a string\ncollapse = proc (s: string) returns (string)\n out: array[char] := array[char]$[]\n last: char := '\\000'\n\n for c: char in string$chars(s) do\n if c ~= last then\n last := c\n array[char]$addh(out,c)\n end\n end\n return (string$ac2s(out))\nend collapse\n\n% Show a string in brackets, with its length\nbrackets = proc (s: string)\n stream$putl(stream$primary_output(),\n int$unparse(string$size(s))\n || \" <<<\"\n || s\n || \">>>\")\nend brackets\n\n% Show a string and its collapsed version, and the corresponding lengths\nshow = proc (s: string)\n brackets(s)\n brackets(collapse(s))\n stream$putl(stream$primary_output(), \"\")\nend show\n\n% Try the examples from the task description\nstart_up = proc ()\n examples: array[string] := array[string]$[\n \"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \"\n ]\n\n for ex: string in array[string]$elements(examples) do\n show(ex)\n end\nend start_up\n", "language": "CLU" }, { "code": "include \"cowgol.coh\";\ninclude \"strings.coh\";\n\n# Collapse the string at in, and store the result in the given buffer\nsub collapse(in: [uint8], out: [uint8]) is\n var ch := [in];\n in := @next in;\n loop\n if ch == 0 then\n [out] := 0;\n return;\n elseif [in] != ch then\n [out] := ch;\n out := @next out;\n ch := [in];\n end if;\n in := @next in;\n end loop;\nend sub;\n\n# Given a string, collapse it and print all required output\nsub show(str: [uint8]) is\n sub bracket_length(str: [uint8]) is\n print_i32(StrLen(str) as uint32);\n print(\" <<<\");\n print(str);\n print(\">>>\");\n print_nl();\n end sub;\n\n var buf: uint8[256];\n collapse(str, &buf[0]);\n bracket_length(str);\n bracket_length(&buf[0]);\n print_nl();\nend sub;\n\n# Strings from the task\nvar strings: [uint8][] := {\n\"\",\n\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n\"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n\"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n\" --- Harry S Truman \"\n};\n\n# Collapse and print each string\nvar i: @indexof strings := 0;\nwhile i < @sizeof strings loop\n show(strings[i]);\n i := i + 1;\nend loop;\n", "language": "Cowgol" }, { "code": "import std.stdio;\n\nvoid collapsible(string s) {\n writeln(\"old: <<<\", s, \">>>, length = \", s.length);\n\n write(\"new: <<<\");\n char last = '\\0';\n int len = 0;\n foreach (c; s) {\n if (c != last) {\n write(c);\n len++;\n }\n last = c;\n }\n writeln(\">>>, length = \", len);\n\n writeln;\n}\n\nvoid main() {\n collapsible(``);\n collapsible(`\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln `);\n collapsible(`..1111111111111111111111111111111111111111111111111111111111111117777888`);\n collapsible(`I never give 'em hell, I just tell the truth, and they think it's hell. `);\n collapsible(` --- Harry S Truman `);\n}\n", "language": "D" }, { "code": "program Determine_if_a_string_is_collapsible;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils;\n\nprocedure collapsible(s: string);\nvar\n c, last: char;\n len: Integer;\nbegin\n writeln('old: <<<', s, '>>>, length = ', s.length);\n write('new: <<<');\n last := #0;\n len := 0;\n for c in s do\n begin\n if c <> last then\n begin\n write(c);\n inc(len);\n end;\n last := c;\n end;\n writeln('>>>, length = ', len, #10);\nend;\n\nbegin\n collapsible('');\n collapsible('\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ');\n collapsible('..1111111111111111111111111111111111111111111111111111111111111117777888');\n collapsible('I never give ''em hell, I just tell the truth, and they think it''s hell. ');\n collapsible(' --- Harry S Truman ');\n readln;\nend.\n", "language": "Delphi" }, { "code": "func$ collapse s$ .\n for c$ in strchars s$\n if c$ <> cc$\n r$ &= c$\n .\n cc$ = c$\n .\n return r$\n.\ns$[] &= \"\"\ns$[] &= \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"\ns$[] &= \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\ns$[] &= \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\ns$[] &= \" --- Harry S Truman \"\nfor s$ in s$[]\n print \"«««\" & s$ & \"»»» (\" & len s$ & \")\"\n r$ = collapse s$\n print \"«««\" & r$ & \"»»» (\" & len r$ & \")\"\n print \"\"\n.\n", "language": "EasyLang" }, { "code": "// Collapse a String. Nigel Galloway: June 9th., 2020\n//As per the task description a function which 'determines if a character string is collapsible' by testing if any consecutive characters are the same.\nlet isCollapsible n=n|>Seq.pairwise|>Seq.tryFind(fun(n,g)->n=g)\n//As per the task description a function which 'if the string is collapsable, collapses the string (by removing immediately repeated characters).\nlet collapse n=match isCollapsible n with\n Some _->let i=Seq.head n\n let fN=let mutable g=i in (fun n->if n=g then false else g<-n; true)\n let g=System.String([|yield i;yield! Seq.tail n|>Seq.filter fN|])\n printfn \"<<<%s>>> (length %d) colapses to <<<%s>>> (length %d)\" n n.Length g g.Length\n | _->printfn \"<<<%s>>> (length %d) does not colapse\" n n.Length\n\ncollapse \"\"\ncollapse \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"\ncollapse \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\ncollapse \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\ncollapse \" --- Harry S Truman \"\ncollapse \"withoutConsecutivelyRepeatedCharacters\"\n", "language": "F-Sharp" }, { "code": "USING: formatting io kernel sbufs sequences strings ;\nIN: rosetta-code.string-collapse\n\n: (collapse) ( str -- str )\n unclip-slice 1string >sbuf\n [ over last over = [ drop ] [ suffix! ] if ] reduce >string ;\n\n: collapse ( str -- str ) [ \"\" ] [ (collapse) ] if-empty ;\n\n: .str ( str -- ) dup length \"«««%s»»» (length %d)\\n\" printf ;\n\n: show-collapse ( str -- )\n [ \"Before collapse: \" write .str ]\n [ \"After collapse: \" write collapse .str ] bi nl ;\n\n: collapse-demo ( -- )\n {\n \"\"\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n \" --- Harry S Truman \"\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\"\n \"headmistressship\"\n \"aardvark\"\n \"😍😀🙌💃😍😍😍🙌\"\n } [ show-collapse ] each ;\n\nMAIN: collapse-demo\n", "language": "Factor" }, { "code": "Const numCad = 5\nData \"\"\nData \"'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln \"\nData \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\nData \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\nData \" --- Harry S Truman \"\n\nDim Shared As String cadIN, cadOUT\n\nSub Collapse\n Dim As String a, b\n If cadIN = \"\" Then cadOUT = cadIN: Exit Sub\n cadOUT = Space(Len(cadIN))\n a = Left(cadIN,1)\n Mid(cadOUT,1,1) = a\n Dim As Integer txtOUT = 2\n For i As Integer = 2 To Len(cadIN)\n b = Mid(cadIN,i,1)\n If a <> b Then Mid(cadOUT,txtOUT,1) = b: txtOUT += 1: a = b\n Next i\n cadOUT = Left(cadOUT,txtOUT-1)\nEnd Sub\n\nFor j As Integer = 1 To numCad\n Read cadIN\n Collapse\n Print \" <<<\"; cadIN; \">>> (longitud \"; Len(cadIN); _\n !\")\\n se pliega a:\\n <<<\"; cadOUT; \">>> (longitud \"; Len(cadOUT); !\")\\n\"\nNext j\nSleep\n", "language": "FreeBASIC" }, { "code": "collapse[str] := str =~ %s/(.)\\1+/$1/g\n\nlines = [\"\",\n \"\"\"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln \"\"\",\n\"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n\"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n\" --- Harry S Truman \"]\n\nfor line = lines\n println[collapse[line]]\n", "language": "Frink" }, { "code": "local fn CollapseString( inString as CFStringRef ) as CFStringRef\n CFMutableStringRef outString = fn MutableStringWithCapacity(0)\n long index\n unichar prevChar = 0, currChar\n\n for index = 0 to len(inString) - 1\n currChar = fn StringCharacterAtIndex( inString, index )\n if ( currChar != prevChar ) then MutableStringAppendFormat( outString, @\"%C\", currChar )\n prevChar = currChar\n next\nend fn = outString\n\nwindow 1, @\"Collapse String\", (0,0,600,300)\n\nCFStringRef string, collapsedString\n\nstring = @\"\"\ncollapsedString = fn CollapseString( string )\nprintf @\"<<<%@>>> %ld\\n<<<%@>>> %ld\\n\",string,len(string),collapsedString,len(collapsedString)\n\nstring = @\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"\ncollapsedString = fn CollapseString( string )\nprintf@\"<<<%@>>> %ld\\n<<<%@>>> %ld\\n\",string,len(string),collapsedString,len(collapsedString)\n\nstring = @\"..1111111111111111111111111111111111111111111111111111111111111117777888\"\ncollapsedString = fn CollapseString( string )\nprintf@\"<<<%@>>> %ld\\n<<<%@>>> %ld\\n\",string,len(string),collapsedString,len(collapsedString)\n\nstring = @\"I never give 'em hell, I just tell the truth, and they think it's hell. \"\ncollapsedString = fn CollapseString( string )\nprintf@\"<<<%@>>> %ld\\n<<<%@>>> %ld\\n\",string,len(string),collapsedString,len(collapsedString)\n\nstring = @\" --- Harry S Truman \"\ncollapsedString = fn CollapseString( string )\nprintf@\"<<<%@>>> %ld\\n<<<%@>>> %ld\\n\",string,len(string),collapsedString,len(collapsedString)\n\nstring = @\"\\\"AAAAAll that glitters is not goldDDDD.\\\" - William Shakespeare\"\ncollapsedString = fn CollapseString( string )\nprintf@\"<<<%@>>> %ld\\n<<<%@>>> %ld\\n\",string,len(string),collapsedString,len(collapsedString)\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport \"fmt\"\n\n// Returns collapsed string, original and new lengths in\n// unicode code points (not normalized).\nfunc collapse(s string) (string, int, int) {\n r := []rune(s)\n le, del := len(r), 0\n for i := le - 2; i >= 0; i-- {\n if r[i] == r[i+1] {\n copy(r[i:], r[i+1:])\n del++\n }\n }\n if del == 0 {\n return s, le, le\n }\n r = r[:le-del]\n return string(r), le, len(r)\n}\n\nfunc main() {\n strings:= []string {\n \"\",\n `\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln `,\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"😍😀🙌💃😍😍😍🙌\",\n }\n for _, s := range strings {\n cs, olen, clen := collapse(s)\n fmt.Printf(\"original : length = %2d, string = «««%s»»»\\n\", olen, s)\n fmt.Printf(\"collapsed: length = %2d, string = «««%s»»»\\n\\n\", clen, cs)\n }\n}\n", "language": "Go" }, { "code": "class StringCollapsible {\n static void main(String[] args) {\n for ( String s : [\n \"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"122333444455555666666777777788888888999999999\",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\"]) {\n String result = collapse(s)\n System.out.printf(\"old: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n\", s.length(), s, result.length(), result)\n }\n }\n\n private static String collapse(String input) {\n StringBuilder sb = new StringBuilder()\n for ( int i = 0 ; i < input.length() ; i++ ) {\n if ( i == 0 || input.charAt(i-1) != input.charAt(i) ) {\n sb.append(input.charAt(i))\n }\n }\n return sb.toString()\n }\n}\n", "language": "Groovy" }, { "code": "import Text.Printf (printf)\nimport Data.Maybe (catMaybes)\nimport Control.Monad (guard)\n\ninput :: [String]\ninput = [ \"\"\n , \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\"\n , \"headmistressship\"\n , \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"\n , \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n , \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n , \" --- Harry S Truman \"\n , \"😍😀🙌💃😍😍😍🙌\"\n ]\n\ncollapse :: Eq a => [a] -> [a]\ncollapse = catMaybes . (\\xs -> zipWith (\\a b -> guard (a /= b) >> a) (Nothing : xs) (xs <> [Nothing])) . map Just\n\nmain :: IO ()\nmain =\n mapM_ (\\(a, b) -> printf \"old: %3d «««%s»»»\\nnew: %3d «««%s»»»\\n\\n\" (length a) a (length b) b)\n $ ((,) <*> collapse) <$> input\n", "language": "Haskell" }, { "code": "import Data.List (group)\n\nisCollapsible :: String -> Bool\nisCollapsible = any ((1 <) . length) . group\n\ncollapsed :: String -> String\ncollapsed = map head . group\n", "language": "Haskell" }, { "code": "isCollapsible :: String -> Bool\nisCollapsible [] = False\nisCollapsible [_] = False\nisCollapsible (h:t@(x:_)) = h == x || isCollapsible t\n\ncollapsed :: String -> String\ncollapsed [] = []\ncollapsed [x] = [x]\ncollapsed (h:t@(x:_))\n | h == x = collapsed t\n | otherwise = h : collapsed t\n", "language": "Haskell" }, { "code": "// Title: Determine if a string is collapsible\n\npublic class StringCollapsible {\n\n public static void main(String[] args) {\n for ( String s : new String[] {\n \"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"122333444455555666666777777788888888999999999\",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\"}) {\n String result = collapse(s);\n System.out.printf(\"old: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n\", s.length(), s, result.length(), result);\n }\n }\n\n private static String collapse(String in) {\n StringBuilder sb = new StringBuilder();\n for ( int i = 0 ; i < in.length() ; i++ ) {\n if ( i == 0 || in.charAt(i-1) != in.charAt(i) ) {\n sb.append(in.charAt(i));\n }\n }\n return sb.toString();\n }\n\n}\n", "language": "Java" }, { "code": "String.prototype.collapse = function() {\n let str = this;\n for (let i = 0; i < str.length; i++) {\n while (str[i] == str[i+1]) str = str.substr(0,i) + str.substr(i+1);\n }\n return str;\n}\n\n// testing\nlet strings = [\n '',\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n '..1111111111111111111111111111111111111111111111111111111111111117777888',\n `I never give 'em hell, I just tell the truth, and they think it's hell. `,\n ' --- Harry S Truman '\n];\nfor (let i = 0; i < strings.length; i++) {\n let str = strings[i], col = str.collapse();\n console.log(`«««${str}»»» (${str.length})`);\n console.log(`«««${col}»»» (${col.length})`);\n}\n", "language": "JavaScript" }, { "code": "# Input: an array\n# Output: a stream\ndef uniq: foreach .[] as $x ({x:nan, y:.[0]}; {x:$x, y:.x}; select(.x != .y) | .x);\n\ndef collapse: explode | [uniq] | implode;\n", "language": "Jq" }, { "code": "def Guillemets: \"«««\\(.)»»»\";\n\n\"Original: \\(Guillemets) has length \\(length)\",\n(collapse | \"Collapsed \\(Guillemets) has length \\(length)\")\n", "language": "Jq" }, { "code": "Original: «««»»» has length 0\nCollapsed «««»»» has length 0\nOriginal: «««\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln »»» has length 72\nCollapsed «««\"If I were two-faced, would I be wearing this one?\" - Abraham Lincoln »»» has length 70\nOriginal: «««..1111111111111111111111111111111111111111111111111111111111111117777888»»» has length 72\nCollapsed «««.178»»» has length 4\nOriginal: «««I never give 'em hell, I just tell the truth, and they think it's hell. »»» has length 72\nCollapsed «««I never give 'em hel, I just tel the truth, and they think it's hel. »»» has length 69\nOriginal: ««« --- Harry S Truman »»» has length 72\nCollapsed ««« - Hary S Truman »»» has length 17\n", "language": "Jq" }, { "code": "const teststrings = [\n \"\",\n \"\"\"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln \"\"\",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"\"\"I never give 'em hell, I just tell the truth, and they think it's hell. \"\"\",\n \" --- Harry S Truman \"]\n\nfunction collapse(s)\n len = length(s)\n if len < 2\n return s, len, s, len\n end\n result = last = s[1]\n for c in s[2:end]\n if c != last\n last = c\n result *= c\n end\n end\n return s, len, result, length(result)\nend\n\nfunction testcollapse(arr)\n for s in arr\n (s1, len1, s2, len2) = collapse(s)\n println(\"«««$s1»»» (length $len1)\\n collapses to:\\n«««$s2»»» (length $len2).\\n\")\n end\nend\n\ntestcollapse(teststrings)\n", "language": "Julia" }, { "code": "const teststrings = [\n \"\",\n \"\"\"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln \"\"\",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"\"\"I never give 'em hell, I just tell the truth, and they think it's hell. \"\"\",\n \" --- Harry S Truman \"]\n\ncollapse(s) = (t = isempty(s) ? \"\" : s[1:1]; for c in s if c != t[end] t *= c end; end; t)\n\nfor s in teststrings\n n, t = length(s), collapse(s)\n println(\"«««$s»»» (length $n)\\n collapses to:\\n«««$t»»» (length $(length(t))).\\n\")\nend\n", "language": "Julia" }, { "code": "fun collapse(s: String): String {\n val cs = StringBuilder()\n var last: Char = 0.toChar()\n for (c in s) {\n if (c != last) {\n cs.append(c)\n last = c\n }\n }\n return cs.toString()\n}\n\nfun main() {\n val strings = arrayOf(\n \"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\"\n )\n for (s in strings) {\n val c = collapse(s)\n println(\"original : length = ${s.length}, string = «««$s»»»\")\n println(\"collapsed : length = ${c.length}, string = «««$c»»»\")\n println()\n }\n}\n", "language": "Kotlin" }, { "code": "#!/bin/ksh\n\n# Determine if a string is collapsible (repeated letters)\n\n#\t# Variables:\n#\ntypeset -a strings\nstrings[0]=\"\"\nstrings[1]='\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln'\nstrings[2]=\"..1111111111111111111111111111111111111111111111111111111111111117777888\"\nstrings[3]=\"I never give 'em hell, I just tell the truth, and they think it's hell.\"\nstrings[4]=\" --- Harry S Truman\"\n\ntypeset -a Guillemet=( \"«««\" \"»»»\" )\n\n#\t# Functions:\n#\n#\t# Function _collapse(str) - return colapsed version of str\n#\nfunction _collapse {\n\ttypeset _str ; _str=\"$1\"\n\ttypeset _i _buff ; integer _i\n\n\tfor ((_i=1; _i<${#_str}; _i++)); do\n\t\tif [[ \"${_str:$((_i-1)):1}\" == \"${_str:${_i}:1}\" ]]; then\n\t\t\tcontinue\n\t\telse\n\t\t\t_buff+=${_str:$((_i-1)):1}\n\t\tfi\n\tdone\n\t[[ \"${_str:$((_i-1)):1}\" != \"${_str:${_i}:1}\" ]] && _buff+=${_str:$((_i-1)):1}\n\techo \"${_buff}\"\n}\n\n ######\n# main #\n ######\nfor ((i=0; i<${#strings[*]}; i++)); do\n\tstr=$(_collapse \"${strings[i]}\")\n\tprint ${#strings[i]} \"${Guillemet[0]}${strings[i]}${Guillemet[1]}\"\n\tprint ${#str} \"${Guillemet[0]}${str}${Guillemet[1]}\\n\"\ndone\n", "language": "Ksh" }, { "code": "function collapse(s)\n local ns = \"\"\n local last = nil\n for c in s:gmatch\".\" do\n if last then\n if last ~= c then\n ns = ns .. c\n end\n last = c\n else\n ns = ns .. c\n last = c\n end\n end\n return ns\nend\n\nfunction test(s)\n print(\"old: \" .. s:len() .. \" <<<\" .. s .. \">>>\")\n local a = collapse(s)\n print(\"new: \" .. a:len() .. \" <<<\" .. a .. \">>>\")\nend\n\nfunction main()\n test(\"\")\n test(\"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\")\n test(\"headmistressship\")\n test(\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \")\n test(\"..1111111111111111111111111111111111111111111111111111111111111117777888\")\n test(\"I never give 'em hell, I just tell the truth, and they think it's hell. \")\n test(\" --- Harry S Truman \")\nend\n\nmain()\n", "language": "Lua" }, { "code": "ClearAll[StringCollapse]\nStringCollapse[s_String] := FixedPoint[StringReplace[y_ ~~ y_ :> y], s]\nstrings = {\"\",\n\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n\"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n\"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n\" --- Harry S Truman \"};\nDo[\n Print[\"«««\" <> s <> \"»»»\"];\n Print[\"Length = \", StringLength[s]];\n Print[\"«««\" <> StringCollapse[s] <> \"»»»\"];\n Print[\"Length = \", StringLength[StringCollapse[s]]]\n ,\n {s, strings}\n ]\n", "language": "Mathematica" }, { "code": "function r = collapse(s)\n ix=find((s(1:end-1)==s(2:end))+1;\n r=s;\n r(ix)=[];\n\n fprintf(1,'Input: <<<%s>>> length: %d\\n',s,length(s));\n fprintf(1,'Output: <<<%s>>> length: %d\\n',r,length(r));\n fprintf(1,'Character to be squeezed: \"%s\"\\n',c);\n\nend\n\n\ncollapse('', ' ')\ncollapse('║╚═══════════════════════════════════════════════════════════════════════╗', '-')\ncollapse('║\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ║', '7')\ncollapse('║..1111111111111111111111111111111111111111111111111111111111111117777888║', '.')\ncollapse('║I never give ''em hell, I just tell the truth, and they think it''s hell. ║', '.')\ncollapse('║ --- Harry S Truman ║', '.')\ncollapse('║ --- Harry S Truman ║', '-')\ncollapse('║ --- Harry S Truman ║', 'r')\n", "language": "MATLAB" }, { "code": "main :: [sys_message]\nmain = [Stdout (lay (map test tests))]\n\ntests :: [[char]]\ntests\n= [\n \"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111111111788\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \"\n ]\n\ntest :: [char]->[char]\ntest s = lay [before, after]\n where before = disp s\n after = disp (collapse s)\n\ndisp :: [char]->[char]\ndisp s = show (#s) ++ \": <<<\" ++ s ++ \">>>\"\n\ncollapse :: [*]->[*]\ncollapse [] = []\ncollapse [x] = [x]\ncollapse (x:y:xs) = collapse (y:xs), if x=y\n = x:collapse (y:xs), otherwise\n", "language": "Miranda" }, { "code": "MODULE StrCollapse;\nFROM InOut IMPORT WriteString, WriteCard, WriteLn;\nFROM Strings IMPORT Length;\n\n(* Collapse a string *)\nPROCEDURE Collapse(in: ARRAY OF CHAR; VAR out: ARRAY OF CHAR);\n VAR i, o: CARDINAL;\nBEGIN\n i := 0;\n o := 0;\n WHILE (i < HIGH(in)) AND (in[i] # CHR(0)) DO\n IF (o = 0) OR (out[o-1] # in[i]) THEN\n out[o] := in[i];\n INC(o);\n END;\n INC(i);\n END;\n out[o] := CHR(0);\nEND Collapse;\n\n(* Display a string and collapse it as stated in the task *)\nPROCEDURE Task(s: ARRAY OF CHAR);\n VAR buf: ARRAY [0..127] OF CHAR;\n PROCEDURE LengthAndBrackets(s: ARRAY OF CHAR);\n BEGIN\n WriteCard(Length(s), 2);\n WriteString(\" <<<\");\n WriteString(s);\n WriteString(\">>>\");\n WriteLn();\n END LengthAndBrackets;\nBEGIN\n LengthAndBrackets(s);\n Collapse(s, buf);\n LengthAndBrackets(buf);\n WriteLn();\nEND Task;\n\nBEGIN\n Task(\"\");\n Task('\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ');\n Task(\"..1111111111111111111111111111111111111111111111111111111111111117777888\");\n Task(\"I never give 'em hell, I just tell the truth, and they think it's hell. \");\n Task(\" --- Harry S Truman \");\nEND StrCollapse.\n", "language": "Modula-2" }, { "code": "to-report split [ string ]\n ;; utility reporter to split a string into a list\n report n-values length string [ [ n ] -> item n string ]\nend\n\nto-report collapse [ string ]\n ;; reporter that actually does the collapse function\n ifelse ( string = \"\" )\n [ report \"\" ]\n [ report reduce [ [ a b ] -> (word a ifelse-value last a != b [ b ] [ \"\" ] ) ] split string ]\nend\n\nto-report format [ string ]\n ;; reporter to format the output as required\n report ( word \"<<<\" string \">>> \" length string )\nend\n\nto demo-collapse [ string ]\n ;; procedure to display the required output\n output-print format string\n output-print format collapse string\nend\n\nto demo\n ;; procedure to perform the test cases\n foreach\n [ \"\"\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n \" --- Harry S Truman \"\n ]\n demo-collapse\nend\n", "language": "NetLogo" }, { "code": "import unicode, strformat\n\nproc collapse(s: string) =\n let original = s.toRunes\n echo fmt\"Original: length = {original.len}, string = «««{s}»»»\"\n var previous = Rune(0)\n var collapsed: seq[Rune]\n for rune in original:\n if rune != previous:\n collapsed.add(rune)\n previous = rune\n echo fmt\"Collapsed: length = {collapsed.len}, string = «««{collapsed}»»»\"\n echo \"\"\n\n\nconst Strings = [\"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"😍😀🙌💃😍😍😍🙌\",]\n\n\nfor s in Strings:\n s.collapse()\n", "language": "Nim" }, { "code": "use strict;\nuse warnings;\nuse utf8;\nbinmode STDOUT, \":utf8\";\n\nmy @lines = split \"\\n\", <<~'STRINGS';\n\n \"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln\n ..1111111111111111111111111111111111111111111111111111111111111117777888\n I never give 'em hell, I just tell the truth, and they think it's hell.\n --- Harry S Truman\n The American people have a right to know if their president is a crook.\n --- Richard Nixon\n AАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑ\n AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n STRINGS\n\nfor (@lines) {\n my $squish = s/(.)\\1+/$1/gr;\n printf \"\\nLength: %2d <<<%s>>>\\nCollapsible: %s\\nLength: %2d <<<%s>>>\\n\",\n length($_), $_, $_ ne $squish ? 'True' : 'False', length($squish), $squish\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">`\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln `</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"..1111111111111111111111111111111111111111111111111111111111111117777888\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"I never give 'em hell, I just tell the truth, and they think it's hell. \"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\" --- Harry S Truman \"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #000000;\">fmt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"\"\t\t\n length %2d input: &lt;&lt;&lt;%s&gt;&gt;&gt;\n length %2d output: &lt;&lt;&lt;%s&gt;&gt;&gt;\n \"\"\"</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">ti</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">ci</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">unique</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"PRESORTED\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">fmt</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">ci</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">collapsible</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- sequence utf32 = utf8_to_utf32(t) -- maybe\n -- for i=2 to length(utf32) do -- \"\"\"\n -- if utf32[i]=utf32[i-1] then -- \"\"\"</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\nAs predicate: \"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%t \"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">collapsible</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\n\nfunction collapseString($string) {\n $previousChar = null;\n $collapse = '';\n $charArray = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);\n for ($i = 0 ; $i < count($charArray) ; $i++) {\n $currentChar = $charArray[$i];\n if ($previousChar !== $currentChar) {\n $collapse .= $charArray[$i];\n }\n $previousChar = $currentChar;\n }\n return $collapse;\n}\n\nfunction isCollapsible($string) {\n return ($string !== collapseString($string));\n}\n\n$strings = array(\n '',\n 'another non colapsing string',\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n '..1111111111111111111111111111111111111111111111111111111111111117777888',\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n ' --- Harry S Truman ',\n '0112223333444445555556666666777777778888888889999999999',\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n 'headmistressship',\n \"😍😀🙌💃😍😍😍🙌\",\n);\n\nforeach ($strings as $original) {\n echo 'Original : <<<', $original, '>>> (len=', mb_strlen($original), ')', PHP_EOL;\n if (isCollapsible($original)) {\n $collapse = collapseString($original);\n echo 'Collapse : <<<', $collapse, '>>> (len=', mb_strlen($collapse), ')', PHP_EOL, PHP_EOL;\n } else {\n echo 'Collapse : string is not collapsing...', PHP_EOL, PHP_EOL;\n }\n}\n", "language": "PHP" }, { "code": "100H:\nBDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;\nEXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;\nPRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;\n\n/* PRINT NUMBER */\nPRINT$NUMBER: PROCEDURE (N);\n DECLARE S (6) BYTE INITIAL ('.....$');\n DECLARE (N, P) ADDRESS, C BASED P BYTE;\n P = .S(5);\nDIGIT:\n P = P - 1;\n C = N MOD 10 + '0';\n N = N / 10;\n IF N > 0 THEN GO TO DIGIT;\n CALL PRINT(P);\nEND PRINT$NUMBER;\n\n/* STRING LENGTH */\nSTR$LEN: PROCEDURE (STR) ADDRESS;\n DECLARE (STR, I) ADDRESS, S BASED STR BYTE;\n I = 0;\n DO WHILE S(I) <> '$';\n I = I + 1;\n END;\n RETURN I;\nEND STR$LEN;\n\n/* COLLAPSE */\nCOLLAPSE: PROCEDURE (IN, OUT);\n DECLARE (IN, OUT) ADDRESS, (I BASED IN, O BASED OUT, C) BYTE;\n C = I;\n DO WHILE C <> '$';\n IN = IN + 1;\n IF I <> C THEN DO;\n O = C;\n OUT = OUT + 1;\n C = I;\n END;\n END;\n O = '$';\nEND COLLAPSE;\n\n/* PRINT STRING AND LENGTH WITH BRACKETS */\nPRINT$BRACKETS: PROCEDURE (S);\n DECLARE S ADDRESS;\n CALL PRINT$NUMBER(STR$LEN(S));\n CALL PRINT(.' <<<$');\n CALL PRINT(S);\n CALL PRINT(.('>>>',13,10,'$'));\nEND PRINT$BRACKETS;\n\n/* GIVEN A STRING, PRINT IT AND ITS COLLAPSED FORM */\nSHOW: PROCEDURE (S);\n DECLARE S ADDRESS, BUFFER (256) BYTE;\n CALL COLLAPSE(S, .BUFFER);\n CALL PRINT$BRACKETS(S);\n CALL PRINT$BRACKETS(.BUFFER);\n CALL PRINT(.(13,10,'$'));\nEND SHOW;\n\n/* STRINGS FROM THE TASK */\nDECLARE X (5) ADDRESS;\nX(0)=.'$';\nX(1)=.('''IF I WERE TWO-FACED, WOULD I BE WEARING ',\n 'THIS ONE.'' --- ABRAHAM LINCOLN $');\nX(2)=.('..111111111111111111111111111111111111111',\n '1111111111111111111111117777888$');\nX(3)=.('I NEVER GIVE ''EM HELL, I JUST TELL THE TR',\n 'UTH, AND THEY THINK IT''S HELL. $');\nX(4)=.(' ',\n ' --- HARRY S TRUMAN $');\n\nDECLARE I BYTE;\nDO I=0 TO LAST(X);\n CALL SHOW(X(I));\nEND;\nCALL EXIT;\nEOF\n", "language": "PL-M" }, { "code": "collapse_( [], [] ).\ncollapse_( [A], [A] ).\ncollapse_( [A,A|T], R ) :- collapse_( [A|T], R ).\ncollapse_( [A,B|T], [A|R] ) :- dif( A, B ), collapse_( [B|T], R ).\n\ncollapse( Str, Collapsed ) :-\n string_chars( Str, Chars ),\n collapse_( Chars, Result ),\n string_chars( Collapsed, Result ).\n", "language": "Prolog" }, { "code": "EnableExplicit\nDataSection\n STR1:\n Data.s \"\"\n STR2:\n Data.s \"'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln \"\n STR3:\n Data.s \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n STR4:\n Data.s \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n STR5:\n Data.s \" --- Harry S Truman \"\nEndDataSection\n\nProcedure.s collapse(txt$)\n Define *c.Character=@txt$, last.c=0, result$\n While *c\\c\n If *c\\c<>last\n result$+Chr(*c\\c)\n last=*c\\c\n EndIf\n *c+SizeOf(Character)\n Wend\n ProcedureReturn result$\nEndProcedure\n\nOpenConsole(\"\")\nDefine *p_data=?STR1, buf$\nWhile *p_data<=?STR4+StringByteLength(PeekS(?STR4))+2\n buf$=PeekS(*p_data)\n PrintN(\"Before collapse: «««\"+buf$+\"»»» (length: \"+Str(Len(buf$))+\")\")\n buf$=collapse(PeekS(*p_data))\n PrintN(\"After collapse: «««\"+buf$+~\"»»» (length: \"+Str(Len(buf$))+~\")\\n\")\n *p_data+StringByteLength(PeekS(*p_data))+2\nWend\nInput()\n", "language": "PureBasic" }, { "code": "from itertools import groupby\n\ndef collapser(txt):\n return ''.join(item for item, grp in groupby(txt))\n\nif __name__ == '__main__':\n strings = [\n \"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"😍😀🙌💃😍😍😍🙌\",\n ]\n for txt in strings:\n this = \"Original\"\n print(f\"\\n{this:14} Size: {len(txt)} «««{txt}»»»\" )\n this = \"Collapsed\"\n sqz = collapser(txt)\n print(f\"{this:>14} Size: {len(sqz)} «««{sqz}»»»\" )\n", "language": "Python" }, { "code": "'''Determining if a string is collapsible'''\n\nfrom operator import eq\n\n\n# isCollapsible :: String -> Bool\ndef isCollapsible(s):\n '''True if s contains any consecutively\n repeated characters.\n '''\n return False if 2 > len(s) else (\n any(map(eq, s, s[1:]))\n )\n\n\n# ------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Determining whether each string is collapsible'''\n xs = [\n \"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"😍😀🙌💃😍😍😍🙌\",\n \"abcdefghijklmnopqrstuvwxyz\"\n ]\n print([\n isCollapsible(x) for x in xs\n ])\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": " [ false -1 rot\n witheach\n [ 2dup = iff\n [ drop dip not\n conclude ]\n else nip ]\n drop ] is collapsible ( $ --> b )\n\n [ [] -1 rot\n witheach\n [ 2dup = iff drop\n else\n [ nip dup dip join ] ]\n drop ] is collapse ( $ --> $ )\n\n [ dup collapsible iff\n [ dup collapse\n swap 2 ]\n else\n [ say \"(Not collapsible.)\" cr\n 1 ]\n times\n [ say \"<<<\"\n dup echo$\n say \">>>\" cr\n say \" Length: \"\n size echo\n say \" characters\" cr cr ]\n cr ] is task ( $ --> )\n\n$ \"\" task\n$ '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ' task\n$ \"..1111111111111111111111111111111111111111111111111111111111111117777888\" task\n$ \"I never give 'em hell, I just tell the truth, and they think it's hell. \" task\n$ \" --- Harry S Truman \" task\n", "language": "Quackery" }, { "code": "collapse_string <- function(string){\n\n str_iterable <- strsplit(string, \"\")[[1]]\n\n message(paste0(\"Original String: \", \"<<<\", string, \">>>\\n\",\n \"Length: \", length(str_iterable)))\n\n detect <- rep(TRUE, length(str_iterable))\n\n\n for(i in 2:length(str_iterable)){\n\n if(length(str_iterable)==0) break\n\n if(str_iterable[i] == str_iterable[i-1])\n\n detect[i] <- FALSE\n }\n\n collapsed_string <- paste(str_iterable[detect],collapse = \"\")\n\n message(paste0(\"Collapsed string: \", \"<<<\",collapsed_string, \">>>\\n\",\n \"Length: \", length(str_iterable[detect])), \"\\n\")\n\n}\n\ntest_strings <- c(\n \"\",\n \"'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"Ciao Mamma, guarda come mi diverto!!\"\n)\n\nfor(test in test_strings){\n collapse_string(test)\n}\n", "language": "R" }, { "code": "#lang racket\n\n(define (collapse text)\n (if (< (string-length text) 2)\n text\n (string-append\n (if (equal? (substring text 0 1) (substring text 1 2))\n \"\" (substring text 0 1))\n (collapse (substring text 1)))))\n\n; Test cases\n(define tcs\n '(\"\"\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n \" --- Harry S Truman \"\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\"\n \"headmistressship\"\n \"aardvark\"\n \"😍😀🙌💃😍😍😍🙌\"))\n\n(for ([text tcs])\n (let ([collapsed (collapse text)])\n (display (format \"Original (size ~a): «««~a»»»\\nCollapsed (size ~a): «««~a»»»\\n\\n\"\n (string-length text) text\n (string-length collapsed) collapsed))))\n", "language": "Racket" }, { "code": "map {\n my $squish = .comb.squish.join;\n printf \"\\nLength: %2d <<<%s>>>\\nCollapsible: %s\\nLength: %2d <<<%s>>>\\n\",\n .chars, $_, .chars != $squish.chars, $squish.chars, $squish\n}, lines\n\nq:to/STRINGS/;\n\n \"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln\n ..1111111111111111111111111111111111111111111111111111111111111117777888\n I never give 'em hell, I just tell the truth, and they think it's hell.\n --- Harry S Truman\n The American people have a right to know if their president is a crook.\n --- Richard Nixon\n AАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑ\n AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n STRINGS\n", "language": "Raku" }, { "code": "$ENTRY Go {\n , ('')\n ('\"If I were two-faced, would I be wearing this '\n 'one?\" --- Abraham Lincoln ')\n ('..11111111111111111111111111111111111111111111'\n '11111111111111111117777888')\n ('I never give \\'em hell, I just tell the truth, '\n 'and they think it\\'s hell. ')\n (' '\n ' --- Harry S Truman '): e.Strings\n = <Each Show e.Strings>;\n};\n\nEach {\n s.F = ;\n s.F t.I e.X = <Mu s.F t.I> <Each s.F e.X>;\n};\n\nBrackets {\n e.X, <Lenw e.X>: s.L e.X =\n <Prout <Symb s.L> ': <<<' e.X '>>>'>;\n};\n\nShow {\n (e.X) = <Brackets e.X>\n <Brackets <Collapse e.X>>\n <Prout>;\n};\n\nCollapse {\n = ;\n s.C s.C e.S = <Collapse s.C e.S>;\n s.C e.S = s.C <Collapse e.S>;\n};\n", "language": "Refal" }, { "code": "/*REXX program \"collapses\" all immediately repeated characters in a string (or strings).*/\n@.= /*define a default for the @. array. */\nparse arg x /*obtain optional argument from the CL.*/\nif x\\='' then @.1= x /*if user specified an arg, use that. */\n else do; @.1=\n @.2= '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln '\n @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888\n @.4= \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n @.5= ' --- Harry S Truman '\n end\n\n do j=1; L= length(@.j) /*obtain the length of an array element*/\n say copies('═', 105) /*show a separator line between outputs*/\n if j>1 & L==0 then leave /*if arg is null and J>1, then leave. */\n new= collapse(@.j)\n say 'string' word(\"isn't is\",1+collapsible) 'collapsible' /*display semaphore value*/\n say ' length='right(L, 3) \" input=«««\" || @.j || '»»»'\n w= length(new)\n say ' length='right(w, 3) \" output=«««\" || new || '»»»'\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncollapse: procedure expose collapsible; parse arg y 1 $ 2 /*get the arg; get 1st char. */\n do k=2 to length(y) /*traipse through almost all the chars.*/\n _= substr(y, k, 1) /*pick a character from Y (1st arg). */\n if _==right($, 1) then iterate /*Is this the same character? Skip it.*/\n $= $ || _ /*append the character, it's different.*/\n end /*j*/\n collapsible= y\\==$; return $ /*set boolean to true if collapsible.*/\n", "language": "REXX" }, { "code": "load \"stdlib.ring\"\n\nsee \"working...\" + nl + nl\nstr = [\"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell.\",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\"]\nstrsave = str\nfor n = 1 to len(str)\n for m = 1 to len(str[n])-1\n if substr(str[n],m,1) = substr(str[n],m+1,1)\n str[n] = left(str[n],m) + right(str[n],len(str[n])-m-1)\n for p = len(str[n]) to 2 step -1\n if substr(str[n],p,1) = substr(str[n],p-1,1)\n str[n] = left(str[n],p-1) + right(str[n],len(str[n])-p)\n ok\n next\n ok\n next\nnext\n\nfor n = 1 to len(str)\n see \"\" + len(strsave[n]) + \"«««\" + strsave[n] + \"»»»\" + nl\n see \"\" + len(str[n]) + \"«««\" + str[n] + \"»»»\" + nl + nl\nnext\n\nsee \"done...\" + nl\n", "language": "Ring" }, { "code": "strings = [\"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"😍😀🙌💃😍😍😍🙌\",]\n\nstrings.each do |str|\n puts \"«««#{str}»»» (size #{str.size})\"\n ssq = str.squeeze\n puts \"«««#{ssq}»»» (size #{ssq.size})\"\n puts\nend\n", "language": "Ruby" }, { "code": "fn collapse_string(val: &str) -> String {\n let mut output = String::new();\n let mut chars = val.chars().peekable();\n\n while let Some(c) = chars.next() {\n while let Some(&b) = chars.peek() {\n if b == c {\n chars.next();\n } else {\n break;\n }\n }\n\n output.push(c);\n }\n\n output\n}\n\nfn main() {\n let tests = [\n \"122333444455555666666777777788888888999999999\",\n \"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n ];\n\n for s in &tests {\n println!(\"Old: {:>3} <<<{}>>>\", s.len(), s);\n let collapsed = collapse_string(s);\n println!(\"New: {:>3} <<<{}>>>\", collapsed.len(), collapsed);\n\n println!();\n }\n}\n", "language": "Rust" }, { "code": "object CollapsibleString {\n\n /**Collapse a string (if possible)*/\n def collapseString (s : String) : String = {\n var res = s\n var isOver = false\n var i = 0\n if(res.size == 0) res\n else while(!isOver){\n if(res(i) == res(i+1)){\n res = res.take(i) ++ res.drop(i+1)\n i-=1\n }\n i+=1\n if(i==res.size-1) isOver = true\n }\n res\n }\n\n /**Check if a string is collapsible*/\n def isCollapsible (s : String) : Boolean = collapseString(s).length != s.length\n\n /**Display results as asked in the task*/\n def reportResults (s : String) : String = {\n val sCollapsed = collapseString(s)\n val originalRes = \"ORIGINAL : length = \" + s.length() + \", string = «««\" + s + \"»»»\"\n val collapsedRes = \"COLLAPSED : length = \" + sCollapsed.length() + \", string = «««\" + sCollapsed + \"»»»\"\n //In order to avoid useless computations, the function isCollapsible isn't called\n if(s.length != sCollapsed.length) originalRes + \"\\n\" + collapsedRes + \"\\n\" + \"This string IS collapsible !\"\n else originalRes + \"\\n\" + collapsedRes + \"\\n\" + \"This string is NOT collapsible !\"\n }\n\n\n\n def main(args: Array[String]): Unit = {\n println(reportResults(\"\"))\n println(\"------------\")\n println(reportResults(\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"))\n println(\"------------\")\n println(reportResults(\"..1111111111111111111111111111111111111111111111111111111111111117777888\"))\n println(\"------------\")\n println(reportResults(\"I never give 'em hell, I just tell the truth, and they think it's hell. \"))\n println(\"------------\")\n println(reportResults(\" --- Harry S Truman \"))\n println(\"------------\")\n println(reportResults(\"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\"))\n println(\"------------\")\n println(reportResults(\"headmistressship\"))\n println(\"------------\")\n println(reportResults(\"aardvark\"))\n }\n\n\n}\n", "language": "Scala" }, { "code": "h\ns/.*/<<<&>>>/\nx\ns/\\(.\\)\\1*/\\1/g\ns/.*/<<<&>>>/\nH\ns/.*//\nG\n", "language": "Sed" }, { "code": "func squeeze(str) {\n str.gsub(/(.)\\1+/, {|s1| s1 })\n}\n\nvar strings = [\"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"😍😀🙌💃😍😍😍🙌\"]\n\nstrings.each {|str|\n var ssq = squeeze(str)\n say \"«««#{str}»»» (length: #{str.len})\"\n say \"«««#{ssq}»»» (length: #{ssq.len})\\n\"\n}\n", "language": "Sidef" }, { "code": "#(\n 'The better the 4-wheel drive, the further you''ll be from help when ya get stuck!'\n 'headmistressship'\n 'aardvark'\n '😍😀🙌💃😍😍😍🙌'\n) do:[:eachWord |\n |shortened|\n\n shortened :=\n String streamContents:[:out |\n eachWord inject:nil into:[:prev :this |\n prev ~= this ifTrue:[out nextPut:this].\n this\n ]\n ].\n Transcript\n showCR:( eachWord,'(length:',eachWord size,')' );\n showCR:( shortened,'(length:',shortened size,')' ).\n]\n", "language": "Smalltalk" }, { "code": "let strings = [\n\t\"\",\n\t#\"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln \"#,\n\t\"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n\t\"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n\t\" --- Harry S Truman \",\n\t\"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n\t\"headmistressship\",\n\t\"aardvark\",\n\t\"😍😀🙌💃😍😍😍🙌\"\n]\n\nlet collapsedStrings = strings.map { $0.replacingOccurrences( of: #\"(.)\\1*\"#, with: \"$1\", options: .regularExpression)}\n\nfor (original, collapsed) in zip(strings, collapsedStrings) {\n\tprint (String(format: \"%03d «%@»\\n%03d «%@»\\n\", original.count, original, collapsed.count, collapsed))\n}\n", "language": "Swift" }, { "code": "set test {\n {}\n {\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln }\n {..1111111111111111111111111111111111111111111111111111111111111117777888}\n {I never give 'em hell, I just tell the truth, and they think it's hell. } ;# '\n { --- Harry S Truman }\n {The better the 4-wheel drive, the further you'll be from help when ya get stuck!} ;# '\n {headmistressship}\n}\n\nforeach {str} $test {\n # Uses regexp lookbehind to detect repeated characters\n set sub [regsub -all {(.)(\\1+)} $str {\\1}]\n\n # Output\n puts [format \"Original (length %3d): %s\" [string length $str] $str]\n puts [format \"Subbed (length %3d): %s\" [string length $sub] $sub]\n puts ----------------------\n}\n", "language": "Tcl" }, { "code": "// Returns collapsed string, original and new lengths in\n// unicode code points (not normalized).\nfn collapse(s string) (string, int, int) {\n mut r := s.runes()\n le, mut del := r.len, 0\n for i := le - 2; i >= 0; i-- {\n if r[i] == r[i+1] {\n r.delete(i)\n del++\n }\n }\n if del == 0 {\n return s, le, le\n }\n r = r[..le-del]\n return r.string(), le, r.len\n}\n\nfn main() {\n strings:= [\n \"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"😍😀🙌💃😍😍😍🙌\",\n\t]\n for s in strings {\n cs, olen, clen := collapse(s)\n println(\"original : length = ${olen:2}, string = «««$s»»»\")\n println(\"collapsed: length = ${clen:2}, string = «««$cs»»»\\n\")\n }\n}\n", "language": "V-(Vlang)" }, { "code": "Function Collapse(strIn As String) As String\nDim i As Long, strOut As String\n If Len(strIn) > 0 Then\n strOut = Mid$(strIn, 1, 1)\n For i = 2 To Len(strIn)\n If Mid$(strIn, i, 1) <> Mid$(strIn, i - 1, 1) Then\n strOut = strOut & Mid$(strIn, i, 1)\n End If\n Next i\n End If\n Collapse = strOut\nEnd Function\n", "language": "VBA" }, { "code": "Sub CallCollapse()\nDim S As String\n S = vbNullString\n Debug.Print \"String : <<<\" & S & \">>>\", \"Lenght : \" & Len(S)\n Debug.Print \"Collapsed : <<<\" & Collapse(S) & \">>>\", \"Lenght : \" & Len(Collapse(S))\n S = \"\"\"If I were two-faced, would I be wearing this one?\"\" --- Abraham Lincoln \"\n Debug.Print \"String : <<<\" & S & \">>>\", \"Lenght : \" & Len(S)\n Debug.Print \"Collapsed : <<<\" & Collapse(S) & \">>>\", \"Lenght : \" & Len(Collapse(S))\n S = \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n Debug.Print \"String : <<<\" & S & \">>>\", \"Lenght : \" & Len(S)\n Debug.Print \"Collapsed : <<<\" & Collapse(S) & \">>>\", \"Lenght : \" & Len(Collapse(S))\n S = \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n Debug.Print \"String : <<<\" & S & \">>>\", \"Lenght : \" & Len(S)\n Debug.Print \"Collapsed : <<<\" & Collapse(S) & \">>>\", \"Lenght : \" & Len(Collapse(S))\n S = \" --- Harry S Truman \"\n Debug.Print \"String : <<<\" & S & \">>>\", \"Lenght : \" & Len(S)\n Debug.Print \"Collapsed : <<<\" & Collapse(S) & \">>>\", \"Lenght : \" & Len(Collapse(S))\nEnd Sub\n", "language": "VBA" }, { "code": "Module Module1\n\n Function Collapse(s As String) As String\n If String.IsNullOrEmpty(s) Then\n Return \"\"\n End If\n Return s(0) + New String(Enumerable.Range(1, s.Length - 1).Where(Function(i) s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray)\n End Function\n\n Sub Main()\n Dim input() = {\n \"\",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n ControlChars.Quote + \"If I were two-faced, would I be wearing this one?\" + ControlChars.Quote + \" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \"\n }\n For Each s In input\n Console.WriteLine($\"old: {s.Length} «««{s}»»»\")\n Dim c = Collapse(s)\n Console.WriteLine($\"new: {c.Length} «««{c}»»»\")\n Next\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./fmt\" for Fmt\n\n// Returns collapsed string, original and new lengths in\n// unicode code points (not normalized).\nvar collapse = Fn.new { |s|\n var c = s.codePoints.toList\n var le = c.count\n if (le < 2) return [s, le, le]\n for (i in le-2..0) {\n if (c[i] == c[i+1]) c.removeAt(i)\n }\n var cc = c.reduce(\"\") { |acc, cp| acc + String.fromCodePoint(cp) }\n return [cc, le, cc.count]\n}\n\nvar strings = [\n \"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"😍😀🙌💃😍😍😍🙌\"\n]\n\nfor (s in strings) {\n var r = collapse.call(s)\n System.print(\"original : length = %(Fmt.d(2, r[1])), string = «««%(s)»»»\")\n System.print(\"collapsed: length = %(Fmt.d(2, r[2])), string = «««%(r[0])»»»\\n\")\n}\n", "language": "Wren" }, { "code": "string 0;\nchar C, I, J, Last;\n\nproc Collapse(S); \\Eliminate immediately repeated characters from string\nchar S;\n[I:= 0; J:= 0; Last:= -1;\nloop [if S(I) # Last then\n [C(J):= S(I);\n if S(I) = 0 then quit;\n J:= J+1;\n ];\n Last:= S(I);\n I:= I+1;\n ];\n];\n\nint String, K;\n[String:= [\n \"\",\n \"^\"If I were two-faced, would I be wearing this one?^\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \"];\nC:= Reserve(79+1); \\space for collapsed string\nfor K:= 0 to 4 do\n [Collapse(String(K));\n Text(0, \"<<<\"); Text(0, String(K)); Text(0, \">>> \"); IntOut(0, I); CrLf(0);\n Text(0, \"<<<\"); Text(0, C); Text(0, \">>> \"); IntOut(0, J); CrLf(0);\n ];\n]\n", "language": "XPL0" }, { "code": "fcn collapsible(str){\t\t\t// no Unicode\n sink:=Sink(String);\n str.reduce('wrap(c1,c2){ if(c1!=c2) sink.write(c2); c2 },\"\"); // prime with \\0\n cstr:=sink.close();\n return(str.len()!=cstr.len(), cstr);\n}\n", "language": "Zkl" }, { "code": "strings:=\n0'^\n\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln\n..1111111111111111111111111111111111111111111111111111111111111117777888\nI never give 'em hell, I just tell the truth, and they think it's hell.\n --- Harry S Truman\nThe American people have a right to know if their president is a crook.\n --- Richard Nixon\nThe better the 4-wheel drive, the further you'll be from help when ya get stuck!\nheadmistressship\naardvark^\n.split(\"\\n\");\n#<<<\n\nforeach s in (strings){\n println(\"Before: %3d >>>%s<<<\".fmt(s.len(),s));\n _,cstr:=collapsible(s);\n println(\"After: %3d >>>%s<<<\\n\".fmt(cstr.len(),cstr));\n}\n", "language": "Zkl" } ]
Determine-if-a-string-is-collapsible
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable\n", "language": "00-META" }, { "code": "Determine if a character string is &nbsp; ''squeezable''.\n\nAnd if so, &nbsp; squeeze the string &nbsp; (by removing any number of\na &nbsp; ''specified'' &nbsp; ''immediately repeated'' &nbsp; character).\n\n\nThis task is very similar to the task &nbsp; &nbsp; '''Determine if a character string is collapsible''' &nbsp; &nbsp; except\nthat only a specified character is &nbsp; ''squeezed'' &nbsp; instead of any character that is ''immediately repeated''.\n\n\nIf a character string has a specified &nbsp; ''immediately repeated'' &nbsp; character(s), &nbsp; the repeated characters are to be\ndeleted (removed), &nbsp; but not the primary (1<sup>st</sup>) character(s).\n\n\nA specified &nbsp; ''immediately repeated'' &nbsp; character is any specified character that is &nbsp; <u>immediately</u> &nbsp;\nfollowed by an identical character (or characters). &nbsp; Another word choice could've been &nbsp; ''duplicated\ncharacter'', &nbsp; but that might have ruled out &nbsp; (to some readers) &nbsp; triplicated characters &nbsp; ··· &nbsp; or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced &nbsp; (as of around\nNovember 2019) &nbsp; '''PL/I''' &nbsp; BIF: &nbsp; '''squeeze'''.}\n\n\n;Examples:\nIn the following character string with a specified &nbsp; ''immediately repeated'' &nbsp; character of &nbsp; '''e''':\n\n\n <big><big> The better the 4-whe<u>e</u>l drive, the further you'll be from help when ya get stuck! </big></big>\n\n\nOnly the 2<sup>nd</sup> &nbsp; '''e''' &nbsp; is an specified repeated character, &nbsp; indicated by an underscore\n(above), &nbsp; even though they (the characters) appear elsewhere in the character string.\n\n\n\nSo, after ''squeezing'' the string, the result would be:\n\n <big><big> The better the 4-whel drive, the further you'll be from help when ya get stuck! </big></big>\n\n\n\n\nAnother example:\nIn the following character string, &nbsp; using a specified immediately repeated character &nbsp; '''s''':\n\n <big><big> headmistres<u>ss</u>hip </big></big>\n\n\nThe \"squeezed\" string would be:\n\n <big><big> headmistreship </big></big>\n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine··· &nbsp; to locate a &nbsp; ''specified immediately repeated'' &nbsp; character\nand &nbsp; ''squeeze'' &nbsp; (delete) &nbsp; them from the character string. &nbsp; The\ncharacter string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* &nbsp; the &nbsp; specified repeated character &nbsp; (to be searched for and possibly ''squeezed''):\n:* &nbsp; the &nbsp; original string and its length\n:* &nbsp; the resultant string and its length\n:* &nbsp; the above strings should be \"bracketed\" with &nbsp; '''<<<''' &nbsp; and &nbsp; '''>>>''' &nbsp; (to delineate blanks)\n;* &nbsp; «««Guillemets may be used instead for \"bracketing\" for the more artistic programmers, &nbsp; shown used here»»»\n<!-- Guillemots shouldn't be used as they stink. !-->\n\n\nUse (at least) the following five strings, &nbsp; all strings are length seventy-two (characters, including blanks), &nbsp; except\nthe 1<sup>st</sup> string:\n\n immediately\n string repeated\n number character\n ( ↓ a blank, a minus, a seven, a period)\n ╔╗\n 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)\n 2 ║\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ║ '-'\n 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'\n 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'\n 5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks\n ╚════════════════════════════════════════════════════════════════════════╝ ↑\n │\n │\n For the 5<sup>th</sup> string (Truman's signature line), use each of these specified immediately repeated characters:\n &bull; a blank\n &bull; a minus\n &bull; a lowercase '''r'''\n\n\nNote: &nbsp; there should be seven results shown, &nbsp; one each for the 1<sup>st</sup> four strings, &nbsp; and three results for\nthe 5<sup>th</sup> string.\n\n{{Template:Strings}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F squeeze(input, include)\n V s = ‘’\n L(i) 0 .< input.len\n I i == 0 | input[i - 1] != input[i] | (input[i - 1] == input[i] & input[i] != include)\n s ‘’= input[i]\n R s\n\nV testStrings = [\n ‘’,\n ‘\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ’,\n ‘..1111111111111111111111111111111111111111111111111111111111111117777888’,\n ‘I never give 'em hell, I just tell the truth, and they think it's hell. ’,\n ‘ --- Harry S Truman ’,\n ‘122333444455555666666777777788888888999999999’,\n ‘The better the 4-wheel drive, the further you'll be from help when ya get stuck!’,\n ‘headmistressship’\n]\n\nV testChar = [\n ‘ ’,\n ‘-’,\n ‘7’,\n ‘.’,\n ‘ -r’,\n ‘5’,\n ‘e’,\n ‘s’\n]\n\nL(testNum) 0 .< testStrings.len\n V s = testStrings[testNum]\n L(c) testChar[testNum]\n V result = squeeze(s, c)\n print(\"use: '#.'\\nold: #2 <<<#.>>>\\nnew: #2 <<<#.>>>\\n\".format(c, s.len, s, result.len, result))\n", "language": "11l" }, { "code": "puts:\tequ\t9\n\torg\t100h\n\tjmp\tdemo\n\t;;;\tSqueeze the string at DE on the character in C.\n\t;;;\tThe result is written starting at HL.\nsqueez:\tmvi\tb,'$'\t; Last character seen\n\tdcx\td\t; Move pointer back one item \t\nsqzlp:\tmvi\tm,'$'\t; Stop on end of string\n\tinx \td\t; Increment input pointer\n\tldax\td\t; Grab character from input string\n\tcmp \tm\t; End reached?\n\trz\t\t; Then stop\n\tcmp\tc\t; Was it equal to the character to squeeze?\n\tjnz\tsqzwr\t; If not, then write it to the output\n\tmov\ta,b\t; If so, is the previous character?\n\tcmp\tc\n\tjz\tsqzlp\t; If so, ignore this one\nsqzwr:\tldax\td\t; Retrieve the character again\n\tmov\tm,a\t; It goes in the output\n\tmov\tb,a\t; And it is the last character seen\n\tinx\th\t; Increment output pointer\n\tjmp\tsqzlp\n\t;;;\tPrint the string in DE and character in C as specified,\n\t;;;\tsqueeze the string and print the output.\nprsqz:\tpush\tb\t; Save input parameters\n\tpush\td\n\tmov\ta,c\t; Store character\n\tsta\tchval\n\tlxi\td,chstr\t; Print character\n\tmvi\tc,puts\n\tcall\t5\n\tpop\th\t; Retrieve input string pointer\n\tpush\th\n\tcall\tprbrkt\t; Print the string in brackets\n\tpop\td\t; Retrieve both input parameters\n\tpop \tb\t\n\tlxi\th,buffer\n\tcall\tsqueez\t; Squeeze the input string\n\tlxi\th,buffer\t; ... fall through to print the result\n\t;;;\tWrite the string at HL and its length in brackets\nprbrkt:\tpush\th\t; Keep the pointer\n\tmvi\tb,0FFh\t; Find the length\n\tmvi\ta,'$'\t; End marker\n\tdcx \th\nlscan:\tinr\tb\t; Scan through the string incrementing B\n\tinx\th\t; and HL until the end is found\n\tcmp\tm\n\tjnz\tlscan\n\tmov\ta,b\t; Find high and low digit (assuming < 100)\n\tmvi\tb,'0'-1\npdigit:\tinr\tb\t; B = high digit\n\tsui\t10\n\tjnc\tpdigit\n\tlxi\th,bstart+1\n\tadi\t'0'+10\n\tmov\tm,a\t; Write low digit\n\tdcx\th\n\tmov\tm,b\t; Write high digit\n\txchg\n\tmvi\tc,puts\t; Print length and brackets\n\tcall \t5\n\tpop\td\t; Retrieve the string pointer\n\tmvi\tc,puts\t; Print the string\n\tcall \t5\n\tlxi\td,bend\t; Print the ending brackets\n\tmvi\tc,puts\n\tjmp\t5\n\t;;;\tSqueeze each string by the given character\ndemo:\tlxi\th,list\t; Pointer to start of list\nloop:\tmov\te,m\t; Load pointer and character\n\tinx\th\n\tmov\td,m\n\tinx\th\n\tmov\tc,m\n\tinx\th\n\txra\ta\t; Stop when zero reached\n\tora\tc\n\trz\n\tpush\th\t; Keep list pointer\n\tcall\tprsqz\t; Squeeze and print\n\tpop \th\t; Restore list pointer\n\tjmp \tloop\n\t;;;\tFormatting strings\nchstr:\tdb\t'Character: \"'\nchval:\tdb\t'*\"',13,10,'$'\nbstart:\tdb\t'##<<<$'\nbend:\tdb\t'>>>'\nnl:\tdb\t13,10,'$'\n\t;;;\tInput strings\nstr1: \tdb\t'$'\nstr2:\tdb\t'\"If I were two-faced, would I be wearing'\n\tdb\t' this one?\" --- Abraham Lincoln $'\nstr3:\tdb\t'..11111111111111111111111111111111111111'\n\tdb\t'11111111111111111111111117777888$'\nstr4: \tdb\t'I never give ',39,'em hell, I just tell the t'\n\tdb\t'ruth, and they think it',39,'s hell. $'\nstr5:\tdb\t' '\n\tdb\t' --- Harry S Truman $'\n\t;;;\tPairs of string pointers and characters to squeeze\nlist:\tdw \tstr1\n\tdb \t' '\n\tdw\tstr2\n\tdb \t'-'\n\tdw\tstr3\n\tdb \t'7'\n\tdw\tstr4\n\tdb \t'.'\n\tdw\tstr5\n\tdb \t' '\n\tdw\tstr5\n\tdb \t'-'\n\tdw\tstr5\n\tdb \t'r'\n\tdw\t0\n\tdb \t0\nbuffer:\tequ\t$\n", "language": "8080-Assembly" }, { "code": "PROC Squeeze(CHAR ARRAY in,out CHAR a)\n BYTE i,j\n CHAR c\n\n j=1 c=0\n FOR i=1 TO in(0)\n DO\n IF in(i)#c OR in(i)#a THEN\n c=in(i)\n out(j)=c\n j==+1\n FI\n OD\n out(0)=j-1\nRETURN\n\nPROC Test(CHAR ARRAY s CHAR a)\n CHAR ARRAY c(100)\n BYTE CH=$02FC ;Internal hardware value for last key pressed\n\n Squeeze(s,c,a)\n PrintF(\"Character to squeeze: \"\"%C\"\"%E\",a)\n PrintF(\"<<<%S>>> (len=%B)%E\",s,s(0))\n PrintF(\"<<<%S>>> (len=%B)%E\",c,c(0))\n PutE()\n PrintE(\"Press any key to continue\")\n PutE()\n\n DO UNTIL CH#$FF OD\n CH=$FF\nRETURN\n\nPROC Main()\n Test(\"\",' )\n Test(\"\"\"If I were two-faced, would I be wearing this one?\"\" --- Abraham Lincoln \",'-)\n Test(\"..1111111111111111111111111111111111111111111111111111111111111117777888\",'7)\n Test(\"I never give 'em hell, I just tell the truth, and they think it's hell. \",'.)\n Test(\" --- Harry S Truman \",' )\n Test(\" --- Harry S Truman \",'-)\n Test(\" --- Harry S Truman \",'r)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\nprocedure Test_Squeezable is\n procedure Squeeze (S : in String; C : in Character) is\n Res : String (1 .. S'Length);\n Len : Natural := 0;\n begin\n Put_Line (\"Character to be squeezed: '\" & C & \"'\");\n Put_Line (\"Input = <<<\" & S & \">>>, length =\" & S'Length'Image);\n for I in S'Range loop\n if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then\n Len := Len + 1;\n Res(Len) := S(I);\n end if;\n end loop;\n Put_Line (\"Output = <<<\" & Res (1 .. Len) & \">>>, length =\" & Len'Image);\n end Squeeze;\nbegin\n Squeeze (\"\", ' ');\n Squeeze (\"\"\"If I were two-faced, would I be wearing this one?\"\" --- Abraham Lincoln \", '-');\n Squeeze (\"..1111111111111111111111111111111111111111111111111111111111111117777888\", '7');\n Squeeze (\"I never give 'em hell, I just tell the truth, and they think it's hell. \", '.');\n Squeeze (\" --- Harry S Truman \", ' ');\n Squeeze (\" --- Harry S Truman \", '-');\n Squeeze (\" --- Harry S Truman \", 'r');\nend Test_Squeezable;\n", "language": "Ada" }, { "code": "BEGIN\n # returns a squeezed version of s #\n # i.e. s with adjacent duplicate c characters removed #\n PRIO SQUEEZE = 9;\n OP SQUEEZE = ( STRING s, CHAR c )STRING:\n IF s = \"\"\n THEN \"\" # empty string #\n ELSE # non-empty string #\n [ LWB s : UPB s ]CHAR result;\n INT r pos := LWB result;\n result[ r pos ] := s[ LWB s ];\n FOR s pos FROM LWB s + 1 TO UPB s DO\n IF result[ r pos ] /= s[ s pos ]\n OR result[ r pos ] /= c\n THEN\n r pos +:= 1;\n result[ r pos ] := s[ s pos ]\n FI\n OD;\n result[ LWB result : r pos ]\n FI # SQUEEZE # ;\n # test the SQUEEZE operator #\n PROC test squeeze = ( STRING s, CHAR c )VOID:\n BEGIN\n STRING z = s SQUEEZE c;\n print( ( \"Squeezing \"\"\", c, \"\"\" in \", \"<<<\", s, \">>> (length \", whole( ( UPB s + 1 ) - LWB s, 0 ), \")\", newline ) );\n print( ( \" -> \", \"<<<\", z, \">>> (length \", whole( ( UPB z + 1 ) - LWB z, 0 ), \")\", newline ) )\n END # test squeeze # ;\n # task test cases #\n test squeeze( \"\", \" \" );\n test squeeze( \"\"\"If I were two-faced, would I be wearing this one?\"\" --- Abraham Lincoln \", \"-\" );\n test squeeze( \"..1111111111111111111111111111111111111111111111111111111111111117777888\", \"7\" );\n test squeeze( \"I never give 'em hell, I just tell the truth, and they think it's hell. \", \".\" );\n STRING hst = \" --- Harry S Truman \";\n test squeeze( hst, \" \" );\n test squeeze( hst, \"-\" );\n test squeeze( hst, \"r\" )\nEND\n", "language": "ALGOL-68" }, { "code": "task←{\n ⍝ Squeeze a string\n squeeze ← ⊢(/⍨)≠∨1,1↓⊣≠¯1⌽⊢\n\n ⍝ Display string and length in the manner given in the task\n display ← {(¯2↑⍕≢⍵),' «««',⍵,'»»»'}\n\n ⍝ Squeeze string and display output\n show ← {\n r← ⊂'chr: ''',⍺,''''\n r←r,⊂' in: ',display ⍵\n r←r,⊂'out: ',display ⍺ squeeze ⍵\n ↑r,⊂''\n }\n\n ⍝ Strings from the task\n s1←''\n s2←'\"If I were two-faced, would I be wearing this one?\"'\n s2←s2,' --- Abraham Lincoln '\n s3←'..1111111111111111111111111111111111111111111111111'\n s3←s3,'111111111111117777888'\n s4←'I never give ''em hell, I just tell the truth, and t'\n s4←s4,'hey think it''s hell. '\n s5←' '\n s5←s5,' --- Harry S Truman '\n\n ⎕←' ' show s1\n ⎕←'-' show s2\n ⎕←'7' show s3\n ⎕←'.' show s4\n {⎕←⍵ show s5}¨' -r' ⍝⍝ note use of 'show' here in a lambda (dfn)\n}\n", "language": "APL" }, { "code": "#!/usr/local/bin/apl --script\n\n∇r ← c squeeze s\n s ← 0,s,0\n r ← 1↓¯2↓∊((s≠c)⊂s),¨c\n∇\n\n∇r ← display s\n r ← (¯2↑⍕≢s),' «««',s,'»»»'\n∇\n\n∇r ← c show s\n r ← ⊂ (\"chr: '\",c,\"'\")\n r ← r, ⊂(\" in: \",display s)\n r ← r, ⊂ (\"out: \",display c squeeze s)\n r ← ⊃r\n∇\n\n∇main\n s1←''\n s2←'\"If I were two-faced, would I be wearing this one?\"'\n s2←s2,' --- Abraham Lincoln '\n s3←'..1111111111111111111111111111111111111111111111111'\n s3←s3,'111111111111117777888'\n s4←'I never give ''em hell, I just tell the truth, and t'\n s4←s4,'hey think it''s hell. '\n s5←' '\n s5←s5,' --- Harry S Truman '\n\n ⎕←' ' show s1\n ⎕←'-' show s2\n ⎕←'7' show s3\n ⎕←'.' show s4\n\n ⊃ {⍵ show s5}¨' -r'\n∇\n", "language": "APL" }, { "code": "squeezable_string(str, char){\n for i, ch in StrSplit(str){\n if (ch <> prev) || !InStr(ch, char)\n res .= ch\n prev := ch\n }\n result := \"\n (ltrim\n Original string:`t\" StrLen(str) \" characters`t«««\" str \"»»»\n Squeezable Character «««\" char \"»»»\n Resultant string:`t\" StrLen(res) \" characters`t«««\" res \"»»»\n )\"\n return result\n}\n", "language": "AutoHotkey" }, { "code": "data := [\"\"\n , \"\"\"If I were two-faced, would I be wearing this one?\"\" --- Abraham Lincoln \"\n , \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n , \"I never give 'em hell, I just tell the truth, and they think it's hell. \"]\nchar := [\"\",\"-\",\"7\",\".\"]\nfor i, str in data\n MsgBox % squeezable_string(str, char[i])\n\nstr := \" --- Harry S Truman \"\nfor i, char in [\" \",\"-\",\"r\"]\n MsgBox % squeezable_string(str, char)\nreturn\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f DETERMINE_IF_A_STRING_IS_SQUEEZABLE.AWK\nBEGIN {\n arr[++n] = \"\" ; arr2[n] = \" \"\n arr[++n] = \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \" ; arr2[n] = \"-\"\n arr[++n] = \"..1111111111111111111111111111111111111111111111111111111111111117777888\" ; arr2[n] = \"7\"\n arr[++n] = \"I never give 'em hell, I just tell the truth, and they think it's hell. \" ; arr2[n] = \".\"\n arr[++n] = \" --- Harry S Truman \" ; arr2[n] = \" -r\"\n arr[++n] = \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\" ; arr2[n] = \"e\"\n arr[++n] = \"headmistressship\" ; arr2[n] = \"s\"\n for (i=1; i<=n; i++) {\n for (j=1; j<=length(arr2[i]); j++) {\n main(arr[i],substr(arr2[i],j,1))\n }\n }\n exit(0)\n}\nfunction main(str,chr, c,i,new_str,prev_c) {\n for (i=1; i<=length(str); i++) {\n c = substr(str,i,1)\n if (!(prev_c == c && c == chr)) {\n prev_c = c\n new_str = new_str c\n }\n }\n printf(\"use: '%s'\\n\",chr)\n printf(\"old: %2d <<<%s>>>\\n\",length(str),str)\n printf(\"new: %2d <<<%s>>>\\n\\n\",length(new_str),new_str)\n}\n", "language": "AWK" }, { "code": "10 DEFINT A-Z\n20 READ N: DIM S$(N): FOR I=1 TO N: READ S$(I): NEXT\n30 READ S,C$: IF S=0 THEN END\n40 PRINT \"Character: '\";C$;\"'\"\n50 O$=S$(S): GOSUB 200\n60 I$=S$(S): GOSUB 100: GOSUB 200\n70 PRINT\n80 GOTO 30\n100 REM --\n101 REM -- Squeeze I$ on character C$, output in O$\n102 REM --\n105 O$ = \"\"\n110 X = INSTR(I$,C$)\n120 IF X = 0 THEN O$ = O$ + I$: RETURN\n130 O$ = O$ + LEFT$(I$,X)\n140 FOR X=X TO LEN(I$): IF MID$(I$,X,1) = C$ THEN NEXT\n150 I$ = RIGHT$(I$,LEN(I$)-X+1)\n160 GOTO 110\n200 REM --\n201 REM -- Display O$ and its length in brackets\n202 REM --\n210 PRINT USING \"##\";LEN(O$);\n220 PRINT \"<<<\";O$;\">>>\"\n230 RETURN\n400 REM -- Strings\n410 DATA 5\n415 DATA\"\"\n420 DATA\"'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln \"\n430 DATA\"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n440 DATA\"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n450 DATA\" --- Harry S Truman \"\n500 REM -- String index and character to squeeze\n510 DATA 1,\" \", 2,\"-\", 3,\"7\", 4,\".\", 5,\" \", 5,\"-\", 5,\"r\", 0,\"\"\n", "language": "BASIC" }, { "code": "get \"libhdr\"\n\n// Squeeze a string\nlet squeeze(in, ch, out) = valof\n$( out%0 := 0\n for i=1 to in%0\n if i=1 | in%i~=ch | in%(i-1)~=ch\n $( out%0 := out%0 + 1\n out%(out%0) := in%i\n $)\n resultis out\n$)\n\n// Print string with brackets and length\nlet brackets(s) be\n writef(\"%N: <<<%S>>>*N\", s%0, s)\n\n// Print original and collapsed version\nlet show(s, ch) be\n$( let v = vec 1+255/BYTESPERWORD\n writef(\"Character: '%C'*N\", ch)\n brackets(s)\n brackets(squeeze(s, ch, v))\n wrch('*N')\n$)\n\nlet start() be\n$( let s1=\"\"\n let s2=\"*\"If I were two-faced, would I be wearing this one?*\" --- Abraham Lincoln \"\n let s3=\"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n let s4=\"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n let s5=\" --- Harry S Truman \"\n\n show(s1, ' ')\n show(s2, '-')\n show(s3, '7')\n show(s4, '.')\n show(s5, ' ')\n show(s5, '-')\n show(s5, 'r')\n$)\n", "language": "BCPL" }, { "code": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\n#define COLLAPSE 0\n#define SQUEEZE 1\n\ntypedef struct charList{\n char c;\n struct charList *next;\n} charList;\n\n/*\nImplementing strcmpi, the case insensitive string comparator, as it is not part of the C Standard Library.\n\nComment this out if testing on a compiler where it is already defined.\n*/\n\nint strcmpi(char str1[100],char str2[100]){\n int len1 = strlen(str1), len2 = strlen(str2), i;\n\n if(len1!=len2){\n return 1;\n }\n\n else{\n for(i=0;i<len1;i++){\n if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))\n return 1;\n else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))\n return 1;\n else if(str1[i]!=str2[i])\n return 1;\n }\n }\n\n return 0;\n}\n\ncharList *strToCharList(char* str){\n int len = strlen(str),i;\n\n charList *list, *iterator, *nextChar;\n\n list = (charList*)malloc(sizeof(charList));\n list->c = str[0];\n list->next = NULL;\n\n iterator = list;\n\n for(i=1;i<len;i++){\n nextChar = (charList*)malloc(sizeof(charList));\n nextChar->c = str[i];\n nextChar->next = NULL;\n\n iterator->next = nextChar;\n iterator = nextChar;\n }\n\n return list;\n}\n\nchar* charListToString(charList* list){\n charList* iterator = list;\n int count = 0,i;\n char* str;\n\n while(iterator!=NULL){\n count++;\n iterator = iterator->next;\n }\n\n str = (char*)malloc((count+1)*sizeof(char));\n iterator = list;\n\n for(i=0;i<count;i++){\n str[i] = iterator->c;\n iterator = iterator->next;\n }\n\n free(list);\n str[i] = '\\0';\n\n return str;\n}\n\nchar* processString(char str[100],int operation, char squeezeChar){\n charList *strList = strToCharList(str),*iterator = strList, *scout;\n\n if(operation==SQUEEZE){\n while(iterator!=NULL){\n if(iterator->c==squeezeChar){\n scout = iterator->next;\n\n while(scout!=NULL && scout->c==squeezeChar){\n iterator->next = scout->next;\n scout->next = NULL;\n free(scout);\n scout = iterator->next;\n }\n }\n iterator = iterator->next;\n }\n }\n\n else{\n while(iterator!=NULL && iterator->next!=NULL){\n if(iterator->c == (iterator->next)->c){\n scout = iterator->next;\n squeezeChar = iterator->c;\n\n while(scout!=NULL && scout->c==squeezeChar){\n iterator->next = scout->next;\n scout->next = NULL;\n free(scout);\n scout = iterator->next;\n }\n }\n iterator = iterator->next;\n }\n }\n\n return charListToString(strList);\n}\n\nvoid printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){\n if(operation==SQUEEZE){\n printf(\"Specified Operation : SQUEEZE\\nTarget Character : %c\",squeezeChar);\n }\n\n else\n printf(\"Specified Operation : COLLAPSE\");\n\n printf(\"\\nOriginal %c%c%c%s%c%c%c\\nLength : %d\",174,174,174,originalString,175,175,175,(int)strlen(originalString));\n printf(\"\\nFinal %c%c%c%s%c%c%c\\nLength : %d\\n\",174,174,174,finalString,175,175,175,(int)strlen(finalString));\n}\n\nint main(int argc, char** argv){\n int operation;\n char squeezeChar;\n\n if(argc<3||argc>4){\n printf(\"Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\\n\",argv[0]);\n return 0;\n }\n\n if(strcmpi(argv[1],\"SQUEEZE\")==0 && argc!=4){\n scanf(\"Please enter characted to be squeezed : %c\",&squeezeChar);\n operation = SQUEEZE;\n }\n\n else if(argc==4){\n operation = SQUEEZE;\n squeezeChar = argv[3][0];\n }\n\n else if(strcmpi(argv[1],\"COLLAPSE\")==0){\n operation = COLLAPSE;\n }\n\n if(strlen(argv[2])<2){\n printResults(argv[2],argv[2],operation,squeezeChar);\n }\n\n else{\n printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);\n }\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <algorithm>\n#include <string>\n#include <iostream>\n\ntemplate<typename char_type>\nstd::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {\n auto i = std::unique(str.begin(), str.end(),\n [ch](char_type a, char_type b) { return a == ch && b == ch; });\n str.erase(i, str.end());\n return str;\n}\n\nvoid test(const std::string& str, char ch) {\n std::cout << \"character: '\" << ch << \"'\\n\";\n std::cout << \"original: <<<\" << str << \">>>, length: \" << str.length() << '\\n';\n std::string squeezed(squeeze(str, ch));\n std::cout << \"result: <<<\" << squeezed << \">>>, length: \" << squeezed.length() << '\\n';\n std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n test(\"\", ' ');\n test(\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \", '-');\n test(\"..1111111111111111111111111111111111111111111111111111111111111117777888\", '7');\n test(\"I never give 'em hell, I just tell the truth, and they think it's hell. \", '.');\n std::string truman(\" --- Harry S Truman \");\n test(truman, ' ');\n test(truman, '-');\n test(truman, 'r');\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n static void Main()\n {\n SqueezeAndPrint(\"\", ' ');\n SqueezeAndPrint(\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \", '-');\n SqueezeAndPrint(\"..1111111111111111111111111111111111111111111111111111111111111117777888\", '7');\n SqueezeAndPrint(\"I never give 'em hell, I just tell the truth, and they think it's hell. \", '.');\n string s = \" --- Harry S Truman \";\n SqueezeAndPrint(s, ' ');\n SqueezeAndPrint(s, '-');\n SqueezeAndPrint(s, 'r');\n }\n\n static void SqueezeAndPrint(string s, char c) {\n Console.WriteLine($\"squeeze: '{c}'\");\n Console.WriteLine($\"old: {s.Length} «««{s}»»»\");\n s = Squeeze(s, c);\n Console.WriteLine($\"new: {s.Length} «««{s}»»»\");\n }\n\n static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? \"\" :\n s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray());\n}\n", "language": "C-sharp" }, { "code": "(defn squeeze [s c]\n (let [spans (partition-by #(= c %) s)\n span-out (fn [span]\n (if (= c (first span))\n (str c)\n (apply str span)))]\n (apply str (map span-out spans))))\n\n(defn test-squeeze [s c]\n (let [out (squeeze s c)]\n (println (format \"Input: <<<%s>>> (len %d)\\n\" s (count s))\n (format \"becomes: <<<%s>>> (len %d)\" out (count out)))))\n", "language": "Clojure" }, { "code": "include \"cowgol.coh\";\ninclude \"strings.coh\";\n\nsub squeeze(ch: uint8, str: [uint8], buf: [uint8]): (r: [uint8]) is\n r := buf;\n var prev: uint8 := 0;\n while [str] != 0 loop\n if prev != ch or [str] != ch then\n prev := [str];\n [buf] := prev;\n buf := @next buf;\n end if;\n str := @next str;\n end loop;\n [buf] := 0;\nend sub;\n\nsub squeezeAndPrint(ch: uint8, str: [uint8]) is\n sub bracketLength(str: [uint8]) is\n print_i32(StrLen(str) as uint32);\n print(\" <<<\");\n print(str);\n print(\">>>\\n\");\n end sub;\n\n var buf: uint8[256];\n bracketLength(str);\n bracketLength(squeeze(ch, str, &buf[0]));\n print_nl();\nend sub;\n\nvar strs: [uint8][] := {\n\"\",\n\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n\"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n\"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n\" --- Harry S Truman \"\n};\n\nsqueezeAndPrint(' ', strs[0]);\nsqueezeAndPrint('-', strs[1]);\nsqueezeAndPrint('7', strs[2]);\nsqueezeAndPrint('.', strs[3]);\nsqueezeAndPrint(' ', strs[4]);\nsqueezeAndPrint('-', strs[4]);\nsqueezeAndPrint('r', strs[4]);\n", "language": "Cowgol" }, { "code": "import std.stdio;\n\nvoid squeezable(string s, char rune) {\n writeln(\"squeeze: '\", rune, \"'\");\n writeln(\"old: <<<\", s, \">>>, length = \", s.length);\n\n write(\"new: <<<\");\n char last = '\\0';\n int len = 0;\n foreach (c; s) {\n if (c != last || c != rune) {\n write(c);\n len++;\n }\n last = c;\n }\n writeln(\">>>, length = \", len);\n\n writeln;\n}\n\nvoid main() {\n squeezable(``, ' ');\n squeezable(`\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln `, '-');\n squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');\n squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');\n\n string s = ` --- Harry S Truman `;\n squeezable(s, ' ');\n squeezable(s, '-');\n squeezable(s, 'r');\n}\n", "language": "D" }, { "code": "program Determine_if_a_string_is_squeezable;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils;\n\nvar\n TestStrings: TArray<string> = ['',\n '''If I were two-faced, would I be wearing this one?'' --- Abraham Lincoln ',\n '..1111111111111111111111111111111111111111111111111111111111111117777888',\n 'I never give ''em hell, I just tell the truth, and they think it''s hell. ',\n ' --- Harry S Truman ',\n '122333444455555666666777777788888888999999999',\n 'The better the 4-wheel drive, the further you''ll be from help when ya get stuck!',\n 'headmistressship'];\n TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];\n\nfunction squeeze(s: string; include: char): string;\nbegin\n var sb := TStringBuilder.Create;\n for var i := 1 to s.Length do\n begin\n if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then\n sb.Append(s[i]\n end;\n Result := sb.ToString;\n sb.Free;\nend;\n\nbegin\n for var testNum := 0 to high(TestStrings) do\n begin\n var s := TestStrings[testNum];\n for var c in TestChar[testNum] do\n begin\n var result: string := squeeze(s, c);\n writeln(format('use: \"%s\"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,\n s.Length, s, result.length, result]));\n end;\n end;\n readln;\nend.\n", "language": "Delphi" }, { "code": "func$ squeeze s$ x$ .\n for c$ in strchars s$\n if c$ <> x$ or c$ <> cc$\n r$ &= c$\n .\n cc$ = c$\n .\n return r$\n.\nproc do s$ x$ . .\n print \"'\" & x$ & \"'\"\n print \"«««\" & s$ & \"»»» (\" & len s$ & \")\"\n r$ = squeeze s$ x$\n print \"«««\" & r$ & \"»»» (\" & len r$ & \")\"\n print \"\"\n.\ndo \"\" \" \"\ndo \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \" \"-\"\ndo \"..1111111111111111111111111111111111111111111111111111111111111117777888\" \"7\"\ndo \"I never give 'em hell, I just tell the truth, and they think it's hell. \" \".\"\ndo \" --- Harry S Truman \" \" \"\ndo \" --- Harry S Truman \" \"-\"\ndo \" --- Harry S Truman \" \"r\"\n", "language": "EasyLang" }, { "code": "// Determine if a string is squeezable. Nigel Galloway: June 9th., 2020\nlet squeeze n i=if String.length n=0 then None else\n let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)\n let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)\n if fG.Length=n.Length then None else Some fG\nlet isSqueezable n g=match squeeze n g with\n Some i->printfn \"%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)\" g n n.Length i i.Length\n |_->printfn \"%A does not squeeze <<<%s>>> (length %d)\" g n n.Length\n\nisSqueezable \"\" ' '\nisSqueezable \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \" '-'\nisSqueezable \"..1111111111111111111111111111111111111111111111111111111111111117777888\" '7'\nisSqueezable \"I never give 'em hell, I just tell the truth, and they think it's hell. \" '.'\nlet fN=isSqueezable \" --- Harry S Truman \" in fN ' '; fN '-'; fN 'r'\n", "language": "F-Sharp" }, { "code": "USING: formatting fry io kernel math sbufs sequences strings ;\nIN: rosetta-code.squeeze\n\n: (squeeze) ( str c -- new-str )\n [ unclip-slice 1string >sbuf ] dip\n '[ over last over [ _ = ] both? [ drop ] [ suffix! ] if ]\n reduce >string ;\n\n: squeeze ( str c -- new-str )\n over empty? [ 2drop \"\" ] [ (squeeze) ] if ;\n\n: .str ( str -- ) dup length \"«««%s»»» (length %d)\\n\" printf ;\n\n: show-squeeze ( str c -- )\n dup \"Specified character: '%c'\\n\" printf\n [ \"Before squeeze: \" write drop .str ]\n [ \"After squeeze: \" write squeeze .str ] 2bi nl ;\n\n: squeeze-demo ( -- )\n {\n \"\"\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n } \"\\0-7.\" [ show-squeeze ] 2each\n\n \" --- Harry S Truman \"\n [ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri\n [ show-squeeze ] 2tri@ ;\n\nMAIN: squeeze-demo\n", "language": "Factor" }, { "code": "program main\nimplicit none\ncharacter(len=:),allocatable :: strings(:)\n\nstrings=[ character(len=72) :: &\n'', &\n'\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln', &\n'..1111111111111111111111111111111111111111111111111111111111111117777888', &\n'I never give ''em hell, I just tell the truth, and they think it''s hell.',&\n' --- Harry S Truman' &\n]\n\n call printme( trim(strings(1)), ' ' )\n call printme( strings(2:4), ['-','7','.'] )\n call printme( strings(5), [' ','-','r'] )\n\ncontains\n\nimpure elemental subroutine printme(str,chr)\ncharacter(len=*),intent(in) :: str\ncharacter(len=1),intent(in) :: chr\ncharacter(len=:),allocatable :: answer\n write(*,'(a)')repeat('=',9)\n write(*,'(\"IN: <<<\",g0,\">>>\")')str\n answer=compact(str,chr)\n write(*,'(\"OUT: <<<\",g0,\">>>\")')answer\n write(*,'(\"LENS: \",*(g0,1x))')\"from\",len(str),\"to\",len(answer),\"for a change of\",len(str)-len(answer)\n write(*,'(\"CHAR: \",g0)')chr\nend subroutine printme\n\nelemental function compact(str,charp) result (outstr)\n\ncharacter(len=*),intent(in) :: str\ncharacter(len=1),intent(in) :: charp\ncharacter(len=:),allocatable :: outstr\ncharacter(len=1) :: ch, last_one\ninteger :: i, pio ! position in output\n\n outstr=repeat(' ',len(str)) ! start with a string big enough to hold any output\n if(len(outstr)==0)return ! handle edge condition\n last_one=str(1:1) ! since at least this long start output with first character\n outstr(1:1)=last_one\n pio=1\n\n do i=2,len(str)\n ch=str(i:i)\n pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp) ! decide whether to advance before saving\n outstr(pio:pio)=ch ! store new one or overlay the duplcation\n last_one=ch\n enddo\n\n outstr=outstr(:pio) ! trim the output string to just what was set\nend function compact\n\nend program main\n}\n", "language": "Fortran" }, { "code": "function squeeze(byval s as string,target as string) as string\n dim as string g\n dim as long n\n for n =0 to len(s)-2\n if s[n]=asc(target) then\n if s[n]<>s[n+1] then g+=chr(s[n])\n else\n g+=chr(s[n])\n end if\n next n\n if len(s) then g+=chr(s[n])\n return g\nend function\n\ndim as string z,o\n print \"character \"\" \"\"\"\n o=\"\"\n print \"original \";o;tab(90);\"(\";len(o);\")\"\n z=Squeeze(\"\", \" \")\n print \"squeeze \"; z;tab(90);\"(\";len(z);\")\"\n print\n print \"character \"\"-\"\"\"\n o= \"\"\"If I were two-faced, would I be wearing this one?\"\" --- Abraham Lincoln \"\n print \"original \";o;tab(90);\"(\";len(o);\")\"\n z=Squeeze(o,\"-\")\n print \"squeeze \"; z;tab(90);\"(\";len(z);\")\"\n print\n print \"character \"\"7\"\"\"\n o=\"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n print \"original \";o;tab(90);\"(\";len(o);\")\"\n z=Squeeze(o,\"7\")\n print \"squeeze \"; z;tab(90);\"(\";len(z);\")\"\n print\n print \"character \"\".\"\"\"\n o=\"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n print \"original \";o;tab(90);\"(\";len(o);\")\"\n z=Squeeze(o,\".\")\n print \"squeeze \";z ;tab(90);\"(\";len(z);\")\"\n print\n dim as string s = \" --- Harry S Truman \"\n print \"character \"\" \"\"\"\n o=\" --- Harry S Truman \"\n print \"original \";o;tab(90);\"(\";len(o);\")\"\n z=Squeeze(s, \" \")\n print \"squeeze \";z ;tab(90);\"(\";len(z);\")\"\n print\n print \"character \"\"-\"\"\"\n o=\" --- Harry S Truman \"\n print \"original \";o;tab(90);\"(\";len(o);\")\"\n z=Squeeze(s, \"-\")\n print \"squeeze \"; z;tab(90);\"(\";len(z);\")\"\n print\n print \"character \"\"r\"\"\"\n o=\" --- Harry S Truman \"\n print \"original \";o;tab(90);\"(\";len(o);\")\"\n z=Squeeze(s, \"r\")\n print \"squeeze \"; z;tab(90);\"(\";len(z);\")\"\n sleep\n", "language": "FreeBASIC" }, { "code": "squeeze[str, ch] :=\n{\n println[\"Use: '$ch'\"]\n println[\"old: \" + length[str] + \" <<<$str>>>\"]\n str =~ subst[\"($ch)\\\\1+\", \"$$1\", \"g\"]\n println[\"new: \" + length[str] + \" <<<$str>>>\"]\n}\n\nlines = [[\"\", [\"\"]],\n [\"\"\"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln \"\"\", [\"-\"]],\n[\"..1111111111111111111111111111111111111111111111111111111111111117777888\", [\"7\"]],\n[\"I never give 'em hell, I just tell the truth, and they think it's hell. \", [\".\"]],\n[\" --- Harry S Truman \",[\" \", \"-\", \"r\"]]]\n\nfor [line, chars] = lines\n for char = chars\n println[squeeze[line, char]]\n", "language": "Frink" }, { "code": "package main\n\nimport \"fmt\"\n\n// Returns squeezed string, original and new lengths in\n// unicode code points (not normalized).\nfunc squeeze(s string, c rune) (string, int, int) {\n r := []rune(s)\n le, del := len(r), 0\n for i := le - 2; i >= 0; i-- {\n if r[i] == c && r[i] == r[i+1] {\n copy(r[i:], r[i+1:])\n del++\n }\n }\n if del == 0 {\n return s, le, le\n }\n r = r[:le-del]\n return string(r), le, len(r)\n}\n\nfunc main() {\n strings := []string{\n \"\",\n `\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln `,\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"😍😀🙌💃😍😍😍🙌\",\n }\n chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}\n\n for i, s := range strings {\n for _, c := range chars[i] {\n ss, olen, slen := squeeze(s, c)\n fmt.Printf(\"specified character = %q\\n\", c)\n fmt.Printf(\"original : length = %2d, string = «««%s»»»\\n\", olen, s)\n fmt.Printf(\"squeezed : length = %2d, string = «««%s»»»\\n\\n\", slen, ss)\n }\n }\n}\n", "language": "Go" }, { "code": "class StringSqueezable {\n static void main(String[] args) {\n String[] testStrings = [\n \"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"122333444455555666666777777788888888999999999\",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\"\n ]\n\n String[] testChar = [\" \", \"-\", \"7\", \".\", \" -r\", \"5\", \"e\", \"s\"]\n for (int testNum = 0; testNum < testStrings.length; testNum++) {\n String s = testStrings[testNum]\n for (char c : testChar[testNum].toCharArray()) {\n String result = squeeze(s, c)\n System.out.printf(\"use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n\", c, s.length(), s, result.length(), result)\n }\n }\n }\n\n private static String squeeze(String input, char include) {\n StringBuilder sb = new StringBuilder()\n for (int i = 0; i < input.length(); i++) {\n if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) {\n sb.append(input.charAt(i))\n }\n }\n return sb.toString()\n }\n}\n", "language": "Groovy" }, { "code": "import Text.Printf (printf)\n\ninput :: [(String, Char)]\ninput = [ (\"\", ' ')\n , (\"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\", 'e')\n , (\"headmistressship\", 's')\n , (\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \", '-')\n , (\"..1111111111111111111111111111111111111111111111111111111111111117777888\", '7')\n , (\"I never give 'em hell, I just tell the truth, and they think it's hell. \", '.')\n , (\" --- Harry S Truman \", 'r')\n , (\"aardvark\", 'a')\n , (\"😍😀🙌💃😍😍😍🙌\", '😍')\n ]\n\ncollapse :: Eq a => [a] -> a -> [a]\ncollapse s c = go s\n where go [] = []\n go (x:y:xs)\n | x == y && x == c = go (y:xs)\n | otherwise = x : go (y:xs)\n go xs = xs\n\nmain :: IO ()\nmain =\n mapM_ (\\(a, b, c) -> printf \"squeeze: '%c'\\nold: %3d «««%s»»»\\nnew: %3d «««%s»»»\\n\\n\" c (length a) a (length b) b)\n $ (\\(s, c) -> (s, collapse s c, c)) <$> input\n", "language": "Haskell" }, { "code": " dlb\n}.~ (=&' ' (i.) 0:)\n dtb\n#~ ([: +./\\. ' '&~:)\n deb\n#~ ((+.) (1: |. (> </\\)))@(' '&~:)\n", "language": "J" }, { "code": " 'x' squeeze 'xabxxcxdxxx' NB. example\nxabxcxdx\n\n\n ,.' -7. -r' main&.> <;._2 to_be_squished\n┌──────────────────────────────────────────────────────────────────────────────┐\n│squeeze ' ' reduces the length from 0 to 0 │\n│<<<>>> │\n│<<<>>> │\n├──────────────────────────────────────────────────────────────────────────────┤\n│squeeze '-' reduces the length from 71 to 69 │\n│<<<\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln>>> │\n│<<<\"If I were two-faced, would I be wearing this one?\" - Abraham Lincoln>>> │\n├──────────────────────────────────────────────────────────────────────────────┤\n│squeeze '7' reduces the length from 72 to 69 │\n│<<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>│\n│<<<..1111111111111111111111111111111111111111111111111111111111111117888>>> │\n├──────────────────────────────────────────────────────────────────────────────┤\n│squeeze '.' reduces the length from 71 to 71 │\n│<<<I never give 'em hell, I just tell the truth, and they think it's hell.>>> │\n│<<<I never give 'em hell, I just tell the truth, and they think it's hell.>>> │\n├──────────────────────────────────────────────────────────────────────────────┤\n│squeeze ' ' reduces the length from 70 to 19 │\n│<<< --- Harry S Truman>>> │\n│<<< --- Harry S Truman>>> │\n├──────────────────────────────────────────────────────────────────────────────┤\n│squeeze '-' reduces the length from 70 to 68 │\n│<<< --- Harry S Truman>>> │\n│<<< - Harry S Truman>>> │\n├──────────────────────────────────────────────────────────────────────────────┤\n│squeeze 'r' reduces the length from 70 to 69 │\n│<<< --- Harry S Truman>>> │\n│<<< --- Hary S Truman>>> │\n└──────────────────────────────────────────────────────────────────────────────┘\n", "language": "J" }, { "code": "NB. Note |.!.1 here instead of the APL version's 1 , }. to more elegantly handle the null case in J\nsq =: ] #~ ~: +. _1 |.!.1 ] ~: 1 |. ]\n", "language": "J" }, { "code": "require'format/printf' NB. For formatting the output\n'C I' =: <\"1 |: P =: ; ;\"0 1^:(0<#@[)&.>/\"1 (({.~ ; (}.~>:)) i.&'|')&> LF cut noun define\n|\n-|\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln\n7|..1111111111111111111111111111111111111111111111111111111111111117777888\n.|I never give 'em hell, I just tell the truth, and they think it's hell.\n -r| --- Harry S Truman\n)\nS =: sq&.>/\"1 P\nsmoutput 'chr: ''%s''\\nin: %d «««%s»»»\\nout: %d «««%s»»»\\n' sprintf C ,. (#&.>I),.I ,. (#&.>S),.S\n", "language": "J" }, { "code": "// Title: Determine if a string is squeezable\n\npublic class StringSqueezable {\n\n public static void main(String[] args) {\n String[] testStrings = new String[] {\n \"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"122333444455555666666777777788888888999999999\",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\"};\n\n String[] testChar = new String[] {\n \" \",\n \"-\",\n \"7\",\n \".\",\n \" -r\",\n \"5\",\n \"e\",\n \"s\"};\n for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) {\n String s = testStrings[testNum];\n for ( char c : testChar[testNum].toCharArray() ) {\n String result = squeeze(s, c);\n System.out.printf(\"use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n\", c, s.length(), s, result.length(), result);\n }\n }\n }\n\n private static String squeeze(String in, char include) {\n StringBuilder sb = new StringBuilder();\n for ( int i = 0 ; i < in.length() ; i++ ) {\n if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) {\n sb.append(in.charAt(i));\n }\n }\n return sb.toString();\n }\n\n}\n", "language": "Java" }, { "code": "# Assume $c is specified as a single character correctly\ndef squeeze($c): gsub(\"[\\($c)]+\"; $c);\n\ndef Guillemets: \"«««\\(.)»»»\";\n\ndef Squeeze(s; $c):\n \"Squeeze character: \\($c)\",\n (s | \"Original: \\(Guillemets) has length \\(length)\",\n (squeeze($c) | \"result is \\(Guillemets) with length \\(length)\")),\n \"\";\n", "language": "Jq" }, { "code": " Squeeze(\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"; \"-\"),\n Squeeze (\"..1111111111111111111111111111111111111111111111111111111111111117777888\"; \"7\"),\n Squeeze (\"I never give 'em hell, I just tell the truth, and they think it's hell. \"; \".\"),\n Squeeze (\" --- Harry S Truman \"; \" \"),\n Squeeze (\" --- Harry S Truman \"; \"-\"),\n Squeeze (\" --- Harry S Truman \"; \"r\"),\n\n Squeeze(\"SabcSS:SSdefSSSghSS\";\"S\")\n", "language": "Jq" }, { "code": "Squeeze character: -\nOriginal: «««\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln »»» has length 72\nresult is «««\"If I were two-faced, would I be wearing this one?\" - Abraham Lincoln »»» with length 70\n\nSqueeze character: 7\nOriginal: «««..1111111111111111111111111111111111111111111111111111111111111117777888»»» has length 72\nresult is «««..1111111111111111111111111111111111111111111111111111111111111117888»»» with length 69\n\nSqueeze character: .\nOriginal: «««I never give 'em hell, I just tell the truth, and they think it's hell. »»» has length 72\nresult is «««.»»» with length 1\n\nSqueeze character:\nOriginal: ««« --- Harry S Truman »»» has length 72\nresult is ««« --- Harry S Truman »»» with length 20\n\nSqueeze character: -\nOriginal: ««« --- Harry S Truman »»» has length 72\nresult is ««« - Harry S Truman »»» with length 70\n\nSqueeze character: r\nOriginal: ««« --- Harry S Truman »»» has length 72\nresult is ««« --- Hary S Truman »»» with length 71\n\nSqueeze character: S\nOriginal: «««SabcSS:SSdefSSSghSS»»» has length 19\nresult is «««SabcS:SdefSghS»»» with length 14\n", "language": "Jq" }, { "code": "const teststringpairs = [\n (\"\", ' '),\n (\"\"\"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln \"\"\", '-'),\n (\"..1111111111111111111111111111111111111111111111111111111111111117777888\", '7'),\n (\"\"\"I never give 'em hell, I just tell the truth, and they think it's hell. \"\"\", '.'),\n (\" --- Harry S Truman \", ' '),\n (\" --- Harry S Truman \", '-'),\n (\" --- Harry S Truman \", 'r')]\n\nfunction squeezed(s, c)\n t = isempty(s) ? \"\" : s[1:1]\n for x in s[2:end]\n if x != t[end] || x != c\n t *= x\n end\n end\n t\nend\n\nfor (s, c) in teststringpairs\n n, t = length(s), squeezed(s, c)\n println(\"«««$s»»» (length $n)\\n\",\n s == t ? \"is not squeezed, so remains\" : \"squeezes to\",\n \":\\n«««$t»»» (length $(length(t))).\\n\")\nend\n", "language": "Julia" }, { "code": "fun main() {\n val testStrings = arrayOf(\n \"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"122333444455555666666777777788888888999999999\",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\")\n val testChar = arrayOf(\n \" \",\n \"-\",\n \"7\",\n \".\",\n \" -r\",\n \"5\",\n \"e\",\n \"s\")\n for (testNum in testStrings.indices) {\n val s = testStrings[testNum]\n for (c in testChar[testNum].toCharArray()) {\n val result = squeeze(s, c)\n System.out.printf(\"use: '%c'%nold: %2d &gt;&gt;&gt;%s&lt;&lt;&lt;%nnew: %2d &gt;&gt;&gt;%s&lt;&lt;&lt;%n%n\", c, s.length, s, result.length, result)\n }\n }\n}\n\nprivate fun squeeze(input: String, include: Char): String {\n val sb = StringBuilder()\n for (i in input.indices) {\n if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {\n sb.append(input[i])\n }\n }\n return sb.toString()\n}\n", "language": "Kotlin" }, { "code": "function squeezable(s, rune)\n print(\"squeeze: `\" .. rune .. \"`\")\n print(\"old: <<<\" .. s .. \">>>, length = \" .. string.len(s))\n\n local last = nil\n local le = 0\n io.write(\"new: <<<\")\n for c in s:gmatch\".\" do\n if c ~= last or c ~= rune then\n io.write(c)\n le = le + 1\n end\n last = c\n end\n print(\">>>, length = \" .. le)\n\n print()\nend\n\nfunction main()\n squeezable(\"\", ' ');\n squeezable(\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \", '-')\n squeezable(\"..1111111111111111111111111111111111111111111111111111111111111117777888\", '7')\n squeezable(\"I never give 'em hell, I just tell the truth, and they think it's hell. \", '.')\n\n local s = \" --- Harry S Truman \"\n squeezable(s, ' ')\n squeezable(s, '-')\n squeezable(s, 'r')\nend\n\nmain()\n", "language": "Lua" }, { "code": "ClearAll[Squeeze]\nSqueeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq]\ns={\n \"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln\",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \"\n};\nSqueeze[s[[1]],\"\"]\nSqueeze[s[[2]],\"-\"]\nSqueeze[s[[3]],\"7\"]\nSqueeze[s[[4]],\".\"]\nSqueeze[s[[5]],\" \"]\nSqueeze[s[[5]],\"-\"]\nSqueeze[s[[5]],\"r\"]\n", "language": "Mathematica" }, { "code": "function r = squeezee(s,c)\n ix = [];\n c = unique(c);\n for k=1:length(c)\n ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1];\n end\n r=s;\n r(ix)=[];\n\n fprintf(1,'Character to be squeezed: \"%s\"\\n',c);\n fprintf(1,'Input: <<<%s>>> length: %d\\n',s,length(s));\n fprintf(1,'Output: <<<%s>>> length: %d\\n',r,length(r));\n fprintf(1,'Character to be squeezed: \"%s\"\\n',c);\n\nend\n\n\nsqueezee('', ' ')\nsqueezee('║╚═══════════════════════════════════════════════════════════════════════╗', '-')\nsqueezee('║\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ║', '7')\nsqueezee('║..1111111111111111111111111111111111111111111111111111111111111117777888║', '.')\nsqueezee('║I never give ''em hell, I just tell the truth, and they think it''s hell. ║', '.')\nsqueezee('║ --- Harry S Truman ║', '.')\nsqueezee('║ --- Harry S Truman ║', '-')\nsqueezee('║ --- Harry S Truman ║', 'r')\n", "language": "MATLAB" }, { "code": "to-report split [ string ]\n ;; utility reporter to split a string into a list\n report n-values length string [ [ n ] -> item n string ]\nend\n\nto-report squeeze [ character string ]\n ;; reporter that actually does the squeeze function\n ;; remote immeadiately repeating instances of character from string\n ifelse ( string = \"\" )\n [ report \"\" ] ;; empty input, report empty output\n [ report\n reduce\n [ [ a b ] ->\n ( word a\n ifelse-value b = character and b = last a\n [ \"\" ]\n [ b ]\n )\n ]\n split string\n ]\nend\n\nto-report bracket [ string ]\n ;; utility reporter to enclose a string in brackets\n report ( word \"<<<\" string \">>>\" )\nend\n\nto-report format [ string ]\n ;; utility reporter to format the output as required\n report ( word bracket string \" \" length string )\nend\n\nto demo-squeeze [ character string ]\n ;; procedure to display the required output\n output-print bracket character\n output-print format string\n output-print format squeeze character string\nend\n\nto demo\n ;; procedure to perform the test cases\n demo-squeeze \" \" \"\"\n demo-squeeze \"-\" \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"\n demo-squeeze \"7\" \"..1111111111111111111111111111111111111111111111111111111111111117777888\"\n demo-squeeze \".\" \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n demo-squeeze \" \" \" --- Harry S Truman \"\n demo-squeeze \"-\" \" --- Harry S Truman \"\n demo-squeeze \"r\" \" --- Harry S Truman \"\nend\n", "language": "NetLogo" }, { "code": "import unicode, strformat\n\nproc squeeze(s: string; ch: Rune) =\n echo fmt\"Specified character: '{ch}'\"\n let original = s.toRunes\n echo fmt\"Original: length = {original.len}, string = «««{s}»»»\"\n var previous = Rune(0)\n var squeezed: seq[Rune]\n for rune in original:\n if rune != previous:\n squeezed.add(rune)\n previous = rune\n elif rune != ch:\n squeezed.add(rune)\n echo fmt\"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»\"\n echo \"\"\n\n\nconst Strings = [\"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"😍😀🙌💃😍😍😍🙌\",]\n\nconst Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],\n @[Rune(' '), Rune('-'), Rune('r')],\n @[Rune('e')], @[Rune('s')], @[Rune('a')], \"😍\".toRunes]\n\n\nfor i, s in Strings:\n for ch in Chars[i]:\n s.squeeze(ch)\n", "language": "Nim" }, { "code": "use strict;\nuse warnings;\nuse Unicode::UCD 'charinfo';\n\nfor (\n ['', ' '],\n ['\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ', '-'],\n ['..1111111111111111111111111111111111111111111111111111111111111117777888', '7'],\n [\"I never give 'em hell, I just tell the truth, and they think it's hell. \", '.'],\n [' --- Harry S Truman ', ' '],\n [' --- Harry S Truman ', '-'],\n [' --- Harry S Truman ', 'r']\n) {\n my($phrase,$char) = @$_;\n (my $squeeze = $phrase) =~ s/([$char])\\1+/$1/g;\n printf \"\\nOriginal length: %d <<<%s>>>\\nSqueezable on \\\"%s\\\": %s\\nSqueezed length: %d <<<%s>>>\\n\",\n length($phrase), $phrase,\n charinfo(ord $char)->{'name'},\n $phrase ne $squeeze ? 'True' : 'False',\n length($squeeze), $squeeze\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">`\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln `</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"-\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"..1111111111111111111111111111111111111111111111111111111111111117777888\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"7\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\"I never give 'em hell, I just tell the truth, and they think it's hell. \"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\".\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #008000;\">\" --- Harry S Truman \"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" -r\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #000000;\">fmt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"\"\n length %2d input: &lt;&lt;&lt;%s&gt;&gt;&gt;\n length %2d squeeze(%c): &lt;&lt;&lt;%s&gt;&gt;&gt;\n \"\"\"</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">squeeze</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)></span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">outdx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">prev</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #000000;\">prev</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">prev</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">ch</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">prev</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">outdx</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">outdx</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">prev</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">outdx</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">s</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">ti</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">chars</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">chars</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">si</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">squeeze</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">chars</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">fmt</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">chars</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">si</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\n\nfunction squeezeString($string, $squeezeChar) {\n $previousChar = null;\n $squeeze = '';\n $charArray = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);\n for ($i = 0 ; $i < count($charArray) ; $i++) {\n $currentChar = $charArray[$i];\n if ($previousChar !== $currentChar || $currentChar !== $squeezeChar) {\n $squeeze .= $charArray[$i];\n }\n $previousChar = $currentChar;\n }\n return $squeeze;\n}\n\nfunction isSqueezable($string, $squeezeChar) {\n return ($string !== squeezeString($string, $squeezeChar));\n}\n\n$strings = array(\n ['-', '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln '],\n ['1', '..1111111111111111111111111111111111111111111111111111111111111117777888'],\n ['l', \"I never give 'em hell, I just tell the truth, and they think it's hell. \"],\n [' ', ' --- Harry S Truman '],\n ['9', '0112223333444445555556666666777777778888888889999999999'],\n ['e', \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\"],\n ['k', \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\"],\n);\nforeach ($strings as $params) {\n list($char, $original) = $params;\n echo 'Original : <<<', $original, '>>> (len=', mb_strlen($original), ')', PHP_EOL;\n if (isSqueezable($original, $char)) {\n $squeeze = squeezeString($original, $char);\n echo 'Squeeze(', $char, ') : <<<', $squeeze, '>>> (len=', mb_strlen($squeeze), ')', PHP_EOL, PHP_EOL;\n } else {\n echo 'Squeeze(', $char, ') : string is not squeezable (char=', $char, ')...', PHP_EOL, PHP_EOL;\n }\n}\n", "language": "PHP" }, { "code": "squeeze_( [], _, [] ).\nsqueeze_( [A], _, [A] ).\nsqueeze_( [A,A|T], A, R ) :- squeeze_( [A|T], A, R ).\nsqueeze_( [A,A|T], B, [A|R] ) :- dif( A, B ), squeeze_( [A|T], B, R ).\nsqueeze_( [A,B|T], S, [A|R] ) :- dif( A, B ), squeeze_( [B|T], S, R ).\n\nsqueeze( Str, SqueezeChar, Collapsed ) :-\n string_chars( Str, Chars ),\n squeeze_( Chars, SqueezeChar, Result ),\n string_chars( Collapsed, Result ).\n", "language": "Prolog" }, { "code": "from itertools import groupby\n\ndef squeezer(s, txt):\n return ''.join(item if item == s else ''.join(grp)\n for item, grp in groupby(txt))\n\nif __name__ == '__main__':\n strings = [\n \"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"😍😀🙌💃😍😍😍🙌\",\n ]\n squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',')\n for txt, chars in zip(strings, squeezers):\n this = \"Original\"\n print(f\"\\n{this:14} Size: {len(txt)} «««{txt}»»»\" )\n for ch in chars:\n this = f\"Squeezer '{ch}'\"\n sqz = squeezer(ch, txt)\n print(f\"{this:>14} Size: {len(sqz)} «««{sqz}»»»\" )\n", "language": "Python" }, { "code": "squeeze_string <- function(string, character){\n\n str_iterable <- strsplit(string, \"\")[[1]]\n\n message(paste0(\"Original String: \", \"<<<\", string, \">>>\\n\",\n \"Length: \", length(str_iterable), \"\\n\",\n \"Character: \", character))\n\n detect <- rep(TRUE, length(str_iterable))\n\n\n for(i in 2:length(str_iterable)){\n\n if(length(str_iterable) == 0) break\n if(str_iterable[i] != character) next\n\n if(str_iterable[i] == str_iterable[i-1])\n\n detect[i] <- FALSE\n }\n\n squeezed_string <- paste(str_iterable[detect], collapse = \"\")\n\n message(paste0(\"squeezed string: \", \"<<<\",squeezed_string, \">>>\\n\",\n \"Length: \", length(str_iterable[detect])), \"\\n\")\n\n }\n\n\n squeeze_string(\"\", \" \")\n squeeze_string(\"'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln \", \"-\")\n squeeze_string(\"..1111111111111111111111111111111111111111111111111111111111111117777888\", \"7\")\n squeeze_string(\"I never give 'em hell, I just tell the truth, and they think it's hell. \", \".\")\n squeeze_string(\" --- Harry S Truman \", \" \")\n squeeze_string(\" --- Harry S Truman \", \"-\")\n squeeze_string(\" --- Harry S Truman \", \"r\")\n squeeze_string(\" Ciao Mamma, guarda come mi diverto!!! \", \"!\")\n", "language": "R" }, { "code": "#lang racket/base\n\n(define (squeeze-string s c)\n (let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))\n (cond [(null? cs) (values l (list->string (reverse acc)))]\n [(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]\n [else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))\n\n(define (report-squeeze s c)\n (define-values (l′ s′) (squeeze-string s c))\n (printf \"Squeezing ~s in «««~a»»» (length ~a)~%\" c s (string-length s))\n (printf \"Result: «««~a»»» (length ~a)~%~%\" s′ l′))\n\n(define (Determine-if-a-string-is-squeezeable)\n (report-squeeze \"\" #\\space)\n (report-squeeze \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \" #\\-)\n (report-squeeze \"..1111111111111111111111111111111111111111111111111111111111111117777888\" #\\7)\n (report-squeeze \"I never give 'em hell, I just tell the truth, and they think it's hell. \" #\\.)\n (define truman-sig \" --- Harry S Truman \")\n (report-squeeze truman-sig #\\space)\n (report-squeeze truman-sig #\\-)\n (report-squeeze truman-sig #\\r))\n\n(module+ main\n (Determine-if-a-string-is-squeezeable))\n", "language": "Racket" }, { "code": "map {\n my $squeeze = $^phrase;\n sink $^reg;\n $squeeze ~~ s:g/($reg)$0+/$0/;\n printf \"\\nOriginal length: %d <<<%s>>>\\nSqueezable on \\\"%s\\\": %s\\nSqueezed length: %d <<<%s>>>\\n\",\n $phrase.chars, $phrase, $reg.uniname, $phrase ne $squeeze, $squeeze.chars, $squeeze\n},\n '', ' ',\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ', '-',\n '..1111111111111111111111111111111111111111111111111111111111111117777888', '7',\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \", '.',\n ' --- Harry S Truman ', ' ',\n ' --- Harry S Truman ', '-',\n ' --- Harry S Truman ', 'r'\n", "language": "Raku" }, { "code": "/*REXX program \"squeezes\" all immediately repeated characters in a string (or strings). */\n@.= /*define a default for the @. array. */\n#.1= ' '; @.1=\n#.2= '-'; @.2= '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln '\n#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888\n#.4= . ; @.4= \"I never give 'em hell, I just tell the truth, and they think it's hell. \"\n#.5= ' '; @.5= ' --- Harry S Truman '\n#.6= '-'; @.6= @.5\n#.7= 'r'; @.7= @.5\n\n do j=1; L= length(@.j) /*obtain the length of an array element*/\n say copies('═', 105) /*show a separator line between outputs*/\n if j>1 & L==0 then leave /*if arg is null and J>1, then leave. */\n say ' specified immediate repeatable character=' #.j \" ('\"c2x(#.j)\"'x)\"\n say ' length='right(L, 3) \" input=«««\" || @.j || '»»»'\n new= squeeze(@.j, #.j)\n w= length(new)\n say ' length='right(w, 3) \" output=«««\" || new || '»»»'\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsqueeze: procedure; parse arg y 1 $ 2,z /*get string; get immed. repeated char.*/\n if pos(z || z, y)==0 then return y /*No repeated immediate char? Return Y*/\n /* [↑] Not really needed; a speed─up.*/\n do k=2 to length(y) /*traipse through almost all the chars.*/\n _= substr(y, k, 1) /*pick a character from Y */\n if _==right($, 1) & _==z then iterate /*Same character? Skip it.*/\n $= $ || _ /*append char., it's diff. */\n end /*j*/\n return $\n", "language": "REXX" }, { "code": "strings = [\"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"😍😀🙌💃😍😍😍🙌\",]\nsqueeze_these = [\"\", \"-\", \"7\", \".\", \" -r\", \"😍\"]\n\nstrings.zip(squeeze_these).each do |str, st|\n puts \"original: «««#{str}»»» (size #{str.size})\"\n st.chars.each do |c|\n ssq = str.squeeze(c)\n puts \"#{c.inspect}-squeezed: «««#{ssq}»»» (size #{ssq.size})\"\n end\n puts\nend\n", "language": "Ruby" }, { "code": "fn squeezable_string<'a>(s: &'a str, squeezable: char) -> impl Iterator<Item = char> + 'a {\n let mut previous = None;\n\n s.chars().filter(move |c| match previous {\n Some(p) if p == squeezable && p == *c => false,\n _ => {\n previous = Some(*c);\n true\n }\n })\n}\n\nfn main() {\n fn show(input: &str, c: char) {\n println!(\"Squeeze: '{}'\", c);\n println!(\"Input ({} chars): \\t{}\", input.chars().count(), input);\n let output: String = squeezable_string(input, c).collect();\n println!(\"Output ({} chars): \\t{}\", output.chars().count(), output);\n println!();\n }\n\n let harry = r#\"I never give 'em hell, I just tell the truth, and they think it's hell.\n --- Harry S Truman\"#;\n\n #[rustfmt::skip]\n let inputs = [\n (\"\", ' '),\n (r#\"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln \"#, '-'),\n (\"..1111111111111111111111111111111111111111111111111111111111111117777888\", '7'),\n (harry, ' '),\n (harry, '-'),\n (harry, 'r'),\n (\"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\", 'e'),\n (\"headmistressship\", 's'),\n ];\n\n inputs.iter().for_each(|(input, c)| show(input, *c));\n}\n", "language": "Rust" }, { "code": "func squeeze(str, c) {\n str.gsub(Regex(\"(\" + c.escape + \")\" + '\\1+'), {|s1| s1 })\n}\n\nvar strings = [\"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"😍😀🙌💃😍😍😍🙌\"]\n\nvar squeeze_these = [\"\", \"-\", \"7\", \".\", \" -r\", \"😍\"]\n\n[strings, squeeze_these].zip {|str,st|\n say \" original: «««#{str}»»» (length: #{str.len})\"\n st.each {|c|\n var ssq = squeeze(str, c)\n say \"'#{c}'-squeezed: «««#{ssq}»»» (length: #{ssq.len})\"\n }\n say ''\n}\n", "language": "Sidef" }, { "code": "# Set test data as a list pairing even and odd values\n# as test string and squeeze character(s) respectively.\nset test {\n {} {\" \"}\n {\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln } {\"-\"}\n {..1111111111111111111111111111111111111111111111111111111111111117777888} {\"7\"}\n {I never give 'em hell, I just tell the truth, and they think it's hell. } {\".\"} ;# '\n { --- Harry S Truman } {\" \" \"-\" \"r\"}\n {The better the 4-wheel drive, the further you'll be from help when ya get stuck!} {\"e\"} ;# '\n {headmistressship} {\"s\"}\n}\n\nforeach {str chrs} $test {\n foreach c $chrs {\n # Escape non-word replacement characters (such as .)\n set c [regsub -all {\\W} $c {\\\\&}]\n\n # Uses regexp lookbehind to detect repeated characters\n set re [subst -noback {($c)(\\1+)}] ;# build expression\n set sub [regsub -all $re $str {\\1}]\n\n # Output\n puts [format \"Original (length %3d): %s\" [string length $str] $str]\n puts [format \"Subbed (length %3d): %s\" [string length $sub] $sub]\n puts ----------------------\n }\n}\n", "language": "Tcl" }, { "code": "// Returns squeezed string, original and new lengths in\n// unicode code points (not normalized).\nfn squeeze(s string, c string) (string, int, int) {\n mut r := s.runes()\n mut t := c.runes()[0]\n le, mut del := r.len, 0\n for i := le - 2; i >= 0; i-- {\n if r[i] == t && r[i] == r[i+1] {\n r.delete(i)\n del++\n }\n }\n if del == 0 {\n return s, le, le\n }\n r = r[..le-del]\n return r.string(), le, r.len\n}\n\nfn main() {\n strings := [\n \"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"😍😀🙌💃😍😍😍🙌\",\n\t]\n chars := [[' '], ['-'], ['7'], ['.'], [' ', '-', 'r'], ['e'], ['s'], ['a'], ['😍']]\n\n for i, s in strings {\n for c in chars[i] {\n ss, olen, slen := squeeze(s, c)\n println(\"specified character = $c\")\n println(\"original : length = ${olen:2}, string = «««$s»»»\")\n println(\"squeezed : length = ${slen:2}, string = «««$ss»»»\\n\")\n }\n }\n}\n", "language": "V-(Vlang)" }, { "code": "Imports System.Linq.Enumerable\n\nModule Module1\n\n Function Squeeze(s As String, c As Char) As String\n If String.IsNullOrEmpty(s) Then\n Return \"\"\n End If\n Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray())\n End Function\n\n Sub SqueezeAndPrint(s As String, c As Char)\n Console.WriteLine(\"squeeze: '{0}'\", c)\n Console.WriteLine(\"old: {0} «««{1}»»»\", s.Length, s)\n s = Squeeze(s, c)\n Console.WriteLine(\"new: {0} «««{1}»»»\", s.Length, s)\n End Sub\n\n Sub Main()\n Const QUOTE = \"\"\"\"\n\n SqueezeAndPrint(\"\", \" \")\n SqueezeAndPrint(QUOTE & \"If I were two-faced, would I be wearing this one?\" & QUOTE & \" --- Abraham Lincoln \", \"-\")\n SqueezeAndPrint(\"..1111111111111111111111111111111111111111111111111111111111111117777888\", \"7\")\n SqueezeAndPrint(\"I never give 'em hell, I just tell the truth, and they think it's hell. \", \".\")\n\n Dim s = \" --- Harry S Truman \"\n SqueezeAndPrint(s, \" \")\n SqueezeAndPrint(s, \"-\")\n SqueezeAndPrint(s, \"r\")\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./fmt\" for Fmt\n\n// Returns squeezed string, original and new lengths in\n// unicode code points (not normalized).\nvar squeeze = Fn.new { |s, ch|\n var c = s.codePoints.toList\n var le = c.count\n if (le < 2) return [s, le, le]\n for (i in le-2..0) {\n if (c[i] == ch.codePoints[0] && c[i] == c[i+1]) c.removeAt(i)\n }\n var cc = c.reduce(\"\") { |acc, cp| acc + String.fromCodePoint(cp) }\n return [cc, le, cc.count]\n}\n\nvar strings = [\n \"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"😍😀🙌💃😍😍😍🙌\"\n]\n\nvar chars = [ [\" \"], [\"-\"], [\"7\"], [\".\"], [\" \", \"-\", \"r\"], [\"e\"], [\"s\"], [\"a\"], [\"😍\"] ]\n\nvar i = 0\nfor (s in strings) {\n for (ch in chars[i]) {\n var r = squeeze.call(s, ch)\n System.print(\"Specified character = '%(ch)'\")\n System.print(\"original : length = %(Fmt.d(2, r[1])), string = «««%(s)»»»\")\n System.print(\"squeezed : length = %(Fmt.d(2, r[2])), string = «««%(r[0])»»»\\n\")\n }\n i = i + 1\n}\n", "language": "Wren" }, { "code": "string 0;\nchar C, I, J, Last;\n\nproc Squeeze(Char, S); \\Eliminate specified repeated characters from string\nchar Char, S;\n[I:= 0; J:= 0; Last:= -1;\nloop [if S(I) # Last or Char # Last then\n [C(J):= S(I);\n if S(I) = 0 then quit;\n J:= J+1;\n ];\n Last:= S(I);\n I:= I+1;\n ];\n];\n\nint String, K, Char;\n[String:= [\n \"\",\n \"^\"If I were two-faced, would I be wearing this one?^\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \"];\nChar:= [0, ^-, ^1, ^l, ^ , ^-, ^r];\nC:= Reserve(79+1); \\space for collapsed string\nfor K:= 0 to 4+2 do\n [Squeeze(Char(K), String(if K>4 then 4 else K));\n Text(0, \"<<<\"); Text(0, String(if K>4 then 4 else K)); Text(0, \">>> \");\n IntOut(0, I); CrLf(0);\n Text(0, \"<<<\"); Text(0, C); Text(0, \">>> \"); IntOut(0, J); CrLf(0);\n ];\n]\n", "language": "XPL0" }, { "code": "fcn squeeze(c,str){ // Works with UTF-8\n s,cc,sz,n := Data(Void,str), String(c,c), c.len(), 0; // byte buffer in case of LOTs of deletes\n while(Void != (n=s.find(cc,n))){ str=s.del(n,sz) } // and searching is faster for big strings\n s.text\n}\n", "language": "Zkl" }, { "code": "strings:=T(\nT(\"\",\"\"),\nT(\"-\",\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \"),\nT(\"7\",\"..1111111111111111111111111111111111111111111111111111111111111117777888\"),\nT(\" \",\"I never give 'em hell, I just tell the truth, and they think it's hell. \"),\nT(\" \",\" --- Harry S Truman \"),\nT(\"-\",\" --- Harry S Truman \"),\nT(\"r\",\" --- Harry S Truman \"),\nT(\"e\",\"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\"),\nT(\"s\",\"headmistressship\"),\nT(\"\\Ubd;\",\"\\Ubc;\\Ubd;\\Ubd;\\Ube;\"),\n);\n\nforeach c,s in (strings){\n println(\"Squeeze: \\\"\",c,\"\\\"\");\n println(\"Before: %2d <<<%s>>>\".fmt(s.len(-8),s));\n sstr:=squeeze(c,s);\n println(\"After: %2d <<<%s>>>\\n\".fmt(sstr.len(-8),sstr));\n}\n", "language": "Zkl" } ]
Determine-if-a-string-is-squeezable
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running\nnote: Programming environment operations\n", "language": "00-META" }, { "code": "This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.\n\n", "language": "00-TASK" }, { "code": "with Ada.Text_IO;\n\nprocedure Single_Instance is\n\n package IO renames Ada.Text_IO;\n Lock_File: IO.File_Type;\n Lock_File_Name: String := \"single_instance.magic_lock\";\n\nbegin\n begin\n IO.Open(File => Lock_File, Mode=> IO.In_File, Name => Lock_File_Name);\n IO.Close(Lock_File);\n IO.Put_Line(\"I can't -- another instance of me is running ...\");\n exception\n when IO.Name_Error =>\n IO.Put_Line(\"I can run!\");\n IO.Create(File => Lock_File, Name => Lock_File_Name);\n for I in 1 .. 10 loop\n IO.Put(Integer'Image(I));\n delay 1.0; -- wait one second\n end loop;\n IO.Delete(Lock_File);\n IO.New_Line;\n IO.Put_Line(\"I am done!\");\n end;\nexception\n when others => IO.Delete(Lock_File);\nend Single_Instance;\n", "language": "Ada" }, { "code": "PRAGMA INCLUDE <sys/file.h>\nOPTION DEVICE O_NONBLOCK\n\nOPEN ME$ FOR DEVICE AS me\n\nIF flock(me, LOCK_EX | LOCK_NB) <> 0 THEN\n PRINT \"I am already running, exiting...\"\n END\nENDIF\n\nPRINT \"Running this program, doing things...\"\nSLEEP 5000\n\nCLOSE DEVICE me\n", "language": "BaCon" }, { "code": " SYS \"CreateMutex\", 0, 1, \"UniqueLockName\" TO Mutex%\n SYS \"GetLastError\" TO lerr%\n IF lerr% = 183 THEN\n SYS \"CloseHandle\", Mutex%\n SYS \"MessageBox\", @hwnd%, \"I am already running\", 0, 0\n QUIT\n ENDIF\n\n SYS \"ReleaseMutex\", Mutex%\n SYS \"CloseHandle\", Mutex%\n END\n", "language": "BBC-BASIC" }, { "code": "#include <fcntl.h>\t/* fcntl, open */\n#include <stdlib.h>\t/* atexit, getenv, malloc */\n#include <stdio.h>\t/* fputs, printf, puts, snprintf */\n#include <string.h>\t/* memcpy */\n#include <unistd.h>\t/* sleep, unlink */\n\n/* Filename for only_one_instance() lock. */\n#define INSTANCE_LOCK \"rosetta-code-lock\"\n\nvoid\nfail(const char *message)\n{\n\tperror(message);\n\texit(1);\n}\n\n/* Path to only_one_instance() lock. */\nstatic char *ooi_path;\n\nvoid\nooi_unlink(void)\n{\n\tunlink(ooi_path);\n}\n\n/* Exit if another instance of this program is running. */\nvoid\nonly_one_instance(void)\n{\n\tstruct flock fl;\n\tsize_t dirlen;\n\tint fd;\n\tchar *dir;\n\n\t/*\n\t * Place the lock in the home directory of this user;\n\t * therefore we only check for other instances by the same\n\t * user (and the user can trick us by changing HOME).\n\t */\n\tdir = getenv(\"HOME\");\n\tif (dir == NULL || dir[0] != '/') {\n\t\tfputs(\"Bad home directory.\\n\", stderr);\n\t\texit(1);\n\t}\n\tdirlen = strlen(dir);\n\n\tooi_path = malloc(dirlen + sizeof(\"/\" INSTANCE_LOCK));\n\tif (ooi_path == NULL)\n\t\tfail(\"malloc\");\n\tmemcpy(ooi_path, dir, dirlen);\n\tmemcpy(ooi_path + dirlen, \"/\" INSTANCE_LOCK,\n\t sizeof(\"/\" INSTANCE_LOCK)); /* copies '\\0' */\n\n\tfd = open(ooi_path, O_RDWR | O_CREAT, 0600);\n\tif (fd < 0)\n\t\tfail(ooi_path);\n\n\tfl.l_start = 0;\n\tfl.l_len = 0;\n\tfl.l_type = F_WRLCK;\n\tfl.l_whence = SEEK_SET;\n\tif (fcntl(fd, F_SETLK, &fl) < 0) {\n\t\tfputs(\"Another instance of this program is running.\\n\",\n\t\t stderr);\n\t\texit(1);\n\t}\n\n\t/*\n\t * Run unlink(ooi_path) when the program exits. The program\n\t * always releases locks when it exits.\n\t */\n\tatexit(ooi_unlink);\n}\n\n/*\n * Demo for Rosetta Code.\n * http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running\n */\nint\nmain()\n{\n\tint i;\n\n\tonly_one_instance();\n\n\t/* Play for 10 seconds. */\n\tfor(i = 10; i > 0; i--) {\n\t\tprintf(\"%d...%s\", i, i % 5 == 1 ? \"\\n\" : \" \");\n\t\tfflush(stdout);\n\t\tsleep(1);\n\t}\n\tputs(\"Fin!\");\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <fcntl.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n/* unistd for sleep */\n\nvoid sigint_handler(int sig)\n{\n fprintf(stderr, \"Caught signal %d.\\n\", sig);\n unlink(\"/tmp/MyUniqueName\");\n /* exit() is not safe in a signal handler, use _exit() */\n _exit(1);\n}\n\nint main()\n{\n struct sigaction act;\n int myfd;\n\n myfd = open(\"/tmp/MyUniqueName\", O_CREAT|O_EXCL);\n if ( myfd < 0 )\n {\n fprintf(stderr, \"I am already running!\\n\");\n exit(1);\n }\n act.sa_handler = sigint_handler;\n sigemptyset(&act.sa_mask);\n act.sa_flags = 0;\n sigaction(SIGINT, &act, NULL);\n /* here the real code of the app*/\n sleep(20);\n /* end of the app */\n unlink(\"/tmp/MyUniqueName\"); close(myfd);\n return 0;\n}\n", "language": "C" }, { "code": "#include <afx.h>\n", "language": "C++" }, { "code": "HANDLE mutex;\n", "language": "C++" }, { "code": "mutex = CreateMutex( NULL, TRUE, \"MyApp\" );\nif ( GetLastError() == ERROR_ALREADY_EXISTS )\n{\n // There's another instance running. What do you do?\n}\n", "language": "C++" }, { "code": "CloseHandle( mutex );\n", "language": "C++" }, { "code": "using System;\nusing System.Net;\nusing System.Net.Sockets;\n\nclass Program {\n static void Main(string[] args) {\n try {\n TcpListener server = new TcpListener(IPAddress.Any, 12345);\n server.Start();\n }\n\n catch (SocketException e) {\n if (e.SocketErrorCode == SocketError.AddressAlreadyInUse) {\n Console.Error.WriteLine(\"Already running.\");\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "// Use this class in your process to guard against multiple instances\n//\n// This is valid for C# running on Windows, but not for C# with Linux.\n//\nusing System;\nusing System.Threading;\n\n/// <summary>\n/// RunOnce should be instantiated in the calling processes main clause\n/// (preferably using a \"using\" clause) and then calling process\n/// should then check AlreadyRunning and do whatever is appropriate\n/// </summary>\npublic class RunOnce : IDisposable\n{\n\tpublic RunOnce( string name )\n\t{\n\t\tm_name = name;\n\t\tAlreadyRunning = false;\n\n\t\tbool created_new = false;\n\n\t\tm_mutex = new Mutex( false, m_name, out created_new );\n\n\t\tAlreadyRunning = !created_new;\n\t}\n\n\t~RunOnce()\n\t{\n\t\tDisposeImpl( false );\n\t}\n\n\tpublic bool AlreadyRunning\n\t{\n\t\tget { return m_already_running; }\n\t\tprivate set { m_already_running = value; }\n\t}\n\n\tprivate void DisposeImpl( bool is_disposing )\n\t{\n\t\tGC.SuppressFinalize( this );\n\n\t\tif( is_disposing )\n\t\t{\n\t\t\tm_mutex.Close();\n\t\t}\n\t}\n\n\t#region IDisposable Members\n\n\tpublic void Dispose()\n\t{\n\t\tDisposeImpl( true );\n\t}\n\n\t#endregion\n\n\tprivate string m_name;\n\tprivate bool m_already_running;\n\tprivate Mutex m_mutex;\n}\n\nclass Program\n{\n // Example code to use this\n static void Main( string[] args )\n {\n using ( RunOnce ro = new RunOnce( \"App Name\" ) )\n {\n if ( ro.AlreadyRunning )\n {\n Console.WriteLine( \"Already running\" );\n return;\n }\n\n // Program logic\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(import (java.net ServerSocket InetAddress))\n\n(def *port* 12345) ; random large port number\n(try (new ServerSocket *port* 10 (. InetAddress getLocalHost))\n (catch IOException e (System/exit 0))) ; port taken, so app is already running\n", "language": "Clojure" }, { "code": "bool is_unique_instance()\n{\n import std.socket;\n auto socket = new Socket(AddressFamily.UNIX, SocketType.STREAM);\n auto addr = new UnixAddress(\"\\0/tmp/myapp.uniqueness.sock\");\n try\n {\n socket.bind(addr);\n return true;\n }\n catch (SocketOSException e)\n {\n import core.stdc.errno : EADDRINUSE;\n\n if (e.errorCode == EADDRINUSE)\n return false;\n else\n throw e;\n }\n}\n", "language": "D" }, { "code": "program OneInstance;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils, Windows;\n\nvar\n FMutex: THandle;\nbegin\n FMutex := CreateMutex(nil, True, 'OneInstanceMutex');\n if FMutex = 0 then\n RaiseLastOSError\n else\n begin\n try\n if GetLastError = ERROR_ALREADY_EXISTS then\n Writeln('Program already running. Closing...')\n else\n begin\n // do stuff ...\n Readln;\n end;\n finally\n CloseHandle(FMutex);\n end;\n end;\nend.\n", "language": "Delphi" }, { "code": "Shell(\"tasklist > temp.txt\")\n\nDim linea As String\nOpen \"temp.txt\" For Input As #1\nDo While Not Eof(1)\n Line Input #1, linea\n If Instr(linea, \"fbc.exe\") = 0 Then Print \"Task is Running\" : Exit Do\nLoop\nClose #1\nShell(\"del temp.txt\")\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"net\"\n \"time\"\n)\n\nconst lNet = \"tcp\"\nconst lAddr = \":12345\"\n\nfunc main() {\n if _, err := net.Listen(lNet, lAddr); err != nil {\n fmt.Println(\"an instance was already running\")\n return\n }\n fmt.Println(\"single instance started\")\n time.Sleep(10 * time.Second)\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"os\"\n \"time\"\n)\n\n// The path to the lock file should be an absolute path starting from the root.\n// (If you wish to prevent the same program running in different directories,\n// that is.)\nconst lfn = \"/tmp/rclock\"\n\nfunc main() {\n lf, err := os.OpenFile(lfn, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)\n if err != nil {\n fmt.Println(\"an instance is already running\")\n return\n }\n lf.Close()\n fmt.Println(\"single instance started\")\n time.Sleep(10 * time.Second)\n os.Remove(lfn)\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"os\"\n \"strconv\"\n \"strings\"\n \"time\"\n)\n\n// The path to the lock file should be an absolute path starting from the root.\n// (If you wish to prevent the same program running in different directories, that is.)\nconst lfn = \"/tmp/rclock\"\n\nfunc main() {\n lf, err := os.OpenFile(lfn, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)\n if err == nil {\n // good\n // 10 digit pid seems to be a standard for lock files\n fmt.Fprintf(lf, \"%10d\", os.Getpid())\n lf.Close()\n defer os.Remove(lfn)\n } else {\n // problem\n fmt.Println(err)\n // dig deeper\n lf, err = os.Open(lfn)\n if err != nil {\n return\n }\n defer lf.Close()\n fmt.Println(\"inspecting lock file...\")\n b10 := make([]byte, 10)\n _, err = lf.Read(b10)\n if err != nil {\n fmt.Println(err)\n return\n }\n pid, err := strconv.Atoi(strings.TrimSpace(string(b10)))\n if err != nil {\n fmt.Println(err)\n return\n }\n fmt.Println(\"lock file created by pid\", pid)\n return\n }\n fmt.Println(os.Getpid(), \"running...\")\n time.Sleep(1e10)\n}\n", "language": "Go" }, { "code": "import Control.Concurrent\nimport System.Directory (doesFileExist, getAppUserDataDirectory,\n removeFile)\nimport System.IO (withFile, Handle, IOMode(WriteMode), hPutStr)\n\noneInstance :: IO ()\noneInstance = do\n -- check if file \"$HOME/.myapp.lock\" exists\n user <- getAppUserDataDirectory \"myapp.lock\"\n locked <- doesFileExist user\n if locked\n then print \"There is already one instance of this program running.\"\n else do\n t <- myThreadId\n -- this is the entry point to the main program:\n -- withFile creates a file, then calls a function,\n -- then closes the file\n withFile user WriteMode (do_program t)\n -- remove the lock when we're done\n removeFile user\n\ndo_program :: ThreadId -> Handle -> IO ()\ndo_program t h = do\n let s = \"Locked by thread: \" ++ show t\n -- print what thread has acquired the lock\n putStrLn s\n -- write the same message to the file, to show that the\n -- thread \"owns\" the file\n hPutStr h s\n -- wait for one second\n threadDelay 1000000\n\nmain :: IO ()\nmain = do\n -- launch the first thread, which will create the lock file\n forkIO oneInstance\n -- wait for half a second\n threadDelay 500000\n -- launch the second thread, which will find the lock file and\n -- thus will exit immediately\n forkIO oneInstance\n return ()\n", "language": "Haskell" }, { "code": "procedure main(A)\n if not open(\":\"||54321,\"na\") then stop(\"Already running\")\n repeat {}\t# busy loop\nend\n", "language": "Icon" }, { "code": "import java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.net.UnknownHostException;\n\npublic class SingletonApp\n{\n private static final int PORT = 65000; // random large port number\n private static ServerSocket s;\n\n // static initializer\n static {\n try {\n s = new ServerSocket(PORT, 10, InetAddress.getLocalHost());\n } catch (UnknownHostException e) {\n // shouldn't happen for localhost\n } catch (IOException e) {\n // port taken, so app is already running\n System.out.print(\"Application is already running,\");\n System.out.println(\" so terminating this instance.\");\n System.exit(0);\n }\n }\n\n public static void main(String[] args) {\n System.out.print(\"OK, only this instance is running\");\n System.out.println(\" but will terminate in 10 seconds.\");\n try {\n Thread.sleep(10000);\n if (s != null && !s.isClosed()) s.close();\n } catch (Exception e) {\n System.err.println(e);\n }\n }\n}\n", "language": "Java" }, { "code": "/* Determine if only one instance, in Jsish */\nvar sock;\n\ntry {\n sock = new Socket({client:false, port:54321});\n puts('\\nApplication running for 30 seconds, from', strftime());\n update(30000);\n puts('\\nApplication ended at', strftime());\n} catch (err) {\n puts('Applicaion already running');\n exit(1);\n}\n", "language": "Jsish" }, { "code": "using Sockets\n\nconst portnum = 12345\n\nfunction canopen()\n try\n server = listen(portnum)\n println(\"This is the only instance.\")\n sleep(20)\n catch y\n if findfirst(\"EADDRINUSE\", string(y)) != nothing\n println(\"There is already an instance running.\")\n end\n end\nend\n\ncanopen()\n", "language": "Julia" }, { "code": "// version 1.0.6\n\nimport java.io.IOException\nimport java.net.*\n\nobject SingleInstance {\n private var ss: ServerSocket? = null\n\n fun alreadyRunning(): Boolean {\n try {\n ss = ServerSocket(65000, 10, InetAddress.getLocalHost()) // using private port 65000\n }\n catch (e: IOException) {\n // port already in use so an instance is already running\n return true\n }\n return false\n }\n\n fun close() {\n if (ss == null || ss?.isClosed() == true) return\n ss?.close()\n }\n}\n\nfun main(args: Array<String>) {\n if (SingleInstance.alreadyRunning()) {\n println(\"Application is already running, so terminating this instance\")\n System.exit(0)\n }\n else {\n println(\"OK, only this instance is running but will terminate in 10 seconds\")\n Thread.sleep(10000)\n SingleInstance.close()\n }\n}\n", "language": "Kotlin" }, { "code": "#!/usr/bin/lasso9\n\nlocal(lockfile = file('/tmp/myprocess.lockfile'))\n\nif(#lockfile -> exists) => {\n\tstdoutnl('Error: App is running as of ' + #lockfile -> readstring)\n\tabort\n}\n\nhandle => {\n\t#lockfile -> delete\n}\n\nstdoutnl('Starting execution')\n\n#lockfile -> doWithClose => {\n\t#lockfile -> writebytes(bytes(date))\n}\n\nsleep(10000)\n\nstdoutnl('Execution done')\n", "language": "Lasso" }, { "code": "'Create a Mutex to prevent more than one instance from being open at a single time.\nCallDLL #kernel32, \"CreateMutexA\", 0 as Long, 1 as Long, \"Global\\My Program\" as ptr, mutex as ulong\nCallDLL #kernel32, \"GetLastError\", LastError as Long\n\nif LastError = 183 then 'Error returned when a Mutex already exists\n 'Close the handle if the mutex already exists\n calldll #kernel32, \"CloseHandle\", mutex as ulong, ret as ulong\n notice \"An instance of My Program is currently running!\"\n end\nend if\n\n'Release the Mutex/ Close the handle prior to ending the program\n'Comment out these lines to allow the program to remain active to test for the mutex's presence\ncalldll #kernel32, \"ReleaseMutex\", mutex as ulong, ret as ulong\ncalldll #kernel32, \"CloseHandle\", mutex as ulong, ret as ulong\nend\n", "language": "Liberty-BASIC" }, { "code": "Module Checkit {\n Try {\n Open \"MYLOCK\" For Output Exclusive As #F\n Print \"DO SOMETHING\"\n A$=Key$\n Close#f\n }\n}\n", "language": "M2000-Interpreter" }, { "code": "$Epilog := Print[\"Another instance is running \"];\nIf[Attributes[Global`Mutex] == {Protected},\n Exit[],\n Global`Mutex[x_] := Locked; Protect[Global`Mutex];\n ]\n", "language": "Mathematica" }, { "code": "import os, posix\n\nlet fn = getHomeDir() & \"rosetta-code-lock\"\nproc ooiUnlink {.noconv.} = discard unlink fn\n\nproc onlyOneInstance =\n var fl = TFlock(lType: F_WRLCK.cshort, lWhence: SEEK_SET.cshort)\n var fd = getFileHandle fn.open fmReadWrite\n if fcntl(fd, F_SETLK, addr fl) < 0:\n stderr.writeLine \"Another instance of this program is running\"\n quit 1\n addQuitProc ooiUnlink\n\nonlyOneInstance()\n\nfor i in countdown(10, 1):\n echo i\n sleep 1000\necho \"Fin!\"\n", "language": "Nim" }, { "code": "import options, os\nfrom net import newSocket, bindUnix\nfrom nativesockets import AF_UNIX, SOCK_DGRAM, IPPROTO_IP\nfrom posix import EADDRINUSE\n\nconst sockAddr = \"\\0com.myapp.sock\" # Linux will delete this when the application ends\n# notice the prefixed null byte, it's the Linux abstract namespace\n\nproc server()=\n echo \"Unique instance detected\"\n\nproc client()=\n echo \"Duplicate instance detected\"\n\nwhen isMainModule:\n var\n sock = newSocket(AF_UNIX, SOCK_DGRAM, IPPROTO_IP)\n isUnique: Option[bool]\n\n try:\n sock.bindUnix(sock_addr)\n is_unique = some true\n except OSError:\n if cint(osLastError()) == EADDRINUSE:\n isUnique = some false\n else:\n raise getCurrentException()\n\n if unlikely is_unique.isNone:\n echo \"Error detecting uniqueness\" # unreachable\n else:\n if isUnique.unsafeGet():\n server()\n else:\n client()\n", "language": "Nim" }, { "code": "open Sem\n\nlet () =\n let oflags = [Unix.O_CREAT;\n Unix.O_EXCL] in\n let sem = sem_open \"MyUniqueName\" ~oflags () in\n (* here the real code of the app *)\n Unix.sleep 20;\n (* end of the app *)\n sem_unlink \"MyUniqueName\";\n sem_close sem\n", "language": "OCaml" }, { "code": "functor\nimport Application Open System\ndefine\n fun {IsAlreadyRunning}\n try\n\t S = {New Open.socket init}\n in\n\t {S bind(takePort:12345)}\n\t false\n catch system(os(os \"bind\" ...) ...) then\n\t true\n end\n end\n\n if {IsAlreadyRunning} then\n {System.showInfo \"Exiting because already running.\"}\n {Application.exit 1}\n end\n {System.showInfo \"Press enter to exit.\"}\n {{New Open.file init(name:stdin)} read(list:_ size:1)}\n {Application.exit 0}\nend\n", "language": "Oz" }, { "code": "use Fcntl ':flock';\n\nINIT\n{\n\tdie \"Not able to open $0\\n\" unless (open ME, $0);\n\tdie \"I'm already running !!\\n\" unless(flock ME, LOCK_EX|LOCK_NB);\n}\n\nsleep 60; # then your code goes here\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #000080;font-style:italic;\">-- demo\\rosetta\\Single_instance.exw</span>\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">copydata_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">pCommandLine</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">size</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- (the first instance is sent a copy of the second one's command line)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"COPYDATA(%s, %d)\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">peek_string</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pCommandLine</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">size</span><span style=\"color: #0000FF;\">});</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span><span style=\"color: #0000FF;\">;</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupSetGlobal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"SINGLEINSTANCE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"Single\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (must [partially] match the main window title)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">IupGetGlobal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"SINGLEINSTANCE\"</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #008000;\">\"\"</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">IupVbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"hello\"</span><span style=\"color: #0000FF;\">)},</span><span style=\"color: #008000;\">\"MARGIN=200x200\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Single Instance\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"COPYDATA_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"copydata_cb\"</span><span style=\"color: #0000FF;\">));</span>\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "$ pil +\n: (call \"killall\" \"-0\" \"-q\" \"myScript\")\n-> T\n", "language": "PicoLisp" }, { "code": ": (acquire \"running1\")\n-> 30817 # A successful call returns the PID\n", "language": "PicoLisp" }, { "code": "if (Get-Process -Name \"notepad\" -ErrorAction SilentlyContinue)\n{\n Write-Warning -Message \"notepad is already running.\"\n}\nelse\n{\n Start-Process -FilePath C:\\Windows\\notepad.exe\n}\n", "language": "PowerShell" }, { "code": "if (Get-Process -Name \"notepad\" -ErrorAction SilentlyContinue)\n{\n Write-Warning -Message \"notepad is already running.\"\n}\nelse\n{\n Start-Process -FilePath C:\\Windows\\notepad.exe\n}\n", "language": "PowerShell" }, { "code": "#MyApp=\"MyLittleApp\"\nMutex=CreateMutex_(0,1,#MyApp)\nIf GetLastError_()=#ERROR_ALREADY_EXISTS\n MessageRequester(#MyApp,\"One instance is already started.\")\n End\nEndIf\n\n; Main code executes here\n\nReleaseMutex_(Mutex)\nEnd\n", "language": "PureBasic" }, { "code": "import __main__, os\n\ndef isOnlyInstance():\n # Determine if there are more than the current instance of the application\n # running at the current time.\n return os.system(\"(( $(ps -ef | grep python | grep '[\" +\n __main__.__file__[0] + \"]\" + __main__.__file__[1:] +\n \"' | wc -l) > 1 ))\") != 0\n", "language": "Python" }, { "code": "#lang racket\n(define *port* 12345) ; random large port number\n(define listener-handler\n (with-handlers ([exn? (λ(e) (printf \"Already running, bye.\\n\") (exit))])\n (tcp-listen *port*)))\n(printf \"Working...\\n\")\n(sleep 10)\n", "language": "Racket" }, { "code": "my $name = $*PROGRAM-NAME;\nmy $pid = $*PID;\n\nmy $lockdir = \"/tmp\";\nmy $lockfile = \"$lockdir/$name.pid\";\nmy $lockpid = \"$lockfile$pid\";\nmy $havelock = False;\n\nEND {\n unlink $lockfile if $havelock;\n try unlink $lockpid;\n}\n\nmy $pidfile = open \"$lockpid\", :w orelse .die;\n$pidfile.say($pid);\n$pidfile.close;\n\nif try link($lockpid, $lockfile) {\n $havelock = True;\n}\nelse {\n shell \"kill -CONT `cat $lockfile` || rm $lockfile\";\n if try link($lockfile, $lockpid) {\n $havelock = True;\n }\n else {\n die \"You can't run right now!\";\n }\n}\nnote \"Got lock!\";\nunlink $lockpid;\n", "language": "Raku" }, { "code": "/* Simple ARexx program to open a port after checking if it's already open */\nIF Show('PORTS','ROSETTA') THEN DO /* Port is already open; exit */\n SAY 'This program may only be run in a single instance at a time.'\n EXIT 5 /* Exit with a mild warning */\n END\n /* Open rexxsupport.library so that ports can be opened */\nIF ~Show('LIBRARIES','rexxsupport.library')\n THEN CALL AddLib('rexxsupport.library',0,-30,0)\n\nIF ~OpenPort('ROSETTA') THEN EXIT 10 /* Open port, end if it fails */\n\nSAY 'Program is now running.'\n\nDO FOREVER /* Busyloop */\n /* Program stuff here */\n END\n\nEXIT 0\n", "language": "REXX" }, { "code": "# Project : Determine if only one instance is running\n\ntask = \"ringw.exe\"\ntaskname = \"tasklist.txt\"\nremove(taskname)\nsystem(\"tasklist >> tasklist.txt\")\nfp = fopen(taskname,\"r\")\ntasks = read(\"tasklist.txt\")\ncounttask = count(tasks,task)\nif counttask > 0\n see task + \" running in \" + counttask + \" instances\" + nl\nelse\n see task + \" is not running\" + nl\nok\n\nfunc count(cString,dString)\n sum = 0\n while substr(cString,dString) > 0\n sum++\n cString = substr(cString,substr(cString,dString)+len(string(sum)))\n end\n return sum\n", "language": "Ring" }, { "code": "def main\n puts \"first instance\"\n sleep 20\n puts :done\nend\n\nif $0 == __FILE__\n if File.new(__FILE__).flock(File::LOCK_EX | File::LOCK_NB)\n main\n else\n raise \"another instance of this program is running\"\n end\nend\n\n__END__\n", "language": "Ruby" }, { "code": "if instr(shell$(\"tasklist\"),\"rbp.exe\") <> 0 then print \"Task is Running\"\n", "language": "Run-BASIC" }, { "code": "use std::net::TcpListener;\n\nfn create_app_lock(port: u16) -> TcpListener {\n match TcpListener::bind((\"0.0.0.0\", port)) {\n Ok(socket) => {\n socket\n },\n Err(_) => {\n panic!(\"Couldn't lock port {}: another instance already running?\", port);\n }\n }\n}\n\nfn remove_app_lock(socket: TcpListener) {\n drop(socket);\n}\n\nfn main() {\n let lock_socket = create_app_lock(12345);\n // ...\n // your code here\n // ...\n remove_app_lock(lock_socket);\n}\n", "language": "Rust" }, { "code": "import java.io.IOException\nimport java.net.{InetAddress, ServerSocket}\n\nobject SingletonApp extends App {\n private val port = 65000\n\n try {\n val s = new ServerSocket(port, 10, InetAddress.getLocalHost)\n }\n catch {\n case _: IOException =>\n // port taken, so app is already running\n println(\"Application is already running, so terminating this instance.\")\n sys.exit(-1)\n }\n\n println(\"OK, only this instance is running but will terminate in 10 seconds.\")\n\n Thread.sleep(10000)\n\n sys.exit(0)\n\n}\n", "language": "Scala" }, { "code": "# For this to work, you need to explicitly\n# store the returned fh inside a variable.\nvar fh = File(__FILE__).open_r\n\n# Now call the flock() method on it\nfh.flock(File.LOCK_EX | File.LOCK_NB) ->\n || die \"I'm already running!\"\n\n# Your code here...\nsay \"Running...\"\nSys.sleep(20)\nsay 'Done!'\n", "language": "Sidef" }, { "code": "import Foundation\n\nlet globalCenter = NSDistributedNotificationCenter.defaultCenter()\nlet time = NSDate().timeIntervalSince1970\n\nglobalCenter.addObserverForName(\"OnlyOne\", object: nil, queue: NSOperationQueue.mainQueue()) {not in\n if let senderTime = not.userInfo?[\"time\"] as? NSTimeInterval where senderTime != time {\n println(\"More than one running\")\n exit(0)\n } else {\n println(\"Only one\")\n }\n}\n\nfunc send() {\n globalCenter.postNotificationName(\"OnlyOne\", object: nil, userInfo: [\"time\": time])\n\n let waitTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * NSEC_PER_SEC))\n\n dispatch_after(waitTime, dispatch_get_main_queue()) {\n send()\n }\n}\n\nsend()\nCFRunLoopRun()\n", "language": "Swift" }, { "code": "package require Tcl 8.6\ntry {\n # Pick a port number based on the name of the main script executing\n socket -server {apply {{chan args} {close $chan}}} -myaddr localhost \\\n [expr {1024 + [zlib crc32 [file normalize $::argv0]] % 30000}]\n} trap {POSIX EADDRINUSE} {} {\n # Generate a nice error message\n puts stderr \"Application $::argv0 already running?\"\n exit 1\n}\n", "language": "Tcl" }, { "code": ";;; Define some typedefs for clear correspondence with Win32\n(typedef HANDLE cptr)\n(typedef LPSECURITY_ATTRIBUTES cptr)\n(typedef WINERR (enum WINERR ERROR_SUCCESS\n (ERROR_ALREADY_EXISTS 183)))\n(typedef BOOL (enum BOOL FALSE TRUE))\n(typedef LPCWSTR wstr)\n\n;;; More familiar spelling for null pointer.\n(defvarl NULL cptr-null)\n\n;;; Define access to foreign functions.\n(with-dyn-lib \"kernel32.dll\"\n (deffi CreateMutex \"CreateMutexW\" HANDLE (LPSECURITY_ATTRIBUTES BOOL LPCWSTR))\n (deffi CloseHandle \"CloseHandle\" BOOL (HANDLE))\n (deffi GetLastError \"GetLastError\" WINERR ()))\n\n;;; Now, the single-instance program:\n(defvar m (CreateMutex NULL 'TRUE \"ApplicationName\"))\n\n(unless (eq (GetLastError) 'ERROR_ALREADY_EXISTS)\n ;; mutual exclusion here\n )\n\n(CloseHandle m)\n", "language": "TXR" }, { "code": "# (c) Copyright 2005 Mark Hobley\n#\n# This is free software. This file can be redistributed or modified\n# under the terms of version 1.2 of the GNU Free Documentation Licence\n# as published by the Free Software Foundation.\n#\n\n singleinstance ()\n {\n if [ -d $SRUNDIR ] ; then\n if [ -w $SRUNDIR ] ; then\n if [ -d $SRUNDIR/$APPNAME ] ; then\n echo \"Process Already Running\" >& 2\n return 221\n else\n mkdir $SRUNDIR/$APPNAME\n if [ \"$?\" -ne 0 ] ; then\n if [ -d $SRUNDIR/$APPNAME ] ; then\n echo \"Process Already Running\" >& 2\n return 221\n else\n echo \"Unexpected Error\" >& 2\n return 239\n fi\n fi\n return 0 ; # This is a unique instance\n fi\n else\n echo \"Permission Denied\" >& 2\n return 210\n fi\n else\n echo \"Missing Directory\" >& 2\n return 199\n fi\n }\n", "language": "UNIX-Shell" }, { "code": "Dim onlyInstance as Boolean\nonlyInstance = not App.PrevInstance\n", "language": "Visual-Basic" }, { "code": "import \"io\" for File, FileFlags\n\nvar specialFile = \"wren-exclusive._sp\"\nvar checkOneInstanceRunning = Fn.new {\n // attempt to create the special file with exclusive access\n var ff = FileFlags.create | FileFlags.exclusive\n File.openWithFlags(specialFile, ff) { |file| } // closes automatically if successful\n}\n\n// check if the current instance is the only one running\nvar fiber = Fiber.new {\n checkOneInstanceRunning.call()\n}\nvar error = fiber.try()\nif (error) {\n System.print(\"An instance is already running.\")\n return\n}\n\n// do something that takes a while for testing purposes\nvar sum = 0\nfor (i in 1...1e8) {\n sum = sum + i\n}\nSystem.print(sum)\n\nFile.delete(specialFile) // clean up\n", "language": "Wren" } ]
Determine-if-only-one-instance-is-running
[ { "code": "---\ncategory:\n- Geometry\n- Collision detection\nfrom: http://rosettacode.org/wiki/Determine_if_two_triangles_overlap\n", "language": "00-META" }, { "code": "Determining if two triangles in the same plane overlap is an important topic in collision detection.\n\n\n;Task:\nDetermine which of these pairs of triangles overlap in 2D:\n\n:::* &nbsp; (0,0),(5,0),(0,5) &nbsp; &nbsp; and &nbsp; (0,0),(5,0),(0,6)\n:::* &nbsp; (0,0),(0,5),(5,0) &nbsp; &nbsp; and &nbsp; (0,0),(0,5),(5,0)\n:::* &nbsp; (0,0),(5,0),(0,5) &nbsp; &nbsp; and &nbsp; (-10,0),(-5,0),(-1,6)\n:::* &nbsp; (0,0),(5,0),(2.5,5) &nbsp; and &nbsp; (0,4),(2.5,-1),(5,4)\n:::* &nbsp; (0,0),(1,1),(0,2) &nbsp; &nbsp; and &nbsp; (2,1),(3,0),(3,2)\n:::* &nbsp; (0,0),(1,1),(0,2) &nbsp; &nbsp; and &nbsp; (2,1),(3,-2),(3,4)\n\n\nOptionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):\n:::* &nbsp; (0,0),(1,0),(0,1) &nbsp; and &nbsp; (1,0),(2,0),(1,1)\n<br><br>\n\n;Related tasks\n* [[Check_if_two_polygons_overlap|Check if two polygons overlap]]\n* [[Check_if_a_polygon_overlaps_with_a_rectangle|Check if a polygon overlaps with a rectangle]]\n<br><br>\n\n", "language": "00-TASK" }, { "code": "T Triangle\n (Float, Float) p1, p2, p3\n\n F (p1, p2, p3)\n .p1 = p1\n .p2 = p2\n .p3 = p3\n\n F String()\n R ‘Triangle: #., #., #.’.format(.p1, .p2, .p3)\n\n F.const det2D()\n R .p1[0] * (.p2[1] - .p3[1])\n + .p2[0] * (.p3[1] - .p1[1])\n + .p3[0] * (.p1[1] - .p2[1])\n\nF checkTriWinding(Triangle &t; allowReversed)\n V detTri = t.det2D()\n I detTri < 0.0\n assert(allowReversed, ‘Triangle has wrong winding direction’)\n swap(&t.p2, &t.p3)\n\nF boundaryCollideChk(Triangle t, Float eps)\n R t.det2D() < eps\n\nF boundaryDoesntCollideChk(Triangle t, Float eps)\n R t.det2D() <= eps\n\nF triTri2D(Triangle &t1, &t2; eps = 0.0, allowReversed = 0B, onBoundary = 1B)\n checkTriWinding(&t1, allowReversed)\n checkTriWinding(&t2, allowReversed)\n V chkEdge = I onBoundary {:boundaryCollideChk} E :boundaryDoesntCollideChk\n V lp1 = [t1.p1, t1.p2, t1.p3]\n V lp2 = [t2.p1, t2.p2, t2.p3]\n\n L(i) 3\n V j = (i + 1) % 3\n I chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) &\n chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) &\n chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)\n R 0B\n\n L(i) 3\n V j = (i + 1) % 3\n I chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) &\n chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) &\n chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)\n R 0B\n\n R 1B\n\nF overlap(Triangle &t1, &t2; eps = 0.0, allowReversed = 0B, onBoundary = 1B)\n I triTri2D(&t1, &t2, eps, allowReversed, onBoundary)\n print(‘overlap’)\n E\n print(‘do not overlap’)\n\nV t1 = Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 5.0))\nV t2 = Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 6.0))\nprint(t1\" and\\n\"t2)\noverlap(&t1, &t2)\nprint()\n\nt1 = Triangle((0.0, 0.0), (0.0, 5.0), (5.0, 0.0))\nt2 = t1\nprint(t1\" and\\n\"t2)\noverlap(&t1, &t2, 0.0, 1B)\nprint()\n\nt1 = Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 5.0))\nt2 = Triangle((-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0))\nprint(t1\" and\\n\"t2)\noverlap(&t1, &t2)\nprint()\n\nt1.p3 = (2.5, 5.0)\nt2 = Triangle((0.0, 4.0), (2.5, -1.0), (5.0, 4.0))\nprint(t1\" and\\n\"t2)\noverlap(&t1, &t2)\nprint()\n\nt1 = Triangle((0.0, 0.0), (1.0, 1.0), (0.0, 2.0))\nt2 = Triangle((2.0, 1.0), (3.0, 0.0), (3.0, 2.0))\nprint(t1\" and\\n\"t2)\noverlap(&t1, &t2)\nprint()\n\nt2 = Triangle((2.0, 1.0), (3.0, -2.0), (3.0, 4.0))\nprint(t1\" and\\n\"t2)\noverlap(&t1, &t2)\nprint()\n\nt1 = Triangle((0.0, 0.0), (1.0, 0.0), (0.0, 1.0))\nt2 = Triangle((1.0, 0.0), (2.0, 0.0), (1.0, 1.1))\nprint(t1\" and\\n\"t2)\nprint(‘which have only a single corner in contact, if boundary points collide’)\noverlap(&t1, &t2)\nprint()\n\nprint(t1\" and\\n\"t2)\nprint(‘which have only a single corner in contact, if boundary points do not collide’)\noverlap(&t1, &t2, 0.0, 0B, 0B)\n", "language": "11l" }, { "code": "WITH Ada.Text_IO; USE Ada.Text_IO;\n\nPROCEDURE Main IS\n TYPE Vertex IS MOD 3;\n TYPE Point IS ARRAY (0 .. 1) OF Float;\n TYPE Triangle IS ARRAY (Vertex) OF Point;\n TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float;\n\n FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS\n FUNCTION Aff (U : Point) RETURN Float IS\n ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1)));\n BEGIN\n RETURN Aff (M) * Aff (N) >= 0.0;\n END Same_Side;\n\n FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS\n (FOR ALL V IN Vertex =>\n (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P)));\n\n FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS\n (In_Side (T1, T2) AND THEN In_Side (T2, T1));\n\n FUNCTION \"+\" (T : Triangle_Vertices) RETURN Triangle IS\n ((T (0), T (1)), (T (2), T (3)), (T (4), T (5)));\n\n PROCEDURE Put (T1, T2 : Triangle_Vertices) IS\n BEGIN\n Put_Line (Overlap (+T1, +T2)'Img);\n END Put;\n\nBEGIN\n Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0));\n Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0));\n Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0));\n Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0));\n Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0));\n Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0));\n Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0));\nEND Main;\n", "language": "Ada" }, { "code": "BEGIN # test for overlapping 2D triangles - using the code from the Algol 68 #\n # sample for the Check if two polygons overlap task, the code of which #\n # is based on a translation of that tasks' Go which is a translation #\n # of Wren #\n\n # In the following a polygon is represented as a row of vertices #\n # and a vertex ( POINT ) by a pair of x, y coordinates in the plane #\n\n MODE POINT = STRUCT( REAL x, y );\n MODE PROJECTION = STRUCT( REAL min, max );\n MODE POLYGON = FLEX[ 1 : 0 ]POINT;\n\n PRIO DOT = 3;\n OP DOT = ( POINT v, other )REAL:\n ( x OF v * x OF other ) + ( y OF v * y OF other );\n\n # returns the axes of the polygon defined by poly #\n OP AXES = ( POLYGON poly )[]POINT:\n BEGIN\n [ LWB poly : UPB poly ]POINT result;\n FOR i FROM LWB poly TO UPB poly DO\n INT j = IF i = UPB poly THEN LWB poly ELSE i + 1 FI;\n POINT vertex1 = poly[ i ];\n POINT vertex2 = poly[ j ];\n POINT edge = ( x OF vertex1 - x OF vertex2, y OF vertex1 - y OF vertex2 );\n result[ i ] := ( - y OF edge, x OF edge )\n OD;\n result\n END # AXES # ;\n\n # returns the projection of poly onto axis #\n PRIO PROJECTONTO = 3;\n OP PROJECTONTO = ( POLYGON poly, POINT axis )PROJECTION:\n BEGIN\n REAL min := axis DOT poly[ LWB poly ];\n REAL max := min;\n FOR i FROM LWB poly + 1 TO UPB poly DO\n REAL p = axis DOT poly[ i ];\n IF p < min THEN\n min := p\n ELIF p > max THEN\n max := p\n FI\n OD;\n PROJECTION( min, max )\n END # PROJECTONTO # ;\n\n PRIO OVERLAPS = 5;\n # returns TRUE if the projections proj1 and proj2 overlap, #\n # FALSE otherrwise #\n OP OVERLAPS = ( PROJECTION proj1, proj2 )BOOL:\n IF max OF proj1 < min OF proj2 THEN FALSE\n ELIF max OF proj2 < min OF proj1 THEN FALSE\n ELSE TRUE\n FI # OVERLAPS # ;\n\n # returns TRUE if the ppolygons poly1 and poly2 overlap, #\n # FALSE otherrwise #\n OP OVERLAPS = ( POLYGON poly1, poly2 )BOOL:\n BEGIN\n []POINT axes1 = AXES poly1, axes2 = AXES poly2;\n BOOL does overlap := TRUE;\n FOR a FROM LWB axes1 TO UPB axes1 WHILE does overlap DO\n does overlap := ( poly1 PROJECTONTO axes1[ a ] )\n OVERLAPS ( poly2 PROJECTONTO axes1[ a ] )\n OD;\n FOR a FROM LWB axes2 TO UPB axes2 WHILE does overlap DO\n does overlap := ( poly1 PROJECTONTO axes2[ a ] )\n OVERLAPS ( poly2 PROJECTONTO axes2[ a ] )\n OD;\n does overlap\n END # OVERLAPS # ;\n\n # returns x as a string without trailing 0 decoimals #\n OP TOSTRING = ( REAL x )STRING:\n BEGIN\n STRING v := fixed( x, -14, 11 );\n INT end pos := UPB v;\n WHILE IF end pos < LWB v THEN FALSE ELSE v[ end pos ] = \"0\" FI DO\n end pos -:= 1\n OD;\n IF end pos >= LWB v THEN\n IF v[ end pos ] = \".\" THEN end pos -:= 1 FI\n FI;\n INT start pos := LWB v;\n WHILE IF start pos > end pos THEN FALSE ELSE v[ start pos ] = \" \" FI DO\n start pos +:= 1\n OD;\n IF end pos < start pos THEN \"0\" ELSE v[ start pos : end pos ] FI\n END # TOSTRING # ;\n\n # returns a string representation of the POINT p #\n OP TOSTRING = ( POINT p )STRING: \"( \" + TOSTRING x OF p + \", \" + TOSTRING y OF p + \" )\";\n\n # returns a string representation of the points of p #\n OP TOSTRING = ( POLYGON p )STRING:\n BEGIN\n STRING result := \"(\", separator := \"\";\n FOR i FROM LWB p TO UPB p DO\n result +:= separator + \" \" + TOSTRING p[ i ];\n separator := \",\"\n OD;\n result + \" )\"\n END # TOSTRING # ;\n\n # code specific to thius task #\n # test cases - using the general POLYGON MODE to represent triangles #\n [,]POLYGON triangle pairs\n = ( ( ( ( 0, 0 ), ( 5, 0 ), ( 0, 5 ) ), ( ( 0, 0 ), ( 5, 0 ), ( 0, 6 ) ) )\n , ( ( ( 0, 0 ), ( 0, 5 ), ( 5, 0 ) ), ( ( 0, 0 ), ( 0, 5 ), ( 5, 0 ) ) )\n , ( ( ( 0, 0 ), ( 5, 0 ), ( 0, 5 ) ), ( (-10, 0 ), ( -5, 0 ), ( -1, 6 ) ) )\n , ( ( ( 0, 0 ), ( 5, 0 ), ( 2.5, 5 ) ), ( ( 0, 4 ), ( 2.5, -1 ), ( 5, 4 ) ) )\n , ( ( ( 0, 0 ), ( 1, 1 ), ( 0, 2 ) ), ( ( 2, 1 ), ( 3, 0 ), ( 3, 2 ) ) )\n , ( ( ( 0, 0 ), ( 1, 1 ), ( 0, 2 ) ), ( ( 2, 1 ), ( 3, -2 ), ( 3, 4 ) ) )\n , ( ( ( 0, 0 ), ( 1, 0 ), ( 0, 1 ) ), ( ( 1, 0 ), ( 2, 0 ), ( 1, 1 ) ) )\n );\n FOR t pos FROM LWB triangle pairs TO UPB triangle pairs DO\n []POLYGON tpair = triangle pairs[ t pos, : ];\n POLYGON t1 = tpair[ LWB tpair ];\n POLYGON t2 = tpair[ UPB tpair ];\n print( ( TOSTRING t1\n , IF t1 OVERLAPS t2 THEN \" overlaps \" ELSE \" does not overlap \" FI\n , TOSTRING t2\n , newline\n )\n )\n OD\nEND\n", "language": "ALGOL-68" }, { "code": "begin % determine if two triangles overlap %\n record Point ( real x, y );\n record Triangle ( reference(Point) p1, p2, p3 );\n procedure WritePoint ( reference(Point) value p ) ;\n writeon( r_w := 3, r_d := 1, r_format := \"A\", s_w := 0, \"(\", x(p), \", \", y(p), \")\" );\n procedure WriteTriangle ( reference(Triangle) value t ) ;\n begin\n WritePoint( p1(t) );\n writeon( \", \" );\n WritePoint( p2(t) );\n writeon( \", \" );\n WritePoint( p3(t) )\n end WriteTriangle ;\n real procedure Det2D ( reference(Triangle) value t ) ;\n ( ( x(p1(t)) * ( y(p2(t)) - y(p3(t)) ) )\n + ( x(p2(t)) * ( y(p3(t)) - y(p1(t)) ) )\n + ( x(p3(t)) * ( y(p1(t)) - y(p2(t)) ) )\n );\n procedure CheckTriWinding ( reference(Triangle) value t ; logical value allowReversed ) ;\n begin\n real detTri;\n detTri := Det2D(t);\n if detTri < 0.0 then begin\n if allowReversed then begin\n reference(Point) a;\n a := p3(t);\n p3(t) := p2(t);\n p2(t) := a\n end\n else begin\n write( \"triangle has wrong winding direction\" );\n assert( false )\n end\n end if_detTri_lt_0\n end CheckTriWinding ;\n logical procedure BoundaryCollideChk( reference(Triangle) value t ; real value eps ) ; Det2D( t ) < eps ;\n logical procedure BoundaryDoesntCollideChk( reference(Triangle) value t ; real value eps ) ; Det2D( t ) <= eps ;\n logical procedure TriTri2D( reference(Triangle) value t1, t2 ; real value eps ; logical value allowReversed, onBoundary ) ;\n begin\n logical procedure ChkEdge( reference(Triangle) value t ) ;\n if onBoundary then % Points on the boundary are considered as colliding %\n BoundaryCollideChk( t, eps )\n else % Points on the boundary are not considered as colliding %\n BoundaryDoesntCollideChk( t, eps )\n ;\n reference(Point) array lp1, lp2 ( 0 :: 2 );\n logical overlap;\n overlap := true;\n % Triangles must be expressed anti-clockwise %\n CheckTriWinding( t1, allowReversed );\n CheckTriWinding( t2, allowReversed );\n lp1( 0 ) := p1(t1); lp1( 1 ) := p2(t1); lp1( 2 ) := p3(t1);\n lp2( 0 ) := p1(t2); lp2( 1 ) := p2(t2); lp2( 2 ) := p3(t2);\n % for each edge E of t1 %\n for i := 0 until 2 do begin\n integer j;\n j := ( i + 1 ) rem 3;\n % Check all points of t2 lay on the external side of edge E. %\n % if they do, the triangles do not overlap. %\n if ChkEdge( Triangle( lp1( i ), lp1( j ), lp2( 0 ) ) )\n and ChkEdge( Triangle( lp1( i ), lp1( j ), lp2( 1 ) ) )\n and ChkEdge( Triangle( lp1( i ), lp1( j ), lp2( 2 ) ) )\n then begin\n overlap := false;\n goto return\n end\n end for_i ;\n % for each edge E of t2 %\n for i := 0 until 2 do begin\n integer j;\n j := ( i + 1 ) rem 3;\n % Check all points of t1 lay on the external side of edge E. %\n % if they do, the triangles do not overlap. %\n if ChkEdge( Triangle( lp2( i ), lp2( j ), lp1( 0 ) ) )\n and ChkEdge( Triangle( lp2( i ), lp2( j ), lp1( 1 ) ) )\n and ChkEdge( Triangle( lp2( i ), lp2( j ), lp1( 2 ) ) )\n then begin\n overlap := false;\n goto return\n end\n end for_i;\n % if we get here, The triangles overlap %\nreturn: overlap\n end TriTri2D ;\n procedure CheckOverlap( reference(Triangle) value t1, t2\n ; real value eps\n ; logical value allowReversed, onBoundary\n ) ;\n begin\n write( \"Triangles \" );\n WriteTriangle( t1 );\n writeon( \" and \" );\n WriteTriangle( t2 );\n writeon( if TriTri2D( t1, t2, eps, allowReversed, onBoundary ) then \" overlap\" else \" do not overlap\" );\n end CheckOverlap ;\n begin % main %\n reference(Triangle) t1, t2;\n t1 := Triangle( Point( 0.0, 0.0 ), Point( 5.0, 0.0 ), Point( 0.0, 5.0 ) );\n t2 := Triangle( Point( 0.0, 0.0 ), Point( 5.0, 0.0 ), Point( 0.0, 6.0 ) );\n CheckOverlap( t1, t2, 0.0, false, true );\n t1 := Triangle( Point( 0.0, 0.0 ), Point( 0.0, 5.0 ), Point( 5.0, 0.0 ) );\n t2 := Triangle( Point( 0.0, 0.0 ), Point( 0.0, 5.0 ), Point( 5.0, 0.0 ) );\n CheckOverlap(t1, t2, 0.0, true, true );\n t1 := Triangle( Point( 0.0, 0.0 ), Point( 5.0, 0.0 ), Point( 0.0, 5.0 ) );\n t2 := Triangle( Point( -10.0, 0.0 ), Point( -5.0, 0.0 ), Point( -1.0, 6.0 ) );\n CheckOverlap( t1, t2, 0.0, false, true );\n t1 := Triangle( Point( 0.0, 0.0 ), Point( 5.0, 0.0 ), Point( 2.5, 5.0 ) );\n t2 := Triangle( Point( 0.0, 4.0 ), Point( 2.5, -1.0 ), Point( 5.0, 4.0 ) );\n CheckOverlap( t1, t2, 0.0, false, true );\n t1 := Triangle( Point( 0.0, 0.0 ), Point( 1.0, 1.0 ), Point( 0.0, 2.0 ) );\n t2 := Triangle( Point( 2.0, 1.0 ), Point( 3.0, 0.0 ), Point( 3.0, 2.0 ) );\n CheckOverlap( t1, t2, 0.0, false, true );\n t1 := Triangle( Point( 0.0, 0.0 ), Point( 1.0, 1.0 ), Point( 0.0, 2.0 ) );\n t2 := Triangle( Point( 2.0, 1.0 ), Point( 3.0, -2.0 ), Point( 3.0, 4.0 ) );\n CheckOverlap( t1, t2, 0.0, false, true );\n t1 := Triangle( Point( 0.0, 0.0 ), Point( 1.0, 0.0 ), Point( 0.0, 1.0 ) );\n t2 := Triangle( Point( 1.0, 0.0 ), Point( 2.0, 0.0 ), Point( 1.0, 1.1 ) );\n CheckOverlap( t1, t2, 0.0, false, true );\n t1 := Triangle( Point( 0.0, 0.0 ), Point( 1.0, 0.0 ), Point( 0.0, 1.0 ) );\n t2 := Triangle( Point( 1.0, 0.0 ), Point( 2.0, 0.0 ), Point( 1.0, 1.1 ) );\n CheckOverlap( t1, t2, 0.0, false, false );\n end\nend.\n", "language": "ALGOL-W" }, { "code": "(* Given that the context is collision detection, we will consider\n containment of one triangle entirely inside the other as ‘overlap’\n and test for that, as well as for overlap of the triangle sides\n themselves. One must agree that, if one triangle has become buried\n entirely inside another, then the two have collided. There are\n consequences for the conservation of momentum.\n\n Besides, the full set of overlap tests, INCLUDING containment of\n one polygonal hull inside another, is relevant to the problem of\n finding intersections of Bézier curves. See\n https://rosettacode.org/wiki/B%C3%A9zier_curves/Intersections\n\n This code specifically tests for overlapping vertices, in case the\n main tests fail to catch such overlaps. Approximate equality is\n employed rather than exact floating-point equality. *)\n\n#include \"share/atspre_staload.hats\"\n\n%{^\n#include <math.h>\n#include <float.h>\n%}\n\nmacdef dbl_epsilon = $extval (double, \"DBL_EPSILON\")\n\n(* We will use some simple homogeneous geometric algebra. *)\n\ntypedef point =\n @{e1 = double,\n e2 = double,\n e0 = double}\n\nmacdef Pt (x, y) = (* Shorthand for creating a normalized point. *)\n @{e1 = ,(x),\n e2 = ,(y),\n e0 = 1.0} : point\n\ntypedef line =\n @{e0_e1 = double,\n e0_e2 = double,\n e1_e2 = double}\n\ntypedef triangle = @(point, point, point)\n\nfn\nouter_product_point_point (a : point, b : point) : line =\n @{e0_e1 = ~(~a.e0 * b.e1 + a.e1 * b.e0),\n e0_e2 = ~(~a.e0 * b.e2 + a.e2 * b.e0),\n e1_e2 = (a.e1 * b.e2 - a.e2 * b.e1)}\n\nfn\nleft_contraction_point_line (a : point, b : line) : point =\n @{e1 = (a.e0 * b.e0_e1 - a.e2 * b.e1_e2),\n e2 = (a.e0 * b.e0_e2 + a.e1 * b.e1_e2),\n e0 = (~a.e1 * b.e0_e1 - a.e2 * b.e0_e2)}\n\nfn\nleft_contraction_point_point (a : point, b : point) : double =\n (* This is the same as the scalar product but saves us having to add\n an operator for which I cannot think of a good symbol. *)\n (a.e1 * b.e1) + (a.e2 * b.e2) + (a.e0 * b.e0)\n\nfn\ndual_line (a : line) : point =\n @{e1 = ~a.e0_e2,\n e2 = a.e0_e1,\n e0 = a.e1_e2}\n\noverload outer_product with outer_product_point_point\noverload left_contraction with left_contraction_point_line\noverload left_contraction with left_contraction_point_point\noverload dual with dual_line (* Orthogonal complement. *)\ninfixl ( * ) ^ .|\noverload ^ with outer_product\noverload .| with left_contraction\n\nfn\nintersection_line_line (a : line, b : line) : point =\n let\n val p = dual a .| b\n in\n if p.e0 = 0.0 then\n (* The lines are parallel (or coincident, if p is all zeros). *)\n p\n else\n (* Normalize the intersection point. *)\n @{e1 = p.e1 / p.e0,\n e2 = p.e2 / p.e0,\n e0 = 1.0}\n end\n\nfn\nwhich_side_point_line (a : point, b : line) : Sgn =\n (* 1 = left, 0 = lies on the line, ~1 = right *)\n let\n val x = dual b .| a\n in\n if x < 0.0 then\n ~1\n else if x > 0.0 then\n 1\n else\n 0\n end\n\noverload intersection with intersection_line_line\noverload which_side with which_side_point_line\n\nfn\norientation_triangle (t : triangle) : Sgn =\n (* 1 = counterclockwise, 0 = collinear, ~1 = clockwise *)\n which_side (t.2, t.0 ^ t.1)\n\noverload orientation with orientation_triangle\n\nfn\nset_orientation_triangle {s : int | abs s == 1}\n (t : triangle, s : int s) : triangle =\n (* 1 = counterclockwise, ~1 = clockwise. If the triangle is\n collinear, leave it unchanged. If the triangle does need\n rearrangement, do so by swapping vertices t.1 and t.2. *)\n let\n val s0 = orientation t\n in\n if (s = 0) + (s = s0) then\n t\n else\n @(t.0, t.2, t.1)\n end\n\noverload set_orientation with set_orientation_triangle\n\nfn\noverlap_triangle_triangle (t1 : triangle, t2 : triangle) : bool =\n let\n val t1 = set_orientation (t1, 1)\n and t2 = set_orientation (t2, 1)\n\n (* The lines that form the sides of the triangles. *)\n val s1 = @(t1.0 ^ t1.1, t1.1 ^ t1.2, t1.2 ^ t1.0)\n val s2 = @(t2.0 ^ t2.1, t2.1 ^ t2.2, t2.2 ^ t2.0)\n\n fn\n sides_intersect (pa : point, pb : point, ln_p : line,\n qa : point, qb : point, ln_q : line) : bool =\n let\n val x = intersection (ln_p, ln_q)\n in\n if x.e0 <> 0.0 then\n let\n val px_min = min (pa.e1, pb.e1)\n and px_max = max (pa.e1, pb.e1)\n and py_min = min (pa.e2, pb.e1)\n and py_max = max (pa.e2, pb.e1)\n\n val px_min2 = px_min + px_min\n and px_max2 = px_max + px_max\n and py_min2 = py_min + py_min\n and py_max2 = py_max + py_max\n\n val px_min_eps = abs (px_min) * dbl_epsilon\n and px_max_eps = abs (px_max) * dbl_epsilon\n val py_min_eps = abs (py_min) * dbl_epsilon\n and py_max_eps = abs (py_max) * dbl_epsilon\n in\n if px_min2 - px_min_eps <= x.e1 + x.e1\n && x.e1 + x.e1 <= px_max2 + px_max_eps\n && py_min2 - py_min_eps <= x.e2 + x.e2\n && x.e2 + x.e2 <= py_max2 + py_max_eps then\n let\n val qx_min = min (qa.e1, qb.e1)\n and qx_max = max (qa.e1, qb.e1)\n and qy_min = min (qa.e2, qb.e1)\n and qy_max = max (qa.e2, qb.e1)\n\n val qx_min2 = qx_min + qx_min\n and qx_max2 = qx_max + qx_max\n and qy_min2 = qy_min + qy_min\n and qy_max2 = qy_max + qy_max\n\n val qx_min_eps = abs (qx_min) * dbl_epsilon\n and qx_max_eps = abs (qx_max) * dbl_epsilon\n val qy_min_eps = abs (qy_min) * dbl_epsilon\n and qy_max_eps = abs (qy_max) * dbl_epsilon\n in\n qx_min2 - qx_min_eps <= x.e1 + x.e1\n && x.e1 + x.e1 <= qx_max2 + qx_max_eps\n && qy_min2 - qy_min_eps <= x.e2 + x.e2\n && x.e2 + x.e2 <= qy_max2 + qy_max_eps\n end\n else\n false\n end\n else if x.e1 = 0.0 && x.e2 = 0.0 then\n (* The lines are coincident *)\n ~(max (qa.e1, qb.e1) < min (pa.e1, pb.e1)\n || max (pa.e1, pb.e1) < min (qa.e1, qb.e1))\n && ~(max (qa.e2, qb.e2) < min (pa.e2, pb.e2)\n || max (pa.e2, pb.e2) < min (qa.e2, qb.e2))\n else\n (* The lines are parallel. *)\n false\n end\n\n fn\n sides_intersection_tests () : bool =\n sides_intersect (t1.0, t1.1, s1.0, t2.0, t2.1, s2.0)\n || sides_intersect (t1.0, t1.1, s1.0, t2.1, t2.2, s2.1)\n || sides_intersect (t1.0, t1.1, s1.0, t2.2, t2.0, s2.2)\n || sides_intersect (t1.1, t1.2, s1.1, t2.0, t2.1, s2.0)\n || sides_intersect (t1.1, t1.2, s1.1, t2.1, t2.2, s2.1)\n || sides_intersect (t1.1, t1.2, s1.1, t2.2, t2.0, s2.2)\n || sides_intersect (t1.2, t1.0, s1.2, t2.0, t2.1, s2.0)\n || sides_intersect (t1.2, t1.0, s1.2, t2.1, t2.2, s2.1)\n || sides_intersect (t1.2, t1.0, s1.2, t2.2, t2.0, s2.2)\n\n fn\n points_approx_equal (p : point, q : point) : bool =\n let\n val @{e1 = px, e2 = py, e0 = _} = p\n and @{e1 = qx, e2 = qy, e0 = _} = q\n\n val x_max_eps = max (abs px, abs qx) * dbl_epsilon\n and y_max_eps = max (abs py, abs py) * dbl_epsilon\n in\n abs ((px + px) - (qx + qx)) <= x_max_eps\n && abs ((py + py) - (qy + qy)) <= y_max_eps\n end\n\n fn\n vertex_vertex_tests () : bool =\n points_approx_equal (t1.0, t2.0)\n || points_approx_equal (t1.0, t2.1)\n || points_approx_equal (t1.0, t2.2)\n || points_approx_equal (t1.1, t2.0)\n || points_approx_equal (t1.1, t2.1)\n || points_approx_equal (t1.1, t2.2)\n || points_approx_equal (t1.2, t2.0)\n || points_approx_equal (t1.2, t2.1)\n || points_approx_equal (t1.2, t2.2)\n\n fn\n is_inside (a : point, b : @(line, line, line)) : bool =\n which_side (a, b.0) = 1\n && which_side (a, b.1) = 1\n && which_side (a, b.2) = 1\n\n fn\n vertex_insideness_tests () : bool =\n is_inside (t1.0, s2)\n || is_inside (t1.1, s2)\n || is_inside (t1.2, s2)\n || is_inside (t2.0, s1)\n || is_inside (t2.1, s1)\n || is_inside (t2.2, s1)\n in\n sides_intersection_tests ()\n || vertex_vertex_tests ()\n || vertex_insideness_tests ()\n end\n\noverload overlap with overlap_triangle_triangle\n\nfn\nprintln_triangle (t : triangle) : void =\n println! (\"(\", t.0.e1, \",\", t.0.e2, \")--(\",\n t.1.e1, \",\", t.1.e2, \")--(\",\n t.2.e1, \",\", t.2.e2, \")--cycle\")\n\nfn\ntest_triangles (t1 : triangle, t2 : triangle) : void =\n begin\n println_triangle t1;\n println_triangle t2;\n println! (\" overlap: \", overlap (t1, t2))\n end\n\nimplement\nmain () =\n begin\n println! ();\n test_triangles (@(Pt (0.0, 0.0),\n Pt (5.0, 0.0),\n Pt (0.0, 5.0)),\n @(Pt (0.0, 0.0),\n Pt (5.0, 0.0),\n Pt (0.0, 6.0)));\n test_triangles (@(Pt (0.0, 0.0),\n Pt (0.0, 5.0),\n Pt (5.0, 0.0)),\n @(Pt (0.0, 0.0),\n Pt (0.0, 5.0),\n Pt (5.0, 0.0)));\n test_triangles (@(Pt (0.0, 0.0),\n Pt (5.0, 0.0),\n Pt (0.0, 5.0)),\n @(Pt (~10.0, 0.0),\n Pt ( ~5.0, 0.0),\n Pt ( ~1.0, 6.0)));\n test_triangles (@(Pt (0.0, 0.0),\n Pt (5.0, 0.0),\n Pt (2.5, 5.0)),\n @(Pt (0.0, 4.0),\n Pt (2.5, ~1.0),\n Pt (5.0, 4.0)));\n test_triangles (@(Pt (0.0, 0.0),\n Pt (1.0, 1.0),\n Pt (0.0, 2.0)),\n @(Pt (2.0, 1.0),\n Pt (3.0, 0.0),\n Pt (3.0, 2.0)));\n test_triangles (@(Pt (0.0, 0.0),\n Pt (1.0, 1.0),\n Pt (0.0, 2.0)),\n @(Pt (2.0, 1.0),\n Pt (3.0, ~2.0),\n Pt (3.0, 4.0)));\n test_triangles (@(Pt (0.0, 0.0),\n Pt (1.0, 0.0),\n Pt (0.0, 1.0)),\n @(Pt (1.0, 0.0),\n Pt (2.0, 0.0),\n Pt (1.0, 1.0)));\n\n println! ();\n println! (\"What follows is a test where one triangle is \",\n \"contained entirely\");\n println! (\"inside the other. Without such a test, our \",\n \"algorithm would have\");\n println! (\"one of its features undemonstrated.\");\n println! ();\n test_triangles (@(Pt ( 0.0, 0.0),\n Pt (10.0, 0.0),\n Pt ( 5.0, 10.0)),\n @(Pt ( 4.0, 1.0),\n Pt ( 5.0, 2.0),\n Pt ( 6.0, 1.0)));\n println! ();\n\n 0\n end\n", "language": "ATS" }, { "code": "TrianglesIntersect(T1, T2){\t\t; T1 := [[x1,y1],[x2,y2],[x3,y3]]\t, T2 :=[[x4,y4],[x5,y5],[x6,y6]]\n\tcounter := 0\n\tfor i, Pt in T1\n\t\tcounter += PointInTriangle(Pt, T2)\t; check if any coordinate of triangle 1 is inside triangle 2\n\tfor i, Pt in T2\n\t\tcounter += PointInTriangle(Pt, T1)\t; check if any coordinate of triangle 2 is inside triangle 1\n\t; check if sides of triangle 1 intersect with sides of triangle 2\n\tcounter += LinesIntersect([t1.1,t1.2],[t2.1,t2.2]) ? 1 : 0\n\tcounter += LinesIntersect([t1.1,t1.3],[t2.1,t2.2]) ? 1 : 0\n\tcounter += LinesIntersect([t1.2,t1.3],[t2.1,t2.2]) ? 1 : 0\n\t\n\tcounter += LinesIntersect([t1.1,t1.2],[t2.1,t2.3]) ? 1 : 0\n\tcounter += LinesIntersect([t1.1,t1.3],[t2.1,t2.3]) ? 1 : 0\n\tcounter += LinesIntersect([t1.2,t1.3],[t2.1,t2.3]) ? 1 : 0\n\t\n\tcounter += LinesIntersect([t1.1,t1.2],[t2.2,t2.3]) ? 1 : 0\n\tcounter += LinesIntersect([t1.1,t1.3],[t2.2,t2.3]) ? 1 : 0\n\tcounter += LinesIntersect([t1.2,t1.3],[t2.2,t2.3]) ? 1 : 0\n\treturn (counter>3) ; 3 points inside or 1 point inside and 2 lines intersect or 3 lines intersect\n}\nPointInTriangle(pt, Tr){\t; pt:=[x,y]\t, Tr := [[x1,y1],[x2,y2],[x3,y3]]\n\tv1 := Tr.1, v2 := Tr.2, v3 := Tr.3\n d1 := sign(pt, v1, v2)\n d2 := sign(pt, v2, v3)\n d3 := sign(pt, v3, v1)\n has_neg := (d1 < 0) || (d2 < 0) || (d3 < 0)\n has_pos := (d1 > 0) || (d2 > 0) || (d3 > 0)\n return !(has_neg && has_pos)\n}\nsign(p1, p2, p3){\n return (p1.1 - p3.1) * (p2.2 - p3.2) - (p2.1 - p3.1) * (p1.2 - p3.2)\n}\nLinesIntersect(L1, L2){\t\t; L1 := [[x1,y1],[x2,y2]]\t, L2 := [[x3,y3],[x4,y4]]\n\tx1 := L1[1,1], y1 := L1[1,2]\n\tx2 := L1[2,1], y2 := L1[2,2]\n\tx3 := L2[1,1], y3 := L2[1,2]\n\tx4 := L2[2,1], y4 := L2[2,2]\n\tx := ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4)) / ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4))\n\ty := ((x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)) / ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4))\n\tif (x<>\"\" && y<>\"\") && isBetween(x, x1, x2) && isBetween(x, x3, x4) && isBetween(y, y1, y2) && isBetween(y, y3, y4)\n\t\treturn 1\n}\nisBetween(x, p1, p2){\n\treturn !((x>p1 && x>p2) || (x<p1 && x<p2))\n}\n", "language": "AutoHotkey" }, { "code": "result := \"\"\nresult .= TrianglesIntersect([[0,0],[5,0],[0,5]],\t[[0,0],[5,0],[0,6]])\t\"`n\"\nresult .= TrianglesIntersect([[0,0],[0,5],[5,0]],\t[[0,0],[0,5],[5,0]])\t\"`n\"\nresult .= TrianglesIntersect([[0,0],[5,0],[0,5]],\t[[-10,0],[-5,0],[-1,6]])\"`n\"\nresult .= TrianglesIntersect([[0,0],[5,0],[2.5,5]],\t[[0,4],[2.5,-1],[5,4]])\t\"`n\"\nresult .= TrianglesIntersect([[0,0],[1,1],[0,2]],\t[[2,1],[3,0],[3,2]])\t\"`n\"\nresult .= TrianglesIntersect([[0,0],[1,1],[0,2]],\t[[2,1],[3,-2],[3,4]])\t\"`n\"\nresult .= TrianglesIntersect([[0,0],[1,0],[0,1]],\t[[1,0],[2,0],[1,1]])\t\"`n\"\nMsgBox % result\nreturn\n", "language": "AutoHotkey" }, { "code": "#include <errno.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n double x, y;\n} Point;\n\ndouble det2D(const Point * const p1, const Point * const p2, const Point * const p3) {\n return p1->x * (p2->y - p3->y)\n + p2->x * (p3->y - p1->y)\n + p3->x * (p1->y - p2->y);\n}\n\nvoid checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) {\n double detTri = det2D(p1, p2, p3);\n if (detTri < 0.0) {\n if (allowReversed) {\n double t = p3->x;\n p3->x = p2->x;\n p2->x = t;\n\n t = p3->y;\n p3->y = p2->y;\n p2->y = t;\n } else {\n errno = 1;\n }\n }\n}\n\nbool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) {\n return det2D(p1, p2, p3) < eps;\n}\n\nbool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) {\n return det2D(p1, p2, p3) <= eps;\n}\n\nbool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) {\n bool(*chkEdge)(Point*, Point*, Point*, double);\n int i;\n\n // Triangles must be expressed anti-clockwise\n checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed);\n if (errno != 0) {\n return false;\n }\n checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed);\n if (errno != 0) {\n return false;\n }\n\n if (onBoundary) {\n // Points on the boundary are considered as colliding\n chkEdge = boundaryCollideChk;\n } else {\n // Points on the boundary are not considered as colliding\n chkEdge = boundaryDoesntCollideChk;\n }\n\n //For edge E of trangle 1,\n for (i = 0; i < 3; ++i) {\n int j = (i + 1) % 3;\n\n //Check all points of trangle 2 lay on the external side of the edge E. If\n //they do, the triangles do not collide.\n if (chkEdge(&t1[i], &t1[j], &t2[0], eps) &&\n chkEdge(&t1[i], &t1[j], &t2[1], eps) &&\n chkEdge(&t1[i], &t1[j], &t2[2], eps)) {\n return false;\n }\n }\n\n //For edge E of trangle 2,\n for (i = 0; i < 3; i++) {\n int j = (i + 1) % 3;\n\n //Check all points of trangle 1 lay on the external side of the edge E. If\n //they do, the triangles do not collide.\n if (chkEdge(&t2[i], &t2[j], &t1[0], eps) &&\n chkEdge(&t2[i], &t2[j], &t1[1], eps) &&\n chkEdge(&t2[i], &t2[j], &t1[2], eps))\n return false;\n }\n\n //The triangles collide\n return true;\n}\n\nint main() {\n {\n Point t1[] = { {0, 0}, {5, 0}, {0, 5} };\n Point t2[] = { {0, 0}, {5, 0}, {0, 6} };\n printf(\"%d,true\\n\", triTri2D(t1, t2, 0.0, false, true));\n }\n\n {\n Point t1[] = { {0, 0}, {0, 5}, {5, 0} };\n Point t2[] = { {0, 0}, {0, 5}, {5, 0} };\n printf(\"%d,true\\n\", triTri2D(t1, t2, 0.0, true, true));\n }\n\n {\n Point t1[] = { {0, 0}, {5, 0}, {0, 5} };\n Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} };\n printf(\"%d,false\\n\", triTri2D(t1, t2, 0.0, false, true));\n }\n\n {\n Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} };\n Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} };\n printf(\"%d,true\\n\", triTri2D(t1, t2, 0.0, false, true));\n }\n\n {\n Point t1[] = { {0, 0}, {1, 1}, {0, 2} };\n Point t2[] = { {2, 1}, {3, 0}, {3, 2} };\n printf(\"%d,false\\n\", triTri2D(t1, t2, 0.0, false, true));\n }\n\n {\n Point t1[] = { {0, 0}, {1, 1}, {0, 2} };\n Point t2[] = { {2, 1}, {3, -2}, {3, 4} };\n printf(\"%d,false\\n\", triTri2D(t1, t2, 0.0, false, true));\n }\n\n //Barely touching\n {\n Point t1[] = { {0, 0}, {1, 0}, {0, 1} };\n Point t2[] = { {1, 0}, {2, 0}, {1, 1} };\n printf(\"%d,true\\n\", triTri2D(t1, t2, 0.0, false, true));\n }\n\n //Barely touching\n {\n Point t1[] = { {0, 0}, {1, 0}, {0, 1} };\n Point t2[] = { {1, 0}, {2, 0}, {1, 1} };\n printf(\"%d,false\\n\", triTri2D(t1, t2, 0.0, false, false));\n }\n\n return EXIT_SUCCESS;\n}\n", "language": "C" }, { "code": "#include <vector>\n#include <iostream>\n#include <stdexcept>\nusing namespace std;\n\ntypedef std::pair<double, double> TriPoint;\n\ninline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3)\n{\n\treturn +p1.first*(p2.second-p3.second)\n\t\t+p2.first*(p3.second-p1.second)\n\t\t+p3.first*(p1.second-p2.second);\n}\n\nvoid CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed)\n{\n\tdouble detTri = Det2D(p1, p2, p3);\n\tif(detTri < 0.0)\n\t{\n\t\tif (allowReversed)\n\t\t{\n\t\t\tTriPoint a = p3;\n\t\t\tp3 = p2;\n\t\t\tp2 = a;\n\t\t}\n\t\telse throw std::runtime_error(\"triangle has wrong winding direction\");\n\t}\n}\n\nbool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps)\n{\n\treturn Det2D(p1, p2, p3) < eps;\n}\n\nbool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps)\n{\n\treturn Det2D(p1, p2, p3) <= eps;\n}\n\nbool TriTri2D(TriPoint *t1,\n\tTriPoint *t2,\n\tdouble eps = 0.0, bool allowReversed = false, bool onBoundary = true)\n{\n\t//Trangles must be expressed anti-clockwise\n\tCheckTriWinding(t1[0], t1[1], t1[2], allowReversed);\n\tCheckTriWinding(t2[0], t2[1], t2[2], allowReversed);\n\n\tbool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL;\n\tif(onBoundary) //Points on the boundary are considered as colliding\n\t\tchkEdge = BoundaryCollideChk;\n\telse //Points on the boundary are not considered as colliding\n\t\tchkEdge = BoundaryDoesntCollideChk;\n\n\t//For edge E of trangle 1,\n\tfor(int i=0; i<3; i++)\n\t{\n\t\tint j=(i+1)%3;\n\n\t\t//Check all points of trangle 2 lay on the external side of the edge E. If\n\t\t//they do, the triangles do not collide.\n\t\tif (chkEdge(t1[i], t1[j], t2[0], eps) &&\n\t\t\tchkEdge(t1[i], t1[j], t2[1], eps) &&\n\t\t\tchkEdge(t1[i], t1[j], t2[2], eps))\n\t\t\treturn false;\n\t}\n\n\t//For edge E of trangle 2,\n\tfor(int i=0; i<3; i++)\n\t{\n\t\tint j=(i+1)%3;\n\n\t\t//Check all points of trangle 1 lay on the external side of the edge E. If\n\t\t//they do, the triangles do not collide.\n\t\tif (chkEdge(t2[i], t2[j], t1[0], eps) &&\n\t\t\tchkEdge(t2[i], t2[j], t1[1], eps) &&\n\t\t\tchkEdge(t2[i], t2[j], t1[2], eps))\n\t\t\treturn false;\n\t}\n\n\t//The triangles collide\n\treturn true;\n}\n\nint main()\n{\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)};\n\tTriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)};\n\tcout << TriTri2D(t1, t2) << \",\" << true << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)};\n\tTriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)};\n\tcout << TriTri2D(t1, t2, 0.0, true) << \",\" << true << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)};\n\tTriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)};\n\tcout << TriTri2D(t1, t2) << \",\" << false << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)};\n\tTriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)};\n\tcout << TriTri2D(t1, t2) << \",\" << true << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)};\n\tTriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)};\n\tcout << TriTri2D(t1, t2) << \",\" << false << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)};\n\tTriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)};\n\tcout << TriTri2D(t1, t2) << \",\" << false << endl;}\n\n\t//Barely touching\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)};\n\tTriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)};\n\tcout << TriTri2D(t1, t2, 0.0, false, true) << \",\" << true << endl;}\n\n\t//Barely touching\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)};\n\tTriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)};\n\tcout << TriTri2D(t1, t2, 0.0, false, false) << \",\" << false << endl;}\n\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\n\nnamespace TriangleOverlap {\n class Triangle {\n public Tuple<double, double> P1 { get; set; }\n public Tuple<double, double> P2 { get; set; }\n public Tuple<double, double> P3 { get; set; }\n\n public Triangle(Tuple<double, double> p1, Tuple<double, double> p2, Tuple<double, double> p3) {\n P1 = p1;\n P2 = p2;\n P3 = p3;\n }\n\n public double Det2D() {\n return P1.Item1 * (P2.Item2 - P3.Item2)\n + P2.Item1 * (P3.Item2 - P1.Item2)\n + P3.Item1 * (P3.Item1 - P2.Item2);\n }\n\n public void CheckTriWinding(bool allowReversed) {\n var detTri = Det2D();\n if (detTri < 0.0) {\n if (allowReversed) {\n var a = P3;\n P3 = P2;\n P2 = a;\n } else {\n throw new Exception(\"Triangle has wrong winding direction\");\n }\n }\n }\n\n public bool BoundaryCollideChk(double eps) {\n return Det2D() < eps;\n }\n\n public bool BoundaryDoesntCollideChk(double eps) {\n return Det2D() <= eps;\n }\n\n public override string ToString() {\n return string.Format(\"Triangle: {0}, {1}, {2}\", P1, P2, P3);\n }\n }\n\n class Program {\n static bool BoundaryCollideChk(Triangle t, double eps) {\n return t.BoundaryCollideChk(eps);\n }\n\n static bool BoundaryDoesntCollideChk(Triangle t, double eps) {\n return t.BoundaryDoesntCollideChk(eps);\n }\n\n static bool TriTri2D(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) {\n // Triangles must be expressed anti-clockwise\n t1.CheckTriWinding(allowReversed);\n t2.CheckTriWinding(allowReversed);\n // 'onBoundary' determines whether points on boundary are considered as colliding or not\n var chkEdge = onBoundary\n ? (Func<Triangle, double, bool>)BoundaryCollideChk\n : BoundaryDoesntCollideChk;\n List<Tuple<double, double>> lp1 = new List<Tuple<double, double>>() { t1.P1, t1.P2, t1.P3 };\n List<Tuple<double, double>> lp2 = new List<Tuple<double, double>>() { t2.P1, t2.P2, t2.P3 };\n\n // for each edge E of t1\n for (int i = 0; i < 3; i++) {\n var j = (i + 1) % 3;\n // Check all points of t2 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge(new Triangle(lp1[i], lp1[j], lp2[0]), eps) &&\n chkEdge(new Triangle(lp1[i], lp1[j], lp2[1]), eps) &&\n chkEdge(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) {\n return false;\n }\n }\n\n // for each edge E of t2\n for (int i = 0; i < 3; i++) {\n var j = (i + 1) % 3;\n // Check all points of t1 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge(new Triangle(lp2[i], lp2[j], lp1[0]), eps) &&\n chkEdge(new Triangle(lp2[i], lp2[j], lp1[1]), eps) &&\n chkEdge(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) {\n return false;\n }\n }\n\n // The triangles overlap\n return true;\n }\n\n static void Overlap(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) {\n if (TriTri2D(t1, t2, eps, allowReversed, onBoundary)) {\n Console.WriteLine(\"overlap\");\n } else {\n Console.WriteLine(\"do not overlap\");\n }\n }\n\n static void Main(string[] args) {\n var t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0));\n var t2 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 6.0));\n Console.WriteLine(\"{0} and\\n{1}\", t1, t2);\n Overlap(t1, t2);\n Console.WriteLine();\n\n // need to allow reversed for this pair to avoid exception\n t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(0.0, 5.0), new Tuple<double, double>(5.0, 0.0));\n t2 = t1;\n Console.WriteLine(\"{0} and\\n{1}\", t1, t2);\n Overlap(t1, t2, 0.0, true);\n Console.WriteLine();\n\n t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0));\n t2 = new Triangle(new Tuple<double, double>(-10.0, 0.0), new Tuple<double, double>(-5.0, 0.0), new Tuple<double, double>(-1.0, 6.0));\n Console.WriteLine(\"{0} and\\n{1}\", t1, t2);\n Overlap(t1, t2);\n Console.WriteLine();\n\n t1.P3 = new Tuple<double, double>(2.5, 5.0);\n t2 = new Triangle(new Tuple<double, double>(0.0, 4.0), new Tuple<double, double>(2.5, -1.0), new Tuple<double, double>(5.0, 4.0));\n Console.WriteLine(\"{0} and\\n{1}\", t1, t2);\n Overlap(t1, t2);\n Console.WriteLine();\n\n t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 1.0), new Tuple<double, double>(0.0, 2.0));\n t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, 0.0), new Tuple<double, double>(3.0, 2.0));\n Console.WriteLine(\"{0} and\\n{1}\", t1, t2);\n Overlap(t1, t2);\n Console.WriteLine();\n\n t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, -2.0), new Tuple<double, double>(3.0, 4.0));\n Console.WriteLine(\"{0} and\\n{1}\", t1, t2);\n Overlap(t1, t2);\n Console.WriteLine();\n\n t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(0.0, 1.0));\n t2 = new Triangle(new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(2.0, 0.0), new Tuple<double, double>(1.0, 1.1));\n Console.WriteLine(\"{0} and\\n{1}\", t1, t2);\n Console.WriteLine(\"which have only a single corner in contact, if boundary points collide\");\n Overlap(t1, t2);\n Console.WriteLine();\n\n Console.WriteLine(\"{0} and\\n{1}\", t1, t2);\n Console.WriteLine(\"which have only a single corner in contact, if boundary points do not collide\");\n Overlap(t1, t2, 0.0, false, false);\n }\n }\n}\n", "language": "C-sharp" }, { "code": "import std.stdio;\nimport std.typecons;\n\nalias Pair = Tuple!(real, real);\n\nstruct Triangle {\n Pair p1;\n Pair p2;\n Pair p3;\n\n void toString(scope void delegate(const(char)[]) sink) const {\n import std.format;\n sink(\"Triangle: \");\n formattedWrite!\"%s\"(sink, p1);\n sink(\", \");\n formattedWrite!\"%s\"(sink, p2);\n sink(\", \");\n formattedWrite!\"%s\"(sink, p3);\n }\n}\n\nauto det2D(Triangle t) {\n return t.p1[0] *(t.p2[1] - t.p3[1])\n + t.p2[0] *(t.p3[1] - t.p1[1])\n + t.p3[0] *(t.p1[1] - t.p2[1]);\n}\n\nvoid checkTriWinding(Triangle t, bool allowReversed) {\n auto detTri = t.det2D();\n if (detTri < 0.0) {\n if (allowReversed) {\n auto a = t.p3;\n t.p3 = t.p2;\n t.p2 = a;\n } else {\n throw new Exception(\"Triangle has wrong winding direction\");\n }\n }\n}\n\nauto boundaryCollideChk(Triangle t, real eps) {\n return t.det2D() < eps;\n}\n\nauto boundaryDoesntCollideChk(Triangle t, real eps) {\n return t.det2D() <= eps;\n}\n\nbool triTri2D(Triangle t1, Triangle t2, real eps = 0.0, bool allowReversed = false, bool onBoundary = true) {\n // Triangles must be expressed anti-clockwise\n checkTriWinding(t1, allowReversed);\n checkTriWinding(t2, allowReversed);\n // 'onBoundary' determines whether points on boundary are considered as colliding or not\n auto chkEdge = onBoundary ? &boundaryCollideChk : &boundaryDoesntCollideChk;\n auto lp1 = [t1.p1, t1.p2, t1.p3];\n auto lp2 = [t2.p1, t2.p2, t2.p3];\n\n // for each edge E of t1\n foreach (i; 0..3) {\n auto j = (i + 1) % 3;\n // Check all points of t2 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) &&\n chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) &&\n chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) {\n return false;\n }\n }\n\n // for each edge E of t2\n foreach (i; 0..3) {\n auto j = (i + 1) % 3;\n // Check all points of t1 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) &&\n chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) &&\n chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) {\n return false;\n }\n }\n\n // The triangles overlap\n return true;\n}\n\nvoid overlap(Triangle t1, Triangle t2, real eps = 0.0, bool allowReversed = false, bool onBoundary = true) {\n if (triTri2D(t1, t2, eps, allowReversed, onBoundary)) {\n writeln(\"overlap\");\n } else {\n writeln(\"do not overlap\");\n }\n}\n\nvoid main() {\n auto t1 = Triangle(Pair(0.0, 0.0), Pair(5.0, 0.0), Pair(0.0, 5.0));\n auto t2 = Triangle(Pair(0.0, 0.0), Pair(5.0, 0.0), Pair(0.0, 6.0));\n writeln(t1, \" and\\n\", t2);\n overlap(t1, t2);\n writeln;\n\n // need to allow reversed for this pair to avoid exception\n t1 = Triangle(Pair(0.0, 0.0), Pair(0.0, 5.0), Pair(5.0, 0.0));\n t2 = t1;\n writeln(t1, \" and\\n\", t2);\n overlap(t1, t2, 0.0, true);\n writeln;\n\n t1 = Triangle(Pair(0.0, 0.0), Pair(5.0, 0.0), Pair(0.0, 5.0));\n t2 = Triangle(Pair(-10.0, 0.0), Pair(-5.0, 0.0), Pair(-1.0, 6.0));\n writeln(t1, \" and\\n\", t2);\n overlap(t1, t2);\n writeln;\n\n t1.p3 = Pair(2.5, 5.0);\n t2 = Triangle(Pair(0.0, 4.0), Pair(2.5, -1.0), Pair(5.0, 4.0));\n writeln(t1, \" and\\n\", t2);\n overlap(t1, t2);\n writeln;\n\n t1 = Triangle(Pair(0.0, 0.0), Pair(1.0, 1.0), Pair(0.0, 2.0));\n t2 = Triangle(Pair(2.0, 1.0), Pair(3.0, 0.0), Pair(3.0, 2.0));\n writeln(t1, \" and\\n\", t2);\n overlap(t1, t2);\n writeln;\n\n t2 = Triangle(Pair(2.0, 1.0), Pair(3.0, -2.0), Pair(3.0, 4.0));\n writeln(t1, \" and\\n\", t2);\n overlap(t1, t2);\n writeln;\n\n t1 = Triangle(Pair(0.0, 0.0), Pair(1.0, 0.0), Pair(0.0, 1.0));\n t2 = Triangle(Pair(1.0, 0.0), Pair(2.0, 0.0), Pair(1.0, 1.1));\n writeln(t1, \" and\\n\", t2);\n writeln(\"which have only a single corner in contact, if boundary points collide\");\n overlap(t1, t2);\n writeln;\n\n writeln(t1, \" and\\n\", t2);\n writeln(\"which have only a single corner in contact, if boundary points do not collide\");\n overlap(t1, t2, 0.0, false, false);\n}\n", "language": "D" }, { "code": "func det2d t[][] .\n return t[1][1] * (t[2][2] - t[3][2]) + t[2][1] * (t[3][2] - t[1][2]) + t[3][1] * (t[1][2] - t[2][2])\n.\nproc triwind . t[][] .\n det = det2d t[][]\n if det < 0\n swap t[1][] t[2][]\n .\n.\nfunc overlap t1[][] t2[][] .\n triwind t1[][]\n triwind t2[][]\n for t to 2\n for i to 3\n j = (i + 1) mod1 3\n for k to 3\n if det2d [ t1[i][] t1[j][] t2[k][] ] >= 0\n break 1\n .\n .\n if k = 4\n return 0\n .\n .\n swap t1[][] t2[][]\n .\n return 1\n.\nprint overlap [ [ 0 0 ] [ 5 0 ] [ 0 5 ] ] [ [ 0 0 ] [ 5 0 ] [ 0 6 ] ]\nprint overlap [ [ 0 0 ] [ 0 5 ] [ 5 0 ] ] [ [ 0 0 ] [ 0 5 ] [ 5 0 ] ]\nprint overlap [ [ 0 0 ] [ 5 0 ] [ 0 5 ] ] [ [ -10 0 ] [ -5 0 ] [ -1 6 ] ]\nprint overlap [ [ 0 0 ] [ 5 0 ] [ 2.5 5 ] ] [ [ 0 4 ] [ 2.5 -1 ] [ 5 4 ] ]\nprint overlap [ [ 0 0 ] [ 1 1 ] [ 0 2 ] ] [ [ 2 1 ] [ 3 0 ] [ 3 2 ] ]\nprint overlap [ [ 0 0 ] [ 1 1 ] [ 0 2 ] ] [ [ 2 1 ] [ 3 -2 ] [ 3 4 ] ]\n", "language": "EasyLang" }, { "code": "open System\n\ntype Point = double * double\ntype Triangle = Point * Point * Point\n\nlet Det2D (t:Triangle) =\n let (p1, p2, p3) = t\n let (p1x, p1y) = p1\n let (p2x, p2y) = p2\n let (p3x, p3y) = p3\n\n p1x * (p2y - p3y) +\n p2x * (p3y - p1y) +\n p3x * (p1y - p2y)\n\nlet CheckTriWinding allowReversed t =\n let detTri = Det2D t\n if detTri < 0.0 then\n if allowReversed then\n let (p1, p2, p3) = t\n (p1, p3, p2)\n else\n raise (Exception \"Triangle has wrong winding direction\")\n else\n t\n\nlet boundaryCollideChk eps t =\n (Det2D t) < eps\n\nlet boundaryDoesntCollideChk eps t =\n (Det2D t) <= eps\n\nlet TriTri2D eps allowReversed onBoundary t1 t2 =\n // Triangles must be expressed anti-clockwise\n let t3 = CheckTriWinding allowReversed t1\n let t4 = CheckTriWinding allowReversed t2\n\n // 'onBoundary' determines whether points on boundary are considered as colliding or not\n let chkEdge = if onBoundary then boundaryCollideChk else boundaryDoesntCollideChk\n let (t1p1, t1p2, t1p3) = t3\n let (t2p1, t2p2, t2p3) = t4\n\n // Check all points of t2 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge eps (t1p1, t1p2, t2p1)) && (chkEdge eps (t1p1, t1p2, t2p2)) && (chkEdge eps (t1p1, t1p2, t2p3)) then\n false\n else if (chkEdge eps (t1p2, t1p3, t2p1)) && (chkEdge eps (t1p2, t1p3, t2p2)) && (chkEdge eps (t1p2, t1p3, t2p3)) then\n false\n else if (chkEdge eps (t1p3, t1p1, t2p1)) && (chkEdge eps (t1p3, t1p1, t2p2)) && (chkEdge eps (t1p3, t1p1, t2p3)) then\n false\n\n // Check all points of t1 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n else if (chkEdge eps (t2p1, t2p2, t1p1)) && (chkEdge eps (t2p1, t2p2, t1p2)) && (chkEdge eps (t2p1, t2p2, t1p3)) then\n false\n else if (chkEdge eps (t2p2, t2p3, t1p1)) && (chkEdge eps (t2p2, t2p3, t1p2)) && (chkEdge eps (t2p2, t2p3, t1p3)) then\n false\n else if (chkEdge eps (t2p3, t2p1, t1p1)) && (chkEdge eps (t2p3, t2p1, t1p2)) && (chkEdge eps (t2p3, t2p1, t1p3)) then\n false\n\n else\n // The triangles overlap\n true\n\nlet Print t1 t2 =\n Console.WriteLine(\"{0} and\\n{1}\\n{2}\\n\", t1, t2, if TriTri2D 0.0 false true t1 t2 then \"overlap\" else \"do not overlap\")\n\n[<EntryPoint>]\nlet main _ =\n let t1 = ((0.0, 0.0), (5.0, 0.0), (0.0, 5.0))\n let t2 = ((0.0, 0.0), (5.0, 0.0), (0.0, 6.0))\n Print t1 t2\n\n let t3 = ((0.0, 0.0), (0.0, 5.0), (5.0, 0.0))\n Console.WriteLine(\"{0} and\\n{1}\\n{2}\\n\", t3, t3, if TriTri2D 0.0 true true t3 t3 then \"overlap (reversed)\" else \"do not overlap\")\n\n let t4 = ((0.0, 0.0), (5.0, 0.0), (0.0, 5.0))\n let t5 = ((-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0))\n Print t4 t5\n\n let t6 = ((0.0, 0.0), (5.0, 0.0), (2.5, 5.0))\n let t7 = ((0.0, 4.0), (2.5, -1.0), (5.0, 4.0))\n Print t6 t7\n\n let t8 = ((0.0, 0.0), (1.0, 1.0), (0.0, 2.0))\n let t9 = ((2.0, 1.0), (3.0, 0.0), (3.0, 2.0))\n Print t8 t9\n\n let t10 = ((2.0, 1.0), (3.0, -2.0), (3.0, 4.0))\n Print t8 t10\n\n let t11 = ((0.0, 0.0), (1.0, 0.0), (0.0, 1.0))\n let t12 = ((1.0, 0.0), (2.0, 0.0), (1.0, 1.1))\n printfn \"The following triangles which have only a single corner in contact, if boundary points collide\"\n Print t11 t12\n\n Console.WriteLine(\"{0} and\\n{1}\\nwhich have only a single corner in contact, if boundary points do not collide\\n{2}\", t11, t12, if TriTri2D 0.0 false false t11 t12 then \"overlap\" else \"do not overlap\")\n\n 0 // return an integer exit code\n", "language": "F-Sharp" }, { "code": "#macro min(x,y)\n Iif(x>y,y,x)\n#endmacro\n#macro max(x,y)\n Iif(x>y,x,y)\n#endmacro\n\ntype pnt 'typedef for a point\n x as double\n y as double\nend type\n\ntype edg 'typedef for an edge\n p1 as pnt\n p2 as pnt\nend type\n\nfunction point_in_tri( r as pnt, a as pnt, b as pnt, c as pnt ) as boolean\n 'uses barycentric coordinates to determine whether point r is in the triangle defined by a, b, c\n dim as double k = ((b.y - c.y)*(a.x - c.x) + (c.x - b.x)*(a.y - c.y))\n dim as double v = ((b.y - c.y)*(r.x - c.x) + (c.x - b.x)*(r.y - c.y)) / k\n dim as double w = ((c.y - a.y)*(r.x - c.x) + (a.x - c.x)*(r.y - c.y)) / k\n dim as double z = 1 - v- w\n if v<0 or v>1 then return false\n if w<0 or w>1 then return false\n if z<0 or z>1 then return false\n return true\nend function\n\nfunction bbox_overlap( a1 as pnt, a2 as pnt, b1 as pnt, b2 as pnt) as boolean\n dim as double a1x = min(a1.x, a2.x), a1y = min(a1.y, a2.y)\n dim as double a2x = max(a1.x, a2.x), a2y = max(a1.y, a2.y)\n dim as double b1x = min(b1.x, b2.x), b1y = min(b1.y, b2.y)\n dim as double b2x = max(b1.x, b2.x), b2y = max(b1.y, b2.y)\n if a1x > b2x or b1x > a2x then return false\n if a1y > b2y or b2y > a2y then return false\n return true\nend function\n\nfunction ccw( a as pnt, b as pnt, c as pnt) as double\n return (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y)\nend function\n\nfunction line_intersect( a as edg, b as edg ) as boolean\n if ccw(a.p1, a.p2, b.p1)*ccw(a.p1, a.p2, b.p2) > 0 then return false\n if ccw(b.p1, b.p2, a.p1)*ccw(b.p1, b.p2, a.p2) > 0 then return false\n if not bbox_overlap( a.p1, a.p2, b.p1, b.p2 ) then return false\n return true\nend function\n\nfunction triangle_overlap( a() as pnt, b() as pnt ) as boolean\n 'if two triangles overlap then either a corner of one triangle is inside\n 'the other OR an edge of one triangle intersects an edge of the other.\n dim as uinteger i, j\n dim as edg c, d\n for i = 0 to 2\n if point_in_tri( a(i), b(0), b(1), b(2) ) then return true\n if point_in_tri( b(i), a(0), a(1), a(2) ) then return true\n c.p1.x = a(i).x\n c.p1.y = a(i).y\n c.p2.x = a((i+1) mod 3).x\n c.p2.y = a((i+1) mod 3).y\n for j = 0 to 2\n d.p1.x = b(i).x\n d.p1.y = b(i).y\n d.p2.x = b((i+1) mod 3).x\n d.p2.y = b((i+1) mod 3).y\n if line_intersect( c, d ) then return true\n next j\n next i\n return 00\nend function\n\ndata 0,0 , 5,0 , 0,5 , 0,0 , 5,0 , 0,6\ndata 0,0 , 0,5 , 5,0 , 0,0 , 0,5 , 5,0\ndata 0,0 , 5,0 , 0,5 , -10,0 , -5,0 , -1,6\ndata 0,0 , 5,0 , 2.5,5 , 0,4 , 2.5,-1 , 5,4\ndata 0,0 , 1,1 , 0,2 , 2,1 , 3,0 , 3,2\ndata 0,0 , 1,1 , 0,2 , 2,1 , 3,-2 , 3,4\ndata 0,0 , 1,0 , 0,1 , 1,0 , 2,0 , 1,1\n\ndim as uinteger t, i\ndim as pnt a(0 to 2), b(0 to 2)\n\nfor t = 1 to 7\n for i = 0 to 2\n read a(i).x, a(i).y\n next i\n for i = 0 to 2\n read b(i).x, b(i).y\n next i\n print triangle_overlap( a(), b() )\nnext t\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport \"fmt\"\n\ntype point struct {\n x, y float64\n}\n\nfunc (p point) String() string {\n return fmt.Sprintf(\"(%.1f, %.1f)\", p.x, p.y)\n}\n\ntype triangle struct {\n p1, p2, p3 point\n}\n\nfunc (t *triangle) String() string {\n return fmt.Sprintf(\"Triangle %s, %s, %s\", t.p1, t.p2, t.p3)\n}\n\nfunc (t *triangle) det2D() float64 {\n return t.p1.x * (t.p2.y - t.p3.y) +\n t.p2.x * (t.p3.y - t.p1.y) +\n t.p3.x * (t.p1.y - t.p2.y)\n}\n\nfunc (t *triangle) checkTriWinding(allowReversed bool) {\n detTri := t.det2D()\n if detTri < 0.0 {\n if allowReversed {\n a := t.p3\n t.p3 = t.p2\n t.p2 = a\n } else {\n panic(\"Triangle has wrong winding direction.\")\n }\n }\n}\n\nfunc boundaryCollideChk(t *triangle, eps float64) bool {\n return t.det2D() < eps\n}\n\nfunc boundaryDoesntCollideChk(t *triangle, eps float64) bool {\n return t.det2D() <= eps\n}\n\nfunc triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool {\n // Triangles must be expressed anti-clockwise.\n t1.checkTriWinding(allowReversed)\n t2.checkTriWinding(allowReversed)\n\n // 'onBoundary' determines whether points on boundary are considered as colliding or not.\n var chkEdge func (*triangle, float64) bool\n if onBoundary {\n chkEdge = boundaryCollideChk\n } else {\n chkEdge = boundaryDoesntCollideChk\n }\n lp1 := [3]point{t1.p1, t1.p2, t1.p3}\n lp2 := [3]point{t2.p1, t2.p2, t2.p3}\n\n // for each edge E of t1\n for i := 0; i < 3; i++ {\n j := (i + 1) % 3\n // Check all points of t2 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n tri1 := &triangle{lp1[i], lp1[j], lp2[0]}\n tri2 := &triangle{lp1[i], lp1[j], lp2[1]}\n tri3 := &triangle{lp1[i], lp1[j], lp2[2]}\n if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) {\n return false\n }\n }\n\n // for each edge E of t2\n for i := 0; i < 3; i++ {\n j := (i + 1) % 3\n // Check all points of t1 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n tri1 := &triangle{lp2[i], lp2[j], lp1[0]}\n tri2 := &triangle{lp2[i], lp2[j], lp1[1]}\n tri3 := &triangle{lp2[i], lp2[j], lp1[2]}\n if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) {\n return false\n }\n }\n\n // The triangles overlap.\n return true\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n if cond {\n return s1\n }\n return s2\n}\n\nfunc main() {\n t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}}\n t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}}\n fmt.Printf(\"%s and\\n%s\\n\", t1, t2)\n overlapping := triTri2D(t1, t2, 0.0, false, true)\n fmt.Println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n // Need to allow reversed for this pair to avoid panic.\n t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}}\n t2 = t1\n fmt.Printf(\"\\n%s and\\n%s\\n\", t1, t2)\n overlapping = triTri2D(t1, t2, 0.0, true, true)\n fmt.Println(iff(overlapping, \"overlap (reversed)\", \"do not overlap\"))\n\n t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}}\n t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}}\n fmt.Printf(\"\\n%s and\\n%s\\n\", t1, t2)\n overlapping = triTri2D(t1, t2, 0.0, false, true)\n fmt.Println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n t1.p3 = point{2.5, 5.0}\n t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}}\n fmt.Printf(\"\\n%s and\\n%s\\n\", t1, t2)\n overlapping = triTri2D(t1, t2, 0.0, false, true)\n fmt.Println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}}\n t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}}\n fmt.Printf(\"\\n%s and\\n%s\\n\", t1, t2)\n overlapping = triTri2D(t1, t2, 0.0, false, true)\n fmt.Println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}}\n fmt.Printf(\"\\n%s and\\n%s\\n\", t1, t2)\n overlapping = triTri2D(t1, t2, 0.0, false, true)\n fmt.Println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}}\n t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}}\n fmt.Printf(\"\\n%s and\\n%s\\n\", t1, t2)\n println(\"which have only a single corner in contact, if boundary points collide\")\n overlapping = triTri2D(t1, t2, 0.0, false, true)\n fmt.Println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n fmt.Printf(\"\\n%s and\\n%s\\n\", t1, t2)\n fmt.Println(\"which have only a single corner in contact, if boundary points do not collide\")\n overlapping = triTri2D(t1, t2, 0.0, false, false)\n fmt.Println(iff(overlapping, \"overlap\", \"do not overlap\"))\n}\n", "language": "Go" }, { "code": "import java.util.function.BiFunction\n\nclass TriangleOverlap {\n private static class Pair {\n double first\n double second\n\n Pair(double first, double second) {\n this.first = first\n this.second = second\n }\n\n @Override\n String toString() {\n return String.format(\"(%s, %s)\", first, second)\n }\n }\n\n private static class Triangle {\n Pair p1, p2, p3\n\n Triangle(Pair p1, Pair p2, Pair p3) {\n this.p1 = p1\n this.p2 = p2\n this.p3 = p3\n }\n\n @Override\n String toString() {\n return String.format(\"Triangle: %s, %s, %s\", p1, p2, p3)\n }\n }\n\n private static double det2D(Triangle t) {\n Pair p1 = t.p1\n Pair p2 = t.p2\n Pair p3 = t.p3\n return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second)\n }\n\n private static void checkTriWinding(Triangle t, boolean allowReversed) {\n double detTri = det2D(t)\n if (detTri < 0.0) {\n if (allowReversed) {\n Pair a = t.p3\n t.p3 = t.p2\n t.p2 = a\n } else throw new RuntimeException(\"Triangle has wrong winding direction\")\n }\n }\n\n private static boolean boundaryCollideChk(Triangle t, double eps) {\n return det2D(t) < eps\n }\n\n private static boolean boundaryDoesntCollideChk(Triangle t, double eps) {\n return det2D(t) <= eps\n }\n\n private static boolean triTri2D(Triangle t1, Triangle t2) {\n return triTri2D(t1, t2, 0.0, false, true)\n }\n\n private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) {\n return triTri2D(t1, t2, eps, allowedReversed, true)\n }\n\n private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) {\n // Triangles must be expressed anti-clockwise\n checkTriWinding(t1, allowedReversed)\n checkTriWinding(t2, allowedReversed)\n // 'onBoundary' determines whether points on boundary are considered as colliding or not\n BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap.&boundaryCollideChk : TriangleOverlap.&boundaryDoesntCollideChk\n Pair[] lp1 = [t1.p1, t1.p2, t1.p3]\n Pair[] lp2 = [t2.p1, t2.p2, t2.p3]\n\n // for each edge E of t1\n for (int i = 0; i < 3; ++i) {\n int j = (i + 1) % 3\n // Check all points of t2 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) &&\n chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) &&\n chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false\n }\n\n // for each edge E of t2\n for (int i = 0; i < 3; ++i) {\n int j = (i + 1) % 3\n // Check all points of t1 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) &&\n chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) &&\n chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false\n }\n\n // The triangles overlap\n return true\n }\n\n static void main(String[] args) {\n Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0))\n Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0))\n printf(\"%s and\\n%s\\n\", t1, t2)\n if (triTri2D(t1, t2)) {\n println(\"overlap\")\n } else {\n println(\"do not overlap\")\n }\n\n // need to allow reversed for this pair to avoid exception\n t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0))\n t2 = t1\n printf(\"\\n%s and\\n%s\\n\", t1, t2)\n if (triTri2D(t1, t2, 0.0, true)) {\n println(\"overlap (reversed)\")\n } else {\n println(\"do not overlap\")\n }\n\n t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0))\n t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0))\n printf(\"\\n%s and\\n%s\\n\", t1, t2)\n if (triTri2D(t1, t2)) {\n println(\"overlap\")\n } else {\n println(\"do not overlap\")\n }\n\n t1.p3 = new Pair(2.5, 5.0)\n t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0))\n printf(\"\\n%s and\\n%s\\n\", t1, t2)\n if (triTri2D(t1, t2)) {\n println(\"overlap\")\n } else {\n println(\"do not overlap\")\n }\n\n t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0))\n t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0))\n printf(\"\\n%s and\\n%s\\n\", t1, t2)\n if (triTri2D(t1, t2)) {\n println(\"overlap\")\n } else {\n println(\"do not overlap\")\n }\n\n t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0))\n printf(\"\\n%s and\\n%s\\n\", t1, t2)\n if (triTri2D(t1, t2)) {\n println(\"overlap\")\n } else {\n println(\"do not overlap\")\n }\n\n t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0))\n t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1))\n printf(\"\\n%s and\\n%s\\n\", t1, t2)\n println(\"which have only a single corner in contact, if boundary points collide\")\n if (triTri2D(t1, t2)) {\n println(\"overlap\")\n } else {\n println(\"do not overlap\")\n }\n\n printf(\"\\n%s and\\n%s\\n\", t1, t2)\n println(\"which have only a single corner in contact, if boundary points do not collide\")\n if (triTri2D(t1, t2, 0.0, false, false)) {\n println(\"overlap\")\n } else {\n println(\"do not overlap\")\n }\n }\n}\n", "language": "Groovy" }, { "code": "isOverlapping :: Triangle Double -> Triangle Double -> Bool\nisOverlapping t1 t2 = vertexInside || midLineInside\n where\n vertexInside =\n any (isInside t1) (vertices t2) ||\n any (isInside t2) (vertices t1)\n\n isInside t = (Outside /=) . overlapping t\n\n midLineInside =\n any (\\p -> isInside t1 p && isInside t2 p) midPoints\n\n midPoints =\n [ intersections l1 l2 | l1 <- midLines t1\n , l2 <- midLines t2 ]\n\n intersections (a1,b1,c1) (a2,b2,c2) =\n ( -(-b2*c1+b1*c2)/(a2*b1-a1*b2)\n , -(a2*c1-a1*c2)/(a2*b1-a1*b2) )\n\n midLines (Triangle a b c) =\n [line a b c, line b c a, line c a b]\n\n line (x,y) (ax, ay) (bx, by) =\n (ay+by-2*y, -ax-bx+2*x, -ay*x-by*x+ax*y+bx*y)\n\ntest = map (uncurry isOverlapping)\n [ (Triangle (0,0) (5,0) (0,5), Triangle (0,0) (5,0) (0,6))\n , (Triangle (0,0) (0,5) (5,0), Triangle (0,0) (0,5) (5,0))\n , (Triangle (0,0) (5,0) (0,5), Triangle (-10,0) (-5,0) (-1,6))\n , (Triangle (0,0) (5,0) (2.5,5), Triangle (0,4) (2.5,-1) (5,4))\n , (Triangle (0,0) (1,1) (0,2), Triangle (2,1) (3,0) (3,2))\n , (Triangle (0,0) (1,1) (0,2), Triangle (2,1) (3,-2) (3,4))\n , (Triangle (0,0) (1,0) (0,1), Triangle (1,0) (2,0) (1,1))]\n", "language": "Haskell" }, { "code": "import java.util.function.BiFunction;\n\npublic class TriangleOverlap {\n private static class Pair {\n double first;\n double second;\n\n Pair(double first, double second) {\n this.first = first;\n this.second = second;\n }\n\n @Override\n public String toString() {\n return String.format(\"(%s, %s)\", first, second);\n }\n }\n\n private static class Triangle {\n Pair p1, p2, p3;\n\n Triangle(Pair p1, Pair p2, Pair p3) {\n this.p1 = p1;\n this.p2 = p2;\n this.p3 = p3;\n }\n\n @Override\n public String toString() {\n return String.format(\"Triangle: %s, %s, %s\", p1, p2, p3);\n }\n }\n\n private static double det2D(Triangle t) {\n Pair p1 = t.p1;\n Pair p2 = t.p2;\n Pair p3 = t.p3;\n return p1.first * (p2.second - p3.second)\n + p2.first * (p3.second - p1.second)\n + p3.first * (p1.second - p2.second);\n }\n\n private static void checkTriWinding(Triangle t, boolean allowReversed) {\n double detTri = det2D(t);\n if (detTri < 0.0) {\n if (allowReversed) {\n Pair a = t.p3;\n t.p3 = t.p2;\n t.p2 = a;\n } else throw new RuntimeException(\"Triangle has wrong winding direction\");\n }\n }\n\n private static boolean boundaryCollideChk(Triangle t, double eps) {\n return det2D(t) < eps;\n }\n\n private static boolean boundaryDoesntCollideChk(Triangle t, double eps) {\n return det2D(t) <= eps;\n }\n\n private static boolean triTri2D(Triangle t1, Triangle t2) {\n return triTri2D(t1, t2, 0.0, false, true);\n }\n\n private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) {\n return triTri2D(t1, t2, eps, allowedReversed, true);\n }\n\n private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) {\n // Triangles must be expressed anti-clockwise\n checkTriWinding(t1, allowedReversed);\n checkTriWinding(t2, allowedReversed);\n // 'onBoundary' determines whether points on boundary are considered as colliding or not\n BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap::boundaryCollideChk : TriangleOverlap::boundaryDoesntCollideChk;\n Pair[] lp1 = new Pair[]{t1.p1, t1.p2, t1.p3};\n Pair[] lp2 = new Pair[]{t2.p1, t2.p2, t2.p3};\n\n // for each edge E of t1\n for (int i = 0; i < 3; ++i) {\n int j = (i + 1) % 3;\n // Check all points of t2 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) &&\n chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) &&\n chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false;\n }\n\n // for each edge E of t2\n for (int i = 0; i < 3; ++i) {\n int j = (i + 1) % 3;\n // Check all points of t1 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) &&\n chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) &&\n chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false;\n }\n\n // The triangles overlap\n return true;\n }\n\n public static void main(String[] args) {\n Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0));\n Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0));\n System.out.printf(\"%s and\\n%s\\n\", t1, t2);\n if (triTri2D(t1, t2)) {\n System.out.println(\"overlap\");\n } else {\n System.out.println(\"do not overlap\");\n }\n\n // need to allow reversed for this pair to avoid exception\n t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0));\n t2 = t1;\n System.out.printf(\"\\n%s and\\n%s\\n\", t1, t2);\n if (triTri2D(t1, t2, 0.0, true)) {\n System.out.println(\"overlap (reversed)\");\n } else {\n System.out.println(\"do not overlap\");\n }\n\n t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0));\n t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0));\n System.out.printf(\"\\n%s and\\n%s\\n\", t1, t2);\n if (triTri2D(t1, t2)) {\n System.out.println(\"overlap\");\n } else {\n System.out.println(\"do not overlap\");\n }\n\n t1.p3 = new Pair(2.5, 5.0);\n t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0));\n System.out.printf(\"\\n%s and\\n%s\\n\", t1, t2);\n if (triTri2D(t1, t2)) {\n System.out.println(\"overlap\");\n } else {\n System.out.println(\"do not overlap\");\n }\n\n t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0));\n t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0));\n System.out.printf(\"\\n%s and\\n%s\\n\", t1, t2);\n if (triTri2D(t1, t2)) {\n System.out.println(\"overlap\");\n } else {\n System.out.println(\"do not overlap\");\n }\n\n t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0));\n System.out.printf(\"\\n%s and\\n%s\\n\", t1, t2);\n if (triTri2D(t1, t2)) {\n System.out.println(\"overlap\");\n } else {\n System.out.println(\"do not overlap\");\n }\n\n t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0));\n t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1));\n System.out.printf(\"\\n%s and\\n%s\\n\", t1, t2);\n System.out.println(\"which have only a single corner in contact, if boundary points collide\");\n if (triTri2D(t1, t2)) {\n System.out.println(\"overlap\");\n } else {\n System.out.println(\"do not overlap\");\n }\n\n System.out.printf(\"\\n%s and\\n%s\\n\", t1, t2);\n System.out.println(\"which have only a single corner in contact, if boundary points do not collide\");\n if (triTri2D(t1, t2, 0.0, false, false)) {\n System.out.println(\"overlap\");\n } else {\n System.out.println(\"do not overlap\");\n }\n }\n}\n", "language": "Java" }, { "code": "# Points are realized as arrays of two numbers [x, y]\n\n# Triangles are realized as triples of Points [p1, p2, p3]\n\n# Input: a Triangle\ndef det2D:\n . as [ [$p1x, $p1y], [$p2x, $p2y], [$p3x, $p3y]]\n | $p1x * ($p2y - $p3y) +\n $p2x * ($p3y - $p1y) +\n $p3x * ($p1y - $p2y) ;\n\n# Input: a Triangle\ndef checkTriWinding(allowReversed):\n if det2D < 0\n then if allowReversed\n then . as [$p1, $p2, $p3]\n | [$p1, $p3, $p2 ]\n else \"Triangle has wrong winding direction\" | error\n end\n else .\n end;\n\ndef boundaryCollideChk(eps): det2D < eps;\n\ndef boundaryDoesntCollideChk(eps): det2D <= eps;\n\ndef triTri2D($t1; $t2; $eps; $allowReversed; $onBoundary):\n def chkEdge:\n if $onBoundary then boundaryCollideChk($eps)\n else boundaryDoesntCollideChk($eps)\n end;\n\n # Triangles must be expressed anti-clockwise\n ($t1|checkTriWinding($allowReversed))\n | ($t2|checkTriWinding($allowReversed))\n # 'onBoundary' determines whether points on boundary are considered as colliding or not\n # for each edge E of t1\n | first( range(0;3) as $i\n | (($i + 1) % 3) as $j\n # Check all points of t2 lie on the external side of edge E.\n # If they do, the triangles do not overlap.\n | if ([$t1[$i], $t1[$j], $t2[0]]| chkEdge) and\n ([$t1[$i], $t1[$j], $t2[1]]| chkEdge) and\n ([$t1[$i], $t1[$j], $t2[2]]| chkEdge)\n then 0\n else empty\n \t end) // true\n | if . == 0 then false\n else\n # for each edge E of t2\n first( range(0;3) as $i\n | (($i + 1) % 3) as $j\n # Check all points of t1 lie on the external side of edge E.\n # If they do, the triangles do not overlap.\n | if ([$t2[$i], $t2[$j], $t1[0]] | chkEdge) and\n ([$t2[$i], $t2[$j], $t1[1]] | chkEdge) and\n ([$t2[$i], $t2[$j], $t1[2]] | chkEdge)\n\t then 0\n\t else empty\n\t end) // true\n | if . == 0 then false\n else true # The triangles overlap\n end\n end ;\n", "language": "Jq" }, { "code": "def task:\n def t: \"Triangle: \";\n def printTris(t1; t2; nl):\n \"\\(nl)\\(t)\\(t1) and\\n\\(t)\\(t2)\" ;\n\n def overlap(t1; t2):\n if triTri2D(t1; t2; 0; false; true) then \"overlap\" else \"do not overlap\" end;\n\n def overlapr(t1; t2):\n if triTri2D(t1; t2; 0; true; true) then \"overlap (reversed)\" else \"do not overlap\" end;\n\n ([ [0, 0], [5, 0], [0, 5] ] as $t1\n | [ [0, 0], [5, 0], [0, 6] ] as $t2\n | printTris($t1; $t2; \"\"),\n overlap($t1; $t2) ),\n\n ([ [0, 0], [0, 5], [5, 0] ] as $t1\n | $t1 as $t2\n | printTris($t1; $t2; \"\\n\"),\n # need to allow reversed for this pair to avoid exception\n overlapr($t1; $t2) ),\n\n ([ [0, 0], [5, 0], [0, 5] ] as $t1\n | [ [-10, 0], [-5, 0], [-1, 6] ] as $t2\n | printTris($t1; $t2; \"\\n\"),\n overlap($t1; $t2) ),\n\n ([ [0, 0], [5, 0], [2.5, 5] ] as $t1\n | [ [0, 4], [2.5, -1], [5, 4] ] as $t2\n | printTris($t1; $t2; \"\\n\"),\n overlap($t1; $t2) ),\n\n ([ [0, 0], [1, 1], [0, 2] ] as $t1\n | ([ [2, 1], [3, 0], [3, 2] ] as $t2\n | printTris($t1; $t2; \"\\n\"),\n overlap($t1; $t2) ),\n ( [[2, 1], [3, -2], [3, 4]] as $t2\n | printTris($t1; $t2; \"\\n\"),\n overlap($t1; $t2) )),\n\n ([ [0, 0], [1, 0], [0, 1] ] as $t1\n | [ [1, 0], [2, 0], [1, 1.1] ] as $t2\n | (printTris($t1; $t2; \"\"),\n \"which have only a single corner in contact, if boundary points collide\",\n overlap($t1; $t2) ),\n\n (printTris($t1; $t2; \"\\n\"),\n \"which have only a single corner in contact, if boundary points do not collide\",\n if triTri2D($t1; $t2; 0; false; false) then \"overlap\" else \"do not overlap\" end) );\n\ntask\n", "language": "Jq" }, { "code": "module Triangles\n\nusing LinearAlgebra\n\nexport AntiClockwise, Both, StrictCheck, MildCheck\n\nabstract type Widing end\nstruct AntiClockwise <: Widing end\nstruct Both <: Widing end\n\nfunction _check_triangle_winding(t, widing::AntiClockwise)\n trisq = fill!(Matrix{eltype(t)}(undef, 3, 3), 1)\n trisq[:, 1:2] .= t\n det(trisq) < 0 && throw(ArgumentError(\"triangle has wrong winding direction\"))\n return trisq\nend\n\nfunction _check_triangle_winding(t, widing::Both)\n trisq = fill!(Matrix{eltype(t)}(undef, 3, 3), 1)\n trisq[:, 1:2] .= t\n if det(trisq) < 0\n tmp = trisq[2, :]\n trisq[2, :] .= trisq[1, :]\n trisq[1, :] .= tmp\n end\n return trisq\nend\n\nabstract type OnBoundaryCheck end\nstruct StrictCheck <: OnBoundaryCheck end\nstruct MildCheck <: OnBoundaryCheck end\n\n_checkedge(::StrictCheck, x, ϵ) = det(x) < ϵ\n_checkedge(::MildCheck, x, ϵ) = det(x) ≤ ϵ\n\nfunction overlap(T₁, T₂, onboundary::OnBoundaryCheck=MildCheck(),; ϵ=0.0, widing::Widing=AntiClockwise())\n # Trangles must be expressed anti-clockwise\n T₁ = _check_triangle_winding(T₁, widing)\n T₂ = _check_triangle_winding(T₂, widing)\n\n edge = similar(T₁)\n for (A, B) in ((T₁, T₂), (T₂, T₁)), i in 1:3\n circshift!(edge, A, (i, 0))\n @views if all(_checkedge(onboundary, vcat(edge[1:2, :], B[r, :]'), ϵ) for r in 1:3)\n return false\n end\n end\n\n return true\nend\n\nend # module Triangles\n", "language": "Julia" }, { "code": "using .Triangles\n\nt1 = [0 0; 5 0; 0 5]\nt2 = [0 0; 5 0; 0 6]\n@show Triangles.overlap(t1, t2)\n\nt1 = [0 0; 0 5; 5 0]\nt2 = [0 0; 0 6; 5 0]\n@show Triangles.overlap(t1, t2, widing=Both())\n\nt1 = [0 0; 5 0; 0 5]\nt2 = [-10 0; -5 0; -1 6]\n@show Triangles.overlap(t1, t2)\n\nt1 = [0 0; 5 0; 2.5 5]\nt2 = [0 4; 2.5 -1; 5 4]\n@show Triangles.overlap(t1, t2)\n\nt1 = [0 0; 1 1; 0 2]\nt2 = [2 1; 3 0; 3 2]\n@show Triangles.overlap(t1, t2)\n\nt1 = [0 0; 1 1; 0 2]\nt2 = [2 1; 3 -2; 3 4]\n@show Triangles.overlap(t1, t2)\n\n# Barely touching\nt1 = [0 0; 1 0; 0 1]\nt2 = [1 0; 2 0; 1 1]\n@show Triangles.overlap(t1, t2, StrictCheck())\n\n# Barely touching\nt1 = [0 0; 1 0; 0 1]\nt2 = [1 0; 2 0; 1 1]\n@show Triangles.overlap(t1, t2, MildCheck())\n", "language": "Julia" }, { "code": "// version 1.1.0\n\ntypealias Point = Pair<Double, Double>\n\ndata class Triangle(var p1: Point, var p2: Point, var p3: Point) {\n override fun toString() = \"Triangle: $p1, $p2, $p3\"\n}\n\nfun det2D(t: Triangle): Double {\n val (p1, p2, p3) = t\n return p1.first * (p2.second - p3.second) +\n p2.first * (p3.second - p1.second) +\n p3.first * (p1.second - p2.second)\n}\n\nfun checkTriWinding(t: Triangle, allowReversed: Boolean) {\n val detTri = det2D(t)\n if (detTri < 0.0) {\n if (allowReversed) {\n val a = t.p3\n\t t.p3 = t.p2\n\t t.p2 = a\n }\n else throw RuntimeException(\"Triangle has wrong winding direction\")\n }\n}\n\nfun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps\n\nfun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps\n\nfun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0,\n allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean {\n // Triangles must be expressed anti-clockwise\n checkTriWinding(t1, allowReversed)\n checkTriWinding(t2, allowReversed)\n // 'onBoundary' determines whether points on boundary are considered as colliding or not\n val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk\n val lp1 = listOf(t1.p1, t1.p2, t1.p3)\n val lp2 = listOf(t2.p1, t2.p2, t2.p3)\n\n // for each edge E of t1\n for (i in 0 until 3) {\n val j = (i + 1) % 3\n // Check all points of t2 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n\tif (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) &&\n chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) &&\n chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false\n }\n\n // for each edge E of t2\n for (i in 0 until 3) {\n val j = (i + 1) % 3\n // Check all points of t1 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) &&\n chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) &&\n chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false\n }\n\n // The triangles overlap\n return true\n}\n\nfun main(args: Array<String>) {\n var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0)\n var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0)\n println(\"$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n // need to allow reversed for this pair to avoid exception\n t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0)\n t2 = t1\n println(\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2, 0.0, true)) \"overlap (reversed)\" else \"do not overlap\")\n\n t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0)\n t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0)\n println(\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n t1.p3 = 2.5 to 5.0\n t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0)\n println(\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0)\n t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0)\n println(\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0)\n println(\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0)\n t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1)\n println(\"\\n$t1 and\\n$t2\")\n println(\"which have only a single corner in contact, if boundary points collide\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n println(\"\\n$t1 and\\n$t2\")\n println(\"which have only a single corner in contact, if boundary points do not collide\")\n println(if (triTri2D(t1, t2, 0.0, false, false)) \"overlap\" else \"do not overlap\")\n}\n", "language": "Kotlin" }, { "code": "Here we present a rasterized version based on a single function \"isInside\".\n\n1) isInside\n\nGiven A, B, C, P is in the triangle ABC if the three cross-products\nPA^PB, PB^PC and PC^PA are of equal sign.\n\n{def isInside\n {lambda {:a :b :c :p}\n {let { {:ax {car :a}} {:ay {cdr :a}}\n {:bx {car :b}} {:by {cdr :b}}\n {:cx {car :c}} {:cy {cdr :c}}\n {:px {car :p}} {:py {cdr :p}}\n } {let { {:w1 {- {* {- :px :ax} {- :cy :ay}}\n {* {- :cx :ax} {- :py :ay}} }}\n {:w2 {- {* {- :px :bx} {- :ay :by}}\n {* {- :ax :bx} {- :py :by}} }}\n {:w3 {- {* {- :px :cx} {- :by :cy}}\n {* {- :bx :cx} {- :py :cy}} }}\n } {or {and {>= :w1 0} {>= :w2 0} {>= :w3 0}}\n {and {< :w1 0} {< :w2 0} {< :w3 0}}} }}}}\n-> isInside\n\n2) overlapping\n\nFor every points in the rectangle surrounding two given triangles\nwe compute the number of points inside both. If it is null they don't overlap.\n\n{def overlap\n\n {def overlap.row\n {lambda {:p0 :p1 :p2 :q0 :q1 :q2 :w :h :y}\n {S.map {{lambda {:p0 :p1 :p2 :q0 :q1 :q2 :qp}\n {if {and {isInside :p0 :p1 :p2 :qp}\n {isInside :q0 :q1 :q2 :qp}}\n then x else}} :p0 :p1 :p2 :q0 :q1 :q2}\n {S.map {{lambda {:y :x} {cons :x :y}} :y}\n {S.serie :w :h} }}}}\n\n {lambda {:p0 :p1 :p2 :q0 :q1 :q2 :w :h}\n {S.length {S.map {overlap.row :p0 :p1 :p2 :q0 :q1 :q2 :w :h}\n {S.serie :w :h}} }}}\n-> overlap\n\nGiven coordonnees will just be scaled to become integers, here miltiplied by 10\n\n{overlap {cons 0 0} {cons 50 0} {cons 0 50}\n {cons 0 0} {cons 50 0} {cons 0 60} 0 60} -> 1326\n\n{overlap {cons 0 0} {cons 0 50} {cons 50 0}\n {cons 0 0} {cons 0 50} {cons 50 0} 0 50} -> 1176\n\n{overlap {cons 0 0} {cons 50 0} {cons 0 50}\n {cons -100 0} {cons -50 0} {cons -10 60} 100 60} -> 0\n\n{overlap {cons 0 0} {cons 50 0} {cons 25 50}\n {cons 0 40} {cons 25 -10} {cons 50 40} -10 50} -> 831\n\n{overlap {cons 0 0} {cons 10 10} {cons 0 20}\n {cons 20 10} {cons 30 0} {cons 30 20} 0 20} -> 0\n\n{overlap {cons 0 0} {cons 10 10} {cons 0 20}\n {cons 20 10} {cons 30 -20} {cons 40 40} -20 40} -> 0\n\n{overlap {cons 0 0} {cons 10 0} {cons 0 10}\n {cons 10 0} {cons 20 0} {cons 10 10} 0 20} -> 1\n\n3) plot\n\nThe first triangle is plotted with 1s, the second with 2s,\n the intersection with 3s, else with dots.\n\n{def plot\n {def plot.row\n {lambda {:p0 :p1 :p2 :q0 :q1 :q2 :w :h :y}\n {br}{S.replace \\s by in\n {S.map {{lambda {:p0 :p1 :p2 :q0 :q1 :q2 :qp}\n {let { {:isinp {isInside :p0 :p1 :p2 :qp}}\n {:isinq {isInside :q0 :q1 :q2 :qp}}\n } {if {and :isinp :isinq} then 3\n else {if :isnp then 1\n else {if :isnq then 2\n else .}}} }} :p0 :p1 :p2 :q0 :q1 :q2}\n {S.map {{lambda {:y :x} {cons :x :y}} :y}\n {S.serie :w :h} }}} }}\n {lambda {:p0 :p1 :p2 :q0 :q1 :q2 :w :h}\n {S.map {plot.row :p0 :p1 :p2 :q0 :q1 :q2 :w :h}\n {S.serie :w :h}} }}\n-> plot\n\n{plot {cons 0 0} {cons 30 0} {cons 30 30}\n {cons 5 10} {cons 25 10} {cons 5 25} 0 30}\n->\n\n1111111111111111111111111111111\n.111111111111111111111111111111\n..11111111111111111111111111111\n...1111111111111111111111111111\n....111111111111111111111111111\n.....11111111111111111111111111\n......1111111111111111111111111\n.......111111111111111111111111\n........11111111111111111111111\n.........1111111111111111111111\n.....22222333333333333333311111\n.....22222233333333333331111111\n.....22222223333333333311111111\n.....22222222333333333111111111\n.....22222222233333311111111111\n.....22222222223333111111111111\n.....22222222222331111111111111\n.....22222222222.11111111111111\n.....2222222222...1111111111111\n.....222222222.....111111111111\n.....2222222........11111111111\n.....222222..........1111111111\n.....22222............111111111\n.....222...............11111111\n.....22.................1111111\n.....2...................111111\n..........................11111\n...........................1111\n............................111\n.............................11\n..............................1\n", "language": "Lambdatalk" }, { "code": "function det2D(p1,p2,p3)\n return p1.x * (p2.y - p3.y)\n + p2.x * (p3.y - p1.y)\n + p3.x * (p1.y - p2.y)\nend\n\nfunction checkTriWinding(p1,p2,p3,allowReversed)\n local detTri = det2D(p1,p2,p3)\n if detTri < 0.0 then\n if allowReversed then\n local t = p3\n p3 = p2\n p2 = t\n else\n error(\"triangle has wrong winding direction\")\n end\n end\n return nil\nend\n\nfunction boundaryCollideChk(p1,p2,p3,eps)\n return det2D(p1,p2,p3) < eps\nend\n\nfunction boundaryDoesntCollideChk(p1,p2,p3,eps)\n return det2D(p1,p2,p3) <= eps\nend\n\nfunction triTri2D(t1,t2,eps,allowReversed,onBoundary)\n eps = eps or 0.0\n allowReversed = allowReversed or false\n onBoundary = onBoundary or true\n\n -- triangles must be expressed anti-clockwise\n checkTriWinding(t1[1], t1[2], t1[3], allowReversed)\n checkTriWinding(t2[1], t2[2], t2[3], allowReversed)\n\n local chkEdge\n if onBoundary then\n -- points on the boundary are considered as colliding\n chkEdge = boundaryCollideChk\n else\n -- points on the boundary are not considered as colliding\n chkEdge = boundaryDoesntCollideChk\n end\n\n -- for edge E of triangle 1\n for i=0,2 do\n local j = (i+1)%3\n\n -- check all points of triangle 2 lay on the external side of the edge E.\n -- If they do, the triangles do not collide\n if chkEdge(t1[i+1], t1[j+1], t2[1], eps) and\n chkEdge(t1[i+1], t1[j+1], t2[2], eps) and\n chkEdge(t1[i+1], t1[j+1], t2[3], eps) then\n return false\n end\n end\n\n -- for edge E of triangle 2\n for i=0,2 do\n local j = (i+1)%3\n\n -- check all points of triangle 1 lay on the external side of the edge E.\n -- If they do, the triangles do not collide\n if chkEdge(t2[i+1], t2[j+1], t1[1], eps) and\n chkEdge(t2[i+1], t2[j+1], t1[2], eps) and\n chkEdge(t2[i+1], t2[j+1], t1[3], eps) then\n return false\n end\n end\n\n -- the triangles collide\n return true\nend\n\nfunction formatTri(t)\n return \"Triangle: (\"..t[1].x..\", \"..t[1].y\n ..\"), (\"..t[2].x..\", \"..t[2].y\n ..\"), (\"..t[3].x..\", \"..t[3].y..\")\"\nend\n\nfunction overlap(t1,t2,eps,allowReversed,onBoundary)\n if triTri2D(t1,t2,eps,allowReversed,onBoundary) then\n return \"overlap\\n\"\n else\n return \"do not overlap\\n\"\n end\nend\n\n-- Main\nlocal t1 = {{x=0,y=0},{x=5,y=0},{x=0,y=5}}\nlocal t2 = {{x=0,y=0},{x=5,y=0},{x=0,y=6}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2))\n\nt1 = {{x=0,y=0},{x=0,y=5},{x=5,y=0}}\nt2 = {{x=0,y=0},{x=0,y=5},{x=5,y=0}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2,0.0,true))\n\nt1 = {{x=0,y=0},{x=5,y=0},{x=0,y=5}}\nt2 = {{x=-10,y=0},{x=-5,y=0},{x=-1,y=6}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2))\n\nt1 = {{x=0,y=0},{x=5,y=0},{x=2.5,y=5}}\nt2 = {{x=0,y=4},{x=2.5,y=-1},{x=5,y=4}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2))\n\nt1 = {{x=0,y=0},{x=1,y=1},{x=0,y=2}}\nt2 = {{x=2,y=1},{x=3,y=0},{x=3,y=2}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2))\n\nt1 = {{x=0,y=0},{x=1,y=1},{x=0,y=2}}\nt2 = {{x=2,y=1},{x=3,y=-2},{x=3,y=4}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2))\n\n-- Barely touching\nt1 = {{x=0,y=0},{x=1,y=0},{x=0,y=1}}\nt2 = {{x=1,y=0},{x=2,y=0},{x=1,y=1}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2,0.0,false,true))\n\n-- Barely touching\nlocal t1 = {{x=0,y=0},{x=1,y=0},{x=0,y=1}}\nlocal t2 = {{x=1,y=0},{x=2,y=0},{x=1,y=1}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2,0.0,false,false))\n", "language": "Lua" }, { "code": "p1 = Polygon@{{0, 0}, {5, 0}, {0, 5}};\np2 = Polygon@{{0, 0}, {5, 0}, {0, 6}};\n! RegionDisjoint[p1, p2]\n\np1 = Polygon@{{0, 0}, {0, 5}, {5, 0}};\np2 = Polygon@{{0, 0}, {0, 5}, {5, 0}};\n! RegionDisjoint[p1, p2]\n\np1 = Polygon@{{0, 0}, {5, 0}, {0, 5}};\np2 = Polygon@{{-10, 0}, {-5, 0}, {-1, 6}};\n! RegionDisjoint[p1, p2]\n\np1 = Polygon@{{0, 0}, {5, 0}, {2.5, 5}};\np2 = Polygon@{{0, 4}, {2.5, -1}, {5, 4}};\n! RegionDisjoint[p1, p2]\n\np1 = Polygon@{{0, 0}, {1, 1}, {0, 2}};\np2 = Polygon@{{2, 1}, {3, 0}, {3, 2}};\n! RegionDisjoint[p1, p2]\n\np1 = Polygon@{{0, 0}, {1, 1}, {0, 2}};\np2 = Polygon@{{2, 1}, {3, -2}, {3, 4}};\n! RegionDisjoint[p1, p2]\n\np1 = Polygon@{{0, 0}, {1, 0}, {0, 1}};\np2 = Polygon@{{1, 0}, {2, 0}, {1, 1}};\n! RegionDisjoint[p1, p2]\n", "language": "Mathematica" }, { "code": "MODULE Overlap;\nFROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE;\nFROM LongStr IMPORT RealToFixed;\nFROM Terminal IMPORT WriteString,WriteLn,ReadChar;\n\nTYPE\n Point = RECORD\n x,y : LONGREAL;\n END;\n Triangle = RECORD\n p1,p2,p3 : Point;\n END;\n\nVAR\n TextWinExSrc : ExceptionSource;\n\nPROCEDURE WritePoint(p : Point);\nVAR buf : ARRAY[0..31] OF CHAR;\nBEGIN\n WriteString(\"(\");\n RealToFixed(p.x, 2, buf);\n WriteString(buf);\n WriteString(\", \");\n RealToFixed(p.y, 2, buf);\n WriteString(buf);\n WriteString(\")\")\nEND WritePoint;\n\nPROCEDURE WriteTriangle(t : Triangle);\nBEGIN\n WriteString(\"Triangle: \");\n WritePoint(t.p1);\n WriteString(\", \");\n WritePoint(t.p2);\n WriteString(\", \");\n WritePoint(t.p3)\nEND WriteTriangle;\n\nPROCEDURE Det2D(p1,p2,p3 : Point) : LONGREAL;\nBEGIN\n RETURN p1.x * (p2.y - p3.y)\n + p2.x * (p3.y - p1.y)\n + p3.x * (p1.y - p2.y)\nEND Det2D;\n\nPROCEDURE CheckTriWinding(VAR p1,p2,p3 : Point; allowReversed : BOOLEAN);\nVAR\n detTri : LONGREAL;\n t : Point;\nBEGIN\n detTri := Det2D(p1, p2, p3);\n IF detTri < 0.0 THEN\n IF allowReversed THEN\n t := p3;\n p3 := p2;\n p2 := t\n ELSE\n RAISE(TextWinExSrc, 0, \"triangle has wrong winding direction\")\n END\n END\nEND CheckTriWinding;\n\nPROCEDURE BoundaryCollideChk(p1,p2,p3 : Point; eps : LONGREAL) : BOOLEAN;\nBEGIN\n RETURN Det2D(p1, p2, p3) < eps\nEND BoundaryCollideChk;\n\nPROCEDURE BoundaryDoesntCollideChk(p1,p2,p3 : Point; eps : LONGREAL) : BOOLEAN;\nBEGIN\n RETURN Det2D(p1, p2, p3) <= eps\nEND BoundaryDoesntCollideChk;\n\nPROCEDURE TriTri2D(t1,t2 : Triangle; eps : LONGREAL; allowReversed,onBoundary : BOOLEAN) : BOOLEAN;\nTYPE\n Points = ARRAY[0..2] OF Point;\nVAR\n chkEdge : PROCEDURE(Point, Point, Point, LONGREAL) : BOOLEAN;\n lp1,lp2 : Points;\n i,j : CARDINAL;\nBEGIN\n (* Triangles must be expressed anti-clockwise *)\n CheckTriWinding(t1.p1, t1.p2, t1.p3, allowReversed);\n CheckTriWinding(t2.p1, t2.p2, t2.p3, allowReversed);\n\n (* 'onBoundary' determines whether points on boundary are considered as colliding or not *)\n IF onBoundary THEN\n chkEdge := BoundaryCollideChk\n ELSE\n chkEdge := BoundaryDoesntCollideChk\n END;\n\n lp1 := Points{t1.p1, t1.p2, t1.p3};\n lp2 := Points{t2.p1, t2.p2, t2.p3};\n\n (* for each edge E of t1 *)\n FOR i:=0 TO 2 DO\n j := (i + 1) MOD 3;\n (* Check all points of t2 lay on the external side of edge E.\n If they do, the triangles do not overlap. *)\n IF chkEdge(lp1[i], lp1[j], lp2[0], eps)\n AND chkEdge(lp1[i], lp1[j], lp2[1], eps)\n AND chkEdge(lp1[i], lp1[j], lp2[2], eps)\n THEN\n RETURN FALSE\n END\n END;\n\n (* for each edge E of t2 *)\n FOR i:=0 TO 2 DO\n j := (i + 1) MOD 3;\n (* Check all points of t1 lay on the external side of edge E.\n If they do, the triangles do not overlap. *)\n IF chkEdge(lp2[i], lp2[j], lp1[0], eps)\n AND chkEdge(lp2[i], lp2[j], lp1[1], eps)\n AND chkEdge(lp2[i], lp2[j], lp1[2], eps)\n THEN\n RETURN FALSE\n END\n END;\n\n (* The triangles overlap *)\n RETURN TRUE\nEND TriTri2D;\n\nPROCEDURE CheckOverlap(t1,t2 : Triangle; eps : LONGREAL; allowReversed,onBoundary : BOOLEAN);\nBEGIN\n WriteTriangle(t1);\n WriteString(\" and\");\n WriteLn;\n WriteTriangle(t2);\n WriteLn;\n\n IF TriTri2D(t1, t2, eps, allowReversed, onBoundary) THEN\n WriteString(\"overlap\")\n ELSE\n WriteString(\"do not overlap\")\n END;\n WriteLn\nEND CheckOverlap;\n\n(* main *)\nVAR\n t1,t2 : Triangle;\nBEGIN\n t1 := Triangle{{0.0,0.0},{5.0,0.0},{0.0,5.0}};\n t2 := Triangle{{0.0,0.0},{5.0,0.0},{0.0,6.0}};\n CheckOverlap(t1, t2, 0.0, FALSE, TRUE);\n WriteLn;\n\n t1 := Triangle{{0.0,0.0},{0.0,5.0},{5.0,0.0}};\n t2 := Triangle{{0.0,0.0},{0.0,5.0},{5.0,0.0}};\n CheckOverlap(t1, t2, 0.0, TRUE, TRUE);\n WriteLn;\n\n t1 := Triangle{{0.0,0.0},{5.0,0.0},{0.0,5.0}};\n t2 := Triangle{{-10.0,0.0},{-5.0,0.0},{-1.0,6.0}};\n CheckOverlap(t1, t2, 0.0, FALSE, TRUE);\n WriteLn;\n\n t1 := Triangle{{0.0,0.0},{5.0,0.0},{2.5,5.0}};\n t2 := Triangle{{0.0,4.0},{2.5,-1.0},{5.0,4.0}};\n CheckOverlap(t1, t2, 0.0, FALSE, TRUE);\n WriteLn;\n\n t1 := Triangle{{0.0,0.0},{1.0,1.0},{0.0,2.0}};\n t2 := Triangle{{2.0,1.0},{3.0,0.0},{3.0,2.0}};\n CheckOverlap(t1, t2, 0.0, FALSE, TRUE);\n WriteLn;\n\n t1 := Triangle{{0.0,0.0},{1.0,1.0},{0.0,2.0}};\n t2 := Triangle{{2.0,1.0},{3.0,-2.0},{3.0,4.0}};\n CheckOverlap(t1, t2, 0.0, FALSE, TRUE);\n WriteLn;\n\n t1 := Triangle{{0.0,0.0},{1.0,0.0},{0.0,1.0}};\n t2 := Triangle{{1.0,0.0},{2.0,0.0},{1.0,1.1}};\n CheckOverlap(t1, t2, 0.0, FALSE, TRUE);\n WriteLn;\n\n t1 := Triangle{{0.0,0.0},{1.0,0.0},{0.0,1.0}};\n t2 := Triangle{{1.0,0.0},{2.0,0.0},{1.0,1.1}};\n CheckOverlap(t1, t2, 0.0, FALSE, FALSE);\n WriteLn;\n\n ReadChar\nEND Overlap.\n", "language": "Modula-2" }, { "code": "import strformat\n\ntype Point = tuple[x, y: float]\n\ntype Triangle = array[3, Point]\n\nfunc `$`(p: Point): string =\n fmt\"({p.x:.1f}, {p.y:.1f})\"\n\nfunc `$`(t: Triangle): string =\n fmt\"Triangle {t[0]}, {t[1]}, {t[2]}\"\n\nfunc det2D(t: Triangle): float =\n t[0].x * (t[1].y - t[2].y) +\n t[1].x * (t[2].y - t[0].y) +\n t[2].x * (t[0].y - t[1].y)\n\nfunc checkTriWinding(t: var Triangle; allowReversed: bool) =\n let det = t.det2D()\n if det < 0:\n if allowReversed:\n swap t[1], t[2]\n else:\n raise newException(ValueError, \"Triangle has wrong winding direction.\")\n\nfunc boundaryCollideChk(t: Triangle; eps: float): bool =\n t.det2D() < eps\n\nfunc boundaryDoesntCollideChk(t: Triangle; eps: float): bool =\n t.det2D() <= eps\n\nfunc triTri2D(t1, t2: var Triangle; eps = 0.0;\n allowReversed = false; onBoundary = true): bool =\n\n # Triangles must be expressed anti-clockwise.\n t1.checkTriWinding(allowReversed)\n t2.checkTriWinding(allowReversed)\n\n # \"onBoundary\" determines whether points on boundary are considered as colliding or not.\n let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk\n\n # For each edge E of t1.\n for i in 0..2:\n let j = (i + 1) mod 3\n # Check that all points of t2 lay on the external side of edge E.\n # If they do, the triangles do not overlap.\n if chkEdge([t1[i], t1[j], t2[0]], eps) and\n chkEdge([t1[i], t1[j], t2[1]], eps) and\n chkEdge([t1[i], t1[j], t2[2]], eps):\n return false\n\n # For each edge E of t2.\n for i in 0..2:\n let j = (i + 1) mod 3\n # Check that all points of t1 lay on the external side of edge E.\n # If they do, the triangles do not overlap.\n if chkEdge([t2[i], t2[j], t1[0]], eps) and\n chkEdge([t2[i], t2[j], t1[1]], eps) and\n chkEdge([t2[i], t2[j], t1[2]], eps):\n return false\n\n # The triangles overlap.\n result = true\n\n\nwhen isMainModule:\n\n var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)]\n var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)]\n echo t1, \" and\\n\", t2\n var overlapping = triTri2D(t1, t2, 0, false, true)\n echo if overlapping: \"overlap\\n\" else: \"do not overlap\\n\"\n\n # Need to allow reversed for this pair to avoid exception.\n t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)]\n t2 = t1\n echo t1, \" and\\n\", t2\n overlapping = triTri2D(t1, t2, 0, true, true)\n echo if overlapping: \"overlap (reversed)\\n\" else: \"do not overlap\\n\"\n\n t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)]\n t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)]\n echo t1, \" and\\n\", t2\n overlapping = triTri2D(t1, t2, 0, false, true)\n echo if overlapping: \"overlap\\n\" else: \"do not overlap\\n\"\n\n t1[2] = (2.5, 5.0)\n t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)]\n echo t1, \" and\\n\", t2\n overlapping = triTri2D(t1, t2, 0, false, true)\n echo if overlapping: \"overlap\\n\" else: \"do not overlap\\n\"\n\n t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)]\n t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)]\n echo t1, \" and\\n\", t2\n overlapping = triTri2D(t1, t2, 0, false, true)\n echo if overlapping: \"overlap\\n\" else: \"do not overlap\\n\"\n\n t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)]\n echo t1, \" and\\n\", t2\n overlapping = triTri2D(t1, t2, 0, false, true)\n echo if overlapping: \"overlap\\n\" else: \"do not overlap\\n\"\n\n t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)]\n t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)]\n echo t1, \" and\\n\", t2\n echo \"which have only a single corner in contact, if boundary points collide\"\n overlapping = triTri2D(t1, t2, 0, false, true)\n echo if overlapping: \"overlap\\n\" else: \"do not overlap\\n\"\n\n echo t1, \" and\\n\", t2\n echo \"which have only a single corner in contact, if boundary points do not collide\"\n overlapping = triTri2D(t1, t2, 0, false, false)\n echo if overlapping: \"overlap\\n\" else: \"do not overlap\\n\"\n", "language": "Nim" }, { "code": "/*--------------------------------------------------------------------\n* Determine if two triangles overlap\n* Fully (?) tested with integer coordinates of the 6 corners\n* This was/is an exercise with ooRexx\n* Removed the fraction arithmetic\n* add test for triangles' validity\n*-------------------------------------------------------------------*/\nParse Version v\noid='trioo.txt'; 'erase' oid\nCall o v\ncase=0\ncc=0\nCall trio_test '0 0 4 0 0 4 1 1 2 1 1 2'\nCall trio_test '0 0 0 6 8 3 8 0 8 8 0 3'\nCall trio_test '0 0 0 2 2 0 0 0 4 0 0 6'\n/* The task's specified input */\nCall trio_test '0 0 5 0 0 5 0 0 5 0 0 6'\nCall trio_test '0 0 0 5 5 0 0 0 0 5 5 0'\nCall trio_test '0 0 5 0 0 5 -10 0 -5 0 -1 6'\nCall trio_test '0 0 5 0 2.5 5 0 4 2.5 -1 5 4'\nCall trio_test '0 0 1 1 0 2 2 1 3 0 3 2'\nCall trio_test '0 0 1 1 0 2 2 1 3 -2 3 4'\nCall trio_test '0 0 1 0 0 1 1 0 2 0 1 1'\nCall trio_test '0 0 0 0 2 2 1 1 2 1 1 2' -- two points are identical\nCall trio_test '0 0 0 3 2 2 1 1 2 2 3 3' -- three points on a line\nExit\n/* Other test cases */\nCall trio_test '0 0 0 4 4 0 0 2 2 2 2 0'\nCall trio_test '0 0 0 5 5 0 0 0 0 5 5 0'\nCall trio_test '0 0 0 5 5 0 0 0 0 5 7 0'\nCall trio_test '0 0 1 0 0 1 1 0 2 0 1 1'\nCall trio_test '0 0 1 1 0 2 2 1 3 0 3 2'\nCall trio_test '0 0 1 1 0 2 2 1 3 -2 3 4'\nCall trio_test '0 0 2 0 2 2 3 3 5 3 5 5'\nCall trio_test '0 0 2 0 2 3 0 0 2 0 2 3'\nCall trio_test '0 0 4 0 0 4 0 2 2 0 2 2'\nCall trio_test '0 0 4 0 0 4 1 1 2 1 1 2'\nCall trio_test '0 0 5 0 0 2 5 0 8 0 4 8'\nCall trio_test '0 0 5 0 0 5 0 0 5 0 0 6'\nCall trio_test '0 0 5 0 0 5 -10 0 -5 0 -1 6'\nCall trio_test '0 0 5 0 0 5 -5 0 -1 6 -3 0'\nCall trio_test '0 0 5 0 3 5 0 4 3 -1 5 4'\nCall trio_test '0 0 6 0 4 6 1 1 4 2 7 1'\nCall trio_test '0 1 0 4 2 2 3 1 3 4 5 2'\nCall trio_test '1 0 3 0 2 2 1 3 3 3 2 2'\nCall trio_test '1 0 3 0 2 2 1 3 3 3 2 5'\nCall trio_test '1 1 4 2 7 1 0 0 8 0 4 8'\nCall trio_test '2 0 2 6 1 8 0 1 0 5 8 3'\nCall trio_test '0 0 4 0 0 4 1 1 2 1 1 2'\nSay case 'cases tested'\nSay cc\nExit\n\ntrio_test:\nParse Arg tlist\ncc+=1\ntlist=space(tlist)\ntl1=tlist ; Call trio_t tl1\nIf result=-1 Then Return\ntl2=reversex(tlist) ; Call trio_t tl2\ntl3=''\ntl=tlist\nDo While tl<>''\n Parse Var tl x y tl\n tl3=tl3 y x\n End\n Call trio_t tl3\ntl4=reversex(tl3) ; Call trio_t tl4\ntl5=subword(tl4,7) subword(tl4,1,6) ; Call trio_t tl5\ntl6=''\ntl=tlist\nDo While tl<>''\n Parse Var tl x y tl\n tl6=tl6 y x\n End\n Call trio_t tl6\nReturn\n\ntrio_t:\nParse Arg tlist\ntlist=space(tlist)\nSay '>' tlist\ncase+=1\nParse Arg ax ay bx by cx cy dx dy ex ey fx fy\n/*---------------------------------------------------------------------\n* First build the objects needed\n*--------------------------------------------------------------------*/\na=.point~new(ax,ay); b=.point~new(bx,by); c=.point~new(cx,cy)\nd=.point~new(dx,dy); e=.point~new(ex,ey); f=.point~new(fx,fy)\nIf area(a,b,c)=0 Then Do\n Say a b c 'is not a valid triangle'\n Return -1\n End\nIf area(d,e,f)=0 Then Do\n Say d e f 'is not a valid triangle'\n Return -1\n End\nabc=.triangle~new(a,b,c)\ndef=.triangle~new(d,e,f)\nCall o 'Triangle: ABC:' abc ,1\nCall o 'Edges of ABC:'; Do i=1 To 3; Call o ' 'abc~edge(i); End\nCall o 'Triangle: DEF:' def ,1\nCall o 'Edges of DEF:'; Do i=1 To 3; Call o ' 'def~edge(i); End\npixl=' '\nDo i=1 To 3\n pixl=pixl abc~draw(i,'O')\n pixl=pixl def~draw(i,'*')\n End\nres=0\nfc=0\ntouch=0\nbordl=''\nDo i=1 To 3\n p1=abc~point(i)\n p2=def~point(i)\n Do j=1 To 3\n e1=abc~edge(j)\n e2=def~edge(j)\n If e1~contains(p2) Then Do\n Call o e1 'contains' p2\n ps=p2~string\n If wordpos(ps,bordl)=0 Then Do\n bordl=bordl ps\n touch+=1\n End\n End\n Else\n Call o e1 'does not contain' p2 i j\n If e2~contains(p1) Then Do\n Call o e2 'contains' p1\n ps=p1~string\n If wordpos(ps,bordl)=0 Then Do\n bordl=bordl ps\n touch+=1\n End\n End\n Else\n Call o e2 'does not contain' p1\n End\n End\n\nwb=words(bordl) /* how many of them? */\nIf wb>0 Then\n Call o 'Corner(s) that touch the other triangle:' bordl,1\n\n/*---------------------------------------------------------------------\n* How many of them are corners of both triangles\n*--------------------------------------------------------------------*/\nm=0\ncmatch=''\ndo i=1 To 3\n If wordpos(abc~point(i),bordl)>0 &,\n wordpos(abc~point(i),def)>0 Then Do\n cmatch=cmatch abc~point(i)\n m+=1\n End\n End\n\n/*---------------------------------------------------------------------\n* With two or three touching corners we show the result and return\n*--------------------------------------------------------------------*/\nSelect\n When wb=3 Then Do /* all three touch */\n Call draw(pixl)\n Select\n When m=3 Then\n Call o 'Triangles are identical',1\n When m=2 Then\n Call o 'Triangles have an edge in common:' cmatch,1\n Otherwise\n Call o 'Triangles overlap and touch on' bordl,1\n End\n Call o '',1\n -- Pull .\n Return\n End\n When wb=2 Then Do /* two of them match */\n Call draw(pixl)\n If m=2 Then\n Call o 'Triangles have an edge in common:' cmatch,1\n Else\n Call o 'Triangles overlap and touch on' bordl,1\n Call o ''\n -- Pull .\n Return\n End\n When wb=1 Then Do /* one of them matches */\n Call o 'Triangles touch on' bordl,1 /* other parts may overlap */\n Call o ' we analyze further',1\n End\n Otherwise /* we know nothing yet */\n Nop\n End\n\n/*---------------------------------------------------------------------\n* Now we look for corners of abc that are within the triangle def\n*--------------------------------------------------------------------*/\nin_def=0\nDo i=1 To 3\n p=abc~point(i)\n Call o 'p ='p\n Call o 'def='def\n If def~contains(p) &,\n wordpos(p,bordl)=0 Then Do\n Call o def 'contains' p\n in_def+=1\n End\n End\n\nIf in_def=3 Then Do\n Call o abc 'is fully contained in' def,1\n Call o '',1\n Call draw(pixl)\n fc=1\n End\nres=(in_def>0)\n/*---------------------------------------------------------------------\n* Now we look for corners of def that are within the triangle abc\n*--------------------------------------------------------------------*/\nIf res=0 Then Do\n in_abc=0\n If res=0 Then Do\n Do i=1 To 3\n p=def~point(i)\n Call o 'p ='p\n Call o 'def='def\n If abc~contains(p) &,\n wordpos(p,bordl)=0 Then Do\n Call o abc 'contains' p\n in_abc+=1\n End\n End\n End\n If in_abc=3 Then Do\n Call o def 'is fully contained in' abc,1\n Call o '',1\n Call draw(pixl)\n fc=1\n End\n res=(in_abc>0)\n\n End\n\n/*---------------------------------------------------------------------\n* Now we check if some edge of abc crosses any edge of def\n*--------------------------------------------------------------------*/\nIf res=0 Then Do\n Do i=1 To 3\n Do j=1 To 3\n e1=abc~edge(i); Call o 'e1='e1\n e2=def~edge(j); Call o 'e2='e2\n Call o 'crossing???'\n res=e1~crosses(e2)\nIf res Then Do\n End\n If res Then\n Call o 'edges cross'\n Else\n Call o 'edges don''t cross'\n End\n End\n End\n\nIf fc=0 Then Do /* no fully contained */\n Call draw(pixl)\n If res=0 Then /* no overlap */\n If wb=1 Then /* but one touching corner */\n call o abc 'and' def 'don''t overlap but touch on' bordl,1\n Else\n call o abc 'and' def 'don''t overlap',1\n Else /* overlap */\n If wb>0 Then /* one touching corner */\n call o abc 'and' def 'overlap and touch on' bordl,1\n Else\n call o abc 'and' def 'overlap',1\n Call o '',1\n-- Pull .\n End\nReturn\n\n/*---------------------------------------------------------------------\n* And here are all the classes and methods needed:\n* point init, x, y, string\n* triangle init, point, edge, contains, string\n* edge init, p1, p2, kdx, contains, crosses, string\n*--------------------------------------------------------------------*/\n\n::class point public\n::attribute x\n::attribute y\n::method init\n expose x y\n use arg x,y\n::method string\n expose x y\n return \"(\"||x\",\"y\")\"\n\n::class triangle public\n::method init\n expose point edge\n use arg p1,p2,p3\n If area(p1,p2,p3)=0 Then Do\n Say p1 p2 p3 'is not a valid triangle!'\n Return .nil\n End\n point=.array~new\n point[1]=p1\n point[2]=p2\n point[3]=p3\n edge=.array~new\n Do i=1 To 3\n ia=i+1; If ia=4 Then ia=1\n edge[i]=.edge~new(point[i],point[ia])\n End\n::method point\n expose point\n use arg n\n Return point[n]\n::method edge\n expose edge\n use arg n\n Return edge[n]\n::method contains\n expose point edge\n use arg pp\n Call o self\n Call o 'pp='pp\n xmin=1.e9\n ymin=1.e9\n xmax=-1.e9\n ymax=-1.e9\n Do i=1 To 3\n e=edge[i]\n Parse Value e~kdx With ka.i da.i xa.i\n Call o show_g(ka.i,da.i,xa.i)\n p1=e~p1\n p2=e~p2\n xmin=min(xmin,p1~x,p2~x)\n xmax=max(xmax,p1~x,p2~x)\n ymin=min(ymin,p1~y,p2~y)\n ymax=max(ymax,p1~y,p2~y)\n End\n If pp~x<xmin|pp~x>xmax|pp~y<ymin|pp~y>ymax Then\n res=0\n Else Do\n e=edge[1]\n e2=edge[2]\n p1=e2~p1\n p2=e2~p2\n Call o 'e:' e\n Select\n When ka.1='*' Then Do\n y2=ka.2*pp~x+da.2\n y3=ka.3*pp~x+da.3\n res=between(y2,pp~y,y3)\n End\n When ka.2='*' Then Do\n y2=ka.1*pp~x+da.1\n res=between(p1~y,y2,p2~y)\n End\n Otherwise Do\n dap=pp~y-ka.1*pp~x\n If ka.3='*' Then\n x3=xa.3\n Else\n x3=(da.3-dap)/(ka.1-ka.3)\n x2=(da.2-dap)/(ka.1-ka.2)\n res=between(x2,pp~x,x3)\n End\n End\n End\n Return res\n::method string\n expose point\n ol=''\n Do p over point\n ol=ol p~string\n End\n return ol\n::method draw\n expose point\n Use Arg i,c\n p=self~point(i)\n Return p~x p~y c\n::class edge public\n::method init\n expose edge p1 p2\n use arg p1,p2\n edge=.array~new\n edge[1]=p1\n edge[2]=p2\n::method p1\n expose edge p1 p2\n return p1\n::method p2\n expose edge p1 p2\n return p2\n::method kdx\n expose edge p1 p2\n x1=p1~x\n y1=p1~y\n x2=p2~x\n y2=p2~y\n If x1=x2 Then Do\n Parse Value '*' '-' x1 With ka da xa\n Call o show_g(ka,da,xa)\n End\n Else Do\n ka=(y2-y1)/(x2-x1)\n da=y2-ka*x2\n xa='*'\n End\n Return ka da xa\n::method contains\n Use Arg p\n p1=self~p1\n p2=self~p2\n parse Value self~kdx With k d x\n If k='*' Then Do\n res=(p~x=p1~x)&between(p1~y,p~y,p2~y,'I')\n End\n Else Do\n ey=k*p~x+d\n res=(ey=p~y)&between(p1~x,p~x,p2~x,'I')\n End\n If res Then Call o self 'contains' p\n Else Call o self 'does not contain' p\n Return res\n::method crosses\n expose p1 p2\n Use Arg e\n q1=e~p1\n q2=e~p2\n Call o 'Test if' e 'crosses' self\n Call o self~kdx\n Call o e~kdx\n Parse Value self~kdx With ka da xa; Call o ka da xa\n Call o show_g(ka,da,xa)\n Parse Value e~kdx With kb db xb; Call o kb db xb\n Call o show_g(kb,db,xb)\n Call o 'ka='ka\n Call o 'kb='kb\n Select\n When ka='*' Then Do\n If kb='*' Then Do\n res=(xa=xb)\n End\n Else Do\n Call o 'kb='kb 'xa='||xa 'db='db\n yy=kb*xa+db\n res=between(q1~y,yy,q2~y)\n End\n End\n When kb='*' Then Do\n yy=ka*xb+da\n res=between(p1~y,yy,p2~y)\n End\n When ka=kb Then Do\n If da=db Then Do\n If min(p1~x,p2~x)>max(q1~x,q2~x) |,\n min(q1~x,q2~x)>max(p1~x,p2~x) Then\n res=0\n Else Do\n res=1\n End\n End\n Else\n res=0\n End\n Otherwise Do\n x=(db-da)/(ka-kb)\n y=ka*x+da\n Call o 'cross:' x y\n res=between(p1~x,x,p2~x)\n End\n End\n Return res\n::method string\n expose edge p1 p2\n ol=p1~string'-'p2~string\n return ol\n\n::routine between /* check if a number is between two others */\n Use Arg a,x,b,inc\n Call o 'between:' a x b\n Parse Var a anom '/' adenom\n Parse Var x xnom '/' xdenom\n Parse Var b bnom '/' bdenom\n If adenom='' Then adenom=1\n If xdenom='' Then xdenom=1\n If bdenom='' Then bdenom=1\n aa=anom*xdenom*bdenom\n xx=xnom*adenom*bdenom\n bb=bnom*xdenom*adenom\n If inc='I' Then\n res=sign(xx-aa)<>sign(xx-bb)\n Else\n res=sign(xx-aa)<>sign(xx-bb) & (xx-aa)*(xx-bb)<>0\n Call o a x b 'res='res\n Return res\n\n::routine show_g /* show a straight line's forula */\n/*---------------------------------------------------------------------\n* given slope, y-distance, and (special) x-value\n* compute y=k*x+d or, if a vertical line, k='*'; x=c\n*--------------------------------------------------------------------*/\n Use Arg k,d,x\n Select\n When k='*' Then res='x='||x /* vertical line */\n When k=0 Then res='y='d /* horizontal line */\n Otherwise Do /* ordinary line */\n Select\n When k=1 Then res='y=x'dd(d)\n When k=-1 Then res='y=-x'dd(d)\n Otherwise res='y='k'*x'dd(d)\n End\n End\n End\n Return res\n\n::routine dd /* prepare a displacement for presenting it in show_g */\n/*---------------------------------------------------------------------\n* prepare y-distance for display\n*--------------------------------------------------------------------*/\n Use Arg dd\n Select\n When dd=0 Then dd='' /* omit dd if it's zero */\n When dd<0 Then dd=dd /* use dd as is (-value) */\n Otherwise dd='+'dd /* prepend '+' to positive dd */\n End\n Return dd\n\n::routine o /* debug output */\n Use Arg txt,say\n If say=1 Then\n Say txt\n oid='trioo.txt'\n Return lineout(oid,txt)\n\n::routine draw\n Use Arg pixl\n Return /* remove to see the triangle corners */\n Say 'pixl='pixl\n pix.=' '\n Do While pixl<>''\n Parse Var pixl x y c pixl\n x=2*x+16; y=2*y+4\n If pix.x.y=' ' Then\n pix.x.y=c\n Else\n pix.x.y='+'\n End\n Do j= 20 To 0 By -1\n ol=''\n Do i=0 To 40\n ol=ol||pix.i.j\n End\n Say ol\n End\n Return\n::routine reversex\n Use Arg list\n n=words(list)\n res=word(list,n)\n Do i=n-1 to 1 By -1\n res=res word(list,i)\n End\n Return res\n\n::ROUTINE distpp PUBLIC --Compute the distance between the points A and B\n/***********************************************************************\n* Compute the distance between the points A and B\n***********************************************************************/\n Use Arg A,B\n ax=A~x; ay=A~y; bx=B~x; by=B~y\n res=rxCalcsqrt((bx-ax)**2+(by-ay)**2)\n Return res\n\n::ROUTINE area PUBLIC --Compute the area of the triangla A B C\n/***********************************************************************\n* Compute the area of the triangla A B C\n***********************************************************************/\n Use Arg A,B,C\n ax=A~x; ay=A~y; bx=B~x; by=B~y; cx=C~x; cy=C~y\n ab=distpp(A,B)\n bc=distpp(B,C)\n ca=distpp(C,A)\n s=(ab+bc+ca)/2\n area=rxCalcsqrt(s*(s-ab)*(s-bc)*(s-ca))\n Return area\n::REQUIRES rxMath Library\n", "language": "OoRexx" }, { "code": "program TrianglesOverlap;\n{\nThe program looks for a separating line between the triangles. It's known that\nonly the triangle sides (produced) need to be considered as possible separators\n(except in the degenerate case when both triangles are reduced to a point).\nIf there's a strong separator, i.e. one that is disjoint from at least one\nof the triangles, then the triangles are disjoint. If there's only a weak\nseparator, i.e. one that intersects both triangles, then the triangles intersect\nin a point or a line segment (this program doesn't work out which).\nIf there's no separator, then the triangles have an overlap of positive area.\n}\n{$IFDEF FPC}\n {$mode objfpc}{$H+}\n{$ENDIF}}\n\nuses Math, SysUtils;\n\n{$DEFINE USE_FP}\n{$IFDEF USE_FP}\ntype TCoordinate = double;\nconst TOLERANCE = 1.0E-6;\n{$ELSE}\ntype TCoordinate = integer;\nconst TOLERANCE = 0;\n{$ENDIF}\n\ntype TVertex = record\n x, y : TCoordinate;\nend;\n\nfunction Vertex( x_in, y_in : TCoordinate) : TVertex;\nbegin\n result.x := x_in;\n result.y := y_in;\nend;\n\n// Result of testing sides of a triangle for separator.\n// Values are arbitrary but must be in this numerical order\nconst\n SEP_NO_TEST = -1; // triangle is a single point, no sides to be tested\n SEP_NONE = 0; // didn't find a separator\n SEP_WEAK = 1; // found a weak separator only\n SEP_STRONG = 2; // found a strong separator\n\nfunction EqualVertices( V, W : TVertex) : boolean;\nbegin\n result := (Abs(V.x - W.x) <= TOLERANCE)\n and (Abs(V.y - W.y) <= TOLERANCE);\nend;\n\n// Determinant: twice the signed area of triangle PQR.\nfunction Det( P, Q, R : TVertex) : TCoordinate;\nbegin\n result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y;\nend;\n\n// Get result of trying sides of LMN as separators.\nfunction TrySides( L, M, N, P, Q, R : TVertex) : integer;\nvar\n s, sMin, sMax: TCoordinate;\n H, K : TVertex;\n\n function TestSide( V, W : TVertex) : integer;\n var\n detP, detQ, detR, tMin, tMax : TCoordinate;\n begin\n result := SEP_NONE;\n detP := Det( V, W, P);\n detQ := Det( V, W, Q);\n detR := Det( V, W, R);\n tMin := Math.Min( Math.Min( detP, detQ), detR);\n tMax := Math.Max( Math.Max( detP, detQ), detR);\n if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then\n result := SEP_STRONG\n else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then\n result := SEP_WEAK;\n end;\n\nbegin\n sMin := 0;\n sMax := 0;\n s := Det( L, M, N);\n if (s <> 0) then begin // L, M, N are not collinear\n if (s < 0) then sMin := s else sMax := s;\n // Once we've found a strong separator, there's no need for further testing\n result := TestSide( M, N);\n if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L));\n if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M));\n end\n else begin // s = 0 so L, M, N are collinear\n // Look for distinct vertices from among L, M, N\n H := L;\n K := M;\n if EqualVertices( H, K) then K := N;\n if EqualVertices( H, K) then result := SEP_NO_TEST // L = M = N\n else result := TestSide( H, K);\n end;\nend;\n\nfunction Algo_5( A, B, C, D, E, F : TVertex) : integer;\nbegin\n result := TrySides( A, B, C, D, E, F);\n if (result < SEP_STRONG) then begin\n result := Math.Max( result, TrySides( D, E, F, A, B, C));\n if (result = SEP_NO_TEST) then begin // A = B = C and D = E = F\n if EqualVertices( A, D) then result := SEP_WEAK\n else result := SEP_STRONG;\n end;\n end;\nend;\n\nprocedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy,\n Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate);\nvar\n ovStr : string;\nbegin\n case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy),\n Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of\n SEP_STRONG : ovStr := 'Disjoint';\n SEP_NONE : ovStr := 'Overlap';\n else ovStr := 'Borderline';\n end;\n WriteLn( SysUtils.Format(\n '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s',\n [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr]));\nend;\n\n// Main routine\nbegin\n TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6);\n TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0);\n TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6);\n TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4);\n TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2);\n TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4);\n TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1);\nend.\n", "language": "Pascal" }, { "code": "use strict;\nuse warnings;\n\nsub det2D {\n my $p1 = shift or die \"4 Missing first point\\n\";\n my $p2 = shift or die \"Missing second point\\n\";\n my $p3 = shift or die \"Missing third point\\n\";\n\n return $p1->{x} * ($p2->{y} - $p3->{y})\n + $p2->{x} * ($p3->{y} - $p1->{y})\n + $p3->{x} * ($p1->{y} - $p2->{y});\n}\n\nsub checkTriWinding {\n my $p1 = shift or die \"14 Missing first point\\n\";\n my $p2 = shift or die \"Missing second point\\n\";\n my $p3 = shift or die \"Missing third point\\n\";\n my $allowReversed = shift;\n\n my $detTri = det2D($p1, $$p2, $$p3);\n if ($detTri < 0.0) {\n if ($allowReversed) {\n my $t = $$p3;\n $$p3 = $$p2;\n $$p2 = $t;\n } else {\n die \"triangle has wrong winding direction\";\n }\n }\n return undef;\n}\n\nsub boundaryCollideChk {\n my $p1 = shift or die \"33 Missing first point\\n\";\n my $p2 = shift or die \"Missing second point\\n\";\n my $p3 = shift or die \"Missing third point\\n\";\n my $eps = shift;\n\n return det2D($p1, $p2, $p3) < $eps;\n}\n\nsub boundaryDoesntCollideChk {\n my $p1 = shift or die \"42 Missing first point\\n\";\n my $p2 = shift or die \"Missing second point\\n\";\n my $p3 = shift or die \"Missing third point\\n\";\n my $eps = shift;\n\n return det2D($p1, $p2, $p3) <= $eps;\n}\n\nsub triTri2D {\n my $t1 = shift or die \"Missing first triangle to calculate with\\n\";\n my $t2 = shift or die \"Missing second triangle to calculate with\\n\";\n my $eps = shift;\n my $allowReversed = shift;\n my $onBoundary = shift;\n\n # triangles must be expressed anti-clockwise\n checkTriWinding($t1->[0], \\$t1->[1], \\$t1->[2], $allowReversed);\n checkTriWinding($t2->[0], \\$t2->[1], \\$t2->[2], $allowReversed);\n\n my $chkEdge;\n if ($onBoundary) {\n # points on the boundary are considered as colliding\n $chkEdge = \\&boundaryCollideChk;\n } else {\n # points on the boundary are NOT considered as colliding\n $chkEdge = \\&boundaryDoesntCollideChk;\n }\n\n # for edge E of triangle 1\n foreach my $i (0, 1, 2) {\n my $j = ($i + 1) % 3;\n\n # check all points of triangle 2 lay on the external side of edge E\n # if they do, the triangles do not collide\n if ($chkEdge->($t1->[$i], $t1->[$j], $t2->[0], $eps)\n and $chkEdge->($t1->[$i], $t1->[$j], $t2->[1], $eps)\n and $chkEdge->($t1->[$i], $t1->[$j], $t2->[2], $eps)) {\n return 0; # false\n }\n }\n\n # for edge E of triangle 2\n foreach my $i (0, 1, 2) {\n my $j = ($i + 1) % 3;\n\n # check all points of triangle 1 lay on the external side of edge E\n # if they do, the triangles do not collide\n if ($chkEdge->($t2->[$i], $t2->[$j], $t1->[0], $eps)\n and $chkEdge->($t2->[$i], $t2->[$j], $t1->[1], $eps)\n and $chkEdge->($t2->[$i], $t2->[$j], $t1->[2], $eps)) {\n return 0; # false\n }\n }\n\n return 1; # true\n}\n\nsub formatTri {\n my $t = shift or die \"Missing triangle to format\\n\";\n my $p1 = $t->[0];\n my $p2 = $t->[1];\n my $p3 = $t->[2];\n return \"Triangle: ($p1->{x}, $p1->{y}), ($p2->{x}, $p2->{y}), ($p3->{x}, $p3->{y})\";\n}\n\nsub overlap {\n my $t1 = shift or die \"Missing first triangle to calculate with\\n\";\n my $t2 = shift or die \"Missing second triangle to calculate with\\n\";\n my $eps = shift;\n my $allowReversed = shift or 0; # false\n my $onBoundary = shift or 1; # true\n\n unless ($eps) {\n $eps = 0.0;\n }\n\n if (triTri2D($t1, $t2, $eps, $allowReversed, $onBoundary)) {\n return \"overlap\\n\";\n } else {\n return \"do not overlap\\n\";\n }\n}\n\n###################################################\n# Main\n###################################################\n\nmy @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5});\nmy @t2 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>6});\nprint formatTri(\\@t1), \" and\\n\", formatTri(\\@t2), \"\\n\", overlap(\\@t1, \\@t2), \"\\n\";\n\n@t1 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0});\n@t2 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0});\nprint formatTri(\\@t1), \" and\\n\", formatTri(\\@t2), \"\\n\", overlap(\\@t1, \\@t2, 0.0, 1), \"\\n\";\n\n@t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5});\n@t2 = ({x=>-10, y=>0}, {x=>-5, y=>0}, {x=>-1, y=>6});\nprint formatTri(\\@t1), \" and\\n\", formatTri(\\@t2), \"\\n\", overlap(\\@t1, \\@t2), \"\\n\";\n\n@t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>2.5, y=>5});\n@t2 = ({x=>0, y=>4}, {x=>2.5, y=>-1}, {x=>5, y=>4});\nprint formatTri(\\@t1), \" and\\n\", formatTri(\\@t2), \"\\n\", overlap(\\@t1, \\@t2), \"\\n\";\n\n@t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2});\n@t2 = ({x=>2, y=>1}, {x=>3, y=>0}, {x=>3, y=>2});\nprint formatTri(\\@t1), \" and\\n\", formatTri(\\@t2), \"\\n\", overlap(\\@t1, \\@t2), \"\\n\";\n\n@t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2});\n@t2 = ({x=>2, y=>1}, {x=>3, y=>-2}, {x=>3, y=>4});\nprint formatTri(\\@t1), \" and\\n\", formatTri(\\@t2), \"\\n\", overlap(\\@t1, \\@t2), \"\\n\";\n\n# Barely touching\n@t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1});\n@t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1});\nprint formatTri(\\@t1), \" and\\n\", formatTri(\\@t2), \"\\n\", overlap(\\@t1, \\@t2, 0.0, 0, 1), \"\\n\";\n\n# Barely touching\n@t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1});\n@t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1});\nprint formatTri(\\@t1), \" and\\n\", formatTri(\\@t2), \"\\n\", overlap(\\@t1, \\@t2, 0.0, 0, 0), \"\\n\";\n", "language": "Perl" }, { "code": "use strict;\nuse warnings;\nuse feature 'say';\n\nsub det2D {\n my($p1,$p2,$p3) = @_;\n return $p1->[0] * ($p2->[1] - $p3->[1])\n + $p2->[0] * ($p3->[1] - $p1->[1])\n + $p3->[0] * ($p1->[1] - $p2->[1]);\n}\n\n# triangles must be expressed anti-clockwise\nsub checkTriWinding {\n my($p1,$p2,$p3,$allowReversed) = @_;\n my $detTri = det2D($p1, $$p2, $$p3);\n if ($detTri < 0.0) {\n if ($allowReversed) { ($$p3,$$p2) = ($$p2,$$p3) }\n else { die \"triangle has wrong winding direction\" }\n }\n return undef;\n}\n\nsub check_edge {\n our($t1,$t2,$eps,$onBoundary) = @_;\n\n # points on the boundary may be considered as colliding, or not\n my $chkEdge = $onBoundary ? \\&boundaryCollideChk : \\&boundaryDoesntCollideChk;\n sub boundaryCollideChk { return det2D($_[0], $_[1], $_[2]) < $eps }\n sub boundaryDoesntCollideChk { return det2D($_[0], $_[1], $_[2]) <= $eps }\n\n # for edge E of triangle 1\n foreach my $i (0, 1, 2) {\n my $j = ($i + 1) % 3;\n\n # check all points of triangle 2 lay on the external side of edge E\n # if they do, the triangles do not collide\n if ($chkEdge->($$t1->[$i], $$t1->[$j], $$t2->[0], $eps)\n and $chkEdge->($$t1->[$i], $$t1->[$j], $$t2->[1], $eps)\n and $chkEdge->($$t1->[$i], $$t1->[$j], $$t2->[2], $eps)) {\n return 0; # false\n }\n }\n return 1;\n}\n\nsub triTri2D {\n my($t1,$t2,$eps,$allowReversed,$onBoundary) = @_;\n checkTriWinding($$t1->[0], \\$$t1->[1], \\$$t1->[2], $allowReversed);\n checkTriWinding($$t2->[0], \\$$t2->[1], \\$$t2->[2], $allowReversed);\n return check_edge($t1,$t2,$eps,$onBoundary) && check_edge($t2,$t1,$eps,$onBoundary);\n}\n\nsub formatTri {\n my $t = shift;\n my @pairs;\n push @pairs, sprintf \"%8s\", '(' . $$_[0] . ',' . $$_[1] . ')' for @$$t;\n join ', ', @pairs;\n}\n\nsub overlap {\n my $t1 = shift or die \"Missing first triangle to calculate with\\n\";\n my $t2 = shift or die \"Missing second triangle to calculate with\\n\";\n my $eps = shift || 0;\n my $allowReversed = shift || 1;\n my $onBoundary = shift || 1;\n\n my $triangles = formatTri($t1) . ' and ' . formatTri($t2);\n if (triTri2D($t1, $t2, $eps, $allowReversed, $onBoundary)) {\n return \" overlap:\" . $triangles;\n } else {\n return \"do not overlap:\" . $triangles;\n }\n}\n\nmy @tests = (\n [ [[0,0], [5,0], [0,5]], [ [0,0], [5,0], [0,6]] ],\n [ [[0,0], [0,5], [5,0]], [ [0,0], [0,5], [5,0]] ],\n [ [[0,0], [5,0], [0,5]], [ [-10,0], [-5,0], [-1,6]] ],\n [ [[0,0], [5,0], [2.5,5]], [ [0,4], [2.5,-1], [5,4]] ],\n [ [[0,0], [1,1], [0,2]], [ [2,1], [3,0], [3,2]] ],\n [ [[0,0], [1,1], [0,2]], [ [2,1], [3,-2], [3,4]] ], # barely touching\n [ [[0,0], [1,0], [0,1]], [ [1,0], [2,0], [1,1]], 0.0, 0, 0 ] # barely touching\n);\n\nsay overlap(\\$_->[0], \\$_->[1], $_->[2], $_->[3], $_->[4]) for @tests;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Determine_if_two_triangles_overlap.exw\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas</span>\n <span style=\"color: #004080;\">cdCanvas</span> <span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cdcanvas</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">triangles</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">}},{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">}}},</span>\n <span style=\"color: #0000FF;\">{{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}},{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}}},</span>\n <span style=\"color: #0000FF;\">{{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">}},{{-</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{-</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">}}},</span>\n <span style=\"color: #0000FF;\">{{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2.5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">}},{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2.5</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">}}},</span>\n <span style=\"color: #0000FF;\">{{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">}},{{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">}}},</span>\n <span style=\"color: #0000FF;\">{{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">}},{{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">}}},</span>\n <span style=\"color: #0000FF;\">{{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}},{{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}}},</span>\n <span style=\"color: #0000FF;\">{{{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}},{{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}}}}</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">draw_triangle</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasSetForeground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasBegin</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">CD_CLOSED_LINES</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #7060A8;\">cdCanvasVertex</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">cdCanvasEnd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">det2D</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">triangle</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">p1x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p1y</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">p2x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p2y</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">p3x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p3y</span><span style=\"color: #0000FF;\">}}</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">triangle</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">p1x</span><span style=\"color: #0000FF;\">*(</span><span style=\"color: #000000;\">p2y</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">p3y</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">p2x</span><span style=\"color: #0000FF;\">*(</span><span style=\"color: #000000;\">p3y</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">p1y</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">p3x</span><span style=\"color: #0000FF;\">*(</span><span style=\"color: #000000;\">p1y</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">p2y</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">bReversed</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">checkWinding</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">triangle</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">allowReversed</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">detTri</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">det2D</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">triangle</span><span style=\"color: #0000FF;\">);</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">detTri</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0.0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">allowReversed</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">bReversed</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #000000;\">triangle</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">extract</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">triangle</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">throw</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"triangle has wrong winding direction\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">triangle</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">overlap</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">t1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">epsilon</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0.0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">allowReversed</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">onBoundary</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- Trangles must be expressed anti-clockwise</span>\n <span style=\"color: #000000;\">bReversed</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">checkWinding</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">allowReversed</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">t2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">checkWinding</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">allowReversed</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #000080;font-style:italic;\">-- check t1 then t2</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">edge</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #000080;font-style:italic;\">-- check each edge</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">p1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">t1</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">edge</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">p2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">t1</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">edge</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000080;font-style:italic;\">-- Check all points of trangle 2 lay on the external side\n -- of the edge E. If they do, the triangles do not collide.</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">onside</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">compare</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">det2D</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">p1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]}),</span><span style=\"color: #000000;\">epsilon</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">onBoundary</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000080;font-style:italic;\">-- -- (the following incomprehensible one-liner is equivalent:)\n -- if compare(det2D({p1,p2,t2[k]}),epsilon)&gt;-onBoundary then exit end if</span>\n <span style=\"color: #000000;\">onside</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">onside</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">onBoundary</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"no overlap\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"no overlap (no boundary)\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">t1</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">t1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- flip and re-test</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">bReversed</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"overlap (reversed)\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"overlap\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">redraw_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasActivate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">cy</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">100</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">triangles</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">t1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">triangles</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">draw_triangle</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">CD_RED</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (smudge tests[1..2] by one\n -- pixel to show them better)</span>\n <span style=\"color: #000000;\">draw_triangle</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">CD_BLUE</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasSetForeground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_BLACK</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasText</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">40</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">overlap</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">t2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">4</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">cy</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">100</span>\n <span style=\"color: #000000;\">cx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">100</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">cx</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">300</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">cdCanvasFlush</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">map_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cdcanvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_IUP</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cddbuffer</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_DBUFFER</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cdcanvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasSetBackground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_WHITE</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">canvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"RASTERSIZE=1250x300\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallbacks</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"MAP_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"map_cb\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #008000;\">\"ACTION\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"redraw_cb\"</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`RESIZE=NO, TITLE=\"Triangle overlap\"`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"RASTERSIZE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "from __future__ import print_function\nimport numpy as np\n\ndef CheckTriWinding(tri, allowReversed):\n\ttrisq = np.ones((3,3))\n\ttrisq[:,0:2] = np.array(tri)\n\tdetTri = np.linalg.det(trisq)\n\tif detTri < 0.0:\n\t\tif allowReversed:\n\t\t\ta = trisq[2,:].copy()\n\t\t\ttrisq[2,:] = trisq[1,:]\n\t\t\ttrisq[1,:] = a\n\t\telse: raise ValueError(\"triangle has wrong winding direction\")\n\treturn trisq\n\ndef TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True):\n\t#Trangles must be expressed anti-clockwise\n\tt1s = CheckTriWinding(t1, allowReversed)\n\tt2s = CheckTriWinding(t2, allowReversed)\n\n\tif onBoundary:\n\t\t#Points on the boundary are considered as colliding\n\t\tchkEdge = lambda x: np.linalg.det(x) < eps\n\telse:\n\t\t#Points on the boundary are not considered as colliding\n\t\tchkEdge = lambda x: np.linalg.det(x) <= eps\n\n\t#For edge E of trangle 1,\n\tfor i in range(3):\n\t\tedge = np.roll(t1s, i, axis=0)[:2,:]\n\n\t\t#Check all points of trangle 2 lay on the external side of the edge E. If\n\t\t#they do, the triangles do not collide.\n\t\tif (chkEdge(np.vstack((edge, t2s[0]))) and\n\t\t\tchkEdge(np.vstack((edge, t2s[1]))) and\n\t\t\tchkEdge(np.vstack((edge, t2s[2])))):\n\t\t\treturn False\n\n\t#For edge E of trangle 2,\n\tfor i in range(3):\n\t\tedge = np.roll(t2s, i, axis=0)[:2,:]\n\n\t\t#Check all points of trangle 1 lay on the external side of the edge E. If\n\t\t#they do, the triangles do not collide.\n\t\tif (chkEdge(np.vstack((edge, t1s[0]))) and\n\t\t\tchkEdge(np.vstack((edge, t1s[1]))) and\n\t\t\tchkEdge(np.vstack((edge, t1s[2])))):\n\t\t\treturn False\n\n\t#The triangles collide\n\treturn True\n\nif __name__==\"__main__\":\n\tt1 = [[0,0],[5,0],[0,5]]\n\tt2 = [[0,0],[5,0],[0,6]]\n\tprint (TriTri2D(t1, t2), True)\n\n\tt1 = [[0,0],[0,5],[5,0]]\n\tt2 = [[0,0],[0,6],[5,0]]\n\tprint (TriTri2D(t1, t2, allowReversed = True), True)\n\n\tt1 = [[0,0],[5,0],[0,5]]\n\tt2 = [[-10,0],[-5,0],[-1,6]]\n\tprint (TriTri2D(t1, t2), False)\n\n\tt1 = [[0,0],[5,0],[2.5,5]]\n\tt2 = [[0,4],[2.5,-1],[5,4]]\n\tprint (TriTri2D(t1, t2), True)\n\n\tt1 = [[0,0],[1,1],[0,2]]\n\tt2 = [[2,1],[3,0],[3,2]]\n\tprint (TriTri2D(t1, t2), False)\n\n\tt1 = [[0,0],[1,1],[0,2]]\n\tt2 = [[2,1],[3,-2],[3,4]]\n\tprint (TriTri2D(t1, t2), False)\n\n\t#Barely touching\n\tt1 = [[0,0],[1,0],[0,1]]\n\tt2 = [[1,0],[2,0],[1,1]]\n\tprint (TriTri2D(t1, t2, onBoundary = True), True)\n\n\t#Barely touching\n\tt1 = [[0,0],[1,0],[0,1]]\n\tt2 = [[1,0],[2,0],[1,1]]\n\tprint (TriTri2D(t1, t2, onBoundary = False), False)\n", "language": "Python" }, { "code": "from __future__ import print_function\nfrom shapely.geometry import Polygon\n\ndef PolyOverlaps(poly1, poly2):\n\tpoly1s = Polygon(poly1)\n\tpoly2s = Polygon(poly2)\n\treturn poly1s.intersects(poly2s)\n\nif __name__==\"__main__\":\n\tt1 = [[0,0],[5,0],[0,5]]\n\tt2 = [[0,0],[5,0],[0,6]]\n\tprint (PolyOverlaps(t1, t2), True)\n\n\tt1 = [[0,0],[0,5],[5,0]]\n\tt2 = [[0,0],[0,6],[5,0]]\n\tprint (PolyOverlaps(t1, t2), True)\n\n\tt1 = [[0,0],[5,0],[0,5]]\n\tt2 = [[-10,0],[-5,0],[-1,6]]\n\tprint (PolyOverlaps(t1, t2), False)\n\n\tt1 = [[0,0],[5,0],[2.5,5]]\n\tt2 = [[0,4],[2.5,-1],[5,4]]\n\tprint (PolyOverlaps(t1, t2), True)\n\n\tt1 = [[0,0],[1,1],[0,2]]\n\tt2 = [[2,1],[3,0],[3,2]]\n\tprint (PolyOverlaps(t1, t2), False)\n\n\tt1 = [[0,0],[1,1],[0,2]]\n\tt2 = [[2,1],[3,-2],[3,4]]\n\tprint (PolyOverlaps(t1, t2), False)\n\n\t#Barely touching\n\tt1 = [[0,0],[1,0],[0,1]]\n\tt2 = [[1,0],[2,0],[1,1]]\n\tprint (PolyOverlaps(t1, t2), \"?\")\n", "language": "Python" }, { "code": "DATA 0,0,5,0,0,5,0,0,5,0,0,6\nDATA 0,0,0,5,5,0,0,0,0,5,5,0\nDATA 0,0,5,0,0,5,-10,0,-5,0,-1,6\nDATA 0,0,5,0,2.5,5,0,4,2.5,-1,5,4\nDATA 0,0,1,1,0,2,2,1,3,0,3,2\nDATA 0,0,1,1,0,2,2,1,3,-2,3,4\n\nTYPE point\n x AS INTEGER\n y AS INTEGER\nEND TYPE\n\nDIM coord(12, 3) AS point\n\nworkscreen = _NEWIMAGE(800, 800, 32)\nbackscreen = _NEWIMAGE(800, 800, 32)\n\nSCREEN workscreen\nFOR i = 1 TO 12 '12 triangles\n FOR j = 1 TO 3 'with 3 coordinates for each\n READ coord(i, j).x 'X coord\n READ coord(i, j).y 'Y coord\n FixCoord coord(i, j)\n NEXT\n\nNEXT\n_DELAY .5\n_SCREENMOVE _MIDDLE\n\n\nFOR i = 1 TO 12\n _DEST workscreen\n CLS\n _DEST backscreen\n _DONTBLEND\n CLS , 0\n PSET (coord(i, 1).x, coord(i, 1).y), _RGBA32(255, 255, 255, 128)\n FOR j = 2 TO 3\n LINE -(coord(i, j).x, coord(i, j).y), _RGBA32(255, 255, 255, 128)\n NEXT\n LINE -(coord(i, 1).x, coord(i, 1).y), _RGBA32(255, 255, 255, 128)\n xinside = (coord(i, 1).x + coord(i, 2).x + coord(i, 3).x) / 3\n yinside = (coord(i, 1).y + coord(i, 2).y + coord(i, 3).y) / 3\n PAINT (xinside, yinside), _RGBA32(255, 255, 255, 128)\n _BLEND\n _PUTIMAGE , backscreen, 0\n CLS , 0\n _DONTBLEND\n i = i + 1\n PSET (coord(i, 1).x, coord(i, 1).y), _RGBA32(255, 0, 0, 128)\n FOR j = 2 TO 3\n LINE -(coord(i, j).x, coord(i, j).y), _RGBA32(255, 0, 0, 128)\n NEXT\n LINE -(coord(i, 1).x, coord(i, 1).y), _RGBA32(255, 0, 0, 128)\n xinside = (coord(i, 1).x + coord(i, 2).x + coord(i, 3).x) / 3\n yinside = (coord(i, 1).y + coord(i, 2).y + coord(i, 3).y) / 3\n PAINT (xinside, yinside), _RGBA32(255, 0, 0, 128)\n _BLEND\n _PUTIMAGE , backscreen, 0\n _DEST workscreen\n _SOURCE workscreen\n overlap = 0\n FOR x = 0 TO 999\n FOR y = 0 TO 999\n IF POINT(x, y) = _RGBA32(190, 63, 63, 255) THEN overlap = -1: GOTO overlap\n NEXT\n NEXT\n overlap:\n IF overlap THEN PRINT \"OVERLAP\" ELSE PRINT \"NO OVERLAP\"\n SLEEP\nNEXT\nSYSTEM\n\nSUB FixCoord (p AS point)\n p.x = (10 + p.x) * 30 + 100\n p.y = (10 + p.y) * 30\nEND SUB\n", "language": "QB64" }, { "code": "#lang racket\n\n;; A triangle is a list of three pairs of points: '((x . y) (x . y) (x . y))\n(define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)))\n\n(define det-2D\n (match-lambda\n [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))]))\n\n(define (assert-triangle-winding triangle allow-reversed?)\n (cond\n [(>= (det-2D triangle) 0) triangle]\n [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])]\n [else (error 'assert-triangle-winding \"triangle is wound in wrong direction\")]))\n\n(define (tri-tri-2d? triangle1 triangle2\n #:ϵ (ϵ 0)\n #:allow-reversed? (allow-reversed? #f)\n #:on-boundary? (on-boundary? #t))\n (define check-edge\n (if on-boundary? ; Points on the boundary are considered as colliding\n (λ (triangle) (< (det-2D triangle) ϵ))\n (λ (triangle) (<= (det-2D triangle) ϵ))))\n\n (define (inr t1 t2)\n (for*/and ((i (in-range 3)))\n ;; Check all points of trangle 2 lay on the external side\n ;; of the edge E. If they do, the triangles do not collide.\n (define t1.i (list-ref t1 i))\n (define t1.j (list-ref t1 (modulo (add1 i) 3)))\n (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j))))))\n\n (let (;; Trangles must be expressed anti-clockwise\n (tri1 (assert-triangle-winding triangle1 allow-reversed?))\n (tri2 (assert-triangle-winding triangle2 allow-reversed?)))\n (and (inr tri1 tri2) (inr tri2 tri1))))\n\n;; ---------------------------------------------------------------------------------------------------\n(module+ test\n (require rackunit)\n\n (define triangleses ; pairs of triangles\n (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6))\n ((0 0 0 5 5 0) ( 0 0 0 5 5 0))\n ((0 0 5 0 0 5) (-10 0 -5 0 -1 6))\n ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4))\n ((0 0 1 1 0 2) ( 2 1 3 0 3 2))\n ((0 0 1 1 0 2) ( 2 1 3 -2 3 4))))))\n (map (curry apply to-tri) a.b)))\n\n (check-equal?\n (for/list ((t1.t2 (in-list triangleses)))\n (define t1 (first t1.t2))\n (define t2 (second t1.t2))\n (define-values (r reversed?)\n (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))])\n (values (tri-tri-2d? t1 t2) #f)))\n (cons r reversed?))\n '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f)))\n\n (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1)))\n (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t))\n (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))\n", "language": "Racket" }, { "code": "# Reference:\n# https://stackoverflow.com/questions/2049582/how-to-determine-if-a-point-is-in-a-2d-triangle\n# https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/\n\nsub if-overlap ($triangle-pair) {\n my (\\A,\\B) = $triangle-pair;\n my Bool $result = False;\n\n sub sign (\\T) {\n return (T[0;0] - T[2;0]) × (T[1;1] - T[2;1]) -\n (T[1;0] - T[2;0]) × (T[0;1] - T[2;1]);\n }\n\n sub point-in-triangle (\\pt, \\Y --> Bool) {\n my $d1 = sign (pt, Y[0], Y[1]);\n my $d2 = sign (pt, Y[1], Y[2]);\n my $d3 = sign (pt, Y[2], Y[0]);\n\n my $has_neg = [or] $d1 < 0, $d2 < 0, $d3 < 0;\n my $has_pos = [or] $d1 > 0, $d2 > 0, $d3 > 0;\n\n return not ($has_neg and $has_pos);\n }\n\n sub orientation(\\P, \\Q, \\R --> Int) {\n my \\val = (Q[1] - P[1]) × (R[0] - Q[0]) -\n (Q[0] - P[0]) × (R[1] - Q[1]);\n\n return 0 if val == 0; # colinear\n return val > 0 ?? 1 !! 2; # clock or counterclock wise\n }\n\n sub onSegment(\\P, \\Q, \\R --> Bool) {\n Q[0] ≤ max(P[0], R[0]) and Q[0] ≥ min(P[0], R[0]) and\n Q[1] ≤ max(P[1], R[1]) and Q[1] ≥ min(P[0], R[1])\n ?? True !! False\n }\n\n sub intersect(\\A,\\B,\\C,\\D --> Bool) {\n my \\o1 = orientation A, C, D;\n my \\o2 = orientation B, C, D;\n my \\o3 = orientation A, B, C;\n my \\o4 = orientation A, B, D;\n\n o1 != o2 and o3 != o4\n or o1 == 0 and onSegment A, C, D\n or o2 == 0 and onSegment B, C, D\n or o3 == 0 and onSegment A, B, C\n or o4 == 0 and onSegment A, B, D\n ?? True !! False\n }\n\n for ^3 {\n { $result = True; last } if\n point-in-triangle A.[$^i], B or\n point-in-triangle B.[$^i], A ;\n }\n\n unless $result {\n $result = True if\n intersect A.[0], A.[1], B.[0], B.[1] or\n intersect A.[0], A.[1], B.[0], B.[2]\n }\n\n say \"{A.gist} and {B.gist} do{' NOT' unless $result} overlap.\";\n}\n\nmy \\DATA = [\n [ [(0,0),(5,0),(0,5)] , [(0,0),(5,0),(0,6)] ],\n [ [(0,0),(0,5),(5,0)] , [(0,0),(0,5),(5,0)] ],\n [ [(0,0),(5,0),(0,5)] , [(-10,0),(-5,0),(-1,6)] ],\n [ [(0,0),(5,0),(2.5,5)] , [ (0,4),(2.5,-1),(5,4)] ],\n [ [(0,0),(1,1),(0,2)] , [(2,1),(3,0),(3,2)] ],\n [ [(0,0),(1,1),(0,2)] , [(2,1),(3,-2),(3,4)] ],\n [ [(0,0),(1,0),(0,1)] , [(1,0),(2,0),(1,1)] ]\n];\n\nif-overlap $_ for DATA ;\n", "language": "Raku" }, { "code": "/* REXX */\nSignal On Halt\nSignal On Novalue\nSignal On Syntax\n\nfid='trio.in'\noid='trio.txt'; 'erase' oid\n\n\nCall trio_test '0 0 5 0 0 5 0 0 5 0 0 6'\nCall trio_test '0 0 0 5 5 0 0 0 0 5 5 0'\nCall trio_test '0 0 5 0 0 5 -10 0 -5 0 -1 6'\nCall trio_test '0 0 5 0 2.5 5 0 4 2.5 -1 5 4'\nCall trio_test '0 0 1 1 0 2 2 1 3 0 3 2'\nCall trio_test '0 0 1 1 0 2 2 1 3 -2 3 4'\nCall trio_test '0 0 1 0 0 1 1 0 2 0 1 1'\n\nCall trio_test '1 0 3 0 2 2 1 3 3 3 2 5'\nCall trio_test '1 0 3 0 2 2 1 3 3 3 2 2'\nCall trio_test '0 0 2 0 2 2 3 3 5 3 5 5'\nCall trio_test '2 0 2 6 1 8 0 1 0 5 8 3'\nCall trio_test '0 0 4 0 0 4 0 2 2 0 2 2'\nCall trio_test '0 0 4 0 0 4 1 1 2 1 1 2'\nExit\n\ntrio_test:\nparse Arg tlist\ntlist=space(tlist)\nParse Arg ax ay bx by cx cy dx dy ex ey fx fy\n\nSay 'ABC:' show_p(ax ay) show_p(bx by) show_p(cx cy)\nSay 'DEF:' show_p(dx dy) show_p(ex ey) show_p(fx fy)\n\nbordl=bord(tlist) /* corners that are on the other triangle's edges */\nIf bordl<>'' Then\n Say 'Corners on the other triangle''s edges:' bordl\nwb=words(bordl) /* how many of them? */\nSelect\n When wb=3 Then Do /* all three match */\n If ident(ax ay,bx by,cx cy,dx dy,ex ey,fx fy) Then\n Say 'Triangles are identical'\n Else\n Say 'Triangles overlap'\n Say ''\n Return\n End\n When wb=2 Then Do /* two of them match */\n Say 'Triangles overlap'\n Say ' they have a common edge 'bordl\n Say ''\n Return\n End\n When wb=1 Then Do /* one of them match */\n Say 'Triangles touch on' bordl /* other parts may overlap */\n Say ' we analyze further'\n End\n Otherwise /* we know nothing yet */\n Nop\n End\n\ntrio_result=trio(tlist) /* any other overlap? */\n\nSelect\n When trio_result=0 Then Do /* none whatsoever */\n If wb=1 Then\n Say 'Triangles touch (border case) at' show_p(bordl)\n Else\n Say 'Triangles don''t overlap'\n End\n When trio_result>0 Then /* plain overlapping case */\n Say 'Triangles overlap'\n End\nSay ''\nReturn\n\ntrio:\n/*---------------------------------------------------------------------\n* Determine if two triangles overlap\n*--------------------------------------------------------------------*/\nparse Arg tlist\nParse Arg pax pay pbx pby pcx pcy pdx pdy pex pey pfx pfy\n\nabc=subword(tlist,1,6)\ndef=subword(tlist,7,6)\n\nDo i=1 To 3\n s.i=subword(abc abc,i*2-1,4)\n t.i=subword(def def,i*2-1,4)\n End\n\nabc_=''\ndef_=''\n\nDo i=1 To 3\n abc.i=subword(abc,i*2-1,2) /* corners of ABC */\n def.i=subword(def,i*2-1,2) /* corners of DEF */\n Parse Var abc.i x y; abc_=abc_ '('||x','y')'\n Parse Var def.i x y; def_=def_ '('||x','y')'\n End\nCall o 'abc_='abc_\nCall o 'def_='def_\n\nover=0\n Do i=1 To 3 Until over\n Do j=1 To 3 Until over\n If ssx(s.i t.j) Then Do /* intersection of two edges */\n over=1\n Leave\n End\n End\n End\n\nIf over=0 Then Do /* no edge intersection found */\n Do ii=1 To 3 Until over /* look for first possibility */\n Call o ' ' 'abc.'ii'='abc.ii 'def='def\n Call o 'ii='ii 'def.'ii'='def.ii 'abc='abc\n If in_tri(abc.ii,def) Then Do /* a corner of ABC is in DEF */\n Say abc.ii 'is within' def\n over=1\n End\n Else If in_tri(def.ii,abc) Then Do /* a corner of DEF is in ABC */\n Say def.ii 'is within' abc\n over=1\n End\n End\n End\n\nIf over=0 Then rw='don''t '\nElse rw=''\n\nCall o 'Triangles' show_p(pax pay) show_p(pbx pby) show_p(pcx pcy),\n 'and' show_p(pdx pdy) show_p(pex pey) show_p(pfx pfy),\n rw'overlap'\nCall o ''\nReturn over\n\nssx: Procedure Expose oid bordl\n/*---------------------------------------------------------------------\n* Intersection of 2 line segments A-B and C-D\n*--------------------------------------------------------------------*/\nParse Arg xa ya xb yb xc yc xd yd\n\nd=ggx(xa ya xb yb xc yc xd yd)\n\nCall o 'ssx:' arg(1) d\nres=0\nSelect\n When d='-' Then res=0\n When d='I' Then Do\n If xa<>xb Then Do\n xab_min=min(xa,xb)\n xcd_min=min(xc,xd)\n xab_max=max(xa,xb)\n xcd_max=max(xc,xd)\n If xab_min>xcd_max |,\n xcd_min>xab_max Then\n res=0\n Else Do\n res=1\n Select\n When xa=xc & isb(xc,xb,xd)=0 Then Do; x=xa; y=ya; End\n When xb=xc & isb(xc,xa,xd)=0 Then Do; x=xb; y=yb; End\n When xa=xd & isb(xc,xb,xd)=0 Then Do; x=xa; y=ya; End\n When xb=xd & isb(xc,xa,xd)=0 Then Do; x=xb; y=yb; End\n Otherwise Do\n x='*'\n y=ya\n End\n End\n Call o 'ssx:' x y\n End\n End\n Else Do\n yab_min=min(ya,yb)\n ycd_min=min(yc,yd)\n yab_max=max(ya,yb)\n ycd_max=max(yc,yd)\n If yab_min>ycd_max |,\n ycd_min>yab_max Then\n res=0\n Else Do\n res=1\n x=xa\n y='*'\n Parse Var bordl x_bord '/' y_bord\n If x=x_bord Then Do\n Call o xa'/* IGNORED'\n res=0\n End\n End\n End\n End\n Otherwise Do\n Parse Var d x y\n If is_between(xa,x,xb) &,\n is_between(xc,x,xd) &,\n is_between(ya,y,yb) &,\n is_between(yc,y,yd) Then Do\n If x'/'y<>bordl Then\n res=1\n End\n End\n End\n If res=1 Then Do\n Say 'Intersection of line segments: ('||x'/'y')'\n Parse Var bordl x_bord '/' y_bord\n If x=x_bord Then Do\n res=0\n Call o x'/'y 'IGNORED'\n End\n End\n Else Call o 'ssx: -'\nReturn res\n\nggx: Procedure Expose oid bordl\n/*---------------------------------------------------------------------\n* Intersection of 2 (straight) lines\n*--------------------------------------------------------------------*/\nParse Arg xa ya xb yb xc yc xd yd\nres=''\nIf xa=xb Then Do\n k1='*'\n x1=xa\n If ya=yb Then Do\n res='Points A and B are identical'\n rs='*'\n End\n End\nElse Do\n k1=(yb-ya)/(xb-xa)\n d1=ya-k1*xa\n End\nIf xc=xd Then Do\n k2='*'\n x2=xc\n If yc=yd Then Do\n res='Points C and D are identical'\n rs='*'\n End\n End\nElse Do\n k2=(yd-yc)/(xd-xc)\n d2=yc-k2*xc\n End\n\nIf res='' Then Do\n If k1='*' Then Do\n If k2='*' Then Do\n If x1=x2 Then Do\n res='Lines AB and CD are identical'\n rs='I'\n End\n Else Do\n res='Lines AB and CD are parallel'\n rs='-'\n End\n End\n Else Do\n x=x1\n y=k2*x+d2\n End\n End\n Else Do\n If k2='*' Then Do\n x=x2\n y=k1*x+d1\n End\n Else Do\n If k1=k2 Then Do\n If d1=d2 Then Do\n res='Lines AB and CD are identical'\n rs='I'\n End\n Else Do\n res='Lines AB and CD are parallel'\n rs='-'\n End\n End\n Else Do\n x=(d2-d1)/(k1-k2)\n y=k1*x+d1\n End\n End\n End\n End\n If res='' Then Do\n res='Intersection is ('||x'/'y')'\n rs=x y\n Call o 'line intersection' x y\n End\n Call o 'A=('xa'/'ya') B=('||xb'/'yb') C=('||xc'/'yc') D=('||xd'/'yd')' '-->' res\n Return rs\n\nisb: Procedure\n Parse Arg a,b,c\n Return sign(b-a)<>sign(b-c)\n\nis_between: Procedure Expose oid\n Parse Arg a,b,c\n Return diff_sign(b-a,b-c)\n\ndiff_sign: Procedure\n Parse Arg diff1,diff2\n Return (sign(diff1)<>sign(diff2))|(sign(diff1)=0)\n\no:\n/*y 'sigl='sigl */\nReturn lineout(oid,arg(1))\n\nin_tri: Procedure Expose oid bordl\n/*---------------------------------------------------------------------\n* Determine if the point (px/py) is within the given triangle\n*--------------------------------------------------------------------*/\nParse Arg px py,ax ay bx by cx cy\nabc=ax ay bx by cx cy\nres=0\nmaxx=max(ax,bx,cx)\nminx=min(ax,bx,cx)\nmaxy=max(ay,by,cy)\nminy=min(ay,by,cy)\n\nIf px>maxx|px<minx|py>maxy|py<miny Then\n Return 0\n\nParse Value mk_g(ax ay,bx by) With k.1 d.1 x.1\nParse Value mk_g(bx by,cx cy) With k.2 d.2 x.2\nParse Value mk_g(cx cy,ax ay) With k.3 d.3 x.3\n/*\nsay 'g1:' show_g(k.1,d.1,x.1)\nsay 'g2:' show_g(k.2,d.2,x.2)\nsay 'g3:' show_g(k.3,d.3,x.3)\nSay px py '-' ax ay bx by cx cy\n*/\nDo i=1 To 3\n Select\n When k.i='*' Then\n Call o 'g.'i':' 'x='||x.i\n When k.i=0 Then\n Call o 'g.'i':' 'y='d.i\n Otherwise\n Call o 'g.'i':' 'y=' k.i'*x'dd(d.i)\n End\n End\n\nIf k.1='*' Then Do\n y2=k.2*px+d.2\n y3=k.3*px+d.3\n If is_between(y2,py,y3) Then\n res=1\n End\nElse Do\n kp1=k.1\n dp1=py-kp1*px\n If k.2='*' Then\n x12=x.2\n Else\n x12=(d.2-dp1)/(kp1-k.2)\n If k.3='*' Then\n x13=x.3\n Else\n x13=(d.3-dp1)/(kp1-k.3)\n If is_between(x12,px,x13) Then\n res=1\n End\n\nIf res=1 Then rr=' '\n Else rr=' not '\nIf pos(px'/'py,bordl)>0 Then Do\n ignored=' but is IGNORED'\n res=0\n End\nElse\n ignored=''\nSay 'P ('px','py') is'rr'in' abc ignored\nReturn res\n\nbord:\n/*---------------------------------------------------------------------\n* Look for corners of triangles that are situated\n* on the edges of the other triangle\n*--------------------------------------------------------------------*/\nparse Arg tlist\nParse Arg pax pay pbx pby pcx pcy pdx pdy pex pey pfx pfy\nbordl=''\nabc=subword(tlist,1,6)\ndef=subword(tlist,7,6)\n\nDo i=1 To 3\n s.i=subword(abc abc,i*2-1,4)\n t.i=subword(def def,i*2-1,4)\n End\n\nabc_=''\ndef_=''\nDo i=1 To 3\n abc.i=subword(abc,i*2-1,2)\n def.i=subword(def,i*2-1,2)\n Parse Var abc.i x y; abc_=abc_ '('||x','y')'\n Parse Var def.i x y; def_=def_ '('||x','y')'\n End\n\nDo i=1 To 3\n i1=i+1\n If i1=4 Then i1=1\n Parse Value mk_g(abc.i,abc.i1) With k.1.i d.1.i x.1.i\n Parse Value mk_g(def.i,def.i1) With k.2.i d.2.i x.2.i\n End\nDo i=1 To 3\n Call o show_g(k.1.i,d.1.i,x.1.i)\n End\nDo i=1 To 3\n Call o show_g(k.2.i,d.2.i,x.2.i)\n End\n\npl=''\nDo i=1 To 3\n p=def.i\n Do j=1 To 3\n j1=j+1\n If j1=4 Then j1=1\n g='1.'j\n If in_segment(p,abc.j,abc.j1) Then Do\n pp=Translate(p,'/',' ')\n If wordpos(pp,bordl)=0 Then\n bordl=bordl pp\n End\n Call o show_p(p) show_g(k.g,d.g,x.g) '->' bordl\n End\n End\nCall o 'Points on abc:' pl\n\npl=''\nDo i=1 To 3\n p=abc.i\n Do j=1 To 3\n j1=j+1\n If j1=4 Then j1=1\n g='2.'j\n If in_segment(p,def.j,def.j1)Then Do\n pp=Translate(p,'/',' ')\n If wordpos(pp,bordl)=0 Then\n bordl=bordl pp\n End\n Call o show_p(p) show_g(k.g,d.g,x.g) '->' bordl\n End\n End\nCall o 'Points on def:' pl\n\nReturn bordl\n\nin_segment: Procedure Expose g. sigl\n/*---------------------------------------------------------------------\n* Determine if point x/y is on the line segment ax/ay bx/by\n*--------------------------------------------------------------------*/\nParse Arg x y,ax ay,bx by\nCall show_p(x y) show_p(ax ay) show_p(bx by)\nParse Value mk_g(ax ay,bx by) With gk gd gx\nSelect\n When gx<>'' Then\n res=(x=gx & is_between(ay,y,by))\n When gk='*' Then\n res=(y=gd & is_between(ax,x,bx))\n Otherwise Do\n yy=gk*x+gd\n res=(y=yy & is_between(ax,x,bx))\n End\n End\nReturn res\n\nmk_g: Procedure Expose g.\n/*---------------------------------------------------------------------\n* given two points (a and b)\n* compute y=k*x+d or, if a vertical line, k='*'; x=c\n*--------------------------------------------------------------------*/\nParse Arg a,b /* 2 points */\nParse Var a ax ay\nParse Var b bx by\nIf ax=bx Then Do /* vertical line */\n gk='*' /* special slope */\n gx=ax /* x=ax is the equation */\n gd='*' /* not required */\n End\nElse Do\n gk=(by-ay)/(bx-ax) /* compute slope */\n gd=ay-gk*ax /* compute y-distance */\n gx='' /* not required */\n End\nReturn gk gd gx\n\nis_between: Procedure\n Parse Arg a,b,c\n Return diff_sign(b-a,b-c)\n\ndiff_sign: Procedure\n Parse Arg diff1,diff2\n Return (sign(diff1)<>sign(diff2))|(sign(diff1)=0)\n\nshow_p: Procedure\n Call trace 'O'\n Parse Arg x y\n If pos('/',x)>0 Then\n Parse Var x x '/' y\n Return space('('||x'/'y')',0)\n\nisb: Procedure Expose oid\n Parse Arg a,b,c\n Return sign(b-a)<>sign(b-c)\n\no: Call o arg(1)\n Return\n\nshow_g: Procedure\n/*---------------------------------------------------------------------\n* given slope, y-distance, and (special) x-value\n* compute y=k*x+d or, if a vertical line, k='*'; x=c\n*--------------------------------------------------------------------*/\nParse Arg k,d,x\nSelect\n When k='*' Then res='x='||x /* vertical line */\n When k=0 Then res='y='d /* horizontal line */\n Otherwise Do /* ordinary line */\n Select\n When k=1 Then res='y=x'dd(d)\n When k=-1 Then res='y=-x'dd(d)\n Otherwise res='y='k'*x'dd(d)\n End\n End\n End\nReturn res\n\ndd: Procedure\n/*---------------------------------------------------------------------\n* prepare y-distance for display\n*--------------------------------------------------------------------*/\n Parse Arg dd\n Select\n When dd=0 Then dd='' /* omit dd if it's zero */\n When dd<0 Then dd=dd /* use dd as is (-value) */\n Otherwise dd='+'dd /* prepend '+' to positive dd */\n End\n Return dd\n\nident: Procedure\n/*---------------------------------------------------------------------\n* Determine if the corners ABC match those of DEF (in any order)\n*--------------------------------------------------------------------*/\n cnt.=0\n Do i=1 To 6\n Parse Value Arg(i) With x y\n cnt.x.y=cnt.x.y+1\n End\n Do i=1 To 3\n Parse Value Arg(i) With x y\n If cnt.x.y<>2 Then\n Return 0\n End\n Return 1\n\nNovalue:\n Say 'Novalue raised in line' sigl\n Say sourceline(sigl)\n Say 'Variable' condition('D')\n Signal lookaround\n\nSyntax:\n Say 'Syntax raised in line' sigl\n Say sourceline(sigl)\n Say 'rc='rc '('errortext(rc)')'\n\nhalt:\nlookaround:\n If fore() Then Do\n Say 'You can look around now.'\n Trace ?R\n Nop\n End\n Exit 12\n", "language": "REXX" }, { "code": "require \"matrix\"\n\ndef det2D(p1, p2, p3)\n return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1])\nend\n\ndef checkTriWinding(p1, p2, p3, allowReversed)\n detTri = det2D(p1, p2, p3)\n if detTri < 0.0 then\n if allowReversed then\n p2[0], p3[0] = p3[0], p2[0]\n p2[1], p3[1] = p3[1], p2[1]\n else\n raise \"Triangle has incorrect winding\"\n end\n end\nend\n\ndef boundaryCollideChk(p1, p2, p3, eps)\n return det2D(p1, p2, p3) < eps\nend\n\ndef boundaryDoesntCollideChk(p1, p2, p3, eps)\n return det2D(p1, p2, p3) <= eps\nend\n\ndef triTri2D(t1, t2, eps, allowReversed, onBoundary)\n # Triangles must be expressed anti-clockwise\n checkTriWinding(t1[0], t1[1], t1[2], allowReversed)\n checkTriWinding(t2[0], t2[1], t2[2], allowReversed)\n\n if onBoundary then\n # Points on the boundary are considered as colliding\n chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) }\n else\n # Points on the boundary are not considered as colliding\n chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) }\n end\n\n # For edge E of triangle 1\n for i in 0..2 do\n j = (i + 1) % 3\n\n # Check all points of trangle 2 lay on the external side of the edge E. If\n # they do, the triangles do not collide.\n if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then\n return false\n end\n end\n\n # For edge E of triangle 2\n for i in 0..2 do\n j = (i + 1) % 3\n\n # Check all points of trangle 1 lay on the external side of the edge E. If\n # they do, the triangles do not collide.\n if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then\n return false\n end\n end\n\n # The triangles collide\n return true\nend\n\ndef main\n t1 = [Vector[0,0], Vector[5,0], Vector[0,5]]\n t2 = [Vector[0,0], Vector[5,0], Vector[0,6]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, false, true)]\n\n t1 = [Vector[0,0], Vector[0,5], Vector[5,0]]\n t2 = [Vector[0,0], Vector[0,5], Vector[5,0]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, true, true)]\n\n t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]]\n t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, false, true)]\n\n t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]]\n t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, false, true)]\n\n t1 = [Vector[0,0], Vector[1,1], Vector[0,2]]\n t2 = [Vector[2,1], Vector[3,0], Vector[3,2]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, false, true)]\n\n t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]]\n t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, false, true)]\n\n # Barely touching\n t1 = [Vector[0,0], Vector[1,0], Vector[0,1]]\n t2 = [Vector[1,0], Vector[2,0], Vector[1,1]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, false, true)]\n\n # Barely touching\n t1 = [Vector[0,0], Vector[1,0], Vector[0,1]]\n t2 = [Vector[1,0], Vector[2,0], Vector[1,1]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, false, false)]\nend\n\nmain()\n", "language": "Ruby" }, { "code": "object Overlap {\n type Point = (Double, Double)\n\n class Triangle(var p1: Point, var p2: Point, var p3: Point) {\n override def toString: String = s\"Triangle: $p1, $p2, $p3\"\n }\n\n def det2D(t: Triangle): Double = {\n val (p1, p2, p3) = (t.p1, t.p2, t.p3)\n p1._1 * (p2._2 - p3._2) +\n p2._1 * (p3._2 - p1._2) +\n p3._1 * (p1._2 - p2._2)\n }\n\n def checkTriWinding(t: Triangle, allowReversed: Boolean): Unit = {\n val detTri = det2D(t)\n if (detTri < 0.0) {\n if (allowReversed) {\n val a = t.p3\n t.p3 = t.p2\n t.p2 = a\n } else throw new RuntimeException(\"Triangle has wrong winding direction\")\n }\n }\n\n def boundaryCollideChk(t: Triangle, eps: Double): Boolean = det2D(t) < eps\n\n def boundaryDoesntCollideChk(t: Triangle, eps: Double): Boolean = det2D(t) <= eps\n\n def triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean = {\n //triangles must be expressed anti-clockwise\n checkTriWinding(t1, allowReversed)\n checkTriWinding(t2, allowReversed)\n // 'onBoundary' determines whether points on boundary are considered as colliding or not\n val chkEdge = if (onBoundary) Overlap.boundaryCollideChk _ else Overlap.boundaryDoesntCollideChk _\n val lp1 = Array(t1.p1, t1.p2, t1.p3)\n val lp2 = Array(t2.p1, t2.p2, t2.p3)\n\n // for each edge E of t1\n for (i <- 0 until 3) {\n val j = (i + 1) % 3\n // Check all points of t2 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge(new Triangle(lp1(i), lp1(j), lp2(0)), eps)\n && chkEdge(new Triangle(lp1(i), lp1(j), lp2(1)), eps)\n && chkEdge(new Triangle(lp1(i), lp1(j), lp2(2)), eps)) return false\n }\n\n // for each edge E of t2\n for (i <- 0 until 3) {\n val j = (i + 1) % 3\n // Check all points of t1 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge(new Triangle(lp2(i), lp2(j), lp1(0)), eps)\n && chkEdge(new Triangle(lp2(i), lp2(j), lp1(1)), eps)\n && chkEdge(new Triangle(lp2(i), lp2(j), lp1(2)), eps)) return false\n }\n\n // The triangles overlap\n true\n }\n\n def main(args: Array[String]): Unit = {\n var t1 = new Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 5.0))\n var t2 = new Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 6.0))\n println(s\"$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n // need to allow reversed for this pair to avoid exception\n t1 = new Triangle((0.0, 0.0), (0.0, 5.0), (5.0, 0.0))\n t2 = t1\n println(s\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2, 0.0, allowReversed = true)) \"overlap (reversed)\" else \"do not overlap\")\n\n t1 = new Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 5.0))\n t2 = new Triangle((-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0))\n println(s\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n t1.p3 = (2.5, 5.0)\n t2 = new Triangle((0.0, 4.0), (2.5, -1.0), (5.0, 4.0))\n println(s\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n t1 = new Triangle((0.0, 0.0), (1.0, 1.0), (0.0, 2.0))\n t2 = new Triangle((2.0, 1.0), (3.0, 0.0), (3.0, 2.0))\n println(s\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n t2 = new Triangle((2.0, 1.0), (3.0, -2.0), (3.0, 4.0))\n println(s\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n t1 = new Triangle((0.0, 0.0), (1.0, 0.0), (0.0, 1.0))\n t2 = new Triangle((1.0, 0.0), (2.0, 0.0), (1.0, 1.1))\n println(s\"\\n$t1 and\\n$t2\")\n println(\"which have only a single corner in contact, if boundary points collide\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n println(s\"\\n$t1 and\\n$t2\")\n println(\"which have only a single corner in contact, if boundary points do not collide\")\n println(if (triTri2D(t1, t2, onBoundary = false)) \"overlap\" else \"do not overlap\")\n }\n}\n", "language": "Scala" }, { "code": "struct Point {\n x f64\n\ty f64\n}\n\nfn (p Point) str() string {\n return \"(${p.x:.1f}, ${p.y:.1f})\"\n}\n\nstruct Triangle {\nmut:\n p1 Point\n\tp2 Point\n\tp3 Point\n}\n\nfn (t Triangle) str() string {\n return \"Triangle $t.p1, $t.p2, $t.p3\"\n}\n\nfn (t Triangle) det_2d() f64 {\n return t.p1.x * (t.p2.y - t.p3.y) +\n t.p2.x * (t.p3.y - t.p1.y) +\n t.p3.x * (t.p1.y - t.p2.y)\n}\n\nfn (mut t Triangle) check_tri_winding(allow_reversed bool) {\n det_tri := t.det_2d()\n if det_tri < 0.0 {\n if allow_reversed {\n a := t.p3\n t.p3 = t.p2\n t.p2 = a\n } else {\n panic(\"Triangle has wrong winding direction.\")\n }\n }\n}\n\nfn boundary_collide_chk(t Triangle, eps f64, does bool) bool {\n\tif does {\n \treturn t.det_2d() < eps\n\t}\n\treturn t.det_2d() <= eps\n}\n\nfn tri_tri_2d(mut t1 Triangle, mut t2 Triangle, eps f64, allow_reversed bool, on_boundary bool) bool {\n // Triangles must be expressed anti-clockwise.\n t1.check_tri_winding(allow_reversed)\n t2.check_tri_winding(allow_reversed)\n\n lp1 := [t1.p1, t1.p2, t1.p3]\n lp2 := [t2.p1, t2.p2, t2.p3]\n\n // for each edge E of t1\n for i in 0..3 {\n j := (i + 1) % 3\n // Check all Points of t2 lay on the external side of edge E.\n // If they do, the Triangles do not overlap.\n tri1 := Triangle{lp1[i], lp1[j], lp2[0]}\n tri2 := Triangle{lp1[i], lp1[j], lp2[1]}\n tri3 := Triangle{lp1[i], lp1[j], lp2[2]}\n if boundary_collide_chk(tri1, eps,on_boundary) && boundary_collide_chk(tri2, eps,on_boundary) && boundary_collide_chk(tri3, eps,on_boundary) {\n return false\n }\n }\n\n // for each edge E of t2\n for i in 0..3 {\n j := (i + 1) % 3\n // Check all Points of t1 lay on the external side of edge E.\n // If they do, the Triangles do not overlap.\n tri1 := Triangle{lp2[i], lp2[j], lp1[0]}\n tri2 := Triangle{lp2[i], lp2[j], lp1[1]}\n tri3 := Triangle{lp2[i], lp2[j], lp1[2]}\n if boundary_collide_chk(tri1, eps,on_boundary) && boundary_collide_chk(tri2, eps,on_boundary) && boundary_collide_chk(tri3, eps,on_boundary) {\n return false\n }\n }\n\n // The Triangles overlap.\n return true\n}\n\nfn iff(cond bool, s1 string, s2 string) string {\n if cond {\n return s1\n }\n return s2\n}\n\nfn main() {\n mut t1 := Triangle{Point{0.0, 0.0}, Point{5.0, 0.0}, Point{0.0, 5.0}}\n mut t2 := Triangle{Point{0.0, 0.0}, Point{5.0, 0.0}, Point{0.0, 6.0}}\n println(\"\\n$t1 and\\n$t2\")\n mut overlapping := tri_tri_2d(mut t1, mut t2, 0.0, false, true)\n println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n // Need to allow reversed for this pair to avoid panic.\n t1 = Triangle{Point{0.0, 0.0}, Point{0.0, 5.0}, Point{5.0, 0.0}}\n t2 = t1\n println(\"\\n$t1 and\\n$t2\")\n overlapping = tri_tri_2d(mut t1, mut t2, 0.0, true, true)\n println(iff(overlapping, \"overlap (reversed)\", \"do not overlap\"))\n\n t1 = Triangle{Point{0.0, 0.0}, Point{5.0, 0.0}, Point{0.0, 5.0}}\n t2 = Triangle{Point{-10.0, 0.0}, Point{-5.0, 0.0}, Point{-1.0, 6.0}}\n println(\"\\n$t1 and\\n$t2\")\n overlapping = tri_tri_2d(mut t1, mut t2, 0.0, false, true)\n println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n t1.p3 = Point{2.5, 5.0}\n t2 = Triangle{Point{0.0, 4.0}, Point{2.5, -1.0}, Point{5.0, 4.0}}\n println(\"\\n$t1 and\\n$t2\")\n overlapping = tri_tri_2d(mut t1, mut t2, 0.0, false, true)\n println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n t1 = Triangle{Point{0.0, 0.0}, Point{1.0, 1.0}, Point{0.0, 2.0}}\n t2 = Triangle{Point{2.0, 1.0}, Point{3.0, 0.0}, Point{3.0, 2.0}}\n println(\"\\n$t1 and\\n$t2\")\n overlapping = tri_tri_2d(mut t1, mut t2, 0.0, false, true)\n println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n t2 = Triangle{Point{2.0, 1.0}, Point{3.0, -2.0}, Point{3.0, 4.0}}\n println(\"\\n$t1 and\\n$t2\")\n overlapping = tri_tri_2d(mut t1, mut t2, 0.0, false, true)\n println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n t1 = Triangle{Point{0.0, 0.0}, Point{1.0, 0.0}, Point{0.0, 1.0}}\n t2 = Triangle{Point{1.0, 0.0}, Point{2.0, 0.0}, Point{1.0, 1.1}}\n println(\"\\n$t1 and\\n$t2\")\n println(\"which have only a single corner in contact, if boundary Points collide\")\n overlapping = tri_tri_2d(mut t1, mut t2, 0.0, false, true)\n println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n println(\"\\n$t1 and\\n$t2\")\n println(\"which have only a single corner in contact, if boundary Points do not collide\")\n overlapping = tri_tri_2d(mut t1, mut t2, 0.0, false, false)\n println(iff(overlapping, \"overlap\", \"do not overlap\"))\n}\n", "language": "V-(Vlang)" }, { "code": "Module Module1\n\n Class Triangle\n Property P1 As Tuple(Of Double, Double)\n Property P2 As Tuple(Of Double, Double)\n Property P3 As Tuple(Of Double, Double)\n\n Sub New(p1 As Tuple(Of Double, Double), p2 As Tuple(Of Double, Double), p3 As Tuple(Of Double, Double))\n Me.P1 = p1\n Me.P2 = p2\n Me.P3 = p3\n End Sub\n\n Function Det2D() As Double\n Return P1.Item1 * (P2.Item2 - P3.Item2) +\n P2.Item1 * (P3.Item2 - P1.Item2) +\n P3.Item1 * (P1.Item2 - P2.Item2)\n End Function\n\n Sub CheckTriWinding(allowReversed As Boolean)\n Dim detTri = Det2D()\n If detTri < 0.0 Then\n If allowReversed Then\n Dim a = P3\n P3 = P2\n P2 = a\n Else\n Throw New Exception(\"Triangle has wrong winding direction\")\n End If\n End If\n End Sub\n\n Function BoundaryCollideChk(eps As Double) As Boolean\n Return Det2D() < eps\n End Function\n\n Function BoundaryDoesntCollideChk(eps As Double) As Boolean\n Return Det2D() <= eps\n End Function\n\n Public Overrides Function ToString() As String\n Return String.Format(\"Triangle: {0}, {1}, {2}\", P1, P2, P3)\n End Function\n End Class\n\n Function TriTri2D(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional alloweReversed As Boolean = False, Optional onBoundary As Boolean = True) As Boolean\n 'Triangles must be expressed anti-clockwise\n t1.CheckTriWinding(alloweReversed)\n t2.CheckTriWinding(alloweReversed)\n\n '\"onboundary\" determines whether points on boundary are considered as colliding or not\n Dim chkEdge = If(onBoundary, Function(t As Triangle) t.BoundaryCollideChk(eps), Function(t As Triangle) t.BoundaryDoesntCollideChk(eps))\n Dim lp1 As New List(Of Tuple(Of Double, Double)) From {t1.P1, t1.P2, t1.P3}\n Dim lp2 As New List(Of Tuple(Of Double, Double)) From {t2.P1, t2.P2, t2.P3}\n\n 'for each edge E of t1\n For i = 0 To 2\n Dim j = (i + 1) Mod 3\n 'Check all points of t2 lay on the external side of edge E.\n 'If they do, the triangles do not overlap.\n If chkEdge(New Triangle(lp1(i), lp1(j), lp2(0))) AndAlso\n chkEdge(New Triangle(lp1(i), lp1(j), lp2(1))) AndAlso\n chkEdge(New Triangle(lp1(i), lp1(j), lp2(2))) Then\n Return False\n End If\n Next\n\n 'for each edge E of t2\n For i = 0 To 2\n Dim j = (i + 1) Mod 3\n 'Check all points of t1 lay on the external side of edge E.\n 'If they do, the triangles do not overlap.\n If chkEdge(New Triangle(lp2(i), lp2(j), lp1(0))) AndAlso\n chkEdge(New Triangle(lp2(i), lp2(j), lp1(1))) AndAlso\n chkEdge(New Triangle(lp2(i), lp2(j), lp1(2))) Then\n Return False\n End If\n Next\n\n 'The triangles overlap\n Return True\n End Function\n\n Sub Overlap(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional allowReversed As Boolean = False, Optional onBoundary As Boolean = True)\n If TriTri2D(t1, t2, eps, allowReversed, onBoundary) Then\n Console.WriteLine(\"overlap\")\n Else\n Console.WriteLine(\"do not overlap\")\n End If\n End Sub\n\n Sub Main()\n Dim t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0))\n Dim t2 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 6.0))\n Console.WriteLine(\"{0} and\", t1)\n Console.WriteLine(\"{0}\", t2)\n Overlap(t1, t2)\n Console.WriteLine()\n\n ' need to allow reversed for this pair to avoid exception\n t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(0.0, 5.0), Tuple.Create(5.0, 0.0))\n t2 = t1\n Console.WriteLine(\"{0} and\", t1)\n Console.WriteLine(\"{0}\", t2)\n Overlap(t1, t2, 0.0, True)\n Console.WriteLine()\n\n t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0))\n t2 = New Triangle(Tuple.Create(-10.0, 0.0), Tuple.Create(-5.0, 0.0), Tuple.Create(-1.0, 6.0))\n Console.WriteLine(\"{0} and\", t1)\n Console.WriteLine(\"{0}\", t2)\n Overlap(t1, t2)\n Console.WriteLine()\n\n t1.P3 = Tuple.Create(2.5, 5.0)\n t2 = New Triangle(Tuple.Create(0.0, 4.0), Tuple.Create(2.5, -1.0), Tuple.Create(5.0, 4.0))\n Console.WriteLine(\"{0} and\", t1)\n Console.WriteLine(\"{0}\", t2)\n Overlap(t1, t2)\n Console.WriteLine()\n\n t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 1.0), Tuple.Create(0.0, 2.0))\n t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, 0.0), Tuple.Create(3.0, 2.0))\n Console.WriteLine(\"{0} and\", t1)\n Console.WriteLine(\"{0}\", t2)\n Overlap(t1, t2)\n Console.WriteLine()\n\n t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, -2.0), Tuple.Create(3.0, 4.0))\n Console.WriteLine(\"{0} and\", t1)\n Console.WriteLine(\"{0}\", t2)\n Overlap(t1, t2)\n Console.WriteLine()\n\n t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 0.0), Tuple.Create(0.0, 1.0))\n t2 = New Triangle(Tuple.Create(1.0, 0.0), Tuple.Create(2.0, 0.0), Tuple.Create(1.0, 1.1))\n Console.WriteLine(\"{0} and\", t1)\n Console.WriteLine(\"{0}\", t2)\n Console.WriteLine(\"which have only a single corner in contact, if boundary points collide\")\n Overlap(t1, t2)\n Console.WriteLine()\n\n Console.WriteLine(\"{0} and\", t1)\n Console.WriteLine(\"{0}\", t2)\n Console.WriteLine(\"which have only a single corner in contact, if boundary points do not collide\")\n Overlap(t1, t2, 0.0, False, False)\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./dynamic\" for Tuple, Struct\n\nvar Point = Tuple.create(\"Point\", [\"x\", \"y\"])\n\nvar Triangle = Struct.create(\"Triangle\", [\"p1\", \"p2\", \"p3\"])\n\nvar det2D = Fn.new { |t|\n return t.p1.x * (t.p2.y - t.p3.y) +\n t.p2.x * (t.p3.y - t.p1.y) +\n t.p3.x * (t.p1.y - t.p2.y)\n}\n\nvar checkTriWinding = Fn.new { |t, allowReversed|\n var detTri = det2D.call(t)\n if (detTri < 0) {\n if (allowReversed) {\n var a = t.p3\n\t t.p3 = t.p2\n\t t.p2 = a\n } else Fiber.abort(\"Triangle has wrong winding direction\")\n }\n}\n\nvar boundaryCollideChk = Fn.new { |t, eps| det2D.call(t) < eps }\n\nvar boundaryDoesntCollideChk = Fn.new { |t, eps| det2D.call(t) <= eps }\n\nvar triTri2D = Fn.new { |t1, t2, eps, allowReversed, onBoundary|\n // Triangles must be expressed anti-clockwise\n checkTriWinding.call(t1, allowReversed)\n checkTriWinding.call(t2, allowReversed)\n // 'onBoundary' determines whether points on boundary are considered as colliding or not\n var chkEdge = onBoundary ? boundaryCollideChk : boundaryDoesntCollideChk\n var lp1 = [t1.p1, t1.p2, t1.p3]\n var lp2 = [t2.p1, t2.p2, t2.p3]\n\n // for each edge E of t1\n for (i in 0..2) {\n var j = (i + 1) % 3\n // Check all points of t2 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n\t if (chkEdge.call(Triangle.new(lp1[i], lp1[j], lp2[0]), eps) &&\n chkEdge.call(Triangle.new(lp1[i], lp1[j], lp2[1]), eps) &&\n chkEdge.call(Triangle.new(lp1[i], lp1[j], lp2[2]), eps)) return false\n }\n\n // for each edge E of t2\n for (i in 0..2) {\n var j = (i + 1) % 3\n // Check all points of t1 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge.call(Triangle.new(lp2[i], lp2[j], lp1[0]), eps) &&\n chkEdge.call(Triangle.new(lp2[i], lp2[j], lp1[1]), eps) &&\n chkEdge.call(Triangle.new(lp2[i], lp2[j], lp1[2]), eps)) return false\n }\n\n // The triangles overlap\n return true\n}\n\nvar tr = \"Triangle: \"\nvar printTris = Fn.new { |t1, t2, nl| System.print(\"%(nl)%(tr)%(t1) and\\n%(tr)%(t2)\") }\n\nvar t1 = Triangle.new(Point.new(0, 0), Point.new(5, 0), Point.new(0, 5))\nvar t2 = Triangle.new(Point.new(0, 0), Point.new(5, 0), Point.new(0, 6))\nprintTris.call(t1, t2, \"\")\nSystem.print(triTri2D.call(t1, t2, 0, false, true) ? \"overlap\" : \"do not overlap\")\n\n// need to allow reversed for this pair to avoid exception\nt1 = Triangle.new(Point.new(0, 0), Point.new(0, 5), Point.new(5, 0))\nt2 = t1\nprintTris.call(t1, t2, \"\\n\")\nSystem.print(triTri2D.call(t1, t2, 0, true, true) ? \"overlap (reversed)\" : \"do not overlap\")\n\nt1 = Triangle.new(Point.new(0, 0), Point.new(5, 0), Point.new(0, 5))\nt2 = Triangle.new(Point.new(-10, 0), Point.new(-5, 0), Point.new(-1, 6))\nprintTris.call(t1, t2, \"\\n\")\nSystem.print(triTri2D.call(t1, t2, 0, false, true) ? \"overlap\" : \"do not overlap\")\n\nt1.p3 = Point.new(2.5, 5)\nt2 = Triangle.new(Point.new(0, 4), Point.new(2.5, -1), Point.new(5, 4))\nprintTris.call(t1, t2, \"\\n\")\nSystem.print(triTri2D.call(t1, t2, 0, false, true) ? \"overlap\" : \"do not overlap\")\n\nt1 = Triangle.new(Point.new(0, 0), Point.new(1, 1), Point.new(0, 2))\nt2 = Triangle.new(Point.new(2, 1), Point.new(3, 0), Point.new(3, 2))\nprintTris.call(t1, t2, \"\\n\")\nSystem.print(triTri2D.call(t1, t2, 0, false, true) ? \"overlap\" : \"do not overlap\")\n\nt2 = Triangle.new(Point.new(2, 1), Point.new(3, -2), Point.new(3, 4))\nprintTris.call(t1, t2, \"\\n\")\nSystem.print(triTri2D.call(t1, t2, 0, false, true) ? \"overlap\" : \"do not overlap\")\n\nt1 = Triangle.new(Point.new(0, 0), Point.new(1, 0), Point.new(0, 1))\nt2 = Triangle.new(Point.new(1, 0), Point.new(2, 0), Point.new(1, 1.1))\nprintTris.call(t1, t2, \"\\n\")\nSystem.print(\"which have only a single corner in contact, if boundary points collide\")\nSystem.print(triTri2D.call(t1, t2, 0, false, true) ? \"overlap\" : \"do not overlap\")\n\nprintTris.call(t1, t2, \"\\n\")\nSystem.print(\"which have only a single corner in contact, if boundary points do not collide\")\nSystem.print(triTri2D.call(t1, t2, 0, false, false) ? \"overlap\" : \"do not overlap\")\n", "language": "Wren" }, { "code": "// A triangle is three pairs of points: ( (x,y), (x,y), (x,y) )\n\nfcn det2D(triangle){\n p1,p2,p3 := triangle;\n p1[0]*(p2[1] - p3[1]) + p2[0]*(p3[1] - p1[1]) + p3[0]*(p1[1] - p2[1]);\n}\nfcn checkTriWinding(triangle,allowReversed){ //-->triangle, maybe new\n detTri:=det2D(triangle);\n if(detTri<0.0){\n if(allowReversed){ p1,p2,p3 := triangle; return(p1,p3,p2); } // reverse\n else throw(Exception.AssertionError(\n\t\t \"triangle has wrong winding direction\"));\n }\n triangle\t// no change\n}\nfcn triTri2D(triangle1,triangle2, eps=0.0, allowReversed=False, onBoundary=True){\n // Trangles must be expressed anti-clockwise\n triangle1=checkTriWinding(triangle1, allowReversed);\n triangle2=checkTriWinding(triangle2, allowReversed);\n\n chkEdge:=\n if(onBoundary) // Points on the boundary are considered as colliding\n\t fcn(triangle,eps){ det2D(triangle)<eps }\n else // Points on the boundary are not considered as colliding\n\t fcn(triangle,eps){ det2D(triangle)<=eps };; // first ; terminates if\n\n t1,t2 := triangle1,triangle2;\t// change names to protect the typist\n do(2){\t\t\t\t// check triangle1 and then triangle2\n foreach i in (3){\t//For edge E of trangle 1,\n\t j:=(i+1)%3;\t// 1,2,0\n\t // Check all points of trangle 2 lay on the external side\n\t // of the edge E. If they do, the triangles do not collide.\n\t if(chkEdge(T(t1[i],t1[j],t2[0]), eps) and\n\t chkEdge(T(t1[i],t1[j],t2[1]), eps) and\n\t chkEdge(T(t1[i],t1[j],t2[2]), eps)) return(False); // no collision\n }\n t2,t1 = triangle1,triangle2; // flip and re-test\n }\n True // The triangles collide\n}\n", "language": "Zkl" }, { "code": "fcn toTri(ax,ay,bx,by,cx,cy){ //-->( (ax,ay),(bx,by),(cx,cy) )\n vm.arglist.apply(\"toFloat\").pump(List,Void.Read)\n}\ntriangles:=T(\t// pairs of triangles\n T(toTri(0,0, 5,0, 0, 5), toTri( 0,0, 5, 0, 0,6)),\n T(toTri(0,0, 0,5, 5, 0), toTri( 0,0, 0, 5 , 5,0)),\n T(toTri(0,0, 5,0, 0, 5), toTri(-10,0, -5, 0, -1,6)),\n T(toTri(0,0, 5,0, 2.5,5), toTri( 0,4, 2.5,-1, 5,4)),\n T(toTri(0,0, 1,1, 0, 2), toTri( 2,1, 3, 0, 3,2)),\n T(toTri(0,0, 1,1, 0, 2), toTri( 2,1, 3, -2, 3,4))\n);\n\n // Expect: overlap, overlap (reversed), no overlap, overlap, no overlap, no overlap\nforeach t1,t2 in (triangles){\n reg r, reversed=False;\n try{ r=triTri2D(t1,t2) }\n catch(AssertionError){ r=triTri2D(t1,t2,0.0,True); reversed=True; }\n print(t1,\"\\n\",t2,\" \");\n println(r and \"overlap\" or \"no overlap\", reversed and \" (reversed)\" or \"\");\n println();\n}\n\nc1,c2 := toTri(0,0, 1,0, 0,1), toTri(1,0, 2,0, 1,1);\nprintln(\"Corner case (barely touching): \",triTri2D(c1,c2,0.0,False,True)); // True\nprintln(\"Corner case (barely touching): \",triTri2D(c1,c2,0.0,False,False)); // False\n", "language": "Zkl" } ]
Determine-if-two-triangles-overlap
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Dice_game_probabilities\n", "language": "00-META" }, { "code": "Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.\n\nThey roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?\n\nLater the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?\n\nThis task was adapted from the Project Euler Problem n.205:\nhttps://projecteuler.net/problem=205\n\n", "language": "00-TASK" }, { "code": "F throw_die(n_sides, n_dice, s, [Int] &counts)\n I n_dice == 0\n counts[s]++\n R\n L(i) 1..n_sides\n throw_die(n_sides, n_dice - 1, s + i, counts)\n\nF beating_probability(n_sides1, n_dice1,\n n_sides2, n_dice2)\n V len1 = (n_sides1 + 1) * n_dice1\n V C1 = [0] * len1\n throw_die(n_sides1, n_dice1, 0, &C1)\n\n V len2 = (n_sides2 + 1) * n_dice2\n V C2 = [0] * len2\n throw_die(n_sides2, n_dice2, 0, &C2)\n\n Float p12 = (n_sides1 ^ n_dice1) * (n_sides2 ^ n_dice2)\n\n V tot = 0.0\n L(i) 0 .< len1\n L(j) 0 .< min(i, len2)\n tot += Float(C1[i]) * C2[j] / p12\n R tot\n\nprint(‘#.16’.format(beating_probability(4, 9, 6, 6)))\nprint(‘#.16’.format(beating_probability(10, 5, 7, 6)))\n", "language": "11l" }, { "code": "INCLUDE \"D2:REAL.ACT\" ;from the Action! Tool Kit\n\nBYTE FUNC Roll(BYTE sides,dices)\n BYTE i,sum\n\n sum=0\n FOR i=1 TO dices\n DO\n sum==+Rand(sides)+1\n OD\nRETURN (sum)\n\nPROC Test(BYTE sides1,dices1,sides2,dices2)\n INT i,count=[10000],sum1,sum2,wins1,wins2,draws\n REAL r1,r2,p\n\n wins1=0 wins2=0 draws=0\n FOR i=1 TO count\n DO\n sum1=Roll(sides1,dices1)\n sum2=Roll(sides2,dices2)\n IF sum1>sum2 THEN\n wins1==+1\n ELSEIF sum1<sum2 THEN\n wins2==+1\n ELSE\n draws==+1\n FI\n OD\n\n IntToReal(wins1,r1)\n IntToReal(wins2,r2)\n RealDiv(r2,r1,p)\n\n PrintF(\"Tested %I times%E\",count)\n PrintF(\"Player 1 with %B dice of %B sides%E\",dices1,sides1)\n PrintF(\"Player 2 with %B dice of %B sides%E\",dices2,sides2)\n PrintF(\"Player 1 wins %I times%E\",wins1)\n PrintF(\"Player 2 wins %I times%E\",wins2)\n PrintF(\"Draw %I times%E\",draws)\n Print(\"Player 1 beating Player 2 probability:\")\n PrintRE(p)\n PutE()\nRETURN\n\nPROC Main()\n Put(125) PutE() ;clear the screen\n\n Test(4,9,6,6)\n Test(10,5,7,6)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Numerics.Discrete_Random;\n\nprocedure Main is\n package real_io is new Float_IO (Long_Float);\n use real_io;\n\n type Dice is record\n Faces : Positive;\n Num_Dice : Positive;\n end record;\n\n procedure Roll_Dice (The_Dice : in Dice; Count : out Natural) is\n subtype Faces is Integer range 1 .. The_Dice.Faces;\n package Die_Random is new Ada.Numerics.Discrete_Random (Faces);\n use Die_Random;\n Seed : Generator;\n begin\n Reset (Seed);\n Count := 0;\n for I in 1 .. The_Dice.Num_Dice loop\n Count := Count + Random (Seed);\n end loop;\n end Roll_Dice;\n\n function Win_Prob\n (Dice_1 : Dice; Dice_2 : Dice; Tries : Positive) return Long_Float\n is\n Count_1 : Natural := 0;\n Count_2 : Natural := 0;\n Count_1_Wins : Natural := 0;\n begin\n for I in 1 .. Tries loop\n Roll_Dice (Dice_1, Count_1);\n Roll_Dice (Dice_2, Count_2);\n if Count_1 > Count_2 then\n Count_1_Wins := Count_1_Wins + 1;\n end if;\n end loop;\n return Long_Float (Count_1_Wins) / Long_Float (Tries);\n end Win_Prob;\n\n D1 : Dice := (Faces => 4, Num_Dice => 9);\n D2 : Dice := (Faces => 6, Num_Dice => 6);\n D3 : Dice := (Faces => 10, Num_Dice => 5);\n D4 : Dice := (Faces => 7, Num_Dice => 6);\n\n P1 : Long_Float := Win_Prob (D1, D2, 1_000_000);\n P2 : Long_Float := Win_Prob (D3, D4, 1_000_000);\nbegin\n Put (\"Dice D1 wins = \");\n Put (Item => P1, Fore => 1, Aft => 7, Exp => 0);\n New_Line;\n Put (\"Dice D2 wins = \");\n Put (Item => P2, Fore => 1, Aft => 7, Exp => 0);\n New_Line;\nend Main;\n", "language": "Ada" }, { "code": "dado1 = 9: lado1 = 4\ndado2 = 6: lado2 = 6\ntotal1 = 0: total2 = 0\n\nfor i = 0 to 1\n for cont = 1 to 100000\n jugador1 = lanzamiento(dado1, lado1)\n jugador2 = lanzamiento(dado2, lado2)\n if jugador1 > jugador2 then\n total1 = total1 + 1\n else\n if jugador1 <> jugador2 then total2 = total2 + 1\n endif\n next cont\n\n print \"Lanzado el dado \"; (cont - 1); \" veces\"\n print \"jugador1 con \"; dado1; \" dados de \"; lado1; \" lados\"\n print \"jugador2 con \"; dado2; \" dados de \"; lado2; \" lados\"\n print \"Total victorias jugador1 = \"; total1; \" => \"; left(string(total2 / total1), 9)\n print \"Total victorias jugador2 = \"; total2\n print (cont - 1) - (total1 + total2); \" empates\" + chr(10)\n\n dado1 = 5: lado1 = 10\n dado2 = 6: lado2 = 7\n total1 = 0: total2 = 0\nnext i\nend\n\nfunction lanzamiento(dado, lado)\n total = 0\n\n for lanza = 1 to dado\n total = total + int(rand * lado) + 1\n next lanza\n return total\nend function\n", "language": "BASIC256" }, { "code": "#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint32_t uint;\ntypedef uint64_t ulong;\n\nulong ipow(const uint x, const uint y) {\n ulong result = 1;\n for (uint i = 1; i <= y; i++)\n result *= x;\n return result;\n}\n\nuint min(const uint x, const uint y) {\n return (x < y) ? x : y;\n}\n\nvoid throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {\n if (n_dice == 0) {\n counts[s]++;\n return;\n }\n\n for (uint i = 1; i < n_sides + 1; i++)\n throw_die(n_sides, n_dice - 1, s + i, counts);\n}\n\ndouble beating_probability(const uint n_sides1, const uint n_dice1,\n const uint n_sides2, const uint n_dice2) {\n const uint len1 = (n_sides1 + 1) * n_dice1;\n uint C1[len1];\n for (uint i = 0; i < len1; i++)\n C1[i] = 0;\n throw_die(n_sides1, n_dice1, 0, C1);\n\n const uint len2 = (n_sides2 + 1) * n_dice2;\n uint C2[len2];\n for (uint j = 0; j < len2; j++)\n C2[j] = 0;\n throw_die(n_sides2, n_dice2, 0, C2);\n\n const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));\n\n double tot = 0;\n for (uint i = 0; i < len1; i++)\n for (uint j = 0; j < min(i, len2); j++)\n tot += (double)C1[i] * C2[j] / p12;\n return tot;\n}\n\nint main() {\n printf(\"%1.16f\\n\", beating_probability(4, 9, 6, 6));\n printf(\"%1.16f\\n\", beating_probability(10, 5, 7, 6));\n return 0;\n}\n", "language": "C" }, { "code": "#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <map>\n\n// Returns map from sum of faces to number of ways it can happen\nstd::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {\n std::map<uint32_t, uint32_t> result;\n for (uint32_t i = 1; i <= faces; ++i)\n result.emplace(i, 1);\n for (uint32_t d = 2; d <= dice; ++d) {\n std::map<uint32_t, uint32_t> tmp;\n for (const auto& p : result) {\n for (uint32_t i = 1; i <= faces; ++i)\n tmp[p.first + i] += p.second;\n }\n tmp.swap(result);\n }\n return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n auto totals1 = get_totals(dice1, faces1);\n auto totals2 = get_totals(dice2, faces2);\n double wins = 0;\n for (const auto& p1 : totals1) {\n for (const auto& p2 : totals2) {\n if (p2.first >= p1.first)\n break;\n wins += p1.second * p2.second;\n }\n }\n double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n return wins/total;\n}\n\nint main() {\n std::cout << std::setprecision(10);\n std::cout << probability(9, 4, 6, 6) << '\\n';\n std::cout << probability(5, 10, 6, 7) << '\\n';\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\n\nclass Program\n{\n static uint MinOf(uint x, uint y)\n {\n return x < y ? x : y;\n }\n\n static void ThrowDie(uint nSides, uint nDice, uint s, uint[] counts)\n {\n if (nDice == 0)\n {\n counts[s]++;\n return;\n }\n for (uint i = 1; i <= nSides; i++)\n {\n ThrowDie(nSides, nDice - 1, s + i, counts);\n }\n }\n\n static double BeatingProbability(uint nSides1, uint nDice1, uint nSides2, uint nDice2)\n {\n uint len1 = (nSides1 + 1) * nDice1;\n uint[] c1 = new uint[len1]; // initialized to zero by default\n ThrowDie(nSides1, nDice1, 0, c1);\n\n uint len2 = (nSides2 + 1) * nDice2;\n uint[] c2 = new uint[len2];\n ThrowDie(nSides2, nDice2, 0, c2);\n double p12 = Math.Pow(nSides1, nDice1) * Math.Pow(nSides2, nDice2);\n\n double tot = 0.0;\n for (uint i = 0; i < len1; i++)\n {\n for (uint j = 0; j < MinOf(i, len2); j++)\n {\n tot += (double)(c1[i] * c2[j]) / p12;\n }\n }\n return tot;\n }\n\n static void Main(string[] args)\n {\n Console.WriteLine(BeatingProbability(4, 9, 6, 6));\n Console.WriteLine(BeatingProbability(10, 5, 7, 6));\n }\n}\n", "language": "C-sharp" }, { "code": "(defun n-ways (n f s &optional (mem (make-array '(999 99) :initial-element -1)))\n (cond ((and (= n 0) (= s 0)) 1)\n ((or (= n 0) (<= s 0)) 0)\n ((>= (aref mem s n) 0) (aref mem s n))\n (t (loop for i from 1 to f\n sum (n-ways (1- n) f (- s i) mem) into total\n finally (return (setf (aref mem s n) total))))))\n\n(defun winning-probability (n1 f1 n2 f2 &aux (w 0))\n (loop for i from n1 to (* n1 f1)\n do (loop for j from n2 to (* n2 f2)\n do (if (> i j)\n (setf w (+ w (* (n-ways n1 f1 i) (n-ways n2 f2 j))))))\n finally (return (/ w (* (expt f1 n1) (expt f2 n2))))))\n", "language": "Common-Lisp" }, { "code": "import std.stdio, std.range, std.algorithm;\n\nvoid throwDie(in uint nSides, in uint nDice, in uint s, uint[] counts)\npure nothrow @safe @nogc {\n if (nDice == 0) {\n counts[s]++;\n return;\n }\n\n foreach (immutable i; 1 .. nSides + 1)\n throwDie(nSides, nDice - 1, s + i, counts);\n}\n\nreal beatingProbability(uint nSides1, uint nDice1,\n uint nSides2, uint nDice2)()\npure nothrow @safe /*@nogc*/ {\n uint[(nSides1 + 1) * nDice1] C1;\n throwDie(nSides1, nDice1, 0, C1);\n\n uint[(nSides2 + 1) * nDice2] C2;\n throwDie(nSides2, nDice2, 0, C2);\n\n immutable p12 = real((ulong(nSides1) ^^ nDice1) *\n (ulong(nSides2) ^^ nDice2));\n\n return cartesianProduct(C1[].enumerate, C2[].enumerate)\n .filter!(p => p[0][0] > p[1][0])\n .map!(p => real(p[0][1]) * p[1][1] / p12)\n .sum;\n}\n\nvoid main() @safe {\n writefln(\"%1.16f\", beatingProbability!(4, 9, 6, 6));\n writefln(\"%1.16f\", beatingProbability!(10, 5, 7, 6));\n}\n", "language": "D" }, { "code": "import std.stdio, std.range, std.algorithm;\n\nulong[] combos(R)(R sides, in uint n) pure nothrow @safe\nif (isForwardRange!R) {\n if (sides.empty)\n return null;\n if (!n)\n return [1];\n auto ret = new typeof(return)(reduce!max(sides[0], sides[1 .. $]) * n + 1);\n foreach (immutable i, immutable v; enumerate(combos(sides, n - 1))) {\n if (!v)\n continue;\n foreach (immutable s; sides)\n ret[i + s] += v;\n }\n return ret;\n}\n\nreal winning(R)(R sides1, in uint n1, R sides2, in uint n2)\npure nothrow @safe if (isForwardRange!R) {\n static void accumulate(T)(T[] arr) pure nothrow @safe @nogc {\n foreach (immutable i; 1 .. arr.length)\n arr[i] += arr[i - 1];\n }\n\n immutable p1 = combos(sides1, n1);\n auto p2 = combos(sides2, n2);\n immutable s = p1.sum * p2.sum;\n accumulate(p2);\n ulong win = 0; // 'win' is 1 beating 2.\n foreach (immutable i, immutable x1; p1.dropOne.enumerate)\n win += x1 * p2[min(i, $ - 1)];\n return win / real(s);\n}\n\nvoid main() @safe {\n writefln(\"%1.16f\", winning(iota(1u, 5u), 9, iota(1u, 7u), 6));\n writefln(\"%1.16f\", winning(iota(1u, 11u), 5, iota(1u, 8u), 6));\n}\n", "language": "D" }, { "code": "proc throw_die n_sides n_dice s . counts[] .\n if n_dice = 0\n counts[s] += 1\n return\n .\n for i = 1 to n_sides\n throw_die n_sides (n_dice - 1) (s + i) counts[]\n .\n.\nfunc proba n_sides1 n_dice1 n_sides2 n_dice2 .\n len c1[] (n_sides1 + 1) * n_dice1\n len c2[] (n_sides2 + 1) * n_dice2\n throw_die n_sides1 n_dice1 0 c1[]\n throw_die n_sides2 n_dice2 0 c2[]\n p12 = pow n_sides1 n_dice1 * pow n_sides2 n_dice2\n for i = 1 to len c1[]\n for j = 1 to lower (i - 1) len c2[]\n tot += c1[i] * c2[j] / p12\n .\n .\n return tot\n.\nnumfmt 5 0\nprint proba 4 9 6 6\nprint proba 10 5 7 6\n", "language": "EasyLang" }, { "code": "USING: dice generalizations kernel math prettyprint sequences ;\nIN: rosetta-code.dice-probabilities\n\n: winning-prob ( a b c d -- p )\n [ [ random-roll ] 2bi@ > ] 4 ncurry [ 100000 ] dip replicate\n [ [ t = ] count ] [ length ] bi /f ;\n\n9 4 6 6 winning-prob\n5 10 6 7 winning-prob [ . ] bi@\n", "language": "Factor" }, { "code": "#! /usr/bin/gforth\n\n\\ Dice game probabilities\n\n: min? ( addr -- min )\n @\n;\n\n: max? ( addr -- max )\n cell + @\n;\n\n: max+1-min? ( addr -- max+1 min )\n dup max? 1+ swap min?\n;\n\n: addr? ( addr x -- addr' )\n over min? - 2 + cells +\n;\n\n: weight? ( addr x -- w )\n 2dup swap min? < IF\n 2drop 0\n ELSE\n 2dup swap max? > IF\n 2drop 0\n ELSE\n addr? @\n THEN\n THEN\n;\n\n: total-weight? ( addr -- w )\n dup max? 1+ ( addr max+1 )\n over min? ( addr max+1 min )\n 0 -rot ?DO ( adrr 0 max+1 min )\n over i weight? +\n LOOP\n nip\n;\n\n: uniform-aux ( min max x -- addr )\n >r 2dup\n 2dup swap - 3 + cells allocate throw ( min max min max addr )\n tuck cell + ! ( min max min addr )\n tuck ! ( min max addr )\n -rot swap ( addr max min )\n r> -rot ( addr x max min )\n - 3 + 2 ?DO ( addr x )\n 2dup swap i cells + !\n LOOP\n drop\n;\n\n: convolve { addr1 addr2 -- addr }\n addr1 min? addr2 min? +\n addr1 max? addr2 max? +\n 0 uniform-aux { addr }\n addr1 max+1-min? ?DO\n addr2 max+1-min? ?DO\n addr1 j weight?\n addr2 i weight? *\n addr i j + addr? +!\n LOOP\n LOOP\n addr\n;\n\n: even? ( n -- f )\n 2 mod 0=\n;\n\n: power ( addr exp -- addr' )\n dup 1 = IF\n drop\n ELSE\n dup even? IF\n 2/ recurse dup convolve\n ELSE\n over swap 2/ recurse dup convolve convolve\n THEN\n THEN\n;\n\n: .dist { addr -- }\n addr total-weight? { tw }\n addr max+1-min? ?DO\n i 10 .r\n addr i weight? dup 20 .r\n 0 d>f tw 0 d>f f/ .\" \" f. cr\n LOOP\n;\n\n: dist-cmp { addr1 addr2 xt -- p }\n 0\n addr1 max+1-min? ?DO\n addr2 max+1-min? ?DO\n j i xt execute IF\n addr1 j weight?\n addr2 i weight?\n * +\n THEN\n LOOP\n LOOP\n 0 d>f\n addr1 total-weight? addr2 total-weight? um* d>f\n f/\n;\n\n: dist> ( addr1 addr2 -- p )\n ['] > dist-cmp\n;\n\n\\ creates the uniform distribution with outcomes from min to max\n: uniform ( min max -- addr )\n 1 uniform-aux\n;\n\n\\ example\n\n1 4 uniform 9 power\n1 6 uniform 6 power\ndist> f. cr\n\n1 10 uniform 5 power\n1 7 uniform 6 power\ndist> f. cr\n\nbye\n", "language": "Forth" }, { "code": "Dim As Integer lado, jugador1, jugador2, total1, total2, cont, i\nDim As Integer dado1 = 9, lado1 = 4\nDim As Integer dado2 = 6, lado2 = 6\n\nRandomize Timer\n\nFunction Lanzamiento(dado As Integer, lado As Integer) As Integer\n Dim As Short lanza, total\n\n For lanza = 1 To dado\n total += Int(Rnd * lado) + 1\n Next lanza\n Return total\nEnd Function\n\nFor i = 0 To 1\n For cont = 1 To 100000\n jugador1 = Lanzamiento(dado1, lado1)\n jugador2 = Lanzamiento(dado2, lado2)\n If jugador1 > jugador2 Then\n total1 += 1\n Elseif jugador1 <> jugador2 Then\n total2 += 1\n End If\n Next cont\n\n Print Using \"Lanzado el dado & veces\"; (cont - 1)\n Print \"jugador1 con\"; dado1; \" dados de\"; lado1; \" lados\"\n Print \"jugador2 con\"; dado2; \" dados de\"; lado2; \" lados\"\n Print Using \"Total victorias jugador1 = & => #.#######\"; total1; (total2 / total1)\n Print \"Total victorias jugador2 =\"; total2\n Print (cont - 1) - (total1 + total2); !\" empates\\n\"\n\n dado1 = 5: lado1 = 10\n dado2 = 6: lado2 = 7\n total1 = 0: total2 = 0\nNext i\n\nSleep\n", "language": "FreeBASIC" }, { "code": "local fn RollTheDice( dice as long, sides as long ) as long\n long i, total = 0\n\n for i = 1 to dice\n total += rnd(sides)\n next\nend fn = total\n\n\nvoid local fn CaclulateProbabilities( dice1 as long, sides1 as long, dice2 as long, sides2 as long )\n long i, player1, player2\n float total1 = 0, total2 = 0, total3 = 0\n\n for i = 1 to 100000\n player1 = fn RollTheDice( dice1, sides1 )\n player2 = fn RollTheDice( dice2, sides2 )\n if ( player1 > player2 ) then total1++ : continue\n if ( player1 < player2 ) then total2++ : continue\n if ( player1 == player2 ) then total3++ : continue\n next\n\n printf @\"Dice cast %ld times.\", i - 1\n printf @\"Player 1 with %ld dice of %ld sides.\", dice1, sides1\n printf @\"Player 2 with %ld dice of %ld sides.\", dice2, sides2\n printf @\"Total wins Player 1 = %.f. Probability of winning: %0.4f%%.\", total1, (total1 / i ) * 100\n printf @\"Total wins Player 2 = %.f\", total2\n printf @\"Number of ties: %.f.\", total3\nend fn\n\nrandomize\nprint\nfn CaclulateProbabilities( 9, 4, 6, 6 )\nprint\nfn CaclulateProbabilities( 5, 10, 6, 7 )\nprint\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "' Gambas module file\n\nPublic Sub Main()\nDim iSides, iPlayer1, iPlayer2, iTotal1, iTotal2, iCount, iCount0 As Integer\nDim iDice1 As Integer = 9\nDim iDice2 As Integer = 6\nDim iSides1 As Integer = 4\nDim iSides2 As Integer = 6\n\nRandomize\n\nFor iCount0 = 0 To 1\n For iCount = 1 To 100000\n iPlayer1 = Roll(iDice1, iSides1)\n iPlayer2 = Roll(iDice2, iSides2)\n If iPlayer1 > iPlayer2 Then\n iTotal1 += 1\n Else If iPlayer1 <> iPlayer2 Then\n iTotal2 += 1\n Endif\n Next\n\n Print \"Tested \" & Str(iCount - 1) & \" times\"\n Print \"Player1 with \" & Str(iDice1) & \" dice of \" & Str(iSides1) & \" sides\"\n Print \"Player2 with \" & Str(iDice2) & \" dice of \" & Str(iSides2) & \" sides\"\n Print \"Total wins Player1 = \" & Str(iTotal1) & \" - \" & Str(iTotal2 / iTotal1)\n Print \"Total wins Player2 = \" & Str(iTotal2)\n Print Str((iCount - 1) - (iTotal1 + iTotal2)) & \" draws\" & gb.NewLine\n\n iDice1 = 5\n iDice2 = 6\n iSides1 = 10\n iSides2 = 7\n iTotal1 = 0\n iTotal2 = 0\nNext\n\nEnd\n\nPublic Sub Roll(iDice As Integer, iSides As Integer) As Integer\nDim iCount, iTotal As Short\n\nFor iCount = 1 To iDice\n iTotal += Rand(1, iSides)\nNext\n\nReturn iTotal\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport(\n \"math\"\n \"fmt\"\n)\n\nfunc minOf(x, y uint) uint {\n if x < y {\n return x\n }\n return y\n}\n\nfunc throwDie(nSides, nDice, s uint, counts []uint) {\n if nDice == 0 {\n counts[s]++\n return\n }\n for i := uint(1); i <= nSides; i++ {\n throwDie(nSides, nDice - 1, s + i, counts)\n }\n}\n\nfunc beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {\n len1 := (nSides1 + 1) * nDice1\n c1 := make([]uint, len1) // all elements zero by default\n throwDie(nSides1, nDice1, 0, c1)\n\n len2 := (nSides2 + 1) * nDice2\n c2 := make([]uint, len2)\n throwDie(nSides2, nDice2, 0, c2)\n p12 := math.Pow(float64(nSides1), float64(nDice1)) *\n math.Pow(float64(nSides2), float64(nDice2))\n\n tot := 0.0\n for i := uint(0); i < len1; i++ {\n for j := uint(0); j < minOf(i, len2); j++ {\n tot += float64(c1[i] * c2[j]) / p12\n }\n }\n return tot\n}\n\nfunc main() {\n fmt.Println(beatingProbability(4, 9, 6, 6))\n fmt.Println(beatingProbability(10, 5, 7, 6))\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n)\n\ntype set struct {\n\tn, s int\n}\n\nfunc (s set) roll() (sum int) {\n\tfor i := 0; i < s.n; i++ {\n\t\tsum += rand.Intn(s.s) + 1\n\t}\n\treturn\n}\n\nfunc (s set) beats(o set, n int) (p float64) {\n\tfor i := 0; i < n; i++ {\n\t\tif s.roll() > o.roll() {\n\t\t\tp = p + 1.0\n\t\t}\n\t}\n\tp = p / float64(n)\n\treturn\n}\n\nfunc main() {\n\tfmt.Println(set{9, 4}.beats(set{6, 6}, 1000))\n\tfmt.Println(set{5, 10}.beats(set{6, 7}, 1000))\n}\n", "language": "Go" }, { "code": "import Control.Monad (replicateM)\nimport Data.List (group, sort)\n\nsucceeds :: (Int, Int) -> (Int, Int) -> Double\nsucceeds p1 p2 =\n sum\n [ realToFrac (c1 * c2) / totalOutcomes\n | (s1, c1) <- countSums p1\n , (s2, c2) <- countSums p2\n , s1 > s2 ]\n where\n totalOutcomes = realToFrac $ uncurry (^) p1 * uncurry (^) p2\n countSums (nFaces, nDice) = f [1 .. nFaces]\n where\n f =\n fmap (((,) . head) <*> (pred . length)) .\n group . sort . fmap sum . replicateM nDice\n\nmain :: IO ()\nmain = do\n print $ (4, 9) `succeeds` (6, 6)\n print $ (10, 5) `succeeds` (7, 6)\n", "language": "Haskell" }, { "code": "gen_dict =: (({. , #)/.~@:,@:(+/&>)@:{@:(# <@:>:@:i.)~ ; ^)&x:\n\nbeating_probability =: dyad define\n 'C0 P0' =. gen_dict/ x\n 'C1 P1' =. gen_dict/ y\n (C0 +/@:,@:(>/&:({.\"1) * */&:({:\"1)) C1) % (P0 * P1)\n)\n", "language": "J" }, { "code": " 10 5 (;x:inv)@:beating_probability 7 6\n┌─────────────────────┬────────┐\n│3781171969r5882450000│0.642789│\n└─────────────────────┴────────┘\n 4 9 (;x:inv)@:beating_probability 6 6\n┌─────────────────┬────────┐\n│48679795r84934656│0.573144│\n└─────────────────┴────────┘\n", "language": "J" }, { "code": "import java.util.Random;\n\npublic class Dice{\n\tprivate static int roll(int nDice, int nSides){\n\t\tint sum = 0;\n\t\tRandom rand = new Random();\n\t\tfor(int i = 0; i < nDice; i++){\n\t\t\tsum += rand.nextInt(nSides) + 1;\n\t\t}\n\t\treturn sum;\n\t}\n\t\n\tprivate static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){\n\t\tint p1Wins = 0;\n\t\tfor(int i = 0; i < rolls; i++){\n\t\t\tint p1Roll = roll(p1Dice, p1Sides);\n\t\t\tint p2Roll = roll(p2Dice, p2Sides);\n\t\t\tif(p1Roll > p2Roll) p1Wins++;\n\t\t}\n\t\treturn p1Wins;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tint p1Dice = 9; int p1Sides = 4;\n\t\tint p2Dice = 6; int p2Sides = 6;\n\t\tint rolls = 10000;\n\t\tint p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 10000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 9; p1Sides = 4;\n\t\tp2Dice = 6; p2Sides = 6;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t}\n}\n", "language": "Java" }, { "code": "let Player = function(dice, faces) {\n this.dice = dice;\n this.faces = faces;\n this.roll = function() {\n let results = [];\n for (let x = 0; x < dice; x++)\n results.push(Math.floor(Math.random() * faces +1));\n return eval(results.join('+'));\n }\n}\n\nfunction contest(player1, player2, rounds) {\n let res = [0, 0, 0];\n for (let x = 1; x <= rounds; x++) {\n let a = player1.roll(),\n b = player2.roll();\n switch (true) {\n case (a > b): res[0]++; break;\n case (a < b): res[1]++; break;\n case (a == b): res[2]++; break;\n }\n }\n document.write(`\n <p>\n <b>Player 1</b> (${player1.dice} × d${player1.faces}): ${res[0]} wins<br>\n <b>Player 2</b> (${player2.dice} × d${player2.faces}): ${res[1]} wins<br>\n <b>Draws:</b> ${res[2]}<br>\n Chances for Player 1 to win:\n ~${Math.round(res[0] / eval(res.join('+')) * 100)} %\n </p>\n `);\n}\n\nlet p1, p2;\n\np1 = new Player(9, 4),\np2 = new Player(6, 6);\ncontest(p1, p2, 1e6);\n\np1 = new Player(5, 10);\np2 = new Player(6, 7);\ncontest(p1, p2, 1e6);\n", "language": "JavaScript" }, { "code": "# To take advantage of gojq's arbitrary-precision integer arithmetic:\ndef power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);\n\n# Input: an array (aka: counts)\ndef throwDie($nSides; $nDice; $s):\n if $nDice == 0\n then .[$s] += 1\n else reduce range(1; $nSides + 1) as $i (.;\n throwDie($nSides; $nDice-1; $s + $i) )\n end ;\n\ndef beatingProbability(nSides1; nDice1; nSides2; nDice2):\n def a: [range(0; .) | 0];\n\n ((nSides1 + 1) * nDice1) as $len1\n | ($len1 | a | throwDie(nSides1; nDice1; 0)) as $c1\n\n | ((nSides2 + 1) * nDice2) as $len2\n | ($len2 | a | throwDie(nSides2; nDice2; 0)) as $c2\n\n |((nSides1|power(nDice1)) * (nSides2|power(nDice2))) as $p12\n\n | reduce range(0; $len1) as $i (0;\n reduce range(0; [$i, $len2] | min) as $j (.;\n . + ($c1[$i] * $c2[$j] / $p12) ) ) ;\n\nbeatingProbability(4; 9; 6; 6),\nbeatingProbability(10; 5; 7; 6)\n", "language": "Jq" }, { "code": "play(ndices::Integer, nfaces::Integer) = (nfaces, ndices) ∋ 0 ? 0 : sum(rand(1:nfaces) for i in 1:ndices)\n\nsimulate(d1::Integer, f1::Integer, d2::Integer, f2::Integer; nrep::Integer=1_000_000) =\n mean(play(d1, f1) > play(d2, f2) for _ in 1:nrep)\n\nprintln(\"\\nPlayer 1: 9 dices, 4 faces\\nPlayer 2: 6 dices, 6 faces\\nP(Player1 wins) = \", simulate(9, 4, 6, 6))\nprintln(\"\\nPlayer 1: 5 dices, 10 faces\\nPlayer 2: 6 dices, 7 faces\\nP(Player1 wins) = \", simulate(5, 10, 6, 7))\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nfun throwDie(nSides: Int, nDice: Int, s: Int, counts: IntArray) {\n if (nDice == 0) {\n counts[s]++\n return\n }\n for (i in 1..nSides) throwDie(nSides, nDice - 1, s + i, counts)\n}\n\nfun beatingProbability(nSides1: Int, nDice1: Int, nSides2: Int, nDice2: Int): Double {\n val len1 = (nSides1 + 1) * nDice1\n val c1 = IntArray(len1) // all elements zero by default\n throwDie(nSides1, nDice1, 0, c1)\n\n val len2 = (nSides2 + 1) * nDice2\n val c2 = IntArray(len2)\n throwDie(nSides2, nDice2, 0, c2)\n\n val p12 = Math.pow(nSides1.toDouble(), nDice1.toDouble()) *\n Math.pow(nSides2.toDouble(), nDice2.toDouble())\n\n var tot = 0.0\n for (i in 0 until len1) {\n for (j in 0 until minOf(i, len2)) {\n tot += c1[i] * c2[j] / p12\n }\n }\n return tot\n}\n\nfun main(args: Array<String>) {\n println(beatingProbability(4, 9, 6, 6))\n println(beatingProbability(10, 5, 7, 6))\n}\n", "language": "Kotlin" }, { "code": "local function simu(ndice1, nsides1, ndice2, nsides2)\n local function roll(ndice, nsides)\n local result = 0;\n for i = 1, ndice do\n result = result + math.random(nsides)\n end\n return result\n end\n local wins, coms = 0, 1000000\n for i = 1, coms do\n local roll1 = roll(ndice1, nsides1)\n local roll2 = roll(ndice2, nsides2)\n if (roll1 > roll2) then\n wins = wins + 1\n end\n end\n print(\"simulated: p1 = \"..ndice1..\"d\"..nsides1..\", p2 = \"..ndice2..\"d\"..nsides2..\", prob = \"..wins..\" / \"..coms..\" = \"..(wins/coms))\nend\n\nsimu(9, 4, 6, 6)\nsimu(5, 10, 6, 7)\n", "language": "Lua" }, { "code": "local function comp(ndice1, nsides1, ndice2, nsides2)\n local function throws(ndice, nsides)\n local sums = {}\n for i = 1, ndice*nsides do\n sums[i] = 0\n end\n local function throw(ndice, nsides, s)\n if (ndice==0) then\n sums[s] = sums[s] + 1\n else\n for i = 1, nsides do\n throw(ndice-1, nsides, s+i)\n end\n end\n return sums\n end\n return throw(ndice, nsides, 0)\n end\n local p1 = throws(ndice1, nsides1)\n local p2 = throws(ndice2, nsides2)\n local wins, coms = 0, nsides1^ndice1 * nsides2^ndice2\n for k1,v1 in pairs(p1) do\n for k2,v2 in pairs(p2) do\n if (k1 > k2) then\n wins = wins + v1 * v2\n end\n end\n end\n print(\"computed: p1 = \"..ndice1..\"d\"..nsides1..\", p2 = \"..ndice2..\"d\"..nsides2..\", prob = \"..wins..\" / \"..coms..\" = \"..(wins/coms))\nend\n\ncomp(9, 4, 6, 6)\ncomp(5, 10, 6, 7)\n", "language": "Lua" }, { "code": "Declare random1 lib \"advapi32.SystemFunction036\" {long lpbuffer, long length}\nFlush\nProb(4, 9, 6, 6, 55555)\nProb(10, 5, 7, 6, 55555)\nSub Prob(face1 as long=4 ,dice1=9, face2 as long=6,dice2=6, games=1000)\n\tif face1<1 or face1>256 or face2<1 or face2>256 then Error \"Faces out of limits\"\n\tprofiler\n\tlocal m=@PlayAll(dice1,dice2, games), tt=timecount\n\tprint \"Time to fill the buffer with random bytes \";str$(tt, \"#0.00 ms\")\n\tlocal s1=dice1-1, s2=dice2-1, k, l, f1=face1/256, f2=face2/256, i, n1=0&, n2=0&\n\tprint \"Buffer size \";str$(len(m)/1024,\"#0.#\");\" Kbyte\": Refresh\n\tprofiler\n\tfor i=0 to games-1\n\t\tlong n1=dice1:for j=0to s1{n1+=eval(m, i!n1!j)*f1}\n\t\tlong n2=dice2:for j=0to s2{n2+=eval(m, i!n2!j)*f2}\n\t\tif n1>n2 then k++ else if n1<n2 then l++\n\tnext\n\tprint \"Games Total \"; games\n\tprint \"Player 1 wins \";k; \" probability of winning:\" ;str$(k/games, \"#0.00 %\")\n\tprint \"Player 2 wins \";l; \" probability of winning:\" ;str$(l/games, \"#0.00 %\")\n\tprint \"Number of ties \";games-k-l\n\tprint \"Execution time \";str$(timecount/1000, \"#0.0 s\")\nEnd Sub\nFunction PlayAll(dice1, dice2, games as long)\n if games<1 then error \"games<1\"\n local onegame\n structure onegame {\n n1 as byte * dice1\n n2 as byte * dice2\n }\n buffer Alfa as onegame*games\n call void random1(alfa(0), len(alfa))\n = Alfa\nEnd Function\n", "language": "M2000-Interpreter" }, { "code": "ClearAll[GetProbability]\nGetProbability[{dice1_List, n_Integer}, {dice2_List, m_Integer}] :=\n Module[{a, b, lena, lenb},\n a = Tuples[dice1, n];\n a = Plus @@@ a;\n lena = a // Length;\n a = Tally[a];\n a[[All, 2]] /= lena;\n\n b = Tuples[dice2, m];\n b = Plus @@@ b;\n lenb = b // Length;\n b = Tally[b];\n b[[All, 2]] /= lenb;\n\n Total[If[#[[1, 1]] > #[[2, 1]], #[[1, 2]] #[[2, 2]], 0] & /@\n Tuples[{a, b}]]\n ]\nGetProbability[{Range[4], 9}, {Range[6], 6}]\nGetProbability[{Range[10], 5}, {Range[7], 6}]\n", "language": "Mathematica" }, { "code": "import bignum\nfrom math import sum\n\nproc counts(ndices, nsides: int): seq[int] =\n result.setlen(ndices * nsides + 1)\n for i in 1..nsides:\n result[i] = 1\n for i in 1..<ndices:\n var c = newSeq[int](result.len)\n for sum in i..(i * nsides):\n for val in 1..nsides:\n inc c[sum + val], result[sum]\n result = move(c)\n\nproc probabilities(counts: seq[int]): seq[Rat] =\n result.setLen(counts.len)\n let total = sum(counts)\n for i, n in counts:\n result[i] = newRat(n, total)\n\nproc beatingProbability(ndices1, nsides1, ndices2, nsides2: int): Rat =\n let counts1 = counts(ndices1, nsides1)\n let counts2 = counts(ndices2, nsides2)\n var p1 = counts1.probabilities()\n var p2 = counts2.probabilities()\n\n result = newRat(0)\n for sum1 in ndices1..p1.high:\n var p = newRat(0)\n for sum2 in ndices2..min(sum1 - 1, p2.high):\n p += p2[sum2]\n result += p1[sum1] * p\n\necho beatingProbability(9, 4, 6, 6).toFloat\necho beatingProbability(5, 10, 6, 7).toFloat\n", "language": "Nim" }, { "code": "Numeric Digits 30\nCall test '9 4 6 6'\nCall test '5 10 6 7'\nExit\ntest:\nParse Arg w1 s1 w2 s2\np1.=0\np2.=0\nCall pp 1,w1,s1,p1.,p2.\nCall pp 2,w2,s2,p1.,p2.\np2low.=0\nDo x=w1 To w1*s1\n Do y=0 To x-1\n p2low.x+=p2.y\n End\n End\npwin1=0\nDo x=w1 To w1*s1\n pwin1+=p1.x*p2low.x\n End\nSay 'Player 1 has' w1 'dice with' s1 'sides each'\nSay 'Player 2 has' w2 'dice with' s2 'sides each'\nSay 'Probability for player 1 to win:' pwin1\nSay ''\nReturn\n\npp: Procedure\n/*---------------------------------------------------------------------\n* Compute and assign probabilities to get a sum x\n* when throwing w dice each having s sides (marked from 1 to s)\n* k=1 sets p1.*, k=2 sets p2.*\n*--------------------------------------------------------------------*/\nUse Arg k,w,s,p1.,p2.\nstr=''\ncnt.=0\nDo wi=1 To w\n str=str||'Do v'wi'=1 To' s';'\n End\nstr=str||'sum='\nDo wi=1 To w-1\n str=str||'v'wi'+'\n End\nstr=str||'v'w';'\nstr=str||'cnt.'sum'+=1;'\nDo wi=1 To w\n str=str||'End;'\n End\nInterpret str\npsum=0\nDo x=0 To w*s\n If k=1 Then\n p1.x=cnt.x/(s**w)\n Else\n p2.x=cnt.x/(s**w)\n psum+=p1.x\n End\nReturn\n", "language": "OoRexx" }, { "code": "Numeric Digits 30\nCall test '9 4 6 6'\nCall test '5 10 6 7'\nExit\n\ntest:\nParse Arg w1 s1 w2 s2\np1.='0/1'\np2.='0/1'\nCall pp 1,w1,s1,p1.,p2.\nCall pp 2,w2,s2,p1.,p2.\np2low.='0/1'\nDo x=w1 To w1*s1\n Do y=0 To x-1\n p2low.x=fr_add(p2low.x,p2.y)\n End\n End\npwin1='0/1'\nDo x=w1 To w1*s1\n pwin1=fr_add(pwin1,fr_Mult(p1.x,p2low.x))\n End\nSay 'Player 1 has' w1 'dice with' s1 'sides each'\nSay 'Player 2 has' w2 'dice with' s2 'sides each'\nSay 'Probability for player 1 to win:' pwin1\nParse Var pwin1 nom '/' denom\nSay ' ->' (nom/denom)\nSay ''\nReturn\n\npp: Procedure\n/*---------------------------------------------------------------------\n* Compute and assign probabilities to get a sum x\n* when throwing w dice each having s sides (marked from 1 to s)\n* k=1 sets p1.*, k=2 sets p2.*\n*--------------------------------------------------------------------*/\nUse Arg k,w,s,p1.,p2.\nstr=''\ncnt.=0\nDo wi=1 To w\n str=str||'Do v'wi'=1 To' s';'\n End\nstr=str||'sum='\nDo wi=1 To w-1\n str=str||'v'wi'+'\n End\nstr=str||'v'w';'\nstr=str||'cnt.sum+=1;'\nDo wi=1 To w\n str=str||'End;'\n End\nInterpret str\n\npsum='0/1'\nDo x=0 To w*s\n If k=1 Then\n p1.x=cnt.x'/'||(s**w)\n Else\n p2.x=cnt.x'/'||(s**w)\n psum=fr_add(psum,p1.x)\n End\nReturn\n\n\nfr_add: Procedure\nParse Arg a,b\nparse Var a an '/' az\nparse Var b bn '/' bz\nrn=an*bz+bn*az\nrz=az*bz\nres=fr_cancel(rn','rz)\nReturn res\n\nfr_div: Procedure\nParse Arg a,b\nparse Var a an '/' az\nparse Var b bn '/' bz\nrn=an*bz\nrz=az*bn\nres=fr_cancel(rn','rz)\nReturn res\n\nfr_mult: Procedure\nParse Arg a,b\nparse Var a an '/' az\nparse Var b bn '/' bz\nrn=an*bn\nrz=az*bz\nres=fr_cancel(rn','rz)\nReturn res\n\nfr_cancel: Procedure\nParse Arg n ',' z\nk=ggt(n,z)\nReturn n%k'/'z%k\n\nggt: Procedure\n/**********************************************************************\n* ggt (gcd) Greatest common Divisor\n* Recursive procedure as shown in PL/I\n**********************************************************************/\nParse Arg a,b\nif b = 0 then return abs(a)\nreturn ggt(b,a//b)\n", "language": "OoRexx" }, { "code": "Numeric Digits 50\nCall test '9 4 6 6'\nCall test '5 10 6 7'\nExit\n\ntest:\nParse Arg w1 s1 w2 s2\np1.=.fraction~new(0,1)\np2.=.fraction~new(0,1)\nCall pp 1,w1,s1,p1.,p2.\nCall pp 2,w2,s2,p1.,p2.\np2low.=.fraction~new(0,1)\nDo x=w1 To w1*s1\n Do y=0 To x-1\n p2low.x=p2low.x+p2.y\n End\n End\npwin1=.fraction~new(0,1)\nDo x=w1 To w1*s1\n pwin1=pwin1+(p1.x*p2low.x)\n End\nSay 'Player 1 has' w1 'dice with' s1 'sides each'\nSay 'Player 2 has' w2 'dice with' s2 'sides each'\nSay 'Probability for player 1 to win:' pwin1~string\nSay ' ->' pwin1~tonumber\nSay ''\nReturn\n\npp: Procedure\n/*---------------------------------------------------------------------\n* Compute and assign probabilities to get a sum x\n* when throwing w dice each having s sides (marked from 1 to s)\n* k=1 sets p1.*, k=2 sets p2.*\n*--------------------------------------------------------------------*/\nUse Arg k,w,s,p1.,p2.\nstr=''\ncnt.=0\nDo wi=1 To w\n str=str||'Do v'wi'=1 To' s';'\n End\nstr=str||'sum='\nDo wi=1 To w-1\n str=str||'v'wi'+'\n End\nstr=str||'v'w';'\nstr=str||'cnt.sum+=1;'\nDo wi=1 To w\n str=str||'End;'\n End\nInterpret str\n\npsum=.fraction~new(0,1)\nDo x=0 To w*s\n If k=1 Then\n p1.x=.fraction~new(cnt.x,s**w)\n Else\n p2.x=.fraction~new(cnt.x,s**w)\n psum=psum+p1.x\n End\nReturn\n\n::class fraction inherit orderable\n::options Digits 50\n::method init\n expose numerator denominator\n use strict arg numerator, denominator = 1\n --Trace ?R\n --if numerator == 0 then denominator = 0\n --else if denominator == 0 then raise syntax 98.900 array(\"Fraction denominator cannot be zero\")\n\n -- if the denominator is negative, make the numerator carry the sign\n if denominator < 0 then do\n numerator = -numerator\n denominator = - denominator\n end\n\n\n -- find the greatest common denominator and reduce to\n -- the simplest form\n gcd = self~gcd(numerator~abs, denominator~abs)\n\n numerator /= gcd\n denominator /= gcd\n\n-- fraction instances are immutable, so these are\n-- read only attributes\n\n-- calculate the greatest common denominator of a numerator/denominator pair\n::method gcd private\n use arg x, y\n --Say 'gcd:' x y digits()\n loop while y \\= 0\n -- check if they divide evenly\n temp = x // y\n x = y\n y = temp\n end\n return x\n\n-- calculate the least common multiple of a numerator/denominator pair\n::method lcm private\n use arg x, y\n return x / self~gcd(x, y) * y\n\n::method abs\n expose numerator denominator\n -- the denominator is always forced to be positive\n return self~class~new(numerator~abs, denominator)\n\n-- convert a fraction to regular Rexx number\n::method toNumber\n expose numerator denominator\n if numerator == 0 then return 0\n return numerator/denominator\n\n::method add\n expose numerator denominator\n use strict arg other\n -- convert to a fraction if a regular number\n if \\other~isa(.fraction) then other = self~class~new(other, 1)\n\n multiple = self~lcm(denominator, other~denominator)\n newa = numerator * multiple / denominator\n newb = other~numerator * multiple / other~denominator\n return self~class~new(newa + newb, multiple)\n\n::method times\n expose numerator denominator\n use strict arg other\n -- convert to a fraction if a regular number\n if \\other~isa(.fraction) then other = self~class~new(other, 1)\n return self~class~new(numerator * other~numerator, denominator * other~denominator)\n\n-- some operator overrides -- these only work if the left-hand-side of the\n-- subexpression is a quaternion\n::method \"*\"\n forward message(\"TIMES\")\n\n::method \"+\"\n -- need to check if this is a prefix plus or an addition\n if arg() == 0 then\n return self -- we can return this copy since it is imutable\n else\n forward message(\"ADD\")\n\n::method string\n expose numerator denominator\n if denominator == 1 then return numerator\n return numerator\"/\"denominator\n\n-- override hashcode for collection class hash uses\n::method hashCode\n expose numerator denominator\n return numerator~hashcode~bitxor(numerator~hashcode)\n\n::attribute numerator GET\n::attribute denominator GET\n\n::requires rxmath library\n", "language": "OoRexx" }, { "code": "oid='diet.xxx'; Call sysFileDelete oid\nCall test '9 4 6 6'\nCall test '5 10 6 7'\nExit\ntest:\nParse Arg n1 s1 n2 s2\nCall o 'Player 1:' n1 'dice with' s1 'sides each'\nCall o 'Player 2:' n2 'dice with' s2 'sides each'\ncnt1.=0\ncnt2.=0\nwin.=0\nnn=10000000\nCall time 'R'\nDo i=1 To nn\n sum1=sum(n1 s1) ; cnt1.sum1+=1\n sum2=sum(n2 s2) ; cnt2.sum2+=1\n Select\n When sum1>sum2 Then win.1+=1\n When sum1<sum2 Then win.2+=1\n Otherwise win.0+=1\n End\n End\nCall o win.1/nn 'player 1 wins'\nCall o win.2/nn 'player 2 wins'\nCall o win.0/nn 'draws'\n/*\nDo i=min(n1,n2) To max(n1*s1,n2*s2)\n Call o right(i,2) format(cnt1.i,7) format(cnt2.i,7)\n End\n*/\nCall o time('E') 'seconds elapsed'\nReturn\n\nsum: Parse Arg n s\nsum=0\nDo k=1 To n\n sum+=rand(s)\n End\nReturn sum\n\nrand: Parse Arg n\n Return random(n-1)+1\n\no:\nSay arg(1)\nReturn lineout(oid,arg(1))\n", "language": "OoRexx" }, { "code": "use List::Util qw(sum0 max);\n\nsub comb {\n my ($s, $n) = @_;\n $n || return (1);\n my @r = (0) x ($n - max(@$s) + 1);\n my @c = comb($s, $n - 1);\n foreach my $i (0 .. $#c) {\n $c[$i] || next;\n foreach my $k (@$s) {\n $r[$i + $k] += $c[$i];\n }\n }\n return @r;\n}\n\nsub winning {\n my ($s1, $n1, $s2, $n2) = @_;\n\n my @p1 = comb($s1, $n1);\n my @p2 = comb($s2, $n2);\n\n my ($win, $loss, $tie) = (0, 0, 0);\n\n foreach my $i (0 .. $#p1) {\n $win += $p1[$i] * sum0(@p2[0 .. $i - 1]);\n $tie += $p1[$i] * sum0(@p2[$i .. $i ]);\n $loss += $p1[$i] * sum0(@p2[$i+1 .. $#p2 ]);\n }\n my $total = sum0(@p1) * sum0(@p2);\n map { $_ / $total } ($win, $tie, $loss);\n}\n\nprint '(', join(', ', winning([1 .. 4], 9, [1 .. 6], 6)), \")\\n\";\nprint '(', join(', ', winning([1 .. 10], 5, [1 .. 7], 6)), \")\\n\";\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">throwDie</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">nSides</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nDice</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">counts</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">nDice</span> <span style=\"color: #0000FF;\">==</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">counts</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">nSides</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">counts</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">throwDie</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nSides</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nDice</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">counts</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">counts</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">beatingProbability</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">nSides1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nDice1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nSides2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nDice2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">len1</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nSides1</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">nDice1</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">len2</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nSides2</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">nDice2</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">c1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">throwDie</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nSides1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nDice1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">len1</span><span style=\"color: #0000FF;\">)),</span>\n <span style=\"color: #000000;\">c2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">throwDie</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nSides2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nDice2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">len2</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">p12</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nSides1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nDice1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nSides2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nDice2</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">tot</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">0.0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">len1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">min</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">len2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">tot</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c1</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">c2</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">p12</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">tot</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%0.16f\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">beatingProbability</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%0.16f\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">beatingProbability</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">))</span>\n<!--\n", "language": "Phix" }, { "code": "*process source attributes xref;\n dicegame: Proc Options(main);\n Call test(9, 4,6,6);\n Call test(5,10,6,7);\n test: Proc(w1,s1,w2,s2);\n Dcl (w1,s1,w2,s2,x,y) Bin Fixed(31);\n Dcl p1(100) Dec Float(18) Init((100)0);\n Dcl p2(100) Dec Float(18) Init((100)0);\n Dcl p2low(100) Dec Float(18) Init((100)0);\n Call pp(w1,s1,p1);\n Call pp(w2,s2,p2);\n Do x=w1 To w1*s1;\n Do y=0 To x-1;\n p2low(x)+=p2(y);\n End;\n End;\n pwin1=0;\n Do x=w1 To w1*s1;\n pwin1+=p1(x)*p2low(x);\n End;\n Put Edit('Player 1 has ',w1,' dice with ',s1,' sides each')\n (Skip,3(a,f(2)));\n Put Edit('Player 2 has ',w2,' dice with ',s2,' sides each')\n (Skip,3(a,f(2)));\n Put Edit('Probability for player 1 to win: ',pwin1)(Skip,a,f(20,18));\n Put Edit('')(Skip,a);\n End;\n pp: Proc(w,s,p);\n /*--------------------------------------------------------------------\n * Compute and assign probabilities to get a sum x\n * when throwing w dice each having s sides (marked from 1 to s)\n *-------------------------------------------------------------------*/\n Dcl (w,s) Bin Fixed(31);\n Dcl p(100) Dec Float(18);\n Dcl cnt(100) Bin Fixed(31);\n Dcl (a(12),e(12),v(12),sum,i,n) Bin Fixed(31);\n a=0;\n e=0;\n Do i=1 To w;\n a(i)=1;\n e(i)=s;\n End;\n n=0;\n cnt=0;\n Do v(1)=a(1) To e(1);\n Do v(2)=a(2) To e(2);\n Do v(3)=a(3) To e(3);\n Do v(4)=a(4) To e(4);\n Do v(5)=a(5) To e(5);\n Do v(6)=a(6) To e(6);\n Do v(7)=a(7) To e(7);\n Do v(8)=a(8) To e(8);\n Do v(9)=a(9) To e(9);\n Do v(10)=a(10) To e(10);\n sum=0;\n Do i=1 To 10;\n sum=sum+v(i);\n End;\n cnt(sum)+=1;\n n+=1;\n End;\n End;\n End;\n End;\n End;\n End;\n End;\n End;\n End;\n End;\n Do k=w To w*s;\n p(k)=divide(cnt(k),n,18,16);\n End;\n End;\n End;\n", "language": "PL-I" }, { "code": "*process source attributes xref;\n dgf: Proc Options(main);\n Call test(9, 4,6,6);\n Call test(5,10,6,7);\n test: Proc(w1,s1,w2,s2);\n Dcl (w1,s1,w2,s2,x,y) Dec Float(18);\n Dcl 1 p1(100),\n 2 nom Dec Float(18) Init((100)0),\n 2 denom Dec Float(18) Init((100)1);\n Dcl 1 p2(100),\n 2 nom Dec Float(18) Init((100)0),\n 2 denom Dec Float(18) Init((100)1);\n Dcl 1 p2low(100),\n 2 nom Dec Float(18) Init((100)0),\n 2 denom Dec Float(18) Init((100)1);\n Dcl 1 pwin1,\n 2 nom Dec Float(18) Init(0),\n 2 denom Dec Float(18) Init(1);\n Dcl 1 prod Like pwin1;\n Call pp(w1,s1,p1);\n Call pp(w2,s2,p2);\n Do x=w1 To w1*s1;\n Do y=0 To x-1;\n Call fr_add(p2low(x),p2(y),p2low(x));\n End;\n End;\n Do x=w1 To w1*s1;\n Call fr_mult(p1(x),p2low(x),prod);\n Call fr_add(pwin1,prod,pwin1);\n End;\n Put Edit('Player 1 has ',w1,' dice with ',s1,' sides each')\n (Skip,3(a,f(2)));\n Put Edit('Player 2 has ',w2,' dice with ',s2,' sides each')\n (Skip,3(a,f(2)));\n Put Edit('Probability for player 1 to win: ',\n str(pwin1.nom),'/',str(pwin1.denom))(Skip,4(a));\n Put Edit(' -> ',\n pwin1.nom/pwin1.denom)(Skip,a,f(20,18));\n Put Edit('')(Skip,a);\n End;\n\n pp: Proc(w,s,p);\n /*--------------------------------------------------------------------\n * Compute and assign probabilities to get a sum x\n * when throwing w dice each having s sides (marked from 1 to s)\n *-------------------------------------------------------------------*/\n Dcl (w,s) Dec Float(18);\n Dcl 1 p(100),\n 2 nom Dec Float(18),\n 2 denom Dec Float(18);\n Dcl cnt(100) Dec Float(18);\n Dcl (a(12),e(12),v(12),sum,i,n) Dec Float(18);\n a=0;\n e=0;\n Do i=1 To w;\n a(i)=1;\n e(i)=s;\n End;\n n=0;\n cnt=0;\n Do v(1)=a(1) To e(1);\n Do v(2)=a(2) To e(2);\n Do v(3)=a(3) To e(3);\n Do v(4)=a(4) To e(4);\n Do v(5)=a(5) To e(5);\n Do v(6)=a(6) To e(6);\n Do v(7)=a(7) To e(7);\n Do v(8)=a(8) To e(8);\n Do v(9)=a(9) To e(9);\n Do v(10)=a(10) To e(10);\n sum=0;\n Do i=1 To 10;\n sum=sum+v(i);\n End;\n cnt(sum)+=1;\n n+=1;\n End;\n End;\n End;\n End;\n End;\n End;\n End;\n End;\n End;\n End;\n Do k=w To w*s;\n p(k).nom=cnt(k);\n p(k).denom=n;\n End;\n End;\n\n fr_add: Proc(a,b,res);\n Dcl 1 a,\n 2 nom Dec Float(18),\n 2 denom Dec Float(18);\n Dcl 1 b Like a;\n Dcl res like a;\n /* Put Edit('fr_add',a.nom,a.denom,b.nom,b.denom)(Skip,a,4(f(15))); */\n res.nom=a.nom*b.denom+b.nom*a.denom;\n res.denom=a.denom*b.denom;\n Call fr_cancel(res,res);\n End;\n\n fr_mult: Proc(a,b,res);\n Dcl 1 a,\n 2 nom Dec Float(18),\n 2 denom Dec Float(18);\n Dcl 1 b Like a;\n Dcl res like a;\n /* Put Edit('fr_mult',a.nom,a.denom,b.nom,b.denom)(Skip,a,4(f(15)));*/\n res.nom=a.nom*b.nom;\n res.denom=a.denom*b.denom;\n Call fr_cancel(res,res);\n End;\n\n fr_cancel: Proc(a,res);\n Dcl 1 a,\n 2 nom Dec Float(18),\n 2 denom Dec Float(18);\n Dcl k Dec Float(18);\n Dcl 1 res like a;\n /* Put Edit('fr_cancel',a.nom,a.denom)(Skip,a,4(f(15))); */\n k=ggt(a.nom,a.denom);\n res=a/k;\n End;\n\n ggt: Proc(a,b) Recursive Returns(Dec Float(18));\n /**********************************************************************\n * ggt (gcd) Greatest common Divisor\n * Recursive Proc(a,b)) as shown in PL/I\n **********************************************************************/\n Dcl (a,b) Dec Float(18);\n if b = 0 then return (abs(a));\n return (ggt(b,mod(a,b)));\n End;\n\n str: Proc(x) Returns(Char(20) Var);\n Dcl x Dec Float(18);\n Dcl res Char(20) Var;\n Put String(res) Edit(x)(f(20));\n Return (trim(res));\n End;\n\n End;\n", "language": "PL-I" }, { "code": "from itertools import product\n\ndef gen_dict(n_faces, n_dice):\n counts = [0] * ((n_faces + 1) * n_dice)\n for t in product(range(1, n_faces + 1), repeat=n_dice):\n counts[sum(t)] += 1\n return counts, n_faces ** n_dice\n\ndef beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):\n c1, p1 = gen_dict(n_sides1, n_dice1)\n c2, p2 = gen_dict(n_sides2, n_dice2)\n p12 = float(p1 * p2)\n\n return sum(p[1] * q[1] / p12\n for p, q in product(enumerate(c1), enumerate(c2))\n if p[0] > q[0])\n\nprint beating_probability(4, 9, 6, 6)\nprint beating_probability(10, 5, 7, 6)\n", "language": "Python" }, { "code": "from __future__ import print_function, division\n\ndef combos(sides, n):\n if not n: return [1]\n ret = [0] * (max(sides)*n + 1)\n for i,v in enumerate(combos(sides, n - 1)):\n if not v: continue\n for s in sides: ret[i + s] += v\n return ret\n\ndef winning(sides1, n1, sides2, n2):\n p1, p2 = combos(sides1, n1), combos(sides2, n2)\n win,loss,tie = 0,0,0 # 'win' is 1 beating 2\n for i,x1 in enumerate(p1):\n # using accumulated sum on p2 could save some time\n win += x1*sum(p2[:i])\n tie += x1*sum(p2[i:i+1])\n loss+= x1*sum(p2[i+1:])\n s = sum(p1)*sum(p2)\n return win/s, tie/s, loss/s\n\nprint(winning(range(1,5), 9, range(1,7), 6))\nprint(winning(range(1,11), 5, range(1,8), 6)) # this seem hardly fair\n\n# mountains of dice test case\n# print(winning((1, 2, 3, 5, 9), 700, (1, 2, 3, 4, 5, 6), 800))\n", "language": "Python" }, { "code": "from __future__ import division, print_function\nfrom itertools import accumulate # Python3 only\n\ndef combos(sides, n):\n ret = [1] + [0]*(n + 1)*sides # extra length for negative indices\n for p in range(1, n + 1):\n rolling_sum = 0\n for i in range(p*sides, p - 1, -1):\n rolling_sum += ret[i - sides] - ret[i]\n ret[i] = rolling_sum\n ret[p - 1] = 0\n return ret\n\ndef winning(d1, n1, d2, n2):\n c1, c2 = combos(d1, n1), combos(d2, n2)\n ac = list(accumulate(c2 + [0]*(len(c1) - len(c2))))\n\n return sum(v*a for v,a in zip(c1[1:], ac)) / (ac[-1]*sum(c1))\n\n\nprint(winning(4, 9, 6, 6))\nprint(winning(5, 10, 6, 7))\n\n#print(winning(6, 700, 8, 540))\n", "language": "Python" }, { "code": "probability <- function(facesCount1, diceCount1, facesCount2, diceCount2)\n{\n mean(replicate(10^6, sum(sample(facesCount1, diceCount1, replace = TRUE)) > sum(sample(facesCount2, diceCount2, replace = TRUE))))\n}\ncat(\"Player 1's probability of victory is\", probability(4, 9, 6, 6),\n \"in the first game and\", probability(10, 5, 7, 6), \"in the second.\")\n", "language": "R" }, { "code": "#lang racket\n\n(define probs# (make-hash))\n\n(define (NdD n d)\n (hash-ref!\n probs# (cons n d)\n (λ ()\n (cond\n [(= n 0) ; every chance of nothing!\n (hash 0 1)]\n [else\n (for*/fold ((hsh (hash))) (((i p) (in-hash (NdD (sub1 n) d))) (r (in-range 1 (+ d 1))))\n (hash-update hsh (+ r i) (λ (p+) (+ p+ (/ p d))) 0))]))))\n\n(define (game-probs N1 D1 N2 D2)\n (define P1 (NdD N1 D1))\n (define P2 (NdD N2 D2))\n (define-values (W D L)\n (for*/fold ((win 0) (draw 0) (lose 0)) (((r1 p1) (in-hash P1)) ((r2 p2) (in-hash P2)))\n (define p (* p1 p2))\n (cond\n [(< r1 r2) (values win draw (+ lose p))]\n [(= r1 r2) (values win (+ draw p) lose)]\n [(> r1 r2) (values (+ win p) draw lose)])))\n\n (printf \"P(P1 win): ~a~%\" (real->decimal-string W 6))\n (printf \"P(draw): ~a~%\" (real->decimal-string D 6))\n (printf \"P(P2 win): ~a~%\" (real->decimal-string L 6))\n (list W D L))\n\n(printf \"GAME 1 (9D4 vs 6D6)~%\")\n(game-probs 9 4 6 6)\n(newline)\n\n(printf \"GAME 2 (5D10 vs 6D7) [what is a D7?]~%\")\n(game-probs 5 10 6 7)\n", "language": "Racket" }, { "code": "sub likelihoods ($roll) {\n my ($dice, $faces) = $roll.comb(/\\d+/);\n my @counts;\n @counts[$_]++ for [X+] |(1..$faces,) xx $dice;\n return [@counts[]:p], $faces ** $dice;\n}\n\nsub beating-probability ([$roll1, $roll2]) {\n my (@c1, $p1) := likelihoods $roll1;\n my (@c2, $p2) := likelihoods $roll2;\n my $p12 = $p1 * $p2;\n\n [+] gather for flat @c1 X @c2 -> $p, $q {\n\ttake $p.value * $q.value / $p12 if $p.key > $q.key;\n }\n}\n\n# We're using standard DnD notation for dice rolls here.\nsay .gist, \"\\t\", .raku given beating-probability < 9d4 6d6 >;\nsay .gist, \"\\t\", .raku given beating-probability < 5d10 6d7 >;\n", "language": "Raku" }, { "code": "/* REXX */\nNumeric Digits 30\nCall test '9 4 6 6'\nCall test '5 10 6 7'\nExit\ntest:\nParse Arg w1 s1 w2 s2\nplist1=pp(w1,s1)\np1.=0\nDo x=w1 To w1*s1\n Parse Var plist1 p1.x plist1\n End\nplist2=pp(w2,s2)\np2.=0\nDo x=w2 To w2*s2\n Parse Var plist2 p2.x plist2\n End\np2low.=0\nDo x=w1 To w1*s1\n Do y=0 To x-1\n p2low.x=p2low.x+p2.y\n End\n End\npwin1=0\nDo x=w1 To w1*s1\n pwin1=pwin1+p1.x*p2low.x\n End\nSay 'Player 1 has' w1 'dice with' s1 'sides each'\nSay 'Player 2 has' w2 'dice with' s2 'sides each'\nSay 'Probability for player 1 to win:' pwin1\nSay ''\nReturn\n\npp: Procedure\n/*---------------------------------------------------------------------\n* Compute and return the probabilities to get a sum x\n* when throwing w dice each having s sides (marked from 1 to s)\n*--------------------------------------------------------------------*/\nParse Arg w,s\nstr=''\ncnt.=0\nDo wi=1 To w\n str=str||'Do v'wi'=1 To' s';'\n End\nstr=str||'sum='\nDo wi=1 To w-1\n str=str||'v'wi'+'\n End\nstr=str||'v'w';'\nstr=str||'cnt.'sum'=cnt.'sum'+1;'\nDo wi=1 To w\n str=str||'End;'\n End\nInterpret str\npsum=0\nDo x=0 To w*s\n p.x=cnt.x/(s**w)\n psum=psum+p.x\n End\nres=''\nDo x=w To s*w\n res=res p.x\n End\nReturn res\n", "language": "REXX" }, { "code": "/* REXX */\noid='diet.xxx'; 'erase' oid\nCall test '9 4 6 6'\nCall test '5 10 6 7'\nExit\ntest:\nParse Arg n1 s1 n2 s2\nCall o 'Player 1:' n1 'dice with' s1 'sides each'\nCall o 'Player 2:' n2 'dice with' s2 'sides each'\ncnt1.=0\ncnt2.=0\nwin.=0\nnn=10000\nCall time 'R'\nDo i=1 To nn\n sum1=sum(n1 s1) ; cnt1.sum1=cnt1.sum1+1\n sum2=sum(n2 s2) ; cnt2.sum2=cnt2.sum2+1\n Select\n When sum1>sum2 Then win.1=win.1+1\n When sum1<sum2 Then win.2=win.2+1\n Otherwise win.0=win.0+1\n End\n End\nCall o win.1/nn 'player 1 wins'\nCall o win.2/nn 'player 2 wins'\nCall o win.0/nn 'draws'\n/*\nDo i=min(n1,n2) To max(n1*s1,n2*s2)\n Call o right(i,2) format(cnt1.i,7) format(cnt2.i,7)\n End\n*/\nCall o time('E') 'seconds elapsed'\nReturn\n\nsum: Parse Arg n s\nsum=0\nDo k=1 To n\n sum=sum+rand(s)\n End\nReturn sum\n\nrand: Parse Arg n\n Return random(n-1)+1\n\no:\nSay arg(1)\nReturn lineout(oid,arg(1))\n", "language": "REXX" }, { "code": "/*REXX pgm computes and displays the probabilities of a two─player S─sided, N─dice game.*/\nnumeric digits 100 /*increase/decrease to heart's desire. */\ncall game 9 4, 6 6 /*1st player: 9 dice, 4 sides; 2nd player: 6 dice, 6 sides*/\ncall game 5 10, 6 7 /* \" \" 5 \" 10 \" \" \" 6 \" 7 \" */\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ngame: parse arg w.1 s.1, w.2 s.2 /*1st player(dice sides), 2nd player···*/\n p.= 0\n do j=1 for 2; @@.j= prob(w.j, s.j)\n do k=w.j to w.j*s.j; parse var @@.j p.j.k @@.j; end /*k*/\n end /*j*/\n low.= 0\n do j=w.1 to w.1*s.1\n do k=0 for j; low.j= low.j + p.2.k; end /*k*/\n end /*j*/\n say ' Player 1 has ' w.1 \" dice with \" s.1 ' sides each.'\n say ' Player 2 has ' w.2 \" dice with \" s.2 ' sides each.'\n winP= 0\n do j=w.1 to w.1*s.1; winP= winP + p.1.j * low.j\n end /*j*/\n say 'The probability for first player to win is ' format(winP*100,,digits()%2) \"%.\"\n say /* ↑ */\n return /*show 1/2 of 100 dec. digits────┘ */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nprob: procedure; parse arg n,s,,@ $; #.= 0; pow= s**n\n do j=1 for n; @= @'DO _'j\"=1 FOR\" s';'; end /*j*/\n @= @'_='; do k=1 for n-1; @= @\"_\"k'+' ; end /*k*/\n interpret @'_'n\";#.\"_'=#.'_\"+1\"copies(';END', k)\n ns= n*s; do j=0 to ns; p.j= #.j / pow; end /*j*/\n do k=n to ns; $= $ p.k; end /*k*/\n return $ /* ◄──────────────── probability of 1st player to win, S─sided, N dice.*/\n", "language": "REXX" }, { "code": "def roll_dice(n_dice, n_faces)\n return [[0,1]] if n_dice.zero?\n one = [1] * n_faces\n zero = [0] * (n_faces-1)\n (1...n_dice).inject(one){|ary,_|\n (zero + ary + zero).each_cons(n_faces).map{|a| a.inject(:+)}\n }.map.with_index(n_dice){|n,sum| [sum,n]} # sum: total of the faces\nend\n\ndef game(dice1, faces1, dice2, faces2)\n p1 = roll_dice(dice1, faces1)\n p2 = roll_dice(dice2, faces2)\n p1.product(p2).each_with_object([0,0,0]) do |((sum1, n1), (sum2, n2)), win|\n win[sum1 <=> sum2] += n1 * n2 # [0]:draw, [1]:win, [-1]:lose\n end\nend\n\n[[9, 4, 6, 6], [5, 10, 6, 7]].each do |d1, f1, d2, f2|\n puts \"player 1 has #{d1} dice with #{f1} faces each\"\n puts \"player 2 has #{d2} dice with #{f2} faces each\"\n win = game(d1, f1, d2, f2)\n sum = win.inject(:+)\n puts \"Probability for player 1 to win: #{win[1]} / #{sum}\",\n \" -> #{win[1].fdiv(sum)}\", \"\"\nend\n", "language": "Ruby" }, { "code": "// Returns a vector containing the number of ways each possible sum of face\n// values can occur.\nfn get_totals(dice: usize, faces: usize) -> Vec<f64> {\n let mut result = vec![1.0; faces + 1];\n for d in 2..=dice {\n let mut tmp = vec![0.0; d * faces + 1];\n for i in d - 1..result.len() {\n for j in 1..=faces {\n tmp[i + j] += result[i];\n }\n }\n result = tmp;\n }\n result\n}\n\nfn probability(dice1: usize, faces1: usize, dice2: usize, faces2: usize) -> f64 {\n let totals1 = get_totals(dice1, faces1);\n let totals2 = get_totals(dice2, faces2);\n let mut wins = 0.0;\n let mut total = 0.0;\n for i in dice1..totals1.len() {\n for j in dice2..totals2.len() {\n let n = totals1[i] * totals2[j];\n total += n;\n if j < i {\n wins += n;\n }\n }\n }\n wins / total\n}\n\nfn main() {\n println!(\"{}\", probability(9, 4, 6, 6));\n println!(\"{}\", probability(5, 10, 6, 7));\n}\n", "language": "Rust" }, { "code": "func combos(sides, n) {\n n || return [1]\n var ret = ([0] * (n*sides.max + 1))\n combos(sides, n-1).each_kv { |i,v|\n v && for s in sides { ret[i + s] += v }\n }\n return ret\n}\n\nfunc winning(sides1, n1, sides2, n2) {\n var (p1, p2) = (combos(sides1, n1), combos(sides2, n2))\n var (win,loss,tie) = (0,0,0)\n p1.each_kv { |i, x|\n win += x*p2.first(i).sum\n tie += x*p2.slice(i).first(1).sum\n loss += x*p2.slice(i+1).sum\n }\n [win, tie, loss] »/» p1.sum*p2.sum\n}\n\nfunc display_results(String title, Array res) {\n say \"=> #{title}\"\n for name, prob in (%w(p₁\\ win tie p₂\\ win) ~Z res) {\n say \"P(#{'%6s' % name}) =~ #{prob.round(-11)} (#{prob.as_frac})\"\n }\n print \"\\n\"\n}\n\ndisplay_results('9D4 vs 6D6', winning(range(1, 4), 9, range(1,6), 6))\ndisplay_results('5D10 vs 6D7', winning(range(1,10), 5, range(1,7), 6))\n", "language": "Sidef" }, { "code": "foreach d0 {1 2 3 4 5 6} {\n foreach d1 {1 2 3 4 5 6} {\n ...\n foreach dN {1 2 3 4 5 6} {\n dict incr sum [::tcl::mathop::+ $n $d0 $d1 ... $DN]\n }\n ...\n }\n}\n", "language": "Tcl" }, { "code": "proc range {b} { ;# a common standard proc: [range 5] -> {0 1 2 3 4}\n set a 0\n set res {}\n while {$a < $b} {\n lappend res $a\n incr a\n }\n return $res\n}\n\n# This proc builds up a nested foreach call, then evaluates it.\n#\n# The script is built up in $script, starting with the body using \"%%\" as\n# a placeholder.\n#\n# For each die, a level is wrapped around it as follows:\n# set script {foreach d0 {1 2 3 4 5 6} $script}\n# set script {foreach d1 {1 2 3 4 5 6} $script}\n#\n# .. and {$d0 $d1 ..} are collected in the variable $vars, which is used\n# to replace \"%%\" at the end.\n#\n# The script is evaluated with [try] - earlier Tcl's could use [catch] or [eval]\nproc NdK {n {k 6}} { ;# calculate a score histogram for $n dice of $k faces\n set sum {}\n set script {\n dict incr sum [::tcl::mathop::+ $n %%] ;# add $n because ranges are 0-based\n } ;# %% is a placeholder\n set vars \"\"\n for {set i 0} {$i < $n} {incr i} {\n set script [list foreach d$i [range $k] $script]\n append vars \" \\$d$i\"\n }\n set script [string map [list %% $vars] $script]\n try $script\n return $sum\n}\n\nproc win_pr {p1 p2} { ;# calculate the winning probability of player 1 given two score histograms\n set P 0\n set N 0\n dict for {d1 k1} $p1 {\n dict for {d2 k2} $p2 {\n set k [expr {$k1 * $k2}]\n incr N $k\n incr P [expr {$k * ($d1 > $d2)}]\n }\n }\n expr {$P * 1.0 / $N}\n}\n\nforeach {p1 p2} {\n {9 4} {6 6}\n {5 10} {6 7}\n} {\n puts [format \"p1 has %dd%d; p2 has %dd%d\" {*}$p1 {*}$p2]\n puts [format \" p1 wins with Pr(%s)\" [win_pr [NdK {*}$p1] [NdK {*}$p2]]]\n}\n", "language": "Tcl" }, { "code": "package require Tcl 8.6 ;# for [tailcall] - otherwise use [uplevel 1 $script]\n# This proc builds up a nested foreach call, then evaluates it.\n#\n# this:\n# foreach* a {1 2 3} b {4 5 6} {\n# puts \"$a + $b\"\n# }\n#\n# becomes:\n# foreach a {1 2 3} {\n# foreach b {4 5 6} {\n# puts \"$a + $b\"\n# }\n# }\nproc foreach* {args} {\n set script [lindex $args end]\n set args [lrange $args 0 end-1]\n foreach {b a} [lreverse $args] {\n set script [list foreach $a $b $script]\n }\n tailcall {*}$script\n}\n\nproc NdK {n {k 6}} { ;# calculate a score histogram for $n dice of $k faces\n\n set args {} ;# arguments to [foreach*]\n set vars {} ;# variables used in [foreach*] arguments that need to be added to sum\n set sum {} ;# this will be the result dictionary\n\n for {set i 0} {$i < $n} {incr i} {\n lappend args d$i [range $k]\n lappend vars \"\\$d$i\"\n }\n\n set vars [join $vars +]\n\n # [string map] to avoid \"Quoting Hell\"\n set script [string map [list %% $vars] {\n dict incr sum [expr {$n + %%}] ;# $n because [range] is 0-based\n }]\n\n foreach* {*}$args $script\n return $sum\n}\n", "language": "Tcl" }, { "code": "import math\n\nfn min_of(x int, y int) int {\n if x < y {\n return x\n }\n return y\n}\n\nfn throw_die(n_sides int, n_dice int, s int, mut counts []int) {\n if n_dice == 0 {\n counts[s]++\n return\n }\n for i := int(1); i <= n_sides; i++ {\n throw_die(n_sides, n_dice - 1, s + i, mut counts)\n }\n}\n\nfn beating_probability(n_sides1 int, n_dice1 int, n_sides2 int, n_dice2 int) f64 {\n len1 := (n_sides1 + 1) * n_dice1\n mut c1 := []int{len: len1} // all elements zero by default\n throw_die(n_sides1, n_dice1, 0, mut c1)\n\n len2 := (n_sides2 + 1) * n_dice2\n mut c2 := []int{len: len2}\n throw_die(n_sides2, n_dice2, 0, mut c2)\n p12 := math.pow(f64(n_sides1), f64(n_dice1)) *\n math.pow(f64(n_sides2), f64(n_dice2))\n\n mut tot := 0.0\n for i := int(0); i < len1; i++ {\n for j := int(0); j < min_of(i, len2); j++ {\n tot += f64(c1[i] * c2[j]) / p12\n }\n }\n return tot\n}\n\nfn main() {\n println(beating_probability(4, 9, 6, 6))\n println(beating_probability(10, 5, 7, 6))\n}\n", "language": "V-(Vlang)" }, { "code": "var throwDie // recursive\nthrowDie = Fn.new { |nSides, nDice, s, counts|\n if (nDice == 0) {\n counts[s] = counts[s] + 1\n return\n }\n for (i in 1..nSides) throwDie.call(nSides, nDice-1, s + i, counts)\n}\n\nvar beatingProbability = Fn.new { |nSides1, nDice1, nSides2, nDice2|\n var len1 = (nSides1 + 1) * nDice1\n var c1 = List.filled(len1, 0)\n throwDie.call(nSides1, nDice1, 0, c1)\n\n var len2 = (nSides2 + 1) * nDice2\n var c2 = List.filled(len2, 0)\n throwDie.call(nSides2, nDice2, 0, c2)\n\n var p12 = nSides1.pow(nDice1) * nSides2.pow(nDice2)\n var tot = 0\n for (i in 0...len1) {\n for (j in 0...i.min(len2)) {\n tot = tot + c1[i] * c2[j] / p12\n }\n }\n return tot\n}\n\nSystem.print(beatingProbability.call(4, 9, 6, 6))\nSystem.print(beatingProbability.call(10, 5, 7, 6))\n", "language": "Wren" }, { "code": "dado1 = 9: lado1 = 4\ndado2 = 6: lado2 = 6\ntotal1 = 0: total2 = 0\n\nfor i = 0 to 1\n for cont = 1 to 100000\n jugador1 = lanzamiento(dado1, lado1)\n jugador2 = lanzamiento(dado2, lado2)\n if jugador1 > jugador2 then\n total1 = total1 + 1\n elseif jugador1 <> jugador2 then\n total2 = total2 + 1\n endif\n next cont\n\n print \"Lanzado el dado \", (cont - 1), \" veces\"\n print \"jugador1 con \", dado1, \" dados de \", lado1, \" lados\"\n print \"jugador2 con \", dado2, \" dados de \", lado2, \" lados\"\n print \"Total victorias jugador1 = \", total1, \" => \", (total2 / total1)\n print \"Total victorias jugador2 = \", total2\n print (cont - 1) - (total1 + total2), \" empates\\n\"\n\n dado1 = 5: lado1 = 10\n dado2 = 6: lado2 = 7\n total1 = 0: total2 = 0\nnext i\n\nsub lanzamiento(dado, lado)\n local lanza, total\n\n for lanza = 1 to dado\n total = total + int(ran(lado)) + 1\n next lanza\n return total\nend sub\n", "language": "Yabasic" }, { "code": "fcn combos(sides, n){\n if(not n) return(T(1));\n ret:=((0).max(sides)*n + 1).pump(List(),0);\n foreach i,v in (combos(sides, n - 1).enumerate()){\n if(not v) continue;\n foreach s in (sides){ ret[i + s] += v }\n }\n ret\n}\n\nfcn winning(sides1,n1, sides2,n2){\n p1, p2 := combos(sides1, n1), combos(sides2, n2);\n win,loss,tie := 0,0,0; # 'win' is 1 beating 2\n foreach i,x1 in (p1.enumerate()){\n # using accumulated sum on p2 could save some time\n win += x1*p2[0,i].sum(0);\n tie += x1*p2[i,1].sum(0); // i>p2.len() but p2[bigi,?]-->[]\n loss+= x1*p2[i+1,*].sum(0);\n }\n s := p1.sum(0)*p2.sum(0);\n return(win.toFloat()/s, tie.toFloat()/s, loss.toFloat()/s);\n}\n", "language": "Zkl" }, { "code": "println(winning([1..4].walk(), 9, [1..6].walk(),6));\nprintln(winning([1..10].walk(),5, [1..7].walk(),6)); # this seem hardly fair\n", "language": "Zkl" } ]
Dice-game-probabilities
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Digital_root\n", "language": "00-META" }, { "code": "The digital root, <math>X</math>, of a number, <math>n</math>, is calculated:\n: find <math>X</math> as the sum of the digits of <math>n</math>\n: find a new <math>X</math> by summing the digits of <math>X</math>, repeating until <math>X</math> has only one digit.\n\nThe additive persistence is the number of summations required to obtain the single digit. \n\nThe task is to calculate the additive persistence and the digital root of a number, e.g.:\n:<math>627615</math> has additive persistence <math>2</math> and digital root of <math>9</math>;\n:<math>39390</math> has additive persistence <math>2</math> and digital root of <math>6</math>;\n:<math>588225</math> has additive persistence <math>2</math> and digital root of <math>3</math>;\n:<math>393900588225</math> has additive persistence <math>2</math> and digital root of <math>9</math>;\n\nThe digital root may be calculated in bases other than 10.\n\n\n;See:\n* [[Casting out nines]] for this wiki's use of this procedure.\n* [[Digital root/Multiplicative digital root]]\n* [[Sum digits of an integer]]\n* [[oeis:A010888|Digital root sequence on OEIS]]\n* [[oeis:A031286|Additive persistence sequence on OEIS]]\n* [[Iterated digits squaring]]\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F digital_root(=n)\n V ap = 0\n L n >= 10\n n = sum(String(n).map(digit -> Int(digit)))\n ap++\n R (ap, n)\n\nL(n) [Int64(627615), 39390, 588225, 393900588225, 55]\n Int64 persistance, root\n (persistance, root) = digital_root(n)\n print(‘#12 has additive persistance #2 and digital root #..’.format(n, persistance, root))\n", "language": "11l" }, { "code": "* Digital root 21/04/2017\nDIGROOT CSECT\n USING DIGROOT,R13 base register\n B 72(R15) skip savearea\n DC 17F'0' savearea\n STM R14,R12,12(R13) save previous context\n ST R13,4(R15) link backward\n ST R15,8(R13) link forward\n LR R13,R15 set addressability\n LA R6,1 i=1\n DO WHILE=(C,R6,LE,=A((PG-T)/4)) do i=1 to hbound(t)\n LR R1,R6 i\n SLA R1,2 *4\n L R10,T-4(R1) nn=t(i)\n LR R7,R10 n=nn\n SR R9,R9 ap=0\n DO WHILE=(C,R7,GE,=A(10)) do while(n>=10)\n SR R8,R8 x=0\n DO WHILE=(C,R7,GE,=A(10)) do while(n>=10)\n LR R4,R7 n\n SRDA R4,32 >>r5\n D R4,=A(10) m=n//10\n LR R7,R5 n=n/10\n AR R8,R4 x=x+m\n ENDDO , end\n AR R7,R8 n=x+n\n LA R9,1(R9) ap=ap+1\n ENDDO , end\n XDECO R10,XDEC nn\n MVC PG+7(10),XDEC+2\n XDECO R9,XDEC ap\n MVC PG+31(3),XDEC+9\n XDECO R7,XDEC n\n MVC PG+41(1),XDEC+11\n XPRNT PG,L'PG print\n LA R6,1(R6) i++\n ENDDO , enddo i\n L R13,4(0,R13) restore previous savearea pointer\n LM R14,R12,12(R13) restore previous context\n XR R15,R15 rc=0\n BR R14 exit\nT DC F'627615',F'39390',F'588225',F'2147483647'\nPG DC CL80'number=xxxxxxxxxx persistence=xxx root=x'\nXDEC DS CL12\n YREGS\n END DIGROOT\n", "language": "360-Assembly" }, { "code": "package Generic_Root is\n type Number is range 0 .. 2**63-1;\n type Number_Array is array(Positive range <>) of Number;\n type Base_Type is range 2 .. 16; -- any reasonable base to write down numb\n\n generic\n with function \"&\"(X, Y: Number) return Number;\n -- instantiate with \"+\" for additive digital roots\n -- instantiate with \"*\" for multiplicative digital roots\n procedure Compute_Root(N: Number;\n Root, Persistence: out Number;\n Base: Base_Type := 10);\n -- computes Root and Persistence of N;\n\nend Generic_Root;\n", "language": "Ada" }, { "code": "package body Generic_Root is\n\n procedure Compute_Root(N: Number;\n Root, Persistence: out Number;\n Base: Base_Type := 10) is\n\n function Digit_Sum(N: Number) return Number is\n begin\n if N < Number(Base) then\n return N;\n else\n return (N mod Number(Base)) & Digit_Sum(N / Number(Base));\n end if;\n end Digit_Sum;\n\n begin\n if N < Number(Base) then\n Root := N;\n Persistence := 0;\n else\n Compute_Root(Digit_Sum(N), Root, Persistence, Base);\n Persistence := Persistence + 1;\n end if;\n end Compute_Root;\n\nend Generic_Root;\n", "language": "Ada" }, { "code": "with Generic_Root, Ada.Text_IO; use Generic_Root;\n\nprocedure Digital_Root is\n\n procedure Compute is new Compute_Root(\"+\");\n -- \"+\" for additive digital roots\n\n package TIO renames Ada.Text_IO;\n\n procedure Print_Roots(Inputs: Number_Array; Base: Base_Type) is\n package NIO is new TIO.Integer_IO(Number);\n Root, Pers: Number;\n begin\n for I in Inputs'Range loop\n Compute(Inputs(I), Root, Pers, Base);\n NIO.Put(Inputs(I), Base => Integer(Base), Width => 12);\n NIO.Put(Root, Base => Integer(Base), Width => 9);\n NIO.Put(Pers, Base => Integer(Base), Width => 12);\n TIO.Put_Line(\" \" & Base_Type'Image(Base));\n end loop;\n end Print_Roots;\nbegin\n TIO.Put_Line(\" Number Root Persistence Base\");\n Print_Roots((961038, 923594037444, 670033, 448944221089), Base => 10);\n Print_Roots((16#7e0#, 16#14e344#, 16#12343210#), Base => 16);\nend Digital_Root;\n", "language": "Ada" }, { "code": "# calculates the digital root and persistance of n #\nPROC digital root = ( LONG LONG INT n, REF INT root, persistance )VOID:\n BEGIN\n LONG LONG INT number := ABS n;\n persistance := 0;\n WHILE persistance PLUSAB 1;\n LONG LONG INT digit sum := 0;\n WHILE number > 0\n DO\n digit sum PLUSAB number MOD 10;\n number OVERAB 10\n OD;\n number := digit sum;\n number > 9\n DO\n SKIP\n OD;\n root := SHORTEN SHORTEN number\n END; # digital root #\n\n# calculates and prints the digital root and persistace of number #\nPROC print digital root and persistance = ( LONG LONG INT number )VOID:\n BEGIN\n INT root, persistance;\n digital root( number, root, persistance );\n print( ( whole( number, -15 ), \" root: \", whole( root, 0 ), \" persistance: \", whole( persistance, -3 ), newline ) )\n END; # print digital root and persistance #\n\n# test the digital root proc #\nBEGIN print digital root and persistance( 627615 )\n ; print digital root and persistance( 39390 )\n ; print digital root and persistance( 588225 )\n ; print digital root and persistance( 393900588225 )\nEND\n", "language": "ALGOL-68" }, { "code": "begin\n\n % calculates the digital root and persistence of an integer in base 10 %\n % in order to allow for numbers larger than 2^31, the number is passed %\n % as the lower and upper digits e.g. 393900588225 can be processed by %\n % specifying upper = 393900, lower = 58825 %\n procedure findDigitalRoot( integer value upper, lower\n ; integer result digitalRoot, persistence\n ) ;\n begin\n\n integer procedure sumDigits( integer value n ) ;\n begin\n integer digits, sum;\n\n digits := abs n;\n sum := 0;\n\n while digits > 0\n do begin\n sum := sum + ( digits rem 10 );\n digits := digits div 10\n end % while digits > 0 % ;\n\n % result: % sum\n end sumDigits;\n\n digitalRoot := sumDigits( upper ) + sumDigits( lower );\n persistence := 1;\n\n while digitalRoot > 9\n do begin\n persistence := persistence + 1;\n digitalRoot := sumDigits( digitalRoot );\n end % while digitalRoot > 9 % ;\n\n end findDigitalRoot ;\n\n % calculates and prints the digital root and persistence %\n procedure printDigitalRootAndPersistence( integer value upper, lower ) ;\n begin\n integer digitalRoot, persistence;\n findDigitalRoot( upper, lower, digitalRoot, persistence );\n write( s_w := 0 % set field saeparator width for this statement %\n , i_w := 8 % set integer field width for this statement %\n , upper\n , \", \"\n , lower\n , i_w := 2 % change integer field width %\n , \": digital root: \"\n , digitalRoot\n , \", persistence: \"\n , persistence\n )\n end printDigitalRootAndPersistence ;\n\n % test the digital root and persistence procedures %\n printDigitalRootAndPersistence( 0, 627615 );\n printDigitalRootAndPersistence( 0, 39390 );\n printDigitalRootAndPersistence( 0, 588225 );\n printDigitalRootAndPersistence( 393900, 588225 )\n\nend.\n", "language": "ALGOL-W" }, { "code": "on digitalroot(N as integer)\n\tscript math\n\t\tto sum(L)\n\t\t\tif L = {} then return 0\n\t\t\t(item 1 of L) + sum(rest of L)\n\t\tend sum\n\tend script\n\t\n\tset i to 0\n\tset M to N\n\t\n\trepeat until M < 10\n\t\tset digits to the characters of (M as text)\n\t\tset M to math's sum(digits)\n\t\tset i to i + 1\n\tend repeat\n\t\n\t{N:N, persistences:i, root:M}\nend digitalroot\n\n\ndigitalroot(627615)\n", "language": "AppleScript" }, { "code": "-------------------------- TESTS --------------------------\non run\n set firstCol to justifyRight(18, space)\n\n script test\n on |λ|(x)\n firstCol's |λ|(str(x)) & ¬\n \" -> \" & showTuple(digitalRoot(10)'s |λ|(x))\n end |λ|\n end script\n\n unlines({\"Base 10:\", firstCol's |λ|(\"Integer\") & ¬\n \" -> (additive persistance, digital root)\"} & ¬\n map(test, ¬\n {627615, 39390, 588225, 3.93900588225E+11}))\nend run\n\n\n---------------- DIGITAL ROOTS IN ANY BASE ----------------\n\n-- digitalRoot :: Int -> Int -> (Int, Int)\non digitalRoot(base)\n script p\n on |λ|(x)\n snd(x) ≥ base\n end |λ|\n end script\n\n script\n on |λ|(n)\n next(dropWhile(p, ¬\n iterate(bimap(my succ, digitalSum(base)), ¬\n Tuple(0, n))))\n end |λ|\n end script\nend digitalRoot\n\n\n-- digitalSum :: Int -> Int -> Int\non digitalSum(base)\n script\n on |λ|(n)\n script go\n on |λ|(x)\n if x > 0 then\n Just(Tuple(x mod base, x div base))\n else\n Nothing()\n end if\n end |λ|\n end script\n sum(unfoldr(go, n))\n end |λ|\n end script\nend digitalSum\n\n\n-------------------- GENERIC FUNCTIONS --------------------\n\n-- Just :: a -> Maybe a\non Just(x)\n -- Constructor for an inhabited Maybe (option type) value.\n -- Wrapper containing the result of a computation.\n {type:\"Maybe\", Nothing:false, Just:x}\nend Just\n\n\n-- Nothing :: Maybe a\non Nothing()\n -- Constructor for an empty Maybe (option type) value.\n -- Empty wrapper returned where a computation is not possible.\n {type:\"Maybe\", Nothing:true}\nend Nothing\n\n\n-- Tuple (,) :: a -> b -> (a, b)\non Tuple(a, b)\n -- Constructor for a pair of values, possibly of two different types.\n {type:\"Tuple\", |1|:a, |2|:b, length:2}\nend Tuple\n\n\n-- bimap :: (a -> b) -> (c -> d) -> (a, c) -> (b, d)\non bimap(f, g)\n -- Tuple instance of bimap.\n -- A tuple of the application of f and g to the\n -- first and second values of tpl respectively.\n script\n on |λ|(x)\n Tuple(|λ|(fst(x)) of mReturn(f), ¬\n |λ|(snd(x)) of mReturn(g))\n end |λ|\n end script\nend bimap\n\n\n-- cons :: a -> [a] -> [a]\non cons(x, xs)\n set c to class of xs\n if list is c then\n {x} & xs\n else if script is c then\n script\n property pRead : false\n on |λ|()\n if pRead then\n |λ|() of xs\n else\n set pRead to true\n return x\n end if\n end |λ|\n end script\n else\n x & xs\n end if\nend cons\n\n\n-- dropWhile :: (a -> Bool) -> Gen [a] -> [a]\non dropWhile(p, xs)\n set v to |λ|() of xs\n tell mReturn(p)\n repeat while (|λ|(v))\n set v to xs's |λ|()\n end repeat\n end tell\n return cons(v, xs)\nend dropWhile\n\n\n-- foldl :: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n\n-- fst :: (a, b) -> a\non fst(tpl)\n if class of tpl is record then\n |1| of tpl\n else\n item 1 of tpl\n end if\nend fst\n\n\n-- iterate :: (a -> a) -> a -> Gen [a]\non iterate(f, x)\n script\n property v : missing value\n property g : mReturn(f)\n on |λ|()\n if missing value is v then\n set v to x\n else\n set v to g's |λ|(v)\n end if\n return v\n end |λ|\n end script\nend iterate\n\n\n-- justifyRight :: Int -> Char -> String -> String\non justifyRight(n, cFiller)\n script\n on |λ|(s)\n if n > length of s then\n text -n thru -1 of ((replicate(n, cFiller) as text) & s)\n else\n strText\n end if\n end |λ|\n end script\nend justifyRight\n\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n -- The list obtained by applying f\n -- to each element of xs.\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n\n-- min :: Ord a => a -> a -> a\non min(x, y)\n if y < x then\n y\n else\n x\n end if\nend min\n\n\n-- mReturn :: First-class m => (a -> b) -> m (a -> b)\non mReturn(f)\n -- 2nd class handler function lifted into 1st class script wrapper.\n if script is class of f then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n\n-- next :: Gen [a] -> a\non next(xs)\n |λ|() of xs\nend next\n\n\n-- Egyptian multiplication - progressively doubling a list, appending\n-- stages of doubling to an accumulator where needed for binary\n-- assembly of a target length\n-- replicate :: Int -> a -> [a]\non replicate(n, a)\n set out to {}\n if 1 > n then return out\n set dbl to {a}\n\n repeat while (1 < n)\n if 0 < (n mod 2) then set out to out & dbl\n set n to (n div 2)\n set dbl to (dbl & dbl)\n end repeat\n return out & dbl\nend replicate\n\n\n-- showTuple :: Tuple -> String\non showTuple(tpl)\n \"(\" & str(fst(tpl)) & \", \" & str(snd(tpl)) & \")\"\nend showTuple\n\n\n-- snd :: (a, b) -> b\non snd(tpl)\n if class of tpl is record then\n |2| of tpl\n else\n item 2 of tpl\n end if\nend snd\n\n\n-- str :: a -> String\non str(x)\n x as string\nend str\n\n\n-- succ :: Enum a => a -> a\non succ(x)\n 1 + x\nend succ\n\n\n-- sum :: [Num] -> Num\non sum(xs)\n script add\n on |λ|(a, b)\n a + b\n end |λ|\n end script\n\n foldl(add, 0, xs)\nend sum\n\n\n-- take :: Int -> Gen [a] -> [a]\non take(n, xs)\n set ys to {}\n repeat with i from 1 to n\n set v to |λ|() of xs\n if missing value is v then\n return ys\n else\n set end of ys to v\n end if\n end repeat\n return ys\nend take\n\n\n-- > unfoldr (\\b -> if b == 0 then Nothing else Just (b, b-1)) 10\n-- > [10,9,8,7,6,5,4,3,2,1]\n-- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]\non unfoldr(f, v)\n set xr to {v, v} -- (value, remainder)\n set xs to {}\n tell mReturn(f)\n repeat -- Function applied to remainder.\n set mb to |λ|(snd(xr))\n if Nothing of mb then\n exit repeat\n else -- New (value, remainder) tuple,\n set xr to Just of mb\n -- and value appended to output list.\n set end of xs to fst(xr)\n end if\n end repeat\n end tell\n return xs\nend unfoldr\n\n\n-- unlines :: [String] -> String\non unlines(xs)\n -- A single string formed by the intercalation\n -- of a list of strings with the newline character.\n set {dlm, my text item delimiters} to ¬\n {my text item delimiters, linefeed}\n set s to xs as text\n set my text item delimiters to dlm\n s\nend unlines\n", "language": "AppleScript" }, { "code": "1 GOSUB 430\"BASE SETUP\n2 FOR E = 0 TO 1 STEP 0\n3 GOSUB 7\"READ\n4 ON E + 1 GOSUB 50, 10\n5 NEXT E\n6 END\n\n7 READ N$\n8 E = N$ = \"\"\n9 RETURN\n\n10 GOSUB 7\"READ BASE\n20 IF E THEN RETURN\n30 BASE = VAL(N$)\n40 READ N$\n\n50 GOSUB 100\"DIGITAL ROOT\n60 GOSUB 420: PRINT \" HAS AD\";\n70 PRINT \"DITIVE PERSISTENCE\";\n80 PRINT \" \"P\" AND DIGITAL R\";\n90 PRINT \"OOT \"X$\";\" : RETURN\n\nREM DIGITAL ROOT OF N$, RETURNS X$ AND P\n\n100 P = 0 : L = LEN(N$)\n110 X$ = MID$(N$, 2, L - 1)\n120 N = LEFT$(X$, 1) = \"-\"\n130 IF NOT N THEN X$ = N$\n140 FOR P = 0 TO 1E38\n150 L = LEN(X$)\n160 IF L < 2 THEN RETURN\n170 GOSUB 200\"DIGIT SUM\n180 X$ = S$\n190 NEXT P : STOP\n\nREM DIGIT SUM OF X$, RETURNS S$\n\n200 S$ = \"0\"\n210 R$ = X$\n220 L = LEN(R$)\n230 FOR L = L TO 1 STEP -1\n240 E$ = \"\" : V$ = RIGHT$(R$, 1)\n250 GOSUB 400 : S = LEN(S$)\n260 ON R$ <> \"0\" GOSUB 300\n270 R$ = MID$(R$, 1, L - 1)\n280 NEXT L\n290 RETURN\n\nREM ADD V TO S$\n\n300 FOR C = V TO 0 STEP 0\n310 V$ = RIGHT$(S$, 1)\n320 GOSUB 400 : S = S - 1\n330 S$ = MID$(S$, 1, S)\n340 V = V + C : C = V >= BASE\n350 IF C THEN V = V - BASE\n360 GOSUB 410 : E$ = V$ + E$\n370 IF S THEN NEXT C\n380 IF C THEN S$ = \"1\"\n390 S$ = S$ + E$ : RETURN\n\nREM BASE VAL\n400 V = V(ASC(V$)) : RETURN\n\nREM BASE STR$\n410 V$ = V$(V) : RETURN\n\nREM BASE DISPLAY\n420 PRINT N$;\n421 IF BASE = 10 THEN RETURN\n422 PRINT \"(\"BASE\")\";\n423 RETURN\n\nREM BASE SETUP\n430 IF BASE = 0 THEN BASE = 10\n440 DIM V(127), V$(35)\n450 FOR I = 0 TO 35\n460 V = 55 + I - (I < 10) * 7\n470 V$(I) = CHR$(V)\n480 V(V) = I\n490 NEXT I : RETURN\n\n500 DATA627615,39390,588225\n510 DATA393900588225\n1000 DATA,30\n1010 DATADIGITALROOT\n63999DATA,\n", "language": "Applesoft-BASIC" }, { "code": "droot: function [num][\n persistence: 0\n until [\n num: sum to [:integer] split to :string num\n persistence: persistence + 1\n ][ num < 10 ]\n return @[num, persistence]\n]\n\nloop [627615, 39390, 588225, 393900588225] 'i [\n a: droot i\n print [i \"has additive persistence\" a\\0 \"and digital root of\" a\\1]\n]\n", "language": "Arturo" }, { "code": "REM Digital root\nDATA 1&, 14&, 267&, 8128&, 39390&, 588225&, 627615&\nFOR I = 0 TO 6\n READ A&\n N& = A&\n Base = 10\n GOSUB CalcDRootAndPers:\n PRINT A&;\n PRINT Pers;\n PRINT Root\nNEXT I\nEND\n\nCalcDRootAndPers:\nREM Results: Root - digital root; Pers - persistance\nPers = 0\nWHILE N& >= Base\n S = 0\n Loop:\n NModBase& = N& MOD Base\n S = S + NModBase&\n N& = N& / Base\n IF N& > 0 THEN Loop:\n Pers = Pers + 1\n N& = S\nWEND\nRoot = N&\nRETURN\n", "language": "ASIC" }, { "code": "p := {}\nfor key, val in [30,1597,381947,92524902,448944221089]\n{\n n := val\n while n > 9\n {\n m := 0\n Loop, Parse, n\n m += A_LoopField\n n := m, i := A_Index\n }\n p[A_Index] := [val, n, i]\n}\n\nfor key, val in p\n Output .= val[1] \": Digital Root = \" val[2] \", Additive Persistence = \" val[3] \"`n\"\n\nMsgBox, 524288, , % Output\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f DIGITAL_ROOT.AWK\nBEGIN {\n n = split(\"627615,39390,588225,393900588225,10,199\",arr,\",\")\n for (i=1; i<=n; i++) {\n dr = digitalroot(arr[i],10)\n printf(\"%12.0f has additive persistence %d and digital root of %d\\n\",arr[i],p,dr)\n }\n exit(0)\n}\nfunction digitalroot(n,b) {\n p = 0 # global\n while (n >= b) {\n p++\n n = digitsum(n,b)\n }\n return(n)\n}\nfunction digitsum(n,b, q,s) {\n while (n != 0) {\n q = int(n / b)\n s += n - q * b\n n = q\n }\n return(s)\n}\n", "language": "AWK" }, { "code": "DECLARE SUB digitalRoot (what AS LONG)\n\n'test inputs:\ndigitalRoot 627615\ndigitalRoot 39390\ndigitalRoot 588225\n\nSUB digitalRoot (what AS LONG)\n DIM w AS LONG, t AS LONG, c AS INTEGER\n\n w = ABS(what)\n IF w > 10 THEN\n DO\n c = c + 1\n WHILE w\n t = t + (w MOD (10))\n w = w \\ 10\n WEND\n w = t\n t = 0\n LOOP WHILE w > 9\n END IF\n PRINT what; \": additive persistance \"; c; \", digital root \"; w\nEND SUB\n", "language": "BASIC" }, { "code": "global dr\nglobal ap\n\ndim a = {627615, 39390, 588225}\n\nfor i = 0 to a[?]-1\n\tdr = digitalRoot(a[i])\n\tprint a[i], \"Additive Persistence = \"; ap, \"Digital root = \"; dr\nnext i\nend\n\nfunction digitalRoot(n)\n\tap = 0\n\tdo\n\t\tdr = 0\n\t\twhile n > 0\n\t\t\tdr += n mod 10\n\t\t\tn = n \\ 10\n\t\tend while\n\t\tap += 1\n\t\tn = dr\n\tuntil dr < 10\n\treturn dr\nend function\n", "language": "BASIC256" }, { "code": ":: Digital Root Task from Rosetta Code Wiki\n:: Batch File Implementation\n:: (Base 10)\n\n@echo off\nsetlocal enabledelayedexpansion\n\n:: THE MAIN THING\nfor %%x in (9876543214 393900588225 1985989328582 34559) do call :droot %%x\necho(\npause\nexit /b\n:: /THE MAIN THING\n\n:: THE FUNCTION\n:droot\nset inp2sum=%1\nset persist=1\n\n:cyc1\nset sum=0\nset scan_digit=0\n:cyc2\nset digit=!inp2sum:~%scan_digit%,1!\nif \"%digit%\"==\"\" (goto :sumdone)\nset /a sum+=%digit%\nset /a scan_digit+=1\ngoto :cyc2\n\n:sumdone\nif %sum% lss 10 (\n\techo(\n\techo ^(%1^)\n\techo Additive Persistence=%persist% Digital Root=%sum%.\n\tgoto :EOF\n)\nset /a persist+=1\nset inp2sum=%sum%\ngoto :cyc1\n:: /THE FUNCTION\n", "language": "Batch-File" }, { "code": " *FLOAT64\n PRINT \"Digital root of 627615 is \"; FNdigitalroot(627615, 10, p) ;\n PRINT \" (additive persistence \" ; p \")\"\n PRINT \"Digital root of 39390 is \"; FNdigitalroot(39390, 10, p) ;\n PRINT \" (additive persistence \" ; p \")\"\n PRINT \"Digital root of 588225 is \"; FNdigitalroot(588225, 10, p) ;\n PRINT \" (additive persistence \" ; p \")\"\n PRINT \"Digital root of 393900588225 is \"; FNdigitalroot(393900588225, 10, p) ;\n PRINT \" (additive persistence \" ; p \")\"\n PRINT \"Digital root of 9992 is \"; FNdigitalroot(9992, 10, p) ;\n PRINT \" (additive persistence \" ; p \")\"\n END\n\n DEF FNdigitalroot(n, b, RETURN c)\n c = 0\n WHILE n >= b\n c += 1\n n = FNdigitsum(n, b)\n ENDWHILE\n = n\n\n DEF FNdigitsum(n, b)\n LOCAL q, s\n WHILE n <> 0\n q = INT(n / b)\n s += n - q * b\n n = q\n ENDWHILE\n = s\n", "language": "BBC-BASIC" }, { "code": "0\" :rebmun retnE\">:#,_0 0v\nv\\1:/+55p00<v\\`\\0::-\"0\"<~<\n#>:55+%00g+^>9`+#v_+\\ 1+\\^\n>|`9:p000<_v#`1\\$< v\"gi\"<\n|> \\ 1 + \\ >0\" :toor lat\"^\n>$$00g\\1+^@,+<v\"Di\",>#+ 5<\n>:#,_$ . 5 5 ^>:#,_\\.55+,v\n^\"Additive Persistence: \"<\n", "language": "Befunge" }, { "code": "DSum ← +´10{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}\nRoot ← 0⊸{(×○⌊÷⟜10)◶⟨𝕨‿𝕩,(1+𝕨)⊸𝕊 Dsum⟩𝕩}\n\nP ← •Show ⊢∾Root\nP 627615\nP 39390\nP 588225\nP 393900588225\n", "language": "BQN" }, { "code": "⟨ 627615 2 9 ⟩\n⟨ 39390 2 6 ⟩\n⟨ 588225 2 3 ⟩\n⟨ 393900588225 2 9 ⟩\n", "language": "BQN" }, { "code": " ( root\n = sum persistence n d\n . !arg:(~>9.?)\n | !arg:(?n.?persistence)\n & 0:?sum\n & ( @( !n\n : ?\n (#%@?d&!d+!sum:?sum&~)\n ?\n )\n | root$(!sum.!persistence+1)\n )\n )\n& ( 627615 39390 588225 393900588225 10 199\n : ?\n ( #%@?N\n & root$(!N.0):(?Sum.?Persistence)\n & out\n $ ( !N\n \"has additive persistence\"\n !Persistence\n \"and digital root of\"\n !Sum\n )\n & ~\n )\n ?\n | done\n );\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n\nint droot(long long int x, int base, int *pers)\n{\n\tint d = 0;\n\tif (pers)\n\t\tfor (*pers = 0; x >= base; x = d, (*pers)++)\n\t\t\tfor (d = 0; x; d += x % base, x /= base);\n\telse if (x && !(d = x % (base - 1)))\n\t\t\td = base - 1;\n\n\treturn d;\n}\n\nint main(void)\n{\n\tint i, d, pers;\n\tlong long x[] = {627615, 39390, 588225, 393900588225LL};\n\n\tfor (i = 0; i < 4; i++) {\n\t\td = droot(x[i], 10, &pers);\n\t\tprintf(\"%lld: pers %d, root %d\\n\", x[i], pers, d);\n\t}\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "// Calculate the Digital Root and Additive Persistance of an Integer - Compiles with gcc4.7\n//\n// Nigel Galloway. July 23rd., 2012\n//\n#include <iostream>\n#include <cmath>\n#include <utility>\n\ntemplate<class P_> P_ IncFirst(const P_& src) {return P_(src.first + 1, src.second);}\n\nstd::pair<int, int> DigitalRoot(unsigned long long digits, int base = 10)\n{\n int x = SumDigits(digits, base);\n return x < base ? std::make_pair(1, x) : IncFirst(DigitalRoot(x, base)); // x is implicitly converted to unsigned long long; this is lossless\n}\n\nint main() {\n const unsigned long long ip[] = {961038,923594037444,670033,448944221089};\n for (auto i:ip){\n auto res = DigitalRoot(i);\n std::cout << i << \" has digital root \" << res.second << \" and additive persistance \" << res.first << \"\\n\";\n }\n std::cout << \"\\n\";\n const unsigned long long hip[] = {0x7e0,0x14e344,0xd60141,0x12343210};\n for (auto i:hip){\n auto res = DigitalRoot(i,16);\n std::cout << std::hex << i << \" has digital root \" << res.second << \" and additive persistance \" << res.first << \"\\n\";\n }\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Linq;\n\nclass Program\n{\n static Tuple<int, int> DigitalRoot(long num)\n {\n int additivepersistence = 0;\n while (num > 9)\n {\n num = num.ToString().ToCharArray().Sum(x => x - '0');\n additivepersistence++;\n }\n return new Tuple<int, int>(additivepersistence, (int)num);\n }\n static void Main(string[] args)\n {\n foreach (long num in new long[] { 627615, 39390, 588225, 393900588225 })\n {\n var t = DigitalRoot(num);\n Console.WriteLine(\"{0} has additive persistence {1} and digital root {2}\", num, t.Item1, t.Item2);\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(defn dig-root [value]\n (let [digits (fn [n]\n (map #(- (byte %) (byte \\0))\n (str n)))\n sum (fn [nums]\n (reduce + nums))]\n (loop [n value\n step 0]\n (if (< n 10)\n {:n value :add-persist step :digital-root n}\n (recur (sum (digits n))\n (inc step))))))\n", "language": "Clojure" }, { "code": "sum_digits = proc (n, base: int) returns (int)\n sum: int := 0\n while n > 0 do\n sum := sum + n // base\n n := n / base\n end\n return (sum)\nend sum_digits\n\ndigital_root = proc (n, base: int) returns (int, int)\n persistence: int := 0\n while n >= base do\n persistence := persistence + 1\n n := sum_digits(n, base)\n end\n return (n, persistence)\nend digital_root\n\nstart_up = proc ()\n po: stream := stream$primary_output()\n tests: array[int] := array[int]$[627615, 39390, 588225, 393900588225]\n\n for test: int in array[int]$elements(tests) do\n root, persistence: int := digital_root(test, 10)\n stream$putl(po, int$unparse(test)\n || \" has additive persistence \"\n || int$unparse(persistence)\n || \" and digital root of \"\n || int$unparse(root))\n end\nend start_up\n", "language": "CLU" }, { "code": " IDENTIFICATION DIVISION.\n PROGRAM-ID. DIGITAL-ROOT.\n\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 VARIABLES.\n 03 INPUT-NUMBER PIC 9(16).\n 03 INPUT-DIGITS REDEFINES INPUT-NUMBER,\n PIC 9 OCCURS 16 TIMES.\n 03 DIGIT-SUM PIC 999.\n 03 DIGIT-NO PIC 99.\n 03 PERSISTENCE PIC 9.\n\n 01 OUTPUT-FORMAT.\n 03 O-NUMBER PIC Z(15)9.\n 03 FILLER PIC X(16) VALUE ': PERSISTENCE = '.\n 03 O-PERSISTENCE PIC Z9.\n 03 FILLER PIC X(9) VALUE ', ROOT = '.\n 03 O-ROOT PIC Z9.\n\n PROCEDURE DIVISION.\n BEGIN.\n MOVE 627615 TO INPUT-NUMBER, PERFORM FIND-DIGITAL-ROOT.\n MOVE 39390 TO INPUT-NUMBER, PERFORM FIND-DIGITAL-ROOT.\n MOVE 588225 TO INPUT-NUMBER, PERFORM FIND-DIGITAL-ROOT.\n MOVE 393900588225 TO INPUT-NUMBER, PERFORM FIND-DIGITAL-ROOT.\n STOP RUN.\n\n FIND-DIGITAL-ROOT.\n MOVE ZERO TO PERSISTENCE.\n MOVE INPUT-NUMBER TO O-NUMBER.\n PERFORM SUMMATION UNTIL INPUT-NUMBER IS LESS THAN 10.\n MOVE INPUT-NUMBER TO O-ROOT.\n MOVE PERSISTENCE TO O-PERSISTENCE.\n DISPLAY OUTPUT-FORMAT.\n\n SUMMATION.\n MOVE ZERO TO DIGIT-SUM.\n ADD 1 TO PERSISTENCE.\n PERFORM ADD-DIGIT VARYING DIGIT-NO FROM 1 BY 1\n UNTIL DIGIT-NO IS GREATER THAN 16.\n MOVE DIGIT-SUM TO INPUT-NUMBER.\n\n ADD-DIGIT.\n ADD INPUT-DIGITS(DIGIT-NO) TO DIGIT-SUM.\n", "language": "COBOL" }, { "code": "(defun digital-root (number &optional (base 10))\n (loop for n = number then s\n for ap = 1 then (1+ ap)\n for s = (sum-digits n base)\n when (< s base)\n return (values s ap)))\n\n(loop for (nr base) in '((627615 10) (393900588225 10) (#X14e344 16) (#36Rdg9r 36))\n do (multiple-value-bind (dr ap) (digital-root nr base)\n (format T \"~vR (base ~a): additive persistence = ~a, digital root = ~vR~%\"\n base nr base ap base dr)))\n", "language": "Common-Lisp" }, { "code": "MODULE DigitalRoot;\nIMPORT StdLog, Strings, TextMappers, DevCommanders;\n\nPROCEDURE CalcDigitalRoot(x: LONGINT; OUT dr,pers: LONGINT);\nVAR\n\tstr: ARRAY 64 OF CHAR;\n\ti: INTEGER;\nBEGIN\n\tdr := 0;pers := 0;\n\tLOOP\n\t\tStrings.IntToString(x,str);\n\t\tIF LEN(str$) = 1 THEN dr := x ;EXIT END;\n\t\ti := 0;dr := 0;\n\t\tWHILE (i < LEN(str$)) DO\n\t\t\tINC(dr,ORD(str[i]) - ORD('0'));\n\t\t\tINC(i)\n\t\tEND;\n\t\tINC(pers);\n\t\tx := dr\n\tEND;\nEND CalcDigitalRoot;\n\nPROCEDURE Do*;\nVAR\n\tdr,pers: LONGINT;\n\ts: TextMappers.Scanner;\nBEGIN\n\ts.ConnectTo(DevCommanders.par.text);\n\ts.SetPos(DevCommanders.par.beg);\n\tREPEAT\n\t\ts.Scan;\n\t\tIF (s.type = TextMappers.int) OR (s.type = TextMappers.lint) THEN\n\t\t\tCalcDigitalRoot(s.int,dr,pers);\n\t\t\tStdLog.Int(s.int);\n\t\t\tStdLog.String(\" Digital root: \");StdLog.Int(dr);\n\t\t\tStdLog.String(\" Persistence: \");StdLog.Int(pers);StdLog.Ln\n\t\tEND\n\tUNTIL s.rider.eot;\nEND Do;\nEND DigitalRoot.\n", "language": "Component-Pascal" }, { "code": "include \"cowgol.coh\";\n\n# Calculate the digital root and additive persistance of a number\n# in a given base\nsub digital_root(n: uint32, base: uint32): (root: uint32, pers: uint8) is\n pers := 0;\n while base < n loop\n var step: uint32 := 0;\n while n > 0 loop\n step := step + (n % base);\n n := n / base;\n end loop;\n pers := pers + 1;\n n := step;\n end loop;\n root := n;\nend sub;\n\n# Print digital root and persistence (in base 10)\nsub test(n: uint32) is\n var root: uint32;\n var pers: uint8;\n\n (root, pers) := digital_root(n, 10);\n\n print_i32(n);\n print(\": root = \");\n print_i32(root);\n print(\", persistence = \");\n print_i8(pers);\n print_nl();\nend sub;\n\ntest(4);\ntest(627615);\ntest(39390);\ntest(588225);\ntest(9992);\n", "language": "Cowgol" }, { "code": "def digital_root(n : Int, base = 10) : Int\n max_single_digit = base - 1\n n = n.abs\n if n > max_single_digit\n n = 1 + (n - 1) % max_single_digit\n end\n n\nend\n\nputs digital_root 627615\nputs digital_root 39390\nputs digital_root 588225\nputs digital_root 7, base: 3\n", "language": "Crystal" }, { "code": "def digital_root_with_persistence(n : Int) : {Int32, Int32}\n n = n.abs\n persistence = 0\n\n until n <= 9\n persistence += 1\n\n digit_sum = (0..(Math.log10(n).floor.to_i)).sum { |i| (n % 10**(i + 1) - n % 10**i) // 10**i }\n\n n = digit_sum\n end\n\n {n, persistence}\nend\n\nputs digital_root_with_persistence 627615\nputs digital_root_with_persistence 39390\nputs digital_root_with_persistence 588225\n", "language": "Crystal" }, { "code": "def digital_root_with_persistence_to_s(n : Int) : {Int32, Int32}\n n = n.abs\n persistence = 0\n\n until n <= 9\n persistence += 1\n\n digit_sum = n.to_s.chars.sum &.to_i\n\n n = digit_sum\n end\n\n {n, persistence}\nend\n\nputs digital_root_with_persistence_to_s 627615\nputs digital_root_with_persistence_to_s 39390\nputs digital_root_with_persistence_to_s 588225\n", "language": "Crystal" }, { "code": "import std.stdio, std.typecons, std.conv, std.bigint, std.math,\n std.traits;\n\nTuple!(uint, Unqual!T) digitalRoot(T)(in T inRoot, in uint base)\npure nothrow\nin {\n assert(base > 1);\n} body {\n Unqual!T root = inRoot.abs;\n uint persistence = 0;\n while (root >= base) {\n auto num = root;\n root = 0;\n while (num != 0) {\n root += num % base;\n num /= base;\n }\n persistence++;\n }\n return typeof(return)(persistence, root);\n}\n\nvoid main() {\n enum f1 = \"%s(%d): additive persistance= %d, digital root= %d\";\n foreach (immutable b; [2, 3, 8, 10, 16, 36]) {\n foreach (immutable n; [5, 627615, 39390, 588225, 393900588225])\n writefln(f1, text(n, b), b, n.digitalRoot(b)[]);\n writeln;\n }\n\n enum f2 = \"<BIG>(%d): additive persistance= %d, digital root= %d\";\n immutable n = BigInt(\"581427189816730304036810394583022044713\" ~\n \"00738980834668522257090844071443085937\");\n foreach (immutable b; [2, 3, 8, 10, 16, 36])\n writefln(f2, b, n.digitalRoot(b)[]); // Shortened output.\n}\n", "language": "D" }, { "code": "?[10~rd10<p]sp[+z1<q]sq[lpxlqxd10<r]dsrxp\n", "language": "Dc" }, { "code": "$ x = p1\n$ count = 0\n$ sum = x\n$ loop1:\n$ length = f$length( x )\n$ if length .eq. 1 then $ goto done\n$ i = 0\n$ sum = 0\n$ loop2:\n$ digit = f$extract( i, 1, x )\n$ sum = sum + digit\n$ i = i + 1\n$ if i .lt. length then $ goto loop2\n$ x = f$string( sum )\n$ count = count + 1\n$ goto loop1\n$ done:\n$ write sys$output p1, \" has additive persistence \", count, \" and digital root of \", sum\n", "language": "DCL" }, { "code": "proc digitalRoot n . x persistence .\n numberString$ = n\n currentPersist = 0\n while len numberString$ > 1\n for i = 1 to len numberString$\n sum += number substr numberString$ i 1\n .\n numberString$ = sum\n currentPersist += 1\n sum = 0\n .\n x = number numberString$\n persistence = currentPersist\n.\nnumbers[] = [ 627615 39390 588225 393900588225 ]\nfor i in numbers[]\n digitalRoot i x persistence\n print i\n print \"Additive persistence: \" & persistence\n print \"Digital root: \" & x\n.\n", "language": "EasyLang" }, { "code": "class\n\tAPPLICATION\n\ninherit\n\tARGUMENTS\n\ncreate\n\tmake\n\nfeature {NONE} -- Initialization\n\n\tdigital_root_test_values: ARRAY [INTEGER_64]\n\t\t\t-- Test values.\n\t\tonce\n\t\t \tResult := <<670033, 39390, 588225, 393900588225>> -- base 10\n\t\tend\n\n\tdigital_root_expected_result: ARRAY [INTEGER_64]\n\t\t\t-- Expected result values.\n\t\tonce\n\t\t\tResult := <<1, 6, 3, 9>> -- base 10\n\t\tend\n\n\tmake\n\t\tlocal\n\t\t\tresults: ARRAY [INTEGER_64]\n\t\t\ti: INTEGER\n\t\tdo\n\t\t\tfrom\n\t\t\t\ti := 1\n\t\t\tuntil\n\t\t\t\ti > digital_root_test_values.count\n\t\t\tloop\n\t\t\t\tresults := compute_digital_root (digital_root_test_values [i], 10)\n\t\t\t\tif results [2] ~ digital_root_expected_result [i] then\n\t\t\t\t\tprint (\"%N\" + digital_root_test_values [i].out + \" has additive persistence \" + results [1].out + \" and digital root \" + results [2].out)\n\t\t\t\telse\n\t\t\t\t\tprint (\"Error in the calculation of the digital root of \" + digital_root_test_values [i].out + \". Expected value: \" + digital_root_expected_result [i].out + \", produced value: \" + results [2].out)\n\t\t\t\tend\n\t\t\t\ti := i\t+ 1\n\t\t\tend\n\t\tend\n\ncompute_digital_root (a_number: INTEGER_64; a_base: INTEGER): ARRAY [INTEGER_64]\n\t\t\t\t-- Returns additive persistence and digital root of `a_number' using `a_base'.\n\t\trequire\n valid_number: a_number >= 0\n valid_base: a_base > 1\n local\n\t\t\ttemp_num: INTEGER_64\n\t\tdo\n\t\t\tcreate Result.make_filled (0, 1, 2)\n\t\t\tfrom\n\t\t\t\tResult [2] := a_number\n\t\t\tuntil\n\t\t\t\tResult [2] < a_base\n\t\t\tloop\n\t\t\t\tfrom\n\t\t\t\t\ttemp_num := Result [2]\n\t\t\t\t\tResult [2] := 0\n\t\t\t\tuntil\n\t\t\t\t\ttemp_num = 0\n\t\t\t\tloop\n\t\t\t\t\tResult [2] := Result [2] + (temp_num \\\\ a_base)\n\t\t\t\t\ttemp_num := temp_num // a_base\n\t\t\t\tend\n\t\t\t\tResult [1] := Result [1] + 1\n\t\t\tend\n\t\tend\n", "language": "Eiffel" }, { "code": "import extensions;\nimport system'routines;\nimport system'collections;\n\nextension op\n{\n get DigitalRoot()\n {\n int additivepersistence := 0;\n long num := self;\n\n while (num > 9)\n {\n num := num.toPrintable().toArray().selectBy::(ch => ch.toInt() - 48).summarize(new LongInteger());\n\n additivepersistence += 1\n };\n\n ^ new Tuple<int,int>(additivepersistence, num.toInt())\n }\n}\n\npublic program()\n{\n new long[]{627615l, 39390l, 588225l, 393900588225l}.forEach::(num)\n {\n var t := num.DigitalRoot;\n\n console.printLineFormatted(\"{0} has additive persistence {1} and digital root {2}\", num, t.Item1, t.Item2)\n }\n}\n", "language": "Elena" }, { "code": "defmodule Digital do\n def root(n, base\\\\10), do: root(n, base, 0)\n\n defp root(n, base, ap) when n < base, do: {n, ap}\n defp root(n, base, ap) do\n Integer.digits(n, base) |> Enum.sum |> root(base, ap+1)\n end\nend\n\ndata = [627615, 39390, 588225, 393900588225]\nEnum.each(data, fn n ->\n {dr, ap} = Digital.root(n)\n IO.puts \"#{n} has additive persistence #{ap} and digital root of #{dr}\"\nend)\n\nbase = 16\nIO.puts \"\\nBase = #{base}\"\nfmt = \"~.#{base}B(#{base}) has additive persistence ~w and digital root of ~w~n\"\nEnum.each(data, fn n ->\n {dr, ap} = Digital.root(n, base)\n :io.format fmt, [n, ap, dr]\nend)\n", "language": "Elixir" }, { "code": "-module( digital_root ).\n\n-export( [task/0] ).\n\ntask() ->\n Ns = [N || N <- [627615, 39390, 588225, 393900588225]],\n Persistances = [persistance_root(X) || X <-\tNs],\n [io:fwrite(\"~p has additive persistence ~p and digital root of ~p~n\", [X, Y, Z]) || {X, {Y, Z}} <- lists:zip(Ns, Persistances)].\n\n\npersistance_root( X ) -> persistance_root( sum_digits:sum_digits(X), 1 ).\n\npersistance_root( X, N ) when X\t< 10 ->\t{N, X};\npersistance_root( X, N ) -> persistance_root( sum_digits:sum_digits(X),\tN + 1 ).\n", "language": "Erlang" }, { "code": "//Find the Digital Root of An Integer - Nigel Galloway: February 1st., 2015\n//This code will work with any integer type\nlet inline digitalRoot N BASE =\n let rec root(p,n) =\n let s = sumDigits n BASE\n if s < BASE then (s,p) else root(p+1, s)\n root(LanguagePrimitives.GenericZero<_> + 1, N)\n", "language": "F-Sharp" }, { "code": "USING: arrays formatting kernel math math.text.utils sequences ;\nIN: rosetta-code.digital-root\n\n: digital-root ( n -- persistence root )\n 0 swap [ 1 digit-groups dup length 1 > ] [ sum [ 1 + ] dip ]\n while first ;\n\n: print-root ( n -- )\n dup digital-root\n \"%-12d has additive persistence %d and digital root %d.\\n\"\n printf ;\n\n{ 627615 39390 588225 393900588225 } [ print-root ] each\n", "language": "Factor" }, { "code": ": (Sdigit) 0 swap begin base @ /mod >r + r> dup 0= until drop ;\n: digiroot 0 swap begin (Sdigit) >r 1+ r> dup base @ < until ;\n", "language": "Forth" }, { "code": "[UNDEFINED] mu/mod [IF] : mu/mod >r 0 r@ um/mod r> swap >r um/mod r> ; [THEN]\n\n: (Sdigit) 0. 2swap begin base @ mu/mod 2>r s>d d+ 2r> 2dup d0= until 2drop ;\n: digiroot 0 -rot begin (Sdigit) 2>r 1+ 2r> 2dup base @ s>d d< until d>s ;\n", "language": "Forth" }, { "code": "program prec\nimplicit none\ninteger(kind=16) :: i\ni = 627615\ncall root_pers(i)\ni = 39390\ncall root_pers(i)\ni = 588225\ncall root_pers(i)\ni = 393900588225\ncall root_pers(i)\nend program\n\nsubroutine root_pers(i)\nimplicit none\ninteger(kind=16) :: N, s, a, i\nwrite(*,*) 'Number: ', i\nn = i\na = 0\ndo while(n.ge.10)\n a = a + 1\n s = 0\n do while(n.gt.0)\n s = s + n-int(real(n,kind=8)/10.0D0,kind=8) * 10_8\n n = int(real(n,kind=16)/real(10,kind=8),kind=8)\n end do\n n = s\nend do\nwrite(*,*) 'digital root = ', s\nwrite(*,*) 'additive persistance = ', a\nend subroutine\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nFunction digitalRoot(n As UInteger, ByRef ap As Integer, base_ As Integer = 10) As Integer\n Dim dr As Integer\n ap = 0\n Do\n dr = 0\n While n > 0\n dr += n Mod base_\n n = n \\ base_\n Wend\n ap += 1\n n = dr\n Loop until dr < base_\n Return dr\nEnd Function\n\nDim As Integer dr, ap\nDim a(3) As UInteger = {627615, 39390, 588225, 393900588225}\nFor i As Integer = 0 To 3\n ap = 0\n dr = digitalRoot(a(i), ap)\n Print a(i), \"Additive Persistence =\"; ap, \"Digital root =\"; dr\n Print\nNext\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n)\n\nfunc Sum(i uint64, base int) (sum int) {\n\tb64 := uint64(base)\n\tfor ; i > 0; i /= b64 {\n\t\tsum += int(i % b64)\n\t}\n\treturn\n}\n\nfunc DigitalRoot(n uint64, base int) (persistence, root int) {\n\troot = int(n)\n\tfor x := n; x >= uint64(base); x = uint64(root) {\n\t\troot = Sum(x, base)\n\t\tpersistence++\n\t}\n\treturn\n}\n\n// Normally the below would be moved to a *_test.go file and\n// use the testing package to be runnable as a regular test.\n\nvar testCases = []struct {\n\tn string\n\tbase int\n\tpersistence int\n\troot int\n}{\n\t{\"627615\", 10, 2, 9},\n\t{\"39390\", 10, 2, 6},\n\t{\"588225\", 10, 2, 3},\n\t{\"393900588225\", 10, 2, 9},\n\t{\"1\", 10, 0, 1},\n\t{\"11\", 10, 1, 2},\n\t{\"e\", 16, 0, 0xe},\n\t{\"87\", 16, 1, 0xf},\n\t// From Applesoft BASIC example:\n\t{\"DigitalRoot\", 30, 2, 26}, // 26 is Q base 30\n\t// From C++ example:\n\t{\"448944221089\", 10, 3, 1},\n\t{\"7e0\", 16, 2, 0x6},\n\t{\"14e344\", 16, 2, 0xf},\n\t{\"d60141\", 16, 2, 0xa},\n\t{\"12343210\", 16, 2, 0x1},\n\t// From the D example:\n\t{\"1101122201121110011000000\", 3, 3, 1},\n}\n\nfunc main() {\n\tfor _, tc := range testCases {\n\t\tn, err := strconv.ParseUint(tc.n, tc.base, 64)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tp, r := DigitalRoot(n, tc.base)\n\t\tfmt.Printf(\"%12v (base %2d) has additive persistence %d and digital root %s\\n\",\n\t\t\ttc.n, tc.base, p, strconv.FormatInt(int64(r), tc.base))\n\t\tif p != tc.persistence || r != tc.root {\n\t\t\tlog.Fatalln(\"bad result:\", tc, p, r)\n\t\t}\n\t}\n}\n", "language": "Go" }, { "code": "class DigitalRoot {\n static int[] calcDigitalRoot(String number, int base) {\n BigInteger bi = new BigInteger(number, base)\n int additivePersistence = 0\n if (bi.signum() < 0) {\n bi = bi.negate()\n }\n BigInteger biBase = BigInteger.valueOf(base)\n while (bi >= biBase) {\n number = bi.toString(base)\n bi = BigInteger.ZERO\n for (int i = 0; i < number.length(); i++) {\n bi = bi.add(new BigInteger(number.substring(i, i + 1), base))\n }\n additivePersistence++\n }\n return [additivePersistence, bi.intValue()]\n }\n\n static void main(String[] args) {\n for (String arg : [627615, 39390, 588225, 393900588225]) {\n int[] results = calcDigitalRoot(arg, 10)\n println(\"$arg has additive persistence ${results[0]} and digital root of ${results[1]}\")\n }\n }\n}\n", "language": "Groovy" }, { "code": "import Data.Bifunctor (bimap)\nimport Data.List (unfoldr)\nimport Data.Tuple (swap)\n\ndigSum :: Int -> Int -> Int\ndigSum base = sum . unfoldr f\n where\n f 0 = Nothing\n f n = Just (swap (quotRem n base))\n\ndigRoot :: Int -> Int -> (Int, Int)\ndigRoot base =\n head .\n dropWhile ((>= base) . snd) . iterate (bimap succ (digSum base)) . (,) 0\n\nmain :: IO ()\nmain = do\n putStrLn \"in base 10:\"\n mapM_ (print . ((,) <*> digRoot 10)) [627615, 39390, 588225, 393900588225]\n", "language": "Haskell" }, { "code": "import Data.Tuple (swap)\nimport Data.Maybe (fromJust)\nimport Data.List (elemIndex, unfoldr)\nimport Numeric (readInt, showIntAtBase)\n\n-- Return a pair consisting of the additive persistence and digital root of a\n-- base b number.\ndigRoot :: Integer -> Integer -> (Integer, Integer)\ndigRoot b = find . zip [0 ..] . iterate (sum . toDigits b)\n where\n find = head . dropWhile ((>= b) . snd)\n\n-- Print the additive persistence and digital root of a base b number (given as\n-- a string).\nprintDigRoot :: Integer -> String -> IO ()\nprintDigRoot b s = do\n let (p, r) = digRoot b $ strToInt b s\n (putStrLn . unwords)\n [s, \"-> additive persistence:\", show p, \"digital root:\", intToStr b r]\n\n--\n-- Utility methods for dealing with numbers in different bases.\n--\n-- Convert a base b number to a list of digits, from least to most significant.\ntoDigits\n :: Integral a\n => a -> a -> [a]\ntoDigits b = unfoldr f\n where\n f 0 = Nothing\n f n = Just (swap (quotRem n b))\n\n-- A list of digits, for bases up to 36.\ndigits :: String\ndigits = ['0' .. '9'] ++ ['A' .. 'Z']\n\n-- Return a number's base b string representation.\nintToStr\n :: (Integral a, Show a)\n => a -> a -> String\nintToStr b n\n | b < 2 || b > 36 = error \"intToStr: base must be in [2..36]\"\n | otherwise = showIntAtBase b (digits !!) n \"\"\n\n-- Return the number for the base b string representation.\nstrToInt\n :: Integral a\n => a -> String -> a\nstrToInt b =\n fst . head . readInt b (`elem` digits) (fromJust . (`elemIndex` digits))\n\nmain :: IO ()\nmain =\n mapM_\n (uncurry printDigRoot)\n [ (2, \"1001100111011110\")\n , (3, \"2000000220\")\n , (8, \"5566623376301\")\n , (10, \"39390\")\n , (16, \"99DE\")\n , (36, \"50YE8N29\")\n , (36, \"37C71GOYNYJ25M3JTQQVR0FXUK0W9QM71C1LVN\")\n ]\n", "language": "Haskell" }, { "code": "main( argv_ ) {\n\tif ( size( argv_ ) < 2 ) {\n\t\tthrow Exception( \"usage: digital-root {NUM}\" );\n\t}\n\tn = argv_[1];\n\tif ( ( size( n ) == 0 ) || ( n.find_other_than( \"0123456789\" ) >= 0 ) ) {\n\t\tthrow Exception( \"{} is not a number\".format( n ) );\n\t}\n\tshift = integer( '0' ) + 1;\n\tacc = 0;\n\tfor ( d : n ) {\n\t\tacc = 1 + ( acc + integer( d ) - shift ) % 9;\n\t}\n\tprint( \"{}\\n\".format( acc ) );\n\treturn ( 0 );\n}\n", "language": "Huginn" }, { "code": "procedure main(A)\n every m := n := integer(!A) do {\n ap := 0\n while (*n > 1) do (ap +:= 1, n := sumdigits(n))\n write(m,\" has additive persistence of \",ap,\" and digital root of \",n)\n }\nend\n\nprocedure sumdigits(n)\n s := 0\n n ? while s +:= move(1)\n return s\nend\n", "language": "Icon" }, { "code": "digrt=: 10&$: :(|&.<:^:<:)\"0\n\naddps=: 10&$: :([: <:@# +/@(#.inv)^:a:)\"0\n", "language": "J" }, { "code": " (,. addps ,. digrt) 627615 39390 588225 393900588225\n 627615 2 9\n 39390 2 6\n 588225 2 3\n393900588225 2 9\n\n 8 digrt 8b4321\n3\n 8 addps 8b4321\n2\n", "language": "J" }, { "code": "equals=: =&(9&|)\"0\n", "language": "J" }, { "code": " equals table i. 10\n┌──────┬───────────────────┐\n│equals│0 1 2 3 4 5 6 7 8 9│\n├──────┼───────────────────┤\n│0 │1 0 0 0 0 0 0 0 0 1│\n│1 │0 1 0 0 0 0 0 0 0 0│\n│2 │0 0 1 0 0 0 0 0 0 0│\n│3 │0 0 0 1 0 0 0 0 0 0│\n│4 │0 0 0 0 1 0 0 0 0 0│\n│5 │0 0 0 0 0 1 0 0 0 0│\n│6 │0 0 0 0 0 0 1 0 0 0│\n│7 │0 0 0 0 0 0 0 1 0 0│\n│8 │0 0 0 0 0 0 0 0 1 0│\n│9 │1 0 0 0 0 0 0 0 0 1│\n└──────┴───────────────────┘\n", "language": "J" }, { "code": "(defn numbers [s] (filter (fn [y] (and (<= y 9) (>= y 0))) (map (fn [z] (- z 48)) (string/bytes s))))\n(defn summa [s] (reduce (fn [x y] (+ x y)) 0 (numbers s)))\n(defn minsumma [x p]\n (if (<= x 9)\n [x p]\n (minsumma (summa (string/format \"%d\" x)) (+ 1 p))))\n(defn test [t] (printf \"%j\" (minsumma (summa t) 1)))\n(test \"627615\")\n(test \"39390\")\n(test \"588225\")\n(test \"393900588225\")\n(test \"19999999999999999999999999999999999999999999999999999999999999999999999999999999999999\")\n(test \"192348-0347203478-20483298402-39482-04720348-20394823-058720375204820-394823842-049802-93482-034892-3\")\n", "language": "Janet" }, { "code": "import java.math.BigInteger;\n\nclass DigitalRoot\n{\n public static int[] calcDigitalRoot(String number, int base)\n {\n BigInteger bi = new BigInteger(number, base);\n int additivePersistence = 0;\n if (bi.signum() < 0)\n bi = bi.negate();\n BigInteger biBase = BigInteger.valueOf(base);\n while (bi.compareTo(biBase) >= 0)\n {\n number = bi.toString(base);\n bi = BigInteger.ZERO;\n for (int i = 0; i < number.length(); i++)\n bi = bi.add(new BigInteger(number.substring(i, i + 1), base));\n additivePersistence++;\n }\n return new int[] { additivePersistence, bi.intValue() };\n }\n\n public static void main(String[] args)\n {\n for (String arg : args)\n {\n int[] results = calcDigitalRoot(arg, 10);\n System.out.println(arg + \" has additive persistence \" + results[0] + \" and digital root of \" + results[1]);\n }\n }\n}\n", "language": "Java" }, { "code": "/// Digital root of 'x' in base 'b'.\n/// @return {addpers, digrt}\nfunction digitalRootBase(x,b) {\n if (x < b)\n return {addpers:0, digrt:x};\n\n var fauxroot = 0;\n while (b <= x) {\n x = (x / b) | 0;\n fauxroot += x % b;\n }\n\n var rootobj = digitalRootBase(fauxroot,b);\n rootobj.addpers += 1;\n return rootobj;\n}\n", "language": "JavaScript" }, { "code": "def do_until(condition; next):\n def u: if condition then . else (next|u) end;\n u;\n\n# n may be a decimal number or a string representing a decimal number\ndef digital_root(n):\n # string-only version\n def dr:\n # state: [mdr, persist]\n do_until( .[0] | length == 1;\n [ (.[0] | explode | map(.-48) | add | tostring), .[1] + 1 ]\n );\n [n|tostring, 0] | dr | .[0] |= tonumber;\n\ndef neatly:\n . as $in\n | range(0;length)\n | \"\\(.): \\($in[.])\";\n\ndef rjust(n): tostring | (n-length)*\" \" + .;\n", "language": "Jq" }, { "code": "(\n \" i : [DR, P]\",\n (961038, 923594037444, 670033, 448944221089\n ) as $i\n | \"\\($i|rjust(12)): \\(digital_root($i))\"\n),\n \"\",\n \"digital_root(\\\"1\\\" * 100000) => \\(digital_root( \"1\" * 100000))\"\n", "language": "Jq" }, { "code": "$ jq -M -n -r -c -f Digital_root.jq\n\n i : [DR, P]\n 961038: [9,2]\n923594037444: [9,2]\n 670033: [1,3]\n448944221089: [1,3]\n\ndigital_root(\"1\" * 100000) => [1,2]\n", "language": "Jq" }, { "code": "function digitalroot(n::Integer, bs::Integer=10)\n if n < 0 || bs < 2 throw(DomainError()) end\n ds, pers = n, 0\n while bs ≤ ds\n ds = sum(digits(ds, bs))\n pers += 1\n end\n return pers, ds\nend\n\nfor i in [627615, 39390, 588225, 393900588225, big(2) ^ 100]\n pers, ds = digitalroot(i)\n println(i, \" has persistence \", pers, \" and digital root \", ds)\nend\n", "language": "Julia" }, { "code": "/ print digital root and additive persistence\nprt: {`\"Digital root = \", x, `\"Additive persistence = \",y}\n/ sum of digits of an integer\nsumdig: {d::(); (0<){d::d,x!10; x%:10}/x; +/d}\n/ compute digital root and additive persistence\ndigroot: {sm::sumdig x; ap::0; (9<){sm::sumdig x;ap::ap+1; x:sm}/x; prt[sm;ap]}\n", "language": "K" }, { "code": "// version 1.0.6\n\nfun sumDigits(n: Long): Int = when {\n n < 0L -> throw IllegalArgumentException(\"Negative numbers not allowed\")\n else -> {\n var sum = 0\n var nn = n\n while (nn > 0L) {\n sum += (nn % 10).toInt()\n nn /= 10\n }\n sum\n }\n }\n\nfun digitalRoot(n: Long): Pair<Int, Int> = when {\n n < 0L -> throw IllegalArgumentException(\"Negative numbers not allowed\")\n n < 10L -> Pair(n.toInt(), 0)\n else -> {\n var dr = n\n var ap = 0\n while (dr > 9L) {\n dr = sumDigits(dr).toLong()\n ap++\n }\n Pair(dr.toInt(), ap)\n }\n }\n\nfun main(args: Array<String>) {\n val a = longArrayOf(1, 14, 267, 8128, 627615, 39390, 588225, 393900588225)\n for (n in a) {\n val(dr, ap) = digitalRoot(n)\n println(\"${n.toString().padEnd(12)} has additive persistence $ap and digital root of $dr\")\n }\n}\n", "language": "Kotlin" }, { "code": "function digital_root(n, base)\n p = 0\n while n > 9.5 do\n n = sum_digits(n, base)\n p = p + 1\n end\n return n, p\nend\n\nprint(digital_root(627615, 10))\nprint(digital_root(39390, 10))\nprint(digital_root(588225, 10))\nprint(digital_root(393900588225, 10))\n", "language": "Lua" }, { "code": " NORMAL MODE IS INTEGER\n VECTOR VALUES INP = $I12*$\n VECTOR VALUES OUTP = $I12,S1,I12*$\n BASE = 10\n\n R READ NUMBERS UNTIL 0 INPUT\nRDNUM READ FORMAT INP,NUMBER\n WHENEVER NUMBER.NE.0\nSUMMAT PERS = 0\n DSUM = 0\n\n R CALCULATE ROOT AND PERSISTENCE\nDIGIT DSUM = DSUM + NUMBER-NUMBER/BASE*BASE\n NUMBER = NUMBER/BASE\n PERS = PERS + 1\n WHENEVER NUMBER.NE.0, TRANSFER TO DIGIT\n NUMBER = DSUM\n WHENEVER NUMBER.GE.10, TRANSFER TO SUMMAT\n\n PRINT FORMAT OUTP,DSUM,PERS\n TRANSFER TO RDNUM\n END OF CONDITIONAL\n END OF PROGRAM\n", "language": "MAD" }, { "code": "seq[n_, b_] := FixedPointList[Total[IntegerDigits[#, b]] &, n];\nroot[n_Integer, base_: 10] := If[base == 10, #, BaseForm[#, base]] &[Last[seq[n, base]]]\npersistance[n_Integer, base_: 10] := Length[seq[n, base]] - 2;\n", "language": "Mathematica" }, { "code": "/* Function that returns a list of digits given a nonnegative integer */\ndecompose(num) := block([digits, remainder],\n digits: [],\n while num > 0 do\n (remainder: mod(num, 10),\n digits: cons(remainder, digits),\n num: floor(num/10)),\n digits\n)$\n\n/* Function that given a positive integer returns the sum of their digits */\nauxdig(n):=block(decompose(n),apply(\"+\",%%));\n\n/* Function that given a positive integer returns a list of two: the additive persistence and the digital root */\ndigrt(n):=block([additive_persistence:0,digital_root:n],\n while length(decompose(digital_root))>1 do (digital_root:auxdig(digital_root),additive_persistence:additive_persistence+1),\n [additive_persistence,digital_root]);\n\n/* Examples */\ndigrt(627615);\ndigrt(39390);\ndigrt(588225);\ndigrt(393900588225);\n", "language": "Maxima" }, { "code": "testNumbers = [627615, 39390, 588225, 393900588225, 45, 9991]\npad = function(n, width)\n\treturn (n + \" \" * width)[:width]\nend function\n\ngetDigitalRoot = function(n)\n\tpersistance = 0\n\twhile floor(log(n)) > 0\n\t\tsum = 0\n\t\twhile n > 0\n\t\t\tsum += n % 10\n\t\t\tn = floor(n / 10)\n\t\tend while\n\t\tn = sum\n\t\tpersistance += 1\n\tend while\n\treturn [n, persistance]\nend function\n\nfor num in testNumbers\n\tdigRoot = getDigitalRoot(num)\n\tprint pad(num, 12), \"\"\n\tprint \" has a digital root \", \"\"\n\tprint digRoot[0], \"\"\n\tprint \" and additive persistance \",\"\"\n\tprint digRoot[1]\nend for\n", "language": "MiniScript" }, { "code": "MODULE DigitalRoot;\nFROM FormatString IMPORT FormatString;\nFROM Terminal IMPORT WriteString,WriteLn,ReadChar;\n\nTYPE Root =\n RECORD\n persistence,root : LONGINT;\n END;\n\nPROCEDURE digitalRoot(inRoot,base : LONGINT) : Root;\nVAR root,persistence,num : LONGINT;\nBEGIN\n root := ABS(inRoot);\n persistence := 0;\n WHILE root>=base DO\n num := root;\n root := 0;\n WHILE num#0 DO\n root := root + (num MOD base);\n num := num DIV base;\n END;\n INC(persistence)\n END;\n RETURN Root{persistence, root}\nEND digitalRoot;\n\nPROCEDURE Print(n,b : LONGINT);\nVAR\n buf : ARRAY[0..63] OF CHAR;\n r : Root;\nBEGIN\n r := digitalRoot(n,b);\n FormatString(\"%u (base %u): persistence=%u, digital root=%u\\n\", buf, n, b, r.persistence, r.root);\n WriteString(buf)\nEND Print;\n\nVAR\n buf : ARRAY[0..63] OF CHAR;\n b,n : LONGINT;\n r : Root;\nBEGIN\n Print(1,10);\n Print(14,10);\n Print(267,10);\n Print(8128,10);\n Print(39390,10);\n Print(627615,10);\n Print(588225,10);\n\n ReadChar\nEND DigitalRoot.\n", "language": "Modula-2" }, { "code": "MODULE DigitalRoot EXPORTS Main;\n\nIMPORT IO;\nFROM Fmt IMPORT F,LongInt;\n\nTYPE\n Root = RECORD persistence,R:LONGINT END;\n\nVAR\n R:Root;\n Arr:ARRAY[0..3] OF LONGINT := ARRAY OF LONGINT{627615L,\n\t\t\t\t\t\t 39390L,\n\t\t\t\t\t\t 588225L,\n\t\t\t\t\t\t 393900588225L};\n\nPROCEDURE DigitalRoot(InRoot,Base:LONGINT):Root =\nVAR\n r,persistence,Num:LONGINT;\nBEGIN\n r := ABS(InRoot);\n persistence := 0L;\n WHILE r >= Base DO\n\t Num := r;\n\t r := 0L;\n\t WHILE Num # 0L DO\n\t r := r + (Num MOD Base);\n\t Num := Num DIV Base;\n\t END;\n\t INC(persistence);\n END;\n RETURN Root{persistence, r};\nEND DigitalRoot;\n\nBEGIN\n FOR I := FIRST(Arr) TO LAST(Arr) DO\n R := DigitalRoot(Arr[I], 10L);\n IO.Put(F(LongInt(Arr[I]) &\n \" has additive persistence %s and digital root of %s\\n\",\n\t\tLongInt(R.persistence),\n\t\tLongInt(R.R)));\n END;\nEND DigitalRoot.\n", "language": "Modula-3" }, { "code": "def digital_root(n)\n\tap = 0\n\tn = +(int(n))\n\twhile n >= 10\n\t\tsum = 0\n\t\tfor digit in str(n)\n\t\t\tsum += int(digit)\n\t\tend\n\t\tn = sum\n\t\tap += 1\n\tend\n\treturn {ap, n}\nend\n\nprintln \"here\"\n\nif main\n\tvalues = {627615, 39390, 588825, 393900588225, 55}\n\tfor n in values\n\t\taproot = digital_root(n)\n\t\tprintln format(\"%12d has additive persistence %2d and digital root %d.\", n, aproot[0], aproot[1])\n\tend\nend\n", "language": "Nanoquery" }, { "code": "10 REM Digital root\n20 FOR I=0 TO 6\n30 READ A\n40 N=A:B=10:GOSUB 500\n50 PRINT SPC(7-LEN(STR$(A)));A;PERS;ROOT\n60 NEXT I\n70 DATA 1,14,267,8128,39390,588225,627615\n80 END\n490 REM ** Calculate digital root\n495 REM and persistance\n500 PERS=0\n510 IF N<B THEN 590\n520 S=0\n530 S=S+N-INT(N/B)*B\n540 N=INT(N/B)\n550 IF N>0 THEN 530\n560 PERS=PERS+1\n570 N=S\n580 GOTO 510\n590 ROOT=N\n600 RETURN\n", "language": "Nascom-BASIC" }, { "code": "/* NetRexx ************************************************************\n* Test digroot\n**********************************************************************/\nSay 'number -> digital_root persistence'\ntest_digroot(7 ,7, 0)\ntest_digroot(627615 ,9, 2)\ntest_digroot(39390 ,6, 2)\ntest_digroot(588225 ,3, 2)\ntest_digroot(393900588225,9, 2)\ntest_digroot(393900588225,9, 3) /* test error case */\n\nmethod test_digroot(n,dx,px) static\nres=digroot(n)\nParse res d p\nIf d=dx & p=px Then tag='ok'\n Else tag='expected:' dx px\nSay n '->' d p tag\n\nmethod digroot(n) static\n/**********************************************************************\n* Compute the digital root and persistence of the given decimal number\n* 19.08.2012 Walter Pachl derived from Rexx\n**************************** Bottom of Data **************************/\np=0 /* persistence */\nLoop While n.length()>1 /* more than one digit in n */\n s=0 /* initialize sum */\n p=p+1 /* increment persistence */\n Loop while n<>'' /* as long as there are digits */\n Parse n c +1 n /* pick the first one */\n s=s+c /* add to the new sum */\n End\n n=s /* the 'new' number */\n End\nreturn n p /* return root and persistence */\n", "language": "NetRexx" }, { "code": "import strutils\n\nproc droot(n: int64): auto =\n var x = @[n]\n while x[x.high] > 10:\n var s = 0'i64\n for dig in $x[x.high]:\n s += parseInt(\"\" & dig)\n x.add s\n return (x.len - 1, x[x.high])\n\nfor n in [627615'i64, 39390'i64, 588225'i64, 393900588225'i64]:\n let (a, d) = droot(n)\n echo align($n, 12),\" has additive persistence \",a,\" and digital root of \",d\n", "language": "Nim" }, { "code": "let rec digit_sum b n =\n if n < b then n else digit_sum b (n / b) + n mod b\n\nlet digital_root b n =\n let rec loop a x =\n if x < b then a, x else loop (succ a) (digit_sum b x)\n in\n loop 0 n\n\nlet () =\n let pr_fmt n (p, r) =\n Printf.printf \"%u: additive persistence = %u, digital root = %u\\n\" n p r\n in\n List.iter\n (fun n -> pr_fmt n (digital_root 10 n))\n [627615; 39390; 588225; 393900588225]\n", "language": "OCaml" }, { "code": ": sumDigits(n, base) 0 while(n) [ n base /mod ->n + ] ;\n\n: digitalRoot(n, base)\n 0 while(n 9 >) [ 1 + sumDigits(n, base) ->n ] n swap Pair new ;\n", "language": "Oforth" }, { "code": "(define (digital-root num)\n (if (less? num 10)\n num\n (let loop ((num num) (sum 0))\n (if (zero? num)\n (digital-root sum)\n (loop (div num 10) (+ sum (mod num 10)))))))\n\n(print (digital-root 627615))\n(print (digital-root 39390))\n(print (digital-root 588225))\n(print (digital-root 393900588225))\n", "language": "Ol" }, { "code": "dsum(n)=my(s); while(n, s+=n%10; n\\=10); s\nadditivePersistence(n)=my(s); while(n>9, s++; n=dsum(n)); s\ndigitalRoot(n)=if(n, (n-1)%9+1, 0)\n", "language": "PARI-GP" }, { "code": "program DigitalRoot;\n\n{$mode objfpc}{$H+}\n\nuses\n {$IFDEF UNIX}{$IFDEF UseCThreads}\n cthreads,\n {$ENDIF}{$ENDIF}\n SysUtils, StrUtils;\n\n// FPC has no Big mumbers implementation, Int64 will suffice.\n\nprocedure GetDigitalRoot(Value: Int64; Base: Byte; var DRoot, Pers: Integer);\nvar\n i: Integer;\n DigitSum: Int64;\nbegin\n Pers := 0;\n repeat\n Inc(Pers);\n DigitSum := 0;\n while Value > 0 do\n begin\n Inc(DigitSum, Value mod Base);\n Value := Value div Base;\n end;\n Value := DigitSum;\n until Value < Base;\n DRoot := Value;\nEnd;\n\nfunction IntToStrBase(Value: Int64; Base: Byte):String;\nconst\n // usable up to 36-Base\n DigitSymbols = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXY';\nbegin\n Result := '';\n while Value > 0 do\n begin\n Result := DigitSymbols[Value mod Base+1] + Result;\n Value := Value div Base;\n End;\n\nEnd;\n\nprocedure Display(const Value: Int64; Base: Byte = 10);\nvar\n DRoot, Pers: Integer;\n StrValue: string;\nbegin\n GetDigitalRoot(Value, Base, DRoot, Pers);\n WriteLn(Format('%s(%d) has additive persistence %d and digital root %d.',\n [IntToStrBase(Value, Base), Base, Pers, DRoot]));\nEnd;\n\nbegin\n WriteLn('--- Examples in 10-Base ---');\n Display(627615);\n Display(39390);\n Display(588225);\n Display(393900588225);\n\n WriteLn('--- Examples in 16-Base ---');\n Display(627615, 16);\n Display(39390, 16);\n Display(588225, 16);\n Display(393900588225, 16);\n\n ReadLn;\nEnd.\n", "language": "Pascal" }, { "code": "#!perl\nuse strict;\nuse warnings;\nuse List::Util qw(sum);\n\nmy @digit = (0..9, 'a'..'z');\nmy %digit = map { +$digit[$_], $_ } 0 .. $#digit;\n\nsub base {\n my ($n, $b) = @_;\n $b ||= 10;\n die if $b > @digit;\n my $result = '';\n while( $n ) {\n $result .= $digit[ $n % $b ];\n $n = int( $n / $b );\n }\n reverse($result) || '0';\n}\n\nsub digi_root {\n my ($n, $b) = @_;\n my $inbase = base($n, $b);\n my $additive_persistance = 0;\n while( length($inbase) > 1 ) {\n ++$additive_persistance;\n $n = sum @digit{split //, $inbase};\n $inbase = base($n, $b);\n }\n $additive_persistance, $n;\n}\n\nMAIN: {\n my @numbers = (5, 627615, 39390, 588225, 393900588225);\n my @bases = (2, 3, 8, 10, 16, 36);\n my $fmt = \"%25s(%2s): persistance = %s, root = %2s\\n\";\n\n if( eval { require Math::BigInt; 1 } ) {\n push @numbers, Math::BigInt->new(\"5814271898167303040368\".\n \"1039458302204471300738980834668522257090844071443085937\");\n }\n\n for my $base (@bases) {\n for my $num (@numbers) {\n my $inbase = base($num, $base);\n $inbase = 'BIG' if length($inbase) > 25;\n printf $fmt, $inbase, $base, digi_root($num, $base);\n }\n print \"\\n\";\n }\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">digital_root</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">persistence</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">work</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">n</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">root</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">work</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">root</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">work</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">work</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">work</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">base</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">work</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">root</span>\n <span style=\"color: #000000;\">persistence</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%15d root: %d persistence: %d\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">persistence</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">digital_root</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">627615</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">digital_root</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">39390</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">digital_root</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">588225</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">digital_root</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">393900588225</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\n// Digital root\n\nfunction rootAndPers($n, $bas)\n// Calculate digital root and persistance\n{\n $pers = 0;\n while ($n >= $bas) {\n $s = 0;\n do {\n $s += $n % $bas;\n $n = floor($n / $bas);\n } while ($n > 0);\n $pers++;\n $n = $s;\n }\n return array($n, $pers);\n}\n\nforeach ([1, 14, 267, 8128, 39390, 588225, 627615] as $a) {\n list($root, $pers) = rootAndPers($a, 10);\n echo str_pad($a, 7, ' ', STR_PAD_LEFT);\n echo str_pad($pers, 6, ' ', STR_PAD_LEFT);\n echo str_pad($root, 6, ' ', STR_PAD_LEFT), PHP_EOL;\n}\n?>\n", "language": "PHP" }, { "code": "go =>\n foreach(N in [627615,39390,588225,393900588225,\n 58142718981673030403681039458302204471300738980834668522257090844071443085937])\n [Sum,Persistence] = digital_root(N),\n printf(\"%w har addititive persistence %d and digital root of %d\\n\", N,Persistence,Sum)\n end,\n nl.\n\n%\n% (Reduced) digit sum (digital root) of a number\n%\ndigital_root(N) = [Sum,Persistence], integer(N) =>\n Sum = N,\n Persistence = 0,\n while(Sum > 9)\n Sum := sum([I.to_integer() : I in Sum.to_string()]),\n Persistence := Persistence + 1\n end.\n", "language": "Picat" }, { "code": "(for N (627615 39390 588225 393900588225)\n (for ((A . I) N T (sum format (chop I)))\n (T (> 10 I)\n (prinl N \" has additive persistance \" (dec A) \" and digital root of \" I \";\") ) ) )\n", "language": "PicoLisp" }, { "code": " digrt: Proc Options(main);\n /* REXX ***************************************************************\n * Test digroot\n **********************************************************************/\n\n Call digrtst('7');\n Call digrtst('627615');\n Call digrtst('39390');\n Call digrtst('588225');\n Call digrtst('393900588225');\n\n digrtst: Proc(n);\n Dcl n Char(100) Var;\n Dcl dr Pic'9';\n Dcl p Dec Fixed(5);\n Call digroot(n,dr,p);\n Put Edit(n,dr,p)(skip,a,col(20),f(1),f(3));\n End;\n\n digroot: Proc(n,dr,p);\n /**********************************************************************\n * Compute the digital root and persistence of the given decimal number\n * 27.07.2012 Walter Pachl (derived from REXX)\n **********************************************************************/\n Dcl n Char(100) Var;\n Dcl dr Pic'9';\n Dcl p Dec Fixed(5);\n Dcl s Pic'(14)Z9';\n Dcl v Char(100) Var;\n p=0;\n v=strip(n); /* copy the number */\n If length(v)=1 Then\n dr=v;\n Else Do;\n Do While(length(v)>1); /* more than one digit in v */\n s=0; /* initialize sum */\n p+=1; /* increment persistence */\n Do i=1 To length(v); /* loop over all digits */\n dig=substr(v,i,1); /* pick a digit */\n s=s+dig; /* add to the new sum */\n End;\n /*Put Skip Data(v,p,s);*/\n v=strip(s); /* the 'new' number */\n End;\n dr=Decimal(s,1,0);\n End;\n Return;\n End;\n\n strip: Proc(x) Returns(Char(100) Var);\n Dcl x Char(*);\n Dcl res Char(100) Var Init('');\n Do i=1 To length(x);\n If substr(x,i,1)>' ' Then\n res=res||substr(x,i,1);\n End;\n Return(res);\n End;\n End;\n", "language": "PL-I" }, { "code": "digital: procedure options (main); /* 29 April 2014 */\n declare 1 pict union,\n 2 x picture '9999999999999',\n 2 d(13) picture '9';\n declare ap fixed, n fixed (15);\n\n do n = 5, 627615, 39390, 588225, 393900588225, 99999999999;\n x = n;\n do ap = 1 by 1 until (x < 10);\n x = sum(d);\n end;\n put skip data (n, x, ap);\n end;\n\nend digital;\n", "language": "PL-I" }, { "code": "100H: /* SHOW THE DIGITAL ROOT AND PERSISTENCE OF SOME NUMBERS */\n\n /* BDOS SYSTEM CALL */\n BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;\n /* PRINTS A BYTE AS A CHARACTER */\n PRINT$CHAR: PROCEDURE( CH ); DECLARE CH BYTE; CALL BDOS( 2, CH ); END;\n /* PRINTS A BYTE AS A NUMBER */\n PRINT$BYTE: PROCEDURE( N );\n DECLARE N BYTE;\n DECLARE ( V, D2 ) BYTE;\n IF ( V := N / 10 ) <> 0 THEN DO;\n D2 = V MOD 10;\n IF ( V := V / 10 ) <> 0 THEN CALL PRINT$CHAR( '0' + V );\n CALL PRINT$CHAR( '0' + D2 );\n END;\n CALL PRINT$CHAR( '0' + N MOD 10 );\n END PRINT$BYTE;\n /* PRINTS A $ TERMINATED STRING */\n PRINT$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;\n\n /* PRINTS N1, N2, N3 AS A SINGLE NUMBER */\n /* N1, N2, N3 MUST ALL BE BETWEEN 0 AND 9999 INCLUSIVE */\n PRINT$NUMBER3: PROCEDURE( N1, N2, N3 );\n DECLARE ( N1, N2, N3 ) ADDRESS;\n DECLARE V ADDRESS, N$STR( 14 ) BYTE, ( W, I, J ) BYTE;\n W = LAST( N$STR );\n N$STR( W ) = '$';\n /* ADD THE DIGITS OF THE THREE NUMBERS TO N$STR */\n DO I = 0 TO 2;\n DO CASE I;\n V = N3;\n V = N2;\n V = N1;\n END;\n DO J = 1 TO 4;\n N$STR( W := W - 1 ) = '0' + ( V MOD 10 );\n V = V / 10;\n END;\n END;\n /* SPACE FILL THE REMAINDER OF THE NUMBER */\n I = W;\n DO WHILE( I > 0 );\n N$STR( I := I - 1 ) = ' ';\n END;\n /* SUPPRESS LEADING ZEROS */\n DO WHILE( W < LAST( N$STR ) - 1 AND N$STR( W ) = '0' );\n N$STR( W ) = ' ';\n W = W + 1;\n END;\n CALL PRINT$STRING( .N$STR );\n END PRINT$NUMBER3;\n\n /* CALCULATES THE DIGITAL ROOT AND PERSISTENCE OF AN INTEGER IN BASE 10 */\n /* IN ORDER TO ALLOW FOR NUMBERS LARGER THAN 2^15, THE NUMBER IS PASSED */\n /* AS THE UPPER, MIDDLE AND LOWER DIGITS IN N1, N2 AND N3 */\n /* E.G. 393900588225 CAN BE PROCESSED BY N1=3939, N2=0058, N3=8225 */\n FIND$DIGITAL$ROOT: PROCEDURE( N1, N2, N3, ROOT$PTR, PERSISTENCE$PTR );\n DECLARE ( N1, N2, N3, ROOT$PTR, PERSISTENCE$PTR ) ADDRESS;\n DECLARE DIGITAL$ROOT BASED ROOT$PTR BYTE;\n DECLARE PERSISTENCE BASED PERSISTENCE$PTR BYTE;\n\n SUM$DIGITS: PROCEDURE( N ) ADDRESS;\n DECLARE N ADDRESS;\n DECLARE DIGITS ADDRESS, SUM BYTE;\n DIGITS = N;\n SUM = 0;\n DO WHILE DIGITS > 0;\n SUM = SUM + ( DIGITS MOD 10 );\n DIGITS = DIGITS / 10;\n END;\n RETURN SUM;\n END SUM$DIGITS;\n\n DIGITAL$ROOT = SUM$DIGITS( N1 ) + SUM$DIGITS( N2 ) + SUM$DIGITS( N3 );\n PERSISTENCE = 1;\n DO WHILE( DIGITAL$ROOT > 9 );\n PERSISTENCE = PERSISTENCE + 1;\n DIGITAL$ROOT = SUM$DIGITS( DIGITAL$ROOT );\n END;\n END FIND$DIGITAL$ROOT ;\n\n /* CALCULATES AND PRINTS THE DIGITAL ROOT AND PERSISTENCE OF THE */\n /* NUMBER FORMED FROM THE CONCATENATION OF N1, N2 AND N3 */\n PRINT$DR$AND$PERSISTENCE: PROCEDURE( N1, N2, N3 );\n DECLARE ( N1, N2, N3 ) ADDRESS;\n DECLARE ( DIGITAL$ROOT, PERSISTENCE ) BYTE;\n CALL FIND$DIGITAL$ROOT( N1, N2, N3, .DIGITAL$ROOT, .PERSISTENCE );\n CALL PRINT$NUMBER3( N1, N2, N3 );\n CALL PRINT$STRING( .': DIGITAL ROOT: $' );\n CALL PRINT$BYTE( DIGITAL$ROOT );\n CALL PRINT$STRING( .', PERSISTENCE: $' );\n CALL PRINT$BYTE( PERSISTENCE );\n CALL PRINT$STRING( .( 0DH, 0AH, '$' ) );\n END PRINT$DR$AND$PERSISTENCE;\n\n /* TEST THE DIGITAL ROOT AND PERSISTENCE PROCEDURES */\n CALL PRINT$DR$ANDPERSISTENCE( 0, 62, 7615 );\n CALL PRINT$DR$ANDPERSISTENCE( 0, 3, 9390 );\n CALL PRINT$DR$ANDPERSISTENCE( 0, 58, 8225 );\n CALL PRINT$DR$ANDPERSISTENCE( 3939, 0058, 8225 );\n\nEOF\n", "language": "PL-M" }, { "code": "digital = (x) :\n dr = x string # Digital Root.\n ap = 0 # Additive Persistence.\n while (dr length > 1) :\n sum = 0\n dr length times (i): sum = sum + dr(i) number integer.\n dr = sum string\n ap++\n .\n (x, \" has additive persistence \", ap,\n \" and digital root \", dr, \";\\n\") join print\n.\n\ndigital(627615)\ndigital(39390)\ndigital(588225)\ndigital(393900588225)\n", "language": "Potion" }, { "code": "function Get-DigitalRoot ($n)\n{\n function Get-Digitalsum ($n)\n {\n if ($n -lt 10) {$n}\n else {\n ($n % 10) + (Get-DigitalSum ([math]::Floor($n / 10)))\n }\n }\n\n $ap = 0\n do {$n = Get-DigitalSum $n; $ap++}\n until ($n -lt 10)\n $DigitalRoot = [pscustomobject]@{\n 'Sum' = $n\n 'Additive Persistence' = $ap\n }\n $DigitalRoot\n}\n", "language": "PowerShell" }, { "code": "function Get-DigitalRoot {\n param($n)\n $ap = 0\n do {$n = Invoke-Expression (\"0\"+([string]$n -split \"\" -join \"+\")+\"0\"); $ap++} while ($n -ge 10)\n [PSCustomObject]@{\n DigitalRoot = $n\n AdditivePersistence = $ap\n }\n}\n", "language": "PowerShell" }, { "code": "digit_sum(N, Base, Sum):-\n digit_sum(N, Base, Sum, 0).\n\ndigit_sum(N, Base, Sum, S1):-\n N < Base,\n !,\n Sum is S1 + N.\ndigit_sum(N, Base, Sum, S1):-\n divmod(N, Base, M, Digit),\n S2 is S1 + Digit,\n digit_sum(M, Base, Sum, S2).\n\ndigital_root(N, Base, AP, DR):-\n digital_root(N, Base, AP, DR, 0).\n\ndigital_root(N, Base, AP, N, AP):-\n N < Base,\n !.\ndigital_root(N, Base, AP, DR, AP1):-\n digit_sum(N, Base, Sum),\n AP2 is AP1 + 1,\n digital_root(Sum, Base, AP, DR, AP2).\n\ntest_digital_root(N, Base):-\n digital_root(N, Base, AP, DR),\n writef('%w has additive persistence %w and digital root %w.\\n', [N, AP, DR]).\n\nmain:-\n test_digital_root(627615, 10),\n test_digital_root(39390, 10),\n test_digital_root(588225, 10),\n test_digital_root(393900588225, 10),\n test_digital_root(685943443231217865409, 10).\n", "language": "Prolog" }, { "code": "; if you just want the DigitalRoot\n; Procedure.q DigitalRoot(N.q) apparently will do\n; i must have missed something because it seems too simple\n; http://en.wikipedia.org/wiki/Digital_root#Congruence_formula\n\nProcedure.q DigitalRoot(N.q)\nProtected M.q=N%9\nif M=0:ProcedureReturn 9\nElse :ProcedureReturn M:EndIf\nEndProcedure\n\n; there appears to be a proof guarantying that Len(N$)<=1 for some X\n; http://en.wikipedia.org/wiki/Digital_root#Proof_that_a_constant_value_exists\n\nProcedure.s DigitalRootandPersistance(N.q)\nProtected r.s,t.s,X.q,M.q,persistance,N$=Str(N)\nM=DigitalRoot(N.q) ; just a test to see if we get the same DigitalRoot via the Congruence_formula\n\nRepeat\nX=0:Persistance+1\n\nFor i=1 to Len(N$) ; finding X as the sum of the digits of N\nX+Val(Mid(N$,i,1))\nNext\n\nN$=Str(X)\nIf Len(N$)<=1:Break:EndIf ; If Len(N$)<=1:Break:EndIf\nForever\n\nIf Not (X-M)=0:t.s=\" Error in my logic\":else:t.s=\" ok\":EndIf\n\nr.s=RSet(Str(N),15)+\" has additive persistance \"+Str(Persistance)\nr.s+\" and digital root of X(slow) =\"+Str(X)+\" M(fast) =\"+Str(M)+t.s\nProcedureReturn r.s\nEndProcedure\n\nNewList Nlist.q()\nAddElement(Nlist()) : Nlist()=627615\nAddElement(Nlist()) : Nlist()=39390\nAddElement(Nlist()) : Nlist()=588225\nAddElement(Nlist()) : Nlist()=393900588225\n\nFirstElement(Nlist())\n\nForEach Nlist()\nN.q=Nlist()\n; cw(DigitalRootandPersistance(N))\nDebug DigitalRootandPersistance(N)\nNext\n", "language": "PureBasic" }, { "code": "def digital_root (n):\n ap = 0\n n = abs(int(n))\n while n >= 10:\n n = sum(int(digit) for digit in str(n))\n ap += 1\n return ap, n\n\nif __name__ == '__main__':\n for n in [627615, 39390, 588225, 393900588225, 55]:\n persistance, root = digital_root(n)\n print(\"%12i has additive persistance %2i and digital root %i.\"\n % (n, persistance, root))\n", "language": "Python" }, { "code": "from functools import (reduce)\n\n\n# main :: IO ()\ndef main():\n print (\n tabulated(digitalRoot)(\n 'Integer -> (additive persistence, digital root):'\n )([627615, 39390, 588225, 393900588225, 55])\n )\n\n\n# digitalRoot :: Int -> (Int, Int)\ndef digitalRoot(n):\n '''Integer -> (additive persistence, digital root)'''\n\n # f :: (Int, Int) -> (Int, Int)\n def f(pn):\n p, n = pn\n return (\n 1 + p,\n reduce(lambda a, x: a + int(x), str(n), 0)\n )\n\n # p :: (Int , Int) -> Bool\n def p(pn):\n return 10 > pn[1]\n\n return until(p)(f)(\n (0, abs(int(n)))\n )\n\n\n# GENERIC -------------------------------------------------\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n return lambda f: lambda x: g(f(x))\n\n\n# tabulated :: (a -> b) -> String -> String\ndef tabulated(f):\n '''function -> heading -> input List -> tabulated output string'''\n def go(s, xs):\n fw = compose(len)(str)\n w = fw(max(xs, key=fw))\n return s + '\\n' + '\\n'.join(list(map(\n lambda x: str(x).rjust(w, ' ') + ' -> ' + str(f(x)), xs\n )))\n return lambda s: lambda xs: go(s, xs)\n\n\n# until :: (a -> Bool) -> (a -> a) -> a -> a\ndef until(p):\n def go(f, x):\n v = x\n while not p(v):\n v = f(v)\n return v\n return lambda f: lambda x: go(f, x)\n\n\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "[ abs 0 swap\n [ base share /mod\n rot + swap\n dup 0 = until ]\n drop ] is digitsum ( n --> n )\n\n[ 0 swap\n [ dup base share > while\n dip 1+\n digitsum again ] ] is digitalroot ( n --> n n )\n\n[ dup digitalroot\n rot echo\n say \" has additive persistance \"\n swap echo\n say \" and digital root of \"\n echo\n say \";\" cr ] is task ( n --> )\n\n627615 task\n39390 task\n588225 task\n393900588225 task\n", "language": "Quackery" }, { "code": "y=1\ndigital_root=function(n){\n x=sum(as.numeric(unlist(strsplit(as.character(n),\"\"))))\n if(x<10){\n k=x\n }else{\n y=y+1\n assign(\"y\",y,envir = globalenv())\n k=digital_root(x)\n }\n return(k)\n}\nprint(\"Given number has additive persistence\",y)\n", "language": "R" }, { "code": "#lang racket\n(define/contract (additive-persistence/digital-root n (ap 0))\n (->* (natural-number/c) (natural-number/c) (values natural-number/c natural-number/c))\n (define/contract (sum-digits x (acc 0))\n (->* (natural-number/c) (natural-number/c) natural-number/c)\n (if (= x 0)\n acc\n (let-values (((q r) (quotient/remainder x 10)))\n (sum-digits q (+ acc r)))))\n (if (< n 10)\n (values ap n)\n (additive-persistence/digital-root (sum-digits n) (+ ap 1))))\n\n(module+ test\n (require rackunit)\n\n (for ((n (in-list '(627615 39390 588225 393900588225)))\n (ap (in-list '(2 2 2 2)))\n (dr (in-list '(9 6 3 9))))\n (call-with-values\n (lambda () (additive-persistence/digital-root n))\n (lambda (a d)\n (check-equal? a ap)\n (check-equal? d dr)\n (printf \":~a has additive persistence ~a and digital root of ~a;~%\" n a d)))))\n", "language": "Racket" }, { "code": "sub digital-root ($r, :$base = 10) {\n my $root = $r.base($base);\n my $persistence = 0;\n while $root.chars > 1 {\n $root = $root.comb.map({:36($_)}).sum.base($base);\n $persistence++;\n }\n $root, $persistence;\n}\n\nmy @testnums =\n 627615,\n 39390,\n 588225,\n 393900588225,\n 58142718981673030403681039458302204471300738980834668522257090844071443085937;\n\nfor 10, 8, 16, 36 -> $b {\n for @testnums -> $n {\n printf \":$b\\<%s>\\ndigital root %s, persistence %s\\n\\n\",\n $n.base($b), digital-root $n, :base($b);\n }\n}\n", "language": "Raku" }, { "code": "sub digital-root ($r, :$base = 10) {\n my &sum = { .comb.map({:36($_)}).sum.base($base) }\n\n return .[*-1], .elems-1\n given $r.base($base), &sum … { .chars == 1 }\n}\n", "language": "Raku" }, { "code": "/* REXX ***************************************************************\n* Test digroot\n**********************************************************************/\n /* n r p */\nsay right(7 ,12) digroot(7 ) /* 7 7 0 */\nsay right(627615 ,12) digroot(627615 ) /* 627615 9 2 */\nsay right(39390 ,12) digroot(39390 ) /* 39390 6 2 */\nsay right(588225 ,12) digroot(588225 ) /* 588225 3 2 */\nsay right(393900588225,12) digroot(393900588225) /*393900588225 9 2 */\n Exit\ndigroot: Procedure\n/**********************************************************************\n* Compute the digital root and persistence of the given decimal number\n* 25.07.2012 Walter Pachl\n**************************** Bottom of Data **************************/\nParse Arg n /* the number */\np=0 /* persistence */\nDo While length(n)>1 /* more than one digit in n */\n s=0 /* initialize sum */\n p=p+1 /* increment persistence */\n Do while n<>'' /* as long as there are digits */\n Parse Var n c +1 n /* pick the first one */\n s=s+c /* add to the new sum */\n End\n n=s /* the 'new' number */\n End\nreturn n p /* return root and persistence */\n", "language": "REXX" }, { "code": "/*REXX program calculates and displays the digital root and additive persistence. */\nsay 'digital additive' /*display the 1st line of the header.*/\nsay \" root persistence\" center('number',77) /* \" \" 2nd \" \" \" \" */\nsay \"═══════ ═══════════\" left('', 77, \"═\") /* \" \" 3rd \" \" \" \" */\nsay digRoot( 627615)\nsay digRoot( 39390)\nsay digRoot( 588225)\nsay digRoot( 393900588225)\nsay digRoot(89999999999999999999999999999999999999999999999999999999999999999999999999999)\nsay \"═══════ ═══════════\" left('', 77, \"═\") /*display the foot separator. */\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ndigRoot: procedure; parse arg x 1 z; L= length(x) /*get a number & also another copy*/\n do pers=1 until L==1; $= left(x, 1) /*sum until digRoot ≡ one digit. */\n do j=2 for L-1; $= $+substr(x,j,1) /*add digits in the decimal number*/\n end /*j*/\n x= $; L= length(x) /*a new num, it may be multi─digit*/\n end /*pers*/\n return center(x, 7) center(pers, 11) z /*return a nicely formatted line. */\n", "language": "REXX" }, { "code": "/*REXX program calculates and displays the digital root and additive persistence. */\nsay 'digital additive' /*display the 1st line of the header.*/\nsay \" root persistence\" center('number',77) /* \" \" 2nd \" \" \" \" */\nsay \"═══════ ═══════════\" left('', 77, \"═\") /* \" \" 3rd \" \" \" \" */\nsay digRoot( 627615)\nsay digRoot( 39390)\nsay digRoot( 588225)\nsay digRoot( 393900588225)\nsay digRoot(89999999999999999999999999999999999999999999999999999999999999999999999999999)\nsay \"═══════ ═══════════\" left('', 77, \"═\") /*display the foot separator. */\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ndigRoot: procedure; parse arg x 1 ox; L=length(x) /*get a number and another copy. */\n do pers=1 until L==1; $= 0 /*keep summing 'til digRoot≡1 dig*/\n do j=1 for L; ?= substr(x, j, 1) /*add each digit in the dec. num.*/\n if datatype(?, 'W') then $= $ + ? /*add a dec. dig to digital root.*/\n end /*j*/\n x= $; L=length(x) /*a new #, it may be multi─digit.*/\n end /*pers*/\n return center(x,7) center(pers,11) ox /*return a nicely formatted line.*/\n", "language": "REXX" }, { "code": "c = 0\nsee \"Digital root of 627615 is \" + digitRoot(627615, 10) + \" persistance is \" + c + nl\nsee \"Digital root of 39390 is \" + digitRoot(39390, 10) + \" persistance is \" + c + nl\nsee \"Digital root of 588225 is \" + digitRoot(588225, 10) + \" persistance is \" + c + nl\nsee \"Digital root of 9992 is \" + digitRoot(9992, 10) + \" persistance is \" + c + nl\n\nfunc digitRoot n,b\n c = 0\n while n >= b\n c = c + 1\n n = digSum(n, b)\n end\n return n\n\nfunc digSum n, b\n s = 0\n while n != 0\n q = floor(n / b)\n s = s + n - q * b\n n = q\n end\n return s\n", "language": "Ring" }, { "code": "class String\n def digroot_persistence(base=10)\n num = self.to_i(base)\n persistence = 0\n until num < base do\n num = num.digits(base).sum\n persistence += 1\n end\n [num.to_s(base), persistence]\n end\nend\n\nputs \"--- Examples in 10-Base ---\"\n%w(627615 39390 588225 393900588225).each do |str|\n puts \"%12s has a digital root of %s and a persistence of %s.\" % [str, *str.digroot_persistence]\nend\nputs \"\\n--- Examples in other Base ---\"\nformat = \"%s base %s has a digital root of %s and a persistence of %s.\"\n[[\"101101110110110010011011111110011000001\", 2],\n [ \"5BB64DFCC1\", 16],\n [\"5\", 8],\n [\"50YE8N29\", 36]].each do |(str, base)|\n puts format % [str, base, *str.digroot_persistence(base)]\nend\n", "language": "Ruby" }, { "code": "print \"Digital root of 627615 is \"; digitRoot$(627615, 10)\nprint \"Digital root of 39390 is \"; digitRoot$(39390, 10)\nprint \"Digital root of 588225 is \"; digitRoot$(588225, 10)\nprint \"Digital root of 393900588225 is \"; digitRoot$(393900588225, 10)\nprint \"Digital root of 9992 is \"; digitRoot$(9992, 10)\nEND\n\nfunction digitRoot$(n,b)\nWHILE n >= b\n c = c + 1\n n = digSum(n, b)\nwend\ndigitRoot$ = n;\" persistance is \";c\nend function\n\nfunction digSum(n, b)\nWHILE n <> 0\n q = INT(n / b)\n s = s + n - q * b\n n = q\nwend\ndigSum = s\nend function\n", "language": "Run-BASIC" }, { "code": "fn sum_digits(mut n: u64, base: u64) -> u64 {\n let mut sum = 0u64;\n while n > 0 {\n sum = sum + (n % base);\n n = n / base;\n }\n sum\n}\n\n// Returns tuple of (additive-persistence, digital-root)\nfn digital_root(mut num: u64, base: u64) -> (u64, u64) {\n let mut pers = 0;\n while num >= base {\n pers = pers + 1;\n num = sum_digits(num, base);\n }\n (pers, num)\n}\n\nfn main() {\n\n // Test base 10\n let values = [627615u64, 39390u64, 588225u64, 393900588225u64];\n for &value in values.iter() {\n let (pers, root) = digital_root(value, 10);\n println!(\"{} has digital root {} and additive persistance {}\",\n value,\n root,\n pers);\n }\n\n println!(\"\");\n\n // Test base 16\n let values_base16 = [0x7e0, 0x14e344, 0xd60141, 0x12343210];\n for &value in values_base16.iter() {\n let (pers, root) = digital_root(value, 16);\n println!(\"0x{:x} has digital root 0x{:x} and additive persistance 0x{:x}\",\n value,\n root,\n pers);\n }\n}\n", "language": "Rust" }, { "code": "rem - return the digital sum of n represented as a string\nfunction digitalsum(nstr = string) = integer\n var i, slen, sum = integer\n var ch = char\n slen = len(nstr)\n sum = 0\n for i = 1 to slen\n ch = mid(nstr, i, 1)\n rem - don't process leading or embedded spaces, etc.\n if ch >= '0' and ch <= '9' then\n sum = sum + (ch - '0')\n next i\nend = sum\n\nvar nstr = string\nvar droot, pers = integer\n\n0again\n rem - input1 does not advance to next line; control-C will exit\n input1 \"What number\"; nstr\n droot = digitalsum(nstr)\n pers = 1\n while droot > 9 do\n begin\n droot = digitalsum(str$(droot))\n pers = pers + 1\n end\n print \" digital root =\"; droot; \" persistence =\"; pers\n goto 0again\n\nend\n", "language": "S-BASIC" }, { "code": "def digitalRoot(x:BigInt, base:Int=10):(Int,Int) = {\n def sumDigits(x:BigInt):Int=x.toString(base) map (_.asDigit) sum\n def loop(s:Int, c:Int):(Int,Int)=if (s < 10) (s, c) else loop(sumDigits(s), c+1)\n loop(sumDigits(x), 1)\n}\n\nSeq[BigInt](627615, 39390, 588225, BigInt(\"393900588225\")) foreach {x =>\n var (s, c)=digitalRoot(x)\n println(\"%d has additive persistance %d and digital root of %d\".format(x,c,s))\n}\nvar (s, c)=digitalRoot(0x7e0, 16)\nprintln(\"%x has additive persistance %d and digital root of %d\".format(0x7e0,c,s))\n", "language": "Scala" }, { "code": "; Convert an integer into a list of its digits.\n\n(define integer->list\n (lambda (integer)\n (let loop ((list '()) (int integer))\n (if (< int 10)\n (cons int list)\n (loop (cons (remainder int 10) list) (quotient int 10))))))\n\n; Return the sum of the digits of an integer.\n\n(define integer-sum-digits\n (lambda (integer)\n (fold-left + 0 (integer->list integer))))\n\n; Compute the digital root (additive) and additive persistence of an integer.\n; Return as a cons of (adr . ap).\n\n(define adr-ap\n (lambda (integer)\n (let loop ((int integer) (cnt 0))\n (if (< int 10)\n (cons int cnt)\n (loop (integer-sum-digits int) (1+ cnt))))))\n\n; Emit a table of integer, digital root (additive), and additive persistence\n; for the example integers given.\n\n(printf \"~13@a ~6@a ~6@a~%\" \"Integer\" \"Root\" \"Pers.\")\n(let rowloop ((intlist '(627615 39390 588225 393900588225 0 1 68010887038)))\n (when (pair? intlist)\n (let* ((int (car intlist))\n (aa (adr-ap int)))\n (printf \"~13@a ~6@a ~6@a~%\" int (car aa) (cdr aa))\n (rowloop (cdr intlist)))))\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n include \"bigint.s7i\";\n\nconst func bigInteger: digitalRoot (in var bigInteger: num, in bigInteger: base, inout bigInteger: persistence) is func\n result\n var bigInteger: sum is 0_;\n begin\n persistence := 0_;\n while num >= base do\n sum := 0_;\n while num > 0_ do\n sum +:= num rem base;\n num := num div base;\n end while;\n num := sum;\n incr(persistence);\n end while;\n end func;\n\nconst proc: main is func\n local\n var bigInteger: num is 0_;\n var bigInteger: root is 0_;\n var bigInteger: persistence is 0_;\n begin\n for num range [] (627615_, 39390_, 588225_, 393900588225_) do\n root := digitalRoot(num, 10_, persistence);\n writeln(num <& \" has additive persistence \" <& persistence <& \" and digital root of \" <& root);\n end for;\n end func;\n", "language": "Seed7" }, { "code": "func digroot (r, base = 10) {\n var root = r.base(base)\n var persistence = 0\n while (root.len > 1) {\n root = root.chars.map{|n| Number(n, 36) }.sum(0).base(base)\n ++persistence\n }\n return(persistence, root)\n}\n\nvar nums = [5, 627615, 39390, 588225, 393900588225]\nvar bases = [2, 3, 8, 10, 16, 36]\nvar fmt = \"%25s(%2s): persistance = %s, root = %2s\\n\"\n\nnums << (550777011503 *\n 105564897893993412813307040538786690718089963180462913406682192479)\n\nbases.each { |b|\n nums.each { |n|\n var x = n.base(b)\n x = 'BIG' if (x.len > 25)\n fmt.printf(x, b, digroot(n, b))\n }\n print \"\\n\"\n}\n", "language": "Sidef" }, { "code": "digitalRoot :=\n [:nr :arIn |\n r := (nr printString asArray collect:#digitValue) sum.\n r > 9 ifTrue:[\n digitalRoot value:r value:arIn+1.\n ] ifFalse:[\n { arIn+1 . r }\n ].\n ].\n\n#(\n 627615 39390 588225 393900588225 10 199\n 1999999999999999999999999999999999999999999999999999999999999999999999999999999999999\n) do:[:nr |\n Transcript showCR:'%1 has digitalRoot %3 and Additive Resistance %2'\n withArguments:{nr},(digitalRoot value:nr value:0)\n]\n", "language": "Smalltalk" }, { "code": "DEF DIGITAL_ROOT N OUT DR,AP\n AP=0\n DR=N\n WHILE DR>9\n INC AP\n STRDR$=STR$(DR)\n NEWDR=0\n FOR I=0 TO LEN(STRDR$)-1\n INC NEWDR,VAL(MID$(STRDR$,I,1))\n NEXT\n DR=NEWDR\n WEND\nEND\n", "language": "SmileBASIC" }, { "code": "package require Tcl 8.5\nproc digitalroot num {\n for {set p 0} {[string length $num] > 1} {incr p} {\n\tset num [::tcl::mathop::+ {*}[split $num \"\"]]\n }\n list $p $num\n}\n\nforeach n {627615 39390 588225 393900588225} {\n lassign [digitalroot $n] p r\n puts [format \"$n has additive persistence $p and digital root of $r\"]\n}\n", "language": "Tcl" }, { "code": ":ClrHome\n­:1→X\n:Input \">\",Str1\n:Str1→Str2\n:Repeat L≤1\n:Disp Str1\n:length(Str1→L\n:L→dim(L₁\n:seq(expr(sub(Str1,A,1)),A,1,L)→L₁\n:sum(L₁→N\n:{0,.5,1→L₂\n:NL₂→L₃\n:Med-Med L₂,L₃,Y₁\n:Equ►String(Y₁,Str1\n:sub(Str1,1,length(Str1)-3→Str1\n:X+1→X\n:End\n:Pause\n:ClrHome\n:Disp Str2,\"DIGITAL ROOT\",expr(Str1),\"ADDITIVE\",\"PERSISTENCE\",X\n:Pause\n", "language": "TI-83-BASIC" }, { "code": "SUB digitalroot (what)\n LET dr = ABS(what)\n IF dr > 10 THEN\n LET ap = 0\n DO\n LET ap = ap + 1\n DO WHILE dr <> 0\n LET t = t + REMAINDER(dr, 10)\n LET dr = IP(dr / 10)\n LOOP\n LET dr = t\n LET t = 0\n LOOP WHILE dr > 9\n END IF\n PRINT what, \"Additive persistance =\"; ap, \"Digital root =\"; dr\nEND SUB\n\nCALL digitalroot (627615)\nCALL digitalroot (39390)\nCALL digitalroot (588225)\nCALL digitalroot (393900588225)\nEND\n", "language": "True-BASIC" }, { "code": "// Digital root\n\nfunction rootAndPers(n: number, bas: number): [number, number] {\n var pers = 0;\n while (n >= bas)\n {\n var s = 0;\n do\n {\n s += n % bas;\n n = Math.floor(n / bas);\n } while (n > 0);\n pers++;\n n = s;\n }\n return [n, pers];\n}\n\nfor (var a of [1, 14, 267, 8128, 39390, 588225, 627615]) {\n var rp = rootAndPers(a, 10);\n console.log(a.toString().padStart(7, ' ') +\n rp[1].toString().padStart(6, ' ') + rp[0].toString().padStart(6, ' '));\n}\n", "language": "TypeScript" }, { "code": "#!/usr/bin/env bash\n\nnumbers=(627615 39390 588225 393900588225 55)\ndeclare root\n\nfor number in \"${numbers[@]}\"; do\n declare -i iterations\n root=\"${number}\"\n while [[ \"${#root}\" -ne 1 ]]; do\n root=\"$(( $(fold -w1 <<<\"${root}\" | xargs | sed 's/ /+/g') ))\"\n iterations+=1\n done\n echo -e \"${number} has additive persistence ${iterations} and digital root ${root}\"\n unset iterations\ndone | column -t\n", "language": "UNIX-Shell" }, { "code": "import strconv\n\nfn sum(ii u64, base int) int {\n\tmut s := 0\n\tmut i := ii\n\tb64 := u64(base)\n\tfor ; i > 0; i /= b64 {\n\t\ts += int(i % b64)\n\t}\n\treturn s\n}\n\nfn digital_root(n u64, base int) (int, int) {\n\tmut persistence := 0\n\tmut root := int(n)\n\tfor x := n; x >= u64(base); x = u64(root) {\n\t\troot = sum(x, base)\n\t\tpersistence++\n\t}\n\treturn persistence, root\n}\n\n// Normally the below would be moved to a *_test.go file and\n// use the testing package to be runnable as a regular test.\n\nstruct Test{\n\tn string\n\tbase int\n\tpersistence int\n\troot int\n}\n\nconst test_cases = [\n\tTest{\"627615\", 10, 2, 9},\n\tTest{\"39390\", 10, 2, 6},\n\tTest{\"588225\", 10, 2, 3},\n\tTest{\"393900588225\", 10, 2, 9},\n\tTest{\"1\", 10, 0, 1},\n\tTest{\"11\", 10, 1, 2},\n\tTest{\"e\", 16, 0, 0xe},\n\tTest{\"87\", 16, 1, 0xf},\n\t// From Applesoft BASIC example:\n\tTest{\"DigitalRoot\", 30, 2, 26}, // 26 is Q base 30\n\t// From C++ example:\n\tTest{\"448944221089\", 10, 3, 1},\n\tTest{\"7e0\", 16, 2, 0x6},\n\tTest{\"14e344\", 16, 2, 0xf},\n\tTest{\"d60141\", 16, 2, 0xa},\n\tTest{\"12343210\", 16, 2, 0x1},\n\t// From the D example:\n\tTest{\"1101122201121110011000000\", 3, 3, 1},\n]\n\nfn main() {\n\tfor tc in test_cases {\n\t\tn, err := strconv.common_parse_uint2(tc.n, tc.base, 64)\n\t\tif err != 0 {\n\t\t\tpanic('ERROR')\n\t\t}\n\t\tp, r := digital_root(n, tc.base)\n\t\tprintln(\"${tc.n:12} (base ${tc.base:2}) has additive persistence $p and digital root ${strconv.format_int(i64(r), tc.base)}\",)\n\t\tif p != tc.persistence || r != tc.root {\n\t\t\tpanic(\"bad result: $tc $p $r\")\n\t\t}\n\t}\n}\n", "language": "V-(Vlang)" }, { "code": "Option Base 1\nPrivate Sub digital_root(n As Variant)\n Dim s As String, t() As Integer\n s = CStr(n)\n ReDim t(Len(s))\n For i = 1 To Len(s)\n t(i) = Mid(s, i, 1)\n Next i\n Do\n dr = WorksheetFunction.Sum(t)\n s = CStr(dr)\n ReDim t(Len(s))\n For i = 1 To Len(s)\n t(i) = Mid(s, i, 1)\n Next i\n persistence = persistence + 1\n Loop Until Len(s) = 1\n Debug.Print n; \"has additive persistence\"; persistence; \"and digital root of \"; dr & \";\"\nEnd Sub\nPublic Sub main()\n digital_root 627615\n digital_root 39390\n digital_root 588225\n digital_root 393900588225#\nEnd Sub\n", "language": "VBA" }, { "code": "Function digital_root(n)\n\tap = 0\n\tDo Until Len(n) = 1\n\t\tx = 0\n\t\tFor i = 1 To Len(n)\n\t\t\tx = x + CInt(Mid(n,i,1))\n\t\tNext\n\t\tn = x\n\t\tap = ap + 1\n\tLoop\n\tdigital_root = \"Additive Persistence = \" & ap & vbCrLf &_\n\t\t\"Digital Root = \" & n & vbCrLf\t\nEnd Function\n\nWScript.StdOut.Write digital_root(WScript.Arguments(0))\n", "language": "VBScript" }, { "code": "Module Module1\n\n Function DigitalRoot(num As Long) As Tuple(Of Integer, Integer)\n Dim additivepersistence = 0\n While num > 9\n num = num.ToString().ToCharArray().Sum(Function(x) Integer.Parse(x))\n additivepersistence = additivepersistence + 1\n End While\n Return Tuple.Create(additivepersistence, CType(num, Integer))\n End Function\n\n Sub Main()\n Dim nums = {627615, 39390, 588225, 393900588225}\n For Each num In nums\n Dim t = DigitalRoot(num)\n Console.WriteLine(\"{0} has additive persistence {1} and digital root {2}\", num, t.Item1, t.Item2)\n Next\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "@let {\n sumDigits ^(@sum @arr)\n drootl &\\@rangef [. sumDigits ^(\\~>1 #@arr)]\n\n droot ^(@last drootl)\n apers ^(#-drootl)\n\n [\n !console.log \"[number]: [digital root] [additive persistence] [intermediate sums]\"\n ~@each [627615 39390 588225 393900588225]\n &n !console.log \"{n}: {!droot n} {!apers n} {@str !drootl n}\"\n ]\n}\n", "language": "Wortel" }, { "code": "import \"./fmt\" for Fmt\n\nvar sumDigits = Fn.new { |n|\n var sum = 0\n while (n > 0) {\n sum = sum + (n%10)\n n = (n/10).floor\n }\n return sum\n}\n\nvar digitalRoot = Fn.new { |n|\n if (n < 0) Fiber.abort(\"Argument must be non-negative.\")\n if (n < 10) return [n, 0]\n var dr = n\n var ap = 0\n while (dr > 9) {\n dr = sumDigits.call(dr)\n ap = ap + 1\n }\n return [dr, ap]\n}\n\nvar a = [1, 14, 267, 8128, 627615, 39390, 588225, 393900588225]\nfor (n in a) {\n var res = digitalRoot.call(n)\n var dr = res[0]\n var ap = res[1]\n Fmt.print(\"$,15d has additive persistence $d and digital root of $d\", n, ap, dr)\n}\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes; \\intrinsic 'code' declarations\n\nfunc DRoot(N, B, P); \\Return digital root and persistance P\nreal N, B; int P;\nint S;\n[P(0):= 0;\nwhile N >= B do\n [S:= 0;\n repeat S:= S + fix(Mod(N,B)); \\sum last digit\n N:= N/B; \\remove last digit\n N:= N - Mod(N,1.);\n until N < 0.1; \\(beware of rounding errors)\n P(0):= P(0)+1; \\increment persistance\n N:= float(S);\n ];\nreturn fix(N);\n];\n\nreal Tbl;\nint I, Root, Pers;\n[Tbl:= [627615., 39390., 588225., 393900588225.];\nfor I:= 0 to 4-1 do\n [Root:= DRoot(Tbl(I), 10., @Pers);\n IntOut(0, Pers); ChOut(0, ^ ); IntOut(0, Root); CrLf(0);\n ];\n]\n", "language": "XPL0" }, { "code": "dim a(2)\na(0) = 627615 : a(1) = 39390 : a(2) = 588225\nfor i = 0 to arraysize(a(),1)\n dr = digitalRoot(a(i))\n print a(i), \"\\tAdditive persistence = \", ap, \"\\tDigital root = \", dr\nnext i\nend\n\nsub digitalRoot(n)\n ap = 0\n repeat\n dr = 0\n while n > 0\n dr = dr + mod(n, 10)\n n = int(n / 10)\n wend\n ap = ap + 1\n n = dr\n until dr < 10\n return dr\nend sub\n", "language": "Yabasic" }, { "code": "fcn sum(n,b){ n.split(b).sum(0) }\nfcn droot(n,b=10,X=0) // -->(digital root, additive persistence)\n { if(n<b)return(n,X); return(self.fcn(sum(n,b),b,X+1)) }\n", "language": "Zkl" }, { "code": "droot(627615)\ndroot(39390)\ndroot(588225)\ndroot(393900588225)\ndroot(7,2)\ndroot(0x7e0,16)\n", "language": "Zkl" }, { "code": "module Main;\ntype\n\tlongint = integer{64};\n\ntype {public,ref}\n\tResponse = object (dr,p: longint)\n\tvar {public,immutable}\n\t\tdigitalRoot,persistence: longint;\n\n\tprocedure {public} Writeln;\n\tbegin\n\t\twriteln(\"digital root: \",digitalRoot:2,\" persistence: \",persistence:2)\n\tend Writeln;\n\n\tbegin\n\t\tself.digitalRoot := dr;\n\t\tself.persistence := p;\n\tend Response;\n\n\tprocedure DigitalRoot(n:longint):Response;\n\tvar\n\t\tsum,p: longint;\n\tbegin\n\t\tp := 0;\n\t\tloop\n\t\t\tinc(p);sum := 0;\n\t\t\twhile (n > 0) do\n\t\t\t\tinc(sum,n mod 10);\n\t\t\t\tn := n div 10;\n\t\t\tend;\n\t\t\tif sum < 10 then return new Response(sum,p) else n := sum end\n\t\tend\n\tend DigitalRoot;\n\nbegin\n\twrite(627615:22,\":> \");DigitalRoot(627615).Writeln;\n\twrite(39390:22,\":> \");DigitalRoot(39390).Writeln;\n\twrite(588225:22,\":> \");DigitalRoot(588225).Writeln;\n\twrite(max(integer{64}):22,\":> \");DigitalRoot(max(integer{64})).Writeln;\nend Main.\n", "language": "Zonnon" }, { "code": "10 DATA 4,627615,39390,588225,9992\n20 READ j: LET b=10\n30 FOR i=1 TO j\n40 READ n\n50 PRINT \"Digital root of \";n;\" is\"\n60 GO SUB 1000\n70 NEXT i\n80 STOP\n1000 REM Digital Root\n1010 LET c=0\n1020 IF n>=b THEN LET c=c+1: GO SUB 2000: GO TO 1020\n1030 PRINT n;\" persistance is \";c''\n1040 RETURN\n2000 REM Digit sum\n2010 LET s=0\n2020 IF n<>0 THEN LET q=INT (n/b): LET s=s+n-q*b: LET n=q: GO TO 2020\n2030 LET n=s\n2040 RETURN\n", "language": "ZX-Spectrum-Basic" } ]
Digital-root